diff --git a/CMakeLists.txt b/CMakeLists.txt index 60168c13..8b76ba4e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,8 +1,7 @@ cmake_minimum_required(VERSION 3.21) -# VERSION is what /version reports and what a client checks compatibility against. It is NOT the -# ABI version -- that lives in abi/rad_abi.h and is read out of the header below, because -# a plugin contract and a server release do not move together. -project(radiance VERSION 1.6.0 LANGUAGES C CXX) +# VERSION is the server release that /version reports. The plugin ABI version is separate and is +# read from abi/rad_abi.h below. +project(radiance VERSION 1.7.0 LANGUAGES C CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -13,35 +12,30 @@ if(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE RelWithDebInfo) endif() -# NOT option(): option() is boolean-only, so a default of AUTO collapses to OFF and the detection -# below never runs -- a machine with cards then silently builds the host backend. Tri-state wants a -# cache STRING. +# A cache STRING, not option(): option() is boolean, so AUTO would collapse to OFF and skip +# detection. set(RAD_WITH_HIP "AUTO" CACHE STRING "ON | OFF | AUTO -- build the HIP backend and device kernels") set_property(CACHE RAD_WITH_HIP PROPERTY STRINGS ON OFF AUTO) -set(RAD_WITH_FFMPEG "AUTO" CACHE STRING "ON | OFF | AUTO -- decode image, video and audio parts with libavformat/libavcodec/libswscale/libswresample") +set(RAD_WITH_FFMPEG "AUTO" CACHE STRING + "ON | OFF | AUTO -- decode image, video and audio parts with libavformat/libavcodec/libswscale/libswresample") set_property(CACHE RAD_WITH_FFMPEG PROPERTY STRINGS ON OFF AUTO) option(RAD_BUILD_TESTS "Build the test suite" ON) -option(RAD_ASAN "Build with AddressSanitizer" OFF) -# Whether the HIP compiler's VOPD pairing is repeatable. LLVM 24's is not unless it carries the -# fix the image builds (docker/llvm-vopd-pairing.patch); without this the build turns pairing off -# on LLVM 24, see rad_hip_repeatable in cmake/RadAddPlugin.cmake. +option(RAD_ASAN "Build host code with AddressSanitizer and UBSan" OFF) +option(RAD_TSAN "Build host code with ThreadSanitizer" OFF) +# LLVM 24's VOPD pairing is not repeatable unless patched (docker/llvm-vopd-pairing.patch); when +# OFF, pairing is disabled on LLVM 24. See rad_hip_repeatable in cmake/RadAddPlugin.cmake. option(RAD_HIP_VOPD_REPEATABLE "The HIP compiler's VOPD pairing is repeatable (the image's LLVM 24 is)" OFF) - # ---------------------------------------------------------------- HIP detection -# RAD_GPU_TARGETS is the set of offload architectures device kernels are compiled for. The project -# does not fix it and holds no opinion about which cards are acceptable: a kernel library is a -# plugin, so which hardware the engine can serve is decided by which kernel plugins are installed, -# not here (spec §2.1). Leaving it unset means "ask this machine", through the enumerator the ROCm -# toolchain ships. +# RAD_GPU_TARGETS lists the offload architectures device kernels are compiled for. Which cards the +# engine serves is decided by the installed kernel plugins, not here (spec §18). Unset means +# enumerate this machine's devices with the ROCm toolchain. # -# A kernel library that covers only some architectures narrows the list for itself with -# rad_plugin_gpu_targets() and skips its own build when the intersection is empty. That is how -# libr4d, which is RDNA4-only, coexists with a target list that may name anything, and it is the -# same mechanism a library for another card uses from out of tree. +# A kernel library covering only some architectures narrows the list with rad_plugin_gpu_targets() +# and skips itself when the intersection is empty (libr4d is RDNA4-only). # -# With no ROCm at all the host backend is built. That is a supported configuration and not a -# degraded one: everything except device kernels is exercised by it. +# Without ROCm the host backend is built, a supported configuration that exercises everything +# except device kernels. set(RAD_HIP_FOUND OFF) if(NOT RAD_WITH_HIP STREQUAL "OFF") find_program(RAD_HIPCC hipcc HINTS /opt/rocm/bin /opt/rocm/llvm/bin ENV ROCM_PATH) @@ -54,10 +48,8 @@ if(NOT RAD_WITH_HIP STREQUAL "OFF") endif() if(RAD_HIP_FOUND AND NOT DEFINED RAD_GPU_TARGETS) - # amdgpu-arch and offload-arch each print one architecture per visible device. EVERY device is - # listed, integrated graphics included, and that is the right input: a plugin filters the list - # down to what it serves, so an architecture no library covers costs a skipped plugin rather - # than a refused configure. + # amdgpu-arch / offload-arch print one architecture per visible device, integrated graphics + # included. Plugins filter the list to what they serve. find_program(RAD_ARCH_TOOL NAMES amdgpu-arch offload-arch HINTS /opt/rocm/bin /opt/rocm/llvm/bin ENV ROCM_PATH) if(RAD_ARCH_TOOL) @@ -71,12 +63,11 @@ if(RAD_HIP_FOUND AND NOT DEFINED RAD_GPU_TARGETS) endif() endif() if(NOT RAD_GPU_TARGETS) - # A toolchain with no card attached is an ordinary build machine. Guessing an architecture here - # would emit kernels for hardware nobody named, so the device build is declined and the way to - # ask for it anyway is spelled out. + # No card attached: do not guess an architecture. Decline the device build and say how to + # request one. set(RAD_HIP_FOUND OFF) message(WARNING - "radiance: hipcc was found but no AMD GPU could be enumerated, so this build has NO device " + "radiance: hipcc was found but no AMD GPU could be enumerated, so this build has no device " "kernels. To cross-compile them anyway, name the architectures: -DRAD_GPU_TARGETS=gfx1201 " "(semicolon-separated for several).") endif() @@ -88,88 +79,66 @@ elseif(RAD_WITH_HIP STREQUAL "OFF") message(STATUS "radiance: HIP backend OFF by request -- host backend only") elseif(NOT RAD_HIPCC) message(WARNING - "radiance: HIP backend OFF -- hipcc was not found, so this build has NO device kernels.\n" - " That is correct on a machine without ROCm and WRONG on one with cards. Looked in " - "/opt/rocm/bin, /opt/rocm/llvm/bin and \.") + "radiance: HIP backend OFF -- hipcc was not found, so this build has no device kernels.\n" + " Expected on a machine without ROCm, wrong on one with cards. Looked in /opt/rocm/bin, " + "/opt/rocm/llvm/bin and $ROCM_PATH.") endif() -# HOST CODE ONLY, AND THAT IS NOT A COMPROMISE -- IT IS THE WHOLE AVAILABLE SURFACE. +# ASan + UBSan for host code only. AMD's amdgcn ASan needs xnack+ for its page-fault-based shadow, +# and RDNA has no xnack, so the generator expressions keep the flags off HIP. Device kernels rely on +# rad-kbench's red zones instead: a poisoned margin around every operand and scratch allocation, +# checked after the launch, which catches out-of-bounds writes. # -# AMD ships an amdgcn AddressSanitizer (/opt/rocm/amdgcn/bitcode/asanrtl.bc) and it cannot run -# on an RDNA card: its shadow is page-fault based, which needs xnack+, and RDNA does not implement -# xnack -- rocminfo reports `XNACK enabled: NO`. Handing -fsanitize=address to the HIP -# compilation therefore buys a device binary that cannot work, so the generator expression keeps -# it off the HIP language entirely. What device kernels get instead is rad-kbench's red zones: a -# poisoned margin either side of every operand and every scratch allocation, verified after the -# launch. That catches the out-of-bounds WRITE, which is the one that corrupts a neighbour. -# -# What this DOES cover is everything else, which is most of the project: the core, the tools, -# libref in full, and every host-side launch wrapper in libr4d. UBSan comes with it because the -# two share a build and the interesting reports here -- a signed shift, a misaligned load, an -# enum out of range -- are UBSan's, not ASan's. +# TSan, likewise host code only, for the threaded host paths (scheduler, server, stager, tokenizer +# cache). libgomp is not instrumented, so tests run it with one thread (tests/CMakeLists.txt). +if(RAD_ASAN AND RAD_TSAN) + message(FATAL_ERROR "RAD_ASAN and RAD_TSAN cannot be combined; use a build directory for each.") +endif() if(RAD_ASAN) add_compile_options($<$:-fsanitize=address,undefined> $<$:-fno-omit-frame-pointer> $<$:-fno-sanitize-recover=all>) add_link_options(-fsanitize=address,undefined) endif() +if(RAD_TSAN) + add_compile_options($<$:-fsanitize=thread> + $<$:-fno-omit-frame-pointer>) + add_link_options(-fsanitize=thread) +endif() add_compile_options(-Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers) -# GNUInstallDirs before the ABI, not after it, because the ABI target's INSTALL_INTERFACE include -# path is spelled in CMAKE_INSTALL_INCLUDEDIR and an undefined variable there expands to nothing -- -# which is not an error, it is an exported target whose include directory is the install prefix -# itself, so every consumer's `#include "rad_abi.h"` misses by one directory level. +# Before the ABI: its INSTALL_INTERFACE path uses CMAKE_INSTALL_INCLUDEDIR, which would otherwise +# expand to nothing and silently export the wrong include directory. include(GNUInstallDirs) # ---------------------------------------------------------------- the ABI -# Header-only. The ONLY thing plugins compile against. +# Header-only, and the only thing plugins compile against. add_library(rad_abi INTERFACE) -# radiance::abi is the name plugins link, in-tree and out. It is an ALIAS here and an imported -# target in the installed package, and the two are spelled identically on purpose: rad_add_plugin -# has ONE body (cmake/RadAddPlugin.cmake) and it cannot branch on which world it is running in. +# Plugins link radiance::abi: an ALIAS here, an imported target when installed, so rad_add_plugin +# (cmake/RadAddPlugin.cmake) needs one body for both. add_library(radiance::abi ALIAS rad_abi) set_target_properties(rad_abi PROPERTIES EXPORT_NAME abi) -# CMAKE_INSTALL_FULL_DATADIR and not a literal "share": it is /share under every default, -# and it moves together with the destination the plugins are actually installed to. Those two -# disagreeing is a prefix that looks complete and whose loader finds nothing. +# CMAKE_INSTALL_FULL_DATADIR, not a literal "share", so it follows the plugin install destination. set(RAD_DEFAULT_HOME "${CMAKE_INSTALL_FULL_DATADIR}/radiance" CACHE STRING "default $RADIANCE_HOME") target_include_directories(rad_abi INTERFACE - # abi/ AND NOT THE REPO ROOT, which is the whole reason the headers sit in a directory of their - # own rather than being included as `abi/rad_abi.h` from the top. A plugin links this target and - # gets exactly the headers in abi/ on its include path -- not core/, not arch/, not the tree. An - # ABI a plugin can see past is not a boundary. - # - # BUILD_INTERFACE/INSTALL_INTERFACE rather than one bare path, because this target is exported: - # a bare ${CMAKE_CURRENT_SOURCE_DIR}/abi is a hard error out of install(EXPORT) ("path which is - # prefixed in the source directory"), and the export is the whole point -- an interface target - # that cannot leave the tree is the defect, not the fix. - # - # The spelling is the same in both worlds: `#include "rad_abi.h"` in-tree and installed, because - # rad_add_plugin has ONE body and cannot branch on which world it is running in. + # abi/, not the repo root, so a plugin sees only the ABI headers, never core/ or arch/. + # Generator expressions because the target is exported, and install(EXPORT) rejects a source + # path. Plugins write `#include "rad_abi.h"` both in-tree and installed. $ $) target_compile_definitions(rad_abi INTERFACE RAD_DEFAULT_HOME="${RAD_DEFAULT_HOME}") if(RAD_HIP_FOUND) target_compile_definitions(rad_abi INTERFACE RAD_HAVE_HIP=1) - # core/device/hip.cpp is compiled by the ORDINARY C++ compiler -- only plugins go through - # hipcc -- so it needs the HIP headers on the include path explicitly. hipcc supplies them to - # itself, which is why this is invisible until the first non-plugin translation unit includes - # hip_runtime.h. + # Host translation units such as core/device/hip.cpp use the ordinary C++ compiler and need the + # HIP headers explicitly. # - # SYSTEM, AND NOT AS A MATTER OF TASTE. hipcc has this same directory on its own path as a - # SYSTEM include, where a warning inside it is suppressed. Naming it again as an ordinary -I - # puts the user-include copy first and the headers stop being system headers -- for every - # plugin, because this is an INTERFACE property of rad_abi and every plugin links it. One ROCm - # header alone (amd_device_functions.h: `__fns`, `__fns64`, unused) then warns in every - # translation unit that includes it, which is a large share of the build output and none of it - # ours. A build whose warnings are mostly somebody else's is a build where nobody reads the - # warnings. + # SYSTEM: hipcc already has this directory as a system include. A plain -I would take precedence + # and make ROCm headers warn in every plugin (rad_abi is an INTERFACE dependency of all of them). # - # BUILD_INTERFACE only: the path is this machine's, and an exported target carrying it fails to - # configure wherever ROCm sits elsewhere. The installed package config finds the headers again on - # the consumer's machine (cmake/radiance-config.cmake.in). + # BUILD_INTERFACE only: the path is this machine's. The installed package config finds the + # headers on the consumer's machine (cmake/radiance-config.cmake.in). get_filename_component(RAD_ROCM_BIN "${RAD_HIPCC}" DIRECTORY) get_filename_component(RAD_ROCM_ROOT "${RAD_ROCM_BIN}" DIRECTORY) if(EXISTS "${RAD_ROCM_ROOT}/include/hip/hip_runtime.h") @@ -190,16 +159,12 @@ endif() set(RAD_PLUGIN_OUT ${CMAKE_BINARY_DIR}/radiance_home) file(MAKE_DIRECTORY ${RAD_PLUGIN_OUT}/kernels ${RAD_PLUGIN_OUT}/architectures) -# THE RECORDED KERNEL FIXTURE, COPIED INTO THE BUILD'S HOME. -# -# data/kernels.rkb is checked in and is what makes `rad-kbench` runnable with no model present: it -# holds the geometries, the seeds the inputs are drawn from and libref's answers reduced to a norm -# and a sample. Copied rather than pointed at, because $RADIANCE_HOME is what the tool looks in and -# an installed prefix has no source tree beside it. Recording a new one is +# Recorded kernel fixtures, copied into the build's $RADIANCE_HOME (where rad-kbench looks; an +# installed prefix has no source tree). data/kernels.rkb lets rad-kbench run with no model: it holds +# geometries, input seeds and libref's answers reduced to a norm and a sample. Re-record with a 27B +# container: # # rad-kbench -m --max-cases 1 --record data/kernels.rkb -# -# and that is the only step that needs a 27B container on the machine. if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels.rkb) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/data/kernels.rkb ${RAD_PLUGIN_OUT}/kernels.rkb COPYONLY) @@ -207,13 +172,9 @@ if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels.rkb) DESTINATION ${CMAKE_INSTALL_DATADIR}/radiance) endif() - -# THE SECOND FIXTURE, AND WHY THERE ARE TWO. A recording is of ONE container -- it holds that -# model's declared geometries -- and no single container in scope declares the whole vocabulary. -# The 27B is dense, has a DFlash2 drafter and gqa 6; the 35B-A3B is routed (moe_gemm_q, -# router_topk, moe_scatter, moe_gather, scale_rows), has an MTP head and gqa 8. Recording only one -# leaves five ops and a whole attention dispatch with no replay coverage at all, so a kernel that -# no locally available model exercises would regress unseen. Recording a new one is +# A recording covers one container's geometries, and no single model declares the whole vocabulary. +# The 27B is dense with a DFlash2 drafter and gqa 6; the 35B-A3B is routed (moe_gemm_q, +# router_topk, moe_scatter, moe_gather, scale_rows) with an MTP head and gqa 8. Re-record with # # rad-kbench -m --max-cases 1 --record data/kernels_moe.rkb # @@ -223,87 +184,41 @@ if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels_moe.rkb) install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels_moe.rkb DESTINATION ${CMAKE_INSTALL_DATADIR}/radiance) endif() -# THE DOWNLOADER `radiance --model ` RUNS (core/hf_model.cpp). The engine finds it at -# /../libexec/radiance/, so the build puts a copy at the same place under the build tree and -# a binary run from either tree finds it without a path to configure. +# The downloader behind `radiance --model ` (core/hf_model.cpp). The engine looks in +# /../libexec/radiance/, so the build tree mirrors that layout. configure_file(${CMAKE_CURRENT_SOURCE_DIR}/scripts/hfget.sh ${CMAKE_BINARY_DIR}/libexec/radiance/hfget.sh COPYONLY) install(PROGRAMS ${CMAKE_CURRENT_SOURCE_DIR}/scripts/hfget.sh DESTINATION ${CMAKE_INSTALL_LIBEXECDIR}/radiance) -# rad_add_plugin() and rad_hipify() live in cmake/RadAddPlugin.cmake because the installed package -# config includes that same file: a third party building a plugin from their own repository needs -# the function, and a second copy of it in the package config would drift from this one. The file -# documents the variables it expects; every one of them is set above. +# rad-export (a finetune to a .rad with the stock model's recipe) runs on the host, beside the +# trainer. It is installed with the tools so the image hands it out +# (`docker run --entrypoint busybox cat /opt/radiance/bin/rad-export`), though the image +# has no Python to run it. +install(PROGRAMS ${CMAKE_CURRENT_SOURCE_DIR}/tools/rad-export + DESTINATION ${CMAKE_INSTALL_BINDIR}) + +# rad_add_plugin() and rad_hipify(), shared with the installed package config. The variables it +# expects are all set above. include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/RadAddPlugin.cmake) if(RAD_HIP_FOUND) string(TOUPPER "${CMAKE_BUILD_TYPE}" RAD_CFG_UPPER) - # NOT `set(CMAKE_CXX_COMPILER hipcc)`. The C++ compiler is fixed by project() and assigning it - # afterwards is silently ignored -- device sources then reach the host C++ compiler with - # --offload-arch, an error that reads like a bad flag rather than a bad compiler. - # - # CMake has had a HIP language since 3.21. Device sources are marked LANGUAGE HIP and the rest of - # the tree stays on the ordinary C++ compiler, which is what we want: only kernels need hipcc. - # CMake refuses hipcc as CMAKE_HIP_COMPILER by design ("use Clang directly"), so this is ROCm's - # own clang++. That needs the address-space cast in libr4d/r4d_common.h: ROCm 7.2 / LLVM 22 - # tightened __builtin_amdgcn_global_load_tr_b128_v8i16 to require a global address space, and - # the builtin fails identically under hipcc and clang++ without it. + # The HIP language (CMake >= 3.21): device sources are LANGUAGE HIP and everything else stays on + # the C++ compiler. Do not set CMAKE_CXX_COMPILER to hipcc; after project() it is silently + # ignored. CMake refuses hipcc as CMAKE_HIP_COMPILER, so this is ROCm's clang++. ROCm 7.2 / + # LLVM 22 requires a global address space for __builtin_amdgcn_global_load_tr_b128_v8i16, hence + # the cast in libr4d/r4d_common.h. enable_language(HIP) + rad_hip_rule_fixes() - # AND CMAKE EMITS NO DEPENDENCY FLAGS FOR HIP, which is the same shape of omission as the two - # below and by far the most dangerous of the three, because it does not fail -- it silently - # builds the wrong thing. + # Device optimisation level for every config. Depending on its version, CMake leaves + # CMAKE_HIP_FLAGS_ empty (device code at -O0 with asserts) or, from CMake 4.4, pre-fills + # the host-style '-O2 -g -DNDEBUG'. At -O0 decode reads weights at ~7 GB/s on a ~640 GB/s card. + # -O3 for kernels; no -g on the device, where it slows compiles and inhibits scheduling. # - # `CMAKE_DEPFILE_FLAGS_` is set by the compiler modules for C and CXX and is EMPTY for HIP. - # Ninja's HIP rule still declares `depfile = $DEP_FILE` and `deps = gcc`, so it WAITS for a - # depfile the command was never told to write, and records nothing: - # - # $ ninja -t deps libr4d/CMakeFiles/libr4d.dir/r4d_model_bf16.hip.o - # ...hip.o: #deps 0, deps mtime ... (VALID) - # - # Zero. No header is a dependency of any .hip object, so editing a header libr4d includes -- - # r4d_emit.h, r4d_common.h, r4d_fp8_wmma.h, or the ABI itself -- recompiles nothing and RELINKS - # the plugin around stale objects. The library then exports one signature and the engine calls - # another -- a hook called with more arguments than it takes, which segfaults inside the plugin - # with a stack that blames the kernel -- and every test after the edit runs objects that predate - # it. - # - # It is a one-line omission with no upper bound on what it can hide, so it is fixed here rather - # than worked around with `touch`. - if(NOT CMAKE_DEPFILE_FLAGS_HIP) - set(CMAKE_DEPFILE_FLAGS_HIP "-MD -MT -MF ") - endif() - - # AND CMAKE DOES NOT SUPPLY A SYSTEM-INCLUDE FLAG FOR HIP EITHER, which is the same shape of - # omission as the optimisation level below and just as quiet. `CMAKE_INCLUDE_SYSTEM_FLAG_` - # is set by the compiler modules for C and CXX and is EMPTY for HIP, and CMake's fallback when it - # is empty is a plain `-I` -- so every SYSTEM include directory reaches a .hip translation unit as - # an ordinary user include and every warning inside it becomes ours. Without this, ONE - # target_include_directories(... SYSTEM ...) call reaches a CXX source as - # `-isystem /opt/rocm/include` and a .hip source as `-I/opt/rocm/include` -- so this is not - # something an author can get right at the call site. It is set once, here, for every HIP target - # in the tree, vendor/ included. - set(CMAKE_INCLUDE_SYSTEM_FLAG_HIP "-isystem ") - - # OPTIMISATION LEVEL, SET HERE FOR EVERY CONFIG BECAUSE CMAKE DOES NOT SUPPLY A USABLE ONE FOR - # HIP. Depending on the CMake version `CMAKE_HIP_FLAGS_` is either EMPTY -- every device - # kernel compiles at -O0 with asserts live while the host half gets -O2 -g -DNDEBUG -- or, from - # CMake 4.4's HIP toolchain on, pre-filled with the host-style '-O2 -g -DNDEBUG'. Nothing in the - # build says so either way: an absent flag reads as the default, a pre-filled one as a choice. - # - # It is the whole performance story. At -O0 decode reads weights at about 7 GB/s against a card - # that does ~640, and no kernel change can fix a build that does not optimise the kernel. -O3 and - # not -O2 because these are the kernels; -g is deliberately NOT carried onto the device side, - # where it costs compile time and inhibits scheduling for a symbol table no profiler here reads. - # - # THE ASSIGNMENT IS UNCONDITIONAL. A guard such as `if(NOT CMAKE_HIP_FLAGS_${cfg})` cannot tell a - # toolchain default from an operator's choice: on a CMake that pre-fills the variable it sees a - # value and leaves every device kernel at -O2 with debug info, and a build tree whose cache still - # holds -O3 from an older CMake hides that until its next fresh configure drops it, with no - # signal in the build output. An operator who genuinely wants other device flags says so BY NAME - # through RAD_HIP_FLAGS_. A deliberate override is a thing someone typed; a toolchain - # default that happens to be non-empty is not, and the two must not be spelled the same way. + # The assignment is unconditional (FORCE) because a guard cannot tell a toolchain default from an + # operator's choice. Override by name with RAD_HIP_FLAGS_. foreach(cfg DEBUG RELEASE RELWITHDEBINFO MINSIZEREL) if(cfg STREQUAL "DEBUG") set(lvl "-O0 -g") @@ -328,10 +243,9 @@ endif() find_package(Threads REQUIRED) # ---------------------------------------------------------------- media decoding -# An image, video or audio part of a request is decoded by libavformat/libavcodec and converted by -# libswscale or libswresample (core/mm/media.cpp). Without them the engine builds and serves text, and refuses a -# media part by name -- the same tri-state as HIP, because a machine that has the libraries should -# not silently build without them. +# Image, video and audio request parts are decoded by libavformat/libavcodec and converted by +# libswscale/libswresample (core/mm/media.cpp). Without them the engine serves text and refuses media +# parts. Tri-state like HIP, so a machine with the libraries does not silently build without them. set(RAD_FFMPEG_FOUND OFF) if(NOT RAD_WITH_FFMPEG STREQUAL "OFF") find_package(PkgConfig QUIET) @@ -350,11 +264,8 @@ endif() add_subdirectory(vendor) add_subdirectory(core) -# THE KERNEL PLUGINS, one directory each, at the root, with no `kernels/` grouping: a plugin's -# kernels, row table, layouts and launch adapter all live in its own directory, so it reads as a -# plugin built on abi/ rather than something the engine assembles. Each links rad_abi and nothing -# else, from one directory, exactly like a plugin written out of tree. That is the acceptance test, -# and this is the layout that states it. +# Kernel plugins, one root directory each. Each holds its kernels, row table and layouts and links +# only rad_abi, exactly like a plugin written out of tree. add_subdirectory(libref) # libquant: the built-in quantisers, the third plugin kind (spec §4.5). Host C++, built everywhere: # rad-convert drives it and the oracle decodes through it. @@ -362,13 +273,10 @@ add_subdirectory(libquant) if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/libr4d/CMakeLists.txt) add_subdirectory(libr4d) endif() -# libavx: the conventional op vocabulary in hand-written x86 SIMD, runtime-dispatched by CPU -# feature -- the production HOST kernels, built wherever libref is, on x86-64. An op the placement -# puts on the host needs a host kernel that is not the oracle (rad_gate_reference_kernels refuses -# to serve on libref), and a model whose table is too large for the card -- the n-gram -# embedding's gather -- puts one there every step. It is not behind an option for that reason: a -# build without it cannot serve such a model. It also builds standalone (`cmake -S libavx -B -# build-avx`) on a box with no ROCm. +# libavx: the production host kernels (x86 SIMD, dispatched by CPU feature), built on every x86-64. +# Not optional: host-placed ops need a kernel other than the oracle (rad_gate_reference_kernels +# refuses libref), and a table too large for the card, such as the n-gram embedding's gather, runs +# on the host every step. Also builds standalone without ROCm (`cmake -S libavx -B build-avx`). if(CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64)$") add_subdirectory(libavx) endif() @@ -380,55 +288,39 @@ if(RAD_BUILD_TESTS) endif() # ---------------------------------------------------------------- the installed package -# Everything below is ADDITIVE: it changes nothing about what gets built or where the build tree -# puts it. It is what makes `find_package(radiance)` work: the ABI headers -- the entire documented -# contract with a plugin -- and the package config are installed, so an out-of-tree plugin compiles -# against an installed prefix rather than a hand-copied abi/. Without it the plugin boundary is -# real inside the tree and imaginary outside it. +# Install-only rules for `find_package(radiance)`; they do not affect the build tree. # -# (a) the ABI headers. They are self-contained -- they include each other and C standard headers, -# and nothing else -- so the directory installs as a unit with no filtering beyond the -# extension. arch/common/ is installed by arch/CMakeLists.txt, which owns those files. -# -# Under include/radiance/ rather than loose in include/: a prefix of /usr shares that directory with -# every other package, and rad_*.h and arch/ are names someone else can have. The include spelling -# does not change -- the target's include path is the radiance/ directory itself. +# (a) The ABI headers, which include only each other and C standard headers. arch/common/ is +# installed by arch/CMakeLists.txt. Under include/radiance/ to avoid clashes in shared prefixes such +# as /usr; the include spelling is unchanged because the target's include path is radiance/ itself. install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/abi/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/radiance FILES_MATCHING PATTERN "*.h") -# (b) the ABI target itself, as radiance::abi. An INTERFACE library has no artifact to install, but -# it carries the include path, RAD_DEFAULT_HOME, RAD_HAVE_HIP and the ROCm include directory -- and -# those are exactly the flags a plugin has to be compiled with to be loadable by this engine, so -# exporting the target is what stops an out-of-tree author reconstructing them by reading our -# CMakeLists and getting one of them wrong. +# (b) The ABI target as radiance::abi. It carries the include path, RAD_DEFAULT_HOME and RAD_HAVE_HIP, +# the flags a plugin must be compiled with to load in this engine. install(TARGETS rad_abi EXPORT radianceTargets) install(EXPORT radianceTargets NAMESPACE radiance:: FILE radianceTargets.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/radiance) -# (c) the package config. The version IS the ABI version, read out of the header rather than written -# down a second time here: the loader refuses any plugin that does not report exactly -# RAD_ABI_VERSION (core/plugin/loader.cpp), so a package version that could drift from the header -# would let find_package(radiance 3) accept an installation whose plugins the consumer cannot load. -# SameMajorVersion, with the ABI as the major, is that same exact-match rule expressed to CMake. +# (c) The package config. Its version is the ABI version, read from the header: the loader requires +# an exact RAD_ABI_VERSION match (core/plugin/loader.cpp), which SameMajorVersion with the ABI as +# the major expresses to CMake. file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/abi/rad_abi.h" RAD_ABI_VERSION_LINE REGEX "^#define[ \t]+RAD_ABI_VERSION[ \t]") string(REGEX MATCH "[0-9]+" RAD_ABI_VERSION "${RAD_ABI_VERSION_LINE}") if(NOT RAD_ABI_VERSION) message(FATAL_ERROR - "could not read RAD_ABI_VERSION out of abi/rad_abi.h. That number is the whole " - "compatibility contract with a plugin; a build that cannot find it must not ship a package " - "config that claims one.") + "could not read RAD_ABI_VERSION out of abi/rad_abi.h; the package config cannot state the " + "plugin compatibility it is built for without it.") endif() include(CMakePackageConfigHelpers) -# PATH_VARS, so the config resolves these against wherever the package was actually found rather -# than against the prefix it was configured with. A staged install (DESTDIR) or a moved tree would -# otherwise hand a consumer absolute paths into a directory that no longer exists, and the symptom -# is a plugin that compiles and installs into nothing. +# PATH_VARS, so the config resolves these relative to where the package is found, which keeps +# staged (DESTDIR) and relocated installs working. set(RAD_HOME_RELDIR "${CMAKE_INSTALL_DATADIR}/radiance") set(RAD_INCLUDE_RELDIR "${CMAKE_INSTALL_INCLUDEDIR}/radiance") configure_package_config_file( @@ -444,14 +336,12 @@ write_basic_package_version_file( install(FILES ${CMAKE_CURRENT_BINARY_DIR}/radiance-config.cmake ${CMAKE_CURRENT_BINARY_DIR}/radiance-config-version.cmake - # The function itself, not a copy of it: the config includes this exact file, so the rule - # that decides what a plugin links and where it lands is one file for both worlds. + # The config includes this exact file, so there is one copy for both builds. ${CMAKE_CURRENT_SOURCE_DIR}/cmake/RadAddPlugin.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/radiance) -# (d) the license and the notices. Apache-2.0 asks that both travel with every copy, and the MIT -# License asks the same of each bundled component's text, so they install beside the binaries and -# anything built from the install (the Docker image) carries them. +# (d) License and notices. Apache-2.0 and the bundled components' licenses require them to travel +# with every copy, including images built from the install. install(FILES LICENSE NOTICE DESTINATION ${CMAKE_INSTALL_DOCDIR}) install(FILES vendor/llama/LICENSE DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME llama.cpp.LICENSE) diff --git a/CMakePresets.json b/CMakePresets.json new file mode 100644 index 00000000..ee5eb945 --- /dev/null +++ b/CMakePresets.json @@ -0,0 +1,81 @@ +{ + "version": 6, + "cmakeMinimumRequired": { "major": 3, "minor": 25, "patch": 0 }, + "configurePresets": [ + { + "name": "default", + "displayName": "RelWithDebInfo in build/, HIP when a card is found", + "generator": "Ninja", + "binaryDir": "${sourceDir}/build" + }, + { + "name": "asan", + "displayName": "AddressSanitizer + UBSan, host backend, in build-asan/", + "inherits": "default", + "binaryDir": "${sourceDir}/build-asan", + "cacheVariables": { "RAD_ASAN": "ON", "RAD_TSAN": "OFF", "RAD_WITH_HIP": "OFF" } + }, + { + "name": "tsan", + "displayName": "ThreadSanitizer, host backend, in build-tsan/", + "inherits": "default", + "binaryDir": "${sourceDir}/build-tsan", + "cacheVariables": { "RAD_TSAN": "ON", "RAD_ASAN": "OFF", "RAD_WITH_HIP": "OFF" } + } + ], + "buildPresets": [ + { "name": "default", "configurePreset": "default" }, + { "name": "asan", "configurePreset": "asan" }, + { "name": "tsan", "configurePreset": "tsan" } + ], + "testPresets": [ + { + "name": "base", + "hidden": true, + "configurePreset": "default", + "output": { "outputOnFailure": true }, + "execution": { "jobs": 8, "noTestsAction": "error" } + }, + { + "name": "fast", + "displayName": "The inner loop: no slow, gpu, oot or perf test", + "inherits": "base", + "filter": { "include": { "label": "^fast$" } } + }, + { + "name": "host", + "displayName": "Everything that runs without a card, except the out-of-tree rebuild", + "inherits": "base", + "filter": { "exclude": { "label": "^(gpu|oot)$" } } + }, + { + "name": "full", + "displayName": "Every test", + "inherits": "base" + }, + { + "name": "gpu", + "displayName": "The tests that need a card, one at a time", + "inherits": "base", + "filter": { "include": { "label": "^gpu$" } } + }, + { + "name": "perf", + "displayName": "The wall-clock checks, one at a time", + "inherits": "base", + "filter": { "include": { "label": "^perf$" } } + }, + { + "name": "asan", + "displayName": "The fast tier under AddressSanitizer + UBSan", + "inherits": "fast", + "configurePreset": "asan" + }, + { + "name": "tsan", + "displayName": "The fast tier under ThreadSanitizer", + "inherits": "fast", + "configurePreset": "tsan" + } + ] +} diff --git a/Dockerfile b/Dockerfile index 3bf52f67..5dc11a17 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,45 +1,42 @@ # syntax=docker/dockerfile:1 # -# radiance as a container image: the engine, its plugins and its tools compiled inside the ROCm -# toolchain image, the host test suite run against that build, and a runtime image built FROM -# SCRATCH that holds the install tree and exactly the shared libraries it loads -- no distribution, -# no package manager, no shell beyond a static busybox. +# radiance as a container image: the engine, plugins and tools built in the ROCm toolchain image, +# the host test suite run against that build, and a FROM scratch runtime image holding the install +# tree and exactly the shared libraries it loads (no distribution, no package manager, only a +# static busybox). # # docker/build.sh # the usual way (BuildKit / buildx) # docker buildx build -t radiance . # the same, by hand # docker buildx build --build-arg GPU_TARGETS="gfx1200;gfx1201" -t radiance . # # Stages: -# ffmpeg FFmpeg built with only the demuxers core/mm/media.cpp admits and the decoders their -# streams need (pictures, video, and audio with swresample), and the three encoders the -# images API writes (png, mjpeg, libwebp); the distribution's build brings ~200 -# packages of encoders, filters and display libraries the engine never calls -# llvm ROCm's libLLVM rebuilt from ROCm's own llvm-project at the commit the image's clang -# reports, with docker/llvm-vopd-pairing.patch -- the fix that makes LLVM 24's device -# code repeatable from build to build (cmake/RadAddPlugin.cmake, rad_hip_repeatable) -# build ROCm dev image + cmake/ninja/g++-14; configures, builds, installs to /stage, every -# device source compiled by ROCm's clang from a shadow of the ROCm tree whose libLLVM -# is the llvm stage's -# test docker/llvm-check.sh, then `ctest -LE gpu` on that build -- everything that does not -# need a card -# rootfs the install tree stripped, and every library its binaries and plugins load, resolved -# by ldd, copied into one directory and checked from inside a chroot -# runtime FROM scratch + rootfs. This is the image that ships +# ffmpeg FFmpeg with only the demuxers core/mm/media.cpp admits, the decoders their streams +# need (pictures, video, audio with swresample) and the three encoders the images API +# writes (png, mjpeg, libwebp); the distribution's build pulls ~200 unused packages +# llvm ROCm's libLLVM rebuilt from ROCm's llvm-project at the commit the image's clang +# reports, with docker/llvm-vopd-pairing.patch, which makes LLVM 24's device code +# repeatable across builds (cmake/RadAddPlugin.cmake, rad_hip_repeatable) +# build ROCm dev image + cmake/ninja/g++-14; configures, builds and installs to /stage, with +# device code compiled by ROCm's clang from a shadow ROCm tree using the llvm stage's +# libLLVM +# test docker/llvm-check.sh, then the host-only ctest suites +# rootfs the stripped install tree plus every library its binaries and plugins load (resolved +# by ldd), copied into one directory and checked from inside a chroot +# runtime FROM scratch + rootfs; the shipped image # -# Device code is NOT built with --offload-compress: the engine's AQL backend reads the fat binaries -# itself and refuses a compressed bundle. +# Device code is not built with --offload-compress: the AQL backend reads the fat binaries itself +# and refuses a compressed bundle. # -# GPU_TARGETS must be named. A bare-metal ./build.sh asks the machine which cards it has; a build -# container has no card to ask, and a build that guessed would emit kernels for hardware nobody -# chose. They are the targets the shipped KERNEL LIBRARIES are compiled for -- libr4d serves RDNA4 -# only and drops every architecture outside gfx12 on its own. The engine itself runs on every AMD -# GPU family whatever is named (its own kernels carry the generic family targets), so a kernel -# library for another card is added to the image by mounting it on the search path: +# GPU_TARGETS must be named: a build container has no card to detect, unlike a bare-metal +# ./build.sh. They are the targets of the shipped kernel libraries; libr4d serves RDNA4 only and +# drops every architecture outside gfx12. The engine's own kernels carry the generic family +# targets and run on every AMD GPU family, so a kernel library for another card is added by +# mounting it on the search path: # docker run ... -v /my/plugins:/plugins -e RADIANCE_HOME=/plugins:/opt/radiance/share/radiance # -# The ROCm userspace in the image must be one the host's amdgpu kernel driver supports. It is -# pinned to the version the serving host runs; move both together. From ROCm 10 on, the dev image -# is published only as the -full tag. +# The image's ROCm userspace must be supported by the host's amdgpu kernel driver; it is pinned to +# the serving host's version, so move both together. From ROCm 10 on, the dev image is published +# only as the -full tag. ARG ROCM_VERSION=10.1.0-full ARG UBUNTU_VERSION=24.04 @@ -57,12 +54,12 @@ RUN apt-get update \ libwebp-dev \ && rm -rf /var/lib/apt/lists/* WORKDIR /tmp -# The demuxers are media.cpp's kFormats whitelist, the only containers it opens. The decoders are -# what those containers carry: still images, H.264 and HEVC (MP4, MOV, HEIF), VP8 and VP9 (WebM, -# WebP), AV1 through dav1d (WebM, MP4, AVIF), MPEG-1/2/4, Theora and the FLV/H.263 family. JPEG XL -# is recognised and refused by name: its only decoder is libjxl's. The encoders are an image -# model's output formats (media.cpp encode_image): png, jpeg as mjpeg, webp through libwebp. No -# protocols: media.cpp reads from memory through its own I/O context. +# Demuxers: media.cpp's kFormats whitelist. Decoders: what those containers carry -- still +# images, H.264 and HEVC (MP4, MOV, HEIF), VP8 and VP9 (WebM, WebP), AV1 through dav1d (WebM, MP4, +# AVIF), MPEG-1/2/4, Theora and the FLV/H.263 family. JPEG XL is recognised and refused by name +# (its only decoder is libjxl's). Encoders: the image output formats of media.cpp encode_image +# (png, jpeg as mjpeg, webp through libwebp). No protocols: media.cpp reads from memory through its +# own I/O context. RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \ curl -fsSL "https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.xz" -o ffmpeg.tar.xz \ && echo "${FFMPEG_SHA256} ffmpeg.tar.xz" | sha256sum -c - \ @@ -87,15 +84,15 @@ RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \ # ------------------------------------------------------------------------------------------- llvm FROM rocm/dev-ubuntu-${UBUNTU_VERSION}:${ROCM_VERSION} AS llvm ARG JOBS= -# THE ONE LIBRARY OF THE HIP COMPILER THAT CHANGES. clang, lld and the offload tools all load -# lib/llvm/lib/libLLVM.so, so this stage rebuilds that file and nothing else: the source is ROCm's -# llvm-project at exactly the commit `clang --version` names (a different commit refuses, as does -# a patch that no longer applies), configured as ROCm's lib/cmake/llvm/LLVMConfig.cmake says it -# was -- Release without assertions, AMDGPU;SPIRV;X86, every component in the dylib, no RTTI or -# exceptions, zlib and zstd from rocm_sysdeps -- and compiled by ROCm's own clang and lld. With -# VOPD pairing off it produces ROCm's code byte for byte; docker/llvm-check.sh holds the build -# stage to that. A sparse, depth-one fetch: llvm/, the cmake/, libc/ and third-party/ directories -# its configure reads, and none of its tests or documentation. +# clang, lld and the offload tools all load lib/llvm/lib/libLLVM.so, so this stage rebuilds only +# that file: ROCm's llvm-project at exactly the commit `clang --version` names (the stage stops if +# clang names none or the patch does not apply), configured as ROCm's +# lib/cmake/llvm/LLVMConfig.cmake records -- Release without assertions, AMDGPU;SPIRV;X86, every +# component in the dylib, no RTTI or exceptions, zlib and zstd from rocm_sysdeps -- and compiled +# by ROCm's own clang and lld. With VOPD pairing off it produces +# ROCm's code byte for byte; docker/llvm-check.sh holds the build stage to that. The fetch is +# sparse and depth one: llvm/ plus the cmake/, libc/ and third-party/ directories configure reads, +# without tests or documentation. RUN apt-get update \ && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ git cmake ninja-build ca-certificates \ @@ -133,40 +130,38 @@ RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \ # ------------------------------------------------------------------------------------------ build FROM rocm/dev-ubuntu-${UBUNTU_VERSION}:${ROCM_VERSION} AS build ARG GPU_TARGETS=gfx1201 -# Parallel compile jobs. Empty means one per core; a device-kernel translation unit takes 2-3 GB -# of RAM under hipcc, so a host that is also serving wants a lower number. +# Parallel compile jobs; empty means one per core. A device-kernel translation unit takes 2-3 GB +# of RAM under hipcc, so lower it on a host that is also serving. ARG JOBS= -# g++-14 rather than the image's default 13: its libstdc++ is the one hipcc then compiles the -# device-side translation units against too, and it is the runtime image's libstdc++ as well. -# gawk because tools/ops_doc_check.sh uses gensub, which Ubuntu's default awk (mawk) lacks. -# libdav1d7 and libwebp7 are the runtime halves of the AV1 decoder and the WebP encoder the ffmpeg -# stage linked; busybox-static goes into the runtime image. +# g++-14 rather than the default 13: hipcc compiles device-side translation units against its +# libstdc++, which is also the runtime image's. gawk: tools/ops_doc_check.sh uses gensub, which +# mawk lacks. libdav1d7 and libwebp7 are the runtime libraries of the ffmpeg stage's AV1 decoder +# and WebP encoder; busybox-static goes into the runtime image. RUN apt-get update \ && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ cmake ninja-build pkg-config g++-14 gawk libdav1d7 libwebp7 busybox-static \ && rm -rf /var/lib/apt/lists/* COPY --from=ffmpeg /opt/ffmpeg /opt/ffmpeg -# ROCm's library directory is registered with the loader beside FFmpeg's because the ROCm 10 images -# register none, and the rootfs stage resolves every library the installed binaries load with ldd. +# Register ROCm's library directory beside FFmpeg's: the ROCm 10 images register none, and the +# rootfs stage resolves the installed binaries' libraries with ldd. RUN echo /opt/ffmpeg/lib > /etc/ld.so.conf.d/ffmpeg.conf \ && echo /opt/rocm/lib > /etc/ld.so.conf.d/rocm.conf && ldconfig ENV ROCM_PATH=/opt/rocm HIP_PATH=/opt/rocm CC=gcc-14 CXX=g++-14 \ PKG_CONFIG_PATH=/opt/ffmpeg/lib/pkgconfig -# THE HIP COMPILER: ROCm's clang, loading the llvm stage's libLLVM. ROCm's tools find their -# libraries through RPATHs relative to themselves -- $ORIGIN/../lib for libLLVM, which -# LD_LIBRARY_PATH cannot override, and $ORIGIN/../../rocm_sysdeps/lib and $ORIGIN/../../../lib, -# which leave lib/llvm -- so the compiler lives in a shadow of the whole ROCm tree at the same -# depth: /opt/rocm-repeatable, every entry a link back into /opt/rocm except lib/llvm/bin, which -# holds real copies of the executables, and lib/llvm/lib's libLLVM, which is the rebuilt one. -# Only compiling uses it. The build names /opt/rocm with --rocm-path, so the headers and device -# libraries are ROCm's and the runtime path clang records in a linked plugin is /opt/rocm/lib; -# without it clang takes the tree it sits in as ROCm, and a loader that follows that path from -# the HIP runtime to comgr reaches the rebuilt libLLVM, which lacks the libstdc++ symbols ROCm's -# GCC-built one re-exports for comgr. The rootfs stage refuses any library resolved through it. +# The HIP compiler: ROCm's clang loading the llvm stage's libLLVM. ROCm's tools find libraries +# through RPATHs relative to themselves ($ORIGIN/../lib for libLLVM, which LD_LIBRARY_PATH cannot +# override, plus $ORIGIN/../../rocm_sysdeps/lib and $ORIGIN/../../../lib), so the compiler runs +# from /opt/rocm-repeatable, a shadow of the whole ROCm tree at the same depth. Every entry links +# back into /opt/rocm except lib/llvm/bin (real copies of the executables) and the rebuilt +# libLLVM. Only compiling uses it. The build passes --rocm-path=/opt/rocm so headers and device +# libraries are ROCm's and linked plugins record /opt/rocm/lib. Without it clang treats its own +# tree as ROCm, and the HIP runtime would reach comgr through the rebuilt libLLVM, which lacks the +# libstdc++ symbols ROCm's GCC-built one re-exports for comgr. The rootfs stage refuses any +# library resolved through the shadow tree. COPY --from=llvm /out/ /tmp/llvm-out/ RUN set -e; R=/opt/rocm; D=/opt/rocm-repeatable; L=lib/llvm; \ so=$(basename $(readlink -f $R/$L/lib/libLLVM.so)); \ @@ -186,10 +181,9 @@ RUN set -e; R=/opt/rocm; D=/opt/rocm-repeatable; L=lib/llvm; \ WORKDIR /src COPY . . -# The install prefix is fixed at configure time because the default $RADIANCE_HOME is compiled in -# as /share/radiance; DESTDIR then stages the tree without moving that default. -# oom_score_adj 1000: on a host that is also serving, the compiler is what the OOM killer takes, -# not the server. +# The prefix is fixed at configure time because the default $RADIANCE_HOME is compiled in as +# /share/radiance; DESTDIR stages the tree without moving that default. +# oom_score_adj 1000: on a host that is also serving, the OOM killer takes the compiler first. RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \ cmake -S . -B /build -G Ninja \ -DCMAKE_INSTALL_PREFIX=/opt/radiance \ @@ -205,41 +199,41 @@ RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \ # ------------------------------------------------------------------------------------------- test FROM build AS test -# Host-only: a build container has no /dev/kfd. The `gpu`-labelled suites (mem_test, +ARG JOBS= +# Host-only: a build container has no /dev/kfd. The `gpu`-labelled tests (the *_card entries, # r4d_selftest, kbench) run against a card from this stage: # docker buildx build --target build -t radiance-build . && docker run --rm \ # --device /dev/kfd --device /dev/dri --security-opt seccomp=unconfined radiance-build \ # ctest --test-dir /build -L gpu --output-on-failure -# One test at a time: several suites assert that a cost scales linearly, a ratio of two timings -# that tests running beside them would distort. The build sandbox forbids io_uring, so avx_check -# reports its file-backed gather case as skipped here. The `oot` suite -- every shipped plugin -# rebuilt against the installed package, libr4d included -- is the development tree's to run -# (tests/oot_plugins.sh): it re-does this stage's whole compile. +# Tests run JOBS at a time (default one per two hardware threads, about one per core on an SMT +# machine: the per-binary CPU budgets in tests/CMakeLists.txt hold for tests that do not share a +# core); the `perf` entries, which assert wall-clock costs, run alone (RUN_SERIAL). The build sandbox forbids io_uring, so avx_check skips its +# file-backed gather case. The `oot` suite (every shipped plugin rebuilt against the installed +# package) repeats this stage's whole compile, so it runs from the development tree instead +# (tests/oot_plugins.sh). RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \ bash /src/docker/llvm-check.sh /build \ - && ctest --test-dir /build -LE 'gpu|oot' --output-on-failure \ + && ctest --test-dir /build -LE 'gpu|oot' -j"${JOBS:-$(( ($(nproc) + 1) / 2 ))}" --output-on-failure \ && touch /build/host-tests-passed # ----------------------------------------------------------------------------------------- rootfs FROM build AS rootfs -# hfget.sh, which fetches the Hugging Face repo a --model id names, runs curl and jq, and curl needs -# a CA bundle to reach the hub over TLS. Installed in this stage, not in `build`, so adding them does -# not recompile the engine. +# hfget.sh (fetches the Hugging Face repo a --model id names) needs curl, jq and a CA bundle. +# Installed here rather than in `build` so changing them does not recompile the engine. RUN apt-get update \ && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ curl jq ca-certificates \ && rm -rf /var/lib/apt/lists/* # The marker makes this stage, and so the shipped image, depend on the test stage. COPY --from=test /build/host-tests-passed /rootfs/opt/radiance/share/radiance/.host-tests-passed -# Every library the binaries and plugins load, plus comgr, which the HIP runtime opens at run time -# and cannot initialise a device without, goes into one directory the dynamic loader searches by -# default: no ld.so.cache, no LD_LIBRARY_PATH. ROCm's own libdrm_amdgpu carries the card name table -# compiled in, so no amdgpu.ids is copied. A static busybox provides the health check's wget and a -# shell for `docker exec`; curl, jq and the CA bundle are hfget.sh's, and the bundle is -# ca-certificates' Mozilla set, which is the directory named for it in the license list. -# docker/licenses.sh traces each of those files to its package and records its license and source -# in /usr/share/doc/THIRD-PARTY. Then every ELF file is resolved from inside the tree, so nothing -# can depend on a library the image lacks. +# Every library the binaries and plugins load, plus comgr (opened by the HIP runtime at run time +# and required to initialise a device), goes into one directory the loader searches by default: +# no ld.so.cache, no LD_LIBRARY_PATH. ROCm's libdrm_amdgpu has the card name table compiled in, so +# no amdgpu.ids is copied. A static busybox provides the health check's wget and a shell for +# `docker exec`; curl, jq and the CA bundle are for hfget.sh (the bundle is ca-certificates' +# Mozilla set, named by that directory in the license list). docker/licenses.sh records each +# file's package, license and source in /usr/share/doc/THIRD-PARTY. Finally every ELF file is +# resolved from inside the tree, so none depends on a library the image lacks. RUN set -e; R=/rootfs; L=$R/usr/lib/x86_64-linux-gnu; \ mkdir -p $L $R/lib64 $R/usr/bin $R/bin $R/etc/ssl/certs $R/data $R/tmp; \ chmod 1777 $R/tmp; \ @@ -283,8 +277,8 @@ LABEL org.opencontainers.image.title="radiance" \ COPY --from=rootfs /rootfs/ / -# A single allocation may take the whole card and the HIP heap may grow to all of VRAM; the -# runtime's defaults cap both below what the placement plan hands out. +# Let one allocation take the whole card and the HIP heap grow to all of VRAM; the runtime's +# defaults cap both below what the placement plan hands out. ENV PATH=/opt/radiance/bin:/usr/bin:/bin \ GPU_MAX_ALLOC_PERCENT=100 \ GPU_MAX_HEAP_SIZE=100 diff --git a/NOTICE b/NOTICE index a0429270..d67b0046 100644 --- a/NOTICE +++ b/NOTICE @@ -5,28 +5,32 @@ Written by Deadcode, with contributions from tcclaviger (the N-rank all-reduce k MXFP4 GEMM, the A-tiled MXFP4 prefill GEMM and the GDN kernels' overflow guards), slydlake (the MXFP4 decode and prefill GEMMs, the MXFP4 linear and the DFlash2 drafter's MXFP4 linears, stop strings after the reasoning block, and the draft refill on a prefix hit), goodman-b (four-rank -tensor parallelism for Qwen3.8-Flash-Next), keptn42 (the four-rank all-reduce served in place, the -fused four-rank writes, the n-gram table in RAM, the four-class expert split, the Grafana dashboard, -the routed GEMM's decode loads and run search, the gated residual's prefill read form and row -groups, the fused router launch, the adaptive draft window, the MoE prefill forms, the sorted -operand's decode kernel, and for Gemma 4 its assistant head as a drafter that reads the trunk's +tensor parallelism for Qwen3.8-Flash-Next, the four-rank collectives ending the link hold +themselves, their selftest cases and the TP4 lever map), keptn42 (the four-rank all-reduce served in +place, the fused four-rank writes, the n-gram table in RAM, the four-class expert split, the Grafana +dashboard, the routed GEMM's decode loads and run search, the gated residual's prefill read form and +row groups, the fused router launch, the adaptive draft window, the MoE prefill forms, the sorted +operand's decode kernel, two K blocks a pass for up to 80 routed rows, --prefill-span, the towers' +lookup tables counted once, and for Gemma 4 its assistant head as a drafter that reads the trunk's cache, bf16 checkpoints, the fused w4a8 decode step, the vision tower and window snapshots that let a prefix hit resume), mechkbfan (the token embedding in the pinned host pool), Code000 (the n-gram gather on the card and the MTP head's history-pass skip), baKon (three-rank tensor parallelism, serving any world size from the shipped container, the request log, an uneven world's per-rank KV and weights split, --rope-scaling, the model entry's context length, root and capabilities, /props, the three-rank two-shot all-reduce and tiered-int8 wire, the diagnosis of the three-rank lossy-wire -crash, cardclock.py, --busy-prefill-chunk, and curl, jq and a CA bundle in the image with hfget.sh -under its busybox), hazyumps (static YaRN for the Qwen rotary paths), malic (ParoQuant: its MXFP4, -int5 and int4 checkpoints imported and served, the Givens rotation as stages and as dense per-group -matrices on the matrix cores, and the 5- and 4-bit asymmetric GEMMs), Perire (Gemma 4 26B-A4B with -z-lab's DFlash drafter: its plugin, its kernels in libr4d -- the windowed paged attention, -pair_argmax, the fused sandwich joins and expert_scale -- and the host emulator that tests them, the -prefill split into two slices with their all-reduces beside the compute, and the vocabulary-sharded -draft head), redxherring (--model taking a Hugging Face repo id), sfjes (Gemma 4 31B dense: its -plugin, its two attention classes and their kernels, and prefix reuse that leaves a windowed group -alone) and zivius (LiquidAI's LFM2 and LFM2-VL and d1's /v1/systemone, after the design of their -Codeberg PR 50). +crash, cardclock.py, --busy-prefill-chunk, curl, jq and a CA bundle in the image with hfget.sh under +its busybox, rad-export, and carrying Smellyyyy's --prefill-interleave), hazyumps (static YaRN for +the Qwen rotary paths), malic (ParoQuant: its MXFP4, int5 and int4 checkpoints imported and served, +the Givens rotation as stages and as dense per-group matrices on the matrix cores, and the 5- and +4-bit asymmetric GEMMs), Perire (Gemma 4 26B-A4B with z-lab's DFlash drafter: its plugin, its +kernels in libr4d -- the windowed paged attention, pair_argmax, the fused sandwich joins and +expert_scale -- and the host emulator that tests them, the prefill split into two slices with their +all-reduces beside the compute, and the vocabulary-sharded draft head), redxherring (--model taking +a Hugging Face repo id), Smellyyyy (--prefill-interleave), gearwave00001 (/v1/messages as Claude +Code sends it), devmilan (the NVFP4 and FP8 compressed-tensors imports), sfjes (Gemma 4 31B dense: +its plugin, its two attention classes and their kernels, and prefix reuse that leaves a windowed +group alone) and zivius (LiquidAI's LFM2 and LFM2-VL and d1's /v1/systemone, after the design of +their Codeberg PR 50, and Qwen3-ASR with /v1/audio/transcriptions and /v1/realtime). This product includes software from the following projects, each under the MIT License. The license text is in the file named beside each. diff --git a/README.md b/README.md index f2b683e9..f9853aeb 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,19 @@ # radiance -An LLM and image-generation inference server for AMD GPUs, in C++ and HIP. Its HTTP API speaks OpenAI's -chat, completions, Responses and images APIs, Anthropic's Messages API and llama-server's native one, -so their clients and SDKs work unchanged. Model architectures, kernel libraries and quantisers are `.so` plugins; the ones in this tree are built -and loaded the same way a third party's are ([`docs/PLUGIN.md`](docs/PLUGIN.md)). +An LLM and image-generation inference server for AMD GPUs, in C++ and HIP. Its HTTP API speaks +OpenAI's chat, completions, Responses and images APIs, Anthropic's Messages API and llama-server's +native one, so their clients and SDKs work unchanged. Model architectures, kernel libraries and +quantisers are `.so` plugins; the ones in this tree are built and loaded the same way a third +party's are ([`docs/PLUGIN.md`](docs/PLUGIN.md)). -The bundled device kernels (`libr4d`) target **AMD RDNA4** (`gfx1200`, `gfx1201`). The serve flags -below are for **two 32 GB cards** (Radeon AI PRO R9700). The engine itself starts on any AMD GPU -family; another card needs a kernel library for it. A machine with no GPU builds the host backend, -which runs the full test suite but does not serve these models at any useful speed. +The bundled device kernels (`libr4d`) target AMD RDNA4 (`gfx1200`, `gfx1201`). The serve flags +below are for two 32 GB cards (Radeon AI PRO R9700). The engine starts on any AMD GPU family; +another card needs a kernel library for it. A machine with no GPU builds the host backend, whose +AVX-512/AVX2 kernels (`libavx`) serve every model here: the small ones (EmbeddingGemma 2, +Qwen3-ASR, the 0.8B-3B models) at interactive speed on a desktop CPU, the 27B and larger far more +slowly than a card. -If you wish to support the developement of the radiance engine you can do so [here](https://patreon.com/StillDeadCode?utm_medium=unknown&utm_source=join_link&utm_campaign=creatorshare_creator&utm_content=copyLink) +To support the development of radiance: [Patreon](https://patreon.com/StillDeadCode). ## Models @@ -29,6 +32,7 @@ If you wish to support the developement of the radiance engine you can do so [he | Qwen3.8-27B bf16 | `qwen3.8-27b-bf16.rad` (50 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-bf16.yaml` | | Qwen3.8-Flash-Next bf16, a disk-streamed reference | `qwen3.8-flash-next-bf16.rad` (335 GiB) | [convert](#convert-a-checkpoint) | `flashnext-bf16.yaml` | | EmbeddingGemma 2 bf16: text, image, video and audio embeddings, one card | `embeddinggemma2-bf16.rad` (1.4 GiB) | [convert](#convert-a-checkpoint) | `embeddinggemma2.yaml` | +| Qwen3-ASR 1.7B bf16: speech to text, `/v1/audio/transcriptions` and live over `/v1/realtime`, 30 languages, one card | the checkpoint as it ships (4.1 GiB) | [Qwen/Qwen3-ASR-1.7B-hf](https://huggingface.co/Qwen/Qwen3-ASR-1.7B-hf) | — | A container holds everything the server needs: the weights, the tokeniser, the chat template and any drafter. Each download link's repository has the recipe and the exact command that made the @@ -44,14 +48,14 @@ repository has the recipe and the calibration step. To convert Google's bf16 che `data/recipes/gemma4-31b-dense-bf16-w4a8.recipe` quantises without calibration (round-to-nearest with a scale search, bf16 lm_head); see [Convert a checkpoint](#convert-a-checkpoint). On two R9700s that container decodes at 103 tok/s on prose and 141 on code, against 112 and 150 for keptn42's, -and its drafts are accepted a little less often (0.46 against 0.50 of them on prose). +and accepts 0.46 of its drafts on prose against 0.50. The ParoQuant containers keep the trunk exactly as the ParoQuant releases ship it, with the learned Givens rotations it was trained in. Convert int4 from `z-lab/Qwen3.8-27B-PARO`, int5 from `Launch80/Qwen3.8-27B-PARO-int5` and MXFP4 from `MisterSnrub/Qwen3.8-27B-PARO-MXFP4-v2`, each with `data/recipes/q38-27b-paro-mxfp4-df2.recipe` and the DFlash2 drafter. A ParoQuant container made -before 1.5.0 is refused at startup. Convert it again and pass the old one as `--reuse` to copy every -tensor that did not change. +before 1.5.0 is refused at startup; convert it again with the old one as `--reuse`, which copies +every tensor that did not change. The Qwen-Image containers serve OpenAI's images API (`/v1/images/generations`, `/v1/images/edits`): pictures from a prompt, and edits of up to ten pictures with an optional mask, 2048x2048 by default. @@ -62,10 +66,10 @@ license, which is non-commercial. ## Run with Docker The host needs Docker and an `amdgpu` driver that supports ROCm 10.1; it does not need ROCm. The -card needs Resizable BAR on (Above 4G Decoding and Resizable BAR in the firmware setup). The -image is [`stilldeadcode/radiance`](https://hub.docker.com/r/stilldeadcode/radiance), with its -kernels built for `gfx1201`. Pull it, clone this repository for its compose files, then start a -model from one of them: +card needs Resizable BAR on (Above 4G Decoding and Resizable BAR in the firmware setup). The image +is [`stilldeadcode/radiance`](https://hub.docker.com/r/stilldeadcode/radiance), with its kernels +built for `gfx1201`. Pull it, clone this repository for its compose files, then start a model from +one of them: ```sh docker pull stilldeadcode/radiance @@ -77,8 +81,8 @@ docker compose -f minicpm5-2b.yaml logs -f docker compose -f minicpm5-2b.yaml down ``` -Every model uses both cards and the same port, so run one at a time. Running without compose, and -the reason for each `docker run` option, is in [`docs/DOCKER.md`](docs/DOCKER.md). +Every model listens on the same port and most use both cards, so run one at a time. Running without +compose, and the reason for each `docker run` option, is in [`docs/DOCKER.md`](docs/DOCKER.md). To build the image yourself, for example for other cards, run `docker/build.sh -t 'gfx1200;gfx1201'` in the clone (it needs `docker buildx` and tests the build as it goes). Then set @@ -92,71 +96,81 @@ build in it: ```sh git clone https://codeberg.org/StillDeadcode/radiance.git && cd radiance -./build.sh # configure, build for the cards present, run the tests +./build.sh # configure, build for the cards present, run the fast tests ./build.sh --no-hip # host backend only cmake -S . -B build -G Ninja -DRAD_GPU_TARGETS='gfx1201' # build for cards this machine lacks -cmake --install build --prefix /opt/radiance # optional; bin/, include/, share/radiance/ ``` +To install, name the prefix when the build directory is first configured +(`-DCMAKE_INSTALL_PREFIX=/opt/radiance`), build, then run `cmake --install build`. The default +plugin path, `/share/radiance`, is compiled in from that first configure, so +`cmake --install build --prefix DIR` alone gives a tree that looks for its plugins elsewhere. The +prefix gets `bin/`, `include/radiance/`, `lib/cmake/radiance/`, `libexec/radiance/`, +`share/radiance/` and `share/doc/radiance/`. + With ROCm 10.1 the build turns the compiler's VOPD pairing (dual-issue instruction pairs) off: its LLVM 24 pairs in an order that follows heap addresses, so two builds of the same source can differ. -The Docker image builds its compiler with the fix and keeps the pairing, which is 1-3% faster on -the fp8 prefill GEMMs; a compiler that has the same fix is declared with +The Docker image builds its compiler with the fix and keeps the pairing, which is 1.4-3.5% faster +on the fp8 prefill GEMMs; a compiler that has the same fix is declared with `-DRAD_HIP_VOPD_REPEATABLE=ON`. ROCm 7.2 is unaffected. ## Run without Docker ```sh -export RADIANCE_HOME=$PWD/build/radiance_home # the plugins; an installed prefix finds its own +export RADIANCE_HOME=$PWD/build/radiance_home # the plugins; an install finds its own build/bin/radiance --model /srv/models/rad/minicpm5-2b-fp8.rad --port 8000 build/bin/radiance --model StillDeadcode/minicpm5-2b-fp8 --port 8000 ``` `--model` also takes a Hugging Face repo id, as vLLM does. The server fetches the repo with `curl` -and `jq` into `~/.cache/radiance/hf` (`--download-dir` puts it elsewhere), serves the container it -holds, and checks it for changes at every start; a start that cannot reach the hub serves the copy -it has. The Docker image has neither tool, so with Docker download the file as shown above. +and `jq` (`scripts/hfget.sh`) into `~/.cache/radiance/hf` (`--download-dir` puts it elsewhere), +serves the container it holds, and checks it for changes at every start; a start that cannot reach +the hub serves the copy it has. The Docker image carries both tools; in a container, +`--download-dir` must name a writable mount, since the compose files mount `/models` read-only. -These are the flags each model is served with. They match its compose file, minus Flash-Next's -prefix-cache tiers: +These rows match the compose files, minus Flash-Next's `--prefix-cache-mib`; the three- and +four-rank rows have no compose file. The other models' flags are in their compose files. | model | flags | |---|---| | Qwen3.8-Flash-Next | `--tp 2 --tp-wire wht6 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 12288 --gpu-headroom-mib 96 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` | | Qwen3.8-Flash-Next, four ranks | `--tp 4 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 12288 --gpu-headroom-mib 96 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` | | Qwen3.8-Flash-Next, three ranks (the shipped container as it is, [`docs/TP3.md`](docs/TP3.md)) | `--tp 3 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 8192 --gpu-headroom-mib 96 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` | -| Qwen3.8-27B FP8, Qwen3.6-35B-A3B | `--tp 2 --max-num-seqs 32 --max-model-len 200000 --kv-cache-dtype fp8` | +| Qwen3.8-27B FP8 and MXFP4, Qwen3.6-35B-A3B | `--tp 2 --max-num-seqs 32 --max-model-len 200000 --kv-cache-dtype fp8` | | Qwen3.8-27B bf16 | `--tp 2 --max-num-seqs 8 --max-model-len 200000 --kv-cache-dtype fp8` | | MiniCPM5-2B FP8 and bf16 | `--tp 2 --max-num-seqs 32 --max-model-len 131072 --kv-cache-dtype fp8 --gpu-headroom-mib 160 --max-num-batched-tokens 512` | | Qwen3.8-Flash-Next bf16 | `--tp 2 --max-model-len 32768 --placement expert_tiered --weights-disk-tier --host-pool-mib 12288 --gpu-headroom-mib 768 --deterministic --max-num-seqs 32 --max-num-batched-tokens 32768 --num-speculative-tokens 0` | | Qwen-Image 2.1 and 2.1 Turbo | `--tp 2 --tp-wire wht6` | -Every model serves up to 32 sequences a step. Two rows keep 8, because on a hybrid model each -sequence holds its own recurrent state, and 32 of them take that memory from the attention cache -and, on Flash-Next, from the expert slab: Flash-Next and the 27B in bf16. See +Every model here runs at up to 32 sequences a step. The Flash-Next rows (except the bf16 reference) +and the 27B in bf16 keep 8: on a hybrid model each sequence holds its own recurrent state, and 32 of +them take that memory from the attention cache and, on Flash-Next, from the expert slab. See [`docs/GUIDE.md`](docs/GUIDE.md) §4.4. -At `--tp 4` the gated residual's write carries the exact all-reduce, with the MoE gather in front -of it, on decode and verify steps; a prefill chunk runs the unfused chain. That chain's exact -all-reduce is one-shot up to 1 MiB a message and two-shot above that, which sends half the bytes -on a prefill chunk; both produce the same bits. The row above runs exact. -`--tp-wire wht6` at three and four ranks selects a different lossy wire, tiered int8 over the -two-shot, above `--tp-wire-min-kb`. Eight ranks have no lossy wire, so `--tp 8 --tp-wire wht6` -stops at startup naming the all-reduce. Four ranks is a capacity configuration; its per-step rate -against `--tp 2` on the same cards has not been measured. The -tiering flags are the tp2 recipe carried over. Above two ranks each rank still owns a **slice of -every expert's width** — each parity's 128-column blocks are cut contiguously over the ranks and the -odd block alternates with the parity, so every rank's share is whole blocks and every block has -exactly one owner — and the resident expert bytes per rank are smaller, so the elastic window is a -different shape: read the boot log's `elastic` line and re-derive `--host-pool-mib` before -trusting it. **`--host-pool-mib` is pinned on every card**, so the row -above pins 4 × 12 GiB = 48 GiB of RAM that nothing else can use and the kernel cannot swap out. The -amdgpu driver caps what every process together pins at the machine's RAM less 1/64 and 1.5 GiB; the -pool is locked user memory, which `ttm.pages_limit` does not count. A 64 GiB machine serves -`flashnext-tp1.yaml` with 49 GiB pinned ([`docs/GUIDE.md`](docs/GUIDE.md) §7). +At `--tp 4`, decode and verify steps carry the exact all-reduce in the gated residual's write, with +the MoE gather in front of it; a prefill chunk runs the unfused chain. That chain's exact +all-reduce is one-shot up to 1 MiB a message and two-shot above, which sends half the bytes on a +prefill chunk; both produce the same bits. The four-rank row runs exact. At three and four ranks +`--tp-wire wht6` selects a different lossy wire, tiered int8 over the two-shot, above +`--tp-wire-min-kb`. Eight ranks have no lossy wire, so `--tp 8 --tp-wire wht6` stops at startup +naming the all-reduce. -Add `--api-key KEY` to require `Authorization: Bearer KEY` (or `X-Api-Key: KEY`). Add `--debug-graph` to print every op -and the kernel it resolved to, then exit without serving. Then: +Four ranks is a capacity configuration: its per-step rate against `--tp 2` on the same cards has +not been measured, and its tiering flags are the two-rank recipe carried over. As at two ranks, each +rank owns a slice of every expert's width: each parity's 128-column blocks are cut contiguously over +the ranks and the odd block alternates with the parity, so every rank's share is whole blocks and +every block has one owner. The resident expert bytes per rank are smaller, so the elastic window +has a different shape: read the boot log's `elastic` line and re-derive `--host-pool-mib` before +trusting it. + +`--host-pool-mib` is pinned on every card, so the four-rank row pins 4 × 12 GiB = 48 GiB of RAM +that nothing else can use and the kernel cannot swap out. The amdgpu driver caps what all processes +together pin at the machine's RAM less 1/64 and 1.5 GiB; the pool is locked user memory, which +`ttm.pages_limit` does not count. A 64 GiB machine serves `flashnext-tp1.yaml` with 49 GiB pinned +([`docs/GUIDE.md`](docs/GUIDE.md) §7). + +Add `--api-key KEY` to require `Authorization: Bearer KEY` (or `X-Api-Key: KEY`). `--debug-graph` +prints every op and the kernel it resolved to, then exits without serving. A chat request: ```sh curl -s localhost:8000/v1/chat/completions -H 'Content-Type: application/json' \ @@ -180,30 +194,38 @@ budgets, long context, speculative decoding and operating a server. `data/recipes/` names. Download checkpoints with `scripts/hfget.sh `. ```sh -build/bin/rad-convert ~/models/Qwen/Qwen3.8-27B -o qwen3.8-27b-bf16.rad \ +build/bin/rad-convert /srv/models/hf/Qwen/Qwen3.8-27B -o qwen3.8-27b-bf16.rad \ --recipe data/recipes/q38-27b-bf16.recipe -build/bin/rad-convert ~/models/Qwen/Qwen3.8-Flash-Next -o qwen3.8-flash-next-bf16.rad --max-ctx 4096 -build/bin/rad-convert ~/models/google/gemma-4-31B-it -o gemma4-31b-w4a8.rad \ +build/bin/rad-convert /srv/models/hf/Qwen/Qwen3.8-Flash-Next -o qwen3.8-flash-next-bf16.rad --max-ctx 4096 +build/bin/rad-convert /srv/models/hf/google/gemma-4-31B-it -o gemma4-31b-w4a8.rad \ --recipe data/recipes/gemma4-31b-dense-bf16-w4a8.recipe \ --set quantization_config.quant_method=compressed-tensors \ - --draft-model ~/models/google/gemma-4-31B-it-assistant -build/bin/rad-convert ~/models/z-lab/Qwen3.8-27B-PARO -o qwen3.8-27b-paro-int4.rad \ + --draft-model /srv/models/hf/google/gemma-4-31B-it-assistant +build/bin/rad-convert /srv/models/hf/z-lab/Qwen3.8-27B-PARO -o qwen3.8-27b-paro-int4.rad \ --recipe data/recipes/q38-27b-paro-mxfp4-df2.recipe \ - --draft-model ~/models/z-lab/Qwen3.8-27B-DFlash2 + --draft-model /srv/models/hf/z-lab/Qwen3.8-27B-DFlash2 ``` -With Docker, use `docker run --rm -v ~/models:/models --entrypoint rad-convert stilldeadcode/radiance ...`. In -the image the recipes are in `/opt/radiance/share/radiance/recipes/`. A checkpoint served at its own -precision needs no container: `radiance --model ~/models/Qwen/Qwen3.8-27B-FP8`. +With Docker, use `docker run --rm -v /srv/models:/models --entrypoint rad-convert stilldeadcode/radiance ...`. +In the image the recipes are in `/opt/radiance/share/radiance/recipes/`. A checkpoint served at its +own precision needs no container: `radiance --model /srv/models/hf/Qwen/Qwen3.8-27B-FP8`. A release +someone else quantised is read as it ships when the engine serves its form (block-scaled FP8, +Quark's MXFP4) and converted from its exact dequantisation when it does not: compressed-tensors' +NVFP4 to the MXFP4 kernels, AutoRound and GPTQ int4 to int8. [docs/GUIDE.md](docs/GUIDE.md) names +the recipes of record with their `rad-convert` commands. ## Test ```sh -ctest --test-dir build -LE 'gpu|oot' # everything that runs without a card (a few minutes) -ctest --test-dir build -L gpu # device suites; they need the cards to themselves -ctest --test-dir build -L oot # rebuilds every bundled plugin out of tree against an install +ctest --test-dir build -L fast -j8 # the inner loop, under 15 s; build.sh runs it +ctest --test-dir build -LE 'gpu|oot' -j8 # everything that runs without a card (about 5 minutes) +ctest --test-dir build -L gpu # the card tests; they need the cards to themselves +ctest --test-dir build -L oot # rebuilds every bundled plugin out of tree against an install ``` +`CMakePresets.json` names the same runs (`ctest --preset fast`, `host`, `gpu`, `full`, `asan`), and +[`docs/GUIDE.md`](docs/GUIDE.md) §1.3 describes the tiers and the test binaries' options. + ## Documentation | | | diff --git a/abi/rad_abi.h b/abi/rad_abi.h index 2870bb0d..c53d1290 100644 --- a/abi/rad_abi.h +++ b/abi/rad_abi.h @@ -1,7 +1,6 @@ -/* rad_abi.h -- the plugin ABI. This file and rad_types.h are the whole contract between the - * engine and an .so it loads. Everything is C: C++ across an .so boundary is a standing - * invitation to a mismatch that manifests as corruption three frames later, and this boundary is - * exactly where a user is expected to substitute their own build. See spec.md §2. +/* rad_abi.h -- the plugin ABI. This file and rad_types.h are the contract between the engine and + * an .so it loads. The interface is plain C: C++ across an .so boundary invites ABI mismatches, + * and this is the boundary where users substitute their own builds. See spec.md §2. */ #ifndef RAD_ABI_H #define RAD_ABI_H @@ -13,27 +12,26 @@ extern "C" { #endif -/* Bumped whenever anything a plugin compiles against changes shape -- this header, rad_types.h, +/* 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 or rad_sample.h. Every - * kind of plugin reports it. A plugin that does not report exactly this is refused at load, by - * name, with both versions printed. An OPTIONAL export added beside the existing ones - * (rad_plugin_reference, say) is not a change of shape: a plugin without it is read as answering - * the default. */ -#define RAD_ABI_VERSION 16u + * 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 17u /* ================================================================== plugin identity */ -/* RAD_PLUGIN_QUANT is a quantiser plugin: rad_quant.h is its whole contract. */ +/* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin: + * rad_quant.h is its whole contract. */ enum { RAD_PLUGIN_KERNEL = 1, RAD_PLUGIN_ARCH = 2, RAD_PLUGIN_QUANT = 3 }; typedef struct RadPluginInfo { - uint32_t kind; /* RAD_PLUGIN_KERNEL | RAD_PLUGIN_ARCH | RAD_PLUGIN_QUANT */ + uint32_t kind; /* one of RAD_PLUGIN_KERNEL, _ARCH, _QUANT */ const char* name; /* "libr4d", "libref", "qwen3_dense_bf16" */ const char* version; const char* description; - /* The devices this build of the plugin can run on, as the backend spells an architecture in - * RadDeviceProps::arch. "host" for a library of CPU kernels, which run anywhere; "" for a - * plugin that claims nothing. Several architectures may be listed, separated by spaces or - * commas, for a binary built to cover more than one. */ + /* The devices this build can run on, spelled as RadDeviceProps::arch. "host" for a library of + * CPU kernels, which run anywhere; "" for a plugin that claims nothing. A binary built for + * several architectures lists them separated by spaces or commas. */ const char* build_target; } RadPluginInfo; @@ -43,8 +41,8 @@ const RadPluginInfo* rad_plugin_info(void); /* ================================================================== execution domain */ /* A CPU kernel is an ordinary kernel with domain RAD_DOMAIN_HOST, resolved through the same - * hierarchy and the same constraints. Declare resolves both domains where both exist, so the - * core can change execution site at runtime without re-resolving -- spec §5.1. */ + * hierarchy and constraints. Declare resolves both domains where both exist, so the core can + * change execution site at runtime without re-resolving (spec §2.1). */ enum { RAD_DOMAIN_DEVICE = 0, RAD_DOMAIN_HOST = 1, RAD_N_DOMAINS = 2 }; /* ================================================================== kernel arguments */ @@ -60,9 +58,8 @@ typedef struct RadArgs { int world_size; } RadArgs; -/* Read a parameter by key. Definitions, not declarations: a plugin links the ABI headers and - * nothing of the engine's, so a function declared here and defined in the core would be - * unlinkable from the plugins that are its only callers. See the note in rad_types.h. */ +/* Read a parameter by key. Inline definitions, because a plugin links only the ABI headers and + * nothing of the engine's. See the note in rad_types.h. */ static inline int rad_args_geti(const RadArgs* a, const char* key, long long* out) { if (!a || !key) return 0; for (int i = 0; i < a->n_p; ++i) @@ -82,95 +79,44 @@ static inline const char* rad_args_gets(const RadArgs* a, const char* key) { } /* ================================================================== kernel hooks */ -/* init/fini exist because some kernels have per-instance state that must be established once and - * not per launch -- libr4d's all-reduce needs its peer signal buffers and IPC handles set up - * across ranks before the first call, and a kernel that JITs or loads a config table wants - * somewhere to do it that is not the hot path. +/* init/fini hold per-instance state that is set up once rather than per launch: libr4d's + * all-reduce exchanges peer signal buffers and IPC handles across ranks before the first call, + * and a kernel that JITs or loads a config table does it here, off the hot path. * - * init is called once per RESOLVED INSTANCE (one op, one band, one domain), after selection and - * before load, with the frozen geometry. It returns an opaque pointer handed back in - * RadArgs.instance, or null. A negative status aborts startup. */ + * init is called once per resolved instance (one op, one band, one domain), after selection and + * before load, with the frozen geometry. The pointer it returns (or null) is handed back in + * RadArgs.instance. A negative status aborts startup. */ typedef int (*RadInitFn) (const RadParam* p, int n_p, int rank, int world_size, void** out_instance); typedef void (*RadFiniFn) (void* instance); /* The launch. Must not allocate and must not synchronise. Returns RAD_OK or negative; a negative - * return aborts the step and fails the requests in it, naming the kernel and the geometry. A launch + * return aborts the step and fails its requests, naming the kernel and the geometry. A launch * handed `link_gate` may return RAD_LINK_ENDED instead of RAD_OK (rad_kernel_collective). */ typedef int (*RadLaunchFn) (const RadArgs* a, RadStream stream); -/* ================================================================== the described launch */ -/* A KERNEL THAT DESCRIBES ITS LAUNCH INSTEAD OF PERFORMING IT, so the runtime can turn one - * description into either a dispatch or a graph node update. - * - * WHY THIS EXISTS. The engine re-issues a fixed op sequence every step: the topology is identical - * from step to step and only a few of the dispatches carry an operand that moved. The cost of - * launching a graph is roughly flat in the number of nodes, while submitting the same dispatches - * one at a time is linear in it, so replaying such a sequence as a graph is cheaper. What a - * `launch` hook cannot support is the UPDATE: it performs the dispatch itself, marshalling its own - * arguments, so nothing above it knows which argument slot holds which operand -- and a node update - * needs exactly that slot. `describe` reports the dispatch instead of performing it. - * - * IT IS OPTIONAL. `launch` remains the required entry point and every kernel that only implements - * it keeps working unchanged -- it simply never becomes a graph node, and a sequence containing - * one is submitted the ordinary way. Implement `describe` for a kernel that is issued repeatedly - * with a stable shape; there is nothing to gain on one that runs once. - * - * THE TRAP, AND THE ONE WAY TO AVOID IT. `launch` and `describe` must dispatch the SAME kernel - * with the SAME arguments, and nothing can check that for you: a divergence is not a crash, it is - * a wrong number produced only on the graph path, only after a capture, and it will read as a - * numerics bug anywhere but here. Do NOT write the two bodies twice. Write the shape arithmetic - * once and let it emit into a sink that is either a stream or a descriptor -- libr4d does this - * with one macro, and an out-of-tree plugin should do the same. - * - * ALLOCATION-FREE, like `launch`. The runtime owns the RadLaunchDesc storage and keeps it alive - * for as long as the node exists, so the shim writes its argument VALUES into `blob` and points - * `params[i]` at them. Pointing `params[i]` at anything else is legal only if that storage - * outlives the graph -- a string literal or the instance state does, a local does not. */ - -/* Fill `out[0..cap)` with the dispatches this call WOULD perform and write how many to `n_out`. - * Most kernels emit one; a split-K kernel and its finisher emit two. Returns RAD_E_FULL without - * writing anything if `cap` is too small, so the runtime can retry with a bigger array; returns - * RAD_OK having written `*n_out` otherwise. Must not allocate, must not synchronise and must not - * touch the device -- it is called at capture time, off the step path, and again whenever the - * runtime needs to know whether an argument moved. - * - * IT DESCRIBES A KERNEL DISPATCH AND ONLY THAT. An op whose work is a memory copy -- libr4d's - * `cast` is a hipMemcpy2DAsync, not a launch -- has nothing to put in a RadLaunchDesc and should - * leave `describe` null. A graph can hold copy nodes, but expressing one would need a second - * descriptor shape, and the ops that want it are the ops a graph saves least on. - * - * IT TAKES THE STREAM, because some launches depend on which one they are going onto: libr4d's - * split-K GEMM takes its arrival counter from a per-stream pool, so a description made without - * the stream would name a different counter than the launch would have used -- a divergence of - * exactly the kind the paragraph above says nothing can check for you. The runtime passes the - * stream the dispatch will actually run on, which for a graph node is the stream the graph is - * launched on. */ -typedef int (*RadDescribeFn)(const RadArgs* a, RadStream s, RadLaunchDesc* out, - int cap, int* n_out); - /* Bytes of scratch one launch of this shape needs. Null means none. Called at declare with the * band's upper bound, so the arena is sized for the worst step. */ typedef int64_t (*RadScratchFn)(const RadArgs* a); /* ================================================================== weight layout * - * WHAT A KERNEL STORES FOR A WEIGHT, GIVEN WHAT THE WEIGHT IS. spec.md §4.1, §4.3. + * What a kernel stores for a weight, given the weight's encoding. spec.md §4.1, §4.3. * - * A container holds each weight's ENCODING -- its codes, scales and zero points as canonical planes - * (rad_encoding.h) -- and nothing shaped for a kernel. The kernel that reads a weight says here - * what it wants instead, and the loader turns one into the other when the model loads. Lossless, - * always: a relayout moves bits and derives nothing a reader of the planes could not derive -- a - * fragment order, a scale repeated into a row's tail, a reference exponent that is a row's - * maximum. Choosing numbers is a quantiser's job (rad_quant.h); a kernel that did it here would - * make the served numbers depend on which library loaded the container. So a kernel library may - * change every layout it has and no container is converted again. */ + * A container holds each weight's encoding (codes, scales and zero points as canonical planes, + * rad_encoding.h) and nothing shaped for a kernel. The kernel that reads a weight describes the + * form it wants here, and the loader converts when the model loads. The conversion is lossless: a + * relayout moves bits and derives only what a reader of the planes could derive (a fragment order, + * a scale repeated into a row's tail, a reference exponent that is a row's maximum). Choosing + * numbers is the quantiser's job (rad_quant.h); a kernel doing it here would make the served + * numbers depend on which library loaded the container. So a kernel library may change any layout + * without containers being converted again. */ typedef struct RadLayout { const char* tag; /* stable name of the arrangement, for messages and for checking * that every kernel reading one weight wants the same bytes */ uint32_t dtype; /* the stored dtype, possibly a plugin-private one */ uint32_t rank; - int64_t shape[RAD_MAX_RANK]; /* the STORED shape, which may differ from the logical one */ + int64_t shape[RAD_MAX_RANK]; /* the stored shape, which may differ from the logical one */ int64_t align; /* byte alignment the stored base must satisfy */ int64_t bytes; /* total, including any padding the layout implies */ } RadLayout; @@ -178,93 +124,103 @@ typedef struct RadLayout { /* Describe what this kernel stores for operand `operand` of the given geometry. * * `enc` is the weight's encoding and `sel[i]` the index into `enc->plane` of planes[i], the planes - * this operand takes, in the order the declaration named them (RadWeightDecl::planes). Each plane - * is THIS RANK'S SLICE, dense: rank 2, [rows, cols] in the plane's own elements, every row starting - * on a byte and rad_dtype_bytes(dtype, cols) long. Here the planes carry their geometry and a null - * `data`. + * this operand takes, in RadWeightDecl::planes order. Each plane is this rank's slice, dense: rank + * 2, [rows, cols] in the plane's own elements, every row starting on a byte and + * rad_dtype_bytes(dtype, cols) long. Here the planes carry their geometry and a null `data`. * * RAD_OK `out` describes the stored form, and `relayout` will produce it. - * RAD_E_UNSUPPORTED stored as it is: the one selected plane, its bytes unchanged -- what most - * weights are, and what a kernel with no hook at all gets. Only such a weight - * can be read where it lies in the container (the file and mapped tiers). - * RAD_E_DTYPE THE KERNEL DOES NOT READ THIS ENCODING -- an fp8 GEMM handed int4, a - * rotated weight to a kernel that does not rotate its activation. A - * declare-time error that names the weight, the encoding and the kernel. - * RAD_E_SHAPE the planes selected, or their extents, are not what the kernel reads. */ + * RAD_E_UNSUPPORTED stored as is: the one selected plane, bytes unchanged. This is most + * weights, and what a kernel with no hook gets. Only such a weight can be + * read where it lies in the container (the file and mapped tiers). + * RAD_E_DTYPE the kernel does not read this encoding (an fp8 GEMM handed int4, a rotated + * weight to a kernel that does not rotate its activation). A declare-time + * error naming the weight, the encoding and the kernel. + * RAD_E_SHAPE the selected planes, or their extents, are not what the kernel reads. */ typedef int (*RadLayoutFn)(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel, const RadTensor* planes, int n_planes, RadLayout* out); /* Write the stored form `layout` described into `dst`, `dst_bytes` long, from the planes, which - * now carry their bytes. Pure host code, run by the loader -- on a pool, behind the read of the - * container, so it has to keep pace with the disk. */ + * now carry their bytes. Pure host code, run by the loader on a pool behind the container read, + * so it has to keep pace with the disk. */ typedef int (*RadRelayoutFn)(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel, const RadTensor* planes, int n_planes, void* dst, int64_t dst_bytes); -/* ...AND BACK: recover the planes from a stored form. `planes` arrive with their geometry and a +/* The inverse: recover the planes from a stored form. `planes` arrive with their geometry and a * buffer each. * - * WHY THE INVERSE HAS TO EXIST, stated from the failure it prevents. A tool that checks a kernel - * against the oracle holds the STORED bytes -- what the kernel reads -- and libref reads canonical - * planes. Handed the stored bytes it computes a correct answer to a permuted question, and the - * comparison is then between two unrelated tensors: a relative error of the size two independent - * draws give, reported against a kernel that is in fact correct. Only the plugin knows its - * permutation, so only the plugin can undo it. A kernel that relayouts and supplies no inverse is - * not a fault -- it is simply not checkable against a dense oracle, and the tools say so BY NAME - * rather than guessing. */ + * A tool checking a kernel against the oracle holds the stored bytes, but libref reads canonical + * planes; given the stored bytes it answers a permuted question, and the comparison reports an + * error the size of two unrelated tensors against a correct kernel. Only the plugin knows its + * permutation. A kernel that relayouts without an inverse is not at fault, only not checkable + * against a dense oracle, and the tools report it by name. */ typedef int (*RadUnrelayoutFn)(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel, const void* src, int64_t src_bytes, const RadTensor* planes, int n_planes); /* ================================================================== operand description */ -/* HOW BIG IS OPERAND i OF THIS OP, AND WHAT MAY BE IN IT. +/* How big operand i of an op is, and what values it may hold. * - * An op's schema names its operands and their roles but not their extents, because the extents - * are not derivable from the parameters in general -- the run phase supplies them at issue. So a - * tool that wants to CALL an op cold, which is what a correctness check and a benchmark both do, - * has to size its buffers somehow. A hand-written table inside `tools/` cannot serve that: it - * covers only the ops someone wrote a row for and skips the rest, it cannot be extended without - * patching the engine, and it is a place where a tool knows something about an op. + * A schema names operands and their roles but not their extents, which are in general not + * derivable from the parameters (the run phase supplies them at issue). A tool that calls an op + * cold, such as a correctness check or a benchmark, asks the kernel through this hook instead of + * keeping its own table of ops. * - * The kernel is the component that knows. This hook asks it. - * - * WHAT IS IN AN OPERAND MATTERS AS MUCH AS HOW BIG IT IS, and that is why this carries a fill - * domain rather than only a shape. A gated-delta-net `g` is an intra-chunk cumulative sum of - * log-decays: non-increasing and never positive, because every decay the scan forms is - * e^{g_i - g_j} with j <= i and that is <= 1 only because g is monotone. Feed it normals and the - * ORACLE overflows to 2e38 while the kernel does something else, and the comparison then measures - * the test rather than the kernel. The same is true of a sigmoid gate, of a lower-triangular - * factor, and of every index operand: a KV slot indexes n_blocks * block_size positions and a - * block-table entry indexes n_blocks, and drawing either from the wrong range tests the kernel's - * out-of-range handling and calls the result correctness. */ + * The fill domain matters as much as the shape. A gated-delta-net `g` is an intra-chunk cumulative + * sum of log-decays: non-increasing and never positive, since each decay e^{g_i - g_j} with j <= i + * is <= 1 only because g is monotone. Fed normals, the oracle overflows to 2e38 and the comparison + * measures the test rather than the kernel. The same holds for a sigmoid gate, a lower-triangular + * factor and every index operand: a KV slot indexes n_blocks * block_size positions and a + * block-table entry n_blocks, and a draw outside that range tests out-of-range handling instead. */ enum { RAD_FILL_NORMAL = 0, /* standard normals -- the default for a float operand */ RAD_FILL_SIGMOID = 1, /* (0, 1): a gate */ RAD_FILL_GATE_CUMSUM = 2, /* non-increasing and <= 0, reset every `fill_chunk` rows */ RAD_FILL_TRI_LOWER = 3, /* zero above the diagonal within a `fill_chunk` block */ RAD_FILL_INDEX = 4, /* integers; see idx_max / idx_const / the IDX flags */ - /* UNIT L2 NORM ALONG THE LAST DIMENSION. The gated-delta-net key is normalised by the - * model's own qk_norm before it reaches the solve, and the solve inverts I + tril(beta k k^T, - * -1): drawn as unit normals over a 128-wide head that matrix has off-diagonals a hundred - * times too large, its inverse is enormous, and two implementations summing an - * ill-conditioned product in different orders disagree by however ill-conditioned it is. What - * that reports is the condition number of the TEST. Same correction as SIGMOID and - * GATE_CUMSUM above: put the operand in the domain the op is only ever handed. */ + /* Unit L2 norm along the last dimension. The gated-delta-net key is normalised by qk_norm + * before the solve, which inverts I + tril(beta k k^T, -1). With unit normals over a 128-wide + * head the off-diagonals are ~100x too large, the matrix is ill-conditioned, and two + * summation orders disagree by its condition number. Like SIGMOID and GATE_CUMSUM, this puts + * the operand in the domain the op is actually given. */ RAD_FILL_UNIT_ROW = 5, + /* The samplers' `params` plane: [rows, 24] 32-bit words, each row a RadSampleParams + * (rad_sample.h) as a request sets it, its flags agreeing with its fields. Drawn as numbers, + * the integer fields and `flags` are bit patterns (a window is all or nothing, a mask row is + * never in range, each flag is a coin toss) and XTC's threshold is past any probability, so + * the mask and XTC stages do nothing and the others act on a random part of the rows. + * Row 0 switches every stage on; every other row switches each stage on or leaves it at its + * identity at random, and a minority is greedy. `fill_chunk` is the width of the op's history + * plane (0 when it has none: the window is then empty) and `idx_max` the row count of its + * bitmask plane (0 when it has none: `mask_row` is then -1). A tool that does not know the + * value draws normals. */ + RAD_FILL_SAMPLE_PARAMS = 6, }; enum { - /* An OPTIONAL operand this geometry does not pass. One entry per schema operand is still - * emitted -- that count is what catches a hook that has drifted from its schema -- so absence - * needs a spelling, and a null RadTensor.data is what the ABI already means by it. */ + /* An optional operand this geometry does not pass. One entry per schema operand is still + * emitted, since that count catches a hook that drifted from its schema; a null + * RadTensor.data marks the absence. */ RAD_OPD_F_ABSENT = 1u << 0, - /* A SCATTER DESTINATION: no value may repeat. Two tokens drawn onto one slot make the store a - * race, and two implementations resolve it differently -- so the comparison would measure the - * scheduler. A read-side index (a gather row, a block-table entry) may repeat and does. */ + /* A scatter destination: no value may repeat. Two tokens on one slot make the store a race + * that two implementations resolve differently. A read-side index (a gather row, a + * block-table entry) may repeat. */ RAD_OPD_F_IDX_UNIQUE = 1u << 1, - /* CUMULATIVE SEQUENCE LENGTHS, [0, ..., T]. Not a draw: it is the batch's shape. */ + /* Cumulative sequence lengths, [0, ..., T]: the batch's shape, not a draw. */ RAD_OPD_F_IDX_CU = 1u << 2, + /* A routing histogram's offsets, [0, ..., idx_max - 1]: non-decreasing, first 0, last the row + * count, each bucket a run of random length (moe_scatter's `expert_offset`). A uniform draw is + * a malformed histogram that two correct implementations may read differently. Additive: + * RAD_ABI_VERSION does not move, and a tool that does not know the flag draws as before. */ + RAD_OPD_F_IDX_PREFIX = 1u << 3, + /* A token history, [rows, width] ids in [0, idx_max): each row repeats itself as generated + * text does, drawing on a few ids spread over the range and copying runs of its own earlier + * tokens. A uniform draw over a vocabulary never repeats, so a frequency penalty never counts + * past one and DRY (which penalises the token that would extend a repeated suffix) never + * finds a repeat. Additive, as IDX_PREFIX: a tool that does not know the flag draws uniform + * ids. */ + RAD_OPD_F_IDX_HISTORY = 1u << 4, }; typedef struct RadOpdDesc { @@ -273,14 +229,15 @@ typedef struct RadOpdDesc { int64_t shape[RAD_MAX_RANK]; uint32_t fill; /* RAD_FILL_* */ - int64_t fill_chunk; /* the reset width for GATE_CUMSUM and TRI_LOWER */ + /* The reset width for GATE_CUMSUM and TRI_LOWER; the history plane's width for + * SAMPLE_PARAMS. */ + int64_t fill_chunk; - /* RAD_FILL_INDEX only. `idx_max` is the EXCLUSIVE upper bound of the draw; 0 means "the - * leading extent of the previous operand", which is the common case and saves every gather - * from restating it. `idx_const` >= 0 makes every element that value rather than a draw -- - * `seqused` is the one that needs it, because a random context length shorter than the query - * makes a causal attention read a prefix that does not exist, which both implementations - * would then agree about while neither computed what the model asks for. */ + /* RAD_FILL_INDEX only, except that SAMPLE_PARAMS reads `idx_max` as its bitmask plane's row + * count. `idx_max` is the exclusive upper bound of the draw; 0 means the leading extent of the + * previous operand, the common case for a gather. `idx_const` >= 0 sets every element to that + * value instead of drawing. `seqused` needs it: a random context length shorter than the query + * makes causal attention read a prefix that does not exist. */ int64_t idx_max; int64_t idx_const; /* -1 to draw */ @@ -288,95 +245,75 @@ typedef struct RadOpdDesc { } RadOpdDesc; /* Fill `out` for operand `operand` of this op at this geometry. `p`/`n_p` is the resolved - * parameter list, exactly as `launch` would receive it. Return RAD_OK, or RAD_E_UNSUPPORTED when - * this geometry does not carry what the description needs -- a caller SKIPS AND COUNTS that - * rather than guessing an extent, because a tool that invents one tests the kernel's bounds - * handling and calls the result correctness. + * parameter list, exactly as `launch` would receive it. Returns RAD_OK, or RAD_E_UNSUPPORTED when + * this geometry lacks what the description needs; a caller skips and counts that instead of + * guessing an extent. * * Pure host code, no device memory, no side effects: it is called before anything is allocated. */ typedef int (*RadShapeFn)(const RadParam* p, int n_p, int operand, RadOpdDesc* out); /* ================================================================== tunable instantiation */ -/* A KERNEL IS A FAMILY, NOT AN IMPLEMENTATION. Tile sizes, split counts, waves per block: which - * member of the family is fastest is a property of the shape and the machine, and the only way to - * know is to measure it on the machine (spec §15). A library declares the AXES here and the core - * takes the cross product. +/* A kernel is a family: tile sizes, split counts, waves per block. Which member is fastest + * depends on the shape and the machine and must be measured there (spec §15). A library declares + * the axes here and the core takes their cross product. Axes rather than a list of named + * combinations, because a hand-enumerated list has holes (a shape with 40 rows of work runs a + * 64-row tile), and because it keeps the tuning policy out of the launch adapter, where an + * out-of-tree author could not write it. * - * AXES, NOT A LIST OF PRE-NAMED COMBINATIONS. Hand-enumerating the interesting points of a - * multi-axis space -- "wv1_sk8_mb3_npw4" and its twenty-odd siblings -- leaves HOLES, and a hole - * costs step time silently: a ladder that skips a value runs the next tile up, so a shape with - * forty rows of work gets a sixty-four-row tile. A cross product has no holes. - * - * It also keeps the tuning LAW out of the launch adapter, where it would be C++ -- ladders, caps, - * a hand-written picker -- that an out-of-tree author cannot write. - * - * THE CHOSEN VALUES ARRIVE AS ORDINARY PARAMETERS. There is no variant index: once the core has - * picked a point in the space it appends the choices to RadArgs::p, and the kernel reads `sk` with - * the same rad_args_geti() it reads `M` with. One way in, for a value the caller supplied and a - * value the tuner chose. */ + * The chosen values arrive as ordinary parameters appended to RadArgs::p, with no variant index: + * the kernel reads `sk` with the same rad_args_geti() it reads `M` with. */ typedef struct RadTunable { const char* key; /* the kernel's own name for the axis: "sk", "bm", "npw" */ const int64_t* values; /* legal values, ascending; the core tries exactly these */ int n_values; - /* WHAT RUNS WHEN THIS MACHINE HAS NO MEASUREMENT FOR THIS INSTANTIATION -- a fresh install, a - * shape nobody tuned, a cache from another card. There is no fallback beneath it, so it must - * be a value the kernel can actually launch: the loader CHECKS that it appears in `values` - * and refuses the plugin by name if it does not. */ + /* The value used when this machine has no measurement for this instantiation (a fresh + * install, an untuned shape, a cache from another card). There is no fallback beneath it, so + * it must be launchable: the loader checks it appears in `values` and refuses the plugin by + * name if not. */ int64_t deflt; const char* doc; /* what the axis does, for the tuner's report */ } RadTunable; -/* IS THIS COMBINATION LEGAL AT THIS GEOMETRY? Cross-axis rules live here rather than in the axis - * lists, because they are exactly what a product of independent lists cannot say: libr4d's skinny - * GEMM needs `wv * sk * 32` inside the block bound AND `K % (sk * unit) == 0`, and neither is a - * property of `sk` alone. +/* Whether a combination is legal at this geometry. Cross-axis rules live here because independent + * axis lists cannot express them: libr4d's skinny GEMM needs `wv * sk * 32` inside the block bound + * and `K % (sk * unit) == 0`. * * `p` is the resolved geometry, `choice` the candidate as key/value parameters. Pure host code, - * called before anything is allocated, once per candidate. + * called once per candidate before anything is allocated. * - * Returns 1 for legal and 0 for SKIP -- which is not an error. A kernel may serve a subset of its - * own cross product, and the tuner reports a skipped candidate as skipped rather than as a - * failure. Null means every combination is legal. */ + * Returns 1 for legal and 0 for skip, which is not an error: a kernel may serve a subset of its + * cross product, and the tuner reports the candidate as skipped. Null means every combination is + * legal. */ typedef int (*RadTuneValidFn)(const RadParam* p, int n_p, const RadParam* choice, int n_choice); /* ================================================================== op schemas */ -/* A parameter is supplied by the caller (REQUIRED), may be (OPTIONAL), or is supplied by the - * KERNEL (DERIVED). +/* A parameter is supplied by the caller (REQUIRED), may be supplied (OPTIONAL), or is supplied by + * the kernel (DERIVED). * - * DERIVED exists because of a circularity that block_size makes concrete. Spec §7.2 says the - * paged block size comes from the resolved attention kernel and not from a core constant -- - * libr4d is compiled for 16 and rejects anything else. But a constraint whose key the geometry - * does not carry does NOT hold (libr4d's rule, and the reason its two-shot all-reduce rows have - * to precede the one-shot ones), so a kernel constrained to block_size == 16 can never be - * selected by a query that omits block_size -- and the resolution the answer was to be read off - * never happens. + * DERIVED breaks a circularity. The paged block size comes from the resolved attention kernel, not + * a core constant (spec §7.2; libr4d is compiled for 16). But a constraint whose key the geometry + * does not carry does not hold (which is also why libr4d's two-shot all-reduce rows must precede + * the one-shot ones), so a kernel constrained to block_size == 16 could never be selected by a + * query that omits block_size. * - * So: constraints on a DERIVED parameter are SKIPPED during matching, and once a kernel wins, - * its RAD_C_EQ value for that key is written into the resolved geometry. A caller that supplies - * one anyway pins it, and it matches normally -- which is how an operator forces a block size - * and gets a refusal by name rather than a silent substitution. A kernel with no EQ on a derived - * key leaves it unset, and rad_kv_block_size() reports that rather than returning zero. */ + * So constraints on a DERIVED parameter are skipped during matching, and the winning kernel's + * RAD_C_EQ value for that key is written into the resolved geometry. A caller that supplies one + * pins it and it matches normally, so a forced block size is refused by name rather than silently + * substituted. A kernel with no EQ on a derived key leaves it unset, and rad_kv_block_size() + * reports that rather than returning zero. */ enum { RAD_OPTIONAL = 0, RAD_REQUIRED = 1, RAD_DERIVED = 2 }; -/* WHAT A PARAMETER MEANS TO THE CORE, when the core has to act on one it did not invent. - * - * Almost none of them: a parameter is a key the plugin and the kernel agree on and the core - * carries it opaquely, which is the whole reason a third party can add an op. The exception is - * the SEQUENCE CHUNK. A linear-state scan tiles the token stream, its kernel is compiled for one - * tile length, and the SCHEDULER has to cut its steps on a multiple of that or a chunk straddles - * a sequence boundary -- so the core does need to find that one number in a geometry it otherwise - * does not read. - * - * The schema is where that number is named, and the alternative is worse: a core that found it by - * SPELLING would carry a list of likely keys ("chunk", "chunk_size", "state_chunk", ...) inside - * the scheduler, which makes the core the thing you edit to add a kernel that spells it - * differently. Declaring the role costs a field and keeps the core free of that vocabulary. */ -/* RAD_PROLE_CAPACITY is a count the kernel is handed as a BOUND and never writes past its - * operands for: it launches, loops and writes by the extents of the tensors it is given. That is - * what lets the activation arena be declared again at a smaller step (RadBuildCtx::shape_probe) -- - * the kernel keeps the geometry it was selected with, including the real declare's value here, - * while its buffers are the smaller step's -- so it is the KERNEL's claim to make, and a fixed - * parameter that differs between the two declares without it refuses the smaller size. */ +/* What a parameter means to the core. The core carries almost every parameter opaquely, which is + * what lets a third party add an op. The exception is the sequence chunk: a linear-state scan is + * compiled for one tile length, and the scheduler must cut its steps on a multiple of it or a + * chunk straddles a sequence boundary. The schema names that role so the core does not have to + * find the parameter by guessing its spelling. */ +/* RAD_PROLE_CAPACITY marks a count the kernel is handed as a bound and never writes past its + * operands for: it launches, loops and writes by the extents of the tensors it is given. That lets + * the activation arena be declared again at a smaller step (RadBuildCtx::shape_probe) while the + * kernel keeps the geometry it was selected with, including the real declare's value here. It is + * the kernel's claim to make; without it, a fixed parameter that differs between the two declares + * refuses the smaller size. */ enum { RAD_PROLE_NONE = 0, RAD_PROLE_SEQ_CHUNK = 1, RAD_PROLE_CAPACITY = 2 }; typedef struct RadParamSpec { @@ -386,13 +323,12 @@ typedef struct RadParamSpec { int role; /* RAD_PROLE_*; 0 for every parameter the core does not interpret */ } RadParamSpec; -/* Positional operand roles. The core needs to know which operands are weights (so issue can - * resolve a handle and wait on the mover) and which are written (so the buffer planner can - * compute liveness). It does not need to know anything else about them. */ -/* RAD_OPD_WTAB is a weight operand whose issue names a RUN of weights rather than one -- a MoE - * layer's experts -- and the kernel is handed a device array of pointers. It is a role of its own - * and not a flag on RAD_OPD_WEIGHT so that a tool reading the schema knows the operand is not a - * plane it can describe with one shape: see RAD_WTAB in rad_runtime.h. */ +/* Positional operand roles. The core needs to know only which operands are weights (issue resolves + * a handle and waits on the mover) and which are written (the buffer planner computes liveness). */ +/* RAD_OPD_WTAB is a weight operand whose issue names a run of weights (a MoE layer's experts); + * the kernel is handed a device array of pointers. It is a separate role, not a flag on + * RAD_OPD_WEIGHT, so a tool reading the schema knows the operand is not one plane it can describe + * with one shape: see RAD_WTAB in rad_runtime.h. */ enum { RAD_OPD_IN = 0, RAD_OPD_OUT = 1, RAD_OPD_INOUT = 2, RAD_OPD_WEIGHT = 3, RAD_OPD_WTAB = 4 }; @@ -412,46 +348,31 @@ typedef struct RadOpSchema { /* ================================================================== declared fusions * - * WHAT CHAIN OF CONVENTIONAL OPS DOES THIS KERNEL COMPUTE? + * Which chain of conventional ops a kernel computes. * - * The obvious design is for a kernel library to advertise that "kernel A can be used to fuse B - * and C", and for the engine to apply that repeatedly until the graph converges. spec.md §2.3 - * refuses the second half -- "a fusion rewriter is a compiler, and a compiler is the thing whose output nobody can - * predict" -- and the declare phase keeps nothing a rewriter could work on in any case: `Program` - * holds no operand edges. The Builder computes them, collapses each buffer's whole use-set to a - * `first_def`/`last_use` pair with reads and writes MERGED, and discards the rest when it returns. + * This is a declaration, not a rewriter. spec.md §2.3 rules out a fusion rewriter, and the + * declare phase keeps nothing one could work on: `Program` holds no operand edges, and the Builder + * collapses each buffer's use-set to a `first_def`/`last_use` pair with reads and writes merged. * "Op A's output is op B's only input" is not recoverable from that, which is also why - * `--debug-graph` declines to print an edge it cannot prove. + * `--debug-graph` prints no edge it cannot prove. Fusion stays a selection: the architecture asks + * for the fused op and emits the sequence when nothing serves it (rad_op_resolved in + * rad_builder.h is the idiom for a banded or optional fusion). * - * So this is a DECLARATION, not a rewriter. Fusion stays a selection: the architecture asks for - * the fused op and emits the sequence when nothing serves it (spec.md 2.3, and rad_op_resolved in - * rad_builder.h, which is the idiom an out-of-tree plugin needs for a banded or optional fusion). - * What the declaration adds is that the EQUIVALENCE becomes machine-readable instead of prose in a - * kernel row -- "byte-identical to the two ops it replaces" -- and prose cannot be checked. It - * buys three things: + * The declaration makes the equivalence machine-readable, which gives: + * - an oracle: a fused kernel with no libref counterpart is checked against its chain run on the + * same plugin's unfused rows, and the answer should be byte-identical; + * - an advisory in --debug-graph: these declared ops form a chain some kernel can run in one + * launch, and why it did not fire; + * - the per-library fusion-claim count in rad-kbench's report. * - * AN ORACLE, which is the one that matters. A fused kernel with no libref counterpart can only - * be skipped by name, and such skips dominate what a coverage run reports on a model built out - * of fusions. A fused kernel that declares its chain can instead be checked against that chain - * run out of the SAME plugin's unfused rows -- which is precisely the claim the row makes, and - * a stronger test than a tolerance against ref, because the answer should be BYTE-IDENTICAL. + * It is a hook rather than a table because a step's geometry is not always derivable from the + * fused op's: `qk_norm_rope_gate` replaces an `rmsnorm` at M = T * n_head, a product that is not + * in its parameter list. * - * AN ADVISORY in --debug-graph: these N declared ops are a chain some kernel says it can do in - * one launch, and here is why it did not fire. - * - * A COVERAGE METRIC, which spec.md:19 lists. - * - * WHY A HOOK AND NOT A TABLE. A step's geometry is not the fused op's geometry and is not always - * derivable by a caller: `qk_norm_rope_gate` replaces an `rmsnorm` at M = T * n_head, and nothing - * in the fused op's parameter list is that product. The kernel is the component that knows, which - * is the same argument RadShapeFn and RadLayoutFn already make. - * - * OPERAND WIRING. Every operand of every step is either an operand of the FUSED kernel or a - * TEMPORARY the chain passes between its own steps. A temporary needs no description here: it is - * sized and typed by the step's own `opd_shape`, which every kernel that wants to be checked this - * way already publishes. Note how often no temporary is needed at all -- the fp8 folds still WRITE - * their intermediate when `out_bf16` is passed, precisely so the fused and unfused forms leave the - * same buffers behind. */ + * Operand wiring: every operand of every step is either an operand of the fused kernel or a + * temporary passed between steps. A temporary needs no description here; the step op's own + * `opd_shape` sizes and types it. Often none is needed: the fp8 folds still write their + * intermediate when `out_bf16` is passed, so the fused and unfused forms leave the same buffers. */ enum { RAD_FUSE_NONE = -1, /* this step does not pass that optional operand */ }; @@ -465,12 +386,11 @@ enum { RAD_MAX_FUSE_OPD = 16, RAD_MAX_FUSE_PARAMS = 12, RAD_MAX_FUSE_TMP = 8 }; typedef struct RadFuseStep { const char* op; /* a conventional op name -- see docs/OPS.md */ - RadParam p[RAD_MAX_FUSE_PARAMS]; /* this STEP's geometry, not the fused one's */ + RadParam p[RAD_MAX_FUSE_PARAMS]; /* this step's geometry, not the fused one's */ int n_p; /* One entry per operand of `op`, in its schema's order: an operand index of the fused kernel, * RAD_FUSE_TMP(t), or RAD_FUSE_NONE. The count is checked against the step op's schema, so a - * hook that drifts from the vocabulary is a diagnosable error rather than a silent misfire -- - * the same rule RadShapeFn's operand count follows, and for the same reason. */ + * hook that drifts from the vocabulary is a diagnosable error (as with RadShapeFn). */ int16_t from[RAD_MAX_FUSE_OPD]; int n_from; } RadFuseStep; @@ -478,34 +398,22 @@ typedef struct RadFuseStep { /* Describe step `step` of the chain this kernel replaces, for this geometry and variant. * * RAD_OK `out` is filled; ask again with step + 1. - * RAD_E_NOTFOUND `step` is past the end. This is how a caller learns the chain's LENGTH, - * and it is why there is no count beside the hook: the chain may differ with - * the geometry (an `rmsnorm_quant_fp8` with a residual replaces `rmsnorm_add` - * and without one replaces `rmsnorm`). - * RAD_E_UNSUPPORTED this geometry or variant has no unfused equivalent in the vocabulary. An - * honest answer, and the right one wherever a fusion computes something the - * conventional ops cannot express between them. + * RAD_E_NOTFOUND `step` is past the end. This is how a caller learns the chain's length, + * which may differ with the geometry (an `rmsnorm_quant_fp8` with a residual + * replaces `rmsnorm_add`, without one `rmsnorm`). + * RAD_E_UNSUPPORTED this geometry or variant has no unfused equivalent in the vocabulary. * - * A chain must be EXACT, not approximate. A kernel that is merely close to the sequence it names - * should publish no hook at all: the whole value of the declaration is that a caller may - * substitute one for the other and compare the bytes. */ -/* WHICH OPTIONAL OPERANDS THIS CALL PASSES, one bit per operand of the FUSED op, bit i set when - * operand i is present. + * A chain must be exact. A kernel that is merely close to a sequence publishes no hook, because + * callers substitute one for the other and compare the bytes. */ +/* `present` has bit i set when operand i of the fused op is passed. The chain can depend on an + * operand, not only on a parameter: `rmsnorm_quant_fp8` replaces `add` -> `rmsnorm` -> + * `quant_act_fp8` given a residual and `rmsnorm` -> `quant_act_fp8` without. Inferring presence + * from the plugin's own RadShapeFn is right for a checker calling the kernel cold but wrong for a + * caller holding a real issue, such as the graph dump. `RAD_FUSE_NONE` cannot express it, since + * the operands that vary are the step's required ones. * - * THIS IS NOT DECORATION: without it the chain is not answerable at all. - * `rmsnorm_quant_fp8` replaces `add` -> `rmsnorm` -> `quant_act_fp8` when it is given a residual - * and `rmsnorm` -> `quant_act_fp8` when it is not: THE CHAIN LENGTH ITSELF depends on an operand, - * not on a parameter. Without this the hook has to infer presence, and the only honest inference - * available is "whatever this plugin's own RadShapeFn publishes" -- which is right for a checker - * calling the kernel cold, since that is where its buffers came from, and WRONG for a caller - * holding a real issue, which is what the graph dump has. A fold with no residual would be - * described as three steps and the advisory would be a lie. - * - * Nor could `RAD_FUSE_NONE` express it: the operands that vary are the step's REQUIRED ones. - * - * RAD_FUSE_PRESENT_ALL is what a caller passes when it does not know, and it means exactly "answer - * for every operand your description says exists". That is a contract rather than a coupling: the - * hook may then assume its own RadShapeFn, and a caller that knows better says so. */ + * RAD_FUSE_PRESENT_ALL means the caller does not know: answer for every operand your RadShapeFn + * says exists. */ #define RAD_FUSE_PRESENT_ALL ((uint64_t)~0ull) #define RAD_FUSE_HAS(mask, i) (((mask) >> (i)) & 1ull) @@ -522,13 +430,13 @@ typedef struct RadKernelInfo { const char* dtypes; int domain; /* RAD_DOMAIN_DEVICE | RAD_DOMAIN_HOST */ - int priority; /* higher wins WITHIN THIS PLUGIN; ties break on declaration order */ + int priority; /* higher wins within this plugin; ties break on declaration order */ const RadConstraint* constraints; int n_constraints; - /* The axes of this kernel's instantiation space, and the cross-axis legality test. Null/0 - * means one implementation with nothing to tune, which is the common case and costs nothing: - * the core appends no choices and the kernel reads no tuned key. See RadTunable. */ + /* The axes of this kernel's instantiation space and the cross-axis legality test. Null/0 + * means one implementation with nothing to tune (the common case): the core appends no + * choices and the kernel reads no tuned key. See RadTunable. */ const RadTunable* tunables; int n_tunables; RadTuneValidFn tune_valid; @@ -538,37 +446,30 @@ typedef struct RadKernelInfo { RadScratchFn scratch; RadLayoutFn layout; RadRelayoutFn relayout; - /* How to size and fill each operand, for a tool that calls this kernel cold. Null means this - * kernel cannot describe itself and every tool that needs a buffer for it skips it BY NAME - * rather than guessing. libref supplies it for the whole conventional vocabulary, so an - * op that stays inside docs/OPS.md is describable even when the kernel under test is not. */ + /* How to size and fill each operand, for a tool that calls this kernel cold. Null means tools + * that need a buffer for it skip it by name. libref supplies it for the whole conventional + * vocabulary, so an op in docs/OPS.md is describable even when the kernel under test is not. */ RadShapeFn opd_shape; - /* The inverse of `relayout`, for a tool holding the stored bytes rather than the planes. - * Null means this kernel's stored form cannot be read back, and a dense oracle therefore has - * nothing to compare against -- which is a skip, named, and not a failure. */ + /* The inverse of `relayout`, for a tool holding the stored bytes rather than the planes. Null + * means the stored form cannot be read back, so a dense oracle has nothing to compare + * against: a named skip, not a failure. */ RadUnrelayoutFn unrelayout; - /* The chain of conventional ops this kernel computes in one launch, or null for a kernel that - * is not a fusion. Non-null is also the fusion-coverage metric's numerator: it is a kernel - * saying "I stand in for these, and you may check me against them". */ - RadFuseFn replaces; - /* Optional. The same dispatch, described rather than performed, so a repeatedly issued - * sequence can be replayed as a graph. Null means this kernel is always submitted - * individually, which is correct and merely slower. See RadDescribeFn for the one trap. + /* The chain of conventional ops this kernel computes in one launch, or null if it is not a + * fusion. Non-null also counts in rad-kbench's fusion-claim column. * - * LAST IN THE STRUCT ON PURPOSE. Every kernel table in this tree is a POSITIONAL aggregate - * initialiser -- `{..., nullptr, nullptr, r4d_rad_embed_lookup, nullptr, ...}` -- so a field - * inserted anywhere else silently shifts every initialiser after it, and `nullptr` converts - * to any function pointer type, so part of that shift would compile. Append here. */ - RadDescribeFn describe; + * Keep this field last. Kernel tables are positional aggregate initialisers + * (`{..., nullptr, nullptr, r4d_rad_embed_lookup, nullptr, ...}`), so a field inserted + * anywhere else shifts every later initialiser, and since `nullptr` converts to any function + * pointer type, part of that shift would still compile. Append new fields after this one. */ + RadFuseFn replaces; } RadKernelInfo; /* ================================================================== kernel plugin exports */ -/* Every kernel plugin exports the whole set. The schemas come first: the first plugin in - * hierarchy order to declare an op fixes its schema, and a later plugin declaring the same op - * name with a different schema is refused at load with both plugins named. Since arguments are - * positional, two disagreeing schemas would make the same call mean different things depending - * on which plugin won selection, and that is not a diagnosable failure -- it is silent - * numerical garbage (spec §2.3). */ +/* Every kernel plugin exports the whole set. The first plugin in hierarchy order to declare an op + * fixes its schema; a later plugin declaring the same op name with a different schema is refused + * at load with both plugins named. Arguments are positional, so disagreeing schemas would make + * the same call mean different things depending on which plugin won selection, silently + * (spec §2.3). */ int rad_kernel_schema_count(void); const RadOpSchema* rad_kernel_schema_at(int i); int rad_kernel_count(void); @@ -577,59 +478,54 @@ const RadKernelInfo* rad_kernel_at(int i); /* Optional. Called once after the plugin is loaded and before any selection, and once at * shutdown. A plugin with no global state need not export them. * - * THE SYMBOL NAMES ARE `rad_plugin_open` and `rad_plugin_close`. The types are named here so a - * plugin can declare them with the right signature; the loader resolves them by those exact - * names, and a plugin that spells them differently is silently never initialised. + * The symbol names are `rad_plugin_open` and `rad_plugin_close`; the types exist so a plugin can + * declare them with the right signature. The loader resolves those exact names, so a plugin that + * spells them differently is silently never initialised. * - * `rad_plugin_open` answering RAD_E_UNSUPPORTED DECLINES this machine: the plugin is unloaded and - * the rest of the installation carries on, which is how one installation ships libraries for - * several cards. Any other negative status refuses the plugin as an error. A kernel library does - * not need to decline a card its device code was not built for -- the loader reads that out of - * the code objects it carries and leaves its device kernels out on its own. */ + * `rad_plugin_open` returning RAD_E_UNSUPPORTED declines this machine: the plugin is unloaded and + * the rest of the installation carries on, so one installation can ship libraries for several + * cards. Any other negative status refuses the plugin as an error. A kernel library need not + * decline a card its device code was not built for: the loader reads that from the code objects + * and leaves those device kernels out itself. */ typedef int (*RadPluginOpenFn) (void); typedef void (*RadPluginCloseFn)(void); -/* Optional, and a promise about kernel `i` of rad_kernel_at: nonzero means every launch of it - * reads and writes no memory but its operands and the scratch it was handed -- no allocation it - * keeps for itself, no counter it keeps between launches -- so two launches may run at the same - * time on one device whenever their operands and scratch do not overlap. The engine then lets a - * launch start before the independent ones in front of it on its queue have finished. A plugin - * that does not export the symbol, or answers 0, has every launch ordered behind everything - * before it, which is always correct. The symbol name is `rad_kernel_concurrent`. */ +/* Optional promise about kernel `i` of rad_kernel_at: nonzero means every launch reads and writes + * only its operands and the scratch it was handed (no allocation it keeps, no counter kept between + * launches), so two launches may run at once on one device when their operands and scratch do not + * overlap. The engine then lets such a launch start before independent earlier launches on its + * queue finish. Without the symbol, or with 0, every launch is ordered behind everything before + * it, which is always correct. Symbol name: `rad_kernel_concurrent`. */ typedef int (*RadKernelConcurrentFn)(int i); -/* Optional, and a promise about kernel `i` of rad_kernel_at: nonzero means it is a COLLECTIVE -- - * its launches exchange data with the other ranks' cards, so the interconnect carries their bytes - * for as long as they run and the step waits on it. The engine then keeps its own bulk traffic on - * the same links (weights it streams onto the card while the card computes) out of their way for - * that time. A plugin that does not export the symbol, or answers 0, has only the conventional - * `all_reduce` op treated as one. The symbol name is `rad_kernel_collective`. +/* Optional promise about kernel `i` of rad_kernel_at: nonzero means it is a collective. Its + * launches exchange data with the other ranks' cards, so the interconnect carries their bytes + * while they run and the step waits on it. The engine keeps its own bulk traffic on those links + * (weights streamed to the card during compute) out of the way for that time. Without the symbol, + * or with 0, only the conventional `all_reduce` op is treated as a collective. Symbol name: + * `rad_kernel_collective`. * - * 2 promises more: every launch of the kernel ends that time itself, as soon as the last byte the - * other ranks send this card for it has landed -- a kernel that reduces after the exchange has the - * link to spare for the rest of its run. The engine then hands each launch it holds the link for - * the parameter `link_gate`, the address of a 64-bit word in memory the kernel reaches at system - * scope; a launch without it holds nothing and has nothing to end. The kernel reads the word on - * the device as it starts -- not the host in the launch call, where the hold has not taken effect - * yet -- and, once those bytes have landed, takes one off it with a system-scope atomic if it was - * odd; an even word it leaves alone. A launch that did so returns RAD_LINK_ENDED; any other - * success is RAD_OK, and the engine then ends the hold behind the launch, so a path that does not - * know the word is always safe. */ + * 2 promises more: each launch ends the link hold itself as soon as the last byte the other ranks + * send this card for it has landed, so a kernel that reduces after the exchange frees the link for + * the rest of its run. The engine then passes each launch it holds the link for the parameter + * `link_gate`, the address of a 64-bit word the kernel reaches at system scope; a launch without + * it holds nothing. The kernel reads the word on the device as it starts (not on the host in the + * launch call, where the hold is not yet in effect) and, once those bytes have landed, decrements + * it with a system-scope atomic if it was odd; an even word it leaves alone. A launch that + * decremented returns RAD_LINK_ENDED. Any other success returns RAD_OK and the engine ends the + * hold behind the launch, so a path that ignores the word is always safe. */ typedef int (*RadKernelCollectiveFn)(int i); #define RAD_LINK_ENDED 1 -/* Optional: nonzero declares this kernel library a REFERENCE implementation -- written to be - * plainly correct rather than fast. Three things follow, for any library that says so and for no - * other, whatever it is called: +/* Optional: nonzero declares this kernel library a reference implementation, written to be + * plainly correct rather than fast. For any library that says so, whatever its name: * - the loader ranks it below every unnamed kernel library, because a reference matches every - * op it declares and would otherwise answer for them ahead of the library serving the card - * (naming it in --kernels still puts it where it is named, and a --kernels list that does - * not name it leaves it out); + * op it declares and would otherwise win over the library serving the card (naming it in + * --kernels still places it where named, and a --kernels list that omits it leaves it out); * - the engine refuses to serve a model with an op only a reference library implements, unless - * told to with --debug-accept-reference-kernels; + * given --debug-accept-reference-kernels; * - rad-kbench checks every other library against it. - * A plugin that does not export the symbol, or answers 0, is an ordinary library. The symbol name - * is `rad_plugin_reference`. */ + * Without the symbol, or with 0, it is an ordinary library. Symbol name: `rad_plugin_reference`. */ typedef int (*RadPluginReferenceFn)(void); #ifdef __cplusplus diff --git a/abi/rad_builder.h b/abi/rad_builder.h index 30a5a571..2b1477af 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -1,9 +1,8 @@ -/* rad_builder.h -- the declare phase. An architecture plugin states everything it will ever do - * before it does any of it: every weight, every buffer, every op, in order. See spec.md §3.1. +/* rad_builder.h -- the declare phase. An architecture plugin states everything it will do before + * doing any of it: every weight, every buffer, every op, in order. See spec.md §3.1. * - * Between declare and plan the whole model is known statically -- every op, every kernel that - * will service it, every weight it touches, and the order. That is the property the rest of the - * engine spends. + * After declare, the whole model is known statically (every op, the kernel serving it, the weights + * it touches, and the order), and the rest of the engine relies on that. */ #ifndef RAD_BUILDER_H #define RAD_BUILDER_H @@ -39,10 +38,10 @@ typedef struct RadModelMeta { float rms_eps; float rope_theta; - /* Always 1. A rotary's scaling is a TYPE with parameters -- linear, YaRN, llama3, longrope -- - * and it is carried in the free-form keys below (rope_parameters.* / rope_scaling.*, with - * text_config.* and draft.* forms), which arch/common/rad_arch.h's yarn_from reads and refuses - * by name. A bare factor here would read every scheme as a linear position divide. */ + /* Always 1. Rotary scaling is a type with parameters (linear, YaRN, llama3, longrope) carried + * in the free-form keys below (rope_parameters.* / rope_scaling.*, with text_config.* and + * draft.* forms); arch/common/rad_arch.h's yarn_from reads them and refuses unknown schemes by + * name. A bare factor here would read every scheme as a linear position divide. */ float rope_scale; /* Free-form key/value from the container header, for anything the struct above does not @@ -59,104 +58,102 @@ const char* rad_meta_gets(const RadModelMeta* m, const char* key, const char* df /* ================================================================== build context */ typedef struct RadBuildCtx { int rank; /* declare runs once per rank; the plugin declares dimensions */ - int world_size; /* ALREADY DIVIDED -- the core inserts no collectives (spec §9) */ + int world_size; /* already divided -- the core inserts no collectives (spec §9) */ int64_t max_tok; /* the largest token count one step may carry */ int64_t max_seqs; /* the largest number of sequences one step may carry */ int64_t max_ctx; /* context bound this deployment was configured for */ int max_spec; /* speculative window bound, 0 if speculation is off */ - /* THE TENSOR-PARALLEL WIRE. 0 -- which is what a zero-initialised context gives, and that is - * deliberate -- is the EXACT all-reduce. Nonzero says this deployment accepts a lossy wire, - * which at two ranks libr4d serves as a Walsh-Hadamard-rotated 6-bit payload: 6 bits an - * element plus a bf16 scale per group of 64, against 16 bits an element, so the message a - * prefill chunk pushes across the link drops by 2.4x. The plugin inverts it into - * `all_reduce`'s `exact` parameter. The polarity is this way round because the sum a rank - * receives is then not the sum it would have received, and a field that defaults to lossy - * when someone forgets to fill it is the failure spec §17 exists to prevent. */ + /* The tensor-parallel wire. 0 (the zero-initialised default) is the exact all-reduce. Nonzero + * accepts a lossy wire: at two ranks libr4d serves a Walsh-Hadamard-rotated 6-bit payload (6 + * bits an element plus a bf16 scale per group of 64, so a prefill chunk's message shrinks + * 2.4x), at three and four ranks a tiered int8 two-shot. The plugin inverts it into + * `all_reduce`'s `exact` parameter. + * The polarity makes a context that forgets the field exact, not lossy (spec §9). */ int tp_wire_lossy; - /* WHERE THE LOSSY WIRE STARTS PAYING, in bytes of one all-reduce message. Below it the exact - * kernel wins and the plugin must use it even when `tp_wire_lossy` is set: compression only - * pays once the transfer is bandwidth-bound, and a decode step's message is not -- it is a few - * tokens of the residual stream, where the rotate/pack/unpack costs more than the bytes it - * saves. Above it a prefill chunk is squarely on the wire and the 2.4x is real. 0 means the - * plugin's own default, which is 128 KiB. */ + /* The all-reduce message size, in bytes, from which the lossy wire is used. Below it the + * plugin must use the exact kernel even when `tp_wire_lossy` is set: compression pays only + * once the transfer is bandwidth-bound, and a decode step's few residual rows cost more to + * rotate/pack/unpack than they save. 0 means the plugin's default, 128 KiB. */ int64_t tp_wire_min_bytes; - /* THE KV CACHE'S WIDTH, AND IT IS A DEPLOYMENT CHOICE RATHER THAN A PROPERTY OF THE - * CHECKPOINT. `kv_dtype` follows the CACHE, not the weights: a container whose weights are - * fp8 may well want a bf16 cache and vice versa, and one field read as "the cache is bf16 - * because the weights are" was true of one checkpoint and never a rule. + /* The KV cache dtype, a deployment choice rather than a property of the checkpoint: fp8 + * weights may want a bf16 cache and vice versa. * - * RAD_DT_INVALID -- which is what a zero-initialised context gives -- means the plugin's own - * default, which every architecture in this tree takes as bf16. RAD_F8E4M3 is the other - * value anything implements today; the fp8kv attention family is band-gated on it and the - * store side writes E4M3 with per-(sequence, head) descales. + * RAD_DT_INVALID (the zero-initialised default) means the plugin's default, bf16 for every + * architecture in this tree. RAD_F8E4M3 is the only other implemented value: the fp8kv + * attention family is band-gated on it, and the store side writes E4M3 with per-(sequence, + * head) descales. * - * IT IS AN ABI FIELD AND NOT AN ENVIRONMENT VARIABLE because it changes what the model - * computes. A per-architecture environment switch gives "is the cache fp8" one answer per - * architecture, each with its own default, and none of them appears in the startup log or in - * a bug report. --kv-cache-dtype is the one answer. */ + * An ABI field rather than an environment variable because it changes what the model + * computes, so it must have one visible answer: --kv-cache-dtype. */ int kv_dtype; /* RAD_DT_INVALID = the plugin's default (bf16); or RAD_F8E4M3 */ int is_draft; /* this builder scope is a drafter (spec §10) */ const char* scope; /* "", "draft", "vision", "audio" -- prefixes declared names */ - /* A DECLARE THAT ONLY SIZES THE ACTIVATIONS, at a `max_tok` smaller than the deployment's. - * The core runs one per level of the activation arena it lends out: what the plugin declares - * says how big every buffer is when no step carries more than `max_tok` tokens, and the top of - * the arena past that is lent to the expert slab while the steps are that small. + /* Nonzero: a declare that only sizes the activations, at a `max_tok` smaller than the + * deployment's. The core runs one per level of the activation arena it lends out; the result + * gives every buffer's size when no step carries more than `max_tok` tokens, and the arena + * above that is lent to the expert slab while steps are that small. * - * THE PLUGIN MUST LEAVE ITS OWN STATE ALONE WHILE THIS IS SET. The state its step function - * reads was written by the real declare, at the real `max_tok`, and a sizing declare that - * overwrote it would run every later step against the smaller configuration. Declare into - * scratch storage instead; nothing a sizing declare produces is ever issued, and its op - * handles are the real declare's. + * Invariant: the plugin must not touch its own state while this is set. Its step function + * reads state the real declare wrote at the real `max_tok`; overwriting it would run every + * later step against the smaller configuration. Declare into scratch storage instead: nothing + * a sizing declare produces is issued, and its op handles are the real declare's. * * Only asked of a plugin that set RadArchProbe::shape_probe_ok. Trailing and zero-defaulted, * so a plugin built against the older struct is unchanged. */ int shape_probe; - /* THE MOST PATCHES ONE ENCODER PASS MAY CARRY, and 0 means this deployment serves no media: - * the plugin declares no encoder, so a tower the container carries stays off the card. It is - * the encoder's `max_tok` -- every activation it declares is sized against it -- and it bounds - * the largest single image the server accepts, since one image is one attention segment and a - * segment is never split across passes. */ + /* The most patches one encoder pass may carry; 0 means the deployment serves no media, the + * plugin declares no encoder, and a tower the container carries stays off the card. It is the + * encoder's `max_tok` (its activations are sized against it) and bounds the largest single + * image accepted, since one image is one attention segment and is never split across passes. */ int64_t max_enc_patches; - /* THE MOST LOGITS ROWS ONE STEP MAY NAME, when that is more than the plugin's own rule of one - * per sequence (1 + max_spec at a speculative step). 0 is the rule. The engine's KL mode sets - * it to a whole step's tokens plus a row a sequence, because it reads a full-vocabulary row at - * every prompt position; the logits buffer and the lm_head's row range are sized from it. The - * engine reads the declared logits buffer back and refuses the mode when it is shorter, so a - * plugin that ignores the field is refused rather than overrun. + /* The most logits rows one step may name, when that exceeds the plugin's own rule of one per + * sequence (1 + max_spec at a speculative step); 0 is the rule. The engine's KL mode sets it to + * a step's tokens plus a row per sequence, since it reads a full-vocabulary row at every prompt + * position; the logits buffer and the lm_head's row range are sized from it. The engine checks + * the declared logits buffer and refuses the mode when it is shorter, so a plugin that ignores + * the field is refused rather than overrun. * * Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */ int64_t max_out_rows; - /* THE MOST FRAMES ONE AUDIO ENCODER PASS MAY CARRY, and 0 means this deployment serves no - * audio: the plugin declares no audio encoder. An audio encoder's `max_tok`, the way - * max_enc_patches is a vision tower's -- its activations are sized against it -- and it bounds - * the longest clip, since one clip is one segment. The engine takes it from - * RadArchProbe::audio_frames, which is the plugin's statement of its longest clip. + /* The most frames one audio encoder pass may carry; 0 means no audio and no audio encoder. + * It is the audio encoder's `max_tok`, as max_enc_patches is a vision tower's, and bounds the + * longest clip, since one clip is one segment. The engine takes it from + * RadArchProbe::audio_frames. * * Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */ int64_t max_audio_frames; + + /* The most tokens a step of more than one sequence may carry, when that is less than + * max_tok; 0 means max_tok. Under --prefill-span a prefill alone in its step may take max_tok + * and every other step is planned at a shared budget, so a step wider than this is one + * sequence. A plugin may size a buffer holding a row per query of every sequence in a step at + * this, and serve a wider step a window at a time. + * + * Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */ + int64_t max_mixed_tok; } RadBuildCtx; /* ================================================================== weights */ -/* Access class, declared per weight because it is information only the architecture plugin has. - * It is what tells the placement planner whether prefetch can be exact (spec §5.2). */ +/* Access class, declared per weight because only the architecture plugin knows it. It tells the + * placement planner whether prefetch can be exact (spec §5.2). */ enum { RAD_ACCESS_PER_TOKEN = 0, /* read every forward pass -- dense weights */ RAD_ACCESS_PER_REQUEST = 1, /* read once per request -- an encoder tower, with an image */ RAD_ACCESS_CONDITIONAL = 2, /* read only if selected -- routed experts */ RAD_ACCESS_RARE = 3, /* may not be read at all in a given deployment */ - RAD_ACCESS_VOCAB = 4 /* lm_head and the embedding table: read every token, enormous, - * and one of them is a gather rather than a GEMM. Its own class - * because neither PER_TOKEN's prefetch nor CONDITIONAL's - * prediction describes it (spec §19.2). */ + RAD_ACCESS_VOCAB = 4 /* lm_head and the embedding table: read every token, very + * large, and one is a gather rather than a GEMM. Neither + * PER_TOKEN's prefetch nor CONDITIONAL's prediction fits it + * (spec §5.2). */ }; /* How a weight is split across tensor-parallel ranks. The plugin says; the core does not infer. */ @@ -167,88 +164,83 @@ enum { }; /* Grouping key: the unit of movement. An expert's gate/up/down share one, because the unit of - * transfer is an expert, not a tensor (spec §4.1). Layer grouping is what makes layer offload a - * contiguous run rather than a scatter. */ + * transfer is an expert, not a tensor (spec §4.2). Layer grouping makes layer offload a contiguous + * run rather than a scatter. */ typedef struct RadWeightGroup { int32_t layer; /* -1 for a model-level weight */ int32_t expert; /* -1 for a non-expert weight */ int32_t slot; /* free index within the group, e.g. gate=0 up=1 down=2 */ } RadWeightGroup; -/* NOTE: these are C compound literals, which C++ accepts only as a GNU extension. An architecture - * plugin written in C++ -- which is the norm -- should use the grp_layer()/grp_expert()/grp_model() - * inline functions in `` instead: the installed spelling, which the plugins in - * radiance's own tree use as well. Same values, no extension. */ +/* Note: these are C compound literals, which C++ accepts only as a GNU extension. A C++ plugin + * should use the equivalent grp_layer()/grp_expert()/grp_model() inline functions in + * ``, as the in-tree plugins do. */ #define rad_group_layer(l) ((RadWeightGroup){ (int32_t)(l), -1, 0 }) #define rad_group_expert(l, e) ((RadWeightGroup){ (int32_t)(l), (int32_t)(e), 0 }) #define rad_group_model() ((RadWeightGroup){ -1, -1, 0 }) -/* The most projections one stored tensor may stack along dim 0. Five is what the bf16 delta net - * needs -- q, k, v, a, b in one row -- and eight leaves room without making the decl big. */ +/* The most projections one stored tensor may stack along dim 0. The bf16 delta net needs five + * (q, k, v, a, b); eight leaves room without making the decl big. */ enum { RAD_MAX_ROW_PARTS = 8 }; typedef struct RadWeightDecl { uint32_t dtype; /* what the kernel reads; the stored layout comes from the kernel */ uint32_t rank; - int64_t shape[RAD_MAX_RANK]; /* THIS RANK's extent of what `planes` select (below) */ + int64_t shape[RAD_MAX_RANK]; /* this rank's extent of what `planes` select (below) */ int access; /* RAD_ACCESS_* */ int shard; /* RAD_SHARD_* */ RadWeightGroup group; int optional; /* absent in the container is not an error */ - /* WHAT IS STACKED IN DIM 0, for a RAD_SHARD_ROW weight whose stored tensor is several - * projections concatenated -- [gate|up], or the delta net's [q|k|v]. Rows of THIS RANK, in - * stored order, summing to shape[0]; 0 parts means one part and dim 0 is one projection. + /* What is stacked in dim 0, for a RAD_SHARD_ROW weight whose stored tensor concatenates + * several projections ([gate|up], the delta net's [q|k|v]). Rows of this rank, in stored + * order, summing to shape[0]; 0 parts means dim 0 is one projection. * - * It exists because a tensor-parallel rank owns a slice of EACH stacked projection and not a - * contiguous slice of the stack. Taking rows [rank*D, (rank+1)*D) of a fused gate_up hands - * rank 0 the whole gate and rank 1 the whole up; both ranks then compute a perfectly - * well-formed wrong thing and the model produces fluent wrong text, which is the failure - * class spec §17 exists to prevent. The parts are NOT inferable from the container: it holds - * the fused result and not the shapes it was fused from, and a single checkpoint tensor may - * already be a fusion nothing in the name map mentions (in_proj_qkv is three head groups in - * one [10240, 5120]). The plugin is the only component that knows, so the plugin says. */ + * A tensor-parallel rank owns a slice of each stacked projection, not a contiguous slice of + * the stack: rows [rank*D, (rank+1)*D) of a fused gate_up would give rank 0 the whole gate and + * rank 1 the whole up, and the model would produce fluent wrong text (spec §9). The parts + * cannot be inferred from the container, which holds only the fused result, and a checkpoint + * tensor may already be a fusion the name map does not mention (in_proj_qkv is three head + * groups in one [10240, 5120]). Only the plugin knows them. */ int n_row_parts; int64_t row_parts[RAD_MAX_ROW_PARTS]; - /* WHICH STORED WEIGHT THIS IS A VIEW OF, AND WHICH OF ITS PLANES. spec.md §4.3. + /* Which stored weight this is a view of, and which of its planes. spec.md §4.3. * - * A container entry, or a checkpoint tensor, is a LOGICAL weight: the planes of its encoding - * (rad_encoding.h) -- a block-fp8 linear's codes and its scale plane are one weight, not two. - * A kernel takes them as whatever operands its schema has: gemm_nt_q takes the codes and the - * scales as two, the fp8 lm_head one operand holding both. So a declared weight names its - * `source` -- null for the logical weight of its own name -- and the `planes` it takes, by - * role, comma-separated: "codes", "scale", "codes,scale". Null takes every plane, which for a - * plain weight is its one. + * A container entry or checkpoint tensor is a logical weight: the planes of its encoding + * (rad_encoding.h). A block-fp8 linear's codes and scale plane are one weight, not two. A + * kernel takes them as whatever operands its schema has: gemm_nt_q takes codes and scales as + * two, the fp8 lm_head one operand holding both. So a declared weight names its `source` (null + * for the logical weight of its own name) and the `planes` it takes, by role, comma-separated: + * "codes", "scale", "codes,scale". Null takes every plane, which for a plain weight is one. * * One declared weight is one stored buffer. Its dtype and shape describe what is selected: a - * single plane's own dtype and extents, or, for several, the codes' dtype and the logical - * extents. A dtype other than the plane's is legal only as an exact widening -- a bf16 norm - * read as f32 -- which the loader performs; anything lossy is a quantiser's job and happens - * before a container is written. */ + * single plane's own dtype and extents, or for several, the codes' dtype and the logical + * extents. A dtype other than the plane's is legal only as an exact widening (a bf16 norm read + * as f32), which the loader performs; anything lossy is the quantiser's job, done before the + * container is written. */ const char* source; const char* planes; } RadWeightDecl; rad_weight rad_decl_weight(RadBuilder* b, const char* name, const RadWeightDecl* d); -/* WHAT A STORED WEIGHT IS: its encoding, and its logical extents in `shape` (RAD_MAX_RANK - * entries, may be null) with the rank returned in `rank` (may be null). RAD_OK, or RAD_E_NOTFOUND - * when the model has no such weight. +/* A stored weight's encoding, its logical extents in `shape` (RAD_MAX_RANK entries, may be null) + * and its rank in `rank` (may be null). RAD_OK, or RAD_E_NOTFOUND when the model has no such + * weight. * - * The answer comes from wherever the model is being loaded from -- a container's entry, a - * checkpoint's tensor, or, in rad-convert, the recipe that will quantise it -- so a plugin learns - * the same thing the same way at convert and at load, and chooses its ops by it: an fp8 GEMM for - * a block-fp8 weight, the rotated expert kernels for `i4*bf16[1x128]/fwht128`. Ask after the - * weight's name map entry (rad_decl_name_map), which is how a checkpoint is searched for it. A - * builder with no model behind it -- a test, a synthetic tool -- answers RAD_E_NOTFOUND, and a - * weight declared there is read as plain in its declared dtype. */ + * The answer comes from whatever the model is loaded from (a container entry, a checkpoint tensor, + * or in rad-convert the recipe that will quantise it), so a plugin chooses its ops the same way at + * convert and at load: an fp8 GEMM for a block-fp8 weight, the rotated expert kernels for + * `i4*bf16[1x128]/fwht128`. Ask after the weight's name map entry (rad_decl_name_map), which is how + * a checkpoint is searched for it. A builder with no model behind it (a test, a synthetic tool) + * answers RAD_E_NOTFOUND, and a weight declared there is read as plain in its declared dtype. */ int rad_weight_encoding(RadBuilder* b, const char* source, RadEncoding* out, int64_t* shape, uint32_t* rank); /* ================================================================== buffers */ -/* Activations are declared too, or the buffer plan has nothing to analyse. Liveness is computed - * over the declared op list, so scratch and intermediates come from one arena sized once instead - * of an allocator called per step (spec §3.1). */ +/* Activations are declared too, so the buffer plan can analyse them. Liveness is computed over the + * declared op list, so scratch and intermediates come from one arena sized once instead of an + * allocator called per step (spec §3.1). */ enum { RAD_BUF_TRANSIENT = 0, /* liveness-analysed, may share storage with another transient */ RAD_BUF_PERSIST = 1, /* survives across steps: a KV-adjacent scratch, a routing histogram */ @@ -262,14 +254,13 @@ typedef struct RadBufDecl { int kind; /* RAD_BUF_* */ int domain; /* RAD_DOMAIN_DEVICE or RAD_DOMAIN_HOST */ const char* derive; /* RAD_BUF_DERIVED: the derivation the core runs */ - /* WHICH KV GROUP A DERIVATION IS ABOUT, or 0 for "the only one of its kind". + /* The KV group a derivation is about, or 0 for the only one of its kind. * - * `conv_state_index` computes a read cursor inside a rolling window, which means it needs THAT - * GROUP's slot per sequence and THAT GROUP's window depth -- and a model may declare several. - * Qwen4-Exp's PLE layer has two conv states of different depths and dtypes beside the gated - * delta net's third. Leaving this 0 with more than one group of the kind a derivation reads is - * refused rather than guessed at: the wrong window's depth produces a plausible cursor and a - * convolution that reads history it never wrote. + * `conv_state_index` computes a read cursor inside a rolling window, so it needs that group's + * slot per sequence and window depth, and a model may declare several (Qwen4-Exp's PLE layer + * has two conv states of different depths and dtypes beside the gated delta net's). 0 with + * more than one group of the kind a derivation reads is refused: the wrong window depth gives + * a plausible cursor and a convolution that reads history it never wrote. * * Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */ rad_kvgroup kv; @@ -278,10 +269,10 @@ typedef struct RadBufDecl { rad_buf rad_decl_buffer(RadBuilder* b, const char* name, const RadBufDecl* d); /* ================================================================== KV groups */ -/* Each distinct state kind is a KV group with its own block geometry, its own pool, and its own - * slot mapping in the step batch. Linear-attention state is a KV group too: it is not paged the - * same way, but it is allocated, mapped and freed by the same manager, because otherwise two - * allocators disagree about what a sequence owns (spec §7.2). */ +/* Each distinct state kind is a KV group with its own block geometry, pool and slot mapping in the + * step batch. Linear-attention state is a KV group too: not paged the same way, but allocated, + * mapped and freed by the same manager, so there is one record of what a sequence owns + * (spec §7.2). */ enum { RAD_KV_FULL = 0, /* paged, per-token, growing -- full attention */ RAD_KV_WINDOW = 1, /* paged, per-token, bounded by the window */ @@ -297,10 +288,9 @@ typedef struct RadKVGroupDecl { int64_t head_dim; int64_t state_dim[2]; /* RAD_KV_LINEAR: the per-head state geometry, e.g. {128,128} */ int64_t conv_width; /* RAD_KV_CONV */ - /* Block size is NOT declared. It is taken off the resolved attention kernel's constraints at - * declare, because a core that picked its own would be a core that has to be edited when a - * kernel changes (spec §7.2). Read it back with rad_kv_block_size() after declaring the - * attention op that consumes this group. */ + /* Block size is not declared. It is taken from the resolved attention kernel's constraints at + * declare, so the core needs no edit when a kernel changes (spec §7.2). Read it back with + * rad_kv_block_size() after declaring the attention op that consumes this group. */ } RadKVGroupDecl; /* `rad_kvgroup` is in rad_types.h with the other handles -- RadBufDecl above carries one. */ @@ -312,9 +302,9 @@ int64_t rad_kv_block_size(RadBuilder* b, rad_kvgroup g); int rad_bind_layer_kv(RadBuilder* b, int layer, rad_kvgroup g); /* ================================================================== ops */ -/* Declared with their parameters and their weight operands. The core resolves each against the - * kernel hierarchy, per band, per domain. This phase ALWAYS completes; if anything failed to - * resolve, the full list is reported at the end rather than the first failure at the top. */ +/* Declared with their parameters and weight operands. The core resolves each against the kernel + * hierarchy, per band, per domain. This phase always completes, and every op that failed to + * resolve is reported together at the end. */ rad_op rad_decl_op(RadBuilder* b, const char* op, const RadParam* params, int n_params, const rad_weight* weights, int n_weights); @@ -332,89 +322,79 @@ rad_op rad_decl_op(RadBuilder* b, const char* op, #define RAD_NOWEIGHTS ((const rad_weight*)0), 0 #define RAD_OP(b, op, ...) rad_decl_op((b), (op), __VA_ARGS__) -/* An op's BUFFER operands, which rad_decl_op does not name -- it names weights, because those are - * what placement moves. But the buffer planner needs liveness, and liveness is exactly which ops - * read and write which buffers. Without these a transient has no declared use and must be assumed - * live for the whole program, which is sound (a plugin may issue any handle in any order) and as - * wasteful as it sounds; --debug-graph prints how many buffers fell into that case so the cost is - * never invisible. - * - * Separate from rad_decl_op rather than more arguments to it, because the common case is one call - * with one read set and one write set and the alternative is four more parameters on every - * declaration. */ +/* An op's buffer operands. rad_decl_op names only weights, which placement moves; the buffer + * planner needs liveness, i.e. which ops read and write which buffers. A transient with no + * declared use is assumed live for the whole program, which is sound (a plugin may issue any + * handle in any order) but wasteful; --debug-graph prints how many buffers fell into that case. + * Separate calls rather than four more parameters on every rad_decl_op. */ int rad_op_reads (RadBuilder* b, rad_op h, const rad_buf* bufs, int n); int rad_op_writes(RadBuilder* b, rad_op h, const rad_buf* bufs, int n); -/* A BUFFER THE ARCHITECTURE TOUCHES FROM THE SECOND LANE, which is the one case where the op - * range a buffer's declarations imply is NOT a bound on when its bytes are in use. +/* A buffer the architecture touches from the second lane, the one case where the op range a + * buffer's declarations imply does not bound when its bytes are in use. * - * The planner packs transients from ONE LINEAR ORDER (spec §3.1): two whose declared lives do not - * overlap share arena bytes. `rad_lane` breaks that assumption rather than the declarations -- - * lane 1's ops are issued at op indices that sit inside lane 0's, so a shared-arm scratch whose - * life is "ops 41..42" can be laid over a routed-arm scratch whose life is "ops 37..38", and on - * two streams those two runs OVERLAP IN TIME. Nothing downstream can tell: it reads as data. + * The planner packs transients from one linear order (spec §3.1): two whose declared lives do not + * overlap share arena bytes. `rad_lane` breaks that: lane 1's ops sit at op indices inside lane + * 0's, so a shared-arm scratch live over ops 41..42 can overlay a routed-arm scratch live over ops + * 37..38, and on two streams those runs overlap in time, corrupting data silently. * - * So a buffer named here is given the WHOLE PROGRAM, which is what a buffer with no declared use - * already gets and is sound for the same reason. It is deliberately per-buffer and not a mode: - * unsharing every buffer would cost ~220 MiB on a model this size, where the lane-1 transients - * of one block are a few MiB. Call it at declare, for every buffer the - * second lane reads or writes -- the ones lane 0 touches in the same window are covered by - * symmetry, since sharing needs both sides. + * A buffer named here is live for the whole program, like a buffer with no declared use. It is + * per-buffer rather than a mode because unsharing every buffer costs ~220 MiB on a large model, + * against a few MiB for one block's lane-1 transients. Call it at declare for every buffer the + * second lane reads or writes; the lane-0 buffers they could share with are covered, since + * sharing needs both sides. * - * Calling it for a PERSIST or DERIVED buffer is a no-op: those are live everywhere already. */ + * A no-op for a PERSIST or DERIVED buffer, which is live everywhere already. */ int rad_buf_concurrent(RadBuilder* b, rad_buf buf); -/* AN UNEVEN SHARD: this rank's slice of a RAD_SHARD_ROW or RAD_SHARD_COL weight's split dimension - * is [lo, hi) and not the even 1/tp of it -- rows of EACH stacked row part for ROW, columns for - * COL, in the container's (unsharded) units. The declared extent must already be `hi - lo` (each - * row part's, for ROW). +/* An uneven shard: this rank's slice of a RAD_SHARD_ROW or RAD_SHARD_COL weight's split dimension + * is [lo, hi) rather than an even 1/tp. Rows of each stacked row part for ROW, columns for COL, in + * the container's unsharded units. The declared extent must already be `hi - lo` (per row part, + * for ROW). * - * For a width that does not divide into equal whole blocks across the ranks: a 640-column - * projection with 128-column scale blocks is five blocks, which two ranks can split three and two - * but not in half. The stacked parts of a ROW weight must be equal in the container, since only - * the rank's own part sizes are declared. Refused by a container converted for more than one - * rank, whose entries are already even shares, and by a stored layout whose row runs or column - * groups the span would cut. */ + * For a width that does not divide into equal whole blocks across ranks: a 640-column projection + * with 128-column scale blocks is five blocks, split three and two. The stacked parts of a ROW + * weight must be equal in the container, since only the rank's own part sizes are declared. + * Refused for a container converted for more than one rank (its entries are already even shares) + * and for a stored layout whose row runs or column groups the span would cut. */ int rad_weight_shard_span(RadBuilder* b, rad_weight w, int64_t lo, int64_t hi); -/* A STACKED weight's span, ONE [lo, hi) PER ROW PART, with each part's whole extent in the - * container: the delta net's [q|k|v|z] is 2048, 2048, 6144, 6144 rows on Flash-Next, and parts - * that are not the same width cannot take rad_weight_shard_span's one span. `n` is the declared - * part count; part g of the container is `total[g]` rows, of which this rank takes [lo[g], hi[g]) - * and declared `hi[g] - lo[g]`; the totals must sum to the entry's rows. A rank's UNEVEN share of - * the heads -- 6 of 16 K heads where three ranks take 6, 5 and 5 -- is declared this way, and - * nothing is padded. Additive export: a plugin that does not call it declares as before. */ +/* A stacked weight's span, one [lo, hi) per row part, with each part's whole extent in the + * container, for parts of unequal width that rad_weight_shard_span's single span cannot express + * (the delta net's [q|k|v|z] is 2048, 2048, 6144, 6144 rows on Flash-Next). `n` is the declared + * part count; container part g is `total[g]` rows, of which this rank takes [lo[g], hi[g]) and + * declared `hi[g] - lo[g]`; the totals must sum to the entry's rows. An uneven share of the heads + * (6 of 16 K heads, with three ranks taking 6, 5 and 5) is declared this way, without padding. + * Additive export. */ int rad_weight_shard_span_parts(RadBuilder* b, rad_weight w, const int64_t* lo, const int64_t* hi, const int64_t* total, int n); -/* THIS RANK KEEPS NO CACHE FOR THE GROUP. The group is declared as on every other rank -- the +/* This rank keeps no cache for the group. The group is still declared as on every other rank (the * scheduler indexes groups by position and one block table serves every rank, so it must exist - * here with the same block size and layers -- and nothing is carved for it: it costs this rank no - * pool. It is for a rank the geometry gives no attention heads (rad_arch.h Geom::attn_zero), - * whose attention is a `fill` of zeros and never reads a key. No op on this rank may name the - * group as a RAD_KV operand after this; the engine refuses one at issue. Additive export. */ + * with the same block size and layers), but no pool is carved for it. For a rank the geometry + * gives no attention heads (rad_arch.h Geom::attn_zero), whose attention is a `fill` of zeros. + * After this, no op on this rank may name the group as a RAD_KV operand; the engine refuses one + * at issue. Additive export. */ int rad_kv_group_zero(RadBuilder* b, rad_kvgroup g); #define RAD_BUFS(...) ((const rad_buf[]){ __VA_ARGS__ }), \ (int)(sizeof((const rad_buf[]){ __VA_ARGS__ }) / sizeof(rad_buf)) /* Did the last rad_decl_op resolve? A plugin asks for the fused op first and emits the unfused - * sequence when it does not, which is what makes fusion a selection rather than a compiler pass - * (spec §2.3). A handle that did not resolve is RAD_NULL_HANDLE and is NOT an error yet -- it - * becomes one only if the plugin issues it. */ + * sequence when it does not, which makes fusion a selection rather than a compiler pass + * (spec §2.3). An unresolved handle is RAD_NULL_HANDLE and becomes an error only if issued. */ int rad_op_resolved(RadBuilder* b, rad_op h); -/* Does a loaded kernel library declare op `op` -- is it in the vocabulary at all? Declaring an op - * nobody declares is an error, because that is what a misspelt name looks like; an op that is - * declared and only resolved to no kernel is not (rad_op_resolved). A plugin asks this first for a - * fused op that only an optional library defines, and emits the chain when the answer is 0. - * Additive export. */ +/* Does any loaded kernel library declare op `op`? Declaring an op outside the vocabulary is an + * error, since that is what a misspelt name looks like; an op that is declared but resolves to no + * kernel is not (rad_op_resolved). A plugin asks this first for a fused op only an optional + * library defines, and emits the chain when the answer is 0. Additive export. */ int rad_op_declared(RadBuilder* b, const char* op); /* ================================================================== checkpoint name map */ /* The plugin owns the map from checkpoint tensor names to declared weight names, including - * convert-time fusions -- q/k/v into a single qkv, gate and up into gate_up. It is the only - * component that knows both sides, and rad-convert reads the map from it (spec §2.4). */ + * convert-time fusions (q/k/v into one qkv, gate and up into gate_up). It is the only component + * that knows both sides, and rad-convert reads the map from it (spec §2.4). */ enum { RAD_MAP_COPY = 0, RAD_MAP_CONCAT = 1 }; typedef struct RadNameMap { @@ -426,86 +406,65 @@ typedef struct RadNameMap { /* A sub-tensor index within src[i], or -1 for the whole tensor. GGUF stores a MoE layer's * experts stacked as one ffn_gate_exps of shape [.., n_expert], while placement needs one - * declared weight per expert -- the movement unit is an expert, not a tensor. Without this - * the expert index survives only inside the declared NAME, which is an unwritten convention - * rad-convert would have to parse. */ + * declared weight per expert; this carries the expert index so rad-convert need not parse it + * out of the declared name. */ int src_index[8]; } RadNameMap; -/* RAD_MAP_COPY with n_src > 1 means FIRST SOURCE PRESENT IN THE CONTAINER WINS. That is how a - * tied lm_head is expressed -- output.weight if the checkpoint has one, else token_embd.weight -- - * and without it a model family whose members differ only in tying needs two plugins. - * RAD_MAP_CONCAT with n_src > 1 concatenates all of them along concat_dim and requires every one. */ +/* RAD_MAP_COPY with n_src > 1: the first source present in the container wins. This expresses a + * tied lm_head (output.weight if present, else token_embd.weight), so one plugin covers family + * members that differ only in tying. RAD_MAP_CONCAT with n_src > 1 concatenates all sources along + * concat_dim and requires every one. */ int rad_decl_name_map(RadBuilder* b, const RadNameMap* m); /* ================================================================== the step's output */ -/* WHICH BUFFER HOLDS THIS STEP'S LOGITS. The core samples from it -- the sampler chain is core - * logic and its ops resolve through the same hierarchy at the same time as the plugin's (spec - * §13) -- so the core has to be told which buffer that is, and the plugin is the only one who - * knows. +/* Which buffer holds this step's logits. The core samples from it (the sampler chain is core logic + * whose ops resolve through the same hierarchy as the plugin's, spec §13), and only the plugin + * knows which buffer it is. A name match would be wrong: a drafter or encoder tower declares into + * a scope (RadBuildCtx::scope, spec §10, §11), so "the buffer called logits" can be two buffers in + * one Program. * - * A name convention would do it and is wrong: a drafter or an encoder tower declares into a SCOPE - * (RadBuildCtx::scope, spec §10, §11), so "the buffer called logits" is two different buffers in - * one Program and matching on the string would sample the draft model's distribution into the - * target's tokens. It is one call and it removes a string match from startup. + * Its extent along dim 0 bounds RadBatch::n_out: one row per sampled position, not per token of + * the step. Declaring it [max_tok, n_vocab] is legal but, at a 248K vocabulary, 8 GiB. * - * Its extent along dim 0 bounds RadBatch::n_out: the buffer holds one row per sampled position, - * not one per token of the step. Declaring it [max_tok, n_vocab] is legal and, at a 248K - * vocabulary, 8 GiB. - * - * A Program with no logits buffer cannot serve, and the engine says so at startup rather than at - * the first step. An embedding-only or encoder-only plugin declares none, deliberately. */ + * A Program with no logits buffer cannot serve, and the engine says so at startup. An + * embedding-only or encoder-only plugin declares none. */ int rad_declare_logits(RadBuilder* b, rad_buf logits); -/* WHICH BUFFER HOLDS THIS STEP'S POOLED VECTORS: what an EMBEDDING model returns instead of logits, - * one row a sequence of the step -- row s is sequence s's whole input pooled into one vector, - * whatever pooling the model was trained with (a mean, the last token, a CLS row). The core reads - * rows [0, n_seq) back after the step and hands each to its request; it does not normalise them, - * because that is the API's choice and not the model's. +/* Which buffer holds this step's pooled vectors, what an embedding model returns instead of + * logits. Row s is sequence s's whole input pooled into one vector, with whatever pooling the + * model was trained with (a mean, the last token, a CLS row). The core reads rows [0, n_seq) back + * after the step and hands each to its request. It does not normalise them; that is the API's + * choice, not the model's. * - * DECLARING IT MAKES THE PROGRAM AN EMBEDDING PROGRAM, and that changes what a step is: + * Declaring it makes the Program an embedding program: + * - every sequence in a step is a whole input. The scheduler never splits one across steps, + * since a bidirectional encoder cannot be fed half its input, and refuses an input longer + * than one step rather than truncating it; + * - there is no sampler, drafter or prefix cache, and nothing is generated: a request ends at + * the step that carried it. * - * - every sequence in a step is a WHOLE input. The scheduler never splits one across steps, - * because an encoder that attends both ways cannot be fed half of its input, and it refuses - * an input longer than one step's tokens rather than truncating it; - * - there is no sampler, no drafter and no prefix cache, and nothing is generated: a request - * ends at the step that carried it. - * - * f32, device, [>= max_seqs, dim]: `dim` is the vector's width and the extent the core reads. A - * Program declares this or logits, never both -- a model that both generates and embeds is two - * deployments. */ + * f32, device, [>= max_seqs, dim]: `dim` is the vector width the core reads. A Program declares + * this or logits, never both. */ int rad_declare_pooled(RadBuilder* b, rad_buf pooled); /* ================================================================== the drafter */ -/* WHAT THE PLUGIN'S DRAFT HEAD IS, declared the same way and for the same reason the logits - * buffer above is: the core drives the extra passes, so it has to be told what it is driving, - * and the plugin is the only one who knows. +/* The plugin's draft head. The core drives the extra passes, and only the plugin knows what it + * is, so it is declared rather than detected from weight names (`mtp.fc.weight`) with the core + * re-reading the drafter's configuration keys the plugin already read. * - * IT REPLACES A WEIGHT-NAME MATCH. The alternative is for the engine to decide whether a - * container drafts by scanning the declared weights for names like `mtp.fc.weight` or - * `dflash.fc.weight`, and then to re-read the drafter's own configuration keys -- block size, - * mask token, sliding window, predicted-layer count -- every one of them a key the plugin has - * already read to build the thing. Two readers of one fact is two places for it to disagree, and - * the second reader would be the core, which is the one that must not know. + * The kind is a drive shape, not a model. SERIAL runs `depth` dependent passes, each embedding the + * last one's proposal, so tokens arrive one at a time and a pass that declines ends the chain + * (MTP, EAGLE, Medusa-serial). BLOCK runs a context pass, then one pass that fills every drafted + * position at once (DFlash2 and other block-diffusion drafters). * - * KIND IS A SHAPE, NOT A MODEL. There are two ways a draft head can be driven and the difference - * is visible from outside it: SERIAL runs `depth` dependent passes, each embedding what the last - * one proposed, so the tokens arrive one at a time and a pass that declines ends the chain. - * BLOCK runs a context pass and then ONE pass that fills every drafted position at once. MTP, - * EAGLE and Medusa-serial are all SERIAL; DFlash2 and any other block-diffusion drafter is - * BLOCK. A plugin picks the shape that describes it and needs no core change to do it. + * `proposal` is the buffer a pass writes its token ids into; 0 means the sampler's token buffer, + * which suits a head whose logits go through the ordinary sampler chain. * - * `proposal` is the buffer a pass writes its token ids into, and 0 means "the sampler's token - * buffer" -- which is what a head whose logits go through the ordinary sampler chain wants. A - * by-name lookup cannot supply this field: it would have to suffix-match a name that is not - * unique in the Program, in exactly the way the comment above rad_declare_logits explains is - * wrong -- a drafter declares into its own scope. - * - * A plugin that declares no drafter is not an error and is the normal case; the scheduler's - * prompt-lookup drafter still runs. */ + * Declaring no drafter is the normal case; the scheduler's prompt-lookup drafter still runs. */ typedef enum { RAD_DRAFT_NONE = 0, RAD_DRAFT_SERIAL = 1, /* `depth` dependent passes, one proposal each */ @@ -521,77 +480,67 @@ typedef struct RadDrafterDecl { rad_buf proposal; int64_t proposal_pitch; /* elements a row in `proposal`; 0 means 1 */ - /* BLOCK only. `mask_token` is the id every unfilled position of the block embeds, and a - * block drafter without one has nothing to run. `window` is the drafter's OWN sliding - * window over its OWN cache, 0 for unbounded -- the core stages the block pass against it, - * so it must be the same number the plugin gated its attention with. */ + /* BLOCK only. `mask_token` is the id every unfilled block position embeds; a block drafter + * without one cannot run. `window` is the drafter's own sliding window over its own cache, 0 + * for unbounded. The core stages the block pass against it, so it must match the window the + * plugin gated its attention with. */ int32_t mask_token; int64_t window; - /* BLOCK only: HOW MANY ROWS THE QUERY PASS RUNS OVER, one sequence's worth. 0 means - * `depth + 1`. + /* BLOCK only: how many rows the query pass runs over, per sequence. 0 means `depth + 1`. * - * IT IS NOT ALWAYS depth + 1, AND THE DIFFERENCE IS A ROW ALIGNMENT. The core stages the - * block as an anchor -- the token the sampler just chose -- followed by `block - 1` copies of - * `mask_token`, and THE HEAD RUNS OVER THE LAST `depth` ROWS. That one rule covers both - * conventions a block-diffusion drafter can be trained in: + * The core stages the block as an anchor (the token the sampler just chose) followed by + * `block - 1` copies of `mask_token`, and the head runs over the last `depth` rows. That covers + * both training conventions: * - * block = depth + 1 the anchor row predicts NOTHING and each mask row predicts the token - * at ITS OWN position. The head sees rows 1..depth. DFlash2. - * block = depth every row predicts the token at the position AFTER it, the anchor - * row included -- the ordinary next-token relation, so the anchor is - * not a wasted row. The head sees rows 0..depth-1. DSpark, whose - * reference takes `hidden[:, -block_size:, :]` over exactly this. + * block = depth + 1 the anchor row predicts nothing; each mask row predicts the token at + * its own position. The head sees rows 1..depth. DFlash2. + * block = depth every row, the anchor included, predicts the token at the next + * position (the ordinary next-token relation). The head sees rows + * 0..depth-1. DSpark, whose reference takes `hidden[:, -block_size:, :]`. * - * GETTING IT WRONG IS INVISIBLE FROM THE OUTSIDE. Both values run, both produce `depth` - * tokens, and the model's own output stays exactly correct because every draft is verified; - * what happens instead is that the proposals are shifted by one position and acceptance - * collapses to roughly the rate of chance. That is why this is declared by the plugin that - * knows how its checkpoint was trained, and not inferred here. */ + * A wrong value is not visible in the output: both run, every draft is verified so the text + * stays correct, but the proposals shift by one position and acceptance drops to about chance. + * Hence it is declared by the plugin, which knows how the checkpoint was trained. */ int64_t block; } RadDrafterDecl; int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d); -/* A SERIAL HEAD WITH NO CACHE OF ITS OWN. Every attention layer of it reads one of the TRUNK's - * layers' K and V and writes none -- Gemma 4's assistant head, whose layers have a query - * projection and nothing else, reads the last sliding and the last global trunk layer. Called - * once, after rad_declare_drafter, by a plugin whose serial head is that shape. Additive export: a - * plugin that does not call it drafts exactly as before, and RAD_ABI_VERSION does not move. +/* A serial head with no cache of its own: each of its attention layers reads one trunk layer's K + * and V and writes none. Gemma 4's assistant head, whose layers have only a query projection, + * reads the last sliding and last global trunk layer. Called once, after rad_declare_drafter. + * Additive export; RAD_ABI_VERSION does not move. * - * What it changes in the serial driver, and each item follows from the head writing nothing: + * Effect on the serial driver, all following from the head writing nothing: * - * NO HISTORY IS OWED. A history pass exists to fill a head's own K and V, and there are none to - * fill. The pass carries round 1 alone: ONE row a drafting sequence, at the committed position, - * with the token the trunk chose after it and the trunk's hidden state there (out_ids). A - * sequence that does not draft gets no row, and a step with nothing to draft no pass. + * No history pass, since there is no K and V of its own to fill. The pass carries round 1 + * alone: one row per drafting sequence, at the committed position, with the token the trunk + * chose after it and the trunk's hidden state there (out_ids). A sequence that does not draft + * gets no row, and a step with nothing to draft no pass. * - * EVERY ROUND RUNS AT THAT SAME POSITION, OVER THE SAME CONTEXT. A head with a cache of its own - * steps one position a round and attends to what it wrote there. This one has nowhere to write, - * and the trunk's cache past the committed position holds the K and V of drafts the last verify - * REJECTED, or of nothing. So every round's `seqused` ends at the committed position, and what - * the head proposed travels forward in its hidden state and its next input token instead. + * Every round runs at that same position over the same context. The trunk's cache past the + * committed position holds K and V of drafts the last verify rejected, or nothing, so every + * round's `seqused` ends at the committed position; the head's proposals travel forward in its + * hidden state and next input token instead. * - * `pos_offset` is where those rows sit for the rotary, as an offset from the committed position: - * 0 is the position of the trunk hidden state the head continues from, 1 the position of the token - * it embeds. It moves nothing else -- the context ends at the committed position either way -- and - * which one a checkpoint was trained with is the plugin's to know. */ + * `pos_offset` is the rotary position of those rows relative to the committed position: 0 is the + * position of the trunk hidden state the head continues from, 1 that of the token it embeds. It + * moves nothing else (the context ends at the committed position either way), and which one a + * checkpoint was trained with is the plugin's to know. */ int rad_drafter_shared_kv(RadBuilder* b, int pos_offset); /* ================================================================== the encoder */ -/* A MEDIA ENCODER THE PLUGIN RUNS ON AN ENCODER PASS (RadBatch::enc), declared for the reason the - * logits buffer and the drafter are: the core drives the pass and reads its result, so it has to - * be told what it is driving, and only the plugin knows. A plugin that declares none serves text, - * and the server refuses a media part by name. +/* A media encoder the plugin runs on an encoder pass (RadBatch::enc). The core drives the pass and + * reads its result, so the plugin declares it. A plugin that declares none serves text only, and + * the server refuses a media part by name. * - * WHAT IS HERE IS THE SHAPE OF THE INTERFACE, NOT THE MODEL. The core stages patches of - * `patch_dim` elements and reads back one `n_embd`-wide row for every `merge` of them; what turns - * the one into the other -- the tower's depth, its attention, its position scheme -- is the - * plugin's business and appears nowhere in the core. How an image or a video becomes patches is - * the processor's (core/mm), which reads its geometry from the container: the two agree through - * `patch_dim` and `merge`, and the core refuses a program whose encoder disagrees with the - * processor about either. */ -/* A PROGRAM DECLARES AT MOST TWO: one serving images and video, one serving audio. An audio + * This is the shape of the interface, not the model. The core stages patches of `patch_dim` + * elements and reads back one `n_embd`-wide row per `merge` of them; the tower itself is the + * plugin's business. How an image or video becomes patches is the processor's (core/mm), which + * reads its geometry from the container; the core refuses a program whose encoder disagrees with + * the processor about `patch_dim` or `merge`. */ +/* A program declares at most two: one serving images and video, one serving audio. An audio * encoder's "patch" is one feature frame (a mel row), its `merge` is frames per output row, and * its `max_patches` is RadBuildCtx::max_audio_frames. RadBatch::enc names which one a pass runs. */ enum { @@ -616,30 +565,29 @@ typedef struct RadEncoderDecl { int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d); /* ================================================================== the image generator */ -/* A PROGRAM THAT MAKES IMAGES: a conditioning network that reads a prompt (and pictures), a - * denoiser that turns a latent from noise into an image's latent over a number of steps, and a - * decoder that turns the latent into pixels. Declared for the reason the logits buffer is: the - * core drives the passes, so it has to be told what it is driving, and only the plugin knows. +/* A program that makes images: a conditioning network reads a prompt (and pictures), a denoiser + * turns a noise latent into an image latent over a number of steps, and a decoder turns the + * latent into pixels. The core drives the passes, so the plugin declares them. * - * DECLARING ONE MAKES THE PROGRAM A GENERATOR, and a generator is driven by passes rather than by - * token steps (RadBatch::gen): + * Declaring one makes the program a generator, driven by passes rather than token steps + * (RadBatch::gen): * - * RAD_GEN_PASS_COND one conditioning sequence -- the prompt, and any reference pictures -- - * encoded into the generator's KV group. Read once per request (twice - * with guidance: the negative prompt is a sequence of its own). - * RAD_GEN_PASS_DENOISE one step of every image in flight that the pass carries: each image's - * latent rows, read from and written back to the plugin's own state at the - * image's lane, against its conditioning's KV. + * RAD_GEN_PASS_COND one conditioning sequence (the prompt and any reference pictures) + * encoded into the generator's KV group. Once per request, twice with + * guidance (the negative prompt is its own sequence). + * RAD_GEN_PASS_DENOISE one step of every image the pass carries: each image's latent rows, + * read from and written back to the plugin's state at the image's lane, + * against its conditioning's KV. * RAD_GEN_PASS_DECODE one image's latent to pixels, in `image_out`, which the core reads back. * - * A program declares this, logits or pooled vectors -- one of the three. + * A program declares exactly one of this, logits or pooled vectors. * - * WHAT IS HERE IS THE MODEL'S CONTRACT WITH A CLIENT: the prompt it was trained on, the sizes it - * makes, the schedule its sampler follows. The core turns a request into passes with it and - * nothing in the core names a model. */ + * The fields are the model's contract with a client: the prompt it was trained on, the sizes it + * makes, its sampler's schedule. The core turns a request into passes from them without naming + * any model. */ enum { RAD_GEN_PASS_COND = 1, RAD_GEN_PASS_DENOISE = 2, RAD_GEN_PASS_DECODE = 3 }; -/* HOW THE GENERATOR'S SEQUENCE IS LAID OUT, which the core builds from the conditioning prompt. +/* How the generator's sequence is laid out; the core builds it from the conditioning prompt. * * JOINT_GRID the prompt's rows after `drop_prefix`, each media slot standing for `slot_rows` * rows that a reference picture's latent tokens take in raster order, then the @@ -654,32 +602,31 @@ typedef struct RadGeneratorDecl { const char* name; /* "qwen-image" -- for messages */ int32_t layout; /* RAD_GEN_LAYOUT_* */ - /* THE CONDITIONING PROMPT, as text the core tokenises. `{prompt}` is replaced by the user's - * prompt; in `tmpl_edit`, `{images}` by one `tmpl_image` for each reference picture, joined by - * `tmpl_image_sep`. In `tmpl_image`, `{n}` is the picture's 1-based number and `{image}` where - * the picture's own tokens go -- the run the media processor makes of it, its markers - * included. */ + /* The conditioning prompt, as text the core tokenises. `{prompt}` is replaced by the user's + * prompt; in `tmpl_edit`, `{images}` by one `tmpl_image` per reference picture, joined by + * `tmpl_image_sep`. In `tmpl_image`, `{n}` is the picture's 1-based number and `{image}` marks + * where the picture's own tokens go (the media processor's run for it, markers included). */ const char* tmpl_text; const char* tmpl_edit; const char* tmpl_image; const char* tmpl_image_sep; - /* The tokens this text tokenises to at the start of the prompt are ENCODED but not handed to - * the generator: the conditioning starts after them (a fixed system turn, say). */ + /* The tokens of this text at the start of the prompt are encoded but not handed to the + * generator; the conditioning starts after them (e.g. a fixed system turn). */ const char* drop_prefix; - /* A TRANSPARENT IMAGE, asked for in the words the model was trained on: `{prompt}` is the + /* Prompt for a transparent image, in the words the model was trained on; `{prompt}` is the * user's description. Empty when the model makes no alpha. */ const char* tmpl_transparent; - /* GEOMETRY. One latent token covers `latent_scale` x `latent_scale` pixels and holds + /* Geometry. One latent token covers `latent_scale` x `latent_scale` pixels and holds * `latent_channels` values; a side is a multiple of `size_multiple` pixels; an image has - * `pixel_channels` channels (4: RGBA). A media slot of the conditioning prompt -- one - * encoder output row -- stands for `slot_rows` rows of the generator's sequence. */ + * `pixel_channels` channels (4: RGBA). A media slot of the conditioning prompt (one encoder + * output row) stands for `slot_rows` rows of the generator's sequence. */ int64_t latent_channels; int64_t latent_scale; int64_t size_multiple; int64_t pixel_channels; int64_t slot_rows; - /* The largest image, in latent tokens: every buffer the plugin sized for one image. */ + /* The largest image, in latent tokens; the plugin sizes its per-image buffers for it. */ int64_t max_tokens; /* Reference pictures: at most `max_refs` a request, each resized to `ref_area` pixels. */ int64_t max_refs; @@ -687,8 +634,8 @@ typedef struct RadGeneratorDecl { /* The size a request that names none is made at. */ int64_t default_width, default_height; - /* THE SAMPLER: flow matching, an Euler step from sigma 1 towards 0. - * A FIXED SCHEDULE: `n_sigmas` values, the terminal 0 implied; a request may not change the + /* The sampler: flow matching, Euler steps from sigma 1 towards 0. + * A fixed schedule: `n_sigmas` values, the terminal 0 implied; a request may not change the * step count. Otherwise `default_steps` sigmas from 1 to 1/steps, shifted: * dyn_shift 0 sigma' = shift * s / (1 + (shift - 1) * s) * dyn_shift 1 mu linear in the image's token count, 256 -> base_shift .. max_seq -> @@ -706,9 +653,9 @@ typedef struct RadGeneratorDecl { /* Guidance a request gets when it names none; 1 is off. */ double default_cfg; - /* WHERE THINGS ARE. `max_lanes` images may be in flight at once, each in a lane of the - * plugin's own state; `image_out` is [max_tokens * latent_scale^2, pixel_channels] u8 on the - * device, row-major pixels of the image a decode pass made. */ + /* `max_lanes` images may be in flight at once, each in a lane of the plugin's own state. + * `image_out` is [max_tokens * latent_scale^2, pixel_channels] u8 on the device: row-major + * pixels of the image a decode pass made. */ int64_t max_lanes; rad_buf image_out; } RadGeneratorDecl; @@ -722,92 +669,78 @@ void rad_note(RadBuilder* b, const char* fmt, ...); /* ================================================================== the arch plugin exports */ const char* rad_arch_id(void); -/* THE QUANTISATION THIS PLUGIN SERVES, and the second half of the key that selects it. +/* The quantisation this plugin serves: the second half of the key that selects it. * * spec §2.4 is one plugin per (architecture, quantisation): a w4a8 model wants - * rmsnorm_had_quant_i8 where a bf16 model wants a plain rmsnorm, and a plugin full of branches on - * a quant descriptor is how you get back to "unclear what actually runs". So `qwen35_bf16` and - * `qwen35_fp8` both answer "qwen35" to rad_arch_id and are told apart HERE, by the string the - * container already carries in RadModelMeta::quant. + * rmsnorm_had_quant_i8 where a bf16 model wants a plain rmsnorm, and branching on a quant + * descriptor inside one plugin obscures what actually runs. So `qwen35_bf16` and `qwen35_fp8` both + * answer "qwen35" to rad_arch_id and are told apart here, by RadModelMeta::quant. * - * The match is EXACT and there is no fallback. An unquantised container and an unquantised plugin - * both say "" -- the symbol is optional and a plugin that does not export it is read as "". - * Falling back from a quantised container to a plugin that declares dense weights would fail - * later, at the name map, with a worse message than "no plugin claims qwen35 at fp8_e4m3; qwen35 - * is served at: (unquantised)". */ + * The match is exact, with no fallback. Unquantised containers and plugins both say ""; the + * symbol is optional and a plugin without it reads as "". A fallback to a dense plugin would fail + * later at the name map with a worse message than "no plugin claims qwen35 at fp8_e4m3; qwen35 is + * served at: (unquantised)". */ const char* rad_arch_quant(void); -/* WHAT THE PLUGIN CAN SAY BEFORE IT DECLARES ANYTHING. OPTIONAL: a plugin that does not export - * it answers every question with the zero, which is each field's default. +/* What the plugin can say before it declares anything. Optional: a plugin that does not export + * it answers zero to everything, each field's default. * - * It exists for the ONE fact that is an INPUT to declaration and a property of the model: - * the draft depth. `RadBuildCtx::max_spec` sizes buffers, bands kernels and sets the scheduler's - * window, so it must be fixed before rad_arch_declare runs -- but "how deep does this container's - * drafter want to go" is answerable only by reading the drafter's own configuration, which is the - * plugin's job. The alternative is a core that reads those keys itself, by name, with an - * architecture's own prefix in the string. + * The main case is the draft depth, a model property that is an input to declaration: + * `RadBuildCtx::max_spec` sizes buffers, bands kernels and sets the scheduler's window, so it is + * fixed before rad_arch_declare runs, yet only the plugin reads the drafter's configuration. 0 + * means the container carries no drafter. * - * A serial head names a THROUGHPUT TRADE-OFF: more rounds cost a pass each and acceptance decays, - * so the number is measured, not derived. A block drafter names the block length ITS CHECKPOINT - * WAS TRAINED AT, and asking for anything else is a silently worse draft. Both are the plugin's - * to know. 0 means "this container carries no drafter", which is the right answer to "speculate - * as deeply as this model can" on a model that cannot. - * - * --num-speculative-tokens overrides whatever comes back, and the plugin sees the result in - * RadBuildCtx::max_spec; a plugin whose checkpoint cannot serve that depth refuses in declare, - * where it has the whole configuration in front of it. */ + * --num-speculative-tokens overrides the answer, and the plugin sees the result in + * RadBuildCtx::max_spec; a plugin whose checkpoint cannot serve that depth refuses in declare. */ typedef struct RadArchProbe { int draft_depth; - /* WHETHER THAT DEPTH IS THE ONLY ONE THE DRAFTER SERVES, and the two callers of this need - * different answers. A SERIAL head names a throughput trade-off: more passes cost one each - * and acceptance decays, so the depth it reports is an operating point and one more pass - * still runs. A BLOCK drafter - * names the block length its checkpoint was TRAINED at -- its convolution masks the position - * within that block -- so any other depth is not a shorter proposal, it is a refusal. + /* Nonzero when `draft_depth` is the only depth the drafter serves. A serial head's depth is a + * throughput operating point (each extra pass costs one pass and acceptance decays, but it + * still runs). A block drafter's depth is the block length its checkpoint was trained at (its + * convolution masks the position within the block), so any other depth is refused. * - * `--num-speculative-tokens auto` takes `draft_depth` either way; it is choosing an operating - * point. rad-convert must not: a CONTAINER carries what the model can serve, so narrowing it - * to a serial head's preferred depth would mean a deployment asking for one more had to - * convert again. It widens to `draft_depth` only when this says the drafter has no choice. */ + * `--num-speculative-tokens auto` takes `draft_depth` either way. rad-convert does not: a + * container carries everything the model can serve, so it widens to `draft_depth` only when + * this says the drafter has no choice; otherwise a deployment wanting a deeper serial draft + * would have to convert again. */ int draft_depth_fixed; - /* THE PLUGIN HONOURS RadBuildCtx::shape_probe: a sizing declare leaves the state its step - * function reads untouched. Zero -- what a plugin that never heard of it leaves -- means the - * core does not ask, and the activation arena is not lent. */ + /* The plugin honours RadBuildCtx::shape_probe: a sizing declare leaves the state its step + * function reads untouched. Zero means the core does not ask, and the activation arena is not + * lent. */ int shape_probe_ok; - /* THE ENCODER'S MERGE: input patches a output row (RadEncoderDecl::merge), when the plugin + /* The encoder's merge, input patches per output row (RadEncoderDecl::merge), when the plugin * declares an encoder. A pass carries whole output rows, so the core rounds the pass size it - * picks itself (`--mm-max-patches auto`) down to a multiple of this; a size the operator - * names is the operator's, and a plugin refuses one that does not divide. 0 is no opinion. */ + * picks itself (`--mm-max-patches auto`) down to a multiple of this; an operator-named size is + * kept, and the plugin refuses one that does not divide. 0 is no opinion. */ int64_t enc_merge; - /* THE LONGEST AUDIO CLIP THE PLUGIN'S AUDIO ENCODER TAKES, in feature frames (a whole - * number of its merge), when it declares one: the engine sizes the audio pass with it - * (RadBuildCtx::max_audio_frames). 0 is no audio. */ + /* The longest clip the audio encoder takes, in feature frames (a whole number of its merge); + * the engine sizes the audio pass with it (RadBuildCtx::max_audio_frames). 0 is no audio. */ int64_t audio_frames; - /* AN IMAGE GENERATOR (rad_declare_generator), and the rows its largest pass carries: the - * engine sizes the step for it before declare -- a denoise pass carries an image's every - * latent row at once, twice with guidance -- and turns off what a generator has no use for. - * 0 is a program that generates text or embeds. */ + /* Nonzero for an image generator (rad_declare_generator): the rows its largest pass carries. + * The engine sizes the step for it before declare (a denoise pass carries all of an image's + * latent rows at once, twice with guidance) and turns off what a generator does not use. 0 is + * a program that generates text or embeds. */ int64_t gen_rows; - /* ...and the patches its conditioning pass encodes at most: every reference picture a request - * may carry, at the size the model resizes them to. The encoder's pass size (max_enc_patches). */ + /* The most patches the generator's conditioning pass encodes: every reference picture a + * request may carry, at the model's resize target. This is the encoder's pass size + * (max_enc_patches). */ int64_t gen_patches; } RadArchProbe; int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out); -/* HOW THIS MODEL SPELLS A TURN, AS DATA. OPTIONAL: a plugin that does not export it leaves the - * engine to derive the format by analysing the chat template. +/* How this model spells a turn, as data. Optional: without it the engine derives the format by + * analysing the chat template. * - * A reply is read back into reasoning, content and tool calls by one streaming parser driven by - * this description, and the lazy grammar that constrains a call and the literal words that - * trigger it are generated from it too -- so a model whose format the template analysis cannot - * find, or finds wrongly, is supported by stating the format here once. What it describes is the - * tagged family: + * One streaming parser driven by this description splits a reply into reasoning, content and tool + * calls, and the lazy grammar that constrains a call and its trigger words are generated from it, + * so a model whose format the template analysis misses or gets wrong is supported by stating it + * here. It describes the tagged family: * * [reasoning_open] reasoning [reasoning_close] content * [call_open] name_prefix NAME name_suffix @@ -820,7 +753,7 @@ int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out); * UTF-8; NULL reads as "". The engine copies what it needs while loading, so static storage in * the plugin is enough. * - * The other family is a call written as a name and ONE object holding its arguments + * The other family is a call written as a name and one object holding its arguments * (args_form = RAD_CHAT_ARGS_OBJECT): * * [call_open] name_prefix NAME name_suffix { key: value, ... } [call_end] [call_close] @@ -832,13 +765,11 @@ int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out); * arguments are that object respelled as JSON. The arg_* fields describe tagged arguments only * and are empty in this family. * - * THE STRUCT GROWS AT ITS END AND NEVER CHANGES IN THE MIDDLE. `struct_size` is - * sizeof(RadChatFormat) as the plugin was compiled; the engine reads only the fields that size - * covers and treats the rest as zero, so a plugin built against an older header keeps loading - * and a field added later is appended with a zero that means "as before". That is why this - * export does not move RAD_ABI_VERSION: it is additive, and a plugin that lacks it or predates a - * field is read correctly. A change that is NOT additive -- a field reordered, retyped or - * removed -- is a layout change and bumps RAD_ABI_VERSION like any other. */ + * The struct only grows at its end. `struct_size` is sizeof(RadChatFormat) as the plugin was + * compiled; the engine reads only the fields that size covers and treats the rest as zero, so a + * plugin built against an older header keeps loading, and a new field must make zero mean "as + * before". So this export does not move RAD_ABI_VERSION. A field reordered, retyped or removed is + * a layout change and bumps RAD_ABI_VERSION like any other. */ enum { RAD_CHAT_VALUE_RAW = 0, /* the text between the delimiters, verbatim */ RAD_CHAT_VALUE_CDATA = 1, /* verbatim, unless wrapped in , which is removed */ @@ -870,9 +801,9 @@ typedef struct RadChatFormat { uint32_t n_reasoning_breaks; uint32_t reasoning_in_prompt; /* RAD_CHAT_THINK_* */ - /* Around ALL of a turn's calls, and between two calls beyond whitespace. The parser does not - * read either yet, so a format that needs one is refused at startup by name; they are fields - * so that supporting them does not change the struct. */ + /* Around all of a turn's calls, and between two calls beyond whitespace. The parser does not + * read these yet, so a format that sets one is refused at startup by name; they are fields so + * supporting them later does not change the struct. */ const char* section_open; const char* section_close; const char* call_separator; @@ -910,15 +841,65 @@ typedef struct RadChatFormat { /* RAD_CHAT_ARGS_OBJECT: non-zero when the dialect writes a key bare, `key:value`. */ uint32_t object_bare_keys; - /* Non-zero: a reasoning block may open again LATER in the reply -- after its answer, between - * calls -- and is read as reasoning there as well, and a reasoning_close with no block open - * is not part of the answer. Zero: only a block the reply starts with is reasoning. */ + /* Non-zero: a reasoning block may open again later in the reply (after its answer, between + * calls) and is read as reasoning there too, and a reasoning_close with no block open is not + * part of the answer. Zero: only a block the reply starts with is reasoning. */ uint32_t reasoning_anywhere; } RadChatFormat; /* Return the format, or NULL for "derive it from the chat template". Called once at startup. */ const RadChatFormat* rad_arch_chat_format(const RadModelMeta* meta); +/* How a speech model's prompt carries audio, as data. Optional: a plugin that does not export it + * is a model the speech routes do not serve. + * + * It states the tokens that open and close a clip, the turn a transcription is asked in, how a + * language is named and forced, and where the transcript starts in the reply, so the core's + * routes know nothing of any one model. Qwen3-ASR, for example: + * + * audio_open "<|audio_start|>" audio_close "<|audio_end|>" + * transcribe_prompt "<|im_start|>system\n{context}<|im_end|>\n<|im_start|>user\n{audio}" + * "<|im_end|>\n<|im_start|>assistant\n{language}" + * language_prompt "language {language}" + * transcript_open "" language_lead "language " + * languages { "en", "English", "zh", "Chinese", ... } + * + * Every string is NUL-terminated UTF-8 and NULL reads as "". The engine copies what it needs while + * loading, so static storage in the plugin is enough. + * + * The struct only grows at its end, as RadChatFormat does: `struct_size` is sizeof(RadAudioFormat) + * as the plugin was compiled, the engine reads only the fields that size covers, and a field added + * later reads as zero for an older plugin. So this export does not move RAD_ABI_VERSION. */ +typedef struct RadAudioFormat { + uint32_t struct_size; + + /* The literal tokens around a clip's placeholder run, as the vocabulary spells them, for a + * model whose config names no id for them. NULL: the config's own (boa/eoa_token_id). */ + const char* audio_open; + const char* audio_close; + + /* The transcription prompt (POST /v1/audio/transcriptions), with three slots: {context} is + * the request's `prompt` text, {audio} the clip, and {language} `language_prompt` with the + * request's language named in it, or "" when the request names none and the model is to say + * which it heard. Each slot appears once. NULL: this model does not transcribe. */ + const char* transcribe_prompt; + const char* language_prompt; + + /* A reply whose language was not forced names it first: `language_lead` and the language's + * name, then `transcript_open`, then the transcript. "" for a model whose reply is the + * transcript alone. */ + const char* transcript_open; + const char* language_lead; + + /* The languages the model names, as n_languages (ISO 639-1 code, the model's own name) pairs: + * a request's `language` matches either spelling, and the name is what {language} takes. */ + const char* const* languages; + uint32_t n_languages; +} RadAudioFormat; + +/* Return the format, or NULL when this model serves no speech route. Called once at startup. */ +const RadAudioFormat* rad_arch_audio_format(const RadModelMeta* meta); + int rad_arch_declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx); /* Forward declaration; the signature is in rad_runtime.h. */ struct RadCtx; diff --git a/abi/rad_device.h b/abi/rad_device.h index 01748bba..0bfbfa59 100644 --- a/abi/rad_device.h +++ b/abi/rad_device.h @@ -1,10 +1,9 @@ -/* rad_device.h -- the device layer. Thin on purpose: everything above it is written once, and - * every backend implements exactly the small set of calls below. +/* rad_device.h -- the device layer. Deliberately thin: everything above it is written once, and + * every backend implements the small set of calls below. * - * The host backend is not a toy. It is what lets the core, the scheduler, the planner, the - * tokeniser, the server and libref be built and tested on a machine with no accelerator, and it - * is the same code path RAD_DOMAIN_HOST kernels run on when the planner puts a layer on the CPU - * (spec §5.1). + * The host backend is a full backend. It lets the core, scheduler, planner, tokeniser, server and + * libref be built and tested without an accelerator, and RAD_DOMAIN_HOST kernels run on it when the + * planner puts a layer on the CPU (spec §5.1). */ #ifndef RAD_DEVICE_H #define RAD_DEVICE_H @@ -19,12 +18,11 @@ typedef void* RadEvent; enum { RAD_MEM_DEVICE = 0, RAD_MEM_HOST_PINNED = 1, RAD_MEM_HOST = 2, RAD_MEM_HOST_MAPPED = 3 }; -/* WHAT THE ENGINE KNOWS ABOUT A DEVICE, AND IT IS ONLY THIS. Nothing above this layer names a - * vendor, a product or an instruction set: the scheduler, the planner and the budgets are written - * against these fields and learn the machine from them at run time. A kernel library is where - * hardware knowledge belongs, and it declares which devices it serves. +/* Everything the engine knows about a device. Nothing above this layer names a vendor, product or + * instruction set: the scheduler, planner and budgets learn the machine from these fields at run + * time. Hardware knowledge belongs in kernel libraries, which declare the devices they serve. * - * Every field carries whatever the backend reports, in the backend's own vocabulary. */ + * Every field carries what the backend reports, in the backend's own vocabulary. */ typedef struct RadDeviceProps { char name[128]; /* the product name, for logs and for the tuning cache's key */ char arch[32]; /* the backend's name for the architecture, with any feature diff --git a/abi/rad_encoding.h b/abi/rad_encoding.h index 385ce5f7..e1ca6f62 100644 --- a/abi/rad_encoding.h +++ b/abi/rad_encoding.h @@ -1,24 +1,24 @@ -/* rad_encoding.h -- what a stored weight's numbers ARE, independently of how any kernel wants them +/* rad_encoding.h -- what a stored weight's numbers are, independent of how any kernel wants them * arranged. spec.md §4.1. * - * An ENCODING is the code type, the codebook the codes index if any, the grouping of the scales, - * zero points and minimums over the weight, and the transform the weight went through before it - * was quantised. It is a property of the model: choosing one is lossy and can be expensive (GPTQ - * wants a calibration run), and changing one means quantising again. A LAYOUT -- fragment order, a - * scale carried in each row's tail, a nibble order that suits one unpack -- is a property of a - * kernel, lossless and cheap, and it is applied when the model loads (rad_abi.h). A container holds - * encodings only, so a kernel library can change every layout it has without a reconvert. + * An encoding is the code type, the codebook the codes index (if any), the grouping of the scales, + * zero points and minimums over the weight, and the transform applied before quantisation. It is a + * property of the model: choosing one is lossy and can be expensive (GPTQ needs a calibration + * run), and changing one means quantising again. A layout (fragment order, a scale carried in each + * row's tail, a nibble order that suits one unpack) is a property of a kernel, lossless and cheap, + * applied when the model loads (rad_abi.h). A container holds encodings only, so a kernel library + * can change any layout without a reconvert. * - * AN ENCODING IS DATA RATHER THAN A NAME IN AN ENUM, so a quantiser plugin can invent one without - * the core learning about it: the core can size, slice and place any encoding from this struct - * alone, and it decodes every encoding of the one scheme it defines, "affine", which is wide enough - * to hold every format in common use -- per-channel and grouped integers of any width, block FP8, - * MXFP4/6/8, NVFP4, llama.cpp's legacy, K- and I-quants, AWQ's column scales, GPTQ's act-order - * permutation, Hadamard and Givens rotations. + * An encoding is data rather than an enum value, so a quantiser plugin can invent one without the + * core knowing it. The core can size, slice and place any encoding from this struct alone, and + * decodes every encoding of the one scheme it defines, "affine". That scheme covers the common + * formats: per-channel and grouped integers of any width, block FP8, MXFP4/6/8, NVFP4, llama.cpp's + * legacy, K- and I-quants, AWQ's column scales, GPTQ's act-order permutation, Hadamard and Givens + * rotations. * * ===================================================================== PLANES * - * An encoding is up to RAD_ENC_MAX_PLANES planes, each a dense ROW-MAJOR array of one core dtype. + * An encoding is up to RAD_ENC_MAX_PLANES planes, each a dense row-major array of one core dtype. * A plane is one of two kinds: * * TILED it covers the weight. A weight of logical shape [d0, ..., dn] is seen as [rows, cols] @@ -30,25 +30,24 @@ * TABLE it does not: a codebook, a lattice grid, a rotation's parameters. Its extents are its * own, [extent0 x extent1], and every slice of the weight carries all of it. * - * SUB-BYTE AND ODD-WIDTH ELEMENTS ARE A BIT STREAM ALONG THE ROW, lowest bits first: element j of a - * b-bit row occupies bits [j*b, (j+1)*b) counted from bit 0 of the row's first byte, so two 4-bit - * codes share a byte with element 0 in bits 0-3, and a 3-bit code may straddle a byte. Every row - * starts on a byte. That is the order a reference implementation and a person reading a hex dump - * assume; a kernel that wants its nibbles permuted for its own unpack does it in its relayout. + * Sub-byte and odd-width elements are a bit stream along the row, lowest bits first: element j of a + * b-bit row occupies bits [j*b, (j+1)*b) from bit 0 of the row's first byte, so two 4-bit codes + * share a byte with element 0 in bits 0-3, and a 3-bit code may straddle a byte. Every row starts + * on a byte. A kernel that wants its nibbles permuted for its own unpack does so in its relayout. * * ===================================================================== THE AFFINE SCHEME * - * The planes are found by ROLE, and only "codes" is required. A weight element decodes as + * The planes are found by role, and only "codes" is required. A weight element decodes as * * q = code codes is TILED; its block is [1 x 1] -- one code a value -- or * [1 x V] with a "grid", one code a V-vector - * q = grid[code][k] grid TABLE [entries x V]: a VECTOR codebook (the IQ2/IQ3/IQ1 + * q = grid[code][k] grid TABLE [entries x V]: a vector codebook (the IQ2/IQ3/IQ1 * lattices); value k of the code's V-vector - * q = table[code] table TABLE [1 x entries]: a SCALAR codebook (IQ4_NL) + * q = table[code] table TABLE [1 x entries]: a scalar codebook (IQ4_NL) * q = -q if the sign bit is set signs TILED u1 [1 x 1], one bit a value - * q = q - zero zero TILED; an integer or real offset in the CODE's domain + * q = q - zero zero TILED; an integer or real offset in the code's domain * v = q * scale * scale.1 * ... scale, scale.1, ... TILED: every scale level, multiplied - * v = v - min * min.1 * ... min, min.1, ... TILED: a minimum in the VALUE's domain + * v = v - min * min.1 * ... min, min.1, ... TILED: a minimum in the value's domain * w = v . T^-1 the transform, per row, over the columns (below) * * so NVFP4 is fp4 codes, an e4m3 scale per [1 x 16] and an f32 scale.1 per tensor; Q4_K is u4 @@ -59,23 +58,23 @@ * ===================================================================== TRANSFORMS * * `transform` names what was done to each row before it was quantised: the stored row is v = w . T, - * so a kernel computes = and transforms its ACTIVATION, never the weight. + * so a kernel computes = and transforms its activation, never the weight. * * "" none. - * "fwhtN" T = H_N / N block-diagonally over groups of N columns, H_N the UNNORMALISED + * "fwhtN" T = H_N / N block-diagonally over groups of N columns, H_N the unnormalised * Sylvester Hadamard (entries +-1, H H = N I). Decoding applies H_N once (w = H v); - * the activation is rotated by H_N, unnormalised, with nothing folded at runtime -- + * the activation is rotated by the unnormalised H_N with nothing folded at runtime: * the 1/N lives in the stored scale. * "perm" T is a column permutation: TABLE "t.perm" i32 [1 x cols], v[j] = w[perm[j]] -- - * GPTQ's act-order, which quantises the columns in a different order than they sit. + * GPTQ's act-order, which quantises the columns in a different order than stored. * "givens" T = D . G_1 . ... . G_S: D = diag(t.scale) when TABLE "t.scale" f32 [1 x cols] * is present, and G_s a stage of disjoint Givens rotations -- TABLE "t.pairs" i32 * [S x cols] lists stage s's pairs as (pairs[s][2p], pairs[s][2p+1]), TABLE "t.angle" * f32 [S x cols/2] their angles, and a row vector's pair (a, b) at angle t becomes * (a cos t + b sin t, b cos t - a sin t). ParoQuant's scaled pairwise rotation. - * A weight whose row PARTS were rotated independently (a fused gate_up, a fused + * A weight whose row parts were rotated independently (a fused gate_up, a fused * q|k|v: each projection has its own rotation) carries P parts: TABLE "t.part" i32 - * [1 x P] holds the END ROW (exclusive) of each part, and the other tables stack the + * [1 x P] holds the end row (exclusive) of each part, and the other tables stack the * parts in order -- t.pairs and t.angle S rows a part (P*S rows), t.scale one row a * part (P rows). Without "t.part" the weight is one part. The stages of a part are * applied in table order, and a part's pairs address columns of the whole row. @@ -233,8 +232,8 @@ static inline int64_t rad_enc_givens_parts(const RadEncoding* e) { e->plane[i].extent[1] >= 1 ? e->plane[i].extent[1] : 0; } -/* Byte-for-byte equality, which is what two encodings agreeing means: the strings are - * zero-padded by construction, so there is nothing a memcmp could see that a reader cannot. */ +/* Byte-for-byte equality. Valid because the strings are always zero-padded, so memcmp sees only + * meaningful bytes. */ static inline int rad_enc_equal(const RadEncoding* a, const RadEncoding* b) { return a && b && memcmp(a, b, sizeof *a) == 0; } diff --git a/abi/rad_format.h b/abi/rad_format.h index 0d7ab0be..73a40f99 100644 --- a/abi/rad_format.h +++ b/abi/rad_format.h @@ -1,6 +1,6 @@ /* rad_format.h -- the .rad container (spec.md §4.2). * - * canonical, not kernel-shaped -- an entry is a LOGICAL weight holding the planes of its + * canonical, not kernel-shaped -- an entry is a logical weight holding the planes of its * encoding (rad_encoding.h), row-major; no kernel library * is named anywhere in the file, and the kernel that reads a * weight rearranges it at load (spec §4.3) @@ -13,8 +13,8 @@ * Little-endian only. Every offset is from the start of the file. Every string is an offset into * the string blob, so the directory is fixed-stride and mmap-walkable without a parse. * - * THERE IS ONE VERSION. A file in any other is refused with the instruction to convert again: the - * product has no installed base, and a second reader would be a second set of invariants. */ + * There is one format version. A file in any other is refused with an instruction to convert + * again, so there is a single reader with a single set of invariants. */ #ifndef RAD_FORMAT_H #define RAD_FORMAT_H @@ -74,7 +74,7 @@ typedef struct RadFileKV { enum { RAD_KV_F64 = 100 }; /* ------------------------------------------------------------------ weight directory */ -/* One LOGICAL weight: what a declaration's `source` names (RadWeightDecl). Fixed stride, so an +/* One logical weight: what a declaration's `source` names (RadWeightDecl). Fixed stride, so an * expert's address inside a layer is base + id*stride and no table is walked on the critical * path. */ typedef struct RadFileEntry { @@ -84,7 +84,7 @@ typedef struct RadFileEntry { uint32_t enc; /* index into the encoding table */ uint32_t rank; - int64_t shape[RAD_MAX_RANK]; /* the LOGICAL shape */ + int64_t shape[RAD_MAX_RANK]; /* the logical shape */ int32_t layer; /* RadWeightGroup, flattened: the movement unit */ int32_t expert; @@ -105,9 +105,9 @@ typedef struct RadFilePlane { } RadFilePlane; /* ------------------------------------------------------------------ expert profile */ -/* Derived from the imatrix's activation counts. A WARM START, not a policy (spec §5.3): what a - * calibration set routes to is not what decoding routes to, so this is worth a small improvement - * in residency hit rate over starting cold and no more. */ +/* Derived from the imatrix's activation counts. A warm start, not a policy (spec §5.3): a + * calibration set routes differently from decoding, so this gives only a small residency hit-rate + * gain over starting cold. */ typedef struct RadFileProfile { int32_t layer; int32_t expert; @@ -116,8 +116,8 @@ typedef struct RadFileProfile { } RadFileProfile; /* ------------------------------------------------------------------ vocab */ -/* rad-convert interprets tokenizer.json properly and bakes the result here, rather than hashing - * the file against a hardcoded enum the way llama.cpp does (spec §12). */ +/* rad-convert interprets tokenizer.json and bakes the result here, rather than hashing the file + * against a hardcoded enum as llama.cpp does (spec §12). */ enum { RAD_TOK_BPE = 1, RAD_TOK_UNIGRAM = 2, RAD_TOK_WORDPIECE = 3, RAD_TOK_RWKV = 4 }; /* Normaliser / pre-tokeniser / decoder steps, in declared order. */ diff --git a/abi/rad_philox.h b/abi/rad_philox.h index dc9f9c36..57808ab7 100644 --- a/abi/rad_philox.h +++ b/abi/rad_philox.h @@ -1,9 +1,9 @@ #ifndef RAD_PHILOX_H #define RAD_PHILOX_H -/* Counter-based Gaussian noise, the one definition every kernel library computes it by, so an - * image's starting latent is a function of its seed and of nothing else: not the batch it shares a - * pass with, not the rank count, not the order its rows are visited in. +/* Counter-based Gaussian noise, the single definition every kernel library uses, so an image's + * starting latent depends only on its seed: not on the batch it shares a pass with, the rank + * count, or the order its rows are visited in. * * Element e of a seed's stream is Philox4x32-10 at counter (e / 4, 0) keyed by the 64-bit seed, * its four words made uniform in (0, 1) as ((w >> 8) + 0.5) * 2^-24 and paired by Box-Muller -- diff --git a/abi/rad_planes.h b/abi/rad_planes.h new file mode 100644 index 00000000..fede9d57 --- /dev/null +++ b/abi/rad_planes.h @@ -0,0 +1,197 @@ +/* rad_planes.h -- the joined form of a weight operand that takes several planes, for kernels that + * read the planes as the container stores them. spec.md §4.3. + * + * A weight can be declared over several planes of one stored tensor (RadWeightDecl::planes: + * "scale,zero", "codes,table", or every plane of an fp8 lm head), and it reaches a kernel as one + * operand, so something has to say where each plane lies. A kernel that wants the planes + * rearranged for its own reads says so in its layout hook (rad_abi.h, RadLayoutFn). One that reads + * them unchanged uses this form instead: + * + * [header][entry 0][entry 1]... padded to RAD_PLANES_ALIGN + * plane 0 dense rows, padded to RAD_PLANES_ALIGN + * plane 1 ... + * + * The header and the entries describe each selected plane (its role, dtype, block, this rank's + * extents and where its bytes start), so a launch finds its planes from the operand alone, without + * the encoding. Each plane is the canonical bytes (rad_encoding.h), unchanged: the conversion is a + * copy and its inverse is one too. + * + * A library implements its layout, relayout and unrelayout hooks with the three functions below + * and reads at launch with rad_planes_find. Every library that uses this form stores the same bytes + * under the same tag, so two such libraries serving different bands of one op read one stored + * weight. A selection of one plane is not joined: rad_planes_layout declines it, and the weight is + * stored as it is. + * + * Pure C, header-only, like the rest of abi/. + */ +#ifndef RAD_PLANES_H +#define RAD_PLANES_H + +#include "rad_abi.h" +#include "rad_encoding.h" + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define RAD_PLANES_TAG "rad.planes" +#define RAD_PLANES_MAGIC 0x534e4c50u /* "PLNS" */ +enum { RAD_PLANES_ALIGN = 64 }; + +/* One selected plane. `offset` counts from the start of the joined bytes. */ +typedef struct RadPlanesEntry { + char role[RAD_ENC_STR]; + uint32_t dtype; + uint32_t kind; /* RAD_PLANE_TILED | RAD_PLANE_TABLE */ + int64_t block[2]; /* the encoding's block (TILED) or extent (TABLE) */ + int64_t rows, cols; /* this rank's extents of the plane, in its own elements */ + int64_t row_bytes; /* rad_dtype_bytes(dtype, cols): every row starts on a byte */ + int64_t offset; +} RadPlanesEntry; + +typedef struct RadPlanesHeader { + uint32_t magic; + int32_t n_planes; + char transform[RAD_ENC_STR]; /* the encoding's, for a kernel that checks it */ + int64_t bytes; /* the whole joined form, padding included */ +} RadPlanesHeader; + +static inline int64_t rad_planes_round(int64_t n) { + return (n + RAD_PLANES_ALIGN - 1) / RAD_PLANES_ALIGN * RAD_PLANES_ALIGN; +} + +/* The joined form's entries for the planes a layout hook was handed, and its total size; -1 when + * the planes cannot be joined (no planes, more than RAD_ENC_MAX_PLANES, an index outside the + * encoding, or a plane with no byte size). */ +static inline int64_t rad_planes_plan(const RadEncoding* enc, const int* sel, + const RadTensor* planes, int n_planes, RadPlanesEntry* e) { + int64_t off; + int i; + if (!enc || !sel || !planes || n_planes < 1 || n_planes > RAD_ENC_MAX_PLANES) return -1; + off = rad_planes_round((int64_t)sizeof(RadPlanesHeader) + + (int64_t)n_planes * (int64_t)sizeof(RadPlanesEntry)); + for (i = 0; i < n_planes; ++i) { + const RadEncPlane* p; + if (sel[i] < 0 || sel[i] >= enc->n_planes) return -1; + p = &enc->plane[sel[i]]; + memset(&e[i], 0, sizeof e[i]); + memcpy(e[i].role, p->role, RAD_ENC_STR); + e[i].dtype = planes[i].dtype; + e[i].kind = p->kind; + e[i].block[0] = p->kind == RAD_PLANE_TABLE ? p->extent[0] : p->block[0]; + e[i].block[1] = p->kind == RAD_PLANE_TABLE ? p->extent[1] : p->block[1]; + e[i].rows = planes[i].rank >= 2 ? planes[i].shape[0] : 1; + e[i].cols = planes[i].rank >= 2 ? planes[i].shape[1] + : (planes[i].rank == 1 ? planes[i].shape[0] : 0); + e[i].row_bytes = rad_dtype_bytes(e[i].dtype, e[i].cols); + if (e[i].rows < 0 || e[i].row_bytes <= 0) return -1; + e[i].offset = off; + off = rad_planes_round(off + e[i].rows * e[i].row_bytes); + } + return off; +} + +/* RadLayoutFn's answer for the joined form. RAD_E_UNSUPPORTED for a single plane, which is stored + * as it is. The stored dtype is the first plane's, so a launch that dispatches on the operand's + * dtype still sees the codes' (or the scale's) type; the stored shape is the byte count. */ +static inline int rad_planes_layout(const RadEncoding* enc, const int* sel, const RadTensor* planes, + int n_planes, RadLayout* out) { + RadPlanesEntry e[RAD_ENC_MAX_PLANES]; + int64_t bytes; + if (n_planes == 1) return RAD_E_UNSUPPORTED; + bytes = rad_planes_plan(enc, sel, planes, n_planes, e); + if (bytes < 0 || !out) return RAD_E_SHAPE; + memset(out, 0, sizeof *out); + out->tag = RAD_PLANES_TAG; + out->dtype = planes[0].dtype; + out->rank = 1; + out->shape[0] = bytes; + out->align = RAD_PLANES_ALIGN; + out->bytes = bytes; + return RAD_OK; +} + +/* RadRelayoutFn: the header, the entries and each plane's rows, copied. The planes are dense, as + * the loader hands them. */ +static inline int rad_planes_relayout(const RadEncoding* enc, const int* sel, + const RadTensor* planes, int n_planes, void* dst, + int64_t dst_bytes) { + RadPlanesEntry e[RAD_ENC_MAX_PLANES]; + RadPlanesHeader h; + uint8_t* d = (uint8_t*)dst; + int i; + const int64_t bytes = rad_planes_plan(enc, sel, planes, n_planes, e); + if (bytes < 0 || !dst || dst_bytes < bytes) return RAD_E_SHAPE; + memset(d, 0, (size_t)bytes); + memset(&h, 0, sizeof h); + h.magic = RAD_PLANES_MAGIC; + h.n_planes = n_planes; + memcpy(h.transform, enc->transform, RAD_ENC_STR); + h.bytes = bytes; + memcpy(d, &h, sizeof h); + memcpy(d + sizeof h, e, (size_t)n_planes * sizeof e[0]); + for (i = 0; i < n_planes; ++i) { + if (!planes[i].data && e[i].rows * e[i].row_bytes > 0) return RAD_E_INVAL; + if (e[i].rows * e[i].row_bytes > 0) + memcpy(d + e[i].offset, planes[i].data, (size_t)(e[i].rows * e[i].row_bytes)); + } + return RAD_OK; +} + +/* RadUnrelayoutFn: the planes back out of the joined form, into the buffers `planes` carry. */ +static inline int rad_planes_unrelayout(const RadEncoding* enc, const int* sel, const void* src, + int64_t src_bytes, const RadTensor* planes, int n_planes) { + RadPlanesEntry e[RAD_ENC_MAX_PLANES]; + const uint8_t* s = (const uint8_t*)src; + int i; + const int64_t bytes = rad_planes_plan(enc, sel, planes, n_planes, e); + if (bytes < 0 || !src || src_bytes < bytes) return RAD_E_SHAPE; + for (i = 0; i < n_planes; ++i) { + if (!planes[i].data && e[i].rows * e[i].row_bytes > 0) return RAD_E_INVAL; + if (e[i].rows * e[i].row_bytes > 0) + memcpy(planes[i].data, s + e[i].offset, (size_t)(e[i].rows * e[i].row_bytes)); + } + return RAD_OK; +} + +/* ================================================================== reading one at launch */ + +/* The joined form's header, or null when `base` does not hold one. */ +static inline const RadPlanesHeader* rad_planes_header(const void* base) { + const RadPlanesHeader* h = (const RadPlanesHeader*)base; + if (!h || h->magic != RAD_PLANES_MAGIC || h->n_planes < 1 || + h->n_planes > RAD_ENC_MAX_PLANES) + return 0; + return h; +} + +/* Entry `i`, or null. */ +static inline const RadPlanesEntry* rad_planes_entry(const void* base, int i) { + const RadPlanesHeader* h = rad_planes_header(base); + if (!h || i < 0 || i >= h->n_planes) return 0; + return (const RadPlanesEntry*)((const uint8_t*)base + sizeof(RadPlanesHeader)) + i; +} + +/* The plane with this role: its bytes, and its entry through `out` when given; null when the + * joined form has no such plane. */ +static inline const void* rad_planes_find(const void* base, const char* role, + const RadPlanesEntry** out) { + const RadPlanesHeader* h = rad_planes_header(base); + int i; + if (!h || !role) return 0; + for (i = 0; i < h->n_planes; ++i) { + const RadPlanesEntry* e = rad_planes_entry(base, i); + if (strncmp(e->role, role, RAD_ENC_STR) == 0) { + if (out) *out = e; + return (const uint8_t*)base + e->offset; + } + } + return 0; +} + +#ifdef __cplusplus +} /* extern "C" */ +#endif +#endif /* RAD_PLANES_H */ diff --git a/abi/rad_plugin.h b/abi/rad_plugin.h index 6431cf2d..5afc8060 100644 --- a/abi/rad_plugin.h +++ b/abi/rad_plugin.h @@ -2,32 +2,28 @@ * * ===================================================================== WHY THIS FILE EXISTS * - * A plugin is a shared object that exports the symbols in rad_abi.h and links NOTHING of - * radiance's. That boundary is fixed. What it leaves an author with, though, is the raw structs - * and nothing else -- so without this header every plugin arrives independently at the same dozen - * helpers: an optional-operand fetch, a parameter-with-default, a contiguity test, a row pitch, - * and f32<->bf16, f32<->f16 and f32<->fp8 conversions. + * A plugin exports the symbols in rad_abi.h and links nothing of radiance's, so it has only the + * raw structs. This header supplies the helpers every plugin would otherwise rewrite: an + * optional-operand fetch, parameters with defaults, row pitch, and f32<->bf16/f16/fp8 + * conversions. * - * Two of those are not merely a duplication of effort. The narrowing conversions define what a - * result IS: libref's contract is f32 accumulation, IEEE round-to-nearest-even, no FMA and - * no reassociation, and a plugin whose bf16 rounding truncates instead of rounding to even does - * not reproduce the reference and cannot be checked against it. That convention belongs in the - * ABI, stated once, not rediscovered per plugin. And the meaning of an ABSENT OPTIONAL OPERAND -- - * a null RadTensor.data, not a short operand count -- is a rule you get wrong silently: read the - * operand after it and every weight in the model shifts by one. + * Two of them are contracts, not conveniences. The narrowing conversions define what a result is: + * libref's contract is f32 accumulation, IEEE round-to-nearest-even, no FMA and no reassociation, + * and a plugin whose bf16 rounding truncates cannot be checked against the reference. And an + * absent optional operand is a null RadTensor.data, not a short operand count; getting that wrong + * silently shifts every later operand by one. * * ===================================================================== WHAT IS AND IS NOT HERE * - * Here: pure, total, header-only functions over the ABI's own types. Nothing allocates, nothing - * has state, nothing calls back into the core, and nothing may ever start. + * Here: pure, total, header-only functions over the ABI's own types. Nothing allocates, holds + * state or calls back into the core, and nothing may start to. * - * Not here: anything that needs the core. A plugin that wants a device allocation, a stream or a - * builder handle calls the functions in rad_device.h / rad_builder.h / rad_runtime.h, which the - * host exports because it must -- those genuinely cannot be inlined, and the loader's ABI check - * is what keeps them honest. + * Not here: anything that needs the core. Device allocations, streams and builder handles come + * from rad_device.h / rad_builder.h / rad_runtime.h, which the host exports; the loader's ABI + * check covers them. * - * This header is OPTIONAL. A plugin that includes only rad_abi.h is complete and correct; this - * is convenience and one shared definition of the rounding, not a requirement. + * This header is optional. A plugin that includes only rad_abi.h is complete; this is + * convenience plus one shared definition of the rounding. * * Pure C, like the rest of abi/. See spec.md 2. */ @@ -44,9 +40,8 @@ extern "C" { /* ================================================================== parameters * - * Two families, because a plugin is asked for things in two shapes. `launch` and `scratch` get a - * RadArgs; `layout`, `relayout`, `unrelayout` and `opd_shape` get a bare (const RadParam*, int) - * pair with no tensors at all. Both are the same lookup and neither should be written twice. */ + * Two families: `launch` and `scratch` get a RadArgs; `layout`, `relayout`, `unrelayout` and + * `opd_shape` get a bare (const RadParam*, int) pair with no tensors. */ static inline const RadParam* rad_param_find(const RadParam* p, int n_p, const char* key) { if (!p || !key) return 0; @@ -55,27 +50,20 @@ static inline const RadParam* rad_param_find(const RadParam* p, int n_p, const c return 0; } -/* An int parameter, or `dflt` if the key is absent or is not an int. +/* An int parameter, or `dflt` if the key is absent or not an int. * - * A RANGE is deliberately NOT accepted here. A ranged parameter is the one axis a declared op is - * bucketed over, and by the time a kernel runs it has been resolved to a value -- so a range - * arriving at a launch is a selection bug, and quietly returning its low bound would hide it. */ + * A range is deliberately not accepted: by the time a kernel runs, the ranged axis has been + * resolved to a value, so a range reaching a launch is a selection bug that returning its low + * bound would hide. */ static inline long long rad_param_geti(const RadParam* p, int n_p, const char* key, long long dflt) { const RadParam* f = rad_param_find(p, n_p, key); return (f && f->kind == RAD_P_INT) ? f->ival : dflt; } -/* THE SAME PARAMETER READ BY A SHAPE HOOK RATHER THAN BY A LAUNCH, which is the one place a range - * is legitimate and must be read as its HIGH bound. - * - * `opd_shape` is called to size buffers BEFORE selection has collapsed anything: a tool asking - * "how big is this operand" over a banded op is describing the whole band, and the arena has to - * hold it. The low end fits inside the high end, so ihi is the answer and rad_param_geti's refusal - * -- correct for a launch, where a surviving range is a selection bug -- is wrong here. - * - * Anyone writing a shape hook needs this on the first one they write, which is why it belongs in - * the ABI rather than once per plugin. */ +/* The same read for a shape hook, the one place a range is legitimate; it reads as its high + * bound. `opd_shape` sizes buffers before selection has collapsed anything, so over a banded op it + * describes the whole band, and the high end covers the low. */ static inline long long rad_param_getdim(const RadParam* p, int n_p, const char* key, long long dflt) { const RadParam* f = rad_param_find(p, n_p, key); @@ -96,9 +84,8 @@ static inline double rad_param_getf(const RadParam* p, int n_p, const char* key, return (f && f->kind == RAD_P_F64) ? f->dval : dflt; } -/* The dtype a parameter names, parsed. RAD_DT_INVALID if the key is absent or unrecognised -- - * which a kernel should treat as a refusal, because a dtype it cannot name is one it cannot - * read. */ +/* The dtype a parameter names, parsed. RAD_DT_INVALID if the key is absent or unrecognised, which + * a kernel should treat as a refusal. */ static inline uint32_t rad_param_getdt(const RadParam* p, int n_p, const char* key) { return rad_dtype_parse(rad_param_gets(p, n_p, key, 0)); } @@ -121,31 +108,23 @@ static inline double rad_args_getf_or(const RadArgs* a, const char* key, double /* ================================================================== operands * - * THE ABSENT-OPERAND RULE, WHICH IS THE EASIEST THING IN THIS ABI TO GET WRONG. + * The absent-operand rule: an optional operand a call does not pass is a RadTensor whose `data` + * is null, not a shorter `n_t`. Operands are positional, so treating absence as a shorter array + * would read operand i+1 for operand i and produce wrong numbers without a fault. * - * An optional operand a call does not pass is a RadTensor whose `data` is null -- NOT a shorter - * `n_t`. The distinction is load-bearing because operands are POSITIONAL: if a plugin treated - * absence as "the array is shorter" it would read operand i+1 where operand i was meant, and for - * a weight that means every weight after it is off by one. Nothing in the arithmetic would fault; - * the model would simply produce wrong numbers. - * - * So: one entry per schema operand, always, and this returns null for both spellings of absent -- - * past the end, or present with no data. A caller that needs to tell those apart has a schema - * disagreement rather than an absent operand, and should say so. */ + * There is always one entry per schema operand. This returns null both past the end and for a + * null `data`; a caller that sees the former has a schema disagreement, not an absent operand. */ static inline const RadTensor* rad_arg_in(const RadArgs* a, int i) { if (!a || !a->t || i < 0 || i >= a->n_t) return 0; return a->t[i].data ? &a->t[i] : 0; } -/* THERE IS NO rad_arg_out, AND THAT IS THE ABI SPEAKING RATHER THAN AN OMISSION. RadArgs::t is a - * `const RadTensor*`: the DESCRIPTORS are const, and a kernel writes an output through the - * non-const `void* data` inside one. So an output operand is fetched exactly like an input and - * the constness a caller sees is the same either way. A separate accessor would have to cast the - * descriptor's constness away and would be advertising a promise the ABI does not make. */ +/* There is deliberately no rad_arg_out. RadArgs::t is a `const RadTensor*`: the descriptors are + * const, and a kernel writes an output through the non-const `void* data` inside one, so outputs + * are fetched with rad_arg_in too. */ -/* Are the first `n` operands all present? The usual opening line of a launch, where the required - * ones are a prefix. */ +/* Are the first `n` operands all present? For a launch whose required operands are a prefix. */ static inline int rad_args_have(const RadArgs* a, int n) { for (int i = 0; i < n; ++i) if (!rad_arg_in(a, i)) return 0; return 1; @@ -154,8 +133,8 @@ static inline int rad_args_have(const RadArgs* a, int n) { /* ================================================================== tensor shape helpers */ /* [rows..., K] flattened to (M, K): every leading axis is a row count and only the last is - * structural. This is what a kernel that owns whole rows -- one workgroup per row -- wants. - * Returns 0 on a rank-0 tensor. */ + * structural, as a row-owning kernel (one workgroup per row) wants. Returns 0 on a rank-0 + * tensor. */ static inline int64_t rad_tensor_rows(const RadTensor* t) { if (!t || t->rank == 0) return 0; int64_t m = 1; @@ -167,36 +146,32 @@ static inline int64_t rad_tensor_lastdim(const RadTensor* t) { return (t && t->rank > 0) ? t->shape[t->rank - 1] : 0; } -/* The element distance between consecutive rows. For a contiguous tensor this is the last extent; - * for a strided one it is the stride of the second-to-last axis, which is the pitch a row-owning - * kernel has to honour. Strides are in ELEMENTS, not bytes (rad_types.h). */ +/* The element distance between consecutive rows: the stride of the second-to-last axis (the last + * extent when contiguous). Strides are in elements, not bytes (rad_types.h). */ static inline int64_t rad_tensor_row_pitch(const RadTensor* t) { if (!t || t->rank == 0) return 0; if (t->rank == 1) return t->shape[0]; return t->stride[t->rank - 2]; } -/* Is `p` aligned to `bytes`? Kernels that issue wide loads need this and the ABI does not promise - * it -- alignment is one of the things a constraint row cannot express, so it is checked in the - * entry point (rad_types.h: constraints are necessary, not sufficient). */ +/* Is `p` aligned to `bytes`? The ABI does not promise alignment and a constraint row cannot + * express it, so a kernel issuing wide loads checks it in the entry point (rad_types.h). */ static inline int rad_ptr_aligned(const void* p, int64_t bytes) { return bytes > 0 && ((uintptr_t)p % (uintptr_t)bytes) == 0; } /* ================================================================== narrowing conversions * - * THESE DEFINE WHAT A RESULT IS, so they are stated once here rather than per plugin. + * These define what a result is, so they are stated once here. * - * libref's contract -- and therefore the definition every kernel is checked against -- is - * f32 accumulation, IEEE round-to-nearest-ties-to-even, no fused multiply-add and no - * reassociation. `-ffp-contract=off` is a CORRECTNESS flag in this project, not a tuning one. A - * plugin whose bf16 narrowing truncates instead of rounding to even is off by up to one ulp on - * every element, which is not a tolerance question: it means the plugin cannot reproduce the - * reference and cannot be checked against it. + * libref's contract, which every kernel is checked against, is f32 accumulation, IEEE + * round-to-nearest-ties-to-even, no fused multiply-add and no reassociation; `-ffp-contract=off` + * is a correctness flag in this project. A plugin whose bf16 narrowing truncates is off by up to + * one ulp on every element and cannot be checked against the reference. * - * Every one of these is exact in the widening direction and RTNE in the narrowing direction, and - * each handles subnormals rather than flushing them -- the hardware decodes subnormals correctly, - * and flushing loses the smallest block of every quantised weight. */ + * Every conversion is exact when widening and RTNE when narrowing, and keeps subnormals rather + * than flushing them: the hardware decodes subnormals, and flushing loses the smallest block of + * every quantised weight. */ static inline float rad_bf16_to_f32(uint16_t h) { uint32_t u = (uint32_t)h << 16; @@ -205,10 +180,9 @@ static inline float rad_bf16_to_f32(uint16_t h) { return f; } -/* The `(u >> 16) & 1` is the tie-break: it adds one more than the halfway point exactly when the - * surviving bit is odd, which is what sends a tie up rather than down. Overflow falls out -- - * 0x7f7fffff plus the rounding carries into 0x7f80, the bf16 infinity -- and a NaN is forced - * quiet rather than allowed to round into an infinity. */ +/* `(u >> 16) & 1` is the tie-break: it adds one more than the halfway point when the surviving + * bit is odd, so ties go to even. Overflow carries into 0x7f80, the bf16 infinity. A NaN is forced + * quiet so it cannot round into an infinity. */ static inline uint16_t rad_f32_to_bf16(float f) { uint32_t u; memcpy(&u, &f, 4); @@ -240,8 +214,8 @@ static inline float rad_f16_to_f32(uint16_t h) { return f; } -/* RTNE, with subnormals and overflow-to-infinity handled explicitly rather than by leaning on a - * hardware convert whose mode a caller could have changed. */ +/* RTNE, with subnormals and overflow-to-infinity handled explicitly rather than by a hardware + * convert whose rounding mode a caller could have changed. */ static inline uint16_t rad_f32_to_f16(float f) { uint32_t u; memcpy(&u, &f, 4); @@ -279,9 +253,9 @@ static inline uint16_t rad_f32_to_f16(float f) { } } -/* OCP fp8 e4m3 ("e4m3fn"): 1-4-3, bias 7, NO infinity, S1111111 is the only NaN, max 448. This is - * the KV-cache format and the block-scaled weight format, so its rounding sits on the attention - * oracle's critical path and on every fp8 GEMM's. */ +/* OCP fp8 e4m3 ("e4m3fn"): 1-4-3, bias 7, no infinity, S1111111 is the only NaN, max 448. The + * KV-cache and block-scaled weight format, so the attention oracle and every fp8 GEMM depend on + * its rounding. */ static inline float rad_fp8e4m3_to_f32(uint8_t b) { uint32_t s = (uint32_t)(b >> 7) << 31; uint32_t e = (uint32_t)(b >> 3) & 0xfu; @@ -306,9 +280,8 @@ static inline float rad_fp8e4m3_to_f32(uint8_t b) { return f; } -/* SATURATES at 448 rather than overflowing. Returning a NaN for a large activation would turn one - * outlier into a poison that spreads through the whole row, and every fp8 cast in this project - * clamps for that reason. */ +/* Saturates at 448 rather than overflowing: a NaN for one large activation would spread through + * the whole row. Every fp8 cast in this project clamps for that reason. */ static inline uint8_t rad_f32_to_fp8e4m3(float f) { uint32_t u; memcpy(&u, &f, 4); @@ -321,10 +294,10 @@ static inline uint8_t rad_f32_to_fp8e4m3(float f) { if (a >= 0x43e00000u) return (uint8_t)(s | 0x7eu); /* >= 448: clamp to the largest */ e = (int)(a >> 23) - 127; m = a & 0x7fffffu; - /* The smallest subnormal is 2^-9, so everything under HALF of it -- exponent -11 and - * below -- rounds to zero. Exponent -10 is [2^-10, 2^-9): its tie point 2^-10 rounds to - * the even zero and the rest of it up to 2^-9, which the subnormal branch does with a - * 24-bit shift. */ + /* The smallest subnormal is 2^-9, so everything below half of it (exponent -11 and + * below) rounds to zero. Exponent -10 is [2^-10, 2^-9): its tie point 2^-10 rounds to the + * even zero and the rest up to 2^-9, which the subnormal branch does with a 24-bit + * shift. */ if (e < -10) return s; if (e < -6) { /* subnormal fp8 */ int sh = -6 - e + 20; @@ -349,9 +322,12 @@ static inline uint8_t rad_f32_to_fp8e4m3(float f) { } } -/* fp8 e5m2: 1-5-2, bias 15, IEEE-shaped -- it has infinities and NaNs, unlike e4m3fn. It is the - * top byte of an f16, so both directions go through the f16 path and the narrowing rounds to even - * a SECOND time on the way down. */ +/* fp8 e5m2: 1-5-2, bias 15, IEEE-shaped (it has infinities and NaNs, unlike e4m3fn). It is the + * top byte of an f16, so both directions go through the f16 path. + * + * Narrowing rounds to f16 and then drops the low byte. Every e5m2 tie point is an f16 value, so + * the f16 step can move `f` onto a tie but never across one; when it lands on a tie, `f`'s side + * of it decides, and only an exact tie goes to even. That makes the result one RTNE of `f`. */ static inline float rad_fp8e5m2_to_f32(uint8_t b) { return rad_f16_to_f32((uint16_t)((uint16_t)b << 8)); } @@ -360,19 +336,30 @@ static inline uint8_t rad_f32_to_fp8e5m2(float f) { uint16_t h = rad_f32_to_f16(f); uint16_t lo = (uint16_t)(h & 0xffu); uint16_t q = (uint16_t)(h >> 8); + /* A NaN keeps its top payload bits and stays quiet; rounding its low byte could carry it out + * of the exponent into a zero of the other sign. */ + if ((h & 0x7fffu) > 0x7c00u) return (uint8_t)(q | 0x02u); + if (lo == 0x80u && (h & 0x7c00u) != 0x7c00u) { + /* Magnitudes of non-negative floats order as their bit patterns. */ + float t = rad_f16_to_f32(h); + uint32_t uf, ut; + memcpy(&uf, &f, 4); + memcpy(&ut, &t, 4); + uf &= 0x7fffffffu; + ut &= 0x7fffffffu; + if (uf != ut) return (uint8_t)(uf > ut ? q + 1u : q); + } if (lo > 0x80u || (lo == 0x80u && (q & 1u))) ++q; return (uint8_t)q; } -/* OCP FP4 e2m1: 1-2-1, bias 1, no infinity and no NaN, so every one of the sixteen codes is a - * number and the largest is 6. */ +/* OCP FP4 e2m1: 1-2-1, bias 1, no infinity or NaN; all sixteen codes are numbers, max 6. */ static inline float rad_fp4e2m1_to_f32(uint8_t nib) { static const float mag[8] = { 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f }; return (nib & 8u) ? -mag[nib & 7u] : mag[nib & 7u]; } -/* OCP FP6, both forms. No infinity and no NaN; e2m3 has bias 1 and tops out at 7.5, e3m2 has - * bias 3 and tops out at 28. */ +/* OCP FP6, both forms. No infinity or NaN; e2m3 has bias 1 and max 7.5, e3m2 bias 3 and max 28. */ static inline float rad_fp6_to_f32(uint8_t c, int ebits) { const int mbits = 5 - ebits, bias = ebits == 2 ? 1 : 3; const int e = (c >> mbits) & ((1 << ebits) - 1), m = c & ((1 << mbits) - 1); @@ -382,7 +369,7 @@ static inline float rad_fp6_to_f32(uint8_t c, int ebits) { return (c & 0x20) ? -mag : mag; } -/* THE BIT STREAM, for every element narrower than a byte or not a power of two wide. +/* The bit stream, for every element narrower than a byte or not a power of two wide. * * Element `i` of a b-bit row occupies bits [i*b, (i+1)*b) counted from bit 0 of `base`, lowest * first, so it may straddle a byte; the read touches only the bytes the element is in. Widths to @@ -444,13 +431,11 @@ static inline float rad_e8m0_to_f32(uint8_t e) { /* ================================================================== dtype-generic access * * Load or store element `i` of a plane as f32, whatever it is stored as. This is what a host - * kernel and a converter both need, and it is the one place the dtype enum and the conversions - * above are wired together -- so a plugin that adds support for a dtype adds it once. Returns 0 - * for a dtype it cannot read, which a caller must treat as a refusal rather than as a value. + * kernel and a converter both need, and the one place the dtype enum and the conversions above + * meet. Returns 0 for a dtype it cannot read, which a caller must treat as a refusal, not a value. * - * A SUB-BYTE `i` COUNTS ELEMENTS FROM `base`, which is right inside one row and wrong across rows - * whose element count does not fill their last byte: a row starts on a byte (rad_encoding.h), so - * a caller crossing rows steps `base` a row's bytes at a time. */ + * For sub-byte dtypes `i` counts elements from `base`, which is valid only within one row: rows + * start on a byte (rad_encoding.h), so a caller crossing rows steps `base` by a row's bytes. */ static inline float rad_load_f32(const void* base, uint32_t dtype, int64_t i) { const uint8_t* b8 = (const uint8_t*)base; int sgn = 0; @@ -482,10 +467,10 @@ static inline float rad_load_f32(const void* base, uint32_t dtype, int64_t i) { } } -/* Store the raw CODE of element `i` of a sub-byte or byte plane -- the bit pattern, already - * chosen, masked to the dtype's width -- leaving its neighbours in the same byte alone. A signed - * code is passed as its value (-8..7 for i4) and stored two's complement. The quantisers' half of - * rad_load_f32; nothing rounds here. Returns 0 for a dtype wider than 16 bits. */ +/* Store the raw code of element `i` of a sub-byte or byte plane (the chosen bit pattern, masked to + * the dtype's width), leaving neighbours in the same byte alone. A signed code is passed as its + * value (-8..7 for i4) and stored two's complement. The quantisers' counterpart to rad_load_f32; + * nothing rounds here. Returns 0 for a dtype wider than 16 bits. */ static inline int rad_store_code(void* base, uint32_t dtype, int64_t i, int code) { const int bits = rad_dtype_bits(dtype); if (bits < 1 || bits > 16) return 0; @@ -495,6 +480,28 @@ static inline int rad_store_code(void* base, uint32_t dtype, int64_t i, int code return 1; } +/* `v` rounded to the nearest integer, ties to even, and clamped to [lo, hi]; NaN is 0. Exact and + * independent of the rounding mode: a float of magnitude 2^23 or more is already an integer, and + * below that its fraction is exact in a double. */ +static inline double rad_round_even_sat(float v, double lo, double hi) { + double d = (double)v, r; + if (v != v) return 0.0; + if (d >= 8388608.0 || d <= -8388608.0) { + r = d; + } else { + const long long t = (long long)d; /* toward zero */ + const double f = d - (double)t; + long long n = t; + if (f > 0.5 || (f == 0.5 && (t & 1))) ++n; + else if (f < -0.5 || (f == -0.5 && (t & 1))) --n; + r = (double)n; + } + return r < lo ? lo : (r > hi ? hi : r); +} + +/* Store `v` as element `i` of a byte-aligned plane. A float dtype rounds as the narrowings above + * do; an integer dtype rounds to nearest, ties to even, and saturates to its range, NaN storing 0. + * Sub-byte dtypes are stored with rad_store_code; any other dtype is left unwritten. */ static inline void rad_store_f32(void* base, uint32_t dtype, int64_t i, float v) { switch (dtype) { case RAD_F32: ((float*)base)[i] = v; break; @@ -502,12 +509,26 @@ static inline void rad_store_f32(void* base, uint32_t dtype, int64_t i, float v) case RAD_BF16: ((uint16_t*)base)[i] = rad_f32_to_bf16(v); break; case RAD_F8E4M3: ((uint8_t*)base)[i] = rad_f32_to_fp8e4m3(v); break; case RAD_F8E5M2: ((uint8_t*)base)[i] = rad_f32_to_fp8e5m2(v); break; - case RAD_I8: ((int8_t*)base)[i] = (int8_t)v; break; - case RAD_U8: ((uint8_t*)base)[i] = (uint8_t)v; break; - case RAD_I16: ((int16_t*)base)[i] = (int16_t)v; break; - case RAD_I32: ((int32_t*)base)[i] = (int32_t)v; break; - case RAD_U32: ((uint32_t*)base)[i] = (uint32_t)v; break; - case RAD_I64: ((int64_t*)base)[i] = (int64_t)v; break; + case RAD_I8: ((int8_t*)base)[i] = (int8_t)rad_round_even_sat(v, -128.0, 127.0); break; + case RAD_U8: ((uint8_t*)base)[i] = (uint8_t)rad_round_even_sat(v, 0.0, 255.0); break; + case RAD_U16: + ((uint16_t*)base)[i] = (uint16_t)rad_round_even_sat(v, 0.0, 65535.0); + break; + case RAD_I16: + ((int16_t*)base)[i] = (int16_t)rad_round_even_sat(v, -32768.0, 32767.0); + break; + case RAD_I32: + ((int32_t*)base)[i] = (int32_t)rad_round_even_sat(v, -2147483648.0, 2147483647.0); + break; + case RAD_U32: + ((uint32_t*)base)[i] = (uint32_t)rad_round_even_sat(v, 0.0, 4294967295.0); + break; + case RAD_I64: { + /* 2^63 is the first float past the range, so it is compared, not clamped to. */ + const double r = rad_round_even_sat(v, -9223372036854775808.0, 9223372036854775808.0); + ((int64_t*)base)[i] = r >= 9223372036854775808.0 ? INT64_MAX : (int64_t)r; + break; + } case RAD_BOOL: ((uint8_t*)base)[i] = v != 0.0f ? 1u : 0u; break; default: break; } diff --git a/abi/rad_quant.h b/abi/rad_quant.h index 6914211b..2f464926 100644 --- a/abi/rad_quant.h +++ b/abi/rad_quant.h @@ -1,23 +1,22 @@ /* rad_quant.h -- the quantiser plugin ABI. spec.md §4.5. * - * A quantiser turns a weight, handed to it in f32, into the planes of an ENCODING (rad_encoding.h). + * A quantiser turns a weight, handed to it in f32, into the planes of an encoding (rad_encoding.h). * It is the third plugin kind beside kernels and architectures, loaded from - * $RADIANCE_HOME/quantizers, and it is the only place a weight's numbers are chosen: a kernel - * rearranges planes it is given (rad_abi.h, RadRelayoutFn) and never quantises. + * $RADIANCE_HOME/quantizers, and the only place a weight's numbers are chosen: a kernel only + * rearranges the planes it is given (rad_abi.h, RadRelayoutFn). * - * rad-convert drives quantisers through a RECIPE -- ordered rules from a logical weight name to a + * rad-convert drives quantisers through a recipe: ordered rules from a logical weight name to a * quantiser and its options (spec §4.4). For each weight a rule picks, it asks the quantiser which - * encoding it would write (`encoding`), lets the architecture plugin declare against that, and - * then hands the weight over in row blocks (`row_block`, `quantize`), so a 51 GB table streams. + * encoding it would write (`encoding`), lets the architecture plugin declare against that, then + * hands the weight over in row blocks (`row_block`, `quantize`), so a 51 GB table streams. * - * WHAT A QUANTISER IS GIVEN. The weight's logical name, shape and movement group, and when the - * converter has an imatrix, the weight's column importances. Anything else it calibrates on -- a - * GPTQ Hessian, AutoRound's activations -- is an option it reads itself (`calib=DIR`): what a - * Hessian is and how it is stored is the quantiser's business, exactly as a layout is a kernel's. + * Input: the weight's logical name, shape and movement group, and the column importances when the + * converter has an imatrix. Other calibration data (a GPTQ Hessian, AutoRound's activations) is an + * option the quantiser reads itself (`calib=DIR`); its format is the quantiser's business. * - * WHAT IT HANDS BACK is the canonical planes and nothing else, so its output is readable by every - * kernel library that accepts the encoding and by the core's own decoder -- which is how rad-convert - * measures its error without knowing what it did. + * Output: the canonical planes only, so every kernel library that accepts the encoding and the + * core's own decoder can read it. That is how rad-convert measures the error without knowing the + * method. * * Pure C, like the rest of abi/. */ @@ -37,12 +36,12 @@ typedef struct RadQuantWeight { uint32_t rank; int64_t shape[RAD_MAX_RANK]; /* the logical shape */ int64_t rows, cols; /* the [rows, cols] view every plane is laid over */ - /* The movement group; -1 for none. -1 also when `encoding` is asked at declare, which runs - * before the weight's group exists -- so an encoding may depend on the name and the shape and - * not on these, and rad-convert refuses a quantiser whose answer moves once it is told. */ + /* The movement group; -1 for none. Also -1 when `encoding` is asked at declare, before the + * group exists, so an encoding may depend on the name and shape but not on these; rad-convert + * refuses a quantiser whose answer changes once it is told. */ int32_t layer, expert; - /* The imatrix's column importances for this weight -- a second moment of its input, one a - * column -- or null when the converter has none. Per expert where the imatrix has the form. */ + /* The imatrix's column importances for this weight (the second moment of its input, one per + * column), or null when the converter has none. Per expert where the imatrix has that form. */ const float* importance; } RadQuantWeight; @@ -57,22 +56,22 @@ typedef struct RadQuantOption { const char* doc; } RadQuantOption; -/* The encoding this quantiser writes for `w` under options `o`. RAD_E_UNSUPPORTED declines -- a - * weight it does not quantise, like a rank-1 norm -- and the converter moves on to the next rule; - * any other failure is an error in the recipe, said with the weight's name. */ +/* The encoding this quantiser writes for `w` under options `o`. RAD_E_UNSUPPORTED declines (a + * weight it does not quantise, like a rank-1 norm) and the converter moves on to the next rule; + * any other failure is a recipe error reported with the weight's name. */ typedef int (*RadQuantEncodingFn)(const RadParam* o, int n_o, const RadQuantWeight* w, RadEncoding* out); /* The rows one `quantize` call may take: every call but the last gets a multiple of this, starting - * on a multiple of it. 0 means the whole weight in one call -- what anything with a cross-row - * decision needs (a per-tensor scale it derives, a rotation it learns, a Hessian it shares). It must - * be a multiple of every TILED plane's block rows. */ + * on a multiple of it. 0 means the whole weight in one call, needed for any cross-row decision (a + * derived per-tensor scale, a learned rotation, a shared Hessian). Must be a multiple of every + * TILED plane's block rows. */ typedef int64_t (*RadQuantRowBlockFn)(const RadParam* o, int n_o, const RadQuantWeight* w); /* Quantise logical rows [row0, row0 + rows) of `w`, given as f32 [rows, cols] in `src`, into the - * planes. `planes[i]` points at the element row of plane i that covers logical row `row0` -- for a - * TILED plane of block rows br that is row row0 / br, for a plane covering the whole extent and for - * a TABLE plane it is the plane's start -- and the call writes exactly the rows its block covers. + * planes. `planes[i]` points at the element row of plane i that covers logical row `row0` (row + * row0 / br for a TILED plane of block rows br; the plane's start for a whole-extent or TABLE + * plane), and the call writes exactly the rows its block covers. * The buffers arrive zeroed. `src` may be modified. */ typedef int (*RadQuantizeFn)(const RadParam* o, int n_o, const RadQuantWeight* w, float* src, int64_t row0, int64_t rows, void* const* planes); @@ -81,12 +80,11 @@ typedef int (*RadQuantizeFn)(const RadParam* o, int n_o, const RadQuantWeight* w * does not decode. Null for a quantiser that writes only "plain" and "affine", which the core * decodes itself. `planes[i]` points at plane i's start. * - * It is how a scheme of a quantiser's own is READ: the oracle checking a kernel against the - * reference, rad-kbench drawing a weight, rad-convert measuring the quantiser's error all decode + * The oracle, rad-kbench and rad-convert's error measurement all read a quantiser's own scheme * through it. The core asks every loaded quantiser that has one, in load order, and takes the - * first answer that is not RAD_E_UNSUPPORTED -- so a decoder answers RAD_E_UNSUPPORTED for an - * encoding it did not write. `w` names the weight where the caller knows it; a decoder must not - * need more than the encoding, `rows` and `cols`, because the oracle knows no more. */ + * first answer that is not RAD_E_UNSUPPORTED, so a decoder must return RAD_E_UNSUPPORTED for an + * encoding it did not write. `w` names the weight where the caller knows it; a decoder must need + * nothing beyond the encoding, `rows` and `cols`, because the oracle knows no more. */ typedef int (*RadQuantDecodeFn)(const RadEncoding* e, const RadQuantWeight* w, const void* const* planes, int64_t row0, int64_t rows, float* out); @@ -102,10 +100,9 @@ typedef struct RadQuantizerInfo { RadQuantDecodeFn decode; /* optional */ } RadQuantizerInfo; -/* Every quantiser plugin exports these, beside rad_plugin_abi_version and rad_plugin_info (whose - * kind is RAD_PLUGIN_QUANT). Two plugins naming the same quantiser is refused at load, both named, - * for the reason two kernel plugins may not disagree about an op's schema: a recipe that names it - * would mean different numbers depending on load order. */ +/* Every quantiser plugin exports these, beside rad_plugin_abi_version and rad_plugin_info (kind + * RAD_PLUGIN_QUANT). Two plugins naming the same quantiser are refused at load, both named, since + * a recipe naming it would otherwise give different numbers depending on load order. */ int rad_quant_count(void); const RadQuantizerInfo* rad_quant_at(int i); diff --git a/abi/rad_runtime.h b/abi/rad_runtime.h index d8782386..b6dce69d 100644 --- a/abi/rad_runtime.h +++ b/abi/rad_runtime.h @@ -1,7 +1,7 @@ /* rad_runtime.h -- the run phase. Ordinary C++ with one rule: it may only issue handles obtained - * during declare. Nothing else is constrained; in particular there is no capture discipline on - * this code, because a graph is built out of the kernels' own launch DESCRIPTIONS (RadDescribeFn - * in rad_abi.h) rather than by capturing the step. See spec.md §3.2. + * during declare. There is no capture discipline: the device backend records a pass's dispatch + * packets at the queue as they are issued and replays them (core/device/aql.cpp, + * core/runtime/ctx.h), so the step function needs no graph-safe form. See spec.md §3.2. */ #ifndef RAD_RUNTIME_H #define RAD_RUNTIME_H @@ -15,12 +15,11 @@ extern "C" { typedef struct RadCtx RadCtx; /* ================================================================== the step batch */ -/* Built ONCE PER STEP BY THE CORE and shared by every layer and every KV group. Rebuilding it per - * KV-cache group and per layer instead turns a substantial share of a decode step into host work - * with the device idle, which is the cost spec §8 exists to avoid. +/* Built once per step by the core and shared by every layer and KV group; rebuilding it per group + * and per layer would make a large share of a decode step host work with the device idle (spec §8). * - * Every pointer here is device memory unless the field name says _h. The host mirrors exist - * because the scheduler and the run phase both need the bounds without a device read. */ + * Every pointer is device memory unless the field name says _h. The host mirrors give the + * scheduler and the run phase the bounds without a device read. */ enum { RAD_PHASE_PREFILL = 0, RAD_PHASE_DECODE = 1, RAD_PHASE_MIXED = 2 }; typedef struct RadKVGroupBatch { @@ -30,11 +29,10 @@ typedef struct RadKVGroupBatch { int64_t block_table_pitch; int32_t* seqused; /* [n_seq] context length in this group, device */ int32_t* state_index; /* [n_seq, state_index_pitch] state slots per sequence, device */ - /* HOW MANY SLOTS A SEQUENCE NAMES, and it is 1 unless the group's kernel asked for scratch - * beside the state. A linear kernel serving speculation does: it cannot commit the state - * until acceptance is known, so it keeps the committed one in column 0 and its own replay - * scratch in the columns after it. The engine zeroes every one of them when the sequence is - * admitted and otherwise does not look inside. Zero means 1, for a caller that predates it. */ + /* State slots per sequence: 1 unless the group's kernel asked for scratch beside the state. + * A linear kernel serving speculation cannot commit the state until acceptance is known, so it + * keeps the committed state in column 0 and replay scratch in the later columns. The engine + * zeroes all of them at admission and otherwise does not look inside. Zero means 1. */ int64_t state_index_pitch; int64_t block_size; int64_t max_blocks; @@ -52,21 +50,20 @@ typedef struct RadBatch { const int32_t* cu_seqlens; /* [n_seq+1] device: sequence boundaries within this step */ const int32_t* seq_ids; /* [n_seq] device: engine-side sequence identity */ - /* WHICH TOKENS THE SAMPLER WANTS LOGITS FOR: indices into THIS STEP's tokens, [n_out]. + /* The tokens the sampler wants logits for: indices into this step's tokens, [n_out]. * - * A prefill chunk computes hidden states for every token in it and the sampler wants one row - * per sequence -- the last. Without this array the architecture plugin has to run the lm_head - * GEMM over all n_tok rows, which is n_tok/n_seq times the work and, at max_tok 8192 against - * a 248K vocab, an 8 GiB logits buffer instead of a 63 MiB one. The plugin issues gather_rows - * against it and then multiplies only what came back (docs/OPS.md, "Vocabulary edges"). + * A prefill chunk computes hidden states for every token, but the sampler wants only each + * sequence's last. The plugin issues gather_rows over these and runs the lm_head only on the + * result (docs/OPS.md, "Vocabulary edges"); over all n_tok rows at max_tok 8192 and a 248K + * vocab the logits buffer would be 8 GiB instead of 63 MiB. * - * n_out is 0 for a chunk that finishes no sequence, which is the ordinary middle of a long - * prefill: no logits are produced at all and the lm_head is not touched. */ + * n_out is 0 for a chunk that finishes no sequence (the middle of a long prefill): no logits + * are produced and the lm_head is not run. */ int64_t n_out; const int32_t* out_ids; /* [n_out] device */ const int32_t* q_lens; /* [n_seq] device: query length this step */ - const int32_t* ctx_lens; /* [n_seq] device: context length BEFORE this step */ + const int32_t* ctx_lens; /* [n_seq] device: context length before this step */ int32_t max_q_len; /* host-side bounds -- these select kernel bands */ int32_t max_ctx_len; @@ -75,28 +72,27 @@ typedef struct RadBatch { /* Speculative window (spec §10). n_spec == 0 for an ordinary decode step. */ int n_spec; /* draft tokens per sequence this step */ - const int32_t* num_accepted; /* [n_seq] device, from the PREVIOUS verify */ + const int32_t* num_accepted; /* [n_seq] device, from the previous verify */ const int32_t* spec_parent; /* [n_tok] device, tree layout; null for a linear chain */ - /* THE DRAFT PASS. 0 is an ordinary step and the plugin runs the trunk; a non-zero value runs - * ONLY the draft head, and the SIGN says which kind of pass: + /* The draft pass. 0 is an ordinary step that runs the trunk; non-zero runs only the draft + * head, and the sign gives the kind: * - * r < 0 a HISTORY pass: one row a token, gathered from the trunk step's rows - * (out_ids). The head attends to its own K and V, and nothing else in the engine - * writes those -- a prefill fills the trunk's layers and leaves the head's - * untouched. This fills them for the positions the step just committed. When - * `n_draft_out` is non-zero the pass is ALSO draft round 1: it ends in the lm_head - * over the rows `draft_out_ids` names, one a drafting sequence (see there). - * r > 1 draft round r, ONE-BASED. One row a sequence, reading the head's own output - * from the round before, ending in the lm_head; the token it samples is the r-th - * draft. There is no pass with r == 1: the history pass carries that round. + * r < 0 a history pass: one row per token, gathered from the trunk step's rows + * (out_ids). The head attends to its own K and V, which nothing else writes (a + * prefill fills only the trunk's layers); this fills them for the positions the + * step just committed. When `n_draft_out` is non-zero the pass is also draft round + * 1 and ends in the lm_head over the rows `draft_out_ids` names. + * r > 1 draft round r, one-based. One row per sequence, reading the head's output from + * the round before and ending in the lm_head; it samples the r-th draft. There is + * no pass with r == 1: the history pass carries that round. * * Zero is the ordinary step so that a zeroed RadBatch runs the model, the same reason * `num_accepted` is one-based (docs/OPS.md). * - * On any such pass `token_ids` is already shifted: the head at index i reads the token at - * i + 1, and the batch builder applies that shift so no kernel and no plugin has to know it. - * Everything else in this struct means what it means on any other step. */ + * On any draft pass `token_ids` is already shifted (the head at index i reads the token at + * i + 1) by the batch builder, so no kernel or plugin applies the shift. Every other field + * keeps its usual meaning. */ int32_t draft_pass; /* Linear-state checkpointing (spec §7.3): tokens at which the scheduler wants a checkpoint @@ -105,125 +101,112 @@ typedef struct RadBatch { const int32_t* checkpoint_tok; /* [n_checkpoints] device: index into this step's tokens */ const int32_t* checkpoint_slot; /* [n_checkpoints] device: destination snapshot slot */ - /* THE DECODE / PREFILL SPLIT WITHIN A MIXED STEP. + /* The decode / prefill split within a mixed step. * - * Sequences [0, n_seq_decode) carry decode rows and the rest carry prefill chunks. The - * scheduler orders every step that way, so a block that has to treat the two differently can - * issue over each as a CONTIGUOUS sub-range of the per-sequence arrays -- `cu_seqlens + - * n_seq_decode`, `state_index + n_seq_decode * pitch`, and so on -- while leaving the token - * operands at their base. That works because cu_seqlens holds ABSOLUTE row offsets: a kernel - * whose workgroup n reads cu[n] and cu[n+1] finds the right rows whichever sub-array it was - * handed, and no kernel changes to allow it. + * Sequences [0, n_seq_decode) carry decode rows and the rest prefill chunks; the scheduler + * orders every step that way. A block that treats the two differently issues over each as a + * contiguous sub-range of the per-sequence arrays (`cu_seqlens + n_seq_decode`, + * `state_index + n_seq_decode * pitch`, ...) with the token operands left at their base. This + * works because cu_seqlens holds absolute row offsets, so a kernel reading cu[n] and cu[n+1] + * finds the right rows in either sub-array. * - * It exists because without the split a mixed step is prefill-shaped for every sequence in it, - * so the decode rows travelling with a prefill chunk cannot verify a draft and produce one - * token where they could have produced several. On an interactive load a large fraction of - * steps are mixed, so that is a large fraction of all decode rows. + * Without the split a mixed step is prefill-shaped for every sequence, so its decode rows + * cannot verify a draft and produce one token instead of several; under interactive load many + * steps are mixed. * - * n_seq_decode == n_seq on a pure decode step and 0 on a pure prefill one, so a block that - * does not care can ignore all three fields, and one that does needs no phase test. */ + * n_seq_decode == n_seq on a pure decode step and 0 on a pure prefill, so a block that does + * not care can ignore these fields, and one that does needs no phase test. */ int64_t n_seq_decode; - /* AND WHERE THEIR TOKENS END. The decode rows are tokens [0, n_tok_decode) and the prefill - * chunks are the rest, which a per-TOKEN op needs and cannot derive: each decode row is - * 1 + its own draft count, and those differ between sequences. */ + /* The decode rows are tokens [0, n_tok_decode) and the prefill chunks the rest. A per-token + * op cannot derive this, since each decode row is 1 + its own draft count. */ int64_t n_tok_decode; - /* The longest query in each half, because max_q_len over a mixed step is the prefill chunk and - * banding the decode half with it would hand a thousand-row GEMM's band to eight rows. + /* The longest query in each half. max_q_len over a mixed step is the prefill chunk's, and + * banding the decode half with it would give eight rows a thousand-row GEMM's band. * - * ONLY THE DECODE ONE IS READ TODAY, by the GDN blocks. The prefill one is here because the - * pair is what makes the split legible, and because a block whose prefill path bands on a - * per-sequence query length will want it -- the GDN prefill ops band on the step's TOTAL - * tokens instead, which they take from their operands, so they never ask. Said plainly rather - * than left to be discovered: an unread field that looks consumed is worse than one that - * says it is not. */ + * Only the decode value is currently read (by the GDN blocks). The prefill value is for a + * block whose prefill path bands on a per-sequence query length; the GDN prefill ops band on + * the step's total tokens, taken from their operands. */ int32_t max_q_len_decode; int32_t max_q_len_prefill; - /* DRAFT ROUND 1, CARRIED BY THE HISTORY PASS: [n_draft_out] device, indices into THIS pass's - * rows, one a sequence that drafts, in the order the later rounds' rows take. + /* Draft round 1, carried by the history pass: [n_draft_out] device, indices into this pass's + * rows, one per drafting sequence, in the order the later rounds' rows take. * - * Round 1 continues from the last position the verify step committed, with the token the - * trunk chose after it -- and the history pass already has a row with exactly those inputs, - * because it covers every position the verify step could have committed and repeats the last - * committed one in the rows past it (core/sched/advance.h, ADV_HIST). A separate round-1 pass - * would run the head's whole layer again over a row that pass has just computed. So each - * drafting sequence's LAST history row is its round-1 row, and the pass ends in the lm_head - * over those rows; the head's wide state at them is what round 2 continues from. + * Round 1 continues from the last committed position with the token the trunk chose after it. + * The history pass already has a row with exactly those inputs: it covers every position the + * verify step could have committed and repeats the last committed one past it + * (core/sched/advance.h, ADV_HIST). So each drafting sequence's last history row is its + * round-1 row, saving a separate pass; the pass ends in the lm_head over those rows, and the + * head's wide state there is what round 2 continues from. * * 0 on a history pass that drafts nothing, and on every other pass. */ int64_t n_draft_out; const int32_t* draft_out_ids; - /* THE PROMPT THAT FOLLOWS THIS STEP: `n_ahead` more tokens of the LAST sequence, stored in - * `token_ids` right after its n_tok -- the next chunk of a prefill with more prompt to run, and - * 0 on every other step (a decode step, a draft pass, a prefill's last chunk). + /* The prompt after this step: `n_ahead` more tokens of the last sequence, stored in + * `token_ids` right after its n_tok (the next prefill chunk); 0 on every other step (decode, + * draft pass, a prefill's last chunk). * - * Nothing is computed on them and no output depends on them. They exist so an op that fetches - * per-token data from a slow tier can start the NEXT step's reads while this step runs: the - * PLE gather reads its rows from the container file, a few tens of thousands of random reads - * a chunk, and the chunk after this one is already known (docs/OPS.md, ngram_ids' `ahead_ids` - * and embed_lookup_q's `ahead`). */ + * Nothing is computed on them. They let an op that fetches per-token data from a slow tier + * start the next step's reads during this one: the PLE gather reads its rows from the + * container file, tens of thousands of random reads per chunk (docs/OPS.md, ngram_ids' + * `ahead_ids` and embed_lookup_q's `ahead`). */ int64_t n_ahead; /* ================================================ multimodal (spec §11) */ - /* THE ROTARY POSITION OF EVERY TOKEN, AND IT IS NOT `positions`. `positions` is a token's - * index in its sequence -- the KV slot, the QSA block and every other piece of bookkeeping - * count in it -- and a rotary embedding over several position components does not. Qwen-VL - * style M-RoPE gives each token three components (temporal, height, width): a text token has - * all three equal, an image token has the image's start in the first and its row and column - * offsets in the other two, and the text after an image continues from the image's largest - * component, so from the first image on the rotary position runs BEHIND the index. + /* The rotary position of every token, which differs from `positions`. `positions` is a + * token's index in its sequence (the KV slot, the QSA block and other bookkeeping count in + * it). Qwen-VL style M-RoPE gives each token three components (temporal, height, width): a + * text token has all three equal, an image token has the image's start in the first and its + * row and column offsets in the others, and text after an image continues from the image's + * largest component, so from the first image on the rotary position runs behind the index. * - * [3, n_tok] device, COMPONENT-MAJOR: plane c is rope_pos + c * n_tok, each n_tok long. Plane - * 0 alone is a valid one-component position for every token whose three components agree, - * which is every token on a pass where `rope_mixed` is 0 -- so a kernel that reads a position - * per token (a cos/sin table row, say) takes plane 0 on such a pass and needs no change. + * [3, n_tok] device, component-major: plane c is rope_pos + c * n_tok. Plane 0 alone is a + * valid one-component position for every token whose components agree, i.e. every token when + * `rope_mixed` is 0, so a kernel reading one position per token can use plane 0 then. * - * Null when the program declares no encoder: nothing can move a rotary position away from - * the index then, and `positions` is the rotary position. */ + * Null when the program declares no encoder; `positions` is then the rotary position. */ const int32_t* rope_pos; - /* Host-side: non-zero when some token on this pass has components that differ -- an image or - * video span is in the rows. A block whose fast path reads one component a token takes the - * multi-component path on such a pass. */ + /* Host-side: non-zero when some token on this pass has differing components (an image or + * video span is present); a block with a one-component fast path must take the + * multi-component path. */ int32_t rope_mixed; - /* ROWS THAT TAKE AN ENCODER'S OUTPUT IN PLACE OF A TOKEN EMBEDDING. The placeholder ids a - * media span holds in `token_ids` are real ids -- a hashed n-gram embedding reads them -- but - * the embedding the model sees at those rows is the encoder's, and this is it: row i of - * `mm_embd` replaces the embedding of this pass's token `mm_rows[i]`. + /* Rows that take an encoder's output in place of a token embedding: row i of `mm_embd` + * replaces the embedding of this pass's token `mm_rows[i]`. The placeholder ids a media span + * holds in `token_ids` are still real ids (a hashed n-gram embedding reads them). * - * RANK 0 HOLDS THE ROWS AND EVERY OTHER RANK HOLDS ZEROS, which is the split a vocabulary- - * sharded embedding lookup produces: a token's embedding comes from the one rank that owns - * its id and the rest contribute zero to the reduction that follows. So a plugin overwrites - * its lookup's output with these rows BEFORE that reduction, and every row arrives once -- - * whether the reduction is its own all-reduce or folded into the first layer's norm. At one - * rank there is no difference. + * Rank 0 holds the rows and every other rank zeros, matching a vocabulary-sharded embedding + * lookup where non-owning ranks contribute zero to the following reduction. So a plugin + * overwrites its lookup output with these rows before that reduction, whether it is an + * all-reduce or folded into the first layer's norm. * - * On a pass that shifts its tokens (a draft head's history pass) the rows are shifted with - * them. 0 rows on every pass with no media in it. */ + * On a pass that shifts its tokens (a draft history pass) the rows are shifted with them. 0 + * rows on every pass without media. */ int64_t n_mm_rows; const int32_t* mm_rows; /* [n_mm_rows] device: index into this pass's tokens */ const void* mm_embd; /* [n_mm_rows, n_embd] bf16 device */ - /* THE ENCODER PASS. Non-zero `enc` runs a declared encoder (rad_declare_encoder) and nothing - * else: no token rows, no KV, no logits. It is that encoder's `modalities` -- RAD_MM_AUDIO - * for an audio encoder, the image/video mask for the other -- so a program that declared two - * knows which to run. Its input is a list of patches, already resized, normalised and cut by - * the processor, and its output is the encoder's declared `out` buffer, one row per `merge` - * patches, which the core reads back after the pass. + /* The encoder pass. Non-zero `enc` runs a declared encoder (rad_declare_encoder) and nothing + * else: no token rows, no KV, no logits. Its value is that encoder's `modalities` + * (RAD_MM_AUDIO, or the image/video mask), selecting between two declared encoders. Input is a + * list of patches already resized, normalised and cut by the processor; output is the + * encoder's declared `out` buffer, one row per `merge` patches, read back after the pass. * - * An AUDIO pass's patches are feature frames and its coordinates are 1-D: plane 0 the frame's - * index in its clip, plane 1 whether the frame is real (1) or the zero padding that makes the - * clip whole output rows (0), plane 2 the clip's real frames and plane 3 its staged ones. + * An audio pass's patches are feature frames with 1-D coordinates: plane 0 the frame's index + * in its clip, plane 1 whether it takes part in the convolution (1) or is staging the encoder + * reads as zero (0), plane 2 the clip's real frames and plane 3 its staged ones. The zero + * frames pad a clip staged whole to whole output rows, or, for a clip staged a second at a + * time (Qwen3-ASR), align each second to whole rows. * - * Patches are grouped into SEGMENTS -- one per image, and one per temporal group of a video - * -- and attention runs within a segment. `enc_coord` gives each patch its place in its - * segment, which is everything a learned position table and a 2-D rotary embedding need. */ + * Patches are grouped into segments (one per image, one per temporal group of a video), and + * attention runs within a segment. `enc_coord` gives each patch's place in its segment, which + * is all a learned position table or a 2-D rotary embedding needs. */ int32_t enc; int64_t enc_n_patch; const void* enc_pixels; /* [enc_n_patch, patch_dim] bf16 device */ - /* [4, enc_n_patch] device, COMPONENT-MAJOR like rope_pos: row, column, the segment's height + /* [4, enc_n_patch] device, component-major like rope_pos: row, column, the segment's height * and its width, all in patches. Planes 0 and 1 together are a [2, enc_n_patch] position. */ const int32_t* enc_coord; int64_t enc_n_seg; @@ -232,15 +215,15 @@ typedef struct RadBatch { /* ================================================ image generation */ - /* A GENERATOR PASS (rad_declare_generator): RAD_GEN_PASS_*, and `gen_b` what it carries. 0 on + /* A generator pass (rad_declare_generator): RAD_GEN_PASS_*, with `gen_b` its payload. 0 on * every step of a program that declared no generator. */ int32_t gen; const struct RadGenBatch* gen_b; } RadBatch; -/* WHAT A GENERATOR PASS CARRIES beside the step batch's own fields, which keep their meanings: +/* What a generator pass carries beside the step batch's own fields, which keep their meanings: * - * COND ONE sequence. `token_ids`, `positions` and `rope_pos` are its conditioning prompt, the + * COND one sequence. `token_ids`, `positions` and `rope_pos` are its conditioning prompt, the * encoder's input (`enc_*`) is the prompt's reference pictures and `mm_rows` the prompt * rows the encoder's output rows replace, as on any media step. What is here lays out * the generator's sequence over those rows and writes it into the KV group. @@ -255,12 +238,12 @@ typedef struct RadGenBatch { /* Where each row comes from: >= 0 the prompt row of that index (the conditioning network's * output there), < 0 the reference latent row -(1 + src). [rows] */ const int32_t* src; - /* Rotary positions, three components a row. On a COND pass they are laid out SEGMENT BY - * SEGMENT: segment s's [3, length] component-major block starts at element 3 * seg_h[s], so a + /* Rotary positions, three components a row. On a COND pass they are laid out segment by + * segment: segment s's [3, length] component-major block starts at element 3 * seg_h[s], so a * segment's positions are one dense operand. On a DENOISE pass, [3, n_tok] component-major, * the latent rows'. */ const int32_t* rope; - /* The sequence in SEGMENTS: rows [seg_h[s], seg_h[s+1]), each a picture (`seg_bidi_h` 1, its + /* The sequence in segments: rows [seg_h[s], seg_h[s+1]), each a picture (`seg_bidi_h` 1, its * rows attend to each other both ways) or a run of text (0, causal). A segment is never split * and attends to every segment before it. `seg` is the same offsets on the device; `seg_cu` * is [n_seg, 2], segment s's own cu_seqlens {0, length}, and `seg_start` [n_seg] its first @@ -273,10 +256,10 @@ typedef struct RadGenBatch { const int32_t* seg_start; /* [rows] the KV slot each row is stored at. */ const int32_t* slot_mapping; - /* PIXELS the decoder's encoder takes: `n_px` blocks of `px` [*, pixel_channels] bf16 in - * [-1, 1], block b at pixel px_h[3b], px_h[3b+1] high and px_h[3b+2] wide. The reference - * pictures, in prompt order, and -- with `inpaint` -- a last block that is no reference but - * the picture being repainted, at the size being made: its latents go to the lanes below. */ + /* Pixels for the decoder's encoder: `n_px` blocks of `px` [*, pixel_channels] bf16 in + * [-1, 1], block b at pixel px_h[3b], px_h[3b+1] high and px_h[3b+2] wide. These are the + * reference pictures in prompt order and, with `inpaint`, a last block holding the picture + * being repainted at the output size, whose latents go to the lanes below. */ int64_t n_px; const void* px; const int32_t* px_h; @@ -294,8 +277,8 @@ typedef struct RadGenBatch { const float* sigma; /* where the entry's latent is */ const float* sigma_next; /* where this step takes it */ const float* cfg; /* guidance: v = neg + cfg * (pos - neg); 1 without a pair */ - /* The entry holding this image's NEGATIVE conditioning, or -1 for none; -2 marks an entry - * that IS one, whose rows serve another entry's step and whose lane it does not move. */ + /* The entry holding this image's negative conditioning, or -1 for none; -2 marks an entry + * that is one, whose rows serve another entry's step and which does not move its lane. */ const int32_t* pair; const int32_t* lane; /* the plugin's lane the image's latent lives in */ const int32_t* lane_dh; /* ... the same, host */ @@ -320,35 +303,31 @@ enum { /* ================================================================== operands */ /* RAD_OPK_KV names a KV group's pool rather than a buffer: attention and kv_store take the cache - * as an operand, and RadKVGroupBatch carries the slot mapping and the block table but not the - * pool base -- the pool belongs to the block manager, not to the batch. handle is the - * rad_kvgroup and offset is the LAYER, because a group's pool holds one cache per bound layer. */ -/* RAD_OPK_WTAB names a RUN of consecutively declared weights rather than one weight, and it - * exists because a routed mixture of experts has no single base to stride from. A layer's experts - * are separate movement units (spec §4.1) -- after placement one of them is in VRAM, the next is - * streamed over the link and the third is still on disk -- so "expert e is base + e*stride" is - * true only of the all-in-VRAM case and silently wrong of every other. The core therefore - * resolves each handle in the run the way it resolves any weight (residency table, mover event, - * use note) and hands the kernel a DEVICE ARRAY OF POINTERS, one per expert, in declaration - * order. See the RadTensor shape rule at RAD_WTAB below. */ + * as an operand, and RadKVGroupBatch carries the slot mapping and block table but not the pool + * base, which belongs to the block manager. handle is the rad_kvgroup and offset is the layer, + * since a group's pool holds one cache per bound layer. */ +/* RAD_OPK_WTAB names a run of consecutively declared weights. A routed MoE layer has no single + * base to stride from: its experts are separate movement units (spec §4.2), and after placement + * one may be in VRAM, the next streamed over the link and a third on disk. The core resolves each + * handle like any weight (residency table, mover event, use note) and hands the kernel a device + * array of pointers, one per expert, in declaration order. See RAD_WTAB below for the RadTensor + * shape rule. */ enum { RAD_OPK_BUF = 0, RAD_OPK_WEIGHT = 1, RAD_OPK_RAW = 2, RAD_OPK_NONE = 3, RAD_OPK_KV = 4, RAD_OPK_WTAB = 5 }; typedef struct RadOperand { uint8_t kind; - uint32_t dtype; /* RAD_OPK_RAW only: what the pointer points at. A buffer and a weight - * carry their dtype in the declaration; a raw pointer is a batch field - * the core did not allocate and has nowhere else to say. RAD_DT_INVALID - * means "the kernel knows from the op schema position", which is true - * for a specialised kernel and false for libref. */ + uint32_t dtype; /* RAD_OPK_RAW only: what the pointer points at (buffers and weights + * carry their dtype in the declaration). RAD_DT_INVALID means the + * kernel knows it from the schema position, which a specialised + * kernel does and libref does not. */ uint32_t handle; /* rad_buf or rad_weight */ void* raw; /* RAD_OPK_RAW: a pointer the core did not allocate (a batch field) */ int64_t offset; /* element offset into the buffer or weight */ int64_t rows; /* 0 = the declared extent; >0 = only this many rows of dim 0 */ - int64_t cols; /* 0 = the declared extent; >0 = a COLUMN SLICE of that width, with the - * declared width kept as the stride. This is what makes a fused qkv - * projection usable: q, k and v are views of one buffer, and without it - * the architecture plugin has to declare three buffers and copy. */ + int64_t cols; /* 0 = the declared extent; >0 = a column slice of that width, with the + * declared width kept as the stride. Lets q, k and v be views of one + * fused qkv buffer instead of three buffers and a copy. */ } RadOperand; #define RAD_B(h) ((RadOperand){ RAD_OPK_BUF, RAD_DT_INVALID, (h), 0, 0, 0, 0 }) @@ -358,28 +337,24 @@ typedef struct RadOperand { * stride. RAD_B_COL(qkv, 0, n_q) is the q view of a fused projection. */ #define RAD_B_COL(h, c, w) ((RadOperand){ RAD_OPK_BUF, RAD_DT_INVALID, (h), 0, (c), 0, (w) }) #define RAD_W(h) ((RadOperand){ RAD_OPK_WEIGHT, RAD_DT_INVALID, (h), 0, 0, 0, 0 }) -/* A WEIGHT TABLE: the `n` weights declared at handles h, h+1, ... h+n-1 -- which is what a - * declaration loop over experts produces, because rad_decl_weight hands out consecutive indices. +/* A weight table: the `n` weights declared at handles h, h+1, ... h+n-1, as a declaration loop + * over experts produces (rad_decl_weight hands out consecutive indices). * - * WHAT THE KERNEL RECEIVES. `RadTensor::data` is a device array of `n` `void*`, entry e being - * expert e's first byte. `shape[0]` is n and `stride[0]` is 0, which is the marker: a zero - * leading stride says the axis is not addressable by arithmetic and the table must be indexed. - * `dtype` and `shape[1..]` / `stride[1..]` are ONE entry's -- every weight in a run must agree - * about those, and the core refuses the issue by name if they do not, because a table whose - * entries have different shapes is a table the kernel cannot walk. + * The kernel receives `RadTensor::data` as a device array of `n` `void*`, entry e pointing at + * expert e's first byte. `shape[0]` is n and `stride[0]` is 0; the zero leading stride marks an + * axis that must be indexed through the table, not by arithmetic. `dtype` and `shape[1..]` / + * `stride[1..]` are one entry's; every weight in the run must agree on them, or the core refuses + * the issue by name. * - * The table is rebuilt only when a pointer in it actually changes, so a resident model pays one - * comparison per expert per issue and no copy at all. */ + * The table is rebuilt only when a pointer changes, so a resident model pays one comparison per + * expert per issue and no copy. */ #define RAD_WTAB(h, n) ((RadOperand){ RAD_OPK_WTAB, RAD_DT_INVALID, (h), 0, 0, (n), 0 }) #define RAD_KV(g, layer) ((RadOperand){ RAD_OPK_KV, RAD_DT_INVALID, (g), 0, (layer), 0, 0 }) #define RAD_P(ptr) ((RadOperand){ RAD_OPK_RAW, RAD_DT_INVALID, 0, (void*)(ptr), 0, 0, 0 }) #define RAD_P_T(ptr, dt) ((RadOperand){ RAD_OPK_RAW, (dt), 0, (void*)(ptr), 0, 0, 0 }) -/* A raw pointer to a DENSE 2-D array: [rows, cols], packed. `cols` on a raw operand is not the - * column SLICE it is on a buffer -- there is no declared width to slice out of -- it is the second - * extent, and giving it is the only way a batch field that is genuinely two-dimensional can say so. - * The block table is the case that forced it: [n_seq, max_blocks], and passed as a rank-1 array of - * n_seq the width is simply gone. Every kernel that reads it then has to guess, and the only two - * guesses available are to refuse the operand for not being rank 2 or to read a width of one. */ +/* A raw pointer to a dense 2-D array, [rows, cols], packed. On a raw operand `cols` is the second + * extent, not a column slice (there is no declared width to slice). This is how a two-dimensional + * batch field such as the block table, [n_seq, max_blocks], keeps its width. */ #define RAD_P_T2(ptr, dt, r, c) \ ((RadOperand){ RAD_OPK_RAW, (dt), 0, (void*)(ptr), 0, (r), (c) }) #define RAD_NONE ((RadOperand){ RAD_OPK_NONE, RAD_DT_INVALID, 0, 0, 0, 0, 0 }) @@ -390,31 +365,29 @@ typedef struct RadOperand { /* ================================================================== issue */ /* The core resolves each weight handle to a pointer, waits on the mover's event if the weight is * in flight, indexes the op's bucket table with `n`, and dispatches to the device or host - * implementation according to the current execution site. + * implementation for the current execution site. * - * `n` is the value of the op's ranged parameter -- at most one per op, which is what keeps this - * a single integer on the hot path. RAD_N_BATCH means "the batch's token count", which is what - * almost every op wants. An op with no ranged parameter ignores it. + * `n` is the value of the op's ranged parameter (at most one per op, so this is a single integer + * on the hot path). RAD_N_BATCH means the batch's token count, which almost every op wants. An op + * with no ranged parameter ignores it. * - * If an op received a void*, the weight's location would be fixed at declare and placement could - * not be a core feature at all. This is the single ABI decision the whole placement design rests - * on (spec §3.2). */ + * Ops take handles, not pointers, so a weight's location is not fixed at declare; placement + * depends on this (spec §3.2). */ #define RAD_N_BATCH ((int64_t)-1) int rad_issue(RadCtx* c, rad_op op, const RadOperand* opd, int n_opd, int64_t n); -/* THE SECOND LANE, for overlapping a collective -- or an arm no shard divides -- with compute. - * `rad_lane` selects which stream subsequent issues launch on (0 or 1); `rad_lane_join(c, from, - * to)` orders `to` behind everything already issued on `from` without blocking the host or - * draining either. The runtime joins lane 1 back into lane 0 at the end of every step, so a - * missing join costs speed and not correctness. +/* The second lane, for overlapping a collective (or an arm no shard divides) with compute. + * `rad_lane` selects the stream later issues launch on (0 or 1); `rad_lane_join(c, from, to)` + * orders `to` behind everything already issued on `from` without blocking the host. The runtime + * joins lane 1 into lane 0 at the end of every step, so a missing join costs speed, not + * correctness. * - * THREE RULES, and Ctx::lane1_ in core carries the reasons: every collective must ride the SAME - * lane (the all-reduce numbers its scratch slots per launch and the two ranks must agree); a - * kernel that carries a device-wide arrival counter must key it on the STREAM, which libr4d's - * split-K GEMM does and a plugin that does not may not run here; and the buffer planner packs - * transients from a SINGLE LINEAR ORDER, so every buffer the second lane touches has to be named - * to rad_buf_concurrent, which gives up a few buffers' worth of the arena's sharing. */ + * Three rules (reasons at Ctx::lane1_ in core): every collective must use the same lane, since + * the all-reduce numbers its scratch slots per launch and the ranks must agree; a kernel with a + * device-wide arrival counter must key it on the stream (libr4d's split-K GEMM does), or it may + * not run here; and every buffer the second lane touches must be named to rad_buf_concurrent, + * because the planner packs transients from one linear order. */ int rad_lane(RadCtx* c, int lane); int rad_lane_join(RadCtx* c, int from, int to); @@ -422,12 +395,9 @@ int rad_lane_join(RadCtx* c, int from, int to); #define RAD_ISSUE(c, op, ...) rad_issue((c), (op), RAD_OPD(__VA_ARGS__), RAD_N_BATCH) #define RAD_ISSUE_N(c, op, n, ...) rad_issue((c), (op), RAD_OPD(__VA_ARGS__), (n)) -/* FAIL THE STEP WITH A REASON. An architecture block's step() returns void, so without this the - * only way to refuse a batch it cannot serve is to issue something invalid and let the operand - * check reject it -- which reports the wrong cause. A block that knows it does not serve - * a batch shape says so here, and the engine stops with `what` in the message rather than - * producing numbers nobody should trust. Returns the status it set, so `return rad_step_fail(...)` - * reads naturally in a helper. */ +/* Fail the step with a reason. An architecture block's step() returns void, so this is how it + * refuses a batch shape it does not serve; the engine stops with `what` in the message. Returns + * the status it set, so a helper can `return rad_step_fail(...)`. */ int rad_step_fail(RadCtx* c, const char* what); /* ================================================================== run-phase queries */ @@ -437,9 +407,9 @@ int rad_world_size(RadCtx* c); RadStream rad_stream(RadCtx* c); /* The routing result for a MoE layer, resolved on device against the current residency table. - * Routing NEVER blocks the compute stream: the histogram is copied back asynchronously and the - * heat engine consumes it on the next step (spec §5.5). This returns the device-side buffers, - * not host-visible expert ids -- the plugin issues its expert ops against them. */ + * Routing never blocks the compute stream: the histogram is copied back asynchronously and the + * heat engine consumes it on the next step (spec §5.5). These are device-side buffers the plugin + * issues its expert ops against, not host-visible expert ids. */ typedef struct RadRouting { const int32_t* expert_ids; /* [n_tok, top_k] device */ const float* expert_w; /* [n_tok, top_k] device */ @@ -455,22 +425,22 @@ typedef struct RadRouting { * ordinary declared ops; this is the handoff, not a computation. */ int rad_route_report(RadCtx* c, int layer, const RadRouting* r); -/* WHERE A LAYER'S EXPERT COUNTS CAN BE WRITTEN IN PLACE: a device row of at least `n_expert` int32 - * that the core owns and carries to the host itself, once, at the end of the pass. A router that - * writes its counts here and reports this pointer as `expert_count` hands them over for nothing; - * any other pointer is copied into this row, which is a dispatch a routed layer on the compute - * stream. Null when the core keeps no histogram for `layer` or its row is narrower than - * `n_expert` -- the router then writes its own buffer and reports that. */ +/* A core-owned device row of at least `n_expert` int32 where a layer's expert counts can be + * written in place; the core copies it to the host once at the end of the pass. A router that + * writes here and reports this pointer as `expert_count` hands the counts over for free; any other + * pointer costs one copy dispatch per routed layer on the compute stream. Null when the core keeps + * no histogram for `layer` or its row is narrower than `n_expert`; the router then writes its own + * buffer and reports that. */ int32_t* rad_route_counts(RadCtx* c, int layer, int64_t n_expert); -/* THE NEXT-LAYER EXPERT PREFETCH, at decode. A routed layer names the next routed layer at its router - * input; the core applies that layer's router to this layer's input rows, takes the experts the next - * layer is likeliest to route that sit in the pinned host pool, and copies them onto the card while - * the rest of this layer runs. Just before the next layer's routed GEMMs it points their weight-table - * entries at the copies, where the copies have landed and the entries still name the pool slots they - * were made from. It changes no result: a copy holds the bytes of its slot. It is on where the - * placement keeps experts in a pinned pool and the device backend can spare a DMA engine for it, and - * a pass of more than 16 rows makes no prediction; the three calls are no-ops otherwise. +/* Next-layer expert prefetch, at decode. At its router input a routed layer names the next routed + * layer; the core applies that layer's router to this layer's input rows, picks the experts it is + * likeliest to route that sit in the pinned host pool, and copies them to the card while the rest + * of this layer runs. Just before the next layer's routed GEMMs it points their weight-table + * entries at the copies that have landed, where the entries still name the pool slots copied from. + * Results are unchanged: a copy holds its slot's bytes. Active only when placement keeps experts + * in a pinned pool and the device backend can spare a DMA engine; a pass of more than 16 rows + * makes no prediction. The three calls are no-ops otherwise. * * `parts` names, for each of the next layer's experts, the weights its unit is made of (at most four, * e.g. the gate-up matrix and its scales and the down matrix and its scales), as the routed GEMMs @@ -493,15 +463,14 @@ typedef struct RadPrefetchNext { * stream -- the block must not overwrite them before this layer's routed GEMMs. */ int rad_expert_prefetch(RadCtx* c, const RadPrefetchNext* next, rad_buf h, int64_t r0, int64_t rows, int64_t n_embd); -/* After this layer's routed down GEMM: the copies cross the link from here, under the next layer's - * attention rather than under this layer's own streamed experts. */ +/* After this layer's routed down GEMM: the copies cross the link from here, overlapping the next + * layer's attention rather than this layer's own streamed experts. */ int rad_expert_prefetch_mark(RadCtx* c); /* Ahead of `layer`'s routed GEMMs, on every routed layer of every pass. */ int rad_expert_prefetch_step(RadCtx* c, int layer); -/* A weight's pointer, for the rare op that genuinely needs one (a plugin-private kernel invoked - * outside the op vocabulary). Waits on the mover. Using this forfeits nothing except the ability - * to move that weight while the pointer is live, so it is legal only within one issue. */ +/* A weight's pointer, for the rare plugin-private kernel invoked outside the op vocabulary. Waits + * on the mover. The weight may move afterwards, so the pointer is valid only within one issue. */ void* rad_weight_ptr(RadCtx* c, rad_weight w); void* rad_buf_ptr(RadCtx* c, rad_buf b); diff --git a/abi/rad_sample.h b/abi/rad_sample.h index 34d69ce4..2ccac0ba 100644 --- a/abi/rad_sample.h +++ b/abi/rad_sample.h @@ -1,22 +1,17 @@ -/* rad_sample.h -- the per-sequence sampling row, and why it is part of the ABI. +/* rad_sample.h -- the per-sequence sampling row. * - * Every sampler op takes `params` as an OPERAND: an array of the struct below, one row per sampled - * position, uploaded once per step. That makes its layout a wire format between the core and every - * kernel plugin, so it belongs here beside RadTensor rather than in core/sample/ where it started - * -- a kernel plugin cannot include a core header, and a struct the host writes and the device - * reads is a struct whose layout has to be STATED, not inferred. + * Every sampler op takes `params` as an operand: an array of the struct below, one row per sampled + * position, uploaded once per step. Its layout is therefore a wire format between the core and + * every kernel plugin, stated here because a plugin cannot include a core header. * * ============================== WHY NOT PARAMETERS ============================== * - * `rep`, `freq`, `pres`, `k` and `p` read like op PARAMETERS, and docs/OPS.md names them that way. - * They cannot be. Parameters are geometry: the selector matches constraints against them and they - * are frozen at declare (spec §2.2). A per-sequence value cannot live there, and the failure is - * not subtle -- two requests in one batch with different top_p would be two different geometries - * and therefore two different resolutions of the same op, which is not something a batch can - * contain. A deployment would have one top_p. - * - * So the values are DATA and they travel as an operand. `seed` and `offset`, which docs/OPS.md - * gives `sample_pick` as two more operands, are fields of the row for the same reason. + * `rep`, `freq`, `pres`, `k` and `p` read like op parameters, and docs/OPS.md names them that way, + * but parameters are geometry: the selector matches constraints against them and they are frozen + * at declare (spec §2.2). Two requests in one batch with different top_p would need two + * resolutions of the same op. So the values are data and travel as an operand. `seed` and + * `offset`, which docs/OPS.md gives `sample_pick` as two more operands, are row fields for the + * same reason. * * core/sample/sampler.h carries the full schema table this implies; libref implements it. */ @@ -29,16 +24,15 @@ extern "C" { #endif -/* Flags, so a kernel can skip a stage for a sequence without reading five floats to discover they - * are the identity. One integer test beats five float comparisons per row per stage. +/* Flags, so a kernel can skip a stage for a sequence with one integer test instead of reading + * five floats to find they are the identity. * - * RAD_SP_GREEDY OWNS THE ROW'S TOKEN. `sample_argmax` writes it, and every candidate stage after - * it -- `sample_topk`, the narrowing stages, `sample_merge_topk` and `sample_pick` -- treats the - * row as having no candidates and leaves `token` alone. A batch mixing greedy and sampled rows - * issues both paths over every row, so a stage that ignored the flag would overwrite the argmax - * with a draw. A greedy row that has to go through the candidate chain instead -- a split - * vocabulary, where the argmax's column is not a token id -- is staged at top_k = 1 WITHOUT this - * flag. */ + * RAD_SP_GREEDY owns the row's token. `sample_argmax` writes it, and every later candidate stage + * (`sample_topk`, the narrowing stages, `sample_merge_topk`, `sample_pick`) treats the row as + * having no candidates and leaves `token` alone. A batch mixing greedy and sampled rows issues + * both paths over every row, so a stage that ignored the flag would overwrite the argmax with a + * draw. A greedy row that must go through the candidate chain (a split vocabulary, where the + * argmax column is not a token id) is staged at top_k = 1 without this flag. */ enum { RAD_SP_GREEDY = 1 << 0, /* argmax path; the candidate chain is not run for this sequence */ RAD_SP_PENALTY = 1 << 1, /* any of rep / freq / pres is non-identity */ @@ -51,14 +45,14 @@ enum { /* One row per sampled position. Laid out so the 8-byte fields are aligned and the struct has no * padding anywhere, including at the tail. * - * THE HISTORY WINDOW. `hist_off` and `hist_len` address the row's OWN row of the history plane, - * [M, max_hist] int32 with row m belonging to sampled position m: the window is - * history[m][hist_off .. hist_off + hist_len), clamped to the row. Token ids in it are GLOBAL + * History window: `hist_off` and `hist_len` address the row's own row of the history plane, + * [M, max_hist] int32 with row m belonging to sampled position m; the window is + * history[m][hist_off .. hist_off + hist_len), clamped to the row. Token ids in it are global * vocabulary ids; a stage over a vocabulary shard subtracts its `vocab_off` parameter. * - * `penalty_last_n` and `dry_penalty_last_n` window the TAIL of that span: 0 turns the stage off - * for the row, a negative value takes the whole span, and n > 0 takes the last n tokens -- the - * meaning llama.cpp gives `repeat_last_n` and `dry_penalty_last_n`. + * `penalty_last_n` and `dry_penalty_last_n` window the tail of that span: 0 turns the stage off + * for the row, a negative value takes the whole span, and n > 0 the last n tokens (llama.cpp's + * meaning for `repeat_last_n` and `dry_penalty_last_n`). * * `dry_rep_limit` is the longest repeat DRY may count for the row, fixed by the most recent * sequence breaker in the DRY window (llama.cpp's `rep_limit`), or 0 when no breaker occurs there @@ -104,15 +98,14 @@ static_assert(offsetof(RadSampleParams, dry_rep_limit) + sizeof(int32_t) == size "RadSampleParams must pack without a tail hole"); #endif -/* THE RANDOM DRAW IS SPECIFIED, not left to a library, because the same stream has to come out of - * a host reference, a device kernel and a rerun (spec §17). splitmix64 over - * (seed * golden ratio + pos), taking 24 bits as a float in [0, 1) -- exactly f32's mantissa, so - * the draw is representable without a double anywhere in the chain. +/* The random draw is specified here, not left to a library, because a host reference, a device + * kernel and a rerun must produce the same stream (spec §13). splitmix64 over + * (seed * golden ratio + pos), taking 24 bits as a float in [0, 1): exactly f32's mantissa, so no + * double is needed anywhere. * - * INDEPENDENT DRAWS AT ONE POSITION TAKE INDEPENDENT STREAMS, and a stream is the request's seed - * XORed with a key before the draw: `rad_sample_uniform01(seed ^ key, pos)`. The pick draws on the - * seed itself. XTC's "does it fire" coin has its own key, so a row whose XTC fired is not a row - * whose pick is correlated with that fact; speculative acceptance and its residual draw have + * Independent draws at one position use independent streams: the request's seed XORed with a key, + * `rad_sample_uniform01(seed ^ key, pos)`. The pick uses the seed itself. XTC's firing coin has its + * own key so the pick is not correlated with it; speculative acceptance and its residual draw have * theirs. Every implementation of a stage takes its key from here. */ #define RAD_SAMPLE_KEY_PICK 0x0ull #define RAD_SAMPLE_KEY_XTC 0x58544311ull diff --git a/abi/rad_types.h b/abi/rad_types.h index dbf2c99b..45d5bfbd 100644 --- a/abi/rad_types.h +++ b/abi/rad_types.h @@ -15,9 +15,8 @@ extern "C" { #endif /* ------------------------------------------------------------------ status */ -/* Zero is success. Negative is failure, and the value names the class of failure so a caller - * can report something better than "it returned -1". A kernel returning negative at issue is a - * bug in selection, not a runtime condition -- spec.md §17. */ +/* Zero is success. Negative is failure, and the value names its class so a caller can report it. + * A kernel returning negative at issue is a selection bug, not a runtime condition (spec.md §17). */ enum { RAD_OK = 0, RAD_E_SHAPE = -1, /* geometry this instantiation does not serve */ @@ -42,24 +41,19 @@ enum { RAD_E_CANCELLED = -20 }; -/* ------------------------------------------------------------------ the helpers, INLINE +/* ------------------------------------------------------------------ the helpers, inline * - * WHY EVERY FREE FUNCTION IN THIS HEADER IS A DEFINITION AND NOT A DECLARATION. + * Every free function in this header is a `static inline` definition, not a declaration. A plugin + * links these headers and nothing of the engine's, so a function defined in the core would + * resolve at dlopen only if the host happened to export it (ENABLE_EXPORTS/-rdynamic); otherwise + * RTLD_NOW fails the plugin. * - * A plugin links these headers and nothing of the engine's. A function merely DECLARED here and - * defined inside the core is therefore not linkable from a plugin, which is the only caller that - * wants it -- and whether it happens to resolve at dlopen time is a property of the HOST, not of - * the ABI: a host that links the core with ENABLE_EXPORTS/-rdynamic exports the symbol and one - * that does not fails the plugin under RTLD_NOW. A capability that depends on a link flag of - * whoever dlopens you is not a capability. + * The helpers are therefore part of the ABI by value: a plugin carries the dtype table it was + * built against, and RAD_ABI_VERSION enforces the match (the loader refuses a mismatch by name, + * with both versions printed). * - * So they are `static inline` and the plugin compiles its own. That makes them part of the ABI - * BY VALUE rather than by linkage: a plugin carries the dtype table it was built against. That - * is the correct trade here, and RAD_ABI_VERSION is what enforces it -- the loader refuses a - * plugin built against a different one, by name, with both versions printed. - * - * Everything here is pure, small and total. Nothing allocates, nothing has state, and nothing - * may ever acquire either. */ + * Everything here is pure, small and total: nothing allocates or holds state, and nothing may + * start to. */ static inline const char* rad_strerror(int status) { switch (status) { case RAD_OK: return "ok"; @@ -88,14 +82,12 @@ static inline const char* rad_strerror(int status) { } /* ------------------------------------------------------------------ dtypes */ -/* The core understands dtypes. Spec §19.6 asked whether it had to; it does -- libref has to - * interpret a tensor to compute on it, rad-kbench has to compare two of them elementwise, the - * buffer planner has to size a buffer from its shape, and rad-convert has to write bytes. An - * opaque dtype would push all four back into the plugin, which is the opposite of the point. +/* The core understands dtypes (spec §19.6): libref computes on tensors, rad-kbench compares them + * elementwise, the buffer planner sizes buffers from shapes, and rad-convert writes bytes. * * The enum is open at the top: values >= RAD_DT_PLUGIN_BASE are kernel-plugin private, sized by - * the plugin's own layout hook, and never interpreted by the core. That is where a format - * invented for one kernel lives (spec §4.3) without the core learning about it. */ + * the plugin's own layout hook and never interpreted by the core. A format invented for one kernel + * lives there (spec §19.6). */ enum { RAD_DT_INVALID = 0, @@ -115,11 +107,10 @@ enum { RAD_U32 = 13, RAD_BOOL = 14, - /* SUB-BYTE CODES AND THE EXPONENT SCALE. The element count is the count of LOGICAL elements - * and the byte size comes from rad_dtype_bits(), which is why it is expressed in bits. They - * pack along a row, lowest bits first -- element 2j of a 4-bit row in bits 0-3 of byte j -- - * and a row starts on a byte (rad_encoding.h). What a code MEANS is its encoding's business; - * these say only how many bits it is and whether it is signed. */ + /* Sub-byte codes and the exponent scale. Element counts are logical elements; byte sizes + * come from rad_dtype_bits(). They pack along a row, lowest bits first (element 2j of a 4-bit + * row in bits 0-3 of byte j), and a row starts on a byte (rad_encoding.h). What a code means + * is its encoding's business; these give only its width and signedness. */ RAD_I4 = 16, /* two's complement, -8..7 */ RAD_I2 = 17, /* two's complement, -2..1 */ RAD_FP4E2M1 = 18, /* OCP FP4: 1-2-1, no inf or nan, max 6 */ @@ -145,10 +136,10 @@ enum { RAD_DT_PLUGIN_BASE = 256 }; -/* THE DTYPE TABLE, and it lives in the header for the reason the block above rad_strerror gives. +/* The dtype table, in the header for the reason given above rad_strerror. * * Sub-byte formats carry their packed width here. A shared scale is never folded into a code's - * width: it is a plane of its own (rad_encoding.h), so every width below is exact. */ + * width (it is a plane of its own, rad_encoding.h), so every width below is exact. */ typedef struct RadDtRow { uint32_t dt; const char* name; int bits; } RadDtRow; static const RadDtRow rad_dt_table[] = { @@ -202,8 +193,8 @@ static inline const char* rad_dtype_name(uint32_t dtype) { return dtype >= RAD_DT_PLUGIN_BASE ? "plugin-private" : "invalid"; } -/* RAD_DT_INVALID if unknown. The alternate spellings are the ones that appear in checkpoints and - * in kernel dtype strings; a converter reading safetensors meets every one of them. */ +/* RAD_DT_INVALID if unknown. The alternate spellings are those found in checkpoints (safetensors) + * and kernel dtype strings. */ static inline uint32_t rad_dtype_parse(const char* name) { if (!name) return RAD_DT_INVALID; for (int i = 0; i < RAD_DT_TABLE_N; ++i) @@ -228,8 +219,8 @@ static inline int64_t rad_dtype_bytes(uint32_t dtype, int64_t n) { /* ------------------------------------------------------------------ tensors */ enum { RAD_MAX_RANK = 6 }; -/* Strides are in ELEMENTS, not bytes -- the convention that survives contact with sub-byte - * dtypes, where a byte stride would be fractional. */ +/* Strides are in elements, not bytes, since a byte stride would be fractional for sub-byte + * dtypes. */ typedef struct RadTensor { void* data; uint32_t dtype; @@ -245,9 +236,8 @@ static inline int64_t rad_tensor_numel(const RadTensor* t) { return n; } -/* A rank-0 tensor and a tensor whose only non-unit axes are already dense are both contiguous. - * The unit-extent test matters: a shape-1 axis may carry any stride at all and still describe the - * same bytes, so demanding the packed value there rejects tensors that are in fact dense. */ +/* A rank-0 tensor and a tensor whose non-unit axes are dense are both contiguous. A shape-1 axis + * may carry any stride and still describe the same bytes, so its stride is not checked. */ static inline int rad_tensor_is_contiguous(const RadTensor* t) { if (!t || t->rank == 0) return 1; int64_t acc = 1; @@ -267,8 +257,8 @@ static inline void rad_tensor_pack(RadTensor* t) { /* ------------------------------------------------------------------ parameters */ /* An op's parameters are named scalars: the geometry the selector matches constraints against. - * A parameter may be a fixed value or a RANGE, which is what turns one declared op into a - * bucket table (spec §2.2). At most one parameter per op may be ranged. */ + * A parameter may be a fixed value or a range, which turns one declared op into a bucket table + * (spec §2.2). At most one parameter per op may be ranged. */ enum { RAD_P_INT = 1, RAD_P_STR = 2, RAD_P_RANGE = 3, RAD_P_F64 = 4 }; typedef struct RadParam { @@ -277,11 +267,10 @@ typedef struct RadParam { long long ival; /* RAD_P_INT, and the low bound of RAD_P_RANGE */ long long ihi; /* RAD_P_RANGE: the high bound, inclusive */ const char* sval; /* RAD_P_STR */ - double dval; /* RAD_P_F64 -- eps, rope theta, an attention scale. Carried as a - * double rather than round-tripped through a "%.9g" string, which is - * exact for an IEEE single but unreadable in a graph dump. Constraints - * do not match on a float: a tolerance is not a predicate, and a kernel - * that cares about eps to that precision is a kernel with a bug. */ + double dval; /* RAD_P_F64: eps, rope theta, an attention scale. A double rather + * than a "%.9g" string, which would be exact for an IEEE single but + * unreadable in a graph dump. Constraints never match on a float: + * a tolerance is not a predicate. */ } RadParam; /* Builders. RAD_PARAMS below wraps these into a positional list. */ @@ -291,9 +280,9 @@ typedef struct RadParam { #define RAD_RANGE(k, lo, hi) ((RadParam){ (k), RAD_P_RANGE, (long long)(lo), (long long)(hi), 0, 0.0 }) /* ------------------------------------------------------------------ constraints */ -/* A kernel's necessary condition on a geometry. Deliberately NOT sufficient: strides, - * contiguity, alignment and buffer sizes are properties of a call rather than of a model, and - * they stay in the entry point, which still rejects what it cannot run -- spec §2.1. */ +/* A kernel's necessary condition on a geometry, deliberately not sufficient: strides, + * contiguity, alignment and buffer sizes are properties of a call rather than of a model, and the + * entry point still rejects what it cannot run (spec §2.1). */ enum { RAD_C_EQ = 0, RAD_C_LE = 1, RAD_C_GE = 2, RAD_C_DIV = 3, RAD_C_IN = 4 }; typedef struct RadConstraint { @@ -303,13 +292,11 @@ typedef struct RadConstraint { const char* sval; /* IN: space-separated set of admissible strings */ } RadConstraint; -/* A CONSTRAINT ON THE MACHINE rather than on the geometry. A key that starts "device." is matched - * against what the engine measured about the ranks' devices at launch, not against the op's - * parameters: a capability such as reaching another card's memory belongs to the machine, and - * carrying it as a parameter would have every architecture plugin declare it on every op and - * every schema grow a field for it. Such a key is in no geometry, so it changes no tuning key - * and no selection fold. Where nothing measured it -- a tool selecting without an engine -- it is - * absent, and a constraint on an absent key does not hold. +/* A constraint on the machine rather than the geometry. A key starting "device." is matched + * against what the engine measured about the ranks' devices at launch, not against op parameters, + * so architecture plugins and schemas need not carry machine capabilities. Such a key is in no + * geometry, so it changes no tuning key and no selection fold. Where nothing measured it (a tool + * selecting without an engine) it is absent, and a constraint on an absent key does not hold. * * device.p2p 1 when every rank's device can read and write every other rank's memory * directly; 0 when some pair cannot. One rank has no peer to reach, and is 1. */ @@ -329,47 +316,20 @@ typedef struct RadConstraint { typedef uint32_t rad_weight; typedef uint32_t rad_buf; typedef uint32_t rad_op; -/* A KV group handle. It lives here with the other handles because a declaration in rad_builder.h - * carries one: a derived buffer names the KV group its derivation is about. */ +/* A KV group handle. Here with the other handles because RadBufDecl in rad_builder.h carries + * one. */ typedef uint32_t rad_kvgroup; #define RAD_NULL_HANDLE 0u /* ------------------------------------------------------------------ streams */ -/* Opaque to the core in the sense that it never dereferences one. On a card it is a queue of the - * engine's own, NOT a hipStream_t: a kernel plugin launches onto it with hipLaunchKernel (and so - * <<<>>>), hipMemcpyAsync, hipMemcpy2DAsync and hipMemsetAsync, which the engine answers itself, - * and hands it to nothing else in HIP (docs/PLUGIN.md, "What a launch may do"). Under the host - * backend it is a queue the host kernels ignore. */ +/* Opaque: the core never dereferences one. On a card it is the engine's own queue, not a + * hipStream_t. A kernel plugin may use it only with hipLaunchKernel (and so <<<>>>), + * hipMemcpyAsync, hipMemcpy2DAsync and hipMemsetAsync, which the engine implements itself, and + * must pass it to nothing else in HIP (docs/PLUGIN.md, "What a launch may do"). Under the host + * backend the host kernels ignore it. */ typedef void* RadStream; -enum { RAD_MAX_KPARAMS = 24, RAD_KPARAM_BLOB = 256 }; - -typedef struct RadLaunchDesc { - /* The entry symbol, as the launch API takes it. A template instantiation resolves to its own - * symbol, which is the point: `heads` picking a different instantiation moves the FUNCTION, - * not just an argument, and a node whose function moved has to be rebuilt rather than - * updated. The runtime compares this across steps and recaptures when it changes. */ - const void* func; - uint32_t grid[3]; - uint32_t block[3]; - uint32_t shared_bytes; - uint32_t n_params; - /* Pointers to the argument values, in the kernel's declared order -- the `kernelParams` - * convention, so slot i is parameter i and the runtime can rewrite exactly the ones that - * moved. */ - void* params[RAD_MAX_KPARAMS]; - /* The width of each slot, which the runtime needs for two things it cannot otherwise do: - * compare a slot against the previous step's to see whether it moved, and recognise a slot - * that holds an OPERAND ADDRESS by matching its value against the operands it just passed in. - * That second one is what lets a replay update ten pointers without re-entering the shim -- - * the mapping is inferred, so no kernel has to declare it and no out-of-tree author has to - * know it exists. */ - uint16_t param_size[RAD_MAX_KPARAMS]; - /* Where the values live. The shim writes into this and points `params` here. */ - unsigned char blob[RAD_KPARAM_BLOB]; -} RadLaunchDesc; - #ifdef __cplusplus } /* extern "C" */ #endif diff --git a/abi/rad_yarn.h b/abi/rad_yarn.h index 17479e1e..a0c69ae5 100644 --- a/abi/rad_yarn.h +++ b/abi/rad_yarn.h @@ -1,10 +1,16 @@ #ifndef RAD_YARN_H #define RAD_YARN_H -/* Static YaRN coefficients. The architecture resolves the correction bounds using - * the ORIGINAL training length, never the deployment/table length. Kernels share - * the resolved coefficients so direct and table-backed RoPE cannot disagree. */ +/* Static YaRN coefficients. The architecture resolves the correction bounds from the original + * training length, never the deployment or table length. Kernels share the resolved coefficients + * so direct and table-backed RoPE cannot disagree. + * + * C++ gets RadYarn with a member frequency() (callable from HIP device code) and default member + * values; C gets the same four-float struct and rad_yarn_frequency(). The two definitions must + * compute the same frequencies; tests/abi_layout_test.cpp compares them. */ #include "rad_plugin.h" + +#ifdef __cplusplus #include #if defined(__HIPCC__) @@ -14,7 +20,7 @@ #endif struct RadYarn { - float factor = 0.0f; /* zero: keep the legacy arithmetic exactly */ + float factor = 0.0f; /* zero: YaRN off, frequency() returns `inv` unchanged */ float low = 0.0f; float high = 0.0f; float magnitude = 1.0f; @@ -46,4 +52,41 @@ inline bool rad_yarn_valid(const RadYarn& y) { } #undef RAD_YARN_HD + +#else /* C */ +#include + +typedef struct RadYarn { + float factor; /* zero: YaRN off, rad_yarn_frequency() returns `inv` unchanged */ + float low; + float high; + float magnitude; /* 1 when off */ +} RadYarn; + +static inline float rad_yarn_frequency(const RadYarn* y, float inv, int i) { + float width, ramp, mask; + if (y->factor == 0.0f) return inv; + width = y->high == y->low ? 0.001f : y->high - y->low; + ramp = fminf(1.0f, fmaxf(0.0f, ((float)i - y->low) / width)); + mask = 1.0f - ramp; + return (inv / y->factor) * (1.0f - mask) + inv * mask; +} + +static inline RadYarn rad_yarn_args(const RadArgs* a) { + RadYarn y = { 0.0f, 0.0f, 0.0f, 1.0f }; + y.factor = (float)rad_args_getf_or(a, "yarn_factor", 0.0); + if (y.factor == 0.0f) return y; + y.low = (float)rad_args_getf_or(a, "yarn_low", 0.0); + y.high = (float)rad_args_getf_or(a, "yarn_high", 0.0); + y.magnitude = (float)rad_args_getf_or(a, "yarn_magnitude", 1.0); + return y; +} + +static inline int rad_yarn_valid(const RadYarn* y) { + return isfinite(y->factor) && (y->factor == 0.0f || + (y->factor >= 1.0f && isfinite(y->low) && isfinite(y->high) && y->high >= y->low && + isfinite(y->magnitude) && y->magnitude > 0.0f)); +} +#endif + #endif diff --git a/arch/CMakeLists.txt b/arch/CMakeLists.txt index a5a730df..77c51cc9 100644 --- a/arch/CMakeLists.txt +++ b/arch/CMakeLists.txt @@ -1,29 +1,20 @@ -# Architecture plugins. One directory each, one .so each, linking only rad_abi -- an architecture -# plugin does not link the core. +# Architecture plugins: one directory and one .so each, linking only rad_abi, never the core. # -# qwen35 covers the Qwen3.5, Qwen3.6 and Qwen3.8 dense models, which all report that id, and -# qwen35moe is the same graph with a routed FFN. See docs/ARCHITECTURES.md for the geometry. -# One plugin per (architecture, quantisation) -- spec §2.4, and the pair is the selection key, so -# qwen35_bf16 and qwen35_fp8 both claim "qwen35" and are told apart by the container's quantisation -# descriptor. See rad_arch_quant in abi/rad_builder.h. +# qwen35 covers the Qwen3.5, Qwen3.6 and Qwen3.8 dense models, which all report that id; qwen35moe +# is the same graph with a routed FFN (docs/ARCHITECTURES.md). There is one plugin per +# (architecture, quantisation) pair, which is the selection key (spec §2.4): qwen35_bf16 and +# qwen35_fp8 both claim "qwen35" and are told apart by the container's quantisation descriptor +# (rad_arch_quant in abi/rad_builder.h). # -# The plugins are discovered, not listed. A hand-written list can name a plugin that has no -# directory, and a name in a build file that resolves to nothing is worse than no name: it is a -# plugin an operator will look for and not find, with no error anywhere to say it was never built. -# With discovery, what is in the tree is what is built, and what is not in the tree does not appear -# in a list. -# -# Globbed the way libref/CMakeLists.txt globs its translation units, and SORTED, because -# file(GLOB) returns directory order and an unsorted list makes the link order -- and therefore the -# plugin load order, which is the hierarchy that decides which architecture wins a tie -- depend on -# the filesystem. +# Plugins are discovered, not listed, so the build is exactly what is in the tree. The glob is +# sorted because file(GLOB) returns directory order, and the link order sets the plugin load order, +# which decides which architecture wins a tie. file(GLOB RAD_ARCH_DIRS CONFIGURE_DEPENDS LIST_DIRECTORIES true ${CMAKE_CURRENT_SOURCE_DIR}/*) list(SORT RAD_ARCH_DIRS) -# THE INCLUDE SPELLING IS THE INSTALLED ONE. arch/common/ installs as /radiance/arch/, so a -# plugin built against an installed radiance writes `#include `; the plugins in -# this tree write the same, through a directory in the build tree whose arch/ is this common/. -# A plugin here that could only be built here would not be a plugin like any other. +# In-tree plugins use the installed include spelling. arch/common/ installs as +# /radiance/arch/, so plugins write `#include `; in this tree that +# resolves through a build-tree directory whose arch/ links to common/. set(RAD_ARCH_INCLUDE_ROOT ${CMAKE_BINARY_DIR}/rad_include) file(MAKE_DIRECTORY ${RAD_ARCH_INCLUDE_ROOT}) if(NOT EXISTS ${RAD_ARCH_INCLUDE_ROOT}/arch) @@ -36,37 +27,28 @@ foreach(d ${RAD_ARCH_DIRS}) continue() endif() get_filename_component(a ${d} NAME) - # common/ is the shared header library every plugin includes, not a plugin. It is excluded by - # name, and that is the only directory with special treatment. + # common/ is the shared header library, not a plugin. if(a STREQUAL "common") continue() endif() if(EXISTS ${d}/CMakeLists.txt) - # Every plugin carries its own build rules, the ones it would be built with out of this tree. + # Each plugin's own build rules, the same ones it uses out of tree. add_subdirectory(${a}) else() - # Named rather than skipped in silence. A directory under arch/ with no CMakeLists.txt is - # either a plugin missing its build file or a directory that does not belong here, and both of - # those are things somebody wants to be told about at configure time rather than discovering - # from an architecture the engine cannot find. + # Reported at configure time rather than skipped silently: either a plugin is missing its build + # file or the directory does not belong here. message(STATUS "arch: '${a}' has no CMakeLists.txt -- not an architecture plugin, skipped") endif() endforeach() -# arch/common/ ships. abi/rad_builder.h tells a plugin author, in the ABI header itself, to use the -# grp_layer()/grp_expert()/grp_model() inline functions in arch/common/rad_arch.h rather than the -# rad_group_*() macros beneath that note, because those macros are C compound literals and C++ -# accepts them only as a GNU extension -- and an architecture plugin in C++ is the norm. Without -# this install the shipped header would point at a file that is not shipped, and the one documented -# way to write a conforming plugin would be available only inside this tree. +# arch/common/ ships: abi/rad_builder.h directs C++ plugin authors to the grp_*() helpers in +# arch/common/rad_arch.h instead of the rad_group_*() compound-literal macros (a GNU extension in +# C++). # -# Installed FLAT into arch/, which is what makes it work without touching a single #include: -# these headers include each other by bare basename ("rad_arch.h", "rad_fp8.h"), which resolves -# relative to the including file in both trees, and rad_arch.h's own "rad_builder.h" resolves -# against the include root that radiance::abi puts on the path. Every plugin, in this tree or out of -# it, writes `#include ` -- see RAD_ARCH_INCLUDE_ROOT above for how that resolves -# here. +# Installed flat into arch/. These headers include each other by bare basename, which resolves +# relative to the including file in both trees, and rad_arch.h's "rad_builder.h" resolves against +# the include root that radiance::abi provides. install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/common/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/radiance/arch FILES_MATCHING PATTERN "*.h") diff --git a/arch/common/rad_arch.h b/arch/common/rad_arch.h index 6e7c6c9a..c7b80d42 100644 --- a/arch/common/rad_arch.h +++ b/arch/common/rad_arch.h @@ -1,14 +1,12 @@ /* rad_arch.h -- the scaffolding an architecture plugin sits on. * - * spec.md §2.4 commits to one plugin per (architecture, quantisation). That is deliberate: a w4a8 - * model wants rmsnorm_had_quant_i8 where a bf16 model wants a plain rmsnorm, and pretending - * otherwise means a plugin full of branches on a quant descriptor -- which is how you get back to - * "unclear what actually runs". A declare function with no branches in it is a readable list of - * what this model does, in order. + * spec.md §2.4 has one plugin per (architecture, quantisation): a w4a8 model wants + * rmsnorm_had_quant_i8 where a bf16 model wants a plain rmsnorm, and a declare function without + * branches on a quant descriptor reads as the list of what the model does, in order. * - * The file-count mitigation for the quant axis is this library. It is header-only, it is C++ - * (nothing here crosses an .so boundary -- only the four exported C symbols do), and it holds one - * small struct per transformer block with a declare() and a step(). A plugin is COMPOSITION. + * This header-only C++ library keeps that from multiplying files: one small struct per + * transformer block with a declare() and a step(), composed by the plugin. Nothing here crosses + * an .so boundary; only the exported C symbols do. */ #ifndef RAD_ARCH_H #define RAD_ARCH_H @@ -28,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -35,29 +34,25 @@ namespace rad { namespace arch { -/* One thread per tensor-parallel rank, all in one process (spec §1), and declare runs once per - * rank. So a plugin's declared handles are per-rank state, not process state: a single global - * would have rank 1's declare overwrite rank 0's. libr4d supports 2/4/8-rank all-reduce, so eight - * is the bound worth carrying. */ +/* One thread per tensor-parallel rank in one process (spec §1), and declare runs once per rank, + * so declared handles are per-rank state; a single global would let rank 1 overwrite rank 0. + * libr4d all-reduces over 2/4/8 ranks, hence eight. */ enum { MAX_RANKS = 8 }; - /* ================================================================== a debug residual probe * - * THE ONE INSTRUMENT FOR A COMPOSITION FAULT, and it exists because nothing else in the tree can - * see one: rad-kbench falsifies an op against the oracle on the same inputs and a graph that wires - * the right ops to the wrong buffers -- or a block whose output is the wrong SIZE -- passes every - * one of those checks and still serves a different model. What a reader needs then is the residual - * stream's magnitude down the stack, which is smooth in a working model and steps in a broken one. + * Finds composition faults: rad-kbench checks each op against the oracle, so a graph that wires + * the right ops to the wrong buffers, or a block whose output has the wrong size, passes kbench + * and still serves a different model. The residual stream's magnitude down the stack is smooth in + * a working model and steps in a broken one. * - * It SYNCHRONISES THE STREAM and copies one row, so it is off unless RADIANCE_DEBUG_RESID is set, - * and it prints each (layer, site) once. bf16 buffers only -- every activation in this tree is. */ + * It synchronises the stream and copies one row, so it is off unless RADIANCE_DEBUG_RESID is set, + * and prints each (layer, site) once. bf16 buffers only, as is every activation in this tree. */ struct DbgStat { double rms = -1.0, med = -1.0, max = -1.0; }; -/* RMS, MEDIAN AND MAX TOGETHER, because a residual stream carries a handful of channels two orders - * of magnitude above the rest (the "massive activations" every model in this family has) and the - * RMS is theirs alone. The MEDIAN is the bulk, which is what a block's delta has to be compared - * against; reading the RMS by itself says twenty layers did nothing when they did. */ +/* RMS, median and max of |x| over one row. A few "massive activation" channels sit two orders of + * magnitude above the rest and dominate the RMS; the median is the bulk, which is what a block's + * delta should be compared against. */ inline DbgStat dbg_row_stat(RadCtx* c, rad_buf b, int64_t n) { DbgStat s; if (!b || n <= 0) return s; @@ -88,12 +83,17 @@ inline bool dbg_resid_on() { return on; } +/* True the first time any rank thread reaches (layer, site), so a probe prints each once. */ +inline bool dbg_first(int layer, const char* site) { + static std::mutex mu; + static std::set> seen; + std::lock_guard lk(mu); + return seen.emplace(layer, site).second; +} + inline void dbg_resid(RadCtx* c, int layer, const char* site, int64_t n_embd, rad_buf x, rad_buf delta) { - if (!dbg_resid_on()) return; - static int seen[512] = {0}; - const int slot = ((layer * 4) + (site[0] & 3)) & 511; - if (seen[slot]++) return; + if (!dbg_resid_on() || !dbg_first(layer, site)) return; const DbgStat sx = dbg_row_stat(c, x, n_embd), sd = dbg_row_stat(c, delta, n_embd); std::fprintf(stderr, "D resid layer %2d %-4s: x rms %8.4f med %8.5f max %9.3f | " "delta rms %8.4f med %8.5f max %9.3f\n", @@ -101,34 +101,29 @@ inline void dbg_resid(RadCtx* c, int layer, const char* site, int64_t n_embd, } /* ================================================================== the GPTQ calibration tap * - * A block that wants to characterise one of its own activations declares an f32 [K, K] PERSIST - * buffer and a `gram_accum` op into it, then calls calib_write() when the corpus is done. These - * three helpers are the parts that are not block-specific: whether it is on, when to stop, and - * the file. + * A block that characterises one of its activations declares an f32 [K, K] PERSIST buffer and a + * `gram_accum` op into it, then calls calib_write() when the corpus is done. These helpers are + * the block-independent parts: whether the tap is on, when to stop, and the file. * - * PERSIST AND NOT TRANSIENT, and that is the whole reason this is not a debug probe: a transient - * buffer is liveness-analysed and may share storage with any other transient, so an accumulator - * declared transient would be overwritten between the launches it is meant to sum. + * The accumulator must be PERSIST: a transient buffer may share storage with other transients + * and would be overwritten between the launches it sums. * - * THE CONSUMER IS ANOTHER PROCESS. rad-convert reads these files; the engine writes them. That - * is not an architectural preference but the only order that works -- GPTQ needs the Hessian of - * a layer's real input, which needs the model running, and a container is written before it can - * be served. The bootstrap is: convert with plain absmax, serve THAT, calibrate on it, convert - * again with the Hessians. A second moment is robust to the small perturbation the first - * container's own error puts on the activation. + * rad-convert reads these files in a separate process, because GPTQ needs the Hessian of a + * layer's real input and so a running model. The bootstrap is: convert with plain absmax, serve + * that, calibrate on it, convert again with the Hessians. The second moment is robust to the + * first container's small quantisation error. * - * PER RANK, AND THE CONSUMER SUMS. Under expert parallelism a rank's `down` input is only the - * tokens routed to ITS experts, so no single rank holds the layer's distribution. Its `gate_up` - * input is the whole token set on every rank, so summing those double-counts by `world` -- which - * is a positive scale on H, and GPTQ is invariant to one (the damping is a fraction of the trace - * and the update uses ratios). So one rule, sum everything, and the gate_up case is harmless. */ + * Files are per rank and the consumer sums them. Under expert parallelism a rank's `down` input + * covers only its own experts' tokens. `gate_up` input is the full token set on every rank, so + * the sum scales H by `world`; GPTQ is invariant to a positive scale (damping is a fraction of + * the trace and the update uses ratios). */ inline const char* calib_dir() { static const char* d = std::getenv("RADIANCE_CALIB_DIR"); return d && *d ? d : nullptr; } -/* The token count at which the tap dumps and switches itself off. Off by default in the sense - * that calib_dir() gates it; this only says how much is enough. */ +/* Token count at which the tap dumps and switches itself off (RADIANCE_CALIB_TOKENS, default + * 65536). Whether the tap runs at all is calib_dir()'s decision. */ inline long long calib_target() { static const long long n = [] { const char* s = std::getenv("RADIANCE_CALIB_TOKENS"); @@ -149,12 +144,11 @@ inline long long calib_target() { * weight's kernel multiplies * uint32_t pad * - * `rows` is not a normaliser: nothing downstream divides by it, because H is used only up to a - * positive scale. It is there so a reader can tell a full calibration from one that was killed - * early -- and, for one expert's file (CalibExperts), an expert the corpus barely routed to from - * one it exercised: libquant reads a per-expert file only when it holds several times K rows. - * `domain` is what the tap actually summed, so a reader quantising in another one -- a rotated - * recipe over a bf16 model's Hessian -- brings the file there itself (libquant's calib_sum). */ + * `rows` is not a normaliser (H is used only up to a positive scale). It tells a full + * calibration from a killed one, and for a per-expert file (CalibExperts) a barely-routed expert + * from an exercised one: libquant reads a per-expert file only when it holds several times K + * rows. `domain` is what the tap summed; a reader quantising in another domain converts the file + * itself (libquant's calib_sum). */ inline bool calib_write_host(const float* h, int64_t k, long long rows, const char* what, uint32_t domain, int rank) { const char* dir = calib_dir(); @@ -194,9 +188,8 @@ inline bool calib_write(RadCtx* c, rad_buf b, int64_t k, long long rows, const c return calib_write_host(h.data(), k, rows, what, domain, rad_rank(c)); } -/* A pinned host buffer of at least `bytes`, one a rank and held for the life of the process, so a - * tap that brings a scratch back every pass copies it at the link's speed and not a pageable - * copy's. Null, said once, when the allocation fails. */ +/* A pinned host buffer of at least `bytes`, one per rank, held for the process lifetime, so a tap + * that copies a scratch back every pass runs at link speed. Null (and logged) on failure. */ inline float* calib_staging(RadCtx* c, int64_t bytes) { static std::mutex mu; static std::map> per_rank; @@ -212,21 +205,18 @@ inline float* calib_staging(RadCtx* c, int64_t bytes) { return (float*)s.first; } -/* ONE HESSIAN AN EXPERT, which is what a routed expert's `down` projection needs and the layer's - * pooled Gram is not. That projection's input is the expert's OWN intermediate units: channel i - * of one expert has nothing to do with channel i of another, so a Gram summed over the layer's - * experts describes none of them. It is dominated by whichever expert carries the most energy -- - * on Qwen3.8-Flash-Next one expert holds a quarter of some layers' -- and GPTQ fitted to it spends - * every other expert's error budget on that expert's channels. +/* One Hessian per expert, for a routed expert's `down` projection. Its input is the expert's own + * intermediate units, so channel i means something different in each expert and a pooled Gram + * describes none of them; it is dominated by the highest-energy expert (a quarter of some layers' + * energy on Qwen3.8-Flash-Next), and GPTQ fitted to it spends every expert's error budget there. * - * ON THE HOST, because the card has no room for it: 640^2 f32 for each of 256 experts a rank is - * 419 MB a layer, 20 GB over 48. A pass sums each expert's rows into one layer-sized scratch on - * the card; the scratch comes back through calib_staging() and its upper triangles are added - * here, packed -- a Gram is symmetric, so half the bytes, 10 GB a rank for that model. The cost is - * a stream sync a layer, which a calibration run reading its experts from disk does not notice. + * Kept on the host: 640^2 f32 for 256 experts per rank is 419 MB a layer, 20 GB over 48 layers. + * A pass sums each expert's rows into one layer-sized device scratch, which comes back through + * calib_staging() and is added here as packed upper triangles (half the bytes, 10 GB per rank for + * that model). The cost is one stream sync per layer. * - * Accumulated in f32: each pass adds one partial sum an expert, so a 10M-token corpus is a few - * hundred adds deep, and the consumer damps H by a percent of its trace. */ + * f32 accumulation suffices: each pass adds one partial sum per expert, so a 10M-token corpus is + * a few hundred adds deep, and the consumer damps H by a percent of its trace. */ struct CalibExperts { int64_t ne = 0, k = 0; std::vector acc; /* `ne` upper triangles of k*(k+1)/2, row by row */ @@ -239,7 +229,7 @@ struct CalibExperts { rows.assign((size_t)ne, 0); } - /* `full` is `ne` row-major k x k Grams, back to back -- the scratch as the card wrote it. */ + /* `full` is `ne` row-major k x k Grams back to back, as the device scratch holds them. */ void add(const float* full) { const int64_t tri = k * (k + 1) / 2; const unsigned hw = std::thread::hardware_concurrency(); @@ -270,9 +260,9 @@ struct CalibExperts { } } - /* One file an expert, `.`: the weight it will pack minus `.weight`, which - * is the name libquant looks for before the pooled ``. Every expert gets one, a - * never-routed expert's saying `rows` 0. */ + /* One file per expert, `.`, where stem is the packed weight's name minus + * `.weight`; libquant looks for it before the pooled ``. A never-routed expert's file + * has `rows` 0. */ bool write(const char* stem, int64_t expert_base, uint32_t domain, int rank) const { std::vector h((size_t)(k * k)); bool ok = true; @@ -287,12 +277,12 @@ struct CalibExperts { }; /* ================================================================== names */ -/* Declared names outlive the call that built them -- the weight manifest, the graph dump and the - * checkpoint name map all hold the pointer. Interning in a deque keeps every c_str() stable for - * the life of the plugin, which a vector would not (it reallocates). +/* Declared names outlive the call that built them (the weight manifest, graph dump and name map + * hold the pointer). A deque keeps every c_str() stable for the plugin's life; a vector would + * reallocate. * - * The scope prefix comes from RadBuildCtx: a drafter or an encoder tower declared into the same - * builder must not collide with the language model's names (spec §10, §11). */ + * The scope prefix comes from RadBuildCtx, so a drafter or encoder tower in the same builder does + * not collide with the language model's names (spec §10, §11). */ class Names { public: explicit Names(const char* scope = "") @@ -318,71 +308,28 @@ private: std::string scope_; }; -/* Errors are values. Declare walks a long list and any step of it can refuse; this propagates the - * first refusal without an early-return ladder swallowing the reason. */ +/* Returns the first negative status from a declare step. */ #define RAD_ARCH_TRY(expr) do { int _s = (expr); if (_s < 0) return _s; } while (0) /* ================================================================== C++-side decl helpers */ -/* rad_group_layer() and friends are C compound literals, which compile in C++ only as a GNU - * extension -- rad_builder.h says so and points here. A named function also reads better in an - * initialiser list than a cast-shaped macro does. */ +/* C++ forms of rad_group_layer() and friends, which are C compound literals (a GNU extension in + * C++; rad_builder.h points here). */ inline RadWeightGroup grp_model() { RadWeightGroup g{}; g.layer = -1; g.expert = -1; return g; } inline RadWeightGroup grp_layer(int l) { RadWeightGroup g{}; g.layer = l; g.expert = -1; return g; } inline RadWeightGroup grp_expert(int l, int e) { RadWeightGroup g{}; g.layer = l; g.expert = e; return g; } -/* ...AND THE SLOT, WHICH IS NOT OPTIONAL FOR AN EXPERT WITH MORE THAN ONE TENSOR. The container - * writes a layer's experts as fixed-stride units and checks that each unit's slots arrive - * 0..n-1 (core/format/radfile.cpp, check_unit_invariant) -- so two tensors of one expert that - * both leave `slot` at 0 are refused by name at convert time. A routed fp8 expert has four: the - * gate_up codes, their scale plane, the down codes and theirs. */ +/* An expert with more than one tensor needs a slot per tensor. The container writes a layer's + * experts as fixed-stride units whose slots must arrive 0..n-1 (core/format/radfile.cpp, + * check_unit_invariant); two tensors both at slot 0 are refused at convert time. A routed fp8 + * expert has four: gate_up codes, their scales, down codes, their scales. */ inline RadWeightGroup grp_expert_slot(int l, int e, int s) { RadWeightGroup g{}; g.layer = l; g.expert = e; g.slot = s; return g; } -/* `row_parts` is rows of THIS RANK per stacked projection, see RadWeightDecl. A single part is - * the same thing as none, so it is not recorded and the load path stays on its plain-rows - * branch. The pointer form exists because the fp8 linear derives its scale plane's parts by - * dividing the weight's, which an initializer_list cannot express. */ -inline rad_weight decl_w_n(RadBuilder* b, const char* name, uint32_t dtype, - std::initializer_list shape, - int access, int shard, RadWeightGroup group, int optional, - const int64_t* row_parts, int n_row_parts) { - RadWeightDecl d{}; - d.dtype = dtype; - d.rank = (uint32_t)shape.size(); - int i = 0; - for (int64_t s : shape) d.shape[i++] = s; - d.access = access; - d.shard = shard; - d.group = group; - d.optional = optional; - if (row_parts && n_row_parts > 1) { - d.n_row_parts = n_row_parts < RAD_MAX_ROW_PARTS ? n_row_parts : RAD_MAX_ROW_PARTS; - for (int j = 0; j < d.n_row_parts; ++j) d.row_parts[j] = row_parts[j]; - } - return rad_decl_weight(b, name, &d); -} - -inline rad_weight decl_w(RadBuilder* b, const char* name, uint32_t dtype, - std::initializer_list shape, - int access, int shard, RadWeightGroup group, int optional = 0, - std::initializer_list row_parts = {}) { - int64_t p[RAD_MAX_ROW_PARTS] = {0}; - int n = 0; - for (int64_t v : row_parts) if (n < RAD_MAX_ROW_PARTS) p[n++] = v; - return decl_w_n(b, name, dtype, shape, access, shard, group, optional, p, n); -} - -/* A VIEW: `planes` of the logical weight `source` (null: the weight named `name` itself), declared - * at what they select -- one plane's own dtype and extents, several planes' codes dtype and the - * logical extents (RadWeightDecl::source, spec §4.3). A block-fp8 linear is ONE stored weight - * that gemm_nt_q takes as two operands, so it is declared twice over the same source: its codes - * as `.weight` and its scales as `.scale`, `source` = `.weight`. Every view of - * a weight takes the weight's movement group. */ -inline rad_weight decl_view(RadBuilder* b, const char* name, const char* source, - const char* planes, uint32_t dtype, - std::initializer_list shape, int access, int shard, - RadWeightGroup group, const int64_t* row_parts = nullptr, - int n_row_parts = 0) { +/* `row_parts` is this rank's rows per stacked projection (RadWeightDecl). A single part equals + * none and is not recorded, keeping the load path on its plain-rows branch. */ +inline RadWeightDecl weight_decl(uint32_t dtype, std::initializer_list shape, int access, + int shard, RadWeightGroup group, const int64_t* row_parts, + int n_row_parts) { RadWeightDecl d{}; d.dtype = dtype; d.rank = (uint32_t)shape.size(); @@ -395,20 +342,53 @@ inline rad_weight decl_view(RadBuilder* b, const char* name, const char* source, d.n_row_parts = n_row_parts < RAD_MAX_ROW_PARTS ? n_row_parts : RAD_MAX_ROW_PARTS; for (int j = 0; j < d.n_row_parts; ++j) d.row_parts[j] = row_parts[j]; } + return d; +} + +/* The pointer form of decl_w's row parts, for a caller that derives them (the fp8 linear divides + * its weight's parts for the scale plane). */ +inline rad_weight decl_w_n(RadBuilder* b, const char* name, uint32_t dtype, + std::initializer_list shape, + int access, int shard, RadWeightGroup group, int optional, + const int64_t* row_parts, int n_row_parts) { + RadWeightDecl d = weight_decl(dtype, shape, access, shard, group, row_parts, n_row_parts); + d.optional = optional; + return rad_decl_weight(b, name, &d); +} + +inline rad_weight decl_w(RadBuilder* b, const char* name, uint32_t dtype, + std::initializer_list shape, + int access, int shard, RadWeightGroup group, int optional = 0, + std::initializer_list row_parts = {}) { + return decl_w_n(b, name, dtype, shape, access, shard, group, optional, row_parts.begin(), + (int)row_parts.size()); +} + +/* A view: `planes` of the logical weight `source` (null: the weight named `name`), declared at + * what they select: one plane's own dtype and extents, or for several planes the codes dtype and + * the logical extents (RadWeightDecl::source, spec §4.3). A block-fp8 linear is one stored weight + * that gemm_nt_q takes as two operands, so it is declared twice over `.weight`: codes as + * `.weight`, scales as `.scale`. Every view takes the weight's movement group. */ +inline rad_weight decl_view(RadBuilder* b, const char* name, const char* source, + const char* planes, uint32_t dtype, + std::initializer_list shape, int access, int shard, + RadWeightGroup group, const int64_t* row_parts = nullptr, + int n_row_parts = 0) { + RadWeightDecl d = weight_decl(dtype, shape, access, shard, group, row_parts, n_row_parts); d.source = source; d.planes = planes; return rad_decl_weight(b, name, &d); } -/* What the model holds `source` as -- its encoding, from the container, the checkpoint, or the - * recipe rad-convert is applying -- or false when nothing is known about it: a builder with no - * model behind it, or a name the name map has not been told about yet (declare the map first). */ +/* The encoding `source` is held in (from the container, the checkpoint, or rad-convert's recipe), + * or false when unknown: a builder with no model behind it, or a name not yet in the name map + * (declare the map first). */ inline bool weight_enc(RadBuilder* b, const char* source, RadEncoding* out) { return rad_weight_encoding(b, source, out, nullptr, nullptr) == RAD_OK; } -/* The dtype a view of every plane of `source` is declared at: the codes', when the encoding is - * known, else `dflt` -- the dtype a weight with nothing behind it is read as. */ +/* The dtype for a view of all of `source`'s planes: the codes' dtype when the encoding is known, + * else `dflt`. */ inline uint32_t weight_codes_dtype(RadBuilder* b, const char* source, uint32_t dflt) { RadEncoding e{}; return weight_enc(b, source, &e) && e.n_planes > 0 ? e.plane[0].dtype : dflt; @@ -427,8 +407,8 @@ inline rad_buf decl_b(RadBuilder* b, const char* name, uint32_t dtype, return rad_decl_buffer(b, name, &d); } -/* Every map starts with src_index all -1: "the whole tensor", which is what all but the stacked - * expert case wants. Zero would mean sub-tensor 0 of every source, which is a silently wrong map. */ +/* src_index starts at -1, "the whole tensor"; 0 would silently select sub-tensor 0 of every + * source. */ inline RadNameMap map_base(const char* declared, int mode) { RadNameMap m{}; m.declared = declared; @@ -445,10 +425,9 @@ inline int map_copy(RadBuilder* b, const char* declared, const char* src) { return rad_decl_name_map(b, &m); } -/* A checkpoint tensor copied through, with alternatives: the first source the container actually - * holds wins. This is how a tied lm_head is expressed -- Qwen3 0.6B and 1.7B ship no - * output.weight and the embedding table serves as both, while 8B and up ship one. Without it the - * plugin would need two builds of the same architecture. */ +/* A copy with an alternative source; the first one the container holds wins. Expresses a tied + * lm_head: Qwen3 0.6B and 1.7B ship no output.weight and reuse the embedding, 8B and up ship + * one. */ inline int map_copy_alt(RadBuilder* b, const char* declared, const char* a, const char* c) { RadNameMap m = map_base(declared, RAD_MAP_COPY); m.n_src = 2; @@ -458,10 +437,8 @@ inline int map_copy_alt(RadBuilder* b, const char* declared, const char* a, cons } /* One expert's slice of a stacked checkpoint tensor. GGUF stores a MoE layer's experts as one - * ffn_gate_exps of shape [.., n_expert] while placement needs one declared weight per expert, - * because the movement unit is an expert and not a tensor (spec §4.1). src_index carries the - * expert; without it the index would survive only inside the declared name, as a convention - * rad-convert would have to parse. */ + * ffn_gate_exps [.., n_expert], while placement moves one expert at a time and so needs one + * declared weight per expert (spec §4.2). src_index carries the expert index explicitly. */ inline int map_slice(RadBuilder* b, const char* declared, const char* src, int index) { RadNameMap m = map_base(declared, RAD_MAP_COPY); m.n_src = 1; @@ -481,11 +458,9 @@ inline int map_slice_concat(RadBuilder* b, const char* declared, return rad_decl_name_map(b, &m); } -/* A convert-time fusion: q/k/v into one qkv, gate and up into one gate_up. The plugin is the only - * component that knows both sides, and rad-convert reads the map from it (spec §2.4). The fusion - * is worth a comment on its cost: it buys one GEMM launch instead of three and one movement unit - * instead of three, and it costs the ability to place q, k and v on different tiers, which - * nothing wants to do. */ +/* A convert-time fusion: q/k/v into qkv, gate and up into gate_up. Only the plugin knows both + * sides, and rad-convert reads the map from it (spec §2.4). One GEMM launch and one movement unit + * instead of three, at the cost of placing q, k and v on different tiers. */ inline int map_concat(RadBuilder* b, const char* declared, std::initializer_list src, int dim = 0) { RadNameMap m = map_base(declared, RAD_MAP_CONCAT); @@ -496,15 +471,13 @@ inline int map_concat(RadBuilder* b, const char* declared, std::initializer_list return rad_decl_name_map(b, &m); } -/* ONE LOGICAL TENSOR THE CHECKPOINT STORES AS N SHARDS, named `` for i in - * [0, n). Qwen3.8-Flash-Next's n-gram embedding is 320,001,536 rows in 128 tensors called - * `...ngram_embedding.shard_0.weight` ... `shard_127.weight`, which is thirty times what - * RadNameMap's `src[8]` holds. +/* One logical tensor stored as n shards named ``, i in [0, n). Qwen3.8-Flash- + * Next's n-gram embedding is 320,001,536 rows in 128 tensors (`...ngram_embedding.shard_0.weight` + * .. `shard_127.weight`), far more than RadNameMap's `src[8]`. * - * So this emits ceil(n/8) CONCAT maps and the core joins them in call order -- see the merge rule - * in core/build/rad_builder.cpp for why the pieces are the answer rather than a bigger array. The - * ORDER IS THE CONCATENATION and shard 0 must come first: a hashed row id addresses the whole - * table and a permuted table is a model that loads, runs, and looks up the wrong embeddings. + * Emits ceil(n/8) CONCAT maps, which the core joins in call order (merge rule in + * core/build/rad_builder.cpp). Call order is the concatenation order and shard 0 must come first: + * hashed row ids address the whole table, and a permuted table silently looks up wrong rows. * * Returns the first refusal, or RAD_OK. */ inline int map_concat_shards(RadBuilder* b, const char* declared, const char* prefix, @@ -526,14 +499,10 @@ inline int map_concat_shards(RadBuilder* b, const char* declared, const char* pr } /* ================================================================== buffer liveness */ -/* An op's WEIGHT operands are named at declare; its BUFFER operands are not, and without them a - * transient has no declared use and the planner must assume it live for the whole program -- - * sound, because a plugin may issue any handle in any order, and as wasteful as it sounds. - * - * So every op this library emits states its read and write sets. Returning the handle rather than - * a status is what keeps the declaration one statement: a refusal from rad_op_reads is recorded by - * the builder, with the op named, and surfaces in declare's final report -- the same way a refusal - * from rad_decl_op does. */ +/* States an op's buffer read and write sets. Weight operands are named at declare but buffer + * operands are not, and a transient with no declared use must be assumed live for the whole + * program. Returns the handle so a declaration stays one statement; a refusal from rad_op_reads + * is recorded by the builder with the op named and surfaces in declare's final report. */ inline rad_op rw(RadBuilder* b, rad_op h, std::initializer_list reads, std::initializer_list writes) { @@ -544,20 +513,13 @@ inline rad_op rw(RadBuilder* b, rad_op h, } /* ================================================================== geometry */ -/* Dimensions come from model metadata, so one plugin covers every size in a family. Everything - * here is ALREADY DIVIDED by world_size where it is sharded: the plugin declares divided - * dimensions and emits the collectives itself, because a sharding inference pass is a compiler - * pass whose failure mode is a model that produces fluent wrong text on a rank count nobody - * tested (spec §9). */ -/* THE PAGED BLOCK, IN TOKENS. `attn_paged` declares `block_size` RAD_DERIVED -- a value the - * KERNEL supplies -- and libr4d's rows all carry C_EQ("block_size", 16), so on the shipped path - * this is the value that would have been derived anyway and pinning it changes no resolution. - * - * It has to be pinned because DERIVED ONLY WORKS WHEN SOMETHING DERIVES IT. A geometry libr4d has - * no attention kernel for -- Qwen3.5-0.8B is head_dim 256 at gqa 4, and libr4d has 256/6 and - * 128/4 -- resolves to libref, which serves any block size and therefore names none; the KV - * group then cannot be sized and declare refuses the model by name. The block size is a property - * of the CACHE the model is asking for, so the model is the right place to say it. */ +/* Dimensions come from model metadata, so one plugin covers every size in a family. Sharded + * dimensions are already divided by world_size: the plugin declares divided dimensions and emits + * the collectives itself rather than relying on a sharding inference pass (spec §9). */ +/* The paged KV block, in tokens. `attn_paged` declares `block_size` RAD_DERIVED (kernel-supplied) + * and every libr4d row has C_EQ("block_size", 16), so pinning it changes nothing there. It must be + * pinned for geometries that resolve to libref (e.g. Qwen3.5-0.8B, head_dim 256 at gqa 4), which + * serves any block size and so derives none; the KV group could not be sized. */ enum { RAD_KV_BLOCK = 16 }; struct Geom { @@ -571,21 +533,17 @@ struct Geom { int64_t n_head_kv = 0; /* per rank */ int64_t n_head_all = 0; int64_t n_head_kv_all = 0; - /* THIS RANK'S FIRST KV ROW inside the checkpoint's UNSHARDED k/v projection rows, used only - * when the KV heads are replicated over ranks instead of split (world > n_head_kv_all, see - * geom_from). It is in container rows, the same unit a LinearFP8 span takes, so a block that - * declares a row-sharded k/v passes it straight through as `span_lo`. Zero on every split - * deployment, which is what keeps TP2 reading the projection exactly as it always did. */ + /* This rank's first row in the checkpoint's unsharded k/v projection, in container rows (the + * unit of a LinearFP8 span, passed as `span_lo`). Nonzero when KV heads are replicated over + * ranks (world > n_head_kv_all) or under a smaller attention world; zero on a plain split. */ int64_t kv_off = 0; - /* THE ATTENTION WORLD. A world size the KV head count neither divides nor is a multiple of - * -- three ranks over Flash-Next's two KV heads -- serves attention on the largest multiple - * of the head count below it (`attn_world`, here 2: split, or replicated when that is still - * above the count) and the remaining ranks are ATTENTION-ZERO: they declare the same heads and - * the same program as their peers, compute no attention (a `fill` of the block's output and - * a zero KV group, rad_kv_group_zero) and add exactly zero to the reduce. `attn_rank` is this - * rank's index inside the attention world (an attention-zero rank clamps to the last). When - * attn_world == world nothing here is used and every block declares as it always did. Set - * only for a plugin that asks for it (geom_from's `attn_world_ok`). */ + /* The attention world. When world neither divides nor is a multiple of the KV head count + * (three ranks over Flash-Next's two KV heads), attention runs on the largest multiple of the + * head count below world (`attn_world`; split, or replicated if still above the count). The + * remaining ranks are attention-zero: same heads and program as their peers, but they compute + * no attention (a `fill` of the block's output and a zero KV group, rad_kv_group_zero) and + * add zero to the reduce. `attn_rank` is the index inside the attention world (attention-zero + * ranks clamp to the last). Only set for plugins that pass geom_from's `attn_world_ok`. */ int attn_world = 1; int attn_rank = 0; bool attn_zero = false; @@ -595,63 +553,52 @@ struct Geom { int64_t max_seqs = 0; int64_t max_ctx = 0; int max_spec = 0; - /* The most rows the sampler can want in one step: one per sequence, or one per draft position - * per sequence at a speculative verify. It bounds the logits buffer, which at a 248K vocab is - * the difference between 63 MiB and 8 GiB. */ + /* Most rows the sampler can want in one step: one per sequence, or one per draft position per + * sequence at a speculative verify. Bounds the logits buffer (at a 248K vocab, 63 MiB rather + * than 8 GiB for max_tok rows). */ int64_t max_logit_rows = 0; int rank = 0; int world = 1; - /* 1 = the exact all-reduce, 0 = this deployment accepts a lossy wire. Straight through to - * every `all_reduce` this library emits; RadBuildCtx says what it costs and buys. */ + /* 1 = exact all-reduce, 0 = a lossy wire is accepted. Passed to every `all_reduce` this + * library emits; RadBuildCtx describes the trade-off. */ int wire_exact = 1; - /* The byte floor under which the lossy wire is refused and the exact kernel serves the - * message anyway. Straight through to `all_reduce`'s `min_bytes`; 0 leaves the choice to - * the kernel plugin, which has the measured default. */ + /* Messages below this many bytes use the exact all-reduce even with a lossy wire. Passed as + * `all_reduce`'s `min_bytes`; 0 leaves the default to the kernel plugin. */ int64_t wire_min_bytes = 0; float eps = 1e-6f; /* GemmaRMSNorm's `1 +`. Qwen3.5, Qwen3-Next and Gemma normalise with `x_hat * (1 + w)` and - * store `w` around 0.1, not around 1.0 -- so reading the gain as a plain RMSNorm gain shrinks - * every normed activation by five to ten times, at every norm, in every layer. It is a - * property of the ARCHITECTURE and not of a block, which is why it lives here: `rmsnorm`, - * `rmsnorm_add`, `qk_norm_rope_gate` and `rmsnorm_had_quant_i8` all carry a `wadd` parameter - * for it (libref/ref_registry.cpp), every block that declares one passes this, and a - * family whose norms are plain leaves it at zero. + * store `w` near 0.1, so reading it as a plain gain shrinks every normed activation 5-10x. An + * architecture property: `rmsnorm`, `rmsnorm_add`, `qk_norm_rope_gate` and + * `rmsnorm_had_quant_i8` take a `wadd` parameter (libref/ref_registry.cpp) and every block + * passes this; plain-norm families leave it 0. * - * NOT the gated delta net's own `ssm_norm`: RMSNormGated is a plain RMS norm in this family - * too, its gains are around 0.88 in the checkpoint, and `gdn_gated_rmsnorm` has no such - * parameter. Two conventions in one model, which is exactly why this is not a build flag. */ + * Not used by the gated delta net's `ssm_norm`: RMSNormGated is a plain RMS norm in these + * families too (gains near 0.88) and `gdn_gated_rmsnorm` has no such parameter. */ float wadd = 0.0f; - /* The same question for the per-head q/k norms, separately: they are a different - * tensor with a different distribution (this checkpoint's are PARTLY NEGATIVE, which - * only `1 + w` explains) and a family could answer the two differently. */ + /* The same for the per-head q/k norms, set separately: a different tensor (partly negative + * gains in this family, which only `1 + w` explains) that a family could treat differently. */ float wadd_qk = 0.0f; float theta = 1e6f; float rope_scale = 1.0f; RadYarn yarn; - /* M-RoPE: the checkpoint's `mrope_section`, when it has one. A model whose rotary has several - * position components declares `rope` with `rope_mode` and these sections and hands it - * RadBatch::rope_pos; empty, the rotary is one-component NeoX over `positions`. Stored here - * rather than pointed at, because the container's strings are not guaranteed to outlive - * declare. */ + /* M-RoPE: the checkpoint's `mrope_section`, if any. A multi-component rotary declares `rope` + * with `rope_mode` and these sections and passes RadBatch::rope_pos; empty means + * one-component NeoX over `positions`. Copied, because the container's strings may not + * outlive declare. */ bool rope_mc = false; char rope_mode[8] = "neox"; char rope_sections[24] = ""; const char* dtype = "bf16"; /* the OPERAND COMBINATION, spec §2.3's dtype key */ uint32_t act_dtype = RAD_BF16; /* what activation buffers are made of */ - /* THE KV CACHE'S OWN WIDTH, and it is separate from `dtype` because it is a separate decision: - * `dtype` says what the WEIGHTS are and follows the checkpoint, while this follows the cache - * and is a deployment choice the checkpoint has no opinion about. They were one field, which - * read as "the cache is bf16 because the weights are fp8-with-bf16-activations" -- a sentence - * that is true of this checkpoint and is not a rule. Whatever this says must be the spelling - * `rad_dtype_name` gives, because the attention and kv_store rows band on it verbatim. */ + /* The KV cache dtype, separate from `dtype`: weights follow the checkpoint, the cache is a + * deployment choice. Must be spelled as `rad_dtype_name` gives it, because the attention and + * kv_store rows band on it verbatim. */ const char* kv_dtype = "bf16"; - /* THE LINEARS ARE PLAIN bf16 WEIGHTS, read by `gemm_nt` over the bf16 activation, in a model - * whose blocks are the fp8 family's (rad_fp8.h). A checkpoint served as it ships -- a dense bf16 - * release, converted without a quantising recipe -- has no scale planes and no use for E4M3 - * activations, so in this mode the producers in front of a linear quantise nothing and declare - * no codes: an `ActFP8` is its bf16 plane alone. It is the MODEL's answer and not a linear's, - * because the producer and its consumers have to agree on it; the plugin reads it off a trunk - * weight's encoding and every linear checks its own against it. */ + /* The linears are plain bf16 weights read by `gemm_nt`, in a model built from the fp8 blocks + * (rad_fp8.h): a dense bf16 checkpoint converted without a quantising recipe. Producers in + * front of a linear then quantise nothing, so an `ActFP8` is its bf16 plane alone. A model-wide + * setting because producers and consumers must agree; the plugin reads it off a trunk weight's + * encoding and every linear checks its own against it. */ bool w_bf16 = false; int64_t q_dim() const { return n_head * head_dim; } @@ -660,20 +607,13 @@ struct Geom { int64_t gqa() const { return n_head_kv ? n_head / n_head_kv : 0; } }; - -/* THE KV CACHE'S WIDTH, RESOLVED ONCE FOR EVERY ARCHITECTURE. RadBuildCtx::kv_dtype is - * --kv-cache-dtype; RAD_DT_INVALID means the operator did not state one and the plugin's own - * default stands. Every architecture in this tree passes RAD_BF16 as that default. - * - * It is one flag on the build context rather than a per-plugin environment switch: a switch read - * at declare is invisible in the startup log and gives "is this cache fp8" a different answer per - * architecture. It changes what the model computes, so it is a flag. */ +/* The KV cache dtype: RadBuildCtx::kv_dtype (--kv-cache-dtype), or `dflt` when it is + * RAD_DT_INVALID (not given). Every architecture in this tree passes RAD_BF16 as the default. */ static inline uint32_t rad_kv_cache_dtype(const RadBuildCtx* c, uint32_t dflt) { return (c && c->kv_dtype != RAD_DT_INVALID) ? (uint32_t)c->kv_dtype : dflt; } -/* Divide, refusing rather than rounding. A rank count that does not divide the head count is not - * a configuration to approximate: it is a configuration to reject at declare, by name, before any - * weight is mapped. */ +/* Divide, refusing (with a message naming `what`) rather than rounding, before any weight is + * mapped. */ inline int divide_or_fail(int64_t v, int world, const char* what, int64_t* out) { if (world <= 0 || v % world != 0) { fprintf(stderr, "radiance: %s = %lld is not divisible by world_size = %d\n", @@ -684,23 +624,16 @@ inline int divide_or_fail(int64_t v, int world, const char* what, int64_t* out) return RAD_OK; } -/* The vocabulary is the one dimension that does not divide -- 151669 and 248320 are not multiples - * of anything convenient -- and refusing tensor parallel over an awkward vocab size would be - * absurd. So the last rank holds fewer rows. The sampler merges candidate sets rather than - * gathering full logits (spec §9, §13), so a ragged shard costs it nothing; a padded one would - * cost a fake token id that has to be masked everywhere forever. */ -/* THE VOCABULARY SPLIT: ceil(total / world) rows a rank, ROUNDED UP TO A WHOLE 128-ROW BLOCK, the - * last rank short. The block is RAD_FP8_BLOCK: a block-scaled fp8 lm_head is stored in 128x128 - * tiles and a row span that cuts a tile is refused (rad_weight_shard_span), so the cut has to land - * on one. At two ranks on 248320 or 151936 the rounding changes nothing -- both halves are block - * multiples -- and a vocabulary the world divides is never rounded; at three it is what makes the - * head shardable at all (248320 / 3 = 82773.3; the ranks take 82816, 82816, 82688). core/engine.cpp - * RESTATES this rule and checks it against the width the plugin declared; the two must move together. */ +/* The vocabulary split. The vocab need not divide by world (151669, 248320), so the last rank + * holds fewer rows. The sampler merges candidate sets rather than gathering full logits (spec §9, + * §13), so a ragged shard is free, while padding would need a fake token id masked everywhere. + * + * A vocabulary world divides keeps the even share. Otherwise each rank takes ceil(total / world) + * rounded up to a 128-row block (RAD_FP8_BLOCK), the last rank short: a block-scaled fp8 lm_head + * is stored in 128x128 tiles and a row span that cuts a tile is refused (rad_weight_shard_span). + * Example: 248320 over 3 ranks gives 82816, 82816, 82688. core/engine.cpp restates this rule and + * checks it against the declared width; keep the two in step. */ inline int64_t vocab_per_rank(int64_t total, int world) { - /* A vocabulary the world divides keeps the even share, whatever the world: every container - * served today splits that way (248320 at 2 and 4, 151936 at 2 -- the last halves mid-block and - * is served with an untiled head). Only a vocabulary the world does NOT divide takes the - * block-aligned ceil, which is what makes a tiled head shardable at all. */ if (total % world == 0) return total / world; const int64_t per = (total + world - 1) / world; return (per + 127) / 128 * 128; @@ -717,11 +650,9 @@ inline int64_t shard_begin(int64_t total, int world, int rank) { return beg < total ? beg : total; } -/* A container-header integer under either of the two spellings a key reaches us in: the GGUF one - * (`qwen35.ssm.state_size`) and the HuggingFace one (`linear_key_head_dim`). One plugin serves a - * .rad converted from either source, and the alternative is a second plugin that differs only in - * its string literals. `found` says whether the value was read or defaulted, because a geometry - * that silently defaults is a model that silently becomes a different model. */ +/* A container-header integer under its GGUF (`qwen35.ssm.state_size`) or HuggingFace + * (`linear_key_head_dim`) spelling, so one plugin serves a .rad converted from either. `found` + * reports whether the value was read or defaulted, so a caller can refuse a silent default. */ inline long long meta_int2(const RadModelMeta* m, const char* gguf_key, const char* hf_key, long long dflt, bool* found = nullptr) { const long long sentinel = -0x7FFFFFFFll; @@ -731,15 +662,130 @@ inline long long meta_int2(const RadModelMeta* m, const char* gguf_key, const ch return v == sentinel ? dflt : v; } -/* THE REMAINDER-FIRST ORDER OF THE RANKS. What does not divide evenly over the world and is a - * HEAD'S worth of work -- the extra delta-net head -- goes to the ranks with NO attention first: - * they pay nothing for attention (rad_block_attn_gated_fp8.h: one fill) and keep no attention - * cache (rad_kv_group_zero), so they have the time for it, and the rank that held the extra head - * AND attention -- the step's slowest -- is lighter for it. An expert's extra block is not a - * head's worth (qwen4exp_fp8.cpp says why it stays on the rotation). This is a rank's PLACE in - * that order: the attention-zero ranks take places 0..n-1 whatever `parity` is, and the attention - * ranks follow in the rotation by `parity` -- so where no rank is attention-zero (every world the - * heads divide) the place is exactly (rank - parity) mod world and every cut is the even one. */ +/* The key a text-model value is under: `
text_config.`, where a multimodal config nests
+ * its language model, when the container has it, else `
`. `pre` is "" for the model and
+ * "draft." for a drafter's config. */
+inline const char* meta_text_key(const RadModelMeta* m, const char* key, const char* pre,
+                                 char (&buf)[192]) {
+    std::snprintf(buf, sizeof buf, "%stext_config.%s", pre, key);
+    if (!rad_meta_gets(m, buf, nullptr)) std::snprintf(buf, sizeof buf, "%s%s", pre, key);
+    return buf;
+}
+inline long long meta_text_geti(const RadModelMeta* m, const char* key, long long dflt,
+                                const char* pre = "") {
+    char k[192];
+    return rad_meta_geti(m, meta_text_key(m, key, pre, k), dflt);
+}
+inline double meta_text_getf(const RadModelMeta* m, const char* key, double dflt,
+                             const char* pre = "") {
+    char k[192];
+    return rad_meta_getf(m, meta_text_key(m, key, pre, k), dflt);
+}
+inline const char* meta_text_gets(const RadModelMeta* m, const char* key, const char* dflt,
+                                  const char* pre = "") {
+    char k[192];
+    return rad_meta_gets(m, meta_text_key(m, key, pre, k), dflt);
+}
+
+/* ================================================================== config arrays */
+/* Calls fn(token, length) for each token of a flattened config array until fn returns false.
+ * rad-convert writes an array of scalars space-separated (core/format/checkpoint.cpp,
+ * flatten_json); commas, brackets and quotes also separate, for values written by hand. */
+template 
+inline void for_each_token(const char* s, F&& fn) {
+    if (!s) return;
+    auto sep = [](char ch) { return ch == ' ' || ch == ',' || ch == '[' || ch == ']' || ch == '"'; };
+    for (const char* p = s; *p;) {
+        while (*p && sep(*p)) ++p;
+        if (!*p) return;
+        const char* t = p;
+        while (*p && !sep(*p)) ++p;
+        if (!fn(t, (size_t)(p - t))) return;
+    }
+}
+
+inline bool token_is(const char* t, size_t n, const char* word) {
+    return std::strlen(word) == n && std::strncmp(t, word, n) == 0;
+}
+
+/* "1 10 20 30 39" -> the trunk layers a drafter taps, at most `max`. Out-of-range entries are
+ * dropped, not clamped: a drafter naming a layer this model lacks belongs to another target, and
+ * clamping would hide that. Parsing stops at the first token that is not a number. */
+inline int parse_layer_ids(const char* s, int64_t n_layer, int* out, int max) {
+    int n = 0;
+    for_each_token(s, [&](const char* t, size_t) {
+        if (n >= max) return false;
+        char* e = nullptr;
+        const long v = std::strtol(t, &e, 10);
+        if (e == t) return false;
+        if (v >= 0 && v < n_layer) out[n++] = (int)v;
+        return true;
+    });
+    return n;
+}
+
+/* A `layer_types` array as one flag per entry: 1 for any name in `one`, 0 for `zero`. Any other
+ * name is refused, naming `arch`. */
+inline int parse_layer_kinds(const char* arch, const char* s, std::initializer_list one,
+                             const char* zero, std::vector* out) {
+    out->clear();
+    int rc = RAD_OK;
+    for_each_token(s, [&](const char* t, size_t n) {
+        int k = token_is(t, n, zero) ? 0 : -1;
+        for (const char* w : one) if (token_is(t, n, w)) k = 1;
+        if (k < 0) {
+            fprintf(stderr, "radiance: %s: layer_types[%zu] is '%.*s'; known kinds are %s and %s\n",
+                    arch, out->size(), (int)n, t, *one.begin(), zero);
+            rc = RAD_E_UNSUPPORTED;
+            return false;
+        }
+        out->push_back(k);
+        return true;
+    });
+    return rc;
+}
+
+/* The hybrid trunk's interval rule (llama.cpp's): every `interval`-th layer is full attention, so
+ * with interval 4 layers 3, 7, ... are full and the rest linear. */
+inline bool is_full_attention(int64_t l, int64_t interval) {
+    return interval > 0 && (l + 1) % interval == 0;
+}
+
+/* Checks a container's `layer_types` (`s`, null or empty when it states none, as a GGUF-converted
+ * container does) against is_full_attention. The interval rule is not a property of the family,
+ * and a model built with the wrong layers linear still generates fluent text, so a disagreement is
+ * fatal. `full` lists the names of a full layer; entries past the trunk (an MTP block) are not
+ * compared. */
+inline int check_layer_schedule(const char* arch, const char* s, int64_t n_layer, int64_t interval,
+                                std::initializer_list full) {
+    if (!s || !*s) return RAD_OK;
+    std::vector kind;
+    RAD_ARCH_TRY(parse_layer_kinds(arch, s, full, "linear_attention", &kind));
+    if ((int64_t)kind.size() < n_layer) {
+        fprintf(stderr, "radiance: %s: layer_types names %zu layers and the model has %lld\n",
+                arch, kind.size(), (long long)n_layer);
+        return RAD_E_UNSUPPORTED;
+    }
+    for (int64_t l = 0; l < n_layer; ++l) {
+        const bool rule = is_full_attention(l, interval);
+        if ((kind[(size_t)l] != 0) != rule) {
+            fprintf(stderr, "radiance: %s: layer_types makes layer %lld %s and "
+                            "full_attention_interval %lld makes it %s; the layers are built by the "
+                            "interval\n", arch, (long long)l, rule ? "linear" : "full",
+                    (long long)interval, rule ? "full" : "linear");
+            return RAD_E_UNSUPPORTED;
+        }
+    }
+    return RAD_OK;
+}
+
+/* A rank's place in the remainder-first order. Head-sized work that does not divide evenly (the
+ * extra delta-net head) goes first to attention-zero ranks, which pay only a fill for attention
+ * (rad_block_attn_gated_fp8.h) and keep no attention cache, so the slowest rank is not also given
+ * the extra head. An expert's extra block is not head-sized and stays on the rotation
+ * (qwen4exp_fp8.cpp). Attention-zero ranks take places 0..n-1 regardless of `parity`; attention
+ * ranks follow, rotated by `parity`. With no attention-zero rank the place is
+ * (rank - parity) mod world. */
 inline int64_t remainder_place(const Geom& g, int rank, int parity) {
     const int nz = g.world - g.attn_world;
     if (rank >= g.attn_world) return rank - g.attn_world;
@@ -747,23 +793,23 @@ inline int64_t remainder_place(const Geom& g, int rank, int parity) {
     return nz + ((rank - parity) % aw + aw) % aw;
 }
 
-/* `arch_splits_ff`: the plugin divides the feed-forward width across the ranks ITSELF (qwen4exp:
- * the routed experts' width is cut by whole fp8 blocks, by parity, at any world up to the block
- * count). With it set, a width the world does not divide is left whole in g.n_ff and the plugin
- * takes its slice from there; without it the refusal stands, because for every other plugin g.n_ff
- * IS the per-rank width. A width that does divide is unaffected either way. */
-/* `attn_world`: the plugin's attention block serves a SMALLER ATTENTION WORLD (Geom::attn_world)
- * -- it declares the attention-zero rank's fill and zero KV group and spans the attention
- * projections by `attn_rank`. Only rad_block_attn_gated_fp8.h does. Without it a world the KV head
- * count neither divides nor is a multiple of is refused here, by name, rather than declared with
- * an even shard the block would then cut wrongly. */
+/* Fills `g` from model metadata and the build context.
+ *
+ * `arch_splits_ff`: the plugin splits the feed-forward width itself (qwen4exp cuts routed expert
+ * width by whole fp8 blocks, by parity). A width world does not divide is then left whole in
+ * g.n_ff for the plugin to slice; otherwise it is refused, since g.n_ff is the per-rank width.
+ *
+ * `attn_world_ok`: the plugin's attention block supports a smaller attention world
+ * (Geom::attn_world): it declares the attention-zero fill and zero KV group and spans projections
+ * by `attn_rank`. Only rad_block_attn_gated_fp8.h does. Otherwise a world the KV head count
+ * neither divides nor is a multiple of is refused. */
 inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
                      const char* dtype, uint32_t act_dtype, bool arch_splits_ff = false,
                      bool attn_world_ok = false) {
     if (!m || !c) return RAD_E_INVAL;
     if (c->is_draft) {
-        /* A drafter declared into this plugin would need a second set of per-rank handles and a
-         * second name-map namespace. Nothing unimplemented returns success (spec §17). */
+        /* A draft scope would need a second set of per-rank handles and name-map namespace; an
+         * unimplemented path never returns success (spec §17). */
         fprintf(stderr, "radiance: this plugin has no draft scope\n");
         return RAD_E_UNSUPPORTED;
     }
@@ -782,8 +828,8 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
     g.max_spec  = c->max_spec;
     g.max_logit_rows = c->max_seqs * (c->max_spec > 0 ? c->max_spec + 1 : 1);
     if (g.max_logit_rows > c->max_tok) g.max_logit_rows = c->max_tok;
-    /* The engine's KL mode reads a row at every prompt position (RadBuildCtx::max_out_rows), which
-     * is more rows than tokens: the sampler's own rows come first and repeat a scored one. */
+    /* KL mode reads a row at every prompt position plus the sampler's own rows, which repeat a
+     * scored one (RadBuildCtx::max_out_rows), so it can exceed the token count. */
     if (c->max_out_rows > g.max_logit_rows) g.max_logit_rows = c->max_out_rows;
     g.rank      = c->rank;
     g.world     = c->world_size ? c->world_size : 1;
@@ -812,9 +858,7 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
     if (g.n_layer <= 0 || g.n_embd <= 0 || g.head_dim <= 0 || g.n_head_all <= 0 ||
         g.n_ff_all <= 0 || g.n_vocab_all <= 0 || g.max_tok <= 0)
         return RAD_E_INVAL;
-    /* eps and theta are read, not defaulted. A container that omits them and gets 1e-6 and 1e6
-     * anyway is a container that silently becomes a different model, and the symptom is fluent
-     * wrong text. */
+    /* eps and theta are required, not defaulted: a wrong default yields fluent wrong text. */
     if (!(g.eps > 0.0f) || !(g.theta > 0.0f)) {
         fprintf(stderr, "radiance: container gives rms_eps=%g rope_theta=%g; both are required\n",
                 (double)g.eps, (double)g.theta);
@@ -822,9 +866,9 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
     }
 
     int s;
-    /* THE ATTENTION WORLD (see the field). Below the KV head count, or a multiple of it, it is the
-     * world and the two rules that follow run on the world as before. Otherwise it is the largest
-     * multiple of the head count under the world, and the ranks past it carry zero attention. */
+    /* The attention world (see Geom::attn_world): the world itself when it is at most the KV head
+     * count or a multiple of it, else the largest multiple below it, with the ranks past it
+     * attention-zero. */
     g.attn_world = g.world;
     g.attn_rank  = g.rank;
     g.attn_zero  = false;
@@ -839,27 +883,14 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
     }
     const int aw = g.attn_world, ar = g.attn_rank;
     if ((s = divide_or_fail(g.n_head_all, aw, "n_head", &g.n_head)) < 0) return s;
-    /* THE KV HEADS ARE REPLICATED WHEN THERE ARE NOT ENOUGH TO SPLIT. There is one row-span per KV
-     * head and no way to hand four ranks half a head, so `divide_or_fail` on n_head_kv is the
-     * wrong verb once world exceeds the head count -- the question is not rounding, it is whether
-     * the declaration is allowed to say one KV head per rank. It is, when world is a multiple of
-     * the KV head count: query heads 0-11 belong to KV head 0 and 12-23 to KV head 1, so ranks
-     * {0,1} need only KV head 0 and ranks {2,3} only KV head 1. Each rank then declares
-     * n_head_kv 1 and reads its own head's row-span of k/v, which `kv_off` locates; the attention
-     * declaration comes out at gqa 6 over a page of 4 instead of gqa 12 over a page of 2, and
-     * kv_dim(), gqa() and every block that reads them need no new branch because from here down a
-     * replicated rank and a split rank look the same.
-     *
-     * THE COST IS HONEST AND IT IS MEMORY, NOT MATH: the replicating ranks hold BYTE-IDENTICAL KV
-     * weights, a replicated read that costs no extra VRAM per rank versus the TP2 split it
-     * replaces (Flash-Next: 2 KV heads x 5120 x 256 rows read twice instead of once). What it buys
-     * is that world 4 is declarable at all.
-     *
-     * When world <= n_head_kv_all the split below is untouched, so a world that divides the KV
-     * heads -- TP2 on this family -- declares exactly as it did before replication existed. */
+    /* KV heads are replicated when there are fewer than ranks, which requires world to be a
+     * multiple of the KV head count. With 24 query heads over 2 KV heads at world 4, ranks {0,1}
+     * need only KV head 0 and ranks {2,3} only KV head 1. Each rank declares n_head_kv 1 and reads
+     * its head's row-span of k/v at `kv_off`; kv_dim(), gqa() and the blocks then treat a
+     * replicated rank like a split one. The replicating ranks hold identical KV weights, at no
+     * extra VRAM per rank versus the TP2 split. */
     if (aw > g.n_head_kv_all) {
-        /* aw is a multiple of the head count by construction (the world itself, checked here, or
-         * the attention world, which is one). */
+        /* Holds for the attention world by construction; checked for the plain world. */
         if (aw % g.n_head_kv_all != 0) {
             fprintf(stderr, "radiance: world_size = %d cannot replicate n_head_kv = %lld; "
                             "replication needs world to be a multiple of the KV head count\n",
@@ -871,9 +902,9 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
     } else if ((s = divide_or_fail(g.n_head_kv_all, aw, "n_head_kv", &g.n_head_kv)) < 0) {
         return s;
     } else {
-        /* A split rank reads the rows the plain row-shard gives it -- when the attention world
-         * is the world. Under a smaller attention world the even shard over `world` is the wrong
-         * cut, and the block spans [kv_off, kv_off + kv_dim) instead. */
+        /* A split rank uses the plain row-shard, except under a smaller attention world, where
+         * the even shard over `world` is the wrong cut and the block spans
+         * [kv_off, kv_off + kv_dim) instead. */
         g.kv_off = aw == g.world ? 0 : ar * g.n_head_kv * g.head_dim;
     }
     if (arch_splits_ff && g.world > 1 && g.n_ff_all % g.world != 0) {
@@ -881,18 +912,9 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
     } else if ((s = divide_or_fail(g.n_ff_all, g.world, "n_ff", &g.n_ff)) < 0) {
         return s;
     }
-    /* THE VOCABULARY IS SPLIT. r4d_sample_topk_f32 takes a vocabulary offset and packs its
-     * candidates as (u32 GLOBAL id, f32 logit) pairs, and the all-gather places every rank's
-     * pairs for one sampled position side by side, which is the layout sample_merge_topk reads.
-     * lm_head is therefore ROW-SHARDED and a rank reads half of it: on Qwen3.8-27B that is
-     * 1.27 GiB of the 16.1 GiB a rank reads per decode step, which makes the logits GEMM a
-     * large single item in the decode budget.
-     *
-     * The last rank is SHORT rather than padded -- 248320 and 151669 divide by nothing convenient
-     * -- because the sampler merges candidate sets rather than gathering full logits, so a ragged
-     * shard costs it nothing and a padded one would cost a fake token id masked everywhere
-     * forever. core/engine.cpp restates this split and checks its restatement against the width
-     * the plugin declared. */
+    /* lm_head is row-sharded by vocabulary (see vocab_per_rank). r4d_sample_topk_f32 takes a
+     * vocabulary offset and packs candidates as (u32 global id, f32 logit) pairs; the all-gather
+     * places every rank's pairs side by side, the layout sample_merge_topk reads. */
     g.n_vocab   = shard_extent(g.n_vocab_all, g.world, g.rank);
     g.vocab_off = shard_begin (g.n_vocab_all, g.world, g.rank);
     if (g.n_vocab <= 0) return RAD_E_INVAL;
@@ -900,47 +922,38 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
 }
 
 /* ================================================================== a vocab-sharded draft head */
-/* WHETHER A DRAFTER'S OWN HEAD CAN BE VOCAB-SHARDED, and it lives here because both the block that
- * declares the op and the plugin that sizes the buffer under it have to give the SAME answer -- a
- * buffer that disagreed with the op declared over it is a read past its end. Every drafter asks
- * the identical question, so the test lives in one place: two copies of a rule this exact are two
- * things to keep in step.
+/* Whether a drafter's own head can be vocab-sharded. Shared so the block declaring the op and the
+ * plugin sizing its buffer agree; a disagreement is a read past the buffer's end.
  *
- * IT REFUSES A RAGGED OR UNALIGNED SHARD rather than working around it. The packed w2a8 layout is
- * TILE-MAJOR at 16 output rows a block, so a rank whose share is not a multiple of 16 has a block
- * spanning two ranks and there is no row shard of it at all; and the candidate merge's global ids
- * are `rank * n_vocab + local`, which is only true of a contiguous, equally-sized split. Either
- * one wrong is fluent text with the wrong tokens in it. */
+ * Requires an even split in multiples of 16: the packed w2a8 layout is tile-major at 16 output
+ * rows a block, so an unaligned share splits a block across ranks, and the candidate merge's
+ * global ids are `rank * n_vocab + local`, true only for a contiguous equal split. */
 inline bool vocab_head_sharded(const Geom& g) {
     return g.world > 1 && g.n_vocab > 0 && (g.n_vocab % 16) == 0 &&
            g.n_vocab * (int64_t)g.world == g.n_vocab_all &&
            g.vocab_off == (int64_t)g.rank * g.n_vocab;
 }
-/* Rows of such a head, and therefore the width of its logit plane, on THIS rank. */
+/* Rows of such a head on this rank, and so the width of its logit plane. */
 inline int64_t vocab_head_rows(const Geom& g) {
     return vocab_head_sharded(g) ? g.n_vocab : g.n_vocab_all;
 }
 
 /* ================================================================== the KV cache operand */
-/* attn_paged and kv_store take the group's cache as an operand. RadKVGroupBatch carries the slot
- * mapping, the block table and the sequence lengths, but the pool base belongs to the block
- * manager and not to the batch -- so the operand names the GROUP and the LAYER and the core
- * resolves it, the same way it resolves a weight handle. */
+/* The cache operand for attn_paged and kv_store. The pool base belongs to the block manager, not
+ * the batch, so the operand names the group and layer and the core resolves it like a weight
+ * handle. */
 inline RadOperand kv_cache(rad_kvgroup group, int layer) { return RAD_KV(group, layer); }
 
 /* ================================================================== step-sized operands */
-/* EVERY OPERAND A STEP ISSUES CARRIES THE STEP'S ROW COUNT, NOT THE BUFFER'S.
+/* Every operand a step issues carries the step's row count, not the buffer's.
  *
- * A ranged parameter is collapsed to a BAND when the instance is resolved (spec §2.2) and
- * `rad_issue` carries the actual value as an integer rather than by rewriting the parameter list,
- * so a kernel cannot read the row count out of `M`: it would get the band's upper bound.
- * libref therefore reads every extent off the operands (libref/ref_ops.h), and an
- * operand handed over at its declared extent means a single-row decode computed over all 8192 rows
- * of an arena buffer -- reading uninitialised memory and writing over the next op's input.
+ * A ranged parameter is collapsed to a band at resolve time (spec §2.2), so a kernel cannot read
+ * the row count from `M` (it would get the band's upper bound); kernels read extents from the
+ * operands (libref/ref_ops.h). An operand at its declared extent makes a one-row decode compute
+ * over the whole arena buffer, reading uninitialised memory and overwriting the next op's input.
  *
- * So the run phase narrows, and these three helpers are how. `rows` is dim 0, which is tokens for
- * every activation buffer in this library; the strides are products of the trailing dimensions, so
- * shortening the outermost one leaves all of them correct (core/runtime/issue.cpp says the same).
+ * `rows` is dim 0, tokens for every activation buffer here. Strides are products of the trailing
+ * dimensions, so shortening dim 0 keeps them correct (core/runtime/issue.cpp).
  */
 inline RadOperand brows(rad_buf h, int64_t rows) {
     RadOperand o = RAD_B(h);
@@ -948,22 +961,18 @@ inline RadOperand brows(rad_buf h, int64_t rows) {
     return o;
 }
 
-/* A column slice narrowed to this step's rows: the two together, because every strided view this
- * library takes is also row-narrowed and spelling it as two calls invites forgetting one. */
+/* A column slice narrowed to this step's rows. */
 inline RadOperand bcol(rad_buf h, int64_t first, int64_t width, int64_t rows) {
     RadOperand o = RAD_B_COL(h, first, width);
     o.rows = rows;
     return o;
 }
 
-
-/* A COLUMN SLICE OF A RANGE OF ROWS. `offset` is a flat element offset and `cols` narrows the last
- * dimension with the declared width kept as the stride, so the two compose: first_row * pitch
- * picks the row, first_col picks the column within it (core/runtime/issue.cpp says the same).
- *
- * The mixed step is what needs it. A block that issues the recurrent path over the decode rows and
- * the chunked path over the prefill ones is issuing each over a RANGE of tokens, and the operands
- * it hands them are already column views of a fused projection. */
+/* A column slice of a range of rows. `offset` is a flat element offset and `cols` narrows the last
+ * dimension keeping the declared width as stride, so first_row * pitch picks the row and
+ * first_col the column (core/runtime/issue.cpp). Used by mixed steps, which issue the recurrent
+ * path over the decode rows and the chunked path over the prefill rows, each over column views
+ * of a fused projection. */
 inline RadOperand bcol_at(rad_buf h, int64_t first_row, int64_t pitch,
                           int64_t first_col, int64_t width, int64_t rows) {
     RadOperand o = RAD_B(h);
@@ -973,15 +982,11 @@ inline RadOperand bcol_at(rad_buf h, int64_t first_row, int64_t pitch,
     return o;
 }
 
-/* A RANGE OF ROWS, offset and count. The element offset is `first * pitch` because a buffer's
- * rows are its declared width apart and RadOperand::offset is in elements; dim 0 is then narrowed
- * to `n`, which is what makes the slice a tensor the kernel sees as [n, pitch].
+/* Rows [first, first + n), seen by the kernel as [n, pitch]; RadOperand::offset is in elements.
  *
- * It exists because one op can cap the whole step. A libr4d kernel is constrained to a band, and
- * an op whose widest kernel stops at M=64 forces every op in the step down to 64 tokens -- on this
- * model that is the delta net's 96-column a|b projection, 0.5% of the layer's projection bytes,
- * holding the prefill chunk of a 27B model to 64. Issuing that one op in slices costs a launch per
- * 64 rows and lets everything else run at the chunk the scheduler wanted. */
+ * Lets one op be issued in slices: an op whose widest kernel stops at M=64 (the delta net's
+ * 96-column a|b projection) would otherwise cap every op in the step at 64 tokens. Slicing it
+ * costs a launch per 64 rows. */
 inline RadOperand brow_slice(rad_buf h, int64_t first, int64_t n, int64_t pitch) {
     RadOperand o = RAD_B(h);
     o.offset = first * pitch;
@@ -989,31 +994,29 @@ inline RadOperand brow_slice(rad_buf h, int64_t first, int64_t n, int64_t pitch)
     return o;
 }
 
-/* A batch field: a pointer the core did not allocate, so it has no declared shape and the row
- * count has to come from here. Without it the operand arrives rank 0 and a kernel that sizes its
- * loop by numel(positions) runs one token. */
-/* A dense two-dimensional batch field: [rows, cols], packed. The block table is the one that
- * needs it -- see RAD_P_T2 in rad_runtime.h for why a rank-1 spelling is not enough. */
+/* A dense two-dimensional batch field, [rows, cols] packed: the block table (RAD_P_T2 in
+ * rad_runtime.h says why rank 1 is not enough). */
 inline RadOperand praw2(const void* p, uint32_t dtype, int64_t rows, int64_t cols) {
     return RAD_P_T2(p, dtype, rows, cols);
 }
 
+/* A batch field. The core did not allocate it, so it has no declared shape and the row count
+ * comes from here; without it the operand is rank 0 and a kernel sizing its loop by
+ * numel(positions) runs one token. */
 inline RadOperand praw(const void* p, uint32_t dtype, int64_t rows) {
     RadOperand o = RAD_P_T(p, dtype);
     o.rows = rows;
     return o;
 }
 
-/* THE ROTARY POSITIONS OF A PASS, in the two forms its consumers take.
+/* Rotary positions of a pass, in the two forms consumers take.
  *
- * `rope_pos1` is one component a token: RadBatch::rope_pos's plane 0 when the batch carries the
- * planes, `positions` when it does not. It is what a cos/sin table is filled and read at, and it
- * is exact for every token of a pass whose components agree (RadBatch::rope_mixed 0) -- so a
- * fused path that reads it is taken only then.
+ * `rope_pos1`: one component per token, RadBatch::rope_pos's plane 0 if present, else
+ * `positions`. A cos/sin table is filled and read at it. It is exact only when every token's
+ * components agree (RadBatch::rope_mixed 0), so fused paths that read it are taken only then.
  *
- * `rope_posmc` is what a multi-component `rope` takes: the dense [3, T] planes for an M-RoPE model
- * with a batch that carries them, and the one-component form otherwise -- which every mode reads
- * as NeoX, so a model without M-RoPE and a text-only deployment rotate over `positions` alone. */
+ * `rope_posmc`: what a multi-component `rope` takes. The dense [3, T] planes for an M-RoPE model
+ * whose batch carries them, else the one-component form, which every mode reads as NeoX. */
 inline RadOperand rope_pos1(const RadBatch* b, int64_t T) {
     return praw(b->rope_pos ? b->rope_pos : b->positions, RAD_I32, T);
 }
@@ -1021,12 +1024,12 @@ inline RadOperand rope_posmc(const Geom& g, const RadBatch* b, int64_t T) {
     if (g.rope_mc && b->rope_pos) return praw2(b->rope_pos, RAD_I32, 3, T);
     return praw(b->positions, RAD_I32, T);
 }
-/* Does a pass have a token whose rotary components differ -- which a one-component fused path
- * cannot rotate. */
+/* True when some token's rotary components differ, which a one-component fused path cannot
+ * rotate. */
 inline bool rope_mixed(const RadBatch* b) { return b->rope_pos && b->rope_mixed; }
 
-/* A rotary op declared with the geometry's YaRN coefficients appended. A model without YaRN declares
- * exactly the parameters it was given, so its op identities and tune keys are unchanged. */
+/* A rotary op declared with the geometry's YaRN coefficients appended. Without YaRN the
+ * parameters are passed unchanged, so op identities and tune keys do not change. */
 inline rad_op decl_rotary(RadBuilder* b, const Geom& g, const char* name,
                           const RadParam* params, int n, const rad_weight* weights, int nw) {
     if (g.yarn.factor == 0.0f) return rad_decl_op(b, name, params, n, weights, nw);
@@ -1038,10 +1041,10 @@ inline rad_op decl_rotary(RadBuilder* b, const Geom& g, const char* name,
     return rad_decl_op(b, name, p.data(), (int)p.size(), weights, nw);
 }
 
-/* THE ONE READER OF A MODEL'S ROTARY SCALING. Every architecture calls it after geom_from, for the
- * target ("") and for a drafter with a config of its own ("draft."), and it sets `g.rope_scale` and
- * `g.yarn` from the free-form keys and from nothing else. RadModelMeta::rope_scale is not read: a
- * factor without its type would be a linear position divide for a scheme that is not one.
+/* Reads a model's rotary scaling into `g.rope_scale` and `g.yarn`. Every architecture calls it
+ * after geom_from, for the target ("") and for a drafter with its own config ("draft."). Only the
+ * free-form keys are read; RadModelMeta::rope_scale is not, since a factor without its type would
+ * be applied as a linear divide.
  *
  * The object read is the first of `text_config.rope_parameters.`, `rope_parameters.`,
  * `text_config.rope_scaling.`, `rope_scaling.` (a drafter: `draft.rope_parameters.`,
@@ -1103,8 +1106,7 @@ inline int yarn_from(Geom& g, const RadModelMeta* meta, const char* prefix, int6
                         "and yarn are\n", who, type, type_key.c_str());
         return RAD_E_UNSUPPORTED;
     }
-    /* `truncate` is a JSON boolean, which the converter writes as 1 or 0; true and false spelled
-     * out are the same answer. */
+    /* `truncate` is a JSON boolean; the converter writes 1 or 0, and true/false are accepted. */
     double truncate = 1.0;
     if (const char* t = rad_meta_gets(meta, (home + "truncate").c_str(), nullptr))
         truncate = !std::strcmp(t, "true") ? 1.0 : !std::strcmp(t, "false") ? 0.0 : get("truncate", 1.0);
@@ -1150,35 +1152,21 @@ inline int yarn_from(Geom& g, const RadModelMeta* meta, const char* prefix, int6
  * `mode` otherwise. */
 inline rad_op decl_rope(RadBuilder* b, const Geom& g, int64_t rows, int64_t head_dim,
                         int64_t n_head, int64_t n_head_kv, int64_t rot, const char* mode) {
-    if (g.rope_mc)
-        return decl_rotary(b, g, "rope",
-                      RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", head_dim),
-                                 RAD_INT("n_head", n_head), RAD_INT("n_head_kv", n_head_kv),
-                                 RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
-                                 RAD_STR("mode", g.rope_mode), RAD_INT("rotary_dim", rot),
-                                 RAD_STR("sections", g.rope_sections)),
-                      RAD_NOWEIGHTS);
-    return decl_rotary(b, g, "rope",
-                  RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", head_dim),
-                             RAD_INT("n_head", n_head), RAD_INT("n_head_kv", n_head_kv),
-                             RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
-                             RAD_STR("mode", mode), RAD_INT("rotary_dim", rot)),
-                  RAD_NOWEIGHTS);
+    const RadParam ps[] = { RAD_RANGE("M", 1, rows), RAD_INT("head_dim", head_dim),
+                            RAD_INT("n_head", n_head), RAD_INT("n_head_kv", n_head_kv),
+                            RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
+                            RAD_STR("mode", g.rope_mc ? g.rope_mode : mode),
+                            RAD_INT("rotary_dim", rot), RAD_STR("sections", g.rope_sections) };
+    const int n = (int)(sizeof ps / sizeof ps[0]) - (g.rope_mc ? 0 : 1);
+    return decl_rotary(b, g, "rope", ps, n, nullptr, 0);
 }
 
-
-/* HOW MANY OF THIS STEP'S SEQUENCES ARE DECODE ROWS, AND WHERE THEIR TOKENS END.
+/* How many of this step's sequences are decode rows, and where their tokens end.
  *
- * A block that issues one path over the decode rows and another over the prefill chunks needs the
- * boundary, and for a MIXED step RadBatch::n_seq_decode is the only thing that carries it. For a
- * pure step it is not: PREFILL means none of them and DECODE means all of them, by definition of
- * the phase, and asking the phase first is what makes the two fields optional there. A batch that
- * sets phase and leaves them zero -- a test, a bench harness, an out-of-tree caller -- would
- * otherwise be handed the prefill path by a block that read them alone, with nothing to say so.
- * tests/arch_test.cpp covers exactly that case.
- *
- * The core sets both fields on every step including the pure ones, so this agrees with them; it
- * is the fallback that matters, not the answer. */
+ * A mixed step carries the boundary in RadBatch::n_seq_decode / n_tok_decode. For a pure step the
+ * phase decides (PREFILL: none, DECODE: all), so a caller that sets only the phase (a test, a
+ * bench, an out-of-tree caller) still gets the right path; tests/arch_test.cpp covers this. The
+ * core sets both fields on every step, so the two agree. */
 inline void batch_split(const RadBatch* b, int64_t* n_seq_dec, int64_t* n_tok_dec) {
     switch (b->phase) {
         case RAD_PHASE_PREFILL: *n_seq_dec = 0;              *n_tok_dec = 0;              break;
@@ -1187,22 +1175,80 @@ inline void batch_split(const RadBatch* b, int64_t* n_seq_dec, int64_t* n_tok_de
     }
 }
 
-/* The step batch's entry for one declared KV group. The batch is built once per step by the core
- * and shared by every layer and every group (spec §8); this is the lookup, not a computation. */
+/* The step batch's entry for one declared KV group (built once per step by the core, spec §8). */
 inline const RadKVGroupBatch* kv_batch(const RadBatch* b, rad_kvgroup group) {
     for (int i = 0; i < b->n_kv_groups; ++i)
         if (b->kv[i].group == group) return &b->kv[i];
     return nullptr;
 }
 
+/* ================================================================== a block drafter */
+/* A drafter's Geom: the target's (n_embd, vocabulary, deployment bounds, rank, wire) with the
+ * layer, head, feed-forward, norm and rotary geometry of the container's `draft.` config, split
+ * over the ranks, and a plain RMS norm. A drafter is a second model, so nothing is defaulted: a
+ * config that does not describe one is refused, naming `what` (spec §17). So is a vocabulary
+ * other than the target's, since a drafter reads the target's embedding and lm_head. */
+inline int drafter_geom(Geom& dg, const Geom& target, const RadModelMeta* meta, const char* what) {
+    dg = target;
+    dg.n_layer       = rad_meta_geti(meta, "draft.num_hidden_layers", 0);
+    dg.head_dim      = rad_meta_geti(meta, "draft.head_dim", 0);
+    dg.n_head_all    = rad_meta_geti(meta, "draft.num_attention_heads", 0);
+    dg.n_head_kv_all = rad_meta_geti(meta, "draft.num_key_value_heads", 0);
+    dg.n_ff_all      = rad_meta_geti(meta, "draft.intermediate_size", 0);
+    dg.eps           = (float)rad_meta_getf(meta, "draft.rms_norm_eps", 0.0);
+    dg.theta         = (float)rad_meta_getf(meta, "draft.rope_parameters.rope_theta",
+                                            rad_meta_getf(meta, "draft.rope_theta", 0.0));
+    dg.wadd = dg.wadd_qk = 0.0f;
+    if (dg.n_layer <= 0 || dg.head_dim <= 0 || dg.n_head_all <= 0 || dg.n_head_kv_all <= 0 ||
+        dg.n_ff_all <= 0 || !(dg.eps > 0.0f) || !(dg.theta > 0.0f)) {
+        fprintf(stderr, "radiance: the container's `draft.` config does not describe a %s "
+                        "drafter: layers %lld, heads %lld / kv %lld, head_dim %lld, ffn %lld, "
+                        "rms_eps %g, rope_theta %g\n", what,
+                (long long)dg.n_layer, (long long)dg.n_head_all, (long long)dg.n_head_kv_all,
+                (long long)dg.head_dim, (long long)dg.n_ff_all, (double)dg.eps, (double)dg.theta);
+        return RAD_E_INVAL;
+    }
+    RAD_ARCH_TRY(yarn_from(dg, meta, "draft.", dg.head_dim));
+    RAD_ARCH_TRY(divide_or_fail(dg.n_head_all,    dg.world, "draft num_attention_heads", &dg.n_head));
+    RAD_ARCH_TRY(divide_or_fail(dg.n_head_kv_all, dg.world, "draft num_key_value_heads", &dg.n_head_kv));
+    RAD_ARCH_TRY(divide_or_fail(dg.n_ff_all,      dg.world, "draft intermediate_size",   &dg.n_ff));
+    const long long dvocab = rad_meta_geti(meta, "draft.vocab_size", dg.n_vocab_all);
+    if (dvocab != dg.n_vocab_all) {
+        fprintf(stderr, "radiance: the %s drafter claims a %lld-token vocabulary and the target "
+                        "has %lld; it reads the target's embedding and lm_head\n",
+                what, dvocab, (long long)dg.n_vocab_all);
+        return RAD_E_UNSUPPORTED;
+    }
+    return RAD_OK;
+}
+
+/* The drafter's own KV group, bound to its layers from `base_layer`: it differs from the trunk's
+ * in layer count and head geometry. A `window` > 0 makes it RAD_KV_WINDOW, which recycles blocks
+ * below the window. Its dtype is --kv-cache-dtype, like every attention cache, and is written to
+ * dg.kv_dtype. */
+inline int drafter_kv_group(RadBuilder* b, Names& nm, const RadBuildCtx* ctx, Geom& dg,
+                            int64_t window, int base_layer, rad_kvgroup* out) {
+    RadKVGroupDecl d{};
+    d.kind      = window > 0 ? RAD_KV_WINDOW : RAD_KV_FULL;
+    d.dtype     = rad_kv_cache_dtype(ctx, RAD_BF16);
+    d.window    = window;
+    d.n_head_kv = dg.n_head_kv;
+    d.head_dim  = dg.head_dim;
+    *out = rad_decl_kv_group(b, nm.f("kv_draft"), &d);
+    for (int64_t l = 0; l < dg.n_layer; ++l)
+        RAD_ARCH_TRY(rad_bind_layer_kv(b, base_layer + (int)l, *out));
+    dg.kv_dtype = rad_dtype_name(d.dtype);
+    return RAD_OK;
+}
+
 /* ================================================================== the plugin exports */
-/* The four C symbols spec §2.4 names, wired to a namespace. Defining them through a macro keeps
- * the plugin source free of extern "C" boilerplate, and RAD_ARCH_NO_EXPORTS lets the unit test
- * include two plugin sources into one translation unit without the exports colliding -- which is
- * what makes the declared graph testable with no GPU and no model file. */
-/* QUANT is the container's quantisation descriptor this plugin serves, "" for an unquantised one.
- * It is the second half of the selection key (spec §2.4, rad_builder.h): qwen35_bf16 and
- * qwen35_fp8 both answer "qwen35" to rad_arch_id and differ only here. */
+/* The C symbols spec §2.4 names, wired to a namespace. RAD_ARCH_NO_EXPORTS lets the unit test
+ * include two plugin sources in one translation unit without the exports colliding, so the
+ * declared graph is testable with no GPU and no model file.
+ *
+ * QUANT is the quantisation descriptor this plugin serves, "" for unquantised: the second half of
+ * the selection key (spec §2.4, rad_builder.h). qwen35_bf16 and qwen35_fp8 both answer "qwen35"
+ * to rad_arch_id and differ only here. */
 #define RAD_ARCH_PLUGIN(NS, ID, QUANT, VERSION, DESC)                                          \
     extern "C" const char* rad_arch_id(void) { return ID; }                                    \
     extern "C" const char* rad_arch_quant(void) { return QUANT; }                              \
@@ -1213,35 +1259,36 @@ inline const RadKVGroupBatch* kv_batch(const RadBatch* b, rad_kvgroup group) {
     }                                                                                          \
     extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; }               \
     extern "C" const RadPluginInfo* rad_plugin_info(void) {                                    \
-        /* The PLUGIN's name, not the architecture id: rad_abi.h spells the convention out       \
-         * ("qwen3_dense_bf16"), the registry requires plugin names to be unique, and a family    \
-         * with one plugin per weight format has several plugins per architecture. Passing ID     \
-         * here would make qwen35_bf16 and qwen35_fp8 both "qwen35", and the second would be      \
-         * refused at load. */                                                                    \
+        /* The plugin's name (rad_abi.h: "qwen3_dense_bf16"), not the architecture id: plugin   \
+         * names must be unique and one architecture can have several plugins. */               \
         static const RadPluginInfo info = { RAD_PLUGIN_ARCH, #NS, VERSION, DESC, "" };         \
         return &info;                                                                          \
     }
 
-
-/* THE FIFTH EXPORT, AND IT IS OPT-IN. A plugin that has nothing to say before declare does not
- * define it; the core reads the absence as "no opinion" and every field of RadArchProbe keeps its
- * zero. Separate from RAD_ARCH_PLUGIN rather than folded into it so that adding a question to
- * RadArchProbe never makes an existing plugin fail to compile. */
+/* Optional pre-declare probe. Without it every RadArchProbe field stays zero. Kept out of
+ * RAD_ARCH_PLUGIN so adding a RadArchProbe field never breaks an existing plugin's build. */
 #define RAD_ARCH_PROBE(NS)                                                                     \
     extern "C" int rad_arch_probe(const RadModelMeta* m, RadArchProbe* out) {                  \
         return NS::probe(m, out);                                                              \
     }
 
-/* THE REPLY FORMAT, ALSO OPT-IN. A plugin whose model spells its reasoning and tool calls in a way
- * the chat template's analysis does not find -- or finds wrongly -- states it here once, and the
- * reply parser, the lazy call grammar and its trigger words all follow from it. NS::chat_format
- * returns a pointer to static storage with struct_size = sizeof(RadChatFormat), or null to let
- * the template decide for this particular model. */
+/* Optional reply format, for a model whose reasoning and tool-call syntax the chat template
+ * analysis misses or misreads. The reply parser, lazy call grammar and trigger words follow from
+ * it. NS::chat_format returns static storage with struct_size = sizeof(RadChatFormat), or null to
+ * let the template decide for this model. */
 #define RAD_ARCH_CHAT_FORMAT(NS)                                                               \
     extern "C" const RadChatFormat* rad_arch_chat_format(const RadModelMeta* m) {              \
         return NS::chat_format(m);                                                             \
     }
 
+/* The audio format, also opt-in: a model with an audio encoder states how its prompt carries a
+ * clip and asks for a transcript (RadAudioFormat). NS::audio_format returns static storage with
+ * struct_size = sizeof(RadAudioFormat), or null for a model that serves no speech route. */
+#define RAD_ARCH_AUDIO_FORMAT(NS)                                                              \
+    extern "C" const RadAudioFormat* rad_arch_audio_format(const RadModelMeta* m) {            \
+        return NS::audio_format(m);                                                            \
+    }
+
 }  /* namespace arch */
 }  /* namespace rad */
 
diff --git a/arch/common/rad_block_attn.h b/arch/common/rad_block_attn.h
new file mode 100644
index 00000000..6ee4a50c
--- /dev/null
+++ b/arch/common/rad_block_attn.h
@@ -0,0 +1,210 @@
+/* rad_block_attn.h -- one grouped-query attention block with per-head q/k RMS norms, bf16
+ * operands, paged KV: Qwen3's attention.
+ *
+ *   rmsnorm -> q gemm, k gemm, v gemm -> q norm, k norm (per head) -> rope (NeoX)
+ *   -> kv_store -> paged attention -> o gemm -> [all_reduce] -> residual
+ *
+ * rad_block_attn_gated.h without the output gate, and more than a flag apart: Qwen3's q_proj is
+ * [n_head * head_dim, n_embd] (queries only, no interleaved gate), the rotary covers every head
+ * dimension as plain NeoX over the token's position, and the norms are plain RMS norms,
+ * `x_hat * w` (Qwen3RMSNorm), not Gemma's `1 + w`. Qwen3-1.7B is Qwen3-ASR's decoder
+ * (arch/qwen3asr_bf16).
+ *
+ * q, k and v are three projections into three contiguous buffers: paged attention reads `q`
+ * contiguous (libr4d's fill_paged refuses a pitched query), so a fused [q|k|v] row would need a
+ * copy before attention. Each per-head norm is an ordinary `rmsnorm` with M = tokens x heads and
+ * n = head_dim, and the rotary is `rope` over q and over k, which every kernel library serves.
+ *
+ * Positions are RadBatch::positions, one component a token. A media span in the prompt (an audio
+ * clip's placeholders) counts up like text, as the reference's position ids do; this block never
+ * reads the M-RoPE planes.
+ */
+#ifndef RAD_BLOCK_ATTN_H
+#define RAD_BLOCK_ATTN_H
+
+#include "rad_arch.h"
+
+namespace rad {
+namespace arch {
+
+struct AttnBF16 {
+    /* The activation buffers, declared once by the plugin and shared by every layer: layers that
+     * share a geometry share the buffer (spec §8). */
+    struct Wire {
+        rad_buf x    = 0;   /* [max_tok, n_embd]  the residual stream */
+        rad_buf h    = 0;   /* [max_tok, n_embd]  normed input, then the o output */
+        rad_buf q    = 0;   /* [max_tok, q_dim]   projected, normed, rotated */
+        rad_buf k    = 0;   /* [max_tok, kv_dim] */
+        rad_buf v    = 0;   /* [max_tok, kv_dim] */
+        rad_buf attn = 0;   /* [max_tok, q_dim]   attention output */
+    };
+
+    /* The checkpoint-side names for one layer; the plugin owns the spelling (spec §2.4). */
+    struct Src {
+        const char* norm   = nullptr;   /* input_layernorm.weight */
+        const char* q      = nullptr;
+        const char* k      = nullptr;
+        const char* v      = nullptr;
+        const char* q_norm = nullptr;
+        const char* k_norm = nullptr;
+        const char* o      = nullptr;
+    };
+
+    Geom        g{};
+    Wire        w{};
+    int         layer = 0;
+    rad_kvgroup kv    = 0;
+
+    rad_weight w_norm = 0, w_q = 0, w_k = 0, w_v = 0, w_q_norm = 0, w_k_norm = 0, w_o = 0;
+    rad_op op_norm = 0, op_q = 0, op_k = 0, op_v = 0, op_q_norm = 0, op_k_norm = 0;
+    rad_op op_rope_q = 0, op_rope_k = 0, op_kv_store = 0, op_attn = 0, op_o = 0, op_ar = 0;
+    rad_op op_add = 0;
+
+    int  declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group,
+                 const Wire& wire, const Src& src);
+    void step(RadCtx* c, const RadBatch* batch) const;
+};
+
+inline int AttnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group,
+                             const Wire& wire, const Src& src) {
+    g = geom; w = wire; layer = l; kv = group;
+    const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim();
+
+    /* KV-head replication is not plumbed here, for the reason rad_block_attn_gated.h gives: the
+     * plain row-shard of k and v would hand a rank part of one KV head. Refused by name. */
+    if (g.world > g.n_head_kv_all) {
+        fprintf(stderr, "radiance: %s declares no KV row span and cannot serve world_size = %d "
+                        "with n_head_kv = %lld\n", __func__, g.world, (long long)g.n_head_kv_all);
+        return RAD_E_UNSUPPORTED;
+    }
+
+    /* ---- weights. [out, in], so nothing is transposed at load. q, k and v row-shard by head;
+     * o column-shards, so each rank holds a partial sum of the residual update. */
+    RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l),   src.norm));
+    RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q.weight", l),      src.q));
+    RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k.weight", l),      src.k));
+    RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_v.weight", l),      src.v));
+    RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l), src.q_norm));
+    RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k_norm.weight", l), src.k_norm));
+    RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_output.weight", l), src.o));
+
+    w_norm   = decl_w(b, nm.f("blk.%d.attn_norm.weight", l),   RAD_F32,  {g.n_embd},
+                      RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
+    w_q      = decl_w(b, nm.f("blk.%d.attn_q.weight", l),      RAD_BF16, {q_dim, g.n_embd},
+                      RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW,  grp_layer(l));
+    w_k      = decl_w(b, nm.f("blk.%d.attn_k.weight", l),      RAD_BF16, {kv_dim, g.n_embd},
+                      RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW,  grp_layer(l));
+    w_v      = decl_w(b, nm.f("blk.%d.attn_v.weight", l),      RAD_BF16, {kv_dim, g.n_embd},
+                      RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW,  grp_layer(l));
+    /* One gain shared by every head, replicated across ranks though the heads are not. */
+    w_q_norm = decl_w(b, nm.f("blk.%d.attn_q_norm.weight", l), RAD_F32,  {g.head_dim},
+                      RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
+    w_k_norm = decl_w(b, nm.f("blk.%d.attn_k_norm.weight", l), RAD_F32,  {g.head_dim},
+                      RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
+    w_o      = decl_w(b, nm.f("blk.%d.attn_output.weight", l), RAD_BF16, {g.n_embd, q_dim},
+                      RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL,  grp_layer(l));
+
+    auto gemm = [&](int64_t N, int64_t K, rad_weight wt) {
+        return RAD_OP(b, "gemm_nt",
+                      RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", N), RAD_INT("K", K),
+                                 RAD_STR("dtype", g.dtype)),
+                      RAD_WEIGHTS(wt));
+    };
+    auto head_norm = [&](int64_t heads, rad_weight wt) {
+        return RAD_OP(b, "rmsnorm",
+                      RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * heads), RAD_INT("n", g.head_dim),
+                                 RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk),
+                                 RAD_STR("dtype", g.dtype)),
+                      RAD_WEIGHTS(wt));
+    };
+
+    op_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", g.wadd),
+                                RAD_STR("dtype", g.dtype)),
+                     RAD_WEIGHTS(w_norm)),
+                 {w.x}, {w.h});
+    op_q = rw(b, gemm(q_dim,  g.n_embd, w_q), {w.h}, {w.q});
+    op_k = rw(b, gemm(kv_dim, g.n_embd, w_k), {w.h}, {w.k});
+    op_v = rw(b, gemm(kv_dim, g.n_embd, w_v), {w.h}, {w.v});
+    /* Each norm runs in place: a row's scale is computed before the row is written. */
+    op_q_norm = rw(b, head_norm(g.n_head,    w_q_norm), {w.q}, {w.q});
+    op_k_norm = rw(b, head_norm(g.n_head_kv, w_k_norm), {w.k}, {w.k});
+    /* Two rope calls because q and k are two buffers: a `rope` that names only q heads is a fused
+     * row with an empty k and v. The full head dim rotates. */
+    op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, g.head_dim, "neox"),
+                   {w.q}, {w.q});
+    op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, g.head_dim, "neox"),
+                   {w.k}, {w.k});
+
+    /* attn_paged before kv_store: block_size is RAD_DERIVED, read off the resolved attention
+     * kernel and back into kv_store with rad_kv_block_size() (rad_block_attn_gated.h says why). */
+    op_attn = rw(b, RAD_OP(b, "attn_paged",
+                     RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
+                                RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
+                                RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
+                                RAD_INT("block_size", RAD_KV_BLOCK),
+                                RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
+                                RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
+                     RAD_NOWEIGHTS),
+                 {w.q}, {w.attn});
+    op_kv_store = rw(b, RAD_OP(b, "kv_store",
+                         RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
+                                    RAD_INT("n_head_kv", g.n_head_kv),
+                                    RAD_INT("block_size", rad_kv_block_size(b, kv)),
+                                    RAD_STR("kv_dtype", g.kv_dtype)),
+                         RAD_NOWEIGHTS),
+                     {w.k, w.v}, {});
+
+    op_o = rw(b, gemm(g.n_embd, q_dim, w_o), {w.attn}, {w.h});
+    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),
+                                  RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
+                                  RAD_INT("min_bytes", g.wire_min_bytes)),
+                       RAD_NOWEIGHTS),
+                   {w.h}, {w.h});
+    op_add = rw(b, RAD_OP(b, "add",
+                    RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
+                               RAD_STR("dtype", g.dtype)),
+                    RAD_NOWEIGHTS),
+                {w.x, w.h}, {w.x});
+    return RAD_OK;
+}
+
+inline void AttnBF16::step(RadCtx* c, const RadBatch* batch) const {
+    const RadKVGroupBatch* kvb = kv_batch(batch, kv);
+    const int32_t* slot  = kvb ? kvb->slot_mapping : nullptr;
+    const int32_t* table = kvb ? kvb->block_table  : nullptr;
+    const int32_t* used  = kvb ? kvb->seqused      : nullptr;
+    const int64_t T = batch->n_tok;
+    const RadOperand pos = praw(batch->positions, RAD_I32, T);
+
+    RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
+    RAD_ISSUE(c, op_q,    brows(w.h, T), RAD_W(w_q),    brows(w.q, T));
+    RAD_ISSUE(c, op_k,    brows(w.h, T), RAD_W(w_k),    brows(w.k, T));
+    RAD_ISSUE(c, op_v,    brows(w.h, T), RAD_W(w_v),    brows(w.v, T));
+    RAD_ISSUE_N(c, op_q_norm, T * g.n_head,    brows(w.q, T), RAD_W(w_q_norm), brows(w.q, T));
+    RAD_ISSUE_N(c, op_k_norm, T * g.n_head_kv, brows(w.k, T), RAD_W(w_k_norm), brows(w.k, T));
+    RAD_ISSUE(c, op_rope_q, brows(w.q, T), pos);
+    RAD_ISSUE(c, op_rope_k, brows(w.k, T), pos);
+    RAD_ISSUE(c, op_kv_store,
+              brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer));
+    /* The actual query length selects the band; cu_seqlens carries a ragged step. */
+    RAD_ISSUE_N(c, op_attn, batch->max_q_len,
+                brows(w.q, T), kv_cache(kv, layer),
+                praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
+                praw(used, RAD_I32, batch->n_seq),
+                RAD_NONE, RAD_NONE,
+                praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
+                brows(w.attn, T));
+    RAD_ISSUE(c, op_o, brows(w.attn, T), RAD_W(w_o), brows(w.h, T));
+    if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
+    RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h, T), brows(w.x, T));
+}
+
+}  /* namespace arch */
+}  /* namespace rad */
+
+#endif /* RAD_BLOCK_ATTN_H */
diff --git a/arch/common/rad_block_attn_fp8.h b/arch/common/rad_block_attn_fp8.h
index 4735b664..ada9ae17 100644
--- a/arch/common/rad_block_attn_fp8.h
+++ b/arch/common/rad_block_attn_fp8.h
@@ -1,42 +1,31 @@
-/* rad_block_attn_fp8.h -- the PLAIN GQA attention block with block-scaled FP8 projections.
+/* rad_block_attn_fp8.h -- plain GQA attention with block-scaled FP8 projections.
  *
  *   rmsnorm -> quant_act_fp8 -> fused q|k|v gemm_nt_q -> rope -> kv_store -> attn_paged
  *   -> quant_act_fp8 -> o gemm_nt_q -> [all_reduce] -> residual add
  *
- * IT IS rad_block_attn_gated_fp8.h WITHOUT THE TWO THINGS THAT MAKE THAT ONE GATED, and those two
- * are what a family answers differently rather than what a model tunes:
+ * rad_block_attn_gated_fp8.h without its two family-specific features:
  *
- *   - NO PER-HEAD Q/K NORM. Qwen3.5 norms each head against its own gain before rotating; LLaMA
- *     and MiniCPM5 rotate the projection as it comes out of the GEMM. A block that normed anyway
- *     against an absent gain would be a different model, and one that normed against a gain of
- *     ones would be a wasted launch a layer.
- *   - NO OUTPUT GATE. There is no second half of the query projection and no sigmoid: the
- *     attention output goes straight into the out-projection.
+ *   - No per-head q/k norm. Qwen3.5 norms each head before rotating; LLaMA and MiniCPM5 rotate
+ *     the GEMM output directly.
+ *   - No output gate. The attention output goes straight into the out-projection.
  *
- * WHAT THAT BUYS is the fused q|k|v, which the gated block cannot have: its query projection is
- * [q|gate] interleaved per head and k and v are separate tensors, so there are three GEMMs a layer.
- * Here the three weights concatenate along dim 0 into one [q_dim + 2*kv_dim, n_embd] and `rope`
- * takes exactly that row -- q heads then k heads, v left alone, which is the operand shape the op
- * was written for (docs/OPS.md). One GEMM, one rope, one quantise in front of all of it.
+ * That allows a fused q|k|v, which the gated block cannot have (its query projection is [q|gate]
+ * interleaved per head). The three weights concatenate along dim 0 into one
+ * [q_dim + 2*kv_dim, n_embd], and `rope` takes that row as is: q heads, then k heads, v untouched
+ * (docs/OPS.md). One GEMM, one rope and one quantise.
  *
- * THE ROW PARTS ARE NOT DECORATION. A tensor-parallel rank owns a slice of EACH of the three
- * projections, not a contiguous slice of the stack; without `row_parts` rank 0 gets the whole query
- * and rank 1 the whole key and value, and both ranks then compute a perfectly well-formed wrong
- * thing. LinearFP8 also checks that each part is a whole number of 128-row scale blocks, which is
- * what makes a block-scaled fusion expressible at all.
+ * `row_parts` is required: a tensor-parallel rank owns a slice of each of the three projections,
+ * not a contiguous slice of the stack. LinearFP8 checks that each part is a whole number of
+ * 128-row scale blocks.
  *
- * Everything else -- the fused norm/quantise/residual/all-reduce op at the front, the KV group's
- * own dtype, the fold flags -- is rad_fp8.h's and rad_block_attn_gated_fp8.h's and is documented
- * there.
+ * The fused front op, the KV dtype and the fold flags are documented in rad_fp8.h and
+ * rad_block_attn_gated_fp8.h.
  */
 #ifndef RAD_BLOCK_ATTN_FP8_H
 #define RAD_BLOCK_ATTN_FP8_H
 
 #include "rad_fp8.h"
 
-#include 
-#include 
-
 namespace rad {
 namespace arch {
 
@@ -49,8 +38,8 @@ struct AttnFP8 {
         ActFP8  attn{};     /* [max_tok, q_dim]                    attention output */
     };
 
-    /* The checkpoint's tensor names. Whether they hold block fp8 already or a dense tensor the
-     * recipe quantises is the container's business; the declaration is the same either way. */
+    /* Checkpoint tensor names; the declaration is the same whether they hold block fp8 or a dense
+     * tensor the recipe quantises. */
     struct Src {
         const char* norm  = nullptr;
         const char* q     = nullptr;
@@ -64,9 +53,8 @@ struct AttnFP8 {
     int         layer = 0;
     rad_kvgroup kv    = 0;
     int64_t     n_rot = 0;
-    /* The rotation pairs HALVES (NeoX), which is what HF's rotate_half does and what every LLaMA
-     * derivative ships. GPT-J's adjacent pairs would be arithmetically silent too -- no per-op
-     * check tells the two apart -- so this is stated rather than inferred. */
+    /* The rotation pairs halves (NeoX, HF's rotate_half), as LLaMA derivatives ship. Stated
+     * explicitly: GPT-J's adjacent pairs would pass every per-op check too. */
     const char* mode  = "neox";
 
     rad_weight w_norm = 0;
@@ -99,10 +87,9 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
         return RAD_E_INVAL;
     }
 
-    /* NO KV-HEAD REPLICATION HERE. The fused [q|k|v] row-shards by head with the plain even shard,
-     * so above the KV head count a rank would get a slice of one KV head and declare fine while
-     * reading the wrong rows. rad_block_attn_gated.h refuses for the same reason; the block that
-     * plumbs geom_from's `kv_off` is rad_block_attn_gated_fp8.h. */
+    /* No KV-head replication: the fused [q|k|v] uses the plain even row shard, so above the KV head
+     * count a rank would read the wrong rows. rad_block_attn_gated_fp8.h is the block that uses
+     * geom_from's `kv_off`. */
     if (g.world > g.n_head_kv_all) {
         fprintf(stderr, "radiance: %s declares no KV row span and cannot serve world_size = %d "
                         "with n_head_kv = %lld.\n", __func__, g.world,
@@ -114,43 +101,29 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
     w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_F32, {g.n_embd},
                     RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
 
-    /* One norm, one quantise, one consumer -- and one op, see rad_fp8.h's NormQuantFP8. */
+    /* Norm and quantise in one op (rad_fp8.h: NormQuantFP8). */
     RAD_ARCH_TRY(nq_h.declare(b, g, w_norm, fold ? w.h.x : w.x, w.h, g.n_embd,
                               fold ? w.x : 0, 0, ar_in));
     RAD_ARCH_TRY(qkv.declare(b, nm, g, nm.f("blk.%d.attn_qkv", l), q_dim + 2 * kv_dim, g.n_embd,
                              RAD_SHARD_ROW, grp_layer(l), { src.q, src.k, src.v }, w.h, w.qkv,
                              0, { q_dim, kv_dim, kv_dim }));
 
-    op_rope = rw(b, decl_rotary(b, g, "rope",
-                     RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
-                                RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", g.n_head_kv),
-                                RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
-                                RAD_STR("mode", mode), RAD_INT("rotary_dim", n_rot)),
-                     RAD_NOWEIGHTS),
+    op_rope = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, g.n_head_kv, n_rot, mode),
                  {w.qkv}, {w.qkv});
 
-    /* THE QUERY IS LIFTED OUT OF THE FUSED ROW, and this op is here because libr4d's paged
-     * attention indexes `q` as one dense [total_q, n_head, head_dim] block and has no pitch
-     * argument for it (r4d_attn_args.h, fill_paged). A column slice of the fused projection has a
-     * row pitch of q_dim + 2*kv_dim, so passing it is refused at issue -- correctly, and loudly.
-     *
-     * The gated block beside this one never needs it: its q comes out of a q|gate de-interleave
-     * that writes a buffer of its own. A plain LLaMA attention has no de-interleave, so the choice
-     * is one `cast` a layer (this) or splitting the projection into q and kv (two more launches a
-     * layer, one GEMM and one rope). The copy is the cheaper of the two at decode, which is the
-     * step that matters, and it is one line to delete if the kernels ever take a q pitch.
-     *
-     * `from` and `to` are the same dtype: `cast` with no conversion is this tree's row copy, and
-     * the drafter tap uses it the same way. */
+    /* Copies the query out of the fused row: libr4d's paged attention reads `q` as a dense
+     * [total_q, n_head, head_dim] block with no pitch argument (r4d_attn_args.h, fill_paged), so a
+     * column slice with pitch q_dim + 2*kv_dim is refused at issue. One copy per layer is cheaper
+     * at decode than splitting the projection (one more GEMM and one more rope). Remove it if the
+     * kernels gain a q pitch. `cast` with from == to is this tree's row copy. */
     op_qlift = rw(b, RAD_OP(b, "cast",
                       RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", q_dim),
                                  RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
                       RAD_NOWEIGHTS),
                   {w.qkv}, {w.q});
 
-    /* Declared before kv_store because `block_size` is RAD_DERIVED and kv_store reads the resolved
-     * kernel's value back; see rad_block_attn_gated.h on why the declared order differs from the
-     * issue order. */
+    /* Declared before kv_store, which reads back the resolved `block_size` (rad_block_attn_gated.h
+     * explains declare vs issue order). */
     op_attn = rw(b, RAD_OP(b, "attn_paged",
                      RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
                                 RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
@@ -169,8 +142,8 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
                          RAD_NOWEIGHTS),
                      {w.qkv}, {});
 
-    /* The out-projection's input quantiser. The gated block folds this into its gate pass; there
-     * is no gate here, so it is the plain `quant_act_fp8` over the attention output. */
+    /* The out-projection's input quantiser; a plain `quant_act_fp8`, as there is no gate pass to
+     * fold it into. */
     RAD_ARCH_TRY(q_attn.declare(b, g, w.attn, q_dim));
     RAD_ARCH_TRY(o.declare(b, nm, g, nm.f("blk.%d.attn_output", l), g.n_embd, q_dim,
                            RAD_SHARD_COL, grp_layer(l), { src.o }, w.attn, w.h.x));
@@ -204,11 +177,11 @@ inline void AttnFP8::step(RadCtx* c, const RadBatch* batch) const {
 
     nq_h.step(c, T);
     qkv.step(c, w.h, w.qkv, T);
-    /* IN PLACE OVER THE FUSED ROW, which is what makes one launch do both halves: `rope` rotates
-     * `n_head` query heads then `n_head_kv` key heads and leaves the value heads alone. */
-    RAD_ISSUE(c, op_rope, brows(w.qkv, T), praw(batch->positions, RAD_I32, T));
+    /* In place over the fused row: rotates n_head query heads, then n_head_kv key heads, and
+     * leaves the value heads alone. */
+    RAD_ISSUE(c, op_rope, brows(w.qkv, T), rope_posmc(g, batch, T));
 
-    /* k and v are COLUMN SLICES of the same row, at q_dim and q_dim + kv_dim. */
+    /* k and v are column slices of the fused row, at q_dim and q_dim + kv_dim. */
     RAD_ISSUE(c, op_kv_store,
               bcol(w.qkv, q_dim, kv_dim, T), bcol(w.qkv, q_dim + kv_dim, kv_dim, T),
               praw(slot, RAD_I32, T), kv_cache(kv, layer));
diff --git a/arch/common/rad_block_attn_gated.h b/arch/common/rad_block_attn_gated.h
index dd3ad321..2b7b09dc 100644
--- a/arch/common/rad_block_attn_gated.h
+++ b/arch/common/rad_block_attn_gated.h
@@ -1,35 +1,26 @@
-/* rad_block_attn_gated.h -- one GATED grouped-query attention block, bf16 operands, paged KV.
+/* rad_block_attn_gated.h -- gated grouped-query attention, bf16 operands, paged KV.
  *
- *   rmsnorm -> q|gate gemm, k gemm, v gemm -> qk-norm + rope + gate extraction
- *   -> kv_store -> paged attention -> attn * sigmoid(gate) -> o gemm -> [all_reduce] -> residual
+ *   rmsnorm -> q|gate gemm, k gemm, v gemm -> qk-norm + rope -> kv_store -> paged attention
+ *   -> attn * sigmoid(gate) -> o gemm -> [all_reduce] -> residual
  *
- * This is Qwen3.5's attention and not Qwen3's, and the difference is not a flag:
+ * Qwen3.5's attention, which differs from Qwen3's in three ways:
  *
- *   * `q_proj` emits the query AND a per-head output gate INTERLEAVED at a pitch of 2*head_dim.
- *     Head h's query is at h*2*head_dim and its gate at h*2*head_dim + head_dim, so neither is a
- *     contiguous half of the projection and both are strided views of one buffer. libr4d's
- *     `qk_norm_rope_gate` splits [q|gate] per head and takes the stride off the `qg` OPERAND's own
- *     row pitch, so the interleaved layout is the one to declare rather than to convert away at
- *     load. There is no `qg_pitch` PARAMETER to pass -- see pQkNormRopeGate in
- *     libr4d/r4d_rows.cpp -- the stride comes from the operand.
- *   * The gate multiplies the attention OUTPUT -- `out = attn * sigmoid(gate)` -- so it is
- *     extracted before attention and consumed after it. `output_gate_type: "swish"` in the config
- *     names the GDN block's gate, not this one; llama.cpp uses sigmoid here and it is ground truth
- *     (../llama.cpp/src/models/qwen35.cpp, build_layer_attn).
- *   * RoPE is PARTIAL -- `partial_rotary_factor` 0.25 rotates the first 64 of 256 head dims -- and
- *     it is MROPE. See the note on `mode` in declare(): with one position component per token,
- *     which is all RadBatch carries, mrope and neox are the same arithmetic, and that equality is
- *     what makes this declaration honest for text and wrong for an image span.
+ *   * `q_proj` emits the query and a per-head output gate interleaved at a pitch of 2*head_dim:
+ *     head h's query at h*2*head_dim, its gate at h*2*head_dim + head_dim. Both are strided views
+ *     of one buffer. libr4d's `qk_norm_rope_gate` takes the stride from the `qg` operand's row
+ *     pitch (there is no `qg_pitch` parameter; pQkNormRopeGate in libr4d/r4d_rows.cpp), so the
+ *     interleaved layout is declared as is.
+ *   * The gate multiplies the attention output, `out = attn * sigmoid(gate)`. The config's `output_gate_type: "swish"` refers to the
+ *     GDN block's gate; this one is sigmoid, as in llama.cpp (src/models/qwen35.cpp,
+ *     build_layer_attn).
+ *   * RoPE is partial (`partial_rotary_factor` 0.25 rotates the first 64 of 256 head dims) and is
+ *     M-RoPE; see `mode` in declare().
  *
- * K AND V ARE NOT FUSED INTO ONE PROJECTION, and that is a decision with a cost: two GEMM launches
- * a layer instead of one, and two movement units instead of one. It buys every consumer a
- * CONTIGUOUS operand. A fused [k|v] row makes the per-head k norm a rank-2 column slice whose last
- * dimension is kv_dim while the norm's width is head_dim, and a kernel that reads extents off its
- * operands -- libref does, by rule -- then walks it as if it were contiguous and normalises
- * across the k/v seam. The fused form is expressible the moment the slice carries the head
- * dimension in its own right; until then this is correct and slightly slow rather than fast and
- * silently wrong. libr4d's kernel takes a `k_pitch` for the fused form, so the w8a8 sibling can
- * make the other choice without changing this block's shape.
+ * k and v are separate projections (two GEMMs, two movement units) so every consumer gets a
+ * contiguous operand. With a fused [k|v] row the per-head k norm would be a column slice whose
+ * last dimension is kv_dim, not head_dim, and a kernel reading extents from its operands (libref
+ * does) would normalise across the k/v seam. libr4d's kernel takes a `k_pitch` for the fused
+ * form, so a quantised sibling can fuse without changing this block's shape.
  */
 #ifndef RAD_BLOCK_ATTN_GATED_H
 #define RAD_BLOCK_ATTN_GATED_H
@@ -40,9 +31,8 @@ namespace rad {
 namespace arch {
 
 struct AttnGatedBF16 {
-    /* The activation buffers this block reads and writes. Declared once by the plugin and shared
-     * by every layer of this kind: layers that share a geometry share the buffer (spec §8), and
-     * the liveness analysis over the declared read and write sets is what makes that safe. */
+    /* Activation buffers, declared once by the plugin and shared by every layer of this kind
+     * (spec §3.1); liveness over the declared read/write sets makes the sharing safe. */
     struct Wire {
         rad_buf x    = 0;   /* [max_tok, n_embd]              the residual stream */
         rad_buf h    = 0;   /* [max_tok, n_embd]              normed input, then the o output */
@@ -50,14 +40,12 @@ struct AttnGatedBF16 {
         rad_buf k    = 0;   /* [max_tok, kv_dim] */
         rad_buf v    = 0;   /* [max_tok, kv_dim] */
         rad_buf q    = 0;   /* [max_tok, q_dim]   de-interleaved, normed, rotated */
-        rad_buf gate  = 0;  /* [max_tok, q_dim]   de-interleaved, then sigmoid in place */
+        rad_buf gate = 0;   /* [max_tok, q_dim]   sigmoid of the de-interleaved gate */
         rad_buf attn = 0;   /* [max_tok, q_dim]   attention output, then gated in place */
     };
 
-    /* The checkpoint-side names for one layer. The plugin owns both sides of the map and is the
-     * only component that knows both (spec §2.4), so the block takes the spelling rather than
-     * inventing one -- this architecture arrives as `model.language_model.layers.N.*` from the
-     * safetensors checkpoint and as `blk.N.*` from a GGUF. */
+    /* Checkpoint-side names for one layer, supplied by the plugin, which owns the map (spec §2.4):
+     * `model.language_model.layers.N.*` from safetensors, `blk.N.*` from GGUF. */
     struct Src {
         const char* norm   = nullptr;   /* input_layernorm.weight */
         const char* qg     = nullptr;   /* self_attn.q_proj.weight -- query AND gate */
@@ -78,8 +66,7 @@ struct AttnGatedBF16 {
     rad_weight w_norm = 0, w_qg = 0, w_k = 0, w_v = 0, w_q_norm = 0, w_k_norm = 0, w_o = 0;
 
     rad_op op_norm = 0, op_qg = 0, op_kp = 0, op_vp = 0;
-    rad_op op_fused = 0;                                     /* qk_norm_rope_gate, if it resolves */
-    rad_op op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0;   /* the fallback */
+    rad_op op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0;
     rad_op op_attn = 0, op_kv_store = 0, op_sigmoid = 0, op_gate = 0;
     rad_op op_o = 0, op_ar = 0, op_add = 0;
 
@@ -103,13 +90,10 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
         return RAD_E_INVAL;
     }
 
-    /* KV-HEAD REPLICATION IS NOT PLUMBED HERE. `geom_from` answers a world size above the KV head
-     * count by giving every rank ONE kv head and a `kv_off` row span into a projection that stays
-     * `n_head_kv_all * head_dim` rows in the container -- and this block declares its k and v with
-     * the plain even row-shard, which at four ranks would hand a rank half of one KV head. The
-     * shapes would declare, the numbers would be wrong, and the text would be fluent. Refuse by
-     * name instead: rad_block_attn_gated_fp8.h is the block that passes the span, and a bf16 model
-     * that needs TP4 plumbs it the same way. */
+    /* KV-head replication is not supported here. Above the KV head count geom_from gives each rank
+     * one KV head and a `kv_off` row span, but this block declares k and v with the plain even
+     * row shard, which would hand a rank part of one head and compute wrong values. The span is
+     * passed in rad_block_attn_gated_fp8.h. */
     if (g.world > g.n_head_kv_all) {
         fprintf(stderr, "radiance: %s declares no KV row span and cannot serve world_size = %d "
                         "with n_head_kv = %lld; the KV-head replication in geom_from needs the "
@@ -118,13 +102,12 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
         return RAD_E_UNSUPPORTED;
     }
 
-    /* ---- weights. Shapes are [out, in]: gemm_nt is A[M,K] times B transposed [N,K], the layout
-     * every transformer weight already has, so nothing is transposed at load.
+    /* ---- weights. Shapes are [out, in]: gemm_nt multiplies A[M,K] by B[N,K] transposed, the
+     * layout checkpoints already use.
      *
-     * The q|gate projection row-shards by HEAD, and that works only because each head's query and
-     * gate are adjacent: rows [h*2*head_dim, (h+1)*2*head_dim) are one head's pair, so a rank's
-     * slice of the head range is a contiguous row range. A projection that put all queries before
-     * all gates would not shard this way. */
+     * The q|gate projection row-shards by head because each head's query and gate are adjacent:
+     * rows [h*2*head_dim, (h+1)*2*head_dim) are one head's pair, so a rank's heads form a
+     * contiguous row range. */
     RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l),   src.norm));
     RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_qg.weight", l),     src.qg));
     RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k.weight", l),      src.k));
@@ -141,8 +124,7 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
                       RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW,  grp_layer(l));
     w_v      = decl_w(b, nm.f("blk.%d.attn_v.weight", l),      RAD_BF16, {kv_dim, g.n_embd},
                       RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW,  grp_layer(l));
-    /* One gain vector shared by every head, so it is replicated across ranks even though the heads
-     * are not. */
+    /* One gain vector shared by every head, so replicated across ranks. */
     w_q_norm = decl_w(b, nm.f("blk.%d.attn_q_norm.weight", l), RAD_F32,  {g.head_dim},
                       RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
     w_k_norm = decl_w(b, nm.f("blk.%d.attn_k_norm.weight", l), RAD_F32,  {g.head_dim},
@@ -150,10 +132,8 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
     w_o      = decl_w(b, nm.f("blk.%d.attn_output.weight", l), RAD_BF16, {g.n_embd, q_dim},
                       RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL,  grp_layer(l));
 
-    /* ---- ops, in the order they run, with the one exception noted at attn_paged. Each states the
-     * buffers it reads and writes, because that is what the buffer planner computes liveness
-     * from -- and a gated attention layer has six activation buffers where a plain one has three,
-     * so an undeclared use here costs an arena, not a rounding error. */
+    /* ---- ops, in run order except attn_paged (see there). Each states its read and write sets,
+     * from which the buffer planner computes liveness. */
     op_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", g.wadd), RAD_STR("dtype", g.dtype)),
@@ -176,89 +156,59 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
                    RAD_WEIGHTS(w_v)),
                {w.h}, {w.v});
 
-    /* Fusion is a selection, not a compiler pass (spec §2.3): ask for the fused op, and emit the
-     * sequence it stands for when nothing in the hierarchy serves it.
+    /* The fused qk_norm_rope_gate is not declared: libr4d's version (libr4d/r4d_rows.cpp,
+     * pQkNormRopeGate) takes a precomputed cos/sin table operand, and this block has no PERSIST
+     * [max_ctx, rot] table to give it. The unfused sequence below runs everywhere, including
+     * without libr4d.
      *
-     * THE PROBE IS NOT MADE, because this block cannot fill the fused op's schema. libr4d's
-     * r4d_qk_norm_rope_gate (libr4d/r4d_rows.cpp, pQkNormRopeGate) names the rotary width `rot`,
-     * takes `q_dtype`, and -- the part that matters -- takes a PRECOMPUTED COS/SIN TABLE as a
-     * required input operand instead of `theta`. Nothing in arch/ or core/ builds such a table.
-     * Declaring the op with parameters the schema does not have is a STRUCTURAL error and fails
-     * declare outright; it is not a miss that falls through to the sequence below, because an
-     * unknown parameter is a caller bug and the builder is right to say so.
+     * `mode` is "mrope" (mrope_section [11,11,10], interleaved). Each rotary dimension has its own
+     * frequency and the section only chooses which position component feeds it, so with equal
+     * components (text) mrope is bit-identical to neox.
      *
-     * What making the probe needs, precisely: a PERSIST buffer of [max_ctx, rot] filled once from
-     * theta, and a way for a plugin to fill a declared buffer at load -- which the ABI has no hook
-     * for, since buffers are arena storage and weights come from the container. Both are real work
-     * and neither belongs in a probe. Until then this model runs the unfused sequence, which is
-     * correct everywhere and is what makes it run on an install with no libr4d at all.
-     *
-     * `mode` would be "mrope" because that is what the model does: mrope_section [11,11,10] over
-     * an interleaved layout. TWO THINGS ABOUT THAT ARE NOT EXPRESSIBLE and both stay true of the
-     * unfused path. The sections have no parameter in any op schema, and RadBatch carries ONE
-     * position component per token, so all three sections would receive the same position. For
-     * text that is not an approximation: every rotary dimension has its own frequency and the
-     * section only decides which position component feeds it, so mrope over equal components is
-     * bit-identical to neox. It stops being identical the moment an image span gives the
-     * components different values, which is why the vision tower needs both a sections parameter
-     * and a 3-row position array before it can be correct. */
-    op_fused = RAD_NULL_HANDLE;
-    {
+     * Per-head RMS norm is a rmsnorm with M = tokens x heads, n = head_dim. The q norm reads the
+     * strided view of the interleaved projection and writes the contiguous q buffer, so it
+     * de-interleaves in the same pass. The k norm runs in place, which is safe because a row's
+     * scale is computed before the row is written. */
+    op_q_norm = rw(b, RAD_OP(b, "rmsnorm",
+                       RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head),
+                                  RAD_INT("n", g.head_dim),
+                                  RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype)),
+                       RAD_WEIGHTS(w_q_norm)),
+                   {w.qg}, {w.q});
+    op_k_norm = rw(b, RAD_OP(b, "rmsnorm",
+                       RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head_kv),
+                                  RAD_INT("n", g.head_dim),
+                                  RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype)),
+                       RAD_WEIGHTS(w_k_norm)),
+                   {w.k}, {w.k});
+    /* Two rope calls because q and k are separate buffers. `rope` describes a fused [q|k|v] row by
+     * n_head and n_head_kv; n_head_kv 0 makes it a q-only (or k-only) row. */
+    op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, n_rot, mode),
+                   {w.q}, {w.q});
+    op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, n_rot, mode),
+                   {w.k}, {w.k});
 
-        /* Per-head RMS norm is an ordinary rmsnorm with M = tokens x heads and n = head_dim. The q
-         * one reads the STRIDED view of the interleaved projection and writes the contiguous q
-         * buffer, so it de-interleaves and normalises in one pass: the copy llama.cpp spends a
-         * ggml_cont on is this op's output operand. The k one runs in place, which is safe for any
-         * implementation that computes a row's scale before writing the row -- and none can do
-         * otherwise. */
-        op_q_norm = rw(b, RAD_OP(b, "rmsnorm",
-                           RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head),
-                                      RAD_INT("n", g.head_dim),
-                                      RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype)),
-                           RAD_WEIGHTS(w_q_norm)),
-                       {w.qg}, {w.q});
-        op_k_norm = rw(b, RAD_OP(b, "rmsnorm",
-                           RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head_kv),
-                                      RAD_INT("n", g.head_dim),
-                                      RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype)),
-                           RAD_WEIGHTS(w_k_norm)),
-                       {w.k}, {w.k});
-        /* Two rope calls rather than one, because q and k are two buffers here. `rope` describes a
-         * fused [q|k|v] row through n_head and n_head_kv; a call that names only q heads is that
-         * row with an empty k and v, which is what a separate q buffer is. */
-        op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, n_rot, mode),
-                       {w.q}, {w.q});
-        op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, n_rot, mode),
-                       {w.k}, {w.k});
-    }
-
-    /* attn_paged is declared BEFORE kv_store even though it runs after it. block_size is
-     * RAD_DERIVED -- the KV block size is a property of the resolved attention kernel and not a
-     * number anyone gets to choose (spec §7.2) -- so it is OMITTED here, the selector skips
-     * constraints on it while matching, writes the winner's value into the resolved geometry, and
-     * kv_store reads it back with rad_kv_block_size(). The two ops touch disjoint buffers, so the
-     * declared order differing from the issue order costs the buffer planner nothing.
+    /* attn_paged is declared before kv_store although it runs after it. `block_size` is
+     * RAD_DERIVED, a property of the resolved attention kernel (spec §7.2): the selector writes the
+     * winner's value into the resolved geometry and kv_store reads it with rad_kv_block_size().
+     * The ops touch disjoint buffers, so the order mismatch does not affect buffer planning.
      *
-     * The ranged parameter is q_len, not M: one query row at decode, up to n_spec+1 at a
-     * speculative verify, thousands in a prefill chunk, and libr4d has a different kernel for each
-     * band. `scale` is left off: 1/sqrt(head_dim) is the default and is what this model uses. */
+     * The ranged parameter is q_len, not M: 1 at decode, up to n_spec+1 at a verify, thousands in
+     * a prefill chunk, with a libr4d kernel per band. `scale` defaults to 1/sqrt(head_dim). */
     op_attn = rw(b, RAD_OP(b, "attn_paged",
                      RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
                                 RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
                                 RAD_INT("window", 0),
-                                /* n_head, max_seqs and max_ctx are what the resolved kernel's SCRATCH HOOK
-                                 * needs at declare: libr4d sizes a split-KV partial buffer of
-                                 * num_seqs * q_len * q_heads * splits rows, and gqa gives the head
-                                 * ratio rather than the count. All three are bounds, which is the
-                                 * right kind of number for an arena sized once for the worst step. */
+                                /* Bounds for the kernel's scratch hook: libr4d sizes a split-KV
+                                 * partial buffer of num_seqs * q_len * q_heads * splits rows. */
                                 RAD_INT("n_head", g.n_head), RAD_INT("block_size", RAD_KV_BLOCK), RAD_INT("max_seqs", g.max_seqs),
                                 RAD_INT("max_ctx", g.max_ctx),
                                 RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
                      RAD_NOWEIGHTS),
                  {w.q}, {w.attn});
 
-    /* kv_store writes the group's pool, which is not a declared buffer -- so its write set is
-     * empty and its read set is the two projections it stores. */
+    /* kv_store writes the group's pool, which is not a declared buffer, so its write set is
+     * empty. */
     op_kv_store = rw(b, RAD_OP(b, "kv_store",
                          RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
                                     RAD_INT("n_head_kv", g.n_head_kv),
@@ -267,19 +217,14 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
                          RAD_NOWEIGHTS),
                      {w.k, w.v}, {});
 
-    /* The gate. Two ops rather than one fused `mul(attn, sigmoid(gate))`, because the vocabulary
-     * has no gated multiply for a bf16 output -- `gated_had_quant_i8` is the same arithmetic with
-     * an int8 epilogue and is what the w8a8 sibling will use instead of this pair.
-     *
-     * The sigmoid's INPUT differs between the two paths and its output does not: the fused kernel
-     * has already written a contiguous gate, and the fallback reads the strided view of the
-     * interleaved projection. Same op, same geometry, one operand spelled two ways -- which is why
-     * there is no second declaration and no branch after this point. */
+    /* The gate, as two ops: the op vocabulary has no gated multiply with a bf16 output
+     * (`gated_had_quant_i8` is the same arithmetic with an int8 epilogue). The sigmoid reads the
+     * strided gate view of the interleaved projection into the contiguous gate buffer. */
     op_sigmoid = rw(b, RAD_OP(b, "sigmoid",
                         RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head),
                                    RAD_INT("n", g.head_dim), RAD_STR("dtype", g.dtype)),
                         RAD_NOWEIGHTS),
-                    {w.qg, w.gate}, {w.gate});
+                    {w.qg}, {w.gate});
 
     op_gate = rw(b, RAD_OP(b, "mul",
                      RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", q_dim),
@@ -293,12 +238,10 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
                   RAD_WEIGHTS(w_o)),
               {w.attn}, {w.h});
 
-    /* The output projection is column-sharded, so each rank holds a partial sum of the residual
-     * update and the ranks must agree before the add. The core inserts nothing: this collective is
-     * here because the plugin put it here, and --debug-graph shows it exactly here (spec §9).
-     * `exact` is stated rather than defaulted -- a caller that does not say it will accept a
-     * quantised wire gets the exact kernel or no kernel. `hops` is not stated: one-shot against
-     * two-shot is the kernel library's choice, by message size. */
+    /* The column-sharded output projection leaves a partial sum on each rank. The plugin emits the
+     * collective itself, so --debug-graph shows it here (spec §9). `exact` is always stated, so a
+     * deployment that has not accepted a lossy wire gets the exact kernel. `hops` (one-shot vs
+     * two-shot) is left to the kernel library, by message size. */
     if (g.world > 1)
         op_ar = rw(b, RAD_OP(b, "all_reduce",
                        RAD_PARAMS(RAD_INT("world_size", g.world),
@@ -318,9 +261,8 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
 }
 
 inline void AttnGatedBF16::step(RadCtx* c, const RadBatch* batch) const {
-    /* rad_issue records its own failure and the core aborts the step and fails the requests in it,
-     * naming the kernel and the geometry (spec §17). There is nothing a plugin can usefully do
-     * with the status, and ignoring it is what keeps the run phase a flat readable list. */
+    /* Issue statuses are ignored: rad_issue records a failure and the core aborts the step and
+     * fails its requests, naming the kernel and geometry (spec §17). */
     const RadKVGroupBatch* kvb = kv_batch(batch, kv);
     const int32_t* slot  = kvb ? kvb->slot_mapping : nullptr;
     const int32_t* table = kvb ? kvb->block_table  : nullptr;
@@ -333,44 +275,31 @@ inline void AttnGatedBF16::step(RadCtx* c, const RadBatch* batch) const {
     RAD_ISSUE(c, op_kp,   brows(w.h, T), RAD_W(w_k),    brows(w.k, T));
     RAD_ISSUE(c, op_vp,   brows(w.h, T), RAD_W(w_v),    brows(w.v, T));
 
-    if (op_fused) {
-        RAD_ISSUE(c, op_fused,
-                  brows(w.qg, T), brows(w.k, T), praw(batch->positions, RAD_I32, T),
-                  RAD_W(w_q_norm), RAD_W(w_k_norm),
-                  brows(w.q, T), brows(w.gate, T));
-    } else {
-        /* The q view of the interleaved projection: head_dim columns out of every 2*head_dim, the
-         * declared width kept as the stride. */
-        RAD_ISSUE_N(c, op_q_norm, T * g.n_head,
-                    bcol(w.qg, 0, g.head_dim, T), RAD_W(w_q_norm), brows(w.q, T));
-        RAD_ISSUE_N(c, op_k_norm, T * g.n_head_kv,
-                    brows(w.k, T), RAD_W(w_k_norm), brows(w.k, T));
-        RAD_ISSUE(c, op_rope_q, brows(w.q, T), rope_posmc(g, batch, T));
-        RAD_ISSUE(c, op_rope_k, brows(w.k, T), rope_posmc(g, batch, T));
-    }
+    /* The q view of the interleaved projection: head_dim columns of every 2*head_dim. */
+    RAD_ISSUE_N(c, op_q_norm, T * g.n_head,
+                bcol(w.qg, 0, g.head_dim, T), RAD_W(w_q_norm), brows(w.q, T));
+    RAD_ISSUE_N(c, op_k_norm, T * g.n_head_kv,
+                brows(w.k, T), RAD_W(w_k_norm), brows(w.k, T));
+    RAD_ISSUE(c, op_rope_q, brows(w.q, T), rope_posmc(g, batch, T));
+    RAD_ISSUE(c, op_rope_k, brows(w.k, T), rope_posmc(g, batch, T));
 
     RAD_ISSUE(c, op_kv_store,
               brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer));
 
-    /* The actual query length, not the batch's token count: it is what selects the attention band,
-     * and a verify step and a prefill chunk can carry the same token count at very different
-     * q_len. */
+    /* The longest query length, not the token count, selects the attention band: a verify step and
+     * a prefill chunk can have the same token count at very different q_len. */
     RAD_ISSUE_N(c, op_attn, batch->max_q_len,
                 brows(w.q, T), kv_cache(kv, layer),
                 praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
                 praw(used, RAD_I32, batch->n_seq),
                 RAD_NONE, RAD_NONE,
-                /* cu_seqlens. The batch may be ragged -- one prefill chunk beside other
-                 * sequences one decode row each -- and without it the kernel has to
-                 * assume a single q_len for the whole step, which it cannot. */
+                /* cu_seqlens: the batch may be ragged (a prefill chunk beside decode rows). */
                 praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
                 brows(w.attn, T));
 
-    /* out = attn * sigmoid(gate). The fused kernel wrote the gate contiguously; the fallback left
-     * it interleaved and this is where it is read out. */
-    if (op_fused) RAD_ISSUE_N(c, op_sigmoid, T * g.n_head, brows(w.gate, T), brows(w.gate, T));
-    else          RAD_ISSUE_N(c, op_sigmoid, T * g.n_head,
-                              bcol(w.qg, g.head_dim, g.head_dim, T), brows(w.gate, T));
+    /* out = attn * sigmoid(gate), the gate read out of the interleaved projection. */
+    RAD_ISSUE_N(c, op_sigmoid, T * g.n_head,
+                bcol(w.qg, g.head_dim, g.head_dim, T), brows(w.gate, T));
     RAD_ISSUE(c, op_gate, brows(w.attn, T), brows(w.gate, T), brows(w.attn, T));
 
     RAD_ISSUE(c, op_o, brows(w.attn, T), RAD_W(w_o), brows(w.h, T));
diff --git a/arch/common/rad_block_attn_gated_fp8.h b/arch/common/rad_block_attn_gated_fp8.h
index 6de75cf8..7c6a2352 100644
--- a/arch/common/rad_block_attn_gated_fp8.h
+++ b/arch/common/rad_block_attn_gated_fp8.h
@@ -1,37 +1,26 @@
-/* rad_block_attn_gated_fp8.h -- the gated GQA block with block-scaled FP8 projections.
+/* rad_block_attn_gated_fp8.h -- gated GQA attention with block-scaled FP8 projections.
  *
- * THE ARCHITECTURE IS rad_block_attn_gated.h's AND IS DOCUMENTED THERE: the interleaved query/gate
- * projection and why it is declared rank 3, the partial mrope and what is not expressible about it,
- * why k and v are not fused, why the fused qk_norm_rope_gate probe is withdrawn, and why the gate
- * is a sigmoid. None of that changes with the weight format and none of it is repeated here.
+ * The architecture (interleaved q|gate projection, partial M-RoPE, separate k and v, sigmoid
+ * gate) is documented in rad_block_attn_gated.h. What differs here:
  *
- * What differs:
+ *   - q|gate, k, v and o are LinearFP8: an E4M3 weight with a bf16 [N/128][K/128] scale plane,
+ *     through `gemm_nt_q` at dtype fp8a8.
+ *   - One input quantise feeds the three input projections (they all read the post-norm hidden
+ *     state); the gate pass quantises the out-projection's input.
+ *   - Per-head norms, rope, kv_store and attn_paged stay bf16.
+ *   - The KV cache dtype is `g.kv_dtype`, not `g.dtype`: it is a deployment choice that selects
+ *     libr4d's fp8kv attention family. The attention op and kv_store both take it, so they agree.
+ *   - Optional fused prologue, QSA sparse attention and an attention-zero mode (see declare).
  *
- *   - q|gate, k, v and o are LinearFP8 -- an E4M3 weight with a bf16 [N/128][K/128] scale plane
- *     declared as a weight of its own, through `gemm_nt_q` at dtype fp8a8.
- *   - two `quant_act_fp8` launches a layer, not four: the three input projections all read the
- *     post-norm hidden state, so one quantise feeds all three, and the output projection gets its
- *     own because it reads the gated attention output.
- *   - everything between the GEMMs -- the per-head norms, rope, kv_store, attn_paged, the sigmoid
- *     and the gate multiply -- is UNCHANGED and still bf16.
- *   - THE KV CACHE'S WIDTH IS `g.kv_dtype` AND NOT `g.dtype`. `dtype` follows the WEIGHTS;
- *     "the cache is bf16 because the weights are fp8" is true of this checkpoint and is not a
- *     rule. `kv_dtype` follows the CACHE, which is a deployment choice: the fp8kv attention family
- *     and its descale operands are in libr4d, and the cache dtype is what selects them.
- *     Both the attention op and kv_store take it, so the two cannot disagree about the width of
- *     the thing one writes and the other reads.
- *
- * The q|gate projection is [2*n_head*head_dim, n_embd] = [12288, 5120] at 27B, and its scale plane
- * is [96, 40]. Row-sharding by head keeps whole 128-row scale blocks together only because
- * 2*head_dim is 512, a multiple of 128 -- so a rank's slice of the head range is a whole number of
- * scale rows. LinearFP8 checks that rather than trusting it.
+ * The q|gate projection is [2*n_head*head_dim, n_embd] = [12288, 5120] at 27B, scale plane
+ * [96, 40]. Row-sharding by head keeps whole 128-row scale blocks only because 2*head_dim = 512 is
+ * a multiple of 128; LinearFP8 checks this.
  */
 #ifndef RAD_BLOCK_ATTN_GATED_FP8_H
 #define RAD_BLOCK_ATTN_GATED_FP8_H
 
 #include "rad_fp8.h"
 
-#include 
 #include 
 
 namespace rad {
@@ -45,14 +34,13 @@ struct AttnGatedFP8 {
         rad_buf k    = 0;   /* [max_tok, kv_dim] */
         rad_buf v    = 0;   /* [max_tok, kv_dim] */
         rad_buf q    = 0;   /* [max_tok, q_dim]   de-interleaved, normed, rotated */
-        /* [rope_table_rows, rot] f32, the model's, shared by every layer and filled once a step.
-         * Zero means the plugin has not been taught to build one, and then the fused prologue is
-         * not asked for at all. */
+        /* [rope_table_rows, rot] f32 cos/sin table, shared by every layer, filled once a step. Zero
+         * if the plugin builds none; the fused prologue is then not requested. */
         rad_buf cos_sin = 0;
         ActFP8  attn{};     /* [max_tok, q_dim]   attention output, then gated in place */
-        /* [max_tok, q_dim] the de-interleaved sigmoid gate, in a model whose linears are bf16
-         * (Geom::w_bf16) only: there the gate is `sigmoid` then `mul`, rad_block_attn_gated.h's
-         * pair, and the fp8 path's fused gate-and-quantiser has no form that skips its codes. */
+        /* [max_tok, q_dim] de-interleaved sigmoid gate, used only with bf16 linears
+         * (Geom::w_bf16), where the gate is `sigmoid` then `mul`; the fused gate quantiser always
+         * writes codes. */
         rad_buf gate = 0;
     };
 
@@ -71,66 +59,47 @@ struct AttnGatedFP8 {
     int         layer = 0;
     rad_kvgroup kv    = 0;
     int64_t     n_rot = 0;
-    /* THE KV PAGE, IN TOKENS. 0 means RAD_KV_BLOCK, which is 16 and is what every geometry in
-     * this tree has wanted. It is a field rather than that constant because Qwen4-Exp's QSA
-     * selects 4-TOKEN BLOCKS, and a page of 4 makes the selected set a paged block table instead
-     * of a new attention kernel -- see docs/QSA.md. The attention kernel's own rows must carry a
-     * matching C_EQ("block_size", ...) or nothing resolves, which is the check that keeps this
-     * from being a number anyone can set. */
+    /* The KV page in tokens; 0 means RAD_KV_BLOCK (16). Qwen4-Exp's QSA selects 4-token blocks,
+     * and a page of 4 turns the selected set into a paged block table, so no new attention kernel
+     * is needed (docs/QSA.md). The attention kernel's rows must carry a matching
+     * C_EQ("block_size", ...) or nothing resolves. */
     int64_t     kv_block = 0;
-    /* THE QSA SELECTION, when this layer has an indexer. Set, and on a step where one query a
-     * sequence makes the selection per-SEQUENCE, the attention is issued with these in place of
-     * the sequence's own block table and context length -- which is the whole of what makes it
-     * sparse. Both are ordinary operands (the block table has always been one), so this is the
-     * SAME op and the SAME kernel reading a different list.
-     *
-     * `sel` is `topk + 1` wide and the kernel takes its block-table pitch from the operand, so
-     * nothing else has to be told. See docs/QSA.md; arch/common/rad_qsa.h produces them. */
+    /* The QSA selection, when this layer has an indexer (produced by arch/common/rad_qsa.h; see
+     * docs/QSA.md). On a sparse step the attention is issued with these in place of each row's
+     * block table and context length: same op, same kernel, different list. `sel` is `topk + 1`
+     * wide and the kernel takes its block-table pitch from the operand. */
     rad_buf     qsa_sel  = 0;
     rad_buf     qsa_sequ = 0;
-    /* THE CONTEXT UP TO WHICH THE DENSE PATH IS THE SAME ANSWER, `budget + ratio - 1`. Below it
-     * every complete block is selected and the two paths agree to the bit, and the dense one is
-     * cheaper at prefill -- it reads each key once a query TILE where the sparse one reads a
-     * table a query. Above it the dense path is a different model. Zero means "always sparse",
-     * which is what a caller that has not been told the bound should get. */
+    /* Context length up to which dense attention gives the same result, `budget + ratio - 1`.
+     * Below it every complete block is selected, the paths agree to the bit, and dense is cheaper
+     * at prefill (it reads each key once per query tile, sparse reads a table per query). Zero
+     * means always sparse. */
     int64_t     qsa_exact_to = 0;
-    /* `sel`'s row pitch, `topk + 1`. The extra slot is the partial page and is not spare --
-     * r4d_qsa_select_bf16.hip says why. */
+    /* `sel`'s row pitch is `topk + 1`; the extra slot is the partial page
+     * (r4d_qsa_select_bf16.hip). */
     int64_t     qsa_topk = 0;
-    /* HOW MANY QUERY ROWS ONE SPARSE ATTENTION LAUNCH CARRIES, and it is a scratch budget rather
-     * than a preference. The decode kernel's split-KV partials are sized AT DECLARE from the
-     * `max_seqs` and `q_len` parameters, so the only way to issue more rows than `max_seqs` is to
-     * declare a larger one -- which grows the scratch arena by `rows * q_len_band * n_head *
-     * (head_dim + 2) * 4`, about 32 MiB at 256 rows on this model, ONCE for the whole program
-     * because the arena is the maximum over ops.
-     *
-     * It matters because the alternative is `max_seqs` itself. At `--max-num-seqs 4` a 2048-token
-     * prefill chunk would be 512 launches a layer, and the dispatch cost of that dominates what
-     * the sparse path saves. 256 makes it 8.
-     *
-     * Raising it further is pure scratch: 512 rows is 63 MiB, 2048 is 253. 256 is the point at
-     * which the launch cost has stopped mattering. */
+    /* Query rows per sparse attention launch, a scratch budget. The decode kernel's split-KV
+     * partials are sized at declare from `max_seqs` and `q_len`, so issuing more rows than
+     * `max_seqs` means declaring a larger value, which grows the scratch arena (the maximum over
+     * ops) by `rows * q_len_band * n_head * (head_dim + 2) * 4` bytes: about 32 MiB at 256 rows on
+     * this model, 63 MiB at 512, 253 MiB at 2048. With max_seqs alone, `--max-num-seqs 4` would
+     * split a 2048-token prefill chunk into 512 launches per layer; 256 makes it 8, past which
+     * launch cost no longer matters. */
     static constexpr int64_t kQsaRows = 256;
     int64_t qsa_rows() const { return g.max_seqs > kQsaRows ? g.max_seqs : kQsaRows; }
-    /* THE GATED FORM TAKES THE WHOLE STEP IN ONE LAUNCH, because its band is q_len 1 and so its
-     * partials are only `rows * n_head * (2 * head_dim + 8)` bytes -- 12.8 MiB at a 2048-row step
-     * on this model, where the ungated op's q_len band makes the same rows cost the figures
-     * above. Fewer launches still pay here: one 2048-row launch takes about 2.16 ms a layer
-     * against about 3.0 ms for eight 256-row ones, each of which is 256 one-wave workgroups -- two
-     * waves a SIMD -- with its own tail. */
+    /* The gated form takes the whole step in one launch: its band is q_len 1, so partials are only
+     * `rows * n_head * (2 * head_dim + 8)` bytes (12.8 MiB for 2048 rows on this model). One
+     * 2048-row launch is about 2.16 ms per layer versus 3.0 ms for eight 256-row launches, each
+     * with its own tail. */
     int64_t qsa_gq_rows() const { return g.max_tok > qsa_rows() ? g.max_tok : qsa_rows(); }
-    /* THE ROTATION'S PAIRING, a question the checkpoint cannot answer by inspection and that no
-     * per-op check can reach, because both readings -- halves (NeoX, what HF's rotate_half does
-     * over the partial rotary width) and adjacent pairs (GPT-J) -- are self-consistent and libref
-     * shares whichever one the graph picks. Either answer is a DIFFERENT MODEL. "mrope" is what the
-     * model does, and over one position component a token it is NeoX (rad_block_attn_gated.h).
+    /* The rotation's pairing. Halves (NeoX, HF's rotate_half over the partial rotary width) and
+     * adjacent pairs (GPT-J) are both self-consistent and pass every per-op check, so it must be
+     * stated. "mrope" over one position component per token is NeoX (rad_block_attn_gated.h).
      *
-     * THE q|gate ORDER IS FIXED TOO. q is the FIRST half of each head's pair and the gate the
-     * second, which is how vLLM chunks q_gate, and every consumer of the projection has to agree
-     * on it: the unfused q norm reads column 0 of each head, the gate quantiser column head_dim,
-     * and the fused prologue splits the pair the same way inside its kernel. A swap would be
-     * arithmetically silent -- q_norm renormalises either half and the sigmoid accepts either --
-     * so an order that only some of them followed would be fluent and wrong. */
+     * The q|gate order is fixed as well: q is the first half of each head's pair, the gate the
+     * second (as vLLM chunks q_gate). The unfused q norm reads column 0 of each head, the gate
+     * quantiser column head_dim, and the fused prologue splits the same way. A swap would pass
+     * silently, since q_norm and the sigmoid accept either half. */
     const char* mode  = "mrope";
 
     rad_weight w_norm = 0, w_q_norm = 0, w_k_norm = 0;
@@ -140,39 +109,54 @@ struct AttnGatedFP8 {
     NormQuantFP8 nq_h{};
 
     rad_op     op_fused = 0;                                 /* qk_norm_rope_gate, if it resolves */
-    rad_op     op_fused_kv = 0;                              /* ...with kv_store folded on, likewise */
-    int64_t    fused_rows = 0;                               /* ...and the widest T it is issued at */
+    rad_op     op_fused_kv = 0;                              /* the same with kv_store folded in */
+    int64_t    fused_rows = 0;                               /* widest T the fused ops take */
     rad_op     op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0;
     rad_op     op_attn = 0, op_kv_store = 0, op_gq = 0;
     rad_op     op_attn_gq = 0;                               /* attn_paged + gate_quant_fp8 */
-    rad_op     op_sig = 0, op_mul = 0;                       /* the bf16 gate, Geom::w_bf16 */
+    /* The output gate as `sigmoid` then `mul`: the bf16-linear form (Geom::w_bf16), and with fp8
+     * linears the chain gate_quant_fp8 fuses, where it is not served. `gate` is the sigmoid's
+     * output (the wire's with bf16 linears, the block's own otherwise) and `q_gate` the chain's
+     * quantiser (no op with bf16 linears). */
+    rad_op     op_sig = 0, op_mul = 0;
+    rad_buf    gate = 0;
+    QuantFP8   q_gate{};
     rad_op     op_ar = 0, op_add = 0;
     rad_op     op_fill = 0;                                  /* the attention-zero rank: see declare */
-    /* ...AND WHETHER THE COLLECTIVE AT THE END OF THIS BLOCK IS THE NEXT BLOCK'S FIRST PASS.
-     * `ar_in` says this block's own norm absorbs its PREDECESSOR's all-reduce; `ar_out` says the
-     * block after it absorbs THIS one's, so this one must not issue it. They are the residual
-     * fold's two flags again, one boundary later, and they are separate for the same reason: a
-     * block is declared without knowing what follows it. On EITHER wire -- the fused kernel
-     * carries both payloads -- and both sides ask ar_fused_ok(g, T), so the two cannot disagree
-     * about whether the collective has already been issued. */
+    /* The next block absorbs this block's closing all-reduce, so this one must not issue it.
+     * Counterpart of `ar_in` (this block's norm absorbs the predecessor's); separate because a
+     * block is declared without knowing what follows. Both sides ask ar_fused_ok(g, T), so they
+     * agree on whether the collective was issued. */
     bool ar_out = false;
-    /* ...and WHICH WIRES that consumer takes (ArOut, rad_fp8.h): the norm's by default, and a gated
-     * residual's write says its own (HyperConn::ar_take). Set before declare; both sides then ask
+    /* Which wires that consumer takes (ArOut, rad_fp8.h): the norm's by default, or a gated
+     * residual's own (HyperConn::ar_take). Set before declare; both sides then ask
      * ar_taken(g, T, ar_out, ar_out_take). */
     int  ar_out_take = kArOutNorm;
 
-    /* `fold` says the PREVIOUS block left its delta in `w.h.x` for this norm to add; `add_out`
-     * says the NEXT one will not, so this block issues the trailing add itself. See rad_fp8.h. */
+    /* `fold`: the previous block left its delta in `w.h.x` for this norm to add. `add_out`: the
+     * next block will not add, so this one issues the trailing add. See rad_fp8.h. */
     int  declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group,
                  int64_t rotary_dim, const Wire& wire, const Src& src,
                  bool fold = false, bool add_out = true,
                  int ar_in = kArNone, bool ar_out_ = false);
-    void step(RadCtx* c, const RadBatch* batch) const;
-    /* The pass's K and V into the cache and nothing else: no query, no attention, no output. What a
-     * pass that only leaves the layer's state behind asks for -- the MTP head's history pass over
-     * a prompt chunk with no row that drafts. The keys are the ones step() stores: the same
-     * projection, norm, rotation and store. */
+    /* Stores the pass's K and V exactly as step() does, with no query, attention or output. Used
+     * by passes that only leave layer state behind, such as the MTP head's history pass over a
+     * prompt chunk with no drafting row. */
     void store_kv(RadCtx* c, const RadBatch* batch) const;
+
+    /* The block's tail, declared last by every rank: the all-reduce and the trailing add. */
+    int  declare_out(RadBuilder* b, bool add_out);
+    /* `own_ar` false: the caller issues the all-reduce itself (GdnFP8::step says when). */
+    void step(RadCtx* c, const RadBatch* batch, bool own_ar = true,
+              ArPieces* pieces = nullptr) const;
+    bool issues_ar(int64_t T) const { return op_ar && !ar_taken(g, T, ar_out, ar_out_take); }
+    void issue_ar(RadCtx* c, int64_t r0, int64_t rows) const {
+        RAD_ISSUE_N(c, op_ar_ov ? op_ar_ov : op_ar, rows * g.n_embd,
+                    brow_slice(w.h.x, r0, rows, g.n_embd), RAD_NONE);
+    }
+    /* Set before declare: the `overlap` issue_ar's collective is declared at, 0 for none. */
+    int    ar_overlap = 0;
+    rad_op op_ar_ov = 0;
 };
 
 inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
@@ -186,23 +170,17 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
     const int64_t kv_dim = g.kv_dim();
     const int64_t qg_dim = 2 * q_dim;
 
-    /* THE KV ROW SPAN, AND IT ONLY EXISTS ABOVE THE KV HEAD COUNT.
-     * A world size larger than `n_head_kv_all` cannot divide the KV heads, so rad_arch.h's
-     * `geom_from` replicates them in PAIRS: two ranks serve the same head, `g.n_head_kv` is 1 on
-     * each, and the checkpoint entry they both read is still `n_head_kv_all * head_dim` rows -- 512
-     * for 2 KV heads at head_dim 256. This rank wants ONE head's row-span of that entry, which the
-     * even shard would cut up instead (at 4 ranks it would hand rank 2 rows [256, 384), half of one
-     * head), so the span `[g.kv_off, g.kv_off + kv_dim)` is declared in the CONTAINER's unsharded
-     * units -- [0, 256) on ranks 0 and 1, [256, 512) on ranks 2 and 3 -- and the scale plane takes
-     * the same span in 128-blocks. `kv_off` is a multiple of head_dim, so it is whole blocks and
-     * never cuts one, and share.cpp's `shard_hi <= cpart` holds with cpart = 512 / 1 part.
-     * AT WORLD <= n_head_kv_all the ordinary even shard already selects exactly these rows, so the
-     * span stays 0/0 and the default path runs as before -- TP2 declares identically. */
-    /* AND UNDER A SMALLER ATTENTION WORLD (rad_arch.h Geom::attn_world: three ranks over two KV
-     * heads) the even shard over `world` is the wrong cut for every projection: q|gate and the
-     * output take this rank's heads [attn_rank * n_head, +n_head) as a span too, and k/v the
-     * kv_off span. An attention-zero rank declares none of them: its block is one `fill` of the
-     * output wire (the branch below), so the spans here are only ever cut for a rank with heads. */
+    /* Row spans, in the container's unsharded rows, used where the even shard is the wrong cut.
+     *
+     * Above the KV head count geom_from replicates KV heads (rad_arch.h): with 2 KV heads at
+     * head_dim 256 and 4 ranks, the k/v entry is 512 rows and ranks 0-1 take [0, 256), ranks 2-3
+     * [256, 512), where the even shard would hand rank 2 half a head. The scale plane takes the
+     * same span in 128-blocks; kv_off is a multiple of head_dim, so it never cuts a block. At
+     * world <= n_head_kv_all the span stays 0/0 and the even shard applies.
+     *
+     * Under a smaller attention world (Geom::attn_world) q|gate and the output also take this
+     * rank's heads [attn_rank * n_head, +n_head) as a span. An attention-zero rank declares none
+     * of them (see the `fill` below). */
     const bool    a_spanned  = g.attn_world != g.world;
     const bool    kv_spanned = g.world > g.n_head_kv_all || a_spanned;
     const int64_t kv_span_lo = kv_spanned ? g.kv_off : 0;
@@ -218,18 +196,13 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
         return RAD_E_INVAL;
     }
 
-    /* THE INPUT MAY BE PREPARED BY THE ARCHITECTURE, and `src.norm == nullptr` is how it says so.
+    /* `src.norm == nullptr`: the architecture prepares the input. A pre-norm block owns its norm
+     * (rad_fp8.h's NormQuantFP8: add the previous delta, normalise, quantise). In a gated-residual
+     * model, rad_block_hc.h's `hc_read` produces the block input from a 4x wider stream, so this
+     * block takes `wire.h` as already normed and quantised and declares no norm weight.
      *
-     * A pre-norm model's block owns its own norm: one op that adds the previous block's delta into
-     * the residual stream, normalises it and quantises it (rad_fp8.h's NormQuantFP8). A GATED
-     * RESIDUAL model's does not -- arch/common/rad_block_hc.h's `hc_read` produces the block input
-     * from a stream four times as wide, with a data-dependent mix the block has no way to compute,
-     * and there is nothing left for a norm here to do. So this block takes `wire.h` as ALREADY
-     * normed and quantised and declares no norm weight at all.
-     *
-     * `ar_in` is refused in that mode rather than ignored: the fused all-reduce lives INSIDE the
-     * norm, so with no norm there is nowhere to fold it and a caller that asked would silently get
-     * an unreduced input. It emits a standalone collective instead (`add_out`/`ar_out`). */
+     * `ar_in` is refused in that mode: the fused all-reduce lives inside the norm, so it would be
+     * silently dropped. The caller emits a standalone collective instead (`add_out`/`ar_out`). */
     ext_in = (src.norm == nullptr);
     if (ext_in) {
         if (!w.h.x || (!g.w_bf16 && (!w.h.q || !w.h.s)) || ar_in != kArNone) return RAD_E_INVAL;
@@ -246,27 +219,23 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
     w_k_norm = decl_w(b, nm.f("blk.%d.attn_k_norm.weight", l), RAD_F32, {g.head_dim},
                       RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
 
-    /* One norm, one quantise, three consumers -- and one op, see rad_fp8.h's NormQuantFP8. */
+    /* One norm+quantise op feeds all three input projections (rad_fp8.h: NormQuantFP8). */
     if (!ext_in)
         RAD_ARCH_TRY(nq_h.declare(b, g, w_norm, fold ? w.h.x : w.x, w.h, g.n_embd,
                                   fold ? w.x : 0, 0, ar_in));
 
-    /* AN ATTENTION-ZERO RANK COMPUTES NO ATTENTION AT ALL. Its share of every projection is zero,
-     * so its q, k and v are zero, its attention is zero and its output projection adds exactly
-     * nothing to the reduce -- which is what the ranks that DO hold heads need from it and all
-     * they need. Declaring the projections and running them on zero weights spent the same
-     * dispatches and bytes as a real rank and a slot for every zero (and a KV pool nothing read,
-     * see rad_kv_group_zero). Here the block's output wire is written to zero by one `fill`, and
-     * the all-reduce and the residual below see what they always saw. The norm above stays: a
-     * pre-norm block's `fold` and `ar_in` live in it. Nothing in this branch runs for a rank with
-     * heads, so a world the heads divide (every TP2 and TP4 deployment) declares as it always did. */
+    /* An attention-zero rank holds no heads, so its output projection contributes zero to the
+     * reduce. Its output wire is zeroed by one `fill` instead of running projections on zero
+     * weights (and it keeps no KV pool, rad_kv_group_zero). The all-reduce and residual add run as
+     * usual, and the norm above stays because a pre-norm block's `fold` and `ar_in` live in it. */
     if (g.attn_zero) {
         op_fill = rw(b, RAD_OP(b, "fill",
                          RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
                                     RAD_STR("dtype", g.dtype)),
                          RAD_NOWEIGHTS),
                      {}, {w.h.x});
-    } else {
+        return declare_out(b, add_out);
+    }
     RAD_ARCH_TRY(qg.declare(b, nm, g, nm.f("blk.%d.attn_qg", l), qg_dim, g.n_embd,
                             RAD_SHARD_ROW, grp_layer(l), { src.qg }, w.h, w.qg,
                             0, {}, qg_span_lo, qg_span_hi));
@@ -277,33 +246,25 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
                             RAD_SHARD_ROW, grp_layer(l), { src.v }, w.h, w.v,
                             0, {}, kv_span_lo, kv_span_hi));
 
-    /* THE FUSED PROLOGUE, AND IT IS A PROBE: the four ops below are declared either way and are
-     * what runs when nothing serves this one. rad_block_attn_gated.h does not make the probe,
-     * because the schema takes a PRECOMPUTED cos/sin table rather than `theta` and that block has
-     * none; `rope_table` builds one here, once a step for every layer, and `w.cos_sin` is where
-     * the model puts it. A block handed no table cannot ask for the fusion, which is what keeps a
-     * plugin that does not build the table on the unfused path.
+    /* The fused prologue (qk norms + rope + q|gate split) is a probe; the four unfused ops below
+     * are declared either way and run when it does not resolve. Its schema takes a precomputed
+     * cos/sin table instead of `theta`: `rope_table` fills `w.cos_sin` once a step for every
+     * layer, and without a table the fusion is not requested.
      *
-     * NEOX ONLY. The fused kernel rotates NeoX pairs and has no `mode`, so the probe is made only
-     * where mrope reduces to neox -- one position component a token, which is every text batch and
-     * is argued in rad_block_attn_gated.h. A vision span would need the sections first.
+     * The kernel rotates NeoX pairs and has no `mode`. M-RoPE qualifies because the table is
+     * filled at one component per token, which is exact when the components agree; step() takes
+     * the fused path only then.
      *
-     * NO `gate_out`. `gate_quant_fp8` below already reads the gate at its column offset inside the
-     * interleaved projection, so a contiguous copy would be q_dim of bf16 a layer written for
-     * nothing. The operand is optional and this passes none.
+     * No `gate_out` is passed: `gate_quant_fp8` reads the gate in place in the interleaved
+     * projection.
      *
-     * IT IS BIT-IDENTICAL TO THE FOUR, checked in r4d_selftest (`qk_norm_rope_gate ... matches the
-     * unfused pair`) rather than argued: the kernel rounds its norm output to bf16 before rotating
-     * because that is what a norm that stores a tensor and a rope that reads it back do. It
-     * reproduces `r4d_rmsnorm_bf16`'s sum-of-squares fold element by element rather than folding
-     * eight elements a lane, and r4d_selftest asserts byte equality. A merely RELATIVE bound is
-     * not enough here: a fold order that agrees to a ULP and not to the last bit moves the
-     * engine's transcript within a few dozen steps. */
-    /* M-RoPE qualifies too: the table is filled at one component a token, which is exact on every
-     * pass whose tokens' components agree, and the step takes the fused path only then. */
+     * Bit-identical to the unfused ops, asserted in r4d_selftest: the kernel rounds the norm output
+     * to bf16 before rotating and reproduces `r4d_rmsnorm_bf16`'s sum-of-squares order element by
+     * element. A ULP-level difference would shift the engine's transcript within a few dozen
+     * steps. */
     const bool rope_neox = !std::strcmp(mode, "neox") || !std::strcmp(mode, "mrope") || g.rope_mc;
     fused_rows = qk_fuse_rows(g);
-    if (w.cos_sin && rope_neox && fused_rows > 0)
+    if (w.cos_sin && rope_neox && fused_rows > 0 && rad_op_declared(b, "qk_norm_rope_gate"))
         op_fused = rw(b, RAD_OP(b, "qk_norm_rope_gate",
                          RAD_PARAMS(RAD_RANGE("M", 1, fused_rows), RAD_INT("head_dim", g.head_dim),
                                     RAD_INT("n_head", g.n_head),
@@ -330,33 +291,25 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
     op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, n_rot, mode),
                    {w.k}, {w.k});
 
-    /* Declared before kv_store because block_size is RAD_DERIVED and kv_store reads it back --
-     * rad_block_attn_gated.h explains why the declared order differs from the issue order. */
+    /* Declared before kv_store, which reads back the resolved `block_size`
+     * (rad_block_attn_gated.h). */
     op_attn = RAD_OP(b, "attn_paged",
                      RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
                                 RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
                                 RAD_INT("window", 0),
                                 RAD_INT("n_head", g.n_head),
                                 RAD_INT("block_size", kv_block > 0 ? kv_block : (int64_t)RAD_KV_BLOCK),
-                                /* The sparse path issues one row a QUERY, so the bound the split-KV
-                                 * scratch is sized from is the widest such launch and not the
-                                 * sequence count -- see kQsaRows. */
+                                /* The sparse path issues one row per query, so the split-KV
+                                 * scratch is sized for the widest launch (kQsaRows). */
                                 RAD_INT("max_seqs", (qsa_sel && qsa_sequ) ? qsa_rows()
                                                                           : g.max_seqs),
                                 RAD_INT("max_ctx", g.max_ctx),
                                 RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
                      RAD_NOWEIGHTS);
-    /* THE QSA SELECTION IS A READ OF THIS OP AND HAS TO BE DECLARED AS ONE. The block table has
-     * always been a raw batch pointer, so `attn_paged`'s read set was just the query -- and
-     * `sel`/`seqused` are BUFFERS, whose lifetimes the Builder plans from exactly these lists. Left
-     * out, their last use is `qsa_select` and the arena is free to lay another buffer over them;
-     * anything written between the selection and the attention then arrives as a page id, and a
-     * garbage page id is an address far outside the cache -- an aperture violation at the first
-     * step whose plan happens to overlap them, which need not be a step that ran before. Spelled
-     * with rad_op_reads rather than rw() because the list is conditional -- a layer with no
-     * indexer has no such read.
-     *
-     * THE DECLARATION ORDER IS THE BUFFER PLAN, and this is one of the shapes that rule takes. */
+    /* The QSA selection buffers must be declared as reads of this op. Otherwise their last use is
+     * `qsa_select`, the arena may overlay another buffer, and the attention reads garbage page
+     * ids: an aperture violation outside the cache. rad_op_reads rather than rw() because the list
+     * depends on whether the layer has an indexer. */
     if (op_attn) {
         const rad_buf rd[3] = { w.q, qsa_sel, qsa_sequ };
         rad_op_reads(b, op_attn, rd, (qsa_sel && qsa_sequ) ? 3 : 1);
@@ -371,12 +324,11 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
                          RAD_NOWEIGHTS),
                      {w.k, w.v}, {});
 
-    /* THE PROLOGUE AND THE CACHE STORE AS ONE LAUNCH, wherever the fused prologue is taken: a k
-     * head's block already holds its token's rotated k, one element a lane, so it writes that and
-     * the head's v into the cache too, byte-for-byte what kv_store would (the fold's row says why).
-     * Declared here and not beside op_fused because the cache's block size is read back from the
-     * attention op above. It resolves for an E4M3 and a bf16 cache alike. */
-    if (op_fused)
+    /* The fused prologue with the cache store folded in: a k head's block already holds its
+     * token's rotated k, so it also writes k and v into the cache, byte-identical to kv_store.
+     * Declared here because the cache block size is read back from the attention op above.
+     * Resolves for E4M3 and bf16 caches. */
+    if (op_fused && rad_op_declared(b, "qk_norm_rope_gate_kv_store"))
         op_fused_kv = rw(b, RAD_OP(b, "qk_norm_rope_gate_kv_store",
                             RAD_PARAMS(RAD_RANGE("M", 1, fused_rows),
                                        RAD_INT("head_dim", g.head_dim), RAD_INT("n_head", g.n_head),
@@ -388,48 +340,62 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
                             RAD_WEIGHTS(w_q_norm, w_k_norm)),
                          {w.qg, w.k, w.cos_sin, w.v}, {w.q, w.k});
 
-    /* THE OUTPUT GATE, THE MULTIPLY AND THE QUANTISER ARE ONE PASS. Unfused they are three --
-     * sigmoid into a de-interleaved buffer, a multiply in place, then quant_act_fp8 -- and at
-     * decode each is small enough that the dispatch gap between them is comparable to the work
-     * itself, once per layer. THE ROW IS A (token, head) PAIR, which is what makes the fusion
-     * expressible: at that shape the gate is a fixed stride inside the [q|gate] projection, the
-     * attention output is contiguous, and the fp8 scale plane of [T * n_head, head_dim / 128] is
-     * byte-for-byte the [T, q_dim / 128] the out projection reads. No separate gate buffer is
-     * declared, because nothing reads one.
+    /* Output gate, multiply and quantiser in one pass (`gate_quant_fp8`); at decode the dispatch
+     * gaps between three small ops are comparable to the work. Each row is a (token, head) pair:
+     * the gate is a fixed stride inside [q|gate], the attention output is contiguous, and the
+     * [T * n_head, head_dim / 128] scale plane is byte-identical to the [T, q_dim / 128] the out
+     * projection reads.
      *
-     * The bf16 product is still written, because that is what the unfused pair left in `w.attn.x`
-     * and the codes are taken over it -- see r4d_fused_quant_fp8.hip on why that is a requirement.
-     * The codes are the int8 pair when the model feeds the out projection int8 (ActFP8::q8_fed),
-     * and the same op writes them: the codes operand's dtype picks the quantiser.
-     * PREFILL AND DECODE BOTH TAKE IT: unlike the gdn fold this one has no reduction across the
-     * row, so there is no shape it cannot serve. */
-    if (g.w_bf16) {
+     * The bf16 product is still written to `w.attn.x` and the codes are taken over it
+     * (r4d_fused_quant_fp8.hip says why). The codes operand's dtype picks the quantiser, int8 when
+     * the out projection is fed int8 (ActFP8::q8_fed). Serves prefill and decode: there is no
+     * cross-row reduction.
+     *
+     * With bf16 linears (Geom::w_bf16) the gate is the plain `sigmoid` + `mul` pair instead.
+     *
+     * Where no loaded library declares gate_quant_fp8, or it does not resolve, the fp8 block runs
+     * the chain it fuses: the gate into a buffer of its own, the multiply, then the activation
+     * quantiser, which write what the fused op writes. A head of whole 128-column blocks makes
+     * the quantiser's [T, q_dim / 128] scale plane the fused op's [T * n_head, head_dim / 128]. */
+    auto gate_pair = [&](rad_buf out) {
+        gate = out;
         op_sig = rw(b, RAD_OP(b, "sigmoid",
                         RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head),
                                    RAD_INT("n", g.head_dim), RAD_STR("dtype", g.dtype)),
                         RAD_NOWEIGHTS),
-                    {w.qg}, {w.gate});
+                    {w.qg}, {gate});
         op_mul = rw(b, RAD_OP(b, "mul",
                         RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", q_dim),
                                    RAD_STR("dtype", g.dtype)),
                         RAD_NOWEIGHTS),
-                    {w.attn.x, w.gate}, {w.attn.x});
-        if (!op_sig || !op_mul) return RAD_E_INVAL;
-    } else
-    op_gq = rw(b, RAD_OP(b, "gate_quant_fp8",
-                   RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head),
-                              RAD_INT("n", g.head_dim), RAD_INT("group", RAD_FP8_BLOCK),
-                              RAD_STR("dtype", g.dtype), RAD_STR("act", "sigmoid")),
-                   RAD_NOWEIGHTS),
-               {w.qg, w.attn.x}, {w.attn.cq(), w.attn.cs(), w.attn.x});
+                    {w.attn.x, gate}, {w.attn.x});
+        return op_sig && op_mul ? RAD_OK : RAD_E_INVAL;
+    };
+    if (g.w_bf16) {
+        RAD_ARCH_TRY(gate_pair(w.gate));
+    } else {
+        if (rad_op_declared(b, "gate_quant_fp8"))
+            op_gq = rw(b, RAD_OP(b, "gate_quant_fp8",
+                           RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head),
+                                      RAD_INT("n", g.head_dim), RAD_INT("group", RAD_FP8_BLOCK),
+                                      RAD_STR("dtype", g.dtype), RAD_STR("act", "sigmoid")),
+                           RAD_NOWEIGHTS),
+                       {w.qg, w.attn.x}, {w.attn.cq(), w.attn.cs(), w.attn.x});
+        if (!op_gq && g.head_dim % RAD_FP8_BLOCK == 0) {
+            RAD_ARCH_TRY(gate_pair(decl_b(b, nm.f("blk.%d.attn_gate", l), g.act_dtype,
+                                          {g.max_tok, q_dim})));
+            RAD_ARCH_TRY(q_gate.declare(b, g, w.attn, q_dim));
+            if (!q_gate.op) return RAD_E_INVAL;
+        }
+    }
 
-    /* AND ON THE SPARSE PATH THE GATE RIDES IN THE ATTENTION'S OWN MERGE. There every launch is
-     * one query row a (token, head) pair at q_len 1, and the split-KV merge that closes each row
-     * holds exactly the 256 values the gate and the quantiser read next -- so the fused op merges,
-     * gates, rounds and quantises the row where it is, byte-for-byte the pair (its row says how),
-     * and the launch between them is gone. Declared only beside a selection: the dense path's
-     * query rows are the band the prefill kernel serves as well, and that kernel has no merge. */
-    if (op_attn && qsa_sel && qsa_sequ && !g.w_bf16) {
+    /* On the sparse path the gate is applied inside the attention's split-KV merge: each launch
+     * row is one (token, head) at q_len 1, and the merge already holds the head_dim values the gate
+     * and quantiser read, so one op merges, gates, rounds and quantises (byte-identical to the
+     * pair). Declared only with a selection: the dense path also uses the prefill kernel, which
+     * has no merge. */
+    if (op_attn && qsa_sel && qsa_sequ && !g.w_bf16 &&
+        rad_op_declared(b, "attn_paged_gate_quant")) {
         op_attn_gq = RAD_OP(b, "attn_paged_gate_quant",
                             RAD_PARAMS(RAD_INT("q_len", 1), RAD_INT("head_dim", g.head_dim),
                                        RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
@@ -453,8 +419,10 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
     RAD_ARCH_TRY(o.declare(b, nm, g, nm.f("blk.%d.attn_output", l), g.n_embd, q_dim,
                            RAD_SHARD_COL, grp_layer(l), { src.o }, w.attn, w.h.x,
                            0, {}, o_span_lo, o_span_hi));
-    }   /* !g.attn_zero */
+    return declare_out(b, add_out);
+}
 
+inline int AttnGatedFP8::declare_out(RadBuilder* b, bool add_out) {
     if (g.world > 1)
         op_ar = rw(b, RAD_OP(b, "all_reduce",
                        RAD_PARAMS(RAD_INT("world_size", g.world),
@@ -463,8 +431,19 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
                                   RAD_INT("min_bytes", g.wire_min_bytes)),
                        RAD_NOWEIGHTS),
                    {w.h.x}, {w.h.x});
+    /* The same collective for a caller that runs it beside other work (issue_ar, a pipelined
+     * prefill): at `overlap` 1 it gets the rows that hold fewer CUs while waiting on the link. */
+    if (g.world > 1 && ar_overlap > 0)
+        op_ar_ov = 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),
+                                     RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
+                                     RAD_INT("min_bytes", g.wire_min_bytes),
+                                     RAD_INT("overlap", ar_overlap)),
+                          RAD_NOWEIGHTS),
+                      {w.h.x}, {w.h.x});
 
-    /* Only where the NEXT block's norm will not do it; see rad_fp8.h's NormQuantFP8. */
+    /* Only when the next block's norm will not add (rad_fp8.h: NormQuantFP8). */
     if (add_out)
         op_add = rw(b, RAD_OP(b, "add",
                     RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
@@ -489,7 +468,8 @@ inline void AttnGatedFP8::store_kv(RadCtx* c, const RadBatch* batch) const {
               brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer));
 }
 
-inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch) const {
+inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
+                               ArPieces* pieces) const {
     const RadKVGroupBatch* kvb = kv_batch(batch, kv);
     const int32_t* slot  = kvb ? kvb->slot_mapping : nullptr;
     const int32_t* table = kvb ? kvb->block_table  : nullptr;
@@ -499,9 +479,9 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch) const {
 
     if (!ext_in) nq_h.step(c, T);
     if (op_fill) {
-        /* The attention-zero rank: the output wire is zero, then the reduce and the residual. */
+        /* Attention-zero rank: zero output, then the reduce and the residual. */
         RAD_ISSUE_N(c, op_fill, T, brows(w.h.x, T));
-        if (op_ar && !ar_taken(g, T, ar_out, ar_out_take))
+        if (own_ar && op_ar && !ar_taken(g, T, ar_out, ar_out_take))
             RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
         if (op_add) RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h.x, T), brows(w.x, T));
         return;
@@ -510,11 +490,10 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch) const {
     kp.step(c, w.h, w.k,  T);
     vp.step(c, w.h, w.v,  T);
 
-    /* Four launches or one. The fused kernel takes the [q|gate] projection WHOLE and splits it
-     * itself -- so `w.qg` goes in as it stands and not as the column slice the unfused norm needs
-     * -- and it rotates k in place, which is what the unfused pair does too. */
-    /* THE FUSED PATH READS ONE COMPONENT A TOKEN, so a pass carrying media tokens -- whose
-     * components differ -- takes the unfused pair with the whole [3, T] instead. */
+    /* Fused or unfused prologue. The fused kernel takes the whole [q|gate] projection and splits it
+     * itself, and rotates k in place like the unfused ops. It reads one rotary component per
+     * token, so a pass with media tokens (differing components) takes the unfused path with the
+     * full [3, T] positions. */
     const bool fuse_ok = T <= fused_rows && !rope_mixed(batch);
     const bool fused_kv = op_fused_kv && fuse_ok;
     if (fused_kv) {
@@ -541,26 +520,49 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch) const {
         RAD_ISSUE(c, op_kv_store,
                   brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer));
 
-    /* ONE ROW A QUERY IS WHAT MAKES THE SPARSE PATH WORK AT PREFILL, and it needs no new kernel
-     * for the same reason the decode path needed none: `attn_paged` indexes its block table and
-     * its length by the ROW, and nothing says a row has to be a sequence. A chunk of T queries
-     * issued as T rows of q_len 1, each with its own selection and its own `seqused`, is exactly
-     * per-query sparse attention -- and at decode, where T is the sequence count, it is the same
-     * issue it has always been.
+    /* Sparse attention issues one row per query. `attn_paged` indexes its block table and length
+     * by row, and a row need not be a sequence, so T queries issued as T rows of q_len 1, each with
+     * its own selection and `seqused`, is per-query sparse attention; at decode T is the sequence
+     * count.
      *
-     * DENSE BELOW THE BOUND, because there the two are the same answer and dense is cheaper: it
-     * reads each key once a query TILE where this reads a table a query. `max_ctx_len` is the
-     * host-side bound the batch already carries, so the test costs nothing.
+     * Below `qsa_exact_to` the dense path gives the same result more cheaply (see the field);
+     * `max_ctx_len` is a host-side bound the batch already carries.
      *
-     * CHUNKED AT max_seqs, and that is not tidiness. The decode kernel's split-KV scratch is
-     * sized AT DECLARE from the `max_seqs` and `q_len` parameters -- max_seqs * q_len_max * heads
-     * rows -- and handing it T rows past that is refused as RAD_E_SCRATCH at issue. max_seqs rows
-     * of q_len 1 is strictly inside what q_len_max >= 1 already bought, so the bound holds
-     * whatever the kernel's band turns out to be. */
+     * Launches are chunked because the split-KV scratch is sized at declare from `max_seqs` and
+     * `q_len` (rows = max_seqs * q_len_max * heads); more rows are refused as RAD_E_SCRATCH at
+     * issue. Rows of q_len 1 up to the declared max_seqs always fit. */
     const int64_t reach  = (int64_t)batch->max_ctx_len + batch->max_q_len;
     const bool    sparse = qsa_sel && qsa_sequ &&
                            (T == batch->n_seq || qsa_exact_to <= 0 || reach > qsa_exact_to);
     const bool gated = sparse && op_attn_gq;
+    /* A piece at a time where the caller takes the all-reduce that way (ArPieces). On the gated
+     * sparse path every query row is its own (q_len 1) and the gate rides in the merge, so the
+     * attention and out projection can finish a piece's rows and hand off its reduction while the
+     * next piece's attention runs. Each piece is launched as a step of the piece's width would
+     * launch it. */
+    if (gated && !own_ar && pieces && pieces->cuts(T) && !op_add) {
+        const int64_t chunk = qsa_gq_rows();
+        const int64_t qw = g.q_dim(), hd = g.head_dim;
+        for (int64_t p0 = 0; p0 < T; p0 += pieces->rows) {
+            const int64_t pn = T - p0 < pieces->rows ? T - p0 : pieces->rows;
+            for (int64_t off = p0; off < p0 + pn; off += chunk) {
+                const int64_t rows = (p0 + pn - off) < chunk ? (p0 + pn - off) : chunk;
+                RAD_ISSUE_N(c, op_attn_gq, 1,
+                            brow_slice(w.q, off, rows, qw),
+                            kv_cache(kv, layer),
+                            brow_slice(qsa_sel, off, rows, qsa_topk + 1),
+                            brow_slice(qsa_sequ, off, rows, 1),
+                            RAD_NONE, RAD_NONE, RAD_NONE,
+                            brow_slice(w.attn.x, off, rows, qw),
+                            bcol_at(w.qg, off, g.n_head * 2 * hd, hd, hd, rows),
+                            brow_slice(w.attn.cq(), off, rows, qw),
+                            brow_slice(w.attn.cs(), off, rows, fp8_blocks(qw)));
+            }
+            o.step(c, w.attn, w.h.x, T, p0, pn);
+            if (p0 + pn < T) pieces->hand(p0, pn);
+        }
+        return;
+    }
     if (gated) {
         const int64_t chunk = qsa_gq_rows();
         const int64_t qw = g.q_dim(), hd = g.head_dim;
@@ -597,25 +599,27 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch) const {
                           kvb ? kvb->block_table_pitch : 0),
                     praw(used, RAD_I32, batch->n_seq),
                     RAD_NONE, RAD_NONE,
-                    /* cu_seqlens. The batch may be ragged -- one prefill chunk beside other
-                     * sequences one decode row each -- and without it the kernel has to
-                     * assume a single q_len for the whole step, which it cannot. */
+                    /* cu_seqlens: the batch may be ragged (a prefill chunk beside decode rows). */
                     praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
                     brows(w.attn.x, T));
     }
 
-    if (op_sig) {
+    if (gated) {
+        /* the sparse attention gated and quantised in its merge */
+    } else if (op_sig) {
         /* The gate is the strided second half of each head's [q|gate] pair. */
         RAD_ISSUE_N(c, op_sig, T * g.n_head,
-                    bcol(w.qg, g.head_dim, g.head_dim, T), brows(w.gate, T));
-        RAD_ISSUE(c, op_mul, brows(w.attn.x, T), brows(w.gate, T), brows(w.attn.x, T));
-    } else if (!gated)
+                    bcol(w.qg, g.head_dim, g.head_dim, T), brows(gate, T));
+        RAD_ISSUE(c, op_mul, brows(w.attn.x, T), brows(gate, T), brows(w.attn.x, T));
+        q_gate.step(c, T);
+    } else {
         RAD_ISSUE_N(c, op_gq, T * g.n_head,
                     bcol(w.qg, g.head_dim, g.head_dim, T), brows(w.attn.x, T),
                     brows(w.attn.cq(), T), brows(w.attn.cs(), T), brows(w.attn.x, T));
+    }
 
     o.step(c, w.attn, w.h.x, T);
-    if (op_ar && !ar_taken(g, T, ar_out, ar_out_take))
+    if (own_ar && op_ar && !ar_taken(g, T, ar_out, ar_out_take))
         RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
     if (op_add) RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h.x, T), brows(w.x, T));
 }
diff --git a/arch/common/rad_block_dflash2.h b/arch/common/rad_block_dflash2.h
index 8f1738f0..6dd450d7 100644
--- a/arch/common/rad_block_dflash2.h
+++ b/arch/common/rad_block_dflash2.h
@@ -1,39 +1,32 @@
 /* rad_block_dflash2.h -- the DFlash2 block-diffusion drafter, bf16.
  *
- * ============================== WHAT IT IS ==============================
+ * A small transformer that proposes a whole block of tokens in one forward pass. Compared with
+ * the MTP head (rad_block_mtp_fp8.h):
  *
- * A SECOND, SMALLER TRANSFORMER that proposes a whole block of tokens in ONE forward pass. It is
- * the other drafter this engine serves, and it is a different shape of thing from the MTP head
- * beside it (rad_block_mtp_fp8.h):
+ *     MTP        depth d costs d chained forwards; round i+1 embeds round i's token.
+ *     DFlash2    depth d costs one forward over d+1 positions: the anchor token plus d mask
+ *                tokens are denoised together.
  *
- *     MTP        depth d costs d CHAINED forwards. Round i+1 cannot start until round i has
- *                produced a token, because the token is what it embeds.
- *     DFlash2    depth d costs ONE forward over d+1 positions. The block is denoised together --
- *                the anchor token plus d mask tokens go in, d+1 hidden states come out.
+ * So depth is nearly free here, and there is no `draft_pass`. Published acceptance is 4.10-5.46
+ * versus MTP's 3.74-5.02 at 7 drafts.
  *
- * That is why depth is nearly free here and expensive there, and it is why this file has no
- * `draft_pass`: there are no rounds. Published acceptance for this drafter is 4.10-5.46 against
- * MTP's 3.74-5.02 at 7 drafts.
- *
- * The price of proposing the positions together is that position l+1 was computed WITHOUT KNOWING
- * what position l would choose. The candidate selector is what puts that dependence back: each
- * position keeps the draft head's top K, a low-rank bilinear form scores the edge between
- * consecutive positions, and a greedy walk picks one path. `dflash_select` is that kernel.
+ * Since positions are proposed together, position l+1 does not know what position l chose. The
+ * candidate selector (`dflash_select`) restores that dependence: each position keeps the draft
+ * head's top K, a low-rank bilinear form scores edges between consecutive positions, and a greedy
+ * walk picks one path.
  *
  * ============================== THE TWO PASSES ==============================
  *
- * THE CONTEXT PASS, one row a committed token. The drafter never runs its layers over the context
- * -- it reads the TARGET's hidden states instead, at five intermediate layers, and turns them
- * straight into its own K and V:
+ * Context pass, one row per committed token. The drafter does not run its layers over the
+ * context; it turns the target's hidden states at five intermediate layers into its own K and V:
  *
  *     c  = fc(concat of the trunk's residual stream at layers 5, 19, 33, 47, 61)   [n_taps*n_embd]
  *     c  = hidden_norm(c)
  *     for each draft layer:  k|v = kv_proj(c);  k = k_norm(k) then rope;  kv_store(k, v)
  *
- * The trunk's side of that -- the taps, and the `dflash_src` buffer they land in -- is in
- * qwen35_fp8.cpp. This file reads the buffer and never asks where the rows came from.
+ * The taps and the `dflash_src` buffer they land in are the trunk's (qwen35_fp8.cpp).
  *
- * THE QUERY PASS, one row a draft position, `block` = 1 + n_spec of them a sequence:
+ * Query pass, one row per draft position, `block` = 1 + n_spec rows per sequence:
  *
  *     x = embed(anchor, mask, mask, ...)
  *     for each layer:
@@ -47,9 +40,8 @@
  *         h  = dflash_conv(h, coef[taps*NG:], ffn_conv_base[1]);   x += h
  *     x = norm(x)
  *
- * and then, over the MASK rows of each sequence's block -- offsets 1..block-1, NOT 0..steps-1.
- * The anchor at offset 0 is a token the target has already chosen, so its row predicts nothing and
- * is there to condition the rest; each mask row predicts the token AT ITS OWN POSITION:
+ * then, over the mask rows of each block (offsets 1..block-1; the anchor at offset 0 is already
+ * chosen and only conditions the rest), each predicting the token at its own position:
  *
  *     cand, unary = top_k(draft_head(x))          the candidates and their logits
  *     hp          = hidden_projection(x)          the selector's query, rank 256
@@ -57,61 +49,38 @@
  *
  * ============================== WHAT IS SHARED WITH THE TARGET ==============================
  *
- * The embedding table and the lm_head, both. The checkpoint ships neither -- 81 tensors, no
- * `embed_tokens` and no `lm_head` -- so a drafter without a target is not a model. `mask_token_id`
- * is an ordinary id in the target's vocabulary (248070 here), which is why there is no separate
- * mask embedding to load.
+ * The embedding table and lm_head. The checkpoint (81 tensors) ships neither, and
+ * `mask_token_id` is an ordinary id in the target's vocabulary (248070 here), so there is no
+ * separate mask embedding.
  *
- * The head reads the 2-BIT copy of the lm_head, exactly as the MTP head does and for exactly the
- * reason rad_block_mtp_fp8.h gives at op_dlogits: a draft is a proposal, the target verifies every
- * one of them with its own untouched head, and speculative decoding is distribution-preserving --
- * so a coarser draft costs acceptance and cannot change a token the model emits. Its candidates
- * are then rescored against the target's own head where that head is fp8 or int8 (op_drerank), so
- * the coarseness costs only which candidates are proposed, not how they are ranked. The 2-bit head
- * also buys something MTP does not need: the head stays a SINGLE-RANK computation, so the candidate ids are
- * global without an all-gather and the selector's codebooks can be indexed directly.
+ * The head reads the 2-bit copy of the lm_head, as the MTP head does (rad_block_mtp_fp8.h,
+ * op_dlogits): the target verifies every draft with its own head, so a coarser draft costs only
+ * acceptance, never an emitted token. Candidates are rescored against the target's head when it
+ * is fp8 or int8 (op_drerank), so coarseness affects only which candidates are proposed.
  *
- * ============================== THE NORMS ARE PLAIN ==============================
+ * ============================== PLAIN NORMS ==============================
  *
- * `w`, not `1 + w`, unlike every norm in the trunk this drafter is bolted to. vLLM says so by
- * using the ordinary RMSNorm rather than the family's GemmaRMSNorm, and the checkpoint agrees:
- * hidden_norm sits at 0.11..1.24 (mean 0.82), input_layernorm at 0.05..1.70, k_norm at 0.32..2.53
- * and the final norm at 2.45..5.25. All positive, all centred near one -- which is a plain gain
- * and is not what a `1 + w` tensor looks like. So `Geom::wadd` and `wadd_qk` are ZERO here while
- * the trunk's are one, and the two geometries are separate structs for this reason among others.
+ * The norms use `w`, not the trunk's `1 + w`: vLLM uses plain RMSNorm here, and the gains are all
+ * positive and centred near one (hidden_norm 0.11..1.24, input_layernorm 0.05..1.70, k_norm
+ * 0.32..2.53, final norm 2.45..5.25). So this geometry's `wadd` and `wadd_qk` are zero.
  *
  * ============================== SHARDING ==============================
  *
- * The layers shard the way any transformer's do: q/kv and gate_up by row, o and down by column
- * with an all-reduce. Ten collectives a draft pass, each 5120 * block * 2 bytes -- 80 KiB at the
- * shipped block of 8 -- which is below the lossy wire's floor and is served exactly.
+ * q/kv and gate_up shard by row, o and down by column with an all-reduce: ten collectives per
+ * draft pass, each 5120 * block * 2 bytes (80 KiB at block 8), below the lossy wire's floor.
  *
- * THREE THINGS ARE REPLICATED AND EACH IS A DECISION:
+ * Replicated:
  *
- *   fc              [n_embd, n_taps*n_embd], 262 MiB. It could be COLUMN-sharded, since its input
- *                   is the replicated residual stream and its output would then be a partial sum:
- *                   131 MiB a rank and half the read bytes on the context pass's widest GEMM. Not
- *                   done, because it puts an all-reduce on the PREFILL path to save a small
- *                   fraction of it, and the real fix for the context pass's cost is not to run it
- *                   over the whole prompt at all (see below).
- *   conv weights    the projection and the base kernel, 26 MiB a layer. The convolution is over
- *                   the whole replicated hidden row and every rank needs every coefficient; a row
- *                   shard would give each rank a fraction of the groups.
- *   the codebooks   [n_vocab, 256] each, 127 MiB each. They are gathered by GLOBAL token id and
- *                   the ids come out of a whole-vocabulary draft head, so a vocabulary shard would
- *                   let a rank score only the candidates that happened to land in its own slice.
- *                   The gather is 128 rows a pass, so the bytes READ are nothing; it is the
- *                   residency that costs.
+ *   fc              [n_embd, n_taps*n_embd], 262 MiB. Column-sharding would halve it but add an
+ *                   all-reduce to the prefill path.
+ *   conv weights    projection and base kernel, 26 MiB a layer. The convolution spans the whole
+ *                   replicated hidden row, so every rank needs every coefficient.
+ *   codebooks       [n_vocab, 256], 127 MiB each, gathered by global token id. Only 128 rows are
+ *                   read per pass; the cost is residency.
  *
- * ============================== THE CONTEXT PASS IS THE EXPENSIVE HALF ==============================
- *
- * In bytes: `fc` is 262 MiB and the five KV projections read 3.4 GB over a 2048-token prefill
- * chunk, which is a real fraction of what the chunk costs.
- *
- * THE FIX IS NOT A FASTER GEMM. The drafter's attention has a 2048-token window, so a context
- * position more than 2048 before the query is never read: for a prompt of any real length, all but
- * the last 2048 rows of the context pass are computed and thrown away. The scheduler can simply
- * not run it over them. That is scheduler work and it is noted here rather than done here.
+ * Cost: the context pass is the expensive half (`fc` plus five KV projections read 3.4 GB over a
+ * 2048-token prefill chunk). The attention window is 2048 tokens, so context rows further back
+ * are never read and the scheduler need not compute them.
  */
 #ifndef RAD_BLOCK_DFLASH2_H
 #define RAD_BLOCK_DFLASH2_H
@@ -122,9 +91,8 @@
 namespace rad {
 namespace arch {
 
-/* A row slice of a WEIGHT, the same thing brow_slice() is for a buffer. The conv's base kernel is
- * [2, taps, n_embd] and the two sides are the prepare tap set and the finish tap set; there is one
- * checkpoint tensor and the op takes one side at a time. */
+/* brow_slice() for a weight. The conv base kernel is one [2, taps, n_embd] tensor holding the
+ * prepare and finish tap sets; the op takes one side at a time. */
 inline RadOperand wrow_slice(rad_weight h, int64_t first, int64_t n, int64_t pitch) {
     RadOperand o = RAD_W(h);
     o.offset = first * pitch;
@@ -135,9 +103,7 @@ inline RadOperand wrow_slice(rad_weight h, int64_t first, int64_t n, int64_t pit
 struct Dflash2 {
     enum { MAX_LAYERS = 8 };
 
-    /* Everything the drafter's own config.json says that its geometry does not. Read by the
-     * plugin from `draft.*` metadata keys and handed in whole, so this file reads no environment
-     * and no container. */
+    /* The drafter config beyond its geometry, read by the plugin from `draft.*` metadata keys. */
     struct Config {
         int64_t n_taps   = 0;     /* how many trunk layers `fc` concatenates */
         int64_t block    = 0;     /* query rows a sequence: the anchor plus n_spec mask tokens */
@@ -149,8 +115,8 @@ struct Dflash2 {
         int     causal   = 0;
         int64_t steps() const { return block - 1; }
         int64_t ng(int64_t n_embd) const { return group ? n_embd / group : 0; }
-        /* The kernel projection emits [2, taps, NG] per token -- one coefficient set for `prepare`
-         * and one for `finish` -- and `dflash_conv` reads a slice of it at the FULL row pitch. */
+        /* The kernel projection emits [2, taps, NG] per token (prepare's set, then finish's);
+         * `dflash_conv` reads a slice of it at the full row pitch. */
         int64_t coef_dim(int64_t n_embd) const { return 2 * taps * ng(n_embd); }
     };
 
@@ -158,43 +124,33 @@ struct Dflash2 {
         /* the context pass */
         rad_buf src  = 0;   /* [max_tok, n_taps * n_embd]  the trunk's taps, read only */
         rad_buf c    = 0;   /* [max_tok, n_embd]           fc's output, then normed in place */
-        /* K AND V ARE TWO BUFFERS, not one [max_tok, 2*kv_dim] with K in its left half. Both
-         * halves are written by one projection and read by one kv_store, so fusing them is the
-         * obvious thing -- and it is wrong, because of the PER-HEAD NORM in between. `rmsnorm`
-         * takes one row pitch. K inside a fused row is `head_dim` apart within a token and
-         * `2*kv_dim` apart between tokens, and no single pitch is both; answering with the
-         * between-tokens stride normalises every eighth head against the wrong numbers. libr4d
-         * refuses that operand (libr4d/r4d_model.cpp, rows_pitch), and the drafter gives it rows
-         * that are what they claim to be. The trunk's attention block splits
-         * k and v for the same reason -- see rad_block_attn_gated.h. */
+        /* K and V are separate buffers because of the per-head k norm: `rmsnorm` takes one row
+         * pitch, and K heads inside a fused [K|V] row are head_dim apart within a token but
+         * 2*kv_dim apart between tokens. libr4d refuses such an operand (libr4d/r4d_model.cpp,
+         * rows_pitch). Same reason as in rad_block_attn_gated.h. */
         rad_buf ck   = 0;   /* [max_tok, kv_dim]           ONE layer's K, reused across layers */
         rad_buf cv   = 0;   /* [max_tok, kv_dim]           ONE layer's V, reused across layers */
         /* the query pass */
         rad_buf x    = 0;   /* [qrows, n_embd]  the drafter's residual stream */
         rad_buf h    = 0;   /* [qrows, n_embd]  normed input, o/down output, and the final norm */
-        rad_buf h2   = 0;   /* [qrows, n_embd]  the convolution's output -- it may not alias x */
+        rad_buf h2   = 0;   /* [qrows, n_embd]  the convolution's output; must not alias x */
         rad_buf coef = 0;   /* [qrows, coef_dim] */
         rad_buf q    = 0;   /* [qrows, q_dim] */
-        rad_buf k    = 0;   /* [qrows, kv_dim]  -- two buffers, and `ck` above says why */
+        rad_buf k    = 0;   /* [qrows, kv_dim]  separate from v, see `ck` */
         rad_buf v    = 0;   /* [qrows, kv_dim] */
         rad_buf attn = 0;   /* [qrows, q_dim] */
         rad_buf gate_up = 0;/* [qrows, 2 * n_ff] */
         rad_buf ffn  = 0;   /* [qrows, n_ff] */
-        /* THE FP8 TWINS OF THE FOUR ACTIVATIONS A LINEAR READS. `quant_act_fp8` writes them and
-         * the six `gemm_nt_q` linears read them; nothing else touches them, and the bf16 buffer
-         * beside each stays the thing the rest of the graph reads and writes.
-         *
-         * ONE PAIR PER ACTIVATION, NOT PER LINEAR. q and k|v both read h2, so quantising it once
-         * is the difference between two launches a layer and three -- the same argument rad_fp8.h
-         * makes for keeping QuantFP8 a separate struct from LinearFP8. h2 is quantised twice a
-         * layer all the same, because the convolution rewrites it between the attention half and
-         * the feed-forward half. */
+        /* FP8 codes and scales of the activations the linears read, written by `quant_act_fp8`
+         * and read only by the `gemm_nt_q` linears. One pair per activation, not per linear: q, k
+         * and v all read h2. h2 is still quantised twice a layer, because the convolution
+         * rewrites it between the attention and feed-forward halves. */
         rad_buf srcq = 0, srcs = 0;  /* [max_tok, n_taps*n_embd] e4m3 | [.., /128] f32 */
         rad_buf cq   = 0, cs   = 0;  /* [max_tok, n_embd] */
         rad_buf h2q  = 0, h2s  = 0;  /* [qrows,   n_embd] */
         rad_buf atq  = 0, ats  = 0;  /* [qrows,   q_dim] */
         rad_buf ffq  = 0, ffs  = 0;  /* [qrows,   n_ff] */
-        /* the head and the selector, at one row per DRAFT POSITION (block - 1 a sequence) */
+        /* the head and the selector, one row per draft position (block - 1 per sequence) */
         rad_buf sel_h = 0;  /* [srows, n_embd]     the gathered final hidden states */
         rad_buf hp    = 0;  /* [srows, sel_rank]   hidden_projection of them */
         rad_buf dq    = 0;  /* [srows, n_embd]  i8   the 2-bit head's quantised activation */
@@ -203,57 +159,45 @@ struct Dflash2 {
         rad_buf dlog  = 0;  /* [srows, head_rows(g)] bf16  the coarse logits */
         rad_buf cand  = 0;  /* [srows, sel_topk] i32  candidate token ids, global */
         rad_buf unary = 0;  /* [srows, sel_topk] f32  and their logits */
-        /* The vocab-parallel pair, declared only when head_sharded(g). Both are f32 (int32 id,
-         * float value) pairs: this rank's top-R, and the all-gathered world_size * R of them. */
+        /* Vocab-parallel pairs, declared only when head_sharded(g): (int32 id, f32 value) pairs
+         * stored as f32, this rank's top-R and the all-gathered world_size * R. */
         rad_buf dpair = 0;  /* [srows, sel_topk, 2]         f32 */
         rad_buf dgath = 0;  /* [srows, world * sel_topk, 2] f32 */
-        rad_buf tokens = 0; /* [max_seqs, steps] i32  THE DRAFT -- the engine reads this by name */
+        rad_buf tokens = 0; /* [max_seqs, steps] i32  the draft; the engine reads it by name */
     };
 
-    /* WHETHER THE 2-BIT DRAFT HEAD IS VOCAB-SHARDED. The test itself is rad_arch.h's
-     * `vocab_head_sharded` -- shared, because the second block-diffusion drafter in this library
-     * asks it too and both the op and the buffer under it have to agree. These two names stay so
-     * that whoever declares Dflash2's buffers can ask the BLOCK rather than re-derive the rule.
-     *
-     * Sharding halves the widest read on the draft path -- 341 MiB of codes and scales at 248320
-     * rows when it is replicated -- at the price of one all_gather of R pairs a row. At 248320
-     * over two ranks the shard is 124160, which is 7760 whole 16-row blocks. */
+    /* Whether the 2-bit draft head is vocab-sharded (rad_arch.h: vocab_head_sharded), so whoever
+     * declares the buffers can ask the block. Sharding halves the draft path's widest read (341 MiB
+     * of codes and scales at 248320 rows) for one all_gather of R pairs a row. */
     static bool    head_sharded(const Geom& g) { return vocab_head_sharded(g); }
-    /* Rows of the draft head, and therefore the width of `dlog`, on THIS rank. */
+    /* Rows of the draft head on this rank, and so the width of `dlog`. */
     static int64_t head_rows(const Geom& g)    { return vocab_head_rows(g); }
 
-    Geom    g{};      /* the DRAFTER's geometry, not the trunk's */
+    Geom    g{};      /* the drafter's geometry, not the trunk's */
     Config  cfg{};
     Wire    w{};
-    int     first_layer = 0;   /* absolute, so the KV group's layer_slot lookup finds these five */
+    int     first_layer = 0;   /* absolute, for the KV group's layer_slot lookup */
     int64_t qrows = 0, crows = 0, srows = 0;
     int64_t gated_rows = 0;    /* the band op_gug was declared over; 0 when there is no fold */
     rad_kvgroup kv = 0;
 
     /* model-scope weights.
      *
-     * THE SIX LINEARS ARE FP8 OR MXFP4 AND THE CHECKPOINT IS BF16. rad_fp8.h's DenseFP8 declares
-     * each as block fp8 or OCP-MXFP4, whichever the recipe made it -- and the reason is bytes: the
-     * drafter is read WHOLE on every decode step, which makes it one of the largest single items in
-     * the decode budget after the trunk's own GEMMs. On Qwen3.8-27B at depth 7, MXFP4 rounded to
-     * nearest accepts ~1% fewer tokens a step than fp8 and takes ~1.5 ms off a ~34 ms step.
-     * Nothing it computes can change an emitted token, because every draft is verified against the
-     * trunk exactly; the only thing quantising it can move is acceptance. */
+     * The linears are block fp8 or OCP-MXFP4 (rad_fp8.h: DenseFP8, per the recipe) although the
+     * checkpoint is bf16: the drafter is read whole every decode step. On Qwen3.8-27B at depth 7,
+     * MXFP4 accepts ~1% fewer tokens per step than fp8 and saves ~1.5 ms of a ~34 ms step.
+     * Quantisation can only change acceptance, since every draft is verified. */
     DenseFP8   w_fc{};
     rad_weight w_hnorm = 0, w_norm = 0;
     rad_weight w_selp = 0, w_pred = 0, w_succ = 0;
-    rad_weight w_tok = 0;                    /* the TARGET's embedding table */
-    rad_weight w_dh = 0, w_dhs = 0;          /* the 2-bit copy of the TARGET's lm_head */
+    rad_weight w_tok = 0;                    /* the target's embedding table */
+    rad_weight w_dh = 0, w_dhs = 0;          /* the 2-bit copy of the target's lm_head */
 
     /* per-layer weights */
     rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {};
-    /* K AND V ARE TWO WEIGHTS, and the fp8 layout hook is why. One fused [2*kv_dim, n_embd]
-     * tensor issued a half at a time through wrow_slice would cost a launch and no bytes -- and a
-     * block-scaled weight cannot be used that way. The layout of an operand is a function of the
-     * OP's N, and this op's N is kv_dim because it computes one half; the hook would be handed a
-     * [2*kv_dim/128][K/128] plane for a [kv_dim, K] op and refuse it. Two weights make the op's N
-     * and the planes' rows the same number again, shard independently at kv_dim, and issue the
-     * same two launches. */
+    /* K and V are separate weights: a block-scaled operand's layout follows the op's N, so a fused
+     * [2*kv_dim, n_embd] weight issued one half at a time would hand the layout hook a
+     * [2*kv_dim/128][K/128] plane for a [kv_dim, K] op, which it refuses. */
     DenseFP8   w_q[MAX_LAYERS]{},  w_k[MAX_LAYERS]{}, w_v[MAX_LAYERS]{}, w_o[MAX_LAYERS]{};
     rad_weight w_qn[MAX_LAYERS] = {}, w_kn[MAX_LAYERS] = {};
     DenseFP8   w_gu[MAX_LAYERS]{}, w_dn[MAX_LAYERS]{};
@@ -264,14 +208,14 @@ struct Dflash2 {
     rad_op op_cfc = 0, op_cnorm = 0, op_crope = 0, op_cstore = 0;
     rad_op op_ck[MAX_LAYERS] = {}, op_cv[MAX_LAYERS] = {}, op_cknorm[MAX_LAYERS] = {};
 
-    /* THE ACTIVATION QUANTISERS, one per activation that feeds a linear. Weightless and shape-only,
-     * so one declaration each serves every layer -- the per-layer ops above are per-layer only
-     * because a weight's prefetch interval comes from the op that declares it. */
-    rad_op op_qsrc = 0, op_qc = 0;                  /* the context pass's two */
-    rad_op op_qh2 = 0, op_qat = 0, op_qff = 0;      /* the query pass's three */
+    /* Activation quantisers, one per activation that feeds a linear. Weightless, so one declaration
+     * serves every layer; ops with weights are per layer because a weight's prefetch interval
+     * comes from the op that declares it. */
+    rad_op op_qsrc = 0, op_qc = 0;                  /* context pass */
+    rad_op op_qh2 = 0, op_qat = 0, op_qff = 0;      /* query pass */
 
-    /* query-pass ops. The weightless ones are declared once and issued per layer: an op's declared
-     * read and write sets are what the buffer planner reads, and they are the same every layer. */
+    /* query-pass ops. Weightless ones are declared once and issued per layer; their read and write
+     * sets are the same every layer. */
     rad_op op_embed = 0, op_embed_ar = 0;
     rad_op op_anorm[MAX_LAYERS] = {}, op_fnorm[MAX_LAYERS] = {};
     rad_op op_acoef[MAX_LAYERS] = {}, op_fcoef[MAX_LAYERS] = {};
@@ -288,11 +232,11 @@ struct Dflash2 {
     rad_op op_gather = 0, op_dquant = 0, op_dlogits = 0, op_dtopk = 0;
     rad_op op_dgather = 0, op_dmerge = 0;   /* the vocab-parallel pair; 0 when the head is whole */
     rad_op op_drerank = 0;                  /* the candidates rescored against the target's head */
-    /* THE TARGET'S lm_head, set by the plugin before declare when its plane is one logit_rerank
-     * reads (fp8 or int8 rows); 0 leaves the coarse head's own scores as the candidates'. */
+    /* The target's lm_head, set by the plugin before declare when logit_rerank can read it (fp8 or
+     * int8 rows); 0 keeps the coarse head's scores. */
     rad_weight w_lm = 0;
-    /* How many candidates the coarse head proposes for the rerank: logit_rerank's and row_topk's
-     * ceiling. Rescoring is exact, so a wider set can only find more of the exact top sel_topk. */
+    /* Candidates the coarse head proposes for the rerank (logit_rerank's and row_topk's ceiling).
+     * Rescoring is exact, so a wider set can only find more of the exact top sel_topk. */
     static constexpr int64_t kRerankR = 32;
     int64_t    top_w = 0;                   /* the coarse top-K's width: kRerankR or sel_topk */
     rad_op op_hp = 0, op_sel = 0;
@@ -300,10 +244,10 @@ struct Dflash2 {
     int  declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer,
                  rad_kvgroup group, rad_weight tok_embd, const char* ck_prefix,
                  const char* ck_lm, const Wire& wire);
-    /* The context pass, one row a committed token. `batch` carries those rows and the draft KV
-     * group's slot mapping; nothing about the query block is read. */
+    /* The context pass, one row per committed token; `batch` carries those rows and the draft KV
+     * group's slot mapping. */
     void context(RadCtx* c, const RadBatch* batch) const;
-    /* The query pass and the selector, one call, `block` rows a sequence. */
+    /* The query pass and the selector, `block` rows per sequence. */
     void step(RadCtx* c, const RadBatch* batch) const;
 
 private:
@@ -360,26 +304,15 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
     w_succ  = decl_w(b, nm.f("dflash.sel_succ"), RAD_BF16, {g.n_vocab_all, cfg.sel_rank},
                      RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
 
-    /* THE 2-BIT DRAFT HEAD. The same declaration the MTP head makes, for the same reasons, argued
-     * at length in rad_block_mtp_fp8.h: `dflash.draft_head.weight` is the target's lm_head under a
-     * name of its own, which the recipe quantises to the 2-bit grid (u2 codes, an f16 scale and a
-     * u8 zero a group of 128) -- one checkpoint tensor, two logical weights. The GEMM takes the
-     * codes as one operand and the scale and zero planes, interleaved by its relayout, as the
-     * other.
+    /* The 2-bit draft head, declared as the MTP head's is (rad_block_mtp_fp8.h):
+     * `dflash.draft_head.weight` is the target's lm_head under its own name, quantised by the
+     * recipe to u2 codes with an f16 scale and u8 zero per group of 128. One checkpoint tensor,
+     * two views: codes, and the scale|zero planes the GEMM's relayout interleaves.
      *
-     * IT IS SHARDED, AND THE MERGE IS WHAT MAKES THAT SAFE. The draft path never goes through the
-     * sampler, so its argmax is a `row_topk` over one rank's plane -- and a sharded plane on its
-     * own would let each rank propose only from its own half, while the selector's codebooks are
-     * gathered by GLOBAL token id and would then see only the candidates that landed locally. The
-     * merge runs BEFORE the selector: each rank's top-R comes back as global ids, an all_gather
-     * moves R pairs a row, and `row_topk_merge` reduces them to the same global top-R an unsharded
-     * head would have found -- exactly, ties included (docs/OPS.md). Both ranks then hold the same
-     * candidate set and the codebooks are replicated, so everything downstream is unchanged.
-     *
-     * What it buys is the widest read on the draft path halved -- 341 MiB of codes and scales at
-     * the whole vocabulary -- and that much device memory given back per rank. What it costs is
-     * one all_gather of `world * R` pairs a row, which at R = 16 is 2 KiB: the link's latency and
-     * essentially no bytes. */
+     * When sharded, each rank's `row_topk` reports global ids, an all_gather moves R pairs a row,
+     * and `row_topk_merge` reduces them to exactly the unsharded global top-R, ties included
+     * (docs/OPS.md). This runs before the selector, so every rank holds the same candidates for
+     * the replicated codebooks. The all_gather is `world * R` pairs a row (2 KiB at R = 16). */
     enum { DF_W2_GROUP = 128 };
     const bool dh_shard = head_sharded(g);
     const int  dh_split = dh_shard ? RAD_SHARD_ROW : RAD_SHARD_NONE;
@@ -418,12 +351,8 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
         RAD_ARCH_TRY(w_q[i].declare(b, nm, nm.f("dflash.blk.%d.attn_q", i), qd, g.n_embd,
                                     RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(first_layer + i),
                                     { nm.ckpt("%s.layers.%d.self_attn.q_proj.weight", ck, i) }));
-        /* K, V AND Q ARE THREE WEIGHTS, which is not the fusion every other attention block in
-         * this library makes. Q is separate because of the context pass: it needs k and v over the
-         * trunk's projected hidden state and has no use for q at all, so a fused qkv would make it
-         * compute and discard a q_dim-wide GEMM per layer per context token. K and V are separate
-         * because a block-scaled weight's layout follows its op's N, and both passes take one of
-         * them at a time -- see the note beside the declarations. */
+        /* q, k and v are separate weights. The context pass needs only k and v, so a fused qkv
+         * would compute and discard q for every context token. k and v: see w_q's declaration. */
         RAD_ARCH_TRY(w_k[i].declare(b, nm, nm.f("dflash.blk.%d.attn_k", i), kvd, g.n_embd,
                                     RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(first_layer + i),
                                     { nm.ckpt("%s.layers.%d.self_attn.k_proj.weight", ck, i) }));
@@ -461,16 +390,12 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
 
     }
 
-    /* NON-CAUSAL, WINDOWED. The block is denoised as a whole, so every query row sees every other
-     * row of its own block as well as the context -- `causal` 0 is the drafter's own config
-     * (`is_causal: false`) and not a default. The window is the checkpoint's `sliding_window`, and
-     * it is the reason the context pass has a bounded amount of real work in it.
+    /* Non-causal and windowed: the block is denoised as a whole, so each query row sees its whole
+     * block plus the context (`causal` comes from the config's `is_causal: false`). The window is
+     * the checkpoint's `sliding_window`.
      *
-     * DECLARED FIRST, before either kv_store, even though it runs long after both. `block_size` is
-     * RAD_DERIVED -- the KV block is a property of the resolved attention kernel and not a number
-     * anyone gets to choose -- so it is omitted here and READ BACK with rad_kv_block_size() for the
-     * two stores, which need it as a parameter. Ask before the attention op is declared and the
-     * answer is zero. */
+     * Declared before both kv_stores, which read the resolved `block_size` back with
+     * rad_kv_block_size(); before this declaration it returns zero. */
     op_attn = rw(b, RAD_OP(b, "attn_paged",
                     RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim),
                                RAD_INT("gqa", g.gqa()), RAD_INT("causal", cfg.causal),
@@ -482,37 +407,28 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
                 {w.q}, {w.attn});
 
     /* ---------------------------------------------------------------- the context pass */
-    /* EVERY LINEAR HERE IS `fp8a8` -- or `mxfp4a8` where the recipe made the drafter 4-bit; DenseFP8
-     * reads which off the container and declares the GEMM (`gemm()`), and either one reads the
-     * same E4M3 pair -- and every activation that feeds one gets a `quant_act_fp8` in
-     * front of it. The fp8 weights are E4M3 with a 128x128 scale plane (rad_fp8.h's DenseFP8 says
-     * why), and there is no `fp8a16` band anywhere in this block: that kernel is M <= 1, and
-     * neither pass here ever runs at one row -- a context pass is a committed chunk and a query
-     * pass is `block` rows by construction.
+    /* Every linear is `fp8a8` (or `mxfp4a8` for a 4-bit recipe; DenseFP8 reads which from the
+     * container and declares the GEMM), reading an E4M3 activation pair from a `quant_act_fp8`.
+     * There is no `fp8a16` band: that kernel is M <= 1, and neither pass runs at one row.
      *
-     * AND NOTHING HERE IS ROW-SLICED. The fp8a8 pair covers every M (narrow to 16, tiled above),
-     * so a context pass over a 2048-token prefill chunk is one launch a layer rather than one per
-     * 64 rows.
-     *
-     * The convolutions' coefficient projections and the selector's hidden projection are still
-     * bf16, and they are not sliced either: libr4d's bf16 GEMM row is C_LE("M", 65536), and all
-     * three of these carry K = n_embd, a multiple of 16, so the wide row serves them whole. */
+     * Nothing is row-sliced: the fp8a8 pair covers every M, and libr4d's bf16 GEMM row (used by
+     * the conv coefficient projections and the selector's hidden projection, K = n_embd) is
+     * C_LE("M", 65536). */
     op_qsrc = rw(b, RAD_OP(b, "quant_act_fp8",
                     RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", cfg.n_taps * g.n_embd),
                                RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
                     RAD_NOWEIGHTS),
                 {w.src}, {w.srcq, w.srcs});
     op_cfc = w_fc.gemm(b, crows, g.n_embd, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.c});
-    /* IN PLACE. Safe for any implementation that computes a row's scale before writing the row,
-     * which none can avoid doing; the per-head q/k norms below run in place for the same reason. */
+    /* In place, like the per-head q/k norms below: a row's scale is computed before the row is
+     * written. */
     op_cnorm = rw(b, RAD_OP(b, "rmsnorm",
                      RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
                                 RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
                                 RAD_STR("dtype", g.dtype)),
                      RAD_WEIGHTS(w_hnorm)),
                  {w.c}, {w.c});
-    /* ONE QUANTISE FOR ALL FIVE LAYERS. `c` is the normed projection of the trunk's taps and every
-     * layer's k|v reads that same buffer, so this is one launch a context pass and not five. */
+    /* One quantise for all layers: every layer's k and v read the same `c`. */
     op_qc = rw(b, RAD_OP(b, "quant_act_fp8",
                   RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
                              RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
@@ -520,9 +436,8 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
               {w.c}, {w.cq, w.cs});
     for (int64_t l = 0; l < g.n_layer; ++l) {
         const int i = (int)l;
-        /* TWO OPS OF THE SAME SHAPE, one per weight. An op's declared weight list is what gives a
-         * weight its prefetch interval and its residency class, so two weights want two ops even
-         * where one would issue both. */
+        /* One op per weight: an op's declared weight list gives each weight its prefetch interval
+         * and residency class. */
         op_ck[i] = w_k[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.ck});
         op_cv[i] = w_v[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.cv});
         op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm",
@@ -532,17 +447,18 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
                              RAD_WEIGHTS(w_kn[i])),
                          {w.ck}, {w.ck});
     }
-    /* K-ONLY ROPE. `rope` rotates the first n_head + n_head_kv heads of its operand and leaves the
-     * V heads that follow alone, so a K-only tensor is described by n_head = n_head_kv and
-     * n_head_kv = 0: all the heads there are rotate, none follow them. Weightless, so one op
-     * serves every layer. */
-    op_crope = rw(b, decl_rotary(b, g, "rope",
-                     RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
-                                RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
-                                RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
-                                RAD_STR("mode", "neox")),
-                     RAD_NOWEIGHTS),
-                 {w.ck}, {w.ck});
+    /* A whole-head NeoX rope over a q-only or k-only tensor of `heads` heads: `rope` rotates the
+     * first n_head + n_head_kv heads, so n_head_kv is 0. Weightless, so one op serves every layer. */
+    auto rope = [&](int64_t rows, int64_t heads, rad_buf x) {
+        return rw(b, decl_rotary(b, g, "rope",
+                         RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", g.head_dim),
+                                    RAD_INT("n_head", heads), RAD_INT("n_head_kv", 0),
+                                    RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
+                                    RAD_STR("mode", "neox")),
+                         RAD_NOWEIGHTS),
+                  {x}, {x});
+    };
+    op_crope = rope(crows, g.n_head_kv, w.ck);
     op_cstore = rw(b, RAD_OP(b, "kv_store",
                       RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
                                  RAD_INT("n_head_kv", g.n_head_kv),
@@ -558,9 +474,8 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
                                 RAD_INT("vocab_offset", g.vocab_off)),
                      RAD_WEIGHTS(w_tok)),
                  {}, {w.x});
-    /* The trunk's embedding is vocab-sharded, so this gather is partial and takes the same exact
-     * reduction. It is on the DRAFT path, which runs once a step ahead of the trunk: a second
-     * small collective. */
+    /* The trunk's embedding is vocab-sharded, so the lookup is partial and needs an exact
+     * all-reduce. */
     if (g.world > 1)
         op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
                             RAD_PARAMS(RAD_INT("world_size", g.world),
@@ -568,10 +483,8 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
                                        RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
                             RAD_NOWEIGHTS),
                         {w.x}, {w.x});
-    /* The query pass's three quantisers, declared once and issued per layer -- weightless ops with
-     * the same shape every layer, exactly like the ropes and the residual add below. h2 is
-     * quantised TWICE a layer because the convolution rewrites it between the two halves; attn and
-     * ffn once each. */
+    /* The query pass's quantisers, issued per layer: h2 twice (the convolution rewrites it between
+     * the halves), attn and ffn once each. */
     op_qh2 = rw(b, RAD_OP(b, "quant_act_fp8",
                    RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
                               RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
@@ -629,40 +542,19 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
                             RAD_WEIGHTS(w_fcp[i])),
                         {w.h}, {w.coef});
         op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.h2q, w.h2s}, {w.gate_up});
-        /* THE SAME FOLD THE TRUNK'S MLP HAS, over the same weights and into the same activation;
-         * rad_block_mlp_fp8.h declares it beside the pair for the same reason. Unfused, a layer
-         * runs gate_up -> silu_mul -> quant, which is two extra launches and two extra passes over
-         * the [T, n_ff] product. The gated kernel is also the faster of the two on the SAME shape,
-         * because the fold saves the bf16 round trip.
-         *
-         * NOT RAD_ARCH_TRY: a kernel set without the row is the ordinary case and the pair below
-         * still runs. `gated_rows` is the band it was declared over and the issue site checks it,
-         * because M > 64 is a refusal in the kernel and not a slower path. */
-        {
-            const int64_t hi = qrows < 64 ? qrows : 64;
-            if (hi > 0 && !w_gu[i].mx) {   /* the fold is an fp8a8 tile; an MXFP4 gate_up takes the pair */
-                op_gug[i] = rw(b, RAD_OP(b, "gemm_nt_q_gated",
-                                   RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", 2 * g.n_ff),
-                                              RAD_INT("K", g.n_embd),
-                                              RAD_INT("group", RAD_FP8_BLOCK),
-                                              RAD_STR("dtype", "fp8a8"), RAD_STR("act", "silu")),
-                                   RAD_WEIGHTS(w_gu[i].w, w_gu[i].s)),
-                               {w.h2q, w.h2s}, {w.ffq, w.ffs});
-                if (op_gug[i]) gated_rows = hi;
-            }
-        }
+        /* The fold saves two launches and the bf16 round trip of the [T, n_ff] product; it is an
+         * fp8a8 tile, so an MXFP4 gate_up takes the pair. */
+        if (!w_gu[i].mx)
+            op_gug[i] = decl_gated_fold(b, qrows, 2 * g.n_ff, g.n_embd, w_gu[i].w, w_gu[i].s,
+                                        {w.h2q, w.h2s}, {w.ffq, w.ffs}, &gated_rows);
         op_dn[i] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffq, w.ffs}, {w.h});
     }
 
-    /* The convolutions. `block_size` is the QUERY BLOCK -- the mask that kills the shifted tap at
-     * the first row of each block is what keeps one sequence's block from convolving with the
-     * previous sequence's, so it is the batch's per-sequence row count and not a tuning number.
+    /* The convolutions. `block_size` is the query block: the shifted tap is masked at each block's
+     * first row so one sequence's block does not convolve with the previous one's.
      *
-     * ONE OP PER (LAYER, CONVOLUTION) even though every one of them is the same shape, because the
-     * base kernel is a WEIGHT and an op's declared weight list is what gives a weight its prefetch
-     * interval and its residency class. A single shared declaration would leave ten weights that
-     * no op admits to using. Each is issued twice -- `prepare` and `finish` -- against the two
-     * halves of one [2, taps, n_embd] tensor. */
+     * One op per (layer, convolution) because the base kernel is a weight (see op_ck). Each op is
+     * issued twice, prepare and finish, against the two halves of its [2, taps, n_embd] tensor. */
     for (int64_t l = 0; l < g.n_layer; ++l) {
         const int i = (int)l;
         op_aconv[i] = rw(b, RAD_OP(b, "dflash_conv",
@@ -680,20 +572,14 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
                             RAD_WEIGHTS(w_fcb[i])),
                         {w.h, w.coef}, {w.h2});
     }
-    op_qrope = rw(b, decl_rotary(b, g, "rope",
-                     RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
-                                RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", 0),
-                                RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
-                                RAD_STR("mode", "neox")),
-                     RAD_NOWEIGHTS),
-                 {w.q}, {w.q});
-    op_krope = rw(b, decl_rotary(b, g, "rope",
-                     RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
-                                RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
-                                RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
-                                RAD_STR("mode", "neox")),
-                     RAD_NOWEIGHTS),
-                 {w.k}, {w.k});
+    /* The attention output is written and read inside every layer, between the two halves of the
+     * attention convolution, but its two ops (op_attn, op_qat) are declared once ahead of the
+     * layers. Planned from those alone, its range would end before the coefficients' begins and
+     * the plan could lay one over the other. Read by the last convolution as well, it is live
+     * wherever the coefficients are. */
+    if (rad_op_reads(b, op_fconv[g.n_layer - 1], &w.attn, 1) < 0) return RAD_E_INVAL;
+    op_qrope = rope(qrows, g.n_head, w.q);
+    op_krope = rope(qrows, g.n_head_kv, w.k);
     op_store = rw(b, RAD_OP(b, "kv_store",
                      RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
                                 RAD_INT("n_head_kv", g.n_head_kv),
@@ -728,15 +614,12 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
 
     /* ---------------------------------------------------------------- the head and the selector
      *
-     * THE MASK ROWS, offsets 1..block-1 of each sequence's block. Offset 0 is the ANCHOR -- the
-     * token the target has already chosen -- and its row predicts nothing: it is there so the mask
-     * rows have something to attend to. Each mask row predicts the token at ITS OWN position, so
-     * the head runs over `steps` rows a sequence and not `block`. Getting this off by one is the
-     * kind of mistake that costs nothing visible: the drafts are simply wrong, acceptance
-     * collapses, and the model's own output stays exactly correct.
+     * The head runs over the mask rows, offsets 1..block-1 of each block: `steps` rows per
+     * sequence, each predicting the token at its own position. The anchor row predicts nothing.
+     * An off-by-one here only shows as collapsed acceptance; the output stays correct.
      *
-     * The gather is what makes those rows contiguous, and it is also what fixes the head's row
-     * numbering at s * steps + l -- which is the numbering `dflash_select` reads. */
+     * The gather makes those rows contiguous, numbered s * steps + l as `dflash_select` reads
+     * them. */
     op_gather = rw(b, RAD_OP(b, "gather_rows",
                       RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
                                  RAD_STR("dtype", g.dtype)),
@@ -753,10 +636,9 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
                                   RAD_STR("dtype", "w2a8")),
                        RAD_WEIGHTS(w_dh, w_dhs)),
                    {w.dq, w.ds, w.dsum}, {w.dlog});
-    /* Sharded, the top-R runs over THIS RANK'S plane and reports global ids, and it also writes
-     * the pair plane the gather moves. `vocab_off` is omitted entirely when the head is
-     * replicated, so that graph is the one it always was -- an optional parameter present with
-     * the value 0 is not the same declaration as an absent one. */
+    /* Sharded, the top-R runs over this rank's plane, reports global ids and also writes the pair
+     * plane the gather moves. Replicated, `vocab_off` is omitted: an optional parameter present
+     * with value 0 is a different declaration from an absent one. */
     const bool rerank = w_lm && (dh_shard || g.world <= 1);   /* see op_drerank below */
     if (!rerank) top_w = cfg.sel_topk;
     op_dtopk = dh_shard
@@ -771,17 +653,14 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
                            RAD_INT("R", top_w), RAD_STR("dtype", g.dtype)),
                 RAD_NOWEIGHTS),
              {w.dlog}, {w.cand, w.unary});
-    /* THE CANDIDATES ARE RESCORED EXACTLY when the target's head can be read row by row. The
-     * coarse head proposes its top kRerankR, `logit_rerank` scores those against the target's own
-     * fp8 head and re-sorts them, and the selector reads the best sel_topk of that order -- the
-     * candidate set and the unary logits the drafter was trained against, at kRerankR rows of the
-     * weight a draft row instead of a second, finer copy of the head. On Qwen3.8-27B the 2-bit
-     * head's own top-1 matches the exact head's on 76% of draft rows and the rescored one on all of
-     * them; served at depth 7 that is the 4-bit head's speed at half its bytes (330 MiB).
+    /* Exact rescoring when the target's head can be read row by row: the coarse head proposes its
+     * top kRerankR, `logit_rerank` scores them against the target's head and re-sorts, and the
+     * selector reads the best sel_topk, giving the candidates and unary logits the drafter was
+     * trained against. On Qwen3.8-27B the 2-bit head's top-1 matches the exact head on 76% of
+     * draft rows, the rescored one on all; this matches the 4-bit head's speed at half its bytes.
      *
-     * Sharded, each rank rescores only ids it owns (row_topk reports this rank's slice), and the
-     * gather and merge below then rank exact values. A replicated draft head above one rank
-     * proposes ids another rank owns, so it keeps its own scores. */
+     * Sharded, each rank rescores only ids it owns and the merge below ranks exact values. A
+     * replicated head above one rank proposes ids other ranks own, so it keeps its own scores. */
     if (rerank) {
         op_drerank = RAD_OP(b, "logit_rerank",
                         RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("R", top_w),
@@ -795,9 +674,8 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
         rad_op_writes(b, op_drerank, wr, dh_shard ? 3 : 2);
     }
     if (dh_shard) {
-        /* ROW-INTERLEAVED, so one draft position's pairs from every rank land side by side --
-         * `row_topk_merge` reads one row at one row stride, the same reason the sampler's own
-         * candidate gather carries `row`. */
+        /* Row-interleaved, so one draft position's pairs from every rank are adjacent, as
+         * `row_topk_merge` reads them. */
         op_dgather = rw(b, RAD_OP(b, "all_gather",
                            RAD_PARAMS(RAD_INT("world_size", g.world),
                                       RAD_INT("numel", srows * top_w * 2),
@@ -817,8 +695,8 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
                              RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
                   RAD_WEIGHTS(w_selp)),
               {w.sel_h}, {w.hp});
-    /* `anchor_stride` is `block`, because the operand is the step's own token_ids: a draft pass
-     * carries `block` ids a sequence and the anchor is the first of them. */
+    /* `anchor_stride` is `block`: the operand is the step's token_ids, `block` per sequence with
+     * the anchor first. */
     op_sel = rw(b, RAD_OP(b, "dflash_select",
                    RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", cfg.steps()),
                               RAD_INT("top_k", cfg.sel_topk), RAD_INT("rank", cfg.sel_rank),
@@ -838,10 +716,7 @@ inline void Dflash2::context(RadCtx* c, const RadBatch* batch) const {
     const RadKVGroupBatch* kvb = kv_batch(batch, kv);
     const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
 
-
-    /* NOT SLICED. A context pass is one row a committed token, so it is as wide as the prefill
-     * chunk; the fp8a8 pair covers every M, so each op here is one launch and not one per 64
-     * rows. */
+    /* As wide as the prefill chunk, one launch per op (the fp8a8 pair covers every M). */
     RAD_ISSUE_N(c, op_qsrc, T, brows(w.src, T), brows(w.srcq, T), brows(w.srcs, T));
     RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s),
                 brows(w.c, T), RAD_NONE, w_fc.bref());
@@ -872,7 +747,6 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
     const int32_t* table = kvb ? kvb->block_table  : nullptr;
     const int32_t* used  = kvb ? kvb->seqused      : nullptr;
 
-
     const int64_t NG = cfg.ng(g.n_embd);
     const int64_t half = cfg.taps * NG;      /* prepare's coefficients, then finish's */
 
@@ -913,10 +787,9 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
         RAD_ISSUE_N(c, op_qat, T, brows(w.attn, T), brows(w.atq, T), brows(w.ats, T));
         RAD_ISSUE_N(c, op_op[i], T, brows(w.atq, T), brows(w.ats, T),
                     RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h, T), RAD_NONE, w_o[i].bref());
-        /* BEFORE the closing convolution, not after. The convolution is linear in its input and
-         * its coefficients come from the replicated pre-attention norm, so either order is the
-         * same arithmetic -- and reducing first keeps the residual stream's contract ("what the
-         * ranks add to x has already been agreed") in one place. */
+        /* Reduce before the closing convolution. It is linear with coefficients from the
+         * replicated norm, so either order gives the same result; reducing first keeps x's
+         * update agreed across ranks. */
         if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
         RAD_ISSUE_N(c, op_aconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T),
                     wrow_slice(w_acb[i], 1, 1, cfg.taps * g.n_embd), brows(w.h2, T));
@@ -948,27 +821,20 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
 
     RAD_ISSUE_N(c, op_final, T, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
 
-    /* The rows that predict something: `steps` of every sequence's `block`. The scheduler names
-     * them through out_ids, the same field the trunk's own logits gather reads. */
+    /* The predicting rows, `steps` per sequence, named by the scheduler through out_ids. */
     const int64_t S = batch->n_out;
     if (S <= 0) return;
     RAD_ISSUE_N(c, op_gather, S, RAD_B(w.h), praw(batch->out_ids, RAD_I32, S), brows(w.sel_h, S));
 
-    /* `dsum` is quant_act_i8's GROUP-major plane, [n_embd/group][ceil(M/16)*16], so it is passed
-     * whole: there is no row slice of it that means anything. */
+    /* `dsum` is group-major, [n_embd/group][ceil(M/16)*16], so it has no row slice; pass it
+     * whole. */
     RAD_ISSUE_N(c, op_dquant, S, brows(w.sel_h, S), brows(w.dq, S), brows(w.ds, S), RAD_B(w.dsum));
-    /* The trailing operand is mxfp4's optional reference and is absent here; an absent optional
-     * operand is a null tensor in a full-length list, not a shorter list. */
+    /* The trailing operand is mxfp4's optional reference, absent here. Operands are positional,
+     * so an absent optional one is RAD_NONE, not a shorter list. */
     RAD_ISSUE_N(c, op_dlogits, S, brows(w.dq, S), brows(w.ds, S), RAD_W(w_dh), RAD_W(w_dhs),
                 brows(w.dlog, S), RAD_B(w.dsum), RAD_NONE);
-    /* RAD_NONE is the `pairs` slot: operands are POSITIONAL, so an optional one that the graph
-     * does not use is still passed, absent. Omitting it is a miscount and the engine refuses the
-     * op rather than guessing which of the four was left out.
-     *
-     * SHARDED, the top-R over this rank's plane is not the answer -- it is this rank's CANDIDATES,
-     * and `cand`/`unary` are overwritten by the merge two ops below. Writing them here anyway
-     * costs nothing (they are the same R entries the pairs plane holds) and keeps one issue site
-     * for both paths. */
+    /* RAD_NONE fills the unused `pairs` slot. Sharded, this rank's top-R are only candidates and
+     * the merge overwrites `cand`/`unary`. */
     if (op_dmerge) {
         RAD_ISSUE_N(c, op_dtopk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S),
                     brows(w.dpair, S));
diff --git a/arch/common/rad_block_dspark.h b/arch/common/rad_block_dspark.h
index 4528da76..d049b6e1 100644
--- a/arch/common/rad_block_dspark.h
+++ b/arch/common/rad_block_dspark.h
@@ -2,161 +2,116 @@
  *
  * ============================== WHAT IT IS ==============================
  *
- * The THIRD drafter this engine serves, and the second block-diffusion one. It is
  * `openbmb/MiniCPM5-2B-DSpark`: five plain Qwen3 attention layers that propose a whole block of
- * tokens in ONE forward pass, conditioned on the target trunk's residual stream at five
+ * tokens in one forward pass, conditioned on the target trunk's residual stream at five
  * intermediate layers. Published acceptance length 5.52 at T = 0 (math 6.05 / code 6.11 /
- * general 4.16) against MTP's 3.74-5.02.
+ * general 4.16) versus MTP's 3.74-5.02.
  *
- * IT IS NOT rad_block_dflash2.h, and the name is the trap. DSpark subclasses SpecForge's
- * `DFlashDraftModel`, which is PLAIN QWEN3 ATTENTION LAYERS; this library's `Dflash2` is the
- * conv-based drafter (`dflash_conv`, `attn_conv_base`, `sel_rank`/`sel_topk`) from a different
- * checkpoint of the same family. Same lineage, same word in the name, different architecture --
- * and the checkpoint settles it: 5 layers of q/k/v/o + q_norm/k_norm + gate/up/down and not one
- * conv or selection tensor. What IS taken from that file is its shape (Config / Wire / declare /
- * context / step), its two rules, and -- see THE MARKOV HEAD below -- its selector.
+ * Not rad_block_dflash2.h despite the name: DSpark subclasses SpecForge's `DFlashDraftModel`,
+ * which is plain Qwen3 attention (the checkpoint has q/k/v/o, q_norm/k_norm, gate/up/down and no
+ * conv or selection tensors), while `Dflash2` is the conv-based drafter. This block reuses
+ * Dflash2's structure (Config / Wire / declare / context / step) and its selector.
  *
- * ============================== THE FORWARD PASS, PINNED ==============================
+ * ============================== THE FORWARD PASS ==============================
  *
- * The reference is NOT in the published repo: `config.json` says `auto_map: dspark.DSparkDraftModel`
- * and the repo holds only config / README / safetensors. `RadixArk/Qwen3.8-27B-DSpark` ships
- * `dspark.py` and `dflash.py`, and that pair is the spec this block implements. The composition is
- * not recoverable from the tensor list alone, so it is written out here:
+ * The published repo has no reference code (`auto_map: dspark.DSparkDraftModel`);
+ * `RadixArk/Qwen3.8-27B-DSpark` ships `dspark.py` and `dflash.py`, which this implements:
  *
  *     target_hidden = hidden_norm(fc(concat of the trunk's residual stream after layers
  *                                    1, 10, 20, 30, 39))          [n_taps * n_embd] -> [n_embd]
  *     h = target.embed_tokens([anchor, MASK, MASK, ...])            `block` noise rows
  *     per layer (x5):
  *         h_n = input_layernorm(h)
- *         q   = q_norm(q_proj(h_n))                                 Q FROM THE NOISE ROWS ONLY
+ *         q   = q_norm(q_proj(h_n))                                 q from the noise rows only
  *         k   = k_norm(concat(k_proj(target_hidden), k_proj(h_n)))  context first, then noise
  *         v   =        concat(v_proj(target_hidden), v_proj(h_n))
- *         rope(q, k);  attention is NON-CAUSAL, mask None at inference
+ *         rope(q, k);  attention is non-causal, mask None at inference
  *         h  += o_proj(attn);  h += mlp(post_attention_layernorm(h))
  *     logits = target.lm_head(norm(h)) + markov_w2 @ markov_w1[prev_token]
  *
- * `fc` THEN `hidden_norm`, in that order, and `target_hidden` is computed ONCE and fed to EVERY
- * layer, which projects it with its OWN k_proj and v_proj. The drafter ships no embedding table
- * and no lm_head; it reads the target's, which is why a vocabulary that disagrees is not a drafter
- * for this target at all.
+ * `fc` then `hidden_norm`; `target_hidden` is computed once and each layer projects it with its
+ * own k_proj and v_proj. The drafter uses the target's embedding table and lm_head, so the
+ * vocabularies must agree.
  *
- * ============================== THE DUAL-SOURCE K/V IS AN ORDINARY KV CACHE ==============================
+ * ============================== DUAL-SOURCE K/V AS A PAGED CACHE ==============================
  *
- * `concat(proj(target_hidden), proj(noise))` needs no new kernel and no fused-operand games. The
- * reference's own cache says why: `past_key_values.update` appends the context rows and the noise
- * rows, the block attends over the whole thing, and then `crop(start)` throws the noise away. That
- * is a paged KV group with the context written per COMMITTED TOKEN and the noise rows written into
- * slots past `seqused` -- which the next context pass overwrites, so the crop is free.
+ * The reference appends context and noise rows to its cache, attends over both, then
+ * `crop(start)`s the noise. Here that is a paged KV group: context written per committed token,
+ * noise rows written past `seqused`, where the next context pass overwrites them. Two passes, as
+ * in Dflash2:
  *
- * So the split is the same two passes Dflash2 has, for the same reason:
+ *   Context pass, one row per committed token: the five k/v projections over the projected trunk
+ *   taps, stored. The drafter's layers never run over the context.
  *
- *   THE CONTEXT PASS, one row a committed token. It runs the five k/v projections over the
- *   projected trunk taps and stores them. The drafter's own layers never run over the context.
+ *   Query pass, `block` rows per sequence, through the five layers, attending to the context and
+ *   to each other.
  *
- *   THE QUERY PASS, `block` rows a sequence, over the drafter's five layers, attending to the
- *   context rows AND to each other.
+ * `k_norm` is per head over head_dim, so norming the two halves separately is bit-identical to
+ * norming the concatenation. `attn_paged` with `causal = 0` serves the non-causal block. The
+ * shape (16 heads, 2 KV heads, head_dim 128, GQA 8) matches the target, so the trunk's attention
+ * and norm/rope rows serve it.
  *
- * AND THE PER-HEAD NORM OVER THE CONCAT IS THE SAME NUMBER EITHER WAY. `k_norm` is an RMS norm
- * over each head's own `head_dim` row, so norming the context half in one pass and the noise half
- * in the other is bit-for-bit what norming the concatenation would have been. Nothing about the
- * split is an approximation.
+ * ============================== ROW ALIGNMENT ==============================
  *
- * `attn_paged` ALREADY TAKES `causal`, so `causal = 0` serves the non-causal block: every noise
- * row sees every other row of its own block as well as the whole context. This drafter is
- * 16 head / 2 kv / head_dim 128 = GQA 8, the same shape as its target, so the attention and the
- * norm/rope rows the trunk resolves serve it unchanged.
+ * `block` is both the number of noise rows and the number of drafts (seven in, seven out, verify
+ * width eight). Row j of [anchor, MASK x (block-1)] predicts position start + j + 1, the anchor
+ * row included, so `steps() == block` here and `block - 1` in Dflash2, whose anchor row predicts
+ * nothing. Getting this wrong only shifts proposals by one and drops acceptance to chance. The
+ * core stages the block against `RadDrafterDecl::block` and runs the head over the last `depth`
+ * rows, which covers both conventions (rad_builder.h).
  *
- * ============================== THE ROW ALIGNMENT, WHICH IS THE WHOLE GAME ==============================
- *
- * `block_size` IS THE NUMBER OF NOISE ROWS AND ALSO THE NUMBER OF DRAFTS. Seven rows in, seven
- * tokens out, verify width eight. The noise stream is [anchor, MASK x (block-1)] and ROW j
- * PREDICTS THE TOKEN AT POSITION start + j + 1 -- the ordinary next-token relation, anchor row
- * included, which is why `steps() == block` here and `steps() == block - 1` in Dflash2.
- *
- * THAT IS THE OPPOSITE CONVENTION TO Dflash2 AND IT IS INVISIBLE IF YOU GET IT WRONG. Dflash2's
- * anchor row predicts nothing and each MASK row predicts the token at ITS OWN position; DSpark's
- * anchor row is a real prediction and no row is wasted. Both run, both produce `depth` tokens, and
- * the model's own output stays exactly correct either way because every draft is verified against
- * the trunk -- what happens instead is that the proposals are shifted one position and acceptance
- * falls to roughly chance. The core stages the block against `RadDrafterDecl::block` and runs the
- * head over the LAST `depth` rows, which is the one rule both conventions reduce to; rad_builder.h
- * argues it, and this file is the reason that field exists.
- *
- * ============================== THE MARKOV HEAD IS Dflash2'S SELECTOR ==============================
+ * ============================== THE MARKOV HEAD USES Dflash2'S SELECTOR ==============================
  *
  * DSpark adds a rank-256 learned bigram bias to the draft logits:
  *
  *     logits[l] += markov_w2 @ markov_w1[prev(l)]      prev(0) = the anchor,
  *                                                      prev(l) = the token chosen at l - 1
  *
- * which is SERIAL in l for exactly the reason a block-diffusion drafter needs a selector at all:
- * the positions were computed together and the bias at l depends on the token chosen at l - 1.
- * Written literally it is seven full-vocabulary [rank, n_vocab] GEMMs with an argmax between each
- * -- 66 MiB of `markov_w2` read seven times a step to use seven of its rows.
- *
- * `dflash_select` ALREADY COMPUTES THIS. Its edge score is
+ * This is serial in l. Literally it is seven [rank, n_vocab] GEMMs with an argmax between each,
+ * reading 66 MiB of `markov_w2` seven times a step. `dflash_select` scores
  *
  *     unary[l][c] + sum_r pred[prev][r] * hp[l][r] * succ[cand[l][c]][r]
  *
- * over the base head's top K candidates, with the predecessor read after the previous step's
- * argmax inside one workgroup and no launch between steps. Set `hp` ABSENT -- it is optional, and
- * absent it is ones -- and the trilinear form drops to the plain bigram
- * ``; pass `markov_w1` as `pred` and `markov_w2` as `succ` and the walk IS
- * the Markov head, greedily decoded. The codebook gather is K * rank * 2 bytes a position, 8 KiB
- * at K = 16, against 466 MiB for the literal form.
+ * over the base head's top K, reading the predecessor after the previous step's argmax inside one
+ * workgroup. With `hp` absent (treated as ones) it is the bigram ``;
+ * passing `markov_w1` as `pred` and `markov_w2` as `succ` makes the walk the greedily decoded
+ * Markov head. The gather is K * rank * 2 bytes a position (8 KiB at K = 16).
  *
- * WHAT IS APPROXIMATED IS THE CANDIDATE SET AND NOTHING ELSE: the bias can only re-rank the base
- * head's top K, where the reference could promote any of 130560. That is the same trade the 2-bit
- * draft head makes and it is sound for the same reason -- a draft is a proposal, the target
- * verifies every one of them with its own untouched head, and speculative decoding is
- * distribution-preserving, so a coarser draft costs acceptance and CANNOT change an emitted token.
- * `RADIANCE_DRAFT_RAW=dspark_cand` proposes column 0 of the candidate plane instead, which is the
- * base head's own argmax with the Markov walk thrown away: it isolates what the walk contributes,
- * and it needs no rebuild.
+ * Only the candidate set is approximated: the bias re-ranks the base head's top K, where the
+ * reference could promote any of 130560 tokens. Since every draft is verified, this costs only
+ * acceptance.
  *
- * THE CONFIDENCE HEAD IS NOT IMPLEMENTED AND THAT IS NOT A GAP. `AcceptRatePredictor` predicts a
- * per-position acceptance probability so a serving loop can shorten the block adaptively; this
- * engine's depth is fixed at declare time and only 1, 3 and 7 are legal. It changes nothing the
- * drafter proposes, so ignoring it is exactly correct -- unlike the input/output scalars Dflash2
- * refuses, which would silently move every logit.
+ * The confidence head (`AcceptRatePredictor`) is not implemented: it only lets a serving loop
+ * shorten the block adaptively, and this engine's depth is fixed at declare (1, 3 or 7). It does
+ * not change what the drafter proposes.
  *
- * ============================== THE NORMS ARE PLAIN ==============================
+ * ============================== PLAIN NORMS ==============================
  *
- * `w`, not `1 + w`: the reference norms with `Qwen3RMSNorm` and the config says `model_type:
- * qwen3`. `Geom::wadd` and `wadd_qk` are therefore ZERO for this block, which happens to agree
- * with its MiniCPM5 target -- but it is the drafter's own answer and not inherited, and the two
- * geometries are separate structs partly for this.
+ * `w`, not `1 + w`: the reference uses `Qwen3RMSNorm` (`model_type: qwen3`), so this geometry's
+ * `wadd` and `wadd_qk` are zero. That matches the MiniCPM5 target but is the drafter's own
+ * setting.
  *
- * ============================== WHAT IS FP8 AND WHAT IS NOT ==============================
+ * ============================== PRECISION ==============================
  *
  *   E4M3 + a bf16 [N/128][K/128] plane   fc, q/k/v/o, gate_up, down -- every linear
- *   BF16, no plane                       every norm, and both Markov codebooks
+ *   bf16, no plane                       every norm, and both Markov codebooks
  *
- * The checkpoint is dense bf16 throughout, so the first row is rad_fp8.h's DenseFP8 over a weight
- * the recipe quantises to block fp8. The reason is bytes -- the drafter is read WHOLE on every
- * decode step, so 324M parameters at bf16 is 648 MB a step and at fp8 is 324 MB. Nothing it
- * computes can change an emitted token; the only thing quantising it can move is acceptance.
+ * The checkpoint is dense bf16; the linears are rad_fp8.h's DenseFP8 over weights the recipe
+ * quantises, because the drafter is read whole every decode step (324M parameters: 648 MB at
+ * bf16, 324 MB at fp8). This can only change acceptance.
  *
- * The codebooks stay bf16 and REPLICATED because they are gathered by GLOBAL token id out of a
- * merged candidate set: a vocabulary shard would let a rank score only the candidates that
- * happened to land in its own slice. 66.8 MiB each, and the gather is K rows a position, so what
- * costs is the residency and not the reads.
+ * The codebooks are bf16 and replicated: they are gathered by global token id from a merged
+ * candidate set. 66.8 MiB each; only K rows are read per position, so the cost is residency.
  *
- * ============================== WHAT IS LEFT ON THE TABLE ==============================
+ * ============================== NOT DONE ==============================
  *
- * Two things this block does not do, and what each would be worth:
+ *   The q/k norms and ropes are four launches per layer where `qk_norm_rope` would be one. That
+ *   op takes a fused [q|k] row; the query pass would need a [q_dim + kv_dim] buffer, a column-
+ *   slice store and a contiguous q copy, as in rad_block_attn_fp8.h. Worth twenty launches a step.
  *
- *   THE Q/K NORM AND ROPE ARE FOUR LAUNCHES A LAYER where `qk_norm_rope` would be one. That op
- *   takes a FUSED [q|k] row and this block keeps q, k and v in three buffers -- which the context
- *   pass forces for k and v (it computes them with no q at all, and a block-scaled weight's layout
- *   follows its op's N) but does not force for the query pass. Fusing would want a [q_dim + kv_dim]
- *   buffer, a column-slice store, and a contiguous q lift for the attention, which is the trunk's
- *   own arrangement (rad_block_attn_fp8.h). It is worth twenty launches a step.
- *
- *   THE ALL-REDUCE IS NOT FOLDED INTO THE FOLLOWING NORM. NormQuantFP8 has the fused form and this
- *   block passes kArNone, so a tp2 query pass issues ten collectives of its own. At `block` rows a
- *   sequence the message is 28 KiB at one sequence -- under the lossy wire's floor and served
- *   exactly -- so what a fold saves is launches, not bytes.
+ *   The all-reduce is not folded into the following norm (kArNone), so a TP2 query pass issues
+ *   ten collectives. At 28 KiB per message for one sequence (under the lossy floor), a fold
+ *   would save launches, not bytes.
  */
 #ifndef RAD_BLOCK_DSPARK_H
 #define RAD_BLOCK_DSPARK_H
@@ -169,78 +124,71 @@ namespace arch {
 
 struct Dspark {
     enum { MAX_LAYERS = 8 };
-    /* The 2-bit draft head's scale group, which is the w2a8 row's own and not a choice. */
+    /* The 2-bit draft head's scale group, fixed by the w2a8 row. */
     enum { DS_W2_GROUP = 128 };
 
-    /* Everything the drafter's own config.json says that its geometry does not. Read by the plugin
-     * from `draft.*` metadata keys and handed in whole, so this file reads no environment and no
-     * container. */
+    /* The drafter config beyond its geometry, read by the plugin from `draft.*` metadata keys. */
     struct Config {
         int64_t n_taps = 0;     /* how many trunk layers `fc` concatenates */
-        int64_t block  = 0;     /* NOISE ROWS a sequence -- and drafts, one per row */
+        int64_t block  = 0;     /* noise rows per sequence, and drafts (one per row) */
         int64_t rank   = 0;     /* markov_rank: the codebooks' width */
         int64_t top_k  = 0;     /* candidates the Markov walk re-ranks */
         int64_t window = 0;     /* sliding attention width, 0 for none */
         int     causal = 0;
-        /* EVERY ROW PREDICTS, so this is `block` and not `block - 1`. See THE ROW ALIGNMENT. */
+        /* Every row predicts, so `block`, not `block - 1` (see ROW ALIGNMENT). */
         int64_t steps() const { return block; }
     };
 
     struct Wire {
-        /* ---- the context pass, one row a COMMITTED TOKEN */
+        /* ---- the context pass, one row per committed token */
         rad_buf src = 0;   /* [max_tok, n_taps * n_embd]  the trunk's taps, read only */
         rad_buf c   = 0;   /* [max_tok, n_embd]           fc's output, then normed in place */
-        /* K AND V ARE TWO BUFFERS, not one [max_tok, 2*kv_dim] with K in its left half. Both
-         * halves are written by one projection and read by one kv_store, so fusing them is the
-         * obvious thing -- and it is wrong, because of the PER-HEAD NORM in between. `rmsnorm`
-         * takes ONE row pitch. K inside a fused row is `head_dim` apart within a token and
-         * `2*kv_dim` apart between tokens, and no single pitch is both; answering with the
-         * between-tokens stride normalises every eighth head against the wrong numbers, which is
-         * a drafter that runs and barely proposes anything the trunk accepts. libr4d refuses that
-         * operand (libr4d/r4d_model.cpp, rows_pitch). */
-        rad_buf ck  = 0;   /* [max_tok, kv_dim]           ONE layer's K, reused across layers */
-        rad_buf cv  = 0;   /* [max_tok, kv_dim]           ONE layer's V, reused across layers */
-        rad_buf srcq = 0, srcs = 0;   /* the fp8 twins: e4m3 | f32 [.., /128] */
+        /* K and V are separate buffers because of the per-head k norm: `rmsnorm` takes one row
+         * pitch, and K heads inside a fused [K|V] row are head_dim apart within a token but
+         * 2*kv_dim apart between tokens. libr4d refuses such an operand (libr4d/r4d_model.cpp,
+         * rows_pitch). */
+        rad_buf ck  = 0;   /* [max_tok, kv_dim]           one layer's K, reused across layers */
+        rad_buf cv  = 0;   /* [max_tok, kv_dim]           one layer's V, reused across layers */
+        rad_buf srcq = 0, srcs = 0;   /* fp8 codes and scales: e4m3 | f32 [.., /128] */
         rad_buf cq   = 0, cs   = 0;
 
-        /* ---- the query pass, `block` rows a sequence */
+        /* ---- the query pass, `block` rows per sequence */
         rad_buf x = 0;     /* [qrows, n_embd]  the drafter's residual stream */
-        /* THE NORMED INPUT AND THE BLOCK'S DELTA ARE ONE ACTIVATION, which is the trunk's own
-         * arrangement (rad_block_attn_fp8.h): o_proj and down_proj write `h.x`, and the NEXT
-         * norm reads it as the delta to fold into the stream before norming. One buffer, and the
-         * op that reads it also writes it. */
+        /* Normed input and the block's delta share one activation, as in the trunk
+         * (rad_block_attn_fp8.h): o_proj and down_proj write `h.x`, and the next norm folds it
+         * into the stream before norming, writing `h` again. */
         ActFP8  h{};       /* [qrows, n_embd] */
         rad_buf q = 0;     /* [qrows, q_dim] */
-        rad_buf k = 0;     /* [qrows, kv_dim]   -- two buffers, and `ck` above says why */
+        rad_buf k = 0;     /* [qrows, kv_dim]   separate from v, see `ck` */
         rad_buf v = 0;     /* [qrows, kv_dim] */
         ActFP8  attn{};    /* [qrows, q_dim] */
         rad_buf gate_up = 0; /* [qrows, 2 * n_ff] */
         ActFP8  ffn{};     /* [qrows, n_ff] */
 
-        /* ---- the head and the Markov walk, one row a DRAFT POSITION */
+        /* ---- the head and the Markov walk, one row per draft position */
         rad_buf sel_h = 0; /* [srows, n_embd]  the gathered final hidden states */
         rad_buf dq    = 0; /* [srows, n_embd]  i8   the 2-bit head's quantised activation */
         rad_buf ds    = 0; /* [srows, 1]       f32  one scale a row */
         rad_buf dsum  = 0; /* [n_embd/128, pad] f32 GROUP-major, quant_act_i8's asum plane */
         rad_buf dlog  = 0; /* [srows, head_rows(g)] bf16  the coarse logits */
-        rad_buf cand  = 0; /* [srows, top_k] i32  candidate token ids, GLOBAL */
+        rad_buf cand  = 0; /* [srows, top_k] i32  candidate token ids, global */
         rad_buf unary = 0; /* [srows, top_k] f32  and their logits */
-        /* The vocab-parallel pair, declared only when the head is sharded. Both are (int32 id,
-         * float value) pairs read as f32: this rank's top-R, and the all-gathered world * R. */
+        /* Vocab-parallel pairs, declared only when the head is sharded: (int32 id, f32 value)
+         * pairs stored as f32, this rank's top-R and the all-gathered world * R. */
         rad_buf dpair = 0; /* [srows, top_k, 2]         f32 */
         rad_buf dgath = 0; /* [srows, world * top_k, 2] f32 */
-        rad_buf tokens = 0;/* [max_seqs, steps] i32  THE DRAFT -- the engine reads this by name */
+        rad_buf tokens = 0;/* [max_seqs, steps] i32  the draft; the engine reads it by name */
     };
 
-    /* rad_arch.h's, asked through the block so whoever sizes `dlog` and the pair planes does not
-     * re-derive the rule. */
+    /* rad_arch.h's vocab-head rule, asked through the block by whoever sizes `dlog` and the pair
+     * planes. */
     static bool    head_sharded(const Geom& g) { return vocab_head_sharded(g); }
     static int64_t head_rows(const Geom& g)    { return vocab_head_rows(g); }
 
-    Geom    g{};      /* the DRAFTER's geometry, not the trunk's */
+    Geom    g{};      /* the drafter's geometry, not the trunk's */
     Config  cfg{};
     Wire    w{};
-    int     first_layer = 0;   /* absolute, so the KV group's layer_slot lookup finds these five */
+    int     first_layer = 0;   /* absolute, for the KV group's layer_slot lookup */
     int64_t qrows = 0, crows = 0, srows = 0;
     int64_t gated_rows = 0;    /* the band op_gug was declared over; 0 when there is no fold */
     rad_kvgroup kv = 0;
@@ -249,14 +197,12 @@ struct Dspark {
     DenseFP8   w_fc{};
     rad_weight w_hnorm = 0, w_norm = 0;
     rad_weight w_mk1 = 0, w_mk2 = 0;         /* markov_w1 (pred), markov_w2 (succ) */
-    rad_weight w_tok = 0;                    /* the TARGET's embedding table */
-    rad_weight w_dh = 0, w_dhs = 0;          /* the 2-bit copy of the TARGET's lm_head */
+    rad_weight w_tok = 0;                    /* the target's embedding table */
+    rad_weight w_dh = 0, w_dhs = 0;          /* the 2-bit copy of the target's lm_head */
 
-    /* ---- per-layer weights. Q, K AND V ARE THREE WEIGHTS and not the trunk's fused one: the
-     * context pass wants k and v over the projected taps and has no use for q at all, so a fusion
-     * would make it compute and discard a q_dim-wide GEMM per layer per context token. K and V are
-     * apart from each other because a block-scaled weight's layout is a function of its OP's N and
-     * both passes take one of them at a time. */
+    /* ---- per-layer weights. q, k and v are separate: the context pass needs only k and v, and a
+     * block-scaled weight's layout follows its op's N, so k and v cannot be one weight issued a
+     * half at a time. */
     rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {};
     DenseFP8   w_q[MAX_LAYERS]{}, w_k[MAX_LAYERS]{}, w_v[MAX_LAYERS]{}, w_o[MAX_LAYERS]{};
     rad_weight w_qn[MAX_LAYERS] = {}, w_kn[MAX_LAYERS] = {};
@@ -266,17 +212,14 @@ struct Dspark {
     rad_op op_qsrc = 0, op_cfc = 0, op_cnorm = 0, op_qc = 0, op_crope = 0, op_cstore = 0;
     rad_op op_ck[MAX_LAYERS] = {}, op_cv[MAX_LAYERS] = {}, op_cknorm[MAX_LAYERS] = {};
 
-    /* ---- query-pass ops. The weightless ones are declared once and issued per layer: an op's
-     * declared read and write sets are what the buffer planner reads, and they are the same every
-     * layer. The per-layer ones are per-layer because a weight's prefetch interval and residency
-     * class come from the op that declares it. */
+    /* ---- query-pass ops. Weightless ones are declared once and issued per layer; ops with weights
+     * are per layer because a weight's prefetch interval and residency class come from the op
+     * that declares it. */
     rad_op op_embed = 0, op_embed_ar = 0;
-    /* THE FUSED NORM / RESIDUAL-ADD / QUANTISE, declared by hand rather than through rad_fp8.h's
-     * NormQuantFP8. The wrapper's extra machinery is its FUSED-COLLECTIVE forms, which this block
-     * does not take (see WHAT IS LEFT ON THE TABLE), so what is left of it is one op -- and an
-     * ARRAY of the wrapper is not compilable: it nests a Geom, and g++ 16.1 ICEs in build_vec_init
-     * value-initialising an array of that inside an enclosing aggregate assignment (`m = Model{}`
-     * in the plugin). Handles are what every other member here is anyway. */
+    /* The fused norm / residual add / quantise, declared directly rather than via rad_fp8.h's
+     * NormQuantFP8: this block uses none of its fused-collective forms, and an array of the wrapper
+     * (which nests a Geom) makes g++ 16.1 ICE in build_vec_init when the plugin assigns
+     * `m = Model{}`. */
     rad_op op_anorm[MAX_LAYERS] = {}, op_fnorm[MAX_LAYERS] = {}, op_outnorm = 0;
     rad_op op_qat = 0;
     rad_op op_qp[MAX_LAYERS] = {}, op_kp[MAX_LAYERS] = {}, op_vp[MAX_LAYERS] = {};
@@ -295,10 +238,10 @@ struct Dspark {
     int  declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer,
                  rad_kvgroup group, rad_weight tok_embd, const char* ck_prefix,
                  const char* ck_lm, const char* ck_lm_alt, const Wire& wire);
-    /* The context pass, one row a committed token. `batch` carries those rows and the draft KV
-     * group's slot mapping; nothing about the query block is read. */
+    /* The context pass, one row per committed token; `batch` carries those rows and the draft KV
+     * group's slot mapping. */
     void context(RadCtx* c, const RadBatch* batch) const;
-    /* The query pass, the head and the Markov walk: one call, `block` rows a sequence. */
+    /* The query pass, the head and the Markov walk, `block` rows per sequence. */
     void step(RadCtx* c, const RadBatch* batch) const;
 
 private:
@@ -326,10 +269,8 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
     crows = g.max_tok;
     qrows = g.max_seqs * cfg.block;
     if (qrows > g.max_tok) qrows = g.max_tok;
-    /* EVERY QUERY ROW PREDICTS, so the head runs over as many rows as the block has. They are the
-     * same number and they are kept apart anyway: one is a pass's rows and the other is what the
-     * head was declared over, and Dflash2 -- the same struct shape over the other convention --
-     * has them differ by one sequence's worth. */
+    /* Every query row predicts, so srows equals the block's rows; kept separate from qrows because
+     * Dflash2's convention makes them differ. */
     srows = g.max_seqs * cfg.steps();
     if (qrows <= 0 || srows <= 0) return RAD_E_INVAL;
 
@@ -346,11 +287,10 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
     w_norm  = decl_w(b, nm.f("dspark.norm.weight"), RAD_F32, {g.n_embd},
                      RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
 
-    /* THE TWO MARKOV CODEBOOKS, replicated at the WHOLE vocabulary and bf16. `markov_w1` is an
-     * nn.Embedding and `markov_w2` an nn.Linear, and both store [vocab, rank] -- so the bigram
-     * bias `w2 @ w1[prev]` is `` and the two go straight into the selector's
-     * `pred` and `succ` slots in that order. RAD_ACCESS_VOCAB because the reads are a gather of K
-     * rows a position and not a pass over the plane. */
+    /* The Markov codebooks, bf16, replicated over the whole vocabulary. `markov_w1` (nn.Embedding)
+     * and `markov_w2` (nn.Linear) both store [vocab, rank], so `w2 @ w1[prev]` is
+     * `` and they map to the selector's `pred` and `succ`. RAD_ACCESS_VOCAB:
+     * reads gather K rows per position. */
     RAD_ARCH_TRY(map_copy(b, nm.f("dspark.markov_w1"),
                           nm.ckpt("%s.markov_head.markov_w1.weight", ck)));
     RAD_ARCH_TRY(map_copy(b, nm.f("dspark.markov_w2"),
@@ -361,16 +301,12 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
     w_mk2 = decl_w(b, nm.f("dspark.markov_w2"), RAD_BF16, {g.n_vocab_all, cfg.rank},
                    RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
 
-    /* THE 2-BIT DRAFT HEAD, over the TARGET's lm_head. `dspark.draft_head.weight` is that tensor
-     * under a name of its own, which the recipe quantises to the 2-bit grid (u2 codes, an f16
-     * scale and a u8 zero a group of 128): one checkpoint tensor, two logical weights. The
-     * argument is rad_block_mtp_fp8.h's and it is the same one the Markov walk's top-K rests on: a
-     * draft is verified, so a coarser head costs acceptance and cannot move an emitted token.
+    /* The 2-bit draft head over the target's lm_head (as in rad_block_mtp_fp8.h):
+     * `dspark.draft_head.weight` is that tensor under its own name, quantised by the recipe to u2
+     * codes with an f16 scale and u8 zero per group of 128. One checkpoint tensor, two views.
      *
-     * A TIED HEAD IS THE ALTERNATIVE SOURCE. Small LLaMA derivatives ship no `lm_head.weight` and
-     * read the embedding table as both; the trunk's own head is declared that way and the
-     * drafter's copy has to agree with it or the two would disagree about what the model's
-     * vocabulary projection IS. */
+     * The alternative source covers a tied head (small LLaMA derivatives ship no `lm_head.weight`
+     * and reuse the embedding); it must match how the trunk declares its own head. */
     const bool dh_shard = head_sharded(g);
     const int  dh_split = dh_shard ? RAD_SHARD_ROW : RAD_SHARD_NONE;
     const char* dhn = nm.f("dspark.draft_head.weight");
@@ -426,15 +362,11 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
                                      { nm.ckpt("%s.layers.%d.mlp.down_proj.weight", ck, i) }));
     }
 
-    /* NON-CAUSAL. The block is denoised as a whole, so every query row sees every other row of its
-     * own block as well as the context -- `causal` 0 is the drafter's own `is_causal: false` and
-     * not a default.
+    /* Non-causal: each query row sees its whole block plus the context (`causal` comes from the
+     * config's `is_causal: false`).
      *
-     * DECLARED FIRST, before either kv_store, even though it runs after both. `block_size` is
-     * RAD_DERIVED -- the KV block is a property of the resolved attention kernel and not a number
-     * anyone gets to choose -- so it is omitted here and READ BACK with rad_kv_block_size() for
-     * the two stores, which need it as a parameter. Ask before the attention op is declared and
-     * the answer is zero. */
+     * Declared before both kv_stores, which read the resolved `block_size` back with
+     * rad_kv_block_size(); before this declaration it returns zero. */
     op_attn = rw(b, RAD_OP(b, "attn_paged",
                     RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim),
                                RAD_INT("gqa", g.gqa()), RAD_INT("causal", cfg.causal),
@@ -447,10 +379,8 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
 
     /* ---------------------------------------------------------------- the context pass
      *
-     * EVERY LINEAR HERE IS `fp8a8` and every activation that feeds one gets a `quant_act_fp8` in
-     * front of it. There is no `fp8a16` band anywhere in this block: that kernel is M <= 1 and
-     * neither pass ever runs at one row -- a context pass is a committed chunk and a query pass is
-     * `block` rows by construction. */
+     * Every linear is `fp8a8`, fed by a `quant_act_fp8`. There is no `fp8a16` band: that kernel is
+     * M <= 1, and neither pass runs at one row. */
     op_qsrc = rw(b, RAD_OP(b, "quant_act_fp8",
                     RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", cfg.n_taps * g.n_embd),
                                RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
@@ -462,16 +392,15 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
                               RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")),
                    RAD_WEIGHTS(w_fc.w, w_fc.s)),
                {w.srcq, w.srcs}, {w.c});
-    /* IN PLACE. Safe for any implementation that computes a row's scale before writing the row,
-     * which none can avoid doing; the per-head q/k norms below run in place for the same reason. */
+    /* In place, like the per-head q/k norms below: a row's scale is computed before the row is
+     * written. */
     op_cnorm = rw(b, RAD_OP(b, "rmsnorm",
                      RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
                                 RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
                                 RAD_STR("dtype", g.dtype)),
                      RAD_WEIGHTS(w_hnorm)),
                  {w.c}, {w.c});
-    /* ONE QUANTISE FOR ALL FIVE LAYERS. `c` is the normed projection of the trunk's taps and every
-     * layer's k|v reads that same buffer, so this is one launch a context pass and not five. */
+    /* One quantise for all layers: every layer's k and v read the same `c`. */
     op_qc = rw(b, RAD_OP(b, "quant_act_fp8",
                   RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
                              RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
@@ -479,8 +408,8 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
               {w.c}, {w.cq, w.cs});
     for (int64_t l = 0; l < g.n_layer; ++l) {
         const int i = (int)l;
-        /* TWO OPS OF THE SAME SHAPE, one per weight: an op's declared weight list is what gives a
-         * weight its prefetch interval and its residency class. */
+        /* One op per weight: an op's declared weight list gives each weight its prefetch interval
+         * and residency class. */
         op_ck[i] = rw(b, RAD_OP(b, "gemm_nt_q",
                          RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", kvd),
                                     RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
@@ -500,14 +429,11 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
                              RAD_WEIGHTS(w_kn[i])),
                          {w.ck}, {w.ck});
     }
-    /* K-ONLY ROPE. `rope` rotates the first n_head + n_head_kv heads of its operand and leaves the
-     * V heads that follow alone, so a K-only tensor is described by n_head = n_head_kv and
-     * n_head_kv = 0: all the heads there are rotate, none follow them. Weightless, so one op
-     * serves every layer.
+    /* K-only rope: `rope` rotates the first n_head + n_head_kv heads, so a K-only tensor is
+     * n_head = n_head_kv, n_head_kv = 0. Weightless, so one op serves every layer.
      *
-     * THE POSITION IS THE COMMITTED TOKEN'S OWN, which is what makes the split passes equal the
-     * reference's one concatenated rope: it hands `k` the full position range and `q` only the
-     * last `q_len` of it, so a context row at absolute position p is rotated by p either way. */
+     * Each context row is rotated by its own absolute position, as in the reference's single
+     * concatenated rope (k gets the full position range, q the last q_len). */
     op_crope = rw(b, decl_rotary(b, g, "rope",
                      RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
                                 RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
@@ -530,9 +456,9 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
                                 RAD_INT("vocab_offset", g.vocab_off)),
                      RAD_WEIGHTS(w_tok)),
                  {}, {w.x});
-    /* The target's embedding is vocab-sharded, so this gather is partial and takes the same EXACT
-     * reduction the trunk's does: each token's row comes from one rank and every other contributes
-     * a zero, so a lossy wire would be pure loss on a value that is already the answer. */
+    /* The target's embedding is vocab-sharded, so the lookup is partial. The all-reduce is exact:
+     * each row comes from one rank and the others add zero, so a lossy wire would only lose
+     * precision. */
     if (g.world > 1)
         op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
                             RAD_PARAMS(RAD_INT("world_size", g.world),
@@ -541,25 +467,16 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
                             RAD_NOWEIGHTS),
                         {w.x}, {w.x});
 
-    /* THE NORM, THE RESIDUAL ADD AND THE QUANTISER ARE ONE OP -- `rmsnorm_quant_fp8`, which
-     * rad_fp8.h's NormQuantFP8 wraps. Layer 0 has no delta to fold (its input is the embedding
-     * itself), every layer after it folds the previous feed-forward's, and `nq_out` folds the last
-     * one into the FINAL norm. So there is no `add` op in this block at all and the final norm is
-     * not a separate launch either.
+    /* Norm, residual add and quantise are one op, `rmsnorm_quant_fp8` (what rad_fp8.h's
+     * NormQuantFP8 wraps). Layer 0 has no delta to fold, each later norm folds the previous
+     * block's delta, and op_outnorm folds the last into the final norm, so there is no `add` op.
+     * The final norm's fp8 output is unused (the head runs its own i8 quantiser), a few KiB of
+     * waste that saves a launch: libr4d has no plain `rmsnorm_add` row.
      *
-     * `nq_out` QUANTISES SOMETHING NOTHING READS. The head after it wants bf16 (it runs its own
-     * i8 quantiser at a different group width), and this op writes the bf16 normed row as well as
-     * the fp8 twin -- so the twin is 14 KiB of waste at a seven-row block, against a launch. The
-     * alternative is `add` + `rmsnorm`, which is two, because libr4d has no plain `rmsnorm_add`
-     * row: `rmsnorm_quant_fp8` IS this library's fused norm-add. */
-    /* `x` IS THE DELTA AND `residual` IS THE STREAM, and the op adds the first into the second
-     * before norming: residual_out = x + residual, y = rmsnorm(residual_out) * w. So a FOLDED
-     * site passes the previous block's output buffer as `x` and the stream as `residual`, and the
-     * UNFOLDED one (layer 0, whose input is the embedding) passes the stream as `x` and no
-     * residual at all. An absent optional operand is a null tensor in a full-length list.
-     *
-     * `residual` is INOUT, so it is in both sets: the buffer planner reads these for liveness and
-     * an INOUT that claimed only one of them is a plan free to reorder a reader in front of it. */
+     * The op computes residual_out = x + residual, y = rmsnorm(residual_out) * w. A folded site
+     * passes the previous block's output as `x` and the stream as `residual`; layer 0 passes the
+     * stream as `x` and no residual. `residual` is INOUT, so it is in both the read and write sets;
+     * otherwise the planner could reorder a reader in front of it. */
     auto decl_norm = [&](rad_weight gain, bool fold) -> rad_op {
         rad_op h = RAD_OP(b, "rmsnorm_quant_fp8",
                           RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
@@ -580,19 +497,13 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
                {w.attn.x}, {w.attn.q, w.attn.s});
     if (!op_qat) return RAD_E_INVAL;
 
-    /* THE NORMS ARE DECLARED WHERE step() ISSUES THEM, because declaration order is the buffer
-     * planner's liveness: a transient lives over the op indices that touch it, and two whose spans
-     * are disjoint may share bytes (core/build/rad_bufplan.cpp). The stream `x` and the norm
-     * outputs `h` are live across every layer, and the norms are the only ops that touch the
-     * stream after the embedding, so their positions are the stream's lifetime. Each layer's two
-     * norms sit inside the loop and the final one after every op the layers issue -- the shared
-     * rope, store, silu_mul and quantiser handles below included.
-     *
-     * Declared together ahead of the layers, the stream's lifetime ended before the first layer's
-     * temporaries began, and the packer put a feed-forward temporary on top of it. The fused gated
-     * GEMM never writes those, so the overlap stayed silent up to 64 rows a pass; past 64 the
-     * unfused pair writes `gate_up` and `ffn.x`, and every draft was rejected from the tenth
-     * sequence on. */
+    /* Invariant: the norms are declared where step() issues them. Declaration order is the buffer
+     * planner's liveness (a transient lives over the op indices that touch it, and disjoint spans
+     * may share bytes; core/build/rad_bufplan.cpp). The norms are the only ops touching the stream
+     * `x` after the embedding, so their positions define its lifetime: each layer's two norms sit
+     * in the loop, the final one after every op the layers issue, including the shared handles
+     * below. Declared up front, the stream's lifetime would end before the layers and the planner
+     * could overlay a feed-forward temporary on it. */
     for (int64_t l = 0; l < g.n_layer; ++l) {
         const int i = (int)l;
         op_anorm[i] = decl_norm(w_anorm[i], i != 0);
@@ -641,24 +552,8 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
                                     RAD_STR("dtype", "fp8a8")),
                          RAD_WEIGHTS(w_gu[i].w, w_gu[i].s)),
                      {w.h.q, w.h.s}, {w.gate_up});
-        /* THE GATED FOLD: gate_up, silu_mul and the quantiser in one GEMM epilogue, over the same
-         * weights and into the same activation. NOT RAD_ARCH_TRY -- a kernel set without the row
-         * is the ordinary case and the pair below still runs -- and `gated_rows` is the band it
-         * was declared over, checked at the issue site, because M past the band is a REFUSAL in
-         * the kernel and not a slower path. */
-        {
-            const int64_t hi = qrows < 64 ? qrows : 64;
-            if (hi > 0) {
-                op_gug[i] = rw(b, RAD_OP(b, "gemm_nt_q_gated",
-                                   RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", 2 * g.n_ff),
-                                              RAD_INT("K", g.n_embd),
-                                              RAD_INT("group", RAD_FP8_BLOCK),
-                                              RAD_STR("dtype", "fp8a8"), RAD_STR("act", "silu")),
-                                   RAD_WEIGHTS(w_gu[i].w, w_gu[i].s)),
-                               {w.h.q, w.h.s}, {w.ffn.q, w.ffn.s});
-                if (op_gug[i]) gated_rows = hi;
-            }
-        }
+        op_gug[i] = decl_gated_fold(b, qrows, 2 * g.n_ff, g.n_embd, w_gu[i].w, w_gu[i].s,
+                                    {w.h.q, w.h.s}, {w.ffn.q, w.ffn.s}, &gated_rows);
         op_dn[i] = rw(b, RAD_OP(b, "gemm_nt_q",
                          RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", g.n_embd),
                                     RAD_INT("K", g.n_ff), RAD_INT("group", RAD_FP8_BLOCK),
@@ -698,11 +593,8 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
                               RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
                    RAD_NOWEIGHTS),
                {w.ffn.x}, {w.ffn.q, w.ffn.s});
-    /* ONE COLLECTIVE DECLARATION, issued after the out projection and after the down projection:
-     * the two have the same shape over the same buffer. It is EXACT or lossy by the deployment's
-     * own setting, exactly as the trunk's is -- the drafter's message is the same residual stream
-     * and there is no reason for it to be held to a different standard than the thing it drafts
-     * for. */
+    /* One collective, issued after both the out and the down projection (same shape, same buffer).
+     * Exact or lossy per the deployment, as for the trunk. */
     if (g.world > 1)
         op_ar = rw(b, RAD_OP(b, "all_reduce",
                       RAD_PARAMS(RAD_INT("world_size", g.world),
@@ -716,12 +608,9 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
 
     /* ---------------------------------------------------------------- the head and the walk
      *
-     * EVERY ROW OF THE BLOCK PREDICTS, so the head runs over all `steps` of them and the anchor is
-     * not skipped -- THE OPPOSITE of Dflash2, and the paragraph at the top of this file is why.
-     * The gather is what makes those rows contiguous, and it is also what fixes the head's row
-     * numbering at s * steps + l, which is the numbering the walk reads. It is the identity map
-     * for this convention as the scheduler emits it; it is issued anyway, because `out_ids` is the
-     * contract and RADIANCE_DFLASH_ANCHOR is allowed to move it. */
+     * Every row predicts, so the head runs over all `steps` rows, anchor included (see ROW
+     * ALIGNMENT). The gather numbers rows s * steps + l as the walk reads them; for this
+     * convention it is the identity, but `out_ids` is the contract, so it is issued anyway. */
     op_gather = rw(b, RAD_OP(b, "gather_rows",
                       RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
                                  RAD_STR("dtype", g.dtype)),
@@ -738,10 +627,9 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
                                   RAD_STR("dtype", "w2a8")),
                        RAD_WEIGHTS(w_dh, w_dhs)),
                    {w.dq, w.ds, w.dsum}, {w.dlog});
-    /* Sharded, the top-R runs over THIS RANK'S plane and reports GLOBAL ids, and it also writes
-     * the pair plane the gather moves. `vocab_off` is omitted entirely when the head is
-     * replicated: an optional parameter present with the value 0 is not the same declaration as
-     * an absent one. */
+    /* Sharded, the top-R runs over this rank's plane, reports global ids and also writes the pair
+     * plane the gather moves. Replicated, `vocab_off` is omitted: an optional parameter present
+     * with value 0 is a different declaration from an absent one. */
     op_dtopk = dh_shard
         ? rw(b, RAD_OP(b, "row_topk",
                 RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
@@ -755,10 +643,9 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
                 RAD_NOWEIGHTS),
              {w.dlog}, {w.cand, w.unary});
     if (dh_shard) {
-        /* ROW-INTERLEAVED, so one draft position's pairs from every rank land side by side --
-         * `row_topk_merge` reads one row at one row stride. The merge reduces them to the same
-         * global top-R an unsharded head would have found, exactly, ties included, which is what
-         * lets the codebooks stay replicated and indexed by global id. */
+        /* Row-interleaved, so one draft position's pairs from every rank are adjacent for
+         * `row_topk_merge`, which reduces them to exactly the unsharded global top-R, ties
+         * included; the replicated codebooks are then indexed by global id. */
         op_dgather = rw(b, RAD_OP(b, "all_gather",
                            RAD_PARAMS(RAD_INT("world_size", g.world),
                                       RAD_INT("numel", srows * cfg.top_k * 2),
@@ -773,14 +660,12 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
                           RAD_NOWEIGHTS),
                       {w.dgath}, {w.cand, w.unary});
     }
-    /* THE MARKOV WALK. `dflash_select` with the hidden projection ABSENT is the plain bigram
-     * `unary + `, decoded greedily with the predecessor read
-     * after the previous step's argmax -- which is the Markov head, and the top of this file
-     * argues both halves of that claim. Operands are POSITIONAL, so the absent `hp` is still
-     * passed, as RAD_NONE, at the issue site.
+    /* The Markov walk: `dflash_select` with `hp` absent is the bigram
+     * `unary + `, decoded greedily (see the file header). The
+     * absent `hp` is passed as RAD_NONE at the issue site.
      *
-     * `anchor_stride` is `block`, because the operand is the step's own token_ids: a draft pass
-     * carries `block` ids a sequence and the anchor is the first of them. */
+     * `anchor_stride` is `block`: the operand is the step's token_ids, `block` per sequence with
+     * the anchor first. */
     op_sel = rw(b, RAD_OP(b, "dflash_select",
                    RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", cfg.steps()),
                               RAD_INT("top_k", cfg.top_k), RAD_INT("rank", cfg.rank),
@@ -830,9 +715,8 @@ inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
     const int32_t* table = kvb ? kvb->block_table  : nullptr;
     const int32_t* used  = kvb ? kvb->seqused      : nullptr;
 
-    /* The fused norm at its three sites. Folded, `x` is the delta the previous block left in
-     * `h.x` and the stream is added into; unfolded (layer 0), `x` IS the stream and there is no
-     * residual operand -- an absent optional operand is still passed, as RAD_NONE. */
+    /* The fused norm. Folded, `x` is the previous block's delta in `h.x` and the stream is the
+     * residual; unfolded (layer 0), `x` is the stream and the residual is RAD_NONE. */
     auto issue_norm = [&](rad_op op, bool fold, rad_weight gain, int64_t rows) {
         RAD_ISSUE_N(c, op, rows, brows(fold ? w.h.x : w.x, rows),
                     fold ? brows(w.x, rows) : RAD_NONE, RAD_W(gain),
@@ -847,9 +731,8 @@ inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
     for (int64_t l = 0; l < g.n_layer; ++l) {
         const int i = (int)l;
 
-        /* ---- attention. The norm folds the previous layer's feed-forward delta into the stream
-         * and quantises, all in one launch; at layer 0 there is no delta and it norms the
-         * embedding itself. */
+        /* ---- attention. The norm folds the previous feed-forward delta into the stream and
+         * quantises; at layer 0 it norms the embedding. */
         issue_norm(op_anorm[i], i != 0, w_anorm[i], T);
         RAD_ISSUE_N(c, op_qp[i], T, brows(w.h.q, T), brows(w.h.s, T),
                     RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, RAD_NONE);
@@ -861,9 +744,8 @@ inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
         RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv, brows(w.k, T), RAD_W(w_kn[i]), brows(w.k, T));
         RAD_ISSUE_N(c, op_qrope, T, brows(w.q, T), praw(batch->positions, RAD_I32, T));
         RAD_ISSUE_N(c, op_krope, T, brows(w.k, T), praw(batch->positions, RAD_I32, T));
-        /* THE NOISE ROWS GO INTO THE CACHE, past this sequence's `seqused`, and the next context
-         * pass overwrites them from the trunk's real hidden states. That is the reference's
-         * `crop(start)` and it is why nothing here has to undo anything. */
+        /* Noise rows go into the cache past `seqused`; the next context pass overwrites them,
+         * which is the reference's `crop(start)`. */
         RAD_ISSUE_N(c, op_store, T, brows(w.k, T), brows(w.v, T),
                     praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i));
         RAD_ISSUE_N(c, op_attn, batch->max_q_len,
@@ -896,28 +778,25 @@ inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
         if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
     }
 
-    /* The last layer's delta folds into the FINAL norm rather than into a norm of its own. */
+    /* The last layer's delta folds into the final norm. */
     issue_norm(op_outnorm, true, w_norm, T);
 
-    /* The rows that predict something, which here is all of them. The scheduler names them
-     * through out_ids, the same field the trunk's own logits gather reads. */
+    /* The predicting rows (all of them), named by the scheduler through out_ids. */
     const int64_t S = batch->n_out;
     if (S <= 0) return;
     RAD_ISSUE_N(c, op_gather, S, RAD_B(w.h.x), praw(batch->out_ids, RAD_I32, S),
                 brows(w.sel_h, S));
 
-    /* `dsum` is quant_act_i8's GROUP-major plane, [n_embd/group][ceil(M/16)*16], so it is passed
-     * whole: there is no row slice of it that means anything. */
+    /* `dsum` is group-major, [n_embd/group][ceil(M/16)*16], so it has no row slice; pass it
+     * whole. */
     RAD_ISSUE_N(c, op_dquant, S, brows(w.sel_h, S), brows(w.dq, S), brows(w.ds, S),
                 RAD_B(w.dsum));
-    /* The trailing operand is mxfp4's optional reference and is absent here; an absent optional
-     * operand is a null tensor in a FULL-LENGTH list, not a shorter list. */
+    /* The trailing operand is mxfp4's optional reference, absent here. Operands are positional,
+     * so an absent optional one is RAD_NONE, not a shorter list. */
     RAD_ISSUE_N(c, op_dlogits, S, brows(w.dq, S), brows(w.ds, S), RAD_W(w_dh), RAD_W(w_dhs),
                 brows(w.dlog, S), RAD_B(w.dsum), RAD_NONE);
     if (op_dmerge) {
-        /* Sharded, this rank's top-R is not the answer -- it is this rank's CANDIDATES, and
-         * `cand`/`unary` are overwritten by the merge two ops below. Writing them here anyway
-         * costs nothing and keeps one issue site for both paths. */
+        /* Sharded, this rank's top-R are only candidates; the merge overwrites `cand`/`unary`. */
         RAD_ISSUE_N(c, op_dtopk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S),
                     brows(w.dpair, S));
         RAD_ISSUE(c, op_dgather, brows(w.dpair, S), brows(w.dgath, S));
@@ -926,7 +805,7 @@ inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
         RAD_ISSUE_N(c, op_dtopk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S),
                     RAD_NONE);
     }
-    /* RAD_NONE in the third slot is the ABSENT hidden projection -- the bigram form. */
+    /* RAD_NONE in the third slot is the absent hidden projection: the bigram form. */
     RAD_ISSUE_N(c, op_sel, batch->n_seq, brows(w.cand, S), brows(w.unary, S), RAD_NONE,
                 praw(batch->token_ids, RAD_I32, T), RAD_W(w_mk1), RAD_W(w_mk2),
                 brows(w.tokens, batch->n_seq));
diff --git a/arch/common/rad_block_gdn.h b/arch/common/rad_block_gdn.h
index ae5155c4..7d44240e 100644
--- a/arch/common/rad_block_gdn.h
+++ b/arch/common/rad_block_gdn.h
@@ -1,50 +1,42 @@
 /* rad_block_gdn.h -- one gated-delta-net (linear attention) block, bf16 operands.
  *
- * Hybrid models are the normal case, not an extension (spec §7.2): Qwen3.5-27B is 48 GDN layers to
- * 16 full-attention ones. This block is the GDN half, and it composes with AttnGatedBF16 and
- * MlpBF16 in one plugin exactly as they compose with each other.
+ * Hybrid models are the normal case (spec §7.2): Qwen3.5-27B has 48 GDN layers to 16
+ * full-attention ones. This block composes with AttnGatedBF16 and MlpBF16 in one plugin.
  *
  *   rmsnorm -> in gemm ([q|k|v|a|b]) -> z gemm
  *     prefill: gdn_conv_prep -> gdn_kkt_solve -> gdn_chunk_scan -> gdn_gated_rmsnorm
  *     decode:  gdn_conv_update -> gdn_recurrent_update       (which folds the gated norm)
  *   -> out gemm -> [all_reduce] -> residual add
  *
- * THE TWO PATHS ARE A BRANCH ON PHASE, WHICH IS NOT THE BRANCH SPEC §2.4 FORBIDS. A quant branch
- * makes the graph unreadable because it hides which of two op sequences a model uses; this branch
- * picks between two sequences that are both declared, both resolved, both in the graph dump, and
- * both run by the same model on different steps. The chunked path amortises across a prefill chunk
- * and the recurrent path is O(1) per token; there is no single kernel that is right for both.
+ * The two paths branch on phase, which spec §10 allows: both sequences are declared, resolved
+ * and in the graph dump. The chunked path amortises over a prefill chunk, the recurrent path is
+ * O(1) per token, and no single kernel suits both.
  *
- * Both paths take `num_accepted`, because a linear-attention kernel pair MUST support speculative
- * rollback: the recurrent state and the conv window have already absorbed rejected tokens, and a
- * rejection is a change of read offset rather than a recompute (spec §10, OPS.md).
+ * Both paths take `num_accepted`: the recurrent state and conv window have already absorbed
+ * rejected draft tokens, and rollback is a change of read offset, not a recompute (spec §10,
+ * OPS.md).
  *
- * ============================== TWO CONVENTIONS TO GET RIGHT ==============================
+ * ============================== TWO CONVENTIONS ==============================
  *
- * `A_log` IS A LOG AND THE EXPONENT HAS NOT BEEN TAKEN. The decay is
+ * `A_log` is a log. The decay is
  *
  *     g = -exp(A_log) . softplus(a + dt_bias)
  *
- * and the kernels -- libr4d's and libref's alike -- take the exponent themselves. The
- * safetensors checkpoint stores `linear_attn.A_log` in exactly that form, so this block declares
- * the weight as `ssm_a_log` and maps it straight through. THE GGUF CONVERSION DOES NOT: llama.cpp
- * writes `ssm_a = -exp(A_log)` at convert time, so a container built from a GGUF must undo that or
- * the decay becomes -exp(-exp(A_log)), which is a number near -1 for every head and a model that
- * forgets everything in four tokens. The name carries the convention so the mismatch is visible in
- * the weight manifest rather than in the perplexity.
+ * and the kernels (libr4d and libref) take the exponent themselves. Safetensors stores
+ * `linear_attn.A_log` in that form, so the weight is declared `ssm_a_log` and copied through.
+ * llama.cpp's GGUF conversion writes `ssm_a = -exp(A_log)` instead, so a container built from a
+ * GGUF must undo it; otherwise the decay is -exp(-exp(A_log)), near -1 for every head. The name
+ * makes the convention visible in the weight manifest.
  *
- * q AND k ARE L2-NORMALISED, NOT RMS-NORMALISED. Different arithmetic -- no division by the head
- * width and no gain vector -- and it lives inside gdn_conv_prep (prefill) and
- * gdn_recurrent_update (decode) because both kernels already have the head in registers. There is
- * no l2_norm op to declare and there should not be one.
+ * q and k are L2-normalised, not RMS-normalised (no division by the width, no gain), inside
+ * gdn_conv_prep (prefill) and gdn_recurrent_update (decode), which already hold the head in
+ * registers. There is no separate l2_norm op.
  *
  * ============================== THE FUSED IN-PROJECTION ==============================
  *
- * gdn_conv_prep's `x` is the whole projection row [q | k | v | a | b]: conv_dim convolved channels
- * followed by one decay input and one beta input per value head. So the three checkpoint tensors
- * in_proj_qkv, in_proj_a and in_proj_b are ONE declared weight and ONE GEMM, which is also one
- * movement unit and one launch instead of three. The cost is the ability to place them
- * separately, which nothing wants.
+ * gdn_conv_prep's `x` is the whole row [q | k | v | a | b]: conv_dim convolved channels, then
+ * one decay input and one beta input per value head. So in_proj_qkv, in_proj_a and in_proj_b are
+ * one declared weight and one GEMM.
  */
 #ifndef RAD_BLOCK_GDN_H
 #define RAD_BLOCK_GDN_H
@@ -93,7 +85,7 @@ struct GdnBF16 {
         const char* in_b     = nullptr;   /* linear_attn.in_proj_b.weight */
         const char* in_z     = nullptr;   /* linear_attn.in_proj_z.weight */
         const char* conv1d   = nullptr;   /* linear_attn.conv1d.weight */
-        const char* a_log    = nullptr;   /* linear_attn.A_log  -- a LOG, see the header comment */
+        const char* a_log    = nullptr;   /* linear_attn.A_log, a log (see the header) */
         const char* dt_bias  = nullptr;   /* linear_attn.dt_bias */
         const char* out_norm = nullptr;   /* linear_attn.norm.weight */
         const char* out      = nullptr;   /* linear_attn.out_proj.weight */
@@ -125,31 +117,22 @@ inline int GdnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
     if (cfg.n_head_k <= 0 || cfg.head_k <= 0 || cfg.n_head_v <= 0 || cfg.head_v <= 0 ||
         cfg.conv_width <= 0 || cfg.chunk <= 0)
         return RAD_E_INVAL;
-    /* q and k are shared across a group of value heads -- 16 key heads to 48 value heads on this
-     * model. The kernels take H and Hg separately for exactly that; a value head count that is not
-     * a multiple of the key head count is a geometry no GDN kernel serves. */
+    /* q and k are shared across a group of value heads (16 key to 48 value heads on Qwen3.5-27B);
+     * the kernels take H and Hg separately and need H to be a multiple of Hg. */
     if (cfg.n_head_v % cfg.n_head_k != 0) {
         fprintf(stderr, "radiance: %lld value heads is not a multiple of %lld key heads\n",
                 (long long)cfg.n_head_v, (long long)cfg.n_head_k);
         return RAD_E_INVAL;
     }
 
-    /* THE QUERY SCALE, AND IT IS NOT OPTIONAL. `gdn_chunk_scan` and `gdn_recurrent_update` both
-     * carry a `scale` that multiplies the output -- o = scale * e^g Q S^T + ... -- and it defaults to
-     * 1. FLA's chunk_gated_delta_rule defaults it to head_k^-0.5 and vllm-radiance passes exactly
-     * that; llama.cpp's fused GDN does the same.
+    /* The query scale is required. `gdn_chunk_scan` and `gdn_recurrent_update` multiply the output
+     * by `scale` (o = scale * e^g Q S^T + ...), which defaults to 1; FLA's chunk_gated_delta_rule,
+     * vLLM and llama.cpp use head_k^-0.5.
      *
-     * IT LOOKS LIKE IT CANCELS AND IT DOES NOT. The scan's output goes straight into the gated RMS
-     * norm, and an RMS norm divides a constant factor back out -- so scaling `o` by c should change
-     * nothing. That argument is wrong here for one reason: the scan output of this model is around
-     * 1e-6, `mean(o^2)` is then around 1e-12, and the norm's eps is 1e-6. eps DOMINATES the variance,
-     * the norm degenerates into a fixed division by sqrt(eps), and the factor passes straight through
-     * to the residual stream.
-     *
-     * Leaving it at 1 is visible end to end: the scan output comes out larger than the reference
-     * implementations' by exactly sqrt(head_k), and with forty-eight of this model's sixty-four
-     * layers delta net the residual stream then carries a delta-net contribution that many times
-     * too large -- fluent grammar with no content. */
+     * The following gated RMS norm does not cancel it: the scan output is around 1e-6, so
+     * mean(o^2) ~ 1e-12 is dominated by eps = 1e-6 and the norm reduces to a fixed division by
+     * sqrt(eps). Without the scale every delta-net layer's contribution is sqrt(head_k) too
+     * large. */
     const double q_scale = 1.0 / std::sqrt((double)cfg.head_k);
 
     const int64_t v_dim    = cfg.v_dim();
@@ -157,11 +140,10 @@ inline int GdnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
     const int64_t in_dim   = cfg.in_dim();
 
     RAD_ARCH_TRY(map_copy  (b, nm.f("blk.%d.attn_norm.weight", l),  src.norm));
-    /* The fusion: q, k, v, a and b in one row, because that is the row
-     * gdn_conv_prep reads. A row-sharded CONCAT shards each source before concatenating -- and
-     * `in_proj_qkv` is ITSELF three head groups, so the row split declared below is FIVE parts and
-     * not three: q, k and v out of the fused source, then a, then b. The maps come ahead of the
-     * weights they name, since a checkpoint is asked what a weight is through its map. */
+    /* q, k, v, a and b in one row, as gdn_conv_prep reads it. A row-sharded CONCAT shards each
+     * source before concatenating, and `in_proj_qkv` is itself three head groups, so the row split
+     * below has five parts. Maps are declared before the weights, since weight encodings are looked
+     * up through the map. */
     RAD_ARCH_TRY(map_concat(b, nm.f("blk.%d.ssm_in.weight", l),
                             { src.in_qkv, src.in_a, src.in_b }, 0));
     RAD_ARCH_TRY(map_copy  (b, nm.f("blk.%d.ssm_z.weight", l),      src.in_z));
@@ -178,11 +160,9 @@ inline int GdnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
                         {cfg.k_dim(), cfg.k_dim(), cfg.v_dim(), cfg.n_head_v, cfg.n_head_v});
     w_z        = decl_w(b, nm.f("blk.%d.ssm_z.weight", l),          RAD_BF16, {v_dim, g.n_embd},
                         RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW,  grp_layer(l));
-    /* The depthwise convolution is per channel, so it shards with the channels it convolves. The
-     * checkpoint ships [conv_dim, 1, 4]; the middle extent is the depthwise group and is squeezed
-     * at convert. There is NO conv bias on this architecture -- Qwen3.5's conv1d has bias=False --
-     * so none is declared and the operand is passed absent rather than as a zero vector nobody
-     * loads. */
+    /* The depthwise convolution shards with its channels. The checkpoint ships [conv_dim, 1, 4];
+     * the depthwise group extent is squeezed at convert. Qwen3.5's conv1d has bias=False, so the
+     * bias operand is passed absent. */
     w_conv     = decl_w(b, nm.f("blk.%d.ssm_conv1d.weight", l),     RAD_BF16,
                         {conv_dim, cfg.conv_width},
                         RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW,  grp_layer(l), 0,
@@ -191,8 +171,7 @@ inline int GdnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
                         RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW,  grp_layer(l));
     w_dt_bias  = decl_w(b, nm.f("blk.%d.ssm_dt.bias", l),           RAD_F32,  {cfg.n_head_v},
                         RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW,  grp_layer(l));
-    /* One gain vector over head_v, shared by every head: replicated, like the attention q/k
-     * gains. */
+    /* One gain vector over head_v shared by every head, so replicated. */
     w_out_norm = decl_w(b, nm.f("blk.%d.ssm_norm.weight", l),       RAD_F32,  {cfg.head_v},
                         RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
     w_out      = decl_w(b, nm.f("blk.%d.ssm_out.weight", l),        RAD_BF16, {g.n_embd, v_dim},
@@ -211,14 +190,10 @@ inline int GdnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
                               RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
                    RAD_WEIGHTS(w_z)), {w.h}, {w.z});
 
-    /* ---- the chunked path: a prefill chunk, where the scan amortises over `chunk` tokens.
-     * `chunk` is RAD_DERIVED on gdn_kkt_solve and gdn_chunk_scan for the same reason block_size is
-     * on attn_paged -- the tile length belongs to the kernel -- so it is omitted there and comes
-     * off the resolution. gdn_conv_prep still takes it, because the gate cumsum it writes is per
-     * chunk and has to be cut at the same boundary the scan tiles on. THAT THOSE TWO NUMBERS CAN
-     * DISAGREE IS A HOLE: one is supplied and one is derived, nothing compares them, and a
-     * mismatch is a decay applied over the wrong span rather than a diagnostic. Closing it needs
-     * either a readback for a resolved parameter or conv_prep's chunk made derived too. */
+    /* ---- the chunked path (prefill). `chunk` is RAD_DERIVED on gdn_kkt_solve and gdn_chunk_scan
+     * (the tile length belongs to the kernel), but gdn_conv_prep takes it explicitly because its
+     * gate cumsum must be cut at the scan's tile boundary. Known gap: nothing checks that the
+     * supplied and derived values agree; a mismatch applies the decay over the wrong span. */
     op_conv_prep = rw(b, RAD_OP(b, "gdn_conv_prep",
                           RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_k", cfg.head_k),
                                      RAD_INT("head_v", cfg.head_v), RAD_INT("chunk", cfg.chunk),
@@ -240,10 +215,10 @@ inline int GdnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
                       RAD_WEIGHTS(w_out_norm)),
                   {w.o, w.z}, {w.o});
 
-    /* ---- the recurrent path: decode and speculative verify, ranged on q_len because a verify
-     * step carries up to n_spec+1 query rows per sequence. `n_head_v` is stated rather than left
-     * to the value tensor's rank: 48 value heads against 16 key heads is the one geometry where
-     * guessing it from a flattened view gives a plausible wrong answer. */
+    /* ---- the recurrent path (decode and speculative verify), ranged on q_len because a verify
+     * step has up to n_spec+1 query rows per sequence. `n_head_v` is stated explicitly: with 48
+     * value heads to 16 key heads, inferring it from a flattened view gives a plausible wrong
+     * answer. */
     op_conv_update = rw(b, RAD_OP(b, "gdn_conv_update",
                             RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok),
                                        RAD_INT("head_k", cfg.head_k),
@@ -251,17 +226,12 @@ inline int GdnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
                                        RAD_INT("conv_width", cfg.conv_width)),
                             RAD_WEIGHTS(w_conv)),
                         {w.in}, {w.q, w.k, w.v});
-    /* WHAT THE STATE CACHE MEANS, and it is not derivable from the operands. libr4d's recurrent
-     * update has two state contracts. PER-CANDIDATE writes one full state per candidate token and
-     * needs `1 + n_spec` distinct slots; ANCHOR keeps one committed state a sequence and replays
-     * the accepted prefix onto it out of a scratch slot, which is two slots whatever the depth.
-     * Same `o` either way, and a completely different `state` -- so a reference that implements one
-     * of them and is handed the other computes a correct answer to the other question.
-     *
-     * The engine already chooses: KVGroupPlan::state_copies is 2 when the deployment speculates
-     * and 1 when it does not, which is exactly this condition. Saying it here is what lets a
-     * reference DECLINE the form it does not implement instead of disagreeing with it, and what
-     * lets the kernel refuse a caller whose pool was sized for the other one. */
+    /* `state_form` states what the state cache holds, which the operands do not show. libr4d's
+     * recurrent update has two contracts: per_candidate writes one full state per candidate token
+     * (1 + n_spec slots); anchor keeps one committed state per sequence and replays the accepted
+     * prefix from a scratch slot (two slots at any depth). `o` is the same, `state` differs. It
+     * matches KVGroupPlan::state_copies (2 when speculating, else 1), and lets a reference decline
+     * the form it lacks and the kernel refuse a pool sized for the other. */
     op_recur = rw(b, RAD_OP(b, "gdn_recurrent_update",
                       RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_k", cfg.head_k),
                                  RAD_INT("head_v", cfg.head_v),
@@ -298,9 +268,8 @@ inline void GdnBF16::step(RadCtx* c, const RadBatch* batch) const {
     const RadKVGroupBatch* st = kv_batch(batch, kv_state);
     const RadKVGroupBatch* cv = kv_batch(batch, kv_conv);
     const int32_t* st_idx = st ? st->state_index : nullptr;
-    /* HOW MANY SLOTS THE ROW NAMES. One is the state; a linear kernel serving speculation
-     * asks for scratch beside it and the manager sizes the row to suit (RadKVGroupBatch).
-     * The block passes the row through and does not read it. */
+    /* Slots per state_index row: the state, plus scratch when a kernel serving speculation asks
+     * for it (RadKVGroupBatch). Passed through unread. */
     const int64_t st_w = st && st->state_index_pitch > 0 ? st->state_index_pitch : 1;
     const int32_t* cv_idx = cv ? cv->state_index : nullptr;
 
@@ -313,17 +282,15 @@ inline void GdnBF16::step(RadCtx* c, const RadBatch* batch) const {
     RAD_ISSUE(c, op_in,   brows(w.h, T), RAD_W(w_in),   brows(w.in, T));
     RAD_ISSUE(c, op_z,    brows(w.h, T), RAD_W(w_z),    brows(w.z, T));
 
-    /* THE TWO PATHS, EACH OVER ITS OWN RUN OF SEQUENCES. rad_block_gdn_fp8.h's step() carries the
-     * long form of why; the short one is that the step is sorted decode-first, every kernel here
-     * derives both its grid and its rows from cu_seqlens, and cu holds ABSOLUTE offsets -- so the
-     * prefill half is addressed by handing it `cu + D` with the token operands left at their
-     * base, and the decode half by narrowing both to DT. The gated norm takes no cu and is per
-     * token, so it takes a row slice instead. */
+    /* Each path runs over its own run of sequences (details in rad_block_gdn_fp8.h's step()). The
+     * step is sorted decode-first and every kernel derives grid and rows from cu_seqlens, which
+     * holds absolute offsets: the prefill half gets `cu + D` with token operands at their base,
+     * the decode half has both narrowed to DT. The gated norm is per token, so it takes a row
+     * slice. */
     int64_t D = 0, DT = 0;
     batch_split(batch, &D, &DT);
-    /* And the band the decode half selects on. max_q_len over a mixed step is the prefill chunk;
-     * over a pure decode step it is already the right number, so a batch that leaves
-     * max_q_len_decode zero still selects correctly there. */
+    /* The decode half's band. In a mixed step max_q_len is the prefill chunk's; in a pure decode
+     * step it is already right, so a batch leaving max_q_len_decode zero still works there. */
     const int32_t qd = batch->phase == RAD_PHASE_MIXED ? batch->max_q_len_decode : batch->max_q_len;
     const int64_t P  = S - D;
     const int64_t PT = T - DT;
@@ -336,8 +303,7 @@ inline void GdnBF16::step(RadCtx* c, const RadBatch* batch) const {
                     praw(batch->cu_seqlens, RAD_I32, D + 1),
                     brows(w.q, DT), brows(w.k, DT), brows(w.v, DT));
         /* a and b are the last 2*n_head_v columns of the projection row, read in place. The
-         * recurrent kernel folds the gated norm, which is why it takes z and the gain: at one
-         * token a head there is nothing to gain from a second pass over the state. */
+         * recurrent kernel folds the gated norm, so it takes z and the gain. */
         RAD_ISSUE_N(c, op_recur, qd,
                     brows(w.q, DT), brows(w.k, DT), brows(w.v, DT),
                     bcol(w.in, conv_dim, H, DT), bcol(w.in, conv_dim + H, H, DT),
@@ -345,25 +311,20 @@ inline void GdnBF16::step(RadCtx* c, const RadBatch* batch) const {
                     praw2(st_idx, RAD_I32, D, st_w), praw(batch->num_accepted, RAD_I32, D),
                     praw(batch->cu_seqlens, RAD_I32, D + 1),
                     brows(w.z, DT), RAD_W(w_out_norm), brows(w.o, DT),
-                    /* The folded out-projection quantiser, which this block does not want: the
-                     * bf16 out projection reads `o` directly. Absent is TWO NULL OPERANDS, not a
-                     * shorter list -- operands are positional and the runtime refuses a count
-                     * that does not match the schema's sixteen (core/runtime/issue.cpp:111). */
+                    /* The folded out-projection quantiser, unused: the bf16 out projection reads
+                     * `o` directly. Operands are positional and the runtime checks the schema's
+                     * count of sixteen (core/runtime/issue.cpp), so pass two RAD_NONE. */
                     RAD_NONE, RAD_NONE);
     }
 
     if (P > 0) {
-        /* Sixteen operands, inputs before outputs (docs/OPS.md). `a` and `b_gate` are the same
-         * strided views of the projection row the recurrent path builds above; they are optional
-         * in the schema -- ref falls back to the fused `x` tail -- but libr4d's conv_prep
-         * dereferences them and `cache_idx` unconditionally, so omitting them does not select a
-         * cheaper kernel, it silently drops the layer to the reference one.
+        /* Sixteen operands, inputs before outputs (docs/OPS.md). `a` and `b_gate` are optional in
+         * the schema (libref falls back to the fused `x` tail), but libr4d's conv_prep requires
+         * them and `cache_idx`; omitting them would silently fall back to the reference kernel.
          *
-         * `has_init` is ctx_lens, and it is exactly the right array: a zero entry means the slot
-         * holds no history, and a sequence's context length before this step is zero precisely
-         * when it is starting fresh -- a new sequence, or one preempted and replaying, whose conv
-         * slot was recycled and holds another sequence's window. Without it the first chunk of
-         * every prefill convolves against whatever the slot last contained. */
+         * `has_init` is ctx_lens: zero exactly when a sequence starts fresh (new, or preempted and
+         * replaying, with a recycled conv slot), so the first chunk does not convolve against the
+         * slot's stale window. */
         RAD_ISSUE(c, op_conv_prep,
                   brows(w.in, T), RAD_W(w_conv), RAD_NONE, RAD_W(w_a_log), RAD_W(w_dt_bias),
                   kv_cache(kv_conv, layer), praw(batch->cu_seqlens + D, RAD_I32, P + 1),
@@ -381,8 +342,8 @@ inline void GdnBF16::step(RadCtx* c, const RadBatch* batch) const {
                   kv_cache(kv_state, layer), praw(batch->cu_seqlens + D, RAD_I32, P + 1),
                   brows(w.o, T), kv_cache(kv_state, layer),
                   praw2(st_idx ? st_idx + D * st_w : nullptr, RAD_I32, P, st_w));
-        /* PER TOKEN, so a row slice and not a sequence sub-array: over the decode rows the
-         * recurrent kernel has already applied the gate in its own epilogue. */
+        /* Per token, so a row slice over the prefill rows only; the recurrent kernel already
+         * gated the decode rows. */
         RAD_ISSUE_N(c, op_gnorm, PT,
                     brow_slice(w.o, DT, PT, v_dim), brow_slice(w.z, DT, PT, v_dim),
                     RAD_W(w_out_norm), brow_slice(w.o, DT, PT, v_dim));
diff --git a/arch/common/rad_block_gdn_fp8.h b/arch/common/rad_block_gdn_fp8.h
index a410d813..7a8f0d34 100644
--- a/arch/common/rad_block_gdn_fp8.h
+++ b/arch/common/rad_block_gdn_fp8.h
@@ -1,46 +1,35 @@
 /* rad_block_gdn_fp8.h -- the gated-delta-net block with block-scaled FP8 projections.
  *
- * THE ARCHITECTURE IS rad_block_gdn.h's AND IS DOCUMENTED THERE: that `A_log` is a log and the
- * kernels take the exponent themselves, that q and k are L2-normalised rather than RMS-normalised
- * and that this happens inside the conv/recurrent kernels, why the prefill and decode paths are two
- * declared sequences and why that is not the branch spec §2.4 forbids, and why both take
- * `num_accepted`. None of it changes with the weight format.
+ * The architecture (A_log convention, in-kernel L2 norm of q and k, the two declared paths,
+ * `num_accepted`) is documented in rad_block_gdn.h and does not change with the weight format.
  *
- * ============================== a AND b SPLIT OUT; z DOES NOT ==============================
+ * ============================== a AND b SPLIT OUT; z FUSED ==============================
  *
- * rad_block_gdn.h fuses in_proj_qkv, in_proj_a and in_proj_b into ONE weight and one GEMM, because
- * [q|k|v|a|b] is the row gdn_conv_prep reads. THAT FUSION IS NOT AVAILABLE HERE, and the reason is
- * the checkpoint rather than a limitation:
+ * rad_block_gdn.h fuses in_proj_qkv, in_proj_a and in_proj_b into one weight. Here the
+ * checkpoint prevents it:
  *
  *   in_proj_qkv.weight   F8_E4M3 [10240, 5120]   with weight_scale_inv [80, 40]
  *   in_proj_z.weight     F8_E4M3 [ 6144, 5120]   with weight_scale_inv [48, 40]
  *   in_proj_a.weight     BF16    [48, 5120]      -- no scale plane
  *   in_proj_b.weight     BF16    [48, 5120]      -- no scale plane
  *
- * a and b emit ONE COLUMN PER VALUE HEAD, 48 of them, and 48 is not a whole 128-row scale block --
- * so the quantiser that produced this checkpoint left them in bf16, and no concatenation of an
- * E4M3 tensor with a BF16 one is a tensor. They become a second, tiny bf16 `gemm_nt`: [96, 5120],
- * 0.5% of the layer's projection bytes, and the price of it is one extra launch.
+ * a and b have one row per value head (48, not a whole 128-row block), so the quantiser left them
+ * bf16 and they cannot be concatenated with E4M3 tensors. They become a separate small bf16
+ * `gemm_nt` ([96, 5120], 0.5% of the layer's projection bytes). gdn_conv_prep and
+ * gdn_recurrent_update take a and b as separate operands in both blocks (column views of the
+ * fused row there, of their own buffer here); libref sizes its `x` read as
+ * `conv_dim + (a present ? 0 : 2*H)` for this case.
  *
- * a and b are separate operands of gdn_conv_prep and gdn_recurrent_update in both blocks -- the
- * bf16 block passes them as column views of the fused row, this one as column views of their own
- * buffer -- so nothing downstream changes shape. Ref sizes its `x` read as
- * `conv_dim + (a present ? 0 : 2*H)` for precisely this case.
- *
- * THE OUTPUT GATE IS THE OPPOSITE CASE and it IS fused, into `ssm_inz`: in_proj_z is E4M3 with its
- * own scale plane, its rows are a whole number of blocks, and it reads the same normed activation.
- * So [q|k|v|z] is one weight, one launch and the same bytes -- see declare() for why one call is
- * cheaper than two. What that costs is that `w.in.x` is conv_dim + v_dim wide, and the convolution
- * and the gate are COLUMN VIEWS of it rather than buffers of their own: gdn_conv_prep,
- * gdn_conv_update and gdn_recurrent_update all take a row pitch on the operand concerned.
+ * The output gate is fused instead, into `ssm_inz`: in_proj_z is E4M3 with whole scale blocks and
+ * reads the same normed activation, so [q|k|v|z] is one weight and one launch. `w.in.x` is then
+ * conv_dim + v_dim wide, and the convolution input and the gate are column views of it; the
+ * consuming kernels all take a row pitch.
  *
  * ============================== THE OUT-PROJECTION'S INPUT IS RANK 3 ==============================
  *
- * `o` is [tokens, value heads, head width] because libr4d's chunk-scan and recurrent kernels
- * require rank 3 there, and it is the out-projection's activation -- so the quantiser has to accept
- * it. It does: rows are dim 0 and everything after is the row, which is the reading r4d_row_pitch
- * already takes and which the consuming GEMM's K forces. Reading it as one row per HEAD would put a
- * scale on a grid the GEMM does not read.
+ * `o` is [tokens, value heads, head width] because libr4d's chunk-scan and recurrent kernels need
+ * rank 3. The quantiser reads dim 0 as rows and the rest as the row (as r4d_row_pitch does and
+ * the GEMM's K requires); one row per head would put scales on a grid the GEMM does not read.
  */
 #ifndef RAD_BLOCK_GDN_FP8_H
 #define RAD_BLOCK_GDN_FP8_H
@@ -48,15 +37,14 @@
 #include "rad_fp8.h"
 
 #include 
-#include 
 #include 
 
 namespace rad {
 namespace arch {
 
 struct GdnFP8 {
-    /* The same geometry the bf16 block takes, with one addition: `ab_dim` is what the split costs
-     * in declared width, and it is 2 * n_head_v. */
+    /* The bf16 block's geometry plus the gate activation, uneven head splits, and `ab_dim`
+     * (2 * n_head_v), the width of the separate a|b projection. */
     struct Config {
         int64_t n_head_k   = 0;
         int64_t head_k     = 0;
@@ -64,19 +52,15 @@ struct GdnFP8 {
         int64_t head_v     = 0;
         int64_t conv_width = 4;
         int64_t chunk      = 64;
-        /* THE OUTPUT GATE'S ACTIVATION, and it is a CHECKPOINT PROPERTY rather than a family
-         * one. `RMSNormGated` defaults to silu and every Qwen3.5/3.6 release leaves it there,
-         * but Qwen4-Exp states `output_gate_type: "sigmoid"` and means it -- a gate of
-         * sigmoid(z) where this said silu(z) scales every value head's output by roughly z
-         * again. libr4d has compiled both arms all along (r4d_gdn_gated_rmsnorm's `gn_act`) and
-         * `gdn_recurrent_update` composes the same parameter, so this is a string to pass and
-         * not a kernel to write. "silu" or "sigmoid"; anything else is refused below. */
+        /* The output gate's activation, a per-checkpoint property: `RMSNormGated` defaults to
+         * silu (every Qwen3.5/3.6 release), while Qwen4-Exp sets `output_gate_type: "sigmoid"`.
+         * libr4d's r4d_gdn_gated_rmsnorm (`gn_act`) and `gdn_recurrent_update` implement both.
+         * "silu" or "sigmoid"; anything else is refused. */
         const char* act    = "silu";
-        /* AN UNEVEN SPLIT OF THE HEADS (rad_weight_shard_span_parts). n_head_k / n_head_v are
-         * this rank's; k_first / v_first its first head of the container's n_head_k_all /
-         * n_head_v_all. k_first < 0 is the even split the plain row shard gives, as before.
-         * Three ranks over 16 K heads take 6, 5 and 5 (and 18, 15, 15 of the 48 V heads) --
-         * every rank real heads, nothing padded, every kernel at its own head count. */
+        /* Uneven head split (rad_weight_shard_span_parts). n_head_k / n_head_v are this rank's;
+         * k_first / v_first are its first heads within the container's n_head_k_all /
+         * n_head_v_all. k_first < 0 means the plain even row shard. Three ranks over 16 K heads
+         * take 6, 5 and 5 (18, 15, 15 of 48 V heads), with no padding. */
         int64_t k_first = -1, v_first = -1;
         int64_t n_head_k_all = 0, n_head_v_all = 0;
         bool    uneven() const { return k_first >= 0; }
@@ -90,10 +74,8 @@ struct GdnFP8 {
     struct Wire {
         rad_buf x    = 0;   /* [max_tok, n_embd]           the residual stream */
         ActFP8  h{};        /* [max_tok, n_embd]           normed input, then the out projection */
-        /* ONE BUFFER, TWO PROJECTIONS: [q|k|v] and the output gate come out of one GEMM (see
-         * ssm_inz in declare()), so the gate is this buffer's right-hand `v_dim` columns and the
-         * convolution reads the left-hand `conv_dim`. Both are `bcol` views, which is why every
-         * consumer of either takes a row pitch. */
+        /* [q|k|v] and the output gate from one GEMM (ssm_inz): the convolution reads the left
+         * `conv_dim` columns and the gate is the right `v_dim`, both as `bcol` views. */
         ActFP8  in{};       /* [max_tok, conv_dim+v_dim]   [q|k|v] then the output gate */
         rad_buf ab   = 0;   /* [max_tok, 2*n_head_v]       the decay and beta inputs, bf16 */
         rad_buf q    = 0;   /* [max_tok, n_head_k, head_k] post-convolution, l2-normed */
@@ -102,7 +84,7 @@ struct GdnFP8 {
         rad_buf gdec = 0;   /* [max_tok, n_head_v] */
         rad_buf beta = 0;   /* [max_tok, n_head_v] */
         rad_buf kkt  = 0;   /* [max_tok, n_head_v, chunk] */
-        ActFP8  o{};        /* [max_tok, n_head_v, head_v] -- RANK 3, see the header */
+        ActFP8  o{};        /* [max_tok, n_head_v, head_v] rank 3, see the header */
     };
 
     struct Src {
@@ -135,33 +117,38 @@ struct GdnFP8 {
     rad_op op_ab = 0;
     rad_op op_conv_prep = 0, op_kkt = 0, op_scan = 0, op_gnorm = 0;   /* prefill */
     rad_op op_conv_update = 0, op_recur = 0;                          /* decode */
-    /* `gdn_conv_recurrent_update`, if it resolves: the pair above as one launch, the convolution
-     * computed in the recurrent update's prologue. 0 leaves the pair, which is declared either
-     * way; cr_rows is the widest decode window the fold serves. */
+    /* `gdn_conv_recurrent_update`, if it resolves: the pair above in one launch, with the
+     * convolution in the recurrent update's prologue. The pair is declared either way; cr_rows is
+     * the widest decode window the fold serves. */
     rad_op  op_cr = 0;
     int64_t cr_rows = 0;
     rad_op op_ar = 0, op_add = 0;
-    /* ...AND WHETHER THE COLLECTIVE AT THE END OF THIS BLOCK IS THE NEXT BLOCK'S FIRST PASS.
-     * `ar_in` says this block's own norm absorbs its PREDECESSOR's all-reduce; `ar_out` says the
-     * block after it absorbs THIS one's, so this one must not issue it. They are the residual
-     * fold's two flags again, one boundary later, and they are separate for the same reason: a
-     * block is declared without knowing what follows it. On EITHER wire -- the fused kernel
-     * carries both payloads -- and both sides ask ar_fused_ok(g, T), so the two cannot disagree
-     * about whether the collective has already been issued. */
+    /* The next block absorbs this block's closing all-reduce (see rad_block_attn_gated_fp8.h). */
     bool ar_out = false;
-    /* ...and WHICH WIRES that consumer takes (ArOut, rad_fp8.h): the norm's by default, and a gated
-     * residual's write says its own (HyperConn::ar_take). Set before declare; both sides then ask
-     * ar_taken(g, T, ar_out, ar_out_take). */
+    /* Which wires that consumer takes (ArOut, rad_fp8.h); set before declare. */
     int  ar_out_take = kArOutNorm;
 
-
-    /* `fold` says the PREVIOUS block left its delta in `w.h.x` for this norm to add; `add_out`
-     * says the NEXT one will not, so this block issues the trailing add itself. See rad_fp8.h. */
+    /* `fold`: the previous block left its delta in `w.h.x` for this norm to add. `add_out`: the
+     * next block will not add, so this one issues the trailing add. See rad_fp8.h. */
     int  declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int l,
                  rad_kvgroup state, rad_kvgroup conv, const Wire& wire, const Src& s,
                  bool fold = false, bool add_out = true,
                  int ar_in = kArNone, bool ar_out_ = false);
-    void step(RadCtx* c, const RadBatch* batch) const;
+    /* `own_ar` false: the caller issues this step's all-reduce itself, a row slice at a time
+     * (issue_ar), to overlap it with other work (a pipelined prefill). Only on a block without a
+     * trailing add, which would read the delta before the reduction. */
+    void step(RadCtx* c, const RadBatch* batch, bool own_ar = true,
+              ArPieces* pieces = nullptr) const;
+    /* Whether a step of T rows issues the all-reduce itself, asked by a caller before taking it
+     * over; and that all-reduce over rows [r0, r0 + rows) of the output. */
+    bool issues_ar(int64_t T) const { return op_ar && !ar_taken(g, T, ar_out, ar_out_take); }
+    void issue_ar(RadCtx* c, int64_t r0, int64_t rows) const {
+        RAD_ISSUE_N(c, op_ar_ov ? op_ar_ov : op_ar, rows * g.n_embd,
+                    brow_slice(w.h.x, r0, rows, g.n_embd), RAD_NONE);
+    }
+    /* Set before declare: the `overlap` issue_ar's collective is declared at, 0 for none. */
+    int    ar_overlap = 0;
+    rad_op op_ar_ov = 0;
 };
 
 inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int l,
@@ -179,22 +166,8 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
         return RAD_E_INVAL;
     }
 
-    /* THE QUERY SCALE, AND IT IS NOT OPTIONAL. `gdn_chunk_scan` and `gdn_recurrent_update` both
-     * carry a `scale` that multiplies the output -- o = scale * e^g Q S^T + ... -- and it defaults to
-     * 1. FLA's chunk_gated_delta_rule defaults it to head_k^-0.5 and vllm-radiance passes exactly
-     * that; llama.cpp's fused GDN does the same.
-     *
-     * IT LOOKS LIKE IT CANCELS AND IT DOES NOT. The scan's output goes straight into the gated RMS
-     * norm, and an RMS norm divides a constant factor back out -- so scaling `o` by c should change
-     * nothing. That argument is wrong here for one reason: the scan output of this model is around
-     * 1e-6, `mean(o^2)` is then around 1e-12, and the norm's eps is 1e-6. eps DOMINATES the variance,
-     * the norm degenerates into a fixed division by sqrt(eps), and the factor passes straight through
-     * to the residual stream.
-     *
-     * Leaving it at 1 is visible end to end: the scan output comes out larger than the reference
-     * implementations' by exactly sqrt(head_k), and with forty-eight of this model's sixty-four
-     * layers delta net the residual stream then carries a delta-net contribution that many times
-     * too large -- fluent grammar with no content. */
+    /* The query scale is required; rad_block_gdn.h explains why the gated norm does not cancel
+     * it. */
     const double q_scale = 1.0 / std::sqrt((double)cfg.head_k);
 
     if (!cfg.act || (std::strcmp(cfg.act, "silu") != 0 && std::strcmp(cfg.act, "sigmoid") != 0)) {
@@ -206,18 +179,10 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
     const int64_t conv_dim = cfg.conv_dim();
     const int64_t ab_dim   = cfg.ab_dim();
 
-    /* THE INPUT MAY BE PREPARED BY THE ARCHITECTURE, and `src.norm == nullptr` is how it says so.
-     *
-     * A pre-norm model's block owns its own norm: one op that adds the previous block's delta into
-     * the residual stream, normalises it and quantises it (rad_fp8.h's NormQuantFP8). A GATED
-     * RESIDUAL model's does not -- arch/common/rad_block_hc.h's `hc_read` produces the block input
-     * from a stream four times as wide, with a data-dependent mix the block has no way to compute,
-     * and there is nothing left for a norm here to do. So this block takes `wire.h` as ALREADY
-     * normed and quantised and declares no norm weight at all.
-     *
-     * `ar_in` is refused in that mode rather than ignored: the fused all-reduce lives INSIDE the
-     * norm, so with no norm there is nowhere to fold it and a caller that asked would silently get
-     * an unreduced input. It emits a standalone collective instead (`add_out`/`ar_out`). */
+    /* `s.norm == nullptr`: the architecture prepares the input (a gated-residual model's
+     * rad_block_hc.h `hc_read`), so `wire.h` is already normed and quantised and no norm weight is
+     * declared. `ar_in` is then refused, since the fused all-reduce lives inside the norm. See
+     * rad_block_attn_gated_fp8.h. */
     ext_in = (s.norm == nullptr);
     if (ext_in) {
         if (!w.h.x || (!g.w_bf16 && (!w.h.q || !w.h.s)) || ar_in != kArNone) return RAD_E_INVAL;
@@ -226,22 +191,19 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
         w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_F32, {g.n_embd},
                         RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
     }
-    /* The name maps ahead of the weights they name: a checkpoint is asked what a weight is
-     * through its map, at the declaration. */
+    /* Maps before weights: weight encodings are looked up through the map. */
     RAD_ARCH_TRY(map_concat(b, nm.f("blk.%d.ssm_ab.weight", l),     { s.in_a, s.in_b }, 0));
     RAD_ARCH_TRY(map_copy  (b, nm.f("blk.%d.ssm_conv1d.weight", l), s.conv1d));
     RAD_ARCH_TRY(map_copy  (b, nm.f("blk.%d.ssm_a_log", l),         s.a_log));
     RAD_ARCH_TRY(map_copy  (b, nm.f("blk.%d.ssm_dt.bias", l),       s.dt_bias));
     RAD_ARCH_TRY(map_copy  (b, nm.f("blk.%d.ssm_norm.weight", l),   s.out_norm));
-    /* The decay and beta projections, kept bf16 because the checkpoint kept them bf16 -- see the
-     * header. Row-sharded with the value heads they belong to: a and b are concatenated along dim 0
-     * so rank r owns rows [r*n_head_v, (r+1)*n_head_v) of EACH half, which is what the two-part
-     * row split says and what a contiguous slice of the concatenation would not give. */
+    /* The decay and beta projections, bf16 as in the checkpoint. Row-sharded with their value
+     * heads: the two-part split gives rank r rows [r*n_head_v, (r+1)*n_head_v) of each of a and
+     * b, which a contiguous slice of the concatenation would not. */
     w_ab       = decl_w(b, nm.f("blk.%d.ssm_ab.weight", l),     RAD_BF16, {ab_dim, g.n_embd},
                         RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l), 0,
                         {cfg.n_head_v, cfg.n_head_v});
-    /* The depthwise convolution is per channel, so it shards with the channels it convolves --
-     * and those channels are [q|k|v], three groups in one stored tensor, so the split is theirs. */
+    /* The depthwise convolution shards with its channels, [q|k|v] (three parts). */
     w_conv     = decl_w(b, nm.f("blk.%d.ssm_conv1d.weight", l), RAD_BF16,
                         {conv_dim, cfg.conv_width},
                         RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l), 0,
@@ -253,34 +215,26 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
     w_out_norm = decl_w(b, nm.f("blk.%d.ssm_norm.weight", l),   RAD_F32, {cfg.head_v},
                         RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
 
-
-    /* One norm and one quantise of the normed hidden state, in one op; the qkv and z
-     * projections both read it. rad_fp8.h's NormQuantFP8 says why they are not two. */
+    /* Norm and quantise in one op (rad_fp8.h: NormQuantFP8); the qkv|z and a|b projections read
+     * it. */
     if (!ext_in)
         RAD_ARCH_TRY(nq_h.declare(b, g, w_norm, fold ? w.h.x : w.x, w.h, g.n_embd,
                                   fold ? w.x : 0, 0, ar_in));
-    /* TWO CHECKPOINT TENSORS, FOUR PROJECTIONS, ONE GEMM. in_proj_qkv is [q|k|v] stacked along
-     * dim 0 and in_proj_z is the output gate; both read the SAME normed, quantised hidden state
-     * and differ only in their rows, so they are one weight here and one launch at step time.
+    /* Two checkpoint tensors (in_proj_qkv = [q|k|v], in_proj_z = the gate), four projections, one
+     * GEMM. At decode two calls at 5120 and 3072 rows cost more than one at 8192, since each pays
+     * its own ramp and tail. Bit-identical: row arithmetic is unchanged and both extents are past
+     * the split-K threshold.
      *
-     * WHY ONE CALL AND NOT TWO. The decode GEMM is bandwidth-bound but not at small N: two calls
-     * at 5120 and 3072 rows cost more between them than one call at 8192, because each pays its
-     * own ramp and tail on top of its launch. Over this model's delta-net layers that adds up to a
-     * measurable share of a decode step. It is bit-identical: nothing about a row's arithmetic
-     * changes, and both extents are already past the split-K threshold so the summation order does
-     * not move either.
-     *
-     * THE ROW PARTS ARE THE WHOLE POINT. Rank r must own its slice of EACH of q, k, v and z, so
-     * the shard is declared as four parts and not as one contiguous cut -- which would give rank 0
-     * all of q, all of k and a third of v, a well-formed wrong model. */
+     * The four row parts are required so rank r owns its slice of each of q, k, v and z; one
+     * contiguous cut would give rank 0 all of q and k. */
     RAD_ARCH_TRY(in.declare(b, nm, g, nm.f("blk.%d.ssm_inz", l), conv_dim + v_dim, g.n_embd,
                             RAD_SHARD_ROW, grp_layer(l), { s.in_qkv, s.in_z }, w.h, w.in.x, 0,
                             { cfg.k_dim(), cfg.k_dim(), cfg.v_dim(), cfg.v_dim() }, 0, 0,
-                            /* a rotated weight was rotated per CHECKPOINT tensor: q|k|v, then z */
+                            /* a rotated weight was rotated per checkpoint tensor: q|k|v, then z */
                             { 2 * cfg.k_dim() + cfg.v_dim(), cfg.v_dim() }));
     if (cfg.uneven()) {
-        /* THIS RANK'S HEADS OF EACH PART, in the container's rows: q and k by K head, v and z by
-         * V head. The scale plane of a row shard has the same rows (its blocks run along K). */
+        /* This rank's heads of each part, in container rows: q and k by K head, v and z by V head.
+         * The scale plane of a row shard has the same rows (its blocks run along K). */
         const int64_t kl = cfg.k_first * cfg.head_k, vl = cfg.v_first * cfg.head_v;
         const int64_t ka = cfg.n_head_k_all * cfg.head_k, va = cfg.n_head_v_all * cfg.head_v;
         const int64_t lo[4] = { kl, kl, vl, vl };
@@ -297,31 +251,21 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
         RAD_ARCH_TRY(rad_weight_shard_span(b, w_a_log,   cfg.v_first, cfg.v_first + cfg.n_head_v));
         RAD_ARCH_TRY(rad_weight_shard_span(b, w_dt_bias, cfg.v_first, cfg.v_first + cfg.n_head_v));
     }
-    /* NOT SLICED, and why it could need to be is worth keeping. This is a 96-column bf16 GEMM --
-     * half a percent of the layer's projection bytes -- and a bf16 kernel for this shape that
-     * stopped at M = 64 would leave a hole in its bucket table above 64. Since every op in a step
-     * is issued at the same token count, that one hole would cap the prefill chunk of the entire
-     * 27B model at 64 tokens, and the workaround is a launch per 64 rows in every GDN layer. The
-     * cap was a launcher guard the kernel does not need: MT row tiles live in a block and grid.y
-     * covers the rest, so M is general, and with the guard raised this is one launch.
+    /* One launch over all rows: libr4d's bf16 kernel for this 96-column shape is general in M
+     * (MT row tiles per block, grid.y covers the rest). A kernel capped at M = 64 would cap every
+     * op in the step, and so the prefill chunk, at 64 tokens (see brow_slice in rad_arch.h).
      *
-     * AT DECODE THE COST IS THE LAUNCH COUNT, not the arithmetic. `gemm_nt` is the most-dispatched
-     * kernel in a decode step and it is almost entirely fixed cost, spread over three separate
-     * small per-layer projections that all read the same activation: the MoE router (one a layer),
-     * the shared expert's gate (one a layer, RANK 0 ONLY, so on the rank the all-reduce is already
-     * waiting for) and this a|b (one a GDN layer).
-     *
-     * Fusing them is the lever and it is not a small one: they read the same activation but hold
-     * different weights, so a merge wants either contiguous weights -- a re-convert, which is
-     * ruled out -- or a GROUPED gemm_nt taking a table of weight pointers the way moe_gemm_q
-     * does. */
+     * At decode the cost is launch count: `gemm_nt` is the most-dispatched decode kernel, nearly
+     * all fixed cost, across three small per-layer projections of the same activation (the MoE
+     * router, the shared expert's gate on rank 0 only, and this a|b). Merging them would need
+     * contiguous weights (a re-convert) or a grouped gemm_nt over a weight-pointer table, as
+     * moe_gemm_q does. */
     op_ab = rw(b, RAD_OP(b, "gemm_nt",
                    RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", ab_dim),
                               RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
                    RAD_WEIGHTS(w_ab)), {w.h.x}, {w.ab});
 
-    /* ---- the chunked path. Unchanged from the bf16 block except that `a` and `b_gate` are views
-     * of `ab` rather than of the projection row's tail. */
+    /* ---- the chunked path. As in the bf16 block, except `a` and `b_gate` are views of `ab`. */
     op_conv_prep = rw(b, RAD_OP(b, "gdn_conv_prep",
                           RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_k", cfg.head_k),
                                      RAD_INT("head_v", cfg.head_v), RAD_INT("chunk", cfg.chunk),
@@ -351,17 +295,7 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
                                        RAD_INT("conv_width", cfg.conv_width)),
                             RAD_WEIGHTS(w_conv)),
                         {w.in.x}, {w.q, w.k, w.v});
-    /* WHAT THE STATE CACHE MEANS, and it is not derivable from the operands. libr4d's recurrent
-     * update has two state contracts. PER-CANDIDATE writes one full state per candidate token and
-     * needs `1 + n_spec` distinct slots; ANCHOR keeps one committed state a sequence and replays
-     * the accepted prefix onto it out of a scratch slot, which is two slots whatever the depth.
-     * Same `o` either way, and a completely different `state` -- so a reference that implements one
-     * of them and is handed the other computes a correct answer to the other question.
-     *
-     * The engine already chooses: KVGroupPlan::state_copies is 2 when the deployment speculates
-     * and 1 when it does not, which is exactly this condition. Saying it here is what lets a
-     * reference DECLINE the form it does not implement instead of disagreeing with it, and what
-     * lets the kernel refuse a caller whose pool was sized for the other one. */
+    /* `state_form`: anchor when speculating, else per_candidate (rad_block_gdn.h explains). */
     op_recur = rw(b, RAD_OP(b, "gdn_recurrent_update",
                       RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_k", cfg.head_k),
                                  RAD_INT("head_v", cfg.head_v),
@@ -372,16 +306,14 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
                                          g.max_spec > 0 ? "anchor" : "per_candidate")),
                       RAD_WEIGHTS(w_a_log, w_dt_bias, w_out_norm)),
                   {w.q, w.k, w.v, w.ab, w.in.x}, {w.o.x});
-    /* The epilogue's codes, for an fp8 or int8 out-projection -- the int8 pair when the model feeds
-     * it (ActFP8::q8_fed), whose dtype picks the kernel's quantiser; a bf16 one reads `o.x` and
-     * nothing else, and the operands are left absent. */
+    /* The epilogue's codes for an fp8 or int8 out-projection (int8 when ActFP8::q8_fed; the codes
+     * dtype picks the quantiser). A bf16 out-projection reads only `o.x` and these stay absent. */
     if (op_recur && w.o.cq()) {
         const rad_buf oq[2] = { w.o.cq(), w.o.cs() };
         RAD_ARCH_TRY(rad_op_writes(b, op_recur, oq, 2));
     }
-    /* THE FOLD, over the same weights and caches. Its window is a register preload, so the band
-     * stops at eight tokens a sequence; not RAD_ARCH_TRY, since a plugin without the row is the
-     * ordinary case and the pair runs. */
+    /* The conv + recurrent fold. Its window is a register preload, so the band stops at eight
+     * tokens per sequence. Optional (no RAD_ARCH_TRY): without it the pair runs. */
     {
         const int64_t hi = g.max_tok < 8 ? g.max_tok : 8;
         op_cr = rw(b, RAD_OP(b, "gdn_conv_recurrent_update",
@@ -415,7 +347,18 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
                                   RAD_INT("min_bytes", g.wire_min_bytes)),
                        RAD_NOWEIGHTS),
                    {w.h.x}, {w.h.x});
-    /* Only where the NEXT block's norm will not do it; see rad_fp8.h's NormQuantFP8. */
+    /* The same collective for a caller that runs it beside other work (issue_ar, a pipelined
+     * prefill): at `overlap` 1 it gets the rows that hold fewer CUs while waiting on the link. */
+    if (g.world > 1 && ar_overlap > 0)
+        op_ar_ov = 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),
+                                     RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
+                                     RAD_INT("min_bytes", g.wire_min_bytes),
+                                     RAD_INT("overlap", ar_overlap)),
+                          RAD_NOWEIGHTS),
+                      {w.h.x}, {w.h.x});
+    /* Only when the next block's norm will not add (rad_fp8.h: NormQuantFP8). */
     if (add_out)
         op_add = rw(b, RAD_OP(b, "add",
                     RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
@@ -425,53 +368,87 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
     return RAD_OK;
 }
 
-inline void GdnFP8::step(RadCtx* c, const RadBatch* batch) const {
+inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
+                         ArPieces* pieces) const {
     const RadKVGroupBatch* st = kv_batch(batch, kv_state);
     const RadKVGroupBatch* cv = kv_batch(batch, kv_conv);
     const int32_t* st_idx = st ? st->state_index : nullptr;
-    /* HOW MANY SLOTS THE ROW NAMES. One is the state; a linear kernel serving speculation
-     * asks for scratch beside it and the manager sizes the row to suit (RadKVGroupBatch).
-     * The block passes the row through and does not read it. */
+    /* Slots per state_index row: the state, plus scratch when a kernel serving speculation asks
+     * for it (RadKVGroupBatch). Passed through unread. */
     const int64_t st_w = st && st->state_index_pitch > 0 ? st->state_index_pitch : 1;
     const int32_t* cv_idx = cv ? cv->state_index : nullptr;
 
     const int64_t T = batch->n_tok;
     const int64_t S = batch->n_seq;
     const int64_t H = cfg.n_head_v;
-    /* The two halves of `w.in.x`: the convolution's [q|k|v] and the output gate behind it. */
+    /* The two parts of `w.in.x`: the convolution's [q|k|v], then the output gate. */
     const int64_t conv_dim = cfg.conv_dim();
     const int64_t v_dim    = cfg.v_dim();
 
+    /* One prefill sequence in two pieces (ArPieces::cu): the whole block a piece at a time, each
+     * piece the chunk a span of 1 makes (the projection over its rows; the convolution, solve and
+     * scan over its bounds, with the state handed on through the cache; the gated norm, quantiser
+     * and out projection), so the first piece's reduction runs beside all of the second piece's
+     * work. The second piece reads the history the first left in the convolution slot: a spanned
+     * step is past the prompt's first interval, so its context length is never zero. */
+    if (!own_ar && pieces && pieces->cu && pieces->cuts(T) && T <= 2 * pieces->rows && ext_in &&
+        !op_add && S == 1 && batch->phase == RAD_PHASE_PREFILL) {
+        const int64_t in_w = conv_dim + v_dim;
+        for (int64_t p = 0; p < 2; ++p) {
+            const int64_t r0 = p * pieces->rows;
+            const int64_t n  = p == 0 ? pieces->rows : T - pieces->rows;
+            const int32_t* cu = pieces->cu + p;
+            in.step(c, w.h, w.in.x, T, r0, n);
+            RAD_ISSUE_N(c, op_ab, n, brow_slice(w.h.x, r0, n, g.n_embd), RAD_W(w_ab),
+                        brow_slice(w.ab, r0, n, 2 * H));
+            RAD_ISSUE_N(c, op_conv_prep, n,
+                        bcol(w.in.x, 0, conv_dim, T), RAD_W(w_conv), RAD_NONE, RAD_W(w_a_log),
+                        RAD_W(w_dt_bias), kv_cache(kv_conv, layer), praw(cu, RAD_I32, 2),
+                        bcol(w.ab, 0, H, T), bcol(w.ab, H, H, T),
+                        praw(cv_idx, RAD_I32, 1), praw(batch->ctx_lens, RAD_I32, 1),
+                        brows(w.q, T), brows(w.k, T), brows(w.v, T),
+                        brows(w.gdec, T), brows(w.beta, T));
+            RAD_ISSUE_N(c, op_kkt, n,
+                        brows(w.k, T), brows(w.beta, T), brows(w.gdec, T),
+                        praw(cu, RAD_I32, 2), brows(w.kkt, T));
+            RAD_ISSUE_N(c, op_scan, n,
+                        brows(w.q, T), brows(w.k, T), brows(w.v, T), brows(w.kkt, T),
+                        brows(w.gdec, T), brows(w.beta, T),
+                        kv_cache(kv_state, layer), praw(cu, RAD_I32, 2),
+                        brows(w.o.x, T), kv_cache(kv_state, layer),
+                        praw2(st_idx, RAD_I32, 1, st_w));
+            RAD_ISSUE_N(c, op_gnorm, n,
+                        brow_slice(w.o.x, r0, n, v_dim),
+                        bcol_at(w.in.x, r0, in_w, conv_dim, v_dim, n),
+                        RAD_W(w_out_norm), brow_slice(w.o.x, r0, n, v_dim));
+            q_o.step(c, T, r0, n);
+            out.step(c, w.o, w.h.x, T, r0, n);
+            if (p == 0) pieces->hand(r0, n);
+        }
+        return;
+    }
+
     if (!ext_in) nq_h.step(c, T);
     in.step(c, w.h, w.in.x, T);
     RAD_ISSUE_N(c, op_ab, T, brows(w.h.x, T), RAD_W(w_ab), brows(w.ab, T));
 
-    /* THE TWO PATHS, EACH OVER ITS OWN RUN OF SEQUENCES.
+    /* Each path runs over its own run of sequences. The step is sorted decode-first: decode rows
+     * are sequences [0, D) with tokens [0, DT), prefill chunks are [D, S) with the rest. A pure
+     * step issues one path.
      *
-     * The step is sorted decode-first, so the decode rows are sequences [0, D) holding tokens
-     * [0, DT) and the prefill chunks are sequences [D, S) holding the rest. Each path is issued
-     * over its own half and a pure step issues exactly one of them.
+     * Per-sequence arrays are offset, token operands are not. Every kernel here derives its grid
+     * and rows from cu_seqlens (N = len(cu) - 1, a sequence's first row is the absolute cu[n]), so
+     * the prefill half gets `cu + D` with q, k, v at their base; offsetting those too would count
+     * the displacement twice. The decode half is the prefix: cu ends at DT and its token operands
+     * are cut to DT rows. The gated norm and the standalone quantiser take no cu and are per
+     * token, so they take row slices at DT.
      *
-     * THE PER-SEQUENCE ARRAYS MOVE AND THE TOKEN OPERANDS DO NOT. Every kernel here takes
-     * cu_seqlens and derives both its grid and its rows from it -- N is cu's own length minus one
-     * and row zero of a sequence is the ABSOLUTE cu[n] -- so the prefill half is addressed by
-     * handing it `cu + D` while leaving q, k, v and the rest at their base. Offsetting those too
-     * would count the displacement twice. The decode half is the prefix, so it narrows instead:
-     * its cu ends at DT and its token operands are cut to DT rows, which agree because they are
-     * the same number.
-     *
-     * The two ops that take no cu -- the gated norm and the standalone quantiser -- are per TOKEN,
-     * so they take a row slice and are the only place DT appears as an offset.
-     *
-     * What this buys is that a mixed step does not run the chunked path over a sequence that is
-     * only decoding. That path commits the state directly and has no num_accepted operand, so a
-     * draft verified on it could not be rolled back and the scheduler would have to refuse one in
-     * every mixed step -- on an agentic load, a large share of all decode rows. */
+     * This keeps decode-only sequences in a mixed step off the chunked path, which commits state
+     * directly and has no num_accepted, so drafts verified there could not be rolled back. */
     int64_t D = 0, DT = 0;
     batch_split(batch, &D, &DT);
-    /* And the band the decode half selects on. max_q_len over a mixed step is the prefill chunk;
-     * over a pure decode step it is already the right number, so a batch that leaves
-     * max_q_len_decode zero still selects correctly there. */
+    /* The decode half's band. In a mixed step max_q_len is the prefill chunk's; in a pure decode
+     * step it is already right, so a batch leaving max_q_len_decode zero still works there. */
     const int32_t qd = batch->phase == RAD_PHASE_MIXED ? batch->max_q_len_decode : batch->max_q_len;
     const int64_t P  = S - D;
     const int64_t PT = T - DT;
@@ -505,6 +482,10 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch) const {
                     w.o.cq() ? brows(w.o.cs(), DT) : RAD_NONE);
     }
 
+    /* The output a piece at a time where the caller takes the all-reduce that way (ArPieces): the
+     * gated norm, quantiser and out projection are per row, so a pure prefill step can finish them
+     * a piece at a time and hand off each piece's reduction behind it. */
+    const bool cut = !own_ar && pieces && pieces->cuts(T) && D == 0 && P > 0 && !op_add;
     if (P > 0) {
         RAD_ISSUE(c, op_conv_prep,
                   bcol(w.in.x, 0, conv_dim, T), RAD_W(w_conv), RAD_NONE, RAD_W(w_a_log), RAD_W(w_dt_bias),
@@ -523,23 +504,33 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch) const {
                   kv_cache(kv_state, layer), praw(batch->cu_seqlens + D, RAD_I32, P + 1),
                   brows(w.o.x, T), kv_cache(kv_state, layer),
                   praw2(st_idx ? st_idx + D * st_w : nullptr, RAD_I32, P, st_w));
-        /* PER TOKEN, so this one is a row slice and not a sequence sub-array. Over the decode
-         * rows the recurrent kernel has already applied the gate in its own epilogue. */
+        if (cut) {
+            for (int64_t r0 = 0; r0 < T; r0 += pieces->rows) {
+                const int64_t n = T - r0 < pieces->rows ? T - r0 : pieces->rows;
+                RAD_ISSUE_N(c, op_gnorm, n,
+                            brow_slice(w.o.x, r0, n, v_dim),
+                            bcol_at(w.in.x, r0, in_w, conv_dim, v_dim, n),
+                            RAD_W(w_out_norm), brow_slice(w.o.x, r0, n, v_dim));
+                q_o.step(c, T, r0, n);
+                out.step(c, w.o, w.h.x, T, r0, n);
+                if (r0 + n < T) pieces->hand(r0, n);
+            }
+            return;
+        }
+        /* Per token, so a row slice over the prefill rows only; the recurrent kernel already
+         * gated the decode rows. */
         RAD_ISSUE_N(c, op_gnorm, PT,
                     brow_slice(w.o.x, DT, PT, v_dim),
                     bcol_at(w.in.x, DT, in_w, conv_dim, v_dim, PT),
                     RAD_W(w_out_norm), brow_slice(w.o.x, DT, PT, v_dim));
-        /* PREFILL STILL QUANTISES SEPARATELY, and only prefill. The decode kernel folds the
-         * quantiser into its own epilogue -- see the operand list on gdn_recurrent_update -- so
-         * issuing this over those rows would overwrite the same bytes with the same values for a
-         * launch a layer, in every delta-net layer, for nothing. The chunked
-         * scan has no such epilogue: its workgroup is a chunk, not a row, and the group's amax is
-         * not a reduction it can do. */
+        /* Only the prefill rows are quantised here; the decode kernel quantises in its epilogue.
+         * The chunked scan cannot: its workgroup is a chunk, not a row, so it cannot reduce a
+         * row group's amax. */
         q_o.step(c, T, DT, PT);
     }
 
     out.step(c, w.o, w.h.x, T);
-    if (op_ar && !ar_taken(g, T, ar_out, ar_out_take))
+    if (own_ar && op_ar && !ar_taken(g, T, ar_out, ar_out_take))
         RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
     if (op_add) RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h.x, T), brows(w.x, T));
 }
diff --git a/arch/gemma4_bf16/gemma4_vision.h b/arch/common/rad_block_gemma4_vision.h
similarity index 86%
rename from arch/gemma4_bf16/gemma4_vision.h
rename to arch/common/rad_block_gemma4_vision.h
index 5dd0b122..6b3c8d6f 100644
--- a/arch/gemma4_bf16/gemma4_vision.h
+++ b/arch/common/rad_block_gemma4_vision.h
@@ -1,36 +1,41 @@
-/* gemma4_vision.h -- the vision tower of Gemma 4's large dense models (31B), for gemma4_bf16.
- *
- * The same tower family embgemma2 serves (transformers' Gemma4VisionModel), at the 31B's size and
- * with the two parts that model leaves out:
+/* rad_block_gemma4_vision.h -- Gemma 4's vision tower (transformers' Gemma4VisionModel), served by
+ * gemma4_bf16 (the 31B's tower: 27 layers of width 1152) and embgemma2 (16 layers of width 768).
  *
  *   a patch is 16 x 16 x 3, staged by the core's Gemma 4 processor as 2 * (u / 255) - 1 in bf16,
  *   (y, x, channel); patch embedding a [width, 768] linear plus a learned row for the patch's
- *   column and one for its row ([2, 10240, width] table)
- *   27 layers of width 1152: sandwich norms (gain w, not 1 + w), q/k RMS-normed with a gain and v
- *   without one, a 2-D rotary over two 36-channel neox blocks a 72-wide head -- x (the column)
- *   over the first, y over the second, each block at theta^(-j / 18) (rope_type "default"; the
- *   embedding model spells the same rotary "axial") -- bidirectional attention within an image at
- *   scale 1, a gated gelu-tanh MLP
- *   pooling: the mean of each 3 x 3 window times sqrt(width) (the processor lays a window's nine
+ *   column and one for its row (a [2, npos, width] table), the two summed first
+ *   layers: sandwich norms (gain w, not 1 + w), q/k RMS-normed with a gain and v without one, a
+ *   2-D rotary over two neox blocks of a head -- x (the column) over the first, y over the second,
+ *   each block at theta^(-j / (hd / 4)) (rope_type "default"; EmbeddingGemma 2 spells the same
+ *   rotary "axial") -- bidirectional attention within an image at scale 1, a gated gelu-tanh MLP
+ *   pooling: the mean of each pool x pool window times sqrt(width) (the processor lays a window's
  *   patches out consecutively, raster order of windows, as the reference's position pooling)
- *   STANDARDISATION (vision_config.standardize): (z - std_bias) * std_scale per channel. The
- *   reference does it in f32 because a few channels carry ~5e4 with a bias that cancels them;
- *   here z is the pooler's bf16 row, so those channels keep bf16's spacing at their magnitude
- *   (about 1e-2 after the scale -- measured against the reference, see vision.md). The bias row
- *   is made on the card: fill(-1) times std_bias, added to z; then times std_scale.
+ *   standardisation (vision_config.standardize), when set: (z - std_bias) * std_scale per channel.
+ *   The reference does it in f32 because a few channels carry ~5e4 with a bias that cancels them;
+ *   here z is the pooler's bf16 row, so those channels keep bf16's spacing at that magnitude
+ *   (about 1e-2 after the scale). The bias row is made on the card: fill(-1) times std_bias, added
+ *   to z, then times std_scale.
  *   the multimodal embedder: an RMS norm with no gain and a width -> n_embd linear. Its rows
  *   replace the image's placeholder embeddings (which the text model scales by sqrt(n_embd); the
  *   image rows are not scaled).
  *
- * Every rank runs the whole tower (engine_mm.cpp), so its weights are replicated (RAD_SHARD_NONE)
- * and each rank writes the rows into its own copy of the embedding stream. */
-#pragma once
+ * One encoder pass carries RadBuildCtx::max_enc_patches patches over any number of segments (an
+ * image, or one frame of a video). Every rank runs the whole tower (engine_mm.cpp), so its weights
+ * are replicated (RAD_SHARD_NONE) and each rank writes the rows into its own copy of the embedding
+ * stream. */
+#ifndef RAD_BLOCK_GEMMA4_VISION_H
+#define RAD_BLOCK_GEMMA4_VISION_H
 
-namespace gemma4_bf16 {
+#include "rad_arch.h"
 
-using namespace rad::arch;
+#include 
+#include 
+#include 
 
-struct Vision {
+namespace rad {
+namespace arch {
+
+struct Gemma4Vision {
     struct Layer {
         rad_weight in_norm = 0, qkv = 0, q_norm = 0, k_norm = 0, o = 0, post_attn = 0;
         rad_weight pre_ff = 0, gate_up = 0, down = 0, post_ff = 0;
@@ -52,8 +57,11 @@ struct Vision {
         return t && !std::strcmp(t, "gemma4_vision");
     }
 
+    /* `pre` is the checkpoint prefix of the tower and its embedder ("model." for Gemma 4's
+     * conditional-generation checkpoints, "" for EmbeddingGemma 2); `who` names the plugin in
+     * refusals. The tower's layers take weight groups from `first_group`. */
     int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
-                int64_t model_embd, int first_group) {
+                int64_t model_embd, int first_group, const char* pre, const char* who) {
         on = false;
         if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK;
         width = rad_meta_geti(m, "vision_config.hidden_size", 0);
@@ -73,19 +81,20 @@ struct Vision {
         if (width <= 0 || heads <= 0 || hd <= 0 || ff <= 0 || pool <= 0 || npos <= 0 ||
             depth <= 0 || patch <= 0 || !(theta > 0) || heads * hd != width || kvh != heads ||
             hd % 4) {
-            fprintf(stderr, "radiance: gemma4_bf16: the container's vision_config is incomplete or "
-                            "not the shape this plugin serves (hidden %lld, heads %lld x %lld, kv "
-                            "%lld, ff %lld, pooling %lld, layers %lld)\n", (long long)width,
+            fprintf(stderr, "radiance: %s: the container's vision_config is incomplete or not the "
+                            "shape this tower serves (hidden %lld, heads %lld x %lld, kv %lld, ff "
+                            "%lld, pooling %lld, layers %lld)\n", who, (long long)width,
                     (long long)heads, (long long)hd, (long long)kvh, (long long)ff,
                     (long long)pool, (long long)depth);
             return RAD_E_INVAL;
         }
+        /* Clipped linears (their bounds are buffers the vision checkpoint states as infinite) and
+         * any rotary or activation other than the 2-D one and gelu-tanh are refused by name. */
         if (rad_meta_geti(m, "vision_config.use_clipped_linears", 0) ||
             (std::strcmp(rt, "default") && std::strcmp(rt, "axial")) ||
             std::strcmp(act, "gelu_pytorch_tanh")) {
-            fprintf(stderr, "radiance: gemma4_bf16: this vision tower uses clipped linears, a '%s' "
-                            "rotary or a '%s' activation, which this plugin does not serve\n",
-                    rt, act);
+            fprintf(stderr, "radiance: %s: this vision tower uses clipped linears, a '%s' rotary or "
+                            "a '%s' activation, which it does not serve\n", who, rt, act);
             return RAD_E_UNSUPPORTED;
         }
         n_embd = model_embd;
@@ -95,14 +104,15 @@ struct Vision {
         if (P % kk) P -= P % kk;
         R = P / kk;
         const int A = RAD_ACCESS_PER_REQUEST, N = RAD_SHARD_NONE;
-        const char* V = "model.vision_tower";
+        char V[64];
+        std::snprintf(V, sizeof V, "%svision_tower", pre);
 
         RAD_ARCH_TRY(map_copy(b, nm.f("v.patch.weight"), nm.ckpt("%s.patch_embedder.input_proj.weight", V)));
         RAD_ARCH_TRY(map_slice(b, nm.f("v.pos_x.weight"),
                                nm.ckpt("%s.patch_embedder.position_embedding_table", V), 0));
         RAD_ARCH_TRY(map_slice(b, nm.f("v.pos_y.weight"),
                                nm.ckpt("%s.patch_embedder.position_embedding_table", V), 1));
-        RAD_ARCH_TRY(map_copy(b, nm.f("v.embed.weight"), nm.ckpt("model.embed_vision.embedding_projection.weight")));
+        RAD_ARCH_TRY(map_copy(b, nm.f("v.embed.weight"), nm.ckpt("%sembed_vision.embedding_projection.weight", pre)));
         w_in   = decl_w(b, nm.f("v.patch.weight"), RAD_BF16, {width, patch_dim}, A, N, grp_model());
         w_px   = decl_w(b, nm.f("v.pos_x.weight"), RAD_BF16, {npos, width}, A, N, grp_model());
         w_py   = decl_w(b, nm.f("v.pos_y.weight"), RAD_BF16, {npos, width}, A, N, grp_model());
@@ -318,4 +328,7 @@ struct Vision {
     }
 };
 
-}  /* namespace gemma4_bf16 */
+}  /* namespace arch */
+}  /* namespace rad */
+
+#endif /* RAD_BLOCK_GEMMA4_VISION_H */
diff --git a/arch/common/rad_block_hc.h b/arch/common/rad_block_hc.h
index c19c8b6d..44c538f7 100644
--- a/arch/common/rad_block_hc.h
+++ b/arch/common/rad_block_hc.h
@@ -1,13 +1,12 @@
-/* rad_block_hc.h -- the GATED RESIDUAL, which is what Qwen4-Exp has instead of a pre-norm and a
- * residual add.
+/* rad_block_hc.h -- the gated residual (hyper-connection) Qwen4-Exp uses instead of a pre-norm
+ * and a residual add.
  *
  * ============================== THE RESIDUAL STREAM IS `hc` TIMES AS WIDE ==============================
  *
- * hidden_size 2560 at hc_count 4 is a 10240-wide stream. It is entered as FOUR IDENTICAL COPIES of
- * the embedding, carried through all 48 layers, and collapsed once at the end by a connection with
- * no write half. Every block -- attention or delta net, then the feed-forward, so 96 of them --
- * reads a 2560 mix of the four streams and writes its output back into all four, and both halves
- * are data-dependent:
+ * hidden_size 2560 at hc_count 4 gives a 10240-wide stream, entered as four identical copies of
+ * the embedding, carried through all 48 layers, and collapsed at the end by a connection with no
+ * write half. Each of the 96 blocks (attention or delta net, then feed-forward) reads a 2560 mix
+ * of the four streams and writes its output back into all four; both halves are data-dependent:
  *
  *     read    N      = grouped_rmsnorm(h)    one rsqrt per 2560 stream, one 10240 gain, `1 + w`
  *             g      = sigmoid(mix_up @ silu(mix_down @ N / hc))
@@ -15,37 +14,21 @@
  *             inj[s] = 2 * sigmoid(inject_w[s] . N / hc)              -> four scalars in (0, 2)
  *     write   h[s]  += inj[s] * y                                     for each stream s
  *
- * docs/OPS.md's `hc_read` / `hc_write` rows carry the same statement and name the three choices a
- * second implementation has to match (the mix is a MEAN; each gate argument has its own `/ hc`;
- * the write adds into the UNNORMED stream).
+ * docs/OPS.md's `hc_read` / `hc_write` rows state the same and name what a second implementation
+ * must match: the mix is a mean, each gate argument has its own `/ hc`, and the write adds into
+ * the unnormed stream.
  *
- * ============================== WHY IT IS A BLOCK AND NOT TWO CALLS ==============================
+ * One struct declares both halves because they share weights and buffers and must pair: each
+ * write consumes the `inj` of its own read.
  *
- * Because the two halves share a weight set and a buffer set, and because the pairing is the
- * invariant: a read whose `inj` nothing consumes is a bug, and a write whose `inj` came from a
- * different read is a worse one. One struct declares both, holds the four weights once, and gives
- * the plugin a `read()` and a `write()` that cannot be mismatched.
+ * Cost: the arithmetic is small (2 x 10240 x 320 + 4 x 10240 = 6.6M MACs per token, about one
+ * expert pair); the cost is launches, 96 connections per step. So the read emits the fp8 form of
+ * `x` itself instead of a following `quant_act_fp8`, and the write could later be folded into the
+ * producing block's epilogue.
  *
- * ============================== WHAT IT COSTS, AND WHERE THAT GOES ==============================
- *
- * The arithmetic is nothing: 2 x 10240 x 320 plus 4 x 10240 is 6.6M MACs a token against the 5.9M
- * of one expert pair. The LAUNCHES are the cost. A kernel costs a dispatch whatever it computes,
- * and there are 96 connections a step, so every extra op in a connection is 96 more dispatches --
- * a real share of a decode budget measured in tens of milliseconds.
- *
- * That is why the read emits the fp8 form of `x` itself rather than leaving a `quant_act_fp8`
- * behind it, and it is why the write is a candidate to be FOLDED INTO THE PRODUCING BLOCK'S
- * EPILOGUE later (this tree's own rule: fold the quantiser into the producer, and quantise the
- * bf16 that was written). Neither the read's five ops nor the write's one are on the table as
- * separate launches.
- *
- * ============================== WHAT IS NOT SHARDED ==============================
- *
- * Nothing here. The residual stream is replicated on every rank (spec §9) and so is every weight
- * in this file: 6.7 MB a connection at bf16, 1.3 GB over the model, which is the price of not
- * putting a collective inside the connection. A sharded low-rank gate would need an all-reduce
- * between `mix_down` and `mix_up` -- 96 more collectives a step, on 1280 bytes each, and a decode
- * all-reduce is mostly fixed cost whatever the message.
+ * Nothing is sharded: the residual stream is replicated (spec §9), and so are these weights
+ * (6.7 MB per connection at bf16, 1.3 GB over the model). Sharding the low-rank gate would add an
+ * all-reduce between `mix_down` and `mix_up`, 96 more small collectives per step.
  */
 #ifndef RAD_BLOCK_HC_H
 #define RAD_BLOCK_HC_H
@@ -55,12 +38,9 @@
 namespace rad {
 namespace arch {
 
-/* THE WIDE STREAM'S FIRST VALUE: hc identical copies of the embedding.
- *
- * One launch for the whole step, and it is its own op rather than part of the embedding lookup
- * because that op's weight is [vocab, n_embd] and its output width is n_embd -- a wide output
- * would be a different weight shape. The copies are identical here and diverge at the first
- * connection, since every block writes into all hc streams with a DIFFERENT per-branch gain. */
+/* Initialises the wide stream with hc identical copies of the embedding, one launch per step.
+ * Separate from the embedding lookup, whose output width is n_embd. The copies diverge at the
+ * first write, which uses a different gain per stream. */
 struct HcEnter {
     Geom    g{};
     int64_t hc = 0;
@@ -87,31 +67,32 @@ struct HyperConn {
     struct Config {
         int64_t hc      = 0;    /* streams; the reference refuses hc <= 1 and so does this */
         int64_t lowrank = 0;    /* the read gate's waist */
-        /* Whether this connection has a WRITE half. The final mixer does not: it collapses the
-         * wide stream into the one hidden state the lm_head reads and nothing follows it. */
+        /* Whether the connection has a write half. The final mixer does not: it collapses the
+         * stream into the hidden state the lm_head reads. */
         int     inject  = 1;
-        /* Whether the read also emits the block input's fp8 codes. The trunk connections all do;
-         * the mixer does not, because its consumer is the lm_head, which reads a bf16 input. */
+        /* Whether the read also emits the block input's fp8 codes. Not for the final mixer, whose
+         * consumer (the lm_head) reads bf16. */
         int     quant   = 1;
-        /* Whether the WRITE also carries the all-reduce of the block's output, which the block in
-         * front then skips on every step takes_ar() answers yes to. The block's partial sum and the
-         * write's input are the same buffer, so the reduction moves into the write's kernel and
-         * the pair's second launch disappears. */
+        /* Whether the write also performs the all-reduce of the block's output; the block then
+         * skips its own on every step takes_ar() accepts. The block's partial sum is the write's
+         * input buffer, so this saves a launch. */
         int     reduce  = 0;
-        /* Whether the read also emits the HADAMARD-ROTATED fp8 codes of the block input, for a
-         * consumer whose weight carries the rotation (MoeFP8's rotated expert plane). They ride in
-         * the plain codes' finisher, so this needs `quant`, and the consumer then declares no
-         * quantiser of its own -- one dependent launch fewer a connection. */
+        /* Whether the read also emits Hadamard-rotated fp8 codes of the block input, for a
+         * consumer whose weight carries the rotation (MoeFP8's rotated expert plane). Produced in
+         * the plain codes' finisher, so requires `quant`; the consumer declares no quantiser. */
         int     rotate  = 0;
-        /* Whether those codes are INT8 (the input's q8/s8 pair) rather than E4M3 (q/s): a model
-         * whose trunk linears are int8 (LinearFP8::i8) reads them there, so the read writing them
-         * is one quantiser launch fewer a consumer. The rotated twin stays E4M3 either way -- it
-         * is the routed experts' operand. */
+        /* Whether the plain codes are int8 (q8/s8) rather than E4M3 (q/s), for int8 trunk linears
+         * (LinearFP8::i8). The rotated codes stay E4M3, the routed experts' operand. */
         int     codes_i8 = 0;
+        /* The most rows one read is declared for, 0 for max_tok; a wider step reads in pieces
+         * (read_pieces). The read's scratch is sized for its band (some 22 KiB a row at
+         * Flash-Next's shape, on every lane with a scratch region), so a model that reads a wider
+         * step in pieces anyway declares the band no wider than a piece. */
+        int64_t read_rows = 0;
     };
 
     struct Wire {
-        rad_buf h   = 0;    /* [max_tok, hc * n_embd]  THE WIDE STREAM, in place */
+        rad_buf h   = 0;    /* [max_tok, hc * n_embd]  the wide stream, updated in place */
         ActFP8  x{};        /* [max_tok, n_embd]       the block input; q/s unused if !quant */
         rad_buf inj = 0;    /* [max_tok, hc]           the per-branch write gains */
         rad_buf rq  = 0;    /* [max_tok, n_embd]       the rotated codes, when `rotate` */
@@ -130,21 +111,20 @@ struct HyperConn {
     Wire   w{};
 
     rad_weight w_norm = 0, w_down = 0, w_up = 0, w_inj = 0;
-    /* Whether the two mixing matrices are E4M3 rows with a scale a group of each row rather than
-     * bf16 -- OPS.md's `mix` -- which is their encoding's to say, read at declare. */
+    /* Whether the mixing matrices are E4M3 rows with a per-group scale rather than bf16 (OPS.md's
+     * `mix`), read from their encoding at declare. */
     bool       mix_e4m3 = false;
     rad_op     op_read = 0, op_write = 0;
-    /* The write with the all-reduce folded in; 0 when not asked for or when no kernel serves it.
-     * `op_ar_write6` is the same write on the ROTATED 6-BIT wire, declared only where a step can
-     * reach that wire -- an install that accepts a lossy payload -- and issued on exactly the steps
-     * ar_wire_is_exact answers no to: at a prefill chunk that is every all-reduce the trunk makes,
-     * and the payload is 2.6x smaller than the exact one. */
+    /* The write with the all-reduce folded in; 0 when not requested or not served.
+     * `op_ar_write6` is the same on the rotated 6-bit wire, declared only when a lossy payload is
+     * accepted and issued on the steps ar_wire_is_exact rejects (every trunk all-reduce at a
+     * prefill chunk); its payload is 2.6x smaller. */
     rad_op     op_ar_write = 0;
     rad_op     op_ar_write6 = 0;
-    /* AND WITH THE MoE GATHER FOLDED IN FRONT OF THAT: the block behind this write leaves its
-     * routed experts' rows unsummed, and the reduction's message is their sum. Declared by
-     * declare_gather() after the block, whose buffers it reads; `gather_rows` is the bound it serves
-     * and 0 when it was not declared or no kernel serves it (see gather_taken). */
+    /* The same with the MoE gather folded in front: the block leaves its routed experts' rows
+     * unsummed, and the reduction's message is their sum. Declared by declare_gather() after the
+     * block, whose buffers it reads; `gather_rows` is its bound, 0 when not declared or not
+     * served (see gather_taken). */
     struct GatherSrc {
         rad_buf ye = 0, ew = 0, sorted = 0, sh = 0, sg = 0;   /* sh and sg: the shared arm, or 0 */
         int64_t top_k = 0;
@@ -155,17 +135,17 @@ struct HyperConn {
     int64_t    gather_rows = 0, gather_rows6 = 0;
 
     int64_t hn() const { return c.hc * g.n_embd; }
-    /* THE REDUCING WRITE THIS STEP ISSUES, on the wire its message goes out on; 0 where that wire
-     * has no fused form, and the block's own collective then runs in front of the plain write. At
-     * four ranks there is no rotated form, so a step ar_exact_write_takes declines gets 0. */
+    /* The reducing write for this step's wire, or 0 when that wire has no fused form (then the
+     * block's own collective runs before the plain write). At four ranks there is no rotated
+     * form, so steps ar_exact_write_takes declines get 0. */
     rad_op ar_write(int64_t T) const {
         return ar_exact_write_takes(g, T) ? op_ar_write : op_ar_write6;
     }
-    /* WHETHER THIS STEP'S WRITE REDUCES THE BLOCK'S OUTPUT. The block in front asks the same
-     * question of the same T -- ar_taken with ar_take() -- before skipping its own collective. */
+    /* Whether this step's write reduces the block's output. The block asks the same of the same T
+     * (ar_taken with ar_take()) before skipping its own collective. */
     bool takes_ar(int64_t T) const { return ar_write(T) != 0; }
-    /* What that block is told: which wires this write takes. The rotated form is declared only
-     * beside the exact one, so the two together take every message. */
+    /* Which wires this write takes, for the block. The rotated form exists only beside the exact
+     * one, so together they take every message. */
     int ar_take() const { return op_ar_write6 ? kArOutBoth : kArOutExact; }
     bool takes_gather(int64_t T) const {
         return takes_ar(T) && gather_taken(g, T, gather_rows, gather_rows6);
@@ -179,6 +159,16 @@ struct HyperConn {
 
     void read (RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const;
     void write(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const;
+    /* The read over rows [0, T), in pieces of Config::read_rows where it is set; one read
+     * otherwise. The read's down product splits K by how many row tiles it is handed
+     * (hc_down_kchunk in libr4d), so one read over twice the rows sums in a different order than
+     * two reads over half of them; reading a wide step in pieces computes what the narrower steps
+     * did. */
+    void read_pieces(RadCtx* c_, int64_t T) const {
+        const int64_t piece = c.read_rows;
+        if (piece <= 0 || T <= piece) { read(c_, T, 0, T); return; }
+        for (int64_t r0 = 0; r0 < T; r0 += piece) read(c_, T, r0, T - r0 < piece ? T - r0 : piece);
+    }
 };
 
 inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const char* name,
@@ -191,9 +181,7 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
         return RAD_E_INVAL;
     }
     if (!src.norm || !src.mix_down || !src.mix_up) return RAD_E_INVAL;
-    /* An inject WEIGHT with no `inj` buffer, or the reverse, is a connection whose two halves
-     * disagree about whether there is a write. Refused here rather than discovered as an
-     * all-rejected draft three stages later. */
+    /* The inject weight and the `inj` buffer must both be present or both absent. */
     if (c.inject && (!src.inject_w || !w.inj)) {
         fprintf(stderr, "radiance: %s: inject is on but %s is missing\n", name,
                 src.inject_w ? "the inj buffer" : "block_inject_weight");
@@ -214,7 +202,7 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
 
     const int64_t HN = hn();
 
-    /* The name maps first: they are how the model is asked what each weight is. */
+    /* Maps first: weight encodings are looked up through them. */
     const char* nn = nm.f("%s_norm.weight", name);
     const char* dn = nm.f("%s_down.weight", name);
     const char* un = nm.f("%s_up.weight", name);
@@ -224,10 +212,9 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
     RAD_ARCH_TRY(map_copy(b, un, src.mix_up));
     if (c.inject) RAD_ARCH_TRY(map_copy(b, in, src.inject_w));
 
-    /* THE MIXING MATRICES ARE WHATEVER THEIR ENCODING IS: bf16, or E4M3 rows with a scale a
-     * group of each row -- lowrank 320 is 2.5 scale blocks, so a 128x128 tile cannot cover them.
-     * Each is declared over every plane it has, at the codes' dtype, and the read's kernel takes
-     * codes and scales together. The two are one format or the read has no kernel. */
+    /* The mixing matrices are bf16 or E4M3 rows with a per-group scale (lowrank 320 is 2.5 scale
+     * blocks, so 128x128 tiles do not fit). Each is declared over all its planes at the codes'
+     * dtype; both must share one format for the read kernel. */
     const uint32_t mdt = weight_codes_dtype(b, dn, RAD_BF16);
     if (weight_codes_dtype(b, un, RAD_BF16) != mdt || (mdt != RAD_BF16 && mdt != RAD_F8E4M3)) {
         fprintf(stderr, "radiance: %s: the mixing matrices are %s and %s; a connection reads both "
@@ -237,8 +224,7 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
     }
     mix_e4m3 = mdt == RAD_F8E4M3;
 
-    /* F32 like every other norm gain in this tree: 10240 numbers read once a connection, and the
-     * norm's arithmetic is f32 regardless, so narrowing them buys nothing. */
+    /* F32 like every norm gain in this tree. */
     w_norm = decl_w(b, nn, RAD_F32, {HN}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
     w_down = decl_w(b, dn, mdt, {c.lowrank, HN}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
                     grp_model());
@@ -249,21 +235,16 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
                        grp_model());
     if (!w_norm || !w_down || !w_up || (c.inject && !w_inj)) return RAD_E_INVAL;
 
-    /* `inject` and `group` are declared even when off, with the value 0, because a kernel row
-     * bands on them: a fused read that writes four gates is a different kernel from one that does
-     * not, and the resolver needs to be able to say so. An ABSENT key fails a constraint, so
-     * leaving them out would make both rows unselectable rather than one. */
-    /* RAD_WEIGHTS expands to TWO arguments -- the array and its length -- so it cannot sit in a
-     * ternary, and the four-or-three choice is made by building the array. The absent inject
-     * weight is a SHORTER list and not a zero handle: rad_plugin.h's absent-operand rule is about
-     * the launch, but a declared weight of 0 is a declaration failure here. */
+    /* `inject` and `group` are declared as 0 when off, not omitted: kernel rows constrain them, and
+     * an absent key fails every constraint.
+     *
+     * RAD_WEIGHTS expands to two arguments, so the weight list is built as an array. A missing
+     * inject weight shortens the list; a zero weight handle would be a declaration failure. */
     const rad_weight wts[4] = { w_norm, w_down, w_up, w_inj };
     const int n_wts = c.inject ? 4 : 3;
 
-    /* The write set is positional and the optional OUTPUTS are the tail, so an absent one shortens
-     * the list exactly as an absent weight does. The read's outputs are x, inj?, q?, scale? and
-     * both switches drop a suffix, never a middle -- which is why the schema puts inj before the
-     * quantiser's pair rather than after. */
+    /* Outputs are x, inj?, codes?, scales?, rotated pair?. The write set is positional with
+     * optional outputs at the tail, so an absent one shortens the list. */
     rad_buf wr[6] = { w.x.x, 0, 0, 0, 0, 0 };
     int n_wr = 1;
     if (c.inject) wr[n_wr++] = w.inj;
@@ -271,7 +252,9 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
     if (c.rotate) { wr[n_wr++] = w.rq;  wr[n_wr++] = w.rs; }
 
     op_read = RAD_OP(b, "hc_read",
-                  RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
+                  RAD_PARAMS(RAD_RANGE("M", 1, c.read_rows > 0 && c.read_rows < g.max_tok
+                                                   ? c.read_rows : g.max_tok),
+                             RAD_INT("n", g.n_embd),
                              RAD_INT("hc", c.hc), RAD_INT("lowrank", c.lowrank),
                              RAD_F64("eps", g.eps), RAD_STR("dtype", g.dtype),
                              RAD_F64("wadd", g.wadd), RAD_INT("inject", c.inject ? 1 : 0),
@@ -293,12 +276,9 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
                          RAD_NOWEIGHTS),
                      {w.x.x, w.inj, w.h}, {w.h});
         if (!op_write) return RAD_E_INVAL;
-        /* A handle that did not resolve is 0 and not an error: a backend without the fused kernel
-         * keeps the pair, and takes_ar() then answers no on every step. At four ranks only the
-         * exact form exists, declared over the decode and verify steps' rows and taken where
-         * ar_wide_write_exact says so. The exact form states `wire` 0 rather than leaving it out:
-         * a row that serves one wire only says so with a constraint on `wire`, and a constraint on
-         * an absent key does not hold. */
+        /* An unresolved handle is 0, not an error: without the fused kernel the pair runs and
+         * takes_ar() always answers no. At four ranks only the exact form exists, declared over the
+         * decode and verify rows. `wire` 0 is stated, not omitted, because rows constrain it. */
         const int64_t ar_rows = ar_exact_write_rows(g);
         if (c.reduce && ar_rows >= 1)
             op_ar_write = rw(b, RAD_OP(b, "ar_hc_write",
@@ -307,9 +287,9 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
                                            RAD_STR("dtype", g.dtype), RAD_INT("wire", 0)),
                                 RAD_NOWEIGHTS),
                              {w.x.x, w.inj, w.h}, {w.x.x, w.h});
-        /* The rotated form at two ranks only: the op has no four-rank form on that wire
-         * (docs/OPS.md), and an op declared that nothing resolves is reported at startup as a
-         * band a request cannot run in. */
+        /* The rotated form at two ranks only: there is no four-rank form on that wire
+         * (docs/OPS.md), and an unresolvable op would be reported at startup as an unservable
+         * band. */
         if (op_ar_write && !g.wire_exact && g.world == 2)
             op_ar_write6 = rw(b, RAD_OP(b, "ar_hc_write",
                                  RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
@@ -323,26 +303,22 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
 
 inline int HyperConn::declare_gather(RadBuilder* b, const GatherSrc& src) {
     if (!op_ar_write || src.top_k <= 0 || !src.ye || !src.ew || !src.sorted) return RAD_OK;
-    /* Two ranks, and four on the exact wire: there the fused write exists in its exact form only,
-     * so the gather does too -- op_ar_write6 is 0 at four and the rotated form below is never
-     * declared. Any other width keeps its gather and both bounds stay 0. */
+    /* Two or four ranks. At four only the exact form exists (op_ar_write6 is 0). Other widths keep
+     * the block's own gather and both bounds stay 0. */
     if (g.world != 2 && g.world != 4) return RAD_OK;
     const bool shared = src.sh && src.sg;
     gsrc = src;
-    /* EVERY ROW COUNT ONE PASS CARRIES, up to the rows the write itself was declared for
-     * (ar_exact_write_rows): prefill chunks included at two ranks, the decode and verify steps at
-     * four. The kernel reads its slots from an LDS table at a decode step and from an inverse
-     * table at a chunk, where the gather's reads then run beside the reduction's push instead of
-     * in a launch of their own. */
+    /* Up to one pass's rows, capped at the write's own bound (ar_exact_write_rows): prefill chunks
+     * at two ranks, decode and verify steps at four. The kernel reads its slots from an LDS table
+     * at decode and from an inverse table at a chunk. */
     int64_t rows = src.rows;
     const int64_t ar_rows = ar_exact_write_rows(g);
     if (rows > ar_rows) rows = ar_rows;
     if (rows < 1) return RAD_OK;
     const rad_buf rd[8] = { src.ye, src.ew, src.sorted, w.x.x, w.inj, w.h, src.sh, src.sg };
     const rad_buf wr[2] = { w.x.x, w.h };
-    /* One op a wire, as the write itself: the rotated form beside the rotated write only. A handle
-     * that did not resolve is 0 and not an error: the block keeps its gather and this write keeps
-     * the reduction alone, and that wire's bound stays 0 so both say so. */
+    /* One op per wire, the rotated form only beside the rotated write. An unresolved handle is 0:
+     * the block keeps its gather and that wire's bound stays 0. */
     op_ar_gather_write = RAD_OP(b, "ar_gather_hc_write",
                                 RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
                                            RAD_INT("hc", c.hc), RAD_INT("top_k", src.top_k),
@@ -389,9 +365,9 @@ inline void HyperConn::read(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) con
                 c.rotate ? brow_slice(w.rs, r0, rows, fp8_blocks(g.n_embd)) : RAD_NONE);
 }
 
-/* `y` is the block's output, and it is `w.x.x` -- the same buffer the read wrote the block's INPUT
- * into. Every block in this tree leaves its delta in the activation its norm produced, so the
- * write reads it there; the input is dead by then. */
+/* The block's output `y` is read from `w.x.x`, the buffer the read wrote the block's input to:
+ * every block leaves its delta in the activation its norm produced, and the input is dead by
+ * then. */
 inline void HyperConn::write(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const {
     if (!op_write) return;
     if (takes_gather(T)) {
diff --git a/arch/common/rad_block_mlp.h b/arch/common/rad_block_mlp.h
index 7e93ce71..25688527 100644
--- a/arch/common/rad_block_mlp.h
+++ b/arch/common/rad_block_mlp.h
@@ -2,10 +2,9 @@
  *
  *   rmsnorm -> gate_up gemm -> silu_mul -> down gemm -> [all_reduce] -> residual add
  *
- * gate and up are one weight and one GEMM. That is a convert-time fusion the plugin owns (spec
- * §2.4): the container ships ffn_gate.weight and ffn_up.weight, the map concatenates them along
- * dim 0, and silu_mul splits [M, 2n] back into gate times up. It buys one GEMM launch instead of
- * two and one movement unit instead of two.
+ * gate and up are fused into one weight at convert time (spec §2.4): the map concatenates the
+ * checkpoint's gate and up along dim 0 and silu_mul splits [M, 2n] back into gate * up. One GEMM
+ * launch and one movement unit instead of two.
  */
 #ifndef RAD_BLOCK_MLP_H
 #define RAD_BLOCK_MLP_H
@@ -23,9 +22,9 @@ struct MlpBF16 {
         rad_buf ffn     = 0;   /* [max_tok, n_ff] */
     };
 
-    /* Checkpoint-side names for one layer. The plugin owns the spelling because it is the only
-     * component that knows both sides of the map (spec §2.4), and one architecture arrives as
-     * `model.language_model.layers.N.mlp.*` and another as `blk.N.ffn_*`. */
+    /* Checkpoint-side names for one layer. The plugin supplies them because only it knows both
+     * sides of the map (spec §2.4); spellings differ per checkpoint (`...layers.N.mlp.*`,
+     * `blk.N.ffn_*`). */
     struct Src {
         const char* norm = nullptr;   /* post_attention_layernorm.weight */
         const char* gate = nullptr;
@@ -84,8 +83,8 @@ inline int MlpBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, c
                      RAD_WEIGHTS(w_down)),
                  {w.ffn}, {w.h});
 
-    /* Column-sharded down projection: every rank holds a partial sum. Emitted here, by the
-     * plugin, so the graph dump shows it here (spec §9). */
+    /* Column-sharded down projection leaves a partial sum on every rank. The plugin emits the
+     * reduction so the graph dump shows it (spec §9). */
     if (g.world > 1)
         op_ar = rw(b, RAD_OP(b, "all_reduce",
                        RAD_PARAMS(RAD_INT("world_size", g.world),
@@ -105,9 +104,8 @@ inline int MlpBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, c
 }
 
 inline void MlpBF16::step(RadCtx* c, const RadBatch* batch) const {
-    /* Every operand carries the STEP's row count and not the buffer's: a kernel reads its extents
-     * off the operands, because a ranged parameter has been collapsed to a band by the time issue
-     * runs (arch/common/rad_arch.h, libref/ref_ops.h). */
+    /* Operands carry the step's row count, not the buffer's: kernels read extents from the
+     * operands because a ranged parameter is collapsed to a band before issue (rad_arch.h). */
     const int64_t T = batch->n_tok;
     RAD_ISSUE(c, op_norm,    brows(w.x, T),       RAD_W(w_norm),    brows(w.h, T));
     RAD_ISSUE(c, op_gate_up, brows(w.h, T),       RAD_W(w_gate_up), brows(w.gate_up, T));
diff --git a/arch/common/rad_block_mlp_fp8.h b/arch/common/rad_block_mlp_fp8.h
index f1b01720..6a9e8261 100644
--- a/arch/common/rad_block_mlp_fp8.h
+++ b/arch/common/rad_block_mlp_fp8.h
@@ -3,27 +3,18 @@
  *   rmsnorm -> quant_act_fp8 -> gate_up gemm_nt_q -> silu_mul -> quant_act_fp8 -> down gemm_nt_q
  *   -> [all_reduce] -> residual add
  *
- * THE ARCHITECTURE IS rad_block_mlp.h's AND IS DOCUMENTED THERE -- the gate/up fusion, why the
- * all-reduce is emitted by the plugin, what the residual add is for. This file is that block with
- * two ops added and two changed, and it repeats none of it: a second copy of the prose is a second
- * thing to keep true.
+ * rad_block_mlp.h documents the architecture. Differences:
  *
- * What differs, and only this:
+ *   - Both projections are LinearFP8 (rad_fp8.h): an E4M3 weight with a bf16 [N/128][K/128]
+ *     scale plane, through `gemm_nt_q` at dtype fp8a8.
+ *   - Each takes an E4M3 activation quantised every step (the checkpoint's `activation_scheme`
+ *     is `dynamic`, so no activation scale is stored).
+ *   - Activations between ops stay bf16, so `Geom::dtype` stays "bf16" and every other op
+ *     resolves as in the bf16 block.
  *
- *   - the two projections are LinearFP8 (rad_fp8.h): an E4M3 weight, a bf16 [N/128][K/128] scale
- *     plane declared as a weight of its own, and `gemm_nt_q` at dtype fp8a8 instead of `gemm_nt`.
- *   - each of them is preceded by a `quant_act_fp8` over its input, because an fp8a8 GEMM takes an
- *     E4M3 activation and the checkpoint's `activation_scheme` is `dynamic` -- there is no
- *     activation scale on disk and one is computed every step.
- *   - the norm, the activation and the collective are UNCHANGED. Activations between ops are still
- *     bf16; only the two GEMM operands are narrow. So `Geom::dtype` stays "bf16" for this block and
- *     every op in it but the two linears resolves exactly as it does in the bf16 plugin.
- *
- * The gate/up fusion survives the format, which is not obvious and is the reason it is kept: the
- * two sources are [17408,5120] each and their scale planes [136,40] each, and concatenating both
- * along dim 0 gives [34816,5120] against [272,40] -- which is the grid, because 34816/128 is 272.
- * A fusion whose parts were not whole multiples of 128 rows would silently misalign every scale
- * after the seam.
+ * The gate/up fusion survives the format because each part is a whole number of 128-row blocks:
+ * two [17408, 5120] sources with [136, 40] scale planes concatenate to [34816, 5120] and
+ * [272, 40]. Parts not on a 128-row boundary would misalign every scale after the seam.
  */
 #ifndef RAD_BLOCK_MLP_FP8_H
 #define RAD_BLOCK_MLP_FP8_H
@@ -41,9 +32,8 @@ struct MlpFP8 {
         ActFP8  ffn{};         /* [max_tok, n_ff] */
     };
 
-    /* The checkpoint side. `gate`, `up` and `down` name the `.weight` tensors; a block-fp8
-     * checkpoint's scale planes sit beside them and the checkpoint reader pairs them, so a caller
-     * cannot spell one of the pair and forget the other. */
+    /* Checkpoint names. `gate`, `up` and `down` name the `.weight` tensors; the checkpoint reader
+     * pairs each with its scale plane. */
     struct Src {
         const char* norm  = nullptr;
         const char* gate  = nullptr;
@@ -60,37 +50,25 @@ struct MlpFP8 {
     NormQuantFP8 nq_h{};
     GateQuantFP8 gq_ffn{};
     rad_op     op_ar = 0, op_add = 0;
-    /* ...AND THE gate_up PROJECTION WITH THE GATE AND THE QUANTISER IN ITS EPILOGUE.
-     *
-     * `gq_ffn`'s only input is `gate_up`'s only output. Unfused it is one of the larger remaining
-     * items in a decode step, and roughly half of that is the launch and half the second pass over
-     * a [M, 2*n_ff] bf16 tensor the GEMM's transposing store had just scattered. Folded, that
-     * tensor is never written at all.
-     *
-     * DECLARED BESIDE THE PAIR AND NOT INSTEAD OF IT, exactly as LinearFP8's matvec is: the fold
-     * is the narrow tile's epilogue and serves M <= 64, so a prefill chunk takes the pair. The two
-     * are byte-identical -- r4d_selftest holds them to it, and ref_test holds the reference to
-     * the same claim -- so this is two spellings of one arithmetic and not two answers. */
+    /* gate_up with the gate and quantiser in its epilogue, so the [M, 2*n_ff] bf16 product is
+     * never written (unfused, the extra launch and second pass are a sizeable decode cost).
+     * Declared beside the pair, not instead of it: the fold is the narrow tile's epilogue and
+     * serves M <= 64, so prefill chunks take the pair. Byte-identical, as r4d_selftest and
+     * ref_test check. */
     rad_op     op_gated = 0;
     int64_t    gated_rows = 0;
-    /* ...AND WHETHER THE COLLECTIVE AT THE END OF THIS BLOCK IS THE NEXT BLOCK'S FIRST PASS.
-     * `ar_in` says this block's own norm absorbs its PREDECESSOR's all-reduce; `ar_out` says the
-     * block after it absorbs THIS one's, so this one must not issue it. They are the residual
-     * fold's two flags again, one boundary later, and they are separate for the same reason: a
-     * block is declared without knowing what follows it. On EITHER wire -- the fused kernel
-     * carries both payloads -- and both sides ask ar_fused_ok(g, T), so the two cannot disagree
-     * about whether the collective has already been issued. */
+    /* The next block absorbs this block's closing all-reduce, so this one must not issue it.
+     * Counterpart of `ar_in`; both sides ask ar_fused_ok(g, T), so they agree. */
     bool ar_out = false;
 
-
-    /* `fold` says this block has a PREDECESSOR whose delta is still in `w.h.x`, so its norm does
-     * the residual add that block would otherwise have issued. False for the first block of a
-     * chain, whose residual stream comes straight from the embedding. See rad_fp8.h. */
+    /* `fold`: a predecessor's delta is still in `w.h.x` and this norm does its residual add
+     * (false for the first block of a chain). `add_out`: issue the trailing add here. See
+     * rad_fp8.h. */
     int  declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
                  const Src& src, bool fold = false, bool add_out = true,
                  int ar_in = kArNone, bool ar_out_ = false);
     void step(RadCtx* c, const RadBatch* batch) const;
-    /* The block over the first `T` rows of its buffers (MoeFP8::step_rows says who asks). */
+    /* The block over the first `T` rows of its buffers (see MoeFP8::step_rows). */
     void step_rows(RadCtx* c, int64_t T) const { slice(c, T, 0, T); }
     /* One row slice of the whole block; `rows <= 0` means the rest of the step. */
     void slice(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const;
@@ -106,41 +84,29 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
     w_norm = decl_w(b, nm.f("blk.%d.ffn_norm.weight", l), RAD_F32, {g.n_embd},
                     RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
 
-    /* THE NORM, THE QUANTISER AND THE RESIDUAL ADD ARE ONE OP, and rad_fp8.h's NormQuantFP8 says
-     * why: both were a launch and a second pass over a row this kernel already had in registers.
-     * Folded, the norm reads the PREVIOUS block's delta out of the shared `h` buffer and adds it
-     * into the stream; unfolded it reads the stream directly and the block ends with its own add. */
+    /* Norm, quantise and residual add in one op (rad_fp8.h: NormQuantFP8). Folded, it adds the
+     * previous block's delta from `h` into the stream; unfolded it reads the stream directly. */
     RAD_ARCH_TRY(nq_h.declare(b, g, w_norm, fold ? w.h.x : w.x, w.h, g.n_embd, fold ? w.x : 0,
                               0, ar_in));
     RAD_ARCH_TRY(gate_up.declare(b, nm, g, nm.f("blk.%d.ffn_gate_up", l),
                                  2 * g.n_ff, g.n_embd, RAD_SHARD_ROW, grp_layer(l),
                                  { src.gate, src.up }, w.h, w.gate_up, 0, { g.n_ff, g.n_ff }));
 
-    /* THE bf16 SILU PRODUCT IS WRITTEN ONLY FOR A READER: a down projection that reads the bf16
-     * plane (LinearFP8::reads_x). A block-fp8 down_proj takes the codes and their scale alone. */
+    /* The bf16 silu product is written only if the down projection reads the bf16 plane
+     * (LinearFP8::reads_x); a block-fp8 down_proj reads only codes and scales. */
     const char* down_base = nm.f("blk.%d.ffn_down", l);
     RAD_ARCH_TRY(down.probe(b, nm, g, down_base, { src.down }));
     RAD_ARCH_TRY(gq_ffn.declare(b, g, w.gate_up, w.ffn, g.n_ff, "silu", 0, down.reads_x));
 
-    /* The fold, over the same weights and into the same activation the pair writes. Not
-     * RAD_ARCH_TRY: a plugin without the row is the ordinary case and the pair still runs. It
-     * multiplies fp8 codes by a block-fp8 gate_up, so a plain gate_up has no fold -- and neither
-     * has an MXFP4 one: libr4d's gated fold is an fp8a8 tile, and the pair serves it (a rotated 5-bit one neither). */
-    {
-        const int64_t hi = g.max_tok < 64 ? g.max_tok : 64;
-        if (hi > 0 && !gate_up.bf16 && !gate_up.mx && !gate_up.paro5) {
-            op_gated = rw(b, RAD_OP(b, "gemm_nt_q_gated",
-                             RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", gate_up.N),
-                                        RAD_INT("K", gate_up.K),
-                                        RAD_INT("group", RAD_FP8_BLOCK),
-                                        RAD_STR("dtype", "fp8a8"), RAD_STR("act", "silu")),
-                             RAD_WEIGHTS(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 });
-            if (op_gated) gated_rows = hi;
-        }
-    }
+    /* The fold (decl_gated_fold), an fp8a8 tile, so bf16, MXFP4 and rotated 5-bit gate_up weights
+     * take the pair. */
+    if (!gate_up.bf16 && !gate_up.mx && !gate_up.paro5)
+        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);
     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));
@@ -154,7 +120,7 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
                        RAD_NOWEIGHTS),
                    {w.h.x}, {w.h.x});
 
-    /* Only where the NEXT block's norm will not do it; see rad_fp8.h's NormQuantFP8. */
+    /* Only when the next block's norm will not add (rad_fp8.h: NormQuantFP8). */
     if (add_out)
         op_add = rw(b, RAD_OP(b, "add",
                         RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
@@ -165,14 +131,11 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
     return RAD_OK;
 }
 
-/* ONE ROW SLICE OF THE BLOCK. `rows` defaults to the whole step, and at r0 = 0 with rows = T every
- * operand is byte-for-byte the one the unsliced form built -- `brow_slice` at offset 0 is `brows`.
- *
- * Every op here is per row: the norm and the quantiser group along K within a row, the GEMMs give
- * each output row its own accumulation, and the fused all-reduce closes every reduction over one
- * row (r4d_ar.cpp says so where it caps the block count). So a slice computes exactly the rows it
- * names and nothing about the arithmetic depends on how the chunk was cut -- PROVIDED the cut
- * obeys the band rule in core/runtime/ctx.h. */
+/* One row slice of the block; r0 = 0, rows = T is the whole step (`brow_slice` at offset 0 is
+ * `brows`). Every op is per row: the norm and quantiser group along K within a row, the GEMMs
+ * accumulate each output row independently, and the fused all-reduce reduces within a row
+ * (r4d_ar.cpp). So results do not depend on the cut, provided it obeys the band rule in
+ * core/runtime/ctx.h. */
 inline void MlpFP8::slice(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const {
     if (rows <= 0) rows = T - r0;
     nq_h.step(c, T, r0, rows);
diff --git a/arch/common/rad_block_moe_fp8.h b/arch/common/rad_block_moe_fp8.h
index 1d1efa1e..240b82ba 100644
--- a/arch/common/rad_block_moe_fp8.h
+++ b/arch/common/rad_block_moe_fp8.h
@@ -1,4 +1,4 @@
-/* rad_block_moe_fp8.h -- the ROUTED feed-forward block with block-scaled FP8 experts.
+/* rad_block_moe_fp8.h -- the routed feed-forward block with block-scaled FP8 experts.
  *
  *   rmsnorm -> quant_act_fp8 -> router gemm -> router_topk -> moe_scatter
  *                            -> gate_up moe_gemm_q -> silu_mul + quant -> down moe_gemm_q
@@ -6,54 +6,43 @@
  *                            -> [shared expert: gate_up -> silu_mul + quant -> down -> gate]
  *                            -> add -> [all_reduce] -> residual add
  *
- * IT IS rad_block_mlp_fp8.h WITH THE FEED-FORWARD ROUTED, and everything that block's header
- * argues -- why the gate/up fusion survives block scaling, why the norm and the residual add and
- * the collective are one op, why the activations between ops stay bf16 -- is argued there and not
- * repeated. What follows is only what routing changes.
+ * rad_block_mlp_fp8.h with the feed-forward routed; that header covers the gate/up fusion, the
+ * fused norm/residual/collective and the bf16 activations. This one covers what routing changes.
  *
- * ============================== THE SHARED EXPERT IS NOT OPTIONAL HERE ==============================
+ * ============================== THE SHARED EXPERT ==============================
  *
- * Qwen3.5-MoE runs a dense expert BESIDE the routed ones on every token, gated by a one-output
- * projection: `y = routed(x) + sigmoid(shared_gate(x)) * shared(x)`. It is `mlp.shared_expert.*`
- * and `mlp.shared_expert_gate.weight` in the checkpoint, and a block that dropped it would produce
- * a plausible distribution and the wrong model. `moe_gather` does the multiply as it sums the
- * routed slots -- see docs/OPS.md's `scale_rows` for why `mul` cannot do it, and note that the
- * gate is applied to the SCALAR before the multiply, not to the product.
+ * Qwen3.5-MoE runs a dense expert beside the routed ones on every token, gated by a one-output
+ * projection: `y = routed(x) + sigmoid(shared_gate(x)) * shared(x)` (`mlp.shared_expert.*` and
+ * `mlp.shared_expert_gate.weight`). `moe_gather` applies the gate to the scalar and multiplies as
+ * it sums the routed slots (docs/OPS.md's `scale_rows` says why `mul` cannot). A family without
+ * one passes `Src::shared` null and the arm, buffers included, is not declared.
  *
- * A family without one passes `Src::shared` null and the whole arm disappears, buffers included.
+ * ============================== ROW SLICING ==============================
  *
- * ============================== WHY THE BLOCK SLICES ITS ROWS ==============================
+ * The expert intermediates are `top_k` times as tall as the step: at an 8192-token chunk and
+ * top_k 8 the down projection's input is 65536 rows, 256 MiB at n_embd 2048. So the block runs in
+ * passes of at most `Config::rows` tokens and declares those buffers at that height. Routing is
+ * per pass (`expert_offset` and `sorted_tok` describe one pass), which is exact because a token's
+ * routing depends only on that token.
  *
- * The expert path's intermediates are `top_k` times as tall as the step: at an 8192-token chunk and
- * top_k 8 the down-projection's input alone is 65536 rows, which at n_embd 2048 is 256 MiB of
- * transient for ONE buffer. So the block runs in passes of at most `Config::rows` tokens and its
- * buffers are declared at that height. Routing is per pass and has to be -- `expert_offset` and
- * `sorted_tok` describe the rows of one pass -- which is not an approximation: a token's routing
- * depends on that token alone, so a pass computes exactly the rows it names.
+ * The default is 2048, the prefill chunk: core/sched/geometry.cpp clamps the chunk to the
+ * linear-state checkpoint interval (2048 on this family), so the shipped configuration is one
+ * pass. Slicing serves deployments with a larger chunk.
  *
- * THE DEFAULT IS 2048 AND THAT IS THE CHUNK, not a tuning choice: core/sched/geometry.cpp clamps
- * the prefill chunk to the linear-state checkpoint interval, which on this family is 2048, so the
- * shipped configuration is one pass and the slicing is inert. It exists so that a deployment with a
- * larger chunk does not need this file edited.
+ * ============================== EXPERT WEIGHT RUNS ==============================
  *
- * ============================== THE EXPERT WEIGHTS ARE EIGHT RUNS ==============================
+ * `moe_gemm_q` takes weights as tables (RAD_OPD_WTAB): a run of consecutively declared handles,
+ * `RAD_WTAB(first, n)`. Each projection's experts are two tables by parity, because all entries of
+ * a table share one geometry and a rank holding an uneven slice of each expert has two (see
+ * Config::ff_lo). So the arrays are declared in separate loops (gate_up codes, gate_up scales,
+ * down codes, down scales, each even then odd), never grouped per expert, which would give strided
+ * runs the operand cannot express. When four ranks split every expert there are four classes by
+ * number mod 4 (`moe_gemm_q_mod4`, Config::ff_lo4), declared the same way class by class.
  *
- * `moe_gemm_q` takes its weights as TABLES (RAD_OPD_WTAB), and a table is a run of CONSECUTIVELY
- * DECLARED handles -- `RAD_WTAB(first, n)` names the first and the count. It takes each
- * projection's experts as TWO tables by parity, the even experts and the odd ones, because every
- * entry of a table has one geometry and a rank holding an uneven slice of each expert has two (see
- * Config::ff_lo). So the arrays are declared in separate loops -- gate_up codes, gate_up scales,
- * down codes, down scales, each for the even experts and then the odd ones -- and NOT as a group
- * per expert. Interleaving them would give runs of stride two or four, which the operand cannot
- * express; the failure would be a table whose second entry is a scale plane. Where four ranks split
- * every expert the classes are four, by number mod 4 (`moe_gemm_q_mod4`, Config::ff_lo4), and the
- * runs sixteen, declared the same way class by class.
- *
- * The codes run and the scale run of a projection are two VIEWS of one stored weight -- its codes
- * plane and its scale plane (RadWeightDecl::source) -- so an expert holds two logical weights,
- * gate_up and down, and is its own movement unit (`grp_expert_slot`, slots 0 and 1) and
- * RAD_ACCESS_CONDITIONAL, which is what lets the placement planner tier them and the heat engine
- * promote the hot ones.
+ * A projection's codes run and scale run are two views of one stored weight
+ * (RadWeightDecl::source). Each expert holds two logical weights, gate_up and down, and is its own
+ * movement unit (`grp_expert_slot`, slots 0 and 1) with RAD_ACCESS_CONDITIONAL, so the placement
+ * planner can tier experts and the heat engine can promote hot ones.
  */
 #ifndef RAD_BLOCK_MOE_FP8_H
 #define RAD_BLOCK_MOE_FP8_H
@@ -70,32 +59,25 @@
 namespace rad {
 namespace arch {
 
-/* THE MOST ROUTING SLOTS THE SORT SERVES IN ONE WORKGROUP, which is what bounds
- * `router_topk_scatter`. It is libr4d's `kScatterSmall` and it is stated here rather than asked
- * of the plugin for the reason every other such bound in this library is: the architecture has to
- * decide, at declare time and identically on both ranks, whether the op exists at all. */
+/* Most routing slots the sort serves in one workgroup, bounding `router_topk_scatter` (libr4d's
+ * `kScatterSmall`). Fixed here so every rank decides identically at declare whether the op
+ * exists. */
 static const int64_t kMoeSortRows = 1024;
 
-/* The skinny bf16 GEMM's decode band, which is where the fused op's GEMM is that GEMM's own
- * arithmetic; past it the router runs the tiled kernel and the pair is issued as before. */
+/* The skinny bf16 GEMM's decode band, within which the fused router op reproduces that GEMM's
+ * arithmetic; above it the router uses the tiled kernel and the unfused pair. */
 static const int64_t kMoeRouterFusedRows = 64;
 
-
-
-/* ---- RADIANCE_DEBUG_ROUTING: the routing WEIGHTS of token 0, which nothing else reports.
+/* ---- RADIANCE_DEBUG_ROUTING: prints token 0's routing weights once per layer.
  *
- * The core's histogram (core/runtime/ctx.cpp) says which experts a step chose and rad_arch.h's
- * dbg_resid says how big each arm's contribution was; neither shows the weights themselves, and a
- * router whose top-k sums to 0.4 instead of 1 is a block that is right in every other respect and
- * scaled down by more than half. It SYNCHRONISES THE STREAM and is off unless the variable is set:
- * a layer number, or negative for every layer. */
+ * The core's histogram (core/runtime/ctx.cpp) shows which experts were chosen and dbg_resid shows
+ * each arm's magnitude; neither shows the weights, so a top-k that sums to 0.4 instead of 1 would
+ * go unnoticed. Synchronises the stream. Off unless set: a layer number, or negative for all. */
 inline void moe_debug_weights(RadCtx* c_, int layer, int64_t top_k, rad_buf ids, rad_buf ew) {
     static const char* dbg = std::getenv("RADIANCE_DEBUG_ROUTING");
     if (!dbg || !ids || !ew) return;
-    const int want = (int)std::strtol(dbg, nullptr, 10);
-    if (want >= 0 && layer != want) return;
-    static int seen[256] = {0};
-    if (seen[layer & 255]++) return;
+    static const int want = (int)std::strtol(dbg, nullptr, 10);
+    if ((want >= 0 && layer != want) || !dbg_first(layer, "moe")) return;
 
     void* pi = rad_buf_ptr(c_, ids);
     void* pw = rad_buf_ptr(c_, ew);
@@ -122,192 +104,153 @@ inline void moe_debug_weights(RadCtx* c_, int layer, int64_t top_k, rad_buf ids,
                  layer, line.c_str(), sum);
 }
 
-/* THE MOST EXPERTS A LAYER PROTECTS ON ONE RANK (MoeFP8::prot): libr4d's sort takes at most eight
- * in its `protect` list. */
+/* Most experts a layer protects on one rank (MoeFP8::prot): libr4d's sort takes at most eight in
+ * its `protect` list. */
 constexpr int64_t kMaxProtected = 8;
 
 struct MoeFP8 {
     struct Config {
-        /* ROUTED EXPERTS THIS RANK OWNS. Equal to `n_expert_all` in every deployment that does not
-         * use expert parallelism -- every rank then holds a slice of every expert (see ff_lo). A
-         * calibration run is the one that splits the experts themselves, because a Hessian is
-         * over an expert's whole K. */
+        /* Routed experts this rank owns. Equal to `n_expert_all` unless experts are split across
+         * ranks, which only a calibration run does (a Hessian spans an expert's whole K); otherwise
+         * each rank holds a slice of every expert (see ff_lo). */
         int64_t n_expert     = 0;
-        /* THE MODEL'S expert count -- what the ROUTER is wide in and what top_k picks from. 0 means
-         * "the same as n_expert", the whole-model case.
+        /* The model's expert count: the router's width and what top_k picks from. 0 means
+         * n_expert.
          *
-         * The router stays replicated under expert parallelism and that is the property the scheme
-         * rests on: every rank scores every expert from the same residual stream and picks the
-         * same top_k, so the ranks agree on the routing without a collective. Each then sorts only
-         * the slots that landed in ITS range and the block's end-of-block all-reduce sums the
-         * partials. Sharding the router instead would have two ranks disagree about where a token
-         * went, and the all-reduce would sum two different models. */
+         * The router stays replicated under expert parallelism: every rank scores every expert from
+         * the same residual stream and picks the same top_k, so ranks agree on routing without a
+         * collective. Each sorts only the slots in its own range and the end-of-block all-reduce
+         * sums the partials. */
         int64_t n_expert_all = 0;
-        /* This rank's first expert id, in the model's numbering. Straight through to moe_scatter,
-         * which subtracts it so the offsets, the counts and the weight table are all local. */
+        /* This rank's first expert id in the model's numbering. moe_scatter subtracts it so the
+         * offsets, counts and weight table are local. */
         int64_t expert_base  = 0;
         int64_t top_k        = 0;
-        int64_t n_ff_exp     = 0;   /* one expert's intermediate width, PER RANK */
-        /* THE ROUTED EXPERTS' SLICE ON THIS RANK WHEN THEIR WIDTH DOES NOT HALVE INTO WHOLE fp8
-         * SCALE BLOCKS: expert e's intermediate columns [ff_lo[e % 2], ff_hi[e % 2]) in the model's
-         * numbering, the slice depending on the expert's PARITY. hi 0 is the even split (or no
-         * split). `n_ff_exp` is then the wider slice, which is what the buffers between the two
-         * grouped GEMMs are.
+        int64_t n_ff_exp     = 0;   /* one expert's intermediate width, per rank */
+        /* This rank's slice of each routed expert when the width does not halve into whole fp8
+         * scale blocks: expert e's intermediate columns [ff_lo[e % 2], ff_hi[e % 2]) in model
+         * numbering, by parity. hi 0 is the even split (or none). `n_ff_exp` is then the wider
+         * slice, the width of the buffers between the two grouped GEMMs.
          *
-         * WHY BY PARITY. This family's expert is 640 columns, five 128-column blocks, so two ranks
-         * split each expert three blocks and two. Giving every expert's three blocks to one rank
-         * would make that rank read 3/5 of every routed expert; alternating which rank takes three
-         * by the expert's parity makes the ranks equal on average, and unequal only by the
-         * difference between how many even and odd experts a step routes -- a fifth of an expert
-         * per unit of that difference, where splitting the EXPERTS between the ranks (expert
-         * parallelism) is unequal by whole experts, the binomial spread of which rank the routed
-         * experts land on. The block's all-reduce turns that spread into the faster rank waiting,
-         * about a millisecond a step at one sequence.
+         * This family's expert is 640 columns (five 128-blocks), so two ranks split each expert
+         * three blocks and two. Alternating by parity balances the ranks on average; the imbalance
+         * is a fifth of an expert per unit of even/odd difference, versus whole experts under
+         * expert parallelism, which the all-reduce turns into waiting (about 1 ms a step at one
+         * sequence).
          *
-         * Every rank computes its slice of every routed expert: its gate/up rows and its K slice of
-         * down, and the all-reduce sums the partials -- the routing weight multiplies each partial,
-         * and the sum of the partials is the expert's output. Rounding moves (two partial sums
-         * where there was one), so this is checked by agreement rather than byte for byte. */
+         * Each rank computes its gate/up rows and its K slice of down for every routed expert; the
+         * routing weight scales each partial and the all-reduce sums them. Rounding differs (two
+         * partial sums), so this is checked by agreement, not bytes. */
         int64_t ff_lo[2] = { 0, 0 }, ff_hi[2] = { 0, 0 };
-        /* OR BY THE EXPERT'S NUMBER MOD 4, where four ranks split it: expert e's columns
-         * [ff_lo4[e % 4], ff_hi4[e % 4]), served by `moe_gemm_q_mod4`, and taking precedence over
-         * the parity slices. hi 0 offers none.
+        /* Or by number mod 4 when four ranks split each expert: expert e's columns
+         * [ff_lo4[e % 4], ff_hi4[e % 4]), served by `moe_gemm_q_mod4`, taking precedence over the
+         * parity slices. hi 0 offers none.
          *
-         * Parity gives the extra block of a five-block expert two places to go, so at four ranks
-         * two of them carry three blocks of every even/odd pair and two carry two -- and the
-         * block's all-reduce has the narrow ranks wait for the wide ones. Four classes give it
-         * four: each rank takes two blocks of one class and one of each other, five of every four
-         * experts. Any count of quantised experts serves: a layer that keeps two plain bf16 has
-         * 510, and its first two classes hold one expert more than the last two (the declaration
-         * gives a table op's first tables the remainder). `n_ff_exp` is the widest slice. "e" is
-         * the expert's place in the sort, as for the parity classes. */
+         * By parity at four ranks, two ranks would carry three blocks of every even/odd pair and
+         * two would carry two. With four classes each rank takes two blocks of one class and one of
+         * each other: five per four experts. Any expert count works; with 510 quantised experts
+         * (two kept bf16) the first two classes hold one more (the first tables of a table op take
+         * the remainder). `n_ff_exp` is the widest slice; "e" is the expert's place in the sort. */
         int64_t ff_lo4[4] = { 0, 0, 0, 0 }, ff_hi4[4] = { 0, 0, 0, 0 };
         int64_t n_ff_shared  = 0;   /* the shared expert's, per rank; 0 = no shared expert */
-        /* THE SHARED ARM'S SLICE ON THIS RANK, when its width does not halve into whole fp8 scale
-         * blocks: [shared_lo, shared_hi) of its columns in the model's numbering, with
-         * `n_ff_shared` then the slice's width. hi 0 is the even split (or no split at world 1);
-         * an empty slice declares no arm on this rank.
+        /* The shared arm's slice on this rank when its width does not halve into whole fp8 scale
+         * blocks: columns [shared_lo, shared_hi) in model numbering, `n_ff_shared` its width. hi 0
+         * is the even split (or none at world 1); an empty slice declares no arm on this rank.
          *
-         * WHY A SLICE AND NOT ONE RANK. This family's shared expert is 640 columns, five
-         * 128-column blocks, so two ranks cannot halve it -- and computing it on one rank alone
-         * makes the ranks unequal at every routed layer, which the block's all-reduce turns into
-         * the other rank waiting: about 20 us a layer at one sequence, which costs far more than
-         * the arm's own bytes. Slicing it three blocks and two puts both ranks within one block of
-         * each other: each computes its columns of the gate/up product, its own K slice of the
-         * down projection, scales that partial by the replicated gate, and the all-reduce sums the
-         * partials -- `sgate * (down_0 + down_1)` is the arm, since the gate is a per-token
-         * scalar. Rounding moves (two partial sums where there was one), so this is checked
-         * against the unsplit arm by agreement rather than byte for byte.
+         * The 640-column shared expert is split three blocks and two rather than run on one rank,
+         * which would leave the other waiting at the all-reduce (about 20 us a layer at one
+         * sequence). Each rank computes its gate/up columns and K slice of down, scales the partial
+         * by the replicated per-token gate, and the all-reduce sums them:
+         * `sgate * (down_0 + down_1)`. Checked by agreement, not bytes.
          *
-         * The arm's stages run behind the routed ones on the same queue (see pass()): a routed
-         * GEMM's tail leaves compute units idle, and the arm fills them. */
+         * The arm runs behind the routed stages on the same queue (see pass()), filling compute
+         * units a routed GEMM's tail leaves idle. */
         int64_t shared_lo = 0, shared_hi = 0;
         int     norm_topk    = 1;   /* renormalise the kept routing weights to sum to one */
-        /* THE EXPERT WEIGHT AT FOUR BITS rather than E4M3, which for Qwen3.8-Flash-Next is the
-         * difference between a model that fits two cards and one that does not (the registry row
-         * for `moe_gemm_w4a8` carries the placement report that says so). It is the STORED
-         * encoding of the experts -- `i4*bf16[1x128]` against `fp8_e4m3*bf16[128x128]` -- so it is
-         * not a choice made here: probe() reads it off the first expert's encoding, which is the
-         * container's, the checkpoint's, or the recipe rad-convert is applying, and declare()
-         * refuses an expert whose encoding is not the one probed.
+        /* 4-bit experts (`i4*bf16[1x128]`) rather than E4M3 (`fp8_e4m3*bf16[128x128]`); for
+         * Qwen3.8-Flash-Next this decides whether the model fits two cards (see the `moe_gemm_w4a8`
+         * registry row). It is the stored encoding: probe() reads it from the first expert's
+         * encoding (container, checkpoint or rad-convert recipe) and declare() refuses an expert
+         * whose encoding differs.
          *
-         * A packed 4-bit row is K/2 bytes, so a width shard has to fall on a scale group; the
-         * per-rank checks in declare() say so by name. */
+         * A packed 4-bit row is K/2 bytes, so a width shard must fall on a scale group; declare()
+         * checks this per rank. */
         int     expert_w4    = 0;
-        /* AND ROTATED: a 128-wide Walsh-Hadamard along K baked into the stored expert weight and
-         * into the activation that meets it -- the encoding's `fwht128` transform, read off it as
-         * `expert_w4` is, and only meaningful with it (dtype `w4a8h`).
+        /* Rotated: a 128-wide Walsh-Hadamard along K baked into the stored expert weight and the
+         * activation meeting it (the encoding's `fwht128` transform, dtype `w4a8h`; only with
+         * `expert_w4`).
          *
-         * WHAT IT COSTS AT RUNTIME, stated because it is the part that is easy to miss. The
-         * rotation itself is free: it rides in the quantiser's registers on a launch already
-         * being paid. The DOWN projection is free outright -- its input comes from this block's
-         * own gated quantiser, which nothing else reads, so that op simply becomes the rotated
-         * one. The GATE_UP projection is not: its input is the block's normed activation, which
-         * the SHARED expert also reads at fp8 and which must therefore stay unrotated, so a
-         * second (q, scale) pair and one extra `had_quant_act_fp8` launch a layer are the price
-         * of keeping the shared arm byte-identical.
+         * Runtime cost: the rotation rides in the quantiser's registers. The down projection's
+         * input comes from this block's own gated quantiser, which simply becomes the rotated one.
+         * The gate_up input is the normed activation, which the shared expert also reads and which
+         * must stay unrotated, so it costs a second (q, scale) pair and one `had_quant_act_fp8`
+         * launch per layer.
          *
-         * ON ITS OWN A ROTATION IS WORSE FOR ROUNDING: it fixes RANGE, and group-128 absmax
-         * already handles range -- 2x worse for RTN int4 on the 27B. It is the basis GPTQ's error
-         * feedback quantises in, and the pair is what the served container carries. */
+         * Alone, rotation is worse for round-to-nearest (2x for RTN int4 on the 27B; group-128
+         * absmax already handles range). It is the basis GPTQ's error feedback quantises in. */
         int     expert_rot   = 0;
-        /* AND A CODEBOOK: the rotated codes index a sixteen-entry `table` plane -- libquant's
-         * `table=w4nl`, non-uniform levels fitted to the rotated weights -- rather than standing
-         * for -8..7 (dtype `w4nla8h`). Only with `expert_rot`, which it implies; the scale grid,
-         * the activation and the GEMM are the rotated form's, and the codes view selects the table
-         * beside the codes so the kernel's relayout can check it is the table it decodes. */
+        /* Codebook: the rotated codes index a sixteen-entry `table` plane (libquant's
+         * `table=w4nl`, non-uniform levels) instead of -8..7 (dtype `w4nla8h`). Only with
+         * `expert_rot`. The codes view selects the table beside the codes so the kernel's relayout
+         * can check it. */
         int     expert_nl    = 0;
-        /* AND ITS SCALES A 64 OF K: one E4M3 byte under a fixed 2^-13 (dtype `w4nl64a8h`, libr4d's
-         * kW4G64Scale) where the codebook form has one bf16 a 128 -- the same bytes. Only with
-         * `expert_nl`. The scale views select the fixed second level beside the scales, which the
-         * relayout checks is the kernel's constant. 2 for a 64, 4 for a 32 (`w4nl32a8h`, twice
-         * the scale bytes): the scale groups a 128 of K. */
+        /* Scales per 64 of K: one E4M3 byte under a fixed 2^-13 (dtype `w4nl64a8h`, libr4d's
+         * kW4G64Scale), the same bytes as one bf16 per 128. Only with `expert_nl`. The scale views
+         * select the fixed second level, which the relayout checks against the kernel's constant.
+         * The value is scale groups per 128 of K: 2 for 64, 4 for 32 (`w4nl32a8h`). */
         int     expert_g64   = 0;
-        /* AND ITS CODES FIVE BITS: libquant's 32-level `table=w5nl` at w4nl64a8h's scales (dtype
-         * `w5nl64a8h`), the sign of each code its high bit. Only with `expert_g64` 2. This is the
-         * PROBED layer's; the 64-group codebook forms may differ by layer and by projection, and
-         * declare() resolves each layer's two (MoeFP8::fmt). */
+        /* 5-bit codes: libquant's 32-level `table=w5nl` at w4nl64a8h's scales (dtype
+         * `w5nl64a8h`), sign in the high bit. Only with `expert_g64` 2. This is the probed
+         * layer's; the 64-group codebook forms may differ by layer and projection, and declare()
+         * resolves each layer's (MoeFP8::fmt). */
         int     expert_w5    = 0;
-        /* PLAIN bf16 -- the checkpoint's own experts, converted without a quantising recipe. Both
-         * GEMMs are then `moe_gemm` over one table of whole experts and the bf16 activation, with
-         * `silu_mul` between them, and the shared arm follows the trunk (Geom::w_bf16). An expert
-         * cannot be sliced by parity here -- a bf16 expert is served whole on its rank, which is
-         * also what keeps it one run of the container for the file tier. */
+        /* Plain bf16 experts (no quantising recipe). Both GEMMs are `moe_gemm` over one table of
+         * whole experts with `silu_mul` between, and the shared arm follows the trunk
+         * (Geom::w_bf16). Not sliced by parity: each expert is served whole on its rank, which
+         * also keeps it one container run for the file tier. */
         int     expert_bf16  = 0;
-        /* The layer and the GLOBAL expert whose gate_up probe() read the format from and therefore
-         * mapped; declare() maps every other. -1 for the layer: none. */
+        /* The layer and global expert whose gate_up probe() read the format from (and so mapped);
+         * declare() maps the rest. Layer -1: none. */
         int64_t probed_layer = -1;
         int64_t probed_expert = 0;
-        /* How many experts from `probed_expert` on probe() mapped: it reads past experts a
-         * quantised layer keeps plain bf16 (see `prot`) to the first one in the layer's format. */
+        /* Experts from `probed_expert` on that probe() mapped: it skips experts a quantised layer
+         * keeps bf16 (see `prot`) to reach the first in the layer's format. */
         int64_t probed_count = 1;
-        /* THE GPTQ CALIBRATION TAP. On, this block declares an f32 [K, K] PERSIST accumulator for
-         * each of its two expert projections and a `gram_accum` into it, running until
-         * RADIANCE_CALIB_TOKENS tokens have passed and then writing the pair to
-         * RADIANCE_CALIB_DIR and switching itself off.
+        /* The GPTQ calibration tap (rad_arch.h). On, the block declares an f32 [K, K] PERSIST
+         * accumulator and a `gram_accum` for each expert projection, runs until
+         * RADIANCE_CALIB_TOKENS tokens, writes them to RADIANCE_CALIB_DIR and switches off.
          *
-         * IT IS A SEPARATE RUN AND NOT A SERVING MODE. The accumulators are 1.34 GB across 48
-         * layers at this model's widths, the dump synchronises the stream, and the two extra
-         * launches a layer are pure overhead once the corpus is in. Nothing reads the files at
-         * serve time -- rad-convert does, in another process, to pack the next container.
+         * A separate run, not a serving mode: the accumulators are 1.34 GB over 48 layers at this
+         * model's widths and the dump synchronises the stream. rad-convert reads the files.
          *
-         * IT TAPS THE QUANTISER'S OUTPUT, not the bf16 before it, and that is deliberate: the
-         * Hessian GPTQ wants is of the operand the expert GEMM actually contracts. Under
-         * `expert_rot` that operand is rotated, so the Hessian is in rotated coordinates -- which
-         * is the same basis the packer quantises in, and the only basis in which the two agree. */
+         * It taps the quantiser's output, the operand the expert GEMM contracts; under
+         * `expert_rot` that is rotated, the same basis the packer quantises in. */
         int     calib        = 0;
         int64_t rows         = 0;   /* tokens per pass; 0 means the whole step */
     };
 
-    /* WHICH BUFFERS ARE A PASS TALL AND WHICH ARE THE STEP'S, and the division is the whole of what
-     * the slicing costs in bookkeeping. Only the four planes that carry one row per (token, slot)
-     * are a pass tall -- they are `top_k` times the step and they are what the slicing exists to
-     * bound. Everything else is one row per TOKEN, is a few megabytes at any chunk, and is sized
-     * at max_tok and sliced by the pass offset like every other activation in this tree.
-     *
-     * That is not a size optimisation, it is what keeps the pass offset expressible: LinearFP8 and
-     * GateQuantFP8 slice their INPUT and their OUTPUT with the same `r0`, so a shared expert whose
-     * output buffer were a pass tall would be written past its end on the second pass. The shipped
-     * chunk is one pass, so that overrun would show no symptom there. */
+    /* Only the four planes with one row per (token, slot) are a pass tall; everything else has one
+     * row per token, is sized at max_tok and sliced by the pass offset. This is required, not an
+     * optimisation: LinearFP8 and GateQuantFP8 slice input and output with the same `r0`, so a
+     * pass-tall shared-expert output would be overrun on the second pass. */
     struct Wire {
         rad_buf x       = 0;   /* [max_tok, n_embd]  the residual stream */
         ActFP8  h{};           /* [max_tok, n_embd]  normed input, then the block's delta */
-        /* THE ROTATED CODES OF THE SAME INPUT, and only `q` and `s` of it are used -- `x` is
-         * `h`'s. Declared only when `expert_rot` is set; the routed gate_up reads this pair and
-         * the shared expert goes on reading `h`'s. */
+        /* Rotated codes of the same input (only `q` and `s`; `x` is `h`'s). Declared only with
+         * `expert_rot`: the routed gate_up reads them, the shared expert reads `h`'s. */
         ActFP8  hr{};          /* [max_tok, n_embd]  q + scale only */
-        /* the routing -- one row per TOKEN, so the step's height */
-        rad_buf logits  = 0;   /* [max_tok, n_expert_all] bf16 -- the MODEL's expert count */
+        /* the routing, one row per token */
+        rad_buf logits  = 0;   /* [max_tok, n_expert_all] bf16, the model's expert count */
         rad_buf ids     = 0;   /* [max_tok, top_k]      i32 */
         rad_buf ew      = 0;   /* [max_tok, top_k]      bf16 */
         rad_buf eoff    = 0;   /* [n_expert + 1]        i32 */
         rad_buf ecnt    = 0;   /* [n_expert]            i32 */
-        /* the expert planes -- one row per (token, slot), so a PASS's height */
+        /* the expert planes, one row per (token, slot), a pass tall */
         rad_buf sorted  = 0;   /* [rows * top_k]               i32, pass-relative slot indices */
         rad_buf egu     = 0;   /* [rows * top_k, 2 * n_ff_exp] bf16 */
         ActFP8  eff{};         /* [rows * top_k, n_ff_exp] */
-        rad_buf edn     = 0;   /* [rows * top_k, n_embd]       bf16, in SORTED order */
-        /* back in token order, and the shared expert beside it: the step's height again */
+        rad_buf edn     = 0;   /* [rows * top_k, n_embd]       bf16, in sorted order */
+        /* back in token order, and the shared expert, one row per token */
         rad_buf moe     = 0;   /* [max_tok, n_embd]           bf16 */
         rad_buf sgu     = 0;   /* [max_tok, 2 * n_ff_shared]  bf16 */
         ActFP8  sff{};         /* [max_tok, n_ff_shared] */
@@ -315,31 +258,24 @@ struct MoeFP8 {
         rad_buf sgate   = 0;   /* [max_tok, 1]                bf16 */
     };
 
-    /* The checkpoint side. `experts` is a PREFIX -- "....mlp.experts" -- and the per-expert names
-     * are built from it, because a caller cannot pass 256 of them and a format string with the
-     * expert in it is a convention this file would have to parse. `shared` is the same for the
-     * dense expert beside them; null means the family has none, and `shared_gate` must then be
-     * null too.
+    /* Checkpoint names. `experts` is a prefix ("....mlp.experts") from which per-expert names are
+     * built; `shared` likewise for the dense expert, null when the family has none (then
+     * `shared_gate` must be null too).
      *
-     * THE CONFIG TRAVELS IN HERE rather than as an argument to declare, and that is not tidiness:
-     * it makes this block's declare() arity IDENTICAL to MlpFP8's, which is what lets MtpBlockFP8
-     * be a template over the two. A routed feed-forward and a dense one are the same thing in the
-     * same position of the same graph, and the only component that should know the difference is
-     * the plugin that picks one. */
+     * The config travels here, not as a declare() argument, so declare() has the same signature
+     * as MlpFP8's and MtpBlockFP8 can be a template over both. */
     struct Src {
         Config      cfg{};
         const char* norm        = nullptr;
         const char* router      = nullptr;   /* mlp.gate.weight, [n_expert, n_embd] bf16 */
         const char* experts     = nullptr;   /* prefix; "..{gate,up,down}_proj.weight" */
         const char* shared      = nullptr;   /* prefix; ".{gate,up,down}_proj.weight" */
-        /* A STACKED CHECKPOINT NAMES TWO TENSORS AND NOT A PREFIX, which is the shape every
-         * recent release uses: `mlp.experts.gate_up_proj` [n_expert, 2*n_ff, n_embd] and
-         * `mlp.experts.down_proj` [n_expert, n_embd, n_ff], one tensor holding every expert.
-         * Set these INSTEAD of `experts` and each declared expert maps to a dim-0 slice
-         * (rad_arch.h's map_slice; core/format/checkpoint.cpp takes the slice as a view, and a
-         * block-fp8 checkpoint's stacked `_scale_inv` plane at the same index).
-         * Note that a stacked gate_up is ALREADY FUSED in the order this block wants -- gate
-         * rows first -- so there is no concatenation left to do. */
+        /* Stacked checkpoints (recent releases) store all experts in two tensors:
+         * `mlp.experts.gate_up_proj` [n_expert, 2*n_ff, n_embd] and `mlp.experts.down_proj`
+         * [n_expert, n_embd, n_ff]. Set these instead of `experts`; each expert maps to a dim-0
+         * slice (rad_arch.h: map_slice; core/format/checkpoint.cpp takes it as a view, with a
+         * block-fp8 checkpoint's stacked `_scale_inv` at the same index). The stacked gate_up is
+         * already fused gate rows first, as this block wants. */
         const char* experts_gate_up = nullptr;
         const char* experts_down    = nullptr;
         const char* shared_gate = nullptr;   /* mlp.shared_expert_gate.weight, [1, n_embd] */
@@ -353,23 +289,22 @@ struct MoeFP8 {
     rad_weight w_norm = 0, w_router = 0, w_sgate = 0;
     /* The input was normed and quantised by the caller; this block declares no norm. */
     bool       ext_in = false;
-    /* The four runs. Only the FIRST handle and the count reach an issue (RAD_WTAB); the rest are
-     * held so that a declaration failure can be reported against the expert it happened on. */
+    /* The weight runs. Only the first handle and the count reach an issue (RAD_WTAB); the rest are
+     * kept so a declaration failure can name its expert. */
     std::vector w_gu, w_gus, w_dn, w_dns;
 
     NormQuantFP8 nq_h{};
     GateQuantFP8 gq_exp{}, gq_sh{};
     LinearFP8    sh_gate_up{}, sh_down{};
     rad_op op_router = 0, op_topk = 0, op_scatter = 0;
-    /* `router_topk_scatter`, if it resolves: the two above in one launch. 0 leaves the pair, which
-     * is declared either way -- the fused form is bounded by the sort's single-workgroup shape and
-     * a prefill chunk is past it. */
+    /* `router_topk_scatter`, if it resolves: topk and scatter in one launch. The pair is declared
+     * either way, since the fused form is bounded by the sort's single workgroup and a prefill
+     * chunk exceeds it. */
     rad_op  op_topk_scatter = 0;
     int64_t topk_scatter_rows = 0;
-    /* `router_gemm_topk_scatter`, if it resolves: the router GEMM in front of the pair above, up
-     * to `router_fused_rows` tokens, and with `router_fused_gate` the shared expert's gate
-     * (`op_sgate`'s work) as well. 0 -- the op did not resolve -- issues the router and the pair
-     * as always, and so does a pass of more rows. */
+    /* `router_gemm_topk_scatter`, if it resolves: the router GEMM fused in front, up to
+     * `router_fused_rows` tokens, plus the shared expert's gate (`op_sgate`) when
+     * `router_fused_gate`. Otherwise, or for larger passes, the separate ops run. */
     rad_op  op_router_fused = 0;
     int64_t router_fused_rows = 0;
     bool    router_fused_gate = false;
@@ -380,19 +315,18 @@ struct MoeFP8 {
      * no quantiser for it. Set before declare. */
     bool   hr_in = false;
     rad_op op_gu = 0, op_dn = 0, op_gather = 0;
-    /* THE PROTECTED EXPERTS (declare): local experts a quantised layer keeps plain bf16 -- the few
-     * whose output dwarfs the rest's (docs/MOE-W4.md). The scatter sorts them last (`protect`,
-     * `prot_list`), the quantised GEMMs above serve the other `n_reg`, and a bf16 grouped GEMM
-     * pair serves these over the trailing run of the offsets: gate_up into `b_pgu`, the gate into
-     * `pff`, and down into the same `edn` rows the quantised down left zero. */
+    /* Protected experts: local experts a quantised layer keeps bf16, the few whose output dwarfs
+     * the rest (docs/MOE-W4.md). The scatter sorts them last (`protect`, `prot_list`), the
+     * quantised GEMMs serve the other `n_reg`, and a bf16 grouped GEMM pair serves these over the
+     * trailing offsets: gate_up into `b_pgu`, the gate into `pff`, down into the `edn` rows the
+     * quantised down left zero. */
     std::vector    prot;
     const char*             prot_list = nullptr;
-    /* THE NEXT-LAYER EXPERT PREFETCH (rad_expert_prefetch). `xp_next` is the next routed layer, which
-     * this one predicts for at its router input -- the architecture links them once every layer is
-     * declared. `xp` is what this layer is to the one before it: its router, and each of the model's
-     * experts' unit -- the four handles its place's tables hold, and its place in the routing counts.
-     * Quantised experts only: a bf16 layer and the protected experts are not described, and a layer
-     * with no description is predicted for by nobody. */
+    /* Next-layer expert prefetch (rad_expert_prefetch). `xp_next` is the next routed layer, which
+     * this one predicts for from its router input; the architecture links them after declare.
+     * `xp` describes this layer to its predecessor: its router and, per model expert, the four
+     * handles its table entries hold and its place in the routing counts. Quantised experts only;
+     * a layer without a description gets no prediction. */
     const MoeFP8*           xp_next = nullptr;
     RadPrefetchNext         xp{};
     std::vector xp_parts;
@@ -401,46 +335,41 @@ struct MoeFP8 {
     /* How many weight-table classes the quantised GEMMs take: 2 by parity (`moe_gemm_q`), or 4 by
      * number mod 4 (`moe_gemm_q_mod4`, Config::ff_lo4). */
     int                     ncls = 2;
-    /* THIS LAYER'S gate_up AND down FORMATS (format_of's numbers), resolved by declare(): the
-     * probed layer's for both, except that among the codebook forms at E4M3 scales -- w4nl64a8h,
-     * w4nl32a8h, w5nl64a8h -- each projection of each layer takes its own experts'. */
+    /* This layer's gate_up and down formats (format_of's numbers), resolved by declare(): the
+     * probed layer's, except that among the codebook forms at E4M3 scales (w4nl64a8h, w4nl32a8h,
+     * w5nl64a8h) each projection of each layer takes its own experts'. */
     int                     fmt[2] = { 0, 0 };
     std::vector w_pgu, w_pdn;
     rad_buf                 b_pgu = 0;
     ActFP8                  pff{};
     GateQuantFP8            gq_prot{};
     rad_op                  op_pgu = 0, op_pdn = 0;
-    /* The gather FOLDS the shared arm in wherever there is one: it takes `sout` and `sgate` and
-     * writes the block's delta straight into `h.x`, so `w.moe` is never written. */
+    /* The gather folds in the shared arm when there is one, reading `sout` and `sgate` and writing
+     * the block's delta straight into `h.x`; `w.moe` is then unused. */
     bool   gfold = false;
-    /* THE WRITE BEHIND THIS BLOCK TAKES THE GATHER up to this many tokens -- HyperConn's
-     * gather_rows and gather_rows6, one a wire, set by the architecture after that write declared
-     * its fused forms, 0 where it did not. Where gather_taken() says so the block leaves its routed
-     * rows unsummed. */
+    /* The following write performs the gather up to this many tokens, per wire (HyperConn's
+     * gather_rows / gather_rows6, set by the architecture after that write is declared; 0 where
+     * not). Where gather_taken() agrees, the block leaves its routed rows unsummed. */
     int64_t gather_out_rows = 0;
     int64_t gather_out_rows6 = 0;
-    /* The calibration tap: two accumulators and the two ops that fill them. Zero unless
-     * `Config::calib` is set. `calib_rows` and `calib_done` are mutable because `pass` is const
-     * and the tap's whole state is a token count -- per block, so a block reaches its target on
-     * the same pass every other block does and nothing has to know which layer is last. */
+    /* The calibration tap's accumulators and ops; zero unless `Config::calib`. `calib_rows` and
+     * `calib_done` are mutable because `pass` is const. The count is per block, so every block
+     * reaches its target on the same pass. */
     rad_buf b_gram_gu = 0, b_gram_dn = 0;
     rad_op  op_gram_gu = 0, op_gram_dn = 0;
-    /* The domain the tap sums in, which its files say (calib_write): the rotation's width when
-     * the GEMMs read rotated codes, the model's own otherwise. */
+    /* The domain the tap sums in, recorded in its files (calib_write): the rotation width when the
+     * GEMMs read rotated codes, else 0. */
     uint32_t gram_domain = 0;
-    /* THE FILE IS NAMED AFTER THE WEIGHT IT WILL BE USED TO PACK, minus the expert index, and
-     * that is the whole protocol between this and the GPTQ quantiser: the recipe hands it the
-     * directory (`calib=`) and rad-convert the weight's logical name, and libquant strips
-     * `..weight` off the name to get the file. A name of this tap's own -- "blk3.gate_up" --
-     * would have made the quantiser carry a table mapping one to the other, for every
-     * architecture. */
+    /* Files are named after the weight they will pack, minus the expert index. That is the whole
+     * protocol with the GPTQ quantiser: the recipe gives the directory (`calib=`), rad-convert the
+     * weight's logical name, and libquant strips `..weight` to find the file. */
     const char* gram_gu_stem = nullptr;
     const char* gram_dn_stem = nullptr;
     mutable long long calib_rows = 0;
     mutable bool      calib_done = false;
-    /* THE DOWN PROJECTION'S HESSIAN AN EXPERT (rad_arch.h, CalibExperts), beside the pooled one:
-     * a layer-sized scratch, `ne` squares of [n_ff_exp, n_ff_exp], a `gram_accum` into each
-     * expert's square over that expert's rows, and the sum kept on the host. */
+    /* Per-expert down-projection Hessians (rad_arch.h: CalibExperts), beside the pooled one: a
+     * layer-sized scratch of `ne` [n_ff_exp, n_ff_exp] squares, a `gram_accum` into each over that
+     * expert's rows, summed on the host. */
     rad_buf b_gram_dne = 0;
     rad_op  op_gram_dne = 0;
     mutable CalibExperts calib_dne;
@@ -453,15 +382,15 @@ struct MoeFP8 {
      * AttnGatedFP8::ar_out_take. */
     int    ar_out_take = kArOutNorm;
 
-    /* THE STORED EXPERT FORMAT, read off the encoding of layer `l`'s first expert's gate_up --
-     * its name map declared here, which declare() then leaves out -- into `cfg->expert_w4` and
-     * `cfg->expert_rot`. Asked before any layer is declared, because the architecture sizes the
-     * rotated activation and tells the connection in front of the block to write it. Nothing
-     * known about the weight (a builder with no model behind it) is block fp8. */
+    /* Reads the stored expert format from layer `l`'s first expert's gate_up encoding into `cfg`
+     * (expert_w4, expert_rot, ...). That name map is declared here and skipped by declare(). Called
+     * before any layer is declared, because the architecture sizes the rotated activation and
+     * tells the preceding connection to write it. An unknown encoding (no model behind the
+     * builder) means block fp8. */
     static int probe(RadBuilder* b, Names& nm, int l, const Src& src, Config* cfg);
     /* The format `e` names: 0 block fp8, 1 four-bit, 2 four-bit rotated, 3 plain bf16, 4 the
-     * rotated w4nl codebook, 5 and 6 that codebook at E4M3 scales a 64 and a 32 of K, 7 its
-     * five-bit form at a 64; RAD_E_DTYPE for an encoding this block serves none of. */
+     * rotated w4nl codebook, 5 and 6 that codebook at E4M3 scales per 64 and 32 of K, 7 its
+     * five-bit form per 64; RAD_E_DTYPE otherwise. */
     static int format_of(const RadEncoding& e);
     /* format_of's numbers as the grouped GEMMs' dtype strings. */
     static constexpr const char* kServed[8] = { "fp8a8", "w4a8", "w4a8h", "bf16", "w4nla8h",
@@ -471,12 +400,26 @@ struct MoeFP8 {
                  const Wire& wire, const Src& src, bool fold = false, bool add_out = true,
                  int ar_in = kArNone, bool ar_out_ = false);
     void step(RadCtx* c, const RadBatch* batch) const;
-    /* The block over the first `T` rows of its buffers, which a pass that runs it for fewer rows
-     * than its batch has asks for: the MTP head's history pass, which reads the head's output only
-     * at its drafting rows. */
+    /* The block over the first `T` rows of its buffers, for passes that need fewer rows than the
+     * batch (the MTP head's history pass reads its output only at drafting rows). */
     void step_rows(RadCtx* c, int64_t T) const;
-    /* One pass of at most `c.rows` tokens. */
-    void pass(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const;
+    /* One pass of at most `c.rows` tokens. `own_ar` false: the caller issues the pass's
+     * all-reduce itself (issue_ar), as GdnFP8::step describes. */
+    void pass(RadCtx* c, int64_t T, int64_t r0, int64_t rows, bool own_ar = true) const;
+    /* The heat engine's handoff, after a step's last pass (step() says what it reports). */
+    void route_report(RadCtx* c) const;
+    bool issues_ar(int64_t T, int64_t rows) const {
+        return op_ar && !ar_taken(g, ar_out_take != kArOutNorm ? T : rows, ar_out, ar_out_take);
+    }
+    /* `beside` false: the collective runs on its own (a pass that owns it), so it takes the
+     * size-chosen block count and not the overlap cap, which only pays beside other work. */
+    void issue_ar(RadCtx* c, int64_t r0, int64_t rows, bool beside = true) const {
+        RAD_ISSUE_N(c, beside && op_ar_ov ? op_ar_ov : op_ar, rows * g.n_embd,
+                    brow_slice(w.h.x, r0, rows, g.n_embd), RAD_NONE);
+    }
+    /* Set before declare: the `overlap` issue_ar's collective is declared at, 0 for none. */
+    int    ar_overlap = 0;
+    rad_op op_ar_ov = 0;
     void shared_up(RadCtx* c, int64_t T, int64_t r0, int64_t rows, bool gate_done = false) const;
 };
 
@@ -484,8 +427,8 @@ inline int MoeFP8::format_of(const RadEncoding& e) {
     if (rad_enc_is(&e, "plain") && e.n_planes == 1 && e.plane[0].dtype == RAD_BF16) return 3;
     if (!rad_enc_is(&e, "affine")) return RAD_E_DTYPE;
     const RadEncPlane* sc = rad_enc_plane(&e, "scale");
-    /* The codebook at E4M3 scales a 64 or 32 of K under one fixed f32 (w4nl64a8h, w4nl32a8h), and
-     * its five-bit form at a 64 (w5nl64a8h). */
+    /* The codebook at E4M3 scales per 64 or 32 of K under one fixed f32 (w4nl64a8h, w4nl32a8h),
+     * and its five-bit form per 64 (w5nl64a8h). */
     if (e.n_planes == 4 && sc && sc->dtype == RAD_F8E4M3) {
         const RadEncPlane* s2 = rad_enc_plane(&e, "scale.1");
         const RadEncPlane* t  = rad_enc_plane(&e, "table");
@@ -520,13 +463,11 @@ inline int MoeFP8::format_of(const RadEncoding& e) {
     return RAD_E_DTYPE;
 }
 
-/* WHETHER A CHECKPOINT SHIPS ONE LAYER'S EXPERTS STACKED OR ONE BY ONE, as the Src it fills.
- * Recent releases stack them -- `.gate_up_proj` and `.down_proj` -- and a
- * quantised export (AutoRound's) writes each expert on its own, `..{gate,up,down}_proj`.
- * Each form is asked of the checkpoint through a probe name mapped to its first expert, which the
- * checkpoint answers or does not. Stacked is the answer when neither is found: a container is
- * read by declared name, the same under both maps, so it asks nothing here. `tag` keeps one
- * caller's probe name apart from another's for the same layer. */
+/* Fills `src` with whether the checkpoint stores a layer's experts stacked
+ * (`.gate_up_proj`, `.down_proj`; recent releases) or one by one
+ * (`..{gate,up,down}_proj`; e.g. AutoRound exports), by probing a name mapped to the
+ * per-expert form's first expert. Defaults to stacked: a container is read by declared name, the
+ * same under both maps. `tag` keeps different callers' probe names apart. */
 inline int moe_expert_sources(RadBuilder* b, Names& nm, const char* tag, const char* prefix,
                               MoeFP8::Src* src) {
     const char* gu = nm.ckpt("%s.gate_up_proj", prefix);
@@ -550,8 +491,7 @@ inline int moe_expert_sources(RadBuilder* b, Names& nm, const char* tag, const c
 inline int moe_map_expert(RadBuilder* b, Names& nm, const MoeFP8::Src& src, const char* guw,
                           const char* dnw, long long ge, bool gate_up) {
     if (src.experts_gate_up) {
-        /* THE SLICE INDEX IS GLOBAL: the checkpoint holds every expert, and this rank declares a
-         * window into it. Slicing by the local index would give every rank experts 0..E/W. */
+        /* The slice index is global: the checkpoint holds every expert. */
         if (gate_up) RAD_ARCH_TRY(map_slice(b, guw, src.experts_gate_up, (int)ge));
         return map_slice(b, dnw, src.experts_down, (int)ge);
     }
@@ -563,12 +503,12 @@ inline int moe_map_expert(RadBuilder* b, Names& nm, const MoeFP8::Src& src, cons
 
 inline int MoeFP8::probe(RadBuilder* b, Names& nm, int l, const Src& src, Config* cfg) {
     if (!cfg || (!src.experts && !src.experts_gate_up)) return RAD_E_INVAL;
-    /* The caller names the expert, in the model's numbering: the first one this rank will own if
-     * the experts are split between the ranks, which declare() then skips -- and an expert every
-     * rank declares a slice of otherwise, which every rank skips. */
-    /* A PLAIN bf16 EXPERT DOES NOT SETTLE IT: a quantised layer keeps up to kMaxProtected of its
-     * experts plain, so the probe reads on past them to the first expert in another format, and
-     * only a run of plain ones longer than any protected set says the model is bf16. */
+    /* The caller names the expert in model numbering (the first this rank owns under expert
+     * parallelism); declare() skips the ones mapped here.
+     *
+     * A bf16 expert does not settle the format: a quantised layer keeps up to kMaxProtected
+     * experts bf16, so the probe reads on to the first expert in another format, and only a longer
+     * run of bf16 ones means the model is bf16. */
     const long long g0 = (long long)cfg->probed_expert;
     const long long all = cfg->n_expert_all > 0 ? (long long)cfg->n_expert_all
                                                 : (long long)cfg->n_expert;
@@ -610,34 +550,23 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
                            int ar_in, bool ar_out_) {
     g = geom; c = src.cfg; w = wire; layer = l;
     ar_out = ar_out_;
-    /* 0 means "not expert-parallel": this rank owns the model's whole expert set. Normalised once,
-     * here, so nothing below has to ask which case it is in. */
+    /* 0 means not expert-parallel: this rank owns every expert. */
     if (c.n_expert_all <= 0) c.n_expert_all = c.n_expert;
     if (c.n_expert <= 0 || c.top_k <= 0 || c.top_k > c.n_expert_all || c.n_ff_exp <= 0)
         return RAD_E_INVAL;
-    /* THE SLICE HAS TO BE INSIDE THE MODEL. A base past the end silently routes nothing to this
-     * rank -- a model that serves and drops a fraction of its own feed-forward. */
+    /* The expert slice must lie inside the model, or tokens routed past it are silently dropped. */
     if (c.expert_base < 0 || c.expert_base + c.n_expert > c.n_expert_all) return RAD_E_INVAL;
     if (c.rows <= 0) c.rows = g.max_tok;
     /* A rank whose slice of the shared arm is empty (see Config) declares no arm, and the
      * all-reduce carries the others' share. */
     const bool shared = c.n_ff_shared > 0 && src.shared;
-    /* Whether `w.sgate` is out of the sharing pool -- set where the shared arm says so, and what
-     * the fused router's gate write relies on (see there). */
+    /* Whether `w.sgate` is excluded from buffer sharing; set with the shared arm and required by
+     * the fused router's gate write (see there). */
     bool sgate_concurrent = false;
 
-    /* THE INPUT MAY BE PREPARED BY THE ARCHITECTURE, and `src.norm == nullptr` is how it says so.
-     *
-     * A pre-norm model's block owns its own norm: one op that adds the previous block's delta into
-     * the residual stream, normalises it and quantises it (rad_fp8.h's NormQuantFP8). A GATED
-     * RESIDUAL model's does not -- arch/common/rad_block_hc.h's `hc_read` produces the block input
-     * from a stream four times as wide, with a data-dependent mix the block has no way to compute,
-     * and there is nothing left for a norm here to do. So this block takes `wire.h` as ALREADY
-     * normed and quantised and declares no norm weight at all.
-     *
-     * `ar_in` is refused in that mode rather than ignored: the fused all-reduce lives INSIDE the
-     * norm, so with no norm there is nowhere to fold it and a caller that asked would silently get
-     * an unreduced input. It emits a standalone collective instead (`add_out`/`ar_out`). */
+    /* `src.norm == nullptr`: the architecture prepares the input (rad_block_hc.h's `hc_read`), so
+     * `wire.h` is already normed and quantised and no norm weight is declared. `ar_in` is then
+     * refused, since the fused all-reduce lives inside the norm. See rad_block_attn_gated_fp8.h. */
     ext_in = (src.norm == nullptr);
     if (ext_in) {
         if (!w.h.x || (!g.w_bf16 && (!w.h.q || !w.h.s)) || ar_in != kArNone) return RAD_E_INVAL;
@@ -647,14 +576,12 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
                         RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
     }
 
-    /* ---- THE EXPERTS' NAME MAPS, and from them which experts this layer PROTECTS. The maps are
-     * how the model is asked what each expert is (rad_weight_encoding): one a LOGICAL weight,
-     * gate_up and down, the scale views having none; the probed experts' gate_up is mapped
-     * already. Every expert is the format the block was set up for -- one table of experts takes
-     * one encoding -- except that a quantised layer may keep a few WHOLE experts plain bf16: the
-     * ones whose output dwarfs the rest's, where the same relative rounding error is a large
-     * absolute one (docs/MOE-W4.md). Those are sorted last and served by a bf16 GEMM pair of
-     * their own; they are found here, before the sort is declared, because the sort takes them. */
+    /* ---- The experts' name maps (one per logical weight, gate_up and down; scale views have
+     * none; the probed experts' gate_up is already mapped), and from their encodings the experts
+     * this layer protects. One table takes one encoding, but a quantised layer may keep a few
+     * whole experts bf16: those whose output dwarfs the rest, where the same relative rounding
+     * error is large in absolute terms (docs/MOE-W4.md). They are sorted last and served by their
+     * own bf16 GEMM pair, so they must be known before the sort is declared. */
     const int64_t ne = c.n_expert;
     for (int64_t e = 0; e < ne; ++e) {
         const long long ge = (long long)(c.expert_base + e);   /* the checkpoint's numbering */
@@ -677,11 +604,10 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
                 if (weight_enc(b, nmv[i], &enc[i])) fe[i] = format_of(enc[i]);
             }
         };
-        /* THE CODEBOOK FORMS AT E4M3 SCALES SHARE EVERYTHING BUT THE GEMM'S DTYPE -- the rotated
-         * input, the scale views, the fixed second level, the accumulators -- so the bits can go
-         * where the error is: a layer, and either projection of it, may be in any of them whatever
-         * the probed layer's. The first expert of the layer kept in one of them decides its two;
-         * every other must match. Outside that family a layer is the probed layer's form. */
+        /* The codebook forms at E4M3 scales differ only in the GEMM's dtype (same rotated input,
+         * scale views, fixed second level, accumulators), so each layer and projection may use any
+         * of them. The layer's first non-bf16 expert decides both; every other must match. Outside
+         * that family a layer uses the probed layer's form. */
         auto family = [](int f) { return f == 5 || f == 6 || f == 7; };
         fmt[0] = fmt[1] = want;
         if (family(want))
@@ -718,16 +644,15 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
                             "places at most %lld last\n", l, prot.size(), (long long)kMaxProtected);
             return RAD_E_INVAL;
         }
-        /* The quantised GEMM takes its experts as two equal tables by parity -- at four classes
-         * (Config::ff_lo4) as four tables, the first n_reg % 4 one expert longer, which any count
-         * gives. */
+        /* The quantised GEMM takes two equal tables by parity; with four classes
+         * (Config::ff_lo4), four tables with the first n_reg % 4 one longer, so any count works. */
         if (!(c.ff_hi[0] > 0 && c.ff_hi4[0] > 0) && n_reg % 2) {
             fprintf(stderr, "radiance: layer %d keeps %zu experts plain bf16 on this rank, which "
                             "leaves %lld quantised; they come in pairs on a rank so the rest split "
                             "into two equal tables by parity\n", l, prot.size(), (long long)n_reg);
             return RAD_E_INVAL;
         }
-        /* The tap's per-expert files are named by expert, and the sort here numbers by place. */
+        /* The tap's per-expert files are named by expert, but this sort numbers by place. */
         if (c.calib) {
             fprintf(stderr, "radiance: calibrate the bf16 container: layer %d of this one keeps "
                             "experts plain bf16 and sorts them out of order\n", l);
@@ -738,12 +663,9 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
         prot_list = nm.ckpt("%s", lst.c_str());
     }
 
-    /* THE ROUTER IS REPLICATED, NOT SHARDED, and that is the property the whole block rests on.
-     * Every rank routes every token to the same experts -- the routing is computed from the full
-     * residual stream, which every rank holds -- so `sorted_tok` and `expert_offset` are identical
-     * across ranks and the expert GEMMs' row layout agrees without a collective. Sharding the
-     * router would make two ranks disagree about which expert a token went to, and the all-reduce
-     * at the end of the block would then sum two different models. */
+    /* The router is replicated (see Config::n_expert_all): every rank computes the same routing
+     * from the full residual stream, so `sorted_tok` and `expert_offset` agree across ranks
+     * without a collective. */
     RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_gate_inp.weight", l), src.router));
     w_router = decl_w(b, nm.f("blk.%d.ffn_gate_inp.weight", l), RAD_BF16,
                       {c.n_expert_all, g.n_embd},
@@ -764,66 +686,42 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
                                RAD_STR("dtype", g.dtype)),
                     RAD_NOWEIGHTS),
                 {w.logits}, {w.ids, w.ew});
-    /* THE PROTECTED EXPERTS ARE SORTED LAST (`protect`), and only a layer that has them says so,
-     * so every other layer's sort is declared without a protect list. */
-    if (!prot_list)
-        op_scatter = rw(b, RAD_OP(b, "moe_scatter",
-                           RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.n_expert),
-                                      RAD_INT("top_k", c.top_k),
-                                      RAD_INT("expert_base", c.expert_base)),
-                           RAD_NOWEIGHTS),
-                       {w.ids}, {w.sorted, w.eoff, w.ecnt});
-    else
-        op_scatter = rw(b, RAD_OP(b, "moe_scatter",
-                           RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.n_expert),
-                                      RAD_INT("top_k", c.top_k),
-                                      RAD_INT("expert_base", c.expert_base),
-                                      RAD_STR("protect", prot_list)),
-                           RAD_NOWEIGHTS),
-                       {w.ids}, {w.sorted, w.eoff, w.ecnt});
+    /* Protected experts are sorted last (`protect`); layers without them declare no protect
+     * list, so it is the last parameter and cut off. */
+    const int n_prot = prot_list ? 1 : 0;
+    {
+        const RadParam ps[] = { RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.n_expert),
+                                RAD_INT("top_k", c.top_k), RAD_INT("expert_base", c.expert_base),
+                                RAD_STR("protect", prot_list) };
+        op_scatter = rw(b, rad_decl_op(b, "moe_scatter", ps, 4 + n_prot, RAD_NOWEIGHTS),
+                        {w.ids}, {w.sorted, w.eoff, w.ecnt});
+    }
 
-    /* THE TWO ABOVE IN ONE LAUNCH, and it is worth asking for because NEITHER IS WORK. At a decode
-     * shape each is a single 256-thread workgroup ranking about a kilobyte, so each costs a full
-     * dispatch for no arithmetic, once per layer per step, twice over. The sort reads
-     * `expert_ids` and nothing else and the selection writes it, so the launch between them buys a
-     * barrier and nothing more.
+    /* topk and scatter in one launch. At decode each is a single 256-thread workgroup ranking
+     * about a kilobyte, so each is a dispatch with almost no work, and the sort reads only what
+     * the selection writes.
      *
-     * BOUNDED BY THE SORT'S SINGLE-WORKGROUP FORM. `moe_scatter` runs one launch at
-     * M*top_k <= 1024 and three above it -- the three exist to keep the sort stable without an
-     * atomic deciding the order -- and only the first shape is fusible. That is the DECODE band by
-     * construction (eight sequences at depth 3 and top_k 10 is 320) and a prefill chunk is past
-     * it, which is also where the pair is amortised over real work and the fusion would buy
-     * nothing. Declared either way, so the graph and the buffer plan do not depend on it. */
-    if (c.top_k > 0 && (int64_t)c.rows * c.top_k <= kMoeSortRows)
-        topk_scatter_rows = c.rows;
-    else
-        topk_scatter_rows = kMoeSortRows / c.top_k;
-    if (topk_scatter_rows > 0 && !prot_list)
-        op_topk_scatter = rw(b, RAD_OP(b, "router_topk_scatter",
-                                RAD_PARAMS(RAD_RANGE("M", 1, topk_scatter_rows),
-                                           RAD_INT("n_expert", c.n_expert_all),
-                                           RAD_INT("n_local", c.n_expert),
-                                           RAD_INT("top_k", c.top_k),
-                                           RAD_INT("norm", c.norm_topk),
-                                           RAD_STR("dtype", g.dtype),
-                                           RAD_INT("expert_base", c.expert_base)),
-                                RAD_NOWEIGHTS),
-                            {w.logits}, {w.ids, w.ew, w.sorted, w.eoff, w.ecnt});
-    else if (topk_scatter_rows > 0)
-        op_topk_scatter = rw(b, RAD_OP(b, "router_topk_scatter",
-                                RAD_PARAMS(RAD_RANGE("M", 1, topk_scatter_rows),
-                                           RAD_INT("n_expert", c.n_expert_all),
-                                           RAD_INT("n_local", c.n_expert),
-                                           RAD_INT("top_k", c.top_k),
-                                           RAD_INT("norm", c.norm_topk),
-                                           RAD_STR("dtype", g.dtype),
-                                           RAD_INT("expert_base", c.expert_base),
-                                           RAD_STR("protect", prot_list)),
-                                RAD_NOWEIGHTS),
-                            {w.logits}, {w.ids, w.ew, w.sorted, w.eoff, w.ecnt});
+     * Bounded by the sort's single-workgroup form: `moe_scatter` is one launch at
+     * M*top_k <= 1024 and three above (for a stable sort without atomics), and only the first is
+     * fusible. That covers decode (eight sequences at depth 3 and top_k 10 is 320); prefill
+     * chunks exceed it. The pair is declared either way, so the graph and buffer plan do not
+     * depend on it. */
+    topk_scatter_rows = (int64_t)c.rows * c.top_k <= kMoeSortRows ? c.rows
+                                                                   : kMoeSortRows / c.top_k;
+    /* Asked for only where a loaded library declares it: a CPU-only engine would refuse the
+     * declare, and the two separate ops serve without it. */
+    if (topk_scatter_rows > 0 && rad_op_declared(b, "router_topk_scatter")) {
+        const RadParam ps[] = { RAD_RANGE("M", 1, topk_scatter_rows),
+                                RAD_INT("n_expert", c.n_expert_all), RAD_INT("n_local", c.n_expert),
+                                RAD_INT("top_k", c.top_k), RAD_INT("norm", c.norm_topk),
+                                RAD_STR("dtype", g.dtype), RAD_INT("expert_base", c.expert_base),
+                                RAD_STR("protect", prot_list) };
+        op_topk_scatter = rw(b, rad_decl_op(b, "router_topk_scatter", ps, 7 + n_prot,
+                                            RAD_NOWEIGHTS),
+                             {w.logits}, {w.ids, w.ew, w.sorted, w.eoff, w.ecnt});
+    }
 
-    /* EITHER a prefix or the two stacked tensors, never both and never neither. A checkpoint
-     * cannot be read two ways at once and a caller that set both has not decided. */
+    /* Exactly one of a prefix or the two stacked tensors. */
     const bool stacked = src.experts_gate_up != nullptr;
     if (stacked != (src.experts_down != nullptr) || (stacked == (src.experts != nullptr))) {
         fprintf(stderr, "radiance: a routed feed-forward takes EITHER an `experts` prefix or "
@@ -833,28 +731,25 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
         return RAD_E_INVAL;
     }
 
-    /* ---- the expert weights, in EIGHT RUNS: gate_up codes, gate_up scales, down codes and down
-     * scales, each for the even experts and then the odd ones. See the header: a weight table is a
-     * run of consecutive handles, and `moe_gemm_q` takes each projection's experts as two tables
-     * by parity -- entry e / 2 of class e % 2 -- so these loops must not be merged. */
+    /* ---- the expert weights, as runs: gate_up codes, gate_up scales, down codes, down scales,
+     * each per class (even then odd; entry e / 2 of class e % 2). A weight table is a run of
+     * consecutive handles (see the header), so these loops must not be merged. */
     if (ne % 2) {
         fprintf(stderr, "radiance: %lld routed experts on this rank; the grouped GEMM takes them as "
                         "two equal tables by parity, so the count must be even\n", (long long)ne);
         return RAD_E_INVAL;
     }
-    /* The quantised experts by their PLACE in the sort -- the protected ones sorted last are not
-     * among them -- which is also the expert slot each is declared in, so the routing counts the
-     * sort writes in place order credit the right unit. */
+    /* The quantised experts by place in the sort (protected ones excluded). Each is declared in
+     * its place's slot, so routing counts written in place order credit the right unit. */
     std::vector reg;
     reg.reserve((size_t)n_reg);
     for (int64_t e = 0; e < ne; ++e)
         if (std::find(prot.begin(), prot.end(), e) == prot.end()) reg.push_back(e);
     w_gu.resize((size_t)ne); w_gus.resize((size_t)ne);
     w_dn.resize((size_t)ne); w_dns.resize((size_t)ne);
-    /* Each class's width on this rank: the Config's slice when the width is split unevenly, and
-     * `n_ff_exp` for every class otherwise. The buffers between the two GEMMs are the widest
-     * one's. FOUR CLASSES where the Config offers them (Config::ff_lo4), the parity classes
-     * otherwise. */
+    /* Each class's width on this rank: the Config's slice when split unevenly, else `n_ff_exp`.
+     * The buffers between the GEMMs take the widest. Four classes when Config::ff_lo4 is set, else
+     * the parity classes. */
     const bool split = c.ff_hi[0] > 0 || c.ff_hi4[0] > 0;
     ncls = c.ff_hi4[0] > 0 ? 4 : 2;
     if (ncls == 4 && n_reg < 4) {
@@ -893,34 +788,28 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
                     (long long)wq[q], (long long)g.n_embd, RAD_FP8_BLOCK, RAD_FP8_BLOCK);
             return RAD_E_INVAL;
         }
-    /* The codes' dtype, which is what the codes view is declared at, and the planes it selects:
-     * a codebook's table rides with its codes, so the relayout sees the table it is asked to
-     * decode by. */
+    /* The codes view's dtype and planes; a codebook's table is selected with its codes so the
+     * relayout sees it. */
     auto edt_of = [&](int f) {
         return f == 7 ? (uint32_t)RAD_U5 : c.expert_nl ? (uint32_t)RAD_U4
              : c.expert_w4 ? (uint32_t)RAD_I4 : (uint32_t)RAD_F8E4M3;
     };
     const uint32_t edt[2] = { edt_of(fmt[0]), edt_of(fmt[1]) };
     const char* const ecodes = c.expert_nl ? "codes,table" : "codes";
-    /* UNDER EXPERT PARALLELISM AN EXPERT IS WHOLE, so its weights are not sharded at all: this
-     * rank holds all of the columns of the experts it owns and none of the others. Declaring them
-     * RAD_SHARD_ROW would have the loader slice each one again -- it refuses by name, because the
-     * declared row parts sum to the full width while the rank's share is half of it. */
+    /* Under expert parallelism each owned expert is whole, so its weights are not sharded;
+     * RAD_SHARD_ROW would make the loader slice it again (and refuse). */
     const bool ep = c.n_expert != c.n_expert_all;
     if (ep && split) {
         fprintf(stderr, "radiance: a rank either owns whole experts or a slice of every one; this "
                         "configuration asks for both\n");
         return RAD_E_INVAL;
     }
-    /* A PACKED 4-BIT ROW SLICES ON ITS SCALE GROUPS AND NOWHERE ELSE: it is K/2 bytes with eight
-     * codes a dword, so a width shard along K is a byte range of every row exactly when it falls on
-     * a group of 128 -- which the per-rank check above already requires -- and a shard along the
-     * rows is whole rows. The rotation is a 128-wide Hadamard inside each group and is cut by
-     * neither. */
-    /* THE ROTATION IS A PROPERTY OF THE 4-BIT PLANE AND HAS NO MEANING WITHOUT IT. There is no
-     * rotated fp8 expert format in this tree -- the fp8 layout hook writes a 128x128 tile scale
-     * and has no rotated form -- so `expert_rot` alone is a configuration that cannot be
-     * built, and saying so is better than silently serving the unrotated one. */
+    /* A packed 4-bit row (K/2 bytes, eight codes per dword) shards along K only on 128-groups,
+     * which the check above requires; row shards are whole rows. The 128-wide rotation lies within
+     * a group, so neither cuts it.
+     *
+     * Rotation exists only for the 4-bit plane (the fp8 layout hook has no rotated form), and the
+     * codebook only with rotation; other combinations are refused. */
     if ((c.expert_rot && !c.expert_w4) || (c.expert_nl && !c.expert_rot)) {
         fprintf(stderr, "radiance: rotated experts (expert_rot) require the 4-bit expert format, "
                         "and a codebook (expert_nl) the rotated one; there is no rotated E4M3 "
@@ -930,36 +819,32 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
     const int  sh_row = ep ? RAD_SHARD_NONE : RAD_SHARD_ROW;
     const int  sh_col = ep ? RAD_SHARD_NONE : RAD_SHARD_COL;
     const int  n_parts = ep ? 0 : 2;
-    /* The scale grid the chosen weight format wants: one per 128x128 tile for E4M3, one per ROW
-     * per group of 128 along K for 4-bit -- which is what a sixteen-level grid needs, and is the
-     * only shape difference between the two declarations. `sdiv` is how many weight rows or
-     * columns one scale covers along the split dimension. */
+    /* The scale grid: one per 128x128 tile for E4M3, one per row per 128 of K for 4-bit. `sdiv` is
+     * how many weight rows or columns one scale covers along the split dimension. */
     const int64_t sdiv = c.expert_w4 ? 1 : RAD_FP8_BLOCK;
-    /* A FORMAT A STRING, and the string is what selects the grouped GEMM; its layout hook then
-     * accepts the experts' encoding or the kernel is not a candidate. One a projection. */
+    /* The dtype string per projection selects the grouped GEMM; its layout hook then accepts the
+     * experts' encoding or the kernel is not a candidate. */
     const char* const edtype[2] = { kServed[fmt[0]], kServed[fmt[1]] };
-    /* The scale views: bf16, one a (row, 128 of K) -- or a 128x128 tile for E4M3 -- or at
-     * w4nl64a8h one E4M3 a (row, 64 of K), selected with the fixed second level beside it. TWO
-     * PLANES MAKE IT A VIEW OF THE LOGICAL WEIGHT, as the codes view is (rad_builder.cpp): it is
-     * declared at the weight's extents, its slice is in the weight's columns, and the stored
-     * plane under it -- [rows, K/64] bytes -- is the layout hook's. `sgk` is the K one declared
-     * scale column covers. */
+    /* The scale views: bf16 per (row, 128 of K) or per 128x128 tile for E4M3, or for the 64-group
+     * forms E4M3 per (row, 64 of K) selected with the fixed second level. With two planes it is a
+     * view of the logical weight, like the codes view (rad_builder.cpp): declared at the weight's
+     * extents and sliced in its columns, with the stored [rows, K/64] plane left to the layout
+     * hook. `sgk` is the K one declared scale column covers. */
     const uint32_t sdt    = c.expert_g64 ? (uint32_t)RAD_F8E4M3 : (uint32_t)RAD_BF16;
     const int64_t  sgk    = c.expert_g64 ? 1 : RAD_FP8_BLOCK;
     const char*    escale = c.expert_g64 ? "scale,scale.1" : "scale";
-    /* A slice of each expert: the gate and up rows [lo, hi) of this class for the gate/up pair,
-     * columns [lo, hi) for down, and the scale planes the same slice in their own units. */
+    /* This class's slice of each expert: gate and up rows [lo, hi), down columns [lo, hi), scale
+     * planes the same in their own units. */
     auto span = [&](rad_weight h, int q, int64_t unit) -> int {
         if (!split || !h) return RAD_OK;
         return rad_weight_shard_span(b, h, qlo[q] / unit, qhi[q] / unit);
     };
     const bool rot = c.expert_rot != 0;
     if (c.expert_bf16) {
-        /* ---- PLAIN bf16 EXPERTS: ONE TABLE A PROJECTION, of whole experts in expert order --
-         * `moe_gemm`'s one weight operand, expert e at entry e -- so each projection's handles are
-         * declared in one loop and the two loops are not merged. An expert is its own movement
-         * unit as it is in every other format, and its bytes in the container are what the kernel
-         * reads, so the file tier can serve it as it lies. */
+        /* ---- Plain bf16 experts: one table per projection of whole experts in expert order
+         * (`moe_gemm`, expert e at entry e), so the two loops must not be merged. Each expert is
+         * its own movement unit, and its container bytes are what the kernel reads, so the file
+         * tier can serve it directly. */
         if (split || rot || c.expert_w4) {
             fprintf(stderr, "radiance: bf16 experts are whole on their rank (expert parallel, or "
                             "one rank) and unrotated; this configuration %s\n",
@@ -981,8 +866,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
                                      sh_col, grp_expert_slot(l, (int)e, 1));
             if (!w_dn[(size_t)e]) return RAD_E_INVAL;
         }
-        /* The same two row orders as the quantised GEMMs, and for the same reason (see a_order
-         * above): gate_up gathers token rows, down reads its input in sorted order. */
+        /* Row orders as for the quantised GEMMs (see `a_order` below): gate_up gathers token rows,
+         * down reads sorted rows. */
         op_gu = rw(b, rad_decl_op(b, "moe_gemm",
                           RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", 2 * c.n_ff_exp),
                                      RAD_INT("K", g.n_embd), RAD_INT("n_expert", ne),
@@ -990,8 +875,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
                                      RAD_STR("dtype", "bf16")),
                           w_gu.data(), (int)ne),
                    {w.h.x, w.sorted, w.eoff}, {w.egu});
-        /* silu(gate) * up into the bf16 plane the down GEMM reads: the gate's bf16 form, whatever
-         * the trunk's (rad_fp8.h, GateQuantFP8). */
+        /* silu(gate) * up into the bf16 plane the down GEMM reads, regardless of the trunk's format
+         * (rad_fp8.h: GateQuantFP8). */
         Geom gx = g;
         gx.w_bf16 = true;
         RAD_ARCH_TRY(gq_exp.declare(b, gx, w.egu, w.eff, c.n_ff_exp, "silu", c.rows * c.top_k,
@@ -1005,8 +890,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
                    {w.eff.x, w.sorted, w.eoff}, {w.edn});
         if (!op_gu || !op_dn) return RAD_E_INVAL;
     } else {
-    /* ---- the eight runs -- sixteen at four classes -- declared as the views the header
-     * describes, class by class. */
+    /* ---- the runs (eight, or sixteen at four classes), declared as views class by class. */
     for (int q = 0; q < ncls; ++q)
         for (int64_t s = q; s < n_reg; s += ncls) {
             const int64_t e = reg[(size_t)s];
@@ -1063,23 +947,18 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
             RAD_ARCH_TRY(span(h, q, sgk));
         }
 
-    /* ---- the two grouped GEMMs. `M` is the TOKEN count of a pass, not the sorted row count: the
-     * kernels read the row count off `y` and the parameter is what the scratch hook and the
-     * operand descriptions size from.
+    /* ---- the two grouped GEMMs. `M` is a pass's token count, not the sorted row count: kernels
+     * read the row count from `y`, and the scratch hook and operand descriptions size from `M`.
      *
-     * THE TWO DISAGREE ABOUT `a_order` AND THAT IS THE WHOLE POINT OF THE PARAMETER. gate_up reads
-     * the block's normed INPUT, which is one row per TOKEN, so a sorted row gathers
-     * `a[sorted_tok[i] / top_k]`. down reads gate_up's output through the gated quantiser, which
-     * is already one row per (token, slot) IN THIS ORDER, so a sorted row is row i. Gathering the
-     * second one as well hands every slot of a token the FIRST slot's intermediate -- at decode,
-     * where a step has one token, all top_k experts then read slot 0 -- and the model still runs
-     * and answers plausibly and wrongly. If the reference and the kernel both gather they AGREE,
-     * and a workbench that builds the operand at the extent the gather wants cannot see the
-     * difference either -- this parameter is the only thing that states which order is meant. */
-    /* THE ROUTED ARM'S OWN COPY OF THE INPUT, ROTATED. `w.h.q` is read by the shared expert too
-     * and that arm's weight is unrotated E4M3, so this cannot be done in place -- see Config's
-     * note on what the isolation buys and what it costs. Declared here, immediately before its
-     * one consumer, so the graph order and the issue order agree. */
+     * `a_order` differs between them. gate_up reads the normed input, one row per token, so sorted
+     * row i gathers `a[sorted_tok[i] / top_k]`. down reads the gated quantiser's output, already
+     * one row per (token, slot) in sorted order, so row i is row i. Gathering there too would give
+     * every slot the first slot's intermediate (at decode, all top_k experts read slot 0), and a
+     * reference that made the same mistake would agree; the parameter states which order is
+     * meant. */
+    /* The routed arm's rotated copy of the input. Not in place: the shared expert also reads
+     * `w.h.q` with an unrotated weight (see Config::expert_rot). Declared just before its one
+     * consumer so graph and issue order agree. */
     if (rot) {
         if (!w.hr.q || !w.hr.s) {
             fprintf(stderr, "radiance: rotated experts need the `hr` (q, scale) pair on the wire; "
@@ -1093,9 +972,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
                           RAD_NOWEIGHTS),
                       {w.h.x}, {w.hr.q, w.hr.s});
     }
-    /* A table op's weights, in its table operands' order: the even experts' codes and scales, then
-     * the odd experts' (`w`, `w_scale`, `w_odd`, `w_odd_scale`) -- or at four classes class 0's,
-     * then 1's, 2's and 3's. */
+    /* A table op's weights in operand order: even experts' codes and scales, then odd experts'
+     * (`w`, `w_scale`, `w_odd`, `w_odd_scale`), or at four classes classes 0 to 3. */
     auto tables = [&](const std::vector& wc, const std::vector& ws) {
         std::vector tab;
         tab.reserve((size_t)n_reg * 2);
@@ -1105,10 +983,9 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
         }
         return tab;
     };
-    /* THE GATE/UP OUTPUT IS TWO PARTS OF THE WIDER CLASS'S WIDTH, gate then up, and the narrower
-     * class fills each part's leading columns and zeros the rest -- so the gated quantiser below
-     * reads one layout for every row, and a row of the narrower class quantises to zeros past its
-     * width, which its down projection does not read. */
+    /* The gate_up output is two parts (gate, up) of the widest class's width. A narrower class
+     * fills each part's leading columns and zeros the rest, so the gated quantiser reads one layout
+     * and the zeros past the width are never read by that class's down projection. */
     {
         const std::vector tab = tables(w_gu, w_gus);
         rad_op h = ncls == 4
@@ -1132,10 +1009,9 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
                        tab.data(), (int)tab.size());
         op_gu = rw(b, h, {rot ? w.hr.q : w.h.q, rot ? w.hr.s : w.h.s, w.sorted, w.eoff}, {w.egu});
     }
-    /* THE DOWN PROJECTION'S INPUT IS FREE TO ROTATE IN PLACE, because `w.eff` is written here and
-     * read by exactly one op -- the down GEMM below, which takes the codes alone, so the bf16
-     * product is not written. So the rotation is not an extra launch, it is the same launch
-     * resolving to the rotated op. */
+    /* The down projection's input can be rotated in place: `w.eff` is read only by the down GEMM,
+     * which takes the codes alone (no bf16 product is written), so the gated quantiser resolves to
+     * the rotated op at no extra launch. */
     RAD_ARCH_TRY(gq_exp.declare(b, g, w.egu, w.eff, c.n_ff_exp, "silu", c.rows * c.top_k,
                                 false, rot));
     {
@@ -1161,42 +1037,33 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
                        tab.data(), (int)tab.size());
         op_dn = rw(b, h, {w.eff.q, w.eff.s, w.sorted, w.eoff}, {w.edn});
     }
-    /* ---- THE PROTECTED EXPERTS' OWN PAIR. Their weights are the layer's, not expert slots: a
-     * container's experts in a layer are one fixed-size unit each, and these are four times the
-     * bytes -- so they are static, always resident, and joined to the layer's unit with the
-     * router. One run of handles a projection, a table of `prot.size()`; the GEMMs are handed the
-     * trailing run of the offsets, the rows the quantised down GEMM left zero, and write them.
+    /* ---- The protected experts' own GEMM pair. Their weights belong to the layer group, not to
+     * expert slots: each container expert unit has a fixed size and these are four times larger, so
+     * they are static and resident with the router. One run per projection, a table of
+     * `prot.size()`; the GEMMs take the trailing offsets, the rows the quantised down GEMM left
+     * zero.
      *
-     * WHERE EVERY RANK HOLDS A SLICE OF EVERY EXPERT, IT HOLDS ONE OF THESE TOO, and an EVEN one:
-     * the parity split exists because a 640-wide expert is five 128-wide scale blocks, and a bf16
-     * expert has no blocks -- so rank r takes intermediate units [r*w, (r+1)*w) of each, rows of
-     * gate and of up and columns of down, and the block's all-reduce sums the partials as it does
-     * every other expert's. */
+     * When every rank holds a slice of every expert, it holds a slice of these too. A bf16 expert
+     * has no scale blocks, so the slice is even where possible (rank r takes intermediate units
+     * [r*w, (r+1)*w)), and the all-reduce sums the partials as for the other experts. */
     if (!prot.empty()) {
         const int64_t np = (int64_t)prot.size();
         int64_t wp = c.n_ff_exp;
         int     psh_row = RAD_SHARD_NONE, psh_col = RAD_SHARD_NONE, pparts = 0;
-        /* This rank's tile range within one plain expert, in the model's numbering; `phi` 0 is the
-         * even split, which needs no span because the loader divides the entry itself. */
+        /* This rank's range within one plain expert, in model numbering; `phi` 0 is the even split,
+         * which the loader divides itself. */
         int64_t plo = 0, phi = 0;
         if (split) {
-            /* THE EXPERT'S WHOLE WIDTH, not this rank's slice of it: `n_ff_all` is the model's, and
-             * where the parity tables end says the same thing at two ranks and nothing else at
-             * more -- reading it off `ff_hi` gave a per-rank answer, which happened to be right
-             * only when there were two of them. A plain expert has no scale blocks to land on, so
-             * the unit here is the GEMM's 64-wide output tile. */
+            /* The expert's whole width: `n_ff_all` (the max of `ff_hi` is the whole width only at
+             * two ranks). A plain expert has no scale blocks, so the unit is the GEMM's 64-wide
+             * output tile. */
             const int64_t full = g.n_ff_all > 0 ? g.n_ff_all
                                                 : (c.ff_hi[0] > c.ff_hi[1] ? c.ff_hi[0]
                                                                           : c.ff_hi[1]);
-            /* ONE SLICE A RANK, and it does not have to be the same size on every rank: an uneven
-             * share of the 64-wide tiles is still whole tiles, and an uneven share is the only
-             * kind available when the width does not divide -- this family's 640 columns are ten
-             * tiles, which four ranks take as 3, 3, 2, 2, the first ranks by index taking the
-             * extra ones. Every tile has exactly one owner, each rank writes its own columns of
-             * gate/up and reads its own of down, and the block's all-reduce sums the partials
-             * exactly as it does for the quantised experts and for the shared arm. The even case
-             * keeps the even-split declaration verbatim -- no span at all -- so a rank count that
-             * divides declares exactly as it did before. */
+            /* One slice per rank, possibly uneven in whole 64-wide tiles: 640 columns are ten
+             * tiles, which four ranks take as 3, 3, 2, 2 (lower ranks take the extra). Each tile
+             * has one owner and the all-reduce sums the partials. An evenly divisible width uses
+             * the plain even split with no span. */
             psh_row = RAD_SHARD_ROW;
             psh_col = RAD_SHARD_COL;
             pparts  = 2;
@@ -1234,8 +1101,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
             if (!w_pdn[(size_t)j]) return RAD_E_INVAL;
             if (phi > 0) RAD_ARCH_TRY(rad_weight_shard_span(b, w_pdn[(size_t)j], plo, phi));
         }
-        /* The gate_up output and the gate's, a sorted row each and in bf16: the rows of the
-         * regular experts are never written and never read. */
+        /* The gate_up and gate outputs, bf16, one sorted row each; regular experts' rows are
+         * unused. */
         b_pgu = decl_b(b, nm.f("blk.%d.moe_prot_gu", l), RAD_BF16, {c.rows * c.top_k, 2 * wp});
         pff.x = decl_b(b, nm.f("blk.%d.moe_prot_ff", l), RAD_BF16, {c.rows * c.top_k, wp});
         if (!b_pgu || !pff.x) return RAD_E_INVAL;
@@ -1260,13 +1127,11 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
         if (!op_pgu || !op_pdn) return RAD_E_INVAL;
     }
     }
-    /* ---- the calibration tap, declared LAST of the routed arm so its buffers cannot alias one
-     * the arm is still using. They are PERSIST, so the planner would not alias them anyway; the
-     * order is kept because declaration order IS the buffer plan and a reader should not have to
-     * check which kind a name is to know that. */
+    /* ---- the calibration tap, declared after the routed arm. Its PERSIST buffers would not be
+     * aliased anyway, but declaration order is the buffer plan, so keep it last. */
     if (c.calib) {
-        /* A rank holding a slice of each expert sees a slice of its K, and a Hessian of a slice is
-         * not the Hessian the packer needs. Calibration runs at one rank. */
+        /* A rank holding a slice of each expert sees a slice of K, and the packer needs the full
+         * Hessian, so calibration runs without expert slicing. */
         if (split) {
             fprintf(stderr, "radiance: calibration runs at one rank; this rank holds a slice of "
                             "every expert's width, and its Hessians would be of the slice\n");
@@ -1277,9 +1142,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
                             "set; there is nowhere to write the Hessians\n");
             return RAD_E_INVAL;
         }
-        /* Both K are multiples of 128 already, which `expert_rot` also requires; gram_accum needs
-         * only a multiple of four, but the 128 is what makes a 64-wide output tile sit inside one
-         * scale group and there is no width here that does not. */
+        /* Both K must be multiples of 128 (as `expert_rot` also requires). gram_accum needs only a
+         * multiple of four, but 128 keeps each 64-wide output tile inside one scale group. */
         if (!c.expert_bf16 && ((g.n_embd % RAD_FP8_BLOCK) || (c.n_ff_exp % RAD_FP8_BLOCK)))
             return RAD_E_SHAPE;
         gram_gu_stem = nm.f("blk.%d.ffn_gate_up_exps", l);
@@ -1288,8 +1152,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
                            RAD_BUF_PERSIST);
         b_gram_dn = decl_b(b, nm.f("blk.%d.gram_dn", l), RAD_F32, {c.n_ff_exp, c.n_ff_exp},
                            RAD_BUF_PERSIST);
-        /* bf16 experts read the model's own activation, and the tap sums exactly that; the
-         * quantised ones read codes, rotated when the plane is, and the files say which. */
+        /* bf16 experts read the model's activation and the tap sums that; quantised ones read
+         * codes, rotated when the plane is; the files record which. */
         gram_domain = rot ? (uint32_t)RAD_FP8_BLOCK : 0u;
         if (c.expert_bf16) {
             op_gram_gu = rw(b, RAD_OP(b, "gram_accum",
@@ -1309,10 +1173,9 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
                                       RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")),
                            RAD_NOWEIGHTS),
                        {rot ? w.hr.q : w.h.q, rot ? w.hr.s : w.h.s, b_gram_gu}, {b_gram_gu});
-        /* The down tap's M is the SORTED height, `rows * top_k`, because `w.eff` is one row per
-         * (token, slot). gate_up's is the token height -- its GEMM gathers internally, and every
-         * token is routed to exactly top_k experts, so the gathered distribution is the token
-         * distribution times top_k and H is used only up to a positive scale. */
+        /* The down tap's M is the sorted height `rows * top_k` (one row per (token, slot)).
+         * gate_up's is the token height: every token goes to exactly top_k experts, so the gathered
+         * distribution is the token distribution scaled by top_k, and H is used only up to scale. */
         op_gram_dn = rw(b, RAD_OP(b, "gram_accum",
                            RAD_PARAMS(RAD_RANGE("M", 1, c.rows * c.top_k),
                                       RAD_INT("n", c.n_ff_exp),
@@ -1320,9 +1183,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
                            RAD_NOWEIGHTS),
                        {w.eff.q, w.eff.s, b_gram_dn}, {b_gram_dn});
         }
-        /* One expert's Gram a launch: the same op over that expert's run of the sorted rows,
-         * into that expert's square of the scratch. TRANSIENT, because nothing on the card reads
-         * it after the pass -- it goes back to the host before the next op is issued. */
+        /* One launch per expert over its run of sorted rows, into its square of the scratch.
+         * Transient: it is copied to the host before the next op is issued. */
         b_gram_dne = decl_b(b, nm.f("blk.%d.gram_dn_experts", l), RAD_F32,
                             {c.n_expert * c.n_ff_exp, c.n_ff_exp});
         if (c.expert_bf16)
@@ -1344,9 +1206,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
         if (!b_gram_dne || !op_gram_dne) return RAD_E_INVAL;
     }
 
-    /* THE GATHER FOLDS THE SHARED ARM IN, so `w.moe` is never written: `scale_rows` and a
-     * separate gather would be two dispatches a layer, with a 160 KiB round trip through the
-     * buffer between them on top. */
+    /* The gather folds the shared arm in, so `w.moe` is never written; `scale_rows` plus a
+     * separate gather would be two dispatches per layer and a 160 KiB round trip. */
     gfold = shared;
     {
         rad_buf grd[5] = { w.edn, w.ew, w.sorted, w.sout, w.sgate };
@@ -1363,19 +1224,17 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
 
     /* ---- the shared expert. Ordinary dense linears over the same normed input. */
     if (shared) {
-        /* THE SECOND LANE NEEDS THESE OUT OF THE SHARING POOL, and rad_buf_concurrent is where
-         * that is said. The arm runs beside the routed GEMMs, so a plan that laid `sgu` over
-         * `egu` -- legal from the linear order, which puts one range entirely after the other --
-         * would have two streams writing the same arena bytes. It costs a few MiB of arena. */
+        /* The shared arm runs concurrently with the routed GEMMs, so its buffers are excluded from
+         * sharing (rad_buf_concurrent). Otherwise the linear order would allow `sgu` over `egu`,
+         * two streams writing the same bytes. Costs a few MiB of arena. */
         RAD_ARCH_TRY(rad_buf_concurrent(b, w.sgu));
-        /* WHAT THE DOWN PROJECTION READS decides what the gate writes, so it is asked first: the
-         * codes, or the bf16 plane when the weight is plain -- a bf16 model, or a quantised one
-         * that keeps the shared expert at the checkpoint's precision. */
+        /* Probe the down projection first: what it reads (codes, or the bf16 plane for a plain
+         * weight) decides what the gate writes. */
         const char* down_base = nm.f("blk.%d.ffn_down_shexp", l);
         RAD_ARCH_TRY(sh_down.probe(b, nm, g, down_base,
                                    { nm.ckpt("%s.down_proj.weight", src.shared) }));
-        /* The code pair the gate writes, E4M3 or the int8 one (ActFP8::q8_fed) -- and an int8
-         * down projection that quantises for itself writes the int8 pair on this lane too. */
+        /* The code pair the gate writes, E4M3 or int8 (ActFP8::q8_fed); an int8 down projection
+         * that quantises for itself also writes the int8 pair on this lane. */
         if (w.sff.cq()) {
             RAD_ARCH_TRY(rad_buf_concurrent(b, w.sff.cq()));
             RAD_ARCH_TRY(rad_buf_concurrent(b, w.sff.cs()));
@@ -1389,9 +1248,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
         RAD_ARCH_TRY(rad_buf_concurrent(b, w.sout));
         RAD_ARCH_TRY(rad_buf_concurrent(b, w.sgate));
         sgate_concurrent = true;
-        /* The gate/up rows and the down columns of this rank's slice -- the even split, or the
-         * uneven one Config states -- and the split of gate from up stays, because that is a
-         * property of the stacked checkpoint tensor and not of the rank count. */
+        /* gate/up rows and down columns of this rank's slice (even, or Config's uneven split); the
+         * gate/up row parts stay, as a property of the stacked checkpoint tensor. */
         RAD_ARCH_TRY(sh_gate_up.declare(b, nm, g, nm.f("blk.%d.ffn_gate_up_shexp", l),
                                         2 * c.n_ff_shared, g.n_embd, RAD_SHARD_ROW, grp_layer(l),
                                         { nm.ckpt("%s.gate_proj.weight", src.shared),
@@ -1407,10 +1265,9 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
                                      { nm.ckpt("%s.down_proj.weight", src.shared) },
                                      w.sff, w.sout, c.rows, {},
                                      c.shared_lo, c.shared_hi));
-        /* The gate. REPLICATED like the router and for the same reason: it is computed from the
-         * whole residual stream and a sharded copy would give two ranks two different gates for
-         * one token. One output column, so the GEMM is skinny and the kernel clamps rather than
-         * masks its N tile -- which is why N = 1 is legal here. */
+        /* The shared gate, replicated like the router so every rank computes the same gate. One
+         * output column: the skinny GEMM kernel clamps its N tile rather than masking, so N = 1 is
+         * legal. */
         RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_gate_shexp.weight", l), src.shared_gate));
         w_sgate = decl_w(b, nm.f("blk.%d.ffn_gate_shexp.weight", l), RAD_BF16, {1, g.n_embd},
                          RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
@@ -1421,25 +1278,19 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
                      {w.h.x}, {w.sgate});
     }
 
-    /* ---- THE ROUTER GEMM AND `router_topk_scatter` AS ONE OP, with the shared expert's gate in
-     * the same launch wherever the layer has one. Asked for wherever the pair itself is declared,
-     * up to the pair's own row bound and the skinny GEMM's decode band; a plugin that does not
-     * serve it leaves the handle 0 and the router and the pair are issued as declared above.
-     * Declared HERE, after the gate's weight, and not beside the router: the op names both
-     * weights, and declaring it late only lengthens the planned lifetime of the buffers it
-     * touches, never shortens one -- each of them is also declared by the op it stands in for, at
-     * that op's place.
+    /* ---- The router GEMM and `router_topk_scatter` as one op, plus the shared gate when the
+     * layer has one; up to the pair's row bound and the skinny GEMM's decode band. Unresolved, the
+     * separate ops run. Declared here, after the gate weight, because it names both weights;
+     * declaring late only lengthens its buffers' planned lifetimes, since each is also declared by
+     * the op it replaces.
      *
-     * EXCEPT `w.sgate`, WHICH THE FUSED OP WRITES AHEAD OF ITS DECLARED WRITER. The gate is issued
-     * at the router's place, before `op_sgate`'s declared index, so a plan bounded by the linear
-     * order could lend `w.sgate`'s bytes to a buffer that is live in between. It cannot here
-     * because the shared arm took `w.sgate` out of the sharing pool (rad_buf_concurrent), and the
-     * declaration refuses a fused gate on a layer where that has not happened.
+     * Exception: it writes `w.sgate` before `op_sgate`'s declared index, so the planner could lend
+     * those bytes to a buffer live in between. That is safe only because the shared arm excluded
+     * `w.sgate` from sharing (rad_buf_concurrent); otherwise the fused gate is refused.
      *
-     * NOT rw()'s braced lists and not one RAD_OP per combination: the parameter list (a protect
-     * list or not), the weights and the write set (the gate or not) are conditional, so each is
-     * one array cut to its length. */
-    if (op_topk_scatter) {
+     * The parameter list, weights and write set are conditional, so each is an array cut to
+     * length. */
+    if (op_topk_scatter && rad_op_declared(b, "router_gemm_topk_scatter")) {
         router_fused_rows = topk_scatter_rows < kMoeRouterFusedRows ? topk_scatter_rows
                                                                     : kMoeRouterFusedRows;
         const bool gate = op_sgate != 0;
@@ -1476,6 +1327,17 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
                                   RAD_INT("min_bytes", g.wire_min_bytes)),
                        RAD_NOWEIGHTS),
                    {w.h.x}, {w.h.x});
+    /* The same collective for a caller that runs it beside other work (issue_ar, a pipelined
+     * prefill): at `overlap` 1 it gets the rows that hold fewer CUs while waiting on the link. */
+    if (g.world > 1 && ar_overlap > 0)
+        op_ar_ov = 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),
+                                     RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
+                                     RAD_INT("min_bytes", g.wire_min_bytes),
+                                     RAD_INT("overlap", ar_overlap)),
+                          RAD_NOWEIGHTS),
+                      {w.h.x}, {w.h.x});
 
     if (add_out)
         op_add = rw(b, RAD_OP(b, "add",
@@ -1484,7 +1346,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
                         RAD_NOWEIGHTS),
                     {w.x, w.h.x}, {w.x});
 
-    /* The layer as the prefetch sees it, by the model's expert number -- what the router ranks. */
+    /* The layer as the prefetch sees it, indexed by model expert number (what the router ranks). */
     if (!c.expert_bf16 && c.n_expert_all > 0 && n_reg > 0) {
         const int64_t na = c.n_expert_all;
         xp_parts.assign((size_t)(na * 4), 0);
@@ -1509,62 +1371,49 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
     return RAD_OK;
 }
 
-/* ONE PASS OF AT MOST `c.rows` TOKENS. Every op here is per row -- the norm and the quantiser group
- * along K within a row, the router and the top-k are a row each, the grouped GEMMs give each sorted
- * row its own accumulation, and the gather closes each token's sum over its own slots -- so a pass
- * computes exactly the rows it names.
- *
- * THE EXPERT BUFFERS ARE ADDRESSED FROM ZERO, not from `r0`. They are one pass tall by declaration,
- * and `sorted_tok` indexes them relative to the pass; the only operands that carry the pass offset
- * are the ones that live at the step's height -- the residual stream and the normed input. */
-
-
-/* The shared arm's first stage: its one-column gate and its gate_up, both over the normed input.
- * The shared expert is ordinary dense linears over that input, and every buffer it touches is the
- * step's height -- so the pass offset goes through all of them exactly as it does through an
- * MlpFP8 slice. */
+/* The shared arm's first stage: its one-column gate and its gate_up over the normed input. Its
+ * buffers are step-tall, so the pass offset applies as in an MlpFP8 slice. */
 inline void MoeFP8::shared_up(RadCtx* c_, int64_t T, int64_t r0, int64_t rows,
                               bool gate_done) const {
     /* `gate_done`: the fused router already wrote this pass's gate. */
     if (!gate_done)
-    RAD_ISSUE_N(c_, op_sgate, rows, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_W(w_sgate),
-                brow_slice(w.sgate, r0, rows, 1));
+        RAD_ISSUE_N(c_, op_sgate, rows, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_W(w_sgate),
+                    brow_slice(w.sgate, r0, rows, 1));
     sh_gate_up.step(c_, w.h, w.sgu, T, r0, rows);
 }
 
-inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const {
-    /* `ne` is THIS RANK'S expert count and `ne_all` the model's: the logits plane and the top-k
-     * are the model's width, everything after the scatter is this rank's slice. */
+/* One pass of at most `c.rows` tokens. Every op is per row (norm and quantiser within a row,
+ * router and top-k per row, per-sorted-row GEMM accumulation, the gather per token), so a pass
+ * computes exactly its rows.
+ *
+ * The expert buffers are addressed from zero, not `r0`: they are a pass tall and `sorted_tok` is
+ * pass-relative. Only step-tall operands (residual stream, normed input) carry the offset. */
+inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool own_ar) const {
+    /* `ne` is this rank's expert count, `ne_all` the model's: logits and top-k are model-wide,
+     * everything after the scatter is this rank's slice. */
     const int64_t ne = c.n_expert, ne_all = c.n_expert_all, k = c.top_k;
     const bool shared = op_sgate != 0;
 
     if (!ext_in) nq_h.step(c_, T, r0, rows);
 
-    /* THE SHARED ARM BESIDE THE ROUTED ONE, ON THE SAME QUEUE. It reads the same normed input the
-     * routed arm does and writes nothing the routed arm touches until the gather joins them, so
-     * each of its three stages is independent of the routed stage it is issued behind: its gate
-     * and gate_up beside the routed gate_up, its quantiser beside the routed one, its down beside
-     * the routed down. A recorded pass plays each such pair with the second launch unordered
-     * behind the first (Ctx::haz_mark), so the two run at once, and the next routed stage --
-     * which waits for everything in front of it -- waits for the shorter shared stage too, which
-     * has long finished. That is the overlap a second queue would buy, without the queue's fork and
-     * join: a barrier packet on each side of the arm, and a join on another queue's signal that
-     * the packet processor sees microseconds late. Every buffer the arm writes is out of the
-     * sharing pool (see declare), so issuing it ahead of its declared position moves no byte. */
+    /* The shared arm is interleaved with the routed arm on the same queue. It reads the same
+     * input and writes nothing the routed arm touches before the gather, so each of its stages
+     * (gate + gate_up, quantiser, down) is issued right behind the matching routed stage. A
+     * recorded pass leaves each such pair unordered (Ctx::haz_mark), so they overlap without a
+     * second queue's fork/join cost. The arm's buffers are excluded from sharing (see declare), so
+     * issuing them ahead of their declared position is safe. */
 
-    /* THE ROUTED ARM. */
-    /* THE NEXT ROUTED LAYER'S PREDICTION, from this router's input, read in place behind the router
-     * on the compute stream (rad_expert_prefetch). A failure there costs the prediction, nothing else. */
+    /* The routed arm. */
+    /* Predict the next routed layer's experts from this router's input, on the compute stream
+     * (rad_expert_prefetch). A failure only loses the prediction. */
     if (xp_next && xp_next->xp.n_parts > 0)
         (void)rad_expert_prefetch(c_, &xp_next->xp, w.h.x, r0, rows, g.n_embd);
-    /* THE COUNTS GO STRAIGHT INTO THE CORE'S ROW for this layer when it keeps one, so the
-     * report at the end of step() hands them over with no copy -- otherwise a card-local blit
-     * a routed layer, a whole dependent dispatch for a kilobyte. */
+    /* Write the routing counts straight into the core's row for this layer when it keeps one, so
+     * the report in step() needs no copy (otherwise a dependent blit per routed layer). */
     int32_t* const counts = rad_route_counts(c_, layer, ne);
     const RadOperand ecnt = counts ? praw(counts, RAD_I32, ne) : brows(w.ecnt, ne);
-    /* THE FUSED ROUTER where it resolved and the pass is within its rows: the router, the pair
-     * below and -- with `router_fused_gate` -- the shared gate, in one launch with the operands
-     * the three are handed. Otherwise the router and the pair, as declared. */
+    /* The fused router when it resolved and the pass fits: router, topk + scatter and (with
+     * `router_fused_gate`) the shared gate in one launch. Otherwise the separate ops. */
     const bool rfused = op_router_fused && rows <= router_fused_rows;
     if (rfused)
         RAD_ISSUE_N(c_, op_router_fused, rows, brow_slice(w.h.x, r0, rows, g.n_embd),
@@ -1574,10 +1423,9 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const
                     brows(w.sorted, rows * k), brows(w.eoff, ne + 1), ecnt,
                     router_fused_gate ? brow_slice(w.sgate, r0, rows, 1) : RAD_NONE);
     else
-    RAD_ISSUE_N(c_, op_router, rows, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_W(w_router),
-                brow_slice(w.logits, r0, rows, ne_all));
-    /* One launch or two. `w.ids` is the fused op's OUTPUT where it was the sort's input, and
-     * every other operand is the one the pair is handed. */
+        RAD_ISSUE_N(c_, op_router, rows, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_W(w_router),
+                    brow_slice(w.logits, r0, rows, ne_all));
+    /* topk + scatter fused, or the pair. In the fused op `w.ids` is an output. */
     if (rfused) {
         /* the fused router wrote all five */
     } else if (op_topk_scatter && rows <= topk_scatter_rows) {
@@ -1591,44 +1439,43 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const
                     brows(w.sorted, rows * k), brows(w.eoff, ne + 1), ecnt);
     }
 
-    /* The rotated re-quantisation of the same input, when the expert plane carries a
-     * rotation and the caller's read did not write it. Without a rotation the GEMM reads
-     * `h`'s pair. */
+    /* The rotated quantisation of the input, when the experts are rotated and the caller did not
+     * write it. Unrotated, the GEMM reads `h`'s pair. */
     const bool rot = c.expert_rot != 0;
     if (op_hq)
         RAD_ISSUE_N(c_, op_hq, rows, brow_slice(w.h.x, r0, rows, g.n_embd),
                     brow_slice(w.hr.q, r0, rows, g.n_embd),
                     brow_slice(w.hr.s, r0, rows, g.n_embd / RAD_FP8_BLOCK));
 
-    /* The two grouped GEMMs, and the weight tables: the FIRST handle of each run and its length.
-     * The runs are contiguous by construction -- see declare -- so `w_gu[q] + i` is expert
-     * 2 * i + q, and each parity is its own pair of table operands; at four classes expert
-     * 4 * i + q, class q holding ceil((n_reg - q) / 4). */
+    /* The grouped GEMMs. Each table is the first handle of its run and its length; runs are
+     * contiguous (see declare), so `w_gu[q] + i` is expert 2 * i + q, or 4 * i + q at four
+     * classes, where class q holds ceil((n_reg - q) / 4). */
     const int64_t n4[4] = { (n_reg + 3) / 4, (n_reg + 2) / 4, (n_reg + 1) / 4, n_reg / 4 };
-    /* The layer before predicted for this one: its copies go into the tables here, where they landed. */
+    /* Apply the previous layer's prefetch prediction: substitute the copied experts into the
+     * tables. */
     (void)rad_expert_prefetch_step(c_, layer);
     if (c.expert_bf16)
         RAD_ISSUE_N(c_, op_gu, rows, brow_slice(w.h.x, r0, rows, g.n_embd),
                     RAD_WTAB(w_gu[0], ne), brows(w.sorted, rows * k), brows(w.eoff, ne + 1),
                     brows(w.egu, rows * k));
     else if (ncls == 4)
-    RAD_ISSUE_N(c_, op_gu, rows,
-                brow_slice(rot ? w.hr.q : w.h.q, r0, rows, g.n_embd),
-                brow_slice(rot ? w.hr.s : w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK),
-                RAD_WTAB(w_gu[0], n4[0]), RAD_WTAB(w_gus[0], n4[0]),
-                brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1),
-                RAD_WTAB(w_gu[1], n4[1]), RAD_WTAB(w_gus[1], n4[1]),
-                RAD_WTAB(w_gu[2], n4[2]), RAD_WTAB(w_gus[2], n4[2]),
-                RAD_WTAB(w_gu[3], n4[3]), RAD_WTAB(w_gus[3], n4[3]),
-                brows(w.egu, rows * k));
+        RAD_ISSUE_N(c_, op_gu, rows,
+                    brow_slice(rot ? w.hr.q : w.h.q, r0, rows, g.n_embd),
+                    brow_slice(rot ? w.hr.s : w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK),
+                    RAD_WTAB(w_gu[0], n4[0]), RAD_WTAB(w_gus[0], n4[0]),
+                    brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1),
+                    RAD_WTAB(w_gu[1], n4[1]), RAD_WTAB(w_gus[1], n4[1]),
+                    RAD_WTAB(w_gu[2], n4[2]), RAD_WTAB(w_gus[2], n4[2]),
+                    RAD_WTAB(w_gu[3], n4[3]), RAD_WTAB(w_gus[3], n4[3]),
+                    brows(w.egu, rows * k));
     else
-    RAD_ISSUE_N(c_, op_gu, rows,
-                brow_slice(rot ? w.hr.q : w.h.q, r0, rows, g.n_embd),
-                brow_slice(rot ? w.hr.s : w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK),
-                RAD_WTAB(w_gu[0], n_reg / 2), RAD_WTAB(w_gus[0], n_reg / 2),
-                brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1),
-                RAD_WTAB(w_gu[1], n_reg / 2), RAD_WTAB(w_gus[1], n_reg / 2),
-                brows(w.egu, rows * k));
+        RAD_ISSUE_N(c_, op_gu, rows,
+                    brow_slice(rot ? w.hr.q : w.h.q, r0, rows, g.n_embd),
+                    brow_slice(rot ? w.hr.s : w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK),
+                    RAD_WTAB(w_gu[0], n_reg / 2), RAD_WTAB(w_gus[0], n_reg / 2),
+                    brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1),
+                    RAD_WTAB(w_gu[1], n_reg / 2), RAD_WTAB(w_gus[1], n_reg / 2),
+                    brows(w.egu, rows * k));
     if (shared) shared_up(c_, T, r0, rows, rfused && router_fused_gate);
     gq_exp.step(c_, w.egu, rows * k, 0, rows * k);
     if (shared) gq_sh.step(c_, w.sgu, T, r0, rows);
@@ -1636,26 +1483,26 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const
         RAD_ISSUE_N(c_, op_dn, rows, brows(w.eff.x, rows * k), RAD_WTAB(w_dn[0], ne),
                     brows(w.sorted, rows * k), brows(w.eoff, ne + 1), brows(w.edn, rows * k));
     else if (ncls == 4)
-    RAD_ISSUE_N(c_, op_dn, rows,
-                brows(w.eff.q, rows * k), brows(w.eff.s, rows * k),
-                RAD_WTAB(w_dn[0], n4[0]), RAD_WTAB(w_dns[0], n4[0]),
-                brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1),
-                RAD_WTAB(w_dn[1], n4[1]), RAD_WTAB(w_dns[1], n4[1]),
-                RAD_WTAB(w_dn[2], n4[2]), RAD_WTAB(w_dns[2], n4[2]),
-                RAD_WTAB(w_dn[3], n4[3]), RAD_WTAB(w_dns[3], n4[3]),
-                brows(w.edn, rows * k));
+        RAD_ISSUE_N(c_, op_dn, rows,
+                    brows(w.eff.q, rows * k), brows(w.eff.s, rows * k),
+                    RAD_WTAB(w_dn[0], n4[0]), RAD_WTAB(w_dns[0], n4[0]),
+                    brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1),
+                    RAD_WTAB(w_dn[1], n4[1]), RAD_WTAB(w_dns[1], n4[1]),
+                    RAD_WTAB(w_dn[2], n4[2]), RAD_WTAB(w_dns[2], n4[2]),
+                    RAD_WTAB(w_dn[3], n4[3]), RAD_WTAB(w_dns[3], n4[3]),
+                    brows(w.edn, rows * k));
     else
-    RAD_ISSUE_N(c_, op_dn, rows,
-                brows(w.eff.q, rows * k), brows(w.eff.s, rows * k),
-                RAD_WTAB(w_dn[0], n_reg / 2), RAD_WTAB(w_dns[0], n_reg / 2),
-                brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1),
-                RAD_WTAB(w_dn[1], n_reg / 2), RAD_WTAB(w_dns[1], n_reg / 2),
-                brows(w.edn, rows * k));
-    /* This layer's streamed experts are read: the next one's copies cross the link from here. */
+        RAD_ISSUE_N(c_, op_dn, rows,
+                    brows(w.eff.q, rows * k), brows(w.eff.s, rows * k),
+                    RAD_WTAB(w_dn[0], n_reg / 2), RAD_WTAB(w_dns[0], n_reg / 2),
+                    brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1),
+                    RAD_WTAB(w_dn[1], n_reg / 2), RAD_WTAB(w_dns[1], n_reg / 2),
+                    brows(w.edn, rows * k));
+    /* This layer's streamed experts are consumed; the next layer's copies may start. */
     (void)rad_expert_prefetch_mark(c_);
-    /* THE PROTECTED EXPERTS, over the trailing run of the offsets: their sorted rows are the
-     * ones the quantised down GEMM above zeroed as past its live count, and the down GEMM
-     * here writes them -- after it, which the shared `edn` orders. */
+    /* The protected experts, over the trailing offsets: the quantised down GEMM zeroed their
+     * sorted rows as past its live count, and this down GEMM writes them afterwards (ordered by
+     * the shared `edn`). */
     if (op_pgu) {
         const int64_t np = (int64_t)prot.size();
         const RadOperand poff = brow_slice(w.eoff, n_reg, np + 1, 1);
@@ -1667,13 +1514,11 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const
                     brows(w.sorted, rows * k), poff, brows(w.edn, rows * k));
     }
     if (shared) sh_down.step(c_, w.sff, w.sout, T, r0, rows);
-    /* THE CALIBRATION TAP, issued between the two GEMMs' inputs being written and the pass
-     * ending. It reads exactly the operands the GEMMs above read and writes nothing they
-     * touch, so removing it changes no number the model produces -- which is the property
-     * that lets a calibration run be compared against a serving one. */
+    /* The calibration tap reads the GEMMs' operands and writes nothing they touch, so it does not
+     * change the model's output. */
     if (op_gram_gu && !calib_done) {
         if (calib_rows == 0) {
-            /* The accumulators are arena memory and arrive holding whatever was there. */
+            /* The accumulators are arena memory, so zero them first. */
             rad_memset_async(rad_buf_ptr(c_, b_gram_gu), 0,
                              g.n_embd * g.n_embd * 4, rad_stream(c_));
             rad_memset_async(rad_buf_ptr(c_, b_gram_dn), 0,
@@ -1709,12 +1554,12 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const
             if (layer == 0)
                 std::fprintf(stderr, "radiance: calibration wrote layer Hessians after %lld "
                                      "tokens to %s%s\n", calib_rows, calib_dir(),
-                             (a && bb && ce) ? "" : " (WITH ERRORS)");
+                             (a && bb && ce) ? "" : ", with errors");
         }
     }
 
-    /* THE GATHER LAST, because with the fold it reads the arm. Its operands are the routed slots
-     * plus `sout` and `sgate`, and it writes the block's delta straight into `h.x`. */
+    /* The gather last, since with the fold it reads the shared arm (`sout`, `sgate`); it writes
+     * the block's delta into `h.x`. */
     if (!gather_taken(g, T, gather_out_rows, gather_out_rows6))
         RAD_ISSUE_N(c_, op_gather, rows, brows(w.edn, rows * k), brow_slice(w.ew, r0, rows, k),
                     brows(w.sorted, rows * k),
@@ -1722,22 +1567,20 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const
                     gfold ? brow_slice(w.sgate, r0, rows, 1) : RAD_NONE,
                     brow_slice(w.h.x, r0, rows, g.n_embd));
 
-    /* A write that takes the all-reduce does it ONCE over the whole step, so it answers on T and
-     * this pass has to ask the same question of the same T, not of its own rows. */
-    if (op_ar && !ar_taken(g, ar_out_take != kArOutNorm ? T : rows, ar_out, ar_out_take))
-        RAD_ISSUE_N(c_, op_ar, rows * g.n_embd, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_NONE);
+    /* A write that takes the all-reduce does it once for the whole step, deciding on T, so this
+     * pass must ask with T, not its own rows. */
+    if (own_ar && issues_ar(T, rows)) issue_ar(c_, r0, rows, false);
     if (op_add)
         RAD_ISSUE_N(c_, op_add, rows, brow_slice(w.x, r0, rows, g.n_embd),
                     brow_slice(w.h.x, r0, rows, g.n_embd),
                     brow_slice(w.x, r0, rows, g.n_embd));
 }
 
-/* ONE PASS OF THE PER-EXPERT TAP. The expert offsets the scatter wrote decide how many launches
- * there are and where each reads, so they come back first; then the scratch is zeroed, each
- * routed expert's run of the `slots` sorted rows is summed into its square, and the scratch comes
- * back to be added on the host. Both syncs are on the block's own stream, with nothing issued
- * after the tap, so every op the scratch could share storage with is finished before it is
- * written and none is issued until it has been read. */
+/* One pass of the per-expert tap. The scatter's expert offsets are copied back first (they decide
+ * the launches); then the scratch is zeroed, each expert's run of the `slots` sorted rows is summed
+ * into its square, and the scratch is copied back and added on the host. Both syncs are on the
+ * block's stream with nothing issued after the tap, so the transient scratch never overlaps a live
+ * buffer's use. */
 inline void MoeFP8::calib_experts_pass(RadCtx* c_, int64_t slots) const {
     if (calib_dne_failed) return;
     const int64_t ne = c.n_expert, K = c.n_ff_exp;
@@ -1786,22 +1629,19 @@ inline void MoeFP8::step_rows(RadCtx* c_, int64_t T) const {
         const int64_t n = (T - r0 < c.rows) ? (T - r0) : c.rows;
         pass(c_, T, r0, n);
     }
+    route_report(c_);
+}
 
-    /* ---- THE HANDOFF TO THE HEAT ENGINE, and it is a handoff and not a computation: the buffers
-     * below were written by ops this block already issued. `rad_route_report` copies the histogram
-     * back ASYNCHRONOUSLY and the heat engine consumes it on the NEXT step, so nothing here blocks
-     * the compute stream (spec §5.5). Without it the expert-tiered placement has no measurement to
-     * promote on, and every expert stays wherever the warm start put it.
+inline void MoeFP8::route_report(RadCtx* c_) const {
+    /* ---- Hand the routing to the heat engine. `rad_route_report` copies the histogram back
+     * asynchronously and the engine consumes it next step, so the compute stream is not blocked
+     * (spec §5.5). Without it, expert-tiered placement has nothing to promote on.
      *
-     * IT REPORTS THE LAST PASS, which on the shipped configuration is the whole step: `c.rows`
-     * defaults to the prefill chunk, so there is one pass. A deployment that raises the chunk past
-     * it gets the last pass's histogram -- a sample of the step rather than the whole of it, which
-     * is what the heat engine wants anyway (it is a popularity estimate consumed a step late).
+     * It reports the last pass, which is the whole step by default (`c.rows` is the prefill
+     * chunk). With more passes it is a sample, adequate for a popularity estimate.
      *
-     * `expert_w` IS LEFT NULL rather than filled: RadRouting declares it `const float*` and this
-     * block's routing weights are bf16, which is what the gather multiplies. Nothing in the core
-     * reads the field -- the heat engine takes `expert_count` -- and handing it a bf16 plane under
-     * a float pointer would be a lie that survives until something does. */
+     * `expert_w` stays null: RadRouting declares it `const float*` but these weights are bf16.
+     * Nothing in the core reads it (the heat engine uses `expert_count`). */
     moe_debug_weights(c_, layer, c.top_k, w.ids, w.ew);
     RadRouting r{};
     r.expert_ids    = (const int32_t*)rad_buf_ptr(c_, w.ids);
diff --git a/arch/common/rad_block_mtp_fp8.h b/arch/common/rad_block_mtp_fp8.h
index 9a9f739b..c571d451 100644
--- a/arch/common/rad_block_mtp_fp8.h
+++ b/arch/common/rad_block_mtp_fp8.h
@@ -2,109 +2,89 @@
  *
  * ============================== WHAT IT IS ==============================
  *
- * Qwen3.5 / Qwen3-Next ship ONE extra transformer layer beside the trunk, under an `mtp.` prefix
- * of its own, whose job is to predict token i+2 from the trunk's hidden state at i and the
- * embedding of the token at i+1. It is the drafter for speculative decoding, and it is a drafter
- * with no second checkpoint: the embedding table and the lm_head are the trunk's
- * (`mtp_use_dedicated_embeddings: false`, and no `mtp.lm_head` in the file).
+ * Qwen3.5 / Qwen3-Next ship one extra transformer layer under an `mtp.` prefix that predicts
+ * token i+2 from the trunk's hidden state at i and the embedding of token i+1. It is the
+ * speculative-decoding drafter; the embedding table and lm_head are the trunk's
+ * (`mtp_use_dedicated_embeddings: false`, no `mtp.lm_head`).
  *
- * THE INDEXING IS THE WHOLE THING, so it is stated once here and everything else follows:
+ * Indexing:
  *
  *     head index i    reads  hidden(i) and embed(token at i + 1)
  *                     writes its K and V at KV position i, with rope position i
  *                     predicts the token at i + 2
  *
- * That is DeepSeek-V3's MTP layout, which this family follows: the head's transformer block runs
- * over the SAME position indices as the trunk, and the shift lives entirely in which token gets
- * embedded. Getting it off by one costs nothing visible -- the drafts are simply wrong and the
- * acceptance rate collapses, while the model's own output stays exactly correct.
+ * This is DeepSeek-V3's MTP layout: the head runs over the trunk's position indices and the shift
+ * is only in which token is embedded. An off-by-one shows only as collapsed acceptance.
  *
- * The forward is short and every piece of it already exists in this library:
+ * The forward:
  *
  *     h = gather(the trunk's final hidden states, at the rows this pass continues from)
  *     e = embed(the token one position on)
  *     x = fc( concat( pre_fc_norm_embedding(e), pre_fc_norm_hidden(h) ) )
  *     x = one gated-GQA layer + one SwiGLU feed-forward, over x            <- AttnGatedFP8, MlpFP8
  *     h'= mtp.norm(x)
- *     logits = the TRUNK's lm_head over h'
+ *     logits = the trunk's lm_head over h'
  *
- * and h' is BOTH the logits input and the `h` of the next draft round. That is the reference's
- * shape too: a Qwen3-Next MTP forward returns one tensor and the proposer feeds the same tensor
- * back, unlike an EAGLE head which returns a (normed, unnormed) pair.
+ * h' is both the logits input and the next round's `h`, as in the reference (a Qwen3-Next MTP
+ * forward returns one tensor; an EAGLE head returns a (normed, unnormed) pair).
  *
  * ============================== THE TWO KINDS OF PASS ==============================
  *
- * RadBatch::draft_pass says which, and the sign is the whole distinction:
+ * By the sign of RadBatch::draft_pass:
  *
- *   < 0   A HISTORY PASS, one row a token, gathering the trunk's hidden states. It exists
- *         because the head's attention reads its OWN K and V for every earlier position, and
- *         nothing else in the engine writes those: the trunk's prefill fills layers 0..n-1 and
- *         leaves the head's layer untouched. Without it the head attends to whatever the pool
- *         last held, which is not wrong output -- a bad draft is only a rejected draft -- but it
- *         is a drafter that proposes noise. The scheduler runs one over the positions the last
- *         step added, the verified ones included.
+ *   < 0   History pass, one row per token, gathering the trunk's hidden states. The head's
+ *         attention reads its own K and V for every earlier position, which the trunk's prefill
+ *         does not write; without this pass the head attends to stale pool contents and proposes
+ *         noise. The scheduler runs it over the positions the last step added, verified ones
+ *         included.
  *
- *         It is also DRAFT ROUND 1 for every sequence that drafts: that sequence's last history
- *         row is the committed position with the token the trunk chose after it -- round 1's
- *         whole input -- so the pass ends in the lm_head over those rows (RadBatch::draft_out_ids)
- *         and leaves the head's output at them where round 2 reads it.
+ *         It is also draft round 1 for every drafting sequence: its last history row is the
+ *         committed position plus the token the trunk chose after it, so the pass ends in the
+ *         lm_head over those rows (RadBatch::draft_out_ids) and leaves the head's output there
+ *         for round 2.
  *
- *   > 1   A DRAFT ROUND, one row a sequence, reading the head's own output from the round before,
- *         which is already in the same buffer. Every round ends in the lm_head, because a draft is
- *         a token. There is no round-1 pass; the history pass is it.
+ *   > 1   Draft round, one row per sequence, reading the previous round's output from the same
+ *         buffer and ending in the lm_head. There is no separate round-1 pass.
  *
- * ============================== WHAT IS AND IS NOT FP8 ==============================
+ * ============================== PRECISION ==============================
  *
- * Read off mtp.safetensors rather than assumed, exactly as qwen35_fp8.cpp reads the trunk:
+ * As stored in mtp.safetensors:
  *
  *   F8_E4M3 + scale   layers.0.self_attn.{q,k,v,o}_proj, layers.0.mlp.{gate,up,down}_proj
  *   BF16, no scale    fc, norm, pre_fc_norm_embedding, pre_fc_norm_hidden, and every norm inside
  *                     the layer
  *
- * `fc` is [5120, 10240] and bf16, so it is a plain `gemm_nt`, issued ONCE over the whole chunk.
- * libr4d's bf16 GEMM row for this shape is C_LE("M", 65536) and K here is 10240, a multiple of 16,
- * so the wide row serves the whole chunk in one launch. That matters because the history pass runs
- * one row a TOKEN over a whole prefill chunk: banding this at 64 and slicing it would be dozens of
- * launches a chunk for a GEMM whose traffic is microseconds.
+ * `fc` ([5120, 10240], bf16) is a plain `gemm_nt` issued once over the whole chunk: libr4d's bf16
+ * row is C_LE("M", 65536) and K = 10240 is a multiple of 16. The history pass has one row per
+ * token of a prefill chunk, so slicing at 64 would cost dozens of launches.
  *
  * ============================== THE CONCAT ORDER ==============================
  *
- * `fc` reads 10240 columns and the two halves are the normed embedding and the normed hidden
- * state. WHICH HALF IS FIRST IS NOT IN THE CHECKPOINT: both orders are one contiguous [5120,10240]
- * matrix and no shape, name or dtype distinguishes them. DeepSeek-V3's MTP -- the design this one
- * follows -- concatenates `enorm(embedding)` then `hnorm(hidden)`, and that is the order here.
- *
- * Both readings are self-consistent, libref shares whichever one the graph picks, and no per-op
- * oracle can reach it -- but it has a CHEAP EMPIRICAL ANSWER, the draft acceptance rate. A head
- * wired the right way round accepts most of what it proposes; wired the wrong way round it
- * proposes noise and accepts nothing, while the model's own output stays perfectly correct
- * because a rejected draft costs only time.
+ * `fc` reads the normed embedding and the normed hidden state concatenated. The order is not in
+ * the checkpoint (both are one [5120, 10240] matrix); this follows DeepSeek-V3's MTP:
+ * `enorm(embedding)` then `hnorm(hidden)`. Per-op checks cannot tell the orders apart; the draft
+ * acceptance rate does (the wrong order accepts almost nothing).
  *
  * ============================== THE NORM GAINS ==============================
  *
- * GemmaRMSNorm's `1 + w` (Geom::wadd) applies here and the checkpoint proves it rather than
- * suggesting it: pre_fc_norm_hidden sits at -0.06 .. -0.24 and pre_fc_norm_embedding at
- * -0.27 .. -0.61 -- NEGATIVE gains, which only `1 + w` explains. `mtp.norm` sits at 0.59 .. 1.31,
- * which reads as either, so it takes the same `final_wadd` the trunk's output norm takes -- one
- * question, asked once, answered in one place.
+ * GemmaRMSNorm's `1 + w` (Geom::wadd) applies: pre_fc_norm_hidden is -0.06 .. -0.24 and
+ * pre_fc_norm_embedding -0.27 .. -0.61, negative gains that only `1 + w` explains. `mtp.norm`
+ * (0.59 .. 1.31) is ambiguous, so it takes the trunk output norm's `final_wadd`.
  *
  * ============================== THE KV CACHE ==============================
  *
- * The head's attention layer is bound to the TRUNK'S full-attention group as one more layer, at
- * absolute index n_main. Two reasons, and neither is thrift:
+ * The head's attention is bound to the trunk's full-attention group as one more layer, at
+ * absolute index n_main:
  *
- *   - the slot mapping and the block table are the trunk's. The head writes its K and V at the
- *     slot the trunk's token for that position occupies, so a rejected draft's entry is
- *     overwritten by the next step's correct token AT THE SAME ADDRESS. Draft rounds run in
- *     position order and each writes its own position before attending to it, so there is no
- *     rollback to get wrong -- which is why vLLM's EAGLE/MTP proposer needs no second block
- *     manager either.
- *   - a second group would need its own page geometry, its own free list and its own eviction,
- *     for a cache one seventeenth the size of the one already there.
+ *   - It shares the trunk's slot mapping and block table, writing K and V at the slot of the
+ *     trunk's token for that position. A rejected draft's entry is overwritten by the next step's
+ *     correct token at the same address, and each round writes its position before attending to
+ *     it, so no rollback is needed (as in vLLM's EAGLE/MTP proposer).
+ *   - A second group would need its own page geometry, free list and eviction for a cache one
+ *     seventeenth the size.
  *
- * The cost is that the group's page grows from 16 layers to 17 -- 6% more attention KV -- and it
- * is paid only when the deployment declares speculation, because that is when the head is
- * declared at all.
+ * The group's page grows from 16 layers to 17 (6% more attention KV), only when speculation is
+ * declared.
  */
 #ifndef RAD_BLOCK_MTP_FP8_H
 #define RAD_BLOCK_MTP_FP8_H
@@ -113,20 +93,16 @@
 #include "rad_block_mlp_fp8.h"
 #include "rad_block_vit.h"
 
-#include 
-
 namespace rad {
 namespace arch {
 
-/* THE 2-BIT DRAFT HEAD IS A WEIGHT THE MODEL HOLDS OR DOES NOT. `head` is the lm_head under a name
- * of its own, which a recipe quantises to the 2-bit grid -- u2 codes, an f16 scale and a u8 zero a
- * group of 128 -- so one checkpoint tensor makes two logical weights. This declares its name map
- * (to `lm`, the checkpoint's head) and answers whether the model holds it at two bits, which is
- * when the draft rounds read it. A checkpoint served as it stands, or a container converted
- * without the rule, holds the bf16 head alone, and the draft rounds read that.
+/* Declares the name map of the 2-bit draft head `head` (the checkpoint lm_head `lm` under its own
+ * name, quantised by a recipe to u2 codes with an f16 scale and u8 zero per group of 128) and
+ * returns whether the model holds it at two bits. If not (no such recipe), draft rounds read the
+ * bf16 head.
  *
- * Called ONCE, by the plugin, before it declares the head's buffers -- a name map is declared once
- * -- and the block reads the answer back from whether those buffers exist. */
+ * Called once by the plugin, before it declares the head's buffers; the block infers the answer
+ * from whether those buffers exist. */
 inline bool mtp_draft_head_q2(RadBuilder* b, const char* head, const char* lm) {
     if (!head || !lm) return false;
     if (map_copy(b, head, lm) < 0) return false;
@@ -134,41 +110,34 @@ inline bool mtp_draft_head_q2(RadBuilder* b, const char* head, const char* lm) {
     return weight_enc(b, head, &e) && e.n_planes > 0 && e.plane[0].dtype == RAD_U2;
 }
 
-/* TEMPLATED ON THE FEED-FORWARD, because the head is a TRUNK LAYER and a trunk layer's
- * feed-forward is dense in one member of this family and routed in the next. Qwen3.6-35B-A3B's
- * `mtp.layers.0` carries `mlp.experts.*`, `mlp.gate` and a shared expert, exactly as its trunk
- * layers do; a head hard-wired to MlpFP8 could not declare it, and the model would have a
- * container with a drafter in it and no way to run one.
- *
- * `Ffn` is MlpFP8 or MoeFP8. Both take the same declare() arity over their own Wire and Src -- the
- * MoE block's Config travels inside its Src for exactly this reason -- so nothing below has to
- * know which one it has. */
+/* Templated on the feed-forward, since the head mirrors a trunk layer, which is dense or routed
+ * by model (Qwen3.6-35B-A3B's `mtp.layers.0` has `mlp.experts.*`, `mlp.gate` and a shared expert).
+ * `Ffn` is MlpFP8 or MoeFP8; both have the same declare() signature over their own Wire and Src
+ * (MoeFP8's Config travels inside its Src for this reason). */
 template 
 struct MtpBlockFP8 {
     struct Wire {
-        /* [max_tok, n_embd] the TRUNK's final hidden states for the step just run -- the plugin's
-         * `h`, which gather_rows already reads for the trunk's own logits. A pass names the rows
-         * it wants through out_ids and never has to know how they were laid out. */
+        /* [max_tok, n_embd] the trunk's final hidden states for the step just run (the plugin's
+         * `h`). A pass names the rows it wants through out_ids. */
         rad_buf src    = 0;
-        /* [max_tok, n_embd] IN: the hidden state this pass predicts from. OUT: the head's own,
-         * which is the next draft round's input. Sized for a whole prefill chunk because a
-         * history pass is one row a token. */
+        /* [max_tok, n_embd] in: the hidden state this pass predicts from; out: the head's own,
+         * the next round's input. Sized for a prefill chunk (history passes are one row per
+         * token). */
         rad_buf hout   = 0;
         rad_buf e      = 0;   /* [max_tok, n_embd]      the input token's embedding */
         rad_buf c      = 0;   /* [max_tok, 2 * n_embd]  the two normed halves, fc's input */
         rad_buf x      = 0;   /* [max_tok, n_embd]      the head's own residual stream */
         rad_buf logits = 0;   /* [max_logit_rows, n_vocab]  the trunk's, shared */
-        /* THE 2-BIT DRAFT HEAD's working set -- see the block comment at op_dlogits. Every one of
-         * these is a draft round's, so they are sized at max_logit_rows and not at max_tok: a
-         * history pass never reaches any of them. */
+        /* The 2-bit draft head's working set (see op_dlogits), sized at max_logit_rows: only
+         * drafting rows reach it. */
         rad_buf dq   = 0;   /* [max_logit_rows, n_embd]   int8 codes */
         rad_buf ds   = 0;   /* [max_logit_rows, 1]        f32, one scale a row */
-        rad_buf dsum = 0;   /* [n_embd/group, mpad]       f32, GROUP-major (quant_act_i8's asum) */
+        rad_buf dsum = 0;   /* [n_embd/group, mpad]       f32, group-major (quant_act_i8's asum) */
         rad_buf dlog = 0;   /* [max_logit_rows, n_vocab]  bf16, the coarse logits */
         rad_buf didx = 0;   /* [max_logit_rows, 1]        i32, the proposed token */
         rad_buf dval = 0;   /* [max_logit_rows, 1]        f32, its logit */
-        /* The layer's working set is the TRUNK's -- those buffers are dead by the time any of
-         * this runs, and a second set would be 150 MiB of activation planes for one layer. */
+        /* The layer reuses the trunk's working set, which is dead by the time the head runs (a
+         * second set would be 150 MiB). */
         AttnGatedFP8::Wire attn{};
         typename Ffn::Wire mlp{};
     };
@@ -178,9 +147,8 @@ struct MtpBlockFP8 {
         const char* norm               = nullptr;
         const char* pre_norm_hidden    = nullptr;
         const char* pre_norm_embedding = nullptr;
-        /* The checkpoint's lm_head, again. The trunk maps it as `output.weight`; the draft head is
-         * a second logical weight over the SAME tensor, which the recipe quantises to 2-bit codes
-         * (mtp_draft_head_q2). One source, two weights, no second checkpoint tensor. */
+        /* The checkpoint's lm_head. The trunk maps it as `output.weight`; the draft head is a
+         * second logical weight over the same tensor, quantised to 2 bits (mtp_draft_head_q2). */
         const char* lm                 = nullptr;
         AttnGatedFP8::Src attn{};
         typename Ffn::Src mlp{};
@@ -188,8 +156,8 @@ struct MtpBlockFP8 {
 
     Geom       g{};
     Wire       w{};
-    int        layer   = 0;    /* ABSOLUTE, so the KV group's layer_slot lookup finds it */
-    int64_t    rows    = 0;    /* the widest pass: one row a token of a prefill chunk */
+    int        layer   = 0;    /* absolute, for the KV group's layer_slot lookup */
+    int64_t    rows    = 0;    /* the widest pass: one row per token of a prefill chunk */
     int64_t    off_e = 0, off_h = 0;   /* the two halves' column offsets inside `c` */
     rad_weight w_tok = 0, w_lm = 0, w_fc = 0, w_norm = 0, w_pre_h = 0, w_pre_e = 0;
     rad_weight w_dh = 0, w_dhs = 0;    /* the 2-bit lm_head and its (scale, zero) plane */
@@ -197,9 +165,9 @@ struct MtpBlockFP8 {
     AttnGatedFP8 attn{};
     Ffn          mlp{};
     rad_op     op_gather = 0, op_embed = 0, op_embed_ar = 0, op_pre_h = 0, op_pre_e = 0, op_fc = 0;
-    /* THE PROMPT'S MEDIA ROWS over the head's own embedding: its history pass embeds the prompt
-     * too, one position on, and an image token's embedding is the encoder's there as well. Set
-     * `media` before declare when the program has an encoder. */
+    /* Media rows over the head's embedding: the history pass embeds the prompt too (one position
+     * on), and an image token's embedding comes from the encoder. Set `media` before declare when
+     * the program has an encoder. */
     bool       media = false;
     MediaRows  mrows{};
     rad_op     op_norm = 0, op_dsel = 0, op_dback = 0, op_logits = 0;
@@ -220,14 +188,12 @@ inline int MtpBlockFP8::declare(RadBuilder* b, Names& nm, const Geom& geom,
     rows = g.max_tok;
     if (rows <= 0 || !w_tok || !w_lm) return RAD_E_INVAL;
 
-    /* The normed embedding first, then the normed hidden state; see THE CONCAT ORDER above. */
+    /* The normed embedding first, then the normed hidden state (see the header). */
     off_e = 0;
     off_h = g.n_embd;
 
-    /* The head's own weights. SHARD_NONE on all four: three are per-channel norms over the
-     * residual stream, which is replicated, and `fc` reads and writes that same stream -- a
-     * column-sharded fc would need an all-reduce to buy 52 MiB a rank back, which is the wrong
-     * side of the trade at one GEMM per draft round. */
+    /* The head's own weights, all replicated: three norms over the replicated stream, and `fc`,
+     * which column-sharded would save 52 MiB per rank at the cost of an all-reduce per round. */
     RAD_ARCH_TRY(map_copy(b, nm.f("mtp.pre_fc_norm_hidden.weight"),    src.pre_norm_hidden));
     RAD_ARCH_TRY(map_copy(b, nm.f("mtp.pre_fc_norm_embedding.weight"), src.pre_norm_embedding));
     RAD_ARCH_TRY(map_copy(b, nm.f("mtp.norm.weight"),                  src.norm));
@@ -242,9 +208,8 @@ inline int MtpBlockFP8::declare(RadBuilder* b, Names& nm, const Geom& geom,
     w_fc    = decl_w(b, nm.f("mtp.fc.weight"), RAD_BF16, {g.n_embd, 2 * g.n_embd},
                      RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
 
-    /* A SECOND gather_rows and a SECOND embed_lookup, over the trunk's own buffers and weights.
-     * They are separate ops rather than re-issues of the trunk's because an op's read and write
-     * sets are what the buffer planner reads for liveness, and these write somewhere else. */
+    /* Separate gather_rows and embed_lookup ops over the trunk's buffers and weights, because
+     * they write different buffers and liveness comes from each op's read/write sets. */
     op_gather = rw(b, RAD_OP(b, "gather_rows",
                        RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
                                   RAD_STR("dtype", g.dtype)),
@@ -257,9 +222,8 @@ inline int MtpBlockFP8::declare(RadBuilder* b, Names& nm, const Geom& geom,
                      RAD_WEIGHTS(w_tok)),
                  {}, {w.e});
     if (media) RAD_ARCH_TRY(mrows.declare(b, rows, g.n_embd, w.e));
-    /* The trunk's table is vocab-sharded, so this gather is a partial one and needs the same
-     * exact reduction the trunk does. Its own op rather than the trunk's because it writes a
-     * different buffer, which is the rule the gather above states. */
+    /* The trunk's table is vocab-sharded, so the lookup is partial and needs an exact
+     * all-reduce. */
     if (g.world > 1)
         op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
                             RAD_PARAMS(RAD_INT("world_size", g.world),
@@ -289,11 +253,10 @@ inline int MtpBlockFP8::declare(RadBuilder* b, Names& nm, const Geom& geom,
 
     RAD_ARCH_TRY(attn.declare(b, nm, g, l, kv, rotary_dim, w.attn, src.attn));
 
-    /* DRAFT ROUND 1'S ROWS OUT OF A HISTORY PASS (RadBatch::draft_out_ids), one a drafting
-     * sequence in round order, to the front of the residual stream `x` -- before the feed-forward,
-     * which then runs over those rows alone. Through `hout`, which is dead from the fc's read to
-     * the norm's write, because a gather in place could overwrite a row another sequence has yet to
-     * read. */
+    /* Moves round 1's rows of a history pass (RadBatch::draft_out_ids, one per drafting sequence)
+     * to the front of `x` before the feed-forward, which then runs on those rows only. Goes through
+     * `hout` (dead between fc's read and the norm's write), since an in-place gather could
+     * overwrite a row not yet read. */
     op_dsel = rw(b, RAD_OP(b, "gather_rows",
                     RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
                                RAD_STR("dtype", g.dtype)),
@@ -315,8 +278,8 @@ inline int MtpBlockFP8::declare(RadBuilder* b, Names& nm, const Geom& geom,
                      RAD_WEIGHTS(w_norm)),
                  {w.x}, {w.hout});
 
-    /* The trunk's lm_head, over the head's hidden state. Banded at the logits buffer's own extent
-     * rather than at `rows`: it runs over one row a drafting sequence. */
+    /* The trunk's lm_head over the head's hidden state, banded at the logits buffer's extent: it
+     * runs over one row per drafting sequence. */
     op_logits = rw(b, RAD_OP(b, "logits_gemm",
                       RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
                                  RAD_INT("n_vocab", g.n_vocab),
@@ -324,47 +287,31 @@ inline int MtpBlockFP8::declare(RadBuilder* b, Names& nm, const Geom& geom,
                       RAD_WEIGHTS(w_lm)),
                   {w.hout}, {w.logits});
 
-    /* ---- THE 2-BIT DRAFT HEAD -------------------------------------------------------------
+    /* ---- The 2-bit draft head.
      *
-     * `logits_gemm` IS ALREADY AT THE MEMORY ROOFLINE for the bf16 lm_head's 2.54 GB, so the only
-     * lever it has is FEWER BYTES. That matters here and not at the trunk, because a speculative
-     * step runs the projection THREE times: once to verify, and once per draft round.
+     * `logits_gemm` is at the memory roofline for the bf16 lm_head's 2.54 GB, and a speculative
+     * step runs the projection once to verify plus once per draft round. Drafts are verified by the
+     * exact head, so a coarser draft head costs only acceptance, never an emitted token.
      *
-     * The two draft ones do not need the exact distribution. A draft is a PROPOSAL; the target
-     * verifies every one of them with its own untouched bf16 head, and speculative decoding is
-     * distribution-preserving -- so a worse draft costs ACCEPTANCE and cannot change a token the
-     * model emits. That is the one place in the step where precision buys throughput outright.
+     * The draft rounds read a 2-bit copy: 318 MB of codes and 40 MB of (scale, zero) dwords, an
+     * eighth of the traffic. libr4d's `gemm_w2a8_nt` takes codes and the scale/zero planes as two
+     * operands, laid out as `r4d.w2a8.frag.g128` at load (libr4d/r4d_layout.cpp). The grid is
+     * asymmetric (four levels are too few for a symmetric one), so the activation side uses
+     * `quant_act_i8`'s three-output form, whose per-group row sums subtract the stored zero.
      *
-     * So the drafter reads a 2-bit copy: 318 MB of codes and 40 MB of (scale, zero) dwords against
-     * 2.54 GB, an eighth of the traffic. It is a logical weight of its own over the checkpoint's
-     * head (mtp_draft_head_q2), quantised by the recipe; libr4d's `gemm_w2a8_nt` takes its codes
-     * and its scale and zero planes as two operands and lays them out as `r4d.w2a8.frag.g128` at
-     * load (libr4d/r4d_layout.cpp). The grid is asymmetric -- four levels are not enough for a
-     * symmetric one -- which is why the activation side is `quant_act_i8`'s three-output form: the
-     * per-group row sums are what subtract the stored zero.
-     *
-     * AND IT DOES NOT GO THROUGH THE SAMPLER. The 2-bit GEMM writes bf16 and the sampler's chain
-     * reads the f32 logits plane, so a draft round would need a cast of a 248K-wide row to reach
-     * it -- for an argmax. `row_topk` at R=1 is that argmax, on the bf16 the GEMM already wrote,
-     * and the engine reads the proposed id straight out of `didx`. The trunk's logits plane is
-     * left alone, which is also what lets a draft round sample nothing at all.
+     * The draft head bypasses the sampler, which reads f32 logits: `row_topk` at R=1 takes the
+     * argmax on the GEMM's bf16 output and the engine reads the id from `didx`. The trunk's logits
+     * plane is untouched.
      */
     enum { MTP_W2_GROUP = 128 };      /* libr4d's R4D_GEMM_W2A8_GROUP, and the layout's g128 tag */
-    /* The plugin declared the working set only where mtp_draft_head_q2 found the head at two
-     * bits, which declared its name map too. */
+    /* The plugin declares the working set only when mtp_draft_head_q2 found a 2-bit head (and
+     * declared its name map). */
     q2 = src.lm && w.dq && w.ds && w.dsum && w.dlog && w.didx && w.dval;
     if (q2) {
-        /* REPLICATED, AT THE WHOLE VOCABULARY, and that is a decision rather than an omission.
-         *
-         * The trunk's lm_head is row-sharded and its logits are merged across ranks by the
-         * sampler. This head does NOT go through the sampler -- the comment above op_dlogits says
-         * why -- so its argmax is a `row_topk` over one rank's plane, and a sharded plane would
-         * make every rank propose only tokens from its own half. Replicating it costs 341 MiB a
-         * card at 2 bits (against the 1.27 GiB a rank saves on the trunk head) and keeps the
-         * draft path a single-rank computation, which is what it is.
-         *
-         * The stored bytes are also tile-major (16 output rows a packed block), so the relayout
-         * would have to be handed a row share that is a whole number of tiles. */
+        /* Replicated over the whole vocabulary. Without the sampler's cross-rank merge, a sharded
+         * plane would let each rank propose only its own vocabulary slice. Replication costs 341
+         * MiB per card at 2 bits and keeps the draft path single-rank. (The stored bytes are also
+         * tile-major, 16 output rows per packed block, so a shard would have to be whole tiles.) */
         const char* dhn = nm.f("mtp.draft_head.weight");
         w_dh  = decl_view(b, dhn, nullptr, "codes", RAD_U2, {g.n_vocab_all, g.n_embd},
                           RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
@@ -395,11 +342,9 @@ inline int MtpBlockFP8::declare(RadBuilder* b, Names& nm, const Geom& geom,
                      {w.dlog}, {w.didx, w.dval});
     }
 
-    /* THE HEAD'S OUTPUT STAYS LIVE THROUGH THE WHOLE HEAD. It is the next round's input, written
-     * before this pass's lm_head runs; declared as read by the lm_head's first op alone, the
-     * buffer planner would let the ops after it take its bytes, and the next round would continue
-     * from what they wrote. Nothing fails: acceptance falls. Read by the head's last op as well,
-     * it survives every pass of the step. */
+    /* Keep `hout` live through the head's last op: it is the next round's input, and if only the
+     * lm_head's first op read it, the planner could give its bytes to later ops (silently lowering
+     * acceptance). */
     {
         const rad_op last = q2 ? op_dtopk : op_logits;
         if (rad_op_reads(b, last, &w.hout, 1) < 0) return RAD_E_INVAL;
@@ -407,17 +352,16 @@ inline int MtpBlockFP8::declare(RadBuilder* b, Names& nm, const Geom& geom,
     return RAD_OK;
 }
 
-/* One pass of the head. The batch is the one the scheduler built for it: n_tok rows, `token_ids`
- * already shifted one position on (batch.cpp, token_at), `positions` the head's own indices, and
- * the KV group batch carrying the slot each row writes at -- so every op below runs at n_tok rows
- * and the attention layer needs no special case at all. */
+/* One pass of the head over the scheduler's batch for it: n_tok rows, `token_ids` already shifted
+ * one position on (batch.cpp, token_at), `positions` the head's indices, and the KV group batch
+ * carrying each row's slot, so the attention layer needs no special case. */
 template 
 inline void MtpBlockFP8::step(RadCtx* c, const RadBatch* batch) const {
     const int64_t T = batch->n_tok;
     const int r = batch->draft_pass;
 
-    /* The history pass gathers; the rounds after it read the head's own output, which the pass
-     * before left in the same buffer. */
+    /* The history pass gathers; later rounds read the previous pass's output from the same
+     * buffer. */
     if (r == 1) {
         rad_step_fail(c, "the MTP head was handed a draft-round-1 pass: that round is carried by "
                          "the history pass (RadBatch::draft_out_ids) and has no pass of its own");
@@ -437,21 +381,16 @@ inline void MtpBlockFP8::step(RadCtx* c, const RadBatch* batch) const {
 
     RAD_ISSUE(c, op_fc, brows(w.c, T), RAD_W(w_fc), brows(w.x, T));
 
-    /* A HISTORY PASS THAT DRAFTS NOTHING ONLY LEAVES K AND V BEHIND, and they come from the
-     * block's input. The query, the attention, its output, the feed-forward, the norm and the
-     * lm_head compute the head's output, which only a drafting row reads -- and every prefill
-     * chunk but a prompt's last drafts nothing. `n_draft_out` is the batch's and the same on every
-     * rank, so a collective skipped here is skipped on all of them. */
+    /* A history pass with no drafting rows (every prefill chunk but a prompt's last) only needs
+     * K and V. `n_draft_out` is the same on every rank, so skipped collectives match. */
     if (r < 0 && batch->n_draft_out <= 0) {
         attn.store_kv(c, batch);
         return;
     }
     attn.step(c, batch);
 
-    /* A HISTORY PASS THAT DRAFTS GOES ON WITH ITS DRAFTING ROWS ALONE. They are round 1, and
-     * nothing reads the head's output at any other row: the feed-forward, the norm and the lm_head
-     * would run over a whole prompt chunk for a handful of rows. So round 1's rows come to the
-     * front of `x` first, and everything after runs as a pass of those rows. */
+    /* A history pass with drafting rows continues on those rows alone (round 1): they are moved
+     * to the front of `x` and the rest of the head runs over them. */
     int64_t L = T;                      /* the rows the stream goes on with */
     if (r < 0) {
         L = batch->n_draft_out;
@@ -464,12 +403,12 @@ inline void MtpBlockFP8::step(RadCtx* c, const RadBatch* batch) const {
 
     RAD_ISSUE(c, op_norm, brows(w.x, L), RAD_W(w_norm), brows(w.hout, L));
     if (q2) {
-        /* `dsum` is GROUP-major [n_embd/group][ceil(L/16)*16] and not row-major, so it is passed
-         * whole: there is no row slice of it that means anything. */
+        /* `dsum` is group-major [n_embd/group][ceil(L/16)*16], so it has no row slice; pass it
+         * whole. */
         RAD_ISSUE_N(c, op_dquant, L, brows(w.hout, L), brows(w.dq, L), brows(w.ds, L),
                     RAD_B(w.dsum));
-        /* The trailing `b_ref` is mxfp4's and absent here; an absent optional operand is a null
-         * tensor in a full-length list, not a shorter list (rad_fp8.h says why). */
+        /* The trailing `b_ref` is mxfp4's and absent; operands are positional, so pass RAD_NONE
+         * (rad_fp8.h). */
         RAD_ISSUE_N(c, op_dlogits, L, brows(w.dq, L), brows(w.ds, L), RAD_W(w_dh), RAD_W(w_dhs),
                     brows(w.dlog, L), RAD_B(w.dsum), RAD_NONE);
         RAD_ISSUE_N(c, op_dtopk, L, brows(w.dlog, L), brows(w.didx, L), brows(w.dval, L),
@@ -479,10 +418,8 @@ inline void MtpBlockFP8::step(RadCtx* c, const RadBatch* batch) const {
     }
 }
 
-/* The dense head, which is the 27B's and every other member of this family whose feed-forward is
- * one SwiGLU. The routed one is MtpBlockFP8, named by the plugin that wants it -- this
- * header does not include rad_block_moe_fp8.h, because a dense plugin should not compile a routed
- * block it will never declare. */
+/* The dense head (SwiGLU feed-forward). The routed one is MtpBlockFP8, named by the
+ * plugin that needs it; this header does not include rad_block_moe_fp8.h. */
 using MtpFP8 = MtpBlockFP8;
 
 }  /* namespace arch */
diff --git a/arch/common/rad_block_mtp_hc.h b/arch/common/rad_block_mtp_hc.h
index 11ea0019..6f1fe749 100644
--- a/arch/common/rad_block_mtp_hc.h
+++ b/arch/common/rad_block_mtp_hc.h
@@ -1,30 +1,25 @@
 /* rad_block_mtp_hc.h -- the multi-token-prediction head of a model whose residual stream is `hc`
  * times the model width.
  *
- * ============================== WHY THIS IS NOT rad_block_mtp_fp8.h ==============================
+ * ============================== DIFFERENCES FROM rad_block_mtp_fp8.h ==============================
  *
- * That file serves Qwen3.5 / Qwen3-Next / Qwen3.6, where the head is a PRE-NORM transformer layer
- * that reads the trunk's [n_embd] hidden state. It is the same idea, the same indexing and the
- * same two kinds of pass -- and almost none of the same parts, because Qwen4-Exp's head lives in
- * the WIDE stream:
+ * That file serves Qwen3.5 / Qwen3-Next / Qwen3.6, whose head is a pre-norm layer reading the
+ * trunk's [n_embd] hidden state. Qwen4-Exp's head has the same indexing and passes but lives in
+ * the wide stream:
  *
- *   ITS INPUT IS 10240 WIDE      `mtp.pre_fc_norm_hidden.weight` is [hc * n_embd], so the hidden
- *                               state this head continues from is the trunk's wide stream BEFORE
- *                               the output mixer collapses it, not `last_hidden_state`.
- *   THERE ARE TWO fc MATRICES    `mtp.fc_hidden` and `mtp.fc_embedding`, both [n_embd, n_embd].
- *                               So there is no concatenation and no concat-ORDER question: the
- *                               hidden half is one square matrix applied to EACH sub-stream and
- *                               the embedding half is one product broadcast into all of them.
- *                               docs/OPS.md's `mtp_enter` row is that arithmetic.
- *   ITS LAYER HAS TWO GATED      `mtp.layers.0.attn_hyper_connection` and `.mlp_hyper_connection`,
- *   RESIDUALS, NOT TWO NORMS     exactly as a trunk layer does. There is no `input_layernorm` and
- *                               no `post_attention_layernorm` in this checkpoint at all.
- *   AND A MIXER OF ITS OWN       `mtp.hyper_connection_mixer` -- a connection with no write half,
- *                               which is what collapses the head's wide stream for the lm_head.
- *                               It is the 98th connection in the model and the trunk's 97th has
- *                               the same shape and the same absent `block_inject_weight`.
- *
- * What is NOT different is the part that is easy to get wrong, so it is restated here in full.
+ *   10240-wide input             `mtp.pre_fc_norm_hidden.weight` is [hc * n_embd]: the head
+ *                               continues from the trunk's wide stream before the output mixer,
+ *                               not `last_hidden_state`.
+ *   two fc matrices              `mtp.fc_hidden` and `mtp.fc_embedding`, both [n_embd, n_embd], so
+ *                               no concatenation: the hidden matrix is applied to each
+ *                               sub-stream and the embedding product broadcast into all of them
+ *                               (docs/OPS.md's `mtp_enter` row).
+ *   gated residuals, no norms    `mtp.layers.0.attn_hyper_connection` and `.mlp_hyper_connection`,
+ *                               as in a trunk layer; no `input_layernorm` or
+ *                               `post_attention_layernorm`.
+ *   its own mixer                `mtp.hyper_connection_mixer`, a connection with no write half
+ *                               that collapses the wide stream for the lm_head (the model's 98th
+ *                               connection, shaped like the trunk's final one).
  *
  * ============================== THE INDEXING ==============================
  *
@@ -32,62 +27,44 @@
  *                     writes its K and V at KV position i, with rope position i
  *                     predicts the token at i + 2
  *
- * DeepSeek-V3's MTP layout, which this family follows: the head's transformer block runs over the
- * SAME position indices as the trunk and the shift lives entirely in which token gets embedded.
- * Getting it off by one costs nothing visible -- the drafts are simply wrong, acceptance collapses,
- * and the model's own output stays exactly correct.
+ * DeepSeek-V3's layout: the head runs over the trunk's position indices and the shift is only in
+ * which token is embedded. An off-by-one shows only as collapsed acceptance.
  *
  * ============================== THE TWO KINDS OF PASS ==============================
  *
- * `RadBatch::draft_pass` says which and the SIGN is the whole distinction:
+ * By the sign of `RadBatch::draft_pass` (details in rad_block_mtp_fp8.h):
  *
- *   < 0   A HISTORY PASS, one row a token, continuing from the trunk's own wide stream. The
- *         head's attention reads its OWN K and V for every earlier position and nothing else in
- *         the engine writes those -- the trunk's prefill fills layers 0..n-1 and leaves the head's
- *         untouched. Without it the head attends to whatever the pool last held, which is not
- *         wrong output (a bad draft is only a rejected draft) but is a drafter that proposes noise.
- *         It is also DRAFT ROUND 1 for the sequences that draft: each one's last history row is
- *         the committed position with the token the trunk chose after it, which is round 1's
- *         whole input, so the pass ends in the lm_head over those rows (RadBatch::draft_out_ids)
- *         and hands their wide state on as the carry.
- *   > 1   A DRAFT ROUND, one row a sequence, continuing from the head's own stream. There is no
- *         round-1 pass; the history pass is it.
+ *   < 0   History pass, one row per token, continuing from the trunk's wide stream. It writes the
+ *         head's own K and V, which nothing else writes. It is also draft round 1 for drafting
+ *         sequences: it ends in the lm_head over their rows (RadBatch::draft_out_ids) and hands
+ *         their wide state on as the carry.
+ *   > 1   Draft round, one row per sequence, continuing from the head's own stream.
  *
- * ============================== THE CARRY, AND WHY IT IS A COPY ==============================
+ * ============================== THE CARRY ==============================
  *
- * `hin` is what a round continues FROM and `hw` is the head's own stream. They cannot be one
- * buffer: `mtp_enter` reads the whole wide row to produce every channel of its output, so a
- * workgroup writing channels 0..31 would clobber input another workgroup has not read yet. The
- * pre-norm head has no such problem because its carry is written by a DIFFERENT op at the end of
- * the round (`mtp.norm`), and here the end of the round is the mlp connection's write, in place.
- *
- * So one `cast` copies `hw` back to `hin` between rounds -- a 20 KB row copy at decode, whose cost
- * is its launch -- and it is SKIPPED on the last round because nothing reads it there. A history
- * pass that drafts takes its carry with a `gather_rows` instead, of the round-1 rows alone, and
- * copies them back to the front of `hw`, where the mixer reads a round's rows.
+ * `hin` is what a round continues from and `hw` the head's own stream. They cannot share a buffer:
+ * `mtp_enter` reads the whole wide row for every output channel, so in-place writes would clobber
+ * unread input. (The pre-norm head's carry is written by a different op, `mtp.norm`; here the
+ * round ends with the mlp connection's in-place write.) A `cast` copies `hw` to `hin` between
+ * rounds (a 20 KB row at decode), skipped on the last round. A drafting history pass instead
+ * gathers its round-1 rows and copies them back to the front of `hw`, where the mixer reads them.
  *
  * ============================== THE KV CACHE ==============================
  *
- * The head's attention layer is bound to the TRUNK'S full-attention group as one more layer, at
- * absolute index n_layer. The slot mapping and the block table are the trunk's, so the head writes
- * its K and V at the slot the trunk's token for that position occupies and A REJECTED DRAFT'S
- * ENTRY IS OVERWRITTEN BY THE NEXT STEP'S CORRECT TOKEN AT THE SAME ADDRESS. Draft rounds run in
- * position order and each writes its own position before attending to it, so there is no rollback
- * to get wrong. The cost is that the group's page grows from 12 layers to 13 -- 8% more attention
- * KV -- and it is paid only when the deployment declares speculation.
+ * The head's attention is bound to the trunk's full-attention group as one more layer, at
+ * absolute index n_layer, sharing its slot mapping and block table; a rejected draft's entry is
+ * overwritten by the next step's token at the same address (see rad_block_mtp_fp8.h). The group's
+ * page grows from 12 layers to 13 (8% more attention KV), only when speculation is declared.
  *
- * ============================== WHAT IS AND IS NOT DECLARED ==============================
+ * ============================== BUFFERS ==============================
  *
- * The head reuses the TRUNK'S working buffers for its layer -- `attn_qg`, the expert planes, the
- * narrow block input. Every one of them is dead by the time a draft round runs (the trunk step has
- * been sampled and committed) and a second set would be 150 MiB of activation planes for one
- * layer. Only the wide stream, the carry, the embedding and the head's own logits path are its
- * own, because those must survive the round that produced them.
+ * The layer reuses the trunk's working buffers (`attn_qg`, the expert planes, the narrow block
+ * input), which are dead once the trunk step is committed; a second set would be 150 MiB. Only
+ * the wide stream, the carry, the embedding and the logits path are its own.
  *
- * THIS BLOCK MUST THEREFORE BE DECLARED AFTER THE TRUNK'S LAST OP. Declaration order IS the buffer
- * planner's liveness (core/build/rad_bufplan.cpp) and a drafter declared mid-trunk shares bytes
- * with buffers the trunk still has live. The signature of getting it wrong is fluent output with
- * acceptance EXACTLY zero.
+ * Invariant: declare this block after the trunk's last op. Declaration order is the buffer
+ * planner's liveness (core/build/rad_bufplan.cpp); declared mid-trunk, the head would share bytes
+ * with live trunk buffers (symptom: correct output, zero acceptance).
  */
 #ifndef RAD_BLOCK_MTP_HC_H
 #define RAD_BLOCK_MTP_HC_H
@@ -99,32 +76,24 @@
 #include "rad_qsa.h"
 #include "rad_block_vit.h"
 
-#include 
-
 namespace rad {
 namespace arch {
 
-/* HOW MANY CANDIDATES THE COARSE HEAD PROPOSES, and it is 8 because they are RESCORED.
+/* Candidates the coarse 2-bit head proposes for exact rescoring (`logit_rerank` against the
+ * full-precision head) before column 0 is read. The 2-bit head's top-1 differs from the exact one
+ * often enough to cost acceptance; 8 is the reference implementation's value, which recovered
+ * 99.63% agreement with the exact argmax, at R rows of the weight per draft row (40 KB against
+ * 318 MB).
  *
- * A draft needs one token. The 2-bit head picks a different top-1 than the exact head often enough
- * to cost several points of acceptance, so the coarse head proposes R candidates and
- * `logit_rerank` scores those R against the full-precision head before column 0 is read. 8 is the
- * reference implementation's number, which recovered a coarse head to 99.63% agreement with the
- * exact argmax; the cost is R rows of the weight a draft row, 40 KB against 318 MB. */
-/* AND R HAS AN OPTIMUM, which is not the obvious thing. A wider candidate set can only raise the
- * EXACT score the rescore selects, so more candidates ought to be free -- and both sixteen and
- * four are reproducibly worse than eight on draft acceptance.
- *
- * Because acceptance is agreement with the TRUNK and the rescore maximises the MTP HEAD's own
- * preference over the candidate set. Past some width, taking that preference more seriously walks
- * away from the trunk's argmax -- so the coarse head's ranking is a useful restriction and not
- * just noise to be corrected. */
+ * Both 4 and 16 give lower acceptance than 8: acceptance is agreement with the trunk, while the
+ * rescore maximises the head's own preference, so beyond some width the coarse ranking is a useful
+ * restriction. */
 static constexpr int64_t kDraftTopR = 8;
 
 struct MtpHcBlock {
     struct Wire {
-        /* [max_tok, hc * n_embd] the TRUNK's wide stream for the step just run. A pass names the
-         * rows it wants through out_ids and never has to know how they were laid out. */
+        /* [max_tok, hc * n_embd] the trunk's wide stream for the step just run; a pass names the
+         * rows it wants through out_ids. */
         rad_buf src  = 0;
         rad_buf hin  = 0;   /* [max_tok, hc * n_embd]  what this round continues from */
         rad_buf hw   = 0;   /* [max_tok, hc * n_embd]  the head's own wide stream */
@@ -132,12 +101,12 @@ struct MtpHcBlock {
         rad_buf inj  = 0;   /* [max_tok, hc]           both connections' write gains */
         rad_buf hout = 0;   /* [max_logit_rows, n_embd]  the mixer's output, the lm_head's input */
         rad_buf logits = 0; /* [max_logit_rows, n_vocab] the trunk's, shared */
-        ActFP8  x{};        /* the narrow block input -- the TRUNK's */
-        /* THE 2-BIT DRAFT HEAD's working set. Every one of these is a draft round's, so they are
-         * sized at max_logit_rows: a history pass never reaches any of them. */
+        ActFP8  x{};        /* the narrow block input, the trunk's */
+        /* The 2-bit draft head's working set, sized at max_logit_rows (only drafting rows reach
+         * it). */
         rad_buf dq = 0, ds = 0, dsum = 0, dlog = 0, didx = 0, dval = 0;
-        /* The vocab-parallel pair, declared only when the head is SHARDED. Both are (int32 id,
-         * float value) pairs read as f32: this rank's top-1, and the all-gathered world * 1. */
+        /* Vocab-parallel pairs, declared only when the head is sharded: (int32 id, f32 value)
+         * pairs stored as f32, this rank's top-R and the all-gathered world * R. */
         rad_buf dpair = 0, dgath = 0;
         AttnGatedFP8::Wire attn{};
         MoeFP8::Wire       mlp{};
@@ -160,12 +129,11 @@ struct MtpHcBlock {
     Wire    w{};
     int     layer  = 0;
     int64_t rows   = 0;
-    int     depth  = 0;    /* rounds this deployment will run -- the carry's last-round test */
-    int64_t ngroup = 0;    /* the pre-fc norm's groups: hc, one rsqrt a sub-stream */
+    int     depth  = 0;    /* rounds this deployment runs; decides whether the carry is needed */
+    int64_t ngroup = 0;    /* the pre-fc norm's groups: hc, one rsqrt per sub-stream */
     bool    q2     = false;
-    /* The 2-bit draft head's logical weight: the checkpoint's lm_head under a name of its own,
-     * which a recipe stores as 2-bit codes. The plugin asks mtp_draft_head_q2 about this name --
-     * which also declares its map -- and declares the head's buffers when the answer is yes. */
+    /* The 2-bit draft head's name. The plugin passes it to mtp_draft_head_q2 (which declares the
+     * map) and declares the head's buffers if that returns true. */
     static const char* head_name(Names& nm) { return nm.f("mtp.draft_head.weight"); }
 
     rad_weight w_tok = 0, w_lm = 0, w_fc_h = 0, w_fc_e = 0, w_pre_h = 0, w_pre_e = 0;
@@ -174,13 +142,15 @@ struct MtpHcBlock {
     HyperConn    hc_attn{}, hc_mlp{}, mixer{};
     AttnGatedFP8 attn{};
     QsaIndexer   qsa{};
+    /* The indexer's window bounds for a pass wider than its score plane (QsaIndexer::step), set by
+     * the caller before step(); null where no pass is. */
+    const int32_t* qsa_win_cu = nullptr;
     MoeFP8       mlp{};
 
     rad_op op_gather = 0, op_embed = 0, op_embed_ar = 0, op_enter = 0, op_carry = 0;
 
-    /* THE PROMPT'S MEDIA ROWS over the head's own embedding: its history pass embeds the prompt
-     * too, one position on, and an image token's embedding is the encoder's there as well. Set
-     * `media` before declare when the program has an encoder. */
+    /* Media rows over the head's embedding (see MtpBlockFP8::media). Set before declare when the
+     * program has an encoder. */
 
     bool       media = false;
 
@@ -189,8 +159,8 @@ struct MtpHcBlock {
     rad_op op_logits = 0, op_dquant = 0, op_dlogits = 0, op_dtopk = 0, op_drerank = 0;
     rad_op op_dgather = 0, op_dmerge = 0;
 
-    /* rad_arch.h's, asked through the block so whoever sizes `dlog` and the pair planes does not
-     * re-derive the rule. */
+    /* rad_arch.h's vocab-head rule, asked through the block by whoever sizes `dlog` and the pair
+     * planes. */
     static bool    head_sharded(const Geom& g) { return vocab_head_sharded(g); }
     static int64_t head_rows(const Geom& g)    { return vocab_head_rows(g); }
 
@@ -206,19 +176,16 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
                                const Wire& wire, const Src& src) {
     g = geom; w = wire; layer = l; w_tok = tok_embd; w_lm = lm_head;
     rows = g.max_tok; depth = draft_depth;
-    /* The pre-fc norm over the wide stream is GROUPED, one rsqrt a sub-stream, which is what every
-     * gated residual in this architecture does. A flat norm fits the same [hc*n] gain and no
-     * per-op oracle can tell the two apart; the acceptance rate can -- docs/OPS.md's `mtp_enter`
-     * row. */
+    /* The pre-fc norm over the wide stream is grouped, one rsqrt per sub-stream, like every gated
+     * residual here. A flat norm fits the same [hc*n] gain and passes per-op checks; only the
+     * acceptance rate tells them apart (docs/OPS.md's `mtp_enter` row). */
     ngroup = hc.hc;
     if (rows <= 0 || !w_tok || !w_lm || hc.hc <= 1) return RAD_E_INVAL;
     if (!w.src || !w.hin || !w.hw || !w.e || !w.hout) return RAD_E_INVAL;
     const int64_t HN = hc.hc * g.n_embd;
 
-    /* ---- the entry's four weights. SHARD_NONE on all of them: two are per-channel gains over a
-     * replicated stream and the two fc matrices read and write that same stream, so a column shard
-     * would need an all-reduce to save 13 MB a rank -- the wrong side of the trade at one launch
-     * per draft round. */
+    /* ---- the entry's four weights, all replicated: two gains over the replicated stream, and two
+     * fc matrices whose column shard would save 13 MB per rank at an all-reduce per round. */
     const char* nph = nm.f("mtp.pre_fc_norm_hidden.weight");
     const char* npe = nm.f("mtp.pre_fc_norm_embedding.weight");
     const char* nfh = nm.f("mtp.fc_hidden.weight");
@@ -227,9 +194,8 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
     RAD_ARCH_TRY(map_copy(b, npe, src.pre_norm_embedding));
     RAD_ARCH_TRY(map_copy(b, nfh, src.fc_hidden));
     RAD_ARCH_TRY(map_copy(b, nfe, src.fc_embedding));
-    /* THE TWO ENTRY MATRICES ARE WHATEVER THEIR ENCODING IS -- bf16, or E4M3 rows with a scale a
-     * group of each row (OPS.md's `fc` on mtp_enter) -- declared over every plane at the codes'
-     * dtype. It only ever changes the DRAFTS: the head proposes and the trunk verifies. */
+    /* The entry matrices are bf16 or E4M3 rows with a per-group scale (OPS.md's `fc` on
+     * mtp_enter), declared over all planes at the codes' dtype; both must match. */
     const uint32_t fdt = weight_codes_dtype(b, nfh, RAD_BF16);
     if (weight_codes_dtype(b, nfe, RAD_BF16) != fdt || (fdt != RAD_BF16 && fdt != RAD_F8E4M3)) {
         fprintf(stderr, "radiance: the MTP head's fc_hidden is %s and fc_embedding %s; the entry "
@@ -246,9 +212,8 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
                      grp_layer(l));
     if (!w_pre_h || !w_pre_e || !w_fc_h || !w_fc_e) return RAD_E_INVAL;
 
-    /* A SECOND gather_rows and a SECOND embed_lookup over the trunk's own buffers and weights.
-     * They are separate ops rather than re-issues of the trunk's because an op's read and write
-     * sets are what the buffer planner reads for liveness, and these write somewhere else. */
+    /* Separate gather_rows and embed_lookup ops over the trunk's buffers and weights, because
+     * they write different buffers and liveness comes from each op's read/write sets. */
     op_gather = rw(b, RAD_OP(b, "gather_rows",
                        RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", HN),
                                   RAD_STR("dtype", g.dtype)),
@@ -261,8 +226,8 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
                      RAD_WEIGHTS(w_tok)),
                  {}, {w.e});
     if (media) RAD_ARCH_TRY(mrows.declare(b, rows, g.n_embd, w.e));
-    /* The trunk's table is vocab-sharded, so this gather is a partial one and needs the same exact
-     * reduction the trunk's does. Its own op because it writes a different buffer. */
+    /* The trunk's table is vocab-sharded, so the lookup is partial and needs an exact
+     * all-reduce. */
     if (g.world > 1)
         op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
                             RAD_PARAMS(RAD_INT("world_size", g.world),
@@ -281,9 +246,9 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
                  {w.hin, w.e}, {w.hw});
     if (!op_gather || !op_embed || !op_enter) return RAD_E_INVAL;
 
-    /* ---- the layer. One gated residual, a gated full-attention block with its indexer, a second
-     * gated residual and the routed feed-forward -- a trunk full-attention layer, at layer index
-     * n_layer, and declared in exactly the order step() issues it in. */
+    /* ---- the layer, as a trunk full-attention layer at index n_layer: gated residual, gated
+     * attention with its indexer, gated residual, routed feed-forward. Declared in step()'s issue
+     * order. */
     RAD_ARCH_TRY(hc_attn.declare(b, nm, g, nm.f("mtp.attn_hc"), hc, HyperConn::Wire{w.hw, w.x, w.inj},
                                  src.hc_attn));
     RAD_ARCH_TRY(rad_bind_layer_kv(b, l, kv));
@@ -292,10 +257,9 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
                               false, false, kArNone, hc_attn.op_ar_write != 0));
     if (src.qsa.qk_proj)
         RAD_ARCH_TRY(qsa.declare(b, nm, g, l, src.qsa, w.qsa, w.attn.h, qsa_bk));
-    /* ---- draft round 1's rows out of a history pass (RadBatch::draft_out_ids), before the
-     * feed-forward, which then runs over them alone: gathered into `hin`, one row a drafting
-     * sequence in round order, and copied back to the front of `hw`. Two ops and not one because a
-     * gather in place could overwrite a row another sequence has yet to read. */
+    /* ---- round 1's rows of a history pass (RadBatch::draft_out_ids), moved before the
+     * feed-forward, which then runs on them only: gathered into `hin` and copied back to the
+     * front of `hw` (an in-place gather could overwrite unread rows). */
     op_dsel = rw(b, RAD_OP(b, "gather_rows",
                     RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", HN),
                                RAD_STR("dtype", g.dtype)),
@@ -308,7 +272,7 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
                  {w.hin}, {w.hw});
     if (!op_dsel || !op_dback) return RAD_E_INVAL;
 
-    /* The rotated expert input rides in this read, as it does on the trunk. */
+    /* The connection's read also writes the rotated expert input, as on the trunk. */
     HyperConn::Config mcfg = hc;
     HyperConn::Wire   mwire{w.hw, w.x, w.inj};
     if (src.mlp.cfg.expert_rot) { mcfg.rotate = 1; mwire.rq = w.mlp.hr.q; mwire.rs = w.mlp.hr.s; }
@@ -317,7 +281,7 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
     mlp.hr_in = mcfg.rotate != 0;
     RAD_ARCH_TRY(mlp.declare(b, nm, g, l, w.mlp, src.mlp, false, false, kArNone,
                              hc_mlp.op_ar_write != 0));
-    /* The write behind the block takes its gather where it can, as on the trunk. */
+    /* The following write takes the MoE gather where it can, as on the trunk. */
     {
         HyperConn::GatherSrc gs{};
         gs.ye     = mlp.w.edn;
@@ -331,15 +295,15 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
         mlp.gather_out_rows6 = hc_mlp.gather_rows6;
     }
 
-    /* ---- the carry. See the header: `mtp_enter` cannot be issued in place. */
+    /* ---- the carry (see the header: `mtp_enter` cannot run in place). */
     op_carry = rw(b, RAD_OP(b, "cast",
                      RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", HN),
                                 RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
                      RAD_NOWEIGHTS),
                  {w.hw}, {w.hin});
 
-    /* ---- the head's own mixer: the connection with no write half, which collapses its wide
-     * stream to the one hidden state the lm_head reads. No fp8 twin -- that input is bf16. */
+    /* ---- the head's mixer: a connection with no write half that collapses the wide stream for
+     * the lm_head, which reads bf16, so no fp8 codes. */
     {
         HyperConn::Config mc = hc;
         mc.inject = 0;
@@ -349,8 +313,8 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
         RAD_ARCH_TRY(mixer.declare(b, nm, g, nm.f("mtp.output_hc"), mc, mixw, src.hc_mix));
     }
 
-    /* The trunk's lm_head over the head's hidden state, banded at the logits buffer's own extent:
-     * only a DRAFT round reaches this and a draft round is one row a sequence. */
+    /* The trunk's lm_head over the head's hidden state, banded at the logits buffer's extent (one
+     * row per drafting sequence). */
     op_logits = rw(b, RAD_OP(b, "logits_gemm",
                       RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
                                  RAD_INT("n_vocab", g.n_vocab),
@@ -359,33 +323,22 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
                   {w.hout}, {w.logits});
     if (!op_carry || !op_logits) return RAD_E_INVAL;
 
-    /* ---- THE 2-BIT DRAFT HEAD. rad_block_mtp_fp8.h argues it in full; the short version is that
-     * `logits_gemm` is already at the memory roofline, so its only lever is FEWER BYTES -- and
-     * a speculative step runs the projection once to verify and once PER DRAFT ROUND. A draft is a
-     * proposal the target verifies with its own head, so a worse draft costs acceptance and
-     * cannot change a token the model emits. */
+    /* ---- The 2-bit draft head (rationale in rad_block_mtp_fp8.h): fewer bytes per draft round,
+     * at the cost of acceptance only. */
     enum { MTP_W2_GROUP = 128 };
-    /* A DRAFT NEEDS ONE TOKEN AND THE TOP-R IS WIDER THAN THAT; kDraftTopR says why. There is also
-     * a HARD LOWER BOUND of 2 from the all-gather: `ar_gather_2rank` places rank r's contribution
-     * row-interleaved and requires the row to be a whole number of 16-byte words, and a pair is
-     * (int32 id, float value) -- so R = 1 is an 8-byte row and is refused, while R = 2 is 16. The
-     * engine reads column 0 through `proposal_pitch`, which is what that field is for. */
+    /* R is kDraftTopR. It must also be at least 2: `ar_gather_2rank` needs rows of whole 16-byte
+     * words and a pair is 8 bytes. The engine reads column 0 through `proposal_pitch`. */
     q2 = w.dq && w.ds && w.dsum && w.dlog && w.didx && w.dval;
     if (q2) {
-        /* AND IT IS VOCAB-PARALLEL, which is 159 MB a round rather than 318. The head does not go
-         * through the sampler, so its argmax is a `row_topk` over one rank's plane -- and a
-         * sharded plane alone would make every rank propose only tokens from its own half. That
-         * is what `row_topk`'s `vocab_off` and `row_topk_merge` are for, and they are the same
-         * three ops arch/common/rad_block_dspark.h already drives: a top-R reporting GLOBAL ids,
-         * an all_gather of (id, value) pairs, and a merge that finds exactly the top-R an
-         * unsharded head would have. */
+        /* Vocab-parallel when possible (159 MB a round instead of 318). Bypassing the sampler, it
+         * uses the same three ops as rad_block_dspark.h: a top-R reporting global ids, an
+         * all_gather of (id, value) pairs, and a merge giving exactly the unsharded top-R. */
         const bool dh_shard = head_sharded(g) && w.dpair && w.dgath;
         const int  dh_split = dh_shard ? RAD_SHARD_ROW : RAD_SHARD_NONE;
         const int64_t hrows = dh_shard ? g.n_vocab : g.n_vocab_all;
-        /* ITS OWN STORED WEIGHT, MADE FROM THE TRUNK'S lm_head by the recipe: two-bit codes with
-         * an f16 scale and a u8 zero point a group of 128 (`u2*f16+u8[1x128]`), its name map
-         * declared by mtp_draft_head_q2. The GEMM takes the codes as one operand and the scale
-         * and zero planes as the other. */
+        /* Its own stored weight made from the trunk's lm_head by the recipe (`u2*f16+u8[1x128]`),
+         * name map declared by mtp_draft_head_q2. The GEMM takes codes as one operand and the
+         * scale/zero planes as the other. */
         const char* dhn = head_name(nm);
         w_dh  = decl_view(b, dhn, nullptr, "codes", RAD_U2, {hrows, g.n_embd},
                           RAD_ACCESS_PER_TOKEN, dh_split, grp_layer(l));
@@ -405,10 +358,9 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
                                       RAD_INT("group", MTP_W2_GROUP), RAD_STR("dtype", "w2a8")),
                            RAD_WEIGHTS(w_dh, w_dhs)),
                        {w.dq, w.ds, w.dsum}, {w.dlog});
-        /* Sharded, the top-R runs over THIS RANK'S plane and reports GLOBAL ids, and it also
-         * writes the pair plane the gather moves. `vocab_off` is omitted entirely when the head is
-         * replicated: an optional parameter present with the value 0 is not the same declaration
-         * as an absent one. */
+        /* Sharded, the top-R runs over this rank's plane, reports global ids and also writes the
+         * pair plane the gather moves. Replicated, `vocab_off` is omitted: an optional parameter
+         * present with value 0 is a different declaration from an absent one. */
         op_dtopk = dh_shard
             ? rw(b, RAD_OP(b, "row_topk",
                     RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("N", hrows),
@@ -421,29 +373,18 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
                                RAD_INT("R", kDraftTopR), RAD_STR("dtype", g.dtype)),
                     RAD_NOWEIGHTS),
                  {w.dlog}, {w.didx, w.dval});
-        /* ---- THE COARSE HEAD'S CANDIDATES, RESCORED EXACTLY.
+        /* ---- Exact rescoring of the coarse candidates against `w_lm`, the trunk's lm_head
+         * (already resident; the fallback `op_logits` reads it). It reads R rows per draft row in
+         * the trunk's stored layout, which libr4d's rerank shares with its fp8 logits GEMM.
          *
-         * `w_lm` is the trunk's lm_head: already declared, already resident, already this
-         * block's (it is what the fallback's `op_logits` reads), so the rerank costs no weight.
-         * It reads R rows of it a draft row, in the stored form the trunk's logits_gemm reads:
-         * libr4d's rerank takes the same layout as its fp8 logits GEMM, so one stored head serves
-         * both, and a kernel that reads neither form is not selected for either.
+         * No extra collective: sharded, every candidate is one this rank owns, and the existing
+         * gather and merge then rank exact values. It overwrites `didx`/`dval`/`dpair` in place.
          *
-         * IT NEEDS NO COLLECTIVE OF ITS OWN. Sharded, `row_topk` picked from THIS RANK'S plane and
-         * reported global ids, so every candidate it hands over is one this rank owns and can
-         * score; the existing all_gather and merge then find the global winner over exact values
-         * instead of coarse ones. The op writes back over `didx`/`dval`/`dpair` in place, which is
-         * what keeps that chain unchanged.
+         * Skipped for a replicated draft head above one rank: the vocabulary did not shard cleanly
+         * (vocab_head_sharded) while the trunk's lm_head stays row-sharded, so candidates include
+         * ids this rank cannot score.
          *
-         * AND THAT OWNERSHIP IS WHY A REPLICATED DRAFT HEAD ABOVE ONE RANK SKIPS IT. A vocabulary
-         * that does not shard cleanly (vocab_head_sharded) replicates the DRAFT head while the
-         * trunk's lm_head stays row-sharded, so `row_topk` then reports ids from the whole
-         * vocabulary and half of them are not this rank's to score. The coarse head's own answer
-         * stands, unreranked, and the rerank sits out.
-         *
-         * `vocab_off` is passed always and not only when sharded: unlike `row_topk`, this op has
-         * one form, and at world 1 the offset is 0 and `n_vocab` is the whole vocabulary, which is
-         * the same declaration either way. */
+         * `vocab_off` is always passed: this op has one form, and at world 1 it is 0. */
         const bool rerank = dh_shard || g.world <= 1;
         if (rerank) {
             op_drerank = RAD_OP(b, "logit_rerank",
@@ -454,16 +395,16 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
                                        RAD_STR("dtype", g.dtype)),
                             RAD_WEIGHTS(w_lm));
             if (!op_drerank) return RAD_E_INVAL;
-            /* Arrays and not rw()'s braced lists: the write set is conditional and a braced list
-             * inside a ternary is a temporary -- rad_fp8.h's NormQuantFP8 records the same. */
+            /* Arrays rather than rw(): the write set is conditional (see rad_fp8.h:
+             * NormQuantFP8). */
             rad_buf rd[2] = { w.hout, w.didx };
             rad_buf wr[3] = { w.didx, w.dval, w.dpair };
             rad_op_reads (b, op_drerank, rd, 2);
             rad_op_writes(b, op_drerank, wr, dh_shard ? 3 : 2);
         }
         if (dh_shard) {
-            /* ROW-INTERLEAVED, so one draft row's pairs from every rank land side by side --
-             * `row_topk_merge` reads one row at one row stride. */
+            /* Row-interleaved, so one draft row's pairs from every rank are adjacent for
+             * `row_topk_merge`. */
             op_dgather = rw(b, RAD_OP(b, "all_gather",
                                RAD_PARAMS(RAD_INT("world_size", g.world),
                                           RAD_INT("numel", g.max_logit_rows * kDraftTopR * 2),
@@ -482,11 +423,9 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
         }
         if (!op_dquant || !op_dlogits || !op_dtopk) return RAD_E_INVAL;
     }
-    /* THE CARRY STAYS LIVE THROUGH THE WHOLE HEAD. A pass writes `hin` for the round after it
-     * before its mixer and lm_head run; declared as used by the carry alone, the buffer planner
-     * would let the ops after it take its bytes, and the next round would continue from what they
-     * wrote. Nothing fails: acceptance falls. Read by the head's last op as well, it survives
-     * every pass of the step. */
+    /* Keep the carry `hin` live through the head's last op: it is written before the mixer and
+     * lm_head run, and the planner could otherwise give its bytes to them (silently lowering
+     * acceptance). */
     {
         rad_op last = op_logits;
         if (q2) last = op_dmerge ? op_dmerge : op_drerank ? op_drerank : op_dtopk;
@@ -495,16 +434,15 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
     return RAD_OK;
 }
 
-/* One pass of the head. The batch is the one the scheduler built for it: n_tok rows, `token_ids`
- * already shifted one position on (sched/batch.cpp, token_at), `positions` the head's own indices,
- * and the KV group batch carrying the slot each row writes at -- so every op below runs at n_tok
- * rows and the attention layer needs no special case at all. */
+/* One pass of the head over the scheduler's batch for it: n_tok rows, `token_ids` already shifted
+ * one position on (sched/batch.cpp, token_at), `positions` the head's indices, and the KV group
+ * batch carrying each row's slot, so the attention layer needs no special case. */
 inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
     const int64_t T = batch->n_tok;
     const int     r = batch->draft_pass;
 
-    /* The history pass continues from the TRUNK's wide stream; the rounds after it continue from
-     * the head's, which the carry left in the same buffer. */
+    /* The history pass continues from the trunk's wide stream; later rounds from the head's,
+     * which the carry left in the same buffer. */
     if (r == 1) {
         rad_step_fail(c, "the MTP head was handed a draft-round-1 pass: that round is carried by "
                          "the history pass (RadBatch::draft_out_ids) and has no pass of its own");
@@ -523,34 +461,26 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
     RAD_ISSUE(c, op_enter, brows(w.hin, T), brows(w.e, T), RAD_W(w_pre_h), RAD_W(w_pre_e),
               RAD_W(w_fc_h), RAD_W(w_fc_e), brows(w.hw, T));
 
-    hc_attn.read(c, T, 0, T);
+    hc_attn.read_pieces(c, T);
 
-    /* A HISTORY PASS THAT DRAFTS NOTHING ONLY LEAVES THE HEAD'S STATE BEHIND: the K and V of its
-     * rows and the indexer's block keys and tail, all of which come from the block's input. The
-     * query, the indexer's scores and selection, the attention, its output and everything after
-     * compute the head's stream, which only a drafting row reads. Every prefill chunk but a
-     * prompt's last is such a pass. `n_draft_out` is the batch's and the same on every rank, so
-     * the collectives skipped here are skipped on all of them. */
+    /* A history pass with no drafting rows (every prefill chunk but a prompt's last) only stores
+     * the head's state: K and V, and the indexer's block keys and tail. `n_draft_out` is the same
+     * on every rank, so skipped collectives match. */
     if (r < 0 && batch->n_draft_out <= 0) {
         qsa.store(c, attn.w.h, batch);
         attn.store_kv(c, batch);
         return;
     }
 
-    /* THE INDEXER RUNS FIRST, because the attention reads its selection. It can: this block's
-     * input is normed and quantised by the connection above, so `w.h` is already what it will be
-     * when the attention runs. */
-    qsa.step(c, attn.w.h, batch);
+    /* The indexer runs first because the attention reads its selection; `w.h` is already final,
+     * written by the connection above. */
+    qsa.step(c, attn.w.h, batch, qsa_win_cu);
     attn.step(c, batch);
 
     hc_attn.write(c, T, 0, T);
 
-    /* A HISTORY PASS THAT DRAFTS GOES ON WITH ITS DRAFTING ROWS ALONE. They are round 1, and
-     * nothing reads the head's stream at any other row: the experts, their connection and the
-     * lm_head would run over a whole prompt chunk for a handful of rows. So round 1's rows come out
-     * of `hw` first -- gathered into `hin` and copied back to its front, two ops because a gather
-     * in place could overwrite a row another sequence has yet to read -- and everything after runs
-     * as a pass of those rows. */
+    /* A history pass with drafting rows continues on those rows alone (round 1): they are moved
+     * to the front of `hw` and the rest of the head runs over them. */
     int64_t L = T;                      /* the rows the stream goes on with */
     if (r < 0) {
         L = batch->n_draft_out;
@@ -559,31 +489,29 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
         RAD_ISSUE_N(c, op_dback, L, brows(w.hin, L), brows(w.hw, L));
     }
 
-    hc_mlp.read(c, L, 0, L);
+    hc_mlp.read_pieces(c, L);
     mlp.step_rows(c, L);
     hc_mlp.write(c, L, 0, L);
 
-    /* THE CARRY, and only where a round after this one will read it. The last round of a group
-     * is followed by a trunk step; a history pass is round 1, followed by round 2 when the
-     * deployment drafts deeper. */
+    /* The carry, only if a later round reads it: a history pass is round 1, followed by round 2
+     * when depth > 1; the last round is followed by a trunk step. */
     if (r < 0 ? depth > 1 : r < depth)
         RAD_ISSUE_N(c, op_carry, L, brows(w.hw, L), brows(w.hin, L));
 
     mixer.read(c, L, 0, L);
     if (q2) {
-        /* `dsum` is GROUP-major [n_embd/group][ceil(L/16)*16] and not row-major, so it is passed
-         * whole: there is no row slice of it that means anything. */
+        /* `dsum` is group-major [n_embd/group][ceil(L/16)*16], so it has no row slice; pass it
+         * whole. */
         RAD_ISSUE_N(c, op_dquant, L, brows(w.hout, L), brows(w.dq, L), brows(w.ds, L),
                     RAD_B(w.dsum));
-        /* The trailing `b_ref` is mxfp4's and absent here; an absent optional operand is a null
-         * tensor in a full-length list, not a shorter list (rad_fp8.h says why). */
+        /* The trailing `b_ref` is mxfp4's and absent; operands are positional, so pass RAD_NONE
+         * (rad_fp8.h). */
         RAD_ISSUE_N(c, op_dlogits, L, brows(w.dq, L), brows(w.ds, L), RAD_W(w_dh), RAD_W(w_dhs),
                     brows(w.dlog, L), RAD_B(w.dsum), RAD_NONE);
         if (op_dmerge) {
             RAD_ISSUE_N(c, op_dtopk, L, brows(w.dlog, L), brows(w.didx, L), brows(w.dval, L),
                         brows(w.dpair, L));
-            /* In place over all three, so the gather and the merge below are unchanged and now
-             * carry EXACT values instead of the coarse head's. */
+            /* In place over all three, so the gather and merge carry exact values. */
             if (op_drerank)
                 RAD_ISSUE_N(c, op_drerank, L, brows(w.hout, L), RAD_W(w_lm), brows(w.didx, L),
                             brows(w.didx, L), brows(w.dval, L), brows(w.dpair, L));
diff --git a/arch/common/rad_block_ple.h b/arch/common/rad_block_ple.h
index 155dee31..a09f2f78 100644
--- a/arch/common/rad_block_ple.h
+++ b/arch/common/rad_block_ple.h
@@ -2,10 +2,10 @@
  *
  * ============================== WHAT IT IS ==============================
  *
- * ONE layer of the model gets a second embedding table, addressed not by the token but by a HASH of
- * the last three. Qwen3.8-Flash-Next's is 320,001,536 rows of 160 -- FOUR FIFTHS OF THE CHECKPOINT,
- * 51 of its 125 billion parameters -- read sixteen rows a token and mixed into the residual stream
- * by a dot product against the stream itself:
+ * One layer has a second embedding table addressed by a hash of the last three tokens.
+ * Qwen3.8-Flash-Next's is 320,001,536 rows of 160 (51 of the checkpoint's 125 billion
+ * parameters), read sixteen rows per token and mixed into the residual stream by a dot product
+ * against the stream:
  *
  *   ids  = ngram_ids(tokens)                     [T, 16]   a hash of the last 3 ids, per head
  *   e    = embed_lookup_q(ids, table, scale)     [T, 2560]  16 x 160, flattened
@@ -15,44 +15,37 @@
  *   out  = ple_conv(gvn, resid = gv, ...)        dilated depthwise conv, silu, and the add
  *   h   += out
  *
- * and it happens BEFORE the attention hyper-connection reads the stream, so `h` here is the wide
- * un-normed residual.
+ * This runs before the attention hyper-connection reads the stream, so `h` is the wide, un-normed
+ * residual.
  *
- * ============================== THE TABLE DECIDES THE SHAPE OF ALL OF THIS ======================
+ * ============================== THE TABLE ==============================
  *
- * 51.2 GB cannot be staged onto a card, so `embed_lookup_q` reads it where --ngram-placement put
- * it: the HOST gather over the container's own mmap or a locked copy in RAM (libavx/avx_ngram.cpp
- * carries that argument in full), or a device kernel reading a pinned copy over the link -- or the
- * card's own copy, on a card that holds it. Either way its result reaches the card through the
- * host arena, 5 KB a token at decode. Three consequences reach this file:
+ * The 51.2 GB table cannot be staged onto a card, so `embed_lookup_q` reads it where
+ * --ngram-placement put it: a host gather over the container's mmap or a locked RAM copy
+ * (libavx/avx_ngram.cpp), a device kernel reading a pinned copy over the link, or a card's own
+ * copy. The result reaches the card through the host arena, 5 KB per token at decode. Hence:
  *
- *   THE TABLE IS A WEIGHT OPERAND, because the planner puts an op on the host only when every
- *   weight operand of it is Site::Host, and decides that from the table's placement. A gather
- *   whose source were an activation could never be placed there.
+ *   The table is a weight operand: the planner places an op on the host only when all its weight
+ *   operands are Site::Host, judged from the table's placement.
  *
- *   ITS BUFFERS ARE HOST DOMAIN. `ids` and `e` are read and written by the host gather when it
- *   runs, so they live in the host arena, which a device gather reads and writes over the link
- *   just as well; everything downstream of `e` is ordinary device work.
+ *   `ids` and `e` are host-domain buffers, written and read by the host gather; a device gather
+ *   accesses them over the link. Everything downstream of `e` is device work.
  *
- *   IT IS 128 CHECKPOINT TENSORS. RadNameMap holds eight sources, so the map is declared in pieces
- *   by map_concat_shards() and the order IS the concatenation -- a permuted table is a model that
- *   loads, runs, and looks up the wrong embeddings.
+ *   It is 128 checkpoint tensors, mapped in pieces by map_concat_shards(); the order is the
+ *   concatenation, and a permuted table silently looks up wrong rows.
  *
- * ============================== TWO STATES, ONE CONTRACT ==============================
+ * ============================== THE TWO ROLLING WINDOWS ==============================
  *
- * The n-gram hash needs the two committed ids in front of the step, and the convolution needs nine
- * timesteps of its input. Both are RAD_KV_CONV rolling windows read at `num_accepted - 1`. They
- * differ in ONE thing: the token window's cold value is EOS and the convolution's is zero, because
- * zero is a real token id. `has_init` says which slots are cold and both ops read it.
+ * The n-gram hash needs the two committed ids before the step, and the convolution nine timesteps
+ * of its input. Both are RAD_KV_CONV windows read at `num_accepted - 1`. The token window's cold
+ * value is EOS, the convolution's zero (zero is a real token id); `has_init` marks cold slots.
  *
- * WHAT A STEP LEAVES IN THE WINDOW DEPENDS ON WHAT KIND OF STEP IT WAS, and the op learns that
- * from whether `num_accepted` is passed (libref/ref_ple.cpp). A decode row may have its drafts
- * rejected, so its window is left in gdn_conv_update's shifted layout, where the next step's read
- * offset picks out the history ending at the last token kept. A prefill chunk commits everything,
- * so its window is its tail at offset zero, which the scheduler's `num_accepted` of 1 for the next
- * step reads. One layout cannot serve both: at offset zero the first holds the history ending at
- * the step's FIRST token and the second the history ending at its LAST. So step() issues both ops
- * once per half of the batch, the way rad_block_gdn_fp8.h issues its two convolutions.
+ * What a step leaves in the window depends on the step, signalled by whether `num_accepted` is
+ * passed (libref/ref_ple.cpp). A decode row may have drafts rejected, so its window uses
+ * gdn_conv_update's shifted layout, where the next read offset selects the history ending at the
+ * last kept token. A prefill chunk commits everything and leaves its tail at offset zero, read by
+ * the next step's `num_accepted` of 1. One layout cannot serve both, so step() issues both ops
+ * once per half of the batch, as rad_block_gdn_fp8.h does.
  */
 #ifndef RAD_BLOCK_PLE_H
 #define RAD_BLOCK_PLE_H
@@ -79,7 +72,7 @@ struct PleLayer {
     };
 
     struct Wire {
-        rad_buf h = 0;   /* [max_tok, hc * n_embd] THE WIDE STREAM, read and added into */
+        rad_buf h = 0;   /* [max_tok, hc * n_embd] the wide stream, read and added into */
     };
 
     struct Src {
@@ -103,7 +96,7 @@ struct PleLayer {
     int    layer_ = 0;
 
     rad_weight w_table = 0, w_scale = 0, w_mult = 0, w_vsz = 0, w_off = 0;
-    /* The table as the checkpoint ships it -- plain bf16, no scale weight -- rather than E4M3. */
+    /* The table is plain bf16 as shipped (no scale weight) rather than E4M3. */
     bool       table_bf16 = false;
     rad_weight w_key = 0, w_value = 0, w_nk = 0, w_nq = 0, w_nc = 0, w_conv = 0;
 
@@ -121,7 +114,7 @@ struct PleLayer {
 
     int  declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& cfg, int layer,
                  const Wire& wire, const Src& src);
-    /* The hash, issued at the TOP of the step; the rest, at the layer. See step(). */
+    /* The hash, issued at the top of the step; the rest at the layer (see ids()). */
     void ids(RadCtx* c_, const RadBatch* batch) const;
     void step(RadCtx* c_, const RadBatch* batch) const;
 };
@@ -140,7 +133,7 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
         return RAD_E_INVAL;
     }
     /* `heads` is `ngram - 1` equal blocks, one per n-gram order, and `embed_dim` splits evenly
-     * across them. Both are the reference's own constructor checks. */
+     * across heads (the reference's constructor checks). */
     if (c.heads % (c.ngram - 1) || c.embed_dim % c.heads) {
         fprintf(stderr, "radiance: ple: %lld heads over %lld n-gram orders, %lld embed dims -- "
                         "neither divides\n", (long long)c.heads, (long long)(c.ngram - 1),
@@ -151,69 +144,41 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
     if (!src.shard_prefix || !src.shard_suffix || !src.mult || !src.vocab_sizes ||
         !src.offsets || !src.key_proj || !src.value_proj || !src.norm_key || !src.norm_query ||
         !src.norm_conv || !src.conv1d) return RAD_E_INVAL;
-    /* ============================== THE WHOLE LAYER IS REPLICATED UNDER TP ==============================
+    /* ============================== REPLICATED UNDER TP ==============================
      *
-     * Replication is the RIGHT answer here, not a gap: sharding would be the mistake.
+     * The whole layer is replicated and has no collective. The table is addressed by a token hash
+     * every rank computes identically, so a vocabulary shard is useless; and it is Tier::Mapped,
+     * so all ranks gather through one shared row cache over the same file.
      *
-     * THE TABLE IS ADDRESSED BY A HASH OF THE TOKENS, which every rank computes identically, so a
-     * vocabulary shard would give each rank rows it can never be asked for. And it costs NOTHING
-     * to replicate: it is Tier::Mapped, read from the container's own file, so both ranks point at
-     * the same table on the same machine and gather through one row cache they share.
+     * The rest is 63 MiB per rank (key_proj 50, value_proj 12.5, three norm gains, a conv weight).
+     * Column-sharding the projections would shard `gv` and `gvn` across the hyper-connection
+     * streams and need an all-gather per step to save 31 MiB per card. Every rank adds the same
+     * `out` into an identical copy of the stream, so the result stays bit-identical across ranks.
      *
-     * WHAT IS LEFT IS 63 MiB A RANK -- key_proj 50, value_proj 12.5, three norm gains and a conv
-     * weight -- against the 112 GiB of experts TP exists to split here. Column-sharding the
-     * projections would shard `gv` and `gvn` across the hyper-connection streams, and then the
-     * convolution and the residual add would need the full width back: an all-gather a step, to
-     * save 31 MiB a card. Geom::n_embd is "the residual stream, replicated on every rank", and
-     * this layer reads and writes exactly that.
-     *
-     * SO EVERY RANK RUNS THE WHOLE LAYER AND THERE IS NO COLLECTIVE IN IT. Both ranks see the same
-     * token ids, hash them the same way, gather the same rows and add the same `out` into their
-     * own copy of a stream that was already identical -- bit for bit, because the all-reduce that
-     * produced it delivers the same sum to both. The duplicated work is two small GEMMs and one
-     * host gather per rank.
-     *
-     * ---- AND THAT LAST SENTENCE IS TRUE AT DECODE AND EXPENSIVE AT PREFILL ---------------------
-     *
-     * The duplicated gather is `heads` rows a TOKEN, so what is sixteen rows at a decode step is
-     * sixteen thousand at a 1024-token chunk and thirty-two thousand at a 2048 one. A gather that
-     * reads the table through the mapping costs each rank about 70 ms at a 2048-token chunk --
-     * about 7.6% of a prefill step each. The RANKS ARE THREADS IN ONE PROCESS, so the page faults
-     * are shared, but each rank still walks every row, and the step waits for both.
-     *
-     * THAT COST IS PAGE-TABLE POPULATION, NOT I/O. The distinct rows a prefill wants land on
-     * distinct 4 KiB pages -- about ONE USEFUL ROW A PAGE, where a page holds 25 of them -- so a
-     * gather through the mapping pays a fault per row. At decode, with varied text, it is the
-     * other way round: half of every step's rows are new, and the page cache makes the waiting
-     * thread start each of those reads itself. So the kernel keeps the rows in a cache of its own
-     * and reads a miss straight from the file (libavx/avx_ngram.cpp).
-     *
-     * AND THAT CACHE SPLITS THE COLD WORK WITHOUT A COLLECTIVE. Dividing the rows between ranks,
-     * or having one rank gather for both, would need a cross-rank HOST barrier inside a block that
-     * deliberately has no collective in it. The shared cache does not: each rank claims the misses
-     * it reaches first, reads only those, and waits only for rows the other rank has already
-     * claimed -- so a miss is read once, and a late rank finds the rows there. What each rank still
-     * does alone is decode the rows into its own output, which is a table lookup a byte. A
-     * vocabulary shard is still wrong for the reason given above.
+     * The duplicated gather is `heads` rows per token: 16 at decode, 32768 at a 2048-token chunk,
+     * about 70 ms per rank through the mapping (7.6% of a prefill step). That cost is page-table
+     * population, not I/O: a prefill's distinct rows land about one per 4 KiB page (of 25), so the
+     * mapping pays a fault per row. At decode half of each step's rows are new and the page cache
+     * makes the waiting thread start each read. So the kernel keeps its own row cache and reads
+     * misses straight from the file (libavx/avx_ngram.cpp). Ranks share that cache: each claims
+     * and reads the misses it reaches first and waits only for rows another rank has claimed, so
+     * each miss is read once without a cross-rank barrier.
      */
 
     const int64_t HN = hn();
     const int64_t HD = c.head_dim();
 
     /* ---- the table, its scale, and the three hash constants -------------------------------- */
-    /* E4M3 with ONE scale for all 320 million rows -- Qwen3.8-Flash-Next-FP8's own choice, and the
-     * table's statistics say why that works: E4M3 carries its own exponent, a row's dynamic range
-     * is 2.3x, and the scale sits on a three-octave plateau. ONE STORED WEIGHT, `fp8_e4m3*bf16[*x*]`
-     * -- its codes and a one-element scale plane, made by the recipe from the dense checkpoint
-     * (data/recipes/qwen4exp-w4.recipe) -- and the gather takes the two planes as two operands.
-     * The shards are joined along rows by the name map, declared first because it is how the
-     * model is asked what the table is. RAD_ACCESS_VOCAB because it IS a vocabulary table, just
-     * not the token one. */
+    /* E4M3 with one scale for all 320 million rows (Qwen3.8-Flash-Next-FP8's choice; E4M3 has its
+     * own exponent, a row's dynamic range is 2.3x, and the scale sits on a three-octave plateau).
+     * One stored weight, `fp8_e4m3*bf16[*x*]`: codes plus a one-element scale plane, made by the
+     * recipe (data/recipes/qwen4exp-w4.recipe); the gather takes them as two operands. The name map
+     * joins the shards along rows and is declared first, since the encoding is looked up through
+     * it. RAD_ACCESS_VOCAB: it is a vocabulary table, just not the token one. */
     const char* tn = nm.f("blk.%d.ple_ngram.weight", layer);
     RAD_ARCH_TRY(map_concat_shards(b, tn, src.shard_prefix, src.shard_suffix, (int)c.shards, 0));
-    /* OR THE CHECKPOINT'S OWN bf16 TABLE, 102 GB, when the container holds it as it ships: the
-     * same op with no scale (embed_lookup_q's absent scale is one), so it stays a host gather over
-     * the mapping like the E4M3 one -- the gather's row cache serves either row size. */
+    /* Or the checkpoint's own bf16 table (102 GB) when the container holds it as shipped: the same
+     * op with no scale (an absent scale means 1), still a host gather over the mapping. */
     RadEncoding te{};
     table_bf16 = weight_enc(b, tn, &te) && rad_enc_is(&te, "plain") && te.n_planes == 1 &&
                  te.plane[0].dtype == RAD_BF16;
@@ -227,8 +192,8 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
                             RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
     }
 
-    /* I64 AND NOT I32. The multipliers are ~2.4e13 -- the hash's whole point is that a token id
-     * times one of them fills sixty-three bits -- so narrowing them would change every id. */
+    /* I64: the multipliers are ~2.4e13 (a token id times one fills 63 bits), so narrowing them
+     * would change every id. */
     RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_mult", layer), src.mult));
     w_mult = decl_w(b, nm.f("blk.%d.ple_mult", layer), RAD_I64, {c.ngram},
                     RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
@@ -240,8 +205,7 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
                    RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
 
     /* ---- the projections and the three gains ------------------------------------------------ */
-    /* BF16 AND NOT fp8: `modules_to_not_convert` in the FP8 checkpoint names both projections, so
-     * these arrive dense whichever checkpoint is the source. */
+    /* bf16: the FP8 checkpoint's `modules_to_not_convert` names both projections. */
     RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_key.weight", layer), src.key_proj));
     w_key = decl_w(b, nm.f("blk.%d.ple_key.weight", layer), RAD_BF16, {HN, c.embed_dim},
                    RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
@@ -269,15 +233,13 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
         !w_nk || !w_nq || !w_nc || !w_conv) return RAD_E_INVAL;
 
     /* ---- the two rolling windows ------------------------------------------------------------ */
-    /* RAD_KV_CONV is "per-sequence, a rolling window of width-1 + num_spec entries", which is both
-     * of these. The token window's `conv_width` is ngram, so its window is ngram - 1 + n_spec.
+    /* RAD_KV_CONV is a per-sequence rolling window of width-1 + num_spec entries. The token
+     * window's `conv_width` is ngram, so its window is ngram - 1 + n_spec.
      *
-     * THE CHANNEL COUNT IS n_head_kv * head_dim AND NOT state_dim, which is the one field pair a
-     * reader of RadKVGroupDecl gets wrong: `state_dim` is RAD_KV_LINEAR's per-head geometry and
-     * the CONV kind never looks at it. Declared into state_dim, both of these size to zero bytes a
-     * sequence and the KV manager refuses the model at bring-up -- which is the good outcome, but
-     * rad-kbench cannot find it: it synthesises the state operand from the op's own shape function
-     * and never asks the manager for one. */
+     * The channel count is n_head_kv * head_dim, not `state_dim` (RAD_KV_LINEAR's per-head
+     * geometry, ignored by the CONV kind). Set via state_dim, both groups would size to zero and
+     * the KV manager would refuse the model; rad-kbench would not catch it, since it synthesises
+     * the state operand from the op's shape function. */
     {
         RadKVGroupDecl td{};
         td.kind = RAD_KV_CONV;
@@ -290,10 +252,9 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
         RadKVGroupDecl cd{};
         cd.kind = RAD_KV_CONV;
         cd.dtype = g.act_dtype;
-        /* The conv's history is (width-1)*dilation deep, so the GROUP's width -- which the manager
-         * reads as "window = conv_width - 1 + n_spec" -- is that plus one. Passing the raw
-         * conv_width here would size the window for an undilated convolution and the deepest tap
-         * would read a value that was never written. */
+        /* The conv's history is (width-1)*dilation deep, so the group's width (window =
+         * conv_width - 1 + n_spec) is that plus one; the raw conv_width would size an undilated
+         * window and the deepest tap would read unwritten data. */
         cd.conv_width = c.hist() + 1;
         cd.n_head_kv = 1;
         cd.head_dim = HN;           /* [n_states, hc*n_embd, hist + n_spec] */
@@ -304,49 +265,38 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
     RAD_ARCH_TRY(rad_bind_layer_kv(b, layer, kv_conv));
 
     /* ---- buffers ---------------------------------------------------------------------------- */
-    /* HOST DOMAIN for the two the gather touches. `ids` is written by ngram_ids and read by the
-     * gather; `e` is written by the gather and read by one device copy onto the card
-     * (`ple_emb_dev`, below). The host arena is mapped, so the device side of that hand-off is a
-     * link read (core/runtime/ctx.cpp) -- 5 KB a token at decode. Where a device kernel gathers
-     * (--ngram-placement ram or vram, with libr4d loaded) it reads `ids` and writes `e` over the
-     * link too, which costs a round trip of those 5 KB and leaves no host op in the step: the
-     * domain is declared here, before the placement that would say who gathers is decided.
+    /* The two buffers the gather touches are host domain. `ids` is written by ngram_ids and read by
+     * the gather; `e` is written by the gather and copied onto the card (`ple_emb_dev`). The host
+     * arena is mapped, so the device reads it over the link (core/runtime/ctx.cpp), 5 KB per token
+     * at decode. A device gather (--ngram-placement ram or vram, with libr4d) reads `ids` and
+     * writes `e` over the link too; the domain is fixed here, before placement decides who gathers.
      *
-     * `ids` IS PERSIST because it is written at the top of the step and read at this layer: the
-     * buffer plan computes liveness in DECLARED order, where the two ops are neighbours, and a
-     * transient would lend its bytes to anything issued in between. */
+     * `ids` is PERSIST: it is written at the top of the step and read at this layer, but liveness
+     * 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 own ids, then the ids of the prompt that follows it
-         * (RadBatch::n_ahead), which the gather hands to its reader to fetch while the step runs. */
+        /* 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. */
         RadBufDecl d{};
         d.dtype = RAD_I32; d.rank = 2; d.shape[0] = 2 * 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);
 
-        /* [max_tok, embed_dim] AND NOT [max_tok * heads, head_dim], because ONE declared shape has
-         * to serve two readings and only this one does. The gather writes `heads` rows a token and
-         * the projections read one row a token of `embed_dim` -- the same bytes either way -- and
-         * the direction that works is decided by HOW EACH KERNEL FINDS ITS ROW COUNT.
-         *
-         * The gather derives it: r4d_rows_pitch(x, n_embd) is numel / the width the kernel asks
-         * for, so [T, 2560] read at 160 IS T*16 rows of 160. The GEMM does not: gemm_ops takes
-         * M = a->shape[0] and K = a->shape[1] straight off the operand, because a strided rank-3
-         * activation has to be refused rather than folded. So the wide shape serves both and the
-         * tall one serves only the gather: declared tall, the key projection is handed M = T*16,
-         * K = 160 against a [T, 10240] output and refuses the step. */
+        /* [max_tok, embed_dim], not [max_tok * heads, head_dim]: one shape must serve the gather
+         * (`heads` rows per token) and the projections (one `embed_dim` row per token). The gather
+         * derives its row count as numel / width (r4d_rows_pitch), so [T, 2560] read at 160 is
+         * T*16 rows. The GEMM takes M and K from the operand's shape (gemm_ops), so the tall shape
+         * would give it M = T*16, K = 160 and the step would be refused. */
         RadBufDecl e{};
         e.dtype = g.act_dtype; e.rank = 2;
         e.shape[0] = g.max_tok; e.shape[1] = c.embed_dim;
         e.kind = RAD_BUF_TRANSIENT; e.domain = RAD_DOMAIN_HOST;
         b_emb = rad_decl_buffer(b, nm.f("ple_emb"), &e);
     }
-    /* AND ITS COPY ON THE CARD, which is what the two projections read. `e` in the mapped host
-     * arena is a link read, and a GEMM does not read its A operand once: the tiled kernel reads
-     * each row band once a column block, 80 times for the key projection, every one of them a PCIe
-     * round trip or a hit on the copy that round trip left in the card's cache. At a 2048-token
-     * chunk the two projections take about 3.0 and 0.9 ms reading the host arena against 1.4 and
-     * 0.3 ms reading VRAM. One pass of the link into VRAM is 10.5 MB at a chunk and 5 KB a token
-     * at decode. */
+    /* The device copy the projections read. A tiled GEMM reads each A row band once per column
+     * block (80 times for the key projection), so reading `e` from the host arena repeats link
+     * traffic: at a 2048-token chunk the projections take about 3.0 and 0.9 ms from the host arena
+     * versus 1.4 and 0.3 ms from VRAM. The copy is 10.5 MB per chunk, 5 KB per token at decode. */
     b_embd = decl_b(b, nm.f("ple_emb_dev"), g.act_dtype, {g.max_tok, c.embed_dim});
     b_k   = decl_b(b, nm.f("ple_k"),   g.act_dtype, {g.max_tok, HN});
     b_v   = decl_b(b, nm.f("ple_v"),   g.act_dtype, {g.max_tok, g.n_embd});
@@ -356,12 +306,8 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
     if (!b_ids || !b_emb || !b_embd || !b_k || !b_v || !b_gv || !b_gvn || !b_out)
         return RAD_E_INVAL;
 
-    /* NO DERIVED BUFFER FOR THE STATE SLOTS, and that is worth saying because the obvious reading
-     * of the core says otherwise. `conv_state_index` exists, computes exactly the cursor these two
-     * states want, and is called by NO architecture plugin: rad_block_gdn_fp8.h takes
-     * `cv->state_index` straight off RadKVGroupBatch, which the step batch fills PER GROUP. This
-     * block does the same -- one fewer per-step computation, and the same number the working
-     * precedent uses.
+    /* State slots come from RadKVGroupBatch::state_index, filled per group by the step batch, as in
+     * rad_block_gdn_fp8.h; the core's `conv_state_index` is not used.
      *
      * ---- the ops, in the order step() issues them ------------------------------------------- */
     layer_ = layer;
@@ -372,20 +318,16 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
                    RAD_WEIGHTS(w_mult, w_vsz, w_off)),
                {}, {b_ids});
 
-    /* M IS T * heads HERE, not T: the gather fetches one table row per HEAD per token, and the
-     * band this op resolves on is that count. */
-    if (table_bf16)
+    /* M is T * heads: the gather fetches one table row per head per token, and the band resolves
+     * on that count. */
+    {
+        const rad_weight wt[2] = { w_table, w_scale };   /* a bf16 table has no scale plane */
         op_gather = rw(b, RAD_OP(b, "embed_lookup_q",
                           RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * c.heads), RAD_INT("n_embd", HD),
                                      RAD_INT("n_vocab", c.rows), RAD_STR("dtype", g.dtype)),
-                          RAD_WEIGHTS(w_table)),
+                          wt, table_bf16 ? 1 : 2),
                       {b_ids}, {b_emb});
-    else
-    op_gather = rw(b, RAD_OP(b, "embed_lookup_q",
-                      RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * c.heads), RAD_INT("n_embd", HD),
-                                 RAD_INT("n_vocab", c.rows), RAD_STR("dtype", g.dtype)),
-                      RAD_WEIGHTS(w_table, w_scale)),
-                  {b_ids}, {b_emb});
+    }
 
     op_embd = rw(b, RAD_OP(b, "cast",
                      RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", c.embed_dim),
@@ -404,8 +346,8 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
                      RAD_WEIGHTS(w_value)),
                  {b_embd}, {b_v});
 
-    /* `q` IS THE INCOMING STREAM ITSELF, un-normed: the op owns all three norms because the third
-     * is taken over bytes it wrote. */
+    /* `q` is the incoming stream, un-normed; the op applies all three norms because the third is
+     * over bytes it writes. */
     op_gate = rw(b, RAD_OP(b, "ple_gate",
                     RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
                                RAD_INT("hc", c.hc), RAD_F64("eps", g.eps),
@@ -420,9 +362,8 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
                     RAD_WEIGHTS(w_conv)),
                 {b_gvn, b_gv}, {b_out});
 
-    /* AND THE ADD INTO THE STREAM. The reference is `hidden_states = hidden_states + ple(...)`,
-     * and `ple(...)` is what ple_conv already produced -- the convolution's residual operand
-     * folded the layer's own `gv + silu(conv)`, so what is left is one add of the whole thing. */
+    /* The add into the stream: `hidden_states + ple(...)`, where ple_conv's residual operand
+     * already produced `gv + silu(conv)`. */
     op_add = rw(b, RAD_OP(b, "add",
                    RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", HN),
                               RAD_STR("dtype", g.dtype)),
@@ -435,26 +376,19 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
     return RAD_OK;
 }
 
-/* THE SLOTS COME OFF THE GROUP BATCH, per group, exactly as the gated delta net reads them. And
- * `has_init` is `ctx_lens`: a sequence with computed tokens behind it has a history, one without
- * has none, which is the same test rad_block_gdn_fp8.h makes of the same field.
+/* Slots come from the group batch, and `has_init` is `ctx_lens` (nonzero means a history), as in
+ * rad_block_gdn_fp8.h.
  *
- * THE TWO WINDOWED OPS ARE ISSUED ONCE PER HALF OF THE STEP. The step is sorted decode-first, so
- * the decode rows are sequences [0, D) holding tokens [0, DT) and the prefill chunks are sequences
- * [D, S) holding the rest (batch_split). The decode half passes `num_accepted`, which is what
- * makes the op leave its window in the layout a partly rejected verify can be read back from; the
- * prefill half passes none, so each chunk leaves its tail at offset zero. A pure step issues one
- * half, so a pure decode step is one launch and only a mixed step pays a second.
+ * The two windowed ops are issued once per half of the step (batch_split: decode sequences
+ * [0, D) with tokens [0, DT) first, then prefill). The decode half passes `num_accepted`, so the
+ * op leaves its window readable after a partial rejection; the prefill half passes none and leaves
+ * each chunk's tail at offset zero. The prefill half gets per-sequence arrays at `+ D` with token
+ * operands at their base (kernels use the absolute offsets in `cu`); the decode half narrows to DT
+ * rows.
  *
- * The prefill half is addressed the way the GDN's is: the per-sequence arrays move to `+ D` and
- * the token operands stay at their base, because each kernel takes a sequence's rows from the
- * ABSOLUTE offsets in `cu`. The decode half is the prefix, so it narrows to DT rows instead. */
-/* THE HASH GOES FIRST IN THE STEP, AHEAD OF EVERY LAYER. It reads the batch's token ids and its
- * own rolling window and nothing the trunk computes, so it can run as soon as the batch has been
- * uploaded. The gather that consumes it runs on the host and has to wait for it; issued here, that
- * wait is for one small kernel, and the layers issued between the two keep the device busy while
- * the host gathers. Issued at the layer, the wait would be for every layer in front of it, and the
- * device would sit idle through the gather. */
+ * ids() runs first in the step, before every layer: it reads only the token ids and its own
+ * window. The host gather that consumes it then waits for one small kernel, and the layers issued
+ * in between keep the device busy during the gather. */
 inline void PleLayer::ids(RadCtx* c_, const RadBatch* batch) const {
     const int64_t T = batch->n_tok;
     const int64_t S = batch->n_seq;
@@ -475,9 +409,9 @@ inline void PleLayer::ids(RadCtx* c_, const RadBatch* batch) const {
                     praw(batch->ctx_lens, RAD_I32, D),
                     praw(batch->num_accepted, RAD_I32, D),
                     brows(b_ids, DT), RAD_NONE);
-    /* THE PROMPT THAT FOLLOWS the last prefill chunk is hashed in the same launch, into the rows
-     * after the step's: `tok` then reaches past the step by that many tokens, and the window the
-     * op leaves behind is the step's alone. */
+    /* The prompt following the last prefill chunk is hashed in the same launch into the rows
+     * after the step's (`tok` reaches A tokens past the step); the window left behind is the
+     * step's alone. */
     const int64_t A = P > 0 ? ahead_rows(batch) : 0;
     if (P > 0)
         RAD_ISSUE_N(c_, op_ids, T,
@@ -494,7 +428,6 @@ inline void PleLayer::ids(RadCtx* c_, const RadBatch* batch) const {
 inline void PleLayer::step(RadCtx* c_, const RadBatch* batch) const {
     const int64_t T = batch->n_tok;
     const int64_t S = batch->n_seq;
-    const int64_t HD = c.head_dim();
 
     const RadKVGroupBatch* cv = kv_batch(batch, kv_conv);
     const int32_t* cv_idx = cv ? cv->state_index : nullptr;
@@ -503,17 +436,14 @@ inline void PleLayer::step(RadCtx* c_, const RadBatch* batch) const {
     batch_split(batch, &D, &DT);
     const int64_t P = S - D;
 
-    /* T ROWS, not T * heads: the buffer is [max_tok, embed_dim] and the gather derives its own
-     * 16-rows-a-token reading out of numel. The op's M band is still T * heads -- that is how many
-     * table rows it fetches -- but the OPERAND is the token count. */
-    /* The ids of the prompt that follows, which the gather's reader fetches while this step
-     * runs, so the next step finds its rows already read. */
+    /* Operands are T rows (the gather derives its per-head rows from numel); the op's M band is
+     * T * heads. The trailing operand is the following prompt's ids, which the gather's reader
+     * prefetches for the next step. */
     const int64_t A = P > 0 ? ahead_rows(batch) : 0;
     RAD_ISSUE_N(c_, op_gather, T * c.heads,
                 brows(b_ids, T), RAD_W(w_table), table_bf16 ? RAD_NONE : RAD_W(w_scale),
                 brows(b_emb, T),
                 A > 0 ? brow_slice(b_ids, T, A, c.heads) : RAD_NONE);
-    (void)HD;
 
     RAD_ISSUE_N(c_, op_embd,  T, brows(b_emb, T), brows(b_embd, T));
     RAD_ISSUE_N(c_, op_key,   T, brows(b_embd, T), RAD_W(w_key),   brows(b_k, T));
@@ -541,9 +471,7 @@ inline void PleLayer::step(RadCtx* c_, const RadBatch* batch) const {
                     RAD_NONE,
                     brows(b_out, T));
 
-    /* M IS T, not T * HN. `add` counts ROWS of `n` -- every other block in this tree issues it
-     * that way -- and the declared band is 1..max_tok. Passing the element count instead lands
-     * outside every band of the op's own bucket table and the run phase refuses the step. */
+    /* M is T rows of `n`, not the element count, matching the declared band 1..max_tok. */
     RAD_ISSUE_N(c_, op_add, T, brows(w.h, T), brows(b_out, T), brows(w.h, T));
 }
 
diff --git a/arch/common/rad_block_vit.h b/arch/common/rad_block_vit.h
index 217cb2de..9d0186e2 100644
--- a/arch/common/rad_block_vit.h
+++ b/arch/common/rad_block_vit.h
@@ -14,22 +14,20 @@
  *     x += fc2(gelu_tanh(fc1(LN2(x))))
  *   out = fc2'(gelu(fc1'(LN(x) viewed [P/merge^2, merge^2 * width])))   the patch merger
  *
- * which is transformers' Qwen3_5VisionModel. Qwen3-VL's DEEPSTACK taps -- the residual stream
- * after named blocks, each through a merger of its own whose norm is taken AFTER the 2x2 view
- * (over merge^2 * width), into rows added to the language model's hidden state after its first
- * layers -- are declared only for a plugin that asks (declare's `deepstack`); one that does not is
- * refused a tower with taps rather than served without them. Every linear layer is
- * `gemm_nt_bias` with its activation and residual in the epilogue, each rounded where the
- * reference's separate tensors are.
+ * which is transformers' Qwen3_5VisionModel. Qwen3-VL's deepstack taps (the residual stream after
+ * named blocks, each through its own merger whose norm is taken after the 2x2 view, over
+ * merge^2 * width, added to the language model's hidden state after its first layers) are declared
+ * only for a plugin that passes `deepstack`; otherwise a tower with taps is refused. Every linear
+ * is `gemm_nt_bias` with activation and residual in the epilogue, rounded where the reference's
+ * separate tensors are.
  *
- * EVERY RANK RUNS THE WHOLE TOWER. Its weights are replicated rather than sharded: the rows are
- * needed on every rank (each rank embeds every token), and a tower split across ranks would pay a
- * collective per layer to save compute that happens once per picture. The weights are
+ * Every rank runs the whole tower with replicated weights: every rank embeds every token, and
+ * sharding would cost a collective per layer for once-per-picture compute. Weights are
  * RAD_ACCESS_PER_REQUEST, so placement may keep them off the card when VRAM is short.
  *
- * ITS ACTIVATIONS ARE SIZED BY THE PASS, not by a step: RadBuildCtx::max_enc_patches rows. A
- * sizing declare (shape_probe) sizes them by the probe's step instead, which keeps the tower out
- * of the smaller arena levels -- an encoder pass always runs at the full plan (Engine::arena_step).
+ * Activations are sized by the pass (RadBuildCtx::max_enc_patches rows), except in a sizing
+ * declare (shape_probe), which uses the probe's step to keep the tower out of the smaller arena
+ * levels; an encoder pass always runs at the full plan (Engine::arena_step).
  */
 #ifndef RAD_BLOCK_VIT_H
 #define RAD_BLOCK_VIT_H
@@ -65,8 +63,8 @@ struct VisionTower {
     rad_buf b_x = 0, b_h = 0, b_qkv = 0, b_att = 0, b_ff = 0, b_mh = 0, b_mf = 0, b_out = 0;
     char    sec[48] = {};
 
-    /* DEEPSTACK: tap t is the residual stream after block `ds_layer[t]`, merged into `b_ds[t]`
-     * ([P / merge^2, n_embd], one row a merged token, in the order `b_out` holds them). */
+    /* Deepstack: tap t is the residual stream after block `ds_layer[t]`, merged into `b_ds[t]`
+     * ([P / merge^2, n_embd], one row per merged token, in `b_out`'s order). */
     enum { MAX_DS = 4 };
     int        n_ds = 0;
     int        ds_layer[MAX_DS] = {};
@@ -75,8 +73,7 @@ struct VisionTower {
     rad_op     ds_ln[MAX_DS] = {}, ds_1[MAX_DS] = {}, ds_2[MAX_DS] = {};
     rad_buf    b_ds[MAX_DS] = {};
 
-    /* Is there a tower to declare: the container carries one and the deployment asked for media.
-     * `why` is set when the container carries one this block cannot serve. */
+    /* Whether the container carries a vision tower. */
     static bool present(const RadModelMeta* m) {
         return rad_meta_geti(m, "vision_config.depth", 0) > 0;
     }
@@ -112,15 +109,14 @@ inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadB
                 (long long)ff, (long long)patch, (long long)merge, (long long)npos);
         return RAD_E_INVAL;
     }
-    /* THE MERGER WRITES ROWS OF THE MODEL'S OWN WIDTH, or its rows could not replace a token's. */
+    /* The merger's rows replace token embeddings, so they must be the model's width. */
     if (n_embd != model_embd) {
         fprintf(stderr, "radiance: the vision tower emits %lld-wide rows and the model embeds "
                         "%lld-wide tokens\n", (long long)n_embd, (long long)model_embd);
         return RAD_E_INVAL;
     }
-    /* DEEPSTACK -- tower layers feeding the language model's early layers directly -- is a second
-     * input path, and a plugin that does not consume it is refused the tower by name rather than
-     * served without it. */
+    /* Deepstack feeds tower layers into the language model's early layers; a plugin that does not
+     * consume it is refused the tower. */
     const char* ds = rad_meta_gets(m, "vision_config.deepstack_visual_indexes", "");
     n_ds = 0;
     for (const char* q = ds; q && *q;) {
@@ -154,13 +150,13 @@ inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadB
 
     const int64_t mm = merge * merge;
     P = ctx->max_enc_patches;
-    /* The longest segment attention may see: the REAL pass size in a sizing declare too. It is a
-     * fixed parameter the kernel is chosen by, and the engine runs the real declare's kernel at
-     * every level; only the ranged row counts may follow the probe's step. */
+    /* The longest segment attention may see: the real pass size, even in a sizing declare. It
+     * selects the kernel, and the engine runs the real declare's kernel at every level; only the
+     * ranged row counts may follow the probe's step. */
     const int64_t max_seg = P;
     if (ctx->shape_probe) {
-        /* A sizing declare: the tower's rows follow the probe's step, which keeps its activations
-         * out of the levels a decode step runs at. Rounded to a whole merged row. */
+        /* A sizing declare: rows follow the probe's step (rounded to whole merged rows), keeping
+         * the activations out of the levels a decode step runs at. */
         const int64_t r = std::min(P, ctx->max_tok);
         P = std::max(mm, r / mm * mm);
     }
@@ -168,12 +164,12 @@ inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadB
     const int64_t R = P / mm;
     const int ACC = RAD_ACCESS_PER_REQUEST;
 
-    /* ---- weights. Replicated; model-level groups for the stem and the merger, and one group a
-     * block from `first_group` on, past every language layer, so a tower block is its own unit
-     * of movement and never shares one with a text layer. */
+    /* ---- weights, replicated. Model-level groups for the stem and merger; one group per block
+     * from `first_group` on (past every language layer), so a tower block is its own movement
+     * unit. */
     auto bw = [&](const char* dn, const char* src, uint32_t dt, std::initializer_list shp,
                   RadWeightGroup g) -> rad_weight {
-        /* the map first: it is how the checkpoint is asked what the weight is */
+        /* map first: the weight's encoding is looked up through it */
         if (map_copy(b, dn, src) < 0) return 0;
         return decl_w(b, dn, dt, shp, ACC, RAD_SHARD_NONE, g);
     };
@@ -221,9 +217,9 @@ inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadB
             return RAD_E_INVAL;
     }
 
-    /* ---- activations. `mh` is the merger's input, declared at the MERGED width: the norm writes
-     * it as P rows of `width` and the first merger layer reads it as P/mm rows of mm * width,
-     * which is the same bytes -- the reference's view(), with no copy. */
+    /* ---- activations. `mh`, the merger's input, is declared at the merged width: the norm writes
+     * P rows of `width` and the first merger layer reads the same bytes as P/mm rows of
+     * mm * width (the reference's view(), no copy). */
     b_x   = decl_b(b, nm.f("v.x"),   RAD_BF16, { P, width });
     b_h   = decl_b(b, nm.f("v.h"),   RAD_BF16, { P, width });
     b_qkv = decl_b(b, nm.f("v.qkv"), RAD_BF16, { P, 3 * width });
@@ -282,11 +278,10 @@ inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadB
     op_mln = rw(b, lnorm(P, mn_w, mn_b), { b_x }, { b_mh });
     op_m1  = rw(b, gemm(R, mm * width, mm * width, "gelu", m1_w, m1_b), { b_mh }, { b_mf });
     op_m2  = rw(b, gemm(R, n_embd, mm * width, "none", m2_w, m2_b), { b_mf }, { b_out });
-    /* A deepstack merger normalises AFTER the view, over a merged row: the same bytes as P rows of
-     * `width`, read as R rows of merge^2 * width. Its ops are declared here, after the tower, and
-     * issued between its blocks; their working planes are consumed before the next block runs.
-     * Each tap's OUTPUT is not -- it waits for the language model while the remaining blocks
-     * overwrite the tower's planes -- so it is PERSIST, outside the planner's sharing. */
+    /* A deepstack merger normalises after the view, over R rows of merge^2 * width. Its ops are
+     * declared after the tower and issued between blocks; their working planes are consumed before
+     * the next block. Each tap's output must survive until the language model reads it, so it is
+     * PERSIST. */
     for (int t = 0; t < n_ds; ++t) {
         b_ds[t] = decl_b(b, nm.f("v.ds.%d.out", t), RAD_BF16, { R, n_embd }, RAD_BUF_PERSIST);
         if (!b_ds[t]) return RAD_E_INVAL;
@@ -327,8 +322,8 @@ inline void VisionTower::step(RadCtx* c, const RadBatch* batch) const {
                          "more patches than it was declared for, or not whole merged rows");
         return;
     }
-    /* The patches, their coordinates -- planes 0 and 1 are a dense [2, P] (row, column), all four
-     * a dense [4, P] -- and the segment boundaries, all staged by the core. */
+    /* Patches, coordinates (planes 0-1 a dense [2, P] of (row, column); all four a dense [4, P])
+     * and segment boundaries, staged by the core. */
     const RadOperand pix = praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim);
     const RadOperand rc  = praw2(batch->enc_coord, RAD_I32, 2, Pn);
     const RadOperand crd = praw2(batch->enc_coord, RAD_I32, 4, Pn);
@@ -362,8 +357,7 @@ inline void VisionTower::step(RadCtx* c, const RadBatch* batch) const {
                         brows(b_ds[t], Rn));
         }
     }
-    /* The merger norm writes P rows of `width` into a buffer declared at the merged width: the
-     * same bytes the next layer reads as P/mm rows. */
+    /* The merger norm writes P rows of `width`; the next layer reads them as P/mm merged rows. */
     RAD_ISSUE_N(c, op_mln, Pn, brows(b_x, Pn), RAD_W(mn_w), RAD_W(mn_b), brows(b_mh, Rn));
     RAD_ISSUE_N(c, op_m1, Rn, brows(b_mh, Rn), RAD_W(m1_w), RAD_W(m1_b), RAD_NONE,
                 brows(b_mf, Rn));
@@ -373,13 +367,12 @@ inline void VisionTower::step(RadCtx* c, const RadBatch* batch) const {
 
 /* ================================================================== the encoder rows
  *
- * THE ROWS AN ENCODER PRODUCED, OVER THE TOKEN EMBEDDINGS THEY REPLACE (RadBatch::mm_rows). One
- * `scatter_rows` over opaque bytes: a row is `n_embd` bf16, the destination the embedding buffer.
+ * Scatters encoder rows over the token embeddings they replace (RadBatch::mm_rows): one
+ * `scatter_rows` of `n_embd` bf16 rows into the embedding buffer.
  *
- * ISSUE IT BEFORE THE EMBEDDING'S REDUCTION. The lookup is vocab-sharded, so each rank's output is
- * a partial sum, and the core hands rank 0 the encoder rows and every other rank zeros: overwritten
- * there, the reduction that follows -- an all_reduce, or the first layer's fused norm -- counts
- * each row once, as it counts a token's embedding once. */
+ * Issue it before the embedding's reduction. The lookup is vocab-sharded, so each rank holds a
+ * partial sum; the core gives rank 0 the encoder rows and other ranks zeros, so the following
+ * reduction (an all_reduce, or the first layer's fused norm) counts each row once. */
 struct MediaRows {
     rad_op  op = 0;
     int64_t n_embd = 0;
diff --git a/arch/common/rad_fp8.h b/arch/common/rad_fp8.h
index 811feee4..e5a4012a 100644
--- a/arch/common/rad_fp8.h
+++ b/arch/common/rad_fp8.h
@@ -1,114 +1,87 @@
-/* rad_fp8.h -- the two pieces every block-scaled FP8 block is built from.
+/* rad_fp8.h -- the pieces every block-scaled FP8 block is built from: a linear whose weight is E4M3
+ * with a block scale plane, the activation quantisers that feed it, and the fused norm/residual/
+ * all-reduce front op.
  *
- * One plugin per (architecture, quantisation) is spec §2.4, and the file-count mitigation is that
- * the blocks are COMPOSITION (rad_arch.h). This is the composed piece the FP8 blocks share and the
- * bf16 ones have no use for: a linear layer whose weight is E4M3 with a block scale plane, and the
- * activation quantiser that feeds it.
+ * ============================== BLOCK-SCALED FP8 ==============================
  *
- * ============================== WHAT "BLOCK-SCALED FP8" IS ==============================
- *
- * The format is the checkpoint's, not this project's. Qwen3.8-27B-FP8 -- and every other
- * `quantization_config: {quant_method: fp8, weight_block_size: [128,128]}` release -- stores each
+ * The checkpoint's format. Qwen3.8-27B-FP8 and other
+ * `quantization_config: {quant_method: fp8, weight_block_size: [128,128]}` releases store each
  * linear as
  *
  *   .weight             F8_E4M3, row-major [N][K]
  *   .weight_scale_inv   BF16,    row-major [ceil(N/128)][ceil(K/128)]
  *
- * and libr4d's gemm_fp8a16_nt_m1 / gemm_fp8a8_nt_m16 / gemm_fp8a8_tiled read exactly those bytes
- * (libr4d/r4d_fp8_layout.cpp verified the grid against the real file). So rad-convert COPIES:
- * no permutation, no repacking, no dequantisation, and a .rad costs what the checkpoint does. That
- * is the whole reason this plugin family exists -- widening a 27B FP8 checkpoint to bf16 doubles
- * the weight bytes, which does not fit the device memory this engine is built for.
+ * and libr4d's fp8 GEMMs read those bytes (grid verified in libr4d/r4d_fp8_layout.cpp), so
+ * rad-convert copies them unchanged. Widening a 27B FP8 checkpoint to bf16 would double the
+ * weight bytes.
  *
- * ============================== WHY THE SCALE PLANE IS A WEIGHT ==============================
+ * ============================== THE SCALE PLANE IS A WEIGHT ==============================
  *
- * `gemm_nt_q`'s operand list is `a`, `a_scale`, `b`(w), `b_scale`(w) -> `y`, so the scale plane is
- * a first-class WEIGHT OPERAND and is declared here as its own rad_weight. It is not an `aux`
- * stream on the weight, and that is not a stylistic choice:
+ * `gemm_nt_q` takes `a`, `a_scale`, `b`(w), `b_scale`(w) -> `y`, so the scale plane is its own
+ * rad_weight rather than an `aux` stream: RadArgs cannot deliver an aux stream to a launch
+ * (libr4d/r4d_fp8_layout.cpp), and a weight can be placed, moved and load-time sharded on its own
+ * (a row-sharded [136,40] plane is sliced like its [17408,5120] weight). The cost is one extra
+ * weight per linear (2.1 KiB of scales against 89 MiB at gate_proj's shape) and a name-map entry,
+ * `_scale_inv`, derived here.
  *
- *   - RadLayout can declare an aux stream beside a weight, but RadArgs has NO WAY TO DELIVER one
- *     to a launch (libr4d/r4d_fp8_layout.cpp reports this). An aux scale would be unreachable
- *     at run time by construction.
- *   - a weight can be placed, moved and load-time SHARDED on its own. The engine slices a
- *     row-sharded [136,40] plane at dim 0 exactly as it slices the [17408,5120] weight, and an aux
- *     stream has no shard axis at all.
+ * ============================== FP8 ACTIVATIONS ==============================
  *
- * The cost is one extra declared weight per linear -- 2.1 KiB of scales against 89 MiB of weight at
- * gate_proj's shape -- and one extra name-map entry, which is `_scale_inv` and is derived
- * here rather than spelled at every call site.
+ * Every block-fp8 linear is `fp8a8`, whose two kernels cover every M (`nt_m16` to 16, `tiled`
+ * above), at the cost of quantising each activation that feeds a GEMM. libr4d's `fp8a16` matvec,
+ * which reads bf16 directly, is not used: it assumes 16 consecutive k of a row per lane, which the
+ * stored WMMA fragment order (libr4d/r4d_fp8_frag.h) does not provide.
  *
- * ============================== WHY THE ACTIVATIONS ARE FP8 TOO ==============================
- *
- * `dtype` is ONE string per declared op, so a linear is `fp8a16` or `fp8a8` and cannot be both.
- * fp8a16 reads a bf16 activation directly and needs no quantise launch, which is strictly better --
- * and its kernel is `M <= 1`. One row. That serves a single-sequence decode and nothing else: at
- * two concurrent sequences M is 2 and there is no kernel. So the shipped path is `fp8a8`, whose two
- * kernels between them cover every M (`nt_m16` to 16, `tiled` above), and the price is one
- * `quant_act_fp8` launch per activation that feeds a GEMM.
- *
- * PER ACTIVATION, NOT PER LINEAR. The three attention projections all read the post-norm hidden
- * state, and the GDN block's in and z projections both read it; quantising once and pointing every
- * linear at the same pair is the difference between one launch a layer and five. That is why
- * QuantFP8 is a separate struct from LinearFP8 rather than a step inside it.
+ * Quantisation is per activation, not per linear: the three attention projections, or the GDN's
+ * in and z projections, share one quantised input. Hence QuantFP8 is separate from LinearFP8.
  */
 #ifndef RAD_FP8_H
 #define RAD_FP8_H
 
 #include "rad_arch.h"
 
-#include 
 #include 
 #include 
 
 namespace rad {
 namespace arch {
 
-/* The scale block, in both dimensions. A property of the CHECKPOINT (`weight_block_size`), not a
- * knob: libr4d compiles it in as a shift and its constraint rows carry C_EQ("group", 128), so a
- * container quantised at any other width resolves to no kernel and says so by name. Declared as a
- * named constant because three files have to agree about it. */
+/* The scale block in both dimensions, fixed by the checkpoint (`weight_block_size`). libr4d
+ * compiles it in and its rows carry C_EQ("group", 128), so other widths resolve to no kernel. */
 enum { RAD_FP8_BLOCK = 128 };
 
 /* Rows of the scale plane for an N-row weight, and columns for a K-wide one. */
 inline int64_t fp8_blocks(int64_t n) { return (n + RAD_FP8_BLOCK - 1) / RAD_FP8_BLOCK; }
 
-/* An activation and its fp8 twin. The bf16 buffer is what the rest of the graph reads and writes;
- * the other two exist only between the quantiser and the GEMMs that consume them. */
+/* An activation and its quantised codes. The bf16 buffer is what the rest of the graph uses; the
+ * codes exist only between the quantiser and the GEMMs that consume them. */
 struct ActFP8 {
     rad_buf x = 0;   /* [max_tok, n]                bf16 */
     rad_buf q = 0;   /* [max_tok, n]                e4m3 */
     rad_buf s = 0;   /* [max_tok, ceil(n/block)]    f32 */
-    /* THE SAME ACTIVATION AT INT8 CODES, for an int8 linear (LinearFP8::i8): [max_tok, n] i8 and
-     * its f32 scale per (row, block). Declared only where a model's trunk is int8 (declare_qs's
-     * `i8`), and written either by the linear's own quant_act_i8g from `x` or, when `q8_fed`, by
-     * the producer itself. */
+    /* Int8 codes of the same activation, for an int8 linear (LinearFP8::i8): [max_tok, n] i8 and
+     * an f32 scale per (row, block). Declared only for an int8 trunk (declare_qs's `i8`); written
+     * by the linear's own quant_act_i8g from `x`, or by the producer when `q8_fed`. */
     rad_buf q8 = 0;
     rad_buf s8 = 0;
-    /* THE PRODUCER WRITES q8/s8 ITSELF -- a connection read (HyperConn::Config::codes_i8), a gated
-     * quantiser, the attention's gate epilogue, the delta net's output epilogue -- in place of
-     * the E4M3 pair, so an int8 linear reading this input declares no quantiser of its own. Set by
-     * the model when it declares the pair, before the wires copy it. */
+    /* The producer writes q8/s8 instead of the E4M3 pair (a connection read with
+     * HyperConn::Config::codes_i8, a gated quantiser, the attention gate or delta-net output
+     * epilogue), so an int8 linear reading it declares no quantiser. Set by the model when it
+     * declares the pair, before the wires are copied. */
     bool    q8_fed = false;
 
     /* The code pair the producer writes: int8 when the model fed it, E4M3 otherwise. */
     rad_buf cq() const { return q8_fed ? q8 : q; }
     rad_buf cs() const { return q8_fed ? s8 : s; }
 
-    /* Declare all three at once, since a caller that declared two of them is a caller with a bug.
-     * `x` is passed in rather than made here: it is usually a buffer the block already had.
+    /* Declares the codes (and the int8 pair with `i8`); `x` is set by the caller.
      *
-     * `rows` IS NOT OPTIONAL FOR A BUFFER THAT IS NOT ONE ROW A TOKEN, and leaving it at the
-     * default for one that is not is a silent arena overrun rather than a refusal. The default is
-     * `g.max_tok` because that is what an activation is; a MoE expert plane is `rows * top_k` and
-     * an encoder tower's is its own patch count. Getting it wrong is hard to see: a routed expert
-     * pair declared at max_tok while the gated quantiser writes `rows * top_k` overruns onto a
-     * buffer that may already be dead, so the model stays correct and only a later reader of that
-     * buffer sees it. core/runtime/issue.cpp refuses the issue by name, which is the guard; this
-     * is the honest declaration. */
+     * `rows` defaults to g.max_tok and must be given for any buffer that is not one row per token
+     * (a MoE expert plane is `rows * top_k`, an encoder tower's its patch count); too small a value
+     * overruns the arena (core/runtime/issue.cpp refuses such an issue). */
     int declare_qs(RadBuilder* b, Names& nm, const Geom& g, const char* name, int64_t n,
                    int64_t rows = 0, bool i8 = false) {
-        /* A bf16 model's linears read `x` and nothing else (Geom::w_bf16), so there are no codes
-         * to declare: an arena plane nothing writes is a plane the planner still charges. */
+        /* bf16 linears read only `x` (Geom::w_bf16), so declare no codes; an unused plane would
+         * still take arena space. */
         if (g.w_bf16) { q = s = q8 = s8 = 0; return RAD_OK; }
         const int64_t m = rows > 0 ? rows : g.max_tok;
         q = decl_b(b, nm.f("%s.q", name), RAD_F8E4M3, { m, n });
@@ -122,103 +95,34 @@ struct ActFP8 {
     }
 };
 
-/* HOW MANY TOKEN ROWS THE fp8a16 MATVEC COVERS, which is the one number that decides both which
- * GEMM a linear issues and whether the quantiser in front of it runs at all.
+/* The fused attention prologue's row band, shared by the block issuing it, the rope table fill,
+ * the QSA indexer reading that table, and the step deciding whether to fill it.
  *
- * IT IS ONE ROW. The multi-row matvec reads the weight once for all M rows, so widening the band
- * looks free; it is not. The matvec is issue-bound above one row: the per-row work is 27
- * instructions per 16 weight bytes and eight rows of it do not fit in the issue budget, so
- * effective weight bandwidth falls as M rises on identical weight traffic
- * (r4d_gemm_fp8a16_nt_m1.hip has the ISA counts). The fp8a8 tile's cost is flat in M to 16, so it
- * wins from two rows up and the crossover is not near eight.
- *
- * SO THE SHIPPED PATH IS W8A8, which is also what the checkpoint is: `quant=fp8_e4m3` with
- * `activation_scheme: dynamic`, and prefill always quantises. A deployment that speculates
- * runs T = 1 + n_spec on every trunk step, so it is W8A8 end to end and decode computes the
- * same function prefill does.
- *
- * WHAT ONCE KEPT A ROW FOR THE MATVEC was the standalone `quant_act_fp8` in front of every linear
- * -- one launch per activation per layer -- which the fp8a8 path needs and this one does not. The
- * fusions below remove it: the producer that feeds a linear quantises in its own epilogue
- * (`rmsnorm_quant_fp8`, `gated_quant_fp8`, `gate_quant_fp8`), so the fp8a8 path pays no extra
- * launch and the last argument for a wider matvec band goes with it. */
-/* ...AND IT IS DECLINED, because of where the fp8 weight is stored and what the matvec can read.
- *
- * The fp8 weight is stored in WMMA FRAGMENT ORDER (libr4d/r4d_fp8_frag.h): a (16 row, 64 k) tile
- * laid out as 32 lanes x 32 bytes, which is what lets the two fp8a8 GEMMs read a fragment straight
- * from a coalesced global load instead of transposing 16 rows through LDS. Both of them do, and
- * both are checked against the host reference.
- *
- * The matvec is built on the opposite premise -- "a lane reads 16 CONSECUTIVE k of one row", in
- * three separate read paths with their own RB blocking -- and 16 consecutive k of a row are not
- * contiguous in fragment order. Converting it is a rewrite of a tuned kernel, not an edit, so it
- * is not done here and the op is not declared rather than declared and wrong.
- *
- * WHAT THAT COSTS is the one-row band falling back to the fp8a8 tile, which serves M <= 16 and
- * therefore covers it. A deployment that speculates never takes this band at all: T is
- * 1 + n_spec on every trunk step. */
-inline int64_t fp8_matvec_rows(const Geom& g) {
-    (void)g;
-    return 0;
-}
-
-/* THE FUSED ATTENTION PROLOGUE'S BAND, asked here rather than restated because the block that
- * issues the fused op, the op that fills the rope table, the QSA indexer that reads that table and
- * the step that decides whether to fill it all have to agree on it.
- *
- * The fusion is bit-exact against the unfused path: the kernel reproduces `r4d_rmsnorm_bf16`'s
- * sum-of-squares fold element by element rather than folding eight elements a lane, and
- * r4d_selftest asserts byte equality over 1.8M elements at both gain widths. A fold order that
- * merely agrees to a ULP is not enough here -- it moves the engine's transcript.
- *
- * IT STOPS AT THE DECODE BAND, because a fusion that replaces four launches with one pays where
- * the launch is the cost and nowhere else. At a 2048-token chunk it is slightly slower than the
- * four separate kernels: those are already wide enough to fill the device, and the fused form
- * does strictly more arithmetic -- a rotary lane re-derives its partner's normed value rather than
- * taking it from a register. 64 is the same decode band the narrow GEMM and the gated fold use,
- * and for the same reason. */
+ * The fusion is bit-exact against the unfused path (r4d_selftest asserts byte equality over 1.8M
+ * elements at both gain widths; it reproduces `r4d_rmsnorm_bf16`'s sum-of-squares order). It stops
+ * at the 64-row decode band, like the narrow GEMM and the gated fold: at a 2048-token chunk the
+ * four separate kernels already fill the device and the fused form, which recomputes each rotary
+ * partner's normed value, is slightly slower. */
 inline int64_t qk_fuse_rows(const Geom& g) {
     return g.max_tok < 64 ? g.max_tok : 64;
 }
 
-/* THE ROPE TABLE'S HEIGHT. `rope_table` writes each position at its OWN row, and the fused
- * prologue and the QSA indexer read it there, so the table needs a row for every position a step
- * can name -- and a speculative step names positions past the context bound. The last verify of a
- * request that fills its context feeds position max_ctx - 2 and one more row a draft token, and a
- * draft round rotates at positions ahead of the committed end as well: `max_spec` rows past
- * `max_ctx` cover both, and the one after them keeps the bound from resting on that arithmetic
- * being exact. The extra rows are (max_spec + 1) * rot floats. */
+/* The rope table's height. `rope_table` writes each position at its own row, so the table needs a
+ * row for every position a step can name, and speculative steps (verify and draft rounds) name up
+ * to `max_spec` positions past `max_ctx`; one more row is margin. */
 inline int64_t rope_table_rows(const Geom& g) {
     return g.max_ctx + (g.max_spec > 0 ? (int64_t)g.max_spec : 0) + 1;
 }
 
-/* THE SMALLEST TOKEN COUNT AT WHICH A QUANTISED ACTIVATION IS ACTUALLY READ.
- *
- * `LinearFP8::step` takes the matvec at T <= fp8_matvec_rows(), and the matvec does not read
- * `a.q` or `a.s` -- libr4d says so itself about that kernel: "the ONLY member of this family that
- * does not need r4d_quant_act_fp8". Left unguarded, the quantiser in front of it runs anyway, so a
- * single-sequence decode step issues 256 launches -- one per activation per layer -- to produce
- * bytes nobody reads. A decode step's budget IS launches.
- *
- * The buffer PLAN is unaffected. Liveness comes from the declared op list, not from what a step
- * issues, so `q` and `s` keep their arena slots and an op that does read them at a larger T still
- * finds them where it expects. */
-inline int64_t fp8_quant_min_rows(const Geom& g) {
-    return fp8_matvec_rows(g) + 1;
-}
-
 /* ================================================================== the activation quantiser */
 struct QuantFP8 {
     ActFP8  a{};
     int64_t n  = 0;
-    /* The smallest T at which some linear reads what this produces; see fp8_quant_min_rows. */
-    int64_t min_rows = 1;
     rad_op  op = 0;
 
     int  declare(RadBuilder* b, const Geom& g, const ActFP8& act, int64_t width);
-    /* `r0`/`rows` narrow it to a RANGE of rows, the same spelling every other helper here takes.
-     * A mixed step needs it: only the prefill rows want the standalone quantiser, because the
-     * recurrent path folds it into its own epilogue. */
+    /* `r0`/`rows` narrow it to a row range: in a mixed step only the prefill rows need the
+     * standalone quantiser, since the recurrent path quantises in its epilogue. */
     void step(RadCtx* c, int64_t T, int64_t r0 = 0, int64_t rows = 0) const;
 };
 
@@ -227,11 +131,9 @@ inline int QuantFP8::declare(RadBuilder* b, const Geom& g, const ActFP8& act, in
     n = width;
     /* Nothing to quantise for a bf16 model: no op, and step() issues nothing. */
     if (g.w_bf16) { op = 0; return a.x ? RAD_OK : RAD_E_INVAL; }
-    min_rows = fp8_quant_min_rows(g);
     if (!a.x || !a.cq() || !a.cs() || n <= 0) return RAD_E_INVAL;
-    /* `dtype` here is the INPUT's, which is bf16 -- the output width is what the op name says.
-     * libr4d's row constrains it to bf16 for that reason and ref reads each operand's own dtype.
-     * An input the model feeds at int8 codes is quantised by quant_act_i8g into its int8 pair. */
+    /* `dtype` is the input's (bf16); the op name gives the output format. An input fed at int8
+     * codes is quantised by quant_act_i8g into its int8 pair. */
     op = rw(b, RAD_OP(b, a.q8_fed ? "quant_act_i8g" : "quant_act_fp8",
                RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n),
                           RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
@@ -243,61 +145,37 @@ inline int QuantFP8::declare(RadBuilder* b, const Geom& g, const ActFP8& act, in
 inline void QuantFP8::step(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const {
     if (!op) return;
     if (rows <= 0) rows = T - r0;
-    if (rows < min_rows) return;
     RAD_ISSUE(c, op, brow_slice(a.x, r0, rows, n), brow_slice(a.cq(), r0, rows, n),
               brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK));
 }
 
-/* ================================== the quantiser folded into the op that PRODUCES the row
+/* ================================== the quantiser folded into the op that produces the row
  *
- * QuantFP8 above is the standalone launch, and two thirds of them do not have to be. A decode
- * step issues ~300 quantisers across both ranks, and each is dominated by launch cost rather than
- * arithmetic: the work is 82 KiB of row. What it costs is a launch, a grid fill, and a second
- * pass over a row the previous kernel had in registers -- and for ~190 of the ~300 the previous
- * kernel is right there in the same block:
+ * A standalone quantiser is mostly launch cost (an 82 KiB row), and most have a producer in the
+ * same block:
  *
  *     rmsnorm -> quant     the input of every attention, GDN and MLP linear
  *     silu_mul -> quant    down_proj's input
  *
- * libr4d's `rmsnorm_quant_fp8` and `gated_quant_fp8` are those two producers with the quantiser on
- * the same pass. They still write the bf16 output the unfused producer wrote -- the fp8a16 matvec
- * reads it at one row -- and they take the codes over the BF16-ROUNDED value, so the bytes are the
- * unfused pair's exactly and generated text does not move.
+ * libr4d's `rmsnorm_quant_fp8` and `gated_quant_fp8` quantise in the producer's pass. They still
+ * write the bf16 output and take the codes from the bf16-rounded value, so the bytes match the
+ * unfused pair exactly.
  *
- * AND THE RESIDUAL ADD FOLDS IN TOO, which is another ~130 launches. `add` is the cheapest kernel
- * in the model and is almost entirely launch cost: 82 KiB of row is negligible traffic beside it.
- * Every block in this architecture ends the same way -- out-projection into
- * the shared `h` buffer, all-reduce, `x += h` -- and every block BEGINS with a norm of `x`. So the
- * add moves from the end of one block to the front of the next, where a kernel is already reading
- * both buffers, and `fold` is what says a block has a predecessor to add.
+ * The residual add folds in too. Every block ends with out-projection into the shared `h`,
+ * all-reduce, `x += h`, and begins with a norm of `x`, so the add moves to the next block's norm,
+ * which already reads both buffers; `fold` says a block has a predecessor to add. The kernel rounds
+ * the sum to bf16 and stores it before normalising (unlike the int8 sibling, which keeps the more
+ * accurate f32 sum), reproducing the unfused pair byte for byte. */
+/* Whether the two-rank all-reduce at `T` rows uses the exact wire. Must match the plugin's
+ * `all_reduce` row, which decides from the same three facts: lossy wire not accepted, a message
+ * the rotation's group of 64 does not tile, or a message under the byte floor. Every rank
+ * evaluates it on the same T.
  *
- * The kernel rounds the sum to bf16 and STORES it before normalising, which is not what the int8
- * sibling does: that one keeps the f32 sum, which is more accurate. This one reproduces the pair
- * it replaces to the byte, and byte-identical output across builds is the property this engine is
- * checked against.
- *
- * THE FOLDED FORM HAS NO min_rows. QuantFP8 declines to run below the matvec's band
- * because it would be producing bytes nobody reads; there is nothing to decline when the write is
- * two stores on a pass that happens anyway. */
-/* WHETHER THE ALL-REDUCE AT `T` ROWS WILL GO OUT ON THE EXACT WIRE, which is the one question the
- * fused form below turns on, and it is answered here rather than guessed because the plugin's
- * `all_reduce` row answers it per call from the same three facts: an install that forbids a lossy
- * wire, a message the rotation's group of 64 does not tile, or a message under the floor. Get this
- * wrong in the optimistic direction and a step issues the fused kernel where the collective needed
- * the compressed payload; get it wrong the other way and the pair runs, which merely costs the
- * unfused launch. Both ranks evaluate it on the same T, so neither can take a different branch.
- *
- * The 6-bit wire pushes 2.6x fewer bytes than the exact one, and the fused kernel carries BOTH
- * payloads -- so the question below decides which wire the fused op is issued with rather than
- * whether it is issued at all, and `ar_fused_ok` is the separate question of whether a fused form
- * exists for that answer.
- *
- * WHY THE FLOOR IS A FLOOR AND NOT A SWITCH: the trade is the message size, and it changes sign
- * across the band. At a single sequence the message is small -- T * n_embd * 2 bytes with T on the
- * order of 8 -- and the rotation's own arithmetic costs more than the bytes it saves, so the exact
- * wire wins. From two concurrent sequences up the message is large enough that the compressed wire
- * wins, and the margin grows monotonically with it, so there is no second crossover inside the
- * band. M is C * (1 + n_spec), and 128 KiB sits between the two regimes.
+ * The 6-bit wire carries 2.6x fewer bytes and the fused kernel carries both payloads, so this
+ * chooses the fused op's wire; `ar_fused_ok` says whether a fused form exists. The floor exists
+ * because small messages (one sequence, T around 8) lose more to the rotation's arithmetic than
+ * they save in bytes, while from two sequences up the compressed wire wins increasingly; 128 KiB
+ * sits between the regimes.
  */
 inline bool ar_wire_is_exact(const Geom& g, int64_t T) {
     if (g.world != 2) return false;
@@ -308,63 +186,49 @@ inline bool ar_wire_is_exact(const Geom& g, int64_t T) {
     return numel * 2 < g.wire_min_bytes;   /* bf16 on the wire */
 }
 
-/* WHAT THE COMPRESSED FUSED FORM NEEDS ON TOP OF THE WIRE ITSELF: the fused kernel gives a block
- * whole ROWS, because a sum of squares closes only over one, and it packs the wire in chunks of
- * this many elements -- so a chunk must not straddle a row, or the two ranks would disagree about
- * which bytes a block owns. Stated here rather than asked of the plugin for the same reason the
- * rotation's group of 64 is stated above: the architecture has to decide, at declare time and
- * identically on both ranks, whether the op exists at all. */
+/* The compressed fused form's packing chunk, in elements. The kernel gives each block whole rows
+ * (the sum of squares closes over one row), so a chunk must not straddle a row. Fixed here so
+ * every rank decides identically at declare whether the op exists. */
 static const int64_t kArWire6Chunk = 512;
 
-/* Whether the all-reduce at `T` rows can be folded into the norm that follows it. The exact wire
- * always can; the compressed one can when a chunk tiles the row. Both ranks evaluate it on the
- * same T, so neither can take a different branch, and the block in FRONT asks the same question
- * before deciding to skip its own collective. */
+/* Whether the all-reduce at `T` rows can be folded into the following norm: always on the exact
+ * wire, on the compressed one when a chunk tiles the row. The preceding block asks the same
+ * question before skipping its own collective. */
 inline bool ar_fused_ok(const Geom& g, int64_t T) {
     if (g.world != 2 || T * g.n_embd <= 0) return false;
     return ar_wire_is_exact(g, T) || (g.n_embd % kArWire6Chunk) == 0;
 }
 
-/* THE FOUR-RANK LOSSY WIRE'S TILE: tiered int8 in groups of 32, and a group may not straddle one
- * of the four shards, so a message whose element count is not a multiple of 128 goes out exact.
- * Stated here for the reason the rotation's group of 64 is stated in ar_wire_is_exact: the
- * architecture has to decide, identically on every rank, which wire a step's message takes. */
+/* The four-rank lossy wire's tile: tiered int8 in groups of 32 that may not straddle a shard, so a
+ * message whose element count is not a multiple of 128 goes out exact. */
 static const int64_t kArWideWireTile = 128;
 
-/* THE MOST ROWS A DECODE OR SPECULATIVE-VERIFY STEP CARRIES: one a sequence, and 1 + max_spec a
- * sequence at a verify (max_spec is 0 with speculation off), never more than max_tok. It is a fact
- * about this engine's own steps, which is why the architecture holds it. The four-rank fused write
- * and its gather are declared over M up to this, and ar_wide_write_exact takes no step above it, so
- * a step sent to them is always inside the range they were resolved for. */
+/* The most rows a decode or verify step carries: 1 + max_spec per sequence, at most max_tok. The
+ * four-rank fused write and gather are declared up to this, and ar_wide_write_exact takes no
+ * larger step. */
 inline int64_t ar_wide_write_rows(const Geom& g) {
     const int64_t r = g.max_seqs * (1 + (g.max_spec > 0 ? g.max_spec : 0));
     return r < g.max_tok ? r : g.max_tok;
 }
 
-/* THE ROWS THE EXACT FUSED WRITE IS DECLARED FOR: every step at two ranks, the decode and verify
- * steps at four (ar_wide_write_rows), and none at any other width. */
+/* Rows the exact fused write is declared for: every step at two ranks, decode and verify steps at
+ * four (ar_wide_write_rows), none otherwise. */
 inline int64_t ar_exact_write_rows(const Geom& g) {
     if (g.world == 2) return g.max_tok;
     if (g.world == 4) return ar_wide_write_rows(g);
     return 0;
 }
 
-/* THE FOUR-RANK FUSED WRITE'S STEPS. At four ranks ar_hc_write exists on the exact wire only, and
- * it is the exact ONE-SHOT with the write behind it. A step takes it where both of these hold:
+/* Whether a four-rank step takes the fused write (ar_hc_write, exact one-shot only). Both must hold:
  *
- *   rows      T is at most ar_wide_write_rows. The fused kernel is a one-shot, and the messages a
- *             one-shot is for are the decode and verify steps'. A larger step -- a prefill chunk --
- *             keeps the pair, and there the standalone `all_reduce`'s own size bands choose the
- *             one-shot or the two-shot: where that choice falls is the kernel library's to say,
- *             so the architecture holds no copy of it. The fused one-shot serves any message it was
- *             declared for with the same bytes, so this bound is a cost, not a correctness line.
- *   exact     --tp-wire exact, or a message the four-rank lossy row serves exactly itself: one
- *             kArWideWireTile does not tile, or one under `min_bytes`, both of which that row hands
- *             to the exact sum. ar_wire_is_exact's three facts, with that wire's tile.
+ *   rows      T <= ar_wide_write_rows (decode and verify steps). Larger steps keep the separate
+ *             `all_reduce`, whose size bands choose one-shot or two-shot. This is a cost bound,
+ *             not a correctness one.
+ *   exact     --tp-wire exact, or a message the four-rank lossy row sends exact anyway
+ *             (not a multiple of kArWideWireTile, or under `min_bytes`).
  *
- * ar_wire_is_exact itself stays false off two ranks: the embedding's collective asks it whether
- * layer 0's fused norm absorbs that reduction, and at four no norm does. Every rank evaluates this
- * on the same T, so none can take a different branch. */
+ * ar_wire_is_exact stays false off two ranks: the embedding's collective uses it to ask whether
+ * layer 0's fused norm absorbs the reduction, and at four ranks none does. */
 inline bool ar_wide_write_exact(const Geom& g, int64_t T) {
     if (g.world != 4 || T < 1 || T > ar_wide_write_rows(g)) return false;
     const int64_t numel = T * g.n_embd;
@@ -374,15 +238,15 @@ inline bool ar_wide_write_exact(const Geom& g, int64_t T) {
     return numel * 2 < g.wire_min_bytes;   /* bf16 on the wire */
 }
 
-/* WHETHER A GATED RESIDUAL'S EXACT FUSED WRITE TAKES THE ALL-REDUCE AT T ROWS: at two ranks on every
- * step whose wire is exact, at four where ar_wide_write_exact says so. The write
- * (HyperConn::ar_write) and the block in front (ar_taken with kArOutExact) both ask exactly this. */
+/* Whether a gated residual's exact fused write takes the all-reduce at T rows: at two ranks when
+ * the wire is exact, at four per ar_wide_write_exact. Asked by both the write (HyperConn::ar_write)
+ * and the preceding block (ar_taken with kArOutExact). */
 inline bool ar_exact_write_takes(const Geom& g, int64_t T) {
     return g.world == 2 ? ar_wire_is_exact(g, T) : ar_wide_write_exact(g, T);
 }
 
-/* WHICH WIRES THE CONSUMER OF A BLOCK'S ALL-REDUCE TAKES. A block is declared without knowing what
- * follows it, so the architecture tells it:
+/* Which wires the consumer of a block's all-reduce takes; a block is declared without knowing what
+ * follows, so the architecture tells it:
  *
  *   kArOutNorm   the next block's norm, which takes either wire it has a fused form for
  *                (ar_fused_ok);
@@ -397,8 +261,8 @@ enum ArOut : int {
     kArOutBoth  = 2,
 };
 
-/* WHETHER A BLOCK SKIPS ITS OWN ALL-REDUCE because its consumer takes it. The consumer asks the
- * same question of the same T, so the two cannot both skip it or both issue it. */
+/* Whether a block skips its own all-reduce because its consumer takes it. The consumer asks the
+ * same question of the same T, so exactly one of them issues it. */
 inline bool ar_taken(const Geom& g, int64_t T, bool out, int take) {
     if (!out) return false;
     if (take == kArOutBoth)  return true;
@@ -406,77 +270,118 @@ inline bool ar_taken(const Geom& g, int64_t T, bool out, int take) {
     return ar_fused_ok(g, T);
 }
 
-/* WHETHER A MoE BLOCK'S GATHER RIDES IN FRONT OF THE REDUCTION THAT FOLLOWS IT (ar_gather_hc_write).
- * `rows` and `rows6` are the bounds the fused op was declared for on the exact and on the rotated
- * wire, 0 where it was not: at most the tokens one MoE pass carries, so a step it serves is one
- * pass whose gather is the whole step's. The wire the step's message goes out on picks the bound:
- * the exact one wherever the exact fused write takes the step (ar_exact_write_takes -- at two
- * ranks ar_wire_is_exact itself, at four the decode and verify steps on the exact wire, where
- * `rows6` is always 0).
- * The block that would issue the gather and the write that would absorb it ask this of the same T
- * and the same bounds, so neither can skip it while the other issues it. */
+/* A caller that takes a block's all-reduce a piece at a time (qwen4exp_fp8's pipelined prefill).
+ * A block whose last stages are per row finishes its output `rows` rows at a time and calls `done`
+ * behind every piece but the last, so the caller can start that piece's reduction while the block
+ * works on the next; `handed` counts the calls. A block that cannot cut its output calls nothing
+ * and the caller issues every piece itself. The last piece is always the caller's: it waits for the
+ * first pieces, and a wait on the second lane is a wait on everything issued there. */
+struct ArPieces {
+    int64_t rows = 0;
+    void  (*done)(void* u, int64_t r0, int64_t n) = nullptr;
+    void*   u = nullptr;
+    int64_t handed = 0;
+    /* Optional, on the card: {0, rows, T} for a step of one prefill sequence in two pieces, so a
+     * block whose recurrence runs over cu_seqlens can run it a piece at a time (each piece the
+     * chunk a span of 1 makes, the state carried through the cache) and hand off the first
+     * piece's reduction before the second piece's projection. Null for any other step. */
+    const int32_t* cu = nullptr;
+    bool cuts(int64_t T) const { return done && rows > 0 && T > rows; }
+    void hand(int64_t r0, int64_t n) { done(u, r0, n); ++handed; }
+};
+
+/* Whether a MoE block's gather is folded into the following reduction (ar_gather_hc_write).
+ * `rows` and `rows6` are the fused op's declared bounds on the exact and rotated wires (0 if not
+ * declared), at most one MoE pass, so a served step is a single pass. The step's wire picks the
+ * bound: `rows` wherever ar_exact_write_takes (at four ranks `rows6` is always 0). The block and
+ * the write ask this with the same T and bounds, so they agree. */
 inline bool gather_taken(const Geom& g, int64_t T, int64_t rows, int64_t rows6) {
     const int64_t r = ar_exact_write_takes(g, T) ? rows : rows6;
     return r > 0 && T <= r;
 }
 
-/* WHAT A NORM MAY ABSORB FROM THE COLLECTIVE IN FRONT OF IT.
+/* Which preceding collective a norm may absorb.
  *
- * `kArAny` is every layer boundary: the predecessor reduced a PARTIAL SUM, both ranks contributed
- * real values, and the compressed wire is the trade this model already makes there.
+ * `kArAny`: a layer boundary, where the predecessor reduced partial sums and the compressed wire is
+ * acceptable.
  *
- * `kArExact` is the EMBEDDING, and the difference is not stylistic. That collective sums DISJOINT
- * rows -- one rank gathered the token and the other contributed zeros -- so the compressed wire
- * takes a value that is already exactly right and degrades it, at the model's INPUT, before any
- * layer runs. It also disagrees with the DRAFTER, whose own embedding reduction is exact, and a
- * trunk and a drafter that see different embeddings reject each other's tokens.
- *
- * It is visible in the output, not just in principle: allowing the compressed wire here changes
- * the greedy text, because a prompt of a few dozen tokens crosses --tp-wire-min-kb where an 8-row
- * decode step does not. Exact-only keeps the decode fold -- which is the whole win -- and leaves
- * prefill on the standalone collective. */
+ * `kArExact`: the embedding. Its collective sums disjoint rows (one rank has the token, the others
+ * zeros), so a lossy wire would only degrade an exact value at the model's input, and would differ
+ * from the drafter's exact embedding reduction, hurting acceptance. A prompt of a few dozen tokens
+ * crosses --tp-wire-min-kb, so allowing it changes greedy text. Exact-only keeps the decode fold
+ * and leaves prefill on the standalone collective. */
 enum ArFold : int {
     kArNone  = 0,
     kArAny   = 1,
     kArExact = 2,
 };
 
+/* Where trunk layer `l` of `n` does its residual add, for a trunk of fp8 blocks whose feed-forward
+ * always folds its mixer's delta into its own norm (NormQuantFP8), so a mixer never adds.
+ *
+ * The mixer folds its predecessor's delta unless it is layer 0 or follows a layer that kept its
+ * add. A feed-forward keeps its add where something reads `x` between blocks: a drafter tap (in
+ * `taps`), which must see the layer's real output, and the final norm, a plain `rmsnorm` with no
+ * residual operand.
+ *
+ * The all-reduce moves with the add, at two ranks only (tp1 has no collective and there is no
+ * fused kernel at four): a block's norm absorbs the preceding collective where it folds. Layer 0's
+ * mixer does not fold but absorbs the vocab-sharded embedding's reduction (`embed_ar`), exact
+ * only (kArExact). */
+struct LayerFold {
+    bool mix_fold   = false;
+    int  mix_ar_in  = kArNone;
+    bool mix_ar_out = false;   /* the mixer leaves its collective to the feed-forward's norm */
+    bool mlp_add    = false;
+    int  mlp_ar_in  = kArNone;
+    bool mlp_ar_out = false;
+};
+
+inline LayerFold layer_fold(const Geom& g, int64_t l, int64_t n, const int* taps, int n_taps,
+                            bool embed_ar) {
+    auto tapped = [&](int64_t i) { return std::find(taps, taps + n_taps, (int)i) != taps + n_taps; };
+    const bool tp2 = g.world == 2;
+    LayerFold f;
+    f.mix_fold   = l > 0 && !tapped(l - 1);
+    f.mix_ar_in  = !tp2 ? kArNone : f.mix_fold ? kArAny : (l == 0 && embed_ar) ? kArExact : kArNone;
+    f.mix_ar_out = tp2;
+    f.mlp_add    = tapped(l) || l + 1 >= n;
+    f.mlp_ar_in  = tp2 ? kArAny : kArNone;
+    f.mlp_ar_out = tp2 && !f.mlp_add;
+    return f;
+}
+
 struct NormQuantFP8 {
     ActFP8     a{};
     rad_weight w = 0;
-    /* What the norm is taken of. Without a fold that is the residual stream itself; with one it is
-     * the PREVIOUS block's delta, which this op adds into the stream first. */
+    /* The norm's input: the residual stream, or with a fold the previous block's delta, which the
+     * op first adds into the stream (`res`). */
     rad_buf    src = 0;
     rad_buf    res = 0;
     rad_op     op = 0;
-    /* ...AND THE SAME OP WITH THE PRECEDING ALL-REDUCE FOLDED INTO IT. Declared only where the
-     * predecessor has an all-reduce whose output this norm is the sole consumer of, which is
-     * exactly where `residual` is non-null: `src` is then the delta buffer the collective wrote
-     * and nothing between the two reads it. BOTH are declared and the choice is made at step time,
-     * because the wire the collective picks depends on T and the fused kernel serves one of them.
-     * The predecessor asks the same question and skips its own all_reduce on the same answer. */
+    /* The same op with the preceding all-reduce folded in, declared when the caller passes
+     * `fuse_ar` (this norm is the collective's sole consumer). Both forms are declared and step()
+     * chooses, since the wire depends on T; the predecessor asks the same question and skips its
+     * own all_reduce on the same answer. */
     rad_op     op_arn = 0;
-    /* ...and the same fused op again with the ROTATED 6-BIT payload, which is the one a served
-     * step actually issues: the message is T * n_embd * 2 bytes and T is n_seq * (1 + n_spec), so
-     * it crosses --tp-wire-min-kb at the second concurrent sequence and stays across it. Declared
-     * separately rather than parameterised at step time because a wire is a declaration-time
-     * parameter of the op, and the two are chosen between exactly as `op_arn` and `op` are. */
+    /* The fused form on the rotated 6-bit wire, taken from the second concurrent sequence up
+     * (the T * n_embd * 2-byte message then crosses --tp-wire-min-kb). The wire is a declare-time
+     * parameter, hence a separate op. */
     rad_op     op_arn6 = 0;
     Geom       gm{};
-    /* The row width, kept so a ROW SLICE can turn a row offset into an element offset. */
+    /* The row width, for turning a row slice into element offsets. */
     int64_t    n = 0;
 
     int  declare(RadBuilder* b, const Geom& g, rad_weight gain, rad_buf x, const ActFP8& act,
                  int64_t n, rad_buf residual = 0, int64_t max_rows = 0, int fuse_ar = kArNone);
     void step(RadCtx* c, int64_t T, int64_t r0 = 0, int64_t rows = 0) const;
-    /* Which of the three this step runs. The exact wire and the compressed one each have a fused
-     * form; without one, the pair. */
+    /* The op this step runs: the fused form for the step's wire if declared, else the plain op. */
     rad_op pick(int64_t T) const {
         if (op_arn && ar_wire_is_exact(gm, T)) return op_arn;
         if (op_arn6 && ar_fused_ok(gm, T)) return op_arn6;
         return op;
     }
-    /* What the block in FRONT of this one asks before issuing its own collective. */
+    /* Asked by the preceding block before issuing its own collective. */
     bool takes_ar(int64_t T) const { return pick(T) != op; }
 };
 
@@ -489,9 +394,8 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain,
     res = residual;
     gm = g;
     this->n = n;                    /* the parameter shadows the member; the member is the pitch */
-    /* A bf16 model of this family takes every block input from its gated residual (hc_read) and
-     * declares no block norm; a pre-norm model served bf16 is the bf16 blocks' (rad_block_*.h), not
-     * these. Refused by name rather than declared as a quantiser nothing reads. */
+    /* bf16 models of this family take block inputs from hc_read and declare no block norm; a
+     * pre-norm bf16 model uses the bf16 blocks. */
     if (g.w_bf16) {
         fprintf(stderr, "radiance: a fused norm and quantiser was declared on a model whose "
                         "linears are bf16; its blocks take a prepared input instead\n");
@@ -505,26 +409,21 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain,
                            RAD_F64("wadd", g.wadd)),
                 RAD_WEIGHTS(w));
     if (!op) return RAD_E_INVAL;
-    /* Not rw()'s two initializer_lists, because the sets are conditional and a braced list in a
-     * ternary has no lifetime extension. `residual` is read AND written, so it is in both: the
-     * buffer planner reads these for liveness, and an INOUT that claimed only one of them is a
-     * use-after-free waiting for a plan that reorders around it. */
+    /* Arrays rather than rw(): the sets are conditional, and a braced list in a ternary is not
+     * lifetime-extended. `residual` is INOUT, so it is in both sets; otherwise the planner could
+     * reorder a reader around it. */
     rad_buf rd[2] = { src, res };
     rad_buf wr[4] = { a.q, a.s, a.x, res };
     rad_op_reads (b, op, rd, res ? 2 : 1);
     rad_op_writes(b, op, wr, res ? 4 : 3);
 
-    /* THE FUSED FORM'S EXTRA OUTPUT IS THE REDUCED MESSAGE IN `src`, and whether that is new
-     * liveness depends on which form this is. A FOLDED norm's `src` IS `a.x` -- the same buffer,
-     * already in the write set. An UNFOLDED one's `src` is the residual stream itself and is NOT,
-     * so it is added: the buffer planner reads these sets, and a collective writing a buffer it is
-     * not recorded as writing is a plan free to reorder a reader in front of it.
+    /* The fused form also writes the reduced message into `src`. With a fold, `src` is `a.x`,
+     * already in the write set; without one it is the residual stream, so it is added (as `res`'s
+     * slot) to keep liveness correct.
      *
-     * `res` is NOT required. A fused collective mostly makes sense where the predecessor left a
-     * delta, but the EMBEDDING is a predecessor too, and with a vocab-sharded table its gather is
-     * partial and needs exactly this reduction. That case has no residual: `x` is the stream, not
-     * a delta to add to one. The kernel compiles the arm (r4d_fused_quant_fp8.hip dispatches
-     * `res ? true : false`) and the schema marks `residual` optional. */
+     * `res` is optional: the embedding's partial (vocab-sharded) lookup also needs this reduction,
+     * with `x` the stream and no residual. The kernel supports it (r4d_fused_quant_fp8.hip) and the
+     * schema marks `residual` optional. */
     if (fuse_ar && g.world == 2) {
         op_arn = RAD_OP(b, "ar_rmsnorm_quant_fp8",
                         RAD_PARAMS(RAD_RANGE("M", 1, max_rows > 0 ? max_rows : g.max_tok),
@@ -538,10 +437,8 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain,
         rad_op_reads (b, op_arn, rd, res ? 2 : 1);
         rad_op_writes(b, op_arn, wr_ar, 4);
 
-        /* Declared only where the compressed wire can actually be reached and served: an install
-         * that forbids a lossy payload never picks it, and a width the wire's chunk does not tile
-         * would be a step-time shape refusal -- which in this engine is fatal -- rather than a
-         * choice not taken. */
+        /* Only where the compressed wire is reachable and servable: a lossy payload accepted, and
+         * the width tiled by the chunk (otherwise a fatal step-time shape refusal). */
         if (fuse_ar != kArExact && !g.wire_exact && (n % kArWire6Chunk) == 0) {
             op_arn6 = RAD_OP(b, "ar_rmsnorm_quant_fp8",
                              RAD_PARAMS(RAD_RANGE("M", 1, max_rows > 0 ? max_rows : g.max_tok),
@@ -559,14 +456,10 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain,
     return RAD_OK;
 }
 
-/* `r0` and `rows` are the ROW SLICE this issue covers, and they default to the whole step. At
- * offset 0 `brow_slice` builds exactly the operand `brows` did -- same rows, offset zero -- so the
- * unsliced path is unchanged by construction rather than by inspection.
- *
- * The slice is what lets a block run its rows in passes -- the routed feed-forward's, whose
- * expert planes are one pass tall. Its correctness rests on the band rule in core/runtime/ctx.h:
- * every slice must land in the same bucket-table band as the whole, or the op resolves to a
- * different kernel with a different summation order. */
+/* `r0`/`rows` select a row slice, defaulting to the whole step (`brow_slice` at offset 0 equals
+ * `brows`). Slicing lets a block run in passes (the routed feed-forward). Each slice must land in
+ * the same bucket-table band as the whole (core/runtime/ctx.h), or a different kernel with a
+ * different summation order would run. */
 inline void NormQuantFP8::step(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const {
     if (rows <= 0) rows = T - r0;
     RAD_ISSUE_N(c, pick(rows), rows, brow_slice(src, r0, rows, n),
@@ -576,23 +469,25 @@ inline void NormQuantFP8::step(RadCtx* c, int64_t T, int64_t r0, int64_t rows) c
                 brow_slice(a.x, r0, rows, n));
 }
 
-/* `act` is the vocabulary's name for the gate and it is a NAME: "silu" is down_proj's input,
- * "sigmoid" is a gated attention o_proj's. */
+/* Gate activation then quantise, over a [gate|up] input. `act` names the gate: "silu" for
+ * down_proj's input, "sigmoid" for a gated attention o_proj's. */
 struct GateQuantFP8 {
     ActFP8 a{};
     rad_op op = 0;
-    /* WHETHER THE bf16 PRODUCT IS WRITTEN AT ALL. `out_bf16` is not an optimisation in general --
-     * docs/OPS.md says a layer with a bf16 consumer of the fused value must ask for it or the
-     * fusion is a different function -- but a block-fp8 down_proj reads the E4M3 codes and their
-     * scale, and only a down_proj that reads the bf16 plane instead (LinearFP8::reads_x) reads the
-     * bf16 silu product. It is [T, n_ff] a layer: 18.2 GB of a 16k prefill and 71 MB of an
-     * 8-sequence decode step, written for one reader that is not there. Declared out of the write
-     * list rather than merely passed absent, so the plan says what actually happens. */
+    /* Whether the bf16 product is written. A consumer of the bf16 value must request it
+     * (docs/OPS.md), but a block-fp8 down_proj reads only codes and scales; only one that reads
+     * the bf16 plane (LinearFP8::reads_x) needs it. Skipping it saves [T, n_ff] per layer (18.2 GB
+     * over a 16k prefill). Left out of the write list, not just passed absent, so the plan is
+     * accurate. */
     bool   want_x = true;
-    /* The row width. `gate_up` is 2n wide, the quantised output n; see NormQuantFP8::n. */
+    /* The output width; `gate_up` is 2n wide. */
     int64_t n = 0;
     /* `silu_mul` into the bf16 plane alone, for a model whose linears are bf16 (Geom::w_bf16). */
     bool   bf16 = false;
+    /* The rotated form's chain, where no loaded library declares `gated_had_quant_fp8` or it does
+     * not resolve: `silu_mul` into the bf16 plane (`op`), then `had_quant_act_fp8` over it into the
+     * codes (`op_q`). */
+    rad_op op_q = 0;
 
     int  declare(RadBuilder* b, const Geom& g, rad_buf gate_up, const ActFP8& act, int64_t n,
                  const char* act_name = "silu", int64_t max_rows = 0, bool bf16_out = true,
@@ -600,18 +495,17 @@ struct GateQuantFP8 {
     void step(RadCtx* c, rad_buf gate_up, int64_t T, int64_t r0 = 0, int64_t rows = 0) const;
 };
 
-/* `rot` PICKS A DIFFERENT OP, not a parameter on the same one: the codes are not the same codes,
- * so the consumer is not free either -- only a weight stored with the matching rotation reads
- * them. It exists for the routed MoE arm's down projection at four bits and nothing else, and
- * `out_bf16` still receives the UNROTATED product in both cases. */
+/* `rot` selects a different op (`gated_had_quant_fp8`), whose rotated codes only a weight stored
+ * with the matching rotation can read; used for the routed MoE down projection at four bits. The
+ * bf16 output is unrotated either way. */
 inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up, const ActFP8& act,
                                  int64_t n, const char* act_name, int64_t max_rows,
                                  bool bf16_out, bool rot) {
     a = act;
     want_x = bf16_out;
     this->n = n;
-    /* A bf16 model's down projection reads the product itself, so the producer is `silu_mul` and
-     * writes the bf16 plane alone. A rotation has no meaning without the codes it rotates. */
+    /* bf16 linears read the product itself: `silu_mul` into the bf16 plane only, and no
+     * rotation. */
     bf16 = g.w_bf16;
     if (bf16) {
         if (!gate_up || !a.x || n <= 0 || rot || std::strcmp(act_name, "silu") != 0) {
@@ -628,30 +522,45 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
         return op ? RAD_OK : RAD_E_INVAL;
     }
     if (!gate_up || !a.x || !a.cq() || !a.cs() || n <= 0) return RAD_E_INVAL;
-    /* The rotated codes are a four-bit expert's operand, which reads E4M3 only. */
+    /* Rotated codes feed a four-bit expert, which reads E4M3 only. */
     if (rot && a.q8_fed) return RAD_E_INVAL;
-    const char* opname = rot ? "gated_had_quant_fp8" : "gated_quant_fp8";
-    op = want_x
-        ? rw(b, RAD_OP(b, opname,
-                RAD_PARAMS(RAD_RANGE("M", 1, max_rows > 0 ? max_rows : g.max_tok),
-                           RAD_INT("n", n), RAD_INT("group", RAD_FP8_BLOCK),
-                           RAD_STR("dtype", g.dtype), RAD_STR("act", act_name)),
-                RAD_NOWEIGHTS),
-            { gate_up }, { a.cq(), a.cs(), a.x })
-        : rw(b, RAD_OP(b, opname,
-                RAD_PARAMS(RAD_RANGE("M", 1, max_rows > 0 ? max_rows : g.max_tok),
-                           RAD_INT("n", n), RAD_INT("group", RAD_FP8_BLOCK),
-                           RAD_STR("dtype", g.dtype), RAD_STR("act", act_name)),
-                RAD_NOWEIGHTS),
-            { gate_up }, { a.cq(), a.cs() });
-    return op ? RAD_OK : RAD_E_INVAL;
+    const int64_t rows = max_rows > 0 ? max_rows : g.max_tok;
+    if (!rot || rad_op_declared(b, "gated_had_quant_fp8"))
+        op = RAD_OP(b, rot ? "gated_had_quant_fp8" : "gated_quant_fp8",
+                    RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
+                               RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype),
+                               RAD_STR("act", act_name)),
+                    RAD_NOWEIGHTS);
+    /* The rotated op's chain, which writes the bf16 plane whether or not a consumer asked. */
+    if (!op && rot && std::strcmp(act_name, "silu") == 0) {
+        want_x = true;
+        op = rw(b, RAD_OP(b, "silu_mul",
+                   RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("dtype", g.dtype)),
+                   RAD_NOWEIGHTS),
+               { gate_up }, { a.x });
+        op_q = rw(b, RAD_OP(b, "had_quant_act_fp8",
+                     RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
+                                RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
+                     RAD_NOWEIGHTS),
+                 { a.x }, { a.cq(), a.cs() });
+        return op && op_q ? RAD_OK : RAD_E_INVAL;
+    }
+    if (!op) return RAD_E_INVAL;
+    const rad_buf wr[3] = { a.cq(), a.cs(), a.x };
+    rad_op_reads (b, op, &gate_up, 1);
+    rad_op_writes(b, op, wr, want_x ? 3 : 2);
+    return RAD_OK;
 }
 
 inline void GateQuantFP8::step(RadCtx* c, rad_buf gate_up, int64_t T, int64_t r0,
                                int64_t rows) const {
     if (rows <= 0) rows = T - r0;
-    if (bf16) {
+    if (bf16 || op_q) {
         RAD_ISSUE_N(c, op, rows, brow_slice(gate_up, r0, rows, 2 * n), brow_slice(a.x, r0, rows, n));
+        if (op_q)
+            RAD_ISSUE_N(c, op_q, rows, brow_slice(a.x, r0, rows, n),
+                        brow_slice(a.cq(), r0, rows, n),
+                        brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK));
         return;
     }
     RAD_ISSUE_N(c, op, rows, brow_slice(gate_up, r0, rows, 2 * n),
@@ -660,52 +569,72 @@ inline void GateQuantFP8::step(RadCtx* c, rad_buf gate_up, int64_t T, int64_t r0
                 want_x ? brow_slice(a.x, r0, rows, n) : RAD_NONE);
 }
 
+/* A linear's stacked row parts (RadWeightDecl::row_parts) in weight rows (`w`) and in the rows of
+ * its scale plane (`s`, `div` times fewer). */
+struct RowParts {
+    int64_t w[RAD_MAX_ROW_PARTS] = {0}, s[RAD_MAX_ROW_PARTS] = {0};
+    int     n = 0;
+
+    /* Refuses more than RAD_MAX_ROW_PARTS parts, or a part that is not whole `unit`-row tiles
+     * (`tile` names them), since a row shard cuts the weight at part boundaries. */
+    int set(std::initializer_list parts, int64_t unit, int64_t div, const char* base,
+            const char* tile) {
+        n = 0;
+        for (int64_t p : parts) {
+            if (n >= RAD_MAX_ROW_PARTS) return RAD_E_INVAL;
+            if (p % unit) {
+                fprintf(stderr, "radiance: '%s' stacks a %lld-row part, which is not a whole "
+                                "number of %lld-row %s; it cannot be row-sharded\n",
+                        base, (long long)p, (long long)unit, tile);
+                return RAD_E_INVAL;
+            }
+            w[n] = p;
+            s[n] = p / div;
+            ++n;
+        }
+        return RAD_OK;
+    }
+};
+
 /* ================================================================== one block-scaled linear */
 struct LinearFP8 {
     rad_weight w = 0, ws = 0;
     rad_op     op = 0;
     int64_t    N = 0, K = 0;
-    /* ROWS OF THE SCALE PLANE PER ROW OF THE WEIGHT: 1 for an int8 or bf16 linear, whose scale
-     * plane (if any) has the weight's rows, RAD_FP8_BLOCK for a block-fp8 one, whose scale plane
-     * is 1/128 of them. A row span on `ws` is in the plane's own rows (declare's span code
-     * divides); span_parts below divides the same way. */
+    /* Weight rows per scale-plane row: RAD_FP8_BLOCK for block fp8, 1 otherwise. Row spans on `ws`
+     * are converted with it (declare, span_parts). */
     int64_t    ws_row_div = 1;
-    /* A PLAIN bf16 WEIGHT read by `gemm_nt` over the activation's bf16 plane, in a model whose
-     * linears are bf16 (Geom::w_bf16): one weight and no scale plane, and no quantiser in front. */
+    /* Plain bf16 weight read by `gemm_nt` over the bf16 activation (Geom::w_bf16): no scale plane,
+     * no quantiser. */
     bool       bf16 = false;
-    /* AN INT8 WEIGHT, read by `gemm_nt_q` at dtype i8a8 against an INT8 activation: i8 codes and
-     * a bf16 scale per row per 128 of K (libquant `codes=i8 group=128 scale=bf16`), the activation
-     * i8 with an f32 scale per (row, 128) -- the E4M3 activation's grid at int8 codes, in the same
-     * two buffers (`a.q`, `a.s`). The weight carries a quarter of E4M3's error at the same bytes and
-     * the iu8 WMMA runs at the fp8 one's rate. `op_q` writes those codes from the bf16 plane
-     * (quant_act_i8g) when the producer in front writes E4M3; it is declared and issued before the
-     * GEMM. Read off the weight's encoding like `bf16`. */
+    /* Int8 weight read by `gemm_nt_q` at dtype i8a8: i8 codes with a bf16 scale per row per 128 of
+     * K (libquant `codes=i8 group=128 scale=bf16`), against an i8 activation with an f32 scale per
+     * (row, 128). A quarter of E4M3's error at the same bytes, and iu8 WMMA runs at the fp8 rate.
+     * `op_q` (quant_act_i8g) writes the activation codes from the bf16 plane when the producer
+     * writes E4M3. Read from the weight's encoding. */
     bool       i8 = false;
     rad_op     op_q = 0;
-    /* AN OCP-MXFP4 WEIGHT, read by `gemm_nt_q` at dtype mxfp4a8 against the SAME E4M3 pair every
-     * other linear here reads (`a.q`, `a.s` at an f32 scale per (row, 128)): e2m1 codes and one
-     * E8M0 exponent per 32 of K, as libquant writes `codes=fp4_e2m1 group=32 scale=e8m0`. libr4d
-     * folds each block's exponent into the e4m3 operand against a per-row reference, so the scale
-     * plane is handed over TWICE: as `b_scale` and as `b_ref`, whose layout hook reduces the same
-     * plane to that reference -- `wref` is the second view. The activation grid is the fp8 family's, so every producer's fused quantiser
-     * feeds an MXFP4 linear unchanged. Read off the weight's encoding like `bf16` and `i8`. */
+    /* OCP-MXFP4 weight read by `gemm_nt_q` at dtype mxfp4a8 against the usual E4M3 activation pair:
+     * e2m1 codes with one E8M0 exponent per 32 of K (libquant `codes=fp4_e2m1 group=32
+     * scale=e8m0`). libr4d folds each block's exponent into the e4m3 operand against a per-row
+     * reference, so the scale plane is passed twice, as `b_scale` and as `b_ref` (`wref`, a second
+     * view whose layout hook reduces it). Read from the weight's encoding. */
     bool       mx = false;
     rad_weight wref = 0;
-    /* ...ROTATED (ParoQuant), a variant of `mx`: the same GEMM over an activation that
-     * `givens_dense_quant` made from the input's bf16 plane -- the channel scale, the rotation (a
-     * dense per-group matrix) and the E4M3 quantiser in one pass, once for each rotated PART of a fused projection
-     * (gate|up, qkv|z: each piece was rotated on its own) -- into this linear's own code and
-     * scale planes, `parts` copies side by side. The tables are views of the weight's own planes.
-     * The GEMM takes the parts' row bounds as `pb1`/`pb2` and meets copy p with part p's rows. */
+    /* Rotated (ParoQuant) variant of `mx`: the same GEMM over an activation that
+     * `givens_dense_quant` makes from the bf16 plane (channel scale, dense per-group rotation and
+     * E4M3 quantiser in one pass), once per independently rotated part of a fused projection
+     * (gate|up, qkv|z), into this linear's own code and scale planes side by side. The tables are
+     * views of the weight's planes. The GEMM takes the parts' row bounds as `pb1`/`pb2` and meets
+     * copy p with part p's rows. */
     bool       paro = false;
-    /* ...AND ITS 5-BIT SIBLING: the same rotation, to f16 (`rot_q` is then the f16 plane and there is no
-     * `rot_s`), then gemm_nt_q at w5a16 over a weight of u5 codes, an f16 scale and a zero point. */
+    /* The 5-bit sibling: the same rotation to f16 (`rot_q` is the f16 plane, no `rot_s`), then
+     * gemm_nt_q at w5a16 over u5 codes with an f16 scale and a zero point. */
     bool       paro5 = false;
-    /* ...AND ITS PREFILL BAND (z-lab's int4 and the int5): above `rot_split` rows the f16 skinny kernel is
-     * bound by the slow f16 matrix instruction, so a second chain runs there -- the same rotation to
-     * int8 with a scale a (row, 128) into `rot_q2`/`rot_s2`, then the int8 tiled GEMM
-     * (`w4a8i8_asym` / `w5a8i8`), both reading the SAME weight views. At or below the split the f16 chain
-     * above runs. */
+    /* Prefill band for z-lab's int4 and the int5: above `rot_split` rows the f16 skinny kernel is
+     * bound by the slow f16 matrix instruction, so a second chain runs: the same rotation to int8
+     * with a scale per (row, 128) into `rot_q2`/`rot_s2`, then the int8 tiled GEMM (`w4a8i8_asym` /
+     * `w5a8i8`) over the same weight views. At or below the split the f16 chain runs. */
     int64_t    rot_split = 0;
     rad_buf    rot_q2 = 0, rot_s2 = 0;
     rad_op     op_rot2 = 0, op2 = 0;
@@ -713,47 +642,33 @@ struct LinearFP8 {
     rad_buf    rot_q = 0, rot_s = 0;
     rad_op     op_rot = 0;
     int64_t    rot_parts = 1, rot_stages = 0;
-    /* What probe() read: the weight is int8. Lets a model learn its trunk's format from one linear
-     * before it declares the activation buffers that format decides (ActFP8::declare_qs's `i8`). */
+    /* probe() found an int8 weight; lets a model learn its trunk's format from one linear before
+     * declaring activation buffers (ActFP8::declare_qs's `i8`). */
     bool       probed_i8 = false;
-    /* THE DECODE MATVEC, DECLARED BESIDE THE GEMM. libr4d has gemm_fp8a16_nt_m1 -- an M <= 1
-     * kernel that reads the bf16 activation directly, with no quantise and no tiling -- and it is
-     * written for exactly the shape a single-sequence decode step issues. Declaring only fp8a8
-     * leaves every decode on the TILED kernel at M = 1, which is the shape it is worst at.
-     *
-     * `dtype` is one string per declared op, so an op cannot be both: this is two ops over the
-     * same weights, banded so their bucket tables do not overlap, and step() picks by the token
-     * count. That is the same shape as the delta net's prefill/decode pair and for the same
-     * reason -- it is a choice between two DECLARED sequences, not a branch inside one. */
-    rad_op     op_m1 = 0;
-    /* The widest T that op_m1 serves. 0 when the matvec is declined. */
-    int64_t    mv_rows = 0;
-    /* WHETHER THIS LINEAR READS THE INPUT'S bf16 PLANE, known before its producer is declared.
-     * In a quantised model a producer writes the bf16 plane only when something reads it -- a
-     * gated quantiser writes the codes alone -- so the block asks probe() first and has the
-     * producer write the plane when this is set. Without that a plain weight reads arena bytes
-     * nothing wrote: finite nonsense on the first step, NaN once they hold one. */
+    /* Whether this linear reads the input's bf16 plane, known from probe() before the producer is
+     * declared. A producer writes the bf16 plane only when asked, so the block must ask for it when
+     * this is set; otherwise the linear reads unwritten arena bytes. */
     bool       reads_x = false;
     bool       mapped  = false;   /* probe() made the name map; declare() does not make it again */
 
-    /* The name map, and from the encoding behind it whether the weight is plain bf16. `base` and
-     * `src` are what declare() is then given. */
+    /* Declares the name map and reads the weight's format (reads_x, probed_i8). `base` and `src`
+     * are the same as for declare(). */
     int  probe(RadBuilder* b, Names& nm, const Geom& g, const char* base,
                std::initializer_list src);
 
-    /* `base` is the DECLARED name without a suffix ("blk.7.ffn_gate_up"); the logical weight is
-     * `.weight` and its two views are `.weight` (the codes) and `.scale`. `src` is the
-     * checkpoint side, one name or several to concatenate along dim 0 -- and a block-fp8
-     * checkpoint's scale planes join with them, which is what makes a fusion of two fp8 linears
-     * expressible at all: [17408,5120]+[17408,5120] concatenates to [34816,5120] and
-     * [136,40]+[136,40] to [272,40], and 34816/128 is 272. A fusion whose parts are not whole
-     * multiples of the block would not line up, and none here are. */
-    /* `span_lo`/`span_hi`, when hi is set, is this rank's uneven slice of the split dimension in
-     * the model's units -- rows of each row part for RAD_SHARD_ROW, columns for RAD_SHARD_COL --
-     * and n_out / n_in is already its width; see rad_weight_shard_span. Whole scale blocks. */
-    /* `rot_parts`: the rows of each independently rotated part of a ROTATED weight,
-     * which `row_parts` is when the pieces and the shard parts are the same cut -- gate|up -- and
-     * is not when they are not: the delta net's qkv|z is four shard parts and two rotated ones. */
+    /* `base` is the declared name without suffix ("blk.7.ffn_gate_up"); the logical weight is
+     * `.weight` with views `.weight` (codes) and `.scale`. `src` is one checkpoint name, or
+     * several concatenated along dim 0; block-fp8 scale planes concatenate with them, so each part
+     * must be a whole number of 128-row blocks ([17408,5120] x 2 -> [34816,5120] with scales
+     * [136,40] x 2 -> [272,40]).
+     *
+     * `span_lo`/`span_hi` (when hi is set): this rank's uneven slice of the split dimension in
+     * model units (rows of each row part for RAD_SHARD_ROW, columns for RAD_SHARD_COL), whole scale
+     * blocks; n_out / n_in is already its width (rad_weight_shard_span).
+     *
+     * `rot_part_rows`: rows of each independently rotated part of a rotated weight. Equal to
+     * `row_parts` when the cuts coincide (gate|up), not otherwise (the delta net's qkv|z has four
+     * shard parts and two rotated ones). */
     int  declare(RadBuilder* b, Names& nm, const Geom& g, const char* base,
                  int64_t n_out, int64_t n_in, int shard, RadWeightGroup grp,
                  std::initializer_list src,
@@ -761,23 +676,23 @@ struct LinearFP8 {
                  std::initializer_list row_parts = {},
                  int64_t span_lo = 0, int64_t span_hi = 0,
                  std::initializer_list rot_part_rows = {});
-    /* THE ROTATION OF A ROTATED WEIGHT: its parts and stages (`rot_parts`, `rot_stages`) and its
-     * channel scale as a view of the weight's own plane. `cut` is the rows of each rotated part; the
-     * GEMM's part bounds come back in pb1 and pb2. */
+    /* Declares a rotated weight's rotation: parts and stages (`rot_parts`, `rot_stages`) and the
+     * channel scale as a view of the weight's plane. `cut` is each rotated part's rows; the GEMM's
+     * part bounds are returned in pb1 and pb2. */
     int  declare_rotation(RadBuilder* b, Names& nm, const char* base, const char* wn,
                           const RadEncoding& enc, int64_t N, int64_t K, RadWeightGroup grp,
                           const std::vector& cut, int64_t* pb1, int64_t* pb2);
-    /* THE SEQUENTIAL NETWORK (decode: a few rows, where one network a row is cheap): the pairs and
-     * angles as views, and givens_rotate over them to f16, for M in [lo, hi]. */
+    /* The sequential rotation network (cheap at decode's few rows): pairs and angles as views, and
+     * givens_rotate over them to f16 for M in [lo, hi]. */
     int  decl_seq_tables(RadBuilder* b, Names& nm, const char* base, const char* wn, RadWeightGroup grp);
     rad_op decl_rot_op(RadBuilder* b, const Geom& g, const ActFP8& a, int64_t lo, int64_t hi,
                        std::initializer_list outs) const;
-    /* THE DENSE ROTATION (rot_dense, decl_dense): givens_dense_quant to `out` ("fp8" or "i8") codes
+    /* The dense rotation (rot_dense, decl_dense): givens_dense_quant to `out` ("fp8" or "i8") codes
      * and a scale, for M in [lo, hi]. */
     rad_op decl_dense_op(RadBuilder* b, const Geom& g, const ActFP8& a, const char* out, int64_t lo,
                          int64_t hi, std::initializer_list outs) const;
-    /* gemm_nt_q over this weight, M in [lo, hi]. `pb1`/`pb2` go only to a weight with rotated
-     * parts, so a one-part op keeps the plain op's geometry -- the key the tune cache is read by. */
+    /* gemm_nt_q over this weight, M in [lo, hi]. `pb1`/`pb2` are passed only for rotated parts,
+     * so a one-part op keeps the plain geometry (the tune cache key). */
     rad_op decl_gemm_q(RadBuilder* b, int64_t lo, int64_t hi, int64_t group, const char* dtype,
                        int64_t pb1, int64_t pb2, std::initializer_list wts,
                        std::initializer_list reads, rad_buf y) const;
@@ -786,9 +701,9 @@ struct LinearFP8 {
                           RadWeightGroup grp);
     void step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, int64_t r0 = 0,
               int64_t rows = 0) const;
-    /* A SPAN PER STACKED ROW PART (rad_weight_shard_span_parts), in the weight's rows; the scale
-     * plane takes the same spans in its own rows. After declare(); every span and total has to be
-     * whole scale blocks when the plane is 1/128, which head widths of 128 are. */
+    /* A span per stacked row part (rad_weight_shard_span_parts), in weight rows; the scale plane
+     * gets the same spans in its rows. Call after declare(). With a 1/128 plane every span and
+     * total must be whole scale blocks. */
     int  span_parts(RadBuilder* b, const int64_t* lo, const int64_t* hi, const int64_t* total,
                     int n) const {
         RAD_ARCH_TRY(rad_weight_shard_span_parts(b, w, lo, hi, total, n));
@@ -810,11 +725,9 @@ struct LinearFP8 {
     }
 };
 
-/* THE NAME MAP OF A LINEAR, DECLARED BEFORE ITS WEIGHT: it is how the checkpoint -- or the recipe
- * rad-convert applies -- is asked what the weight is (rad_weight_encoding), so it has to exist
- * first. One source is copied; several are a convert-time fusion (gate and up into gate_up),
- * concatenated along dim 0 -- and a block-fp8 checkpoint's scale planes join with them, which is
- * why a fused part has to be a whole number of 128-row blocks. */
+/* A linear's name map, declared before its weight because the weight's encoding is looked up
+ * through it (rad_weight_encoding). One source is copied; several are concatenated along dim 0
+ * (with block-fp8 scale planes, so each part must be whole 128-row blocks). */
 inline int map_linear(RadBuilder* b, const char* wn, std::initializer_list src) {
     if (src.size() == 1) return map_copy(b, wn, *src.begin());
     RadNameMap mw = map_base(wn, RAD_MAP_CONCAT);
@@ -828,8 +741,8 @@ inline int map_linear(RadBuilder* b, const char* wn, std::initializer_listblock[0] == 1 && sc->block[1] == RAD_FP8_BLOCK;
 }
 
-/* The OCP-MXFP4 weight LinearFP8 serves at mxfp4a8: e2m1 codes one a value and an E8M0 exponent
- * per [1 x 32], no transform -- what libr4d's MXFP4 layout hook accepts. */
+/* The OCP-MXFP4 weight LinearFP8 serves at mxfp4a8: e2m1 codes and an E8M0 exponent per [1 x 32],
+ * no transform (libr4d's MXFP4 layout hook). */
 enum { RAD_MX_GROUP = 32 };
 inline bool linear_is_mxfp4(const RadEncoding& e) {
     if (!rad_enc_is(&e, "affine") || e.n_planes != 2 || e.transform[0]) return false;
@@ -847,10 +760,9 @@ inline bool linear_is_mxfp4(const RadEncoding& e) {
            sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == RAD_MX_GROUP;
 }
 
-/* A ROTATED weight (ParoQuant): an affine encoding stored in the basis a "givens" transform names,
- * with the rotation's tables as planes of their own -- int32 column pairs, f32 angles, f32 channel
- * scales, and for a fused projection one set a part. The GEMM reads the codes as stored; the
- * activation in front of it is rotated first. */
+/* A rotated weight (ParoQuant): an affine encoding in the basis of a "givens" transform, with the
+ * rotation tables as planes (int32 column pairs, f32 angles, f32 channel scales; one set per part
+ * of a fused projection). The GEMM reads the codes as stored; the activation is rotated first. */
 inline bool linear_is_givens(const RadEncoding& e) {
     if (!rad_enc_is(&e, "affine") || std::strncmp(e.transform, "givens", RAD_ENC_STR) != 0) return false;
     if (!rad_enc_valid(&e)) return false;
@@ -859,15 +771,15 @@ inline bool linear_is_givens(const RadEncoding& e) {
     return pr && an && rs && pr->dtype == RAD_I32 && an->dtype == RAD_F32 && rs->dtype == RAD_F32;
 }
 
-/* ...whose codes and E8M0 exponents are OCP-MXFP4's: read as the plain MXFP4 weight. */
+/* A rotated weight with OCP-MXFP4 codes and exponents, read like the plain MXFP4 weight. */
 inline bool linear_is_paro_mxfp4(const RadEncoding& e) {
     const RadEncPlane* sc = rad_enc_plane(&e, "scale");
     return linear_is_givens(e) && e.plane[0].dtype == RAD_FP4E2M1 && e.plane[0].block[1] == 1 && sc &&
            sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == RAD_MX_GROUP;
 }
 
-/* ...whose codes are ParoQuant's int5 (u5) or z-lab's int4 (u4), asymmetric: an f16 scale and a u8
- * zero point a 128 of K. Read by gemm_nt_q at w5a16 / w4a16_asym over an f16 activation, and at
+/* A rotated weight with ParoQuant int5 (u5) or z-lab int4 (u4) asymmetric codes: an f16 scale and
+ * u8 zero point per 128 of K. Read by gemm_nt_q at w5a16 / w4a16_asym over an f16 activation, or
  * w5a8i8 / w4a8i8_asym over an int8 one. */
 inline bool linear_is_paro_w5(const RadEncoding& e) {
     const RadEncPlane *sc = rad_enc_plane(&e, "scale"), *zp = rad_enc_plane(&e, "zero");
@@ -887,7 +799,7 @@ inline int LinearFP8::probe(RadBuilder* b, Names& nm, const Geom& g, const char*
     const bool plain = known && rad_enc_is(&enc, "plain") && enc.n_planes == 1 &&
                        enc.plane[0].dtype == RAD_BF16;
     probed_i8 = known && linear_is_w8(enc);
-    /* A ROTATED weight rotates the bf16 plane itself: its quantiser is not the producer's. */
+    /* A rotated weight rotates and quantises the bf16 plane itself. */
     const bool rotated = known && (linear_is_paro_mxfp4(enc) || linear_is_paro_w5(enc));
     reads_x = g.w_bf16 || plain || probed_i8 || rotated;
     return RAD_OK;
@@ -908,9 +820,8 @@ inline int LinearFP8::declare_rotation(RadBuilder* b, Names& nm, const char* bas
                                        const RadEncoding& enc, int64_t N, int64_t K,
                                        RadWeightGroup grp, const std::vector& cut_in,
                                        int64_t* pb1, int64_t* pb2) {
-    /* THE PARTS, in rows, and the tables as weights of their own. The container records how many
-     * parts there are and not where they end -- a declaration has no plane bytes -- so the block
-     * says: `rot_part_rows`, or its row parts when those are the cut. */
+    /* The container records the number of rotated parts but not their row bounds, so the block
+     * supplies them (`rot_part_rows`, or its row parts when those are the cut). */
     const int64_t P = rad_enc_givens_parts(&enc);
     const RadEncPlane* tp = rad_enc_plane(&enc, "t.pairs");
     if (P < 1 || !tp || tp->extent[0] % P || tp->extent[1] != K) {
@@ -973,16 +884,15 @@ inline rad_op LinearFP8::decl_dense_op(RadBuilder* b, const Geom& g, const ActFP
               { a.x }, outs);
 }
 
-/* The dense rotation matrices of a rotated weight: a view of its "t.dense" table, f16 [P * K/128, 128*128],
- * which rad-convert composes from the givens tables (abi/rad_encoding.h). A container written before the
- * table existed carries only the pairs and angles; it is refused here, naming the reconvert, rather than
- * served through a matrix the kernel library would have to compute. */
+/* The dense rotation matrices of a rotated weight: a view of its "t.dense" table, f16
+ * [P * K/128, 128*128], which rad-convert composes from the givens tables (abi/rad_encoding.h). A
+ * container with only pairs and angles is refused with a message to reconvert. */
 inline rad_weight LinearFP8::decl_dense(RadBuilder* b, Names& nm, const char* base, const char* wn,
                                         const RadEncoding& enc, int64_t K, RadWeightGroup grp) {
     if (!rad_enc_plane(&enc, "t.dense")) {
-        fprintf(stderr, "radiance: '%s' carries its rotation as pairs and angles only, and the dense "
-                        "quantiser reads it composed (a \"t.dense\" table); convert it again with this "
-                        "rad-convert -- --reuse  copies every other weight\n", wn);
+        fprintf(stderr, "radiance: '%s' carries its rotation as pairs and angles only and the dense "
+                        "quantiser reads a composed \"t.dense\" table; convert it again (--reuse "
+                        " copies every other weight)\n", wn);
         return 0;
     }
     return decl_view(b, nm.f("%s.rot_dense", base), wn, "t.dense", RAD_F16,
@@ -1001,8 +911,7 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
     K = n_in;
     if (N <= 0 || K <= 0 || src.size() == 0) return RAD_E_INVAL;
 
-    /* THE NAME MAP FIRST: it is how the checkpoint -- or the recipe rad-convert applies -- is
-     * asked what the weight is, and that answer picks the branch below. */
+    /* Name map first: the weight's encoding, looked up through it, picks the branch below. */
     const char* wn = nm.f("%s.weight", base);
     if (!mapped) RAD_ARCH_TRY(map_linear(b, wn, src));
     RadEncoding enc{};
@@ -1010,34 +919,29 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
     const bool plain = known && rad_enc_is(&enc, "plain") && enc.n_planes == 1 &&
                        enc.plane[0].dtype == RAD_BF16;
 
-    /* ---- A bf16 WEIGHT, `gemm_nt` over `a.x`: every linear of a bf16 model, and one a quantised
-     * container keeps at the checkpoint's precision -- the QSA indexer's projection, whose top-k is
-     * a hard choice between blocks and costs 20 MB to keep exact. The row parts and an uneven
-     * slice apply to it as they would to the codes; there is no block to respect. */
+    /* ---- bf16 weight, `gemm_nt` over `a.x`: every linear of a bf16 model, or one a quantised
+     * container keeps at checkpoint precision (e.g. the QSA indexer's projection, whose top-k is a
+     * hard choice; 20 MB to keep exact). Row parts and uneven slices apply without block
+     * constraints. */
     bf16 = g.w_bf16 || plain;
     if (bf16) {
         if (known && !plain) {
             char en[256];
             rad_enc_format(&enc, en, sizeof en);
-            fprintf(stderr, "radiance: '%s' is %s, and this model's linears are plain bf16 -- a "
+            fprintf(stderr, "radiance: '%s' is %s and this model's linears are plain bf16; a "
                             "bf16 container is served bf16 throughout\n", wn, en);
             return RAD_E_DTYPE;
         }
-        /* The input's bf16 plane is what a bf16 weight multiplies. A quantised model's producer
-         * may write only the codes -- a gated quantiser does -- and then there is nothing here to
-         * read; the weight has to be quantised with the rest. */
+        /* A bf16 weight needs the input's bf16 plane, which a quantised model's producer may not
+         * write (a gated quantiser writes only codes). */
         if (!a.x) {
             fprintf(stderr, "radiance: '%s' is plain bf16 and its input has no bf16 plane in this "
                             "model; quantise it with its neighbours\n", wn);
             return RAD_E_DTYPE;
         }
-        int64_t parts[RAD_MAX_ROW_PARTS] = {0};
-        int     np = 0;
-        for (int64_t p : row_parts) {
-            if (np >= RAD_MAX_ROW_PARTS) return RAD_E_INVAL;
-            parts[np++] = p;
-        }
-        w = decl_w_n(b, wn, RAD_BF16, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp, 0, parts, np);
+        RowParts rp;
+        RAD_ARCH_TRY(rp.set(row_parts, 1, 1, base, "rows"));
+        w = decl_w_n(b, wn, RAD_BF16, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp, 0, rp.w, rp.n);
         if (!w) return RAD_E_INVAL;
         if (span_hi > 0) RAD_ARCH_TRY(rad_weight_shard_span(b, w, span_lo, span_hi));
         op = rw(b, RAD_OP(b, "gemm_nt",
@@ -1048,44 +952,37 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
         return op ? RAD_OK : RAD_E_INVAL;
     }
 
-    /* ---- AN INT8 WEIGHT, `gemm_nt_q` at i8a8 over the input's int8 pair `a.q8` / `a.s8`. The
-     * scale plane is one bf16 per row per 128 of K, so it takes the weight's row parts and row
-     * slice as they are, and a column slice in groups of 128 -- which the per-rank K being a
-     * whole number of groups guarantees. The codes are the producer's own when the model feeds
-     * the pair (ActFP8::q8_fed); otherwise op_q writes them from `a.x`, so the producer in front
-     * has to write the bf16 plane (probe() set reads_x for it). Either way the model has to have
-     * declared the pair (ActFP8::declare_qs's `i8`). */
+    /* ---- int8 weight, `gemm_nt_q` at i8a8 over the input's `a.q8` / `a.s8`. The scale plane is
+     * one bf16 per row per 128 of K: row parts and row slices apply as is, column slices in groups
+     * of 128. The codes come from the producer (ActFP8::q8_fed) or from op_q over `a.x` (probe()
+     * set reads_x). The model must have declared the pair (ActFP8::declare_qs's `i8`). */
     i8 = known && linear_is_w8(enc);
     if (i8) {
         if (!a.x || !a.q8 || !a.s8) {
-            fprintf(stderr, "radiance: '%s' is an int8 weight, quantised from its input's bf16 "
-                            "plane into its int8 code pair, and its input lacks one of them -- the "
-                            "model did not learn its trunk is int8 before declaring it\n", wn);
+            fprintf(stderr, "radiance: '%s' is an int8 weight and its input lacks the bf16 plane "
+                            "or the int8 code pair (the model declared its input before learning "
+                            "the trunk is int8)\n", wn);
             return RAD_E_DTYPE;
         }
         if (N % 16 || K % RAD_FP8_BLOCK) {
             fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an int8 weight takes rows in "
-                            "16s and K in whole %d-column scale groups.\n",
+                            "16s and K in whole %d-column scale groups\n",
                     base, (long long)N, (long long)K, RAD_FP8_BLOCK);
             return RAD_E_INVAL;
         }
-        int64_t parts[RAD_MAX_ROW_PARTS] = {0};
-        int     np = 0;
-        for (int64_t p : row_parts) {
-            if (np >= RAD_MAX_ROW_PARTS) return RAD_E_INVAL;
-            parts[np++] = p;
-        }
+        RowParts rp;
+        RAD_ARCH_TRY(rp.set(row_parts, 1, 1, base, "rows"));
         const char* sn = nm.f("%s.scale", base);
         w  = decl_view(b, wn, nullptr, "codes", RAD_I8, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp,
-                       parts, np);
+                       rp.w, rp.n);
         ws = decl_view(b, sn, wn, "scale", RAD_BF16, { N, K / RAD_FP8_BLOCK }, RAD_ACCESS_PER_TOKEN,
-                       shard, grp, parts, np);
+                       shard, grp, rp.w, rp.n);
         if (!w || !ws) return RAD_E_INVAL;
         if (span_hi > 0) {
             const bool col = shard == RAD_SHARD_COL;
             if (col && (span_lo % RAD_FP8_BLOCK || span_hi % RAD_FP8_BLOCK)) {
                 fprintf(stderr, "radiance: '%s' is sliced [%lld, %lld) on this rank, which cuts a "
-                                "%d-column scale group.\n", base, (long long)span_lo,
+                                "%d-column scale group\n", base, (long long)span_lo,
                         (long long)span_hi, RAD_FP8_BLOCK);
                 return RAD_E_INVAL;
             }
@@ -1108,9 +1005,9 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
         return (op_q || a.q8_fed) && op ? RAD_OK : RAD_E_INVAL;
     }
 
-    /* ---- A ROTATED 5-BIT OR ASYMMETRIC 4-BIT WEIGHT (ParoQuant int5; z-lab's int4): its input's
-     * bf16 plane rotated into this linear's own f16 planes, then the w5a16 GEMM. Two views of one
-     * stored weight: the codes, and the (scale, zero) pair as `b_scale`. */
+    /* ---- Rotated 5-bit or asymmetric 4-bit weight (ParoQuant int5, z-lab int4): the input's bf16
+     * plane rotated into this linear's own f16 plane, then the w5a16 / w4a16_asym GEMM. Two views:
+     * codes, and (scale, zero) as `b_scale`. */
     paro5 = known && linear_is_paro_w5(enc);
     if (paro5) {
         const int bits = enc.plane[0].dtype == RAD_U4 ? 4 : 5;
@@ -1154,8 +1051,8 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
                          pb1, pb2, { w, ws }, { rot_q }, y);
         if (!op) return RAD_E_INVAL;
         if (band) {
-            /* THE PREFILL BAND: rows above the skinny kernel's ceiling rotate to int8 and meet the int8
-             * tiled GEMM. Declared over the tables and weight views already made above. */
+            /* Prefill band: rows above the skinny kernel's ceiling rotate to int8 and use the int8
+             * tiled GEMM, over the same tables and weight views. */
             rot_split = kSplit;
             rot_q2 = decl_b(b, nm.f("%s.rot_q2", base), RAD_I8, { hi, P * K });
             rot_s2 = decl_b(b, nm.f("%s.rot_s2", base), RAD_F32, { hi, P * (K / RAD_FP8_BLOCK) });
@@ -1170,24 +1067,23 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
         return RAD_OK;
     }
 
-    /* An E4M3 weight reads the E4M3 pair, and an input the model feeds at int8 codes has none --
-     * a container whose trunk mixes the two formats, which the model's one probe did not see. */
+    /* The remaining formats read the E4M3 pair, which an int8-fed input lacks (a trunk mixing
+     * formats that the model's probe did not detect). */
     if (a.q8_fed) {
         fprintf(stderr, "radiance: '%s' is not an int8 weight, and its input is fed int8 codes "
                         "because this model's trunk is int8; quantise it with its neighbours\n", wn);
         return RAD_E_DTYPE;
     }
 
-    /* ---- AN OCP-MXFP4 WEIGHT over the E4M3 pair. Three views of one stored weight: the codes,
-     * the exponent plane as `b_scale`, and the same plane again as `b_ref`. Every view takes the
-     * weight's row parts as they are -- the exponent grid is one row tall -- and a column slice in
-     * whole 128s, which is the ACTIVATION's scale block and so the stricter of the two. */
+    /* ---- OCP-MXFP4 weight over the E4M3 pair. Three views: codes, exponents as `b_scale`, and
+     * the same plane as `b_ref`. Row parts apply as is (the exponent grid is one row tall); column
+     * slices must be whole 128s, the activation's scale block. */
     paro = known && linear_is_paro_mxfp4(enc);
     mx = known && (linear_is_mxfp4(enc) || paro);
     if (mx) {
         if (paro) {
-            /* THE ROTATION OF A ROTATED WEIGHT IS THE ACTIVATION'S, so this linear needs the input's
-             * bf16 plane (probe() set reads_x; the producer wrote it) and quantises it itself. */
+            /* The rotation is applied to the activation, so this linear needs the input's bf16
+             * plane (probe() set reads_x) and quantises it itself. */
             if (!a.x) {
                 fprintf(stderr, "radiance: '%s' is a rotated MXFP4 weight, rotated and quantised "
                                 "from its input's bf16 plane, and its input has none\n", wn);
@@ -1206,22 +1102,12 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
         }
         if (N % 16 || K % RAD_FP8_BLOCK) {
             fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an MXFP4 weight takes rows in "
-                            "16s and K in whole %d-column activation scale blocks.\n",
+                            "16s and K in whole %d-column activation scale blocks\n",
                     base, (long long)N, (long long)K, RAD_FP8_BLOCK);
             return RAD_E_INVAL;
         }
-        int64_t parts[RAD_MAX_ROW_PARTS] = {0};
-        int     np = 0;
-        for (int64_t p : row_parts) {
-            if (np >= RAD_MAX_ROW_PARTS) return RAD_E_INVAL;
-            if (p % 16) {
-                fprintf(stderr, "radiance: '%s' stacks a %lld-row part, which is not a whole "
-                                "number of 16-row MXFP4 tiles; it cannot be row-sharded.\n",
-                        base, (long long)p);
-                return RAD_E_INVAL;
-            }
-            parts[np++] = p;
-        }
+        RowParts rp;
+        RAD_ARCH_TRY(rp.set(row_parts, 16, 1, base, "MXFP4 tiles"));
         int64_t pb1 = 0, pb2 = 0;
         if (paro) {
             std::vector cut;
@@ -1240,17 +1126,17 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
         const char* sn = nm.f("%s.scale", base);
         const char* rn = nm.f("%s.ref", base);
         w    = decl_view(b, wn, nullptr, "codes", RAD_FP4E2M1, { N, K }, RAD_ACCESS_PER_TOKEN,
-                         shard, grp, parts, np);
+                         shard, grp, rp.w, rp.n);
         ws   = decl_view(b, sn, wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
-                         RAD_ACCESS_PER_TOKEN, shard, grp, parts, np);
+                         RAD_ACCESS_PER_TOKEN, shard, grp, rp.w, rp.n);
         wref = decl_view(b, rn, wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
-                         RAD_ACCESS_PER_TOKEN, shard, grp, parts, np);
+                         RAD_ACCESS_PER_TOKEN, shard, grp, rp.w, rp.n);
         if (!w || !ws || !wref) return RAD_E_INVAL;
         if (span_hi > 0) {
             const bool col = shard == RAD_SHARD_COL;
             if (col && (span_lo % RAD_FP8_BLOCK || span_hi % RAD_FP8_BLOCK)) {
                 fprintf(stderr, "radiance: '%s' is sliced [%lld, %lld) on this rank, which cuts a "
-                                "%d-column activation scale block.\n", base, (long long)span_lo,
+                                "%d-column activation scale block\n", base, (long long)span_lo,
                         (long long)span_hi, RAD_FP8_BLOCK);
                 return RAD_E_INVAL;
             }
@@ -1260,58 +1146,43 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
             RAD_ARCH_TRY(rad_weight_shard_span(b, ws, lo, hi));
             RAD_ARCH_TRY(rad_weight_shard_span(b, wref, lo, hi));
         }
-        /* ONE GEMM for both: a rotated weight reads its own rotated pair, a plain one the producer's. */
+        /* One GEMM: a rotated weight reads its own rotated pair, a plain one the producer's. */
         op = decl_gemm_q(b, 1, max_rows > 0 ? max_rows : g.max_tok, RAD_MX_GROUP, "mxfp4a8", pb1, pb2,
                          { w, ws, wref }, { paro ? rot_q : a.q, paro ? rot_s : a.s }, y);
         return op ? RAD_OK : RAD_E_INVAL;
     }
 
-    /* The one geometric precondition, checked here so it is reported once per weight with the
-     * weight named rather than as a kernel miss with a band in it. These are PER-RANK extents, so
-     * this is also the check that a tensor-parallel width does not cut a scale block in half. */
+    /* Block fp8: per-rank extents must be whole scale blocks, checked here to name the weight (this
+     * also catches a tensor-parallel width that cuts a block). */
     if (N % RAD_FP8_BLOCK || K % RAD_FP8_BLOCK) {
         fprintf(stderr, "radiance: '%s' is %lldx%lld per rank, which is not a whole number of "
                         "%dx%d scale blocks. A block-scaled fp8 weight cannot be split inside a "
-                        "block; use a bf16 linear here or a world_size that divides cleanly.\n",
+                        "block; use a bf16 linear here or a world_size that divides cleanly\n",
                 base, (long long)N, (long long)K, RAD_FP8_BLOCK, RAD_FP8_BLOCK);
         return RAD_E_INVAL;
     }
 
-    /* THE SCALE PLANE SPLITS WHERE THE WEIGHT DOES, in units of RAD_FP8_BLOCK rows. A fused
-     * [q|k|v] whose parts are 1024/1024/3072 rows per rank is 8/8/24 scale rows per rank, and the
-     * scale would otherwise be sliced contiguously while the weight it scales was not -- a
-     * mismatch that survives every shape check and shows up only as wrong numbers. A part that is
-     * not a whole number of blocks cannot be expressed either way, so it is refused by name. */
-    int64_t wparts[RAD_MAX_ROW_PARTS] = {0}, sparts[RAD_MAX_ROW_PARTS] = {0};
-    int     np = 0;
-    for (int64_t p : row_parts) {
-        if (np >= RAD_MAX_ROW_PARTS) return RAD_E_INVAL;
-        if (p % RAD_FP8_BLOCK) {
-            fprintf(stderr, "radiance: '%s' stacks a %lld-row part, which is not a whole number "
-                            "of %d-row scale blocks; it cannot be row-sharded.\n",
-                    base, (long long)p, RAD_FP8_BLOCK);
-            return RAD_E_INVAL;
-        }
-        wparts[np] = p;
-        sparts[np] = p / RAD_FP8_BLOCK;
-        ++np;
-    }
+    /* The scale plane is split where the weight is, in RAD_FP8_BLOCK rows: fused [q|k|v] parts of
+     * 1024/1024/3072 rows are 8/8/24 scale rows. Without this the scale would be sliced
+     * contiguously while the weight was not, passing shape checks with wrong values. Parts must be
+     * whole blocks. */
+    RowParts rp;
+    RAD_ARCH_TRY(rp.set(row_parts, RAD_FP8_BLOCK, RAD_FP8_BLOCK, base, "scale blocks"));
 
     const char* sn = nm.f("%s.scale",  base);
-    /* ONE STORED WEIGHT, TWO OPERANDS: the codes and the scale plane of `.weight`, which is
-     * block-fp8 in the checkpoint or made so by the recipe. A checkpoint that is not (a dense
-     * bf16 release) declares the same two views; what makes the planes exist is rad-convert. */
+    /* One stored weight, two operands: the codes and scale plane of `.weight`, block fp8 in
+     * the checkpoint or made so by rad-convert's recipe. */
     w  = decl_view(b, wn, nullptr, "codes", RAD_F8E4M3, { N, K },
-                   RAD_ACCESS_PER_TOKEN, shard, grp, wparts, np);
+                   RAD_ACCESS_PER_TOKEN, shard, grp, rp.w, rp.n);
     ws_row_div = RAD_FP8_BLOCK;
     ws = decl_view(b, sn, wn, "scale", RAD_BF16, { fp8_blocks(N), fp8_blocks(K) },
-                   RAD_ACCESS_PER_TOKEN, shard, grp, sparts, np);
+                   RAD_ACCESS_PER_TOKEN, shard, grp, rp.s, rp.n);
     if (!w || !ws) return RAD_E_INVAL;
-    /* AN UNEVEN SLICE, and the scale plane takes the same slice in blocks. */
+    /* An uneven slice; the scale plane takes the same slice in blocks. */
     if (span_hi > 0) {
         if (span_lo % RAD_FP8_BLOCK || span_hi % RAD_FP8_BLOCK) {
             fprintf(stderr, "radiance: '%s' is sliced [%lld, %lld) on this rank, which cuts a %d-"
-                            "wide scale block.\n", base, (long long)span_lo, (long long)span_hi,
+                            "wide scale block\n", base, (long long)span_lo, (long long)span_hi,
                     RAD_FP8_BLOCK);
             return RAD_E_INVAL;
         }
@@ -1320,21 +1191,10 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
                                            span_hi / RAD_FP8_BLOCK));
     }
 
-    /* `M` is ranged over the token count, which is what selects between libr4d's narrow (M<=16)
-     * and tiled instantiations. A caller with a tighter bound -- the lm_head, which runs only on
-     * the sampled rows -- passes it, because a band ceiling of max_tok would size the narrow
-     * kernel's split-K scratch for a step that cannot happen. */
+    /* `M` ranges over the token count and selects libr4d's narrow (M <= 16) or tiled kernel. A
+     * caller with a tighter bound (the lm_head, over sampled rows only) passes `max_rows`, so the
+     * narrow kernel's split-K scratch is not sized for max_tok. */
     const int64_t hi = max_rows > 0 ? max_rows : g.max_tok;
-    /* The matvec first, up to the width its kernel serves, so a VERIFY STEP still takes it.
-     * fp8_matvec_rows is that width and says how it is chosen; at 0 the matvec is declined and
-     * every T goes to the fp8a8 GEMM below. */
-    mv_rows = fp8_matvec_rows(g);
-    if (mv_rows > 0)
-        op_m1 = rw(b, RAD_OP(b, "gemm_nt_q",
-                      RAD_PARAMS(RAD_RANGE("M", 1, mv_rows), RAD_INT("N", N), RAD_INT("K", K),
-                                 RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a16")),
-                      RAD_WEIGHTS(w, ws)),
-                  { a.x }, { y });
     op = rw(b, RAD_OP(b, "gemm_nt_q",
                RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
                           RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")),
@@ -1343,11 +1203,9 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
     return RAD_OK;
 }
 
-/* THE TWO TRAILING OPTIONAL OPERANDS ARE PASSED, as RAD_NONE. `gemm_nt_q`'s schema is seven long
- * -- `a_sum` and `b_ref` sit after `y` for the asymmetric integer and mxfp4 grids -- and operands
- * are POSITIONAL, so the runtime takes an operand count that disagrees with the schema as a miscount
- * rather than as an omission (core/runtime/issue.cpp). An absent optional operand is a null tensor
- * in the list, not a shorter list; an fp8 grid is symmetric and needs neither. */
+/* `gemm_nt_q` has seven positional operands; the optional `a_sum` and `b_ref` after `y` (for
+ * asymmetric integer and mxfp4 grids) are passed as RAD_NONE when unused, since the runtime checks
+ * the operand count against the schema (core/runtime/issue.cpp). */
 inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, int64_t r0,
                             int64_t rows) const {
     if (rows <= 0) rows = T - r0;
@@ -1381,8 +1239,8 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
         return;
     }
     if (mx) {
-        /* A rotated weight rotates its input first, into its own codes, `rot_parts` copies side
-         * by side (one for a plain weight, which reads the producer's). */
+        /* A rotated weight first rotates its input into its own codes, `rot_parts` copies side by
+         * side; a plain weight reads the producer's. */
         const rad_buf aq = paro ? rot_q : a.q, as = paro ? rot_s : a.s;
         const int64_t ak = rot_parts * K;
         if (paro)
@@ -1394,36 +1252,27 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
                     RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_W(wref));
         return;
     }
-    if (op_m1 && rows <= mv_rows)
-        RAD_ISSUE_N(c, op_m1, rows, brow_slice(a.x, r0, rows, K), RAD_NONE,
-                    RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
-    else
-        RAD_ISSUE_N(c, op, rows, brow_slice(a.q, r0, rows, K),
-                    brow_slice(a.s, r0, rows, K / RAD_FP8_BLOCK),
-                    RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
+    RAD_ISSUE_N(c, op, rows, brow_slice(a.q, r0, rows, K),
+                brow_slice(a.s, r0, rows, K / RAD_FP8_BLOCK),
+                RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
 }
 
-
 /* ================================================== an fp8 weight with no op of its own
  *
- * LinearFP8's two views without the GEMM: a weight a block declares here and reads through an op
- * of its own -- the DFlash2 and DSpark drafters' projections, which ship bf16 and are made block
- * fp8 by the recipe, since they are read whole on every decode step and only have to be good
- * enough to PROPOSE (every draft is verified against the trunk exactly).
+ * LinearFP8's views without the GEMM, for blocks that declare their own op over the weight: the
+ * DFlash2 and DSpark drafters' projections, shipped bf16 and made block fp8 by the recipe (read
+ * whole every decode step, and drafts are verified).
  *
- * BOTH VIEWS ARE DECLARED AT WHAT THEY SELECT -- [N][K] E4M3 codes, [N/128][K/128] BF16 scales --
- * because that is the shape the runtime hands a kernel, and libr4d checks the scale plane's
- * extents against ceil(N/128) x ceil(K/128) before it will run. The row parts follow it: the
- * weight's are rows and the plane's are BLOCKS of 128 rows, the same division LinearFP8 makes. A
- * part that is not a whole number of blocks cannot be sharded and is refused by name.
+ * Views are declared at what they select ([N][K] E4M3 codes, [N/128][K/128] BF16 scales), the
+ * shapes libr4d checks before running. Row parts are rows for the weight and 128-row blocks for
+ * the plane, as in LinearFP8; parts must be whole blocks.
  */
 struct DenseFP8 {
     rad_weight w = 0, s = 0;
-    /* OR AN OCP-MXFP4 WEIGHT, when that is what the container holds for it (a recipe's `codes=
-     * fp4_e2m1 group=32 scale=e8m0`): e2m1 codes, the E8M0 plane, and that plane again as the
-     * per-row reference -- LinearFP8's mx branch, without the GEMM. A block that declares its own
-     * GEMM over a DenseFP8 asks `gemm()` for it and passes `bref()` as the op's last operand, so
-     * one block serves either format against the same E4M3 activation pair. */
+    /* Or OCP-MXFP4 when the container holds that (`codes=fp4_e2m1 group=32 scale=e8m0`): e2m1
+     * codes, the E8M0 plane, and that plane again as the per-row reference (LinearFP8's mx branch).
+     * Blocks declare the GEMM with `gemm()` and pass `bref()` as its last operand, so either format
+     * works against the same E4M3 activation pair. */
     rad_weight ref = 0;
     bool       mx = false;
 
@@ -1456,9 +1305,8 @@ inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t
                              std::initializer_list row_parts) {
     if (N <= 0 || K <= 0 || src.size() == 0) return RAD_E_INVAL;
 
-    /* ---- OCP-MXFP4, read off the encoding the name map resolves to. The exponent grid is one row
-     * tall, so a part needs only whole 16-row tiles; K takes whole 128s because the E4M3 activation
-     * in front carries a scale per (row, 128). */
+    /* ---- OCP-MXFP4, from the weight's encoding. The exponent grid is one row tall, so parts need
+     * only whole 16-row tiles; K takes whole 128s for the activation's per-(row, 128) scale. */
     {
         const char* wn = nm.f("%s.weight", base);
         RAD_ARCH_TRY(map_linear(b, wn, src));
@@ -1467,55 +1315,59 @@ inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t
         if (mx) {
             if (N % 16 || K % RAD_FP8_BLOCK) {
                 fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an MXFP4 weight takes rows "
-                                "in 16s and K in whole %d-column activation scale blocks.\n",
+                                "in 16s and K in whole %d-column activation scale blocks\n",
                         base, (long long)N, (long long)K, RAD_FP8_BLOCK);
                 return RAD_E_INVAL;
             }
-            int64_t p[RAD_MAX_ROW_PARTS] = {0};
-            int     np = 0;
-            for (int64_t q : row_parts) {
-                if (np >= RAD_MAX_ROW_PARTS || q % 16) return RAD_E_INVAL;
-                p[np++] = q;
-            }
-            w   = decl_view(b, wn, nullptr, "codes", RAD_FP4E2M1, { N, K }, access, shard, grp, p, np);
+            RowParts rp;
+            RAD_ARCH_TRY(rp.set(row_parts, 16, 1, base, "MXFP4 tiles"));
+            w   = decl_view(b, wn, nullptr, "codes", RAD_FP4E2M1, { N, K }, access, shard, grp,
+                            rp.w, rp.n);
             s   = decl_view(b, nm.f("%s.scale", base), wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
-                            access, shard, grp, p, np);
+                            access, shard, grp, rp.w, rp.n);
             ref = decl_view(b, nm.f("%s.ref", base), wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
-                            access, shard, grp, p, np);
+                            access, shard, grp, rp.w, rp.n);
             return w && s && ref ? RAD_OK : RAD_E_INVAL;
         }
     }
     if (N % RAD_FP8_BLOCK || K % RAD_FP8_BLOCK) {
         fprintf(stderr, "radiance: '%s' is %lldx%lld per rank, which is not a whole number of "
                         "%dx%d scale blocks. A block-scaled fp8 weight cannot be split inside a "
-                        "block; use a bf16 linear here or a world_size that divides cleanly.\n",
+                        "block; use a bf16 linear here or a world_size that divides cleanly\n",
                 base, (long long)N, (long long)K, RAD_FP8_BLOCK, RAD_FP8_BLOCK);
         return RAD_E_INVAL;
     }
 
-    int64_t wp[RAD_MAX_ROW_PARTS] = {0}, sp[RAD_MAX_ROW_PARTS] = {0};
-    int     np = 0;
-    for (int64_t p : row_parts) {
-        if (np >= RAD_MAX_ROW_PARTS) return RAD_E_INVAL;
-        if (p % RAD_FP8_BLOCK) {
-            fprintf(stderr, "radiance: '%s' stacks a %lld-row part, which is not a whole number "
-                            "of %d-row scale blocks; it cannot be row-sharded.\n",
-                    base, (long long)p, RAD_FP8_BLOCK);
-            return RAD_E_INVAL;
-        }
-        wp[np] = p;
-        sp[np] = p / RAD_FP8_BLOCK;
-        ++np;
-    }
+    RowParts rp;
+    RAD_ARCH_TRY(rp.set(row_parts, RAD_FP8_BLOCK, RAD_FP8_BLOCK, base, "scale blocks"));
 
     const char* wn = nm.f("%s.weight", base);
     const char* sn = nm.f("%s.scale",  base);   /* the name map was made above */
-    w = decl_view(b, wn, nullptr, "codes", RAD_F8E4M3, { N, K }, access, shard, grp, wp, np);
+    w = decl_view(b, wn, nullptr, "codes", RAD_F8E4M3, { N, K }, access, shard, grp, rp.w, rp.n);
     s = decl_view(b, sn, wn, "scale", RAD_BF16, { fp8_blocks(N), fp8_blocks(K) }, access, shard,
-                  grp, sp, np);
+                  grp, rp.s, rp.n);
     return w && s ? RAD_OK : RAD_E_INVAL;
 }
 
+/* gate_up, silu_mul and the E4M3 quantiser in one GEMM epilogue (`gemm_nt_q_gated`, an fp8a8
+ * tile over a block-fp8 [2n, K] weight), declared for M up to min(rows, 64): the kernel refuses M
+ * past that band. Optional: when it does not resolve the caller's unfused ops run, and the issue
+ * site checks `*gated_rows`, set to the band only when the op exists. */
+inline rad_op decl_gated_fold(RadBuilder* b, int64_t rows, int64_t N, int64_t K, rad_weight w,
+                              rad_weight ws, std::initializer_list reads,
+                              std::initializer_list writes, int64_t* gated_rows) {
+    const int64_t hi = rows < 64 ? rows : 64;
+    if (hi <= 0) return 0;
+    const rad_op op = rw(b, RAD_OP(b, "gemm_nt_q_gated",
+                             RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
+                                        RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8"),
+                                        RAD_STR("act", "silu")),
+                             RAD_WEIGHTS(w, ws)),
+                         reads, writes);
+    if (op) *gated_rows = hi;
+    return op;
+}
+
 }  /* namespace arch */
 }  /* namespace rad */
 
diff --git a/arch/common/rad_gemma4_chat.h b/arch/common/rad_gemma4_chat.h
index 74dc4ae7..2911037a 100644
--- a/arch/common/rad_gemma4_chat.h
+++ b/arch/common/rad_gemma4_chat.h
@@ -1,9 +1,8 @@
-/* rad_gemma4_chat.h -- how Gemma 4 spells a turn: its reasoning and its tool calls, as data.
+/* rad_gemma4_chat.h -- Gemma 4's reply format (reasoning and tool calls) as data.
  *
- * The chat template is one llama.cpp reads with a hand-written handler, so the template analysis
- * finds nothing in it, and the engine would serve the model with no reasoning split and refuse
- * every request that sends tools. The model's own tokenizer_config.json states the format instead
- * (`response_template`), and this is that statement in the engine's terms:
+ * Template analysis finds nothing in Gemma 4's chat template (llama.cpp uses a hand-written
+ * handler), so without this the model would get no reasoning split and refuse tool requests.
+ * This restates the model's tokenizer_config.json `response_template` in the engine's terms:
  *
  *   thinking      <|channel>thought\n ... 
  *   tool calls    <|tool_call>call:NAME{key:<|"|>text<|"|>,n:3,flag:true}, repeated
@@ -12,14 +11,12 @@
  *   the turn      ends at ; after its calls the model writes <|tool_response> and stops
  *                 (generation_config.json names it beside  and )
  *
- * llama.cpp's handler records two habits of the model beyond that: an extra thought channel after
- * the answer, and a lone . `reasoning_anywhere` reads the first as reasoning and drops
- * the second, so neither reaches the content.
+ * The model also emits an extra thought channel after the answer and a lone .
+ * `reasoning_anywhere` reads the first as reasoning and drops the second.
  *
- * Here rather than in one plugin because two plugins serve Gemma 4 -- arch/gemma4 (bf16 and fp8
- * experts) and arch/gemma4_bf16 (the CT-INT4 dense release) -- and the format is the model's, not
- * the weights'. One declaration, so the two cannot drift apart, and so the reply-format tests read
- * the declaration the plugins export rather than a copy of it. */
+ * Shared because two plugins serve Gemma 4 (arch/gemma4 with bf16 and fp8 experts, arch/gemma4_bf16
+ * for the CT-INT4 dense release) and the format belongs to the model; the reply-format tests read
+ * this same declaration. */
 #pragma once
 #include "rad_builder.h"
 
@@ -38,8 +35,8 @@ inline const RadChatFormat* gemma4_chat_format() {
         /* A call that starts inside an unclosed thought ends it there. */
         c.reasoning_breaks    = kBreaks;
         c.n_reasoning_breaks  = 1;
-        /* Thinking off, the template closes an empty channel in the generation prompt; on, the
-         * model opens its own -- or, after a tool response, the prompt has opened it. */
+        /* Thinking off: the template closes an empty channel in the generation prompt. On: the
+         * model opens its own, or the prompt has opened it after a tool response. */
         c.reasoning_in_prompt = RAD_CHAT_THINK_FROM_PROMPT;
         c.reasoning_anywhere  = 1;
 
diff --git a/arch/common/rad_qsa.h b/arch/common/rad_qsa.h
index cb95ded6..b8ad9223 100644
--- a/arch/common/rad_qsa.h
+++ b/arch/common/rad_qsa.h
@@ -1,16 +1,15 @@
-/* rad_qsa.h -- Qwen4-Exp's QSA indexer: the part of a full-attention layer that decides WHICH
- * blocks of key history that layer's attention reads.
+/* rad_qsa.h -- Qwen4-Exp's QSA indexer: decides which blocks of key history a full-attention
+ * layer's attention reads.
  *
- * docs/QSA.md is the decomposition and the argument; this is the declaration side of it. The
- * kernels are libr4d's `qsa_block_key`, `qsa_score` and `qsa_select`, and the sparse attention is
- * the ORDINARY `attn_paged` issued with the selection in place of the sequence's own block table
- * -- both of those are plain operands, so nothing in core/ learns what QSA is.
+ * docs/QSA.md has the design; this is the declaration side. The kernels are libr4d's
+ * `qsa_block_key`, `qsa_score` and `qsa_select`; the sparse attention is the ordinary `attn_paged`
+ * issued with the selection in place of the sequence's block table (both plain operands, so core/
+ * knows nothing of QSA).
  *
- * WHAT IS HERE is the whole indexer: the projection and the query path, the block-key path with
- * its two states, and the score and selection the sparse attention is issued with. Below
- * `budget + ratio - 1` tokens of context the selection is EVERY visible block, so the sparse path
- * must reproduce the dense path's text byte for byte -- which is the oracle any change to this
- * file is checked against.
+ * Contents: the projection and query path, the block-key path with its two states, and the score
+ * and selection. Below `budget + ratio - 1` tokens of context every visible block is selected, so
+ * the sparse path must reproduce the dense path's text byte for byte; that is the test for any
+ * change here.
  */
 #ifndef RAD_QSA_H
 #define RAD_QSA_H
@@ -18,6 +17,8 @@
 #include "rad_arch.h"
 #include "rad_fp8.h"
 
+#include 
+
 namespace rad {
 namespace arch {
 
@@ -27,105 +28,75 @@ struct QsaIndexer {
         int64_t     head_dim = 0;   /* indexer_head_dim     -- 128 */
         int64_t     ratio    = 0;   /* indexer_compress_ratio -- 4 tokens a block */
         int64_t     budget   = 0;   /* indexer_budget       -- 2048 tokens, so 512 blocks */
-        int64_t     rot      = 0;   /* the LAYER's rotary width, which the indexer shares */
+        int64_t     rot      = 0;   /* the layer's rotary width, shared by the indexer */
         const char* mode     = "neox";
         /* Checkpoint names. Absent means this layer has no indexer and declare() is a no-op. */
         const char* qk_proj  = nullptr;
         const char* q_norm   = nullptr;
         const char* k_norm   = nullptr;
-        /* Derived, and all four are the caller's because they size things it declares. */
+        /* Derived; set by the caller because they size buffers it declares. */
         int64_t     topk       = 0;   /* budget / ratio -- blocks the selection keeps */
         int64_t     max_blocks = 0;   /* max_ctx / ratio -- the widest block table */
         int64_t     max_work   = 0;   /* ceil(max_tok / ratio) + max_seqs */
-        /* THE TAIL'S RING LENGTH, `ratio + max_spec`, and the `max_spec` is the whole of it.
-         *
-         * A tail of exactly `ratio` rows indexed by `pos % ratio` is right when a step's tokens
-         * are the tokens that happened. Under speculation they are not: a verify step runs
-         * 1 + n_spec positions and the next step RESTARTS at the first rejected one, so positions
-         * the tail has already overwritten are needed again. Concretely at ratio 4, depth 3,
-         * positions 9..12 -- the store writes slots 1,2,3,0 and position 12 lands on the slot
-         * position 8 is still owed to. Accept one and the next step rebuilds block 2 (tokens
-         * 8..11) out of a slot holding token 12. That block key is then wrong in the cache for
-         * the rest of the sequence, and it happens on any step that straddles a block boundary
-         * and does not accept everything -- which is most of them.
-         *
-         * The deepest rollback is to the first draft, so the widest window a step can still owe
-         * is [p0 - ratio + 1, p0 + n_spec]: ratio + n_spec positions, each needing its own
-         * residue. Under `ratio + max_spec` a slot is only ever overwritten by a position that
-         * far ahead, which is past the end of the step that could ask for it. */
+        /* The tail's ring length, `ratio + max_spec`. A ring of `ratio` indexed by `pos % ratio`
+         * fails under speculation: the next step restarts at the first rejected position, so
+         * overwritten slots are needed again (at ratio 4, depth 3, positions 9..12 write slots
+         * 1,2,3,0 and 12 overwrites the slot of 8; accepting one then rebuilds block 2 from token
+         * 12, corrupting that block key permanently). A step can still owe positions
+         * [p0 - ratio + 1, p0 + n_spec], so `ratio + max_spec` slots keep every owed position. */
         int64_t     ring       = 0;   /* ratio + max_spec */
-        /* THE ATTENTION GROUP, because the SELECTION's output is what the attention reads and so
-         * it is that group's page ids that come out. The block-key group is this block's own and
-         * is declared on first use -- see declare(). */
+        /* The attention group, whose page ids the selection outputs. The block-key group is
+         * declared on first use (see declare()). */
         rad_kvgroup kv_attn    = 0;
-        /* THE TAIL'S GROUP: one RAD_KV_LINEAR state a sequence a layer, `ring` rows of
-         * `head_dim`. It is a KV group and not a buffer because a buffer has no way to name a
-         * SEQUENCE -- see the note on Wire. */
+        /* The tail's group: one RAD_KV_LINEAR state per sequence per layer, `ring` rows of
+         * `head_dim` (a KV group because it is per-sequence state; see Wire). */
         rad_kvgroup kv_tail    = 0;
-        /* DOES ANYTHING READ THE SELECTION? False on the DENSE path, where the attention is
-         * issued with the sequence's own block table and `sel` is written for nobody. The block-key
-         * half still runs -- it is STATEFUL, and a history built without it is a history the sparse
-         * path could not later read -- but the score and the selection are then dead work, and on
-         * this model they are the largest op in the indexer. Declared either way, so the graph and
-         * the buffer plan do not depend on it. */
+        /* Whether anything reads the selection. False on the dense path; the stateful block-key
+         * half still runs so the sparse path can later read the history, but score and select (the
+         * indexer's largest ops) are skipped. Declared either way, so the graph and buffer plan do
+         * not depend on it. */
         bool        emit_sel   = true;
+        /* The rows the score plane was declared with, 0 for max_tok. Fewer only where a step
+         * wider than them is one sequence (RadBuildCtx::max_mixed_tok); such a step scores and
+         * selects in windows of this many rows (step()). */
+        int64_t     plane_rows = 0;
     };
 
-    /* The two planes the front half produces. `qk` is the projection whole -- `heads` query heads
-     * then ONE raw key head -- and `q` is the query heads normed and rotated, contiguous.
+    /* `qk` is the whole projection (`heads` query heads, then one raw key head); `q` is the query
+     * heads normed and rotated, contiguous.
      *
-     * THE RAW KEY IS NEVER NORMED OR ROTATED HERE. It is pooled over `ratio` tokens FIRST and the
-     * norm and the rotation happen to the pooled result, at the position of the block's first
-     * token (`qsa_block_key`). Reading the reference quickly gives the opposite impression,
-     * because the q path right above it does both. */
+     * The raw key is not normed or rotated here: it is pooled over `ratio` tokens first, and the
+     * pooled result is normed and rotated at the block's first token's position (`qsa_block_key`),
+     * unlike the q path. */
     struct Wire {
         rad_buf qk = 0;   /* [max_tok, (heads + 1) * head_dim] */
         rad_buf q  = 0;   /* [max_tok, heads * head_dim] */
-        /* THE TAIL IS NOT IN THIS WIRE AND CANNOT BE. Every other buffer here is within-step
-         * scratch, which is why one set serves the whole model; the tail carries an unfinished
-         * block's RAW INDEX KEYS ACROSS STEPS, and that makes it state with two axes a buffer
-         * cannot express.
-         *
-         *   THE LAYER. The keys are `index_qk_proj`'s output and that weight is PER LAYER, so a
-         *   shared tail has layer L pooling layer L-1's keys -- at decode three of every four
-         *   keys in a completing block come from the wrong layer. Every layer needs its own,
-         *   including the MTP head's.
-         *
-         *   THE SEQUENCE. A per-layer buffer indexed by the BATCH ROW is no better across
-         *   requests: the row is step-local -- the scheduler builds the step from `running_` in
-         *   priority order and then stable-sorts decode first -- so a sequence that outlives an
-         *   earlier one shifts down a row and inherits its keys. A buffer has no per-sequence
-         *   axis to index instead; a KV group does, and that is the one the engine keeps stable
-         *   for the life of a sequence, zeroes when it hands a slot out, and checkpoints with
-         *   the rest of the linear state when the prefix cache saves one.
-         *
-         * So the tail is `Config::kv_tail`, a RAD_KV_LINEAR group, and declare() binds this
-         * layer to it. Nothing about it belongs to a wire shared by every layer. */
+        /* These buffers are within-step scratch shared by every layer. The tail is not here: it
+         * carries an unfinished block's raw index keys across steps, per layer (each layer has its
+         * own `index_qk_proj`, the MTP head included) and per sequence (batch rows are step-local
+         * and shift between steps). A KV group has a stable per-sequence slot, zeroed on hand-out
+         * and checkpointed with the linear state by the prefix cache, so the tail is
+         * `Config::kv_tail` (RAD_KV_LINEAR), bound to this layer in declare(). */
         rad_buf stage = 0;   /* [max_work * ratio, head_dim] */
         rad_buf page  = 0;   /* [max_work]      i32 */
         rad_buf bpos  = 0;   /* [max_work] i32, or [max_work, 3] under M-RoPE */
         rad_buf nc    = 0;   /* [max_seqs]      i32 */
-        /* The selection, ONE ROW A QUERY and not one a sequence. At decode the two are the same
-         * thing; at prefill a chunk's queries share one history and each picks its own set out of
-         * it, which is the whole of Stage B (docs/QSA.md). `sel` and `seqused` are what the sparse
-         * attention is issued with in place of the sequence's own block table and length.
+        /* The selection, one row per query, not per sequence (the same at decode; at prefill each
+         * query of a chunk selects from the shared history, docs/QSA.md, "Per-query selection"). `sel` and
+         * `seqused` replace the sequence's block table and length for the sparse attention.
          *
-         * `score` IS THE BIG ONE: max_tok * max_ctx/ratio floats, 134 MB at a 2048-token chunk and
-         * 64K of context. It is one buffer for the whole model rather than one a layer, and
-         * declare() refuses a geometry whose product is unreasonable rather than discovering it as
-         * an allocation failure. Tiling the query axis would cap it, and the reason it is not done
-         * is that `cu` is absolute over the batch: a tile would need its rows rebased, which means
-         * a per-token sequence id operand -- qsa_work is where it would come from. */
+         * `score` is the largest: max_tok * max_ctx/ratio floats, 134 MB at a 2048-token chunk
+         * and 64K context, one buffer for the whole model. A step of one sequence is tiled on the
+         * query axis when it is wider than the plane (Config::plane_rows): a window of it is a
+         * sequence of its own rows. A step of several is not: that would need a per-token
+         * sequence id operand (from qsa_work), since `cu` is absolute over the batch. */
         rad_buf score = 0;   /* [max_tok, max_blocks] f32 */
         rad_buf sel   = 0;   /* [max_tok, topk + 1]   i32 */
         rad_buf nsel  = 0;   /* [max_tok]             i32 */
         rad_buf sequ  = 0;   /* [max_tok]             i32 */
-        /* THE MODEL'S cos/sin PLANE, [rope_table_rows, rot], or 0 if it builds none. It is the
-         * attention block's -- `rope_table` fills it once a step for every layer -- and the
-         * indexer's own rotation is at the same `rot`, `theta` and `scale`, so the rows are
-         * already there. A block handed no table asks for no fusion and runs the per-head norms
-         * below, which is what keeps a plugin that does not build the table on the unfused
-         * path. */
+        /* The model's cos/sin plane, [rope_table_rows, rot], or 0 if it builds none. Filled once a
+         * step by `rope_table` for the attention block; the indexer rotates at the same `rot`,
+         * `theta` and `scale`. Without it the unfused per-head norms run. */
         rad_buf cos_sin = 0;
     };
 
@@ -137,26 +108,24 @@ struct QsaIndexer {
     LinearFP8   proj{};
     rad_kvgroup kv_bk = 0;
     rad_op      op_norm = 0, op_rope = 0, op_qprep = 0;
-    /* The most rows `op_qprep` may be issued over, 0 when it is not declared. It is the model's
-     * own `qk_fuse_rows` and it is NOT a tuning: the cos/sin table is filled only for steps at or
-     * under it, so above it the rows this op would read were never written. */
+    /* Most rows `op_qprep` may be issued over (0 when not declared): `qk_fuse_rows`, a correctness
+     * bound, since the cos/sin table is filled only for steps at or under it. */
     int64_t     qprep_rows = 0;
     rad_op      op_work = 0, op_bkey = 0, op_tail = 0, op_score = 0, op_select = 0;
 
     bool on() const { return op_rope != 0; }
 
-    /* `bk` is the block-key KV group, created on FIRST USE and shared by every QSA layer after
-     * that -- which is why it is an in/out parameter rather than a member. It cannot be declared
-     * with the model's other groups: `Builder::find_kv_consumer` binds a group to the first op
-     * declared AFTER it that carries a `block_size`, and between a model-level declaration and
-     * this block's `qsa_block_key` there is a whole layer of other ops. Declared immediately
-     * before its own consumer, the binding cannot be anything else. */
+    /* `bk` is the block-key KV group, created on first use and shared by all QSA layers (hence
+     * in/out). It must be declared immediately before `qsa_block_key`: `Builder::find_kv_consumer`
+     * binds a group to the first later-declared op with a `block_size`. */
     int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Config& cfg,
                 const Wire& wire, const ActFP8& in, rad_kvgroup* bk);
-    void step(RadCtx* c, const ActFP8& in, const RadBatch* batch) const;
-    /* The block keys and the tail of the pass's rows and nothing else: no query, no score, no
-     * selection. What a pass that only leaves the layer's state behind asks for (see
-     * AttnGatedFP8::store_kv); the stores are the ones step() makes. */
+    /* `win_cu`, device: {0, plane_rows}, the one sequence of a window of a step wider than the
+     * score plane (Config::plane_rows); null where no step is. */
+    void step(RadCtx* c, const ActFP8& in, const RadBatch* batch,
+              const int32_t* win_cu = nullptr) const;
+    /* Stores the pass's block keys and tail exactly as step() does, with no query, score or
+     * selection (see AttnGatedFP8::store_kv). */
     void store(RadCtx* c, const ActFP8& in, const RadBatch* batch) const;
     bool store_keys(RadCtx* c, const RadBatch* batch) const;
 };
@@ -168,9 +137,8 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
     if (!c.qk_proj || !c.q_norm) return RAD_OK;          /* no indexer on this layer */
     if (c.heads <= 0 || c.head_dim <= 0 || c.ratio <= 0 || c.budget <= 0) return RAD_E_INVAL;
     if (!w.qk || !w.q) return RAD_E_INVAL;
-    /* The rotation is the LAYER's and it has to fit inside the index head, which the checkpoint's
-     * own validator also requires -- so a container that violated it is refused here by name
-     * rather than rotating past the end of a head. */
+    /* The layer's rotary width must fit inside the index head (as the checkpoint's validator also
+     * requires). */
     if (c.rot < 0 || c.rot > c.head_dim || (c.rot & 1)) return RAD_E_SHAPE;
 
     const int64_t nw = (c.heads + 1) * c.head_dim;       /* the projection width */
@@ -182,41 +150,23 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
                   RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
     if (!w_qn) return RAD_E_INVAL;
 
-    /* ONE DECLARED NORM, ISSUED ONCE A HEAD, and the reason is the projection's layout rather
-     * than a preference. `qk` is `heads + 1` heads wide, so the query heads are 128 apart WITHIN
-     * a token and 640 apart ACROSS tokens -- which is not a stride any rank-2 view can express,
-     * and the ABI narrows dim 0 or the last dimension and nothing between. A column slice of ONE
-     * head is expressible, so the norm runs `heads` times and writes into a contiguous `q` that
-     * the rotation can then take whole.
+    /* Unfused, one norm op is issued once per head: in `qk` (`heads + 1` heads wide) the query
+     * heads are 128 apart within a token and 640 apart across tokens, which no rank-2 view can
+     * express, but a one-head column slice can. It writes a contiguous `q` that the rope takes
+     * whole. For 128-wide rows these launches are nearly all overhead.
      *
-     * Four extra launches a layer, and for a 128-wide row the launch IS the cost: the norms and
-     * the ropes across the model's indexer layers are a real slice of a decode step against
-     * microseconds of arithmetic. `op_qprep` is the fused form that replaces them.
-     *
-     * THE FUSED FORM IS `qk_norm_rope_gate`'S K SIDE, not a new op. That kernel already reads a
-     * plain [tokens, heads, head_dim] input at the operand's OWN row pitch and writes the heads
-     * contiguously -- which is exactly this projection's query half inside its `heads + 1` width
-     * -- and it already rounds the norm to bf16 before rotating, because that is what a norm that
-     * stores a tensor and a rope that reads it back do. The only thing its q side adds is the
-     * [q|gate] split, and there is no gate here, so `n_head` 0 asks for the half that fits and
-     * passes no q operands at all. Five launches a layer become one.
-     *
-     * IT NEEDS THE MODEL'S cos/sin TABLE and asks for nothing if it has none. The rotation is at
-     * the same `rot`, `theta` and `scale` as the attention block's, so `rope_table` has already
-     * written the rows this step's positions name -- and a plugin that builds no table leaves
-     * `w.cos_sin` at 0 and runs the per-head norms below unchanged.
-     *
-     * AND ONLY UP TO `qk_fuse_rows`, WHICH IS A CORRECTNESS BOUND AND NOT A TUNING. The model
-     * issues `rope_table` only for steps at or under that row count -- the fusion pays where the
-     * launch is the cost, and a prefill chunk's kernels already fill the card -- so ABOVE it the
-     * table rows this op would read were never written THIS step. It would rotate by another
-     * step's angles: fluent text with a subtly wrong sense of position, which is the failure
-     * `rope_table`'s own note calls out and which nothing downstream would flag. The bound is the
-     * attention block's, off the same function, so the two cannot drift apart. */
+     * `op_qprep` fuses them (five launches to one) using `qk_norm_rope_gate`'s k side: it reads
+     * [tokens, heads, head_dim] at the operand's row pitch, writes heads contiguously, and rounds
+     * the norm to bf16 before rotating. With no gate, `n_head` 0 selects that half and passes no
+     * q operands. It needs the model's cos/sin table (same `rot`, `theta`, `scale` as the
+     * attention block) and is used only up to `qk_fuse_rows`, a correctness bound: the table is
+     * filled only for steps that small, so a larger step would rotate by stale angles. The bound
+     * comes from the same function as the attention block's. */
     const bool qprep_neox = !std::strcmp(c.mode, "neox") || !std::strcmp(c.mode, "mrope") ||
                             g.rope_mc;
     qprep_rows = qk_fuse_rows(g);
-    if (w.cos_sin && qprep_neox && qprep_rows > 0 && (c.head_dim % 32) == 0)
+    if (w.cos_sin && qprep_neox && qprep_rows > 0 && (c.head_dim % 32) == 0 &&
+        rad_op_declared(b, "qk_norm_rope_gate"))
         op_qprep = rw(b, RAD_OP(b, "qk_norm_rope_gate",
                          RAD_PARAMS(RAD_RANGE("M", 1, qprep_rows),
                                     RAD_INT("head_dim", c.head_dim), RAD_INT("n_head", 0),
@@ -239,9 +189,7 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
     if (!c.k_norm || !w.stage || !c.topk || !c.max_blocks || !c.max_work)
         return RAD_E_INVAL;
     if (!c.kv_tail || c.ring < c.ratio) return RAD_E_INVAL;
-    /* THIS LAYER'S TAIL STATE. The group is the caller's -- it holds one state per sequence per
-     * BOUND LAYER, so binding is how this layer gets its own, and it is the same call the
-     * block-key group needs for the same reason. */
+    /* This layer's tail state: the caller's group holds one state per sequence per bound layer. */
     RAD_ARCH_TRY(rad_bind_layer_kv(b, l, c.kv_tail));
     RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.qsa_k_norm.weight", l), c.k_norm));
     w_kn = decl_w(b, nm.f("blk.%d.qsa_k_norm.weight", l), RAD_F32, { c.head_dim },
@@ -256,10 +204,9 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
                     RAD_NOWEIGHTS),
                 {w.qk}, {w.stage, w.page, w.bpos, w.nc});
 
-    /* THE GROUP IS DECLARED HERE, immediately before the op that sizes it -- see declare()'s
-     * note. `kv_heads` 1, `block_size` the compress ratio and `head_dim` n/(2*ratio) make a page
-     * hold exactly `n` contiguous values, which is one block key, and make the manager allocate
-     * exactly one page per `ratio` tokens. The geometry is a container, not an attention shape. */
+    /* The block-key group, declared immediately before its consumer (see the declaration). One KV
+     * head, `block_size` = ratio and `head_dim` = n / (2 * ratio) make a page hold exactly one
+     * block key of `n` values, one page per `ratio` tokens. */
     if (*bk == 0) {
         if ((c.head_dim % (2 * c.ratio)) != 0) return RAD_E_SHAPE;
         RadKVGroupDecl d{};
@@ -271,27 +218,20 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
         if (!*bk) return RAD_E_INVAL;
     }
     kv_bk = *bk;
-    /* UNDER M-RoPE a block key rotates at its first token's three components, which qsa_work
-     * writes into a [work, 3] `bpos` when it is handed the step's rotary planes. */
-    op_bkey = g.rope_mc
-        ? decl_rotary(b, g, "qsa_block_key",
-                 RAD_PARAMS(RAD_RANGE("M", 1, c.max_work), RAD_INT("n", c.head_dim),
-                            RAD_INT("ratio", c.ratio), RAD_INT("rotary_dim", c.rot),
-                            RAD_INT("block_size", c.ratio),
-                            RAD_F64("eps", g.eps), RAD_F64("theta", g.theta),
-                            RAD_F64("scale", g.rope_scale), RAD_F64("wadd", g.wadd_qk),
-                            RAD_STR("dtype", g.dtype), RAD_STR("mode", g.rope_mode),
-                            RAD_STR("sections", g.rope_sections)),
-                 RAD_WEIGHTS(w_kn))
-        : decl_rotary(b, g, "qsa_block_key",
-                 RAD_PARAMS(RAD_RANGE("M", 1, c.max_work), RAD_INT("n", c.head_dim),
-                            RAD_INT("ratio", c.ratio), RAD_INT("rotary_dim", c.rot),
-                            RAD_INT("block_size", c.ratio),
-                            RAD_F64("eps", g.eps), RAD_F64("theta", g.theta),
-                            RAD_F64("scale", g.rope_scale), RAD_F64("wadd", g.wadd_qk),
-                            RAD_STR("dtype", g.dtype)),
-                 RAD_WEIGHTS(w_kn));
-    op_bkey = rw(b, op_bkey, {w.stage, w.page, w.bpos}, {});
+    /* Under M-RoPE a block key rotates at its first token's three components, which qsa_work
+     * writes into a [work, 3] `bpos` when given the step's rotary planes. */
+    {
+        const RadParam ps[] = { RAD_RANGE("M", 1, c.max_work), RAD_INT("n", c.head_dim),
+                                RAD_INT("ratio", c.ratio), RAD_INT("rotary_dim", c.rot),
+                                RAD_INT("block_size", c.ratio),
+                                RAD_F64("eps", g.eps), RAD_F64("theta", g.theta),
+                                RAD_F64("scale", g.rope_scale), RAD_F64("wadd", g.wadd_qk),
+                                RAD_STR("dtype", g.dtype), RAD_STR("mode", g.rope_mode),
+                                RAD_STR("sections", g.rope_sections) };
+        const int n_ps = (int)(sizeof ps / sizeof ps[0]) - (g.rope_mc ? 0 : 2);
+        op_bkey = rw(b, decl_rotary(b, g, "qsa_block_key", ps, n_ps, &w_kn, 1),
+                     {w.stage, w.page, w.bpos}, {});
+    }
     RAD_ARCH_TRY(rad_bind_layer_kv(b, l, kv_bk));
 
     op_tail = rw(b, RAD_OP(b, "qsa_tail_store",
@@ -302,8 +242,7 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
                     RAD_NOWEIGHTS),
                 {w.qk}, {});
 
-    /* M IS QUERIES ON BOTH, up to a whole prefill chunk. A band stopping at max_seqs would be
-     * right only for a per-SEQUENCE selection; this one selects per QUERY. */
+    /* M is queries for both, up to a whole prefill chunk: the selection is per query. */
     op_score = rw(b, RAD_OP(b, "qsa_score",
                      RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", c.head_dim),
                                 RAD_INT("heads", c.heads), RAD_INT("blocks", c.max_blocks),
@@ -319,9 +258,9 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
     return RAD_OK;
 }
 
-/* THE KEYS A PASS LEAVES BEHIND: the block keys of the blocks its rows complete and the tail of
- * raw keys after them, out of the projection's raw-key head. False when the step carries no batch
- * for the indexer's groups. */
+/* Stores the block keys of the blocks the pass completes and the tail of raw keys after them,
+ * from the projection's raw-key head. False when the step has no batch for the indexer's
+ * groups. */
 inline bool QsaIndexer::store_keys(RadCtx* c_, const RadBatch* batch) const {
     const int64_t T = batch->n_tok, S = batch->n_seq;
     const int64_t nw = (c.heads + 1) * c.head_dim;
@@ -329,26 +268,18 @@ inline bool QsaIndexer::store_keys(RadCtx* c_, const RadBatch* batch) const {
     const RadKVGroupBatch* bkb = kv_batch(batch, kv_bk);
     const RadKVGroupBatch* tlb = kv_batch(batch, c.kv_tail);
     if (!bkb || !tlb) return false;
-    /* COLUMN 0 OF THE STATE ROW IS THE COMMITTED SLOT. The row is wider than one whenever the
-     * deployment speculates -- the manager gives every linear group a second copy then, because
-     * the kernel that needed one asked for it -- and this op wants the committed slot in every
-     * case. The pitch is the batch's, not a constant. */
+    /* Column 0 of the state row is the committed slot; the row is wider when speculating (linear
+     * groups get a second copy), so use the batch's pitch. */
     const int64_t tw = tlb->state_index_pitch > 0 ? tlb->state_index_pitch : 1;
 
-    /* THE WORK LIST BEFORE THE TAIL STORE, and the order is load-bearing rather than tidy: the
-     * gather reads the raw keys of the block that is completing, and up to `ratio - 1` of them
-     * are in the tail from earlier steps -- which the store is about to overwrite with this
-     * step's. Reversed, every block completing at decode would pool three of this step's keys.
-     *
-     * The ring makes the store's overwrite land `ring` positions later rather than `ratio`, so
-     * the two do not collide within a step either -- but the order still decides what a
-     * straddling block reads, and it is the cheaper of the two guarantees to keep. */
+    /* Invariant: the work list runs before the tail store. The gather reads a completing block's
+     * raw keys, up to `ratio - 1` of which are in the tail from earlier steps and are about to be
+     * overwritten. The ring also spaces overwrites by `ring` positions, but the order still decides
+     * what a straddling block reads. */
     const int64_t work = (T + c.ratio - 1) / c.ratio + S;
-    /* THE BLOCK POSITIONS: one component a block, or -- under M-RoPE with the planes -- three.
-     * Under M-RoPE `bpos` is declared [max_work, 3], a block a row, so a smaller step is fewer
-     * rows and the arena's sizing declare can shrink it; this step hands [work, 3], or its first
-     * column alone when the pass has no planes -- qsa_work then writes component 0 and the block
-     * key reads the one-component form. */
+    /* Block positions: one component per block, or three under M-RoPE with planes. Under M-RoPE
+     * `bpos` is [max_work, 3]; this step passes [work, 3], or only column 0 when the pass has no
+     * planes (qsa_work then writes component 0 and the block key reads the one-component form). */
     const bool mc = g.rope_mc && batch->rope_pos;
     RadOperand bpos = g.rope_mc ? RAD_B_COL(w.bpos, 0, mc ? 3 : 1) : brows(w.bpos, work);
     if (g.rope_mc) bpos.rows = work;
@@ -381,20 +312,18 @@ inline void QsaIndexer::store(RadCtx* c_, const ActFP8& in, const RadBatch* batc
     (void)store_keys(c_, batch);
 }
 
-inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch) const {
+inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch,
+                             const int32_t* win_cu) const {
     if (!on()) return;
     const int64_t T = batch->n_tok, S = batch->n_seq;
     const int64_t qw = c.heads * c.head_dim;
     const int64_t nw = (c.heads + 1) * c.head_dim;
 
     proj.step(c_, in, w.qk, T);
-    /* ONE LAUNCH OR `heads` + 1. The fused form takes the projection WHOLE -- the kernel picks
-     * head `h` out of it at the operand's own row pitch, so the strided view the unfused norm
-     * needs is not taken at all -- and it writes the query heads contiguous and rotated, which is
-     * what the pair below leaves behind. `n_head` 0 is the k-only form: no q_gate, no q_w, no
-     * q_out, and the ninth operand (`gate_out`) is absent as it is everywhere else.
-     *
-     * `T <= qprep_rows` IS THE TABLE'S BOUND and declare() says why it is correctness. */
+    /* One fused launch or `heads` + 1 unfused. The fused form takes the whole projection at its
+     * row pitch and writes the query heads contiguous and rotated. `n_head` 0 is the k-only form:
+     * no q_gate, q_w or q_out, and `gate_out` absent. `T <= qprep_rows` is a correctness bound
+     * (see declare()). */
     if (op_qprep && T <= qprep_rows && !rope_mixed(batch)) {
         RAD_ISSUE_N(c_, op_qprep, T,
                     RAD_NONE, brows(w.qk, T), RAD_B(w.cos_sin), rope_pos1(batch, T),
@@ -413,29 +342,57 @@ inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch
     const RadKVGroupBatch* atb = kv_batch(batch, c.kv_attn);
     if (!atb || !store_keys(c_, batch)) return;
 
-    /* SCORE AND SELECT OVER EVERY QUERY IN THE STEP. A selection does not have to be per-SEQUENCE
-     * even though a block table is: both ops take `cu`, the block table stays the sequence's, and
-     * `m` is a query row. So a prefill chunk's queries each get their own selection out of the one
-     * history they share, which is what the checkpoint does, and there is no cap on the context a
-     * step may index. */
+    /* Score and select per query: both ops take `cu`, the block table stays per sequence, and `m`
+     * is a query row, so each query of a prefill chunk selects from the shared history, as the
+     * checkpoint does. */
     if (!c.emit_sel) return;
 
-    /* HOW MUCH HISTORY THERE ACTUALLY IS. The score plane is declared for `max_ctx`, so scoring
-     * and selecting to its width means a 2000-token prompt walks 50000 block slots -- and both
-     * kernels size their GRID from the declared width, because the live count is device data.
-     * Narrowing the operand is how the host tells them: the pitch stays the declaration's, only
-     * the column count moves, which is the same trick the attention block plays with `reach`.
+    /* Narrow the score columns to the live history. Both kernels size their grid from the
+     * operand's width (the live count is device data), so the full `max_ctx` width would make a
+     * 2000-token prompt walk 50000 block slots; the pitch stays declared, only the column count
+     * moves.
      *
-     * IT IS A CEILING AND EVERY TERM IS SLACK, because an UNDER-estimate silently drops blocks
-     * from the selection and nothing would say so. A query's complete-block count is at most
-     * (position + 1) / ratio; the highest position this step can reach is bounded by the
-     * host-side context bound plus every token in the step plus the draft window; and the +1
-     * keeps `n < nb`, which is what makes the partial page -- `bt[n]` -- readable at all. */
+     * This must be an upper bound: an underestimate silently drops blocks. A query has at most
+     * (position + 1) / ratio complete blocks; positions are bounded by the host context bound plus
+     * the step's tokens plus the draft window; the +1 keeps `n < nb` so the partial page `bt[n]`
+     * is readable. */
     const int64_t reach = (int64_t)batch->max_ctx_len + batch->n_tok + batch->n_spec + c.ratio;
     int64_t live = reach / c.ratio + 1;
     if (live > c.max_blocks) live = c.max_blocks;
     if (live < 1) live = 1;
 
+    /* A step wider than the score plane is one sequence (Config::plane_rows), scored and selected
+     * in windows of the plane's rows from the front, the last one ending at the step's end and
+     * overlapping the one before. A window is handed as a sequence of its own rows (`win_cu` =
+     * {0, rows}). Every operand a query row reads is its own (query, position, selection) and the
+     * block table and complete-block count are the step's, so each row is scored and selected as
+     * in one pass over the step, and a row two windows share is written twice with the same
+     * bytes. */
+    const int64_t PR = c.plane_rows > 0 ? c.plane_rows : T;
+    if (T > PR) {
+        if (S != 1 || !win_cu) {
+            rad_step_fail(c_, "qsa: a step wider than the score plane must be one sequence with "
+                              "its window bounds (RadBuildCtx::max_mixed_tok)");
+            return;
+        }
+        for (int64_t w0 = 0;;) {
+            RAD_ISSUE_N(c_, op_score, PR,
+                        brow_slice(w.q, w0, PR, qw), kv_cache(kv_bk, layer),
+                        praw2(bkb->block_table, RAD_I32, S, bkb->block_table_pitch),
+                        praw(win_cu, RAD_I32, 2), brows(w.nc, S),
+                        bcol_at(w.score, 0, c.max_blocks, 0, live, PR));
+            RAD_ISSUE_N(c_, op_select, PR,
+                        bcol_at(w.score, 0, c.max_blocks, 0, live, PR),
+                        praw2(atb->block_table, RAD_I32, S, atb->block_table_pitch),
+                        brows(w.nc, S), praw(batch->positions + w0, RAD_I32, PR),
+                        praw(win_cu, RAD_I32, 2),
+                        brow_slice(w.sel, w0, PR, c.topk + 1), brow_slice(w.nsel, w0, PR, 1),
+                        brow_slice(w.sequ, w0, PR, 1));
+            if (w0 + PR >= T) break;
+            w0 = w0 + PR + PR <= T ? w0 + PR : T - PR;
+        }
+        return;
+    }
     RAD_ISSUE_N(c_, op_score, T,
                 brows(w.q, T), kv_cache(kv_bk, layer),
                 praw2(bkb->block_table, RAD_I32, S, bkb->block_table_pitch),
@@ -448,14 +405,13 @@ inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch
                 praw(batch->cu_seqlens, RAD_I32, S + 1),
                 brows(w.sel, T), brows(w.nsel, T), brows(w.sequ, T));
 
-    /* RADIANCE_DEBUG_QSA: the only window into a selection. Nothing else in the tree reports one,
-     * and the numbers it prints are what tell a divergence from the dense path apart from QSA
-     * doing its job -- `nc` above `topk` is blocks being dropped ON PURPOSE. It SYNCHRONISES THE
-     * STREAM, so it is an environment variable, off, and costs nothing when it is not set; the
-     * first few decode steps are enough to see the shape. */
-    if (getenv("RADIANCE_DEBUG_QSA")) {
-        static int seen = 0;
-        if (seen++ < 6) {
+    /* RADIANCE_DEBUG_QSA: prints the first few selections (nc, nsel, sequ, leading sel and score
+     * entries) to tell a divergence from intended dropping (`nc` above `topk`). Synchronises the
+     * stream; off unless set. */
+    static const bool dbg = std::getenv("RADIANCE_DEBUG_QSA") != nullptr;
+    if (dbg) {
+        static std::atomic seen{0};
+        if (seen.fetch_add(1) < 6) {
             rad_stream_sync(rad_stream(c_));
             std::vector hnc(1), hns(1), hsu(1), hsel(8);
             std::vector   hsc(8);
diff --git a/arch/embgemma2/CMakeLists.txt b/arch/embgemma2/CMakeLists.txt
index e7119f87..2baa67d8 100644
--- a/arch/embgemma2/CMakeLists.txt
+++ b/arch/embgemma2/CMakeLists.txt
@@ -1,6 +1,5 @@
-# A plugin like any other: built here inside radiance's tree, or on its own against an installed
-# radiance (`cmake -S arch/embgemma2 -B build -DCMAKE_PREFIX_PATH=`) -- the same
-# rad_add_plugin either way (cmake/RadAddPlugin.cmake).
+# Built in radiance's tree, or standalone against an installed radiance
+# (`cmake -S arch/embgemma2 -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake.
 if(NOT COMMAND rad_add_plugin)
   cmake_minimum_required(VERSION 3.21)
   project(embgemma2 LANGUAGES CXX)
diff --git a/arch/embgemma2/embgemma2.cpp b/arch/embgemma2/embgemma2.cpp
index 1fe96b41..6dd04f00 100644
--- a/arch/embgemma2/embgemma2.cpp
+++ b/arch/embgemma2/embgemma2.cpp
@@ -1,11 +1,10 @@
 /* embgemma2 -- EmbeddingGemma 2, a bidirectional Gemma encoder that pools a whole input into one
  * vector. bf16 weights and bf16 activations.
  *
- * AN EMBEDDING MODEL, NOT A GENERATIVE ONE. It declares a pooled output (rad_declare_pooled) and
- * no logits, so the engine runs it with no sampler and no KV cache, carries every input whole in
- * one step and hands each sequence's pooled row back as its answer. Attention is BIDIRECTIONAL on
- * every layer, which is why nothing is paged: a token attends to the tokens after it, so there is
- * nothing a cache could carry from one step to the next.
+ * An embedding model: it declares a pooled output (rad_declare_pooled) and no logits, so the
+ * engine runs it with no sampler and no KV cache, carries every input whole in one step, and
+ * returns each sequence's pooled row. Attention is bidirectional on every layer, so nothing is
+ * paged: a token attends to later tokens, and there is nothing to carry between steps.
  *
  * ============================== THE SHAPE ==============================
  *
@@ -13,27 +12,26 @@
  *   layer_types: five `sliding_attention` then one `full_attention`, four times over
  *     sliding: 4 heads / 2 kv heads / head_dim 256, rope theta 1e4, |i - j| <= 512
  *     full:    4 heads / 1 kv head  / head_dim 512, rope theta 1e6, the whole input
- *   attention scale 1.0 (the q/k norms carry the temperature); q, k AND v are RMS-normed per head,
+ *   attention scale 1.0 (the q/k norms carry the temperature); q, k and v are RMS-normed per head,
  *   v with no gain
- *   Gemma's sandwich norms: a norm before AND after attention and the feed-forward, all plain
+ *   Gemma's sandwich norms: a norm before and after attention and the feed-forward, all plain
  *   RMSNorm gains (x_hat * w, not 1 + w)
  *   a gated gelu-tanh feed-forward
- *   PER-LAYER EMBEDDINGS, projection-only: the token embedding projected to 24 x 512, normed, and
+ *   per-layer embeddings, projection-only: the token embedding projected to 24 x 512, normed, and
  *   each layer's slice gating that layer's residual through a 512 -> 512 -> 512 bottleneck
  *   a learned scalar per layer, multiplying the residual stream at the layer's end
  *   final norm, then the mean over every token of the input, then 512 -> 768
  *
  * The reference is transformers' modeling_embedding_gemma2 (model_type embedding_gemma2, which
  * rad-convert spells `embeddinggemma2`). Its mean pooling and normalisation are
- * sentence-transformers' modules on top; the normalisation is the server's (it truncates to
+ * sentence-transformers' modules on top; normalisation is the server's (it truncates to
  * `dimensions` first), so the pooled row here is the unnormalised mean.
  *
- * ============================== WHAT THIS PLUGIN DOES NOT YET DECLARE ==============================
- *
- * Nothing the checkpoint carries: the text model, the vision tower and the audio encoder are all
- * below.
+ * Everything the checkpoint carries is declared: the text model, the vision tower
+ * (rad_block_gemma4_vision.h) and the audio encoder.
  */
 #include 
+#include 
 
 #include 
 #include 
@@ -67,285 +65,6 @@ struct Layer {
     rad_op op_post_ple = 0, op_add_ple = 0, op_scale = 0;
 };
 
-/* ============================== THE VISION TOWER (Gemma 4's) ==============================
- *
- *   a patch is 16 x 16 x 3, staged by the processor as 2 * (u / 255) - 1 in bf16, (y, x, channel)
- *   patch embedding: a 768 x 768 linear, plus a learned row for the patch's column and one for its
- *   row (a [2, 10240, 768] table), the two summed first
- *   16 layers: Gemma's sandwich norms, q/k RMS-normed with a gain and v without one, a 2-D rotary
- *   (theta 100) with x over the first half of each 64-wide head and y over the second, each half a
- *   rotary of its own; bidirectional attention within an image at scale 1; a gated gelu-tanh MLP
- *   pooling: the mean of each 3 x 3 window -- the processor lays a window's nine patches out
- *   consecutively -- times sqrt(768), then the multimodal embedder: an RMS norm with no gain and a
- *   768 -> 512 linear. Its rows take the place of the image's placeholder tokens BEFORE the
- *   per-layer inputs are projected, so the per-layer inputs of an image token are its image row's.
- *
- * One encoder pass carries RadBuildCtx::max_enc_patches patches over any number of segments (an
- * image, or one frame of a video). */
-struct Vision {
-    struct Layer {
-        rad_weight in_norm = 0, qkv = 0, q_norm = 0, k_norm = 0, o = 0, post_attn = 0;
-        rad_weight pre_ff = 0, gate_up = 0, down = 0, post_ff = 0;
-        rad_op op_in = 0, op_qkv = 0, op_qk = 0, op_attn = 0, op_o = 0, op_pa = 0, op_add1 = 0;
-        rad_op op_pf = 0, op_gu = 0, op_act = 0, op_down = 0, op_pff = 0, op_add2 = 0;
-    };
-    bool on = false;
-    int64_t P = 0, R = 0, width = 0, heads = 0, hd = 0, ff = 0, patch_dim = 0, pool = 0;
-    int64_t npos = 0, n_embd = 0;
-    rad_weight w_in = 0, w_px = 0, w_py = 0, w_proj = 0;
-    rad_op op_patch = 0, op_px = 0, op_py = 0, op_padd = 0, op_add = 0, op_pool = 0, op_norm = 0;
-    rad_op op_out = 0;
-    rad_buf b_x = 0, b_h = 0, b_o = 0, b_qkv = 0, b_att = 0, b_gu = 0, b_ff = 0, b_px = 0,
-            b_py = 0, b_pool = 0, b_pn = 0, b_out = 0;
-    std::vector L;
-
-    static bool present(const RadModelMeta* m) {
-        const char* t = rad_meta_gets(m, "vision_config.model_type", "");
-        return t && !std::strcmp(t, "gemma4_vision");
-    }
-
-    int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
-                int64_t model_embd, int first_group) {
-        on = false;
-        if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK;
-        width = rad_meta_geti(m, "vision_config.hidden_size", 0);
-        heads = rad_meta_geti(m, "vision_config.num_attention_heads", 0);
-        hd    = rad_meta_geti(m, "vision_config.head_dim", 0);
-        ff    = rad_meta_geti(m, "vision_config.intermediate_size", 0);
-        pool  = rad_meta_geti(m, "vision_config.pooling_kernel_size", 0);
-        npos  = rad_meta_geti(m, "vision_config.position_embedding_size", 0);
-        const int64_t depth = rad_meta_geti(m, "vision_config.num_hidden_layers", 0);
-        const int64_t patch = rad_meta_geti(m, "vision_config.patch_size", 0);
-        const int64_t kvh   = rad_meta_geti(m, "vision_config.num_key_value_heads", heads);
-        const double  eps   = rad_meta_getf(m, "vision_config.rms_norm_eps", 1e-6);
-        const double  theta = rad_meta_getf(m, "vision_config.rope_parameters.rope_theta", 0.0);
-        const char*   rt    = rad_meta_gets(m, "vision_config.rope_parameters.rope_type", "");
-        const char*   act   = rad_meta_gets(m, "vision_config.hidden_activation", "");
-        if (width <= 0 || heads <= 0 || hd <= 0 || ff <= 0 || pool <= 0 || npos <= 0 ||
-            depth <= 0 || patch <= 0 || !(theta > 0) || heads * hd != width || kvh != heads ||
-            hd % 4) {
-            fprintf(stderr, "radiance: embgemma2: the container's vision_config is incomplete or "
-                            "not the shape this plugin serves (hidden %lld, heads %lld x %lld, kv "
-                            "%lld, ff %lld, pooling %lld, layers %lld)\n", (long long)width,
-                    (long long)heads, (long long)hd, (long long)kvh, (long long)ff,
-                    (long long)pool, (long long)depth);
-            return RAD_E_INVAL;
-        }
-        /* What this tower does not carry is refused by name: clipped linears (their bounds are
-         * buffers the vision checkpoint states as infinite), feature standardisation, and any
-         * rotary or activation other than the axial one and gelu-tanh. */
-        if (rad_meta_geti(m, "vision_config.use_clipped_linears", 0) ||
-            rad_meta_geti(m, "vision_config.standardize", 0) || std::strcmp(rt, "axial") ||
-            std::strcmp(act, "gelu_pytorch_tanh")) {
-            fprintf(stderr, "radiance: embgemma2: this vision tower uses clipped linears, "
-                            "standardisation, a '%s' rotary or a '%s' activation, which this "
-                            "plugin does not serve\n", rt, act);
-            return RAD_E_UNSUPPORTED;
-        }
-        n_embd = model_embd;
-        patch_dim = 3 * patch * patch;
-        const int64_t kk = pool * pool;
-        P = ctx->max_enc_patches;
-        if (P % kk) P -= P % kk;
-        R = P / kk;
-        const int A = RAD_ACCESS_PER_REQUEST, N = RAD_SHARD_NONE;
-        const char* V = "vision_tower";
-
-        /* ---- weights: the stem, the position tables and the embedder are model-level; each
-         * tower layer is its own group, past every text layer. */
-        RAD_ARCH_TRY(map_copy(b, nm.f("v.patch.weight"), nm.ckpt("%s.patch_embedder.input_proj.weight", V)));
-        RAD_ARCH_TRY(map_slice(b, nm.f("v.pos_x.weight"),
-                               nm.ckpt("%s.patch_embedder.position_embedding_table", V), 0));
-        RAD_ARCH_TRY(map_slice(b, nm.f("v.pos_y.weight"),
-                               nm.ckpt("%s.patch_embedder.position_embedding_table", V), 1));
-        RAD_ARCH_TRY(map_copy(b, nm.f("v.embed.weight"), nm.ckpt("embed_vision.embedding_projection.weight")));
-        w_in   = decl_w(b, nm.f("v.patch.weight"), RAD_BF16, {width, patch_dim}, A, N, grp_model());
-        w_px   = decl_w(b, nm.f("v.pos_x.weight"), RAD_BF16, {npos, width}, A, N, grp_model());
-        w_py   = decl_w(b, nm.f("v.pos_y.weight"), RAD_BF16, {npos, width}, A, N, grp_model());
-        w_proj = decl_w(b, nm.f("v.embed.weight"), RAD_BF16, {n_embd, width}, A, N, grp_model());
-        L.assign((size_t)depth, Layer{});
-        for (int64_t i = 0; i < depth; ++i) {
-            Layer& l = L[(size_t)i];
-            const long long li = (long long)i;
-            const RadWeightGroup g = grp_layer(first_group + (int)i);
-            auto src = [&](const char* s) { return nm.ckpt("%s.encoder.layers.%lld.%s", V, li, s); };
-            RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.in_norm", li), src("input_layernorm.weight")));
-            RAD_ARCH_TRY(map_concat(b, nm.f("v.blk.%lld.qkv", li),
-                                    {src("self_attn.q_proj.linear.weight"),
-                                     src("self_attn.k_proj.linear.weight"),
-                                     src("self_attn.v_proj.linear.weight")}));
-            RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.q_norm", li), src("self_attn.q_norm.weight")));
-            RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.k_norm", li), src("self_attn.k_norm.weight")));
-            RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.o", li), src("self_attn.o_proj.linear.weight")));
-            RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.post_attn", li), src("post_attention_layernorm.weight")));
-            RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.pre_ff", li), src("pre_feedforward_layernorm.weight")));
-            RAD_ARCH_TRY(map_concat(b, nm.f("v.blk.%lld.gate_up", li),
-                                    {src("mlp.gate_proj.linear.weight"),
-                                     src("mlp.up_proj.linear.weight")}));
-            RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.down", li), src("mlp.down_proj.linear.weight")));
-            RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.post_ff", li), src("post_feedforward_layernorm.weight")));
-            l.in_norm   = decl_w(b, nm.f("v.blk.%lld.in_norm", li),   RAD_BF16, {width}, A, N, g);
-            l.qkv       = decl_w(b, nm.f("v.blk.%lld.qkv", li),       RAD_BF16, {3 * width, width}, A, N, g);
-            l.q_norm    = decl_w(b, nm.f("v.blk.%lld.q_norm", li),    RAD_BF16, {hd}, A, N, g);
-            l.k_norm    = decl_w(b, nm.f("v.blk.%lld.k_norm", li),    RAD_BF16, {hd}, A, N, g);
-            l.o         = decl_w(b, nm.f("v.blk.%lld.o", li),         RAD_BF16, {width, width}, A, N, g);
-            l.post_attn = decl_w(b, nm.f("v.blk.%lld.post_attn", li), RAD_BF16, {width}, A, N, g);
-            l.pre_ff    = decl_w(b, nm.f("v.blk.%lld.pre_ff", li),    RAD_BF16, {width}, A, N, g);
-            l.gate_up   = decl_w(b, nm.f("v.blk.%lld.gate_up", li),   RAD_BF16, {2 * ff, width}, A, N, g);
-            l.down      = decl_w(b, nm.f("v.blk.%lld.down", li),      RAD_BF16, {width, ff}, A, N, g);
-            l.post_ff   = decl_w(b, nm.f("v.blk.%lld.post_ff", li),   RAD_BF16, {width}, A, N, g);
-        }
-
-        /* ---- activations, sized by the pass. */
-        b_x    = decl_b(b, nm.f("v.x"),    RAD_BF16, {P, width});
-        b_h    = decl_b(b, nm.f("v.h"),    RAD_BF16, {P, width});
-        b_o    = decl_b(b, nm.f("v.o"),    RAD_BF16, {P, width});
-        b_qkv  = decl_b(b, nm.f("v.qkv"),  RAD_BF16, {P, 3 * width});
-        b_att  = decl_b(b, nm.f("v.att"),  RAD_BF16, {P, width});
-        b_gu   = decl_b(b, nm.f("v.gu"),   RAD_BF16, {P, 2 * ff});
-        b_ff   = decl_b(b, nm.f("v.ff"),   RAD_BF16, {P, ff});
-        b_px   = decl_b(b, nm.f("v.px"),   RAD_BF16, {P, width});
-        b_py   = decl_b(b, nm.f("v.py"),   RAD_BF16, {P, width});
-        b_pool = decl_b(b, nm.f("v.pool"), RAD_BF16, {R, width});
-        b_pn   = decl_b(b, nm.f("v.pn"),   RAD_BF16, {R, width});
-        b_out  = decl_b(b, nm.f("v.out"),  RAD_BF16, {R, n_embd});
-
-        auto rms = [&](int64_t rows, rad_weight w) {
-            if (!w)
-                return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width),
-                                                       RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
-                                                       RAD_STR("dtype", "bf16")),
-                              RAD_NOWEIGHTS);
-            return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width),
-                                                   RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
-                                                   RAD_STR("dtype", "bf16")),
-                          RAD_WEIGHTS(w));
-        };
-        auto gemm = [&](int64_t rows, int64_t Nn, int64_t K, rad_weight w) {
-            return RAD_OP(b, "gemm_nt", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", Nn),
-                                                   RAD_INT("K", K), RAD_STR("dtype", "bf16")),
-                          RAD_WEIGHTS(w));
-        };
-        auto add = [&](int64_t rows) {
-            return RAD_OP(b, "add", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width),
-                                               RAD_STR("dtype", "bf16")),
-                          RAD_NOWEIGHTS);
-        };
-        auto lookup = [&](rad_weight w) {
-            return RAD_OP(b, "embed_lookup",
-                          RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n_embd", width),
-                                     RAD_INT("n_vocab", npos), RAD_STR("dtype", "bf16"),
-                                     RAD_INT("vocab_offset", 0), RAD_F64("mult", 1.0)),
-                          RAD_WEIGHTS(w));
-        };
-        op_patch = rw(b, gemm(P, width, patch_dim, w_in), {}, {b_x});
-        op_px    = rw(b, lookup(w_px), {}, {b_px});
-        op_py    = rw(b, lookup(w_py), {}, {b_py});
-        op_padd  = rw(b, add(P), {b_px, b_py}, {b_px});
-        op_add   = rw(b, add(P), {b_x, b_px}, {b_x});
-        char sec[48];
-        std::snprintf(sec, sizeof sec, "%lld %lld", (long long)(hd / 4), (long long)(hd / 4));
-        for (Layer& l : L) {
-            l.op_in   = rw(b, rms(P, l.in_norm), {b_x}, {b_h});
-            l.op_qkv  = rw(b, gemm(P, 3 * width, width, l.qkv), {b_h}, {b_qkv});
-            /* x is the column (plane 1 of the staged coordinates), y the row (plane 0). */
-            l.op_qk   = rw(b, RAD_OP(b, "qk_norm_rope",
-                                     RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", hd),
-                                                RAD_INT("n_head", heads), RAD_INT("n_head_kv", heads),
-                                                RAD_F64("theta", theta), RAD_F64("eps", eps),
-                                                RAD_STR("mode", "blocks"), RAD_INT("v_norm", 1),
-                                                RAD_STR("sections", sec), RAD_STR("comps", "1 0")),
-                                     RAD_WEIGHTS(l.q_norm, l.k_norm)),
-                           {b_qkv}, {b_qkv});
-            l.op_attn = rw(b, RAD_OP(b, "attn_dense",
-                                     RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", hd),
-                                                RAD_INT("gqa", 1), RAD_INT("causal", 0),
-                                                RAD_STR("dtype", "bf16"), RAD_F64("scale", 1.0),
-                                                RAD_INT("max_seqlen", P), RAD_INT("window", 0)),
-                                     RAD_NOWEIGHTS),
-                           {b_qkv}, {b_att});
-            l.op_o    = rw(b, gemm(P, width, width, l.o), {b_att}, {b_o});
-            l.op_pa   = rw(b, rms(P, l.post_attn), {b_o}, {b_o});
-            l.op_add1 = rw(b, add(P), {b_x, b_o}, {b_x});
-            l.op_pf   = rw(b, rms(P, l.pre_ff), {b_x}, {b_h});
-            l.op_gu   = rw(b, gemm(P, 2 * ff, width, l.gate_up), {b_h}, {b_gu});
-            l.op_act  = rw(b, RAD_OP(b, "act_mul",
-                                     RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", ff),
-                                                RAD_STR("act", "gelu_tanh"), RAD_STR("dtype", "bf16")),
-                                     RAD_NOWEIGHTS),
-                           {b_gu}, {b_ff});
-            l.op_down = rw(b, gemm(P, width, ff, l.down), {b_ff}, {b_o});
-            l.op_pff  = rw(b, rms(P, l.post_ff), {b_o}, {b_o});
-            l.op_add2 = rw(b, add(P), {b_x, b_o}, {b_x});
-        }
-        op_pool = rw(b, RAD_OP(b, "pool_rows",
-                               RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
-                                          RAD_INT("k", kk), RAD_F64("mult", std::sqrt((double)width)),
-                                          RAD_STR("dtype", "bf16")),
-                               RAD_NOWEIGHTS),
-                     {b_x}, {b_pool});
-        op_norm = rw(b, rms(R, 0), {b_pool}, {b_pn});
-        op_out  = rw(b, gemm(R, n_embd, width, w_proj), {b_pn}, {b_out});
-
-        RadEncoderDecl e{};
-        e.name        = "vision";
-        e.modalities  = RAD_MM_IMAGE | RAD_MM_VIDEO;
-        e.patch_dim   = patch_dim;
-        e.merge       = kk;
-        e.max_patches = P;
-        e.n_embd      = n_embd;
-        e.out         = b_out;
-        RAD_ARCH_TRY(rad_declare_encoder(b, &e));
-        rad_note(b, "vision tower: %lld layers of %lld (%lld heads x %lld), ff %lld, patch %lld, "
-                    "pooled %lldx%lld; %lld patches a pass -> %lld rows of %lld",
-                 (long long)depth, (long long)width, (long long)heads, (long long)hd, (long long)ff,
-                 (long long)patch, (long long)pool, (long long)pool, (long long)P, (long long)R,
-                 (long long)n_embd);
-        on = true;
-        return RAD_OK;
-    }
-
-    void step(RadCtx* c, const RadBatch* batch) const {
-        const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg, kk = pool * pool;
-        if (!on || Pn <= 0 || Pn > P || Pn % kk || S <= 0) {
-            rad_step_fail(c, "an encoder pass this program's vision tower cannot serve: no tower, "
-                             "more patches than it was declared for, or not whole pooling windows");
-            return;
-        }
-        const int64_t Rn = Pn / kk;
-        const int32_t* crd = batch->enc_coord;
-        const RadOperand pix = praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim);
-        const RadOperand rc  = praw2(crd, RAD_I32, 2, Pn);
-        const RadOperand cu  = praw(batch->enc_cu, RAD_I32, S + 1);
-
-        RAD_ISSUE_N(c, op_patch, Pn, pix, RAD_W(w_in), brows(b_x, Pn));
-        RAD_ISSUE_N(c, op_px, Pn, praw(crd + Pn, RAD_I32, Pn), RAD_W(w_px), brows(b_px, Pn));
-        RAD_ISSUE_N(c, op_py, Pn, praw(crd, RAD_I32, Pn), RAD_W(w_py), brows(b_py, Pn));
-        RAD_ISSUE_N(c, op_padd, Pn, brows(b_px, Pn), brows(b_py, Pn), brows(b_px, Pn));
-        RAD_ISSUE_N(c, op_add, Pn, brows(b_x, Pn), brows(b_px, Pn), brows(b_x, Pn));
-        for (const Layer& l : L) {
-            RAD_ISSUE_N(c, l.op_in, Pn, brows(b_x, Pn), RAD_W(l.in_norm), brows(b_h, Pn));
-            RAD_ISSUE_N(c, l.op_qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv), brows(b_qkv, Pn));
-            RAD_ISSUE_N(c, l.op_qk, Pn, brows(b_qkv, Pn), rc, RAD_W(l.q_norm), RAD_W(l.k_norm));
-            RAD_ISSUE_N(c, l.op_attn, Pn, bcol(b_qkv, 0, width, Pn), bcol(b_qkv, width, width, Pn),
-                        bcol(b_qkv, 2 * width, width, Pn), cu, brows(b_att, Pn));
-            RAD_ISSUE_N(c, l.op_o, Pn, brows(b_att, Pn), RAD_W(l.o), brows(b_o, Pn));
-            RAD_ISSUE_N(c, l.op_pa, Pn, brows(b_o, Pn), RAD_W(l.post_attn), brows(b_o, Pn));
-            RAD_ISSUE_N(c, l.op_add1, Pn, brows(b_x, Pn), brows(b_o, Pn), brows(b_x, Pn));
-            RAD_ISSUE_N(c, l.op_pf, Pn, brows(b_x, Pn), RAD_W(l.pre_ff), brows(b_h, Pn));
-            RAD_ISSUE_N(c, l.op_gu, Pn, brows(b_h, Pn), RAD_W(l.gate_up), brows(b_gu, Pn));
-            RAD_ISSUE_N(c, l.op_act, Pn, bcol(b_gu, 0, ff, Pn), bcol(b_gu, ff, ff, Pn),
-                        brows(b_ff, Pn));
-            RAD_ISSUE_N(c, l.op_down, Pn, brows(b_ff, Pn), RAD_W(l.down), brows(b_o, Pn));
-            RAD_ISSUE_N(c, l.op_pff, Pn, brows(b_o, Pn), RAD_W(l.post_ff), brows(b_o, Pn));
-            RAD_ISSUE_N(c, l.op_add2, Pn, brows(b_x, Pn), brows(b_o, Pn), brows(b_x, Pn));
-        }
-        RAD_ISSUE_N(c, op_pool, Pn, brows(b_x, Pn), brows(b_pool, Rn));
-        RAD_ISSUE_N(c, op_norm, Rn, brows(b_pool, Rn), RAD_NONE, brows(b_pn, Rn));
-        RAD_ISSUE_N(c, op_out, Rn, brows(b_pn, Rn), RAD_W(w_proj), brows(b_out, Rn));
-    }
-};
-
 /* ============================== THE AUDIO ENCODER (Gemma 4's USM conformer) ==============================
  *
  *   a frame is 128 log-mel bins (the processor's), four frames an output row
@@ -355,12 +74,12 @@ struct Vision {
  *   12 conformer blocks: a feed-forward at half weight, local attention (11 frames back, a
  *   relative-position term, a softplus per-dimension query scale, a softcap of 50), a gated
  *   depthwise causal convolution, a second half-weight feed-forward, a norm; their linears are
- *   CLIPPED, input and output clamped to bounds the checkpoint stores
+ *   clipped: input and output clamped to bounds the checkpoint stores
  *   1024 -> 1536 with a bias, then the multimodal embedder: an RMS norm with no gain, 1536 -> 512.
  *
- * The blocks' clamps at +-1e10 ("gradient clipping") are left out: they bound activations ten
- * orders of magnitude past anything bf16 holds near them, so they change nothing a pass computes.
- * One clip is one segment; a pass carries up to RadBuildCtx::max_audio_frames frames. */
+ * The blocks' clamps at +-1e10 ("gradient clipping") are omitted: they are ten orders of magnitude
+ * beyond the activations' range and change nothing. One clip is one segment; a pass carries up to
+ * RadBuildCtx::max_audio_frames frames. */
 struct Audio {
     /* A clipped linear: the weight and its four bounds. */
     struct Clip {
@@ -607,9 +326,8 @@ struct Audio {
                           RAD_WEIGHTS(wt));
         };
         /* A clipped linear over rows of `in` into `out`: the input clamp writes a copy (the input
-         * is shared by the projections it feeds, each with its own bounds), the output clamp is in
-         * place. The copy is a whole [R, n_in] buffer: a GEMM's input must be contiguous, and a
-         * column slice of a wider one is not. */
+         * feeds several projections, each with its own bounds), the output clamp is in place. The
+         * copy is a whole [R, n_in] buffer, since a GEMM's input must be contiguous. */
         auto clipped = [&](Clip& c, int64_t n_out, int64_t n_in, rad_buf in, rad_buf tmp,
                            rad_buf out) {
             c.op_in  = rw(b, clamp(R, n_in, c.in_lo, c.in_hi), {in}, {tmp});
@@ -790,25 +508,15 @@ struct Model {
     rad_op op_mm = 0;           /* the media rows over their placeholders' embeddings */
 
     std::vector layers;
-    Vision vis;
+    Gemma4Vision vis;
     Audio aud;
 };
 
 static Model g_model[MAX_RANKS];
 
-/* A value as a bf16 tensor holds it: round to nearest even on the top 16 bits of the f32. */
-static double bf16_round(double v) {
-    float f = (float)v;
-    uint32_t u;
-    std::memcpy(&u, &f, 4);
-    u = (u + 0x7FFFu + ((u >> 16) & 1u)) & 0xFFFF0000u;
-    std::memcpy(&f, &u, 4);
-    return (double)f;
-}
-
-/* The layer schedule, read and not derived: layer_types is the checkpoint's statement of which
- * layers attend to the whole input, and a pattern assumed from the model card would build a model
- * that runs and pools the wrong function if a sibling checkpoint moved one. */
+/* The layer schedule, read rather than derived: layer_types states which layers attend to the
+ * whole input, and an assumed pattern would silently be wrong for a sibling checkpoint that
+ * differs. */
 static int read_schedule(const RadModelMeta* meta, int64_t n_layer, std::vector* full) {
     const char* s = rad_meta_gets(meta, "layer_types", nullptr);
     if (!s || !*s) {
@@ -842,8 +550,8 @@ static int read_schedule(const RadModelMeta* meta, int64_t n_layer, std::vector<
 static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
     if (!b || !meta || !ctx) return RAD_E_INVAL;
     if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
-    /* A 270M encoder is a fraction of one card; splitting it would cost an all-reduce a layer to
-     * save nothing, so it is not offered. */
+    /* A 270M encoder fits easily on one card; tensor parallelism would only add an all-reduce per
+     * layer, so it is not offered. */
     if (ctx->world_size > 1) {
         fprintf(stderr, "radiance: embgemma2 runs on one card (--tp 1); the text model is 270M "
                         "parameters\n");
@@ -862,14 +570,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     RAD_ARCH_TRY(read_schedule(meta, g.n_layer, &full));
 
     /* The two attention kinds. The sliding one is the config's top-level geometry; the full one
-     * overrides head width and KV heads per layer (per_layer_config), and every full layer of
-     * this checkpoint states the same override -- checked below, layer by layer. */
+     * overrides head width and KV heads per layer (per_layer_config), and every full layer must
+     * state the same override (checked below). */
     m.ks.head_dim  = g.head_dim;
     m.ks.n_head    = g.n_head;
     m.ks.n_head_kv = g.n_head_kv;
     m.ks.theta     = rad_meta_getf(meta, "rope_parameters.sliding_attention.rope_theta", 0.0);
-    /* A RADIUS in the reference (|i - j| <= sliding_window), and attn_dense's window is the
-     * strict bound, so one more. */
+    /* The reference's window is a radius (|i - j| <= sliding_window) and attn_dense's is a strict
+     * bound, so one more. */
     const int64_t radius = meta_int2(meta, "", "sliding_window", 0);
     m.ks.window = radius + 1;
     m.kf.n_head = g.n_head;
@@ -901,12 +609,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
         return RAD_E_INVAL;
     }
     const int64_t P = m.n_ple * g.n_layer;
-    /* ONE INPUT IS AT MOST ONE STEP (Request::embed), so the longest attention segment is the
+    /* One input is at most one step (Request::embed), so the longest attention segment is the
      * step's token budget. */
     const int64_t max_seg = T;
 
-    /* ---- activations. ple holds every layer's per-layer input for the whole step, read a
-     * column slice a layer. */
+    /* ---- activations. ple holds every layer's per-layer input for the whole step, read as one
+     * column slice per layer. */
     m.b_x     = decl_b(b, nm.f("x"),       RAD_BF16, {T, E});
     m.b_h     = decl_b(b, nm.f("h"),       RAD_BF16, {T, E});
     m.b_o     = decl_b(b, nm.f("o"),       RAD_BF16, {T, E});
@@ -923,9 +631,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     m.b_pooled= decl_b(b, nm.f("pooled"),  RAD_F32,  {g.max_seqs, m.n_out}, RAD_BUF_PERSIST);
     RAD_ARCH_TRY(rad_declare_pooled(b, m.b_pooled));
 
-    /* ---- the model-level weights. Every one at the checkpoint's own bf16, the norm gains
-     * included: the reference widens a gain to f32 at use, which is exact, so storing it wider
-     * buys nothing and costs reading it in place on the host backend. */
+    /* ---- the model-level weights, all at the checkpoint's bf16, norm gains included: the
+     * reference widens a gain to f32 at use, which is exact, and a wider stored copy could not be
+     * read in place on the host backend. */
     const char* L = "language_model";
     RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("%s.embed_tokens.weight", L)));
     RAD_ARCH_TRY(map_copy(b, nm.f("ple_proj.weight"),
@@ -974,23 +682,22 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                       RAD_NOWEIGHTS);
     };
 
-    /* The embedding, scaled by sqrt(hidden) AS THE REFERENCE ROUNDS IT: the scale is a bf16
-     * buffer, so sqrt(512) = 22.6274 multiplies as 22.625. */
-    const double escale = bf16_round(std::sqrt((double)E));
+    /* The embedding, scaled by sqrt(hidden) rounded as the reference rounds it (a bf16 buffer):
+     * sqrt(512) = 22.6274 multiplies as 22.625. */
+    const double escale = rad_bf16_to_f32(rad_f32_to_bf16((float)std::sqrt((double)E)));
     m.op_embed = rw(b, RAD_OP(b, "embed_lookup",
                         RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", E),
                                    RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
                                    RAD_INT("vocab_offset", 0), RAD_F64("mult", escale)),
                         RAD_WEIGHTS(m.w_tok)),
                     {}, {m.b_x});
-    /* THE PER-LAYER INPUTS: the embedding projected to n_layer x n_ple and RMS-normed per layer.
-     * The reference scales the projection by hidden^-0.5 before the norm; an RMS norm of s*x with
-     * eps is exactly the norm of x with eps / s^2, which is what this declares, so the scale is
-     * applied without the extra bf16 rounding of s*x the reference pays. */
-    /* A media part's rows over its placeholders' embeddings, before anything reads them: the
-     * per-layer inputs are projected from what the model embeds, and for an image token that is
-     * its image row (declared only when a tower is). */
-    if ((Vision::present(meta) && ctx->max_enc_patches > 0) ||
+    /* The per-layer inputs: the embedding projected to n_layer x n_ple and RMS-normed per layer.
+     * The reference scales the projection by hidden^-0.5 before the norm; the RMS norm of s*x with
+     * eps equals the norm of x with eps / s^2, which is what is declared, avoiding the bf16
+     * rounding of s*x. */
+    /* A media part's rows overwrite its placeholders' embeddings before anything reads them, so an
+     * image token's per-layer inputs come from its image row (declared only with a tower). */
+    if ((Gemma4Vision::present(meta) && ctx->max_enc_patches > 0) ||
         (Audio::present(meta) && ctx->max_audio_frames > 0))
         m.op_mm = rw(b, RAD_OP(b, "scatter_rows",
                                RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
@@ -1106,7 +813,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                              RAD_NOWEIGHTS),
                    {m.b_proj}, {m.b_pooled});
 
-    RAD_ARCH_TRY(m.vis.declare(b, meta, ctx, nm, E, (int)g.n_layer));
+    RAD_ARCH_TRY(m.vis.declare(b, meta, ctx, nm, E, (int)g.n_layer, "", "embgemma2"));
     RAD_ARCH_TRY(m.aud.declare(b, meta, ctx, nm, E,
                                (int)g.n_layer + (int)m.vis.L.size()));
 
@@ -1123,11 +830,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     return RAD_OK;
 }
 
-/* Before declare: the vision tower's pooling window, so a pass size the core picks itself is a
- * whole number of them. */
+/* Before declare: the vision tower's pooling window, so a pass size the core picks is a whole
+ * number of windows. */
 static int probe(const RadModelMeta* meta, RadArchProbe* out) {
     if (!meta || !out) return RAD_E_INVAL;
-    if (Vision::present(meta)) {
+    if (Gemma4Vision::present(meta)) {
         const int64_t k = rad_meta_geti(meta, "vision_config.pooling_kernel_size", 0);
         if (k > 0) out->enc_merge = k * k;
     }
diff --git a/arch/gemma4/CMakeLists.txt b/arch/gemma4/CMakeLists.txt
index 54e911f6..fb0874d5 100644
--- a/arch/gemma4/CMakeLists.txt
+++ b/arch/gemma4/CMakeLists.txt
@@ -1,8 +1,8 @@
-# gemma4 -- the architecture plugin for Gemma 4's text model (Gemma4ForConditionalGeneration /
-# Gemma4ForCausalLM; the 26B-A4B MoE and the dense sizes without per-layer embeddings), with a
+# gemma4 -- architecture plugin for Gemma 4's text model (Gemma4ForConditionalGeneration /
+# Gemma4ForCausalLM: the 26B-A4B MoE and the dense sizes without per-layer embeddings), with a
 # z-lab DFlash drafter merged at convert time.
 #
-# Built inside radiance's tree (arch/ discovers it) or on its own against an installed radiance:
+# Built in radiance's tree (arch/ discovers it) or standalone against an installed radiance:
 #   cmake -S arch/gemma4 -B build-gemma4 -DCMAKE_PREFIX_PATH=/opt/radiance && cmake --build build-gemma4
 if(NOT COMMAND rad_add_plugin)
   cmake_minimum_required(VERSION 3.21)
diff --git a/arch/gemma4/gemma4.cpp b/arch/gemma4/gemma4.cpp
index dfd173da..f6d56cef 100644
--- a/arch/gemma4/gemma4.cpp
+++ b/arch/gemma4/gemma4.cpp
@@ -7,13 +7,13 @@
  *   30 layers, hidden 2816, vocab 262144 (tied to the embedding), rms_norm_eps 1e-6
  *   layer_types: five `sliding_attention` then one `full_attention`, five times over
  *     sliding: 16 heads / 8 KV heads x 256, rope theta 1e4 over the whole head, window 1024
- *     full:    16 heads / 2 KV heads x 512, PROPORTIONAL rope theta 1e6 over a quarter of it,
- *              and K IS V (`attention_k_eq_v`): there is no v_proj, V is the k projection before
+ *     full:    16 heads / 2 KV heads x 512, proportional rope theta 1e6 over a quarter of it,
+ *              and K is V (`attention_k_eq_v`): there is no v_proj, V is the k projection before
  *              its norm and its rotary
  *   attention scale 1.0 -- the q/k norms carry the temperature; q and k RMS-normed per head with a
  *   gain, v with none
  *   Gemma's sandwich norms, plain gains (x_hat * w, not 1 + w)
- *   the feed-forward is TWO ARMS BESIDE EACH OTHER, both reading the same residual:
+ *   the feed-forward is two parallel arms, both reading the same residual:
  *     dense    pre_feedforward_layernorm -> gate|up 2112 (gelu-tanh) -> down
  *              -> post_feedforward_layernorm_1
  *     routed   router over rmsnorm(x) * scale * hidden^-0.5 -> softmax -> top 8 of 128 ->
@@ -22,54 +22,53 @@
  *              post_feedforward_layernorm_2
  *     sum -> post_feedforward_layernorm -> residual add
  *   layer_scalar multiplies the residual stream at the end of every layer
- *   embedding scaled by sqrt(hidden) AS A bf16 (53.0, not 53.066); final norm; tied lm_head;
+ *   embedding scaled by sqrt(hidden) rounded to bf16 (53.0, not 53.066); final norm; tied lm_head;
  *   final_logit_softcapping 30
  *
  * The reference is transformers' modeling_gemma4 (Gemma4TextDecoderLayer, Gemma4TextAttention,
  * Gemma4TextRouter, _compute_proportional_rope_parameters), read at 5.19.
  *
- * ============================== THE READINGS THAT STAY PLAUSIBLE WHEN WRONG ==============================
+ * ============================== EASY TO GET SUBTLY WRONG ==============================
  *
- *   PROPORTIONAL ROPE IS NOT A PARTIAL ROTARY. It rotates the first 64 frequency PAIRS of a
- *   512-wide head at theta^(-2j/512) -- the exponent divides by the HEAD, and pair j is channels
- *   (j, j + 256) -- and leaves the other 192 pairs at frequency zero. `rope` with rotary_dim 128
- *   would pair (j, j + 64) at theta^(-2j/128), which is a different function that still produces
- *   fluent text. It is declared here as a full-width NeoX rotary whose frequencies past pair 63
- *   are divided by 1e30 -- the YaRN blend `rope` already carries, with the ramp a step at 63.5..64
- *   -- which evaluates to exactly the reference's angles below the step and to cos 1, sin ~1e-31
- *   above it. See decl_full_rope().
+ *   Proportional rope is not a partial rotary. It rotates the first 64 frequency pairs of a
+ *   512-wide head at theta^(-2j/512) (the exponent divides by the head width, and pair j is
+ *   channels (j, j + 256)) and leaves the other 192 pairs at frequency zero. `rope` with
+ *   rotary_dim 128 would pair (j, j + 64) at theta^(-2j/128), a different function that still
+ *   produces fluent text. It is declared as a full-width NeoX rotary whose frequencies past pair
+ *   63 are divided by 1e30 (the YaRN blend `rope` already has, with the ramp a step at 63.5..64),
+ *   which gives exactly the reference's angles below the step and cos 1, sin ~1e-31 above it. See
+ *   decl_full_rope().
  *
- *   V ON A FULL LAYER IS THE UN-NORMED, UN-ROTATED K PROJECTION, RMS-normed with a unit gain. So
- *   the value norm reads `k` BEFORE the key norm writes it, which is the issue order below.
+ *   V on a full layer is the un-normed, un-rotated k projection, RMS-normed with a unit gain, so
+ *   the value norm must read `k` before the key norm writes it (the issue order below).
  *
- *   THE ROUTER DOES NOT READ THE FEED-FORWARD'S INPUT. It reads the residual stream through a
- *   GAINLESS norm, times its own `scale` vector, times hidden^-0.5 -- one `rmsnorm` with `scale`
- *   as the gain and `mult` the constant -- while the experts read pre_feedforward_layernorm_2's
- *   output and the dense arm pre_feedforward_layernorm's.
+ *   The router does not read the feed-forward's input. It reads the residual stream through a
+ *   gainless norm, times its own `scale` vector, times hidden^-0.5 (one `rmsnorm` with `scale` as
+ *   the gain and `mult` the constant), while the experts read pre_feedforward_layernorm_2's output
+ *   and the dense arm pre_feedforward_layernorm's.
  *
- *   per_expert_scale MULTIPLIES THE RENORMALISED WEIGHT, after the top-k. It is gathered by expert
+ *   per_expert_scale multiplies the renormalised weight, after the top-k. It is gathered by expert
  *   id with `embed_lookup` (a 128 x 1 table) and multiplied in with `mul`.
  *
- *   THE TWO POST-NORMS OF THE ARMS ARE PER ARM, so under tensor parallel each arm's partial sum is
- *   reduced BEFORE its norm. The two partials sit in one [2T, n_embd] buffer -- dense rows first,
- *   routed rows after -- so one all-reduce carries both.
+ *   The arms' post-norms are per arm, so under tensor parallel each arm's partial sum is reduced
+ *   before its norm. The two partials share one [2T, n_embd] buffer (dense rows first, routed
+ *   after), so one all-reduce carries both.
  *
  * ============================== TENSOR PARALLEL ==============================
  *
  * Heads split by rank, o and down by column with an all-reduce, the vocabulary by row. The full
- * layers' two KV heads are REPLICATED past two ranks -- at four, ranks {0,1} hold KV head 0 and
- * {2,3} KV head 1, each reading its head's row span of k_proj -- the scheme rad_arch.h's geom_from
- * describes. Routed experts are EXPERT-PARALLEL (whole experts, 128/world a rank): a 704-wide
- * expert is 5.5 fp8 blocks and has no block-aligned width split. The router is replicated, so
- * every rank agrees on the routing without a collective and the arm's all-reduce sums the ranks'
- * experts.
+ * layers' two KV heads are replicated past two ranks: at four, ranks {0,1} hold KV head 0 and
+ * {2,3} KV head 1, each reading its head's row span of k_proj (rad_arch.h, geom_from). Routed
+ * experts are expert-parallel (whole experts, 128/world per rank), since a 704-wide expert is 5.5
+ * fp8 blocks and has no block-aligned width split. The router is replicated, so every rank agrees
+ * on the routing without a collective, and the arm's all-reduce sums the ranks' experts.
  *
  * ============================== FP8 EXPERTS ==============================
  *
- * The experts are ~90% of the weight bytes and the decode step reads whichever were routed, so
- * their width is the step's bandwidth. Each projection is served as the container holds it --
- * bf16 by `moe_gemm`, block fp8 (the recipe's `rtn codes=fp8_e4m3 block=128x128 scale=bf16`) by
- * `moe_gemm_q` at fp8a8 over an E4M3 input -- per layer and per projection (expert_format):
+ * The experts are ~90% of the weight bytes and decode reads whichever were routed, so their width
+ * sets the step's bandwidth. Each projection is served as the container holds it, per layer and
+ * per projection (expert_format): bf16 by `moe_gemm`, block fp8 (the recipe's `rtn
+ * codes=fp8_e4m3 block=128x128 scale=bf16`) by `moe_gemm_q` at fp8a8 over an E4M3 input:
  *
  *   gate_up  [2 * 704, 2816]: 1408 rows are whole 64-row tiles and eleven 128-row scale blocks
  *            (one straddles gate and up, which only shares a scale); K is 22 blocks. fp8 at the
@@ -80,13 +79,13 @@
  *            padded columns, which meet zero columns of down, so the function is unchanged, and
  *            then both projections are fp8 (data/recipes/gemma4-26b-a4b-df-pad768.recipe).
  *
- * ============================== WHAT THIS PLUGIN DOES NOT YET DECLARE ==============================
+ * ============================== NOT DECLARED ==============================
  *
- *   the vision tower (Gemma 4's, which arch/embgemma2 already declares for an encoder) -- this
- *   serves text; a container that carries a tower is served with --mm-max-patches 0 and the
- *   server refuses a media part by name;
- *   an fp8 attention or dense arm -- under a tenth of the weight bytes, and the dense arm's 2112
- *   is not whole 128-blocks either.
+ *   the vision tower (arch/embgemma2 declares Gemma 4's for an encoder): this plugin serves text;
+ *   a container carrying a tower is served with --mm-max-patches 0 and media parts are refused by
+ *   name;
+ *   an fp8 attention or dense arm: under a tenth of the weight bytes, and the dense arm's 2112 is
+ *   not whole 128-blocks.
  */
 #include 
 #include 
@@ -105,102 +104,32 @@ namespace gemma4 {
 
 using namespace rad::arch;
 
-/* The fused router's two bounds, as rad_block_moe_fp8.h states them: the most routing slots
- * libr4d's sort serves in one workgroup (its kScatterSmall), and the skinny bf16 GEMM's decode
- * band, where the fused op's GEMM is that GEMM's own arithmetic. */
+/* The fused router's two bounds (rad_block_moe_fp8.h): the most routing slots libr4d's sort
+ * serves in one workgroup (kScatterSmall), and the skinny bf16 GEMM's decode band, within which the
+ * fused op's GEMM matches that GEMM's arithmetic. */
 static const int64_t kMoeSortRows = 1024;
 static const int64_t kMoeRouterFusedRows = 64;
 
 /* ============================================================== metadata */
 /* Gemma4ForConditionalGeneration nests the text model's config under `text_config`; a
- * Gemma4ForCausalLM checkpoint does not. rad-convert flattens nested keys with dots, so every key
- * is asked for in both spellings, text_config's first. */
-static long long tc_geti(const RadModelMeta* m, const char* k, long long dflt) {
-    const long long sentinel = -0x7FFFFFFFll;
-    char key[160];
-    std::snprintf(key, sizeof key, "text_config.%s", k);
-    long long v = rad_meta_geti(m, key, sentinel);
-    if (v == sentinel) v = rad_meta_geti(m, k, sentinel);
-    return v == sentinel ? dflt : v;
-}
-static double tc_getf(const RadModelMeta* m, const char* k, double dflt) {
-    char key[160];
-    std::snprintf(key, sizeof key, "text_config.%s", k);
-    if (rad_meta_gets(m, key, nullptr)) return rad_meta_getf(m, key, dflt);
-    return rad_meta_getf(m, k, dflt);
-}
-static const char* tc_gets(const RadModelMeta* m, const char* k, const char* dflt) {
-    char key[160];
-    std::snprintf(key, sizeof key, "text_config.%s", k);
-    const char* v = rad_meta_gets(m, key, nullptr);
-    return v ? v : rad_meta_gets(m, k, dflt);
-}
+ * Gemma4ForCausalLM checkpoint does not, so keys are read with meta_text_get*. */
 /* A JSON boolean reaches the meta as 1/0 or as true/false, depending on the converter's path. */
 static bool tc_getb(const RadModelMeta* m, const char* k, bool dflt) {
-    const char* s = tc_gets(m, k, nullptr);
+    const char* s = meta_text_gets(m, k, nullptr);
     if (!s) return dflt;
     if (!std::strcmp(s, "true") || !std::strcmp(s, "True")) return true;
     if (!std::strcmp(s, "false") || !std::strcmp(s, "False") || !std::strcmp(s, "null")) return false;
     return std::atoll(s) != 0;
 }
 
-/* A value as a bf16 tensor holds it: round to nearest even on the top 16 bits of the f32. The
- * reference's embedding scale is a bf16 buffer, so sqrt(2816) = 53.066 multiplies as 53.0. */
-static double bf16_round(double v) {
-    float f = (float)v;
-    uint32_t u;
-    std::memcpy(&u, &f, 4);
-    u = (u + 0x7FFFu + ((u >> 16) & 1u)) & 0xFFFF0000u;
-    std::memcpy(&f, &u, 4);
-    return (double)f;
-}
-
-/* "1 6 11 17 22 27" -> the trunk layers whose output the drafter reads. Out-of-range entries are
- * dropped (llama_fp8.cpp says why). */
-static int parse_ids(const char* s, int64_t n, int* out, int max) {
-    if (!s) return 0;
-    int k = 0;
-    for (const char* p = s; *p && k < max;) {
-        while (*p == ' ' || *p == ',' || *p == '[' || *p == ']') ++p;
-        if (!*p) break;
-        char* e = nullptr;
-        const long v = std::strtol(p, &e, 10);
-        if (e == p) break;
-        p = e;
-        if (v >= 0 && v < n) out[k++] = (int)v;
-    }
-    return k;
-}
-
-/* "sliding_attention full_attention ..." -> 1 for each full layer. */
-static int parse_types(const char* s, std::vector* full) {
-    full->clear();
-    if (!s) return RAD_E_INVAL;
-    for (const char* p = s; *p;) {
-        while (*p == ' ' || *p == ',' || *p == '[' || *p == ']' || *p == '"') ++p;
-        if (!*p) break;
-        const char* t = p;
-        while (*p && *p != ' ' && *p != ',' && *p != ']' && *p != '"') ++p;
-        const size_t len = (size_t)(p - t);
-        if (len == 14 && !std::strncmp(t, "full_attention", 14))         full->push_back(1);
-        else if (len == 17 && !std::strncmp(t, "sliding_attention", 17)) full->push_back(0);
-        else {
-            fprintf(stderr, "radiance: gemma4: layer_types names '%.*s'; this plugin knows "
-                            "full_attention and sliding_attention\n", (int)len, t);
-            return RAD_E_UNSUPPORTED;
-        }
-    }
-    return RAD_OK;
-}
-
 /* ============================================================== the model */
 
 /* One attention kind: the sliding and the full layers differ in head width, KV heads, rotary
  * and window, and in whether V has a projection of its own. */
 struct Kind {
     int64_t hd = 0;          /* head_dim */
-    int64_t nh = 0;          /* query heads, THIS rank */
-    int64_t nkv = 0;         /* KV heads, THIS rank */
+    int64_t nh = 0;          /* query heads, this rank */
+    int64_t nkv = 0;         /* KV heads, this rank */
     int64_t nkv_all = 0;
     bool    kv_repl = false; /* KV heads replicated across ranks (world > nkv_all) */
     int64_t kv_off = 0;      /* this rank's first KV row in the unsharded k/v projection */
@@ -223,10 +152,10 @@ struct Layer {
     /* dense arm */
     rad_weight w_fnorm = 0, w_gu = 0, w_dn = 0, w_fpost1 = 0;
     rad_op op_fnorm = 0, op_gu = 0, op_act = 0, op_dn = 0;
-    /* routed arm. Each projection's experts are plain bf16 or block fp8, whichever the container
-     * holds (expert_format). A bf16 projection's handles are its experts in order, one table; an
-     * fp8 one's are the EVEN local experts then the ODD ones, codes in w_egu/w_edn and the scale
-     * views in w_egus/w_edns, so each parity is one run (see declare). */
+    /* routed arm. Each projection's experts are plain bf16 or block fp8, as the container holds
+     * (expert_format). A bf16 projection's handles are its experts in order, one table; an fp8
+     * one's are the even local experts then the odd ones, codes in w_egu/w_edn and scale views in
+     * w_egus/w_edns, so each parity is one run (see declare). */
     rad_weight w_rscale = 0, w_router = 0, w_escale = 0, w_enorm = 0, w_fpost2 = 0;
     std::vector w_egu, w_edn, w_egus, w_edns;
     bool gu_fp8 = false, dn_fp8 = false;
@@ -244,17 +173,17 @@ struct Layer {
     rad_weight w_fpost = 0, w_scalar = 0;
     rad_op op_ar_f = 0, op_fpost1 = 0, op_fpost2 = 0, op_fsum = 0, op_fpost = 0, op_add_f = 0;
     rad_op op_scale = 0;
-    /* THE SANDWICH JOINS, FUSED: op_join_a is apost + add_a + fnorm, op_join_f the
-     * routed layer's fpost1 + fpost2 + fsum + fpost + add_f + scale. Zero where not served, and
-     * then the chain above is declared and issued instead. */
+    /* The sandwich joins, fused: op_join_a is apost + add_a + fnorm, op_join_f the routed layer's
+     * fpost1 + fpost2 + fsum + fpost + add_f + scale. Zero where not served; the chain above is
+     * then declared and issued instead. */
     rad_op op_join_a = 0, op_join_f = 0;
     /* op_join_r: op_join_a writing the routed arm's two inputs as well -- the router's norm into
      * b_rn and the experts' fp8 codes into b_hq / b_hqs (norm_add_norm_route) -- where the
      * layer's gate_up is block fp8. op_rnorm and op_enorm are then declared and not issued. */
     rad_op op_join_r = 0;
-    /* op_join_f also writes the NEXT norm -- the following layer's input norm, or the final norm
-     * after the last layer -- into `h`, with that norm's gain `w_next`; the norm it replaces is
-     * then neither declared nor issued. */
+    /* op_join_f also writes the next norm (the following layer's input norm, or the final norm
+     * after the last layer) into `h`, with that norm's gain `w_next`; the replaced norm is then
+     * neither declared nor issued. */
     bool next_norm = false;
     rad_weight w_next = 0;
     /* the drafter's tap, on a layer the drafter reads (see declare) */
@@ -266,7 +195,7 @@ struct Model {
     Geom    g{};             /* the sliding kind's geometry, and everything model-wide */
     Kind    ks{}, kf{};      /* sliding, full */
     int64_t n_layer = 0, E = 0;
-    int64_t n_ff = 0;        /* dense arm, THIS rank */
+    int64_t n_ff = 0;        /* dense arm, this rank */
     bool    moe = false;
     int64_t n_expert = 0, n_local = 0, expert_base = 0, top_k = 0, n_ffe = 0;
     int64_t moe_rows = 0;    /* tokens a routed pass */
@@ -329,9 +258,9 @@ static int split_heads(Kind& k, int64_t nh_all, int world, int rank, const char*
         k.kv_repl = false;
         k.kv_off = rank * k.nkv * k.hd;
     } else {
-        /* REPLICATED: ranks [i*r, (i+1)*r) share KV head i, r = world / nkv_all. A rank's query
-         * heads [rank*nh, (rank+1)*nh) all belong to that head because gqa = nh_all / nkv_all is a
-         * multiple of nh exactly when world is a multiple of nkv_all -- which is checked. */
+        /* Replicated: ranks [i*r, (i+1)*r) share KV head i, r = world / nkv_all. A rank's query
+         * heads [rank*nh, (rank+1)*nh) all belong to that head, because gqa = nh_all / nkv_all is a
+         * multiple of nh exactly when world is a multiple of nkv_all, which is checked. */
         if (world % k.nkv_all) {
             fprintf(stderr, "radiance: gemma4: %d ranks cannot replicate %lld %s KV heads; the "
                             "world must be a multiple of the KV head count\n", world,
@@ -345,8 +274,8 @@ static int split_heads(Kind& k, int64_t nh_all, int world, int rank, const char*
     return RAD_OK;
 }
 
-/* THE FULL LAYERS' ROTARY (see the header). `rope` rotates n_head + n_head_kv heads of its operand,
- * so a q-only tensor is n_head = nh, n_head_kv = 0 and a k-only one n_head = nkv. */
+/* The full layers' rotary (see the file header). `rope` rotates n_head + n_head_kv heads of its
+ * operand, so a q-only tensor is n_head = nh, n_head_kv = 0 and a k-only one n_head = nkv. */
 static rad_op decl_full_rope(RadBuilder* b, const Kind& k, int64_t rows, int64_t heads) {
     const int64_t half = k.hd / 2;
     if (k.rot_pairs >= half)
@@ -375,42 +304,14 @@ static rad_op decl_full_rope(RadBuilder* b, const Kind& k, int64_t rows, int64_t
 static int declare_dflash(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx,
                           Model& m, int base_layer) {
     Names& nm = m.nm;
-    Geom   dg = m.g;
-    dg.n_layer       = rad_meta_geti(meta, "draft.num_hidden_layers", 0);
-    dg.head_dim      = rad_meta_geti(meta, "draft.head_dim", 0);
-    dg.n_head_all    = rad_meta_geti(meta, "draft.num_attention_heads", 0);
-    dg.n_head_kv_all = rad_meta_geti(meta, "draft.num_key_value_heads", 0);
-    dg.n_ff_all      = rad_meta_geti(meta, "draft.intermediate_size", 0);
-    dg.eps           = (float)rad_meta_getf(meta, "draft.rms_norm_eps", 0.0);
-    dg.theta         = (float)rad_meta_getf(meta, "draft.rope_parameters.rope_theta",
-                                            rad_meta_getf(meta, "draft.rope_theta", 0.0));
-    dg.wadd = dg.wadd_qk = 0.0f;
-    if (dg.n_layer <= 0 || dg.head_dim <= 0 || dg.n_head_all <= 0 || dg.n_head_kv_all <= 0 ||
-        dg.n_ff_all <= 0 || !(dg.eps > 0.0f) || !(dg.theta > 0.0f)) {
-        fprintf(stderr, "radiance: gemma4: the container's `draft.` config does not describe a "
-                        "DFlash drafter: layers %lld, heads %lld / kv %lld, head_dim %lld, ffn "
-                        "%lld, rms_eps %g, rope_theta %g\n",
-                (long long)dg.n_layer, (long long)dg.n_head_all, (long long)dg.n_head_kv_all,
-                (long long)dg.head_dim, (long long)dg.n_ff_all, (double)dg.eps, (double)dg.theta);
-        return RAD_E_INVAL;
-    }
+    Geom   dg{};
+    RAD_ARCH_TRY(drafter_geom(dg, m.g, meta, "gemma4 DFlash"));
     if (rad_meta_geti(meta, "draft.hidden_size", dg.n_embd) != dg.n_embd) {
         fprintf(stderr, "radiance: gemma4: the drafter is %lld wide and the target %lld; it reads "
                         "the target's embedding and head, so it is not this target's drafter\n",
                 (long long)rad_meta_geti(meta, "draft.hidden_size", 0), (long long)dg.n_embd);
         return RAD_E_UNSUPPORTED;
     }
-    RAD_ARCH_TRY(yarn_from(dg, meta, "draft.", dg.head_dim));
-    int s;
-    if ((s = divide_or_fail(dg.n_head_all,    dg.world, "draft num_attention_heads", &dg.n_head))    < 0) return s;
-    if ((s = divide_or_fail(dg.n_head_kv_all, dg.world, "draft num_key_value_heads", &dg.n_head_kv)) < 0) return s;
-    if ((s = divide_or_fail(dg.n_ff_all,      dg.world, "draft intermediate_size",   &dg.n_ff))      < 0) return s;
-    const long long dvocab = rad_meta_geti(meta, "draft.vocab_size", dg.n_vocab_all);
-    if (dvocab != dg.n_vocab_all) {
-        fprintf(stderr, "radiance: gemma4: the drafter claims a %lld-token vocabulary and the "
-                        "target has %lld\n", dvocab, (long long)dg.n_vocab_all);
-        return RAD_E_UNSUPPORTED;
-    }
 
     Dflash1::Config dc{};
     dc.n_taps = m.n_taps;
@@ -436,7 +337,8 @@ static int declare_dflash(RadBuilder* b, const RadModelMeta* meta, const RadBuil
         std::vector full;
         const char* lt = rad_meta_gets(meta, "draft.layer_types", nullptr);
         if (lt) {
-            RAD_ARCH_TRY(parse_types(lt, &full));
+            RAD_ARCH_TRY(parse_layer_kinds("gemma4", lt, {"full_attention"}, "sliding_attention",
+                                          &full));
             if ((int64_t)full.size() != dg.n_layer) {
                 fprintf(stderr, "radiance: gemma4: the drafter's layer_types names %zu layers and "
                                 "it has %lld\n", full.size(), (long long)dg.n_layer);
@@ -461,19 +363,11 @@ static int declare_dflash(RadBuilder* b, const RadModelMeta* meta, const RadBuil
         }
     }
 
-    /* ONE CACHE FOR ALL FIVE LAYERS, unbounded, because the full layer reads every position. The
-     * sliding layers bound themselves with their attention op's `window`, so the declared drafter
-     * window is 0 and the core stages the whole context. A window group for the four sliding
-     * layers would cap their share at the window; it is the obvious saving once this runs. */
-    RadKVGroupDecl dd{};
-    dd.kind      = RAD_KV_FULL;
-    dd.dtype     = rad_kv_cache_dtype(ctx, RAD_BF16);
-    dd.n_head_kv = dg.n_head_kv;
-    dd.head_dim  = dg.head_dim;
-    m.kv_draft = rad_decl_kv_group(b, nm.f("kv_draft"), &dd);
-    for (int64_t l = 0; l < dg.n_layer; ++l)
-        RAD_ARCH_TRY(rad_bind_layer_kv(b, base_layer + (int)l, m.kv_draft));
-    dg.kv_dtype = rad_dtype_name(dd.dtype);
+    /* One unbounded cache for all the drafter's layers, because its full layer reads every
+     * position. The sliding layers bound themselves with their attention op's `window`, so the
+     * declared drafter window is 0 and the core stages the whole context. A separate window group
+     * for the sliding layers would save memory. */
+    RAD_ARCH_TRY(drafter_kv_group(b, nm, ctx, dg, 0, base_layer, &m.kv_draft));
 
     const int64_t qd  = dg.n_head * dg.head_dim;
     const int64_t kvd = dg.n_head_kv * dg.head_dim;
@@ -522,8 +416,8 @@ static int declare_dflash(RadBuilder* b, const RadModelMeta* meta, const RadBuil
                 (long long)dg.n_vocab_all, dg.world);
         return RAD_E_UNSUPPORTED;
     }
-    /* THE DRAFT, one row a draft position -- [n_seq * steps, 1], which is [n_seq, steps] with a
-     * pitch of `steps` -- and the engine reads it by the declaration below. */
+    /* The draft, one row per draft position: [n_seq * steps, 1], i.e. [n_seq, steps] with pitch
+     * `steps`, read by the engine through the drafter declaration below. */
     dw.tokens = decl_b(b, nm.f("dflash_tokens"), RAD_I32, {sr, 1});
 
     RAD_ARCH_TRY(m.df.declare(b, nm, dg, dc, base_layer, m.kv_draft, m.w_tok, "draft", dw,
@@ -565,11 +459,10 @@ static int declare_dflash(RadBuilder* b, const RadModelMeta* meta, const RadBuil
 
 /* ============================================================== the experts' encoding */
 
-/* WHAT ONE EXPERT PROJECTION IS STORED AS -- the container's entry, or in rad-convert the recipe's
- * plan for it (rad_weight_encoding) -- which picks the GEMM: plain bf16 is `moe_gemm`, block fp8
- * (fp8_e4m3 codes, a bf16 scale a 128x128 block) is `moe_gemm_q` at fp8a8. Anything else is
- * refused by name. A builder with no model behind it answers nothing, and the declared dtype is
- * then what is read: bf16. */
+/* How one expert projection is stored (the container's entry, or in rad-convert the recipe's
+ * plan, rad_weight_encoding), which picks the GEMM: plain bf16 is `moe_gemm`, block fp8 (fp8_e4m3
+ * codes, a bf16 scale per 128x128 block) is `moe_gemm_q` at fp8a8. Anything else is refused by
+ * name. A builder with no model behind it answers nothing, and the declared dtype bf16 is read. */
 enum { EXP_BF16 = 0, EXP_FP8 = 1 };
 static int expert_format(RadBuilder* b, const char* wn, int* fmt) {
     RadEncoding e{};
@@ -588,8 +481,8 @@ static int expert_format(RadBuilder* b, const char* wn, int* fmt) {
     return RAD_E_DTYPE;
 }
 
-/* ONE ENCODING A PROJECTION A LAYER, because one table of experts takes one: the first local
- * expert's decides, and every other has to match it. `what` is "gate_up" or "down". */
+/* One encoding per projection per layer, since one expert table takes one: the first local
+ * expert's decides and every other must match. `what` is "gate_up" or "down". */
 static int layer_expert_format(RadBuilder* b, Names& nm, int64_t l, int64_t base, int64_t n,
                                const char* what, int* fmt) {
     for (int64_t e = 0; e < n; ++e) {
@@ -633,9 +526,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     Names& nm = m.nm;
     Geom&  g  = m.g;
 
-    /* ---- what this plugin is NOT, refused by name. */
-    if (tc_geti(meta, "hidden_size_per_layer_input", 0) > 0 ||
-        tc_geti(meta, "num_kv_shared_layers", 0) > 0 || tc_getb(meta, "use_double_wide_mlp", false) ||
+    /* ---- variants this plugin does not serve, refused by name. */
+    if (meta_text_geti(meta, "hidden_size_per_layer_input", 0) > 0 ||
+        meta_text_geti(meta, "num_kv_shared_layers", 0) > 0 || tc_getb(meta, "use_double_wide_mlp", false) ||
         tc_getb(meta, "attention_bias", false)) {
         fprintf(stderr, "radiance: gemma4: this checkpoint uses per-layer embeddings, shared KV "
                         "layers, a double-wide MLP or attention biases (the E2B/E4B shape); this "
@@ -643,7 +536,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
         return RAD_E_UNSUPPORTED;
     }
     {
-        const char* act = tc_gets(meta, "hidden_activation", "");
+        const char* act = meta_text_gets(meta, "hidden_activation", "");
         if (!act || std::strcmp(act, "gelu_pytorch_tanh")) {
             fprintf(stderr, "radiance: gemma4: hidden_activation '%s'; this plugin serves "
                             "gelu_pytorch_tanh\n", act ? act : "");
@@ -651,22 +544,22 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
         }
     }
 
-    /* ---- the geometry. Read, never derived: head_dim is not hidden / heads on this family. */
-    m.n_layer = meta->n_layers > 0 ? meta->n_layers : tc_geti(meta, "num_hidden_layers", 0);
-    m.E       = tc_geti(meta, "hidden_size", meta->n_embd);
-    const int64_t nh_all  = tc_geti(meta, "num_attention_heads", meta->n_head);
-    const int64_t vocab   = tc_geti(meta, "vocab_size", meta->n_vocab);
-    const int64_t ff_all  = tc_geti(meta, "intermediate_size", meta->n_ff);
-    const double  eps     = tc_getf(meta, "rms_norm_eps", meta->rms_eps);
-    m.ks.hd      = tc_geti(meta, "head_dim", meta->head_dim);
-    m.ks.nkv_all = tc_geti(meta, "num_key_value_heads", meta->n_head_kv);
-    m.kf.hd      = tc_geti(meta, "global_head_dim", m.ks.hd);
-    m.kf.nkv_all = tc_geti(meta, "num_global_key_value_heads", m.ks.nkv_all);
+    /* ---- the geometry, read rather than derived: head_dim is not hidden / heads here. */
+    m.n_layer = meta->n_layers > 0 ? meta->n_layers : meta_text_geti(meta, "num_hidden_layers", 0);
+    m.E       = meta_text_geti(meta, "hidden_size", meta->n_embd);
+    const int64_t nh_all  = meta_text_geti(meta, "num_attention_heads", meta->n_head);
+    const int64_t vocab   = meta_text_geti(meta, "vocab_size", meta->n_vocab);
+    const int64_t ff_all  = meta_text_geti(meta, "intermediate_size", meta->n_ff);
+    const double  eps     = meta_text_getf(meta, "rms_norm_eps", meta->rms_eps);
+    m.ks.hd      = meta_text_geti(meta, "head_dim", meta->head_dim);
+    m.ks.nkv_all = meta_text_geti(meta, "num_key_value_heads", meta->n_head_kv);
+    m.kf.hd      = meta_text_geti(meta, "global_head_dim", m.ks.hd);
+    m.kf.nkv_all = meta_text_geti(meta, "num_global_key_value_heads", m.ks.nkv_all);
     m.kf.k_eq_v  = tc_getb(meta, "attention_k_eq_v", false);
-    m.ks.theta   = tc_getf(meta, "rope_parameters.sliding_attention.rope_theta", 0.0);
-    m.kf.theta   = tc_getf(meta, "rope_parameters.full_attention.rope_theta", 0.0);
-    m.ks.window  = tc_geti(meta, "sliding_window", 0);   /* HF: q - k < window, attn_paged's rule */
-    m.softcap    = tc_getf(meta, "final_logit_softcapping", 0.0);
+    m.ks.theta   = meta_text_getf(meta, "rope_parameters.sliding_attention.rope_theta", 0.0);
+    m.kf.theta   = meta_text_getf(meta, "rope_parameters.full_attention.rope_theta", 0.0);
+    m.ks.window  = meta_text_geti(meta, "sliding_window", 0);   /* HF: q - k < window, attn_paged's rule */
+    m.softcap    = meta_text_getf(meta, "final_logit_softcapping", 0.0);
     if (m.n_layer <= 0 || m.E <= 0 || nh_all <= 0 || vocab <= 0 || ff_all <= 0 || !(eps > 0) ||
         m.ks.hd <= 0 || m.ks.nkv_all <= 0 || m.kf.hd <= 0 || m.kf.nkv_all <= 0 ||
         !(m.ks.theta > 0) || !(m.kf.theta > 0) || m.ks.window <= 0) {
@@ -678,13 +571,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                 (long long)m.ks.window, (long long)m.kf.hd, (long long)m.kf.nkv_all, m.kf.theta);
         return RAD_E_INVAL;
     }
-    /* The two rotaries. The sliding one is the ordinary full-head NeoX; the full one is read for
-     * its type and its proportion and refused if it is anything this plugin does not compute. */
+    /* The two rotaries. The sliding one is ordinary full-head NeoX; the full one's type and
+     * proportion are read and refused if this plugin does not compute them. */
     {
-        const char* st = tc_gets(meta, "rope_parameters.sliding_attention.rope_type", "default");
-        const char* ft = tc_gets(meta, "rope_parameters.full_attention.rope_type", "default");
-        const double prf = tc_getf(meta, "rope_parameters.full_attention.partial_rotary_factor", 1.0);
-        const double ff  = tc_getf(meta, "rope_parameters.full_attention.factor", 1.0);
+        const char* st = meta_text_gets(meta, "rope_parameters.sliding_attention.rope_type", "default");
+        const char* ft = meta_text_gets(meta, "rope_parameters.full_attention.rope_type", "default");
+        const double prf = meta_text_getf(meta, "rope_parameters.full_attention.partial_rotary_factor", 1.0);
+        const double ff  = meta_text_getf(meta, "rope_parameters.full_attention.factor", 1.0);
         if (std::strcmp(st, "default") || (std::strcmp(ft, "default") && std::strcmp(ft, "proportional")) ||
             ff != 1.0 || !(prf > 0.0) || prf > 1.0) {
             fprintf(stderr, "radiance: gemma4: rotary '%s' (sliding) and '%s' factor %g "
@@ -701,7 +594,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     }
 
     std::vector full;
-    RAD_ARCH_TRY(parse_types(tc_gets(meta, "layer_types", nullptr), &full));
+    const char* lt = meta_text_gets(meta, "layer_types", nullptr);
+    if (!lt) return RAD_E_INVAL;
+    RAD_ARCH_TRY(parse_layer_kinds("gemma4", lt, {"full_attention"}, "sliding_attention", &full));
     if ((int64_t)full.size() != m.n_layer) {
         fprintf(stderr, "radiance: gemma4: layer_types names %zu layers and the model has %lld\n",
                 full.size(), (long long)m.n_layer);
@@ -748,9 +643,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     /* ---- the routed arm's geometry. */
     m.moe = tc_getb(meta, "enable_moe_block", false);
     if (m.moe) {
-        m.n_expert = tc_geti(meta, "num_experts", meta->n_expert);
-        m.top_k    = tc_geti(meta, "top_k_experts", meta->n_expert_used);
-        m.n_ffe    = tc_geti(meta, "moe_intermediate_size", 0);
+        m.n_expert = meta_text_geti(meta, "num_experts", meta->n_expert);
+        m.top_k    = meta_text_geti(meta, "top_k_experts", meta->n_expert_used);
+        m.n_ffe    = meta_text_geti(meta, "moe_intermediate_size", 0);
         if (m.n_expert <= 0 || m.top_k <= 0 || m.top_k > m.n_expert || m.n_ffe <= 0) {
             fprintf(stderr, "radiance: gemma4: enable_moe_block with %lld experts, top %lld, of "
                             "%lld\n", (long long)m.n_expert, (long long)m.top_k,
@@ -760,12 +655,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
         RAD_ARCH_TRY(divide_or_fail(m.n_expert, W, "num_experts", &m.n_local));
         m.expert_base = (int64_t)R * m.n_local;
         /* A pass bounds the [rows * top_k, ...] expert planes; 2048 tokens is one pass at the
-         * default chunk. */
+         * default chunk size. */
         m.moe_rows = T < 2048 ? T : 2048;
     }
 
-    /* ---- the embedding scale and the rotary scaling the converter may have written. */
-    m.escale = bf16_round(std::sqrt((double)E));
+    /* ---- the embedding scale and the rotary scaling the converter may have written. The scale
+     * is rounded to bf16 because the reference holds it in a bf16 buffer: sqrt(2816) = 53.066
+     * multiplies as 53.0. */
+    m.escale = rad_bf16_to_f32(rad_f32_to_bf16((float)std::sqrt((double)E)));
     RAD_ARCH_TRY(yarn_from(g, meta, "", m.ks.hd));
     if (g.yarn.factor != 0.0f || g.rope_scale != 1.0f) {
         fprintf(stderr, "radiance: gemma4: --rope-scaling is not implemented for this family's "
@@ -773,29 +670,23 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
         return RAD_E_UNSUPPORTED;
     }
 
-    /* ---- the KV groups, one a geometry: the sliding layers' (256-wide heads) and the full
+    /* ---- the KV groups, one per geometry: the sliding layers' (256-wide heads) and the full
      * layers' (512).
      *
-     * THE SLIDING LAYERS' GROUP IS RAD_KV_FULL, NOT RAD_KV_WINDOW, and the window lives on the
-     * attention op (`window` 1024), which reads only the keys inside it. A WINDOW group is not
-     * prefix-cached (core/mem/prefix.cpp: a hit's blocks do not describe a cache whose floor
-     * moves). Before the scheduler knew that, a hit gave the sliding layers a table whose reused
-     * prefix was never written for this request -- recycled blocks of other conversations, and a
-     * reply that answers someone else's question; now a hit on a model with a windowed trunk group
-     * reuses nothing and re-prefills (core/sched). As FULL the group is cached with the others and
-     * a hit is kept, exactly; the drafter's KV gets no hole either. What it costs is the recycling
-     * below the window, which buys nothing here: the planner gives every paged group the same
-     * block count, so the full group bounds the tokens a card holds either way. */
+     * The sliding layers' group is RAD_KV_FULL, not RAD_KV_WINDOW; the window lives on the
+     * attention op (`window` 1024), which reads only keys inside it. A window group is not
+     * prefix-cached (core/mem/prefix.cpp), so a prefix hit on a model with one reuses nothing and
+     * re-prefills (core/sched). As FULL the group is cached with the others and the drafter's KV
+     * has no hole. The only loss is recycling below the window, which gains nothing here: the
+     * planner gives every paged group the same block count, so the full group bounds the tokens a
+     * card holds anyway. */
     {
         RadKVGroupDecl d{};
         d.kind = RAD_KV_FULL;
         d.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
-        d.window = 0;
         d.n_head_kv = m.ks.nkv;
         d.head_dim = m.ks.hd;
         m.ks.kv = rad_decl_kv_group(b, nm.f("kv_swa"), &d);
-        d.kind = RAD_KV_FULL;
-        d.window = 0;
         d.n_head_kv = m.kf.nkv;
         d.head_dim = m.kf.hd;
         m.kf.kv = rad_decl_kv_group(b, nm.f("kv_full"), &d);
@@ -808,10 +699,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     const char* L = (archs && std::strstr(archs, "Gemma4ForCausalLM")) ? "model"
                                                                        : "model.language_model";
 
-    /* ---- THE EXPERTS' NAME MAPS, AND FROM THEM WHAT EACH LAYER'S EXPERTS ARE, before any buffer:
-     * an fp8 projection reads an E4M3 input that a bf16 one does not, and a plane nothing reads
-     * is still charged by the planner. One stacked tensor a projection a layer, sliced by the
-     * GLOBAL expert index -- this rank declares its window into the checkpoint's experts. */
+    /* ---- the experts' name maps, and from them each layer's expert format, before any buffer:
+     * an fp8 projection reads an E4M3 input a bf16 one does not, and an unread plane would still
+     * be charged by the planner. One stacked tensor per projection per layer, sliced by the global
+     * expert index: this rank declares its window into the checkpoint's experts. */
     m.layers.resize((size_t)m.n_layer);
     if (m.moe) {
         const int64_t NL = m.n_local;
@@ -830,8 +721,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
             RAD_ARCH_TRY(layer_expert_format(b, nm, l, m.expert_base, NL, "down", &fdn));
             y.gu_fp8 = fgu == EXP_FP8;
             y.dn_fp8 = fdn == EXP_FP8;
-            /* moe_gemm_q's geometry, refused here by name rather than as a kernel miss. Its
-             * experts are two tables by parity, so a rank holds an even count of them. */
+            /* moe_gemm_q's geometry, refused here by name rather than as a kernel miss. It takes
+             * experts as two tables by parity, so a rank must hold an even count. */
             if ((y.gu_fp8 || y.dn_fp8) && NL % 2) {
                 fprintf(stderr, "radiance: gemma4: block fp8 experts come in pairs on a rank (the "
                                 "fp8 grouped GEMM takes them as two tables by parity); this rank "
@@ -900,8 +791,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     }
     m.b_hout = decl_b(b, nm.f("h_out"), RAD_BF16, {g.max_logit_rows, E});
 
-    /* ---- the drafter's taps: declared when the container carries a DFlash drafter AND this serve
-     * speculates. DFlash2 is refused by name -- its convolutions and selector are another block. */
+    /* ---- the drafter's taps, declared when the container carries a DFlash drafter and this
+     * serve speculates. DFlash2 is refused by name: its convolutions and selector are another
+     * block. */
     if (ctx->max_spec > 0) {
         const char* da = rad_meta_gets(meta, "draft.architectures", "");
         if (da && std::strstr(da, "DFlash2")) {
@@ -912,7 +804,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
         if (da && std::strstr(da, "DFlash")) {
             const char* ids = rad_meta_gets(meta, "draft.dflash_config.target_layer_ids", nullptr);
             if (!ids) ids = rad_meta_gets(meta, "draft.target_layer_ids", nullptr);
-            m.n_taps = parse_ids(ids, m.n_layer, m.tap_layer, Model::MAX_TAPS);
+            m.n_taps = parse_layer_ids(ids, m.n_layer, m.tap_layer, Model::MAX_TAPS);
             if (m.n_taps <= 0) {
                 fprintf(stderr, "radiance: gemma4: the drafter names no trunk layer this model "
                                 "has; it is paired with a different target\n");
@@ -925,9 +817,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     m.b_logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab});
     RAD_ARCH_TRY(rad_declare_logits(b, m.b_logits));
 
-    /* ---- the vocabulary edges: ONE table, row-sharded with the vocabulary, read as the embedding
-     * by `embed_lookup` and as the head by `logits_gemm` -- Gemma ties them, so storing the head
-     * a second time would be 1.4 GiB for nothing. */
+    /* ---- the vocabulary edges: one table, row-sharded with the vocabulary, read as the embedding
+     * by `embed_lookup` and as the head by `logits_gemm`. Gemma ties them; a second copy would be
+     * 1.4 GiB. */
     m.tok_src = nm.ckpt("%s.embed_tokens.weight", L);
     RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), m.tok_src));
     RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("%s.norm.weight", L)));
@@ -949,7 +841,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                                RAD_NOWEIGHTS),
                            {m.b_x}, {m.b_x});
 
-    /* ---- small declaration helpers, every one rows-banded at the step's height unless told. */
+    /* ---- small declaration helpers, each banded over rows up to the step's height unless
+     * given another bound. */
     auto rmsnorm = [&](int64_t rows, int64_t n, rad_weight w, double mult, rad_buf in, rad_buf out) {
         rad_op h = w ? RAD_OP(b, "rmsnorm",
                               RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
@@ -1013,15 +906,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                   {kb, vb}, {});
     };
 
-    /* THE SANDWICH JOINS, expert_scale AND attn_paged_qrow: asked of the kernel libraries as one
-     * op each and declared as the chain where they do not resolve. Not every library declares them
-     * -- libr4d does, with device rows; libref and libavx do not -- and declaring an op no loaded
-     * library declares is an error, so each is asked about first (rad_op_declared). A deployment
-     * where none is declared -- a CPU-only build, a --kernels list without libr4d -- or where none
-     * resolves -- the host backend -- runs the chain. The fused kernels round where the host chain
-     * rounds (libr4d/r4d_norm_join_bf16.hip); on a card they differ from libr4d's chain by the
-     * order of its reductions. libref has no row for them on purpose, so "nothing serves them"
-     * stays reachable. */
+    /* The sandwich joins, expert_scale and attn_paged_qrow are each requested as one op and
+     * declared as the chain where they do not resolve. Only libr4d declares them (device rows; not
+     * libref or libavx), and declaring an op no loaded library declares is an error, so each is
+     * checked first with rad_op_declared. A CPU-only build, a --kernels list without libr4d, or
+     * the host backend runs the chain. The fused kernels round where the host chain rounds
+     * (libr4d/r4d_norm_join_bf16.hip); on a card they differ from libr4d's chain only in reduction
+     * order. libref deliberately has no row for them, so the chain path stays tested. */
     const bool has_join_a = rad_op_declared(b, "norm_add_norm") != 0;
     const bool has_join_r = rad_op_declared(b, "norm_add_norm_route") != 0;
     const bool has_join_f = rad_op_declared(b, "join_add_scale") != 0;
@@ -1030,9 +921,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     int n_joins = 0, n_route = 0;
 
     const int A = RAD_ACCESS_PER_TOKEN, N = RAD_SHARD_NONE;
-    /* EVERY LAYER'S INPUT NORM GAIN, AHEAD OF THE LAYERS: a feed-forward join writes the next
-     * layer's input norm (join_add_scale's `y`) and so names that layer's gain before the layer
-     * itself is declared. */
+    /* Every layer's input norm gain, declared ahead of the layers: a feed-forward join writes the
+     * next layer's input norm (join_add_scale's `y`), naming that gain before its layer is
+     * declared. */
     for (int64_t l = 0; l < m.n_layer; ++l) {
         const long long ll = (long long)l;
         RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_norm.weight", ll),
@@ -1064,18 +955,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                            RAD_SHARD_COL, gl);
         y.w_apost = decl_w(b, nm.f("blk.%lld.attn_post_norm.weight", ll), RAD_F32, {E}, A, N, gl);
         if (!y.full) {
-            /* ONE PROJECTION, q|k|v, three row parts: every rank takes its slice of each. */
+            /* One projection, q|k|v, three row parts: every rank takes its slice of each. */
             RAD_ARCH_TRY(map_concat(b, nm.f("blk.%lld.attn_qkv.weight", ll),
                                     { src("self_attn.q_proj.weight"), src("self_attn.k_proj.weight"),
                                       src("self_attn.v_proj.weight") }));
-            if (!k.kv_repl) {
-                y.w_qkv = decl_w(b, nm.f("blk.%lld.attn_qkv.weight", ll), RAD_BF16,
-                                 {k.q() + 2 * k.kv_dim(), E}, A, RAD_SHARD_ROW, gl, 0,
-                                 {k.q(), k.kv_dim(), k.kv_dim()});
-            } else {
-                y.w_qkv = decl_w(b, nm.f("blk.%lld.attn_qkv.weight", ll), RAD_BF16,
-                                 {k.q() + 2 * k.kv_dim(), E}, A, RAD_SHARD_ROW, gl, 0,
-                                 {k.q(), k.kv_dim(), k.kv_dim()});
+            y.w_qkv = decl_w(b, nm.f("blk.%lld.attn_qkv.weight", ll), RAD_BF16,
+                             {k.q() + 2 * k.kv_dim(), E}, A, RAD_SHARD_ROW, gl, 0,
+                             {k.q(), k.kv_dim(), k.kv_dim()});
+            if (k.kv_repl) {
                 const int64_t lo[3] = { R * k.q(), k.kv_off, k.kv_off };
                 const int64_t hi[3] = { lo[0] + k.q(), lo[1] + k.kv_dim(), lo[2] + k.kv_dim() };
                 const int64_t tot[3] = { nh_all * k.hd, k.nkv_all * k.hd, k.nkv_all * k.hd };
@@ -1111,22 +998,21 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                                            RAD_F64("wadd", 0.0), RAD_INT("v_norm", 1)),
                                 RAD_WEIGHTS(y.w_qn, y.w_kn)),
                             {m.b_qkv}, {m.b_qkv});
-            /* Q IS READ WHERE THE PROJECTION LEFT IT, a column slice of the fused [q|k|v] row, by
-             * `attn_paged_qrow` -- attn_paged with q at its own row pitch, an op of its own so
-             * that no `--kernels` order can hand the slice to a kernel that reads q only dense
-             * (one refuses it with RAD_E_STRIDE, which stops the engine). That saves the
-             * lift: a launch and a [T, q] round trip a sliding layer. Where the op is not declared
-             * or does not resolve, q is lifted into a dense block for attn_paged, which every
-             * attention library takes. Asked once, because every
-             * sliding layer asks the same question; a miss is still the group's first op carrying
-             * a block_size, and answers rad_kv_block_size with the RAD_KV_BLOCK it declares. */
+            /* q is read in place, a column slice of the fused [q|k|v] row, by `attn_paged_qrow`
+             * (attn_paged with q at its own row pitch). It is a separate op so no `--kernels`
+             * order can hand the slice to a kernel that reads q only dense (which would refuse it
+             * with RAD_E_STRIDE and stop the engine). This saves a launch and a [T, q] round trip
+             * per sliding layer. Where the op is not declared or does not resolve, q is copied
+             * into a dense block for attn_paged. Asked once for all sliding layers; even a miss
+             * is the group's first op carrying a block_size, so rad_kv_block_size answers with
+             * its RAD_KV_BLOCK. */
             if (has_qrow && m.qrow != 0) {
                 y.op_attn = attn(k, m.b_qkv, m.b_atts, "attn_paged_qrow");
                 m.qrow = y.op_attn ? 1 : 0;
             }
             if (!y.op_attn) {
-                /* declared here, not with the others: a buffer no op names is live for the whole
-                 * program, and where q is read in place nothing names this one */
+                /* Declared here, not with the others: a buffer no op names is live for the whole
+                 * program, and when q is read in place nothing names this one. */
                 if (!m.b_qs) m.b_qs = decl_b(b, nm.f("q_s"), RAD_BF16, {T, k.q()});
                 y.op_lift = rw(b, RAD_OP(b, "cast",
                                     RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", k.q()),
@@ -1140,7 +1026,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
         } else {
             y.op_q     = gemm(T, k.q(), E, y.w_q, m.b_h, m.b_qf);
             y.op_k     = gemm(T, k.kv_dim(), E, y.w_k, m.b_h, m.b_kf);
-            /* V FIRST: the unit-gain norm of the RAW k projection, before the key norm writes k. */
+            /* V first: the unit-gain norm of the raw k projection, before the key norm writes k. */
             y.op_vnorm = rmsnorm(T * k.nkv, k.hd, 0, 1.0, m.b_kf, m.b_vf);
             y.op_qn    = rmsnorm(T * k.nh, k.hd, y.w_qn, 1.0, m.b_qf, m.b_qf);
             y.op_kn    = rmsnorm(T * k.nkv, k.hd, y.w_kn, 1.0, m.b_kf, m.b_kf);
@@ -1151,8 +1037,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
             y.op_o     = gemm(T, E, k.q(), y.w_o, m.b_attf, m.b_o);
         }
         if (W > 1) y.op_ar_o = allreduce(T * E, m.b_o);
-        /* The post-norm AFTER the reduction: it is a norm of the whole sum. Declared below, with the
-         * dense arm's pre-norm, as one `norm_add_norm` where a kernel library serves it. */
+        /* The post-norm comes after the reduction, since it normalises the whole sum. Declared
+         * below with the dense arm's pre-norm, as one `norm_add_norm` where a kernel serves it. */
 
         /* ------------------------------------------------ the dense arm */
         RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_norm.weight", ll), src("pre_feedforward_layernorm.weight")));
@@ -1171,9 +1057,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
         /* bf16 and one element: the reference multiplies the bf16 stream by it. */
         y.w_scalar = decl_w(b, nm.f("blk.%lld.layer_scalar", ll), RAD_BF16, {1}, A, N, gl);
 
-        /* The routed arm's two input norms -- the router's gain and the experts' pre-norm -- are
-         * declared here, ahead of the attention join, which writes both inputs where
-         * `norm_add_norm_route` is served and an op names its weights after they are declared. */
+        /* The routed arm's two input norm gains (the router's and the experts' pre-norm) are
+         * declared here, before the attention join, which writes both inputs where
+         * `norm_add_norm_route` is served; an op can only name weights already declared. */
         if (m.moe) {
             RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_norm_exps.weight", ll),
                                   src("pre_feedforward_layernorm_2.weight")));
@@ -1183,10 +1069,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
             y.w_rscale = decl_w(b, nm.f("blk.%lld.ffn_gate_inp.scale", ll), RAD_F32, {E}, A, N, gl);
         }
 
-        /* THE ATTENTION JOIN, and on a layer whose gate_up is block fp8 the routed arm's two
-         * inputs with it: the router's norm (rmsnorm's expression, its mult hidden^-0.5) and the
-         * experts' E4M3 codes (rmsnorm_quant_fp8's) from the norm of x the join already takes --
-         * two launches a layer fewer, and two reads of x. Then norm_add_norm, then the chain. */
+        /* The attention join. On a layer whose gate_up is block fp8 it also writes the routed
+         * arm's two inputs: the router's norm (rmsnorm with mult hidden^-0.5) and the experts'
+         * E4M3 codes (as rmsnorm_quant_fp8), saving two launches and two reads of x per layer.
+         * Otherwise norm_add_norm, else the chain. */
         if (has_join_r && m.moe && y.gu_fp8)
             y.op_join_r = rw(b, RAD_OP(b, "norm_add_norm_route",
                                     RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
@@ -1222,19 +1108,19 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
             RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_exp_scale", ll), src("router.per_expert_scale")));
             y.w_fpost1 = decl_w(b, nm.f("blk.%lld.ffn_post_norm1.weight", ll), RAD_F32, {E}, A, N, gl);
             y.w_fpost2 = decl_w(b, nm.f("blk.%lld.ffn_post_norm2.weight", ll), RAD_F32, {E}, A, N, gl);
-            /* THE ROUTER IS REPLICATED (rad_block_moe_fp8.h argues it): every rank routes every
-             * token the same way from the same residual stream. */
+            /* The router is replicated (rad_block_moe_fp8.h): every rank routes every token the
+             * same way from the same residual stream. */
             y.w_router = decl_w(b, nm.f("blk.%lld.ffn_gate_inp.weight", ll), RAD_BF16,
                                 {m.n_expert, E}, A, N, gl);
             y.w_escale = decl_w(b, nm.f("blk.%lld.ffn_exp_scale", ll), RAD_BF16, {m.n_expert}, A,
                                 N, gl);
-            /* THE EXPERTS: whole experts, this rank's run of them (their name maps and encodings
-             * were settled before the buffers). Each projection's handles are declared as the
-             * runs its GEMM's tables are: bf16, one run in expert order; block fp8, the codes of
-             * the even local experts, then the odd ones', then the scale views in the same two
-             * runs -- `moe_gemm_q` takes a projection's experts as two tables by parity, and a
-             * table is a run of consecutively declared handles. The codes and the scale plane are
-             * two views of one stored weight and one movement unit (slot 0 gate_up, 1 down). */
+            /* The experts: this rank's run of whole experts (name maps and encodings were settled
+             * before the buffers). Each projection's handles are declared in its GEMM's table
+             * order, since a table is a run of consecutively declared handles: bf16 is one run in
+             * expert order; block fp8 is the even local experts' codes, then the odd ones', then
+             * the scale views in the same two runs (`moe_gemm_q` takes two tables by parity). Codes
+             * and scale plane are two views of one stored weight and one movement unit (slot 0
+             * gate_up, 1 down). */
             auto experts = [&](bool fp8, const char* what, int slot, int64_t rows, int64_t cols,
                                std::vector& wc, std::vector& ws) {
                 wc.assign((size_t)NL, 0);
@@ -1293,8 +1179,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                                   RAD_NOWEIGHTS),
                               {m.b_logit}, {m.b_ids, m.b_ew});
             /* per_expert_scale[expert] times the routing weight: one launch where `expert_scale` is
-             * served, and otherwise the table gathered as [n_expert, 1] by the ids and a
-             * `mul` -- the same bf16 product either way (docs/OPS.md). */
+             * served, otherwise the [n_expert, 1] table gathered by id and a `mul`; the same bf16
+             * product either way (docs/OPS.md). */
             if (has_escale)
                 y.op_expert_scale = rw(b, RAD_OP(b, "expert_scale",
                                            RAD_PARAMS(RAD_RANGE("M", 1, P),
@@ -1310,9 +1196,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                                   {m.b_ids}, {m.b_es});
                 y.op_emul   = binop("mul", P, K, m.b_ew, m.b_es, m.b_ew);
             }
-            /* THE EXPERTS' INPUT: pre_feedforward_layernorm_2 of the stream -- for an fp8 gate_up,
-             * normed and quantised in one pass (`rmsnorm_quant_fp8`), with no bf16 copy, since the
-             * fp8 GEMM reads only the codes and their scales. */
+            /* The experts' input, pre_feedforward_layernorm_2 of the stream. For an fp8 gate_up it
+             * is normed and quantised in one pass (`rmsnorm_quant_fp8`) with no bf16 copy, since
+             * the fp8 GEMM reads only codes and scales. */
             if (y.gu_fp8) {
                 y.op_enorm = RAD_OP(b, "rmsnorm_quant_fp8",
                                     RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", E),
@@ -1329,18 +1215,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                                               RAD_INT("expert_base", m.expert_base)),
                                    RAD_NOWEIGHTS),
                                {m.b_ids}, {m.b_sorted, m.b_eoff, m.b_ecnt});
-            /* THE ROUTER, ITS TOP-K AND THE SORT IN ONE LAUNCH at decode heights. At a decode step
-             * each of the three is one small workgroup's work behind a full dispatch, and libr4d
-             * fuses them: `router_topk_scatter` for the pair, bounded by the sort's single-workgroup
-             * form (kMoeSortRows routing slots), and `router_gemm_topk_scatter` with the router's
-             * GEMM in front, up to the skinny GEMM's decode band -- byte-identical to the launches
-             * they stand in for (docs/OPS.md), so the routing does not move. The per-expert scale
-             * and the experts' input norm sit between them in the issue order and read only the ids
-             * and weights the fused op writes. Declared here, after every buffer they name: a late
+            /* The router, its top-k and the sort in one launch at decode heights, where each is a
+             * small workgroup's work behind a full dispatch. `router_topk_scatter` fuses top-k and
+             * sort, bounded by the sort's single-workgroup form (kMoeSortRows routing slots);
+             * `router_gemm_topk_scatter` adds the router GEMM, up to the skinny GEMM's decode band.
+             * Both are byte-identical to the separate launches (docs/OPS.md). The per-expert scale
+             * and the experts' input norm sit between them in issue order and read only the ids
+             * and weights the fused op writes. Declared after every buffer they name; a late
              * declaration only lengthens a buffer's planned life (rad_block_moe_fp8.h). */
             {
                 const int64_t sort_rows = P * K <= kMoeSortRows ? P : kMoeSortRows / K;
-                if (sort_rows > 0)
+                if (sort_rows > 0 && rad_op_declared(b, "router_topk_scatter"))
                     y.op_topk_scatter = rw(b, RAD_OP(b, "router_topk_scatter",
                                                RAD_PARAMS(RAD_RANGE("M", 1, sort_rows),
                                                           RAD_INT("n_expert", m.n_expert),
@@ -1352,7 +1237,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                 if (y.op_topk_scatter) {
                     y.topk_scatter_rows = sort_rows;
                     const int64_t fr = sort_rows < kMoeRouterFusedRows ? sort_rows : kMoeRouterFusedRows;
-                    y.op_router_fused = rw(b, RAD_OP(b, "router_gemm_topk_scatter",
+                    if (rad_op_declared(b, "router_gemm_topk_scatter"))
+                        y.op_router_fused = rw(b, RAD_OP(b, "router_gemm_topk_scatter",
                                                RAD_PARAMS(RAD_RANGE("M", 1, fr), RAD_INT("K", E),
                                                           RAD_INT("n_expert", m.n_expert),
                                                           RAD_INT("n_local", NL), RAD_INT("top_k", K),
@@ -1364,9 +1250,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                     if (y.op_router_fused) y.router_fused_rows = fr;
                 }
             }
-            /* THE TWO GROUPED GEMMs DISAGREE ABOUT a_order, and must: gate_up reads the block
-             * input, a row a TOKEN, gathered through sorted_tok; down reads gate_up's product,
-             * already a row a (token, slot) in the scatter's order (rad_block_moe_fp8.h). */
+            /* The two grouped GEMMs use different a_order: gate_up reads the block input, one row
+             * per token, gathered through sorted_tok; down reads gate_up's product, already one row
+             * per (token, slot) in scatter order (rad_block_moe_fp8.h). */
             if (y.gu_fp8) {
                 const std::vector tab = tables(y.w_egu, y.w_egus);
                 y.op_egu = rw(b, rad_decl_op(b, "moe_gemm_q",
@@ -1428,8 +1314,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
             if (W > 1) y.op_ar_f = allreduce(2 * T * E, m.b_ff2);
             if (has_join_f)
             {
-                /* ...and the norm that reads the x it writes: the next layer's input norm, or the
-                 * final norm after the last layer -- one launch and one read of x the less. */
+                /* The join also applies the norm that reads its x (the next layer's input norm, or
+                 * the final norm after the last layer), saving a launch and a read of x. */
                 const rad_weight w_next = l + 1 < m.n_layer ? m.layers[(size_t)l + 1].w_anorm
                                                             : m.w_onorm;
                 y.op_join_f = rw(b, RAD_OP(b, "join_add_scale",
@@ -1461,13 +1347,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
         n_joins += (y.op_join_a || y.op_join_r ? 1 : 0) + (y.op_join_f ? 1 : 0);
         n_route += y.op_join_r ? 1 : 0;
 
-        /* THE TAP: a row copy of the layer's output into the column slice a tap owns, DECLARED
-         * HERE, after the layer's last op, because that is where step() issues it. The buffer
-         * planner's liveness is declaration order. One tap op declared after the whole trunk made
-         * `dflash_src` look born at the end of it, so the plan was free to put it on top of
-         * buffers every layer writes -- and at --max-num-seqs 16 it did, under `moe_edn`, the
-         * routed experts' output: every MoE layer after a tap overwrote what the drafter reads,
-         * and on gemma-4-26B-A4B-it it accepted 2% of its drafts with the reply still fluent. */
+        /* The tap: a row copy of the layer's output into its column slice, declared here after
+         * the layer's last op because step() issues it here and declaration order is the
+         * planner's liveness. Declared after the whole trunk instead, `dflash_src` would look
+         * born at the end and could alias buffers every layer writes (e.g. `moe_edn`), corrupting
+         * what the drafter reads while the output stays correct. */
         for (int t = 0; t < m.n_taps; ++t)
             if (m.tap_layer[t] == (int)l && !y.op_tap)
                 y.op_tap = rw(b, RAD_OP(b, "cast",
@@ -1477,24 +1361,22 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                               {m.b_x}, {m.b_dfsrc});
     }
 
-    /* ---- THE PREFILL OVERLAP (trunk_overlap): where there is a reduction to hide, a routed arm
-     * whose passes a slice can be a whole number of, and every join fused -- the slices issue the
-     * fused forms only. On the exact wire alone: nothing here shows the lossy one gives a slice
-     * the bits it gives the whole. On two R9700s the two slices give the whole chunk's text and
-     * logprobs exactly, at 2048- and 8192-token chunks. The two buffers the second lane reduces in place are taken out of the arena's
-     * sharing, which the runtime asks of every buffer a second lane touches (rad_buf_concurrent);
-     * both live across the whole trunk already, so what that costs is only the sharing with the
-     * drafter's and the head's buffers. */
+    /* ---- the prefill overlap (trunk_overlap). Requires a reduction to hide, a routed arm whose
+     * passes divide a slice, and every join fused (the slices issue only the fused forms). Exact
+     * wire only, since nothing shows the lossy wire gives a slice the same bits as the whole; on
+     * the exact wire the two slices reproduce the whole chunk's text and logprobs exactly. The two
+     * buffers the second lane reduces in place leave the arena's sharing (rad_buf_concurrent);
+     * both already live across the trunk, so this only costs sharing with the drafter's and the
+     * head's buffers. */
     m.overlap = W > 1 && m.moe && g.wire_exact && T >= 2 * m.moe_rows;
     for (const Layer& y : m.layers)
         m.overlap = m.overlap && (y.op_join_a || y.op_join_r) && y.op_join_f && y.next_norm &&
                     y.op_ar_o && y.op_ar_f;
-    /* ---- THE TWO ARMS SIDE BY SIDE (trunk), in a step that runs whole: the dense arm on the
-     * second lane beside the routed arm, which needs nothing of it until the feed-forward join. At a
-     * decode step on 4x R9700 the dense arm is three launches, ~36 us under --profile-ops, behind
-     * the routed arm's ~120 in a layer, and its GEMMs at a few rows are latency-bound -- far from
-     * the bandwidth the experts take. No collective rides it, so the reductions keep lane 0. The
-     * buffers the dense arm touches leave the arena's sharing. */
+    /* ---- the two arms side by side (trunk), in a step that runs whole: the dense arm on the
+     * second lane beside the routed arm, which needs nothing from it until the feed-forward join.
+     * At decode the dense arm is three latency-bound launches (~36 us against the routed arm's
+     * ~120 us per layer on 4x R9700), so it hides behind the experts' bandwidth. No collective
+     * rides it, so the reductions stay on lane 0. Its buffers leave the arena's sharing. */
     m.arms = m.moe;
     if (m.overlap) RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_o));
     if (m.overlap || m.arms) RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_ff2));
@@ -1514,10 +1396,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                                      RAD_STR("dtype", "bf16")),
                           RAD_WEIGHTS(m.w_tok)),
                       {m.b_hout}, {m.b_logits});
-    /* FINAL LOGIT SOFTCAPPING, cap * tanh(x / cap) over the f32 logits: `logit_softcap`, which
-     * libref, libavx and libr4d serve. Where nothing does the model still runs and greedy decoding
-     * is unchanged -- the cap is strictly increasing -- but a sampled distribution is SHARPER than
-     * the model's, so the startup log says so. */
+    /* Final logit softcapping, cap * tanh(x / cap) over the f32 logits (`logit_softcap`, served by
+     * libref, libavx and libr4d). Without it greedy decoding is unchanged (the cap is strictly
+     * increasing) but sampling draws from a sharper distribution, so the startup log warns. */
     if (m.softcap > 0.0) {
         m.op_cap = rw(b, RAD_OP(b, "logit_softcap",
                            RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
@@ -1526,13 +1407,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                            RAD_NOWEIGHTS),
                        {m.b_logits}, {m.b_logits});
         if (!m.op_cap)
-            rad_note(b, "WARNING: nothing serves `logit_softcap` (load libr4d or libavx). "
-                        "The model's logits are %g * tanh(x / %g); without it greedy output is "
-                        "unchanged and SAMPLED output draws from a sharper distribution than the "
-                        "model's", m.softcap, m.softcap);
+            rad_note(b, "warning: no kernel serves `logit_softcap` (load libr4d or libavx), so "
+                        "the logits skip %g * tanh(x / %g): greedy output is unchanged, sampled "
+                        "output draws from a sharper distribution", m.softcap, m.softcap);
     }
 
-    /* THE DRAFTER LAST: declaration order is the buffer planner's liveness (llama_fp8.cpp). */
+    /* The drafter last: declaration order is the buffer planner's liveness. */
     if (m.n_taps > 0)
         RAD_ARCH_TRY(declare_dflash(b, meta, ctx, m, (int)m.n_layer));
 
@@ -1579,8 +1459,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                     "beside the routed");
     }
     if (m.kf.rot_pairs < m.kf.hd / 2)
-        rad_note(b, "full layers: PROPORTIONAL rope -- %lld of %lld frequency pairs rotate at "
-                    "theta %g over the whole %lld-wide head, the rest stay at frequency zero",
+        rad_note(b, "full layers: proportional rope, %lld of %lld frequency pairs rotating at "
+                    "theta %g over the whole %lld-wide head and the rest at frequency zero",
                  (long long)m.kf.rot_pairs, (long long)(m.kf.hd / 2), m.kf.theta,
                  (long long)m.kf.hd);
     return RAD_OK;
@@ -1588,9 +1468,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
 
 /* ============================================================== step */
 
-/* The routed arm over rows [first, first + rows) of a T-token step, in passes of m.moe_rows, its
- * partial into rows [dst, dst + rows) of the join: [T, 2T) for a whole step, and right after the
- * slice's dense rows for a slice of one (trunk_overlap). */
+/* The routed arm over rows [first, first + rows) of a T-token step, in passes of m.moe_rows,
+ * writing its partial into rows [dst, dst + rows) of the join: [T, 2T) for a whole step, or right
+ * after the slice's dense rows for a slice (trunk_overlap). */
 static void routed(RadCtx* c, const Model& m, const Layer& y, int64_t T, int64_t first,
                    int64_t rows, int64_t dst) {
     const int64_t E = m.E, K = m.top_k, NL = m.n_local, NE = m.n_expert;
@@ -1602,7 +1482,7 @@ static void routed(RadCtx* c, const Model& m, const Layer& y, int64_t T, int64_t
         if (!y.op_join_r)   /* the attention join wrote the router's input otherwise */
             RAD_ISSUE_N(c, y.op_rnorm, n, brow_slice(m.b_x, r0, n, E), RAD_W(y.w_rscale),
                         brow_slice(m.b_rn, r0, n, E));
-        /* One launch, two or three: the router, its top-k and the sort (see declare). */
+        /* The router, its top-k and the sort in one, two or three launches (see declare). */
         const bool rfused = y.op_router_fused && n <= y.router_fused_rows;
         const bool pair = !rfused && y.op_topk_scatter && n <= y.topk_scatter_rows;
         if (rfused) {
@@ -1621,7 +1501,7 @@ static void routed(RadCtx* c, const Model& m, const Layer& y, int64_t T, int64_t
                 RAD_ISSUE_N(c, y.op_topk, n, brow_slice(m.b_logit, r0, n, NE),
                             brow_slice(m.b_ids, r0, n, K), brow_slice(m.b_ew, r0, n, K));
         }
-        /* The ids and the gathered scales read as flat [n * K] vectors: the same bytes. */
+        /* The ids and gathered scales are read as flat [n * K] vectors over the same bytes. */
         int32_t* ids = (int32_t*)rad_buf_ptr(c, m.b_ids);
         uint16_t* es = (uint16_t*)rad_buf_ptr(c, m.b_es);
         if (y.op_expert_scale) {
@@ -1633,8 +1513,8 @@ static void routed(RadCtx* c, const Model& m, const Layer& y, int64_t T, int64_t
             RAD_ISSUE_N(c, y.op_emul, n, brow_slice(m.b_ew, r0, n, K), brow_slice(m.b_es, r0, n, K),
                         brow_slice(m.b_ew, r0, n, K));
         }
-        /* rmsnorm_quant_fp8's operands: x, residual (absent), w, q, scale, out_bf16 (absent) --
-         * where the attention join did not write the codes already. */
+        /* rmsnorm_quant_fp8's operands: x, residual (absent), w, q, scale, out_bf16 (absent);
+         * issued only where the attention join did not already write the codes. */
         if (y.gu_fp8 && !y.op_join_r)
             RAD_ISSUE_N(c, y.op_enorm, n, brow_slice(m.b_x, r0, n, E), RAD_NONE, RAD_W(y.w_enorm),
                         brow_slice(m.b_hq, r0, n, E), brow_slice(m.b_hqs, r0, n, E / RAD_FP8_BLOCK),
@@ -1755,8 +1635,8 @@ static void trunk(RadCtx* c, const Model& m, const RadBatch* batch) {
             RAD_ISSUE(c, y.op_fnorm, brows(m.b_x, T), RAD_W(y.w_fnorm), brows(m.b_h, T));
         }
 
-        /* dense arm -> rows [0, T) of the join: on lane 1 behind the attention join, where the arms
-         * run side by side, and lane 0 joins it back before the reduction reads them */
+        /* The dense arm into rows [0, T) of the join. With side-by-side arms it runs on lane 1
+         * behind the attention join, and lane 0 joins it back before the reduction. */
         if (m.arms)
             lanes_ok = lanes_ok && rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK;
         RAD_ISSUE(c, y.op_gu, brows(m.b_h, T), RAD_W(y.w_gu), brows(m.b_gu, T));
@@ -1788,8 +1668,8 @@ static void trunk(RadCtx* c, const Model& m, const RadBatch* batch) {
             RAD_ISSUE(c, y.op_scale, brows(m.b_x, T), RAD_W(y.w_scalar), brows(m.b_x, T));
         }
 
-        /* The tap AFTER the scalar: HF's hidden_states[i + 1] is the decoder layer's return value,
-         * which has been multiplied by it. */
+        /* The tap comes after the layer scalar: HF's hidden_states[i + 1] is the decoder layer's
+         * return value, which includes it. */
         for (int t = 0; t < m.n_taps && y.op_tap; ++t) {
             if (m.tap_layer[t] != (int)li) continue;
             RAD_ISSUE(c, y.op_tap, brows(m.b_x, T),
@@ -1802,36 +1682,35 @@ static void trunk(RadCtx* c, const Model& m, const RadBatch* batch) {
 }
 
 /* ============================================================== the prefill overlap */
-/* A PREFILL CHUNK IN TWO SLICES, each slice's all-reduces on the second lane (rad_lane) beside the
- * other slice's compute. On gemma-4-26B-A4B at tp 4 on 4x R9700 the reductions were 47% of a
- * 20K-token prefill under --profile-ops: a layer reduces T x E after attention and both arms' 2T x
- * E after the feed-forward, at ~16.5 GB/s a rank on the link, against ~8 ms of compute a layer at
- * the average chunk. Run whole, the two take turns. Cut in two, a slice's reduction runs while the
- * other slice computes:
+/* A prefill chunk in two slices, each slice's all-reduces on the second lane (rad_lane) beside
+ * the other slice's compute. A layer reduces T x E after attention and 2T x E (both arms) after the
+ * feed-forward; at tp 4 on 4x R9700 the reductions were about half of a long prefill (~16.5 GB/s
+ * per rank on the link against ~8 ms of compute per layer). Run whole, compute and reduction
+ * alternate; cut in two, one slice reduces while the other computes:
  *
  *   lane 0  o(A) o(B) . nan(A) ff(A) . nan(B) ff(B) . jas(A) qkv(A) . jas(B) qkv(B) attn o(A) ..
  *   lane 1       ar_o(A)    ar_o(B)       ar_f(A)         ar_f(B)
  *
- * ATTENTION RUNS WHOLE: it reads every row's keys, and its batch bounds describe the whole step.
- * The rest is a row at a time -- the projections, the joins, both arms -- and so is the reduction,
- * which folds a word in fp32 in ascending rank order whichever message carries it.
+ * Attention runs whole: it reads every row's keys, and its batch bounds describe the whole step.
+ * Everything else (projections, joins, both arms, and the reduction, which folds each word in fp32
+ * in ascending rank order) is row-wise.
  *
- * THE SAME KERNELS, SO THE SAME BITS (core/runtime/ctx.h, the second lane's rule FOUR). A cut is
- * a whole number of routed passes from the step's first row, so the routed arm makes exactly the
- * passes the whole step makes, and both slices are at least one pass (2048 rows): above every row
- * band the projections, the joins, the activation and the reduction have -- the GEMM's at 16 and
- * 64, the reduction's one-shot edge at 524288 elements. None of those kernels' row results
- * depends on the row count, so the step's output is the whole step's.
+ * Same kernels, so same bits (core/runtime/ctx.h, the second lane's fourth rule). The cut is a
+ * whole number of routed passes from the first row, so the routed arm makes the same passes as the
+ * whole step, and both slices are at least one pass (2048 rows), above every row band of the
+ * projections, joins, activation and reduction (the GEMM's at 16 and 64, the reduction's one-shot
+ * edge at 524288 elements). No row result depends on the row count, so the output matches the
+ * whole step's.
  *
- * THE ORDER. Every reduction rides lane 1 behind a join from lane 0, which holds its producer;
- * lane 0 waits for lane 1 before the reduction's consumer. A join orders behind EVERYTHING its
- * lane has issued, so each wait goes in after the lane-0 work that does not need it and before
- * the next reduction is issued -- which is what fixes the issue order below. The embedding's
- * reduction stays on lane 0, ahead of everything lane 1 is first joined behind, so the
- * collectives keep one order on every rank; the runtime joins lane 1 back at the end of a step. */
+ * Ordering: each reduction rides lane 1 behind a join from lane 0, which holds its producer; lane 0
+ * waits for lane 1 before the reduction's consumer. A join orders behind everything its lane has
+ * issued, so each wait goes after the lane-0 work that does not need it and before the next
+ * reduction, which fixes the issue order below. The embedding's reduction stays on lane 0, before
+ * lane 1's first join, so the collectives keep one order on every rank; the runtime joins lane 1
+ * back at the end of the step. */
 
 /* The first row of slice B, or 0 for a step that runs whole: the whole number of routed passes
- * nearest half the step. Both slices are then at least one pass. */
+ * nearest half the step, so both slices are at least one pass. */
 static int64_t split_at(const Model& m, int64_t T) {
     if (!m.overlap || T < 2 * m.moe_rows) return 0;
     const int64_t P = m.moe_rows;
@@ -1858,8 +1737,8 @@ static void out_proj(RadCtx* c, const Model& m, const Layer& y, int64_t r0, int6
 }
 
 /* Rows [r0, r0 + n) from the attention join to the arms' partials, once those rows' attention
- * reduction is in. The slice's partials land in rows [2 r0, 2 r0 + 2n) of the join, dense then
- * routed, so its feed-forward reduction is one run. */
+ * reduction is done. The partials land in rows [2 r0, 2 r0 + 2n) of the join, dense then routed,
+ * so the slice's feed-forward reduction is one run. */
 static void arms(RadCtx* c, const Model& m, const Layer& y, int64_t T, int64_t r0, int64_t n) {
     const int64_t E = m.E, F = m.n_ff;
     if (y.op_join_r)
@@ -1879,8 +1758,8 @@ static void arms(RadCtx* c, const Model& m, const Layer& y, int64_t T, int64_t r
     routed(c, m, y, T, r0, n, 2 * r0 + n);
 }
 
-/* Rows [r0, r0 + n) of layer li's feed-forward join, once their reduction is in -- with the next
- * norm it writes -- and the drafter's taps of those rows. */
+/* Rows [r0, r0 + n) of layer li's feed-forward join (with the next norm it writes), once their
+ * reduction is done, and the drafter's taps of those rows. */
 static void join_ff(RadCtx* c, const Model& m, size_t li, int64_t r0, int64_t n) {
     const Layer& y = m.layers[li];
     const int64_t E = m.E;
@@ -1899,8 +1778,8 @@ static void trunk_overlap(RadCtx* c, const Model& m, const RadBatch* batch, int6
     const int64_t T = batch->n_tok, E = m.E;
     const int64_t a0 = 0, an = cut, b0 = cut, bn = T - cut;
     bool lanes_ok = true;
-    /* An all-reduce in place over `rows` rows of `buf` from `row`, on lane 1 behind everything
-     * lane 0 has issued -- its producer among it. */
+    /* An in-place all-reduce over `rows` rows of `buf` from `row`, on lane 1 behind everything
+     * lane 0 has issued, including its producer. */
     auto reduce = [&](rad_op op, rad_buf buf, int64_t row, int64_t rows) {
         lanes_ok = lanes_ok && rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK;
         RAD_ISSUE_N(c, op, rows * E, brow_slice(buf, row, rows, E), RAD_NONE);
@@ -1985,8 +1864,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
 }
 
 /* ============================================================== probe */
-/* DFlash proposes its whole block in one pass, so its depth is the block it was trained at less
- * the anchor, and nothing else: 15 for z-lab's Gemma 4 drafters (block_size 16). */
+/* DFlash proposes its whole block in one pass, so its depth is fixed at the trained block size
+ * minus the anchor: 15 for z-lab's Gemma 4 drafters (block_size 16). */
 static int probe(const RadModelMeta* meta, RadArchProbe* out) {
     if (!meta || !out) return RAD_E_INVAL;
     out->draft_depth = 0;
@@ -2003,10 +1882,9 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
 }
 
 /* ============================================================== the reply format
- * The model's, not this plugin's -- the thought channel, and calls written as a name and one
- * object in Gemma's dialect of JSON -- and shared with gemma4_bf16 (arch/rad_gemma4_chat.h). The
- * container's template is not visible from here (it lives in the vocab section, not the metadata),
- * so this answers for every Gemma 4 container. */
+ * Gemma 4's thought channel and calls written as a name and one object in Gemma's JSON dialect,
+ * shared with gemma4_bf16 (arch/rad_gemma4_chat.h). The container's template lives in the vocab
+ * section, not the metadata, so it is not visible here; this answers for every Gemma 4 container. */
 static const RadChatFormat* chat_format(const RadModelMeta*) { return gemma4_chat_format(); }
 
 }  /* namespace gemma4 */
diff --git a/arch/gemma4/gemma4_dflash.h b/arch/gemma4/gemma4_dflash.h
index 3fc58bc5..1e6e2e2f 100644
--- a/arch/gemma4/gemma4_dflash.h
+++ b/arch/gemma4/gemma4_dflash.h
@@ -2,11 +2,10 @@
  *
  * ============================== WHAT IT IS ==============================
  *
- * rad_block_dflash2.h WITHOUT THE TWO THINGS DFLASH2 ADDED: the per-layer dynamic convolutions
- * around attention and the feed-forward, and the candidate selector that walks a path through the
- * block. What is left is the original DFlash: a small Qwen3-shaped transformer that denoises one
- * anchor token plus `block - 1` mask tokens in ONE forward and reads every position's argmax off
- * the TARGET's lm_head.
+ * rad_block_dflash2.h without DFlash2's additions (the per-layer dynamic convolutions around
+ * attention and the feed-forward, and the candidate selector). The original DFlash is a small
+ * Qwen3-shaped transformer that denoises one anchor token plus `block - 1` mask tokens in one
+ * forward and takes every position's argmax from the target's lm_head.
  *
  *     context pass, one row a committed token:
  *         c = hidden_norm(fc(concat of the trunk's residual stream at target_layer_ids)))
@@ -17,57 +16,55 @@
  *         for each layer:
  *             h = input_layernorm(x)
  *             q, k, v = q_proj(h), k_proj(h), v_proj(h);  q_norm, k_norm;  rope;  kv_store
- *             x += o_proj(attention(q, cache))        sliding layers CAUSAL over a 2048 window,
- *                                                     the full layer NON-causal over everything
+ *             x += o_proj(attention(q, cache))        sliding layers causal over a 2048 window,
+ *                                                     the full layer non-causal over everything
  *             x += down(silu(gate(h')) * up(h')),  h' = post_attention_layernorm(x)
  *         x = norm(x)
- *         over the mask rows: logits = lm_head(x) [the TARGET's];  draft = argmax
+ *         over the mask rows: logits = lm_head(x) [the target's];  draft = argmax
  *
  * ============================== THE THREE GEMMA-SPECIFIC FACTS ==============================
  *
- * They are vLLM PR #41703's, and each one costs acceptance and nothing else when it is wrong --
- * every draft is verified against the trunk, so the model's output never depends on any of them.
+ * From vLLM PR #41703. Getting any of them wrong costs only acceptance, since every draft is
+ * verified against the trunk.
  *
- *   THE EMBEDDING IS SCALED. Gemma multiplies its token embedding by sqrt(hidden_size), stored as a
- *   bf16 (53.0 at 2816), and the drafter was trained reading the target's embedding module, which
+ *   The embedding is scaled. Gemma multiplies its token embedding by sqrt(hidden_size), stored as
+ *   bf16 (53.0 at 2816), and the drafter was trained through the target's embedding module, which
  *   applies it. `embed_lookup`'s `mult` carries it.
  *
- *   THE SLIDING LAYERS ARE CAUSAL AND THE FULL LAYER IS NOT. The checkpoint's `layer_types` names
- *   four sliding layers and one full one; the PR's own test pins `causal True` on the sliding
- *   layers and `False` on the full one. So this block declares TWO attention ops and issues the
- *   one each layer's type names.
+ *   The sliding layers are causal and the full layer is not. The checkpoint's `layer_types` names
+ *   four sliding layers and one full one, and the PR's test pins `causal True` on the sliding
+ *   layers and `False` on the full one, so this block declares two attention ops and issues the one
+ *   each layer's type names.
  *
- *   THE LOGITS ARE SOFT-CAPPED, and that is ignored on purpose: the draft is an argmax, and
- *   cap * tanh(x / cap) is strictly increasing, so it cannot move one.
+ *   The logits are soft-capped, which is deliberately ignored: the draft is an argmax, and
+ *   cap * tanh(x / cap) is strictly increasing.
  *
  * ============================== THE HEAD ==============================
  *
  * The target's own head, read in bf16 by an ordinary `gemm_nt` over the gathered mask rows. Gemma
- * ties it to the embedding, so it is the same weight the trunk's `embed_lookup` and `logits_gemm`
- * read: no extra bytes are stored. It is vocab-sharded with the trunk, so the top-1 runs over this
- * rank's slice and the ranks' candidates are merged exactly (`row_topk` at R = 2 -> `all_gather` ->
+ * ties it to the embedding, so it is the weight the trunk's `embed_lookup` and `logits_gemm` read
+ * and costs no extra bytes. It is vocab-sharded with the trunk: the top-1 runs over this rank's
+ * slice and the ranks' candidates merge exactly (`row_topk` at R = 2 -> `all_gather` ->
  * `pair_argmax`; R = 2 because the gather moves 16-byte rows, see kTopR).
  *
- * Reading the bf16 head every draft pass is the expensive way to do it -- 262144 x 2816 x 2 bytes
- * over the ranks, 566 us of a 26B-A4B decode step at tp 4 (--profile-ops, 4x R9700), the widest
- * read on the draft path. So where the CONTAINER holds a block-fp8 copy of the table under a name
- * of its own -- `dflash.draft_head.weight`, one checkpoint tensor and two logical weights, as
- * rad_block_dflash2.h does it, made by a recipe line
+ * The bf16 head (262144 x 2816 x 2 bytes) is the widest read on the draft path, about 566 us of a
+ * 26B-A4B decode step at tp 4 on 4x R9700. So where the container holds a block-fp8 copy of the
+ * table under its own name, `dflash.draft_head.weight` (one checkpoint tensor, two logical
+ * weights, as in rad_block_dflash2.h), made by the recipe line
  *
  *     dflash.draft_head.weight  rtn codes=fp8_e4m3 block=128x128 scale=bf16
  *
- * -- the head is `gemm_nt_q` over that copy at fp8a8, half the bytes, and the argmax is taken over
- * its coarser logits. Every draft is still verified, so the copy can change what is proposed and
- * never what is accepted; draft_n_accepted is what says whether it proposes worse. A container
- * without it, or with it in any other encoding, reads the bf16 table as before. The copy costs
- * half the table's bytes again, 176 MiB a rank at tp 4. No rerank against the bf16 table yet:
- * DFlash2's needs the target's head in fp8 or int8, which a tied Gemma head is not.
+ * the head is `gemm_nt_q` over that copy at fp8a8, half the bytes, with the argmax over its
+ * coarser logits. Drafts are still verified, so the copy can change proposals but never accepted
+ * text. Without the copy, or in another encoding, the bf16 table is read. The copy costs half the
+ * table's bytes again (176 MiB per rank at tp 4). There is no rerank against the bf16 table:
+ * DFlash2's rerank needs the target's head in fp8 or int8, which a tied Gemma head is not.
  *
  * ============================== THE LINEARS ARE FP8 ==============================
  *
- * The same as DFlash2 and for the same reason -- the drafter is read whole on every decode step --
- * so the container must be converted with a recipe that makes the six linears block fp8 (or
- * MXFP4). declare() refuses a bf16 one by name rather than letting the loader fail on a view.
+ * As in DFlash2, since the drafter is read whole on every decode step: the container must be
+ * converted with a recipe that makes the six linears block fp8 (or MXFP4). declare() refuses a bf16
+ * one by name rather than letting the loader fail on a view.
  */
 #ifndef GEMMA4_DFLASH_H
 #define GEMMA4_DFLASH_H
@@ -82,8 +79,8 @@ namespace gemma4 {
 
 using namespace rad::arch;
 
-/* Block fp8 as libr4d's fp8a8 GEMMs read it: fp8_e4m3 codes, a bf16 scale a 128x128 block, no
- * transform -- a recipe's `rtn codes=fp8_e4m3 block=128x128 scale=bf16`. */
+/* Block fp8 as libr4d's fp8a8 GEMMs read it: fp8_e4m3 codes, a bf16 scale per 128x128 block, no
+ * transform (a recipe's `rtn codes=fp8_e4m3 block=128x128 scale=bf16`). */
 inline bool block_fp8_128(const RadEncoding& e) {
     const RadEncPlane* sc = rad_enc_plane(&e, "scale");
     return rad_enc_is(&e, "affine") && e.n_planes == 2 && !e.transform[0] &&
@@ -96,7 +93,7 @@ struct Dflash1 {
 
     struct Config {
         int64_t n_taps = 0;      /* how many trunk layers `fc` concatenates */
-        int64_t block  = 0;      /* query rows a sequence: the anchor plus block - 1 masks */
+        int64_t block  = 0;      /* query rows per sequence: the anchor plus block - 1 masks */
         int64_t window = 0;      /* the sliding layers' window; 0 for none */
         int     full[MAX_LAYERS] = {};   /* 1: a full-attention (non-causal, unwindowed) layer */
         double  escale = 1.0;    /* the target's embedding scale, rounded as the target holds it */
@@ -114,13 +111,13 @@ struct Dflash1 {
         rad_buf attn = 0, atq = 0, ats = 0;    /* [qrows, q_dim] */
         rad_buf gate_up = 0;                   /* [qrows, 2 * n_ff] */
         rad_buf ffn = 0, ffq = 0, ffs = 0;     /* [qrows, n_ff] */
-        /* the head, one row a draft position */
+        /* the head, one row per draft position */
         rad_buf sel_h = 0;                     /* [srows, n_embd] */
         rad_buf selq = 0, sels = 0;            /* [srows, n_embd] e4m3 | f32, the fp8 head's */
         rad_buf dlog = 0;                      /* [srows, n_vocab on this rank] bf16 */
         rad_buf cand = 0, unary = 0;           /* [srows, kTopR] i32 | f32 -- this rank's best */
         rad_buf dpair = 0, dgath = 0;          /* [srows, kTopR, 2] | [srows, world * kTopR, 2] f32 */
-        rad_buf tokens = 0;                    /* [srows, 1] i32: THE DRAFT, pitch `steps` */
+        rad_buf tokens = 0;                    /* [srows, 1] i32: the draft, pitch `steps` */
     };
 
     Geom    g{};          /* the drafter's geometry */
@@ -133,7 +130,7 @@ struct Dflash1 {
 
     DenseFP8   w_fc{};
     rad_weight w_hnorm = 0, w_norm = 0;
-    rad_weight w_tok = 0;                     /* the TARGET's table: embedding AND head */
+    rad_weight w_tok = 0;                     /* the target's table: embedding and head */
     DenseFP8   w_dh{};                        /* its block-fp8 copy, the head where it is stored */
     bool       fp8_head = false;
     rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {};
@@ -146,10 +143,10 @@ struct Dflash1 {
 
     rad_op op_embed = 0, op_embed_ar = 0, op_qh = 0, op_qat = 0, op_qff = 0;
     rad_op op_anorm[MAX_LAYERS] = {}, op_fnorm[MAX_LAYERS] = {};
-    /* THE RESIDUAL ADD, THE NORM AND THE QUANTISER IN ONE LAUNCH where `rmsnorm_quant_fp8` is
-     * served (libr4d): op_anq[i] the attention input's -- layer 0's with no add, x as the
-     * embedding left it -- and op_fnq[i] the feed-forward input's. Zero where it is not, and the
-     * `add` / `rmsnorm` / `quant_act_fp8` chain is issued instead. */
+    /* The residual add, norm and quantiser in one launch where `rmsnorm_quant_fp8` is served
+     * (libr4d): op_anq[i] for the attention input (layer 0's without the add) and op_fnq[i] for
+     * the feed-forward input. Zero where not served; the `add` / `rmsnorm` / `quant_act_fp8` chain
+     * is issued instead. */
     rad_op op_anq[MAX_LAYERS] = {}, op_fnq[MAX_LAYERS] = {};
     rad_op op_qp[MAX_LAYERS] = {}, op_kp[MAX_LAYERS] = {}, op_vp[MAX_LAYERS] = {};
     rad_op op_op[MAX_LAYERS] = {}, op_qn[MAX_LAYERS] = {}, op_kn[MAX_LAYERS] = {};
@@ -158,10 +155,10 @@ struct Dflash1 {
     rad_op op_act = 0, op_ar = 0, op_add = 0, op_final = 0;
     rad_op op_gather = 0, op_qsel = 0, op_head = 0, op_topk = 0, op_dgather = 0, op_pick = 0;
 
-    /* CANDIDATES A RANK CONTRIBUTES under a sharded head. The draft needs one, but the gather moves
-     * whole 16-byte words a row and an (int32 id, f32 value) pair is 8 bytes, so R = 1 is refused at
-     * launch ("shape this kernel does not serve") -- the bound rad_block_mtp_hc.h states. Two pairs
-     * are one word; `pair_argmax` reduces the world * 2 of them to the global top-1. */
+    /* Candidates each rank contributes under a sharded head. The draft needs one, but the gather
+     * moves whole 16-byte words per row and an (int32 id, f32 value) pair is 8 bytes, so R = 1 is
+     * refused at launch (as rad_block_mtp_hc.h states). Two pairs make one word; `pair_argmax`
+     * reduces the world * 2 of them to the global top-1. */
     static constexpr int64_t kTopR = 2;
 
     static bool head_sharded(const Geom& g) { return vocab_head_sharded(g); }
@@ -175,9 +172,9 @@ struct Dflash1 {
 private:
     int64_t q_dim()  const { return g.n_head * g.head_dim; }
     int64_t kv_dim() const { return g.n_head_kv * g.head_dim; }
-    /* The six linears must be what the recipe made them. DenseFP8 declares E4M3 (or MXFP4) views
-     * whatever the container holds, and the loader's complaint about a bf16 weight read through an
-     * fp8 view names the view, not the missing recipe. */
+    /* The six linears must be quantised by the recipe. DenseFP8 declares E4M3 (or MXFP4) views
+     * whatever the container holds, and the loader's error for a bf16 weight read through an fp8
+     * view would name the view, not the missing recipe. */
     static int need_quantised(RadBuilder* b, const char* wn) {
         RadEncoding e{};
         if (!weight_enc(b, wn, &e) || e.n_planes <= 0) return RAD_OK;   /* nothing to ask yet */
@@ -246,8 +243,8 @@ inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
                             RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl);
         w_kn[i]    = decl_w(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i), RAD_F32, {g.head_dim},
                             RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl);
-        /* The declared names are rad_block_dflash2.h's, deliberately: the recipe that quantises a
-         * DFlash2 drafter's linears names exactly these, so one recipe serves both drafters. */
+        /* The declared names match rad_block_dflash2.h's, so one recipe quantises both
+         * drafters. */
         RAD_ARCH_TRY(w_q[i].declare(b, nm, nm.f("dflash.blk.%d.attn_q", i), qd, g.n_embd,
                                     RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl,
                                     { nm.ckpt("%s.layers.%d.self_attn.q_proj.weight", ck, i) }));
@@ -274,8 +271,8 @@ inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
     }
 
     /* ---------------------------------------------------------------- attention: two kinds
-     * Declared before either kv_store: `block_size` is read back off the resolved kernel. Both
-     * read the one KV group, so whichever resolves first answers for it. */
+     * Declared before either kv_store, which reads `block_size` back from the resolved kernel.
+     * Both read the one KV group, so whichever resolves first answers for it. */
     auto attn = [&](int causal, int64_t window) {
         return rw(b, RAD_OP(b, "attn_paged",
                      RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim),
@@ -366,10 +363,9 @@ inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
                    RAD_NOWEIGHTS),
                {w.ffn}, {w.ffq, w.ffs});
 
-    /* x's norm under `gain`, quantised into hq|hs, in one launch; with `add` the fused_add_rms_norm
-     * form, x += h first. The row is the chain's function exactly -- the norm of the bf16-rounded
-     * sum, the codes of the bf16-rounded norm (libr4d/r4d_rows.cpp) -- and a draft is verified
-     * whatever it is. */
+    /* x's norm under `gain`, quantised into hq|hs, in one launch; with `add`, the
+     * fused_add_rms_norm form (x += h first). It computes exactly the chain's result: the norm of
+     * the bf16-rounded sum and the codes of the bf16-rounded norm (libr4d/r4d_rows.cpp). */
     auto norm_quant = [&](rad_weight gain, bool add) -> rad_op {
         const rad_op h = RAD_OP(b, "rmsnorm_quant_fp8",
                                 RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
@@ -412,8 +408,8 @@ inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
                         {w.x}, {w.h});
         op_fnq[i] = norm_quant(w_fnorm[i], true);
         op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.hq, w.hs}, {w.gate_up});
-        /* The gate_up|silu|quant fold where it resolves, the pair where it does not --
-         * rad_block_dflash2.h's rule, band included. */
+        /* The gate_up|silu|quant fold where it resolves, else the pair (rad_block_dflash2.h's
+         * rule, band included). */
         {
             const int64_t hi = qrows < 64 ? qrows : 64;
             if (hi > 0 && !w_gu[i].mx) {
@@ -476,20 +472,20 @@ inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
                  {w.x}, {w.h});
 
     /* ---------------------------------------------------------------- the head
-     * The MASK rows -- offsets 1..block-1 of each block; the core names them through out_ids --
-     * gathered contiguous, projected onto THIS RANK's slice of the target's vocabulary, and the
-     * argmax taken. Sharded, each rank's best kTopR are reported as global ids with their logits,
-     * all-gathered, and reduced to the global top-1 by `pair_argmax`, ties to the lower id -- exact,
-     * since the global winner is its own shard's first. */
+     * The mask rows (offsets 1..block-1 of each block, named by out_ids) are gathered contiguous,
+     * projected onto this rank's slice of the target's vocabulary, and the argmax taken. Sharded,
+     * each rank reports its best kTopR as global ids with logits; these are all-gathered and
+     * reduced to the global top-1 by `pair_argmax` (ties to the lower id), which is exact since the
+     * global winner is its own shard's first. */
     op_gather = rw(b, RAD_OP(b, "gather_rows",
                       RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
                                  RAD_STR("dtype", g.dtype)),
                       RAD_NOWEIGHTS),
                   {w.h}, {w.sel_h});
-    /* THE FP8 COPY, where the container holds one (see the top of this file). The name map comes
-     * first -- it is how the encoding is looked up -- and a map whose weight is never declared is
-     * written by nothing: rad-convert walks the declared weights. The copy is row-sharded exactly
-     * as the table is, so this rank's rows are the same vocabulary slice and `vocab_off` holds. */
+    /* The fp8 copy, where the container holds one (see the file header). The name map comes first
+     * since it is how the encoding is looked up; rad-convert writes only declared weights. The
+     * copy is row-sharded like the table, so this rank's rows are the same vocabulary slice and
+     * `vocab_off` holds. */
     const char* dhn = nm.f("dflash.draft_head.weight");
     RAD_ARCH_TRY(map_copy(b, dhn, tok_src));
     RadEncoding he{};
@@ -530,7 +526,7 @@ inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
                                    RAD_STR("dtype", g.dtype)),
                         RAD_NOWEIGHTS),
                     {w.dlog}, {w.cand, w.unary, w.dpair});
-        /* ROW-INTERLEAVED, so one draft position's pairs from every rank land side by side. */
+        /* Row-interleaved, so one draft position's pairs from every rank land side by side. */
         op_dgather = rw(b, RAD_OP(b, "all_gather",
                            RAD_PARAMS(RAD_INT("world_size", g.world),
                                       RAD_INT("numel", srows * kTopR * 2), RAD_STR("dtype", "f32"),
diff --git a/arch/gemma4_bf16/CMakeLists.txt b/arch/gemma4_bf16/CMakeLists.txt
index 1a4f2317..4436f96e 100644
--- a/arch/gemma4_bf16/CMakeLists.txt
+++ b/arch/gemma4_bf16/CMakeLists.txt
@@ -1,6 +1,5 @@
-# A plugin like any other: built here inside radiance's tree, or on its own against an installed
-# radiance (`cmake -S arch/gemma4_bf16 -B build -DCMAKE_PREFIX_PATH=`) -- the same
-# rad_add_plugin either way (cmake/RadAddPlugin.cmake).
+# Built in radiance's tree, or standalone against an installed radiance
+# (`cmake -S arch/gemma4_bf16 -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake.
 if(NOT COMMAND rad_add_plugin)
   cmake_minimum_required(VERSION 3.21)
   project(gemma4_bf16 LANGUAGES CXX)
diff --git a/arch/gemma4_bf16/gemma4_bf16.cpp b/arch/gemma4_bf16/gemma4_bf16.cpp
index 7ffed45d..5a1345a4 100644
--- a/arch/gemma4_bf16/gemma4_bf16.cpp
+++ b/arch/gemma4_bf16/gemma4_bf16.cpp
@@ -1,14 +1,15 @@
-/* gemma4_bf16.cpp -- Gemma 4 dense, bf16, with its vision tower (gemma4_vision.h).
+/* gemma4_bf16.cpp -- Gemma 4 dense, bf16, with its vision tower (rad_block_gemma4_vision.h).
  *
- * Two attention classes over ONE residual stream, alternating by layer. A "sliding" layer is
+ * Two attention classes over one residual stream, alternating by layer. A "sliding" layer is
  * sliding-window attention over head_dim 256 with a v projection and standard RoPE; a "global"
  * layer is windowless attention over head_dim 512 with no v projection (k == v) and proportional
- * RoPE (the "head" ladder) over the partial rotary width. Every layer is GemmaRMSNorm -- x_hat *
- * (1 + w) -- with a SECOND norm on each projection's output before its residual, a weightless RMS
- * on the value, and a GELU (not SwiGLU) feed-forward. The final logits are soft-capped to
+ * RoPE (the "head" ladder) over the partial rotary width. Norms are plain RMSNorm, x_hat * w (see
+ * declare), with a second norm on each projection's output before its residual, a weightless RMS
+ * norm on the value, and a GELU (not SwiGLU) feed-forward. The final logits are soft-capped to
  * cap * tanh(x / cap).
  */
 #include 
+#include 
 #include 
 
 #include 
@@ -18,61 +19,35 @@
 #include 
 #include 
 
-#include "gemma4_vision.h"
-
 namespace gemma4_bf16 {
 
 using namespace rad::arch;
 
-/* ---- container geometry RadModelMeta does not name. Both spellings are accepted: a .rad
- * converted from the HF safetensors carries the flat HuggingFace keys and one converted from a
- * GGUF carries llama.cpp's. */
-static long long g4_i(const RadModelMeta* m, const char* bare, long long dflt) {
-    long long v = rad_meta_geti(m, bare, dflt);
-    if (v == dflt) v = rad_meta_geti(m, (std::string("text_config.") + bare).c_str(), dflt);
-    return v;
-}
-static double g4_f(const RadModelMeta* m, const char* bare, double dflt) {
-    double v = rad_meta_getf(m, bare, dflt);
-    if (v == dflt) v = rad_meta_getf(m, (std::string("text_config.") + bare).c_str(), dflt);
-    return v;
-}
-
-/* THE RESIDUAL JUNCTIONS AS ONE OP EACH. A w4a8 block opens with rmsnorm -> quant_act_i8 and closes
+/* Residual junctions as one op each. A w4a8 block opens with rmsnorm -> quant_act_i8 and closes
  * with rmsnorm (post) -> add -> [scale], so between two blocks the stream runs five single-row
- * dispatches -- the previous block's post-norm, the add, the layer scalar, this block's norm and
- * its quantiser. libr4d's `rmsnorm_quant_i8` is that chain in one dispatch, byte-identical to it,
- * and q, k and v read one quantised pair instead of three; `qkv_norm_rope` does the same for the
- * attention prologue's five ops, `gelu_mul_quant_i8` for down's input, and at two ranks
- * `ar_rmsnorm_quant_i8` folds the all-reduce in front of each junction into it. A kernel set without
- * an op keeps that op's chain. */
+ * dispatches: the previous post-norm, the add, the layer scalar, this block's norm and its
+ * quantiser. libr4d's `rmsnorm_quant_i8` is that chain in one byte-identical dispatch, and q, k and
+ * v read one quantised pair instead of three. `qkv_norm_rope` does the same for the attention
+ * prologue's five ops, `gelu_mul_quant_i8` for down's input, and at two ranks
+ * `ar_rmsnorm_quant_i8` also folds in the all-reduce before each junction. A kernel set without an
+ * op keeps that op's chain. */
 
-/* layer_types is optional. When present it must name EVERY layer "full_attention" or
- * "sliding_attention"; when absent the (l + 1) % interval == 0 fallback is the model card. */
+/* layer_types is optional. When present it must name every layer "full_attention" or
+ * "sliding_attention"; when absent, layer l is global when (l + 1) % interval == 0. */
 static int g4_parse_types(const char* lt, int64_t n, std::vector& is_global) {
-    is_global.assign((size_t)n, -1);
-    size_t got = 0;
-    const char* p = lt;
-    while (*p) {
-        if (!std::strncmp(p, "full_attention", 14)) {
-            if (got >= (size_t)n) return RAD_E_INVAL;
-            is_global[got++] = 1; p += 14;
-        } else if (!std::strncmp(p, "sliding_attention", 17)) {
-            if (got >= (size_t)n) return RAD_E_INVAL;
-            is_global[got++] = 0; p += 17;
-        } else {
-            ++p;   /* separators: whitespace, quotes, [ ] , and / */
-        }
+    RAD_ARCH_TRY(parse_layer_kinds("gemma4", lt, {"full_attention"}, "sliding_attention",
+                                   &is_global));
+    if ((int64_t)is_global.size() != n) {
+        fprintf(stderr, "radiance: gemma4: layer_types names %zu layers and the model has %lld\n",
+                is_global.size(), (long long)n);
+        return RAD_E_INVAL;
     }
-    if (got != (size_t)n) return RAD_E_INVAL;
-    for (size_t i = 0; i < is_global.size(); ++i) if (is_global[i] < 0) return RAD_E_INVAL;
     return RAD_OK;
 }
 
 static int g4_schedule(const RadModelMeta* m, int64_t n, int64_t interval,
                        std::vector& is_global) {
-    const char* lt = rad_meta_gets(m, "layer_types", rad_meta_gets(m, "text_config.layer_types", nullptr));
-    is_global.assign((size_t)n, 0);
+    const char* lt = meta_text_gets(m, "layer_types", nullptr);
     if (lt && *lt) {
         RAD_ARCH_TRY(g4_parse_types(lt, n, is_global));
     } else {
@@ -81,14 +56,15 @@ static int g4_schedule(const RadModelMeta* m, int64_t n, int64_t interval,
                     (long long)interval);
             return RAD_E_INVAL;
         }
-        for (int64_t l = 0; l < n; ++l) is_global[(size_t)l] = ((l + 1) % interval == 0) ? 1 : 0;
+        is_global.resize((size_t)n);
+        for (int64_t l = 0; l < n; ++l) is_global[(size_t)l] = is_full_attention(l, interval);
     }
     return RAD_OK;
 }
 
-/* A LINEAR'S WEIGHT IS ITS CHECKPOINT'S `X.weight`. Google's bf16 release names it so; its CT-INT4
- * (QAT) release ships `X.weight_packed` and `X.weight_scale`, which the checkpoint reader imports
- * as `X.weight` (core/format/checkpoint.h, CT-INT4), so the name map is the same for both. */
+/* A linear's weight is its checkpoint's `X.weight`. Google's CT-INT4 (QAT) release ships
+ * `X.weight_packed` and `X.weight_scale`, which the checkpoint reader imports as `X.weight`
+ * (core/format/checkpoint.h), so one name map serves both releases. */
 
 /* The two attention classes share the residual stream and the FFN but differ in head geometry,
  * the value path and the RoPE. The main Geom (from geom_from) is the slider; the global class is
@@ -105,31 +81,23 @@ struct ClassGeom {
     int64_t gqa()    const { return n_head / n_head_kv; }
 };
 
-/* ---- one linear, plain bf16 or w4a8. The recipe re-quantises the GEMM weights to int4 codes
- * with an f16 scale per [1 x 128] (group 128); a weight no rule matches stays bf16. This probes
- * the weight's encoding and chooses the op by it: `gemm_nt` for a plain bf16 weight, `gemm_nt_q`
- * at dtype w4a8 for the codes + their scale. w4a8 is the int8-activation grid: it reads an int8
- * activation + an f32 per-row scale, which the model's bf16 activation has to be quantised into.
- * The quantiser is declared here (quant_act_i8) over the activation's bf16 plane and writes the
- * int8 pair (q8, s8) the GEMM reads -- in the GEMM's fragment byte order, with one scale per row.
- * quant_act_i8g (row-major, a per-(row,group) scale) is i8a8's producer, not this one's; pairing
- * it with w4a8 is the compounding-into-inf seed of the all-NaN logits (see the declare comment).
- * w4a16 was tried and is the WRONG grid: its row declares an f16 activation and
- * its launcher never checks the operand dtype, so feeding it the model's bf16 bits reinterprets
- * them as f16 -- a magnitude-compressed garbage stream (bf16 0.1 -> 1.45, 1.0 -> 1.875), finite
- * nonsense that propagates through the residual. The name map is made here, before the weight is
- * asked what it is (Builder::finish() needs the map entry before the declaration). */
+/* ---- one linear, plain bf16 or w4a8. The recipe quantises GEMM weights to int4 codes with an
+ * f16 scale per [1 x 128]; a weight no rule matches stays bf16. The weight's encoding picks the
+ * op: `gemm_nt` for plain bf16, `gemm_nt_q` at w4a8 for codes + scale. w4a8 reads an int8
+ * activation and an f32 per-row scale, written by a quant_act_i8 declared here over the bf16
+ * activation, in the GEMM's fragment byte order. Not quant_act_i8g (row-major, per-(row, group)
+ * scale; i8a8's producer), and not w4a16, whose row expects an f16 activation and does not check
+ * the operand dtype, so bf16 bits would be misread as f16. The name map is made before the weight
+ * is queried (Builder::finish() needs the map entry before the declaration). */
 struct G4Linear {
     rad_weight w = 0, ws = 0;   /* the codes + scale (w4a8), or the single bf16 weight */
     rad_op     op = 0, op_q = 0;   /* the quantised GEMM and, for w4a8, its activation quantiser */
     rad_buf    q8 = 0, s8 = 0;     /* the int8 pair (i8 codes + f32 row scale) the quantiser writes */
     int64_t    N = 0, K = 0;
     bool       quant = false;   /* true: w4a8 */
-    /* READS ANOTHER LINEAR'S INT8 PAIR. q, k and v quantise the same norm output into the same
-     * per-row grid (quant_act_i8 over [T, n_embd]), so three quantisers write three identical
-     * pairs. With `in_from` set at declare this linear reads that linear's pair and declares no
-     * quantiser of its own: the GEMM's input bytes are the same bytes, one dispatch instead of
-     * three. */
+    /* Reads another linear's int8 pair. q, k and v quantise the same norm output on the same
+     * per-row grid, so with `in_from` set at declare this linear reads that linear's pair and
+     * declares no quantiser of its own: one dispatch instead of three. */
     bool       shared_in = false;
 
     int  declare(RadBuilder* b, Names& nm, const Geom& g, const char* base,
@@ -156,8 +124,8 @@ inline int G4Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char
     else                RAD_ARCH_TRY(map_concat(b, wn, src, 0));
     RadEncoding enc{};
     const bool known = weight_enc(b, wn, &enc);
-    /* a builder with no model behind it (a test, a synthetic tool) answers RAD_E_NOTFOUND, and a
-     * weight declared there is read as plain in its declared dtype -- the bf16 path. */
+    /* A builder with no model behind it (a test, a synthetic tool) answers RAD_E_NOTFOUND, and
+     * the weight is read as plain bf16. */
     const bool plain = !known || (rad_enc_is(&enc, "plain") && enc.n_planes == 1 &&
                                   enc.plane[0].dtype == RAD_BF16);
     int64_t parts[RAD_MAX_ROW_PARTS] = {0};
@@ -174,17 +142,14 @@ inline int G4Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char
         return op ? RAD_OK : RAD_E_INVAL;
     }
 
-    /* a w4 weight: i4 codes + an f16 scale per [1 x 128]. The GEMM (gemm_nt_q at w4a8) reads an
-     * int8 activation + an f32 per-row scale, which the model's bf16 activation has to be quantised
-     * into, so the quantiser (quant_act_i8g) is declared over the activation's bf16 plane `a` and
-     * writes the int8 pair (q8, s8) the GEMM reads. The codes + scale layout is byte-for-byte the
-     * w4a16 one -- the container serves unchanged; only the op dtype and the activation producer
-     * differ. */
+    /* A w4 weight: i4 codes and an f16 scale per [1 x 128]. gemm_nt_q at w4a8 reads an int8
+     * activation and an f32 per-row scale, so a quantiser over the bf16 plane `a` writes the int8
+     * pair (q8, s8). The codes + scale layout is the same as w4a16's, so containers serve
+     * unchanged. */
     const RadEncPlane* sc = rad_enc_plane(&enc, "scale");
-    /* An 8-bit weight on the same grid -- i8 codes, an f16 scale per [1 x 128] -- is the same
-     * pair at twice the radix: gemm_nt_q at w8a8 reads the identical int8 activation + per-row
-     * scale the w4a8 GEMM reads, so the quantiser declaration is shared. It is how a recipe keeps
-     * a linear the int4 grid hurts (the attention, down_proj) closer to the checkpoint. */
+    /* An 8-bit weight on the same grid (i8 codes, f16 scale per [1 x 128]): gemm_nt_q at w8a8
+     * reads the same int8 activation and per-row scale as w4a8, so the quantiser is shared. A
+     * recipe uses it for linears int4 hurts (attention, down_proj). */
     const uint32_t cdt = known && enc.n_planes > 0 ? enc.plane[0].dtype : 0;
     const bool w4 = known && rad_enc_is(&enc, "affine") && enc.n_planes == 2 && !enc.transform[0] &&
                     (cdt == RAD_I4 || cdt == RAD_I8) && enc.plane[0].block[1] == 1 &&
@@ -209,23 +174,14 @@ inline int G4Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char
             s8 = decl_b(b, nm.f("%s.s8", base), RAD_F32, { g.max_tok, 1 });
         }
         if (!q8 || !s8) return RAD_E_INVAL;
-        /* quant_act_i8, NOT quant_act_i8g: the w4a8 GEMM's A fragment reads a byte-shuffled plane
-         * (r4d_gemm_w4a8_nt_m64.hip:46-52, "the quantiser writes it") and applies an f32 per-ROW
-         * scale at the store (:61-63), so the producer must be the fragment-order per-row quantiser
-         * (r4d_quant_act_i8.hip:1-2). quant_act_i8g writes PLAIN ROW-MAJOR codes with a
-         * per-(row,group) scale (r4d_rows.cpp:2043-2046, "what the int8 trunk GEMMs (i8a8) read")
-         * -- pairing it with this GEMM shuffles the dot and broadcasts the wrong scale grid, the
-         * compounding-into-inf seed of the all-NaN logits. */
-        /* group=K, NOT 128: the host quantisers (libref/libavx) are per-`group` -- one f32 scale
-         * per group of `group` elements -- while the device one (r4d_quant_act_i8) is per-ROW and
-         * ignores `group` in this 3-operand form (it only reads it in the asum form). group=K makes
-         * the host ngrp=1 (one scale per row, the [M,1] buffer the arch declares) and is a no-op on
-         * the device, so the same declaration is self-consistent on both backends. group=128 left
-         * the host quantiser refusing the [M,1] scale (it wants [M, K/128]). */
+        /* quant_act_i8, not quant_act_i8g: the w4a8 and w8a8 GEMMs read codes in the int8 WMMA's
+         * step order with one f32 scale a row (docs/OPS.md). quant_act_i8g writes row-major codes
+         * with a scale per (row, group) for i8a8; paired with these GEMMs it produces NaN logits.
+         * `group` only sizes the optional code sums, which this symmetric grid does not take. */
         if (!shared_in)
             op_q = rw(b, RAD_OP(b, "quant_act_i8",
                         RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", K),
-                                   RAD_INT("group", K), RAD_STR("dtype", "bf16")),
+                                   RAD_INT("group", 128), RAD_STR("dtype", "bf16")),
                         RAD_NOWEIGHTS),
                     { a }, { q8, s8 });
         op = rw(b, RAD_OP(b, "gemm_nt_q",
@@ -246,11 +202,9 @@ inline int G4Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char
 
 inline void G4Linear::step(RadCtx* c, rad_buf a, rad_buf y, int64_t T) const {
     if (quant) {
-        /* quantise the bf16 activation into the int8 pair (fragment order + a per-row scale), then
-         * read the pair. The scale plane is one f32 per row, browsed at T rows like the codes.
-         * quant_act_i8's schema is 4 operands -- x, q, scale, asum -- and `asum` (the per-group row
-         * sums the asymmetric grids subtract) is absent on this symmetric grid, so it is passed as
-         * a null tensor, not dropped: operands are positional (issue.cpp). */
+        /* Quantise the bf16 activation into the int8 pair, then run the GEMM. quant_act_i8 takes
+         * x, q, scale, asum; `asum` (the per-group row sums asymmetric grids subtract) is absent on
+         * this symmetric grid and passed as a null tensor, since operands are positional. */
         if (!shared_in)
             RAD_ISSUE_N(c, op_q, T, brows(a, T), brows(q8, T), brows(s8, T), RAD_NONE);
         gemm(c, y, T);
@@ -293,16 +247,13 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
     g = geom; cls = cgeo; layer = l; kv = group; w = wire;
     const int64_t qd = cls.q_dim(), kvd = cls.kv_dim();
 
-    /* the norms: always bf16 (no rule matches them), name map first. */
+    /* The norms: always bf16 (no rule matches them), name map first. */
     RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l),      nm.ckpt("%s.%lld.input_layernorm.weight",   pre, (long long)l)));
     RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l),    nm.ckpt("%s.%lld.self_attn.q_norm.weight",   pre, (long long)l)));
     RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k_norm.weight", l),    nm.ckpt("%s.%lld.self_attn.k_norm.weight",   pre, (long long)l)));
     RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_post_norm.weight", l), nm.ckpt("%s.%lld.post_attention_layernorm.weight", pre, (long long)l)));
-    /* declared bf16, not f32: the checkpoint holds them bf16 and no rule re-quantises them, so an
-     * f32 declaration would widen them at load -- and a widened weight cannot be served from the
-     * mapped tier, which the whole layer group is pinned to because the w4a16 GEMM has no device
-     * kernel for the M > 64 prefill band. Reading the gain in its own (bf16) dtype is identical:
-     * the widening was a lossless upcast of the same bf16 value. */
+    /* Declared bf16, not f32: the checkpoint holds them bf16, and a widened weight cannot be
+     * served from the mapped tier. Reading the gain as bf16 gives the same values. */
     w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_BF16, {g.n_embd},
                     RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
     w_qn = decl_w(b, nm.f("blk.%d.attn_q_norm.weight", l), RAD_BF16, {cls.head_dim},
@@ -312,7 +263,7 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
     w_post = decl_w(b, nm.f("blk.%d.attn_post_norm.weight", l), RAD_BF16, {g.n_embd},
                      RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
 
-    /* the GEMM weights: bf16 or w4a8, probed by G4Linear. */
+    /* The GEMM weights: bf16 or w4a8, probed by G4Linear. */
     RAD_ARCH_TRY(ln_q.declare(b, nm, g, nm.f("blk.%d.attn_q", l),
                               { nm.ckpt("%s.%lld.self_attn.q_proj.weight", pre, (long long)l) },
                               qd, g.n_embd, RAD_SHARD_ROW, grp_layer(l), w.h, w.q));
@@ -335,8 +286,8 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
                   RAD_WEIGHTS(w_norm)),
                  {w.x}, {w.h});
 
-    /* Gemma normalises the value with a WEIGHTLESS rms (the checkpoint has no v_norm gain). A
-     * sliding class normalises v in place; a k_eq_v class derives v from the RAW k into its own
+    /* Gemma normalises the value with a weightless RMS norm (the checkpoint has no v_norm gain).
+     * A sliding class normalises v in place; a k_eq_v class derives v from the raw k into its own
      * buffer, which must happen before k_norm rewrites k. */
     op_vn = rw(b, RAD_OP(b, "rmsnorm_p",
                RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * cls.n_head_kv), RAD_INT("n", cls.head_dim),
@@ -365,13 +316,10 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
                             RAD_STR("ladder", cls.head_ladder ? "head" : "rotary")),
                  RAD_NOWEIGHTS),
                 {w.q}, {w.q});
-    /* The rope kernel serves the fused QKV row and requires n_head > 0 (it rotates n_head +
-     * n_head_kv heads over a row of (n_head + 2*n_head_kv)*head_dim). The K heads are a separate
-     * buffer, so the K-only form is expressed as a Q-only form over the K heads: n_head is the
-     * count of heads to rotate (here n_head_kv) and n_head_kv is 0, so the row is
-     * n_head_kv*head_dim -- exactly the K buffer's width. RoPE is identical for Q and K (same
-     * theta, same positions), so this is the reference's separate K rope (llama.cpp ggml_rope_ext
-     * over the K buffer). */
+    /* The rope kernel rotates n_head + n_head_kv heads of a fused QKV row and requires
+     * n_head > 0. K is a separate buffer, so it is rotated as a Q-only form over the K heads:
+     * n_head = n_head_kv and n_head_kv = 0, a row of n_head_kv*head_dim, exactly K's width. Q and K
+     * share theta and positions, so this matches the reference's separate K rope. */
     op_rk = rw(b, RAD_OP(b, "rope",
                   RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim),
                              RAD_INT("n_head", cls.n_head_kv), RAD_INT("n_head_kv", 0),
@@ -381,10 +329,9 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
                   RAD_NOWEIGHTS),
                  {w.k}, {w.k});
 
-    /* Gemma 4 scores Q.K WITHOUT the 1/sqrt(head_dim) factor: both the HF reference
-     * (Gemma4TextAttention: self.scaling = 1.0) and the vLLM oracle use scaling = 1.0 --
-     * the learnable q/k RMSNorm weights absorb the scaling, so no extra 1/sqrt(d) is applied.
-     * attn_paged's default is 1/sqrt(head_dim), so pass 1.0 explicitly to match the reference. */
+    /* Gemma 4 scores Q.K without the 1/sqrt(head_dim) factor (HF Gemma4TextAttention and vLLM
+     * use scaling = 1.0; the q/k norm gains absorb it). attn_paged defaults to 1/sqrt(head_dim),
+     * so 1.0 is passed explicitly. */
     op_attn = rw(b, RAD_OP(b, "attn_paged",
                    RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim),
                               RAD_INT("gqa", cls.gqa()), RAD_INT("causal", 1), RAD_INT("window", cls.window),
@@ -395,12 +342,13 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
                    RAD_NOWEIGHTS),
                   {w.q}, {w.attn});
 
-    /* THE PROLOGUE AS ONE OP: libr4d's `qkv_norm_rope` is rmsnorm_p + rmsnorm + rmsnorm + rope +
-     * rope over the three separate projections, byte-identical to them, one workgroup a (token,
-     * head). Declared beside the unfused five and used only where it resolves; a multi-component
-     * or YaRN rotary keeps the five. */
-    if (!g.rope_mc && g.yarn.factor == 0.0f)
-        op_qnr = rw(b, RAD_OP(b, "qkv_norm_rope",
+    /* The prologue as one op: libr4d's `qkv_norm_rope` is rmsnorm_p + rmsnorm + rmsnorm + rope +
+     * rope over the three projections, byte-identical, one workgroup per (token, head). Declared
+     * beside the unfused five and used only where it resolves; a multi-component or YaRN rotary
+     * keeps the five, as does an engine whose libraries do not declare it (CPU-only), where asking
+     * for it would stop the declare. */
+    if (!g.rope_mc && g.yarn.factor == 0.0f && rad_op_declared(b, "qkv_norm_rope")) {
+        op_qnr = RAD_OP(b, "qkv_norm_rope",
                       RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim),
                                  RAD_INT("n_head", cls.n_head), RAD_INT("n_head_kv", cls.n_head_kv),
                                  RAD_F64("theta", cls.theta), RAD_F64("eps", g.eps),
@@ -409,8 +357,11 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
                                  RAD_STR("ladder", cls.head_ladder ? "head" : "rotary"),
                                  RAD_F64("wadd", g.wadd_qk), RAD_INT("v_from_k", cls.has_v ? 0 : 1),
                                  RAD_STR("dtype", g.dtype)),
-                      RAD_WEIGHTS(w_qn, w_kn)),
-                    {w.q, w.k, w.v}, {w.q, w.k, w.v});
+                      RAD_WEIGHTS(w_qn, w_kn));
+        /* A k_eq_v class derives v from the raw k: v is written, never read. */
+        op_qnr = cls.has_v ? rw(b, op_qnr, {w.q, w.k, w.v}, {w.q, w.k, w.v})
+                           : rw(b, op_qnr, {w.q, w.k}, {w.q, w.k, w.v});
+    }
 
     op_kv = rw(b, RAD_OP(b, "kv_store",
                 RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim),
@@ -420,7 +371,7 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
                 RAD_NOWEIGHTS),
                 {w.k, w.v}, {});
 
-    /* o_proj is column-sharded: the rank's partial sum is reduced FIRST, then normed. */
+    /* o_proj is column-sharded: the rank's partial sum is reduced first, then normed. */
     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),
@@ -429,7 +380,7 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
                    RAD_NOWEIGHTS),
                   {w.h}, {w.h});
 
-    /* the SECOND residual: the (reduced) attention output is itself normed before the add. */
+    /* The second norm: the reduced attention output is normed before the residual add. */
     op_post = 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", g.wadd), RAD_STR("dtype", g.dtype)),
@@ -466,7 +417,7 @@ void Gemma4Attn::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool ta
         RAD_ISSUE(c, op_qnr, brows(w.q, T), brows(w.k, T), brows(w.v, T), rope_posmc(g, batch, T),
                   RAD_W(w_qn), RAD_W(w_kn));
     } else {
-        /* normalise v FIRST: on a k_eq_v class v is derived from the raw k, before k_norm rewrites it. */
+        /* Normalise v first: on a k_eq_v class v derives from the raw k, before k_norm rewrites it. */
         RAD_ISSUE_N(c, op_vn, T * cls.n_head_kv, brows(cls.has_v ? w.v : w.k, T), brows(w.v, T));
         RAD_ISSUE_N(c, op_qn, T * cls.n_head,    brows(w.q, T), RAD_W(w_qn), brows(w.q, T));
         RAD_ISSUE_N(c, op_kn, T * cls.n_head_kv, brows(w.k, T), RAD_W(w_kn), brows(w.k, T));
@@ -486,9 +437,8 @@ void Gemma4Attn::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool ta
                 brows(w.attn, T));
 
     ln_o.step(c, w.attn, w.h, T);
-    /* THE ALL-REDUCE BEFORE THE POST-NORM. o_proj is column-sharded, so each rank holds a PARTIAL
-     * sum here; the norm is of the whole output (HF, and vLLM's RowParallelLinear, reduce first).
-     * Normed per rank and then summed is sum_r rmsnorm(p_r), not rmsnorm(sum_r p_r). */
+    /* The all-reduce comes before the post-norm: o_proj is column-sharded, so each rank holds a
+     * partial sum, and the norm is of the whole output (sum_r rmsnorm(p_r) != rmsnorm(sum_r p_r)). */
     if (op_ar && !(tail_fused && ar_fused)) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
     if (tail_fused) return;
     RAD_ISSUE_N(c, op_post, T, brows(w.h, T), RAD_W(w_post), brows(w.h, T));
@@ -516,17 +466,17 @@ struct Gemma4Mlp {
 int Gemma4Mlp::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire, const char* pre) {
     g = geom; layer = l; w = wire;
 
-    /* the norms: always bf16 (no rule matches them), name map first. */
+    /* The norms: always bf16 (no rule matches them), name map first. */
     RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ffn_norm.weight", l), nm.ckpt("%s.%lld.pre_feedforward_layernorm.weight", pre, (long long)l)));
     RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ffn_post_norm.weight", l), nm.ckpt("%s.%lld.post_feedforward_layernorm.weight", pre, (long long)l)));
-    /* bf16, not f32: same reason as the attention norms -- an f32 declaration widens them and a
-     * widened weight cannot be served from the mapped tier the whole layer group is pinned to. */
+    /* bf16, not f32, as for the attention norms: a widened weight cannot be served from the
+     * mapped tier. */
     w_norm = decl_w(b, nm.f("blk.%d.ffn_norm.weight", l), RAD_BF16, {g.n_embd},
                     RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
     w_post = decl_w(b, nm.f("blk.%d.ffn_post_norm.weight", l), RAD_BF16, {g.n_embd},
                      RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
 
-    /* the GEMM weights: bf16 or w4a8, probed by G4Linear. gate_up is the gate|up fusion. */
+    /* The GEMM weights: bf16 or w4a8, probed by G4Linear. gate_up is the gate|up fusion. */
     RAD_ARCH_TRY(ln_gu.declare(b, nm, g, nm.f("blk.%d.ffn_gate_up", l),
                                { nm.ckpt("%s.%lld.mlp.gate_proj.weight", pre, (long long)l),
                                  nm.ckpt("%s.%lld.mlp.up_proj.weight", pre, (long long)l) },
@@ -545,7 +495,7 @@ int Gemma4Mlp::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}, {w.ffn});
-    if (ln_down.quant && !ln_down.shared_in)
+    if (ln_down.quant && !ln_down.shared_in && rad_op_declared(b, "gelu_mul_quant_i8"))
         op_gq = rw(b, RAD_OP(b, "gelu_mul_quant_i8",
                      RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_ff), RAD_STR("dtype", g.dtype)),
                      RAD_NOWEIGHTS),
@@ -594,8 +544,8 @@ void Gemma4Mlp::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tai
 }
 
 /* ---- one residual junction as one op: [post-norm of the branch `x`, the add into `res`, the
- * layer scalar,] the next block's norm and its int8 quantiser (libr4d `rmsnorm_quant_i8`). `res`
- * null is the plain form, the norm of `x` itself -- the first block's entry. */
+ * layer scalar,] the next block's norm and its int8 quantiser (libr4d `rmsnorm_quant_i8`). With
+ * `res` null it is the plain norm of `x`, the first block's entry. */
 struct G4Junction {
     rad_op     op = 0;
     rad_op     op_ar = 0;   /* the same with the two-rank exact all-reduce of `x` in front, or 0 */
@@ -612,16 +562,19 @@ struct G4Junction {
                                RAD_F64("wadd", g.wadd) };
         const rad_weight ws[3] = { w, wp, sc };
         const int nw = sc ? 3 : (wp ? 2 : 1);
-        op = rad_decl_op(b, "rmsnorm_quant_i8", p, (int)(sizeof p / sizeof p[0]), ws, nw);
-        if (!op) return RAD_OK;   /* not resolved: the caller keeps the unfused chain */
+        /* Not declared by any loaded library (CPU-only) or not resolved: the caller keeps the
+         * unfused chain. */
+        if (rad_op_declared(b, "rmsnorm_quant_i8"))
+            op = rad_decl_op(b, "rmsnorm_quant_i8", p, (int)(sizeof p / sizeof p[0]), ws, nw);
+        if (!op) return RAD_OK;
         const rad_buf rd[2] = { x, res };
         const rad_buf wr[3] = { q8, s8, res };
         rad_op_reads (b, op, rd, res ? 2 : 1);
         rad_op_writes(b, op, wr, res ? 3 : 2);
-        /* THE ALL-REDUCE IN FRONT, at two ranks on the exact wire: `x` is then a rank's partial sum
-         * of a column-sharded linear, the message as well as the input. A deployment that allows
-         * the lossy wire keeps the standalone all-reduce, which may pick it. */
-        if (res && g.world == 2 && g.wire_exact) {
+        /* With the all-reduce in front, at two ranks on the exact wire: `x` is then a rank's
+         * partial sum of a column-sharded linear. With the lossy wire allowed, the standalone
+         * all-reduce is kept, since it may choose that wire. */
+        if (res && g.world == 2 && g.wire_exact && rad_op_declared(b, "ar_rmsnorm_quant_i8")) {
             const RadParam pa[] = { RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
                                     RAD_F64("eps", g.eps), RAD_INT("world_size", g.world),
                                     RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd) };
@@ -643,42 +596,39 @@ struct G4Junction {
 
 /* ==================================================================== the assistant head
  *
- * GEMMA 4'S DRAFT HEAD, the "assistant" (Gemma4AssistantForCausalLM), merged under `draft.` by
- * `rad-convert --draft-model `. Read off the checkpoint and three reference
- * implementations -- transformers' modeling_gemma4_assistant.py with its candidate generator,
- * vLLM's gemma4_mtp.py with spec_decode/gemma4.py, and llama.cpp's gemma4-assistant.cpp:
+ * Gemma 4's draft head, the "assistant" (Gemma4AssistantForCausalLM), merged under `draft.` by
+ * `rad-convert --draft-model `. From the checkpoint and three references:
+ * transformers' modeling_gemma4_assistant.py with its candidate generator, vLLM's gemma4_mtp.py
+ * with spec_decode/gemma4.py, and llama.cpp's gemma4-assistant.cpp:
  *
  *     x  = pre_projection( concat( E_trunk[tok] * sqrt(n_trunk), h_trunk ) )        2*n_trunk -> n
  *     x  = the head's layers over x (31B: sliding, sliding, sliding, full)
  *     hd = norm(x)
- *     logits = lm_head(hd)       the head's OWN table, tied to its embed_tokens; no soft-cap
+ *     logits = lm_head(hd)       the head's own table, tied to its embed_tokens; no soft-cap
  *     h' = post_projection(hd)                                                       n -> n_trunk
  *
- * `h_trunk` is the trunk's FINAL-NORMED hidden state -- the trunk lm_head's input -- and `E_trunk`
- * the trunk's embedding table, scaled the way the trunk scales it. The head's own embed_tokens is
- * its lm_head and nothing else (vLLM swaps the trunk's table in for the input side). The
- * concatenation is the embedding FIRST, then the hidden state; all three references agree.
+ * `h_trunk` is the trunk's final-normed hidden state (the trunk lm_head's input) and `E_trunk` the
+ * trunk's embedding table, scaled as the trunk scales it. The head's own embed_tokens serves only
+ * as its lm_head (vLLM uses the trunk's table on the input side). The concatenation is embedding
+ * first, then hidden state; all three references agree.
  *
- * A LAYER IS A TRUNK LAYER WITH THE KEY AND VALUE TAKEN AWAY: q_proj, the per-head q norm, the
- * rotary of its class, attention over the TRUNK'S cache at scale 1, o_proj, the same four
- * plain-gain norms, the GELU feed-forward and the per-layer scalar. Each layer reads the LAST trunk
- * layer of its own class -- the sliding ones the last sliding layer, the full one the last full
- * layer, 58 and 59 on the 31B (vLLM's _setup_gemma4_kv_sharing). So the head's q heads and the
- * trunk's kv heads must be the same geometry, and declare checks that they are.
+ * A head layer is a trunk layer without key and value: q_proj, the per-head q norm, its class's
+ * rotary, attention over the trunk's cache at scale 1, o_proj, the same four plain-gain norms, the
+ * GELU feed-forward and the per-layer scalar. Each layer reads the last trunk layer of its class
+ * (58 and 59 on the 31B; vLLM's _setup_gemma4_kv_sharing), so the head's q heads and the trunk's
+ * kv heads must share geometry, which declare checks.
  *
- * IT KEEPS NO CACHE OF ITS OWN, and that is what the core is told (rad_drafter_shared_kv): no
- * history pass, one row a drafting sequence, every round at the committed position over the
- * committed context. Round 1's row embeds the token the trunk chose and continues from the trunk's
- * hidden state; round r embeds round r-1's proposal and continues from its h'. What the head
- * proposed reaches the next round through those two and nothing else -- which is the whole design
- * of the head, not a shortcut taken here.
+ * The head keeps no cache of its own (rad_drafter_shared_kv): no history pass, one row per
+ * drafting sequence, every round at the committed position over the committed context. Round 1
+ * embeds the token the trunk chose and continues from the trunk's hidden state; round r embeds
+ * round r-1's proposal and continues from its h'. Those two are the only path from one round to
+ * the next, by design of the head.
  *
- * THE TENSOR-PARALLEL SPLIT IS THE TRUNK'S: q heads row-sharded over the ranks, so each rank's
- * queries meet its own share of the trunk's kv heads; o_proj and the feed-forward down projection
- * column-sharded, each followed by an all-reduce BEFORE its post-norm (the norm of a partial sum is
- * not the partial of a norm). The two projections and every norm are replicated: they read and
- * write the replicated stream, and a split would cost an all-reduce to save a few MiB. The lm_head
- * is vocab-sharded like the trunk's and goes through the same sampler chain, greedy. */
+ * Tensor-parallel split as the trunk's: q heads row-sharded, so each rank's queries meet its share
+ * of the trunk's kv heads; o_proj and the feed-forward down projection column-sharded, each
+ * followed by an all-reduce before its post-norm. The two projections and every norm are
+ * replicated, since they read and write the replicated stream. The lm_head is vocab-sharded like
+ * the trunk's and goes through the same sampler chain, greedy. */
 /* Where the head's rows sit for the rotary, relative to the committed position
  * (rad_drafter_shared_kv), and the depth `--num-speculative-tokens auto` takes. */
 static constexpr int kHeadPosOffset = 0;
@@ -702,7 +652,7 @@ struct Gemma4Head {
     int64_t n = 0;          /* the head's width (1024 on the 31B) */
     int64_t n_trunk = 0;    /* the trunk's width, which the two projections join */
     int64_t n_ff = 0;       /* this rank's share of the feed-forward */
-    int64_t rows = 0;       /* the most rows one pass carries: one a drafting sequence */
+    int64_t rows = 0;       /* the most rows one pass carries: one per drafting sequence */
     double  softcap = 0.0;  /* 0: none, which is what the 31B's head says */
     std::vector layers;
 
@@ -721,18 +671,6 @@ struct Gemma4Head {
     void step(RadCtx* c, const RadBatch* batch) const;
 };
 
-/* A `draft.` key under the head's text config, where Gemma4AssistantConfig nests every dimension,
- * or at the top of it. */
-static long long hd_i(const RadModelMeta* m, const char* k, long long d) {
-    long long v = rad_meta_geti(m, (std::string("draft.text_config.") + k).c_str(), -0x7FFFFFFFll);
-    return v != -0x7FFFFFFFll ? v : rad_meta_geti(m, (std::string("draft.") + k).c_str(), d);
-}
-static double hd_f(const RadModelMeta* m, const char* k, double d) {
-    const double nan = std::nan("");
-    double v = rad_meta_getf(m, (std::string("draft.text_config.") + k).c_str(), nan);
-    return std::isnan(v) ? rad_meta_getf(m, (std::string("draft.") + k).c_str(), d) : v;
-}
-
 /* Does the container carry an assistant head at all? */
 static bool has_assistant(const RadModelMeta* m) {
     const char* a = rad_meta_gets(m, "draft.architectures", "");
@@ -751,23 +689,23 @@ int Gemma4Head::declare(RadBuilder* b, Names& nm, const RadModelMeta* meta, cons
     w_tok = tok_embd;
 
     /* ---- the head's own geometry, and what it must share with the trunk's. */
-    n       = hd_i(meta, "hidden_size", 0);
+    n       = meta_text_geti(meta, "hidden_size", 0, "draft.");
     n_trunk = rad_meta_geti(meta, "draft.backbone_hidden_size", 0);
-    const long long n_l      = hd_i(meta, "num_hidden_layers", 0);
-    const long long n_h      = hd_i(meta, "num_attention_heads", 0);
-    const long long n_kv     = hd_i(meta, "num_key_value_heads", 0);
-    const long long n_kv_g   = hd_i(meta, "num_global_key_value_heads", n_kv);
-    const long long head_s   = hd_i(meta, "head_dim", 0);
-    const long long head_g   = hd_i(meta, "global_head_dim", head_s);
-    const long long ff       = hd_i(meta, "intermediate_size", 0);
-    const long long win      = hd_i(meta, "sliding_window", 0);
-    const long long vocab    = hd_i(meta, "vocab_size", 0);
+    const long long n_l      = meta_text_geti(meta, "num_hidden_layers", 0, "draft.");
+    const long long n_h      = meta_text_geti(meta, "num_attention_heads", 0, "draft.");
+    const long long n_kv     = meta_text_geti(meta, "num_key_value_heads", 0, "draft.");
+    const long long n_kv_g   = meta_text_geti(meta, "num_global_key_value_heads", n_kv, "draft.");
+    const long long head_s   = meta_text_geti(meta, "head_dim", 0, "draft.");
+    const long long head_g   = meta_text_geti(meta, "global_head_dim", head_s, "draft.");
+    const long long ff       = meta_text_geti(meta, "intermediate_size", 0, "draft.");
+    const long long win      = meta_text_geti(meta, "sliding_window", 0, "draft.");
+    const long long vocab    = meta_text_geti(meta, "vocab_size", 0, "draft.");
     const long long ordered  = rad_meta_geti(meta, "draft.use_ordered_embeddings", 0);
-    const double    eps      = hd_f(meta, "rms_norm_eps", 0.0);
-    const double    theta_s  = hd_f(meta, "rope_parameters.sliding_attention.rope_theta", 0.0);
-    const double    theta_g  = hd_f(meta, "rope_parameters.full_attention.rope_theta", 0.0);
-    double          prf      = hd_f(meta, "rope_parameters.full_attention.partial_rotary_factor", -1.0);
-    softcap = hd_f(meta, "final_logit_softcapping", 0.0);
+    const double    eps      = meta_text_getf(meta, "rms_norm_eps", 0.0, "draft.");
+    const double    theta_s  = meta_text_getf(meta, "rope_parameters.sliding_attention.rope_theta", 0.0, "draft.");
+    const double    theta_g  = meta_text_getf(meta, "rope_parameters.full_attention.rope_theta", 0.0, "draft.");
+    double          prf      = meta_text_getf(meta, "rope_parameters.full_attention.partial_rotary_factor", -1.0, "draft.");
+    softcap = meta_text_getf(meta, "final_logit_softcapping", 0.0, "draft.");
     if (!(prf > 0.0)) prf = 1.0;
 
     if (n <= 0 || n_l <= 0 || n_h <= 0 || ff <= 0 || !(eps > 0.0)) {
@@ -776,9 +714,9 @@ int Gemma4Head::declare(RadBuilder* b, Names& nm, const RadModelMeta* meta, cons
                 (long long)n, n_l, n_h, ff, eps);
         return RAD_E_INVAL;
     }
-    /* IT READS THE TRUNK'S CACHE, so everything the cache's shape depends on must agree: the two
-     * head widths, the two kv head counts and the window. A head that disagrees was trained beside
-     * another trunk, and its attention would read keys that are not the ones it learned against. */
+    /* The head reads the trunk's cache, so everything the cache's shape depends on must agree:
+     * the two head widths, the two kv head counts and the window. A head that disagrees was trained
+     * with another trunk. */
     if (n_trunk != trunk.n_embd || vocab != trunk.n_vocab_all || head_s != cs.head_dim ||
         head_g != cg.head_dim || n_kv != cs.n_head_kv * trunk.world ||
         n_kv_g != cg.n_head_kv * trunk.world || win != cs.window) {
@@ -792,7 +730,7 @@ int Gemma4Head::declare(RadBuilder* b, Names& nm, const RadModelMeta* meta, cons
                 (long long)trunk.n_embd, (long long)trunk.n_vocab_all);
         return RAD_E_INVAL;
     }
-    /* THE QUERIES MUST ROTATE AS THE TRUNK'S KEYS DID, or q.k measures the wrong distance. */
+    /* The queries must rotate as the trunk's keys did, or q.k measures the wrong distance. */
     const int64_t rot_g = (int64_t)(head_g * prf + 0.5);
     if (theta_s != cs.theta || theta_g != cg.theta || rot_g != cg.n_rot) {
         fprintf(stderr, "radiance: gemma4 assistant: its rotary (theta %g / %g, %lld of %lld global "
@@ -802,9 +740,8 @@ int Gemma4Head::declare(RadBuilder* b, Names& nm, const RadModelMeta* meta, cons
                 (long long)cg.n_rot);
         return RAD_E_INVAL;
     }
-    /* CENTROID MASKING (use_ordered_embeddings) scores a top-k of vocabulary clusters instead of
-     * the whole head. The 31B's head does not use it, and nothing here implements it; refusing is
-     * better than a head that scores every token while its checkpoint expects a mask. */
+    /* Centroid masking (use_ordered_embeddings) scores a top-k of vocabulary clusters instead of
+     * the whole head. The 31B's head does not use it and it is not implemented, so it is refused. */
     if (ordered) {
         fprintf(stderr, "radiance: gemma4 assistant: use_ordered_embeddings (centroid-masked logits) "
                         "is not implemented\n");
@@ -853,8 +790,8 @@ int Gemma4Head::declare(RadBuilder* b, Names& nm, const RadModelMeta* meta, cons
 
     /* ---- the entry: the trunk's hidden state into the right half of `c`, the trunk's scaled
      * embedding into the left. A history pass gathers the hidden state from the trunk's rows; a
-     * round copies the head's own h' from the round before. Both write the half in place: a
-     * gather and a cast read their destination's row pitch off the operand. */
+     * round copies the head's own h' from the previous round. Both write the half in place, since
+     * gather and cast take the destination's row pitch from the operand. */
     op_hsrc = rw(b, RAD_OP(b, "gather_rows",
                    RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n_trunk), RAD_STR("dtype", g.dtype)),
                    RAD_NOWEIGHTS),
@@ -885,12 +822,35 @@ int Gemma4Head::declare(RadBuilder* b, Names& nm, const RadModelMeta* meta, cons
                   {b_e}, {b_c});
     if (!op_hsrc || !op_hcopy || !op_embed || !op_ecopy) return RAD_E_INVAL;
 
-    /* pre_projection: the joined row to the head's width. Replicated: it reads and writes the
-     * replicated stream. */
+    /* pre_projection: the joined row to the head's width. Replicated, like the stream it reads
+     * and writes. */
     RAD_ARCH_TRY(ln_pre.declare(b, nm, g, nm.f("mtp.pre_proj"), { nm.ckpt("draft.pre_projection.weight") },
                                 n, 2 * n_trunk, RAD_SHARD_NONE, grp_layer((int)(base + n_l)),
                                 b_c, b_x));
 
+    /* The head's n-wide norm (plain gain), residual add and all-reduce. */
+    auto norm = [&](rad_weight w, rad_buf x, rad_buf y) {
+        return rw(b, RAD_OP(b, "rmsnorm",
+                     RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps),
+                                RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)),
+                     RAD_WEIGHTS(w)),
+                  {x}, {y});
+    };
+    auto add = [&]() {
+        return rw(b, RAD_OP(b, "add",
+                     RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("dtype", g.dtype)),
+                     RAD_NOWEIGHTS),
+                  {b_x, b_h}, {b_x});
+    };
+    auto all_reduce = [&]() {
+        return rw(b, RAD_OP(b, "all_reduce",
+                     RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", n, rows * n),
+                                RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
+                                RAD_INT("min_bytes", g.wire_min_bytes)),
+                     RAD_NOWEIGHTS),
+                  {b_h}, {b_h});
+    };
+
     /* ---- the layers. */
     layers.resize((size_t)n_l);
     for (int64_t l = 0; l < n_l; ++l) {
@@ -948,11 +908,7 @@ int Gemma4Head::declare(RadBuilder* b, Names& nm, const RadModelMeta* meta, cons
                                        { nm.ckpt("%s.%lld.mlp.down_proj.weight", pre, (long long)l) },
                                        n, n_ff, RAD_SHARD_COL, grp_layer(gl), b_ffn, b_h));
 
-        L.op_norm = rw(b, RAD_OP(b, "rmsnorm",
-                         RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps),
-                                    RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)),
-                         RAD_WEIGHTS(L.w_norm)),
-                       {b_x}, {b_h});
+        L.op_norm = norm(L.w_norm, b_x, b_h);
         L.op_qn = rw(b, RAD_OP(b, "rmsnorm",
                        RAD_PARAMS(RAD_RANGE("M", 1, rows * L.cls.n_head), RAD_INT("n", L.cls.head_dim),
                                   RAD_F64("eps", eps), RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)),
@@ -966,9 +922,9 @@ int Gemma4Head::declare(RadBuilder* b, Names& nm, const RadModelMeta* meta, cons
                                   RAD_STR("ladder", L.cls.head_ladder ? "head" : "rotary")),
                        RAD_NOWEIGHTS),
                      {L.q}, {L.q});
-        /* ONE QUERY ROW A SEQUENCE over the trunk's cache, at scale 1 like the trunk's. The
-         * context is the committed positions (the core's doing: rad_drafter_shared_kv), so the
-         * decode band is the only band there is. */
+        /* One query row per sequence over the trunk's cache, at scale 1 like the trunk. The
+         * context is the committed positions (rad_drafter_shared_kv), so only the decode band
+         * exists. */
         L.op_attn = rw(b, RAD_OP(b, "attn_paged",
                          RAD_PARAMS(RAD_RANGE("q_len", 1, 1), RAD_INT("head_dim", L.cls.head_dim),
                                     RAD_INT("gqa", L.cls.gqa()), RAD_INT("causal", 1),
@@ -978,47 +934,17 @@ int Gemma4Head::declare(RadBuilder* b, Names& nm, const RadModelMeta* meta, cons
                                     RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
                          RAD_NOWEIGHTS),
                        {L.q}, {L.attn});
-        if (g.world > 1)
-            L.op_ar = rw(b, RAD_OP(b, "all_reduce",
-                            RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", n, rows * n),
-                                       RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
-                                       RAD_INT("min_bytes", g.wire_min_bytes)),
-                            RAD_NOWEIGHTS),
-                         {b_h}, {b_h});
-        L.op_post = rw(b, RAD_OP(b, "rmsnorm",
-                         RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps),
-                                    RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)),
-                         RAD_WEIGHTS(L.w_post)),
-                       {b_h}, {b_h});
-        L.op_add = rw(b, RAD_OP(b, "add",
-                        RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("dtype", g.dtype)),
-                        RAD_NOWEIGHTS),
-                      {b_x, b_h}, {b_x});
-        L.op_fnorm = rw(b, RAD_OP(b, "rmsnorm",
-                          RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps),
-                                     RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)),
-                          RAD_WEIGHTS(L.w_fnorm)),
-                        {b_x}, {b_h});
+        if (g.world > 1) L.op_ar = all_reduce();
+        L.op_post  = norm(L.w_post, b_h, b_h);
+        L.op_add   = add();
+        L.op_fnorm = norm(L.w_fnorm, b_x, b_h);
         L.op_act = rw(b, RAD_OP(b, "gelu_mul",
                         RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n_ff), RAD_STR("dtype", g.dtype)),
                         RAD_NOWEIGHTS),
                       {b_gu}, {b_ffn});
-        if (g.world > 1)
-            L.op_far = rw(b, RAD_OP(b, "all_reduce",
-                             RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", n, rows * n),
-                                        RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
-                                        RAD_INT("min_bytes", g.wire_min_bytes)),
-                             RAD_NOWEIGHTS),
-                          {b_h}, {b_h});
-        L.op_fpost = rw(b, RAD_OP(b, "rmsnorm",
-                          RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps),
-                                     RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)),
-                          RAD_WEIGHTS(L.w_fpost)),
-                        {b_h}, {b_h});
-        L.op_fadd = rw(b, RAD_OP(b, "add",
-                         RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("dtype", g.dtype)),
-                         RAD_NOWEIGHTS),
-                       {b_x, b_h}, {b_x});
+        if (g.world > 1) L.op_far = all_reduce();
+        L.op_fpost = norm(L.w_fpost, b_h, b_h);
+        L.op_fadd  = add();
         L.op_scale = rw(b, RAD_OP(b, "scale",
                           RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("dtype", g.dtype)),
                           RAD_WEIGHTS(L.w_scalar)),
@@ -1034,18 +960,13 @@ int Gemma4Head::declare(RadBuilder* b, Names& nm, const RadModelMeta* meta, cons
     RAD_ARCH_TRY(map_copy(b, nm.f("mtp.output.weight"), nm.ckpt("draft.model.embed_tokens.weight")));
     w_norm = decl_w(b, nm.f("mtp.output_norm.weight"), RAD_BF16, {n}, RAD_ACCESS_PER_TOKEN,
                     RAD_SHARD_NONE, grp_layer((int)(base + n_l)));
-    /* VOCAB-SHARDED, LIKE THE TRUNK'S: the draft's logits go through the same sampler chain, which
-     * merges the ranks' candidate sets, so a rank holds its own slice of the vocabulary. Declared
-     * at its codes' dtype: bf16 as Google ships it, or int8 / block fp8 where a recipe makes it so,
-     * and the logits_gemm kernel that reads that encoding serves it. It is the largest read of a
-     * round, and a draft is only a proposal: the trunk verifies every token with its own head. */
+    /* Vocab-sharded like the trunk's: the draft's logits go through the same sampler chain, which
+     * merges the ranks' candidates. Declared at its codes' dtype (bf16 as shipped, or int8 / block
+     * fp8 where a recipe makes it so), selecting the matching logits_gemm kernel. It is a round's
+     * largest read, and quantising it only affects proposals, which the trunk verifies. */
     w_lm = decl_w(b, nm.f("mtp.output.weight"), weight_codes_dtype(b, nm.f("mtp.output.weight"), RAD_BF16),
                   {g.n_vocab, n}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_layer((int)(base + n_l)));
-    op_norm = rw(b, RAD_OP(b, "rmsnorm",
-                   RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps),
-                              RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)),
-                   RAD_WEIGHTS(w_norm)),
-                 {b_x}, {b_hd});
+    op_norm = norm(w_norm, b_x, b_hd);
     op_logits = rw(b, RAD_OP(b, "logits_gemm",
                      RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n_vocab", g.n_vocab),
                                 RAD_INT("n_embd", n), RAD_STR("dtype", g.dtype)),
@@ -1058,9 +979,9 @@ int Gemma4Head::declare(RadBuilder* b, Names& nm, const RadModelMeta* meta, cons
                       RAD_NOWEIGHTS),
                     {logits}, {logits});
     if (!op_norm || !op_logits || (softcap > 0.0 && !op_cap)) return RAD_E_INVAL;
-    /* post_projection LAST: h' is the next round's input, and the op that reads it (op_hcopy) is
-     * the head's first. Declared here, its life runs the whole head, so no op of a pass can be laid
-     * over it before the round after has read it. */
+    /* post_projection last: h' is the next round's input, read by the head's first op
+     * (op_hcopy). Declared here, its buffer lives across the whole head, so nothing in a pass can
+     * overwrite it before the next round reads it. */
     RAD_ARCH_TRY(ln_post.declare(b, nm, g, nm.f("mtp.post_proj"), { nm.ckpt("draft.post_projection.weight") },
                                  n_trunk, n, RAD_SHARD_NONE, grp_layer((int)(base + n_l)),
                                  b_hd, b_hn));
@@ -1073,14 +994,14 @@ int Gemma4Head::declare(RadBuilder* b, Names& nm, const RadModelMeta* meta, cons
     return RAD_OK;
 }
 
-/* One pass. The batch is the one the scheduler staged for a head with no cache of its own: one row
- * a drafting sequence, at the committed position, its context ending there. */
+/* One pass, over the batch staged for a head with no cache of its own: one row per drafting
+ * sequence, at the committed position, with the context ending there. */
 void Gemma4Head::step(RadCtx* c, const RadBatch* batch) const {
     const int64_t T = batch->n_tok;
     if (T <= 0) return;
     if (batch->draft_pass < 0) {
-        /* Every row of the pass is a drafting row: that is what rad_drafter_shared_kv asked the
-         * scheduler for. Anything else is a batch built for a head with a cache of its own. */
+        /* Every row must be a drafting row, as rad_drafter_shared_kv requested; anything else
+         * was built for a head with its own cache. */
         if (batch->n_draft_out != T || batch->n_out != T) {
             rad_step_fail(c, "the gemma4 assistant head was handed a history pass that is not one row "
                              "a drafting sequence; it keeps no cache of its own and drafts from that "
@@ -1138,9 +1059,10 @@ struct Layer {
     Gemma4Mlp  mlp{};
     rad_weight w_scalar = 0;   /* the per-layer [1] residual scalar, `cur = cur * scalar` */
     rad_op     op_scale = 0;
-    /* the fused junctions (see THE RESIDUAL JUNCTIONS above): attention -> this layer's feed-forward, and this layer's
-     * feed-forward -> the next layer's attention, scalar included. The last layer has no j_ma: its
-     * stream goes to the final norm, which feeds the lm_head and not a quantiser. */
+    /* The fused junctions (see "Residual junctions" above): attention -> this layer's
+     * feed-forward, and this layer's feed-forward -> the next layer's attention, scalar included.
+     * The last layer has no j_ma: its stream goes to the final norm, which feeds the lm_head, not
+     * a quantiser. */
     G4Junction j_am{}, j_ma{};
 };
 
@@ -1168,10 +1090,10 @@ struct Model {
     Gemma4Head head{};
     bool       have_head = false;
 
-    /* The vision tower (gemma4_vision.h), declared when the container carries one and the
-     * deployment serves media; `op_mm` writes its rows over the placeholders' embeddings. */
-    Vision     vis{};
-    rad_op     op_mm = 0;
+    /* The vision tower (rad_block_gemma4_vision.h), declared when the container carries one and
+     * the deployment serves media; `op_mm` writes its rows over the placeholders' embeddings. */
+    Gemma4Vision vis{};
+    rad_op       op_mm = 0;
 
     G4Junction j0{};       /* the first block's entry: norm + quantiser of the embedding stream */
     bool       fuse = false;
@@ -1199,24 +1121,23 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     Names& nm = m.nm;
 
     /* ---- geometry RadModelMeta does not name. */
-    const int64_t kv_g_all    = g4_i(meta, "num_global_key_value_heads", 0);
-    const int64_t head_g      = g4_i(meta, "global_head_dim", 0);
-    const int64_t sliding_win = g4_i(meta, "sliding_window", 0);
-    const int64_t kv_shared   = g4_i(meta, "num_kv_shared_layers", 0);
-    const int64_t interval    = g4_i(meta, "full_attention_interval", 0);
-    /* Whether the global layers read V from K: 31B's do (attention_k_eq_v), and then they have no
-     * v_proj. A checkpoint that does not say is refused rather than guessed at -- the wrong
-     * guess either asks for weights that are not there or ignores ones that are. */
-    const long long k_eq_v    = g4_i(meta, "attention_k_eq_v", -1);
+    const int64_t kv_g_all    = meta_text_geti(meta, "num_global_key_value_heads", 0);
+    const int64_t head_g      = meta_text_geti(meta, "global_head_dim", 0);
+    const int64_t sliding_win = meta_text_geti(meta, "sliding_window", 0);
+    const int64_t kv_shared   = meta_text_geti(meta, "num_kv_shared_layers", 0);
+    const int64_t interval    = meta_text_geti(meta, "full_attention_interval", 0);
+    /* Whether the global layers read V from K (attention_k_eq_v; the 31B's do, and have no
+     * v_proj). A checkpoint that does not say is refused rather than guessed. */
+    const long long k_eq_v    = meta_text_geti(meta, "attention_k_eq_v", -1);
     if (k_eq_v != 0 && k_eq_v != 1) {
         fprintf(stderr, "radiance: gemma4: the config does not say whether the global layers read "
                         "V from K (attention_k_eq_v)\n");
         return RAD_E_INVAL;
     }
-    const double  theta_s     = g4_f(meta, "rope_parameters.sliding_attention.rope_theta", 0.0);
-    const double  theta_g     = g4_f(meta, "rope_parameters.full_attention.rope_theta", 0.0);
-    const double  softcap     = g4_f(meta, "final_logit_softcapping", 0.0);
-    double        prf         = g4_f(meta, "rope_parameters.full_attention.partial_rotary_factor", -1.0);
+    const double  theta_s     = meta_text_getf(meta, "rope_parameters.sliding_attention.rope_theta", 0.0);
+    const double  theta_g     = meta_text_getf(meta, "rope_parameters.full_attention.rope_theta", 0.0);
+    const double  softcap     = meta_text_getf(meta, "final_logit_softcapping", 0.0);
+    double        prf         = meta_text_getf(meta, "rope_parameters.full_attention.partial_rotary_factor", -1.0);
 
     if (head_g <= 0 || kv_g_all <= 0) {
         fprintf(stderr, "radiance: gemma4: global_head_dim %lld / num_global_key_value_heads %lld; both required\n",
@@ -1247,11 +1168,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     int64_t kv_g = 0;
     if (divide_or_fail(kv_g_all, g.world, "num_global_key_value_heads", &kv_g) < 0) return RAD_E_INVAL;
 
-    /* Plain RMSNorm: x_hat * w, on every norm including the post-projection ones. Gemma 4
-     * (unlike Gemma 2/3) does NOT use the (1 + w) form: the vLLM 0.27.1 oracle (which serves
-     * this checkpoint correctly) uses the stock RMSNorm (weight init 1.0), HF transformers'
-     * Gemma4RMSNorm multiplies by the weight with no +1 (weight init 1.0), and llama.cpp's
-     * gemma4 uses LLM_NORM_RMS with no load-time offset. wadd=0.0 = the plain form. */
+    /* Plain RMSNorm, x_hat * w, on every norm including the post-projection ones. Unlike
+     * Gemma 2/3, Gemma 4 does not use the (1 + w) form: vLLM's stock RMSNorm, HF's Gemma4RMSNorm
+     * (weight init 1.0) and llama.cpp's LLM_NORM_RMS all multiply by the weight alone. */
     g.wadd    = 0.0f;
     g.wadd_qk = 0.0f;
     const float final_wadd = 0.0f;
@@ -1262,8 +1181,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     int n_global = 0;
     for (int v : is_global) n_global += v;
 
-    /* the slider comes off geom_from (head_dim 256, 16 kv heads, full rotation, theta_s); the global
-     * class is built from the container head. */
+    /* The sliding class comes from geom_from (head_dim 256, 16 kv heads, full rotation, theta_s);
+     * the global class is built from the container header. */
     m.cs.n_head = g.n_head;      m.cs.n_head_kv = g.n_head_kv; m.cs.head_dim = g.head_dim;
     m.cs.n_rot  = g.head_dim;    m.cs.window = sliding_win;    m.cs.theta = theta_s;
     m.cs.scale  = g.rope_scale;  m.cs.head_ladder = false;     m.cs.has_v = true;
@@ -1309,21 +1228,19 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     m.w_tok = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, g.n_embd},
                      RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
     /* bf16, not f32: the model group is pinned to the mapped tier (token_embd's embed_lookup is
-     * host-only), so an f32-declared output_norm would widen and fail to serve from the mapping. */
+     * host-only), and a widened output_norm could not be served from the mapping. */
     m.w_out = decl_w(b, nm.f("output_norm.weight"), RAD_BF16, {g.n_embd},
                       RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
-    /* DECLARED AT ITS CODES' DTYPE, as the assistant head's lm_head is: bf16 as the checkpoint ships
-     * it, or int8 / block fp8 where a recipe (`--quant output.weight=...`) makes it so, and the
-     * logits_gemm kernel for that encoding serves it. At a decode step it is the largest single read
-     * of the trunk (n_vocab x n_embd a rank), so its encoding is a direct share of the step. */
+    /* Declared at its codes' dtype, like the assistant head's lm_head: bf16 as shipped, or int8 /
+     * block fp8 where a recipe (`--quant output.weight=...`) makes it so, selecting the matching
+     * logits_gemm kernel. It is the trunk's largest single read at decode (n_vocab x n_embd per
+     * rank). */
     m.w_lm  = decl_w(b, nm.f("output.weight"), weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16),
                      {g.n_vocab, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
 
-    /* The embedding is scaled by sqrt(n_embd) at the LOOKUP, not baked into the table (the
-     * reference's build_inp_embd and HF's ScaledWordEmbedding both do it there), and the
-     * checkpoint's table is plain -- so the scale rides the op and the table stays tied to the
-     * head's. Absent it, the residual stream carries a 73x-too-small token signal and the first
-     * layer's scale-invariant norm hides nothing downstream. */
+    /* The embedding is scaled by sqrt(n_embd) at the lookup, not in the table (as in llama.cpp's
+     * build_inp_embd and HF's ScaledWordEmbedding), so the plain table stays tied to the head.
+     * Without it the token signal in the residual stream would be ~73x too small. */
     m.op_embed = rw(b, RAD_OP(b, "embed_lookup",
                     RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd),
                                RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
@@ -1338,17 +1255,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                                           RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
                                RAD_NOWEIGHTS),
                           {m.b_x}, {m.b_x});
-    /* An image's rows over its placeholders' embeddings, after the (all-reduced) lookup and
-     * before the first block reads the stream: the reference scales the token embeddings by
-     * sqrt(n_embd) and scatters the image features in unscaled. */
-    if (Vision::present(meta) && ctx->max_enc_patches > 0)
+    /* An image's rows overwrite its placeholders' embeddings after the (all-reduced) lookup and
+     * before the first block: the reference scales token embeddings by sqrt(n_embd) and scatters
+     * the image features in unscaled. */
+    if (Gemma4Vision::present(meta) && ctx->max_enc_patches > 0)
         m.op_mm = rw(b, RAD_OP(b, "scatter_rows",
                                RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
                                           RAD_STR("dtype", "bf16")),
                                RAD_NOWEIGHTS),
                      {m.b_x}, {m.b_x});
 
-    /* ---- the layers. This loop is the model card. */
+    /* ---- the layers. */
     Gemma4Attn::Wire sw{}; sw.x = m.b_x; sw.h = m.b_h; sw.q = m.b_qs; sw.k = m.b_ks; sw.v = m.b_vs;        sw.attn = m.b_attns;
     Gemma4Attn::Wire gw{}; gw.x = m.b_x; gw.h = m.b_h; gw.q = m.b_qg; gw.k = m.b_kg; gw.v = m.b_vg;        gw.attn = m.b_atting;
     Gemma4Mlp::Wire  mw{}; mw.x = m.b_x; mw.h = m.b_h; mw.gu = m.b_gu; mw.ffn = m.b_ffn;
@@ -1364,7 +1281,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
         RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, cgeo, kg, aw, pre));
         RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, pre));
 
-        /* the per-layer scalar: `cur = cur * scalar`, a [1] bf16 over the residual stream. */
+        /* The per-layer scalar: `cur = cur * scalar`, a [1] bf16 over the residual stream. */
         RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.layer_scalar", (int)l),
                               nm.ckpt("%s.%lld.layer_scalar", pre, (long long)l)));
         lay.w_scalar = decl_w(b, nm.f("blk.%d.layer_scalar", (int)l), RAD_BF16, {1},
@@ -1376,11 +1293,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                            {mw.x}, {mw.x});
     }
 
-    /* ---- the junctions, declared once every layer exists (j_ma reads the next layer's gain). Used
-     * only when every one of them resolved and every linear a junction feeds reads its int8 pair:
-     * q, k and v (k and v through q's) and gate_up. A junction writes that pair and not the bf16
-     * norm output, so a bf16 k or v beside an int8 q would read a stale buffer. Otherwise the
-     * blocks keep their own norms, quantisers, post-norms and adds. */
+    /* ---- the junctions, declared once every layer exists (j_ma reads the next layer's gain).
+     * Used only when all resolved and every linear a junction feeds reads its int8 pair (q, k and
+     * v through q's, and gate_up): a junction writes that pair, not the bf16 norm output, so a bf16
+     * k or v beside an int8 q would read a stale buffer. Otherwise the blocks keep their own norms,
+     * quantisers, post-norms and adds. */
     if (m.n_main > 0) {
         bool ok = true;
         for (const Layer& lay : m.layers)
@@ -1433,8 +1350,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                      {m.b_logits}, {m.b_logits});
 
     /* ---- the assistant head, when the container carries one (`rad-convert --draft-model`) and
-     * the deployment speculates. A container converted without it, or a serve at max_spec 0,
-     * declares none of it: half a gigabyte of weights stays off the card. */
+     * the deployment speculates; otherwise its ~0.5 GB of weights stay off the card. */
     if (ctx->max_spec > 0 && has_assistant(meta)) {
         int last_s = -1, last_f = -1;
         for (int64_t l = 0; l < m.n_main; ++l) (is_global[(size_t)l] ? last_f : last_s) = (int)l;
@@ -1442,9 +1358,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                                     m.n_main, m.w_tok, m.b_h, m.b_logits));
         m.have_head = true;
 
-        /* WHAT THE ENGINE DRIVES. Serial: `max_spec` dependent passes, each embedding what the
-         * last one proposed, through the ordinary sampler chain (proposal 0) -- and a head with no
-         * cache of its own, so the core stages every pass at the committed position. */
+        /* Serial drafter: `max_spec` dependent passes, each embedding the last one's proposal,
+         * through the ordinary sampler chain (proposal 0). The head has no cache of its own, so
+         * the core stages every pass at the committed position. */
         RadDrafterDecl dd{};
         dd.name           = "mtp";
         dd.kind           = RAD_DRAFT_SERIAL;
@@ -1456,11 +1372,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
         RAD_ARCH_TRY(rad_drafter_shared_kv(b, kHeadPosOffset));
     }
 
-    /* ---- the vision tower, its weight groups past the trunk's and the head's (whether or not
-     * this deployment declares the head, so the groups do not move with max_spec). */
+    /* ---- the vision tower, its weight groups past the trunk's and the head's (counted even when
+     * the head is not declared, so the groups do not move with max_spec). */
     {
-        const int64_t head_groups = has_assistant(meta) ? hd_i(meta, "num_hidden_layers", 0) + 1 : 0;
-        RAD_ARCH_TRY(m.vis.declare(b, meta, ctx, nm, g.n_embd, (int)(m.n_main + head_groups)));
+        const int64_t head_groups = has_assistant(meta) ? meta_text_geti(meta, "num_hidden_layers", 0, "draft.") + 1 : 0;
+        RAD_ARCH_TRY(m.vis.declare(b, meta, ctx, nm, g.n_embd, (int)(m.n_main + head_groups),
+                                   "model.", "gemma4_bf16"));
     }
 
     rad_note(b, "rank %d/%d: %lld layers (%lld global, %lld sliding), sliding window %lld, "
@@ -1474,13 +1391,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
 static void step(RadCtx* c, const RadBatch* batch) {
     Model& m = g_model[rad_rank(c)];
 
-    /* AN ENCODER PASS RUNS THE TOWER AND NOTHING ELSE. */
+    /* An encoder pass runs only the tower. */
     if (batch->enc) {
         m.vis.step(c, batch);
         return;
     }
-    /* A DRAFT PASS RUNS THE HEAD AND NOTHING ELSE. The trunk already ran this step and left its
-     * final-normed hidden state in `h`, which the head's history pass gathers from. */
+    /* A draft pass runs only the head. The trunk already left its final-normed hidden state in
+     * `h`, which the head's history pass gathers from. */
     if (batch->draft_pass != 0) {
         if (!m.have_head) {
             rad_step_fail(c, "the batch asks for a drafter pass and no drafter is declared: the "
@@ -1510,17 +1427,13 @@ static void step(RadCtx* c, const RadBatch* batch) {
         if (m.fuse) l.j_am.step(c, T, m.fuse_ar);
         l.mlp.step(c, batch, m.fuse, m.fuse && !last, m.fuse_ar);
         if (m.fuse && !last) {
-            /* [all-reduce,] post-norm, add, the layer scalar, the next block's norm and quantiser: one op */
+            /* [all-reduce,] post-norm, add, layer scalar, next block's norm and quantiser: one op */
             l.j_ma.step(c, T, m.fuse_ar);
             continue;
         }
-        /* the per-layer scalar: `cur = cur * scalar`, the [1] bf16 over the residual stream,
-         * applied at the end of each layer (after the mlp add) -- exactly the vLLM oracle's
-         * `hidden_states = hidden_states * self.layer_scalar`. The checkpoint's values (0.03-0.99,
-         * the vLLM text-only loader remaps `model.language_model.` -> `model.` and loads the
-         * buffer, gemma4.py:1419/1644) are the trained weights: they rescale the residual toward
-         * O(1) (the RMSNorms normalise magnitude but keep direction, so the input signal survives
-         * through the branch, not the identity path). */
+        /* The per-layer scalar, `cur = cur * scalar` over the residual stream, applied after the
+         * mlp add, as vLLM's `hidden_states = hidden_states * self.layer_scalar`. The checkpoint's
+         * values (0.03-0.99) are trained weights that rescale the residual toward O(1). */
         RAD_ISSUE(c, l.op_scale, brows(m.b_x, batch->n_tok), RAD_W(l.w_scalar),
                   brows(m.b_x, batch->n_tok));
     }
@@ -1545,9 +1458,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
 /* The reply format: the model's, shared with arch/gemma4 (arch/rad_gemma4_chat.h). */
 const RadChatFormat* chat_format(const RadModelMeta*) { return gemma4_chat_format(); }
 
-/* WHAT THIS CONTAINER'S HEAD IS WORTH SPECULATING TO, for `--num-speculative-tokens auto`. A serial
- * head names an operating point, not a trained depth: one more round is one more pass of the head,
- * and every depth still runs. */
+/* The default draft depth for `--num-speculative-tokens auto`. A serial head's depth is an
+ * operating point, not a trained depth: every depth runs. */
 static int probe(const RadModelMeta* meta, RadArchProbe* out) {
     if (!meta || !out) return RAD_E_INVAL;
     if (has_assistant(meta)) {
@@ -1555,7 +1467,7 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
         out->draft_depth_fixed = 0;
     }
     /* The tower's pooling window, so a pass size the core picks itself is whole windows. */
-    if (Vision::present(meta)) {
+    if (Gemma4Vision::present(meta)) {
         const int64_t k = rad_meta_geti(meta, "vision_config.pooling_kernel_size", 0);
         if (k > 0) out->enc_merge = k * k;
     }
@@ -1565,7 +1477,7 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
 #ifndef RAD_ARCH_NO_EXPORTS
 RAD_ARCH_PLUGIN(gemma4_bf16, "gemma4", "compressed-tensors", "0.1.0",
                 "Gemma 4 dense (text and images), w4a8 from its bf16 or its CT-INT4 (QAT) release: "
-                "sliding-window and proportional-RoPE global attention over a GemmaRMSNorm stream "
+                "sliding-window and proportional-RoPE global attention over a plain RMSNorm stream "
                 "with GELU feed-forward, per-layer scalar scaling and soft-capped logits")
 RAD_ARCH_CHAT_FORMAT(gemma4_bf16)
 RAD_ARCH_PROBE(gemma4_bf16)
diff --git a/arch/lfm2_bf16/CMakeLists.txt b/arch/lfm2_bf16/CMakeLists.txt
index 119b72a4..c97aabda 100644
--- a/arch/lfm2_bf16/CMakeLists.txt
+++ b/arch/lfm2_bf16/CMakeLists.txt
@@ -1,5 +1,5 @@
-# A plugin like any other: built here inside radiance's tree, or on its own against an installed
-# radiance (`cmake -S arch/lfm2_bf16 -B build -DCMAKE_PREFIX_PATH=`).
+# Built in radiance's tree, or standalone against an installed radiance
+# (`cmake -S arch/lfm2_bf16 -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake.
 if(NOT COMMAND rad_add_plugin)
   cmake_minimum_required(VERSION 3.21)
   project(lfm2_bf16 LANGUAGES CXX)
diff --git a/arch/lfm2_bf16/lfm2_bf16.cpp b/arch/lfm2_bf16/lfm2_bf16.cpp
index 51717ba8..57f1895b 100644
--- a/arch/lfm2_bf16/lfm2_bf16.cpp
+++ b/arch/lfm2_bf16/lfm2_bf16.cpp
@@ -2,30 +2,29 @@
  *
  * ============================== THE SHAPE ==============================
  *
- * A hybrid of two layer kinds, in the order the checkpoint's `layer_types` lists them -- d1-3B's
- * schedule is irregular (attention at 2, 5, 9, 13, ...), so it is read, never derived:
+ * A hybrid of two layer kinds, in the order the checkpoint's `layer_types` lists them (read, not
+ * derived: d1-3B's schedule is irregular, attention at 2, 5, 9, 13, ...):
  *
  *   conv            in_proj -> [B | C | x], y = out_proj(C * conv(B * x)), where conv is a
  *                   depthwise causal convolution of width `conv_L_cache` with no activation
  *   full_attention  GQA with per-head RMS norms on q and k, NeoX rotary over the whole head
  *
  * each followed by a SwiGLU feed-forward (w1 the gate, w3 the up, w2 the down). Every norm is a
- * plain RMSNorm -- `x_hat * w`, not Gemma's `1 + w` -- and the final one is `embedding_norm`. At
+ * plain RMSNorm (`x_hat * w`, not Gemma's `1 + w`), and the final one is `embedding_norm`. At
  * d1-3B: 30 layers (10 attention), hidden 2048, 32 heads over 8 at head_dim 64, ffn 10752,
- * vocabulary 128000 with the lm_head TIED to the embedding, conv width 3.
+ * vocabulary 128000 with the lm_head tied to the embedding, conv width 3.
  *
  * LFM2-VL nests the same text model under `model.language_model` and adds a SigLIP2 tower and a
  * projector (siglip2.h), declared when the container carries their weights and the deployment
  * asked for media; the projector's rows replace the image placeholders' embeddings, which rotate
  * at their token positions like any other token. A text-only LFM2 checkpoint keeps the text model
- * under `model`. Which one this is is read off the config (a VL checkpoint has a `text_config`),
- * not off the model's name.
+ * under `model`. Which one this is comes from the config (a VL checkpoint has a `text_config`),
+ * not the model's name.
  *
  * ============================== WHAT IT DOES NOT SERVE ==============================
  *
- * Tensor parallelism: one rank. A 3B model has no need of a second card, and the vocabulary
- * shard, the head split and the all-reduces would be code no deployment runs. A drafter, MoE
- * (LFM2-8B-A1B), conv bias, or a checkpoint without the rotary: each is refused by name.
+ * Tensor parallelism (a 3B model needs one card). A drafter, MoE (LFM2-8B-A1B), conv bias, or a
+ * checkpoint without the rotary: each is refused by name.
  */
 #include 
 #include 
@@ -96,7 +95,7 @@ static bool text_bool(const RadModelMeta* m, const char* key, bool dflt) {
     return std::strcmp(v, "true") == 0 || std::strcmp(v, "1") == 0;
 }
 
-/* `layer_types`, one word a layer. The container flattens the list space-separated. */
+/* `layer_types`, one word per layer, space-separated in the container. */
 static int read_schedule(const RadModelMeta* m, int64_t n_layer, std::vector* out) {
     const char* s = text_key(m, "layer_types");
     if (!s || !*s) {
@@ -142,8 +141,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     m.nm = Names(ctx->scope);
     Names& nm = m.nm;
 
-    /* The FFN width as stated, unless the config asks for LFM2's sizing rule (the 1.2B and
-     * smaller releases): two thirds of it, times the multiplier, rounded up to `multiple_of`. */
+    /* The FFN width as stated, unless the config asks for LFM2's sizing rule (1.2B and smaller
+     * releases): two thirds of it, times the multiplier, rounded up to `multiple_of`. */
     RadModelMeta dims = *meta;
     if (text_bool(meta, "block_auto_adjust_ff_dim", false)) {
         int64_t ff = 2 * dims.n_ff / 3;
@@ -205,9 +204,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     m.b_logits   = decl_b(b, nm.f("logits"),   RAD_F32,  {g.max_logit_rows, g.n_vocab});
     RAD_ARCH_TRY(rad_declare_logits(b, m.b_logits));
 
-    /* ---- the vocabulary edges. The lm_head is tied in every release so far, and declared as a
-     * weight of its own anyway: the embedding lives in host memory (--embedding-placement) and the
-     * head on the card, and a kernel may ask the head for a layout the lookup does not read. */
+    /* ---- the vocabulary edges. The lm_head is tied but declared as its own weight: the
+     * embedding may live in host memory (--embedding-placement) and the head on the card, and a
+     * kernel may want a head layout the lookup does not read. */
     RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("%s.embed_tokens.weight", pre)));
     RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("%s.embedding_norm.weight", pre)));
     RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
@@ -224,7 +223,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                                    RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype)),
                         RAD_WEIGHTS(m.w_tok)),
                     {}, {m.b_x});
-    /* The encoder's rows, over the lookup: one rank, so nothing is reduced after it. */
+    /* The encoder's rows overwrite the lookup; with one rank there is no reduction after it. */
     m.media = Siglip2::present(meta) && ctx->max_enc_patches > 0;
     if (m.media) RAD_ARCH_TRY(m.mrows.declare(b, g.max_tok, g.n_embd, m.b_x));
 
@@ -281,14 +280,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
             L.op_k  = gemm(g.kv_dim(), g.n_embd, L.w_k, m.b_h, m.b_k);
             L.op_v  = gemm(g.kv_dim(), g.n_embd, L.w_v, m.b_h, m.b_v);
             /* The head norms run over rows of head_dim: a [T, heads * head_dim] buffer is
-             * T * heads such rows. */
+             * T * heads rows. */
             L.op_q_norm = rmsnorm(g.max_tok * g.n_head, g.head_dim, L.w_q_norm, m.b_q, m.b_q);
             L.op_k_norm = rmsnorm(g.max_tok * g.n_head_kv, g.head_dim, L.w_k_norm, m.b_k, m.b_k);
             L.op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, g.head_dim,
                                           "neox"), {m.b_q}, {m.b_q});
             L.op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, g.head_dim,
                                           "neox"), {m.b_k}, {m.b_k});
-            /* attn_paged before kv_store: the cache's block size is read off the resolved
+            /* attn_paged before kv_store: the cache's block size is read from the resolved
              * attention kernel. */
             L.op_attn = rw(b, RAD_OP(b, "attn_paged",
                                RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok),
@@ -371,7 +370,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                          RAD_WEIGHTS(m.w_lm_head)),
                      {m.b_hout}, {m.b_logits});
 
-    /* THE VISION TOWER, LAST, so its activations share the arena with every buffer above. */
+    /* The vision tower, last, so its activations share the arena with every buffer above. */
     if (m.media) RAD_ARCH_TRY(m.vit.declare(b, meta, ctx, nm, g.n_embd, (int)g.n_layer + 64));
 
     int64_t n_attn = 0;
@@ -384,12 +383,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     return RAD_OK;
 }
 
-/* THE CONVOLUTION IS ISSUED ONCE PER HALF OF THE STEP, as the PLE's and the gated delta net's
- * are: the decode rows [0, D) with `num_accepted`, which leaves the window in the layout a
- * partly rejected verify reads back from, and the prefill chunks [D, S) without it, each leaving
- * its tail at offset zero. `has_init` is `ctx_lens`: a sequence with tokens behind it has a
- * history. The per-sequence arrays of the prefill half move to `+ D`; the token operands stay at
- * their base, because the kernel reads rows at the absolute offsets in `cu`. */
+/* The convolution is issued once per half of the step, like the PLE's and the gated delta net's:
+ * the decode rows [0, D) with `num_accepted`, leaving the window in the layout a partly rejected
+ * verify reads back from, and the prefill chunks [D, S) without it, each leaving its tail at
+ * offset zero. `has_init` is `ctx_lens` (a sequence with earlier tokens has a history). The
+ * prefill half's per-sequence arrays start at `+ D`; the token operands stay at their base, since
+ * the kernel reads rows at the absolute offsets in `cu`. */
 static void conv_step(const Model& m, const Layer& L, RadCtx* c, const RadBatch* batch, int l) {
     const int64_t T = batch->n_tok, S = batch->n_seq;
     const RadKVGroupBatch* cv = kv_batch(batch, m.kv_conv);
@@ -421,7 +420,7 @@ static void step(RadCtx* c, const RadBatch* batch) {
                          "and the program declares none of them");
         return;
     }
-    /* AN ENCODER PASS RUNS THE VISION TOWER AND NOTHING ELSE (RadBatch::enc). */
+    /* An encoder pass runs only the vision tower (RadBatch::enc). */
     if (batch->enc) {
         m.vit.step(c, batch);
         return;
@@ -468,8 +467,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
         L.mlp.step(c, batch);
     }
 
-    /* The lm_head runs on the rows the sampler asked for and on nothing else; a prefill chunk
-     * that finishes no sequence issues none of it. */
+    /* The lm_head runs only on the rows the sampler asked for; a prefill chunk that finishes no
+     * sequence skips it. */
     if (batch->n_out > 0) {
         RAD_ISSUE_N(c, m.op_gather, batch->n_out, brows(m.b_x, T),
                     praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.b_hout, batch->n_out));
diff --git a/arch/lfm2_bf16/siglip2.h b/arch/lfm2_bf16/siglip2.h
index 323b1363..abcfa418 100644
--- a/arch/lfm2_bf16/siglip2.h
+++ b/arch/lfm2_bf16/siglip2.h
@@ -1,6 +1,6 @@
 /* siglip2.h -- LFM2-VL's image encoder: the SigLIP2 NaFlex tower and the projector after it.
  *
- * WHAT IT COMPUTES, per encoder pass (RadBatch::enc):
+ * Per encoder pass (RadBatch::enc):
  *
  *   x  = patches @ Wp^T + bp                     the patch embedding, a linear layer over a patch
  *                                                row (y, x, channel)
@@ -13,18 +13,18 @@
  *   y  = post_LN(x)
  *   out = l2(gelu(l1([LN](y viewed [P/merge^2, merge^2 * width]))))   the projector
  *
- * which is transformers' Siglip2VisionModel (no pooling head) followed by Lfm2VlMultiModalProjector.
- * The projector's pixel unshuffle is a VIEW here: the processor stores each segment's patches in
+ * i.e. transformers' Siglip2VisionModel (no pooling head) then Lfm2VlMultiModalProjector. The
+ * projector's pixel unshuffle is a view: the processor stores each segment's patches in
  * merge-block order (core/mm/processor.cpp, image_lfm2), so a block's merge^2 patches are
- * consecutive rows, dy then dx -- the order the unshuffle concatenates them in. The tower itself
- * does not care about the order: attention within a segment is permutation-equivariant and every
- * other layer is per patch, and the position table is resampled at each patch's own (row, column).
+ * consecutive rows, dy then dx, the order the unshuffle concatenates them. The tower is
+ * order-independent: attention within a segment is permutation-equivariant, every other layer is
+ * per patch, and the position table is resampled at each patch's own (row, column).
  *
  * q, k and v are one fused weight, concatenated at convert (map_concat), so a layer is one QKV
  * GEMM; the attention reads the three as column slices.
  *
- * Replicated, per-request weights and pass-sized activations, as arch/common/rad_block_vit.h's
- * tower: see the notes there.
+ * Replicated, per-request weights and pass-sized activations, as in arch/common/rad_block_vit.h's
+ * tower.
  */
 #ifndef LFM2_SIGLIP2_H
 #define LFM2_SIGLIP2_H
@@ -64,11 +64,6 @@ struct Siglip2 {
         return !std::strcmp(rad_meta_gets(m, "vision_config.model_type", ""), "siglip2_vision_model") &&
                rad_meta_geti(m, "vision_config.num_hidden_layers", 0) > 0;
     }
-    /* Input patches an output row: the projector's unshuffle. */
-    static int64_t merge_of(const RadModelMeta* m) {
-        const int64_t d = rad_meta_geti(m, "downsample_factor", 0);
-        return d * d;
-    }
 
     int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
                 int64_t model_embd, int first_group);
@@ -102,8 +97,8 @@ inline int Siglip2::declare(RadBuilder* b, const RadModelMeta* m, const RadBuild
                 (long long)proj_hidden);
         return RAD_E_INVAL;
     }
-    /* The pooling head is SigLIP2's contrastive readout; LFM2-VL reads the patch rows, and a
-     * checkpoint that ships a head would load weights nothing runs. Refused by name. */
+    /* The pooling head is SigLIP2's contrastive readout; LFM2-VL reads the patch rows, so a
+     * checkpoint that ships a head is refused by name rather than loading unused weights. */
     if (rad_meta_geti(m, "vision_config.vision_use_head", 0) != 0 ||
         !std::strcmp(rad_meta_gets(m, "vision_config.vision_use_head", ""), "true")) {
         fprintf(stderr, "radiance: lfm2: this SigLIP2 tower has a pooling head, which LFM2-VL does "
@@ -131,8 +126,8 @@ inline int Siglip2::declare(RadBuilder* b, const RadModelMeta* m, const RadBuild
     const int64_t mm = merge * merge, mw = mm * width;
     P = ctx->max_enc_patches;
     /* The longest segment attention sees: a tile or the largest thumbnail, which the processor
-     * keeps within max_num_patches. A bound that picks the attention kernel's block height, so it
-     * is the real one in a sizing declare too. */
+     * keeps within max_num_patches. It selects the attention kernel's block height, so a sizing
+     * declare uses the real value too. */
     const int64_t seg = rad_meta_geti(m, "processor.image_processor.max_num_patches",
                                       rad_meta_geti(m, "max_num_patches", P));
     const int64_t max_seg = std::min(P, seg);
@@ -166,7 +161,7 @@ inline int Siglip2::declare(RadBuilder* b, const RadModelMeta* m, const RadBuild
         l.n1b = bw(nm.f("v.blk.%d.norm1.bias", li),   nm.ckpt(e, tw, li, "layer_norm1.bias"),   { width }, g);
         l.n2w = bw(nm.f("v.blk.%d.norm2.weight", li), nm.ckpt(e, tw, li, "layer_norm2.weight"), { width }, g);
         l.n2b = bw(nm.f("v.blk.%d.norm2.bias", li),   nm.ckpt(e, tw, li, "layer_norm2.bias"),   { width }, g);
-        /* q, k, v fused at convert: one GEMM a layer. */
+        /* q, k, v fused at convert: one GEMM per layer. */
         const char* qw = nm.f("v.blk.%d.qkv.weight", li);
         const char* qb = nm.f("v.blk.%d.qkv.bias", li);
         if (map_concat(b, qw, { nm.ckpt(e, tw, li, "self_attn.q_proj.weight"),
@@ -203,8 +198,9 @@ inline int Siglip2::declare(RadBuilder* b, const RadModelMeta* m, const RadBuild
     if (!w_patch || !b_patch || !w_pos || !pn_w || !pn_b || !m1_w || !m1_b || !m2_w || !m2_b)
         return RAD_E_INVAL;
 
-    /* ---- activations. `mh` is the post-norm's output declared at the MERGED width: the norm
-     * writes P rows of `width` and the projector reads P/mm rows of mm * width, the same bytes. */
+    /* ---- activations. `mh` is the post-norm's output declared at the merged width: the norm
+     * writes P rows of `width` and the projector reads the same bytes as P/mm rows of
+     * mm * width. */
     b_x   = decl_b(b, nm.f("v.x"),   RAD_BF16, { P, width });
     b_h   = decl_b(b, nm.f("v.h"),   RAD_BF16, { P, width });
     b_qkv = decl_b(b, nm.f("v.qkv"), RAD_BF16, { P, 3 * width });
@@ -290,8 +286,8 @@ inline void Siglip2::step(RadCtx* c, const RadBatch* batch) const {
                          "merged rows");
         return;
     }
-    /* The patches, their coordinates -- a dense [4, P] of row, column, segment height and width,
-     * which is what the position resample reads -- and the segment boundaries. */
+    /* The patches, their coordinates (a dense [4, P] of row, column, segment height and width,
+     * read by the position resample) and the segment boundaries. */
     const RadOperand pix = praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim);
     const RadOperand crd = praw2(batch->enc_coord, RAD_I32, 4, Pn);
     const RadOperand cu  = praw(batch->enc_cu, RAD_I32, S + 1);
@@ -313,8 +309,8 @@ inline void Siglip2::step(RadCtx* c, const RadBatch* batch) const {
         RAD_ISSUE_N(c, l.down, Pn, brows(b_ff, Pn), RAD_W(l.down_w), RAD_W(l.down_b),
                     brows(b_x, Pn), brows(b_x, Pn));
     }
-    /* The post-norm writes Pn rows of `width` into a buffer declared at the merged width: the
-     * same bytes the projector reads as Pn/mm rows -- the pixel unshuffle. */
+    /* The post-norm writes Pn rows of `width` into the merged-width buffer, which the projector
+     * reads as Pn/mm rows: the pixel unshuffle. */
     RAD_ISSUE_N(c, op_post, Pn, brows(b_x, Pn), RAD_W(pn_w), RAD_W(pn_b), brows(b_mh, Rn));
     if (proj_norm)
         RAD_ISSUE_N(c, op_mln, Rn, brows(b_mh, Rn), RAD_W(mn_w), RAD_W(mn_b), brows(b_mn, Rn));
diff --git a/arch/llama_dense_fp8/CMakeLists.txt b/arch/llama_dense_fp8/CMakeLists.txt
index 66db636d..abdc1a60 100644
--- a/arch/llama_dense_fp8/CMakeLists.txt
+++ b/arch/llama_dense_fp8/CMakeLists.txt
@@ -1,6 +1,5 @@
-# A plugin like any other: built here inside radiance's tree, or on its own against an installed
-# radiance (`cmake -S arch/llama_dense_fp8 -B build -DCMAKE_PREFIX_PATH=`) -- the same
-# rad_add_plugin either way (cmake/RadAddPlugin.cmake).
+# Built in radiance's tree, or standalone against an installed radiance
+# (`cmake -S arch/llama_dense_fp8 -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake.
 if(NOT COMMAND rad_add_plugin)
   cmake_minimum_required(VERSION 3.21)
   project(llama_dense_fp8 LANGUAGES CXX)
diff --git a/arch/llama_dense_fp8/llama_dense_fp8.cpp b/arch/llama_dense_fp8/llama_dense_fp8.cpp
index 5d92c22b..1ed8312e 100644
--- a/arch/llama_dense_fp8/llama_dense_fp8.cpp
+++ b/arch/llama_dense_fp8/llama_dense_fp8.cpp
@@ -1,16 +1,13 @@
-/* llama_dense_fp8 -- arch/llama_fp8 over a checkpoint that was never quantised.
+/* llama_dense_fp8 -- arch/llama_fp8 over a bf16 checkpoint quantised by rad-convert.
  *
- * MiniCPM5-2B is the model this exists for: OpenBMB publishes it in bf16 and nothing else, so
- * "MiniCPM5-2B FP8A8" is a statement about what this engine runs rather than about what the
- * checkpoint holds. rad-convert does the quantising, by the recipe
- * data/recipes/minicpm5-2b-dspark.recipe -- one amax per 128x128 block, scale = amax/448 rounded to
- * bf16 -- so the container it writes holds what a checkpoint that shipped fp8 would, and every
- * kernel, every layout and every placement decision downstream is the same.
+ * For MiniCPM5-2B, which OpenBMB publishes only in bf16. The recipe
+ * data/recipes/minicpm5-2b-dspark.recipe takes one amax per 128x128 block with scale = amax/448
+ * rounded to bf16, so the container matches what a checkpoint shipped in fp8 would hold and every
+ * kernel, layout and placement decision downstream is the same.
  *
- * A SEPARATE .so BECAUSE THE SELECTION KEY IS THE PAIR (spec §2.4): one plugin claims one
- * (architecture, quantisation), and the descriptor a dense checkpoint carries is the empty one.
- * Everything else is arch/llama_fp8/llama_fp8.cpp; `#if LLAMA_DENSE_SRC` there changes only the
- * descriptor check and what the graph dump says.
+ * A separate .so because the selection key is the (architecture, quantisation) pair (spec §2.4),
+ * and a dense checkpoint's descriptor is empty. Everything else is arch/llama_fp8/llama_fp8.cpp;
+ * `#if LLAMA_DENSE_SRC` there changes only the descriptor check and the graph dump text.
  */
 #define LLAMA_DENSE_SRC 1
 #define LLAMA_NS        llama_dense_fp8
diff --git a/arch/llama_fp8/CMakeLists.txt b/arch/llama_fp8/CMakeLists.txt
index e11e277a..4996f494 100644
--- a/arch/llama_fp8/CMakeLists.txt
+++ b/arch/llama_fp8/CMakeLists.txt
@@ -1,6 +1,5 @@
-# A plugin like any other: built here inside radiance's tree, or on its own against an installed
-# radiance (`cmake -S arch/llama_fp8 -B build -DCMAKE_PREFIX_PATH=`) -- the same
-# rad_add_plugin either way (cmake/RadAddPlugin.cmake).
+# Built in radiance's tree, or standalone against an installed radiance
+# (`cmake -S arch/llama_fp8 -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake.
 if(NOT COMMAND rad_add_plugin)
   cmake_minimum_required(VERSION 3.21)
   project(llama_fp8 LANGUAGES CXX)
diff --git a/arch/llama_fp8/llama_fp8.cpp b/arch/llama_fp8/llama_fp8.cpp
index 00bc5b27..725a5aeb 100644
--- a/arch/llama_fp8/llama_fp8.cpp
+++ b/arch/llama_fp8/llama_fp8.cpp
@@ -2,43 +2,34 @@
  *
  * ============================== WHAT IT SERVES ==============================
  *
- * `model_type: llama` with `LlamaForCausalLM`, which is the most widely shared decoder shape there
- * is and is what MiniCPM5-2B reports: 42 layers, hidden 2048, 16 query heads over 2 KV heads at
- * head_dim 128, SwiGLU at 6144, RMS norms, full rotary at theta 5e6, an untied 130560-row head,
- * and no biases anywhere. Every layer is full attention; there is no gated delta net, no layer
- * schedule, no output gate and no per-head q/k norm, which is precisely what separates this file
- * from arch/qwen35_fp8.
+ * `model_type: llama` with `LlamaForCausalLM`, as MiniCPM5-2B reports: 42 layers, hidden 2048, 16
+ * query heads over 2 KV heads at head_dim 128, SwiGLU at 6144, RMS norms, full rotary at theta
+ * 5e6, an untied 130560-row head, and no biases. Every layer is full attention; unlike
+ * arch/qwen35_fp8 there is no gated delta net, layer schedule, output gate or per-head q/k norm.
  *
  * ============================== TWO CHECKPOINT FORMATS, ONE GRAPH ==============================
  *
- * The selection key is the PAIR (architecture, quantisation) -- spec §2.4 -- and one .so claims one
+ * The selection key is the (architecture, quantisation) pair (spec §2.4) and one .so claims one
  * pair, so this source builds twice:
  *
- *   llama_fp8        quant "fp8_e4m3"    the checkpoint already holds E4M3 codes and a
- *                                        `weight_scale_inv` plane, which are the two planes of
- *                                        each linear as the engine reads them.
- *   llama_dense_fp8  quant ""            the checkpoint is one dense bf16 tensor per linear, and
- *                                        a RECIPE quantises each to those two planes at convert
- *                                        time (data/recipes/minicpm5-2b-dspark.recipe). The
- *                                        container then holds what the first one's checkpoint
- *                                        does.
+ *   llama_fp8        quant "fp8_e4m3"    the checkpoint holds E4M3 codes and a `weight_scale_inv`
+ *                                        plane per linear, as the engine reads them.
+ *   llama_dense_fp8  quant ""            the checkpoint is dense bf16, and a recipe quantises each
+ *                                        linear to those two planes at convert time
+ *                                        (data/recipes/minicpm5-2b-dspark.recipe: amax per 128x128
+ *                                        block, scale = amax/448 rounded to bf16).
  *
- * THE SECOND IS THE ONE MiniCPM5-2B NEEDS, because OpenBMB publishes it in bf16 and nothing else.
- * "MiniCPM5-2B FP8A8" is therefore a statement about what this engine RUNS and not about what the
- * checkpoint holds, and the conversion is where the two meet: one pass per 128x128 block, amax,
- * scale = amax/448 rounded to bf16, divide and encode. Both builds declare the same weights and
- * the same ops, so nothing downstream -- the kernels, the container, the placement plan -- can
- * tell which one ran; the descriptor is the only reason there are two.
+ * MiniCPM5-2B needs the second, since it is published only in bf16. Both builds declare the same
+ * weights and ops, so nothing downstream can tell which one ran.
  *
  * ============================== WHAT IS AND IS NOT FP8 ==============================
  *
  *   E4M3 + a bf16 [N/128][K/128] plane   self_attn.{q,k,v,o}_proj, mlp.{gate,up,down}_proj
  *   BF16, no plane                       every norm and the embedding
  *
- * The lm_head is declared at whatever the model holds it as: bf16 as every llama checkpoint ships
- * it, or block fp8 where a recipe quantised it -- the widest GEMM in the model at half the bytes.
- * The logits kernel that reads that encoding is the one selected. Both vocabulary edges are
- * ROW-SHARDED with the vocabulary.
+ * The lm_head is declared at whatever the model holds: bf16 as llama checkpoints ship it, or block
+ * fp8 where a recipe quantised it (the widest GEMM at half the bytes), and the logits kernel for
+ * that encoding is selected. Both vocabulary edges are row-sharded with the vocabulary.
  */
 #ifndef LLAMA_DENSE_SRC
 #define LLAMA_DENSE_SRC 0
@@ -84,22 +75,21 @@ struct Model {
     rad_buf b_gate_up = 0;
     ActFP8  a_ffn{};
 
-    /* THE AUXILIARY HIDDEN-STATE TAPS, declared only when the container carries a drafter that
-     * asks for them. A DSpark or DFlash drafter does not read the trunk's FINAL hidden state --
-     * it reads the RESIDUAL STREAM at several intermediate layers and projects the concatenation
-     * down, so its `fc` is [n_embd, n_taps * n_embd] and the input has to be one contiguous row.
-     * The trunk keeps one residual buffer that every layer overwrites, so the rows are copied out
-     * as they pass, into the column slice that tap owns. This is arch/qwen35_fp8's mechanism and
-     * the comments there carry the reasoning; what is here is the same thing over this graph. */
+    /* Auxiliary hidden-state taps, declared only when the container carries a drafter that wants
+     * them. A DSpark or DFlash drafter reads the residual stream at several intermediate layers
+     * and projects the concatenation down (`fc` is [n_embd, n_taps * n_embd]), so the input must
+     * be one contiguous row. The trunk's one residual buffer is overwritten by every layer, so
+     * each tap's rows are copied into its column slice as they pass. Same mechanism as
+     * arch/qwen35_fp8. */
     enum { MAX_TAPS = 8 };
     int      n_taps = 0;
     int      tap_layer[MAX_TAPS] = {};
     rad_buf  b_dfsrc = 0;                 /* [max_tok, n_taps * n_embd] */
     rad_op   op_tap = 0;
 
-    /* THE DRAFTER, declared only when the container carries one and this serve intends to
-     * speculate. Its layers get absolute layer indices AFTER the trunk's, so the KV group's
-     * layer_slot lookup finds them and its weights land in layer groups of their own. */
+    /* The drafter, declared only when the container carries one and this serve speculates. Its
+     * layers get absolute indices after the trunk's, so the KV group's layer_slot lookup finds
+     * them and its weights land in layer groups of their own. */
     Dspark       ds{};
     Dspark::Wire dsw{};
     rad_kvgroup  kv_draft = 0;
@@ -111,44 +101,24 @@ struct Model {
     std::vector layers;
 };
 
-/* "1 10 20 30 39" -> the layers whose output a drafter wants. rad-convert flattens a config.json
- * array into a space-separated string (tools/rad_convert.cpp, flatten_json), so this is the shape
- * every list-valued key arrives in. Out-of-range entries are DROPPED rather than clamped: a
- * drafter naming a layer this model does not have is paired with the wrong target, and silently
- * reading layer 41 instead of 49 would turn that into a quality mystery. */
-static int parse_tap_layers(const char* s, int64_t n_layer, int* out, int max) {
-    if (!s) return 0;
-    int n = 0;
-    for (const char* p = s; *p && n < max;) {
-        while (*p == ' ' || *p == ',') ++p;
-        if (!*p) break;
-        char* e = nullptr;
-        const long v = std::strtol(p, &e, 10);
-        if (e == p) break;
-        p = e;
-        if (v >= 0 && v < n_layer) out[n++] = (int)v;
-    }
-    return n;
-}
-
 static Model g_model[MAX_RANKS];
 
-/* THE CONTAINER'S QUANTISATION DESCRIPTOR IS THE SELECTION KEY AND IT IS CHECKED ANYWAY, because
- * `--arch` can override the architecture id at convert time and a plugin that is handed the wrong
- * checkpoint should say which half disagrees rather than fail at a name map. */
+/* The quantisation descriptor is the selection key but is checked anyway: `--arch` can override
+ * the architecture id at convert time, and a plugin handed the wrong checkpoint should say which
+ * half disagrees rather than fail at a name map. */
 static int check_format(const RadModelMeta* meta) {
     const char* q = meta->quant ? meta->quant : "";
 #if LLAMA_DENSE_SRC
     if (*q) {
-        fprintf(stderr, "radiance: llama_dense_fp8 serves an UNQUANTISED checkpoint and this one "
-                        "declares '%s'. The fp8 sibling (llama_fp8) reads that one.\n", q);
+        fprintf(stderr, "radiance: llama_dense_fp8 serves an unquantised checkpoint and this one "
+                        "declares '%s'; llama_fp8 serves it\n", q);
         return RAD_E_UNSUPPORTED;
     }
 #else
     if (std::strncmp(q, "fp8", 3) != 0) {
         fprintf(stderr, "radiance: llama_fp8 serves a block-scaled fp8 checkpoint and this one "
-                        "declares '%s'. A dense bf16 one is served by llama_dense_fp8, after a "
-                        "recipe has quantised it.\n", *q ? q : "(unquantised)");
+                        "declares '%s'; llama_dense_fp8 serves a dense bf16 one\n",
+                *q ? q : "(unquantised)");
         return RAD_E_UNSUPPORTED;
     }
 #endif
@@ -160,62 +130,23 @@ static int check_format(const RadModelMeta* meta) {
     return RAD_OK;
 }
 
-/* THE DSPARK DRAFTER. The Geom is the TRUNK'S with the drafter's own geometry substituted in: the
- * vocabulary, the deployment bounds, the rank and the wire stay the trunk's (they are properties
- * of this serve, not of the checkpoint) and everything about the layers comes from `draft.*`.
+/* The DSpark drafter. Its Geom is the trunk's with the drafter's layer geometry from `draft.*`
+ * substituted; the vocabulary, deployment bounds, rank and wire stay the trunk's.
  *
- * Nothing here is defaulted quietly. A container whose `draft.` config does not describe this
- * drafter, or describes one this file does not implement, is refused BY NAME: a drafter that
- * silently ignored a scale factor or a head type would simply accept less, which reads as a
- * quality mystery and not as a missing feature (spec §17).
+ * Nothing is defaulted quietly: a `draft.` config that does not describe a drafter this file
+ * implements is refused by name, because a silently ignored scale factor or head type would only
+ * lower acceptance (spec §17).
  *
- * THE ONE THING THAT IS DELIBERATELY IGNORED is the confidence head, and rad_block_dspark.h argues
- * it: `AcceptRatePredictor` exists so a serving loop can shorten the block adaptively, this
- * engine's depth is fixed at declare time, and the head changes nothing the drafter proposes. */
+ * The confidence head (`AcceptRatePredictor`) is deliberately ignored: it drives adaptive block
+ * length, this engine's depth is fixed at declare, and it changes nothing the drafter proposes
+ * (rad_block_dspark.h). */
 static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx,
                           Model& m, int base_layer) {
     Names& nm = m.nm;
-    Geom   dg = m.g;   /* n_embd, the vocabulary, the deployment bounds, the rank, the wire */
-
-    dg.n_layer       = rad_meta_geti(meta, "draft.num_hidden_layers", 0);
-    dg.head_dim      = rad_meta_geti(meta, "draft.head_dim", 0);
-    dg.n_head_all    = rad_meta_geti(meta, "draft.num_attention_heads", 0);
-    dg.n_head_kv_all = rad_meta_geti(meta, "draft.num_key_value_heads", 0);
-    dg.n_ff_all      = rad_meta_geti(meta, "draft.intermediate_size", 0);
-    dg.eps           = (float)rad_meta_getf(meta, "draft.rms_norm_eps", 0.0);
-    dg.theta         = (float)rad_meta_getf(meta, "draft.rope_parameters.rope_theta",
-                                            rad_meta_getf(meta, "draft.rope_theta", 0.0));
-    /* PLAIN RMS NORM: the reference norms with Qwen3RMSNorm and the config says `model_type:
-     * qwen3`. It happens to agree with this MiniCPM5 target, and it is asked of the DRAFTER's
-     * config anyway -- two conventions in one process is exactly why this is a second Geom. */
-    dg.wadd    = 0.0f;
-    dg.wadd_qk = 0.0f;
-
-    if (dg.n_layer <= 0 || dg.head_dim <= 0 || dg.n_head_all <= 0 || dg.n_head_kv_all <= 0 ||
-        dg.n_ff_all <= 0 || !(dg.eps > 0.0f) || !(dg.theta > 0.0f)) {
-        fprintf(stderr, "radiance: the container's `draft.` config does not describe a DSpark "
-                        "drafter: layers %lld, heads %lld / kv %lld, head_dim %lld, ffn %lld, "
-                        "rms_eps %g, rope_theta %g\n",
-                (long long)dg.n_layer, (long long)dg.n_head_all, (long long)dg.n_head_kv_all,
-                (long long)dg.head_dim, (long long)dg.n_ff_all, (double)dg.eps, (double)dg.theta);
-        return RAD_E_INVAL;
-    }
-    RAD_ARCH_TRY(yarn_from(dg, meta, "draft.", dg.head_dim));
-    int s;
-    if ((s = divide_or_fail(dg.n_head_all,    dg.world, "draft num_attention_heads", &dg.n_head))    < 0) return s;
-    if ((s = divide_or_fail(dg.n_head_kv_all, dg.world, "draft num_key_value_heads", &dg.n_head_kv)) < 0) return s;
-    if ((s = divide_or_fail(dg.n_ff_all,      dg.world, "draft intermediate_size",   &dg.n_ff))      < 0) return s;
-
-    /* THE DRAFTER BORROWS THE TARGET'S EMBEDDING TABLE AND lm_head -- it ships neither -- so a
-     * vocabulary that disagrees is not a drafter for this target at all. */
-    const long long dvocab = rad_meta_geti(meta, "draft.vocab_size", dg.n_vocab_all);
-    if (dvocab != dg.n_vocab_all) {
-        fprintf(stderr, "radiance: the DSpark drafter claims a %lld-token vocabulary and the "
-                        "target has %lld. The drafter ships no embedding table and no lm_head; it "
-                        "reads the target's, so the two have to be the same vocabulary.\n",
-                dvocab, (long long)dg.n_vocab_all);
-        return RAD_E_UNSUPPORTED;
-    }
+    Geom   dg{};
+    /* Plain RMS norm: the reference uses Qwen3RMSNorm (`model_type: qwen3`). It matches this
+     * MiniCPM5 target, but it is the drafter's convention, set on the drafter's own Geom. */
+    RAD_ARCH_TRY(drafter_geom(dg, m.g, meta, "DSpark"));
 
     Dspark::Config dc{};
     dc.n_taps = m.n_taps;
@@ -223,11 +154,10 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
     dc.causal = rad_meta_geti(meta, "draft.is_causal", 0) ? 1 : 0;
     if (rad_meta_geti(meta, "draft.use_sliding_window", 0))
         dc.window = rad_meta_geti(meta, "draft.sliding_window", 0);
-    /* HOW MANY CANDIDATES THE MARKOV WALK RE-RANKS. The reference biases all 130560 logits and
-     * takes the argmax; this re-ranks the base head's top K, which is the only approximation in
-     * the head and it can cost acceptance and nothing else (rad_block_dspark.h). K is bounded by
-     * the selector at 32; 16 is 8 KiB of codebook a position, which is free, and it is read from
-     * the container so a checkpoint can ask for more. */
+    /* How many candidates the Markov walk re-ranks. The reference biases all 130560 logits and
+     * takes the argmax; this re-ranks the base head's top K, the head's only approximation, which
+     * can cost acceptance but not correctness (rad_block_dspark.h). The selector bounds K at 32;
+     * the default 16 is 8 KiB of codebook per position, and a checkpoint may ask for more. */
     dc.top_k  = rad_meta_geti(meta, "draft.markov_top_k", 16);
     if (dc.top_k < 1 || dc.top_k > 32) {
         fprintf(stderr, "radiance: draft.markov_top_k is %lld; the Markov walk scores at most 32 "
@@ -235,15 +165,14 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
         return RAD_E_UNSUPPORTED;
     }
 
-    /* THE BLOCK IS THE NUMBER OF NOISE ROWS AND ALSO THE NUMBER OF DRAFTS -- every row predicts
-     * the token after it, the anchor row included. So the engine's depth IS `block_size`, where a
-     * Dflash2 container's is `block_size - 1`, and that off-by-one is the whole reason
-     * RadDrafterDecl carries a `block` field. Getting it wrong runs, drafts, and accepts nothing.
+    /* The block is both the number of noise rows and the number of drafts: every row, the anchor
+     * included, predicts the token after it. So the depth is `block_size`, where a DFlash2
+     * container's is `block_size - 1` (see RadDrafterDecl::block). A wrong value runs but accepts
+     * nothing.
      *
-     * A BLOCK-DIFFUSION DRAFTER WAS TRAINED FOR ONE BLOCK LENGTH, so a serve that asks for another
-     * depth is refused here rather than run: the reference denoises exactly `block_size` masked
-     * positions and there is no partial block. The probe reports `draft_depth_fixed`, so the
-     * engine will normally have picked this already. */
+     * A block-diffusion drafter is trained for one block length and has no partial block, so any
+     * other depth is refused. The probe reports `draft_depth_fixed`, so the engine normally picks
+     * this already. */
     const long long trained = rad_meta_geti(meta, "draft.block_size", 0);
     if (trained < 2) {
         fprintf(stderr, "radiance: this DSpark checkpoint declares no draft.block_size; the "
@@ -260,8 +189,8 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
     }
     dc.block = trained;
 
-    /* Two things this drafter's family can carry that this implementation does not apply. Each
-     * changes what the drafter proposes, which is why neither is ignored quietly. */
+    /* Two variants this implementation does not apply; each changes the proposals, so neither is
+     * ignored quietly. */
     const char* mh = rad_meta_gets(meta, "draft.markov_head_type", "vanilla");
     if (dc.rank <= 0 || !mh || std::strcmp(mh, "vanilla") != 0) {
         fprintf(stderr, "radiance: this DSpark checkpoint has markov_rank %lld and "
@@ -276,26 +205,12 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
         return RAD_E_UNSUPPORTED;
     }
 
-    /* THE DRAFTER'S OWN KV CACHE, a group of its own. It cannot share the trunk's: five layers
-     * against forty-two, and -- when the checkpoint asks for one -- a WINDOW. RAD_KV_WINDOW
-     * recycles the blocks that fall below it; DSpark's published config sets `sliding_window:
-     * null`, so this is normally a full cache of five layers. Its width is the trunk's,
-     * --kv-cache-dtype: one flag says what every attention cache of the deployment is made of. */
-    RadKVGroupDecl dd{};
-    dd.kind      = dc.window > 0 ? RAD_KV_WINDOW : RAD_KV_FULL;
-    dd.dtype     = rad_kv_cache_dtype(ctx, RAD_BF16);
-    dd.window    = dc.window;
-    dd.n_head_kv = dg.n_head_kv;
-    dd.head_dim  = dg.head_dim;
-    m.kv_draft = rad_decl_kv_group(b, nm.f("kv_draft"), &dd);
-    for (int64_t l = 0; l < dg.n_layer; ++l)
-        RAD_ARCH_TRY(rad_bind_layer_kv(b, base_layer + (int)l, m.kv_draft));
-    dg.kv_dtype = rad_dtype_name(dd.dtype);
+    /* DSpark's published config sets `sliding_window: null`, so this is normally a full cache. */
+    RAD_ARCH_TRY(drafter_kv_group(b, nm, ctx, dg, dc.window, base_layer, &m.kv_draft));
 
-    /* Activation buffers. The context pass is one row a COMMITTED TOKEN and runs over a whole
-     * prefill chunk; everything after it is one row a DRAFT POSITION, `block` of them a sequence,
-     * so the two halves are sized apart. None of it is large -- the drafter's cost is its
-     * weights, not its activations. */
+    /* Activations. The context pass has one row per committed token over a whole prefill chunk;
+     * the query pass one row per draft position, `block` per sequence; the two are sized apart.
+     * All are small: the drafter's cost is its weights. */
     const int64_t qd  = dg.n_head * dg.head_dim;
     const int64_t kvd = dg.n_head_kv * dg.head_dim;
     int64_t qr = dg.max_seqs * dc.block;
@@ -308,9 +223,8 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
     dw.c    = decl_b(b, nm.f("ds_c"),  dg.act_dtype, {dg.max_tok, dg.n_embd});
     dw.ck   = decl_b(b, nm.f("ds_ck"), dg.act_dtype, {dg.max_tok, kvd});
     dw.cv   = decl_b(b, nm.f("ds_cv"), dg.act_dtype, {dg.max_tok, kvd});
-    /* THE FP8 TWINS OF THE CONTEXT PASS. `srcq` is the largest of them by a distance -- 20 MiB at
-     * a 2048-token chunk, five taps and hidden 2048, against the 40 MiB `draft_src` it shadows --
-     * and it buys half the bytes of the one GEMM the context pass spends its time in. */
+    /* FP8 copies for the context pass. `srcq` is the largest (20 MiB at a 2048-token chunk, five
+     * taps, hidden 2048) and halves the bytes of the context pass's dominant GEMM. */
     dw.srcq = decl_b(b, nm.f("ds_srcq"), RAD_F8E4M3, {dg.max_tok, dc.n_taps * dg.n_embd});
     dw.srcs = decl_b(b, nm.f("ds_srcs"), RAD_F32,
                      {dg.max_tok, fp8_blocks(dc.n_taps * dg.n_embd)});
@@ -335,12 +249,11 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
     dw.sel_h  = decl_b(b, nm.f("ds_selh"), dg.act_dtype, {sr, dg.n_embd});
     dw.dq     = decl_b(b, nm.f("ds_dq"), RAD_I8,  {sr, dg.n_embd});
     dw.ds     = decl_b(b, nm.f("ds_ds"), RAD_F32, {sr, 1});
-    /* GROUP-major, [n_embd/group][ceil(M/16)*16] -- quant_act_i8's asum plane, whose first
-     * dimension is the K group and not the token. */
+    /* Group-major, [n_embd/group][ceil(M/16)*16]: quant_act_i8's asum plane, whose first
+     * dimension is the K group, not the token. */
     dw.dsum   = decl_b(b, nm.f("ds_dsum"), RAD_F32, {dg.n_embd / 128, spad});
-    /* THIS RANK'S plane. `head_rows` is the block's own answer to whether the 2-bit head is
-     * vocab-sharded, asked here rather than re-derived, because a buffer that disagreed with the
-     * op declared over it is a read past its end. */
+    /* This rank's plane. `head_rows` is the block's own answer to whether the 2-bit head is
+     * vocab-sharded; asking it keeps the buffer consistent with the op declared over it. */
     dw.dlog   = decl_b(b, nm.f("ds_dlog"), dg.act_dtype, {sr, Dspark::head_rows(dg)});
     dw.cand   = decl_b(b, nm.f("dspark_cand"), RAD_I32, {sr, dc.top_k});
     dw.unary  = decl_b(b, nm.f("ds_unary"), RAD_F32, {sr, dc.top_k});
@@ -348,23 +261,21 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
         dw.dpair = decl_b(b, nm.f("ds_dpair"), RAD_F32, {sr, dc.top_k, 2});
         dw.dgath = decl_b(b, nm.f("ds_dgath"), RAD_F32, {sr, (int64_t)dg.world * dc.top_k, 2});
     }
-    /* NAMED, because the engine reads the draft out of it by name: a block pass proposes through
-     * the drafter's own walk and never through the sampler's token buffer. */
+    /* The proposal buffer (RadDrafterDecl::proposal): a block pass proposes through the
+     * drafter's own walk, never through the sampler's token buffer. */
     dw.tokens = decl_b(b, nm.f("dspark_tokens"), RAD_I32, {dg.max_seqs, dc.steps()});
 
-    /* A TIED lm_head IS THE ALTERNATIVE SOURCE, and it has to be the same pair the trunk's own
-     * head reads or the drafter would be projecting onto a different vocabulary. */
+    /* The same lm_head sources as the trunk's head (embedding as the tied alternative), so both
+     * project onto one vocabulary. */
     RAD_ARCH_TRY(m.ds.declare(b, nm, dg, dc, base_layer, m.kv_draft, m.w_tok, "draft",
                               nm.ckpt("lm_head.weight"), nm.ckpt("model.embed_tokens.weight"),
                               dw));
     m.have_ds = true;
 
-    /* WHAT THE ENGINE DRIVES. Block: a context pass that mirrors the trunk step, then ONE pass
-     * that fills the whole block. `block` is `depth` and not `depth + 1`, which is this drafter's
-     * trained convention and the field's reason for existing. `window` must be the number this
-     * plugin gated its OWN attention with, because the scheduler stages the block pass against
-     * it: two readings of "how far back can the drafter see" is a drafter attending to positions
-     * the scheduler did not stage. */
+    /* Block drafter: a context pass mirroring the trunk step, then one pass filling the whole
+     * block. `block` is `depth`, not `depth + 1` (this drafter's training convention). `window`
+     * must be the one this plugin gated its own attention with, since the scheduler stages the
+     * block pass against it. */
     RadDrafterDecl drf{};
     drf.name           = "dspark";
     drf.kind           = RAD_DRAFT_BLOCK;
@@ -377,27 +288,22 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
     if (drf.mask_token < 0)
         drf.mask_token = (int32_t)rad_meta_geti(meta, "draft.dflash_config.mask_token_id", -1);
     if (drf.mask_token < 0) {
-        fprintf(stderr, "radiance: this DSpark checkpoint declares no mask_token_id, and every "
-                        "position the block has not filled embeds it -- there is nothing to "
-                        "run.\n");
+        fprintf(stderr, "radiance: this DSpark checkpoint declares no mask_token_id, which every "
+                        "unfilled block position embeds\n");
         return RAD_E_FORMAT;
     }
     RAD_ARCH_TRY(rad_declare_drafter(b, &drf));
 
-    rad_note(b, "the DSpark drafter is declared: %lld layers of its own at absolute %d..%d, "
-                "%lld heads / %lld kv x %lld, ffn %lld, %s attention with a %lld-token window, "
-                "reading the trunk at %d tap(s). ONE forward over %lld noise row(s) proposes "
-                "%lld tokens -- there are no rounds -- and EVERY row predicts, the anchor "
-                "included, so the block is `depth` rows and not `depth + 1`",
+    rad_note(b, "DSpark drafter: %lld layers at absolute %d..%d, %lld heads / %lld kv x %lld, "
+                "ffn %lld, %s attention with a %lld-token window, %d trunk tap(s); one forward "
+                "over %lld noise row(s), the anchor included, proposes %lld tokens",
              (long long)dg.n_layer, base_layer, base_layer + (int)dg.n_layer - 1,
              (long long)dg.n_head, (long long)dg.n_head_kv, (long long)dg.head_dim,
              (long long)dg.n_ff, dc.causal ? "causal" : "non-causal", (long long)dc.window,
              m.n_taps, (long long)dc.block, (long long)dc.steps());
-    rad_note(b, "the rank-%lld Markov bigram head runs as the candidate walk with no hidden "
-                "projection: `unary + ` over the draft head's "
-                "top %lld, decoded greedily. The confidence head is present in the checkpoint and "
-                "deliberately not applied -- it drives adaptive block length, which this engine "
-                "does not have, and it changes nothing the drafter proposes",
+    rad_note(b, "the rank-%lld Markov bigram head walks `unary + ` over the draft head's top %lld, greedily; the confidence head "
+                "(adaptive block length) is not applied",
              (long long)dc.rank, (long long)dc.top_k);
     return RAD_OK;
 }
@@ -410,17 +316,15 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     m = Model{};
     m.nm = Names(ctx->scope);
     RAD_ARCH_TRY(check_format(meta));
-    /* "bf16" is the ACTIVATION dtype: everything but the two GEMM operands runs at it. */
+    /* "bf16" is the activation dtype: everything but the two GEMM operands runs at it. */
     RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
 
     Geom&  g  = m.g;
     Names& nm = m.nm;
     m.n_main  = g.n_layer;
 
-    /* THE ROTARY WIDTH IS THE WHOLE HEAD unless the config says otherwise. LLaMA rotates every
-     * dimension; `partial_rotary_factor` exists in this config schema and Phi-style models set it,
-     * so it is read rather than assumed -- but the DEFAULT is the family's answer and not a
-     * refusal, because a checkpoint that states nothing is stating "all of it". */
+    /* The rotary width is the whole head unless `partial_rotary_factor` says otherwise (Phi-style
+     * models set it). A config that states nothing means the full head. */
     {
         double prf = rad_meta_getf(meta, "partial_rotary_factor", 0.0);
         if (!(prf > 0.0)) prf = rad_meta_getf(meta, "rope_parameters.partial_rotary_factor", 0.0);
@@ -456,22 +360,19 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff));
     m.b_hout   = decl_b(b, nm.f("h_out"),    g.act_dtype, {g.max_logit_rows, g.n_embd});
 
-    /* ---- the drafter's taps. Gated on BOTH halves of the question: the container has to carry a
-     * drafter that reads them, and the deployment has to intend to speculate. The buffer is one
-     * residual stream per tap -- 40 MiB at a 2048-token chunk, five taps and hidden 2048 -- which
-     * a server that never drafts should not be carrying.
+    /* ---- the drafter's taps, only when the container carries a drafter that reads them and the
+     * deployment speculates: the buffer is one residual stream per tap, 40 MiB at a 2048-token
+     * chunk with five taps and hidden 2048.
      *
-     * TWO KEY SPELLINGS, because the two checkpoints spell it differently and both are real. A
-     * SpecForge DFlash config nests the drafter's wiring under `dflash_config`; the published
-     * DSpark configs (openbmb/MiniCPM5-2B-DSpark and its siblings) put the same fields at the top
-     * level. Reading the flat one first and falling back keeps one plugin serving both rather
-     * than making the spelling an architecture. */
+     * Two key spellings: a SpecForge DFlash config nests the wiring under `dflash_config`, while
+     * the published DSpark configs (openbmb/MiniCPM5-2B-DSpark and siblings) put it at the top
+     * level. The flat key is read first. */
     if (ctx->max_spec > 0) {
         const char* da = rad_meta_gets(meta, "draft.architectures", "");
         if (da && (std::strstr(da, "DSpark") || std::strstr(da, "DFlash"))) {
             const char* ids = rad_meta_gets(meta, "draft.target_layer_ids", nullptr);
             if (!ids) ids = rad_meta_gets(meta, "draft.dflash_config.target_layer_ids", nullptr);
-            m.n_taps = parse_tap_layers(ids, m.n_main, m.tap_layer, Model::MAX_TAPS);
+            m.n_taps = parse_layer_ids(ids, m.n_main, m.tap_layer, Model::MAX_TAPS);
             if (m.n_taps > 0) {
                 m.b_dfsrc = decl_b(b, nm.f("draft_src"), g.act_dtype,
                                    {g.max_tok, (int64_t)m.n_taps * g.n_embd});
@@ -493,11 +394,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     m.b_logits = decl_b(b, nm.f("logits"),   RAD_F32,     {g.max_logit_rows, g.n_vocab});
     RAD_ARCH_TRY(rad_declare_logits(b, m.b_logits));
 
-    /* ---- the vocabulary edges, both ROW-SHARDED with the vocabulary. A tied head is expressed by
-     * the alternative source: a model that ships no `lm_head.weight` reads the embedding table as
-     * both, which is what every small LLaMA derivative does. The head is declared at its codes'
-     * dtype -- bf16, or E4M3 where a recipe made it block fp8 -- after its map, which is how the
-     * model is asked. */
+    /* ---- the vocabulary edges, both row-sharded with the vocabulary. A tied head is the
+     * alternative source: without `lm_head.weight` the embedding table serves as both, as in small
+     * LLaMA derivatives. The head is declared at its codes' dtype (bf16, or E4M3 where a recipe
+     * made it block fp8), queried after its name map entry. */
     RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("model.embed_tokens.weight")));
     RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("model.norm.weight")));
     RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
@@ -516,9 +416,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                                    RAD_INT("vocab_offset", g.vocab_off)),
                         RAD_WEIGHTS(m.w_tok)),
                     {}, {m.b_x});
-    /* EXACT, unconditionally: each token's embedding comes from exactly one rank and every other
-     * contributes a zero, so a lossy wire would be pure loss on a value that is already the
-     * answer. The same argument arch/qwen35_fp8 makes about its own. */
+    /* Always exact: each token's embedding comes from one rank and the others contribute zero, so
+     * a lossy wire would only add error. */
     if (g.world > 1)
         m.op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
                                RAD_PARAMS(RAD_INT("world_size", g.world),
@@ -532,37 +431,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     MlpFP8::Wire mw{};
     mw.x = m.b_x; mw.h = m.a_h; mw.gate_up = m.b_gate_up; mw.ffn = m.a_ffn;
 
-    auto is_tap = [&](int64_t l) {
-        for (int t = 0; t < m.n_taps; ++t)
-            if (m.tap_layer[t] == (int)l) return true;
-        return false;
-    };
-
     m.layers.resize((size_t)m.n_main);
     for (int64_t l = 0; l < m.n_main; ++l) {
         Layer& lay = m.layers[(size_t)l];
-        /* THE RESIDUAL FOLD, and the rule is arch/qwen35_fp8's with exactly one of its exceptions:
-         * there are no ablation switches here, so every block folds its predecessor's delta into
-         * its own norm and the LAST layer's feed-forward keeps its own add -- for the final norm,
-         * which is a plain `rmsnorm` with no residual operand.
-         *
-         * A TAP IS THE OTHER READER OF `x` BETWEEN BLOCKS, and it forces the add to stay where it
-         * was. What the drafter conditions on has to be that layer's REAL output, so a tap layer's
-         * feed-forward keeps its own add and the block after it has nothing left to fold. Get this
-         * wrong and the taps carry a residual stream missing its last delta -- a drafter that
-         * still runs, still proposes, and is quietly conditioned on the wrong thing.
-         *
-         * `ar_in`/`ar_out` move the collective with the add, one boundary at a time, at two ranks
-         * only: at tp1 there is none and at four the fused kernel does not exist. They need no
-         * change for the taps -- a tap layer's MLP has `add`, so it does not defer its all-reduce,
-         * and the next mixer does not fold, so it looks for none. The two stay consistent because
-         * both are derived from the same two flags. */
-        const bool tp2      = g.world == 2;
-        const bool mix_fold = l > 0 && !is_tap(l - 1);
-        const bool mlp_add  = is_tap(l) || (l + 1 >= m.n_main);
-        const int  mix_ar_in  = !tp2 ? kArNone
-                              : mix_fold ? kArAny
-                              : (l == 0 && m.op_embed_ar) ? kArExact : kArNone;
+        /* Residual fold and collective placement: rad_fp8.h, layer_fold. */
+        const LayerFold f = layer_fold(g, l, m.n_main, m.tap_layer, m.n_taps, m.op_embed_ar != 0);
 
         const char* pre = "model.layers";
         AttnFP8::Src as{};
@@ -573,15 +446,15 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
         as.o    = nm.ckpt("%s.%lld.self_attn.o_proj.weight", pre, (long long)l);
         RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_full));
         RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, m.kv_full, m.n_rot, aw, as,
-                                      mix_fold, /*add_out=*/false, mix_ar_in, tp2));
+                                      f.mix_fold, false, f.mix_ar_in, f.mix_ar_out));
 
         MlpFP8::Src ms{};
         ms.norm = nm.ckpt("%s.%lld.post_attention_layernorm.weight", pre, (long long)l);
         ms.gate = nm.ckpt("%s.%lld.mlp.gate_proj.weight",            pre, (long long)l);
         ms.up   = nm.ckpt("%s.%lld.mlp.up_proj.weight",              pre, (long long)l);
         ms.down = nm.ckpt("%s.%lld.mlp.down_proj.weight",            pre, (long long)l);
-        RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, ms, /*fold=*/true, mlp_add,
-                                     tp2 ? kArAny : kArNone, !mlp_add && tp2));
+        RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, ms, true, f.mlp_add,
+                                     f.mlp_ar_in, f.mlp_ar_out));
     }
 
     m.op_final_norm = rw(b, RAD_OP(b, "rmsnorm",
@@ -602,27 +475,18 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                          RAD_WEIGHTS(m.w_lm_head)),
                      {m.b_hout}, {m.b_logits});
 
-    /* THE DRAFTER IS DECLARED LAST, AFTER `op_logits`, AND THE ORDER IS LOAD-BEARING.
+    /* The drafter is declared last, after `op_logits`. Do not move it.
      *
-     * DECLARATION ORDER IS WHAT THE BUFFER PLANNER'S LIVENESS IS: a transient's range is
-     * [first_def, last_use] over OP INDICES, and two buffers whose ranges are disjoint may share
-     * bytes (core/build/rad_bufplan.cpp). The drafter's passes run AFTER the whole trunk pass, so
-     * declaring them here is the order that says so. Declared in the MIDDLE -- before
-     * `op_final_norm`, say -- the trunk's own tail ops get indices past the drafter's, the planner
-     * reads that as "these live after the drafter is done", and it shares bytes between a trunk
-     * buffer and a drafter buffer that are both live inside one engine step.
+     * Declaration order is the buffer planner's liveness: a transient lives over [first_def,
+     * last_use] in op indices, and buffers with disjoint ranges may share bytes
+     * (core/build/rad_bufplan.cpp). The drafter's passes run after the whole trunk, so they must
+     * be declared after it; declared earlier, the trunk's tail ops would look live after the
+     * drafter, and trunk and drafter buffers live in one step would share bytes.
      *
-     * THE SYMPTOM OF GETTING IT WRONG IS NOT A CRASH: the trunk's output stays fluent, because row
-     * 0 of a verify step is computed before the clobber lands, and EVERY DRAFT IS REJECTED, because
-     * rows 1..n_spec are not. Speculation looks broken and the drafter looks wrong while it is
-     * proposing exactly the right tokens. It is the one class of fault the op oracle cannot see: a
-     * buffer clobbered before an op runs makes the device and the host compute the same wrong
-     * answer and agree.
-     *
-     * The same declaration can be correct at one world size and wrong at another: the shard
-     * halves every sharded buffer and the greedy packer's offsets are a function of the sizes.
-     * arch/qwen35_fp8 declares its drafter here for the same reason; this is not a stylistic
-     * match. */
+     * The failure is silent: the trunk output stays correct (row 0 of a verify step is computed
+     * before the clobber) but every draft is rejected. The op oracle cannot see it, since device
+     * and host compute the same wrong answer from a clobbered input. It can also depend on world
+     * size, because sharding changes buffer sizes and so the packer's offsets. */
     if (m.n_taps > 0)
         RAD_ARCH_TRY(declare_dspark(b, meta, ctx, m, (int)m.n_main));
 
@@ -632,51 +496,41 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
              (long long)g.head_dim, (long long)m.n_rot, (long long)g.n_ff,
              (long long)g.vocab_off, (long long)(g.vocab_off + g.n_vocab));
 #if LLAMA_DENSE_SRC
-    rad_note(b, "the checkpoint is DENSE bf16 and its recipe quantised every linear to E4M3 with "
-                "a bf16 [N/%d,K/%d] scale plane -- one amax per block, scale = amax/448 rounded "
-                "to bf16. The container is half the checkpoint's size and the graph is the one "
-                "llama_fp8 declares over a checkpoint that shipped that way",
+    rad_note(b, "a dense bf16 checkpoint, every linear quantised by the recipe to E4M3 with a "
+                "bf16 [N/%d,K/%d] scale plane (scale = block amax / 448, rounded to bf16)",
              RAD_FP8_BLOCK, RAD_FP8_BLOCK);
 #else
     rad_note(b, "weights are block-scaled fp8: E4M3 [N,K] with a bf16 [N/%d,K/%d] scale plane, "
                 "one stored weight taken by gemm_nt_q as two operands",
              RAD_FP8_BLOCK, RAD_FP8_BLOCK);
 #endif
-    rad_note(b, "NOT fp8 in the checkpoint: every norm, the embedding and the lm_head. The head "
-                "is declared at what the model holds -- block fp8 where a recipe made it so");
+    rad_note(b, "bf16 in the checkpoint: every norm, the embedding and the lm_head, which is "
+                "declared at what the container holds");
     if (m.n_taps > 0) {
         char ids[64] = {};
         int  off = 0;
         for (int t = 0; t < m.n_taps && off < (int)sizeof(ids) - 8; ++t)
             off += snprintf(ids + off, sizeof(ids) - (size_t)off, t ? " %d" : "%d",
                             m.tap_layer[t]);
-        rad_note(b, "the drafter reads the residual stream at layer(s) %s into a [%lld, %lld] "
-                    "buffer -- %lld tap(s) x %lld. Those layers keep their own residual add and "
-                    "the layer after each one has nothing to fold, so the tap sees the real "
-                    "output rather than a stream still missing its last delta",
-                 ids, (long long)g.max_tok, (long long)((int64_t)m.n_taps * g.n_embd),
-                 (long long)m.n_taps, (long long)g.n_embd);
+        rad_note(b, "the drafter reads the residual stream after layer(s) %s into a [%lld, %lld] "
+                    "buffer; those layers keep their own residual add",
+                 ids, (long long)g.max_tok, (long long)((int64_t)m.n_taps * g.n_embd));
     }
-    rad_note(b, "q, k and v are ONE fused [%lld, %lld] projection and `rope` rotates the fused "
-                "row in place -- q heads then k heads, v untouched. There is no per-head q/k norm "
-                "and no output gate in this family; qwen35 has both and that is the whole "
-                "difference between the two attention blocks",
+    rad_note(b, "q, k and v are one fused [%lld, %lld] projection, rotated in place by `rope` "
+                "(q heads, then k heads); no per-head q/k norm and no output gate",
              (long long)(q_dim + 2 * kv_dim), (long long)g.n_embd);
     return RAD_OK;
 }
 
 static void step(RadCtx* c, const RadBatch* batch) {
     Model& m = g_model[rad_rank(c)];
-    /* A DRAFTER PASS, AND THE SIGN SAYS WHICH KIND. For a block-diffusion drafter the two kinds
-     * are the two passes: POSITIVE is the QUERY pass, which proposes the whole block in one go,
-     * and NEGATIVE is the CONTEXT pass, which turns the tokens the trunk just committed into the
-     * drafter's own K and V. There is no third kind and no round counter -- this drafter runs its
-     * layers once per step. Zero is a trunk step, so a zeroed RadBatch runs the model. */
+    /* A drafter pass; the sign gives the kind. Positive is the query pass, proposing the whole
+     * block at once; negative is the context pass, turning the tokens the trunk just committed
+     * into the drafter's own K and V. Zero is a trunk step. */
     if (batch->draft_pass != 0) {
         if (!m.have_ds) {
             rad_step_fail(c, "the batch asks for a drafter pass and no drafter is declared: the "
-                             "container carries no `draft.` block, or declare ran at max_spec 0, "
-                             "which is the engine saying it would not draft");
+                             "container carries no `draft.` block, or declare ran at max_spec 0");
             return;
         }
         if (batch->draft_pass > 0) m.ds.step(c, batch);
@@ -694,9 +548,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
     for (size_t li = 0; li < m.layers.size(); ++li) {
         m.layers[li].attn.step(c, batch);
         m.layers[li].mlp.step(c, batch);
-        /* The tap, into the column slice this one owns. It runs on the PREFILL and DECODE passes
-         * alike, because the drafter conditions on every committed token's residual stream and
-         * the rows it wants are whatever this batch just computed. */
+        /* The tap, into its column slice. Runs on prefill and decode alike: the drafter
+         * conditions on every committed token's residual stream. */
         for (int t = 0; t < m.n_taps; ++t) {
             if (m.tap_layer[t] != (int)li) continue;
             RAD_ISSUE(c, m.op_tap, brows(m.b_x, batch->n_tok),
@@ -717,15 +570,12 @@ static void step(RadCtx* c, const RadBatch* batch) {
     }
 }
 
-/* WHAT THIS CONTAINER CAN SPECULATE TO. A plain llama container answers zero -- there is no MTP
- * head in this family and no draft block -- and one converted with `--draft-model` against a
- * DSpark checkpoint answers its trained block length.
+/* The speculation depth this container supports: zero for a plain llama container (no MTP head
+ * in this family), or the trained block length of a DSpark drafter added with `--draft-model`.
  *
- * `draft_depth` IS `block_size` AND NOT `block_size - 1`, which is the one number a reader coming
- * from arch/qwen35_fp8 will expect to be different: DSpark's anchor row predicts the token after
- * it like every other row, so seven noise rows are seven drafts. `draft_depth_fixed` says the
- * engine may not pick another -- the drafter denoises a fixed number of masked positions and was
- * trained for exactly one block length. */
+ * `draft_depth` is `block_size`, not `block_size - 1` as in arch/qwen35_fp8: DSpark's anchor row
+ * predicts too. `draft_depth_fixed` forbids any other depth, since the drafter was trained for
+ * exactly one block length. */
 static int probe(const RadModelMeta* meta, RadArchProbe* out) {
     if (!meta || !out) return RAD_E_INVAL;
     out->draft_depth = 0;
@@ -743,14 +593,14 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
 }  /* namespace LLAMA_NS */
 
 #ifndef RAD_ARCH_NO_EXPORTS
-/* One more level of expansion so `#NS` sees the expanded namespace; arch/qwen35_fp8 explains it. */
+/* One more level of expansion so `#NS` sees the expanded namespace. */
 #define LLAMA_PROBE_X(NS)        RAD_ARCH_PROBE(NS)
 #define LLAMA_PLUGIN_X(NS, ...)  RAD_ARCH_PLUGIN(NS, __VA_ARGS__)
 LLAMA_PROBE_X(LLAMA_NS)
 #if LLAMA_DENSE_SRC
 LLAMA_PLUGIN_X(LLAMA_NS, "llama", LLAMA_QUANT, "0.1.0",
                "LLaMA-shaped decoders (MiniCPM5, Llama 3, and every derivative that reports "
-               "model_type llama) from a DENSE bf16 checkpoint, made block-scaled fp8 by a recipe "
+               "model_type llama) from a dense bf16 checkpoint, made block-scaled fp8 by a recipe "
                "at convert time and served fp8 weights / fp8 activations")
 #else
 LLAMA_PLUGIN_X(LLAMA_NS, "llama", LLAMA_QUANT, "0.1.0",
diff --git a/arch/qwen35_bf16/CMakeLists.txt b/arch/qwen35_bf16/CMakeLists.txt
index 5d9aeb99..4ca24895 100644
--- a/arch/qwen35_bf16/CMakeLists.txt
+++ b/arch/qwen35_bf16/CMakeLists.txt
@@ -1,6 +1,5 @@
-# A plugin like any other: built here inside radiance's tree, or on its own against an installed
-# radiance (`cmake -S arch/qwen35_bf16 -B build -DCMAKE_PREFIX_PATH=`) -- the same
-# rad_add_plugin either way (cmake/RadAddPlugin.cmake).
+# Built in radiance's tree, or standalone against an installed radiance
+# (`cmake -S arch/qwen35_bf16 -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake.
 if(NOT COMMAND rad_add_plugin)
   cmake_minimum_required(VERSION 3.21)
   project(qwen35_bf16 LANGUAGES CXX)
diff --git a/arch/qwen35_bf16/qwen35_bf16.cpp b/arch/qwen35_bf16/qwen35_bf16.cpp
index 18d73225..b23b9472 100644
--- a/arch/qwen35_bf16/qwen35_bf16.cpp
+++ b/arch/qwen35_bf16/qwen35_bf16.cpp
@@ -1,45 +1,38 @@
 /* qwen35_bf16 -- Qwen3.5 / 3.6 / 3.8 dense, bf16 weights and bf16 activations.
  *
- * Qwen3.5, Qwen3.6 and Qwen3.8 dense models all report the architecture id `qwen35`, and
- * `qwen35moe` is the same graph with a routed FFN. Dimensions come from model metadata, so this
- * one file serves every size in the family -- 0.8B through 27B. docs/ARCHITECTURES.md has the
- * geometry and the traps that stay plausible when they are wrong.
+ * Qwen3.5, 3.6 and 3.8 dense models report the architecture id `qwen35`; `qwen35moe` is the same
+ * graph with a routed FFN. Dimensions come from metadata, so this file serves every size (0.8B to
+ * 27B). docs/ARCHITECTURES.md has the geometry and its plausible-but-wrong traps.
  *
- * One plugin implements one architecture id for one quantisation scheme (spec §2.4). A
- * `qwen35_w8a8` sibling is a different directory that composes the same blocks against
- * rmsnorm_had_quant_i8, gemm_nt_q and gdn_gated_norm_had_quant_i8 -- not a branch in here. That is
- * why the declare function below is a list of what runs, in order, with no branch on quant in it.
+ * One plugin implements one architecture id for one quantisation scheme (spec §2.4); a quantised
+ * variant is a separate plugin composing the same blocks against other ops (e.g.
+ * rmsnorm_had_quant_i8, gemm_nt_q), so declare() below has no branch on quantisation.
  *
  * ============================== WHAT IT SERVES ==============================
  *
- * The unquantised release -- Qwen3.8-27B in bf16, quantisation descriptor "" -- served at its own
- * precision: every projection a bf16 GEMM. The block-scaled fp8 release is qwen35_fp8's, which
- * declares the same graph over fp8 linears. The lm_head here is declared at whatever the model
- * holds it as, so a container whose recipe made it block fp8 reads it through the fp8 logits
- * kernel and a checkpoint loaded as it stands through the bf16 one.
+ * The unquantised release (quantisation descriptor ""), every projection a bf16 GEMM. The
+ * block-scaled fp8 release is qwen35_fp8's. The lm_head is declared at whatever the model holds,
+ * so a recipe-made block-fp8 head uses the fp8 logits kernel.
  *
  * ============================== THE SHAPE, AT 27B ==============================
  *
- *   64 layers, full_attention_interval 4 -> layers 3,7,...,63 are FULL ATTENTION (16 of them),
- *                                           the other 48 are GATED DELTA NET
- *   hidden 5120   ffn 17408   vocab 248320   (lm_head NOT tied)
- *   24 heads / 4 kv heads / head_dim 256  -> GQA 6, and head_dim is READ, not derived:
- *                                            n_embd / n_head is 213 and every shape after it
- *                                            would be wrong.
+ *   64 layers, full_attention_interval 4 -> layers 3,7,...,63 are full attention (16 of them),
+ *                                           the other 48 are gated delta net
+ *   hidden 5120   ffn 17408   vocab 248320   (lm_head not tied)
+ *   24 heads / 4 kv heads / head_dim 256  -> GQA 6; head_dim is read, not derived
+ *                                            (n_embd / n_head would be 213)
  *   attn_output_gate -> q_proj is [n_embd, 2 * n_head * head_dim], query and gate interleaved
  *   partial_rotary_factor 0.25 -> MROPE over the first 64 of 256 head dims, theta 1e7
  *   linear: 16 key heads / 48 value heads of 128, conv width 4, fp32 recurrent state
  *
  * ============================== WHAT THIS PLUGIN DOES NOT DECLARE ==============================
  *
- * The MTP / NextN head (one extra decoder block plus fc, enorm, hnorm) is real scope and is NOT
- * here. It does not block text generation, and it has to be declared from tensor names read off
- * the checkpoint -- a name map written from memory is a model that loads half its weights and
- * says nothing. It sits BESIDE the trunk under an `mtp.` prefix of its own, so
- * `nextn_predict_layers` is not subtracted from the layer count (see declare()), and declaring
- * the MTP block as a trunk layer would run it in the main pass, which is a different model.
+ * The MTP / NextN head (one extra decoder block plus fc, enorm, hnorm) is not declared here; it
+ * is not needed for text generation. It sits beside the trunk under its own `mtp.` prefix, so
+ * `nextn_predict_layers` is not subtracted from the layer count (see declare()); running it as a
+ * trunk layer would be a different model.
  *
- * The VISION TOWER (27 blocks, hidden 1152, 16 heads of 72, patch 16, out 5120) is declared
+ * The vision tower (27 blocks, hidden 1152, 16 heads of 72, patch 16, out 5120) is declared
  * through arch/common/rad_block_vit.h, only when the container carries one and the deployment
  * asked for media.
  */
@@ -55,10 +48,8 @@ namespace qwen35_bf16 {
 
 using namespace rad::arch;
 
-/* One trunk layer. A hybrid model's layer is one of two kinds and the plugin holds both structs
- * rather than a union: they are small, and a variant would buy nothing except a cast at every use.
- * `full` is the only branch in step(), and it is a branch on the MODEL, not on a configuration --
- * the same layer is the same kind on every step and in every deployment. */
+/* One trunk layer, of one of two kinds; both small structs are held rather than a union. `full`
+ * is the only branch in step(), and it is fixed per layer by the model. */
 struct Layer {
     int           full = 0;
     AttnGatedBF16 attn;
@@ -97,65 +88,10 @@ struct Model {
     std::vector layers;
 };
 
-/* Declare runs once per rank, in one process, on the rank's own thread (spec §1, §9). A single
- * static Model would have rank 1's declare overwrite rank 0's handles; this is indexed by rank and
- * read back in step() with rad_rank(). */
+/* Declare runs once per rank, in one process, on the rank's own thread (spec §1, §9), so the
+ * model state is indexed by rank and read back in step() with rad_rank(). */
 static Model g_model[MAX_RANKS];
 
-/* Layer kind. llama.cpp is ground truth: `is_recr(i) = (i < n_main) && ((i + 1) % interval != 0)`,
- * so with interval 4 the FULL-ATTENTION layers are 3, 7, ... and everything else is linear. */
-static inline bool is_full_attention(int64_t l, int64_t interval) {
-    return interval > 0 && ((l + 1) % interval == 0);
-}
-
-static int check_layer_schedule(const RadModelMeta* meta, int64_t n_layer, int64_t interval) {
-    const char* s = rad_meta_gets(meta, "qwen35.layer_types", nullptr);
-    if (!s) s = rad_meta_gets(meta, "text_config.layer_types", nullptr);
-    if (!s) s = rad_meta_gets(meta, "layer_types", nullptr);
-    if (!s || !*s) return RAD_OK;
-
-    int64_t l = 0;
-    for (const char* p = s; *p; ) {
-        while (*p == ' ') ++p;
-        if (!*p) break;
-        const char* tok = p;
-        while (*p && *p != ' ') ++p;
-        const size_t len = (size_t)(p - tok);
-
-        const bool says_full = len == 14 && std::strncmp(tok, "full_attention", 14) == 0;
-        const bool says_lin  = len == 16 && std::strncmp(tok, "linear_attention", 16) == 0;
-        if (!says_full && !says_lin) {
-            fprintf(stderr, "radiance: qwen35: layer_types[%lld] is '%.*s'; this plugin knows "
-                            "'full_attention' and 'linear_attention' and will not guess at a "
-                            "third kind of layer.\n", (long long)l, (int)len, tok);
-            return RAD_E_UNSUPPORTED;
-        }
-        /* Past the trunk is the MTP block, which the array may or may not include; it is not a
-         * trunk layer and its kind is the drafter's business (see declare_draft). */
-        if (l >= n_layer) break;
-        if (says_full != is_full_attention(l, interval)) {
-            fprintf(stderr, "radiance: qwen35: the container says layer %lld is %s, and "
-                            "full_attention_interval %lld makes it %s. The interval rule is "
-                            "llama.cpp's and it is not a property of this family -- a model whose "
-                            "layer_types differ from it would be built with the wrong layers "
-                            "linear, and would load and generate fluent text from an architecture "
-                            "that is not the one in the checkpoint. Read layer_types directly "
-                            "before serving this model.\n",
-                    (long long)l, says_full ? "full_attention" : "linear_attention",
-                    (long long)interval,
-                    is_full_attention(l, interval) ? "full_attention" : "linear_attention");
-            return RAD_E_UNSUPPORTED;
-        }
-        ++l;
-    }
-    if (l && l < n_layer) {
-        fprintf(stderr, "radiance: qwen35: layer_types names %lld layers and the model has %lld. "
-                        "A short schedule is not a schedule.\n", (long long)l, (long long)n_layer);
-        return RAD_E_UNSUPPORTED;
-    }
-    return RAD_OK;
-}
-
 static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
     if (!b || !meta || !ctx) return RAD_E_INVAL;
     if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
@@ -165,7 +101,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     m.nm = Names(ctx->scope);
     RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
 
-    /* A routed model is a different graph, not a flag on this one. qwen35moe_bf16 serves it. */
+    /* A routed model is a different graph, served by the qwen35moe plugin. */
     if (meta->n_expert > 0) {
         fprintf(stderr, "radiance: qwen35_bf16 refuses a checkpoint with %lld experts; that is "
                         "qwen35moe\n", (long long)meta->n_expert);
@@ -175,9 +111,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     Geom&  g  = m.g;
     Names& nm = m.nm;
 
-    /* ---- geometry that RadModelMeta does not name, read from the container's free-form header.
-     * Both spellings are accepted: a .rad converted from the FP8 safetensors carries the
-     * HuggingFace keys and one converted from a GGUF carries llama.cpp's. */
+    /* ---- geometry RadModelMeta does not name, from the container's free-form header. Both
+     * spellings are accepted: HuggingFace keys (from safetensors) and llama.cpp's (from GGUF). */
     bool have_interval = false;
     const int64_t interval = meta_int2(meta, "qwen35.full_attention_interval",
                                        "full_attention_interval", 4, &have_interval);
@@ -189,43 +124,32 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                 (long long)interval, (long long)nextn, (long long)g.n_layer);
         return RAD_E_INVAL;
     }
-    RAD_ARCH_TRY(check_layer_schedule(meta, g.n_layer, interval));
-    /* EVERY DECLARED LAYER IS A TRUNK LAYER. `mtp_num_hidden_layers` is NOT part of
-     * `num_hidden_layers` in this family -- Qwen3.8-27B-FP8 ships layers-0..63 under
-     * `model.language_model.layers.N` and its one MTP block separately, under an `mtp.` prefix of
-     * its own, in mtp.safetensors. Subtracting it here would drop layer 63, which is a
-     * full-attention layer, and the model would answer with the trunk one layer short: still a
-     * distribution, still self-consistent op by op, and wrong. `nextn` is kept for the note below,
-     * which is the only thing the count is good for until the MTP head is declared. */
+    RAD_ARCH_TRY(check_layer_schedule("qwen35", meta_text_gets(meta, "layer_types", nullptr),
+                                      g.n_layer, interval, {"full_attention"}));
+    /* Every declared layer is a trunk layer: `mtp_num_hidden_layers` is not part of
+     * `num_hidden_layers` in this family (the MTP block ships separately under `mtp.`).
+     * Subtracting it would drop full-attention layer 63 and silently run a trunk one layer short.
+     * `nextn` is used only for the note below. */
     m.n_main = g.n_layer;
 
-    /* Qwen3.5's norms are GemmaRMSNorm: `x_hat * (1 + w)`, not `x_hat * w`. vLLM says so by
-     * importing it under the family's own name -- `from ...layernorm import GemmaRMSNorm as
-     * Qwen3_5RMSNorm` -- and the checkpoint says so too: `input_layernorm.weight` sits around 0.07
-     * to 0.29, which is a gain of 1.1 to 1.3 the right way round and a five-to-ten-times shrink
-     * the wrong way. It applies to input_layernorm, post_attention_layernorm, the model's final
-     * norm and the q/k head norms -- and NOT to the delta net's ssm_norm, which is a plain
-     * RMSNormGated with gains around 0.88.
-     *
-     * The checkpoint answers two of the three families by itself: the layer norms (0.07..0.29)
-     * and the q/k head norms (partly NEGATIVE) can only be `1 + w`. The model's FINAL norm sits at
-     * 0.68..0.96, which reads as either, and takes `1 + w` because the reference implementation
-     * does. */
+    /* Qwen3.5's norms are GemmaRMSNorm, `x_hat * (1 + w)` (vLLM imports GemmaRMSNorm as
+     * Qwen3_5RMSNorm). This covers input_layernorm, post_attention_layernorm, the final norm and
+     * the q/k head norms, but not the delta net's ssm_norm, a plain RMSNormGated (gains ~0.88).
+     * The checkpoint confirms it: layer norm weights of 0.07..0.29 and partly negative q/k norm
+     * weights only make sense as `1 + w`. The final norm (0.68..0.96) is ambiguous and follows the
+     * reference implementation. */
     g.wadd    = 1.0f;
     g.wadd_qk = 1.0f;
     const float final_wadd = 1.0f;
 
-    /* The rotary width. partial_rotary_factor 0.25 over head_dim 256 is 64, and a container that
-     * omits it is refused rather than defaulted to head_dim: a full rotation is a different model
-     * and its symptom is fluent wrong text, which is exactly what spec §17 is about. */
+    /* The rotary width: partial_rotary_factor 0.25 over head_dim 256 is 64. A container that
+     * omits it is refused rather than defaulted to a full rotation, which would give fluent wrong
+     * text (spec §17). */
     m.n_rot = meta_int2(meta, "qwen35.rope.dimension_count", "rope_dimension_count", 0);
     if (m.n_rot <= 0) {
-        /* BOTH SPELLINGS, because the family uses both. Qwen3.8-27B-FP8 states
-         * `partial_rotary_factor` at the text_config level AND inside `rope_parameters`;
-         * Qwen3.5-0.8B states it ONLY inside `rope_parameters`, and rad-convert flattens nested
-         * config with a dot. Reading only one spelling refuses a container of the same
-         * architecture with "no usable rotary width", which is a true statement about the key and
-         * a false one about the model. */
+        /* Both spellings occur in this family: Qwen3.8-27B-FP8 states `partial_rotary_factor`
+         * at the top level and inside `rope_parameters`, Qwen3.5-0.8B only inside
+         * `rope_parameters` (rad-convert flattens nested config with a dot). */
         double prf = rad_meta_getf(meta, "partial_rotary_factor", 0.0);
         if (!(prf > 0.0)) prf = rad_meta_getf(meta, "rope_parameters.partial_rotary_factor", 0.0);
         if (prf > 0.0) m.n_rot = (int64_t)(g.head_dim * prf);
@@ -263,10 +187,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                 (long long)gc.head_v, (long long)gc.conv_width);
         return RAD_E_INVAL;
     }
-    /* The chunked scan's tile length. Not a model parameter: it is libr4d's
-     * gdn_chunk_scan_k128_v128_c64_bf16, and it is also the interval a linear-state checkpoint is
-     * snapshotted at (spec §7.3). Note that gdn_conv_prep takes it while gdn_chunk_scan derives it
-     * from the kernel, and nothing checks that the two agree. */
+    /* The chunked scan's tile length, not a model parameter: libr4d's
+     * gdn_chunk_scan_k128_v128_c64_bf16, and also the linear-state checkpoint interval
+     * (spec §7.3). Note: gdn_conv_prep takes it while gdn_chunk_scan derives it from the kernel,
+     * and nothing checks that the two agree. */
     gc.chunk = 64;
 
     int s;
@@ -280,13 +204,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     const int64_t v_dim    = gc.v_dim();
     const int64_t conv_dim = gc.conv_dim();
 
-    /* ---- THREE KV groups, which is why hybrid KV groups are first-class rather than an
-     * extension (spec §7.2). Every layer is bound to the group it owns state in, below: a group
-     * with no bound layers is a declare error, because how many state instances a sequence holds
-     * is the layer count and assuming one would make the page size a guess.
+    /* ---- three KV groups (spec §7.2). Every layer is bound below to the group it owns state
+     * in; a group with no bound layers is a declare error, since the bound layer count is how
+     * many state instances a sequence holds.
      *
-     * The block size is NOT declared for the full-attention group -- it comes off the resolved
-     * attention kernel's constraints and is read back with rad_kv_block_size() inside the block. */
+     * The full-attention group's block size is not declared: it comes from the resolved attention
+     * kernel and is read back with rad_kv_block_size() inside the block. */
     RadKVGroupDecl fd{};
     fd.kind      = RAD_KV_FULL;
     fd.dtype     = rad_kv_cache_dtype(ctx, RAD_BF16);
@@ -295,12 +218,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     m.kv_full = rad_decl_kv_group(b, nm.f("kv_attn"), &fd);
     g.kv_dtype = rad_dtype_name(fd.dtype);
 
-    /* The recurrent state is fp32 because that is the only state width libr4d has a kernel for
-     * (gdn_recurrent_update_k128_v128_bf16_fp32state) and what `mamba_ssm_dtype: float32` asks
-     * for. It costs 48 x 128 x 128 x 4 = 3 MiB a layer and 144 MiB across the 48 linear layers,
-     * PER SEQUENCE, which is the largest single number in this deployment's memory plan.
-     * An fp16 state would halve that and cost a little step time, but declaring it here would be
-     * declaring a geometry no kernel serves, so it waits for the kernel. */
+    /* The recurrent state is fp32, as `mamba_ssm_dtype: float32` asks; an f16 state changes the
+     * generated text (qwen35_fp8.cpp). It costs 48 x 128 x 128 x 4 = 3 MiB per layer, 144 MiB
+     * across the 48 linear layers per sequence, the largest item in the memory plan. */
     RadKVGroupDecl sd{};
     sd.kind         = RAD_KV_LINEAR;
     sd.dtype        = RAD_F32;
@@ -309,7 +229,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     sd.state_dim[1] = gc.head_k;
     m.kv_state = rad_decl_kv_group(b, nm.f("kv_gdn_state"), &sd);
 
-    /* The conv window: conv_width-1 + n_spec entries of the whole convolved row, counted in HEADS
+    /* The conv window: conv_width-1 + n_spec entries of the whole convolved row, counted in heads
      * so the channel split never straddles a q/k/v boundary at any tensor-parallel width. */
     RadKVGroupDecl cd{};
     cd.kind       = RAD_KV_CONV;
@@ -319,18 +239,15 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     cd.conv_width = gc.conv_width;
     m.kv_conv = rad_decl_kv_group(b, nm.f("kv_gdn_conv"), &cd);
 
-    /* ---- activation buffers, sized at max_tok because that is the worst step. Every layer of a
-     * kind shares these: layers that share a geometry share the buffer, and the buffer plan's
-     * liveness analysis over the declared read and write sets is what makes one arena enough
-     * (spec §3.1, §8). */
+    /* ---- activation buffers, sized at max_tok (the worst step) and shared by every layer of a
+     * kind; liveness analysis over the declared read and write sets fits them in one arena
+     * (spec §3.1). */
     m.b_x       = decl_b(b, nm.f("x"),        g.act_dtype, {g.max_tok, g.n_embd});
     m.b_h       = decl_b(b, nm.f("h"),        g.act_dtype, {g.max_tok, g.n_embd});
 
-    /* The query-and-gate projection is declared RANK 3, [tokens, heads, 2*head_dim], because that
-     * is what makes the interleaving addressable: the query is the first head_dim columns of the
-     * last dimension and the gate is the second head_dim, so both are ordinary column slices whose
-     * row stride is the declared width. Flattened to [tokens, 2*q_dim] the same bytes describe a
-     * per-head view no operand can name. */
+    /* The query-and-gate projection is rank 3, [tokens, heads, 2*head_dim], so the per-head
+     * interleaving is addressable: query and gate are the first and second head_dim columns of the
+     * last dimension, i.e. ordinary column slices. Flattened, no operand could name them. */
     m.b_qg      = decl_b(b, nm.f("attn_qg"),  g.act_dtype, {g.max_tok, g.n_head, 2 * g.head_dim});
     m.b_k       = decl_b(b, nm.f("attn_k"),   g.act_dtype, {g.max_tok, kv_dim});
     m.b_v       = decl_b(b, nm.f("attn_v"),   g.act_dtype, {g.max_tok, kv_dim});
@@ -343,45 +260,37 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     m.b_gq      = decl_b(b, nm.f("gdn_q"),    g.act_dtype, {g.max_tok, gc.n_head_k, gc.head_k});
     m.b_gk      = decl_b(b, nm.f("gdn_k"),    g.act_dtype, {g.max_tok, gc.n_head_k, gc.head_k});
     m.b_gv      = decl_b(b, nm.f("gdn_v"),    g.act_dtype, {g.max_tok, gc.n_head_v, gc.head_v});
-    /* The decay, beta and the chunk inverse are f32 and not bf16. The decay is a cumulative sum
-     * whose intra-chunk span reaches hundreds of nats on real prefill inputs; a bf16 running sum
-     * loses the low bits of exactly the quantity every decay factor is an exponent of. */
+    /* Decay and beta are f32: the decay is a cumulative sum whose intra-chunk span reaches
+     * hundreds of nats on real prefill inputs, and a bf16 running sum would lose the low bits that
+     * every decay factor exponentiates. */
     m.b_gdec    = decl_b(b, nm.f("gdn_g"),    RAD_F32,     {g.max_tok, gc.n_head_v});
     m.b_beta    = decl_b(b, nm.f("gdn_beta"), RAD_F32,     {g.max_tok, gc.n_head_v});
-    /* BF16, not f32: gdn_kkt_solve writes this plane as bf16 and gdn_chunk_scan reads it as bf16
-     * (libr4d's own row text, and the casts in both .hip files). See qwen35_fp8.cpp. */
+    /* bf16, not f32: gdn_kkt_solve writes this plane as bf16 and gdn_chunk_scan reads it as
+     * bf16. */
     m.b_kkt     = decl_b(b, nm.f("gdn_kkt"),  RAD_BF16,    {g.max_tok, gc.n_head_v, gc.chunk});
     m.b_go      = decl_b(b, nm.f("gdn_o"),    g.act_dtype, {g.max_tok, gc.n_head_v, gc.head_v});
 
     m.b_gate_up = decl_b(b, nm.f("gate_up"),  g.act_dtype, {g.max_tok, 2 * g.n_ff});
     m.b_ffn     = decl_b(b, nm.f("ffn"),      g.act_dtype, {g.max_tok, g.n_ff});
-    /* The lm_head runs over the SAMPLED ROWS, not over every token of the chunk. `max_logit_rows`
-     * is one row per sequence, or one per verified draft position per sequence -- at 248320 vocab
-     * that is the difference between 63 MiB and 8 GiB, and between one GEMM per sequence and one
-     * per token. `b_hout` is where gather_rows puts the hidden states it selects; it is narrow
-     * (n_embd, not n_vocab) which is why gathering before the GEMM and not after is the whole
-     * point. */
+    /* The lm_head runs over the sampled rows only: `max_logit_rows` is one row per sequence, or
+     * per verified draft position. At 248320 vocab that is 63 MiB of logits instead of 8 GiB.
+     * gather_rows selects the hidden states into the narrow `b_hout` (n_embd wide) before the
+     * GEMM. */
     m.b_hout    = decl_b(b, nm.f("h_out"),    g.act_dtype, {g.max_logit_rows, g.n_embd});
     m.b_logits  = decl_b(b, nm.f("logits"),   RAD_F32,     {g.max_logit_rows, g.n_vocab});
     RAD_ARCH_TRY(rad_declare_logits(b, m.b_logits));
 
-    /* ---- vocabulary edges.
-     * BOTH ENDS OF THE VOCABULARY ARE ROW-SHARDED. Replicating the embedding while sharding the
-     * lm_head would put 248320 x 5120 in bf16 -- 2.43 GiB -- on every rank, for a table each rank
-     * uses a slice of. `embed_lookup` takes a `vocab_offset`: a rank gathers the ids in its own
-     * slice, writes a zero row for every id belonging to another rank, and the all_reduce below
-     * sums the ranks into x. lm_head is sharded because the sampler runs a distributed top-k and full
-     * logits are never gathered anywhere (spec §9, §13); the embedding is sharded because the
-     * other end of the same vocabulary already was. */
+    /* ---- vocabulary edges, both row-sharded. The lm_head is sharded because the sampler runs a
+     * distributed top-k and full logits are never gathered (spec §9, §13); replicating the
+     * embedding would cost 248320 x 5120 bf16 (2.43 GiB) per rank. `embed_lookup` takes a
+     * `vocab_offset`: a rank gathers the ids in its slice and writes zero rows for the rest, and
+     * the all_reduce below sums the ranks into x. */
     RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"),
                           nm.ckpt("model.language_model.embed_tokens.weight")));
     RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"),
                           nm.ckpt("model.language_model.norm.weight")));
-    /* This model does NOT tie its lm_head -- `tie_word_embeddings: false`, and the checkpoint
-     * ships lm_head.weight beside the embedding. The second source is for the small members of the
-     * family that do tie; first source present wins, and without it a family whose members differ
-     * only in tying needs two plugins. The maps come first: they are how the model is asked what
-     * each weight is. */
+    /* The 27B does not tie its lm_head (`tie_word_embeddings: false`); the second source serves
+     * the small family members that do. The first source present wins. */
     RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
                               nm.ckpt("model.language_model.embed_tokens.weight")));
 
@@ -389,10 +298,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                      RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
     m.w_out_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd},
                           RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
-    /* ROW-SHARDED with the vocabulary: g.n_vocab is THIS RANK'S share and rad_arch.h says what
-     * the split is and what it buys. The two change together. Declared at its codes' dtype: bf16
-     * as the checkpoint ships it, E4M3 where a recipe made it block fp8 -- and the logits kernel
-     * that reads that encoding is the one selected. */
+    /* Row-sharded with the vocabulary: g.n_vocab is this rank's share (rad_arch.h). Declared at
+     * its codes' dtype (bf16 as shipped, E4M3 where a recipe made it block fp8), which selects the
+     * logits kernel. */
     m.w_lm_head = decl_w(b, nm.f("output.weight"),
                          weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16),
                          {g.n_vocab, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
@@ -403,12 +311,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                                    RAD_INT("vocab_offset", g.vocab_off)),
                         RAD_WEIGHTS(m.w_tok)),
                     {}, {m.b_x});
-    /* THE ENCODER'S ROWS, over the lookup and before its reduction (MediaRows says why). */
+    /* The encoder's rows overwrite the lookup before its reduction (see MediaRows). */
     m.media = VisionTower::present(meta) && ctx->max_enc_patches > 0;
     if (m.media) RAD_ARCH_TRY(m.mrows.declare(b, g.max_tok, g.n_embd, m.b_x));
-    /* EXACT, and not g.wire_exact: this sums DISJOINT rows -- every token comes from exactly one
-     * rank and the others contribute zeros -- so a lossy wire would be loss on a value that is
-     * already the answer, not a bandwidth trade against a partial product. */
+    /* Always exact, not g.wire_exact: this sums disjoint rows (each token from one rank, zeros
+     * from the others), so a lossy wire would only add error. */
     if (g.world > 1)
         m.op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
                                RAD_PARAMS(RAD_INT("world_size", g.world),
@@ -417,7 +324,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                                RAD_NOWEIGHTS),
                            {m.b_x}, {m.b_x});
 
-    /* ---- the layers. This loop is the model card. */
+    /* ---- the layers. */
     AttnGatedBF16::Wire aw{};
     aw.x = m.b_x; aw.h = m.b_h; aw.qg = m.b_qg; aw.k = m.b_k; aw.v = m.b_v;
     aw.q = m.b_q; aw.gate = m.b_gate; aw.attn = m.b_attn;
@@ -491,7 +398,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                          RAD_WEIGHTS(m.w_lm_head)),
                      {m.b_hout}, {m.b_logits});
 
-    /* ---- what a reader of --debug-graph should be told, in the plugin's own words. */
+    /* ---- notes for --debug-graph. */
     rad_note(b, "rank %d/%d: %lld trunk layers, %lld full attention + %lld gated delta net, "
                 "n_head=%lld n_head_kv=%lld head_dim=%lld n_ff=%lld vocab=[%lld,%lld)",
              g.rank, g.world, (long long)m.n_main,
@@ -503,27 +410,21 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
              (long long)gc.n_head_k, (long long)gc.head_k, (long long)gc.n_head_v,
              (long long)gc.head_v, (long long)gc.conv_width, (long long)gc.chunk,
              (long long)conv_dim, (long long)gc.in_dim());
-    rad_note(b, "ssm_a_log carries A_log AS A LOG: the kernels form -exp(A_log)*softplus(a+dt). "
-                "A container built from a GGUF has ssm_a = -exp(A_log) already applied and must "
-                "undo it, or every head's decay collapses");
-    rad_note(b, "rope is mrope over %lld of %lld head dims, sections [11,11,10]; RadBatch carries "
-                "one position component per token, so the three sections see the same position -- "
-                "exact for text, wrong for an image span",
-             (long long)m.n_rot, (long long)g.head_dim);
+    rad_note(b, "ssm_a_log holds A_log itself: the kernels form -exp(A_log) * softplus(a + dt), "
+                "so a GGUF's ssm_a = -exp(A_log) must be converted back");
+    rad_note(b, "rope: %s over %lld of %lld head dims%s%s", g.rope_mode, (long long)m.n_rot,
+             (long long)g.head_dim, g.rope_mc ? ", sections " : "", g.rope_sections);
     if (!have_interval)
         rad_note(b, "the container did not state full_attention_interval; assuming %lld, which "
                     "makes layers 3,7,... full attention", (long long)interval);
-    rad_note(b, "logits are computed for the %lld sampled rows of a step, not for all %lld "
-                "tokens: RadBatch::out_ids names them and gather_rows selects the hidden states "
-                "before the lm_head, which is the difference between 63 MiB and 8 GiB at this "
-                "vocabulary", (long long)g.max_logit_rows, (long long)g.max_tok);
+    rad_note(b, "logits for at most %lld sampled rows a step (of %lld tokens): gather_rows "
+                "selects RadBatch::out_ids before the lm_head", (long long)g.max_logit_rows,
+             (long long)g.max_tok);
     if (nextn > 0)
-        rad_note(b, "%lld MTP/NextN layer(s) sit BESIDE the %lld trunk layers -- under an `mtp.` "
-                    "prefix of their own, not as layers %lld.. -- and are NOT declared: this "
-                    "plugin serves the trunk only",
-                 (long long)nextn, (long long)m.n_main, (long long)m.n_main);
+        rad_note(b, "the %lld MTP/NextN layer(s) under `mtp.` are not declared: this plugin "
+                    "serves the trunk only", (long long)nextn);
 
-    /* THE VISION TOWER, LAST, so its activations share the arena with every buffer above. */
+    /* The vision tower, last, so its activations share the arena with every buffer above. */
     if (m.media) RAD_ARCH_TRY(m.vit.declare(b, meta, ctx, nm, g.n_embd, (int)g.n_layer + 64));
     return RAD_OK;
 }
@@ -531,7 +432,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
 static void step(RadCtx* c, const RadBatch* batch) {
     Model& m = g_model[rad_rank(c)];
 
-    /* AN ENCODER PASS RUNS THE VISION TOWER AND NOTHING ELSE (RadBatch::enc). */
+    /* An encoder pass runs only the vision tower (RadBatch::enc). */
     if (batch->enc) {
         m.vit.step(c, batch);
         return;
@@ -555,9 +456,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
     RAD_ISSUE(c, m.op_final_norm,
               brows(m.b_x, batch->n_tok), RAD_W(m.w_out_norm), brows(m.b_h, batch->n_tok));
 
-    /* The lm_head runs on the rows the sampler asked for and on nothing else. A prefill chunk in
-     * the middle of a long prompt sets n_out to zero: it finishes no sequence, so there is no
-     * distribution to draw from and the widest GEMM in the model is not issued at all. */
+    /* The lm_head runs only on the rows the sampler asked for; a mid-prompt prefill chunk has
+     * n_out zero and skips it. */
     if (batch->n_out > 0) {
         RAD_ISSUE_N(c, m.op_gather, batch->n_out,
                     brows(m.b_h, batch->n_tok),
diff --git a/arch/qwen35_fp8/CMakeLists.txt b/arch/qwen35_fp8/CMakeLists.txt
index 71142b36..360a3b21 100644
--- a/arch/qwen35_fp8/CMakeLists.txt
+++ b/arch/qwen35_fp8/CMakeLists.txt
@@ -1,6 +1,5 @@
-# A plugin like any other: built here inside radiance's tree, or on its own against an installed
-# radiance (`cmake -S arch/qwen35_fp8 -B build -DCMAKE_PREFIX_PATH=`) -- the same
-# rad_add_plugin either way (cmake/RadAddPlugin.cmake).
+# Built in radiance's tree, or standalone against an installed radiance
+# (`cmake -S arch/qwen35_fp8 -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake.
 if(NOT COMMAND rad_add_plugin)
   cmake_minimum_required(VERSION 3.21)
   project(qwen35_fp8 LANGUAGES CXX)
diff --git a/arch/qwen35_fp8/qwen35_fp8.cpp b/arch/qwen35_fp8/qwen35_fp8.cpp
index 77d68017..ce4e6659 100644
--- a/arch/qwen35_fp8/qwen35_fp8.cpp
+++ b/arch/qwen35_fp8/qwen35_fp8.cpp
@@ -1,10 +1,9 @@
-/* qwen35_fp8 -- Qwen3.5 / 3.6 / 3.8 dense, BLOCK-SCALED FP8 weights and FP8 activations.
+/* qwen35_fp8 -- Qwen3.5 / 3.6 / 3.8 dense, block-scaled FP8 weights and FP8 activations.
  *
- * The sibling of qwen35_bf16 and the one that serves the production checkpoint. Same architecture,
- * same graph, same metadata, same name maps for everything that is not a projection matrix -- so
- * the architecture prose lives in qwen35_bf16.cpp and in the three block headers, and this file
- * says only what makes it a different plugin. One plugin implements one architecture id for one
- * quantisation scheme (spec §2.4), and this is the second scheme.
+ * The sibling of qwen35_bf16: same architecture, graph, metadata and name maps for everything but
+ * the projection matrices. The architecture is described in qwen35_bf16.cpp and the block headers;
+ * this file covers what differs. One plugin implements one architecture id for one quantisation
+ * scheme (spec §2.4).
  *
  * ============================== WHAT IT SERVES ==============================
  *
@@ -14,51 +13,38 @@
  *                              "activation_scheme": "dynamic",
  *                              "weight_block_size": [128, 128] }
  *
- * which is Qwen3.8-27B-FP8, Qwen3.6-27B-FP8 and every other DeepSeek-style fp8 release of this
- * family. Each large linear ships as `.weight` in F8_E4M3 [N][K] beside
- * `.weight_scale_inv` in BF16 [ceil(N/128)][ceil(K/128)] -- the codes and the scale plane
- * of one weight, `fp8_e4m3*bf16[128x128]`, which libr4d's three block-scaled fp8 GEMMs read as
- * they are, so the checkpoint loads directly and a .rad of it costs what the checkpoint does.
- *
- * qwen35_bf16's header argues for widening to bf16 instead, and that argument holds only where
- * libr4d's registry exposes no fp8-weight GEMM. It does expose them (libr4d/r4d_fp8.cpp), so the
- * widening is not the cheaper path here: it doubles 24 GiB of weights to 48 GiB to buy nothing.
+ * as in Qwen3.8-27B-FP8, Qwen3.6-27B-FP8 and other DeepSeek-style fp8 releases of this family.
+ * Each large linear ships as `.weight` in F8_E4M3 [N][K] beside `.weight_scale_inv` in
+ * BF16 [ceil(N/128)][ceil(K/128)]: the codes and scale plane of one weight,
+ * `fp8_e4m3*bf16[128x128]`, which libr4d's block-scaled fp8 GEMMs (libr4d/r4d_fp8.cpp) read as
+ * is. The checkpoint loads directly; widening to bf16 would double 24 GiB of weights to 48 GiB.
  *
  * ============================== WHAT IS AND IS NOT FP8 ==============================
  *
- * Read off `layers-0.safetensors` and `layers-3.safetensors` rather than assumed, because the
- * pattern is not "the big ones":
+ * From the checkpoint's safetensors (the pattern is not simply "the big ones"):
  *
  *   F8_E4M3 + scale   self_attn.{q,k,v,o}_proj, mlp.{gate,up,down}_proj,
  *                     linear_attn.{in_proj_qkv, in_proj_z, out_proj}
  *   BF16, no scale    every norm, A_log, dt_bias, conv1d, embed_tokens, lm_head, AND
  *                     linear_attn.in_proj_a / in_proj_b
  *
- * in_proj_a and in_proj_b emit one column per value head -- 48 of them -- and 48 is not a whole
- * 128-row scale block, so the quantiser that made the checkpoint left them alone. That is why
- * GdnFP8 splits the in-projection the bf16 block fuses; rad_block_gdn_fp8.h has the detail.
+ * in_proj_a and in_proj_b emit one column per value head (48), not a whole 128-row scale block,
+ * so the checkpoint's quantiser left them bf16. That is why GdnFP8 splits the in-projection the
+ * bf16 block fuses (rad_block_gdn_fp8.h).
  *
- * The lm_head being bf16 in the checkpoint is worth stating too. It is declared at whatever the
- * model holds it as -- bf16 loaded directly, block fp8 where a recipe quantised it -- and the
- * logits kernel that reads that encoding is the one selected.
+ * The lm_head is declared at whatever the model holds (bf16 as shipped, block fp8 where a recipe
+ * quantised it), and the logits kernel for that encoding is selected.
  */
 /* ============================== ONE SOURCE, TWO PLUGINS ==============================
  *
- * `qwen35moe` is this architecture with the feed-forward ROUTED and everything above it identical:
- * the same gated attention, the same gated delta net, the same layer schedule, the same rope, the
- * same vocabulary edges, the same MTP head in the same position. Qwen3.6-35B-A3B-FP8 is the model,
- * and reading its config beside Qwen3.8-27B-FP8's the only structural difference is `mlp.experts.*`
- * plus a router and a shared expert where `mlp.{gate,up,down}_proj` was.
+ * `qwen35moe` (Qwen3.6-35B-A3B-FP8) is this architecture with a routed feed-forward and
+ * everything above it identical: the only structural difference is `mlp.experts.*` plus a router
+ * and a shared expert in place of `mlp.{gate,up,down}_proj`.
  *
- * So there is ONE source and two translation units, exactly as libr4d's attention dispatches are
- * one set of kernel templates instantiated at three geometries. arch/qwen35moe_fp8/ is four lines
- * that define the three macros below and include this file. The alternative is a second 1300-line
- * plugin kept in step by hand, and two hand-kept copies of one thing drift apart -- the reason
- * libr4d/r4d_rows.cpp keeps exactly one table of its kernels.
- *
- * EVERY DIFFERENCE IS BEHIND `#if QWEN35_MOE` AND THERE ARE SIX OF THEM: the expert-count check,
- * the routing geometry read out of metadata, the block's buffers, the per-layer source names, the
- * MTP head's feed-forward, and the plugin's own identity. Nothing else in this file knows. */
+ * So one source builds two translation units; arch/qwen35moe_fp8/ defines the three macros below
+ * and includes this file. Every difference is behind `#if QWEN35_MOE`: the expert-count check, the
+ * routing geometry read from metadata, the block's buffers, the per-layer source names, the MTP
+ * head's feed-forward, and the plugin identity. */
 #ifndef QWEN35_MOE
 #define QWEN35_MOE 0
 #endif
@@ -88,9 +74,9 @@ namespace QWEN35_NS {
 
 using namespace rad::arch;
 
-/* The feed-forward this build declares, and the ONE name the rest of the file uses for it. Both
- * blocks take the same declare() arity over their own Wire and Src -- the routed one carries its
- * geometry inside its Src for exactly that reason -- so every site below is spelled once. */
+/* The feed-forward this build declares, under one name. Both blocks take the same declare()
+ * arity over their own Wire and Src (the routed one carries its geometry in its Src for this), so
+ * every site below is spelled once. */
 #if QWEN35_MOE
 using Ffn    = MoeFP8;
 using MtpHead = MtpBlockFP8;
@@ -120,9 +106,8 @@ struct Model {
     ActFP8  a_h{};
     /* full attention */
     rad_buf b_qg = 0, b_k = 0, b_v = 0, b_q = 0;
-    /* [rope_table_rows, n_rot] f32, the rope cos/sin every attention layer reads. One buffer and
-     * one fill a step, against a rope launch a layer -- see rad_block_attn_gated_fp8.h at
-     * op_fused. */
+    /* [rope_table_rows, n_rot] f32, the rope cos/sin every attention layer reads: one fill per
+     * step instead of a rope launch per layer (rad_block_attn_gated_fp8.h, op_fused). */
     rad_buf b_rope_cs = 0;
     ActFP8  a_attn{};
     /* gated delta net */
@@ -133,9 +118,8 @@ struct Model {
     rad_buf b_gate_up = 0;
     ActFP8  a_ffn{};
 #if QWEN35_MOE
-    /* ...and the routed one's, which are the expert path's intermediates. They are `moe_rows`
-     * tokens tall and not max_tok, because the expert planes are top_k times as tall as the step;
-     * rad_block_moe_fp8.h argues the slicing. */
+    /* The routed expert path's intermediates. `moe_rows` tall, not max_tok, because expert planes
+     * are top_k times as tall as the step (rad_block_moe_fp8.h). */
     MoeFP8::Config moecfg{};
     rad_buf b_rlogits = 0, b_eids = 0, b_ew = 0, b_sorted = 0, b_eoff = 0, b_ecnt = 0;
     rad_buf b_egu = 0, b_edn = 0, b_emoe = 0;
@@ -144,10 +128,9 @@ struct Model {
     ActFP8  a_sff{};
 #endif
 
-    /* THE DFLASH2 DRAFTER, declared only when the container carries one and the deployment
-     * speculates. It is the second drafter and it is not an alternative spelling of the first: an
-     * MTP head is one chained forward per draft token, this is one forward for the whole block.
-     * Both can be in a container; only one is declared, and DFlash2 wins because it is the better
+    /* The DFlash2 drafter, declared only when the container carries one and the deployment
+     * speculates. An MTP head runs one chained forward per draft token; this runs one forward for
+     * the whole block. If a container carries both, only DFlash2 is declared, being the better
      * drafter on this target. */
     bool          have_df = false;
     Dflash2       df{};
@@ -161,13 +144,11 @@ struct Model {
     rad_buf  b_mtp_dq = 0, b_mtp_ds = 0, b_mtp_dsum = 0;
     rad_buf  b_mtp_dlog = 0, b_mtp_didx = 0, b_mtp_dval = 0;
 
-    /* THE AUXILIARY HIDDEN-STATE TAPS, declared only when the container carries a drafter that
-     * asks for them. A DFlash2 drafter does not read the trunk's FINAL hidden state -- it reads
-     * the residual stream at several intermediate layers and projects the concatenation down, so
-     * `fc` is [n_embd, n_taps * n_embd] and its input has to be one contiguous row. The trunk
-     * keeps one residual buffer that every layer overwrites, so the rows have to be copied out as
-     * they pass, into the column slice that layer owns. Nothing else in the trunk changes, and on
-     * a container with no drafter none of this is declared. */
+    /* Auxiliary hidden-state taps, declared only when the container carries a drafter that wants
+     * them. A DFlash2 drafter reads the residual stream at several intermediate layers and
+     * projects the concatenation down (`fc` is [n_embd, n_taps * n_embd]), so its input must be one
+     * contiguous row. The trunk's one residual buffer is overwritten by every layer, so each tap's
+     * rows are copied into its column slice as they pass. */
     enum { MAX_TAPS = 8 };
     int      n_taps = 0;
     int      tap_layer[MAX_TAPS] = {};
@@ -187,103 +168,13 @@ struct Model {
     std::vector layers;
 };
 
-/* "5 19 33 47 61" -> the layers whose output a drafter wants. rad-convert flattens a config.json
- * array into a space-separated string (tools/rad_convert.cpp, flatten_json), so this is the shape
- * every list-valued key arrives in. Out-of-range entries are dropped rather than clamped: a
- * drafter that names a layer this model does not have is paired with the wrong target, and
- * silently reading layer 63 instead of 71 would make that a quality mystery. */
-static int parse_tap_layers(const char* s, int64_t n_layer, int* out, int max) {
-    if (!s) return 0;
-    int n = 0;
-    for (const char* p = s; *p && n < max;) {
-        while (*p == ' ' || *p == ',') ++p;
-        if (!*p) break;
-        char* e = nullptr;
-        const long v = std::strtol(p, &e, 10);
-        if (e == p) break;
-        p = e;
-        if (v >= 0 && v < n_layer) out[n++] = (int)v;
-    }
-    return n;
-}
-
 static Model g_model[MAX_RANKS];
 
-static inline bool is_full_attention(int64_t l, int64_t interval) {
-    return interval > 0 && ((l + 1) % interval == 0);
-}
-
-/* THE CONTAINER'S OWN LAYER SCHEDULE, CHECKED AGAINST THE ONE WE COMPUTE.
- *
- * `is_full_attention` derives the schedule from one integer: every `interval`-th layer is full
- * attention and the rest are linear. That is llama.cpp's rule and it is right for this model. It
- * is NOT a property of the family -- HuggingFace states the schedule explicitly, as a
- * `layer_types` array of "linear_attention" / "full_attention", and rad-convert carries that array
- * into the container as a space-separated string, which is what this function reads.
- *
- * A model whose array does not match the modular rule would be built with the WRONG LAYERS LINEAR.
- * It would convert, load, and generate fluent text from a different architecture than the one on
- * disk -- the exact silent-wrong-model failure this plugin's check_format exists to prevent one
- * layer down. So: where the container states the schedule, it is authoritative and disagreement
- * is fatal.
- *
- * A container that states nothing is accepted, for check_format's reason -- a .rad converted from
- * a GGUF carries no HuggingFace config, and the modular rule is then the only evidence there is.
- * `text_config.` is where it lands for a checkpoint whose config nests the language model. */
-static int check_layer_schedule(const RadModelMeta* meta, int64_t n_layer, int64_t interval) {
-    const char* s = rad_meta_gets(meta, "qwen35.layer_types", nullptr);
-    if (!s) s = rad_meta_gets(meta, "text_config.layer_types", nullptr);
-    if (!s) s = rad_meta_gets(meta, "layer_types", nullptr);
-    if (!s || !*s) return RAD_OK;
-
-    int64_t l = 0;
-    for (const char* p = s; *p; ) {
-        while (*p == ' ') ++p;
-        if (!*p) break;
-        const char* tok = p;
-        while (*p && *p != ' ') ++p;
-        const size_t len = (size_t)(p - tok);
-
-        const bool says_full = len == 14 && std::strncmp(tok, "full_attention", 14) == 0;
-        const bool says_lin  = len == 16 && std::strncmp(tok, "linear_attention", 16) == 0;
-        if (!says_full && !says_lin) {
-            fprintf(stderr, "radiance: qwen35: layer_types[%lld] is '%.*s'; this plugin knows "
-                            "'full_attention' and 'linear_attention' and will not guess at a "
-                            "third kind of layer.\n", (long long)l, (int)len, tok);
-            return RAD_E_UNSUPPORTED;
-        }
-        /* Past the trunk is the MTP block, which the array may or may not include; it is not a
-         * trunk layer and its kind is the drafter's business (see declare_draft). */
-        if (l >= n_layer) break;
-        if (says_full != is_full_attention(l, interval)) {
-            fprintf(stderr, "radiance: qwen35: the container says layer %lld is %s, and "
-                            "full_attention_interval %lld makes it %s. The interval rule is "
-                            "llama.cpp's and it is not a property of this family -- a model whose "
-                            "layer_types differ from it would be built with the wrong layers "
-                            "linear, and would load and generate fluent text from an architecture "
-                            "that is not the one in the checkpoint. Read layer_types directly "
-                            "before serving this model.\n",
-                    (long long)l, says_full ? "full_attention" : "linear_attention",
-                    (long long)interval,
-                    is_full_attention(l, interval) ? "full_attention" : "linear_attention");
-            return RAD_E_UNSUPPORTED;
-        }
-        ++l;
-    }
-    if (l && l < n_layer) {
-        fprintf(stderr, "radiance: qwen35: layer_types names %lld layers and the model has %lld. "
-                        "A short schedule is not a schedule.\n", (long long)l, (long long)n_layer);
-        return RAD_E_UNSUPPORTED;
-    }
-    return RAD_OK;
-}
-
-/* The container's own statement about its format. Checked rather than assumed, because every
- * failure mode of getting it wrong is silent: a `weight_block_size` of [64,64] against kernels that
- * shift by 7 reads the right bytes with the wrong gain, and an e5m2 checkpoint decodes as e4m3 into
- * numbers that are merely implausible. A container that says nothing at all is accepted -- a .rad
- * converted from a GGUF carries no HuggingFace quantization_config -- because the weight shapes and
- * the scale planes are then the only evidence and they are checked where they are read. */
+/* Checks the container's statement of its format, since every mismatch is silent: a
+ * `weight_block_size` of [64,64] against kernels that shift by 7 reads the right bytes with the
+ * wrong gain, and e5m2 decoded as e4m3 gives merely implausible numbers. A container that states
+ * nothing (a .rad converted from a GGUF) is accepted; weight shapes and scale planes are checked
+ * where they are read. */
 static int check_format(const RadModelMeta* meta) {
     const char* method = rad_meta_gets(meta, "quantization_config.quant_method", nullptr);
     const char* fmt    = rad_meta_gets(meta, "quantization_config.fmt", nullptr);
@@ -315,61 +206,22 @@ static int check_format(const RadModelMeta* meta) {
     return RAD_OK;
 }
 
-/* THE DFLASH2 DRAFTER: its geometry, its KV group, its buffers and its block.
+/* The DFlash2 drafter: its geometry, KV group, buffers and block.
  *
- * Split out of declare() because it is A SECOND MODEL and not a head. It has its own layer count,
- * head count, feed-forward width, rope base, norm convention and vocabulary claim, none of which
- * the trunk's Geom can carry -- so it starts from a COPY of the trunk's (n_embd, the deployment
- * bounds, the rank and the wire) and overwrites everything the drafter's own config states.
+ * A second model, not a head: it has its own layer count, head count, feed-forward width, rope
+ * base, norm convention and vocabulary claim. Its Geom starts as a copy of the trunk's (n_embd,
+ * deployment bounds, rank, wire) and takes everything else from the drafter's config.
  *
- * Nothing here is defaulted quietly. A container whose `draft.` config does not describe a
- * drafter, or describes one this engine does not implement, is refused by name: a drafter that
- * silently ignored a scale factor would simply accept less, which reads as a quality mystery and
- * not as a missing feature (spec §17). */
+ * Nothing is defaulted quietly: a `draft.` config that does not describe a drafter this engine
+ * implements is refused by name, because a silently ignored scale factor would only lower
+ * acceptance (spec §17). */
 static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx,
                            Model& m, int base_layer) {
     Names& nm = m.nm;
-    Geom   dg = m.g;   /* n_embd, the vocabulary, the deployment bounds, the rank, the wire */
-
-    dg.n_layer       = rad_meta_geti(meta, "draft.num_hidden_layers", 0);
-    dg.head_dim      = rad_meta_geti(meta, "draft.head_dim", 0);
-    dg.n_head_all    = rad_meta_geti(meta, "draft.num_attention_heads", 0);
-    dg.n_head_kv_all = rad_meta_geti(meta, "draft.num_key_value_heads", 0);
-    dg.n_ff_all      = rad_meta_geti(meta, "draft.intermediate_size", 0);
-    dg.eps           = (float)rad_meta_getf(meta, "draft.rms_norm_eps", 0.0);
-    dg.theta         = (float)rad_meta_getf(meta, "draft.rope_parameters.rope_theta",
-                                            rad_meta_getf(meta, "draft.rope_theta", 0.0));
-    RAD_ARCH_TRY(yarn_from(dg, meta, "draft.", dg.head_dim));
-    /* PLAIN RMS NORM. The drafter uses the ordinary norm where the trunk uses GemmaRMSNorm, and
-     * the checkpoint agrees rather than only vLLM -- rad_block_dflash2.h has the numbers. Two
-     * conventions in one process, which is exactly why this is a second Geom and not a flag. */
-    dg.wadd = 0.0f;
-    dg.wadd_qk = 0.0f;
-
-    if (dg.n_layer <= 0 || dg.head_dim <= 0 || dg.n_head_all <= 0 || dg.n_head_kv_all <= 0 ||
-        dg.n_ff_all <= 0 || !(dg.eps > 0.0f) || !(dg.theta > 0.0f)) {
-        fprintf(stderr, "radiance: the container's `draft.` config does not describe a DFlash2 "
-                        "drafter: layers %lld, heads %lld / kv %lld, head_dim %lld, ffn %lld, "
-                        "rms_eps %g, rope_theta %g\n",
-                (long long)dg.n_layer, (long long)dg.n_head_all, (long long)dg.n_head_kv_all,
-                (long long)dg.head_dim, (long long)dg.n_ff_all, (double)dg.eps, (double)dg.theta);
-        return RAD_E_INVAL;
-    }
-    int s;
-    if ((s = divide_or_fail(dg.n_head_all,    dg.world, "draft num_attention_heads", &dg.n_head))    < 0) return s;
-    if ((s = divide_or_fail(dg.n_head_kv_all, dg.world, "draft num_key_value_heads", &dg.n_head_kv)) < 0) return s;
-    if ((s = divide_or_fail(dg.n_ff_all,      dg.world, "draft intermediate_size",   &dg.n_ff))      < 0) return s;
-
-    /* THE DRAFTER BORROWS THE TARGET'S EMBEDDING TABLE AND lm_head -- it ships neither -- so a
-     * vocabulary that disagrees is not a drafter for this target at all. */
-    const long long dvocab = rad_meta_geti(meta, "draft.vocab_size", dg.n_vocab_all);
-    if (dvocab != dg.n_vocab_all) {
-        fprintf(stderr, "radiance: the DFlash2 drafter claims a %lld-token vocabulary and the "
-                        "target has %lld. The drafter ships no embedding table and no lm_head; it "
-                        "reads the target's, so the two have to be the same vocabulary.\n",
-                dvocab, (long long)dg.n_vocab_all);
-        return RAD_E_UNSUPPORTED;
-    }
+    Geom   dg{};
+    /* Plain RMS norm: the drafter uses the ordinary norm where the trunk uses GemmaRMSNorm
+     * (rad_block_dflash2.h). */
+    RAD_ARCH_TRY(drafter_geom(dg, m.g, meta, "DFlash2"));
 
     Dflash2::Config dc{};
     dc.n_taps   = m.n_taps;
@@ -389,10 +241,9 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
         return RAD_E_INVAL;
     }
 
-    /* THE QUERY BLOCK MUST BE A POWER OF TWO, and this is where that is said. The convolution
-     * masks a row's position within the block with `block_size - 1`, so any other value silently
-     * convolves one sequence's block into the next -- the shim rejects it, but by then the
-     * deployment has loaded four gigabytes of drafter to be told no. */
+    /* The query block must be a power of two: the convolution masks a row's position with
+     * `block_size - 1`, so any other value convolves one sequence's block into the next. The shim
+     * also rejects it, but only after the drafter's weights have loaded. */
     const long long trained = rad_meta_geti(meta, "draft.dflash_config.block_size", 0);
     if (dc.block < 2 || (dc.block & (dc.block - 1))) {
         fprintf(stderr, "radiance: DFlash2's convolution masks the block position with "
@@ -403,15 +254,12 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
         return RAD_E_UNSUPPORTED;
     }
     if (trained > 0 && trained != dc.block)
-        rad_note(b, "DFlash2 was trained at block_size %lld (%lld draft tokens) and this serve "
-                    "asks for %lld. A block-diffusion drafter denoises a fixed number of mask "
-                    "positions and was trained for one block length; it will run, and it will "
-                    "accept less than the checkpoint can do",
+        rad_note(b, "DFlash2 was trained at block_size %lld (%lld draft tokens) and runs at "
+                    "%lld; it accepts less away from its trained block length",
                  trained, trained - 1, (long long)dc.block);
 
-    /* Three scalars this drafter's family can carry that this implementation does not apply.
-     * Each of them changes what the drafter proposes, and each would show up as acceptance that
-     * is merely disappointing rather than as anything that looks like a bug. */
+    /* Three scalars this implementation does not apply. Each changes the proposals and would show
+     * up only as lower acceptance, so a non-default value is refused. */
     const double escale = rad_meta_getf(meta, "draft.dflash_config.input_embedding_scale", 1.0);
     const double omul   = rad_meta_getf(meta, "draft.dflash_config.output_multiplier", 1.0);
     const double scap   = rad_meta_getf(meta, "draft.dflash_config.final_logit_softcapping", 0.0);
@@ -423,26 +271,12 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
         return RAD_E_UNSUPPORTED;
     }
 
-    /* THE DRAFTER'S OWN KV CACHE, a group of its own. It cannot share the trunk's: different head
-     * count, different head_dim, five layers against sixteen, and -- the one that matters -- a
-     * WINDOW. RAD_KV_WINDOW recycles the blocks that fall below it, so this cache is sized by the
-     * drafter's 2048-token window and not by the model's context length. Its width is the trunk's,
-     * --kv-cache-dtype: one flag says what every attention cache of the deployment is made of. */
-    RadKVGroupDecl dd{};
-    dd.kind      = dc.window > 0 ? RAD_KV_WINDOW : RAD_KV_FULL;
-    dd.dtype     = rad_kv_cache_dtype(ctx, RAD_BF16);
-    dd.window    = dc.window;
-    dd.n_head_kv = dg.n_head_kv;
-    dd.head_dim  = dg.head_dim;
-    m.kv_draft = rad_decl_kv_group(b, nm.f("kv_draft"), &dd);
-    for (int64_t l = 0; l < dg.n_layer; ++l)
-        RAD_ARCH_TRY(rad_bind_layer_kv(b, base_layer + (int)l, m.kv_draft));
-    dg.kv_dtype = rad_dtype_name(dd.dtype);
+    /* The window bounds the cache: the drafter's 2048-token window, not the context length. */
+    RAD_ARCH_TRY(drafter_kv_group(b, nm, ctx, dg, dc.window, base_layer, &m.kv_draft));
 
-    /* Activation buffers. The context pass is one row a COMMITTED TOKEN and runs over a whole
-     * prefill chunk; everything after it is one row a DRAFT POSITION, `block` of them a sequence,
-     * so the two halves are sized apart. None of it is large -- the drafter's cost is its
-     * weights, not its activations. */
+    /* Activations. The context pass has one row per committed token over a whole prefill chunk;
+     * the query pass one row per draft position, `block` per sequence; the two are sized apart.
+     * All are small: the drafter's cost is its weights. */
     const int64_t qd  = dg.n_head * dg.head_dim;
     const int64_t kvd = dg.n_head_kv * dg.head_dim;
     int64_t qr = dg.max_seqs * dc.block;
@@ -465,11 +299,10 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
     dw.attn    = decl_b(b, nm.f("df_attn"), dg.act_dtype, {qr, qd});
     dw.gate_up = decl_b(b, nm.f("df_gate_up"), dg.act_dtype, {qr, 2 * dg.n_ff});
     dw.ffn     = decl_b(b, nm.f("df_ffn"),  dg.act_dtype, {qr, dg.n_ff});
-    /* THE FP8 TWINS. The drafter's six linears are block-scaled fp8 over a bf16 checkpoint
-     * (rad_fp8.h's DenseFP8), so every activation that feeds one carries an E4M3 copy and a plane
-     * of f32 scales beside it. `srcq` is the largest of them by a distance -- 50 MiB at a
-     * 2048-token chunk and five taps, against the 100 MiB `dflash_src` it shadows -- and it buys
-     * half the bytes of the one GEMM the context pass spends its time in. */
+    /* FP8 copies. The drafter's six linears are block-scaled fp8 over a bf16 checkpoint
+     * (rad_fp8.h's DenseFP8), so every activation feeding one has an E4M3 copy and an f32 scale
+     * plane. `srcq` is the largest (50 MiB at a 2048-token chunk and five taps) and halves the
+     * bytes of the context pass's dominant GEMM. */
     dw.srcq    = decl_b(b, nm.f("df_srcq"), RAD_F8E4M3,
                         {dg.max_tok, dc.n_taps * dg.n_embd});
     dw.srcs    = decl_b(b, nm.f("df_srcs"), RAD_F32,
@@ -486,16 +319,15 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
     dw.hp      = decl_b(b, nm.f("df_hp"),   dg.act_dtype, {sr, dc.sel_rank});
     dw.dq      = decl_b(b, nm.f("df_dq"),   RAD_I8,  {sr, dg.n_embd});
     dw.ds      = decl_b(b, nm.f("df_ds"),   RAD_F32, {sr, 1});
-    /* GROUP-major, [n_embd/group][ceil(M/16)*16] -- quant_act_i8's asum plane, whose first
-     * dimension is the K group and not the token. */
+    /* Group-major, [n_embd/group][ceil(M/16)*16]: quant_act_i8's asum plane, whose first
+     * dimension is the K group, not the token. */
     dw.dsum    = decl_b(b, nm.f("df_dsum"), RAD_F32, {dg.n_embd / 128, spad});
-    /* THIS RANK'S plane. `head_rows` is the block's own answer to whether the 2-bit head is
-     * vocab-sharded, asked here rather than re-derived, because a buffer that disagreed with the
-     * op declared over it is a read past its end. */
+    /* This rank's plane. `head_rows` is the block's own answer to whether the 2-bit head is
+     * vocab-sharded; asking it keeps the buffer consistent with the op declared over it. */
     dw.dlog    = decl_b(b, nm.f("df_dlog"), dg.act_dtype, {sr, Dflash2::head_rows(dg)});
-    /* THE CANDIDATES ARE RESCORED against the target's head when logit_rerank can read its plane
-     * (fp8 or int8 rows) and every candidate a rank proposes is one it owns -- the rule the block
-     * applies; the planes are then kRerankR wide and the selector reads the first sel_topk. */
+    /* Candidates are rescored against the target's head when logit_rerank can read its plane
+     * (fp8 or int8 rows) and every candidate a rank proposes is one it owns; the planes are then
+     * kRerankR wide and the selector reads the first sel_topk. */
     {
         const uint32_t hd = weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16);
         if ((hd == RAD_F8E4M3 || hd == RAD_I8) && (Dflash2::head_sharded(dg) || dg.world <= 1)) {
@@ -512,29 +344,24 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
         dw.dpair = decl_b(b, nm.f("df_dpair"), RAD_F32, {sr, tw, 2});
         dw.dgath = decl_b(b, nm.f("df_dgath"), RAD_F32, {sr, (int64_t)dg.world * tw, 2});
     }
-    /* NAMED, because the engine reads the draft out of it by name: a DFlash2 pass proposes through
-     * the selector and never through the sampler's token buffer. */
+    /* The proposal buffer (RadDrafterDecl::proposal): a DFlash2 pass proposes through the
+     * selector, never through the sampler's token buffer. */
     dw.tokens  = decl_b(b, nm.f("dflash_tokens"), RAD_I32, {dg.max_seqs, dc.steps()});
 
     RAD_ARCH_TRY(m.df.declare(b, nm, dg, dc, base_layer, m.kv_draft, m.w_tok, "draft",
                               nm.ckpt("lm_head.weight"), dw));
     m.have_df = true;
 
-    /* WHAT THE ENGINE DRIVES. Block: a context pass that mirrors the trunk step, then ONE pass
-     * that fills the whole block. `mask_token_id` is read HERE and nowhere else: it travels in the
-     * drafter declaration, so no other component has to sniff the container for a drafter.
-     *
-     * `window` must be the number this plugin gated its OWN attention with, because the scheduler
-     * stages the block pass against it: two readings of "how far back can the drafter see" is
-     * a drafter attending to positions the scheduler did not stage. */
+    /* Block drafter: a context pass mirroring the trunk step, then one pass filling the whole
+     * block. `mask_token_id` is read only here and travels in the drafter declaration. `window`
+     * must be the one this plugin gated its own attention with, since the scheduler stages the
+     * block pass against it. */
     RadDrafterDecl drf{};
     drf.name           = "dflash2";
     drf.kind           = RAD_DRAFT_BLOCK;
     drf.depth          = ctx->max_spec;
-    /* THE ANCHOR ROW PREDICTS NOTHING here, so the block is one row longer than the depth and the
-     * head runs over rows 1..depth. Stated rather than defaulted: it is the half of the row
-     * alignment that lives in this plugin, and the other convention is a real drafter
-     * (rad_builder.h, RadDrafterDecl::block). */
+    /* The anchor row predicts nothing here, so the block is one row longer than the depth and the
+     * head runs over rows 1..depth (rad_builder.h, RadDrafterDecl::block). */
     drf.block          = dc.block;
     drf.proposal       = dw.tokens;
     drf.proposal_pitch = dc.steps();
@@ -548,10 +375,9 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
     }
     RAD_ARCH_TRY(rad_declare_drafter(b, &drf));
 
-    rad_note(b, "the DFlash2 drafter is declared: %lld layers of its own at absolute %d..%d, "
-                "%lld heads / %lld kv x %lld, ffn %lld, %s attention with a %lld-token window, "
-                "reading the trunk at %d tap(s). ONE forward proposes %lld tokens -- there are no "
-                "rounds -- and the candidate selector walks a path through the block",
+    rad_note(b, "DFlash2 drafter: %lld layers at absolute %d..%d, %lld heads / %lld kv x %lld, "
+                "ffn %lld, %s attention with a %lld-token window, %d trunk tap(s); one forward "
+                "proposes %lld tokens through the candidate selector",
              (long long)dg.n_layer, base_layer, base_layer + (int)dg.n_layer - 1,
              (long long)dg.n_head, (long long)dg.n_head_kv, (long long)dg.head_dim,
              (long long)dg.n_ff, dc.causal ? "causal" : "non-causal", (long long)dc.window,
@@ -567,10 +393,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     m = Model{};
     m.nm = Names(ctx->scope);
     RAD_ARCH_TRY(check_format(meta));
-    /* "bf16" is the ACTIVATION dtype and it is what every op but the fp8 linears matches on: the
-     * norms, rope, attention, the delta-net kernels and the collectives all run on bf16 here, and
-     * the E4M3 activations exist only between quant_act_fp8 and the GEMM that reads them. Saying
-     * "fp8" here would be saying it about the residual stream, which is false. */
+    /* "bf16" is the activation dtype every op but the fp8 linears matches on: norms, rope,
+     * attention, delta-net kernels and collectives run on bf16, and E4M3 activations exist only
+     * between quant_act_fp8 and the GEMM that reads them. */
     RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
 
 #if QWEN35_MOE
@@ -601,40 +426,29 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                 (long long)interval, (long long)nextn, (long long)g.n_layer);
         return RAD_E_INVAL;
     }
-    RAD_ARCH_TRY(check_layer_schedule(meta, g.n_layer, interval));
-    /* EVERY DECLARED LAYER IS A TRUNK LAYER. `mtp_num_hidden_layers` is NOT part of
-     * `num_hidden_layers` in this family -- Qwen3.8-27B-FP8 ships layers-0..63 under
-     * `model.language_model.layers.N` and its one MTP block separately, under an `mtp.` prefix of
-     * its own, in mtp.safetensors. Subtracting it here would drop layer 63, which is a
-     * full-attention layer, and the model would answer with the trunk one layer short: still a
-     * distribution, still self-consistent op by op, and wrong. `nextn` is kept for the note below,
-     * which is the only thing the count is good for until the MTP head is declared. */
+    RAD_ARCH_TRY(check_layer_schedule("qwen35", meta_text_gets(meta, "layer_types", nullptr),
+                                      g.n_layer, interval, {"full_attention"}));
+    /* Every declared layer is a trunk layer: `mtp_num_hidden_layers` is not part of
+     * `num_hidden_layers` in this family. Qwen3.8-27B-FP8 ships layers 0..63 under
+     * `model.language_model.layers.N` and its MTP block separately under `mtp.`; subtracting it
+     * would drop full-attention layer 63 and silently run a trunk one layer short. */
     m.n_main = g.n_layer;
 
-    /* Qwen3.5's norms are GemmaRMSNorm: `x_hat * (1 + w)`, not `x_hat * w`. vLLM says so by
-     * importing it under the family's own name -- `from ...layernorm import GemmaRMSNorm as
-     * Qwen3_5RMSNorm` -- and the checkpoint says so too: `input_layernorm.weight` sits around 0.07
-     * to 0.29, which is a gain of 1.1 to 1.3 the right way round and a five-to-ten-times shrink
-     * the wrong way. It applies to input_layernorm, post_attention_layernorm, the model's final
-     * norm and the q/k head norms -- and NOT to the delta net's ssm_norm, which is a plain
-     * RMSNormGated with gains around 0.88.
-     *
-     * The checkpoint answers two of the three families by itself: the layer norms (0.07..0.29)
-     * and the q/k head norms (partly NEGATIVE) can only be `1 + w`. The model's FINAL norm sits at
-     * 0.68..0.96, which reads as either, and takes `1 + w` because the reference implementation
-     * does. */
+    /* Qwen3.5's norms are GemmaRMSNorm, `x_hat * (1 + w)` (vLLM imports GemmaRMSNorm as
+     * Qwen3_5RMSNorm). This covers input_layernorm, post_attention_layernorm, the final norm and
+     * the q/k head norms, but not the delta net's ssm_norm, a plain RMSNormGated (gains ~0.88).
+     * The checkpoint confirms it: layer norm weights of 0.07..0.29 and partly negative q/k norm
+     * weights only make sense as `1 + w`. The final norm (0.68..0.96) is ambiguous and follows the
+     * reference implementation. */
     g.wadd    = 1.0f;
     g.wadd_qk = 1.0f;
     const float final_wadd = 1.0f;
 
     m.n_rot = meta_int2(meta, "qwen35.rope.dimension_count", "rope_dimension_count", 0);
     if (m.n_rot <= 0) {
-        /* BOTH SPELLINGS, because the family uses both. Qwen3.8-27B-FP8 states
-         * `partial_rotary_factor` at the text_config level AND inside `rope_parameters`;
-         * Qwen3.5-0.8B states it ONLY inside `rope_parameters`, and rad-convert flattens nested
-         * config with a dot. Reading only one spelling refuses a container of the same
-         * architecture with "no usable rotary width", which is a true statement about the key and
-         * a false one about the model. */
+        /* Both spellings occur in this family: Qwen3.8-27B-FP8 states `partial_rotary_factor`
+         * at the top level and inside `rope_parameters`, Qwen3.5-0.8B only inside
+         * `rope_parameters` (rad-convert flattens nested config with a dot). */
         double prf = rad_meta_getf(meta, "partial_rotary_factor", 0.0);
         if (!(prf > 0.0)) prf = rad_meta_getf(meta, "rope_parameters.partial_rotary_factor", 0.0);
         if (prf > 0.0) m.n_rot = (int64_t)(g.head_dim * prf);
@@ -681,60 +495,39 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     const int64_t v_dim    = gc.v_dim();
     const int64_t conv_dim = gc.conv_dim();
 
-    /* ---- the three KV groups. The attention cache is BF16 and `kv_dtype` follows it.
+    /* ---- the three KV groups. The attention cache is bf16 by default; `kv_dtype` follows it.
      *
-     * --kv-cache-dtype fp8 MAKES IT E4M3, AND IT IS THE ONE KNOB HERE THAT IS WORTH REAL TIME
-     * AT DEPTH. The attention cache is
-     * `n_head_kv * head_dim * 2` bytes a token a layer -- 2 KiB a rank on this model -- and ONLY
-     * the 16 attention layers pay it, because the 48 delta-net layers carry fixed-size state
-     * instead. At eight sequences of 16k that is 4.3 GB of read traffic a step, which is most of
-     * what depth costs at that concurrency, and halving the width halves it. It also halves what a
-     * sequence costs in the KV pool, which is context and batch size as well as time.
+     * --kv-cache-dtype fp8 makes it E4M3. The cache is `n_head_kv * head_dim * 2` bytes per token
+     * per layer (2 KiB per rank here), paid only by the 16 attention layers; the 48 delta-net
+     * layers carry fixed-size state. At eight sequences of 16k that is 4.3 GB of reads per step,
+     * most of the cost of depth at that concurrency, and fp8 halves it along with each sequence's
+     * KV pool footprint.
      *
-     * IT IS OFF BY DEFAULT ON A QUALITY ARGUMENT, not as a precaution. Greedy continuations from a
-     * long prompt agree between bf16 and fp8 for the first few hundred tokens and then diverge,
-     * and the fp8 side can produce syntactically broken code where the bf16 side stays clean --
-     * and this model is a CODER, so that is the workload.
+     * Off by default for quality: greedy continuations from a long prompt agree for a few hundred
+     * tokens and then diverge, and the fp8 side can produce syntactically broken code where bf16
+     * stays clean, which matters for a coding model.
      *
-     * Comparing the two formats takes more than a byte comparison: a few hundred tokens of
-     * agreement is not evidence that survives a longer sample, and once the text moves the only
-     * question left is whether what it moved to is WORSE, which needs reading and more than one
-     * prompt. Alternate the two -- bf16 / fp8 / bf16 / fp8 -- so a difference between the FORMATS
-     * can be told from a difference between two runs of one.
-     *
-     * `--kv-cache-dtype fp8` turns it on. The descales stay at libr4d's default of 1.0, which is
-     * vLLM's default too; the kernels index them per (sequence, head), so a calibrated pair needs
-     * no different mechanism.
-     *
-     * Nothing else moves with it: the fp8kv attention rows and their `k_descale` / `v_descale`
-     * operands are in libr4d, the core sizes a page from the group's own dtype, and
-     * `kv_store_fp8` is the write side. The drafter's cache takes the same width
-     * (declare_dflash2). */
+     * The descales stay at libr4d's default of 1.0 (vLLM's default too); the kernels index them
+     * per (sequence, head), so calibrated descales need no other mechanism. The fp8kv attention
+     * rows and `kv_store_fp8` are in libr4d, the core sizes a page from the group's dtype, and the
+     * drafter's cache takes the same dtype (declare_dflash2). */
     RadKVGroupDecl fd{};
     fd.kind      = RAD_KV_FULL;
     fd.dtype     = rad_kv_cache_dtype(ctx, RAD_BF16);
     fd.n_head_kv = g.n_head_kv;
     fd.head_dim  = g.head_dim;
     m.kv_full = rad_decl_kv_group(b, nm.f("kv_attn"), &fd);
-    /* The op parameter has to be the SAME SPELLING the rows band on, and the rows band on
-     * rad_dtype_name's, so it is taken from there rather than written out twice. */
+    /* The op parameter must use the spelling the rows band on, which is rad_dtype_name's. */
     g.kv_dtype = rad_dtype_name(fd.dtype);
 
-    /* THE SSM STATE CACHE IS f32.
+    /* The SSM state cache is f32.
      *
-     * The state read and write ARE the two GDN kernels: one [128,128] state is 64 KiB at f32, and
-     * a speculative step writes one PER CANDIDATE TOKEN PER HEAD, because which candidate survives
-     * verification is not known until after the layer has run. At depth 7 that is hundreds of
-     * megabytes a rank a step, and one of the largest single kernels after the fp8 GEMMs. An f16
-     * state would halve it.
-     *
-     * libr4d compiles both widths (`SDT`), and it argues the numerics where the kernel lives: the
-     * elements are O(0.1) with no range problem and f16's eleven mantissa bits are four more than
-     * bf16's, which puts the round-trip error at 5e-4 relative. vLLM allocates this cache from
-     * `--mamba-ssm-cache-dtype`, and reference serves of this model pass `float16`.
-     *
-     * f32 ALL THE SAME, because f16 changes the generated text, and nothing else in this plugin
-     * does that without being asked to. */
+     * State reads and writes dominate the two GDN kernels: one [128,128] state is 64 KiB at f32,
+     * and a speculative step writes one per candidate token per head, since the surviving
+     * candidate is unknown until after the layer. At depth 7 that is hundreds of MB per rank per
+     * step; f16 would halve it. libr4d compiles both widths (`SDT`) and the f16 round-trip error is
+     * ~5e-4 relative (elements are O(0.1)); vLLM's `--mamba-ssm-cache-dtype` is commonly float16.
+     * It stays f32 because f16 changes the generated text. */
     RadKVGroupDecl sd{};
     sd.kind         = RAD_KV_LINEAR;
     sd.dtype        = RAD_F32;
@@ -751,11 +544,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     cd.conv_width = gc.conv_width;
     m.kv_conv = rad_decl_kv_group(b, nm.f("kv_gdn_conv"), &cd);
 
-    /* ---- activation buffers. Every activation that FEEDS A GEMM carries an fp8 twin: an E4M3
-     * plane of the same shape and an f32 scale plane one column per 128. The twins are transients
-     * like everything else here, so the liveness analysis shares their storage with whatever else
-     * is dead at that point -- but they are not free, and the largest is `ffn`: 8192 x 17408 bytes
-     * is 143 MiB against the 285 MiB the bf16 buffer it shadows already costs. */
+    /* ---- activation buffers. Every activation that feeds a GEMM has an fp8 copy: an E4M3 plane
+     * of the same shape and an f32 scale plane with one column per 128. They are transients that
+     * liveness analysis can share, but not free: the largest, `ffn`'s, is 8192 x 17408 bytes
+     * (143 MiB) beside its 285 MiB bf16 buffer. */
     m.b_x       = decl_b(b, nm.f("x"),        g.act_dtype, {g.max_tok, g.n_embd});
     m.a_h.x     = decl_b(b, nm.f("h"),        g.act_dtype, {g.max_tok, g.n_embd});
     RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd));
@@ -765,23 +557,20 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     m.b_v       = decl_b(b, nm.f("attn_v"),   g.act_dtype, {g.max_tok, kv_dim});
     m.b_q       = decl_b(b, nm.f("attn_q"),   g.act_dtype, {g.max_tok, q_dim});
     m.a_attn.x  = decl_b(b, nm.f("attn_out"), g.act_dtype, {g.max_tok, q_dim});
-    /* THE ROPE TABLE, and it is the model's rather than a layer's because sixteen layers rotate at
-     * the same positions with the same theta. Only the rows a step names are written, so the fill
-     * is kilobytes; the plane has a row per position, past `max_ctx` by the speculative window
-     * (rope_table_rows), because the fused kernel indexes it by ABSOLUTE position. f32, so the
-     * cosines the fused rotation multiplies are the ones `rope` computes. */
-    /* PERSIST, not transient. A transient may share storage with another transient, and this one is
-     * written once at the top of a step and read by sixteen layers spread across the whole of it --
-     * so anything the planner overlaps it with lands in the middle of its live range. It is also
-     * the only buffer here whose rows outlive the step that wrote them, which is what PERSIST is
-     * for. */
+    /* The rope table, shared by all sixteen attention layers (same positions, same theta). Only
+     * the rows a step names are written. One row per absolute position, past `max_ctx` by the
+     * speculative window (rope_table_rows), because the fused kernel indexes it by absolute
+     * position. f32, so the fused rotation uses the same cosines `rope` computes.
+     *
+     * PERSIST: its rows outlive the step that wrote them, and it is read across the whole step, so
+     * it must not share storage with transients. */
     m.b_rope_cs = decl_b(b, nm.f("rope_cs"), RAD_F32, {rope_table_rows(g), m.n_rot},
                          RAD_BUF_PERSIST);
     RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", q_dim));
 
-    /* `gdn_in` is conv_dim + v_dim and not in_dim: a and b are their own buffer here because the
-     * checkpoint keeps them bf16, and the output gate is the tail of THIS one because it does not
-     * (rad_block_gdn_fp8.h). The convolution and the gate are column views of it. */
+    /* `gdn_in` is conv_dim + v_dim, not in_dim: a and b have their own buffer because the
+     * checkpoint keeps them bf16, while the fp8 output gate is the tail of this one
+     * (rad_block_gdn_fp8.h). The convolution input and the gate are column views of it. */
     m.a_in.x    = decl_b(b, nm.f("gdn_in"),   g.act_dtype, {g.max_tok, conv_dim + v_dim});
     RAD_ARCH_TRY(m.a_in.declare_qs(b, nm, g, "gdn_in", conv_dim + v_dim));
     m.b_ab      = decl_b(b, nm.f("gdn_ab"),   g.act_dtype, {g.max_tok, gc.ab_dim()});
@@ -790,27 +579,22 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     m.b_gv      = decl_b(b, nm.f("gdn_v"),    g.act_dtype, {g.max_tok, gc.n_head_v, gc.head_v});
     m.b_gdec    = decl_b(b, nm.f("gdn_g"),    RAD_F32,     {g.max_tok, gc.n_head_v});
     m.b_beta    = decl_b(b, nm.f("gdn_beta"), RAD_F32,     {g.max_tok, gc.n_head_v});
-    /* BF16, not f32. gdn_kkt_solve WRITES this plane as `unsigned short*` and gdn_chunk_scan reads
-     * it back the same way -- libr4d's rows say "bf16 k and A out" and "bf16 q/k/v/A". Declaring
-     * it f32 sizes it at twice the bytes and makes the two kernels disagree about every element;
-     * libref reads the operand's own dtype and is correct either way, which is exactly why nothing
-     * on the host path would catch that. */
+    /* bf16, not f32: gdn_kkt_solve writes this plane as `unsigned short*` and gdn_chunk_scan
+     * reads it the same way. libref reads the declared dtype and is correct either way, so a wrong
+     * declaration would not show up on the host path. */
     m.b_kkt     = decl_b(b, nm.f("gdn_kkt"),  RAD_BF16,    {g.max_tok, gc.n_head_v, gc.chunk});
-    /* RANK 3, because libr4d's scan and recurrent kernels require it there -- and the quantiser
-     * takes it that way, reading dim 0 as the row. */
+    /* Rank 3, as libr4d's scan and recurrent kernels require; the quantiser reads dim 0 as the
+     * row. */
     m.a_go.x    = decl_b(b, nm.f("gdn_o"),    g.act_dtype, {g.max_tok, gc.n_head_v, gc.head_v});
     RAD_ARCH_TRY(m.a_go.declare_qs(b, nm, g, "gdn_o", v_dim));
 
 #if QWEN35_MOE
-    /* ---- THE ROUTING GEOMETRY, read here rather than in the block so that a refusal names the
-     * container's key and not an internal struct field. `n_ff` is already the PER-RANK expert
-     * width: rad-convert falls `intermediate_size` back to `moe_intermediate_size`, which on a
-     * routed checkpoint is the only one there is, and geom_from divided it by world_size.
+    /* ---- the routing geometry, read here so a refusal names the container's key. `n_ff` is
+     * already the per-rank expert width: rad-convert falls `intermediate_size` back to
+     * `moe_intermediate_size` and geom_from divided it by world_size.
      *
-     * THE EXPERT COUNT IS NOT DIVIDED. Every rank holds every expert and routes every token the
-     * same way; what tensor parallel splits is each expert's INTERMEDIATE width, which is the
-     * division geom_from already made. Sharding the expert SET instead would make the two ranks
-     * compute different tokens and the block's all-reduce would sum two models. */
+     * The expert count is not divided. Every rank holds every expert and routes every token the
+     * same way; tensor parallelism splits each expert's intermediate width. */
     {
         MoeFP8::Config& mc = m.moecfg;
         mc.n_expert = meta->n_expert;
@@ -818,11 +602,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                                               : meta_int2(meta, "qwen35.expert_used_count",
                                                           "num_experts_per_tok", 0);
         mc.n_ff_exp = g.n_ff;
-        /* `norm_topk_prob` defaults TRUE in this family (Qwen2-MoE onward), and a container that
-         * does not say so gets the family's answer rather than an off switch. It is the difference
-         * between routing weights that sum to one and weights that sum to whatever the top-k of a
-         * softmax over 256 experts happened to be -- roughly 0.4 here, so reading it the other way
-         * scales every routed contribution down by more than half. */
+        /* `norm_topk_prob` defaults to true in this family (Qwen2-MoE onward). Without it the
+         * top-k weights of a softmax over 256 experts sum to roughly 0.4 here, shrinking every
+         * routed contribution by more than half. */
         mc.norm_topk = (int)meta_int2(meta, "qwen35.expert_weights_norm", "norm_topk_prob", 1);
         const int64_t sh_all = meta_int2(meta, "qwen35.expert_shared_feed_forward_length",
                                          "shared_expert_intermediate_size", 0);
@@ -844,9 +626,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
         }
     }
     {
-        /* THE STEP'S HEIGHT FOR EVERYTHING THAT IS ONE ROW A TOKEN, and a PASS's height only for
-         * the four planes that carry one row per (token, slot). rad_block_moe_fp8.h states the
-         * rule at Wire and says what breaks if it is not kept. */
+        /* The step's height for everything with one row per token, and a pass's height only for
+         * the four planes with one row per (token, slot); see the rule at rad_block_moe_fp8.h,
+         * Wire. */
         const MoeFP8::Config& mc = m.moecfg;
         const int64_t R = g.max_tok, K = mc.rows * mc.top_k;
         m.b_rlogits = decl_b(b, nm.f("moe_logits"), g.act_dtype, {R, mc.n_expert});
@@ -854,8 +636,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
         m.b_ew      = decl_b(b, nm.f("moe_w"),      g.act_dtype, {R, mc.top_k});
         m.b_sorted  = decl_b(b, nm.f("moe_sorted"), RAD_I32,     {K});
         m.b_eoff    = decl_b(b, nm.f("moe_off"),    RAD_I32,     {mc.n_expert + 1});
-        /* PERSIST: the histogram's only reader is rad_route_report, which is not a declared op, so
-         * liveness would see it dead the moment moe_scatter wrote it. See qwen4exp_fp8.cpp. */
+        /* PERSIST: the histogram's only reader is rad_route_report, not a declared op, so
+         * liveness would see it dead as soon as moe_scatter wrote it. */
         m.b_ecnt    = decl_b(b, nm.f("moe_cnt"),    RAD_I32,     {mc.n_expert},
                              RAD_BUF_PERSIST);
         m.b_egu     = decl_b(b, nm.f("moe_gate_up"), g.act_dtype, {K, 2 * mc.n_ff_exp});
@@ -881,14 +663,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
 
     m.b_hout    = decl_b(b, nm.f("h_out"),    g.act_dtype, {g.max_logit_rows, g.n_embd});
 
-    /* The auxiliary taps. Gated on the DRAFTER being in the container AND on the deployment
-     * intending to speculate: the buffer is one residual stream per tap, 100 MiB at a 2048-token
-     * chunk and five taps, which a server that never drafts should not be carrying. `cast` is the
-     * copy -- see libr4d/r4d_rows.cpp on why the destination is a column slice. */
+    /* The auxiliary taps, only when the container carries the drafter and the deployment
+     * speculates: one residual stream per tap, 100 MiB at a 2048-token chunk and five taps. `cast`
+     * does the copy into a column slice (libr4d/r4d_rows.cpp). */
     if (ctx->max_spec > 0) {
         const char* da = rad_meta_gets(meta, "draft.architectures", "");
         if (da && std::strstr(da, "DFlash")) {
-            m.n_taps = parse_tap_layers(
+            m.n_taps = parse_layer_ids(
                 rad_meta_gets(meta, "draft.dflash_config.target_layer_ids", nullptr),
                 m.n_main, m.tap_layer, Model::MAX_TAPS);
             if (m.n_taps > 0) {
@@ -906,19 +687,16 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     m.b_logits  = decl_b(b, nm.f("logits"),   RAD_F32,     {g.max_logit_rows, g.n_vocab});
     RAD_ARCH_TRY(rad_declare_logits(b, m.b_logits));
 
-    /* ---- vocabulary edges. The embedding is bf16 in this checkpoint. The lm_head is whatever the
-     * model holds it as -- bf16 as the checkpoint ships it, or block fp8 where the recipe made it
-     * so -- and it is declared at its codes' dtype, so the logits kernel that reads that encoding
-     * is the one selected: the widest GEMM in the model at half the bytes when it is fp8.
+    /* ---- vocabulary edges. The embedding is bf16. The lm_head is declared at its codes' dtype
+     * (bf16 as shipped, or block fp8 where the recipe made it so; the widest GEMM at half the
+     * bytes), selecting the logits kernel for that encoding.
      *
-     * AND BOTH ARE ROW-SHARDED WITH THE VOCABULARY. Sharding one end and replicating the other
-     * would put 248320 x 5120 in bf16 -- 2.43 GiB -- on EVERY rank, and that is KV cache.
-     * `embed_lookup` takes a `vocab_offset`, so a rank gathers the ids in its own slice and writes
-     * a zero row for the rest, and the all_reduce below sums the ranks back into x. Every token
-     * lands on exactly one rank, so the sum is exact and `exact` is not the wire's choice to make
-     * here.
+     * Both are row-sharded with the vocabulary; replicating one would put 248320 x 5120 bf16
+     * (2.43 GiB) on every rank, at the expense of KV cache. `embed_lookup` takes a `vocab_offset`:
+     * a rank gathers the ids in its slice and writes zero rows for the rest, and the all_reduce
+     * below sums the ranks into x.
      *
-     * The name maps come first: they are how the checkpoint is asked what each weight is. */
+     * The name maps come first, since they are how the checkpoint is queried for each weight. */
     RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"),
                           nm.ckpt("model.language_model.embed_tokens.weight")));
     RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"),
@@ -930,8 +708,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                      RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
     m.w_out_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd},
                           RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
-    /* ROW-SHARDED with the vocabulary: g.n_vocab is THIS RANK'S share and rad_arch.h says what
-     * the split is and what it buys. The two change together. */
+    /* Row-sharded with the vocabulary: g.n_vocab is this rank's share (rad_arch.h). */
     m.w_lm_head = decl_w(b, nm.f("output.weight"),
                          weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16),
                          {g.n_vocab, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
@@ -942,15 +719,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                                    RAD_INT("vocab_offset", g.vocab_off)),
                         RAD_WEIGHTS(m.w_tok)),
                     {}, {m.b_x});
-    /* THE ENCODER'S ROWS, over the lookup and before its reduction -- which layer 0's norm folds
-     * in at two ranks, so there is no other place to put them (MediaRows says why). */
+    /* The encoder's rows overwrite the lookup before its reduction, which layer 0's norm folds
+     * in at two ranks, so this is the only place for them (see MediaRows). */
     m.media = VisionTower::present(meta) && ctx->max_enc_patches > 0;
     if (m.media) RAD_ARCH_TRY(m.mrows.declare(b, g.max_tok, g.n_embd, m.b_x));
-    /* EXACT, unconditionally, and not g.wire_exact. Every other all_reduce in this model sums
-     * partial products where a lossy wire trades a little error for bandwidth; this one sums
-     * DISJOINT rows -- each token's embedding comes from exactly one rank and every other rank
-     * contributes a zero -- so a lossy wire would be pure loss on a value that is already the
-     * answer. min_bytes is left at 0 for the same reason. */
+    /* Always exact, not g.wire_exact: this all_reduce sums disjoint rows (each token's embedding
+     * comes from one rank, the others contribute zero), so a lossy wire would only add error.
+     * min_bytes stays 0 for the same reason. */
     if (g.world > 1)
         m.op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
                                RAD_PARAMS(RAD_INT("world_size", g.world),
@@ -959,11 +734,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                                RAD_NOWEIGHTS),
                            {m.b_x}, {m.b_x});
     /* ---- the layers. */
-    /* The rope table's fill, declared before the layers that read it. If it does not resolve the
-     * buffer stays zero and every attention block falls back to its unfused norm + rope pair --
-     * which is why `aw.cos_sin` is cleared rather than left pointing at a plane nothing fills. Its
-     * band is the fused prologue's (qk_fuse_rows), so a step the prologue does not serve -- a
-     * prefill chunk, where the fill's grid is one block a TOKEN -- issues no fill either. */
+    /* The rope table's fill, declared before the layers that read it. If it does not resolve,
+     * `aw.cos_sin` is cleared and every attention block uses its unfused norm + rope pair. Its band
+     * is the fused prologue's (qk_fuse_rows), so a step the prologue does not serve (a prefill
+     * chunk, where the fill's grid is one block per token) issues no fill either. */
     m.op_rope_cs = rw(b, decl_rotary(b, g, "rope_table",
                          RAD_PARAMS(RAD_RANGE("M", 1, qk_fuse_rows(g)), RAD_INT("rot", m.n_rot),
                                     RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
@@ -992,60 +766,16 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     mw.x = m.b_x; mw.h = m.a_h; mw.gate_up = m.b_gate_up; mw.ffn = m.a_ffn;
 #endif
 
-    /* ---- WHERE THE RESIDUAL ADD HAPPENS, which is the one thing this chain has to agree on.
-     *
-     * Every block ends `x += h` and every block begins `norm(x)`, so the add can move to the front
-     * of the NEXT block's norm and stop being a launch of its own (rad_fp8.h, NormQuantFP8): ~128
-     * of them a step, each a full dispatch for 82 KiB of row. `fold` says a block adds its predecessor's
-     * delta; `add_out` says the block after it will not, so this one must.
-     *
-     * TWO THINGS READ `x` BETWEEN BLOCKS and each keeps the add at the end of its block:
-     *
-     *   - THE DRAFTER'S TAPS. `op_tap` copies the residual stream after a named layer, and what
-     *     DFlash2 conditions on has to be that layer's real output. So a tap layer's MLP keeps its
-     *     own add, and the block after it has nothing to fold.
-     *   - THE FINAL NORM, which is a plain `rmsnorm` and has no residual operand. The last layer
-     *     keeps its add.
-     *
-     * The MTP head below is left unfolded for the same reason in reverse: it is a second chain
-     * over a different residual buffer, it is not the shipped drafter, and two launches a step is
-     * not worth a second copy of this argument. */
-    auto is_tap = [&](int64_t l) {
-        for (int t = 0; t < m.n_taps; ++t)
-            if (m.tap_layer[t] == (int)l) return true;
-        return false;
-    };
-
+    /* ---- where the residual add happens (rad_fp8.h, layer_fold): each block folds its
+     * predecessor's delta into its own norm, saving ~128 dispatches per step. The MTP head stays
+     * unfolded: it is a separate chain over its own residual buffer and saves only two launches a
+     * step. */
     m.layers.resize((size_t)m.n_main);
     for (int64_t l = 0; l < m.n_main; ++l) {
         Layer& lay = m.layers[(size_t)l];
         lay.full = is_full_attention(l, interval) ? 1 : 0;
 
-        /* The mixer folds unless it is first in the chain or its predecessor's MLP kept its add. */
-        const bool mix_fold = l > 0 && !is_tap(l - 1);
-        /* ...and never adds itself, because the MLP beside it always folds. */
-        const bool mlp_fold = true;
-        const bool mix_add  = !mlp_fold;
-        const bool mlp_add  = is_tap(l) || l + 1 >= m.n_main;
-        /* ...AND THE COLLECTIVE MOVES WITH THE ADD, one boundary at a time. A block's all-reduce
-         * can become the next block's first pass exactly where that block folds -- the fold is
-         * what says the delta in `h` is still there and that this norm is its only reader -- so
-         * `ar_in` is the fold and `ar_out` is the successor's fold, which is the flag already
-         * computed as `!*_add`. Two ranks or nothing: at tp1 there is no collective to fold, and
-         * at four the kernel does not exist. See rad_fp8.h. */
-        const bool tp2      = g.world == 2;
-        /* ...AND LAYER 0 ABSORBS THE EMBEDDING'S. Its mixer does not FOLD -- there is no previous
-         * block and so no delta to add -- but the embedding table is vocab-sharded, so there IS a
-         * collective in front of it, and the fused norm takes one without the other. That is the
-         * only place `ar_in` and `fold` come apart, and it is why they are separate flags.
-         * rad_fp8.h::NormQuantFP8 declares the fused op without a residual. */
-        const int  mix_ar_in  = !tp2               ? kArNone
-                              : mix_fold           ? kArAny
-                              : (l == 0 && m.op_embed_ar) ? kArExact   /* the embedding; see rad_fp8.h */
-                                                   : kArNone;
-        const bool mix_ar_out = !mix_add && tp2;
-        const bool mlp_ar_in  = mlp_fold && tp2;
-        const bool mlp_ar_out = !mlp_add && tp2;
+        const LayerFold f = layer_fold(g, l, m.n_main, m.tap_layer, m.n_taps, m.op_embed_ar != 0);
 
         const char* pre = "model.language_model.layers";
         if (lay.full) {
@@ -1059,7 +789,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
             as.o      = nm.ckpt("%s.%lld.self_attn.o_proj.weight",    pre, (long long)l);
             RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_full));
             RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, m.kv_full, m.n_rot, aw, as,
-                                          mix_fold, mix_add, mix_ar_in, mix_ar_out));
+                                          f.mix_fold, false, f.mix_ar_in, f.mix_ar_out));
         } else {
             GdnFP8::Src gs{};
             gs.norm     = nm.ckpt("%s.%lld.input_layernorm.weight",           pre, (long long)l);
@@ -1075,7 +805,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
             RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_state));
             RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_conv));
             RAD_ARCH_TRY(lay.gdn.declare(b, nm, g, gc, (int)l, m.kv_state, m.kv_conv, gw, gs,
-                                         mix_fold, mix_add, mix_ar_in, mix_ar_out));
+                                         f.mix_fold, false, f.mix_ar_in, f.mix_ar_out));
         }
 
         Ffn::Src ms{};
@@ -1094,8 +824,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
         ms.up   = nm.ckpt("%s.%lld.mlp.up_proj.weight",              pre, (long long)l);
         ms.down = nm.ckpt("%s.%lld.mlp.down_proj.weight",            pre, (long long)l);
 #endif
-        RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, ms, mlp_fold, mlp_add,
-                                     mlp_ar_in, mlp_ar_out));
+        RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, ms, true, f.mlp_add,
+                                     f.mlp_ar_in, f.mlp_ar_out));
     }
 #if QWEN35_MOE
     /* Each routed layer predicts the next one's experts at its router input (MoeFP8::xp_next). */
@@ -1123,45 +853,40 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
 
     /* ---- the multi-token-prediction head (rad_block_mtp_fp8.h).
      *
-     * DECLARED ONLY WHEN THE DEPLOYMENT SPECULATES. It is half a gigabyte of weights that a
-     * non-speculative server would read off disk, place in VRAM and never issue, and `max_spec`
-     * is the engine already saying whether it intends to draft. rad-convert declares at a
-     * non-zero max_spec on purpose, because a CONTAINER should carry what the model can serve
-     * even when the run that made it would not have used it.
+     * Declared only when the deployment speculates, since its ~0.5 GB of weights would otherwise
+     * be loaded and never issued. rad-convert declares at a non-zero max_spec so the container
+     * carries everything the model can serve.
      *
-     * AND ONLY WHEN THERE IS NO DFLASH2 DRAFTER, which `n_taps` is the sign of. A container can
-     * carry both; a deployment drafts with one, and DFlash2 is the better one on this target --
-     * one forward a block against one chained forward a token. Declaring both would put half a
-     * gigabyte of MTP weights on the card for a head nothing ever issues. */
+     * Also only when there is no DFlash2 drafter (`n_taps` == 0): a deployment drafts with one,
+     * and DFlash2 (one forward per block rather than one per token) is the better one here. */
     if (nextn > 0 && g.max_spec > 0 && m.n_taps == 0) {
-        /* AT max_tok, NOT max_logit_rows. A draft round is one row a sequence, but the history
-         * pass that fills the head's own K and V is one row a TOKEN and runs over a whole prefill
-         * chunk. 26 MiB at a 512-token chunk, against the 477 MiB of head weights beside it. */
+        /* Sized at max_tok, not max_logit_rows: a draft round is one row per sequence, but the
+         * history pass that fills the head's own K and V is one row per token over a whole prefill
+         * chunk (26 MiB at a 512-token chunk, beside 477 MiB of head weights). */
         m.b_mtp_h = decl_b(b, nm.f("mtp_h"), g.act_dtype, {g.max_tok, g.n_embd});
         m.b_mtp_e = decl_b(b, nm.f("mtp_e"), g.act_dtype, {g.max_tok, g.n_embd});
         m.b_mtp_c = decl_b(b, nm.f("mtp_c"), g.act_dtype, {g.max_tok, 2 * g.n_embd});
         m.b_mtp_x = decl_b(b, nm.f("mtp_x"), g.act_dtype, {g.max_tok, g.n_embd});
 
-        /* The 2-bit draft head's working set, at max_logit_rows: only a DRAFT round reaches any of
-         * it, and a draft round is one row a sequence. `mtp_dsum` is the odd one -- it is
-         * quant_act_i8's group-major [n_embd/128][ceil(M/16)*16] plane, so its first dimension is
-         * the K group and not the token. */
+        /* The 2-bit draft head's working set, at max_logit_rows, since only a draft round (one row
+         * per sequence) uses it. `mtp_dsum` is quant_act_i8's group-major
+         * [n_embd/128][ceil(M/16)*16] plane, first dimension the K group, not the token. */
         if (mtp_draft_head_q2(b, nm.f("mtp.draft_head.weight"), nm.ckpt("lm_head.weight"))) {
             const int64_t dmpad = ((g.max_logit_rows + 15) / 16) * 16;
             m.b_mtp_dq   = decl_b(b, nm.f("mtp_dq"),   RAD_I8,   {g.max_logit_rows, g.n_embd});
             m.b_mtp_ds   = decl_b(b, nm.f("mtp_ds"),   RAD_F32,  {g.max_logit_rows, 1});
             m.b_mtp_dsum = decl_b(b, nm.f("mtp_dsum"), RAD_F32,  {g.n_embd / 128, dmpad});
             m.b_mtp_dlog = decl_b(b, nm.f("mtp_dlog"), g.act_dtype, {g.max_logit_rows, g.n_vocab_all});
-            /* NAMED, because the engine finds it by name: a draft round's proposal comes out of
-             * row_topk and never through the sampler's token buffer. */
+            /* A draft round's proposal comes out of row_topk here, never through the sampler's
+             * token buffer. */
             m.b_mtp_didx = decl_b(b, nm.f("mtp_didx"), RAD_I32,  {g.max_logit_rows, 1});
             m.b_mtp_dval = decl_b(b, nm.f("mtp_dval"), RAD_F32,  {g.max_logit_rows, 1});
         }
 
-        /* The layer's working set is the trunk's: `attn_qg`, `attn_k`, the ffn planes and `h` are
-         * all dead by the time a draft round runs, and a second set would be 150 MiB of transients
-         * for one layer. Only the residual stream is the head's own -- it must not be the trunk's
-         * `x`, which the next step's prefill still needs. */
+        /* The head reuses the trunk's working buffers (`attn_qg`, `attn_k`, the ffn planes, `h`),
+         * all dead by the time a draft round runs; a second set would be 150 MiB. Only the
+         * residual stream is its own, because the trunk's `x` is still needed by the next step's
+         * prefill. */
         AttnGatedFP8::Wire tw_attn = aw; tw_attn.x = m.b_mtp_x;
         Ffn::Wire          tw_mlp  = mw; tw_mlp.x  = m.b_mtp_x;
 
@@ -1186,10 +911,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
         ts.attn.o      = nm.ckpt("mtp.layers.0.self_attn.o_proj.weight");
         ts.mlp.norm    = nm.ckpt("mtp.layers.0.post_attention_layernorm.weight");
 #if QWEN35_MOE
-        /* THE HEAD'S FEED-FORWARD IS ROUTED TOO, and it has its own 256 experts -- `mtp.layers.0`
-         * carries `mlp.experts.*`, `mlp.gate` and a shared expert exactly as a trunk layer does.
-         * That is what MtpBlockFP8 is a template for; a head hard-wired to the dense block could
-         * not declare it, and the container would carry a drafter nothing could run. */
+        /* The head's feed-forward is routed too, with its own 256 experts: `mtp.layers.0` carries
+         * `mlp.experts.*`, `mlp.gate` and a shared expert like a trunk layer. That is why
+         * MtpBlockFP8 is a template over the feed-forward. */
         ts.mlp.cfg     = m.moecfg;
         ts.mlp.router  = nm.ckpt("mtp.layers.0.mlp.gate.weight");
         ts.mlp.experts = nm.ckpt("mtp.layers.0.mlp.experts");
@@ -1207,20 +931,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
         ts.lm          = nm.ckpt("lm_head.weight");
 
         /* Bound as one more layer of the trunk's full-attention group, at absolute index n_main,
-         * so a draft round writes its K and V at the slot the trunk's token for that position
-         * owns. rad_block_mtp_fp8.h argues the case; the short version is that it makes a rejected
-         * draft self-correcting instead of something to roll back. */
+         * so a draft round writes its K and V at the slot of the trunk's token for that position.
+         * A rejected draft is then overwritten rather than rolled back (rad_block_mtp_fp8.h). */
         RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)m.n_main, m.kv_full));
         m.mtp.media = m.media;
         RAD_ARCH_TRY(m.mtp.declare(b, nm, g, (int)m.n_main, m.kv_full, m.n_rot, m.w_tok,
                                    m.w_lm_head, final_wadd, tw, ts));
         m.have_mtp = true;
 
-        /* WHAT THE ENGINE DRIVES. Serial: `max_spec` dependent passes, each embedding what the
-         * last one proposed. `proposal` is the buffer a pass leaves its token in, and the two
-         * heads differ -- the 2-bit head takes its own argmax into `mtp_didx`, the bf16 head goes
-         * through the ordinary sampler chain and 0 says so. Declaring it is what keeps the engine
-         * from having to work it out from buffer names. */
+        /* Serial drafter: `max_spec` dependent passes, each embedding the last one's proposal.
+         * The 2-bit head writes its own argmax into `mtp_didx`; without it `mtp_didx` is 0 and the
+         * bf16 head goes through the ordinary sampler chain. */
         RadDrafterDecl dd{};
         dd.name           = "mtp";
         dd.kind           = RAD_DRAFT_SERIAL;
@@ -1232,16 +953,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     }
 
     /* ---- the DFlash2 drafter (rad_block_dflash2.h), at absolute layers n_main.. of its own KV
-     * group. Gated on the same two things the taps are: a drafter in the container, and a
-     * deployment that means to speculate. `n_taps` is already both -- it is non-zero only when
-     * `draft.architectures` named a DFlash model AND max_spec was positive. */
+     * group. `n_taps` is non-zero only when `draft.architectures` names a DFlash model and
+     * max_spec is positive. */
     if (m.n_taps > 0) {
         RAD_ARCH_TRY(declare_dflash2(b, meta, ctx, m, (int)m.n_main));
         if (nextn > 0)
-            rad_note(b, "the DFlash2 drafter DISPLACES the %lld-layer MTP head, which is not "
-                        "declared and whose weights this container therefore does not carry. One "
-                        "drafter a container: the two are 4.3 GB between them and a deployment "
-                        "drafts with one of them. Convert without --draft-model for the MTP one",
+            rad_note(b, "the DFlash2 drafter replaces the %lld-layer MTP head, which is not "
+                        "declared or carried; convert without --draft-model for the MTP head",
                      (long long)nextn);
     }
 
@@ -1252,48 +970,38 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
              (long long)g.n_head, (long long)g.n_head_kv, (long long)g.head_dim,
              (long long)g.n_ff, (long long)g.vocab_off, (long long)(g.vocab_off + g.n_vocab));
     rad_note(b, "weights are block-scaled fp8: E4M3 [N,K] with a bf16 [N/%d,K/%d] scale plane, "
-                "one stored weight taken by gemm_nt_q at dtype fp8a8 as two operands -- no "
-                "repacking and no dequantisation, so the model costs what the checkpoint does",
+                "read by gemm_nt_q at fp8a8 as stored",
              RAD_FP8_BLOCK, RAD_FP8_BLOCK);
-    rad_note(b, "activations are quantised to E4M3 every step (activation_scheme: dynamic): one "
-                "quant_act_fp8 per activation that feeds a GEMM, not per GEMM -- the three "
-                "attention projections share one, and so do the delta net's qkv and z");
-    rad_note(b, "NOT fp8 in the checkpoint: every norm, A_log, dt_bias, conv1d, the embedding, the "
-                "lm_head (unless a recipe made it so), and the delta net's in_proj_a / in_proj_b "
-                "-- 48 columns each, which is not a whole %d-row scale block, so the checkpoint "
-                "left them bf16 and this plugin runs them as a separate bf16 gemm_nt instead of "
-                "fusing them into the qkv row", RAD_FP8_BLOCK);
+    rad_note(b, "activations are quantised to E4M3 every step (activation_scheme: dynamic), once "
+                "per activation: the attention projections share one, as do the delta net's qkv "
+                "and z");
+    rad_note(b, "bf16 in the checkpoint: every norm, A_log, dt_bias, conv1d, the embedding, the "
+                "lm_head (unless a recipe quantised it) and the delta net's in_proj_a / in_proj_b, "
+                "whose 48 rows are not a whole %d-row scale block and run as a separate gemm_nt",
+             RAD_FP8_BLOCK);
     rad_note(b, "gdn: %lld key heads x %lld, %lld value heads x %lld, conv width %lld, chunk %lld; "
                 "conv row %lld channels, a|b row %lld",
              (long long)gc.n_head_k, (long long)gc.head_k, (long long)gc.n_head_v,
              (long long)gc.head_v, (long long)gc.conv_width, (long long)gc.chunk,
              (long long)conv_dim, (long long)gc.ab_dim());
-    rad_note(b, "ssm_a_log carries A_log AS A LOG: the kernels form -exp(A_log)*softplus(a+dt). "
-                "A container built from a GGUF has ssm_a = -exp(A_log) already applied and must "
-                "undo it, or every head's decay collapses");
-    rad_note(b, "rope is mrope over %lld of %lld head dims, sections [11,11,10]; RadBatch carries "
-                "one position component per token, so the three sections see the same position -- "
-                "exact for text, wrong for an image span",
-             (long long)m.n_rot, (long long)g.head_dim);
+    rad_note(b, "ssm_a_log holds A_log itself: the kernels form -exp(A_log) * softplus(a + dt), "
+                "so a GGUF's ssm_a = -exp(A_log) must be converted back");
+    rad_note(b, "rope: %s over %lld of %lld head dims%s%s", g.rope_mode, (long long)m.n_rot,
+             (long long)g.head_dim, g.rope_mc ? ", sections " : "", g.rope_sections);
     if (!have_interval)
         rad_note(b, "the container did not state full_attention_interval; assuming %lld, which "
                     "makes layers 3,7,... full attention", (long long)interval);
     if (m.have_mtp)
-        rad_note(b, "the MTP head is declared: %lld NextN layer(s) exist under an `mtp.` prefix of "
-                    "their own and the FIRST is served, as absolute layer %lld of the "
-                    "full-attention KV group. It drafts; the trunk verifies. mtp.fc reads the "
-                    "normed embedding then the normed hidden state",
+        rad_note(b, "MTP head: the first of %lld NextN layer(s) under `mtp.`, as absolute layer "
+                    "%lld of the full-attention KV group",
                  (long long)nextn, (long long)m.n_main);
     else if (nextn > 0)
-        rad_note(b, "%lld MTP/NextN layer(s) sit BESIDE the %lld trunk layers -- under an `mtp.` "
-                    "prefix of their own, not as layers %lld.. -- and are NOT declared, because "
-                    "this deployment asked for no speculative window (max_spec 0). Half a "
-                    "gigabyte of weights stays off the card",
-                 (long long)nextn, (long long)m.n_main, (long long)m.n_main);
+        rad_note(b, "the %lld MTP/NextN layer(s) under `mtp.` are not loaded: this deployment "
+                    "does not speculate", (long long)nextn);
 
-    /* THE VISION TOWER, LAST: an encoder pass issues nothing else, so its activations share the
-     * arena with every buffer declared above. Its weight groups start past every text layer, the
-     * MTP head and a drafter's. */
+    /* The vision tower, last: an encoder pass issues nothing else, so its activations share the
+     * arena with every buffer above. Its weight groups start past every text layer, the MTP head
+     * and a drafter's. */
     if (m.media) RAD_ARCH_TRY(m.vit.declare(b, meta, ctx, nm, g.n_embd, (int)g.n_layer + 64));
     return RAD_OK;
 }
@@ -1301,39 +1009,26 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
 static void step(RadCtx* c, const RadBatch* batch) {
     Model& m = g_model[rad_rank(c)];
 
-    /* AN ENCODER PASS RUNS THE VISION TOWER AND NOTHING ELSE (RadBatch::enc). */
+    /* An encoder pass runs only the vision tower (RadBatch::enc). */
     if (batch->enc) {
         m.vit.step(c, batch);
         return;
     }
 
-    /* AN MTP PASS runs the head and NOTHING ELSE. The trunk already ran this step and left its
-     * hidden states in `h`; the head reads the rows it wants out of them and turns them into
-     * either a draft token or one more position of its own attention history. Which of the two
-     * is the SIGN of `draft_pass`, and rad_block_mtp_fp8.h says why there are two.
-     *
-     * Zero is a trunk step, so a zeroed RadBatch runs the model -- the same convention, and for
-     * the same reason, as `num_accepted` (docs/OPS.md). */
+    /* A drafter pass runs only the drafter. For MTP, the trunk already left its hidden states in
+     * `h`; the head turns the rows it wants into a draft token or one more position of its own
+     * attention history, by the sign of `draft_pass` (rad_block_mtp_fp8.h). Zero is a trunk step. */
     if (batch->draft_pass != 0) {
-        /* THE DRAFTER'S OWN cos/sin ROWS FIRST, AND THE TRUNK DID NOT WRITE THEM. `rope_table`
-         * fills the rows THIS STEP'S POSITIONS name, and a drafter pass runs PAST the committed
-         * end -- the MTP head's round k is at position head_i + k - 1, which the trunk step
-         * before it never reached. Without this the head rotates by whatever the plane held at a
-         * row nothing had written, which costs only ACCEPTANCE (a mis-rotated draft is rejected
-         * and the text is still the trunk's) and therefore has no symptom at all.
-         *
-         * A row is a function of its POSITION ALONE, so re-filling is idempotent and can never
-         * write a row a later reader disagrees with. qwen4exp_fp8.cpp carries the same call for
-         * the same reason and says more about it. */
+        /* Fill the drafter's own cos/sin rows first. A drafter pass runs past the committed end
+         * (the MTP head's round k is at position head_i + k - 1), at rows the trunk step never
+         * wrote; a stale row would silently cost acceptance only. A row depends only on its
+         * position, so re-filling is idempotent. */
         if (m.op_rope_cs && batch->n_tok <= qk_fuse_rows(m.g) && !rope_mixed(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 FIELD MEANS "A DRAFTER PASS, AND THE SIGN SAYS WHICH KIND", and both drafters read
-         * it that way even though only the MTP head has rounds. For DFlash2 the two kinds are the
-         * two passes: positive is the QUERY pass, which proposes the whole block in one go, and
-         * negative is the CONTEXT pass, which turns the tokens the trunk just committed into the
-         * drafter's own K and V. There is no third kind and no round counter -- a block-diffusion
-         * drafter runs its layers once per step. */
+        /* For DFlash2, positive is the query pass, proposing the whole block at once, and
+         * negative the context pass, turning the tokens the trunk just committed into the
+         * drafter's own K and V. */
         if (m.have_df) {
             if (batch->draft_pass > 0) m.df.step(c, batch);
             else                      m.df.context(c, batch);
@@ -1342,8 +1037,7 @@ static void step(RadCtx* c, const RadBatch* batch) {
         if (!m.have_mtp) {
             rad_step_fail(c, "the batch asks for a drafter pass and no drafter is declared: the "
                              "container has neither an `mtp.` block nor a `draft.` one, or "
-                             "declare ran at max_spec 0, which is the engine saying it would not "
-                             "draft");
+                             "declare ran at max_spec 0");
             return;
         }
         m.mtp.step(c, batch);
@@ -1354,21 +1048,17 @@ static void step(RadCtx* c, const RadBatch* batch) {
               praw(batch->token_ids, RAD_I32, batch->n_tok), RAD_W(m.w_tok),
               brows(m.b_x, batch->n_tok));
     m.mrows.step(c, batch, m.b_x, batch->n_tok);
-    /* The vocab shard's reduction -- ONLY WHERE LAYER 0'S NORM WILL NOT DO IT, which is the same
-     * sentence every block in this model already carries about its own collective. At tp1 there
-     * is no op and the graph is what it always was; at tp2 the fused norm takes it and this is
-     * not issued at all, which for n_embd 5120 is every step. The standalone op stays DECLARED
-     * because ar_fused_ok is a question about T and a width, and a model whose n_embd the
-     * compressed wire cannot tile would fall back to it. */
+    /* The vocab shard's reduction, only where layer 0's norm does not fold it. At tp1 there is no
+     * op; at tp2 the fused norm normally takes it (every step for n_embd 5120). The standalone op
+     * stays declared because ar_fused_ok depends on T and the width, and an n_embd the compressed
+     * wire cannot tile falls back to it. */
     if (m.op_embed_ar && !ar_wire_is_exact(m.g, batch->n_tok))
         RAD_ISSUE_N(c, m.op_embed_ar, (int64_t)batch->n_tok * m.g.n_embd,
                     brows(m.b_x, batch->n_tok), RAD_NONE);
 
-    /* ONE FILL A STEP, HERE, because every attention layer below reads it and they all rotate at
-     * the same positions. Only the rows this step names are written -- and only on a step whose
-     * width the fusion actually serves, because the table has exactly one consumer and a prefill
-     * chunk takes the unfused pair. The band is asked of `qk_fuse_rows` rather than restated, so
-     * the fill and the op that reads it cannot disagree about which steps have a table. */
+    /* One rope-table fill per step for all attention layers, writing only this step's rows, and
+     * only when the fused prologue serves the step (a prefill chunk takes the unfused pair). The
+     * band comes from `qk_fuse_rows`, so the fill and its reader agree. */
     if (m.op_rope_cs && batch->n_tok <= qk_fuse_rows(m.g) && !rope_mixed(batch))
         RAD_ISSUE_N(c, m.op_rope_cs, batch->n_tok,
                     rope_pos1(batch, batch->n_tok), RAD_B(m.b_rope_cs));
@@ -1381,10 +1071,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
         l.mlp.step(c, batch);
         dbg_resid(c, (int)li, "ffn", m.g.n_embd, m.b_x, m.a_h.x);
 
-        /* THE TAP, AFTER the layer, because what a drafter conditions on is this layer's OUTPUT.
-         * The residual stream is one buffer the next layer overwrites, so the rows are copied into
-         * the column slice this tap owns while they are still here. Linear in the tap count and
-         * only over the layers named. */
+        /* The tap, after the layer: the drafter conditions on this layer's output, which the next
+         * layer overwrites, so the rows are copied into this tap's column slice now. */
         for (int t = 0; t < m.n_taps; ++t) {
             if (m.tap_layer[t] != (int)li) continue;
             RAD_ISSUE(c, m.op_tap, brows(m.b_x, batch->n_tok),
@@ -1406,28 +1094,19 @@ static void step(RadCtx* c, const RadBatch* batch) {
     }
 }
 
-
 /* ================================================================== the probe
  *
- * WHAT THIS CONTAINER'S DRAFTER IS WORTH SPECULATING TO, answered before anything is declared
- * because `max_spec` is an input to declaration -- it sizes the drafter's buffers, bands the
- * kernels and sets the scheduler's window. The core asks; it reads none of these keys itself.
+ * The speculation depth this container's drafter supports, answered before declare because
+ * `max_spec` sizes the drafter's buffers, bands kernels and sets the scheduler's window.
  *
- * THE DRAFT DEPTH IS A PROPERTY OF THE DRAFTER, not something an operator has to remember. The two
- * numbers below are far apart because the two drafters propose in different shapes.
+ * An MTP head is serial: depth d is d chained passes, so each extra token costs more as it gets
+ * less likely. On Qwen3.8-27B-FP8 at two ranks throughput is flat across depths 2-4 and falls
+ * after, so 3 is used.
  *
- * An MTP head is SERIAL: depth d is d chained forward passes, each one embedding the token the
- * last one proposed, so the marginal token gets more expensive exactly as it gets less likely. On
- * Qwen3.8-27B-FP8 at two ranks throughput is flat across depths 2, 3 and 4 and falls away after,
- * so 3 is the top of that plateau.
+ * DFlash2 proposes the whole block in one pass, so its depth is the block length it was trained
+ * at (block_size 8: one anchor and 7 mask positions), and any other depth is refused.
  *
- * DFlash2 is block-diffusion and proposes the WHOLE block in one pass, so its depth is not a
- * throughput trade at all: it is the block length the checkpoint was trained at, and asking for
- * anything else is a silently worse draft. This one ships trained at block_size 8, which is one
- * anchor and 7 mask positions.
- *
- * 0 when the container carries no drafter, which is the right answer to "speculate as deeply as
- * this model can" on a model that cannot. */
+ * 0 when the container carries no drafter. */
 static int probe(const RadModelMeta* meta, RadArchProbe* out) {
     if (!meta || !out) return RAD_E_INVAL;
     const char* da = rad_meta_gets(meta, "draft.architectures", "");
@@ -1445,20 +1124,19 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
 }  /* namespace QWEN35_NS */
 
 #ifndef RAD_ARCH_NO_EXPORTS
-/* ONE MORE LEVEL OF EXPANSION, and it is load-bearing. RAD_ARCH_PLUGIN stringifies its NS argument
- * to name the plugin, and `#` applies to the parameter as WRITTEN -- so passing QWEN35_NS directly
- * would register a plugin called "QWEN35_NS", which the registry would then refuse the second copy
- * of by name. An argument that is not stringified in the intermediate macro IS macro-expanded
- * before substitution, so these two forward the expanded namespace. */
+/* One more level of expansion is required. RAD_ARCH_PLUGIN stringifies its NS argument to name
+ * the plugin, and `#` applies to the parameter as written, so passing QWEN35_NS directly would
+ * register "QWEN35_NS" for both builds. An argument not stringified in the intermediate macro is
+ * expanded first, so these forward the expanded namespace. */
 #define QWEN35_PROBE_X(NS)              RAD_ARCH_PROBE(NS)
 #define QWEN35_PLUGIN_X(NS, ...)        RAD_ARCH_PLUGIN(NS, __VA_ARGS__)
 QWEN35_PROBE_X(QWEN35_NS)
 #if QWEN35_MOE
 QWEN35_PLUGIN_X(QWEN35_NS, QWEN35_ARCH_ID, "fp8_e4m3", "0.1.0",
                 "Qwen3.5 / 3.6 MoE (35B-A3B), block-scaled fp8 weights and fp8 activations: the "
-                "dense graph with a routed feed-forward -- 256 experts, 8 a token, a shared expert "
-                "beside them -- gated attention over paged KV every fourth layer and gated delta "
-                "net between")
+                "dense graph with a routed feed-forward (256 experts, 8 a token, and a shared "
+                "expert), gated attention over paged KV every fourth layer and gated delta net "
+                "between")
 #else
 QWEN35_PLUGIN_X(QWEN35_NS, QWEN35_ARCH_ID, "fp8_e4m3", "0.1.0",
                 "Qwen3.5 / 3.6 / 3.8 dense (0.8B..27B), block-scaled fp8 weights and fp8 "
diff --git a/arch/qwen35moe_fp8/CMakeLists.txt b/arch/qwen35moe_fp8/CMakeLists.txt
index 565c4d54..f7d0356e 100644
--- a/arch/qwen35moe_fp8/CMakeLists.txt
+++ b/arch/qwen35moe_fp8/CMakeLists.txt
@@ -1,6 +1,5 @@
-# A plugin like any other: built here inside radiance's tree, or on its own against an installed
-# radiance (`cmake -S arch/qwen35moe_fp8 -B build -DCMAKE_PREFIX_PATH=`) -- the same
-# rad_add_plugin either way (cmake/RadAddPlugin.cmake).
+# Built in radiance's tree, or standalone against an installed radiance
+# (`cmake -S arch/qwen35moe_fp8 -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake.
 if(NOT COMMAND rad_add_plugin)
   cmake_minimum_required(VERSION 3.21)
   project(qwen35moe_fp8 LANGUAGES CXX)
diff --git a/arch/qwen35moe_fp8/qwen35moe_fp8.cpp b/arch/qwen35moe_fp8/qwen35moe_fp8.cpp
index c15a20a1..787acd22 100644
--- a/arch/qwen35moe_fp8/qwen35moe_fp8.cpp
+++ b/arch/qwen35moe_fp8/qwen35moe_fp8.cpp
@@ -1,21 +1,14 @@
 /* qwen35moe_fp8 -- Qwen3.5 / 3.6 MoE (35B-A3B), block-scaled FP8 weights and FP8 activations.
  *
- * IT IS arch/qwen35_fp8/qwen35_fp8.cpp WITH THE FEED-FORWARD ROUTED, and that is the whole of this
- * file: three macros and an include. Everything above the FFN -- the gated attention, the gated
- * delta net, the layer schedule, the rope, the vocabulary edges, the MTP head, every switch and
- * every bisect -- is identical between the two members of this family, and reading the two
- * config.json files side by side that is not an approximation. The six places where a routed
- * feed-forward differs are behind `#if QWEN35_MOE` in that file, each with its own comment.
+ * This is arch/qwen35_fp8/qwen35_fp8.cpp with a routed feed-forward: three macros and an include.
+ * Everything above the FFN (gated attention, gated delta net, layer schedule, rope, vocabulary
+ * edges, MTP head) is identical between the dense and MoE configs. The places where a routed
+ * feed-forward differs are behind `#if QWEN35_MOE` in that file.
  *
- * WHY A SECOND TRANSLATION UNIT AT ALL, rather than one plugin that branches on `n_expert`: the
- * architecture id and the quantisation descriptor are the SELECTION KEY (spec §2.4). A container
- * converted from `model_type: qwen3_5_moe` reports `qwen35moe`, the dense one reports `qwen35`, and
- * the loader picks by that pair. One .so cannot claim both ids, and it should not: an operator
- * looking at what is installed should see two plugins for two architectures.
- *
- * The precedent is libr4d's attention dispatches -- one set of kernel templates, three translation
- * units instantiating them at three geometries. The alternative is a second 1300-line plugin kept
- * in step by hand.
+ * A second translation unit rather than a branch on `n_expert`, because the architecture id and
+ * quantisation descriptor are the selection key (spec §2.4): a container converted from
+ * `model_type: qwen3_5_moe` reports `qwen35moe`, the dense one `qwen35`, and one .so cannot claim
+ * both ids.
  */
 #define QWEN35_MOE     1
 #define QWEN35_NS      qwen35moe_fp8
diff --git a/arch/qwen3asr_bf16/CMakeLists.txt b/arch/qwen3asr_bf16/CMakeLists.txt
new file mode 100644
index 00000000..b673bed0
--- /dev/null
+++ b/arch/qwen3asr_bf16/CMakeLists.txt
@@ -0,0 +1,11 @@
+# A plugin like any other: built here inside radiance's tree, or on its own against an installed
+# radiance (`cmake -S arch/qwen3asr_bf16 -B build -DCMAKE_PREFIX_PATH=`) -- the
+# same rad_add_plugin either way (cmake/RadAddPlugin.cmake).
+if(NOT COMMAND rad_add_plugin)
+  cmake_minimum_required(VERSION 3.21)
+  project(qwen3asr_bf16 LANGUAGES CXX)
+  find_package(radiance REQUIRED)
+  rad_plugin_defaults()
+endif()
+
+rad_add_plugin(qwen3asr_bf16 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/qwen3asr_bf16.cpp)
diff --git a/arch/qwen3asr_bf16/qwen3asr_bf16.cpp b/arch/qwen3asr_bf16/qwen3asr_bf16.cpp
new file mode 100644
index 00000000..1930ed6f
--- /dev/null
+++ b/arch/qwen3asr_bf16/qwen3asr_bf16.cpp
@@ -0,0 +1,623 @@
+/* qwen3asr_bf16 -- Qwen3-ASR: a Whisper-style audio encoder over a dense Qwen3 decoder, bf16
+ * weights and bf16 activations.
+ *
+ * A speech recogniser served as the generative model it is: the clip goes through the audio
+ * encoder (RadEncoderDecl, RAD_MM_AUDIO), its rows replace the prompt's <|audio_pad|>
+ * placeholders, and the decoder writes the transcript, after "language " when the
+ * request forces a language and after naming it when it does not. POST /v1/audio/transcriptions
+ * builds the prompt from rad_arch_audio_format (below); /v1/chat/completions takes the clip as an
+ * input_audio part. The reference is transformers' modeling_qwen3_asr (5.18) with its
+ * Qwen3ASRFeatureExtractor, which core/mm reproduces (AudioFamily::Qwen3ASR).
+ *
+ * ============================== THE SHAPE, AT 1.7B ==============================
+ *
+ *   audio encoder: log-mel [frames, 128], convolved one second (100 frames) at a time: three
+ *     Conv2d 3x3 / stride 2 / pad 1 over [mel, time] with 480 channels and exact gelu, 128 mel ->
+ *     16 and 100 frames -> 13 rows; a row's 16 x 480 features through a 7680 -> 1024 linear (no
+ *     bias); sinusoidal positions 0..12 added to each second's rows; 24 pre-LayerNorm layers (eps
+ *     1e-5), d_model 1024, 16 heads of 64, biased q/k/v/o and FFN linears, FFN 4096 with exact
+ *     gelu, attention bidirectional in blocks of 104 rows (n_window_infer 800 frames = 8 s) from
+ *     the clip's start; a final LayerNorm.
+ *   projector: 1024 -> 1024, gelu, 1024 -> 2048.
+ *   decoder: Qwen3-1.7B: 28 layers, hidden 2048, 16 heads over 8 KV heads of 128 (GQA 2), per-head
+ *     q/k RMS norms, NeoX rope over the whole head at theta 1e6, SwiGLU 6144, RMS eps 1e-6,
+ *     vocab 151936, the lm_head tied to the embedding.
+ *
+ * ============================== WHAT IS EASY TO GET WRONG ==============================
+ *
+ * Each second is convolved on its own. The core lays a clip out so one convolution over it does
+ * that (core/mm/processor.h, AudioFamily::Qwen3ASR): a whole second is staged as 104 frames whose
+ * last four read as zero (RadBatch::enc_coord plane 1), and the last, shorter second as 8 x the
+ * rows the reference keeps of it. `conv2d`'s `valid` at strides 1, 2 and 4 keeps one second's
+ * convolution out of the next's, and every row the tower writes is a row the reference keeps, so
+ * nothing is compacted.
+ *
+ * The convolutions run over [mel, time], so PyTorch's kernel is [cout, cin, mel, time] with time
+ * last, where `conv2d` convolves (time, width); `t_last` reads the checkpoint as it is. The 7680 ->
+ * 1024 linear takes its input channel-major (c * 16 + f) where the convolution writes
+ * frequency-major (f * 480 + c); as a 1 x 16 convolution over the frequency axis, the checkpoint's
+ * [1024, 7680] is the kernel [1024, 480, 1, 16] in PyTorch's layout, and nothing is permuted.
+ *
+ * The 480-channel convolutions are GEMMs. Two of them and the 7680 -> 1024 linear are 95% of the
+ * tower's arithmetic outside its transformer (68 GMAC for 30 s), and a direct convolution re-reads
+ * the weights for every output. `conv2d_unfold` writes each output position's receptive field as
+ * a row, its columns in the weight's own order, so `gemm_nt_bias` against the checkpoint's kernel
+ * read as [cout, cin * 9] (a reshape, not a relayout) is the convolution, with the bias and the
+ * gelu in its epilogue. The first convolution has one input channel and nine taps, too narrow a K
+ * for a GEMM, so it stays a `conv2d`.
+ *
+ * Positions restart every 13 rows (`seg_sinusoid`, per clip), and attention runs in blocks of 104
+ * rows from the clip's start, the last one short (`attn_dense`'s `block`). A clip is one encoder
+ * segment, so the segment bounds (in frames, read at cu_div 8) are the clip's.
+ *
+ * The decoder's positions are the tokens' indices. The checkpoint's text_config is plain Qwen3
+ * (no mrope_section), and the reference's position ids count the placeholders like text.
+ */
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+
+namespace qwen3asr_bf16 {
+
+using namespace rad::arch;
+
+/* The longest clip one encoder pass carries, in seconds: the reference extractor's own chunk
+ * length (`chunk_length`), and the clip the transcription route cuts longer audio into. */
+constexpr int64_t kPassSeconds = 30;
+
+/* Rows a chunk of `frames` keeps: three convolutions of kernel 3, stride 2, padding 1. */
+static int64_t post_cnn(int64_t frames) {
+    for (int i = 0; i < 3; ++i) frames = frames > 0 ? (frames - 1) / 2 + 1 : 0;
+    return frames;
+}
+
+/* ============================== THE AUDIO ENCODER ============================== */
+struct AudioTower {
+    struct Layer {
+        rad_weight ln1w = 0, ln1b = 0, qkv_w = 0, qkv_b = 0, o_w = 0, o_b = 0;
+        rad_weight ln2w = 0, ln2b = 0, fc1_w = 0, fc1_b = 0, fc2_w = 0, fc2_b = 0;
+        rad_op op_ln1 = 0, op_qkv = 0, op_attn = 0, op_o = 0, op_ln2 = 0, op_fc1 = 0, op_fc2 = 0;
+    };
+    bool on = false;
+    int64_t P = 0, R = 0, H = 0, heads = 0, hd = 0, ffn = 0, C = 0, nmel = 0, f3 = 0, w3 = 0;
+    int64_t chunk_rows = 0, block = 0, n_embd = 0;
+    static constexpr int64_t kMerge = 8;   /* three stride-2 convolutions: 8 frames a row */
+    rad_weight w_c1 = 0, b_c1 = 0, w_c2 = 0, b_c2 = 0, w_c3 = 0, b_c3 = 0, w_co = 0;
+    rad_weight ln_w = 0, ln_b = 0, p1_w = 0, p1_b = 0, p2_w = 0, p2_b = 0;
+    rad_op op_c1 = 0, op_u2 = 0, op_c2 = 0, op_u3 = 0, op_c3 = 0, op_uo = 0, op_co = 0;
+    rad_op op_pos = 0, op_add_pos = 0;
+    rad_op op_ln = 0, op_p1 = 0, op_p2 = 0;
+    rad_buf b_s1 = 0, b_u = 0, b_s2 = 0, b_s3 = 0, b_uo = 0, b_x = 0, b_h = 0, b_pos = 0;
+    rad_buf b_qkv = 0, b_att = 0;
+    rad_buf b_f = 0, b_p1 = 0, b_out = 0;
+    std::vector L;
+
+    static bool present(const RadModelMeta* m) {
+        const char* t = rad_meta_gets(m, "audio_config.model_type", "");
+        return t && !std::strcmp(t, "qwen3_asr_encoder");
+    }
+    /* The frames a pass of kPassSeconds stages: whole seconds of merge x 13 rows each. */
+    static int64_t frames_for(const RadModelMeta* m) {
+        const int64_t nw = rad_meta_geti(m, "audio_config.n_window", 0);
+        if (nw <= 0) return 0;
+        return kPassSeconds * kMerge * post_cnn(2 * nw);
+    }
+
+    int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
+                int64_t model_embd, int first_group) {
+        on = false;
+        if (!present(m) || ctx->max_audio_frames <= 0) return RAD_OK;
+        auto gi = [&](const char* k, int64_t d) {
+            char key[96];
+            std::snprintf(key, sizeof key, "audio_config.%s", k);
+            return rad_meta_geti(m, key, d);
+        };
+        H     = gi("d_model", 0);
+        heads = gi("encoder_attention_heads", 0);
+        ffn   = gi("encoder_ffn_dim", 0);
+        C     = gi("downsample_hidden_size", 0);
+        nmel  = gi("num_mel_bins", 0);
+        const int64_t depth  = gi("encoder_layers", 0);
+        const int64_t nw     = gi("n_window", 0);
+        const int64_t nwi    = gi("n_window_infer", 0);
+        const int64_t out    = gi("output_dim", 0);
+        const int64_t kvh    = gi("num_key_value_heads", heads);
+        const char*   act    = rad_meta_gets(m, "audio_config.activation_function", "");
+        hd = heads > 0 ? H / heads : 0;
+        f3 = ((((nmel + 1) / 2) + 1) / 2 + 1) / 2;
+        chunk_rows = post_cnn(2 * nw);
+        block = nw > 0 && nwi % (2 * nw) == 0 ? chunk_rows * (nwi / (2 * nw)) : 0;
+        /* What this tower does not carry is refused by name: a scaled embedding, grouped heads,
+         * an activation other than exact gelu, a projector into some other width. */
+        if (H <= 0 || heads <= 0 || hd * heads != H || ffn <= 0 || C <= 0 || nmel <= 0 ||
+            depth <= 0 || nw <= 0 || block <= 0 || kvh != heads || out != model_embd ||
+            std::strcmp(act ? act : "", "gelu") ||
+            rad_meta_geti(m, "audio_config.scale_embedding", 0)) {
+            fprintf(stderr, "radiance: qwen3asr: the container's audio_config is not the encoder "
+                            "this plugin serves (d_model %lld, heads %lld, ffn %lld, channels %lld, "
+                            "mel %lld, layers %lld, n_window %lld/%lld, output %lld for a %lld-wide "
+                            "decoder, act %s)\n", (long long)H, (long long)heads, (long long)ffn,
+                    (long long)C, (long long)nmel, (long long)depth, (long long)nw,
+                    (long long)nwi, (long long)out, (long long)model_embd, act ? act : "");
+            return RAD_E_UNSUPPORTED;
+        }
+        n_embd = model_embd;
+        P = ctx->max_audio_frames;
+        if (P % kMerge) return RAD_E_SHAPE;
+        R = P / kMerge;
+        const int AC = RAD_ACCESS_PER_REQUEST, N = RAD_SHARD_NONE;
+        const char* T = "model.audio_tower";
+
+        auto w = [&](const char* dn, const char* src, std::initializer_list shp,
+                     RadWeightGroup g) -> rad_weight {
+            if (map_copy(b, dn, src) < 0) return 0;
+            return decl_w(b, dn, RAD_BF16, shp, AC, N, g);
+        };
+        /* q, k and v into one projection, weights and biases alike: one GEMM a layer, and the
+         * attention reads three column slices of its row. */
+        auto wcat = [&](const char* dn, std::initializer_list src,
+                        std::initializer_list shp, RadWeightGroup g) -> rad_weight {
+            if (map_concat(b, dn, src, 0) < 0) return 0;
+            return decl_w(b, dn, RAD_BF16, shp, AC, N, g);
+        };
+        w_c1 = w(nm.f("a.conv1.w"), nm.ckpt("%s.conv2d1.weight", T), {C, 1, 3, 3}, grp_model());
+        b_c1 = w(nm.f("a.conv1.b"), nm.ckpt("%s.conv2d1.bias", T),   {C}, grp_model());
+        /* The two 480-channel kernels as the [cout, cin * 9] matrices their GEMMs read: the
+         * checkpoint's [C, C, 3, 3], row-major, is that matrix. */
+        w_c2 = w(nm.f("a.conv2.w"), nm.ckpt("%s.conv2d2.weight", T), {C, C * 9}, grp_model());
+        b_c2 = w(nm.f("a.conv2.b"), nm.ckpt("%s.conv2d2.bias", T),   {C}, grp_model());
+        w_c3 = w(nm.f("a.conv3.w"), nm.ckpt("%s.conv2d3.weight", T), {C, C * 9}, grp_model());
+        b_c3 = w(nm.f("a.conv3.b"), nm.ckpt("%s.conv2d3.bias", T),   {C}, grp_model());
+        w_co = w(nm.f("a.conv_out.w"), nm.ckpt("%s.conv_out.weight", T), {H, C * f3}, grp_model());
+        ln_w = w(nm.f("a.ln_post.w"), nm.ckpt("%s.ln_post.weight", T), {H}, grp_model());
+        ln_b = w(nm.f("a.ln_post.b"), nm.ckpt("%s.ln_post.bias", T),   {H}, grp_model());
+        p1_w = w(nm.f("a.proj1.w"), nm.ckpt("model.multi_modal_projector.linear_1.weight"), {H, H}, grp_model());
+        p1_b = w(nm.f("a.proj1.b"), nm.ckpt("model.multi_modal_projector.linear_1.bias"),   {H}, grp_model());
+        p2_w = w(nm.f("a.proj2.w"), nm.ckpt("model.multi_modal_projector.linear_2.weight"), {n_embd, H}, grp_model());
+        p2_b = w(nm.f("a.proj2.b"), nm.ckpt("model.multi_modal_projector.linear_2.bias"),   {n_embd}, grp_model());
+        if (!w_c1 || !b_c1 || !w_c2 || !b_c2 || !w_c3 || !b_c3 || !w_co || !ln_w || !ln_b ||
+            !p1_w || !p1_b || !p2_w || !p2_b)
+            return RAD_E_INVAL;
+        L.assign((size_t)depth, Layer{});
+        for (int64_t i = 0; i < depth; ++i) {
+            Layer& l = L[(size_t)i];
+            const RadWeightGroup g = grp_layer(first_group + (int)i);
+            const int li = (int)i;
+            const char* S = "model.audio_tower.layers";
+            l.ln1w  = w(nm.f("a.blk.%d.ln1.w", li), nm.ckpt("%s.%d.self_attn_layer_norm.weight", S, li), {H}, g);
+            l.ln1b  = w(nm.f("a.blk.%d.ln1.b", li), nm.ckpt("%s.%d.self_attn_layer_norm.bias", S, li),   {H}, g);
+            l.qkv_w = wcat(nm.f("a.blk.%d.qkv.w", li),
+                           { nm.ckpt("%s.%d.self_attn.q_proj.weight", S, li),
+                             nm.ckpt("%s.%d.self_attn.k_proj.weight", S, li),
+                             nm.ckpt("%s.%d.self_attn.v_proj.weight", S, li) }, {3 * H, H}, g);
+            l.qkv_b = wcat(nm.f("a.blk.%d.qkv.b", li),
+                           { nm.ckpt("%s.%d.self_attn.q_proj.bias", S, li),
+                             nm.ckpt("%s.%d.self_attn.k_proj.bias", S, li),
+                             nm.ckpt("%s.%d.self_attn.v_proj.bias", S, li) }, {3 * H}, g);
+            l.o_w   = w(nm.f("a.blk.%d.o.w", li),   nm.ckpt("%s.%d.self_attn.out_proj.weight", S, li), {H, H}, g);
+            l.o_b   = w(nm.f("a.blk.%d.o.b", li),   nm.ckpt("%s.%d.self_attn.out_proj.bias", S, li),   {H}, g);
+            l.ln2w  = w(nm.f("a.blk.%d.ln2.w", li), nm.ckpt("%s.%d.final_layer_norm.weight", S, li),   {H}, g);
+            l.ln2b  = w(nm.f("a.blk.%d.ln2.b", li), nm.ckpt("%s.%d.final_layer_norm.bias", S, li),     {H}, g);
+            l.fc1_w = w(nm.f("a.blk.%d.fc1.w", li), nm.ckpt("%s.%d.fc1.weight", S, li), {ffn, H}, g);
+            l.fc1_b = w(nm.f("a.blk.%d.fc1.b", li), nm.ckpt("%s.%d.fc1.bias", S, li),   {ffn}, g);
+            l.fc2_w = w(nm.f("a.blk.%d.fc2.w", li), nm.ckpt("%s.%d.fc2.weight", S, li), {H, ffn}, g);
+            l.fc2_b = w(nm.f("a.blk.%d.fc2.b", li), nm.ckpt("%s.%d.fc2.bias", S, li),   {H}, g);
+            if (!l.ln1w || !l.ln1b || !l.qkv_w || !l.qkv_b || !l.o_w || !l.o_b || !l.ln2w ||
+                !l.ln2b || !l.fc1_w || !l.fc1_b || !l.fc2_w || !l.fc2_b)
+                return RAD_E_INVAL;
+        }
+
+        /* ---- activations: the convolutions' planes at their own widths, (time, mel, channel)
+         * with the channel innermost; the rest at R rows. */
+        /* The second and third convolutions' outputs are their GEMMs' [positions, C], which is the
+         * same bytes as [time rows, width * C]: the next unfold reads them that way. */
+        const int64_t w2 = (nmel + 1) / 2;
+        w3 = (w2 + 1) / 2;
+        b_s1  = decl_b(b, nm.f("a.s1"),  RAD_BF16, {P / 2, w2 * C});
+        b_u   = decl_b(b, nm.f("a.unfold"), RAD_BF16, {P / 4 * w3, 9 * C});
+        b_s2  = decl_b(b, nm.f("a.s2"),  RAD_BF16, {P / 4 * w3, C});
+        b_s3  = decl_b(b, nm.f("a.s3"),  RAD_BF16, {R * f3, C});
+        b_uo  = decl_b(b, nm.f("a.unfold_out"), RAD_BF16, {R, f3 * C});
+        b_x   = decl_b(b, nm.f("a.x"),   RAD_BF16, {R, H});
+        b_h   = decl_b(b, nm.f("a.h"),   RAD_BF16, {R, H});
+        b_pos = decl_b(b, nm.f("a.pos"), RAD_BF16, {R, H});
+        b_qkv = decl_b(b, nm.f("a.qkv"), RAD_BF16, {R, 3 * H});
+        b_att = decl_b(b, nm.f("a.att"), RAD_BF16, {R, H});
+        b_f   = decl_b(b, nm.f("a.f"),   RAD_BF16, {R, ffn});
+        b_p1  = decl_b(b, nm.f("a.p1"),  RAD_BF16, {R, H});
+        b_out = decl_b(b, nm.f("a.out"), RAD_BF16, {R, n_embd});
+
+        /* The first convolution has one input channel, so it is direct: nine taps are too narrow
+         * a K for a GEMM. */
+        auto conv1 = [&](rad_weight wt, rad_weight bias) {
+            return RAD_OP(b, "conv2d",
+                          RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("width", nmel),
+                                     RAD_INT("cin", 1), RAD_INT("cout", C), RAD_INT("kh", 3),
+                                     RAD_INT("kw", 3), RAD_INT("stride", 2), RAD_INT("pad", 1),
+                                     RAD_INT("cu_div", 1), RAD_INT("valid_stride", 1),
+                                     RAD_STR("dtype", "bf16"), RAD_INT("t_last", 1),
+                                     RAD_STR("act", "gelu")),
+                          RAD_WEIGHTS(wt, bias));
+        };
+        auto gemm_m = [&](int64_t rows, int64_t Nn, int64_t K, const char* act_, rad_weight wt,
+                          rad_weight bias) {
+            return RAD_OP(b, "gemm_nt_bias",
+                          RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", Nn), RAD_INT("K", K),
+                                     RAD_STR("dtype", "bf16"), RAD_STR("act", act_)),
+                          RAD_WEIGHTS(wt, bias));
+        };
+        auto gemm = [&](int64_t Nn, int64_t K, const char* act_, rad_weight wt, rad_weight bias) {
+            return gemm_m(R, Nn, K, act_, wt, bias);
+        };
+        auto unfold = [&](int64_t rows, int64_t width, int64_t kh, int64_t kw, int64_t stride,
+                          int64_t pad, int64_t cu_div, int tlast) {
+            return RAD_OP(b, "conv2d_unfold",
+                          RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("width", width),
+                                     RAD_INT("cin", C), RAD_INT("kh", kh), RAD_INT("kw", kw),
+                                     RAD_INT("stride", stride), RAD_INT("pad", pad),
+                                     RAD_INT("cu_div", cu_div), RAD_INT("valid_stride", cu_div),
+                                     RAD_INT("t_last", tlast), RAD_STR("dtype", "bf16")),
+                          RAD_NOWEIGHTS);
+        };
+        auto lnorm = [&](rad_weight wt, rad_weight bias) {
+            return RAD_OP(b, "layernorm",
+                          RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", H), RAD_F64("eps", 1e-5),
+                                     RAD_STR("dtype", "bf16")),
+                          RAD_WEIGHTS(wt, bias));
+        };
+
+        op_c1 = rw(b, conv1(w_c1, b_c1), {}, {b_s1});
+        op_u2 = rw(b, unfold(P / 2, w2, 3, 3, 2, 1, 2, 1), {b_s1}, {b_u});
+        op_c2 = rw(b, gemm_m(P / 4 * w3, C, 9 * C, "gelu", w_c2, b_c2), {b_u}, {b_s2});
+        op_u3 = rw(b, unfold(P / 4, w3, 3, 3, 2, 1, 4, 1), {b_s2}, {b_u});
+        op_c3 = rw(b, gemm_m(R * f3, C, 9 * C, "gelu", w_c3, b_c3), {b_u}, {b_s3});
+        /* The 7680 -> 1024 linear as a 1 x f3 convolution over the frequency axis, unfolded: its
+         * rows are (channel, frequency), the checkpoint's own [H, C * f3] column order. */
+        op_uo = rw(b, unfold(R, f3, 1, f3, 1, 0, kMerge, 0), {b_s3}, {b_uo});
+        op_co = rw(b, RAD_OP(b, "gemm_nt",
+                             RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("N", H),
+                                        RAD_INT("K", C * f3), RAD_STR("dtype", "bf16")),
+                             RAD_WEIGHTS(w_co)),
+                   {b_uo}, {b_x});
+        op_pos = rw(b, RAD_OP(b, "seg_sinusoid",
+                              RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", H),
+                                         RAD_INT("period", chunk_rows),
+                                         RAD_F64("max_timescale", 10000.0),
+                                         RAD_INT("cu_div", kMerge), RAD_STR("dtype", "bf16")),
+                              RAD_NOWEIGHTS),
+                    {}, {b_pos});
+        op_add_pos = rw(b, RAD_OP(b, "add",
+                                  RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", H),
+                                             RAD_STR("dtype", "bf16")),
+                                  RAD_NOWEIGHTS),
+                        {b_x, b_pos}, {b_x});
+        for (Layer& l : L) {
+            l.op_ln1 = rw(b, lnorm(l.ln1w, l.ln1b), {b_x}, {b_h});
+            l.op_qkv = rw(b, gemm(3 * H, H, "none", l.qkv_w, l.qkv_b), {b_h}, {b_qkv});
+            l.op_attn = rw(b, RAD_OP(b, "attn_dense",
+                                     RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("head_dim", hd),
+                                                RAD_INT("gqa", 1), RAD_INT("causal", 0),
+                                                RAD_STR("dtype", "bf16"),
+                                                RAD_F64("scale", 1.0 / std::sqrt((double)hd)),
+                                                RAD_INT("max_seqlen", R),
+                                                RAD_INT("cu_div", kMerge),
+                                                RAD_INT("block", block)),
+                                     RAD_NOWEIGHTS),
+                           {b_qkv}, {b_att});
+            /* The output projection and the second FFN linear add the residual in their epilogue,
+             * rounded after the biased product as the reference's two tensors are. */
+            l.op_o   = rw(b, gemm(H, H, "none", l.o_w, l.o_b), {b_att, b_x}, {b_x});
+            l.op_ln2 = rw(b, lnorm(l.ln2w, l.ln2b), {b_x}, {b_h});
+            l.op_fc1 = rw(b, gemm(ffn, H, "gelu", l.fc1_w, l.fc1_b), {b_h}, {b_f});
+            l.op_fc2 = rw(b, gemm(H, ffn, "none", l.fc2_w, l.fc2_b), {b_f, b_x}, {b_x});
+        }
+        op_ln = rw(b, lnorm(ln_w, ln_b), {b_x}, {b_h});
+        op_p1 = rw(b, gemm(H, H, "gelu", p1_w, p1_b), {b_h}, {b_p1});
+        op_p2 = rw(b, gemm(n_embd, H, "none", p2_w, p2_b), {b_p1}, {b_out});
+
+        if (!ctx->shape_probe) {
+            RadEncoderDecl e{};
+            e.name        = "audio";
+            e.modalities  = RAD_MM_AUDIO;
+            e.patch_dim   = nmel;
+            e.merge       = kMerge;
+            e.max_patches = P;
+            e.n_embd      = n_embd;
+            e.out         = b_out;
+            RAD_ARCH_TRY(rad_declare_encoder(b, &e));
+            rad_note(b, "audio encoder: 3 convolutions of %lld channels over %lld mel bins, %lld "
+                        "layers of %lld (%lld heads x %lld), ffn %lld, attention in blocks of %lld "
+                        "rows; %lld frames a pass (%lld s) -> %lld rows of %lld",
+                     (long long)C, (long long)nmel, (long long)depth, (long long)H,
+                     (long long)heads, (long long)hd, (long long)ffn, (long long)block,
+                     (long long)P, (long long)kPassSeconds, (long long)R, (long long)n_embd);
+        }
+        on = true;
+        return RAD_OK;
+    }
+
+    void step(RadCtx* c, const RadBatch* batch) const {
+        const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg;
+        if (!on || Pn <= 0 || Pn > P || Pn % kMerge || S <= 0) {
+            rad_step_fail(c, "an audio pass this program's audio encoder cannot serve: none "
+                             "declared, more frames than it was declared for, or not whole rows");
+            return;
+        }
+        const int64_t Rn = Pn / kMerge;
+        const RadOperand frames = praw2(batch->enc_pixels, RAD_BF16, Pn, nmel);
+        /* Plane 1: whether a frame takes part in the convolution (item.cpp). */
+        const RadOperand valid = praw(batch->enc_coord + Pn, RAD_I32, Pn);
+        const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1);
+
+        RAD_ISSUE_N(c, op_c1, Pn, frames, RAD_W(w_c1), cu, valid, brows(b_s1, Pn / 2),
+                    RAD_W(b_c1));
+        const int64_t n2 = Pn / 4 * w3, n3 = Rn * f3;
+        RAD_ISSUE_N(c, op_u2, Pn / 2, brows(b_s1, Pn / 2), cu, valid, brows(b_u, n2));
+        RAD_ISSUE_N(c, op_c2, n2, brows(b_u, n2), RAD_W(w_c2), RAD_W(b_c2), RAD_NONE,
+                    brows(b_s2, n2));
+        RAD_ISSUE_N(c, op_u3, Pn / 4, brows(b_s2, n2), cu, valid, brows(b_u, n3));
+        RAD_ISSUE_N(c, op_c3, n3, brows(b_u, n3), RAD_W(w_c3), RAD_W(b_c3), RAD_NONE,
+                    brows(b_s3, n3));
+        RAD_ISSUE_N(c, op_uo, Rn, brows(b_s3, n3), cu, RAD_NONE, brows(b_uo, Rn));
+        RAD_ISSUE_N(c, op_co, Rn, brows(b_uo, Rn), RAD_W(w_co), brows(b_x, Rn));
+        RAD_ISSUE_N(c, op_pos, Rn, cu, brows(b_pos, Rn));
+        RAD_ISSUE_N(c, op_add_pos, Rn, brows(b_x, Rn), brows(b_pos, Rn), brows(b_x, Rn));
+        for (const Layer& l : L) {
+            RAD_ISSUE_N(c, l.op_ln1, Rn, brows(b_x, Rn), RAD_W(l.ln1w), RAD_W(l.ln1b),
+                        brows(b_h, Rn));
+            RAD_ISSUE_N(c, l.op_qkv, Rn, brows(b_h, Rn), RAD_W(l.qkv_w), RAD_W(l.qkv_b), RAD_NONE,
+                        brows(b_qkv, Rn));
+            RAD_ISSUE_N(c, l.op_attn, Rn, bcol(b_qkv, 0, H, Rn), bcol(b_qkv, H, H, Rn),
+                        bcol(b_qkv, 2 * H, H, Rn), cu, brows(b_att, Rn));
+            RAD_ISSUE_N(c, l.op_o, Rn, brows(b_att, Rn), RAD_W(l.o_w), RAD_W(l.o_b),
+                        brows(b_x, Rn), brows(b_x, Rn));
+            RAD_ISSUE_N(c, l.op_ln2, Rn, brows(b_x, Rn), RAD_W(l.ln2w), RAD_W(l.ln2b),
+                        brows(b_h, Rn));
+            RAD_ISSUE_N(c, l.op_fc1, Rn, brows(b_h, Rn), RAD_W(l.fc1_w), RAD_W(l.fc1_b), RAD_NONE,
+                        brows(b_f, Rn));
+            RAD_ISSUE_N(c, l.op_fc2, Rn, brows(b_f, Rn), RAD_W(l.fc2_w), RAD_W(l.fc2_b),
+                        brows(b_x, Rn), brows(b_x, Rn));
+        }
+        RAD_ISSUE_N(c, op_ln, Rn, brows(b_x, Rn), RAD_W(ln_w), RAD_W(ln_b), brows(b_h, Rn));
+        RAD_ISSUE_N(c, op_p1, Rn, brows(b_h, Rn), RAD_W(p1_w), RAD_W(p1_b), RAD_NONE,
+                    brows(b_p1, Rn));
+        RAD_ISSUE_N(c, op_p2, Rn, brows(b_p1, Rn), RAD_W(p2_w), RAD_W(p2_b), RAD_NONE,
+                    brows(b_out, Rn));
+    }
+};
+
+/* ============================== THE DECODER ============================== */
+struct Layer {
+    AttnBF16 attn;
+    MlpBF16  mlp;
+};
+
+struct Model {
+    Names nm{""};
+    Geom  g{};
+    rad_kvgroup kv = 0;
+    rad_buf b_x = 0, b_h = 0, b_q = 0, b_k = 0, b_v = 0, b_attn = 0;
+    rad_buf b_gate_up = 0, b_ffn = 0, b_hout = 0, b_logits = 0;
+    rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0;
+    rad_op op_embed = 0, op_embed_ar = 0, op_final_norm = 0, op_gather = 0, op_logits = 0;
+    bool media = false;
+    MediaRows mrows{};
+    AudioTower aud{};
+    std::vector layers;
+};
+
+static Model g_model[MAX_RANKS];
+
+static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
+    if (!b || !meta || !ctx) return RAD_E_INVAL;
+    if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
+    Model& m = g_model[ctx->rank];
+    m = Model{};
+    m.nm = Names(ctx->scope);
+    RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
+    Geom& g = m.g;
+    Names& nm = m.nm;
+
+    /* Plain Qwen3: every layer full attention, no sliding window, plain RMS gains. */
+    if (meta->n_expert > 0 || rad_meta_geti(meta, "text_config.use_sliding_window", 0)) {
+        fprintf(stderr, "radiance: qwen3asr: the decoder has experts or a sliding window; this "
+                        "plugin serves the dense, full-attention Qwen3 decoder\n");
+        return RAD_E_UNSUPPORTED;
+    }
+    if (!(g.theta > 0.0f)) g.theta = (float)rad_meta_getf(meta, "rope_parameters.rope_theta", 0.0);
+    if (!(g.theta > 0.0f) || g.head_dim <= 0 || g.n_head % g.n_head_kv) {
+        fprintf(stderr, "radiance: qwen3asr: the decoder's geometry is incomplete (theta %g, "
+                        "head_dim %lld, heads %lld over %lld)\n", (double)g.theta,
+                (long long)g.head_dim, (long long)g.n_head, (long long)g.n_head_kv);
+        return RAD_E_INVAL;
+    }
+    g.wadd = 0.0f;
+    g.wadd_qk = 0.0f;
+
+    RadKVGroupDecl fd{};
+    fd.kind      = RAD_KV_FULL;
+    fd.dtype     = rad_kv_cache_dtype(ctx, RAD_BF16);
+    fd.n_head_kv = g.n_head_kv;
+    fd.head_dim  = g.head_dim;
+    m.kv = rad_decl_kv_group(b, nm.f("kv_attn"), &fd);
+    g.kv_dtype = rad_dtype_name(fd.dtype);
+
+    m.b_x       = decl_b(b, nm.f("x"),        g.act_dtype, {g.max_tok, g.n_embd});
+    m.b_h       = decl_b(b, nm.f("h"),        g.act_dtype, {g.max_tok, g.n_embd});
+    m.b_q       = decl_b(b, nm.f("attn_q"),   g.act_dtype, {g.max_tok, g.q_dim()});
+    m.b_k       = decl_b(b, nm.f("attn_k"),   g.act_dtype, {g.max_tok, g.kv_dim()});
+    m.b_v       = decl_b(b, nm.f("attn_v"),   g.act_dtype, {g.max_tok, g.kv_dim()});
+    m.b_attn    = decl_b(b, nm.f("attn_out"), g.act_dtype, {g.max_tok, g.q_dim()});
+    m.b_gate_up = decl_b(b, nm.f("gate_up"),  g.act_dtype, {g.max_tok, 2 * g.n_ff});
+    m.b_ffn     = decl_b(b, nm.f("ffn"),      g.act_dtype, {g.max_tok, g.n_ff});
+    m.b_hout    = decl_b(b, nm.f("h_out"),    g.act_dtype, {g.max_logit_rows, g.n_embd});
+    m.b_logits  = decl_b(b, nm.f("logits"),   RAD_F32,     {g.max_logit_rows, g.n_vocab});
+    RAD_ARCH_TRY(rad_declare_logits(b, m.b_logits));
+
+    /* ---- the vocabulary edges, both row-sharded; the head is tied to the embedding
+     * (tie_word_embeddings, and the checkpoint ships no lm_head.weight). */
+    const char* pre = "model.language_model";
+    RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("%s.embed_tokens.weight", pre)));
+    RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("%s.norm.weight", pre)));
+    RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
+                              nm.ckpt("%s.embed_tokens.weight", pre)));
+    m.w_tok = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, g.n_embd},
+                     RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
+    m.w_out_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd},
+                          RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
+    m.w_lm_head = decl_w(b, nm.f("output.weight"),
+                         weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16),
+                         {g.n_vocab, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
+
+    m.op_embed = rw(b, RAD_OP(b, "embed_lookup",
+                        RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd),
+                                   RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
+                                   RAD_INT("vocab_offset", g.vocab_off)),
+                        RAD_WEIGHTS(m.w_tok)),
+                    {}, {m.b_x});
+    /* The encoder's rows, over the lookup and before its reduction (MediaRows says why). */
+    m.media = AudioTower::present(meta) && ctx->max_audio_frames > 0;
+    if (m.media) RAD_ARCH_TRY(m.mrows.declare(b, g.max_tok, g.n_embd, m.b_x));
+    if (g.world > 1)
+        m.op_embed_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),
+                                             RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
+                                  RAD_NOWEIGHTS),
+                              {m.b_x}, {m.b_x});
+
+    AttnBF16::Wire aw{};
+    aw.x = m.b_x; aw.h = m.b_h; aw.q = m.b_q; aw.k = m.b_k; aw.v = m.b_v; aw.attn = m.b_attn;
+    MlpBF16::Wire mw{};
+    mw.x = m.b_x; mw.h = m.b_h; mw.gate_up = m.b_gate_up; mw.ffn = m.b_ffn;
+    m.layers.resize((size_t)g.n_layer);
+    for (int64_t l = 0; l < g.n_layer; ++l) {
+        Layer& lay = m.layers[(size_t)l];
+        const char* lp = "model.language_model.layers";
+        const long long li = (long long)l;
+        AttnBF16::Src as{};
+        as.norm   = nm.ckpt("%s.%lld.input_layernorm.weight",  lp, li);
+        as.q      = nm.ckpt("%s.%lld.self_attn.q_proj.weight", lp, li);
+        as.k      = nm.ckpt("%s.%lld.self_attn.k_proj.weight", lp, li);
+        as.v      = nm.ckpt("%s.%lld.self_attn.v_proj.weight", lp, li);
+        as.q_norm = nm.ckpt("%s.%lld.self_attn.q_norm.weight", lp, li);
+        as.k_norm = nm.ckpt("%s.%lld.self_attn.k_norm.weight", lp, li);
+        as.o      = nm.ckpt("%s.%lld.self_attn.o_proj.weight", lp, li);
+        RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv));
+        RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, m.kv, aw, as));
+        MlpBF16::Src ms{};
+        ms.norm = nm.ckpt("%s.%lld.post_attention_layernorm.weight", lp, li);
+        ms.gate = nm.ckpt("%s.%lld.mlp.gate_proj.weight",            lp, li);
+        ms.up   = nm.ckpt("%s.%lld.mlp.up_proj.weight",              lp, li);
+        ms.down = nm.ckpt("%s.%lld.mlp.down_proj.weight",            lp, li);
+        RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, ms));
+    }
+
+    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", 0.0),
+                                        RAD_STR("dtype", g.dtype)),
+                             RAD_WEIGHTS(m.w_out_norm)),
+                         {m.b_x}, {m.b_h});
+    m.op_gather = rw(b, RAD_OP(b, "gather_rows",
+                         RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
+                                    RAD_INT("n", g.n_embd), RAD_STR("dtype", g.dtype)),
+                         RAD_NOWEIGHTS),
+                     {m.b_h}, {m.b_hout});
+    m.op_logits = rw(b, RAD_OP(b, "logits_gemm",
+                         RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
+                                    RAD_INT("n_vocab", g.n_vocab),
+                                    RAD_INT("n_embd", g.n_embd), RAD_STR("dtype", g.dtype)),
+                         RAD_WEIGHTS(m.w_lm_head)),
+                     {m.b_hout}, {m.b_logits});
+
+    rad_note(b, "rank %d/%d: %lld decoder layers, n_head=%lld n_head_kv=%lld head_dim=%lld "
+                "n_ff=%lld theta=%g vocab=[%lld,%lld), lm_head tied",
+             g.rank, g.world, (long long)g.n_layer, (long long)g.n_head, (long long)g.n_head_kv,
+             (long long)g.head_dim, (long long)g.n_ff, (double)g.theta, (long long)g.vocab_off,
+             (long long)(g.vocab_off + g.n_vocab));
+
+    /* The audio tower last, so its activations share the arena with every buffer above. */
+    if (m.media) RAD_ARCH_TRY(m.aud.declare(b, meta, ctx, nm, g.n_embd, (int)g.n_layer + 64));
+    return RAD_OK;
+}
+
+static void step(RadCtx* c, const RadBatch* batch) {
+    Model& m = g_model[rad_rank(c)];
+    /* An encoder pass runs the audio tower and nothing else (RadBatch::enc). */
+    if (batch->enc) {
+        m.aud.step(c, batch);
+        return;
+    }
+    const int64_t T = batch->n_tok;
+    RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_x, T));
+    m.mrows.step(c, batch, m.b_x, T);
+    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);
+    for (const Layer& l : m.layers) {
+        l.attn.step(c, batch);
+        l.mlp.step(c, batch);
+    }
+    RAD_ISSUE(c, m.op_final_norm, brows(m.b_x, T), RAD_W(m.w_out_norm), brows(m.b_h, T));
+    if (batch->n_out > 0) {
+        RAD_ISSUE_N(c, m.op_gather, batch->n_out, brows(m.b_h, T),
+                    praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.b_hout, batch->n_out));
+        RAD_ISSUE_N(c, m.op_logits, batch->n_out, brows(m.b_hout, batch->n_out),
+                    RAD_W(m.w_lm_head), brows(m.b_logits, batch->n_out));
+    }
+}
+
+/* Before declare: the frames a pass carries, so the core sizes the audio encoder's pass. */
+static int probe(const RadModelMeta* meta, RadArchProbe* out) {
+    if (!meta || !out) return RAD_E_INVAL;
+    if (AudioTower::present(meta)) out->audio_frames = AudioTower::frames_for(meta);
+    return RAD_OK;
+}
+
+/* Qwen3-ASR's audio format (RadAudioFormat): its clip markers; its transcription turn, which is
+ * the reference processor's chat template with the request's prompt as the system text and the
+ * clip as the user turn; and the forced-language prefix the model was trained with,
+ * "language ". The language names are the reference processor's
+ * LANGUAGE_CODE_TO_NAME. */
+static const char* const kLanguages[] = {
+    "ar", "Arabic",     "yue", "Cantonese",  "zh", "Chinese",   "cs", "Czech",
+    "da", "Danish",     "nl", "Dutch",       "en", "English",   "fil", "Filipino",
+    "fi", "Finnish",    "fr", "French",      "de", "German",    "el", "Greek",
+    "hi", "Hindi",      "hu", "Hungarian",   "id", "Indonesian", "it", "Italian",
+    "ja", "Japanese",   "ko", "Korean",      "mk", "Macedonian", "ms", "Malay",
+    "fa", "Persian",    "pl", "Polish",      "pt", "Portuguese", "ro", "Romanian",
+    "ru", "Russian",    "es", "Spanish",     "sv", "Swedish",   "th", "Thai",
+    "tr", "Turkish",    "vi", "Vietnamese",
+};
+
+static const RadAudioFormat* audio_format(const RadModelMeta* meta) {
+    if (!AudioTower::present(meta)) return nullptr;
+    static const RadAudioFormat f = {
+        (uint32_t)sizeof(RadAudioFormat),
+        "<|audio_start|>",
+        "<|audio_end|>",
+        "<|im_start|>system\n{context}<|im_end|>\n<|im_start|>user\n{audio}<|im_end|>\n"
+        "<|im_start|>assistant\n{language}",
+        "language {language}",
+        "",
+        "language ",
+        kLanguages,
+        (uint32_t)(sizeof(kLanguages) / sizeof(kLanguages[0]) / 2),
+    };
+    return &f;
+}
+
+}  /* namespace qwen3asr_bf16 */
+
+#ifndef RAD_ARCH_NO_EXPORTS
+RAD_ARCH_PLUGIN(qwen3asr_bf16, "qwen3asr", "", "0.1.0",
+                "Qwen3-ASR: a Whisper-style audio encoder over a dense Qwen3 decoder; bf16 weights "
+                "and activations")
+RAD_ARCH_PROBE(qwen3asr_bf16)
+RAD_ARCH_AUDIO_FORMAT(qwen3asr_bf16)
+#endif
diff --git a/arch/qwen4exp_fp8/CMakeLists.txt b/arch/qwen4exp_fp8/CMakeLists.txt
index 20e15414..e389f5de 100644
--- a/arch/qwen4exp_fp8/CMakeLists.txt
+++ b/arch/qwen4exp_fp8/CMakeLists.txt
@@ -1,6 +1,5 @@
-# A plugin like any other: built here inside radiance's tree, or on its own against an installed
-# radiance (`cmake -S arch/qwen4exp_fp8 -B build -DCMAKE_PREFIX_PATH=`) -- the same
-# rad_add_plugin either way (cmake/RadAddPlugin.cmake).
+# Built in radiance's tree, or standalone against an installed radiance
+# (`cmake -S arch/qwen4exp_fp8 -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake.
 if(NOT COMMAND rad_add_plugin)
   cmake_minimum_required(VERSION 3.21)
   project(qwen4exp_fp8 LANGUAGES CXX)
diff --git a/arch/qwen4exp_fp8/qwen4exp_fp8.cpp b/arch/qwen4exp_fp8/qwen4exp_fp8.cpp
index 16de4373..97f6ed5e 100644
--- a/arch/qwen4exp_fp8/qwen4exp_fp8.cpp
+++ b/arch/qwen4exp_fp8/qwen4exp_fp8.cpp
@@ -1,25 +1,23 @@
-/* qwen4exp_fp8 -- Qwen4-Exp (`model_type: qwen4_exp`), the architecture Qwen3.8-Flash-Next ships
- * and the one Qwen says Qwen4 will be built on. DENSE bf16 checkpoint, quantised by a recipe ahead
- * of time (data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe is the served one): int8 or fp8 trunk
- * linears with activations of the same kind, four-bit routed experts, or bf16 throughout.
+/* qwen4exp_fp8 -- Qwen4-Exp (`model_type: qwen4_exp`), the architecture of Qwen3.8-Flash-Next.
+ * The checkpoint is dense bf16, quantised ahead of time by a recipe
+ * (data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe is the served one): int8 or fp8 trunk linears with
+ * matching activations, four-bit routed experts, or bf16 throughout.
  *
- * ============================== WHAT IT IS, RELATIVE TO WHAT ALREADY RUNS ==============================
+ * ============================== RELATION TO QWEN3.5 MOE ==============================
  *
- * In transformers it is `Qwen4ExpTextModel`, a subclass of `Qwen3_5MoeTextModel` -- and this tree
- * already serves that (arch/qwen35moe_fp8, Qwen3.6-35B-A3B-FP8). So most of this file is
- * composition over the same blocks, and what is genuinely new is small and named:
+ * In transformers it is `Qwen4ExpTextModel`, a subclass of `Qwen3_5MoeTextModel`, which this tree
+ * already serves (arch/qwen35moe_fp8). Most of this file composes the same blocks:
  *
- *   SAME, reused as-is          the Gated DeltaNet (conv width 4, key/value head dim 128), the
- *                              GATED full attention (`attn_output_gate`, q_proj twice as wide,
- *                              half of it a sigmoid gate on the attention output), partial rotary
- *                              (64 of 256 dims), the routed feed-forward with a shared expert and
- *                              its own sigmoid gate, the MTP position.
- *   NEW, in this tree           the GATED RESIDUAL (arch/common/rad_block_hc.h), the n-gram / PLE
+ *   reused                     the Gated DeltaNet (conv width 4, key/value head dim 128), gated
+ *                              full attention (`attn_output_gate`: q_proj twice as wide, half of
+ *                              it a sigmoid gate on the output), partial rotary (64 of 256 dims),
+ *                              the routed feed-forward with a gated shared expert, the MTP
+ *                              position.
+ *   new                        the gated residual (arch/common/rad_block_hc.h), the n-gram / PLE
  *                              layer (arch/common/rad_block_ple.h), QSA's indexer
- *                              (arch/common/rad_qsa.h), the STACKED dense expert tensors
- *                              (tools/rad_convert.cpp's slice_stacked), gqa 12, and the delta
- *                              net's SIGMOID output gate. The last two sections of this comment
- *                              say what the first two of those are for.
+ *                              (arch/common/rad_qsa.h), stacked dense expert tensors
+ *                              (tools/rad_convert.cpp, slice_stacked), gqa 12, and the delta net's
+ *                              sigmoid output gate.
  *
  * Qwen3.8-Flash-Next: 48 layers of 12 x (3 x GatedDeltaNet -> MoE, then 1 x QSA -> MoE), hidden
  * 2560, hc_count 4 so the residual stream is 10240, 512 experts of 640 at top-10 plus a shared 640,
@@ -27,26 +25,24 @@
  *
  * ============================== THE RESIDUAL STREAM IS FOUR TIMES AS WIDE ==============================
  *
- * There is no `input_layernorm`, no `post_attention_layernorm` and no final `norm` in this
- * checkpoint. In their place every block has a GATED RESIDUAL connection -- a grouped norm over a
- * 10240 stream, a low-rank data-dependent read gate that mixes the four sub-streams down to 2560,
- * and four data-dependent scalars that gain the block's output back into all four. 96 of them, plus
- * a 97th with no write half that collapses the stream for the lm_head.
+ * The checkpoint has no `input_layernorm`, `post_attention_layernorm` or final `norm`. Instead
+ * every block has a gated residual connection: a grouped norm over the 10240-wide stream, a
+ * low-rank data-dependent read gate that mixes the four sub-streams down to 2560, and four
+ * data-dependent scalars that add the block's output back into all four. There are 96, plus a 97th
+ * with no write half that collapses the stream for the lm_head.
  *
  * arch/common/rad_block_hc.h holds the arithmetic and docs/OPS.md's `hc_read` / `hc_write` rows
- * hold the schema. What matters HERE is that the blocks do not own their norms: this plugin
- * passes `Src::norm = nullptr`, which is the three fp8 blocks' "the input is already normed and
- * quantised" mode, and it therefore also gives up the two fusions that mode is built on -- the
- * residual add folded into the next norm, and the all-reduce folded into it. The all-reduce rides
- * in the gated residual's write instead, wherever a kernel serves that (HyperConn::Config::reduce,
- * see declare()).
+ * the schema. The blocks do not own their norms: this plugin passes `Src::norm = nullptr`, the fp8
+ * blocks' "input already normed and quantised" mode, which forgoes folding the residual add and
+ * the all-reduce into the next norm. The all-reduce rides in the gated residual's write instead,
+ * where a kernel serves that (HyperConn::Config::reduce, see declare()).
  *
  * ============================== WHAT IS AND IS NOT FP8 ==============================
  *
- * The checkpoint is bf16 THROUGHOUT -- it carries no `quantization_config` at all -- so this
- * plugin's quantisation descriptor is the EMPTY one and the formats it serves are made by a
- * recipe (data/recipes/qwen4exp-*.recipe). The plugin reads each weight's encoding and declares
- * what that is; the blocks that read a weight in more than one format choose their ops by it:
+ * The checkpoint is bf16 throughout (no `quantization_config`), so the quantisation descriptor is
+ * empty and the served formats come from a recipe (data/recipes/qwen4exp-*.recipe). The plugin
+ * declares each weight at its encoding, and blocks that read several formats choose their ops by
+ * it:
  *
  *   block fp8 or int8  self_attn.{q,k,v,o}_proj, linear_attn.{in_proj_qkv, in_proj_z, out_proj},
  *                      the shared expert's three (LinearFP8); the indexer's qk projection
@@ -63,28 +59,25 @@
  *
  * ============================== HOW TENSOR PARALLEL SPLITS AN EXPERT ==============================
  *
- * `moe_intermediate_size` is 640 = 5 x 128. A rank's even share at tp2 is 320, which is NOT a whole
- * number of 128-column blocks -- the fp8 scale block, the 4-bit scale group and the rotation all
- * sit on them. So each rank takes three blocks of the experts of one parity and two of the
- * other's, the router stays replicated so both ranks agree on the routing, each rank computes its
- * slice of every routed expert, and THE BLOCK'S EXISTING END-OF-BLOCK ALL-REDUCE SUMS THE
- * PARTIALS. No all-to-all, no extra collective. The section in declare() carries the detail, and
- * why this is preferred to splitting the experts themselves between the ranks.
+ * `moe_intermediate_size` is 640 = 5 x 128. An even tp2 share, 320, is not a whole number of
+ * 128-column blocks, on which the fp8 scale block, the 4-bit scale group and the rotation sit. So
+ * each rank takes three blocks of the experts of one parity and two of the other's; the router is
+ * replicated so both ranks route alike, each rank computes its slice of every routed expert, and
+ * the block's existing end-of-block all-reduce sums the partials, with no all-to-all. See the
+ * section in declare().
  *
  * ============================== PLE AND QSA ==============================
  *
- * PLE / THE N-GRAM EMBEDDING is 51B of the model's 180B parameters -- a 320,001,536-row table of
- * 160-dim embeddings, gathered 16 rows a token by a hash of the last three token ids, read once at
- * layer 1 and injected into the wide stream. Without it this is a 125B model missing a third of
- * its parameters.
+ * PLE, the n-gram embedding, is 51B of the model's 180B parameters: a 320,001,536-row table of
+ * 160-dim embeddings, gathered 16 rows per token by a hash of the last three token ids, read once
+ * at layer 1 and injected into the wide stream.
  *
- * QSA'S INDEXER picks the best `indexer_budget / indexer_compress_ratio` = 512 blocks of 4 tokens
- * for each query and attends to those alone. Below `indexer_budget + indexer_compress_ratio - 1` =
- * 2051 tokens of context EVERY complete block is selected, so QSA is DENSE CAUSAL ATTENTION bit
- * for bit -- which is the oracle any change to it is checked against, and is also why the engine
- * issues the cheaper dense attention there. Above it the selection is per QUERY on both paths
- * (docs/QSA.md, arch/common/rad_qsa.h), so a long prompt is prefilled with the model's own
- * attention and not a denser stand-in.
+ * QSA's indexer picks the best `indexer_budget / indexer_compress_ratio` = 512 blocks of 4 tokens
+ * per query and attends only to those. Below `indexer_budget + indexer_compress_ratio - 1` = 2051
+ * tokens of context every complete block is selected, so QSA equals dense causal attention bit for
+ * bit; the engine issues the cheaper dense attention there, and it serves as the oracle for QSA.
+ * Above it the selection is per query on both prefill and decode (docs/QSA.md,
+ * arch/common/rad_qsa.h).
  *
  * The vision tower is declared through arch/common/rad_block_vit.h, only when the container
  * carries one and the deployment asked for media; rad-convert writes only declared weights.
@@ -123,7 +116,7 @@ struct Model {
     Geom           g{};
     GdnFP8::Config gcfg{};
     MoeFP8::Config moecfg{};
-    /* The trunk's linears are int8 (LinearFP8::i8), read off the first delta-net layer's input
+    /* The trunk's linears are int8 (LinearFP8::i8), as read from the first delta-net layer's input
      * projection before the activation buffers are declared. */
     bool           trunk_i8 = false;
     HyperConn::Config hccfg{};
@@ -132,7 +125,6 @@ struct Model {
     rad_kvgroup        kv_qsa_bkey = 0;   /* created by the first QSA layer's declare() */
 
     int64_t n_rot = 0;
-    int64_t n_run = 0;          /* layers this step actually issues; the bisect truncates it */
 
     rad_kvgroup kv_full = 0, kv_state = 0, kv_conv = 0;
     /* PLE lives on exactly one layer; -1 when the checkpoint has none or this build does not
@@ -140,13 +132,11 @@ struct Model {
     PleLayer    ple;
     int64_t     ple_layer = -1;
 
-    /* THE WIDE STREAM and the narrow block input. `b_h` is the residual stream -- hc * n_embd a
-     * token -- and `a_x` is what a connection's read produces and what the block it fronts writes
-     * its delta back into. One of each for the whole model, as qwen35_fp8 has one `x` and one `h`:
-     * a connection's read is immediately followed by its block and then by its write, so nothing
-     * in `a_x` or `b_inj` has to survive past the write that consumes it. DECLARATION ORDER IS
-     * WHAT THE BUFFER PLANNER'S LIVENESS IS (see the note at declare()), so that sentence is a
-     * statement about this file's order and not a hope. */
+    /* The wide stream and the narrow block input. `b_h` is the residual stream, hc * n_embd per
+     * token; `a_x` is what a connection's read produces and where its block writes the delta. One
+     * of each for the whole model: a read is immediately followed by its block and its write, so
+     * nothing in `a_x` or `b_inj` outlives the write that consumes it. Declaration order determines
+     * the planner's liveness (see the note at declare()), so this holds by this file's order. */
     rad_buf b_h = 0;
     ActFP8  a_x{};
     rad_buf b_inj = 0;
@@ -163,19 +153,17 @@ struct Model {
     rad_buf b_rlogits = 0, b_eids = 0, b_ew = 0, b_sorted = 0, b_eoff = 0, b_ecnt = 0;
     rad_buf b_egu = 0, b_edn = 0, b_emoe = 0, b_sgu = 0, b_sout = 0, b_sgate = 0;
     ActFP8  a_eff{}, a_sff{};
-    /* The ROTATED codes of the block input, for the routed arm alone -- only `q` and `s` are used
-     * and `x` stays zero, because the bf16 it was quantised from is `a_x`'s and is unrotated.
-     * Declared only when the container asks for a rotation; zero otherwise, which is how the MoE block
-     * knows the pair is absent. */
+    /* The rotated codes of the block input, for the routed arm only: `q` and `s` are used and `x`
+     * stays zero, since the bf16 source is `a_x`, unrotated. Declared only when the container asks
+     * for a rotation; zero handles tell the MoE block the pair is absent. */
     ActFP8  a_hr{};
 
     rad_buf b_hout = 0, b_logits = 0;
 
     /* ---- the multi-token-prediction head (arch/common/rad_block_mtp_hc.h). Declared only when
-     * the deployment speculates -- it is ~2.5 GiB of weights a non-speculative server would read
-     * off disk, place in VRAM and never issue, and `max_spec` is the engine already saying whether
-     * it intends to draft. rad-convert declares at a non-zero max_spec on purpose, because a
-     * CONTAINER should carry what the model can serve even when the run that made it would not. */
+     * the deployment speculates, since its ~2.5 GiB of weights would otherwise be loaded and never
+     * issued. rad-convert declares at a non-zero max_spec so the container carries everything the
+     * model can serve. */
     bool        have_mtp = false;
     MtpHcBlock  mtp{};
     rad_buf     b_mtp_hin = 0, b_mtp_hw = 0, b_mtp_e = 0, b_mtp_hout = 0;
@@ -185,15 +173,32 @@ struct Model {
 
     HcEnter   enter;
     HyperConn mixer;            /* the 97th connection: no write half */
+    /* Whether this rank has said that it pipelines a prefill step (step_pipelined), once. */
+    bool      pipe_noted = false;
+    /* Whether the deployment spans (RadBuildCtx::max_mixed_tok below a max_tok wider than a MoE
+     * pass): a step wider than a pass is then one sequence, the connections read it a pass at a
+     * time and the indexer scores it in windows. `pipe_on` adds ranks whose blocks issue their own
+     * all-reduce at such a step (declare): it is pipelined (step_pipelined) and its all-reduces
+     * are declared at `overlap` 1. Without a span neither is set and none of these paths is
+     * declared or taken. A sizing declare runs at a max_tok no wider than a pass and takes both
+     * from the real declare, so it declares the same ops. */
+    bool      span_on = false;
+    bool      pipe_on = false;
+    /* {0, pass, T} for a step wider than a pass (pipe_bounds): the windows of the indexer's score
+     * plane and the delta net's pieces. A transient (declare), uploaded by every step that reads
+     * it -- the first two from the pinned host copy `pipe_cu_h`, made once. */
+    rad_buf   b_pipe_cu = 0;
+    int32_t*  pipe_cu_h = nullptr;
+    bool      pipe_cu_tried = false;
 
     std::vector layers;
 
     rad_weight w_tok = 0, w_lm_head = 0;
     rad_op op_embed = 0, op_embed_ar = 0, op_rope_cs = 0, op_gather = 0, op_logits = 0;
 
-    /* ---- media (arch/common/rad_block_vit.h): the vision tower an encoder pass runs, and the
-     * scatter that puts its rows over the token embeddings. Declared only when the container
-     * carries a tower and the deployment asked for media (RadBuildCtx::max_enc_patches). */
+    /* ---- media (arch/common/rad_block_vit.h): the vision tower and the scatter of its rows over
+     * the token embeddings, declared only when the container carries a tower and the deployment
+     * asked for media (RadBuildCtx::max_enc_patches). */
     bool        media = false;
     VisionTower vit{};
     MediaRows   mrows{};
@@ -202,78 +207,16 @@ struct Model {
 
 static Model g_model[MAX_RANKS];
 
-static inline bool is_full_attention(int64_t l, int64_t interval) {
-    return interval > 0 && ((l + 1) % interval == 0);
-}
-
-/* THE CONTAINER'S OWN SCHEDULE, CHECKED AGAINST THE ONE WE DERIVE -- qwen35_fp8 argues this at
- * length and the argument is identical here, with one addition: Qwen4-Exp's config says
- * "full_attention" for the layers that actually run QSA (the HuggingFace post_init rewrites them to
- * "qwen_sparse_attention" in memory and the file on disk says the former), so BOTH spellings are
- * accepted for a full layer and neither is accepted for a linear one. */
-static int check_layer_schedule(const RadModelMeta* meta, int64_t n_layer, int64_t interval) {
-    const char* s = rad_meta_gets(meta, "text_config.layer_types", nullptr);
-    if (!s) s = rad_meta_gets(meta, "layer_types", nullptr);
-    if (!s || !*s) return RAD_OK;
-
-    int64_t l = 0;
-    const char* p = s;
-    while (*p && l < n_layer) {
-        while (*p == ' ') ++p;
-        if (!*p) break;
-        const char* e = p;
-        while (*e && *e != ' ') ++e;
-        const size_t n = (size_t)(e - p);
-        const bool says_full = (n == 15 && std::strncmp(p, "full_attention", 14) == 0) ||
-                               (n == 14 && std::strncmp(p, "full_attention", 14) == 0) ||
-                               (n == 22 && std::strncmp(p, "qwen_sparse_attention", 21) == 0) ||
-                               (n == 21 && std::strncmp(p, "qwen_sparse_attention", 21) == 0);
-        const bool says_lin  = (n == 17 && std::strncmp(p, "linear_attention", 16) == 0) ||
-                               (n == 16 && std::strncmp(p, "linear_attention", 16) == 0);
-        if (!says_full && !says_lin) {
-            fprintf(stderr, "radiance: qwen4exp: layer_types[%lld] is '%.*s', which is neither a "
-                            "linear_attention nor a full/sparse attention layer\n",
-                    (long long)l, (int)n, p);
-            return RAD_E_UNSUPPORTED;
-        }
-        if (says_full != is_full_attention(l, interval)) {
-            fprintf(stderr, "radiance: qwen4exp: the container says layer %lld is %s and the "
-                            "interval rule (every %lld-th) says %s. The schedule decides which "
-                            "layers are linear, so a disagreement is a different model.\n",
-                    (long long)l, says_full ? "full attention" : "linear",
-                    (long long)interval, is_full_attention(l, interval) ? "full" : "linear");
-            return RAD_E_UNSUPPORTED;
-        }
-        ++l;
-        p = e;
-    }
-    if (l != n_layer) {
-        fprintf(stderr, "radiance: qwen4exp: layer_types names %lld layers and the container has "
-                        "%lld\n", (long long)l, (long long)n_layer);
-        return RAD_E_UNSUPPORTED;
-    }
-    return RAD_OK;
-}
-
-/* An env switch that is OFF unless set to something other than "0". Spelled once because there are
- * four of them and each one is a statement that the model being run is not the model on disk. */
-/* HOW MANY ROWS THE N-GRAM TABLE HAS, and it is a prime search because the checkpoint's own answer
- * arrives too late.
+/* The n-gram table's row count, by prime search.
  *
- * Each of the `heads` hash heads gets its own vocabulary: the 1st, 2nd, ... nth prime above
- * `ngram_vocab_size_base - 1`. The table is their sum, padded to `divisor`. The reference builds
- * exactly this in `Qwen4ExpTextNGramEmbedding.__init__` and the resulting per-head sizes ARE in the
- * checkpoint -- `ngram_heads_vocab_sizes` -- which is where the served hash reads them from, and
- * nothing here re-derives those.
+ * Each of the `heads` hash heads has its own vocabulary: the 1st, 2nd, ... nth prime above
+ * `ngram_vocab_size_base - 1`; the table is their sum, padded to `divisor`
+ * (`Qwen4ExpTextNGramEmbedding.__init__`). The per-head sizes are in the checkpoint
+ * (`ngram_heads_vocab_sizes`) and the served hash reads them there; only the total is derived,
+ * because a weight's shape must be declared before any tensor is opened. rad-convert checks it:
+ * a multi-source concat's declared leading extent must equal its sources'.
  *
- * WHAT IS DERIVED IS THE TOTAL, and only because a weight's shape must be declared before any
- * tensor has been opened. Getting it wrong would ship a container whose directory claims one row
- * count and carries another's bytes, so rad-convert refuses exactly that: the declared leading
- * extent of a multi-source concat has to equal its sources'. This search is checked against 128
- * shards of real bytes on every convert.
- *
- * The cost is 16 primes near 2e7 by trial division -- a few hundred thousand divisions, once, at
- * declare. */
+ * Cost: 16 primes near 2e7 by trial division, once at declare. */
 static bool ngram_is_prime(int64_t v) {
     if (v < 2) return false;
     if (v % 2 == 0) return v == 2;
@@ -292,46 +235,51 @@ static int64_t ngram_table_rows(int64_t base, int64_t heads, int64_t divisor) {
     return divisor > 1 ? ((total + divisor - 1) / divisor) * divisor : total;
 }
 
-/* A RANK'S PLACE WHERE THE SHARED EXPERT'S BLOCKS DO NOT DIVIDE over the ranks, the first places
- * taking one block more. A plain expert is a routed expert's width in 64-wide tiles, which need
- * not divide either, and MoeFP8::declare hands its extra tiles to the first ranks by index; the
- * shared expert's extra blocks start at the rank after the last of those, so the two remainders
- * land on different ranks while there are ranks enough for both. The routed experts leave no
- * remainder to avoid: at two ranks the parity split and at four the four-class split give every
- * rank the same width of them. At four ranks and this family's 640 columns -- ten tiles, five
- * blocks -- ranks 0 and 1 take a tile more and rank 2 the block; at two the ten tiles divide and
- * the place is the rank. */
+/* A rank's place in the shared expert's uneven block split, where the first places take one
+ * block more. MoeFP8::declare hands a plain expert's extra 64-wide tiles to the first ranks by
+ * index; the shared expert's extra blocks start at the rank after the last of those, so the two
+ * remainders land on different ranks when there are enough. (Routed experts leave no remainder:
+ * the parity split at two ranks and the four-class split at four are even.) At four ranks and 640
+ * columns (ten tiles, five blocks) ranks 0 and 1 take a tile more and rank 2 the block; at two the
+ * place is the rank. */
 static int64_t shared_place(int64_t n_ff_all, int world, int rank) {
     const int64_t first = (n_ff_all / 64) % world;
     return (rank - first + world) % world;
 }
 
+/* Columns [lo, hi) of the slice at `place` when `nb` fp8 blocks split over `world` places, the
+ * first nb % world places taking one block more. */
+static void block_slice(int64_t nb, int world, int64_t place, int64_t* lo, int64_t* hi) {
+    const int64_t base = nb / world, extra = nb % world;
+    const int64_t b0 = place * base + std::min(place, extra);
+    *lo = b0 * RAD_FP8_BLOCK;
+    *hi = (b0 + base + (place < extra ? 1 : 0)) * RAD_FP8_BLOCK;
+}
+
 static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
     if (!b || !meta || !ctx) return RAD_E_INVAL;
     if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
 
-    /* A SIZING DECLARE WRITES SCRATCH. The step reads g_model, which the real declare filled at
-     * the real max_tok; one sized for a smaller step must not replace it (RadBuildCtx). */
+    /* A sizing declare writes scratch: the step reads g_model, filled by the real declare at the
+     * real max_tok (RadBuildCtx::shape_probe). */
     static thread_local Model probe_model;
     Model& m = ctx->shape_probe ? probe_model : g_model[ctx->rank];
     m = Model{};
     m.nm = Names(ctx->scope ? ctx->scope : "");
     Names& nm = m.nm;
 
-    /* arch_splits_ff: the routed experts' width (640 = five fp8 blocks) is split by the plugin
-     * below, by whole blocks and parity, at any world up to the block count -- three ranks included,
-     * which 640 does not divide. geom_from must not refuse what the plugin then answers.
-     * attn_world_ok: every attention block this plugin declares is rad_block_attn_gated_fp8.h's,
-     * which serves the smaller attention world of a world the two KV heads do not divide. */
+    /* arch_splits_ff: the plugin splits the routed experts' width (640 = five fp8 blocks) itself,
+     * by whole blocks and parity, at any world up to the block count (including three, which 640
+     * does not divide), so geom_from must not refuse it. attn_world_ok: this plugin's attention
+     * blocks (rad_block_attn_gated_fp8.h) serve a smaller attention world when the two KV heads do
+     * not divide the world. */
     RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16, /*arch_splits_ff=*/true,
                            /*attn_world_ok=*/true));
     Geom& g = m.g;
 
-    /* Qwen4-Exp's norms are all `x_hat * (1 + w)` -- `Qwen3NextRMSNorm.forward` is
-     * `_norm(x.float()) * (1.0 + weight.float())` with the weight initialised to ZEROS -- and its
-     * delta net's gated output norm is the plain `weight * x` with weights initialised to ONES.
-     * That is read off the reference rather than inferred from the checkpoint: one answer, from
-     * the source. */
+    /* Qwen4-Exp's norms are all `x_hat * (1 + w)` (`Qwen3NextRMSNorm.forward` is
+     * `_norm(x.float()) * (1.0 + weight.float())`, weight initialised to zeros); the delta net's
+     * gated output norm is plain `weight * x` (initialised to ones). Taken from the reference. */
     g.wadd    = 1.0f;
     g.wadd_qk = 1.0f;
 
@@ -345,13 +293,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                 (long long)m.hccfg.hc, (long long)m.hccfg.lowrank);
         return RAD_E_INVAL;
     }
-    /* EVERY BLOCK'S ALL-REDUCE RIDES IN THE WRITE THAT FOLLOWS IT, wherever a kernel serves that
-     * (HyperConn::Config::reduce): the block's partial sum is the write's input, so the pair
-     * becomes one launch. The blocks are told below, per connection, whether it resolved. */
+    /* Every block's all-reduce rides in the following write where a kernel serves that
+     * (HyperConn::Config::reduce): the block's partial sum is the write's input, so the pair is one
+     * launch. Each block is told below whether its connection's fused op resolved. */
     m.hccfg.reduce = 1;
     const int64_t HN = m.hccfg.hc * g.n_embd;
 
-    /* ---- partial rotary. 0.25 of head_dim 256 is 64, and the other 192 dims pass through. */
+    /* ---- partial rotary: 0.25 of head_dim 256 is 64; the other 192 dims pass through. */
     {
         const double pr = rad_meta_getf(meta, "text_config.rope_parameters.partial_rotary_factor",
                           rad_meta_getf(meta, "rope_parameters.partial_rotary_factor",
@@ -365,11 +313,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
         }
     }
     RAD_ARCH_TRY(yarn_from(g, meta, "", m.n_rot));
-    /* THERE IS NO BRING-UP SLICE, and the rule is worth stating: if a model ever arrives too large
-     * for the target device, the answer is a converter flag that writes a NAMED partial container
-     * -- not an environment variable that makes a full one silently mean something else. A slice
-     * declared at serve time is a server computing something that is not the model while looking
-     * exactly like one that is. */
+    /* There is deliberately no serve-time layer slice. A model too large for the device needs a
+     * converter flag that writes a named partial container, not a switch that silently serves less
+     * than the model. */
 
     /* ---- the layer schedule. */
     const int64_t interval = meta_int2(meta, "qwen4exp.full_attention_interval",
@@ -380,9 +326,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                 (long long)interval);
         return RAD_E_INVAL;
     }
-    /* The container's `layer_types` names every layer of the WHOLE model, and the count check
-     * inside is against the layer count passed here rather than against the array's length. */
-    RAD_ARCH_TRY(check_layer_schedule(meta, g.n_layer, interval));
+    /* The config file says "full_attention" for the QSA layers (HuggingFace's post_init rewrites
+     * them to "qwen_sparse_attention" in memory), so both spellings mean a full layer. */
+    RAD_ARCH_TRY(check_layer_schedule("qwen4exp", meta_text_gets(meta, "layer_types", nullptr),
+                                      g.n_layer, interval,
+                                      {"full_attention", "qwen_sparse_attention"}));
 
     /* ---- the delta net. */
     {
@@ -395,8 +343,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
         gc.head_v     = meta_int2(meta, "qwen4exp.ssm.value_head_dim", "linear_value_head_dim", 0);
         gc.conv_width = meta_int2(meta, "qwen4exp.ssm.conv_kernel",    "linear_conv_kernel_dim", 0);
         gc.chunk      = 64;
-        /* `output_gate_type` is a CHECKPOINT property: Qwen3.5/3.6 leave it unset and mean silu,
-         * Qwen4-Exp states "sigmoid". libr4d's gated norm has both arms. */
+        /* `output_gate_type` is a checkpoint property: Qwen3.5/3.6 leave it unset and mean silu,
+         * Qwen4-Exp states "sigmoid". libr4d's gated norm has both. */
         const char* ogt = rad_meta_gets(meta, "text_config.output_gate_type",
                           rad_meta_gets(meta, "output_gate_type", nullptr));
         if (!ogt || !*ogt) ogt = rad_meta_gets(meta, "text_config.hidden_act",
@@ -410,12 +358,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                     (long long)gc.conv_width);
             return RAD_E_INVAL;
         }
-        /* THE HEADS SPLIT EVENLY WHEN THEY CAN, as before, and UNEVENLY WHEN THEY CANNOT: 16 K
-         * heads over three ranks are 6, 5 and 5, each rank's V heads the same multiple of its K
-         * heads (48 / 16 = 3 -> 18, 15, 15), declared as spans of the container's rows
-         * (rad_block_gdn_fp8.h Config::k_first). Nothing is padded and every rank holds real
-         * heads; the kernels take any head count. A V count that is not a multiple of the K count
-         * cannot be grouped that way and is refused. */
+        /* Heads split evenly when they can and unevenly otherwise: 16 K heads over three ranks
+         * are 6, 5 and 5, each rank's V heads the same multiple of its K heads (48 / 16 = 3 ->
+         * 18, 15, 15), declared as spans of the container's rows (rad_block_gdn_fp8.h,
+         * Config::k_first). Nothing is padded; the kernels take any head count. A V count that is
+         * not a multiple of the K count is refused. */
         gc.n_head_k_all = nk;
         gc.n_head_v_all = nv;
         if (g.world > 1 && (nk % g.world != 0 || nv % g.world != 0)) {
@@ -426,15 +373,15 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                 return RAD_E_INVAL;
             }
             const int64_t ratio = nv / nk, base = nk / g.world, rem = nk % g.world;
-            /* The extra heads go to the ranks without attention first (rad_arch.h
-             * remainder_place); with none, this is the rank's own place and the split as before. */
+            /* Extra heads go first to ranks without attention (rad_arch.h remainder_place);
+             * with none, this is the rank's own place. */
             const int64_t pl = remainder_place(g, g.rank, 0);
             gc.n_head_k = base + (pl < rem ? 1 : 0);
             gc.k_first  = pl * base + (pl < rem ? pl : rem);
             gc.n_head_v = ratio * gc.n_head_k;
             gc.v_first  = ratio * gc.k_first;
-            fprintf(stderr, "radiance: qwen4exp: rank %d takes delta-net K heads [%lld, %lld) of "
-                            "%lld and V heads [%lld, %lld) of %lld\n", g.rank,
+            rad_note(b, "rank %d takes delta-net K heads [%lld, %lld) of %lld and V heads "
+                        "[%lld, %lld) of %lld", g.rank,
                     (long long)gc.k_first, (long long)(gc.k_first + gc.n_head_k), (long long)nk,
                     (long long)gc.v_first, (long long)(gc.v_first + gc.n_head_v), (long long)nv);
         } else {
@@ -446,10 +393,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
 
     /* ---- the routed feed-forward.
      *
-     * n_ff is `moe_intermediate_size`: divided by world_size when the world divides it, and left
-     * whole when it does not (geom_from's `arch_splits_ff`). Either way it is only the starting
-     * point -- at more than one rank the split below decides the rank's width, by whole fp8
-     * blocks and parity, which is what the header's tensor-parallel section is about. */
+     * n_ff is `moe_intermediate_size`, divided by world_size when the world divides it and whole
+     * otherwise (geom_from's `arch_splits_ff`). At more than one rank the split below sets the
+     * rank's width, by whole fp8 blocks and parity (see the file header). */
     {
         MoeFP8::Config& mc = m.moecfg;
         mc.n_expert    = meta_int2(meta, "qwen4exp.expert_count",      "num_experts", 0);
@@ -457,11 +403,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
         mc.n_ff_exp    = g.n_ff;
         mc.n_ff_shared = meta_int2(meta, "qwen4exp.expert_shared_feed_forward_length",
                                    "shared_expert_intermediate_size", 0);
-        /* THE SHARED ARM IS SPLIT BY WHOLE fp8 SCALE BLOCKS: evenly when its width halves into
-         * them, and otherwise as evenly as whole blocks allow, cut by the rank's place
-         * (shared_place) -- this family's 640 columns are five blocks, three on rank 0 and two on
-         * rank 1; at four ranks two on rank 2 and one on each of the others. See
-         * MoeFP8::Config::shared_lo. */
+        /* The shared expert is split by whole fp8 scale blocks: evenly when possible, otherwise
+         * as evenly as whole blocks allow, by the rank's place (shared_place). Its 640 columns are
+         * five blocks: three on rank 0 and two on rank 1; at four ranks two on rank 2 and one on
+         * each other. See MoeFP8::Config::shared_lo. */
         if (mc.n_ff_shared > 0 && g.world > 1 && (mc.n_ff_shared / g.world) % RAD_FP8_BLOCK == 0) {
             int s;
             if ((s = divide_or_fail(mc.n_ff_shared, g.world,
@@ -476,47 +421,40 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                 return RAD_E_INVAL;
             }
             const int64_t nb = mc.n_ff_shared / RAD_FP8_BLOCK;
-            const int64_t base = nb / g.world, extra = nb % g.world;
-            const int64_t place = shared_place(g.n_ff_all, g.world, g.rank);
-            const int64_t b0 = place * base + std::min(place, extra);
-            const int64_t b1 = b0 + base + (place < extra ? 1 : 0);
-            mc.shared_lo   = b0 * RAD_FP8_BLOCK;
-            mc.shared_hi   = b1 * RAD_FP8_BLOCK;
+            block_slice(nb, g.world, shared_place(g.n_ff_all, g.world, g.rank),
+                        &mc.shared_lo, &mc.shared_hi);
             mc.n_ff_shared = mc.shared_hi - mc.shared_lo;
-            rad_note(b, "the shared expert does not halve into %d-column fp8 scale blocks, so rank "
-                        "%d computes columns [%lld, %lld) of it -- %lld of %lld blocks -- and the "
-                        "block's all-reduce sums the ranks' partials.", RAD_FP8_BLOCK, g.rank,
-                     (long long)mc.shared_lo, (long long)mc.shared_hi, (long long)(b1 - b0),
-                     (long long)nb);
+            rad_note(b, "the shared expert does not split evenly into %d-column fp8 scale blocks: "
+                        "rank %d computes columns [%lld, %lld) of it, %lld of %lld blocks, and the "
+                        "all-reduce sums the partials", RAD_FP8_BLOCK, g.rank,
+                     (long long)mc.shared_lo, (long long)mc.shared_hi,
+                     (long long)(mc.n_ff_shared / RAD_FP8_BLOCK), (long long)nb);
         }
         mc.norm_topk   = 1;
-        /* THE GPTQ CALIBRATION RUN, gated by the same variable that says where to write: there is
-         * no second switch, because a calibration with nowhere to put its answer is a 1.34 GB
-         * allocation and two extra launches a layer for nothing. It is a separate run from
-         * serving -- see MoeFP8::Config::calib. */
+        /* GPTQ calibration run, enabled by the same setting that names the output directory (a
+         * calibration with nowhere to write would be a 1.34 GB allocation and two launches per
+         * layer for nothing). A separate run from serving; see MoeFP8::Config::calib. */
         mc.calib       = calib_dir() != nullptr ? 1 : 0;
-        /* Tokens a pass. 2048 is the linear-state checkpoint interval this family's scheduler
-         * clamps the prefill chunk to, so the shipped configuration is ONE pass and the slicing is
-         * inert -- but it also sizes four buffers at `rows * top_k`, so a deployment whose
-         * max_tok is smaller must not pay for rows it cannot present. */
+        /* Tokens per pass. 2048 is the linear-state checkpoint interval the scheduler clamps the
+         * prefill chunk to, so the shipped configuration is one pass. It also sizes four buffers at
+         * `rows * top_k`, so a smaller max_tok lowers it. */
         mc.rows        = g.max_tok < 2048 ? g.max_tok : 2048;
         if (mc.n_expert <= 0 || mc.top_k <= 0 || mc.top_k > mc.n_expert) {
             fprintf(stderr, "radiance: qwen4exp: the container describes %lld expert(s) with "
                             "top_k %lld\n", (long long)mc.n_expert, (long long)mc.top_k);
             return RAD_E_INVAL;
         }
-        /* ---- THE EXPERTS' STORED FORMAT -- block fp8, four-bit, four-bit rotated, or the
-         * checkpoint's plain bf16 -- read off one expert's encoding (MoeFP8::probe) before anything
-         * is sized by it: how the experts are split between the ranks, the rotated copy of the
-         * block input, the connection in front of every routed block, and -- for bf16 -- every
-         * linear in the model. It is the container's, the checkpoint's, or the recipe's that
-         * rad-convert is applying, so a container cannot be served in a format other than the one
-         * it holds.
+        /* ---- the experts' stored format (block fp8, four-bit, four-bit rotated, or plain bf16),
+         * read from one expert's encoding (MoeFP8::probe) before anything is sized by it: the
+         * split between ranks, the rotated copy of the block input, the connection in front of
+         * every routed block, and for bf16 every linear in the model. The encoding comes from the
+         * container, checkpoint or recipe being applied, so a container is always served in the
+         * format it holds.
          *
-         * THE EXPERT ASKED IS THE FIRST ONE THIS RANK OWNS UNDER EXPERT PARALLELISM. The answer
-         * decides whether the experts are split that way, so it has to be asked before; and the
-         * expert is declared on this rank either way -- whole under expert parallelism, a slice of
-         * it under the parity split -- so the block skips exactly the map the probe made. */
+         * The probed expert is the first one this rank owns under expert parallelism: the answer
+         * decides whether that split is used, and the expert is declared on this rank either way
+         * (whole, or a slice under the parity split), so the block skips exactly the map the probe
+         * made. */
         mc.probed_expert = (g.world > 1 && mc.n_expert % g.world == 0)
                                ? (int64_t)g.rank * (mc.n_expert / g.world) : 0;
         {
@@ -525,57 +463,48 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                                             "model.language_model.layers.0.mlp.experts", &ps));
             RAD_ARCH_TRY(MoeFP8::probe(b, nm, 0, ps, &mc));
         }
-        /* A CHECKPOINT SERVED AS IT SHIPS IS bf16 THROUGHOUT. Plain experts mean a container
-         * converted without a quantising recipe, and every linear of it is then plain too: the
-         * blocks issue bf16 GEMMs over the bf16 activation and nothing in front of them quantises
-         * (Geom::w_bf16). Each linear checks its own encoding against this and refuses a quantised
-         * one. The other way round is allowed: a quantised container may keep a linear plain --
-         * the QSA indexer's projection -- and LinearFP8 reads that one as bf16. */
+        /* Plain experts mean a container converted without a quantising recipe, so every linear
+         * is plain too: the blocks issue bf16 GEMMs over bf16 activations and nothing quantises
+         * (Geom::w_bf16). Each linear refuses a quantised encoding then. The converse is allowed:
+         * a quantised container may keep a linear plain (the QSA indexer's projection), which
+         * LinearFP8 reads as bf16. */
         g.w_bf16 = mc.expert_bf16 != 0;
-        /* ...and the connections in front of the blocks emit no codes, since nothing reads any. */
+        /* The connections in front of the blocks then emit no codes, since nothing reads them. */
         m.hccfg.quant = g.w_bf16 ? 0 : 1;
         /* ============================== EVERY RANK HOLDS A SLICE OF EVERY EXPERT ==============================
          *
-         * An expert of this model is 640 columns, five 128-column blocks -- the fp8 scale block,
-         * the 4-bit plane's scale group and the rotation's width all at once -- so two ranks
-         * cannot halve one.
+         * An expert is 640 columns, five 128-column blocks (the fp8 scale block, the 4-bit scale
+         * group and the rotation width), so two ranks cannot halve one.
          *
-         * THE SPLIT IS BY PARITY: each parity's five blocks are cut contiguously over the ranks,
-         * and the rank that takes the extra block alternates with the expert's parity
-         * (MoeFP8::Config::ff_lo says why by parity). At two ranks, rank r's slice of expert e is
-         * the first three blocks when e % 2 == r and the last two otherwise. The router stays
-         * replicated, every rank computes its slice of every routed expert, and the block's
-         * all-reduce sums the partials.
+         * The split is by parity: each parity's five blocks are cut contiguously over the ranks,
+         * and the rank taking the extra block alternates with the expert's parity
+         * (MoeFP8::Config::ff_lo). At two ranks, rank r's slice of expert e is the first three
+         * blocks when e % 2 == r and the last two otherwise. The router is replicated, every rank
+         * computes its slice of every routed expert, and the block's all-reduce sums the partials.
          *
-         * AT FOUR RANKS PARITY IS NOT ENOUGH. It gives the extra block only two places to go, so
-         * ranks 0 and 1 would compute three blocks of every even/odd pair of experts and ranks 2
-         * and 3 two, and the all-reduce would have ranks 2 and 3 wait for the other two. So at four
-         * the extra block is rotated over four places, by the expert's number mod 4: four slice
-         * tables (`moe_gemm_q_mod4`), and every rank computes five blocks of every four experts.
-         * A layer keeping two experts plain bf16 has 510 quantised ones, and its first two classes
-         * are one expert longer. What does not divide elsewhere stays apart: the plain experts'
-         * extra tiles are ranks 0 and 1's (MoeFP8::declare) and the shared expert's extra block
-         * rank 2's (shared_place).
+         * At four ranks parity alone would give ranks 0 and 1 three blocks of every expert pair
+         * and ranks 2 and 3 two, leaving 2 and 3 waiting in the all-reduce. So the extra block
+         * rotates over four places by expert number mod 4 (four slice tables, `moe_gemm_q_mod4`),
+         * and every rank computes five blocks of every four experts. A layer keeping two experts
+         * plain bf16 has 510 quantised ones, and its first two classes are one expert longer.
+         * Other remainders stay apart: the plain experts' extra tiles go to ranks 0 and 1
+         * (MoeFP8::declare), the shared expert's extra block to rank 2 (shared_place).
          *
-         * WHY NOT EXPERT PARALLELISM, which splits the EXPERTS: rank r owns [r*E/W, (r+1)*E/W)
-         * whole. The bytes a rank reads are the same on average either way, but which rank a
-         * routed expert lands on is a coin flip, and a verify step's forty routed slots leave one
-         * rank about five experts ahead -- which the all-reduce turns into the other ranks waiting,
-         * about a millisecond a step at one sequence. Split by parity the ranks differ by a fifth
-         * of an expert per unit of the even/odd difference instead. Whole experts would also break
-         * the protected experts' pairing: the recipe protects them in pairs so each rank's count of
-         * quantised experts stays even, which the two parity tables need.
+         * Not expert parallelism (rank r owning experts [r*E/W, (r+1)*E/W) whole): bytes per rank
+         * are equal on average, but routing is random, and a verify step's forty routed slots leave
+         * one rank about five experts ahead, costing about a millisecond per step at one sequence
+         * in the all-reduce wait. With parity the ranks differ by a fifth of an expert per unit of
+         * even/odd imbalance. Whole experts would also break the recipe's pairing of protected
+         * experts, which keeps each rank's quantised-expert count even for the two parity tables.
          *
-         * A CALIBRATION RUN SPLITS THE EXPERTS INSTEAD, whole experts per rank. The down
-         * projection's Hessian is over an expert's whole K, and a rank holding a slice of each
-         * expert has only its slice's block of it -- the cross terms live on the other rank. Whole
-         * experts give each rank the Hessian of every expert it holds, which is what the packer
-         * sums (rad_arch.h's calib_dir). */
+         * A calibration run does split whole experts per rank: the down projection's Hessian spans
+         * an expert's whole K, and a slice would lack the cross terms. Whole experts give each rank
+         * the full Hessian of every expert it holds, which the packer sums (rad_arch.h,
+         * calib_dir). */
         mc.n_expert_all = mc.n_expert;
-        /* AND bf16 EXPERTS ARE SPLIT THE SAME WAY, whole experts per rank: a slice of a bf16 expert
-         * is two row ranges and a column range of the container, which the file tier cannot read
-         * as one run, and nothing about bf16 needs the parity split's balance -- a bf16 model is
-         * served to calibrate and to compare, not for its decode rate. */
+        /* bf16 experts are also split whole per rank: a slice of a bf16 expert is two row ranges
+         * and a column range, which the file tier cannot read as one run, and a bf16 model is
+         * served to calibrate and compare, not for decode speed. */
         if (g.world > 1 && (mc.calib || mc.expert_bf16)) {
             int s;
             int64_t per = 0;
@@ -599,59 +528,46 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
             if (nb % g.world == 0) {
                 mc.n_ff_exp = g.n_ff_all / g.world;
             } else if (g.world <= nb) {
-                /* The uneven split is TWO SLICES, not two RANKS: each parity's blocks are cut
+                /* The uneven split is two slices per rank: each parity's blocks are cut
                  * contiguously across the ranks and the rank taking the odd block alternates with
-                 * the parity, so every rank's slices are whole blocks and every block of every
-                 * expert has exactly one owner. At two ranks this is the split the tree has always
-                 * made, byte for byte; at four it gives widths of ceil(nb/W) and floor(nb/W).
-                 * A rank must come away with at least one block of each parity -- an empty slice
-                 * is a rank that computes nothing and still joins the all-reduce -- which needs
-                 * the ranks to fit inside the two parities' blocks together. */
-                const int64_t base = nb / g.world, extra = nb % g.world;
+                 * the parity, so slices are whole blocks and every block has exactly one owner.
+                 * Widths are ceil(nb/W) and floor(nb/W). Every rank must get at least one block of
+                 * each parity, since an empty slice still joins the all-reduce, so the world may
+                 * not exceed nb. */
                 for (int q = 0; q < 2; ++q) {
                     /* This rank's place in expert parity q's split: first for its own parity.
-                     * THE EXPERTS DO NOT GO REMAINDER-FIRST (rad_arch.h remainder_place): an
-                     * expert block is a whole GEMM of every routed token, and a rank taking the
-                     * extra block of every class became the step's slowest rank -- measured at
-                     * three ranks, Flash-Next: 50/25/25 cost 25% a step single-stream, and even
-                     * one class's extra block (37/25/37) swung 16-19 ms between boots. The delta
-                     * net's remainder is a head's worth of work and goes to the rank without
-                     * attention; the experts stay on the rotation every world has always had. */
-                    const int64_t p = (g.rank - q + g.world) % g.world;
-                    const int64_t b0 = p * base + std::min(p, extra);
-                    const int64_t b1 = b0 + base + (p < extra ? 1 : 0);
-                    mc.ff_lo[q] = b0 * RAD_FP8_BLOCK;
-                    mc.ff_hi[q] = b1 * RAD_FP8_BLOCK;
+                     * Experts do not go remainder-first (rad_arch.h remainder_place): an expert
+                     * block is a whole GEMM over every routed token, and a rank taking the extra
+                     * block of every class becomes the slowest rank (at three ranks on
+                     * Flash-Next, a 50/25/25 split cost 25% per step single-stream). Only the
+                     * delta net's remainder, a head's worth of work, goes to the rank without
+                     * attention. */
+                    block_slice(nb, g.world, (g.rank - q + g.world) % g.world, &mc.ff_lo[q],
+                                &mc.ff_hi[q]);
                 }
                 mc.n_ff_exp = std::max(mc.ff_hi[0] - mc.ff_lo[0], mc.ff_hi[1] - mc.ff_lo[1]);
-                /* AND AT FOUR RANKS FOUR CLASSES, by the expert's number mod 4 (MoeFP8::Config::
-                 * ff_lo4), which every layer then takes instead: the same cut with the rank's place
-                 * shifted by the class, so the extra block goes round all four ranks instead of
-                 * two. Every block of every expert still has one owner, and each slice is one a
-                 * rank already takes of some parity. */
+                /* At four ranks, four classes by expert number mod 4 (MoeFP8::Config::ff_lo4),
+                 * used by every layer instead: the same cut with the rank's place shifted by the
+                 * class, so the extra block rotates over all four ranks. Every block still has one
+                 * owner. */
                 if (g.world == 4) {
                     for (int q = 0; q < 4; ++q) {
-                        const int64_t p = (g.rank - q + 4) % 4;
-                        const int64_t b0 = p * base + std::min(p, extra);
-                        const int64_t b1 = b0 + base + (p < extra ? 1 : 0);
-                        mc.ff_lo4[q] = b0 * RAD_FP8_BLOCK;
-                        mc.ff_hi4[q] = b1 * RAD_FP8_BLOCK;
-                        mc.n_ff_exp  = std::max(mc.n_ff_exp, mc.ff_hi4[q] - mc.ff_lo4[q]);
+                        block_slice(nb, 4, (g.rank - q + 4) % 4, &mc.ff_lo4[q], &mc.ff_hi4[q]);
+                        mc.n_ff_exp = std::max(mc.n_ff_exp, mc.ff_hi4[q] - mc.ff_lo4[q]);
                     }
                     rad_note(b, "routed experts at four classes: rank %d computes columns [%lld, "
-                                "%lld) [%lld, %lld) [%lld, %lld) [%lld, %lld) of the experts of "
-                                "number 0, 1, 2 and 3 mod 4 -- %lld blocks of every four experts, "
-                                "as every rank does.",
+                                "%lld) [%lld, %lld) [%lld, %lld) [%lld, %lld) of the experts "
+                                "numbered 0, 1, 2 and 3 mod 4, %lld blocks per four experts like "
+                                "every rank",
                              g.rank, (long long)mc.ff_lo4[0], (long long)mc.ff_hi4[0],
                              (long long)mc.ff_lo4[1], (long long)mc.ff_hi4[1],
                              (long long)mc.ff_lo4[2], (long long)mc.ff_hi4[2],
                              (long long)mc.ff_lo4[3], (long long)mc.ff_hi4[3], (long long)nb);
                 } else {
                     rad_note(b, "routed experts: rank %d computes columns [%lld, %lld) of each "
-                                "even expert and [%lld, %lld) of each odd one, of %lld. The width "
-                                "is %lld blocks of %d, which %lld ranks split unevenly, so the rank "
-                                "taking the extra block alternates with the expert's parity; the "
-                                "block's all-reduce sums the partials.",
+                                "even expert and [%lld, %lld) of each odd one, of %lld; %lld "
+                                "blocks of %d do not split evenly over %lld ranks, so the extra "
+                                "block alternates with the expert's parity",
                              g.rank, (long long)mc.ff_lo[0], (long long)mc.ff_hi[0],
                              (long long)mc.ff_lo[1], (long long)mc.ff_hi[1],
                              (long long)g.n_ff_all, (long long)nb, RAD_FP8_BLOCK,
@@ -668,21 +584,18 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
         }
     }
 
-
-    /* ---- the n-gram embedding's layer and the indexer's geometry, each stated in a note where it
-     * changes what this build computes. */
+    /* ---- the n-gram embedding's layer and the indexer's geometry, each noted where it changes
+     * what this build computes. */
     {
         const char* ple = rad_meta_gets(meta, "text_config.ple_layer_ids",
                           rad_meta_gets(meta, "ple_layer_ids", nullptr));
         if (ple && *ple) {
-            /* ONE-INDEXED, and the whole layer hangs off getting that right: `ple_layer_ids: [2]`
-             * is layer_idx 1. The reference says so twice -- `config.ple_layer_ids.index(layer_idx
-             * + 1)` at construction and a [1, num_hidden_layers] bound in the validator. */
+            /* One-indexed: `ple_layer_ids: [2]` is layer_idx 1 (the reference uses
+             * `config.ple_layer_ids.index(layer_idx + 1)` and validates [1, num_hidden_layers]). */
             m.ple_layer = (int64_t)std::strtoll(ple, nullptr, 10) - 1;
             if (m.ple_layer < 0 || m.ple_layer >= g.n_layer) {
-                /* Out of the declared range, which a DECL_LAYERS slice makes ordinary: the layer
-                 * simply is not in this build. Said rather than skipped, because a slice that
-                 * silently drops PLE looks exactly like one that has it. */
+                /* Outside the declared layers: the n-gram embedding is not in this build, and the
+                 * note says so rather than dropping it silently. */
                 rad_note(b, "ple_layer_ids = %s is outside the %lld layers declared, so the n-gram "
                             "embedding is not in this build.", ple, (long long)g.n_layer);
                 m.ple_layer = -1;
@@ -701,32 +614,26 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
         m.qsacfg.topk       = (ratio > 0) ? budget / ratio : 0;
         m.qsacfg.max_blocks = (ratio > 0) ? (g.max_ctx + ratio - 1) / ratio : 0;
         m.qsacfg.max_work   = (ratio > 0) ? (g.max_tok + ratio - 1) / ratio + g.max_seqs : 0;
-        /* The tail's ring, and QsaIndexer::Config::ring is where the arithmetic is argued. It is
-         * `max_spec` and not `n_spec`: a deployment that can speculate three deep sizes for
-         * three, whatever a given step turns out to carry. */
+        /* The tail's ring (see QsaIndexer::Config::ring), sized for `max_spec`, the deepest
+         * speculation any step can carry. */
         m.qsacfg.ring       = ratio + g.max_spec;
         if (budget > 0 && ratio > 0) {
-            /* THE EXACTNESS BOUND, and it is the whole reason dense attention is not an
-             * approximation here: with `pos + 1 <= budget + ratio - 1` tokens visible, the number
-             * of COMPLETE blocks is at most budget/ratio, the indexer's top-k keeps all of them,
-             * and the tail is attended unconditionally -- so the selected set is every visible
-             * token and QSA is dense causal attention bit for bit. */
+            /* The exactness bound: with `pos + 1 <= budget + ratio - 1` tokens visible there are
+             * at most budget/ratio complete blocks, the indexer's top-k keeps all of them, and the
+             * tail is always attended, so QSA equals dense causal attention bit for bit. */
             const int64_t exact_to = budget + ratio - 1;
-            /* THERE IS NO CAP ON `--max-ctx` HERE. Prefill selects per query exactly as decode
-             * does (arch/common/rad_qsa.h, docs/QSA.md), so above the bound this runs the model's
-             * own attention rather than a denser stand-in -- and there is no force-dense switch,
-             * because above the bound the dense path is NOT the trained attention and such a
-             * switch would make a server quietly serve a different model. */
+            /* The context bound is not capped: prefill selects per query exactly as decode does
+             * (arch/common/rad_qsa.h, docs/QSA.md). There is deliberately no force-dense switch,
+             * since above the bound dense attention is not the trained model. */
             if (g.max_ctx > exact_to)
-                rad_note(b, "QSA: sparse past %lld tokens of context -- %lld blocks of %lld a "
-                            "query, selected per query at prefill and at decode. At or below that "
-                            "the selection is every visible block and the engine issues the "
-                            "cheaper dense attention, which is the same answer to the bit.",
+                rad_note(b, "QSA: sparse past %lld tokens of context, %lld blocks of %lld per "
+                            "query at prefill and decode; at or below that the engine issues the "
+                            "bit-identical dense attention",
                          (long long)exact_to, (long long)(budget / ratio), (long long)ratio);
             else
-                rad_note(b, "QSA: dense attention is EXACT to %lld tokens of context and "
-                            "--max-ctx is %lld, so the indexer selects every visible block "
-                            "and changes nothing.", (long long)exact_to, (long long)g.max_ctx);
+                rad_note(b, "QSA: dense attention is exact to %lld tokens of context and "
+                            "--max-model-len is %lld, so the indexer selects every visible block",
+                         (long long)exact_to, (long long)g.max_ctx);
         }
     }
 
@@ -735,7 +642,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
              (long long)m.hccfg.hc, (long long)g.n_embd, (long long)HN,
              (long long)m.hccfg.lowrank, (long long)(2 * g.n_layer));
 
-    /* ---- the KV groups. Same three as qwen35_fp8 and for the same reasons. */
+    /* ---- the KV groups: the same three as qwen35_fp8. */
     {
         RadKVGroupDecl fd{};
         fd.kind      = RAD_KV_FULL;
@@ -762,18 +669,16 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
         m.kv_conv = rad_decl_kv_group(b, nm.f("kv_gdn_conv"), &cd);
         if (!m.kv_full || !m.kv_state || !m.kv_conv) return RAD_E_INVAL;
 
-        /* ---- the QSA indexer's TAIL, which is state and not a buffer.
+        /* ---- the QSA indexer's tail, which is state, not a buffer.
          *
-         * It carries an unfinished block's raw index keys across steps, so it has to be indexed
-         * by the SEQUENCE and by the LAYER -- and a buffer can express neither. The batch row is
-         * step-local and the keys are per-layer; arch/common/rad_qsa.h's Wire is the full
-         * argument. As a linear group the engine keeps a slot stable for the life of a sequence,
-         * zeroes it when it hands one out, and saves and restores it with the rest of the linear
-         * state when the prefix cache checkpoints -- which is also the only thing that makes a
-         * resume onto a half-built block read anything defined.
+         * It carries an unfinished block's raw index keys across steps, so it is indexed by
+         * sequence and layer, which a step-local buffer cannot express (arch/common/rad_qsa.h,
+         * Wire). As a linear group the engine keeps a slot stable for the sequence's life, zeroes
+         * it on allocation, and saves and restores it with the linear state on prefix-cache
+         * checkpoints, so a resume onto a half-built block reads defined data.
          *
-         * `n_head_kv` 1 and `state_dim` {ring, head_dim}: one state is `ring` raw keys, a few
-         * kilobytes a layer a sequence. */
+         * `n_head_kv` 1 and `state_dim` {ring, head_dim}: `ring` raw keys, a few KiB per layer per
+         * sequence. */
         if (m.qsacfg.heads > 0 && m.qsacfg.head_dim > 0 && m.qsacfg.ring > 0) {
             RadKVGroupDecl td{};
             td.kind         = RAD_KV_LINEAR;
@@ -786,11 +691,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
         }
     }
 
-    /* ---- THE TRUNK'S STORED FORMAT, read off the first delta-net layer's input projection the way
-     * the experts' is read off one expert: the activation buffers below carry an int8 code pair
-     * only when the trunk's linears are int8 (LinearFP8::i8), so it has to be known before they
-     * are declared. The probe maps that weight through the layer's own LinearFP8, which then does
-     * not map it again. */
+    /* ---- the trunk's stored format, read from the first delta-net layer's input projection as
+     * the experts' is from one expert. The activation buffers below carry an int8 code pair only
+     * when the trunk's linears are int8 (LinearFP8::i8), so it must be known first. The probe maps
+     * the weight through the layer's own LinearFP8, which then does not map it again. */
     m.layers.resize((size_t)g.n_layer);
     {
         const char* pre0 = "model.language_model.layers";
@@ -815,11 +719,35 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
 
     m.b_h   = decl_b(b, nm.f("h_wide"), g.act_dtype, {T, HN});
     m.a_x.x = decl_b(b, nm.f("x"),      g.act_dtype, {T, g.n_embd});
+    if (ctx->shape_probe) {
+        m.span_on = g_model[ctx->rank].span_on;
+        m.pipe_on = g_model[ctx->rank].pipe_on;
+    } else {
+        m.span_on = ctx->max_mixed_tok > 0 && ctx->max_mixed_tok < g.max_tok &&
+                    g.max_tok > m.moecfg.rows;
+        /* Only where the blocks issue their own all-reduce at a step wider than a pass: at two
+         * ranks the gated residual's fused write takes every step's (ar_exact_write_rows), so such
+         * a step runs serially. */
+        m.pipe_on = m.span_on && g.world > 1 && ar_exact_write_rows(g) < g.max_tok;
+    }
+    /* The pipelined step's all-reduces run on the second lane, in place over `x`, so it is the one
+     * buffer that lane touches; it is live over the whole program anyway. */
+    if (m.pipe_on) RAD_ARCH_TRY(rad_buf_concurrent(b, m.a_x.x));
+    /* A transient although only its last entry changes per step: a persistent buffer sits in the
+     * fixed region under every transient, and one more alignment unit there moves every
+     * activation by 256 bytes, which on Flash-Next at four ranks slows the MoE gather by 73 % and
+     * a prefill by 3 %. Every step that reads it rewrites it (pipe_bounds). */
+    if (m.span_on)
+        m.b_pipe_cu = decl_b(b, nm.f("pipe_cu"), RAD_I32, {4});
+    /* Under a span every connection reads a step wider than a pass a pass at a time
+     * (HyperConn::read_pieces, and the pipelined step's own reads), so the reads are declared no
+     * wider than a pass and their scratch is sized for that band. */
+    if (m.span_on) m.hccfg.read_rows = m.moecfg.rows;
     RAD_ARCH_TRY(m.a_x.declare_qs(b, nm, g, "x", g.n_embd, 0, m.trunk_i8));
-    /* THE CONNECTIONS WRITE THE INT8 CODES THEMSELVES when every reader of their codes is an int8
-     * linear: the trunk's are, and the routed experts read the rotated twin (or the bf16 plane),
-     * never these. Experts that read the plain E4M3 codes keep them, and the int8 linears then
-     * quantise for themselves. */
+    /* The connections write int8 codes themselves when every reader of their codes is an int8
+     * linear: the trunk's are, and the routed experts then read the rotated copy or the bf16
+     * plane. When experts read the plain E4M3 codes, the connections keep those and the int8
+     * linears quantise for themselves. */
     m.hccfg.codes_i8 = (m.trunk_i8 && (m.moecfg.expert_rot || m.moecfg.expert_bf16)) ? 1 : 0;
     m.a_x.q8_fed     = m.hccfg.codes_i8 != 0;
     m.b_inj = decl_b(b, nm.f("hc_inj"), g.act_dtype, {T, m.hccfg.hc});
@@ -834,9 +762,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     m.a_attn.q8_fed = m.trunk_i8;
     /* The bf16 gate's own plane (AttnGatedFP8::Wire::gate); the fp8 path fuses it away. */
     if (g.w_bf16) m.b_gate = decl_b(b, nm.f("attn_gate"), g.act_dtype, {T, q_dim});
-    /* THE QSA INDEXER'S TWO PLANES, shared by every full-attention layer the way `attn_out` is.
-     * Declared only when the checkpoint carries an indexer, so a container without one allocates
-     * nothing and the layer's declare() is a no-op. */
+    /* The QSA indexer's planes, shared by every full-attention layer like `attn_out`. Declared
+     * only when the checkpoint carries an indexer; otherwise the layer's declare() is a no-op. */
     if (m.qsacfg.heads > 0 && m.qsacfg.head_dim > 0) {
         m.qsaw.qk = decl_b(b, nm.f("qsa_qk"), g.act_dtype,
                            { g.max_tok, (m.qsacfg.heads + 1) * m.qsacfg.head_dim });
@@ -849,23 +776,29 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
         m.qsaw.bpos  = g.rope_mc ? decl_b(b, nm.f("qsa_bpos"), RAD_I32, { wk, 3 })
                                  : decl_b(b, nm.f("qsa_bpos"), RAD_I32, { wk });
         m.qsaw.nc    = decl_b(b, nm.f("qsa_nc"),    RAD_I32, { g.max_seqs });
-        /* ONE ROW A QUERY, not one a sequence -- QSA Stage B, arch/common/rad_qsa.h. The score
-         * plane is the only buffer in this model whose size is a PRODUCT of the two deployment
-         * bounds, so it is refused here by name rather than discovered as an allocation failure
-         * halfway through the arena: 2 GiB is already an absurd answer and the message says which
-         * two flags produced it. */
-        const int64_t sc_elems = g.max_tok * m.qsacfg.max_blocks;
+        /* A pass tall under a span whose shared steps fit in a pass (RadBuildCtx::
+         * max_mixed_tok): a wider step is one sequence and scores and selects in windows of a
+         * pass (QsaIndexer::step, with the bounds in b_pipe_cu). The plane is the largest buffer
+         * the span would otherwise grow, max_ctx / ratio floats a query row (512 MiB more at 4096
+         * rows and 256K of context). */
+        const int64_t qsa_rows = (m.span_on && ctx->max_mixed_tok <= m.moecfg.rows)
+                                     ? m.moecfg.rows : g.max_tok;
+        m.qsacfg.plane_rows = qsa_rows < g.max_tok ? qsa_rows : 0;
+        /* One row per query, not per sequence (arch/common/rad_qsa.h). The score plane is the
+         * only buffer whose size is the product of two deployment bounds, so an oversized one is
+         * refused here, naming the two flags, rather than failing later as an allocation. */
+        const int64_t sc_elems = qsa_rows * m.qsacfg.max_blocks;
         if (sc_elems > (int64_t)512 * 1024 * 1024) {
             fprintf(stderr,
-                "radiance: qwen4exp: the QSA score plane would be %lld MiB -- "
-                "--max-num-batched-tokens %lld by --max-ctx %lld / compress ratio %lld. "
+                "radiance: qwen4exp: the QSA score plane would be %lld MiB -- %lld rows "
+                "(--max-num-batched-tokens %lld) by --max-model-len %lld / compress ratio %lld. "
                 "Lower either.\n",
-                (long long)(sc_elems * 4 / (1024 * 1024)), (long long)g.max_tok,
-                (long long)g.max_ctx, (long long)m.qsacfg.ratio);
+                (long long)(sc_elems * 4 / (1024 * 1024)), (long long)qsa_rows,
+                (long long)g.max_tok, (long long)g.max_ctx, (long long)m.qsacfg.ratio);
             return RAD_E_UNSUPPORTED;
         }
         m.qsaw.score = decl_b(b, nm.f("qsa_score"), RAD_F32,
-                              { g.max_tok, m.qsacfg.max_blocks });
+                              { qsa_rows, m.qsacfg.max_blocks });
         m.qsaw.sel   = decl_b(b, nm.f("qsa_sel"),   RAD_I32,
                               { g.max_tok, m.qsacfg.topk + 1 });
         m.qsaw.nsel  = decl_b(b, nm.f("qsa_nsel"),  RAD_I32, { g.max_tok });
@@ -882,44 +815,37 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     m.b_gq   = decl_b(b, nm.f("gdn_q"),    g.act_dtype, {T, m.gcfg.n_head_k, m.gcfg.head_k});
     m.b_gk   = decl_b(b, nm.f("gdn_k"),    g.act_dtype, {T, m.gcfg.n_head_k, m.gcfg.head_k});
     m.b_gv   = decl_b(b, nm.f("gdn_v"),    g.act_dtype, {T, m.gcfg.n_head_v, m.gcfg.head_v});
-    /* F32 AND NOT THE ACTIVATION DTYPE, both of them, and the kernels say so rather than tolerate
-     * it: `gdn_conv_prep` ends `R4D_DT(g, RAD_F32); R4D_DT(beta, RAD_F32)`. The log decay is a
-     * cumulative sum that the chunked scan exponentiates differences of, and beta is its
-     * companion; bf16's eight mantissa bits are not enough for either. The refusal is
-     * "dtype this kernel does not serve" at the first step, which is the right failure and not an
-     * obvious one to read. */
+    /* Both f32, not the activation dtype; `gdn_conv_prep` requires it and otherwise fails the
+     * first step with "dtype this kernel does not serve". The log decay is a cumulative sum whose
+     * differences the chunked scan exponentiates, and bf16's eight mantissa bits are not enough for
+     * it or for beta. */
     m.b_gdec = decl_b(b, nm.f("gdn_gdec"), RAD_F32,  {T, m.gcfg.n_head_v});
     m.b_beta = decl_b(b, nm.f("gdn_beta"), RAD_F32,  {T, m.gcfg.n_head_v});
     m.b_kkt  = decl_b(b, nm.f("gdn_kkt"),  RAD_BF16, {T, m.gcfg.n_head_v, m.gcfg.chunk});
     m.a_go.x = decl_b(b, nm.f("gdn_o"),    g.act_dtype, {T, m.gcfg.n_head_v, m.gcfg.head_v});
     RAD_ARCH_TRY(m.a_go.declare_qs(b, nm, g, "gdn_o", v_dim, 0, m.trunk_i8));
-    /* So does the delta net's output epilogue, and its prefill quantiser is the int8 one. */
+    /* The delta net's output epilogue also writes its int8 codes; its prefill quantiser is the
+     * int8 one. */
     m.a_go.q8_fed = m.trunk_i8;
 
-    /* THE MODEL'S expert count, not this rank's: the router is replicated under expert
-     * parallelism and scores every expert. */
+    /* The model's expert count, not this rank's: the router is replicated and scores every
+     * expert. */
     m.b_rlogits = decl_b(b, nm.f("moe_logits"), g.act_dtype, {T, m.moecfg.n_expert_all});
     m.b_eids    = decl_b(b, nm.f("moe_ids"),    RAD_I32,     {T, m.moecfg.top_k});
     m.b_ew      = decl_b(b, nm.f("moe_ew"),     g.act_dtype, {T, m.moecfg.top_k});
     m.b_eoff    = decl_b(b, nm.f("moe_eoff"),   RAD_I32,     {m.moecfg.n_expert + 1});
-    /* PERSIST, NOT TRANSIENT, and it is the one buffer here that has to be. `moe_scatter` writes
-     * the per-expert histogram and NO DECLARED OP READS IT -- the reader is rad_route_report,
-     * which is a handoff and not an op -- so liveness analysis sees it die the instant it is
-     * written and is free to alias its storage with anything later in the step. Declared
-     * transient, a wide enough prefill chunk gives the planner something to lay over it and the
-     * histogram comes back holding values a sum of placements cannot be -- negative counts. A
-     * small step may miss it entirely, so this is not a fault a short run reveals.
-     *
-     * The buffer is one int32 an expert. */
+    /* PERSIST, not transient. `moe_scatter` writes the per-expert histogram and no declared op
+     * reads it (rad_route_report is a handoff, not an op), so as a transient liveness would let a
+     * later buffer alias it, and a wide prefill chunk would corrupt the counts (even negative).
+     * One int32 per expert. */
     m.b_ecnt    = decl_b(b, nm.f("moe_ecnt"),   RAD_I32,     {m.moecfg.n_expert},
                          RAD_BUF_PERSIST);
     m.b_sorted  = decl_b(b, nm.f("moe_sorted"), RAD_I32,     {ER});
     m.b_egu     = decl_b(b, nm.f("moe_egu"),    g.act_dtype, {ER, 2 * m.moecfg.n_ff_exp});
     m.a_eff.x   = decl_b(b, nm.f("moe_eff"),    g.act_dtype, {ER, m.moecfg.n_ff_exp});
-    /* ER ROWS, NOT max_tok: this is an EXPERT plane, one row per (token, slot). Taking
-     * declare_qs's default declares it `top_k` times too short, and the gated quantiser then
-     * writes that many times past the end of it -- see ActFP8::declare_qs, which is where the
-     * guard and the argument live. */
+    /* ER rows, not max_tok: an expert plane has one row per (token, slot). declare_qs's default
+     * would make it `top_k` times too short and the gated quantiser would overrun it (see
+     * ActFP8::declare_qs). */
     RAD_ARCH_TRY(m.a_eff.declare_qs(b, nm, g, "moe_eff", m.moecfg.n_ff_exp, ER));
     if (m.moecfg.expert_rot)
         RAD_ARCH_TRY(m.a_hr.declare_qs(b, nm, g, "moe_hr", g.n_embd));
@@ -930,7 +856,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
         m.a_sff.x = decl_b(b, nm.f("moe_sff"),   g.act_dtype, {T, m.moecfg.n_ff_shared});
         RAD_ARCH_TRY(m.a_sff.declare_qs(b, nm, g, "moe_sff", m.moecfg.n_ff_shared, 0,
                                          m.trunk_i8));
-        /* And the shared expert's gated quantiser in front of its int8 down projection. */
+        /* The shared expert's gated quantiser in front of its int8 down projection writes its codes
+     * too. */
         m.a_sff.q8_fed = m.trunk_i8;
         m.b_sout  = decl_b(b, nm.f("moe_sout"),  g.act_dtype, {T, g.n_embd});
         m.b_sgate = decl_b(b, nm.f("moe_sgate"), g.act_dtype, {T, 1});
@@ -940,15 +867,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     m.b_logits = decl_b(b, nm.f("logits"), RAD_F32,     {g.max_logit_rows, g.n_vocab});
     RAD_ARCH_TRY(rad_declare_logits(b, m.b_logits));
 
-    /* ---- the vocabulary edges, both row-sharded as qwen35_fp8 has them. `lm_head.weight` is
-     * present in this checkpoint (tie_word_embeddings is false), but the alternative spelling
-     * costs nothing and a smaller member of the family may tie them.
+    /* ---- the vocabulary edges, both row-sharded as in qwen35_fp8. This checkpoint ships
+     * `lm_head.weight` (tie_word_embeddings is false); the alternative source covers a smaller
+     * family member that ties them.
      *
-     * THE HEAD IS DECLARED OVER EVERY PLANE IT HAS, at the codes' dtype: bf16 as the checkpoint
-     * ships it, block fp8 where a recipe makes it so. Which `logits_gemm` kernel serves it is
-     * then the selector's -- a kernel whose layout does not read the head's encoding is not a
-     * candidate -- so one declaration serves both. The maps come first: they are how the model
-     * is asked what the head is. */
+     * The head is declared over all its planes at the codes' dtype (bf16 as shipped, block fp8
+     * where a recipe makes it so); the selector then picks a `logits_gemm` kernel whose layout
+     * reads that encoding. The name maps come first, since they are how the head is queried. */
     RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"),
                           nm.ckpt("model.language_model.embed_tokens.weight")));
     RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
@@ -959,10 +884,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                          weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16),
                          {g.n_vocab, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
     if (!m.w_tok || !m.w_lm_head) return RAD_E_INVAL;
-    /* THE RANK'S ROWS, STATED: a vocabulary that does not divide by the world (248320 at three
-     * ranks) is split by rad_arch.h's rule -- ceil to a 128-row block, last rank short -- and that
-     * is a span, not the even share the core would otherwise cut. Harmless where it does divide
-     * (the span IS the even share). */
+    /* The rank's rows, stated explicitly: a vocabulary the world does not divide (248320 at three
+     * ranks) is split by rad_arch.h's rule (ceil to a 128-row block, last rank short), not the
+     * core's even share. Where it divides, the span equals the even share. */
     if (g.world > 1) {
         RAD_ARCH_TRY(rad_weight_shard_span(b, m.w_tok,     g.vocab_off, g.vocab_off + g.n_vocab));
         RAD_ARCH_TRY(rad_weight_shard_span(b, m.w_lm_head, g.vocab_off, g.vocab_off + g.n_vocab));
@@ -974,11 +898,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                                   RAD_INT("vocab_offset", g.vocab_off)),
                        RAD_WEIGHTS(m.w_tok)),
                    {}, {m.a_x.x});
-    /* THE ENCODER'S ROWS, over the lookup and before its reduction (MediaRows says why). */
+    /* The encoder's rows overwrite the lookup before its reduction (see MediaRows). */
     m.media = VisionTower::present(meta) && ctx->max_enc_patches > 0;
     if (m.media) RAD_ARCH_TRY(m.mrows.declare(b, T, g.n_embd, m.a_x.x));
-    /* EXACT unconditionally: every other collective here sums partial products, this one sums
-     * DISJOINT rows -- a token's embedding comes from exactly one rank. qwen35_fp8 says the same. */
+    /* Always exact: this sums disjoint rows, a token's embedding coming from exactly one rank. */
     if (g.world > 1)
         m.op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
                               RAD_PARAMS(RAD_INT("world_size", g.world),
@@ -987,19 +910,16 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                               RAD_NOWEIGHTS),
                           {m.a_x.x}, {m.a_x.x});
 
-    /* THE STREAM'S FIRST VALUE: hc identical copies of the embedding. */
+    /* The stream's initial value: hc identical copies of the embedding. */
     RAD_ARCH_TRY(m.enter.declare(b, g, m.hccfg.hc, m.a_x.x, m.b_h));
 
     /* ---- the layers.
      *
-     * DECLARATION ORDER IS WHAT THE BUFFER PLANNER'S LIVENESS IS: a transient's lifetime is
-     * [first definition, last use] over OP INDICES in this order, and two transients whose ranges
-     * are disjoint MAY share bytes (core/build/rad_bufplan.cpp). Every buffer above is shared by
-     * every layer, so the order below has to be the order step() issues in -- read, block, write,
-     * read, block, write -- and it is. A connection declared out of that order would make a false
-     * statement about liveness and the planner would alias two buffers that are both live inside
-     * one step; the symptom is fluent output with one arm of the model reading the other's
-     * leftovers, which nothing downstream flags.
+     * Declaration order is the buffer planner's liveness: a transient lives over [first
+     * definition, last use] in op indices, and transients with disjoint ranges may share bytes
+     * (core/build/rad_bufplan.cpp). The buffers above are shared by every layer, so the order
+     * below must match step()'s issue order (read, block, write, ...). Declaring a connection out
+     * of order would alias buffers live in the same step, silently corrupting the output.
      */
     m.op_rope_cs = rw(b, decl_rotary(b, g, "rope_table",
                          RAD_PARAMS(RAD_RANGE("M", 1, qk_fuse_rows(g)),
@@ -1013,12 +933,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     aw.x = m.b_h; aw.h = m.a_x; aw.qg = m.b_qg; aw.k = m.b_k; aw.v = m.b_v;
     aw.q = m.b_q; aw.attn = m.a_attn; aw.gate = m.b_gate;
     aw.cos_sin = m.op_rope_cs ? m.b_rope_cs : 0;
-    /* AND THE INDEXER READS THE SAME PLANE. Its rotation is at `m.n_rot`, `g.theta` and
-     * `g.rope_scale` -- the three the table was built from -- so the rows this step's positions
-     * name are already written, and the twelve trunk layers plus the head's four passes stop
-     * issuing `heads` norms and a rope each. Set HERE rather than where `m.qsaw`'s buffers are
-     * declared because the table is declared after them, and `tw.qsa = m.qsaw` below copies this
-     * wire to the MTP head, which is how the head's passes get it too. */
+    /* The indexer reads the same rope table: its rotation uses `m.n_rot`, `g.theta` and
+     * `g.rope_scale`, as the table does, which saves the trunk layers and the head's passes a norm
+     * and rope each. Set here because the table is declared after `m.qsaw`'s buffers;
+     * `tw.qsa = m.qsaw` below passes it on to the MTP head. */
     m.qsaw.cos_sin = aw.cos_sin;
 
     GdnFP8::Wire gw{};
@@ -1038,18 +956,19 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
 
     m.layers.resize((size_t)g.n_layer);
     const char* pre = "model.language_model.layers";
+    /* The pipelined step's all-reduces run beside the other piece's work, so each block declares
+     * its collective a second time at `overlap` 1, for the rows that leave the CUs to that work
+     * (the lane rows of libr4d/r4d_rows.cpp). */
+    const int pipe_overlap = m.pipe_on ? 1 : 0;
     for (int64_t l = 0; l < g.n_layer; ++l) {
         Layer& lay = m.layers[(size_t)l];
         lay.full = is_full_attention(l, interval) ? 1 : 0;
+        lay.attn.ar_overlap = lay.gdn.ar_overlap = lay.mlp.ar_overlap = pipe_overlap;
 
-        /* PLE COMES FIRST, BEFORE THE ATTENTION CONNECTION READS THE STREAM, because the reference
-         * adds it into `hidden_states` at the top of the decoder layer's forward -- so the gated
-         * residual that follows normalises a stream the n-gram features are already in.
-         *
-         * DECLARATION ORDER IS THE BUFFER PLANNER'S LIVENESS, so this has to be here and not
-         * hoisted out of the loop: every buffer the block owns is live from here to its `add`, and
-         * declaring it earlier would overstate that and cost the planner a sharing it could have
-         * had. The same rule the connections below follow. */
+        /* PLE comes first, before the attention connection reads the stream: the reference adds
+         * it into `hidden_states` at the top of the decoder layer, so the following gated residual
+         * normalises a stream that already includes the n-gram features. It is declared here, not
+         * hoisted, so its buffers' liveness starts where they are used. */
         if (l == m.ple_layer) {
             PleLayer::Config pc{};
             pc.hc         = m.hccfg.hc;
@@ -1062,8 +981,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
             pc.shards     = meta_int2(meta, "qwen4exp.split_ngram_parts", "split_ngram_parts", 0);
             pc.conv_width = meta_int2(meta, "qwen4exp.ple_conv_kernel_size",
                                       "ple_conv_kernel_size", 0);
-            /* THE DILATION IS THE N-GRAM SIZE. `conv_dilation = config.ngram_size` in the
-             * reference's PLE layer -- not a separate key, and not 1. */
+            /* The dilation is the n-gram size (`conv_dilation = config.ngram_size` in the
+             * reference), not a separate key and not 1. */
             pc.dilation   = pc.ngram;
             pc.rows       = ngram_table_rows(
                 meta_int2(meta, "qwen4exp.ngram_vocab_size_base", "ngram_vocab_size_base", 0),
@@ -1104,10 +1023,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
         RAD_ARCH_TRY(lay.hc_mix.declare(b, nm, g, nm.f("blk.%lld.attn_hc", (long long)l),
                                         m.hccfg, hw, mixs));
 
-        /* `Src::norm = nullptr` is the blocks' "the input is already normed and quantised" mode,
-         * and `add_out = false` stops them adding into the stream -- the write half of the
-         * connection does that, with the four gains the read produced. `fold` and `ar_in` are both
-         * off for the same reason: both fuse into a norm this block does not have. */
+        /* `Src::norm = nullptr` is the blocks' "input already normed and quantised" mode, and
+         * `add_out = false` stops them adding into the stream; the connection's write half does
+         * that with the four gains the read produced. `fold` and `ar_in` are off because both fuse
+         * into a norm these blocks do not have. */
         if (lay.full) {
             AttnGatedFP8::Src as{};
             as.qg     = nm.ckpt("%s.%lld.self_attn.q_proj.weight", pre, (long long)l);
@@ -1116,45 +1035,38 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
             as.q_norm = nm.ckpt("%s.%lld.self_attn.q_norm.weight", pre, (long long)l);
             as.k_norm = nm.ckpt("%s.%lld.self_attn.k_norm.weight", pre, (long long)l);
             as.o      = nm.ckpt("%s.%lld.self_attn.o_proj.weight", pre, (long long)l);
-            /* THE KV PAGE IS THE QSA COMPRESS BLOCK when that is asked for. A page of 4 makes the
-             * indexer's selected set a paged block table rather than a new attention kernel
-             * (docs/QSA.md); the attention kernel's rows have to declare the same 4 or nothing
-             * resolves, which is what keeps this honest.
-             *
-             * A page size is pure storage, so the only thing it can move is the block-table walk:
-             * a page of 4 and a page of 16 cost the same at long context and produce identical
-             * text. */
+            /* The KV page is the QSA compress block, so the indexer's selection is a paged block
+             * table rather than a new attention kernel (docs/QSA.md); the attention rows must
+             * declare the same 4 or nothing resolves. Page size only affects the block-table walk:
+             * pages of 4 and 16 cost the same at long context and give identical text. */
             lay.attn.kv_block = 4;
-            /* THE SELECTION IS SET BEFORE THE ATTENTION IS DECLARED, and the order is
-             * load-bearing: `attn_paged` declares `sel` and `seqused` as READS, and a read
-             * declared after the op is not a read at all -- see rad_block_attn_gated_fp8.h. The
-             * indexer itself is declared after the attention block (its ops have to sit where the
-             * sparse attention reads them), which is why the two halves of this are apart.
+            /* The selection must be set before the attention is declared: `attn_paged` declares
+             * `sel` and `seqused` as reads, and a read declared after the op does not count
+             * (rad_block_attn_gated_fp8.h). The indexer itself is declared after the attention
+             * block, where the sparse attention reads its ops.
              *
-             * Below the indexer's budget the selection is every visible block, so the sparse
-             * and dense paths must produce identical text and a difference is a defect rather
-             * than a model change. */
+             * Below the indexer's budget the selection is every visible block, so sparse and dense
+             * paths must give identical text; any difference is a defect. */
             if (m.qsaw.qk) {
                 lay.attn.qsa_sel      = m.qsaw.sel;
                 lay.attn.qsa_sequ     = m.qsaw.sequ;
                 lay.attn.qsa_topk     = m.qsacfg.topk;
-                /* THE BOUND, so the attention keeps the cheaper dense issue where the two paths
-                 * are the same answer. Decode ignores it and always takes the sparse path, which
-                 * is what keeps that path exercised on every step this engine runs. */
+                /* The exactness bound, below which prefill issues the cheaper dense attention.
+                 * Decode ignores it and always takes the sparse path, keeping that path exercised
+                 * on every step. */
                 lay.attn.qsa_exact_to = m.qsacfg.budget + m.qsacfg.ratio - 1;
             }
             RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_full));
-            /* AN ATTENTION-ZERO RANK KEEPS NO ATTENTION CACHE. Its block is a fill of zeros
-             * (rad_block_attn_gated_fp8.h) and never stores or reads a key; the indexer below
-             * reads only the group's block table, which every rank shares. Once per model: the
-             * group is one and the call is idempotent, but the first layer is the honest place. */
+            /* An attention-zero rank keeps no attention cache: its block is a fill of zeros
+             * (rad_block_attn_gated_fp8.h), and the indexer reads only the shared block table. The
+             * call is idempotent. */
             if (g.attn_zero && m.kv_full) RAD_ARCH_TRY(rad_kv_group_zero(b, m.kv_full));
             lay.attn.ar_out_take = lay.hc_mix.ar_take();
             RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, m.kv_full, m.n_rot, aw, as,
                                           false, false, kArNone, lay.hc_mix.op_ar_write != 0));
-            /* THE INDEXER, after the attention block so its ops sit where the sparse attention
-             * reads them. It reads the same normed fp8 input the projections do; arch/common/
-             * rad_qsa.h is the declaration side of docs/QSA.md. */
+            /* The indexer, after the attention block so its ops sit where the sparse attention
+             * reads them. It reads the same normed fp8 input as the projections
+             * (arch/common/rad_qsa.h, docs/QSA.md). */
             if (m.qsaw.qk) {
                 QsaIndexer::Config qc = m.qsacfg;
                 qc.mode    = lay.attn.mode;
@@ -1235,9 +1147,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     /* Each routed layer predicts the next one's experts at its router input (MoeFP8::xp_next). */
     for (size_t l = 0; l + 1 < m.layers.size(); ++l) m.layers[l].mlp.xp_next = &m.layers[l + 1].mlp;
 
-    /* ---- the 97th connection. No write half, no fp8 twin: it produces the one hidden state the
-     * lm_head reads, as a bf16 input. Its `hc_norm` is what a pre-norm model calls the
-     * final norm -- this checkpoint has no `model.language_model.norm.weight` at all. */
+    /* ---- the 97th connection: no write half, no fp8 copy. It produces the bf16 hidden state the
+     * lm_head reads; its `hc_norm` takes the place of a final norm (the checkpoint has no
+     * `model.language_model.norm.weight`). */
     {
         HyperConn::Config mc = m.hccfg;
         mc.inject = 0;
@@ -1268,35 +1180,32 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
 
     /* ---- the multi-token-prediction head (arch/common/rad_block_mtp_hc.h).
      *
-     * AFTER op_logits, and that is load-bearing rather than tidy. Declaration order IS the buffer
-     * planner's liveness, so a drafter declared before the trunk's tail ops would make the planner
-     * read those ops as living AFTER the drafter is done -- and share a trunk buffer with one of
-     * the head's. The symptom is fluent output with acceptance EXACTLY zero; arch/qwen35_fp8
-     * declares its own drafter in this same position for the same reason.
+     * Declared after op_logits; do not move it. Declaration order is the planner's liveness, and a
+     * drafter declared before the trunk's tail ops would share a trunk buffer with one of the
+     * head's, giving correct output with zero acceptance.
      *
-     * DECLARED ONLY WHEN THE DEPLOYMENT SPECULATES. `mtp_num_hidden_layers` says the checkpoint
-     * carries a head and `max_spec` says the engine intends to use one; at max_spec 0 the weights
-     * stay off the card and the container still carries them, because rad-convert declares at a
-     * non-zero max_spec on purpose. */
+     * Declared only when the checkpoint carries a head and the deployment speculates; at
+     * max_spec 0 the weights stay off the card (the container still carries them, since
+     * rad-convert declares at a non-zero max_spec). */
     const int64_t nextn = meta_int2(meta, "qwen4exp.mtp_num_hidden_layers",
                                     "mtp_num_hidden_layers", 0);
     if (nextn > 0 && g.max_spec > 0) {
         const char* mpre = "mtp";
-        /* AT max_tok, NOT max_logit_rows. A draft round is one row a sequence, but the history
-         * pass that fills the head's own K and V is one row a TOKEN over a whole prefill chunk. */
+        /* Sized at max_tok, not max_logit_rows: the history pass that fills the head's own K and V
+         * has one row per token over a whole prefill chunk. */
         m.b_mtp_hin  = decl_b(b, nm.f("mtp_hin"),  g.act_dtype, {T, HN});
         m.b_mtp_hw   = decl_b(b, nm.f("mtp_hw"),   g.act_dtype, {T, HN});
         m.b_mtp_e    = decl_b(b, nm.f("mtp_e"),    g.act_dtype, {T, g.n_embd});
         m.b_mtp_hout = decl_b(b, nm.f("mtp_hout"), g.act_dtype, {g.max_logit_rows, g.n_embd});
-        /* THE 2-BIT DRAFT HEAD, when the model holds one: asked once, here, because the answer
-         * declares the head's buffers and the block reads it back from them. */
+        /* The 2-bit draft head, when the model holds one: asked once here, since the answer
+         * decides the head's buffers and the block reads it back from them. */
         if (mtp_draft_head_q2(b, MtpHcBlock::head_name(nm), nm.ckpt("lm_head.weight"))) {
             const int64_t dmpad = ((g.max_logit_rows + 15) / 16) * 16;
             m.b_mtp_dq   = decl_b(b, nm.f("mtp_dq"),   RAD_I8,  {g.max_logit_rows, g.n_embd});
             m.b_mtp_ds   = decl_b(b, nm.f("mtp_ds"),   RAD_F32, {g.max_logit_rows, 1});
             m.b_mtp_dsum = decl_b(b, nm.f("mtp_dsum"), RAD_F32, {g.n_embd / 128, dmpad});
-            /* AT THIS RANK'S ROWS, not the model's: the 2-bit head is vocab-parallel and the
-             * merge below puts the halves back together. rad_arch.h owns the rule. */
+            /* This rank's rows, not the model's: the 2-bit head is vocab-parallel and the merge
+             * reassembles it (rad_arch.h). */
             m.b_mtp_dlog = decl_b(b, nm.f("mtp_dlog"), g.act_dtype,
                                   {g.max_logit_rows, vocab_head_rows(g)});
             if (vocab_head_sharded(g)) {
@@ -1305,12 +1214,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                 m.b_mtp_dgath = decl_b(b, nm.f("mtp_dgath"), RAD_F32,
                                        {g.max_logit_rows, (int64_t)g.world * kDraftTopR, 2});
             }
-            /* NAMED and declared, because the engine reads the proposal straight out of it: a
-             * draft round's token comes from row_topk and never through the sampler. */
-            /* kDraftTopR COLUMNS, and a draft reads one. The rest are the coarse head's other
-             * candidates, which `logit_rerank` scores before column 0 is taken, and their width
-             * is also what gives the vocab-parallel all-gather a 16-byte row; rad_block_mtp_hc.h's
-             * kDraftTopR says why. */
+            /* The proposal: a draft round's token comes from row_topk, never the sampler.
+             * kDraftTopR columns, of which a draft reads column 0; the rest are the coarse head's
+             * other candidates, which `logit_rerank` scores first, and the width also gives the
+             * vocab-parallel all-gather a 16-byte row (rad_block_mtp_hc.h, kDraftTopR). */
             m.b_mtp_didx = decl_b(b, nm.f("mtp_didx"), RAD_I32, {g.max_logit_rows, kDraftTopR});
             m.b_mtp_dval = decl_b(b, nm.f("mtp_dval"), RAD_F32, {g.max_logit_rows, kDraftTopR});
         }
@@ -1322,17 +1229,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
         tw.dq   = m.b_mtp_dq;   tw.ds = m.b_mtp_ds;    tw.dsum = m.b_mtp_dsum;
         tw.dlog = m.b_mtp_dlog; tw.didx = m.b_mtp_didx; tw.dval = m.b_mtp_dval;
         tw.dpair = m.b_mtp_dpair; tw.dgath = m.b_mtp_dgath;
-        /* The layer's working set is the TRUNK's: every one of these is dead by the time a draft
-         * round runs, and a second set would be 150 MiB of activation planes for one layer. Only
-         * the wide stream and the carry are the head's own, because those must survive the round
-         * that produced them. */
+        /* The head reuses the trunk's working buffers, all dead by the time a draft round runs (a
+         * second set would be 150 MiB). Only the wide stream and the carry are its own, since
+         * they must survive the round that produced them. */
         tw.attn = aw; tw.attn.x = m.b_mtp_hw;
         tw.mlp  = mw; tw.mlp.x  = m.b_mtp_hw;
-        /* Everything in the wire is within-step scratch and a draft round is its own step, so the
-         * head shares all of it. The QSA tail is the exception and it is not in the wire at all:
-         * a head leaving its own index keys where a trunk layer pools them is a layer pooling
-         * another layer's keys, so the tail is `kv_qsa_tail` -- per sequence and per layer -- and
-         * declare() binds this layer to it like any other. */
+        /* The QSA wire is within-step scratch and a draft round is its own step, so the head
+         * shares all of it. The QSA tail is per-layer state (`kv_qsa_tail`), not in the wire, and
+         * declare() binds the head's layer to it like any other. */
         tw.qsa  = m.qsaw;
 
         MtpHcBlock::Src ts{};
@@ -1355,8 +1259,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
                                       "input_mix_weight_up.weight", mpre);
         ts.hc_mlp.inject_w  = nm.ckpt("%s.layers.0.mlp_hyper_connection."
                                       "block_inject_weight.weight", mpre);
-        /* The head's own mixer, and it has no `block_inject_weight` for the same reason the
-         * trunk's 97th connection has none: nothing follows it to write back into. */
+        /* The head's own mixer has no `block_inject_weight`, like the trunk's 97th connection:
+         * nothing follows it to write back into. */
         ts.hc_mix.norm      = nm.ckpt("%s.hyper_connection_mixer.hc_norm.weight", mpre);
         ts.hc_mix.mix_down  = nm.ckpt("%s.hyper_connection_mixer.input_mix_weight_down.weight",
                                       mpre);
@@ -1378,9 +1282,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
             ts.mlp.shared_gate = nm.ckpt("%s.layers.0.mlp.shared_expert_gate.weight", mpre);
         }
 
-        /* THE ATTENTION'S TWO SETTINGS ARE SET BEFORE declare(), for the reason the trunk's are:
-         * `attn_paged` declares `sel` and `seqused` as READS, and a read declared after the op is
-         * not a read at all. */
+        /* Set before declare(), as for the trunk: `attn_paged` declares `sel` and `seqused` as
+         * reads, which must precede the op. */
         m.mtp.attn.kv_block = 4;
         if (m.qsaw.qk) {
             m.mtp.attn.qsa_sel      = m.qsaw.sel;
@@ -1399,12 +1302,19 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
         m.mtp.media = m.media;
         RAD_ARCH_TRY(m.mtp.declare(b, nm, g, (int)g.n_layer, m.kv_full, &m.kv_qsa_bkey, m.n_rot,
                                    m.w_tok, m.w_lm_head, m.hccfg, g.max_spec, tw, ts));
+        /* A head pass refills the rope table ahead of the head's ops (step), while the carry
+         * `mtp_hin` still holds the rows the previous pass left. The refill is the trunk's
+         * `rope_table` op, so the table's planned life would end at its last declared reader,
+         * which is in the trunk when no head op reads the table (no fused prologue), and the
+         * planner could then put the carry in the table's bytes. Declared as written by the
+         * head's first op, the table is live where the carry is. */
+        if (m.op_rope_cs && rad_op_writes(b, m.mtp.op_gather, &m.b_rope_cs, 1) < 0)
+            return RAD_E_INVAL;
         m.have_mtp = true;
 
-        /* WHAT THE ENGINE DRIVES. Serial: `max_spec` dependent passes, each embedding what the
-         * last one proposed. `proposal` is the buffer a pass leaves its token in, and the two
-         * heads differ -- the 2-bit head takes its own argmax into `mtp_didx`, the bf16 head goes
-         * through the ordinary sampler chain and 0 says so. */
+        /* Serial drafter: `max_spec` dependent passes, each embedding the last one's proposal.
+         * The 2-bit head writes its own argmax into `mtp_didx`; without it `mtp_didx` is 0 and the
+         * bf16 head goes through the ordinary sampler chain. */
         RadDrafterDecl dd{};
         dd.name           = "mtp";
         dd.kind           = RAD_DRAFT_SERIAL;
@@ -1413,93 +1323,215 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
         dd.proposal_pitch = kDraftTopR;   /* the pick is column 0; see kDraftTopR */
         dd.mask_token     = -1;
         RAD_ARCH_TRY(rad_declare_drafter(b, &dd));
-        rad_note(b, "MTP head: one gated-attention layer with 512 routed experts, over the WIDE "
+        rad_note(b, "MTP head: one gated-attention layer with 512 routed experts over the wide "
                     "stream, %d serial draft round(s)", ctx->max_spec);
     } else if (nextn > 0) {
-        rad_note(b, "the checkpoint carries an `mtp.` head and this deployment asked for no "
-                    "speculative window (max_spec 0). Its weights stay off the card");
+        rad_note(b, "the checkpoint's `mtp.` head is not loaded: this deployment does not "
+                    "speculate");
     }
 
-    /* THERE IS NO LAYER BISECT AND THERE ARE NO BLOCK ABLATIONS HERE, which is a deliberate
-     * absence rather than an omission.
-     *
-     * A switch that truncates the layer loop, or drops a block from it, is a real instrument for a
-     * COMPOSITION fault -- the class an op oracle structurally cannot see, because it compares one
-     * op's device result against the host's on the operands the device handed it, and a graph
-     * wired wrongly hands both sides the same wrong operands.
-     *
-     * What such a switch costs is that it makes the server compute something that is NOT the model
-     * while looking exactly like a server that is. It is read at declare, it is invisible in a bug
-     * report, and a "THIS IS NOT THE MODEL" note is one line in a startup log nobody re-reads. A
-     * deployment would be one stale shell export away from being fluent and wrong. A composition
-     * bisect belongs in a tool that names what it is doing in its own output, not in an
-     * environment variable read by a production path.
-     *
-     * The residual probe (RADIANCE_DEBUG_RESID) is the instrument that fits that rule: it MEASURES
-     * the composition rather than breaking it, so a server carrying it still serves the model. */
-    m.n_run = g.n_layer;
-    /* THE VISION TOWER, LAST: an encoder pass issues nothing else, so its activations can share
-     * the arena with every buffer the language model declared above. Its weight groups start past
-     * every text layer and the MTP head. */
+    /* The vision tower, last: an encoder pass issues nothing else, so its activations share the
+     * arena with every buffer above. Its weight groups start past every text layer and the MTP
+     * head. */
     if (m.media) RAD_ARCH_TRY(m.vit.declare(b, meta, ctx, nm, g.n_embd, (int)g.n_layer + 64));
     return RAD_OK;
 }
 
-
-static void step(RadCtx* c, const RadBatch* batch) {
-    Model& m = g_model[rad_rank(c)];
-    const Geom& g = m.g;
-    const int64_t T = batch->n_tok;
-
-    /* AN ENCODER PASS RUNS THE VISION TOWER AND NOTHING ELSE (RadBatch::enc). */
-    if (batch->enc) {
-        m.vit.step(c, batch);
-        return;
+/* ============================== A prefill step wider than one MoE pass ==============================
+ *
+ * Every layer of a prefill chunk makes two all-reduces, the mixer's and the MoE's, each in a hard
+ * chain: mixer -> all-reduce -> write -> read -> MoE -> all-reduce -> write -> read. At four ranks
+ * a chunk's 97 tiered-int8 two-shots are about a quarter of its time, with nothing beside them on
+ * one stream.
+ *
+ * Under --prefill-span the scheduler hands a prefill alone in its step several checkpoint
+ * intervals, each piece the interval-sized chunk a span of 1 makes. Everything a piece can run by
+ * itself runs a piece at a time, and every all-reduce goes out on the second lane, beside the
+ * other piece's work on the first:
+ *
+ *   the mixer       the delta net runs whole a piece at a time (projection, convolution, solve and
+ *                   scan over the piece's bounds, the state handed on through the cache as between
+ *                   two chunks), and the attention runs its gated sparse path a piece at a time;
+ *                   each hands its first piece's all-reduce off behind that piece's out projection
+ *                   (ArPieces), so it runs beside the second piece's mixer;
+ *   the MoE         a pass a piece: the mixer's all-reduce of piece 1 runs beside piece 0's write,
+ *                   read and pass, the MoE's of piece 0 beside piece 1's;
+ *   the last one    the MoE's all-reduce of piece 1 runs beside piece 0's write and the next
+ *                   layer's read.
+ *
+ * The indexer's selection and the embedding run over the whole step.
+ *
+ * A piece computes the bytes the narrower chunk does: every all-reduce message has a piece's rows,
+ * so the tiered-int8 shards and their owners are the ones a span of 1 sends; every connection read
+ * is a piece, so its down product splits K the same way (HyperConn::read_pieces); every MoE pass
+ * and delta-net piece is a chunk's, and attention rows are their own. The first interval of a
+ * prompt is never spanned (Scheduler::plan_chunk), so the dense attention below QSA's exactness
+ * bound is taken where it was.
+ *
+ * The second lane's requirements (Ctx::lane1_) hold: every collective of the step is on it,
+ * including the embedding's; none carries an arrival counter; and the one buffer it touches is out
+ * of the sharing pool (declare). The collectives there are declared at `overlap` 1, whose rows
+ * leave the CUs to the work beside them. */
+static bool pipelined(const Model& m, int64_t T) {
+    const int64_t R = m.moecfg.rows;
+    if (!m.pipe_on || R <= 0 || T <= R) return false;
+    if (m.moecfg.calib || dbg_resid_on() || !m.op_embed_ar) return false;
+    for (const Layer& l : m.layers) {
+        if (!(l.full ? l.attn.issues_ar(T) : l.gdn.issues_ar(T))) return false;
+        if (!l.mlp.issues_ar(T, R)) return false;
     }
+    return true;
+}
 
-    /* AN MTP PASS RUNS THE HEAD AND NOTHING ELSE. The trunk already ran this step and left its
-     * wide stream in `h`; the head reads the rows it wants out of it and turns them into either a
-     * draft token or one more position of its own attention history. Which of the two is the SIGN
-     * of `draft_pass`, and rad_block_mtp_hc.h says why there are two.
-     *
-     * Zero is a trunk step, so a zeroed RadBatch runs the model -- the same convention, and for
-     * the same reason, as `num_accepted` (docs/OPS.md). */
-    if (batch->draft_pass != 0) {
-        if (!m.have_mtp) {
-            rad_step_fail(c, "the batch asks for a drafter pass and no drafter is declared: the "
-                             "container carries no `mtp.` head, or declare ran at max_spec 0, "
-                             "which is the engine saying it would not draft");
-            return;
+/* The mixer's reduction of a piece the block has finished (ArPieces), on the second lane behind
+ * the out projection that wrote it. */
+struct MixAr {
+    RadCtx*      c = nullptr;
+    const Layer* l = nullptr;
+};
+static void mix_ar_piece(void* u, int64_t r0, int64_t n) {
+    const MixAr& s = *(const MixAr*)u;
+    rad_lane(s.c, 1);
+    rad_lane_join(s.c, 0, 1);
+    if (s.l->full) s.l->attn.issue_ar(s.c, r0, n);
+    else           s.l->gdn.issue_ar(s.c, r0, n);
+    rad_lane(s.c, 0);
+}
+
+/* The bounds a step wider than a pass is cut by, on the card: {0, pass, T}. The first two are the
+ * window of the indexer's score plane (QsaIndexer::step, Config::plane_rows) and the delta net's
+ * first piece (ArPieces::cu), copied from the pinned host copy; T is copied on the card from the
+ * step's cu_seqlens. Both are issued on the step's stream ahead of every layer by each step of one
+ * sequence wider than a pass, since the buffer is a transient (declare). Null where no step can be
+ * wider than a pass (no b_pipe_cu) or the pinned copy could not be allocated. */
+static const int32_t* pipe_bounds(RadCtx* c, const RadBatch* batch, Model& m) {
+    if (!m.b_pipe_cu) return nullptr;
+    if (!m.pipe_cu_tried) {
+        m.pipe_cu_tried = true;
+        m.pipe_cu_h = (int32_t*)rad_dev_alloc(2 * sizeof(int32_t), RAD_MEM_HOST_PINNED);
+        if (m.pipe_cu_h) {
+            m.pipe_cu_h[0] = 0;
+            m.pipe_cu_h[1] = (int32_t)m.moecfg.rows;
+        } else if (m.g.rank == 0) {
+            fprintf(stderr, "radiance: qwen4exp: no pinned host memory for the window bounds; a "
+                            "step wider than a pass cannot run\n");
         }
-        /* THE HEAD'S OWN cos/sin ROWS, AND THE TRUNK DID NOT WRITE THEM. `rope_table` fills the
-         * rows THIS STEP'S POSITIONS name, and a draft round runs PAST the committed end -- the
-         * scheduler says so where it reserves the lookahead blocks: "round k writes the head's K
-         * and V at position head_i + k - 1, which runs past the committed end". The trunk step
-         * before this one covered head_i and no further, so without this call rounds past the
-         * first would rotate by whatever the table held at a row nothing had written yet.
-         *
-         * LEAVING IT OUT COSTS ONLY ACCEPTANCE, WHICH IS WHY IT IS EASY TO MISS. A draft is
-         * verified; a mis-rotated one is rejected and the text is still the trunk's, so the
-         * failure has no symptom except a draft that agrees less often. It becomes visible only
-         * once the indexer reads the same table: the head's QSA selection moves, its drafts move,
-         * and the accepted text moves with them at tie level -- a transcript difference at long
-         * context and none at all below the exactness bound, where every block is selected
-         * regardless.
-         *
-         * A row is a function of its POSITION ALONE -- the angle for position P is the same angle
-         * for every request and every step -- so re-filling costs nothing but the launch and can
-         * never write a row a reader disagrees with. */
-        if (m.op_rope_cs && T <= qk_fuse_rows(g) && !rope_mixed(batch))
-            RAD_ISSUE_N(c, m.op_rope_cs, T, rope_pos1(batch, T), RAD_B(m.b_rope_cs));
-        m.mtp.step(c, batch);
-        return;
+    }
+    if (!m.pipe_cu_h) return nullptr;
+    int32_t* d = (int32_t*)rad_buf_ptr(c, m.b_pipe_cu);
+    if (batch->n_tok > m.moecfg.rows && batch->n_seq == 1) {
+        const RadStream s = rad_stream(c);
+        if (rad_memcpy_async(d, m.pipe_cu_h, 2 * sizeof(int32_t), s) != RAD_OK ||
+            rad_memcpy_async(d + 2, batch->cu_seqlens + 1, sizeof(int32_t), s) != RAD_OK)
+            return nullptr;
+    }
+    return d;
+}
+
+static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int32_t* pcu) {
+    const Geom& g = m.g;
+    const int64_t T = batch->n_tok, R = m.moecfg.rows;
+    const int64_t K = (T + R - 1) / R;
+    auto r0 = [&](int64_t p) { return p * R; };
+    auto rn = [&](int64_t p) { return T - p * R < R ? T - p * R : R; };
+    /* A collective on the second lane, ordered behind lane 0 where it reads what lane 0 just
+     * wrote (a join to a lane not yet built is a no-op). */
+    auto on1 = [&](bool behind0, auto&& issue) {
+        rad_lane(c, 1);
+        if (behind0) rad_lane_join(c, 0, 1);
+        issue();
+        rad_lane(c, 0);
+    };
+    auto wait1 = [&] { rad_lane_join(c, 1, 0); };
+    if (!m.pipe_noted) {
+        m.pipe_noted = true;
+        if (g.rank == 0)
+            fprintf(stderr, "radiance: qwen4exp: prefill steps wider than a MoE pass are pipelined: "
+                            "%lld rows in %lld pieces of %lld, all-reduces on the second lane\n",
+                    (long long)T, (long long)K, (long long)R);
     }
 
     RAD_ISSUE(c, m.op_embed,
               praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.a_x.x, T));
     m.mrows.step(c, batch, m.a_x.x, T);
-    /* Unconditional, unlike qwen35_fp8's: there is no norm in front of the first block to fold it
-     * into, because the first thing that touches the stream is a gated-residual read. */
+    on1(true, [&] { RAD_ISSUE_N(c, m.op_embed_ar, T * g.n_embd, brows(m.a_x.x, T), RAD_NONE); });
+    wait1();
+    if (m.ple_layer >= 0) m.ple.ids(c, batch);
+    m.enter.step(c, T);
+    if (m.op_rope_cs && T <= qk_fuse_rows(g) && !rope_mixed(batch))
+        RAD_ISSUE_N(c, m.op_rope_cs, T, rope_pos1(batch, T), RAD_B(m.b_rope_cs));
+
+    /* The delta net runs a piece at a time over the bounds (ArPieces::cu) in a step of one
+     * prefill sequence in two pieces. */
+    const int32_t* gcu = pcu && K == 2 && batch->n_seq == 1 && batch->phase == RAD_PHASE_PREFILL
+                       ? pcu : nullptr;
+
+    const int64_t n = (int64_t)m.layers.size();
+    if (n > 0) {
+        if (m.ple_layer == 0) m.ple.step(c, batch);
+        for (int64_t p = 0; p < K; ++p) m.layers[0].hc_mix.read(c, T, r0(p), rn(p));
+    }
+    for (int64_t li = 0; li < n; ++li) {
+        const Layer& l = m.layers[(size_t)li];
+        /* The mixer finishes its output a piece at a time where its last stages are per row and
+         * hands the first pieces' reductions to the second lane as it goes (ArPieces), so the
+         * first piece's all-reduce runs beside the next piece's attention or out projection. */
+        MixAr ms{c, &l};
+        ArPieces pc{};
+        pc.rows = R; pc.done = mix_ar_piece; pc.u = &ms; pc.cu = gcu;
+        if (l.full) { l.qsa.step(c, l.attn.w.h, batch, pcu); l.attn.step(c, batch, false, &pc); }
+        else        l.gdn.step(c, batch, false, &pc);
+        auto ar_mix = [&](int64_t p) {
+            if (l.full) l.attn.issue_ar(c, r0(p), rn(p));
+            else        l.gdn.issue_ar(c, r0(p), rn(p));
+        };
+        /* A block that handed nothing leaves the first piece's all-reduce to be issued here. */
+        if (pc.handed == 0) on1(true, [&] { ar_mix(0); });
+        wait1();
+        int64_t issued = pc.handed > 0 ? pc.handed : 1;
+        bool behind = pc.handed == 0;     /* lane 1 already behind the whole mixer */
+        for (int64_t p = 0; p < K; ++p) {
+            if (p + 1 < K && p + 1 >= issued) {
+                on1(!behind, [&] { ar_mix(p + 1); });
+                behind = true;
+                issued = p + 2;
+            }
+            l.hc_mix.write(c, T, r0(p), rn(p));
+            l.hc_ffn.read(c, T, r0(p), rn(p));
+            l.mlp.pass(c, T, r0(p), rn(p), false);
+            /* Lane 0 waits here for the next piece's mixer all-reduce and the last piece's MoE
+             * one, both issued before this pass; lane 1 then takes this piece's behind its
+             * gather. */
+            wait1();
+            on1(true, [&] { l.mlp.issue_ar(c, r0(p), rn(p)); });
+        }
+        l.mlp.route_report(c);
+        /* The writes, and the next layer's reads beside the last piece's all-reduce. PLE adds into
+         * every row of the stream before the next layer reads it, so there the reads wait. */
+        const Layer* nx = li + 1 < n ? &m.layers[(size_t)li + 1] : nullptr;
+        const bool ple_next = nx && li + 1 == m.ple_layer;
+        for (int64_t p = 0; p < K; ++p) {
+            if (p == K - 1) wait1();
+            l.hc_ffn.write(c, T, r0(p), rn(p));
+            if (nx && !ple_next) nx->hc_mix.read(c, T, r0(p), rn(p));
+        }
+        if (ple_next) {
+            m.ple.step(c, batch);
+            for (int64_t p = 0; p < K; ++p) nx->hc_mix.read(c, T, r0(p), rn(p));
+        }
+    }
+}
+
+/* The trunk one stream at a time over the whole step: every step a span of 1 makes, and every
+ * other where step_pipelined's conditions do not hold. */
+static void step_serial(RadCtx* c, const RadBatch* batch, Model& m, const int32_t* pcu) {
+    const Geom& g = m.g;
+    const int64_t T = batch->n_tok;
+    RAD_ISSUE(c, m.op_embed,
+              praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.a_x.x, T));
+    m.mrows.step(c, batch, m.a_x.x, T);
+    /* Unconditional, unlike qwen35_fp8's: the first block has no norm to fold it into, only a
+     * gated-residual read. */
     if (m.op_embed_ar)
         RAD_ISSUE_N(c, m.op_embed_ar, T * g.n_embd, brows(m.a_x.x, T), RAD_NONE);
     /* The PLE's hash, ahead of every layer: its host gather waits for it, and the layers issued
@@ -1510,29 +1542,62 @@ static void step(RadCtx* c, const RadBatch* batch) {
     if (m.op_rope_cs && T <= qk_fuse_rows(g) && !rope_mixed(batch))
         RAD_ISSUE_N(c, m.op_rope_cs, T, rope_pos1(batch, T), RAD_B(m.b_rope_cs));
 
-    for (int64_t li = 0; li < m.n_run && li < (int64_t)m.layers.size(); ++li) {
+    for (int64_t li = 0; li < (int64_t)m.layers.size(); ++li) {
         const Layer& l = m.layers[(size_t)li];
         /* Before the attention connection reads the stream, which is where the reference puts it. */
         if (li == m.ple_layer) m.ple.step(c, batch);
-        {
-            l.hc_mix.read(c, T, 0, T);
-            /* THE INDEXER RUNS FIRST, because the attention reads its selection. It can: this
-             * block's input is normed and quantised by the caller (`ext_in`), so `w.h` is already
-             * what it will be when the attention runs. */
-            if (l.full) { l.qsa.step(c, l.attn.w.h, batch); l.attn.step(c, batch); }
-            else        l.gdn.step(c, batch);
-            l.hc_mix.write(c, T, 0, T);
-        }
+        l.hc_mix.read_pieces(c, T);
+        /* The indexer runs first, since the attention reads its selection. The block's input is
+         * already normed and quantised by the connection (`ext_in`), so `w.h` is final. */
+        if (l.full) { l.qsa.step(c, l.attn.w.h, batch, pcu); l.attn.step(c, batch); }
+        else        l.gdn.step(c, batch);
+        l.hc_mix.write(c, T, 0, T);
         dbg_resid(c, (int)li, "mix", g.n_embd, m.b_h, m.a_x.x);
-        {
-            l.hc_ffn.read(c, T, 0, T);
-            l.mlp.step(c, batch);
-            l.hc_ffn.write(c, T, 0, T);
-        }
+        l.hc_ffn.read_pieces(c, T);
+        l.mlp.step(c, batch);
+        l.hc_ffn.write(c, T, 0, T);
         dbg_resid(c, (int)li, "ffn", g.n_embd, m.b_h, m.a_x.x);
     }
+}
 
-    m.mixer.read(c, T, 0, T);
+static void step(RadCtx* c, const RadBatch* batch) {
+    Model& m = g_model[rad_rank(c)];
+    const Geom& g = m.g;
+    const int64_t T = batch->n_tok;
+
+    /* An encoder pass runs only the vision tower (RadBatch::enc). */
+    if (batch->enc) {
+        m.vit.step(c, batch);
+        return;
+    }
+
+    /* An MTP pass runs only the head. The trunk already left its wide stream in `h`; the head
+     * turns the rows it wants into a draft token or one more position of its own attention
+     * history, by the sign of `draft_pass` (rad_block_mtp_hc.h). Zero is a trunk step. */
+    if (batch->draft_pass != 0) {
+        if (!m.have_mtp) {
+            rad_step_fail(c, "the batch asks for a drafter pass and no drafter is declared: the "
+                             "container carries no `mtp.` head, or declare ran at max_spec 0");
+            return;
+        }
+        /* Fill the head's own cos/sin rows. A draft round runs past the committed end (round k
+         * writes K and V at position head_i + k - 1), at rows the preceding trunk step never
+         * wrote. Without this, later rounds would rotate by stale rows: only acceptance drops, and
+         * because the indexer reads the same table, the head's QSA selection and so the accepted
+         * text shift at tie level at long context. A row depends only on its position, so
+         * re-filling is idempotent. */
+        if (m.op_rope_cs && T <= qk_fuse_rows(g) && !rope_mixed(batch))
+            RAD_ISSUE_N(c, m.op_rope_cs, T, rope_pos1(batch, T), RAD_B(m.b_rope_cs));
+        m.mtp.qsa_win_cu = pipe_bounds(c, batch, m);
+        m.mtp.step(c, batch);
+        return;
+    }
+
+    const int32_t* pcu = pipe_bounds(c, batch, m);
+    if (pipelined(m, T)) step_pipelined(c, batch, m, pcu);
+    else                 step_serial(c, batch, m, pcu);
+
+    m.mixer.read_pieces(c, T);
 
     if (batch->n_out > 0) {
         RAD_ISSUE_N(c, m.op_gather, batch->n_out,
@@ -1544,18 +1609,13 @@ static void step(RadCtx* c, const RadBatch* batch) {
     }
 }
 
-/* WHAT THE PLUGIN WOULD DRAFT AT, which is what `--num-speculative-tokens auto` takes and what
- * rad-convert declares at when the run that makes a container would not itself have drafted.
+/* The default draft depth, used by `--num-speculative-tokens auto` and by rad-convert.
  *
- * 3 and not `mtp_num_hidden_layers`: the checkpoint says the head EXISTS (one layer), never how
- * deep a chain of it is worth running. It is an operating point, not a property of the model,
- * which is why `draft_depth_fixed` stays 0 and the flag overrides it.
- *
- * THREE IS WHERE THROUGHPUT PEAKS on this model. Per-POSITION acceptance stays high at every
- * depth, so the head is not what runs out; what runs out is the VERIFY step. Each extra query row
- * costs real time here because the model's weights do not fit device memory -- more rows mean more
- * experts streamed and more n-gram rows faulted out of the mapped table -- and most of what a
- * deeper step adds is that, not the head's own ops. */
+ * 3 is an operating point, not a model property (`mtp_num_hidden_layers` only says the one-layer
+ * head exists), so `draft_depth_fixed` stays 0. Throughput peaks at 3 on this model: per-position
+ * acceptance stays high at every depth, but each extra verify row costs real time because the
+ * weights do not fit device memory (more experts streamed, more n-gram rows faulted from the
+ * mapped table). */
 static int probe(const RadModelMeta* meta, RadArchProbe* out) {
     if (!meta || !out) return RAD_E_INVAL;
     out->draft_depth = 0;
@@ -1570,7 +1630,7 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
 #ifndef RAD_ARCH_NO_EXPORTS
 RAD_ARCH_PROBE(qwen4exp_fp8)
 RAD_ARCH_PLUGIN(qwen4exp_fp8, "qwen4exp", "", "0.1.0",
-                "Qwen4-Exp (Qwen3.8-Flash-Next): hybrid Gated DeltaNet / gated attention, a GATED "
-                "RESIDUAL four streams wide, and 512 routed experts -- from a DENSE bf16 "
-                "checkpoint, quantised ahead of time by a recipe")
+                "Qwen4-Exp (Qwen3.8-Flash-Next): hybrid Gated DeltaNet / gated attention, a gated "
+                "residual four streams wide and 512 routed experts, from a dense bf16 checkpoint "
+                "quantised ahead of time by a recipe")
 #endif
diff --git a/arch/qwenimage21/CMakeLists.txt b/arch/qwenimage21/CMakeLists.txt
index 47d8f45a..ac43c436 100644
--- a/arch/qwenimage21/CMakeLists.txt
+++ b/arch/qwenimage21/CMakeLists.txt
@@ -1,6 +1,5 @@
-# A plugin like any other: built here inside radiance's tree, or on its own against an installed
-# radiance (`cmake -S arch/qwenimage21 -B build -DCMAKE_PREFIX_PATH=`) -- the same
-# rad_add_plugin either way (cmake/RadAddPlugin.cmake).
+# Built in radiance's tree, or standalone against an installed radiance
+# (`cmake -S arch/qwenimage21 -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake.
 if(NOT COMMAND rad_add_plugin)
   cmake_minimum_required(VERSION 3.21)
   project(qwenimage21 LANGUAGES CXX)
diff --git a/arch/qwenimage21/qwenimage21.cpp b/arch/qwenimage21/qwenimage21.cpp
index c0082d67..b8e1ec7e 100644
--- a/arch/qwenimage21/qwenimage21.cpp
+++ b/arch/qwenimage21/qwenimage21.cpp
@@ -4,22 +4,22 @@
  *
  * Three networks behind one prompt (diffusers' QwenImage21Pipeline):
  *
- *   THE CONDITIONING NETWORK is Qwen3-VL-8B-Instruct, unchanged: its vision tower (with the three
- *   deepstack taps) reads the reference pictures, its 36-layer language model reads the prompt,
- *   and what the generator conditions on is the LAST LAYER'S OUTPUT BEFORE THE FINAL NORM, minus
- *   the fixed system turn the template starts with.
+ *   Conditioning network: Qwen3-VL-8B-Instruct, unchanged. Its vision tower (with the three
+ *   deepstack taps) reads the reference pictures and its 36-layer language model reads the
+ *   prompt. The generator conditions on the last layer's output before the final norm, minus the
+ *   template's fixed system turn.
  *
- *   THE DENOISER is a 7.1B single-stream diffusion transformer over one joint sequence: the
+ *   Denoiser: a 7.1B single-stream diffusion transformer over one joint sequence: the
  *   conditioning's text rows (through `txt_in`), each reference picture's latent tokens in place of
- *   its vision slots (through `img_in`, four latent rows a slot), and the image being made. 32
+ *   its vision slots (through `img_in`, four latent rows per slot), and the image being made. 32
  *   blocks of `h += tanh(g1) attn(LN(h)(1 + s1)); h += tanh(g2) mlp(LN(h)(1 + s2))`, the four
- *   modulation rows from ONE projection of the timestep embedding shared by every block. Attention
- *   is block-causal: text causal, a picture's rows bidirectional, every row sees all earlier ones.
- *   The conditioning is modulated at t = 0, so its keys and values do not depend on the step --
- *   they are computed once (a COND pass) and cached in this plugin's KV group, and each DENOISE
- *   pass runs only the image's rows against them.
+ *   modulation rows coming from one projection of the timestep embedding shared by every block.
+ *   Attention is block-causal: text causal, a picture's rows bidirectional, every row sees all
+ *   earlier ones. The conditioning is modulated at t = 0, so its keys and values do not depend on
+ *   the step: they are computed once (a COND pass) and cached in this plugin's KV group, and each
+ *   DENOISE pass runs only the image's rows against them.
  *
- *   THE DECODER is a 2-D VAE: 64 latent channels, 16x down, RGBA in and out. Its encoder turns the
+ *   Decoder: a 2-D VAE, 64 latent channels, 16x down, RGBA in and out. Its encoder turns the
  *   reference pictures (and a picture being repainted) into latents on the COND pass; its decoder
  *   turns a finished latent into pixels on a DECODE pass.
  *
@@ -29,20 +29,20 @@
  *
  * ============================== WHAT IS QUANTISED ==============================
  *
- * One plugin serves a bf16 container and a block-fp8 one: every linear of the language model and
- * of the DiT's blocks is a LinearFP8, which reads whatever the container holds (rad_fp8.h), and the
- * model is bf16 throughout when the first DiT projection is plain. The small linears around them --
- * txt_in, img_in, the timestep MLP, the shared modulation, norm_out, proj_out -- and the vision
- * tower and the VAE are bf16 in both: they are read once a pass or less, and the recipe keeps them.
+ * One plugin serves bf16 and block-fp8 containers: every linear of the language model and of the
+ * DiT's blocks is a LinearFP8, which reads whatever the container holds (rad_fp8.h), and the model
+ * is bf16 throughout when the first DiT projection is plain. The small linears around them
+ * (txt_in, img_in, the timestep MLP, the shared modulation, norm_out, proj_out), the vision tower
+ * and the VAE stay bf16 in both, since they are read once per pass or less.
  *
  * ============================== TENSOR PARALLEL ==============================
  *
  * The language model and the DiT blocks are split by heads and by feed-forward width, an
- * all-reduce after each output projection. Everything else is replicated and runs on every rank:
- * the embedding table, the vision tower, the small linears, the sampler and the VAE encoder --
- * each is once a pass and smaller than the collective a split would cost. The decoder is split
- * after its mid-block, by rows (see `Vae::band_from`), and every rank ends with the same pixels;
- * the core reads rank 0's.
+ * all-reduce after each output projection. Everything else is replicated and runs on every rank
+ * (the embedding table, the vision tower, the small linears, the sampler and the VAE encoder),
+ * since each runs once per pass and costs less than the collective a split would add. The decoder
+ * is split by rows after its mid-block (see `Vae::band_from`); every rank ends with the same
+ * pixels, and the core reads rank 0's.
  */
 #include 
 #include 
@@ -65,27 +65,27 @@ using namespace rad::arch;
 /* The largest image: 2400 x 1792 pixels, the widest preset the model card lists, 16800 latent
  * tokens. 2048 x 2048 (16384) is the native size and the default. */
 enum { kMaxImageTokens = 16800 };
-/* Reference pictures: at most ten a request, each resized to 1024 x 1024 pixels of area. */
+/* Reference pictures: at most ten per request, each resized to 1024 x 1024 pixels of area. */
 enum { kMaxRefs = 10, kRefArea = 1024 * 1024 };
 /* Images a request may ask for, and so the lanes of latent state. */
 enum { kMaxLanes = 16 };
-/* A reference picture's latent tokens at most: its area over 16 x 16, a little over for its sides'
- * rounding (the driver's own bound, core/gen/driver.cpp). */
+/* The most latent tokens of a reference picture: its area over 16 x 16, plus slack for its sides'
+ * rounding (the driver's bound, core/gen/driver.cpp). */
 static inline int64_t ref_tokens_max() { return (int64_t)kRefArea / 256 * 11 / 10 + 64; }
 
 static const char* kSysPrompt = "Comprehend and analyze the provided prompt.";
 
 /* ================================================================== the VAE as a recorded graph
  *
- * AN IMAGE'S SIZE IS A REQUEST'S, so the VAE's ops are declared once for the largest image and
- * issued with the real one's extents: every image operand is a raw [height, width * channels]
- * view of its buffer (docs/OPS.md, "Image generation"), and its extents follow from the pass's
- * picture size and the stage's scale. `Vae` records each op with what it needs to rebuild its
- * operands, so declare() and step() walk the same list and cannot disagree.
+ * Image size varies per request, so the VAE's ops are declared once for the largest image and
+ * issued with the actual extents: every image operand is a raw [height, width * channels] view of
+ * its buffer (docs/OPS.md, "Image generation"), with extents from the pass's picture size and the
+ * stage's scale. `Vae` records each op with what it needs to rebuild its operands, so declare()
+ * and step() walk the same list.
  *
- * EVERY OUTPUT IS A BUFFER OF ITS OWN, sized for its stage. The planner shares storage between
- * the ones whose lives do not overlap, which is the whole of the memory plan: no buffer is reused
- * by hand. The ops are issued in the order they were declared, which is what makes that sound. */
+ * Every output is its own buffer, sized for its stage; the planner shares storage between those
+ * whose lives do not overlap, and no buffer is reused by hand. This is sound because ops are issued
+ * in declaration order. */
 struct VImg {
     rad_buf buf = 0;
     int64_t ch = 0;
@@ -110,13 +110,13 @@ struct Vae {
     int64_t     base_px = 0;     /* pixels at level 0, the largest any pass hands it */
     int         n_buf = 0;
     int         first_group = 0;
-    /* THE BANDED TAIL. From op `band_from` on, every output pixel reads a bounded window of rows
-     * above and below it -- 3x3 convolutions, nearest upsampling, per-pixel norms and adds, the
-     * depth-to-space shortcuts -- so a rank can run the tail on its own band of level-0 rows plus
-     * `halo` rows a side and get its band's pixels bit for bit: the rows a conv's zero padding
-     * spoils at a band's edge never reach the band. The ops before it hold the mid-block's
-     * attention, which reads every pixel, and run whole. `whole` is what they wrote, which the
-     * tail reads at the band's row offset. -1: no tail. */
+    /* The banded tail. From op `band_from` on, every output pixel reads a bounded window of rows
+     * (3x3 convolutions, nearest upsampling, per-pixel norms and adds, depth-to-space shortcuts),
+     * so a rank can run the tail on its band of level-0 rows plus `halo` rows per side and get its
+     * band's pixels bit for bit: rows spoiled by a conv's zero padding at the band edge never reach
+     * the band. The ops before it include the mid-block's attention, which reads every pixel, and
+     * run whole; `whole` holds their outputs, read by the tail at the band's row offset. -1: no
+     * tail. */
     int                  band_from = -1;
     int64_t              halo = 0;
     std::vector whole;
@@ -389,11 +389,20 @@ struct DitLayer {
     rad_op     op_kq = 0, op_attn_q = 0;
 };
 
+/* Weight groups (movement units) by network. The text encoder's layers take 0.. and the DiT's
+ * blocks kGrpDit + 1..; declare refuses a network deep enough to run into the next range. */
+enum : int {
+    kGrpTxtIn  = 1000,   /* txt_in */
+    kGrpVaeEnc = 1100,
+    kGrpVaeDec = 1200,
+    kGrpDit    = 2000,   /* the DiT's model-level weights */
+    kGrpVision = 3000,
+};
+
 struct Model {
     Names nm{""};
     Geom  gt{}, gd{};          /* the language model's and the DiT's geometry, per rank */
     int64_t max_ref_rows = 0;  /* every reference picture's latent tokens together */
-    int64_t n_cond_max = 0;    /* conditioning rows: the text, or one picture's latents */
     bool  media = false;
     VisionTower vit{};
     rad_kvgroup kv = 0;
@@ -401,7 +410,7 @@ struct Model {
     /* ---- the language model */
     rad_weight w_tok = 0;
     rad_op  op_embed = 0, op_mm = 0, op_ds[VisionTower::MAX_DS] = {};
-    rad_buf b_tx = 0, b_tq = 0, b_tkv = 0, b_th2 = 0, b_tgu = 0;
+    rad_buf b_tx = 0, b_tkv = 0, b_th2 = 0, b_tgu = 0;
     ActFP8  a_th{}, a_tattn{}, a_tffn{};
     std::vector te;
 
@@ -431,7 +440,7 @@ struct Model {
     rad_buf b_v = 0;
 
     /* ---- the per-image state (PERSIST) and what crosses passes */
-    rad_buf b_state = 0, b_prev = 0, b_inp = 0, b_mask = 0, b_img = 0, b_txt_keep = 0, b_reflat = 0;
+    rad_buf b_state = 0, b_prev = 0, b_inp = 0, b_mask = 0, b_img = 0, b_reflat = 0;
     rad_op  op_lstore_lat = 0, op_lstore_mask = 0, op_enc_aff = 0, op_dec_aff = 0, op_rgba = 0;
     /* More than one rank: the decoder's bands gathered, and the bytes made from the gather. */
     rad_op  op_bands = 0, op_rgba_bands = 0;
@@ -520,8 +529,8 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
     const int64_t T = g.max_tok;
     const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim();
 
-    /* The embedding is REPLICATED: a rank looks up every token itself, so no collective sums it,
-     * and the rows the vision tower replaces are overwritten on every rank alike. */
+    /* The embedding is replicated: each rank looks up every token itself, so no collective sums
+     * it, and the vision tower's rows overwrite it identically on every rank. */
     RAD_ARCH_TRY(map_copy(b, nm.f("te.token_embd.weight"),
                           nm.ckpt("model.language_model.embed_tokens.weight")));
     m.w_tok = decl_w(b, nm.f("te.token_embd.weight"), RAD_BF16, { g.n_vocab_all, g.n_embd },
@@ -653,9 +662,9 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
                        { m.b_tx, m.b_th2 }, { m.b_tx });
     }
 
-    /* ---- txt_in, over every prompt row. Its output crosses the conditioning's segments, each of
-     * which runs the DiT's blocks over the same buffers, so it is PERSIST. */
-    const int gti = 1000;
+    /* ---- txt_in, over every prompt row. Its output must survive across the conditioning's
+     * segments, each of which runs the DiT's blocks over the same buffers, so it is PERSIST. */
+    const int gti = kGrpTxtIn;
     const int64_t D = m.gd.n_embd;
     m.b_txa = decl_b(b, nm.f("txt.a"), RAD_BF16, { T, D });
     m.b_txb = decl_b(b, nm.f("txt.b"), RAD_BF16, { T, D });
@@ -686,7 +695,7 @@ static int declare_encoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
     v.b = b;
     v.scope = "venc";
     v.down = true;
-    v.first_group = 1100;
+    v.first_group = kGrpVaeEnc;
     /* The largest picture the encoder reads: a repainted one at the largest output size. */
     v.base_px = (int64_t)kMaxImageTokens * 256;
     const int64_t base = rad_meta_geti(meta, "vae.base_dim", 96);
@@ -757,7 +766,7 @@ static int declare_decoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
     v.b = b;
     v.scope = "vdec";
     v.down = false;
-    v.first_group = 1200;
+    v.first_group = kGrpVaeDec;
     v.base_px = kMaxImageTokens;
     const int64_t base = rad_meta_geti(meta, "vae.decoder_base_dim", 144);
     const std::vector mult = meta_list(meta, "vae.dim_mult");
@@ -815,9 +824,10 @@ static int declare_decoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
         fprintf(stderr, "radiance: qwenimage21: the decoder after its mid-block is not row-local\n");
         return RAD_E_INVAL;
     }
-    /* THE BANDS, GATHERED. A band is ceil(H / world) latent rows and the split is taken only where
-     * a band and its two halos are under the whole -- so H > 2 * halo, which bounds W and with it
-     * the largest band: under kMaxImageTokens / world + kMaxImageTokens / (2 * halo) tokens. */
+    /* The bands, gathered. A band is ceil(H / world) latent rows, and the split is taken only where
+     * a band plus its two halos is smaller than the whole, so H > 2 * halo, which bounds W and
+     * thus the largest band: under kMaxImageTokens / world + kMaxImageTokens / (2 * halo)
+     * tokens. */
     const int world = m.gt.world;
     if (world > 1) {
         const int64_t bpx = (kMaxImageTokens / world + kMaxImageTokens / (2 * v.halo) + 1) * 256;
@@ -844,7 +854,7 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
     const int64_t T = g.max_tok;
     const int64_t D = g.n_embd, hd = g.head_dim, qd = g.q_dim();
     const int64_t C = rad_meta_geti(meta, "transformer.in_channels", 64);
-    const int gx = 2000;   /* the DiT's model-level weights' group; its blocks are 2001.. */
+    const int gx = kGrpDit;
 
     /* ---- the timestep: [cos | sin] of t * 1000 over 256 channels, an MLP to D, then the shared
      * modulation (four D-wide rows) and norm_out's scale, each through a silu. */
@@ -970,13 +980,12 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
         return i8 ? rw(b, op, { m.b_qkv, m.b_k8, m.b_ks }, { m.a_attn.x })
                   : rw(b, op, { m.b_qkv }, { m.a_attn.x });
     };
-    /* THE DENOISING ATTENTION'S SCORES IN INT8 where the linears are fp8: the keys quantised per
-     * (token, head) by quant_act_i8g, the query inside the op. The score product is about half the
-     * attention's issue and runs at twice the rate in int8; the picture moves by less than it moves
-     * between two exact attention implementations (Qwen-Image 2.1 at 1024^2 in diffusers, int8
-     * scores against exact ones: 36.2 dB PSNR, where diffusers' own SDPA kernels differ from each
-     * other by 32.6 to 34.4). The conditioning pass, run once a request, keeps bf16, and so does a
-     * bf16 container. */
+    /* The denoising attention's scores in int8 where the linears are fp8: keys quantised per
+     * (token, head) by quant_act_i8g, the query inside the op. The score product is about half of
+     * the attention and runs at twice the rate in int8. The image changes less than between two
+     * exact attention implementations (at 1024^2: 36.2 dB PSNR against exact scores, while
+     * diffusers' SDPA kernels differ from each other by 32.6 to 34.4 dB). The conditioning pass
+     * (once per request) and a bf16 container keep bf16. */
     const bool qk8 = !g.w_bf16;
     if (qk8) {
         m.b_k8 = decl_b(b, nm.f("dit.k8"), RAD_I8, { T, qd });
@@ -987,7 +996,7 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
     for (int64_t l = 0; l < g.n_layer; ++l) {
         DitLayer& L = m.dit[(size_t)l];
         const int li = (int)l;
-        const int grp = 2001 + li;
+        const int grp = kGrpDit + 1 + li;
         const char* pre = "transformer.transformer_blocks";
         RAD_ARCH_TRY(rad_bind_layer_kv(b, li, m.kv));
         RAD_ARCH_TRY(map_copy(b, nm.f("dit.blk.%d.q_norm.weight", li),
@@ -1016,7 +1025,7 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
                                 RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", hd),
                                            RAD_INT("n_head", g.n_head),
                                            RAD_INT("n_head_kv", g.n_head_kv),
-                                           RAD_F64("theta", 10000.0), RAD_F64("eps", eps),
+                                           RAD_F64("theta", g.theta), RAD_F64("eps", eps),
                                            RAD_STR("mode", "gptj_blocks"),
                                            RAD_INT("rotary_dim", hd),
                                            RAD_STR("sections", sections)),
@@ -1105,13 +1114,18 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     gd.n_embd     = gd.head_dim * gd.n_head_all;
     gd.n_ff_all   = gd.n_embd * rad_meta_geti(meta, "transformer.mlp_ratio", 3);
     gd.eps        = (float)rad_meta_getf(meta, "transformer.eps", 1e-6);
-    gd.theta      = 10000.0f;
+    gd.theta      = 10000.0f;   /* diffusers' QwenEmbedRope fixes it; the config does not say */
     gd.rope_mc    = false;
     RAD_ARCH_TRY(divide_or_fail(gd.n_head_all, gd.world, "transformer.num_attention_heads",
                                 &gd.n_head));
     gd.n_head_kv = gd.n_head;
     gd.kv_off = 0;
     RAD_ARCH_TRY(divide_or_fail(gd.n_ff_all, gd.world, "the DiT's feed-forward width", &gd.n_ff));
+    if (m.gt.n_layer >= kGrpTxtIn || gd.n_layer >= kGrpVision - kGrpDit) {
+        fprintf(stderr, "radiance: qwenimage21: %lld text-encoder and %lld DiT layers overrun the "
+                        "weight-group ranges\n", (long long)m.gt.n_layer, (long long)gd.n_layer);
+        return RAD_E_UNSUPPORTED;
+    }
     if (rad_meta_geti(meta, "transformer.context_in_dim", 4096) != m.gt.n_embd) {
         fprintf(stderr, "radiance: qwenimage21: the DiT reads %lld-wide conditioning and the text "
                         "encoder writes %lld\n",
@@ -1180,7 +1194,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
     /* ---- in issue order: the tower, the language model, the encoder, the DiT, the decoder.
      * (Vae says why the order matters.) */
     m.media = VisionTower::present(meta) && ctx->max_enc_patches > 0;
-    if (m.media) RAD_ARCH_TRY(m.vit.declare(b, meta, ctx, nm, m.gt.n_embd, 3000, true));
+    if (m.media) RAD_ARCH_TRY(m.vit.declare(b, meta, ctx, nm, m.gt.n_embd, kGrpVision, true));
     RAD_ARCH_TRY(declare_te(b, meta, m));
     RAD_ARCH_TRY(declare_encoder(b, meta, m));
     RAD_ARCH_TRY(declare_dit(b, meta, m));
@@ -1278,7 +1292,7 @@ static void step_te(RadCtx* c, const RadBatch* batch, const Model& m) {
         L.down.step(c, m.a_tffn, m.b_th2, T);
         if (L.op_ar2) RAD_ISSUE_N(c, L.op_ar2, T * g.n_embd, brows(m.b_th2, T), RAD_NONE);
         RAD_ISSUE(c, L.op_add2, brows(m.b_tx, T), brows(m.b_th2, T), brows(m.b_tx, T));
-        /* DEEPSTACK: tap l's rows join the hidden state at the vision slots after layer l. */
+        /* Deepstack: tap l's rows join the hidden state at the vision slots after layer l. */
         if (m.media && nmm > 0 && l < m.vit.n_ds)
             RAD_ISSUE_N(c, m.op_ds[l], nmm, brows(m.vit.b_ds[l], nmm),
                         praw(batch->mm_rows, RAD_I32, nmm), brows(m.b_tx, T));
@@ -1304,16 +1318,15 @@ static void step_temb(RadCtx* c, const Model& m, const float* t, int64_t S) {
  * (`bt` / `used`) and its own rows, causal or not; the rows' keys and values stored at `slot`
  * when it is given.
  *
- * TWO HALVES, THE ALL-REDUCES ON THE SECOND LANE. With more than one rank, a denoising pass of one
- * entry runs everything after the attention -- the output projection, the norm, the feed-forward
- * -- and the next block's norm and qkv projection over the rows in two halves, and each half's
- * all-reduce goes to lane 1 while lane 0 computes the other half. Every op between two attentions
- * is row-local, so a half computes exactly the bits the whole would. The attention stays whole:
- * every query reads every key. One entry only, because the norms find a row's modulation by its
- * entry, and with a single entry every row of either half is entry 0's; several entries run
+ * Two halves, all-reduces on the second lane. With more than one rank, a denoising pass of one
+ * entry runs everything after the attention (output projection, norm, feed-forward) and the next
+ * block's norm and qkv projection over the rows in two halves; each half's all-reduce goes to lane
+ * 1 while lane 0 computes the other half. Every op between two attentions is row-local, so a half
+ * computes exactly the bits the whole would. The attention stays whole: every query reads every
+ * key. One entry only, because the norms find a row's modulation by its entry; several entries run
  * unsplit. Lane 0 waits for a half's all-reduce just before its first reader, and that wait is
- * issued before the next all-reduce goes to lane 1 -- a join orders a lane behind everything
- * issued on the other, so in the other order it would wait for both. */
+ * issued before the next all-reduce goes to lane 1: a join orders a lane behind everything issued
+ * on the other, so the reverse order would wait for both. */
 static void step_blocks(RadCtx* c, const Model& m, int64_t R, int64_t S, const RadOperand& cu,
                         const RadOperand& pos, const RadOperand& bt, const RadOperand& used,
                         const int32_t* slot, bool causal) {
@@ -1526,8 +1539,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
             return;
         }
         /* The mid-block whole, then this rank's band of latent rows [a, a + band) with `halo` rows
-         * a side; its pixels sit (a - lo) * 16 rows into the tail's output. The last band may be
-         * short, and what the gather moves past the picture's last row nobody reads. */
+         * per side; its pixels sit (a - lo) * 16 rows into the tail's output. The last band may be
+         * short; whatever the gather moves past the picture's last row is never read. */
         m.dec.issue(c, H, W, cu, nullptr, 0, (size_t)m.dec.band_from);
         const int64_t a = rank * band;
         const int64_t lo = std::max(0, a - halo), hi = std::min(H, a + band + halo);
@@ -1547,8 +1560,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
 }
 
 /* ================================================================== the probe */
-/* The rows a pass carries -- one image at the largest size with guidance, so two entries -- and
- * the vision patches of ten reference pictures at 1024 x 1024 of area. */
+/* The rows a pass carries (one image at the largest size with guidance, so two entries) and the
+ * vision patches of ten reference pictures at 1024 x 1024 of area. */
 static int probe(const RadModelMeta* meta, RadArchProbe* out) {
     if (!meta || !out) return RAD_E_INVAL;
     out->gen_rows = 2 * (int64_t)kMaxImageTokens;
diff --git a/build.sh b/build.sh
index e8ba1a37..f2abd0ba 100755
--- a/build.sh
+++ b/build.sh
@@ -1,5 +1,5 @@
 #!/bin/sh
-# build.sh -- configure and build.
+# build.sh -- configure, build and run the fast tests.
 #
 # With no arguments the build configures itself: if hipcc is present and a card can be enumerated,
 # device kernels are compiled for that card's architecture, and otherwise the host backend is
@@ -10,19 +10,29 @@
 # have. Which of them actually get kernels is decided by the kernel libraries present; each one
 # declares the architectures it serves.
 #
-#   ./build.sh              configure + build + test
+#   ./build.sh              configure + build + the fast tests (ctest -L fast)
 #   ./build.sh -c           wipe the build directory first
 #   ./build.sh --no-hip     force the host backend even where hipcc exists
+#   ./build.sh --asan       AddressSanitizer + UBSan, host backend, in build-asan/
+#   ./build.sh --tsan       ThreadSanitizer, host backend, in build-tsan/
+#   ./build.sh --debug      CMAKE_BUILD_TYPE=Debug
+#   ./build.sh -b DIR       build in DIR instead of build/ (or build-asan/, build-tsan/)
+#
+# The other tiers (docs/GUIDE.md §1.3): ctest --test-dir build -LE 'gpu|oot' for everything that
+# runs without a card, plain ctest --test-dir build for everything.
 set -e
 
-BUILD=build
+BUILD=
+CLEAN=0
+SAN=
 CMAKE_ARGS=""
 
 while [ $# -gt 0 ]; do
     case "$1" in
-        -c|--clean) rm -rf "$BUILD" ;;
+        -c|--clean) CLEAN=1 ;;
         --no-hip)   CMAKE_ARGS="$CMAKE_ARGS -DRAD_WITH_HIP=OFF" ;;
-        --asan)     CMAKE_ARGS="$CMAKE_ARGS -DRAD_ASAN=ON" ;;
+        --asan)     SAN=asan ;;
+        --tsan)     SAN=tsan ;;
         --debug)    CMAKE_ARGS="$CMAKE_ARGS -DCMAKE_BUILD_TYPE=Debug" ;;
         -b)         shift; BUILD="$1" ;;
         *)          echo "build.sh: unknown option $1" >&2; exit 2 ;;
@@ -30,6 +40,17 @@ while [ $# -gt 0 ]; do
     shift
 done
 
+# A sanitised build gets a directory of its own, so it never reconfigures the normal tree. Host
+# code only: device kernels are not sanitised, and a sanitised engine is not one to serve from.
+case "$SAN" in
+    asan) CMAKE_ARGS="$CMAKE_ARGS -DRAD_ASAN=ON -DRAD_TSAN=OFF -DRAD_WITH_HIP=OFF"
+          BUILD=${BUILD:-build-asan} ;;
+    tsan) CMAKE_ARGS="$CMAKE_ARGS -DRAD_TSAN=ON -DRAD_ASAN=OFF -DRAD_WITH_HIP=OFF"
+          BUILD=${BUILD:-build-tsan} ;;
+    *)    BUILD=${BUILD:-build} ;;
+esac
+[ "$CLEAN" = 1 ] && rm -rf "$BUILD"
+
 cmake -S . -B "$BUILD" -G Ninja $CMAKE_ARGS
 cmake --build "$BUILD" -j"$(nproc)"
-ctest --test-dir "$BUILD" --output-on-failure
+ctest --test-dir "$BUILD" -L '^fast$' -j8 --no-tests=error --output-on-failure
diff --git a/cmake/RadAddPlugin.cmake b/cmake/RadAddPlugin.cmake
index 9ff68ae7..7992fd75 100644
--- a/cmake/RadAddPlugin.cmake
+++ b/cmake/RadAddPlugin.cmake
@@ -1,19 +1,10 @@
-# rad_add_plugin / rad_hipify -- the ONE definition of how a source file becomes a loadable
-# radiance plugin, shared by the in-tree build and by an out-of-tree one.
+# rad_add_plugin / rad_hipify -- the single definition of how sources become a loadable radiance
+# plugin, shared by the in-tree and out-of-tree builds.
 #
-# This file is included from two different worlds. The top-level CMakeLists.txt includes it while
-# the ABI target is being built in this very tree; the installed radiance-config.cmake includes it
-# after pulling the same target in as an import from radianceTargets.cmake. It is a file of its own
-# because a third party who runs find_package(radiance) needs it as much as the tree does: the
-# single call that decides what a plugin links, where it lands, and how its device sources reach
-# hipcc cannot be a private detail of radiance's own build, or every out-of-tree plugin has to
-# reinvent it by reading our CMakeLists.
-#
-# Copying the function into the package config instead is the worse option. Two copies of the rule
-# that fixes the plugin layout drift, and the drift does not present as a build error: it presents
-# as a plugin that loads in the tree it was written in and is silently absent everywhere else,
-# because it was emitted one directory level away from where the loader scans. So there is one
-# file, and both worlds include it.
+# The top-level CMakeLists.txt includes it while building the ABI target; the installed
+# radiance-config.cmake includes it after importing that target from radianceTargets.cmake. Keep
+# one copy: a drifted duplicate would emit plugins where the loader does not scan, with no build
+# error.
 #
 # What an includer must set first:
 #   radiance::abi      the ABI interface target -- an in-tree ALIAS, or the imported target
@@ -22,37 +13,30 @@
 #   RAD_GPU_TARGETS    the offload architectures this build targets. Any gfx name; a library that
 #                      serves only some of them narrows the list with rad_plugin_gpu_targets()
 #   RAD_HIP_RUNTIME    the amdhip64 library a device plugin links
-# The top-level file sets all five as it detects them. radiance-config.cmake sets all five from what
-# the install recorded, so that an out-of-tree plugin is compiled against the same runtime as the
-# engine that will dlopen it; its GPU targets are the consumer's to name (-DRAD_GPU_TARGETS) and
-# default to the ones the engine was built for.
+# The top-level file sets all five as it detects them. radiance-config.cmake sets them from what the
+# install recorded, so an out-of-tree plugin uses the engine's runtime; its GPU targets default to
+# the engine's and can be overridden with -DRAD_GPU_TARGETS.
 #
-# And one an includer MAY set:
+# Optional:
 #   RAD_PLUGIN_INSTALL_HOME  the $RADIANCE_HOME `cmake --install` puts a plugin under. Unset in
-#                      the tree, where a plugin installs beside the engine under the same prefix;
-#                      radiance-config.cmake sets it to the found installation's home, so a plugin
-#                      built out of tree installs where that engine's loader scans.
+#                      the tree (plugins install beside the engine under the same prefix);
+#                      radiance-config.cmake sets it to the found installation's home.
 #   RAD_HIP_VOPD_REPEATABLE  ON when the HIP compiler's VOPD pairing is repeatable; unset is OFF,
 #                      which turns the pairing off on LLVM 24 (rad_hip_repeatable, below).
 
-# For CMAKE_INSTALL_DATADIR, below. Idempotent, and included here rather than left to the includer
-# because this file is what needs it: a consumer project has no reason to have included it, and the
-# install destination would silently become the relative path "radiance/kernels" -- interpreted
-# against the prefix, so it lands in /radiance/kernels and the loader never looks there.
+# For CMAKE_INSTALL_DATADIR. Included here because a consumer may not have; without it plugins
+# would install to /radiance/, where the loader never looks.
 include(GNUInstallDirs)
 
-# What radiance's own tree sets for every plugin it builds, for a plugin built on its own against
-# an installed radiance: C++20, and a build type that optimises when none was asked for. Every
-# plugin directory in radiance's tree opens with the same few lines a third party's does --
+# The tree's defaults for a plugin built standalone: C++20 and an optimised build type when none was
+# given. Every plugin directory, in tree or not, opens with:
 #
-#   if(NOT COMMAND rad_add_plugin)          # on its own, not inside radiance's tree
+#   if(NOT COMMAND rad_add_plugin)          # standalone, not inside radiance's tree
 #     cmake_minimum_required(VERSION 3.21)
 #     project(mylib LANGUAGES CXX)          # CXX HIP for device code
 #     find_package(radiance REQUIRED)
 #     rad_plugin_defaults()
 #   endif()
-#
-# -- so the libraries radiance ships are built and installed exactly as anyone else's are.
 macro(rad_plugin_defaults)
   if(NOT CMAKE_CXX_STANDARD)
     set(CMAKE_CXX_STANDARD 20)
@@ -63,10 +47,24 @@ macro(rad_plugin_defaults)
   endif()
 endmacro()
 
-# A kernel, architecture or quantiser plugin: one call, so a new plugin is a directory and a line.
-# `kind` is the $RADIANCE_HOME directory the engine scans for it. An installed plugin must name one
-# of the three the engine scans -- a misspelt kind would build, install, and never be loaded; the
-# test plugins, which are never installed (RAD_PLUGIN_INSTALL below), use directories of their own.
+# CMake leaves two HIP rule variables empty. Without CMAKE_DEPFILE_FLAGS_HIP, Ninja records no
+# header as a dependency of a .hip object (`ninja -t deps` shows #deps 0), so editing a header
+# relinks a plugin around stale objects, which can leave engine and plugin disagreeing on a
+# signature. Without CMAKE_INCLUDE_SYSTEM_FLAG_HIP, SYSTEM include directories reach .hip sources as
+# `-I` and their warnings become ours. A macro, so the variables land in the caller's scope; values
+# already set are kept.
+macro(rad_hip_rule_fixes)
+  if(NOT CMAKE_DEPFILE_FLAGS_HIP)
+    set(CMAKE_DEPFILE_FLAGS_HIP "-MD -MT  -MF ")
+  endif()
+  if(NOT CMAKE_INCLUDE_SYSTEM_FLAG_HIP)
+    set(CMAKE_INCLUDE_SYSTEM_FLAG_HIP "-isystem ")
+  endif()
+endmacro()
+
+# Build a kernel, architecture or quantiser plugin. `kind` is the $RADIANCE_HOME directory the engine
+# scans for it; an installed plugin must use one of the three, or it would never be loaded. Test
+# plugins (never installed, see RAD_PLUGIN_INSTALL) use their own directories.
 function(rad_add_plugin name kind)
   cmake_parse_arguments(P "" "" "SOURCES;HIP_SOURCES;LIBS;INCLUDES;GPU_TARGETS" ${ARGN})
   if((NOT DEFINED RAD_PLUGIN_INSTALL OR RAD_PLUGIN_INSTALL) AND
@@ -77,37 +75,29 @@ function(rad_add_plugin name kind)
   endif()
   set(srcs ${P_SOURCES})
   if(P_HIP_SOURCES AND NOT RAD_HIP_FOUND)
-    # Said rather than skipped in silence: a kernel library whose device sources were dropped
-    # builds, installs, and has rows with no kernels behind them.
+    # Warn: a kernel library without its device sources still installs, with rows that have no
+    # kernels behind them.
     message(WARNING
       "rad_add_plugin(${name}) was given HIP_SOURCES but this radiance has no device build "
       "(RAD_HIP_FOUND is OFF), so they are left out. A radiance configured without ROCm, or on a "
       "machine with no card and no -DRAD_GPU_TARGETS, has none.")
   endif()
   if(RAD_HIP_FOUND AND P_HIP_SOURCES)
-    # The HIP language has to be enabled by the project that owns the target, not by us:
-    # enable_language() is a project-scope decision and a library file that reaches out and enables
-    # a language behind the consumer's back changes their compiler set. In-tree the top-level file
-    # does it. Out-of-tree it is one line in the consumer's CMakeLists, and the failure without it
-    # is "Cannot find source file" or a source compiled as C++ with --offload-arch on the command
-    # line, neither of which names the missing enable_language(HIP).
+    # The owning project must enable HIP itself; enable_language() is project scope and changes the
+    # consumer's compiler set. Without it CMake fails with errors that do not name the cause, so
+    # check here.
     get_property(_rad_langs GLOBAL PROPERTY ENABLED_LANGUAGES)
     if(NOT "HIP" IN_LIST _rad_langs)
       message(FATAL_ERROR
         "rad_add_plugin(${name}) was given HIP_SOURCES but the HIP language is not enabled in this "
-        "project. Add `enable_language(HIP)` after project() -- radiance cannot enable it for you, "
-        "because the language a project compiles in is the project's own decision.")
+        "project. Add `enable_language(HIP)` after project(); the project must enable it itself.")
     endif()
     set_source_files_properties(${P_HIP_SOURCES} PROPERTIES LANGUAGE HIP)
-    # EVERY DEVICE SOURCE NAMES ITS OWN COMPILATION UNIT ID, from the plugin's name and the
-    # source's path inside the plugin's directory. Left to clang, the ID is a hash of the absolute
-    # input path, the output path and the command line, so one source built in two directories --
-    # the tree and an out-of-tree build of the same plugin -- gets two IDs. The ID becomes a symbol
-    # (__hip_cuid_) whose name is not of fixed length, and a longer one shifts the code
-    # object's read-only data and with it every PC-relative address .text forms into it: the same
-    # instructions, different bytes. Named from what identifies the unit and nothing about where it
-    # was built, the ID is the same wherever the plugin is built and still differs between any two
-    # sources, which is the property clang needs of it.
+    # Each device source gets a compilation unit ID from the plugin name and its relative path.
+    # clang's default hashes absolute paths and the command line, and the resulting
+    # __hip_cuid_ symbol has variable length, which shifts read-only data and every
+    # PC-relative address into it. A location-independent ID keeps code objects identical wherever
+    # the plugin is built, while still unique per source.
     foreach(src ${P_HIP_SOURCES})
       get_filename_component(_rad_abs "${src}" ABSOLUTE)
       file(RELATIVE_PATH _rad_rel "${CMAKE_CURRENT_SOURCE_DIR}" "${_rad_abs}")
@@ -120,11 +110,8 @@ function(rad_add_plugin name kind)
   add_library(${name} MODULE ${srcs})
   target_link_libraries(${name} PRIVATE radiance::abi ${P_LIBS})
   target_include_directories(${name} PRIVATE ${P_INCLUDES})
-  # The build tree is a working $RADIANCE_HOME, and it is created here rather than assumed: a
-  # LIBRARY_OUTPUT_DIRECTORY that does not exist is created by the build, but the engine scans the
-  # directory at startup and an out-of-tree build with one kernel plugin and no architectures would
-  # otherwise have no architectures/ for the scan to find and fail at the scan rather than at the
-  # lookup.
+  # The build tree is a working $RADIANCE_HOME. Create the kind directory at configure time: the
+  # engine scans it at startup, and a missing one fails the scan rather than the lookup.
   file(MAKE_DIRECTORY ${RAD_PLUGIN_OUT}/${kind})
   set_target_properties(${name} PROPERTIES
     PREFIX "" OUTPUT_NAME "${name}"
@@ -133,16 +120,9 @@ function(rad_add_plugin name kind)
     rad_hipify(${name} ${P_GPU_TARGETS})
   endif()
 
-  # ...and so is the install tree, in the same shape. RAD_DEFAULT_HOME points at
-  # /share/radiance, and without this rule nothing is installed into it, so the only
-  # $RADIANCE_HOME that works is somebody's build directory. A plugin built and not installed is the
-  # same class of defect as a plugin built and never loaded.
-  #
-  # RAD_PLUGIN_INSTALL is the opt-out, and it has exactly one in-tree user: core/plugin/testplugin
-  # (set in core/CMakeLists.txt, where that subtree is reached), whose .so files exist to be
-  # refused, to conflict, to report a stale ABI and to stand in for a card. Shipping those
-  # into a prefix would put rows into a real installation that implement nothing -- see the same
-  # argument, made about the build tree, in core/plugin/testplugin/CMakeLists.txt.
+  # The install tree has the same shape, under RAD_DEFAULT_HOME (/share/radiance).
+  # RAD_PLUGIN_INSTALL=OFF opts out; its only in-tree user is core/plugin/testplugin (set in
+  # core/CMakeLists.txt), whose plugins must never reach a real installation.
   if(NOT DEFINED RAD_PLUGIN_INSTALL)
     set(RAD_PLUGIN_INSTALL ON)
   endif()
@@ -156,18 +136,15 @@ function(rad_add_plugin name kind)
   endif()
 endfunction()
 
-# REPEATABLE DEVICE CODE ON LLVM 24. ROCm 10.1's clang (AMD clang 24) does not compile the same
-# source to the same code twice. Its post-RA scheduler pairs VALU instructions for dual issue
-# (VOPD), and the pairing pass (GCNVOPDUtils.cpp) caches each load's transitive load dependencies;
-# fusing a pair adds edges behind that cache, and which entries were cached before a fusion
-# follows the iteration order of a pointer-keyed set -- heap addresses. So every compile can pair
-# differently: r4d_hc_bf16.hip came out with a different .text on each of three builds, a kernel's
-# speed depends on which build it came from, and no comparison between two builds can be trusted.
-# LLVM 22 (ROCm 7.2) pairs without that cache and is repeatable.
+# Repeatable device code on LLVM 24. ROCm 10.1's clang (AMD clang 24) is not deterministic: the
+# post-RA VOPD pairing pass (GCNVOPDUtils.cpp) caches each load's transitive load dependencies, a
+# fusion adds edges behind that cache, and which entries are cached follows the iteration order of
+# a pointer-keyed set. So two compiles can pair differently, giving different .text and speed.
+# LLVM 22 (ROCm 7.2) has no such cache and is repeatable.
 #
-# The image builds its compiler's libLLVM with the cache dropped after every fusion
-# (docker/llvm-vopd-pairing.patch) and says so with RAD_HIP_VOPD_REPEATABLE=ON. Any other LLVM 24
-# has the pairing turned off: repeatable, at a price -- 1.4 to 3.5% on the fp8 prefill tiles.
+# The docker image patches libLLVM to drop the cache after every fusion
+# (docker/llvm-vopd-pairing.patch) and sets RAD_HIP_VOPD_REPEATABLE=ON. Any other LLVM 24 gets VOPD
+# disabled, which costs 1.4 to 3.5% on the fp8 prefill tiles.
 function(rad_hip_repeatable tgt)
   if(CMAKE_HIP_COMPILER_ID STREQUAL "Clang" AND CMAKE_HIP_COMPILER_VERSION VERSION_GREATER_EQUAL 24
      AND NOT RAD_HIP_VOPD_REPEATABLE)
@@ -175,29 +152,23 @@ function(rad_hip_repeatable tgt)
   endif()
 endfunction()
 
-# Mark a target's device sources as HIP and pin the architecture. -ffp-contract=off is mandatory
-# for any quantised cross-rank op: two ranks see the two dequantised products in the opposite order
-# and contracting either into an FMA makes them disagree by ~1 ULP, which breaks the
-# replicated-state invariant.
+# Set a target's HIP architectures and device flags. -ffp-contract=off is mandatory for any
+# quantised cross-rank op: two ranks sum the dequantised products in opposite order, and an FMA on
+# either side makes them differ by ~1 ULP, breaking the replicated-state invariant.
 function(rad_hipify tgt)
-  # Any extra arguments are the architectures THIS target is compiled for, which is how a library
-  # that serves one generation stays out of the build for the others. With none given the target
-  # takes the whole build's list.
+  # Extra arguments narrow the architectures for this target; default is RAD_GPU_TARGETS.
   set(arches "${ARGN}")
   if(NOT arches)
     set(arches "${RAD_GPU_TARGETS}")
   endif()
   set_target_properties(${tgt} PROPERTIES HIP_ARCHITECTURES "${arches}")
   target_compile_options(${tgt} PRIVATE $<$:-ffp-contract=off>)
-  # THE DEVICE OPTIMISATION LEVEL, ON THE TARGET, because CMake supplies no usable one for HIP:
-  # depending on its version CMAKE_HIP_FLAGS_ is empty -- the kernels compile at -O0 with
-  # asserts live -- or the host-style '-O2 -g'. The top-level CMakeLists.txt sets the variables for
-  # the tree; a plugin built out of tree gets the same levels here, after the toolchain's flags on
-  # the command line, so they win. A later -O replaces an earlier one but a later -O does not undo
-  # -g, so the levels outside Debug end in -g0: device debug info costs compile time, inhibits
-  # scheduling, and makes an out-of-tree build's code objects differ from the tree's. NDEBUG is not
-  # decoration on the device: an assert is a hostcall, and the engine's queues provide no hostcall
-  # buffer (docs/PLUGIN.md). RAD_HIP_FLAGS_ overrides, as it does in the tree.
+  # Device optimisation level, set on the target because CMake's CMAKE_HIP_FLAGS_ is,
+  # depending on version, empty (-O0 with asserts) or host-style '-O2 -g'. These come after the
+  # toolchain flags, so they win. Non-Debug levels end in -g0 because a later -O does not undo -g,
+  # and device debug info slows compiles, inhibits scheduling and changes code objects. NDEBUG is
+  # required: a device assert is a hostcall, and the engine's queues have no hostcall buffer
+  # (docs/PLUGIN.md). RAD_HIP_FLAGS_ overrides, as in the tree.
   foreach(cfg DEBUG RELEASE RELWITHDEBINFO MINSIZEREL)
     if(RAD_HIP_FLAGS_${cfg})
       set(lvl "${RAD_HIP_FLAGS_${cfg}}")
@@ -211,24 +182,17 @@ function(rad_hipify tgt)
     separate_arguments(lvl)
     target_compile_options(${tgt} PRIVATE "$<$,$>:${lvl}>")
   endforeach()
-  # AN UNCOMPRESSED FAT BINARY, because the engine reads the code object out of it itself
-  # (core/device/aql_code.cpp) and refuses a compressed one -- at the first launch, as a kernel
-  # failure. A toolchain or a CMAKE_HIP_FLAGS that turns compression on is overridden here.
+  # Uncompressed fat binary: the engine extracts the code object itself (core/device/aql_code.cpp)
+  # and rejects a compressed one at first launch. This overrides any toolchain setting.
   target_compile_options(${tgt} PRIVATE $<$:--no-offload-compress>)
   target_link_options(${tgt} PRIVATE $<$:--no-offload-compress>)
   target_link_libraries(${tgt} PRIVATE ${RAD_HIP_RUNTIME})
   rad_hip_repeatable(${tgt})
 endfunction()
 
-# Narrow RAD_GPU_TARGETS to the architectures ONE kernel library actually serves. A library states
-# its coverage as regular expressions -- "^gfx12" for a generation, "^gfx1201$" for a single chip --
-# and gets back the intersection with what this build is targeting, which may be empty.
-#
-# AN EMPTY RESULT IS NOT AN ERROR. It means this build's cards are served by some other kernel
-# library, and the right response is for the plugin to skip itself and say so, leaving the rest of
-# the tree to configure normally. A kernel library that failed the configure instead would make
-# every card it does not cover an unbuildable project rather than an unserved one -- which is the
-# opposite of what a plugin boundary is for.
+# Narrow RAD_GPU_TARGETS to the architectures one kernel library serves, given as regular
+# expressions ("^gfx12" for a generation, "^gfx1201$" for a chip). The result may be empty; the
+# plugin should then skip itself with a message rather than fail the configure.
 function(rad_plugin_gpu_targets out)
   set(keep "")
   foreach(t ${RAD_GPU_TARGETS})
diff --git a/cmake/radiance-config.cmake.in b/cmake/radiance-config.cmake.in
index 30f694fb..7beddc11 100644
--- a/cmake/radiance-config.cmake.in
+++ b/cmake/radiance-config.cmake.in
@@ -1,9 +1,7 @@
 # radiance-config.cmake -- what `find_package(radiance)` gets.
 #
-# This file exists so that a plugin can be built from a repository that is not this one, against
-# the installed ABI headers rather than a copy of abi/ taken out of a checkout, and installed into
-# the $RADIANCE_HOME the engine's loader scans. A plugin boundary that can only be crossed from
-# inside the tree is not a plugin boundary; it is a build layout.
+# Lets a plugin in another repository build against the installed ABI headers and install into
+# the $RADIANCE_HOME the engine's loader scans.
 #
 # What a consumer gets:
 #   radiance::abi              the header-only ABI target -- abi/ plus RAD_DEFAULT_HOME,
@@ -21,49 +19,39 @@
 #                              target (arch/common/ is installed under ${RADIANCE_INCLUDE_DIR}/arch)
 #   RAD_GPU_TARGETS            the offload architectures a device plugin is compiled for: the
 #                              consumer's -DRAD_GPU_TARGETS when given, else the ones radiance was
-#                              built for. The engine itself runs on every AMD GPU family, so a
-#                              plugin for a card the engine's build machine does not have is
-#                              ordinary.
+#                              built for. The engine itself runs on every AMD GPU family.
 
 @PACKAGE_INIT@
 
-# The ABI version is not written here; it is read out of abi/rad_abi.h at radiance's
-# configure time and carried through. One number, in the header the loader compares against, so a
-# bump cannot be half-applied.
+# Read from abi/rad_abi.h at radiance's configure time, so the header stays the single source.
 set(RADIANCE_ABI_VERSION @RAD_ABI_VERSION@)
 
 set_and_check(RADIANCE_INCLUDE_DIR "@PACKAGE_RAD_INCLUDE_RELDIR@")
 
-# $RADIANCE_HOME, as a CACHE PATH so that a consumer building a plugin for an installed engine can
-# see and override where it is going in ccmake, and so that `cmake --install` on their project puts
-# the .so where this engine's loader will scan for it. Computed from PACKAGE_PREFIX_DIR rather than
-# baked absolute, so a relocated prefix still answers correctly.
+# $RADIANCE_HOME as a CACHE PATH, so a consumer can override it. Relative to PACKAGE_PREFIX_DIR, so
+# a relocated prefix still resolves.
 set(RADIANCE_HOME "@PACKAGE_RAD_HOME_RELDIR@" CACHE PATH
     "\$RADIANCE_HOME of the radiance installation found by find_package(radiance)")
 set(RADIANCE_KERNELS_DIR       "${RADIANCE_HOME}/kernels")
 set(RADIANCE_ARCHITECTURES_DIR "${RADIANCE_HOME}/architectures")
 set(RADIANCE_QUANTIZERS_DIR    "${RADIANCE_HOME}/quantizers")
-# Where rad_add_plugin installs: under the home of the engine this consumer built against, which is
-# the one whose loader will scan it. A consumer installing somewhere else -- a home of its own on
-# $RADIANCE_HOME's search path, say -- sets this.
+# Where rad_add_plugin installs: the home of the engine this consumer built against. Override to
+# install elsewhere.
 set(RAD_PLUGIN_INSTALL_HOME "${RADIANCE_HOME}" CACHE PATH
     "the \$RADIANCE_HOME rad_add_plugin installs plugins under")
 
-# The imported targets: radiance::abi, and whatever else the export set carries.
+# The imported targets, including radiance::abi.
 include("${CMAKE_CURRENT_LIST_DIR}/radianceTargets.cmake")
 
-# The device-build facts rad_add_plugin needs, recorded at radiance's configure time and replayed
-# here under the same names the in-tree build uses -- one function body, one set of variable names.
-# A plugin compiled for a different gfx target than the engine that dlopens it is not a link error
-# and not a load error: it is a kernel that launches and computes garbage, so the target list is
-# carried across rather than re-detected.
+# Device-build facts rad_add_plugin needs, recorded at radiance's configure time under the in-tree
+# names. The target list is carried over, not re-detected: a plugin built for the wrong gfx target
+# loads and launches, then computes garbage.
 set(RAD_HIP_FOUND    @RAD_HIP_FOUND@)
 if(NOT DEFINED RAD_GPU_TARGETS)
   set(RAD_GPU_TARGETS "@RAD_GPU_TARGETS@")
 endif()
-# The HIP runtime and headers as radiance found them, and where this machine has them when the
-# recorded path is not here -- a consumer building against an installed radiance on another
-# machine, or inside a container whose ROCm sits elsewhere.
+# The HIP runtime and headers as radiance found them, or this machine's copies when the recorded
+# path does not exist (another machine, or a container with ROCm elsewhere).
 set(RAD_HIP_RUNTIME  "@RAD_HIP_RUNTIME@")
 if(RAD_HIP_FOUND)
   if(NOT EXISTS "${RAD_HIP_RUNTIME}")
@@ -81,24 +69,17 @@ if(RAD_HIP_FOUND)
     set_property(TARGET radiance::abi APPEND PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${_rad_rocm_inc}")
     set_property(TARGET radiance::abi APPEND PROPERTY INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "${_rad_rocm_inc}")
   endif()
-  # The HIP compiler's two omissions the tree fixes for itself (CMakeLists.txt): no depfile, so no
-  # header is a dependency of a .hip object, and no system-include flag. Only where unset.
-  if(NOT CMAKE_DEPFILE_FLAGS_HIP)
-    set(CMAKE_DEPFILE_FLAGS_HIP "-MD -MT  -MF ")
-  endif()
-  if(NOT CMAKE_INCLUDE_SYSTEM_FLAG_HIP)
-    set(CMAKE_INCLUDE_SYSTEM_FLAG_HIP "-isystem ")
-  endif()
 endif()
 
-# The build-tree $RADIANCE_HOME for the CONSUMER's build, so that a freshly built out-of-tree plugin
-# can be exercised with RADIANCE_HOME=/radiance_home before it is installed --
-# which is how an in-tree plugin is tested, and there is no reason the boundary should make that
-# harder. Not forced: a consumer who has already set it keeps their own.
+# The consumer's build-tree $RADIANCE_HOME, so a plugin can be tested with
+# RADIANCE_HOME=/radiance_home before install. A value already set is kept.
 if(NOT DEFINED RAD_PLUGIN_OUT)
   set(RAD_PLUGIN_OUT ${CMAKE_BINARY_DIR}/radiance_home)
 endif()
 
 include("${CMAKE_CURRENT_LIST_DIR}/RadAddPlugin.cmake")
+if(RAD_HIP_FOUND)
+  rad_hip_rule_fixes()
+endif()
 
 check_required_components(radiance)
diff --git a/core/CMakeLists.txt b/core/CMakeLists.txt
index 738548ad..892bcf3d 100644
--- a/core/CMakeLists.txt
+++ b/core/CMakeLists.txt
@@ -1,8 +1,8 @@
-# One static library. The engine is monolithic on purpose (spec §head): the plugin boundary is
-# where substitution happens, and inside it there is nothing to gain from .so seams.
+# One static library. The engine is monolithic on purpose (spec §head): substitution happens at the
+# plugin boundary, so .so seams inside it buy nothing.
 #
-# Sources are globbed per subdirectory with CONFIGURE_DEPENDS so that adding a file to a component
-# does not mean editing a file another component owns. Re-run cmake if a new file does not appear.
+# Sources are globbed per subdirectory with CONFIGURE_DEPENDS. Re-run cmake if a new file does not
+# appear.
 set(RAD_CORE_DIRS util device plugin build runtime mem sched place sample text server format mm diag gen)
 
 set(RAD_CORE_SRC "")
@@ -12,10 +12,9 @@ foreach(d ${RAD_CORE_DIRS})
        ${CMAKE_CURRENT_SOURCE_DIR}/${d}/*.c)
   list(APPEND RAD_CORE_SRC ${_s})
 endforeach()
-# The top level, MINUS main.cpp. main() belongs to the `radiance` executable and not to the
-# library: with the archive linked whole -- which every host of an architecture plugin must do, see
-# tools/CMakeLists.txt -- a main() inside it collides with each tool's own. A plain archive link
-# hides this, because the tools reference nothing in main.cpp.o and the linker skips it.
+# The top level minus main.cpp, which belongs to the `radiance` executable. Every architecture plugin
+# host links the archive whole (tools/CMakeLists.txt), so a main() inside it would collide with each
+# tool's own.
 file(GLOB _top CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp)
 list(REMOVE_ITEM _top ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp)
 list(APPEND RAD_CORE_SRC ${_top})
@@ -40,43 +39,36 @@ endif()
 if(RAD_HIP_FOUND)
   target_compile_definitions(rad_core PUBLIC RAD_HAVE_HIP=1)
   target_link_libraries(rad_core PUBLIC ${RAD_HIP_RUNTIME} ${RAD_HSA_RUNTIME})
-  # AN EXECUTABLE RUNS THE ROCm IT WAS BUILT AGAINST. The runtime is linked by its full path, but the
-  # HIP driver reports that directory among its implicit link directories, so CMake writes no RPATH
-  # for it: the engine, the tools and the tests loaded whichever libamdhip64.so.7 the system's loader
-  # cache names, and a tree built against a second ROCm beside /opt/rocm ran /opt/rocm's runtime
-  # under its own kernels. A linker flag and not CMake's RPATH, because install rewrites CMake's, and
-  # rewriting it beside the entry ROCm 10's clang gives a shared library left an empty element -- the
-  # current directory -- in the installed plugin.
+  # Run the ROCm the tree was built against. The HIP driver reports the runtime's directory as an
+  # implicit link directory, so CMake writes no RPATH for it and the loader cache would pick the
+  # system's libamdhip64.so.7. A linker flag instead of CMake's RPATH, because install rewrites the
+  # latter and, next to ROCm 10 clang's entry, leaves an empty element (the current directory).
   get_filename_component(RAD_HIP_LIBDIR "${RAD_HIP_RUNTIME}" DIRECTORY)
   target_link_options(rad_core INTERFACE "LINKER:-rpath,${RAD_HIP_LIBDIR}")
-  # THE AQL BACKEND'S OWN KERNELS: the copies and fills it dispatches for rad_memcpy_async and
-  # rad_memset_async.
+  # AQL backend kernels: the copies and fills behind rad_memcpy_async and rad_memset_async.
   target_sources(rad_core PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/device/aql_blit.hip)
   set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/device/aql_blit.hip PROPERTIES LANGUAGE HIP)
-  # THE STEP'S OWN BOOKKEEPING ON THE CARD: acceptance and the next pass's positions (sched/advance.h).
+  # Step bookkeeping on the card: acceptance and the next pass's positions (sched/advance.h).
   target_sources(rad_core PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/sched/advance.hip)
   set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/sched/advance.hip PROPERTIES LANGUAGE HIP)
-  # WEIGHT-TABLE ENTRIES WRITTEN IN STREAM ORDER, their values carried in the arguments (runtime/wtab.h).
+  # Weight-table entries written in stream order, values passed as arguments (runtime/wtab.h).
   target_sources(rad_core PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/runtime/wtab.hip)
   set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/runtime/wtab.hip PROPERTIES LANGUAGE HIP)
-  # THE NEXT-LAYER EXPERT PREFETCH's prediction, plan and table patches (runtime/xprefetch.h).
+  # Next-layer expert prefetch: prediction, plan and table patches (runtime/xprefetch.h).
   target_sources(rad_core PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/runtime/xprefetch.hip)
   set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/runtime/xprefetch.hip PROPERTIES LANGUAGE HIP)
-  # THE CORE'S OWN KERNELS ARE BUILT FOR EVERY AMD GPU FAMILY, not only for the cards this build
-  # targets. They are what every copy and fill on a card runs, so an engine without a code object
-  # for a card cannot start on it -- whatever kernel plugin is installed for that card, and a plugin
-  # for a card the build machine does not have is exactly what a third party ships. The generic
-  # targets cost three small files a family; the loader prefers the exact chip where both exist
-  # (core/device/aql_code.cpp), so a targeted card still runs code built for it.
+  # Core kernels are built for every AMD GPU family, not only RAD_GPU_TARGETS: every copy and fill
+  # runs them, so without a code object the engine cannot start on a card even when a third-party
+  # kernel plugin supports it. The loader prefers the exact chip when both exist
+  # (core/device/aql_code.cpp).
   set(RAD_CORE_GPU_TARGETS ${RAD_GPU_TARGETS}
       gfx9-generic gfx9-4-generic gfx10-1-generic gfx10-3-generic gfx11-generic gfx12-generic)
   list(REMOVE_DUPLICATES RAD_CORE_GPU_TARGETS)
   set_target_properties(rad_core PROPERTIES HIP_ARCHITECTURES "${RAD_CORE_GPU_TARGETS}")
   rad_hip_repeatable(rad_core)
-  # EVERY EXECUTABLE THAT LINKS THE CORE EXPORTS THE HIP ENTRY POINTS THE BACKEND DEFINES. A kernel
-  # plugin is dlopen'ed and its hipLaunchKernel binds to the first definition in the global scope,
-  # which is the executable's only if the executable exports it. Without this a plugin would launch
-  # through HIP onto a queue HIP does not own; aql.cpp checks at startup and refuses to run.
+  # Executables linking the core export the HIP entry points the backend defines, so a dlopen'ed
+  # kernel plugin binds to them instead of real HIP (which does not own the queues). aql.cpp checks
+  # this at startup and refuses to run without it.
   foreach(sym hipLaunchKernel hipMemcpy2DAsync hipMemcpyAsync hipMemsetAsync hipMemset hipStreamSynchronize
               hipEventRecord hipStreamWaitEvent hipGetLastError hipPeekAtLastError
               __hipRegisterFatBinary __hipRegisterFunction __hipUnregisterFatBinary)
@@ -89,28 +81,18 @@ if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp)
   add_executable(radiance main.cpp)
   target_link_libraries(radiance PRIVATE "$")
   # ENABLE_EXPORTS: the architecture plugin binds the declare-phase C ABI back to this binary at
-  # dlopen. See the same note in tools/CMakeLists.txt.
+  # dlopen (tools/CMakeLists.txt).
   set_target_properties(radiance PROPERTIES
     RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
     ENABLE_EXPORTS ON)
-  # Installed beside the tools, so a prefix that holds rad-convert and rad-kbench also holds the
-  # binary they exist to feed. RUNTIME and not a bare DESTINATION so that ENABLE_EXPORTS -- which
-  # is what lets an architecture plugin bind the declare-phase C ABI back to this binary at
-  # dlopen, see the note above -- is carried by the same rule that carries the executable.
+  # Installed beside the tools. RUNTIME rather than a bare DESTINATION, so the rule that carries
+  # the executable also carries ENABLE_EXPORTS.
   install(TARGETS radiance RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
 endif()
 
-# The plugin layer's test plugins. They are .so files rather than part of rad_core, so they need a
-# CMakeLists of their own -- and it needs to be reached. (Owned by core/plugin/.)
+# The plugin layer's test plugins (.so files, so they need their own CMakeLists).
 #
-# RAD_PLUGIN_INSTALL=OFF for that whole subtree, and this is the one place in the build that turns
-# it off. rad_add_plugin installs what it builds, because a plugin that is built and not installed
-# leaves $RADIANCE_HOME working only when it points at a build directory. But the .so files under
-# core/plugin/testplugin exist only for tests -- to be refused, to conflict with each other, to
-# report a stale ABI, or to stand in for a card in one test -- and none is a kernel a real run may
-# select. Shipping those into a real prefix is the same mistake testplugin/CMakeLists.txt already
-# refuses to make in the build tree -- "a test plugin that a real run could select is a fallback
-# nobody knows about" -- so the opt-out is set here, where the subtree is reached, rather than in a
-# file that component owns.
+# RAD_PLUGIN_INSTALL=OFF for this subtree only. rad_add_plugin normally installs what it builds,
+# but these plugins exist only for tests and must never be selectable from a real prefix.
 set(RAD_PLUGIN_INSTALL OFF)
 add_subdirectory(plugin)
diff --git a/core/build/rad_bufplan.cpp b/core/build/rad_bufplan.cpp
index 0693a4a0..c8c43e08 100644
--- a/core/build/rad_bufplan.cpp
+++ b/core/build/rad_bufplan.cpp
@@ -1,19 +1,16 @@
 /* rad_bufplan.cpp -- the buffer plan (spec §3.1).
  *
  * Activations are declared, liveness is computed over the declared op list, and non-overlapping
- * lifetimes are packed into one arena sized once. The alternative is an allocator on the hot
- * path, and an allocator on the hot path is the thing this engine exists to remove.
+ * lifetimes are packed into one arena sized once, so the hot path never allocates.
  *
- * Two conservatisms are deliberate and both are stated in the spec: the arena is sized for
- * max_tok, and liveness is computed over the declared list, which is a superset of what any given
- * step issues. A plan that is correct for the worst step is correct for every step.
+ * Two deliberate conservatisms (both in the spec): the arena is sized for max_tok, and liveness
+ * covers the declared list, a superset of what any step issues. A plan correct for the worst step
+ * is correct for every step.
  *
- * The packer is greedy interval colouring, largest first: for each buffer in descending size
- * order, take the lowest aligned offset that collides with no already-placed buffer whose
- * lifetime overlaps. It is O(n^2) in the buffer count at declare, which for a few hundred
- * activations is microseconds, and it is within a few percent of optimal on the shapes that
- * matter -- the one big activation is placed first and everything else fills in around it.
- * Optimal packing here is NP-hard and the difference is not worth a solver.
+ * The packer is greedy interval colouring, largest first: each buffer takes the lowest aligned
+ * offset that collides with no placed buffer whose lifetime overlaps. O(n^2) in the buffer count,
+ * microseconds for a few hundred activations, and within a few percent of optimal on real shapes
+ * (the one big activation goes first). Optimal packing is NP-hard and not worth a solver.
  */
 #include "rad_build.h"
 #include "rad_internal.h"
@@ -23,13 +20,11 @@
 
 namespace rad {
 
-/* Every buffer starts at a 256-byte boundary: the container's sub-block alignment, and wide
- * enough for any vector load an RDNA4 kernel issues (dwordx4 is 16 B). A kernel that needs more
- * than this from its scratch says so through its scratch hook, which is sized separately. */
+/* Every buffer starts at a 256-byte boundary: the container's sub-block alignment, and enough for
+ * any RDNA4 vector load (dwordx4 is 16 B). A kernel needing more alignment for its scratch says so
+ * through its scratch hook, which is sized separately. */
 static constexpr int64_t kBufAlign = (int64_t)RAD_ALIGN_SUB;
 
-#include 
-
 namespace {
 
 struct Item {
@@ -41,8 +36,8 @@ struct Item {
 
 bool overlaps(const Item& a, const Item& b) { return a.lo <= b.hi && b.lo <= a.hi; }
 
-/* Lowest aligned offset at or above 0 that fits `need` bytes without colliding with anything in
- * `placed` that is alive at the same time. */
+/* Lowest aligned offset that fits `want` without colliding with anything already placed
+ * (off >= 0) that is alive at the same time. */
 int64_t first_fit(const Item& want, const std::vector& placed) {
     std::vector> occ;
     occ.reserve(placed.size());
@@ -58,6 +53,22 @@ int64_t first_fit(const Item& want, const std::vector& placed) {
     return off;
 }
 
+/* Places every item, largest first, ties by lifetime start then index, so the plan is identical
+ * on every rank and every run. Returns the packed extent. */
+int64_t pack(std::vector& items) {
+    std::sort(items.begin(), items.end(), [](const Item& a, const Item& b) {
+        if (a.bytes != b.bytes) return a.bytes > b.bytes;
+        if (a.lo != b.lo) return a.lo < b.lo;
+        return a.idx < b.idx;
+    });
+    int64_t end = 0;
+    for (Item& it : items) {
+        it.off = first_fit(it, items);
+        end = std::max(end, it.off + it.bytes);
+    }
+    return end;
+}
+
 }  /* namespace */
 
 int plan_buffers(Program& p, BufPlanReport* rep) {
@@ -79,50 +90,35 @@ int plan_buffers(Program& p, BufPlanReport* rep) {
 
         Item it{ i, align_up(b.bytes, kBufAlign), b.first_def, b.last_use };
         if (it.lo < 0 || it.hi < it.lo) {
-            /* Live for the whole program: the sound assumption when nothing declared a use. */
+            /* No declared use: live for the whole program. */
             it.lo = 0;
             it.hi = last_op > 0 ? last_op : 0;
             if (b.decl.kind == RAD_BUF_TRANSIENT) ++r.n_unknown_live;
         }
 
-        /* The two domains are coloured SEPARATELY and each offset is relative to its own arena.
-         * A host-site activation cannot index device memory, so interleaving them in one offset
-         * space would leave both arenas sparse -- correct, and paying VRAM for host activations.
+        /* Each domain is coloured separately, with offsets relative to its own arena. One shared
+         * offset space would leave both arenas sparse and spend VRAM on host activations.
          * Program::arena_bytes is the device high-water mark, host_arena_bytes the host one. */
         if (b.decl.domain == RAD_DOMAIN_HOST) host.push_back(it);
         else if (b.decl.kind == RAD_BUF_TRANSIENT) transient.push_back(it);
         else persist.push_back(it);
     }
 
-    /* Largest first, ties broken by lifetime start and then by index, so the plan is the same on
-     * every rank and every run -- a placement that varies between ranks is a debugging nightmare
-     * for a bug that only shows up as a numerical difference. */
-    auto by_size = [](const Item& a, const Item& b) {
-        if (a.bytes != b.bytes) return a.bytes > b.bytes;
-        if (a.lo != b.lo) return a.lo < b.lo;
-        return a.idx < b.idx;
-    };
-    std::sort(transient.begin(), transient.end(), by_size);
-    std::sort(host.begin(), host.end(), by_size);
-
     for (const Item& t : transient) r.sum_bytes += t.bytes;
 
-    /* peak_live is what a perfect packer would reach, so the pair (peak_live, transient_bytes)
-     * brackets the arena and says whether the greedy pass left anything on the table. */
+    /* peak_live: what a perfect packer would reach (see BufPlanReport). */
     for (int32_t t = 0; t <= std::max(last_op, 0); ++t) {
         int64_t live = 0;
         for (const Item& it : transient) if (it.lo <= t && t <= it.hi) live += it.bytes;
         r.peak_live = std::max(r.peak_live, live);
     }
 
-    /* PERSIST survives across steps and DERIVED is written once per step by the core before any
-     * op runs, so neither may share with a transient or with each other: both are live for every
-     * op that could read them.
+    /* PERSIST survives across steps and DERIVED is written by the core before any op runs, so
+     * both are live for every op and share with nothing.
      *
-     * THEY GO AT THE BOTTOM, and the transients above them. A step smaller than the largest packs
-     * its transients smaller (plan_level), and what it does not reach at the TOP of the arena is
-     * lent to the expert slab; the fixed region has to be where no level moves it, because what
-     * it holds outlives the step that wrote it. */
+     * They go at the bottom, transients above. A smaller step packs its transients smaller
+     * (plan_level) and lends the unused top of the arena to the expert slab, so the fixed region
+     * must sit where no level moves it: its contents outlive the step that wrote them. */
     int64_t off = 0;
     for (const Item& it : persist) {
         p.buffers[it.idx].arena_offset = off;
@@ -132,32 +128,17 @@ int plan_buffers(Program& p, BufPlanReport* rep) {
     const int64_t fixed = align_up(off, kBufAlign);
     r.persist_bytes = fixed;
 
-    std::vector placed;
-    placed.reserve(transient.size());
-    int64_t tr_end = 0;
-    for (Item it : transient) {
-        it.off = first_fit(it, placed);
-        tr_end = std::max(tr_end, it.off + it.bytes);
-        p.buffers[it.idx].arena_offset = fixed + it.off;
-        placed.push_back(it);
-    }
+    const int64_t tr_end = pack(transient);
+    for (const Item& it : transient) p.buffers[it.idx].arena_offset = fixed + it.off;
     r.transient_bytes = tr_end;
 
     p.arena_fixed_bytes = fixed;
     p.arena_bytes = fixed + tr_end;
 
-    /* The host arena is its own address space and its own base pointer. Offsets below are relative
-     * to it, not to Program::arena_bytes. */
-    std::vector host_placed;
-    int64_t host_end = 0;
-    for (Item it : host) {
-        /* One pass, same packer: a host PERSIST is live for the whole program by construction, so
-         * first_fit already refuses to share it with anything. */
-        it.off = first_fit(it, host_placed);
-        host_end = std::max(host_end, it.off + it.bytes);
-        p.buffers[it.idx].arena_offset = it.off;
-        host_placed.push_back(it);
-    }
+    /* The host arena has its own base pointer; these offsets are relative to it. Same packer in
+     * one pass: a host PERSIST is live for the whole program, so it shares with nothing. */
+    const int64_t host_end = pack(host);
+    for (const Item& it : host) p.buffers[it.idx].arena_offset = it.off;
     r.host_bytes = host_end;
     p.host_arena_bytes = host_end;
 
@@ -192,9 +173,8 @@ int plan_level(const Program& full, const Program& probe, int64_t rows, ArenaLev
             f.dtype != q.dtype || f.rank != q.rank)
             return refuse(fmt("buffer %zu is '%s' in the real declare and '%s' in the sizing one",
                               i, fb.name.c_str(), pb.name.c_str()));
-        /* ONLY THE ROWS MAY SHRINK. Every other extent is a stride some kernel was resolved
-         * against at the real size, and a buffer narrower in any of them would be read at the
-         * wrong pitch. */
+        /* Only the rows may shrink. Every other extent is a stride some kernel was resolved
+         * against at the real size. */
         for (uint32_t d = 1; d < f.rank; ++d)
             if (f.shape[d] != q.shape[d])
                 return refuse(fmt("buffer '%s' changes extent %u (%lld to %lld) with the step size",
@@ -203,36 +183,27 @@ int plan_level(const Program& full, const Program& probe, int64_t rows, ArenaLev
             return refuse(fmt("buffer '%s' is larger for a smaller step (%lld rows to %lld)",
                               fb.name.c_str(), (long long)f.shape[0], (long long)q.shape[0]));
         lv.decl[i] = q;
-        /* THE FIXED REGION AND THE HOST ARENA ARE THE SAME AT EVERY LEVEL. A persistent buffer
-         * holds what an earlier step wrote, so it cannot move -- and it keeps its full size too:
-         * one the plugin sizes by the step (a per-token plane it writes from outside the op order)
-         * is only ever smaller at a smaller step, and the real declare's extent covers it. */
+        /* The fixed region and the host arena are the same at every level. A persistent buffer
+         * holds an earlier step's data, so it cannot move, and it keeps its full size: one sized
+         * by the step (a per-token plane written outside the op order) is only smaller at a
+         * smaller step, and the real extent covers it. */
         if (f.kind != RAD_BUF_TRANSIENT || f.domain == RAD_DOMAIN_HOST) {
             lv.decl[i] = f;
             lv.offset[i] = fb.arena_offset;
             continue;
         }
-        /* The real declare's liveness: the op list is the same, and it is the one the kernels were
-         * issued against. */
+        /* The real declare's liveness: the op list is the same one the kernels were issued
+         * against. */
         Item it{ i, align_up(buffer_bytes(q), kBufAlign), fb.first_def, fb.last_use };
-        if (it.lo < 0 || it.hi < it.lo) { it.lo = 0; it.hi = (int32_t)full.ops.size(); }
+        if (it.lo < 0 || it.hi < it.lo) {
+            it.lo = 0;
+            it.hi = std::max((int32_t)full.ops.size() - 1, 0);
+        }
         transient.push_back(it);
     }
 
-    auto by_size = [](const Item& a, const Item& b) {
-        if (a.bytes != b.bytes) return a.bytes > b.bytes;
-        if (a.lo != b.lo) return a.lo < b.lo;
-        return a.idx < b.idx;
-    };
-    std::sort(transient.begin(), transient.end(), by_size);
-    std::vector placed;
-    int64_t tr_end = 0;
-    for (Item it : transient) {
-        it.off = first_fit(it, placed);
-        tr_end = std::max(tr_end, it.off + it.bytes);
-        lv.offset[it.idx] = full.arena_fixed_bytes + it.off;
-        placed.push_back(it);
-    }
+    const int64_t tr_end = pack(transient);
+    for (const Item& it : transient) lv.offset[it.idx] = full.arena_fixed_bytes + it.off;
     lv.end = full.arena_fixed_bytes + tr_end;
     if (lv.end > full.arena_bytes)
         return refuse(fmt("packing the smaller buffers took %lld bytes, more than the full plan's "
diff --git a/core/build/rad_build.h b/core/build/rad_build.h
index 06b723bc..877f057b 100644
--- a/core/build/rad_build.h
+++ b/core/build/rad_build.h
@@ -1,26 +1,21 @@
-/* rad_build.h -- the declare phase (spec §3.1). The architecture plugin states everything it will
- * ever do; this is what receives it.
+/* rad_build.h -- the declare phase (spec §3.1): receives everything the architecture plugin will
+ * ever do.
  *
- * Two properties are the whole point of the phase and everything here is arranged around them:
+ *   Declare always completes. A missing kernel does not stop the walk: every op, band and domain
+ *   that resolved to nothing is collected with the constraint that refused it and reported at the
+ *   end, which shows whether a plugin or a model is missing.
  *
- *   DECLARE ALWAYS COMPLETES. A missing kernel does not stop the walk. Every op, every band and
- *   every domain that resolved to nothing is accumulated with the constraint that refused it, and
- *   the full list is reported at the end. The first failure at the top tells you one thing; the
- *   whole list tells you whether you are missing a plugin or missing a model.
+ *   Nothing is decided twice. After declare the model is static (every op, its kernel, the
+ *   weights it touches, the order). The bucket table, weight manifest, buffer plan and KV block
+ *   sizes are built once here, so the step path indexes tables.
  *
- *   NOTHING IS DECIDED TWICE. Between declare and plan the model is known statically -- every op,
- *   every kernel that will service it, every weight it touches, and the order. The bucket table,
- *   the weight manifest, the buffer plan and the KV block sizes are all built once, here, so the
- *   step path indexes tables instead of asking questions.
+ * The kernel hierarchy, op schemas, constraint matching and bucket boundaries belong to
+ * core/plugin/. The Builder calls Registry::validate and Registry::build_bands rather than
+ * reimplementing them, so selector and builder cannot drift apart.
  *
- * WHAT THIS COMPONENT DOES NOT DO. The kernel hierarchy, the op schemas, the constraint match and
- * the bucket boundaries are core/plugin/'s, and the Builder asks rather than reimplements: it
- * calls Registry::validate for the schema check and Registry::build_bands for the bucket table.
- * Two answers to one question is how a selector and a builder drift apart.
- *
- * LIFETIME. Every KernelRow, Resolved and RadOpSchema in the Program points into a plugin's static
- * tables, which the Registry dlclose()s. The Program must not outlive the Registry it was built
- * against, and neither may.
+ * Lifetime: every KernelRow, Resolved and RadOpSchema in the Program points into a plugin's static
+ * tables, which the Registry dlclose()s. Neither the Builder nor the Program may outlive the
+ * Registry.
  */
 #pragma once
 #include "plugin/registry.h"
@@ -33,32 +28,27 @@
 #include 
 #include 
 
-/* The handle the plugin holds. rad_builder.h only forward-declares it; core/build/ owns it, and
- * making it a base of rad::Builder means the C shims are a static_cast rather than a lookup. */
+/* The plugin's handle. rad_builder.h only forward-declares it; as a base of rad::Builder, the C
+ * shims reach the Builder with a static_cast. */
 struct RadBuilder { };
 
 namespace rad {
 
-/* Process-lifetime storage for declared names.
- *
- * RadNameMap and RadKernelInfo hold raw `const char*`, and the Program outlives the Builder that
- * filled it -- so a std::string member would dangle and there is nowhere in the frozen struct to
- * put one. These are interned instead: a few thousand short strings, deduplicated, never freed.
- * Freeing them would mean making RadNameMap own its storage, which is an ABI change for a few
- * kilobytes. */
+/* Process-lifetime storage for declared names. RadNameMap and RadKernelInfo hold raw
+ * `const char*` and the Program outlives the Builder, so the strings are interned: a few thousand,
+ * deduplicated, never freed. Owning them in RadNameMap would be an ABI change. */
 const char* intern(std::string_view s);
 
-/* Names for the enums the graph dump prints. `bld_` prefixed because tier_name and site_name in
- * rad_core.h belong to the planner and these are the same kind of thing for a different axis. */
+/* Names for the enums the graph dump prints; `bld_` prefixed to keep them apart from the
+ * planner's tier_name and site_name in rad_core.h. */
 const char* bld_domain_name(int domain);
 const char* bld_access_name(int access);
 const char* bld_buf_kind_name(int kind);
 const char* bld_kv_kind_name(int kind);
 
 /* ------------------------------------------------------------------ the buffer plan */
-/* What the packing produced, for the --debug-graph report. `sum_bytes` is what no sharing at all
- * would have cost and `peak_live` is what a perfect packer would reach, so the pair brackets the
- * arena and says whether the greedy pass left anything on the table. */
+/* Packing results for the --debug-graph report. `sum_bytes` (no sharing) and `peak_live` (a
+ * perfect packer) bracket the arena and show what the greedy pass left unused. */
 struct BufPlanReport {
     int64_t transient_bytes = 0;   /* the packed, shared region */
     int64_t persist_bytes   = 0;   /* PERSIST + DERIVED: their own non-overlapping region */
@@ -69,37 +59,37 @@ struct BufPlanReport {
 };
 
 /* Liveness must already be in BufferInfo::first_def / last_use; a transient with first_def < 0 is
- * treated as live for the whole program, which is the sound assumption and not a guess.
+ * treated as live for the whole program, which is sound.
  *
  * Assigns BufferInfo::arena_offset for every buffer and sets Program::arena_bytes. Returns RAD_OK,
  * or RAD_E_INVAL if a buffer could not be sized (a plugin-private dtype the core cannot measure). */
 int plan_buffers(Program& p, BufPlanReport* rep = nullptr);
 
-/* ONE SIZE OF STEP'S ARENA LAYOUT. The same buffers as the real plan, the fixed region where it
- * was, and the transients packed for a step of at most `rows` tokens -- so the arena past `end`
- * is unused by any such step and can be lent. `offset` and `decl` are indexed by buffer handle. */
+/* The arena layout for steps of at most `rows` tokens: the real plan's buffers, the fixed region
+ * unchanged, and the transients repacked, so the arena past `end` is unused by such a step and
+ * can be lent. `offset` and `decl` are indexed by buffer handle. */
 struct ArenaLevel {
     int64_t rows = 0;
     int64_t end = 0;
     std::vector    offset;
     std::vector decl;
 };
-/* Lay out `probe`'s buffers -- a sizing declare at `rows` -- over `full`'s. Refused, with the
- * reason in `why`, when the two declares do not describe the same buffers with only their rows
- * smaller: anything else cannot share the real plan's fixed region and kernels. */
+/* Lay out `probe`'s buffers (a sizing declare at `rows`) over `full`'s. Refused, with the reason
+ * in `why`, unless both declares describe the same buffers with only fewer rows; otherwise they
+ * cannot share the real plan's fixed region and kernels. */
 int plan_level(const Program& full, const Program& probe, int64_t rows, ArenaLevel* out,
                std::string* why);
 
-/* Bytes a declared buffer occupies. 0 means the core cannot size it -- a plugin-private dtype,
- * which is legal for a WEIGHT (the kernel's layout hook sizes those) and not for an activation. */
+/* Bytes a declared buffer occupies. 0 means the core cannot size it: a plugin-private dtype, legal
+ * for a weight (the kernel's layout hook sizes it) but not for an activation. */
 int64_t buffer_bytes(const RadBufDecl& d);
 
 /* ------------------------------------------------------------------ the model behind a declare */
-/* WHAT THE MODEL HOLDS FOR A LOGICAL WEIGHT: its encoding and its logical extents. This is what
- * rad_weight_encoding answers and what every declaration is checked against (spec §4.3). The
- * engine answers from the container or the checkpoint it loads, rad-convert from the recipe it
- * will quantise by; `prog` is the declare so far, whose name map is how a checkpoint is searched.
- * RAD_OK, or RAD_E_NOTFOUND for a weight the model does not have. */
+/* What the model holds for a logical weight: its encoding and logical extents. rad_weight_encoding
+ * answers with it and every declaration is checked against it (spec §2.4). The engine answers from
+ * the container or checkpoint it loads, rad-convert from its recipe. `prog` is the declare so far,
+ * whose name map is used to search a checkpoint. RAD_OK, or RAD_E_NOTFOUND for a weight the model
+ * does not have. */
 struct WeightSource {
     RadEncoding enc{};
     uint32_t    rank = 0;
@@ -111,12 +101,11 @@ using WeightSourceFn = std::function& errors() const { return errors_; }
     int  status() const { return status_; }
     const BufPlanReport& buf_report() const { return bufrep_; }
 
 private:
-    /* Record a structural error and remember its class. Returns 0 so callers can `return err(...)`
-     * straight out of a decl_ function, which is what makes a failed decl_* falsy. */
+    /* Record a structural error and its class. Returns 0 so a decl_ function can
+     * `return err(...)` and yield a null handle. */
     uint32_t err(int code, const char* f, ...) __attribute__((format(printf, 3, 4)));
     std::string scoped(const char* name) const;
 
     void resolve_bands(OpInfo& oi);
     void record_tune_request(const Resolved& r);
-    /* init() for every surviving instance, run once the WHOLE graph has resolved. Running it
-     * during resolution would let a failing init abort declare before the miss report was
-     * assembled, and the miss report is the point of the phase. */
+    /* 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();
     int32_t find_kv_consumer(rad_kvgroup g);
     void finish_layouts();
@@ -218,32 +196,30 @@ private:
 
     std::string scope_;
 
-    /* Parallel to prog_.ops. Empty until the ABI carries buffer operands. */
+    /* Parallel to prog_.ops: the buffers each op declared it reads and writes. */
     struct OpBufUse { std::vector reads, writes; };
     std::vector op_bufs_;
 
-    /* Buffers the architecture said it touches from the second lane. See rad_buf_concurrent:
-     * their declared op range does not bound when their bytes are in use, so liveness gives them
-     * the whole program instead. */
+    /* Buffers touched from the second lane (rad_buf_concurrent). Their declared op range does not
+     * bound when their bytes are in use, so they are live for the whole program. */
     std::set concurrent_bufs_;
 
-    /* Parallel to prog_.kv_groups: where in the op list the group was declared, and which op was
-     * found to consume it. Declaration order is the binding, because nothing else links an op to
-     * a group -- see find_kv_consumer(). */
+    /* Parallel to prog_.kv_groups: where in the op list the group was declared, and the op found
+     * to consume it. Declaration order is the only link between an op and a group; see
+     * find_kv_consumer(). */
     std::vector kv_decl_at_;
     std::vector kv_consumer_;
 
-    /* Declared name -> the index in prog_.name_map of its FIRST entry, so a repeated declaration
-     * can be checked against it in constant time. A linear scan would be quadratic in the weight
-     * count, and a routed model declares tens of thousands of them. */
+    /* Declared name -> index of its first prog_.name_map entry, so a repeated declaration is
+     * checked in constant time; a routed model declares tens of thousands of weights. */
     std::unordered_map name_map_first_;
 
-    /* Declared weight name -> its handle, for the same reason: Flash-Next declares about a hundred
-     * thousand weights a rank, and a scan of the ones before each made declare take seconds. */
+    /* Declared weight name -> handle, for the same reason (Flash-Next declares about 100K weights
+     * per rank). */
     std::unordered_map weight_by_name_;
 
-    /* The model's answers, asked once a source: a routed model declares each expert's codes and
-     * scales as two weights over one source, and a checkpoint lookup is a name-map walk. */
+    /* The model's answers, cached per source: a routed model declares each expert's codes and
+     * scales as two weights over one source, and a checkpoint lookup walks the name map. */
     WeightSourceFn sources_;
     std::unordered_map> source_cache_;
     int lookup_source(const std::string& name, WeightSource* out);
@@ -252,50 +228,16 @@ private:
 };
 
 /* ------------------------------------------------------------------ --debug-graph (spec §16) */
-/* The entire declared graph: every op in declared order, its bucket table with one line per band,
- * the kernel and variant that resolved each band and which plugin it came from, the constraints
- * that matched, the weights it touches and the buffer it writes; then the weight manifest, the
- * buffer plan, the KV groups, the tuning requests and the miss report.
- *
- * This is the answer to "it is unclear what even runs", so it is a first-class artifact and not a
- * debug print: the bucket-table block is byte-for-byte the format in spec §2.2. */
+/* The entire declared graph: every op in declared order with its bucket table (one line per band:
+ * the resolving kernel, variant and plugin, the matched constraints, the weights touched and the
+ * buffer written); then the weight manifest, buffer plan, KV groups, tuning requests and miss
+ * report. The bucket-table block is exactly the format in spec §2.2. */
 std::string dump_graph_str(const Program& p, const std::vector* errors = nullptr);
 
-/* The same walk, as JSON, for the server's Model view. Grouped by (op, band table): a 64-layer
- * model declares one op sixty-four times with one bucket table, and sixty-four identical rows are
- * not more information than one row saying x64. */
+/* The same walk as JSON, for the server's Model view, grouped by (op, band table): an op declared
+ * once per layer with one bucket table is one row with a count. */
 std::string dump_graph_json(const Program& p);
 void        dump_graph    (const Program& p, FILE* out,
                            const std::vector* errors = nullptr);
 
 }  /* namespace rad */
-
-/* ------------------------------------------------------------------ PROPOSED ABI ADDITION */
-/* These two belong in include/rad/rad_builder.h beside rad_decl_op, and they are declared here
- * only because that header is frozen and this one is not. They are purely additive: no existing
- * signature changes and no existing plugin breaks.
- *
- * Without them, an op names its weight operands and not its buffer operands, so the declare phase
- * cannot compute activation liveness and the arena is the sum of every transient rather than the
- * peak of them -- on a 64-layer model with a per-layer residual and a per-layer FFN intermediate
- * that is the difference between one buffer and a hundred and twenty-eight. The declaration reads:
- *
- *     rad_op h = RAD_OP(b, "gemm_nt", RAD_PARAMS(...), RAD_WEIGHTS(w));
- *     rad_op_reads (b, h, RAD_BUFS(x));
- *     rad_op_writes(b, h, RAD_BUFS(y));
- *
- * Separate calls rather than more arguments to rad_decl_op, so the common declaration stays one
- * line and the buffer plan is opt-in per op. */
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-int rad_op_reads (RadBuilder* b, rad_op h, const rad_buf* bufs, int n);
-int rad_op_writes(RadBuilder* b, rad_op h, const rad_buf* bufs, int n);
-
-#define RAD_BUFS(...)  ((const rad_buf[]){ __VA_ARGS__ }), \
-                       (int)(sizeof((const rad_buf[]){ __VA_ARGS__ }) / sizeof(rad_buf))
-
-#ifdef __cplusplus
-}   /* extern "C" */
-#endif
diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp
index fcf3ed13..7536b0f1 100644
--- a/core/build/rad_builder.cpp
+++ b/core/build/rad_builder.cpp
@@ -1,13 +1,12 @@
 /* rad_builder.cpp -- the Builder, and the C surface of rad_builder.h that drives it.
  *
- * Handles are 1-based indices into the Program's tables, so index 0 is a sentinel and a failed
- * decl_* is falsy. That is not a convention for its own sake: it is what lets an architecture
- * plugin write
+ * Handles are 1-based indices into the Program's tables; index 0 is a sentinel, so a failed
+ * decl_* is falsy and an architecture plugin can write
  *
  *     rad_op h = decl_op(b, "rmsnorm_had_quant_i8", ...);
  *     if (!h) { ... emit the unfused sequence ... }
  *
- * and have fusion be a selection rather than a compiler pass (spec §2.3).
+ * which makes fusion a selection rather than a compiler pass (spec §2.3).
  */
 #include "rad_build.h"
 #include "../device/device.h"
@@ -24,9 +23,8 @@ namespace rad {
 
 /* ================================================================== interning */
 const char* intern(std::string_view s) {
-    /* A node-based set: insertion never moves an existing element, so the pointer we hand out
-     * stays valid for the life of the process. Declare runs once per rank on its own thread
-     * (spec §1), hence the lock -- taken a few thousand times at startup and never again. */
+    /* A node-based set: insertion never moves an element, so returned pointers stay valid. Locked
+     * because each rank declares on its own thread (spec §1). */
     static std::unordered_set pool;
     static std::mutex m;
     std::lock_guard lk(m);
@@ -34,22 +32,17 @@ const char* intern(std::string_view s) {
 }
 
 /* ================================================================== small helpers */
-/* Names for the enums the graph dump prints. `bld_` prefixed because tier_name and site_name in
- * rad_core.h belong to the planner and these are the same kind of thing for a different axis --
- * two components should not race for one symbol. */
 const char* bld_domain_name(int d) { return d == RAD_DOMAIN_HOST ? "host" : "device"; }
 
-/* The full-detail rendering of one miss, used by --debug-graph and by the device-hole report.
- * Defined here rather than in the header so that the domain has exactly one spelling. */
+/* Defined here so the domain is spelled by bld_domain_name. */
 std::string Program::Miss::line() const {
     return fmt("%-22s %s  [%s] -> %s", op.c_str(), geom.c_str(), bld_domain_name(domain),
                why.c_str());
 }
 
 std::vector Program::device_holes(bool host_backend) const {
-    /* By INSTANCE, because bands are: two declarations of one op can differ in geometry and in
-     * whether they carry a weight, and only the instance that missed decides whether the planner
-     * can move it to the host. */
+    /* Per instance, like bands: two declarations of one op can differ in geometry and in whether
+     * they carry a weight, which decides whether the planner can move the op to the host. */
     std::set> no_host;
     for (const Miss& m : misses)
         if (m.domain == RAD_DOMAIN_HOST) no_host.emplace(m.index, m.span);
@@ -113,7 +106,7 @@ Builder::Builder(Registry& reg, const RadModelMeta& meta, const RadBuildCtx& ctx
     prog_.ctx  = ctx;
     scope_ = ctx.scope ? ctx.scope : "";
 
-    /* Sentinels. Handle 0 is never valid, so a zeroed struct is an unset handle. */
+    /* Sentinels: handle 0 is never valid, so a zeroed struct is an unset handle. */
     prog_.weights.emplace_back();
     prog_.buffers.emplace_back();
     prog_.ops.emplace_back();
@@ -130,16 +123,14 @@ uint32_t Builder::err(int code, const char* f, ...) {
     vsnprintf(msg, sizeof msg, f, ap);
     va_end(ap);
     errors_.emplace_back(msg);
-    /* First class wins: a later error is usually a consequence of the first, and the list carries
-     * all of them anyway. */
+    /* First class wins; later errors are usually consequences, and the list keeps them all. */
     if (status_ == RAD_OK) status_ = code;
     RAD_ERR("declare: %s", msg);
     return RAD_NULL_HANDLE;
 }
 
 /* The scope prefixes declared names so a drafter, a vision tower and the language model can share
- * one builder without colliding (spec §10, §11). Op names are NOT scoped: they are the shared
- * vocabulary the selector matches on. */
+ * one builder (spec §10, §11). Op names are not scoped: the selector matches on them. */
 std::string Builder::scoped(const char* name) const {
     if (scope_.empty()) return name ? name : "";
     return scope_ + "." + (name ? name : "");
@@ -164,18 +155,16 @@ rad_weight Builder::decl_weight(const char* name, const RadWeightDecl* d) {
     WeightInfo w;
     w.name = n;
     w.decl = *d;
-    /* Under tensor parallel the plugin declares dimensions ALREADY DIVIDED (spec §9), so this is
-     * what THIS RANK holds. The core does not reason about sharding propagation and does not
-     * divide anything: a sharding inference pass is a compiler pass, and its failure mode is a
-     * model that produces fluent wrong text on a rank count nobody tested. */
+    /* Under tensor parallelism the plugin declares dimensions already divided (spec §9), so this
+     * is what this rank holds. The core never infers or divides shards. */
     w.logical_bytes = rad_dtype_bytes(d->dtype, numel);
     if (w.logical_bytes == 0 && d->dtype < RAD_DT_PLUGIN_BASE)
         return err(RAD_E_DTYPE, "weight '%s': dtype %u is not one the core can size", n.c_str(),
                    d->dtype);
 
-    /* WHAT IT IS A VIEW OF (spec §4.3): the source's encoding as the model holds it, and the planes
-     * this declaration takes. With nothing behind the builder the weight is its own plain plane
-     * in the declared dtype, which is what a test or a synthetic tool declares against. */
+    /* The view's source (spec §4.3): its encoding as the model holds it, and the planes this
+     * declaration takes. With no source (tests, synthetic tools) the weight is one plain plane in
+     * the declared dtype. */
     w.source = (d->source && *d->source) ? scoped(d->source) : n;
     WeightSource ws;
     w.enc_known = lookup_source(w.source, &ws) == RAD_OK;
@@ -211,10 +200,10 @@ rad_weight Builder::decl_weight(const char* name, const RadWeightDecl* d) {
         }
     }
 
-    /* THE DECLARATION AGAINST THE PLANES. One plane is declared at its own dtype and extents --
-     * this rank's share of them under a shard -- and several at the codes' dtype and the logical
-     * extents. A dtype that is not the plane's is an exact widening the loader performs, or it is
-     * a quantisation, which belongs to rad-convert and is refused here by name. */
+    /* Check the declaration against the planes. One plane is declared at its own dtype and extents
+     * (this rank's share under a shard); several at the codes' dtype and the logical extents. A
+     * different dtype must be an exact widening the loader performs; a quantisation belongs to
+     * rad-convert and is refused. */
     const RadEncPlane& p0 = w.enc.plane[w.sel[0]];
     if (p0.dtype != d->dtype) {
         const bool widen = w.n_sel == 1 && d->dtype == RAD_F32 &&
@@ -242,13 +231,13 @@ rad_weight Builder::decl_weight(const char* name, const RadWeightDecl* d) {
             rad_enc_plane_dims(&pk, vr, vc, &w.sel_rows[k], &w.sel_cols[k]);
             fr = sr; fc = sc;
         }
-        /* Unsharded, the declaration IS the plane (or, for several, the logical weight), and a
-         * mismatch is the plugin and the model disagreeing about a shape -- named now rather than
-         * found at load as a byte count. A shard's share is the loader's to check. */
+        /* Unsharded, the declaration must match the plane (or, for several, the logical weight);
+         * a mismatch is reported now rather than as a byte count at load. The loader checks a
+         * shard's share. */
         const bool whole = d->shard == RAD_SHARD_NONE || prog_.ctx.world_size <= 1;
-        /* A RESHAPE IS NOT A DISAGREEMENT: one whole plane of single elements, a byte or more
-         * each, declared under another shape of the same count -- a conv kernel [O, C, T, H, W]
-         * read as the [O, C*T*H*W] matrix it is. Row-major, its bytes do not move. */
+        /* A reshape is allowed: one whole plane of single elements (a byte or more each) declared
+         * under another shape with the same count, e.g. a conv kernel [O, C, T, H, W] read as
+         * [O, C*T*H*W]. Row-major bytes are unchanged. */
         const bool reshape = w.n_sel == 1 && whole && pk.kind == RAD_PLANE_TILED &&
                              pk.block[0] == 1 && pk.block[1] == 1 &&
                              rad_dtype_bits(pk.dtype) >= 8 && fr * fc == vr * vc;
@@ -260,9 +249,9 @@ rad_weight Builder::decl_weight(const char* name, const RadWeightDecl* d) {
                        (long long)(w.n_sel == 1 ? fr : sr), (long long)(w.n_sel == 1 ? fc : sc));
     }
 
-    /* The stored form defaults to the selected plane as it is. finish_layouts() overwrites it when
-     * the resolved kernel asks for something else through its layout hook (spec §4.3); a kernel
-     * with no hook, or one that answers RAD_E_UNSUPPORTED, takes exactly this. */
+    /* The stored form defaults to the selected plane unchanged. finish_layouts() overwrites it when
+     * the resolved kernel's layout hook asks for another (spec §4.3); no hook, or
+     * RAD_E_UNSUPPORTED, keeps this. */
     w.identity     = true;
     w.stored_dtype = w.widen ? d->dtype : p0.dtype;
     w.stored_bytes = w.widen ? rad_dtype_bytes(d->dtype, vr * vc)
@@ -287,8 +276,8 @@ int Builder::lookup_source(const std::string& name, WeightSource* out) {
     }
     WeightSource ws;
     const int st = sources_(name, prog_, &ws);
-    /* Only an answer is remembered: a weight not found before its name map entry was declared
-     * may be found after it. */
+    /* Cache only successes: a weight not found before its name-map entry is declared may be found
+     * after. */
     if (st == RAD_OK) source_cache_.emplace(name, std::make_pair(st, ws));
     *out = ws;
     return st;
@@ -357,7 +346,7 @@ rad_kvgroup Builder::decl_kv_group(const char* name, const RadKVGroupDecl* d) {
     g.name = n;
     g.decl = *d;
     prog_.kv_groups.push_back(std::move(g));
-    kv_decl_at_.push_back((int32_t)prog_.ops.size());   /* where in the op list we are now */
+    kv_decl_at_.push_back((int32_t)prog_.ops.size());   /* current position in the op list */
     kv_consumer_.push_back(-1);
     return (rad_kvgroup)(prog_.kv_groups.size() - 1);
 }
@@ -374,19 +363,15 @@ int Builder::bind_layer_kv(int layer, rad_kvgroup g) {
     return RAD_OK;
 }
 
-/* Which op reads this group.
+/* Which op reads this group. The ABI does not link an op to a KV group, so declaration order is
+ * the binding, as documented: "declare the group, declare the op, then ask rad_kv_block_size()"
+ * (docs/OPS.md, spec §7.2). The consumer is the first unclaimed op after the group that carries a
+ * block_size; an op serves at most one group, so a hybrid model's full and sliding-window groups
+ * each claim their own attention op.
  *
- * Nothing in the ABI links an op to a KV group: rad_decl_op names parameters and weight operands,
- * and a group is not either of those. Declaration order is therefore the binding, and it is the
- * order the documentation already prescribes -- "declare the group, declare the op, then ask
- * rad_kv_block_size()" (docs/OPS.md, spec §7.2). The consuming op is the first op declared after
- * the group that carries a block_size, and an op serves at most one group, so a hybrid model's
- * full and sliding-window groups each claim their own attention op.
- *
- * "Carries a block_size" means any of three things, and all three are checked because an
- * architecture plugin may legitimately do none of the others: the op DECLARED one, its SCHEMA
- * names one (attn_paged does, so the op is recognisable even when the plugin left the value off
- * precisely because it is about to ask for it), or its resolved kernel CONSTRAINS one. */
+ * An op carries a block_size if it declared one, its schema names one (attn_paged does, so it is
+ * found even when the plugin omits the value it is about to ask for), or its resolved kernel
+ * constrains one. */
 int32_t Builder::find_kv_consumer(rad_kvgroup g) {
     if (kv_consumer_[g] >= 0) return kv_consumer_[g];
 
@@ -420,8 +405,8 @@ int64_t Builder::kv_block_size(rad_kvgroup g) {
     }
     KVGroupInfo& gi = prog_.kv_groups[g];
 
-    /* A per-sequence state has no block size and asking for one is a category error, not a
-     * failure. Say so once and return 0; the caller wants bytes_per_state. */
+    /* Per-sequence state has no block size; warn and return 0 (the caller wants
+     * bytes_per_state). */
     if (gi.decl.kind == RAD_KV_LINEAR || gi.decl.kind == RAD_KV_CONV) {
         RAD_WARN("kv group '%s' is per-sequence state; it has no block size", gi.name.c_str());
         return 0;
@@ -430,8 +415,8 @@ int64_t Builder::kv_block_size(rad_kvgroup g) {
 
     int32_t consumer = find_kv_consumer(g);
     if (consumer < 0) {
-        /* A silent zero here becomes a division by zero in the block manager three components
-         * later, so it is an error with the reason attached. */
+        /* An error, not a silent 0, which would become a division by zero in the block
+         * manager. */
         err(RAD_E_STATE,
             "rad_kv_block_size('%s'): no op that reads this group has been declared yet. The "
             "block size comes off the RESOLVED attention kernel's block_size constraint, so the "
@@ -441,9 +426,8 @@ int64_t Builder::kv_block_size(rad_kvgroup g) {
 
     const OpInfo& o = prog_.ops[consumer];
 
-    /* The kernel's own constraint is the answer, read with core/plugin/'s own accessor: a second
-     * constraint walk here would be a second reading of the same rows. A core that picked its own
-     * block size would be a core that has to be edited when a kernel changes (spec §7.2). */
+    /* The resolved kernel's block_size constraint is the answer, read with core/plugin/'s
+     * accessor; the core never picks a block size (spec §7.2). */
     for (const Band& b : o.bands)
         for (int d = 0; d < RAD_N_DOMAINS; ++d) {
             if (!b.dom[d] || !b.dom[d].row) continue;
@@ -454,22 +438,15 @@ int64_t Builder::kv_block_size(rad_kvgroup g) {
             }
         }
 
-    /* No kernel constrained it: this kernel serves any block size (libref does exactly
-     * that -- correct, slow, no geometry constraints, spec §17). Then the number is the plugin's
-     * declared parameter, which is still not the core choosing one. */
+    /* No kernel constrains it (e.g. libref, which serves any block size, spec §17): use the
+     * plugin's declared parameter. */
     long long v = 0;
     if (o.base.get_i("block_size", &v) && v > 0) { gi.block_size = v; return gi.block_size; }
 
-    /* Nothing to read it off, and the reason is almost always the same one, so it is named here in
-     * full rather than left as "0".
-     *
-     * A constraint whose key the geometry does not carry does NOT hold (rad_util.cpp, and it is
-     * libr4d's rule for good reasons). So a kernel constrained to `block_size == 16` cannot be
-     * selected by a query that omits block_size -- which means an attention op declared WITHOUT a
-     * block_size can never resolve to the kernel whose constraint the answer was supposed to come
-     * from. The plugin has to declare the block size it wants; the resolved kernel's constraint
-     * then either confirms it or refuses it by name, and THAT is what keeps the number the
-     * kernel's rather than the core's (spec §7.2). */
+    /* Nothing to read it from. The usual cause: a constraint on a key the geometry lacks does not
+     * hold, so a kernel constrained to `block_size == 16` is never selected for an op declared
+     * without block_size. The plugin must declare the block size it wants; the resolved kernel's
+     * constraint then confirms or refuses it (spec §7.2). */
     bool resolved_anywhere = false;
     for (const Band& b : o.bands)
         for (int d = 0; d < RAD_N_DOMAINS; ++d) if (b.dom[d]) resolved_anywhere = true;
@@ -489,14 +466,12 @@ int64_t Builder::kv_block_size(rad_kvgroup g) {
 /* ================================================================== ops */
 void Builder::record_tune_request(const Resolved& r) {
     if (!r.row || !r.row->info || r.row->info->n_tunables <= 0) return;
-    /* ONE REQUEST PER KERNEL INSTANTIATION, and the instantiation is (kernel, plugin, the input
-     * params it was resolved at). Every distinct shape a kernel is asked for is a separate
-     * benchmark, and the same shape asked for by sixty-four layers is one (spec §15).
+    /* One request per kernel instantiation: (kernel, plugin, resolved input params). The same
+     * shape requested by many layers is one benchmark (spec §15).
      *
-     * `geom_key` and not geom.str(): the tuner and the selector must key the same way or the cache
-     * never hits, and geom_key is tunecache.h's canonical spelling -- sorted, and taken BEFORE the
-     * tuned axes were folded into the geometry. geom.str() preserves declaration order and now
-     * also carries the axes, so keying on it would make the key depend on its own answer. */
+     * Keyed on geom_key, not geom.str(), so tuner and selector key identically: geom_key is
+     * tunecache.h's canonical sorted spelling without the tuned axes, while geom.str() keeps
+     * declaration order and includes the axes. */
     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)
@@ -512,9 +487,8 @@ void Builder::record_tune_request(const Resolved& r) {
     prog_.tune_requests.push_back(std::move(req));
 }
 
-/* The geometry a band is DISPLAYED as: the fixed parameters plus the ranged one at the band's
- * upper bound. Diagnostics only -- a resolved band already carries the geometry the registry froze
- * it at, and that is the one the kernel is handed. */
+/* The geometry a band is displayed as: the fixed parameters plus the ranged one at the band's upper
+ * bound. Diagnostics only; the kernel receives the geometry the registry froze in Resolved. */
 static Geometry display_geometry(const OpInfo& oi, const Band& b) {
     Geometry g = oi.base;
     if (!oi.ranged_key.empty() && b.hi != INT64_MAX) g.set_i(oi.ranged_key, b.hi);
@@ -522,17 +496,16 @@ static Geometry display_geometry(const OpInfo& oi, const Band& b) {
 }
 
 void Builder::resolve_bands(OpInfo& oi) {
-    /* The bucket table is core/plugin/'s and this component does not second-guess it: the
-     * boundaries are the union of the constraint values candidate kernels place on the ranged
-     * parameter, clamped to the declared range, and both domains are resolved AT EACH BAND'S UPPER
-     * BOUND -- the worst case in the band and therefore the only value safe to select and size on.
-     * An empty ranged_key comes back as exactly one band whose hi is INT64_MAX, so the
-     * no-ranged-parameter case needs no separate path and band_for() always finds it. */
-    /* A KERNEL THAT CANNOT READ A WEIGHT'S ENCODING IS NOT A CANDIDATE FOR THE OP. Its layout
-     * hook says so with RAD_E_DTYPE, and a device row with no hook reads one plane as it is and
-     * nothing else -- so a bf16 head goes to the bf16 GEMM rather than being refused by the fp8
-     * one, and the same declaration serves a checkpoint and its quantised container. The host
-     * domain's hookless rows are libref, which reads canonically and is gated elsewhere. */
+    /* The bucket table comes from core/plugin/: boundaries are the union of candidate kernels'
+     * constraint values on the ranged parameter, clamped to the declared range, and both domains
+     * resolve at each band's upper bound (the worst case, the only safe value to select and size
+     * on). No ranged parameter yields one band with hi INT64_MAX, which band_for() always finds.
+     *
+     * A kernel that cannot read a weight's encoding is not a candidate: its layout hook returns
+     * RAD_E_DTYPE, and a hookless device row reads only a single plane as stored. So a bf16 head
+     * goes to the bf16 GEMM instead of being refused by the fp8 one, and one declaration serves a
+     * checkpoint and its quantised container. Hookless host rows are libref, which reads
+     * canonically and is gated elsewhere. */
     const Registry::RowFilter accept = [&](const KernelRow& r, const Geometry& g) -> std::string {
         const RadKernelInfo* ki = r.info;
         for (size_t wi = 0; wi < oi.weights.size(); ++wi) {
@@ -542,23 +515,10 @@ void Builder::resolve_bands(OpInfo& oi) {
             if (sources_ && !w.enc_known && w.decl.optional) continue;
             const int operand = wi < oi.weight_opd.size() && oi.weight_opd[wi] >= 0
                                     ? (int)oi.weight_opd[wi] : (int)wi;
-            char enc[256];
-            if (!ki->layout) {
-                if (ki->domain == RAD_DOMAIN_DEVICE && w.n_sel > 1) {
-                    rad_enc_format(&w.enc, enc, sizeof enc);
-                    return fmt("reads '%s' as stored, and it is %d planes of %s", w.name.c_str(),
-                               w.n_sel, enc);
-                }
-                continue;
-            }
             RadTensor t[RAD_ENC_MAX_PLANES];
             weight_planes(w, t);
-            RadLayout L{};
-            if (ki->layout(g.params(), g.n_params(), operand, &w.enc, w.sel, t, w.n_sel, &L) ==
-                RAD_E_DTYPE) {
-                rad_enc_format(&w.enc, enc, sizeof enc);
-                return fmt("does not read '%s' encoded %s", w.name.c_str(), enc);
-            }
+            std::string why = weight_refusal(ki, g, operand, w.enc, w.sel, t, w.n_sel, w.name);
+            if (!why.empty()) return why;
         }
         return std::string();
     };
@@ -566,8 +526,7 @@ void Builder::resolve_bands(OpInfo& oi) {
                                 oi.weights.empty() ? nullptr : &accept);
 
     if (oi.bands.empty()) {
-        /* No rows for this op at all. The range still owes an answer, so the miss report names a
-         * band rather than saying nothing about the op. */
+        /* No rows for this op at all; add one band so the miss report names it. */
         oi.bands.emplace_back();
         oi.bands.back().hi = oi.ranged_key.empty() ? INT64_MAX : oi.range_hi;
         for (int d = 0; d < RAD_N_DOMAINS; ++d)
@@ -579,21 +538,17 @@ void Builder::resolve_bands(OpInfo& oi) {
             Resolved& r = b.dom[d];
 
             if (!r) {
-                /* One entry per op per band per domain that resolved to nothing, each carrying the
-                 * constraint that refused it. build_bands records and does not abort -- a device
-                 * miss is fatal for that band and a host miss removes a placement option, and
-                 * which of those matters is not selection's call. Declare always completes and
-                 * reports the list whole (spec §3.1). */
+                /* One miss per op, band and domain, with the refusing constraint. Recorded, not
+                 * fatal: whether a miss matters is decided later (spec §3.1). */
                 prog_.misses.push_back({ oi.op, display_geometry(oi, b).str(), b.span,
                                          b.miss[d].empty() ? "no kernel matched" : b.miss[d],
                                          d, oi.index });
                 continue;
             }
 
-            /* Scratch at the same value the band was selected at. r.geom IS that value, frozen by
-             * the registry, so asking it here cannot drift from what the choice was made against.
-             * RadArgs carries no tensors: a scratch hook is a function of the geometry, which is
-             * the whole reason it can be called at declare at all. */
+            /* Scratch sized at r.geom, the frozen geometry the band was selected at. RadArgs
+             * carries no tensors: a scratch hook depends only on geometry, so it can run at
+             * declare. */
             if (r.row->info && r.row->info->scratch) {
                 RadArgs a{};
                 a.p          = r.geom.params();
@@ -615,13 +570,9 @@ void Builder::resolve_bands(OpInfo& oi) {
     }
 }
 
-/* init() once per resolved instance -- one op, one band, one domain -- run once the WHOLE graph
- * has resolved (spec §2.1). Not during resolution: one kernel's failing init would then abort
- * declare before the miss report was assembled, and the miss report is the point of the phase.
- *
- * A negative init is not a runtime condition. The kernel matched the constraints and then refused
- * the instance, so the band becomes a miss and the report names it here, rather than the failure
- * surfacing at the first launch three frames away. */
+/* init() once per resolved instance (op, band, domain), after the whole graph has resolved
+ * (spec §2.1; see rad_build.h). A negative init means the kernel refused an instance it matched:
+ * the band becomes a miss reported here rather than at the first launch. */
 void Builder::finish_instances() {
     for (size_t i = 1; i < prog_.ops.size(); ++i) {
         OpInfo& oi = prog_.ops[i];
@@ -649,14 +600,10 @@ rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p,
     if (!opname || !*opname) return err(RAD_E_INVAL, "decl_op: null op name");
     if (n_p < 0 || n_w < 0) return err(RAD_E_INVAL, "decl_op('%s'): negative count", opname);
 
-    /* ---- the schema, checked by the component that owns it.
-     *
-     * Registry::validate covers the whole parameter side: no such op (with the near miss named, so
-     * a typo and an unimplemented op are not the same diagnostic), an unknown key, a key given
-     * twice, a type mismatch, an empty range, and the one-ranged-parameter rule. A second copy of
-     * that check here would be a second answer to one question, and the two would drift. The
-     * sentence it fills in is written for an architecture-plugin author, so it goes into the
-     * report unchanged. */
+    /* ---- the schema, checked by its owner. Registry::validate covers the parameter side: unknown
+     * op (naming the near miss), unknown or repeated key, type mismatch, empty range, and the
+     * one-ranged-parameter rule. Its message is written for plugin authors and passed through
+     * unchanged. */
     std::string verr;
     const int v = reg_.validate(opname, p, n_p, &verr);
     if (v < 0) return err(v, "%s", verr.c_str());
@@ -664,8 +611,7 @@ rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p,
     const RadOpSchema* sc = reg_.schema(opname);
     if (!sc) return err(RAD_E_NOSCHEMA, "op '%s' has no declared schema", opname);
 
-    /* ---- parameters. validate() already guaranteed the shape of this list, so this only has to
-     * split the fixed parameters from the single ranged one. */
+    /* ---- parameters, already validated: split the fixed ones from the single ranged one. */
     Geometry base;
     std::string ranged_key;
     int64_t lo = 0, hi = 0;
@@ -675,10 +621,8 @@ rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p,
         switch (q.kind) {
             case RAD_P_INT:   base.set_i(q.key, q.ival); break;
             case RAD_P_STR:   base.set_s(q.key, q.sval); break;
-            /* A float parameter carries a value the kernel reads and NOTHING THE SELECTOR MATCHES
-             * ON: a tolerance is not a predicate, and a kernel that cares about eps to that
-             * precision has a bug (docs/OPS.md). So it goes into the geometry, where the kernel
-             * finds it, and never becomes a band boundary. */
+            /* A float reaches the kernel through the geometry but is never matched on or made a
+             * band boundary (docs/OPS.md; see constraint_holds). */
             case RAD_P_F64:   base.set_f(q.key, q.dval); break;
             case RAD_P_RANGE: ranged_key = q.key; lo = q.ival; hi = q.ihi; break;
             default:
@@ -687,11 +631,9 @@ rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p,
         }
     }
 
-    /* ---- operand count, which validate() does not see: it is handed the parameters and not the
-     * operands. Arguments are positional, so a count that disagrees with the schema means the same
-     * call means different things to different kernels -- not a diagnosable failure at issue, but
-     * silent numerical garbage (spec §2.3). Only the WEIGHT operands are named at declare, so that
-     * is what is counted here; the full count is checked against this same schema at issue. */
+    /* ---- weight operand count, which validate() does not see. Arguments are positional, so a
+     * count that disagrees with the schema produces silent garbage, not an error (spec §2.3). Only
+     * weight operands are named at declare; the full count is checked at issue. */
     size_t before = errors_.size();
     int w_req = 0, w_max = 0, n_tab = 0;
     for (int i = 0; sc->operands && i < sc->n_operands; ++i) {
@@ -700,22 +642,13 @@ rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p,
         ++w_max;
         if (!sc->operands[i].optional) ++w_req;
     }
-    /* ---- and where the operand is a TABLE, the run length.
-     *
-     * A RAD_OPD_WTAB position consumes a RUN of declared weights, so the count alone does not
-     * say how the list divides. The rule is EQUAL DIVISION: whatever is left after the fixed
-     * weight positions have taken one each is split evenly across the table positions, in
-     * declaration order. That is exactly right for the case tables exist for -- a grouped GEMM's
-     * codes and scale planes are one of each per expert, always the same count.
-     *
-     * WHERE IT DOES NOT COME OUT WHOLE, THE FIRST POSITIONS TAKE ONE MORE. A grouped GEMM whose
-     * n experts are C classes by number mod C, declared class by class as a codes table and a
-     * scales table each, gives its first `n % C` classes one expert more than the rest -- exactly
-     * the positions this rule lengthens. A list grouped any other way is refused at issue: the
-     * plugin names each table's run there, and a run other than the one this division bound is
-     * refused. A bound run must also be contiguous, checked when the tables are bound before the
-     * first step, and its entries of one shape, checked at its first issue. A list shorter than
-     * the tables is refused here. */
+    /* ---- table run lengths. A RAD_OPD_WTAB position consumes a run of declared weights. After
+     * each fixed weight position takes one, the rest is divided equally across the table
+     * positions in declaration order (a grouped GEMM has one codes and one scales plane per
+     * expert). If it does not divide, the first positions take one more, which matches n experts
+     * split into C classes by number mod C. Any other grouping is refused at issue, where the
+     * plugin names each run. Runs must also be contiguous (checked when tables are bound) and of
+     * one shape (checked at first issue). Too few weights for the tables is refused here. */
     int per_tab = 0, tab_extra = 0;
     if (n_tab > 0) {
         const int rest = n_w - w_max;
@@ -753,10 +686,8 @@ rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p,
         oi.range_hi   = hi;
     }
     oi.weights.assign(w, w + n_w);
-    /* The many-to-one map from declared weight to schema operand position, built here so the
-     * layout pass, the converter and the issue path all read one answer. A fixed weight position
-     * takes one; a table position takes `per_tab` in a row, and the first `tab_extra` of them one
-     * more. */
+    /* Declared weight -> schema operand position (OpInfo::weight_opd). A fixed position takes one
+     * weight; a table position takes `per_tab`, plus one for the first `tab_extra` tables. */
     oi.weight_opd.assign((size_t)n_w, -1);
     {
         int wi = 0, ti = 0;
@@ -778,10 +709,9 @@ rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p,
                                     "'%s' there -- the plugin declares a different graph at a "
                                     "smaller max_tok", at, opname,
                        at < ref_->ops.size() ? ref_->ops[at].op.c_str() : "nothing");
-        /* AND WITH THE SAME FIXED PARAMETERS. The kernel was chosen for the real declare's, and it
-         * runs with them: an op whose fixed geometry follows max_tok -- a row count declared as a
-         * constant rather than a range -- would be handed the real size while its buffers are the
-         * smaller level's, and write past them into whatever the arena lent out. */
+        /* Fixed parameters must match too: the kernel runs with the real declare's. A fixed row
+         * count that follows max_tok would be launched at the real size over the smaller level's
+         * buffers and write past them into lent arena memory. */
         const Geometry& rb = ref_->ops[at].base;
         auto role_of = [&](const char* key) {
             for (int k = 0; sc->params && k < sc->n_params; ++k)
@@ -801,7 +731,7 @@ rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p,
             bool same = false;
             switch (ra[x].kind) {
                 case RAD_P_INT:
-                    /* A CAPACITY MAY SHRINK: its kernel writes by its operands' extents. */
+                    /* A capacity may shrink: its kernel writes by its operands' extents. */
                     same = y->ival == ra[x].ival ||
                            (role_of(ra[x].key) == RAD_PROLE_CAPACITY && y->ival <= ra[x].ival);
                     break;
@@ -829,9 +759,9 @@ rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p,
     prog_.ops.push_back(std::move(oi));
     op_bufs_.emplace_back();
 
-    /* An op recorded but not handed back: the graph dump still shows it and its holes, and the
-     * plugin gets a falsy handle so it can offer the unfused sequence instead. A miss is not an
-     * error yet -- it becomes one only if the plugin issues it (spec §2.3, §3.2). */
+    /* An unresolved op is recorded (the graph dump shows it) but returns a null handle, so the
+     * plugin can declare the unfused sequence instead. It becomes an error only if issued
+     * (spec §2.3, §3.2). */
     return resolved ? h : RAD_NULL_HANDLE;
 }
 
@@ -866,9 +796,7 @@ int Builder::op_writes(rad_op h, const rad_buf* b, int n) {
     return RAD_OK;
 }
 
-/* SEE rad_buf_concurrent. A buffer a second lane touches is not bounded by the op range its
- * declarations imply, so liveness hands it the whole program. Recorded rather than applied here
- * because liveness runs at finish(), after every declaration is in. */
+/* See rad_buf_concurrent. Recorded here and applied by liveness at finish(). */
 int Builder::buf_concurrent(rad_buf b) {
     if (finished_) { err(RAD_E_STATE, "buf_concurrent after declare finished"); return RAD_E_STATE; }
     if (b == 0 || b >= prog_.buffers.size()) return RAD_E_INVAL;
@@ -876,8 +804,8 @@ int Builder::buf_concurrent(rad_buf b) {
     return RAD_OK;
 }
 
-/* SEE rad_weight_shard_span. Checked against the declaration here, where the plugin that got it
- * wrong can be named; the loader checks it against the container. */
+/* See rad_weight_shard_span. Checked against the declaration here, where the plugin can be named;
+ * the loader checks it against the container. */
 int Builder::weight_shard_span(rad_weight h, int64_t lo, int64_t hi) {
     if (finished_) { err(RAD_E_STATE, "weight_shard_span after declare finished"); return RAD_E_STATE; }
     if (h == 0 || h >= prog_.weights.size()) return RAD_E_INVAL;
@@ -893,8 +821,8 @@ int Builder::weight_shard_span(rad_weight h, int64_t lo, int64_t hi) {
             (long long)lo, (long long)hi);
         return RAD_E_INVAL;
     }
-    /* The declared extent is the rank's own, so it has to be the span's length: each stacked
-     * part's for ROW, the columns for COL. */
+    /* The declared extent is this rank's, so it must equal the span's length: each stacked part's
+     * rows for ROW, the columns for COL. */
     bool ok;
     if (d.shard == RAD_SHARD_ROW) {
         if (d.n_row_parts > 1) {
@@ -954,11 +882,10 @@ int Builder::weight_shard_span_parts(rad_weight h, const int64_t* lo, const int6
 int Builder::kv_group_zero(rad_kvgroup h) {
     if (finished_) { err(RAD_E_STATE, "kv_group_zero after declare finished"); return RAD_E_STATE; }
     if (h == 0 || h >= prog_.kv_groups.size()) return RAD_E_INVAL;
-    /* PAGED GROUPS ONLY. A zero group is one whose rank computes nothing that reads or writes it,
-     * and a paged group's absence is invisible to the others: they index the shared block table
-     * and this rank has no shard to index. A linear or conv group carries per-sequence state the
-     * snapshot store saves and the step clears on every rank, and a zero-sized one would make
-     * each of those copies a size mismatch. */
+    /* Paged groups only. A zero group is one this rank never reads or writes; for a paged group
+     * the other ranks just index the shared block table. A linear or conv group's per-sequence
+     * state is saved and cleared on every rank, so a zero-sized one would mismatch those
+     * copies. */
     const int kind = prog_.kv_groups[h].decl.kind;
     if (kind != RAD_KV_FULL && kind != RAD_KV_WINDOW) {
         err(RAD_E_INVAL, "kv group '%s': kv_group_zero on a group that is not paged",
@@ -994,32 +921,22 @@ int Builder::decl_name_map(const RadNameMap* m) {
         }
         c.src[i] = intern(m->src[i]);
     }
-    /* AND `src_index`, BECAUSE THIS COPY IS FIELD BY FIELD. Every field added to RadNameMap has to
-     * be added here too, and the cost of missing one is not that the value is lost: `RadNameMap
-     * c{}` value-initialises it to ZERO, and zero means "sub-tensor 0 of this source" while the
-     * ABI's own default and arch/common/rad_arch.h's map_base() both say -1, "the whole tensor".
-     * A dropped field is therefore every map in every model quietly asking for slice 0 of its
-     * source (rad_convert.cpp refuses an index it cannot serve rather than ignoring it). */
+    /* This copy is field by field: a field added to RadNameMap must be added here too. A missed
+     * src_index would stay 0 ("sub-tensor 0") instead of the ABI default -1 ("whole tensor",
+     * also map_base() in arch/common/rad_arch.h), so every map would ask for slice 0. */
     for (int i = 0; i < m->n_src; ++i) c.src_index[i] = m->src_index[i];
     for (int i = m->n_src; i < 8; ++i) c.src_index[i] = -1;
 
-    /* A CONCAT MAP MAY BE DECLARED IN PIECES, AND EVERY OTHER REPEAT IS A BUG.
+    /* A CONCAT map may be declared in pieces; any other repeat is an error.
      *
-     * `src[8]` is the ABI's cap and a sharded checkpoint blows straight through it:
-     * Qwen3.8-Flash-Next stores its 320-million-row n-gram embedding as 128 tensors named
-     * `...ngram_embedding.shard_K.weight`. Growing the array is the wrong answer -- there is one
-     * map per declared weight and the full model declares about fifty thousand of them, so 8 -> 128
-     * would cost ~80 MB of Program to serve one tensor.
+     * `src[8]` is the ABI's cap, and a sharded checkpoint exceeds it: Qwen3.8-Flash-Next stores
+     * its n-gram embedding as 128 tensors `...ngram_embedding.shard_K.weight`. Growing the array
+     * would cost ~80 MB of Program (one map per declared weight, ~50K weights). So successive
+     * CONCAT maps for one name extend it in call order, and rad-convert joins their sources end
+     * to end (map_concat_shards() in arch/common/rad_arch.h).
      *
-     * So successive CONCAT maps for one declared name EXTEND it, in call order, and rad-convert
-     * joins their sources end to end. arch/common/rad_arch.h's map_concat_shards() is the one-line
-     * form; nothing else in the tree needs more than eight.
-     *
-     * Every OTHER repeat is refused rather than merged, and the refusal is the point. A lookup
-     * built with `std::map::emplace` KEEPS THE FIRST and drops the rest without a word, so two
-     * maps for one weight -- a copy-paste, a loop with a constant index -- convert a model whose
-     * weights came from the wrong tensors and say nothing. A merge rule that is a merge rule has
-     * to say which repeats it is not. */
+     * Other repeats are refused: a lookup built with std::map::emplace would silently keep the
+     * first, so a copy-paste mistake would convert weights from the wrong tensors. */
     auto seen = name_map_first_.find(c.declared);
     if (seen != name_map_first_.end()) {
         const RadNameMap& first = prog_.name_map[seen->second];
@@ -1044,11 +961,9 @@ int Builder::decl_name_map(const RadNameMap* m) {
     return RAD_OK;
 }
 
-/* Which buffer the core samples from. Refusing a second call rather than letting the last one win:
- * two plugins declaring into one builder (a target and its drafter, spec §10) both have logits,
- * and silently keeping the second would sample the draft model's distribution into the target's
- * tokens -- fluent wrong text, and nothing would say so. The drafter's own logits are reached
- * through its scope, not through this. */
+/* The buffer the core samples from. A second call is refused rather than winning: a target and
+ * its drafter declaring into one builder (spec §10) both have logits, and keeping the second would
+ * sample the draft distribution. The drafter's logits are reached through its scope. */
 int Builder::declare_logits(rad_buf b) {
     if (finished_) { err(RAD_E_STATE, "declare_logits after declare finished"); return RAD_E_STATE; }
     if (b == RAD_NULL_HANDLE || (size_t)b >= prog_.buffers.size()) {
@@ -1076,10 +991,9 @@ int Builder::declare_logits(rad_buf b) {
     return RAD_OK;
 }
 
-/* The embedding program's output (rad_declare_pooled). Checked here for the logits buffer's
- * reasons, and for shape: the core reads `n_seq` f32 rows of it from the device after every step,
- * so a buffer narrower than a step's sequences, or in another dtype or domain, is refused now
- * rather than read past or misread at the first request. */
+/* The embedding program's output (rad_declare_pooled). Checked as declare_logits is, and for
+ * shape: the core reads `n_seq` f32 rows from the device after every step, so the wrong dtype,
+ * domain or too few rows is refused now rather than misread at the first request. */
 int Builder::declare_pooled(rad_buf b) {
     if (finished_) { err(RAD_E_STATE, "declare_pooled after declare finished"); return RAD_E_STATE; }
     if (b == RAD_NULL_HANDLE || (size_t)b >= prog_.buffers.size()) {
@@ -1115,15 +1029,12 @@ int Builder::declare_pooled(rad_buf b) {
     return RAD_OK;
 }
 
-
-/* WHAT THE ENCODER IS. Checked here, at declare, for the drafter's reason: an encoder is exercised
- * only when a request carries media, so a declaration the engine cannot drive would otherwise
- * surface on the first image as a pass that reads or writes past a buffer.
+/* Validates the encoder at declare: it runs only when a request carries media, so a bad
+ * declaration would otherwise surface on the first image as an out-of-bounds pass.
  *
- * `max_patches` must be what the deployment asked for, because the plugin sized every activation
- * of its tower with RadBuildCtx::max_enc_patches and the core stages up to this many patches; a
- * disagreement is a tower declared for one pass size and driven at another. `out` has to hold a
- * whole pass's rows, since the core reads them back from it. */
+ * `max_patches` must equal RadBuildCtx::max_enc_patches (or max_audio_frames), which the plugin
+ * sized its activations with and the core stages up to. `out` must hold a whole pass's rows, which
+ * the core reads back. */
 int Builder::declare_encoder(const RadEncoderDecl* d) {
     if (finished_) { err(RAD_E_STATE, "declare_encoder after declare finished"); return RAD_E_STATE; }
     if (!d) { err(RAD_E_INVAL, "declare_encoder: null declaration"); return RAD_E_INVAL; }
@@ -1167,8 +1078,7 @@ int Builder::declare_encoder(const RadEncoderDecl* d) {
         return RAD_E_INVAL;
     }
     const RadBufDecl& ob = prog_.buffers[d->out].decl;
-    int64_t numel = 1;
-    for (uint32_t i = 0; i < ob.rank; ++i) numel *= ob.shape[i];
+    const int64_t numel = decl_numel(ob.rank, ob.shape);
     if (ob.dtype != RAD_BF16 || ob.domain != RAD_DOMAIN_DEVICE ||
         numel < d->max_patches / d->merge * d->n_embd) {
         err(RAD_E_INVAL, "declare_encoder '%s': out '%s' must be a device bf16 buffer of at least "
@@ -1183,11 +1093,9 @@ int Builder::declare_encoder(const RadEncoderDecl* d) {
     return RAD_OK;
 }
 
-/* WHAT THE GENERATOR IS. Checked whole here: a generator's every request runs all three of its
- * passes, so a declaration the core cannot drive fails the first request rather than a rare one,
- * and the first request is the wrong place to learn that the plugin sized its image buffer for a
- * smaller picture than it says it makes. The strings are copied: the plugin's storage is not the
- * Program's, and the Program outlives a declare. */
+/* Validates the whole generator at declare rather than at the first request (e.g. an image
+ * buffer too small for the largest picture). The strings are copied because the Program outlives
+ * the plugin's declare-time storage. */
 int Builder::declare_generator(const RadGeneratorDecl* d) {
     if (finished_) { err(RAD_E_STATE, "declare_generator after declare finished"); return RAD_E_STATE; }
     if (!d) { err(RAD_E_INVAL, "declare_generator: null declaration"); return RAD_E_INVAL; }
@@ -1254,8 +1162,7 @@ int Builder::declare_generator(const RadGeneratorDecl* d) {
         return RAD_E_INVAL;
     }
     const RadBufDecl& ob = prog_.buffers[d->image_out].decl;
-    int64_t numel = 1;
-    for (uint32_t i = 0; i < ob.rank; ++i) numel *= ob.shape[i];
+    const int64_t numel = decl_numel(ob.rank, ob.shape);
     const int64_t px = d->max_tokens * d->latent_scale * d->latent_scale;
     if (ob.dtype != RAD_U8 || ob.domain != RAD_DOMAIN_DEVICE || numel < px * d->pixel_channels) {
         err(RAD_E_INVAL, "declare_generator '%s': image_out '%s' must be a device u8 buffer of at "
@@ -1273,8 +1180,8 @@ int Builder::declare_generator(const RadGeneratorDecl* d) {
     g.tmpl_transparent = d->tmpl_transparent ? d->tmpl_transparent : "";
     g.sigmas.assign(d->sigmas, d->sigmas + d->n_sigmas);
     prog_.generator = *d;
-    /* The Program is moved after declare, and a pointer into a moved string is a pointer into the
-     * old one's storage: nothing here may be read through the decl, only through gen_str. */
+    /* The Program is moved after declare, which would invalidate pointers into gen_str, so the
+     * decl's string fields are cleared; read them only through gen_str. */
     RadGeneratorDecl& c = prog_.generator;
     c.name = c.tmpl_text = c.tmpl_edit = c.tmpl_image = c.tmpl_image_sep = nullptr;
     c.drop_prefix = c.tmpl_transparent = nullptr;
@@ -1282,14 +1189,9 @@ int Builder::declare_generator(const RadGeneratorDecl* d) {
     return RAD_OK;
 }
 
-/* WHAT THE DRAFT HEAD IS. Every field is checked here rather than at the first draft pass: a
- * drafter is exercised only once a request is speculating, so a decl that is wrong in a way the
- * engine cannot act on would otherwise surface as acceptance that is quietly zero.
- *
- * `depth` must equal what the deployment was configured for. The plugin was TOLD the number in
- * RadBuildCtx::max_spec and sized its own buffers with it, so a disagreement is not a preference
- * to reconcile -- it is the plugin having declared a graph for one depth and a drafter for
- * another, and the engine would drive the second against the first. */
+/* Validates the draft head at declare rather than at the first draft pass, where a bad decl would
+ * only show as zero acceptance. `depth` must equal RadBuildCtx::max_spec, which the plugin sized
+ * its buffers with. */
 int Builder::declare_drafter(const RadDrafterDecl* d) {
     if (finished_) {
         err(RAD_E_STATE, "declare_drafter after declare finished");
@@ -1333,27 +1235,24 @@ int Builder::declare_drafter(const RadDrafterDecl* d) {
             (long long)d->proposal_pitch);
         return RAD_E_INVAL;
     }
-    /* A BLOCK PASS EMBEDS THE MASK ID AT EVERY POSITION IT HAS NOT FILLED. Without one there is
-     * nothing to run, and the failure without this check is a block of whatever token id 0 is. */
+    /* A block pass embeds the mask id at every unfilled position, so it needs one. */
     if (d->kind == RAD_DRAFT_BLOCK && d->mask_token < 0) {
         err(RAD_E_INVAL, "declare_drafter '%s': RAD_DRAFT_BLOCK with no mask_token. Every "
                          "position the block has not filled embeds it; there is nothing to run.",
             nm);
         return RAD_E_INVAL;
     }
-    /* A BLOCK drafter's proposal cannot come from the sampler: the whole block is filled by one
-     * pass and the sampler writes one token a row. SERIAL may use either. */
+    /* A block drafter's proposal cannot come from the sampler, which writes one token per row
+     * while one pass fills the whole block. A serial drafter may use either. */
     if (d->kind == RAD_DRAFT_BLOCK && d->proposal == RAD_NULL_HANDLE) {
         err(RAD_E_INVAL, "declare_drafter '%s': RAD_DRAFT_BLOCK with no proposal buffer. One pass "
                          "fills %d positions and the sampler writes one token a row, so there is "
                          "nowhere for the rest of the block to arrive.", nm, d->depth);
         return RAD_E_INVAL;
     }
-    /* THE BLOCK'S ROW COUNT, defaulted and then checked against the depth it has to carry. The
-     * head runs over the LAST `depth` rows of the block (rad_builder.h), so a block shorter than
-     * the depth names rows that do not exist, and a block more than one row longer than the depth
-     * leaves leading rows that nothing reads -- neither is a convention, both are a mistake in
-     * the plugin, and both produce a drafter whose proposals are simply shifted. */
+    /* The block's row count, defaulted to depth + 1. The head runs over the last `depth` rows
+     * (rad_builder.h), so the block must be depth or depth + 1 rows; anything else shifts the
+     * proposals. */
     int64_t block = d->block;
     if (d->kind == RAD_DRAFT_BLOCK) {
         if (block == 0) block = (int64_t)d->depth + 1;
@@ -1371,12 +1270,10 @@ int Builder::declare_drafter(const RadDrafterDecl* d) {
         return RAD_E_INVAL;
     }
 
-    /* THE NAME LIVES IN drafter_name AND ONLY THERE. `drafter.name` is the plugin's pointer, into
-     * storage this program does not own, and pointing it at drafter_name instead would not
-     * survive the program being moved or copied out of the builder: a short name is stored inside
-     * the std::string object itself, so the pointer would name the builder's copy after it is
-     * gone. Left null, a reader that forgets this gets nothing rather than freed memory; the
-     * engine points its own copy of the decl at its own copy of the string. */
+    /* The name lives only in drafter_name. `drafter.name` points into plugin storage, and
+     * pointing it at drafter_name would not survive moving the Program (a short string is stored
+     * inline in the std::string). Left null, a careless reader gets nothing instead of freed
+     * memory; the engine points its own copy of the decl at its own string. */
     prog_.drafter      = *d;
     prog_.drafter_name = nm;
     prog_.drafter.name = nullptr;
@@ -1385,9 +1282,8 @@ int Builder::declare_drafter(const RadDrafterDecl* d) {
     return RAD_OK;
 }
 
-/* A SERIAL HEAD THAT READS THE TRUNK'S CACHE AND KEEPS NONE (rad_builder.h). Checked here for the
- * reason declare_drafter checks everything: the driver only reaches the head once a request
- * speculates, and a head staged the wrong way round costs acceptance and says nothing. */
+/* A serial head that reads the trunk's cache and keeps none (rad_builder.h). Validated at declare
+ * for the same reason as declare_drafter. */
 int Builder::drafter_shared_kv(int pos_offset) {
     if (finished_) {
         err(RAD_E_STATE, "drafter_shared_kv after declare finished");
@@ -1419,13 +1315,9 @@ void Builder::note_v(const char* f, va_list ap) {
 
 /* ================================================================== finalise */
 void Builder::finish_weight_uses() {
-    /* Layer offload is a scheduling problem and not a prediction one precisely because this walk
-     * exists: declare enumerated every op with its weight operands in order, so the core knows
-     * the entire future access sequence statically and prefetch is exact (spec §5).
-     *
-     * An op that did not resolve still counts here. That widens a weight's interval by at most the
-     * op the plugin fell back from, and widening it means prefetching earlier and freeing later --
-     * conservative in the safe direction. */
+    /* Declare enumerated every op and its weights in order, so the access sequence is known
+     * statically and prefetch is exact (spec §5). Unresolved ops still count, which can only widen
+     * an interval (prefetch earlier, free later): the safe direction. */
     for (size_t i = 1; i < prog_.ops.size(); ++i) {
         const OpInfo& o = prog_.ops[i];
         for (rad_weight h : o.weights) {
@@ -1437,32 +1329,40 @@ void Builder::finish_weight_uses() {
     }
 }
 
-/* The weight layout pass (spec §4.3).
+/* The weight layout pass (spec §4.3). Each kernel's layout hook, given the weight's encoding and
+ * this rank's planes, states the stored form it wants (e.g. libr4d's gemm_w4a8 wants WMMA fragment
+ * order); the manifest records it and the loader produces it with the same kernel's relayout. A
+ * hook may also refuse an encoding, which becomes a declare error naming weight, encoding and
+ * kernel.
  *
- * Nothing in the core knows that libr4d's gemm_w4a8 wants its codes in WMMA fragment order: libr4d
- * says so through its layout hook, given the weight's encoding and this rank's share of its
- * planes, and the manifest records what it said. The loader produces it with the same kernel's
- * relayout. The hook is also where a kernel REFUSES an encoding it does not read, and that refusal
- * is a declare-time error naming the weight, the encoding and the kernel.
+ * A weight is stored once, so two kernels wanting different stored forms is an error, reported
+ * here rather than as a shape mismatch at load.
  *
- * A weight touched by two kernels that want DIFFERENT stored forms is a real, diagnosable failure
- * and it is named here: a weight is stored once. Discovering that at load, as a shape mismatch,
- * would be much worse. */
+ * Device rows claim first, over every op, and host rows after them. A host row only claims a
+ * weight no device row did: on a card a host row is the fallback of a device kernel that may
+ * relayout, and a different reading there is not an error but a reason the op cannot move to the
+ * host, which the runtime's check_domain_layout decides. On the host backend there are no device
+ * rows, and the host rows' hooks decide the stored form (a weight over several planes is joined
+ * by them, abi/rad_planes.h). */
 void Builder::finish_layouts() {
-    /* Who asked for each weight's layout, so a conflict names both kernels rather than one. */
+    /* Who asked for each weight's layout, so a conflict names both kernels, and on which domain. */
     std::vector claimant(prog_.weights.size());
+    std::vector claim_dom(prog_.weights.size(), -1);
+    /* The host kernels that read a weight over several planes without joining them, for the error
+     * when nothing else does. */
+    std::vector unjoined(prog_.weights.size());
 
+    for (int d : { (int)RAD_DOMAIN_DEVICE, (int)RAD_DOMAIN_HOST })
     for (size_t i = 1; i < prog_.ops.size(); ++i) {
         const OpInfo& o = prog_.ops[i];
         if (o.weights.empty()) continue;
 
-        /* The hook indexes the schema's POSITIONAL operand list, not the weight list, and
-         * OpInfo::weight_opd is that map -- recorded at declare because RAD_OPD_WTAB makes it
-         * many-to-one, so it is not a function of the weight's index. */
+        /* The hook indexes the schema's positional operand list; OpInfo::weight_opd maps weights
+         * to it. */
         for (size_t wi = 0; wi < o.weights.size(); ++wi) {
             rad_weight h = o.weights[wi];
             if (h == 0 || h >= prog_.weights.size()) continue;
-            /* An optional weight the source does not hold is absent, and no kernel reads it. */
+            /* An optional weight the source lacks is absent; no kernel reads it. */
             if (sources_ && !prog_.weights[h].enc_known && prog_.weights[h].decl.optional)
                 continue;
             int operand = wi < o.weight_opd.size() && o.weight_opd[wi] >= 0
@@ -1470,39 +1370,27 @@ void Builder::finish_layouts() {
 
             for (size_t bi = 0; bi < o.bands.size(); ++bi) {
                 const Band& b = o.bands[bi];
-                for (int d = 0; d < RAD_N_DOMAINS; ++d) {
+                {
                     const Resolved& r = b.dom[d];
                     if (!r || !r.row->info) continue;
                     const RadKernelInfo* ki = r.row->info;
                     WeightInfo& w = prog_.weights[h];
 
-                    /* THIS RANK'S PLANES, as geometry: what the kernel will be handed, minus the
-                     * bytes. */
+                    /* This rank's planes as geometry, without data. */
                     RadTensor t[RAD_ENC_MAX_PLANES];
                     weight_planes(w, t);
 
-                    /* A ROW WITH NO LAYOUT HOOK IS NOT SILENT: it is asserting that it reads the
-                     * selected plane AS IT IS. Reading it as "no opinion" instead admits a whole
-                     * class of bug.
+                    /* A device row with no layout hook claims the selected plane as stored; it is
+                     * not "no opinion". All bands of an op read the same stored bytes, so if one
+                     * band's kernel relayouts and another's does not, the second misreads them
+                     * with a matching byte count. Example: on an fp8 lm_head, logits_gemm_fp8
+                     * (M <= 32) packs codes and scales per row, while logits_gemm_bf16 above it
+                     * would read the E4M3 codes as bf16 and return empty completions once
+                     * batches grow.
                      *
-                     * The bands of one op can resolve to different kernels -- M <= 32 to one and
-                     * M <= 64 to another -- and they all read THE SAME STORED BYTES, because a
-                     * weight is stored once. If one of them relayouts and another does not, the
-                     * second reads the first one's arrangement under a different interpretation,
-                     * and nothing downstream can catch that: the byte count matches.
-                     *
-                     * The shape it takes, on an fp8 lm_head: logits_gemm_fp8 serves M <= 32 and
-                     * asks for codes and scales in one row; the band above it falls to
-                     * logits_gemm_bf16, which has no hook and reads the E4M3 codes as bf16. Such a
-                     * model loads, serves every request under 32 rows correctly, and returns EMPTY
-                     * completions the moment enough sequences batch together.
-                     *
-                     * THE HOST DOMAIN IS EXEMPT from claiming the plane as it is, and that is not
-                     * an oversight. libref reads every weight canonically and declares no hook, so
-                     * every op with a relaying device kernel would collide with its own reference
-                     * fallback and no model would declare at all. The reference reading a
-                     * relayed weight is a real hazard, but it is the one
-                     * rad_gate_reference_kernels already refuses to serve on. */
+                     * A host row with no hook, or one declining the operand, is exempt: it reads
+                     * the planes as the container stores them, and counting it would make every
+                     * relayouting device op conflict with its own fallback. */
                     RadLayout L{};
                     const int st = ki->layout ? ki->layout(r.geom.params(), r.geom.n_params(),
                                                            operand, &w.enc, w.sel, t, w.n_sel, &L)
@@ -1521,10 +1409,16 @@ void Builder::finish_layouts() {
                             enc, rad_strerror(st));
                         continue;
                     }
-                    if (st == RAD_E_UNSUPPORTED && d != RAD_DOMAIN_DEVICE) continue;
+                    if (st == RAD_E_UNSUPPORTED && d != RAD_DOMAIN_DEVICE) {
+                        if (w.n_sel > 1 && unjoined[h].find(ki->name) == std::string::npos)
+                            unjoined[h] += (unjoined[h].empty() ? "" : ", ") + std::string(ki->name);
+                        continue;
+                    }
 
                     const std::string tag = st == RAD_OK ? (L.tag && *L.tag ? L.tag : ki->name)
                                                          : std::string();
+                    /* A device row's form stands; this host row then cannot take the op. */
+                    if (d == RAD_DOMAIN_HOST && claim_dom[h] == RAD_DOMAIN_DEVICE) continue;
                     if (!claimant[h].empty() && w.layout_tag != tag) {
                         err(RAD_E_SHAPE,
                             "weight '%s' is wanted in two stored forms: '%s' by %s and '%s' by %s. "
@@ -1539,6 +1433,7 @@ void Builder::finish_layouts() {
                     }
                     if (!claimant[h].empty()) continue;   /* the same form, asked again */
                     claimant[h] = ki->name;
+                    claim_dom[h] = d;
 
                     if (tag.empty()) {
                         if (w.n_sel != 1)
@@ -1568,8 +1463,8 @@ void Builder::finish_layouts() {
                     for (uint32_t k = 0; k < RAD_MAX_RANK; ++k)
                         w.stored_shape[k] = k < L.rank ? L.shape[k] : 0;
                     if (L.align > 0) w.align = L.align;
-                    /* The hook's byte count wins: it includes whatever padding the layout implies,
-                     * and the core cannot derive that from a shape. */
+                    /* The hook's byte count wins: it includes layout padding the core cannot derive
+                     * from a shape. */
                     if (L.bytes > 0) {
                         w.stored_bytes = L.bytes;
                     } else {
@@ -1590,13 +1485,18 @@ void Builder::finish_layouts() {
     }
 
     /* A weight taking several planes as one operand needs a kernel to join them; one no op reads
-     * has none. */
+     * has none, and neither has one read only by host kernels without a hook for it. */
     for (size_t h = 1; h < prog_.weights.size(); ++h) {
         const WeightInfo& w = prog_.weights[h];
-        if (w.n_sel > 1 && w.identity && claimant[h].empty())
+        if (w.n_sel <= 1 || !w.identity || !claimant[h].empty()) continue;
+        if (unjoined[h].empty())
             err(RAD_E_SHAPE, "'%s' takes %d planes of '%s' as one weight and no op reads it, so "
                              "nothing says how they are stored", w.name.c_str(), w.n_sel,
                 w.source.c_str());
+        else
+            err(RAD_E_SHAPE, "'%s' takes %d planes of '%s' as one weight, and the host kernels "
+                             "reading it (%s) have no layout that joins them (abi/rad_planes.h)",
+                w.name.c_str(), w.n_sel, w.source.c_str(), unjoined[h].c_str());
     }
 }
 
@@ -1606,51 +1506,35 @@ void Builder::finish_kv_groups() {
         const RadKVGroupDecl& d = gi.decl;
 
         if ((d.kind == RAD_KV_FULL || d.kind == RAD_KV_WINDOW) && gi.block_size == 0) {
-            /* The plugin may never have asked. The manifest still needs the answer, and asking
-             * here reports the same diagnostic it would have got. */
+            /* The plugin may never have asked; the manifest still needs the answer. */
             kv_block_size((rad_kvgroup)g);
         }
 
         int64_t elem_n_head = d.n_head_kv > 0 ? d.n_head_kv : 1;
-        /* EVERY LAYER BOUND TO THE GROUP, because that is what a page is. KVManager documents both
-         * of these as covering the whole bundle -- "one page covers every layer bound to the group.
-         * That is where the zero-padding property lives" -- and its own fallback formula multiplies
-         * by the layer count. A figure computed here for ONE layer under-sizes the pool by the
-         * layer count, because that fallback is unreachable whenever the builder supplies a value:
-         * the manager then divides a one-layer page across every bound layer, giving a per-layer
-         * stride that is a fraction of a layer and a layer base pointer that need not even be
-         * 2-byte aligned. It surfaces as an alignment refusal from the attention kernel at the
-         * SECOND bound layer, layer 0 being at offset 0. */
+        /* Sizes cover every layer bound to the group: KVManager defines a page as covering all of
+         * them and divides it across the bound layers. A one-layer figure would make the per-layer
+         * stride a fraction of a layer (misaligned from the second bound layer on). */
         const int64_t n_bound = gi.layers.empty() ? 1 : (int64_t)gi.layers.size();
         switch (d.kind) {
             case RAD_KV_FULL:
             case RAD_KV_WINDOW:
-                /* One block holds K and V for block_size tokens: the pair is the unit the block
-                 * manager allocates, so it is the unit sized here. */
+                /* One block holds K and V for block_size tokens, the block manager's unit. */
                 gi.bytes_per_block =
                     rad_dtype_bytes(d.dtype, 2 * gi.block_size * elem_n_head * d.head_dim) * n_bound;
                 gi.bytes_per_state = 0;
                 break;
             case RAD_KV_LINEAR:
-                /* Per sequence and fixed size: 32 heads of 128x128 fp32 is 2 MiB a layer, which
-                 * is why it cannot be snapshotted per block (spec §7.3). */
+                /* Per sequence, fixed size (32 heads of 128x128 fp32 is 2 MiB a layer), so it
+                 * cannot be snapshotted per block (spec §7.3). */
                 gi.bytes_per_block = 0;
                 gi.bytes_per_state = rad_dtype_bytes(
                     d.dtype, elem_n_head * (d.state_dim[0] ? d.state_dim[0] : 1)
                                          * (d.state_dim[1] ? d.state_dim[1] : 1)) * n_bound;
                 break;
             case RAD_KV_CONV: {
-                /* A rolling window of conv_width-1 + n_spec entries, so a speculative rejection
-                 * is a change of read offset rather than a recompute (spec §10). The window is
-                 * sized for the largest speculative window this deployment was configured for.
-                 *
-                 * EXACTLY THE STATE TENSOR'S EXTENT, conv_window_entries(), and not one more. The
-                 * kernels lay the slots out from the tensor, so an allocation one entry wider a
-                 * slot puts the manager's slot `s` -- the bytes it clears when it hands the slot
-                 * out, and saves and restores at a checkpoint -- over the start of the kernels'
-                 * slot `s + 1`. Handing a slot to a new sequence then zeroes part of a running
-                 * sequence's window. conv_state_index's cursor cycles by the same number, so it
-                 * stays inside the slot. */
+                /* A rolling window of conv_width-1 + max_spec entries, so a speculative rejection
+                 * moves the read offset instead of recomputing (spec §10). Must be exactly
+                 * conv_window_entries(), the state tensor's extent; see its comment. */
                 int64_t entries = conv_window_entries(d, prog_.ctx.max_spec);
                 if (entries <= 0) entries = 1;
                 gi.bytes_per_block = 0;
@@ -1664,10 +1548,9 @@ void Builder::finish_kv_groups() {
         gi.drafter = prog_.meta.n_layers > 0 && !gi.layers.empty() &&
                      gi.layers.front() >= prog_.meta.n_layers;
 
-        /* A group nothing is bound to is a group the block manager cannot size: how many state
-         * instances a sequence owns is the layer count, and assuming one would make the page size
-         * a guess. KVManager::configure refuses it, so it is refused here where the name of the
-         * missing call is still obvious. */
+        /* A group with no bound layers cannot be sized (the layer count is the number of state
+         * instances per sequence). KVManager::configure would refuse it; refuse here, where the
+         * missing call is obvious. */
         if (gi.layers.empty())
             err(RAD_E_STATE,
                 "kv group '%s' has no layers bound: call rad_bind_layer_kv(b, layer, g) for every "
@@ -1677,65 +1560,41 @@ void Builder::finish_kv_groups() {
 }
 
 void Builder::finish_buffer_liveness() {
-    const int32_t last_op = (int32_t)prog_.ops.size() - 1;
-    /* A program that runs a second lane gets a second scratch region with it: see
-     * Program::scratch_regions. The concurrent buffers are how an architecture says it has one. */
+    const int32_t last_op = std::max((int32_t)prog_.ops.size() - 1, 0);
+    /* A second lane, signalled by any concurrent buffer, gets a second scratch region
+     * (Program::scratch_regions). */
     prog_.scratch_regions = concurrent_bufs_.empty() ? 1 : 2;
 
-    for (size_t i = 1; i < prog_.buffers.size(); ++i) {
+    /* Each buffer's first and last declaring op, in one pass over the op lists. */
+    const size_t nb = prog_.buffers.size();
+    std::vector first(nb, -1), last(nb, -1);
+    for (size_t o = 1; o < op_bufs_.size(); ++o)
+        for (const std::vector* v : { &op_bufs_[o].reads, &op_bufs_[o].writes })
+            for (rad_buf h : *v) {
+                if (first[h] < 0) first[h] = (int32_t)o;
+                last[h] = (int32_t)o;
+            }
+
+    for (size_t i = 1; i < nb; ++i) {
         BufferInfo& b = prog_.buffers[i];
-
-        /* PERSIST survives across steps and DERIVED is written once per step by the core before
-         * any op runs. Both are live at every op by construction, and saying so here rather than
-         * leaving -1 means one rule reads the field and the plan and the dump agree. */
-        if (b.decl.kind != RAD_BUF_TRANSIENT) {
+        /* Live at every op: PERSIST and DERIVED (set explicitly so the plan and the dump read one
+         * rule); a buffer on the second lane, whose declared range does not bound when its bytes
+         * are in use; and one with no declared use, since an op may issue any handle in any
+         * order (--debug-graph reports the cost). */
+        if (b.decl.kind != RAD_BUF_TRANSIENT || concurrent_bufs_.count((rad_buf)i) || first[i] < 0) {
             b.first_def = 0;
-            b.last_use  = last_op > 0 ? last_op : 0;
+            b.last_use  = last_op;
             continue;
         }
+        b.first_def = first[i];
+        b.last_use  = last[i];
 
-        /* The second lane: the declared range is not a bound on when the bytes are in use. */
-        if (concurrent_bufs_.count((rad_buf)i)) {
-            b.first_def = 0;
-            b.last_use  = last_op > 0 ? last_op : 0;
-            continue;
-        }
-
-        int32_t first = -1, last = -1;
-        for (size_t o = 1; o < op_bufs_.size(); ++o) {
-            auto touches = [&](const std::vector& v) {
-                return std::find(v.begin(), v.end(), (rad_buf)i) != v.end();
-            };
-            if (!touches(op_bufs_[o].reads) && !touches(op_bufs_[o].writes)) continue;
-            if (first < 0) first = (int32_t)o;
-            last = (int32_t)o;
-        }
-
-        if (first < 0) {
-            /* Nothing declared a use. The sound assumption is the whole program: an op may issue
-             * any handle obtained during declare, in any order, so declaration position proves
-             * nothing about when a buffer is read. It costs sharing, and --debug-graph says how
-             * much (see rad_build.h on rad_op_reads/rad_op_writes). */
-            b.first_def = 0;
-            b.last_use  = last_op > 0 ? last_op : 0;
-        } else {
-            b.first_def = first;
-            b.last_use  = last;
-        }
-
-        /* THE LOGITS BUFFER IS READ AFTER THE DECLARED OP LIST AND NOT BY IT. The plugin's lm_head
-         * WRITES it and declares that write, so liveness derived from declarations alone ends its
-         * life at that op -- and everything that actually consumes it comes later: the sampler's
-         * stages (core/sample/sampler.cpp declares its ops with no buffer lists, because its own
-         * planes are PERSIST for the same reason), the logprob readback, and the engine.
-         *
-         * Extending it to the last op is the truthful statement and costs nothing measurable: the
-         * lm_head is at the end of the graph, so the set of buffers still live after it is nearly
-         * empty and nothing that shared with logits before is prevented from doing so. The
-         * undeclared-use guard in core/runtime/issue.cpp is what refuses the untruthful version. */
-        if ((rad_buf)i == prog_.logits_buf && last_op > b.last_use) b.last_use = last_op;
-        /* The pooled output for the same reason: the engine reads it after the last op. */
-        if ((rad_buf)i == prog_.pooled_buf && last_op > b.last_use) b.last_use = last_op;
+        /* The logits buffer is read after the declared op list: the sampler (whose ops declare no
+         * buffer lists; its planes are PERSIST), the logprob readback and the engine. Extend its
+         * life to the last op. The lm_head is at the end of the graph, so this costs almost no
+         * sharing; the undeclared-use guard in core/runtime/issue.cpp enforces it. The pooled
+         * output likewise: the engine reads it after the last op. */
+        if ((rad_buf)i == prog_.logits_buf || (rad_buf)i == prog_.pooled_buf) b.last_use = last_op;
     }
 }
 
@@ -1743,17 +1602,16 @@ int Builder::finish() {
     if (finished_) return status_;
     finished_ = true;
 
-    /* A sizing declare wants its buffers and their liveness and nothing else: its kernels are the
-     * real declare's, already initialised, and its weights and KV groups are never used. */
+    /* A sizing declare needs only buffers and liveness; its kernels are the real declare's and its
+     * weights and KV groups are unused. */
     if (ref_) {
         finish_buffer_liveness();
         return status_;
     }
 
-    /* A WEIGHT DECLARED BEFORE ITS NAME MAP was read as plain in its declared dtype, and its
-     * kernels were chosen for that: the checkpoint or the recipe behind the builder is searched
-     * through the name map, so asking first finds nothing. Asked again now, a source that answers
-     * is that ordering, named rather than served as the wrong encoding. */
+    /* A weight declared before its name-map entry was looked up and not found (sources are
+     * searched through the name map), so it was read as plain and its kernels chosen for that. If
+     * the source answers now, report the ordering rather than serve the wrong encoding. */
     if (sources_)
         for (size_t h = 1; h < prog_.weights.size(); ++h) {
             const WeightInfo& w = prog_.weights[h];
@@ -1769,9 +1627,8 @@ int Builder::finish() {
     finish_weight_uses();
     finish_layouts();
     finish_kv_groups();
-    /* A HEAD DECLARED TO KEEP NO CACHE OF ITS OWN (rad_drafter_shared_kv) is given no history pass:
-     * the scheduler owes it none. A KV group bound at one of its layers -- meta.n_layers and above
-     * are the drafter's -- would then be read without anything ever having written it. */
+    /* A head with no cache of its own (rad_drafter_shared_kv) gets no history pass, so a KV group
+     * bound at one of its layers (meta.n_layers and above) would be read but never written. */
     if (prog_.drafter_shared_kv)
         for (size_t g = 1; g < prog_.kv_groups.size(); ++g)
             for (int l : prog_.kv_groups[g].layers)
@@ -1788,22 +1645,11 @@ int Builder::finish() {
     if (s < 0 && status_ == RAD_OK) status_ = s;
 
     if (!prog_.misses.empty()) {
-        /* Reported whole, at the end, never the first failure at the top (spec §1 step 4). Which
-         * of these is fatal is the engine's call: a device miss covered by a host kernel costs
-         * speed, a host miss costs a placement option, and one covered by neither costs the
-         * model.
-         *
-         * SPLIT BY DOMAIN, because the two counts mean different things and one total means
-         * neither. Every caller of this that is not the engine -- rad-check, rad-tune, rad-convert
-         * -- reads this line and nothing else, so it has to say which kind it found. */
-        /* A device miss a host kernel stands in for is not a hole -- the planner runs it there
-         * (Program::device_holes has the rule, engine_bringup.cpp's miss_report the longer
-         * account). Counting it as a device miss makes a deliberately host-only op open every
-         * run with a warning that names a hole there is not. */
+        /* Reported whole at the end (spec §1 step 4); the engine decides what is fatal. Split by
+         * domain, since the tools read only this line. A device miss a host kernel stands in for
+         * is not a hole (Program::device_holes; engine_bringup.cpp's miss_report). */
         const size_t dev = prog_.device_holes(device_is_host()).size();
-        /* A host-only miss set is not a warning at all -- see the report in engine_bringup.cpp --
-         * so it does not get warned about here either. The device count is the one that means
-         * something to a tool reading this line and nothing else. */
+        /* Host-only misses are not a warning (see engine_bringup.cpp). */
         RAD_LOG_AT(dev ? Log::Warn : Log::Debug,
                    "declare: %zu device band(s) and %zu host band(s) resolved to nothing; "
                    "run with --debug-graph for the full list", dev, prog_.misses.size() - dev);
@@ -1814,8 +1660,8 @@ int Builder::finish() {
 }  /* namespace rad */
 
 /* ================================================================== the C surface */
-/* Every entry point in rad_builder.h. Each is a static_cast and a forward: the handle IS the
- * builder, so there is no table lookup between a plugin's call and the work. */
+/* Every entry point in rad_builder.h: a static_cast and a forward, since the handle is the
+ * builder. */
 extern "C" {
 
 static rad::Builder* B(RadBuilder* b) { return static_cast(b); }
@@ -1867,9 +1713,6 @@ int rad_op_declared(RadBuilder* b, const char* op) {
     return B(b)->op_declared(op);
 }
 
-/* Proposed additions to rad_builder.h -- defined here so the mechanism exists and core-side
- * callers (rad-convert, the tests) can use it. A C plugin cannot until the declarations
- * move into the frozen header. */
 int rad_op_reads(RadBuilder* b, rad_op h, const rad_buf* bufs, int n) {
     if (!b || (!bufs && n)) return RAD_E_INVAL;
     return B(b)->op_reads(h, bufs, n);
@@ -1944,8 +1787,8 @@ void rad_note(RadBuilder* b, const char* f, ...) {
     va_end(ap);
 }
 
-/* ---- model metadata accessors. The free-form key/value the container header carried, which the
- * struct above does not name. The core never interprets these; a plugin reads what it needs. */
+/* ---- model metadata accessors for the container header's free-form key/values. The core never
+ * interprets these; a plugin reads what it needs. */
 static const char* meta_lookup(const RadModelMeta* m, const char* key) {
     if (!m || !key || !m->kv_key || !m->kv_val) return nullptr;
     for (int i = 0; i < m->n_kv; ++i)
diff --git a/core/build/rad_graph.cpp b/core/build/rad_graph.cpp
index 5da19486..410544bc 100644
--- a/core/build/rad_graph.cpp
+++ b/core/build/rad_graph.cpp
@@ -1,20 +1,16 @@
-/* rad_graph.cpp -- `--debug-graph` (spec §16).
+/* rad_graph.cpp -- `--debug-graph` (spec §16): the full record of what runs. Every op in declared
+ * order with its bucket table (one line per band: the resolving kernel, variant and plugin), the
+ * matched constraints, the weights it touches and the buffer it writes; then the weight manifest,
+ * buffer plan, KV groups, tuning requests and miss report.
  *
- * "It is unclear what even runs" is the complaint this project exists to answer, so this is not a
- * debug print: it is the artifact. Every op in declared order, its bucket table with one line per
- * band, the kernel and variant that resolved each band and which plugin it came from, the
- * constraints that matched, the weights it touches and the buffer it writes -- then the weight
- * manifest, the buffer plan, the KV groups, the tuning requests and the miss report.
- *
- * The bucket-table block is byte-for-byte the format in spec §2.2:
+ * The bucket-table block is exactly the format in spec §2.2:
  *
  *     gemm_w4a8_nt  N=8192 K=5120
  *         M <=   16  ->  gemm_w4a8_nt_m64        (libr4d, prio 20)
  *         M <=   64  ->  gemm_w4a8_nt_m64        (libr4d, prio 20)
  *         M <= 8192  ->  gemm_w4a8_prefill       (libr4d, prio 10)
  *
- * Everything this file adds beyond that goes on its own lines at a deeper indent, so the table
- * stays a table and stays greppable.
+ * Everything else goes on its own lines at a deeper indent, so the table stays greppable.
  */
 #include "rad_build.h"
 
@@ -29,14 +25,13 @@
 
 namespace rad {
 
-/* ordered_json, so the object reads in the order it was written -- a graph dump whose keys are
- * alphabetised is a graph dump nobody can scan. */
+/* ordered_json keeps keys in insertion order rather than alphabetical. */
 using json = nlohmann::ordered_json;
 
 namespace {
 
-/* A constraint as the kernel wrote it. constraint_why() in rad_util.cpp phrases the same thing as
- * a refusal ("M <= 16, have 8192"), which is right for the miss column and wrong here. */
+/* A constraint as the kernel wrote it. constraint_why() phrases it as a refusal
+ * ("M <= 16, have 8192") for the miss column. */
 std::string constraint_str(const RadConstraint& c) {
     switch (c.op) {
         case RAD_C_EQ:  return fmt("%s == %lld", c.key, c.ival);
@@ -48,22 +43,20 @@ std::string constraint_str(const RadConstraint& c) {
     }
 }
 
-/* "(libr4d, prio 20)" -- and the tuned point only when there was a choice to report. A kernel with no
- * declared axis has nothing to say about tuning, and printing "- (axis defaults)" for
- * every row of every table buries the ones that do (spec §15). */
+/* "(libr4d, prio 20)", plus the tuned point only for a kernel with declared axes, so rows that
+ * were tuned stand out (spec §15). */
 std::string origin(const Resolved& r) {
     const RadKernelInfo* k = r.row->info;
     if (!k || k->n_tunables <= 0) return fmt("(%s, prio %d)", r.row->plugin.c_str(),
                                              k ? k->priority : 0);
     const char* vn = r.choice.empty() ? "?" : r.choice.c_str();
-    /* Same spelling as render_band_table in core/plugin/: two dumps of one table that punctuate
-     * differently are two dumps somebody has to reconcile by eye. */
+    /* Same spelling as render_band_table in core/plugin/. */
     return fmt("(%s, prio %d, %s from %s)", r.row->plugin.c_str(), k->priority, vn,
                r.tune_source.empty() ? "axis defaults" : r.tune_source.c_str());
 }
 
-/* The left half of a band line, up to and including the arrow. Identical column positions in both
- * the ranged and the fixed case, so the two forms stack in one table. */
+/* The left half of a band line, through the arrow. Ranged and fixed forms share column positions
+ * so they stack in one table. */
 std::string band_prefix(const OpInfo& o, const Band& b) {
     if (o.ranged_key.empty()) return "    always     ->  ";
     if (b.hi == LLONG_MAX)    return fmt("    %s <=  any  ->  ", o.ranged_key.c_str());
@@ -82,8 +75,7 @@ void dump_bucket_table(std::string& s, const OpInfo& o, int d) {
             s += band_prefix(o, b) + fmt("%-24s", r.row->info ? r.row->info->name : "?")
                + origin(r) + "\n";
         } else {
-            /* The missing-kernel report is per band. A range with a hole in it is reported as that
-             * band, not as the whole op (spec §2.2). */
+            /* Misses are reported per band, not per op (spec §2.2). */
             s += band_prefix(o, b) + fmt("%-24s", "(nothing)")
                + "-- " + (b.miss[d].empty() ? "no kernel matched" : b.miss[d]) + "\n";
         }
@@ -91,8 +83,7 @@ void dump_bucket_table(std::string& s, const OpInfo& o, int d) {
 }
 
 void dump_matched(std::string& s, const OpInfo& o, int d) {
-    /* One line per distinct kernel rather than per band: sixty-four layers and three bands sharing
-     * one kernel is one fact, not a hundred and ninety-two. */
+    /* One line per distinct kernel, not per band. */
     std::vector seen;
     for (const Band& b : o.bands) {
         const Resolved& r = b.dom[d];
@@ -110,21 +101,14 @@ void dump_matched(std::string& s, const OpInfo& o, int d) {
     }
 }
 
-/* Append a table row with the trailing columns trimmed. The tier and site columns are empty at
- * declare -- the planner fills them -- and a line of trailing spaces is a diff nobody wants to
- * read twice. */
+/* Append a table row with trailing spaces trimmed; the tier and site columns are empty at declare
+ * (the planner fills them). */
 void append_row(std::string& s, std::string row) {
     while (!row.empty() && row.back() == ' ') row.pop_back();
     s += row;
     s += '\n';
 }
 
-std::string join_names(const std::vector& v) {
-    std::string s;
-    for (size_t i = 0; i < v.size(); ++i) { if (i) s += ", "; s += v[i]; }
-    return s;
-}
-
 }  /* namespace */
 
 std::string dump_graph_str(const Program& p, const std::vector* errors) {
@@ -144,9 +128,8 @@ std::string dump_graph_str(const Program& p, const std::vector* err
         if (!params.empty()) { s += "  "; s += params; }
         s += "\n";
 
-        /* Device first and unlabelled, which is the §2.2 form. A host-only kernel set -- which is
-         * the primary development target here, not a fallback -- gets its table labelled instead
-         * of a table of holes. */
+        /* Device first and unlabelled, the §2.2 form. A host-only kernel set (a primary target,
+         * not a fallback) gets a labelled host table instead of a device table of holes. */
         bool dev = domain_has_any(o, RAD_DOMAIN_DEVICE);
         bool hst = domain_has_any(o, RAD_DOMAIN_HOST);
         bool printed_device = dev || !hst;
@@ -164,25 +147,24 @@ std::string dump_graph_str(const Program& p, const std::vector* err
             std::vector names;
             for (rad_weight h : o.weights)
                 names.push_back(h < p.weights.size() ? p.weights[h].name : fmt("", h));
-            s += fmt("      weights  %s\n", join_names(names).c_str());
+            s += fmt("      weights  %s\n", join(names).c_str());
         }
 
-        /* The buffer this op writes, read off the plan rather than off a second bookkeeping
-         * structure: a transient whose live range begins here is one this op defines. */
+        /* Buffers this op writes, read off the plan: a transient whose live range begins here is
+         * defined by this op. */
         std::vector defs, ends;
         const int32_t nops = (int32_t)p.ops.size() - 1;
         for (size_t bi = 1; bi < p.buffers.size(); ++bi) {
             const BufferInfo& b = p.buffers[bi];
             if (b.decl.kind != RAD_BUF_TRANSIENT) continue;
-            /* A buffer whose live range is the whole program is one nothing declared a use for.
-             * Printing it against the first and last op would be inventing a fact; the buffer plan
-             * says how many of these there are, which is the honest version. */
+            /* Whole-program liveness means no declared use; attributing it to the first and last
+             * op would be wrong. The buffer plan section counts these. */
             if (b.first_def <= 0 && b.last_use >= nops) continue;
             if (b.first_def == (int32_t)i) defs.push_back(b.name);
             else if (b.last_use == (int32_t)i) ends.push_back(b.name);
         }
-        if (!defs.empty()) s += fmt("      writes   %s\n", join_names(defs).c_str());
-        if (!ends.empty()) s += fmt("      last use %s\n", join_names(ends).c_str());
+        if (!defs.empty()) s += fmt("      writes   %s\n", join(defs).c_str());
+        if (!ends.empty()) s += fmt("      last use %s\n", join(ends).c_str());
 
         s += "\n";
     }
@@ -197,10 +179,9 @@ std::string dump_graph_str(const Program& p, const std::vector* err
                       "layout", "tier", "site"));
     for (size_t i = 1; i < p.weights.size(); ++i) {
         const WeightInfo& w = p.weights[i];
-        /* `layout` is what the resolved kernel asked its weights be stored as, and it is why the
-         * stored bytes may differ from the logical ones. tier and site are left blank on purpose:
-         * the planner fills them, after declare and before load, and printing a default here would
-         * read as a decision nobody made. */
+        /* `layout` is the storage form the resolved kernel asked for, which is why stored bytes may
+         * differ from logical ones. tier and site stay blank: the planner fills them after
+         * declare, and a default would read as a decision. */
         append_row(s, fmt("  %-40s %12s %6lld  %-12s %6d %7d %6d %6d  %-16s %-5s %-5s",
                           w.name.c_str(), humanb(w.stored_bytes).c_str(), (long long)w.align,
                           bld_access_name(w.decl.access), w.decl.group.layer, w.decl.group.expert,
@@ -238,8 +219,7 @@ std::string dump_graph_str(const Program& p, const std::vector* err
              humanb(p.arena_bytes - persist).c_str(), humanb(sum).c_str(),
              humanb(peak).c_str(), humanb(p.arena_bytes - persist - peak).c_str());
     s += fmt("  persist     %12s\n", humanb(persist).c_str());
-    /* Two arenas, coloured separately: a host-site activation cannot index device memory, so each
-     * domain gets its own offset space and its own high-water mark. */
+    /* Two arenas, coloured separately (see plan_buffers). */
     if (p.host_arena_bytes)
         s += fmt("  host arena  %12s   (its own offset space and its own base pointer)\n",
                  humanb(p.host_arena_bytes).c_str());
@@ -308,18 +288,10 @@ std::string dump_graph_str(const Program& p, const std::vector* err
 
     /* ---------------------------------------------------------------- fusions (spec §2.3)
      *
-     * WHICH OF THIS PROGRAM'S LAUNCHES ARE STANDING IN FOR SEVERAL OPS, AND WHAT ARE THEY.
-     *
-     * spec.md:19 lists "fusion coverage" as one of the seven patch classes this engine exists to
-     * answer, and its answer is "fused ops are ops you can select on" -- a claim that needs a
-     * number behind it, which is this section. A kernel that declares `replaces` is a kernel
-     * saying, in data rather than in prose, which conventional chain it computes. That is what
-     * makes it substitutable, it is what rad-check checks it against, and it is what this prints.
-     *
-     * Read this as coverage, not as advice to act on: an op with no fusion is not a defect, and a
-     * fusion that did not fire is usually banded on purpose. What the section is for is answering
-     * "what actually ran" without reading the kernel source, which is the complaint the whole
-     * graph dump exists to answer. */
+     * Launches that stand in for several ops. A kernel with `replaces` declares, as data, the
+     * conventional chain it computes; rad-check checks it against that chain. This section is
+     * coverage, not advice: an op with no fusion is not a defect, and a fusion that did not fire
+     * is usually banded on purpose. */
     {
         std::vector lines;
         int n_fused = 0, n_ops_replaced = 0;
@@ -329,20 +301,15 @@ std::string dump_graph_str(const Program& p, const std::vector* err
                 for (int d = 0; d < RAD_N_DOMAINS; ++d) {
                     const Resolved& r = o.bands[b].dom[d];
                     if (!r || !r.row || !r.row->info || !r.row->info->replaces) continue;
-                    /* Walk the chain the kernel names. The hook reports its own length by
-                     * declining the step past the end, so there is no count to disagree with it. */
+                    /* Walk the chain; the hook ends it by declining the step past the end. */
                     std::string chain;
                     int n_step = 0;
                     for (int step = 0; step < RAD_MAX_FUSE_OPD; ++step) {
                         RadFuseStep fs{};
-                        /* RAD_FUSE_PRESENT_ALL, and it is the honest answer here rather than a
-                         * shortcut. A declared graph records which OPS were declared and at what
-                         * geometry; it does not record which optional operands each issue passes,
-                         * because that is a property of a step and this dump is a property of the
-                         * program. So the kernel is asked to describe the chain for the operand set
-                         * its own description publishes, which is exactly what the constant means,
-                         * and the row below is read as "what this kernel stands in for" rather than
-                         * as "what ran on the last token". */
+                        /* RAD_FUSE_PRESENT_ALL: the declared graph records ops and geometry, not
+                         * which optional operands a given issue passes (a per-step property). So
+                         * the row means "what this kernel stands in for", described for the operand
+                         * set the kernel publishes, not "what ran on the last token". */
                         const int st = r.row->info->replaces(r.geom.params(), r.geom.n_params(),
                                                              RAD_FUSE_PRESENT_ALL,
                                                              step, &fs);
@@ -403,30 +370,22 @@ void dump_graph(const Program& p, FILE* out, const std::vector* err
     fflush(out ? out : stderr);
 }
 
-
 /* ================================================================== the graph, as JSON
  *
- * The same content as dump_graph_str and then some, for the server's Model view. NOT a second
- * source of truth: both walk the same Program and both call origin()/constraint_str()/the fuse
- * hook, so a kernel that reads one way in the text dump cannot read another way in the browser.
+ * dump_graph_str's content and more, for the server's Model view. It walks the same Program with
+ * the same helpers (origin, constraint_str, the fuse hook), so the two views cannot disagree.
  *
- * WHY IT CARRIES MORE THAN THE TEXT DUMP. A text dump is read top to bottom and every extra
- * column costs every reader; a view with a selection has somewhere to put the detail that only
- * matters once you have pointed at something. So the flow carries the shape and the panel carries
- * everything the core knows about ONE op: what the op means (its schema doc and its operands),
- * what geometry it was declared at, which kernel won each band AND WHICH ONES LOST AND WHY, what
- * that kernel says about itself, what it stands in for, which weights it reads at what size and
- * layout, and which buffers begin and end their lives at it.
+ * The extra detail lives in the per-op panel: the schema doc and operands, declared geometry,
+ * each band's winner and the candidates that lost with their reasons, the kernel's own
+ * description, what it stands in for, the weights read (size, layout) and the buffers whose lives
+ * begin and end at the op.
  *
- * GROUPED BY (op, band table). A 64-layer model declares the same op with the same bucket table
- * sixty-four times, and sixty-four identical rows is not more information than one row saying
- * "x64" -- it is the same information, spread over enough screen that nobody reads it. The
- * grouping key is what a reader would compare by eye: the op name and every band's resolution.
- * The per-occurrence facts (which weights, which buffers, which op index) are those of the FIRST
- * declaration in the group and are labelled as such in the page. */
+ * Ops are grouped by (op name, every band's resolution), so a per-layer op is one entry with a
+ * count. Per-occurrence facts (weights, buffers, op index) are the first declaration's, and the
+ * page labels them so. */
 
-/* A RadFuseStep's own geometry, which is NOT the fused op's -- `qk_norm_rope_gate` replaces an
- * rmsnorm at M = T * n_head, and nothing in the fused op's parameter list is that product. */
+/* A RadFuseStep's own geometry, which differs from the fused op's: `qk_norm_rope_gate` replaces
+ * an rmsnorm at M = T * n_head, a product absent from the fused op's parameters. */
 static std::string params_str(const RadParam* p, int n) {
     std::string s;
     for (int i = 0; i < n; ++i) {
@@ -443,18 +402,14 @@ static std::string params_str(const RadParam* p, int n) {
     return s;
 }
 
-/* The chain this kernel declares it computes, WITH each step's geometry. The names alone are the
- * advisory; the geometries are what make it checkable, and they are the part a reader cannot
- * derive. */
+/* The chain this kernel declares it computes, with each step's geometry, which makes the claim
+ * checkable and which a reader cannot derive. */
 static json fuse_steps(const Resolved& r) {
     json out = json::array();
     if (!r || !r.row || !r.row->info || !r.row->info->replaces) return out;
     for (int step = 0; step < RAD_MAX_FUSE_OPD; ++step) {
         RadFuseStep fs{};
-        /* RAD_FUSE_PRESENT_ALL -- see the long note at the same call in dump_graph_str: a declared
-         * graph records which ops were declared and at what geometry, not which optional operands
-         * each issue passes, so the kernel is asked to describe the chain for the operand set its
-         * own description publishes. */
+        /* RAD_FUSE_PRESENT_ALL: see the same call in dump_graph_str. */
         if (r.row->info->replaces(r.geom.params(), r.geom.n_params(),
                                   RAD_FUSE_PRESENT_ALL, step, &fs) != RAD_OK) break;
         if (!fs.op) break;
@@ -467,11 +422,9 @@ static json fuse_steps(const Resolved& r) {
     return out;
 }
 
-/* WHAT THIS KERNEL CAN DESCRIBE ABOUT ITSELF. Every one of these is an optional ABI hook, and
- * which of them a row supplies decides what the tools around it can do: no `opd_shape` and
- * rad-check skips the row by name, no `unrelayout` and a dense oracle has nothing to compare
- * against, no `replaces` and a fusion's claim stays prose. A reader asking "why does rad-check
- * skip this" is asking exactly this list. */
+/* The optional ABI hooks a kernel supplies, which decide what the tools can do with it: without
+ * `opd_shape` rad-check skips the row, without `unrelayout` a dense oracle has nothing to compare,
+ * without `replaces` a fusion is unchecked. */
 static json kernel_hooks(const RadKernelInfo* k) {
     json h = json::array();
     if (k->init)       h.push_back("init");
@@ -493,8 +446,7 @@ static json resolved_json(const Resolved& r) {
     j["priority"] = k->priority;
     j["geometry"] = r.geom.str();
     j["domain"]   = bld_domain_name(k->domain);
-    /* The kernel's own prose. It is written by the person who wrote the kernel and it is the only
-     * sentence in this whole structure that a reader does not have to reconstruct. */
+    /* The kernel author's own description. */
     if (k->family   && *k->family)   j["family"]   = k->family;
     if (k->computes && *k->computes) j["computes"] = k->computes;
     if (k->shape    && *k->shape)    j["shape"]    = k->shape;
@@ -503,11 +455,8 @@ static json resolved_json(const Resolved& r) {
     if (k->n_tunables > 0) {
         j["tuned"]        = r.choice;
         j["tuned_source"] = r.tune_source.empty() ? "axis defaults" : r.tune_source;
-        /* EVERY AXIS AND ITS WHOLE RANGE, not just what was chosen: "this kernel has these axes,
-           the tuner timed the legal points of them and picked these" is the sentence rad-tune
-           exists to produce, and the ranges are what make it one. It is also how a reader sees
-           that an axis HAS no alternatives at this shape, which is the difference between a tuned
-           choice and a forced one. */
+        /* Every axis with its full range, not just the choice, so a reader can tell a tuned
+           choice from a forced one (an axis with no alternatives at this shape). */
         json ax = json::array();
         int64_t space = 1;
         for (int i = 0; i < k->n_tunables; ++i) {
@@ -525,10 +474,8 @@ static json resolved_json(const Resolved& r) {
         j["tunables"]   = std::move(ax);
         j["tune_space"] = space;
     }
-    /* WHY THIS KERNEL: the constraints it declares, which are exactly what selection matched it
-     * on. A reader asking "why did this one win" is asking three things -- what it demanded, who
-     * else wanted the row, and what beat them -- and the first is here, the second is in the
-     * band's `considered`, and the third is `priority`. */
+    /* The kernel's declared constraints, which selection matched it on. With the band's
+     * `considered` list and `priority`, they explain why it won. */
     json cons = json::array();
     for (int i = 0; i < k->n_constraints; ++i) cons.push_back(constraint_str(k->constraints[i]));
     j["constraints"] = std::move(cons);
@@ -543,20 +490,11 @@ static json resolved_json(const Resolved& r) {
     return j;
 }
 
-/* WHO ELSE WANTED THIS BAND, AND WHAT REFUSED THEM.
- *
- * The selector already builds this list -- SelectionTrace::candidates carries every row it walked
- * with the constraint that turned it away -- and build_bands keeps only the miss reason out of it.
- * Recovering it here is what makes selection legible: "gemm_nt_q M <= 64 went to
- * r4d_gemm_fp8_narrow, and r4d_gemm_fp8_tiled wanted it too and lost on priority, and the ref row
- * lost on the domain" is the whole of selection in one table.
- *
- * Recomputed rather than stored. Keeping the candidates on every Band would hold a few megabytes
- * of strings for the life of the process to answer a question nobody asks until they open a
- * browser; asking the selector again costs one pass over one op's rows, once per DISTINCT band
- * table -- which on a 64-layer model is tens of tables, not one per declared op. `record = false`
- * so the selection table's "asked" counts stay a record of what the engine asked for, not of what
- * the graph dump asked on its behalf. */
+/* Every candidate for this band and what refused it (SelectionTrace::candidates; build_bands keeps
+ * only the miss reason). Recomputed rather than stored on every Band, which would hold megabytes of
+ * strings for the process lifetime; the cost is one pass over one op's rows per distinct band
+ * table. `record = false` keeps the selection table's "asked" counts to the engine's own
+ * queries. */
 static json considered_json(Registry& reg, const OpInfo& o, const Band& b, int dom) {
     Geometry q = o.base;
     if (!o.ranged_key.empty()) q.set_i(o.ranged_key, b.hi == INT64_MAX ? o.range_hi : b.hi);
@@ -576,9 +514,8 @@ static json considered_json(Registry& reg, const OpInfo& o, const Band& b, int d
     return out;
 }
 
-/* WHAT THE OP MEANS, from the schema the plugin hierarchy agreed on. The operand list is the part
- * that pays: `RadArgs.t` is positional, and a reader looking at a fused kernel's `from` wiring
- * has no way to know which slot is which without it. */
+/* The op's schema. The operand list matters most: `RadArgs.t` is positional, so it is the only
+ * way to read a fused kernel's `from` wiring. */
 static json schema_json(const RadOpSchema* s) {
     if (!s) return nullptr;
     json j;
@@ -614,9 +551,8 @@ static std::string shape_str(const int64_t* dims, uint32_t rank) {
     return s;
 }
 
-/* The weights ONE declaration of this op reads, with the two facts a reader is actually after:
- * how big it is where it lives, and what layout the winning kernel demanded -- which is why the
- * stored bytes may not be the logical ones. */
+/* A weight one declaration of this op reads: its stored size, and the layout the winning kernel
+ * demanded (why stored bytes may differ from logical ones). */
 static json weight_json(const WeightInfo& w) {
     json j;
     j["name"]    = w.name;
@@ -663,9 +599,7 @@ std::string dump_graph_json(const Program& p) {
     counts["scratch_bytes"]    = p.scratch_bytes;
     root["counts"] = std::move(counts);
 
-    /* THE PLUGIN HIERARCHY, which is the answer to "where did this kernel come from" one level up
-     * from the kernel row: an override is a plugin ahead of the default in this list, and a reader
-     * who sees `libref` winning a row wants to know what was ahead of it. */
+    /* The plugin hierarchy: an override is a plugin ahead of the default in this list. */
     json plugs = json::array();
     for (const Plugin& pl : reg.plugins()) {
         json j;
@@ -704,9 +638,8 @@ std::string dump_graph_json(const Program& p) {
                 if (!rj.is_null()) jb[dn] = std::move(rj);
                 else if (!b.miss[d].empty())  jb[std::string(dn) + "_miss"] = b.miss[d];
             }
-            /* The grouping key is formed BEFORE the candidate lists go on, so two declarations
-             * that resolved identically stay one group: `considered` is a function of the op and
-             * the band, so it cannot differ between them, and hashing it would only cost. */
+            /* The grouping key is formed before the candidate lists are added: `considered`
+             * depends only on op and band, so hashing it would add cost and nothing else. */
             key += "|" + jb.dump();
             for (int d = 0; d < RAD_N_DOMAINS; ++d)
                 jb[std::string(bld_domain_name(d)) + "_considered"] =
@@ -731,11 +664,8 @@ std::string dump_graph_json(const Program& p) {
             if (w && w < p.weights.size()) ws.push_back(weight_json(p.weights[w]));
         j["weights"] = std::move(ws);
 
-        /* THE BUFFERS THIS OP BEGINS AND ENDS. Read off the plan rather than off a second
-         * bookkeeping structure, exactly as the text dump does: a transient whose live range
-         * begins here is one this op defines, and one whose range ends here is storage the arena
-         * hands to something else after it. A buffer live for the whole program is one nothing
-         * declared a use for, and pinning it on the first op would be inventing a fact. */
+        /* Buffers whose lives begin or end at this op, read off the plan as in the text dump.
+         * Whole-program buffers (no declared use) are skipped. */
         json writes = json::array(), frees = json::array();
         for (size_t bi = 1; bi < p.buffers.size(); ++bi) {
             const BufferInfo& bf = p.buffers[bi];
@@ -767,10 +697,8 @@ std::string dump_graph_json(const Program& p) {
         ops.push_back(std::move(j));
     }
 
-    /* THE DECLARED ORDER, as an index into `ops`. The groups above collapse the sixty-four copies
-     * of a layer into one entry; a DIAGRAM needs the sequence back, and the sequence is what the
-     * grouping threw away. One small integer per declared op -- six kilobytes against the two
-     * megabytes that emitting every op in full would cost. */
+    /* The declared order as indices into `ops`, which the grouping dropped and the diagram needs.
+     * One small integer per declared op, far smaller than emitting every op in full. */
     json ord = json::array();
     std::vector first_at((size_t)ops.size(), -1), last_at((size_t)ops.size(), -1);
     for (size_t k = 0; k < seq.size(); ++k) {
@@ -779,8 +707,7 @@ std::string dump_graph_json(const Program& p) {
         if (first_at[(size_t)gi] < 0) first_at[(size_t)gi] = (int)k;
         last_at[(size_t)gi] = (int)k;
     }
-    /* Where in the flow this group's declarations sit -- one op index is a group of sixty-four
-     * telling the reader about its first copy only, and the pair says so. */
+    /* First and last position of the group's declarations in the flow. */
     for (size_t k = 0; k < ops.size(); ++k) {
         ops[k]["first_at"] = first_at[k];
         ops[k]["last_at"]  = last_at[k];
diff --git a/core/build/startup.cpp b/core/build/startup.cpp
index d8e9e0d3..9569c0d0 100644
--- a/core/build/startup.cpp
+++ b/core/build/startup.cpp
@@ -1,9 +1,6 @@
 /* startup.cpp -- the tools' seam onto core/plugin and core/build, and the shared CLI plumbing.
- *
- * rad-convert, rad-check and rad-tune are the engine's startup with a different last step, so they
- * do not get their own loader: they call the same Registry and the same Builder the engine will,
- * through the two functions below. A tool that resolved kernels differently from the engine would
- * be a tool whose answers are about a different program.
+ * The tools use the same Registry and Builder as the engine (see startup.h), so they resolve the
+ * same program.
  */
 #include "build/startup.h"
 #include "build/rad_build.h"
@@ -14,22 +11,17 @@
 
 #include 
 #include 
+#include 
 
 namespace rad {
 
-/* One Registry for the life of the process. A Resolved, a Band and a KernelRow all point into a
- * plugin's static tables, and the Program outlives the call that built it, so the registry cannot
- * be a local. registry.h says the same thing about the engine.
+/* One Registry for the life of the process: Resolved, Band and KernelRow point into plugin
+ * static tables, and the Program outlives the call that built it.
  *
- * NEVER DESTROYED, because exit destroys in the wrong order for it. A function-local static is
- * constructed before the first plugin is loaded, so its destructor runs AFTER every plugin's own
- * static destructors -- and closing from there calls each instance's fini into plugin state that
- * no longer exists. libr4d's router keeps its per-device counter blocks in a global map; fini
- * looked up and erased a node of the destroyed map, a double free that glibc reported as
- * "corrupted size vs. prev_size" or "free(): invalid pointer" on whichever exit the heap layout
- * exposed it. A caller that needs the finis to run closes the registry itself while the plugins
- * are alive, as Engine's shutdown does; at exit the process is ending and what the instances
- * hold goes with it. */
+ * Never destroyed. A function-local static would be destroyed after the plugins' own static
+ * destructors, and its close would call each instance's fini into destroyed plugin state (e.g.
+ * libr4d's router erasing from its destroyed global map: a double free). A caller that needs the
+ * finis closes the registry while plugins are alive, as Engine's shutdown does. */
 Registry& rad_tools_registry() {
     static Registry* r = new Registry();
     return *r;
@@ -37,16 +29,10 @@ Registry& rad_tools_registry() {
 
 /* ------------------------------------------------------------------ the reference-kernel gate */
 
-/* An op counts as "on the reference" when NO domain and NO band offers a kernel from a library that
- * is not a reference implementation (RadPluginReferenceFn).
- *
- * The narrower reading matters. A reference library is usually a HOST plugin, so every op's host
- * band resolves to it -- that is what makes the host domain work at all, and flagging it would
- * flag the entire vocabulary of every model. What is a hazard is an op a reference is the ONLY
- * implementation of: wherever the planner puts it, it runs naive generic code.
- *
- * The op is still counted once per declared instance, because "rmsnorm resolves to ref" reads very
- * differently at one layer and at sixty-four. */
+/* An op is "on the reference" when no band in any domain offers a non-reference kernel
+ * (RadPluginReferenceFn). A reference library usually serves the host domain for every op, so
+ * only an op with no other implementation is flagged: wherever it is placed, it runs naive code.
+ * Counted once per declared instance; `out` lists distinct op names. */
 int rad_reference_ops(const Program& p, std::vector* out) {
     int n = 0;
     for (size_t i = 1; i < p.ops.size(); ++i) {
@@ -58,8 +44,7 @@ int rad_reference_ops(const Program& p, std::vector* out) {
                     real = true;
         if (real) continue;
         ++n;
-        /* By op NAME and deduplicated: a 64-layer model declares sixty-four identical rmsnorms and
-         * the useful sentence is "rmsnorm has no kernel", not sixty-four copies of it. */
+        /* Deduplicated by op name. */
         if (out && std::find(out->begin(), out->end(), oi.op) == out->end())
             out->push_back(oi.op);
     }
@@ -71,9 +56,8 @@ int rad_gate_reference_kernels(const Program& p, bool allow, const char* what) {
     const int n = rad_reference_ops(p, &ops);
     if (n == 0) return RAD_OK;
 
-    std::string list;
-    for (size_t i = 0; i < ops.size(); ++i) { if (i) list += ", "; list += ops[i]; }
-    /* Which reference libraries those are, by the name each one gave itself. */
+    const std::string list = join(ops);
+    /* The reference libraries involved, by plugin name. */
     std::vector refs;
     for (size_t i = 1; i < p.ops.size(); ++i)
         for (const Band& b : p.ops[i].bands)
@@ -81,8 +65,7 @@ int rad_gate_reference_kernels(const Program& p, bool allow, const char* what) {
                 if (b.dom[d] && b.dom[d].row && b.dom[d].row->reference &&
                     std::find(refs.begin(), refs.end(), b.dom[d].row->plugin) == refs.end())
                     refs.push_back(b.dom[d].row->plugin);
-    std::string libs;
-    for (size_t i = 0; i < refs.size(); ++i) { if (i) libs += ", "; libs += refs[i]; }
+    const std::string libs = join(refs);
 
     if (allow) {
         RAD_WARN("%d declared op(s) resolve to a reference implementation (%s) and "
@@ -92,15 +75,12 @@ int rad_gate_reference_kernels(const Program& p, bool allow, const char* what) {
         return RAD_OK;
     }
 
-    RAD_ERR("%d declared op(s) resolve only to a reference implementation (%s).\n"
+    RAD_ERR("%d declared op(s) resolve only to a reference implementation (%s), which runs "
+            "orders of magnitude slower; %s refuses them (spec §17).\n"
             "    %zu distinct op(s): %s\n"
-            "  A reference library exists to be an ORACLE and a last resort, not a deployment. "
-            "Falling back to it silently is a model running orders of magnitude below the machine "
-            "with nothing in the output to say so, which is the failure spec §17 exists to prevent "
-            "-- so %s refuses rather than serving it.\n"
-            "  Either supply a kernel plugin that covers these ops, or pass "
-            "--debug-accept-reference-kernels to accept the cost deliberately.",
-            n, libs.c_str(), ops.size(), list.c_str(), what);
+            "  Supply a kernel plugin that covers these ops, or pass "
+            "--debug-accept-reference-kernels to accept the cost.",
+            n, libs.c_str(), what, ops.size(), list.c_str());
     return RAD_E_NOKERNEL;
 }
 
@@ -145,13 +125,9 @@ int rad_tools_load_plugins(const std::string& home, const std::vector kdirs = home_subdirs(home, "kernels");
     if (kdirs.empty()) kdirs.push_back(first + "/kernels");
@@ -163,9 +139,8 @@ int rad_tools_load_plugins(const std::string& home, const std::vector qdirs = home_subdirs(home, "quantizers");
     if (!qdirs.empty()) {
         s = r.load_dirs(qdirs, {});
@@ -174,18 +149,16 @@ int rad_tools_load_plugins(const std::string& home, const std::vector 0) RAD_INFO("tune cache: %d row(s) from %s", n_tuned, tune.c_str());
 
-    /* The selection key is the PAIR (spec §2.4). An exact match on both halves, with no fallback:
-     * a quantised container handed to a plugin that declares dense weights fails later, at the
-     * name map, with a worse message than the one below. */
+    /* The selection key is the (arch_id, quant) pair (spec §2.4), matched exactly with no
+     * fallback; a mismatched plugin would only fail later at the name map with a worse message. */
     for (const Plugin& p : r.plugins()) {
         if (p.kind == RAD_PLUGIN_KERNEL) {
             out->kernels.push_back({ p.name, p.version });
@@ -198,7 +171,7 @@ int rad_tools_load_plugins(const std::string& home, const std::vectorarch_plugin.empty()) {
         std::vector fam, quantised;
         for (const Plugin& p : r.plugins())
@@ -234,10 +207,8 @@ int rad_tools_load_plugins(const std::string& home, const std::vectorarch_plugin.empty()) {
-        /* No match, no model (spec §1). Name what IS installed AND at which quantisation, because
-         * the two causes look identical otherwise: an architecture nobody has written a plugin for,
-         * and one that is written but only for another weight format. The second is the common one
-         * for a family with more than one member. */
+        /* No match, no model (spec §1). List what is installed with its quantisation, to tell an
+         * unsupported architecture from one supported only at another weight format. */
         std::string have, same;
         for (const Plugin& p : r.plugins()) {
             if (p.kind != RAD_PLUGIN_ARCH) continue;
@@ -261,13 +232,9 @@ int rad_tools_load_plugins(const std::string& home, const std::vectorarch_chat_format(&meta);
 }
 
+const RadAudioFormat* rad_tools_audio_format(const LoadedPlugins& lp, const RadModelMeta& meta) {
+    const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin);
+    if (!ap || !ap->arch_audio_format) return nullptr;
+    const RadAudioFormat* f = ap->arch_audio_format(&meta);
+    if (!f) return nullptr;
+    /* The plugin's struct may be older than ours: it is copied into a zeroed one up to the size
+     * it states, so a field it predates reads as null (rad_builder.h). */
+    static thread_local RadAudioFormat copy;
+    copy = RadAudioFormat{};
+    const size_t n = f->struct_size < sizeof copy ? f->struct_size : sizeof copy;
+    std::memcpy(©, f, n);
+    copy.struct_size = (uint32_t)sizeof copy;
+    return ©
+}
+
 WeightSourceFn rad_container_sources(const RadFile& f) {
     return [&f](const std::string& name, const Program&, WeightSource* out) {
         const RadFileEntry* e = f.find(name);
@@ -313,8 +295,8 @@ int CheckpointSources::answer(const std::string& name, const Program& prog, Weig
         CkptWeight w;
         std::string why;
         const int st = ckpt_resolve(ck_, prog, name, false, &w, &why);
-        /* Not found is not remembered as an answer -- declare may map the name later -- but
-         * its reason is, for the loader to give if it never is. */
+        /* Not-found is not cached, since declare may map the name later, but its reason is kept
+         * for the loader to report. */
         if (st == RAD_E_NOTFOUND) {
             missing_[name] = why;
             return st;
@@ -369,7 +351,6 @@ int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const R
         return RAD_E_NOTFOUND;
     }
 
-    /* The Builder takes the Registry directly: there is no selector adapter between the two. */
     Builder b(r, meta, ctx);
     if (ref) b.set_reference(ref);
     if (sources) b.set_sources(sources);
@@ -382,20 +363,15 @@ int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const R
         return s;
     }
 
-    /* The sampler declares here, into the same builder and before finish(), so its ops go through
-     * the same resolution as the plugin's. A sampler op that does not resolve is deliberately NOT
-     * a declare failure -- a deployment that never sends `typical_p` does not need a typical
-     * kernel -- so this returning negative means something structural, not a miss. */
-    /* NOT FOR AN EMBEDDING PROGRAM (rad_declare_pooled) OR AN IMAGE GENERATOR: neither samples a
-     * token, so a sampler chain in it would be ops and buffers no step ever issues. */
+    /* The sampler declares into the same builder before finish(). An unresolved sampler op is not
+     * a declare failure (a deployment that never sends `typical_p` needs no typical kernel), so a
+     * negative return here is structural. Skipped for embedding programs and image generators,
+     * which sample no token. */
     if (also && b.program().pooled_buf == RAD_NULL_HANDLE && !b.program().is_generator()) {
-        /* THE WIDTH THE PLUGIN ACTUALLY DECLARED, handed over rather than re-derived. The sampler
-         * needs to know how much vocabulary THIS RANK produces, and the one place that is a fact
-         * is the logits buffer the plugin just named. Computing it a second time from n_vocab and
-         * world_size puts the sharding rule in two files, and the two disagree the moment a plugin
-         * stops splitting the vocabulary -- which arch/common/rad_arch.h currently does, on
-         * purpose. A sampler reading 248320 logits out of a 124160-wide row is not a crash; it is
-         * fluent text with the wrong tokens. */
+        /* This rank's vocabulary width, taken from the declared logits buffer rather than
+         * re-derived from n_vocab and world_size, which would break when a plugin does not split
+         * the vocabulary (arch/common/rad_arch.h does not). A wrong width does not crash; it
+         * samples the wrong tokens. */
         int64_t lw = 0;
         if (b.program().logits_buf != RAD_NULL_HANDLE &&
             (size_t)b.program().logits_buf < b.program().buffers.size()) {
@@ -410,8 +386,7 @@ int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const R
     }
 
     s = b.finish();
-    /* Declare ALWAYS completes: a structural error is reported whole, not first-failure-at-the-top
-     * (spec §3.1). */
+    /* Declare always completes; every structural error is reported (spec §3.1). */
     for (const auto& e : b.errors()) RAD_ERR("    %s", e.c_str());
     if (s < 0) return s;
     if (b.status() < 0) return b.status();
diff --git a/core/build/startup.h b/core/build/startup.h
index 813051cd..7eccd86c 100644
--- a/core/build/startup.h
+++ b/core/build/startup.h
@@ -1,14 +1,13 @@
-/* startup.h -- steps 1 through 4 of spec §1's startup sequence, shared by the engine and by every
- * tool that needs them.
+/* startup.h -- steps 1 through 4 of spec §1's startup sequence, shared by the engine and the
+ * tools.
  *
  *   1. Load kernel plugins from $RADIANCE_HOME/kernels/, in the configured hierarchy order.
  *   3. Look up the architecture id in $RADIANCE_HOME/architectures/.
  *   4. Declare.
  *
- * These live in core rather than in tools/ because rad-convert, rad-check and rad-tune are all
- * the engine's startup with a different last step (spec §4.2, §15, §17). Two implementations of
- * "load the plugins and run declare" would eventually disagree about hierarchy order, and the
- * hierarchy order is what decides which layout got baked into the container.
+ * In core because rad-convert, rad-check and rad-tune are the engine's startup with a different
+ * last step (spec §4.4, §15, §17). A second implementation could disagree on hierarchy order,
+ * which decides the layout baked into a container.
  */
 #pragma once
 #include "rad_core.h"
@@ -29,17 +28,16 @@ namespace rad {
 struct PluginId { std::string name, version; };
 
 struct LoadedPlugins {
-    /* Kernel plugins in HIERARCHY ORDER, which is what decides selection, so a report of what ran
-     * names them in it. */
+    /* Kernel plugins in hierarchy order, which decides selection. */
     std::vector       kernels;
     std::string                 arch_plugin;
     std::string                 arch_version;
     std::string                 arch_id;
-    /* The other half of the key that selected it, "" for an unquantised container. */
+    /* The quantisation half of the selection key, "" for an unquantised container. */
     std::string                 arch_quant;
 
-    /* `name@version`, space separated, in hierarchy order: what a benchmark records as the
-     * libraries it measured. */
+    /* `name@version`, space separated, in hierarchy order; what a benchmark records as the
+     * libraries measured. */
     std::string libraries() const {
         std::string s;
         for (const auto& p : kernels) {
@@ -50,29 +48,27 @@ struct LoadedPlugins {
     }
 };
 
-/* $RADIANCE_HOME AS A SEARCH PATH: one or more homes separated by ':', the first taking precedence
- * -- a directory of one's own plugins ahead of an installation's, without copying the installation.
- * Each home holds kernels/, architectures/ and quantizers/, any of which it may lack; a plugin a
- * home earlier on the path supplies shadows one of the same file name later on it. Files that are
- * not plugins -- the tuning cache, rad-kbench's fixtures -- are read from the first home that has
- * them and written to the first home. */
+/* $RADIANCE_HOME is a ':'-separated search path, first home first, so a directory of one's own
+ * plugins can precede an installation. Each home may hold kernels/, architectures/ and
+ * quantizers/; a plugin earlier on the path shadows one with the same file name later. Non-plugin
+ * files (the tuning cache, rad-kbench fixtures) are read from the first home that has them and
+ * written to the first home. */
 std::vector rad_home_dirs(const std::string& home);
 /* `/` for the first home on the path that has it; the first home's when none does. */
 std::string rad_home_file(const std::string& home, const std::string& rel);
 
-/* The Registry loaded into is process-lifetime, because a Resolved, a Band and a KernelRow all
- * point into a plugin's static tables and the Program outlives this call. */
-/* `arch_id` and `quant` are BOTH halves of the selection key (spec §2.4, rad_builder.h): a family
- * has one plugin per weight format and they all answer the same architecture id. `quant` is the
- * container's own descriptor -- RadModelMeta::quant, RadFileHeader::quant -- and "" is the
- * unquantised case, which matches a plugin that says "" and nothing else. */
-/*
- * `imported` is a checkpoint whose quantisation is imported weight by weight
- * (Checkpoint::imports): its descriptor names the tool that made it and no plugin claims it, so
- * the plugin is the architecture's QUANTISED one -- the one plugin of the family claiming a
- * descriptor, or the family's only plugin when that claims none. Two quantised plugins are a
- * choice this cannot make, and are refused by name. `out->arch_quant` is the descriptor chosen,
- * which is what a container converted from it records. */
+/* Loads into the process-lifetime registry (rad_tools_registry).
+ *
+ * `arch_id` and `quant` together are the selection key (spec §2.4, rad_builder.h): a family has
+ * one plugin per weight format, all answering the same architecture id. `quant` is the container's
+ * descriptor (RadModelMeta::quant, RadFileHeader::quant); "" is unquantised and matches only a
+ * plugin that says "".
+ *
+ * `imported`: the checkpoint's quantisation is imported weight by weight (Checkpoint::imports), so
+ * its descriptor names the producing tool and no plugin claims it. The family's quantised plugin
+ * serves it: the one plugin claiming a descriptor, or the only plugin if none does. Two quantised
+ * plugins are refused by name. `out->arch_quant` is the chosen descriptor, which a container
+ * converted from it records. */
 int rad_tools_load_plugins(const std::string& radiance_home,
                            const std::vector& hierarchy,
                            const std::string& arch_id,
@@ -80,24 +76,34 @@ int rad_tools_load_plugins(const std::string& radiance_home,
                            LoadedPlugins* out,
                            bool imported = false);
 
-/* `also` declares into the SAME builder after the architecture plugin has. That is what puts the
- * sampler chain in the same Program: its ops resolve through the same hierarchy at the same
- * time as the plugin's, so a missing sampler kernel is in the same miss list rather than
- * discovered at the first request that asks for it (spec §3.1, §13). Empty for the tools --
- * rad-convert cares about the weight layout and has no sampler. */
+/* The architecture plugin's rad_arch_probe answers, given before declare. */
 int rad_tools_probe(const LoadedPlugins& plugins, const RadModelMeta& meta, RadArchProbe* out);
 
 /* The architecture plugin's declared reply format (rad_arch_chat_format), or null when it
  * declares none and the format is to be derived from the chat template. */
 const RadChatFormat* rad_tools_chat_format(const LoadedPlugins& plugins, const RadModelMeta& meta);
 
-/* `ref`, when given, makes this a SIZING declare (RadBuildCtx::shape_probe, Builder::
- * set_reference): the plugin declares against the bands `ref` resolved and nothing is selected
- * or initialised. The Program that comes back is for its buffers and nothing else. */
-/* `sources` answers rad_weight_encoding (Builder::set_sources): a container's entries, a
- * checkpoint's tensors, or a recipe. Empty, every weight is read as plain in its declared dtype. */
-/* `instances` false selects every kernel and initialises none (Builder::set_instances): for a
- * caller that launches nothing, such as rad-convert planning a container's stored form. */
+/* The architecture plugin's declared audio format (rad_arch_audio_format), or null when it
+ * declares none -- a model the speech routes do not serve. A format whose struct_size is too
+ * small to hold a field reads that field as null. */
+const RadAudioFormat* rad_tools_audio_format(const LoadedPlugins& plugins, const RadModelMeta& meta);
+
+/* Run declare.
+ *
+ * `also` declares into the same builder after the architecture plugin, which is how the sampler
+ * chain joins the Program: its ops resolve through the same hierarchy, so a missing sampler kernel
+ * is in the same miss list rather than found at the first request (spec §3.1, §13). Empty for the
+ * tools, which have no sampler.
+ *
+ * `ref` makes this a sizing declare (RadBuildCtx::shape_probe, Builder::set_reference): the plugin
+ * declares against `ref`'s bands, nothing is selected or initialised, and the result is used only
+ * for its buffers.
+ *
+ * `sources` answers rad_weight_encoding (Builder::set_sources): container entries, checkpoint
+ * tensors, or a recipe. Empty: every weight is plain in its declared dtype.
+ *
+ * `instances` false selects every kernel and initialises none (Builder::set_instances), for
+ * callers that launch nothing, such as rad-convert. */
 int rad_tools_declare(const LoadedPlugins& plugins, const RadModelMeta& meta,
                       const RadBuildCtx& ctx, Program* out,
                       const std::function& also = {},
@@ -108,14 +114,13 @@ int rad_tools_declare(const LoadedPlugins& plugins, const RadModelMeta& meta,
  * declare. */
 WeightSourceFn rad_container_sources(const RadFile& f);
 
-/* A CHECKPOINT AS THE SOURCE, served directly (spec §4.3): each declared weight resolved through
- * the name map once, and kept for the loader, which reads the same tensors the answer was made
- * from. Every rank declares at once, so it is locked.
+/* A checkpoint served directly as the source (spec §4.3). Each declared weight is resolved
+ * through the name map once and kept for the loader, which reads the same tensors. Locked, since
+ * every rank declares concurrently.
  *
- * Only a TRIVIAL encoding is answered -- bf16, f16, f32, block-scaled FP8 -- because nothing is
- * quantised at load. A weight whose checkpoint form is anything else is recorded with the reason
- * and answered RAD_E_UNSUPPORTED; refused() names them after declare, and the remedy is a
- * container. */
+ * Only trivial encodings are answered (bf16, f16, f32, block-scaled FP8) because nothing is
+ * quantised at load. Anything else is recorded with its reason and answered RAD_E_UNSUPPORTED;
+ * refused() lists them after declare, and the remedy is a container. */
 class CheckpointSources {
 public:
     explicit CheckpointSources(Checkpoint& ck) : ck_(ck) {}
@@ -136,22 +141,16 @@ private:
     std::map missing_;
 };
 
-
 /* ------------------------------------------------------------------ the reference-kernel gate */
-/* A reference library -- one that declares itself so, RadPluginReferenceFn -- is BOTH the fallback
- * that makes an unsupported model run at reduced speed and the oracle rad-kbench measures against
- * (spec §17). The first of those is a hazard in production and
- * the second is not, so which one is happening has to be a decision and not a discovery: a model
- * that silently fell back to the reference implementation for its GEMMs is a model running orders
- * of magnitude below what the machine can do, and nothing in the output says so.
- *
- * So: resolving to a reference library is FATAL unless --debug-accept-reference-kernels was
- * passed. The flag is spelled with `debug` in it because that is what it is for. */
+/* A reference library (RadPluginReferenceFn) is both the slow fallback for an unsupported model
+ * and the oracle rad-kbench measures against (spec §17). As a silent fallback it runs orders of
+ * magnitude below the machine with no visible sign, so resolving to one is fatal unless
+ * --debug-accept-reference-kernels is passed. */
 
 int rad_reference_ops(const Program& p, std::vector* out);
 
 /* Report and refuse, or report and continue when `allow`. `what` names the caller ("serve",
- * "the container's layout") so the message says what the consequence actually is. */
+ * "the container's layout") so the message states the consequence. */
 int rad_gate_reference_kernels(const Program& p, bool allow, const char* what);
 
 Registry& rad_tools_registry();
diff --git a/core/config.cpp b/core/config.cpp
index 689febe6..0869d5f5 100644
--- a/core/config.cpp
+++ b/core/config.cpp
@@ -1,8 +1,6 @@
-/* config.cpp -- the command line. Every pool is budgeted explicitly: no profiling pass, no
- * utilisation fraction, no inference about what the workload will be. The trade between KV blocks
- * and resident weights is real and workload-dependent -- a long-context low-concurrency server and
- * a short-context high-concurrency one want opposite splits -- but it is the operator's to make.
- * An engine that quietly re-optimises the split is an engine whose benchmarks do not reproduce
+/* config.cpp -- the command line. Every pool is budgeted explicitly, with no profiling pass,
+ * utilisation fraction or workload inference. The KV-versus-weights trade is workload-dependent
+ * and the operator's to make; re-optimising it quietly would make benchmarks irreproducible
  * (spec §6).
  */
 #include "rad_core.h"
@@ -10,6 +8,8 @@
 #include "sample/host_ref.h"
 #include "server/oai.h"
 #include "diag/diag.h"
+#include "util/kernel_list.h"
+#include "place/planner.h"
 
 #include 
 
@@ -30,8 +30,8 @@ struct Flag {
     const char* help;
 };
 
-/* Built from kDraftWindowDefault, so the default is stated in one place. Defined before the table
- * that points at it: the two are initialised in this order. */
+/* Built from kDraftWindowDefault so the default is stated once. Defined before the table that
+ * points at it, which fixes their initialisation order. */
 static const std::string g_draft_window_help =
     std::string("fixed | adaptive: how many drafts each sequence carries. fixed drafts\n"
                 "                                    --num-speculative-tokens every step; adaptive makes that\n"
@@ -46,7 +46,7 @@ static const Flag g_flags[] = {
                                         "$XDG_CACHE_HOME/radiance/hf, else ~/.cache/radiance/hf" },
     { "--radiance-home",      "DIRS",   "where kernels/, architectures/ and quantizers/ live; several\n"
                                         "homes separated by ':' are searched in order, the first winning" },
-    { "--kernels",            "LIST",   "the kernel libraries to use, comma-separated, first wins; unnamed ones are not loaded. Default: every library found" },
+    { "--kernels",            "LIST",   "the kernel libraries to use, separated by ',' or ':', first wins; unnamed ones are not loaded. Default: every library found" },
 
     { "--tp",                 "N",      "tensor-parallel ranks" },
     { "--tp-wire",            "MODE",   "cross-rank all-reduce payload: exact (default) or wht6, a\n"
@@ -60,6 +60,9 @@ static const Flag g_flags[] = {
     { "--busy-prefill-chunk", "MODE",   "a prefill chunk's share of a step that has other work: auto\n"
                                         "(default) leaves decode rows and new requests their room,\n"
                                         "off takes the whole step, N holds the chunk to N tokens" },
+    { "--prefill-interleave", "N",      "decode-only steps after each prefill chunk while other\n"
+                                        "sequences decode, at most 64; 0 (default) lets every step\n"
+                                        "carry a chunk" },
     { "--max-num-seqs",       "N",      "the largest number of sequences one step may carry" },
     { "--max-model-len",      "N",      "context bound; 0 takes the model's training context" },
     { "--rope-scaling",       "SPEC",   "yarn:FACTOR[:ORIG]: static YaRN over the container's own rotary\n"
@@ -101,11 +104,15 @@ static const Flag g_flags[] = {
     "                                    this does NOT make the engine bit-reproducible across\n"
     "                                    batch positions -- see spec §19" },
     { "--checkpoint-interval","N",      "linear-attention state checkpoint interval, in tokens" },
-    /* TOTAL, NOT PER SEQUENCE. The snapshot store is one pool of N slots for the whole server
-     * (KVManager::set_checkpoint_store), so an operator reading "per sequence" and setting 2 gets
-     * 2 for the whole server rather than 2 x --max-num-seqs. At the default 8 slots and
-     * 8 sequences that is one snapshot a sequence, which is what an append-only chat wants --
-     * the next turn's hit lands at the end of the last one. */
+    { "--prefill-span",       "N",      "checkpoint intervals one step may carry of a prefill alone\n"
+    "                                    in its step, from the prompt's second interval on (default\n"
+    "                                    1); needs --max-num-batched-tokens of N intervals. Every\n"
+    "                                    other step is planned at the budget less the extra\n"
+    "                                    intervals, and the checkpoints inside a span are not\n"
+    "                                    written" },
+    /* A total, not per sequence: the snapshot store is one pool of N slots
+     * (KVManager::set_checkpoint_store). The default 8 gives one per sequence at 8 sequences,
+     * enough for append-only chat, where the next turn hits at the end of the last. */
     { "--checkpoint-slots",   "N",      "linear-state or sliding-window snapshots "
                                           "retained IN TOTAL (not "
                                           "per sequence), in pinned host memory; compare "
@@ -122,18 +129,20 @@ static const Flag g_flags[] = {
 
     { "--host",               "ADDR",   "listen address" },
     { "--port",               "N",      "listen port" },
-    { "--api-key",            "KEY",    "require `Authorization: Bearer KEY` on every request but /health, /ping and the dashboard page" },
+    { "--api-key",            "KEY",    "require `Authorization: Bearer KEY` or `X-Api-Key: KEY` on every request but /health,\n"
+    "                                    /v1/health, /ping and the dashboard page" },
     { "--served-model-name",  "NAME",   "the model id /v1/models lists and responses carry; default the container's name" },
     { "--mm-max-patches",     "N",      "patches one encoder pass carries, and so the largest image (a patch is 16x16\n"
                                         "pixels). Default `auto`: 16384 when the container carries a vision tower. 0\n"
                                         "serves text only and keeps the tower off the card" },
     { "--generation-config",  "PATH",   "a generation_config.json whose sampler settings become the default\n"
-    "                                    for requests that send none. Without it the container's own\n"
-    "                                    `generation.*` metadata is used, then a .generation.json\n"
-    "                                    beside the container, then the built-in defaults" },
+    "                                    for requests that send none. Without it a .generation.json\n"
+    "                                    beside the container is used, then the container's own\n"
+    "                                    `generation.*` metadata, then the built-in defaults" },
     { "--override-chat-template", "PATH", "a Jinja chat template file, used in place of the one the container carries" },
     { "--temp",               "F",      "default temperature for requests that do not set one" },
-    { "--top-k",              "N",      "default top_k (0 = off) for requests that do not set one" },
+    { "--top-k",              "N",      "default top_k for requests that do not set one; 0 is the 1024 most\n"
+    "                                    likely tokens, the sampler's candidate width" },
     { "--top-p",              "F",      "default top_p for requests that do not set one" },
     { "--min-p",              "F",      "default min_p (0 = off) for requests that do not set one.\n"
     "                                    These four override whatever the container or its generation\n"
@@ -159,7 +168,7 @@ static const Flag g_flags[] = {
     { "--repeat-last-n",      "N",      "default repeat_last_n, the tokens those penalties look back over; -1 is all" },
     { "--dry-multiplier",     "F",      "default dry_multiplier; 0 is DRY off" },
     { "--dry-base",           "F",      "default dry_base, >= 1" },
-    { "--dry-allowed-length", "N",      "default dry_allowed_length" },
+    { "--dry-allowed-length", "N",      "default dry_allowed_length, >= 1" },
     { "--dry-penalty-last-n", "N",      "default dry_penalty_last_n; -1 is the whole context" },
     { "--dry-sequence-breakers", "JSON", "default dry_sequence_breakers, a JSON array of at most 16 strings" },
     { "--xtc-probability",    "F",      "default xtc_probability, [0, 1]" },
@@ -233,8 +242,7 @@ static const Flag g_flags[] = {
 
 void config_usage(const char* argv0) {
     fprintf(stderr, "usage: %s --model FILE [options]\n\n", argv0);
-    /* A help text's continuation lines start under its first line, whatever indentation the
-     * string itself carries. */
+    /* Align help continuation lines under the first, whatever indentation the string carries. */
     for (const Flag& f : g_flags) {
         char left[64];
         snprintf(left, sizeof left, "%s%s%s", f.name, f.arg ? " " : "", f.arg ? f.arg : "");
@@ -248,13 +256,11 @@ void config_usage(const char* argv0) {
         fprintf(stderr, "  %-32s %s\n", left, help.c_str());
     }
     fprintf(stderr,
-        "\nEvery pool is budgeted explicitly. The trade between KV blocks and resident weights\n"
-        "is the operator's to make: an engine that re-optimises it quietly is an engine whose\n"
-        "benchmarks do not reproduce.\n");
+        "\nEvery pool is budgeted explicitly: the split between KV blocks and resident weights\n"
+        "is the operator's to set.\n");
 }
 
-/* The four names exactly, lower case: what a table's placement costs is the operator's to state,
- * so a spelling this build does not know stops the server rather than picking a tier. */
+/* The four names exactly, lower case; anything else is refused rather than mapped to a tier. */
 static bool parse_table_placement(const char* v, TablePlacement* out) {
     if      (!std::strcmp(v, "auto")) *out = TablePlacement::Auto;
     else if (!std::strcmp(v, "vram")) *out = TablePlacement::Vram;
@@ -264,20 +270,8 @@ static bool parse_table_placement(const char* v, TablePlacement* out) {
     return true;
 }
 
-static std::vector split_commas(const std::string& s) {
-    std::vector out;
-    size_t i = 0;
-    while (i <= s.size()) {
-        size_t j = s.find(',', i);
-        if (j == std::string::npos) j = s.size();
-        if (j > i) out.push_back(s.substr(i, j - i));
-        i = j + 1;
-    }
-    return out;
-}
-
-/* A NUMBER IS THE WHOLE ARGUMENT OR IT IS REFUSED. atof reads "high" as 0, and for --temp that is
- * greedy decoding: a typo that changes every reply and says nothing. */
+/* The whole argument must be a number: atof reads "high" as 0, which for --temp silently means
+ * greedy decoding. */
 static bool parse_num(const char* flag, const char* v, double* out) {
     char* end = nullptr;
     errno = 0;
@@ -309,9 +303,8 @@ static bool parse_int(const char* flag, const char* v, int64_t lo, int64_t hi, i
     return true;
 }
 
-/* A SAMPLER DEFAULT IS CHECKED AGAINST THE RANGE A REQUEST'S OWN VALUE IS (server::sampler_value_ok),
- * here rather than at the first request. A default outside it would be a 400 on every request
- * that omits the field -- a server that starts, reports healthy, and answers nothing. */
+/* Sampler defaults are checked against the request range (server::sampler_value_ok) at startup;
+ * an out-of-range default would 400 every request that omits the field. */
 static bool sampler_num(const char* flag, const char* field, const char* v, double* out) {
     if (!parse_num(flag, v, out)) return false;
     std::string why;
@@ -330,9 +323,9 @@ static bool sampler_int(const char* flag, const char* field, const char* v, int*
     return true;
 }
 
-/* THE NAMES THE RENDERER SETS ITSELF. The template context is built from these and the variables
- * are written over them (common_chat_template_direct_apply_impl), so a variable by one of these
- * names would replace the conversation, the tools or the special tokens of every request. */
+/* Names the renderer sets itself. Kwargs are written over the template context
+ * (common_chat_template_direct_apply_impl), so a kwarg with one of these names would replace every
+ * request's messages, tools or special tokens. */
 static const char* const kTemplateOwnNames[] = {
     "messages", "tools", "bos_token", "eos_token", "add_generation_prompt",
 };
@@ -368,16 +361,19 @@ static bool parse_template_kwargs(const char* v, std::map const char* {
         if (i + 1 >= argc) { RAD_ERR("%s needs an argument", argv[i]); return nullptr; }
         return argv[++i];
@@ -387,15 +383,21 @@ int config_parse(int argc, char** argv, Config* c) {
         std::string a = argv[i];
         const char* v = nullptr;
         auto S = [&](const char* n) { return a == n; };
+        /* The flag's argument as a whole number in [lo, hi], stored into *out. */
+        auto num = [&](int64_t lo, int64_t hi, auto* out) {
+            int64_t n = 0;
+            if (!(v = need(i)) || !parse_int(a.c_str(), v, lo, hi, &n)) return false;
+            *out = static_cast>(n);
+            return true;
+        };
 
-        if (S("--help") || S("-h"))            return 1;
-        else if (S("-v"))                      log_set_level(Log::Debug);
+        if (S("-v"))                           log_set_level(Log::Debug);
         else if (S("-vv"))                     log_set_level(Log::Trace);
         else if (S("--model"))                 { if (!(v = need(i))) return RAD_E_INVAL; c->model = v; }
         else if (S("--download-dir"))          { if (!(v = need(i))) return RAD_E_INVAL; c->download_dir = v; }
         else if (S("--radiance-home"))         { if (!(v = need(i))) return RAD_E_INVAL; c->radiance_home = v; }
-        else if (S("--kernels"))               { if (!(v = need(i))) return RAD_E_INVAL; c->kernel_hierarchy = split_commas(v); }
-        else if (S("--tp"))                    { if (!(v = need(i))) return RAD_E_INVAL; c->tp = atoi(v); }
+        else if (S("--kernels"))               { if (!(v = need(i))) return RAD_E_INVAL; c->kernel_hierarchy = rad_split_kernel_list(v); }
+        else if (S("--tp"))                    { if (!num(1, INT32_MAX, &c->tp)) return RAD_E_INVAL; }
         else if (S("--tp-wire")) {
             if (!(v = need(i))) return RAD_E_INVAL;
             if      (!std::strcmp(v, "exact")) c->tp_wire_exact = 1;
@@ -409,26 +411,20 @@ int config_parse(int argc, char** argv, Config* c) {
             else if (!std::strcmp(v, "off"))  c->p2p = RAD_P2P_OFF;
             else { RAD_ERR("--p2p takes auto, on or off, not '%s'", v); return RAD_E_INVAL; }
         }
-        else if (S("--tp-wire-min-kb"))        { if (!(v = need(i))) return RAD_E_INVAL; c->tp_wire_min_kb = atoll(v); }
-        else if (S("--max-num-batched-tokens")){ if (!(v = need(i))) return RAD_E_INVAL; c->max_tok = atoll(v); }
+        else if (S("--tp-wire-min-kb"))        { if (!num(0, INT64_MAX, &c->tp_wire_min_kb)) return RAD_E_INVAL; }
+        else if (S("--max-num-batched-tokens")){ if (!num(1, INT64_MAX, &c->max_tok)) return RAD_E_INVAL; }
         else if (S("--busy-prefill-chunk")) {
             if (!(v = need(i))) return RAD_E_INVAL;
-            char* end = nullptr;
-            const long long n = std::strtoll(v, &end, 10);
             if      (!std::strcmp(v, "auto")) c->busy_prefill_chunk = -1;
             else if (!std::strcmp(v, "off"))  c->busy_prefill_chunk = 0;
-            else if (end && end != v && *end == '\0' && n > 0) c->busy_prefill_chunk = n;
-            else {
-                RAD_ERR("--busy-prefill-chunk takes auto, off or a positive token count, not '%s'", v);
-                return RAD_E_INVAL;
-            }
+            else if (!parse_int(a.c_str(), v, 1, INT64_MAX, &c->busy_prefill_chunk)) return RAD_E_INVAL;
         }
-        else if (S("--max-num-seqs"))          { if (!(v = need(i))) return RAD_E_INVAL; c->max_seqs = atoll(v); }
-        else if (S("--max-model-len"))         { if (!(v = need(i))) return RAD_E_INVAL; c->max_ctx = atoll(v); }
+        else if (S("--prefill-interleave"))    { if (!num(0, 64, &c->prefill_interleave)) return RAD_E_INVAL; }
+        else if (S("--max-num-seqs"))          { if (!num(1, INT64_MAX, &c->max_seqs)) return RAD_E_INVAL; }
+        else if (S("--max-model-len"))         { if (!num(0, INT64_MAX, &c->max_ctx)) return RAD_E_INVAL; }
         else if (S("--rope-scaling")) {
             if (!(v = need(i))) return RAD_E_INVAL;
-            /* Checked here, so a typo is a refusal at the command line and not a model served
-             * with its trained rotary at a length it cannot reach. */
+            /* Checked here so a typo is refused rather than served with the trained rotary. */
             RopeSpec rs;
             if (!rope_spec_parse(v, &rs) || rs.kind == RopeSpec::Keep) {
                 RAD_ERR("--rope-scaling takes yarn:FACTOR (above 1) with an optional :ORIG trained "
@@ -437,9 +433,8 @@ int config_parse(int argc, char** argv, Config* c) {
             }
             c->rope_scaling = v;
         }
-        /* THE TWO POOLS ARE THE BUDGET RESOLVER'S, always (core/mem/vram_budget.h). A launch
-         * line that tries to size them is told which flags move the split, rather than "unknown
-         * option". */
+        /* The two pools are always sized by the budget resolver (core/mem/vram_budget.h); point
+         * old launch lines at the flags that move the split. */
         else if (S("--vram-weights-mib") || S("--vram-kv-mib")) {
             RAD_ERR("%s was removed: the card is split between the weights and the cache from what "
                     "the model needs. --gpu-headroom-mib takes card space away, --max-model-len and "
@@ -447,11 +442,9 @@ int config_parse(int argc, char** argv, Config* c) {
                     "on the card", a.c_str());
             return RAD_E_INVAL;
         }
-        /* --gpu-headroom takes the short name too: it is the flag an operator reaches for and
-         * "-mib" is the unit, which every other size flag in this list also spells out. Both
-         * parse to the same field. */
+        /* --gpu-headroom is accepted as an alias of --gpu-headroom-mib. */
         else if (S("--gpu-headroom-mib") || S("--gpu-headroom"))
-                                               { if (!(v = need(i))) return RAD_E_INVAL; c->gpu_headroom_mib = atoll(v); }
+                                               { if (!num(0, INT64_MAX, &c->gpu_headroom_mib)) return RAD_E_INVAL; }
         else if (S("--kv-cache-dtype")) {
             if (!(v = need(i))) return RAD_E_INVAL;
             if (std::strcmp(v, "bf16") && std::strcmp(v, "fp8")) {
@@ -460,20 +453,18 @@ int config_parse(int argc, char** argv, Config* c) {
             }
             c->kv_cache_dtype = v;
         }
-        else if (S("--host-pool-mib"))         { if (!(v = need(i))) return RAD_E_INVAL; c->host_pool_mib = atoll(v); }
+        else if (S("--host-pool-mib"))         { if (!num(0, INT64_MAX, &c->host_pool_mib)) return RAD_E_INVAL; }
         else if (S("--embedding-placement") || S("--ngram-placement")) {
             const bool emb = S("--embedding-placement");
             if (!(v = need(i))) return RAD_E_INVAL;
             TablePlacement p;
-            /* The embedding has two tiers: its lookup writes activations the card reads, which a
-             * host kernel reading the container cannot reach, so there is no disk -- and with
-             * ram the default wherever it can be honoured, nothing left for auto to choose. */
+            /* The embedding has two tiers: its lookup writes device activations, so there is no
+             * disk tier, and with ram the default there is nothing for auto to choose. */
             if (emb && (!parse_table_placement(v, &p) ||
                         (p != TablePlacement::Ram && p != TablePlacement::Vram))) {
                 if (parse_table_placement(v, &p) && p == TablePlacement::Auto)
-                    RAD_ERR("--embedding-placement auto was removed in 1.3.0: ram, the default, "
-                            "holds the table in pinned host memory, and vram keeps it on the card. "
-                            "Drop the flag or name one of the two");
+                    RAD_ERR("--embedding-placement auto was removed: ram, the default, holds the "
+                            "table in pinned host memory, and vram keeps it on the card");
                 else
                     RAD_ERR("--embedding-placement takes ram or vram, not '%s'", v);
                 return RAD_E_INVAL;
@@ -488,7 +479,7 @@ int config_parse(int argc, char** argv, Config* c) {
         else if (S("--vision-tower-placement")) {
             if (!(v = need(i))) return RAD_E_INVAL;
             TablePlacement p;
-            /* Two tiers, for the embedding's reason: an encoder writes activations the card reads. */
+            /* Two tiers, as for the embedding: an encoder writes device activations. */
             if (!parse_table_placement(v, &p) || (p != TablePlacement::Ram && p != TablePlacement::Vram)) {
                 RAD_ERR("--vision-tower-placement takes vram or ram, not '%s'", v);
                 return RAD_E_INVAL;
@@ -496,15 +487,9 @@ int config_parse(int argc, char** argv, Config* c) {
             c->tower_placement = p;
         }
         else if (S("--weights-disk-tier"))     { c->weights_disk_tier = true; }
-        else if (S("--prefix-cache-mib"))          { if (!(v = need(i)) ||
-                                                         !parse_int(a.c_str(), v, 0, INT32_MAX, &c->prefix_cache_mib))
-                                                         return RAD_E_INVAL; }
-        else if (S("--prefix-cache-ttl"))          { if (!(v = need(i)) ||
-                                                         !parse_int(a.c_str(), v, 0, INT32_MAX, &c->prefix_cache_ttl))
-                                                         return RAD_E_INVAL; }
-        /* THE PREFIX CACHE KEEPS NOTHING ON A DRIVE: a tier there wore it at the rate the server
-         * prefills, and its copies never outlived the process. The old size flags are told what
-         * replaced them rather than "unknown option". */
+        else if (S("--prefix-cache-mib"))      { if (!num(0, INT32_MAX, &c->prefix_cache_mib)) return RAD_E_INVAL; }
+        else if (S("--prefix-cache-ttl"))      { if (!num(0, INT32_MAX, &c->prefix_cache_ttl)) return RAD_E_INVAL; }
+        /* The prefix cache has no disk tier; the removed flags name their replacements. */
         else if (S("--prefix-cache-host-mib")) {
             RAD_ERR("--prefix-cache-host-mib was renamed: use --prefix-cache-mib");
             return RAD_E_INVAL;
@@ -514,16 +499,26 @@ int config_parse(int argc, char** argv, Config* c) {
                     "(--prefix-cache-mib), and --prefix-cache-ttl says how long", a.c_str());
             return RAD_E_INVAL;
         }
-        else if (S("--placement"))             { if (!(v = need(i))) return RAD_E_INVAL; c->placement = v; }
+        else if (S("--placement")) {
+            if (!(v = need(i))) return RAD_E_INVAL;
+            /* The planner's names, checked here so a typo stops the parse rather than startup
+             * after the container is opened. */
+            Strategy st;
+            if (strategy_parse(v, &st) < 0) {
+                RAD_ERR("--placement takes all_vram, layer_offload, expert_tiered or auto, not "
+                        "'%s'", v);
+                return RAD_E_INVAL;
+            }
+            c->placement = v;
+        }
         else if (S("--deterministic"))         c->deterministic = true;
-        else if (S("--checkpoint-interval"))   { if (!(v = need(i))) return RAD_E_INVAL; c->checkpoint_interval = atoll(v); }
-        else if (S("--checkpoint-slots"))      { if (!(v = need(i))) return RAD_E_INVAL; c->checkpoint_slots = atoll(v); }
+        else if (S("--checkpoint-interval"))   { if (!num(0, INT64_MAX, &c->checkpoint_interval)) return RAD_E_INVAL; }
+        else if (S("--prefill-span"))          { if (!num(1, INT32_MAX, &c->prefill_span)) return RAD_E_INVAL; }
+        else if (S("--checkpoint-slots"))      { if (!num(0, INT64_MAX, &c->checkpoint_slots)) return RAD_E_INVAL; }
         else if (S("--no-prefix-cache"))       c->prefix_cache = false;
         else if (S("--checkpoint-policy")) {
             if (!(v = need(i))) return RAD_E_INVAL;
-            /* Named here rather than accepted blind: a policy name this build does not know would
-             * otherwise fall through to the default and the measurement would compare the default
-             * against itself. */
+            /* Validated, so an unknown name does not silently fall back to the default. */
             if (std::strcmp(v, "geometric-backoff") && std::strcmp(v, "tip-only") &&
                 std::strcmp(v, "keep-all")) {
                 RAD_ERR("--checkpoint-policy '%s' is not one of geometric-backoff, tip-only, "
@@ -534,18 +529,14 @@ int config_parse(int argc, char** argv, Config* c) {
         }
         else if (S("--num-speculative-tokens")) {
             if (!(v = need(i))) return RAD_E_INVAL;
-            /* "auto" is -1 and the engine resolves it once the container is open: the depth is a
-             * property of the DRAFTER and the ARCHITECTURE PLUGIN is the one that knows it
-             * (rad_arch_probe): a serial head names a measured throughput trade-off, a block
-             * drafter names the block length its checkpoint was trained at. */
-            if (!std::strcmp(v, "auto")) c->n_spec = -1;
-            else c->n_spec = atoi(v);
-            /* Every negative depth reads as auto downstream, so only the word may say it. */
-            if (std::strcmp(v, "auto") && c->n_spec < 0) {
-                RAD_ERR("--num-speculative-tokens takes auto or a depth >= 0 (0 turns speculation "
-                        "off), not '%s'", v);
+            /* "auto" is -1, resolved once the container is open from the architecture plugin
+             * (rad_arch_probe): a serial head's measured operating point, or a block drafter's
+             * trained block length. Any negative depth means auto downstream, so only the word
+             * is accepted. */
+            int64_t n = -1;
+            if (std::strcmp(v, "auto") && !parse_int(a.c_str(), v, 0, INT32_MAX, &n))
                 return RAD_E_INVAL;
-            }
+            c->n_spec = (int)n;
         }
         else if (S("--draft-window")) {
             if (!(v = need(i))) return RAD_E_INVAL;
@@ -557,16 +548,10 @@ int config_parse(int argc, char** argv, Config* c) {
             }
         }
         else if (S("--draft-model")) {
-            /* REFUSED, NOT QUIETLY IGNORED. Accepting this flag and then serving the container's
-             * own drafter -- or none -- would hand the caller a server that is not the one they
-             * asked for, with nothing in the output to say so.
-             *
-             * It refuses rather than disappearing because a caller coming from vLLM will reach
-             * for it, and a message that says where the drafter actually comes from is the whole
-             * value the flag can still deliver. This engine loads its drafter from the model
-             * container: rad-convert's OWN --draft-model merges one in, and an MTP head
-             * that ships inside the target checkpoint needs no flag at all. spec.md §10's
-             * "separate draft models load as a second plugin" is a design, not a feature. */
+            /* Refused, not ignored: separate draft models are not supported (spec §10), and the
+             * drafter comes from the container (rad-convert --draft-model merges one in; an MTP
+             * head inside the checkpoint needs no flag). Kept so vLLM users get a message saying
+             * so. */
             if (!(v = need(i))) return RAD_E_INVAL;
             RAD_ERR("--draft-model is not implemented. This engine loads its drafter from the "
                     "model container, not from a second one: merge it at conversion time with "
@@ -575,7 +560,7 @@ int config_parse(int argc, char** argv, Config* c) {
             return RAD_E_INVAL;
         }
         else if (S("--host"))                  { if (!(v = need(i))) return RAD_E_INVAL; c->host = v; }
-        else if (S("--port"))                  { if (!(v = need(i))) return RAD_E_INVAL; c->port = atoi(v); }
+        else if (S("--port"))                  { if (!num(0, 65535, &c->port)) return RAD_E_INVAL; }
         else if (S("--api-key"))               { if (!(v = need(i))) return RAD_E_INVAL; c->api_key = v; }
         else if (S("--served-model-name")) {
             if (!(v = need(i))) return RAD_E_INVAL;
@@ -585,15 +570,7 @@ int config_parse(int argc, char** argv, Config* c) {
         else if (S("--mm-max-patches")) {
             if (!(v = need(i))) return RAD_E_INVAL;
             if (!std::strcmp(v, "auto")) c->mm_max_patches = -1;
-            else {
-                char* end = nullptr;
-                const long long n = std::strtoll(v, &end, 10);
-                if (!end || *end || n < 0) {
-                    RAD_ERR("--mm-max-patches takes auto or a patch count >= 0, not '%s'", v);
-                    return RAD_E_INVAL;
-                }
-                c->mm_max_patches = n;
-            }
+            else if (!parse_int(a.c_str(), v, 0, INT64_MAX, &c->mm_max_patches)) return RAD_E_INVAL;
         }
         else if (S("--reasoning-effort"))      { if (!(v = need(i))) return RAD_E_INVAL;
                                                  c->reasoning_effort = v; }
@@ -615,17 +592,12 @@ int config_parse(int argc, char** argv, Config* c) {
                 at = end + 1;
             }
         }
-        else if (S("--thinking-token-budget")) { if (!(v = need(i)) ||
-                                                     !parse_int(a.c_str(), v, 0, INT32_MAX,
-                                                                &c->thinking_token_budget))
-                                                     return RAD_E_INVAL; }
+        else if (S("--thinking-token-budget")) { if (!num(0, INT32_MAX, &c->thinking_token_budget)) return RAD_E_INVAL; }
         else if (S("--generation-config"))     { if (!(v = need(i))) return RAD_E_INVAL;
                                                  c->generation_config = v; }
         else if (S("--override-chat-template")) { if (!(v = need(i))) return RAD_E_INVAL;
                                                  c->override_chat_template = v; }
-        /* A NEGATIVE VALUE IS REFUSED BY THE RANGE: these four fields use a negative number to
-         * mean "not set", so `--temp -0.5` taken as given would be read as no flag at all and
-         * the container's default served in its place. */
+        /* The range check refuses negatives, which these fields use for "not set". */
         else if (S("--temp") || S("--top-p") || S("--min-p")) {
             if (!(v = need(i))) return RAD_E_INVAL;
             const char* field = S("--temp") ? "temperature" : S("--top-p") ? "top_p" : "min_p";
@@ -665,6 +637,12 @@ int config_parse(int argc, char** argv, Config* c) {
                                                           : "dry_penalty_last_n";
             int n = 0;
             if (!sampler_int(a.c_str(), field, v, &n)) return RAD_E_INVAL;
+            /* A DRY request with an allowed length below 1 is refused at admission, so such a
+             * default would refuse every request that turns DRY on without stating one. */
+            if (S("--dry-allowed-length") && n < 1) {
+                RAD_ERR("--dry-allowed-length must be >= 1, not %d", n);
+                return RAD_E_INVAL;
+            }
             (S("--repeat-last-n") ? c->sample_penalty_last_n
              : S("--dry-allowed-length") ? c->sample_dry_allowed_length
                                          : c->sample_dry_penalty_last_n) = n;
@@ -679,8 +657,7 @@ int config_parse(int argc, char** argv, Config* c) {
                         "'[\"\\n\", \":\"]', not '%s'", v);
                 return RAD_E_INVAL;
             }
-            /* The sampler refuses a DRY request with more (sample/host_ref.h), and every request
-             * leaving the field to this default would be that request. */
+            /* The sampler refuses more (sample/host_ref.h), so the default must not exceed it. */
             if (j.size() > kDryMaxBreakers) {
                 RAD_ERR("--dry-sequence-breakers holds %zu strings; the sampler takes at most %zu",
                         j.size(), kDryMaxBreakers);
@@ -696,28 +673,17 @@ int config_parse(int argc, char** argv, Config* c) {
                 return RAD_E_INVAL;
             }
         }
-        else if (S("--max-tokens-cap"))        { if (!(v = need(i)) ||
-                                                     !parse_int(a.c_str(), v, 0, INT32_MAX, &c->max_tokens_cap))
-                                                     return RAD_E_INVAL; }
-        else if (S("--max-n"))                 { if (!(v = need(i)) ||
-                                                     !parse_int(a.c_str(), v, 1, INT32_MAX, &c->max_n))
-                                                     return RAD_E_INVAL; }
-        else if (S("--max-queued-requests"))   { if (!(v = need(i)) ||
-                                                     !parse_int(a.c_str(), v, 1, INT32_MAX, &c->max_queued_requests))
-                                                     return RAD_E_INVAL; }
-        else if (S("--max-stop-strings"))      { if (!(v = need(i)) ||
-                                                     !parse_int(a.c_str(), v, 1, INT32_MAX, &c->max_stop_strings))
-                                                     return RAD_E_INVAL; }
-        else if (S("--max-stop-bytes"))        { if (!(v = need(i)) ||
-                                                     !parse_int(a.c_str(), v, 1, INT32_MAX, &c->max_stop_bytes))
-                                                     return RAD_E_INVAL; }
+        else if (S("--max-tokens-cap"))        { if (!num(0, INT32_MAX, &c->max_tokens_cap)) return RAD_E_INVAL; }
+        else if (S("--max-n"))                 { if (!num(1, INT32_MAX, &c->max_n)) return RAD_E_INVAL; }
+        else if (S("--max-queued-requests"))   { if (!num(1, INT32_MAX, &c->max_queued_requests)) return RAD_E_INVAL; }
+        else if (S("--max-stop-strings"))      { if (!num(1, INT32_MAX, &c->max_stop_strings)) return RAD_E_INVAL; }
+        else if (S("--max-stop-bytes"))        { if (!num(1, INT32_MAX, &c->max_stop_bytes)) return RAD_E_INVAL; }
         else if (S("--chat-template-kwargs"))  { if (!(v = need(i)) ||
                                                      !parse_template_kwargs(v, &c->chat_template_kwargs))
                                                      return RAD_E_INVAL; }
         else if (S("--reasoning-format")) {
             if (!(v = need(i))) return RAD_E_INVAL;
-            /* Two values, because the reply reader makes one distinction: whether a reasoning
-             * block is lifted out of the content or left in it. */
+            /* The reply reader only distinguishes lifting reasoning out of content or not. */
             if (std::strcmp(v, "auto") && std::strcmp(v, "none")) {
                 RAD_ERR("--reasoning-format takes auto or none, not '%s'", v);
                 return RAD_E_INVAL;
@@ -727,8 +693,7 @@ int config_parse(int argc, char** argv, Config* c) {
         else if (S("--http-threads") || S("--read-timeout") || S("--write-timeout") ||
                  S("--keep-alive-timeout") || S("--retry-after")) {
             if (!(v = need(i))) return RAD_E_INVAL;
-            /* The transport keeps at least four workers whatever it is told (server/http.cpp);
-             * fewer would be a number this flag accepted and the server did not serve. */
+            /* The transport keeps at least four workers (server/http.cpp), so fewer is refused. */
             const int64_t lo = S("--http-threads") ? 4 : S("--retry-after") ? 0 : 1;
             int64_t n = 0;
             if (!parse_int(a.c_str(), v, lo, INT32_MAX, &n)) return RAD_E_INVAL;
@@ -738,9 +703,7 @@ int config_parse(int argc, char** argv, Config* c) {
              : S("--retry-after")   ? c->retry_after_s
                                     : c->http_keep_alive_timeout_s) = (int)n;
         }
-        else if (S("--max-body-mib"))          { if (!(v = need(i)) ||
-                                                     !parse_int(a.c_str(), v, 1, (int64_t)1 << 20, &c->http_max_body_mib))
-                                                     return RAD_E_INVAL; }
+        else if (S("--max-body-mib"))          { if (!num(1, (int64_t)1 << 20, &c->http_max_body_mib)) return RAD_E_INVAL; }
         else if (S("--no-cors"))               c->cors = false;
         else if (S("--image-min-pixels") || S("--image-max-pixels") || S("--video-min-pixels") ||
                  S("--video-max-pixels") || S("--max-source-pixels")) {
@@ -789,51 +752,37 @@ int config_parse(int argc, char** argv, Config* c) {
             RAD_ERR("unknown option '%s'", a.c_str());
             return RAD_E_INVAL;
         }
-        /* WHERE EACH OPTION CAME FROM, for the startup report (core/diag/diag.h): every branch
-         * above that returned refused the option, so reaching here is the option taken. Under the
-         * table's spelling, so an alias reports as the option it is. */
+        /* Record the option's source for the startup report (core/diag/diag.h), under the
+         * table's spelling so aliases report as their option. */
         c->given[S("--gpu-headroom") ? "--gpu-headroom-mib" : a] = "command line";
     }
 
+    /* Both variables are read as the tools read them (rad_home() and rad_hierarchy_from_env() in
+     * tools/iface.cpp), so a plugin validated with rad-kbench or rad-tune serves the same way. Set
+     * but empty is unset, as for RADIANCE_KERNELS: an empty home would load no plugin at all. */
     if (c->radiance_home.empty()) {
         const char* h = getenv("RADIANCE_HOME");
-        c->radiance_home = h ? h : RAD_DEFAULT_HOME;
-        if (h) c->given["--radiance-home"] = "environment (RADIANCE_HOME)";
+        const bool set = h && *h;
+        c->radiance_home = set ? h : RAD_DEFAULT_HOME;
+        if (set) c->given["--radiance-home"] = "environment (RADIANCE_HOME)";
     }
     if (c->kernel_hierarchy.empty()) {
-        /* RADIANCE_KERNELS, ahead of the built-in default.
-         *
-         * The tools read the same variable through rad_hierarchy_from_env() in tools/iface.cpp,
-         * and the engine has to honour it too: otherwise an operator who validated a third-party
-         * plugin with rad-kbench or rad-tune has no way to serve with it short of editing every
-         * launcher's command line. Same spelling, same separator. */
         const char* e = getenv("RADIANCE_KERNELS");
         if (e && *e) {
-            c->kernel_hierarchy = split_commas(e);
+            c->kernel_hierarchy = rad_split_kernel_list(e);
             c->given["--kernels"] = "environment (RADIANCE_KERNELS)";
         }
     }
-    /* AND THERE IS NO BUILT-IN DEFAULT, deliberately. Naming a library here -- the RDNA4 one, say
-     * -- would make the core carry the name of one card's kernels, and on any other machine that
-     * name matches nothing: the engine would warn about a library that is not installed and then
-     * rank the one that IS installed behind the reference implementation, which matches every op
-     * and would answer for all of them.
-     *
-     * An empty hierarchy is not "no order". The loader loads everything it finds and orders it,
-     * the reference library last by construction because it matches anything
-     * (core/plugin/loader.cpp). So dropping a kernel library into $RADIANCE_HOME/kernels is
-     * enough to be used, on any card, with no configuration. A list names the libraries to use:
-     * only those load, in its order, so naming one ahead of another settles a tie between two that
-     * both serve an op and leaving one out keeps it out. */
+    /* No built-in default, deliberately: a named library would be wrong on other cards and would
+     * rank the installed one behind the reference implementation. An empty hierarchy loads every
+     * library found, ordered with the reference last (core/plugin/loader.cpp). A list loads only
+     * the named libraries, in its order. */
     if (c->model.empty()) {
         RAD_ERR("--model is required");
         return RAD_E_INVAL;
     }
-    if (c->tp < 1) { RAD_ERR("--tp must be >= 1"); return RAD_E_INVAL; }
 
-    /* THE KL MODE: one direction, and each direction with what it reads. A run given both would
-     * have to pick which one the operator meant, and picking wrong records a quantised model as
-     * the yardstick. */
+    /* KL mode: exactly one direction, each with the inputs it reads. */
     if (!c->kld_record.empty() && !c->kld_ref.empty()) {
         RAD_ERR("--kld-record writes a reference and --kld-ref scores against one; give one");
         return RAD_E_INVAL;
@@ -852,9 +801,8 @@ int config_parse(int argc, char** argv, Config* c) {
         return RAD_E_INVAL;
     }
 
-    /* TWO FLAGS THAT WOULD SAY THE SAME THING. --reasoning-effort is a template variable with one
-     * extra meaning ("none" is enable_thinking false), so naming either key in
-     * --chat-template-kwargs as well leaves two defaults for one setting and no order to read. */
+    /* --reasoning-effort is a template variable ("none" also sets enable_thinking false), so
+     * either key in --chat-template-kwargs as well would give two defaults for one setting. */
     if (!c->reasoning_effort.empty() &&
         (c->chat_template_kwargs.count("reasoning_effort") ||
          c->chat_template_kwargs.count("enable_thinking"))) {
@@ -869,9 +817,8 @@ int config_parse(int argc, char** argv, Config* c) {
                 (long long)c->max_tokens_cap);
         return RAD_E_INVAL;
     }
-    /* A request is admitted only if all its choices fit the queue, so an `n` past it would be a
-     * 429 however long the caller waited. Checked only when one of the two was stated: the
-     * defaults (8, or --max-num-seqs; and 8 x --max-num-seqs) always fit. */
+    /* A request's choices must all fit the queue, else it is always 429. The defaults always fit,
+     * so this is checked only when one was given. */
     if (c->max_n > 0 || c->max_queued_requests > 0) {
         const int64_t n = c->max_n > 0 ? c->max_n : std::max(8, c->max_seqs);
         const int64_t q = c->max_queued_requests > 0 ? c->max_queued_requests : c->max_seqs * 8;
@@ -918,11 +865,9 @@ std::string joined(const std::map& m, const char* sep)
 using Show = std::string (*)(const Config&);
 struct ShowRow { const char* flag; Show show; };
 
-/* HOW EACH OPTION'S VALUE IS SHOWN, one entry an option of the table above, under the same
- * spelling. config_rows walks the TABLE, so an option missing here still appears in the report --
- * as "(not shown)" -- and diag_test fails naming it. A sentinel a field uses for "resolved at
- * startup" (-1, 0, empty) is shown as what it means; the engine's decisions replace it with the
- * value it resolved to. */
+/* How each option's value is shown, one entry per option of the table above. config_rows walks
+ * the table, so a missing entry shows "(not shown)" and fails diag_test. Sentinels for "resolved
+ * at startup" (-1, 0, empty) are shown by meaning; the engine's decisions replace them. */
 const ShowRow kShow[] = {
     { "--model",              [](const Config& c) { return c.model; } },
     { "--download-dir",       [](const Config& c) { return or_none(c.download_dir, "the XDG cache (~/.cache/radiance/hf)"); } },
@@ -940,6 +885,8 @@ const ShowRow kShow[] = {
     { "--busy-prefill-chunk", [](const Config& c) {
           return c.busy_prefill_chunk < 0 ? std::string("auto")
                : c.busy_prefill_chunk == 0 ? std::string("off") : num(c.busy_prefill_chunk); } },
+    { "--prefill-interleave", [](const Config& c) {
+          return c.prefill_interleave > 0 ? num(c.prefill_interleave) : std::string("off"); } },
     { "--max-num-seqs",       [](const Config& c) { return num(c.max_seqs); } },
     { "--max-model-len",      [](const Config& c) {
           return c.max_ctx ? num(c.max_ctx) : std::string("0 (the model's training context)"); } },
@@ -958,6 +905,7 @@ const ShowRow kShow[] = {
     { "--placement",          [](const Config& c) { return c.placement; } },
     { "--deterministic",      [](const Config& c) { return onoff(c.deterministic); } },
     { "--checkpoint-interval", [](const Config& c) { return num(c.checkpoint_interval); } },
+    { "--prefill-span",       [](const Config& c) { return num(c.prefill_span); } },
     { "--checkpoint-slots",   [](const Config& c) { return num(c.checkpoint_slots); } },
     { "--no-prefix-cache",    [](const Config& c) {
           return std::string(c.prefix_cache ? "not given: prefix caching on" : "prefix caching off"); } },
@@ -967,7 +915,7 @@ const ShowRow kShow[] = {
     { "--draft-model",        [](const Config&) { return std::string("not implemented (the container's own drafter)"); } },
     { "--host",               [](const Config& c) { return c.host; } },
     { "--port",               [](const Config& c) { return num(c.port); } },
-    /* A SECRET IS NOT A VALUE. Whether one is set is what a reader of the log needs. */
+    /* Never print the secret, only whether it is set. */
     { "--api-key",            [](const Config& c) { return std::string(c.api_key.empty() ? "not set" : "set"); } },
     { "--served-model-name",  [](const Config& c) { return or_none(c.served_model_name, "the container's name"); } },
     { "--mm-max-patches",     [](const Config& c) { return c.mm_max_patches < 0 ? std::string("auto") : num(c.mm_max_patches); } },
@@ -991,9 +939,7 @@ const ShowRow kShow[] = {
     { "--dry-allowed-length", [](const Config& c) { return opt(c.sample_dry_allowed_length, "the request default"); } },
     { "--dry-penalty-last-n", [](const Config& c) { return opt(c.sample_dry_penalty_last_n, "the request default"); } },
     { "--dry-sequence-breakers", [](const Config& c) {
-          /* Replaced, not thrown on, like every dump in the report: the strings reach Config from
-           * outside the engine, and a serialiser that throws would end a startup that is otherwise
-           * sound over one line of its log. */
+          /* Invalid UTF-8 is replaced, not thrown on: these strings come from outside. */
           return c.sample_dry_seq_breakers
                      ? nlohmann::json(*c.sample_dry_seq_breakers)
                            .dump(-1, ' ', false, nlohmann::json::error_handler_t::replace)
@@ -1055,7 +1001,7 @@ namespace diag {
 std::vector config_rows(const Config& c) {
     std::vector out;
     for (const Flag& f : g_flags) {
-        /* --help asks for this text and serves nothing; it is not a setting. */
+        /* --help is not a setting. */
         if (!std::strcmp(f.name, "--help")) continue;
         ConfigRow r;
         r.flag = f.name;
diff --git a/core/device/aql.cpp b/core/device/aql.cpp
index d4859f40..02d49ebf 100644
--- a/core/device/aql.cpp
+++ b/core/device/aql.cpp
@@ -1,33 +1,30 @@
 /* aql.cpp -- the AQL device backend: every stream is an HSA queue the engine owns, and every
- * kernel, copy, fill and fence on it is an AQL packet this file writes.
+ * kernel, copy, fill and fence on it is an AQL packet written here.
  *
- * WHY THE ENGINE WRITES ITS OWN PACKETS. hipLaunchKernel costs 0.5-1.3 us of host time a
- * dispatch, where writing the packet is 6 ns; and HIP fences every kernel at SYSTEM scope, which
- * costs the device about half a microsecond between two dependent kernels that an AGENT-scope
- * fence does not. A decode step is ~1600 dispatches a rank, so both are milliseconds a step. HIP
- * also retires a Command object per launch on a thread of its own, which is most of a core under
- * load. None of that is needed to put a kernel on a queue.
+ * Why own packets: hipLaunchKernel costs 0.5-1.3 us of host time per dispatch versus 6 ns to
+ * write the packet, and HIP fences every kernel at system scope, which costs ~0.5 us of device
+ * time between dependent kernels that an agent-scope fence does not. At ~1600 dispatches per rank
+ * per decode step both add up to milliseconds. HIP also retires a Command object per launch on its
+ * own thread, most of a core under load.
  *
- * WHAT STAYS WITH HIP. Allocation, device properties, peer access, IPC and elastic memory are
- * HIP's, through the HIP backend's own entry points. So is compiling and REGISTERING kernels: a
- * kernel library is built by hipcc and calls hipLaunchKernel exactly as it would under HIP. This
- * file defines hipLaunchKernel in the executable, which the dynamic linker binds every plugin's
- * reference to ahead of the HIP runtime's, and it records what __hipRegisterFatBinary and
- * __hipRegisterFunction are told so a host stub maps to its own code object. A launch onto a
- * stream this backend did not create is forwarded to HIP unchanged.
+ * What stays with HIP: allocation, device properties, peer access, IPC, elastic memory, and
+ * compiling and registering kernels. A kernel library is built by hipcc and calls hipLaunchKernel
+ * as usual; this file defines hipLaunchKernel in the executable, so the dynamic linker binds every
+ * plugin's reference here ahead of the HIP runtime, and it records __hipRegisterFatBinary and
+ * __hipRegisterFunction so a host stub maps to its code object. A launch onto a stream this
+ * backend did not create is forwarded to HIP unchanged.
  *
- * THE FENCES. Two kernels on one queue see each other's writes through the L2 with an agent-scope
- * fence; the system scope is only needed where memory the L2 does not see is involved:
- *
- *   - the kernel argument ring lives in VRAM and the host writes it through the BAR, which the L2
- *     does not snoop. A slot is rewritten one ring lap after it was last read, so a system-scope
- *     acquire is placed at least once per half lap: at agent scope alone, every kernel after the
- *     first lap reads its predecessor's arguments. Slots are 1 KiB so that no
- *     kernel's argument fetch shares a cache line with the next slot;
- *   - memory the host wrote. The first dispatch after the host has waited on any queue takes a
- *     system-scope acquire, since that wait is what host writes for the next step follow;
- *   - copies that read or write host or peer memory carry the scope themselves, and so do the
- *     barrier packets that implement events and synchronisation.
+ * Fences: kernels on one queue see each other's writes through the L2 with an agent-scope fence.
+ * System scope is needed only for memory the L2 does not see:
+ *   - the kernel argument ring is in VRAM and written by the host through the BAR, which the L2
+ *     does not snoop. A slot is rewritten one lap after it was last read, so a system-scope
+ *     acquire is placed at least once per half lap; without it every kernel after the first lap
+ *     reads its predecessor's arguments. Slots are 1 KiB so no argument fetch shares a cache line
+ *     with the next slot;
+ *   - host-written memory: the first dispatch after the host waits on any queue takes a
+ *     system-scope acquire, since host writes for the next step follow such a wait;
+ *   - copies touching host or peer memory carry the scope themselves, as do the barrier packets
+ *     that implement events and synchronisation.
  */
 #include "device.h"
 
@@ -136,21 +133,19 @@ Real& real() {
     return *r;
 }
 
-/* THE LAST-ERROR SLOT, AS HIP KEEPS IT. Every HIP call overwrites the thread's last error with
- * its own result, success included, and a plugin's `launch; if (hipGetLastError())` depends on
- * exactly that: an error left by some earlier call must not be reported against the launch. An
- * entry point handled here records its result and marks itself as the thread's latest call, and
- * hipGetLastError answers from it while the mark stands. */
+/* HIP's per-thread last-error slot. Every HIP call overwrites it, success included, and a
+ * plugin's `launch; if (hipGetLastError())` relies on that: an earlier call's error must not be
+ * reported against the launch. An entry point handled here records its result and marks itself
+ * as the thread's latest call; hipGetLastError answers from it while the mark stands. */
 thread_local hipError_t t_err = hipSuccess;
 thread_local bool       t_ours = false;
 
 inline hipError_t ret(hipError_t e) { t_err = e; t_ours = true; return e; }
 thread_local uint8_t    t_next_fence = 0;
 
-/* WHETHER ANYTHING WAS EVER HANDED TO HIP'S OWN STREAMS. Every submission this process makes goes
- * to the backend's queues; a HIP stream gets work only when a caller passes one the backend does
- * not own, and that is forwarded. Until then HIP's default stream is empty, so synchronising it is
- * a no-op answered here -- asking HIP would make it build the stream's queue first. */
+/* Whether any work was forwarded to a HIP stream (a stream this backend does not own). Until
+ * then HIP's default stream is empty and synchronising it is answered here; asking HIP would
+ * make it create the stream's queue first. */
 std::atomic g_hip_streams_used{false};
 
 /* ------------------------------------------------------------------ kernels */
@@ -196,8 +191,8 @@ struct Registry {
     std::mutex mu;
     std::unordered_map by_handle;
     std::unordered_map by_stub;
-    /* Every registration in the order it happened, so the fat binaries one dlopen brought in are a
-     * contiguous run the plugin loader can check against the card (a_code_runs). */
+    /* Registrations in order, so one dlopen's fat binaries form a contiguous run the plugin
+     * loader can check against the card (a_code_runs). */
     std::vector order;
 };
 
@@ -258,11 +253,10 @@ hsa_status_t collect_isa(hsa_isa_t isa, void* data) {
     return HSA_STATUS_SUCCESS;
 }
 
-/* The code-object targets an agent runs, in the runtime's order of preference: its own processor
- * first, then the generic target of its family, each with the modes the agent is in -- for one of
- * these R9700s "gfx1201" then "gfx12-generic". A kernel library built for either loads; asking the
- * runtime rather than keeping a family table here is what keeps a card released after this file
- * from needing an edit to it. */
+/* The code-object targets an agent runs, in the runtime's order of preference: its own processor,
+ * then its family's generic target, each with the agent's modes (an R9700: "gfx1201", then
+ * "gfx12-generic"). Asking the runtime instead of keeping a family table means newer cards need
+ * no edit here. */
 std::vector agent_isas(hsa_agent_t a) {
     std::vector v;
     hsa_agent_iterate_isas(a, collect_isa, &v);
@@ -285,11 +279,11 @@ int topo_node(uint32_t gpu_id) {
     return -1;
 }
 
-/* WHETHER THE CPU CAN WRITE THE CARD'S VRAM: 1 yes, 0 no, -1 the topology does not say. The driver
- * maps VRAM for the CPU only where the PCI BAR spans all of it. With a smaller BAR -- Resizable BAR
- * off in the firmware, or a board without it -- the topology calls the card's memory a private
- * frame buffer and the runtime maps every VRAM allocation PROT_NONE, which the kernel argument
- * rings are; the heap type is what the runtime itself decides from. */
+/* Whether the CPU can write the card's VRAM: 1 yes, 0 no, -1 unknown. The driver maps VRAM for
+ * the CPU only when the PCI BAR spans all of it. With a smaller BAR (Resizable BAR off or
+ * unsupported) the topology reports a private frame buffer heap and the runtime maps every VRAM
+ * allocation PROT_NONE, including the kernel argument rings. The heap type is what the runtime
+ * itself decides from. */
 int vram_host_writable(uint32_t gpu_id) {
     constexpr unsigned long long kHeapFbPrivate = 2;    /* HSA_HEAPTYPE_FRAME_BUFFER_PRIVATE */
     const int n = gpu_id ? topo_node(gpu_id) : -1;
@@ -411,8 +405,8 @@ bool init_devices() {
             g.why = fmt("HIP device %d (%s) has no matching HSA agent with a VRAM pool", i, bus);
             return false;
         }
-        /* Every dispatch's arguments are written by the host into VRAM (a_stream_create), so a
-         * card the CPU cannot write is refused here rather than at the first launch's SIGSEGV. */
+        /* The host writes every dispatch's arguments into VRAM (a_stream_create), so a card the
+         * CPU cannot write is refused here instead of at the first launch's SIGSEGV. */
         if (vram_host_writable(g.dev[(size_t)i].kfd_id) == 0) {
             g.why = fmt("card %d (%s) does not let the CPU write its VRAM: its PCI BAR is smaller "
                         "than its memory. The AQL backend needs Resizable BAR -- turn on Above 4G "
@@ -421,8 +415,8 @@ bool init_devices() {
             return false;
         }
     }
-    /* Refused, a fault is left to the runtime's own handling, which is what the memory-fault
-     * report below exists to replace: so the start says it. */
+    /* Without the handler a fault falls back to the runtime's own handling, which the
+     * memory-fault report below replaces; warn at startup. */
     if (hsa_amd_register_system_event_handler(on_system_event, nullptr) != HSA_STATUS_SUCCESS)
         RAD_WARN("device: the runtime refused the memory-fault report's handler; a GPU memory "
                  "fault will not be reported, and may hang the server instead of ending it");
@@ -508,16 +502,15 @@ KernelRec* resolve(Func* fn, int ord) {
                                    &k->group_size);
     hsa_executable_symbol_get_info(s, HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_PRIVATE_SEGMENT_SIZE,
                                    &k->private_size);
-    /* THE ARGUMENT SLOT IS FIXED AT 1 KiB, and a kernel whose segment does not fit leaves less
-     * than the guard the fence scheme needs between one slot and the next. Refused by name: no
-     * kernel in this tree comes near it. */
+    /* The argument slot is fixed at 1 KiB; a larger segment would eat into the guard the fence
+     * scheme needs between slots. No kernel in this tree comes near it. */
     if (k->kernarg_size > kKargMax) {
         fn->err[ord] = fmt("its kernel argument segment is %u bytes and the backend's slot holds %u",
                            k->kernarg_size, kKargMax);
         return nullptr;
     }
-    /* A dynamic stack needs a scratch size the kernel cannot state; HIP guesses one. This backend
-     * does not guess, and no kernel in this tree has one. */
+    /* A dynamic stack needs a scratch size the kernel cannot state; HIP guesses one, this backend
+     * refuses. No kernel in this tree has one. */
     if (meta->dynamic_stack) {
         fn->err[ord] = "it uses a dynamic stack, which the AQL backend does not size";
         return nullptr;
@@ -546,7 +539,7 @@ KernelRec* resolve(Func* fn, int ord) {
     return out;
 }
 
-/* One lookup a launch, so a thread-local direct-mapped cache sits in front of the registry. */
+/* One lookup per launch: a thread-local direct-mapped cache in front of the registry. */
 struct CacheEnt { const void* stub; int ord; KernelRec* k; };
 thread_local CacheEnt t_cache[512];
 
@@ -585,6 +578,7 @@ struct Stream {
     uint64_t        epoch = 0;                /* host epoch at the last system acquire */
     hsa_signal_t    ride{};                   /* rad_ride: the next dispatch's completion signal */
     bool            agent_only = false;       /* rad_xp_stream_create: never a system-scope acquire */
+    std::atomic gates{0};                /* closed gates (rad_stream_gate) on this queue */
     std::atomic fault{0};
     char*           bounce = nullptr;         /* pinned, for pageable copies */
     std::mutex      bounce_mu;
@@ -596,9 +590,9 @@ struct Stream {
     void unlock() { busy.store(false, std::memory_order_release); }
 };
 
-/* EVERY QUEUE THIS PROCESS HAS MADE, by a number that is never reused, so a record of "the wait
- * packet at index i of queue n" stays meaningful after the queue is destroyed: a destroyed queue's
- * entry is null, and everything it held has been consumed. */
+/* Every queue this process has made, by an id that is never reused, so "packet i of queue n"
+ * stays meaningful after the queue is destroyed. A destroyed queue's entry is null; everything
+ * it held has been consumed. */
 constexpr uint32_t kMaxQueues = 1024;
 std::atomic g_queue_by_id[kMaxQueues];
 std::atomic     g_next_queue_id{0};
@@ -619,11 +613,11 @@ void on_queue_error(hsa_status_t st, hsa_queue_t*, void* data) {
     RAD_ERR("device %d: the AQL queue faulted: %s", s->ord, m ? m : "?");
 }
 
-/* WHAT EVERY QUEUE IS DOING, printed once when a host wait has not come back for five seconds.
- * Nothing on the step path takes that long, so a wait that does is a queue stuck on a packet --
- * a barrier on a signal nothing will decrement, or a kernel that faulted without a report -- and
- * the packet at the read index is the answer. */
-/* Every queue's read index, summed: it only grows, so an unchanged sum is "no queue moved". */
+/* Queue dump, printed once when a host wait has not returned for 5 s. Nothing on the step path
+ * takes that long, so such a wait means a queue is stuck on a packet (a barrier on a signal
+ * nothing will decrement, or a kernel that faulted silently); the packet at the read index says
+ * which. */
+/* Sum of every queue's read index. It only grows, so an unchanged sum means no queue moved. */
 uint64_t read_progress() {
     std::lock_guard lk(G().streams_mu);
     uint64_t n = 0;
@@ -631,7 +625,7 @@ uint64_t read_progress() {
     return n;
 }
 
-/* The DMA lanes' part of the dump, set once a lane opens (the lanes are kept further down). */
+/* The DMA lanes' part of the dump, set once a lane opens. */
 void (*g_dump_lanes)() = nullptr;
 
 void dump_queues(const char* where) {
@@ -669,23 +663,19 @@ void dump_queues(const char* where) {
 
 /* ------------------------------------------------------------------ the memory-fault report
  *
- * WHAT A GPU MEMORY FAULT READ, in this process's terms. The runtime's own line gives the card and
- * the address and nothing else, and an address alone cannot say whether a kernel was handed a
- * buffer that was freed under it, read past the end of a live one, or followed a pointer that was
- * never one. So every range this backend hands out is kept with its kind, size and order, and the
- * latest frees with it, and on a fault the address and the running kernel's pointer arguments are
- * each placed against both.
+ * Explains a GPU memory fault in this process's terms. The runtime reports only the card and the
+ * address, which cannot distinguish a use-after-free, an overrun of a live buffer, or a bogus
+ * pointer. So every range this backend hands out is kept with its kind, size and order, along
+ * with the latest frees, and on a fault the address and the running kernel's pointer arguments
+ * are each located against both.
  *
- * AND THEN THE PROCESS ENDS, at once and without a core. A fault stops the queue it happened on for
- * good, and what the runtime does next turns on the core-size limit, neither way usefully. With no
- * core file to write, the HIP runtime's own handler claims the event (HIP_SKIP_ABORT_ON_GPU_ERROR
- * defaults on) and keeps the error for a HIP call this backend never makes: nothing prints, nothing
- * aborts, and every wait spins on the stopped queue -- a server that hangs with only the stall
- * report to say so. With a limit set, the runtime prints its line and writes a GPU core of every
- * device mapping before it aborts, tens of gigabytes for a served model: minutes of a server that
- * neither answers nor exits. So the report is followed by fatal() -- exit status 70, no destructors
- * (they would wait on that queue), no core -- and a supervisor's restart is what brings the server
- * back. */
+ * The process then ends at once, without a core. A fault stops its queue for good, and the
+ * runtime's next step depends on the core-size limit, uselessly either way. With no core limit,
+ * HIP's handler claims the event (HIP_SKIP_ABORT_ON_GPU_ERROR defaults on) and holds the error
+ * for a HIP call this backend never makes, so every wait spins on the stopped queue and the
+ * server hangs. With a limit, the runtime writes a GPU core of every device mapping before
+ * aborting, tens of GB for a served model. So the report is followed by fatal(): exit status 70,
+ * no destructors (they would wait on that queue), no core; a supervisor restarts the server. */
 struct AllocRec {
     uintptr_t base = 0;
     int64_t   bytes = 0;
@@ -738,9 +728,9 @@ std::string rec_str(const AllocRec& r, uintptr_t a) {
                humanb(r.bytes).c_str(), r.base, humanb((int64_t)(a - r.base)).c_str());
 }
 
-/* Where address `a` lies among this process's ranges: inside a live one, inside one freed since
- * (the newest such first -- a range handed out again holds the address live as well), or in
- * neither, with the live ranges either side of it. Called with g_alloc_mu held. */
+/* Where address `a` lies: inside a live range, inside a freed one (newest first; a reallocated
+ * range also holds it live), or in neither, with the live ranges on either side. Called with
+ * g_alloc_mu held. */
 std::string where_is(uintptr_t a) {
     auto it = g_live.upper_bound(a);
     if (it != g_live.begin()) {
@@ -766,8 +756,8 @@ std::string where_is(uintptr_t a) {
     return s;
 }
 
-/* The runtime's view of the address, which covers what this backend did not allocate itself (a
- * kernel library's own hipMalloc, the runtime's internals): the allocation it falls in, if any. */
+/* The runtime allocation containing the address, if any. Covers what this backend did not
+ * allocate (a kernel library's own hipMalloc, runtime internals). */
 std::string runtime_view(uintptr_t a) {
     hsa_amd_pointer_info_t info{};
     info.size = sizeof info;
@@ -805,11 +795,10 @@ hsa_status_t on_system_event(const hsa_amd_event_t* e, void*) {
         RAD_ERR("device %d: GPU memory fault at %#" PRIxPTR " (%s ): %s; %s", card, va,
                 why.empty() ? " ?" : why.c_str(), where_is(va).c_str(), runtime_view(va).c_str());
     }
-    /* THE KERNEL THAT RAN, AND WHAT IT WAS GIVEN. A queue's read index stays on a packet until it
-     * completes, so the packet there is the one in flight; every pointer-shaped word of its
-     * arguments is placed like the address, which names the operand a stale or short buffer was
-     * passed as. Card `card`'s queues only, and the arguments read through the BAR as they were
-     * written. */
+    /* The running kernel and its arguments. A queue's read index stays on a packet until it
+     * completes, so the packet there is in flight. Every pointer-shaped argument word is located
+     * like the address, which names the operand that got a stale or short buffer. Only card
+     * `card`'s queues; arguments are read back through the BAR. */
     std::lock_guard sl(G().streams_mu);
     for (Stream* s : G().streams) {
         if (s->ord != card) continue;
@@ -843,13 +832,13 @@ hsa_status_t on_system_event(const hsa_amd_event_t* e, void*) {
 /* How long a host wait goes before it reports the queues; see dump_queues. */
 constexpr uint32_t kStallMs = 5000;
 
-/* A spin that notices when it has gone on too long. Checked every 64k iterations, so the clock
- * is read a few thousand times a second at most.
+/* Stall detector for a spin loop. tick() reads the clock every 64k iterations, a few thousand
+ * times a second at most.
  *
- * SLOW OR STUCK: the dump alone cannot say. A long prefill at a deep context can hold one wait past
- * five seconds while the queue drains packet after packet, and a hung kernel holds it with the
- * read index frozen. So the read indices are noted with the dump and looked at once more a stall
- * period later: advanced is a long wait, unchanged is a queue the GPU is not running. */
+ * The dump alone cannot tell slow from stuck: a long prefill at deep context can hold one wait
+ * past 5 s while the queue drains, and a hung kernel holds it with the read index frozen. So the
+ * read indices are sampled with the dump and again one stall period later: advanced means a long
+ * wait, unchanged means the GPU is not running the queue. */
 struct Stall {
     const char* where;
     uint32_t n = 0;
@@ -861,7 +850,7 @@ struct Stall {
         if (told == 2 || (++n & 0xffff)) return;
         check();
     }
-    /* Every call, for a loop that sleeps between calls and so makes few of them. */
+    /* Checks on every call, for a loop that sleeps between calls. */
     void check() {
         if (told == 2) return;
         const auto waited = std::chrono::steady_clock::now() - t0;
@@ -882,11 +871,10 @@ struct Stall {
     }
 };
 
-/* The slot for packet `idx`, once the packet processor has consumed far enough that it is free.
- * A packet with the barrier bit having been LAUNCHED means every packet before it has COMPLETED --
- * which is what a kernel argument slot, read by the whole of its kernel, needs. A played tape
- * leaves the bit off on at most kTapeOverlapRun packets in a row (see TapeRec::overlap), so of any
- * kTapeOverlapRun + 1 consecutive packets one carries it; the margin is that run and one more. */
+/* Reserves packet `idx` once the packet processor has consumed far enough that its slot is free.
+ * A launched barrier-bit packet means every packet before it has completed, which a kernel
+ * argument slot (read for the kernel's whole run) needs. A played tape clears the bit on at most
+ * kTapeOverlapRun consecutive packets (TapeRec::overlap), so the margin is that run plus one. */
 constexpr uint64_t kReserveMargin = (uint64_t)kTapeOverlapRun + 2;
 
 inline int reserve(Stream* s, uint64_t* out) {
@@ -898,6 +886,13 @@ inline int reserve(Stream* s, uint64_t* out) {
             s->rd = hsa_queue_load_read_index_scacquire(s->q);
             if (idx + kReserveMargin - s->rd <= size) break;
             if (s->fault.load(std::memory_order_relaxed)) return RAD_E_DEVICE;
+            /* Behind a closed gate the queue drains only once the host opens it, and the host is
+             * the one waiting here. */
+            if (s->gates.load(std::memory_order_relaxed) > 0) {
+                device_set_error("a submission onto a full queue behind a closed gate: open the "
+                                 "gate (rad_gate_open) first");
+                return RAD_E_STATE;
+            }
             st.tick();
             _mm_pause();
         }
@@ -919,19 +914,17 @@ inline void publish(Stream* s, uint64_t idx, uint16_t header, uint16_t setup) {
 
 /* ------------------------------------------------------------------ recorded passes
  *
- * A PASS RECORDED ONCE IS WRITTEN STRAIGHT INTO THE QUEUES AFTERWARDS. The engine issues the same
- * pass -- the same kernels with the same arguments -- step after step, and nearly all of a
- * dispatch's host cost is producing it: the architecture's block code, the runtime's operand
- * resolution, the kernel library's argument packing. A recorded dispatch is the finished packet and
- * its finished argument block, which lives in VRAM for as long as the tape does, so playing it back
- * is a 60-byte copy into the queue and a header store.
+ * A pass is recorded once and then written straight into the queues. The engine issues the same
+ * kernels with the same arguments step after step, and nearly all of a dispatch's host cost is
+ * producing it (block code, operand resolution, argument packing). A recorded dispatch is the
+ * finished packet plus its argument block, kept in VRAM for the tape's lifetime, so playback is a
+ * 60-byte copy into the queue and a header store.
  *
- * WHAT IS RECORDED is what THIS THREAD submits while a capture is open: dispatches -- kernels, and
- * the backend's own copies and fills -- and event records and waits. Those are kept by EVENT and
- * replayed through the ordinary calls, because a record takes a fresh signal every time (see
- * "events"). A pageable copy stages through the host and waits, which a tape cannot reproduce, and
- * it makes the tape unusable. Other threads' submissions to the same queues are theirs and are not
- * recorded. */
+ * Recorded: what this thread submits while a capture is open -- dispatches (kernels and the
+ * backend's own copies and fills) and event records and waits. Events are kept by event and
+ * replayed through the ordinary calls, because each record takes a fresh signal (see "events").
+ * A pageable copy stages through the host and waits, which a tape cannot reproduce, so it makes
+ * the tape unusable. Other threads' submissions are not recorded. */
 enum : uint8_t { kTapeDispatch = 0, kTapeRecord = 1, kTapeWait = 2 };
 
 struct TapeRec {
@@ -942,9 +935,9 @@ struct TapeRec {
     Stream*  s = nullptr;
     void*    ev = nullptr;              /* a record's or a wait's event */
     hsa_kernel_dispatch_packet_t pkt{}; /* a dispatch's packet, all but the header word */
-    /* A dispatch played WITHOUT the barrier bit, which lets the packet processor launch it while
-     * the packets before it on its queue are still running. Set by the recorder only where it has
-     * shown the dispatch reads and writes nothing those packets write (tape_set_overlap). */
+    /* Play without the barrier bit, so the packet processor may launch it while earlier packets
+     * on the queue still run. Set only where the dispatch touches nothing those packets write
+     * (tape_set_overlap). */
     uint8_t  overlap = 0;
 };
 
@@ -954,8 +947,8 @@ struct Tape {
     std::vector karg_host;   /* the argument blocks, kept to compare tapes by */
     char*                karg = nullptr;    /* VRAM, CPU-mapped, from the end of the capture on */
     std::string          bad;               /* why this tape cannot be played, if it cannot */
-    /* The last packet the latest play wrote on each queue. The argument block is freed only once
-     * each of them has been consumed. */
+    /* Last packet the latest play wrote on each queue; the argument block is freed only after
+     * all of them are consumed. */
     std::vector> last;
 };
 
@@ -997,8 +990,8 @@ inline int acquire_scope(Stream* s, uint64_t idx, bool forced) {
     if (forced || lap || s->epoch != ep) {
         s->last_sys_acq = (int64_t)idx;
         s->epoch = ep;
-        /* The prefetch's stream reads nothing the host writes: a system acquire there would only
-         * invalidate the L2 under the compute stream's feet. */
+        /* The prefetch stream reads nothing the host writes; a system acquire there would only
+         * invalidate the L2 under the compute stream. */
         if (s->agent_only && !forced) return HSA_FENCE_SCOPE_AGENT;
         return HSA_FENCE_SCOPE_SYSTEM;
     }
@@ -1071,8 +1064,8 @@ int dispatch(Stream* s, const KernelRec* k, dim3 g, dim3 b, void** args, size_t
     p->completion_signal.handle = 0;
     constexpr uint16_t setup = 3u << HSA_KERNEL_DISPATCH_PACKET_SETUP_DIMENSIONS;
     if (capturing()) tape_note_dispatch(s, p, setup, ka, n, fence);
-    /* A ride goes on after the tape has its copy: a recorded packet carries no signal of this
-     * issue's, and a play puts on whichever ride is waiting then (PlayRun::put). */
+    /* Attach the ride after the tape copied the packet: a recorded packet carries no signal, and
+     * a play attaches whichever ride is pending then (PlayRun::put). */
     if (s->ride.handle) {
         p->completion_signal = s->ride;
         s->ride.handle = 0;
@@ -1084,21 +1077,18 @@ int dispatch(Stream* s, const KernelRec* k, dim3 g, dim3 b, void** args, size_t
     return RAD_OK;
 }
 
-/* A RUN OF RECORDED DISPATCHES ONTO ONE QUEUE, under one hold of the queue's lock and with the
- * doorbell rung once for every kPlayRing packets rather than once a packet: the doorbell is an
- * uncached write across the link, and a pass is over a thousand dispatches. Each packet's body is
- * copied as recorded and its header -- whose acquire scope depends on what the host wrote since --
- * decided now, as dispatch() decides it. The argument blocks were written to VRAM when the tape
- * was made, so there is nothing to fence before the header. A reserve that would wait for room
- * rings first: the packet processor only takes packets the doorbell has announced. */
+/* A run of recorded dispatches onto one queue, under one hold of the queue lock, ringing the
+ * doorbell once per kPlayRing packets: the doorbell is an uncached write across the link and a
+ * pass is over a thousand dispatches. Each body is copied as recorded; the header is decided now
+ * as in dispatch(), since its acquire scope depends on host writes since recording. Argument
+ * blocks were written to VRAM when the tape was made, so no fence precedes the header. Ring
+ * before a reserve that would wait: the packet processor only takes announced packets. */
 constexpr int kPlayRing = 64;
 
-/* WHERE THIS THREAD'S PLAYS LAST LEFT EACH QUEUE. A queue found further on has had packets put on
- * it that no recording saw -- a weight-table patch or a mover wait between two played stretches,
- * another thread's copy -- and the next played packet on it keeps its barrier bit whatever the
- * recording's analysis said: the analysis proved it independent of the packets recorded before
- * it, and those are no longer the ones in front of it. A queue not in the list is treated the
- * same way. */
+/* Where this thread's plays last left each queue. If a queue has moved since, it holds packets
+ * no recording saw (a weight-table patch or mover wait between played stretches, another thread's
+ * copy), so the next played packet keeps its barrier bit: the overlap analysis only proved it
+ * independent of the recorded packets before it. A queue not in the list is treated the same. */
 struct PlayLeft { uint32_t q = UINT32_MAX; uint64_t wr = 0; };
 constexpr int kPlayLeft = 8;
 thread_local PlayLeft t_left[kPlayLeft];
@@ -1133,8 +1123,8 @@ struct PlayRun {
             if (t_left[i].q == q->id) return t_left[i].wr != q->wr;
         return true;
     }
-    /* `done`, when set, is the packet's completion signal and `rel_min` the least release scope
-     * it must carry -- a record riding on this dispatch; see a_tape_play. */
+    /* `done`, when set, is the packet's completion signal and `rel_min` its minimum release
+     * scope, for a record riding on this dispatch (see a_tape_play). */
     int put(const TapeRec& r, uint64_t* out_idx, hsa_signal_t done = hsa_signal_t{0},
             int rel_min = HSA_FENCE_SCOPE_NONE) {
         if (s != r.s) {
@@ -1153,9 +1143,9 @@ struct PlayRun {
         auto* p = static_cast(s->q->base_address) + (idx & s->mask);
         std::memcpy(reinterpret_cast(p) + 4, reinterpret_cast(&r.pkt) + 4,
                     sizeof(hsa_kernel_dispatch_packet_t) - 4);
-        /* A ride left waiting by host work between two played stretches (rad_ride) is the first
-         * played dispatch's to complete, as an issued one's would be. A record riding on this
-         * dispatch already has the signal; the ride then waits for the next one. */
+        /* A ride left pending by host work between played stretches (rad_ride) is completed by
+         * the first played dispatch, as with an issued one. If a record already rides on this
+         * dispatch, the ride waits for the next. */
         if (!done.handle && s->ride.handle) {
             done = s->ride;
             s->ride.handle = 0;
@@ -1164,8 +1154,8 @@ struct PlayRun {
         const int acq = acquire_scope(s, idx, (r.fence & kFenceAcquireSystem) != 0);
         int rel = (r.fence & kFenceReleaseSystem) ? HSA_FENCE_SCOPE_SYSTEM : HSA_FENCE_SCOPE_AGENT;
         if (rel < rel_min) rel = rel_min;
-        /* A record riding on the dispatch keeps the bit: its completion signal stands for
-         * everything before it on the queue, which an unordered dispatch's completion does not. */
+        /* A dispatch carrying a record keeps the bit: its completion must cover everything before
+         * it on the queue, which an unordered dispatch's does not. */
         const bool ordered = foreign || !r.overlap || done.handle;
         const uint16_t h = header(HSA_PACKET_TYPE_KERNEL_DISPATCH, acq, rel, ordered);
         __atomic_store_n(reinterpret_cast(p), (uint32_t)h | ((uint32_t)r.pkt.setup << 16),
@@ -1179,9 +1169,8 @@ struct PlayRun {
     }
 };
 
-/* One completion signal a thread for synchronous waits, an interrupt signal (see "host waits"):
- * two threads waiting on the same queue each get their own, and a signal is only ever waited on by
- * the thread that armed it. */
+/* One interrupt signal per thread for synchronous waits (see "host waits"). A signal is only
+ * waited on by the thread that armed it, so two threads waiting on one queue do not share. */
 hsa_signal_t thread_signal() {
     thread_local hsa_signal_t s{0};
     if (!s.handle && hsa_signal_create(0, 0, nullptr, &s) != HSA_STATUS_SUCCESS) s.handle = 0;
@@ -1190,28 +1179,25 @@ hsa_signal_t thread_signal() {
 
 /* ------------------------------------------------------------------ host waits
  *
- * A HOST WAIT BLOCKS IN THE DRIVER UNTIL THE DEVICE SAYS IT IS DONE. Every signal the host waits
- * on is an interrupt signal: when the packet that carries it completes, the packet processor posts
- * the signal's event and raises an interrupt, and the driver wakes the threads blocked on that
- * event. A wait costs the host one system call and one wake-up whatever its length, and it makes
- * no guess at how long the device will take, so it can neither sleep past a device that finished
- * early nor spin through one that runs late. What it does cost is the interrupt's delivery: some
- * tens of microseconds between the packet completing and the thread running. That is hidden
- * rather than shortened. The engine keeps work queued behind every point it waits for -- the next
- * step behind a step's end, the layers that do not read a host op's output behind that op's join
- * -- so the device is still running when the host wakes.
+ * A host wait blocks in the driver until the device completes. Every signal the host waits on is
+ * an interrupt signal: when its packet completes, the packet processor posts the signal's event
+ * and raises an interrupt, and the driver wakes the threads blocked on it. A wait costs one
+ * syscall and one wake-up regardless of length, and never guesses the device's duration. The
+ * cost is interrupt delivery, some tens of us; the engine hides it by keeping work queued behind
+ * every point it waits on (the next step behind a step's end, independent layers behind a host
+ * op's join), so the device is still busy when the host wakes.
  *
- * THE WAIT GOES TO THE DRIVER DIRECTLY. The runtime's own blocking wait polls the signal for a
- * stretch before it blocks, which spends a short wait's whole length on a core; the driver's wait
- * on the signal's event spends nothing until the interrupt arrives.
+ * The wait goes to the driver directly. The runtime's blocking wait polls before it blocks,
+ * burning a core for a short wait's whole length; the driver's event wait costs nothing until
+ * the interrupt.
  *
- * NO WAKE-UP IS LOST. The driver counts each event's firings (its age), and a wait that names an
- * age returns at once if the event has fired since. A thread keeps the age each event last woke it
- * at, so an interrupt that lands between reading the signal and entering the driver ends the wait
- * instead of being missed; an age gone stale costs one early return and a second look.
+ * No wake-up is lost. The driver counts each event's firings (its age), and a wait naming an age
+ * returns at once if the event has fired since. Each thread keeps the age each event last woke it
+ * at, so an interrupt between reading the signal and entering the driver ends the wait; a stale
+ * age costs one early return.
  *
- * A FAULT ENDS EVERY WAIT. A faulted queue never completes the signal a wait is on, so every wait
- * also names the fault signal's event, which the queue-error callback fires. */
+ * A fault ends every wait. A faulted queue never completes its signals, so every wait also names
+ * the fault signal's event, which the queue-error callback fires. */
 
 /* The age an event last woke this thread at; 1 is the driver's "never fired". */
 uint64_t& seen_age(uint32_t ev) {
@@ -1251,9 +1237,16 @@ int host_wait(hsa_signal_t sig) {
     return RAD_OK;
 }
 
-/* The store that arms a signal is silent: an interrupt signal's ordinary store also fires its
- * event, which would wake nobody and cost a system call. */
+/* The arming store is silent: an ordinary store to an interrupt signal also fires its event,
+ * which wakes nobody and costs a syscall. */
 int stream_drain(Stream* s) {
+    /* A pageable copy or a destroy behind a closed gate would wait for a barrier the host has not
+     * released yet. */
+    if (s->gates.load(std::memory_order_acquire) > 0) {
+        device_set_error("a host wait on a queue at a closed gate: open the gate "
+                         "(rad_gate_open) first");
+        return RAD_E_STATE;
+    }
     hsa_signal_t sig = thread_signal();
     if (!sig.handle) return RAD_E_DEVICE;
     hsa_signal_silent_store_relaxed(sig, 1);
@@ -1266,18 +1259,16 @@ int stream_drain(Stream* s) {
 
 enum Loc : uint8_t { kDevLocal, kDevPeer, kHost, kPageable };
 
-/* THE ALLOCATIONS A THREAD COPIES BETWEEN, REMEMBERED. hsa_amd_pointer_info takes the runtime's
- * global lock and walks its allocation map, and every copy asks it about both ends -- a few hundred
- * questions a step about the same dozen allocations, about 17 us of each rank thread's step. A hit
- * here answers from the allocation's own range.
+/* Per-thread cache of pointer locations. hsa_amd_pointer_info takes the runtime's global lock and
+ * walks its allocation map; every copy asks about both ends, a few hundred queries per step on
+ * the same dozen allocations, ~17 us of each rank thread's step.
  *
- * Only an answer about a live allocation is kept, never "pageable": memory the runtime does not
- * know may be registered later, and an allocation's kind cannot change while it lives. What can
- * change is WHICH allocation an address belongs to, and only by a free or an unmap -- every one of
- * those in this backend moves `g_loc_gen` first, and an entry of an older generation is ignored.
- * The ranges come back from the runtime itself (sizeInBytes), so a hit is exactly the answer the
- * call would give. A reserved-but-unbacked address is not kept: its card is the reservation's and
- * is looked up per page. */
+ * Only live allocations are cached, never "pageable": unknown memory may be registered later,
+ * while a live allocation's kind cannot change. Which allocation an address belongs to changes
+ * only by a free or unmap, and each of those in this backend bumps `g_loc_gen` first; entries of
+ * an older generation are ignored. Ranges come from the runtime (sizeInBytes), so a hit equals the
+ * call's answer. Reserved-but-unbacked addresses are not cached; their card is looked up per
+ * page. */
 struct LocHit {
     uintptr_t lo = 0, hi = 0;   /* the allocation's range, as the host addresses it */
     intptr_t  shift = 0;        /* agent address minus host address (pinned host memory) */
@@ -1289,7 +1280,7 @@ thread_local LocHit t_loc[kLocWays];
 thread_local unsigned t_loc_next = 0;
 std::atomic g_loc_gen{1};
 
-/* Every entry in every thread's cache stops answering. */
+/* Invalidates every thread's cache. */
 void loc_forget() { g_loc_gen.fetch_add(1, std::memory_order_acq_rel); }
 
 void loc_keep(const void* host_base, size_t bytes, intptr_t shift, uint64_t owner, uint64_t gen) {
@@ -1302,9 +1293,9 @@ void loc_keep(const void* host_base, size_t bytes, intptr_t shift, uint64_t owne
     h.gen = gen;
 }
 
-/* The host ranges this backend pinned itself (see "pinned host memory, in pieces"), by base,
- * ordered so an inner address finds its range. `pool` is the host-pool allocation the range sits
- * in when it was not locked in pieces, and null when it was. */
+/* Host ranges this backend pinned itself (see "pinned host memory, in pieces"), ordered by base
+ * so an interior address finds its range. `pool` is the host-pool allocation holding the range,
+ * or null if it was locked in pieces. */
 struct Pinned {
     int64_t len = 0;
     void* pool = nullptr;
@@ -1334,9 +1325,9 @@ Loc locate(const void* p, const Stream* s, const void** gpu) {
         if (!h.owner) return kHost;
         return h.owner == s->agent.handle ? kDevLocal : kDevPeer;
     }
-    /* PINNED HERE, ANSWERED HERE. hsa_amd_pointer_info reports memory locked with
-     * hsa_amd_memory_lock_to_pool as UNKNOWN on this runtime -- indistinguishable from pageable --
-     * although the lock mapped it on every card at its own address. */
+    /* Ranges pinned here are answered here: hsa_amd_pointer_info reports memory locked with
+     * hsa_amd_memory_lock_to_pool as UNKNOWN (like pageable), although the lock mapped it on
+     * every card at its own address. */
     uintptr_t plo = 0;
     int64_t plen = 0;
     if (pinned_range(p, &plo, &plen)) {
@@ -1475,6 +1466,11 @@ void a_stream_destroy(RadStream rs) {
 int a_stream_sync(RadStream rs) {
     Stream* s = ours(rs);
     if (!s) { device_set_error("rad_stream_sync: not a stream of this backend"); return RAD_E_INVAL; }
+    if (s->gates.load(std::memory_order_acquire) > 0) {
+        device_set_error("rad_stream_sync: the queue waits at a closed gate, which only "
+                         "rad_gate_open releases");
+        return RAD_E_STATE;
+    }
     const int rc = stream_drain(s);
     if (rc < 0) device_set_error("rad_stream_sync: the queue on device %d faulted", s->ord);
     return rc;
@@ -1482,16 +1478,14 @@ int a_stream_sync(RadStream rs) {
 
 /* ---- events.
  *
- * A RECORD TAKES A FRESH SIGNAL, and a signal is only reused once nothing can still name it. That
- * means two things: its own record has completed, AND every wait packet that was enqueued against
- * it has been consumed. Reusing a signal whose record has completed but whose waiters have not yet
- * been reached re-arms it under them: a lagging queue's wait for record r then waits for whatever
- * record reused the signal, which can sit behind a wait on that same lagging queue. Two lanes that
- * join each other every layer produce exactly that cycle within a step.
+ * Each record takes a fresh signal. A signal is reused only when its record has completed and
+ * every wait packet enqueued against it has been consumed. Reusing it earlier re-arms it under a
+ * lagging waiter, which then waits on the newer record; that record can sit behind a wait on the
+ * same lagging queue, a deadlock that two lanes joining each other every layer hit within a step.
  *
- * So each signal carries the (queue, packet index) of every wait that names it, and returns to the
- * free list when both conditions hold. Nothing here ever blocks the host: a signal that cannot be
- * reused yet is simply not reused, and the pool grows to the number of records in flight. */
+ * So each signal carries the (queue, packet index) of every wait naming it and returns to the
+ * free list when both conditions hold. The host never blocks on this; the pool grows to the
+ * number of records in flight. */
 struct Sig {
     hsa_signal_t h{};
     bool         irq = false;                              /* an interrupt signal */
@@ -1519,20 +1513,17 @@ bool reusable(const Sig* g) {
     return true;
 }
 
-/* A signal for one record: an interrupt signal for an event the host waits on, and a GPU_ONLY one
- * otherwise. Only the first kind can end a host wait (see "host waits"), and it costs what the
- * second does not: a driver event, of which a process has a few thousand, and an interrupt at every
- * completion, which an event recorded dozens of times a step and only ever waited on by other
- * queues has no use for. */
+/* A signal for one record: an interrupt signal if the host waits on the event, else GPU_ONLY.
+ * Only interrupt signals can end a host wait (see "host waits"), but each costs a driver event (a
+ * process has a few thousand) and an interrupt per completion, wasted on events recorded dozens
+ * of times a step and waited on only by queues. */
 Sig* sig_get(bool irq) {
     SigPool& p = pool();
     std::lock_guard lk(p.mu);
-    /* THE OLDEST FIRST. A signal retires when its event is recorded again, so the retiring list is
-     * in record order and its front is the signal most likely to be done: taking from the front
-     * until one of the kind asked for is free costs a look or two, where a walk of the whole list
-     * reads every signal's value and every waiter's queue out of memory the device writes. The
-     * walk is kept for when the front is not done -- the host plays a step while the card is
-     * still on the one before, and the records that step retired are then still in flight. */
+    /* Oldest first. Signals retire in record order, so the front is most likely done; popping
+     * from the front costs a look or two, where a full walk reads every signal and waiter queue
+     * from device-written memory. The walk is the fallback for when the front is not done (the
+     * host plays a step while the card is still on the previous one). */
     while (p.free[irq].empty() && !p.retiring.empty() && reusable(p.retiring.front())) {
         Sig* g = p.retiring.front();
         p.retiring.pop_front();
@@ -1595,7 +1586,7 @@ int a_event_create(RadEvent* out, unsigned flags) {
     return RAD_OK;
 }
 
-/* The event goes; its signal stays with the pool until the waits that name it are consumed. */
+/* The signal stays in the pool until the waits naming it are consumed. */
 void a_event_destroy(RadEvent re) {
     Event* e = ev_of(re);
     if (!e) return;
@@ -1610,22 +1601,21 @@ void a_event_destroy(RadEvent re) {
     delete e;
 }
 
-/* A fresh signal armed for one record of `e` on `s`, and the release scope that record needs. The
- * caller puts it on a packet and then hands it to record_adopt. */
+/* A fresh signal armed for one record of `e` on `s`, plus the release scope the record needs. The
+ * caller puts it on a packet, then passes it to record_adopt. */
 Sig* record_arm(Event* e, Stream* s, int* rel) {
     Sig* g = sig_get(e->host);
     if (!g) return nullptr;
     hsa_signal_silent_store_relaxed(g->h, 1);
     g->agent = s->agent;
-    /* A LOCAL EVENT RELEASES TO THE CARD, which its own L2 already is. The system scope has to
-     * wait out every write still on its way to host memory, and while the link is carrying
-     * weights that is a stall of up to tens of microseconds in the recording stream. */
+    /* A local event releases at agent scope, which its L2 already satisfies. System scope waits
+     * for every in-flight write to host memory: up to tens of us while the link streams weights. */
     *rel = e->local ? HSA_FENCE_SCOPE_AGENT : HSA_FENCE_SCOPE_SYSTEM;
     return g;
 }
 
-/* The record carrying `g` is on its queue: it becomes the event's latest, and the one before goes
- * back to the pool once the waits that name it are consumed. */
+/* The record carrying `g` is enqueued: it becomes the event's latest, and the previous signal
+ * retires to the pool. */
 void record_adopt(Event* e, Sig* g) {
     Sig* old = nullptr;
     {
@@ -1657,8 +1647,8 @@ int a_event_record(RadEvent re, RadStream rs) {
     return RAD_OK;
 }
 
-/* The event's lock is held across the enqueue so the signal cannot be retired between being read
- * and having this wait noted against it. */
+/* The event lock is held across the enqueue so the signal cannot retire before this wait is
+ * noted against it. */
 int a_event_wait(RadStream rs, RadEvent re) {
     Event* e = ev_of(re);
     Stream* s = ours(rs);
@@ -1673,8 +1663,8 @@ int a_event_wait(RadStream rs, RadEvent re) {
     std::lock_guard lk(e->mu);
     if (!e->cur) return RAD_OK;               /* never recorded: nothing to wait for */
     uint64_t idx = 0;
-    /* A producer on this stream's own card wrote through the L2 this stream reads, so the acquire
-     * need only reach the card; one on another card, or the host, needs the system's. */
+    /* A producer on this card wrote through the shared L2, so agent scope suffices; another card
+     * or the host needs system scope. */
     const int acq = e->cur->agent.handle == s->agent.handle ? HSA_FENCE_SCOPE_AGENT
                                                             : HSA_FENCE_SCOPE_SYSTEM;
     RAD_TRY(barrier(s, e->cur->h, hsa_signal_t{0}, acq, HSA_FENCE_SCOPE_NONE, &idx));
@@ -1708,8 +1698,7 @@ int a_event_sync(RadEvent re) {
     return host_wait(sig);
 }
 
-/* The host wrote memory the device is about to read: the next dispatch on every queue acquires at
- * system scope, exactly as after a host wait. */
+/* The next dispatch on every queue acquires at system scope, as after a host wait. */
 void a_host_wrote(void) { G().host_epoch.fetch_add(1, std::memory_order_acq_rel); }
 
 /* ---- recorded passes: the calls. See "recorded passes" above. */
@@ -1719,12 +1708,12 @@ inline Tape* tape_of(RadTape t) {
     return (p && p->magic == kTapeMagic) ? p : nullptr;
 }
 
-/* Tapes destroyed while a play of theirs may still be in a queue. */
+/* Destroyed tapes whose plays may still be queued. */
 std::mutex         g_tape_mu;
 std::vector g_tape_retired;
 
-/* Whether every packet the tape's latest play wrote has completed, or its queue is gone: a packet
- * kReserveMargin past it has been launched, which proves it for the reason reserve() gives. */
+/* Whether every packet of the tape's latest play has completed (or its queue is gone): a packet
+ * kReserveMargin past it has launched, which proves it as in reserve(). */
 bool tape_idle(const Tape* t) {
     for (const auto& l : t->last) {
         hsa_queue_t* q = g_queue_by_id[l.first].load(std::memory_order_acquire);
@@ -1767,8 +1756,8 @@ void a_tape_pause(int on) {
     else if (t_tape_pause > 0) --t_tape_pause;
 }
 
-/* The argument blocks go to VRAM on the card the tape's queues belong to, where the packet
- * processor reads them as it reads the ring's; the packets are then final but for their header. */
+/* Moves the argument blocks to VRAM on the tape's card, where the packet processor reads them as
+ * it reads the ring; the packets are then final except for the header. */
 RadTape a_tape_end(int keep) {
     Tape* t = t_tape;
     t_tape = nullptr;
@@ -1846,13 +1835,11 @@ int a_tape_play(RadTape rt, int from, int to) {
     for (int i = from; i < to && rc >= 0; ++i) {
         const TapeRec& r = t->rec[(size_t)i];
         if (r.kind == kTapeDispatch) {
-            /* A RECORD DIRECTLY BEHIND A DISPATCH ON THE SAME QUEUE RIDES ON THE DISPATCH. The
-             * kernel packet carries the barrier bit, so its completion already means everything
-             * before it on the queue is done -- which is all the record's own barrier packet says
-             * -- and the packet processor decrements its completion signal after its release
-             * fence, raised here to the scope the record needs. The separate packet costs the
-             * recording queue a packet of its own between two kernels, and a queue waiting on the
-             * record sees the signal that much later. */
+            /* A record directly after a dispatch on the same queue rides on the dispatch. The
+             * kernel packet has the barrier bit, so its completion already means everything before
+             * it is done, which is all the record's barrier packet would say; the completion signal
+             * is decremented after the release fence, raised here to the record's scope. This
+             * saves a packet between two kernels and signals waiters sooner. */
             const TapeRec* nx = i + 1 < to ? &t->rec[(size_t)i + 1] : nullptr;
             Event* ne = (nx && nx->kind == kTapeRecord && nx->s == r.s) ? ev_of(nx->ev) : nullptr;
             Sig* g = nullptr;
@@ -1870,16 +1857,16 @@ int a_tape_play(RadTape rt, int from, int to) {
                 if (l.first == r.s->id) { l.second = idx; found = true; break; }
             if (!found) t->last.emplace_back(r.s->id, idx);
             if (g) {
-                /* Announced before the event names it, as the record's own path does: another
-                 * queue is about to wait on it. The event's lock is taken with no queue held. */
+                /* Ring before the event names the signal, as a_event_record does, since another
+                 * queue may wait on it next. The event lock is taken with no queue held. */
                 run.end();
                 record_adopt(ne, g);
                 ++i;
             }
             continue;
         }
-        /* An event takes its queue's lock itself, and a wait on another queue must not sit behind
-         * packets this run has written and not yet announced. */
+        /* Event calls take the queue lock themselves, and a wait on another queue must not sit
+         * behind packets this run has written but not announced. */
         run.end();
         rc = r.kind == kTapeRecord ? a_event_record(r.ev, (RadStream)r.s)
                                    : a_event_wait((RadStream)r.s, r.ev);
@@ -1972,9 +1959,9 @@ int blit_copy(Stream* s, void* dst, const void* src, int64_t bytes, uint8_t fenc
     return rc < 0 ? RAD_E_DEVICE : RAD_OK;
 }
 
-/* PAGEABLE MEMORY IS BOUNCED THROUGH PINNED MEMORY AND WAITED FOR, one bounce buffer at a time,
- * which is what HIP does with it too. It is counted: a pageable copy on the step path is a host
- * wait in the middle of a step, and the counter is how such a caller is found. */
+/* Pageable memory is bounced through pinned memory and waited for, one bounce buffer at a time,
+ * as HIP does. The bytes are counted (aql_pageable_bytes) because a pageable copy on the step
+ * path is a host wait mid-step. */
 int pageable_copy(Stream* s, void* dst, Loc ld, const void* src, Loc ls, int64_t bytes) {
     g_pageable_bytes.fetch_add(bytes, std::memory_order_relaxed);
     if (capturing() && t_tape->bad.empty())
@@ -1986,8 +1973,8 @@ int pageable_copy(Stream* s, void* dst, Loc ld, const void* src, Loc ls, int64_t
         if (ls == kPageable && ld == kPageable) {
             std::memcpy((char*)dst + off, (const char*)src + off, (size_t)n);
         } else if (ls == kPageable) {
-            /* The bounce buffer is reused by the next chunk, so the copy out of it has to have run
-             * before the host overwrites it. */
+            /* The previous chunk's copy out of the bounce buffer must finish before the host
+             * overwrites it. */
             RAD_TRY(stream_drain(s));
             std::memcpy(s->bounce, (const char*)src + off, (size_t)n);
             RAD_TRY(blit_copy(s, (char*)dst + off, s->bounce, n,
@@ -2031,8 +2018,7 @@ int a_memcpy_2d_async(void* dst, int64_t dpitch, const void* src, int64_t spitch
     const Loc ld = locate(dst, s, &gd);
     const Loc ls = locate(src, s, &gs);
     if (ld == kPageable || ls == kPageable) {
-        /* Row by row through the 1-D path: a pitched copy of pageable memory has no fast form and
-         * no caller on the step path. */
+        /* Row by row through the 1-D path; no step-path caller copies pitched pageable memory. */
         for (int64_t r = 0; r < height; ++r)
             RAD_TRY(a_memcpy_async((char*)dst + r * dpitch, (const char*)src + r * spitch, width, rs));
         return RAD_OK;
@@ -2046,8 +2032,8 @@ int a_memcpy_2d_async(void* dst, int64_t dpitch, const void* src, int64_t spitch
     return rc < 0 ? RAD_E_DEVICE : RAD_OK;
 }
 
-/* NO PAGEABLE FORM: the kernel reads the range list and the source where they are, so both have
- * to be memory the card reaches, and bouncing them would be a host wait inside the copy. */
+/* No pageable form: the kernel reads the range list and the source in place, so both must be
+ * card-reachable; bouncing them would put a host wait inside the copy. */
 int a_memcpy_ranges_async(void* dst, const void* src, int64_t prefix, const RadCopyRange* ranges,
                           int n, RadStream rs) {
     Stream* s = ours(rs);
@@ -2084,46 +2070,44 @@ int a_memcpy_ranges_async(void* dst, const void* src, int64_t prefix, const RadC
 
 /* ---- the DMA lane: a card's own SDMA queue ------------------------------------------------------
  *
- * A LIST OF COPIES GOES TO THE CARD'S DMA ENGINE THROUGH A QUEUE OF THIS BACKEND'S OWN, not through
- * the runtime's copy call. Measured on gfx1201 with 1.3 MB host->card copies beside a kernel stream
- * that saturates VRAM: this queue moves 28.7 GB/s -- the link -- and costs the kernels nothing; the
- * runtime's copy call moves 22.0 GB/s and costs them 8%; copy kernels get 2.3 GB/s. The runtime's
- * difference is in its packets: from gfx10 on it brackets every copy with a write-back and an
- * invalidation of the WHOLE L2, so a prefill layer's ninety copies were 180 cache flushes under the
- * running GEMMs, and the engine sat out each flush. Here a list is one wait, its copies and one
- * write, and the caches are kept by the two barriers that order the list on its AQL stream.
+ * Copy lists go to the card's DMA engine through this backend's own queue, not the runtime's copy
+ * call. On gfx1201, 1.3 MB host->card copies beside a VRAM-saturating kernel stream: this queue
+ * moves 28.7 GB/s (the link) at no cost to the kernels; the runtime's copy moves 22.0 GB/s and
+ * slows them 8%; copy kernels get 2.3 GB/s. From gfx10 on the runtime brackets every copy with a
+ * write-back and invalidation of the whole L2, two flushes per copy under the running GEMMs. Here
+ * a list is one wait, its copies and one write; the two barriers ordering the list on its AQL
+ * stream handle the caches.
  *
- * The queue is the driver's user-mode SDMA queue (AMDKFD_IOC_CREATE_QUEUE), and the driver holds its
- * buffers to rules the runtime's allocations do not meet: the write pointer must open a one-page GTT
- * buffer of THIS card, which the scheduler firmware pins into the GART, and the ring must be a buffer
- * of exactly its own size. So both are allocated here with the driver calls the runtime's thunk makes
- * for its queues, at an address reserved in this process so the CPU and the card share it, and
- * CPU-mapped through the render node the thunk bound to the process's GPU address space -- the one
- * file the driver lets map a buffer of that space.
+ * The queue is the driver's user-mode SDMA queue (AMDKFD_IOC_CREATE_QUEUE), whose buffers must
+ * meet rules the runtime's allocations do not: the write pointer must start a one-page GTT buffer
+ * of this card (the scheduler firmware pins it into the GART), and the ring must be a buffer of
+ * exactly its own size. Both are allocated here with the thunk's driver calls, at an address
+ * reserved in this process so CPU and card share it, and CPU-mapped through the render node the
+ * thunk bound to the process's GPU address space (the only file the driver lets map such a
+ * buffer).
  *
- * Engine 0 only. A second engine on the same direction moved nothing more (the link is the bound)
- * and cost a VRAM-bound kernel stream 40%. */
+ * Engine 0 only: a second engine in the same direction adds nothing (the link is the bound) and
+ * slowed a VRAM-bound kernel stream 40%. */
 constexpr uint32_t kSdmaCopy     = 1;            /* COPY, sub-op LINEAR */
 constexpr uint32_t kSdmaFence    = 5;
 constexpr uint32_t kSdmaPoll     = 8;            /* POLL_REGMEM */
 constexpr uint64_t kSdmaMaxCopy  = 0x3fffe0;     /* the largest count a linear copy carries */
 constexpr uint64_t kDmaRingBytes = (uint64_t)1 << 20;
 constexpr size_t   kDoorbellPage = 8192;         /* 1024 64-bit doorbells a process */
-/* THE LINK GATE is a signal that only ever counts down: each hold and each release is a barrier
- * packet on the holding stream whose completion takes one off, so the value is odd exactly while a
- * hold is in force, and the engine waits on its low bit. Even to start, and far from zero. */
+/* The link gate is a signal that only counts down: each hold and each release is a barrier packet
+ * on the holding stream whose completion decrements it, so the value is odd exactly while held,
+ * and the engine polls its low bit. Starts even and far from zero. */
 constexpr int64_t  kGateStart    = (int64_t)1 << 62;
-/* A YIELDING LIST CHECKS THE GATE EVERY MEGABYTE. A check costs the engine ~2 us whatever the word's
- * place, so this is 5% of its rate, and a hold that starts mid-list shares the link for 36 us at
- * most; at 2 MB the prefill was slower, at 256 KB the checks cost 17%. */
+/* A yielding list checks the gate every 1 MiB. A check costs the engine ~2 us wherever the word
+ * lives, 5% of its rate, and a hold starting mid-list shares the link for 36 us at most. 2 MiB
+ * made prefill slower; 256 KiB made the checks cost 17%. */
 constexpr uint64_t kYieldBytes   = (uint64_t)1 << 20;
 
-/* THE QUEUE REQUEST AT THE DRIVER'S CURRENT LAYOUT, NOT THE BUILD MACHINE'S. Naming the SDMA engine
- * -- queue type 4 and the sdma_engine_id field -- is KFD ioctl 1.17, and the kernel headers a build
- * sees can be older than the driver the engine runs on: Ubuntu 24.04's  is 1.14,
- * whose struct ends before both fields. The driver copies as many bytes as the ioctl number says and
- * zero-fills or drops the rest, so this longer form is what every driver is sent; one older than
- * 1.17 refuses the queue type, and the lane reports that as its reason. */
+/* The create-queue request in the current driver layout, not the build headers'. Selecting the
+ * SDMA engine (queue type 4, sdma_engine_id) needs KFD ioctl 1.17, but build headers can be older
+ * (Ubuntu 24.04's  is 1.14, which lacks both fields). The driver copies as many
+ * bytes as the ioctl number encodes and zero-fills or drops the rest, so every driver gets this
+ * form; one older than 1.17 refuses the queue type and the lane reports that. */
 struct KfdCreateQueue {
     uint64_t ring_base_address, write_pointer_address, read_pointer_address, doorbell_offset;
     uint32_t ring_size, gpu_id, queue_type, queue_percentage, queue_priority, queue_id;
@@ -2159,10 +2143,10 @@ struct DmaQueue {
     bool                ever_held = false;       /* a stream has held this card's link at least once */
     std::atomic   tried{false};            /* dma_open has run, for the startup report */
     std::string         why;                     /* why it failed */
-    /* A QUEUE WHOSE EVERY LIST ENDS BY WRITING ITS NUMBER to `fin` (the expert prefetch's): the room
-     * check takes the end of the last list finished as the least the engine has read. The read
-     * pointer the engine writes back has been seen to stop moving on such a queue while the engine
-     * ran on, and a ring the host thinks full would wait for ever. */
+    /* For a queue whose lists each end by writing their number to `fin` (the expert prefetch's),
+     * the room check uses the end of the last finished list as a lower bound on what the engine
+     * has read. The engine's written-back read pointer can stop moving on such a queue while the
+     * engine runs on, and a ring the host thinks full would wait forever. */
     volatile uint32_t*  fin = nullptr;
     uint32_t            lists = 0;               /* lists handed over; list k ends at ends[k % kDmaEnds] */
     std::unique_ptr ends;
@@ -2171,7 +2155,7 @@ constexpr uint32_t kDmaEnds = 4096;
 DmaQueue g_dma[kMaxDevices];
 DmaQueue g_dma_xp[kMaxDevices];   /* the expert prefetch's, on the card's second engine */
 
-/* The render node a card's buffers are CPU-mapped through: /dev/dri/renderD, the minor from
+/* Minor of the render node (/dev/dri/renderD) a card's buffers are CPU-mapped through, from
  * the driver's topology entry for its gpu_id. */
 int render_minor(uint32_t gpu_id) {
     const int n = topo_node(gpu_id);
@@ -2266,8 +2250,8 @@ bool dma_bo(uint32_t gpu_id, int minor, size_t size, DmaBo* b, std::string* why)
     return false;
 }
 
-/* THE GATE IS MADE APART FROM THE QUEUE, on first use by either: a launch is handed its address when
- * its op is bound, and that must not open a DMA queue on a card nothing streams weights onto. */
+/* The gate is created separately from the queue, on first use by either: a launch receives its
+ * address when its op is bound, which must not open a DMA queue on a card nothing streams to. */
 hsa_signal_t* gate_signal(int ord) {
     if (ord < 0 || ord >= kMaxDevices) return nullptr;
     DmaQueue& q = g_dma[ord];
@@ -2342,9 +2326,9 @@ bool dma_open(int ord, DmaQueue* q, std::string* why, uint32_t engine = 0, bool
 
 inline uint64_t dma_read(const DmaQueue* q);
 
-/* The DMA lanes beside dump_queues' AQL queues: a list stops at the gate while a hold is in force,
- * so a gate left odd shows as a lane whose ring is written past what it has read. Read without the
- * lane's lock, which a stuck writer may hold. */
+/* The DMA lanes' part of dump_queues. A list stops at the gate while held, so a gate left odd
+ * shows as a ring written past what was read. Read without the lane lock, which a stuck writer
+ * may hold. */
 void dump_dma_lanes() {
     for (int c = 0; c < kMaxDevices; ++c) {
         DmaQueue& q = g_dma[c];
@@ -2362,7 +2346,7 @@ void dump_dma_lanes() {
     }
 }
 
-/* The card's queue, made on first use; null, after one warning, where the driver will not give one. */
+/* The card's queue, opened on first use; null (after one warning) if the driver refuses. */
 DmaQueue* dma_queue(int ord) {
     if (ord < 0 || ord >= kMaxDevices || ord >= (int)G().dev.size()) return nullptr;
     DmaQueue& q = g_dma[ord];
@@ -2385,8 +2369,8 @@ DmaQueue* dma_queue(int ord) {
     return q.ok ? &q : nullptr;
 }
 
-/* What the engine has read: the read pointer it writes back, or past it the end of the last list a
- * numbered queue has finished (DmaQueue::fin). */
+/* Bytes the engine has read: its written-back read pointer, or the end of the last finished list
+ * on a numbered queue if that is further (DmaQueue::fin). */
 inline uint64_t dma_read(const DmaQueue* q) {
     uint64_t r = *q->rptr;
     if (q->fin) {
@@ -2396,9 +2380,9 @@ inline uint64_t dma_read(const DmaQueue* q) {
     return r;
 }
 
-/* `n` dwords onto the ring, the queue's lock held. A packet never straddles the ring's end: the
- * tail is padded with single-dword NOPs. The room is what the engine has read: the ring holds a few
- * hundred layers' lists, so a wait here is the host that far ahead of a stalled engine. */
+/* Writes `n` dwords to the ring; queue lock held. A packet never straddles the ring end: the tail
+ * is padded with single-dword NOPs. The ring holds a few hundred layers' lists, so waiting for
+ * room means the host is that far ahead of a stalled engine. */
 int dma_put(DmaQueue* q, const uint32_t* dw, uint64_t n) {
     const uint64_t cap = kDmaRingBytes / 4;
     uint64_t at = (q->w / 4) & (cap - 1);
@@ -2437,8 +2421,8 @@ inline uint64_t sig_value_addr(const Sig* g) {
 
 /* ------------------------------------------------- the expert prefetch's device half (rad_xp_*) */
 
-/* The card's prefetch queue, on its second DMA engine (the first is the lane's): made on first use;
- * null where the driver gives none. Its lists end with a write of their number to a signal's value,
+/* The card's prefetch queue on its second DMA engine (the lane has the first), opened on first
+ * use; null if the driver refuses. Each list ends by writing its number to a signal's value,
  * which the room check and rad_xp_behind read. */
 DmaQueue* xp_queue(int ord) {
     if (ord < 0 || ord >= kMaxDevices || ord >= (int)G().dev.size()) return nullptr;
@@ -2456,8 +2440,9 @@ DmaQueue* xp_queue(int ord) {
         }
         q.why = why;
         q.tried.store(true, std::memory_order_release);
-        if (!q.ok) RAD_INFO("card %d: no DMA queue on the second engine for the expert prefetch (%s)", ord,
-                            why.c_str());
+        if (!q.ok)
+            RAD_INFO("device: card %d has no DMA queue on the second engine for the expert "
+                     "prefetch (%s)", ord, why.c_str());
     });
     return q.ok ? &q : nullptr;
 }
@@ -2471,7 +2456,7 @@ int a_xp_stream_create(RadStream* out) {
     return RAD_OK;
 }
 
-/* Refused while another ride is waiting for its dispatch on the stream. */
+/* Refused while another ride on the stream is still waiting for its dispatch. */
 int a_ride(RadStream rs, void** token) {
     Stream* s = ours(rs);
     if (!s || !token) return RAD_E_INVAL;
@@ -2514,8 +2499,75 @@ void a_ride_release(void* token, RadStream after, int64_t packets) {
     sig_retire(g);
 }
 
-/* Wait for the mark, wait for the card's link gate if a collective has ever held it (TP: the
- * all-reduce crosses the same link, and the step waits on it, not on these copies), copy, write
+/* ---- gates (rad_stream_gate): a barrier on a signal only the host releases.
+ *
+ * The barrier acquires at system scope, which also takes the acquire the first dispatch after a
+ * host wait would otherwise take (acquire_scope), so the packets behind it run at agent scope. The
+ * signal is an interrupt signal from the event pool, the kind host-wait events record: created by
+ * hsa_signal_create in host memory, where the host's store reaches the packet processor's poll as
+ * any host write to fine-grained memory does. It returns to the pool once the barrier is
+ * consumed. */
+constexpr uint64_t kGateMagic = 0x5241442d41514c47ull;   /* "RAD-AQLG" */
+
+struct Gate {
+    uint64_t magic = kGateMagic;
+    Stream*  s = nullptr;
+    Sig*     g = nullptr;
+};
+
+int a_stream_gate(RadStream rs, void** out) {
+    Stream* s = ours(rs);
+    if (!s || !out) { device_set_error("rad_stream_gate: null or foreign argument"); return RAD_E_INVAL; }
+    if (capturing()) {
+        device_set_error("rad_stream_gate: a tape cannot record a gate");
+        return RAD_E_STATE;
+    }
+    Sig* g = sig_get(true);
+    if (!g) { device_set_error("rad_stream_gate: no signal could be made"); return RAD_E_DEVICE; }
+    hsa_signal_silent_store_relaxed(g->h, 1);
+    uint64_t idx = 0;
+    const int rc = barrier(s, g->h, hsa_signal_t{0}, HSA_FENCE_SCOPE_SYSTEM, HSA_FENCE_SCOPE_NONE,
+                           &idx);
+    if (rc < 0) {
+        hsa_signal_silent_store_relaxed(g->h, 0);
+        sig_retire(g);
+        return rc;
+    }
+    g->waiters.emplace_back(s->id, idx);
+    s->gates.fetch_add(1, std::memory_order_acq_rel);
+    Gate* gt = new Gate();
+    gt->s = s;
+    gt->g = g;
+    *out = gt;
+    return RAD_OK;
+}
+
+int a_gate_open(void* p) {
+    Gate* gt = static_cast(p);
+    if (!gt || gt->magic != kGateMagic) return RAD_E_INVAL;
+    hsa_signal_store_screlease(gt->g->h, 0);
+    gt->s->gates.fetch_sub(1, std::memory_order_acq_rel);
+    sig_retire(gt->g);
+    gt->magic = 0;
+    delete gt;
+    return RAD_OK;
+}
+
+/* The packets that fit before reserve() would wait for the read index, and before a dispatch would
+ * take the half-lap system-scope acquire (acquire_scope). Barriers count against both. */
+int64_t a_gate_room(RadStream rs) {
+    Stream* s = ours(rs);
+    if (!s) return 0;
+    s->lock();
+    const uint64_t rd = hsa_queue_load_read_index_scacquire(s->q);
+    const int64_t cap = (int64_t)(rd + s->mask + 1) - (int64_t)kReserveMargin - (int64_t)s->wr;
+    const int64_t lap = s->last_sys_acq + (int64_t)(kQueuePackets / 2) - (int64_t)s->wr;
+    s->unlock();
+    return std::max(0, std::min(cap, lap));
+}
+
+/* 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. */
 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) {
@@ -2588,12 +2640,11 @@ void a_free_uncached(void* p) {
     if (p) (void)hipFree(p);
 }
 
-/* A LIST: the engine waits for the stream, copies, and the stream waits for the engine (the two
- * barriers in `flush`). A copy the engine cannot take goes the kernel way, in its place in the
- * list: pageable memory (staged through a bounce buffer), a peer card's memory, and any copy while a
- * pass is being recorded -- a tape replays queue packets, and a DMA submission is not one. The two
- * signals go back to the pool behind the second barrier: by then the engine has written `out`, so
- * it has stopped reading `in` as well. */
+/* The engine waits for the stream, copies, and the stream waits for the engine (the two barriers
+ * in `flush`). Copies the engine cannot take go as kernels, in list order: pageable memory
+ * (bounced), a peer card's memory, and any copy while recording (a tape replays queue packets, and
+ * a DMA submission is not one). Both signals retire behind the second barrier: once the engine
+ * has written `out` it has stopped reading `in`. */
 int a_memcpy_list_async(const RadCopySeg* segs, int n, unsigned flags, RadStream rs) {
     Stream* s = ours(rs);
     if (!s) { device_set_error("rad_memcpy_list_async: not a stream of this backend"); return RAD_E_INVAL; }
@@ -2609,13 +2660,12 @@ int a_memcpy_list_async(const RadCopySeg* segs, int n, unsigned flags, RadStream
     std::vector dma;
     dma.reserve((size_t)n);
     bool card = false;                       /* a copy reads or writes this card's memory */
-    /* THE ORDER ON THE STREAM IS KEPT BY TWO BARRIERS AND A SIGNAL EACH WAY. The first completes `in`
-     * once everything before the list has; the engine polls `in` before the copies and writes `out`
-     * after them, and the second barrier holds the stream on `out`. The release before is the
-     * system's when a copy touches this card's memory, so the engine reads what kernels wrote and no
-     * dirty L2 line of a destination is written back over its copy later; the acquire after is the
-     * system's always, because the engine writes memory past the L2 and the L2 may still hold the
-     * destination's old bytes. */
+    /* Stream order is kept by two barriers and a signal each way. The first barrier completes
+     * `in` once everything before the list is done; the engine polls `in`, copies, and writes
+     * `out`; the second barrier holds the stream on `out`. The first releases at system scope
+     * when a copy touches this card's memory, so the engine sees kernel writes and no dirty L2
+     * line is later written back over a copied destination. The second always acquires at system
+     * scope: the engine writes past the L2, which may still hold the destination's old bytes. */
     auto flush = [&]() -> int {
         if (dma.empty()) return RAD_OK;
         DmaQueue* dq = dma_queue(s->ord);
@@ -2651,11 +2701,10 @@ int a_memcpy_list_async(const RadCopySeg* segs, int n, unsigned flags, RadStream
                                        (uint32_t)ia, (uint32_t)(ia >> 32), 0u, 0xffffffffu,
                                        10u /* interval */ | (0xfffu << 16) /* retry forever */ };
             rc = dma_put(dq, poll, 6);
-            /* A yielding list checks the gate before its first copy and again once a piece's worth
-             * has gone since the last check, its copies cut to that size, so a hold that starts
-             * mid-list shares the link for one piece at most. Not on a card whose link nothing has
-             * held: no collective crosses it (one card serving alone), and the checks would cost
-             * the engine 5% of a link-bound prefill for nothing. */
+            /* A yielding list checks the gate before its first copy and after every piece (copies
+             * are cut to piece size), so a hold starting mid-list shares the link for one piece at
+             * most. Skipped on a card whose link was never held (no collective, e.g. one card
+             * alone), where the checks would cost 5% of a link-bound prefill. */
             const bool yield = (flags & RAD_COPY_YIELD) != 0 && dq->ever_held;
             const uint64_t piece = yield ? std::min(kYieldBytes, kSdmaMaxCopy) : kSdmaMaxCopy;
             const uint64_t ga = (uint64_t)dq->gate.handle + offsetof(amd_signal_t, value);
@@ -2688,7 +2737,7 @@ int a_memcpy_list_async(const RadCopySeg* segs, int n, unsigned flags, RadStream
             }
             dma_kick(dq);
         }
-        /* A list the ring could not take is not waited for: the stream would stop on `out` for good. */
+        /* If the ring refused the list, release `out` so the stream does not wait on it forever. */
         if (rc != RAD_OK) hsa_signal_store_screlease(out->h, 0);
         uint64_t idx = 0;
         const int br = barrier(s, out->h, hsa_signal_t{0}, HSA_FENCE_SCOPE_SYSTEM,
@@ -2717,7 +2766,7 @@ int a_memcpy_list_async(const RadCopySeg* segs, int n, unsigned flags, RadStream
         const void* gs = nullptr;
         const Loc ld = locate(g.dst, s, &gd);
         const Loc ls = locate(g.src, s, &gs);
-        /* A peer card's memory is the peer's engine's to copy, and the list keeps to this card. */
+        /* The list stays on this card; a peer's memory is copied by kernel. */
         if (capturing() || ld == kPageable || ls == kPageable || ld == kDevPeer || ls == kDevPeer) {
             RAD_TRY(flush());
             RAD_TRY(a_memcpy_async(g.dst, g.src, g.bytes, rs));
@@ -2729,15 +2778,15 @@ int a_memcpy_list_async(const RadCopySeg* segs, int n, unsigned flags, RadStream
     return flush();
 }
 
-/* A hold or a release is one barrier on the holding stream, completing the gate: it takes effect
- * once everything before it on the stream is done, which is when the collective issued after it
- * starts, or when the one before it has finished. A recorded pass holds nothing -- a hold only paces
- * the lists, and a play issues none. */
+/* A hold or release is one barrier on the holding stream that decrements the gate. It takes
+ * effect once everything before it on the stream is done: as the following collective starts, or
+ * after the preceding one finishes. A recorded pass holds nothing; holds only pace lists, and a
+ * play issues none. */
 int a_link_hold(RadStream rs, int on) {
     Stream* s = ours(rs);
     if (!s) { device_set_error("rad_link_hold: not a stream of this backend"); return RAD_E_INVAL; }
     if (capturing()) return RAD_OK;
-    /* Only where lists go to the engine: nothing else polls the gate. */
+    /* Only the DMA engine polls the gate. */
     DmaQueue* dq = dma_queue_open(s->ord);
     if (!dq) return RAD_OK;
     std::lock_guard lk(dq->mu);
@@ -2746,7 +2795,7 @@ int a_link_hold(RadStream rs, int on) {
                          on == 1 ? "already" : "not");
         return RAD_E_STATE;
     }
-    /* The book follows the queue: a barrier the queue refused changed nothing. */
+    /* Update the state only after the barrier is accepted. */
     if (on != 2)
         RAD_TRY(barrier(s, hsa_signal_t{0}, dq->gate, HSA_FENCE_SCOPE_NONE, HSA_FENCE_SCOPE_NONE));
     dq->held = on == 1;
@@ -2795,23 +2844,19 @@ int a_memset_async(void* dst, int value, int64_t bytes, RadStream rs) {
 
 /* ---- VRAM: the room check.
  *
- * A VRAM ALLOCATION THE DRIVER REFUSES KILLS THE PROCESS IN THIS RUNTIME once a queue has been
- * destroyed. On a refusal ROCr releases its caches and asks again (GpuAgent::Trim), and the release
- * walks every queue the process created on the card. ROCm 7.2's runtime adds a queue to that list
- * (GpuAgent::aql_queues_, amd_gpu_agent.cpp) and never takes a destroyed one off it, so the walk
- * calls into freed memory and the process dies of SIGSEGV inside libhsa-runtime64.so instead of
- * being told no. Startup destroys queues before it allocates anything large -- the two it makes to
- * measure what a queue costs, and the loader's when a load ends -- so every refused device
- * allocation took that path: a card another process had taken memory from crashed startup in
- * hipMalloc rather than refusing its arena. ROCr's develop branch takes the queue off the list on
- * destroy; until a release carries that, every device allocation here is held to what the driver
- * will still give on the card and refused by this layer, naming what the card has and which
- * processes hold it, before the runtime is asked.
+ * In ROCm 7.2 a VRAM allocation the driver refuses kills the process once any queue has been
+ * destroyed. On a refusal ROCr frees its caches and retries (GpuAgent::Trim), walking every queue
+ * created on the card, but it never removes destroyed queues from that list
+ * (GpuAgent::aql_queues_, amd_gpu_agent.cpp), so the walk touches freed memory and SIGSEGVs in
+ * libhsa-runtime64.so. Startup destroys queues before its large allocations (the two that measure
+ * a queue's cost, and the loader's), so a card short on memory would crash in hipMalloc instead of
+ * refusing the arena. Until a ROCr release removes the queue on destroy (develop does), every
+ * device allocation is checked here first against what the driver will still give, and refused
+ * with what the card has and which processes hold it.
  *
- * The figure is the driver's own (AMDKFD_IOC_AVAILABLE_MEMORY), the one its allocation check
- * compares against, and the request is rounded up to 2 MiB so one the driver rounds up is not
- * passed by a hair. It is a check, not a reservation: memory another process takes between it and
- * the allocation still reaches the runtime. */
+ * The figure is the driver's own (AMDKFD_IOC_AVAILABLE_MEMORY), which its allocation check uses;
+ * requests are rounded up to 2 MiB so one the driver rounds up does not slip past. It is a check,
+ * not a reservation: memory another process takes in between still reaches the runtime. */
 
 /* What the driver will still allocate on card `ord`, -1 when it will not say. */
 int64_t card_available(int ord) {
@@ -2822,9 +2867,9 @@ int64_t card_available(int ord) {
     return (int64_t)a.available;
 }
 
-/* The processes holding VRAM on card `ord`, largest first, as the driver lists them: host process
- * ids, which inside a container are not this process's own numbering, so this process is named
- * only where the ids agree. */
+/* Processes holding VRAM on card `ord`, largest first. The driver lists host pids, which differ
+ * from this process's numbering inside a container, so this process is named only when they
+ * agree. */
 std::string card_holders(int ord) {
     const uint32_t id = G().dev[(size_t)ord].kfd_id;
     std::vector> held;
@@ -2859,7 +2904,7 @@ std::string card_holders(int ord) {
 }
 
 /* True when card `ord` can take `bytes` more; otherwise false with the refusal set, `what` naming
- * the call. A card whose figure the driver will not give is let through, as before this check. */
+ * the call. If the driver gives no figure the allocation is allowed. */
 bool card_has_room(int ord, int64_t bytes, const char* what) {
     const int64_t avail = card_available(ord);
     if (avail < 0) return true;
@@ -2876,23 +2921,21 @@ bool card_has_room(int ord, int64_t bytes, const char* what) {
 
 /* ---- elastic memory, through HSA.
  *
- * HIP's virtual-memory calls build HIP's own default-stream queue on the card the first time a
- * range is backed -- hipMemCreate hands the new pages to HIP's command machinery -- and that queue
- * is a hardware queue this process never submits to. A card runs only so many queues at once; past
- * that it time-slices them, every kernel on the busy ones pays for the switch, and the two lanes of
- * a rank stop overlapping. The same reservations, backings and unmappings through HSA touch no
- * queue at all.
+ * HIP's virtual-memory calls create HIP's default-stream queue on the card the first time a range
+ * is backed (hipMemCreate hands the pages to HIP's command machinery), a hardware queue this
+ * process never submits to. Past a card's concurrent-queue limit it time-slices queues, every
+ * kernel pays for the switch, and a rank's two lanes stop overlapping. The same operations through
+ * HSA create no queue.
  *
- * A CARD WHOSE POOL REPORTS NO ALLOCATION GRANULE REPORTS A GRANULARITY OF ZERO, and every pool is
- * then sized once and allocated whole (VMem::supported()). A backed range is readable and writable
- * by its reservation's card only: every elastic pool belongs to one rank, and tensor parallel shares
- * through the all-reduce buffers, not these.
+ * A card whose pool reports no allocation granule reports granularity 0, and pools are then sized
+ * once and allocated whole (VMem::supported()). A backed range is accessible only to its
+ * reservation's card: each elastic pool belongs to one rank, and tensor parallel shares through
+ * the all-reduce buffers, not these.
  *
- * WHICH CARD A RESERVATION BELONGS TO is recorded when it is made, because the pages a commit maps
- * go on a device and the vtable names none: the device current at RESERVE time is the rank's --
- * every rank reserves its pools with its own card selected -- while the thread that later grows a
- * pool may have visited another card since. A mapping's handle is kept until the unmap, which is
- * what releases it. */
+ * The owning card is recorded at reserve time, because a commit must map pages on a device and
+ * the vtable names none. Each rank reserves with its own card current, while the thread that later
+ * grows a pool may have switched cards since. A mapping's handle is kept until the unmap releases
+ * it. */
 struct VRes { uintptr_t base; uintptr_t end; int ord; };
 std::mutex                                                   g_vres_mu;
 std::vector                                            g_vres;
@@ -2914,17 +2957,20 @@ int64_t a_vmem_granularity(void) {
                                      HSA_AMD_MEMORY_POOL_INFO_RUNTIME_ALLOC_REC_GRANULE, &gran) !=
             HSA_STATUS_SUCCESS || gran == 0)
         return 0;
-    /* The pool's own answer is a floor and not the quantum to use: a map is tens of microseconds
-     * whatever it covers. RAD_ALIGN_POOL is what every pool is aligned to already, and taking it
-     * makes this backend's granule the host backend's. */
+    /* The pool's granule is only a floor: a map costs tens of us whatever its size. Every pool is
+     * already aligned to RAD_ALIGN_POOL, and using it matches the host backend's granule. */
     const int64_t g = (int64_t)gran < (int64_t)RAD_ALIGN_POOL ? (int64_t)RAD_ALIGN_POOL : (int64_t)gran;
     return align_up(g, (int64_t)RAD_ALIGN_POOL);
 }
 
 void* a_vmem_reserve(int64_t bytes, int64_t align) {
     if (bytes <= 0) return nullptr;
+    /* The reservation's card decides where a_vmem_commit maps its pages. */
     int dev = 0;
-    if (hipGetDevice(&dev) != hipSuccess) dev = 0;
+    if (hipGetDevice(&dev) != hipSuccess) {
+        device_set_error("vmem: no current device to reserve %lld bytes for", (long long)bytes);
+        return nullptr;
+    }
     void* p = nullptr;
     if (hsa_amd_vmem_address_reserve_align(&p, (size_t)bytes, 0,
                                            (uint64_t)(align > 0 ? align : 0), 0) !=
@@ -2949,8 +2995,8 @@ void a_vmem_release(void* base, int64_t bytes) {
     (void)hsa_amd_vmem_address_free(base, (size_t)bytes);
 }
 
-/* Backed, and readable and writable by the reservation's card at once: HSA grants access per
- * mapping, so there is nothing for a later protect over a longer run to add. */
+/* Backs the range and grants the reservation's card read/write access at once. HSA grants access
+ * per mapping, so vmem_protect has nothing to add. */
 int a_vmem_commit(void* addr, int64_t bytes) {
     if (!addr || bytes <= 0) return RAD_E_INVAL;
     int dev = vres_ord(addr);
@@ -2978,7 +3024,7 @@ int a_vmem_commit(void* addr, int64_t bytes) {
     }
     std::lock_guard lk(g_vres_mu);
     g_vmaps[(uintptr_t)addr] = h;
-    loc_forget();   /* the range is backed now, and no longer only reserved */
+    loc_forget();   /* the range is backed, no longer only reserved */
     return RAD_OK;
 }
 
@@ -3006,52 +3052,43 @@ int a_vmem_decommit(void* addr, int64_t bytes) {
 
 /* ------------------------------------------------------------------ pinned host memory, in pieces
  *
- * EVERY PINNED OR MAPPED HOST ALLOCATION IS ONE ADDRESS RANGE LOCKED AS PIECES OF AT MOST
- * kPinPiece, BECAUSE OF THE IOMMU. Host memory a card reaches is a userptr buffer object, which the
- * kernel DMA-maps for each card as one scatterlist. On an Intel VT-d host in scalable mode (Linux
- * 7.0, two R9700) that mapping fails for any single buffer larger than about 2.5 GiB while smaller
- * ones succeed every time, so a 12 GiB host pool allocated whole was refused at startup far below
- * the driver's pinned-memory cap. Passthrough (iommu=pt) lets the large pin through but takes peer
- * access away, which every multi-rank kernel requires, so the configuration has to work with
- * translation on. A range locked in pieces never asks the IOMMU for more than one piece at a time.
+ * Every pinned or mapped host allocation is one address range locked in pieces of at most
+ * kPinPiece, because of the IOMMU. Card-reachable host memory is a userptr buffer object that the
+ * kernel DMA-maps per card as one scatterlist. On Intel VT-d in scalable mode that mapping fails
+ * for any single buffer over ~2.5 GiB, so a large host pool allocated whole is refused far below
+ * the driver's pinned-memory cap. iommu=pt allows the large pin but removes peer access, which
+ * every multi-rank kernel needs, so translation must stay on.
  *
- * The lock is ROCr's, hsa_amd_memory_lock_to_pool: the same userptr pin hipHostMalloc makes, one
- * buffer object per call. hsa_amd_pointer_info does not report what it locked, so locate() answers
- * from this backend's own record of the ranges (g_pinned) and HIP is never asked about them.
- * hipHostRegister would be HIP's record instead, and HIP's record is not what the copies read.
+ * The lock is ROCr's hsa_amd_memory_lock_to_pool, the same userptr pin hipHostMalloc makes, one
+ * buffer object per call. hsa_amd_pointer_info does not report locked ranges, so locate() answers
+ * from g_pinned and HIP is never asked. (hipHostRegister would record them in HIP, which the
+ * copies do not read.)
  *
- * The cards still see one range: a locked piece is mapped at its own host address, so the pieces
- * of one reservation are consecutive on the card too. Each piece is checked rather than assumed,
- * because the pools, the mover and the activation arena all hand a kernel base + offset.
+ * The cards still see one range: each piece is mapped at its host address, so the pieces are
+ * contiguous on the card too. This is checked per piece, because the pools, the mover and the
+ * activation arena all hand kernels base + offset.
  *
- * THAT TAKES THE KERNEL DRIVER'S SVM API, AND WITHOUT IT THE RANGE IS ONE ALLOCATION OF THE HOST
- * POOL. A lock lands at its host address because ROCr's thunk registers the range through the
- * KFD's SVM API, which maps a range where it is. A driver that does not offer it -- amdgpu could
- * not register the card's memory with HMM, seen in a KVM guest with both cards passed through --
- * gets a userptr buffer object instead, at an address the thunk's own aperture hands out: below
- * the host address, and each piece a guard page away from the one before, so the pieces are
- * neither where the host has them nor next to each other on the card. hsa_amd_vmem cannot join
- * them (ROCm 7.2 refuses a vmem handle on the host pool). The host pool's own allocation can: the
- * thunk maps it for the CPU at the address the aperture gave the cards. It is one buffer object,
- * as hipHostMalloc made before the pieces, so a host whose IOMMU refuses a large pin AND whose
- * driver has no SVM API has no large pinned range at all; the refusal names both. Which path a
- * process takes is the runtime's HSA_AMD_SYSTEM_INFO_SVM_SUPPORTED, the same capability the thunk
- * decides by, and the log says it once.
+ * In-place mapping needs the KFD's SVM API, through which ROCr's thunk registers the range.
+ * Without it (e.g. amdgpu could not register card memory with HMM, seen in a KVM guest with
+ * passed-through cards) each lock becomes a userptr buffer object at an address from the thunk's
+ * aperture: below the host address, with a guard page between pieces, so pieces are neither in
+ * place nor contiguous. hsa_amd_vmem cannot join them (ROCm 7.2 refuses a vmem handle on the host
+ * pool), but a host-pool allocation can: the thunk maps it for the CPU at the cards' address. It
+ * is one buffer object, so a host whose IOMMU refuses large pins and whose driver lacks SVM has no
+ * large pinned range at all; the refusal names both. The path is chosen by
+ * HSA_AMD_SYSTEM_INFO_SVM_SUPPORTED, the capability the thunk uses, and logged once.
  *
- * What hipHostMalloc does besides the pin is kept: huge pages advised from 2 MiB up, a preferred
- * NUMA node that is the one nearest the current card (ROCr allocates from that node's pool),
- * fine-grained coherence (the pool locked to), and access from every card. The memory is PRIVATE
- * anonymous memory and not hipHostMalloc's shared kind, because the advice is only as good as the
- * policy behind it: shared anonymous memory is shmem, whose huge pages follow
- * transparent_hugepage/shmem_enabled, `never` on stock Ubuntu, so the pool got 4 KiB pages there
- * whatever it advised. Private memory follows transparent_hugepage/enabled, `madvise` on the same
- * hosts. Where an IOMMU translates the cards' reads (Intel VT-d, which these pieces exist for) each
- * page is a translation of its own, and a pool streamed from at 4 KiB measured 10-21% slower
- * prefill on such a host. MADV_DONTFORK keeps the range out of any child: a private range
- * a card has pinned is copied whole into a forked child, where it is of no use.
+ * Kept from hipHostMalloc: huge pages advised from 2 MiB up, preferred NUMA node nearest the
+ * current card (ROCr allocates from that node's pool), fine-grained coherence (the pool locked
+ * to), and access from every card. The memory is private anonymous, not hipHostMalloc's shared
+ * kind: shared anonymous memory is shmem, whose huge pages follow
+ * transparent_hugepage/shmem_enabled (`never` on stock Ubuntu), while private memory follows
+ * transparent_hugepage/enabled (`madvise` there). Under IOMMU translation each page is its own
+ * translation, and streaming from a 4 KiB-page pool made prefill 10-21% slower. MADV_DONTFORK
+ * keeps a forked child from copying the pinned range whole.
  *
- * kPinPiece is a power of two well under the failing size. The cost is one buffer object per piece
- * per card: a few dozen for the largest pools. */
+ * kPinPiece is a power of two well under the failing size; the cost is one buffer object per
+ * piece per card, a few dozen for the largest pools. */
 constexpr int64_t kPinPiece = (int64_t)1 << 30;
 
 /* The NUMA node sysfs reports for the current card, -1 when it reports none. */
@@ -3072,10 +3109,9 @@ int current_card_numa_node() {
     return node;
 }
 
-/* MPOL_PREFERRED | MPOL_F_STATIC_NODES, the policy ROCr's own host allocations take. A refusal (a
- * seccomp profile that blocks mbind, a node with no memory) leaves the pages on whichever node
- * first touches them, which is a placement cost and not a correctness one: said once, then the
- * lock goes ahead. */
+/* MPOL_PREFERRED | MPOL_F_STATIC_NODES, the policy ROCr's host allocations use. On refusal (seccomp
+ * blocking mbind, a node without memory) pages land on the first-touching node, a placement cost
+ * only: warn once and continue. */
 void prefer_numa_node(void* p, int64_t len, int node) {
     constexpr int kMaxNodes = 1024;
     constexpr int kBits = 8 * (int)sizeof(unsigned long);
@@ -3093,9 +3129,9 @@ void prefer_numa_node(void* p, int64_t len, int node) {
                  std::strerror(errno));
 }
 
-/* TRANSPARENT HUGE PAGES TURNED OFF leave every pinned range at 4 KiB pages whatever it advises:
- * said once, because on a host whose IOMMU translates the cards' reads that is a slower stream
- * from the host pool and nothing else on the log points at it. */
+/* With transparent huge pages off, pinned ranges get 4 KiB pages whatever they advise. Warned
+ * once, because under IOMMU translation that slows streaming from the host pool and nothing else
+ * in the log would explain it. */
 void warn_if_no_huge_pages() {
     static std::atomic said{false};
     if (said.exchange(true)) return;
@@ -3113,7 +3149,7 @@ const char* hsa_why(hsa_status_t st) {
     return hsa_status_string(st, &m) == HSA_STATUS_SUCCESS && m ? m : "unknown HSA status";
 }
 
-/* Whether every card's driver offers the SVM API, so that a locked piece is mapped in place. */
+/* Whether the driver offers the SVM API, so a locked piece is mapped in place. */
 bool svm_in_place() {
     static const bool on = [] {
         bool svm = false;
@@ -3129,9 +3165,8 @@ bool svm_in_place() {
     return on;
 }
 
-/* The range as one allocation of the host pool, for a driver without the SVM API. The pool
- * aligns only a buffer's end to 2 MiB, so one alignment more is asked for and the base rounded
- * up inside it. */
+/* The range as one host-pool allocation, for a driver without the SVM API. The pool aligns only
+ * a buffer's end to 2 MiB, so one extra alignment is requested and the base rounded up within it. */
 void* pin_whole(int64_t bytes, const std::vector& cards) {
     const int64_t align = RAD_ALIGN_POOL;
     const int64_t len = align_up(bytes, 4096);
@@ -3165,8 +3200,8 @@ void* pin_pieces(int64_t bytes) {
 
     const int64_t align = RAD_ALIGN_POOL;
     const int64_t len = align_up(bytes, 4096);
-    /* One alignment over, trimmed at both ends, so the range starts on a 2 MiB boundary: a pool's
-     * fixed-stride slots inherit its base alignment, and a huge page needs it. */
+    /* Map one alignment extra and trim both ends so the range starts on a 2 MiB boundary: a
+     * pool's fixed-stride slots inherit its base alignment, and huge pages need it. */
     void* m = ::mmap(nullptr, (size_t)(len + align), PROT_READ | PROT_WRITE,
                      MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
     if (m == MAP_FAILED) {
@@ -3251,10 +3286,10 @@ void unpin_pieces(void* p) {
 
 bool pinned_kind(int kind) { return kind == RAD_MEM_HOST_PINNED || kind == RAD_MEM_HOST_MAPPED; }
 
-/* HIP's own allocation calls for device and pageable memory; the pinned kinds are the pieces. The
- * two pinned kinds are one thing here: RAD_MEM_HOST_PINNED (the mover's staging and the O_DIRECT
- * landing zone, spec §5.4) and RAD_MEM_HOST_MAPPED (the zero-copy execution site, row three of
- * spec §5.1's table) are both a locked range every card addresses at its host address. */
+/* Device and pageable memory come from HIP's allocation calls; the pinned kinds are locked in
+ * pieces. RAD_MEM_HOST_PINNED (mover staging and the O_DIRECT landing zone, spec §5.4) and
+ * RAD_MEM_HOST_MAPPED (the zero-copy execution site, spec §5.1) are the same thing here: a locked
+ * range every card addresses at its host address. */
 void* (*g_hip_alloc)(int64_t, int) = nullptr;
 void* a_alloc(int64_t bytes, int kind) {
     if (kind == RAD_MEM_DEVICE && bytes > 0) {
@@ -3276,7 +3311,7 @@ void* a_alloc(int64_t bytes, int kind) {
     return p;
 }
 
-/* Behind the forgetting every free needs (locate's cache). */
+/* Every free invalidates locate()'s cache first. */
 void (*g_hip_free)(void*, int) = nullptr;
 void a_free(void* p, int kind) {
     loc_forget();
@@ -3286,7 +3321,7 @@ void a_free(void* p, int kind) {
     else if (g_hip_free) g_hip_free(p, kind);
 }
 
-/* A pinned range is the same address on both sides, inner addresses included. */
+/* A pinned range has the same address on host and device, interior addresses included. */
 void* (*g_hip_host_ptr)(void*) = nullptr;
 void* (*g_hip_device_ptr)(void*) = nullptr;
 void* a_host_ptr(void* p) { return pinned_range(p, nullptr, nullptr) ? p : g_hip_host_ptr(p); }
@@ -3300,10 +3335,9 @@ size_t a_code_mark(void) {
     return r.order.size();
 }
 
-/* Whether every fat binary registered in [from, to) holds a code object `device` runs -- the
- * same choice the first launch out of each will make (module_meta), made now, while a library
- * that carries nothing for this card can still be left out of selection rather than chosen and
- * failed at its first launch. */
+/* Whether every fat binary registered in [from, to) has a code object `device` runs. Makes the
+ * same choice as the first launch (module_meta), early enough that a library with nothing for
+ * this card is left out of selection instead of failing at its first launch. */
 int a_code_runs(size_t from, size_t to, int device, char* why, int cap) {
     if (device < 0 || (size_t)device >= G().dev.size()) return RAD_E_INVAL;
     const std::vector& isas = G().dev[(size_t)device].isas;
@@ -3335,10 +3369,9 @@ const DeviceBackend* aql_backend_if_present(void) {
     static const DeviceBackend* b = []() -> const DeviceBackend* {
         const DeviceBackend* hip = hip_backend_if_present();
         if (!hip) return nullptr;
-        /* THE INTERPOSITION HAS TO BE LIVE, or every plugin launch would hand HIP a queue it has
-         * never heard of. It is live when this executable exports hipLaunchKernel, which every
-         * target linking the core does (core/CMakeLists.txt); a binary that does not is a build
-         * error, reported as one rather than run on the other backend. */
+        /* The interposition must be live, or plugin launches would hand HIP queues it does not
+         * know. It is live when this executable exports hipLaunchKernel, as every target linking
+         * the core does (core/CMakeLists.txt); otherwise it is a build error, reported as such. */
         void* bound = dlsym(RTLD_DEFAULT, "hipLaunchKernel");
         if (bound != reinterpret_cast(&::hipLaunchKernel)) {
             RAD_ERR("device: this executable does not export hipLaunchKernel, so kernel plugins "
@@ -3407,6 +3440,9 @@ const DeviceBackend* aql_backend_if_present(void) {
         g_aql.code_runs = a_code_runs;
         g_aql.tape_set_overlap = a_tape_set_overlap;
         g_aql.tape_destroy = a_tape_destroy;
+        g_aql.stream_gate = a_stream_gate;
+        g_aql.gate_open = a_gate_open;
+        g_aql.gate_room = a_gate_room;
         return &g_aql;
     }();
     return b;
@@ -3425,8 +3461,8 @@ int aql_vmem_device_of(const void* addr, int* dev) {
 
 /* ================================================================== the HIP entry points
  *
- * Defined in the executable, so the dynamic linker binds a plugin's references here ahead of the
- * HIP runtime's. Each forwards anything that is not this backend's to HIP. */
+ * Defined in the executable, so the dynamic linker binds plugin references here ahead of the HIP
+ * runtime. Each forwards anything not on this backend's streams to HIP. */
 
 using namespace rad::aql;
 
@@ -3440,9 +3476,8 @@ void** __hipRegisterFatBinary(const void* data) {
     if (w && w->binary) {
         Registry& r = reg();
         std::lock_guard lk(r.mu);
-        /* HIP hands back no handle for a fat binary with nothing for any visible device. It is
-         * still counted, under a record nothing can launch from, because that is exactly the
-         * plugin the loader's check exists to catch. */
+        /* HIP returns no handle for a fat binary with nothing for any visible device. It is still
+         * recorded (unlaunchable) so the plugin loader's check (a_code_runs) can catch it. */
         if (!h) {
             Module* m = new Module();
             m->bundle = w->binary;
@@ -3450,10 +3485,10 @@ void** __hipRegisterFatBinary(const void* data) {
             return h;
         }
         Module*& m = r.by_handle[h];
-        /* A handle HIP hands out again after a plugin was unloaded -- the loader closes one it
-         * refuses -- names a new fat binary, and the old record's parsed code object points into a
-         * mapping that is gone. Records are never freed (see __hipUnregisterFatBinary), so the old
-         * one is simply left behind. */
+        /* HIP may reuse a handle after a plugin is unloaded (the loader closes refused ones); it
+         * then names a new fat binary, and the old record's code object points into an unmapped
+         * image. Records are never freed (see __hipUnregisterFatBinary), so the old one is
+         * abandoned. */
         if (!m || m->bundle != w->binary) m = new Module();
         m->bundle = w->binary;
         r.order.push_back(m);
@@ -3478,8 +3513,8 @@ void __hipRegisterFunction(void** modules, const void* host_fn, char* device_fn,
 }
 
 void __hipUnregisterFatBinary(void** modules) {
-    /* The module's executables stay loaded: a process that unloads a kernel plugin is exiting,
-     * and the records above are what a late launch would otherwise dereference. */
+    /* The module's executables and records stay: a process unloading a kernel plugin is exiting,
+     * and a late launch would dereference them. */
     if (real().unreg_fat) real().unreg_fat(modules);
 }
 
@@ -3531,18 +3566,15 @@ hipError_t hipMemsetAsync(void* dst, int value, size_t bytes, hipStream_t st) {
                                                                               : hipSuccess);
 }
 
-/* A SYNCHRONOUS FILL, ON ONE OF THE BACKEND'S OWN QUEUES FOR THE CURRENT DEVICE. Kernel libraries
- * zero their small private blocks this way -- an all-reduce's flags at init, a split-K GEMM's
- * arrival counters on first use -- and HIP would serve each by building its default stream's
- * queues on that card. Those are hardware queues this process never otherwise uses, and a card
- * whose compute work is spread over more queues than it runs at once time-slices them: every
- * kernel on the busy ones then pays a switch, and the two lanes of a rank stop overlapping.
+/* A synchronous fill on one of the backend's own queues for the current device. Kernel libraries
+ * zero small private blocks this way (an all-reduce's flags at init, a split-K GEMM's arrival
+ * counters on first use), and HIP would create its default-stream queues on the card to serve
+ * them: extra hardware queues that make the card time-slice, so every kernel pays a switch and a
+ * rank's two lanes stop overlapping.
  *
- * The fill goes on the first queue this process made on the device, which is the compute stream of
- * the rank that owns it, and is waited for there. A device with no queue yet -- a peer's buffers
- * set up before its rank has started -- gets one for the fill and loses it again, so no queue
- * outlives the call. It is never part of a recorded pass: it runs once for a block that is then
- * kept. */
+ * The fill runs on the first queue this process made on the device (the owning rank's compute
+ * stream) and is waited for. A device with no queue yet (a peer's buffers set up before its rank
+ * starts) gets a temporary one for the call. Never recorded into a tape: it runs once. */
 hipError_t hipMemset(void* dst, int value, size_t bytes) {
     if (!G().ok) return real().memset_sync ? real().memset_sync(dst, value, bytes) : hipErrorNotSupported;
     int dev = -1;
@@ -3572,9 +3604,8 @@ hipError_t hipStreamSynchronize(hipStream_t st) {
     return ret(rad_stream_sync((RadStream)st) < 0 ? hipErrorLaunchFailure : hipSuccess);
 }
 
-/* The two stream APIs a plugin could plausibly reach for that have no meaning on a queue of this
- * backend: events are the engine's, through rad_event_*. Refused by name rather than handed to
- * HIP, which would dereference the queue as one of its own streams. */
+/* HIP events have no meaning on this backend's queues (events go through rad_event_*). Refused
+ * instead of forwarded, since HIP would dereference the queue as one of its own streams. */
 hipError_t hipEventRecord(hipEvent_t e, hipStream_t st) {
     if (!ours(st)) return real().ev_record ? real().ev_record(e, st) : hipErrorNotSupported;
     RAD_ERR("hipEventRecord on an engine stream: use rad_event_record");
@@ -3592,8 +3623,8 @@ hipError_t hipGetLastError(void) {
         const hipError_t e = t_err;
         t_ours = false;
         t_err = hipSuccess;
-        /* HIP's own slot holds whatever came before this backend's call, which that call
-         * overwrote. */
+        /* Clear HIP's own slot: it holds an error from before this backend's call, which that
+         * call superseded. */
         if (real().last) (void)real().last();
         return e;
     }
diff --git a/core/device/aql.h b/core/device/aql.h
index cdb56126..7e3b9228 100644
--- a/core/device/aql.h
+++ b/core/device/aql.h
@@ -1,9 +1,8 @@
-/* aql.h -- what the AQL backend's translation units share.
+/* aql.h -- declarations shared by the AQL backend's translation units.
  *
- * Three files: aql_code.cpp reads code objects (the offload bundle, the ELF note, the msgpack
- * metadata inside it), aql.cpp owns the queues and everything submitted to them, and
- * aql_blit.hip holds the copy and fill kernels the backend dispatches for itself. The last one is
- * compiled as HIP, so nothing in this header may pull in HSA or anything HIP would object to.
+ * aql_code.cpp reads code objects (offload bundle, ELF note, msgpack metadata), aql.cpp owns the
+ * queues and all submission, and aql_blit.hip holds the backend's own copy and fill kernels.
+ * aql_blit.hip is compiled as HIP, so this header must not pull in HSA.
  */
 #pragma once
 
@@ -17,9 +16,9 @@ namespace aql {
 
 /* ------------------------------------------------------------------ code objects */
 
-/* One kernel argument as the code object's metadata lays it out. `hidden` names the implicit
- * arguments the compiler appends after the declared ones; every other kind is an explicit
- * parameter, and those map one to one, in order, onto hipLaunchKernel's `kernelParams`. */
+/* One kernel argument as laid out in the code object's metadata. `hidden` names the implicit
+ * arguments the compiler appends; explicit parameters map in order onto hipLaunchKernel's
+ * `kernelParams`. */
 enum class Hidden : uint8_t {
     None,           /* an explicit parameter */
     Pad,            /* hidden_none: bytes the compiler reserved and reads nothing from */
@@ -48,13 +47,12 @@ struct KernelMeta {
     std::vector args;
 };
 
-/* The code object a card runs, out of a clang offload bundle, or an empty span with `*why` naming
- * what the bundle holds and what the card accepts. `isas` is the card's own list of the targets it
- * accepts, in the runtime's order of preference: "amdgcn-amd-amdhsa--gfx1036", then the family's
- * "amdgcn-amd-amdhsa--gfx10-3-generic", each carrying the modes the card runs in
- * ("gfx942:sramecc+:xnack-"). The bundle carries no total length, so it is read entry by entry from
- * its own header; a compressed bundle is refused rather than decompressed, because nothing in this
- * tree builds one. */
+/* Selects the card's code object from a clang offload bundle, or fails with `*why` naming what
+ * the bundle holds and what the card accepts. `isas` lists the card's accepted targets in the
+ * runtime's order of preference ("amdgcn-amd-amdhsa--gfx1036", then the family's
+ * "amdgcn-amd-amdhsa--gfx10-3-generic"), each with its modes ("gfx942:sramecc+:xnack-"). The
+ * bundle has no total length, so it is walked entry by entry. Compressed bundles are refused;
+ * nothing in this tree builds one. */
 bool bundle_code_object(const void* bundle, const std::vector& isas, const void** out,
                         size_t* out_size, std::string* why);
 
@@ -64,8 +62,8 @@ bool code_object_kernels(const void* elf, size_t size, std::vector*
 
 /* ------------------------------------------------------------------ fence policy
  *
- * What the next dispatch on this thread has to be fenced at, beyond the agent scope every kernel
- * gets. Set by the backend around its own blits and cleared by the dispatch that consumes it. */
+ * Extra fence scope for the next dispatch on this thread, beyond the agent scope every kernel
+ * gets. Set by the backend around its own blits; cleared by the dispatch that consumes it. */
 enum : uint8_t { kFenceAcquireSystem = 1, kFenceReleaseSystem = 2 };
 void set_next_fence(uint8_t f);
 
@@ -74,17 +72,17 @@ void set_next_fence(uint8_t f);
 
 struct RadCopyRange;
 
-/* The blit kernels' launchers, defined in aql_blit.hip. Each issues exactly one kernel onto
- * `stream` through hipLaunchKernel, which the backend intercepts. Alignment is the caller's: the
- * 16-byte forms need both addresses and the length 16-byte aligned. */
+/* Blit kernel launchers, defined in aql_blit.hip. Each issues one kernel onto `stream` through
+ * hipLaunchKernel, which the backend intercepts. The caller guarantees alignment: the 16-byte
+ * forms need both addresses and the length 16-byte aligned. */
 extern "C" {
-/* `link` when either side is across the link (pinned host memory): one narrow workgroup instead
- * of a grid that fills the card; aql_blit.hip says why. */
+/* `link`: either side is pinned host memory, so use one narrow workgroup instead of a full grid
+ * (see aql_blit.hip). */
 int rad_aql_blit_copy(void* dst, const void* src, uint64_t bytes, void* stream, bool link = false);
 int rad_aql_blit_copy2d(void* dst, uint64_t dpitch, const void* src, uint64_t spitch,
                         uint64_t width, uint64_t height, void* stream);
 int rad_aql_blit_fill(void* dst, int value, uint64_t bytes, void* stream);
-/* rad_memcpy_ranges_async's kernel: `prefix` a multiple of sixteen and both bases 16-aligned. */
+/* rad_memcpy_ranges_async's kernel: `prefix` a multiple of 16, both bases 16-byte aligned. */
 int rad_aql_blit_ranges(void* dst, const void* src, uint64_t prefix, const RadCopyRange* ranges,
                         int n, void* stream);
 }
diff --git a/core/device/aql_blit.hip b/core/device/aql_blit.hip
index 24bfdc01..e09bf4d6 100644
--- a/core/device/aql_blit.hip
+++ b/core/device/aql_blit.hip
@@ -1,14 +1,13 @@
-/* aql_blit.hip -- the copy and fill kernels the AQL backend dispatches for rad_memcpy_async,
- * rad_memcpy_2d_async and rad_memset_async.
+/* aql_blit.hip -- copy and fill kernels behind rad_memcpy_async, rad_memcpy_2d_async and
+ * rad_memset_async on the AQL backend.
  *
- * A copy on this backend is a kernel on the stream's own queue, the same as HIP's blit path: the
- * alternative is the DMA engine, which is a second queue to order against with signals and costs
- * more in latency than a small copy takes to run. Every address these kernels see is one the GPU
- * can reach directly -- device memory, a peer's, or pinned host memory; pageable host memory is
- * staged by the caller.
+ * A copy is a kernel on the stream's own queue, like HIP's blit path. The DMA engine would be a
+ * second queue to order against with signals, and its latency exceeds a small copy's run time.
+ * Every address is GPU-reachable (device, peer or pinned host memory); the caller stages
+ * pageable host memory.
  *
- * The launchers go through hipLaunchKernel like any plugin's, and the backend intercepts that, so
- * these kernels are dispatched exactly as a kernel library's are.
+ * The launchers go through hipLaunchKernel, which the backend intercepts, so these kernels are
+ * dispatched like any kernel library's.
  */
 #include 
 
@@ -24,8 +23,8 @@ constexpr uint64_t kMaxBlocks = 2048;
 
 typedef unsigned u32x4 __attribute__((ext_vector_type(4)));
 
-/* Four loads in flight a thread before the first store: a copy that reads pinned host memory is
- * link-latency bound, and one outstanding load a thread leaves most of the link idle. */
+/* Four loads in flight per thread before the first store: a copy from pinned host memory is
+ * link-latency bound, and one outstanding load per thread leaves most of the link idle. */
 __global__ __launch_bounds__(kThreads) void aql_copy16(const u32x4* __restrict__ src,
                                                        u32x4* __restrict__ dst, uint64_t n) {
     const uint64_t stride = (uint64_t)gridDim.x * kThreads;
@@ -37,15 +36,12 @@ __global__ __launch_bounds__(kThreads) void aql_copy16(const u32x4* __restrict__
     for (; i < n; i += stride) dst[i] = src[i];
 }
 
-/* A COPY THAT READS OR WRITES ACROSS THE LINK IS ONE WORKGROUP OF FOUR WAVES.
+/* A copy across the link (pinned host memory) is one workgroup of four waves.
  *
- * The link delivers ~29 GB/s whatever the grid, so the only question is how few waves reach that,
- * because every wave a copy holds is one the compute queue's kernels do not get while the copy
- * crawls along at link speed. A wide link copy -- 16 workgroups of 256 threads, 128 waves -- costs
- * a prefill whose stager keeps a copy running beside every layer ~15%: hc_read at a 2048-row chunk
- * takes 1154 us a call with such copies running and 609 without, because its down product is
- * exactly one wave of workgroups on the part and any slot a copy holds pushes some of it into a
- * second. Link bandwidth by grid, one card, 89 MB from pinned host memory:
+ * The link delivers ~29 GB/s regardless of grid size, so the copy should hold as few waves as
+ * possible: every wave it holds is denied to compute kernels for the copy's duration (a wide link
+ * copy beside each layer slows a staged prefill by ~15%). Link bandwidth by grid, one card,
+ * 89 MB from pinned host memory:
  *
  *     16 x 256 threads, 4 loads in flight    28.9 GB/s
  *      1 x 256 threads, 16 in flight         28.9
@@ -54,11 +50,10 @@ __global__ __launch_bounds__(kThreads) void aql_copy16(const u32x4* __restrict__
  *      1 x  64 threads,  8 in flight         10.4
  *
  * 32 KiB in flight is several times the link's bandwidth-delay product; fewer threads leave the
- * link idle, and 32 loads a thread spill. Non-temporal loads and stores change nothing: it is the
- * slots, not the caches.
+ * link idle and 32 loads per thread spill. Non-temporal loads and stores make no difference.
  *
- * The last round loads clamped rather than guarded, so its loads are all in flight at once: a
- * guarded load waits for the one before it. */
+ * The last round clamps its load indices instead of guarding them, so all its loads are in flight
+ * at once; a guarded load waits for the one before it. */
 constexpr int kLinkThreads = 128, kLinkDepth = 16;
 constexpr uint64_t kLinkByteBlocks = 16;
 
@@ -119,11 +114,11 @@ __global__ __launch_bounds__(kThreads) void aql_copy2d1(const unsigned char* __r
     }
 }
 
-/* A RANGED COPY: the first `prefix_blocks` workgroups move the prefix as aql_copy16 does, and each
- * workgroup after them one range. A range is four-byte aligned only, so it moves in words, sixteen
- * a thread a round: every load of a round is issued before its first store, since each is a read
- * across the link, and the loads past the range's end read its last word rather than branch
- * around the load -- a guarded load waits for the one before it. */
+/* Ranged copy: the first `prefix_blocks` workgroups copy the prefix as aql_copy16 does, and each
+ * later workgroup copies one range. Ranges are only 4-byte aligned, so they move in words, 16 per
+ * thread per round, with all loads issued before the first store (each is a read across the
+ * link). Loads past the range end clamp to its last word instead of branching, since a guarded
+ * load waits for the one before it. */
 constexpr int kRangeWords = 16;
 
 __global__ __launch_bounds__(kThreads) void aql_copy_ranges(const u32x4* __restrict__ src16,
@@ -199,8 +194,8 @@ extern "C" int rad_aql_blit_copy(void* dst, const void* src, uint64_t bytes, voi
             hipLaunchKernelGGL(aql_copy16, dim3(blocks_for(n, 4 * kThreads)), dim3(kThreads), 0,
                                s, (const u32x4*)src, (u32x4*)dst, n);
     } else {
-        /* Unaligned: byte copies, one byte a thread in flight, so across the link they take
-         * sixteen workgroups rather than the one narrow workgroup of the aligned path. */
+        /* Unaligned: byte copies have one byte per thread in flight, so across the link they
+         * use 16 workgroups instead of the aligned path's one. */
         const uint64_t cap = link ? kLinkByteBlocks : kMaxBlocks;
         hipLaunchKernelGGL(aql_copy1, dim3(blocks_for(bytes, 4 * kThreads, cap)), dim3(kThreads),
                            0, s, (const unsigned char*)src, (unsigned char*)dst, bytes);
diff --git a/core/device/aql_code.cpp b/core/device/aql_code.cpp
index 9ef8bcd1..ddb429d7 100644
--- a/core/device/aql_code.cpp
+++ b/core/device/aql_code.cpp
@@ -1,10 +1,9 @@
-/* aql_code.cpp -- reading AMDGPU code objects: the offload bundle a HIP fat binary is, the ELF
- * inside it, and the msgpack metadata note that says where each kernel's arguments go.
+/* aql_code.cpp -- reads AMDGPU code objects: the offload bundle of a HIP fat binary, the ELF
+ * inside it, and the msgpack metadata note that gives each kernel's argument layout.
  *
- * The AQL backend dispatches kernels HIP compiled and registered, so it needs two things HIP keeps
- * to itself: the code object for this card, to load into an executable of its own, and each
- * kernel's argument layout, to write a kernarg segment without HIP's help. Both are in the fat
- * binary the compiler embedded, and this file reads them.
+ * The AQL backend dispatches HIP-registered kernels itself, so it needs two things HIP does not
+ * expose: the card's code object, to load into its own executable, and each kernel's argument
+ * layout, to write kernarg segments. Both come from the embedded fat binary.
  *
  * Nothing here touches a device, so it builds and is tested without one.
  */
@@ -21,10 +20,9 @@ namespace {
 
 const char kHsaPrefix[] = "amdgcn-amd-amdhsa--";
 
-/* A target ID as LLVM writes it after the triple: a processor and any number of target features,
- * each `name+` or `name-` ("gfx942:sramecc+:xnack-"). A feature left out of a code object's ID
- * means the code object runs in either mode; one left out of a card's ID means the card has no
- * such mode. */
+/* A target ID as LLVM writes it after the triple: a processor and target features, each `name+`
+ * or `name-` ("gfx942:sramecc+:xnack-"). A feature absent from a code object's ID means it runs in
+ * either mode; absent from a card's ID, the card has no such mode. */
 struct TargetId {
     std::string proc;
     std::vector> feat;
@@ -44,18 +42,22 @@ TargetId parse_target_id(const std::string& s) {
     return t;
 }
 
-/* The target ID out of an ISA name ("amdgcn-amd-amdhsa--gfx1036") or a bundle entry's triple
- * ("hipv4-amdgcn-amd-amdhsa--gfx1036"); empty for anything that is not an AMDGPU HSA target, such
- * as the bundle's host entry. */
+/* The target ID from an ISA name ("amdgcn-amd-amdhsa--gfx1036") or a bundle entry's triple
+ * ("hipv4-amdgcn-amd-amdhsa--gfx1036"); empty for non-AMDGPU targets such as the host entry. */
 std::string target_id_of(const std::string& name) {
     const size_t at = name.find(kHsaPrefix);
     if (at == std::string::npos) return std::string();
     return name.substr(at + sizeof kHsaPrefix - 1);
 }
 
-/* -1 when a code object built for `co` cannot run on a card that accepts `card`; otherwise how
- * many target features the code object pins, so that one built for the card's exact mode is
- * preferred to one built for either mode. */
+/* An ISA name's target ID, or the name itself when it carries no HSA prefix. */
+std::string isa_target(const std::string& isa) {
+    const std::string id = target_id_of(isa);
+    return id.empty() ? isa : id;
+}
+
+/* -1 if a code object for `co` cannot run on a card accepting `card`; otherwise the number of
+ * features the code object pins, so one built for the card's exact mode is preferred. */
 int target_fit(const TargetId& co, const TargetId& card) {
     if (co.proc != card.proc) return -1;
     for (const auto& f : co.feat) {
@@ -77,7 +79,7 @@ bool bundle_code_object(const void* bundle, const std::vector& isas
     *out_size = 0;
     if (!b) { *why = "null bundle"; return false; }
     if (std::memcmp(b, "CCOB", 4) == 0) {
-        *why = "the fat binary is a COMPRESSED offload bundle; build the kernel library without "
+        *why = "the fat binary is a compressed offload bundle; build the kernel library without "
                "--offload-compress";
         return false;
     }
@@ -89,8 +91,8 @@ bool bundle_code_object(const void* bundle, const std::vector& isas
     std::memcpy(&n, b + 24, 8);
     if (n == 0 || n > 4096) { *why = "offload bundle with an implausible entry count"; return false; }
 
-    /* Every device entry, as "-amdgcn-amd-amdhsa--". Both kinds HIP has used,
-     * "hip" and "hipv4", carry the same code object format for this purpose. */
+    /* Device entries are "-amdgcn-amd-amdhsa--"; both kinds, "hip" and "hipv4",
+     * carry the same code object format for this purpose. */
     struct Entry { uint64_t off, size; TargetId id; std::string text; };
     std::vector ents;
     const unsigned char* p = b + 32;
@@ -107,13 +109,11 @@ bool bundle_code_object(const void* bundle, const std::vector& isas
         ents.push_back({ off, size, parse_target_id(id), id });
     }
 
-    /* THE CARD'S LIST DECIDES, IN THE CARD'S ORDER. The runtime reports the processor itself
-     * first and then the generic target of its family ("gfx1036", then "gfx10-3-generic"), each
-     * with the modes the card runs in. So a library built for the exact chip is used where it
-     * exists, and one built once for a family runs on every member of it. Within one accepted
-     * target, a code object pinned to the card's mode beats one built for either mode. */
+    /* Walk the card's ISA list in its own order: the exact processor first, then its family's
+     * generic target. An exact-chip build wins where present; a family build runs on every
+     * member. Within one target, a code object pinned to the card's mode wins. */
     for (const std::string& isa : isas) {
-        const TargetId card = parse_target_id(target_id_of(isa).empty() ? isa : target_id_of(isa));
+        const TargetId card = parse_target_id(isa_target(isa));
         const Entry* best = nullptr;
         int best_fit = -1;
         for (const Entry& e : ents) {
@@ -130,7 +130,7 @@ bool bundle_code_object(const void* bundle, const std::vector& isas
     std::string have, want;
     for (const Entry& e : ents) have += (have.empty() ? "" : ", ") + e.text;
     for (const std::string& isa : isas)
-        want += (want.empty() ? "" : ", ") + (target_id_of(isa).empty() ? isa : target_id_of(isa));
+        want += (want.empty() ? "" : ", ") + isa_target(isa);
     *why = "the fat binary has code objects for [" + (have.empty() ? std::string("none") : have) +
            "] and this card runs [" + want + "]";
     return false;
@@ -138,9 +138,9 @@ bool bundle_code_object(const void* bundle, const std::vector& isas
 
 /* ------------------------------------------------------------------ msgpack
  *
- * The subset a code object's metadata uses: maps, arrays, strings, integers, booleans and nil.
- * A DOM, because the metadata is walked by key and is a few hundred kilobytes at most, read once
- * per module at the first dispatch into it. */
+ * The subset code object metadata uses: maps, arrays, strings, integers, booleans and nil. Parsed
+ * into a DOM: the metadata is looked up by key, is a few hundred KB at most, and is read once per
+ * module at its first dispatch. */
 namespace {
 
 struct MP {
diff --git a/core/device/device.h b/core/device/device.h
index 409debe2..f5f8b78a 100644
--- a/core/device/device.h
+++ b/core/device/device.h
@@ -1,16 +1,12 @@
-/* device.h -- the device layer's internal face.
+/* device.h -- the device layer's internal interface.
  *
- * `abi/rad_device.h` is what the rest of the engine and every plugin calls. This header is
- * the seam between the two implementations of it, plus the two questions the rest of the core
- * actually needs to ask about which one won.
+ * `abi/rad_device.h` is what the engine and plugins call. This header is the seam between its
+ * backend implementations, plus queries for which backend is active.
  *
- * The seam is a vtable rather than an `#ifdef` at every call site. That is a deliberate trade: an
- * indirect call costs a load and a jump, which is unmeasurable against a `hipMemcpyAsync` and
- * unmeasurable against a `memcpy` of anything worth enqueuing, and in exchange there is exactly one
- * definition of each `rad_dev_*` symbol and no way for the two backends to drift into implementing
- * different contracts. Two device layers that have silently diverged is the failure this avoids,
- * and it is the failure that matters, because the host backend is where everything above the
- * kernels is developed (docs/IMPLEMENTATION.md) and the HIP backend is where it has to still work.
+ * The seam is a vtable, not an `#ifdef` per call site. The indirect call is unmeasurable next to
+ * any copy worth enqueuing, and in exchange each `rad_dev_*` symbol has one definition, so the
+ * backends cannot drift into different contracts. That matters because the host backend is where
+ * everything above the kernels is developed (docs/IMPLEMENTATION.md).
  */
 #pragma once
 #include "rad_abi.h"
@@ -21,105 +17,95 @@
 #include 
 #include 
 
-/* AN EVENT THAT ONLY ORDERS WORK ON ONE CARD. Its record makes the recording stream's writes
- * visible to the rest of that card and to nothing else, so it may be waited on by another stream
- * of the same card and queried or synchronised by the host for WHEN, but the host must not read
- * device-written memory on the strength of it, and no other card may wait on it. What that buys
- * is the release: making writes visible to the system waits for every write still in flight to
- * host memory, and with the link busy streaming weights that is most of a microsecond at best and
- * over ten at worst on every record, where the card-wide release costs the packet alone. */
+/* An event that orders work on one card only. Its record makes the stream's writes visible to
+ * that card and nothing else: another stream of the same card may wait on it and the host may
+ * query or sync it for timing, but the host must not read device-written memory on its strength
+ * and no other card may wait on it. The gain is the cheaper release: a system-scope release waits
+ * for every in-flight write to host memory, ~1-10 us per record while the link streams weights. */
 extern "C" int rad_event_create_local(RadEvent* out);
-/* WHAT AN EVENT IS FOR, fixed when it is made. RAD_EVENT_LOCAL is rad_event_create_local's scope.
- * RAD_EVENT_HOST_WAIT is an event the host synchronises on: its records complete with an interrupt
- * the waiting thread blocks on, where the other kind complete silently and can only be waited on by
- * a stream. rad_event_create is RAD_EVENT_HOST_WAIT, rad_event_create_local is RAD_EVENT_LOCAL
- * alone, and rad_event_sync refuses an event made without RAD_EVENT_HOST_WAIT. */
+/* Event purpose, fixed at creation. RAD_EVENT_LOCAL is rad_event_create_local's scope.
+ * RAD_EVENT_HOST_WAIT records complete with an interrupt a host thread can block on; without it
+ * records complete silently and only a stream can wait on them. rad_event_create is
+ * RAD_EVENT_HOST_WAIT, rad_event_create_local is RAD_EVENT_LOCAL alone, and rad_event_sync refuses
+ * an event made without RAD_EVENT_HOST_WAIT. */
 enum : unsigned {
     RAD_EVENT_LOCAL     = 1u,
     RAD_EVENT_HOST_WAIT = 2u,
 };
 extern "C" int rad_event_create_as(RadEvent* out, unsigned flags);
-/* The host has just written memory a kernel issued after this call reads, and no host wait came
- * between: a host-site op's output, read over the link by the device op after it. */
+/* The host has just written memory that a kernel issued after this call reads, with no host wait
+ * in between (e.g. a host-site op's output read over the link by the next device op). */
 extern "C" void rad_dev_host_wrote(void);
 
-/* ONE RANGE OF A RANGED COPY: `bytes` from byte `src` of the source to byte `dst` of the
- * destination, all three multiples of four. */
+/* One range of a ranged copy: `bytes` from source offset `src` to destination offset `dst`, all
+ * three multiples of four. */
 struct RadCopyRange {
     int64_t src;
     int64_t dst;
     int64_t bytes;
 };
-/* A FIXED PREFIX AND A LIST OF RANGES, IN ONE DISPATCH: src[0, prefix) to dst[0, prefix) -- a
- * multiple of sixteen, and it may be zero -- and then every range. The copy reads `ranges` when it
- * runs, so the list lives in memory the device reaches (pinned host memory beside `src`) and stays
- * as written until the stream has passed the copy, like `src` itself. One workgroup copies one
- * range, so a caller cuts a long run into ranges of a few kilobytes. */
+/* Copies src[0, prefix) to dst[0, prefix) (a multiple of 16, possibly zero), then every range,
+ * in one dispatch. The kernel reads `ranges` when it runs, so the list must be device-reachable
+ * (pinned host memory beside `src`) and stay unchanged until the stream passes the copy. One
+ * workgroup copies one range, so callers cut long runs into ranges of a few KB. */
 extern "C" int rad_memcpy_ranges_async(void* dst, const void* src, int64_t prefix,
                                        const RadCopyRange* ranges, int n, RadStream s);
 
-/* ONE COPY OF A LIST: `bytes` from `src` to `dst`, both absolute addresses. */
+/* One copy of a list: `bytes` from `src` to `dst`, both absolute addresses. */
 struct RadCopySeg {
     const void* src;
     void*       dst;
     int64_t     bytes;
 };
-/* MANY UNRELATED COPIES, IN LIST ORDER ON THE STREAM, on the card's DMA engine where the backend
- * has one. The list is read at the call, so it need not outlive it; the bytes it names do, like
- * any copy's. A backend without a DMA engine copies the segments one by one, in order. An empty
- * list puts nothing on the stream, and readies what the backend's first list on that stream's card
- * would otherwise set up, so a caller can take that cost at bring-up.
+/* Many unrelated copies, in list order on the stream, on the card's DMA engine where the backend
+ * has one (otherwise segment by segment). The list itself is read at the call; the bytes it names
+ * must live until the copy runs. An empty list enqueues nothing but performs the card's first-list
+ * setup, so a caller can pay that cost at bring-up.
  *
- * It exists for bulk copies across the link while the card computes -- the prefill stager's,
- * a layer's pooled experts a call. A copy as a kernel holds a compute unit's slot for as long as
- * the link takes, and waits for one to free up at every launch: beside kernels that keep every unit
- * busy, 1.3 MB copies from pinned host memory ran at 2.3 GB/s as kernels and at 28.7 GB/s -- the
- * link -- on the DMA engine, which cost those kernels nothing (aql.cpp, "the DMA lane").
+ * For bulk link copies while the card computes (e.g. a layer's pooled experts in the prefill
+ * stager). A copy kernel holds a CU slot for the link's duration and waits for a free one at
+ * launch: beside busy kernels, 1.3 MB pinned-host copies run at 2.3 GB/s as kernels versus
+ * 28.7 GB/s (link rate) on the DMA engine, at no cost to the kernels (aql.cpp, "the DMA lane").
  *
- * RAD_COPY_YIELD makes the list give way to the card's collectives: it waits, between pieces of
- * about a megabyte, while a stream of that card holds the link (rad_link_hold). */
+ * RAD_COPY_YIELD makes the list yield to the card's collectives: between ~1 MB pieces it waits
+ * while a stream of that card holds the link (rad_link_hold). */
 #define RAD_COPY_YIELD 1u
 extern "C" int rad_memcpy_list_async(const RadCopySeg* segs, int n, unsigned flags, RadStream s);
 
-/* THE CARD'S LINK, HELD BY A STREAM FOR WHAT IT ISSUES BETWEEN TWO CALLS: `on` 1 at the point in
- * `s` where traffic the step waits on starts to cross the card's link -- a collective -- and 0
- * where it ends, or 2 where the work in between ended the hold itself (rad_link_gate). Lists issued
- * RAD_COPY_YIELD for that card stop between pieces while it is held. The holds of one card
- * alternate, on then off, in the order they are issued across all its streams: they never nest or
- * overlap. And the holding stream must not wait, between the two
- * calls, on anything behind a yielding list -- the list would wait for the hold to end, and the
- * hold for the list. A backend without a DMA engine holds nothing.
+/* Holds the card's link for the work `s` issues between two calls. `on` = 1 where step-critical
+ * link traffic (a collective) starts, 0 where it ends, or 2 where the work in between released the
+ * hold itself (rad_link_gate). RAD_COPY_YIELD lists for that card pause between pieces while held.
+ * A card's holds alternate on/off in issue order across all its streams; they never nest or
+ * overlap. Between the two calls the holding stream must not wait on anything behind a yielding
+ * list, or the list and the hold deadlock. A backend without a DMA engine holds nothing.
  *
- * WHY: a card's inbound link carries a collective's peer bytes and the stager's copies alike, and
- * the DMA engine takes its share at the link's full rate. A 4 MB all-reduce message that crosses in
- * 165 us on its own took 301 us beside a layer's copies, and the step waits on every one; the
- * copies have the rest of the layer to finish in. */
+ * Why: collective peer bytes and stager copies share the inbound link, and the DMA engine takes
+ * its share at full rate. A 4 MB all-reduce message takes 165 us alone and 301 us beside a layer's
+ * copies; the step waits on the collective, while the copies have the rest of the layer. */
 extern "C" int rad_link_hold(RadStream s, int on);
 
-/* THE WORD THE HOLD IS KEPT IN, for a launch that ends its own: a 64-bit word in memory every
- * engine and kernel of the card reaches, odd while the link is held. rad_link_hold(s, 2) after a
- * launch that was handed this address records that the launch released the hold itself, by taking
- * one off the word -- once, and only if it found it odd -- as soon as the bytes it waited for had
- * landed. Null where the backend holds nothing. */
+/* The hold word, for a launch that ends its own hold: a 64-bit word reachable by every engine and
+ * kernel of the card, odd while the link is held. A launch handed this address releases the hold
+ * by decrementing the word once, only if odd, as soon as its awaited bytes have landed; follow it
+ * with rad_link_hold(s, 2). Null where the backend holds nothing. */
 extern "C" void* rad_link_gate(RadStream s);
 
-/* THE EXPERT PREFETCH'S DEVICE HALF (core/runtime/xprefetch.cpp). A backend that cannot make a
- * dispatch complete a signal, or has no DMA engine to spare for it, leaves these out:
- * rad_xp_supported is then 0 and the prefetch is off.
+/* Device half of the expert prefetch (core/runtime/xprefetch.cpp). A backend that cannot have a
+ * dispatch complete a signal, or has no spare DMA engine, leaves these out; rad_xp_supported is
+ * then 0 and the prefetch is off.
  *
- * A RIDE is a signal the next dispatch issued on a stream completes -- that dispatch keeps its
- * ordering bit, so the signal stands for everything before it on the stream -- in place of a
- * barrier packet of its own between two kernels. rad_ride_wait puts a barrier on another stream
- * that waits for it and gives the signal back behind that barrier; a ride the DMA engine polls
- * instead goes back with rad_ride_release once nothing can poll it: at once (`after` null) when the
- * list that polled it has finished, else once `after` is `packets` dispatches further on, which is
- * long after the ridden dispatch has completed it.
+ * A ride is a signal completed by the next dispatch on a stream, instead of a separate barrier
+ * packet. That dispatch keeps its ordering bit, so the signal covers everything before it.
+ * rad_ride_wait puts a barrier waiting on it onto another stream and recycles the signal behind
+ * that barrier. A ride polled by the DMA engine is returned with rad_ride_release once nothing can
+ * poll it: immediately (`after` null) when the polling list has finished, else once `after` is
+ * `packets` dispatches further on.
  *
- * rad_xp_list hands the card's prefetch DMA queue a list: wait for `mark` (a ride, or null), copy
- * the `n` ranges, then write `done_val` to `done` (pinned host memory, or null). rad_xp_behind is how
- * many lists the queue has been handed and not yet finished. The prefetch's ring is uncached device
- * memory (rad_dev_alloc_uncached): the engine writes it and kernels read it, and no cache may hold
- * what a slot held before. */
+ * rad_xp_list gives the card's prefetch DMA queue a list: wait for `mark` (a ride, or null), copy
+ * the `n` ranges, then write `done_val` to `done` (pinned host memory, or null). rad_xp_behind
+ * 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. */
 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);
@@ -131,35 +117,53 @@ 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);
 
+/* A gate on a stream: the stream stops at the point rad_stream_gate enqueues and goes on once the
+ * host calls rad_gate_open. Everything enqueued behind the gate meanwhile is then ready at once, so
+ * the device runs it back to back however long the host took to submit it. For timing a batch of
+ * launches without the host's submission rate in the measurement (tools/kbench_timer.cpp); the
+ * engine has no use for it.
+ *
+ * Behind a closed gate the queue only fills. A caller enqueues at most rad_gate_room(s) more
+ * submissions, counting each launch's own (a kernel may issue several), and must not wait on the
+ * stream before opening the gate. The backends refuse with RAD_E_STATE, rather than deadlock, a
+ * submission that would wait for room and a rad_stream_sync on a gated stream; an event sync on a
+ * record behind the gate is not caught. Open every gate before destroying its stream.
+ *
+ * The gate itself acquires at system scope, so nothing behind it takes the acquire a first
+ * dispatch after a host wait otherwise takes. rad_gate_room counts the submissions that fit
+ * before the queue is full or before a dispatch would take the periodic system-scope acquire
+ * (an L2 invalidate, see aql.cpp "fences"); on a stream without a closed gate it is the same
+ * count with the device still draining. `gate` is single-use: opening it frees it. Not inside a
+ * tape capture. RAD_E_UNSUPPORTED (and a room of 0) on a backend without gates. */
+extern "C" int     rad_stream_gate(RadStream s, void** gate);
+extern "C" int     rad_gate_open(void* gate);
+extern "C" int64_t rad_gate_room(RadStream s);
+
 namespace rad {
 
 /* A recorded pass, owned by the backend that recorded it. See DeviceBackend::tape_begin. */
 typedef void* RadTape;
 
-/* ------------------------------------------------------------------ who won */
-/* Decided once, at first use, and cached. Callers: the planner (a host backend has no VRAM tier
- * worth planning against, only a budget), the selector (RAD_DOMAIN_HOST is the only domain that
- * can run), and every test that must skip a device-only assertion rather than fail it. */
+/* ------------------------------------------------------------------ active backend */
+/* Decided once at first use and cached. Used by the planner (a host backend has only a budget,
+ * no VRAM tier), the selector (only RAD_DOMAIN_HOST can run) and tests that skip device-only
+ * assertions. */
 bool        device_is_host();
 const char* device_backend_name();      /* "host" or "aql" */
 
 /* ------------------------------------------------------------------ two contract notes
  *
- * These are properties of rad_device.h that the frozen header does not state and that
- * tests/device_test.cpp pins against a real card. Written down here rather than left to be
- * rediscovered:
+ * Properties of rad_device.h that the frozen header does not state; tests/device_test.cpp pins
+ * them against a real card.
  *
- *  1. `rad_memset_async` requires a DEVICE-ACCESSIBLE destination: RAD_MEM_DEVICE,
- *     RAD_MEM_HOST_PINNED or RAD_MEM_HOST_MAPPED. Plain RAD_MEM_HOST is pageable memory the GPU
- *     has never been shown and hipMemsetAsync refuses it. The host backend cannot reproduce that
- *     refusal, so this is the one asymmetry between the two -- see the comment on d_memset_async
- *     in hip.cpp for why it is reported rather than papered over. `rad_memcpy_async` has no such
- *     restriction: hipMemcpyDefault handles pageable memory on both ends.
+ *  1. `rad_memset_async` requires a device-accessible destination: RAD_MEM_DEVICE,
+ *     RAD_MEM_HOST_PINNED or RAD_MEM_HOST_MAPPED. hipMemsetAsync refuses pageable RAD_MEM_HOST.
+ *     The host backend cannot reproduce that refusal, so this is the one asymmetry between the
+ *     two (see d_memset_async in hip.cpp). `rad_memcpy_async` has no such restriction.
  *
- *  2. A null RadStream is refused by BOTH backends. HIP's stream 0 serialises against every other
- *     blocking stream in the process, which is the opposite of spec §5.4's requirement that a
- *     transfer involve no host synchronisation; the engine creates its streams and never uses the
- *     default one, so passing null is a bug and the host backend reports it as one as well.
+ *  2. Both backends refuse a null RadStream. HIP's stream 0 serialises against every blocking
+ *     stream, contrary to spec §5.4 (no host synchronisation in a transfer). The engine never uses
+ *     the default stream, so null is a bug.
  */
 
 /* ------------------------------------------------------------------ the backend vtable */
@@ -190,9 +194,8 @@ struct DeviceBackend {
     int   (*event_sync)(RadEvent e);
     int   (*event_elapsed_ms)(RadEvent a, RadEvent b, float* out);
 
-    /* The host has written memory a kernel issued from here on will read, without a host wait
-     * having come between: whatever makes the device see host writes after a wait has to be done
-     * now as well. */
+    /* The host wrote memory that kernels issued from here on read, with no host wait in between:
+     * do whatever a wait would have done to make host writes visible to the device. */
     void  (*host_wrote)(void);
 
     int   (*memcpy_async)(void* dst, const void* src, int64_t bytes, RadStream s);
@@ -205,73 +208,59 @@ struct DeviceBackend {
     int   (*link_hold)(RadStream s, int on);
     void* (*link_gate)(RadStream s);
 
-    /* ---- recorded passes. A backend with none leaves these null, and the run phase then issues
-     * every pass; see Ctx::run_step for what a tape is for and when one is kept.
+    /* ---- recorded passes. Null on a backend without them; the run phase then issues every
+     * pass. See Ctx::run_step for what a tape is for.
      *
-     * `tape_begin` opens a capture of every submission THIS THREAD makes -- dispatches, event
-     * records and waits -- while `tape_pause` is not in effect (it nests). `tape_mark` is the
-     * number of records so far, which is how the caller cuts a tape into the stretches between
-     * its own host work. `tape_end` closes the capture and returns the tape, or null when `keep`
-     * is 0 or the pass did something a tape cannot reproduce (the reason is in
-     * rad_dev_last_error). `tape_play` submits records [from, to) again, onto the queues they
-     * were recorded on. `tape_destroy` may be called while a play is still queued; the backend
-     * frees the tape once nothing can read it. */
+     * `tape_begin` captures every submission this thread makes (dispatches, event records and
+     * waits) outside `tape_pause` (which nests). `tape_mark` returns the record count, so the
+     * caller can cut the tape at its own host work. `tape_end` returns the tape, or null when
+     * `keep` is 0 or the pass did something a tape cannot reproduce (reason in
+     * rad_dev_last_error). `tape_play` resubmits records [from, to) onto their recorded queues.
+     * `tape_destroy` may be called while a play is queued; the tape is freed once unreachable. */
     int     (*tape_begin)(void);
     int     (*tape_mark)(void);
     void    (*tape_pause)(int on);
     RadTape (*tape_end)(int keep);
     int     (*tape_len)(RadTape t);
     int     (*tape_play)(RadTape t, int from, int to);
-    /* The first record at which two tapes differ, -1 when they agree: the same submissions to the
-     * same queues, the same packets but for where their arguments live, the same argument bytes.
-     * What differs is described into `why`. */
+    /* First record at which two tapes differ, or -1 if they agree (same submissions to the same
+     * queues, same packets apart from argument addresses, same argument bytes). The difference is
+     * described into `why`. */
     int     (*tape_diff)(RadTape a, RadTape b, char* why, int cap);
     void    (*tape_destroy)(RadTape t);
-    /* Record `i` of a tape: what it is (0 a dispatch, 1 an event record or wait) and the queue it
-     * goes to. And the one edit a closed tape takes: whether dispatch `i` is played WITHOUT the
-     * barrier bit, launching while the packets in front of it on its queue are still running.
-     * The caller sets it only where it has shown the dispatch touches nothing those packets write,
-     * and on at most kTapeOverlapRun dispatches in a row; see Ctx::haz_mark. */
+    /* `tape_record`: record `i`'s kind (0 dispatch, 1 event record or wait) and queue.
+     * `tape_set_overlap`, the one edit a closed tape accepts: play dispatch `i` without the barrier
+     * bit, so it launches while earlier packets on its queue still run. The caller sets it only
+     * where the dispatch touches nothing those packets write, and on at most kTapeOverlapRun
+     * consecutive dispatches; see Ctx::haz_mark. */
     int     (*tape_record)(RadTape t, int i, int* kind, uint32_t* queue);
     int     (*tape_set_overlap)(RadTape t, int i, int on);
 
 
-    /* ---- elastic memory: an address range whose SIZE IS FIXED AND WHOSE BACKING IS NOT.
+    /* ---- elastic memory: an address range of fixed size whose backing comes and goes.
      *
-     * A pool allocated whole owns its bytes for the life of the process, which is the right trade
-     * for a pool whose demand is known at startup and the wrong one for two pools that take
-     * turns. The KV cache and the expert slab are that pair: the cache holds what the live
-     * sessions hold and nothing more, and a byte it is not holding is a byte the expert plane
-     * would rather have resident than stream over the link.
+     * Lets two pools that take turns share memory: the KV cache backs only what live sessions
+     * hold, and the expert plane keeps the rest resident instead of streaming it over the link.
      *
-     * WHY THIS IS A PRIMITIVE AND NOT FREE-THEN-REALLOCATE. The KV pool is layer-major
-     * (core/mem/kv.h): layer i lives at `base + i * n_blocks * layer_bytes_per_block`, so the
-     * block count is baked into every layer's base address and the unused blocks are a stripe
-     * inside each layer rather than a tail anyone could hand back. Reserving the address range at
-     * its maximum and backing only part of it leaves every stride where the kernels already
-     * expect it while the physical pages come and go underneath.
+     * Free-then-reallocate does not work: the KV pool is layer-major (core/mem/kv.h), layer i at
+     * `base + i * n_blocks * layer_bytes_per_block`, so unused blocks are a stripe inside each
+     * layer, not a tail. Reserving the maximum range and backing part of it keeps every stride
+     * where the kernels expect it.
      *
-     * A backend without elastic memory leaves these null, and everything above it sizes its pools
-     * once and lives with the split: the absence is a configuration rather than a degradation.
-     *
-     * The contract:
-     *
-     *   `vmem_reserve` takes address space and no pages.
-     *
-     *   `vmem_commit` backs ONE GRANULE and `vmem_decommit` unbacks one. A MAPPING IS UNMAPPED
-     *   EXACTLY AS IT WAS MAPPED: a driver handed four granules in one call refuses to unmap the
-     *   second of them on its own. VMem below therefore issues one call per granule and never a
-     *   run, which is what makes the granule the unit a pool can grow and shrink by.
-     *
-     *   `vmem_protect` grants this device read/write access to a range that is already backed. It
-     *   is separate from the commit because the range to name is not the one just mapped: access
-     *   set over a granule adjacent to an already-accessible one is refused where the whole
-     *   contiguous run containing both is accepted, so VMem names the run.
+     * A backend without elastic memory leaves these null and pools are sized once at startup;
+     * that is a supported configuration.
      *
+     * Contract:
+     *   `vmem_reserve` takes address space, no pages.
+     *   `vmem_commit` backs one granule and `vmem_decommit` unbacks one. The driver unmaps a
+     *   mapping only exactly as it was mapped (four granules mapped in one call cannot be unmapped
+     *   singly), so VMem issues one call per granule.
+     *   `vmem_protect` grants this device read/write access to an already-backed range. It is
+     *   separate from commit because access set on a granule adjacent to an accessible one is
+     *   refused, while the whole contiguous run is accepted; VMem names the run.
      *   `vmem_release` takes a range with nothing committed in it.
      *
-     * The bookkeeping that keeps a commit off a commit lives in VMem below, once, rather than in
-     * each backend. */
+     * Overlap bookkeeping lives once in VMem below, not in each backend. */
     int64_t (*vmem_granularity)(void);                     /* commit quantum; 0 = unsupported */
     void*   (*vmem_reserve)(int64_t bytes, int64_t align);
     void    (*vmem_release)(void* base, int64_t bytes);
@@ -279,47 +268,41 @@ struct DeviceBackend {
     int     (*vmem_decommit)(void* addr, int64_t bytes);
     int     (*vmem_protect)(void* addr, int64_t bytes);
 
-    /* ---- observation. The VRAM in use on a card, every process's, as the driver counts it, read
-     * without entering the device runtime: a dashboard polls it, and a runtime call can wait on
-     * a lock the launch path holds. Available once props() has been read for the device;
-     * RAD_E_UNSUPPORTED before that, and from a backend with no such counter. Last in the table
-     * so that a backend listing its entries in order may leave it out. */
+    /* ---- observation. VRAM in use on a card by all processes, as the driver counts it, read
+     * without entering the device runtime (a dashboard polls it, and a runtime call can block on
+     * a lock the launch path holds). Available once props() has been read for the device;
+     * otherwise, or without such a counter, RAD_E_UNSUPPORTED. */
     int     (*vram_used)(int device, int64_t* out);
 
-    /* ---- plugin device code. A backend that loads device code out of the fat binaries kernel
-     * plugins carry counts each registration; `code_mark` is how many there have been, and
-     * `code_runs` answers whether every one in [from, to) holds a code object `device` runs (1),
-     * not (0, with the reason in `why`), or cannot say (< 0). The plugin loader brackets each
-     * dlopen with marks, so the run is exactly that plugin's. Null on a backend that loads no
-     * device code. */
+    /* ---- plugin device code. `code_mark` counts fat-binary registrations so far; `code_runs`
+     * reports whether every registration in [from, to) has a code object `device` runs (1), not
+     * (0, reason in `why`), or unknown (< 0). The plugin loader brackets each dlopen with marks.
+     * Null on a backend that loads no device code. */
     size_t  (*code_mark)(void);
     int     (*code_runs)(size_t from, size_t to, int device, char* why, int cap);
 
-    /* ---- 1 when the device is integrated graphics: its memory is the host's, so what it reports
-     * as device memory is shared with every process on the machine. Null on a backend with no such
-     * devices, which answers 0. */
+    /* ---- 1 when the device is integrated graphics: its "device memory" is host memory shared
+     * with every process. Null (answers 0) on a backend with no such devices. */
     int     (*integrated)(int device);
 
-    /* ---- 1 when `self` can read and write `peer`'s memory directly, 0 when it cannot, < 0 when
-     * the backend cannot say. Asked, not enabled: rad_dev_enable_peer is the call that maps the
-     * memory. Null on a backend whose devices share one address space, which answers 1. */
+    /* ---- 1 when `self` can access `peer`'s memory directly, 0 when not, < 0 when unknown. A
+     * query only; rad_dev_enable_peer maps the memory. Null (answers 1) on a backend whose devices
+     * share one address space. */
     int     (*peer_access)(int self, int peer);
 
-    /* ---- the card's PCI address, "0000:03:00.0", into `out`; RAD_E_UNSUPPORTED from a backend
-     * whose devices are not PCI devices. It is what joins the runtime's device index to the
-     * kernel's description of the same card -- its link, its power limits, its IOMMU group -- in
-     * the startup report (core/diag/diag.h). */
+    /* ---- the card's PCI address, "0000:03:00.0", into `out`; RAD_E_UNSUPPORTED for non-PCI
+     * devices. The startup report (core/diag/diag.h) uses it to join the runtime's device index to
+     * the kernel's view of the card (link, power limits, IOMMU group). */
     int     (*pci_address)(int device, char* out, int cap);
     /* ---- the device runtime's name and version, "HIP 7.2.25403", into `out`. Null on a backend
-     * with no runtime behind it. */
+     * with no runtime. */
     int     (*runtime_version)(char* out, int cap);
-    /* ---- what carries the engine's copy lists for `device` (rad_memcpy_list_async), into `out`:
-     * the card's DMA engine on a queue of the process's own, or why not. Null on a backend that
-     * copies every list segment by segment. */
+    /* ---- what carries rad_memcpy_list_async for `device`, into `out`: the card's DMA engine on
+     * the process's own queue, or why not. Null on a backend that copies segment by segment. */
     int     (*dma_lane)(int device, char* out, int cap);
 
-    /* ---- the expert prefetch's device half: see rad_xp_supported. Last in the table, so a backend
-     * listing its entries in order leaves them null. */
+    /* ---- expert prefetch device half: see rad_xp_supported. Last in the table, so a backend
+     * listing its entries positionally leaves them null. */
     int     (*xp_supported)(int device);
     int     (*xp_stream_create)(RadStream* out);
     int     (*ride)(RadStream s, void** token);
@@ -330,6 +313,11 @@ struct DeviceBackend {
     int64_t (*xp_behind)(int device);
     void*   (*alloc_uncached)(int64_t bytes);
     void    (*free_uncached)(void* p);
+
+    /* ---- gates: see rad_stream_gate. Null on a backend without them. */
+    int     (*stream_gate)(RadStream s, void** gate);
+    int     (*gate_open)(void* gate);
+    int64_t (*gate_room)(RadStream s);
 };
 
 
@@ -354,8 +342,8 @@ int     dev_peer_access(int self, int peer);
 /* The current backend's DeviceBackend::vram_used. */
 int     dev_vram_used(int device, int64_t* out);
 
-/* The current backend's DeviceBackend::code_mark and code_runs. A backend without them has no
- * device code to check: the mark is 0 and every plugin runs (1). */
+/* The current backend's DeviceBackend::code_mark and code_runs. Without them the mark is 0 and
+ * every plugin runs (1). */
 size_t  dev_code_mark();
 int     dev_code_runs(size_t from, size_t to, int device, std::string* why);
 
@@ -368,41 +356,40 @@ std::string dev_runtime_version();
 /* The current backend's DeviceBackend::dma_lane, "" where it has none. */
 std::string dev_dma_lane(int device);
 
-/* THE LONGEST RUN OF DISPATCHES A PLAYED TAPE LEAVES UNORDERED. Of any kTapeOverlapRun + 1
- * consecutive packets on a queue, one carries the barrier bit, so a packet having been launched
- * still proves that everything more than that many packets before it has completed -- which is
- * what the backend's argument slots and a tape's own lifetime are reclaimed on. */
+/* Longest run of dispatches a played tape leaves unordered. Of any kTapeOverlapRun + 1
+ * consecutive packets on a queue one carries the barrier bit, so a launched packet still proves
+ * that everything more than that many packets earlier has completed. Argument slots and tape
+ * lifetimes are reclaimed on that guarantee. */
 constexpr int kTapeOverlapRun = 6;
 
 /* ------------------------------------------------------------------ the allocation ledger
- * What rad_dev_alloc has handed out, by RAD_MEM_* kind, since the process started. See the
- * comment on the ledger in dispatch.cpp for what it is for and -- more to the point -- what it
- * cannot see: a kernel plugin that calls hipMalloc directly never reaches this file. */
+ * What rad_dev_alloc has handed out since process start, by RAD_MEM_* kind. It does not see a
+ * kernel plugin that calls hipMalloc directly; see the ledger in dispatch.cpp. */
 void rad_dev_alloc_totals(int kind, int64_t* bytes, int64_t* count);
 
 /* Event handles created and not yet destroyed, process-wide. */
 int64_t rad_dev_live_events(void);
+/* Calls to rad_event_sync and rad_stream_sync since process start, from any thread: the host
+ * blocks the ABI makes. */
+int64_t rad_dev_host_blocks(void);
 
 /* ------------------------------------------------------------------ elastic memory
- * One reserved address range and the record of which granules inside it are backed.
+ * One reserved address range and which granules inside it are backed.
  *
- * The interval bookkeeping is here rather than in the backends because the driver refuses a
- * commit that overlaps a commit and a decommit that covers a hole, and two implementations of
- * "which parts of this range are already backed" is two places for that answer to drift. The
- * backends get granule-aligned, disjoint ranges and no decisions.
+ * The interval bookkeeping lives here, not in the backends, because the driver refuses a commit
+ * overlapping a commit and a decommit covering a hole. Backends get granule-aligned, disjoint
+ * ranges and make no decisions.
  *
- * THE TWO ROUNDINGS GO OPPOSITE WAYS, AND IT IS NOT A DETAIL. A commit rounds OUTWARD, so the
- * bytes the caller asked for are certainly backed; a decommit rounds INWARD, so a granule holding
- * one byte the caller still wants is never taken away. The alternative -- one rounding for both --
- * either strands memory or unmaps live data, and the second reads as a kernel fault at an address
- * that was valid a moment ago.
+ * The roundings differ on purpose: commit rounds outward, so every requested byte is backed;
+ * decommit rounds inward, so a granule holding any byte still in use is kept. A shared rounding
+ * would either strand memory or unmap live data (a kernel fault at a valid address).
  *
- * Nothing here is thread-safe. A range is owned by whatever owns the pool it backs, and the
- * commit/decommit path is a policy decision, not a step-path one. */
+ * Not thread-safe. A range is owned by the owner of the pool it backs, and commit/decommit is
+ * policy, not step-path work. */
 class VMem {
 public:
-    /* Whether this process's backend has elastic memory at all. Callers size their pools whole
-     * when it does not: see the DeviceBackend comment for why that is a supported configuration. */
+    /* Whether the backend has elastic memory. Without it callers size pools whole (a supported
+     * configuration; see DeviceBackend). */
     static bool    supported();
     static int64_t granularity();          /* 0 when unsupported */
 
@@ -410,9 +397,8 @@ public:
     ~VMem() { release(); }
     VMem(const VMem&) = delete;
     VMem& operator=(const VMem&) = delete;
-    /* Movable, because an elastic range is owned by whatever structure holds it and those
-     * structures live in vectors. The source is left naming nothing, so the destructor it still
-     * gets does not unmap a range the destination now owns. */
+    /* Movable, since owners live in vectors. The source is left empty so its destructor does not
+     * unmap the range the destination now owns. */
     VMem(VMem&& o) noexcept
         : base_(o.base_), size_(o.size_), committed_(o.committed_), ext_(std::move(o.ext_)) {
         o.base_ = nullptr;
@@ -433,9 +419,8 @@ public:
         return *this;
     }
 
-    /* Address space only: no pages, no VRAM, nothing the card notices. `align` defaults to the
-     * granularity. Reserving large is the point -- the range is the MAXIMUM the pool may ever
-     * reach, because it is the one thing that cannot be changed later without moving addresses. */
+    /* Address space only: no pages, no VRAM. `align` defaults to the granularity. Reserve the
+     * maximum the pool may ever reach; the range cannot grow later without moving addresses. */
     int   reserve(int64_t bytes, int64_t align = 0);
     void  release();                       /* decommits whatever is still backed, then frees the VA */
 
@@ -443,22 +428,22 @@ public:
     int64_t size() const { return size_; }
     int64_t committed() const { return committed_; }   /* bytes actually backed right now */
 
-    /* Both are idempotent and both clamp to the range. commit() backs every granule touching
-     * [off, off+bytes) that is not backed; decommit() unbacks every granule wholly inside it that
-     * is. Either may do nothing and report success. */
+    /* Idempotent and clamped to the range. commit() backs every unbacked granule touching
+     * [off, off+bytes); decommit() unbacks every backed granule wholly inside it. Doing nothing is
+     * success. */
     int  commit(int64_t off, int64_t bytes);
     int  decommit(int64_t off, int64_t bytes);
 
-    /* Is every byte of [off, off+bytes) backed? The question a caller asks before handing the
-     * range to a kernel. */
+    /* Whether every byte of [off, off+bytes) is backed; check before handing a range to a
+     * kernel. */
     bool is_committed(int64_t off, int64_t bytes) const;
 
 private:
     void*   base_ = nullptr;
     int64_t size_ = 0;
     int64_t committed_ = 0;
-    /* Sorted, disjoint and never adjacent: a commit that touches an existing extent merges into
-     * it, so the list length tracks the number of live REGIONS and not the number of calls. */
+    /* Backed extents (offset, bytes): sorted, disjoint and never adjacent, since a touching
+     * commit merges. Length tracks live regions, not calls. */
     std::vector> ext_;
 
     /* Adds a newly mapped piece and merges it with whatever it touches. */
@@ -466,34 +451,30 @@ private:
     void drop_extent(int64_t off, int64_t bytes);
 };
 
-/* What every VMem in this process has backed, for the receipt Engine::start prints. Device memory
- * committed this way never reaches the rad_dev_alloc ledger -- it is not an allocation -- so
- * without this line the card's own accounting and the engine's disagree by exactly the elastic
- * pools. */
+/* Bytes backed by every VMem in the process, for Engine::start's receipt. VMem commits bypass the
+ * rad_dev_alloc ledger, so without this the engine's accounting would miss the elastic pools. */
 int64_t rad_dev_vmem_committed(void);
 
 #if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP
-/* Null when the build has HIP but the machine shows no device. A build that can talk to a GPU and
- * a machine that has one are separate facts, and conflating them is how a CI container that
- * happens to have ROCm headers installed fails at the first hipMalloc instead of running the host
- * backend it was always going to run. The configure decides which kernels are COMPILED; this
- * decides whether there is a card to run them on, and neither answer implies the other. */
+/* Null when the build has HIP but the machine shows no device, so a machine with ROCm installed
+ * but no card runs the host backend instead of failing at the first hipMalloc. Configure decides
+ * which kernels are compiled; this decides whether there is a card to run them. */
 const DeviceBackend* hip_backend_if_present(void);
-/* The HIP backend with its streams, events, copies and fills replaced by AQL packets the engine
- * writes itself (aql.cpp). Aborts, naming why, on a machine it cannot run on. */
+/* The HIP backend with streams, events, copies and fills replaced by AQL packets the engine writes
+ * itself (aql.cpp). Aborts with the reason on a machine it cannot run on. */
 const DeviceBackend* aql_backend_if_present(void);
-/* Bytes copied to or from pageable host memory so far: every such copy is a host wait. */
+/* Bytes copied to or from pageable host memory so far; each such copy is a host wait. */
 int64_t aql_pageable_bytes(void);
-/* The fat binaries registered so far, counted whichever backend runs: the registration hooks are
- * this build's own exported symbols and see every dlopen'ed kernel plugin's device code, card or
- * no card. The host backend's code_mark in a HIP build. */
+/* Fat binaries registered so far, counted whichever backend runs: the registration hooks are this
+ * build's exported symbols and see every dlopen'ed plugin's device code, card or not. Serves as
+ * the host backend's code_mark in a HIP build. */
 size_t  aql_code_registered(void);
 #endif
 
 /* ------------------------------------------------------------------ the error slot */
-/* Both backends write here; rad_dev_last_error() drains it. Thread-local, because spec §1 puts one
- * thread per tensor-parallel rank and the mover on its own: a fault on the mover's thread reported
- * as the compute rank's would send the operator to the wrong half of the engine. */
+/* Both backends write here; rad_dev_last_error() drains it. Thread-local because spec §1 gives each
+ * tensor-parallel rank and the mover their own thread, and an error must be reported on the thread
+ * that caused it. */
 void device_set_error(const char* fmt, ...) __attribute__((format(printf, 1, 2)));
 
 }  /* namespace rad */
diff --git a/core/device/directio.cpp b/core/device/directio.cpp
index 7841dbde..70a3b506 100644
--- a/core/device/directio.cpp
+++ b/core/device/directio.cpp
@@ -15,30 +15,12 @@
 namespace rad {
 namespace {
 
-/* The bounce is one megabyte, allocated on first misaligned use and never on the aligned path.
- * Big enough that a misaligned read of a whole weight is a handful of syscalls; small enough that
- * a DirectFile nobody misuses costs nothing. */
+/* Bounce buffer size; allocated on first misaligned use only. */
 constexpr int64_t kBounceBytes = 1 << 20;
 
 int64_t align_down(int64_t v, int64_t a) { return v / a * a; }
 
-/* Fill `bytes` exactly. A short pread inside the file is a torn read, not a smaller one. */
-int pread_exact(int fd, void* dst, int64_t bytes, int64_t off) {
-    int64_t done = 0;
-    while (done < bytes) {
-        ssize_t r = ::pread(fd, (uint8_t*)dst + done, (size_t)(bytes - done), (off_t)(off + done));
-        if (r < 0) {
-            if (errno == EINTR) continue;
-            return RAD_E_IO;
-        }
-        if (r == 0) return RAD_E_IO;   /* end of file inside a range the caller said was there */
-        done += r;
-    }
-    return RAD_OK;
-}
-
-/* As much as the file has, which is what the aligned superset of a misaligned tail asks for.
- * Negative is an error; otherwise the byte count. */
+/* Reads up to `bytes`, stopping at end of file. Returns the byte count, or a negative error. */
 int64_t pread_some(int fd, void* dst, int64_t bytes, int64_t off) {
     int64_t done = 0;
     while (done < bytes) {
@@ -53,6 +35,14 @@ int64_t pread_some(int fd, void* dst, int64_t bytes, int64_t off) {
     return done;
 }
 
+/* Fill `bytes` exactly. A short pread inside the file is a torn read, not a smaller one: end of
+ * file inside a range the caller said was there is an error. */
+int pread_exact(int fd, void* dst, int64_t bytes, int64_t off) {
+    const int64_t got = pread_some(fd, dst, bytes, off);
+    if (got < 0) return (int)got;
+    return got == bytes ? RAD_OK : RAD_E_IO;
+}
+
 int pwrite_exact(int fd, const void* src, int64_t bytes, int64_t off) {
     int64_t done = 0;
     while (done < bytes) {
@@ -76,9 +66,7 @@ int DirectFile::open(const char* path, int flags) {
     close();
 
     const bool want_write = (flags & RAD_DIO_WRITE) != 0;
-    /* O_RDWR whenever writing, even if the caller only said RAD_DIO_WRITE: a write that does not
-     * cover a whole block has to read the block first (see write_at), and O_WRONLY would turn that
-     * into an EBADF at the worst possible moment. */
+    /* O_RDWR whenever writing: a partial-block write reads the block first (see write_at). */
     int oflags = want_write ? O_RDWR : O_RDONLY;
     if (flags & RAD_DIO_CREATE) oflags |= O_CREAT;
     if (flags & RAD_DIO_TRUNC)  oflags |= O_TRUNC;
@@ -87,7 +75,7 @@ int DirectFile::open(const char* path, int flags) {
     direct_ = fd_ >= 0;
 
     if (fd_ < 0 && (errno == EINVAL || errno == ENOTSUP || errno == EOPNOTSUPP)) {
-        /* The filesystem, not the file: tmpfs and some network mounts refuse O_DIRECT outright. */
+        /* tmpfs and some network mounts refuse O_DIRECT outright. */
         if (flags & RAD_DIO_ALLOW_BUFFERED) {
             fd_ = ::open(path, oflags, 0600);
             direct_ = false;
@@ -145,19 +133,13 @@ int DirectFile::read_at(void* dst, int64_t off, int64_t bytes) {
     const bool aligned = (off % A) == 0 && (bytes % A) == 0 &&
                          ((uintptr_t)dst % (uintptr_t)A) == 0;
 
-    /* THE PATH THAT MATTERS. One pread, straight into the caller's pinned buffer, no intermediate
-     * copy anywhere -- which is what makes the mover able to DMA from it (spec §5.4). Every extent
-     * the .rad container describes lands here, because the container aligns its movement units to
-     * RAD_ALIGN_UNIT and rad_dev_alloc aligns its pools to the same. */
+    /* Fast path: one pread straight into the caller's pinned buffer. Every .rad extent lands here
+     * (movement units and rad_dev_alloc pools are both RAD_ALIGN_UNIT-aligned). */
     if (aligned) return pread_exact(fd_, dst, bytes, off);
 
-    /* THE ONLY BOUNCE IN THE ENGINE'S READ PATH, and it is here because O_DIRECT gives no
-     * alternative: the kernel will EINVAL a transfer whose offset, length or buffer is not
-     * block-aligned, so an unaligned extent can either be read through an aligned superset and
-     * copied out, or not read at all. It is acceptable here and nowhere else for one reason --
-     * this path is not the mover's. It serves the tail of a file whose length is not a block
-     * multiple, and callers reading a header or a footer rather than a movement unit. Anything on
-     * the step path that finds itself here has a layout bug, not a performance problem. */
+    /* O_DIRECT rejects unaligned transfers with EINVAL, so read an aligned superset through the
+     * bounce and copy out. This serves file tails and header/footer reads, never the mover; a
+     * step-path read landing here indicates a layout bug. */
     RAD_TRY(bounce_ready());
 
     const int64_t lo = align_down(off, A);
@@ -170,9 +152,7 @@ int DirectFile::read_at(void* dst, int64_t off, int64_t bytes) {
 
         const int64_t got = pread_some(fd_, bounce_, span, base);
         if (got < 0) return (int)got;
-        /* A short read is only survivable when the file ends past the slice the caller asked for.
-         * Otherwise the caller named bytes that are not in the file, which is RAD_E_IO and not a
-         * partial success (see read_at's contract in the header). */
+        /* A short read is fine only if it still covers the requested slice. */
         if (got < e - base) return RAD_E_IO;
         std::memcpy((uint8_t*)dst + (s - off), bounce_ + (s - base), (size_t)(e - s));
     }
@@ -181,8 +161,7 @@ int DirectFile::read_at(void* dst, int64_t off, int64_t bytes) {
 
 /* ------------------------------------------------------------------ write */
 
-/* The same shape as read_at -- one fast path for whole aligned blocks, and a read-modify-write for
- * anything that does not cover a whole block. */
+/* Aligned writes go straight through; anything else is a read-modify-write of whole blocks. */
 int DirectFile::write_at(const void* src, int64_t off, int64_t bytes) {
     if (fd_ < 0) return RAD_E_STATE;
     if (!src || off < 0 || bytes < 0) return RAD_E_INVAL;
@@ -201,10 +180,8 @@ int DirectFile::write_at(const void* src, int64_t off, int64_t bytes) {
     const int64_t hi = align_up(off + bytes, A);
     for (int64_t base = lo; base < hi; base += bounce_bytes_) {
         const int64_t span = std::min(bounce_bytes_, hi - base);
-        /* Read-modify-write the whole chunk, including blocks the request covers completely. That
-         * is a wasted read per interior block and it is deliberate: the branchless version is
-         * short enough to be obviously correct, and this path exists for correctness at a boundary,
-         * not for throughput. The aligned path above is the one that has to be fast. */
+        /* Read-modify-write the whole chunk, including fully covered interior blocks. The extra
+         * reads are deliberate: this path is for correctness at boundaries, not throughput. */
         const int64_t got = pread_some(fd_, bounce_, span, base);
         if (got < 0) return (int)got;
         if (got < span) std::memset(bounce_ + got, 0, (size_t)(span - got));
@@ -216,8 +193,7 @@ int DirectFile::write_at(const void* src, int64_t off, int64_t bytes) {
         RAD_TRY(pwrite_exact(fd_, bounce_, span, base));
     }
 
-    /* The last chunk padded the file out to a block boundary. Cut it back, so size() reports what
-     * was actually written and a later read_at of the tail sees the real end of file. */
+    /* The last chunk padded the file to a block boundary; truncate back to the real end. */
     const int64_t want = std::max(old_size, off + bytes);
     if (size() > want && ::ftruncate(fd_, (off_t)want) != 0) return RAD_E_IO;
     return RAD_OK;
diff --git a/core/device/directio.h b/core/device/directio.h
index 52aa5488..acff3080 100644
--- a/core/device/directio.h
+++ b/core/device/directio.h
@@ -1,21 +1,14 @@
-/* directio.h -- the file tier's reader.
+/* directio.h -- the file tier's reader (spec §5.4): O_DIRECT reads into pinned buffers, used by
+ * the weight tier and the KV tier.
  *
- * spec §5.4: "a file tier read with O_DIRECT into pinned buffers. Predictable latency, no
- * page-cache double-copy, and reads land where the mover can DMA from them without a bounce."
- * This file is that approach, narrowed to the one thing the weight tier and the KV tier both need.
+ * The page cache is avoided for two reasons:
+ *   - it is a second copy of every byte already headed for a pinned buffer;
+ *   - it evicts. A large tier read through the page cache throws out the mapped `.rad` pool's
+ *     pages, which shows up later as an untraceable decode stall.
  *
- * Two reasons the page cache is the wrong place for this and not merely a redundant one:
- *
- *   - it is a second copy of bytes that are already going to a pinned buffer, paid on every read,
- *     of a store measured in gigabytes;
- *   - it evicts. A weight-tier read pulling a hundred megabytes through the page cache throws out
- *     the mapped `.rad` pool's own pages, and the cost of that shows up in decode as a stall
- *     nobody can trace back to the read that caused it.
- *
- * The alignment rules are O_DIRECT's: the file offset, the transfer length and the buffer address
- * must all be block-aligned. Everything rad_dev_alloc returns already is (host.cpp), and .rad
- * pads its movement units to RAD_ALIGN_UNIT (rad_format.h), so the mover's every read takes the
- * path with no bounce in it. The bounce exists for the other callers.
+ * O_DIRECT requires the file offset, transfer length and buffer address to be block-aligned.
+ * rad_dev_alloc memory is (host.cpp) and .rad pads movement units to RAD_ALIGN_UNIT
+ * (rad_format.h), so every mover read takes the unbounced path. The bounce is for other callers.
  */
 #pragma once
 #include 
@@ -28,13 +21,9 @@ enum {
     RAD_DIO_CREATE = 4,
     RAD_DIO_TRUNC  = 8,
 
-    /* Open buffered when the filesystem refuses O_DIRECT, instead of failing the open.
-     *
-     * Off by default, and that default is the point. The weight tier is sized in gigabytes and
-     * read in megabyte runs; a silent buffered fallback turns it into a page-cache pump that is
-     * three times slower and looks like nothing at all in a profile. An operator whose container
-     * sits on tmpfs wants to be told, not accommodated. The flag is for tests, which have to run
-     * on whatever /tmp happens to be. */
+    /* Open buffered when the filesystem refuses O_DIRECT, instead of failing. Off by default: a
+     * silent buffered fallback makes the weight tier ~3x slower and is invisible in a profile.
+     * For tests, which run on whatever /tmp is. */
     RAD_DIO_ALLOW_BUFFERED = 16,
 };
 
@@ -55,17 +44,14 @@ public:
     int     fd() const      { return fd_; }
     int64_t size() const;
 
-    /* Exact reads and writes: a short transfer is RAD_E_IO, never a partial success. A mover that
-     * has to check a byte count on every extent is a mover with a branch on the step path, and a
-     * caller that forgets to check gets half a weight. */
+    /* Exact reads and writes: a short transfer is RAD_E_IO, never a partial success, so callers
+     * need no byte-count check. */
     int  read_at(void* dst, int64_t off, int64_t bytes);
     int  write_at(const void* src, int64_t off, int64_t bytes);
 
-    /* The alignment every fast-path extent must satisfy. 4096 rather than the device's own logical
-     * block size (which is 512 on plenty of hardware, and queryable via STATX_DIOALIGN on a recent
-     * kernel): 4096 is a superset of every real requirement, it is RAD_ALIGN_UNIT, and accepting
-     * 512-aligned extents would only widen the fast path for extents the .rad container never
-     * produces. One constant, no per-filesystem behaviour to reproduce a bug against. */
+    /* The alignment every fast-path extent must satisfy. A fixed 4096 rather than the device's
+     * logical block size (often 512, see STATX_DIOALIGN): it covers every real requirement, equals
+     * RAD_ALIGN_UNIT, and keeps behaviour independent of the filesystem. */
     static constexpr int64_t alignment() { return 4096; }
 
 private:
diff --git a/core/device/dispatch.cpp b/core/device/dispatch.cpp
index ce184f9b..a5694a6e 100644
--- a/core/device/dispatch.cpp
+++ b/core/device/dispatch.cpp
@@ -1,13 +1,10 @@
 /* dispatch.cpp -- picks a backend once, then forwards.
  *
- * The only definition of every rad_dev_* / rad_stream_* / rad_event_* symbol in the engine.
- * host.cpp and hip.cpp export vtables and nothing else, so there is no #ifdef anywhere above this
- * file and no way for the two to end up implementing different contracts.
+ * The only definition of every rad_dev_* / rad_stream_* / rad_event_* symbol. host.cpp and hip.cpp
+ * export vtables only, so there is no #ifdef above this file and both backends share one contract.
  *
- * The selection rule: a build with HIP still runs the host backend when the machine shows no
- * device. Having ROCm installed and having a card are separate facts -- a CI container with the
- * headers and no `/dev/kfd` is the normal case -- and the honest response is to say which backend
- * won at Info and carry on, not to fail at the first hipMalloc.
+ * A build with HIP still runs the host backend when no device is visible (e.g. a CI container
+ * with ROCm headers and no /dev/kfd); the chosen backend is logged at Info.
  */
 #include "device.h"
 #include "../rad_internal.h"
@@ -18,6 +15,7 @@
 #include 
 #include 
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -27,9 +25,8 @@
 namespace rad {
 
 /* ------------------------------------------------------------------ the error slot */
-/* Thread-local and drained by reading, which is the ABI's own contract. One thread per rank plus
- * the mover (spec §1), so a fault reported on the wrong thread would name the wrong half of the
- * engine to an operator who has to decide whether to restart. */
+/* Thread-local and cleared by reading, per the ABI. Each rank and the mover run on their own
+ * thread (spec §1), so an error must stay on the thread that raised it. */
 static thread_local std::string t_last_error;
 
 void device_set_error(const char* f, ...) {
@@ -39,23 +36,16 @@ void device_set_error(const char* f, ...) {
     vsnprintf(buf, sizeof buf, f, ap);
     va_end(ap);
     t_last_error.assign(buf);
-    /* Debug rather than Error: most of these are answered by the caller (a pool that tries an
-     * allocation, finds it does not fit and asks the planner for a smaller one). The ones that are
-     * fatal are reported by whoever decided they were fatal, with context this layer does not have. */
+    /* Debug, not Error: callers often recover (e.g. a pool retrying smaller), and fatal ones are
+     * reported by the caller with more context. */
     RAD_DEBUG("device: %s", buf);
 }
 
 /* ------------------------------------------------------------------ selection */
 
-/* One line, listing every visible device by index and arch.
- *
- * This is not decoration. A machine reports more devices than it has accelerators: a workstation
- * with two discrete cards and an APU reports three, and the integrated one claims tens of GiB of
- * "VRAM" that is really system RAM. A --tp matching that count, or a planner that sums vram_bytes
- * across devices, is wrong in a way that shows up as a memory error much later -- and the arch
- * printed here is what tells the two kinds apart. The device layer does not filter -- which
- * devices are usable is the engine's decision and it has rad_dev_props to make it with -- but it
- * does not let the inventory go unsaid either (spec §16). */
+/* The startup line's list of every visible device by index and arch. A machine may report more
+ * devices than accelerators: an APU shows up beside discrete cards and claims system RAM as
+ * "VRAM". The arch tells them apart. Filtering is the engine's decision (via rad_dev_props). */
 static std::string device_inventory(const DeviceBackend* b) {
     std::string s;
     const int n = b->count();
@@ -68,15 +58,12 @@ static std::string device_inventory(const DeviceBackend* b) {
 }
 
 #if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP
-/* COMPUTE WAVE SAVE/RESTORE OFF IS A GPU HANG WAITING FOR AN EVICTION. The driver evicts a
- * process's queues whenever host memory the card maps is moved or reclaimed under memory pressure,
- * and a serve with a host pool or a host KV tier maps gigabytes of it. With
- * amdgpu.cwsr_enable=0 it cannot preempt a running queue and waits for it to drain, which a queue
- * a serve keeps fed never does: the queue stops inside whatever kernel it was running, MES fails
- * REMOVE_QUEUE, and the driver resets the card. Said at startup because nothing later can tell
- * that hang from a kernel bug -- and said here, as the backend comes up, and not only in the
- * startup report: a hang during the load ends the process before the report prints, and the
- * tools that bring a backend up (rad-kbench, rad-tune) print no report at all. */
+/* With amdgpu.cwsr_enable=0 (compute wave save/restore off) a queue eviction hangs the GPU. The
+ * driver evicts a process's queues when card-mapped host memory is moved or reclaimed, and a serve
+ * maps gigabytes of it. Without CWSR the driver waits for the queue to drain, a busy queue never
+ * does, MES fails REMOVE_QUEUE and the card resets. Warned here as the backend comes up, not only
+ * in the startup report: a hang during load kills the process first, and rad-kbench and rad-tune
+ * print no report. */
 static void warn_cwsr_off() {
     FILE* f = std::fopen("/sys/module/amdgpu/parameters/cwsr_enable", "r");
     if (!f) return;
@@ -90,11 +77,10 @@ static void warn_cwsr_off() {
                  "amdgpu.cwsr_enable=1 (module option, then rebuild the initramfs and reboot)");
 }
 
-/* THE HOST BACKEND IN A BUILD THAT HAS HIP STILL COUNTS THE GPU CODE PLUGINS BRING. The
- * registration hooks are this build's own exported symbols and see every dlopen'ed kernel
- * library's fat binaries, card or no card, so the plugin loader can bracket each dlopen and know
- * which library brought device code. An engine serving here leaves that library's device rows out
- * of selection (Registry::set_no_device_code); a tool that only selects keeps them. */
+/* The host backend in a HIP build still counts plugin GPU code. This build's fat-binary
+ * registration hooks see every dlopen'ed kernel library, card or no card, so the plugin loader can
+ * tell which library brought device code. A serving engine drops those device rows from selection
+ * (Registry::set_no_device_code); a selection-only tool keeps them. */
 static DeviceBackend g_host_beside_hip;
 #endif
 
@@ -117,9 +103,7 @@ static const DeviceBackend* select_backend() {
     return b;
 }
 
-/* std::call_once rather than a function-local static, because the answer is read from every rank
- * thread and the guard variable's acquire load is the cheaper of the two on the paths that matter
- * -- and because a backend chosen twice would be a backend chosen differently twice. */
+/* Selected exactly once, under std::call_once; read from every rank thread. */
 static const DeviceBackend* g_backend = nullptr;
 static std::once_flag       g_once;
 
@@ -135,36 +119,22 @@ const char* device_backend_name() { return dev()->name; }
 
 /* ------------------------------------------------------------------ the ledger
  *
- * EVERY DEVICE ALLOCATION THIS ENGINE MAKES, COUNTED, because without it an unaccounted allocation
- * can only be found by sampling /sys/class/drm through startup and correlating the steps against
- * the log by eye.
+ * Counts every device allocation the engine makes. The VRAM budget (core/mem/vram_budget.cpp)
+ * spends the card down to --gpu-headroom-mib, so whatever lands outside the two pools and is not
+ * derived from the buffer plan or run configuration must be counted here.
  *
- * The VRAM budget (core/mem/vram_budget.cpp) spends the card down to --gpu-headroom-mib, which
- * only works if what lands outside the two pools is known. Most of it is known by construction:
- * the activation arena is computed from the buffer plan, the step batch staging from the run
- * configuration. Everything else has to be counted here, because an allocation nobody counts is an
- * allocation that eats the headroom and then fails somebody else's.
+ * Not seen: plugins that call hipMalloc directly (libr4d's split-tail workspaces and all-reduce
+ * peer scratch). Engine::start reads the card back after allocation for that reason.
  *
- * WHAT THIS DOES NOT SEE, and it is stated here because the number is only honest with the caveat
- * attached: a kernel plugin that calls hipMalloc itself goes nowhere near this file. libr4d does,
- * for its split-tail workspaces and its all-reduce peer scratch, and the engine's own accounting
- * cannot include them. Engine::start reads the card back after everything has allocated for
- * exactly that reason -- the ledger says what the core spent, the card says what was spent.
+ * RADIANCE_TRACE_ALLOC=N logs each allocation of at least N bytes.
  *
- * RADIANCE_TRACE_ALLOC=N logs every allocation of at least N bytes as it happens. That is the
- * instrument; the counters are the summary.
- *
- * RADIANCE_DEBUG_POISON_ALLOC=B fills every fresh DEVICE allocation with byte B (0..255) before
- * it is handed out, so a buffer that is read before anything wrote it shows up as garbage rather
- * than as the zeros a wiped card hands back by luck. A card that has just been through a driver
- * reset ("VRAM is lost") is that garbage for real, which is where such a read is otherwise first
- * seen. A correct engine serves the same output with it set. RADIANCE_DEBUG_POISON_RANGE=lo:hi
- * narrows the fill to device allocations with ordinal in [lo, hi) -- ordinals count from 1 in
- * allocation order ON THE ALLOCATING THREAD, the `#n on this thread` the trace prints -- to bisect
- * to the one allocation that matters. Both are instruments: the fill is synchronous, through one
- * stream per thread and device that lives until exit (a stream is a hardware queue, and creating
- * and destroying one per allocation is both slow and the queue churn ROCr's Trim path faults on).
- * A byte outside 0..255 or a range that does not parse is refused at the first allocation. */
+ * RADIANCE_DEBUG_POISON_ALLOC=B fills every fresh DEVICE allocation with byte B (0..255), so a
+ * read-before-write shows up as garbage instead of lucky zeros (as after a driver reset, "VRAM is
+ * lost"). A correct engine serves the same output with it set. RADIANCE_DEBUG_POISON_RANGE=lo:hi
+ * limits the fill to device allocations with ordinal in [lo, hi), counted from 1 per allocating
+ * thread (the trace's `#n on this thread`), for bisecting. The fill is synchronous on one stream
+ * per thread and device, kept until exit: a stream is a hardware queue, and per-allocation queue
+ * churn is slow and faults in ROCr's Trim path. Bad values abort at the first allocation. */
 namespace rad {
 namespace {
 
@@ -172,12 +142,14 @@ struct Ledger {
     std::atomic bytes{0};
     std::atomic count{0};
 };
-Ledger g_ledger[4];        /* indexed by RAD_MEM_*; see rad_dev_alloc below for the bound check */
+Ledger g_ledger[4];        /* indexed by RAD_MEM_*; rad_dev_alloc bounds the kind */
 
-/* Event handles, counted here and not in a backend so the number means the same on both. An
- * event a component forgets at teardown is reclaimed at exit and reported by nothing else, so
- * this is the one place such a leak shows. */
+/* Live event handles, counted here so the number is backend-independent; the only place an
+ * event leaked at teardown shows. */
 std::atomic g_live_events{0};
+/* Host blocks through the ABI (rad_event_sync, rad_stream_sync), counted here so a test can
+ * assert that a path never stops the host, whichever backend runs it. */
+std::atomic g_host_blocks{0};
 
 int64_t trace_floor() {
     static const int64_t v = [] {
@@ -232,17 +204,21 @@ const char* kind_name(int kind) {
 }  /* namespace */
 
 void rad_dev_alloc_totals(int kind, int64_t* bytes, int64_t* count) {
-    if (kind < 0 || kind >= 4) { if (bytes) *bytes = 0; if (count) *count = 0; return; }
+    if (kind < 0 || kind >= (int)std::size(g_ledger)) {
+        if (bytes) *bytes = 0;
+        if (count) *count = 0;
+        return;
+    }
     if (bytes) *bytes = g_ledger[kind].bytes.load(std::memory_order_relaxed);
     if (count) *count = g_ledger[kind].count.load(std::memory_order_relaxed);
 }
 
 int64_t rad_dev_live_events(void) { return g_live_events.load(std::memory_order_relaxed); }
+int64_t rad_dev_host_blocks(void) { return g_host_blocks.load(std::memory_order_relaxed); }
 
 
 /* ------------------------------------------------------------------ elastic memory */
-/* See device.h for what this is for. What is here is the interval arithmetic and the two
- * roundings; the backends do the mapping. */
+/* See device.h. Interval arithmetic and rounding here; the backends do the mapping. */
 
 namespace {
 std::atomic g_vmem_committed{0};
@@ -250,10 +226,8 @@ std::atomic g_vmem_committed{0};
 
 int64_t rad_dev_vmem_committed(void) { return g_vmem_committed.load(std::memory_order_relaxed); }
 
-/* BOTH HALVES OF THE QUESTION. A backend can carry the entries and still be running on a device
- * whose driver has no virtual memory manager -- d_vmem_granularity answers 0 there -- and a pool
- * that asked only whether the function pointers existed would reserve an address range it could
- * never back, then fail at the first commit instead of sizing itself whole at startup. */
+/* Both checks: a backend may have the entries on a driver with no virtual memory manager
+ * (granularity 0). Checking only the pointers would reserve a range that can never be backed. */
 bool    VMem::supported()   { return dev()->vmem_reserve != nullptr && VMem::granularity() > 0; }
 int64_t VMem::granularity() {
     if (!dev()->vmem_granularity) return 0;
@@ -271,8 +245,7 @@ int VMem::reserve(int64_t bytes, int64_t align) {
     const int64_t g = granularity();
     if (g <= 0) return RAD_E_UNSUPPORTED;
     if (align <= 0) align = g;
-    /* ROUNDED UP TO A GRANULE, because the last granule of a range that is not a whole number of
-     * them can never be committed and the bytes in it are then reserved and unreachable. */
+    /* Round up to a granule: a partial last granule could never be committed. */
     const int64_t want = align_up(bytes, g);
     void* p = dev()->vmem_reserve(want, align);
     if (!p) return RAD_E_NOMEM;
@@ -285,9 +258,8 @@ int VMem::reserve(int64_t bytes, int64_t align) {
 
 void VMem::release() {
     if (!base_) { size_ = 0; committed_ = 0; ext_.clear(); return; }
-    /* A range released with pages still in it leaks the pages and, on some drivers, refuses the
-     * address free as well -- so the teardown order is fixed here rather than asked of callers.
-     * Granule at a time, because that is how each of them was mapped. */
+    /* Decommit before release: releasing a range with pages still mapped leaks them, and some
+     * drivers refuse the free. One granule at a time, as each was mapped. */
     const int64_t g = granularity();
     for (const auto& e : ext_) {
         if (dev()->vmem_decommit && g > 0)
@@ -309,29 +281,20 @@ bool VMem::is_committed(int64_t off, int64_t bytes) const {
         if (off >= e.first && off + bytes <= e.first + e.second) return true;
     return false;                       /* extents are merged, so one of them covers it or none does */
 }
-/* WHAT TO MAP IS COMPUTED BEFORE ANYTHING IS MAPPED, and that is not a style choice. add_extent
- * MERGES, so the list this walk is reading rearranges itself under the walk the moment a gap is
- * filled -- the cursor then lands past the end of a list that just got shorter and the tail of the
- * request is mapped a second time. On the host backend a double map silently succeeds and only
- * the accounting is wrong; on a card the driver refuses it and a pool fails to grow.
+/* The granules to map are gathered before mapping any: add_extent merges, so walking ext_ while
+ * mapping would skip entries and map the tail twice (the driver refuses a double map).
  *
- * ONE GRANULE PER CALL, AND THE ACCESS OVER THE RUN. Both halves of that are the driver's rule
- * rather than a preference, and they pull in opposite directions:
- *
- *   A mapping can only be unbacked exactly as it was backed, so a run mapped in one call is a run
- *   that can only be released whole. Mapping the granules separately is what lets a pool hand back
- *   the top of its range while it keeps the rest, which is the entire purpose of an elastic pool.
- *
- *   Access, though, cannot be granted per granule: a granule that sits against an already-
- *   accessible one is refused on its own and accepted as part of the contiguous run containing
- *   both. So the maps are named one at a time and the access is named once, over every extent the
- *   new granules ended up part of -- which add_extent has already merged by then. Re-granting
- *   access over a range that has it is free and is what makes that simple. */
+ * Driver rules:
+ *   - A mapping can only be unbacked exactly as it was backed, so each granule is mapped
+ *     separately; that lets the pool hand back the top of its range.
+ *   - Access cannot be granted per granule: a granule adjacent to an accessible one is refused on
+ *     its own. Access is granted once per merged extent the new granules belong to; re-granting
+ *     access to a range is free. */
 int VMem::commit(int64_t off, int64_t bytes) {
     if (!base_ || bytes <= 0) return bytes <= 0 ? RAD_OK : RAD_E_INVAL;
     const int64_t g = granularity();
     if (g <= 0) return RAD_E_UNSUPPORTED;
-    /* OUTWARD: the caller asked for these bytes and must get all of them. */
+    /* Round outward: every requested byte must be committed. */
     const int64_t lo = (off < 0 ? 0 : off / g * g);
     int64_t hi = align_up(off + bytes, g);
     if (hi > size_) hi = size_;
@@ -343,9 +306,8 @@ int VMem::commit(int64_t off, int64_t bytes) {
         if (!is_committed(o, g)) want.push_back(o);
     if (want.empty()) return RAD_OK;
 
-    /* A failure part way through leaves what already mapped mapped AND RECORDED. Half a grow is a
-     * smaller pool, which the caller can live with; half a grow the bookkeeping has forgotten is
-     * memory this process can neither use nor return. */
+    /* On a failure part way, what already mapped stays mapped and recorded: a partial grow is
+     * usable, untracked mappings are not. */
     int rc = RAD_OK;
     size_t took = 0;
     for (; took < want.size(); ++took) {
@@ -354,9 +316,7 @@ int VMem::commit(int64_t off, int64_t bytes) {
         add_extent(want[took], g);
     }
 
-    /* AND THE ACCESS IS GRANTED EVEN WHEN THE GROW STOPPED SHORT, for the same reason. A pool that
-     * got half of what it asked for is one the caller can live with; one whose new granules are
-     * mapped and unreachable is not, and the granules that did map are in the run either way. */
+    /* Grant access even if the grow stopped short, so the granules that did map are usable. */
     int prc = RAD_OK;
     if (took > 0 && dev()->vmem_protect) {
         for (const auto& e : ext_) {
@@ -366,9 +326,8 @@ int VMem::commit(int64_t off, int64_t bytes) {
         }
     }
     if (prc < 0) {
-        /* MAPPED BUT UNREACHABLE IS WORSE THAN NOT MAPPED: the VRAM is spent and the first kernel
-         * to touch it faults. Give back exactly what this call took and leave the rest, which is
-         * reachable and was before. */
+        /* Mapped but inaccessible memory faults the first kernel that touches it. Undo exactly
+         * what this call mapped; earlier extents were already accessible. */
         for (size_t i = 0; i < took; ++i) {
             if (dev()->vmem_decommit) (void)dev()->vmem_decommit((char*)base_ + want[i], g);
             drop_extent(want[i], g);
@@ -382,14 +341,13 @@ int VMem::decommit(int64_t off, int64_t bytes) {
     if (!base_ || bytes <= 0) return bytes <= 0 ? RAD_OK : RAD_E_INVAL;
     const int64_t g = granularity();
     if (g <= 0) return RAD_E_UNSUPPORTED;
-    /* INWARD: a granule holding one byte the caller still wants stays. */
+    /* Round inward: a granule holding any byte outside the range stays. */
     const int64_t lo = align_up(off < 0 ? 0 : off, g);
     int64_t hi = (off + bytes) / g * g;
     if (hi > size_) hi = size_;
     if (lo >= hi) return RAD_OK;
 
-    /* Gathered first, for the same reason as commit, and unmapped one granule at a time because
-     * that is how each was mapped. */
+    /* Gathered first and unmapped per granule, as in commit. */
     std::vector drop;
     for (int64_t o = lo; o < hi; o += g)
         if (is_committed(o, g)) drop.push_back(o);
@@ -405,9 +363,8 @@ int VMem::decommit(int64_t off, int64_t bytes) {
 void VMem::add_extent(int64_t off, int64_t bytes) {
     committed_ += bytes;
     g_vmem_committed.fetch_add(bytes, std::memory_order_relaxed);
-    /* Insert in order, then absorb any neighbour it touches. Merging is not cosmetic: an extent
-     * list that grows by one per commit turns is_committed() into a scan of every call ever made,
-     * and the pool that uses this grows a granule at a time. */
+    /* Insert in order, then merge touching neighbours, so is_committed() stays a short scan
+     * although pools grow one granule at a time. */
     size_t i = 0;
     while (i < ext_.size() && ext_[i].first < off) ++i;
     ext_.insert(ext_.begin() + (long)i, { off, bytes });
@@ -423,9 +380,8 @@ void VMem::add_extent(int64_t off, int64_t bytes) {
     }
 }
 
-/* The inverse, and it takes a piece that lies WHOLLY INSIDE one extent by construction -- decommit
- * clips every part it gathers to the extent it came from. What is left of that extent is nothing,
- * a head, a tail, or both. */
+/* Precondition: the piece lies wholly inside one extent (decommit only drops committed granules).
+ * What remains of that extent is nothing, a head, a tail, or both. */
 void VMem::drop_extent(int64_t off, int64_t bytes) {
     committed_ -= bytes;
     g_vmem_committed.fetch_sub(bytes, std::memory_order_relaxed);
@@ -460,12 +416,11 @@ int  rad_dev_props(int device, RadDeviceProps* o)  { return dev()->props(device,
 int  rad_dev_enable_peer(int self, int peer)      { return dev()->enable_peer(self, peer); }
 
 void* rad_dev_alloc(int64_t bytes, int kind) {
-    /* The poison range is over THIS THREAD's device allocations, because a rank brings itself up on
-     * its own thread in a fixed order while the threads interleave freely: a process-wide ordinal
-     * would name a different allocation on every run, and a bisect over it would not converge. */
+    /* Poison ordinals are per thread: each rank allocates in a fixed order on its own thread, but
+     * threads interleave, so a process-wide ordinal would not be repeatable. */
     thread_local int64_t t_device_ordinal = 0;
     void* p = dev()->alloc(bytes, kind);
-    if (p && kind >= 0 && kind < 4) {
+    if (p && kind >= 0 && kind < (int)std::size(rad::g_ledger)) {
         rad::g_ledger[kind].bytes.fetch_add(bytes, std::memory_order_relaxed);
         const int64_t total = rad::g_ledger[kind].count.fetch_add(1, std::memory_order_relaxed) + 1;
         const int64_t ordinal = kind == RAD_MEM_DEVICE ? ++t_device_ordinal : total;
@@ -475,8 +430,7 @@ void* rad_dev_alloc(int64_t bytes, int kind) {
                      rad::kind_name(kind), rad::humanb(bytes).c_str(), (long long)ordinal,
                      (long long)rad::g_ledger[kind].bytes.load(std::memory_order_relaxed),
                      (long long)total);
-        /* The poison fill (see the top of this file). Through the backend's own stream so it
-         * holds on both backends; synchronous, so the bytes are there before the caller sees p. */
+        /* Poison fill (see the ledger header): synchronous, so it lands before p is returned. */
         const int poison = rad::poison_byte();
         if (poison >= 0 && kind == RAD_MEM_DEVICE && rad::poison_in_range(ordinal)) {
             RadStream& s = t_poison_stream[t_device];
@@ -493,9 +447,8 @@ void* rad_dev_alloc(int64_t bytes, int kind) {
     return p;
 }
 void  rad_dev_free(void* p, int kind) {
-    /* The ledger tracks what was TAKEN, not what is live: rad_dev_free has no size and the
-     * backends do not keep one. Every caller in this engine frees at teardown and nowhere else,
-     * so the two numbers differ only after the run is over. */
+    /* The ledger counts allocations, not live bytes: rad_dev_free has no size. The engine frees
+     * only at teardown, so the two agree while running. */
     dev()->free(p, kind);
 }
 void* rad_dev_host_ptr(void* p)                   { return dev()->host_ptr(p); }
@@ -503,7 +456,10 @@ void* rad_dev_device_ptr(void* p)                 { return dev()->device_ptr(p);
 
 int  rad_stream_create(RadStream* out, int hi)    { return dev()->stream_create(out, hi); }
 void rad_stream_destroy(RadStream s)              { dev()->stream_destroy(s); }
-int  rad_stream_sync(RadStream s)                 { return dev()->stream_sync(s); }
+int  rad_stream_sync(RadStream s) {
+    rad::g_host_blocks.fetch_add(1, std::memory_order_relaxed);
+    return dev()->stream_sync(s);
+}
 
 }  /* extern "C" */
 
@@ -537,38 +493,29 @@ int     tape_set_overlap(RadTape t, int i, bool on) {
     return dev()->tape_set_overlap ? dev()->tape_set_overlap(t, i, on ? 1 : 0) : RAD_E_UNSUPPORTED;
 }
 bool    dev_integrated(int device) { return dev()->integrated && dev()->integrated(device) > 0; }
-/* A FAILURE ANSWERED HERE, as "", is not one for the next reader of rad_dev_last_error: that
- * reader is reporting a failure of its own and would name this one instead. The slot is put back
- * as the call found it. */
-std::string dev_pci_address(int device) {
-    char buf[64] = { 0 };
-    if (!dev()->pci_address) return std::string();
+/* These getters answer "" on failure and restore the error slot, so the next
+ * rad_dev_last_error reader does not see an unrelated error. `get` fills a buffer of `n` bytes. */
+template  static std::string dev_string(int n, Get get) {
+    std::string buf((size_t)n, '\0');
     const std::string before = t_last_error;
-    if (dev()->pci_address(device, buf, (int)sizeof buf) < 0) {
+    if (get(buf.data(), n) < 0) {
         t_last_error = before;
         return std::string();
     }
+    buf.resize(std::strlen(buf.c_str()));
     return buf;
 }
+std::string dev_pci_address(int device) {
+    if (!dev()->pci_address) return std::string();
+    return dev_string(64, [&](char* b, int n) { return dev()->pci_address(device, b, n); });
+}
 std::string dev_dma_lane(int device) {
-    char buf[256] = { 0 };
     if (!dev()->dma_lane) return std::string();
-    const std::string before = t_last_error;
-    if (dev()->dma_lane(device, buf, (int)sizeof buf) < 0) {
-        t_last_error = before;
-        return std::string();
-    }
-    return buf;
+    return dev_string(256, [&](char* b, int n) { return dev()->dma_lane(device, b, n); });
 }
 std::string dev_runtime_version() {
-    char buf[128] = { 0 };
     if (!dev()->runtime_version) return std::string();
-    const std::string before = t_last_error;
-    if (dev()->runtime_version(buf, (int)sizeof buf) < 0) {
-        t_last_error = before;
-        return std::string();
-    }
-    return buf;
+    return dev_string(128, [&](char* b, int n) { return dev()->runtime_version(b, n); });
 }
 int     dev_peer_access(int self, int peer) {
     if (self == peer) return 1;
@@ -604,7 +551,10 @@ void rad_event_destroy(RadEvent e) {
 int  rad_event_record(RadEvent e, RadStream s)    { return dev()->event_record(e, s); }
 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)                   { return dev()->event_sync(e); }
+int  rad_event_sync(RadEvent e) {
+    rad::g_host_blocks.fetch_add(1, std::memory_order_relaxed);
+    return dev()->event_sync(e);
+}
 void rad_dev_host_wrote(void)                     { dev()->host_wrote(); }
 int  rad_event_elapsed_ms(RadEvent a, RadEvent b, float* out) {
     return dev()->event_elapsed_ms(a, b, out);
@@ -673,9 +623,22 @@ void* rad_dev_alloc_uncached(int64_t bytes) {
 void rad_dev_free_uncached(void* p) {
     if (const auto f = dev()->free_uncached) f(p);
 }
+int rad_stream_gate(RadStream s, void** gate) {
+    if (gate) *gate = nullptr;
+    if (const auto f = dev()->stream_gate) return f(s, gate);
+    rad::device_set_error("rad_stream_gate: the %s backend has no gates", dev()->name);
+    return RAD_E_UNSUPPORTED;
+}
+int rad_gate_open(void* gate) {
+    if (const auto f = dev()->gate_open) return f(gate);
+    return RAD_E_UNSUPPORTED;
+}
+int64_t rad_gate_room(RadStream s) {
+    if (const auto f = dev()->gate_room) return f(s);
+    return 0;
+}
 
-/* Cleared by reading it, per the header. Never null: a caller printing "%s" on a path where
- * nothing failed should get an empty line, not a segfault. */
+/* Cleared by reading. Never null; "" when nothing failed. */
 const char* rad_dev_last_error(void) {
     static thread_local std::string drained;
     drained.swap(rad::t_last_error);
diff --git a/core/device/hip.cpp b/core/device/hip.cpp
index 2f440bfa..0ee6e91d 100644
--- a/core/device/hip.cpp
+++ b/core/device/hip.cpp
@@ -1,16 +1,14 @@
 /* hip.cpp -- the HIP half of the device backend: devices, memory and elastic memory.
  *
- * Streams, events, copies and fills are not here. They are AQL packets the engine writes into
- * queues it owns (aql.cpp), which starts from this table and fills in the rest -- pinned host
- * memory included, because the copies have to recognise it.
+ * Streams, events, copies and fills are AQL packets on engine-owned queues (aql.cpp), which
+ * starts from this table and fills in the rest, pinned host memory included because the copies
+ * must recognise it.
  *
- * Thin by design. Every entry point is one hip* call plus an error capture, because anything
- * cleverer than that is a place where the host backend and this one can disagree, and the host
- * backend is where all of it is tested (docs/IMPLEMENTATION.md). If a call here grows a policy,
- * the policy belongs in the component that wanted it, not in the device layer.
+ * Thin by design: each entry point is one hip* call plus error capture, so it cannot diverge from
+ * the host backend, where the logic is tested (docs/IMPLEMENTATION.md). Policy belongs in the
+ * component that wants it.
  *
- * The whole file compiles to nothing without RAD_HAVE_HIP, so a no-ROCm configure builds it and
- * gets an empty object rather than needing the source list to know about the backend split.
+ * Compiles to nothing without RAD_HAVE_HIP, so the source list needs no backend split.
  */
 #include "device.h"
 
@@ -36,9 +34,7 @@
 namespace rad {
 namespace {
 
-/* One place that turns a hipError_t into a RAD_E_*. The mapping is coarse on purpose: the string
- * carries the detail, the code carries the class, and a caller that wants to know exactly what the
- * driver said reads rad_dev_last_error(). */
+/* Maps a hipError_t to a coarse RAD_E_* class; the detail goes to rad_dev_last_error(). */
 int hip_fail(hipError_t e, const char* who) {
     device_set_error("%s: %s (%s)", who, hipGetErrorString(e), hipGetErrorName(e));
     switch (e) {
@@ -55,9 +51,8 @@ int hip_fail(hipError_t e, const char* who) {
     do { hipError_t _e = (call);                                                 \
          if (_e != hipSuccess) return hip_fail(_e, #call); } while (0)
 
-/* For the calls whose caller returns void -- the frees and the destroys. A failing teardown is
- * still worth naming: hipFree returning anything but success means the pointer was not what the
- * caller thought it was, and the next allocation of that class is the one that will look wrong. */
+/* For void callers (frees, destroys): a failing teardown is still logged, since it means the
+ * pointer was not what the caller thought. */
 void hip_note(hipError_t e, const char* who) {
     if (e != hipSuccess) RAD_WARN("device: %s: %s", who, hipGetErrorString(e));
 }
@@ -79,24 +74,14 @@ int d_set(int device) {
 
 /* ------------------------------------------------------------------ how much VRAM is really free
  *
- * hipMemGetInfo IS NOT THE ANSWER ON THIS DRIVER, and the error is large enough to pay for.
+ * On a card that also drives a display, hipMemGetInfo's "free" sits up to 0.7 GiB below the
+ * amdgpu driver's own per-card accounting, and that gap is allocatable. So read the driver's
+ * counters (bytes, per card, all processes) from the drm node matched by PCI slot. The node's
+ * total must equal HIP's total, so both describe the same memory; any failure returns -1 and the
+ * caller keeps hipMemGetInfo. -1 on every non-amdgpu platform.
  *
- * On a card that also drives a display, hipMemGetInfo's "free" sits up to 0.7 GiB below what the
- * amdgpu driver's own per-card accounting reports as unused -- while two otherwise identical cards
- * differ by only tens of MiB in the driver's numbers. That gap is not memory anything holds: a run
- * budgeted past hipMemGetInfo's figure allocates all of it and serves, with sysfs still reporting
- * hundreds of MiB unused afterwards. Believing HIP's number costs that 0.7 GiB, which on a model
- * whose experts do not fit is most of a millisecond a decode step.
- *
- * amdgpu publishes its own accounting, in bytes, per card, counting every process on it. Match the
- * HIP device to a drm node by PCI slot and read it. Two guards: the node's total must equal the
- * total HIP reports, so the two accountings are known to be the same accounting, and any failure
- * at any step falls back to hipMemGetInfo rather than inventing a number.
- *
- * Returns -1 when sysfs cannot answer, which is every non-amdgpu platform.
- *
- * The node's `mem_info_vram_used` is also kept open, per device, for d_vram_used: an observer
- * reads the card through that one descriptor and never through the runtime. */
+ * The node's `mem_info_vram_used` is also kept open per device for d_vram_used, so an observer
+ * reads the card through that descriptor and never through the runtime. */
 constexpr int kMaxVramNodes = 64;
 std::atomic g_vram_used_fd[kMaxVramNodes] = {};   /* 0: not opened; else the fd plus one */
 
@@ -144,8 +129,7 @@ static int64_t sysfs_vram_free(int device, int64_t total) {
     }
     return -1;
 }
-/* A sysfs attribute is regenerated by a read at offset 0, so the descriptor is read with pread and
- * never moved. */
+/* A sysfs attribute is regenerated by a read at offset 0, so read with pread at 0. */
 int d_vram_used(int device, int64_t* out) {
     if (!out || device < 0 || device >= kMaxVramNodes) return RAD_E_INVAL;
     const int fd = g_vram_used_fd[device].load(std::memory_order_acquire) - 1;
@@ -166,8 +150,7 @@ int d_integrated(int device) {
     return hipDeviceGetAttribute(&v, hipDeviceAttributeIntegrated, device) == hipSuccess ? v : 0;
 }
 
-/* /proc/meminfo's MemAvailable: what the host could still hand out without swapping, -1 when it
- * cannot be read. */
+/* /proc/meminfo's MemAvailable in bytes, or -1. */
 static int64_t host_mem_available() {
     FILE* f = std::fopen("/proc/meminfo", "r");
     if (!f) return -1;
@@ -185,17 +168,12 @@ int d_props(int device, RadDeviceProps* out) {
     HIP_TRY(hipGetDeviceProperties(&p, device));
     std::memset(out, 0, sizeof *out);
 
-    /* TRUNCATION IS INTENDED AND IS SAID SO. HIP's name and gcnArchName are 256 bytes each and
-     * these fields are 128 and 32; snprintf would cut them safely anyway, but silently enough that
-     * gcc warns about it, and a build that carries a warning nobody intends to act on is a build
-     * whose warnings stop being read. The explicit precision is the same cut, declared. Real
-     * values are far inside both -- a product name and a gcnArchName run to a couple of dozen
-     * characters -- so this is about the bound, not about the data. */
+    /* Intended truncation: HIP's fields are 256 bytes, ours 128 and 32. The explicit precision
+     * silences gcc's truncation warning; real values are a few dozen characters. */
     snprintf(out->name, sizeof out->name, "%.*s", (int)(sizeof out->name) - 1, p.name);
     snprintf(out->arch, sizeof out->arch, "%.*s", (int)(sizeof out->arch) - 1, p.gcnArchName);
-    /* gcnArchName carries the feature suffixes -- "gfx1201:sramecc-:xnack-". The arch a kernel
-     * plugin's constraints match on is the bare target, so cut at the colon here rather than
-     * making every consumer do it. */
+    /* Strip feature suffixes ("gfx1201:sramecc-:xnack-"): plugin constraints match the bare
+     * target. */
     if (char* c = std::strchr(out->arch, ':')) *c = '\0';
 
     out->device_id  = device;
@@ -205,10 +183,8 @@ int d_props(int device, RadDeviceProps* out) {
     out->lds_bytes  = (int64_t)p.sharedMemPerBlock;
     out->is_host_backend = 0;
 
-    /* hipMemGetInfo reports the CURRENT device, so ask about `device` by visiting it. That costs
-     * two context switches on a call nobody makes per step -- props is read at startup and by
-     * rad-info -- and the alternative is a vram_free that silently describes the wrong card under
-     * tensor parallel. */
+    /* hipMemGetInfo reports the current device, so switch to `device` and back. props is not
+     * called per step. */
     int prev = 0;
     bool moved = false;
     if (hipGetDevice(&prev) == hipSuccess && prev != device &&
@@ -219,30 +195,24 @@ int d_props(int device, RadDeviceProps* out) {
         out->vram_free = (int64_t)freeb;
         if (totalb) out->vram_bytes = (int64_t)totalb;
     }
-    /* And then prefer the driver's own counter where it can be read -- see sysfs_vram_free. The
-     * fallback above is what every non-amdgpu platform gets; it is conservative by up to a GiB on
-     * a card that drives a display. */
+    /* Prefer the driver's counter where readable (see sysfs_vram_free). */
     {
         const int64_t sf = sysfs_vram_free(device, out->vram_bytes);
         if (sf >= 0) {
             out->vram_free = sf;
         } else if (d_integrated(device)) {
-            /* INTEGRATED GRAPHICS WHOSE "DEVICE MEMORY" IS THE HOST'S. When the runtime reports
-             * more than the carve-out the driver counts as VRAM, the rest is system RAM mapped for
-             * the GPU, and the runtime's free figure knows nothing of the other processes using
-             * it: a budget derived from it claims memory the machine is already running on. What
-             * the host can still give is the bound. A carve-out the runtime reports as it is --
-             * the case sysfs answers above -- is dedicated memory and is left alone. */
+            /* Integrated GPU whose reported memory exceeds the driver's carve-out: the rest is
+             * system RAM, and the runtime's free figure ignores other processes using it. Bound
+             * it by MemAvailable. (A carve-out reported as-is is answered by sysfs above.) */
             const int64_t avail = host_mem_available();
             if (avail >= 0 && avail < out->vram_free) out->vram_free = avail;
         }
     }
-    /* A failed restore leaves this thread pointed at the wrong card, which under tensor parallel
-     * is a rank quietly working on its neighbour's memory. Say so. */
+    /* A failed restore leaves this thread on the wrong card; under TP that is a rank working on
+     * its neighbour's memory, so it is logged. */
     if (moved) HIP_NOTE(hipSetDevice(prev));
 
-    /* Whether any peer is reachable at all. The engine asks for a specific pair through
-     * rad_dev_enable_peer; this flag is for the report. */
+    /* Whether any peer is reachable, for the report; pairs go through rad_dev_enable_peer. */
     int n = d_count();
     for (int i = 0; i < n && !out->supports_p2p; ++i) {
         if (i == device) continue;
@@ -258,8 +228,8 @@ int d_peer_access(int self, int peer) {
     return can ? 1 : 0;
 }
 
-/* The runtime's bus id, rewritten in the kernel's spelling (lower case, four-digit domain) so it
- * names the same directory under /sys/bus/pci/devices. */
+/* The runtime's bus id in the kernel's spelling (lower case, four-digit domain), matching
+ * /sys/bus/pci/devices. */
 int d_pci_address(int device, char* out, int cap) {
     if (!out || cap <= 0) return RAD_E_INVAL;
     char bus[64] = { 0 };
@@ -297,8 +267,8 @@ int d_enable_peer(int self, int peer) {
     HIP_TRY(hipSetDevice(self));
     hipError_t e = hipDeviceEnablePeerAccess(peer, 0);
     HIP_NOTE(hipSetDevice(prev));
-    /* Already enabled is success. The kernel plugin's init() hook runs per resolved instance
-     * (spec §2.1) and several instances legitimately want the same pair. */
+    /* Already enabled is success: init() runs per resolved instance (spec §2.1) and several may
+     * want the same pair. */
     if (e != hipSuccess && e != hipErrorPeerAccessAlreadyEnabled)
         return hip_fail(e, "hipDeviceEnablePeerAccess");
     return RAD_OK;
@@ -319,12 +289,11 @@ void* d_alloc(int64_t bytes, int kind) {
             break;
         case RAD_MEM_HOST_PINNED:
         case RAD_MEM_HOST_MAPPED:
-            /* The AQL backend's, which pins host memory through ROCr in pieces the IOMMU can map
-             * (aql.cpp, "pinned host memory, in pieces"). */
+            /* Pinned by the AQL backend through ROCr (aql.cpp, "pinned host memory, in pieces"). */
             device_set_error("rad_dev_alloc: pinned host memory is the AQL backend's");
             return nullptr;
         case RAD_MEM_HOST:
-            /* Pageable. Aligned to a page anyway so the same buffer can be an O_DIRECT target. */
+            /* Pageable, page-aligned so it can be an O_DIRECT target. */
             if (posix_memalign(&p, 4096, (size_t)((bytes + 4095) / 4096 * 4096)) != 0) p = nullptr;
             if (!p) e = hipErrorOutOfMemory;
             break;
@@ -367,7 +336,7 @@ void* d_device_ptr(void* p) {
     hipPointerAttribute_t a{};
     if (hipPointerGetAttributes(&a, p) != hipSuccess) return nullptr;
     if (a.devicePointer) return a.devicePointer;
-    /* A mapped host allocation that the attribute query did not resolve: ask the explicit way. */
+    /* Mapped host allocation not resolved by the attribute query. */
     void* d = nullptr;
     if (hipHostGetDevicePointer(&d, p, 0) == hipSuccess) return d;
     return nullptr;
@@ -378,22 +347,20 @@ const DeviceBackend g_hip = {
     "hip",
     d_count, d_set, d_props, d_enable_peer,
     d_alloc, d_free, d_host_ptr, d_device_ptr,
-    /* Streams, events, copies and fills: the AQL backend's (aql.cpp), which starts from this
-     * table and fills these in. */
+    /* Streams, events, copies and fills: filled in by the AQL backend (aql.cpp). */
     nullptr, nullptr, nullptr,
     nullptr, nullptr, nullptr, nullptr,
     nullptr, nullptr, nullptr,
     nullptr,
     nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
-    /* Recorded passes: likewise the AQL backend's. */
+    /* Recorded passes: AQL backend. */
     nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
 
-    /* Elastic memory: likewise the AQL backend's, which reserves and backs ranges through HSA
-     * (aql.cpp, "elastic memory, through HSA"). */
+    /* Elastic memory: AQL backend, through HSA (aql.cpp, "elastic memory, through HSA"). */
     nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
 
     d_vram_used,
-    /* Plugin device code: the AQL backend's, which owns the fat-binary registrations. */
+    /* Plugin device code: AQL backend, which owns the fat-binary registrations. */
     nullptr, nullptr,
     d_integrated,
     d_peer_access,
@@ -409,8 +376,7 @@ const DeviceBackend* hip_backend_if_present(void) {
     int n = 0;
     hipError_t e = hipGetDeviceCount(&n);
     if (e != hipSuccess || n <= 0) {
-        /* Not an error and not a warning: a HIP build on a machine with no visible card is a
-         * supported configuration, it is just the host one. dispatch.cpp says so at Info. */
+        /* Supported configuration (host backend); dispatch.cpp logs it at Info. */
         RAD_DEBUG("device: hipGetDeviceCount -> %s, %d device(s)", hipGetErrorName(e), n);
         return nullptr;
     }
diff --git a/core/device/host.cpp b/core/device/host.cpp
index 702b7a92..d404a2bb 100644
--- a/core/device/host.cpp
+++ b/core/device/host.cpp
@@ -1,24 +1,16 @@
 /* host.cpp -- the host device backend.
  *
- * This is a primary development target, not a fallback. On a machine with no ROCm the builder, the
- * planner, the mover, the scheduler, the KV manager, the tokeniser, the sampler's host reference
- * chain and the server all run and are tested through these fourteen calls
- * (docs/IMPLEMENTATION.md). It is also the code path a RAD_DOMAIN_HOST kernel runs on when the
- * planner puts a layer on the CPU, which is the fourth row of spec §5.1's table.
+ * A primary development target, not a fallback: without ROCm the whole engine (builder, planner,
+ * mover, scheduler, KV manager, tokeniser, sampler host reference, server) runs and is tested
+ * through these calls (docs/IMPLEMENTATION.md). It is also where RAD_DOMAIN_HOST kernels run when
+ * the planner puts a layer on the CPU (spec §5.1).
  *
- * The one design decision worth defending: **the streams are real.** Each stream is an in-order
- * work queue with its own worker thread, and an event is a sequence number that a stream reaches.
- * A backend whose "async" calls execute inline would let ordering bugs -- a missing
- * rad_event_wait, a buffer reused before the mover's copy landed -- pass every test here and
- * corrupt weights on a real device. The cost is one thread per stream and one condition-variable
- * wake per enqueue, which is nothing against the value of exercising the contract the HIP backend
- * actually has.
+ * The streams are real: each is an in-order queue with its own worker thread, and an event is a
+ * sequence number the stream reaches. Inline "async" calls would let ordering bugs (a missing
+ * rad_event_wait, a buffer reused before a copy landed) pass here and corrupt a real device.
  *
- * The second: **no allocation on the step path.** The mover enqueues a transfer per weight per
- * layer dispatch, so the queue is a fixed-capacity ring of POD tasks sized at stream creation, not
- * a deque of std::function. A std::function holding a destination, a source and a length does not
- * fit libstdc++'s small-object buffer and would call operator new inside rad_memcpy_async, which
- * is exactly the thing docs/IMPLEMENTATION.md forbids on the step path.
+ * No allocation on the step path: the queue is a fixed-capacity ring of POD tasks, not
+ * std::function, which would heap-allocate inside rad_memcpy_async.
  */
 #include "device.h"
 #include "../rad_internal.h"
@@ -41,36 +33,27 @@ namespace {
 
 using Clock = std::chrono::steady_clock;
 
-/* Every allocation kind maps to page-aligned host memory. 4096 is not arbitrary: it is
- * RAD_ALIGN_UNIT, the .rad container's movement unit, and it is what O_DIRECT demands of a buffer
- * (directio.cpp), so a pinned pool allocated here is directly usable as a file-tier landing zone
- * with no bounce. */
+/* Every allocation kind is page-aligned host memory. 4096 is RAD_ALIGN_UNIT and the O_DIRECT
+ * buffer alignment (directio.cpp), so pools here are file-tier targets without a bounce. */
 constexpr int64_t kAlign = 4096;
 
-/* A stream's queue depth. Deep enough that a layer dispatch's worth of mover transfers plus the
- * compute stream's issues never touch the backpressure path; shallow enough that the ring is a
- * few tens of KiB. Enqueue onto a full ring blocks, which is honest -- a saturated hardware queue
- * does the same thing -- and it is the only place in this file a caller can be made to wait. */
+/* Per-stream queue depth: enough that a layer's mover transfers plus compute issues never hit
+ * backpressure, small enough for a ring of a few tens of KiB. Enqueue onto a full ring blocks, as
+ * on a saturated hardware queue. */
 constexpr size_t kQueueDepth = 1024;
 
-/* Tensor-parallel world sizes past 8 are not served: libr4d supplies 2/4/8-rank all-reduce and
- * nothing wider (spec §9), so a fake host backend that claimed 16 cards would only ever produce a
- * declare-time miss further down. */
+/* libr4d all-reduce supports at most 8 ranks (spec §9), so more fake devices are useless. */
 constexpr int kMaxFakeDevices = 8;
 
 /* ------------------------------------------------------------------ events */
 
-/* An event is a pair of sequence numbers. `recorded` advances on the host, at the moment
- * rad_event_record is called; `completed` advances on the stream's worker, when the queue reaches
- * that record. The event is complete when the second has caught the first, which is exactly HIP's
- * rule that re-recording an event makes it pending again.
+/* An event is two sequence numbers: `recorded` advances on the host at rad_event_record,
+ * `completed` on the stream worker when it reaches that record. Complete when completed has caught
+ * up, so re-recording makes it pending again, as in HIP.
  *
- * `refs` is one for the caller's handle plus one for every queued task that names the event.
- * HIP lets a caller destroy an event whose record or wait is still queued -- the call returns and
- * the resources go once the queue is past them -- and teardown code written against a card does
- * exactly that. Freeing the object at rad_event_destroy instead leaves those tasks pointing at
- * freed memory, and the worker that reaches one locks a mutex whose bytes the allocator has
- * overwritten: the stream wedges and the rad_stream_destroy behind it never returns. */
+ * `refs` counts the handle plus every queued task naming the event. HIP allows destroying an event
+ * whose record or wait is still queued; freeing it at destroy would leave the worker locking a
+ * freed mutex and wedge the stream. */
 struct HostEvent {
     std::mutex              m;
     std::condition_variable cv;
@@ -83,7 +66,7 @@ struct HostEvent {
 
 void event_retain(HostEvent* e) { e->refs.fetch_add(1, std::memory_order_relaxed); }
 
-/* The last reference out frees it, whether that is the handle or the last task naming it. */
+/* The last reference, handle or task, frees it. */
 void event_release(HostEvent* e) {
     if (e->refs.fetch_sub(1, std::memory_order_acq_rel) == 1) delete e;
 }
@@ -116,17 +99,23 @@ struct HostStream {
 
     uint64_t submitted = 0;            /* tasks ever pushed */
     uint64_t retired   = 0;            /* tasks ever finished executing */
+    int      gates     = 0;            /* closed gates (rad_stream_gate) queued on this stream */
 
     std::thread worker;
 };
 
 void stream_run(HostStream* s);
 
-/* Push one task, blocking while the ring is full; see kQueueDepth. Always succeeds -- there is no
- * "stream is closing" state to report, because rad_stream_destroy queues its stop behind the work
- * already submitted rather than racing it. */
+/* Push one task, blocking while the ring is full. Fails only behind a closed gate: the ring cannot
+ * drain until the host opens it, and the host is the caller. Destroy queues its stop behind
+ * submitted work, so there is no closing state. */
 int stream_push(HostStream* s, const Task& t) {
     std::unique_lock lk(s->m);
+    if (s->count >= s->ring.size() && s->gates > 0) {
+        device_set_error("a submission onto a full stream behind a closed gate: open the gate "
+                         "(rad_gate_open) first");
+        return RAD_E_STATE;
+    }
     s->cv_room.wait(lk, [s] { return s->count < s->ring.size(); });
     s->ring[s->tail] = t;
     s->tail = (s->tail + 1) % s->ring.size();
@@ -156,9 +145,7 @@ void stream_run(HostStream* s) {
                 break;
 
             case Task::Copy2D:
-                /* a = dpitch, b = spitch, c = width bytes, d = height rows. Row by row, because
-                 * the pitches are what make a 2D copy a 2D copy: a KV block's rows are strided by
-                 * the pool's row pitch, not packed. */
+                /* a = dpitch, b = spitch, c = width bytes, d = height rows. */
                 for (int64_t r = 0; r < t.d; ++r)
                     std::memcpy((uint8_t*)t.dst + r * t.a, (const uint8_t*)t.src + r * t.b,
                                 (size_t)t.c);
@@ -189,10 +176,8 @@ void stream_run(HostStream* s) {
             }
 
             case Task::Wait: {
-                /* The worker blocks here, which is the whole point: no host thread synchronises,
-                 * the *stream* does (spec §5.4). A wait whose event is only ever recorded later on
-                 * this same stream wedges the stream -- which is precisely what the same construction
-                 * does to a hardware queue, so it is a bug to catch, not a case to smooth over. */
+                /* The stream blocks, not a host thread (spec §5.4). Waiting on an event recorded
+                 * later on this same stream wedges it, as it would a hardware queue. */
                 std::unique_lock lk(t.ev->m);
                 t.ev->cv.wait(lk, [&t] { return t.ev->completed >= t.seq; });
                 break;
@@ -202,7 +187,7 @@ void stream_run(HostStream* s) {
                 done = true;
                 break;
         }
-        /* After the task's lock has gone out of scope: this may be the last reference. */
+        /* After the event lock is released: this may be the last reference. */
         if (t.ev) event_release(t.ev);
 
         {
@@ -228,33 +213,24 @@ std::unordered_map&      alloc_table() {
     return t;
 }
 
-/* Per-device VRAM accounting, so rad_dev_props reports a vram_free that moves. The placement
- * planner's "did it fit" path is one of the things the host backend exists to exercise, and a
- * constant vram_free would let a plan that overcommits a real card pass here (spec §5.3). */
+/* Per-device VRAM accounting, so vram_free moves and the planner's fit checks are exercised
+ * (spec §5.3). */
 std::atomic g_used[kMaxFakeDevices];
 
-/* A map lookup under a mutex on every alloc and free is fine and stays fine: allocation happens at
- * load and at pool construction, never inside rad_arch_step. If that ever changes, it is a
- * declare-phase bug and this mutex is where it will show up. */
+/* A mutex-guarded map is fine: allocation happens at load and pool construction, never inside
+ * rad_arch_step. */
 void alloc_note(void* p, int64_t bytes, int kind, int device) {
     std::lock_guard lk(alloc_mutex());
     alloc_table()[p] = AllocRec{bytes, kind, device};
 }
 
-bool alloc_take(void* p, AllocRec* out) {
-    std::lock_guard lk(alloc_mutex());
-    auto it = alloc_table().find(p);
-    if (it == alloc_table().end()) return false;
-    *out = it->second;
-    alloc_table().erase(it);
-    return true;
-}
-
-bool alloc_find(void* p, AllocRec* out) {
+/* The record of allocation `p`, removed from the table when `take`. */
+bool alloc_find(void* p, AllocRec* out, bool take = false) {
     std::lock_guard lk(alloc_mutex());
     auto it = alloc_table().find(p);
     if (it == alloc_table().end()) return false;
     *out = it->second;
+    if (take) alloc_table().erase(it);
     return true;
 }
 
@@ -273,9 +249,8 @@ int64_t env_i64(const char* key, int64_t dflt) {
 }
 
 int host_count() {
-    /* Memoised: the device count must not change under a rank thread that already called
-     * rad_dev_set. RADIANCE_HOST_DEVICES is how tensor-parallel code gets tested without two
-     * cards -- two ranks, two budgets, one address space (spec §9). */
+    /* Memoised so the count cannot change under a rank thread. RADIANCE_HOST_DEVICES fakes
+     * several devices in one address space for testing tensor parallel without cards (spec §9). */
     static int n = [] {
         int64_t v = env_i64("RADIANCE_HOST_DEVICES", 1);
         if (v < 1) v = 1;
@@ -289,9 +264,7 @@ int host_count() {
     return n;
 }
 
-/* Per-thread, matching hipSetDevice: spec §1 gives one thread per tensor-parallel rank, each
- * owning one device, so the current device is a property of the rank thread and never of the
- * process. */
+/* Per-thread, matching hipSetDevice: one thread per rank, one device per rank (spec §1). */
 thread_local int t_device = 0;
 
 int64_t physical_ram() {
@@ -300,12 +273,8 @@ int64_t physical_ram() {
     return (int64_t)pages * (int64_t)page;
 }
 
-/* The budget the placement planner plans against. Read on every call rather than memoised: props
- * is not on the step path, and re-reading is what lets a test set the budget and see it.
- *
- * The default is half of physical RAM, divided by the fake device count -- a two-"card" host
- * backend that each claimed half the machine would let a plan pass here that cannot be loaded, and
- * the planner is exactly the component this budget exists to falsify. */
+/* The fake per-device VRAM budget. Read on every call so a test can change it. Default: half of
+ * physical RAM, split across the fake devices so their sum is loadable. */
 int64_t host_vram_bytes() {
     int64_t mib = env_i64("RADIANCE_HOST_VRAM_MIB", 0);
     if (mib > 0) return mib << 20;
@@ -358,30 +327,23 @@ int h_props(int device, RadDeviceProps* out) {
     snprintf(out->arch, sizeof out->arch, "host");
     out->device_id = device;
 
-    /* Threads, divided the same way the budget is: a fake two-device backend on a 32-core box is
-     * two 16-"CU" devices, so a kernel plugin's occupancy arithmetic sees a coherent machine
-     * rather than two copies of the whole one. */
+    /* Hardware threads split across fake devices, like the budget. */
     unsigned hw = std::thread::hardware_concurrency();
     out->n_cu = (int)((hw ? hw : 1u) / (unsigned)host_count());
     if (out->n_cu < 1) out->n_cu = 1;
 
-    /* A host lane is one element wide. Any code that divides a tile by warp_size gets the honest
-     * answer for a scalar backend. */
+    /* A host lane is one element wide. */
     out->warp_size = 1;
 
     out->vram_bytes = host_vram_bytes();
     int64_t used = g_used[device].load(std::memory_order_relaxed);
     out->vram_free = out->vram_bytes > used ? out->vram_bytes - used : 0;
 
-    /* There is no LDS on a CPU, and this is a stand-in with one job. Budget arithmetic of the
-     * form "how many tiles fit in LDS" divides by this, and a zero would trap on the backend
-     * whose whole purpose is to run that arithmetic on a machine with no card. The figure is a
-     * conventional per-workgroup scratch budget, not a property of this machine: host kernels are
-     * not LDS-bound and must not read it as a limit. */
+    /* A CPU has no LDS. Nonzero because budget arithmetic divides by it; a conventional
+     * per-workgroup figure, not a limit host kernels should honour. */
     out->lds_bytes = 64 * 1024;
 
-    /* Every fake device shares one address space, so peer access is not merely available, it is
-     * the only thing there is. */
+    /* All fake devices share one address space. */
     out->supports_p2p = 1;
     out->is_host_backend = 1;
     return RAD_OK;
@@ -406,13 +368,9 @@ void* h_alloc(int64_t bytes, int kind) {
         return nullptr;
     }
     void* p = nullptr;
-    /* All four kinds are the same aligned host memory here. The distinction still matters and is
-     * still recorded, because the planner reasons in kinds and on a real device rad_dev_free has
-     * to give the right one back; the host backend's job is to make that code run, not to make the
-     * distinction vanish. */
-    /* Rounded up to a whole page as well as aligned to one, so a buffer handed to DirectFile can
-     * receive the aligned superset of a misaligned extent without overrunning. That is the same
-     * reason .rad pads its movement units to RAD_ALIGN_UNIT. */
+    /* All kinds are the same memory here, but the kind is recorded so mismatched frees are
+     * caught. The size is rounded up to whole pages so DirectFile can read an aligned superset
+     * into it without overrunning. */
     if (posix_memalign(&p, (size_t)kAlign, (size_t)align_up(bytes, kAlign)) != 0 || !p) {
         device_set_error("rad_dev_alloc(%lld, kind=%d): out of host memory",
                          (long long)bytes, kind);
@@ -427,9 +385,8 @@ void* h_alloc(int64_t bytes, int kind) {
 void h_free(void* p, int kind) {
     if (!p) return;
     AllocRec r;
-    if (!alloc_take(p, &r)) {
-        /* Not ours. Freeing it would be a heap corruption three frames later, which is the class of
-         * bug the plugin ABI's C-only rule exists to avoid; refuse loudly instead. */
+    if (!alloc_find(p, &r, /*take=*/true)) {
+        /* Not ours: freeing it would corrupt the heap, so refuse and warn. */
         RAD_WARN("rad_dev_free(%p, kind=%d): pointer was not allocated by the device layer",
                  p, kind);
         return;
@@ -440,10 +397,8 @@ void h_free(void* p, int kind) {
     std::free(p);
 }
 
-/* Both views are the same pointer: on this backend the zero-copy execution site of spec §5.1 is
- * degenerate, and that is the correct answer rather than a shortcut -- the bytes really are
- * reachable from both sides without a transfer. Null for a pointer the layer did not allocate,
- * which is what the ABI's "null if the kind has no such view" means here. */
+/* Host and device views are the same pointer (spec §5.1 zero-copy is trivial here). Null for a
+ * pointer the device layer did not allocate. */
 void* h_host_ptr(void* p) {
     if (!p) return nullptr;
     AllocRec r;
@@ -453,10 +408,8 @@ void* h_device_ptr(void* p) { return h_host_ptr(p); }
 
 int h_stream_create(RadStream* out, int high_priority) {
     if (!out) return RAD_E_INVAL;
-    /* Priority is accepted and ignored. The mover and the compute stream ask for different
-     * priorities on a real device and the same code has to run here; raising a thread's scheduling
-     * class needs privileges this process does not have and would buy nothing on a queue that is
-     * one thread deep. */
+    /* Priority is ignored: raising a thread's scheduling class needs privileges and buys nothing
+     * on a one-thread queue. */
     (void)high_priority;
     auto* s = new (std::nothrow) HostStream();
     if (!s) { device_set_error("rad_stream_create: out of memory"); return RAD_E_NOMEM; }
@@ -471,9 +424,7 @@ void h_stream_destroy(RadStream st) {
     auto* s = (HostStream*)st;
     Task t;
     t.kind = Task::Stop;
-    /* Queued behind everything already submitted, so destroy drains rather than discards -- the
-     * mover's last transfer must land before its stream goes away, or a weight is half-written and
-     * nothing says so. */
+    /* Queued behind submitted work, so destroy drains rather than discards. */
     stream_push(s, t);
     if (s->worker.joinable()) s->worker.join();
     delete s;
@@ -486,16 +437,20 @@ int h_stream_sync(RadStream st) {
     }
     auto* s = (HostStream*)st;
     std::unique_lock lk(s->m);
-    /* Snapshot: sync waits for work submitted *before* this call, not for work another thread
-     * pushes while we wait. That is hipStreamSynchronize's contract and the scheduler depends on
-     * it -- a sync that could never return under a busy mover would be a step-path stall. */
+    if (s->gates > 0) {
+        device_set_error("rad_stream_sync: the stream waits at a closed gate, which only "
+                         "rad_gate_open releases");
+        return RAD_E_STATE;
+    }
+    /* Waits only for work submitted before this call, as hipStreamSynchronize does; the
+     * scheduler relies on sync returning while another thread keeps pushing. */
     const uint64_t target = s->submitted;
     s->cv_done.wait(lk, [s, target] { return s->retired >= target; });
     return RAD_OK;
 }
 
-/* RAD_EVENT_LOCAL means nothing in one memory; RAD_EVENT_HOST_WAIT is kept, so a host sync on an
- * event made without it is refused here as it is on a card. */
+/* RAD_EVENT_LOCAL is meaningless here; RAD_EVENT_HOST_WAIT is kept so event_sync refuses events
+ * created without it, as on a card. */
 int h_event_create(RadEvent* out, unsigned flags) {
     if (!out) return RAD_E_INVAL;
     auto* e = new (std::nothrow) HostEvent();
@@ -505,8 +460,7 @@ int h_event_create(RadEvent* out, unsigned flags) {
     return RAD_OK;
 }
 
-/* Drops the handle. A record or wait still queued keeps the event alive until the worker is past
- * it -- see HostEvent. */
+/* Drops the handle; queued tasks keep the event alive (see HostEvent). */
 void h_event_destroy(RadEvent ev) { if (ev) event_release((HostEvent*)ev); }
 
 int h_event_record(RadEvent ev, RadStream st) {
@@ -539,9 +493,8 @@ int h_event_wait(RadStream st, RadEvent ev) {
         std::lock_guard lk(e->m);
         target = e->recorded;
     }
-    /* Waiting on an event that was never recorded is a no-op, matching hipStreamWaitEvent. The
-     * mover relies on it: a weight with no transfer in flight has an event nobody recorded, and
-     * making that case an error would put a branch on the issue path for nothing. */
+    /* Waiting on a never-recorded event is a no-op, matching hipStreamWaitEvent; the mover relies
+     * on it. */
     if (target == 0) return RAD_OK;
     Task t;
     t.kind = Task::Wait;
@@ -576,29 +529,23 @@ int h_event_sync(RadEvent ev) {
 
 int h_event_elapsed_ms(RadEvent a, RadEvent b, float* out) {
     if (!a || !b || !out) return RAD_E_INVAL;
-    auto* ea = (HostEvent*)a;
-    auto* eb = (HostEvent*)b;
+    /* An event's stamp, if it was recorded and has completed. */
+    auto stamp = [](RadEvent ev, Clock::time_point* t) {
+        auto* e = (HostEvent*)ev;
+        std::lock_guard lk(e->m);
+        if (e->recorded == 0 || e->completed < e->recorded) return false;
+        *t = e->stamp;
+        return true;
+    };
     Clock::time_point ta, tb;
-    {
-        std::lock_guard lk(ea->m);
-        if (ea->recorded == 0 || ea->completed < ea->recorded) return RAD_E_STATE;
-        ta = ea->stamp;
-    }
-    {
-        std::lock_guard lk(eb->m);
-        if (eb->recorded == 0 || eb->completed < eb->recorded) return RAD_E_STATE;
-        tb = eb->stamp;
-    }
+    if (!stamp(a, &ta) || !stamp(b, &tb)) return RAD_E_STATE;
     *out = std::chrono::duration(tb - ta).count();
     return RAD_OK;
 }
 
-/* A null stream is refused on both backends, and that is a decision rather than an oversight.
- * HIP's stream 0 carries legacy implicit-synchronisation semantics: work on it serialises against
- * every other blocking stream in the process. That is the exact opposite of spec §5.4's
- * requirement that a transfer involve no host synchronisation and not serialise the step, so the
- * engine never wants it, and letting it through here would let a caller pick it up by accident and
- * only find out on a real device. */
+/* A null stream is refused on both backends. HIP's stream 0 implicitly synchronises with every
+ * blocking stream, which spec §5.4 forbids for transfers; accepting it here would hide such a
+ * caller until it ran on a card. */
 int check_stream(RadStream s, const char* who) {
     if (s) return RAD_OK;
     device_set_error("%s: null stream -- radiance does not use the default stream, "
@@ -647,12 +594,20 @@ int h_memcpy_2d_async(void* dst, int64_t dpitch, const void* src, int64_t spitch
 int h_memcpy_ranges_async(void* dst, const void* src, int64_t prefix, const RadCopyRange* ranges,
                           int n, RadStream st) {
     RAD_TRY(check_stream(st, "rad_memcpy_ranges_async"));
-    if (!dst || !src || prefix < 0 || n < 0 || (n > 0 && !ranges)) {
-        device_set_error("rad_memcpy_ranges_async(%p <- %p, prefix %lld, %d ranges): invalid "
-                         "argument", dst, src, (long long)prefix, n);
+    /* The card's copy kernel moves 16-byte pieces (aql.cpp, a_memcpy_ranges_async), so the same
+     * calls are refused here: a caller passing the host suite must run on a card. Whether the
+     * memory is pinned cannot be told on this backend. */
+    if (!dst || !src || prefix < 0 || (prefix & 15) || n < 0 || (n > 0 && !ranges)) {
+        device_set_error("rad_memcpy_ranges_async(%p <- %p, prefix %lld (a multiple of 16), %d "
+                         "ranges): invalid argument", dst, src, (long long)prefix, n);
         return RAD_E_INVAL;
     }
     if (prefix == 0 && n == 0) return RAD_OK;
+    if (((uintptr_t)dst | (uintptr_t)src) & 15) {
+        device_set_error("rad_memcpy_ranges_async(%p <- %p): both bases must be 16-byte aligned",
+                         dst, src);
+        return RAD_E_UNSUPPORTED;
+    }
     Task t;
     t.kind = Task::Ranges;
     t.dst = dst;
@@ -663,8 +618,7 @@ int h_memcpy_ranges_async(void* dst, const void* src, int64_t prefix, const RadC
     return stream_push((HostStream*)st, t);
 }
 
-/* A copy a segment, queued in list order: this stream has no dispatch to save, and a task holds
- * no list, so the list is read here, at the call, as the device backend reads it. */
+/* One copy task per segment, in list order. The list is read at the call, as on the device. */
 int h_memcpy_list_async(const RadCopySeg* segs, int n, unsigned, RadStream st) {
     RAD_TRY(check_stream(st, "rad_memcpy_list_async"));
     if (n < 0 || (n > 0 && !segs)) {
@@ -690,17 +644,81 @@ int h_memset_async(void* dst, int value, int64_t bytes, RadStream st) {
     return stream_push((HostStream*)st, t);
 }
 
+/* ------------------------------------------------------------------ gates */
+/* A gate is a wait task on an event whose one record only the host completes: recorded is 1 from
+ * the start and rad_gate_open sets completed. The task holds a reference, so the event outlives
+ * the handle until the worker has passed it. */
+struct HostGate {
+    HostEvent*  e = nullptr;
+    HostStream* s = nullptr;
+};
+
+int h_stream_gate(RadStream st, void** out) {
+    RAD_TRY(check_stream(st, "rad_stream_gate"));
+    if (!out) return RAD_E_INVAL;
+    auto* s = (HostStream*)st;
+    auto* e = new (std::nothrow) HostEvent();
+    auto* g = new (std::nothrow) HostGate();
+    if (!e || !g) {
+        delete e;
+        delete g;
+        device_set_error("rad_stream_gate: out of memory");
+        return RAD_E_NOMEM;
+    }
+    e->recorded = 1;
+    Task t;
+    t.kind = Task::Wait;
+    t.ev   = e;
+    t.seq  = 1;
+    event_retain(e);
+    const int rc = stream_push(s, t);
+    if (rc < 0) {
+        event_release(e);
+        event_release(e);
+        delete g;
+        return rc;
+    }
+    {
+        std::lock_guard lk(s->m);
+        ++s->gates;
+    }
+    g->e = e;
+    g->s = s;
+    *out = g;
+    return RAD_OK;
+}
+
+int h_gate_open(void* p) {
+    auto* g = (HostGate*)p;
+    if (!g || !g->e) return RAD_E_INVAL;
+    {
+        std::lock_guard lk(g->e->m);
+        g->e->completed = 1;
+    }
+    g->e->cv.notify_all();
+    {
+        std::lock_guard lk(g->s->m);
+        --g->s->gates;
+    }
+    event_release(g->e);
+    delete g;
+    return RAD_OK;
+}
+
+int64_t h_gate_room(RadStream st) {
+    if (!st) return 0;
+    auto* s = (HostStream*)st;
+    std::lock_guard lk(s->m);
+    return (int64_t)(s->ring.size() - s->count);
+}
+
 /* ------------------------------------------------------------------ elastic memory */
-/* mmap is the host backend's answer to the card's virtual memory manager, and it is the same
- * mechanism rather than a simulation of one: PROT_NONE takes address space and no pages, MAP_FIXED
- * over it backs a granule, and PROT_NONE over that hands the pages back to the kernel. What a test
- * proves here -- that a decommitted range comes back zeroed, that the addresses never move, that
- * committing over a commit is the caller's bug -- is true of the HIP path for the same reasons.
+/* Elastic memory via mmap, the same mechanism as the card's VMM: PROT_NONE reserves address space
+ * without pages, MAP_FIXED read/write backs a granule, and PROT_NONE over it returns the pages.
+ * Decommitted ranges come back zeroed and addresses never move, as on the HIP path.
  *
- * THE GRANULE IS THE POOL ALIGNMENT AND NOT THE PAGE SIZE. A host page is 4 KiB and a card's
- * allocation granularity is 2 MiB, so rounding to the page here would let a pool size that only
- * works on this backend pass its tests and then strand up to 2 MiB per stripe on the card. Matching
- * the coarser number is what makes the host suite able to hold the arithmetic down. */
+ * The granule is the pool alignment (the card's 2 MiB), not the 4 KiB page, so pool sizing that
+ * passes here does not strand memory on a card. */
 constexpr int64_t kVmemGranule = RAD_ALIGN_POOL;
 
 int64_t h_vmem_granularity(void) { return kVmemGranule; }
@@ -708,10 +726,8 @@ int64_t h_vmem_granularity(void) { return kVmemGranule; }
 void* h_vmem_reserve(int64_t bytes, int64_t align) {
     if (bytes <= 0) return nullptr;
     if (align < kVmemGranule) align = kVmemGranule;
-    /* Over-reserve by one alignment, then give back the head and the tail, so the range that
-     * remains is exactly [base, base+bytes) and release() is a single munmap of what it was
-     * handed. The alternative -- remembering the raw mapping in a side table -- is a table whose
-     * only purpose is to survive until teardown. */
+    /* Over-reserve by one alignment and unmap the head and tail, so the range is exactly
+     * [base, base+bytes) and release is one munmap with no side table. */
     const size_t raw_len = (size_t)(bytes + align);
     void* raw = ::mmap(nullptr, raw_len, PROT_NONE,
                        MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
@@ -745,9 +761,8 @@ int h_vmem_commit(void* addr, int64_t bytes) {
 
 int h_vmem_decommit(void* addr, int64_t bytes) {
     if (!addr || bytes <= 0) return RAD_E_INVAL;
-    /* MAP_FIXED over the same range rather than munmap: munmap would leave a HOLE in the
-     * reservation that an unrelated mmap could be handed, and the whole promise of this primitive
-     * is that the address range stays the caller's until it releases it. */
+    /* MAP_FIXED rather than munmap: a hole in the reservation could be handed to an unrelated
+     * mmap. */
     void* p = ::mmap(addr, (size_t)bytes, PROT_NONE,
                      MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
     if (p != addr) {
@@ -758,11 +773,8 @@ int h_vmem_decommit(void* addr, int64_t bytes) {
     return RAD_OK;
 }
 
-/* The host backend's commit already maps readable and writable, so this has nothing to grant. It
- * is implemented rather than left null because the run VMem computes for it is the same run the
- * card is handed, and a path that only ever runs on the machine with the card is a path whose
- * arithmetic the host suite cannot hold down. mprotect over an anonymous mapping that already has
- * these bits is a permission check and a no-op. */
+/* Commit already maps read/write, so this is a no-op mprotect. It is implemented anyway so the
+ * host suite exercises the ranges VMem computes for the card. */
 int h_vmem_protect(void* addr, int64_t bytes) {
     if (!addr || bytes <= 0) return RAD_E_INVAL;
     if (::mprotect(addr, (size_t)bytes, PROT_READ | PROT_WRITE) != 0) {
@@ -773,7 +785,7 @@ int h_vmem_protect(void* addr, int64_t bytes) {
 }
 
 int h_vram_used(int device, int64_t* out) {
-    if (!out || device < 0 || device >= kMaxFakeDevices) return RAD_E_INVAL;
+    if (!out || device < 0 || device >= host_count()) return RAD_E_INVAL;
     *out = g_used[device].load(std::memory_order_relaxed);
     return RAD_OK;
 }
@@ -789,15 +801,21 @@ const DeviceBackend g_host = {
     h_memcpy_async, h_memcpy_2d_async, h_memset_async, h_memcpy_ranges_async,
     h_memcpy_list_async,
     nullptr, nullptr,   /* no DMA engine, so no link to hold */
-    /* No recorded passes: a host stream runs its work as it is issued, so there is no queue to
-     * write a recording into, and every pass is issued. */
+    /* No recorded passes: host streams run work as issued. */
     nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
 
-    /* Elastic memory, which the host backend DOES have: see above. */
+    /* Elastic memory: see above. */
     h_vmem_granularity, h_vmem_reserve, h_vmem_release, h_vmem_commit, h_vmem_decommit,
     h_vmem_protect,
 
     h_vram_used,
+    nullptr, nullptr,            /* no device code to register */
+    nullptr, nullptr,            /* not integrated graphics; one address space */
+    nullptr, nullptr, nullptr,   /* no PCI address, runtime or DMA engine */
+    /* No expert prefetch. */
+    nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
+
+    h_stream_gate, h_gate_open, h_gate_room,
 };
 
 }  /* namespace */
diff --git a/core/diag/checks.cpp b/core/diag/checks.cpp
index 2c407d58..14702b5d 100644
--- a/core/diag/checks.cpp
+++ b/core/diag/checks.cpp
@@ -1,15 +1,12 @@
 /* checks.cpp -- what in the configuration or on the machine costs speed or correctness, and what to
  * do about it.
  *
- * EACH CHECK IS A FUNCTION OF THE FACTS AND NOTHING ELSE: no file is read here and no device is
- * asked, so every one of them is tested by handing it a machine described in a struct. A check
- * says what it saw with the numbers, why that matters, and the change that addresses it -- a
- * warning without a fix is a worry handed to the reader.
+ * Each check is a pure function of the facts (no file or device access), so tests pass a machine
+ * described in a struct. A finding states what was seen with numbers, why it matters, and a fix.
  *
- * WARN is a cost or a risk the operator should act on; NOTE is a setting that is a trade-off or
- * worth knowing when reading a benchmark. A finding that depends on load (a parked link) is only
- * raised when the card was busy when the facts were read: at startup the cards are idle and a
- * PCIe link at rest parks at its lowest speed, which is the power management doing its job.
+ * Warn: a cost or risk to act on. Note: a trade-off, or worth knowing when reading a benchmark.
+ * Load-dependent findings (a parked link) are raised only when the card was busy, since an idle
+ * PCIe link parks at its lowest speed by design.
  */
 #include "diag/diag.h"
 #include "rad_internal.h"
@@ -26,9 +23,6 @@ namespace {
 
 constexpr int64_t kGiB = (int64_t)1 << 30;
 constexpr int64_t kMiB = (int64_t)1 << 20;
-/* A card this busy when its link was read is under load, so a link below its maximum is not the
- * idle parking every PCIe link does. */
-constexpr int kBusyPercent = 30;
 
 void add(std::vector* out, Finding::Level lv, const char* id, std::string what,
          std::string why, std::string fix) {
@@ -50,8 +44,8 @@ std::vector served(const Facts& f) {
     return out;
 }
 
-/* WHETHER THE SERVING CARDS' DMA IS TRANSLATED, from their own IOMMU groups where the kernel
- * says, and from the machine's mode where it does not. */
+/* Whether the serving cards' DMA is translated: from their IOMMU groups where known, else the
+ * machine's mode. */
 bool translated(const Facts& f) {
     bool any = false, dma = false;
     for (const CardFacts* c : served(f)) {
@@ -62,8 +56,8 @@ bool translated(const Facts& f) {
     return any ? dma : f.host.iommu == "translated";
 }
 
-/* A GPU the engine could serve on: an amdgpu device with VRAM of its own worth the name. An
- * integrated GPU's carve-out of a few hundred MiB is not one; an APU set up with tens of GiB is. */
+/* An amdgpu device with at least 4 GiB of VRAM. Excludes small iGPU carve-outs, includes an APU
+ * configured with tens of GiB. */
 bool servable_gpu(const CardFacts& c) {
     return c.vendor == "0x1002" && c.driver == "amdgpu" && c.vram_total >= ((int64_t)4 << 30);
 }
@@ -73,19 +67,14 @@ std::string card_name(const CardFacts& c) {
 }
 
 std::string hop_link(const PciHop& h, bool cur) {
-    const std::string& s = cur ? h.cur_speed : h.max_speed;
-    const int w = cur ? h.cur_width : h.max_width;
-    std::string sp = s;
-    const size_t p = sp.find(" PCIe");
-    if (p != std::string::npos) sp.erase(p);
-    return w > 0 ? fmt("%s x%d", sp.c_str(), w) : sp;
+    return cur ? link_text(h.cur_speed, h.cur_width) : link_text(h.max_speed, h.max_width);
 }
 
 /* ---- the link ------------------------------------------------------------------------------ */
 
-/* A HOP BELOW ITS OWN MAXIMUM WHILE THE CARD IS BUSY: the SMU's link power management stuck a
- * level down, or a link that retrained narrower. The card's own endpoint can read full speed
- * while the root port above it runs at half (a card with a switch on it), so every hop is read. */
+/* A hop below its own maximum while the card is busy: link power management stuck a level down,
+ * or a link retrained narrower. Every hop is checked, because the card's endpoint can read full
+ * speed while the root port above an on-card switch runs at half. */
 void check_link_under_load(const Facts& f, std::vector* out) {
     for (const CardFacts* c : served(f)) {
         if (c->busy_percent < kBusyPercent) continue;
@@ -120,9 +109,8 @@ void check_link_under_load(const Facts& f, std::vector* out) {
     }
 }
 
-/* A LINK THAT CANNOT REACH THE CARD'S SPEED, whatever the load: a hop whose own maximum is below
- * the card's -- a slot one generation older, a riser, a lane split. Not a fault, and often the
- * board's design; worth knowing when two machines measure differently. */
+/* A hop whose maximum is below the card's (older slot, riser, lane split). Often the board's
+ * design, not a fault; a Note. */
 void check_link_capped(const Facts& f, std::vector* out) {
     for (const CardFacts* c : served(f)) {
         if (c->chain.size() < 2) continue;
@@ -149,9 +137,8 @@ void check_link_capped(const Facts& f, std::vector* out) {
 
 /* ---- the cards against each other ----------------------------------------------------------- */
 
-/* A TENSOR-PARALLEL STEP ENDS WHEN ITS SLOWEST RANK DOES, so cards set up differently serve at
- * the slower one's pace, and a difference in a setting nobody remembers making is the usual
- * reason one card is the slow one. */
+/* A tensor-parallel step ends when its slowest rank does, so differently configured cards serve
+ * at the slower one's pace. */
 void check_cards_differ(const Facts& f, std::vector* out) {
     const auto cs = served(f);
     if (cs.size() < 2) return;
@@ -173,7 +160,7 @@ void check_cards_differ(const Facts& f, std::vector* out) {
     field("root port link", [](const CardFacts& c) {
               return c.chain.empty() ? std::string() : hop_link(c.chain.front(), false); }, str);
     field("power cap", [](const CardFacts& c) { return c.power_cap_uw; },
-          [](int64_t uw) { return uw < 0 ? std::string("unknown") : fmt("%lld W", (long long)(uw / 1000000)); });
+          watts_text);
     field("voltage offset", [](const CardFacts& c) { return c.vddgfx_offset; }, str);
     field("top PCIe power level", [](const CardFacts& c) {
               return c.dpm_pcie.empty() ? std::string() : c.dpm_pcie.back(); }, str);
@@ -189,10 +176,8 @@ void check_cards_differ(const Facts& f, std::vector* out) {
         "/sys/class/drm/cardN/device; set them with the server stopped)");
 }
 
-/* A CAP LOWERED BELOW THE CARD'S OWN DEFAULT. The default, not the maximum, is the yardstick: a
- * stock card ships below the most its board allows (300 W of 330 W on an R9700), and a finding on
- * every stock card is one nobody reads. A cap someone lowered -- or one a reset left at a value a
- * tool set before it -- is the one that changes what the card does under load. */
+/* A power cap below the card's default. Compared to the default, not the maximum: stock cards
+ * ship below the board maximum (300 W of 330 W on an R9700). */
 void check_power_cap(const Facts& f, std::vector* out) {
     for (const CardFacts* c : served(f)) {
         if (c->power_cap_uw <= 0 || c->power_cap_default_uw <= 0) continue;
@@ -224,12 +209,9 @@ void check_small_bar(const Facts& f, std::vector* out) {
     }
 }
 
-/* AN OVERDRIVE SETTING AND RUNTIME SUSPEND. The driver holds the offset and uploads it again
- * whenever the card resumes from runtime suspend; on RDNA4 that upload has been seen to fail in
- * the kernel log ("Failed to upload customized OD settings") at every resume. Whether the
- * firmware still holds the offset afterwards is not readable here, and a card that lost it runs a
- * lower clock at the same power cap. Keeping the card out of runtime suspend keeps the question
- * from arising. */
+/* Overdrive offset with runtime suspend enabled. The driver re-uploads the offset on every resume,
+ * and on RDNA4 that upload can fail ("Failed to upload customized OD settings"). Whether the
+ * firmware kept it is not readable here; a card that lost it clocks lower at the same cap. */
 void check_od_runtime_pm(const Facts& f, std::vector* out) {
     for (const CardFacts* c : served(f)) {
         if (c->vddgfx_offset.empty() || c->vddgfx_offset == "0 mV") continue;
@@ -382,8 +364,7 @@ void check_engine(const Facts& f, const RunFacts& r, std::vector* out)
             "faster prefill, but the model does not compute the exact function; two runs on "
             "different world sizes are not comparable token for token",
             "--tp-wire exact when exactness matters more than prefill speed");
-    /* Only when the operator turned it off: where the engine did (the KL mode, an embedding
-     * model) there is no cache to have, and the configuration line says why. */
+    /* Only when the operator turned it off; an engine-side reason is shown in the configuration. */
     if (!r.prefix_cache && r.prefix_cache_off_why.empty())
         add(out, Finding::Note, "prefix-cache-off", "prefix caching is off (--no-prefix-cache)",
             "every request prefills its whole prompt, including the conversation it shares with "
@@ -432,12 +413,24 @@ std::vector check(const Facts& f, const RunFacts& r) {
     check_iommu(f, r, &out);
     check_memlock(f, r, &out);
     check_cpu(f, &out);
-    /* Warnings first, each group in the order above: what to act on before what to know. */
+    /* Warnings first; stable, so each group keeps the order above. */
     std::stable_sort(out.begin(), out.end(),
                      [](const Finding& a, const Finding& b) { return a.level > b.level; });
     return out;
 }
 
+std::string link_text(const std::string& speed, int width) {
+    std::string s = speed;
+    const size_t p = s.find(" PCIe");
+    if (p != std::string::npos) s.erase(p);
+    if (s.empty()) s = "?";
+    return width > 0 ? fmt("%s x%d", s.c_str(), width) : s;
+}
+
+std::string watts_text(int64_t uw) {
+    return uw < 0 ? std::string("unknown") : fmt("%lld W", (long long)(uw / 1000000));
+}
+
 double link_gts(const std::string& speed) {
     return speed.empty() ? 0.0 : std::strtod(speed.c_str(), nullptr);
 }
diff --git a/core/diag/diag.h b/core/diag/diag.h
index 92a582e7..a02e2824 100644
--- a/core/diag/diag.h
+++ b/core/diag/diag.h
@@ -1,27 +1,17 @@
 /* diag.h -- the startup report: what was configured, what it runs on, and what looks wrong.
  *
- * WHY ONE REPORT AND NOT THE LINES ALREADY IN THE LOG. Every decision startup makes is said
- * somewhere on the way up, in the order it was made, between a hundred other lines. A log a user
- * pastes into an issue is read by someone who has to find the line about the embedding, the one
- * about the VRAM split and the one about the card's link, and cannot find the line that was never
- * printed because the value was a default. The report puts all of it in one block at the end of
- * startup: every option the command line takes with the value in force and where it came from,
- * the machine as the kernel describes it, and a list of the things on it that cost speed or
- * correctness with what to do about each.
+ * One block at the end of startup, instead of decisions scattered through the log (defaults are
+ * never logged at all): every option with its value and source, the machine as the kernel
+ * describes it, and findings that cost speed or correctness, each with a fix.
  *
- * THREE PARTS, each built from data rather than from a list kept beside the code:
+ * Each part is built from data, not a list kept beside the code:
+ *   Configuration  every row of the option table (core/config.cpp); a value startup resolved
+ *                  carries its reason (Decision).
+ *   Hardware       read from /proc and /sys under a root, so tests can supply a tree and a
+ *                  FROM-scratch container (no shell, lspci or rocm-smi) reads the same files.
+ *   Findings       small functions over the two above (checks.cpp), testable without a card.
  *
- *   CONFIGURATION  every row of the option table (core/config.cpp), so an option added there
- *                  appears here without anyone remembering to; a value startup resolved carries
- *                  the reason it was resolved that way (Decision).
- *   HARDWARE       read from /proc and /sys under a ROOT, so a test can hand the collector a
- *                  directory tree of its own and a container built FROM scratch -- no shell, no
- *                  lspci, no rocm-smi -- reads the same files the host does.
- *   FINDINGS       each a small function over the two above (checks.cpp), unit-testable without
- *                  a card.
- *
- * Unknown is a value. A field that could not be read is reported as unknown rather than left out:
- * a report that silently drops a line reads as a machine that does not have the thing.
+ * A field that could not be read is reported as unknown, never omitted.
  */
 #pragma once
 
@@ -34,11 +24,9 @@ struct Config;
 namespace diag {
 
 /* ------------------------------------------------------------------ decisions */
-/* ONE VALUE STARTUP RESOLVED, and why. `key` is the option it resolves (`--placement`) when there
- * is one, so the configuration table can show it on that option's row, or a topic of its own
- * (`vram split`) for what no single option states. Recording the same key again replaces the
- * earlier answer: a later stage that revises a choice (the n-gram copy that could not be made)
- * is the answer in force. */
+/* One value startup resolved, and why. `key` is the option it resolves (`--placement`), shown on
+ * that option's row, or a topic of its own (`vram split`). Recording a key again replaces the
+ * earlier answer, so a later stage can revise a choice. */
 struct Decision {
     std::string key;
     std::string value;
@@ -49,9 +37,8 @@ void decide(std::vector* list, const std::string& key, const std::stri
             const std::string& why);
 
 /* ------------------------------------------------------------------ the configuration table */
-/* One option as the report shows it: the value in force, where it came from (`default`, `command
- * line`, an environment variable, or `auto` for a value startup derived), and the reason when
- * startup derived it. */
+/* One option: the value in force, its source (`default`, `command line`, an environment
+ * variable, or `auto` when startup derived it), and the reason when derived. */
 struct ConfigRow {
     std::string flag;
     std::string value;
@@ -59,18 +46,17 @@ struct ConfigRow {
     std::string why;
 };
 
-/* Every option in the command line's table (core/config.cpp), in its order, with the value `c`
- * holds and its source from Config::given. Secrets are not values: --api-key is "set" or "not
- * set". */
+/* Every option in core/config.cpp's table, in order, with the value `c` holds and its source
+ * from Config::given. Secrets are not shown: --api-key is "set" or "not set". */
 std::vector config_rows(const Config& c);
 
 /* The options the table holds, for a test that every one reaches the report. */
 std::vector config_option_names();
 
 /* ------------------------------------------------------------------ hardware */
-/* One PCIe link on the way from the root port to a card. Speeds are the kernel's strings
- * ("32.0 GT/s PCIe"), widths lanes; -1 / "" where the file is absent, as it is on a bridge
- * internal to a card's own switch on some boards. */
+/* One PCIe link between the root port and a card. Speeds are the kernel's strings
+ * ("32.0 GT/s PCIe"), widths in lanes; -1 / "" where the file is absent (some bridges inside a
+ * card's own switch). */
 struct PciHop {
     std::string bdf;
     std::string cur_speed, max_speed;
@@ -98,7 +84,7 @@ struct CardFacts {
     std::string vddgfx_offset;       /* "-75 mV" from pp_od_clk_voltage, "" when unknown */
     bool        integrated = false;  /* the KFD topology's node has no local memory of its own */
 
-    /* What the engine knows and the kernel does not: filled by the engine for its own cards. */
+    /* Filled by the engine for the cards it uses. */
     std::string name;                /* the runtime's product name */
     int         rank = -1;           /* the tensor-parallel rank it serves, -1 none */
     int         device = -1;         /* the backend's device index, -1 none */
@@ -130,24 +116,22 @@ struct Facts {
     std::vector cards;    /* every display-class PCI device, in address order */
 };
 
-/* Reads /proc and /sys under `root` ("" is the live system). Never fails: what cannot be read is
+/* Reads /proc and /sys under `root` ("" is the live system). Never fails: unreadable fields are
  * left unknown.
  *
- * `managed`, when given, names the cards (by PCI address) whose power-management files are read
- * -- the DPM tables, the overdrive block, the busy percentage and the hwmon power limits; every
- * other card is described from its PCI and memory files alone. The driver answers those files
- * from the card's SMU under its power-management lock, and wakes a card that was runtime-
- * suspended to do it, so a server reading the machine again while it serves reads them for the
- * cards it serves on and no others. Null reads them for every card. */
+ * `managed`, when given, lists the cards (by PCI address) whose power-management files are read:
+ * DPM tables, overdrive, busy percentage, hwmon power limits. The driver answers those from the
+ * SMU under its power-management lock and wakes a runtime-suspended card to do so, so a serving
+ * process reads them only for its own cards. Null reads them for every card. */
 Facts collect(const std::string& root, const std::vector* managed = nullptr);
 
-/* What only a system call answers, filled for the live process: the memlock limit and whether
- * io_uring is allowed here (a container's seccomp profile refuses it). */
+/* Fills what only a system call answers for the live process: the memlock limit and whether
+ * io_uring is allowed (a container's seccomp profile may refuse it). */
 void probe_process(HostFacts* h);
 
-/* The names of the variables in `env` (an environ-shaped, null-terminated array) that start with
- * `prefix`, sorted. Names only: a value can be a path, a host name or a token, and the report is
- * written to be pasted into an issue. */
+/* Sorted names of the variables in `env` (environ-shaped, null-terminated) starting with
+ * `prefix`. Names only: values may be paths, host names or tokens, and the report gets pasted
+ * into issues. */
 std::vector env_names(char* const* env, const char* prefix);
 
 /* ------------------------------------------------------------------ what the engine did */
@@ -164,8 +148,8 @@ struct RunFacts {
     bool        tp_wire_lossy = false;
     int64_t     tp_wire_min_kb = 0;
     bool        prefix_cache = true;
-    /* Why the engine turned prefix caching off itself (the KL mode, an embedding model); "" when
-     * it is on or the operator turned it off. */
+    /* Why the engine disabled prefix caching itself (KL mode, an embedding model); "" when it is
+     * on or the operator turned it off. */
     std::string prefix_cache_off_why;
     int64_t     host_pool_mib = 0;       /* a rank, as configured */
     int64_t     pinned_bytes = -1;       /* every pinned host allocation the process made */
@@ -176,9 +160,8 @@ struct RunFacts {
     bool        reference_kernels = false;
     bool        profile_ops = false;
     bool        deterministic = false;
-    /* The RADIANCE_* variables set in the environment, by name (env_names). The option table
-     * covers what the command line takes; these change behaviour beside it -- the log level, a
-     * pinned tuning, an instrument left on -- and a report of every setting in force names them. */
+    /* Names of the RADIANCE_* variables set (env_names): settings outside the option table,
+     * such as the log level, a pinned tuning or an instrument left on. */
     std::vector environment;
 };
 
@@ -211,5 +194,14 @@ void merge(std::vector* rows, const std::vector& decisions,
 /* "32.0 GT/s PCIe" -> 32.0; 0 when it does not parse. */
 double link_gts(const std::string& speed);
 
+/* "32.0 GT/s x16" from a sysfs speed and width; "?" for an unknown speed. */
+std::string link_text(const std::string& speed, int width);
+
+/* "300 W" from microwatts; "unknown" when negative. */
+std::string watts_text(int64_t uw);
+
+/* Busy percentage above which a link below its maximum is not idle parking. */
+constexpr int kBusyPercent = 30;
+
 }  /* namespace diag */
 }  /* namespace rad */
diff --git a/core/diag/report.cpp b/core/diag/report.cpp
index 707d489d..189b7678 100644
--- a/core/diag/report.cpp
+++ b/core/diag/report.cpp
@@ -1,10 +1,8 @@
 /* report.cpp -- the startup report, as text for the log and as JSON for /diagnostics.
  *
- * ONE LAYOUT FOR A READER WHO DID NOT RUN THE SERVER: every option on its own line with the value
- * in force and where it came from, the reason under any value startup derived, the machine in a
- * few dense lines and a block a card, and the findings last with what to do about each. The text
- * and the JSON are rendered from the same structs, so neither can say something the other does
- * not.
+ * Text layout: one line per option with value and source (the reason below any derived value),
+ * the host in a few lines, a block per card, then findings with fixes. Text and JSON render from
+ * the same structs.
  */
 #include "diag/diag.h"
 #include "rad_internal.h"
@@ -57,15 +55,6 @@ std::string short_bdf(const std::string& b) {
     return b.rfind("0000:", 0) == 0 ? b.substr(5) : b;
 }
 
-std::string link(const std::string& speed, int width) {
-    std::string s = speed;
-    const size_t p = s.find(" PCIe");
-    if (p != std::string::npos) s.erase(p);
-    if (s.empty()) s = "?";
-    return width > 0 ? fmt("%s x%d", s.c_str(), width) : s;
-}
-
-std::string watts(int64_t uw) { return uw < 0 ? std::string("unknown") : fmt("%lld W", (long long)(uw / 1000000)); }
 
 std::string host_lines(const HostFacts& h, const RunFacts& r) {
     std::string o;
@@ -118,10 +107,12 @@ std::string card_lines(const CardFacts& c) {
     std::string chain;
     for (const PciHop& h : c.chain)
         chain += fmt("%s%s %s (max %s)", chain.empty() ? "" : " -> ", short_bdf(h.bdf).c_str(),
-                     link(h.cur_speed, h.cur_width).c_str(), link(h.max_speed, h.max_width).c_str());
+                     link_text(h.cur_speed, h.cur_width).c_str(),
+                     link_text(h.max_speed, h.max_width).c_str());
     o += fmt("      link   %s  [read at %s%% busy%s]\n", chain.empty() ? "unknown" : chain.c_str(),
              c.busy_percent < 0 ? "?" : std::to_string(c.busy_percent).c_str(),
-             c.busy_percent >= 0 && c.busy_percent < 30 ? ": a link at rest parks below its maximum" : "");
+             c.busy_percent >= 0 && c.busy_percent < kBusyPercent
+                 ? ": a link at rest parks below its maximum" : "");
     if (!c.dpm_pcie.empty()) {
         std::string t;
         for (size_t i = 0; i < c.dpm_pcie.size(); ++i)
@@ -131,8 +122,8 @@ std::string card_lines(const CardFacts& c) {
     if (!c.dma.empty()) o += "      dma    " + c.dma + "\n";
     o += fmt("      power  cap %s (default %s, max %s) | voltage offset %s | sclk %s | mclk %s | "
              "runtime pm %s (control %s) | iommu group %s\n",
-             watts(c.power_cap_uw).c_str(), watts(c.power_cap_default_uw).c_str(),
-             watts(c.power_cap_max_uw).c_str(), or_unknown(c.vddgfx_offset).c_str(),
+             watts_text(c.power_cap_uw).c_str(), watts_text(c.power_cap_default_uw).c_str(),
+             watts_text(c.power_cap_max_uw).c_str(), or_unknown(c.vddgfx_offset).c_str(),
              or_unknown(c.sclk).c_str(), or_unknown(c.mclk).c_str(),
              or_unknown(c.runtime_status).c_str(), or_unknown(c.runtime_control).c_str(),
              c.iommu_type.empty() ? "none" : c.iommu_type.c_str());
@@ -286,9 +277,8 @@ std::string to_json(const std::vector& config, const std::vector 4 && std::isdigit((unsigned char)d[4])) c->drm = d;
 
-    /* THE WHOLE PATH TO THE ROOT PORT, not the card's own link alone. A card with a switch on it
-     * reports its own endpoint link at full speed whatever the slot does upstream: a root port
-     * parked one speed down shows only at the root port (and in the card's DPM table). */
+    /* Every hop up to the root port, not just the card's link: a card with an on-board switch
+     * reports its endpoint at full speed regardless of the slot, so a parked root port shows only
+     * at the root port (and in the card's DPM table). */
+    auto hop = [&](const std::string& at, const std::string& hop_bdf) {
+        PciHop h;
+        h.bdf       = hop_bdf;
+        h.cur_speed = line(at + "/current_link_speed");
+        h.max_speed = line(at + "/max_link_speed");
+        h.cur_width = (int)num(at + "/current_link_width", -1);
+        h.max_width = (int)num(at + "/max_link_width", -1);
+        c->chain.push_back(h);
+    };
     std::error_code ec;
     const fs::path real = fs::canonical(dev, ec);
     if (!ec) {
         for (const fs::path& part : real) {
             const std::string p = part.string();
-            if (!is_bdf(p)) continue;
-            const std::string hd = root + "/sys/bus/pci/devices/" + p;
-            PciHop h;
-            h.bdf       = p;
-            h.cur_speed = line(hd + "/current_link_speed");
-            h.max_speed = line(hd + "/max_link_speed");
-            h.cur_width = (int)num(hd + "/current_link_width", -1);
-            h.max_width = (int)num(hd + "/max_link_width", -1);
-            c->chain.push_back(h);
+            if (is_bdf(p)) hop(root + "/sys/bus/pci/devices/" + p, p);
         }
     }
-    if (c->chain.empty()) {
-        PciHop h;
-        h.bdf       = bdf;
-        h.cur_speed = line(dev + "/current_link_speed");
-        h.max_speed = line(dev + "/max_link_speed");
-        h.cur_width = (int)num(dev + "/current_link_width", -1);
-        h.max_width = (int)num(dev + "/max_link_width", -1);
-        c->chain.push_back(h);
-    }
+    if (c->chain.empty()) hop(dev, bdf);
 
     c->vram_total   = num(dev + "/mem_info_vram_total", -1);
     c->vram_visible = num(dev + "/mem_info_vis_vram_total", -1);
@@ -185,8 +176,8 @@ void read_card(const std::string& root, const std::string& bdf, bool pm, CardFac
         break;
     }
     {
-        /* "OD_VDDGFX_OFFSET:\n-75mV": the offset the driver holds for the card, which is the one
-         * it uploads; whether the firmware took it is not in this file. */
+        /* "OD_VDDGFX_OFFSET:\n-75mV": the offset the driver holds and uploads; whether the
+         * firmware applied it is not in this file. */
         const std::string od = slurp(dev + "/pp_od_clk_voltage");
         const size_t at = od.find("OD_VDDGFX_OFFSET:");
         if (at != std::string::npos) {
@@ -198,14 +189,13 @@ void read_card(const std::string& root, const std::string& bdf, bool pm, CardFac
     }
 }
 
-/* The KFD topology knows what the PCI files do not: each GPU node's target and SIMD count, keyed
- * by its PCI location -- `location_id` is (bus << 8) | (device << 3) | function. */
+/* Each KFD topology GPU node's target and SIMD count, keyed by PCI location:
+ * `location_id` is (bus << 8) | (device << 3) | function. */
 void read_kfd(const std::string& root, std::vector* cards) {
     const std::string nodes = root + "/sys/class/kfd/kfd/topology/nodes";
     for (const std::string& n : list(nodes)) {
-        /* A LINE AT A TIME, and only the four keys this needs parsed: the file holds values no
-         * signed 64-bit integer takes (unique_id is a full 64-bit hash), and a stream extraction
-         * that meets one fails and stops reading every key after it. */
+        /* Line by line, parsing only the needed keys: some values (unique_id, a 64-bit hash)
+         * overflow int64, and a failed stream extraction would stop reading all later keys. */
         std::istringstream in(slurp(nodes + "/" + n + "/properties"));
         std::string l;
         long long loc = -1, dom = 0, gfx = 0, simd = -1;
@@ -236,19 +226,18 @@ void read_kfd(const std::string& root, std::vector* cards) {
     }
 }
 
-/* Of two memory limits in HostFacts' encoding (bytes, -2 unlimited, -1 unknown), the one that
- * binds: the smaller number, else unlimited over unknown. */
+/* The binding one of two limits in HostFacts' encoding (bytes, -2 unlimited, -1 unknown): the
+ * smaller number, else unlimited over unknown. */
 int64_t tighter(int64_t a, int64_t b) {
     if (a >= 0 && b >= 0) return std::min(a, b);
     if (a >= 0 || b >= 0) return std::max(a, b);
     return a == -2 || b == -2 ? -2 : -1;
 }
 
-/* THE TIGHTEST MEMORY LIMIT FROM A CGROUP UP TO THE MOUNT'S ROOT. A limit binds every cgroup
- * below it, so the process's own group can say "max" while the systemd slice or the container's
- * group above it holds the limit that counts. `rel` is the path /proc/self/cgroup names, under
- * `mount`; every level on the way up is read, the mount's root included -- inside a container's
- * cgroup namespace that root is the container's own group. */
+/* The tightest memory limit from a cgroup up to the mount's root. A limit binds every cgroup
+ * below it, so the process's group may say "max" while a parent slice holds the real limit.
+ * `rel` is the /proc/self/cgroup path under `mount`; every level is read, the root included
+ * (inside a cgroup namespace that is the container's own group). */
 int64_t cgroup_limit(const std::string& mount, std::string rel, const char* file) {
     int64_t lim = -1;
     while (!rel.empty() && rel.back() == '/') rel.pop_back();
@@ -323,9 +312,9 @@ void read_host(const std::string& root, HostFacts* h) {
         else if (cg.find("containerd") != std::string::npos) h->container = "containerd";
     }
     {
-        /* THE PROCESS'S OWN CGROUP, which inside a container is "/" under its namespace, and
-         * every one above it: cgroup_limit says why. Version 2 is the "0::" line; version 1's
-         * memory controller is the ":memory:" one, where "unlimited" is a number near 2^63. */
+        /* The process's cgroup ("/" inside a container's namespace) and its ancestors. v2 is
+         * the "0::" line; v1's memory controller is ":memory:", where unlimited is a number
+         * near 2^63. */
         std::istringstream in(slurp(root + "/proc/self/cgroup"));
         std::string l;
         int64_t lim = -1;
@@ -355,9 +344,9 @@ void read_host(const std::string& root, HostFacts* h) {
                 if (t.rfind(k, 0) == 0) { h->cmdline += (h->cmdline.empty() ? "" : " ") + t; break; }
     }
     {
-        /* PASSTHROUGH OR TRANSLATED, from what decides it for the cards: their IOMMU groups' type
-         * (identity is passthrough) is the kernel's own answer; the boot parameters and the
-         * presence of an IOMMU are what is left when a card has no group. */
+        /* Passthrough or translated. The cards' IOMMU group type (identity = passthrough) is the
+         * kernel's own answer; IOMMU presence and boot parameters are the fallback for a card
+         * with no group. */
         const bool any_iommu = !list(root + "/sys/class/iommu").empty();
         const bool groups = !list(root + "/sys/kernel/iommu_groups").empty();
         const std::string cl = " " + h->cmdline + " ";
@@ -379,7 +368,7 @@ void read_host(const std::string& root, HostFacts* h) {
     }
     {
         int64_t lim = num(root + "/sys/module/ttm/parameters/pages_limit", -1);
-        /* 0 IS THE DRIVER'S DEFAULT, which is half of RAM. */
+        /* 0 means the driver default, half of RAM. */
         if (lim == 0 && h->mem_total > 0) lim = h->mem_total / 2 / h->page_size;
         h->ttm_pages_limit = lim;
     }
@@ -404,8 +393,7 @@ Facts collect(const std::string& root, const std::vector* managed)
         if (ps > 0) f.host.page_size = ps;
     }
     read_host(root, &f.host);
-    /* EVERY DISPLAY-CLASS DEVICE, the engine's or not: an integrated GPU beside the cards, or a
-     * card the engine was told not to use, is part of the answer to "what is in this machine". */
+    /* Every display-class device, used by the engine or not (an iGPU, an excluded card). */
     for (const std::string& d : list(root + "/sys/bus/pci/devices")) {
         const std::string cls = line(root + "/sys/bus/pci/devices/" + d + "/class");
         if (cls.rfind("0x03", 0) != 0) continue;
@@ -416,23 +404,21 @@ Facts collect(const std::string& root, const std::vector* managed)
         f.cards.push_back(std::move(c));
     }
     read_kfd(root, &f.cards);
-    /* THE IOMMU'S MODE AS THE CARDS SEE IT, which beats the command line where both exist: each
-     * card's group says identity (passthrough) or DMA / DMA-FQ (translated), and a machine can
-     * hold both -- an integrated GPU left identity-mapped beside a translated discrete card. */
-    if (f.host.iommu == "unknown") {
-        std::map by;
-        for (const CardFacts& c : f.cards)
-            if (!c.iommu_type.empty()) by[c.iommu_type] += (by[c.iommu_type].empty() ? "" : ", ") + c.bdf;
-        if (by.size() == 1) {
-            const bool id = by.begin()->first == "identity";
-            f.host.iommu = id ? "passthrough" : "translated";
-            f.host.iommu_why = "the display devices' IOMMU groups are of type " + by.begin()->first;
-        } else if (by.size() > 1) {
-            f.host.iommu = "mixed";
-            f.host.iommu_why.clear();
-            for (const auto& [t, bdfs] : by)
-                f.host.iommu_why += (f.host.iommu_why.empty() ? "" : "; ") + t + " for " + bdfs;
-        }
+    /* The IOMMU mode as the cards see it, which beats the command line where both exist:
+     * identity is passthrough, DMA / DMA-FQ translated. A machine can mix both (an
+     * identity-mapped iGPU beside a translated discrete card). */
+    std::map by;
+    for (const CardFacts& c : f.cards)
+        if (!c.iommu_type.empty()) by[c.iommu_type] += (by[c.iommu_type].empty() ? "" : ", ") + c.bdf;
+    if (by.size() == 1) {
+        const bool id = by.begin()->first == "identity";
+        f.host.iommu = id ? "passthrough" : "translated";
+        f.host.iommu_why = "the display devices' IOMMU groups are of type " + by.begin()->first;
+    } else if (by.size() > 1) {
+        f.host.iommu = "mixed";
+        f.host.iommu_why.clear();
+        for (const auto& [t, bdfs] : by)
+            f.host.iommu_why += (f.host.iommu_why.empty() ? "" : "; ") + t + " for " + bdfs;
     }
     return f;
 }
@@ -442,8 +428,8 @@ void probe_process(HostFacts* h) {
     if (getrlimit(RLIMIT_MEMLOCK, &rl) == 0)
         h->memlock_soft = rl.rlim_cur == RLIM_INFINITY ? -2 : (int64_t)rl.rlim_cur;
 #ifdef SYS_io_uring_setup
-    /* ASKED, NOT INFERRED: a seccomp profile (Docker's default) refuses the call whatever the
-     * sysctl says, and the answer is the error the call returns. One entry, closed at once. */
+    /* Try the call: a seccomp profile (Docker's default) refuses it whatever the sysctl says.
+     * One entry, closed at once. */
     struct { uint32_t sq_entries, cq_entries, flags, sq_thread_cpu, sq_thread_idle, features,
              wq_fd, resv[3]; uint64_t sq_off[5]; uint64_t cq_off[5]; } p{};
     static_assert(sizeof(p) == 120, "io_uring_params is 120 bytes");
diff --git a/core/engine.cpp b/core/engine.cpp
index e5b3ce9c..9544e08a 100644
--- a/core/engine.cpp
+++ b/core/engine.cpp
@@ -1,8 +1,6 @@
-/* engine.cpp -- the step loop and the server.
- *
- * The Engine's construction, the per-rank threads, the one loop that runs a step, and the server
- * it runs under; bring-up, the drafters and the buffer probe have files of their own. See
- * engine_priv.h for what the four share.
+/* engine.cpp -- the step loop and the server: Engine construction, the per-rank threads, the
+ * step loop and the server it runs under. Bring-up, the drafters and the buffer probe live in
+ * their own files (engine_priv.h).
  */
 #include "engine_priv.h"
 #include "gen/driver.h"
@@ -21,6 +19,7 @@
 #include "server/sink.h"
 #include "server/liveview.h"
 #include "text/tokenizer.h"
+#include "util/stallwatch.h"
 
 #include 
 #include 
@@ -39,10 +38,7 @@
 
 namespace rad {
 
-
-
-/* The RADIANCE_* names are taken here, before start(): bring-up sets one of its own
- * (RADIANCE_GDN_ANCHOR, Engine::configure_kv), and the report lists what the operator set. */
+/* The operator's RADIANCE_* names, captured at construction for the diagnostics report. */
 Engine::Engine(Config cfg)
     : cfg_(std::move(cfg)), env_set_(diag::env_names(environ, "RADIANCE_")) {}
 
@@ -59,19 +55,15 @@ Engine::Readback::~Readback() {
 }
 
 Engine::~Engine() {
-    /* WHERE --profile-ops LEAVES ITS FINAL TABLE. Here, because this is the last moment the
-     * program still holds the op table the rows name -- and it has to be printed somewhere: a
-     * flag that pays for the synchronisations, warns that the run is not comparable, and then
-     * says nothing is worse than no flag at all. */
+    /* --profile-ops prints its final table here, the last point where the program still holds
+     * the op table the rows name. */
     if (cfg_.profile_ops) for (auto& r : ranks_) r->ctx.dump_profile();
     for (float* p : kld_host_) if (p) rad_dev_free(p, RAD_MEM_HOST_PINNED);
     if (pooled_host_) rad_dev_free(pooled_host_, RAD_MEM_HOST_PINNED);
     for (auto& r : ranks_) if (r->score_host) rad_dev_free(r->score_host, RAD_MEM_HOST_PINNED);
-    /* WHAT THE TIERING ACTUALLY DID, and it is printed here for the same reason: this is the last
-     * moment the plan the rows name is still alive. Only when the plan was dynamic -- a static
-     * one has nothing to say and a banner saying nothing is a banner people learn to skip. The
-     * per-layer residency histogram at the end of it is the number that says whether the global
-     * ranking starved a layer, which is the failure this engine has and a hit rate cannot show. */
+    /* The tiering summary, here for the same reason, and only for a dynamic plan. Its per-layer
+     * residency histogram shows whether the global ranking starved a layer, which a hit rate
+     * cannot. */
     for (auto& r : ranks_) {
         if (!r->heat.enabled()) continue;
         LogRank lr(r->index);
@@ -82,11 +74,10 @@ Engine::~Engine() {
                  (unsigned long long)r->ctx.route_dropped());
         RAD_INFO("%s", r->mover.report().c_str());
     }
-    /* THE TRANSFER STREAM BEFORE THE CONTEXTS. Ctx::shutdown drains the compute streams and then
-     * frees the arena, but the mover's stream copies into the arena too -- the prefill stager's
-     * ring is its top, and an idle arena lends its slots to the expert slab -- and is drained only
-     * when the mover goes, after it. A fill still landing in a lent arena slot at that moment is
-     * a GPU memory fault on the way out. */
+    /* Drain the transfer streams before the contexts. Ctx::shutdown drains the compute streams
+     * and frees the arena, but the mover's stream also copies into the arena (the prefill
+     * stager's ring, lent slab slots) and would otherwise drain only later, with the mover. A fill
+     * landing in a freed arena is a GPU memory fault. */
     for (auto& r : ranks_)
         if (RadStream s = r->mover.transfer_stream()) (void)rad_stream_sync(s);
     for (auto& r : ranks_) r->ctx.shutdown();
@@ -99,25 +90,20 @@ Engine::~Engine() {
     rad_tools_registry().close();
 }
 
-
 /* ================================================================== 7. serve */
-/* The step loop, which is the one place every component meets. Threading is spec §1's exactly:
- * HTTP threads feed a request queue, ONE scheduler thread produces ONE step, one thread per
- * tensor-parallel rank each owning one device.
+/* The step loop, where every component meets. Threading per spec §1: HTTP threads feed a request
+ * queue, one scheduler thread produces one step, and one thread per tensor-parallel rank owns one
+ * device.
  *
- * The ranks share an address space, so the batch is shared BY POINTER and the whole of the
- * handoff is a barrier -- no serialisation, no pipe, no pickling, which is most of what a Python
- * engine's multiprocessing budget actually buys (rank_barrier.h). The barrier is entered TWICE
- * per step: once to release the ranks against the batch, once to join them before the sampler's
- * answer is read. The scheduler thread is a participant on both sides, which is why the barrier's
- * width is tp + 1 and not tp.
+ * The batch is shared by pointer and the handoff is a barrier (rank_barrier.h), entered twice per
+ * step: to release the ranks against the batch, and to join them before the sampler's answer is
+ * read. The scheduler thread takes part, so the width is tp + 1.
  */
 
 int Engine::declare_sampler(int rank, RadBuilder* b, int64_t logits_width, bool sizing) {
     Rank& r = *ranks_[(size_t)rank];
-    /* A SIZING DECLARE DECLARES INTO A SAMPLER OF ITS OWN. The chain has to be in the Program for
-     * the buffer list to match the real one, but the rank's sampler keeps the handles the real
-     * declare gave it -- the ones every step issues. */
+    /* A sizing declare uses a throwaway sampler: the chain must be in the Program so the buffer
+     * list matches, but the rank's sampler keeps the real declare's handles. */
     Sampler scratch;
     Sampler& smp = sizing ? scratch : r.sampler;
     rad_buf scratch_tok = 0;
@@ -125,24 +111,18 @@ int Engine::declare_sampler(int rank, RadBuilder* b, int64_t logits_width, bool
 
     SamplerConfig sc{};
     sc.n_vocab       = meta_.n_vocab;
-    /* WHAT THIS RANK ACTUALLY PRODUCES, taken from the logits buffer the plugin declared rather
-     * than re-derived from n_vocab and world_size. `program.meta` is the CONTAINER's metadata and
-     * carries the whole model's n_vocab on every rank, so reading it here would be wrong the
-     * moment a vocabulary is split; and computing the split a second time here would be wrong
-     * again the moment a plugin decides not to split it, which is where rad_arch.h stands
-     * and says why. Either mistake is a sampler reading past the end of every logits row. */
+    /* This rank's vocabulary width, from the declared logits buffer (see rad_tools_declare).
+     * meta_.n_vocab is the whole model's on every rank. */
     sc.n_vocab_local = logits_width > 0 ? logits_width : meta_.n_vocab;
-    /* THIS RANK'S FIRST VOCABULARY ROW, and it is the one thing the declared width cannot say:
-     * a width tells you how many rows a rank owns, not which. The rule is arch/common/rad_arch.h's
-     * shard_begin -- ceil(total/world) per rank, rounded up to a 128-row block, the last one short -- and it is restated here
-     * rather than carried through the ABI, so the restatement is CHECKED against what the plugin
-     * actually declared. A plugin that shards some other way gets a named refusal at startup
-     * instead of a sampler that names rank 0's tokens with rank 1's ids. */
+    /* This rank's first vocabulary row, which the width cannot tell. The rule restates
+     * arch/common/rad_arch.h's shard_begin rather than passing through the ABI, and is checked
+     * against the declared width, so a plugin that shards differently is refused at startup
+     * instead of sampling with the wrong ids. */
     sc.vocab_off = 0;
     if (sc.n_vocab_local < sc.n_vocab) {
-        /* rad_arch.h vocab_per_rank, restated: the even share when the world divides the vocabulary;
-         * otherwise ceil(n / tp) rounded up to a whole 128-row block so a block-scaled head can be
-         * cut there. */
+        /* rad_arch.h vocab_per_rank: the even share when tp divides the vocabulary, otherwise
+         * ceil(n / tp) rounded up to a 128-row block so a block-scaled head can be cut there; the
+         * last rank is short. */
         const int64_t ceil_per = (sc.n_vocab + cfg_.tp - 1) / cfg_.tp;
         const int64_t per = (sc.n_vocab % cfg_.tp == 0) ? sc.n_vocab / cfg_.tp
                                                         : (ceil_per + 127) / 128 * 128;
@@ -163,10 +143,9 @@ int Engine::declare_sampler(int rank, RadBuilder* b, int64_t logits_width, bool
     sc.world_size    = cfg_.tp;
     RAD_TRY(smp.declare(b, sc));
 
-    /* Where the chain writes the sampled ids. The sampler takes it as an argument rather than
-     * declaring it, because rad-kbench drives the same chain against a buffer it owns -- so the
-     * engine is the one that has to provide one. PERSIST, not transient: the step loop copies it
-     * back after the step, by which time a transient's storage may belong to another buffer. */
+    /* Where the chain writes the sampled ids. The engine declares it because rad-kbench drives the
+     * same chain against its own buffer. PERSIST, since the step loop copies it back after the
+     * step, when a transient's storage may belong to another buffer. */
     RadBufDecl d{};
     d.dtype    = RAD_I32;
     d.rank     = 1;
@@ -176,47 +155,32 @@ int Engine::declare_sampler(int rank, RadBuilder* b, int64_t logits_width, bool
     return tok ? RAD_OK : RAD_E_STATE;
 }
 
-
 /* ------------------------------------------------------------------ the tiering seam
  *
- * WHERE THE HEAT ENGINE RUNS, AND WHY IT IS A STEP AND NOT A LAYER. mover.h writes its run-phase
- * contract as "the order a layer dispatch calls it", and ctx.cpp states the invariant that
- * decides the unit: THE MOVER RELOCATES BETWEEN STEPS, NEVER DURING ONE -- `weights_dirty_` is
- * honoured once at the top of run_step, so a table edit made mid-step would be seen by some
- * issues and not others. A step is therefore the dispatch, and this pair brackets it.
+ * The heat engine dispatches per step, not per layer: the mover relocates only between steps
+ * (Ctx::run_step syncs the residency table once at its top), so a mid-step table edit would be
+ * seen by some issues and not others.
  *
- * IT RUNS ONCE A STEP, AFTER THE STEP'S FORWARD PASS IS ON THE QUEUE:
+ * It runs once per step, after the step's forward pass is queued:
  *
- *   - AFTER, because nothing in it is work the pass waits for. Ahead of a draft pass the device
- *     is idle -- the previous pass was drained to read its proposal -- so whatever the rank thread
- *     does before its first dispatch is time the device sits out; behind the issue it runs under
- *     the pass instead. Nothing it changes can reach the pass just issued: table edits are
- *     honoured at the top of the NEXT run_step, and a slot it frees is quarantined behind an event
- *     on the compute stream recorded after this pass.
- *   - ONCE A STEP, on the trunk pass and not the draft passes, because a swap almost never
- *     clears the hysteresis between two passes of one step and every call ranks the whole
- *     movable set. The draft head's histograms are not lost by it: they accumulate in the step's
- *     bank and are credited at the next step, weighted by the passes they stand for.
- *   - `begin_dispatch` only RETIRES. It never starts anything, so a loop that retires without
- *     issuing is not a slower engine but a stuck one (mover.h says so at length). The issue call
- *     below is the other half and they are written together for that reason.
- *   - The histograms this credits are the PREVIOUS step's -- a copy is asynchronous and lands
- *     while the step that produced it is still running (spec §5.5) -- and `histogram_ready` says
- *     which have landed.
+ *   - After, so it runs under the pass instead of in front of it (ahead of a draft pass the
+ *     device is idle). Its changes cannot reach the pass just issued: table edits apply at the
+ *     next run_step, and a freed slot is quarantined behind an event recorded after this pass.
+ *   - On the trunk pass only, since a swap rarely clears the hysteresis between passes of one
+ *     step and each call ranks the whole movable set. Draft-pass histograms accumulate in the
+ *     step's bank and are credited next step, weighted by pass count.
+ *   - `begin_dispatch` only retires; the issue call below is the other half. Retiring without
+ *     issuing stalls the mover (mover.h).
+ *   - It credits the previous step's histograms, whose copies land asynchronously while that step
+ *     runs (spec §5.5); `histogram_ready` says which have landed.
  *
- * ON A LONG PREFILL CHUNK ALMOST NONE OF THIS LANDS, and the counters below say so rather than
- * leaving it to be inferred from a placement that will not settle. This runs BEFORE run_step and
- * every issue path is enqueue-and-return, so on a chunk worth most of a second of device time the
- * host is many steps ahead of the card: the freshest bank holds a copy the device has not reached,
- * `histogram_ready` is 0, and the layer is skipped. Through a prefill of 2048-token chunks about 2%
- * of the layer-histograms are credited and the rest skipped as not yet landed, against effectively
- * all of them at a decode shape, where the step is short enough that the device keeps up. The same
- * shortfall is what the link panel's expert-streaming share is computed from, so it reads near zero
- * through a prefill that is in fact streaming.
+ * On long prefill chunks the host runs many steps ahead of the card, so most histograms have not
+ * landed and are skipped (about 2% credited with 2048-token chunks, nearly all at decode shapes).
+ * The counters report this, and the link panel's expert-streaming share reads near zero for the
+ * same reason.
  *
- * `heat_seen` is what stops a layer being credited twice. A bank holds its counts until the next
- * report overwrites them, so a step in which some layer did not route -- a drafter pass, or a
- * bisect running fewer layers -- would otherwise credit the stale plane again and again.
+ * `heat_seen` prevents crediting a bank twice: a bank keeps its counts until the next report, so a
+ * step where a layer did not route (a drafter pass) would re-credit the stale plane.
  */
 void Engine::tiering_dispatch(Rank& r, int step) {
     if (!r.heat.enabled()) return;
@@ -225,21 +189,17 @@ void Engine::tiering_dispatch(Rank& r, int step) {
 
     const int n_layer = r.ctx.n_route_layers();
     if ((int)r.heat_seen.size() != n_layer) r.heat_seen.assign((size_t)n_layer, -1);
-    /* THE SWEEP'S HISTOGRAMS ARE FOUND FIRST AND CREDITED SECOND, in the same order. A histogram
-     * is a row the card copied into host memory, so every line of it is a miss, and one layer's
-     * credit is too little work to hide the next row's fetch behind. With the rows known up front
-     * each is prefetched while an earlier one is credited: two rows ahead is 32 lines in flight,
-     * about what one core keeps outstanding to memory, so further ahead would only queue. */
+    /* Find all histograms first, then credit them in order. Each is a card-written row in host
+     * memory (every line a cache miss), and one credit is too little work to hide the next fetch.
+     * Prefetching two rows ahead keeps 32 lines in flight, about what one core sustains. */
     int8_t landed[kRouteBanks];
     std::memset(landed, -1, sizeof landed);
     std::vector& rows = r.heat_rows;
     rows.clear();
     for (int l = 0; l < n_layer; ++l) {
-        /* DRAIN THE LAYER, do not take one and move on. The host reaches this once per step it
-         * ISSUES, and on a long chunk it issues far ahead of the card -- so between two visits the
-         * device can have produced many of this layer's histograms. Taking only the newest would
-         * throw the rest away and, worse, usually find the newest still in flight and take
-         * nothing. */
+        /* Drain every landed histogram for the layer. The host runs this once per issued step,
+         * possibly far ahead of the card, so several may have landed since the last visit, and the
+         * newest is often still in flight. */
         int seen = r.heat_seen[(size_t)l];
         bool any = false;
         for (;;) {
@@ -259,9 +219,8 @@ void Engine::tiering_dispatch(Rank& r, int step) {
     for (size_t i = 0; i < rows.size(); ++i) {
         if (i + kAhead < rows.size()) r.heat.prefetch(rows[i + kAhead].h, n_ex);
         const Rank::HeatRow& hr = rows[i];
-        /* One histogram can stand for more than one pass: a draft head reports once per draft
-         * pass and they all land in the same bank. Crediting such a bank once underprices that
-         * layer's experts by the number of passes, and the engine then drains the layer. */
+        /* A bank can hold several passes (a draft head reports once per pass into one bank), so
+         * weight it by the report count, or the layer's experts are underpriced and drained. */
         const int reps = r.ctx.last_histogram_reports(hr.layer, hr.bank);
         r.heat.observe(hr.layer, hr.h, n_ex, reps > 1 ? (float)reps : 1.0f);
         r.heat_seen[(size_t)hr.layer] = r.ctx.last_histogram_step(hr.layer, hr.bank);
@@ -269,36 +228,29 @@ void Engine::tiering_dispatch(Rank& r, int step) {
         ++r.heat_credited;
     }
 
-    /* NO SWAPS BEHIND A PASS THE STAGER ARMED. Such a step is bound by its own copies -- every
-     * pooled expert of every routed layer crosses the link on the transfer stream a swap would
-     * share -- and the turnover slots a swap would land in are filled for it (below). The
-     * histograms are credited all the same, and the next step that stages nothing swaps on what
-     * they said. */
+    /* No swaps behind a pass the stager armed: that step is bound by its own copies on the same
+     * transfer stream, and the turnover slots are filled for it (below). Histograms are still
+     * credited; the next unstaged step swaps on them. */
     std::vector swaps;
     if (!r.stager.staged() && r.heat.step(&swaps) < 0) return;
     for (const Swap& s : swaps) {
-        /* CONTRACT: every unit the engine named is BUSY on the way out, and a proposal that is
-         * silently dropped leaves the pair busy forever. `issue` clears it; `abandon` is what
-         * this owes the engine when the mover cannot take it. */
+        /* Contract: every proposed unit is busy until `issue` takes it or `abandon` returns it;
+         * a dropped proposal stays busy forever. */
         if (r.mover.issue(s, &r.heat) < 0) r.heat.abandon(s);
     }
 
-    /* AFTER the swaps, because a swap is what the policy asked for and a fill is what the memory
-     * allows: spending a move record on a fill that the next swap then needs would let a
-     * boundary the arbiter happens to be moving reorder the engine's own decisions.
+    /* Fill after the swaps: swaps are the policy's decisions, fills only use spare memory, and a
+     * fill must not take a move record the next swap needs.
      *
-     * Behind a staged pass the turnover slots are filled too: that step swaps nothing, and kept
-     * free they are residents its stager copies instead -- at TP2 a 160K-token prompt staged
-     * 9.6% more and ran 3-5% slower.
+     * Behind a staged pass the turnover slots are filled too, since that step swaps nothing; left
+     * free, the stager would copy those residents instead (at TP2 a 160K-token prompt staged 9.6%
+     * more and ran 3-5% slower).
      *
-     * AND THEY STAY FILLED UNTIL kTurnoverAfter STEPS IN A ROW HAVE STAGED NOTHING, idle ticks
-     * included. A prompt answered in a token or two -- or a pause before the next one -- would
-     * otherwise drop them and copy them straight back at the next prompt's first chunk, across the
-     * link the chunk stages over, and each round trip scatters the lent residents through the
-     * pool runs the stager coalesces its copies on: at TP2, 26K-token prompts back to back ran
-     * 33 copies a staged layer that way against 16 held, and the first prompt after a pause up to
-     * 0.4% slower. A decode run reaches the count in a few steps, and its swaps land in the working
-     * slots until it does. */
+     * They stay filled until kTurnoverAfter consecutive unstaged steps (idle ticks included).
+     * Otherwise a short answer or a pause drops them and the next prompt's first chunk copies them
+     * back, scattering the lent residents through the pool runs the stager coalesces on (at TP2,
+     * back-to-back 26K-token prompts: 33 copies per staged layer instead of 16). Decode reaches the
+     * count in a few steps. */
     constexpr int kTurnoverAfter = 4;
     r.unstaged_steps = r.stager.staged() ? 0 : r.unstaged_steps + 1;
     const bool hold = r.unstaged_steps < kTurnoverAfter;
@@ -319,9 +271,8 @@ void Engine::rank_loop(int index) {
 
         const RadBatch* b = step_batch_.load(std::memory_order_acquire);
         if (b) {
-            /* This rank's view of the step: the same numbers, pointed at this card's staging.
-             * The upload that filled it was issued on THIS stream, so the ordering is an
-             * ordinary same-stream dependency and no cross-rank fence is needed. */
+            /* This rank's view of the step, pointing at this card's staging. Its upload was issued
+             * on this rank's stream, so no cross-rank fence is needed. */
             const RadBatch* mine = gen_ ? gen_->batch_for(index) : sched_.batch_for(index);
             if (!mine) {
                 RAD_ERR("rank %d: the builder has no batch for this rank", index);
@@ -336,19 +287,16 @@ void Engine::rank_loop(int index) {
                 RAD_ERR("rank %d step %d: %s", index, b->step, r.ctx.step_error());
                 step_status_.store(s, std::memory_order_release);
             } else if (b->n_out > 0 && what != kIssueModel) {
-                /* WAIT FOR THE STAGING, WHICH THE SCHEDULER IS DOING RIGHT NOW UNDER THE MODEL
-                 * THIS THREAD JUST ENQUEUED. Everything above is enqueue-and-return, so arriving
-                 * here means the device has a forward pass in front of it and this wait costs
-                 * nothing it was not going to spend in collect_step anyway. */
+                /* Wait for the scheduler's sampler staging, which runs while the device executes
+                 * the forward pass enqueued above, so the wait is hidden behind device work. */
                 int bst = RAD_OK;
                 {
                     std::unique_lock lk(build_mu_);
                     build_cv_.wait(lk, [this] { return build_ready_; });
                     bst = build_status_;
                 }
-                /* The sampler chain is issued on the SAME stream, right behind the model, with no
-                 * host synchronisation between them: it is more ops on the compute stream and not
-                 * a second phase (spec §13). */
+                /* The sampler chain goes on the same stream behind the model with no host sync
+                 * (spec §13). */
                 if (bst >= 0) {
                     /* The scored rows first: the sampler may rewrite a row in place. */
                     if (b->draft_pass == 0 && !score_rows_.empty()) s = issue_scored_rows(r);
@@ -369,14 +317,13 @@ void Engine::rank_loop(int index) {
 
 /* ------------------------------------------------------------------ the scheduler thread */
 int Engine::prepare_release(const RadBatch* b) {
-    /* THE ARENA LEVEL, AND THE ARENA'S MEMORY BACK FROM THE SLAB IF THIS STEP NEEDS IT. Every
-     * rank thread is parked, so a level can change and a recall can drain both streams. */
+    /* The arena level, recalling lent arena memory if this step needs it. Every rank thread is
+     * parked, so the level can change and a recall can drain both streams. */
     if (const int as = arena_step(b); as < 0) return as;
-    /* THE FOLLOWERS' POOLS, BEFORE THE TABLE THAT INDEXES THEM. Admission grew rank 0's cache for
-     * this step and the ids are already in the block table; a follower still at the old mark
-     * would read pages it never mapped. Here rather than on the arbiter's tick because the tick
-     * is 100 ms away and this step is about to run, and safe here because every rank thread is
-     * parked at the release. */
+    /* Grow the followers' pools to match rank 0's before the step's block table is used:
+     * admission grew rank 0's cache and the new ids are already in the table. Done here, not on
+     * the 100 ms arbiter tick, because the step is about to run; safe because every rank thread is
+     * parked. */
     for (size_t i = 1; i < ranks_.size(); ++i) {
         if (rad_dev_set(ranks_[i]->device) < 0) continue;
         if (ranks_[i]->kv.follow(ranks_[0]->kv) < 0)
@@ -393,8 +340,8 @@ int Engine::issue_ahead(const RadBatch** out) {
         sched_.expect_draft(serial_row_[(size_t)i].seq, serial_done_);
     const RadBatch* nb = sched_.step_next();
     if (!nb) return RAD_OK;
-    /* Its rows' tokens, positions and slots, from where this step's acceptance and drafts leave
-     * them -- in stream order behind all of it. */
+    /* Its rows' tokens, positions and slots, advanced on the card behind this step's acceptance
+     * and drafts. */
     RAD_TRY(advance_all(ADV_TRUNK, 0, false));
     RAD_TRY(prepare_release(nb));
     issue_what_.store(kIssueModel, std::memory_order_release);
@@ -417,14 +364,13 @@ void Engine::phase_mark(int p) {
     phase_t_ = now;
 }
 
-/* EVERY WAY OUT OF THE STEP LOOP ON AN ERROR GOES THROUGH HERE, because leaving it is three
- * obligations and forgetting one is a server that looks alive and serves nothing:
+/* Every error exit from the step loop goes through here, which does three things:
  *
- *   - the rank threads are parked on the barrier, and only an abort lets them see `stopping_`;
- *   - every request queued or running is waiting on a step that will never come, so it is failed
- *     now and its connection answered, and the scheduler refuses anything submitted after;
- *   - run_server watches `loop_status_` and takes the HTTP side down, so the process exits with
- *     the error rather than accepting requests into a queue nothing drains (spec §17). */
+ *   - aborts the barrier, so the parked rank threads see `stopping_`;
+ *   - fails every queued or running request and answers its connection; the scheduler then
+ *     refuses new submissions;
+ *   - sets `loop_status_`, which run_server watches to stop HTTP, so the process exits with the
+ *     error instead of queueing requests nothing will drain (spec §17). */
 int Engine::fail_loop(int st) {
     stopping_.store(true, std::memory_order_release);
     if (barrier_) barrier_->abort();
@@ -434,45 +380,25 @@ int Engine::fail_loop(int st) {
 }
 
 int Engine::step_loop() {
-    /* The batch is built on rank 0's stream into rank 0's memory and shared by pointer, so
-     * this thread lives on rank 0's device. The backend's current device is thread-local:
-     * a fresh thread starts on device 0, which is right only by accident. */
+    /* The batch is built on rank 0's stream into rank 0's memory, so this thread binds rank 0's
+     * device; the backend's current device is thread-local and starts at device 0. */
     if (rad_dev_set(ranks_[0]->device) < 0)
         RAD_ERR("step loop: could not bind rank 0's device");
     StepOut so;
     int idle = 0;
     std::vector cancel;
-    /* Not in the KL mode: its scored rows are copied out of the logits buffer after the step is
-     * collected, and a pass issued ahead would have overwritten them by then. */
+    /* Not in KL mode: its scored rows are copied out of the logits buffer after collection, and a
+     * pass issued ahead would overwrite them. */
     pipelining_ = !cfg_.kld() && !embedding_ && drafter_.kind != RAD_DRAFT_BLOCK &&
                   (serial_drafting() || cfg_.n_spec <= 0);
     const bool t_on = (int)log_level() >= (int)Log::Debug;
-    /* Read once. See the block in the idle branch below for what it is for. */
-    /* "kv" | "arena" | "all" | "kv:," -- the last narrows the KV scrub to named groups,
-     * which is the level below "it is the pool" and the one that names the defect. */
-    const char* const scrub_s_ = std::getenv("RADIANCE_DEBUG_IDLE_SCRUB");
-    std::string scrub_groups_;
-    int scrub_ = 0;
-    if (scrub_s_ && *scrub_s_) {
-        if (!std::strncmp(scrub_s_, "kv:", 3)) { scrub_ = 1; scrub_groups_ = std::string(",") + (scrub_s_ + 3) + ","; }
-        else if (!std::strcmp(scrub_s_, "kv"))    scrub_ = 1;
-        else if (!std::strcmp(scrub_s_, "arena")) scrub_ = 2;
-        else                                      scrub_ = 3;
-    }
-    if (scrub_)
-        RAD_WARN("RADIANCE_DEBUG_IDLE_SCRUB=%d: the %s%s%s will be ZEROED every time the engine "
-                 "goes idle. This is a determinism diagnostic and it is not free.", scrub_,
-                 (scrub_ & 1) ? "KV pool" : "", scrub_ == 3 ? " and the " : "",
-                 (scrub_ & 2) ? "activation arena" : "");
-
-    /* THE NEXT STEP'S FORWARD PASS, when it is already on the card: issued behind the step before
-     * it, before that step was read back (Scheduler::step_next). */
+    /* The next step's forward pass when already issued behind the previous step, before its
+     * readback (Scheduler::step_next). */
     const RadBatch* ahead = nullptr;
     while (!stopping_.load(std::memory_order_acquire)) {
         phase_t_ = std::chrono::steady_clock::now();
-        /* MEDIA A WAITING REQUEST NEEDS, encoded while nothing is in flight: the last step has been
-         * collected and none was issued ahead of it -- the scheduler issues none while a request
-         * is waiting, and one whose media is not encoded waits. */
+        /* Encode media for waiting requests while nothing is in flight. The scheduler issues no
+         * step ahead while a request waits, and a request with unencoded media waits. */
         if (!ahead && sched_.encodes_pending()) {
             if (const int es = run_encodes(); es < 0) return fail_loop(es);
         }
@@ -482,20 +408,18 @@ int Engine::step_loop() {
         if (issued) sched_.promote_next();
         else        b = sched_.step();
         if (!b) {
-            /* Nothing to run is not an error. Back off in small steps rather than spinning a core
-             * at idle; the first wait is short, because a request arriving into an empty engine
-             * should not pay for the queue having been empty. */
+            /* Idle: back off in small steps instead of spinning; the first wait is short so a new
+             * request into an empty engine is not delayed. */
             step_batch_.store(nullptr, std::memory_order_release);
             drain_completed();
             sched_.publish(/*idle=*/true);
-            /* Nothing could run because what can run is waiting on the encoder: go round now. */
+            /* Work is waiting only on the encoder: loop immediately. */
             if (sched_.encodes_pending()) { idle = 0; continue; }
-            /* A RELEASE THE LAST STEP DEFERRED AND NO COMMIT WILL NOW MAKE. A request cancelled
-             * while a drafter pass was being built keeps its blocks until the passes that name
-             * them have run (Scheduler::cancel), and commit() is where that normally lands -- an
-             * idle engine runs none, and blocks held by a cancelled request can be exactly what
-             * keep the next one from being admitted. The streams are drained first so no pass
-             * still in flight can be reading those blocks when they are handed on. */
+            /* Release deferred by the last step. A request cancelled while a drafter pass was being
+             * built keeps its blocks until the passes naming them run (Scheduler::cancel), and
+             * commit() normally releases them; an idle engine makes no commit, and those blocks
+             * may be what blocks the next admission. Drain the streams first so no in-flight pass
+             * still reads them. */
             if (sched_.has_deferred()) {
                 for (auto& rk : ranks_) (void)rad_stream_sync(rk->ctx.stream());
                 sched_.release_deferred();
@@ -503,63 +427,6 @@ int Engine::step_loop() {
             tier_tick();
             expire_tick(rad_mono_ns());
             loan_tick(/*idle=*/true);
-            /* RADIANCE_DEBUG_IDLE_SCRUB -- a DIAGNOSTIC, not a fix, and the one question it
-             * answers is whether request N+1 differs from request N because of bytes request N
-             * left behind. The engine is idle here: no sequence is live, so nothing in either the
-             * KV pool or the activation arena is owned by anybody and zeroing all of it is safe.
-             *
-             * `kv` zeroes every KV group's pool -- paged blocks included, which are NOT cleared on
-             * grab (see StateClear in mem/kv.h). `arena` zeroes the buffer plan, which is where
-             * every RAD_BUF_PERSIST buffer lives -- `qsa_tail` and `mtp_qsa_tail` among them, and
-             * those are indexed by SEQUENCE SLOT and are cleared for a new sequence by nothing at
-             * all. `all` does both.
-             *
-             * If the difference survives the scrub, bytes left behind are not its cause. */
-            if (scrub_ && idle == 0) {
-                for (auto& rk : ranks_) {
-                    if (scrub_ & 1)
-                        for (const KVGroupPlan& p : rk->kv.plans()) {
-                            if (!p.base || p.pool_bytes <= 0) continue;
-                            /* `name`, or `name@L`, or `name@LO-HI` -- a LAYER RANGE, because the
-                             * groups are bundles and the layers in one bundle are not one thing.
-                             * kv_attn carries the twelve trunk QSA layers AND the MTP draft head's
-                             * at index 12, and "which of those" is the question the group level
-                             * cannot answer. The pool is layer-major, so a layer is a contiguous
-                             * `layer_stride()` at `base + L * layer_stride()`. */
-                            int64_t lo = 0, hi = p.n_layers - 1;
-                            if (!scrub_groups_.empty()) {
-                                const size_t at = scrub_groups_.find("," + p.name + "@");
-                                const size_t plain = scrub_groups_.find("," + p.name + ",");
-                                if (at == std::string::npos && plain == std::string::npos) continue;
-                                if (at != std::string::npos) {
-                                    const char* q = scrub_groups_.c_str() + at + p.name.size() + 2;
-                                    lo = hi = std::strtoll(q, nullptr, 10);
-                                    if (const char* d = std::strchr(q, '-'))
-                                        if (d < std::strchr(q, ',')) hi = std::strtoll(d + 1, nullptr, 10);
-                                }
-                            }
-                            if (lo < 0) lo = 0;
-                            if (hi > p.n_layers - 1) hi = p.n_layers - 1;
-                            const int64_t stride = p.layer_stride();
-                            for (int64_t L = lo; L <= hi && stride > 0; ++L)
-                                rad_memset_async((char*)p.base + L * stride, 0, stride,
-                                                 rk->ctx.stream());
-                        }
-                    /* The arena's lent top holds expert weights, so it comes back first. */
-                    if ((scrub_ & 2) && !rk->arena_lent.empty()) {
-                        (void)rad_dev_set(rk->device);
-                        (void)rk->mover.reclaim(Mover::kLendArena, 0, &rk->heat);
-                        (void)rk->ctx.set_level(0);
-                        arena_floor_ = cfg_.max_tok;
-                        arena_floor_ns_ = rad_mono_ns();
-                    }
-                    if (scrub_ & 2)
-                        if (void* ab = rk->ctx.arena_base())
-                            if (const int64_t n = rk->ctx.arena_bytes(); n > 0)
-                                rad_memset_async(ab, 0, n, rk->ctx.stream());
-                    rad_stream_sync(rk->ctx.stream());
-                }
-            }
             if (idle < 200) ++idle;
             std::this_thread::sleep_for(std::chrono::microseconds(idle * 5));
             continue;
@@ -567,15 +434,11 @@ int Engine::step_loop() {
         idle = 0;
         if (t_on) phase_mark(PH_PLAN);
 
-        /* A FRESHLY ASSIGNED RECURRENT SLOT IS ZEROED BEFORE THE STEP THAT READS IT. The manager
-         * recorded the grab and cannot do the write itself (StateClear in core/mem/kv.h); this is
-         * the first moment a stream exists and the last before the ranks are released, and it is
-         * off the hot path -- the list is empty on every step but a sequence's first. Every rank
-         * clears its own pool BY ITS OWN PLAN: the slot number is the scheduler's, the memory and
-         * its size are the rank's. A state is as large as the heads this rank holds of the group,
-         * and the ranks' shares need not be equal (rad_arch.h remainder_place): a rank clearing
-         * rank 0's byte count of a larger state leaves its tail as the last sequence left it, and
-         * the recurrence reads it from the first token. */
+        /* Zero freshly assigned recurrent slots before the step that reads them. The manager
+         * records the grab but cannot write (StateClear in core/mem/kv.h); the list is empty except
+         * on a sequence's first step. Each rank clears by its own plan: the slot number is the
+         * scheduler's, but the state size depends on the heads this rank holds, which can differ
+         * per rank (rad_arch.h remainder_place). */
         for (const StateClear& c : ranks_[0]->kv.state_clears()) {
             for (auto& rk : ranks_) {
                 const KVGroupPlan* gp = rk->kv.plan(c.group);
@@ -588,16 +451,13 @@ int Engine::step_loop() {
         }
         ranks_[0]->kv.clear_state_clears();
 
-        /* Which entries want a logits row, in the order BatchBuilder wrote out_ids: entries with
-         * produces_token, 1 + n_spec rows each. Everything downstream indexes off this, because
-         * row index and sequence index are NOT the same -- a prefill chunk in the middle of a long
-         * prompt produces no row at all. */
+        /* Entries that want logits rows, in BatchBuilder's out_ids order: those with
+         * produces_token, 1 + n_spec rows each. Row and sequence indices differ (a mid-prompt
+         * chunk produces no row). */
         const StepPlan& plan = sched_.plan();
-        /* ONE ENTRY PER REQUEST, and the row counter is separate. Sampler::build_step expands
-         * each request into 1 + n_draft rows of its own -- that is where the per-position RNG
-         * coordinate comes from -- so pushing the request once per row here would stage (1+n)^2
-         * rows and overrun the arena whenever a drafter sets Request::n_draft. `first_row` is what
-         * indexes the sampled tokens, so it counts rows and not requests. */
+        /* One entry per request; Sampler::build_step expands each into 1 + n_draft rows itself
+         * (giving each position its RNG coordinate), so one push per row would stage (1+n)^2 rows.
+         * `first_row` indexes sampled tokens, so it counts rows. */
         so.reqs.clear();
         so.first_row.assign(plan.e.size(), -1);
         int32_t logit_row = 0;
@@ -611,31 +471,21 @@ int Engine::step_loop() {
         so.n_rows = logit_row;
         if (const int ss = stage_scored_rows(plan, so); ss < 0) return fail_loop(ss);
 
-        /* THE SAMPLER'S HOST WORK, staged by this lambda either in front of the ranks or -- by
-         * default, see build_mu_ in engine.h -- underneath them. It touches request state and the
-         * host grammar automata, which no rank thread reaches: every upload in the sampler chain
-         * is issued by Sampler::run, after the gate this fills.
+        /* The sampler's host work, run while the ranks enqueue (see build_mu_ in engine.h). It
+         * touches only request state and host grammar automata; Sampler::run issues the uploads
+         * after the gate opens.
          *
-         * CANCELLATIONS ARE COLLECTED, NOT APPLIED. A cancel touches scheduler state that the
-         * rank threads are reading through batch_for() while this runs; they are applied after the
-         * join, ahead of collect_step. */
+         * Cancellations are collected, not applied: the rank threads read scheduler state through
+         * batch_for() meanwhile. They are applied after the join, before collect_step. */
         auto stage_sampler = [&]() -> int {
         if (!so.reqs.empty() && !embedding_) {
-            /* PER-REQUEST SAMPLER STATE IS BUILT HERE, ON FIRST SIGHT. A grammar arrives compiled
-             * from admission and is only positioned here; a DRY sequence-breaker set is resolved
-             * against the vocabulary once. Both belong off the step path, and this is the first
-             * point on the scheduler thread where a request is known to be about to sample.
-             * Without it `seqs_` stays permanently empty, and `grammar` and
-             * `dry_sequence_breakers` are accepted by the API, carried through the request, and
-             * then quietly do nothing -- the one outcome core/server/oai.h's header forbids.
+            /* Per-request sampler state is built on first sight: the grammar (compiled at
+             * admission) is positioned and DRY sequence breakers are resolved against the
+             * vocabulary. Without this, `grammar` and `dry_sequence_breakers` would silently do
+             * nothing. Every rank does it, since each masks its own vocabulary shard.
              *
-             * EVERY RANK, because every rank masks its own vocabulary shard from its own automaton.
-             *
-             * A FAILURE HERE FAILS THE REQUEST, NOT THE ENGINE. A grammar this machine cannot run
-             * (left recursion, say) is a bad request, and taking the server down with it would let
-             * one caller end every other caller's generation. The server compiles at admission so
-             * this should already be unreachable; if it is reached, the request is cancelled with
-             * the reason in the log and the rest of the step goes on. */
+             * A failure (e.g. a left-recursive grammar) cancels the request, not the engine. The
+             * server compiles at admission, so this should be unreachable. */
             for (Request* rq : so.reqs) {
                 if (!rq) continue;
                 bool failed = false;
@@ -660,8 +510,7 @@ int Engine::step_loop() {
             for (auto& rk : ranks_) {
                 const int s = rk->sampler.build_step(so.reqs);
                 if (s < 0) { RAD_ERR("sampler build_step: %s", rad_strerror(s)); return s; }
-                /* A request the sampler could not serve is cancelled, not returned: the step goes
-                 * on for everyone else in the batch. */
+                /* A request the sampler could not serve is cancelled; the step goes on. */
                 for (uint64_t id : rk->sampler.take_failed()) cancel.push_back(id);
             }
             if (t_on) phase_mark(PH_BUILD);
@@ -672,12 +521,10 @@ int Engine::step_loop() {
         cancel.clear();
         int bst = RAD_OK;
 
-        /* ONE LINE PER STEP, on request. The shape of a step -- its phase, how many sequences,
-         * how many tokens each, and what context each is continuing from -- is the first thing
-         * anyone debugging a wrong answer needs, and no other log line carries it: -v prints the
-         * tokenizer and the loader and nothing about the steps that follow. Off by
-         * default because it is a line per step and decode steps are thousands of them. */
-        if (std::getenv("RADIANCE_LOG_STEPS")) {
+        /* RADIANCE_LOG_STEPS: one line per step with its phase and each sequence's slot, query
+         * length and context. Off by default (one line per decode step). */
+        static const bool log_steps = std::getenv("RADIANCE_LOG_STEPS") != nullptr;
+        if (log_steps) {
             std::string s = fmt("step %d %s n_seq=%lld n_tok=%lld", b->step,
                                 b->phase == RAD_PHASE_PREFILL ? "prefill" :
                                 b->phase == RAD_PHASE_DECODE  ? "decode"  : "MIXED",
@@ -688,14 +535,12 @@ int Engine::step_loop() {
             RAD_INFO("%s", s.c_str());
         }
 
-        /* THE RECURRENT HALF OF A PREFIX HIT, restored BEFORE the step that reads it. The adopted
-         * blocks carry the attention layers; this carries the recurrent ones, copied out of the
-         * snapshot's slot in host memory. Enqueued on each rank's own stream ahead of the
-         * release, so it is ordered before the kernels without a synchronisation -- the same way
-         * collect_step's readback is ordered after them.
+        /* Restore the recurrent half of a prefix hit before the step that reads it (the adopted
+         * blocks carry the attention layers), copying from the snapshot's host slot. Enqueued on
+         * each rank's stream before the release, so no synchronisation is needed.
          *
-         * UNDER THE SCHEDULER'S LOCK, because it reads the sequence table, which an HTTP thread's
-         * cancel mutates under that lock. Taken only on a step that has a restore in it. */
+         * Under the scheduler's lock, because an HTTP thread's cancel mutates the sequence table.
+         * Taken only when the step has a restore. */
         bool any_restore = false;
         for (const StepEntry& e : plan.e) if (e.ckpt_restore >= 0) { any_restore = true; break; }
         if (any_restore) {
@@ -703,7 +548,7 @@ int Engine::step_loop() {
                 for (const StepEntry& e : plan.e) {
                     if (e.ckpt_restore < 0) continue;
                     if (!state_slots_of(e.seq, &ckpt_slots_)) continue;
-                    /* The window behind the hit, in the blocks admit_one seeded at its floor. */
+                    /* The window behind the hit, in the blocks admit_one seeded. */
                     if (ranks_[0]->kv.has_window_snapshot() &&
                         !ranks_[0]->kv.window_rows(e.seq, e.ctx_len, &ckpt_win_)) {
                         RAD_ERR("sequence %llu: no window rows at %d to restore into",
@@ -712,7 +557,6 @@ int Engine::step_loop() {
                     }
                     for (size_t ri = 0; ri < ranks_.size(); ++ri) {
                         auto& rk = ranks_[ri];
-                        /* This rank's device, for its own stream and its own state slots. */
                         if (ranks_.size() > 1) (void)rad_dev_set(rk->device);
                         const int s = rk->kv.checkpoint_restore(ckpt_slots_.data(),
                                                                 (int)ckpt_slots_.size(),
@@ -733,16 +577,12 @@ int Engine::step_loop() {
             if (rs < 0) return fail_loop(rs);
         }
 
-        /* WHICH SIDE OF THE BARRIER THE TIME IS ON. Everything above this point is scheduler-thread
-         * work the device is idle for -- build_step, the grammar, the plan; everything between the
-         * two arrivals is the ranks ENQUEUEING, not running. A step that is slow for a host reason
-         * and one that is slow for a device reason look identical in total step time; this split
-         * is the only thing that tells them apart. */
+        /* Host time before the release, with the device idle; time between the two arrivals is
+         * the ranks enqueueing. The split separates host-bound from device-bound steps. */
         if (t_on) phase_mark(PH_PRE);
 
         if (!issued) {
-            /* The gate is reset while every rank is still parked at the release, so there is no
-             * window in which one can read a stale ready flag from the step before. */
+            /* Reset the gate while every rank is parked, so none sees a stale ready flag. */
             {
                 std::lock_guard lk(build_mu_);
                 build_ready_  = false;
@@ -754,9 +594,7 @@ int Engine::step_loop() {
             step_batch_.store(b, std::memory_order_release);
             barrier_->arrive_and_wait();      /* release the ranks */
             {
-                /* HERE IS THE POINT OF ALL OF IT: the ranks are enqueueing the forward pass and
-                 * the device is running it while this thread stages the sampler and walks the
-                 * grammar. */
+                /* Stage the sampler while the ranks enqueue and the device runs the pass. */
                 bst = stage_sampler();
                 {
                     std::lock_guard lk(build_mu_);
@@ -767,9 +605,9 @@ int Engine::step_loop() {
             }
             barrier_->arrive_and_wait();      /* wait for them */
         } else {
-            /* THE FORWARD PASS IS ALREADY ON THE CARD, issued behind the last step, and that step
-             * has now committed -- so the sampler is staged from exactly the state it would have
-             * been, and the ranks put the chain behind the pass while the card is still in it. */
+            /* The forward pass was issued ahead and the previous step has now committed, so the
+             * sampler is staged from the correct state and its chain queued behind the running
+             * pass. */
             bst = stage_sampler();
             {
                 std::lock_guard lk(build_mu_);
@@ -787,27 +625,21 @@ int Engine::step_loop() {
         for (uint64_t id : cancel) sched_.cancel(id);
         cancel.clear();
 
-        /* A staging failure is discovered with the ranks already released, so they have to be
-         * let go before this thread leaves -- the gate above carries the failure, so they have
-         * skipped the sampler and arrived at the join. */
+        /* A staging failure is known only after the ranks were released; the gate passed it to
+         * them, so they skipped the sampler and reached the join. */
         if (bst < 0) return fail_loop(bst);
 
         int st = step_status_.load(std::memory_order_acquire);
         if (st < 0) {
-            /* A device fault is not recoverable in process, and we do not serve from a wedged
-             * queue (spec §17): stop, release anyone parked on the barrier, and return. */
+            /* A device fault is not recoverable in-process (spec §17). */
             RAD_ERR("step %d failed: %s -- the engine cannot continue", b->step, rad_strerror(st));
             return fail_loop(st);
         }
 
-        /* AND THE SNAPSHOT, taken AFTER the step that produced the state. The chunker split this
-         * chunk so its last token IS the checkpoint position, so what copy 0 holds now is exactly
-         * the state at that position. It is a copy across the link into the snapshot's slot in host
-         * memory, issued before collect_step's readback synchronises and ahead of any step issued
-         * behind this one, which is what orders the next write of the state after it.
-         *
-         * Under the scheduler's lock for the reason the restore above is, and only on a step that
-         * writes a checkpoint. */
+        /* Snapshot after the step that produced the state: the chunker ended this chunk at the
+         * checkpoint position, so copy 0 holds exactly that state. The copy to the host slot is
+         * issued before collect_step's readback and before any step issued ahead, which orders the
+         * next write of the state after it. Under the scheduler's lock, as the restore. */
         bool any_save = false;
         for (const StepEntry& e : plan.e)
             if (e.ckpt_slot >= 0 && e.ckpt_tok >= 0) { any_save = true; break; }
@@ -816,10 +648,9 @@ int Engine::step_loop() {
                 for (const StepEntry& e : plan.e) {
                     if (e.ckpt_slot < 0 || e.ckpt_tok < 0) continue;
                     if (!state_slots_of(e.seq, &ckpt_slots_)) continue;
-                    /* The window behind the checkpoint position. The chunk that ends there
-                     * still holds it (its ensure kept the window behind the chunk's first
-                     * query), so a miss is a broken invariant -- and skipping would leave the
-                     * cache a slot it commits as valid with somebody else's pages in it. */
+                    /* The window behind the checkpoint position. The chunk ending there still
+                     * holds it, so a miss is a broken invariant; skipping would commit a slot
+                     * holding another sequence's pages. */
                     if (ranks_[0]->kv.has_window_snapshot() &&
                         !ranks_[0]->kv.window_rows(e.seq, e.ctx_len + e.ckpt_tok + 1,
                                                    &ckpt_win_)) {
@@ -849,19 +680,16 @@ int Engine::step_loop() {
         }
 
         if (t_on) phase_mark(PH_SAVE);
-        /* A SERIAL DRAFTER'S PASSES GO IN BEHIND THE STEP BEFORE ANYTHING WAITS FOR IT. The card
-         * works out the acceptance itself and every pass reads it from there (sched/advance.h),
-         * so the host has nothing to wait for until the step's last pass -- and the one wait below
-         * then covers the whole step. */
-        st = issue_serial_drafter(b->step, b, so);
+        /* Queue the serial drafter's passes behind the step before waiting: the card computes
+         * acceptance itself and every pass reads it there (sched/advance.h), so one wait covers
+         * the whole step. */
+        st = issue_serial_drafter(b->step, so);
         if (st < 0) return fail_loop(st);
         st = mark_step_end(b, so);
         if (st < 0) return fail_loop(st);
-        /* AND THE NEXT STEP'S FORWARD PASS, BEHIND ALL OF IT, before this step is read back. Its
-         * rows continue where the card's acceptance leaves them and verify what the drafter just
-         * proposed; its sampler waits for this step's commit, which it is staged from. So the card
-         * goes from this step's last pass straight into the next step's first, and the host's
-         * wait, commit and staging all happen while it runs. */
+        /* Then the next step's forward pass, before this step is read back. Its rows continue from
+         * the card's acceptance and verify the new drafts; its sampler waits for this step's
+         * commit. The card runs straight on while the host waits, commits and stages. */
         st = issue_ahead(&ahead);
         if (st < 0) return fail_loop(st);
         st = embedding_ ? collect_pooled(b, so) : collect_step(b, so);
@@ -872,21 +700,13 @@ int Engine::step_loop() {
             if (st < 0) return fail_loop(st);
         }
 
-        /* The buffer probe, after the trunk step: RADIANCE_DUMP_BUF names the buffers to print
-         * and trace level gates it, because dumping reads device memory back to the host and no
-         * serving run should pay for that. The drafters dump their own buffers after their own
-         * passes, for the reason engine_priv.h gives. */
-        if ((int)log_level() >= (int)Log::Trace)
-            dump_buffers(ranks_[0]->ctx, b->step, std::getenv("RADIANCE_DUMP_BUF"));
+        /* Buffer probe after the trunk step; drafters dump after their own passes. */
+        dump_buffers(ranks_[0]->ctx, b->step);
 
-        /* --profile-ops PRINTS WHILE THE SERVER IS STILL RUNNING rather than once at the end.
-         * The counters are cumulative, so each dump is the run so far and the us/call column is
-         * an average over it; a reader wants the table during the run it is diagnosing.
-         *
-         * Every 32 steps by default, and RADIANCE_PROFILE_EVERY moves it. Per-op timing restores
-         * a synchronisation around every launch -- over a thousand of them a step on a large
-         * model -- so a profiled step is several times slower and 32 of them is minutes. Often
-         * enough to read, rare enough not to bury the log. */
+        /* --profile-ops also prints during the run. Counters are cumulative, so each dump covers
+         * the run so far. Every 32 steps by default (RADIANCE_PROFILE_EVERY): per-op timing
+         * synchronises around every launch (over a thousand per step on a large model), so a
+         * profiled step is several times slower. */
         static const int prof_every = [] {
             const char* v = std::getenv("RADIANCE_PROFILE_EVERY");
             const int n = (v && *v) ? (int)std::strtol(v, nullptr, 10) : 32;
@@ -895,17 +715,13 @@ int Engine::step_loop() {
         if (cfg_.profile_ops && b->step > 0 && (b->step % prof_every) == 0)
             for (auto& rk : ranks_) rk->ctx.dump_profile();
 
-        /* One line a step at -vv. It is the only view of the loop there is: everything else the
-         * engine prints happens at startup, so a request that goes in and never comes out looks
-         * exactly like a request that never arrived. */
+        /* One line per step at -vv, the only log view of the loop itself. */
         RAD_TRACE("step %d: %lld tok / %lld seq, %lld logit row(s) -> tokens %s", b->step,
                   (long long)b->n_tok, (long long)b->n_seq, (long long)b->n_out,
                   so.token.empty() ? "(none)" : fmt("%d%s", so.token[0],
                                                     so.token.size() > 1 ? " ..." : "").c_str());
-        /* AND WHAT WENT IN. Every op in the forward pass can agree with the reference and the
-         * answer still be wrong if the ids are not the ids the model was trained on; the two look
-         * identical from the logits, which is why this is printed beside them rather than left to
-         * be inferred. Bounded at 32 because a 2048-token prefill's ids are not a log line. */
+        /* And the input ids (first 32): wrong ids look like a wrong forward pass from the logits
+         * alone. */
         if ((int)log_level() >= (int)Log::Trace && b->n_tok > 0 && b->token_ids) {
             std::string ids;
             const int64_t n = std::min(b->n_tok, 32);
@@ -931,19 +747,15 @@ int Engine::step_loop() {
         if (t_on) phase_mark(PH_COMMIT);
         if (st < 0) { RAD_ERR("commit: %s", rad_strerror(st)); return fail_loop(st); }
 
-        /* THE DRAFTER FOR THE NEXT STEP. A block drafter runs here, because its passes are staged
-         * from the committed sequence; a serial one already ran on the card behind the step, and
-         * what is left is to check its acceptance against the host's and publish its proposals.
-         *
-         * ONE SWITCH ON A DECLARED SHAPE, not on a model. Both drivers return RAD_OK immediately
-         * when the declared kind is not theirs, so a program with no drafter costs a compare. */
+        /* The drafter for the next step. A block drafter runs here, since its passes are staged
+         * from the committed sequence. A serial one already ran on the card; what remains is to
+         * check its acceptance against the host's and publish its proposals. Both drivers return
+         * immediately for a kind that is not theirs. */
         st = drafter_.kind == RAD_DRAFT_BLOCK ? run_block_drafter(b->step)
                                               : finish_serial_drafter(so);
         if (st < 0) return fail_loop(st);
-        /* AND NOW THE STEP IS OVER. The draft rounds above are forward passes and they belong to
-         * the step that paid for them; charging the step at commit would leave them in the gap
-         * between one iteration and the next, which nothing measures. Scheduler::step_finished
-         * says what that costs. */
+        /* The step ends here, after its draft rounds, so step timing includes them
+         * (Scheduler::step_finished). */
         sched_.step_finished();
         tier_tick();
         loan_tick(/*idle=*/false);
@@ -953,10 +765,8 @@ int Engine::step_loop() {
         drain_completed();
         sched_.publish(/*idle=*/false);
 
-        /* ONE LINE EVERY 128 STEPS, and it adds up to the step. `ranks` is the enqueue, not the
-         * execution: the device work is waited for in `collect`, which is the only host
-         * synchronisation a step has, so `collect` is where device time shows up and any host
-         * cost the ranks could have been running under is time `collect` did not get to hide. */
+        /* One line every 128 steps; the phases sum to the step. `ranks` is the enqueue; device time
+         * shows up in `collect`, the step's only host synchronisation. */
         if (t_on) {
             phase_mark(PH_DRAFT);
             if (++phase_n_ == 128) {
@@ -978,10 +788,10 @@ int Engine::step_loop() {
     return RAD_OK;
 }
 
-/* THE SAMPLED IDS ON THEIR WAY TO THE HOST: a copy into pinned memory behind the sampler, and
- * nothing waited for. Issued by the serial drafter before its passes -- a head that samples
- * through the sampler's own buffer overwrites the ids -- and otherwise right before the wait. */
-int Engine::collect_issue(const RadBatch* b, StepOut& so) {
+/* Issue the copy of the sampled ids into pinned memory behind the sampler, without waiting.
+ * Issued by the serial drafter before its passes (a head sampling through the sampler's buffer
+ * overwrites the ids), otherwise just before the wait. */
+int Engine::collect_issue(StepOut& so) {
     so.rb = nullptr;
     so.lg.clear();
     if (so.n_rows <= 0) return RAD_OK;
@@ -995,11 +805,8 @@ int Engine::collect_issue(const RadBatch* b, StepOut& so) {
     if (!so.rb) return RAD_E_NOMEM;
     RAD_TRY(rad_memcpy_async(so.rb, src, (int64_t)so.n_rows * 4, r0.ctx.stream()));
 
-    /* THE FIRST FEW LOGITS, at -vv. There is no other window into the forward pass: rad-kbench can
-     * falsify one op against the oracle but nothing compares a whole layer, so when every op agrees
-     * and the model still answers the same token to every prompt, the question "are the logits even
-     * a function of the input" has no cheaper answer than looking. One copy on a path that already
-     * synchronises, and only when the operator asked for trace. */
+    /* The first logits row at -vv, the only direct view of the forward pass's output (rad-kbench
+     * checks single ops, not whole layers). */
     const int64_t nv = meta_.n_vocab;
     if ((int)log_level() >= (int)Log::Trace && nv > 0) {
         void* lp = r0.ctx.buf_ptr(r0.program.logits_buf);
@@ -1013,13 +820,12 @@ int Engine::collect_issue(const RadBatch* b, StepOut& so) {
 
 int Engine::mark_step_end(const RadBatch* b, StepOut& so) {
     if (embedding_) RAD_TRY(collect_pooled_issue(b, so));
-    else if (so.n_rows > 0 && !so.rb) RAD_TRY(collect_issue(b, so));
+    else if (so.n_rows > 0 && !so.rb) RAD_TRY(collect_issue(so));
     return rad_event_record(step_end_, ranks_[0]->ctx.stream());
 }
 
-/* AN EMBEDDING STEP'S ANSWER, ON ITS WAY TO THE HOST: the pooled buffer's first n_seq rows, copied
- * into pinned memory behind the pass on rank 0's stream -- every rank holds the same vectors, so
- * one copy is the answer. Nothing waits here; collect_pooled does, once. */
+/* Issue the copy of an embedding step's pooled rows (the first n_seq) into pinned memory on rank
+ * 0's stream; every rank holds the same vectors. collect_pooled waits. */
 int Engine::collect_pooled_issue(const RadBatch* b, StepOut& /*so*/) {
     if (b->n_seq <= 0) return RAD_OK;
     Rank& r0 = *ranks_[0];
@@ -1033,9 +839,8 @@ int Engine::collect_pooled_issue(const RadBatch* b, StepOut& /*so*/) {
                             r0.ctx.stream());
 }
 
-/* Each sequence's vector to its request's sink, and the step's three per-sequence arrays set so
- * the commit FINISHES every request it carried: an embedding request is one step long. The token
- * is never emitted (Request::embed), so its value is irrelevant; eos is what ends the request. */
+/* Hand each sequence's vector to its sink, and set eos for every sequence so the commit finishes
+ * it: an embedding request is one step long. The token is never emitted (Request::embed). */
 int Engine::collect_pooled(const RadBatch* b, StepOut& so) {
     const StepPlan& plan = sched_.plan();
     so.token.assign(plan.e.size(), 0);
@@ -1062,13 +867,11 @@ int Engine::collect_pooled(const RadBatch* b, StepOut& so) {
     return RAD_OK;
 }
 
-/* THE SCORED ROWS (Request::token_scores): the logits row at a scored prompt's last position, on
- * its way to the host before the sampler can rewrite it in place. Three parts, on three threads'
- * turns: which rows, decided with the rows themselves and while every rank is parked
- * (stage_scored_rows); one copy a row on each rank's own stream, right ahead of its sampler
- * (issue_scored_rows); and each request's ids read out of the staging after the step's one wait
- * (collect_scored_rows), which is ahead of the commit that finishes the request. A whole row
- * crosses, not the ids: one copy of 512 KB at a 128K vocabulary is cheaper than a copy an id. */
+/* Scored rows (Request::token_scores): the logits row at a scored prompt's last position, copied
+ * to the host before the sampler can rewrite it in place. stage_scored_rows picks the rows while
+ * every rank is parked; issue_scored_rows copies one row per rank stream ahead of its sampler;
+ * collect_scored_rows reads each request's ids after the step's wait, before the commit. A whole
+ * row is copied (512 KB at a 128K vocabulary), which is cheaper than one copy per id. */
 int Engine::stage_scored_rows(const StepPlan& plan, const StepOut& so) {
     score_rows_.clear();
     if (embedding_) return RAD_OK;
@@ -1132,11 +935,9 @@ int Engine::collect_scored_rows() {
     return RAD_OK;
 }
 
-/* One sampled row's logprobs into the step's table, which is sized on the first row that asks.
- * A ROW WHOSE LOGPROBS CANNOT BE COMPUTED FAILS ITS REQUEST, NOT THE STEP: its numbers are not
- * finite (RAD_E_INVAL), so its entry is left at token -1 (TokenLogprobs), which the scheduler
- * answers by failing that request with the reason, and every other sequence in the batch goes on.
- * A row outside the step, or one that was never staged for logprobs, is the engine's own fault. */
+/* One sampled row's logprobs into the step's table, sized on first use. A non-finite row
+ * (RAD_E_INVAL) is left at token -1, and the scheduler fails only that request. A row outside the
+ * step, or never staged for logprobs, is an engine error. */
 int Engine::row_logprobs(StepOut& so, int32_t row, int32_t token) {
     if (so.lp.empty()) so.lp.resize((size_t)so.n_rows);
     if (row < 0 || row >= so.n_rows) return RAD_E_STATE;
@@ -1146,9 +947,8 @@ int Engine::row_logprobs(StepOut& so, int32_t row, int32_t token) {
     return s;
 }
 
-/* Wait for the sampled ids and turn them into the three per-sequence arrays the scheduler wants.
- * This is the ONE host synchronisation on the step path: the host needs the tokens to commit them
- * and to stream them. Everything else in a step is enqueued and never waited on (spec §5.4). */
+/* Wait for the sampled ids and build the scheduler's per-sequence arrays. The step path's only
+ * host synchronisation: the host needs the tokens to commit and stream them (spec §5.4). */
 int Engine::collect_step(const RadBatch* b, StepOut& so) {
     const StepPlan& plan = sched_.plan();
     so.token.assign(plan.e.size(), 0);
@@ -1158,8 +958,7 @@ int Engine::collect_step(const RadBatch* b, StepOut& so) {
     if (so.n_rows <= 0) return RAD_OK;
 
     so.rows.resize((size_t)so.n_rows);
-    /* The step's one wait. For the step's end and not for the stream: a step issued ahead is
-     * behind it, and the host's commit and staging are what that step runs over. */
+    /* Wait on the step-end event, not the stream: a step issued ahead is queued behind it. */
     RAD_TRY(rad_event_sync(step_end_));
     std::memcpy(so.rows.data(), so.rb, (size_t)so.n_rows * sizeof(int32_t));
     so.rb = nullptr;
@@ -1167,9 +966,8 @@ int Engine::collect_step(const RadBatch* b, StepOut& so) {
     const std::vector& lg = so.lg;
     const int64_t nv = meta_.n_vocab;
     if (!lg.empty()) {
-        /* The top three of the first sampled row. A sampler that answers the same token to every
-         * prompt is either reading a distribution with a fixed spike in it or not reading the
-         * distribution at all, and the two look identical from outside. */
+        /* Top three of the first sampled row, to tell a fixed spike in the distribution from a
+         * sampler that ignores it. */
         int64_t i0 = 0, i1 = 0, i2 = 0;
         for (int64_t i = 1; i < nv; ++i) {
             if (lg[(size_t)i] > lg[(size_t)i0])      { i2 = i1; i1 = i0; i0 = i; }
@@ -1189,76 +987,47 @@ int Engine::collect_step(const RadBatch* b, StepOut& so) {
         const StepEntry& e = plan.e[i];
 
         if (e.n_spec > 0) {
-            /* THE COMPARISON IS AGAINST THE TARGET'S OWN SAMPLED TOKEN, AND THAT IS EXACT AT ANY
-             * TEMPERATURE. It looks as though everything but temperature 0 has to be refused: a
-             * positive temperature needs rejection sampling, and rejection sampling needs the
-             * target's probability planes, which this path does not bring back. Both halves are
-             * true and the conclusion does not follow, because there is a third rule that needs
-             * no planes at all:
+            /* Accept draft[k] when it equals the token the target itself drew at position k. This
+             * is exact at any temperature without rejection sampling or probability planes,
+             * because the sampler gives every verified position its own RNG coordinate
+             * (`p.pos = n_out + k`, sampler.cpp): y_k is the target's own draw at that output
+             * position, and each later token is conditioned on a prefix accepted only because it
+             * matched. The output is a draw from the target.
              *
-             *   accept draft[k] when it equals the token the target ITSELF drew at position k.
+             * It is not byte-identical to non-speculative decoding above temperature 0: a verify
+             * step computes 1 + n_spec rows and split-K depends on M, so logits differ slightly
+             * and a pick near a CDF boundary can flip. Greedy output matches exactly; both are
+             * deterministic.
              *
-             * That is exact because the sampler gives every verified position its own RNG
-             * coordinate -- `p.pos = n_out + k`, "its randomness is the same whether it arrived
-             * through speculation or one token at a time" (sampler.cpp). So y_k is the draw the
-             * target's own distribution specifies at that output position. The first emitted token
-             * is y_0 whether or not the draft agreed; every later one is conditioned on a prefix
-             * that was accepted only because it matched, so the conditioning is the one the target
-             * asked for. The emitted sequence is a draw from the target, not an approximation of
-             * one.
-             *
-             * IT IS NOT, HOWEVER, BYTE-IDENTICAL TO A NON-SPECULATIVE RUN ABOVE TEMPERATURE 0, and
-             * that is worth stating because the paragraph above sounds like it should be. The rule
-             * is exact given the same logits; the logits themselves are shape-dependent, because a
-             * verify step computes 1 + n_spec rows where a decode step computes one and split-K
-             * picks its count from M. At temperature 0 that survives the argmax and the text
-             * matches exactly. Above it a sampled pick near a CDF boundary can land the other way,
-             * so spec and non-spec agree on most prompts and not all -- deterministic and
-             * reproducible either way, and a property of the GEMMs rather than of acceptance.
-             *
-             * It accepts less often than optimal rejection sampling -- P(y == x) rather than
-             * min(1, p/q) -- and that is the whole price. Refusing instead would cost the request
-             * every drafted token AND take the step down with it, failing every other request
-             * batched alongside, for the common case of a client that left temperature at 1.
-             *
-             * `so.rows` is the sampler's OUTPUT, which is the sampled token -- at temperature 0
-             * that is the argmax, which is why the greedy-acceptance name still fits. */
+             * The cost is a lower acceptance rate than rejection sampling (P(y == x) instead of
+             * min(1, p/q)). `so.rows` holds the sampled tokens (the argmax at temperature 0). */
             if (!e.req) continue;
             int32_t out[RAD_SCHED_MAX_SPEC + 1] = { 0 };
             int32_t acc = 0;
             RAD_TRY(accept_greedy(e.draft, e.n_spec, &so.rows[(size_t)so.first_row[i]], out, &acc));
 
-            /* THE TURN CAN END IN THE MIDDLE OF AN ACCEPTED RUN, and stopping only on the last
-             * token of it is how the engine generates past the end of a turn. accept_greedy stops
-             * at the first DISAGREEMENT, not at the first end-of-generation token -- and a drafter
-             * that correctly predicts the model is about to stop AGREES about the stop token, so
-             * the run continues past it. Everything after it is the model writing the next turn:
-             * `<|im_end|><|im_start|>user ...` decoded, with the control tokens rendering as
-             * nothing, which reads as a model that rambles rather than as a bug in the accept
-             * path. Truncating here rather than in the scheduler keeps one definition of "how far
-             * did this step get" -- `accepted` and `token` are what the KV rollback, the conv
-             * cursor and the emitted text are all derived from. */
-            for (int32_t j = 0; j <= acc; ++j) {
-                if (vocab_ && vocab_->is_eog(out[j])) { acc = j; break; }
-            }
+            /* Truncated at the first end-of-generation token, so `accepted` and `token` (which
+             * drive the KV rollback, the conv cursor and the emitted text) say how far the step
+             * really got. */
+            acc = accept_cut_at_eog(out, acc,
+                                    [&](int32_t t) { return vocab_ && vocab_->is_eog(t); });
 
             so.accepted[i] = acc;
             so.token[i]    = out[acc];
             so.eos[i]      = vocab_ && vocab_->is_eog(so.token[i]) ? 1 : 0;
-            /* Each emitted token's logprobs from its own row: an accepted draft is the token the
-             * target drew at its position, so its row is the distribution it came from. */
+            /* Each emitted token's logprobs come from its own row, the distribution it was drawn
+             * from. */
             if (e.req && e.req->sp.n_probs >= 0)
                 for (int32_t j = 0; j <= acc; ++j)
                     RAD_TRY(row_logprobs(so, so.first_row[i] + j, out[j]));
-            /* EVERY token that leaves, in order: the grammar's state has to advance over the
-             * accepted drafts too, or the next step's mask is built n_accepted tokens behind.
-             * Bounded by the truncated `acc`, so it sees exactly the tokens the client does. */
+            /* Advance the grammar over every emitted token, accepted drafts included, up to the
+             * truncated `acc`, so it sees exactly what the client sees. */
             if (e.req)
                 for (auto& rk : ranks_)
                     for (int32_t j = 0; j <= acc; ++j) {
                         const int as = rk->sampler.accept_token(e.req->id, out[j]);
-                        /* A parse that outgrew the grammar's bounds is the request's, not a
-                         * defect: the backend is dead and the request fails at its next mask. */
+                        /* A parse that outgrew the grammar's bounds fails the request at its next
+                         * mask; not an engine defect. */
                         if (as == RAD_E_FULL || as == RAD_E_NOMEM)
                             RAD_WARN("engine: req %llu: its grammar's parse outgrew the bounds a "
                                      "grammar may use at token %d; the request fails at its next "
@@ -1277,19 +1046,14 @@ int Engine::collect_step(const RadBatch* b, StepOut& so) {
         so.eos[i]   = vocab_ && vocab_->is_eog(so.token[i]) ? 1 : 0;
         if (e.req && e.req->sp.n_probs >= 0)
             RAD_TRY(row_logprobs(so, so.first_row[i], so.token[i]));
-        /* The grammar must see the token it just emitted, or the next step's mask is built from a
-         * state one token behind the sequence. EVERY rank, not just rank 0: each rank builds the
-         * mask for its own vocabulary shard from its own automaton, so a rank whose grammar did
-         * not advance masks the next step against the previous token's state. */
+        /* Advance the grammar on every rank: each builds the mask for its own vocabulary shard from
+         * its own automaton. */
         if (e.req)
             for (auto& rk : ranks_) rk->sampler.accept_token(e.req->id, so.token[i]);
     }
 
-    /* WHETHER EACH REQUEST MAY BE SPECULATED ON NEXT STEP, decided HERE and not in the block that
-     * starts requests, because the answer changes exactly where this loop just changed it: a lazy
-     * grammar becomes constraining inside accept_token, above. Deciding it any later means the
-     * scheduler sizes the next step from a stale answer and hands a constrained request a draft
-     * the sampler will then refuse. */
+    /* Update may_speculate here, because a lazy grammar becomes constraining inside accept_token
+     * above; a stale value would give a constrained request a draft the sampler refuses. */
     for (size_t i = 0; i < plan.e.size(); ++i) {
         const StepEntry& e = plan.e[i];
         if (!e.req) continue;
@@ -1299,59 +1063,37 @@ int Engine::collect_step(const RadBatch* b, StepOut& so) {
     return RAD_OK;
 }
 
-/* Requests that reached a terminal state. The server drains the text through the sink and calls
- * reap(), which is what finally lets the Request go -- only the HTTP thread knows when it has
- * stopped writing into it. All this does is drop the sampler's per-request host state. */
-/* ------------------------------------------------------------------ the idle-tier tick */
-/* EVERY ITERATION, ON BOTH PATHS. A copy to host memory is asynchronous and reported when its
- * event has signalled, so the tick that collects it is simply the first one after it landed; the
- * next copy is handed out on the same tick. Tying either to a slower clock would only delay the
- * moment a finished conversation's VRAM can be given up. Room in a full arena is made at once
- * when the host tier has refused a copy for want of it, since that copy is waiting on it.
+/* ------------------------------------------------------------------ the KV loan */
+/* The only place the boundary between the KV cache and the expert slab moves.
  *
- * THE SCHEDULER'S LOCK IS HELD FOR THE BOOKKEEPING ONLY. Planning a batch and reporting one touch
- * rank 0's manager, the prefix cache and -- through the tiers' drop sinks -- the index an HTTP
- * thread's cancel also changes; issuing the transfers and polling them touch none of that, and a
- * transfer's records are pending the whole time it is out, which is what keeps everything else off
- * them without a lock. */
-/* THE ONE PLACE THE BOUNDARY BETWEEN THE KV CACHE AND THE EXPERT SLAB MOVES.
+ * The budget divides the card once at startup, so an unused KV block is VRAM no expert can use.
+ * The cache therefore lends what it does not hold at addresses it already owns: no allocation,
+ * mapping or driver call. There is exactly one lender, so the same memory is never in two pools.
  *
- * The budget divides the card once, at startup: a KV block nothing holds is VRAM no expert can
- * use, and an expert that does not fit is read across the link on the critical path of every step
- * that routes to it. The cache therefore LENDS what it is not holding, at the addresses it already
- * owns -- nothing is allocated, mapped or released, so the loan moves with no driver call and the
- * card's free VRAM is the same before and after. There is exactly one lender: two owners with two
- * opinions about how much is spare is the same memory in two pools.
+ * The order is the safety argument:
  *
- * THE ORDER IS THE WHOLE SAFETY ARGUMENT:
- *
- *   1. the cache says what it can spare -- above the highest block it holds, less its buffer;
- *   2. the cache's mark is set from the larger of that and what every rank's slab ACTUALLY
- *      HOLDS -- a shrink is met as units leave the slots, and reading the offer instead would put
- *      the same blocks in both pools;
+ *   1. the cache reports what it can spare (above its highest held block, less its buffer);
+ *   2. the cache's mark is set to the larger of that and what any rank's slab actually holds, so
+ *      a shrink completes only as units leave the slots;
  *   3. only then are the slabs told the offer, which they fill into or drain out of.
  *
- * A request that cannot wait for a shrink does not wait for one: the cache calls back into every
- * slab and has the blocks at once (KVManager::set_reclaim, installed in start()). */
+ * A request that cannot wait for a shrink takes the blocks at once through a callback into every
+ * slab (KVManager::set_reclaim, installed in start()). */
 void Engine::loan_tick(bool idle) {
     if (!lending_) return;
     const uint64_t now = rad_mono_ns();
     if (now - loan_last_ns_ < 100000000ull) return;    /* 100 ms */
     loan_last_ns_ = now;
 
-    /* UNDER THE SCHEDULER'S LOCK: the loan moves rank 0's live mark and free count, which an HTTP
-     * thread's cancel changes under that lock when it frees a sequence, and /metrics reads them
-     * under it. */
+    /* Under the scheduler's lock: the loan moves rank 0's live mark and free count, which an HTTP
+     * thread's cancel changes and /metrics reads under that lock. */
     const auto lk = sched_.hold();
     Rank& lead = *ranks_[0];
 
-    /* A FINISHED CONVERSATION'S VRAM IS ALREADY FREE by the time this runs: tier_tick gives up
-     * every entry whose host copy has landed, so what the cache can spare below counts it. */
-    /* WHAT THE CACHE CAN DO WITHOUT, AND WHAT THE SLABS STILL OCCUPY. A loan grows as soon as the
-     * cache can spare it -- the slots are filled on the next dispatch or the next idle tick -- but
-     * only by at least a prefill chunk, so a cache breathing by a few blocks does not have its
-     * boundary chase it. It shrinks at once, and the cache gets the blocks back as the slabs
-     * leave them: the cache's mark is never above the deepest slot any rank's slab still holds. */
+    /* tier_tick has already released every entry whose host copy landed, so `spare` counts
+     * finished conversations. The loan grows only in steps of at least a prefill chunk, so small
+     * fluctuations do not move the boundary; it shrinks at once, the cache regaining blocks as the
+     * slabs vacate them. */
     const int64_t cur   = lead.kv.loan_tokens();
     const int64_t spare = lead.kv.spare_tokens();
     const int64_t chunk = std::max(cfg_.max_tok, 1);
@@ -1360,10 +1102,8 @@ void Engine::loan_tick(bool idle) {
     int64_t held = 0;
     for (auto& r : ranks_) held = std::max(held, r->mover.loan_held(Mover::kLendKV));
 
-    /* THE CACHE FIRST WHEN THE LOAN GROWS, THE SLABS FIRST WHEN IT SHRINKS. Either way no block is
-     * both handed out by the cache and a slot in a slab: a growing loan is lent only once the
-     * cache has stopped handing those blocks out, and a shrinking one is returned to the cache
-     * only as the slabs leave it. */
+    /* The cache moves first when the loan grows, the slabs first when it shrinks, so no block is
+     * ever both a cache block and a slab slot. */
     if (lead.kv.set_loan(std::max(offer, held)) < 0) {
         RAD_ERR("kv loan: the cache refused a loan of %lld tokens it said it could spare; lending "
                 "stops", (long long)std::max(offer, held));
@@ -1384,34 +1124,27 @@ void Engine::loan_tick(bool idle) {
 }
 
 /* ------------------------------------------------------------------ the arena's level */
-/* WHICH LEVEL THE STEP RUNS AT, AND WHAT THE SLAB MAY KEEP OF THE ARENA WHILE IT DOES.
+/* Pick the step's arena level and how much of the arena the slab may keep. A step's rows are its
+ * tokens or, for the drafter's passes, one per drafted position per sequence; the smallest level
+ * serving that many is used, else the full plan, which lends nothing.
  *
- * The rows a step puts through the arena are its tokens and, after it, the drafter's passes --
- * at most one row per drafted position of every sequence. The smallest level serving that many is
- * the one the step runs at; a step larger than every level runs at the full plan, which lends
- * nothing.
- *
- * A LEVEL THAT NEEDS MORE THAN THE SLAB LEFT IT TAKES IT BACK BEFORE THE STEP, synchronously: the
- * units in the slots it needs go back to their host copies, which is a change of address and not
- * a copy, and both streams that can read a slot are drained before this returns. The first chunk
- * of a prefill pays that once; the chunks after it find the memory already theirs, because the
- * loan does not grow again until the steps have been small for a while (arena_tick). */
+ * If the level needs memory the slab holds, it is reclaimed synchronously before the step: units
+ * in those slots revert to their host copies (an address change, not a copy) and both streams
+ * that can read a slot are drained. A prefill pays this on its first chunk only, since the loan
+ * does not regrow until steps have been small for a while (arena_tick). */
 int Engine::arena_step(const RadBatch* b) {
     if (arena_rows_.size() <= 1 || !b) return RAD_OK;
-    /* AN ENCODER PASS TAKES THE FULL PLAN: its activations are sized by the pass, not by a step's
-     * rows, and only the full plan holds them (a plugin declares them small under shape_probe). */
+    /* An encoder pass needs the full plan: its activations are sized by the pass, and a plugin
+     * declares them small under shape_probe. */
     const int64_t need = b->enc ? INT64_MAX : std::max(
         b->n_tok, (int64_t)b->n_seq * (1 + std::max(cfg_.n_spec, 0)));
-    int level = 0;
-    for (size_t k = 1; k < arena_rows_.size(); ++k)
-        if (arena_rows_[k] >= need && (level == 0 || arena_rows_[k] < arena_rows_[(size_t)level]))
-            level = (int)k;
+    const int level = arena_level(need);
     const uint64_t now = rad_mono_ns();
     arena_last_ = arena_rows_[(size_t)level];
     if (arena_last_ >= arena_floor_) { arena_floor_ = arena_last_; arena_floor_ns_ = now; }
-    /* Whether the step after this one goes on with a prompt, for the stager to stage that step's
-     * first layers at this one's end. A step issued ahead is a decode step and the plan the
-     * scheduler holds is not its own, so it never says so. */
+    /* Whether the next step continues a prompt, so the stager stages its first layers at this
+     * step's end. Never for a step issued ahead (a decode step whose plan the scheduler does not
+     * hold). */
     const bool more = b->phase != RAD_PHASE_DECODE && sched_.prefill_continues();
     for (auto& r : ranks_) {
         const int64_t allow = r->arena_lent[(size_t)level];
@@ -1426,29 +1159,36 @@ int Engine::arena_step(const RadBatch* b) {
             }
         }
         RAD_TRY(r->ctx.set_level(level));
-        /* The full plan lends nothing, so its top -- the staging region -- is the step's. */
-        r->stager.set_full_arena(level == 0);
+        /* The full plan lends nothing, so its top (the staging region) is the step's ring; the
+         * span's shared level keeps a place of its own for it (stager.h); every other level
+         * lends both. */
+        char* const ring = level == 0 ? r->stager.ring_full()
+                         : arena_last_ == arena_span_rows_ && r->arena_low_off >= 0
+                               ? r->stager.ring_low() : nullptr;
+        r->stager.set_ring(ring);
+        /* The next step's first layers go ahead only from the full plan, into the region at the
+         * top that no level's buffers use. At the shared level the ring is memory the full plan
+         * computes in, and a copy still going there when such a step starts would race it; a
+         * pass's own copies are behind its own ops, which wait for them. */
         r->stager.set_next_prefill(more && level == 0);
     }
     if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device);
     return RAD_OK;
 }
 
-/* THE LOAN GROWS ONLY ONCE THE LARGE STEPS HAVE STOPPED. A prefill is a run of chunks with decode
- * steps between them, and lending the arena out after every chunk would refill the slab across
- * the link and recall it at the next one. So the floor -- the largest step seen -- holds for two
- * seconds after it was last reached, and only then falls to the size of the latest step. */
+int Engine::arena_level(int64_t rows) const { return arena_level_for(arena_rows_, rows); }
+
+/* The arena loan grows only after large steps stop. A prefill is chunks with decode steps between,
+ * and lending after every chunk would refill and recall the slab each time. So the floor (the
+ * largest step seen) holds for two seconds after it was last reached, then falls to the latest
+ * step's size. */
 void Engine::arena_tick(uint64_t now_ns) {
     if (arena_rows_.size() <= 1) return;
     if (arena_last_ < arena_floor_ && now_ns - arena_floor_ns_ > 2000000000ull) {
         arena_floor_ = arena_last_;
         arena_floor_ns_ = now_ns;
     }
-    int level = 0;
-    for (size_t k = 1; k < arena_rows_.size(); ++k)
-        if (arena_rows_[k] >= arena_floor_ &&
-            (level == 0 || arena_rows_[k] < arena_rows_[(size_t)level]))
-            level = (int)k;
+    const int level = arena_level(arena_floor_);
     for (auto& r : ranks_) {
         const int64_t want = r->arena_lent[(size_t)level];
         if (want <= r->mover.loan(Mover::kLendArena)) continue;
@@ -1458,6 +1198,15 @@ void Engine::arena_tick(uint64_t now_ns) {
     if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device);
 }
 
+/* ------------------------------------------------------------------ the idle-tier tick */
+/* Runs every iteration, busy or idle. A host copy is reported once its event signals, so the
+ * first tick after it lands collects it and hands out the next; a slower clock would only delay
+ * releasing a finished conversation's VRAM. When the host tier has refused a copy for lack of
+ * arena room, room is made at once.
+ *
+ * The scheduler's lock covers only the bookkeeping (planning and reporting touch rank 0's
+ * manager, the prefix cache and the index an HTTP cancel changes). Issuing and polling touch none
+ * of that, and a transfer's records stay pending while it is out. */
 void Engine::tier_tick() {
     Rank& lead = *ranks_[0];
     if (!pump_ || !lead.tierx.enabled()) return;
@@ -1474,9 +1223,8 @@ void Engine::tier_tick() {
         }
         if (ranks_.size() > 1) (void)rad_dev_set(lead.device);
         if (all) {
-            /* A COPY IS GOOD ONLY IF EVERY RANK'S SHARD LANDED. One that did not leaves an entry
-             * whose host copy is part this card's bytes and part stale, which is not restorable
-             * anywhere, so the whole batch is a failure and every slot goes back. */
+            /* A copy is good only if every rank's shard landed; otherwise the host copy is
+             * partly stale, so the whole batch fails and every slot goes back. */
             const std::vector ok(P.copy.size(), good ? 1 : 0);
             {
                 const auto lk = sched_.hold();
@@ -1503,14 +1251,10 @@ void Engine::tier_tick() {
     }
 
     /* ---- what is not live leaves VRAM -------------------------------------------------------- */
-    /* AS SOON AS ITS COPY HAS LANDED, WHILE THE EXPERT SLAB HAS A USE FOR THE BLOCKS. An entry no
-     * running sequence reads and whose host copy is in place costs nothing to give up -- a later
-     * turn restores it in a copy -- and its blocks are lent to the slab. With no lender, or a slab
-     * whose loan already covers every slot it has, the blocks would sit empty in the pool, so the
-     * entry stays where the next turn finds it for free; a request that needs the room takes it
-     * through trim, which drops the same entries on demand.
-     *
-     * NOT THE SNAPSHOTS: they are in host memory already and hold no VRAM. */
+    /* Release an entry once its host copy has landed, if the expert slab can use the blocks; a
+     * later turn restores it with a copy. Otherwise (no lending, or the loan already covers every
+     * slab slot) it stays in VRAM, and a request needing room takes it through trim. Snapshots
+     * are already in host memory. */
     if (lending_) {
         int64_t ceiling = 0;
         for (auto& r : ranks_) ceiling = std::max(ceiling, r->mover.loan_ceiling(Mover::kLendKV));
@@ -1519,8 +1263,8 @@ void Engine::tier_tick() {
     }
 
     /* ---- capacity ---------------------------------------------------------------------------- */
-    /* WHEN THE ARENA HAS REFUSED A COPY: the oldest host-only entries make room for it. The drops
-     * move no bytes, so the plan is reported as soon as it is made. */
+    /* When the host arena refused copies, drop host-only entries worth less than them to make
+     * room (IdleTiers::plan). Drops move no bytes, so the plan is reported at once. */
     if (lead.tiers.starved()) {
         std::vector jobs;
         lead.tiers.plan(P.slow_budget, &jobs);
@@ -1547,14 +1291,13 @@ bool Engine::flush_copies() {
     Rank& lead = *ranks_[0];
     bool landed = false;
     const uint64_t t0 = rad_mono_ns();
-    /* Counted only when something was in flight or waiting: a call that found nothing to land
-     * stalled nobody. */
+    /* Counted only when something was in flight or waiting. */
     struct Note {
         IdleTiers& t; uint64_t t0; bool worked = false;
         ~Note() { if (worked) t.note_flush((int64_t)(rad_mono_ns() - t0)); }
     } note{lead.tiers, t0};
-    /* BOUNDED: each round lands one batch of P.max_copy entries, and a pool short of more than
-     * that many rounds' worth is a pool the tiers cannot relieve in one step. */
+    /* Bounded: each round lands one batch of P.max_copy entries; a larger shortfall cannot be
+     * relieved in one step. */
     for (int round = 0; round < 64; ++round) {
         if (!P.copy.empty()) {
             note.worked = true;
@@ -1582,16 +1325,18 @@ bool Engine::flush_copies() {
     return landed;
 }
 
+/* Drop the sampler's per-request state for requests that reached a terminal state. The server
+ * drains their text through the sink and calls reap(), which releases the Request; only the HTTP
+ * thread knows when it has stopped writing. */
 void Engine::drain_completed() {
-    /* TAKEN, NOT READ. The list is appended to by HTTP threads' cancels, so walking it by
-     * reference would race them; and nothing else consumes it -- the server learns of a terminal
-     * request through its sink and reaps it on its own -- so each id is seen here exactly once and
-     * the cost stays proportional to what finished rather than to everything that ever has. */
+    /* Taken, not read: HTTP cancels append to the list, and nothing else consumes it, so each id
+     * is seen exactly once. */
     sched_.take_completed(&done_);
     for (uint64_t id : done_) for (auto& rk : ranks_) rk->sampler.end_request(id);
 }
 
-int Engine::serve() {
+int Engine::serve(std::unique_ptr watch) {
+    startup_watch_ = std::move(watch);
     if (ranks_.empty() || !ranks_[0]->ctx.program()) {
         RAD_ERR("serve: start() has not run, or stopped at --debug-graph");
         return RAD_E_STATE;
@@ -1645,8 +1390,8 @@ int Engine::serve() {
                     (long long)cfg_.max_seqs, (long long)pooled_dim_);
             return RAD_E_NOMEM;
         }
-        /* NO PREFIX CACHE: an encoder keeps no KV to reuse, and attending both ways means a
-         * shared prefix does not even compute to the same rows. */
+        /* No prefix cache: an encoder keeps no KV, and with bidirectional attention a shared
+         * prefix does not compute to the same rows. */
         cfg_.prefix_cache = false;
         prefix_off_why_ = "an embedding model: an encoder keeps no KV to reuse, and attending both "
                           "ways means a shared prefix does not compute to the same rows";
@@ -1655,13 +1400,11 @@ int Engine::serve() {
                  "tokens an input", (long long)pooled_dim_, (long long)cfg_.max_tok);
     }
 
-    /* The scheduler drives ONE block manager. Block ids are pure bookkeeping and identical on
-     * every rank: every rank carves the same block count (Engine::configure_kv caps each at the
-     * least rank's), so its free list evolves identically even where the ranks' shares of a
-     * group differ in bytes, or are zero (rad_kv_group_zero). What differs per rank is the pool
-     * BASE, and that lives in KVPoolBinding. So rank 0's manager owns the bookkeeping and the
-     * others exist to own their own card's allocation. If the counts ever disagree the block
-     * tables mean different things on different cards, so it is checked rather than assumed. */
+    /* The scheduler drives one block manager, rank 0's. Block ids are identical on every rank:
+     * all carve the same block count (Engine::configure_kv caps each at the smallest rank's), even
+     * where a group's share differs in bytes or is zero (rad_kv_group_zero). Only the pool base
+     * differs per rank (KVPoolBinding). Check the counts, since a mismatch would make one block
+     * table mean different things on different cards. */
     for (size_t i = 1; i < ranks_.size(); ++i) {
         const auto& a = ranks_[0]->kv.plans();
         const auto& c = ranks_[i]->kv.plans();
@@ -1679,28 +1422,24 @@ int Engine::serve() {
         }
     }
 
-    /* BACK TO RANK 0 BEFORE THE SCHEDULER IS BUILT. The per-rank loops above left this
-     * thread on the LAST rank's device, and the scheduler is given ranks_[0]->ctx.stream()
-     * -- so its staging buffers and its staging EVENT would be created on one card and
-     * recorded on another card's stream, which fails every step with "could not record
-     * the staging event". One batch serves every rank (spec §1), and rank 0 owns it. */
+    /* Back to rank 0's device before building the scheduler: the loops above left this thread on
+     * the last rank's device, and the scheduler's staging buffers and event must live on rank 0,
+     * whose stream it is given (spec §1). */
     RAD_TRY(rad_dev_set(ranks_[0]->device));
 
     kv_iface_ = std::make_unique>(&ranks_[0]->kv);
     pc_iface_ = std::make_unique>(&ranks_[0]->prefix);
-    /* THE RESTORE PATH, installed only when the tiers are on. The scheduler calls this before the
-     * admission lookup and must not know what a tier is; the engine does, so the knowledge lives
-     * here as a callable rather than as an include in core/sched.
+    /* The restore path, installed only when the tiers are on. The scheduler calls it before the
+     * admission lookup without knowing about tiers, so it is a callable rather than an include in
+     * core/sched.
      *
-     * EVERY RANK RESTORES ITS OWN SHARD, and rank 0 goes first because its TierExec is the one
-     * holding the policy -- it allocates the blocks and reports the job, and the others follow
-     * into the same block ids. A rank that fails leaves the prefix shorter and nothing worse,
-     * which is why none of this returns an error upward: a miss is always safe. */
+     * Every rank restores its own shard. Rank 0's TierExec holds the policy: it allocates the
+     * blocks and reports the job, and the others follow into the same block ids. A failure only
+     * shortens the prefix, so no error is returned. */
     if (ranks_[0]->tierx.enabled()) {
         auto* b = static_cast*>(pc_iface_.get());
-        /* CALLED FROM INSIDE Scheduler::step(), UNDER ITS LOCK -- which is what makes it safe to
-         * touch the cache and rank 0's manager here, and why nothing below may call back into the
-         * scheduler. */
+        /* Called inside Scheduler::step() under its lock, which makes touching the cache and rank
+         * 0's manager safe; nothing here may call back into the scheduler. */
         b->restore_fn = [this](const Request& req) {
             const uint64_t t0 = rad_mono_ns();
             PrefixCache& pc = ranks_[0]->prefix;
@@ -1708,10 +1447,9 @@ int Engine::serve() {
             media_keys(req, &mk);
             const std::vector want = pc.restorable_from(req.prompt, mk);
             if (want.empty()) return;
-            /* THE WHOLE CHAIN IN ONE RESTORE. A 4-token block makes a long conversation tens of
-             * thousands of entries, and one transfer an entry is tens of thousands of host round
-             * trips before the turn can start; as one restore it is a launch per (group, layer)
-             * per staging batch and a copy per run of arena slots. */
+            /* The whole chain in one restore. With 4-token blocks a long conversation is tens of
+             * thousands of entries; batched, it is one launch per (group, layer) per staging batch
+             * and one copy per run of arena slots instead of a round trip per entry. */
             std::vector jobs;
             jobs.reserve(want.size());
             for (const BlockHash& h : want) {
@@ -1726,24 +1464,19 @@ int Engine::serve() {
                 (void)r->tierx.issue_restore(jobs, r->ctx.stream(), &mine);
                 for (size_t i = 0; i < ok.size(); ++i) ok[i] = ok[i] && i < mine.size() && mine[i];
             }
-            /* Back to rank 0's card before anything else runs on this thread: the admission this
-             * restore is part of grows rank 0's pool next. */
+            /* Back to rank 0's device: the admission continues by growing rank 0's pool. */
             if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device);
             ranks_[0]->tierx.report_pass(jobs, ok, rad_mono_ns());
-            /* EVERY ENTRY THAT CAME BACK IS REBOUND, not only the leading run: the tiers have
-             * already marked each one resident at its new blocks, and an entry the cache did not
-             * take would name blocks nothing references. */
+            /* Rebind every entry that came back, not only the leading run: the tiers already
+             * marked each resident at its new blocks. */
             const std::vector& cg = pc.cached_groups();
             for (size_t i = 0; i < jobs.size(); ++i) {
                 TierJob& j = jobs[i];
                 if (!ok[i]) continue;
                 const int rb = pc.rebind(j.key, j.blocks);
                 if (rb != RAD_OK) {
-                    /* A PROMOTION WITH NO ENTRY TO LAND IN. The blocks were reserved for the entry
-                     * and nothing else holds them; the record the tiers just marked resident names
-                     * them too, and would be released later from under whoever the pool gives them
-                     * to. Both are let go, so the blocks return to the pool and the key is simply
-                     * unknown. */
+                    /* No entry to land in: release the reserved blocks and forget the tier record,
+                     * which would otherwise release them later from under their next owner. */
                     ranks_[0]->tierx.quiesce();
                     for (size_t k = 0; k < cg.size() && k < j.blocks.size(); ++k)
                         if (j.blocks[k] >= 0) ranks_[0]->kv.release_block(cg[k], j.blocks[k]);
@@ -1752,40 +1485,45 @@ int Engine::serve() {
             }
             ranks_[0]->tiers.note_restore((int64_t)(rad_mono_ns() - t0));
         };
-        /* AN EVICTION THAT WOULD LOSE AN ENTRY WAITS FOR ITS COPY INSTEAD. Called by the
-         * prefix cache binding under the scheduler's lock, on this thread, when dropping the
-         * entries that already have a host copy did not free enough: every copy waiting is
-         * planned, issued and landed now, so the entries it covers can leave VRAM and be kept. */
+        /* An eviction that would lose an entry waits for its copy instead. Called by the prefix
+         * cache binding under the scheduler's lock when dropping already-copied entries did not
+         * free enough: all waiting copies are landed now, so those entries can leave VRAM. */
         b->flush_fn = [this]() -> bool { return flush_copies(); };
     }
-    /* EVERY RANK'S CARD, STREAM AND ARENA. The batch is one build shared by pointer (spec §1) and
-     * that is right for the host side; the DEVICE side is staged per rank, because a rank reading
-     * another card's staging is both a PCIe read on the step path and, worse, unordered against
-     * the copies that fill it -- see the Set comment in batch.h. */
+    /* Per-rank card, stream and program. The batch is built once and shared by pointer on the
+     * host (spec §1), but its device side is staged per rank: reading another card's staging is a
+     * PCIe read and unordered against the copies that fill it (see Set in batch.h). */
     std::vector rio;
     rio.reserve(ranks_.size());
     for (auto& rk : ranks_)
         rio.push_back({ rk->device, rk->ctx.stream(), &rk->program });
     if (generator) {
-        /* THE GENERATOR'S DRIVER IN PLACE OF THE SCHEDULER: the scheduler is never initialised,
-         * so its step staging -- sized for token steps the generator never runs -- is never
-         * allocated, and nothing calls it. */
+        /* The generator's driver replaces the scheduler, which is never initialised, so its
+         * token-step staging is never allocated. */
         std::vector gio;
         for (auto& rk : ranks_) gio.push_back({ rk->device, rk->ctx.stream() });
         gen_ = std::make_unique();
-        RAD_TRY(gen_->init(ranks_[0]->program, cfg_, kv_iface_.get(), gio));
+        RAD_TRY(gen_->init(ranks_[0]->program, kv_iface_.get(), gio));
         RAD_TRY(rad_dev_set(ranks_[0]->device));
     } else
     RAD_TRY(sched_.init(ranks_[0]->program, cfg_, kv_iface_.get(), pc_iface_.get(), rio, &geo_));
-    /* THE SMALLEST STEP THE PREFILL STAGER OVERLAPS. A prefill chunk the scheduler holds back for
-     * other work in the step (--busy-prefill-chunk) is kept at or above it: under it every routed
-     * layer reads its pooled experts synchronously, which costs a long prefill far more than the
-     * step it shares saves. The largest over the ranks, since the step waits for the slowest. */
+    /* The smallest step the prefill stager overlaps. A chunk held back for other work
+     * (--busy-prefill-chunk) stays at or above it; below it every routed layer reads its pooled
+     * experts synchronously, which costs far more than sharing the step saves. The maximum over
+     * ranks, since the step waits for the slowest. */
     {
         int64_t stage_rows = 0;
         for (auto& rk : ranks_)
             if (rk->stager.enabled()) stage_rows = std::max(stage_rows, rk->stager.min_rows());
         sched_.set_stage_rows(stage_rows);
+        /* The shortest prompt a span pays for where routed experts are read from host memory: a
+         * spanned step runs at the full plan, which lends the expert slab nothing, while every
+         * other step runs at the span's shared level and lends it the span's extra rows. On
+         * Qwen3.8-Flash-Next at TP2 (two R9700, 12 GiB host pool) the span loses to one-interval
+         * steps up to 12K tokens and wins from 18K, hence eight intervals. With every expert on
+         * the card there is no such cost and every lone prefill spans. */
+        sched_.set_span_min(stage_rows > 0 && arena_span_rows_ > 0
+                                ? 8 * std::max(geo_.checkpoint_interval, 0) : 0);
     }
 
     for (auto& r : ranks_) r->sampler.attach_vocab(vocab_view_.get());
@@ -1800,31 +1538,28 @@ int Engine::serve() {
     for (int i = 0; i < cfg_.tp; ++i) rank_threads_.emplace_back([this, i] { rank_loop(i); });
     std::thread stepper([this] { if (gen_) gen_loop(); else step_loop(); });
 
-    if (cfg_.kld()) print_startup_report(RAD_OK);
+    if (cfg_.kld()) {
+        print_startup_report(RAD_OK);
+        startup_watch_.reset();
+    }
     int s = cfg_.kld() ? run_kld() : run_server();
+    startup_watch_.reset();
 
-    /* Stop the step loop before anything the server owns is destroyed: Request::sink is a raw
-     * pointer into the server's storage, and a request the scheduler has not finished is a request
-     * still writing into it (server.h). */
+    /* Stop the step loop before the server's storage is destroyed: Request::sink points into it,
+     * and an unfinished request still writes there (server.h). */
     stopping_.store(true, std::memory_order_release);
     barrier_->abort();
     if (stepper.joinable()) stepper.join();
     for (auto& t : rank_threads_) if (t.joinable()) t.join();
     rank_threads_.clear();
-    /* A step loop that died is the answer, whatever the transport said on the way down: the
-     * process should exit with the engine's error, not report a clean shutdown of a server that
-     * stopped serving. */
+    /* A step-loop error takes precedence over the transport's status. */
     const int ls = loop_status_.load(std::memory_order_acquire);
     return ls < 0 ? ls : s;
 }
 
-/* THE STATE SLOTS A SEQUENCE OWNS, one per KV group, -1 where the group is not stateful.
- *
- * Read from RANK 0 and applied to every rank, which is correct for the same reason the batch hands
- * one `state_index` row to all of them: only rank 0's KVManager tracks sequences (kv_iface_ is
- * bound to it), while every rank's pool has identical geometry, so a slot index means the same
- * offset everywhere and only the base pointer differs. Looking the sequence up in any other rank's
- * manager returns "not found". */
+/* The state slots a sequence owns, one per KV group, -1 where the group is not stateful. Read from
+ * rank 0 and applied to every rank: only rank 0's KVManager tracks sequences (kv_iface_), and
+ * every rank's pool has identical geometry, so a slot index means the same offset everywhere. */
 bool Engine::state_slots_of(uint64_t seq, std::vector* out) const {
     const KVManager& kv = ranks_[0]->kv;
     out->assign((size_t)kv.n_groups(), -1);
@@ -1842,28 +1577,9 @@ bool Engine::state_slots_of(uint64_t seq, std::vector* out) const {
 }
 
 /* ------------------------------------------------------------------ the HTTP frontend */
-/* WHAT IS WIRED AND WHAT IS NOT, stated rather than discovered at runtime. `/v1/completions`,
- * `/v1/chat/completions`, `/v1/models`, `/metrics` and `/health` are live. `/v1/embeddings` is
- * 501 (no embedding head in the container), and so are image, video and audio content parts
- * unless the program declared an encoder that accepts them (MEDIA, below).
- *
- * THE CHAT ENDPOINT IS 501 ONLY WHEN THE MODEL HAS NO TEMPLATE, and that distinction is the whole
- * reason `chat_bridge` is conditional below. A container that carries a chat template gets the
- * full path: the template's grammar and lazy triggers reach the sampler, and the reply parser the
- * auto-parser derives from that same template comes back out through IChatTemplate::apply bound
- * to the request that asked for it. A container without one gets an endpoint that says so,
- * because a chat template guessed is a prompt format guessed, and the failure mode of guessing is
- * fluent text in the wrong shape. */
-/* WHAT /server_info SAYS ABOUT THE ENGINE.
- *
- * The server cannot derive any of this: it holds interfaces and knows nothing about devices,
- * containers or placement. Rather than growing ServerOptions a field per fact, the engine renders
- * the object it owns and the server splices it in verbatim.
- *
- * IT IS THE OPERATOR'S FIRST QUESTION, asked of a process that is already running: which model,
- * on how many cards, with how much KV, drafting how deeply, over which wire. All of it is printed
- * at startup too -- and a startup log is on a machine, in a file, from a process that may have
- * been restarted since. */
+/* The engine's part of /server_info: model, cards, KV, drafting and wire, for a running process.
+ * The server holds only interfaces, so the engine renders this object and the server splices it in
+ * verbatim. */
 std::string Engine::engine_info() const {
     nlohmann::ordered_json e;
     e["arch"]        = meta_.arch_id ? meta_.arch_id : "";
@@ -1879,8 +1595,7 @@ std::string Engine::engine_info() const {
     e["tp_wire_min_kb"]         = cfg_.tp_wire_exact ? 0 : cfg_.tp_wire_min_kb;
     e["max_num_batched_tokens"] = cfg_.max_tok;
     e["placement"]              = cfg_.placement;
-    /* What each lookup table was asked for and where it went: auto's answer is the one a
-     * dashboard reading this needs, and the request is the one the command line shows. */
+    /* Each lookup table's requested and resolved placement. */
     e["embedding_placement"]    = { { "asked", table_placement_name(cfg_.embedding_placement) },
                                     { "resolved", table_placement_name(cfg_.embedding_resolved) } };
     e["ngram_placement"]        = { { "asked", table_placement_name(cfg_.ngram_placement) },
@@ -1906,8 +1621,8 @@ std::string Engine::engine_info() const {
     }
     e["devices"] = std::move(devs);
 
-    /* Rank 0's, and every rank declares the same graph -- see the miss report in
-     * engine_bringup.cpp for why that is relied on rather than assumed. */
+    /* Rank 0's; every rank declares the same graph (see the miss report in
+     * engine_bringup.cpp). */
     const Program& p0 = ranks_[0]->program;
     e["ops"]     = (int64_t)p0.ops.size() - 1;
     e["weights"] = (int64_t)p0.weights.size() - 1;
@@ -1916,16 +1631,11 @@ std::string Engine::engine_info() const {
     const KVManager& kv = ranks_[0]->kv;
     for (int32_t g = 0; g < kv.n_groups(); ++g) {
         const KVGroupPlan* pl = kv.plan(g);
-        /* Group 0 is the "no KV group" sentinel every program carries so that a handle of zero is
-         * absent rather than valid. It has no layers and no pool, and reporting it would be
-         * reporting the absence of a thing. */
+        /* Skip group 0, the sentinel that makes handle 0 mean "none". */
         if (!pl || pl->name.empty() || pl->n_layers <= 0) continue;
         nlohmann::ordered_json k;
         k["name"]     = pl->name;
-        k["kind"]     = pl->kind == RAD_KV_FULL   ? "full"
-                      : pl->kind == RAD_KV_WINDOW ? "window"
-                      : pl->kind == RAD_KV_LINEAR ? "linear"
-                      : pl->kind == RAD_KV_CONV   ? "conv" : "none";
+        k["kind"]     = bld_kv_kind_name(pl->kind);
         k["n_layers"] = pl->n_layers;
         k["bytes"]    = pl->pool_bytes;
         if (pl->paged()) {
@@ -1952,30 +1662,22 @@ std::string Engine::engine_info() const {
     return e.dump();
 }
 
-
 /* ------------------------------------------------------------------ a clean stop
  *
- * SIGINT AND SIGTERM ARE HANDLED, so a serving process has a way to end other than being killed
- * where it stands. Unhandled, `~Engine` never runs: `--profile-ops` collects a table nobody
- * prints, the placement banner is unreachable by construction, and an in-flight request is cut
- * rather than drained.
+ * SIGINT and SIGTERM are handled so `~Engine` runs: --profile-ops prints its table, the placement
+ * summary prints, and in-flight requests drain instead of being cut.
  *
- * A WATCHER THREAD AND NOT THE HANDLER ITSELF. `Server::stop` takes locks, joins threads and
- * drains a graveyard; none of that is async-signal-safe, and calling it from a handler is the
- * deadlock that only shows up under load. The handler does the one thing it may -- store to a
- * lock-free atomic -- and this thread does the work. A second signal is left to the default
- * disposition, so an operator who has decided not to wait still gets an immediate kill.
+ * The handler only stores to a lock-free atomic; a watcher thread does the work, because
+ * `Server::stop` takes locks and joins threads, which is not async-signal-safe. A second signal
+ * gets the default disposition, so the operator can still force an immediate kill.
  */
 namespace {
 std::atomic g_signalled{false};
 void on_signal(int) { g_signalled.store(true, std::memory_order_relaxed); }
 
 /* ================================================================== sampling defaults */
-/* WHAT A REQUEST THAT SENDS NO SAMPLER SETTINGS IS SERVED WITH.
- *
- * The reading and the range checks belong to core/gen_config.h, which carries the argument for
- * why any of this exists. What is here is the ORDER, and the container lookup, which is the one
- * part that reads the model's metadata:
+/* The sampler for a request that sends no sampler settings. Parsing and range checks live in
+ * core/gen_config.h; this is the precedence order and the container lookup:
  *
  *   --temp / --top-k / --top-p / --min-p    an operator overriding, field by field, and last
  *   --generation-config PATH                a generation_config.json named outright
@@ -1984,11 +1686,11 @@ void on_signal(int) { g_signalled.store(true, std::memory_order_relaxed); }
  *                                          checkpoint carries it
  *   SamplingParams' own defaults            the untruncated floor
  *
- * Each source is consulted only if the one above it said nothing at all, so a deployment that
- * names a file gets that file's sampler and not a blend of it with the container's.
+ * The flags override field by field. Of the file sources, the first that states anything is used
+ * whole, never blended with a lower one.
  *
  * `stated` and `source`, when given, receive what the source in force read and its name ("" for
- * none): gen_sampling_sources turns the two into the reason for each field. */
+ * none), which gen_sampling_sources turns into a reason per field. */
 SamplingParams resolve_sampling_defaults(const RadModelMeta& meta, bool container,
                                          const Config& cfg, GenSampling* stated = nullptr,
                                          std::string* source = nullptr) {
@@ -2018,9 +1720,8 @@ SamplingParams resolve_sampling_defaults(const RadModelMeta& meta, bool containe
     if (cfg.sample_min_p >= 0.0f) { sp.min_p = cfg.sample_min_p; over += " --min-p"; }
     if (cfg.sample_top_k >= 0)    { sp.top_k = cfg.sample_top_k; over += " --top-k"; }
 
-    /* THE REST OF THE SAMPLER HAS NO FILE SOURCE: a generation_config.json is read for the four
-     * fields above and no others, so these are SamplingParams' own values unless a flag sets
-     * them, and request_overrides() logs the ones that did. */
+    /* The remaining fields have no file source (generation_config.json supplies only the four
+     * above): SamplingParams' defaults unless a flag sets them; request_overrides() logs those. */
     if (cfg.sample_typical_p)          sp.typical_p          = *cfg.sample_typical_p;
     if (cfg.sample_rep_penalty)        sp.rep_penalty        = *cfg.sample_rep_penalty;
     if (cfg.sample_pres_penalty)       sp.pres_penalty       = *cfg.sample_pres_penalty;
@@ -2050,9 +1751,9 @@ SamplingParams resolve_sampling_defaults(const RadModelMeta& meta, bool containe
     return sp;
 }
 
-/* "presence_penalty 1.5, max_tokens auto, ..." -- every request default and bound the command line
- * moved, under the request's spelling of the field, or "" when it moved none. The four fields
- * resolve_sampling_defaults describes are not repeated. */
+/* "presence_penalty 1.5, max_tokens auto, ...": every request default or bound the command line
+ * changed, in the request's field names; "" if none. Excludes the four fields
+ * resolve_sampling_defaults reports. */
 std::string request_overrides(const Config& c) {
     std::string out;
     auto add = [&out](const std::string& s) { out += (out.empty() ? "" : ", ") + s; };
@@ -2091,30 +1792,31 @@ std::string request_overrides(const Config& c) {
     return out;
 }
 }  /* namespace */
+/* The HTTP server over the engine. `/v1/completions`, `/v1/chat/completions`, `/v1/models`,
+ * `/metrics` and `/health` are live. `/v1/embeddings` answers 501 unless the program is an
+ * embedding program, and so do image, video and audio content parts unless the program declared an
+ * encoder that accepts them (MEDIA, below). The chat endpoint answers 501 only when the model has
+ * no chat template: a guessed template is a guessed prompt format. With one, the template's
+ * grammar and lazy triggers reach the sampler and its derived reply parser comes back through
+ * IChatTemplate::apply. */
 int Engine::run_server() {
-    /* The rank-0 sampler comes along so admission can refuse a request whose sampling stage this
-     * build has no kernel for, by name and at the door (IScheduler::admit). The tiers come along
-     * because they are where a stored conversation is RECORDED, and that is passed whether or not
-     * any tier can move anything: with the caps at zero the object still holds the session table,
-     * and withholding it on that ground would leave the sessions view reporting an empty server. */
+    /* The rank-0 sampler lets admission refuse, by name, a request whose sampling stage has no
+     * kernel (IScheduler::admit). The tiers are passed even when they move nothing, because they
+     * hold the session table the sessions view reads. */
     server::SchedulerBridge sched_bridge(&sched_, ranks_.empty() ? nullptr : &ranks_[0]->sampler,
                                         ranks_.empty() ? nullptr : &ranks_[0]->tiers);
     server::TokenizerBridge tok_bridge(vocab_);
     server::ChatTemplateBridge chat_bridge;
     server::GrammarBridge grammar_bridge(vocab_view_.get());
 
-    /* THE SNAPSHOT OF WHAT ONLY THE ENGINE CAN SEE, and there is ONE of it. The live view
-     * (spec §16) and the web dashboard are two renderers of the same numbers, so they are given
-     * the same function rather than each reaching into the engine on its own -- two readers is
-     * two chances to disagree about what the engine was doing.
+    /* One snapshot function feeds both the live view (spec §16) and the web dashboard, so they
+     * cannot disagree. It runs on the drawing thread and must not slow the engine: it reads the
+     * scheduler's published copy (Scheduler::publish), the driver's VRAM counter, and rank 0's
+     * plan, immutable after start().
      *
-     * Called from whichever thread is drawing, and it must not be able to slow the engine: it
-     * reads the scheduler's published copy (Scheduler::publish), the driver's VRAM counter
-     * through a descriptor opened here, and rank 0's plan, which is immutable after start().
-     *
-     * THE CARDS' FIXED FACTS ARE READ ONCE, HERE, on the engine thread before serving. The props
-     * call enters the device runtime -- device properties, a device switch, a free-memory query,
-     * a peer walk -- and is meant for startup; it also opens the counter dev_vram_used reads. */
+     * The cards' fixed facts are read once here, before serving: rad_dev_props enters the device
+     * runtime (properties, device switch, free-memory query, peer walk) and also opens the counter
+     * dev_vram_used reads. */
     std::vector card_facts;
     for (const auto& r : ranks_) {
         RadDeviceProps pr{};
@@ -2131,11 +1833,9 @@ int Engine::run_server() {
 
         s.cards.clear();
         for (const server::CardStat& f : card_facts) {
-            /* vram_used is sampled per call rather than cached: it is the number that moves, and
-             * it is the one an operator watching for a leak is watching. A card whose counter
-             * cannot be read is left out rather than drawn empty. Utilisation, power and
-             * temperature stay 0 -- "not sampled" -- because the device layer does not expose
-             * them and a plausible invented number is worse than a blank. */
+            /* vram_used is sampled per call. A card whose counter cannot be read is left out.
+             * Utilisation, power and temperature stay 0 ("not sampled"): the device layer does
+             * not expose them. */
             int64_t used = 0;
             if (dev_vram_used(f.index, &used) != RAD_OK) continue;
             server::CardStat c = f;
@@ -2143,16 +1843,12 @@ int Engine::run_server() {
             s.cards.push_back(std::move(c));
         }
 
-        /* THE EXPERT PLANE, from rank 0's placement plan. A dense model has no expert units, so
-         * this stays empty and both renderers omit the panel -- which is why it is filled
-         * unconditionally rather than behind a "is this MoE" test the engine would have to
-         * invent. When there are experts, this is the picture the heat engine is judged by. */
+        /* The expert plane from rank 0's placement plan; empty for a dense model, and the
+         * renderers then omit the panel. */
         s.experts = server::ExpertPlane{};
         if (!ranks_.empty()) {
             const Plan& p = ranks_[0]->plan;
-            /* Read ONCE for both halves of this panel: the same struct answers "what did the
-             * mover do to the experts" and "what did it put on the link", and two reads is two
-             * chances for the two halves of one picture to disagree. */
+            /* Read once for both the expert and link halves of the panel, so they agree. */
             const MoverStats ms = ranks_[0]->mover.stats();
             int32_t n_layer = 0, n_expert = 0;
             for (const MoveUnit& mu : p.units)
@@ -2164,12 +1860,9 @@ int Engine::run_server() {
                 s.experts.n_layers  = n_layer;
                 s.experts.n_experts = n_expert;
                 s.experts.tier.assign((size_t)n_layer * (size_t)n_expert, (uint8_t)Tier::VRAM);
-                /* THE LIVE TIER WHERE THERE IS ONE, and the plan's otherwise. The plan is where a
-                 * unit STARTED; once the heat engine runs, the picture this panel exists to show
-                 * is the one that moves, and reading the plan would draw a frozen plane under an
-                 * engine doing nothing but change it. HeatEngine::tier is a plain vector
-                 * read and the writes are made by the dispatch thread at a step boundary, so a
-                 * draw racing one gets the value from either side of a single store. */
+                /* The live tier when the heat engine runs, else the plan's (where a unit started).
+                 * HeatEngine::tier is a plain vector written by the dispatch thread at step
+                 * boundaries, so a racing read sees either side of a single store. */
                 const HeatEngine& heat = ranks_[0]->heat;
                 const bool live_tier = heat.enabled();
                 s.experts.heat_enabled = live_tier;
@@ -2181,11 +1874,9 @@ int Engine::run_server() {
                     const Tier t = live_tier ? heat.tier((int32_t)u) : mu.tier;
                     s.experts.tier[(size_t)mu.layer * (size_t)n_expert + (size_t)mu.expert]
                         = (uint8_t)t;
-                    /* RESIDENCY IS COUNTED OVER THE UNITS, NOT OVER THE PLANE. The plane is a
-                     * rectangle and a model need not fill it -- a draft head's expert count can
-                     * differ from the trunk's -- so tallying cells would count
-                     * (layer, expert) pairs that were never placed as VRAM-resident, which is the
-                     * one direction the number must not be wrong in. */
+                    /* Count residency over units, not plane cells: the plane is a rectangle a
+                     * model need not fill (a draft head's expert count can differ), and empty
+                     * cells default to VRAM. */
                     const int ti = (int)t >= 0 && (int)t < kTierCount ? (int)t : (int)Tier::SSD;
                     s.experts.units[ti]++;
                     s.experts.bytes[ti] += mu.bytes;
@@ -2208,39 +1899,25 @@ int Engine::run_server() {
                 s.experts.stage_copies   = (int64_t)ms.stage_copies;
                 s.experts.flex_bytes    = ranks_[0]->mover.flex_used_bytes();
                 s.experts.flex_capacity = ranks_[0]->mover.flex_offered_bytes();
-                /* THE HEAT ENGINE'S OWN TALLY, which answers a different question from the
-                 * mover's. The mover counts bytes that went; these count decisions -- how many
-                 * dispatches proposed nothing and why, and whether a promotion was of a unit
-                 * never promoted before (investment) or one just demoted (pure loss). */
+                /* The heat engine's decision counts (the mover counts bytes): dispatches that
+                 * proposed nothing and why, and whether a promotion was a first (investment) or a
+                 * readmit of a just-demoted unit (pure loss). */
                 const HeatStats hs = heat.stats();
                 s.experts.dispatches        = (int64_t)hs.dispatches;
                 s.experts.refused           = (int64_t)hs.refused;
                 s.experts.no_candidate      = (int64_t)hs.no_candidate;
                 s.experts.distinct_promoted = (int64_t)hs.distinct_promoted;
                 s.experts.readmits          = (int64_t)hs.readmits;
-                /* AND WHETHER THE PLACEMENT IS ACTUALLY PAYING. Residency is a property of the
-                 * plan; the hit rate is a property of the TRAFFIC, and a plan holding 80% of the
-                 * units can still miss on most tokens if the hot ones are the ones outside. */
+                /* The routed hit rate: residency describes the plan, this describes the traffic. */
                 s.experts.routed            = (int64_t)hs.routed;
                 s.experts.routed_resident   = (int64_t)hs.routed_resident;
 
             }
 
-            /* THE LINK, and the two things that share it.
-             *
-             * THE COLLECTIVE IS ONE RANK'S AND THE MOVES ARE EVERY RANK'S, which is why the two
-             * halves of this panel are summed differently. The ranks are symmetric in the
-             * all-reduce -- each pushes the same message -- so rank 0's count IS the machine's and
-             * summing it would double it. A promotion, a demotion and a streamed expert are the
-             * opposite: each rank holds its own shard of the plane and pulls its own bytes over
-             * its own link, so the machine's traffic is the sum and rank 0 alone is a half of it
-             * at --tp 2. Reading one rank for all of them would put the move and stream rows at
-             * 1/world of the truth while the all-reduce beside them stayed right, which is the
-             * worse of the two errors: the SHARES would be wrong, and the shares are the whole
-             * point of the panel.
-             *
-             * `world` is published so the reader can still recover a per-card figure, which is the
-             * one to hold against a single link's ceiling. */
+            /* The link panel. All-reduce counts come from rank 0 only: the ranks are symmetric,
+             * so summing would double them. Moves and streamed experts are summed over ranks:
+             * each rank moves its own shard over its own link. `world` lets a reader recover the
+             * per-card figure to compare against one link's ceiling. */
             s.passes.present = true;
             for (const auto& rk : ranks_) {
                 const Ctx::PassCounts pc = rk->ctx.pass_counts();
@@ -2281,13 +1958,9 @@ int Engine::run_server() {
     d.grammar = &grammar_bridge;
     d.live  = snap;
 
-    /* load_from_vocab warns on its own when the template is missing or will not compile; all we
-     * decide here is whether the endpoint exists. The reply format is the architecture plugin's
-     * when it declares one, and the template's otherwise. */
-    /* WHAT AN EMBEDDING MODEL SERVES: /v1/embeddings, and no chat. */
-    /* Its named prompts are the checkpoint's sentence-transformers configuration
-     * (`sentence_transformers.prompts.*`), and a `messages` input renders through its chat
-     * template. */
+    /* An embedding model serves /v1/embeddings and no chat. Its named prompts are the checkpoint's
+     * sentence-transformers configuration (`sentence_transformers.prompts.*`); a `messages` input
+     * renders through its chat template. */
     struct EmbedInfo final : server::IEmbedder {
         int64_t d = 0, n = 0;
         const RadModelMeta* meta = nullptr;
@@ -2312,20 +1985,20 @@ int Engine::run_server() {
     embed_info.meta = &meta_;
     if (embedding_) d.embed = &embed_info;
 
+    /* The template loader warns on its own about a missing or broken template; this only decides
+     * whether the chat endpoint exists. The reply format is the architecture plugin's when it
+     * declares one, else derived from the template. */
     const RadChatFormat* declared_format = rad_tools_chat_format(plugins_, meta_);
+    /* An image model's template is its conditioning network's; nothing is served as chat. */
+    const bool have_tpl = !gen_ && vocab_ && !vocab_->chat_template().empty() &&
+                          chat_bridge.init(*vocab_, declared_format, plugins_.arch_plugin) >= 0 &&
+                          chat_bridge.ready();
     if (embedding_) {
         /* No chat endpoint: the model's template, when it has one, renders a `messages` input. */
-        if (vocab_ && !vocab_->chat_template().empty() &&
-            chat_bridge.init(*vocab_, declared_format, plugins_.arch_plugin) >= 0 &&
-            chat_bridge.ready())
-            embed_info.tpl = &chat_bridge;
-    } else if (gen_) {
-        /* An image model's template is its conditioning network's; nothing is served as chat. */
-    } else if (vocab_ && !vocab_->chat_template().empty() &&
-        chat_bridge.init(*vocab_, declared_format, plugins_.arch_plugin) >= 0 &&
-        chat_bridge.ready()) {
+        if (have_tpl) embed_info.tpl = &chat_bridge;
+    } else if (have_tpl) {
         d.chat = &chat_bridge;
-    } else {
+    } else if (!gen_) {
         RAD_WARN("no chat template in this container; /v1/chat/completions will answer 501 and "
                  "/v1/completions is the endpoint to use");
     }
@@ -2340,8 +2013,8 @@ int Engine::run_server() {
     o.port     = cfg_.port;
     o.api_key  = cfg_.api_key;
     o.max_seqs = cfg_.max_seqs;
-    /* `n` fans one request out over the batch, so a server that runs more sequences a step takes
-     * more choices a request; the floor keeps a small batch from refusing what it would queue. */
+    /* `n` fans one request out over the batch, so the default scales with --max-num-seqs; the
+     * floor of 8 keeps a small batch from refusing what it would queue. */
     o.max_n    = cfg_.max_n > 0 ? (int)cfg_.max_n : (int)std::max(o.max_n, cfg_.max_seqs);
     if (cfg_.max_n <= 0)
         decide("--max-n", std::to_string(o.max_n), "the larger of 8 and --max-num-seqs");
@@ -2351,8 +2024,8 @@ int Engine::run_server() {
     o.reasoning_effort_map = cfg_.reasoning_effort_map;
     o.default_thinking_budget = cfg_.thinking_token_budget;
     {
-        /* THE FOUR SAMPLER DEFAULTS A FILE CAN STATE, where no flag set them: the value served and,
-         * field by field, the file or metadata it came from. */
+        /* The four sampler defaults a file can state: the served value and, per field, its
+         * source. */
         GenSampling stated;
         std::string src;
         o.default_sampling =
@@ -2367,8 +2040,8 @@ int Engine::run_server() {
     o.default_dry_breakers_set = cfg_.sample_dry_seq_breakers.has_value();
     /* An embedding model samples nothing, so it has no logprobs to give. */
     o.supports_logprobs = !embedding_ && ranks_[0]->sampler.has_logprobs();
-    /* -1 leaves ServerOptions' own default, which is `auto` (0). That is resolved per request
-     * against the context, so it needs one to resolve against. */
+    /* -1 keeps ServerOptions' default, `auto` (0), resolved per request against the context, so
+     * it needs a known context. */
     if (cfg_.default_max_tokens >= 0) o.default_max_tokens = cfg_.default_max_tokens;
     if (o.default_max_tokens == 0 && o.max_ctx <= 0) {
         RAD_ERR("a request that names no max_tokens gets what the context leaves after its prompt "
@@ -2398,18 +2071,19 @@ int Engine::run_server() {
                                      moved.c_str());
     }
     o.engine_info = engine_info();
-    /* Per request, not once: the dump carries OpInfo::issued, which only becomes true once the
-     * run phase has run. See ServerOptions::graph_json. */
+    /* Per request, since OpInfo::issued changes once the run phase runs
+     * (ServerOptions::graph_json). */
     o.graph_json  = [this] { return dump_graph_json(ranks_[0]->program); };
-    /* Read again for a request, from a reading at most a second old (Engine::diagnostics_json):
-     * the links and clocks it reports are only telling under load. */
+    /* Per request, from a reading at most a second old (Engine::diagnostics_json). */
     o.diagnostics_json = [this] { return diagnostics_json(); };
 
-    /* MEDIA, WHEN THE PROGRAM DECLARED AN ENCODER. The processor reads its geometry from the
-     * container and the encoder states the one it was built for; the two meet at the patch width
-     * and the merge, and a disagreement is refused here rather than discovered as garbage rows. */
+    /* Media, when the program declared an encoder. The processor's geometry comes from the
+     * container and the encoder states its own; patch width and merge must agree, checked here
+     * rather than found as garbage rows. */
     std::unique_ptr mm_proc;
     std::unique_ptr mm_bridge;
+    /* How the model hears, for the speech routes: the plugin's RadAudioFormat copied out. */
+    server::SpeechFormat speech_fmt;
     const RadEncoderDecl& encd = ranks_[0]->program.encoder;
     if (encd.modalities != 0) {
         mm::VisionConfig vc;
@@ -2420,13 +2094,11 @@ int Engine::run_server() {
             return RAD_E_INVAL;
         }
         vc.max_patches = encd.max_patches;
-        /* THE COMMAND LINE OVER THE CONTAINER, field by field, and the result checked as a whole:
-         * a minimum stated alone can land above the maximum the container states.
-         *
-         * A TOKEN-BUDGET PROCESSOR (Gemma 4's) sizes images and frames by soft tokens, not pixel
-         * bands: the band flags would do nothing on it, so they are refused by name, and the
-         * budgets come from --image-tokens and --video-max-frame-tokens. */
-        /* LFM2-VL's processor takes pictures only, so the video flags would do nothing on it. */
+        /* Flags override the container field by field, and the result is checked as a whole (a
+         * minimum given alone can exceed the container's maximum). Flags a processor would ignore
+         * are refused by name: LFM2-VL takes pictures only, and a token-budget processor (Gemma
+         * 4's) sizes by soft tokens (--image-tokens, --video-max-frame-tokens), not pixel
+         * bands. */
         if (vc.family == mm::Family::Lfm2 &&
             (cfg_.video_min_pixels || cfg_.video_max_pixels || cfg_.video_min_frames ||
              cfg_.video_max_frames || cfg_.video_fps || cfg_.video_max_frame_tokens)) {
@@ -2466,8 +2138,7 @@ int Engine::run_server() {
                     why.c_str());
             return RAD_E_INVAL;
         }
-        /* The processor lowers the image band to one encoder pass; an operator who asked for
-         * more is told, rather than finding the cap in the startup line below. */
+        /* The processor caps the image band at one encoder pass; warn if more was asked for. */
         const int64_t pass_px = encd.max_patches * vc.patch * vc.patch;
         if (cfg_.image_max_pixels && *cfg_.image_max_pixels > pass_px)
             RAD_WARN("media: --image-max-pixels %lld is above what one encoder pass takes (%lld "
@@ -2533,8 +2204,8 @@ int Engine::run_server() {
                      (long long)mm_proc->config().image_max_pixels, (long long)encd.max_patches,
                      (long long)mm_proc->config().video_max_pixels);
     }
-    /* AUDIO, WHEN THE PROGRAM DECLARED AN AUDIO ENCODER: the feature extractor reads its framing
-     * from the container, and the encoder states the frame width and the frames an output row. */
+    /* Audio, when the program declared an audio encoder: framing comes from the container; the
+     * encoder states the frame width and frames per output row. */
     const RadEncoderDecl& aend = ranks_[0]->program.audio_encoder;
     if (aend.modalities != 0) {
         mm::AudioConfig ac;
@@ -2550,26 +2221,70 @@ int Engine::run_server() {
                     (long long)aend.patch_dim);
             return RAD_E_INVAL;
         }
+        /* The tokens around a clip: the config's ids where it names them (Gemma 4's boa/eoa),
+         * else the spellings the architecture plugin states (RadAudioFormat). Each must be one
+         * token of this vocabulary, or the prompt would carry text where the model was trained on
+         * a marker. */
+        const RadAudioFormat* afmt = rad_tools_audio_format(plugins_, meta_);
+        auto one_token = [&](const char* spell, int32_t* id) -> int {
+            if (*id >= 0 || !spell || !*spell) return RAD_OK;
+            const std::vector t = tok_bridge.encode(spell, /*add_special=*/false,
+                                                             /*parse_special=*/true);
+            if (t.size() != 1) {
+                RAD_ERR("the architecture plugin spells a clip's marker '%s', which this "
+                        "vocabulary reads as %zu tokens rather than one", spell, t.size());
+                return RAD_E_INVAL;
+            }
+            *id = t[0];
+            return RAD_OK;
+        };
+        if (afmt) {
+            RAD_TRY(one_token(afmt->audio_open, &ac.tok_start));
+            RAD_TRY(one_token(afmt->audio_close, &ac.tok_end));
+            auto str = [](const char* p) { return std::string(p ? p : ""); };
+            speech_fmt.transcribe_prompt = str(afmt->transcribe_prompt);
+            speech_fmt.language_prompt   = str(afmt->language_prompt);
+            speech_fmt.transcript_open   = str(afmt->transcript_open);
+            speech_fmt.language_lead     = str(afmt->language_lead);
+            for (uint32_t i = 0; afmt->languages && i < afmt->n_languages; ++i)
+                speech_fmt.languages.emplace_back(str(afmt->languages[2 * i]),
+                                                  str(afmt->languages[2 * i + 1]));
+        }
+        if (ac.tok_start < 0 || ac.tok_end < 0) {
+            RAD_ERR("the '%s' encoder's clips have no opening or closing token: the container "
+                    "names none and the architecture plugin states none (rad_arch_audio_format)",
+                    ranks_[0]->program.audio_encoder_name.c_str());
+            return RAD_E_INVAL;
+        }
         ac.merge = (int32_t)aend.merge;
         ac.max_frames = aend.max_patches;
         if (!mm_proc) mm_proc = std::make_unique();
-        RAD_TRY(mm_proc->init_audio(ac));
+        if (const int rc = mm_proc->init_audio(ac, &why); rc < 0) {
+            RAD_ERR("the '%s' encoder's audio front end cannot be built: %s",
+                    ranks_[0]->program.audio_encoder_name.c_str(), why.c_str());
+            return rc;
+        }
         o.allow_audio = true;
         if (mm::decoder_available())
             RAD_INFO("media: audio through '%s'; a clip is cut at %.3g s, %d mel bins a %d ms frame, "
                      "%d frames a token; %lld frames a pass",
                      ranks_[0]->program.audio_encoder_name.c_str(),
-                     (double)ac.max_samples / (double)ac.rate, ac.n_mels,
+                     (double)mm_proc->audio_config().max_samples / (double)ac.rate, ac.n_mels,
                      ac.hop * 1000 / ac.rate, ac.merge, (long long)aend.max_patches);
     }
     if (mm_proc) {
         mm_bridge = std::make_unique(
             mm_proc.get(), encd.modalities | aend.modalities);
         d.mm = mm_bridge.get();
+        if (speech_fmt.transcribes() && o.allow_audio) {
+            d.speech = &speech_fmt;
+            RAD_INFO("speech: /v1/audio/transcriptions through '%s', %zu languages",
+                     ranks_[0]->program.audio_encoder_name.c_str(), speech_fmt.languages.size());
+        }
     }
 
-    /* AN IMAGE GENERATOR'S ENDPOINTS: the driver's queue, the model's declared prompts and sizes,
-     * and the processor for the conditioning network's view of a reference picture. */
+    /* An image generator's endpoints: the driver's queue, the declared prompts and sizes, and the
+     * processor that prepares a reference picture for the conditioning network. */
     struct ImageBridge final : server::IImageGen {
         gen::Driver*         drv = nullptr;
         const mm::Processor* proc = nullptr;
@@ -2617,8 +2332,8 @@ int Engine::run_server() {
         image_bridge.drv = gen_.get();
         image_bridge.proc = mm_proc.get();
         d.images = &image_bridge;
-        /* The model a client lists and names is the generator's own (qwen-image-2.1), not the
-         * architecture a diffusers pipeline's container is named after. */
+        /* The served model id is the generator's own name (qwen-image-2.1), not the container's
+         * architecture name. */
         if (cfg_.served_model_name.empty() && !in.name.empty()) {
             o.model_id = in.name;
             decide("--served-model-name", o.model_id, "an image generator: its own name");
@@ -2639,10 +2354,9 @@ int Engine::run_server() {
     if (cfg_.max_queued_requests <= 0)
         decide("--max-queued-requests", std::to_string(srv.queue_cap()), "8 x --max-num-seqs");
 
-    /* A TEMPLATE DEFAULT THE TEMPLATE REFUSES is a 400 on every chat request that leaves it to
-     * the default, found by the first caller rather than the operator. --chat-template-kwargs
-     * stops startup; --reasoning-effort only warns, because a deployment whose clients all send
-     * their own effort serves correctly with one the template would refuse. */
+    /* A default the template refuses would 400 every chat request that relies on it. Bad
+     * --chat-template-kwargs stop startup; --reasoning-effort only warns, since clients that send
+     * their own effort are unaffected. */
     if (d.chat && (!cfg_.chat_template_kwargs.empty() || !cfg_.reasoning_effort.empty())) {
         std::string kw_why, eff_why;
         srv.check_template_defaults(&kw_why, &eff_why);
@@ -2656,9 +2370,8 @@ int Engine::run_server() {
                      "that sends no reasoning effort of its own will be answered 400: %s",
                      cfg_.reasoning_effort.c_str(), eff_why.c_str());
     }
-    /* THE EFFORTS THE TEMPLATE TAKES, said once: a client sending another gets this set back in
-     * its 400 and can read it off /server_info beforehand. A map whose target the template
-     * refuses would refuse every request it maps, so it stops startup. */
+    /* Log the efforts the template accepts (a client sending another gets this set in its 400,
+     * and /server_info shows it). A map target the template refuses stops startup. */
     if (d.chat) {
         const std::vector efforts = srv.probe_reasoning_efforts();
         std::string mapped;
@@ -2678,41 +2391,31 @@ int Engine::run_server() {
             return RAD_E_INVAL;
         }
     }
-    /* A BUDGET THE MODEL CANNOT HOLD STOPS STARTUP, as --chat-template-kwargs does: the default
-     * would apply to no request at all, and the operator who set it would not find out. */
+    /* A thinking budget the model cannot hold stops startup; it would silently apply to no
+     * request. */
     if (const std::string why = srv.check_thinking_budget(); !why.empty()) {
         RAD_ERR("--thinking-token-budget %lld: %s", (long long)cfg_.thinking_token_budget,
                 why.c_str());
         return RAD_E_INVAL;
     }
     print_startup_report(RAD_OK);
+    const char* const keyed = o.api_key.empty() ? "" : "; a bearer key is required";
     if (embedding_)
-        RAD_INFO("serving on http://%s:%d  (/v1/embeddings; completions and chat are 501)%s",
-                 o.host.c_str(), o.port, o.api_key.empty() ? "" : "  -- a bearer key is required");
+        RAD_INFO("serving on http://%s:%d  (/v1/embeddings; completions and chat are 501%s)",
+                 o.host.c_str(), o.port, keyed);
     else if (gen_)
         RAD_INFO("serving on http://%s:%d  (/v1/images/generations%s; completions and chat are "
-                 "501)%s", o.host.c_str(), o.port,
-                 d.images && d.images->info().max_refs > 0 ? " and /v1/images/edits" : "",
-                 o.api_key.empty() ? "" : "  -- a bearer key is required");
+                 "501%s)", o.host.c_str(), o.port,
+                 d.images && d.images->info().max_refs > 0 ? " and /v1/images/edits" : "", keyed);
     else
-        RAD_INFO("serving on http://%s:%d  (/v1/completions%s)%s", o.host.c_str(), o.port,
+        RAD_INFO("serving on http://%s:%d  (/v1/completions%s%s)", o.host.c_str(), o.port,
                  d.chat ? "; /v1/chat/completions with tools and reasoning" : "; chat is 501",
-                 o.api_key.empty() ? "" : "  -- a bearer key is required");
+                 keyed);
 
-    /* THE LIVE VIEW (spec §16), constructed here and nowhere else.
-     *
-     * `core/server/liveview.{h,cpp}` is the console's view of a running engine, and the
-     * throughput heartbeat the server otherwise has no form of: nothing here logs a request,
-     * and everything else the engine prints happens at startup, so a loop that stalls looks
-     * exactly like a loop with nothing to do.
-     *
-     * Off by default, because §16 opens with "everything below is off by default". Redirected, it
-     * prints one greppable key=value line per interval and no escape sequences at all -- which is
-     * the property that makes it usable under nohup, and the reason the renderer is chosen once by
-     * isatty() rather than per draw.
-     *
-     * The snapshot function is the only part the engine owns: LiveView holds no data and reads no
-     * device. Held by value in this scope so its thread is joined before Deps goes out of it. */
+    /* The live view (spec §16, off by default): the console's throughput heartbeat
+     * (core/server/liveview.h). Redirected, it prints one key=value line per interval with no
+     * escape sequences; the renderer is chosen once by isatty(). LiveView holds no data and only
+     * calls `snap`. Scoped here so its thread is joined before Deps goes out of scope. */
     std::unique_ptr live;
     if (cfg_.live_view) {
         live = std::make_unique(snap);
@@ -2734,10 +2437,8 @@ int Engine::run_server() {
                 srv.stop();
                 return;
             }
-            /* THE STEP LOOP HAS DIED, so nothing will ever run another step. Every request it
-             * held has already been failed and answered (Engine::fail_loop); what is left is to
-             * stop taking new ones, which a transport left up would accept into a queue nobody
-             * drains. */
+            /* The step loop died and its requests were already failed (Engine::fail_loop); stop
+             * the transport so no new request is queued. */
             if (loop_status_.load(std::memory_order_acquire) < 0) {
                 RAD_ERR("stopping: the step loop failed with %s",
                         rad_strerror(loop_status_.load(std::memory_order_acquire)));
@@ -2748,10 +2449,11 @@ int Engine::run_server() {
         }
     });
 
+    /* Startup ends here; a quiet server from now on is an idle one. */
+    startup_watch_.reset();
     const int rc = srv.run();
-    /* The loop tests `watching` FIRST, so clearing it ends the watcher WITHOUT a second stop: a
-     * normal return from run() has already torn the transport down. It costs one sleep interval
-     * to join, which is the price of not polling a condition variable nobody else waits on. */
+    /* The watcher tests `watching` first, so clearing it ends the thread without a second stop;
+     * run() has already torn the transport down. Joining costs up to one sleep interval. */
     watching.store(false, std::memory_order_relaxed);
     watcher.join();
     if (live) live->stop();
diff --git a/core/engine.h b/core/engine.h
index 1acbd1d9..bccf2a03 100644
--- a/core/engine.h
+++ b/core/engine.h
@@ -1,23 +1,21 @@
-/* engine.h -- the startup sequence and the step loop. This is the file that says, in order, what
- * happens between a command line and a served token, and it is deliberately the thinnest thing in
- * the project: every step below is one component doing its own job.
+/* engine.h -- the startup sequence and the step loop: what happens, in order, between a command
+ * line and a served token. Kept thin; each step is one component doing its own job.
  *
  * Startup, per spec §1:
  *
  *   1. Load kernel plugins from $RADIANCE_HOME/kernels/, in the configured hierarchy order.
- *   2. Load the model's metadata ONLY -- architecture id, dimensions, quantisation, vocab.
+ *   2. Load the model's metadata only: architecture id, dimensions, quantisation, vocab.
  *   3. Look up the architecture id in $RADIANCE_HOME/architectures/. No match, no model.
- *   4. DECLARE. The architecture plugin enumerates every weight, buffer and op it will ever
- *      issue. The core resolves each op against the kernel hierarchy. This phase ALWAYS
- *      completes; if anything failed to resolve, the full list is reported at the end rather
- *      than the first failure at the top.
- *   5. PLAN. The placement planner assigns every weight a tier and an execution site, against
+ *   4. Declare. The architecture plugin enumerates every weight, buffer and op it will ever
+ *      issue, and the core resolves each op against the kernel hierarchy. This phase always
+ *      completes and reports every resolution failure, not just the first.
+ *   5. Plan. The placement planner assigns every weight a tier and an execution site against
  *      explicit pool budgets.
- *   6. LOAD. Weights are mapped and staged according to the plan.
+ *   6. Load. Weights are mapped and staged according to the plan.
  *   7. Serve.
  *
- * Between 4 and 5 the whole model is known statically: every op, every kernel that will service
- * it, every weight it touches, and the order. That is the property the rest of the engine spends.
+ * After step 4 the whole model is known statically: every op, its kernel, the weights it touches,
+ * and the order. The rest of the engine relies on that.
  */
 #pragma once
 #include "rad_core.h"
@@ -42,86 +40,86 @@
 namespace rad {
 
 class Kld;
+class StallWatch;
 namespace gen { class Driver; }
 struct TierPump;
 struct TierJob;
 struct StepSlot;
 
 struct VramFacts;   /* mem/vram_budget.h */
+struct WeightFootprint;   /* place/planner.h */
 
 class Engine {
 public:
     explicit Engine(Config cfg);
     ~Engine();
 
-    /* Steps 1..6. Returns negative and has already printed WHAT failed and WHY. A missing kernel
-     * is reported as the whole list, not the first one. */
+    /* Steps 1..6. Returns negative after printing what failed and why; missing kernels are
+     * reported as a full list. */
     int start();
 
-    /* Step 7. Blocks. Returns when the server is asked to stop or a device fault ends the
-     * process -- a device fault is not recoverable in-process and we exit non-zero rather than
-     * serving from a wedged queue (spec §17). */
-    int serve();
+    /* Step 7. Blocks until the server is asked to stop. A device fault is not recoverable
+     * in-process, so it exits non-zero rather than serving from a wedged queue (spec §17).
+     * `watch`, when given, is the startup's stall watch (util/stallwatch.h): held until the
+     * server listens, or the KL mode starts scoring, so the stretch from start() to there
+     * reports where it waits like start() itself. */
+    int serve(std::unique_ptr watch);
 
-    /* --debug-graph and friends: everything declare and plan learned, printed, without serving.
-     * This is the answer to "it is unclear what even runs", so it is a first-class mode and not
-     * a side effect of a verbose flag. */
+    /* --debug-graph and friends: print everything declare and plan learned, without serving. A
+     * first-class mode rather than a verbose-flag side effect, so what runs is always visible. */
     int dump();
 
     const Program& program() const;
     const Config&  config()  const { return cfg_; }
 
-    /* THE STARTUP REPORT (core/diag/diag.h): every option with the value in force and its source,
-     * the machine, and what on it costs speed or correctness. serve() prints it before it starts
-     * listening with `status` RAD_OK; main prints it with the error start() or serve() stopped
-     * with, so a log of a server that never came up still says what it was running on and what
-     * it had decided -- and ends with that error again on an E line, because the report's lines
-     * now follow the one that said it and a reader of the log's tail would see only them. */
+    /* The startup report (core/diag/diag.h): every option with its value and source, the
+     * machine, and what on it costs speed or correctness. serve() prints it with RAD_OK before
+     * listening; main prints it with the error start() or serve() failed with, so a server that
+     * never came up still logs its setup. The report then repeats the error on an E line, so the
+     * log's tail shows it. */
     void print_startup_report(int status);
-    /* The same, as JSON, with the hardware read again -- a card's link and clock are only
-     * meaningful under load, and /diagnostics is how they are read while a request runs. The
-     * reading is reused for a second, and covers the power-management files of the serving
-     * cards only (hardware_facts). */
+    /* The report as JSON, with the hardware re-read, since link and clock state only mean
+     * something under load (/diagnostics). The reading is reused for a second and covers only the
+     * serving cards' power-management files (hardware_facts). */
     std::string diagnostics_json() const;
     bool startup_report_printed() const { return report_printed_; }
 
 private:
-    /* One thread per tensor-parallel rank, each owning one device. No IPC, no shared-memory
-     * handshake, no serialisation between ranks -- which is most of what a Python engine spends
-     * its multiprocessing budget on. Because the ranks share an address space, the step batch is
-     * shared BY POINTER rather than broadcast (spec §1). */
+    /* One thread per tensor-parallel rank, each owning one device. Ranks share the address
+     * space, so there is no IPC or serialisation and the step batch is shared by pointer rather
+     * than broadcast (spec §1). */
     struct Rank;
     std::vector> ranks_;
-    /* THE TIERS' WORK IN FLIGHT: the copy to host memory the transfer streams are running. */
+    /* The tiers' work in flight: the host-memory copies the transfer streams are running. */
     std::unique_ptr pump_;
+    /* serve()'s startup stall watch, released when the server listens (run_server) or the KL
+     * mode starts (run_kld). */
+    std::unique_ptr startup_watch_;
     std::vector           rank_threads_;
 
     Config cfg_;
-    /* THE SPLIT EACH RANK ACTUALLY TAKES. Equal to cfg_ on every rank whose cache costs as much per
-     * token as the dearest rank's -- every rank of a world whose ranks all cost the same; a rank
-     * whose cache costs less (an attention-zero rank) gets a KV pool sized for the common token
-     * count and the difference in its weights pool. Engine::plan fills it, and every reader of the
-     * resolved pool sizes -- Pools::configure and the planner -- takes its rank's entry, never
-     * cfg_: a grown pool the planner never reads is an empty pool, and plan() refuses a rank whose
-     * plan and weights pool disagree. */
+    /* The VRAM split each rank actually takes, filled by Engine::plan. Equal to cfg_ on every
+     * rank whose cache costs as much per token as the dearest rank's. A cheaper rank (an
+     * attention-zero rank) gets a KV pool sized for the common token count and the difference in
+     * its weights pool. Pools::configure and the planner must read the rank's entry, never cfg_;
+     * plan() refuses a rank whose plan and weights pool disagree. */
     std::vector rank_cfg_;
     int64_t kv_planned_tokens_ = 0;   /* the common token count plan() sized the re-split pools for */
 
-    /* The model's source, one of the two. A container stays mapped for the life of the engine:
-     * the mapped and file tiers read it where it lies (spec §4.2). A checkpoint served directly
-     * stays mapped too, and is read once, at load (spec §4.3). */
+    /* The model's source, one of the two. A container stays mapped for the engine's life because
+     * the mapped and file tiers read it in place (spec §4.3). A checkpoint served directly also
+     * stays mapped and is read once, at load (spec §4.3). */
     std::unique_ptr file_;
     std::unique_ptr ckpt_;
     std::unique_ptr ckpt_src_;
-    /* What rad_weight_encoding is answered from: the container's entries or the checkpoint's
-     * tensors. */
+    /* The source rad_weight_encoding answers from: container entries or checkpoint tensors. */
     WeightSourceFn sources() const;
 
     RadModelMeta   meta_{};
     LoadedPlugins  plugins_;
 
-    /* RadModelMeta holds bare char*, so the strings behind its free-form key/value table have to
-     * outlive every declare. */
+    /* RadModelMeta holds bare char*, so the strings behind its key/value table must outlive
+     * every declare. */
     std::vector meta_kv_k_, meta_kv_v_;
     std::vector meta_kv_kp_, meta_kv_vp_;
 
@@ -135,35 +133,38 @@ private:
     int apply_rope_scaling();
     int declare();
     int plan();
-    /* --embedding-placement, --vision-tower-placement and --ngram-placement, resolved into Config
-     * before the card is split (engine_bringup.cpp says how auto chooses). */
+    /* Resolves --embedding-placement, --vision-tower-placement and --ngram-placement into Config
+     * before the card is split (engine_bringup.cpp describes how auto chooses). `wfs` is every
+     * rank's footprint, read for its towers. `host_late` is the pinned host memory startup
+     * allocates after the tables and outside every pool (the checkpoint store, the host
+     * activation arenas), which a table pinned in host memory must leave room for. */
     int resolve_table_placement(const std::vector& facts,
                                 const std::vector& emb_bytes,
-                                const std::vector& tower_bytes, int64_t kv_floor,
-                                int64_t ngram_bytes, bool ngram_device, bool ngram_host);
-    /* --ngram-placement ram: the copy of the container's [src, src + n), file offset `foff`, made
-     * once and shared by every rank -- locked for the host gather, or pinned for a device kernel
-     * to read over the link (`card`). */
+                                const std::vector& wfs, int64_t kv_floor,
+                                int64_t ngram_bytes, bool ngram_device, bool ngram_host,
+                                int64_t host_late);
+    /* --ngram-placement ram: one copy of the container's [src, src + n) at file offset `foff`,
+     * shared by every rank. Locked for the host gather, or pinned for a device kernel to read
+     * over the link (`card`). */
     int copy_table(const uint8_t* src, int64_t n, int64_t foff, bool card, void** out,
                    std::string* why);
-    /* An auto-chosen pinned copy that could not be made: every rank's n-gram gather to the host. */
+    /* An auto-chosen pinned copy failed: move every rank's n-gram gather to the host. */
     bool ngram_gather_to_host();
-    /* The copies made: the locked ones, each [base, base + bytes); the pinned ones, rad_dev_alloc
-     * RAD_MEM_HOST_MAPPED ranges; and the container address each one copies. Freed in ~Engine
-     * after the ranks that read them are gone. */
+    /* The table copies: locked ones as [base, base + bytes), pinned ones as rad_dev_alloc
+     * RAD_MEM_HOST_MAPPED ranges, and the container address each copies. Freed in ~Engine after
+     * the ranks that read them are gone. */
     std::vector table_copies_;
     std::vector card_copies_;
     std::vector> table_copy_of_;
     int load_weights();
     int configure_kv();
-    /* One sampled row's worth of bookkeeping, so the step loop can map a logits row back to the
-     * sequence that wanted it. It is NOT the identity: a prefill chunk in the middle of a long
-     * prompt produces no row at all, and a speculative verify produces 1 + n_spec of them. */
+    /* Maps the step's logits rows back to the sequences that wanted them. Not the identity: a
+     * mid-prompt prefill chunk produces no row, and a speculative verify produces 1 + n_spec. */
     struct StepOut {
         std::vector reqs;       /* the requests that wanted a row, in row order */
         std::vector  first_row;  /* [n_seq] that entry's first row, or -1 */
-        /* HOW MANY OF THE STEP'S LOGITS ROWS THE SAMPLER READS: the first ones. RadBatch::n_out
-         * counts the KL mode's scored rows after them too (Request::score). */
+        /* Leading logits rows the sampler reads. RadBatch::n_out also counts the KL mode's scored
+         * rows after them (Request::score). */
         int32_t               n_rows = 0;
         std::vector  rows;       /* [n_out] the device's answer, copied back */
         int32_t*              rb = nullptr;   /* the pinned readback collect_issue filled */
@@ -176,15 +177,14 @@ private:
         std::vector lp;
     };
 
-    /* The text frontend, loaded out of the container. `vocab_view_` is what the sampler's
-     * grammars walk; it holds a reference to `vocab_` and must not outlive it. */
+    /* The text frontend, loaded from the container. The sampler's grammars walk `vocab_view_`,
+     * which references `vocab_` and must not outlive it. */
     std::shared_ptr vocab_;
     std::unique_ptr   vocab_view_;
 
-    /* The chunk geometry, resolved ONCE here and handed to both consumers. The prefix cache needs
-     * the checkpoint interval at configure time and the scheduler needs the whole geometry at
-     * init; resolving it independently in each is how the cache ends up testing the operator's raw
-     * interval against positions the scheduler chose with the rounded one. */
+    /* The chunk geometry, resolved once and shared: the prefix cache needs the checkpoint interval
+     * at configure time and the scheduler the whole geometry at init. Resolving it separately
+     * would let the cache use the raw interval while the scheduler uses the rounded one. */
     ChunkGeometry                 geo_;
 
     /* One scheduler for every rank: one decision per step, one batch, shared by pointer. */
@@ -192,38 +192,23 @@ private:
     std::unique_ptr   kv_iface_;
     std::unique_ptr pc_iface_;
 
-    /* The release point. Width is tp + 1 -- the scheduler thread is on both sides of it. */
+    /* The release point. Width is tp + 1: the scheduler thread also takes part. */
     std::unique_ptr  barrier_;
     std::atomic  step_batch_{nullptr};
-    /* WHAT A RELEASE ASKS THE RANKS TO ISSUE: the forward pass and its sampler (kIssueAll), the
-     * forward pass alone (kIssueModel) -- the next step's, issued before this one is read back --
-     * or that pass's sampler alone (kIssueSampler), once the host has committed what the sampler
-     * stages from. Every release sets it: one left over from the release before tells a draft
-     * pass to issue nothing but its sampler. */
+    /* What a release asks the ranks to issue: the forward pass and its sampler (kIssueAll), the
+     * forward pass alone (kIssueModel: the next step's, issued before this one is read back), or
+     * that pass's sampler alone (kIssueSampler, once the host has committed its inputs). Every
+     * release must set it; a stale value would make a draft pass issue only its sampler. */
     enum { kIssueAll = 0, kIssueModel = 1, kIssueSampler = 2 };
     std::atomic              issue_what_{kIssueAll};
     std::atomic              step_status_{RAD_OK};
     std::atomic             stopping_{false};
-    /* WHY THE STEP LOOP ENDED, when it ended on an error; RAD_OK while it runs or after a clean
-     * stop. Written once, by fail_loop(); read by the server watcher to take the HTTP side down
-     * and by serve() to return it. */
+    /* The error the step loop ended on; RAD_OK while running or after a clean stop. Written once
+     * by fail_loop(); read by the server watcher to stop HTTP and by serve() to return it. */
     std::atomic              loop_status_{RAD_OK};
     int  fail_loop(int st);
 
-    /* THE SAMPLER'S HOST WORK RUNS UNDER THE MODEL, NOT IN FRONT OF IT.
-     *
-     * Staging a step's sampler parameters -- and with a grammar, walking a whole-vocabulary mask
-     * for every position in the speculative window -- is pure host work: every upload in the chain
-     * is issued by Sampler::run on the rank thread, so build_step touches no stream and nothing
-     * the ranks read until they are told to sample. Run BEFORE the release it sits in front of a
-     * device with nothing to do, and every microsecond of it is added to the step.
-     *
-     * So the ranks are released to enqueue the model first, and the scheduler stages the sampler
-     * while they do. The ranks then wait here for it before enqueueing the sampler chain -- which
-     * the device cannot reach until the whole forward pass has run, and that pass is the time the
-     * walk hides inside. This is a one-shot gate per step, reset while the ranks are parked at the
-     * release, so there is no window in which a rank can read a stale ready flag. */
-    /* THIS STEP'S SCORED ROWS (Request::token_scores): a logits row and the result it fills.
+    /* This step's scored rows (Request::token_scores): a logits row and the result it fills.
      * Written by the scheduler thread while the ranks are parked, read by them during the step,
      * consumed by collect_step. */
     std::vector> score_rows_;
@@ -231,12 +216,18 @@ private:
     int  issue_scored_rows(Rank& r);
     int  collect_scored_rows();
 
+    /* Gate for the sampler's host work, which runs while the device executes the model.
+     * Staging sampler parameters (and, with a grammar, a whole-vocabulary mask per draft
+     * position) touches no stream: Sampler::run issues every upload on the rank thread. So the
+     * ranks enqueue the model first, the scheduler runs build_step meanwhile, and the ranks wait
+     * here before enqueueing the sampler chain. One-shot per step, reset while the ranks are
+     * parked at the release, so no rank can see a stale ready flag. */
     std::mutex                    build_mu_;
     std::condition_variable       build_cv_;
     bool                          build_ready_  = false;
     int                           build_status_ = RAD_OK;
 
-    /* Scratch for the checkpoint copies: the state slots of one sequence, reused so the step path
+    /* Scratch for the checkpoint copies: one sequence's state slots, reused so the step path
      * does not allocate. See state_slots_of. */
     std::vector          ckpt_slots_;
     std::vector          ckpt_win_;    /* KVManager::window_rows, same reuse */
@@ -244,41 +235,37 @@ private:
 
     int  load_vocab();
     int  declare_sampler(int rank, RadBuilder* b, int64_t logits_width, bool sizing = false);
-    /* The build context every declare of rank `rank` gets, at `max_tok` -- the real one and the
-     * activation arena's sizing declares differ in nothing else. */
+    /* The build context for every declare of rank `rank` at `max_tok`; the real declare and the
+     * arena's sizing declares differ only in max_tok. */
     RadBuildCtx build_ctx(int rank, int64_t max_tok) const;
     void probe_arena_levels();
     int  step_loop();
-    /* The step's sampled ids on their way to the host, and then the wait for them and what they
-     * mean. Split so the copy can be issued before draft passes that overwrite the ids and the
-     * wait left until after them. */
-    int  collect_issue(const RadBatch* b, StepOut& so);
+    /* Issue the copy of the step's sampled ids to the host, then wait for and interpret them.
+     * Split so the copy is issued before draft passes overwrite the ids, and the wait comes after
+     * them. */
+    int  collect_issue(StepOut& so);
     int  collect_step(const RadBatch* b, StepOut& so);
     int  row_logprobs(StepOut& so, int32_t row, int32_t token);
-    /* WHERE THE STEP ENDS ON THE CARD: after its last draft pass and the copies the host reads,
-     * and before the step issued ahead of it. collect_step waits for this and not for the
-     * stream, so the card runs the next step while the host commits this one. */
+    /* The step's end on the card: after its last draft pass and the host readbacks, before the
+     * step issued ahead. collect_step waits on this event, not the stream, so the card runs the
+     * next step while the host commits this one. */
     int  mark_step_end(const RadBatch* b, StepOut& so);
     RadEvent step_end_ = nullptr;
 
-    /* THE DRAFT HEAD, exactly as the plugin declared it (rad_declare_drafter), and zeroed when
-     * the deployment asked for no speculative window. `kind` selects which of the two drivers
-     * below runs; nothing else in the engine knows what model this is.
-     *
-     * `drafter_name_` owns the string, because RadDrafterDecl::name points into the Program. */
+    /* The draft head as declared (rad_declare_drafter), zeroed when no speculative window was
+     * asked for. `kind` selects which of the two drivers below runs. `drafter_name_` owns the
+     * string because RadDrafterDecl::name points into the Program. */
     RadDrafterDecl       drafter_{};
     std::string          drafter_name_;
 
-    /* THE SERIAL DRIVER (spec §10): `depth` dependent passes after the step commits, each
-     * embedding what the last one proposed. MTP, EAGLE and Medusa-serial are all this shape. */
+    /* Serial driver (spec §10): `depth` dependent passes after the step commits, each embedding
+     * the previous proposal. MTP, EAGLE and Medusa-serial have this shape. */
     std::vector draft_out_;   /* [rows][depth], what each pass proposed */
 
-    /* THE HOST SIDE OF EVERY READBACK ON THE STEP PATH: the sampled tokens, and each draft pass's
-     * proposals. Pinned, because a device-to-host copy into pageable memory is a synchronous
-     * bounce through a staging buffer -- the copy itself waits for the whole stream, and the wait
-     * the step then makes finds nothing left to wait for, so it cannot be the wait that sleeps.
-     * Into pinned memory the copy is one more packet on the stream and the step's wait is the
-     * whole of the wait. Grown on first use to the largest readback asked for. */
+    /* Host side of every step-path readback (sampled tokens, draft proposals). Pinned, because a
+     * device-to-host copy into pageable memory bounces synchronously through a staging buffer and
+     * blocks on the whole stream; into pinned memory it is one more stream packet and the step's
+     * own wait is the only wait. Grown on first use to the largest readback requested. */
     struct Readback {
         int32_t* p = nullptr;
         int64_t  n = 0;
@@ -286,33 +273,33 @@ private:
         ~Readback();
     };
     Readback             readback_;
-    /* AN EMBEDDING PROGRAM (rad_declare_pooled): no sampler, and a step's answer is the pooled
-     * buffer's first n_seq rows rather than sampled ids. `pooled_host_` is their pinned landing
-     * place, [max_seqs, pooled_dim_] f32; collect_pooled copies them there behind the step and
-     * hands each row to its request's sink after the step's one wait. */
+    /* Embedding program (rad_declare_pooled): no sampler; a step's answer is the pooled buffer's
+     * first n_seq rows. `pooled_host_` is their pinned landing area, [max_seqs, pooled_dim_] f32;
+     * collect_pooled copies them behind the step and hands each row to its sink after the
+     * step's one wait. */
     bool                 embedding_ = false;
     int64_t              pooled_dim_ = 0;
     float*               pooled_host_ = nullptr;
     int  collect_pooled_issue(const RadBatch* b, StepOut& so);
     int  collect_pooled(const RadBatch* b, StepOut& so);
-    /* AN IMAGE GENERATOR (rad_declare_generator): the driver that turns its requests into passes
-     * and the loop that runs them, in place of the scheduler and the step loop (engine_gen.cpp).
-     * Null for every other program. */
+    /* Image generator (rad_declare_generator): the driver that turns requests into passes and the
+     * loop that runs them, replacing the scheduler and step loop (engine_gen.cpp). Null for every
+     * other program. */
     std::unique_ptr gen_;
     int  gen_loop();
     bool serial_drafting() const;
     int  advance_all(int mode, int round, bool from_proposal, int rows = -1);
-    int  issue_serial_drafter(int step, const RadBatch* b, StepOut& so);
+    int  issue_serial_drafter(int step, StepOut& so);
     /* The next step's forward pass, issued before this one is read back; null when the scheduler
      * wants this step committed first. See Scheduler::step_next. */
     int  issue_ahead(const RadBatch** out);
     /* The arena level and the followers' pools, before any release that runs a forward pass. */
     int  prepare_release(const RadBatch* b);
-    /* Whether a step may be issued ahead at all: the drafter, if there is one, runs on the card
-     * (a block drafter and the prompt-lookup drafter both read the committed sequence). */
+    /* Whether a step may be issued ahead: requires that the drafter, if any, runs on the card (a
+     * block drafter and the prompt-lookup drafter both read the committed sequence). */
     bool pipelining_ = false;
     int  finish_serial_drafter(const StepOut& so);
-    /* What issue_serial_drafter left for finish_serial_drafter: the rows that draft, the rounds
+    /* Handed from issue_serial_drafter to finish_serial_drafter: the drafting rows, the rounds
      * asked for, and the rounds that ran. */
     std::vector serial_row_;
     int  serial_rounds_ = 0, serial_rows_ = 0, serial_done_ = 0;
@@ -322,11 +309,9 @@ private:
     void step_state_fini();
     StepSlot*            slots_host_ = nullptr;
 
-    /* STEP-TIME ATTRIBUTION, Debug only (see the barrier in step_loop): which of the scheduler's
-     * own jobs the time went to. A two-way host/ranks split says which side of the barrier a step
-     * is slow on and nothing more: it does not separate the plan from the grammar from the staging,
-     * and the whole region after the join -- the readback, the commit, the drafter -- falls in
-     * neither bucket, leaving most of the step unattributed. These nine sum to the step. */
+    /* Step-time attribution, Debug only (see the barrier in step_loop): time per scheduler phase.
+     * The nine phases sum to the whole step, including the readback, commit and drafter after the
+     * join. */
     enum Ph { PH_PLAN, PH_BEGIN, PH_BUILD, PH_PRE, PH_RANKS, PH_SAVE, PH_COLLECT, PH_COMMIT,
               PH_DRAFT, PH_N };
     double phase_us_[PH_N] = {};
@@ -334,62 +319,63 @@ private:
     std::chrono::steady_clock::time_point phase_t_{};
     void   phase_mark(int p);
 
-    /* THE BLOCK DRIVER (spec §10): a context pass that mirrors the step just run, then ONE pass
-     * that fills every drafted position at once. DFlash2 is this shape. */
-    rad_buf              raw_buf_ = 0;  /* RADIANCE_DRAFT_RAW's bisect; see run_block_drafter */
+    /* Block driver (spec §10): a context pass mirroring the step just run, then one pass that
+     * fills every drafted position at once. DFlash2 has this shape. */
     int  run_block_drafter(int step);
-    /* THE ENCODER DRIVER (spec §11): every media item the scheduler is waiting on, encoded in
-     * passes of whole segments and read back into the item, between steps and never inside one.
-     * core/engine_mm.cpp. */
+    /* Encoder driver (spec §11, core/engine_mm.cpp): encodes every media item the scheduler waits
+     * on, in passes of whole segments, and reads it back into the item. Runs between steps, never
+     * inside one. */
     int  run_encodes();
     int32_t enc_step_ = 0;
     void drain_completed();
-    /* The terminal ids drain_completed() took, reused so a steady state allocates nothing. */
+    /* Terminal ids drain_completed() took, reused so steady state allocates nothing. */
     std::vector done_;
-    /* THE TIERS' SIDE OF THE LOOP, every iteration: collect a copy that has landed, hand the next
-     * one out, and make room in a full arena. Nothing in it waits on the device, and the
-     * scheduler's lock is held only around the bookkeeping. */
+    /* The tiers' per-iteration work: collect a landed copy, start the next, make room in a full
+     * arena. Never waits on the device; the scheduler's lock covers only the bookkeeping. */
     void tier_tick();
     /* --prefix-cache-ttl, once a second, with or without the tiers (PrefixCache::expire). */
     void expire_tick(uint64_t now_ns);
     uint64_t expire_last_ns_ = 0;
-    /* Every host copy that is waiting, issued and landed now. Under the scheduler's lock, from an
+    /* Issue and land every waiting host copy now. Called under the scheduler's lock by an
      * eviction that would otherwise erase what the copies cover. True when any landed. */
     bool flush_copies();
-    /* THE LOAN: what the KV cache is not using, lent to every rank's expert slab at the addresses
-     * the cache already owns (KVManager, the loan block). Here rather than inside the scheduler
-     * because it spans both sides -- rank 0's cache decides how much, and every rank's mover
-     * fills or empties its slots -- and because a mover may only be driven while its rank thread
-     * is parked, which this thread is the one to know. `idle` also runs each mover's own fill,
-     * which a busy engine gets from the step. */
+    /* The KV loan: what the cache is not using, lent to every rank's expert slab at addresses the
+     * cache already owns (KVManager, the loan block). Lives here, not in the scheduler, because
+     * rank 0's cache sets the amount while every rank's mover fills or empties slots, and a mover
+     * may only be driven while its rank thread is parked, which this thread knows. `idle` also
+     * runs each mover's own fill, which a busy engine gets from the step. */
     void loan_tick(bool idle);
     bool     lending_ = false;
     uint64_t loan_last_ns_ = 0;
-    /* THE ACTIVATION ARENA'S LOAN (Engine::arena_step). `arena_rows_[k]` is the largest step Ctx
-     * level k serves -- level 0 is the full plan -- and empty when the arena lends nothing. The
-     * floor is the largest step seen lately: the loan grows past what it allows only once no step
-     * that large has run for a while, so a turn of prefill chunks does not refill and recall the
-     * slab between every chunk. */
+    /* The activation arena's loan (Engine::arena_step). `arena_rows_[k]` is the largest step Ctx
+     * level k serves (level 0 is the full plan); empty when the arena lends nothing. The floor is
+     * the largest recent step: the loan grows past it only after no step that large has run for a
+     * while, so a run of prefill chunks does not refill and recall the slab between chunks. */
     int  arena_step(const RadBatch* b);
     void arena_tick(uint64_t now_ns);
+    int  arena_level(int64_t rows) const;
     std::vector arena_rows_;
+    /* The span's shared level (Engine::probe_arena_levels): the rows of the level a step of one
+     * interval runs at under --prefill-span, where the prefill stager's ring is the level's own
+     * (stager.h); 0 without one. */
+    int64_t  arena_span_rows_ = 0;
     int64_t  arena_floor_ = 0;
     int64_t  arena_last_ = 0;
     uint64_t arena_floor_ns_ = 0;
-    /* WHAT THE VRAM BUDGET KEPT FOR ALLOCATIONS MADE AFTER start(), on top of --gpu-headroom-mib:
-     * the step batch's staging, which serve() allocates, and what is built on first use, if
-     * ever -- the KV tiers' copy staging and the second compute lane's queue. The bringup's
-     * closing reading is checked against both. */
+    /* VRAM the budget reserves for allocations after start(), on top of --gpu-headroom-mib: the
+     * step batch's staging (allocated by serve()) and what is built on first use, if ever (the KV
+     * tiers' copy staging, the second compute lane's queue). Bring-up's final VRAM reading is
+     * checked against both. */
     int64_t  late_step_bytes_ = 0;
     int64_t  late_lazy_bytes_ = 0;
-    /* THE LINEAR-STATE SNAPSHOT STORE: pinned host memory, --checkpoint-slots slots, each holding
-     * every rank's shard of one snapshot (KVManager::set_checkpoint_store). Not on the card: a
-     * snapshot is read by no kernel, only copied back into a sequence's state. */
+    /* Linear-state snapshot store: pinned host memory, --checkpoint-slots slots, each holding every
+     * rank's shard of one snapshot (KVManager::set_checkpoint_store). Off the card because no
+     * kernel reads a snapshot; it is only copied back into a sequence's state. */
     HostArena ck_store_;
     int  run_server();
-    /* THE KL MODE (core/kld.h), in place of run_server: the corpus's documents submitted as
-     * scoring requests, and every step's scored rows copied to the host and handed to `kld_`.
-     * One pinned block a rank, a step's tokens of this rank's logits columns. */
+    /* KL mode (core/kld.h), replacing run_server: submits the corpus documents as scoring
+     * requests and hands every step's scored rows, copied to the host, to `kld_`. One pinned
+     * block per rank, holding a step's tokens of that rank's logits columns. */
     int  run_kld();
     int  score_rows(const RadBatch* b, const StepOut& so);
     std::unique_ptr kld_;
@@ -398,9 +384,8 @@ private:
     /* The engine half of /server_info, as a JSON object. See the definition in engine.cpp. */
     std::string engine_info() const;
 
-    /* ---- what the startup report says about the run (engine_diag.cpp). `decisions_` holds each
-     * value startup resolved and why, recorded where it was resolved; the rest are the facts a
-     * check needs that only startup saw. */
+    /* ---- startup report inputs (engine_diag.cpp). `decisions_` holds each value startup resolved
+     * and why, recorded where it was resolved; the rest are facts only startup saw. */
     std::vector decisions_;
     void decide(const std::string& key, const std::string& value, const std::string& why) {
         diag::decide(&decisions_, key, value, why);
@@ -412,38 +397,34 @@ private:
     std::string prefix_off_why_;     /* why the engine itself turned prefix caching off, or "" */
     std::vector env_set_;   /* the RADIANCE_* names set when the engine was made */
     bool        report_printed_ = false;
-    /* THE RUNTIME'S DEVICES, ASKED ONCE, in start() beside usable_devices, which reads every
-     * device's properties anyway. A report printed after start() failed -- possibly after a device
-     * fault -- then makes no runtime call at all, and /diagnostics, on an HTTP thread, makes none
-     * either: a runtime call there can wait on a lock the launch path holds
-     * (DeviceBackend::vram_used says the same of the dashboard). What only the runtime knows --
-     * each device's PCI address, its name, whether it is integrated, and the runtime's version --
-     * is kept from that one reading. */
+    /* Runtime device identity (PCI address, name, integrated flag, runtime version), read once in
+     * start() beside usable_devices. Later reports make no runtime call: after a failed start
+     * there may have been a device fault, and on an HTTP thread (/diagnostics) a runtime call can
+     * wait on a lock the launch path holds (see DeviceBackend::vram_used). */
     struct DevId { int device = -1; std::string bdf, name; bool integrated = false; };
     std::vector dev_ids_;
     std::string        runtime_version_;
     void identify_devices(const std::vector& names);
-    /* WHAT ONLY A SYSTEM CALL ANSWERS (diag::probe_process), asked once when the report is first
-     * printed: the memlock limit cannot change under a running process, and the io_uring probe is
-     * a syscall that /diagnostics has no reason to repeat on every request. */
+    /* Syscall-only facts (diag::probe_process), read once at the first report: the memlock limit
+     * cannot change under a running process, and the io_uring probe need not repeat per
+     * /diagnostics request. */
     bool        probed_ = false;
     int64_t     memlock_soft_ = -1;
     std::string io_uring_;
-    /* THE MACHINE AS /diagnostics LAST READ IT, kept for kDiagReuseNs. The card files are answered
-     * by the SMU under the driver's power-management lock, so a client polling the endpoint must
-     * not turn into a stream of SMU requests beside the serving process; a second's staleness is
-     * nothing to a reading of links and clocks. */
+    /* The last /diagnostics hardware reading, reused for kDiagReuseNs. The SMU answers the card
+     * files under the driver's power-management lock, so a polling client must not become a
+     * stream of SMU requests beside the server. */
     mutable std::mutex  diag_mu_;
     mutable diag::Facts diag_facts_;
     mutable uint64_t    diag_read_ns_ = 0;
-    /* `serving`: read the power-management files of the cards the ranks serve on only
-     * (diag::collect's `managed`), which is how a running server reads them. */
+    /* `serving`: read power-management files only for the cards the ranks serve on
+     * (diag::collect's `managed`). */
     diag::Facts    hardware_facts(bool serving) const;
     diag::RunFacts run_facts(bool failed) const;
 
-    /* One dispatch of the tiering seam: retire what landed, credit last step's routing and issue
-     * what the heat engine proposes. A member because Rank is private, and a no-op on a static
-     * plan. See the long note at the definition for why a step is the unit. */
+    /* One dispatch of the tiering seam: retire what landed, credit last step's routing, issue
+     * what the heat engine proposes. A member because Rank is private; a no-op on a static plan.
+     * The definition explains why a step is the unit. */
     void tiering_dispatch(Rank& r, int step);
     void rank_loop(int rank);
 };
diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp
index b2bc70a3..06c100e0 100644
--- a/core/engine_bringup.cpp
+++ b/core/engine_bringup.cpp
@@ -1,13 +1,11 @@
-/* engine_bringup.cpp -- everything the Engine does ONCE, in the order it does it.
+/* engine_bringup.cpp -- everything the Engine does once, in order: devices, the container's
+ * metadata, the plugins, declare, the placement plan, the weights, the KV pools, the rank threads
+ * and the vocabulary. Each numbered section is one component doing its own job.
  *
- * Devices, the container's metadata, the plugins, declare, the placement plan, the weights, the
- * KV pools, the ranks' threads, the vocabulary. Each numbered section is one component doing its
- * own job; this file is the order they happen in and nothing else.
- *
- * Kept apart from engine.cpp because none of it runs again: the step loop next door is on the hot
- * path and shares nothing with this but the Engine's fields. See engine_priv.h.
+ * Separate from engine.cpp (the hot step loop), with which it shares only the Engine's fields.
  */
 #include "engine_priv.h"
+#include "engine_hostmem.h"
 #include "gen/driver.h"
 
 #include "build/startup.h"
@@ -21,9 +19,11 @@
 #include "rad_plugin.h"
 #include "mem/vram_budget.h"
 #include "runtime/arena.h"
+#include "runtime/kvbind.h"
 #include "runtime/xprefetch.h"
 #include "sample/gbnf.h"
 #include "sched/scheduler.h"
+#include "text/token_view.h"
 #include "text/tokenizer.h"
 
 #include 
@@ -52,39 +52,27 @@
 namespace rad {
 
 /* ================================================================== the miss report */
-/* WHAT DID NOT RESOLVE, in the three shapes the three answers want.
+/* What did not resolve, in three classes reported differently:
  *
- * A DEVICE miss NO HOST KERNEL STANDS IN FOR is a hole (Program::device_holes has the rule). The
- * band exists and a request can land in it, so the engine refuses to start on one rather than
- * serve until the first step that does -- and every one gets a line of its own carrying the
- * geometry and the constraint that refused it.
+ *   - A device miss no host kernel stands in for is a hole (Program::device_holes). A request can
+ *     land in it, so the engine refuses to start; each gets its own line with the geometry and
+ *     refusing constraint.
+ *   - A device miss a host kernel stands in for is not a hole: the planner runs the op on the host
+ *     with its weights in the container's mapping (how `embed_lookup_q` serves a table too large
+ *     for VRAM). An op with no weights has nothing to place, so on a card its host kernel cannot
+ *     stand in (paged attention reads a VRAM cache).
+ *   - A host miss only removes one placement option and is normal for a GPU library: one line for
+ *     all of them.
  *
- * A DEVICE miss a host kernel stands in for is not a hole at all. The planner puts that op's
- * arithmetic on the host and its weights in the container's mapping, which is how `embed_lookup_q`
- * serves a table too large to copy into VRAM when no device kernel for it is loaded. Reporting
- * that as fatal produces an error nobody believes, and an error nobody believes is how a real one
- * goes unread. An op with no weights has nothing to place, so on a card its host kernel does not
- * stand in: paged attention reads a cache in VRAM, and only a device kernel can.
- *
- * A HOST miss removes ONE placement option for ONE op, and for a kernel library written for a GPU
- * it is the ordinary case rather than news: most ops have no host implementation and never will.
- * One line for all of them.
- *
- * The distinction is the whole point of this function. Printed alike, a large model at tp2 opens
- * with thousands of lines of `E` that are all host misses, and a real device hole is invisible
- * among them. */
+ * Printed alike, host misses would bury a real device hole in thousands of lines. */
 struct MissReport {
     std::vector device;   /* one line each; the engine does not start */
     std::string              host;     /* one line, or empty */
-    /* Device bands whose op DOES have a host kernel. Not a hole: the planner runs such an op on
-     * the host and pins its weights there (Tier::Mapped), which is the whole of how a table too
-     * large to copy into VRAM is served. Reported apart because calling it fatal is a lie an
-     * operator has to learn to ignore -- and an error nobody believes is how a real one goes
-     * unread. */
+    /* Device misses covered by a host kernel (Tier::Mapped weights); informational. */
     std::string              host_only;
-    /* A hole is an all-reduce instance declared on the lossy wire (`exact` 0, which the model
-     * plugin derives from --tp-wire, rad_builder.h). The libraries may serve that world size on
-     * the exact wire, so the refusal names the flag that asks for it. */
+    /* A hole is an all-reduce declared on the lossy wire (`exact` 0, from --tp-wire;
+     * rad_builder.h). The exact wire may be served at that world size, so the refusal names the
+     * flag. */
     bool                     lossy_wire = false;
 
     bool operator==(const MissReport& o) const {
@@ -140,12 +128,8 @@ static MissReport miss_report(const Program& p, bool host_backend) {
     }
     if (host_ops.empty()) return r;
 
-    /* THE OP NAMES, ALL OF THEM UNTIL IT GETS SILLY, and not the bands: a reader who wants the
-     * bands wants --debug-graph, and the bands are what would make this report thousands of lines
-     * long. The names are what a reader can act on -- each one is a reference kernel somebody could
-     * write -- and a short list is not enough to act on: whole-model host execution needs EVERY op
-     * covered, so the op behind "and 1 more" is the one that stops the run and the one the line
-     * does not name. Sixteen is past the point where the answer is a list rather than a shape. */
+    /* Op names, not bands (--debug-graph has those), up to 16. Whole-model host execution needs
+     * every op covered, so the names are actionable; past 16 the list stops being useful. */
     std::string names;
     const size_t k_named = 16;
     for (size_t i = 0; i < host_ops.size() && i < k_named; ++i)
@@ -161,16 +145,13 @@ static MissReport miss_report(const Program& p, bool host_backend) {
 }
 
 /* ================================================================== 1. devices */
-/* A HIP device is not necessarily a discrete GPU. A host with an integrated GPU reports it as a
- * device of its own, claiming a slice of system RAM as VRAM, and a --tp that lands a rank on one
- * runs slowly and wrongly with a failure that looks like a kernel bug. So the engine uses the
- * discrete cards when there are any -- integrated graphics only when it is all there is, which is
- * an APU machine -- and of those the ones sharing the first one's arch, and prints only what that
- * choice DID, rather than reprinting the backend's inventory. Which devices the backend shows at
- * all is the runtime's to say: ROCR_VISIBLE_DEVICES and HIP_VISIBLE_DEVICES pick them. */
-/* `names` receives every device's product name, indexed by device ("" where its properties could
- * not be read), for the startup report's identification of the cards (Engine::identify_devices):
- * the properties are read here once, and reading them again visits each device. */
+/* Choose the devices. An integrated GPU appears as its own HIP device with system RAM as VRAM, and
+ * a rank placed on one runs slowly and wrongly. So the engine uses the discrete cards if any
+ * (integrated only on an APU-only machine), restricted to the first one's arch, and reports only
+ * what it skipped. ROCR_VISIBLE_DEVICES / HIP_VISIBLE_DEVICES control what the runtime exposes.
+ *
+ * `names` receives every device's product name by index ("" if unreadable), for
+ * Engine::identify_devices, so the properties are read only once. */
 static int usable_devices(std::vector* out, std::string* inventory, std::string* note,
                           std::vector* names) {
     const int n = rad_dev_count();
@@ -191,7 +172,7 @@ static int usable_devices(std::vector* out, std::string* inventory, std::st
         any_discrete |= !igpu;
     }
 
-    std::string want;              /* the arch of the first device taken -- the ranks must all match */
+    std::string want;              /* the first taken device's arch; all ranks must match */
     std::string use, skip;
     for (const D& d : all) {
         const bool take = (!any_discrete || !d.igpu) && (want.empty() || want == d.arch);
@@ -202,11 +183,8 @@ static int usable_devices(std::vector* out, std::string* inventory, std::st
     }
     *inventory = fmt("%s backend, %d device(s) [%s]", device_backend_name(), n, inv.c_str());
 
-    /* THE BACKEND ALREADY PRINTED THAT INVENTORY (core/device/dispatch.cpp), so repeating it here
-     * would only cost a reader two lines that say the same thing in different capitalisation.
-     * What is the engine's to say is which of them it will USE -- and that is news only when the
-     * arch filter dropped one, so on a uniform machine this stays empty and nothing is
-     * printed. */
+    /* The backend already printed the inventory (core/device/dispatch.cpp); note only devices
+     * skipped by the filter. */
     *note = skip.empty()
           ? std::string()
           : fmt("using %zu of %d [%s], ignoring [%s]: integrated graphics beside a discrete card, "
@@ -216,16 +194,23 @@ static int usable_devices(std::vector* out, std::string* inventory, std::st
     return out->empty() ? RAD_E_DEVICE : RAD_OK;
 }
 
-/* WHY A POOL'S MEMORY WAS REFUSED, from what the machine holds now. The refusal carries the
- * driver's own answer; these are the facts that explain most of them.
+/* A /proc/meminfo field ("MemTotal", "MemAvailable") in bytes, or -1 when absent. */
+static int64_t meminfo_bytes(const char* key) {
+    std::ifstream f("/proc/meminfo");
+    const std::string want = std::string(key) + ": %lld kB";
+    std::string line;
+    long long kb = 0;
+    while (std::getline(f, line))
+        if (std::sscanf(line.c_str(), want.c_str(), &kb) == 1) return (int64_t)kb * 1024;
+    return -1;
+}
+
+/* Explain a refused pool allocation from the machine's current state.
  *
- * A card refusing its weights pool after its budget was measured had that memory taken in
- * between, and another process on the card is the usual taker -- the budget is measured once,
- * before any rank allocates. A host pool is PINNED memory, and every rank pins its own
- * --host-pool-mib, so a second rank asks for the same amount again. The pool is locked user memory,
- * which the amdgpu driver counts against one system-wide cap: RAM less 1/64 and 1.5 GiB (half of
- * RAM less 1/64 below 3 GiB), unless amdgpu.no_system_mem_limit lifts it. ttm.pages_limit bounds
- * the driver's own allocations and not these. */
+ * A card pool refused after the budget was measured (once, before any rank allocates) usually
+ * lost the memory to another process. A host pool is pinned, once per rank. Pinned memory counts
+ * against amdgpu's system-wide cap: RAM less 1/64 and 1.5 GiB (half of RAM less 1/64 below
+ * 3 GiB), unless amdgpu.no_system_mem_limit lifts it; ttm.pages_limit does not apply. */
 static void report_pool_refusal(int rank, int device, const Pools& pools, const Config& cfg) {
     bool card = false, host = false;
     for (const Shortfall& f : pools.shortfalls()) (f.pool == "host_pool" ? host : card) = true;
@@ -241,16 +226,7 @@ static void report_pool_refusal(int rank, int device, const Pools& pools, const
         int64_t pinned = 0, mapped = 0;
         rad_dev_alloc_totals(RAD_MEM_HOST_PINNED, &pinned, nullptr);
         rad_dev_alloc_totals(RAD_MEM_HOST_MAPPED, &mapped, nullptr);
-        int64_t total = -1, avail = -1;
-        {
-            std::ifstream f("/proc/meminfo");
-            std::string line;
-            while (std::getline(f, line)) {
-                long long kb = 0;
-                if (std::sscanf(line.c_str(), "MemTotal: %lld kB", &kb) == 1) total = (int64_t)kb * 1024;
-                if (std::sscanf(line.c_str(), "MemAvailable: %lld kB", &kb) == 1) avail = (int64_t)kb * 1024;
-            }
-        }
+        const int64_t total = meminfo_bytes("MemTotal"), avail = meminfo_bytes("MemAvailable");
         bool lifted = false;
         {
             std::ifstream f("/sys/module/amdgpu/parameters/no_system_mem_limit");
@@ -263,8 +239,7 @@ static void report_pool_refusal(int rank, int device, const Pools& pools, const
             cap = total - (total >> 6);
             cap = cap < 2 * reserve ? cap >> 1 : cap - reserve;
         }
-        /* A refusal with room under both is not a capacity one, and advice to shrink the pool
-         * would send the reader after the wrong cause: the device's reason above is the answer. */
+        /* With room under both limits the refusal is not about size; do not advise shrinking. */
         const int64_t pool = cfg.host_pool_total_mib() * 1024 * 1024;
         std::string tables, advice = "Lower --host-pool-mib";
         if (cfg.embedding_host_mib) {
@@ -293,57 +268,17 @@ static void report_pool_refusal(int rank, int device, const Pools& pools, const
 }
 
 /* ------------------------------------------------------------------ locked host memory */
-/* WHAT EVERYTHING ELSE ON THE HOST STILL NEEDS beside a table locked whole: the process's own
- * unpooled allocations, the load's staging windows and the page cache the container's hot pages
- * live in. A copy that spends the last of it trades a faster gather for the kernel reclaiming
- * the files this engine reads, and then for the OOM killer. */
+/* Host memory left free beside a table locked whole: the process's unpooled allocations, the
+ * load's staging windows, and the page cache holding the container's hot pages. Without it the
+ * kernel reclaims the files the engine reads, then the OOM killer runs. */
 static const int64_t kLockMargin = (int64_t)4 << 30;
 
-/* A cgroup limit and what its members use that reclaim cannot give back: memory.current less its
- * file pages (cgroup v2) or usage_in_bytes less its cache (v1), since page cache yields to a
- * locked allocation and anonymous memory does not. "max" and v1's near-INT64_MAX sentinel are no
- * limit. True with `room` set when `dir` holds one. */
-static bool cgroup_room(const std::string& dir, bool v2, int64_t* room) {
-    auto read_ll = [](const std::string& f, long long* v) {
-        std::ifstream in(f);
-        std::string t;
-        if (!(in >> t)) return false;
-        char* e = nullptr;
-        *v = std::strtoll(t.c_str(), &e, 10);
-        return e && *e == '\0';
-    };
-    auto stat_ll = [](const std::string& f, const char* key, long long* v) {
-        std::ifstream in(f);
-        std::string k;
-        long long x = 0;
-        while (in >> k >> x) if (k == key) { *v = x; return true; }
-        return false;
-    };
-    long long lim = 0, used = 0, file = 0;
-    if (v2) {
-        if (!read_ll(dir + "/memory.max", &lim)) return false;           /* "max" fails to parse */
-        if (!read_ll(dir + "/memory.current", &used)) return false;
-        (void)stat_ll(dir + "/memory.stat", "file", &file);
-    } else {
-        if (!read_ll(dir + "/memory.limit_in_bytes", &lim) || lim >= ((long long)1 << 62))
-            return false;
-        if (!read_ll(dir + "/memory.usage_in_bytes", &used)) return false;
-        if (!stat_ll(dir + "/memory.stat", "total_cache", &file))
-            (void)stat_ll(dir + "/memory.stat", "cache", &file);
-    }
-    const long long hard = used > file ? used - file : 0;
-    *room = lim > hard ? (int64_t)(lim - hard) : 0;
-    return true;
-}
-
-/* WHETHER `need` MORE BYTES CAN BE HELD IN HOST MEMORY, after `still` more that this process will
- * allocate before the copy is made, or why not. Each limit is one a copy would otherwise meet part
- * way through: the memory the kernel reports available, every memory cgroup from the process's own
- * up to the root it can see, which is the limit Docker's --memory sets and the kernel enforces by
- * killing the process -- and, for a copy mlock()ed for the host gather (`mlocks`), RLIMIT_MEMLOCK
- * unless the process holds CAP_IPC_LOCK. Pinned memory a card reads is the driver's userptr
- * mapping, the host pools' kind, and RLIMIT_MEMLOCK does not count it. A limit that cannot be read
- * is not one; a limit that can is never guessed at. */
+/* Whether `need` more bytes fit in host memory after `still` more this process will allocate
+ * first, or why not. Checks MemAvailable; every memory cgroup from the process's own up to the
+ * visible root (Docker's --memory, enforced by the OOM killer); and, for an mlock()ed copy
+ * (`mlocks`), RLIMIT_MEMLOCK unless the process has CAP_IPC_LOCK. Pinned memory a card reads is a
+ * driver userptr mapping, which RLIMIT_MEMLOCK does not count. An unreadable limit is ignored,
+ * never guessed. */
 static bool lockable_room(int64_t need, int64_t still, bool mlocks, std::string* why) {
     long long locked_kb = 0;
     unsigned long long caps = 0;
@@ -363,22 +298,17 @@ static bool lockable_room(int64_t need, int64_t still, bool mlocks, std::string*
                    humanb(need).c_str());
         return false;
     }
-    {
-        std::ifstream f("/proc/meminfo");
-        std::string line;
-        long long kb = -1;
-        while (std::getline(f, line))
-            if (std::sscanf(line.c_str(), "MemAvailable: %lld kB", &kb) == 1) break;
-        if (kb >= 0 && kb * 1024 - still - kLockMargin < need) {
-            *why = fmt("%s of memory is available, %s more is still to be allocated (the pinned "
-                       "host pools and the prefix cache's host tier), and the copy wants %s with %s "
-                       "to spare", humanb(kb * 1024).c_str(), humanb(still).c_str(),
-                       humanb(need).c_str(), humanb(kLockMargin).c_str());
-            return false;
-        }
+    if (const int64_t avail = meminfo_bytes("MemAvailable");
+        avail >= 0 && avail - still - kLockMargin < need) {
+        *why = fmt("%s of memory is available, %s more is still to be allocated (the pinned host "
+                   "pools, the prefix cache's host tier, the checkpoint slots and the host "
+                   "activation arenas), and this wants %s with %s to spare",
+                   humanb(avail).c_str(), humanb(still).c_str(), humanb(need).c_str(),
+                   humanb(kLockMargin).c_str());
+        return false;
     }
     /* /proc/self/cgroup: "0::/path" on v2, "N:memory:/path" (or a comma list naming memory) on v1.
-     * Each level up to the root of the hierarchy this process can see is a limit of its own. */
+     * Each level up to the visible root is a separate limit. */
     std::ifstream f("/proc/self/cgroup");
     std::string line;
     while (std::getline(f, line)) {
@@ -395,28 +325,24 @@ static bool lockable_room(int64_t need, int64_t still, bool mlocks, std::string*
         }
         if (!memory) continue;
         const std::string root = v2 ? "/sys/fs/cgroup" : "/sys/fs/cgroup/memory";
-        for (;;) {
-            const std::string dir = root + (path == "/" ? std::string() : path);
-            int64_t room = 0;
-            if (cgroup_room(dir, v2, &room) && room - still - kLockMargin < need) {
-                *why = fmt("the memory cgroup at %s leaves %s, %s more is still to be allocated, "
-                           "and the copy wants %s with %s to spare", dir.c_str(),
-                           humanb(room).c_str(), humanb(still).c_str(), humanb(need).c_str(),
-                           humanb(kLockMargin).c_str());
-                return false;
-            }
-            if (path.empty() || path == "/") break;
-            const size_t up = path.find_last_of('/');
-            path = up == 0 || up == std::string::npos ? "/" : path.substr(0, up);
-        }
+        bool fits = true;
+        cgroup_levels(root, path, v2, [&](const std::string& dir, int64_t room) {
+            if (room - still - kLockMargin >= need) return true;
+            *why = fmt("the memory cgroup at %s leaves %s, %s more is still to be allocated, "
+                       "and this wants %s with %s to spare", dir.c_str(),
+                       humanb(room).c_str(), humanb(still).c_str(), humanb(need).c_str(),
+                       humanb(kLockMargin).c_str());
+            fits = false;
+            return false;
+        });
+        if (!fits) return false;
     }
     return true;
 }
 
-/* --ngram-placement ram: the copy is table_copy_make's (core/format/table_copy.h), or for a card,
- * table_copy_fill's into pinned memory every card maps at its host address (rad_dev_alloc
- * RAD_MEM_HOST_MAPPED, locked in pieces). This keeps one a container address, shared by every rank,
- * and frees them after the ranks in ~Engine. */
+/* The copy is table_copy_make's (core/format/table_copy.h), or for a card, table_copy_fill into
+ * pinned memory every card maps (rad_dev_alloc RAD_MEM_HOST_MAPPED, locked in pieces). One copy
+ * per container address, shared by every rank; freed in ~Engine. */
 int Engine::copy_table(const uint8_t* src, int64_t n, int64_t foff, bool card, void** out,
                        std::string* why) {
     for (const auto& c : table_copy_of_)
@@ -450,11 +376,11 @@ int Engine::copy_table(const uint8_t* src, int64_t n, int64_t foff, bool card, v
     return RAD_OK;
 }
 
-/* THE GATHER MOVES TO THE HOST WITH THE TABLE, when --ngram-placement auto chose a pinned copy for
- * a card and it could not be made. Every rank's n-gram weights take the host site, on the
- * WeightInfo Ctx::init reads to choose the op's domain and on the plan beside it, so the gather and
- * its scale move together; a copy some rank already published is host memory, which the host
- * gather reads as it reads RAM. False where no host kernel gathers the table. */
+/* When --ngram-placement auto chose a pinned copy for a card and it could not be made, move the
+ * gather to the host. Every rank's n-gram weights take the host site, in both the WeightInfo
+ * Ctx::init reads and the plan, so the gather and its scale move together; a copy already
+ * published is host memory the host gather can read. False when no host kernel gathers the
+ * table. */
 bool Engine::ngram_gather_to_host() {
     for (auto& r : ranks_) {
         WeightFootprint f;
@@ -471,32 +397,29 @@ bool Engine::ngram_gather_to_host() {
     return true;
 }
 
-/* WHERE THE TWO LOOKUP TABLES GO (--embedding-placement, --ngram-placement), decided once for every
- * rank before the card is split, and written into Config for the planner and the load phase.
+/* Resolve the lookup-table placements (--embedding-placement, --vision-tower-placement,
+ * --ngram-placement) once for every rank before the card is split, into Config for the planner
+ * and the load phase.
  *
- * THE EMBEDDING: Ram, the default, pins it in host memory of its own beside --host-pool-mib
- * (Config::embedding_host_mib), the card's lookup reading its M rows a step over the link in
- * place, so its VRAM goes to the KV cache and the experts. Where it cannot -- a model whose output
- * head is tied to the table reads it whole every step, and a host without the memory has nowhere
- * to pin it -- the default keeps it on the card and says why, and a named `ram` stops the server.
- * Vram keeps it on the card with every other weight a step reads. There is no third tier: the
- * lookup writes the activations a card reads, which a host kernel reading the container cannot
- * reach -- an architecture declares a buffer's domain, and the token embedding's is the device.
+ * Embedding: Ram (default) pins it in its own host memory beside --host-pool-mib
+ * (Config::embedding_host_mib); the card reads its M rows per step over the link, freeing VRAM for
+ * KV and experts. If impossible (an output head tied to the table reads it whole every step, or
+ * the host lacks memory) the default falls back to the card with a reason, while an explicit `ram`
+ * stops the server. There is no disk tier: the lookup writes device-domain activations.
  *
- * THE ENCODER TOWERS: Vram by default; Ram, when named, pins them beside the pool as the embedding
- * is (Config::tower_host_mib), read over the link once an image.
+ * Encoder towers: Vram by default; Ram pins them beside the pool (Config::tower_host_mib), read
+ * over the link once per image.
  *
- * THE N-GRAM TABLE: Vram where a device kernel gathers it and the card holds it; Ram as a copy,
- * pinned for that kernel to read over the link or locked for the host gather; Disk in the
- * container, read by the host gather. Each tier is refused where no kernel reads it there. Auto
- * takes the first that holds the table, in that order: the card's test is the fixed weights and a
- * KV pool for one --max-model-len sequence (`kv_floor`) beside it, and RAM's is lockable_room's --
- * the memory and every cgroup after the pools still to be allocated, and the memlock limit for a
- * locked copy. */
+ * N-gram table: Vram where a device kernel gathers it and it fits; Ram as a copy (pinned for the
+ * device kernel, or locked for the host gather); Disk in the container, read by the host gather.
+ * Each tier is refused where no kernel reads it. Auto takes the first that fits, in that order.
+ * The card test: the fixed weights plus a KV pool for one --max-model-len sequence (`kv_floor`).
+ * The RAM test: lockable_room after the pools still to be allocated. */
 int Engine::resolve_table_placement(const std::vector& facts,
                                     const std::vector& emb_bytes,
-                                    const std::vector& tower_bytes, int64_t kv_floor,
-                                    int64_t ngram_bytes, bool ngram_device, bool ngram_host) {
+                                    const std::vector& wfs, int64_t kv_floor,
+                                    int64_t ngram_bytes, bool ngram_device, bool ngram_host,
+                                    int64_t host_late) {
     const int64_t MiB = (int64_t)1 << 20;
     int64_t emb_max = 0;
     for (int64_t b : emb_bytes) emb_max = std::max(emb_max, b);
@@ -504,12 +427,11 @@ int Engine::resolve_table_placement(const std::vector& facts,
     TablePlacement emb = cfg_.embedding_placement;
     const bool emb_asked = cfg_.embedding_placement_given;
     std::string emb_why;
-    /* THE HOST MEMORY THE TABLE WOULD PIN, every rank its own shard, after the pools and the prefix
-     * cache's host tier still to be allocated: lockable_room's test, without the memlock limit,
-     * which a pin the cards read is not charged to. */
+    /* Host memory the table would pin (each rank its shard) after the pools and the prefix cache's
+     * host tier still to be allocated; no memlock check, since card-read pins are not charged. */
     const int64_t emb_pin = (int64_t)cfg_.tp * align_up(emb_max, (int64_t)MiB);
     const int64_t pools_still = (int64_t)cfg_.tp * cfg_.host_pool_mib * MiB +
-                                cfg_.prefix_cache_mib * MiB;
+                                cfg_.prefix_cache_mib * MiB + host_late;
     std::string emb_room_why;
     auto emb_room = [&]() { return lockable_room(emb_pin, pools_still, false, &emb_room_why); };
     if (emb_max == 0) {
@@ -543,10 +465,13 @@ int Engine::resolve_table_placement(const std::vector& facts,
     cfg_.embedding_resolved = emb;
     cfg_.embedding_host_mib = emb == TablePlacement::Ram ? align_up(emb_max, MiB) / MiB : 0;
 
-    /* THE ENCODER TOWERS: on the card unless ram was named, and then pinned beside the pool or the
-     * server stops -- the flag has no default to give way to. Every rank pins a whole tower: an
-     * encoder is not sharded. Decided before the n-gram table, whose card test needs the statics
-     * as they will be and whose RAM test the pools still to be allocated. */
+    /* Encoder towers: on the card unless ram was named; then pinned or the server stops. Every rank
+     * pins a whole tower (encoders are not sharded). Decided before the n-gram table, whose tests
+     * need the final statics and the pools still to be allocated. A rank's tower bytes leave out
+     * the lookup tables the embedding pins (tower_pin_bytes); the pin, the card test below and
+     * the split in Engine::plan all read that figure. */
+    std::vector tower_bytes;
+    for (const WeightFootprint& wf : wfs) tower_bytes.push_back(tower_pin_bytes(wf, emb));
     int64_t tower_max = 0;
     for (int64_t b : tower_bytes) tower_max = std::max(tower_max, b);
     const TablePlacement tw = cfg_.tower_placement;
@@ -575,13 +500,10 @@ int Engine::resolve_table_placement(const std::vector& facts,
 
     TablePlacement ng = cfg_.ngram_placement;
     std::string ng_why;
-    /* THE FASTEST TIER WITH THE ROOM, the card first: the table on the card, every rank holding
-     * all of it (a lookup is not sharded), with the fixed weights and a KV pool for one
-     * --max-model-len sequence beside it; then a copy in RAM -- pinned
-     * for a device kernel to read over the link, or locked for the host gather; then the
-     * container, which only the host gather reads. Each is open only where a kernel reads it. */
+    /* The fastest tier with room: the card (every rank holds the whole table), then a RAM copy,
+     * then the container. */
     const int64_t still = (int64_t)cfg_.tp * cfg_.host_pool_total_mib() * MiB +
-                          cfg_.prefix_cache_mib * MiB;
+                          cfg_.prefix_cache_mib * MiB + host_late;
     const int64_t need = align_up(ngram_bytes, (int64_t)2 << 20);
     const char* copy = ngram_device ? "a pinned copy the card reads" : "a locked copy";
     auto card_holds = [&](std::string* why) {
@@ -594,13 +516,13 @@ int Engine::resolve_table_placement(const std::vector& facts,
             if (tw == TablePlacement::Ram) f.statics -= tower_bytes[i];
             fixed = std::max(fixed, f.statics);
         }
-        /* `fixed` and not the trial's own statics: the split clamps those to what the card can give
-         * and serves on, streaming every expert, so the trial alone cannot say they do not fit. */
+        /* Use `fixed`, not the trial's statics: the split clamps those to the card and would
+         * stream every expert, so the trial alone cannot report a misfit. */
         VramBudget tb;
         const int st = vram_budget_trial(cfg_, with, &tb);
         const bool over = st == RAD_OK && fixed >= tb.claimable;
-        /* AND THE EXPERTS KEEP A TIER: where the cache lends, those the host pool cannot hold have
-         * only the card, and a table that took their room would leave them nowhere. */
+        /* The experts must keep a tier: when the cache lends, those the host pool cannot hold
+         * have only the card. */
         const bool starved = st == RAD_OK && tb.lends && tb.expert_ceiling > 0 &&
                              tb.experts < tb.expert_floor;
         if (st == RAD_OK && !over && !starved && tb.kv >= kv_floor)
@@ -708,14 +630,13 @@ int Engine::resolve_table_placement(const std::vector& facts,
 }
 
 /* ================================================================== 2. metadata */
-/* The model's metadata ONLY -- architecture id, dimensions, quantisation, vocab. Not the weights:
- * which weights exist is the architecture plugin's answer, not the container's, and reading them
- * before declare would be reading them before we know what they are for. */
+/* The model's metadata only: architecture id, dimensions, quantisation, vocab. Which weights exist
+ * is the architecture plugin's answer at declare, not the container's. */
 namespace {
 
-/* A CONTAINER IS A FILE THAT SAYS SO: its first four bytes are the magic. Anything else --
- * a checkpoint directory, a .safetensors, an index, a .gguf -- is a checkpoint. A .rad that is not
- * one is still opened as a container, so its own reader names what is wrong with it. */
+/* A container is a file starting with the magic; anything else (a checkpoint directory, a
+ * .safetensors, an index, a .gguf) is a checkpoint. A .rad path is always opened as a container,
+ * so its reader reports what is wrong with it. */
 bool is_container(const std::string& path) {
     if (path.size() > 4 && path.compare(path.size() - 4, 4, ".rad") == 0) return true;
     FILE* f = std::fopen(path.c_str(), "rb");
@@ -747,24 +668,14 @@ int Engine::read_metadata() {
     auto geti = [&](const char* k, int64_t d) { int64_t v = d; file_->get_i(k, &v); return v; };
     auto getf = [&](const char* k, double d) { double v = d; file_->get_f(k, &v); return (float)v; };
 
-    /* THE KEYS ARE RadModelMeta'S OWN FIELD NAMES, because that is what rad-convert writes and
-     * what rad-kbench and rad-tune read. Reading GGUF's spellings instead -- `block_count`,
-     * `embedding_length`, `attention.head_count` -- yields zero for every dimension, since no
-     * writer in this project produces them; declare then refuses with "invalid argument" while
-     * rad-info prints the correct shape off the same file.
-     *
-     * The GGUF names are NOT accepted as a fallback. A container carries these because
-     * rad-convert normalises whatever it read -- safetensors or GGUF -- into RadModelMeta before
-     * writing, so a file that lacks them is a file no version of this project wrote, and reading
-     * it as if the absent keys were zeros turns a bad container into a wrong model instead of a
-     * refusal. */
+    /* Keys are RadModelMeta's field names, which rad-convert writes (normalising safetensors or
+     * GGUF input) and rad-kbench and rad-tune read. GGUF spellings (`block_count`, ...) are not a
+     * fallback: a file lacking these keys was not written by rad-convert and is refused below. */
     meta_.n_layers        = geti("n_layers", 0);
     meta_.n_embd          = geti("n_embd", 0);
     meta_.n_head          = geti("n_head", 0);
     meta_.n_head_kv       = geti("n_head_kv", 0);
-    /* Read head_dim; do NOT derive it. A model may declare a head_dim that is not n_embd/n_head,
-     * and a derived one then makes every downstream shape silently wrong
-     * (docs/ARCHITECTURES.md). */
+    /* Read head_dim, never derive it: it need not equal n_embd/n_head (docs/ARCHITECTURES.md). */
     meta_.head_dim        = geti("head_dim", 0);
     meta_.n_ff            = geti("n_ff", 0);
     meta_.n_vocab         = geti("n_vocab", 0);
@@ -774,12 +685,11 @@ int Engine::read_metadata() {
     meta_.n_expert_shared = geti("n_expert_shared", 0);
     meta_.rms_eps         = getf("rms_eps", 1e-6);
     meta_.rope_theta      = getf("rope_theta", 10000.0);
-    /* 1 (abi/rad_builder.h): the rotary's scaling is read with its type from the free-form keys.
-     * An older container's `rope_scale` key holds the factor alone and is not read. */
+    /* 1 (abi/rad_builder.h): rotary scaling and its type come from the free-form keys. A
+     * `rope_scale` key (the factor alone) is not read. */
     meta_.rope_scale      = 1.0f;
 
-    /* A container that says nothing about its own shape is refused HERE, by name, rather than at
-     * declare as an "invalid argument" from a plugin that was handed zeros. */
+    /* Refuse a container with no dimensions here, by name, rather than at declare. */
     if (meta_.n_layers <= 0 || meta_.n_embd <= 0 || meta_.n_head <= 0 || meta_.n_vocab <= 0) {
         RAD_ERR("%s carries no model dimensions (n_layers=%lld n_embd=%lld n_head=%lld "
                 "n_vocab=%lld). A .rad written by rad-convert always does; rad-info prints what "
@@ -788,8 +698,8 @@ int Engine::read_metadata() {
         return RAD_E_FORMAT;
     }
 
-    /* Everything the struct does not name, verbatim, for the plugin to read. The vectors own the
-     * storage because RadModelMeta holds bare pointers. */
+    /* All other keys verbatim for the plugin. The vectors own the storage; RadModelMeta holds
+     * bare pointers. */
     meta_kv_k_.clear(); meta_kv_v_.clear();
     for (int64_t i = 0; i < file_->meta_count(); ++i) {
         const RadFileKV& kv = file_->meta_at(i);
@@ -815,10 +725,9 @@ int Engine::read_metadata() {
     return RAD_OK;
 }
 
-/* A CHECKPOINT SERVED DIRECTLY (spec §4.3): its config.json -- or the GGUF header -- is the
- * metadata, read the way rad-convert reads it, and its tensors are the weights. Only an encoding
- * served as it stands is answered to declare (CheckpointSources), so a checkpoint whose served
- * form needs quantisation is refused by name after declare, with the container as the remedy. */
+/* A checkpoint served directly (spec §4.3): config.json or the GGUF header is the metadata, read
+ * as rad-convert reads it, and its tensors are the weights. Only encodings served as stored are
+ * answered (CheckpointSources); weights needing quantisation are refused after declare. */
 int Engine::read_checkpoint_metadata() {
     ckpt_ = std::make_unique();
     RAD_TRY(ckpt_->open(cfg_.model));
@@ -849,11 +758,10 @@ int Engine::read_checkpoint_metadata() {
     return RAD_OK;
 }
 
-/* --rope-scaling (format/rope_override.h): YaRN written into the container's own rotary keys at
- * load, where the architecture's reader takes them, so an existing container serves past its
- * trained context with no reconvert -- and is checked by the same reader a converted one is. The
- * drafter, when there is one, gets the same factor over its own trained length. Then one line says
- * what the rotary is, and a context past what it covers is named. */
+/* --rope-scaling (format/rope_override.h): write YaRN into the container's rotary keys at load,
+ * where the architecture's reader takes them, so a container serves past its trained context
+ * without reconversion. A drafter gets the same factor over its own trained length. Then log the
+ * rotary and warn if the context exceeds its reach. */
 int Engine::apply_rope_scaling() {
     RopeSpec spec;
     if (!rope_spec_parse(cfg_.rope_scaling.c_str(), &spec)) {
@@ -905,8 +813,11 @@ int Engine::load_plugins() {
                                    meta_.arch_id, meta_.quant ? meta_.quant : "", &plugins_,
                                    ckpt_ && ckpt_->imports() != Checkpoint::Import::None);
     if (s < 0) {
-        /* rad_tools_load_plugins has said why -- a plugin refused, or no architecture plugin for
-         * this model -- each by name. What it does not know is that this was the engine's start. */
+        /* rad_tools_load_plugins already logged why. A checkpoint whose quantisation the import
+         * refused keeps the tool's descriptor, which no plugin claims; the refusal is the reason. */
+        if (ckpt_ && !ckpt_->import_refusal().empty() && plugins_.arch_plugin.empty())
+            RAD_ERR("quantisation '%s' cannot be imported: %s", meta_.quant ? meta_.quant : "",
+                    ckpt_->import_refusal().c_str());
         RAD_ERR("the plugins under %s did not load (above)", cfg_.radiance_home.c_str());
         return s;
     }
@@ -925,47 +836,26 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const {
     bc.max_ctx    = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train;
     bc.max_spec   = cfg_.n_spec;
     bc.tp_wire_lossy = cfg_.tp_wire_exact ? 0 : 1;
-    /* One answer to "is the cache fp8", for every architecture. The engine always states it;
-     * RAD_DT_INVALID stays meaningful in the ABI for an out-of-tree caller that leaves the field
-     * zero, and means the plugin's own default. */
+    /* The engine always states the KV dtype. RAD_DT_INVALID (zero) remains valid in the ABI for
+     * other callers and means the plugin's default. */
     bc.kv_dtype = cfg_.kv_cache_dtype == "fp8" ? RAD_F8E4M3 : RAD_BF16;
     bc.tp_wire_min_bytes = cfg_.tp_wire_min_kb * 1024;
     bc.scope      = "";
     bc.max_enc_patches = cfg_.mm_max_patches > 0 ? cfg_.mm_max_patches : 0;
     bc.max_audio_frames = cfg_.mm_audio_frames > 0 ? cfg_.mm_audio_frames : 0;
-    /* A row at every token of the step and the sampler's row a sequence before them
-     * (core/kld.h); the KL mode has no speculation, so a sequence samples one. */
+    /* A row at every token of the step plus the sampler's one row per sequence before them
+     * (core/kld.h); KL mode has no speculation. */
     bc.max_out_rows = cfg_.kld() ? max_tok + cfg_.max_seqs : 0;
+    /* Under --prefill-span every step but a lone prefill is planned at the shared budget
+     * (Scheduler::step), so a wider step is one sequence; 0 without a span. */
+    bc.max_mixed_tok = cfg_.prefill_span > 1 ? std::min(max_tok, prefill_shared_tok(cfg_)) : 0;
     return bc;
 }
 
 int Engine::declare() {
-    /* Declare runs ONCE PER RANK, with rank and world_size in RadBuildCtx, and the plugin declares
-     * dimensions ALREADY DIVIDED. The core does not reason about sharding propagation and does not
-     * insert collectives -- a sharding inference pass is a compiler pass whose failure mode is a
-     * model that produces fluent wrong text on a rank count nobody tested (spec §9).
-     *
-     * EVERY RANK DECLARES AT THE SAME TIME, ON ITS OWN THREAD. That is a requirement and not a
-     * speed-up. Kernel init() runs from here (registry.h says so), and a collective's init is a
-     * RENDEZVOUS: libr4d's all-reduce publishes this rank's peer scratch pointer and then WAITS
-     * for every other rank to publish before it can enable peer access. A serial loop never gets
-     * a second rank there, so the first one times out after 60 seconds and --tp 2 fails startup
-     * with `ar_oneshot_2rank_exact ... called in the wrong phase`. Registry::select() and
-     * init_instance() are already behind one mutex for exactly this, and the arch plugin's
-     * per-rank state is indexed by ctx->rank.
-     *
-     * The device is bound per thread because the backend's current device is thread-local and a
-     * collective's init ALLOCATES on it -- unbound, both ranks would hand each other pointers into
-     * card 0 and the reduce would read its own scratch twice. */
-    /* Resolved HERE and not at argument parsing: it is the PLUGIN that says how deep this
-     * container's drafter goes, and the plugin is not selected until the container is open. Every
-     * consumer of `n_spec` -- buffer sizing, the kernel bands, the scheduler's window -- runs
-     * after this line. The core reads no drafter configuration of its own; rad_arch_probe is the
-     * whole of what it knows. */
-    /* THE KL MODE MEASURES THE TRUNK (core/kld.h). A drafter adds passes that write no scored
-     * row, and a prefix hit would start a document past positions the reference holds, so both
-     * are off -- and an explicit depth is refused rather than dropped, because the operator asked
-     * for something this run will not do. The tower stays off the card: the corpus is text. */
+    /* KL mode measures the trunk (core/kld.h): a drafter writes no scored rows and a prefix hit
+     * would skip positions the reference holds, so both are off, and an explicit depth is refused
+     * rather than ignored. The tower stays off the card; the corpus is text. */
     if (cfg_.kld()) {
         if (cfg_.n_spec > 0) {
             RAD_ERR("--num-speculative-tokens %d: the KL mode scores the trunk's own rows and "
@@ -980,11 +870,10 @@ int Engine::declare() {
             "the KL mode: a prefix hit would start a document past positions the reference holds";
         decide("--no-prefix-cache", "prefix caching off", prefix_off_why_);
     }
-    /* AN IMAGE GENERATOR SIZES THE STEP ITSELF (RadArchProbe::gen_rows): a denoise pass carries an
-     * image's every latent row at once -- twice with guidance -- and a conditioning pass encodes
-     * every reference picture a request may carry. What the operator named is kept; what they did
-     * not is the generator's. A generator samples no tokens, so it drafts none, and a conditioning
-     * is read only by its own request's images, so there is no prefix to cache. */
+    /* An image generator sizes the step itself (RadArchProbe::gen_rows): a denoise pass carries all
+     * of an image's latent rows (twice with guidance), and a conditioning pass encodes every
+     * reference picture of a request. Operator-given values are kept. No drafting (no tokens) and
+     * no prefix cache (a conditioning is read only by its own request). */
     {
         RadArchProbe pb{};
         (void)rad_tools_probe(plugins_, meta_, &pb);
@@ -1014,6 +903,10 @@ int Engine::declare() {
             cfg_.prefix_cache = false;
         }
     }
+    /* Resolved here, not at argument parsing: the plugin states its drafter's depth, and it is
+     * selected only once the container is open. Every consumer of `n_spec` (buffer sizing, kernel
+     * bands, the scheduler's window) runs after this. rad_arch_probe is the core's only source of
+     * drafter configuration. */
     if (cfg_.n_spec < 0) {
         RadArchProbe pb{};
         (void)rad_tools_probe(plugins_, meta_, &pb);
@@ -1027,14 +920,8 @@ int Engine::declare() {
                cfg_.n_spec > 0 ? "the depth the drafter in this container states as its operating point"
                                : "this container carries no draft head");
     }
-    /* THE ENCODER'S PASS SIZE, resolved the same way and for the same reason: whether there is a
-     * tower to size is a property of the model file. A container says so (`radiance.encoder`,
-     * written when its weights went in); a checkpoint served directly is the release itself, so a
-     * vision_config is a tower whose weights are in it. 16384 patches is a 2048 x 2048 image, the
-     * largest one pass takes; the reference processor allows sixteen times that area, which would
-     * need an activation region sixteen times as large on every card for one picture. */
-    /* THE AUDIO ENCODER'S PASS: the plugin's longest clip, when the model file carries an audio
-     * encoder (`radiance.encoder` names one) and the deployment did not ask for text only. */
+    /* The audio encoder's pass: the plugin's longest clip, when the model file carries an audio
+     * encoder (`radiance.encoder` names one) and the deployment is not text-only. */
     if (cfg_.mm_audio_frames < 0) {
         const char* enc = rad_meta_gets(&meta_, "radiance.encoder", "");
         const bool named = enc && std::strstr(enc, "audio") != nullptr;
@@ -1044,6 +931,10 @@ int Engine::declare() {
         cfg_.mm_audio_frames = !text_only && pb.audio_frames > 0 && (named || !file_)
                                    ? pb.audio_frames : 0;
     }
+    /* The vision encoder's pass size. A container records its tower in `radiance.encoder` (written
+     * when the tower's weights went in); a checkpoint served directly has one if it has a
+     * vision_config. 16384 patches is a 2048 x 2048 image; the reference processor allows 16x that
+     * area, which would need 16x the activation memory on every card. */
     if (cfg_.mm_max_patches < 0) {
         const char* enc = rad_meta_gets(&meta_, "radiance.encoder", "");
         const bool tower = rad_meta_geti(&meta_, "vision_config.patch_size", 0) > 0;
@@ -1065,6 +956,13 @@ int Engine::declare() {
                        : "the model carries no vision tower");
     }
 
+    /* Declare once per rank (rank and world_size in RadBuildCtx; the plugin declares dimensions
+     * already divided, spec §9), every rank concurrently on its own thread. Concurrency is
+     * required: kernel init() runs during declare, and a collective's init is a rendezvous
+     * (libr4d's all-reduce publishes its peer scratch pointer and waits for every other rank), so
+     * a serial loop times out. Registry::select() and init_instance() share a mutex for this. Each
+     * thread binds its device first, because the current device is thread-local and the init
+     * allocates on it. */
     std::vector         st(ranks_.size(), RAD_OK);
     std::vector th;
     th.reserve(ranks_.size());
@@ -1086,9 +984,8 @@ int Engine::declare() {
                                                nullptr, sources());
         });
     }
-    /* A message is a step's rows of the residual stream in bf16, so the floor is a ROW COUNT: a
-     * decode step's rows are its sequences times one plus the speculative depth, and concurrency
-     * alone decides whether a decode step is under it. */
+    /* A message is a step's bf16 residual rows, so the floor is a row count: a decode step has
+     * sequences x (1 + speculative depth) rows. */
     if (cfg_.tp > 1 && !cfg_.tp_wire_exact) {
         const int64_t row_bytes = meta_.n_embd > 0 ? meta_.n_embd * 2 : 1;
         const int64_t exact_rows = (cfg_.tp_wire_min_kb * 1024 + row_bytes - 1) / row_bytes - 1;
@@ -1104,14 +1001,9 @@ int Engine::declare() {
 
     for (auto& t : th) t.join();
 
-    /* This phase ALWAYS completes: if anything failed to resolve, the FULL list is reported at
-     * the end rather than the first failure at the top (spec §1 step 4). Reported after the join
-     * and in rank order -- two ranks printing their lists concurrently interleaves them into one
-     * that reads like neither.
-     *
-     * ONCE FOR EVERY RANK THAT AGREES, which is normally all of them: each rank declares the same
-     * model against the same registry, so N ranks produce N identical copies of the same list. A
-     * rank whose report differs is itself worth seeing, and gets its own. */
+    /* Declare always completes and reports the full miss list (spec §1 step 4), after the join and
+     * in rank order so lists do not interleave. Printed once when all ranks agree (the normal
+     * case); a rank that differs gets its own report. */
     {
         std::vector rep;
         for (auto& r : ranks_) rep.push_back(miss_report(r->program, device_is_host()));
@@ -1130,12 +1022,9 @@ int Engine::declare() {
             if (!rep[i].host_only.empty()) RAD_INFO("%s", rep[i].host_only.c_str());
             if (!rep[i].host.empty()) RAD_INFO("%s", rep[i].host.c_str());
         }
-        /* A HOLE IS A REFUSAL HERE, not an error the first request finds. Every band is one a
-         * request can land in -- the bands are cut from the limits this run was started with --
-         * and the step that lands in one fails at issue and takes the engine down with it. A
-         * kernel library that serves the op (--kernels), or a model whose geometry the installed
-         * one covers, is the remedy; serving until then is not. --debug-graph serves nothing, so
-         * it goes on to print the graph the holes are in, and its exit status says they are there
+        /* A hole refuses startup: the bands come from this run's limits, so a request can land in
+         * one, and that step would fail at issue and stop the engine. --debug-graph serves nothing,
+         * so it continues to print the graph and reports the holes in its exit status
          * (Engine::dump). */
         for (const MissReport& m : rep)
             if (!m.device.empty() && !cfg_.debug_graph) {
@@ -1148,8 +1037,8 @@ int Engine::declare() {
                 return RAD_E_UNSUPPORTED;
             }
     }
-    /* A CHECKPOINT WEIGHT THAT IS NOT SERVED AS IT STANDS was declared as plain and nothing can
-     * load it: every one is named, with the remedy, whatever declare made of the rest. */
+    /* Checkpoint weights that cannot be served as stored cannot be loaded; name them all with the
+     * remedy. */
     if (ckpt_src_) {
         const std::vector no = ckpt_src_->refused();
         if (!no.empty()) {
@@ -1167,24 +1056,16 @@ int Engine::declare() {
              ranks_[0]->program.ops.size() - 1, ranks_[0]->program.weights.size() - 1,
              ranks_[0]->program.buffers.size() - 1, ranks_[0]->program.kv_groups.size());
 
-    /* IS THERE A DRAFT HEAD, AND WHAT SHAPE IS IT? The plugin declared it (rad_declare_drafter)
-     * or it did not, and that is the whole of the question. There is no flag to read, no metadata
-     * key to re-read and no second place for the two to disagree.
-     *
-     * Sniffing it out instead -- scanning the declared weights for known draft-head names, then
-     * re-reading the metadata keys the plugin already read to build the head -- would put a list
-     * of model names in the core, and a third party's drafter could not then exist without
-     * editing this function. */
+    /* The draft head is exactly what the plugin declared (rad_declare_drafter). The core never
+     * infers one from weight names or metadata, so third-party drafters need no core changes. */
     const Program& p0 = ranks_[0]->program;
     drafter_       = p0.drafter;
     drafter_name_  = p0.drafter_name;
     drafter_.name  = drafter_name_.c_str();
     if (cfg_.n_spec <= 0) drafter_ = RadDrafterDecl{};
     if (drafter_.kind != RAD_DRAFT_NONE) {
-        /* The proposal buffer is a HANDLE the plugin passed, not a name this looked up. Zero is
-         * legal and means the sampler's token buffer -- a head whose logits go through the
-         * ordinary sampler chain, which the bf16 MTP head does and the 2-bit draft head does
-         * not. */
+        /* A zero proposal handle means the sampler's token buffer: the head's logits go through
+         * the ordinary sampler chain. */
         RAD_INFO("speculation: %s",
                  drafter_.kind == RAD_DRAFT_BLOCK
                  ? fmt("'%s' proposes %d token(s) in ONE block pass over %lld row(s) (mask id %d, "
@@ -1201,24 +1082,28 @@ int Engine::declare() {
     return RAD_OK;
 }
 
-/* THE ACTIVATION ARENA'S SMALLER LEVELS, sized by the plugin itself.
+/* The mebibyte between a level's highest buffer and the memory above it, which is lent or holds
+ * the stager's ring: what a kernel writes past the rows it was given lands there rather than in
+ * an expert's weights. */
+static constexpr int64_t kArenaGuard = 1ll << 20;
+
+/* The activation arena's smaller levels, sized by the plugin itself.
  *
- * Every activation is declared for the largest step, and a decode step is a few dozen rows of the
- * 2048 a prefill chunk carries: most of the arena sits unread for as long as nothing prefills. The
- * plugin is asked to declare again at a smaller step (RadBuildCtx::shape_probe) -- its own shape
- * rules are the only ones that know how each buffer scales, so no rule here second-guesses them --
- * and each answer that describes the same buffers with only their rows smaller becomes a level:
- * the same fixed region, the transients packed lower, and the arena above them free while the
- * steps are that small.
+ * Activations are declared for the largest step, but a decode step uses a few dozen of a prefill
+ * chunk's rows, leaving most of the arena idle. The plugin declares again at smaller step sizes
+ * (RadBuildCtx::shape_probe), since only its shape rules know how each buffer scales; each answer
+ * with the same buffers and fewer rows becomes a level: same fixed region, transients packed lower,
+ * the arena above them free while steps stay that small.
  *
- * THE SMALLEST LEVEL IS 256 ROWS AT LEAST. A kernel that computes whole tiles may write the
- * padding rows of its last one; at the real size those land inside the buffer because the chunk is
- * a multiple of every tile, and a level is held to the same property so that padding never reaches
- * the next buffer or the memory past the level's end. Each level above is four times the one
- * below, up to the chunk.
+ * The smallest level is at least 256 rows. A tiled kernel may write padding rows of its last tile;
+ * the real size is a multiple of every tile, and levels keep that property so padding never
+ * reaches the next buffer or past the level's end. Each level is 4x the one below, up to the chunk.
  *
- * A refusal costs a level and nothing else: the arena is lent from the levels that were accepted,
- * or not at all. */
+ * Under --prefill-span there is one level more, at the shared budget (prefill_shared_tok). The
+ * full plan is sized for a spanned step, which only a prefill alone in its step takes; every other
+ * step is at most the shared size, and at this level the span's extra rows are lent.
+ *
+ * A refused level is simply dropped. */
 void Engine::probe_arena_levels() {
     for (auto& r : ranks_) r->arena_levels.clear();
     RadArchProbe pb{};
@@ -1234,9 +1119,16 @@ void Engine::probe_arena_levels() {
     lo = std::max(lo, 256);
     std::vector want;
     for (int64_t R = lo; R < cfg_.max_tok; R *= 4) want.push_back(R);
+    arena_span_rows_ = 0;
+    const int64_t span_rows = cfg_.prefill_span > 1 ? prefill_shared_tok(cfg_) : 0;
+    if (span_rows >= lo && span_rows < cfg_.max_tok &&
+        std::find(want.begin(), want.end(), span_rows) == want.end()) {
+        want.push_back(span_rows);
+        std::sort(want.begin(), want.end());
+    }
 
-    /* One sizing declare a (level, rank), all of them side by side: a sizing declare selects and
-     * initialises nothing, so they share no state, and each is a whole declare of the model. */
+    /* One sizing declare per (level, rank), all in parallel: they select and initialise nothing,
+     * so they share no state. */
     const size_t nl = want.size(), nr = ranks_.size();
     std::vector  got(nl * nr);
     std::vector why(nl * nr);
@@ -1282,6 +1174,7 @@ void Engine::probe_arena_levels() {
         }
         for (size_t i = 0; i < nr; ++i)
             ranks_[i]->arena_levels.push_back(std::move(got[l * nr + i]));
+        if (R == span_rows) arena_span_rows_ = R;
         said += fmt("%s%lld tokens use %s", said.empty() ? "" : ", ", (long long)R,
                     humanb(ranks_[0]->arena_levels.back().end).c_str());
     }
@@ -1294,37 +1187,34 @@ void Engine::probe_arena_levels() {
 
 /* ================================================================== 5. plan */
 int Engine::plan() {
-    /* THE BUDGET IS RESOLVED ONCE, FOR EVERY RANK, BEFORE ANY RANK ALLOCATES.
+    /* The budget is resolved once, for every rank, before any rank allocates. vram_budget_resolve
+     * folds the smallest capacity with the largest program so one split fits every card, and
+     * writes it into Config; per-rank resolution would let rank 1 measure a card rank 0 already
+     * filled.
      *
-     * It has to happen here and not inside the per-rank loop below for two reasons. One card's
-     * answer is not another's -- the fold in vram_budget_resolve takes the smallest capacity and
-     * the largest program so that one split fits every card it is applied to -- and the answer is
-     * written back into Config, which the loop then reads. Doing it per rank would let rank 1
-     * re-resolve against a card rank 0 has already filled.
-     *
-     * Every input is available by now and not before: declare() has run, so the buffer plan exists
-     * and the arena can be sized; every kernel plugin's init has run, so the code objects are
-     * resident and the free-VRAM reading is the steady-state one; and the KV groups are declared,
-     * so a full cache's cost is computable. */
+     * All inputs exist by now: declare() has run (buffer plan, KV groups), and every kernel init
+     * has run, so code objects are resident and free VRAM is the steady-state reading. */
     {
         std::vector facts;
         facts.reserve(ranks_.size());
         late_step_bytes_ = late_lazy_bytes_ = 0;
-        /* The placement flags' tables, per rank where they are sharded (the embedding) and once
-         * where they are not (the n-gram table every rank reads from the one mapping). */
-        std::vector emb_bytes, tower_bytes;
+        /* The lookup tables' sizes: per rank where sharded (the embedding; the towers are read
+         * from `wfs`), once where not (the n-gram table, read by every rank from one mapping). */
+        std::vector emb_bytes;
         std::vector wfs;
         int64_t ngram_bytes = 0, kv_floor = 0;
+        /* One checkpoint slot (every rank's shard) and the ranks' host activation arenas: pinned
+         * after the tables are placed, outside every pool. */
+        int64_t ck_slot = 0, host_arenas = 0;
         bool ngram_device = false, ngram_host = false;
         const int64_t ctx = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train;
         for (auto& r : ranks_) {
             RAD_TRY(rad_dev_set(r->device));
             VramFacts f{};
-            /* ONE HARDWARE QUEUE'S VRAM, MEASURED BY MAKING TWO. The engine's compute stream,
-             * its mover's and a second compute lane are all made after this reading, and the
-             * driver backs each queue with VRAM the ring alone does not account for. The second
-             * queue is the unit, so a runtime that sets itself up on its first queue charges that
-             * once and to `already held`, which is read after both are gone. */
+            /* One hardware queue's VRAM, measured as the difference between creating the first and
+             * the second queue (the runtime's one-time setup lands on the first, and is charged to
+             * `already held`). The compute stream, the mover's and a second lane are created after
+             * this reading, and the driver backs each with VRAM beyond its ring. */
             {
                 RadStream q[2] = { nullptr, nullptr };
                 RadDeviceProps a{}, b{};
@@ -1334,57 +1224,49 @@ int Engine::plan() {
                 for (RadStream s : q) if (s) rad_stream_destroy(s);
             }
             f.n_queues = 2 + (r->program.scratch_regions > 1 ? 1 : 0);
-            /* THE EXPERT PREFETCH'S STREAM, RING AND BUFFERS, where it can be on: a placement that
-             * keeps experts in a pinned pool, not --deterministic, on a backend with a DMA engine to
-             * spare for it (asked before the free figure below, so its queue there is already held). */
-            WeightFootprint xwf;
-            weight_footprint(r->program, &xwf, TablePlacement::Vram, TablePlacement::Disk, device_is_host(),
-                             file_ != nullptr);
-            if (xwf.routed && xwf.expert_unit_max > 0 && !cfg_.deterministic &&
+            /* The weights' cost, split into the fixed floor and the elastic plane
+             * (weight_footprint in core/place/planner.h). Per rank, so already this card's share
+             * under TP. */
+            WeightFootprint wf;
+            weight_footprint(r->program, &wf, TablePlacement::Vram, TablePlacement::Disk,
+                             device_is_host(), file_ != nullptr);
+            /* The expert prefetch's stream, ring and buffers, when it can run: experts in a pinned
+             * pool, not --deterministic, and a spare DMA engine (asked before the free reading
+             * below, so its queue is already counted there). */
+            if (wf.routed && wf.expert_unit_max > 0 && !cfg_.deterministic &&
                 (cfg_.placement == "auto" || cfg_.placement == "expert_tiered") && rad_xp_supported(r->device)) {
-                /* Counted as Ctx::bind_routing counts the routed layers: past the trunk where a head is. */
+                /* Routed layers counted as Ctx::bind_routing does, including a head past the trunk. */
                 int64_t nl = r->program.meta.n_layers;
                 for (const WeightInfo& w : r->program.weights)
                     if (w.decl.group.expert >= 0) nl = std::max(nl, (int64_t)w.decl.group.layer + 1);
                 f.n_queues += 1;
-                f.prefetch = xp_device_bytes(xwf.expert_unit_max, nl);
+                f.prefetch = xp_device_bytes(wf.expert_unit_max, nl);
             }
             RadDeviceProps props{};
             rad_dev_props(r->device, &props);
             f.capacity = props.vram_bytes;
             f.free     = props.vram_free;
-            /* AN EIGHTH OF THE HOST'S MEMORY STAYS THE HOST'S on integrated graphics. The card's
-             * free figure is already bounded by what the host has available (core/device/hip.cpp);
-             * this is the margin the rest of the machine keeps on top of that, because a budget
-             * that spends every available byte leaves the operating system to reclaim its page
-             * cache and then to kill something. */
+            /* On integrated graphics an eighth of host memory stays the host's, on top of the free
+             * figure's own bound (core/device/hip.cpp), so the OS is not driven to reclaim and
+             * kill. */
             if (dev_integrated(r->device)) {
                 const long pages = sysconf(_SC_PHYS_PAGES), page = sysconf(_SC_PAGE_SIZE);
                 if (pages > 0 && page > 0) f.host_reserve = (int64_t)pages * page / 8;
             }
             arena_plan_bytes(r->program, nullptr, &f.arena);
-            /* WHAT THE WEIGHTS WOULD COST, split into the floor and the elastic plane -- see
-             * weight_footprint in core/place/planner.h. Per RANK, which under tensor parallel is
-             * already this card's even share of the static weights: declare ran once per rank
-             * with every dimension divided. */
-            WeightFootprint wf;
-            weight_footprint(r->program, &wf, TablePlacement::Vram, TablePlacement::Disk,
-                             device_is_host(), file_ != nullptr);
             f.statics = wf.statics;
             f.experts = wf.experts;
             wfs.push_back(wf);
-            /* THE CACHE LENDS where units move and the pool can give its blocks back in place. */
+            /* The cache lends where units move and the pool can return blocks in place. */
             f.lends = VMem::supported() && !cfg_.deterministic &&
                       (cfg_.placement == "auto" || cfg_.placement == "expert_tiered");
             emb_bytes.push_back(wf.embedding);
-            tower_bytes.push_back(wf.tower);
             ngram_bytes = std::max(ngram_bytes, wf.ngram);
             ngram_device = ngram_device || wf.ngram_device;
             ngram_host = ngram_host || wf.ngram_host;
-            /* ONE --max-model-len SEQUENCE'S CACHE: the same groups planned for a single
-             * sequence, which is the least a KV pool can hold and still serve every request the
-             * API accepts (configure_kv warns below it). --ngram-placement auto puts the table
-             * on the card only where the pool stays above it. */
+            /* One --max-model-len sequence's cache: the least a KV pool can hold and still serve
+             * every acceptable request (configure_kv warns below it). --ngram-placement auto puts
+             * the table on the card only if the pool stays above it. */
             {
                 Config one = cfg_;
                 one.max_seqs = 1;
@@ -1394,36 +1276,36 @@ int Engine::plan() {
                     f.kv_one = single.ceiling(ctx);
                 }
             }
-            /* THE STAGING REGION IS SIZED ONLY WHERE THE ARENA LENDS ITS TOP: with no smaller level
-             * nothing gives the region back to the slab at decode, and a deterministic plan moves
-             * nothing, so neither can stage or recover what a region would cost. */
+            /* The staging region is sized only where the arena lends its top: without smaller
+             * levels nothing returns it to the slab at decode, and a deterministic plan moves
+             * nothing. */
             if (!r->arena_levels.empty() && !cfg_.deterministic) f.expert_layer_max = wf.expert_layer_max;
-            /* A THROWAWAY MANAGER, because the question is what the groups WOULD cost and the
-             * real one is configured against a pool that does not exist yet. plan_groups touches
-             * no memory and no pool; it is the half of configure() that is pure arithmetic on the
-             * declaration, split out for exactly this caller. */
+            /* A throwaway manager: plan_groups is configure()'s pure-arithmetic half and touches no
+             * memory, and the real pool does not exist yet. */
             KVManager probe;
+            host_arenas += arena_host_bytes(r->program);
             if (probe.plan_groups(r->program.kv_groups, cfg_) == RAD_OK) {
+                ck_slot += probe.checkpoint_bytes();
                 f.kv_ceiling = probe.ceiling(ctx);
                 f.kv_fixed   = probe.fixed_bytes();
             }
-            /* THE STEP BATCH'S DEVICE STAGING, which the scheduler reserves after this split: its
-             * block tables are carved for max_seqs sequences at max_ctx and its media staging for
-             * max_tok encoder rows. The state-index widths are the probe's, as the scheduler takes
-             * them from the configured manager. */
+            /* The step batch's device staging, reserved by the scheduler after this split: block
+             * tables for max_seqs sequences at max_ctx, media staging for max_tok encoder rows.
+             * State-index widths come from the probe, as the scheduler takes them from the
+             * configured manager. */
             KVGeom kg = KVGeom::of(r->program.kv_groups);
             for (size_t i = 0; i < kg.g.size(); ++i) {
                 const int64_t w = probe.state_index_width((int32_t)i);
                 if (w > 0) kg.g[i].sidx_width = w;
             }
-            f.staging = r->program.is_generator() ? gen::Driver::device_bytes(r->program, cfg_)
+            f.staging = r->program.is_generator() ? gen::Driver::device_bytes(r->program)
                                                   : BatchBuilder::device_bytes(r->program, cfg_, kg);
             if (f.staging < 0) return RAD_E_INVAL;
             late_step_bytes_ = std::max(late_step_bytes_, f.staging);
             int64_t lazy = r->program.scratch_regions > 1 ? f.queue_bytes : 0;
-            /* AND THE KV TIERS' COPY STAGING, which TierExec::device_init builds on the first
-             * copy out. Which groups the prefix cache indexes is settled after this split, so
-             * every paged group is counted: the entry it sizes can only be smaller. */
+            /* The KV tiers' copy staging, built by TierExec::device_init on the first copy out.
+             * The cached groups are settled later, so every paged group is counted (an upper
+             * bound). */
             if (cfg_.prefix_cache_mib > 0) {
                 int64_t entry = 0, bs = 0;
                 int ng = 0;
@@ -1441,24 +1323,30 @@ int Engine::plan() {
             late_lazy_bytes_ = std::max(late_lazy_bytes_, lazy);
             facts.push_back(f);
         }
-        /* THE PINNED HOST POOL IS THE EXPERTS' OTHER HOME, less the file tier's staging, which
-         * Planner::plan takes out of it before any expert. The embedding placed in host memory
-         * brings its own room (Config::embedding_host_mib), so it leaves this floor as it is. */
+        /* The pinned host pool is the experts' other home, less the file tier's staging, which
+         * Planner::plan takes first. A host-placed embedding has its own room
+         * (Config::embedding_host_mib). */
         for (size_t i = 0; i < facts.size(); ++i) {
             int64_t room = cfg_.host_pool_mib * ((int64_t)1 << 20);
             if (cfg_.weights_disk_tier)
                 room -= file_stage_reserve(wfs[i].layer_unit_max, wfs[i].routed);
             facts[i].expert_floor = expert_vram_floor(wfs[i], std::max(room, 0));
         }
-        RAD_TRY(resolve_table_placement(facts, emb_bytes, tower_bytes, kv_floor, ngram_bytes,
-                                        ngram_device, ngram_host));
-        /* The n-gram table was counted off the card; on it, it is every rank's whole table. */
+        /* Capped well below overflow, so the sums it joins stay defined: a store that large is
+         * refused by name in configure_kv. */
+        const int64_t ck_n = std::max(cfg_.checkpoint_slots, 0), ck_cap = INT64_MAX / 8;
+        const int64_t ck_store = !cfg_.prefix_cache || ck_slot <= 0 ? 0
+                                 : ck_n > ck_cap / ck_slot ? ck_cap : ck_slot * ck_n;
+        RAD_TRY(resolve_table_placement(facts, emb_bytes, wfs, kv_floor, ngram_bytes,
+                                        ngram_device, ngram_host, ck_store + host_arenas));
+        /* The n-gram table was counted off the card; on it, every rank holds the whole table. */
         if (cfg_.ngram_resolved == TablePlacement::Vram)
             for (VramFacts& f : facts) f.statics += ngram_bytes;
         if (cfg_.embedding_resolved == TablePlacement::Ram)
             for (size_t i = 0; i < facts.size(); ++i) facts[i].statics -= emb_bytes[i];
         if (cfg_.tower_resolved == TablePlacement::Ram)
-            for (size_t i = 0; i < facts.size(); ++i) facts[i].statics -= tower_bytes[i];
+            for (size_t i = 0; i < facts.size(); ++i)
+                facts[i].statics -= tower_pin_bytes(wfs[i], cfg_.embedding_resolved);
         VramBudget vb;
         RAD_TRY(vram_budget_resolve(cfg_, facts, &vb));
         if (!vb.report.empty()) RAD_INFO("%s", vb.report.c_str());
@@ -1466,8 +1354,8 @@ int Engine::plan() {
                fmt("weights %s (experts %s of it), KV cache %s, a card", humanb(vb.weights).c_str(),
                    humanb(vb.experts).c_str(), humanb(vb.kv).c_str()),
                vb.report);
-        /* The staging region the budget took out of the experts, above everything the buffer plan
-         * placed -- so it is at the top of the arena, the part the smaller levels lend. */
+        /* The staging region the budget took from the experts, placed above every planned buffer:
+         * the arena top that smaller levels lend. */
         if (vb.stage > 0)
             for (auto& r : ranks_) {
                 int64_t dev = 0;
@@ -1477,26 +1365,20 @@ int Engine::plan() {
                 r->program.arena_bytes       = r->program.arena_stage_off + vb.stage;
             }
 
-        /* ---- AN UNEVEN WORLD: EACH RANK'S OWN POOLS FOR THE ONE TOKEN COUNT -------------------
+        /* ---- uneven worlds: each rank's own pools for the common token count ------------------
          *
          * The split above is the dearest rank's, applied to every card, and one block table serves
-         * every rank -- configure_kv caps each at the least rank's paged tokens. A rank whose cache
-         * costs less per token (an attention-zero rank keeps no attention cache, only what its
-         * other groups cost) would reserve the common KV pool and page a fraction of it, while its
-         * experts beyond the common weights pool sit in the pinned host pool. So such a rank gets a
-         * KV pool that pages exactly the common token count and the difference in its weights
-         * pool, up to every one of its weights resident. The token count, the carve, the loan and
-         * the dearest ranks' pools are what they were.
+         * every rank (configure_kv caps each at the smallest paged token count). A rank whose cache
+         * costs less per token (an attention-zero rank) would page only part of the common KV pool
+         * while its extra experts sit in host memory. Such a rank gets a KV pool that pages exactly
+         * the common token count, and the difference goes to its weights pool, up to all of its
+         * weights resident. The token count, carve, loan and dearer ranks' pools are unchanged.
          *
-         * Only a split under expert_tiered is re-split: under `auto` a rank whose grown pool covers all of
-         * its weights would choose all_vram while its peers spill -- one strategy per world is the
-         * contract that keeps their movers alike, so `auto` keeps the common split. A cache that
-         * does not lend (--deterministic, or a device without virtual memory management) is
-         * re-split all the same: the bytes it would never page are bytes its experts can hold, and
-         * without virtual memory management they are allocated whole.
-         * Where every rank's cache costs the same per token no rank qualifies and rank_cfg_ is cfg_
-         * on every rank, field for field. A rank that qualifies and is not re-split is named with
-         * the reason, once. */
+         * Only expert_tiered re-splits: under `auto` a grown rank could pick all_vram while its
+         * peers spill, and one strategy per world keeps the movers alike. A cache that does not
+         * lend (--deterministic, or no virtual memory management) is still re-split, since its
+         * unpaged bytes would otherwise be wasted. When all ranks cost the same, rank_cfg_ equals
+         * cfg_. A qualifying rank that is not re-split is logged once with the reason. */
         rank_cfg_.assign(ranks_.size(), cfg_);
         kv_planned_tokens_ = 0;
         constexpr int64_t kMiB = (int64_t)1 << 20;
@@ -1515,9 +1397,9 @@ int Engine::plan() {
             kept = fmt("--placement %s keeps one split for every card; only expert_tiered re-splits",
                        cfg_.placement.c_str());
         } else {
-            /* THE TOKEN COUNT configure_kv WILL SETTLE ON: every rank's paged tokens in the common
-             * pool, the least of them. Asked of the same plan configure_kv makes, against the same
-             * bytes: nothing reserves from a KV pool before its carve. */
+            /* The token count configure_kv will settle on: the least paged token count over ranks in
+             * the common pool, from the same plan and bytes (nothing reserves from a KV pool before
+             * its carve). */
             for (size_t i = 0; i < ranks_.size(); ++i) {
                 probes[i] = std::make_unique();
                 if (probes[i]->plan_groups(ranks_[i]->program.kv_groups, cfg_) != RAD_OK) {
@@ -1540,10 +1422,9 @@ int Engine::plan() {
                 RAD_INFO("%s; its pools stay the common split: %s", costs.c_str(), kept.c_str());
                 continue;
             }
-            /* EXACT, NO MARGIN: paged_split is monotone in the budget, so the least whole MiB that
-             * pages T here pages at least T in configure_kv -- the same plan, the same arithmetic,
-             * a pool whose budget is exactly this many MiB. The pool's own alignment is already
-             * among the plan's fixed costs (a RAD_ALIGN_UNIT a reservation). */
+            /* Exact, no margin: paged_split is monotone in the budget, so the least whole MiB that
+             * pages T here pages at least T in configure_kv (same plan, same arithmetic). The
+             * pool's alignment is already among the plan's fixed costs. */
             const int64_t need = probes[i]->pool_mib_for_tokens(T, cfg_.vram_kv_mib);
             if (need < 0) {
                 RAD_INFO("%s; its pools stay the common split: it does not page the common %lld "
@@ -1579,18 +1460,14 @@ int Engine::plan() {
         /* This rank's own split: cfg_ field for field unless the block above re-split it. */
         const Config& rc = rank_cfg_[ri];
         LogRank lr(r->index);
-        /* THE MAIN THREAD RUNS EVERY RANK'S STARTUP, one rank after another, and every allocator
-         * reachable from here takes the CURRENT device -- rad_dev_alloc has no device argument.
-         * Unbound, rank 1's pools, its weights and its KV cache all land on card 0. That fits by
-         * accident at tp 1 and is silently wrong above it, so each phase binds the rank it is
-         * working on before it allocates anything for it. */
+        /* This thread runs every rank's setup in turn, and rad_dev_alloc uses the current device,
+         * so bind the rank's device before allocating anything for it. */
         RAD_TRY(rad_dev_set(r->device));
         RadDeviceProps props{};
         rad_dev_props(r->device, &props);
 
-        /* Every pool is budgeted explicitly. No profiling pass, no utilisation fraction, no
-         * inference about what the workload will be (spec §6). Pools refuses by name and by how
-         * much rather than shrinking anything. */
+        /* Every pool is budgeted explicitly, with no profiling pass or utilisation fraction
+         * (spec §6). Pools refuses by name and amount rather than shrinking anything. */
         int s = r->pools.configure(rc, props.vram_bytes);
         RAD_INFO("pools:\n%s", r->pools.fit_report().c_str());
         if (s < 0) {
@@ -1598,8 +1475,8 @@ int Engine::plan() {
             return s;
         }
 
-        /* Under tensor parallel the placement unit is a SHARD of a weight, so each rank plans
-         * against its own card's budget (spec §5.3) -- the same split its pools were given. */
+        /* Under TP the placement unit is a weight shard, so each rank plans against its own
+         * card's budget (spec §5.3), the split its pools were given. */
         PlannerInput in{};
         in.program    = &r->program;
         in.config     = &rc;
@@ -1616,7 +1493,7 @@ int Engine::plan() {
         if (cfg_.debug_placement || s < 0)
             fputs(r->plan.report(r->program).c_str(), stderr);
         if (s < 0) return s;
-        /* The slab the planner filled is the pool the mover will fill: one split, read twice. */
+        /* The planner's slab must match the weights pool the mover fills. */
         RAD_TRY(plan_check_weights_pool(r->plan, r->pools.weights().bytes()));
         if (r->index == 0) {
             decide("--placement", strategy_name(r->plan.strategy),
@@ -1634,9 +1511,8 @@ int Engine::plan() {
                              humanb(r->plan.forced_host_used).c_str())
                        : std::string());
         }
-        /* --host-pool-mib IS ONE NUMBER FOR EVERY RANK, allocated whole by Pools::configure, so a
-         * re-split rank whose grown weights pool took every weight still holds it. Said, because
-         * the `kv: rank N ...` line above reads as if that rank's memory were all accounted for. */
+        /* --host-pool-mib is allocated whole on every rank, so a re-split rank whose weights all
+         * fit its grown pool still holds an empty host pool; log it. */
         if (rc.vram_kv_mib < cfg_.vram_kv_mib && cfg_.host_pool_mib > 0 &&
             r->plan.totals.bytes[(int)Tier::HostPinned] == 0)
             RAD_INFO("kv: rank %d's weights all fit its grown weights pool, so its pinned host pool "
@@ -1647,19 +1523,19 @@ int Engine::plan() {
 }
 
 /* ================================================================== 6. load */
-/* Weights are mapped and staged according to the plan. The mover has already reserved every slot
- * and published the address each weight will live at, so this is a fill: for every declared
- * weight, find its entry in the container and copy THIS RANK'S SHARD of it into place.
+/* Weights are filled according to the plan. The mover has already reserved every slot and
+ * published each weight's address, so this copies this rank's shard of each declared weight from
+ * its container entry into place.
  *
- * The container holds whole weights unless it was converted pre-sharded, and the plugin declared
- * dimensions ALREADY DIVIDED (spec §9) -- so the slicing happens here, and it is the only place
- * in the engine that knows a weight is a piece of a larger one. Row sharding is a contiguous
- * range of dim 0. Column sharding is not contiguous and needs a 2D copy, which is exactly why
- * the two are different enum values rather than a bool. */
-/* ONE RUN OF CONTAINER BYTES, AND WHERE THEY GO. Emitted by the walk below, consumed by the
- * sweep; `ny == 1` with `span == wb` is one contiguous range, and everything else is a column
- * share, whose pieces are `wb` bytes every `sp`. A run with `stage >= 0` fills that staged
- * weight's input at `dst` bytes in rather than landing where the weight lives. */
+ * The container holds whole weights (unless converted pre-sharded) and the plugin declared
+ * dimensions already divided (spec §9), so slicing happens here, the only place that knows a
+ * weight is part of a larger one. A row shard is a contiguous range of dim 0; a column shard
+ * needs a 2D copy. */
+
+/* One run of container bytes and its destination, emitted by the walk and consumed by the sweep.
+ * `ny == 1` with `span == wb` is one contiguous range; otherwise a column share of `ny` pieces of
+ * `wb` bytes every `sp`. With `stage >= 0` it fills that staged weight's input at offset `dst`
+ * instead of the weight's home. */
 struct LoadRun {
     int64_t  foff;      /* first container byte the run reads */
     int64_t  span;      /* container bytes it covers, its own internal gaps included */
@@ -1674,24 +1550,20 @@ struct LoadRun {
 
 /* ================================================================== the relayout pool
  *
- * A WEIGHT THE LOADER HAS TO REARRANGE (spec §4.3): the resolved kernel stores something other
- * than the container's canonical planes -- a fragment order, a scale carried in each row's tail --
- * or the declaration widens a bf16 plane to f32. Its share of the planes is read out of the sweep
- * into host memory of its own, and when the last byte of it has arrived a worker produces the
- * stored form: straight into its host pool, or, for VRAM, into memory of its own and up through
- * that worker's pinned bounce buffers.
+ * Weights the loader must rearrange (spec §4.3): the resolved kernel stores something other than
+ * the canonical planes (a fragment order, a per-row scale tail), or the declaration widens bf16 to
+ * f32. The sweep copies the weight's planes into a host input; once all bytes arrive, a worker
+ * produces the stored form, directly into its host pool slot or, for VRAM, through the worker's
+ * pinned bounce buffers.
  *
- * IT HAS TO KEEP PACE WITH THE DISK, because Qwen3.8-27B-FP8 rearranges 24 GiB of its 29 at every
- * load and a single thread scattering bytes into fragment order runs at a fraction of 7 GB/s. So
- * it is a pool, and the sweep only reads: the copies out of its windows -- into a staged input,
- * or into a host pool slot -- are the pool's too, taken before any relayout, because a window
- * cannot be read into again until they are done. On the sweep thread those copies, and the first
- * touch of every fresh input, would run in series with the reads.
+ * It must keep pace with the disk (Qwen3.8-27B-FP8 rearranges 24 GiB of 29 per load; one thread
+ * runs at a fraction of 7 GB/s), so it is a thread pool and the sweep only reads. The copies out
+ * of sweep windows (into staged inputs or host pool slots) are also the pool's, done before any
+ * relayout, because a window cannot be refilled until they finish.
  *
- * AND IT HOLDS A BOUNDED AMOUNT, because a staged input is a copy of the weight in host memory and
- * a model is larger than that memory. A new input waits for room while there is finished work
- * that will free some -- and only then: a weight still arriving cannot be relaid, so waiting on
- * it would wait forever. Past the bound with nothing finished, the input is taken anyway. */
+ * The pool holds a bounded amount, since staged inputs are host copies and a model exceeds host
+ * memory. A new input waits for room only while finished work will free some (an incomplete
+ * weight cannot be relaid, so waiting on it would deadlock); otherwise it is taken anyway. */
 struct StagedWeight {
     const Program* prog = nullptr;
     size_t   wi = 0;
@@ -1704,8 +1576,8 @@ struct StagedWeight {
     bool     reserved = false;  /* its input counts against the pool's budget */
     uint8_t* in = nullptr;      /* its input: in the pool's region, or its own allocation */
     bool     own = false;       /* ...its own, because the region had no hole that size */
-    /* A checkpoint's weight has no sweep: the worker fills its input itself, from the mapped
-     * tensors, before it lays it out -- so the reads run on every worker at once. */
+    /* A checkpoint weight has no sweep: the worker fills its input from the mapped tensors
+     * itself, so reads run on all workers in parallel. */
     std::function fill;
 };
 
@@ -1719,11 +1591,9 @@ public:
         if (region_) ::munmap(region_, (size_t)budget_);
     }
 
-    /* THE INPUTS SHARE ONE REGION THE SIZE OF THE BUDGET, made once and handed out again as each
-     * weight is done with it. Memory made fresh for every input is a page fault every 4 KiB of
-     * it, and over a model's worth of weights those faults are most of the load's CPU time; a
-     * region the workers keep reusing faults once. An input with no hole its size -- larger than
-     * the budget, or the region too cut up -- gets an allocation of its own. */
+    /* Inputs share one budget-sized region, reused as weights finish: fresh memory per input
+     * would page-fault every 4 KiB, which dominates load CPU time. An input with no hole its size
+     * (larger than the budget, or fragmentation) gets its own allocation. */
     void start(int threads, int64_t budget) {
         budget_ = budget;
         void* p = ::mmap(nullptr, (size_t)budget_, PROT_READ | PROT_WRITE,
@@ -1740,10 +1610,9 @@ public:
         for (int t = 0; t < threads; ++t) threads_.emplace_back([this] { worker(); });
     }
 
-    /* The sweep thread: room for a staged weight's input, taken the first time a run reaches it.
-     * ROOM AND NOT MEMORY: the allocation is input()'s, on a worker. An allocation this size is
-     * an mmap, which waits on every munmap and fault the workers are making in the same address
-     * space -- milliseconds an input, and on the sweep thread that is a second of a load. */
+    /* Sweep thread: reserve budget for a staged weight's input when a run first reaches it. Only
+     * the accounting happens here; input() allocates on a worker, because an mmap this size
+     * contends with the workers' munmaps and faults and would stall the sweep. */
     void reserve(int i) {
         StagedWeight& s = items_[(size_t)i];
         if (s.reserved) return;
@@ -1754,7 +1623,7 @@ public:
         s.reserved = true;
     }
 
-    /* `n` more bytes of it are in -- from whichever worker copied them, so under the lock. */
+    /* `n` more bytes of input `i` arrived; called by any worker, so locked. */
     void arrived(int i, int64_t n) {
         std::lock_guard lk(mu_);
         StagedWeight& s = items_[(size_t)i];
@@ -1765,13 +1634,12 @@ public:
         work_.notify_one();
     }
 
-    /* A COPY OUT OF A SWEEP WINDOW: the part of run `q` that lies in file range [j0, j1), out of
-     * window `slot`, whose first byte is file offset `w0`. A staged run lands in its weight's
-     * input, which the sweep has made room for with reserve() first; any other run is a host
-     * destination. */
+    /* A copy out of sweep window `slot` (first byte at file offset `w0`): the part of run `q` in
+     * file range [j0, j1). A staged run lands in its weight's input (reserved first); any other
+     * run has a host destination. */
     struct Copy { const uint8_t* win; int64_t w0, j0, j1; LoadRun q; int slot; };
 
-    /* The sweep thread: how many windows it reads into. */
+    /* Sweep thread: the number of windows it reads into. */
     void windows(int n) {
         std::lock_guard lk(mu_);
         out_.assign((size_t)n, 0);
@@ -1782,8 +1650,8 @@ public:
         copies_.push_back(c);
         work_.notify_one();
     }
-    /* The sweep thread: until no copy out of window `slot` is outstanding. A failed pool still
-     * retires its copies, so this returns either way. */
+    /* Sweep thread: wait until no copy from window `slot` is outstanding. A failed pool still
+     * retires its copies, so this always returns. */
     void drain(int slot) {
         std::unique_lock lk(mu_);
         drained_.wait(lk, [&] { return out_[(size_t)slot] == 0; });
@@ -1803,10 +1671,8 @@ public:
                 rad_stream_destroy(uplinks_[(size_t)d].st);
                 uplinks_[(size_t)d].st = nullptr;
             }
-        /* EVERY STAGED WEIGHT MUST HAVE BEEN DELIVERED. One nothing arrived for was never laid out
-         * and its slot holds whatever the card had there: zeros on a card whose freed memory the
-         * driver wipes, which is how such a slot serves for months unnoticed, and garbage on one
-         * that has just been through a reset. Refusing here is what makes the hole visible. */
+        /* Every staged weight must have been delivered; otherwise its slot holds whatever memory
+         * held before (often zeros, so the bug can go unnoticed). */
         if (status_ == RAD_OK && !audited_) {
             audited_ = true;
             int64_t undelivered = 0;
@@ -1831,32 +1697,30 @@ public:
     int64_t peak() const { return peak_; }
 
 private:
-    /* ONE STREAM A CARD FOR EVERY WORKER'S COPIES. A stream is a hardware queue of its own on
-     * this backend, and a stream a worker a card made some twenty queues a card, which the card
-     * time-slices: the workers spent three quarters of a Flash-Next load waiting on their copies.
-     * One link copy fills the link by itself, so one queue a card loses nothing; the workers take
-     * turns putting their copies on it. */
+    /* One stream per card shared by all workers. Each stream is a hardware queue on this backend,
+     * and a stream per worker per card means ~20 time-sliced queues per card (workers spent three
+     * quarters of a Flash-Next load waiting). One copy already saturates the link. */
     struct Uplink {
         std::mutex mu;
         RadStream  st = nullptr;
     };
 
-    /* A worker's way onto a card: a ring of pinned slots. A weight that fits one is laid out
-     * straight into it, and a larger one goes up a slot's worth at a time; each slot is waited
-     * for when the ring comes back round to it, not after every copy. */
+    /* A worker's path to a card: a ring of pinned slots. A weight that fits is laid out directly
+     * into a slot, a larger one goes up a slot at a time; a slot is waited for only when the ring
+     * wraps back to it. */
     struct Bounce {
         static constexpr int     kSlots = 8;
         static constexpr int64_t kSlot  = 4ll << 20;
         explicit Bounce(Uplink* up) : up_(up) {}
         Uplink* up_;
         void* buf = nullptr;
-        /* THE RELAYOUT'S OUTPUT for a weight larger than a slot, kept from one weight to the next
-         * up to kKeep -- the same page faults as the inputs' region saves, and a worker's own. */
+        /* Relayout output for weights larger than a slot, reused across weights up to kKeep to
+         * avoid page faults. */
         static constexpr int64_t kKeep = 256ll << 20;
         std::unique_ptr out;
         int64_t out_cap = 0;
-        /* An event a device, since an event belongs to the device it was made on; `live` is the
-         * device the slot's last copy went to. */
+        /* One event per device (an event belongs to its device); `live` is the device of the
+         * slot's last copy. */
         struct Slot { std::vector ev; int live = -1; };
         Slot slot[kSlots];
         int  next = 0;
@@ -1961,14 +1825,14 @@ private:
             if (st < 0 && !failed_) { failed_ = true; status_ = st; }
             room_.notify_all();
         }
-        /* Its copies are still in flight: finish() returns once every worker's have landed. */
+        /* Wait for this worker's copies still in flight. */
         const int fs = b.flush();
         std::lock_guard lk(mu_);
         if (fs < 0 && !failed_) { failed_ = true; status_ = fs; }
     }
 
-    /* A staged weight's input, made by the first worker that needs it: the first copy into it, or
-     * the job that fills it from a checkpoint. The first hole that holds it. */
+    /* A staged weight's input, created once by the first worker to need it, in the first region
+     * hole that fits. */
     uint8_t* input(int i) {
         StagedWeight& s = items_[(size_t)i];
         std::call_once(once_[(size_t)i], [&] {
@@ -1989,8 +1853,7 @@ private:
         return s.in;
     }
 
-    /* Under the lock: [off, off + n) of the region is free again, merged with the holes either
-     * side of it. */
+    /* Under the lock: free [off, off + n) of the region, merging with adjacent holes. */
     void give_back(int64_t off, int64_t n) {
         auto next = holes_.lower_bound(off);
         if (next != holes_.end() && off + n == next->first) {
@@ -2004,8 +1867,8 @@ private:
         holes_[off] = n;
     }
 
-    /* One piece after another of the run, each the part of it the job's range holds: dense in
-     * the destination, a row of a column share at a time. */
+    /* Copy each piece of the run that falls in the copy's file range: dense in the destination,
+     * one row of a column share at a time. */
     void take(const Copy& c) {
         const LoadRun& q = c.q;
         uint8_t* base = q.stage >= 0 ? input(q.stage) + (intptr_t)q.dst : q.dst;
@@ -2028,7 +1891,7 @@ private:
             const int fs = s.fill(s.in);
             if (fs < 0) return fs;
         }
-        /* STORED AS IT IS, which only a weight with no sweep reaches: its share goes up as read. */
+        /* Stored as read (only reached by a weight with no sweep). */
         if (w.identity && !w.widen) {
             const int64_t n = w.stored_bytes;
             if (!s.dev) { std::memcpy(s.dst, s.in, (size_t)n); return RAD_OK; }
@@ -2058,7 +1921,7 @@ private:
         int st = RAD_OK;
         const char* who = "the loader";
         if (w.widen) {
-            /* EXACT: every bf16 and f16 value is an f32. */
+            /* Exact: every bf16 and f16 value is representable in f32. */
             const int64_t cnt = w.sel_rows[0] * w.sel_cols[0];
             if (cnt * 4 != n) st = RAD_E_SHAPE;
             else for (int64_t e = 0; e < cnt; ++e) ((float*)out)[e] = rad_load_f32(pt[0].data, pt[0].dtype, e);
@@ -2086,7 +1949,7 @@ private:
     }
 
     std::vector& items_;
-    std::unique_ptr once_;   /* one an item: its input is made once */
+    std::unique_ptr once_;   /* per item: its input is made once */
     std::unique_ptr  uplinks_;       /* indexed by device */
     int                        n_uplinks_ = 0;
     static constexpr int64_t kHole = 4096;     /* every input starts on a page of its own */
@@ -2105,45 +1968,36 @@ private:
     int status_ = RAD_OK;
 };
 
-/* THE ONE PASS OVER THE CONTAINER, SERVING EVERY RANK.
+/* One pass over the container, serving every rank. The runs (declaration order, grouped by rank)
+ * are sorted by file offset into one front-to-back sweep: read a window, hand it to every rank
+ * that wants a piece, move on.
  *
- * The runs arrive in declaration order, grouped by rank. Sorted by FILE OFFSET they become a
- * single front-to-back sweep: read a window, hand it to every rank that asked for a piece of it,
- * move on. That is three separate wins over reading per rank as the walk goes:
+ *   - The file is read once; replicated weights (gigabytes on a large container) are not read
+ *     once per rank.
+ *   - Reads are sequential, which one thread can sustain at the NVMe rate, provided they bypass
+ *     the page cache: a buffered pread copies every byte on this thread and caps the rate at
+ *     about two thirds (half with the relayout pool's copies). O_DIRECT DMAs into the window.
+ *   - Copies overlap reads: a ring of pinned windows with one event per rank each, so reading one
+ *     window overlaps the DMAs and pool memcpys out of the others. Serialising, or waiting on the
+ *     stream instead of the event, costs about a fifth of the load rate.
  *
- *   - the file is read ONCE. A weight every rank wants -- every replicated weight, which is
- *     gigabytes on a large container -- would otherwise be read once per rank.
- *   - the reads are SEQUENTIAL. A declaration-order access pattern reads at a fraction of an
- *     NVMe disk's sequential rate; one thread reading front to back reaches it, and more threads
- *     do not help -- provided the reads go around the page cache. A buffered pread is the kernel
- *     copying every byte out of the cache into the window on this one thread, and that copy,
- *     not the disk, sets the rate: about two thirds of it alone, and half once the relayout
- *     pool's copies share the memory system. O_DIRECT lands the disk's DMA in the window itself.
- *   - the copies OVERLAP the reads. A ring of pinned windows, an event a rank on each: the read
- *     that fills one window runs while the copies out of the others are in flight -- the DMAs to
- *     the cards, and the pool's memcpys to host memory. Serialising them costs about a fifth of
- *     the load rate; waiting on the stream instead of on the event costs the same, because the
- *     stream also holds the copies this read was supposed to hide under.
- *
- * Host pinned memory is portable across devices in one process, so ONE window feeds every card:
- * copying each window to all of them still runs at the disk's rate rather than the link's. */
+ * Pinned host memory is portable across devices in one process, so one window feeds every
+ * card. */
 static int sweep_container(RadFile* file, std::vector& runs,
                            const std::vector& devices, RelayoutPool* pool,
                            int64_t* read_out) {
     *read_out = 0;
     if (runs.empty()) return RAD_OK;
 
-    /* By where the bytes ARE, which is the whole idea: after this the runs are a reading order
-     * and no longer a rank order. The tie-break on span keeps the order total, so two builds of
-     * the same load issue their copies in the same sequence. */
+    /* Sort by file offset into a reading order; the span tie-break makes the order total, so the
+     * same load always issues copies in the same sequence. */
     std::sort(runs.begin(), runs.end(), [](const LoadRun& a, const LoadRun& b) {
         if (a.foff != b.foff) return a.foff < b.foff;
         return a.span > b.span;
     });
 
-    /* What the sweep will actually read, for the progress line: the union of the runs, which is
-     * NOT the sum of them at --tp 2 and not the size of the file either -- the mapped tier is in
-     * neither. */
+    /* Bytes the sweep reads, for the progress line: the union of the runs (not their sum under TP,
+     * nor the file size, since the mapped tier is excluded). */
     int64_t want_bytes = 0;
     {
         int64_t hi = -1;
@@ -2155,30 +2009,21 @@ static int sweep_container(RadFile* file, std::vector& runs,
     }
 
     int64_t window = 64 << 20;
-    if (const char* e = getenv("RADIANCE_LOAD_WINDOW_MIB")) {
-        const long long v = atoll(e);
-        if (v > 0) window = (int64_t)v << 20;
-    }
-    /* A window WIDE ENOUGH to hold one piece of a strided run, whatever the widest is. The
-     * slicing below is correct at any window -- a piece cut by a chunk boundary is copied in the
-     * two halves it falls in -- but a window narrower than a piece turns every piece into two
-     * copies instead of one 2D copy for a whole row group at a time. Nothing in this tree comes
-     * near 64 MiB in a piece: a column shard's piece is one row group of one rank's columns. */
+    /* Widen the window to hold the widest strided piece. Slicing is correct at any width (a cut
+     * piece is copied in two halves), but a narrower window doubles the copies. In practice no
+     * piece approaches 64 MiB. */
     int64_t widest = 0;
     for (const LoadRun& q : runs) if (q.ny > 1 && q.wb > widest) widest = q.wb;
     if (widest > window) window = align_up(widest, 4096);
 
-    /* READ THROUGH A GAP RATHER THAN BREAK THE STREAM FOR IT, up to a point. On an NVMe disk a
-     * megabyte of sequential read costs about what starting a fresh read costs, so bytes nobody
-     * asked for are cheaper than the break until there are a few million of them. The gaps that
-     * matter are whole tiers -- a mapped n-gram table is tens of gigabytes of one -- and those
-     * are nowhere near this bound, so the choice only ever costs a little and saves a lot. */
+    /* Read through gaps up to kGap instead of breaking the stream: on NVMe a megabyte of
+     * sequential read costs about as much as starting a new read. Large gaps (a mapped n-gram
+     * table, tens of gigabytes) are far above this bound. */
     const int64_t kGap = 4 << 20;
 
-    /* SIX WINDOWS, because the host copies out of one are a worker's memcpy and not a DMA: a
-     * window a staged weight's piece sits in is free only when a worker has taken it, and the
-     * ring is how far the read may run ahead of them. Pieces are cut at kPiece so one window's
-     * worth spreads over several workers. */
+    /* Six windows: host copies out of a window are worker memcpys, so a window is free only once
+     * the workers have taken their pieces, and the ring bounds how far reads run ahead. Copies are
+     * cut at kPiece so one window spreads over several workers. */
     constexpr int     kWin   = 6;
     constexpr int64_t kPiece = 8 << 20;
     constexpr int64_t kBlk   = DirectFile::alignment();
@@ -2190,27 +2035,24 @@ static int sweep_container(RadFile* file, std::vector& runs,
     void*    buf[kWin] = {};
     pool->windows(kWin);
     int64_t  read_bytes = 0;
-    double   read_s = 0;     /* of the sweep's wall time, how much was the disk itself */
+    double   read_s = 0;     /* the part of the sweep's wall time spent reading */
 
     const int rc = [&]() -> int {
         for (size_t k = 0; k < nr; ++k) {
-            /* A stream and an event both belong to the device that was current when they were
-             * made, and recording one on the other's stream is an error rather than a slow path.
-             * The COPIES need no such bind: a stream carries its own device. */
+            /* Streams and events belong to the device current at creation, so bind it here; the
+             * copies themselves need no bind, since a stream carries its device. */
             RAD_TRY(rad_dev_set(devices[k]));
             RAD_TRY(rad_stream_create(&st[k], 0));
             for (int b = 0; b < kWin; ++b) RAD_TRY(rad_event_create(&ev[(size_t)b * nr + k]));
         }
-        /* O_DIRECT WANTS THE OFFSET, THE LENGTH AND THE BUFFER BLOCK-ALIGNED, and a chunk is
-         * wherever its runs put it: a window is read from the block below the chunk to the block
-         * above it, so it is two blocks wider than the chunk can be. A filesystem that refuses
-         * O_DIRECT is read through the cache instead, at the cache's rate. */
+        /* O_DIRECT needs block-aligned offset, length and buffer, while a chunk falls wherever its
+         * runs do, so a window is read from the block below the chunk to the block above it (two
+         * blocks wider). A filesystem that refuses O_DIRECT is read buffered. */
         RAD_TRY(dio.open(file->path(), RAD_DIO_READ | RAD_DIO_ALLOW_BUFFERED));
         for (int b = 0; b < kWin; ++b) {
             buf[b] = rad_dev_alloc(window + 2 * kBlk, RAD_MEM_HOST_PINNED);
             if (!buf[b]) {
-                RAD_ERR("load: no %s pinned staging window. The load needs %d of them; lower "
-                        "RADIANCE_LOAD_WINDOW_MIB or free host memory.",
+                RAD_ERR("load: no %s pinned staging window (the load needs %d); free host memory",
                         humanb(window).c_str(), kWin);
                 return RAD_E_NOMEM;
             }
@@ -2218,11 +2060,10 @@ static int sweep_container(RadFile* file, std::vector& runs,
 
         int cur = 0;
 
-        /* Read the chunk [c0, c1) into window `b`; `*at` is where its first byte landed. The
-         * blocks are whole up to the file's last full one, and a tail past that is the only read
-         * the bounce in DirectFile serves. Read buffered, the cache goes with the window: nothing
-         * comes back for a window the sweep has finished, and tens of gigabytes of dead pages
-         * turn into reclaim the reads then wait on. */
+        /* Read chunk [c0, c1) into window `b`; `*at` receives its first byte. Whole blocks up to
+         * the file's last full block; only the tail past it uses DirectFile's bounce. When read
+         * buffered, drop the window's pages afterwards, or tens of gigabytes of dead cache force
+         * reclaim that the reads then wait on. */
         const int64_t whole = file->size() / kBlk * kBlk;
         auto fill = [&](int b, int64_t c0, int64_t c1, const uint8_t** at) -> int {
             const auto t = std::chrono::steady_clock::now();
@@ -2238,17 +2079,10 @@ static int sweep_container(RadFile* file, std::vector& runs,
             return RAD_OK;
         };
 
-        /* Hand one run the part of itself that lies in the staged chunk [c0, c1).
-         *
-         * A run is SLICED BY THE CHUNK rather than given a chunk of its own, and that is the
-         * whole reason the chunk is a file range and not a run. At --tp 2 a column-sharded weight
-         * is two runs over the same entry, half a row apart: served one run at a time the entry
-         * is read TWICE, so the sweep reads more bytes than the container holds; served as a
-         * range, both runs take their columns out of one read.
-         *
-         * The strided case keeps its 2D copy for every piece the chunk holds WHOLE, which is all
-         * of them but the two at the ends; a piece cut by a chunk boundary is the only thing that
-         * becomes a copy of its own. */
+        /* Issue the part of a run that lies in chunk [c0, c1). Chunks are file ranges, not runs, so
+         * runs over the same entry (a column-sharded weight's per-rank runs, half a row apart)
+         * share one read. Pieces wholly inside the chunk go as one 2D copy; only a piece cut by a
+         * chunk boundary is copied separately. */
         auto one = [&](const LoadRun& q, uint8_t* dst, const uint8_t* src, int64_t len) -> int {
             touched[(size_t)q.rank] = 1;
             return rad_memcpy_async(dst, src, len, st[(size_t)q.rank]);
@@ -2259,9 +2093,8 @@ static int sweep_container(RadFile* file, std::vector& runs,
         };
         auto issue = [&](const LoadRun& q, const uint8_t* win, int64_t c0, int64_t c1,
                          int slot) -> int {
-            /* A HOST DESTINATION IS A MEMCPY, and the pool's workers make it: a staged run into
-             * its weight's input, which tells the pool how much of it has arrived, and any other
-             * into its host pool slot. The sweep only reads. */
+            /* Host destinations are memcpys done by the pool's workers: a staged run into its
+             * weight's input (counted as arrived), any other into its host pool slot. */
             if (q.stage >= 0 || !q.dev) {
                 if (pool->failed()) return RAD_E_STATE;
                 if (q.stage >= 0) pool->reserve(q.stage);
@@ -2296,10 +2129,9 @@ static int sweep_container(RadFile* file, std::vector& runs,
             }
             return RAD_OK;
         };
-        /* The window about to be overwritten is still the source of the copies issued out of it
-         * a turn of the ring ago. Wait for THOSE, by event, and not for the stream: the stream
-         * also holds the other windows' copies, which are exactly what this read is meant to hide
-         * under. And for the pool's memcpys out of it. */
+        /* Before reusing a window, wait for the copies issued from it a ring turn ago: by event,
+         * not stream sync (the stream also holds the other windows' copies this read should
+         * overlap), and for the pool's memcpys out of it. */
         auto acquire = [&](int b) -> int {
             for (size_t k = 0; k < nr; ++k)
                 if (live[(size_t)b * nr + k]) {
@@ -2321,10 +2153,9 @@ static int sweep_container(RadFile* file, std::vector& runs,
 
         const auto t0 = std::chrono::steady_clock::now();
         int64_t    last_note = 0;
-        /* A LOAD THAT STOPS HAS TO SAY WHERE. This names a file offset, which `rad-info -v` turns
-         * back into a weight -- the only way to localise a stall inside the sweep. Coarse by
-         * default because the sweep is seconds long; RADIANCE_DEBUG_LOAD_EVERY_MIB=64 is the
-         * fine-grained trail. */
+        /* Progress lines name a container offset, which `rad-info -v` maps back to a weight, to
+         * localise a stalled sweep. Every 8 GiB by default; RADIANCE_DEBUG_LOAD_EVERY_MIB sets a
+         * finer interval. */
         int64_t kNoteEvery = 8LL << 30;
         if (const char* e = getenv("RADIANCE_DEBUG_LOAD_EVERY_MIB")) {
             const long long v = atoll(e);
@@ -2332,10 +2163,9 @@ static int sweep_container(RadFile* file, std::vector& runs,
         }
         size_t i = 0;
         while (i < runs.size()) {
-            /* THE GROUP IS A STRETCH OF FILE, NOT A RUN. Every run that chains to this one within
-             * kGap belongs to the same read stream, however many ranks and however many weights
-             * that is, and however far it reaches: a group larger than a window is read in
-             * windows, not abandoned to a path of its own. */
+            /* A group is a stretch of file: every run chaining to this one within kGap, across
+             * ranks and weights, however long. A group larger than a window is read window by
+             * window. */
             const int64_t g0 = runs[i].foff;
             int64_t g1 = g0 + runs[i].span;
             size_t  j  = i + 1;
@@ -2345,9 +2175,8 @@ static int sweep_container(RadFile* file, std::vector& runs,
                 if (end > g1) g1 = end;
             }
 
-            /* `lo` is the first run that has not finished. Sorted by offset, a run whose last
-             * byte is behind the chunk is behind it for good, so the scan never goes backwards
-             * and each run is looked at once per chunk it reaches into. */
+            /* `lo` is the first unfinished run. Runs are sorted by offset, so one that ends before
+             * the chunk is done for good and the scan never goes back. */
             size_t lo = i;
             for (int64_t c0 = g0; c0 < g1; ) {
                 const int64_t c1 = g1 < c0 + window ? g1 : c0 + window;
@@ -2373,17 +2202,14 @@ static int sweep_container(RadFile* file, std::vector& runs,
             i = j;
         }
 
-        /* The last host synchronisation before serving: after this the step path never waits on
-         * the host again (spec §5.4). */
+        /* The last host synchronisation before serving (spec §5.4). */
         for (size_t k = 0; k < nr; ++k) RAD_TRY(rad_stream_sync(st[k]));
         for (int b = 0; b < kWin; ++b) pool->drain(b);
 
         const double s = std::chrono::duration(
                              std::chrono::steady_clock::now() - t0).count();
-        /* THE SPLIT IS THE DIAGNOSTIC. If the disk time is the whole of the wall time the sweep
-         * is at the drive's ceiling and there is nothing here to win; what is left over is the
-         * copies that did not hide under a read -- the host-tier memcpy, which is synchronous,
-         * and the per-run issue loop. */
+        /* Wall time vs disk time: when they match, the sweep is at the drive's ceiling; the
+         * difference is copies that did not overlap a read (host memcpys, the issue loop). */
         RAD_INFO("load: one pass over the container, %s read in %.1f s (%.1f GB/s) for %zu "
                  "rank(s); %.1f s of that was the disk (%.1f GB/s)",
                  humanb(read_bytes).c_str(), s, read_bytes / (s > 0 ? s : 1) / 1e9, nr,
@@ -2391,12 +2217,10 @@ static int sweep_container(RadFile* file, std::vector& runs,
         return RAD_OK;
     }();
 
-    /* AND THE PAGE CACHE GOES BACK. Weights that will never be read from the file again are cache
-     * the mapped tier cannot use: a mapped n-gram table is read from its mapping for the life of
-     * the process, and it is the one thing here that wants the cache. What this frees is worth
-     * more to the model than to the loader. */
+    /* Release the page cache of weights never read from the file again, leaving it to the mapped
+     * tier (e.g. a mapped n-gram table, read from its mapping for the process lifetime). */
     file->drop_blob_cache();
-    /* NOT FREED UNDER A WORKER: a sweep that failed part-way may have left copies out of them. */
+    /* Drain before freeing: a sweep that failed part-way may have copies outstanding. */
     for (int b = 0; b < kWin; ++b) pool->drain(b);
     for (int b = 0; b < kWin; ++b) if (buf[b]) rad_dev_free(buf[b], RAD_MEM_HOST_PINNED);
     for (size_t k = 0; k < ev.size(); ++k) if (ev[k]) rad_event_destroy(ev[k]);
@@ -2405,10 +2229,9 @@ static int sweep_container(RadFile* file, std::vector& runs,
     return rc;
 }
 
-/* One rank's share of a checkpoint weight's selected planes, read out of the mapped tensors into
- * `in` at the offsets the pool laid out: whole rows as one read, a column share a block of rows at
- * a time with the bytes it owns taken out of each. A whole plane declared under another shape (a
- * reshape) is the same bytes, so it is read in the checkpoint's own rows. */
+/* Read one rank's share of a checkpoint weight's selected planes from the mapped tensors into
+ * `in` at the pool's offsets: whole rows in one read, a column share a block of rows at a time.
+ * A reshaped whole plane has the same bytes, so it is read in the checkpoint's rows. */
 static int fill_from_checkpoint(const CkptWeight& cw, const std::vector& shares,
                                 const std::vector& sel, const std::vector& offs,
                                 const std::string& name, uint8_t* in) {
@@ -2457,22 +2280,13 @@ static int fill_from_checkpoint(const CkptWeight& cw, const std::vector runs;
     std::vector staged;
     int64_t n_out = 0;      /* destination overruns reported, capped */
@@ -2480,43 +2294,31 @@ int Engine::load_weights() {
     /* ============================================================== the walk */
     for (auto& r : ranks_) {
         LogRank lr(r->index);
-        /* Bound before anything is allocated for this rank: rad_dev_alloc has no device argument
-         * and takes whatever is current, so the mover's slabs would otherwise all land on card 0.
-         * See plan() for the same bind and the same reason. */
+        /* Bind before allocating for this rank (as in plan()). */
         RAD_TRY(rad_dev_set(r->device));
 
-        /* THE CONTAINER IS THE FILE TIER, and the mover has to be told so. `--weights-disk-tier` makes
-         * the planner place units on Tier::SSD, and a bare `MoverConfig{}` then dies in
-         * Mover::init with "the plan put weights on the file tier but no container path was
-         * given" -- after the plan has already been made. The mover reads THIS file with O_DIRECT
-         * rather than a copy of it: the weights are already
-         * here, RAD_ALIGN_UNIT-aligned (rad_format.h), which is DirectFile's alignment exactly,
-         * so a stage takes the no-bounce path. */
+        /* The container is the file tier (--weights-disk-tier places units on Tier::SSD), so the
+         * mover needs its path. It reads the container with O_DIRECT: weights are RAD_ALIGN_UNIT-
+         * aligned (rad_format.h), DirectFile's alignment, so stages take the no-bounce path. */
         MoverConfig mc{};
         mc.container_path = file_ ? cfg_.model : std::string();
         RAD_TRY(r->mover.init(r->program, r->plan, mc, &r->pools));
-        /* WHAT THE MOVER TOOK, said before the first copy. The slabs are allocated in init, so by
-         * here the pool is as full as it will get -- the copy loop writes into slots that already
-         * exist and moves the cursor no further. A load that stops with the pool at zero free is
-         * a placement failure wearing a loader's costume, and this line is what tells the two
-         * apart from the outside. */
+        /* What the mover took, before the first copy. Its slabs are allocated in init, so the pool
+         * is as full as it will get; a load stopping with zero free is a placement failure, not
+         * a loader one. */
         RAD_INFO("load: rank %d, mover took %s, weights pool %s free of %s", r->index,
                  humanb(r->pools.weights().used()).c_str(),
                  humanb(r->pools.weights().avail()).c_str(),
                  humanb(r->pools.weights().used() + r->pools.weights().avail()).c_str());
 
-        /* THE POLICY HALF, BOUND TO THE SAME PLAN. It returns RAD_OK on a static plan and reports
-         * `enabled() == false`, which is a mode and not a failure -- all_vram and
-         * --deterministic both land there -- so there is nothing to branch on here. */
+        /* The heat engine, bound to the same plan. On a static plan (all_vram, --deterministic) it
+         * returns RAD_OK with `enabled() == false`. */
         RAD_TRY(r->heat.init(r->plan, HeatParams{}));
 
-        /* A DESTINATION HAS TO LIE INSIDE THE POOL IT WAS CARVED FROM. A slot pointer that runs
-         * past the end of the weights pool is a write to device memory the process does not own,
-         * and on this driver that does not fault -- the copy is accepted, never completes, and
-         * the host thread spins inside the runtime with the copy engine idle and no I/O. It looks
-         * exactly like a hang, and it moves with the weights pool's size because a bigger pool is a
-         * later overrun. Cheap enough to check on every copy, and checked before any of them
-         * start rather than as each one is issued. */
+        /* Every destination must lie inside the weights pool. A copy past its end targets memory
+         * the process does not own, which on this driver does not fault: the copy never completes
+         * and the host spins in the runtime, like a hang. Checked for every copy before any
+         * starts. */
         const uint8_t* wp_lo = (const uint8_t*)r->pools.weights().base();
         const uint8_t* wp_hi = wp_lo + r->pools.weights().bytes();
         auto dst_fits = [&](const void* p, int64_t len, const char* nm) {
@@ -2531,16 +2333,15 @@ int Engine::load_weights() {
             return false;
         };
 
-        /* AND THE SOURCE OF A SHARE HAS TO LIE INSIDE ITS PLANE. Every offset below is computed
-         * from the rank index, so rank 0 cannot exercise the arithmetic at all -- whatever the
-         * shape is, it reads from the start of the plane. An offset that runs off the end is a
-         * read of the wrong weight, or of nothing at all, so it is checked, not trusted. */
+        /* And every source range must lie inside its plane. Offsets depend on the rank index
+         * (rank 0 always starts at the plane's start, so it never exercises the arithmetic), and
+         * an overrun would read the wrong weight. */
         const int64_t file_bytes = file_ ? file_->size() : 0;
 
         for (size_t i = 1; i < r->program.weights.size(); ++i) {
             WeightInfo& w = r->program.weights[i];
-            /* WHERE ITS PLANES ARE: a container entry, or the checkpoint tensors declare resolved
-             * it to. Either way the encoding and the logical shape the share is cut in. */
+            /* The planes' source: a container entry or the checkpoint tensors declare resolved,
+             * giving the encoding and logical shape the share is cut in. */
             const RadFileEntry* e = file_ ? file_->find(w.source) : nullptr;
             const CkptWeight* cw = ckpt_src_ ? ckpt_src_->find(w.source) : nullptr;
             if (!e && !cw) {
@@ -2559,10 +2360,8 @@ int Engine::load_weights() {
             const uint32_t src_rank = e ? e->rank : cw->rank;
             const int64_t* src_shape = e ? e->shape : cw->shape;
 
-            /* THE ENCODING THE KERNELS WERE CHOSEN FOR IS THE ONE THE SOURCE HOLDS. Declare asked
-             * it (rad_weight_encoding) and every layout hook answered for that encoding, so a
-             * difference here is a declaration that was made against something else -- refused
-             * by name rather than relaid as if it were the same weight. */
+            /* The source must hold the encoding declare saw (rad_weight_encoding) and every layout
+             * hook answered for; otherwise refuse rather than relayout the wrong bytes. */
             if (!rad_enc_equal(&src_enc, &w.enc)) {
                 char want[256], have[256];
                 rad_enc_format(&w.enc, want, sizeof want);
@@ -2573,28 +2372,12 @@ int Engine::load_weights() {
                 return RAD_E_FORMAT;
             }
 
-            /* THE PLANNER'S DECISION HAS TO LAND ON WeightInfo, and this is where it lands.
-             *
-             * WeightInfo::tier/site/slab_slot say "Filled by the planner (spec §5.3)" and the
-             * planner's own finish() says it is "the component that fills these three" -- but
-             * what it fills is Plan::weight[], a parallel array. Leaving the two apart is silent
-             * in both directions:
-             *
-             *   - Ctx::bind_weights picks RAD_DOMAIN_HOST only when EVERY weight operand of an op
-             *     has site == Site::Host. Left at the default Site::Device that test can never
-             *     pass, so host-site execution is unreachable and the planner's whole
-             *     "contiguous host runs" objective lands nowhere -- layer offload becomes dead
-             *     code that still passes its tests.
-             *   - a file-tier weight is skipped below on `tier == Tier::SSD` read off the PLAN,
-             *     so the two spellings of the same fact would disagree right here.
-             *
-             * file_offset is the same story one layer down: Mover::stage reads it to pread the
-             * container, and left unset every SSD stage reads offset 0 -- the file header -- for
-             * every weight. It is the selected plane's, and only a weight read where it lies ever
-             * uses it (weight_file_direct).
-             *
-             * Set before the residency lookup, not after: a file-tier weight has no address yet
-             * and takes the `continue` below, and it is precisely the one that needs the offset. */
+            /* Copy the planner's decision (Plan::weight[], a parallel array) onto WeightInfo.
+             * Ctx::bind_weights picks RAD_DOMAIN_HOST only when every weight operand has
+             * Site::Host, so without this host-site execution is unreachable. file_offset (the
+             * selected plane's) is what Mover::stage preads for a weight read in place
+             * (weight_file_direct); unset, it would read the file header. Set before the residency
+             * lookup, because a file-tier weight has no address yet and `continue`s below. */
             w.tier        = r->plan.weight[i].tier;
             w.site        = r->plan.weight[i].site;
             w.slab_slot   = r->plan.weight[i].slab_slot;
@@ -2609,16 +2392,10 @@ int Engine::load_weights() {
                 return RAD_E_STATE;
             }
 
-            /* THE MAPPED TIER IS A PUBLISH AND NOT A LOAD. The bytes are already at a host
-             * address -- the container is mmapped and stays mapped for the life of the engine
-             * (core/format/radfile.cpp) -- so there is nothing to copy and no pool to copy into.
-             * This is the only weight class the load phase does not move, and the sweep below
-             * never reads a byte of it -- which on a container with a large mapped table is most
-             * of the file.
-             *
-             * IT HAS TO GO THROUGH THE RESIDENCY TABLE and not only onto WeightInfo::ptr, because
-             * Ctx::resolve_weight reads the table whenever a mover exists and would otherwise
-             * find the null the mover published for a unit with no slab class. */
+            /* The mapped tier is published, not loaded: the container stays mmapped for the
+             * engine's life (core/format/radfile.cpp), and the sweep never reads these bytes.
+             * Publish through the residency table too, not only WeightInfo::ptr, because
+             * Ctx::resolve_weight reads the table whenever a mover exists. */
             if (w.tier == Tier::Mapped) {
                 const RadFilePlane& p0 = file_->plane(*e, w.sel[0]);
                 const int64_t n = (int64_t)p0.bytes;
@@ -2630,12 +2407,10 @@ int Engine::load_weights() {
                 }
                 w.ptr = (void*)file_->data(p0);
                 w.host_ptr = w.ptr;
-                /* --ngram-placement ram: the gather reads a copy instead of the mapping -- pinned
-                 * memory a device kernel reads in place over the link, where the planner put the
-                 * table on the zero-copy site, or locked memory for the host gather. A copy auto
-                 * chose and could not make leaves the table in the container and says so, and a
-                 * card's gather moves to the host with it; one the operator asked for refuses the
-                 * start. */
+                /* --ngram-placement ram: the gather reads a copy instead of the mapping: pinned
+                 * memory for a device kernel on the zero-copy site, or locked memory for the host
+                 * gather. If auto's copy fails, the table stays in the container (a card's gather
+                 * moves to the host); if `ram` was asked for, startup fails. */
                 if (cfg_.ngram_resolved == TablePlacement::Ram &&
                     is_ngram_table(r->program, (rad_weight)i)) {
                     const bool card = w.site == Site::DeviceZeroCopy;
@@ -2672,21 +2447,10 @@ int Engine::load_weights() {
                                "rows are read from the container%s", into, why.c_str(),
                                card ? " by the host gather" : ""));
                 }
-                /* NO READAHEAD ON A MAPPED WEIGHT. What reads one is a host kernel gathering rows
-                 * out of it, and the only reason a weight is on this tier at all is that it is far
-                 * too big to be resident -- so a fault is a real read from the file and the pages
-                 * around it are pages nobody asked for. Linux's default 128 KiB readahead turns a
-                 * row of a few hundred bytes into 32 pages of I/O, and at a dozen rows a token
-                 * that is megabytes read to use kilobytes. MADV_RANDOM is the whole of the
-                 * correction and it is per range, so the rest of the container keeps the
-                 * sequential behaviour the load pass wants.
-                 *
-                 * IT SHOWS NOTHING ON A WARM PAGE CACHE. When the hot part of the table is
-                 * already resident the serving process reads nothing from disk and the advice
-                 * changes no timing at all; the regime it protects -- a table genuinely colder
-                 * than RAM -- is the regime this tier exists for, and it costs one syscall at
-                 * load. What shows its effect is a cold cache and a byte counter, not a
-                 * stopwatch. */
+                /* No readahead on a mapped weight: a host kernel gathers a few rows from a table
+                 * too large to be resident, so the default 128 KiB readahead would read 32 pages
+                 * for a row of a few hundred bytes. MADV_RANDOM is per range, so the rest of the
+                 * container keeps sequential readahead. The effect shows only with a cold cache. */
                 posix_madvise(w.ptr, (size_t)n, POSIX_MADV_RANDOM);
                 r->mover.publish_mapped((rad_weight)i, w.ptr);
                 ++n_mapped;
@@ -2696,36 +2460,25 @@ int Engine::load_weights() {
 
             const WeightSlot* slot = r->mover.residency()->lookup((rad_weight)i);
             if (!slot || !slot->ptr) {
-                /* A file-tier unit has no address until the mover stages it, which is correct and
-                 * not an error: RAD_ACCESS_RARE weights are read on demand (spec §5.2). */
+                /* A file-tier unit has no address until the mover stages it (spec §5.4). */
                 if (w.tier == Tier::SSD) continue;
                 RAD_ERR("rank %d: '%s' has no address after mover init", r->index, w.name.c_str());
                 return RAD_E_STATE;
             }
 
-            /* THE ADDRESS HAS TO LAND ON WeightInfo, not only in the residency table. In the
-             * all-in-VRAM case Ctx is built with a NULL residency -- the mover never runs, so
-             * there is nothing to look up per issue -- and `Ctx::resolve_weight` collapses to
-             * `WeightInfo::ptr` (core/runtime/issue.cpp says exactly that). Leaving it null
-             * leaves every weight in the program unbound at issue, which the run phase reports as
-             * "weight 'x' has no pointer at issue: the load phase never bound it" -- the load
-             * having copied the whole model into addresses nothing afterwards can name.
-             * `generation` is not bumped because `bind_weights` runs for the first time after
-             * this, in Ctx::init. */
+            /* The address must also land on WeightInfo: with everything in VRAM, Ctx has no
+             * residency table and Ctx::resolve_weight reads WeightInfo::ptr
+             * (core/runtime/issue.cpp). `generation` is not bumped, since bind_weights first runs
+             * after this, in Ctx::init. */
             w.ptr = slot->ptr;
 
-            /* HOST-POOL DESTINATIONS STAY A memcpy. The host pool is pinned and device-mapped
-             * (core/mem/pools.cpp), so the copy engine CAN write it, and the synchronous
-             * host-tier memcpy is most of what separates this sweep from the disk's own rate --
-             * which makes putting those copies on the stream look as though it would hide them
-             * under the next read. It does not: an async host-to-host copy is not a DMA on this
-             * stack, it is the same memcpy with a stream in front of it. */
+            /* Host-pool destinations stay a memcpy. The pool is pinned and device-mapped
+             * (core/mem/pools.cpp), but an async host-to-host copy on this stack is the same memcpy
+             * behind a stream, not a DMA, so streaming it would not overlap it with reads. */
             const bool dev = w.tier == Tier::VRAM;
             if (dev && !dst_fits(slot->ptr, w.stored_bytes, w.name.c_str())) return RAD_E_STATE;
 
-            /* THIS RANK'S SHARE OF THE SELECTED PLANES, cut on the canonical form where a ROW
-             * shard is rows of every plane and a COL shard is columns -- each on the plane's own
-             * block boundary, and refused where a block or a byte would be split. */
+            /* This rank's share of the selected planes (format/share.h). */
             PlaneShare sh[RAD_ENC_MAX_PLANES];
             std::string why;
             if (weight_share(w, src_enc, src_rank, src_shape, cfg_.tp, r->index, sh, &why) !=
@@ -2735,9 +2488,8 @@ int Engine::load_weights() {
                 return RAD_E_SHAPE;
             }
 
-            /* FROM A CHECKPOINT, every weight is staged and its worker reads it: there is no
-             * sweep to deliver it, and the stored form is whatever the pool makes of the share --
-             * as it is, widened, or relaid. */
+            /* From a checkpoint every weight is staged and read by its worker (no sweep); the pool
+             * stores it as is, widened, or relaid. */
             if (!e) {
                 StagedWeight sw;
                 sw.prog = &r->program;
@@ -2771,8 +2523,8 @@ int Engine::load_weights() {
                 continue;
             }
 
-            /* STORED AS IT IS: the share goes from the file to the slot. Otherwise it is staged
-             * whole for the relayout pool, plane after plane, and the pool writes the slot. */
+            /* Stored as is: the share goes from the file to the slot. Otherwise it is staged plane
+             * by plane for the relayout pool, which writes the slot. */
             int32_t stage = -1;
             int64_t in_bytes = 0;
             if (!w.identity || w.widen) {
@@ -2831,8 +2583,8 @@ int Engine::load_weights() {
     }
 
     if (n_missing) {
-        RAD_ERR("%lld declared weights are absent from the container. Reported whole rather than "
-                "first-failure-at-the-top; the model cannot run.", (long long)n_missing);
+        RAD_ERR("%lld declared weights are absent from the container; the model cannot run",
+                (long long)n_missing);
         return RAD_E_NOTFOUND;
     }
 
@@ -2845,15 +2597,15 @@ int Engine::load_weights() {
     for (const StagedWeight& sw : staged) staged_bytes += sw.in_bytes;
     RelayoutPool pool(staged);
     const unsigned hw = std::thread::hardware_concurrency();
-    /* Started whatever is staged: a host pool slot is filled by the same workers. */
+    /* Started even with nothing staged: the same workers fill host pool slots. */
     const int workers = (int)std::max(2u, std::min(16u, hw > 2 ? hw - 2 : 2u));
-    pool.start(workers, std::max(4ll << 30, 0));
+    pool.start(workers, 4ll << 30);
     const auto rt0 = std::chrono::steady_clock::now();
     int sw_st = RAD_OK;
     if (file_) {
         sw_st = sweep_container(file_.get(), runs, devices, &pool, &read_bytes);
     } else {
-        /* every weight to the workers, in declaration order, as fast as the budget lets them in */
+        /* Every weight to the workers in declaration order, as the budget allows. */
         for (size_t k = 0; k < staged.size() && !pool.failed(); ++k) {
             const int64_t n = staged[k].remaining;
             pool.reserve((int)k);
@@ -2879,10 +2631,8 @@ int Engine::load_weights() {
              humanb(total).c_str(), humanb(read_bytes).c_str(),
              file_ ? "container" : "checkpoint");
     if (n_mapped)
-        /* THE BYTES ARE SHARED BETWEEN RANKS and the counters are not: every rank maps the same
-         * file, so at --tp 2 this counts one mapped table twice. Said rather than halved,
-         * because what the number IS is the sum of the mappings -- and an operator reading it as
-         * memory would size a box for twice what the model needs. */
+        /* Summed over ranks, which map the same file, so under TP the resident bytes are this
+         * divided by --tp; the message says so. */
         RAD_INFO("load: %lld weight(s), %s, read in place from the container's mapping -- not "
                  "copied and charged to no pool%s", (long long)n_mapped,
                  humanb(mapped_bytes).c_str(),
@@ -2892,38 +2642,14 @@ int Engine::load_weights() {
 }
 
 /* ================================================================== 6b. KV pools */
-/* The block manager owns every KV group's memory -- paged attention caches, the GDN recurrent
- * states and the conv windows alike -- because two allocators disagreeing about what a sequence
- * owns is not a leak but the bug where a freed sequence's state slot is handed to the next
- * request while the first is still reading it (spec §7.2).
+/* The block manager owns all KV group memory (paged attention caches, GDN recurrent states, conv
+ * windows), so one owner decides what a sequence holds and a freed state slot is never handed out
+ * while still in use (spec §7.2).
  *
- * This runs after load, not before, because it takes what the weight pool LEFT. It has to be
- * before Ctx::init: a Ctx built without these bindings resolves every RAD_OPK_KV operand to null,
- * and the first attention kernel of the first step dereferences it. */
+ * Runs after load, since it takes what the weight pool left, and before Ctx::init, which would
+ * otherwise resolve every RAD_OPK_KV operand to null. */
 int Engine::configure_kv() {
-    /* THE ANCHOR IS A PROPERTY OF THE POOL, SO THE POOL'S OWNER TURNS IT ON. libr4d's recurrent
-     * update can keep one committed state a sequence and replay the accepted prefix onto it out
-     * of a scratch slot, instead of writing a full state per candidate token -- 2 slots a
-     * sequence against 1 + n_spec, which at a realistic depth is several times less. It is off by
-     * default because it is NOT PAGED: it assumes a sequence's state stays in the slot it was
-     * given, which is true of radiance's linear pool and is not true of vLLM's, and the two
-     * callers share the kernel. Set before any kernel runs; libr4d reads it once.
-     *
-     * The engine's half of the bargain is KVGroupPlan::state_copies (core/mem/kv.cpp): two slots
-     * a sequence, both zeroed on admission, named by a state_index row wide enough to reach
-     * them. Without speculation there is nothing to defer and the plain path is both correct and
-     * one slot cheaper. */
-    /* Overwrite 0, so an operator can still set it -- but the two settings are NOT both runnable at
-     * every depth. Per-candidate indexing needs `1 + n_spec` distinct slots and this pool has two,
-     * so at a draft depth above one it gives several candidate tokens the same slot: a partially
-     * accepted step then resumes from a state one or more tokens too far along, silently, in a
-     * cache nothing reads back. The arch declares `state_form` on the op from the same condition
-     * below, and libr4d refuses the form that disagrees with the declaration -- so an override that
-     * would corrupt is a selection error naming the kernel and the geometry, rather than a
-     * generation that drifts. */
-    if (cfg_.n_spec > 0) setenv("RADIANCE_GDN_ANCHOR", "1", 0);
-    /* Resolved once, for the cache below and for Scheduler::init later. Resolving it separately in
-     * each is how the two come to disagree, and the interval is the field where that shows. */
+    /* Resolved once, for the cache below and Scheduler::init later (see Engine::geo_). */
     RAD_TRY(chunk_geometry_resolve(ranks_[0]->program, cfg_, &geo_));
     if (geo_.checkpoint_interval != cfg_.checkpoint_interval)
         decide("--checkpoint-interval",
@@ -2933,22 +2659,18 @@ int Engine::configure_kv() {
                          "block and the linear-state chunk), so a checkpoint is a legal chunk split",
                          (long long)geo_.quantum)
                    : std::string("the model keeps no linear state to checkpoint"));
-    /* ONE BLOCK TABLE SERVES EVERY RANK (serve() checks it), so every rank carves the SAME number
-     * of paged blocks. The ranks' pools are not the same size under an uneven tensor-parallel
-     * split -- a rank with more delta-net heads holds more recurrent state, a rank with zero
-     * attention weights has more pool -- so each is planned first, asked what it could carve, and
-     * every rank is capped at the least before any carves. At an even split the cap is what
-     * every rank would have carved anyway. */
+    /* One block table serves every rank (serve() checks it), so every rank carves the same number
+     * of paged blocks. Under an uneven split the pools differ (more delta-net heads, or zero
+     * attention weights), so each rank is planned first and all are capped at the least before
+     * any carves. */
     int64_t least = -1;
     for (size_t i = 0; i < ranks_.size(); ++i) {
         auto& r = ranks_[i];
         LogRank lr(r->index);
         RAD_TRY(r->kv.plan_groups(r->program.kv_groups, cfg_));
         const int64_t t = r->kv.paged_tokens(r->pools.kv().avail());
-        /* A RANK plan() RE-SIZED FOR THE COMMON TOKEN COUNT PAGES AT LEAST THAT COUNT, by
-         * construction: its pool is the least whole MiB whose paged split reaches it, asked of the
-         * same plan against the same bytes. Short of it, this rank would set every rank's count
-         * under what its dearest peer pages -- a broken construction, refused by name. */
+        /* A rank plan() re-sized for the common token count must page at least that count (same
+         * plan, same bytes); anything less is a broken invariant. */
         if (rank_cfg_[i].vram_kv_mib < cfg_.vram_kv_mib && t < kv_planned_tokens_) {
             RAD_ERR("kv: rank %d's KV pool was sized at %lld MiB to page the common %lld tokens "
                     "and pages %lld: the pool and the plan that sized it disagree", r->index,
@@ -2961,7 +2683,7 @@ int Engine::configure_kv() {
     }
     for (auto& r : ranks_) {
         LogRank lr(r->index);
-        RAD_TRY(rad_dev_set(r->device));   /* allocates on the CURRENT device; see plan() */
+        RAD_TRY(rad_dev_set(r->device));   /* allocates on the current device; see plan() */
         if (ranks_.size() > 1) {
             const int64_t own = r->kv.paged_tokens(r->pools.kv().avail());
             if (own > least && own != KVManager::kUnboundedTokens)
@@ -2971,12 +2693,8 @@ int Engine::configure_kv() {
             r->kv.cap_paged_tokens(least);
         }
         RAD_TRY(r->kv.carve(r->pools.kv()));
-        /* THE ONE CASE WHERE THE CACHE CANNOT GIVE ANYTHING BACK, said once and named. Every
-         * caller is written against the elastic contract and runs unchanged here -- the pool
-         * simply holds its whole carve -- so nothing fails, and the only symptom is an expert
-         * plane that never grows and a split that stays where the budget put it.
-         * That is worth a line, because it is indistinguishable from a working run in every
-         * counter this engine reports. */
+        /* Without virtual memory management the cache cannot lend: everything still works, but
+         * the expert slab never grows, which no counter shows, so log it once. */
         if (r->index == 0 && !r->pools.kv().elastic())
             RAD_WARN("this device has no virtual memory management, so the KV cache holds its "
                      "whole carve and the expert slab has nothing to grow into. The experts were "
@@ -2985,18 +2703,13 @@ int Engine::configure_kv() {
     }
 
     /* ---------------- the linear-state snapshot store ---------------- */
-    /* PINNED HOST MEMORY, NOT THE CARD. A snapshot is a copy of a sequence's recurrent state that
-     * no kernel reads: a save copies the state out after the step that produced it and a hit
-     * copies it back before the step that resumes from it, each a few milliseconds across the
-     * link. Holding it in VRAM would charge the KV pool for memory the live cache could use.
-     *
-     * One slot holds every rank's shard, each at its own offset, so the disk tier moves a slot as
-     * one payload; rank 0's manager hands the ids out. Opened only where there is something to
-     * snapshot and a cache to serve it. */
+    /* Pinned host memory, not VRAM: no kernel reads a snapshot; it is copied out after the step
+     * that produced it and back before a resume, a few milliseconds over the link each. One slot
+     * holds every rank's shard at its own offset; rank 0's manager hands out ids. Opened only when
+     * there is state to snapshot and a prefix cache. */
     {
-        /* THE SHARDS NEED NOT BE EQUAL: a rank's state holds its own heads of each group, and a
-         * world the heads do not divide gives the ranks different shares. A slot is the sum of
-         * the ranks' shards and a rank's starts where the ranks before it end. */
+        /* Shards can differ in size (heads need not divide evenly), so a slot is the sum of the
+         * ranks' shards, each starting where the previous ends. */
         std::vector shard_off(ranks_.size(), 0);
         int64_t slot = 0;
         for (size_t i = 0; i < ranks_.size(); ++i) {
@@ -3007,15 +2720,32 @@ int Engine::configure_kv() {
         /* A slot holds linear state or a trunk's window, never both (KVGroupPlan::win_snap). */
         const char* what = ranks_[0]->kv.has_window_snapshot() ? "sliding-window" : "linear-state";
         if (slot > 0 && n > 0 && cfg_.prefix_cache) {
-            if (ck_store_.open(slot, slot * n) != RAD_OK) {
-                RAD_WARN("checkpoint slots: no pinned host memory for %lld %s snapshot(s) of %s; "
-                         "a session's prefix hits prefill from the start. Lower "
-                         "--checkpoint-slots.", (long long)n, what, humanb(slot).c_str());
-            } else {
-                RAD_INFO("checkpoint slots: %lld %s snapshot(s) of %s in pinned host memory (%s), "
-                         "none of it on the card", (long long)n, what, humanb(slot).c_str(),
-                         humanb(ck_store_.cap_bytes()).c_str());
-            }
+            /* Pinned all at once and outside every pool. A store larger than the memory left would
+             * push the process into reclaim, which stalls it without a word; one that cannot be had
+             * would leave every prefix hit on this model prefilling from the start, which no counter
+             * makes visible. Either stops startup. */
+            const bool sized = n <= INT64_MAX / slot;
+            auto refuse = [&](const std::string& reason) {
+                RAD_ERR("checkpoint slots: %lld %s snapshot(s) of %s are %s of pinned host memory, "
+                        "which %s. Lower --checkpoint-slots (a larger --checkpoint-interval needs "
+                        "fewer for the same context), or pass --checkpoint-slots 0 to serve with "
+                        "no %s snapshot, every prefix hit on this model then prefilling from the "
+                        "start", (long long)n, what, humanb(slot).c_str(),
+                        sized ? humanb(slot * n).c_str() : "more than 8 EiB", reason.c_str(),
+                        what);
+                return RAD_E_NOMEM;
+            };
+            if (!sized) return refuse("no host has");
+            std::string why;
+            if (!lockable_room(slot * n, 0, false, &why)) return refuse("does not fit: " + why);
+            if (ck_store_.open(slot, slot * n) != RAD_OK)
+                return refuse(std::string("the host did not pin: ") + rad_dev_last_error());
+            RAD_INFO("checkpoint slots: %lld %s snapshot(s) of %s in pinned host memory (%s), "
+                     "none of it on the card", (long long)n, what, humanb(slot).c_str(),
+                     humanb(ck_store_.cap_bytes()).c_str());
+        } else if (slot > 0 && cfg_.prefix_cache) {
+            RAD_INFO("checkpoint slots: --checkpoint-slots 0 keeps no %s snapshot, so every "
+                     "prefix hit on this model prefills from the start", what);
         }
         for (auto& r : ranks_)
             r->kv.set_checkpoint_store(&ck_store_, shard_off[(size_t)(&r - &ranks_[0])]);
@@ -3026,28 +2756,17 @@ int Engine::configure_kv() {
     }
 
     /* ---------------- the idle session tiers (spec §7.3) ---------------- */
-    /* AFTER the prefix cache, because the tiers are sized in units of ONE CACHE ENTRY and only the
-     * configured cache knows which groups an entry covers. No memory is committed unless the
-     * operator gave the host tier a size.
-     *
-     * CONFIGURED EVEN SO, because this object is also where a stored conversation is RECORDED,
-     * and that is not a tiering fact. A server with no --prefix-cache-mib holds its whole prefix
-     * cache in VRAM and holds it for exactly as long; skipping the configure would leave the
-     * sessions view reading an unconfigured object and reporting an empty server, on every
-     * deployment that has not opted into demotion. What the flags gate is the MOVER, below. */
+    /* After the prefix cache, since the tiers are sized in cache entries and only the configured
+     * cache knows which groups an entry covers. No memory is committed unless the host tier has a
+     * size, but the tiers are configured anyway because they also hold the session record the
+     * sessions view reads. The flags gate only the mover, below. */
     {
         const bool tier_asked = cfg_.prefix_cache_mib > 0;
         const std::vector& cg = ranks_[0]->prefix.cached_groups();
-        /* ONE SLOT HOLDS EVERY RANK'S SHARD. An entry under tensor parallelism is n_ranks
-         * pieces of KV that are not interchangeable, so the unit the tiers store and budget
-         * in is the whole thing; each rank writes only its own window of it. THE SHARDS NEED
-         * NOT BE EQUAL -- a rank's block holds its own heads of a group, and a world the heads
-         * do not divide gives the ranks different shares, or none (rad_kv_group_zero) -- so a
-         * slot is the SUM of the ranks' entries and a rank's window starts where the ranks
-         * before it end. Where every rank's share is the same this is n_ranks times one entry
-         * at offsets of one entry, as it always was. The sizing below (TierExec::sizes) takes
-         * the largest rank's entry: the staging ring is a rank's own, and the ring that fits
-         * the largest fits every one. */
+        /* One slot holds every rank's shard of an entry; each rank writes only its window. Shards
+         * can differ or be empty (uneven heads, rad_kv_group_zero), so a slot is the sum and each
+         * window starts where the previous ends. TierExec::sizes uses the largest rank's entry,
+         * since the staging ring is per rank. */
         std::vector rank_entry(ranks_.size(), 0), entry_off(ranks_.size(), 0);
         int64_t entry_bytes = 0, slot_bytes = 0;
         for (size_t i = 0; i < ranks_.size(); ++i) {
@@ -3060,12 +2779,11 @@ int Engine::configure_kv() {
             entry_bytes = std::max(entry_bytes, rank_entry[i]);
         }
 
-        /* THE SNAPSHOTS ARE NOT IN THE HOST TIER: they live in the checkpoint store, which
-         * --checkpoint-slots sizes, and --prefix-cache-mib is the blocks' alone. */
+        /* Snapshots live in the checkpoint store (--checkpoint-slots); --prefix-cache-mib is for
+         * blocks only. */
         const int64_t ck_slot_bytes = ck_store_.enabled() ? ck_store_.slot_bytes() : 0;
         if (cg.empty() || entry_bytes <= 0) {
-            /* Said only to an operator who asked for a tier. With no flag there is nothing to
-             * report: a cache that indexes no paged group stores no blocks to begin with. */
+            /* Warn only when a tier was asked for. */
             if (tier_asked)
                 RAD_WARN("kv tiers: the prefix cache indexes no paged group, so there is nothing "
                          "to move. --prefix-cache-mib does nothing here.");
@@ -3075,34 +2793,37 @@ int Engine::configure_kv() {
             tc.entry_bytes     = slot_bytes;
             tc.ckpt_bytes      = ck_slot_bytes;
             tc.ckpt_slots      = ck_store_.capacity();
+            tc.block_tokens    = ranks_[0]->prefix.block_size();
 
-            /* THE POLICY IS RANK 0'S AND THE TRANSFER IS EVERY RANK'S. A session is not sharded --
-             * it is a conversation -- so one decision is taken about it; but each rank holds its
-             * own shard of every block and gathers out of its own pool, so each rank moves its own
-             * bytes when that decision is taken. */
+            /* Policy on rank 0 (a session is not sharded); every rank moves its own shard. */
             IdleTiers& T = ranks_[0]->tiers;
             RAD_TRY(T.configure(tc));
             T.set_model(meta_.name && meta_.name[0] ? meta_.name : "(unnamed)");
-            if (T.any_on()) {
-                /* HOW MUCH A PASS MOVES, SIZED IN BYTES AND NOT IN ENTRIES. A cache entry is one
-                 * block per cached group, and that is 29 KiB on a 4-token-block hybrid and four
-                 * times more on a 16-token one -- so a fixed entry count means a fixed batch on
-                 * one model and a quarter of one on another. At a fixed 64 entries a 200K session
-                 * on a 4-token-block hybrid takes about thirteen minutes to leave VRAM: a tier that
-                 * works and is too slow to be worth having.
-                 *
-                 * 16 MiB of device staging a rank, which is about a millisecond of PCIe a pass
-                 * and 0.02 ms a step of the VRAM it costs. The batch is one gather per (group,
-                 * layer) however many entries are in it, so the launches are the same either
-                 * way -- this buys the copies, which are what there are thousands of. */
-                /* A COPY OUT IS FOUR STAGING BATCHES, about 64 MiB a rank. It shares the transfer
-                 * stream with the expert mover, so what it queues is what a promotion issued
-                 * behind it waits for -- a few milliseconds of link at this size -- and the next
-                 * copy goes out on the tick after this one lands, so a long conversation still
-                 * leaves at the rate the link carries it.
-                 *
-                 * A RESTORE IS A WHOLE CHAIN, as long as the longest context this server takes.
-                 * TierExec::sizes holds the arithmetic, which the VRAM budget reserves from. */
+            if (T.host_on()) {
+                /* A conversation longer than the tier keeps only its start on the host; the rest
+                 * is prefilled again once VRAM gives it up, which on a card whose experts do not
+                 * fit is right after the turn. */
+                const int64_t held = T.arena().capacity() * tc.block_tokens;
+                const int64_t ctx = cfg_.max_ctx > 0 ? cfg_.max_ctx : meta_.n_ctx_train;
+                if (held < ctx)
+                    RAD_WARN("kv tiers: --prefix-cache-mib %lld holds %lld tokens of context (%s "
+                             "per %lld-token block), less than one --max-model-len %lld "
+                             "conversation: a longer one keeps its first %lld tokens in host "
+                             "memory and is prefilled again past them once VRAM gives it up. "
+                             "%lld MiB would hold one.",
+                             (long long)cfg_.prefix_cache_mib, (long long)held,
+                             humanb(slot_bytes).c_str(), (long long)tc.block_tokens,
+                             (long long)ctx, (long long)held,
+                             (long long)((ctx + tc.block_tokens - 1) / tc.block_tokens *
+                                         slot_bytes / (1 << 20) + 1));
+                /* Pass sizes are in bytes, not entries: an entry (one block per cached group) is
+                 * 29 KiB on a 4-token-block hybrid and 4x that at 16 tokens, and a fixed 64-entry
+                 * batch would take ~13 minutes to move a 200K session. A batch is 16 MiB of device
+                 * staging per rank (about 1 ms of PCIe per pass), one gather per (group, layer)
+                 * regardless of entry count. A copy out is four batches (~64 MiB per rank); it
+                 * shares the transfer stream with the expert mover, so promotions wait at most a
+                 * few milliseconds behind it. A restore is a whole chain up to the longest
+                 * context. TierExec::sizes holds the arithmetic, which the VRAM budget uses. */
                 const TierExec::Sizes tz = TierExec::sizes(
                     entry_bytes, cfg_.max_ctx > 0 ? cfg_.max_ctx : meta_.n_ctx_train,
                     ranks_[0]->prefix.block_size());
@@ -3110,15 +2831,10 @@ int Engine::configure_kv() {
                 const int64_t max_copy = tz.max_copy, max_chain = tz.max_chain;
                 bool all = true;
                 for (auto& r : ranks_) {
-                    /* ON THAT RANK'S DEVICE. rad_dev_alloc takes the CURRENT device, and the
-                     * staging buffer TierExec builds on its first pass is this rank's. The device
-                     * is recorded in configure() and re-selected there, but selecting it here too
-                     * keeps the rule that a rank is configured on its own card in one place: a
-                     * gather reading a pointer that belongs to another card fails as a plain
-                     * device error with nothing to say it was an addressing mistake.
-                     *
-                     * AND THE STREAM IS THE MOVER'S. See Mover::transfer_stream -- a fourth
-                     * hardware queue costs an RDNA4 card 65% of its decode step. */
+                    /* Configure on the rank's own device (rad_dev_alloc uses the current one; a
+                     * cross-card pointer fails as an opaque device error). The stream is the
+                     * mover's: a fourth hardware queue costs an RDNA4 card 65% of its decode
+                     * step (Mover::transfer_stream). */
                     RAD_TRY(rad_dev_set(r->device));
                     if (r->tierx.configure(&rad_tools_registry(), &r->kv, &T, cg,
                                            max_batch, max_copy, max_chain,
@@ -3133,17 +2849,15 @@ int Engine::configure_kv() {
                 }
                 RAD_TRY(rad_dev_set(ranks_[0]->device));
                 if (!all) {
-                    /* THE MOVER IS OFF AND THE BOOKKEEPING IS NOT. close() forgets the entry and
-                     * snapshot sizes with everything else, and those are what a session's
-                     * reported size is computed from, so the object is re-configured for the
-                     * caps it can still honour -- none. */
+                    /* The mover is off but the bookkeeping stays: close() forgets the entry and
+                     * snapshot sizes that session sizes are computed from, so re-configure with
+                     * zero caps. */
                     T.close();
                     tc.host_cap_bytes = 0;
                     RAD_TRY(T.configure(tc));
                 } else {
-                    /* The tiers can lose an entry without the cache asking: a capacity drop, or a
-                     * promotion that failed. The cache has to hear about it or it will go on
-                     * serving block ids that are not its own any more. */
+                    /* The tiers can drop an entry on their own (capacity drop, failed promotion);
+                     * the cache must hear of it or it would serve block ids it no longer owns. */
                     T.set_drop_sink([this](const BlockHash& h) {
                         ranks_[0]->prefix.drop_offdevice(h);
                     });
@@ -3155,37 +2869,24 @@ int Engine::configure_kv() {
                     RAD_INFO("%s", ranks_[0]->tierx.report().c_str());
                 }
             }
-            /* ATTACHED WHETHER OR NOT ANYTHING MOVES. A null `tiers_` is the whole of the cache's
-             * "off" path, and it turns off the session record along with the demotion it was
-             * written for -- so detached, a server with no tier flag would publish no conversations
-             * at all and the sessions view would have nothing to draw. With the caps at zero every
-             * call the cache makes here is a record of what it is holding and nothing is ever
-             * moved. */
+            /* Attached even when nothing moves: a null `tiers_` would also disable the session
+             * record. With zero caps every call is bookkeeping only. */
             ranks_[0]->prefix.set_tiers(&T);
-            /* AND SAID EITHER WAY. configure() builds this line whether the tiers are on or off;
-             * printed only when they are on, a server that never moves a session would say
-             * nothing about it at all -- leaving "why is the KV pool full with one conversation
-             * open" with no answer in the log and a flag nobody knew was unset. */
+            /* Logged whether the tiers are on or off. */
             RAD_INFO("%s", T.report().c_str());
         }
     }
 
     RAD_INFO("kv: %s", ranks_[0]->kv.report().c_str());
-    /* PrefixCache::configure builds a report saying whether it is on, which groups it covers and
-     * which it had to skip, and this is where it is printed: unprinted, "why is cached_tokens
-     * always zero" has no answer short of reading the source. It is one line at startup and names
-     * the two things
-     * that silently turn caching off for a hybrid model: a windowed group cannot be served a
-     * prefix, and a linear model with no checkpoint interval replays from zero. */
+    /* The prefix cache's report: on or off, groups covered and skipped. It names the two things
+     * that silently disable caching on a hybrid model: a windowed group cannot be served a prefix,
+     * and a linear model with no checkpoint interval replays from zero. */
     RAD_INFO("%s", ranks_[0]->prefix.report().c_str());
 
-    /* CAN THE POOL ACTUALLY HOLD A MAX-LENGTH SEQUENCE? The context limit and the KV pool are set
-     * by two unrelated flags, and this is where they are compared. Uncompared, a server started
-     * with a context its cache cannot cover accepts the request at the door and refuses it at
-     * admission seconds later, with a message about blocks rather than about the flag that was
-     * wrong. A WINDOW group is exempt: its per-sequence cost is the window, not the context, which is
-     * the whole point of it. Only paged groups can run out this way; a linear group is O(1) in
-     * context and is sized per sequence. */
+    /* Can the pool hold one max-length sequence? The context limit and KV pool come from unrelated
+     * flags; otherwise such a request is accepted and then refused at admission with a message
+     * about blocks. Only full paged groups apply: a window group costs the window, and a linear
+     * group is O(1) in context. */
     {
         const int64_t want = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train;
         const KVManager& kv = ranks_[0]->kv;
@@ -3194,18 +2895,12 @@ int Engine::configure_kv() {
             if (!p || !p->paged() || p->window_blocks > 0) continue;
             const int64_t cap = p->n_blocks * p->block_size;
             if (cap >= want) continue;
-            /* THIS ONE IS A REAL LIMIT AND NOT A BACKING RATIO. How much of the worst case
-             * (every sequence at max_ctx at once) the pool backs is a provisioning choice and
-             * well under half is normal for one-shot traffic. (It is NOT harmless for
-             * multi-turn: prefix caching keeps a finished sequence's blocks so the next turn
-             * can reuse them, so a pool that backs fewer live SESSIONS than it admits makes
-             * every turn re-prefill. That is a provisioning choice too, and the budget line
-             * in vram_budget.cpp says it.) What is never acceptable is a pool that cannot
-             * hold ONE max-length sequence:
-             * that request is accepted by the API and can never complete, whatever the load. */
-            /* An image generator's sequence is a conditioning, and its driver refuses one the
-             * cache can never hold by name at admission; the limit is the operator's to know,
-             * in its own terms, with nothing about experts the model does not have. */
+            /* A hard limit, unlike the backing ratio (how much of every-sequence-at-max_ctx the
+             * pool backs, a provisioning choice reported in vram_budget.cpp): a pool that cannot
+             * hold one max-length sequence accepts requests that can never complete.
+             *
+             * For an image generator the sequence is a conditioning, which its driver refuses at
+             * admission; warn in those terms. */
             if (ranks_[0]->program.is_generator()) {
                 RAD_WARN("kv group '%s' holds %lld rows: a conditioning longer than that -- a "
                          "prompt with its pictures, up to %lld rows -- is refused. A picture "
@@ -3214,13 +2909,11 @@ int Engine::configure_kv() {
                          p->name.c_str(), (long long)cap, (long long)want);
                 continue;
             }
-            RAD_WARN("kv group '%s' holds %lld tokens but the context limit is %lld: ONE request "
-                     "longer than %lld tokens is accepted by the API and then refused as too "
-                     "large to ever fit -- this is a hard limit, not a backing ratio. Give the "
-                     "cache more (about %lld MiB for the whole context: a larger --host-pool-mib "
-                     "takes experts off the card), halve the cost a token with --kv-cache-dtype fp8, "
-                     "or lower "
-                     "--max-model-len to %lld.",
+            RAD_WARN("kv group '%s' holds %lld tokens but the context limit is %lld, so a "
+                     "prompt longer than %lld tokens is refused (400) and a reply that grows past "
+                     "it fails (kv_exhausted). Give the cache about %lld MiB "
+                     "more (a larger --host-pool-mib takes experts off the card), use "
+                     "--kv-cache-dtype fp8, or lower --max-model-len to %lld",
                      p->name.c_str(), (long long)cap, (long long)want, (long long)cap,
                      (long long)(((want - cap) / p->block_size * p->bytes_per_block) >> 20),
                      (long long)cap);
@@ -3229,77 +2922,17 @@ int Engine::configure_kv() {
     return RAD_OK;
 }
 
-/* The group pools, as the run phase addresses them. The operand names an ABSOLUTE model layer and
- * the pool holds only the layers bound to this group, so the binding carries the POSITION of each
- * absolute layer within the group -- a group covering layers 3,7,...,63 is sixteen caches and layer
- * 7 is the second, not the fifth, and subtracting the first bound layer says the fifth. */
-static void bind_kv_pools(const Program& p, const KVManager& kv, std::vector* out) {
-    out->assign(p.kv_groups.size(), KVPoolBinding{});
-    for (size_t g = 0; g < p.kv_groups.size(); ++g) {
-        const KVGroupPlan* gp = kv.plan((int32_t)g);
-        if (!gp) continue;
-        KVPoolBinding& b = (*out)[g];
-        b.base         = gp->base;
-        b.layer_stride = gp->layer_stride();
-        b.bytes        = gp->pool_bytes;
-        b.dtype        = p.kv_groups[g].decl.dtype;
-
-        /* The position of every bound layer, indexed by its absolute number. */
-        const std::vector& ls = p.kv_groups[g].layers;
-        int32_t hi = -1;
-        for (int32_t l : ls) if (l > hi) hi = l;
-        b.layer_slot.assign((size_t)(hi + 1), -1);
-        for (size_t i = 0; i < ls.size(); ++i) b.layer_slot[(size_t)ls[i]] = (int32_t)i;
-
-        /* The shape of ONE layer's cache, in the layout libref/ref_ops.h states for the whole
-         * project. Composed here because this is the only place that holds both halves of it: the
-         * plugin's declaration (heads, head_dim, state_dim, conv_width) and the block manager's
-         * decisions (block_size, n_blocks, n_states, conv_slots). A kernel cannot derive the conv
-         * window's depth or the slot count from any op parameter, so a flat span makes every shim
-         * that needs the structure refuse. */
-        const RadKVGroupDecl& d = p.kv_groups[g].decl;
-        switch (gp->kind) {
-        case RAD_KV_FULL:
-        case RAD_KV_WINDOW:
-            b.rank = 4;
-            b.shape[0] = gp->n_blocks;
-            b.shape[1] = d.n_head_kv;
-            b.shape[2] = gp->block_size;
-            b.shape[3] = 2 * d.head_dim;
-            break;
-        case RAD_KV_LINEAR:
-            b.rank = 4;
-            b.shape[0] = gp->n_states;
-            b.shape[1] = d.n_head_kv;
-            b.shape[2] = d.state_dim[0];
-            b.shape[3] = d.state_dim[1];
-            break;
-        case RAD_KV_CONV:
-            b.rank = 3;
-            b.shape[0] = gp->n_states;
-            b.shape[1] = d.n_head_kv * d.head_dim;
-            b.shape[2] = gp->conv_slots;
-            break;
-        default:
-            b.rank = 0;   /* the null sentinel at handle 0; nothing issues against it */
-            break;
-        }
-    }
-}
-
 /* ================================================================== start */
 int Engine::start() {
     std::vector devs;
     std::string inventory;
     std::string devnote;
-    /* Rank tags on the log from here down, so the pools, the planner, the mover and the sampler
-     * are each attributed to the card they are about. At tp 1 there is nothing to disambiguate. */
+    /* Rank tags on log lines from here on (see LogRank). */
     log_rank_tags(cfg_.tp > 1);
 
     std::vector dev_names;
     int s = usable_devices(&devs, &inventory, &devnote, &dev_names);
-    /* Before any refusal below, so a report printed for a startup that stopped here still joins
-     * the runtime's devices to the machine's cards. */
+    /* Before any refusal, so a failed startup's report still identifies the cards. */
     identify_devices(dev_names);
     if (!devnote.empty()) RAD_WARN("device: %s", devnote.c_str());
     devnote_ = devnote;
@@ -3316,14 +2949,13 @@ int Engine::start() {
         decide("--max-model-len", std::to_string(meta_.n_ctx_train),
                "the model's training context (--max-model-len 0)");
     RAD_TRY(load_vocab());
-    /* The cards are chosen, so a kernel library's device code is checked against the ones the
-     * ranks will run on and not against whichever device the backend happens to list first. */
+    /* Check kernel libraries' device code against the cards the ranks use, not device 0. */
     rad_tools_registry().set_code_device(devs[0]);
     rad_tools_registry().set_no_device_code(device_is_host());
     RAD_TRY(load_plugins());
     {
-        /* THE LIBRARIES THAT LOADED, in the order that decides selection: what --kernels named, or
-         * every library the home holds when it named none. */
+        /* The loaded libraries in selection order: as --kernels named them, or every library in
+         * the home. */
         std::string libs;
         for (const PluginId& p : plugins_.kernels)
             libs += (libs.empty() ? "" : ",") + p.name + (p.version.empty() ? "" : "@" + p.version);
@@ -3344,14 +2976,11 @@ int Engine::start() {
         ranks_.push_back(std::move(r));
     }
 
-    /* PEER ACCESS, MEASURED BEFORE ANYTHING IS SELECTED. A kernel that reads or writes another
-     * card's memory says so with a constraint on device.p2p (rad_types.h), and the selector reads
-     * it from here: on a machine where some pair of the ranks' cards cannot reach each other such a
-     * kernel is not selected, and one that exchanges through host memory takes the op instead (or
-     * declare names the constraint) rather than the all-reduce faulting or hanging on its first
-     * message. Every ordered pair, because access is granted one way at a time. --p2p overrides the
-     * answer in one direction each way (Config::p2p): off turns it down whatever the driver says,
-     * on refuses to start without it. */
+    /* Peer access, measured before selection. Kernels that touch another card's memory constrain
+     * device.p2p (rad_types.h); if any pair of the ranks' cards cannot reach each other, they are
+     * not selected and a host-memory variant takes the op (or declare names the constraint),
+     * rather than an all-reduce faulting or hanging. Every ordered pair is checked, since access is
+     * granted one way at a time. --p2p off forces it off; --p2p on refuses to start without it. */
     {
         long long p2p = 1;
         std::string blocked;
@@ -3404,19 +3033,15 @@ int Engine::start() {
 
     RAD_TRY(declare());
 
-    /* --debug-graph stops here on purpose: everything it prints is known between declare and
-     * plan, and a graph dump that first has to fit the model in VRAM is a graph dump you cannot
-     * run on the machine where the model does not fit. */
+    /* --debug-graph stops here: everything it prints is known after declare, and it must work on
+     * a machine where the model does not fit. */
     if (cfg_.debug_graph) return RAD_OK;
 
-    /* Before anything is placed or mapped. A container whose ops resolve to the reference
-     * implementation is a container that will serve at reference speed, and that is a decision the
-     * operator makes rather than one the engine discovers three minutes into a load. */
+    /* Before anything is placed or loaded, so serving at reference speed is refused up front. */
     RAD_TRY(rad_gate_reference_kernels(ranks_[0]->program, cfg_.accept_reference_kernels, "serve"));
     {
-        /* WHAT SELECTION CHOSE, in two lines a reader can compare across machines: how many of the
-         * declared op bands each library serves, and the attention rows by name -- the family whose
-         * choice moves with the card, the head width and the context. */
+        /* Selection summary for the report: op bands served per library, and the attention rows by
+         * name (the family whose choice varies with card, head width and context). */
         std::map by_lib;
         std::set attn;
         for (const OpInfo& op : ranks_[0]->program.ops)
@@ -3441,40 +3066,43 @@ int Engine::start() {
 
     for (auto& r : ranks_) {
         LogRank lr(r->index);
-        RAD_TRY(rad_dev_set(r->device));   /* allocates on the CURRENT device; see plan() */
+        RAD_TRY(rad_dev_set(r->device));   /* allocates on the current device; see plan() */
         CtxDesc d{};
         d.program     = &r->program;
         d.rank        = r->index;
         d.world_size  = cfg_.tp;
         d.device      = r->device;
-        /* Null in the all-in-VRAM case: the degenerate one where the planner assigned everything
-         * to tier 0 and the mover never runs, and lookup collapses to WeightInfo::ptr. */
+        /* Null for all-in-VRAM: the mover never runs and lookup uses WeightInfo::ptr. */
         d.residency   = r->plan.strategy == Strategy::AllVram ? nullptr : r->mover.residency();
         d.arch_step   = arch_step_;
         d.profile_ops = cfg_.profile_ops;
-        bind_kv_pools(r->program, r->kv, &d.kv);
+        bind_kv_pools(r->program, [&](int32_t g) { return r->kv.plan(g); }, &d.kv);
+        d.registry    = &rad_tools_registry();
         RAD_TRY(r->ctx.init(d));
 
-        /* THE MOVER NEEDS THE COMPUTE STREAM.
-         *
-         * Every transfer is ordered against the kernels that read the slot it targets, through an
-         * event recorded on the compute stream once per dispatch (Mover::record_gate). With no
-         * stream bound that function returns RAD_E_STATE, so a mover asked to move anything
-         * refuses. The bind belongs here rather than in load_weights: Ctx owns the stream and does
-         * not create it until init(), and the load runs on its own copy stream.
-         *
-         * Not under `if (d.residency)`: a plan can be static and still stage a file-tier weight
-         * on demand, and a mover that is bound but idle costs one pointer. */
+        /* The mover orders every transfer against the kernels reading its slot via an event on the
+         * compute stream (Mover::record_gate), which exists only after Ctx::init. Bound even for a
+         * static plan, which may still stage file-tier weights on demand. */
         RAD_TRY(r->mover.bind_compute_stream(r->ctx.stream()));
 
-        /* THE PREFILL STAGER, where the budget made room for it: a step larger than every smaller
-         * arena level is the only one that finds the region unlent, so that is the smallest pass
-         * it arms for. */
+        /* The prefill stager, where the budget made room. Only a step larger than every smaller
+         * arena level finds the region unlent, so that is the smallest pass it arms for. */
         if (r->program.arena_stage_bytes > 0 && r->plan.dynamic && !r->arena_levels.empty()) {
+            /* The smallest pass is one past every level that lends the ring. The span's shared
+             * level does not: it keeps its own place for it, right above its buffers and the
+             * guard, wherever that is below the region at the top (stager.h). */
             int64_t top_level = 0;
-            for (const ArenaLevel& lv : r->arena_levels) top_level = std::max(top_level, lv.rows);
+            r->arena_low_off = -1;
+            for (const ArenaLevel& lv : r->arena_levels) {
+                if (lv.rows != arena_span_rows_) { top_level = std::max(top_level, lv.rows); continue; }
+                const int64_t off = (lv.end + kArenaGuard + RAD_ALIGN_UNIT - 1) /
+                                    RAD_ALIGN_UNIT * RAD_ALIGN_UNIT;
+                r->arena_low_off = std::min(off, r->program.arena_stage_off);
+            }
+            char* const base = (char*)r->ctx.arena_base();
             RAD_TRY(r->stager.init(r->program, r->plan, &r->mover,
-                                   (char*)r->ctx.arena_base() + r->program.arena_stage_off,
+                                   base + r->program.arena_stage_off,
+                                   r->arena_low_off >= 0 ? base + r->arena_low_off : nullptr,
                                    r->program.arena_stage_bytes, top_level + 1));
             if (r->stager.enabled() && r->index == 0)
                 RAD_INFO("prefill staging: a %s ring at the top of the arena; a step of more "
@@ -3483,8 +3111,8 @@ int Engine::start() {
                          humanb(r->stager.ring_bytes()).c_str(), (long long)top_level,
                          r->stager.n_layers(), (int)PrefillStager::lead());
         }
-        /* THE FILE STAGER, wherever the plan put a routed expert on the file tier -- static plan
-         * or dynamic, since a file-tier unit has no other address. */
+        /* The file stager, wherever a routed expert is on the file tier (static or dynamic plan;
+         * such a unit has no other address). */
         RAD_TRY(r->fstager.init(r->program, r->plan, &r->mover));
         if (r->fstager.enabled() && r->index == 0)
             RAD_INFO("file stager: %zu routed layers hold experts read from the container; each "
@@ -3501,14 +3129,12 @@ int Engine::start() {
         }
 
     }
-    /* ---- THE LOAN: the cache's idle blocks, lent to the expert slab in place ----------------
+    /* ---- the loan: the cache's idle blocks, lent to the expert slab in place -----------------
      *
-     * Here and not earlier because it needs both halves: the cache's carve fixes the addresses and
-     * the mover's compute stream is what a recall drains. Every rank lends its own pool's strips --
-     * the same geometry on every card -- and only a plan that moves units borrows at all.
-     *
-     * A STRIP IS ONE LAYER'S STRIPE OF ONE LENDABLE GROUP, top down, because that is how the cache
-     * lends: the top blocks of a group are the top of every layer's stripe at once. */
+     * Here because it needs the cache's carve (the addresses) and the mover's compute stream
+     * (which a recall drains). Every rank lends its own pool, same geometry on every card; only a
+     * plan that moves units borrows. A strip is one layer's stripe of one lendable group, lent
+     * from the top, since a group's top blocks are the top of every layer's stripe. */
     for (auto& r : ranks_) {
         if (!r->heat.enabled()) continue;
         RAD_TRY(rad_dev_set(r->device));
@@ -3528,9 +3154,9 @@ int Engine::start() {
         RAD_TRY(r->mover.lend_from(Mover::kLendKV, strips));
         if (r->mover.flex_capacity() > 0) lending_ = true;
     }
-    /* THE NEXT-LAYER EXPERT PREFETCH, wherever the placement left experts in a pinned pool for a
-     * routed layer's GEMMs to read across the link (core/runtime/xprefetch.h). Its stream and ring are
-     * in the VRAM budget (xp_device_bytes, Engine::plan). Not under --deterministic, where nothing moves. */
+    /* The next-layer expert prefetch, wherever experts sit in a pinned pool for routed GEMMs to
+     * read over the link (core/runtime/xprefetch.h). Its stream and ring are in the VRAM budget
+     * (xp_device_bytes, Engine::plan). Off under --deterministic. */
     if (!cfg_.deterministic)
         for (auto& r : ranks_) {
             RAD_TRY(rad_dev_set(r->device));
@@ -3540,11 +3166,10 @@ int Engine::start() {
         }
     (void)rad_dev_set(ranks_[0]->device);
 
-    /* THE MOST THE CACHE CAN HOLD, said once in one line: the whole carve, with every block it lends
-     * the experts taken back -- which a request that needs them does, the same step. Tokens are the
-     * paged groups' shared axis, so the smallest of theirs; a windowed group bounds how far back a
-     * sequence keeps context, not how much fits, and is left out. The /stats and /metrics figures
-     * (kv_tokens_max, radiance:kv_cache_max_tokens) are the same numbers. */
+    /* The most the cache can hold: the whole carve, including lent blocks (a request reclaims them
+     * in the same step). Tokens are the smallest over the full paged groups; a windowed group
+     * bounds history, not capacity. /stats and /metrics report the same numbers (kv_tokens_max,
+     * radiance:kv_cache_max_tokens). */
     {
         const KVManager& kv = ranks_[0]->kv;
         int64_t bytes = 0, state = 0, tokens = 0;
@@ -3578,20 +3203,16 @@ int Engine::start() {
                               : "nothing is lent: it is all the cache's");
     }
 
-    /* ---- AND THE TOP OF THE ACTIVATION ARENA, lent while the steps are small ----------------
+    /* ---- the top of the activation arena, lent while steps are small ----------------------
      *
-     * One stretch a rank: from the end of the full plan's transients down to the end of the
-     * smallest level's, less a guard. A level lends everything above its own end and guard, so the
-     * loan is stated in bytes from the top -- the measure every level can say in one number. Each
-     * rank lends its own arena, whose plan may differ from rank 0's by the buffers only one rank
-     * declares, so each rank's amounts are its own.
+     * One stretch per rank, from the arena top down to the smallest level's end plus a guard. Each
+     * level lends everything above its end and guard, stated in bytes from the top. Ranks' plans
+     * can differ, so each rank's amounts are its own.
      *
-     * THE GUARD is a mebibyte between a level's highest buffer and the lent memory: what a kernel
-     * writes past the rows it was given lands there rather than in an expert's weights, which
-     * would stay corrupt for as long as the unit stayed resident. */
+     * The guard (1 MiB) catches a kernel writing past its rows, which would otherwise corrupt a
+     * resident expert's weights. */
     arena_rows_.clear();
     if (!ranks_.empty() && !ranks_[0]->arena_levels.empty() && ranks_[0]->heat.enabled()) {
-        static constexpr int64_t kGuard = 1ll << 20;
         bool ok = true;
         for (auto& r : ranks_) {
             RAD_TRY(rad_dev_set(r->device));
@@ -3600,8 +3221,14 @@ int Engine::start() {
             const int64_t top = P.arena_bytes;
             for (const ArenaLevel& lv : r->arena_levels) {
                 if (r->ctx.add_level(lv.rows, lv.offset, lv.decl) < 0) { ok = false; break; }
-                const int64_t edge = (lv.end + kGuard + RAD_ALIGN_UNIT - 1) /
-                                     RAD_ALIGN_UNIT * RAD_ALIGN_UNIT;
+                /* The span's shared level keeps the stager's ring above its buffers: it lends
+                 * what is above the ring. */
+                const bool ring = lv.rows == arena_span_rows_ && r->arena_low_off >= 0 &&
+                                  r->stager.enabled();
+                const int64_t edge = ring
+                    ? (r->arena_low_off + P.arena_stage_bytes + RAD_ALIGN_UNIT - 1) /
+                          RAD_ALIGN_UNIT * RAD_ALIGN_UNIT
+                    : (lv.end + kArenaGuard + RAD_ALIGN_UNIT - 1) / RAD_ALIGN_UNIT * RAD_ALIGN_UNIT;
                 r->arena_lent.push_back(top > edge ? top - edge : 0);
             }
             if (!ok) break;
@@ -3630,11 +3257,10 @@ int Engine::start() {
             for (auto& r : ranks_) r->arena_lent.clear();
         }
     }
-    /* A RECALL THAT CANNOT WAIT. When a request needs more of the cache than it kept in hand, rank
-     * 0's cache calls this from the scheduler, between dispatches, with every rank thread parked:
-     * each rank's slab is drained to the loan the cache can still afford before the blocks are
-     * handed out, and every follower's mark moves with rank 0's at once rather than at the next
-     * step's build -- a tier restore on a follower picks the id rank 0 just chose. */
+    /* Immediate recall: when a request needs more cache than is in hand, rank 0's cache calls this
+     * from the scheduler between dispatches, with every rank thread parked. Each rank's slab is
+     * drained to the affordable loan before the blocks are handed out, and the followers' marks
+     * move at once (a tier restore on a follower uses the id rank 0 just chose). */
     if (lending_)
         ranks_[0]->kv.set_reclaim([this](int64_t tokens) -> int {
             int st = RAD_OK;
@@ -3652,10 +3278,8 @@ int Engine::start() {
             return st;
         });
 
-    /* WHAT THE CORE SPENT, beside what the card says was spent. The two differ by exactly the
-     * allocations the core does not make: the driver's context, its code objects, and any kernel
-     * plugin that calls hipMalloc for itself. Naming the difference is the only way to tell a
-     * budget that is wrong from a plugin that is spending behind it. */
+    /* What the core allocated, to compare with the card's usage; the difference is the driver's
+     * context and code objects and any plugin's own hipMalloc. */
     {
         int64_t dev_bytes = 0, dev_count = 0;
         rad_dev_alloc_totals(RAD_MEM_DEVICE, &dev_bytes, &dev_count);
@@ -3670,30 +3294,21 @@ int Engine::start() {
 
     RAD_TRY(step_state_init());
 
-    /* ---- THE BUDGET, CHECKED AGAINST THE CARD IT WAS SPENT ON ----------------------------------
+    /* ---- the budget, checked against the card --------------------------------------------
      *
-     * Everything above this line allocated: the two pools, the activation arena, the step batch
-     * staging, the weight tables a grouped GEMM walks. What is left on the card should now be
-     * --gpu-headroom-mib plus what the budget kept for later, and this is the only place that can
-     * say whether it is.
+     * Everything is allocated now (pools, arena, step staging, grouped-GEMM weight tables), so the
+     * card should have --gpu-headroom-mib plus what the budget kept for later.
      *
-     * TOO LITTLE is memory taken after the budget read the card that the budget did not count:
-     * another process on the card (a desktop, a second server), or a driver allocation made
-     * after the reading. It comes out of the room a kernel's first launch allocates its code
-     * object and scratch from, and running out of that is a fault inside the HIP runtime.
+     * Too little means memory taken after the budget's reading (another process, a late driver
+     * allocation). It comes out of the room a kernel's first launch needs for its code object and
+     * scratch, and running out faults inside the HIP runtime.
      *
-     * THE WARNING IS ON THE ROOM, NOT ON THE FLAG. Raising --gpu-headroom-mib raises what is left
-     * here and what this compares it with by the same amount, so a check of free memory against
-     * the flag can never be satisfied by the flag: the gap is whatever was taken after the
-     * reading, and it is there at every value. The room a first launch has -- what is free less
-     * what the budget kept for later -- is what the flag actually moves, and it is held against
-     * this engine's own allowance for its first launches (the flag's default). A card short of
-     * that is warned with the value that clears it; one that kept the allowance but lost part of
-     * a larger stated headroom says so on its INFO line.
+     * The warning tests the room (free less what is kept for later) against the engine's own
+     * first-launch allowance (the flag's default), not free memory against the flag, which would
+     * move both sides equally. A short card is warned with the flag value that fixes it.
      *
-     * TOO MUCH means the budget left VRAM on the floor, which on a model whose experts do not
-     * fit is milliseconds of decode step for every unspent GiB. A slack of 256 MiB is tolerated
-     * silently: MiB rounding and a kernel plugin's own workspaces live in there. */
+     * Too much means VRAM left unused, costly when experts do not fit; up to 256 MiB of slack
+     * (MiB rounding, plugin workspaces) is silent. */
     const int64_t MiB = 1024 * 1024;
     const int64_t headroom = std::max(cfg_.gpu_headroom_mib, 0) * MiB;
     const int64_t allowance = Config{}.gpu_headroom_mib * MiB;
@@ -3703,9 +3318,8 @@ int Engine::start() {
         RadDeviceProps props{};
         if (rad_dev_props(r->device, &props) < 0 || props.vram_bytes <= 0) continue;
 
-        /* AGAINST THE HEADROOM AND WHAT THE BUDGET KEPT FOR LATER, because both are still free
-         * here: the step staging is allocated by serve(), and the KV tiers' staging and a second
-         * compute lane are built on first use. */
+        /* Both the headroom and the later allocations are still free here: serve() allocates
+         * the step staging; the KV tiers' staging and a second lane are built on first use. */
         const int64_t late = late_step_bytes_ + late_lazy_bytes_;
         const int64_t want = headroom + late;
         const int64_t got  = props.vram_free;
@@ -3736,12 +3350,9 @@ int Engine::start() {
                      r->device, humanb(got).c_str(), asked.c_str(), humanb(want - got).c_str(),
                      humanb(room).c_str());
         } else if (got > want + 256 * MiB) {
-            /* "TOO MUCH" IS NOT A FAULT: the resolver made the split, and what is left is left
-             * because neither pool could address another byte -- a small dense model already at
-             * the largest context its cache can hold leaves most of the card -- and vram_budget.cpp
-             * printed it on the `unusable` line. A rank plan() re-split for the common token count
-             * also leaves what its weights could not use, and the `kv: rank N ...` line said how
-             * much. */
+            /* Not a fault: neither pool could use more (e.g. a small dense model at its largest
+             * context), reported on vram_budget.cpp's `unusable` line, or a re-split rank's
+             * unusable remainder (the `kv: rank N ...` line). */
             const int64_t unclaimed_mib =
                 (cfg_.vram_weights_mib + cfg_.vram_kv_mib) -
                 (rank_cfg_[ri].vram_weights_mib + rank_cfg_[ri].vram_kv_mib);
@@ -3767,72 +3378,22 @@ int Engine::start() {
 const Program& Engine::program() const { return ranks_[0]->program; }
 
 /* ================================================================== dump */
-/* The answer to "it is unclear what even runs" (spec §16). It is a first-class mode rather than a
- * side effect of a verbose flag, because that is the complaint this project exists to answer. */
+/* --debug-graph (spec §16); see Engine::dump in engine.h. */
 int Engine::dump() {
     Program& p = ranks_[0]->program;
     fputs(dump_graph_str(p, nullptr).c_str(), stdout);
     if (cfg_.debug_selection) fputs(rad_tools_registry().selection_table().c_str(), stdout);
-    /* The exit code answers "is there a hole a request can fall into", by the rule declare()
-     * refuses to serve on (Program::device_holes, miss_report()): a device band no kernel
-     * resolved, unless a host kernel stands in for an op whose weights the planner can place on
-     * the host. A host miss is not one. */
+    /* The exit code reports device holes by declare()'s rule (Program::device_holes). */
     for (auto& r : ranks_)
         if (!r->program.device_holes(device_is_host()).empty()) return RAD_E_NOKERNEL;
     return RAD_OK;
 }
 
 /* ================================================================== 6c. the vocabulary */
-/* The sampler needs three facts about a token plus the ability to tokenise a short literal; the
- * text frontend has a whole Vocab. vocab_view.h says core/text implements the view over the real
- * vocabulary; core/text does not, so the adapter is here, where the two are wired together and
- * nowhere else. It belongs in core/text the moment a second caller wants it. */
-namespace {
-class RealVocabView final : public VocabView {
-public:
-    int init(std::shared_ptr v) {
-        v_ = std::move(v);
-        RAD_TRY(tok_.init(v_));
-        /* token_piece returns a reference, so the pieces have to outlive the call. Building them
-         * once costs one pass over the vocabulary and saves a string construction per candidate
-         * token per grammar step, which is host work on the step path.
-         *
-         * piece(), NOT Vocab::text(). text() is the vocab's OWN encoding -- for a byte-level BPE
-         * that is the GPT-2 mapped alphabet, where a space is 'Ġ' (U+0120) and a newline is 'Ċ'.
-         * piece() runs the declared decoder chain, which is what actually reaches the output
-         * stream, and vocab_view.h asks for exactly that. Handing the grammar the mapped form
-         * makes mask and accept consistently wrong, so nothing throws: every token containing a
-         * space or a newline is simply forbidden by every grammar. render_special is TRUE
-         * because the alternative gives a control token an empty piece, and an empty piece
-         * consumes nothing and so satisfies any grammar position. */
-        pieces_.resize((size_t)v_->n_tokens());
-        for (int32_t i = 0; i < v_->n_tokens(); ++i)
-            pieces_[(size_t)i] = tok_.piece(i, /*render_special=*/true);
-        return RAD_OK;
-    }
-    int32_t n_tokens() const override { return v_ ? v_->n_tokens() : 0; }
-    const std::string& token_piece(int32_t id) const override {
-        static const std::string kEmpty;
-        return (id >= 0 && (size_t)id < pieces_.size()) ? pieces_[(size_t)id] : kEmpty;
-    }
-    bool is_eog(int32_t id) const override { return v_ && v_->is_eog(id); }
-    int  tokenize(const std::string& s, std::vector* out) const override {
-        return out ? tok_.encode(s, *out, /*add_special=*/false, /*parse_special=*/false)
-                   : RAD_E_INVAL;
-    }
-    int  tokenize_special(const std::string& s, std::vector* out) const override {
-        return out ? tok_.encode(s, *out, /*add_special=*/false, /*parse_special=*/true)
-                   : RAD_E_INVAL;
-    }
-private:
-    std::shared_ptr v_;
-    Tokenizer                    tok_;
-    std::vector     pieces_;
-};
-}  /* namespace */
 
-/* The container carries the vocabulary and nothing else is consulted. A .rad without one cannot
- * serve text, and says so here rather than at the first request (spec §4.1, §12). */
+/* The vocabulary comes from the model source: the container's vocab section, a GGUF header, or
+ * tokenizer.json beside a checkpoint. A missing one is refused here rather than at the first
+ * request (spec §4.2, §12). */
 int Engine::load_vocab() {
     VocabBuild vb;
     if (file_) {
@@ -3844,22 +3405,23 @@ int Engine::load_vocab() {
         }
         RAD_TRY(vocab_deserialize(file_->base(), (uint64_t)file_->size(), vs.h, vb));
     } else if (ckpt_->is_gguf()) {
-        /* GGUF names its pre-tokeniser and the chain is reconstructed from the name, or refused
-         * where it cannot be -- a container converted with --tokenizer bakes the declared one. */
+        /* GGUF names its pre-tokeniser; the chain is reconstructed from the name or refused (a
+         * container converted with --tokenizer bakes in the declared one). */
         RAD_TRY(vocab_from_gguf(ckpt_->gguf(), vb));
     } else {
-        /* beside config.json, with tokenizer_config.json and chat_template.jinja */
-        const std::string tj = ckpt_->dir() + "/tokenizer.json";
+        /* With tokenizer_config.json and chat_template.jinja: beside config.json in a model
+         * repository, in a diffusers pipeline's processor/ or tokenizer/ folder. */
+        const std::string tj = ckpt_->tok_dir() + "/tokenizer.json";
         if (parse_tokenizer_json(tj.c_str(), vb) < 0) {
-            RAD_ERR("%s: no readable tokenizer.json beside the checkpoint", cfg_.model.c_str());
+            RAD_ERR("%s: no readable tokenizer.json in %s", cfg_.model.c_str(),
+                    ckpt_->tok_dir().c_str());
             return RAD_E_FORMAT;
         }
     }
 
-    /* THE OPERATOR'S TEMPLATE REPLACES THE CONTAINER'S before anything reads it, so the chat
-     * endpoint and the reply format derived from the template agree about which one is served. An
-     * unreadable or empty file is refused: serving the container's template in its place would be
-     * the silent fallback the flag exists to rule out. */
+    /* The operator's template replaces the container's before anything reads it, so the chat
+     * endpoint and the derived reply format agree. An unreadable or empty file is refused rather
+     * than silently falling back. */
     if (!cfg_.override_chat_template.empty()) {
         std::ifstream f(cfg_.override_chat_template);
         if (!f) {
@@ -3870,8 +3432,8 @@ int Engine::load_vocab() {
         std::ostringstream ss;
         ss << f.rdbuf();
         std::string t = ss.str();
-        /* Trailing newlines go, as they do for a checkpoint's own chat_template.jinja, so one file
-         * renders the same prompt whichever way it reaches the server. */
+        /* Strip trailing newlines, as for a checkpoint's chat_template.jinja, so the same file
+         * renders the same prompt either way. */
         while (!t.empty() && (t.back() == '\n' || t.back() == '\r')) t.pop_back();
         if (t.find_first_not_of(" \t\r\n") == std::string::npos) {
             RAD_ERR("--override-chat-template %s: the file is empty",
@@ -3884,8 +3446,8 @@ int Engine::load_vocab() {
         vb.chat_template = std::move(t);
     }
 
-    /* The checkpoint's own end-of-generation list travels as metadata, flattened from
-     * generation_config.json -- a space-separated list, or one id. */
+    /* The checkpoint's end-of-generation ids, flattened from generation_config.json into metadata
+     * as a space-separated list or one id. */
     if (const char* ids = rad_meta_gets(&meta_, "generation.eos_token_id", nullptr)) {
         const char* q = ids;
         while (*q) {
@@ -3901,16 +3463,15 @@ int Engine::load_vocab() {
     RAD_TRY(v->load(std::move(vb)));
     vocab_ = v;
 
-    auto view = std::make_unique();
+    auto view = std::make_unique();
     RAD_TRY(view->init(vocab_));
     vocab_view_ = std::move(view);
 
     RAD_INFO("vocab: %d tokens, bos=%d eos=%d%s", vocab_->n_tokens(), vocab_->bos(), vocab_->eos(),
              vocab_->chat_template().empty() ? ", no chat template" : "");
 
-    /* THE GRAMMAR ENGINE'S VOCABULARY INDEX, built here rather than by the first request that
-     * carries a grammar -- a tool-calling template gives nearly every agent request one -- so
-     * that request's admission pays only for its own grammar. */
+    /* Build the grammar engine's vocabulary index now rather than on the first grammar request
+     * (nearly every tool-calling request has one), so admission pays only for its own grammar. */
     GbnfVocabInfo gi;
     const int gs = gbnf_prepare_vocab(vocab_view_.get(), &gi);
     if (gs < 0) {
diff --git a/core/engine_diag.cpp b/core/engine_diag.cpp
index 6941acae..25f6b80a 100644
--- a/core/engine_diag.cpp
+++ b/core/engine_diag.cpp
@@ -1,9 +1,8 @@
-/* engine_diag.cpp -- the startup report's engine half: the facts only a started engine has, joined
- * to the machine's (core/diag/diag.h).
+/* engine_diag.cpp -- the startup report's engine half: facts only a started engine has, joined to
+ * the machine's (core/diag/diag.h).
  *
- * THE CARDS ARE JOINED BY PCI ADDRESS. The runtime numbers its devices its own way -- a visible-
- * device mask renumbers them, an integrated GPU may come first -- and the kernel describes them by
- * bus address; the backend's pci_address is the one key both sides agree on.
+ * Cards are joined by PCI address: the runtime numbers devices its own way (a visibility mask
+ * renumbers them, an integrated GPU may come first), while the kernel names them by bus address.
  */
 #include "engine_priv.h"
 #include "device/device.h"
@@ -81,9 +80,9 @@ diag::RunFacts Engine::run_facts(bool failed) const {
         rad_dev_alloc_totals(RAD_MEM_HOST_MAPPED, &mapped, &n);
         r.pinned_bytes = pinned + mapped;
     }
-    /* THE MOST ANY RANK READS FROM THE HOST: the ranks step together, so the one that streams most
-     * is the one each step waits for. The embedding the placement flag put in host memory is read
-     * a few rows a step, the encoder towers once an image, and neither is what this counts. */
+    /* The most any rank streams from the host, since each step waits for the slowest rank.
+     * Excludes host-placed tables (the embedding, read a few rows per step; the towers, once per
+     * image). */
     for (const auto& rk : ranks_) {
         const Plan& p = rk->plan;
         const int64_t host = p.totals.bytes[(int)Tier::HostPinned] +
@@ -115,8 +114,8 @@ void Engine::print_startup_report(int status) {
     const diag::Facts f = hardware_facts(false);
     const diag::RunFacts r = run_facts(status < 0);
     const std::vector found = diag::check(f, r);
-    /* A LINE A LOG CALL: the logger formats into a fixed buffer, and one line each keeps every line
-     * of the report on the same level tag a grep for the startup reads. */
+    /* One log call per line: the logger formats into a fixed buffer, and every line keeps the
+     * level tag. */
     const std::string text = diag::render(rows, derived, f, r, found);
     size_t at = 0;
     while (at < text.size()) {
@@ -125,13 +124,11 @@ void Engine::print_startup_report(int status) {
         RAD_INFO("%s", text.substr(at, nl - at).c_str());
         at = nl + 1;
     }
-    /* AND EACH WARNING ON A W LINE OF ITS OWN, because the warnings are what a reader filtering a
-     * production log for W and E lines is looking for. */
+    /* Each warning also on its own W line, for readers filtering a log by level. */
     for (const diag::Finding& x : found)
         if (x.level == diag::Finding::Warn)
             RAD_WARN("startup report: %s: %s. Fix: %s", x.id.c_str(), x.what.c_str(), x.fix.c_str());
-    /* THE FAILURE LAST. The line that said what stopped startup is above the report now, and
-     * `docker logs --tail` or a terminal's last screen shows only what is below it. */
+    /* Repeat the failure last, since the original error line is now above the report. */
     if (status < 0)
         RAD_ERR("startup stopped: %s (the reason is said above the startup report)",
                 rad_strerror(status));
diff --git a/core/engine_draft.cpp b/core/engine_draft.cpp
index 09bb306f..61a12d26 100644
--- a/core/engine_draft.cpp
+++ b/core/engine_draft.cpp
@@ -1,12 +1,8 @@
 /* engine_draft.cpp -- the two drafter drivers (spec §10).
  *
- * A draft head runs as EXTRA PASSES after the trunk step has been sampled and committed, and
- * there are two shapes of it: SERIAL runs `depth` dependent passes, BLOCK runs a context pass and
- * then one pass that fills the whole block. Which one this program has is what the architecture
- * plugin DECLARED (rad_declare_drafter); nothing in this file knows what model it is.
- *
- * Split out of the step loop's file because both drivers are the same idea from the loop's point
- * of view -- one call after commit -- and neither is on the trunk path. See engine_priv.h.
+ * A draft head runs as extra passes after the trunk step. SERIAL runs `depth` dependent passes;
+ * BLOCK runs a context pass, then one pass that fills the whole block. The architecture plugin
+ * declares which (rad_declare_drafter); nothing here depends on the model.
  */
 #include "engine_priv.h"
 
@@ -16,7 +12,6 @@
 #include 
 #include 
 #include 
-#include 
 #include 
 #include 
 #include 
@@ -24,8 +19,8 @@
 namespace rad {
 
 /* ------------------------------------------------------------------ the card's step state */
-/* Every rank's StepSlots, zeroed, and its sorted end-of-generation ids; and the pinned host copy
- * of rank 0's slots that the step reads back. Once, at start: nothing on the step path allocates. */
+/* Every rank's zeroed StepSlots and sorted end-of-generation ids, and the pinned host copy of rank
+ * 0's slots the step reads back. Allocated once at start, so the step path never allocates. */
 int Engine::step_state_init() {
     std::vector eog;
     if (vocab_) eog = vocab_->eog();
@@ -73,41 +68,27 @@ void Engine::step_state_fini() {
 
 /* ------------------------------------------------------------------ the serial driver
  *
- * `RAD_DRAFT_SERIAL`: one forward pass of the head per drafted token, after the trunk step. Round 1
- * consumes the token the sampler chose and the hidden state of the position that token came from,
- * and which position that is depends on how many drafts the verify accepted. Its pass is the
- * history pass, which the head runs anyway and whose rows already include that position
- * (RadBatch::draft_out_ids).
+ * RAD_DRAFT_SERIAL: one head pass per drafted token after the trunk step (MTP, EAGLE, Medusa).
+ * Round 1 consumes the sampled token and the hidden state of the position it came from, which
+ * depends on how many drafts were accepted; it runs in the history pass, whose rows include that
+ * position (RadBatch::draft_out_ids).
  *
- * THE CARD DECIDES THAT, NOT THE HOST (sched/advance.h). Behind the trunk's sampler every rank
- * runs the acceptance itself and keeps what it implies in its StepSlots; every draft pass is then
- * staged with its positions and tokens left to the card, and an advance in front of the pass fills
- * them in. So the host issues the whole step -- trunk, history, every round -- without waiting for
- * any of it, and reads the step back once, after the last round. Reading the sampled ids back and
- * staging round 1 from them instead would leave the card idle for a wake, a readback, a commit and
- * a batch build on every step.
+ * The card, not the host, resolves those positions (sched/advance.h): behind the trunk's sampler
+ * every rank runs the acceptance into its StepSlots, and an advance before each draft pass fills
+ * in its positions and tokens. So the host issues the whole step (trunk, history, every round)
+ * without waiting and reads back once after the last round, instead of idling the card for a
+ * readback, commit and batch build per step.
  *
- * Every pass is an ordinary step: a RadBatch run through the same barrier and the same sampler
- * chain. What makes it a draft pass is `draft_pass`, which the architecture plugin reads to run
- * the head instead of the trunk.
- *
- * The tokens go out through set_draft(), the same door the prompt-lookup drafter uses, so the
- * next step cannot tell them apart -- and a sequence the head declined leaves n_draft at 0,
- * which is exactly the case where the n-gram drafter gets its turn.
- *
- * NOTHING HERE NAMES A MODEL. An MTP head has this shape, and an EAGLE or Medusa head declares
- * RAD_DRAFT_SERIAL and runs on it unchanged.
+ * Each pass is an ordinary RadBatch through the same barrier and sampler chain; `draft_pass`
+ * tells the plugin to run the head. Tokens go out through set_draft(), like prompt lookup's; a
+ * sequence the head declined keeps n_draft 0, leaving it to the n-gram drafter.
  */
 bool Engine::serial_drafting() const {
-    /* THE BISECT KNOB COVERS BOTH DRIVERS. RADIANCE_NO_DRAFT means "propose nothing" -- it is
-     * how a speculative deployment is compared against itself with the drafts taken out, which
-     * separates "is the deferred state right" from "is the rollback right". */
-    static const bool no_draft = std::getenv("RADIANCE_NO_DRAFT") != nullptr;
-    return drafter_.kind == RAD_DRAFT_SERIAL && drafter_.depth > 0 && !no_draft;
+    return drafter_.kind == RAD_DRAFT_SERIAL && drafter_.depth > 0;
 }
 
-/* One advance on every rank, against the build the scheduler just produced -- over its first
- * `rows` rows when that is given, and all of them otherwise. */
+/* One advance on every rank against the scheduler's latest build, over its first `rows` rows
+ * when given, else all. */
 int Engine::advance_all(int mode, int round, bool from_proposal, int rows) {
     for (size_t i = 0; i < ranks_.size(); ++i) {
         Rank& rk = *ranks_[i];
@@ -136,46 +117,35 @@ int Engine::advance_all(int mode, int round, bool from_proposal, int rows) {
     return RAD_OK;
 }
 
-/* THE STEP'S DRAFT PASSES, ISSUED BEHIND IT WITHOUT WAITING FOR IT. Called once the trunk step's
- * ranks have joined: acceptance on every rank, the sampled ids on their way to the host before a
- * draft round can overwrite them, then the history pass and every round, and last the final
- * proposal into the slots and the slots on their way back. Nothing here synchronises; the step's
- * one wait is collect_step's. */
-int Engine::issue_serial_drafter(int step, const RadBatch* b, StepOut& so) {
+/* Issue the step's draft passes behind it, without waiting. After the trunk's ranks join: the
+ * acceptance on every rank, the sampled-id readback (before a round can overwrite them), the
+ * history pass and every round, then the final proposal into the slots and their readback.
+ * Nothing synchronises here; collect_step has the step's one wait. */
+int Engine::issue_serial_drafter(int step, StepOut& so) {
     serial_rounds_ = 0;
     serial_rows_   = 0;
     serial_done_   = 0;
-    /* A step that may be followed by one issued ahead needs the card's acceptance whether or not
-     * anything drafts: that step's rows continue from it. */
+    /* A step issued ahead continues from the card's acceptance, so run it even without drafts. */
     if (!serial_drafting()) {
         if (pipelining_) RAD_TRY(advance_all(ADV_ACCEPT, 0, false));
         return RAD_OK;
     }
 
     RAD_TRY(advance_all(ADV_ACCEPT, 0, false));
-    RAD_TRY(collect_issue(b, so));
+    RAD_TRY(collect_issue(so));
 
     int rounds = drafter_.depth;
     serial_row_.resize((size_t)cfg_.max_seqs);
-    /* `n` counts the rows that can DRAFT. It can be zero while the history pass still has work:
-     * a sequence three chunks into a long prompt has hidden states the head's attention will need
-     * and no token to propose from yet. */
+    /* `n` counts rows that can draft. It can be zero while the history pass still has work (a
+     * mid-prompt sequence has hidden states the head needs but no token to propose from). */
     const int n = sched_.serial_begin(&rounds, serial_row_.data(), (int)serial_row_.size());
     if (rounds <= 0) return RAD_OK;
     serial_rounds_ = rounds;
     serial_rows_   = n;
 
-    /* RADIANCE_DEBUG_STAGE: WHERE A DRAFT PASS'S HOST TIME GOES. It splits the pass four ways --
-     * the batch and its advance, the greedy sampler chain, and the BARRIER PAIR that hands the
-     * pass to the rank threads and waits for them to finish issuing -- and prints a running mean
-     * of each:
-     *
-     *   D draft:  passes -- batch, sampler, release, issue, in us a pass
-     *
-     * All four are host time the device spends running the pass before, so they cost the step
-     * nothing until their sum exceeds a pass's device time.
-     *
-     * Off by default; four clock reads a pass when it is on. */
+    /* RADIANCE_DEBUG_STAGE: running means of a draft pass's host time: batch + advance, greedy
+     * sampler chain, barrier release and issue. They cost the step nothing until their sum exceeds
+     * the previous pass's device time. */
     static const bool stg = std::getenv("RADIANCE_DEBUG_STAGE") != nullptr;
     static double a_batch = 0, a_samp = 0, a_rel = 0, a_iss = 0;
     static long   n_pass = 0;
@@ -186,23 +156,18 @@ int Engine::issue_serial_drafter(int step, const RadBatch* b, StepOut& so) {
         const auto tA = std::chrono::steady_clock::now();
         const RadBatch* db = sched_.serial_batch(rd, step);
         if (!db) { if (rd == 0) continue; break; }
-        /* PASS 0 IS THE HISTORY PASS: the head attends to its own K and V, nothing else in the
-         * engine writes them, and a prefill leaves them untouched. It is also DRAFT ROUND 1 for
-         * every row that drafts -- that round's inputs are the last row of the row's history run
-         * (RadBatch::draft_out_ids) -- so it ends in the lm_head over those rows. Round r >= 2
-         * embeds the token round r-1 proposed, and the advance takes it from that round's
-         * proposal buffer on the card. */
+        /* Pass 0 is the history pass, writing the head's own K and V (nothing else does). It is
+         * also draft round 1 for drafting rows, whose inputs are the last row of their history run
+         * (RadBatch::draft_out_ids), so it ends in the lm_head over those rows. Round r >= 2 embeds
+         * round r-1's proposal, which the advance takes from the proposal buffer on the card. */
         const int drafted = rd == 0 ? (int)db->n_draft_out : n;
         RAD_TRY(advance_all(rd == 0 ? ADV_HIST : ADV_ROUND, rd, rd > 0));
         const auto tB = std::chrono::steady_clock::now();
 
-        /* GREEDY, AND NOT THE REQUEST'S SAMPLER. A draft is a proposal the target then verifies
-         * greedily (core/sample/accept.h), so sampling it at the request's temperature would
-         * spend that request's RNG stream on tokens that may never be emitted and lower
-         * acceptance for nothing. Scheduler-thread work, before the release, like build_step.
-         *
-         * A head with its own proposal buffer samples nothing at all, so its chain is zero rows
-         * wide -- the same chain the history pass builds, for the same reason. */
+        /* Greedy, not the request's sampler: the target verifies against its own draw
+         * (core/sample/accept.h), so sampling a draft would spend the request's RNG stream and
+         * lower acceptance. A head with its own proposal buffer samples nothing (a zero-row
+         * chain). */
         for (auto& rk : ranks_) {
             int s = rk->sampler.build_greedy(drafter_.proposal ? 0 : drafted);
             if (s < 0) {
@@ -214,10 +179,8 @@ int Engine::issue_serial_drafter(int step, const RadBatch* b, StepOut& so) {
         const auto tC = std::chrono::steady_clock::now();
         issue_what_.store(kIssueAll, std::memory_order_release);
         step_batch_.store(db, std::memory_order_release);
-        /* THE TWO CROSSINGS ARE NOT THE SAME MEASUREMENT and timing them together hides which.
-         * The first RELEASES -- the rank threads are already parked on it, so the drafter is last
-         * in and returns as soon as it has notified, which prices the wake. The second WAITS for
-         * them to finish issuing the pass, so it prices the ISSUE. */
+        /* Timed separately: the first crossing releases the parked ranks (the wake), the second
+         * waits for them to finish issuing (the issue). */
         barrier_->arrive_and_wait();
         const auto tC2 = std::chrono::steady_clock::now();
         barrier_->arrive_and_wait();
@@ -236,19 +199,18 @@ int Engine::issue_serial_drafter(int step, const RadBatch* b, StepOut& so) {
             a_rel   += us(tC2 - tC).count();
             a_iss   += us(tD - tC2).count();
             if (++n_pass % 400 == 0)
-                std::fprintf(stderr, "D draft: %ld passes -- batch %.1f, sampler %.1f, "
-                                     "release %.1f, issue %.1f us a pass\n",
-                             n_pass, a_batch / (double)n_pass, a_samp / (double)n_pass,
-                             a_rel / (double)n_pass, a_iss / (double)n_pass);
+                RAD_INFO("draft: %ld passes; batch %.1f, sampler %.1f, release %.1f, issue %.1f us "
+                         "a pass", n_pass, a_batch / (double)n_pass, a_samp / (double)n_pass,
+                         a_rel / (double)n_pass, a_iss / (double)n_pass);
         }
         if (rd > 0) serial_done_ = rd;
         else if (drafted > 0) serial_done_ = 1;
     }
     if (serial_done_ <= 0 || n <= 0) return RAD_OK;
 
-    /* The last round's proposal, which no later round takes, into the slots; and rank 0's slots
-     * back to the host behind it. Over the drafting rows alone: at depth 1 the last pass is the
-     * history pass, whose rows after them only owed history (Scheduler::serial_batch). */
+    /* The last round's proposal into the slots, then rank 0's slots back to the host. Only the
+     * drafting rows: at depth 1 the last pass is the history pass, whose later rows only carried
+     * history (Scheduler::serial_batch). */
     RAD_TRY(advance_all(ADV_TAKE, serial_done_, true, n));
     Rank& r0 = *ranks_[0];
     RAD_TRY(rad_memcpy_async(slots_host_, r0.step_slots,
@@ -256,10 +218,9 @@ int Engine::issue_serial_drafter(int step, const RadBatch* b, StepOut& so) {
     return RAD_OK;
 }
 
-/* AFTER COMMIT: the host's acceptance against the card's, then the proposals out through
- * set_draft and the history watermark moved. The card's acceptance positioned every draft pass,
- * so a disagreement is a defect in one of the two rules and the step is refused rather than
- * served with drafts from the wrong positions. */
+/* After commit: check the host's acceptance against the card's, publish the proposals through
+ * set_draft, and move the history watermark. The card's acceptance positioned every draft pass,
+ * so a disagreement is a defect and the step is refused. */
 int Engine::finish_serial_drafter(const StepOut& so) {
     if (!serial_drafting() || serial_rounds_ <= 0) return RAD_OK;
     const StepPlan& plan = sched_.plan();
@@ -289,11 +250,8 @@ int Engine::finish_serial_drafter(const StepOut& so) {
             draft_out_[(size_t)i * (size_t)rounds + (size_t)(rd - 1)] = S.tok[rd];
     }
     for (int i = 0; i < serial_rows_; ++i) {
-        /* A REQUEST THE SAMPLER WILL NOT SPECULATE ON GETS NO DRAFT. That is a constraining
-         * grammar whose backend cannot snapshot its state: the mask for draft position i depends
-         * on which of 0..i-1 were accepted, and the sampler refuses the whole step rather than
-         * masking against a state the sequence is not in -- which would be a hard failure on the
-         * next step rather than a skipped draft here. */
+        /* No draft for a request the sampler will not speculate on (a constraining grammar that
+         * cannot snapshot its state); the sampler would refuse the next step otherwise. */
         if (!r0.sampler.allows_speculation(serial_row_[(size_t)i].seq)) continue;
         sched_.set_draft(serial_row_[(size_t)i].seq,
                          &draft_out_[(size_t)i * (size_t)rounds], done);
@@ -303,37 +261,26 @@ int Engine::finish_serial_drafter(const StepOut& so) {
 
 /* ------------------------------------------------------------------ the block driver
  *
- * `RAD_DRAFT_BLOCK`: the same slot in the step as the serial driver and a completely different
- * shape. SERIAL is one forward a drafted token, each embedding what the last one proposed. A
- * BLOCK drafter is block-diffusion: ONE backbone pass over a block of `block` positions -- an
- * anchor and `block - 1` masked slots -- proposes `depth` tokens together, so depth is free and
- * there are no rounds to chain. `block` is the drafter's own (it is `depth + 1` when the anchor
- * row predicts nothing and `depth` when it does; rad_builder.h has both conventions).
+ * RAD_DRAFT_BLOCK (block diffusion, e.g. DFlash2): one backbone pass over `block` positions (an
+ * anchor and `block - 1` masked slots) proposes `depth` tokens at once, with no rounds. `block` is
+ * the drafter's own: depth + 1 when the anchor row predicts nothing, depth when it does
+ * (rad_builder.h). Two passes:
  *
- * What there is instead is TWO passes with different shapes, and the split is what a
- * block-diffusion architecture asks for:
+ *   Context pass: mirrors the trunk step just run. The drafter projects the trunk's tapped hidden
+ *   states and stores K and V for those positions in its own cache, over exactly the trunk's rows
+ *   in order.
  *
- *   THE CONTEXT PASS mirrors the trunk step that just ran. The drafter reads the trunk's tapped
- *   hidden states, projects them, and stores K and V for those positions in a cache of its own --
- *   so it runs over exactly the rows the trunk produced, in exactly that order.
+ *   Query pass: the drafter's layers over the block fill every masked position. Its own selector
+ *   writes the tokens to the plugin's `proposal` buffer, which is why RAD_DRAFT_BLOCK requires
+ *   one.
  *
- *   THE QUERY PASS runs the drafter's own layers over the block and fills every masked position.
- *   The tokens land in the buffer the plugin named as `proposal` -- not in the sampler's, because
- *   what chooses here is the drafter's own selector and it is not a sampler. That is why
- *   RAD_DRAFT_BLOCK requires a proposal buffer and RAD_DRAFT_SERIAL does not.
- *
- * They go out through set_draft() like every other proposal, so nothing downstream can tell a
- * block draft from a prompt-lookup one.
+ * Proposals go out through set_draft() like every other.
  */
 int Engine::run_block_drafter(int step) {
     if (drafter_.kind != RAD_DRAFT_BLOCK || drafter_.depth <= 0) return RAD_OK;
-    static const bool no_draft = std::getenv("RADIANCE_NO_DRAFT") != nullptr;
-    if (no_draft) return RAD_OK;
 
     const int steps = drafter_.depth;
-    /* THE ROW COUNT IS THE DRAFTER'S, not `depth + 1`. Both are legal and the plugin knows which
-     * one its checkpoint was trained in; rad_builder.h has the two conventions side by side, and
-     * declare_drafter has already defaulted and checked this. */
+    /* The row count is the drafter's (defaulted and checked by declare_drafter). */
     const int block = drafter_.block > 0 ? (int)drafter_.block : drafter_.depth + 1;
     std::vector rows((size_t)cfg_.max_seqs);
     const int n = sched_.block_begin(block, steps, (int)drafter_.window, drafter_.mask_token,
@@ -347,41 +294,8 @@ int Engine::run_block_drafter(int step) {
         return RAD_E_STATE;
     }
 
-    /* THE BISECT. RADIANCE_DRAFT_RAW= drafts column 0 of that buffer instead of the
-     * drafter's proposal, which for DFlash2 (`df_cand`) is the draft head's own argmax at every
-     * mask row with the selector's walk thrown away. The two halves of such a drafter fail the
-     * same way from the outside -- acceptance near zero, output still exactly correct -- and they
-     * are otherwise hard to tell apart: if the backbone is sound the argmax already accepts, and
-     * if it is not, no path through the candidates can save it. Debug-only, and it makes the
-     * drafter WORSE when everything works, which is the point.
-     *
-     * A NAME, because the buffer is the plugin's own and the core has no business knowing which
-     * drafters have an intermediate worth reading. The match is on the suffix, since a drafter
-     * declares into a scope; being a debug knob that names one buffer, that is exactly as precise
-     * as it needs to be. */
-    static const char* const raw_name = std::getenv("RADIANCE_DRAFT_RAW");
-    if (raw_name && *raw_name && !raw_buf_) {
-        const std::string want(raw_name);
-        for (size_t i = 1; i < r0.program.buffers.size(); ++i) {
-            const std::string& nm = r0.program.buffers[i].name;
-            if (nm.size() >= want.size() &&
-                nm.compare(nm.size() - want.size(), want.size(), want) == 0) {
-                raw_buf_ = (rad_buf)i;
-                break;
-            }
-        }
-        if (!raw_buf_) {
-            RAD_ERR("RADIANCE_DRAFT_RAW=%s names no buffer in this program", raw_name);
-            return RAD_E_NOTFOUND;
-        }
-        RAD_INFO("drafter '%s': proposing column 0 of `%s` instead of `%s` (RADIANCE_DRAFT_RAW)",
-                 drafter_.name, r0.program.buffers[raw_buf_].name.c_str(),
-                 r0.program.buffers[drafter_.proposal].name.c_str());
-    }
-
-    /* Neither pass samples: the context pass produces no logits at all, and the query pass ends in
-     * the drafter's own selector. A zero-row sampler chain is what the serial driver's history
-     * pass builds for the same reason. */
+    /* Neither pass samples (no logits in the context pass; the query pass has its own selector),
+     * so the sampler chain is zero rows. */
     auto run_pass = [&](const RadBatch* db, const char* what) -> int {
         for (auto& rk : ranks_) {
             int s = rk->sampler.build_greedy(0);
@@ -398,52 +312,27 @@ int Engine::run_block_drafter(int step) {
         if (s < 0)
             RAD_ERR("drafter '%s': %s pass of step %d failed: %s -- the engine cannot continue",
                     drafter_.name, what, step, rad_strerror(s));
-        /* THE PROBE HAS TO SEE INSIDE THESE TOO. A drafter that runs as extra passes leaves every
-         * one of its buffers holding the PREVIOUS step's values at the moment the step loop dumps,
-         * so reading them there answers a question one iteration out of date -- which is how a
-         * context pass that produces NaN reads as a query pass that consumes it. */
-        if (s >= 0 && (int)log_level() >= (int)Log::Trace)
-            dump_buffers(r0.ctx, step, std::getenv("RADIANCE_DUMP_BUF"), what);
+        /* Probe after each pass; by the step loop's dump these buffers hold stale values. */
+        if (s >= 0) dump_buffers(r0.ctx, step, what);
         return s;
     };
 
-    /* THE CONTEXT PASS RUNS EVEN WHEN NOTHING CAN DRAFT. A sequence three chunks into a long
-     * prompt has hidden states the drafter's attention will need and no token to anchor on yet --
-     * exactly the case where skipping it would leave a hole nothing ever fills. */
-    /* RADIANCE_DRAFT_NOCTX=1 runs no context pass at all, so the query block attends to whatever
-     * the drafter's KV cache already held. It answers one question and it is the question that
-     * splits the drafter in half: if acceptance does not move, the conditioning is not reaching
-     * the query pass and the backbone is drafting from the anchor token alone. */
-    static const bool no_ctx = std::getenv("RADIANCE_DRAFT_NOCTX") != nullptr;
-    if (!no_ctx)
-        if (const RadBatch* cb = sched_.block_context(step)) RAD_TRY(run_pass(cb, "context"));
+    /* The context pass runs even when nothing drafts: a mid-prompt sequence has hidden states the
+     * drafter will need, and skipping would leave a permanent hole in its cache. */
+    if (const RadBatch* cb = sched_.block_context(step)) RAD_TRY(run_pass(cb, "context"));
 
-    /* EMPTY UNTIL THIS CALL'S QUERY PASS FILLS IT. It is a member, so a query batch that could
-     * not be built would otherwise leave the previous step's proposals standing -- published
-     * below as this step's, and sized for however many rows drafted then, which may be fewer
-     * than drafted now. */
+    /* Cleared so a query batch that could not be built does not republish the previous step's
+     * proposals. */
     draft_out_.clear();
     if (n > 0) {
         if (const RadBatch* qb = sched_.block_query(step)) {
             RAD_TRY(run_pass(qb, "query"));
-            draft_out_.assign((size_t)n * (size_t)steps, 0);
-            const rad_buf from = raw_buf_ ? raw_buf_ : drafter_.proposal;
-            void* src = (from == drafter_.proposal) ? prop : r0.ctx.buf_ptr(from);
-            if (!src) {
-                RAD_ERR("`%s` was declared but never planned",
-                        r0.program.buffers[from].name.c_str());
-                return RAD_E_STATE;
-            }
-            /* A raw buffer is [row][width] and the proposal is [seq][steps]: one may be strided
-             * candidate count and the other is dense, so the bisect copies the whole candidate
-             * plane and takes column zero rather than pretending the two have the same shape. */
-            const int64_t k = raw_buf_ ? r0.program.buffers[from].decl.shape[1] : 1;
-            const int64_t n_raw = (int64_t)n * steps * k;
+            const int64_t n_raw = (int64_t)n * steps;
             int32_t* const raw = readback_.reserve(n_raw);
             if (!raw) return RAD_E_NOMEM;
-            RAD_TRY(rad_memcpy_async(raw, src, n_raw * 4, r0.ctx.stream()));
+            RAD_TRY(rad_memcpy_async(raw, prop, n_raw * 4, r0.ctx.stream()));
             RAD_TRY(rad_stream_sync(r0.ctx.stream()));
-            for (size_t i = 0; i < draft_out_.size(); ++i) draft_out_[i] = raw[i * (size_t)k];
+            draft_out_.assign(raw, raw + n_raw);
         }
     }
     sched_.block_end();
@@ -457,5 +346,4 @@ int Engine::run_block_drafter(int step) {
     return RAD_OK;
 }
 
-
 }  /* namespace rad */
diff --git a/core/engine_gen.cpp b/core/engine_gen.cpp
index f95cdaeb..4a372d19 100644
--- a/core/engine_gen.cpp
+++ b/core/engine_gen.cpp
@@ -1,11 +1,9 @@
-/* engine_gen.cpp -- the image generator's loop: the driver's passes (core/gen/driver.h) run on the
- * ranks the way the step loop runs token steps, one at a time and each drained before the next.
+/* engine_gen.cpp -- the image generator's loop: the driver's passes (core/gen/driver.h) run on
+ * the ranks like token steps, one at a time, each drained before the next.
  *
- * WHY EACH PASS IS DRAINED. A generator pass is tens to thousands of milliseconds of device work,
- * and what decides the next one -- which image finished, which preview a step marked -- is the
- * driver's bookkeeping of the pass just run, not anything the card computes. Waiting for the card
- * between passes costs the few microseconds the host takes to build the next one; issuing ahead
- * would need a second staging region and a commit protocol, for nothing a client could measure.
+ * Draining is cheap: a pass is tens to thousands of milliseconds of device work, and the next
+ * pass depends only on the driver's host bookkeeping, so the wait costs the microseconds of
+ * building it. Issuing ahead would need a second staging region and a commit protocol.
  */
 #include "engine_priv.h"
 #include "gen/driver.h"
@@ -20,6 +18,11 @@ int Engine::gen_loop() {
         RAD_ERR("image generator loop: could not bind rank 0's device");
     int step = 0, idle = 0;
     const rad_buf img = ranks_[0]->program.generator.image_out;
+    /* An error ends the driver's requests, then the loop. */
+    auto stop = [&](int st) {
+        gen_->shutdown("the engine stopped on an error and is not serving", st);
+        return fail_loop(st);
+    };
     while (!stopping_.load(std::memory_order_acquire)) {
         const RadBatch* b = gen_->next(step);
         if (!b) {
@@ -29,10 +32,7 @@ int Engine::gen_loop() {
             continue;
         }
         idle = 0;
-        if (const int ps = prepare_release(b); ps < 0) {
-            gen_->shutdown("the engine stopped on an error and is not serving", ps);
-            return fail_loop(ps);
-        }
+        if (const int ps = prepare_release(b); ps < 0) return stop(ps);
         issue_what_.store(kIssueModel, std::memory_order_release);
         step_batch_.store(b, std::memory_order_release);
         barrier_->arrive_and_wait();      /* release the ranks */
@@ -41,16 +41,15 @@ int Engine::gen_loop() {
         if (st < 0) {
             RAD_ERR("generator pass %d failed: %s -- the engine cannot continue", step,
                     rad_strerror(st));
-            gen_->shutdown("the engine stopped on an error and is not serving", st);
-            return fail_loop(st);
+            return stop(st);
         }
-        /* A DECODE PASS'S IMAGE, behind it on rank 0's stream: every rank decodes the same pixels. */
+        /* A decode pass's image, copied behind it on rank 0's stream; every rank holds the same
+         * pixels. */
         if (const int64_t n = gen_->decode_bytes(); n > 0) {
             const void* src = ranks_[0]->ctx.buf_ptr(img);
             if (!src) {
                 RAD_ERR("the generator's image buffer was declared but never planned");
-                gen_->shutdown("the engine stopped on an error and is not serving", RAD_E_STATE);
-                return fail_loop(RAD_E_STATE);
+                return stop(RAD_E_STATE);
             }
             st = rad_memcpy_async(gen_->host_image(), src, n, ranks_[0]->ctx.stream());
         }
@@ -58,11 +57,9 @@ int Engine::gen_loop() {
             if (st >= 0) st = rad_stream_sync(rk->ctx.stream());
         if (st < 0) {
             RAD_ERR("generator pass %d: the device failed: %s", step, rad_strerror(st));
-            gen_->shutdown("the engine stopped on an error and is not serving", st);
-            return fail_loop(st);
+            return stop(st);
         }
-        if ((int)log_level() >= (int)Log::Trace)
-            dump_buffers(ranks_[0]->ctx, step, std::getenv("RADIANCE_DUMP_BUF"));
+        dump_buffers(ranks_[0]->ctx, step);
         gen_->done();
         ++step;
     }
diff --git a/core/engine_hostmem.cpp b/core/engine_hostmem.cpp
new file mode 100644
index 00000000..acdcb606
--- /dev/null
+++ b/core/engine_hostmem.cpp
@@ -0,0 +1,54 @@
+/* engine_hostmem.cpp -- see engine_hostmem.h. */
+#include "engine_hostmem.h"
+
+#include 
+#include 
+
+namespace rad {
+
+bool cgroup_room(const std::string& dir, bool v2, int64_t* room) {
+    auto read_ll = [](const std::string& f, long long* v) {
+        std::ifstream in(f);
+        std::string t;
+        if (!(in >> t)) return false;
+        char* e = nullptr;
+        *v = std::strtoll(t.c_str(), &e, 10);
+        return e && *e == '\0';
+    };
+    auto stat_ll = [](const std::string& f, const char* key, long long* v) {
+        std::ifstream in(f);
+        std::string k;
+        long long x = 0;
+        while (in >> k >> x) if (k == key) { *v = x; return true; }
+        return false;
+    };
+    long long lim = 0, used = 0, file = 0;
+    if (v2) {
+        if (!read_ll(dir + "/memory.max", &lim)) return false;           /* "max" fails to parse */
+        if (!read_ll(dir + "/memory.current", &used)) return false;
+        (void)stat_ll(dir + "/memory.stat", "file", &file);
+    } else {
+        if (!read_ll(dir + "/memory.limit_in_bytes", &lim) || lim >= ((long long)1 << 62))
+            return false;
+        if (!read_ll(dir + "/memory.usage_in_bytes", &used)) return false;
+        if (!stat_ll(dir + "/memory.stat", "total_cache", &file))
+            (void)stat_ll(dir + "/memory.stat", "cache", &file);
+    }
+    const long long hard = used > file ? used - file : 0;
+    *room = lim > hard ? (int64_t)(lim - hard) : 0;
+    return true;
+}
+
+void cgroup_levels(const std::string& root, std::string path, bool v2,
+                   const std::function& visit) {
+    for (;;) {
+        const std::string dir = root + (path == "/" ? std::string() : path);
+        int64_t room = 0;
+        if (cgroup_room(dir, v2, &room) && !visit(dir, room)) return;
+        if (path.empty() || path == "/") break;
+        const size_t up = path.find_last_of('/');
+        path = up == 0 || up == std::string::npos ? "/" : path.substr(0, up);
+    }
+}
+
+}  /* namespace rad */
diff --git a/core/engine_hostmem.h b/core/engine_hostmem.h
new file mode 100644
index 00000000..258425a6
--- /dev/null
+++ b/core/engine_hostmem.h
@@ -0,0 +1,22 @@
+/* engine_hostmem.h -- the memory cgroup limits bring-up checks before it locks a table into host
+ * memory (engine_bringup.cpp, lockable_room). */
+#pragma once
+#include 
+#include 
+#include 
+
+namespace rad {
+
+/* A cgroup's limit less the usage reclaim cannot give back: memory.current less file pages (v2)
+ * or usage_in_bytes less cache (v1), since page cache yields to a locked allocation and anonymous
+ * memory does not. "max" and v1's near-INT64_MAX sentinel mean no limit. True, with `room` set,
+ * when `dir` has a limit. */
+bool cgroup_room(const std::string& dir, bool v2, int64_t* room);
+
+/* Every level of the memory cgroup at `path` (as /proc/self/cgroup names it), from that level up
+ * to the hierarchy's root mounted at `root`, leaf first: `visit(dir, room)` for each level with a
+ * limit, until it returns false. Each level is a limit of its own. */
+void cgroup_levels(const std::string& root, std::string path, bool v2,
+                   const std::function& visit);
+
+}  /* namespace rad */
diff --git a/core/engine_kld.cpp b/core/engine_kld.cpp
index 7c0f19b8..79bdb659 100644
--- a/core/engine_kld.cpp
+++ b/core/engine_kld.cpp
@@ -1,13 +1,14 @@
-/* engine_kld.cpp -- the KL mode's two halves on the Engine: the driver that runs in place of the
- * HTTP server, and the copy of a step's scored rows off the cards. The arithmetic and the files
- * are core/kld.h's. */
+/* engine_kld.cpp -- the KL mode on the Engine: the driver that replaces the HTTP server, and the
+ * copy of a step's scored rows off the cards. The arithmetic and files are core/kld.h's. */
 #include "engine_priv.h"
 #include "kld.h"
 
 #include "device/device.h"
 #include "server/sink.h"
 
+#include 
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -15,9 +16,9 @@
 namespace rad {
 
 int Engine::run_kld() {
-    /* THE LOGITS BUFFER AS EACH RANK DECLARED IT. It has to hold a step's tokens after the
-     * sampler's rows (RadBuildCtx::max_out_rows); a plugin that sized it by its own rule alone
-     * did not read the field, and is refused here rather than overrun at the first step. */
+    /* Each rank's logits buffer must hold a step's tokens after the sampler's rows
+     * (RadBuildCtx::max_out_rows); a plugin that ignored the field is refused here rather than
+     * overrun. */
     const int64_t need = cfg_.max_tok + cfg_.max_seqs;
     const int64_t nv = meta_.n_vocab;
     kld_vocab0_.clear();
@@ -36,8 +37,8 @@ int Engine::run_kld() {
                     d.dtype == RAD_F32 ? "f32" : "another dtype", (long long)need);
             return RAD_E_UNSUPPORTED;
         }
-        /* The columns a rank owns, by the rule declare_sampler checked at startup: a contiguous
-         * equal split, or the whole vocabulary on every rank -- read from rank 0 alone then. */
+        /* The columns a rank owns: the sampler's split, which declare_sampler checked, or the
+         * whole vocabulary on every rank (then read from rank 0 only). */
         const int64_t w = d.shape[1];
         if (w >= nv) {
             if (!kld_width_.empty()) continue;
@@ -45,8 +46,7 @@ int Engine::run_kld() {
             kld_width_.push_back(nv);
             continue;
         }
-        const int64_t per = (nv + cfg_.tp - 1) / cfg_.tp;
-        kld_vocab0_.push_back(per * rk->index);
+        kld_vocab0_.push_back(rk->sampler.config().vocab_off);
         kld_width_.push_back(w);
     }
     int64_t cover = 0;
@@ -69,13 +69,36 @@ int Engine::run_kld() {
 
     auto kld = std::make_unique();
     RAD_TRY(kld->open(cfg_, vocab_, nv, cfg_.model));
-    /* Published before add_all takes the scheduler's lock, and read by the step loop only on a
-     * step that carries a scored row -- one planned under that lock, after it. */
+    /* Published before add_all takes the scheduler's lock; the step loop reads it only on steps
+     * planned under that lock afterwards. */
     kld_ = std::move(kld);
 
-    /* EVERY DOCUMENT AT ONCE, under one hold of the queue: the steps they are packed into are
-     * then a function of the corpus and the flags alone, so a rerun batches them identically. */
     const size_t n = kld_->n_docs();
+    /* A document the KV pool cannot hold even alone would wait at the head of the queue forever:
+     * admission takes only a chunk the pool can hold, and nothing ever frees enough. Refused up
+     * front, naming every such document. The pool is the least that a full paged group holds. */
+    {
+        const KVManager& kv = ranks_[0]->kv;
+        int64_t pool = INT64_MAX;
+        for (int32_t g = 0; g < kv.n_groups(); ++g) {
+            const KVGroupPlan* p = kv.plan(g);
+            if (p && p->paged() && p->window_blocks == 0)
+                pool = std::min(pool, p->n_blocks * p->block_size);
+        }
+        int too_long = 0;
+        for (size_t d = 0; d < n; ++d) {
+            const int64_t len = (int64_t)kld_->tokens(d).size();
+            if (kv.can_ever_fit(len)) continue;
+            RAD_ERR("kld: document %zu is %lld tokens and the KV pool holds %lld, so it can never "
+                    "be scored; give the cache more room or shorten the document", d,
+                    (long long)len, (long long)pool);
+            ++too_long;
+        }
+        if (too_long) return RAD_E_FULL;
+    }
+
+    /* Submit every document under one hold of the queue, so batching depends only on the corpus
+     * and the flags and a rerun batches identically. */
     std::vector> sinks(n);
     std::vector> reqs(n);
     for (size_t d = 0; d < n; ++d) {
@@ -126,16 +149,16 @@ int Engine::run_kld() {
         sched_.reap(sinks[d]->id);
     }
     if (bad) return RAD_E_STATE;
-    RAD_INFO("kld: %zu documents in %.0f s", n,
-             std::chrono::duration(std::chrono::steady_clock::now() - t0).count());
+    RAD_INFO("kld: %zu documents in %.0f s, %lld preemption(s)", n,
+             std::chrono::duration(std::chrono::steady_clock::now() - t0).count(),
+             (long long)sched_.metrics().preemptions);
     return kld_->finish();
 }
 
-/* A STEP'S SCORED ROWS, OFF THE CARDS. They follow the sampler's rows in the logits buffer, in
- * the entry order the batch builder wrote them (core/sched/batch.cpp, "THE SCORED ROWS"), so the
- * walk below is that loop again and the count is checked against what the batch named. Every
- * rank's piece on its own stream, behind the step; the next step is not issued until they are
- * read, because the KL mode does not pipeline. */
+/* Copy a step's scored rows off the cards. They follow the sampler's rows in the logits buffer in
+ * the batch builder's entry order (core/sched/batch.cpp), so the walk below repeats that loop and
+ * checks the count. Each rank copies on its own stream behind the step; KL mode does not
+ * pipeline, so the next step waits for this. */
 int Engine::score_rows(const RadBatch* b, const StepOut& so) {
     const int64_t n = b->n_out - so.n_rows;
     if (n <= 0) return RAD_OK;
diff --git a/core/engine_mm.cpp b/core/engine_mm.cpp
index fe683731..2495cc5c 100644
--- a/core/engine_mm.cpp
+++ b/core/engine_mm.cpp
@@ -1,27 +1,23 @@
 /* engine_mm.cpp -- the encoder driver (spec §11).
  *
  * The scheduler holds back a request whose media is not encoded (Scheduler::media_ready) and hands
- * its items here. They are encoded BETWEEN steps, never inside one: a pass is issued with no step
- * in flight, read back, and the item marked done, so the next step's admission finds its rows in
- * host memory and the batch builder copies them in with the chunk that reaches them. Nothing on the
- * step path ever waits on the tower.
+ * its items here. They are encoded between steps, never inside one: a pass runs with no step in
+ * flight, is read back, and the item is marked done, so admission finds its rows in host memory and
+ * the batch builder copies them in with the chunk that reaches them. The step path never waits on
+ * the tower.
  *
- * A PASS IS WHOLE SEGMENTS. An image is one segment and a video one per temporal group, and the
- * encoder attends within a segment, so a pass may end between two segments of a video and never
- * inside one; the processor has already kept every segment within a pass. Several items share a
- * pass when they fit, which is what a request with a handful of small pictures wants.
+ * A pass holds whole segments: an image is one segment, a video one per temporal group, and the
+ * encoder attends within a segment (the processor keeps each within a pass). Several items share a
+ * pass when they fit. An audio clip is one segment of the audio encoder, whose passes are separate.
  *
- * AN AUDIO CLIP IS ONE SEGMENT OF THE AUDIO ENCODER, whose passes are separate from the vision
- * tower's: a program declares one of each at most, and an item goes to the one its kind names.
- *
- * EVERY RANK RUNS THE WHOLE TOWER on its own card from its own copy of the patches. The rows are
- * needed on every rank anyway -- each rank embeds every token -- and running it everywhere costs the
- * encoder's compute once per card instead of a transfer of its output between them.
+ * Every rank runs the whole tower from its own copy of the patches: every rank embeds every token,
+ * so this costs compute per card instead of a transfer between them.
  */
 #include "engine_priv.h"
 
 #include "mm/processor.h"
 
+#include 
 #include 
 #include 
 
@@ -31,11 +27,11 @@ int Engine::run_encodes() {
     std::vector> items;
     sched_.take_encodes(&items);
     if (items.empty()) return RAD_OK;
+    const auto t0 = std::chrono::steady_clock::now();
 
-    /* A DIAGNOSTIC: RADIANCE_DEBUG_MM_DUMP= writes each item's patches (`.pix.bf16`, the
-     * processor's output in merge-block order) and its rows (`.bf16`) there as raw bf16, named by
-     * its content key -- the tower's input and output, for comparison against a reference encoder
-     * fed the same input. */
+    /* Diagnostic: RADIANCE_DEBUG_MM_DUMP= writes each item's patches (`.pix.bf16`, processor
+     * output in merge-block order) and rows (`.bf16`) as raw bf16, named by content key, for
+     * comparison against a reference encoder. */
     static const char* const dump_dir = std::getenv("RADIANCE_DEBUG_MM_DUMP");
     auto dump = [&](const mm::Item& it, const char* ext, const uint16_t* p, size_t n) {
         char path[512];
@@ -58,8 +54,8 @@ int Engine::run_encodes() {
         if (dump_dir && *dump_dir) dump(*ip, ".pix.bf16", ip->pixels.data(), ip->pixels.size());
     }
 
-    /* THE PASSES, ENCODER BY ENCODER: an audio clip goes through the audio encoder and a picture
-     * or a video through the other, each with its own pass size and output buffer. */
+    /* Passes per encoder: audio through the audio encoder, pictures and video through the vision
+     * encoder, each with its own pass size and output buffer. */
     for (int which = 0; which < 2; ++which) {
         const bool audio = which == 1;
         const RadEncoderDecl& enc = audio ? prog.audio_encoder : prog.encoder;
@@ -103,18 +99,15 @@ int Engine::run_encodes() {
             const RadBatch* b = sched_.build_encoder(parts, enc_step_++, enc);
             if (!b) return RAD_E_STATE;
             RAD_TRY(prepare_release(b));
-            /* THE OUTPUT'S ADDRESS IS THE PASS'S LEVEL'S, read after prepare_release: a pass runs
-             * at the arena's full plan (Engine::arena_step), and a buffer sits at another offset
-             * in every level. An address taken at the level the last step left would read some
-             * other buffer, or memory lent to the expert slab, in place of the rows. */
+            /* Read the output address after prepare_release: a pass runs at the arena's full plan
+             * (Engine::arena_step), and a buffer's offset differs per level. */
             void* out = r0.ctx.buf_ptr(enc.out);
             if (!out) {
                 RAD_ERR("encoder '%s': its output buffer was declared but never planned",
                         enc_name.c_str());
                 return RAD_E_STATE;
             }
-            /* kIssueModel: the pass and nothing behind it -- no sampler, and no tiering tick,
-             * which belongs to steps. */
+            /* kIssueModel: the pass only, with no sampler and no tiering tick. */
             issue_what_.store(kIssueModel, std::memory_order_release);
             step_batch_.store(b, std::memory_order_release);
             barrier_->arrive_and_wait();
@@ -137,8 +130,7 @@ int Engine::run_encodes() {
                                          bytes, r0.ctx.stream()));
                 row += rows;
             }
-            /* Every rank's stream, not only rank 0's: the next pass rewrites the staging every
-             * rank's copy reads, and the arena every rank's tower wrote. */
+            /* Sync every rank's stream: the next pass rewrites every rank's staging and arena. */
             for (auto& rk : ranks_) RAD_TRY(rad_stream_sync(rk->ctx.stream()));
         }
     }
@@ -151,7 +143,9 @@ int Engine::run_encodes() {
         it.pixels.shrink_to_fit();
         if (dump_dir && *dump_dir) dump(it, ".bf16", it.embd.data(), it.embd.size());
     }
-    RAD_DEBUG("encoder: %zu item(s) encoded", items.size());
+    RAD_DEBUG("encoder: %zu item(s) encoded in %.1f ms", items.size(),
+              std::chrono::duration(std::chrono::steady_clock::now() - t0)
+                  .count());
     return RAD_OK;
 }
 
diff --git a/core/engine_priv.h b/core/engine_priv.h
index 902c5d6a..13750ebe 100644
--- a/core/engine_priv.h
+++ b/core/engine_priv.h
@@ -1,14 +1,12 @@
-/* engine_priv.h -- what the Engine's translation units share and nothing outside them sees.
+/* engine_priv.h -- shared by the Engine's translation units only.
  *
- * `Engine` is one class across four files because its phases have almost nothing to say to each
- * other: bring-up runs once and touches every subsystem; the step loop runs a thousand times a
- * second and touches four; the drafters are two shapes of extra pass; the probe is debug-only and
- * reads everything. Splitting them is not decomposition of the class -- the public surface in
- * engine.h is unchanged -- it is putting each phase where it can be read on its own.
+ * `Engine` is one class split across several files by phase, which share little: bring-up runs
+ * once and touches every subsystem, the step loop runs constantly and touches a few, the drafters
+ * are extra passes, and the probe is debug-only. The public surface in engine.h is unchanged.
  *
- * `Engine::Rank` lives here rather than in engine.h because it names every subsystem's concrete
- * type, and engine.h is included by main.cpp and the tools: a forward declaration there is what
- * keeps a caller that only wants to serve a model from compiling the pool allocator.
+ * `Engine::Rank` is defined here, not in engine.h, because it names every subsystem's concrete
+ * type; engine.h is included by main.cpp and the tools, which then need only a forward
+ * declaration.
  */
 #pragma once
 #include "engine.h"
@@ -30,43 +28,35 @@
 namespace rad {
 
 /* ================================================================== per-rank state */
-/* One thread per tensor-parallel rank, each owning one device. No IPC, no shared-memory
- * handshake, no serialisation between ranks -- which is most of what a Python engine spends its
- * multiprocessing budget on. Because the ranks share an address space, the step batch is shared
- * BY POINTER rather than broadcast (spec §1). */
+/* One tensor-parallel rank's state; see Engine::ranks_. */
 struct Engine::Rank {
     int       index = 0;
     int       device = 0;
-    Program   program;          /* declare runs once PER RANK: dimensions are already divided */
+    Program   program;          /* declare runs once per rank: dimensions are already divided */
     Plan      plan;
     Pools     pools;
     Mover     mover;
-    /* THE POLICY HALF OF TIERED PLACEMENT. Bound to the plan at bringup and off unless the plan
-     * is dynamic; `heat_seen[l]` is the last step whose histogram layer l has already been
-     * credited, because a histogram sits in its bank until the NEXT report overwrites it and
-     * crediting it twice would double every count. */
+    /* The policy half of tiered placement, bound to the plan at bring-up and off unless the plan
+     * is dynamic. `heat_seen[l]` is the last step whose layer-l histogram was credited: a
+     * histogram stays in its bank until the next report overwrites it, and must not be counted
+     * twice. */
     HeatEngine       heat;
     std::vector heat_seen;
     /* One sweep's histograms, found before any is credited; kept so a sweep allocates nothing. */
     struct HeatRow { int layer; int bank; const int32_t* h; };
     std::vector heat_rows;
-    /* WHY A LAYER'S HISTOGRAM WENT UNCREDITED, which the credited total cannot separate on its
-     * own. A histogram is skipped either because its copy has not landed yet or because the bank
-     * still holds a step already credited, and those are different faults: the first says the host
-     * ran ahead of the device and the sample was lost, the second says the layer did not route.
-     * Without the split, a placement engine starved of evidence reads exactly like a model whose
-     * layers are idle. */
+    /* Credited histograms, and layer sweeps that found nothing new. A histogram is skipped
+     * either because its copy has not landed (the host ran ahead and the sample was lost) or
+     * because its bank holds an already-credited step (the layer did not route). Counting these
+     * apart keeps a placement engine starved of evidence from looking like idle layers. */
     uint64_t heat_credited = 0, heat_idle = 0;
     /* Trunk steps in a row whose pass the prefill stager did not arm (Engine::tiering_dispatch). */
     int unstaged_steps = 0;
-    Residency residency;
     KVManager kv;
     PrefixCache prefix;
-    /* THE IDLE SESSION TIERS (spec 7.3). Rank 0 owns the policy and the session index,
-     * because they describe CONVERSATIONS and a conversation is not sharded -- but the
-     * transfer is per rank, since each rank holds its own shard of every KV block and
-     * has its own pool to gather out of. Both are inert unless --prefix-cache-mib gave the
-     * host tier a size. */
+    /* Idle session tiers (spec 7.3). Rank 0 owns the policy and session index, since a
+     * conversation is not sharded; the transfer is per rank, since each holds its own shard of
+     * every KV block. Both are inert unless --prefix-cache-mib sizes the host tier. */
     IdleTiers tiers;
     TierExec  tierx;
     /* The activation arena's smaller levels, smallest step first (Engine::probe_arena_levels). */
@@ -74,32 +64,35 @@ struct Engine::Rank {
     /* Per Ctx level (0 is the full plan): the bytes at the top of this rank's arena that level
      * leaves to the expert slab. */
     std::vector    arena_lent;
-    /* THE PREFILL STAGER (core/place/stager.h): the next routed layer's pooled experts, copied into
-     * the top of this rank's arena while a full-plan step runs the layer before. */
+    /* Where the prefill stager's ring is at the span's shared level, from the arena's base; -1
+     * without that level. */
+    int64_t                 arena_low_off = -1;
+    /* Prefill stager (core/place/stager.h): copies the next routed layer's pooled experts into the
+     * top of this rank's arena while a full-plan step runs the layer before. */
     PrefillStager stager;
-    /* THE FILE STAGER (core/place/stager.h): a routed layer's file-tier experts, read from the
+    /* File stager (core/place/stager.h): reads a routed layer's file-tier experts from the
      * container into one of the mover's two file buffers before the layer's first expert op, on
-     * every pass. With both stagers in use the chain hands each the passes it armed for. */
+     * every pass. With both stagers in use, the chain hands each the passes it armed for. */
     FileStager  fstager;
     StagerChain stagers;
     Ctx       ctx;
     Sampler   sampler;          /* one per rank: each samples its own vocab shard (spec §9) */
-    /* THE SCORED ROWS' LOGITS (Request::token_scores), this rank's vocabulary shard of each,
-     * copied into pinned memory ahead of the sampler. Grown to the most rows a step has scored. */
+    /* Scored rows' logits (Request::token_scores), this rank's vocabulary shard, copied into pinned
+     * memory ahead of the sampler. Grown to the most rows a step has scored. */
     float*    score_host = nullptr;
     int64_t   score_rows_cap = 0;
     rad_buf   tok_buf = 0;      /* where the chain writes the sampled ids */
-    /* THE CARD'S STEP STATE (sched/advance.h): one StepSlot a scheduler slot, and the
-     * end-of-generation ids acceptance stops at, sorted. Every rank keeps its own and computes the
-     * same values from the same sampled ids. */
+    /* The card's step state (sched/advance.h): one StepSlot per scheduler slot, and the sorted
+     * end-of-generation ids acceptance stops at. Every rank keeps its own and computes the same
+     * values from the same sampled ids. */
     StepSlot* step_slots = nullptr;
     int32_t*  eog = nullptr;
     int32_t   n_eog = 0;
 };
 
-/* THE TIERS' WORK IN FLIGHT (Engine::tier_tick). One copy batch out on every rank's transfer
- * stream at a time, with each rank's answer kept until all of them have one -- a rank that has
- * landed must not be asked again and forget it failed. */
+/* The tiers' work in flight (Engine::tier_tick): one copy batch per rank's transfer stream at a
+ * time. Each rank's result is kept until all ranks have one, so a landed rank is not polled again
+ * and a failure is not lost. */
 struct TierPump {
     std::vector copy;
     std::vector     copy_st;    /* per rank: 0 in flight, 1 landed, negative failed */
@@ -107,10 +100,9 @@ struct TierPump {
     int                  slow_budget = 0;   /* capacity drops one plan may make */
 };
 
-/* THE BUFFER PROBE (engine_probe.cpp). Declared here because three files call it: the step
- * loop dumps after a trunk step, and each drafter dumps after its own passes -- a drafter that
- * runs as extra passes leaves every one of its buffers holding the PREVIOUS step's values at the
- * moment the step loop dumps. */
-void dump_buffers(Ctx& ctx, int step, const char* names, const char* phase = "");
+/* The buffer probe (engine_probe.cpp): the buffers RADIANCE_DUMP_BUF names, at -vv only. The step
+ * loop dumps after a trunk step, and each drafter after its own passes, since a drafter's buffers
+ * still hold the previous step's values when the step loop dumps. */
+void dump_buffers(Ctx& ctx, int step, const char* phase = "");
 
 }  /* namespace rad */
diff --git a/core/engine_probe.cpp b/core/engine_probe.cpp
index 4252c038..cff9ac53 100644
--- a/core/engine_probe.cpp
+++ b/core/engine_probe.cpp
@@ -1,13 +1,11 @@
-/* engine_probe.cpp -- RADIANCE_DUMP_BUF, the buffer probe.
- *
- * Debug-only and it reads everything, which is why it is not in the step loop's file: it is the
- * one part of the Engine that knows every dtype and every buffer's shape, and none of that
- * belongs beside code that runs a thousand times a second. See engine_priv.h.
+/* engine_probe.cpp -- RADIANCE_DUMP_BUF, the buffer probe. Debug-only; kept out of the step
+ * loop's file because it decodes every dtype and buffer shape.
  */
 #include "engine_priv.h"
 
 #include "build/rad_build.h"
 #include "device/device.h"
+#include "rad_plugin.h"
 
 #include 
 #include 
@@ -21,75 +19,54 @@ namespace rad {
 
 /* ================================================================== the buffer probe
  *
- * RADIANCE_DUMP_BUF names declared buffers, comma separated, and every step prints the first row
- * of each: its mean, its largest magnitude and its first four elements. RADIANCE_DUMP_HEAD=
- * adds the first n elements verbatim (integers included) and RADIANCE_DUMP_TOPK= the k largest.
+ * RADIANCE_DUMP_BUF names declared buffers (comma separated); every step prints the first row of
+ * each: mean, largest magnitude and first four elements. RADIANCE_DUMP_HEAD= adds the first n
+ * elements verbatim (integers included); RADIANCE_DUMP_TOPK= adds the k largest.
  *
- * It exists because nothing else can see INSIDE a step. rad-kbench falsifies one op against the
- * oracle and passes; --debug-graph shows what was declared and resolved; and between them sits a
- * forward pass that answers the same token to every prompt with every op individually correct.
- * The layer bisect narrows that to a block, and this narrows it to a tensor -- which is as far as
- * anything short of a second implementation can go.
- *
- * An environment variable and not a flag, and only at -vv, because it is a device-to-host copy and
- * a synchronisation per step: it changes what it measures, like every probe does. */
-/* How much of a row to bring back. Eight kibibytes covers an ordinary hidden state; a row that is
- * a CONCATENATION -- the DFlash2 tap buffer is five hidden states wide -- needs more, and looking
- * at only the first of the five is how a probe reports a healthy tensor whose fifth field is
- * garbage. RADIANCE_DUMP_BYTES raises it. */
+ * It shows tensors inside a step, which neither rad-kbench (one op at a time) nor --debug-graph
+ * (what was declared) can. An environment variable at -vv only, because it adds a device-to-host
+ * copy and a synchronisation per step. */
+
+/* A positive integer from the environment, clamped to `hi`, or `dflt` when unset or not one. */
+static int64_t env_count(const char* name, int64_t dflt, int64_t hi) {
+    const char* s = std::getenv(name);
+    const long long v = (s && *s) ? std::strtoll(s, nullptr, 10) : 0;
+    return v > 0 ? std::min(v, hi) : dflt;
+}
+
+/* Bytes of a row to read back. 8 KiB covers an ordinary hidden state; a concatenated row (the
+ * DFlash2 tap buffer is five hidden states wide) needs more, set with RADIANCE_DUMP_BYTES. */
 static int64_t dump_cap() {
-    static const int64_t cap = [] {
-        const char* s = std::getenv("RADIANCE_DUMP_BYTES");
-        const long long v = s ? std::atoll(s) : 0;
-        return v > 0 ? (int64_t)v : (int64_t)8192;
-    }();
+    static const int64_t cap = env_count("RADIANCE_DUMP_BYTES", 8192, INT64_MAX);
     return cap;
 }
 
+/* The floating types, which the summary and the top k decode; index planes have no meaningful
+ * mean. */
+static bool is_float(uint32_t dtype) {
+    return dtype == RAD_F32 || dtype == RAD_F16 || dtype == RAD_BF16 || dtype == RAD_F8E4M3 ||
+           dtype == RAD_F8E5M2;
+}
+
 static void dump_row(int step, const char* phase, const char* name, uint32_t dtype,
                      const std::vector& raw) {
     const int bits = rad_dtype_bits(dtype);
     const int64_t cnt = bits > 0 ? (int64_t)raw.size() * 8 / bits : 0;
+    if (!cnt) return;
+    const bool fl = is_float(dtype);
     double sum = 0, amax = 0;
-    /* NON-FINITE COUNT, beside the mean. A single NaN makes the mean NaN and leaves amax at zero,
-     * which reads as "empty" and is the opposite of what happened; and the interesting question
-     * about a row that has gone wrong is almost always WHERE, since a row that is finite for its
-     * first tap and garbage for its fifth names the bug on its own. */
+    /* Count non-finite values and the first one's index: a single NaN would poison the mean, and
+     * where the garbage starts often locates the bug. */
     int64_t bad = 0, bad_first = -1;
     float first[4] = {0, 0, 0, 0};
-    for (int64_t k = 0; k < cnt; ++k) {
-        float v = 0;
-        if (dtype == RAD_F32) std::memcpy(&v, raw.data() + k * 4, 4);
-        else if (dtype == RAD_BF16) {
-            uint32_t u = (uint32_t)(raw[(size_t)(k * 2)] | (raw[(size_t)(k * 2 + 1)] << 8));
-            u <<= 16; std::memcpy(&v, &u, 4);
-        }
-        else if (dtype == RAD_F8E4M3) {
-            /* E4M3-fn, decoded here rather than skipped: a block-scaled fp8 weight IS the model,
-             * and "is this the tensor the name map named" has to be answerable about it too. */
-            const uint8_t c = raw[(size_t)k];
-            const uint32_t sgn = (uint32_t)(c & 0x80u) << 24;
-            const int      e   = (c >> 3) & 0x0F;
-            uint32_t       m   = c & 0x07u, u;
-            if (e == 0) {
-                if (!m) u = sgn;
-                else { int ex = -6; while (!(m & 0x08u)) { m <<= 1; --ex; }
-                       u = sgn | ((uint32_t)(ex + 127) << 23) | ((m & 0x07u) << 20); }
-            } else if (e == 0x0F && m == 0x07) u = sgn | 0x7FC00000u;
-            else u = sgn | ((uint32_t)(e - 7 + 127) << 23) | (m << 20);
-            std::memcpy(&v, &u, 4);
-        }
-        else continue;                        /* the index types have no meaningful mean */
+    for (int64_t k = 0; fl && k < cnt; ++k) {
+        const float v = rad_load_f32(raw.data(), dtype, k);
         if (!std::isfinite(v)) { if (bad_first < 0) bad_first = k; ++bad; }
         else { sum += v; amax = std::max(amax, (double)std::fabs(v)); }
         if (k < 4) first[k] = v;
     }
-    if (!cnt) return;
-    /* A BIT-EXACT CHECKSUM OF THE RAW BYTES, beside the summary. The mean is what a reader wants
-     * for "is this tensor plausible"; it is useless for "is this run the same as the last one",
-     * which is the other question this probe gets asked: a single logit moving by 1e-3 shifts the
-     * mean of a vocabulary's worth of them by 1e-8 and prints identical at %.6f. FNV-1a over the
-     * bytes answers that one exactly, and it is the cheap half of the loop. */
+    /* FNV-1a over the raw bytes, to tell whether two runs match exactly; the mean cannot (one logit
+     * moving by 1e-3 shifts a vocabulary's mean by 1e-8). */
     uint64_t h = 1469598103934665603ull;
     for (size_t i = 0; i < raw.size(); ++i) { h ^= raw[i]; h *= 1099511628211ull; }
     const int64_t good = cnt - bad;
@@ -100,94 +77,48 @@ static void dump_row(int step, const char* phase, const char* name, uint32_t dty
               bad ? fmt(" from %lld", (long long)bad_first).c_str() : "",
               (double)first[0], (double)first[1], (double)first[2], (double)first[3]);
 
-    /* ---- THE FIRST N ELEMENTS, IN THE ROW'S OWN TYPE ----------------------------------------
+    /* ---- the first n elements, in the row's own type ----------------------------------------
      *
-     * `RADIANCE_DUMP_HEAD=` prints n elements verbatim, integers included. The summary above
-     * decodes only the float types, so an INDEX plane reports mean 0 and four zeros -- which is
-     * a fair answer to "is this tensor plausible" and no answer at all to "which tokens".
-     *
-     * That second question is what the sampler's candidate planes exist to answer. After
-     * sample_merge_topk, `sampler.cand_idx` holds GLOBAL token ids and `sampler.cand_val` their
-     * logits, descending -- so the pair IS this engine's next-token distribution, read at the one
-     * place it is ever assembled whole across the vocabulary shards.
-     *
-     * WHY THAT IS ENOUGH FOR A KL DIVERGENCE, with no log-sum-exp anywhere. Renormalised over a
-     * fixed candidate set S, p~_i = exp(l_i) / sum_{j in S} exp(l_j) -- the partition function
-     * over the WHOLE vocabulary cancels, in both engines independently. So a top-K KLD against
-     * another engine's top-K logprobs needs only these logits. The OpenAI `logprobs` field carries
-     * the normaliser (sample_logprobs) and only the RAW distribution's top 20; this reads the
-     * plane the pick drew from, which is a probe, and it says so by being an environment variable
-     * at -vv rather than a response field. */
-    static const int head = [] {
-        const char* s = std::getenv("RADIANCE_DUMP_HEAD");
-        const long v = (s && *s) ? std::strtol(s, nullptr, 10) : 0;
-        return (int)(v > 0 ? (v < 4096 ? v : 4096) : 0);
-    }();
+     * RADIANCE_DUMP_HEAD= prints n elements verbatim, including integer planes, which the
+     * summary above cannot decode. After sample_merge_topk, `sampler.cand_idx` holds global token
+     * ids and `sampler.cand_val` their logits, descending: the engine's next-token distribution,
+     * assembled across vocabulary shards. Renormalised over a fixed candidate set the full
+     * vocabulary's partition function cancels, so these logits alone give a top-K KL divergence
+     * against another engine's top-K logprobs. */
+    static const int64_t head = env_count("RADIANCE_DUMP_HEAD", 0, 4096);
     if (head > 0) {
         const int64_t n = std::min(head, cnt);
         std::string hl;
         for (int64_t k = 0; k < n; ++k) {
-            float f = 0;
-            switch (dtype) {
-            case RAD_I32: {
-                int32_t v; std::memcpy(&v, raw.data() + k * 4, 4);
-                hl += fmt(" %d", (int)v); continue;
+            if (dtype == RAD_I32 || dtype == RAD_U32) {
+                uint32_t u; std::memcpy(&u, raw.data() + k * 4, 4);
+                hl += dtype == RAD_I32 ? fmt(" %d", (int)(int32_t)u) : fmt(" %u", (unsigned)u);
+            } else if (fl) {
+                hl += fmt(" %.6f", (double)rad_load_f32(raw.data(), dtype, k));
+            } else {
+                hl += " ?";
             }
-            case RAD_U32: {
-                uint32_t v; std::memcpy(&v, raw.data() + k * 4, 4);
-                hl += fmt(" %u", (unsigned)v); continue;
-            }
-            case RAD_F32: std::memcpy(&f, raw.data() + k * 4, 4); break;
-            case RAD_BF16: {
-                uint32_t u = (uint32_t)(raw[(size_t)(k * 2)] | (raw[(size_t)(k * 2 + 1)] << 8));
-                u <<= 16; std::memcpy(&f, &u, 4); break;
-            }
-            default: hl += " ?"; continue;
-            }
-            hl += fmt(" %.6f", (double)f);
         }
         RAD_TRACE("step %d%-8s %-28s head%s", step, phase, name, hl.c_str());
     }
 
-    /* ---- AND THE TOP K OF THE ROW, A GRADED COMPARISON FROM A SERVING ENGINE ---------------
+    /* ---- the top k of the row ---------------------------------------------------------------
      *
-     * `RADIANCE_DUMP_TOPK=` adds one `topk` line per dumped row: the k largest values and where
-     * they are. The hash above answers "is this run the same as the last one" and nothing else,
-     * and the mean of a vocabulary of logits is identical at %.6f long after the model has started
-     * writing different code -- so the question a LOSSY LEVER asks ("how much worse, if at all")
-     * needs an instrument of its own.
-     *
-     * WHY THIS SHAPE AND NOT A PERPLEXITY. The server's logprobs are the generated positions'
-     * only -- never the prompt's -- and a served prefill produces logits only at the rows
-     * `out_ids` names; the teacher-forced scoring pass is the KL mode's (core/kld.h), which runs in
-     * place of the server. What a serving engine offers: send N distinct prompts at max_tokens = 1,
-     * and every build under comparison sees IDENTICAL inputs at one row each. The top of that row,
-     * over enough prompts, is a next-token distribution comparison -- top-1 agreement, rank
-     * displacement, and the gap between the first and second logit, which is what decides whether a
-     * perturbation can flip the token at all.
-     *
-     * WHY A GENERATED CONTINUATION IS NOT EVIDENCE. Divergence at temperature 0 is chaotic: two
-     * numeric formats can agree for hundreds of tokens and then differ arbitrarily, so one
-     * continuation cannot rank them and the difference it shows says nothing about which is
-     * closer to the unquantised model. N prompts at one row each can. */
-    static const int topk = [] {
-        const char* s = std::getenv("RADIANCE_DUMP_TOPK");
-        const long v = (s && *s) ? std::strtol(s, nullptr, 10) : 0;
-        return (int)(v > 0 ? (v < 64 ? v : 64) : 0);
-    }();
-    if (topk <= 0 || cnt <= 0) return;
+     * RADIANCE_DUMP_TOPK= adds a `topk` line per row: the k largest values and their indices.
+     * It grades a lossy change from a serving engine: N distinct prompts at max_tokens = 1 give
+     * every build identical inputs at one row each, and the top of that row compares next-token
+     * distributions (top-1 agreement, rank displacement, the first-to-second logit gap).
+     * Teacher-forced scoring is the KL mode's (core/kld.h). A generated continuation is not
+     * evidence: greedy divergence is chaotic, so one continuation cannot rank two formats. */
+    static const int64_t topk = env_count("RADIANCE_DUMP_TOPK", 0, 64);
+    if (topk <= 0 || !fl) return;
     /* A partial selection, not a sort: n is the whole vocabulary and this runs on the step path. */
     std::vector> best;
     best.reserve((size_t)topk + 1);
     for (int64_t k = 0; k < cnt; ++k) {
-        float v = 0;
-        if (dtype == RAD_F32) std::memcpy(&v, raw.data() + k * 4, 4);
-        else if (dtype == RAD_BF16) {
-            uint32_t u = (uint32_t)(raw[(size_t)(k * 2)] | (raw[(size_t)(k * 2 + 1)] << 8));
-            u <<= 16; std::memcpy(&v, &u, 4);
-        } else continue;
+        const float v = rad_load_f32(raw.data(), dtype, k);
         if (!std::isfinite(v)) continue;
-        if ((int)best.size() < topk) {
+        if ((int64_t)best.size() < topk) {
             best.emplace_back(v, k);
             std::push_heap(best.begin(), best.end(), std::greater<>());
         } else if (v > best.front().first) {
@@ -202,16 +133,27 @@ static void dump_row(int step, const char* phase, const char* name, uint32_t dty
     RAD_TRACE("step %d%-8s %-28s topk%s", step, phase, name, line.c_str());
 }
 
-/* Whether `name` answers to `want`: the whole name, or its last scope components -- "rank0.h" answers
- * to "h" -- and never a bare suffix, or "moe_logits" would answer to "logits" and, declared first,
- * be the one dumped. */
+/* Whether `name` matches `want`: the whole name or its trailing scope components ("rank0.h"
+ * matches "h"), never a bare suffix ("moe_logits" must not match "logits"). */
 static bool answers_to(const std::string& name, const std::string& want) {
     if (name.size() < want.size() ||
         name.compare(name.size() - want.size(), want.size(), want) != 0) return false;
     return name.size() == want.size() || name[name.size() - want.size() - 1] == '.';
 }
 
-void dump_buffers(Ctx& ctx, int step, const char* names, const char* phase) {
+/* Copy `n` bytes at `ptr` back and print them as one row. */
+static bool dump_at(Ctx& ctx, int step, const char* phase, const std::string& name,
+                    uint32_t dtype, const void* ptr, int64_t n) {
+    std::vector raw((size_t)n);
+    if (n <= 0 || rad_memcpy_async(raw.data(), ptr, n, ctx.stream()) < 0) return false;
+    rad_stream_sync(ctx.stream());
+    dump_row(step, phase, name.c_str(), dtype, raw);
+    return true;
+}
+
+void dump_buffers(Ctx& ctx, int step, const char* phase) {
+    if ((int)log_level() < (int)Log::Trace) return;
+    static const char* const names = std::getenv("RADIANCE_DUMP_BUF");
     if (!names || !*names) return;
     const Program& p = *ctx.program();
     for (const char* s = names; *s; ) {
@@ -221,48 +163,33 @@ void dump_buffers(Ctx& ctx, int step, const char* names, const char* phase) {
         s = *e ? e + 1 : e;
         if (want.empty()) continue;
 
-        /* WEIGHTS ANSWER TO THE SAME NAMES. A declared weight is bytes the engine chose to put
-         * somewhere, exactly as a buffer is, and "did the loader put THIS checkpoint tensor in
-         * THIS declared slot" has no other answer short of reading the container by hand. The
-         * name map is one line per weight and a wrong one is a model that runs and means nothing:
-         * output.weight falling back to token_embd, say, gives a model that copies its prompt
-         * fluently and knows nothing. */
-        for (size_t i = 1; i < p.weights.size(); ++i) {
+        /* Weights match the same names, to check that the loader put the right checkpoint tensor
+         * in each declared slot (a wrong name map still runs, but means nothing). */
+        bool done = false;
+        for (size_t i = 1; i < p.weights.size() && !done; ++i) {
             const WeightInfo& wi = p.weights[i];
             if (!answers_to(wi.name, want)) continue;
             void* ptr = ctx.weight_ptr((rad_weight)i);
             if (!ptr) continue;
-            /* A rank-1 weight IS one row -- a norm gain, A_log, dt_bias. Dividing by shape[0]
-             * there shows a single element, which is exactly enough to miss a conversion that
-             * got the first value right and every one after it wrong. */
+            /* A rank-1 weight (a norm gain, A_log, dt_bias) is one row; dividing by shape[0] would
+             * show a single element. */
             const int64_t row = wi.decl.rank >= 2
                                     ? wi.stored_bytes / (wi.decl.shape[0] ? wi.decl.shape[0] : 1)
                                     : wi.stored_bytes;
             const int64_t n = std::min(row > 0 ? row : wi.stored_bytes, dump_cap());
-            std::vector raw((size_t)n);
-            if (n <= 0 || rad_memcpy_async(raw.data(), ptr, n, ctx.stream()) < 0) continue;
-            rad_stream_sync(ctx.stream());
-            dump_row(step, phase, wi.name.c_str(), wi.decl.dtype, raw);
-            goto next;
+            done = dump_at(ctx, step, phase, wi.name, wi.decl.dtype, ptr, n);
         }
 
-        for (size_t i = 1; i < p.buffers.size(); ++i) {
+        for (size_t i = 1; i < p.buffers.size() && !done; ++i) {
             const BufferInfo& b = p.buffers[i];
             if (!answers_to(b.name, want)) continue;
             void* ptr = ctx.buf_ptr((rad_buf)i);
             if (!ptr) continue;
-
             const int64_t row = b.decl.rank >= 1 ? b.bytes / (b.decl.shape[0] ? b.decl.shape[0] : 1)
                                                  : b.bytes;
-            const int64_t n = std::min(row, dump_cap());
-            std::vector raw((size_t)n);
-            if (rad_memcpy_async(raw.data(), ptr, n, ctx.stream()) < 0) continue;
-            rad_stream_sync(ctx.stream());
-
-            dump_row(step, phase, b.name.c_str(), b.decl.dtype, raw);
-            break;
+            done = dump_at(ctx, step, phase, b.name, b.decl.dtype, ptr,
+                           std::min(row, dump_cap()));
         }
-        next:;
     }
 }
 
diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp
index 000e42f3..3af20b86 100644
--- a/core/format/checkpoint.cpp
+++ b/core/format/checkpoint.cpp
@@ -6,6 +6,7 @@
 
 #include 
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -46,16 +47,13 @@ void MetaOwn::finish() {
 
 /* ---------------------------------------------------------------- config.json
  *
- * A safetensors checkpoint carries its architecture and its dimensions in config.json, and both
- * have to reach the plugin: RadModelMeta's typed fields are what declare sizes everything from, so
- * an unparsed config means a graph built on zeros. Parsing it is the core's job and not the
- * architecture plugin's, because the plugin is handed RadModelMeta and never sees the file.
+ * A safetensors checkpoint's architecture and dimensions live in config.json. The core parses it,
+ * since the plugin only sees RadModelMeta, whose typed fields size everything at declare.
  *
- * Two shapes exist and both are handled. A text-only model puts its dimensions at the top level; a
- * multimodal one nests them under `text_config` and puts the tower under `vision_config`. The
- * nested case is not a special case here: EVERY key is flattened into the free-form list with a
- * dotted path, and the typed fields are then read from `text_config.X` falling back to `X`. So a
- * plugin that wants `vision_config.depth` finds it under exactly that name whatever the nesting.
+ * A text-only model puts its dimensions at the top level; a multimodal one nests them under
+ * `text_config` beside `vision_config`. Every key is flattened into the free-form list by dotted
+ * path, and typed fields are read from `text_config.X`, falling back to `X`, so a plugin finds
+ * `vision_config.depth` under that name either way.
  */
 static void flatten_json(const nlohmann::json& j, const std::string& prefix, MetaOwn* out) {
     for (auto it = j.begin(); it != j.end(); ++it) {
@@ -67,9 +65,9 @@ static void flatten_json(const nlohmann::json& j, const std::string& prefix, Met
         else if (v.is_number())       out->kv(key, fmt("%.17g", v.get()));
         else if (v.is_string())       out->kv(key, v.get());
         else if (v.is_array()) {
-            /* An array of scalars becomes a space-separated string: mrope_section "11 11 10",
-             * layer_types "linear_attention full_attention ...". A plugin splits it. Arrays of
-             * objects are not flattened -- nothing in a config uses one for a dimension. */
+            /* An array of scalars becomes a space-separated string (mrope_section "11 11 10",
+             * layer_types "linear_attention full_attention ..."). Arrays of objects are
+             * skipped. */
             std::string s;
             bool ok = true;
             for (const auto& e : v) {
@@ -85,14 +83,10 @@ static void flatten_json(const nlohmann::json& j, const std::string& prefix, Met
     }
 }
 
-/* A SECOND config.json, flattened under a prefix and nothing else.
- *
- * None of meta_from_config_json's typed extraction applies: a drafter's `num_hidden_layers` is 5
- * and the target's is 64, and writing the drafter's into RadModelMeta would size the trunk from
- * the draft head. So the whole of it goes into the free-form table with `draft.` in front, which
- * is where an architecture plugin reads a dimension the struct does not name anyway. The
- * `text_config` aliasing is deliberately not repeated -- a drafter is a text model by
- * construction, and aliasing here would collide with the target's bare keys. */
+/* A second config.json (a drafter's), flattened under a prefix only. No typed extraction, which
+ * would size the trunk from the draft head; the plugin reads `draft.` keys from the free-form
+ * table. No `text_config` aliasing either: a drafter is a text model, and aliasing would collide
+ * with the target's bare keys. */
 int meta_merge_config_json(const std::string& dir, const std::string& prefix, MetaOwn* out) {
     const std::string path = dir + "/config.json";
     std::ifstream f(path);
@@ -111,22 +105,14 @@ int meta_merge_config_json(const std::string& dir, const std::string& prefix, Me
 
 /* ---------------------------------------------------------------- generation_config.json
  *
- * HOW THE CHECKPOINT SAYS IT WANTS TO BE SAMPLED, carried into the container so that serving it
- * does not depend on a file nobody copied. It is a separate file from config.json because it is a
- * separate thing: config.json is the architecture and is required, this is the sampler and is
- * advisory, and a checkpoint that omits it is read without complaint.
- *
- * It matters more than "advisory" suggests. A model tuned against a truncated tail and served
- * without one will occasionally draw a token from far down its distribution, and end-of-turn is
- * one such token -- so the visible symptom is not bad prose, it is a reply that stops early.
- *
- * Flattened under `generation.` rather than merged into the bare keys: `temperature` and `top_k`
- * are common enough words that a bare spelling would collide with an architecture that happens to
- * use one, and the prefix is what tells a reader which file a value came from. */
+ * The checkpoint's sampling defaults, carried into the container so serving does not depend on a
+ * separate file. Optional. Without them a model tuned with a truncated tail occasionally samples
+ * far down its distribution, including end-of-turn, so replies stop early. Flattened under
+ * `generation.` to avoid colliding with architecture keys such as `temperature` or `top_k`. */
 int meta_merge_generation_config(const std::string& dir, MetaOwn* out) {
     const std::string path = dir + "/generation_config.json";
     std::ifstream f(path);
-    if (!f) return RAD_OK;               /* absent is not an error; nothing is written */
+    if (!f) return RAD_OK;               /* optional */
     nlohmann::json j;
     try { f >> j; }
     catch (const std::exception& e) {
@@ -143,21 +129,19 @@ int meta_merge_generation_config(const std::string& dir, MetaOwn* out) {
 
 /* ---------------------------------------------------------------- the preprocessor configs
  *
- * HOW AN IMAGE AND A VIDEO BECOME PATCHES, carried for the reason the sampling defaults are:
- * serving the model must not depend on a file nobody copied. The engine's processor (core/mm)
- * reads the pixel bands, the normalisation and the frame rate from here; the geometry the encoder
- * itself needs is already in config.json's vision_config. Flattened under their own prefixes --
- * `size.shortest_edge` means two different things in the two files. Absent is not an error: a
- * text model has neither. */
+ * How images and video become patches, carried into the container like the sampling defaults.
+ * core/mm reads pixel bands, normalisation and frame rate from these; the encoder's geometry is
+ * in config.json's vision_config. Each file has its own prefix (`size.shortest_edge` differs
+ * between them). Optional. */
 int meta_merge_preprocessor_configs(const std::string& dir, MetaOwn* out) {
-    /* processor_config.json is the newer single file: one object a sub-processor
-     * (`image_processor`, `video_processor`, `feature_extractor`) beside the processor's own keys
-     * -- EmbeddingGemma 2's image budget and its audio token rate are only there. */
+    /* processor_config.json is the newer single file, one object per sub-processor
+     * (`image_processor`, `video_processor`, `feature_extractor`) beside its own keys
+     * (EmbeddingGemma 2's image budget and audio token rate are only there). */
     static const struct { const char* file; const char* prefix; } kFiles[] = {
         { "preprocessor_config.json", "preprocessor" },
         { "video_preprocessor_config.json", "video_preprocessor" },
         { "processor_config.json", "processor" },
-        /* sentence-transformers' own: an embedding model's named prompts and its default. */
+        /* sentence-transformers: an embedding model's named prompts and default. */
         { "config_sentence_transformers.json", "sentence_transformers" },
     };
     for (const auto& f : kFiles) {
@@ -192,18 +176,9 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
 
     flatten_json(j, "", out);
 
-    /* Alias text_config.X to a bare X wherever no bare X already exists.
-     *
-     * A multimodal checkpoint nests the language model's dimensions under `text_config` and a
-     * text-only one does not; that nesting is the ONLY difference between the two files. The
-     * struct fields below already prefer the prefixed spelling, but the free-form key/value table
-     * is handed to the plugin verbatim, so without this a plugin reading `partial_rotary_factor`
-     * finds nothing on exactly the checkpoints that have a vision tower -- and the failure is at
-     * declare, after the architecture has already been matched. One rule, applied once here, is
-     * better than every plugin having to know what a vision tower does to its config.
-     *
-     * The bare key wins where both exist: a top-level value is the file's own answer, and the
-     * prefixed one is the aliased fallback. */
+    /* Alias text_config.X to a bare X where no bare X exists, so plugins read the same free-form
+     * keys (e.g. `partial_rotary_factor`) with or without a vision tower. A bare key wins where
+     * both exist. */
     {
         const size_t n = out->keys.size();
         for (size_t i = 0; i < n; ++i) {
@@ -217,8 +192,7 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
     }
 
     auto gs = [&](const char* k) -> const char* { return out->get(k); };
-    /* text_config first, then the top level: the nesting is the only difference between a
-     * multimodal config and a text one, and every field below appears in exactly one of the two. */
+    /* text_config first, then the top level. */
     auto gi = [&](const char* k, int64_t dflt) -> int64_t {
         const char* v = gs((std::string("text_config.") + k).c_str());
         if (!v) v = gs(k);
@@ -230,15 +204,13 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
         return v ? strtod(v, nullptr) : dflt;
     };
 
-    /* HuggingFace's model_type is the architecture id, minus the underscores its naming convention
-     * uses and GGUF's does not: `qwen3_5` and GGUF's `qwen35` are the same architecture, and a
-     * plugin should not have to claim both spellings. */
+    /* HuggingFace's model_type minus underscores is the architecture id, matching GGUF's spelling
+     * (`qwen3_5` is `qwen35`). */
     if (const char* mt = gs("model_type")) {
         out->arch.clear();
         for (const char* p = mt; *p; ++p) if (*p != '_') out->arch += *p;
-        /* LFM2-VL is LFM2 with a vision tower, and unlike Qwen's VL releases it names the wrapper
-         * rather than the text model. One plugin serves both, the way one serves a Qwen3.5 with
-         * or without its tower; `model_type` itself stays in the free-form keys. */
+        /* LFM2-VL names the wrapper, not the text model; one plugin serves LFM2 with or without
+         * its tower. `model_type` stays in the free-form keys. */
         if (out->arch == "lfm2vl") out->arch = "lfm2";
     }
     if (const char* nm = gs("_name_or_path")) out->name = nm;
@@ -248,15 +220,12 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
     m.n_embd      = gi("hidden_size", 0);
     m.n_head      = gi("num_attention_heads", 0);
     m.n_head_kv   = gi("num_key_value_heads", m.n_head);
-    /* Read head_dim; do NOT derive it. On qwen35 it is 256 while hidden_size/num_attention_heads
-     * is 213, and a derived value makes every downstream shape silently wrong. */
+    /* Read head_dim; derive it only as a fallback. On qwen35 it is 256 while
+     * hidden_size/num_attention_heads is 213. */
     m.head_dim    = gi("head_dim", m.n_head ? m.n_embd / m.n_head : 0);
-    /* ...AND A ROUTED CHECKPOINT HAS NO `intermediate_size` AT ALL. A routed config states
-     * `moe_intermediate_size` (one expert's width) and `shared_expert_intermediate_size` and
-     * nothing else, so reading only the dense spelling leaves n_ff at zero -- and geom_from refuses
-     * a model with a zero feed-forward width by name, which reads as a broken container rather
-     * than as an unread key. The per-expert width is what a GEMM sees, so it is what n_ff means;
-     * the shared expert's is its own key and the plugin reads it from the free-form table. */
+    /* A routed config has no `intermediate_size`, only `moe_intermediate_size` (one expert's
+     * width, which is what a GEMM sees and what n_ff means) and
+     * `shared_expert_intermediate_size` (read by the plugin from the free-form table). */
     m.n_ff        = gi("intermediate_size", gi("moe_intermediate_size", 0));
     m.n_vocab     = gi("vocab_size", 0);
     m.n_ctx_train = gi("max_position_embeddings", 0);
@@ -265,9 +234,8 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
     m.n_expert_shared = gi("shared_expert_intermediate_size", 0) ? 1 : 0;
     m.rms_eps     = (float)gf("rms_norm_eps", gf("norm_eps", 1e-6));   /* LFM2: norm_eps */
     m.rope_theta  = (float)gf("rope_parameters.rope_theta", gf("rope_theta", 10000.0));
-    /* The rotary's scaling stays in the free-form keys with its type beside it; the architecture
-     * reads both (arch/common/rad_arch.h, yarn_from). A factor copied here without its type would
-     * be a linear position divide for llama3, longrope or YaRN. */
+    /* Rotary scaling stays in the free-form keys with its type (arch/common/rad_arch.h,
+     * yarn_from); a bare factor here would wrongly mean linear scaling. */
     m.rope_scale  = 1.0f;
 
     out->quant = quant_descriptor(*out);
@@ -275,9 +243,9 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
     return RAD_OK;
 }
 
-/* The quantisation descriptor, which with the architecture selects the plugin (spec §2.4).
- * "fp8" plus its format, so qwen35_fp8 and qwen35_bf16 are told apart by the checkpoint
- * rather than by a flag. */
+/* The quantisation descriptor, which with the architecture selects the plugin (spec §2.4): the
+ * quant_method plus its fmt ("fp8_e4m3"), so the checkpoint, not a flag, distinguishes fp8 from
+ * bf16 releases. */
 std::string quant_descriptor(const MetaOwn& m) {
     std::string q;
     if (const char* qm = m.get("quantization_config.quant_method")) {
@@ -294,9 +262,8 @@ int meta_from_gguf(GgufFile& g, MetaOwn* out) {
     }
     g.get_str("general.name", &out->name);
 
-    /* Dimensions come from metadata, so one plugin covers every size in a family. The keys are
-     * GGUF's `.` convention; anything the struct does not name is passed through in
-     * the free-form KV list, which the core never interprets. */
+    /* Dimensions come from GGUF's `.` keys, so one plugin covers a family; other keys
+     * pass through in the free-form list. */
     const std::string a = out->arch;
     auto gi = [&](const char* suffix, int64_t dflt) -> int64_t {
         int64_t v = 0;
@@ -322,15 +289,13 @@ int meta_from_gguf(GgufFile& g, MetaOwn* out) {
     m.rope_theta  = (float)gf("rope.freq_base", 10000.0);
     m.rope_scale  = 1.0f;
 
-    /* THE ROTARY'S SCALING, written as the config.json keys a safetensors release carries, because
-     * those are what the architecture reads (arch/common/rad_arch.h, yarn_from) -- one reader, so
-     * a type is refused or honoured by name whichever file it came from. llama.cpp's YaRN
-     * attn_factor, ext_factor and log multiplier modify the magnitude and ramp in ways config.json
-     * has no spelling for, so a file that sets one to anything but its neutral value is refused
-     * here rather than served as plain YaRN. */
+    /* Rotary scaling, rewritten as config.json keys so one reader handles both formats
+     * (arch/common/rad_arch.h, yarn_from). llama.cpp's YaRN attn_factor, ext_factor and log
+     * multiplier have no config.json spelling, so a non-neutral value is refused rather than
+     * served as plain YaRN. */
     {
-        /* llama.cpp's reading: the type defaults to linear, the factor is rope.scaling.factor or
-         * the older rope.scale_linear, and 0 or 1 is no scaling. */
+        /* As llama.cpp reads it: type defaults to linear, the factor is rope.scaling.factor or
+         * rope.scale_linear, and 0 or 1 means none. */
         std::string type = "linear";
         g.get_str(a + ".rope.scaling.type", &type);
         const double factor = gf("rope.scaling.factor", gf("rope.scale_linear", 0.0));
@@ -367,9 +332,8 @@ int meta_from_gguf(GgufFile& g, MetaOwn* out) {
     if (g.get_strs("tokenizer.ggml.tokens", &toks)) m.n_vocab = (int64_t)toks.size();
     if (m.n_vocab == 0) m.n_vocab = gi("vocab_size", 0);
 
-    /* Everything else, verbatim and stringified. A plugin reads what it needs; the core never
-     * interprets these. Arrays are summarised rather than expanded -- a 151k-token array in a
-     * key/value list is not metadata, it is the vocab, and the vocab has its own section. */
+    /* Everything else, stringified, for the plugin. Arrays are summarised (small integer arrays
+     * spelled out); tokenizer keys are skipped, since the vocab has its own section. */
     for (const GgufKV& kv : g.kv()) {
         if (kv.key.rfind("tokenizer.", 0) == 0) continue;
         std::string v;
@@ -389,10 +353,9 @@ int meta_from_gguf(GgufFile& g, MetaOwn* out) {
         out->kv(kv.key, v);
     }
 
-    /* THE DESCRIPTOR A SAFETENSORS RELEASE WOULD CARRY. A float file -- all F32 (0), mostly F16
-     * (1) or mostly BF16 (32), the vectors F32 either way -- is an unquantised checkpoint and
-     * selects the plugin a bf16 release does. Any other file type names its quantisation, which no
-     * plugin serves as it stands. */
+    /* The descriptor a safetensors release would carry. A float file type (0 all F32, 1 mostly
+     * F16, 32 mostly BF16) is unquantised and selects the bf16 plugin; any other names its
+     * quantisation, which no plugin serves directly. */
     int64_t ftype = 0;
     const bool typed = g.get_i64("general.file_type", &ftype);
     out->quant = !typed || ftype == 0 || ftype == 1 || ftype == 32
@@ -431,9 +394,9 @@ int Checkpoint::add_shard(const std::string& p, const std::string& prefix,
     RAD_TRY(shards_.back()->open(p));
     const std::string file = p.substr(p.find_last_of('/') + 1);
     for (const auto& t : shards_.back()->tensors()) {
-        /* THE INDEX SAYS WHICH SHARD A TENSOR IS READ FROM. A directory that merges two
-         * checkpoints -- a finetune's changed tensors in its own shards beside links to the base
-         * model's -- holds some names in two shards, and only the index tells the copies apart. */
+        /* The index decides which shard a tensor is read from: a directory merging two
+         * checkpoints (a finetune's shards beside links to the base model's) holds some names
+         * twice. */
         if (owner) {
             auto it = owner->find(t.name);
             if (it != owner->end() && it->second != file) continue;
@@ -504,9 +467,18 @@ static int meta_merge_json_file(const std::string& path, const std::string& pref
 
 static bool path_exists(const std::string& p) { std::ifstream f(p); return (bool)f; }
 
-/* A DIFFUSERS PIPELINE: model_index.json at the top and one folder a component, each with its own
- * config and weights. It is read as ONE checkpoint, because the components are one model to the
- * architecture plugin that serves them:
+/* "X.weight" -> "X"; false for a name with no such suffix. */
+static bool weight_base(const std::string& name, std::string* base) {
+    static const std::string suffix = ".weight";
+    if (name.size() <= suffix.size() ||
+        name.compare(name.size() - suffix.size(), suffix.size(), suffix) != 0)
+        return false;
+    *base = name.substr(0, name.size() - suffix.size());
+    return true;
+}
+
+/* A diffusers pipeline: model_index.json at the top and one folder per component, each with its
+ * own config and weights, read as one checkpoint:
  *
  *   text_encoder/   its config.json is the container's model config -- the typed dimensions and
  *                   the bare keys -- and its tensors keep their names;
@@ -515,9 +487,9 @@ static bool path_exists(const std::string& p) { std::ifstream f(p); return (bool
  *   scheduler/      scheduler_config.json under `scheduler.` keys;
  *   processor/ (or tokenizer/)  the tokenizer, the chat template and the preprocessor configs.
  *
- * model_index.json itself goes under `pipeline.` keys, and its `_class_name` names the
- * architecture: `QwenImage21Pipeline` is `qwenimage21`. A component folder may be a link to
- * another pipeline's (a distilled release sharing its base's text encoder). */
+ * model_index.json goes under `pipeline.` keys, and its `_class_name` names the architecture
+ * (`QwenImage21Pipeline` is `qwenimage21`). A component folder may link to another pipeline's (a
+ * distilled release sharing its base's text encoder). */
 int Checkpoint::open_diffusers() {
     kind_ = SafeT;
     RAD_TRY(meta_merge_json_file(dir_ + "/model_index.json", "pipeline", false, &meta_));
@@ -573,7 +545,7 @@ int Checkpoint::open_diffusers() {
 
 int Checkpoint::open_safetensors(const std::string& path) {
     kind_ = SafeT;
-    /* One shard, an index, or the directory holding either: one namespace whichever it is. */
+    /* One shard, an index, or the directory holding either, as one namespace. */
     std::vector shards;
     std::unordered_map owner;
     const bool is_index = path.size() > 10 && path.compare(path.size() - 10, 10, "index.json") == 0;
@@ -606,9 +578,8 @@ int Checkpoint::open_safetensors(const std::string& path) {
     return RAD_OK;
 }
 
-/* WHICH PUBLISHED QUANTISATION THIS IS, from quantization_config alone: the tensors are checked
- * one by one when a weight is resolved (import_piece), so a file that says one thing and holds
- * another is refused at the weight that differs. */
+/* Which published quantisation this is, from quantization_config alone; import_piece checks the
+ * tensors weight by weight, refusing a file at the first weight that disagrees. */
 void Checkpoint::detect_import() {
     auto qc = [&](const std::string& k) {
         const char* v = meta_.get("quantization_config." + k);
@@ -621,14 +592,14 @@ void Checkpoint::detect_import() {
     };
     const std::string qm = qc("quant_method");
     if (qm == "auto-round") {
-        /* AutoRound's GPTQ-compatible export; its own `auto_round` packing is another layout. */
+        /* AutoRound's GPTQ-compatible export; its own `auto_round` packing is not read. */
         const std::string pf = qc("packing_format");
         if (pf == "auto_round:auto_gptq") import_ = Import::Gptq;
         else import_why_ = "AutoRound's packing_format '" + pf + "' is not one this reads; its "
                            "auto_round:auto_gptq export is";
     } else if (qm == "gptq") {
-        /* v1, the format auto_gptq writes: the zero point stored less one. gptq_v2 stores it as
-         * it is, and reading it as v1 would shift every code by one. */
+        /* v1 (auto_gptq's) stores the zero point less one; gptq_v2 does not, and reading it as v1
+         * would shift every code by one. */
         const std::string cf = qc("checkpoint_format");
         if (cf.empty() || cf == "gptq") import_ = Import::Gptq;
         else import_why_ = "GPTQ's checkpoint_format '" + cf + "' is not one this reads; 'gptq' is";
@@ -642,9 +613,15 @@ void Checkpoint::detect_import() {
             import_why_ = "Quark's weight scheme here is not MXFP4 (fp4, per_group 32, e8m0 scales) "
                           "throughout, which is the one this reads";
     } else if (qm == "compressed-tensors") {
-        /* COMPRESSED-TENSORS' PACK-QUANTIZED INT4, symmetric and grouped -- Google's Gemma 4 QAT
-         * release (w4a16-ct) is one. Every config group must say so: a zero point, act-order, a
-         * dynamic or activation scheme would each change what a code means. */
+        /* compressed-tensors states each scheme as a config group with a format. Three are read:
+         *   pack-quantized        symmetric grouped int4 (e.g. Google's Gemma 4 QAT w4a16-ct);
+         *                         every group must be one, and a zero point, act-order, or a
+         *                         dynamic or activation scheme would change what a code means
+         *   nvfp4-pack-quantized  NVFP4: e2m1 codes, an e4m3 scale per 16 of K, an f32 global
+         *                         scale per tensor
+         *   float-quantized       8-bit float weights, read by the FP8 path
+         * NVFP4 and float groups may be mixed (a mixed-precision release ships NVFP4 MLPs beside
+         * FP8 linears); the tensors confirm each weight's form at import_piece and ckpt_resolve. */
         std::vector groups;
         const std::string cg = "quantization_config.config_groups.";
         for (const std::string& k : meta_.keys)
@@ -654,35 +631,62 @@ void Checkpoint::detect_import() {
             }
         std::string why;
         int64_t group = 0;
-        if (qc("format") != "pack-quantized")
-            why = "its format is '" + qc("format") + "', and pack-quantized is the one this reads";
-        if (groups.empty() && why.empty()) why = "its quantization_config names no config group";
+        int n_int4 = 0, n_nvfp4 = 0, n_fp8 = 0;
+        if (groups.empty()) why = "its quantization_config names no config group";
         for (const std::string& g : groups) {
             if (!why.empty()) break;
             const std::string w = "config_groups." + g + ".weights.";
-            const std::string gs = qc(w + "group_size");
-            const long long gn = gs.empty() ? 0 : std::atoll(gs.c_str());
-            if (qc("config_groups." + g + ".format") != "pack-quantized" ||
-                qc(w + "num_bits") != "4" || qc(w + "type") != "int" || qc(w + "symmetric") != "1" ||
-                qc(w + "strategy") != "group" || qc(w + "dynamic") != "0" || gn <= 0 ||
-                !qc(w + "actorder").empty() || any_under("config_groups." + g + ".input_activations."))
-                why = "config group '" + g + "' is not symmetric 4-bit int weights in groups, packed, "
-                      "with no act-order and unquantised activations, which is the one this reads";
-            else if (group && gn != group)
-                why = "its config groups state different group sizes";
-            else
-                group = gn;
+            /* A config without per-group formats states the one format at the top level. */
+            std::string f = qc("config_groups." + g + ".format");
+            if (f.empty()) f = qc("format");
+            if (f == "nvfp4-pack-quantized") {
+                if (qc(w + "num_bits") != "4" || qc(w + "type") != "float" ||
+                    qc(w + "group_size") != "16")
+                    why = "config group '" + g + "' is nvfp4-pack-quantized but its weights are not "
+                          "4-bit floats in groups of 16";
+                ++n_nvfp4;
+            } else if (f == "float-quantized") {
+                if (qc(w + "num_bits") != "8" || qc(w + "type") != "float")
+                    why = "config group '" + g + "' is float-quantized but its weights are not "
+                          "8-bit floats";
+                ++n_fp8;
+            } else if (f == "pack-quantized") {
+                const std::string gs = qc(w + "group_size");
+                const long long gn = gs.empty() ? 0 : std::atoll(gs.c_str());
+                if (qc("format") != "pack-quantized")
+                    why = "its format is '" + qc("format") + "', and an int4 group is read only "
+                          "in a pack-quantized config";
+                else if (qc(w + "num_bits") != "4" || qc(w + "type") != "int" ||
+                         qc(w + "symmetric") != "1" || qc(w + "strategy") != "group" ||
+                         qc(w + "dynamic") != "0" || gn <= 0 || !qc(w + "actorder").empty() ||
+                         any_under("config_groups." + g + ".input_activations."))
+                    why = "config group '" + g + "' is not symmetric 4-bit int weights in groups, "
+                          "packed, with no act-order and unquantised activations, which is the "
+                          "one this reads";
+                else if (group && gn != group)
+                    why = "its config groups state different group sizes";
+                else
+                    group = gn;
+                ++n_int4;
+            } else {
+                why = "config group '" + g + "' is in the format '" + f + "'";
+            }
         }
-        if (why.empty()) {
+        if (why.empty() && n_int4 && (n_nvfp4 || n_fp8))
+            why = "it mixes pack-quantized int4 groups with float ones";
+        if (!why.empty()) {
+            import_why_ = "compressed-tensors: " + why + "; the formats read are pack-quantized "
+                          "(symmetric int4), nvfp4-pack-quantized and float-quantized (8-bit float)";
+        } else if (n_int4) {
             import_ = Import::CtInt4;
             ct_group_ = group;
         } else {
-            import_why_ = "compressed-tensors: " + why;
+            import_ = n_nvfp4 ? Import::Nvfp4 : Import::CtFp8;
         }
     } else if (qm == "paroquant") {
-        /* z-lab's ParoQuant at integer widths, in the "int5-bitplane" packing: AWQ nibbles of the
-         * low four bits plus a bit plane for the fifth, group 128, asymmetric, with the learned
-         * rotations beside. Other widths and packings are not read. */
+        /* z-lab's ParoQuant at integer widths: "int5-bitplane" (AWQ nibbles for the low four bits
+         * plus a fifth-bit plane) or AWQ-packed int4, group 128, asymmetric, with the learned
+         * rotations beside. */
         if (qc("format") == "int5-bitplane" && qc("bits") == "5" && qc("group_size") == "128")
             import_ = Import::ParoI5;
         else if (qc("format").empty() && qc("bits") == "4" && qc("group_size") == "128")
@@ -691,19 +695,18 @@ void Checkpoint::detect_import() {
             import_why_ = "ParoQuant here is neither the int5-bitplane format (5-bit codes) nor z-lab's "
                           "AWQ-packed int4, in groups of 128, which are the ones this reads";
     } else if (qm == "paroquant_mxfp4") {
-        /* QUARK'S MXFP4 PLANES IN A ROTATED BASIS: e2m1 codes, an e8m0 exponent a 32 of K, and per
-         * projection the learned Givens rotations (`pairs`, `theta`) and channel scales in groups
-         * of 128 -- z-lab's ParoQuant, retrained for the MXFP4 grid. */
+        /* Quark's MXFP4 planes in a rotated basis (ParoQuant retrained for the MXFP4 grid): e2m1
+         * codes, an e8m0 exponent per 32 of K, and per projection the learned Givens rotations
+         * (`pairs`, `theta`) and channel scales in groups of 128. */
         if (qc("format") == "mxfp4" && qc("mxfp4_block") == "32" && qc("group_size") == "128")
             import_ = Import::ParoMx;
         else
             import_why_ = "ParoQuant's MXFP4 here is not format mxfp4 with 32-element blocks and "
                           "rotation groups of 128, which is the one this reads";
     }
-    /* THE TOOL'S DESCRIPTION IS KEPT, UNDER ANOTHER NAME. A plugin reads quantization_config as
-     * the statement of the format it serves (qwen35_fp8 checks quant_method is "fp8"), and an
-     * imported checkpoint's says how a tool made it instead: every weight states its own
-     * encoding. Renamed, it still travels into the container as provenance. */
+    /* Rename the tool's quantization_config: plugins read that key as the served format
+     * (qwen35_fp8 checks quant_method is "fp8"), while an imported checkpoint states each weight's
+     * encoding. It stays in the container as provenance. */
     if (import_ != Import::None)
         for (std::string& k : meta_.keys)
             if (k.rfind("quantization_config.", 0) == 0) k = "imported_" + k;
@@ -715,7 +718,8 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
         if (why) *why = std::move(m);
         return rc;
     };
-    if (import_ == Import::None) return RAD_E_NOTFOUND;
+    /* CtFp8 has no imported form: its FP8 weights read stock (ckpt_resolve). */
+    if (import_ == Import::None || import_ == Import::CtFp8) return RAD_E_NOTFOUND;
     if (auto hit = imported_.find(name); hit != imported_.end()) {
         *codes = hit->second.first;
         *scale = hit->second.second;
@@ -724,14 +728,11 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
 
     if (import_ == Import::ParoI5 || import_ == Import::ParoI4) {
         const bool i5 = import_ == Import::ParoI5;
-        /* PARO int5: `X.weight` is X.qweight/.qweight_hi (codes), X.scales (f16 [G, N]) and
-         * X.qzeros/.qzeros_hi (zero points). The view carries the logical [N, K] u5 matrix; the
-         * planes are re-laid row by row by ckpt_plane_rows. */
-        const std::string suffix = ".weight";
-        if (name.size() <= suffix.size() ||
-            name.compare(name.size() - suffix.size(), suffix.size(), suffix) != 0)
-            return RAD_E_NOTFOUND;
-        const std::string base = name.substr(0, name.size() - suffix.size());
+        /* Paro int5: `X.weight` is X.qweight/.qweight_hi (codes), X.scales (f16 [G, N]) and
+         * X.qzeros/.qzeros_hi (zero points). The view describes the logical [N, K] u5 matrix;
+         * ckpt_plane_rows re-lays the planes row by row. */
+        std::string base;
+        if (!weight_base(name, &base)) return RAD_E_NOTFOUND;
         const SrcTensor* qw = find(base + ".qweight");
         if (!qw) return RAD_E_NOTFOUND;
         const SrcTensor* hi = i5 ? find(base + ".qweight_hi") : nullptr;
@@ -767,9 +768,9 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
     }
 
     if (import_ == Import::QuarkMx || import_ == Import::ParoMx) {
-        /* QUARK'S MXFP4 IS THE ENCODING AS IT STANDS: two codes a byte, element 2j in the low
-         * nibble, and one biased exponent a 32 of K -- `fp4_e2m1*e8m0[1x32]`. A view renames the
-         * dtypes and the logical width; no byte moves. Its excluded layers are plain tensors. */
+        /* Quark's MXFP4 is `fp4_e2m1*e8m0[1x32]` as stored: two codes per byte (element 2j in the
+         * low nibble), one biased exponent per 32 of K. The view only renames dtypes and the
+         * logical width. Excluded layers are plain tensors. */
         const SrcTensor* w = find(name);
         const SrcTensor* e = w ? find(name + "_scale") : nullptr;
         if (!w || !e || w->rad_dtype != RAD_U8) return RAD_E_NOTFOUND;
@@ -791,14 +792,12 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
     }
 
     if (import_ == Import::CtInt4) {
-        /* CT-INT4: `X.weight` is shipped as X.weight_packed (i32 [N, K/8], eight codes a word from
-         * the low bits, unsigned about 8) and X.weight_scale ([N, K/group]). The words are the
-         * logical [N, K] code matrix in row order already; only the offset is left for the
-         * relayout. A layer the config ignores is an ordinary X.weight. */
-        const std::string suffix = ".weight";
-        if (name.size() <= suffix.size() ||
-            name.compare(name.size() - suffix.size(), suffix.size(), suffix) != 0)
-            return RAD_E_NOTFOUND;
+        /* CT-INT4: `X.weight` ships as X.weight_packed (i32 [N, K/8], eight codes per word from the
+         * low bits, unsigned about 8) and X.weight_scale ([N, K/group]). The words are already the
+         * [N, K] code matrix in row order; only the offset is left for the relayout. An ignored
+         * layer is an ordinary X.weight. */
+        std::string base;
+        if (!weight_base(name, &base)) return RAD_E_NOTFOUND;
         const SrcTensor* pk = find(name + "_packed");
         if (!pk) return RAD_E_NOTFOUND;
         const SrcTensor* sc = find(name + "_scale");
@@ -837,14 +836,84 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
         return RAD_OK;
     }
 
-    /* GPTQ-PACKED: `X.weight` is shipped as X.qweight, X.scales, X.qzeros and, optionally,
-     * X.g_idx. The width is read off the tensors rather than quantization_config, because a
-     * release may mix widths -- int4 experts beside int8 projections -- and say so only per layer. */
-    const std::string suffix = ".weight";
-    if (name.size() <= suffix.size() ||
-        name.compare(name.size() - suffix.size(), suffix.size(), suffix) != 0)
-        return RAD_E_NOTFOUND;
-    const std::string base = name.substr(0, name.size() - suffix.size());
+    if (import_ == Import::Nvfp4) {
+        /* NVFP4 (compressed-tensors' nvfp4-pack-quantized): `X.weight_packed` U8 [N, K/2], two
+         * e2m1 codes per byte with the even k in the low nibble; `X.weight_scale` e4m3 [N, K/16];
+         * `X.weight_global_scale` f32, one per tensor. The global scale is a divisor: the value is
+         * code * (e4m3 / global), as compressed-tensors' dequantise and vLLM's loader (which
+         * stores 1 / global) compute it. The affine scheme multiplies, so the scale plane is that
+         * quotient in f32, one per 16 of K, owned here. A weight without `X.weight_packed` is not
+         * NVFP4 (a mixed release ships FP8 and bf16 linears beside it) and reads stock. */
+        std::string base;
+        if (!weight_base(name, &base)) return RAD_E_NOTFOUND;
+        const SrcTensor* p = find(base + ".weight_packed");
+        if (!p) return RAD_E_NOTFOUND;
+        if (p->rad_dtype != RAD_U8 || p->shape.size() != 2)
+            return refuse(RAD_E_FORMAT, "'" + p->name + "' is not the U8 [N, K/2] packed tensor the"
+                                        " NVFP4 form ships beside its scales");
+        const SrcTensor* s = find(base + ".weight_scale");
+        if (!s || s->rad_dtype != RAD_F8E4M3 || s->shape.size() != 2)
+            return refuse(RAD_E_FORMAT, "'" + name + "' has no e4m3 [N, K/16] weight_scale beside "
+                                        "its packed codes, which is the form this reads");
+        const SrcTensor* g = find(base + ".weight_global_scale");
+        if (!g || g->rad_dtype != RAD_F32 || g->bytes != 4)
+            return refuse(RAD_E_FORMAT, "'" + name + "' has no single f32 weight_global_scale "
+                                        "beside its packed codes, which is the form this reads");
+        const int64_t N = p->shape[0], K = p->shape[1] * 2;
+        if (N <= 0 || p->shape[1] <= 0 || K % 16)
+            return refuse(RAD_E_SHAPE, "'" + p->name + "' packs " + std::to_string(K) +
+                                       " columns of K, which the 16-wide e4m3 scale does not "
+                                       "divide");
+        if (s->shape[0] != N || s->shape[1] != K / 16)
+            return refuse(RAD_E_SHAPE, "'" + s->name + "' is not the [" + std::to_string(N) +
+                                       ", " + std::to_string(K / 16) + "] e4m3 scale of '" +
+                                       p->name + "'");
+        if (const SrcTensor* ws = find(base + ".weight_shape")) {
+            int64_t dims[2] = { 0, 0 };
+            for (int i = 0; i < 2 && i < (int)ws->numel(); ++i)
+                dims[i] = (int64_t)rad_load_f32(ws->data, ws->rad_dtype, i);
+            if (ws->numel() != 2 || dims[0] != N || dims[1] != K)
+                return refuse(RAD_E_SHAPE, "'" + ws->name + "' does not state the [" +
+                                           std::to_string(N) + ", " + std::to_string(K) +
+                                           "] its codes hold");
+        }
+        float d;
+        std::memcpy(&d, g->data, 4);
+        if (!(d > 0.0f) || !std::isfinite(d))
+            return refuse(RAD_E_FORMAT, "'" + g->name + "' is not a usable f32 divisor: " +
+                                        std::to_string(d));
+        /* e4m3 is exact in f32, so each entry is one f32 division, as in the reference dequant. */
+        const int64_t nsc = N * (K / 16);
+        auto raw = std::make_unique((size_t)nsc * 4);
+        float* tab = reinterpret_cast(raw.get());
+        const uint8_t* sb = (const uint8_t*)s->data;
+        for (int64_t i = 0; i < nsc; ++i) {
+            tab[i] = rad_fp8e4m3_to_f32(sb[(size_t)i]) / d;
+            if (!std::isfinite(tab[i]))
+                return refuse(RAD_E_FORMAT, "'" + s->name + "' holds a scale that is not finite "
+                                            "at element " + std::to_string(i));
+        }
+        owned_.push_back(std::move(raw));
+        SrcTensor sv = *s;
+        sv.rad_dtype = RAD_F32;
+        sv.data      = owned_.back().get();
+        sv.bytes     = nsc * 4;
+        SrcTensor pv = *p;
+        pv.rad_dtype = RAD_FP4E2M1;
+        pv.shape     = { N, K };
+        sliced_.push_back(std::move(pv));
+        *codes = &sliced_.back();
+        sliced_.push_back(std::move(sv));
+        *scale = &sliced_.back();
+        imported_[name] = { *codes, *scale };
+        return RAD_OK;
+    }
+
+    /* GPTQ-packed: `X.weight` ships as X.qweight, X.scales, X.qzeros and optionally X.g_idx. The
+     * width is read from the tensors, not quantization_config, because a release may mix widths
+     * (int4 experts beside int8 projections) and state them only per layer. */
+    std::string base;
+    if (!weight_base(name, &base)) return RAD_E_NOTFOUND;
     const SrcTensor* qw = find(base + ".qweight");
     if (!qw) return RAD_E_NOTFOUND;
     const SrcTensor* sc = find(base + ".scales");
@@ -869,8 +938,8 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
         return refuse(RAD_E_SHAPE, "'" + sc->name + "' is not a [groups, " + std::to_string(N) +
                                    "] scale tensor for " + std::to_string(K) + " columns");
     const int64_t group = K / G;
-    /* THE SERVED SCALE COVERS 128 OF K, so a group of 128 is one scale each and a wider one --
-     * per channel included -- repeats; a narrower group has no form the kernels read. */
+    /* The served scale covers 128 of K: wider groups (per-channel included) repeat it; narrower
+     * groups cannot be represented. */
     if (K % 128 || group % 128)
         return refuse(RAD_E_UNSUPPORTED, what + " has groups of " + std::to_string(group) +
                                          " columns; the imported form scales a 128 of K, so the "
@@ -878,8 +947,8 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
     if (qz->shape[0] != G)
         return refuse(RAD_E_SHAPE, "'" + qz->name + "' has " + std::to_string(qz->shape[0]) +
                                    " rows for " + std::to_string(G) + " groups");
-    /* SYMMETRIC, OR NOT READ: every zero point the v1 2^(bits-1) - 1, which is what makes a code
-     * the signed value it offsets to. An asymmetric weight would need a zero plane. */
+    /* Symmetric only: every zero point must be v1's 2^(bits-1) - 1, so a code offsets to its
+     * signed value. An asymmetric weight would need a zero plane. */
     const uint32_t zero = bits == 4 ? 0x77777777u : 0x7f7f7f7fu;
     for (int64_t i = 0; i < qz->numel(); ++i) {
         uint32_t v;
@@ -888,8 +957,8 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
             return refuse(RAD_E_UNSUPPORTED, "'" + qz->name + "' holds a zero point other than "
                                              "the symmetric one; an asymmetric weight is not read");
     }
-    /* AND IN ORDER: act-order (desc_act) permutes the columns' groups, which a [1x128] scale
-     * cannot follow. The identity, or none, is the only g_idx read. */
+    /* In order only: act-order (desc_act) permutes column groups, which a [1x128] scale cannot
+     * follow, so g_idx must be absent or the identity. */
     if (gi) {
         if (gi->rad_dtype != RAD_I32 || gi->numel() != K)
             return refuse(RAD_E_FORMAT, "'" + gi->name + "' is not an int32 [K] group index");
@@ -949,16 +1018,10 @@ const SrcTensor* Checkpoint::find(const std::string& n) const {
     return it == index_.end() ? nullptr : &tensors_[it->second];
 }
 
-/* ONE EXPERT'S SLICE OF A STACKED TENSOR, AS A VIEW.
- *
- * Slicing dim 0 of a row-major tensor is an offset and a shorter shape -- nothing is copied, so
- * the 512 declared weights of a MoE layer read 512 disjoint windows of the same mapped bytes.
- *
- * IT IS ALSO EXACT FOR A BLOCK-QUANTISED SOURCE, and that is not luck: ggml packs blocks along the
- * ROW, and a dim-0 slice is a whole number of rows, so a sub-tensor is a whole number of blocks.
- * `bytes % shape[0] == 0` therefore holds for every dtype and the division is the real byte count
- * rather than an estimate of one. A slice along any other dimension would not have that property
- * and is not offered. */
+/* One expert's slice of a stacked tensor, as a view: slicing dim 0 of a row-major tensor is an
+ * offset and a shorter shape, with nothing copied. It is exact for block-quantised sources too:
+ * ggml packs blocks along the row, so a dim-0 slice is whole blocks and `bytes / shape[0]` is the
+ * exact byte count. Slicing other dimensions is not offered. */
 const SrcTensor* Checkpoint::slice(const SrcTensor& st, int index, const char* declared) {
     if (st.shape.size() < 2) {
         RAD_ERR("'%s' asks for sub-tensor %d of '%s', which has rank %zu. Only a STACKED tensor "
@@ -979,8 +1042,7 @@ const SrcTensor* Checkpoint::slice(const SrcTensor& st, int index, const char* d
         return nullptr;
     }
     SrcTensor v;
-    /* The name carries the index because every diagnostic below this point prints it, and
-     * "experts.gate_up_proj" said 512 times for 512 different weights cannot be read. */
+    /* The name carries the index so diagnostics distinguish the slices. */
     v.name      = st.name + "[" + std::to_string(index) + "]";
     v.ggml      = st.ggml;
     v.rad_dtype = st.rad_dtype;
@@ -995,9 +1057,6 @@ const SrcTensor* Checkpoint::slice(const SrcTensor& st, int index, const char* d
 
 namespace {
 
-/* FP8's scale plane is a companion tensor: `X.weight` is scaled by `X.weight_scale_inv`. */
-std::string scale_name(const std::string& codes) { return codes + "_scale_inv"; }
-
 }  /* namespace */
 
 std::string ckpt_tensor_of(const SrcTensor& t) {
@@ -1022,24 +1081,21 @@ bool ckpt_reads_any(const CkptWeight& w, const std::unordered_set&
 
 namespace {
 
-/* The ROTATION GROUP of a ParoQuant checkpoint: pairs address columns within a group of 128. */
+/* ParoQuant's rotation group: pairs address columns within a group of 128. */
 constexpr int64_t kParoGroup = 128;
 
 /* "model.layers.0.mlp.down_proj.weight" -> "model.layers.0.mlp.down_proj" */
 std::string paro_base(const SrcTensor& piece) {
-    std::string n = ckpt_tensor_of(piece);
-    const std::string suffix = ".weight";
-    return n.size() > suffix.size() && n.compare(n.size() - suffix.size(), suffix.size(), suffix) == 0
-               ? n.substr(0, n.size() - suffix.size()) : n;
+    const std::string n = ckpt_tensor_of(piece);
+    std::string base;
+    return weight_base(n, &base) ? base : n;
 }
 
 }  /* namespace */
 
-/* ONE (PART, GROUP)'S STAGES COMPOSED INTO ITS DENSE MATRIX: out[j * 128 + i] is output j of the
- * stages fed the unit vector e_i, applied in table order (stage 0 first) as a' = a cos t + b sin t,
- * b' = b cos t - a sin t -- libref's loop. In f64 throughout (the f32 angles widened, cos, sin and
- * every product in double), so the error (~1e-15) is far below an f16 step and the bytes are the
- * exact composition rounded to f16 by way of f32, whichever libm or summation order computed it. */
+/* Stages applied in table order (stage 0 first) as a' = a cos t + b sin t, b' = b cos t - a sin t
+ * (libref's loop), in f64 throughout. The error (~1e-15) is far below an f16 step, so the output is
+ * the exact composition rounded to f16 via f32 regardless of libm or summation order. */
 void paro_compose_dense(int64_t S, const int32_t* ia, const int32_t* ib, const float* th,
                         uint16_t* out) {
     constexpr int64_t G = kParoGroup, H = kParoGroup / 2;
@@ -1062,12 +1118,12 @@ void paro_compose_dense(int64_t S, const int32_t* ia, const int32_t* ib, const f
 
 namespace {
 
-/* PARTS: EACH PIECE OF A ROTATED WEIGHT HAS ITS OWN ROTATION. A fused gate_up or q|k|v is several
- * checkpoint projections, each learned with its own pairs, angles and channel scales, so the
- * fused weight is one row PART per piece (abi/rad_encoding.h, "givens"). Gives the encoding its
- * four tables -- t.pairs and t.angle stage-major per part, t.scale a row per part, t.part the end
- * row of each -- and refuses a rotation that is not what the kernels read: a pair that leaves its
- * group of 128, or a stage that does not use every column of a group exactly once. */
+/* Each piece of a rotated weight has its own rotation: a fused gate_up or q|k|v is several
+ * projections with their own pairs, angles and channel scales, so the fused weight has one row
+ * part per piece (abi/rad_encoding.h, "givens"). Adds the tables (t.pairs and t.angle stage-major
+ * per part, t.scale one row per part, t.part each part's end row, t.dense) and refuses a rotation
+ * the kernels cannot read: a pair leaving its group of 128, or a stage that does not use every
+ * column of a group exactly once. */
 int paro_attach(Checkpoint& ck, CkptWeight* out, std::string* why) {
     auto refuse = [&](std::string m) {
         if (why) *why = std::move(m);
@@ -1095,7 +1151,7 @@ int paro_attach(Checkpoint& ck, CkptWeight* out, std::string* why) {
         if (S == 0) S = pr->shape[0];
         if (pr->shape[0] != S)
             return refuse("the pieces of '" + out->name + "' have different numbers of rotation stages");
-        /* every stage is a perfect matching of each group's 128 columns */
+        /* Every stage must be a perfect matching of each group's 128 columns. */
         const int16_t* pv = (const int16_t*)pr->data;
         for (int64_t st = 0; st < S; ++st)
             for (int64_t g = 0; g < K / kParoGroup; ++g) {
@@ -1118,10 +1174,10 @@ int paro_attach(Checkpoint& ck, CkptWeight* out, std::string* why) {
     rad_enc_add_table(&e, "t.angle", RAD_F32, P * S, K / 2);
     rad_enc_add_table(&e, "t.scale", RAD_F32, P, K);
     if (P > 1) rad_enc_add_table(&e, "t.part", RAD_I32, 1, P);
-    /* THE DENSE MATRICES, composed here and stored: the prefill quantiser (givens_dense_quant) applies a
-     * (part, group)'s stages as one 128 x 128 matrix, and a matrix is a number a kernel library must
-     * not choose at load (abi/rad_abi.h, weight layout) -- the pairs and angles stay for the stage-wise
-     * rotation the 16-bit GEMMs read. */
+    /* The dense matrices are composed and stored here, since the prefill quantiser
+     * (givens_dense_quant) applies a (part, group) as one 128 x 128 matrix and a kernel library
+     * must not compute weight values at load (abi/rad_abi.h, weight layout). The pairs and angles
+     * stay for the 16-bit GEMMs' stage-wise rotation. */
     if (rad_enc_add_table(&e, "t.dense", RAD_F16, P * K / kParoGroup, kParoGroup * kParoGroup) < 0)
         return refuse("'" + out->name + "' has more planes than an encoding holds");
     if (!rad_enc_valid(&e)) return refuse("the rotation tables of '" + out->name + "' are malformed");
@@ -1144,9 +1200,8 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
     *out = CkptWeight{};
     out->name = name;
 
-    /* EVERY map for the name, in declaration order. A CONCAT map may be declared in several
-     * calls -- the ABI's `src[8]` against a 128-shard tensor -- and they join end to end; every
-     * other repeat was refused at declare, so more than one implies CONCAT. */
+    /* Every map for the name in declaration order. Only a CONCAT map may be declared in pieces
+     * (declare refused other repeats); the pieces join end to end. */
     std::vector maps;
     for (const auto& nm : prog.name_map)
         if (nm.declared && name == nm.declared) maps.push_back(&nm);
@@ -1157,28 +1212,22 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
         for (int k = 0; k < pm->n_src; ++k) srcs.push_back({ pm->src[k], pm->src_index[k] });
     out->concat_dim = maps.front()->concat_dim;
 
-    /* THE MODE DECIDES WHAT SEVERAL SOURCES MEAN.
+    /* The mode decides what several sources mean:
      *
-     *   RAD_MAP_CONCAT   all of them, joined -- gate and up into gate_up.
-     *   RAD_MAP_COPY     ALTERNATIVES, first present wins: a tied lm_head is output.weight where
-     *                    the checkpoint ships one and the embedding where it does not.
-     *
-     * Treating a COPY's alternatives as a concatenation is silently wrong in both directions: a
-     * checkpoint holding both writes the head at twice its rows, and one holding only the
-     * embedding fails at the missing first source instead of falling back to it. */
+     *   RAD_MAP_CONCAT   all, joined (gate and up into gate_up).
+     *   RAD_MAP_COPY     alternatives, first present wins (a tied lm_head is output.weight when
+     *                    shipped, else the embedding). */
     const bool alternatives = maps.front()->mode == RAD_MAP_COPY && srcs.size() > 1;
     for (const Src1& s1 : srcs) {
         const SrcTensor* st = ck.find(s1.name);
-        const SrcTensor* sc = st ? ck.find(scale_name(s1.name)) : nullptr;
-        /* ParoQuant's fp8 heads and embedding carry ONE f32 SCALE A ROW (`X.weight_scale`, [N]),
-         * not a block plane: Quark's `_scale` naming for a per-channel weight. */
-        if (st && !sc && ck.imports() == Checkpoint::Import::ParoMx &&
-            (st->rad_dtype == RAD_F8E4M3 || st->rad_dtype == RAD_F8E5M2) && st->shape.size() == 2) {
-            const SrcTensor* pr = ck.find(std::string(s1.name) + "_scale");
-            if (pr && pr->rad_dtype == RAD_F32 && pr->shape.size() == 1 && pr->shape[0] == st->shape[0])
-                sc = pr;
-        }
-        /* A WEIGHT THE CHECKPOINT SHIPS IN AN IMPORTED FORM is read through that form's views. */
+        /* An FP8 weight's scale plane: `X.weight_scale_inv` (block-scaled releases) or
+         * `X.weight_scale` (compressed-tensors' and Quark's naming, one per row or per block).
+         * Only an FP8 tensor takes `X.weight_scale`, so a float weight beside an unrelated tensor
+         * of that name reads plain. An imported weight's planes come from import_piece below. */
+        const SrcTensor* sc = st ? ck.find(std::string(s1.name) + "_scale_inv") : nullptr;
+        if (!sc && st && (st->rad_dtype == RAD_F8E4M3 || st->rad_dtype == RAD_F8E5M2))
+            sc = ck.find(std::string(s1.name) + "_scale");
+        /* A weight shipped in an imported form is read through that form's views. */
         {
             const SrcTensor *ic = nullptr, *is = nullptr;
             std::string iw;
@@ -1194,9 +1243,8 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
                 return refuse(ir, iw);
             }
         }
-        /* A SUB-TENSOR INDEX IS TAKEN, never ignored: ignoring it gives every expert a copy of
-         * the whole stack, in a model that loads and answers. Its scale plane is stacked the same
-         * way and sliced at the same index. */
+        /* A sub-tensor index is always applied (ignoring it would give every expert the whole
+         * stack). Its scale plane is sliced at the same index. */
         if (st && s1.index >= 0) {
             st = ck.slice(*st, s1.index, name.c_str());
             if (!st) return refuse(RAD_E_SHAPE, "a sub-tensor it names is not there");
@@ -1221,9 +1269,8 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
                                       " holds none of them");
     }
 
-    /* THE LOGICAL SHAPE: the pieces joined along concat_dim, every other extent agreeing. A
-     * rank-0 tensor is one element and is read as shape [1]: safetensors stores a scalar
-     * parameter (Gemma 4's clipped-linear bounds) with an empty shape. */
+    /* The logical shape: pieces joined along concat_dim, other extents equal. A rank-0 tensor
+     * (safetensors' scalar, e.g. Gemma 4's clipped-linear bounds) reads as shape [1]. */
     const SrcTensor& p0 = *out->pieces[0];
     const int d = out->concat_dim;
     auto shape_of = [](const SrcTensor& t) {
@@ -1248,7 +1295,7 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
     }
     rad_enc_view(out->rank, out->shape, &out->rows, &out->cols);
 
-    /* THE ENCODING THE PIECES ARE, when it is trivial (spec §4.3). */
+    /* The pieces' encoding, when trivial (spec §4.3), or imported. */
     const uint32_t dt = p0.rad_dtype;
     bool same = true, scaled = true, unscaled = true;
     for (size_t k = 0; k < out->pieces.size(); ++k) {
@@ -1261,8 +1308,8 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
     } else if (!same) {
         out->why = "its pieces are stored in different dtypes";
     } else if (p0.pbits) {
-        /* PARO int5-bitplane: u5 codes, an f16 scale and a u8 zero point a 128 of K, then the
-         * rotation tables. Joined only along rows (gate|up), as every imported form is. */
+        /* Paro int5-bitplane: u5 codes, an f16 scale and u8 zero point per 128 of K, then the
+         * rotation tables. Joined only along rows (gate|up), as every imported form. */
         bool fits = d == 0 || out->pieces.size() == 1;
         for (const SrcTensor* pk : out->pieces) fits = fits && pk->pbits == p0.pbits;
         if (!fits) {
@@ -1280,8 +1327,8 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
                        "serve the container it writes";
         }
     } else if (p0.gptq_bits) {
-        /* GPTQ-PACKED, IMPORTED: one width and one group throughout, joined only along rows --
-         * a column join would put two pieces' groups in one scale block. */
+        /* GPTQ-packed: one width and group throughout, joined only along rows (a column join
+         * would put two pieces' groups in one scale block). */
         out->imported = true;
         for (size_t k = 1; k < out->pieces.size() && out->imported; ++k)
             if (out->pieces[k]->gptq_bits != p0.gptq_bits ||
@@ -1302,9 +1349,30 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
                        "rad-convert imports with its scales rounded to bf16 -- serve the "
                        "container it writes";
         }
+    } else if (dt == RAD_FP4E2M1 && scaled && ck.imports() == Checkpoint::Import::Nvfp4) {
+        /* NVFP4 as import_piece reads it: e2m1 codes beside the f32 quotient e4m3 / global, one
+         * per 16 of K, each piece with its own global. Not trivial (the scale is derived), so the
+         * loader refuses it and rad-convert decodes it for a recipe. Joined only along rows: the
+         * planes and the f32 read follow the pieces row by row. */
+        bool f32 = true;
+        for (const SrcTensor* s : out->scales) f32 = f32 && s->rad_dtype == RAD_F32;
+        if (!f32) {
+            out->why = "its FP4 pieces are not all NVFP4";
+        } else if (d != 0 && out->pieces.size() > 1) {
+            out->why = "its NVFP4 pieces are joined along a column, across their global scales";
+        } else {
+            out->imported = true;
+            out->why = "it is NVFP4 (e2m1 codes, an e4m3 scale per 16 of K and an f32 global "
+                       "scale per tensor), which no kernel serves; rad-convert decodes it for a "
+                       "recipe rule";
+            rad_enc_clear(&out->enc);
+            rad_enc_copy_str(out->enc.scheme, "affine");
+            rad_enc_add_plane(&out->enc, "codes", RAD_FP4E2M1, 1, 1);
+            rad_enc_add_plane(&out->enc, "scale", RAD_F32, 1, 16);
+        }
     } else if (dt == RAD_FP4E2M1 && scaled) {
-        /* QUARK'S MXFP4, byte for byte: the codes and exponents are the planes of
-         * `fp4_e2m1*e8m0[1x32]`. Joined only along rows, which is how gate and up become one. */
+        /* Quark's MXFP4 byte for byte: codes and exponents are the planes of
+         * `fp4_e2m1*e8m0[1x32]`. Joined only along rows (gate and up). */
         out->trivial = d == 0 || out->pieces.size() == 1;
         if (!out->trivial) out->why = "its MXFP4 pieces are joined along a column";
         if (out->trivial) {
@@ -1318,18 +1386,21 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
             }
         }
     } else if ((dt == RAD_F8E4M3 || dt == RAD_F8E5M2) && scaled) {
-        /* BLOCK-SCALED FP8, byte for byte: the codes and the scale plane are the planes of
-         * `fp8_e4m3*bf16[128x128]` (whatever the scale's own dtype). Joined only along rows, and
-         * only where each piece but the last fills its last row block -- a scale covering the
-         * tail of one piece and the head of the next belongs to neither. */
+        /* FP8 codes with a scale plane of one dtype, in one of two shapes per piece:
+         *   block    [ceil(N/br), ceil(K/bc)], the checkpoint's block (128x128 unless stated):
+         *            `fp8_e4m3*[brxbc]`
+         *   per row  [N] or [N, 1] (compressed-tensors' channel strategy, ParoQuant's heads):
+         *            `fp8_e4m3*[1x*]`
+         * Both are byte for byte when joined along rows, and a block join only where each piece
+         * but the last fills its last row block. A row join that ends inside a block is still
+         * read piece by piece, so it keeps its encoding without being trivial. Mixed shapes and
+         * column joins state no encoding: ckpt_rows_f32 reads scales along rows only, so it
+         * refuses them with `why`. */
         const int64_t br = ck.fp8_block_rows(), bc = ck.fp8_block_cols();
         const uint32_t sdt = out->scales[0]->rad_dtype;
-        out->trivial = true;
-        if (d != 0 && out->pieces.size() > 1) {
-            out->trivial = false;
-            out->why = "its FP8 pieces are joined along a column, across their scale blocks";
-        }
-        for (size_t k = 0; k < out->pieces.size() && out->trivial; ++k) {
+        int n_row = 0, n_blk = 0;
+        bool bad = false;
+        for (size_t k = 0; k < out->pieces.size() && !bad; ++k) {
             const SrcTensor& pk = *out->pieces[k];
             const SrcTensor& sk = *out->scales[k];
             int64_t r = 0, c = 0;
@@ -1337,31 +1408,50 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
             const int64_t want_r = (r + br - 1) / br, want_c = (c + bc - 1) / bc;
             int64_t sr = 0, scl = 0;
             rad_enc_view((uint32_t)sk.shape.size(), sk.shape.data(), &sr, &scl);
-            const bool per_row = sk.shape.size() == 1;       /* one scale a row; see above */
-            if (per_row && sk.shape[0] == r && sk.rad_dtype == sdt) {
-                /* fits */
-            } else if (per_row || sk.rad_dtype != sdt || sr != want_r || scl != want_c) {
-                out->trivial = false;
-                out->why = "'" + sk.name + "' is not the [" + std::to_string(want_r) + ", " +
+            /* A rank-1 plane is per row; a wider one is a block plane first, then [N, 1]. */
+            const bool row1 = sk.shape.size() == 1 && sk.shape[0] == r;
+            const bool blk = sk.shape.size() >= 2 && sr == want_r && scl == want_c;
+            const bool row2 = sk.shape.size() >= 2 && sr == r && scl == 1;
+            if (sk.rad_dtype != sdt) {
+                bad = true;
+                out->why = "its FP8 pieces' scale planes differ in dtype";
+            } else if (row1) {
+                ++n_row;
+            } else if (blk) {
+                ++n_blk;
+                if (out->why.empty() && k + 1 < out->pieces.size() && r % br)
+                    out->why = "'" + pk.name + "' ends inside a scale block, so the next piece's "
+                               "scales cannot follow it";
+            } else if (row2) {
+                ++n_row;
+            } else {
+                bad = true;
+                out->why = "'" + sk.name + "' is neither the [" + std::to_string(want_r) + ", " +
                            std::to_string(want_c) + "] " + std::to_string(br) + "x" +
-                           std::to_string(bc) + " scale plane of '" + pk.name + "'";
-            } else if (k + 1 < out->pieces.size() && r % br) {
-                out->trivial = false;
-                out->why = "'" + pk.name + "' ends inside a scale block, so the next piece's "
-                           "scales cannot follow it";
+                           std::to_string(bc) + " scale plane of '" + pk.name + "' nor one "
+                           "scale per row";
             }
         }
-        if (out->trivial) {
+        if (!bad && n_row && n_blk) {
+            bad = true;
+            out->why = "its FP8 pieces disagree: some scale per row, some per " +
+                       std::to_string(br) + "x" + std::to_string(bc) + " block";
+        }
+        if (!bad && d != 0 && out->pieces.size() > 1) {
+            bad = true;
+            out->why = "its FP8 pieces are joined along a column, across their scale planes";
+        }
+        if (!bad) {
+            out->trivial = out->why.empty();
             rad_enc_clear(&out->enc);
             rad_enc_copy_str(out->enc.scheme, "affine");
             rad_enc_add_plane(&out->enc, "codes", dt, 1, 1);
-            if (out->scales[0]->shape.size() == 1) rad_enc_add_plane(&out->enc, "scale", sdt, 1, 0);
+            if (n_row) rad_enc_add_plane(&out->enc, "scale", sdt, 1, 0);
             else rad_enc_add_plane(&out->enc, "scale", sdt, br, bc);
         }
     } else if (p0.ct_group) {
-        /* CT-INT4, IMPORTED: one group throughout and joined only along rows, as GPTQ's. The codes
-         * become signed i4 (the offset flipped out at relayout) and the scale is the plane as
-         * shipped, one a group of K. A kernel reads that group or a recipe re-quantises it. */
+        /* CT-INT4: one group throughout, joined only along rows, as GPTQ. Codes become signed i4
+         * (the offset removed at relayout) and the scale plane is as shipped, one per group of K. */
         out->imported = true;
         for (size_t k = 1; k < out->pieces.size() && out->imported; ++k)
             if (out->pieces[k]->ct_group != p0.ct_group ||
@@ -1396,10 +1486,8 @@ namespace {
 
 /* ---------------------------------------------------------------- GGUF block types
  *
- * The ggml block types a weight can be read from as f32. Their GEOMETRY is core/text's -- that is
- * what sizes a tensor -- and decoding one is content, so the short table is here, where a weight
- * is read. The K-quants are refused by name rather than half-implemented: a super-block scale read
- * wrong is a model that talks and is wrong. */
+ * ggml block types decodable to f32. Their geometry lives in core/text; decoding lives here, where
+ * weights are read. K-quants are refused rather than half-implemented. */
 enum { GGML_F32 = 0, GGML_F16 = 1, GGML_Q4_0 = 2, GGML_Q4_1 = 3, GGML_Q5_0 = 6, GGML_Q5_1 = 7,
        GGML_Q8_0 = 8, GGML_BF16 = 30 };
 
@@ -1493,8 +1581,8 @@ struct Joined {
 /* `n` elements of a stored-dtype piece from element `e`, as f32. */
 int piece_f32(const SrcTensor& t, int64_t e, int64_t n, float* out) {
     if (t.ct_group) {
-        /* the signed code: element (row, k) of the logical [N, K] matrix is nibble k % 8 of word
-         * [row, k / 8], less 8 */
+        /* Element (row, k) of the logical [N, K] matrix is nibble k % 8 of word [row, k / 8],
+         * less 8. */
         const int64_t K = t.shape[1];
         for (int64_t i = 0; i < n; ++i) {
             const int64_t row = (e + i) / K, k = (e + i) % K;
@@ -1505,8 +1593,8 @@ int piece_f32(const SrcTensor& t, int64_t e, int64_t n, float* out) {
         return RAD_OK;
     }
     if (t.gptq_bits) {
-        /* the signed code: element (row, k) of the logical [N, K] matrix is field k % (32/bits)
-         * of word [k / (32/bits), row], less its zero point */
+        /* Element (row, k) of the logical [N, K] matrix is field k % (32/bits) of word
+         * [k / (32/bits), row], less the zero point. */
         const int64_t N = t.shape[0], K = t.shape[1];
         const int64_t per = 32 / t.gptq_bits;
         const uint32_t mask = (1u << t.gptq_bits) - 1u;
@@ -1520,7 +1608,7 @@ int piece_f32(const SrcTensor& t, int64_t e, int64_t n, float* out) {
         return RAD_OK;
     }
     if (t.rad_dtype == RAD_DT_INVALID) {
-        /* a GGUF block type: whole rows only, and a row is whole blocks */
+        /* A GGUF block type: whole rows only (a row is whole blocks). */
         const int64_t cols = t.shape.back();
         if (cols <= 0 || e % cols || n % cols) return RAD_E_SHAPE;
         const int64_t rows = t.numel() / cols, rb = t.bytes / (rows ? rows : 1);
@@ -1532,8 +1620,8 @@ int piece_f32(const SrcTensor& t, int64_t e, int64_t n, float* out) {
             std::memcpy(out, (const float*)t.data + e, (size_t)n * 4);
             return RAD_OK;
         case RAD_BF16: {
-            /* The top half of an f32, so a shift -- and a loop the compiler vectorises, which the
-             * per-element dtype switch below is not. Most of a checkpoint is this. */
+            /* bf16 is the top half of an f32: a shift in a loop the compiler vectorises (the
+             * per-element switch below does not). Most checkpoints are mostly bf16. */
             const uint16_t* q = (const uint16_t*)t.data + e;
             for (int64_t i = 0; i < n; ++i) {
                 const uint32_t u = (uint32_t)q[i] << 16;
@@ -1558,14 +1646,14 @@ int ckpt_rows_f32(const CkptWeight& w, int64_t r0, int64_t nr, float* out, std::
         return rc;
     };
     if (r0 < 0 || nr < 0 || r0 + nr > w.rows) return refuse(RAD_E_SHAPE, "rows out of range");
-    /* A ROTATED WEIGHT's codes are in the rotated basis; its f32 value would be the unrotated one,
-     * which only a decoder over the container's tables computes. Nothing quantises it again. */
+    /* A rotated weight's codes are in the rotated basis; its f32 value needs the container's tables
+     * to decode, and nothing re-quantises it. */
     if (w.paro)
         return refuse(RAD_E_UNSUPPORTED, "'" + w.name + "' is a ParoQuant weight, stored rotated; "
                                          "it is kept as it is and has no f32 view here");
     Joined j;
     j.init(w.pieces, w.concat_dim);
-    /* the runs come in order, so the cursor is the elements already written */
+    /* Runs arrive in order, so the cursor is the count already written. */
     int64_t at = 0;
     const int rc = j.walk(r0 * w.cols, (r0 + nr) * w.cols, [&](int k, int64_t e, int64_t n) {
         const int s = piece_f32(*w.pieces[(size_t)k], e, n, out + at);
@@ -1580,9 +1668,10 @@ int ckpt_rows_f32(const CkptWeight& w, int64_t r0, int64_t nr, float* out, std::
                                                               : "?")
                                             : std::string(rad_dtype_name(w.pieces[0]->rad_dtype))) +
                           ")");
-    /* AN IMPORTED CODE TIMES ITS GROUP'S SCALE, the scale read as shipped: GPTQ's scale tensor is
-     * [groups, N], so row r's scales are a column of it; CT-INT4's is [N, groups], a row. */
-    if (w.imported) {
+    /* An imported code times its group's shipped scale: GPTQ's scales are [groups, N] (row r's are
+     * a column), CT-INT4's are [N, groups] (a row). An NVFP4 import has neither group and takes
+     * the scale-plane form below. */
+    if (w.imported && (w.pieces[0]->gptq_group || w.pieces[0]->ct_group)) {
         int64_t base = 0;
         for (size_t k = 0; k < w.pieces.size(); ++k) {
             const SrcTensor& pk = *w.pieces[k];
@@ -1598,20 +1687,26 @@ int ckpt_rows_f32(const CkptWeight& w, int64_t r0, int64_t nr, float* out, std::
         }
         return RAD_OK;
     }
-    /* FP8 IS ITS CODE TIMES ITS BLOCK'S SCALE (and MXFP4 its code times its exponent): the pieces
-     * are joined along rows, so logical row r is in the piece whose rows cover it, and its scales
-     * are that piece's. */
-    if (!w.scales.empty() && w.scales[0]) {
-        const int64_t br = w.enc.n_planes > 1 ? w.enc.plane[1].block[0] : 128;
-        /* a block extent of 0 is the whole extent: a scale a row, one column of scales */
-        const int64_t bc0 = w.enc.n_planes > 1 ? w.enc.plane[1].block[1] : 128;
+    /* A code times its scale-plane element (FP8's block or row scale, MXFP4's exponent, NVFP4's
+     * folded scale). Pieces join along rows, so logical row r takes its covering piece's plane.
+     * A weight whose planes ckpt_resolve could not state an encoding for (mixed shapes, a
+     * column join, a piece without a plane) is refused rather than read with a guessed block. */
+    bool has_scale = false;
+    for (const SrcTensor* s : w.scales)
+        if (s) { has_scale = true; break; }
+    if (has_scale) {
+        if (w.enc.n_planes < 2)
+            return refuse(RAD_E_UNSUPPORTED, "'" + w.name + "' has a scale plane with no stated "
+                                             "encoding" + (w.why.empty() ? "" : ": " + w.why));
+        /* A block extent of 0 is the whole extent (one scale per row or per column). */
+        const int64_t br0 = w.enc.plane[1].block[0], bc0 = w.enc.plane[1].block[1];
         int64_t base = 0;
         for (size_t k = 0; k < w.pieces.size(); ++k) {
             const SrcTensor& pk = *w.pieces[k];
             const SrcTensor& sk = *w.scales[k];
             int64_t pr = 0, pc = 0;
             rad_enc_view((uint32_t)pk.shape.size(), pk.shape.data(), &pr, &pc);
-            const int64_t bc = bc0 > 0 ? bc0 : pc;
+            const int64_t br = br0 > 0 ? br0 : pr, bc = bc0 > 0 ? bc0 : pc;
             const int64_t sc = (pc + bc - 1) / bc;
             for (int64_t r = std::max(r0, base); r < std::min(r0 + nr, base + pr); ++r)
                 for (int64_t c = 0; c < w.cols; ++c)
@@ -1639,11 +1734,10 @@ int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* ds
     const int64_t eb = rad_dtype_bits(dt) / 8;
     uint8_t* o = (uint8_t*)dst;
     if (w.paro && w.pieces[0]->pbits && k <= 2) {
-        /* PARO int5-bitplane, RE-LAID a row of the logical [N, K] matrix at a time. The checkpoint
-         * packs along N: qweight [K, N/8] holds eight low nibbles per word in AWQ order (word
-         * column c of a group of eight sits in nibble j, ORDER[j] == c), and qweight_hi [K, N/32]
-         * the fifth bit of 32 columns, bit n % 32. The zero points are the same two packings over
-         * [G, N]. */
+        /* Paro int5-bitplane, re-laid one row of the logical [N, K] matrix at a time. The
+         * checkpoint packs along N: qweight [K, N/8] holds eight low nibbles per word in AWQ order
+         * (column c of a group of eight is in nibble nib(c)), and qweight_hi [K, N/32] the fifth
+         * bit of 32 columns at bit n % 32. Zero points use the same two packings over [G, N]. */
         auto nib = [](int c) { return c % 2 == 0 ? c / 2 : 4 + c / 2; };      /* AWQ order */
         auto u32 = [](const SrcTensor& t, int64_t i) {
             uint32_t v;
@@ -1692,10 +1786,10 @@ int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* ds
         return RAD_OK;
     }
     if (w.paro && std::strncmp(w.enc.plane[k].role, "t.", 2) == 0) {
-        /* A ROTATION TABLE, built from the checkpoint's own tensors a row at a time: the pairs
-         * from group-local to whole-row columns, the angles widened, the channel scale inverted
-         * (the checkpoint multiplies the activation by it; the encoding's t.scale is the factor
-         * the stored row was MULTIPLIED by, so the activation is divided), the part ends. */
+        /* A rotation table, built a row at a time: pairs converted from group-local to whole-row
+         * columns, angles widened, the channel scale inverted (the checkpoint multiplies the
+         * activation by it; t.scale is the factor the stored row was multiplied by), and the part
+         * ends. */
         const RadEncPlane& pl = w.enc.plane[k];
         const int64_t P = (int64_t)w.pieces.size(), S = w.pq_pairs[0]->shape[0], K = w.cols;
         const std::string role = pl.role;
@@ -1726,7 +1820,7 @@ int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* ds
                 }
                 o += P * 4;
             } else if (role == "t.dense") {
-                /* row r is part r / (K/128), group r % (K/128): its stages, group-local, composed */
+                /* Row r is part r / (K/128), group r % (K/128): its group-local stages composed. */
                 const int64_t nkb = K / kParoGroup, H = kParoGroup / 2, q = r / nkb, g = r % nkb;
                 const int16_t* pv = (const int16_t*)w.pq_pairs[(size_t)q]->data;
                 const SrcTensor& th = *w.pq_theta[(size_t)q];
@@ -1747,20 +1841,20 @@ int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* ds
         }
         return RAD_OK;
     }
-    if (w.imported && !w.paro) {
-        /* GPTQ-PACKED, RE-LAID: a row of codes is a column of the qweight, its words' bytes in
-         * order -- two codes a byte for int4, low nibble first, as the encoding packs them -- each
-         * offset to signed by flipping the top bit of every field; a row of scales is a column of
-         * the scale tensor, one a 128 of K, rounded to bf16. */
+    if (w.imported && !w.paro && (w.pieces[0]->gptq_group || w.pieces[0]->ct_group)) {
+        /* GPTQ-packed, re-laid: a row of codes is a column of the qweight, its words' bytes in order
+         * (int4: two codes per byte, low nibble first), made signed by flipping each field's top
+         * bit; a row of scales is a column of the scale tensor, one per 128 of K, rounded to
+         * bf16. */
         int64_t base = 0;
         for (size_t p = 0; p < w.pieces.size(); ++p) {
             const SrcTensor& c = *w.pieces[p];
             const SrcTensor& s = *w.scales[p];
             const int64_t N = c.shape[0], K = c.shape[1];
             if (c.ct_group) {
-                /* CT-INT4, RE-LAID: a row of codes is a row of the packed words, already two codes
-                 * a byte low nibble first, each offset to signed by flipping its top bit; a row of
-                 * scales is a row of the scale tensor, as shipped. */
+                /* CT-INT4, re-laid: a row of codes is a row of the packed words (already two per
+                 * byte, low nibble first), made signed by flipping each top bit; a row of scales is
+                 * a row of the scale tensor, as shipped. */
                 for (int64_t r = std::max(r0, base); r < std::min(r0 + nr, base + N); ++r) {
                     const int64_t n = r - base;
                     if (k == 0) {
@@ -1799,8 +1893,8 @@ int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* ds
         return RAD_OK;
     }
     if (k == 0) {
-        /* the codes: the pieces joined, bytes as they are. A sub-byte code (MXFP4) joins along
-         * rows of even width, so every run starts and ends on a byte. */
+        /* Codes: the pieces joined, bytes as stored. Sub-byte codes (MXFP4) join along rows of even
+         * width, so every run is byte-aligned. */
         const int64_t bits = rad_dtype_bits(dt);
         Joined j;
         j.init(src, w.concat_dim);
@@ -1811,12 +1905,12 @@ int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* ds
             return (int)RAD_OK;
         });
     }
-    /* an FP8 scale plane: the pieces' scale rows one after another */
+    /* A scale plane: the pieces' scale rows in sequence. */
     int64_t base = 0;
     for (const SrcTensor* s : src) {
         int64_t sr = 0, scl = 0;
         rad_enc_view((uint32_t)s->shape.size(), s->shape.data(), &sr, &scl);
-        if (s->shape.size() == 1) { sr = s->shape[0]; scl = 1; }       /* one scale a row */
+        if (s->shape.size() == 1) { sr = s->shape[0]; scl = 1; }       /* one scale per row */
         const int64_t lo = std::max(r0, base), hi = std::min(r0 + nr, base + sr);
         if (hi > lo) {
             std::memcpy(o, (const uint8_t*)s->data + (lo - base) * scl * eb,
diff --git a/core/format/checkpoint.h b/core/format/checkpoint.h
index acbce471..029b52c5 100644
--- a/core/format/checkpoint.h
+++ b/core/format/checkpoint.h
@@ -1,25 +1,24 @@
 /* checkpoint.h -- a safetensors or GGUF checkpoint as a source of logical weights.
  *
- * A checkpoint is read twice in this engine: by rad-convert, which writes a container from it, and
- * by the loader, which serves a checkpoint whose encoding is trivial directly (spec §4.3). Both
- * need the same three things, and this is the one copy of each:
+ * Read by rad-convert (to write a container) and by the loader (to serve a checkpoint with
+ * trivial encodings directly, spec §4.3). Both need:
  *
- *   - the tensors, as one row-major namespace however many shards and drafters they came in;
- *   - the model's metadata, from config.json (and its siblings) or the GGUF header;
- *   - a LOGICAL WEIGHT for a declared name: the tensors the architecture plugin's name map
- *     resolves it to -- concatenations, alternatives and expert slices included -- with the
- *     encoding they already are when that encoding is trivial, and the rows of it on demand.
+ *   - the tensors, as one row-major namespace across shards and drafters;
+ *   - the metadata, from config.json and its siblings or the GGUF header;
+ *   - the logical weight for a declared name: the tensors the plugin's name map resolves it to
+ *     (concatenations, alternatives, expert slices), with their encoding when trivial, and its rows
+ *     on demand.
  *
- * Trivial is the set spec §4.3 names: plain f32, f16 and bf16 (GGUF's too), block-scaled FP8,
- * where `X.weight_scale_inv` is the scale plane of `X.weight`, and MXFP4 as AMD Quark ships it
- * (`X.weight` U8 codes, `X.weight_scale` U8 exponents), which is `fp4_e2m1*e8m0[1x32]` byte for
- * byte. Anything else is a weight whose served form needs quantisation work, which a recipe does
- * ahead of time -- or, for a published GPTQ-packed release (AutoRound, GPTQ), an IMPORT: the
- * shipped integer codes and group scales re-laid as an encoding the kernels read, at convert time.
+ * Trivial (spec §4.3): plain f32, f16 and bf16 (GGUF's too); FP8 with a block or per-row scale
+ * plane (`X.weight_scale_inv`, or `X.weight_scale`); and MXFP4 as AMD Quark ships it (`X.weight`
+ * U8 codes, `X.weight_scale` U8 exponents), byte for byte `fp4_e2m1*e8m0[1x32]`. Anything else
+ * needs a recipe ahead of time, or for a published release in a form listed under
+ * Checkpoint::Import an import: the shipped codes and scales re-laid, or decoded for a recipe, at
+ * convert time.
  *
- * AN IMPORTED QUANTISATION IS STATED WEIGHT BY WEIGHT. The checkpoint's quantisation descriptor
- * (`auto-round`, `gptq`, `quark`) names the tool that made it, not a served form, so no
- * architecture plugin claims it; the plugin is chosen as Checkpoint::imports() describes.
+ * An imported quantisation's descriptor (`auto-round`, `gptq`, `quark`, `compressed-tensors`,
+ * `paroquant`) names the tool, not a served form, so no plugin claims it; Checkpoint::imports()
+ * describes how the plugin is chosen.
  */
 #pragma once
 #include "../rad_internal.h"
@@ -39,9 +38,8 @@ namespace rad {
 class Program;
 
 /* ================================================================== tensors */
-/* One shape convention from here on: ROW-MAJOR, shape[0] slowest. GGUF stores ne[] fastest-first,
- * so it is reversed on the way in. Getting this backwards transposes every matrix in the model
- * and produces fluent wrong output, so it is done exactly once, in Checkpoint::open. */
+/* Shapes are row-major, shape[0] slowest. GGUF stores ne[] fastest-first, so Checkpoint::open
+ * reverses it, once; getting it wrong transposes every matrix. */
 struct SrcTensor {
     std::string          name;
     uint32_t             ggml = 0;
@@ -49,18 +47,18 @@ struct SrcTensor {
     std::vector shape;                        /* row-major */
     const void*          data = nullptr;
     int64_t              bytes = 0;
-    /* GPTQ-PACKED (auto_gptq's layout, which AutoRound's `auto_round:auto_gptq` export shares):
-     * `data` is the qweight's int32 words [K * bits / 32, N], each packing 32 / bits codes along
-     * K from the low bits up, stored unsigned with the zero point 2^(bits-1). The tensor this
-     * describes is the logical [N, K] code matrix, `rad_dtype` RAD_I4 or RAD_I8; `gptq_group` is
-     * the K columns one row of its scale tensor covers. 0 for any other tensor. */
+    /* GPTQ-packed (auto_gptq's layout, shared by AutoRound's `auto_round:auto_gptq` export):
+     * `data` is the qweight's int32 words [K * bits / 32, N], each packing 32 / bits codes along K
+     * from the low bits up, unsigned with zero point 2^(bits-1). The tensor described is the
+     * logical [N, K] code matrix, `rad_dtype` RAD_I4 or RAD_I8; `gptq_group` is the K columns one
+     * scale row covers. 0 for other tensors. */
     int32_t              gptq_bits = 0;
     int64_t              gptq_group = 0;
-    /* CT-INT4 (compressed-tensors' pack-quantized int4, symmetric): `data` is X.weight_packed's
-     * int32 words [N, K / 8], eight codes a word along K from the low bits up, stored unsigned with
-     * the zero point 8. The tensor this describes is the logical [N, K] code matrix, `rad_dtype`
-     * RAD_I4; `ct_group` is the K columns one scale of X.weight_scale [N, K / group] covers. 0 for
-     * any other tensor. */
+    /* CT-INT4 (compressed-tensors' symmetric pack-quantized int4): `data` is X.weight_packed's
+     * int32 words [N, K / 8], eight codes per word along K from the low bits up, unsigned with zero
+     * point 8. The tensor described is the logical [N, K] code matrix, `rad_dtype` RAD_I4;
+     * `ct_group` is the K columns one scale of X.weight_scale [N, K / group] covers. 0 for other
+     * tensors. */
     int64_t              ct_group = 0;
     /* ParoQuant's int5-bitplane (Import::ParoI5): `data` is the AWQ-packed low nibbles qweight
      * [K, N/8] and the tensor described is the logical [N, K] u5 code matrix; `aux` are the fifth-bit
@@ -85,13 +83,13 @@ struct MetaOwn {
     RadModelMeta m{};
 
     void kv(const std::string& k, const std::string& v) { keys.push_back(k); vals.push_back(v); }
-    /* A key given LAST that must also WIN: a lookup takes the first row with the key, so
-     * appending a key the checkpoint already set would write both and read the old one. */
+    /* Set a key that must win over an existing one: lookups take the first row with a key, so
+     * kv() would leave the old value in effect. */
     void set(const std::string& k, const std::string& v);
     bool has(const std::string& k) const;
     const char* get(const std::string& k) const;     /* null when absent */
-    /* Republish the pointers RadModelMeta carries. Every kv()/set() may move the strings, so this
-     * runs after the last of them and before `m` is read. */
+    /* Republish RadModelMeta's pointers. kv()/set() may move the strings, so call this after the
+     * last of them and before reading `m`. */
     void finish();
 };
 
@@ -110,13 +108,12 @@ public:
     Checkpoint(const Checkpoint&) = delete;
     Checkpoint& operator=(const Checkpoint&) = delete;
 
-    /* A .gguf, a .safetensors, a model.safetensors.index.json, or the directory holding one --
-     * and the metadata beside it. */
+    /* A .gguf, a .safetensors, a model.safetensors.index.json, or the directory holding one,
+     * plus the metadata beside it. */
     int open(const std::string& path);
-    /* A SECOND checkpoint, merged into this one's namespace and metadata under `prefix`: a
-     * drafter that ships as its own repository (DFlash2) borrows the target's embedding and head,
-     * so it belongs in the target's container, its tensors under `draft.` and its config.json
-     * under `draft.` keys. */
+    /* Merge a second checkpoint under `prefix`: a drafter shipped as its own repository (DFlash2)
+     * borrows the target's embedding and head, so it goes into the target's container with its
+     * tensors and config.json keys under `draft.`. */
     int add_draft(const std::string& dir, const std::string& prefix);
 
     const SrcTensor* find(const std::string& n) const;
@@ -131,37 +128,40 @@ public:
     MetaOwn&           meta() { return meta_; }
     const MetaOwn&     meta() const { return meta_; }
 
-    /* Sub-tensor `index` of a STACKED tensor -- dim 0 of a rank >= 2 tensor -- as a view, owned
-     * here so every pointer handed out stays valid for the checkpoint's life. Null, with the
-     * reason logged, when there is no such slice. */
+    /* Sub-tensor `index` along dim 0 of a stacked (rank >= 2) tensor, as a view owned here and
+     * valid for the checkpoint's life. Null, with the reason logged, if there is no such slice. */
     const SrcTensor* slice(const SrcTensor& st, int index, const char* declared);
 
     /* FP8's block, from quantization_config.weight_block_size; 128x128 when it says nothing. */
     int64_t fp8_block_rows() const { return fp8_br_; }
     int64_t fp8_block_cols() const { return fp8_bc_; }
 
-    /* THE CHECKPOINT'S QUANTISATION, IMPORTED WEIGHT BY WEIGHT, or None. Read from
-     * quantization_config at open: AutoRound's `auto_round:auto_gptq` export and GPTQ's own (v1,
-     * the zero point stored less one) are Gptq; Quark's MXFP4 (fp4 weights, per_group 32, e8m0
-     * scales, no per-layer overrides) is QuarkMx; ParoQuant's MXFP4 (`paroquant_mxfp4`: Quark's
-     * codes and exponents in a ROTATED basis, with the rotations beside them) is ParoMx. A quantisation of one of those tools in a form
-     * this does not read stays None, with the reason in import_refusal(). */
-    /* Its quantization_config keys are then renamed `imported_quantization_config.*`: they
-     * describe the tool, not a served format, and a plugin reads the latter there. */
-    enum class Import { None, Gptq, QuarkMx, CtInt4, ParoMx, ParoI5, ParoI4 };
+    /* The checkpoint's quantisation imported weight by weight, or None; read from
+     * quantization_config at open. Gptq: AutoRound's `auto_round:auto_gptq` export and GPTQ v1
+     * (zero point stored less one). QuarkMx: Quark's MXFP4 (fp4 weights, per_group 32, e8m0
+     * scales, no per-layer overrides). ParoMx: ParoQuant's `paroquant_mxfp4` (Quark's codes and
+     * exponents in a rotated basis, rotations beside them). CtInt4, Nvfp4, CtFp8:
+     * compressed-tensors' pack-quantized int4, a release with an nvfp4-pack-quantized group, and
+     * one whose groups are all float-quantized FP8 (detect_import). In an Nvfp4 or CtFp8 release
+     * every weight without the NVFP4 tensors reads stock, so FP8 and bf16 linears beside the
+     * NVFP4 ones read by their own form. An unreadable form of these stays None, with the reason
+     * in import_refusal(). The quantization_config keys are then renamed
+     * `imported_quantization_config.*`, since they describe the tool, not a served format. */
+    enum class Import { None, Gptq, QuarkMx, CtInt4, ParoMx, ParoI5, ParoI4, Nvfp4, CtFp8 };
     Import imports() const { return import_; }
     const std::string& import_refusal() const { return import_why_; }
 
-    /* The pieces an imported weight is read from, as views owned here: for `name` (a `.weight`)
-     * the GPTQ-packed codes and their scale tensor, or Quark's codes and exponents as their RAD
-     * dtypes. RAD_E_NOTFOUND when the checkpoint ships `name` as an ordinary tensor or not at
-     * all; another error, with `why`, when it ships an imported form this cannot read. */
+    /* The pieces an imported `name` (a `.weight`) is read from, as views owned here: GPTQ-packed
+     * codes and their scales, Quark's codes and exponents as RAD dtypes, or NVFP4's codes as fp4
+     * beside an f32 scale plane derived from the e4m3 scales and the global scale. RAD_E_NOTFOUND
+     * when `name` is an ordinary tensor or absent; another error, with `why`, for an unreadable
+     * imported form. */
     int import_piece(const std::string& name, const SrcTensor** codes, const SrcTensor** scale,
                      std::string* why);
 
 private:
-    /* `owner`, when the checkpoint has an index, is its weight_map: a tensor the index places in
-     * another shard is not read from this one. */
+    /* `owner` is the index's weight_map, if any: a tensor it places in another shard is skipped
+     * here. */
     int add_shard(const std::string& p, const std::string& prefix = "",
                   const std::unordered_map* owner = nullptr);
     int open_safetensors(const std::string& path);
@@ -178,11 +178,14 @@ private:
     std::unordered_map index_;
     std::unordered_map index_shard_;   /* name -> shards_ position */
     std::deque sliced_;            /* views; a deque never moves what it holds */
+    /* Bytes a view's data points at when they are derived, not mapped (NVFP4's f32 scale
+     * plane); they live as long as the views. */
+    std::vector> owned_;
     int64_t fp8_br_ = 128, fp8_bc_ = 128;
     Import      import_ = Import::None;
     std::string import_why_;
     int64_t     ct_group_ = 0;   /* CtInt4: the group every weight's config states */
-    /* import_piece's answers by name, so a weight resolved twice reads one pair of views. */
+    /* import_piece's answers by name, so a weight resolved twice reuses its views. */
     std::unordered_map> imported_;
 };
 
@@ -197,18 +200,20 @@ struct CkptWeight {
     uint32_t rank = 0;
     int64_t  shape[RAD_MAX_RANK] = {0};       /* the logical shape */
     int64_t  rows = 0, cols = 0;              /* its [rows, cols] view (rad_enc_view) */
-    /* The encoding the pieces ARE, when it is trivial; `why` says what is not when it is not. */
+    /* `enc` is the pieces' encoding when trivial; otherwise `why` says what is not. */
     bool        trivial = false;
-    /* GPTQ-PACKED PIECES, read into `enc` (`i4` or `i8` codes, bf16 scales a 128 of K) by
-     * ckpt_plane_rows: the codes transposed and offset to signed, the f16 scales rounded to bf16.
-     * Not trivial -- the rounding means the numbers are not served as shipped -- so the loader
-     * refuses one and rad-convert keeps it in `enc`, as it keeps a trivial weight. */
+    /* Imported pieces, read into `enc` by ckpt_plane_rows and ckpt_rows_f32. GPTQ-packed: `i4` or
+     * `i8` codes transposed and offset to signed, f16 scales rounded to bf16 per 128 of K.
+     * NVFP4: fp4 codes beside the f32 scale e4m3 / global per 16 of K. Not trivial (the scales
+     * are changed or derived), so the loader refuses it; rad-convert writes it as `enc` or
+     * quantises it by a recipe rule. A non-trivial FP8 weight may also state `enc` when it
+     * still reads piece by piece (a row join ending inside a scale block); one that cannot be
+     * read leaves `enc` unstated, and ckpt_rows_f32 refuses it with `why`. */
     bool        imported = false;
-    /* PAROQUANT MXFP4, IMPORTED (Import::ParoMx): `imported` too, so the loader refuses it and
-     * rad-convert writes it plane by plane through ckpt_plane_rows. Planes 0 and 1 are Quark's
-     * codes and exponents byte for byte; the rest are the "givens" transform's tables, built here
-     * from `pq_pairs`/`pq_theta`/`pq_scale`, one set per piece (a piece is a row PART: gate and up,
-     * or q, k and v, each rotated on its own). */
+    /* ParoQuant MXFP4 (Import::ParoMx), also `imported`: written plane by plane through
+     * ckpt_plane_rows. Planes 0 and 1 are Quark's codes and exponents byte for byte; the rest are
+     * the "givens" transform's tables, built from `pq_pairs`/`pq_theta`/`pq_scale`, one set per
+     * piece (a row part: gate and up, or q, k and v, each rotated separately). */
     bool        paro = false;
     std::vector pq_pairs, pq_theta, pq_scale;
     RadEncoding enc{};
@@ -230,17 +235,17 @@ std::string ckpt_tensor_of(const SrcTensor& t);
 bool ckpt_reads_any(const CkptWeight& w, const std::unordered_set& names,
                     std::unordered_set* hit = nullptr);
 
-/* One (part, group) of a ParoQuant rotation as its dense matrix: `S` stages of 64 pairs, the pair's two
- * group-local columns `ia`/`ib` and angle `th`, stage-major; out[j * 128 + i] (f16) is output j for the
- * unit vector e_i. It is the "givens" encoding's "t.dense" table, row for row. */
+/* One (part, group) of a ParoQuant rotation as a dense matrix: `S` stages of 64 pairs, each with
+ * group-local columns `ia`/`ib` and angle `th`, stage-major; out[j * 128 + i] (f16) is output j for
+ * unit vector e_i. This is the "givens" encoding's "t.dense" table. */
 void paro_compose_dense(int64_t S, const int32_t* ia, const int32_t* ib, const float* th, uint16_t* out);
 
 /* Logical rows [r0, r0 + nr) of `w` as f32 [nr, cols], whatever the pieces are stored as: a
  * plain float widened, FP8 times its block scale, a GGUF block type dequantised. */
 int ckpt_rows_f32(const CkptWeight& w, int64_t r0, int64_t nr, float* out, std::string* why);
 
-/* Rows [r0, r0 + nr) of plane `k` of a TRIVIAL or IMPORTED `w`, in the plane's own elements, dense
- * into `dst`: the bytes a container entry holds for it. */
+/* Rows [r0, r0 + nr) of plane `k` of a trivial or imported `w`, in the plane's own elements, dense
+ * into `dst`: the bytes a container entry holds. */
 int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* dst,
                     std::string* why);
 
diff --git a/core/format/encoding.cpp b/core/format/encoding.cpp
index 538d3726..d95ffe93 100644
--- a/core/format/encoding.cpp
+++ b/core/format/encoding.cpp
@@ -102,9 +102,8 @@ Rd plane(const EncodedView& v, int idx) {
     return r;
 }
 
-/* The tables of one row part of a "givens" weight, read once: the cosine and sine of every angle
- * and the pairs as indices, so undoing a row is arithmetic and not a table walk. A decode asks for
- * the part its row falls in, and rows of one part follow each other. */
+/* One row part's "givens" tables, read once (pairs as indices, cos and sin of every angle) and
+ * reused while consecutive rows stay in the same part. */
 struct GivensPart {
     int64_t              part = -1;
     int64_t              S = 0;
@@ -199,9 +198,8 @@ int enc_decode_rows(const EncodedView& v, int64_t row0, int64_t n, float* out, s
     const bool plain  = rad_enc_is(&e, "plain");
     const bool affine = rad_enc_is(&e, "affine");
     if (!plain && !affine) {
-        /* A QUANTISER'S OWN SCHEME, read by the quantiser that wrote it -- whichever loaded one
-         * answers for it (abi/rad_quant.h). The weight is described as far as the caller knows it:
-         * a [rows, cols] view and the planes from their starts. */
+        /* A quantiser's own scheme, decoded by whichever loaded quantiser accepts it
+         * (abi/rad_quant.h), given a [rows, cols] view and the plane starts. */
         std::vector fns;
         {
             std::lock_guard lk(g_dec_mu);
@@ -266,12 +264,9 @@ int enc_decode_rows(const EncodedView& v, int64_t row0, int64_t n, float* out, s
     }
     std::vector tmp(perm ? (size_t)v.cols : 0);
     GivensPart gv;
-    /* THE COMMON FORM, A ROW AT A TIME: codes with no codebook, sign, zero or minimum and at most
-     * one scale level -- int4 experts, fp8 rows, a fixed-scale table. The element walk below
-     * resolves every element's dtype and its scale's index through a switch and two divisions,
-     * and on a Flash-Next conversion that walk is a third of the convert; here the codes' dtype is
-     * resolved once a row and the scale read once a group. The same products, so the same
-     * floats. */
+    /* Fast path for the common form (no codebook, sign, zero or minimum; at most one scale level,
+     * e.g. int4 experts, fp8 rows): dtype resolved once per row and the scale read once per group,
+     * instead of per element (a third of a Flash-Next conversion). Same products, same floats. */
     const bool direct = V <= 1 && !table && !signs && !zero && mins.empty() && scales.size() <= 1;
 
     for (int64_t i = 0; i < n; ++i) {
@@ -368,10 +363,8 @@ int enc_selection_logical(const RadEncoding& e, const int* sel, int n_sel, const
                 rad_store_f32(out, dt, i * c + j, rad_load_f32(src + i * rb, p.dtype, j));
         return RAD_OK;
     }
-    /* CODES AND THE SCALAR CODEBOOK THEY INDEX, without the scale: each code as its table entry.
-     * It is what a kernel that folds the scale itself reads -- the codes view of a w4nla8h expert
-     * -- and the entries are the values the reference multiplies, where the raw indices would be
-     * other numbers. */
+    /* Codes with the scalar codebook they index, without the scale: each code as its table entry,
+     * as read by a kernel that applies the scale itself (a w4nla8h expert's codes view). */
     if (n_sel == 2 && !std::strcmp(e.plane[sel[0]].role, "codes") &&
         !std::strcmp(e.plane[sel[1]].role, "table") && e.plane[sel[0]].kind == RAD_PLANE_TILED &&
         e.plane[sel[0]].block[0] == 1 && e.plane[sel[0]].block[1] == 1 &&
@@ -394,14 +387,11 @@ int enc_selection_logical(const RadEncoding& e, const int* sel, int n_sel, const
             }
         return RAD_OK;
     }
-    /* A SCALE AND THE LEVELS ABOVE IT, without the codes: each first-level scale times every level
-     * that covers it. It is what a kernel that takes its scales as an operand of their own reads
-     * where the encoding states them in two levels -- the scale view of a w4nl64a8h expert, an
-     * E4M3 scale a (row, 64 of K) under one fixed f32 -- and the product is the scale the
-     * reference multiplies, where the first level on its own is that scale off by the second. One
-     * element a first-level scale, in that plane's extents. A level has to cover whole
-     * first-level blocks -- the whole weight, or a block a multiple of the first's -- or a scale
-     * would straddle two of its elements and have no one product. */
+    /* A scale with the levels above it, without codes: each first-level scale times every level
+     * covering it, one element per first-level scale. Read by a kernel taking scales as their own
+     * operand when the encoding has two levels (a w4nl64a8h expert: an E4M3 scale per (row, 64 of
+     * K) under one f32). Each level must cover whole first-level blocks, or a product would be
+     * ambiguous. */
     if (n_sel >= 2 && !std::strcmp(e.plane[sel[0]].role, "scale")) {
         bool chain = true;
         for (int k = 0; k < n_sel && chain; ++k) {
@@ -447,8 +437,8 @@ int enc_selection_logical(const RadEncoding& e, const int* sel, int n_sel, const
     if (n_sel != e.n_planes)
         return refuse("it takes " + std::to_string(n_sel) + " of its encoding's " +
                       std::to_string(e.n_planes) + " planes, which decode to nothing on their own");
-    /* The logical rows from the first selected plane and its block height; the columns are what
-     * is left of `n`, since a codes plane of vector codes does not carry them. */
+    /* Logical rows from the first plane and its block height; columns are what remains of `n`,
+     * since a vector-code plane does not carry them. */
     const RadEncPlane& p0 = e.plane[sel[0]];
     const int64_t r = rows[0] * (p0.kind == RAD_PLANE_TILED && p0.block[0] > 0 ? p0.block[0] : 1);
     if (r <= 0 || n % r)
@@ -481,7 +471,7 @@ int enc_plane_rect(const RadEncPlane& p, int64_t rows, int64_t cols, int64_t r0,
                                                     lo, hi, extent);
             return false;
         }
-        if (b <= 0) {                 /* one element covers the whole extent: every slice has it */
+        if (b <= 0) {                 /* one element covers the whole extent; every slice has it */
             *e0 = 0;
             *en = pext;
             return true;
@@ -498,7 +488,7 @@ int enc_plane_rect(const RadEncPlane& p, int64_t rows, int64_t cols, int64_t r0,
     PlaneRect r;
     if (!cut(r0, r1, rows, p.block[0], pr, &r.row0, &r.rows, "rows")) return RAD_E_SHAPE;
     if (!cut(c0, c1, cols, p.block[1], pc, &r.col0, &r.cols, "columns")) return RAD_E_SHAPE;
-    /* A slice is copied as bytes, so a packed plane's cut has to land on a byte. */
+    /* Slices are copied as bytes, so a packed plane's cut must fall on a byte. */
     const int bits = rad_dtype_bits(p.dtype);
     if (bits > 0 && (r.col0 * bits) % 8 != 0) {
         if (why) *why = fmt("column %lld of the ", r.col0) + rad_dtype_name(p.dtype) + " '" +
diff --git a/core/format/encoding.h b/core/format/encoding.h
index 31c68569..0218f649 100644
--- a/core/format/encoding.h
+++ b/core/format/encoding.h
@@ -1,11 +1,9 @@
-/* encoding.h -- the core's half of a weight encoding: decoding one to f32, and cutting a plane for
+/* encoding.h -- the core's half of a weight encoding: decoding to f32, and cutting a plane for
  * tensor parallelism. The encoding itself is abi/rad_encoding.h; spec.md §4.1.
  *
- * The core decodes the two schemes it defines, "plain" and "affine", under every transform the
- * ABI names, and nothing else: a quantiser that invents a scheme decodes it (abi/rad_quant.h). The
- * decoder is what the oracle checks a kernel through, what rad-convert measures a quantiser's
- * error with, and what a weight is read back through to be quantised again -- three consumers
- * that must agree on what a stored weight means, which is why there is one of it.
+ * The core decodes its two schemes, "plain" and "affine", under every ABI transform; a quantiser
+ * that defines another scheme supplies its decoder (abi/rad_quant.h). The oracle, rad-convert's
+ * error measurement and re-quantisation all decode through this one implementation.
  */
 #pragma once
 #include "../rad_internal.h"
@@ -34,23 +32,22 @@ struct EncodedView {
 void enc_view(const RadEncoding& e, int64_t rows, int64_t cols, const void* const* data,
               EncodedView* v);
 
-/* Decode logical rows [row0, row0 + n) into `out`, f32 [n, cols]. Returns RAD_OK, or
- * RAD_E_UNSUPPORTED for a scheme the core does not decode (with `why` saying which), RAD_E_SHAPE
- * when a transform does not fit the row, or RAD_E_FORMAT for a malformed encoding or a code its
- * codebook has no entry for -- a corrupt file, said so, rather than a read past a table. */
+/* Decode logical rows [row0, row0 + n) into `out`, f32 [n, cols]. RAD_OK; RAD_E_UNSUPPORTED for
+ * a scheme nobody decodes (`why` names it); RAD_E_SHAPE when a transform does not fit the row;
+ * RAD_E_FORMAT for a malformed encoding or a code outside its codebook (rather than a read past
+ * the table). */
 int enc_decode_rows(const EncodedView& v, int64_t row0, int64_t n, float* out,
                     std::string* why = nullptr);
 
-/* THE DECODERS FOR SCHEMES THE CORE DOES NOT DEFINE: quantisers' own (RadQuantDecodeFn). The
- * plugin loader adds each loaded quantiser's and removes them when it unloads; enc_decode_rows
- * asks them in that order for any scheme but plain and affine. */
+/* Decoders for schemes the core does not define (RadQuantDecodeFn), registered by the plugin
+ * loader per quantiser; enc_decode_rows asks them in order for any scheme but plain and affine. */
 void enc_add_decoder(RadQuantDecodeFn fn);
 void enc_remove_decoder(RadQuantDecodeFn fn);
 
-/* The unnormalised Sylvester Walsh-Hadamard transform of `n` values in place, `n` a power of two.
- * The butterfly keeps (a + b) in the lower index and (a - b) in the upper, which is H_n in
- * natural (Sylvester) order -- the transform libr4d's r4d_fwht_wave computes in registers, and the
- * one an "fwhtN" encoding names. H_n is symmetric and H_n H_n = n I. */
+/* Unnormalised Walsh-Hadamard transform of `n` values in place, `n` a power of two. The butterfly
+ * keeps (a + b) in the lower index and (a - b) in the upper: H_n in natural (Sylvester) order, as
+ * libr4d's r4d_fwht_wave computes and an "fwhtN" encoding names. H_n is symmetric and
+ * H_n H_n = n I. */
 void fwht_inplace(float* v, int64_t n);
 
 /* The canonical spelling of an encoding (rad_enc_format), as a string. */
@@ -58,15 +55,13 @@ std::string enc_name(const RadEncoding& e);
 
 /* ================================================================== a selection, as a reader reads it
  *
- * The `n_sel` planes of `e` a declaration selects (RadWeightDecl::planes) -- plane `sel[k]` at
- * `data[k]`, dense [rows[k], cols[k]] in its own elements -- as `n` elements of dtype `dt` at
- * `out`: the tensor a reference implementation reads where a kernel reads the stored form. One
- * plane is converted element by element (a bf16 scale plane into an f32 reference, codes as their
- * values); codes with the scalar codebook they index, each code as its table entry; a scale with
- * the levels of its chain above it, each scale as their product; the whole encoding is decoded.
- * RAD_OK, or RAD_E_SHAPE with `why` when the planes do not make that tensor -- part of an
- * encoding, which decodes to nothing on its own, or extents that disagree with `n`; or the
- * decoder's own refusal. */
+ * The `n_sel` planes of `e` a declaration selects (RadWeightDecl::planes; plane `sel[k]` at
+ * `data[k]`, dense [rows[k], cols[k]] in its own elements) as `n` elements of dtype `dt` at `out`:
+ * the tensor a reference implementation reads in place of the stored form. A single plane converts
+ * element by element; codes with their scalar codebook become table entries; a scale with its
+ * chain's higher levels becomes their product; the whole encoding is decoded. RAD_OK, or
+ * RAD_E_SHAPE with `why` when the planes do not form that tensor (an incomplete encoding, or
+ * extents disagreeing with `n`), or the decoder's refusal. */
 int enc_selection_logical(const RadEncoding& e, const int* sel, int n_sel, const int64_t* rows,
                           const int64_t* cols, const void* const* data, uint32_t dt, int64_t n,
                           void* out, std::string* why);
@@ -78,11 +73,10 @@ struct PlaneRect {
     int64_t col0 = 0, cols = 0;
 };
 
-/* The part of plane `p` that covers logical rows [r0, r1) and columns [c0, c1) of a [rows, cols]
- * weight. Refused, with `why`, when a bound would split one of the plane's blocks -- a scale that
- * covers rows two ranks own between them belongs to neither, and taking it twice gives each a
- * plane that decodes to the right numbers for the wrong rows. The weight's own end is never a
- * split: a last block may be short. */
+/* The part of plane `p` covering logical rows [r0, r1) and columns [c0, c1) of a [rows, cols]
+ * weight. Refused, with `why`, when a bound would split one of the plane's blocks (a scale shared
+ * by two ranks' rows belongs to neither). The weight's end never splits: a last block may be
+ * short. */
 int enc_plane_rect(const RadEncPlane& p, int64_t rows, int64_t cols, int64_t r0, int64_t r1,
                    int64_t c0, int64_t c1, PlaneRect* out, std::string* why);
 
diff --git a/core/format/imatrix.cpp b/core/format/imatrix.cpp
index e5754e75..a4805dd5 100644
--- a/core/format/imatrix.cpp
+++ b/core/format/imatrix.cpp
@@ -1,8 +1,5 @@
 /* imatrix.cpp -- the two llama.cpp imatrix formats and the small GGUF walker the newer one needs.
- *
- * Little-endian only, like everything else here. Every read is bounds-checked against the mapping
- * before it happens: an imatrix is a file a user was handed by somebody else, and the quantiser
- * that consumes it runs unattended for an hour.
+ * Little-endian only. Every read is bounds-checked against the mapping: the file is untrusted.
  */
 #include "imatrix.h"
 
@@ -16,7 +13,7 @@
 namespace rad {
 namespace {
 
-/* GGUF's value type tags. Only what a walker needs to know how far to step. */
+/* GGUF's value type tags, enough to know how far to step. */
 enum : uint32_t {
     GT_U8 = 0, GT_I8 = 1, GT_U16 = 2, GT_I16 = 3, GT_U32 = 4, GT_I32 = 5, GT_F32 = 6,
     GT_BOOL = 7, GT_STR = 8, GT_ARR = 9, GT_U64 = 10, GT_I64 = 11, GT_F64 = 12
@@ -48,8 +45,7 @@ struct Cursor {
         if (out) out->assign((const char*)q, (size_t)n);
         return true;
     }
-    /* Step over a value of any type without interpreting it. Arrays recurse, which is how
-     * imatrix.datasets (an array of strings) is skipped when we do not want it. */
+    /* Step over a value of any type without interpreting it; arrays recurse. */
     bool skip_value(uint32_t type) {
         switch (type) {
             case GT_U8: case GT_I8: case GT_BOOL:            return take(1);
@@ -154,8 +150,7 @@ int ImatrixFile::read_legacy(const uint8_t* p, uint64_t n) {
             return RAD_E_FORMAT;
         }
 
-        /* Copied, not pointed at: the legacy layout puts floats at an offset that depends on the
-         * name length, so nothing in the file is guaranteed 4-byte aligned. */
+        /* Copied: legacy float offsets depend on the name length, so they may be unaligned. */
         owned_.emplace_back((size_t)nval);
         std::memcpy(owned_.back().data(), vp, (size_t)nval * sizeof(float));
 
@@ -173,9 +168,8 @@ int ImatrixFile::read_legacy(const uint8_t* p, uint64_t n) {
         RAD_ERR("%s: truncated before the first entry", path_.c_str());
         return RAD_E_FORMAT;
     }
-    /* The legacy format cannot express per-expert data at all, and a MoE quantised against it
-     * weights every expert by the layer's aggregate. Say so once rather than let the quality
-     * difference show up as an unexplained regression. */
+    /* The legacy format has no per-expert data, so a MoE quantised with it weights every expert by
+     * the layer's aggregate; warn once. */
     RAD_WARN("%s is the legacy imatrix format: it has no per-expert dimension, so every expert in "
              "a layer will be weighted by the layer's aggregate activations. Re-collect with a "
              "current llama.cpp for per-expert importance.", path_.c_str());
@@ -234,10 +228,8 @@ int ImatrixFile::read_gguf(const uint8_t* p, uint64_t n) {
     }
     if (!c.ok) { RAD_ERR("%s: truncated in the KV block", path_.c_str()); return RAD_E_FORMAT; }
 
-    /* THE TENSOR COUNT IS A NUMBER FROM THE FILE, and it sizes an allocation. Every tensor info
-     * is at least a name length, a dimension count, a type and an offset -- 24 bytes -- so a count
-     * the rest of the file cannot hold is refused here rather than handed to reserve(), where it
-     * is a multi-exabyte request that ends the process. */
+    /* The tensor count comes from the file and sizes an allocation. Each tensor info is at least
+     * 24 bytes, so refuse a count the file cannot hold before reserve(). */
     constexpr uint64_t kMinInfoBytes = 8 + 4 + 4 + 8;
     if (n_tensors > (uint64_t)(c.end - c.p) / kMinInfoBytes) {
         RAD_ERR("%s: the header declares %llu tensors, and the %llu bytes after the KV block "
@@ -274,9 +266,8 @@ int ImatrixFile::read_gguf(const uint8_t* p, uint64_t n) {
         return RAD_E_FORMAT;
     }
 
-    /* Join `.in_sum2` with `.counts`. Insertion order defines entries() order, so a
-     * report over the file reads in the order the collector wrote it. `held` is how many floats
-     * each half actually spans in the file, parallel to entries_, for the extent checks below. */
+    /* Join `.in_sum2` with `.counts`, in file order. `held` (parallel to entries_) is
+     * how many floats each half spans in the file, for the extent checks below. */
     std::unordered_map by_base;
     struct Held { uint64_t sum2 = 0, counts = 0; };
     std::vector held;
@@ -292,9 +283,8 @@ int ImatrixFile::read_gguf(const uint8_t* p, uint64_t n) {
             continue;
         }
 
-        /* The element count is a product of four numbers from the file, so it is bounded by the
-         * data section BEFORE each multiply: a product that wraps can come out small, pass the
-         * bounds test below and be read at its declared extent. */
+        /* The element count is a product of four file values; bound it by the data section before
+         * each multiply so it cannot wrap. */
         uint64_t numel = 1;
         bool     fits  = true;
         for (uint64_t d : t.dims) if (d == 0) numel = 0;
@@ -332,16 +322,14 @@ int ImatrixFile::read_gguf(const uint8_t* p, uint64_t n) {
         }
     }
 
-    /* THE QUERIES INDEX BY WHAT THE ENTRY CLAIMS, so the claim has to fit what the file holds.
-     * `importance` reads cols floats at expert * cols and `count` reads counts[expert] for every
-     * expert below n_expert -- both taken from the .in_sum2 dims -- so a .counts shorter than the
-     * expert count, or an .in_sum2 whose trailing dims multiply to less than cols x n_expert,
-     * would be read past its own extent. */
+    /* The queries index by the entry's claimed dims (from .in_sum2): `importance` reads cols floats
+     * at expert * cols and `count` reads counts[expert]. Check both halves actually hold that
+     * much. */
     std::vector kept;
     kept.reserve(entries_.size());
     for (size_t k = 0; k < entries_.size(); ++k) {
         ImatrixEntry& e = entries_[k];
-        /* An entry with counts and no values is a collector bug, not something to weight by. */
+        /* Counts without values is a collector bug. */
         if (!e.sum2 || e.cols <= 0) {
             RAD_WARN("%s: '%s' has counts but no .in_sum2 -- dropped", path_.c_str(),
                      e.name.c_str());
@@ -379,21 +367,9 @@ bool ImatrixFile::importance(const std::string& name, int64_t expert,
 
     const float* src = e->sum2 + expert * e->cols;
 
-    /* NORMALISED TO MEAN 1, and that is the whole of it.
-     *
-     * The row is NOT divided by the expert's activation count first, although that looks like a way
-     * to say "an expert that saw ten times the tokens is not ten times as important". The division
-     * cannot do that: the result is a single expert's row scaled to mean 1, and a uniform divisor
-     * applied to every column of that row is removed exactly by the scaling that follows it. What
-     * it can do is flush small columns to zero against a large count, and an all-zero row then
-     * takes the degenerate branch below -- so its only effect would be to lose weights.
-     *
-     * Popularity ACROSS experts is a different question and has its own query, `count`, which
-     * reports the raw number for exactly this reason.
-     *
-     * Mean 1 is what makes a weighted error comparable with an unweighted one, and therefore what
-     * makes the quantiser's error report mean the same thing with and without an imatrix. A
-     * degenerate (all-zero) row falls back to uniform weights rather than to NaN. */
+    /* Normalise to mean 1 only. Dividing by the expert's count first would be undone by the
+     * normalisation and could only flush small columns to zero. Popularity across experts is
+     * `count`'s job. An all-zero row falls back to uniform weights rather than NaN. */
     out->resize((size_t)e->cols);
     std::memcpy(out->data(), src, (size_t)e->cols * sizeof(float));
     double sum = 0.0;
@@ -406,6 +382,27 @@ bool ImatrixFile::importance(const std::string& name, int64_t expert,
     return true;
 }
 
+bool ImatrixFile::importance_for(const std::string& weight, int64_t cols,
+                                 std::vector* out) const {
+    std::string base = weight;
+    if (base.size() > 7 && base.compare(base.size() - 7, 7, ".weight") == 0)
+        base.resize(base.size() - 7);
+    int64_t expert = 0;
+    if (!find(base)) {
+        /* `.`: the last component must be a plain decimal index. */
+        const size_t dot = base.find_last_of('.');
+        if (dot == std::string::npos || dot + 1 == base.size()) return false;
+        for (size_t i = dot + 1; i < base.size(); ++i) {
+            if (base[i] < '0' || base[i] > '9' || expert > ((int64_t)1 << 40)) return false;
+            expert = expert * 10 + (base[i] - '0');
+        }
+        base.resize(dot);
+    }
+    const ImatrixEntry* e = find(base);
+    if (!e || e->cols != cols) return false;
+    return importance(base, expert, out);
+}
+
 double ImatrixFile::count(const std::string& name, int64_t expert) const {
     const ImatrixEntry* e = find(name);
     if (!e || !e->counts || expert < 0 || expert >= e->n_expert) return 0.0;
diff --git a/core/format/imatrix.h b/core/format/imatrix.h
index 490d5d4b..cd7806a5 100644
--- a/core/format/imatrix.h
+++ b/core/format/imatrix.h
@@ -1,30 +1,24 @@
-/* imatrix.h -- llama.cpp's importance matrix, both of the formats it has written.
+/* imatrix.h -- llama.cpp's importance matrix, in both formats it has written.
  *
- * An imatrix is a per-column activation second moment, collected over a calibration set. It does
- * two jobs here and they are unrelated:
+ * An imatrix is a per-column activation second moment over a calibration set. Two unrelated uses:
  *
- *   - the QUANTISER weights its per-block error by it, so bits go where the activations are
- *     (spec §4.3);
- *   - the CONVERTER derives the expert-popularity profile from its activation counts, which is
- *     what the placement planner warm-starts from (spec §5.3). That is a warm start and not a
- *     policy: imatrix popularity is not decode popularity, and the heat engine re-ranks from real
- *     routing within a few dispatches regardless.
+ *   - the quantiser weights its per-block error by it, so bits go where activations are
+ *     (spec §4.5);
+ *   - the converter derives the expert-popularity profile from its counts, the planner's warm
+ *     start (spec §5.3). Only a warm start: the heat engine re-ranks from real routing within a
+ *     few dispatches.
  *
- * Two formats, because llama.cpp has written two and both are in the wild:
+ * Formats:
  *
- *   LEGACY  a flat little-endian binary: int32 n_entries, then per entry
- *           int32 name_len, char[name_len], int32 ncall, int32 nval, float[nval].
- *           The values are SUMS OF SQUARES ALREADY DIVIDED BY ncall by the writer in some
- *           versions and not in others, which is exactly why the newer format exists.
- *   GGUF    a GGUF v3 container whose tensors are `.in_sum2` (f32 [cols] or [cols,n_expert])
- *           and `.counts` (f32 [1] or [1,n_expert]), plus `imatrix.chunk_count`,
- *           `imatrix.chunk_size` and `imatrix.datasets` in the KV block. Per-expert data is a
- *           second dimension, which the legacy format could not express at all.
+ *   legacy  flat little-endian binary: int32 n_entries, then per entry int32 name_len,
+ *           char[name_len], int32 ncall, int32 nval, float[nval]. Whether values are already
+ *           divided by ncall varies by writer version.
+ *   GGUF    a GGUF v3 container with tensors `.in_sum2` (f32 [cols] or [cols,n_expert]) and
+ *           `.counts` (f32 [1] or [1,n_expert]), plus `imatrix.chunk_count`,
+ *           `imatrix.chunk_size` and `imatrix.datasets`. Only this format has per-expert data.
  *
- * The GGUF walker below is local rather than core/text's. That is deliberate: the imatrix is a
- * file format and core/format owns file formats, the walker is a hundred lines, and coupling the
- * quantiser's input to the tokeniser component's reader would join two things with no other
- * relationship. It also has to sit beside the legacy reader, which is not GGUF at all.
+ * The GGUF walker is local rather than core/text's: it is small, and keeps the quantiser's input
+ * independent of the tokeniser's reader.
  */
 #pragma once
 #include "../rad_internal.h"
@@ -35,9 +29,8 @@
 
 namespace rad {
 
-/* `sum2` and `counts` point into the mapped file for a GGUF imatrix, at whatever offset its
- * general.alignment put them -- which may be 1 -- so they are read with memcpy, never in place.
- * importance() and count() do that. */
+/* For a GGUF imatrix, `sum2` and `counts` point into the mapping at general.alignment (possibly 1),
+ * so importance() and count() read them with memcpy, never in place. */
 struct ImatrixEntry {
     std::string  name;              /* the checkpoint tensor name, suffix stripped */
     const float* sum2   = nullptr;  /* [n_expert][cols], expert-major and contiguous */
@@ -67,13 +60,17 @@ public:
     bool               is_gguf()     const { return gguf_; }
     const std::string& path()        const { return path_; }
 
-    /* Column importance for one expert, NORMALISED TO MEAN 1. The normalisation is what makes a
-     * weighted error comparable with an unweighted one, and therefore what makes a quantiser's
-     * error report mean the same thing with and without an imatrix. Returns false if the tensor
-     * is absent, the expert is out of range, or the entry carries no values. */
+    /* Column importance for one expert, normalised to mean 1 so weighted and unweighted errors are
+     * comparable. False if the tensor is absent, the expert out of range, or no values. */
     bool importance(const std::string& name, int64_t expert, std::vector* out) const;
 
-    /* Raw activation count for one expert -- the popularity signal, unnormalised. 0 if absent. */
+    /* importance() for a weight as the converter names it. The imatrix uses GGUF names without the
+     * `.weight` suffix and keeps a MoE layer's experts as one entry, so `blk.5.ffn_down.weight` is
+     * entry `blk.5.ffn_down` (expert 0) and an expert slice `blk.5.ffn_down_exps.9.weight` is
+     * expert 9 of `blk.5.ffn_down_exps`. False when no entry matches or its width is not `cols`. */
+    bool importance_for(const std::string& weight, int64_t cols, std::vector* out) const;
+
+    /* Raw activation count for one expert (the popularity signal). 0 if absent. */
     double count(const std::string& name, int64_t expert) const;
 
 private:
@@ -87,8 +84,8 @@ private:
     std::string path_, dataset_;
     int64_t     chunk_count_ = 0, chunk_size_ = 0;
 
-    /* The legacy format's floats are not aligned in the file and are followed by no counts, so
-     * they are copied out rather than pointed at. GGUF payloads are pointed at. */
+    /* Legacy floats are unaligned in the file, so they are copied out; GGUF payloads are pointed
+     * at. */
     std::vector>         owned_;
     std::vector               entries_;
     std::unordered_map index_;
diff --git a/core/format/machine_key.cpp b/core/format/machine_key.cpp
index b0de43fa..4731c48b 100644
--- a/core/format/machine_key.cpp
+++ b/core/format/machine_key.cpp
@@ -1,10 +1,6 @@
-/* machine_key.cpp -- the machine half of the tuning cache key.
- *
- * Separate from tunecache.cpp on purpose: the cache is pure file I/O and must stay linkable and
- * testable without a device layer, while this needs one. It is also the only part of the key that
- * can be wrong in a way that is invisible -- a cache measured on another card is not a slower
- * answer, it is a wrong one -- so it names everything that changes the answer and nothing that
- * does not.
+/* machine_key.cpp -- the machine half of the tuning cache key. Separate from tunecache.cpp, which
+ * is pure file I/O and must link without a device layer. A cache from another machine gives wrong
+ * answers, so the key names everything that changes the answer and nothing else.
  */
 #include "tunecache.h"
 
@@ -15,10 +11,12 @@ namespace rad {
 std::string rad_machine_key() {
     RadDeviceProps p{};
     const int n = rad_dev_count();
+    return rad_machine_key_of(n, n > 0 && rad_dev_props(0, &p) >= 0 ? &p : nullptr);
+}
 
-    /* The host backend is a supported configuration and not a degraded one, so it gets a real key
-     * rather than a placeholder: host kernels tune too, and their answer depends on the CPU. */
-    if (n <= 0 || rad_dev_props(0, &p) < 0) {
+std::string rad_machine_key_of(int n, const RadDeviceProps* dev) {
+    /* No device to name at all. */
+    if (n <= 0 || !dev) {
 #if defined(__x86_64__)
         return "host-x86_64";
 #elif defined(__aarch64__)
@@ -28,10 +26,12 @@ std::string rad_machine_key() {
 #endif
     }
 
-    /* Device count matters because a collective's variant depends on how many peers there are,
-     * and those rows share this file. Card name is included, arch is not enough: two boards of the
-     * same architecture can differ in clocks and memory width. */
-    std::string name = p.is_host_backend ? "host" : p.name;
+    /* Device count, because a collective's variant depends on the peer count; card name, because
+     * boards of one arch differ in clocks and memory width. The host backend's device name is the
+     * CPU model, which host kernels' tuning depends on (an AVX2 part's answer is not an AVX-512
+     * part's), so its key is `host-x-`. */
+    const RadDeviceProps& p = *dev;
+    std::string name = p.name;
     for (char& c : name)
         if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')))
             c = '_';
diff --git a/core/format/quantise.cpp b/core/format/quantise.cpp
new file mode 100644
index 00000000..0f6327c5
--- /dev/null
+++ b/core/format/quantise.cpp
@@ -0,0 +1,88 @@
+/* quantise.cpp -- see quantise.h. */
+#include "quantise.h"
+
+#include 
+#include 
+
+namespace rad {
+
+int quantise_weight(const RadQuantizerInfo& q, const RadParam* params, int n_params,
+                    const RadQuantWeight& qw, const RadEncoding& enc, int64_t band_bytes,
+                    const QuantIo& io, std::string* why) {
+    auto refuse = [&](int rc, std::string m) {
+        if (why) *why = std::move(m);
+        return rc;
+    };
+    /* The movement group and the importance are known now; the encoding chosen without them must
+     * not change. */
+    {
+        RadEncoding again{};
+        if (q.encoding(params, n_params, &qw, &again) != RAD_OK || !rad_enc_equal(&again, &enc))
+            return refuse(RAD_E_STATE,
+                          std::string(q.name) + " answers with another encoding once it is told "
+                          "the weight's movement group, and declare could not tell it that. An "
+                          "encoding may depend on the weight's name and shape, not on where it is "
+                          "placed.");
+    }
+    const int64_t R = qw.rows, C = qw.cols;
+    int64_t rb = q.row_block ? q.row_block(params, n_params, &qw) : 0;
+    if (rb <= 0 || rb > R) rb = R;
+    int64_t blk = rb;
+    if (rb < R) {
+        const int64_t want = std::max(1, band_bytes / std::max(C * 4, 1));
+        blk = std::max(rb, want - want % rb);
+        if (blk > R) blk = R;
+    }
+    const int np = enc.n_planes;
+    std::vector prow_bytes((size_t)np), pband((size_t)np);
+    std::vector> whole((size_t)np), band((size_t)np);
+    bool misaligned = false;
+    for (int k = 0; k < np; ++k) {
+        const RadEncPlane& p = enc.plane[k];
+        int64_t pr = 0, pc = 0;
+        rad_enc_plane_dims(&p, R, C, &pr, &pc);
+        prow_bytes[(size_t)k] = rad_enc_row_bytes(p.dtype, pc);
+        const bool banded = p.kind == RAD_PLANE_TILED && p.block[0] > 0;
+        pband[(size_t)k] = banded ? p.block[0] : 0;
+        if (banded && blk < R && blk % p.block[0]) misaligned = true;
+        if (!banded) whole[(size_t)k].assign((size_t)(pr * prow_bytes[(size_t)k]), 0);
+    }
+    if (misaligned)
+        return refuse(RAD_E_SHAPE, fmt("%s takes %lld rows a call, which splits a block of its "
+                                       "own encoding's scales", q.name, (long long)rb));
+
+    std::vector f, ref;
+    for (int64_t r0 = 0; r0 < R; r0 += blk) {
+        const int64_t n = std::min(blk, R - r0);
+        f.resize((size_t)(n * C));
+        std::string w1;
+        if (io.read(r0, n, f.data(), &w1) != RAD_OK) return refuse(RAD_E_FORMAT, w1);
+        if (io.band) ref = f;                      /* a quantiser may rotate its input in place */
+        std::vector ptr((size_t)np);
+        for (int k = 0; k < np; ++k) {
+            if (!pband[(size_t)k]) { ptr[(size_t)k] = whole[(size_t)k].data(); continue; }
+            const int64_t rows_k = (n + pband[(size_t)k] - 1) / pband[(size_t)k];
+            band[(size_t)k].assign((size_t)(rows_k * prow_bytes[(size_t)k]), 0);
+            ptr[(size_t)k] = band[(size_t)k].data();
+        }
+        const int st = q.quantize(params, n_params, &qw, f.data(), r0, n, ptr.data());
+        if (st != RAD_OK)
+            return refuse(st, fmt("%s could not quantise rows [%lld, %lld): %s", q.name,
+                                  (long long)r0, (long long)(r0 + n), rad_strerror(st)));
+        for (int k = 0; k < np; ++k) {
+            if (!pband[(size_t)k]) continue;
+            if (io.write(k, (r0 / pband[(size_t)k]) * prow_bytes[(size_t)k],
+                         band[(size_t)k].data(), (int64_t)band[(size_t)k].size()) != RAD_OK)
+                return refuse(RAD_E_IO, fmt("writing plane %d of rows [%lld, %lld) failed", k,
+                                            (long long)r0, (long long)(r0 + n)));
+        }
+        if (io.band) io.band(r0, n, ref.data(), (const void* const*)ptr.data());
+    }
+    for (int k = 0; k < np; ++k)
+        if (!pband[(size_t)k] &&
+            io.write(k, 0, whole[(size_t)k].data(), (int64_t)whole[(size_t)k].size()) != RAD_OK)
+            return refuse(RAD_E_IO, fmt("writing plane %d failed", k));
+    return RAD_OK;
+}
+
+}  /* namespace rad */
diff --git a/core/format/quantise.h b/core/format/quantise.h
new file mode 100644
index 00000000..92d20f22
--- /dev/null
+++ b/core/format/quantise.h
@@ -0,0 +1,46 @@
+/* quantise.h -- one weight through a quantiser plugin, as rad-convert writes it.
+ *
+ * The loop asks the quantiser for its rows per call, hands it bands of a multiple of that near
+ * `band_bytes` of f32 (so a table of tens of GB streams and a GPTQ weight, whose row block is 0, is
+ * passed whole), writes each row-banded plane per band, and holds whole-tensor planes (a codebook, a
+ * per-tensor scale) until the last call. rad-convert writes a container through it, and the
+ * quantiser tests (tests/quant_fixture.h) run the same loop into memory, so the tests exercise the
+ * path every container is made by.
+ */
+#pragma once
+#include "../rad_internal.h"
+#include "rad_encoding.h"
+#include "rad_quant.h"
+
+#include 
+#include 
+
+namespace rad {
+
+/* The band rad-convert quantises at: 64 MiB of f32 rows. */
+constexpr int64_t kQuantBandBytes = (int64_t)64 << 20;
+
+struct QuantIo {
+    /* Rows [r0, r0 + n) of the source weight as f32 [n, cols]. RAD_OK, or a failure with *why. */
+    std::function read;
+    /* `bytes` of plane `k`, at byte `off` within that plane. RAD_OK, or a failure. */
+    std::function write;
+    /* Optional, after each quantise call: the band's source rows as read, before the quantiser
+     * changed them in place, and the planes that call wrote (a row-banded plane's rows for this
+     * band, a whole plane from its start), as a decoder takes them over `n` rows. */
+    std::function band;
+};
+
+/* Quantise `qw` under quantiser `q` and its `params` into `enc`, the encoding the quantiser answered
+ * when the weight was planned. Returns RAD_OK, or with the reason in *why:
+ *   RAD_E_STATE    given `qw`'s movement group and importance, the quantiser answers another
+ *                  encoding than the one planned;
+ *   RAD_E_SHAPE    its row block splits a block of its own encoding's scales;
+ *   RAD_E_FORMAT   the read failed;
+ *   RAD_E_IO       a write failed;
+ *   otherwise      the quantiser's own refusal. */
+int quantise_weight(const RadQuantizerInfo& q, const RadParam* params, int n_params,
+                    const RadQuantWeight& qw, const RadEncoding& enc, int64_t band_bytes,
+                    const QuantIo& io, std::string* why);
+
+}  /* namespace rad */
diff --git a/core/format/radfile.cpp b/core/format/radfile.cpp
index 24ee0055..f36329bd 100644
--- a/core/format/radfile.cpp
+++ b/core/format/radfile.cpp
@@ -1,8 +1,6 @@
-/* radfile.cpp -- the .rad reader and writer.
- *
- * Two halves of one decision. Everything the reader assumes on the hot path, the writer proves
- * while writing and the reader re-proves at open. The pair is in one file so a change to the
- * layout cannot land on only one side.
+/* radfile.cpp -- the .rad reader and writer. Everything the reader assumes on the hot path, the
+ * writer checks while writing and the reader re-checks at open; one file, so a layout change
+ * touches both.
  */
 #include "radfile.h"
 
@@ -73,28 +71,22 @@ int RadFile::read_at(void* dst, int64_t bytes, int64_t off) const {
 }
 
 void RadFile::drop_blob_cache() const {
-
     if (!base_ || !hdr_ || fd_ < 0) return;
     const int64_t tables = (int64_t)hdr_->data_off < size_ ? (int64_t)hdr_->data_off : size_;
     if (tables >= size_) return;
-    /* The process's mapping first, then the cache behind it: a page still mapped here is one the
-     * kernel has to unmap before it can drop it, and doing it in the other order leaves the
-     * fadvise with nothing to free. */
+    /* Unmap first, then drop the cache: the kernel cannot drop a page still mapped here. */
     ::madvise(base_ + tables, (size_t)(size_ - tables), MADV_DONTNEED);
     ::posix_fadvise(fd_, (off_t)tables, (off_t)(size_ - tables), POSIX_FADV_DONTNEED);
 }
 
-/* Advisory, and deliberately NOT paired with an madvise: the load reads with pread and never
- * maps these pages, so there is nothing of ours to unmap -- and the one region that IS read
- * through the mapping, the n-gram table on Tier::Mapped, is never handed to this. */
+/* Advisory, with no madvise: the load reads with pread and never maps these pages. The one region
+ * read through the mapping (a Tier::Mapped table) is never passed here. */
 void RadFile::drop_range(int64_t off, int64_t bytes) const {
-
     if (fd_ < 0 || bytes <= 0) return;
     ::posix_fadvise(fd_, (off_t)off, (off_t)bytes, POSIX_FADV_DONTNEED);
 }
 
 int RadFile::open(const char* path) {
-
     close();
     if (!path || !*path) return RAD_E_INVAL;
     path_ = path;
@@ -119,31 +111,15 @@ int RadFile::open(const char* path) {
     int s = validate();
     if (s < 0) { close(); return s; }
 
-    /* THE TABLES ARE WANTED NOW; THE BLOB IS READ ONCE, FRONT TO BACK.
-     *
-     * THE ADVICE IS DELIBERATELY ASYMMETRIC AND MUST STAY THAT WAY.
-     *
-     * MADV_WILLNEED over the whole file asks the kernel to pull every byte into the page cache.
-     * That is right for a container that fits in RAM and ruinous for one that does not: it becomes
-     * a readahead storm that evicts the pages it just read and never settles, and the weight load
-     * collapses to a small fraction of disk bandwidth with the host thread spinning inside
-     * hipMemcpyAsync waiting on a copy engine starved for source pages. The tables are small and
-     * read immediately and in full, so they keep WILLNEED; the blob gets NO advice at all.
-     *
-     * MADV_SEQUENTIAL is the obvious replacement for the blob and is worse than silence: it widens
-     * the readahead window and drops pages behind the read pointer, and the load is not one
-     * stream. It reads a layer's gate_up experts, then that layer's down experts, then the
-     * scales -- three cursors over three regions -- so "behind" for one of them is "just about to
-     * be read" for another, and every page is fetched, dropped, and fetched again. Default
-     * readahead is what this copy loop is fastest under.
-     *
-     * The Tier::Mapped weights re-advise their own range MADV_RANDOM once the planner has spoken
-     * (engine_bringup.cpp); a later madvise over a sub-range wins for that sub-range, so leaving
-     * the blob unadvised here does not take that away. */
+    /* The advice is deliberately asymmetric; keep it so. The tables are small and read at once,
+     * so they get MADV_WILLNEED. The blob gets no advice: WILLNEED on a container larger than RAM
+     * becomes a readahead storm that evicts what it just read and starves the load, and
+     * MADV_SEQUENTIAL drops pages behind the pointer, which hurts when several cursors read
+     * different regions. Tier::Mapped weights later advise their own range MADV_RANDOM
+     * (engine_bringup.cpp), which wins for that sub-range. */
     const int64_t tables = (int64_t)hdr_->data_off < size_ ? (int64_t)hdr_->data_off : size_;
     ::madvise(base_, (size_t)tables, MADV_WILLNEED);
-    /* A container extended in place (RadWriter::begin_append) keeps its tables PAST the blob;
-     * they are wanted now just the same. */
+    /* A container extended in place (RadWriter::begin_append) keeps its tables past the blob. */
     const int64_t blob_end = (int64_t)(hdr_->data_off + hdr_->data_bytes);
     if ((int64_t)hdr_->str_off >= blob_end && blob_end < size_)
         ::madvise(base_ + (blob_end & ~(int64_t)(RAD_ALIGN_UNIT - 1)),
@@ -153,13 +129,18 @@ int RadFile::open(const char* path) {
 
     by_name_.reserve((size_t)hdr_->dir_count * 2);
     for (int64_t i = 0; i < (int64_t)hdr_->dir_count; ++i)
-        by_name_.emplace(std::string_view(str(dir_[i].name)), i);
+        if (!by_name_.emplace(std::string_view(str(dir_[i].name)), i).second) {
+            RAD_ERR("%s: '%s' is in the directory twice (rows %lld and %lld); a lookup by name "
+                    "would serve only the first", path, str(dir_[i].name),
+                    (long long)by_name_[std::string_view(str(dir_[i].name))], (long long)i);
+            close();
+            return RAD_E_FORMAT;
+        }
 
     return RAD_OK;
 }
 
-/* Every offset and count in the header is attacker-shaped input until this function has run.
- * Nothing below this point re-checks, so nothing below this point may be reached without it. */
+/* Every header offset and count is untrusted until this has run; nothing later re-checks. */
 int RadFile::validate() {
     hdr_ = (const RadFileHeader*)base_;
 
@@ -184,11 +165,9 @@ int RadFile::validate() {
     auto span_ok = [&](uint64_t off, uint64_t bytes) {
         return bytes == 0 ? off <= n : (off <= n && bytes <= n - off);
     };
-    /* A TABLE IS CHECKED BY ITS COUNT, NEVER BY count * sizeof. Every count in the header is
-     * uint64 and attacker-shaped, so the product wraps: meta_count = 0x0AAAAAAAAAAAAAAB times
-     * 24 bytes is 8, span_ok passes, and the loop below -- which iterates meta_count, not the
-     * byte span -- walks 7.6e17 rows off the end of the mapping. Divide into the space that is
-     * left instead, where nothing can wrap. */
+    /* Check tables by count, never by count * sizeof: an untrusted uint64 count can wrap the
+     * product (0x0AAAAAAAAAAAAAAB * 24 == 8) while the loops iterate the count. Divide into the
+     * remaining space instead. */
     auto span_n = [&](uint64_t off, uint64_t count, uint64_t elem) {
         if (count == 0) return off <= n;
         return off <= n && count <= (n - off) / elem;
@@ -251,9 +230,8 @@ int RadFile::validate() {
         }
     }
 
-    /* An encoding the core cannot read is refused here, by its index, rather than handed to a
-     * kernel's layout hook as if it meant something: rad_enc_valid() is the whole contract of the
-     * struct -- roles, chains, plane kinds and core dtypes. */
+    /* Refuse an encoding the core cannot read here, by index, rather than pass it to a layout
+     * hook. rad_enc_valid() checks the whole struct: roles, chains, plane kinds, core dtypes. */
     for (uint64_t i = 0; i < hdr_->enc_count; ++i) {
         RadEncoding e;
         std::memcpy(&e, &encs_[i], sizeof e);
@@ -313,8 +291,8 @@ int RadFile::validate() {
                     (unsigned long long)hdr_->plane_count, enc.n_planes);
             return RAD_E_FORMAT;
         }
-        /* EVERY PLANE IS EXACTLY ITS ENCODING'S SIZE AND INSIDE ITS ENTRY. That is what lets a
-         * reader slice a plane by arithmetic and a mover treat the entry as one span. */
+        /* Every plane is exactly its encoding's size and inside its entry, so readers slice planes
+         * by arithmetic and the mover treats the entry as one span. */
         int64_t rows = 0, cols = 0;
         rad_enc_view(e.rank, e.shape, &rows, &cols);
         for (uint32_t k = 0; k < e.n_planes; ++k) {
@@ -335,18 +313,16 @@ int RadFile::validate() {
 
     /* ---------------------------------------------------------------- vocab */
     if (hdr_->vocab_bytes >= sizeof(RadVocabHeader)) {
-        /* THE SECTION IS READ IN PLACE through typed pointers, so the header and every array have
-         * to sit on their element's alignment, which is where the writer puts them. A file that
-         * does not is damaged, and reading it anyway is a misaligned load for every field. */
+        /* The section is read in place through typed pointers, so the header and every array must
+         * be aligned to their element (the writer guarantees it). */
         if (hdr_->vocab_off % alignof(RadVocabHeader) != 0) {
             RAD_ERR("%s: the vocab section starts at %llu, which is not %zu-aligned", path_.c_str(),
                     (unsigned long long)hdr_->vocab_off, alignof(RadVocabHeader));
             return RAD_E_FORMAT;
         }
         const RadVocabHeader* v = (const RadVocabHeader*)(base_ + hdr_->vocab_off);
-        /* Offset 0 means the array is absent -- an optional one (scores are unigram-only, types
-         * default to normal) simply is not written. Nothing real can live at file offset 0, so
-         * the sentinel is unambiguous. */
+        /* Offset 0 means an optional array is absent (scores are unigram-only; types default to
+         * normal). Nothing real lives at file offset 0. */
         auto arr_ok = [&](uint64_t off, uint64_t bytes, size_t align) {
             return bytes == 0 || off == 0 ||
                    (off >= hdr_->vocab_off &&
@@ -405,13 +381,9 @@ int RadFile::validate() {
     return RAD_OK;
 }
 
-/* Re-derive the fixed stride and refuse a container that does not have one.
- *
- * This is where the format's central claim is checked. `base + id * stride` is what the mover and
- * the expert kernels do on the critical path, and they do it without a bounds test, so the claim
- * has to be true before anything is handed a pointer. A file whose experts within a layer differ
- * in shape or format is REFUSED here rather than read with a table walk: reading it slowly would
- * quietly return exactly the property the format exists to provide. */
+/* Re-derive each layer's fixed expert stride and refuse a container without one. The mover and
+ * expert kernels compute `base + id * stride` with no bounds test, so this must hold before any
+ * pointer is handed out. */
 int RadFile::index_experts() {
     const int64_t n = (int64_t)hdr_->dir_count;
     int64_t i = 0;
@@ -432,7 +404,7 @@ int RadFile::index_experts() {
         g.layer       = layer;
         g.first_index = i;
 
-        /* Expert 0 establishes the shape of every expert in this layer. */
+        /* Expert 0 defines the layout of every expert in this layer. */
         int64_t j = i;
         while (j < n && dir_[j].layer == layer && dir_[j].expert == 0) ++j;
         g.n_slot = (int32_t)(j - i);
@@ -462,8 +434,8 @@ int RadFile::index_experts() {
         }
         g.unit_bytes = unit_end - g.base;
 
-        /* Every further expert must agree, byte for byte, with expert 0's internal layout, and
-         * must sit exactly one stride further along. */
+        /* Every further expert must match expert 0's internal layout exactly and sit one stride
+         * further along. */
         int32_t e_id = 1;
         while (j < n && dir_[j].layer == layer && dir_[j].expert >= 0) {
             if (dir_[j].expert != e_id) {
@@ -559,9 +531,9 @@ int RadWriter::begin(const char* path) {
     fd_out_ = ::open(path_.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
     if (fd_out_ < 0) { RAD_ERR("%s: %s", path_.c_str(), std::strerror(errno)); return RAD_E_IO; }
 
-    /* The data blob is spilled beside the target and spliced in at finish(). The tables in front
-     * of it cannot be sized until every weight has been added, and the blob is the model -- a
-     * 1.5 GB checkpoint is not going to be staged in RAM so the header can be back-patched. */
+    /* The blob is spilled beside the target and spliced in at finish() (unless sealed): the
+     * tables in front cannot be sized until every weight is added, and the blob is not held in
+     * RAM. */
     fd_spill_ = ::open(spill_path_.c_str(), O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
     spill_base_ = 0;
     if (fd_spill_ < 0) {
@@ -576,8 +548,8 @@ int RadWriter::begin(const char* path) {
 
 void RadWriter::abort() {
     if (append_) {
-        /* The file is the caller's container, not ours to unlink: put its header back -- a no-op
-         * unless finish_append() failed inside that last write -- and cut the tail off. */
+        /* The file is the caller's container: restore its header (a no-op unless finish_append()
+         * failed in that write) and truncate the tail. */
         if (fd_out_ >= 0) {
             (void)!::pwrite(fd_out_, &old_hdr_, sizeof old_hdr_, 0);
             (void)!::ftruncate(fd_out_, (off_t)old_size_);
@@ -598,9 +570,8 @@ void RadWriter::abort() {
 
 /* ------------------------------------------------------------------ append in place */
 
-/* The processes other than this one that hold the file open or mapped. /proc//fd for an open
- * descriptor and /proc//maps for a mapping whose descriptor was closed; a process this user
- * cannot inspect is not counted, which is the same reach the caller has over that process. */
+/* Other processes holding the file open (/proc//fd) or mapped (/proc//maps). Processes
+ * this user cannot inspect are not counted. */
 static std::vector other_users(dev_t dev, ino_t ino) {
     std::vector who;
     DIR* d = ::opendir("/proc");
@@ -661,8 +632,8 @@ int RadWriter::begin_append(const char* path, const RadFile& old) {
         ::close(fd_out_); fd_out_ = -1;
         return RAD_E_IO;
     }
-    /* The file `old` describes, unchanged since it was read: its header, byte for byte, and its
-     * length. Anything else and the directory being carried over names somebody else's bytes. */
+    /* The file must be unchanged since `old` read it (header bytes and length), or the carried-over
+     * directory would name the wrong bytes. */
     if (::pread(fd_out_, &old_hdr_, sizeof old_hdr_, 0) != (ssize_t)sizeof old_hdr_ ||
         std::memcmp(&old_hdr_, &old.header(), sizeof old_hdr_) != 0 ||
         (int64_t)st.st_size != old.size()) {
@@ -686,7 +657,6 @@ int RadWriter::begin_append(const char* path, const RadFile& old) {
     spill_base_ = append_base_;
     if (fd_spill_ < 0) {
         RAD_ERR("%s: %s", path, std::strerror(errno));
-        if (fd_spill_ >= 0) ::close(fd_spill_);
         ::close(fd_out_);
         fd_out_ = fd_spill_ = -1;
         return RAD_E_IO;
@@ -698,8 +668,11 @@ int RadWriter::begin_append(const char* path, const RadFile& old) {
 
 int64_t RadWriter::add_existing(const Weight& w, const RadFile& old, const RadFileEntry& e) {
     if (!began_ || !append_) return RAD_E_STATE;
-    /* The bytes and the encoding are the old entry's; what the entry SAYS about where it came from
-     * and which unit it moves with is the caller's, as a fresh write would record it. */
+    if (w.name.empty() || names_.count(w.name)) {
+        RAD_ERR("'%s': the container already holds a weight of this name", w.name.c_str());
+        return RAD_E_INVAL;
+    }
+    /* Bytes and encoding are the old entry's; provenance and movement group are the caller's. */
     RadFileEntry n = e;
     n.name        = intern(w.name);
     n.quantizer   = intern(w.quantizer);
@@ -715,13 +688,13 @@ int64_t RadWriter::add_existing(const Weight& w, const RadFile& old, const RadFi
     }
     dir_.push_back(n);
     dir_abs_.push_back(1);
+    names_.insert(w.name);
     return (int64_t)dir_.size() - 1;
 }
 
 uint32_t RadWriter::intern_encoding(const RadEncoding& e) {
-    /* Zeroed before it is copied in, so the padding and the unused plane slots of a table row
-     * are zeros and two converts of one checkpoint compare equal byte for byte -- and compared
-     * in that form, so stray bytes in a caller's unused slots do not make a second row. */
+    /* Zero first so padding and unused plane slots are zeros: two converts of one checkpoint are
+     * byte-identical, and stray bytes in a caller's unused slots do not create a second row. */
     RadEncoding c;
     std::memset(&c, 0, sizeof c);
     std::memcpy(c.scheme, e.scheme, sizeof c.scheme);
@@ -766,9 +739,8 @@ void RadWriter::add_profile(int32_t layer, int32_t expert, float share) {
     prof_.push_back(p);
 }
 
-/* Movement-unit bookkeeping. A unit is one (layer, expert) pair for a routed expert -- its
- * gate/up/down are adjacent because the unit of transfer is an expert, not a tensor -- and one
- * weight for everything else. */
+/* Movement-unit bookkeeping. A unit is a (layer, expert) pair for a routed expert (its gate/up/down
+ * slots adjacent, since an expert is the unit of transfer) and one weight for everything else. */
 int RadWriter::check_unit_invariant(const Weight& w, uint64_t off, uint64_t bytes) {
     const bool new_unit = (w.layer != cur_layer_ || w.expert != cur_expert_);
     if (new_unit) { cur_layer_ = w.layer; cur_expert_ = w.expert; }
@@ -823,13 +795,16 @@ int RadWriter::check_unit_invariant(const Weight& w, uint64_t off, uint64_t byte
                 w.name.c_str(), w.layer, w.expert, w.slot, grp_slot_seen_ - 1);
         return RAD_E_INVAL;
     }
+    /* The reader addresses at most this many slots an expert (RadFile::ExpertGroup::slot_off). */
+    constexpr int32_t kMaxSlots = (int32_t)(sizeof RadFile::ExpertGroup{}.slot_off /
+                                            sizeof RadFile::ExpertGroup{}.slot_off[0]);
+    if (w.slot >= kMaxSlots) {
+        RAD_ERR("'%s': layer %d expert %d has more than %d slots, which the directory cannot "
+                "address", w.name.c_str(), w.layer, w.expert, kMaxSlots);
+        return RAD_E_INVAL;
+    }
 
-    /* Expert 0 defines the shape of a unit; every later expert must match it slot for slot. The
-     * offset arithmetic above cannot catch a size mismatch on its own: an oversized expert still
-     * lands at the right base, and only the NEXT one is displaced -- so an oversized LAST expert
-     * passes every offset check and leaves a container whose base + id*stride runs off the end of
-     * the group. Refusing here means the writer stops while the operator still has the checkpoint
-     * open and can fix the manifest. */
+    /* Every later expert must match expert 0 slot for slot (see grp_slot_bytes_ in radfile.h). */
     if (grp_n_expert_ == 1) {
         grp_slot_bytes_.push_back(bytes);
     } else if ((size_t)w.slot < grp_slot_bytes_.size() && grp_slot_bytes_[(size_t)w.slot] != bytes) {
@@ -847,6 +822,10 @@ int RadWriter::check_unit_invariant(const Weight& w, uint64_t off, uint64_t byte
 int64_t RadWriter::add_weight(const Weight& w) {
     if (!began_ || sealed_) return RAD_E_STATE;
     if (w.name.empty() || w.rank == 0 || w.rank > RAD_MAX_RANK) return RAD_E_INVAL;
+    if (names_.count(w.name)) {
+        RAD_ERR("'%s': the container already holds a weight of this name", w.name.c_str());
+        return RAD_E_INVAL;
+    }
     if (!rad_enc_valid(&w.enc)) {
         RAD_ERR("'%s': its encoding is not one the core can read", w.name.c_str());
         return RAD_E_INVAL;
@@ -864,10 +843,9 @@ int64_t RadWriter::add_weight(const Weight& w) {
         return RAD_E_INVAL;
     }
 
-    /* Every entry starts on a movement-unit boundary. That costs up to 4 KiB of padding per
-     * matrix -- tens of megabytes on a large MoE -- and buys a transfer that never straddles a
-     * page needlessly. Its planes follow at RAD_ALIGN_SUB, a cacheline on the architectures in
-     * scope: SoA, so a code plane stays dense and a scale plane is its own stream. */
+    /* Every entry starts on a movement-unit boundary (up to 4 KiB padding per matrix, tens of MB on
+     * a large MoE) so a transfer never straddles a page needlessly. Planes follow at RAD_ALIGN_SUB
+     * (a cacheline here), structure-of-arrays: codes stay dense and scales are their own stream. */
     int64_t rows = 0, cols = 0;
     rad_enc_view(w.rank, w.shape, &rows, &cols);
     const uint64_t off = (uint64_t)align_up(blob_bytes_, RAD_ALIGN_UNIT);
@@ -913,6 +891,7 @@ int64_t RadWriter::add_weight(const Weight& w) {
 
     dir_.push_back(e);
     dir_abs_.push_back(0);
+    names_.insert(w.name);
     return (int64_t)dir_.size() - 1;
 }
 
@@ -958,10 +937,9 @@ int RadWriter::write_plane(int64_t idx, int k, int64_t off, const void* data, in
     return RAD_OK;
 }
 
-/* EVERY RESERVED BYTE WAS WRITTEN. A plane left short is a hole of zeros the reader cannot tell
- * from codes -- a quantiser that returned early, a block loop with an off-by-one -- so the file is
- * refused here, naming the weight, rather than written. Counted, not tracked by range: writes that
- * overlapped would pass, and no producer here writes a byte twice. */
+/* Every reserved byte must have been written; a short plane would be zeros indistinguishable from
+ * codes. Counted, not range-tracked: overlapping writes would pass, but no producer writes a byte
+ * twice. */
 int RadWriter::check_complete() const {
     for (size_t i = 0; i < dir_.size(); ++i) {
         if (dir_abs_[i]) continue;
@@ -985,8 +963,7 @@ int RadWriter::set_vocab_section(const void* blob, int64_t bytes) {
                 (long long)bytes, sizeof(RadVocabHeader));
         return RAD_E_INVAL;
     }
-    /* Sanity, here rather than at open: the reader would refuse this file, and a converter that
-     * writes a file its own reader refuses has wasted an hour of somebody's time. */
+    /* Check now what the reader would refuse at open, before a long convert is wasted. */
     const RadVocabHeader* h = (const RadVocabHeader*)blob;
     auto fits = [&](uint64_t off, uint64_t n) {
         return n == 0 || (off <= (uint64_t)bytes && n <= (uint64_t)bytes - off);
@@ -1114,9 +1091,8 @@ int RadWriter::finish() {
     if (sealed_) h = hdr_;
     else layout(&h);
 
-    /* Blob-relative to absolute. Both tables were built with offsets into the spill file, which
-     * is exactly the blob, so one add each. data_off is 2 MiB-aligned and every entry was already
-     * 4 KiB-aligned inside the blob, so the alignments survive the shift. */
+    /* Blob-relative to absolute: one add each. data_off is 2 MiB-aligned and entries are 4 KiB-
+     * aligned within the blob, so alignment is preserved. */
     for (auto& e : dir_) e.offset += h.data_off;
     for (auto& p : planes_) p.offset += h.data_off;
     if (have_vocab_) {
@@ -1153,42 +1129,36 @@ int RadWriter::finish() {
         at = (int64_t)h.data_off;
     }
 
-    /* SEALED, THE BLOB IS ALREADY HERE: every plane went to its final offset. The length is set
-     * explicitly because the blob's tail may be alignment the planes never wrote. */
+    /* Sealed: every plane is already at its final offset. Set the length explicitly, since the
+     * blob's tail may be unwritten alignment. A failure of either leaves a file that is short or
+     * not durable, so it fails the write rather than report a container that is not there. */
     if (sealed_) {
-        if (::ftruncate(fd_out_, (off_t)h.file_bytes) != 0 || ::fsync(fd_out_) != 0)
+        if (::ftruncate(fd_out_, (off_t)h.file_bytes) != 0 || ::fsync(fd_out_) != 0) {
             RAD_ERR("%s: %s", path_.c_str(), std::strerror(errno));
+            abort();
+            return RAD_E_IO;
+        }
         ::close(fd_out_);   fd_out_ = -1;
         ::close(fd_spill_); fd_spill_ = -1;
         began_ = false;
         return RAD_OK;
     }
 
-    /* Splice the spill in. copy_file_range stays in the kernel and reflinks on a filesystem that
-     * can, which on btrfs/xfs makes a 1.5 GB blob nearly free; the read/write fallback is there
-     * because tmpfs and older kernels cannot. The spill is exactly the blob's length: every
-     * reserved byte was written, and the last of them is the last plane's last byte. */
+    /* Splice the spill in with copy_file_range (in-kernel, reflinked on btrfs/xfs), falling back
+     * to read/write where unsupported (tmpfs, older kernels). The spill is exactly the blob's
+     * length. */
     if (::lseek(fd_spill_, 0, SEEK_SET) < 0) {
         RAD_ERR("%s: %s", spill_path_.c_str(), std::strerror(errno)); abort(); return RAD_E_IO;
     }
-    /* ============================== THE SPILL IS FREED AS IT IS COPIED ==============================
-     *
-     * A naive splice needs TWICE THE CONTAINER free, because the spill stays whole until the copy
-     * finishes and is only then unlinked. At container sizes in the hundreds of gigabytes that is
-     * the difference between a convert that fits on the disk and one that runs for half an hour,
-     * writes every weight, and then dies on the splice with ENOSPC.
-     *
-     * Punching a hole in the spill behind the copy gives the blocks back to the filesystem
-     * IMMEDIATELY, so the peak is one container plus a grain rather than two containers. ext4,
-     * xfs and btrfs all support it; where it is not supported fallocate fails and the copy
-     * proceeds exactly as it would without this. It is not an optimisation of the copy -- the
-     * bytes still move -- it is a bound on peak disk use. */
+    /* The spill is freed as it is copied. Otherwise the splice needs twice the container's size
+     * free (hundreds of GB) until the spill is unlinked. Punching holes behind the copy (ext4, xfs,
+     * btrfs) returns blocks immediately, bounding peak disk use to one container plus a grain;
+     * where unsupported, fallocate fails and the copy proceeds unchanged. */
     int64_t left = blob_bytes_;
     int64_t done = 0, punched = 0;
     auto punch_behind = [&](bool final_grain) {
 #if defined(__linux__) && defined(FALLOC_FL_PUNCH_HOLE)
-        /* 256 MiB at a time: enough that the syscall is noise against the copy, small enough that
-         * the residual peak overhead is negligible beside the container itself. */
+        /* 256 MiB grains: the syscall is negligible against the copy, as is the residual peak. */
         const int64_t grain = 256ll << 20;
         const int64_t len = done - punched;
         if (len <= 0 || (!final_grain && len < grain)) return;
@@ -1201,8 +1171,8 @@ int RadWriter::finish() {
 
 #if defined(__linux__) && defined(SYS_copy_file_range)
     while (left > 0) {
-        /* AN EXPLICIT INPUT OFFSET, so the punch below knows where the copy has reached and the
-         * read() fallback can pick up from the same place. */
+        /* An explicit input offset, so the punch and the read() fallback know where the copy
+         * reached. */
         loff_t oi = (loff_t)done;
         ssize_t n = (ssize_t)syscall(SYS_copy_file_range, fd_spill_, &oi,
                                      fd_out_, (loff_t*)nullptr, (size_t)left, 0u);
@@ -1232,7 +1202,11 @@ int RadWriter::finish() {
     }
     punch_behind(true);
 
-    if (::fsync(fd_out_) != 0) { RAD_ERR("%s: fsync: %s", path_.c_str(), std::strerror(errno)); }
+    if (::fsync(fd_out_) != 0) {
+        RAD_ERR("%s: fsync: %s", path_.c_str(), std::strerror(errno));
+        abort();
+        return RAD_E_IO;
+    }
     ::close(fd_out_);   fd_out_ = -1;
     ::close(fd_spill_); fd_spill_ = -1;
     ::unlink(spill_path_.c_str());
@@ -1240,8 +1214,8 @@ int RadWriter::finish() {
     return RAD_OK;
 }
 
-/* The new weights are already past the old end (write_plane() put them there); what is left is the
- * tables and, last, the header. */
+/* The new weights are already past the old end (write_plane()); write the tables, then the
+ * header last. */
 int RadWriter::finish_append() {
     blob_bytes_ = align_up(blob_bytes_, RAD_ALIGN_UNIT);
     const int64_t blob_end = append_base_ + blob_bytes_;
@@ -1278,8 +1252,8 @@ int RadWriter::finish_append() {
     h.prof_off   = (uint64_t)place8((int64_t)(prof_.size() * sizeof(RadFileProfile)));
     h.prof_count = prof_.size();
 
-    /* The blob is the old one and the new weights after it: one span, still pool-aligned at its
-     * start, with the old tail's padding inside it. */
+    /* The blob spans the old blob and the new weights, still pool-aligned at its start, with the
+     * old tail's padding inside. */
     h.data_off   = old_data_off_;
     h.data_bytes = (uint64_t)(blob_end - (int64_t)old_data_off_);
     h.file_bytes = (uint64_t)off;
@@ -1311,12 +1285,12 @@ int RadWriter::finish_append() {
     if (have_vocab_) put(vocab_blob_.data(), (int64_t)vocab_blob_.size(), h.vocab_off);
     put(prof_.data(), (int64_t)(prof_.size() * sizeof(RadFileProfile)), h.prof_off);
     if (st >= 0 && ::ftruncate(fd_out_, (off_t)off) != 0) st = RAD_E_IO;
-    /* Everything the new header names is durable before the header names it. */
+    /* Make everything durable before the new header names it. */
     if (st >= 0 && ::fsync(fd_out_) != 0) st = RAD_E_IO;
     if (st < 0) { RAD_ERR("%s: %s", path_.c_str(), std::strerror(errno)); abort(); return st; }
 
-    /* The way back: the old header and the old length. The old tables are still where that
-     * header points, so writing it back and truncating restores the file byte for byte. */
+    /* The way back: the old header and length. The old tables are still where that header
+     * points, so restoring it and truncating recovers the file byte for byte. */
     {
         const std::string bak = path_ + ".pre-append";
         const std::string tmp = bak + ".tmp";
diff --git a/core/format/radfile.h b/core/format/radfile.h
index 7020b261..adec085e 100644
--- a/core/format/radfile.h
+++ b/core/format/radfile.h
@@ -1,23 +1,17 @@
-/* radfile.h -- the .rad reader and writer.
+/* radfile.h -- the .rad reader and writer, implementing exactly the format frozen in
+ * abi/rad_format.h. The writer and reader live together so they cannot disagree.
  *
- * The container is frozen in abi/rad_format.h; this file implements exactly it and adds
- * nothing to the on-disk shape. What lives here is the two halves that must never disagree: the
- * writer that produces a layout and the reader that maps it.
- *
- * The reader is an mmap and an index build, and then it is done. Every invariant a reader relies
- * on is CHECKED AT OPEN rather than asserted at use:
+ * The reader mmaps and builds an index. Every invariant is checked at open, not at use:
  *
  *   - every offset and count is bounds-checked against the mapped length, so a truncated or
- *     corrupt file is RAD_E_FORMAT with a message and not a SIGSEGV three components later;
- *   - every rad_stroff lands inside a string blob whose last byte is NUL, so str() is a plain
- *     pointer and never a scan;
- *   - the expert directory's fixed stride is RE-DERIVED and verified, so
- *     `base + id * stride` on the critical path is arithmetic somebody already proved.
+ *     corrupt file is RAD_E_FORMAT with a message, not a later SIGSEGV;
+ *   - every rad_stroff lands inside a NUL-terminated string blob, so str() is a plain pointer;
+ *   - the expert directory's fixed stride is re-derived and verified, so `base + id * stride` on
+ *     the critical path is safe.
  *
- * The cost of the last one, stated plainly: a container whose experts within a layer are not all
- * the same shape and format is REFUSED, not read slowly. Addressing by arithmetic is the format's
- * reason to exist; a file that cannot be addressed that way is not a .rad, and reading it with a
- * table walk would silently give back the property the whole design was paying for.
+ * Consequently a container whose experts within a layer differ in shape or format is refused:
+ * addressing by arithmetic is the format's purpose. So is one that names a weight twice, since
+ * find() could return only one of them.
  */
 #pragma once
 #include "../rad_internal.h"
@@ -26,31 +20,24 @@
 #include 
 #include 
 #include 
+#include 
 #include 
 
 namespace rad {
 
 /* ================================================================== vocab */
-/* The MUTABLE side of the vocab -- VocabBuild, the tokenizer.json interpreter and the serialiser
- * that turns one into a RadVocabHeader -- belongs to core/text, because interpreting a declared
- * normaliser chain is that component's whole job (spec §12). What belongs here is the container's
- * half of the contract, and it is two things:
+/* The vocab's mutable side (VocabBuild, the tokenizer.json interpreter, the serialiser) belongs to
+ * core/text (spec §12). The container's half of the contract:
  *
- *   RadWriter::intern_string()   so the vocab section's strings go into the .rad's ONE string
- *                                blob rather than a second one nobody else can read;
- *   RadWriter::set_vocab_section() so the serialised bytes are placed and rebased by the writer
- *                                that owns every other offset in the file.
+ *   RadWriter::intern_string()     the vocab's strings go into the .rad's single string blob;
+ *   RadWriter::set_vocab_section() the writer places and rebases the serialised bytes like every
+ *                                  other offset.
  *
- * core/text's `StringSink` is the interface that joins them, and rad-convert supplies the two-line
- * adapter. Keeping VocabBuild out of this header is what stops two definitions of it existing.
+ * core/text's `StringSink` joins them; rad-convert supplies the adapter.
  *
- * The read-back view below is the container's own: pointers into the mapping, already
- * bounds-checked at open. core/text's vocab_deserialize() copies out of it. */
-/* NOT named VocabView: core/sample/vocab_view.h declares an ABSTRACT CLASS of that name in this
- * same namespace, and two definitions of one name are an ODR violation the moment one translation
- * unit includes both -- which core/engine.cpp does, because it loads the container and drives the
- * sampler. This one is the container's read-back view of the vocab SECTION; the other is what the
- * sampler needs to know about a vocabulary. Different things, deliberately different names. */
+ * The read-back view below holds pointers into the mapping, bounds-checked at open;
+ * vocab_deserialize() copies out of it. Not named VocabView, which core/sample/vocab_view.h
+ * declares in this namespace (an ODR clash in any unit including both). */
 struct VocabSection {
     const RadVocabHeader* h        = nullptr;
     const rad_stroff*     tok_text = nullptr;   /* [n_tokens] */
@@ -69,8 +56,7 @@ public:
     RadFile(const RadFile&) = delete;
     RadFile& operator=(const RadFile&) = delete;
 
-    /* mmap, validate, index. Returns RAD_OK, or RAD_E_IO / RAD_E_FORMAT with the reason logged at
-     * Error naming the field that failed -- a bad container is diagnosed here or nowhere. */
+    /* mmap, validate, index. RAD_OK, or RAD_E_IO / RAD_E_FORMAT with the failing field logged. */
     int  open(const char* path);
     void close();
     bool is_open() const { return base_ != nullptr; }
@@ -80,44 +66,22 @@ public:
     const uint8_t*       base()   const { return base_; }
     int64_t              size()   const { return size_; }
 
-    /* Drop the blob from the page cache and from this process's page tables.
-     *
-     * A container larger than RAM cannot be traversed twice without this. When the weight load
-     * walks the whole file once per rank, the second walk meets a page cache that is entirely the
-     * first walk's pages: nothing it needs is resident, and the readahead it triggers evicts the
-     * pages it is about to want. The load then makes no forward progress while the device sits
-     * idle behind a stream of NVMe reads that are immediately thrown away.
-     *
-     * Only the blob: the tables are small, read constantly, and wanted resident for the life of
-     * the process. Advisory in both directions -- if the kernel declines, the load is exactly as
-     * it was. */
+    /* Drop the blob from the page cache and this process's page tables, so a container larger
+     * than RAM does not leave the cache full of pages nothing will read. Only the blob: the tables
+     * are small and read constantly. Advisory; the kernel may decline. */
     void drop_blob_cache() const;
 
-    /* Drop one range of the blob behind a cursor that will not come back for it.
-     *
-     * The weight load reads the container once, front to back, and nothing re-reads a window it
-     * has finished with -- but buffered reads leave every one of those bytes in the page cache,
-     * and on a container larger than RAM that turns into reclaim pressure the read itself then
-     * waits on, so the sweep rate decays as it advances. Dropping each window as it is consumed
-     * holds the rate flat.
-     *
-     * THE PRECONDITION IS ONE CURSOR. Drop-behind is wrong with several cursors over one file,
-     * because what one discards is what another is about to want -- the same reason a sequential
-     * access hint is worse than silence in that arrangement. This call is correct only for a
-     * single cursor moving in one direction with no revisits, where the pages are genuinely
-     * dead. */
+    /* Drop one range of the blob behind a single forward cursor. A buffered front-to-back read of
+     * a container larger than RAM otherwise builds reclaim pressure that slows the read itself.
+     * Correct only for one cursor moving in one direction with no revisits; with several, one
+     * would drop what another is about to read. */
     void drop_range(int64_t off, int64_t bytes) const;
 
-    /* Read `bytes` at `off` into `dst` with pread, bypassing the mapping entirely.
-     *
-     * The load phase wants this and not the mapping. An async copy whose source is pageable
-     * memory is staged by the HIP runtime through its own pinned buffer, and that path degrades
-     * without bound as a load proceeds: even with the source pages already resident, a single
-     * small hipMemcpyAsync can block for seconds. Reading into a pinned buffer the loader owns
-     * makes the device copy a real DMA from pinned memory, which has none of that behaviour.
-     *
-     * Returns RAD_OK, or RAD_E_IO with the reason logged. Short reads are retried; EINTR is not
-     * an error. */
+    /* pread `bytes` at `off` into `dst`, bypassing the mapping. For loads: an async copy from
+     * pageable memory goes through the HIP runtime's own staging, which degrades as a load
+     * proceeds (a small hipMemcpyAsync can block for seconds even with resident pages); reading
+     * into the loader's pinned buffer makes the copy a real DMA. RAD_OK, or RAD_E_IO with the
+     * reason logged; short reads and EINTR are retried. */
     int read_at(void* dst, int64_t bytes, int64_t off) const;
 
     /* Strings. Offset 0 is the empty string; every offset was bounds-checked at open. */
@@ -138,8 +102,8 @@ public:
     const RadFileEntry* find(std::string_view name) const;
     const uint8_t*      data(const RadFileEntry& e) const { return base_ + e.offset; }
 
-    /* An entry's encoding and its planes, in the encoding's order. Every plane was checked at open
-     * to be exactly the size its encoding and the entry's shape say. */
+    /* An entry's encoding and its planes in encoding order; each plane's size was checked at
+     * open. */
     const RadEncoding&  encoding(const RadFileEntry& e) const { return encs_[e.enc]; }
     const RadFilePlane& plane(const RadFileEntry& e, int k) const {
         return planes_[e.plane_first + (uint64_t)k];
@@ -149,9 +113,8 @@ public:
     const RadEncoding&  encoding_at(int64_t i) const { return encs_[i]; }
 
     /* ------------------------------------------------------------ fixed-stride addressing */
-    /* One layer's experts. All of them share a shape and a format, which is what makes
-     *     addr = base + id * stride
-     * O(1) arithmetic with no table walk on the critical path (spec §4.1). Verified at open. */
+    /* One layer's experts, all of one shape and format, so addr = base + id * stride with no table
+     * walk on the critical path (spec §4.2). Verified at open. */
     struct ExpertGroup {
         int32_t  layer      = -1;
         int32_t  n_expert   = 0;
@@ -160,7 +123,7 @@ public:
         uint64_t base       = 0;      /* file offset of expert 0's first byte */
         uint64_t stride     = 0;      /* bytes between consecutive experts, aligned */
         uint64_t unit_bytes = 0;      /* payload of one expert: every slot's every plane */
-        /* Per-slot displacement from an expert's base. Fixed across experts by construction. */
+        /* Per-slot offset from an expert's base, the same for every expert. */
         uint64_t slot_off[8] = {0};
         uint64_t slot_bytes[8] = {0};
     };
@@ -168,8 +131,7 @@ public:
     int64_t            group_count() const { return (int64_t)groups_.size(); }
     const ExpertGroup* group_for_layer(int32_t layer) const;
 
-    /* The whole point of the format, in one line each. No bounds check on the hot path: the
-     * caller has the group and therefore has n_expert and n_slot. */
+    /* No bounds check on the hot path: the caller has the group's n_expert and n_slot. */
     const uint8_t* expert_ptr(const ExpertGroup& g, int32_t expert, int32_t slot) const {
         return base_ + g.base + (uint64_t)expert * g.stride + g.slot_off[slot];
     }
@@ -205,21 +167,18 @@ private:
 };
 
 /* ================================================================== writer */
-/* Streaming, because the blob is the model: a 100 GB checkpoint cannot be staged in RAM to be
- * re-sorted at the end. The tables (strings, directory, planes, encodings, vocab, profile) ARE held
- * in memory -- a 512-expert 48-layer model is ~50k directory rows, which is megabytes.
+/* Streaming writer: the blob is never held in RAM (a checkpoint may be 100 GB). The tables
+ * (strings, directory, planes, encodings, vocab, profile) are in memory; ~50k directory rows for a
+ * 512-expert 48-layer model is megabytes.
  *
- * A WEIGHT IS RESERVED, THEN WRITTEN. add_weight() places the entry and every plane of its
- * encoding in the blob and returns its index; write_plane() fills any part of any plane, in any
- * order, at its position. That is what a quantiser needs -- it produces a block of rows of EVERY
- * plane at once -- and what a 51 GB table needs, whose codes are produced a block at a time
- * without the whole ever existing anywhere. finish() refuses a plane left short.
+ * A weight is reserved, then written: add_weight() places the entry and every plane and returns
+ * its index; write_plane() fills any part of any plane in any order. A quantiser produces rows of
+ * every plane at once, and a 51 GB table is produced block by block. finish() refuses a plane left
+ * short.
  *
- * The consequence, and it is a real constraint on callers: WEIGHTS MUST BE ADDED IN MOVEMENT-UNIT
- * ORDER. An expert's slots must be added consecutively, and a layer's experts must be added
- * consecutively and identically shaped. The writer verifies it and refuses with RAD_E_INVAL naming
- * the offending pair, rather than producing a file whose stride is a lie. rad-convert sorts its
- * manifest before it starts writing; that sort is over the manifest, not over the bytes.
+ * Callers must add weights in movement-unit order: an expert's slots consecutively, and a layer's
+ * experts consecutively with identical shapes. The writer verifies this and refuses with
+ * RAD_E_INVAL naming the offending pair. rad-convert sorts its manifest before writing.
  */
 class RadWriter {
 public:
@@ -252,23 +211,16 @@ public:
         int32_t     layer = -1, expert = -1, slot = 0;
     };
 
-    /* APPEND IN PLACE: extend the container `old` (opened at `path`) with new weights, without
-     * copying the ones it already holds.
+    /* Append in place: extend container `old` (opened at `path`) with new weights without copying
+     * the existing ones. Offsets are absolute, so new bytes go past the end, followed by fresh
+     * tables naming both the old weights (at their offsets, via add_existing()) and the new; the
+     * header is rewritten last. Until then the file is its old self with an unreachable tail;
+     * afterwards the old tables are dead bytes. finish() leaves `.pre-append` (the old
+     * header and length) to restore it.
      *
-     * A container is a header, its tables, and the blob, and every offset in them is absolute, so
-     * nothing forces a new weight to live anywhere but past the end. The new weights' bytes are
-     * written there, then a fresh set of tables that names both the old weights -- at the offsets
-     * they already have, through add_existing() -- and the new ones, and the header is rewritten
-     * last. Until that one write the file is its old self with a tail the old header does not
-     * reach; after it, the old tables are dead bytes in front of the blob. finish() also leaves
-     * `.pre-append`: the old header and length, which is all it takes to put the file back.
-     *
-     * It is what makes adding a component to a 120 GB container a gigabyte of I/O instead of a
-     * 120 GB copy the disk may not have room for. A new EXPERT weight is refused: a layer's experts
-     * are written consecutively at a fixed stride, and an appended one cannot join its layer.
-     *
-     * The caller must be the file's only user. A process that has it mapped reads the header
-     * through its mapping, and a header that changes under it names tables it never validated. */
+     * New expert weights are refused: a layer's experts sit at a fixed stride and cannot be
+     * extended. The caller must be the file's only user, since a process mapping it would see the
+     * header change under it. */
     int  begin_append(const char* path, const RadFile& old);
     /* A weight `old` already holds, recorded at the offsets it has there. Its encoding and planes
      * are the old entry's; its name, provenance and movement group are `w`'s. */
@@ -276,7 +228,7 @@ public:
 
     /* Reserve the weight and every plane of its encoding. Returns the directory index, or a
      * negative status: an invalid encoding, a shape it cannot cover, a movement-unit order the
-     * stride cannot hold. */
+     * stride cannot hold, a name the container already holds. */
     int64_t add_weight(const Weight& w);
     /* Reserve and write in one call: `planes[k]` is plane k's whole bytes. */
     int64_t add_weight(const Weight& w, const void* const* planes);
@@ -285,26 +237,23 @@ public:
     int write_plane(int64_t idx, int k, int64_t off, const void* data, int64_t bytes);
     int64_t plane_bytes(int64_t idx, int k) const;
 
-    /* Intern into the .rad's single string blob. Public because the vocab section's writer lives
-     * in core/text and has to put its token text somewhere the reader can find it; core/text's
-     * StringSink is the one-method interface rad-convert adapts onto this. */
+    /* Intern into the .rad's single string blob. Public for core/text's vocab writer (via
+     * StringSink). */
     rad_stroff intern_string(std::string_view s) { return intern(s); }
 
-    /* The serialised vocab section. Its internal offsets must be SECTION-RELATIVE (serialise with
-     * a section_file_off of 0); finish() rebases them once it knows where the section lands, the
-     * same way it rebases the directory. */
+    /* The serialised vocab section. Its internal offsets must be section-relative (serialise with
+     * section_file_off 0); finish() rebases them, as it does the directory. */
     int  set_vocab_section(const void* blob, int64_t bytes);
 
     void add_profile(int32_t layer, int32_t expert, float share);
 
-    /* FIX THE LAYOUT AND WRITE THE BLOB WHERE IT STAYS. Once every weight, the metadata, the vocab
-     * section and the profile are in, the tables' sizes -- and so the blob's offset -- are known:
-     * after seal() a plane write lands in the target itself and finish() writes the tables in
-     * front of it, with no spill and no 100 GB copy. A table changed after it fails finish(). A
-     * writer that is not sealed spills the blob and splices it in at finish(). */
+    /* Fix the layout once every weight, the metadata, the vocab section and the profile are in, so
+     * the blob's offset is known: afterwards plane writes land in the target directly and
+     * finish() writes the tables in front, with no spill and no copy. Changing a table afterwards
+     * fails finish(). An unsealed writer spills the blob and splices it in at finish(). */
     int  seal();
 
-    /* Writes the header and every table, then -- unsealed -- splices the spilled blob in at a
+    /* Writes the header and every table, then (if unsealed) splices the spilled blob in at a
      * 2 MiB boundary. */
     int  finish();
 
@@ -326,8 +275,8 @@ private:
     RadFileHeader hdr_{};           /* the sealed layout */
 
     /* Append mode (begin_append). New bytes go at `append_base_`, the old length rounded up to a
-     * pool boundary; an entry recorded by add_existing() is already absolute and is flagged so
-     * finish() does not rebase it. */
+     * pool boundary; add_existing() entries are already absolute and flagged so finish() does not
+     * rebase them. */
     int  finish_append();
     int  check_complete() const;
     bool     append_ = false;
@@ -346,6 +295,8 @@ private:
     std::vector                          written_;   /* parallel to planes_ */
     std::vector                      encs_;
     std::vector                   prof_;
+    /* Every weight name added, since a name is looked up and must find one entry. */
+    std::unordered_set               names_;
 
     /* The vocab section, assembled in memory and appended verbatim. */
     std::vector vocab_blob_;
@@ -353,21 +304,19 @@ private:
 
     int64_t blob_bytes_ = 0;    /* the blob's reserved length */
 
-    /* Movement-unit bookkeeping, so the fixed stride is a property the writer PROVES. */
+    /* Movement-unit bookkeeping, so the writer verifies the fixed stride. */
     int32_t  cur_layer_ = -2, cur_expert_ = -2;
     int32_t  grp_layer_ = -2;
     int32_t  grp_n_slot_ = 0, grp_slot_seen_ = 0, grp_n_expert_ = 0;
     uint64_t grp_first_off_ = 0, grp_expert_off_ = 0, grp_stride_ = 0;
-    /* Expert 0's per-slot payload. ExpertGroup promises slot_off[] and slot_bytes[] are fixed
-     * across the experts of a layer "by construction", and this is where that is constructed:
-     * an expert whose slot differs in size is refused at ITS OWN add_weight, not at the next
-     * one's. The offset check alone cannot see it -- an oversized LAST expert lands at the right
-     * base and simply overruns past base + n*stride. */
+    /* Expert 0's per-slot payload, which enforces ExpertGroup's fixed slot_off[]/slot_bytes[]: an
+     * expert whose slot differs in size is refused at its own add_weight. The offset check alone
+     * misses an oversized last expert, which starts at the right base and overruns. */
     std::vector grp_slot_bytes_;
 };
 
 /* ================================================================== helpers for the tools */
-/* "layer 12 / expert 7" and friends, so rad-info and every diagnostic name a unit the same way. */
+/* "layer 12 / expert 7" etc., so every diagnostic names a unit the same way. */
 std::string rad_unit_name(int32_t layer, int32_t expert);
 
 }  /* namespace rad */
diff --git a/core/format/recipe.cpp b/core/format/recipe.cpp
index 92218728..f26f2486 100644
--- a/core/format/recipe.cpp
+++ b/core/format/recipe.cpp
@@ -1,8 +1,11 @@
 /* recipe.cpp -- see recipe.h. */
 #include "recipe.h"
+#include "../plugin/registry.h"
 
 #include 
 #include 
+#include 
+#include 
 #include 
 
 namespace rad {
@@ -34,8 +37,8 @@ bool recipe_glob(const char* p, const char* n) {
 
 namespace {
 
-/* `$NAME` and `${NAME}` from the environment. An unset name is refused: a recipe that silently
- * quantises against an empty calibration directory is a recipe that did something else. */
+/* Expand `$NAME` and `${NAME}` from the environment. An unset name is refused rather than
+ * expanded to empty (e.g. an empty calibration directory). */
 bool expand(const std::string& in, std::string* out, std::string* why) {
     out->clear();
     for (size_t i = 0; i < in.size(); ++i) {
@@ -159,6 +162,66 @@ const RecipeRule* Recipe::match(const std::string& name) const {
     return nullptr;
 }
 
+int CompiledRule::build(const RecipeRule& r, const Registry& reg, std::string* why) {
+    rule = &r;
+    const Registry::QuantRow* row = reg.quantizer(r.quantizer);
+    if (!row || !row->info) {
+        std::string have;
+        for (const auto& qr : reg.quantizers())
+            if (qr.info) have += std::string(have.empty() ? "" : ", ") + qr.info->name;
+        *why = r.origin + ": no quantiser '" + r.quantizer + "' is loaded (" +
+               (have.empty() ? std::string("none are -- is $RADIANCE_HOME/quantizers there?")
+                             : "loaded: " + have) + ")";
+        return RAD_E_NOTFOUND;
+    }
+    q = row->info;
+    keys.reserve(r.options.size());
+    vals.reserve(r.options.size());
+    for (const auto& [k, v] : r.options) {
+        const RadQuantOption* opt = nullptr;
+        for (int i = 0; i < q->n_options; ++i)
+            if (k == q->options[i].key) opt = &q->options[i];
+        if (!opt) {
+            std::string takes;
+            for (int i = 0; i < q->n_options; ++i)
+                takes += std::string(i ? ", " : "") + q->options[i].key;
+            *why = r.origin + ": " + q->name + " takes no option '" + k + "' (it takes " + takes +
+                   ")";
+            return RAD_E_INVAL;
+        }
+        char* end = nullptr;
+        errno = 0;
+        if (opt->type == RAD_P_INT) {
+            const long long x = std::strtoll(v.c_str(), &end, 10);
+            if (v.empty() || !end || *end || errno == ERANGE) {
+                *why = r.origin + ": " + k + "=" + v + " is not a whole number";
+                return RAD_E_INVAL;
+            }
+            keys.push_back(k);
+            vals.push_back(v);
+            params.push_back(RAD_INT(nullptr, x));
+        } else if (opt->type == RAD_P_F64) {
+            const double x = std::strtod(v.c_str(), &end);
+            if (v.empty() || !end || *end || errno == ERANGE || !std::isfinite(x)) {
+                *why = r.origin + ": " + k + "=" + v + " is not a number";
+                return RAD_E_INVAL;
+            }
+            keys.push_back(k);
+            vals.push_back(v);
+            params.push_back(RAD_F64(nullptr, x));
+        } else {
+            keys.push_back(k);
+            vals.push_back(v);
+            params.push_back(RAD_STR(nullptr, nullptr));
+        }
+    }
+    for (size_t i = 0; i < params.size(); ++i) {
+        params[i].key = keys[i].c_str();
+        if (params[i].kind == RAD_P_STR) params[i].sval = vals[i].c_str();
+    }
+    return RAD_OK;
+}
+
 std::string Recipe::text() const {
     std::string s;
     for (const RecipeRule& r : rules_) {
diff --git a/core/format/recipe.h b/core/format/recipe.h
index bef90067..20e51f7b 100644
--- a/core/format/recipe.h
+++ b/core/format/recipe.h
@@ -1,18 +1,18 @@
 /* recipe.h -- which quantiser makes which weight, for rad-convert (spec §4.4).
  *
- * A recipe is ordered rules from a logical weight name to a quantiser and its options. The first
- * rule whose pattern matches a weight decides it; a weight no rule matches keeps the checkpoint's
- * encoding. Two spellings, one rule each:
+ * A recipe is ordered rules from a logical weight name to a quantiser and options; the first match
+ * decides, and an unmatched weight keeps the checkpoint's encoding. Two spellings:
  *
  *   in a file          PATTERN  QUANTISER  key=value key=value ...      # a comment
  *   on the command     PATTERN=QUANTISER:key=value,key=value
  *
- * A pattern is a glob over the whole name: `*` is any run of characters (dots included), `?` is
- * one. `$NAME` or `${NAME}` in an option is the environment's, expanded when the rule is read, so
- * one recipe serves every machine and the container records what it was actually given.
+ * A pattern is a glob over the whole name: `*` matches any run (dots included), `?` one
+ * character. `$NAME` or `${NAME}` in an option is expanded from the environment when the rule is
+ * read, so the container records the actual values.
  */
 #pragma once
 #include "../rad_internal.h"
+#include "rad_quant.h"
 
 #include 
 #include 
@@ -20,13 +20,15 @@
 
 namespace rad {
 
+class Registry;
+
 struct RecipeRule {
     std::string pattern, quantizer;
     std::vector> options;   /* in the order written */
     std::string origin;                                         /* "file:12" or "--quant" */
 
-    /* The options as one canonical string, `key=value` comma-separated and sorted by key: what a
-     * container entry records and what --reuse compares, however the rule spelled them. */
+    /* The options as one canonical string (`key=value`, comma-separated, sorted by key), as a
+     * container entry records and --reuse compares them. */
     std::string options_text() const;
 };
 
@@ -45,11 +47,34 @@ public:
 
     const std::vector& rules() const { return rules_; }
     bool empty() const { return rules_.empty(); }
-    /* Every rule in the file spelling, one a line, options expanded: what the container records. */
+    /* Every rule in the file spelling, one per line, options expanded, as the container records. */
     std::string text() const;
 
 private:
     std::vector rules_;
 };
 
+/* A rule with its quantiser resolved and its options typed by the quantiser's own option table,
+ * so a misspelt key or a value of the wrong type is refused before declare. Integers are decimal
+ * (the container records the text, and --reuse compares it, so `010` must mean what it reads as);
+ * an empty value or one that is not finite is refused.
+ *
+ * The RadParam strings point into `keys` and `vals`, so a compiled rule is built in place and never
+ * copied or moved. */
+struct CompiledRule {
+    const RecipeRule*        rule = nullptr;
+    const RadQuantizerInfo*  q = nullptr;
+    std::vector keys, vals;
+    std::vector    params;
+
+    CompiledRule() = default;
+    CompiledRule(const CompiledRule&) = delete;
+    CompiledRule& operator=(const CompiledRule&) = delete;
+
+    /* RAD_OK; RAD_E_NOTFOUND when no loaded quantiser has the rule's name (the message lists the
+     * ones that are); RAD_E_INVAL for an option the quantiser does not take or a value its type
+     * refuses. The reason, with the rule's origin, is in *why. */
+    int build(const RecipeRule& r, const Registry& reg, std::string* why);
+};
+
 }  /* namespace rad */
diff --git a/core/format/rope_override.h b/core/format/rope_override.h
index 3151b5bf..82b52c80 100644
--- a/core/format/rope_override.h
+++ b/core/format/rope_override.h
@@ -1,19 +1,17 @@
-/* --rope-scaling, over a container's free-form metadata.
+/* rope_override.h -- --rope-scaling, applied to a container's free-form metadata at load.
  *
- * Static YaRN is read by the architecture (arch/common/rad_arch.h, yarn_from) out of the model's
- * own keys: `text_config.rope_parameters.`, `rope_parameters.`, `text_config.rope_scaling.`,
- * `rope_scaling.`, in that order, the FIRST of them that names a rotary type being the one that
- * counts; a DFlash2 drafter reads `draft.rope_parameters.` / `draft.rope_scaling.` on its own. A
- * container converted without YaRN therefore needs a reconvert to get it -- or these keys rewritten
- * when it is loaded, which is all this does. The architecture then resolves the result exactly as
- * it would a converted container, so there is one reader and one set of checks.
+ * The architecture reads static YaRN (arch/common/rad_arch.h, yarn_from) from the first of
+ * `text_config.rope_parameters.`, `rope_parameters.`, `text_config.rope_scaling.`, `rope_scaling.`
+ * that names a rotary type; a DFlash2 drafter reads `draft.rope_parameters.` /
+ * `draft.rope_scaling.`. These functions rewrite those keys so a container gains YaRN without
+ * reconversion, and the architecture's one reader and checks apply.
  *
- * The rewrite goes into the object the reader would take, not beside it. A Qwen3.8 container says
- * `text_config.rope_parameters.rope_type = default`; a YaRN written under `rope_parameters.` would
- * sit behind that and never be read.
+ * The rewrite targets the object the reader takes: a Qwen3.8 container says
+ * `text_config.rope_parameters.rope_type = default`, so YaRN under `rope_parameters.` would be
+ * ignored.
  *
- * Pure functions over two parallel string vectors, so they are tested without an engine
- * (tests/yarn_test.cpp holds them to yarn_from). */
+ * Pure functions over parallel string vectors, tested without an engine (tests/yarn_test.cpp
+ * checks them against yarn_from). */
 #pragma once
 
 #include 
@@ -32,8 +30,7 @@ struct RopeSpec {
     int64_t orig = 0;   /* 0: the container's own trained length */
 };
 
-/* "yarn:FACTOR[:ORIG]" with FACTOR > 1 and ORIG > 0, or "none"; empty is Keep. False for anything
- * else, so a typo is refused where it was typed. */
+/* "yarn:FACTOR[:ORIG]" with FACTOR > 1 and ORIG > 0, or "none"; empty is Keep. False otherwise. */
 inline bool rope_spec_parse(const char* s, RopeSpec* out) {
     RopeSpec r;
     if (!s || !*s) { *out = r; return true; }
@@ -88,7 +85,7 @@ struct RopeKeys {
     }
 };
 
-/* The reader's order -- yarn_from's, kept in step with it. */
+/* The reader's search order; must match yarn_from's. */
 inline std::vector rope_homes(const char* group) {
     if (!*group)
         return { "text_config.rope_parameters.", "rope_parameters.", "text_config.rope_scaling.",
@@ -96,8 +93,8 @@ inline std::vector rope_homes(const char* group) {
     return { std::string(group) + "rope_parameters.", std::string(group) + "rope_scaling." };
 }
 
-/* The object the reader takes and the key that names its type, or empty strings when no object
- * names one (the model's rotary is then the default). */
+/* The object the reader takes and the key naming its type; empty when none names one (the default
+ * rotary). */
 inline void rope_authoritative(const RopeKeys& kv, const char* group, std::string* home,
                                std::string* type_key) {
     home->clear();
@@ -127,9 +124,9 @@ inline RopeResolved rope_resolve(std::vector& k, std::vector& k, std::vector& v,
                                 const RopeSpec& spec, const char* group, int64_t trained,
                                 std::string* why) {
@@ -154,8 +151,8 @@ inline bool rope_override_group(std::vector& k, std::vector& k, std::vector.rope.* -- as key=value, sorted, after
- * --rope-scaling has been applied. A persisted prefix store is fingerprinted with it: a container
- * converted from the same checkpoint with YaRN has the same name and the same shapes, and its
- * stock-rotated keys (and QSA block keys) read back under YaRN would be attended to at the wrong
- * angles. Key order and unrelated keys do not change it. */
+/* The rotary's identity: every key with a path component containing `rope` or `rotary`
+ * (rope_parameters.*, rope_scaling.*, rope_theta, partial_rotary_factor, their text_config. and
+ * draft. forms, a GGUF's .rope.*) as sorted key=value, after --rope-scaling. A persisted
+ * prefix store is fingerprinted with it, since the same container with YaRN has identical names and
+ * shapes but cached keys would be at the wrong angles. Key order and unrelated keys do not
+ * matter. */
 inline std::string rope_identity(const std::vector& k,
                                  const std::vector& v) {
     auto names_rotary = [](const std::string& key) {
diff --git a/core/format/safetensors.cpp b/core/format/safetensors.cpp
index ea8b8c9b..e83b8775 100644
--- a/core/format/safetensors.cpp
+++ b/core/format/safetensors.cpp
@@ -1,9 +1,6 @@
-/* safetensors.cpp -- the reader, and the small JSON scanner it needs.
- *
- * The scanner is not a general JSON parser and does not try to be. safetensors headers are one
- * flat object of objects with three known keys, so a scanner that understands strings, arrays of
- * integers and nested braces is sufficient and is auditable in one sitting. Anything it does not
- * understand is an error naming the byte offset, never a guess.
+/* safetensors.cpp -- the reader and its small JSON scanner. Not a general JSON parser: the header
+ * is one flat object of objects with three known keys, so strings, integer arrays and nested braces
+ * suffice. Anything else is an error naming the byte offset.
  */
 #include "safetensors.h"
 
@@ -33,8 +30,8 @@ struct Scan {
         return false;
     }
 
-    /* A JSON string with the escapes that actually occur in these files. \u is decoded to UTF-8
-     * because a tensor name is a key we will compare against. */
+    /* A JSON string with the escapes that occur in these files; \u is decoded to UTF-8 because
+     * tensor names are compared. */
     bool str(std::string* out, const char* base) {
         ws();
         if (p >= end || *p != '"') return fail("expected a string", base);
@@ -57,14 +54,10 @@ struct Scan {
                     char hex[5] = { p[0], p[1], p[2], p[3], 0 };
                     unsigned cp = (unsigned)std::strtoul(hex, nullptr, 16);
                     p += 4;
-                    /* A SURROGATE PAIR IS ONE CODEPOINT, AND ENCODING THE HALVES SEPARATELY IS
-                     * NOT UTF-8. JSON has no way to write a codepoint above U+FFFF except as a
-                     * \uD800-\uDBFF \uDC00-\uDFFF pair, and emitting three bytes for each half
-                     * produces CESU-8: it round-trips through this reader but compares unequal to
-                     * the same name written directly, which is what a tensor name is compared for.
-                     * The halves are joined here; an unpaired surrogate is left to the default
-                     * three-byte path rather than rejected, because a name is data to be matched
-                     * and not text to be validated. */
+                    /* Join a surrogate pair (\uD800-\uDBFF \uDC00-\uDFFF) into one codepoint;
+                     * encoding the halves separately is CESU-8, which compares unequal to the same
+                     * name in UTF-8. An unpaired surrogate takes the three-byte path rather than
+                     * being rejected: names are matched, not validated. */
                     if (cp >= 0xD800 && cp < 0xDC00 && end - p >= 6 && p[0] == '\\' &&
                         p[1] == 'u') {
                         char lo_hex[5] = { p[2], p[3], p[4], p[5], 0 };
@@ -108,7 +101,7 @@ struct Scan {
         return true;
     }
 
-    /* Skip one value of any type, so an unknown key inside a tensor object is survivable. */
+    /* Skip one value of any type, so unknown keys in a tensor object are tolerated. */
     bool skip(const char* base) {
         ws();
         if (p >= end) return fail("truncated", base);
@@ -129,7 +122,7 @@ struct Scan {
     }
 };
 
-/* safetensors names its dtypes; we name ours. The table is the only place the two meet. */
+/* safetensors dtype names to RAD dtypes. */
 uint32_t st_dtype(const std::string& s) {
     if (s == "BF16") return RAD_BF16;
     if (s == "F16")  return RAD_F16;
@@ -143,8 +136,7 @@ uint32_t st_dtype(const std::string& s) {
     if (s == "BOOL") return RAD_BOOL;
     if (s == "F8_E4M3") return RAD_F8E4M3;
     if (s == "F8_E5M2") return RAD_F8E5M2;
-    /* F64 and F8_E8M0 have no RAD_ equivalent. Reported by name at use rather than mapped to
-     * something close, because "close" here is a silently wrong number. */
+    /* F64 and F8_E8M0 have no RAD_ equivalent; refused by name at use rather than approximated. */
     return RAD_DT_INVALID;
 }
 
@@ -274,13 +266,10 @@ int SafeTensorsFile::open(const std::string& path) {
         t.bytes  = (uint64_t)(off_end - off_begin);
         t.data   = data_base + t.offset;
 
-        /* THE SHAPE HAS TO DESCRIBE THE SPAN. Every reader of a tensor walks it by shape and
-         * dtype -- numel() elements from `data` -- and not by data_offsets, so a shape that
-         * claims more than the span reads the next tensor's bytes, or past the mapping into a
-         * SIGBUS. The extents are bounded before each multiply because they are numbers from
-         * the file, and a product that wraps can come out equal to the span. An empty shape is a
-         * scalar, one element. A dtype this reader does not know is not sized here; every
-         * consumer refuses it by name. */
+        /* The shape must match the span: readers walk numel() elements from `data`, not
+         * data_offsets, so an oversized shape reads the next tensor or past the mapping. Extents
+         * are untrusted, so bound each multiply against wrap. An empty shape is a scalar. Unknown
+         * dtypes are not sized here; consumers refuse them by name. */
         int64_t elems = 1;
         bool    shape_ok = true;
         for (int64_t d : t.shape) if (d < 0) shape_ok = false; else if (d == 0) elems = 0;
diff --git a/core/format/safetensors.h b/core/format/safetensors.h
index f9096264..dd451cf2 100644
--- a/core/format/safetensors.h
+++ b/core/format/safetensors.h
@@ -1,13 +1,8 @@
-/* safetensors.h -- an 8-byte length, a JSON object, and a blob.
+/* safetensors.h -- an 8-byte header length, a JSON object mapping tensor name to {dtype, shape,
+ * data_offsets}, and raw little-endian bytes. A small fixed-shape parser rather than a dependency,
+ * since the converter must run wherever a checkpoint lands.
  *
- * Written rather than depended on. The whole format is a header length, one JSON object mapping
- * tensor name to {dtype, shape, data_offsets}, and raw little-endian bytes; the parser below is
- * two hundred lines and it does not need to be a general JSON parser, because the document's shape
- * is fixed. A dependency here would be a dependency in the converter, which is the one tool that
- * has to run on a machine that has just been handed a checkpoint.
- *
- * mmap, no copy. A 46-shard model is opened one shard at a time, so peak RSS stays bounded
- * regardless of model size.
+ * Shards are mmapped, not copied.
  */
 #pragma once
 #include "../rad_internal.h"
@@ -59,8 +54,8 @@ private:
     std::unordered_map index_;
 };
 
-/* model.safetensors.index.json -> { tensor name: shard filename }. A single-file checkpoint has
- * no index; the caller falls back to opening model.safetensors directly. */
+/* model.safetensors.index.json -> { tensor name: shard filename }. A single-file checkpoint has no
+ * index; the caller then opens model.safetensors. */
 int st_load_index(const std::string& index_path,
                   std::unordered_map* out);
 
diff --git a/core/format/share.cpp b/core/format/share.cpp
index 0250f3b2..48851a7f 100644
--- a/core/format/share.cpp
+++ b/core/format/share.cpp
@@ -16,15 +16,15 @@ int weight_share(const WeightInfo& w, const RadEncoding& enc, uint32_t rank, con
     int64_t R = 0, C = 0;
     rad_enc_view(rank, shape, &R, &C);
 
-    /* THE VIEW THE DECLARATION IS IN: one plane's own extents, or the logical ones for several. A
-     * shard is cut in it, because that is the space the plugin declared its share and its stacked
-     * parts in -- a block-fp8 scale plane's parts are 1/128 of its weight's. */
+    /* The shard is cut in the view the declaration uses: one plane's own extents, or the logical
+     * ones for several planes. That is where the plugin declared its share and stacked parts; a
+     * block-fp8 scale plane's parts are 1/128 of its weight's. */
     const bool single = w.n_sel == 1;
     const bool whole = world <= 1 || w.decl.shard == RAD_SHARD_NONE;
-    /* A RESHAPE: one whole plane of single elements, a byte or more each, declared under another
-     * shape of the same count (decl_weight admits it). Its row-major bytes are the same, so the
-     * entry is seen the way the declaration sees it. A shard of one would be a different cut, and
-     * a sub-byte row pads, so neither is a reshape. */
+    /* A reshape: one whole plane of single elements (a byte or more each) declared under another
+     * shape with the same element count, which decl_weight admits. The row-major bytes are
+     * identical, so the entry takes the declared shape. A shard would be a different cut and a
+     * sub-byte row pads, so neither is a reshape. */
     if (single && whole) {
         const RadEncPlane& p0 = enc.plane[w.sel[0]];
         if (p0.kind == RAD_PLANE_TILED && p0.block[0] == 1 && p0.block[1] == 1 &&
@@ -42,13 +42,11 @@ int weight_share(const WeightInfo& w, const RadEncoding& enc, uint32_t rank, con
     if (whole) {
         view.push_back({ 0, VR, 0, VC });
     } else {
-        /* A sharded weight is a projection matrix in almost every case, and refusing anything
-         * else is better than guessing which dimension a rank owns -- with TWO exceptions that
-         * are not guesses. A rank-1 weight sharded by ROW is a contiguous slice of a vector, one
-         * value per head, and the head count is what the world size divides; in the [1, n] view
-         * that is a column cut. And a weight whose inner dimensions are all 1 is the matrix of its
-         * first and last -- a depthwise conv kernel [C, 1, K] is [C, K] -- so its rows are the
-         * ones the view already has. */
+        /* A sharded weight must be a matrix; anything else is refused rather than guessing which
+         * dimension a rank owns, with two exceptions. A rank-1 weight sharded by ROW is a
+         * contiguous slice of a per-head vector, which is a column cut in the [1, n] view. A
+         * weight whose inner dimensions are all 1 is the matrix of its first and last (a
+         * depthwise conv kernel [C, 1, K] is [C, K]). */
         uint32_t mat = rank;
         for (uint32_t i = 1; i + 1 < rank; ++i)
             if (shape[i] == 1) --mat;
@@ -69,14 +67,14 @@ int weight_share(const WeightInfo& w, const RadEncoding& enc, uint32_t rank, con
                                            (long long)c0, (long long)c1, (long long)VC));
             view.push_back({ 0, VR, c0, c1 });
         } else {
-            /* CONTIGUOUS WITHIN EACH STACKED PART. The weight may be several projections
-             * concatenated along dim 0 -- [gate|up], or the delta net's [q|k|v] -- and a rank owns
-             * a slice of EACH of them, not a contiguous slice of the stack. The parts are THIS
-             * RANK'S rows, so a part is `world` times as many rows in the entry. */
+            /* Contiguous within each stacked part. The weight may be several projections
+             * concatenated along dim 0 ([gate|up], the delta net's [q|k|v]), and a rank owns a
+             * slice of each, not a contiguous slice of the stack. Declared parts are this rank's
+             * rows, so a part has `world` times as many rows in the entry. */
             const int np = w.decl.n_row_parts > 1 ? w.decl.n_row_parts : 1;
             if (w.n_part_spans > 0) {
-                /* PER-PART SPANS: the plugin stated each stacked part's rows in the container
-                 * and this rank's [lo, hi) of it, so the parts need not be equal. */
+                /* Per-part spans: the plugin states each stacked part's rows in the container
+                 * and this rank's [lo, hi) of it, so parts may differ in size. */
                 if (w.n_part_spans != np)
                     return refuse(fmt("%d per-part spans for %d stacked parts", w.n_part_spans, np));
                 int64_t sum = 0, soff = 0;
@@ -142,13 +140,13 @@ int weight_share(const WeightInfo& w, const RadEncoding& enc, uint32_t rank, con
                 if (enc_plane_rect(p, R, C, q.r0, q.r1, q.c0, q.c1, &pq, &m) != RAD_OK)
                     return refuse(m);
             }
-            /* A plane every slice carries whole -- a table, a per-tensor scale -- is the same
-             * rectangle for every stacked part, and is taken once. */
+            /* A plane every slice carries whole (a table, a per-tensor scale) yields the same
+             * rectangle for every stacked part; take it once. */
             if (pq.row0 == last.row0 && pq.rows == last.rows && pq.col0 == last.col0 &&
                 pq.cols == last.cols)
                 continue;
             last = pq;
-            /* A share is copied as bytes, so both of its column ends have to land on one. */
+            /* A share is copied as bytes, so both column ends must fall on a byte boundary. */
             if ((pq.col0 * bits) % 8 || ((pq.col0 + pq.cols) * bits % 8 && pq.col0 + pq.cols != pc))
                 return refuse(fmt("columns [%lld, %lld) of the %s '%s' plane do not fall on whole "
                                   "bytes", (long long)pq.col0, (long long)(pq.col0 + pq.cols),
diff --git a/core/format/share.h b/core/format/share.h
index 53672495..0c69580e 100644
--- a/core/format/share.h
+++ b/core/format/share.h
@@ -1,14 +1,14 @@
 /* share.h -- which bytes of a container entry one rank's declaration takes.
  *
- * A container entry is a logical weight's planes, whole and canonical (rad_format.h). A rank
- * declares a VIEW of it (RadWeightDecl::source/planes) and, under tensor parallelism, only its
- * share: a ROW shard is rows of every selected plane and a COL shard is columns, each cut on the
- * plane's own block boundary and refused where a block would be split (spec §4.3). This is that
- * arithmetic, and nothing else -- the loader turns its rectangles into reads.
+ * A container entry holds a logical weight's planes, whole and canonical (rad_format.h). A rank
+ * declares a view of it (RadWeightDecl::source/planes) and, under tensor parallelism, only its
+ * share: a ROW shard takes rows of every selected plane, a COL shard takes columns. Each cut falls
+ * on the plane's own block boundary and is refused where it would split a block (spec §4.3). This
+ * is only the arithmetic; the loader turns the rectangles into reads.
  *
- * Pure, so a test can hold it to the shapes tensor parallelism actually produces: a stacked
- * [gate|up] whose every part is split, an uneven span, a block-fp8 scale plane cut at 1/128 of
- * its weight's rows, a per-tensor scale every rank carries whole.
+ * Pure, so tests can cover the shapes tensor parallelism produces: a stacked [gate|up] with every
+ * part split, an uneven span, a block-fp8 scale plane cut at 1/128 of its weight's rows, and a
+ * per-tensor scale every rank carries whole.
  */
 #pragma once
 #include "../rad_core.h"
diff --git a/core/format/table_copy.cpp b/core/format/table_copy.cpp
index 6834f077..a549f642 100644
--- a/core/format/table_copy.cpp
+++ b/core/format/table_copy.cpp
@@ -19,9 +19,9 @@ int table_copy_fill(const RadFile& file, const uint8_t* src, int64_t n, int64_t
     if (!why || !src || !buf || n <= 0) return RAD_E_INVAL;
     const int64_t huge = (int64_t)2 << 20;
 
-    /* A reader per hardware thread up to sixteen, each reading its own contiguous span in pieces of
-     * 64 MiB: a drive serves sixteen queued reads at full rate, and the span keeps each reader's
-     * reads sequential on the file. */
+    /* One reader per hardware thread up to 16, each reading its own contiguous span in 64 MiB
+     * pieces: a drive serves 16 queued reads at full rate, and spans keep each reader
+     * sequential. */
     const int nt = (int)std::max(1u, std::min(16u, std::thread::hardware_concurrency()));
     const int64_t piece = (int64_t)64 << 20;
     const int64_t span = ((n + nt - 1) / nt + huge - 1) & ~(huge - 1);
diff --git a/core/format/table_copy.h b/core/format/table_copy.h
index 68f8e345..4b6e968c 100644
--- a/core/format/table_copy.h
+++ b/core/format/table_copy.h
@@ -1,16 +1,13 @@
 /* table_copy.h -- a container table copied into host memory (--ngram-placement ram): locked memory
- * for the host gather, made here, or pinned memory a card reads, which the caller allocates and
- * table_copy_fill fills. What follows is about the locked copy; the read and the check are both's.
+ * for the host gather (made here), or pinned memory a card reads (allocated by the caller, filled
+ * by table_copy_fill). Both share the read and the check.
  *
- * A COPY IN HUGE PAGES, NOT THE MAPPING LOCKED. Faulting a container's mapping in costs a fault every
- * 4 KiB page and leaves every row behind a 4 KiB translation, so a gather of scattered rows walks
- * the page tables on nearly every row; an anonymous MADV_HUGEPAGE region covers thousands of rows a
- * page. The region is locked as each page is first touched (MLOCK_ONFAULT), so nothing filled is
- * swapped out while the rest fills; it is read from the container by parallel positional reads, the
- * container's pages dropped behind them so the table is not held twice; and it is checked against
- * the mapping before anyone is handed it, because a wrong offset would serve every row from the
- * wrong place without an error. A host kernel reads an address no file backs as the memory it is
- * (libavx's table_file), so no plugin takes part. */
+ * The locked copy uses huge pages rather than locking the mapping: the mapping costs a fault per
+ * 4 KiB page and a TLB walk on nearly every scattered row, while a MADV_HUGEPAGE region covers
+ * thousands of rows per page. It is locked on first touch (MLOCK_ONFAULT); filled by parallel
+ * positional reads, dropping the container's pages behind so the table is not held twice; and
+ * checked against the mapping before use, since a wrong offset would silently serve wrong rows.
+ * A host kernel reads an address no file backs as plain memory (libavx's table_file). */
 #pragma once
 #include "radfile.h"
 
@@ -25,17 +22,17 @@ struct TableCopy {
     size_t bytes = 0;       /* the mapping's length: the table rounded up to 2 MiB */
 };
 
-/* Copies [src, src + n) of `file`'s mapping, which lies at file offset `foff`, into a new locked
- * region. RAD_OK with `out` filled, or a refusal with `why` saying what failed and nothing held. */
+/* Copy [src, src + n) of `file`'s mapping (file offset `foff`) into a new locked region. RAD_OK with
+ * `out` filled, or an error with `why` and nothing held. */
 int  table_copy_make(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff,
                      TableCopy* out, std::string* why);
 
-/* The read and the check table_copy_make makes, into [dst, dst + n) the caller allocated: pinned
- * memory a card reads in place, when a device kernel gathers the table (--ngram-placement ram). */
+/* table_copy_make's read and check, into caller-allocated [dst, dst + n): pinned memory a card
+ * reads in place when a device kernel gathers the table. */
 int  table_copy_fill(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff,
                      uint8_t* dst, std::string* why);
 
-/* Unlocks and unmaps it; a copy never made is a no-op. */
+/* Unlock and unmap; a no-op for a copy never made. */
 void table_copy_free(TableCopy* c);
 
 }  /* namespace rad */
diff --git a/core/format/tunecache.cpp b/core/format/tunecache.cpp
index 94baa036..06069234 100644
--- a/core/format/tunecache.cpp
+++ b/core/format/tunecache.cpp
@@ -1,11 +1,13 @@
-/* tunecache.cpp -- read and write the tuning cache. The format is documented in tunecache.h and
- * that comment is the specification; this file must not drift from it.
+/* tunecache.cpp -- read and write the tuning cache. tunecache.h's format description is the
+ * specification.
  */
 #include "tunecache.h"
 
 #include 
 #include 
 #include 
+#include 
+#include 
 #include 
 #include 
 #include 
@@ -15,8 +17,7 @@
 namespace rad {
 
 namespace {
-/* Whitespace only. See the note at its caller: rad_util.cpp's split_ws also splits on commas,
- * which is right for a constraint set and wrong for every line of this file. */
+/* Split on spaces and tabs only; split_ws also splits on commas (see the caller). */
 std::vector split_ws_only(std::string_view s) {
     std::vector out;
     size_t i = 0;
@@ -49,17 +50,15 @@ std::string TuneCache::now_iso8601() {
 }
 
 std::string TuneCache::canon_geometry(const Geometry& g) {
-    /* Sorted by key so the same shape spells the same however the plugin ordered its params.
-     * Geometry::str() is for humans and preserves declaration order; this one is a key. */
+    /* Sorted by key, so the spelling is independent of parameter order (unlike Geometry::str()). */
     std::vector kv;
     const RadParam* p = g.params();
     for (int i = 0; i < g.n_params(); ++i) {
         if (p[i].kind == RAD_P_STR)
             kv.push_back(fmt("%s=%s", p[i].key, p[i].sval ? p[i].sval : ""));
         else if (p[i].kind == RAD_P_F64)
-            /* %.17g so the key round-trips a double exactly. A float parameter is eps or a rope
-             * theta; two shapes that differ only in eps are the same shape to a tuner, but they
-             * are still different keys and a lossy spelling would silently merge them. */
+            /* %.17g round-trips a double exactly, so keys differing only in eps or rope theta
+             * stay distinct. */
             kv.push_back(fmt("%s=%.17g", p[i].key, p[i].dval));
         else
             kv.push_back(fmt("%s=%lld", p[i].key, p[i].ival));
@@ -92,8 +91,7 @@ std::vector> TuneCache::parse_choice(std::string
         if (eq != std::string_view::npos && eq > 0) {
             const std::string key(tok.substr(0, eq));
             const std::string val(tok.substr(eq + 1));
-            /* strtoll rather than stoll: a malformed value is a dropped pair, not an exception on
-             * a path whose whole contract is that a bad cache cannot stop a server. */
+            /* strtoll, not stoll: a malformed value drops the pair instead of throwing. */
             char* end = nullptr;
             const long long v = std::strtoll(val.c_str(), &end, 10);
             if (end && *end == '\0' && !val.empty()) out.emplace_back(key, (int64_t)v);
@@ -133,41 +131,43 @@ int TuneCache::load(const std::string& home, const std::string& machine) {
     const std::string path = path_for(home, machine);
     FILE* f = ::fopen(path.c_str(), "rb");
     if (!f) {
-        /* No cache is the normal state of a fresh install and not a failure: a plugin's first
-         * axis carries its own default, so nothing is broken, only untuned. */
+        /* No cache is normal on a fresh install: every axis has a default. */
         if (errno == ENOENT) return RAD_OK;
         RAD_WARN("%s: %s", path.c_str(), std::strerror(errno));
         return RAD_E_IO;
     }
 
-    char line[4096];
+    /* getline, not a fixed buffer: a row longer than any buffer would otherwise be split, and its
+     * tail read as a row of its own with a truncated geometry. */
+    char* line = nullptr;
+    size_t cap = 0;
+    ssize_t got = 0;
     int lineno = 0, bad = 0;
     bool saw_magic = false;
 
-    while (::fgets(line, sizeof line, f)) {
+    while ((got = ::getline(&line, &cap, f)) >= 0) {
         ++lineno;
-        std::string_view s(line);
+        std::string_view s(line, (size_t)got);
         while (!s.empty() && (s.back() == '\n' || s.back() == '\r')) s.remove_suffix(1);
         if (s.empty() || s[0] == '#') continue;
 
-        /* SPLIT ON WHITESPACE ONLY, NOT ON COMMAS. `split_ws` treats a comma as a separator too --
-         * it is shared with the constraint parser, where "bf16 fp16,fp32" is one set -- and a
-         * tuned choice is comma-separated by construction ("mb=2,npw=4,sk=8"). Splitting on commas
-         * here turns one field into three and shifts `us` onto a timestamp, which parses as zero
-         * and is then dropped as malformed, so every row with more than one axis disappears. It
-         * disappears SILENTLY, because a cache that cannot be read is by design survivable. */
+        /* Split on whitespace only: `split_ws` also splits on commas (for constraint sets), but a
+         * choice is comma-separated ("mb=2,npw=4,sk=8"), and splitting it would shift the fields
+         * and silently drop every multi-axis row. */
         auto tok = split_ws_only(s);
-        /* A line of blanks is a blank line, and every branch below reads tok[0]. */
+        /* A whitespace-only line; every branch below reads tok[0]. */
         if (tok.empty()) continue;
         if (!saw_magic) {
             if (tok.size() != 2 || tok[0] != "radtune") {
                 RAD_WARN("%s:%d: not a rad-tune cache (expected 'radtune 2')", path.c_str(), lineno);
+                std::free(line);
                 ::fclose(f);
                 return RAD_E_FORMAT;
             }
             if (tok[1] != "2") {
                 RAD_WARN("%s: cache format version %.*s, this build reads 2 -- ignoring the cache",
                          path.c_str(), (int)tok[1].size(), tok[1].data());
+                std::free(line);
                 ::fclose(f);
                 return RAD_E_FORMAT;
             }
@@ -188,14 +188,18 @@ int TuneCache::load(const std::string& home, const std::string& machine) {
         r.plugin   = std::string(tok[1]);
         r.choice   = std::string(tok[2]) == "-" ? std::string() : std::string(tok[2]);
         r.us       = std::strtod(std::string(tok[3]).c_str(), nullptr);
-        r.measured = std::string(tok[4]);
+        /* save() writes an empty date as "-", as it does an empty choice. */
+        r.measured = tok[4] == "-" ? std::string() : std::string(tok[4]);
         for (size_t i = 5; i < tok.size(); ++i) {
             if (i > 5) r.geom += ' ';
             r.geom.append(tok[i]);
         }
-        if (r.us <= 0.0) { ++bad; continue; }
+        /* Not `r.us <= 0`: that holds for neither nan nor inf, and a row timed as either would
+         * win or lose every comparison. */
+        if (!(r.us > 0.0) || !std::isfinite(r.us)) { ++bad; continue; }
         put(r);
     }
+    std::free(line);
     ::fclose(f);
 
     if (!saw_magic) {
@@ -218,8 +222,7 @@ int TuneCache::save(const std::string& home) const {
         return RAD_E_IO;
     }
 
-    /* Write-then-rename, so an interrupted rad-tune leaves the previous cache intact rather than
-     * a half-file the selector will warn about on every start. */
+    /* Write then rename, so an interrupted rad-tune leaves the previous cache intact. */
     const std::string tmp = path + ".tmp";
     FILE* f = ::fopen(tmp.c_str(), "wb");
     if (!f) { RAD_ERR("%s: %s", tmp.c_str(), std::strerror(errno)); return RAD_E_IO; }
@@ -228,7 +231,7 @@ int TuneCache::save(const std::string& home) const {
     ::fprintf(f, "machine %s\n", machine_.c_str());
     ::fprintf(f, "# kernel plugin choice us measured geometry\n");
 
-    /* Sorted, so the file is stable across runs and a diff shows what actually moved. */
+    /* Sorted, so the file is stable across runs and diffs show real changes. */
     std::vector v;
     v.reserve(rows_.size());
     for (const auto& r : rows_) v.push_back(&r);
diff --git a/core/format/tunecache.h b/core/format/tunecache.h
index 60a69ffc..67b52370 100644
--- a/core/format/tunecache.h
+++ b/core/format/tunecache.h
@@ -1,19 +1,16 @@
-/* tunecache.h -- the ONE tuning cache. rad-tune writes it, the selector reads it at declare.
+/* tunecache.h -- the single tuning cache: rad-tune writes it, the selector reads it at declare.
  *
- * Constraint matching finds a kernel that is CORRECT for a geometry. Within one kernel there are
- * usually many tile configurations and the right one is a property of the shape and the machine
- * (spec §15). This file is the whole of the mechanism, and it is deliberately one file and one
- * format: the alternative is every plugin inventing its own tuning tool and its own file, and the
- * engine being unable to say why a shape is slow.
+ * Constraint matching finds a kernel that is correct for a geometry; within a kernel the best tile
+ * configuration depends on the shape and the machine (spec §15). One cache and one format for all
+ * plugins, so the engine can always say how a shape was tuned.
  *
- * ================================================================= THE FORMAT
+ * ================================================================= the format
  *
  *   $RADIANCE_HOME/tune/.tune
  *
- * One file per machine, because "which machine" is the coarsest key and a cache measured on
- * another card is not a slower answer, it is a wrong one. UTF-8 text, LF-terminated, because a
- * human has to be able to read it, diff it, delete one line of it, and check it into a repo
- * beside a deployment. It is small: one row per (kernel, shape) the declared graph asks for.
+ * One file per machine (a cache from another card is wrong, not just slow). UTF-8 text,
+ * LF-terminated, so it can be read, diffed, edited and versioned. One row per (kernel, shape) the
+ * declared graph asks for.
  *
  *   line 1        `radtune 2`                        magic and format version
  *   line 2        `machine `            must equal the reader's own key
@@ -22,27 +19,23 @@
  *
  *     kernel     RadKernelInfo.name, the entry point. No spaces.
  *     plugin     RadPluginInfo.name that supplied it. No spaces.
- *     choice     the TUNED AXES that won, `key=value` comma separated and sorted by key -- for
- *                example `mb=3,npw=4,sk=8`. `-` for a kernel with nothing to tune. It is a point
- *                in the space RadTunable declares, not a name out of a list: a name would tie the
- *                cache to a spelling the library happens to use this release, and a library is
- *                free to add an axis or widen one between builds. An axis the reader no longer
- *                declares is ignored on lookup; one it declares and the row omits falls back to
- *                that axis`s default, so a cache written before an axis existed still helps.
+ *     choice     the winning tuned axes, `key=value` comma separated, sorted by key (e.g.
+ *                `mb=3,npw=4,sk=8`); `-` for a kernel with nothing to tune. A point in the
+ *                RadTunable space, not a variant name, so libraries may add or widen axes. An axis
+ *                no longer declared is ignored on lookup; a declared axis the row omits takes its
+ *                default.
  *     us         median microseconds per launch, `%.6f`.
- *     measured   ISO-8601 UTC, e.g. `2026-09-04T09:11:02Z`. --debug-graph prints it, because the
- *                age of a measurement -- taken before a driver or library changed underneath it --
- *                answers a large share of the questions a slow shape produces.
- *     geometry   the resolved parameters, `key=value` sorted by key, space separated. Ranges are
- *                ALREADY COLLAPSED to the band's upper bound -- a bucket table row is what was
- *                measured, so a bucket table row is what is keyed.
+ *     measured   ISO-8601 UTC, e.g. `2026-09-04T09:11:02Z`; --debug-graph prints it, since a
+ *                measurement may predate a driver or library change.
+ *     geometry   the resolved parameters, `key=value` sorted by key, space separated, with ranges
+ *                collapsed to the band's upper bound (a bucket table row is what was measured).
  *
- * The lookup key is (kernel, plugin, geometry). Not the op: two kernels can serve one op and they
- * tune independently. A row whose kernel no longer exists is kept on rewrite and
- * ignored on lookup, so downgrading a plugin does not throw away the measurements.
+ * The lookup key is (kernel, plugin, geometry), not the op: kernels serving one op tune
+ * independently. Rows for missing kernels are kept on rewrite and ignored on lookup, so a plugin
+ * downgrade keeps the measurements.
  *
- * A missing file is not an error. Every RadTunable carries its own `deflt`, so an untuned install
- * is fast rather than broken (spec §15), and this cache only ever moves a shape off those defaults.
+ * A missing file is not an error: every RadTunable has its own `deflt` (spec §15), and the cache
+ * only moves shapes off those defaults.
  */
 #pragma once
 #include "../rad_internal.h"
@@ -62,8 +55,8 @@ struct TuneRow {
 
 class TuneCache {
 public:
-    /* Missing file -> RAD_OK with an empty cache. Malformed line -> skipped with a Warn naming
-     * the line number; a cache is an optimisation and a typo in it must not stop a server. */
+    /* Missing file: RAD_OK, empty. Malformed line: skipped with a warning naming it; a bad cache
+     * must not stop a server. */
     int load(const std::string& radiance_home, const std::string& machine);
     int save(const std::string& radiance_home) const;
 
@@ -77,17 +70,15 @@ public:
     const std::vector& rows() const { return rows_; }
     bool empty() const { return rows_.empty(); }
 
-    /* `key=value` sorted by key, space separated. The canonical spelling of a shape; every
-     * component that keys on one must go through here or two of them will disagree. */
+    /* `key=value` sorted by key, space separated: the canonical spelling of a shape. Every
+     * component keying on shapes must use it. */
     static std::string canon_geometry(const Geometry& g);
 
-    /* THE `choice` COLUMN, both directions. One spelling, in one place, because the tuner writes
-     * it and the selector reads it and a disagreement between them is a cache that silently never
-     * hits. `key=value` comma separated, sorted by key. */
+    /* The `choice` column in both directions (`key=value` comma separated, sorted by key), shared
+     * by tuner and selector so the cache always hits. */
     static std::string canon_choice(const std::vector>& c);
-    /* Unparseable pairs are DROPPED, not an error: an axis this reader does not understand is the
-     * forward-compatibility case tunecache.h's header promises, and the caller filters by the keys
-     * its kernel actually declares anyway. */
+    /* Unparseable pairs are dropped, not an error (forward compatibility); the caller filters by
+     * its kernel's declared keys anyway. */
     static std::vector> parse_choice(std::string_view s);
 
     static std::string path_for(const std::string& radiance_home, const std::string& machine);
@@ -104,9 +95,10 @@ private:
     std::unordered_map        index_;
 };
 
-/* The machine half of the key. Derived from the device layer, so it changes when the card does.
- * Lives beside the cache and not inside it, because the cache is pure file I/O and testable
- * without a device. */
+/* The machine half of the key, from the device layer (machine_key.cpp), kept apart so the cache
+ * stays pure file I/O. */
 std::string rad_machine_key();
+/* The key for `n` devices, the first described by `dev` (null when there is none to describe). */
+std::string rad_machine_key_of(int n, const RadDeviceProps* dev);
 
 }  /* namespace rad */
diff --git a/core/gen/driver.cpp b/core/gen/driver.cpp
index 56806fcb..73caf73c 100644
--- a/core/gen/driver.cpp
+++ b/core/gen/driver.cpp
@@ -15,8 +15,8 @@ constexpr int64_t kAlign = 256;
 
 int64_t align_up(int64_t v) { return (v + kAlign - 1) / kAlign * kAlign; }
 
-/* A reference picture's latent tokens at most: its area, a little over for the rounding of its
- * sides to the size multiple. */
+/* Upper bound on a reference picture's latent tokens: its area plus slack for rounding its sides
+ * to the size multiple. */
 int64_t ref_tokens_max(const RadGeneratorDecl& d) {
     const int64_t s2 = d.latent_scale * d.latent_scale;
     return (d.ref_area + s2 - 1) / s2 * 11 / 10 + 64;
@@ -42,8 +42,8 @@ Sizes sizes_of(const Program& prog, int64_t block_size) {
     return z;
 }
 
-/* The regions, in order, and the total. One function for both the allocation and the budget's
- * count of it, so the two cannot disagree. */
+/* Region offsets and sizes, in order, and the total. Shared by the allocation and the VRAM budget
+ * so the two always agree. */
 int64_t carve(const Sizes& z, int64_t pixel_ch, int64_t (*bytes)[2], int n) {
     const int64_t I = 4, H = 2;
     const int64_t rope_rows = std::max(z.P, z.T);
@@ -58,7 +58,7 @@ int64_t carve(const Sizes& z, int64_t pixel_ch, int64_t (*bytes)[2], int n) {
         { 0, (z.R + 2) * I },           /* R_ENCCU */
         { 0, z.P * I },                 /* R_SRC */
         { 0, 3 * rope_rows * I },       /* R_GROPE */
-        { 0, (12 * z.R + 24) * I },     /* R_SEG: offsets, {0, length} and start a segment, {0, tokens} a picture */
+        { 0, (12 * z.R + 24) * I },     /* R_SEG: offsets; per segment a {0, length} pair and a start; per picture a {0, tokens} pair */
         { 0, z.P * I },                 /* R_SLOT */
         { 0, z.PX * pixel_ch * H },     /* R_PX */
         { 0, z.NT * 4 },                /* R_MASK */
@@ -83,26 +83,22 @@ int64_t carve(const Sizes& z, int64_t pixel_ch, int64_t (*bytes)[2], int n) {
 
 }  /* namespace */
 
-int64_t Driver::device_bytes(const Program& prog, const Config& cfg) {
-    (void)cfg;
+int64_t Driver::device_bytes(const Program& prog) {
     if (!prog.is_generator() || prog.kv_groups.size() < 2) return 0;
     const Sizes z = sizes_of(prog, prog.kv_groups[1].block_size);
     int64_t b[R_N][2];
     return carve(z, prog.generator.pixel_channels, b, R_N);
 }
 
-int Driver::init(const Program& prog, const Config& cfg, IKVManager* kv,
-                 const std::vector& ranks) {
-    (void)cfg;
+int Driver::init(const Program& prog, IKVManager* kv, const std::vector& ranks) {
     fini();
     if (!prog.is_generator()) return RAD_E_STATE;
     decl_   = prog.generator;
     fixed_  = prog.gen_str.sigmas;
     kv_     = kv;
     ranks_  = ranks;
-    /* ONE KV GROUP, PAGED: the conditioning's keys and values. A generator with no conditioning
-     * cache, or two, is not a shape this driver stages. Group handles start at 1 -- the program's
-     * group 0 is the null handle -- and the KV manager and a batch both index by handle. */
+    /* Exactly one paged full-attention KV group, holding the conditioning. Group handles start at
+     * 1 (group 0 is the null handle); the KV manager and a batch both index by handle. */
     if (prog.kv_groups.size() != 2 || prog.kv_groups[1].decl.kind != RAD_KV_FULL ||
         prog.kv_groups[1].block_size <= 0) {
         RAD_ERR("image generator: the program declares %zu KV group(s); the driver stages exactly "
@@ -262,12 +258,16 @@ Driver::Job* Driver::job_locked(uint64_t id) {
     return nullptr;
 }
 
-void Driver::release_locked(Job& j) {
+void Driver::release_kv_locked(Job& j) {
     for (int b = 0; b < 2; ++b)
         if (j.cond[b].have_kv) {
             kv_->free_sequence(j.cond[b].seq);
             j.cond[b].have_kv = false;
         }
+}
+
+void Driver::release_locked(Job& j) {
+    release_kv_locked(j);
     for (int32_t l : j.lanes) {
         lanes_[(size_t)l] = Lane{};
         free_lanes_.push_back(l);
@@ -280,14 +280,14 @@ void Driver::fail_locked(Job& j, int status, const std::string& why) {
     j.req->ticket->finish(status, why);
 }
 
-/* IN ORDER, AND A REQUEST THAT DOES NOT FIT STOPS THE ONES BEHIND IT. */
+/* In arrival order; a request that does not fit stops the ones behind it. */
 int Driver::admit_locked() {
     for (auto& jp : jobs_) {
         Job& j = *jp;
         if (j.admitted || j.failed) continue;
         Request& r = *j.req;
         if ((int64_t)free_lanes_.size() < r.n) break;
-        /* The sequences, once: their length is what the KV has to hold. */
+        /* Build the layouts once; their length sizes the KV. */
         if (j.cond[0].lay.rows == 0) {
             j.ref_hw.clear();
             for (const Pixels& p : r.refs)
@@ -329,9 +329,8 @@ int Driver::admit_locked() {
         }
         if (j.failed) continue;
         if (!ok) {
-            /* The KV is short now: give back what this one took and wait. */
-            for (int b = 0; b < 2; ++b)
-                if (j.cond[b].have_kv) { kv_->free_sequence(j.cond[b].seq); j.cond[b].have_kv = false; }
+            /* KV is short: release what this request took and wait. */
+            release_kv_locked(j);
             break;
         }
         j.sigmas = schedule(decl_, fixed_, r.steps, j.tokens);
@@ -346,7 +345,7 @@ int Driver::admit_locked() {
             free_lanes_.pop_back();
             Lane& ln = lanes_[(size_t)l];
             ln = Lane{};
-            ln.job = 0;
+            ln.busy = true;
             ln.job_id = j.id;
             ln.index = i;
             ln.seed = r.seed + (uint64_t)i;
@@ -398,6 +397,16 @@ void Driver::finish_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int ste
         B.n_seq_decode = 0;
         B.n_tok_decode = 0;
         B.max_q_len_prefill = max_q;
+        /* No rotary table and no encoder input; build_cond sets its own. */
+        B.rope_pos = nullptr;
+        B.rope_mixed = 0;
+        B.n_mm_rows = 0;
+        B.mm_rows = nullptr;
+        B.enc_n_patch = 0;
+        B.enc_pixels = nullptr;
+        B.enc_coord = nullptr;
+        B.enc_n_seg = 0;
+        B.enc_cu = nullptr;
         K.group = (rad_kvgroup)kv_group_;
         K.slot_mapping = reg_[R_SLOT].used > 0 ? dptr(ri, R_SLOT) : nullptr;
         K.block_table = dptr(ri, R_BT);
@@ -431,15 +440,14 @@ const RadBatch* Driver::next(int step) {
     pass_ = Pass{};
     dec_bytes_ = 0;
     if (closed_) return nullptr;
-    /* What finished, failed or was given up on since the last pass leaves now: its KV and lanes
-     * go back before anything is admitted. Nothing is in flight -- next() runs between passes. */
+    /* Retire finished, failed and cancelled jobs, returning their KV and lanes before admitting.
+     * Safe because next() runs between passes, with nothing in flight. */
     for (auto it = jobs_.begin(); it != jobs_.end();) {
         Job& j = **it;
-        const bool gone = j.failed || j.req->ticket->cancel.load(std::memory_order_acquire) ||
-                          (j.admitted && j.images_done >= j.req->n);
+        const bool cancelled = j.req->ticket->cancel.load(std::memory_order_acquire);
+        const bool gone = j.failed || cancelled || (j.admitted && j.images_done >= j.req->n);
         if (!gone) { ++it; continue; }
-        if (j.req->ticket->cancel.load(std::memory_order_acquire) && !j.failed &&
-            j.images_done < j.req->n)
+        if (cancelled && !j.failed && j.images_done < j.req->n)
             j.req->ticket->finish(RAD_E_CANCELLED, "the request was cancelled");
         release_locked(j);
         it = jobs_.erase(it);
@@ -449,7 +457,7 @@ const RadBatch* Driver::next(int step) {
     /* 1. A decode an image is owed. */
     for (int32_t l = 0; l < (int32_t)lanes_.size(); ++l) {
         Lane& ln = lanes_[(size_t)l];
-        if (ln.job < 0 || ln.finished) continue;
+        if (!ln.busy || ln.finished) continue;
         if (ln.preview_due) return build_decode(l, true, step);
         if (ln.final_due) return build_decode(l, false, step);
     }
@@ -515,8 +523,8 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) {
     reg_[R_ROPE].used = 3 * T * 4;
     reg_[R_CU].used = 2 * 4;
 
-    /* The pictures, for the conditioning network's encoder: every item's patches in prompt order,
-     * one segment an item, and the prompt rows the encoder's output rows replace. */
+    /* Pictures for the conditioning network's encoder: every item's patches in prompt order, its
+     * segments, and the prompt rows the encoder's output replaces. */
     int64_t n_patch = 0, n_seg = 0, n_mm = 0;
     int32_t max_seg = 0;
     if (br.media) {
@@ -525,8 +533,6 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) {
         int32_t* ecu = hptr(R_ENCCU);
         int64_t total = 0;
         for (const mm::Placed& p : br.media->items) total += p.item->n_patch;
-        std::vector row0;
-        int64_t rows_at = 0;
         ecu[0] = 0;
         std::vector tmp;
         for (const mm::Placed& p : br.media->items) {
@@ -544,24 +550,19 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) {
                 max_seg = std::max(max_seg, (int32_t)(e - a));
                 ++n_seg;
             }
-            row0.push_back(rows_at);
-            rows_at += it.n_rows();
             n_patch += it.n_patch;
         }
         int32_t* mmr = hptr(R_MMROW);
-        for (const mm::RopeLayout::Run& run : br.media->rope.runs) {
-            const int64_t base = row0[(size_t)run.item] + run.row0;
-            (void)base;
+        for (const mm::RopeLayout::Run& run : br.media->rope.runs)
             for (int32_t k = 0; k < run.n; ++k) mmr[n_mm++] = run.tok + k;
-        }
         reg_[R_ENCPIX].used = n_patch * patch_dim_ * 2;
         reg_[R_ENCCRD].used = 4 * total * 4;
         reg_[R_ENCCU].used = (n_seg + 1) * 4;
         reg_[R_MMROW].used = n_mm * 4;
     }
 
-    /* The generator's sequence, which the plugin runs a segment at a time: each segment's rotary
-     * positions as one dense [3, length] block, its own {0, length} and its first row. */
+    /* The generator's sequence, run by the plugin a segment at a time: per segment, its rotary
+     * positions as a dense [3, length] block, a {0, length} cu pair and its first row. */
     std::memcpy(hptr(R_SRC), c.lay.src.data(), (size_t)P * 4);
     const int64_t nsg = (int64_t)c.lay.bidi.size();
     int32_t* grope = hptr(R_GROPE);
@@ -593,8 +594,8 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) {
     hptr(R_USED)[0] = (int32_t)P;
     reg_[R_USED].used = 4;
 
-    /* The pictures again, for the generator's own encoder, and with a mask the picture being
-     * repainted -- only the positive conditioning's pass writes the lanes. */
+    /* Pictures again for the generator's own encoder, plus the inpainting source when masked.
+     * Only the positive conditioning's pass writes the lanes. */
     const int64_t ch = decl_.pixel_channels;
     uint16_t* px = hptr(R_PX);
     std::vector pxh;
@@ -626,13 +627,12 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) {
     /* The conditioning is modulated at t = 0. */
     hptr(R_SIG)[0] = 0.0f;
     reg_[R_SIG].used = 4;
-    /* The host arrays the plugin reads on the host: the segments' kinds, the pixel blocks and the
-     * lanes. Kept here, in the driver, for the life of the pass. */
+    /* Host-side arrays the plugin reads (segment kinds, pixel blocks, lanes), owned by the driver
+     * for the life of the pass. */
     host_bidi_ = c.lay.bidi;
     host_px_ = pxh;
     host_lanes_ = inp ? j.lanes : std::vector{};
-    /* ...and the lanes on the device too: the repainted picture's latent and mask are copied into
-     * each of them by an op. */
+    /* The lanes on the device too: an op copies the inpainting latent and mask into each. */
     if (!host_lanes_.empty()) {
         std::memcpy(hptr(R_LANE), host_lanes_.data(), host_lanes_.size() * 4);
         reg_[R_LANE].used = (int64_t)host_lanes_.size() * 4;
@@ -689,12 +689,11 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) {
 
 const RadBatch* Driver::build_denoise(const std::vector& take, int step) {
     for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
-    /* Two passes over the images: the entries and their rows, then the per-entry arrays. */
+    /* Two passes: collect the entries and their rows, then fill the per-entry arrays. */
     struct E { const Job* j; int32_t lane; int branch; };
     std::vector es;
     for (int32_t l : take) {
-        const Job* j = nullptr;
-        for (auto& jp : jobs_) if (jp->id == lanes_[(size_t)l].job_id) { j = jp.get(); break; }
+        const Job* j = job_locked(lanes_[(size_t)l].job_id);
         if (!j) continue;
         for (int b = 0; b < j->n_branch; ++b) es.push_back({ j, l, b });
     }
@@ -777,15 +776,6 @@ const RadBatch* Driver::build_denoise(const std::vector& take, int step
         RadBatch& B = out_[rr];
         const int ri = (int)rr;
         B.max_ctx_len = max_ctx;
-        B.rope_pos = nullptr;
-        B.rope_mixed = 0;
-        B.n_mm_rows = 0;
-        B.mm_rows = nullptr;
-        B.enc_n_patch = 0;
-        B.enc_pixels = nullptr;
-        B.enc_coord = nullptr;
-        B.enc_n_seg = 0;
-        B.enc_cu = nullptr;
         B.gen = RAD_GEN_PASS_DENOISE;
         kout_[rr].block_table_pitch = pitch;
         kout_[rr].slot_mapping = nullptr;
@@ -808,8 +798,7 @@ const RadBatch* Driver::build_denoise(const std::vector& take, int step
 const RadBatch* Driver::build_decode(int32_t l, bool preview, int step) {
     for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
     const Lane& ln = lanes_[(size_t)l];
-    const Job* j = nullptr;
-    for (auto& jp : jobs_) if (jp->id == ln.job_id) { j = jp.get(); break; }
+    const Job* j = job_locked(ln.job_id);
     if (!j) return nullptr;
     int32_t* cu = hptr(R_CU);
     cu[0] = 0;
@@ -820,15 +809,6 @@ const RadBatch* Driver::build_decode(int32_t l, bool preview, int step) {
     for (size_t rr = 0; rr < ranks_.size(); ++rr) {
         RadBatch& B = out_[rr];
         B.max_ctx_len = 0;
-        B.rope_pos = nullptr;
-        B.rope_mixed = 0;
-        B.n_mm_rows = 0;
-        B.mm_rows = nullptr;
-        B.enc_n_patch = 0;
-        B.enc_pixels = nullptr;
-        B.enc_coord = nullptr;
-        B.enc_n_seg = 0;
-        B.enc_cu = nullptr;
         B.gen = RAD_GEN_PASS_DECODE;
         B.n_kv_groups = 0;
         B.kv = nullptr;
diff --git a/core/gen/driver.h b/core/gen/driver.h
index 13246d1d..c8068a54 100644
--- a/core/gen/driver.h
+++ b/core/gen/driver.h
@@ -1,28 +1,25 @@
-/* driver.h -- the image generator's pass driver (gen.h says what the passes are).
+/* driver.h -- the image generator's pass driver (gen.h describes the passes).
  *
- * ONE THREAD DRIVES IT, the engine's, and it asks two things a pass: `next()` decides what runs
- * and stages it, `done()` folds the result back once every rank has run it. Requests arrive from
- * HTTP threads through `submit()` and leave through their Ticket; the queue is the only thing the
- * two kinds of thread share, behind one mutex.
+ * Driven by the engine thread: `next()` picks and stages a pass, `done()` folds its result back
+ * once every rank has run it. Requests arrive from HTTP threads through `submit()` and leave
+ * through their Ticket; the job queue is the only shared state, behind one mutex.
  *
- * WHAT RUNS NEXT, in this order, one pass at a time:
+ * Pass priority, one pass at a time:
  *
- *   1. a DECODE an image is owed -- a finished image, or a preview its last step marked. First,
+ *   1. DECODE an image is owed: a finished image, or a preview its last step marked. Goes first
  *      because a finished image frees its lane and answers its caller, and a preview must be read
- *      before the lane's next step writes the preview latent again.
- *   2. a COND an admitted request is owed: its conditioning, so its images can join the next
- *      denoise pass.
- *   3. a DENOISE over as many images in flight as fit the step's rows, oldest request first, each
+ *      before the lane's next step overwrites the preview latent.
+ *   2. COND an admitted request is owed, so its images can join the next denoise pass.
+ *   3. DENOISE over as many in-flight images as fit the step's rows, oldest request first, each
  *      at its own step.
  *
- * A request is ADMITTED when it can get lanes for every image and KV for every conditioning
- * sequence; until then it waits, in order -- a request that does not fit blocks the ones behind
- * it, so a large request is not starved by a stream of small ones.
+ * A request is admitted once it can get lanes for every image and KV for every conditioning
+ * sequence. Admission is in order: a request that does not fit blocks those behind it, so a large
+ * request is not starved by a stream of small ones.
  *
- * THE STAGING is one region per rank on its card and one pinned host region with the same layout.
- * Every pass is synchronised before the next is built (Engine::gen_loop), so one host region is
- * enough: an image pass is tens of milliseconds and more, and the host work between two is
- * microseconds.
+ * Staging is one device region per rank plus one pinned host region with the same layout. Every
+ * pass is synchronised before the next is built (Engine::gen_loop), so one host region suffices:
+ * a pass takes tens of milliseconds, the host work between passes microseconds.
  */
 #pragma once
 #include "gen.h"
@@ -42,21 +39,20 @@ public:
     };
 
     /* `kv` is rank 0's KV manager: one block table serves every rank. */
-    int  init(const Program& prog, const Config& cfg, IKVManager* kv, const std::vector& ranks);
+    int  init(const Program& prog, IKVManager* kv, const std::vector& ranks);
     void fini();
     ~Driver() { fini(); }
 
     /* The bytes init() allocates on each rank's card, for the VRAM budget. */
-    static int64_t device_bytes(const Program& prog, const Config& cfg);
+    static int64_t device_bytes(const Program& prog);
 
     /* ---------------------------------------------------------- HTTP threads */
-    /* Queue a request. Refused at once -- with `why` -- when it can never run: a size past the
+    /* Queue a request. Refused at once, with `why`, when it can never run: a size past the
      * largest image, more pictures than the model takes, a conditioning longer than a pass. */
     int  submit(std::unique_ptr r, std::string* why);
-    /* What a request may ask for: the model's own limits, for the server to check before it does
-     * the expensive part of preparing one. */
+    /* The model's limits, for the server to check before the expensive part of preparing a
+     * request. */
     const RadGeneratorDecl&    decl() const { return decl_; }
-    const std::vector& fixed_sigmas() const { return fixed_; }
     int64_t max_cond_tokens() const { return max_tok_; }
     /* Fail every request queued or in flight, and refuse new ones. */
     void shutdown(const char* why, int status);
@@ -66,8 +62,8 @@ public:
      * `step` is the engine's pass counter, carried into RadBatch::step. */
     const RadBatch* next(int step);
     const RadBatch* batch_for(int rank) const;
-    /* The bytes of the generator's image buffer the pass just staged makes, 0 for a pass that
-     * makes none: the engine copies them to `host()` behind the pass. */
+    /* Bytes of image output the staged pass produces, 0 if none; the engine copies them to
+     * host_image() behind the pass. */
     int64_t decode_bytes() const { return dec_bytes_; }
     void*   host_image() const { return img_host_; }
     /* The pass has run on every rank and its streams are drained. */
@@ -101,7 +97,7 @@ private:
         bool     failed = false;
     };
     struct Lane {
-        int64_t  job = -1;          /* index into jobs_ by id; -1 free */
+        bool     busy = false;      /* held by request job_id */
         uint64_t job_id = 0;
         int32_t  index = 0;
         int32_t  step = 0;
@@ -112,7 +108,7 @@ private:
         bool     final_due = false;
         bool     finished = false;
     };
-    /* What the pass being run is, for done(). */
+    /* The pass in flight, for done(). */
     struct Pass {
         int      kind = 0;
         uint64_t job = 0;
@@ -138,6 +134,7 @@ private:
     void finish_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int step);
 
     int  admit_locked();
+    void release_kv_locked(Job& j);
     void release_locked(Job& j);
     void fail_locked(Job& j, int status, const std::string& why);
     Job* job_locked(uint64_t id);
@@ -168,7 +165,7 @@ private:
     std::vector     gout_;
     std::vector kout_;
     Pass                         pass_;
-    /* The host arrays a COND pass's plugin reads on the host (RadGenBatch's _h fields). */
+    /* Host arrays a COND pass's plugin reads on the host (RadGenBatch's _h fields). */
     std::vector         host_bidi_, host_px_, host_lanes_;
 
     mutable std::mutex           mu_;
diff --git a/core/gen/gen.cpp b/core/gen/gen.cpp
index 6215d304..8116f29f 100644
--- a/core/gen/gen.cpp
+++ b/core/gen/gen.cpp
@@ -29,11 +29,6 @@ void Ticket::finish(int status, const std::string& why) {
     cv_.notify_all();
 }
 
-void Ticket::step(int32_t done, int32_t total) {
-    (void)done;
-    (void)total;
-}
-
 bool Ticket::next(Image* out, int ms, bool* timed_out) {
     std::unique_lock lk(mu_);
     if (timed_out) *timed_out = false;
@@ -65,8 +60,8 @@ std::string Ticket::why() const {
 
 /* ================================================================== the schedule */
 /* diffusers' FlowMatchEulerDiscreteScheduler.set_timesteps with explicit sigmas, as the pipeline
- * calls it, in the precision it runs at: the sigmas are an f32 array and every shift is numpy f32
- * arithmetic, the Python floats in it (exp(mu), the shift, the terminal) taking the array's type. */
+ * calls it and at its precision: the sigmas are f32 and every shift is numpy f32 arithmetic, with
+ * the Python scalars (exp(mu), the shift, the terminal) taking the array's type. */
 std::vector schedule(const RadGeneratorDecl& d, const std::vector& fixed,
                             int32_t steps, int64_t tokens) {
     std::vector s;
diff --git a/core/gen/gen.h b/core/gen/gen.h
index cdb3f309..9a7d2980 100644
--- a/core/gen/gen.h
+++ b/core/gen/gen.h
@@ -1,25 +1,23 @@
-/* gen.h -- image generation: what a request is, what comes back, and the driver that turns one
+/* gen.h -- image generation: the request, what comes back, and the driver that turns a request
  * into the passes an image generator declares (rad_declare_generator, abi/rad_builder.h).
  *
- * A GENERATOR IS NOT DRIVEN BY TOKEN STEPS. Its work is three kinds of pass -- conditioning,
- * denoising, decoding -- and an image is tens of denoising passes over thousands of latent rows,
- * every one of them read whole, none of them sampled. The scheduler that serves text owns token
- * positions, prefix reuse, preemption and speculation, and none of that has a meaning here, so the
- * generator gets a driver of its own (this file) and shares everything below the step with the rest
- * of the engine: the ranks, the plugin's step function, the KV manager the conditioning lives in.
+ * A generator is not driven by token steps: an image is tens of denoising passes over thousands of
+ * latent rows, all read whole, none sampled. Token positions, prefix reuse, preemption and
+ * speculation have no meaning here, so the generator has its own driver and shares only what lies
+ * below the step: the ranks, the plugin's step function and the KV manager holding conditioning.
  *
- * THE PASSES, as the driver runs them:
+ * Passes, as the driver runs them:
  *
- *   COND     once for every conditioning sequence a request has -- its prompt, and with guidance
- *            its negative prompt -- the prompt (and its reference pictures) encoded into the
- *            generator's KV group. A request is admitted once its lanes and its KV are free.
- *   DENOISE  one step for each image in flight that fits the pass, any mix of requests, sizes and
- *            step counts: each image carries its own sigma. With guidance an image is two entries,
- *            its positive and its negative conditioning, which the plugin combines.
+ *   COND     once per conditioning sequence (the prompt, plus the negative prompt with guidance):
+ *            the prompt and its reference pictures encoded into the generator's KV group. A
+ *            request is admitted once its lanes and its KV are free.
+ *   DENOISE  one step for each in-flight image that fits the pass, any mix of requests, sizes and
+ *            step counts; each image carries its own sigma. With guidance an image is two entries,
+ *            positive and negative conditioning, which the plugin combines.
  *   DECODE   one image's latent to pixels, read back and handed to its request.
  *
- * A request's images run in LANES -- the plugin's own latent state, `max_lanes` of them -- so one
- * request of n images takes n lanes and shares one conditioning.
+ * Images run in lanes, the plugin's own latent state (`max_lanes` of them): a request of n images
+ * takes n lanes and shares one conditioning.
  */
 #pragma once
 #include "rad_core.h"
@@ -44,15 +42,15 @@ struct Pixels {
     std::vector bf16;
 };
 
-/* ONE CONDITIONING SEQUENCE: the prompt as tokens, with the media it carries placed, and how many
- * of its first tokens the generator does not see (RadGeneratorDecl::drop_prefix). */
+/* One conditioning sequence: the prompt tokens with their media placed, and how many leading
+ * tokens the generator does not see (RadGeneratorDecl::drop_prefix). */
 struct Branch {
     std::vector             tokens;
     std::shared_ptr media;    /* null for a prompt with no pictures */
     int32_t                          n_drop = 0;
 };
 
-/* ONE IMAGE, or one preview of one, on its way back. */
+/* One finished image, or a preview of one. */
 struct Image {
     int32_t              index = 0;     /* which of the request's n */
     int32_t              w = 0, h = 0, ch = 4;
@@ -62,18 +60,17 @@ struct Image {
     uint64_t             seed = 0;
 };
 
-/* THE CHANNEL BACK TO THE CALLER: images as they finish, then the end. The driver's thread writes,
- * the caller's reads; a mutex is enough -- an image is megabytes and there are a handful a
- * request. `cancel` is the caller's, read by the driver at its next pass. */
+/* The channel back to the caller: images as they finish, then the end. The driver thread writes,
+ * the caller reads; a mutex suffices for a handful of megabyte images per request. `cancel` is set
+ * by the caller and read by the driver at its next pass. */
 class Ticket {
 public:
     /* driver side */
     void push(Image&& im);
     void finish(int status, const std::string& why = std::string());
-    void step(int32_t done, int32_t total);
 
     /* caller side: the next image, or false once the request has ended and every image was taken.
-     * Waits at most `ms` milliseconds; `*timed_out` says a false was a timeout, not the end. */
+     * Waits at most `ms` milliseconds; `*timed_out` marks a false that was a timeout, not the end. */
     bool next(Image* out, int ms, bool* timed_out);
     bool finished() const;
     int  status() const;
@@ -81,8 +78,8 @@ public:
 
     std::atomic cancel{false};
 
-    /* What the request cost, for the response: the conditioning's tokens, the latent rows made, and
-     * the time each phase took. Written by the driver before finish(). */
+    /* Usage for the response: conditioning tokens, latent rows made, and per-phase times.
+     * Written by the driver before finish(). */
     int64_t in_tokens = 0, out_tokens = 0;
     int64_t t_submit_ns = 0, t_cond_ns = 0, t_first_step_ns = 0, t_denoised_ns = 0, t_done_ns = 0;
     int32_t steps = 0;
@@ -107,8 +104,8 @@ struct Request {
     int32_t  previews = 0;              /* partial images per image, 0..3 */
     /* The reference pictures' encoder view, one per media item of `pos`, in order. */
     std::vector refs;
-    /* REPAINTING (an edit with a mask): the picture at the size being made, and per latent token
-     * how much of it is repainted (1) and how much kept (0). */
+    /* Inpainting (an edit with a mask): the source picture at the output size, and per latent
+     * token how much is repainted (1) versus kept (0). */
     bool                 inpaint = false;
     Pixels               inp_src;
     std::vector   inp_mask;
@@ -116,16 +113,15 @@ struct Request {
 };
 
 /* ================================================================== the sampler's schedule */
-/* The sigmas a request steps through, n + 1 of them, the last 0: the decl's fixed schedule, or
- * `steps` (0: the default) shifted the way the decl says. `tokens` is the image's latent token
- * count, which a dynamic shift reads. f32, as the reference holds them. */
+/* The n + 1 sigmas a request steps through, the last 0: the decl's fixed schedule, or `steps`
+ * (0: the default) shifted as the decl says. `tokens` is the image's latent token count, read by a
+ * dynamic shift. f32, matching the reference. */
 std::vector schedule(const RadGeneratorDecl& d, const std::vector& fixed,
                             int32_t steps, int64_t tokens);
 
 /* ================================================================== the generator's sequence */
-/* ONE CONDITIONING SEQUENCE AS THE GENERATOR SEES IT (RadGeneratorDecl::layout): which prompt row
- * or reference latent row each of its rows is, its rotary positions, its segments, and where the
- * image being made starts. */
+/* One conditioning sequence as the generator sees it (RadGeneratorDecl::layout): the prompt row or
+ * reference latent row behind each row, rotary positions, segments, and the output image's frame. */
 struct Layout {
     int64_t              rows = 0;
     std::vector src;          /* [rows] */
diff --git a/core/gen_config.cpp b/core/gen_config.cpp
index 5510df2f..aeebd68d 100644
--- a/core/gen_config.cpp
+++ b/core/gen_config.cpp
@@ -1,4 +1,4 @@
-/* gen_config.cpp -- reading a checkpoint's own sampling. The header carries the argument. */
+/* gen_config.cpp -- reading a checkpoint's own sampling; see gen_config.h. */
 #include "gen_config.h"
 
 #include "rad_internal.h"
@@ -13,8 +13,7 @@
 namespace rad {
 namespace {
 
-/* A numeric field, taken only if it lands in range. Out of range is warned about and dropped:
- * the value came with the model, and one implausible entry is not a reason to refuse the rest. */
+/* A numeric field, taken only if in range; otherwise warned about and dropped. */
 void take(const char* what, const char* src, double v, double lo, double hi, bool lo_open,
           float* dst) {
     const bool ok = (lo_open ? v > lo : v >= lo) && v <= hi;
@@ -34,9 +33,10 @@ SamplingParams GenSampling::onto(SamplingParams base) const {
 }
 
 std::string GenSampling::describe(const SamplingParams& sp) {
-    char buf[160];
+    char buf[200];
     std::snprintf(buf, sizeof buf, "temperature %.2f, top_k %d%s, top_p %.2f, min_p %.2f",
-                  (double)sp.temp, sp.top_k, sp.top_k == 0 ? " (off)" : "",
+                  (double)sp.temp, sp.top_k,
+                  sp.top_k == 0 ? " (the 1024 most likely tokens, the sampler's candidate width)" : "",
                   (double)sp.top_p, (double)sp.min_p);
     return buf;
 }
@@ -70,9 +70,8 @@ bool gen_sampling_parse(const std::string& json_text, const char* src, GenSampli
     catch (const std::exception& e) { RAD_WARN("%s: %s; ignoring it", src, e.what()); return false; }
     if (!j.is_object()) { RAD_WARN("%s: not a JSON object; ignoring it", src); return false; }
 
-    /* `do_sample: false` IS THE WHOLE ANSWER when it is there. transformers ignores every other
-     * sampler field under it, and greedy is the one thing this sampler spells as a temperature --
-     * so taking top_k or top_p as well would describe a sampler the checkpoint did not ask for. */
+    /* `do_sample: false` means greedy, and transformers then ignores every other sampler field,
+     * so take nothing else. */
     auto it = j.find("do_sample");
     if (it != j.end() && it->is_boolean() && !it->get()) { out->temp = 0.0f; return true; }
 
@@ -85,8 +84,7 @@ bool gen_sampling_parse(const std::string& json_text, const char* src, GenSampli
     it = j.find("top_k");
     if (it != j.end() && it->is_number_integer()) {
         const int64_t v = it->get();
-        /* -1 is transformers' spelling of "no top_k" and this sampler's is 0; anything below that
-         * is not a count at all. */
+        /* -1 is transformers' "no top_k", this sampler's 0; below -1 is invalid. */
         if (v >= -1) out->top_k = (int)(v < 0 ? 0 : v);
         else RAD_WARN("%s states top_k %lld, which is not a count; ignoring it", src, (long long)v);
     }
@@ -104,9 +102,8 @@ bool gen_sampling_from_file(const std::string& path, bool required, GenSampling*
 }
 
 bool gen_sampling_from_kv(const std::function& get, GenSampling* out) {
-    /* REBUILT AS JSON RATHER THAN PARSED FIELD BY FIELD, so that a value written by rad-convert
-     * and a value read out of the original file go through exactly one set of range checks and
-     * one reading of `do_sample`. Two parsers for one schema is how the two come to disagree. */
+    /* Rebuilt as JSON and passed to gen_sampling_parse, so container metadata and the original
+     * file share one set of range checks and one reading of `do_sample`. */
     nlohmann::json j = nlohmann::json::object();
     static const char* const kFields[] = { "do_sample", "temperature", "top_p", "min_p", "top_k" };
     for (const char* k : kFields) {
diff --git a/core/gen_config.h b/core/gen_config.h
index 67b8d0e7..fa24225b 100644
--- a/core/gen_config.h
+++ b/core/gen_config.h
@@ -1,24 +1,14 @@
-/* gen_config.h -- the sampling a checkpoint states for itself.
+/* gen_config.h -- the sampling a checkpoint states for itself (generation_config.json), read in
+ * its three forms: a file named on the command line, a sidecar beside the container, and the
+ * `generation.*` metadata rad-convert flattened into the container.
  *
- * A checkpoint ships a generation_config.json saying how it expects to be sampled, and serving it
- * at anything else is serving a different model. This is the reader for that file, in the three
- * forms it reaches a running engine: as a file named on the command line, as a file beside the
- * container, and as the `generation.*` metadata rad-convert flattened into the container itself.
+ * These values set what a request sending no sampler fields gets. Without them SamplingParams'
+ * defaults sample the whole vocabulary at temperature 1, and a model tuned with a truncated tail
+ * occasionally draws end-of-turn early: replies stop short, and agent turns arrive with text and
+ * no tool call. A separate component so this can be tested.
  *
- * WHY IT IS ITS OWN COMPONENT. The values decide what every request that sends no sampler fields
- * is served with, and the failure they prevent is silent: SamplingParams' defaults are an
- * untruncated sampler -- temperature 1, top_k off, top_p 1 -- and a model tuned against a
- * truncated tail, sampled with its whole vocabulary live, will now and then draw a token from far
- * down its distribution. End-of-turn is one of those tokens, so the symptom is not prose that
- * reads badly, it is a reply that stops early: an agent turn that carries text and no tool call,
- * which reads from the outside as the server having dropped the request. A defect with no
- * signature of its own is one to hold a test against, and a file-static helper cannot have one.
- *
- * NOTHING HERE REFUSES. These values arrive with the model rather than from a person, and a
- * checkpoint with one implausible entry is still a checkpoint worth serving: a field outside its
- * legal range is warned about and dropped, leaving whatever was underneath it. The command-line
- * overrides are checked in core/config.cpp instead, where the answer can still be "that is not a
- * temperature" before anything starts.
+ * Nothing here refuses: values come with the model, so an out-of-range field is warned about and
+ * dropped. Command-line overrides are checked in core/config.cpp.
  */
 #pragma once
 #include "rad_core.h"
@@ -29,56 +19,42 @@
 
 namespace rad {
 
-/* One config's sampler fields. -1 IS "THIS SOURCE DID NOT SAY" RATHER THAN A VALUE, because every
- * field here has a legal setting that would otherwise be indistinguishable from silence: 0 is a
- * real temperature (greedy), 0 is a real top_k (off) and 0 is a real min_p. A source that cannot
- * say "unset" cannot have another resolved underneath it. */
+/* One config's sampler fields. -1 means "not stated", since 0 is a legal value of each (greedy
+ * temperature, top_k off, min_p off). */
 struct GenSampling {
     float temp = -1.0f, top_p = -1.0f, min_p = -1.0f;
     int   top_k = -1;
 
     bool any() const { return temp >= 0.0f || top_p >= 0.0f || min_p >= 0.0f || top_k >= 0; }
 
-    /* Overlay onto `base`, field by field. A field this did not state leaves base's alone, which
-     * is what lets sources stack: the container underneath, a file over it, a flag over that. */
+    /* Overlay onto `base` field by field; unstated fields keep base's, so sources stack. */
     SamplingParams onto(SamplingParams base) const;
 
-    /* "temperature 0.70, top_k 20 (off), top_p 0.95, min_p 0.00" -- for the line the server logs
-     * about what it settled on. Which sampler a deployment serves decides what its output looks
-     * like, and the untruncated fallback is the one a reader most needs told: it is
-     * indistinguishable from a configured sampler in every other way. */
+    /* "temperature 0.70, top_k 20 (off), top_p 0.95, min_p 0.00", for the startup log line. */
     static std::string describe(const SamplingParams& sp);
 };
 
-/* WHERE EACH OF THE FOUR FIELDS SERVED CAME FROM, for the startup report (core/diag/diag.h): one
- * entry a field no flag set, with the option that would have set it, the value served and why.
- * `stated` is what the source in force read and `src` that source's name ("" for none). A source
- * can state some fields and not others -- a generation_config.json with a temperature and no
- * top_k -- and a field it left out is served SamplingParams' own value, so the reason is per field:
- * one reason for all four would name the file for values that never came from it. */
+/* Where each of the four served fields came from, for the startup report (core/diag/diag.h): one
+ * entry per field no flag set, with its option, the served value and why. `stated` is what the
+ * source in force read and `src` its name ("" for none). Reasons are per field, since a source may
+ * state only some fields and the rest take SamplingParams' defaults. */
 struct GenFieldSource { std::string flag, value, why; };
 std::vector gen_sampling_sources(const GenSampling& stated, const std::string& src,
                                                  const SamplingParams& served, const Config& cfg);
 
-/* Parse the sampler fields out of generation_config.json TEXT. `src` names the origin in any
- * warning. Returns whether anything was taken. Unparseable text warns and takes nothing. */
+/* Parse the sampler fields from generation_config.json text. `src` names the origin in warnings.
+ * Returns whether anything was taken; unparseable text warns and takes nothing. */
 bool gen_sampling_parse(const std::string& json_text, const char* src, GenSampling* out);
 
-/* The same from a file. Absent is not an error unless `required` -- a checkpoint that ships no
- * generation config is served from whatever lies underneath it, not refused. */
+/* The same from a file. Absent is not an error unless `required`. */
 bool gen_sampling_from_file(const std::string& path, bool required, GenSampling* out);
 
-/* The same out of a flat key/value table: the container's `generation.*` metadata, whose values
- * are all strings because that is how rad-convert writes free-form metadata. `get` is handed a
- * bare field name ("top_k") and returns null for a key the table does not hold. */
+/* The same from the container's `generation.*` metadata (string values). `get` takes a bare field
+ * name ("top_k") and returns null when absent. */
 bool gen_sampling_from_kv(const std::function& get, GenSampling* out);
 
-/* `.rad` -> `.generation.json`.
- *
- * THE SIDECAR EXISTS BECAUSE A CONTAINER CANNOT BE EDITED. Metadata lives ahead of the weight
- * data, so adding a key to a converted model means rewriting every byte of it, and a container
- * that carries no `generation.*` metadata reads its sampling from nowhere. A file beside it is
- * the one way to correct such a container without converting the weights a second time. */
+/* `.rad` -> `.generation.json`: a sidecar that supplies or corrects a container's
+ * sampling without reconverting it. */
 std::string gen_sidecar_path(const std::string& model_path);
 
 }  /* namespace rad */
diff --git a/core/hf_model.cpp b/core/hf_model.cpp
index d7f6f787..0fadf0a5 100644
--- a/core/hf_model.cpp
+++ b/core/hf_model.cpp
@@ -1,18 +1,15 @@
 /* hf_model.cpp -- resolve a --model that is a Hugging Face repo id (hf_model.h).
  *
- * The entry point (main.cpp) calls resolve_hf_model() once, between config_parse and the Engine,
- * and the rest of bring-up sees a plain file or directory. The fetching is scripts/hfget.sh (curl
- * and jq, no Python), run as a child process; it is installed to libexec/radiance/ and the build
- * copies it to the same place under the build tree, so it is found beside the binary either way.
+ * main.cpp calls resolve_hf_model() once, between config_parse and the Engine; bring-up then sees
+ * a plain file or directory. Fetching is scripts/hfget.sh (curl and jq), run as a child process
+ * from libexec/radiance/ beside the binary, installed or in the build tree.
  *
- * WHERE IT GOES. Not under $RADIANCE_HOME: that is a ':'-separated search path for plugins, and
- * its default is the install's share/ directory, which a user cannot write. A model is a cache --
- * the XDG cache directory by default, --download-dir (vLLM's name) to put it on another disk.
+ * Downloads go to the XDG cache by default, or --download-dir (vLLM's name), not $RADIANCE_HOME,
+ * which is a plugin search path whose default is not user-writable.
  *
- * A HUB THAT CANNOT BE REACHED DOES NOT STOP A RESTART. hfget.sh exits 3 when it changed nothing
- * on disk (the listing failed, or an update does not fit), and the copy a complete fetch left --
- * marked by the manifest it writes only on success -- is then served with a warning. Any other
- * failure may have left a file half-transferred, so it is not served. */
+ * An unreachable hub does not stop a restart: hfget.sh exits 3 when it changed nothing on disk,
+ * and the copy a complete fetch left (marked by its success manifest) is served with a warning.
+ * Any other failure may leave a partial file, so nothing is served. */
 #include "hf_model.h"
 
 #include "rad_internal.h"
diff --git a/core/kld.cpp b/core/kld.cpp
index ba9f1647..9fa5c8fb 100644
--- a/core/kld.cpp
+++ b/core/kld.cpp
@@ -231,8 +231,8 @@ int Kld::load_corpus(const Config& cfg, const std::shared_ptr& voca
             RAD_ERR("kld: %s line %lld has no \"prompt\" string", corpus_.c_str(), (long long)lineno);
             return RAD_E_FORMAT;
         }
-        /* THE TEXT AS THE SERVER WOULD SEE A RENDERED TEMPLATE: control tokens in it are
-         * themselves, and nothing is added in front. */
+        /* Tokenised as the server tokenises a rendered template: control tokens parsed, nothing
+         * prepended. */
         std::vector ids;
         RAD_TRY(tok.encode(j["prompt"].get(), ids, false, true));
         const int64_t from = j.value("score_from", (int64_t)0);
@@ -253,8 +253,8 @@ int Kld::record_into(const std::string& dir, int64_t n_vocab, const std::string&
     n_vocab_ = n_vocab;
     if (docs_.empty()) return RAD_E_INVAL;
     size_rows();
-    /* A REFERENCE IS NEVER OVERWRITTEN. Everything measured against it would silently change
-     * meaning; a directory with no manifest is a run that died, and is written over. */
+    /* Never overwrite a reference; a directory without a manifest is an interrupted run and is
+     * reused. */
     ::mkdir(dir_.c_str(), 0755);
     struct stat st{};
     if (::stat((dir_ + "/kld.json").c_str(), &st) == 0) {
@@ -380,7 +380,7 @@ int Kld::score(const std::vector& spans, const std::vector& s
     return RAD_OK;
 }
 
-/* THE REFERENCE ROW: log-softmax over the whole vocabulary, in double where it sums. */
+/* The reference row: log-softmax over the whole vocabulary, summed in double. */
 void Kld::record_row(const Job& j, const std::vector& sh, std::vector& f16) {
     float m = -std::numeric_limits::infinity();
     for (const KldShard& s : sh) {
@@ -429,14 +429,14 @@ void Kld::record_row(const Job& j, const std::vector& sh, std::vector<
         io_err_.store(1);
 }
 
-/* THE CANDIDATE ROW against the reference's:
+/* The candidate row against the reference's:
  *
  *   KL(P || Q) = sum_i p_i (log p_i - log q_i)
  *
- * with log q from this model's logits at full f32 precision and log p from the reference: f16
- * for the whole row, then the kKldTop most likely tokens replaced by their exact values. p is
- * renormalised over the row as stored -- the f16 rounding leaves sum p a few 1e-5 off one -- so
- * with S = sum e^{lp} and A = sum e^{lp} (lp - lq), KL = A / S - log S. */
+ * with log q from this model's f32 logits and log p from the reference (f16 for the row, exact for
+ * the kKldTop most likely tokens). p is renormalised over the stored row (f16 rounding leaves
+ * sum p a few 1e-5 off one): with S = sum e^{lp} and A = sum e^{lp} (lp - lq), KL = A / S -
+ * log S. */
 void Kld::score_row(const Job& j, const std::vector& sh, std::vector& f16) {
     float m = -std::numeric_limits::infinity();
     int64_t arg = 0;
diff --git a/core/kld.h b/core/kld.h
index 3be7d3eb..63ad3c02 100644
--- a/core/kld.h
+++ b/core/kld.h
@@ -1,32 +1,28 @@
 /* kld.h -- the KL divergence of this model against a recorded reference, at every scored position
  * of a fixed corpus.
  *
- * TWO RUNS, ONE YARDSTICK. `--kld-record DIR` runs the corpus through the model that defines the
- * answer -- the bf16 checkpoint -- and writes its log-probabilities over the whole vocabulary at
- * every scored position, once. `--kld-ref DIR` runs a candidate over the same tokens and compares
- * its own logits against what DIR holds, row by row, so a candidate costs one prefill of the
- * corpus and the reference is never computed again.
+ * `--kld-record DIR` runs the corpus through the reference model (e.g. the bf16 checkpoint) once
+ * and writes its full-vocabulary log-probabilities at every scored position. `--kld-ref DIR` runs a
+ * candidate over the same tokens and compares its logits row by row, so each candidate costs one
+ * prefill of the corpus.
  *
- * WHAT IS REPORTED is the distribution of the per-position KL(P_ref || Q_candidate): its mean,
- * median, 99th, 99.9th and 99.99th percentiles and maximum, the top-1 agreement (the candidate's
- * argmax is the reference's), and both models' perplexity on the corpus's own next tokens. The
- * tail is the point: a quantised model whose mean KL is small can still be confidently wrong at
- * one position in ten thousand, and that is the position a user sees.
+ * Reported: the distribution of per-position KL(P_ref || Q_candidate) (mean, median, 99th, 99.9th,
+ * 99.99th percentile, max), top-1 agreement, and both models' perplexity on the corpus's next
+ * tokens. The tail matters: a small mean KL can hide confidently wrong positions.
  *
- * THE WHOLE VOCABULARY, NOT A TOP-K. A KL over a truncated support is a lower bound that is
- * tightest where it matters least: a peaked distribution keeps its mass in the top few tokens and
- * a flat one -- the high-KL tail -- does not.
+ * The whole vocabulary, not a top-k: a truncated KL is a lower bound, loosest for flat
+ * distributions, which are the high-KL tail.
  *
- * THE REFERENCE FILES (DIR):
+ * Reference files (DIR):
  *   kld.json     the manifest: the model, the corpus, every document's source, token count, first
- *                scored position and first row. Written LAST, so a run that dies leaves a
- *                directory that no --kld-ref will read.
- *   tokens.i32   every document's tokens, concatenated: a candidate is scored on the tokens the
- *                reference saw, not on a re-tokenisation that could differ.
- *   logp.f16     [rows, n_vocab] log-probabilities, f16. Near log p = 0 an f16 has its finest
- *                resolution, and the tail tokens it rounds coarsely carry almost no mass.
- *   top.bin      [rows, kKldTop] {int32 id, f32 log p}: the most likely tokens exactly, which is
- *                where the KL of a confident position lives and where f16 would cost ~1e-4 nats.
+ *                scored position and first row. Written last, so an interrupted run leaves a
+ *                directory no --kld-ref reads.
+ *   tokens.i32   every document's tokens, concatenated, so the candidate scores the reference's
+ *                tokens rather than a re-tokenisation.
+ *   logp.f16     [rows, n_vocab] log-probabilities, f16: finest near log p = 0, coarse only for
+ *                tail tokens with little mass.
+ *   top.bin      [rows, kKldTop] {int32 id, f32 log p}: the most likely tokens exactly, where a
+ *                confident position's KL lives (f16 would cost ~1e-4 nats).
  *   rows.f32     [rows, 2] the reference's own next-token NLL and entropy.
  *
  * Document d scores positions [score_from, n - 1): the logits at p predict token p + 1, and the
@@ -74,9 +70,8 @@ public:
     int open(const Config& cfg, std::shared_ptr vocab, int64_t n_vocab,
              const std::string& model);
 
-    /* The two halves of open() for documents already tokenised, which is what a test drives:
-     * add_doc() each document, then record_into() creates DIR. score_against() is the ref mode
-     * whole. */
+    /* open() split for already-tokenised documents (tests): add_doc() each, then record_into()
+     * creates DIR; score_against() is the whole ref mode. */
     int add_doc(const std::string& source, const std::vector& ids, int64_t score_from);
     int record_into(const std::string& dir, int64_t n_vocab, const std::string& model);
     int score_against(const std::string& dir, const std::string& out, int64_t n_vocab,
@@ -89,8 +84,8 @@ public:
     int64_t rows_done() const { return done_n_.load(std::memory_order_relaxed); }
 
     /* A step's scored rows. Rows outside a document's scored range are skipped; a row seen twice
-     * -- a document re-prefilled after preemption -- is simply computed again. Blocks until every
-     * row is written (record) or scored (ref): the engine reuses the block at the next step. */
+     * (re-prefill after preemption) is recomputed. Blocks until every row is written or scored,
+     * since the engine reuses the block next step. */
     int score(const std::vector& spans, const std::vector& shards);
 
     /* Record: checks every row was written and writes the manifest. Ref: the report, printed and,
diff --git a/core/main.cpp b/core/main.cpp
index 9d5943ce..4cb6d43a 100644
--- a/core/main.cpp
+++ b/core/main.cpp
@@ -1,5 +1,5 @@
-/* main.cpp -- the entry point. Everything it does is in engine.h's comment; this file only turns
- * a command line into that sequence and a status into an exit code.
+/* main.cpp -- the entry point: turns a command line into engine.h's startup sequence and a status
+ * into an exit code.
  */
 #include "engine.h"
 #include "hf_model.h"
@@ -15,24 +15,23 @@ int main(int argc, char** argv) {
 
     rad::Engine engine(std::move(cfg));
 
-    {
-        /* A startup that stops printing says where it waits (util/stallwatch.h). Two minutes:
-         * the slowest normal step, a container read from a slow disk, logs well inside that. */
-        rad::StallWatch watch("startup", 120000);
-        s = engine.start();
-    }
+    /* A startup that stops logging reports where it waits (util/stallwatch.h). Two minutes
+     * comfortably covers the slowest normal step, such as a container read from a slow disk. The
+     * watch goes on into serve() and ends when the server listens. */
+    auto watch = std::make_unique("startup", 120000);
+    s = engine.start();
+    if (s < 0 || engine.config().debug_graph) watch.reset();
     if (s < 0) {
-        /* start() already said what and why; the report adds what it was running on and what it
-         * had decided by then, which is what a log of a server that never came up is read for. */
+        /* start() logged the error; the report adds the machine and the decisions made so far. */
         engine.print_startup_report(s);
         return 1;
     }
 
     if (engine.config().debug_graph) return engine.dump();
-    s = engine.serve();
+    s = engine.serve(std::move(watch));
     if (s < 0) {
-        /* A refusal between start() and listening (a chat template the defaults cannot render, a
-         * thinking budget the model cannot hold) also ends a server that never came up. */
+        /* serve() can also refuse before listening (e.g. a template default the template
+         * rejects, an unholdable thinking budget). */
         if (!engine.startup_report_printed()) engine.print_startup_report(s);
         return 1;
     }
diff --git a/core/mem/hostarena.cpp b/core/mem/hostarena.cpp
index d6d060fc..6b05eb84 100644
--- a/core/mem/hostarena.cpp
+++ b/core/mem/hostarena.cpp
@@ -11,11 +11,8 @@ int HostArena::open(int64_t slot_bytes, int64_t cap_bytes) {
     close();
     if (slot_bytes <= 0 || cap_bytes < slot_bytes) return RAD_E_INVAL;
     const int64_t n = cap_bytes / slot_bytes;
-    /* PINNED, and the allocation is refused rather than downgraded. A pageable host buffer on
-     * this path does not fail, it just collapses -- an async copy to pageable memory serialises
-     * against the stream and the whole point of moving instead of dropping is gone. Better to
-     * start without the store and say so than to run it at a tenth of the rate it was budgeted
-     * at. */
+    /* Pinned or nothing: an async copy to pageable memory serialises against the stream, so a
+     * pageable fallback would run the store at a fraction of its budgeted rate. */
     base_ = rad_dev_alloc(n * slot_bytes, RAD_MEM_HOST_PINNED);
     if (!base_) return RAD_E_NOMEM;
     slot_bytes_ = slot_bytes;
@@ -36,15 +33,9 @@ void HostArena::close() {
     bits_.clear();
 }
 
-int32_t HostArena::alloc() {
-    int32_t got = 0;
-    return alloc_run(1, &got);
-}
-
-/* THE FIRST FREE RUN AT OR AFTER THE CURSOR, wrapping once. A whole word of used slots is skipped
- * in one compare, so a nearly full arena costs a scan of its bitmap -- a few thousand words at the
- * sizes an operator gives this -- and an arena with room costs nothing. The cursor makes
- * consecutive calls hand out consecutive slots, which is what lets a batch be one copy a run. */
+/* First free run at or after the cursor, wrapping once. A fully used word is skipped in one
+ * compare, so a nearly full arena costs one bitmap scan. The cursor makes consecutive calls hand
+ * out consecutive slots, so a batch transfers as one copy per run. */
 int32_t HostArena::alloc_run(int32_t want, int32_t* got) {
     *got = 0;
     if (want <= 0 || !base_ || full()) return -1;
@@ -73,8 +64,8 @@ int32_t HostArena::alloc_run(int32_t want, int32_t* got) {
 
 void HostArena::free(int32_t slot) {
     if (slot < 0 || slot >= cap_slots_) return;
-    /* A slot that is already free is refused rather than counted twice: the used count is what the
-     * sessions view reports and what `full` answers, and a negative one hides the next leak. */
+    /* A double free is ignored so the used count, which `full` and the sessions view read, stays
+     * correct. */
     if (!is_used(slot)) return;
     bits_[(size_t)(slot >> 6)] &= ~(1ull << (slot & 63));
     --used_;
diff --git a/core/mem/hostarena.h b/core/mem/hostarena.h
index d562ce81..b491dacb 100644
--- a/core/mem/hostarena.h
+++ b/core/mem/hostarena.h
@@ -1,21 +1,17 @@
 /* hostarena.h -- fixed-size slots of pinned host memory.
  *
- * Two stores are built from it: the KV tiers' block arena (core/mem/kvtier.h), where one slot is
- * one cache entry, and the linear-state snapshot store (KVManager::set_checkpoint_store), where
- * one slot is one snapshot. Under tensor parallelism a slot holds EVERY rank's shard of its
- * object, each rank at its own offset, so one slot id -- rank 0's to hand out -- names the object
- * on every rank.
+ * Backs two stores: the KV tiers' block arena (core/mem/kvtier.h, one slot per cache entry) and
+ * the linear-state snapshot store (KVManager::set_checkpoint_store, one slot per snapshot). Under
+ * tensor parallelism a slot holds every rank's shard of its object, each at its own offset, so
+ * one slot id (handed out by rank 0) names the object on every rank.
  *
- * Pinned, because every byte of it is a PCIe transfer endpoint and a pageable one collapses: the
- * driver stages an async copy to pageable memory through its own buffer and, on some paths,
- * synchronises. Slot-allocated at one fixed size rather than malloc'd per object: every object a
- * store holds is the same size for a given model, so a bitmap is the whole allocator.
+ * Pinned, because every byte is a PCIe transfer endpoint: the driver stages async copies to
+ * pageable memory through its own buffer and may synchronise. Every object in a store has the same
+ * size for a given model, so a bitmap is the whole allocator.
  *
- * RUNS, BECAUSE A TRANSFER IS PER RUN. A 4-token block makes a 200K-token conversation fifty
- * thousand entries, and a copy per entry is fifty thousand driver calls on the engine thread --
- * the call rate, not the link, is then what a restore costs. Slots taken together are given
- * consecutive ids wherever the arena has them, so a batch crosses the link as one strided copy
- * a run. */
+ * Transfers are per run: with 4-token blocks a 200K-token conversation is 50K entries, and one
+ * copy per entry makes the driver call rate the cost of a restore. Slots allocated together get
+ * consecutive ids where possible, so a batch crosses the link as one strided copy per run. */
 #pragma once
 #include "rad_core.h"
 
@@ -31,21 +27,20 @@ public:
     void close();
     bool enabled() const { return base_ != nullptr; }
 
+    /* Not thread-safe: the owner serialises every call (IdleTiers under its mutex, the snapshot
+     * store on the engine thread). */
     int64_t slot_bytes() const { return slot_bytes_; }
-    /* Fixed when the arena is opened. Stored rather than counted from the bitmap, because an
-     * HTTP thread reads it for the sessions view while the engine thread allocates and frees. */
-    int64_t capacity()   const { return cap_slots_; }
+    int64_t capacity()   const { return cap_slots_; }   /* fixed at open */
     int64_t used_slots() const { return used_; }
     int64_t cap_bytes()  const { return slot_bytes_ * capacity(); }
     int64_t free_slots() const { return cap_slots_ - used_; }
 
-    /* -1 when the arena is full. The caller evicts and retries; this does not choose victims,
-     * because the policy that would choose them lives with the store's owner and an allocator
-     * that reached into it would give each object two owners. */
+    /* alloc: -1 when full. The caller evicts and retries; victim policy belongs to the store's
+     * owner, not the allocator. */
     bool    full() const { return used_ >= cap_slots_; }
-    int32_t alloc();
-    /* UP TO `want` CONSECUTIVE SLOTS, the first free run at or after the cursor. `*got` is how
-     * many; the caller asks again for the rest. -1 when the arena is full. */
+    int32_t alloc() { int32_t got = 0; return alloc_run(1, &got); }
+    /* Up to `want` consecutive slots: the first free run at or after the cursor. `*got` is the
+     * count; the caller asks again for the rest. -1 when full. */
     int32_t alloc_run(int32_t want, int32_t* got);
     void    free(int32_t slot);
     bool    in_use(int32_t slot) const { return slot >= 0 && slot < cap_slots_ && is_used(slot); }
diff --git a/core/mem/kv.cpp b/core/mem/kv.cpp
index 3e534398..2d2eb0cb 100644
--- a/core/mem/kv.cpp
+++ b/core/mem/kv.cpp
@@ -27,15 +27,14 @@ BundleComparison compare_bundling(const std::vector& bundles) {
     const int64_t lo = *std::min_element(bundles.begin(), bundles.end());
     const int64_t hi = *std::max_element(bundles.begin(), bundles.end());
 
-    /* vLLM's rule, transcribed: the smallest bundle, escaping to the largest when they are within
-     * 1.5x (gpt-oss-20b + eagle is 12 sw + 13 full, and padding to (13,13) beats (12,24)). */
+    /* vLLM's rule: the smallest bundle, or the largest when they are within 1.5x
+     * (gpt-oss-20b + eagle is 12 sw + 13 full, and padding to (13,13) beats (12,24)). */
     c.stock_group_size = (hi * 2 < lo * 3) ? hi : lo;
     c.stock_groups = groups(c.stock_group_size);
     c.stock_slots  = slots(c.stock_group_size);
 
-    /* The least-waste answer under the same scheme: least slots, tie-broken on fewer groups, under
-     * a hard cap of the stock group count -- without the cap, size 1 always wins on padding and
-     * drowns the scheduler in per-group bookkeeping. */
+    /* Least waste under the same scheme: fewest slots, then fewest groups, capped at the stock
+     * group count (without the cap size 1 always wins and multiplies per-group bookkeeping). */
     const int64_t cap = c.stock_groups;
     int64_t best = c.stock_group_size;
     for (int64_t g = 1; g <= hi; ++g) {
@@ -47,7 +46,7 @@ BundleComparison compare_bundling(const std::vector& bundles) {
     c.patched_groups = groups(best);
     c.patched_slots  = slots(best);
 
-    /* Ours. One group per state kind, each with its own pool, so there is nothing to pad up to. */
+    /* Ours: one group per state kind, each with its own pool, so no padding. */
     c.our_groups = (int64_t)bundles.size();
     c.our_slots  = 0; for (int64_t b : bundles) c.our_slots += b;
     return c;
@@ -81,18 +80,8 @@ static const char* kv_kind_name(int k) {
     }
 }
 
-/* THE PLAN AND THE CARVE ARE SEPARATE BECAUSE THE BUDGET IS DECIDED FROM THE PLAN.
- *
- * Every per-group size here -- the page, the per-sequence state, the fixed floor -- is a function
- * of the declaration and the run configuration alone, and NONE of it depends on how many bytes the
- * pool ends up with. That matters because core/mem/vram_budget.cpp has to know what a full KV
- * cache would cost BEFORE the pools are allocated: a share larger than the contexts the cache can
- * address is VRAM that nothing will ever touch, left out of the weight plane for nothing. So the
- * budget resolver plans the groups, asks ceiling() what they could use, and caps the share there.
- * Splitting the function is what makes that one code path instead of two that have to agree.
- *
- * plan_groups() fills plans_ and fixed_; carve() spends a pool against them; configure() is both,
- * which is what the engine calls. */
+/* plan_groups() fills plans_ and fixed_ without a pool; carve() spends a pool against them. See
+ * kv.h for why they are separate. */
 int KVManager::configure(const std::vector& groups, const Config& cfg,
                          Pool& kv_pool) {
     RAD_TRY(plan_groups(groups, cfg));
@@ -100,9 +89,9 @@ int KVManager::configure(const std::vector& groups, const Config& c
 }
 
 int KVManager::plan_groups(const std::vector& groups, const Config& cfg) {
-    /* Only to say it is ignored on a model with no recurrent state: the slots are host memory and
-     * the engine opens them (set_checkpoint_store). The operator's own flag, not the default --
-     * every model without such state would otherwise warn about a flag nobody passed. */
+    /* Kept only to warn that the flag is ignored on a model with no recurrent state (the engine
+     * opens the host slots, see set_checkpoint_store). Only an explicitly passed flag counts, so
+     * the default does not warn. */
     const int64_t budget_ckpts = cfg.given.count("--checkpoint-slots") && cfg.checkpoint_slots > 0
                                      ? cfg.checkpoint_slots : 0;
 
@@ -119,25 +108,18 @@ int KVManager::plan_groups(const std::vector& groups, const Config&
 
     std::vector bundles;
     for (size_t i = 0; i < groups.size(); ++i) {
-        /* HANDLE 0 IS THE NULL GROUP. The builder reserves slot 0 of every handle table so that a
-         * zero handle means "none" (rad_builder.cpp), and every loop there starts at 1. A loop
-         * here that starts at 0 without this case refuses the sentinel by name -- "no layers are
-         * bound to it" -- on every real model.
-         *
-         * The placeholder is PUSHED rather than skipped, because plan() indexes plans_ by the
-         * handle. A default-constructed plan is inert everywhere it is walked: 0 blocks and 0
-         * states give empty free lists, and a sequence holds nothing in it. */
+        /* Handle 0 is the null group: the builder reserves slot 0 of every handle table so a zero
+         * handle means "none" (rad_builder.cpp). A placeholder is pushed rather than skipped,
+         * because plan() indexes plans_ by handle; with 0 blocks and 0 states it is inert. */
         if (i == 0) {
             KVGroupPlan null_plan;
             null_plan.index = 0;
             null_plan.name  = "(none)";
-            /* NOT RAD_KV_FULL, which is what a zero-initialised kind would be: -1 makes both
-             * paged() and stateful() false, so every loop that switches on the kind skips it
-             * instead of taking the paged branch and dividing by a zero block size. */
+            /* Not the default RAD_KV_FULL: -1 makes paged() and stateful() both false, so no loop
+             * takes the paged branch and divides by a zero block size. */
             null_plan.kind  = -1;
             plans_.push_back(std::move(null_plan));
-            /* NOT in `bundles`: that list feeds the layer-bundling comparison report, and a zero
-             * entry would report a group with no layers as the smallest real one. */
+            /* Not in `bundles`, which would report it as the smallest real bundle. */
             continue;
         }
         const KVGroupInfo& g = groups[i];
@@ -148,10 +130,8 @@ int KVManager::plan_groups(const std::vector& groups, const Config&
         p.n_layers = (int64_t)g.layers.size();
 
         if (p.n_layers <= 0) {
-            RAD_ERR("KV group '%s': no layers are bound to it. rad_bind_layer_kv() is what tells "
-                    "the block manager how many state instances a sequence owns; without it the "
-                    "group's page size is a guess and this component does not guess.",
-                    p.name.c_str());
+            RAD_ERR("KV group '%s': no layers are bound to it, so its page size is unknown "
+                    "(rad_bind_layer_kv)", p.name.c_str());
             return RAD_E_INVAL;
         }
         const int64_t elt = rad_dtype_bytes(g.decl.dtype, 1);
@@ -170,8 +150,7 @@ int KVManager::plan_groups(const std::vector& groups, const Config&
                         p.name.c_str());
                 return RAD_E_NOKERNEL;
             }
-            /* One page covers every layer bound to the group. That is where the zero-padding
-             * property lives: there is no uniform page size across groups to round up to. */
+            /* One page covers every layer bound to the group. */
             p.bytes_per_block = g.bytes_per_block > 0
                 ? g.bytes_per_block
                 : p.block_size * g.decl.n_head_kv * g.decl.head_dim * elt * 2 * p.n_layers;
@@ -191,9 +170,7 @@ int KVManager::plan_groups(const std::vector& groups, const Config&
         } else if (p.kind == RAD_KV_LINEAR || p.kind == RAD_KV_CONV) {
             if (p.kind == RAD_KV_CONV) {
                 /* A rolling window of conv_width-1 + n_spec entries, so a speculative rejection is
-                 * a change of read offset rather than a recompute (spec §10). The engine's
-                 * contract is that the kernel pair supports that; the manager's job is to make the
-                 * slot big enough for it. */
+                 * a read-offset change rather than a recompute (spec §10). */
                 p.conv_slots = conv_window_entries(g.decl, cfg.n_spec);
                 if (p.conv_slots <= 0) {
                     RAD_ERR("KV group '%s': conv_width %lld with n_spec %d gives 0 slots",
@@ -208,36 +185,23 @@ int KVManager::plan_groups(const std::vector& groups, const Config&
                     ? g.bytes_per_state
                     : g.decl.n_head_kv * g.decl.state_dim[0] * g.decl.state_dim[1] * elt
                       * p.n_layers;
-                /* SPECULATION HAS NOWHERE TO PUT WHAT IT CANNOT COMMIT YET. A verify step runs
-                 * 1 + n_spec tokens through the recurrence before anyone knows which survive, so
-                 * on a rejection the state has folded in tokens the model never emitted -- fluent
-                 * output that drifts, which nothing would report.
-                 *
-                 * The obvious fix is one state per candidate, which is what the plain reading of
-                 * gdn_recurrent_update's state_index asks for. It is also gigabytes a SEQUENCE on a
-                 * real model, tens of gigabytes at a serving concurrency, which no engine can pay.
-                 * The one libr4d implements instead keeps ONE committed state and, beside it, the
-                 * handful of numbers each token's rank-1 update needs -- its normalised k, its v,
-                 * its decay and its beta. That block is RU_TMAX * (4*head_k + head_v + 8) floats a
-                 * head against head_v * head_k for the state, so it fits inside a second slot; the
-                 * next step replays the accepted prefix onto the anchor out of it and starts from a
-                 * state that carries exactly the tokens that survived.
-                 *
-                 * Two slots a sequence, and the second is scratch the kernel owns. The engine's
-                 * side of the bargain is that both are ZEROED when the slot is handed out (a zero
-                 * factor replays as the identity, which is what the first step after a prefill
-                 * needs) and that state_index is wide enough to name them. */
+                /* Speculation: a verify folds 1 + n_spec tokens into the state before acceptance
+                 * is known (see KVGroupPlan::state_copies). One state per candidate would cost
+                 * gigabytes a sequence. libr4d instead keeps one committed state plus each token's
+                 * rank-1 update factors (normalised k, v, decay, beta): RU_TMAX *
+                 * (4*head_k + head_v + 8) floats a head against head_v * head_k for the state, so
+                 * they fit in a second slot, and the next step replays the accepted prefix from
+                 * them. The engine zeroes both slots when handed out (a zero factor replays as the
+                 * identity) and makes state_index wide enough to name them. */
                 p.state_copies = cfg.n_spec > 0 ? 2 : 1;
             }
             if (p.bytes_per_state <= 0) {
                 RAD_ERR("KV group '%s': per-sequence state computes to 0", p.name.c_str());
                 return RAD_E_INVAL;
             }
-            /* THE SLOT THE KERNELS INDEX, which is the slot this manager has to hand out. The
-             * kernels lay slots out from the state tensor ([n_states, channels, conv_slots] or
-             * [n_states, n_head_kv, state_dim]); this manager lays them out from bytes_per_state,
-             * and clears, saves and restores slots in that layout. Two different sizes make every
-             * one of those touch a neighbouring sequence's state. */
+            /* The kernels lay slots out from the state tensor ([n_states, channels, conv_slots]
+             * or [n_states, n_head_kv, state_dim]); this manager clears, saves and restores them
+             * by bytes_per_state. The two sizes must match or those touch a neighbour's state. */
             const int64_t indexed =
                 (p.kind == RAD_KV_CONV
                      ? p.conv_slots * g.decl.n_head_kv * g.decl.head_dim
@@ -251,17 +215,14 @@ int KVManager::plan_groups(const std::vector& groups, const Config&
                         (long long)p.n_layers);
                 return RAD_E_SHAPE;
             }
-            /* Exactly one slot per concurrent sequence, times whatever the kernel needs beside
-             * it. Not a heuristic: a sequence owns exactly one recurrent state, so max_seqs is
-             * the count of LOGICAL states, full stop. */
+            /* One logical state per concurrent sequence, times the copies the kernel needs. */
             p.n_states = max_seqs_ * p.state_copies;
         } else {
             RAD_ERR("KV group '%s': unknown kind %d", p.name.c_str(), p.kind);
             return RAD_E_INVAL;
         }
-        /* A ZERO GROUP COSTS THIS RANK NOTHING: declared for its position and its block count,
-         * never carved, never read. The validation above still ran on the real sizes, so a zero
-         * group is a real group on every other rank. */
+        /* A zero group costs this rank nothing. Validation above ran on the real sizes, which
+         * other ranks still use. */
         if (g.zero) {
             p.zero = true;
             p.bytes_per_block = 0;
@@ -271,11 +232,11 @@ int KVManager::plan_groups(const std::vector& groups, const Config&
     }
     bundling_ = compare_bundling(bundles);
 
-    /* ---- fixed costs first: they are not negotiable and they are not per-token ---- */
+    /* ---- fixed costs first: they are not per-token ---- */
     checkpoint_bytes_ = 0;
     window_ck_bytes_ = 0;
     for (const auto& p : plans_) if (p.stateful()) checkpoint_bytes_ += p.bytes_per_state;
-    /* AND THE WINDOW BEHIND A CHECKPOINT, after the linear state (see has_window_snapshot). */
+    /* Then the window behind a checkpoint, after the linear state (see has_window_snapshot). */
     bool has_state = false;
     for (const auto& p : plans_) has_state = has_state || p.stateful();
     for (size_t i = 1; i < plans_.size(); ++i) {
@@ -287,21 +248,13 @@ int KVManager::plan_groups(const std::vector& groups, const Config&
     }
     checkpoint_bytes_ += window_ck_bytes_;
 
-    /* EVERY RESERVATION IS PADDED TO RAD_ALIGN_UNIT AND THE BUDGET HAS TO SAY SO. Summing the
-     * fixed costs as raw bytes leaves the paged split free to spend the difference, and the plan
-     * then reports a fit that the last reservation does not get.
-     *
-     * It takes an awkward size to show: a state or checkpoint whose byte count sits just past an
-     * alignment boundary pushes most of a unit of padding into every following reservation, so the
-     * shortfall grows with the slot count while each individual number still looks right.
-     *
-     * Padded per RESERVATION and not once at the end, because that is how the pool spends it: one
-     * align_up per reserve() call, whatever the bytes. */
+    /* The pool pads every reserve() call to RAD_ALIGN_UNIT, so the fixed costs are padded per
+     * reservation too. Raw bytes would let the paged split spend the padding and the last
+     * reservation would not fit. */
     int64_t fixed = 0;
     for (const auto& p : plans_)
         if (p.stateful()) fixed += align_up(p.bytes_per_state * p.n_states, RAD_ALIGN_UNIT);
-    /* And one unit a paged group, for the same reason: a page size that is not a multiple of the
-     * alignment pads too, and the carve below hands the groups everything that is left. */
+    /* And one unit per paged group, whose size need not be a multiple of the alignment. */
     for (const auto& p : plans_) if (p.paged()) fixed += RAD_ALIGN_UNIT;
 
     fixed_ = fixed;
@@ -309,11 +262,7 @@ int KVManager::plan_groups(const std::vector& groups, const Config&
     return RAD_OK;
 }
 
-/* WHAT A FULL CACHE WOULD COST, in bytes, for `ctx` tokens on every one of max_seqs sequences.
- * The paged groups are the only elastic term; a windowed group cannot address past its window and
- * is capped there, which is the same cap carve() applies and for the same reason. Anything above
- * this number is memory the block manager can never hand out, and it is the whole reason
- * plan_groups() is callable on its own: the budget resolver asks this before a pool exists. */
+/* Windowed groups are capped at window_pool_cap, as in carve(). */
 int64_t KVManager::ceiling(int64_t ctx) const {
     if (ctx <= 0) return 0;
     int64_t need = fixed_;
@@ -327,18 +276,10 @@ int64_t KVManager::ceiling(int64_t ctx) const {
     return need;
 }
 
-/* EVERY VECTOR THE CARVE FILLS IS PARALLEL TO plans_, AND THEY ARE NOT FILLED AT THE SAME POINT IN
- * IT. The block state is sized after the split is decided and the backing is taken after that, so
- * a carve that returns part way through leaves a manager whose plan table answers every guard and
- * whose block state is empty behind it. The entry points then index one vector having checked
- * another -- reserve_block is a bounds check against plans_ and a read of free_usable_ -- and the
- * read is out of bounds rather than a refusal.
- *
- * A refused carve is a configuration the operator is told about and the caller aborts on, so the
- * cost of this is not that the engine runs badly afterwards; it is that reaching the abort goes
- * through undefined behaviour, and a tier restoring blocks on the way there is one call away from
- * a segmentation fault instead of a return code. Putting the two back in agreement by emptying
- * both is one place, and it holds for every entry point rather than the ones anybody remembered. */
+/* The vectors parallel to plans_ are filled at different points of the carve, so a partial carve
+ * would leave plans_ passing bounds checks (reserve_block checks plans_, then reads free_usable_)
+ * over empty block state. On failure forget() empties both, so every entry point refuses
+ * instead of reading out of bounds. */
 int KVManager::carve(Pool& kv_pool) {
     const int rc = carve_into(kv_pool);
     if (rc < 0) forget();
@@ -357,19 +298,15 @@ void KVManager::forget() {
 }
 
 int64_t KVManager::paged_split(int64_t budget_bytes, std::vector* blocks) const {
-    /* Not a policy: size the groups to exhaust at the same total token count. Any other split
-     * strands memory in whichever group outlasts the others, and a long-context server would then
-     * run out of full-attention blocks with a window pool still half empty. */
+    /* Size the groups to run out at the same total token count (see configure). */
     std::vector out(plans_.size(), 0);
     int64_t remaining = budget_bytes - fixed_;
-    /* A ZERO GROUP COSTS THIS RANK NOTHING, so it takes no part in the split: it holds the
-     * shared table's block count, which is what the costed groups settle on (here, or under the
-     * cap, on the rank that does hold the cache). */
+    /* Zero groups take no part in the split; they get the shared table's block count, which is
+     * what the costed groups settle on here or, under the cap, on the ranks holding the cache. */
     std::vector open, zeros;
     for (const auto& p : plans_)
         if (p.paged()) (p.zero ? zeros : open).push_back(p.index);
-    /* Every paged group zero: nothing on this rank limits the token count. The cap is what the
-     * ranks that hold the cache carve, and without one there is no figure to report. */
+    /* Every paged group zero: this rank limits nothing, so take the cap, or report unbounded. */
     if (open.empty() && !zeros.empty()) {
         const int64_t tokens = tokens_cap_ > 0 ? tokens_cap_ : kUnboundedTokens;
         if (blocks) {
@@ -386,12 +323,12 @@ int64_t KVManager::paged_split(int64_t budget_bytes, std::vector* block
             cost += (double)plans_[i].bytes_per_block / (double)plans_[i].block_size;
         if (cost <= 0) break;
         tokens = (int64_t)((double)remaining / cost);
-        /* ONE BLOCK TABLE SERVES EVERY RANK (Engine::serve checks it), so a rank with more pool
-         * than its peers carves no more than the least of them. */
+        /* One block table serves every rank (Engine::serve checks it), so no rank carves more
+         * than the least of them. */
         if (tokens_cap_ > 0 && tokens > tokens_cap_) tokens = tokens_cap_;
 
-        /* A windowed group cannot use more than window_blocks per sequence; anything past that
-         * is memory nobody will ever address. Cap it and give the bytes back to the others. */
+        /* A windowed group cannot address past its pool cap; cap it and give the bytes back to
+         * the others. */
         int32_t capped = -1;
         for (int32_t i : open) {
             const auto& p = plans_[i];
@@ -413,14 +350,13 @@ int64_t KVManager::pool_mib_for_tokens(int64_t tokens, int64_t max_mib) const {
     const int64_t MiB = (int64_t)1 << 20;
     if (max_mib <= 0) return -1;
     const auto reaches = [&](int64_t mib) {
-        /* The fixed costs (recurrent state, its alignment) come first on every rank -- a rank
-         * whose only paged group is zero still has to hold them. */
+        /* The fixed costs come first on every rank, even one whose paged groups are all zero. */
         if (mib * MiB < fixed_) return false;
         const int64_t t = paged_split(mib * MiB, nullptr);
         return t == kUnboundedTokens || t >= tokens;
     };
     if (!reaches(max_mib)) return -1;
-    /* reaches(hi) holds throughout; lo is the largest size known to fall short (or 0). */
+    /* Invariant: reaches(hi) holds and reaches(lo) does not. */
     int64_t lo = 0, hi = max_mib;
     if (reaches(lo)) return 0;
     while (hi - lo > 1) {
@@ -438,7 +374,7 @@ int64_t KVManager::zero_blocks(const KVGroupPlan& p, int64_t tokens) const {
 }
 
 int KVManager::carve_into(Pool& kv_pool) {
-    /* The pool is what the resolver derived; nothing here re-decides it. What this does decide is how the groups share it, which is arithmetic, not policy. */
+    /* The pool size is the resolver's; this only splits it between the groups. */
     const int64_t budget_bytes = kv_pool.avail();
     const int64_t fixed        = fixed_;
     pool_base_ = kv_pool.base();
@@ -448,7 +384,7 @@ int KVManager::carve_into(Pool& kv_pool) {
         RAD_ERR("vram_kv does not fit its fixed costs:\n"
                 "  linear/conv state  %10s  (%lld sequences)\n"
                 "  vram_kv            %10s\n"
-                "  SHORT BY           %10s\n"
+                "  short by           %10s\n"
                 "Lower --max-num-seqs, or give the cache more of the card: a smaller "
                 "--gpu-headroom-mib or a larger --host-pool-mib. The engine will not shrink one of "
                 "them for you (spec §6).",
@@ -457,8 +393,7 @@ int KVManager::carve_into(Pool& kv_pool) {
         return RAD_E_NOMEM;
     }
 
-    /* ---- the paged split (paged_split below): every rank's share of it is the same arithmetic,
-     * and under a cap it is the least rank's. ---- */
+    /* ---- the paged split; under a cap, the least rank's ---- */
     std::vector blocks;
     (void)paged_split(budget_bytes, &blocks);
     for (auto& p : plans_) if (p.paged()) p.n_blocks = blocks[p.index];
@@ -481,8 +416,8 @@ int KVManager::carve_into(Pool& kv_pool) {
         }
     }
 
-    /* ---- carve. Every reservation comes from the KV pool and only from the KV pool: the mover
-     * works inside the weight slab and cannot reach this (spec §6). ---- */
+    /* ---- carve. Every reservation comes from the KV pool only; the mover works inside the
+     * weight slab and cannot reach it (spec §6). ---- */
     for (auto& p : plans_) {
         int64_t bytes = p.paged() ? p.n_blocks * p.bytes_per_block
                                   : p.n_states * p.bytes_per_state;
@@ -497,7 +432,7 @@ int KVManager::carve_into(Pool& kv_pool) {
         }
         int64_t off = 0;
         void* ptr = kv_pool.reserve(p.name, bytes, RAD_ALIGN_UNIT, &off);
-        if (!ptr && !kv_pool.accounting_only()) {
+        if (!ptr) {
             RAD_ERR("KV group '%s': %s did not fit the KV pool", p.name.c_str(),
                     humanb(bytes).c_str());
             return RAD_E_NOMEM;
@@ -506,8 +441,7 @@ int KVManager::carve_into(Pool& kv_pool) {
         p.pool_offset = off;
         p.pool_bytes = bytes;
     }
-    /* --checkpoint-slots on a model with no recurrent state buys nothing, and opening zero-byte
-     * slots for it would leave the operator's flag looking honoured. Ignore it and say so. */
+    /* --checkpoint-slots does nothing on a model with no recurrent state; say so. */
     if (ckpts_ > 0 && checkpoint_bytes_ <= 0)
         RAD_WARN("--checkpoint-slots %lld ignored: this model declares no linear-attention state, "
                  "so there is nothing to snapshot", (long long)ckpts_);
@@ -523,14 +457,12 @@ int KVManager::carve_into(Pool& kv_pool) {
         if (p.paged()) {
             refcount_[i].assign((size_t)p.n_blocks, 0);
             cached_[i].assign((size_t)p.n_blocks, 0);
-            /* ASCENDING, WHICH IS ALREADY A MIN-HEAP. A sorted run satisfies the heap property,
-             * so the list starts valid and hands out block 0 first. See the loan block in kv.h
-             * for why the lowest free id is the one to hand out. */
+            /* Ascending order is already a valid min-heap (see the loan block in kv.h). */
             free_blocks_[i].resize((size_t)p.n_blocks);
             for (int64_t b = 0; b < p.n_blocks; ++b) free_blocks_[i][(size_t)b] = (int32_t)b;
         } else {
-            /* Only the LOGICAL slots are allocatable. Copy k of slot s is s + k * n_seq_states
-             * and is never handed out on its own -- it belongs to whoever holds s. */
+            /* Only logical slots are allocatable; copy k of slot s (s + k * n_seq_states) belongs
+             * to whoever holds s. */
             const int64_t n_alloc = p.n_seq_states();
             free_states_[i].resize((size_t)n_alloc);
             for (int64_t s = 0; s < n_alloc; ++s)
@@ -540,15 +472,10 @@ int KVManager::carve_into(Pool& kv_pool) {
 
     /* ---- backing ----
      *
-     * EVERYTHING THE CARVE TOOK IS BACKED BEFORE ANYTHING RUNS, and the paged groups stay backed
-     * for the life of the process: a pool on a device with virtual memory management is exactly
-     * one without it, the same bytes in the same places at the same addresses. The loan moves
-     * which blocks the cache hands out and never what is mapped, so it needs no driver call and
-     * cannot leave an address the free list names with nothing behind it.
-     *
-     * The fixed part -- recurrent state and conv slots -- is never released. It is sized per
-     * sequence rather than per token, so there is no idle fraction of it to give back, and a
-     * state slot cannot be re-created on demand the way a page can. */
+     * Everything carved is backed before anything runs and stays backed for the life of the
+     * process, so an elastic pool behaves exactly like a fixed one. The loan never changes what
+     * is mapped, so every id the free list names has memory behind it. The fixed part (state and
+     * conv slots) is sized per sequence and has no idle fraction to release. */
     if (pool_ && pool_->elastic()) {
         const int64_t used = pool_->used();
         const int rc = pool_->commit(0, used);
@@ -569,16 +496,12 @@ int KVManager::carve_into(Pool& kv_pool) {
         if (!p.paged()) continue;
         live_[i]        = p.n_blocks;
         free_usable_[i] = p.n_blocks;
-        /* THE BUFFER FLOOR IS ONE STEP'S WORTH OF THIS GROUP. A step batches at most max_tok
-         * tokens across every sequence in it, so a buffer this size means a prefill asks the
-         * driver for memory once a chunk at worst and a decode step essentially never. Clamped to
-         * the carve, since a group too small to hold one chunk has no floor to speak of. */
+        /* Buffer floor: one step (max_tok tokens) of this group, so a prefill recalls at most
+         * once a chunk and a decode step almost never. Clamped to the carve. */
         const int64_t chunk = blocks_for(p.index, max_tok_);
         chunk_blocks_[i] = std::min(chunk > 0 ? chunk : 1, p.n_blocks);
-        /* A FEW THOUSAND BUCKETS, whatever the carve. The histogram answers "how high does
-         * anything still hold" for the loan, and a bucket is the resolution of that answer: at
-         * this size the loan stops within a fraction of a percent of the carve of the highest
-         * held block, and the walk that finds it is a few thousand counters. */
+        /* At most 4096 buckets: the loan stops within 1/4096 of the carve above the highest held
+         * block, and finding it walks at most 4096 counters. */
         bucket_blocks_[i] = std::max(1, ceil_div(p.n_blocks, 4096));
         held_hist_[i].assign((size_t)ceil_div(p.n_blocks, bucket_blocks_[i]), 0);
     }
@@ -599,9 +522,7 @@ int KVManager::carve_into(Pool& kv_pool) {
                            humanb(p.bytes_per_state).c_str(),
                            (long long)p.n_states, humanb(p.pool_bytes).c_str());
     }
-    /* WHERE EACH GROUP STARTS, SO A FAULT ADDRESS CAN BE PLACED. A GPU memory fault names an
-     * address and nothing else, and without this the only way to tell "kv_attn layer 7" from
-     * "kv_gdn_state slot 3" is to reconstruct the carve by hand from the sizes above. One line. */
+    /* The pool's address range, so a GPU fault address can be placed in the carve. */
     report_ += fmt("    pool at %p, %s; groups at +%lld..+%lld\n",
                    pool_base_, humanb(pool_ ? pool_->bytes() : 0).c_str(),
                    (long long)(plans_.size() > 1 ? plans_[1].pool_offset : 0),
@@ -618,24 +539,14 @@ const KVGroupPlan* KVManager::plan(int32_t g) const {
 
 /* ------------------------------------------------------------------ free lists */
 
-/* THE LOWEST FREE BLOCK, NOT THE ONE FREED MOST RECENTLY. A stack hands back the id released
- * last, which after a busy period is the high block the loan wants -- so the highest held block
- * never falls and nothing can be lent. A min-heap keeps the held blocks packed at the bottom,
- * which is what leaves the top free to lend.
- *
- * It also makes the live gate free. The smallest free id is below live_ whenever ANY free id is,
- * so a pool with backed free blocks finds one at the top of the heap and never scans for it.
- *
- * Entries whose block is no longer free are skipped rather than removed: reserve_specific_block
- * takes one block out of the middle, and erasing from a heap costs a rebuild. A stale entry is
- * consumed by the one pop that meets it. */
+/* Pops the lowest free block (min-heap; see the loan block in kv.h). Entries whose block is no
+ * longer free are skipped: reserve_specific_block leaves its heap entry behind, since erasing
+ * from a heap needs a rebuild. */
 int KVManager::grab_block(int32_t g, int32_t* out) {
     auto& fl = free_blocks_[(size_t)g];
-    /* AN EMPTY POOL THAT HAS LENT BLOCKS TAKES THEM BACK HERE, on the path that needed the block,
-     * because this is the moment the memory is worth more to the cache than to the slab holding
-     * it. ensure() recalls in one call for the whole request; this is the fallback for the callers
-     * that take one block at a time, and it takes back a buffer's worth so that a sequence built
-     * block by block does not recall per block. */
+    /* No usable block: recall the loan here. ensure() recalls once for a whole request; this
+     * covers callers that take one block at a time, and grow_for takes back a buffer's worth so
+     * they do not recall per block. */
     if (free_usable_[(size_t)g] <= 0) (void)grow_for(g, 1);
     if (free_usable_[(size_t)g] <= 0) return RAD_E_FULL;
     while (!fl.empty()) {
@@ -643,10 +554,8 @@ int KVManager::grab_block(int32_t g, int32_t* out) {
         const int32_t b = fl.back();
         fl.pop_back();
         if (refcount_[(size_t)g][(size_t)b] != 0) continue;    /* stale: taken out of the middle */
-        /* AND NEVER PAST THE LIVE MARK. An id above it addresses a page this pool never mapped,
-         * and the first thing to read it is a kernel -- a GPU memory fault with nothing to say
-         * which block or which group. The count and the heap are two structures and this is the
-         * one place they are required to agree, so it is the one place worth asking. */
+        /* Never past the live mark: blocks above it are lent to the expert slab. A hit here
+         * means free_usable_ and the heap disagree. */
         if (b >= live_[(size_t)g]) {
             RAD_ERR("KV group '%s': the free list offered block %d with the live mark at %lld and "
                     "%lld usable -- the count and the heap have gone out of step",
@@ -684,10 +593,7 @@ void KVManager::add_ref(size_t g, int32_t b) {
     ++rc;
 }
 
-/* The held count per bucket, which is the only thing a loan needs to know: the highest bucket
- * anything still holds is where the loan has to stop. Maintained here rather than scanned on demand
- * because a scan of every refcount is not affordable between steps, and a stale answer would lend
- * a block out from under a live sequence. */
+/* Maintains held_hist_ (see kv.h). */
 void KVManager::note_held(int32_t g, int32_t b, int delta) {
     auto& h = held_hist_[(size_t)g];
     if (h.empty()) return;
@@ -699,10 +605,9 @@ int KVManager::grab_state(int32_t g, int32_t* out) {
     auto& fl = free_states_[(size_t)g];
     if (fl.empty()) return RAD_E_FULL;
     *out = fl.back(); fl.pop_back();
-    /* The slot arrives dirty -- see StateClear in kv.h. Recorded rather than zeroed because this
-     * runs on the scheduler thread and the pool is device memory. EVERY COPY IS CLEARED, not
-     * just the state: the second one holds a kernel's replay scratch, and a zero there is what
-     * makes the first step after a prefill replay nothing (KVGroupPlan::state_copies). */
+    /* The slot arrives dirty (see StateClear). Recorded rather than zeroed, because this runs on
+     * the scheduler thread and the pool is device memory. Every copy is cleared: a zero replay
+     * factor makes the first step after a prefill replay nothing (KVGroupPlan::state_copies). */
     const KVGroupPlan* p = plan(g);
     const int64_t copies = p ? p->state_copies : 1, span = p ? p->n_seq_states() : 0;
     for (int64_t k = 0; k < (copies > 0 ? copies : 1); ++k)
@@ -714,11 +619,8 @@ void KVManager::drop_state(int32_t g, int32_t s) {
     if (s >= 0) free_states_[(size_t)g].push_back(s);
 }
 
-/* WHAT CAN BE HANDED OUT, WHICH IS NOT THE LENGTH OF THE FREE LIST. The list holds every id the
- * carve created; a cache lending the top of its range still has those ids in it and a slab's
- * weights behind them, and a stale entry left by reserve_specific_block is in there too. The
- * counter is the answer to the only question anybody asks -- how many more blocks can this group
- * give out right now -- and it is maintained wherever that number changes. */
+/* Blocks that can be handed out now. Not the free list's length, which also holds lent ids and
+ * stale entries left by reserve_specific_block. */
 int64_t KVManager::free_blocks(int32_t g) const {
     return (g >= 0 && g < (int32_t)free_usable_.size()) ? free_usable_[(size_t)g] : 0;
 }
@@ -727,8 +629,6 @@ int64_t KVManager::held_blocks(int32_t g) const {
     const int64_t held = live_[(size_t)g] - free_usable_[(size_t)g];
     return held > 0 ? held : 0;
 }
-/* THE CARVE, not the backing. This is the number every block id is addressed against and the one
- * the scheduler's capacity arithmetic means; live_blocks() is what has VRAM behind it. */
 int64_t KVManager::total_blocks(int32_t g) const {
     const KVGroupPlan* p = plan(g); return p ? p->n_blocks : 0;
 }
@@ -736,13 +636,7 @@ int64_t KVManager::live_blocks(int32_t g) const {
     return (g >= 0 && g < (int32_t)live_.size()) ? live_[(size_t)g] : 0;
 }
 
-int64_t KVManager::committed_bytes() const { return pool_ ? pool_->committed() : 0; }
-
-/* ONE PREFILL CHUNK, OR THE LARGEST RECENT SHORTFALL. The floor is what a single step can consume
- * -- past it a chunked prefill would recall the loan on every chunk -- and the trend term is what
- * says the last few seconds asked for more than that. `short_peak_` decays in spare_tokens(), so a
- * server that has gone quiet settles back to the floor and lends the difference to the expert
- * plane. */
+/* The larger of one prefill chunk and the recent shortfall peak (see buffer_bytes in kv.h). */
 int64_t KVManager::buf_blocks(size_t i) const {
     if (i >= plans_.size()) return 0;
     const int64_t floor_b = i < chunk_blocks_.size() ? chunk_blocks_[i] : 0;
@@ -757,15 +651,9 @@ int64_t KVManager::buffer_bytes() const {
     return b;
 }
 
-/* WHAT THE GROUP CAN STILL HAND OUT, WHICH IS NOT WHAT IT HAS BELOW THE MARK. A lent block is
- * still carved, still addressed and still the operator's budget -- it is one recall away, and the
- * recall happens on the path that needs it. So every admission decision is made against this
- * number and not against the mark, and a cache that is lending admits exactly what one that is
- * not would.
- *
- * Deciding on the mark instead would be a livelock: a 200K-token prefill asks for its blocks in
- * one call, a cache that had lent everything above its idle size would refuse, and the thing that
- * brings the loan back is demand it just refused. */
+/* Free blocks plus lent ones, which are one recall away. Admission decides against this, not the
+ * live mark, so a lending cache admits what a non-lending one would. Deciding on the mark would
+ * livelock: a large request refused for lack of lent blocks is the demand that recalls them. */
 int64_t KVManager::available_blocks(int32_t g) const {
     const KVGroupPlan* p = plan(g);
     if (!p || !p->paged()) return 0;
@@ -793,10 +681,9 @@ int64_t KVManager::held_top(size_t i) const {
     return 0;
 }
 
-/* Take back enough of the loan that `blocks` more can be handed out. Unbounded: this is a request
- * that has already been admitted, and the alternative to serving it is refusing a request the
- * budget says fits. It takes back the shortfall PLUS the buffer, so a sequence that grows a block
- * at a time does not come back here for every block. */
+/* Takes back enough of the loan that `blocks` more can be handed out, without limit: the request
+ * is already admitted and the budget says it fits. Recalls the shortfall plus the buffer, so a
+ * sequence growing a block at a time does not recall per block. */
 int KVManager::grow_for(int32_t g, int64_t blocks) {
     if (g < 0 || g >= (int32_t)plans_.size()) return RAD_E_INVAL;
     const KVGroupPlan& p = plans_[(size_t)g];
@@ -804,18 +691,15 @@ int KVManager::grow_for(int32_t g, int64_t blocks) {
     const int64_t short_by = blocks - free_usable_[(size_t)g];
     if (short_by <= 0) return RAD_OK;
 
-    /* WHAT WAS ASKED FOR AND WAS NOT THERE, which is the one honest measure of how big the buffer
-     * should have been. Recorded before the recall rounds it up, and never from the recall
-     * itself -- the recall already contains the buffer, so feeding it back would size the buffer
-     * from its own last value. */
+    /* Record the shortfall, not the recall (see short_peak_ in kv.h). */
     if ((size_t)g < short_peak_.size() && short_by > short_peak_[(size_t)g])
         short_peak_[(size_t)g] = short_by;
 
     if (!lendable(g) || loan_ <= 0 || live_[(size_t)g] >= p.n_blocks) return RAD_E_FULL;
     int64_t live = live_[(size_t)g] + short_by + buf_blocks((size_t)g);
     if (live > p.n_blocks) live = p.n_blocks;
-    /* The loan that leaves this group `live` blocks, in the unit every group shares. It can only
-     * shrink: a shortfall in one group is never a reason to lend more of another. */
+    /* The loan, in tokens, that leaves this group `live` blocks. It only shrinks: a shortfall in
+     * one group never lends more of another. */
     int64_t keep = (p.n_blocks - live) * p.block_size;
     if (keep > loan_) keep = loan_;
     if (reclaim_) {
@@ -834,11 +718,8 @@ int KVManager::grow_for(int32_t g, int64_t blocks) {
 int64_t KVManager::spare_tokens() {
     int64_t spare = -1;
     for (size_t i = 0; i < plans_.size(); ++i) {
-        /* THE BURST IS FORGOTTEN A LITTLE ON EVERY PASS. Without a decay the buffer would be the
-         * high-water mark of the whole run, so one 200K admission would pin its own worth of VRAM
-         * for as long as the process lived -- the opposite of the point. An eighth a tick is a
-         * half-life of about half a second and a return to the floor in a few, which is slower
-         * than a burst arrives and faster than a workload changes. */
+        /* Decay the shortfall peak by 1/8 a tick (a half-life of about half a second), so one
+         * large admission does not pin its size of buffer for the life of the process. */
         if (i < short_peak_.size()) short_peak_[i] -= short_peak_[i] / 8;
         if (!lendable(plans_[i].index)) continue;
         const KVGroupPlan& p = plans_[i];
@@ -852,7 +733,7 @@ int64_t KVManager::spare_tokens() {
 
 int KVManager::set_loan(int64_t tokens) {
     if (tokens < 0) tokens = 0;
-    /* CHECKED WHOLE BEFORE ANYTHING MOVES, so a refused loan leaves every group where it was. */
+    /* Check every group before moving any, so a refused loan changes nothing. */
     for (size_t i = 0; i < plans_.size(); ++i) {
         if (!lendable(plans_[i].index)) continue;
         const int64_t live = plans_[i].n_blocks - lent_blocks(i, tokens);
@@ -863,46 +744,36 @@ int KVManager::set_loan(int64_t tokens) {
             return RAD_E_STATE;
         }
     }
+    apply_loan(tokens);
+    return RAD_OK;
+}
+
+void KVManager::apply_loan(int64_t tokens) {
     for (size_t i = 0; i < plans_.size(); ++i) {
         if (!lendable(plans_[i].index)) continue;
         const int64_t live = plans_[i].n_blocks - lent_blocks(i, tokens);
-        /* THE FREE COUNT MOVES WITH THE MARK, NOT THE LIST. Every id the carve created stays in
-         * the heap; what changes is how many of them may be handed out. The ids between the two
-         * marks are all free -- nothing is held above the lower of them -- so the count moves by
-         * exactly the distance. */
+        /* The free count moves with the mark; the heap is unchanged. Every id between the old
+         * and new mark is free, so the count moves by exactly the distance. */
         free_usable_[i] += live - live_[i];
         live_[i] = live;
     }
     loan_ = tokens;
-    return RAD_OK;
 }
 
 int KVManager::follow(const KVManager& leader) {
-    if (leader.loan_ == loan_) return RAD_OK;
-    for (size_t i = 0; i < plans_.size() && i < leader.plans_.size(); ++i) {
-        if (!lendable(plans_[i].index)) continue;
-        const int64_t live = plans_[i].n_blocks - lent_blocks(i, leader.loan_);
-        free_usable_[i] += live - live_[i];
-        live_[i] = live;
-    }
-    loan_ = leader.loan_;
+    if (leader.loan_ != loan_) apply_loan(leader.loan_);
     return RAD_OK;
 }
 int64_t KVManager::free_states(int32_t g) const {
     return (g >= 0 && g < (int32_t)free_states_.size()) ? (int64_t)free_states_[(size_t)g].size() : 0;
 }
 
-/* ONE GROUP'S SHARE OF THE CARD, AND WHAT IS HELD OF IT. Paged and stateful groups are counted by
- * the objects they actually hand out, because those are the only ones whose occupancy is tracked:
- * `pool_bytes` may exceed the product for a group whose pool was rounded up when it was carved,
- * and the rounding is capacity nothing can be allocated from rather than capacity in use. */
+/* Counted by the objects a group hands out, not KVGroupPlan::pool_bytes, which may include
+ * alignment rounding that nothing can be allocated from. */
 int64_t KVManager::pool_bytes(int32_t g) const {
     const KVGroupPlan* p = plan(g);
     if (!p) return 0;
-    /* THE PART THE CACHE KEEPS, because this figure is answering "how much of the card is the KV
-     * cache". A group whose top blocks are lent still addresses them and still reports them in
-     * total_blocks(), but the expert slab is holding weights in them, and the slab reports those
-     * bytes as its own (Mover::flex_used_bytes); counting them here as well would count them twice. */
+    /* Live blocks only: lent ones are reported by the slab (Mover::flex_used_bytes). */
     if (p->paged())    return live_blocks(g) * p->bytes_per_block;
     if (p->stateful()) return p->n_states * p->bytes_per_state;
     return 0;
@@ -919,11 +790,9 @@ int64_t KVManager::pool_bytes_carved(int32_t g) const {
 int64_t KVManager::pool_bytes_used(int32_t g) const {
     const KVGroupPlan* p = plan(g);
     if (!p) return 0;
-    if (p->paged())    return (live_blocks(g) - free_blocks(g)) * p->bytes_per_block;
-    /* IN LOGICAL SLOTS, THEN SCALED. The free list holds only logical slots -- copy k of slot s
-     * belongs to whoever holds s and is never handed out alone -- while n_states counts every
-     * copy, so subtracting one from the other reads a speculating deployment's idle pool as
-     * half full. */
+    if (p->paged())    return held_blocks(g) * p->bytes_per_block;
+    /* Counted in logical slots, then scaled by copies: the free list holds logical slots only,
+     * while n_states counts every copy. */
     if (p->stateful()) {
         const int64_t copies = p->state_copies > 0 ? p->state_copies : 1;
         return (p->n_seq_states() - free_states(g)) * copies * p->bytes_per_state;
@@ -941,8 +810,8 @@ int64_t KVManager::blocks_for(int32_t g, int64_t n_tokens) const {
 
 bool KVManager::can_ever_fit(int64_t n_tokens) const {
     for (const auto& p : plans_) {
-        /* Both kinds NAMED, not "paged or else". The null group at handle 0 is neither, so an
-         * `else` branch that assumed stateful would refuse every sequence: it holds no states. */
+        /* Both kinds are tested explicitly: the null group at handle 0 is neither and holds no
+         * states, so a bare `else` would refuse every sequence. */
         if (p.paged())         { if (blocks_for(p.index, n_tokens) > p.n_blocks) return false; }
         else if (p.stateful()) { if (p.n_states < 1) return false; }
     }
@@ -973,15 +842,7 @@ int KVManager::add_sequence(uint64_t id) {
 }
 
 void KVManager::free_sequence(uint64_t id) {
-    Seq* s = find(id);
-    if (!s) return;
-    for (size_t g = 0; g < plans_.size(); ++g) {
-        for (int32_t b : s->blocks[g]) drop_block((int32_t)g, b);
-        s->blocks[g].clear();
-        if (s->state[g] >= 0) { drop_state((int32_t)g, s->state[g]); s->state[g] = -1; }
-    }
-    seqs_.erase(id);
-    ++seq_frees_;
+    if (preempt(id) == RAD_OK) seqs_.erase(id);
 }
 
 int KVManager::preempt(uint64_t id) {
@@ -992,9 +853,7 @@ int KVManager::preempt(uint64_t id) {
         s->blocks[g].clear();
         s->first_block_pos[g] = 0;
         s->dirty_from[g] = 0;
-        /* The recurrent state goes too. A GDN state that was not snapshotted cannot be resumed,
-         * so a preempted sequence replays from its last checkpoint or from zero -- which is what
-         * "preemption by recompute" means for a linear layer (spec §7.1). */
+        /* The recurrent state goes too (see preempt in kv.h, spec §7.1). */
         if (s->state[g] >= 0) { drop_state((int32_t)g, s->state[g]); s->state[g] = -1; }
     }
     s->n_tokens = 0;
@@ -1003,16 +862,12 @@ int KVManager::preempt(uint64_t id) {
 }
 
 /* ------------------------------------------------------------------ rollback (spec §10) */
-/* The other direction from `ensure`, and deliberately NOT `preempt`. A verify wrote KV for
- * 1 + n_spec positions; the sampler accepted a prefix; the rest must go back to the free list.
- * The sequence keeps its state slots and its window base -- see kv.h for why touching the
- * stateful groups here would be actively wrong. */
+/* Paged groups only; see kv.h. */
 int KVManager::rollback(uint64_t id, int64_t n_tokens) {
     Seq* s = find(id);
     if (!s) return RAD_E_NOTFOUND;
     if (n_tokens < 0) return RAD_E_INVAL;
-    /* Monotone in the other direction is `ensure`'s job. Saying RAD_OK rather than refusing keeps
-     * "every draft token was accepted" -- the good case -- off a special path in the caller. */
+    /* Nothing to free; RAD_OK so "every draft accepted" needs no special path in the caller. */
     if (n_tokens >= s->n_tokens) return RAD_OK;
 
     for (size_t g = 0; g < plans_.size(); ++g) {
@@ -1021,9 +876,8 @@ int KVManager::rollback(uint64_t id, int64_t n_tokens) {
         int64_t first = s->first_block_pos[g] / p.block_size;
         int64_t want  = ceil_div(n_tokens, p.block_size) - first;
         if (want < 0) {
-            /* Below what a WINDOW group still retains, which needs n_spec to exceed the whole
-             * window. Drop everything and rebase rather than index a block table from a negative
-             * offset -- the KV for those positions was recycled and is not coming back. */
+            /* Below what a WINDOW group retains (n_spec larger than the window): that KV is
+             * already recycled, so drop everything and rebase. */
             want = 0;
             s->first_block_pos[g] = (n_tokens / p.block_size) * p.block_size;
             s->dirty_from[g] = 0;
@@ -1066,9 +920,6 @@ int32_t KVManager::state_slot(uint64_t id, int32_t g) const {
     return s->state[(size_t)g];
 }
 
-/* The tiers' restore path. grab_block is private because every ordinary caller reaches a block
- * through a sequence; a restore has none yet -- it has bytes and needs somewhere to put them
- * before the prefix cache re-indexes them and takes the reference. */
 int KVManager::reserve_block(int32_t g, int32_t* out) {
     if (!out) return RAD_E_INVAL;
     *out = -1;
@@ -1092,26 +943,14 @@ int64_t KVManager::reserve_blocks(int32_t g, int64_t n, std::vector* ou
     return got;
 }
 
-/* TAKE ONE PARTICULAR BLOCK, for the tiers' restore under tensor parallelism. Block ids are
- * SHARED ACROSS RANKS -- RadBatch carries one block table and every rank indexes its own shard of
- * the pool with it -- so a restore cannot let each rank pick its own. Rank 0 decides and the
- * others take the same id here.
- *
- * It refuses rather than substituting when the id is not free, because a rank quietly restoring
- * into a different block than its peers is the shape of bug that produces correct-looking output
- * on one card and garbage on another. */
 int KVManager::reserve_specific_block(int32_t g, int32_t b) {
     if (g < 0 || g >= (int32_t)plans_.size() || !plans_[(size_t)g].paged()) return RAD_E_INVAL;
     if (b < 0 || b >= plans_[(size_t)g].n_blocks) return RAD_E_INVAL;
-    /* PAST THE LIVE MARK IS A REFUSAL. A block above live_ is lent to the expert slab, and
-     * restoring into one would overwrite the weights a kernel is reading out of it. Rank 0 chooses
-     * from what it can hand out, so every rank can; a rank that could not is a rank whose loan is
-     * deeper than its peers', and taking that block silently would be the garbled-on-one-card bug
-     * this function already exists to prevent. */
+    /* A block above live_ is lent; restoring into it would overwrite expert weights in use. Rank
+     * 0 picks below its own mark, so a refusal here means this rank's loan is deeper. */
     if (b >= live_[(size_t)g]) return RAD_E_STATE;
     if (refcount_[(size_t)g][(size_t)b] != 0) return RAD_E_STATE;
-    /* The heap entry is LEFT BEHIND rather than erased -- erasing from a heap costs a rebuild,
-     * and grab_block skips an entry whose block is no longer free. */
+    /* The heap entry is left behind; grab_block skips it. */
     refcount_[(size_t)g][(size_t)b] = 1;
     --free_usable_[(size_t)g];
     note_held(g, b, +1);
@@ -1139,10 +978,8 @@ void KVManager::cache_reserved_block(int32_t g, int32_t b) {
     if (!mark) { mark = 1; if (refcount_[(size_t)g][(size_t)b] == 1) ++cache_only_[(size_t)g]; }
 }
 
-/* A MARKED BLOCK'S RELEASE IS THE CACHE'S. The cache holds the only marked reference, and the
- * other callers -- a restore giving back what it reserved -- release blocks the cache was never
- * handed. So the mark goes with the release, and a block a sequence still holds stops counting
- * as the cache's. */
+/* Releasing a marked block releases the cache's reference, so the mark goes with it; other
+ * callers (a restore returning a reservation) release unmarked blocks. */
 void KVManager::release_block(int32_t g, int32_t b) {
     if (g < 0 || g >= (int32_t)refcount_.size()) return;
     if (b < 0 || b >= (int32_t)refcount_[(size_t)g].size()) return;
@@ -1171,21 +1008,21 @@ std::vector KVManager::take_pending_copies() {
 /* ------------------------------------------------------------------ ensure */
 
 int64_t KVManager::window_seq_cap(const KVGroupPlan& p) const {
-    return p.window_blocks + (max_tok_ > 0 ? ceil_div(max_tok_, p.block_size) : 0) + 1;
+    return p.window_blocks + step_blocks(p) + 1;
 }
 
 int64_t KVManager::window_pool_cap(const KVGroupPlan& p) const {
-    return max_seqs_ * p.window_blocks + (max_tok_ > 0 ? ceil_div(max_tok_, p.block_size) : 0) +
-           max_seqs_;
+    return max_seqs_ * (p.window_blocks + 1) + step_blocks(p);
 }
 
-/* SLID PAST THE STEP'S FIRST QUERY, NOT ITS LAST. The query at keep_from reads keys down to
+int64_t KVManager::step_blocks(const KVGroupPlan& p) const {
+    return max_tok_ > 0 ? ceil_div(max_tok_, p.block_size) : 0;
+}
+
+/* Slides from the step's first query, not its last. The query at keep_from reads keys down to
  * keep_from - window + 1, which lies in block keep_from / block - (window_blocks - 1) or later
- * (window_blocks - 1 >= window / block). A target taken from the END of the step --
- * ceil(n_tokens / block) - window_blocks -- is the same block for a decode step and drops the keys
- * every row of a longer prefill chunk still needs. Measured on Gemma 4 (#75: 50 of 60 layers
- * windowed at 1024): a 2185-token prompt rebased the table at 1152, its sliding layers held no KV
- * for positions 0..1151, and every prompt past ~1040 tokens came back as nonsense. */
+ * (window_blocks - 1 >= window / block). A target from the step's end is the same for a decode
+ * step but drops keys the earlier rows of a prefill chunk still need. */
 void KVManager::recycle_window(Seq* s, int64_t keep_from) {
     for (size_t g = 0; g < plans_.size(); ++g) {
         const auto& p = plans_[g];
@@ -1217,14 +1054,13 @@ int KVManager::ensure(uint64_t id, int64_t n_tokens, int64_t keep_from) {
     if (n_tokens <= s->n_tokens) return RAD_OK;
     if (keep_from < 0 || keep_from > s->n_tokens) keep_from = s->n_tokens;
 
-    /* Pass 0: recycle whatever the window has slid past. This only frees, so it cannot fail, and
-     * doing it first means the availability check below sees the memory it releases. */
+    /* Pass 0: recycle what the window has slid past. It only frees, so it cannot fail, and the
+     * check below sees the freed blocks. */
     recycle_window(s, keep_from);
 
-    /* Pass 1: can every group serve this? Check before touching anything, so a group that runs
-     * out does not leave the sequence half-extended and the caller unable to say what it owns. */
+    /* Pass 1: check every group before touching any, so a failure leaves the sequence as it
+     * was. */
     std::vector need(plans_.size(), 0);
-    int64_t cow = 0;
     for (size_t g = 0; g < plans_.size(); ++g) {
         const auto& p = plans_[g];
         if (p.paged()) {
@@ -1232,12 +1068,12 @@ int KVManager::ensure(uint64_t id, int64_t n_tokens, int64_t keep_from) {
             int64_t want  = ceil_div(n_tokens, p.block_size) - first;
             need[g] = want - (int64_t)s->blocks[g].size();
             if (need[g] < 0) need[g] = 0;
-            /* Copy-on-write: the partially filled block is the only one a write can reach, and if
-             * somebody else holds it we must not write through. One extra block, per group. */
+            /* Copy-on-write: the partial block is the only one a write reaches; if it is shared,
+             * it needs one extra block. */
             if (s->n_tokens > 0 && s->n_tokens % p.block_size != 0) {
                 int64_t bi = s->n_tokens / p.block_size - first;
                 if (bi >= 0 && bi < (int64_t)s->blocks[g].size()
-                    && refcount_[g][(size_t)s->blocks[g][(size_t)bi]] > 1) { need[g] += 1; ++cow; }
+                    && refcount_[g][(size_t)s->blocks[g][(size_t)bi]] > 1) need[g] += 1;
             }
             if (need[g] > available_blocks((int32_t)g)) return RAD_E_FULL;
             RAD_TRY(grow_for((int32_t)g, need[g]));
@@ -1245,7 +1081,6 @@ int KVManager::ensure(uint64_t id, int64_t n_tokens, int64_t keep_from) {
             if (free_states_[g].empty()) return RAD_E_FULL;
         }
     }
-    (void)cow;
 
     /* Pass 2: commit. Nothing below can fail. */
     for (size_t g = 0; g < plans_.size(); ++g) {
@@ -1290,9 +1125,7 @@ int KVManager::adopt(uint64_t id, int32_t g, const std::vector& blocks,
     if (!s) return RAD_E_NOTFOUND;
     const KVGroupPlan* p = plan(g);
     if (!p || !p->paged()) return RAD_E_INVAL;
-    /* A partial block is never shared: the next token written into it would corrupt whoever else
-     * holds it, and the copy-on-write that would prevent that is pure cost on a block the cache
-     * cannot serve to anyone else either. Whole blocks only. */
+    /* Whole blocks only (see adopt in kv.h). */
     if (n_tokens % p->block_size != 0) return RAD_E_INVAL;
     if ((int64_t)blocks.size() != n_tokens / p->block_size) return RAD_E_INVAL;
     if (!s->blocks[(size_t)g].empty()) return RAD_E_STATE;
@@ -1314,9 +1147,7 @@ int KVManager::fork(uint64_t parent, uint64_t child) {
     if (seqs_.count(child)) return RAD_E_DUPLICATE;
 
     /* Pass 1: the child needs its own state slot in every stateful group before anything is
-     * shared. A recurrent state is one object and not a chain -- there is no "share the first N
-     * tokens of a GDN state" -- so a fork of a linear-attention model costs a whole slot, and the
-     * caller restores into it from a checkpoint (spec §7.3). */
+     * shared (see fork in kv.h, spec §7.3). */
     for (size_t g = 0; g < plans_.size(); ++g)
         if (plans_[g].stateful() && free_states_[g].empty()) return RAD_E_FULL;
 
@@ -1341,8 +1172,7 @@ int KVManager::fork(uint64_t parent, uint64_t child) {
 int KVManager::make_room(uint64_t id, int64_t n_tokens,
                          const std::vector& victims,
                          std::vector* preempted) {
-    /* If it could not fit an empty pool, preempting the whole server would not help. Fail it here
-     * rather than freeing every other sequence and then deadlocking on it (spec §17). */
+    /* Fail before preempting anyone if even an empty pool cannot hold it (spec §17). */
     if (!can_ever_fit(n_tokens)) {
         RAD_WARN("request %llu wants %lld tokens, which exceeds the whole KV pool. Failing it "
                  "rather than preempting the server for a request that still would not fit.",
@@ -1377,13 +1207,8 @@ int KVManager::make_room(uint64_t id, int64_t n_tokens,
 
 /* ------------------------------------------------------------------ checkpoints */
 
-/* A SLOT IS BACKED WHEN IT IS HANDED OUT, NOT WHEN IT IS CARVED. --checkpoint-slots states how
- * many snapshots the server may hold at once; what it costs the card is how many it is holding.
- *
- * THE CARD REFUSING IS A FULL POOL AND NOT AN ERROR. The slot stays in the free list and the
- * caller sees RAD_E_FULL, which is the answer it already handles -- the retention policy runs and
- * the allocation is retried. Anything else would turn a card that is momentarily busy into a
- * failed request. */
+/* A disabled store counts as none. A full store makes alloc_checkpoint return RAD_E_FULL, which
+ * the caller handles by running its retention policy and retrying. */
 void KVManager::set_checkpoint_store(HostArena* store, int64_t rank_off) {
     ck_store_ = store && store->enabled() ? store : nullptr;
     ck_rank_off_ = rank_off;
@@ -1411,15 +1236,12 @@ void* KVManager::checkpoint_ptr(int32_t slot) const {
     return p ? p + ck_rank_off_ : nullptr;
 }
 
-/* One walk, both directions. Keeping save and restore as a single traversal is deliberate: the
- * blob has no header and no self-description, so the only thing that makes it readable is that
- * exactly one piece of code decides its order. Two functions that agreed today would be two
- * functions that could stop agreeing. */
+/* Save and restore share one traversal because the blob has no header: its layout is defined
+ * only by this walk order. */
 int KVManager::checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t ck_slot,
                                bool save, RadStream s, const std::vector* win) {
-    /* A SLOT NOBODY HOLDS IS NOT ONE TO WRITE. Rank 0 hands the ids out, so a follower checks the
-     * shared store rather than a list of its own. Each refusal says which check it is: a slot the
-     * store gave back is a lifetime fault in whoever handed the id out, and nothing about the copy. */
+    /* The slot must be held in the shared store (rank 0 hands out ids, so followers check the
+     * store). A slot not in use is a lifetime fault in whoever handed out the id. */
     const char* dir = save ? "save into" : "restore from";
     if (!ck_store_) {
         RAD_ERR("checkpoint %s slot %d: this rank has no snapshot store", dir, (int)ck_slot);
@@ -1442,9 +1264,8 @@ int KVManager::checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t
         return RAD_E_INVAL;
     }
 
-    /* ONE PITCHED COPY A GROUP. Within a group the state of one sequence is a row a layer, one
-     * layer_stride apart in the pool and packed end to end in the slot, so a group's whole share
-     * crosses the link as one launch rather than a launch a layer. */
+    /* One pitched copy per group: a sequence's state is one row per layer, layer_stride apart in
+     * the pool and packed in the slot. */
     int64_t off = 0;
     for (size_t g = 0; g < plans_.size(); ++g) {
         const KVGroupPlan& p = plans_[g];
@@ -1463,9 +1284,8 @@ int KVManager::checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t
             return RAD_E_STATE;
         }
         if (off + nbytes * p.n_layers > checkpoint_bytes_) {
-            RAD_ERR("checkpoint slot %d holds %lld bytes a rank and this sequence's linear state "
-                    "needs more than that; the store was sized from the same plans, so the two "
-                    "have gone out of step", (int)ck_slot, (long long)checkpoint_bytes_);
+            RAD_ERR("checkpoint slot %d: the linear state needs more than the slot's %lld bytes "
+                    "a rank", (int)ck_slot, (long long)checkpoint_bytes_);
             return RAD_E_STATE;
         }
         const int cs = save ? rad_memcpy_2d_async(ck + off, nbytes, st, p.layer_stride(), nbytes,
@@ -1481,9 +1301,9 @@ int KVManager::checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t
         off += nbytes * p.n_layers;
     }
 
-    /* THE WINDOW SECTION: window_blocks pages a WINDOW group, page j of the window in slot j, each
-     * page n_layers rows of one layer's block -- one pitched copy a page. `win` names the pages
-     * (window_rows); -1 is a page below position zero and is left alone either way. */
+    /* Window section: window_blocks pages per snapshot group, page j at slot position j, each
+     * n_layers rows of one layer's block, one pitched copy per page. `win` names the pages
+     * (window_rows); -1 is a page below position zero and is skipped. */
     if (window_ck_bytes_ > 0) {
         if (!win) {
             RAD_ERR("checkpoint %s slot %d: this model snapshots its window and no window rows "
@@ -1502,11 +1322,20 @@ int KVManager::checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t
                         dir, (int)ck_slot, (int)g, win->size(), (long long)wi);
                 return RAD_E_STATE;
             }
+            if (off + p.window_blocks * p.bytes_per_block > checkpoint_bytes_) {
+                RAD_ERR("checkpoint slot %d: window group %d needs more than the slot's %lld "
+                        "bytes a rank", (int)ck_slot, (int)g, (long long)checkpoint_bytes_);
+                return RAD_E_STATE;
+            }
             const int64_t lb = p.layer_bytes_per_block();
             for (int64_t j = 0; j < p.window_blocks; ++j) {
                 const int32_t b = (*win)[row0 + (size_t)j];
                 if (b < 0) continue;
-                if (b >= p.n_blocks) return RAD_E_STATE;
+                if (b >= p.n_blocks) {
+                    RAD_ERR("checkpoint %s slot %d: window group %d names block %d of %lld", dir,
+                            (int)ck_slot, (int)g, (int)b, (long long)p.n_blocks);
+                    return RAD_E_STATE;
+                }
                 char* dev = (char*)p.base + (int64_t)b * lb;
                 char* host = ck + off + j * p.bytes_per_block;
                 const int cs = save ? rad_memcpy_2d_async(host, lb, dev, p.layer_stride(), lb,
@@ -1522,7 +1351,6 @@ int KVManager::checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t
             }
             off += p.window_blocks * p.bytes_per_block;
         }
-        if (off > checkpoint_bytes_) return RAD_E_STATE;
     }
     return RAD_OK;
 }
@@ -1587,15 +1415,10 @@ int KVManager::seed_window(uint64_t id, int64_t pos) {
     return RAD_OK;
 }
 
-/* HOW MANY COLUMNS A SEQUENCE'S state_index ROW HAS. One per physical copy would be the obvious
- * answer and it is not the one libr4d wants: its anchor scheme was written against a PAGED state
- * cache, where the page a sequence's state lives in moves by -1, 0 or +1 from step to step, so it
- * names each copy THREE times and picks the column at run time out of a marker it stamped into
- * the scratch. Radiance's linear pool does not page -- a slot is a slot for the life of the
- * sequence -- so the three columns naming a copy all name the SAME slot and the marker steers a
- * read that lands in the same place whatever it says.
- *
- * Three columns a copy, therefore, and column j names copy j * copies / width. */
+/* Columns in a sequence's state_index row: three per copy when speculating. libr4d's anchor
+ * scheme targets a paged state cache where a state's page moves by -1, 0 or +1 per step, so it
+ * names each copy three times and picks a column at run time. Here a slot is fixed for the
+ * sequence's life, so all three name the same slot. Column j names copy j * copies / width. */
 int64_t KVManager::state_index_width(int32_t g) const {
     const KVGroupPlan* p = plan(g);
     if (!p || !p->stateful()) return 0;
@@ -1610,8 +1433,7 @@ int KVManager::state_index_row(uint64_t seq, int32_t g, int32_t* out, int max) c
     const int64_t span = p ? p->n_seq_states() : 0, copies = p ? p->state_copies : 1;
     const int n = (int)(w < (int64_t)max ? w : (int64_t)max);
     for (int j = 0; j < n; ++j) {
-        /* A sequence with no slot has none of its copies either: -1 all the way across, which is
-         * the pad every kernel already tests for. */
+        /* No slot: -1 across the row, the pad every kernel tests for. */
         out[j] = base < 0 ? -1 : (int32_t)(base + (int64_t)j * copies / w * span);
     }
     return n;
diff --git a/core/mem/kv.h b/core/mem/kv.h
index 51637d84..a29e8c64 100644
--- a/core/mem/kv.h
+++ b/core/mem/kv.h
@@ -1,21 +1,19 @@
 /* kv.h -- the KV block manager (spec §7.2).
  *
- * Paged, per KV group, each group with its OWN block geometry, its own pool and its own slot
- * mapping. Block size comes from KVGroupInfo::block_size, which the build component took off the
- * resolved attention kernel's constraints -- never a core constant. A core that picked its own
- * block size would be a core that has to be edited when a kernel changes.
+ * Paged per KV group; each group has its own block geometry, pool and slot mapping. Block size
+ * comes from KVGroupInfo::block_size, taken from the resolved attention kernel's constraints,
+ * never from a core constant, so a kernel change needs no core edit.
  *
- * Hybrid models are the normal case, not an extension. Four state kinds:
+ * Four state kinds (hybrid models are the normal case):
  *
  *   RAD_KV_FULL    paged, per-token, growing
- *   RAD_KV_WINDOW  paged, per-token, bounded by the window -- blocks below the window are recycled
- *   RAD_KV_LINEAR  per-sequence, FIXED size: the GDN recurrent state
- *   RAD_KV_CONV    per-sequence, FIXED size: a rolling window of conv_width-1 + n_spec entries
+ *   RAD_KV_WINDOW  paged, per-token, bounded by the window; blocks below the window are recycled
+ *   RAD_KV_LINEAR  per-sequence, fixed size: the GDN recurrent state
+ *   RAD_KV_CONV    per-sequence, fixed size: a rolling window of conv_width-1 + n_spec entries
  *
- * The last two are not paged the same way, and they are allocated, mapped and freed BY THIS
- * MANAGER anyway, because otherwise two allocators disagree about what a sequence owns. That
- * disagreement is not a memory leak, it is a correctness bug: the scheduler frees a sequence and
- * one of the two allocators keeps handing its state slot to the next request.
+ * The two stateful kinds are also allocated, mapped and freed here, so one allocator decides what
+ * a sequence owns. With two, a freed sequence's state slot could still be handed to the next
+ * request by the other.
  */
 #pragma once
 #include "mem/hostarena.h"
@@ -30,22 +28,14 @@
 namespace rad {
 
 /* ------------------------------------------------------------------ group sizing */
-/* vLLM slices a hybrid model's layers into equal-sized groups and PADS each bundle up to a
- * multiple of that size -- and a padding layer is allocated real memory. On a 48 linear / 16 full
- * / 5 drafter model its rule ("group size = the smallest bundle") picks 5, which divides neither
- * 48 nor 16, so it allocates 15 groups x 5 = 75 slots for 69 real layers, and rounds the
- * per-request requirement up once per group -- fifteen round-ups on every request, which is where
- * most of the loss actually is. Replacing that rule with a least-waste search recovers a
- * substantial fraction of the KV tokens at a byte-identical budget.
+/* Layer bundling compared with vLLM. vLLM splits a hybrid model's layers into equal-sized groups
+ * and pads each bundle to a multiple of that size with real memory: on a 48 linear / 16 full /
+ * 5 drafter model its rule picks size 5, giving 15 groups x 5 = 75 slots for 69 layers and a
+ * per-request round-up per group. A least-waste search recovers part of that.
  *
- * Radiance does not need the search, because it does not have the constraint the search works
- * around. A KV group here is one state kind with one geometry and ITS OWN POOL (spec §7.2), so
- * there is no uniform page size to pad up to and no reason to subdivide a bundle: every state
- * kind is exactly one group covering exactly its own layers. Padding is structurally zero and the
- * group count is structurally minimal.
- *
- * This struct exists so `--debug-placement` can print that claim next to what vLLM would have
- * done, and so the test can assert it rather than trusting the comment. */
+ * Here each state kind is one group with its own pool (spec §7.2), so there is no uniform page
+ * size to pad to: padding is zero and the group count is minimal. This struct lets
+ * `--debug-placement` print the comparison and lets a test assert it. */
 struct BundleComparison {
     std::vector bundles;        /* layers per state kind, as declared */
     int64_t stock_group_size = 0;        /* vLLM's rule: the smallest bundle (with the 1.5x escape) */
@@ -55,7 +45,7 @@ struct BundleComparison {
     int64_t patched_groups = 0;
     int64_t patched_slots = 0;
     int64_t our_groups = 0;              /* == bundles.size() */
-    int64_t our_slots = 0;               /* == sum(bundles); padding is zero by construction */
+    int64_t our_slots = 0;               /* == sum(bundles); no padding */
     std::string report() const;
 };
 BundleComparison compare_bundling(const std::vector& bundles);
@@ -68,31 +58,28 @@ struct KVGroupPlan {
     int64_t     n_layers = 0;
 
     int64_t     block_size = 0;        /* tokens per block, from the resolved kernel */
-    int64_t     bytes_per_block = 0;   /* covers EVERY layer bound to the group -- see the note
-                                        * on bundling above: one page, one bundle, no padding */
+    int64_t     bytes_per_block = 0;   /* covers every layer bound to the group */
     int64_t     bytes_per_state = 0;   /* LINEAR/CONV: per sequence, every layer */
     int64_t     conv_slots = 0;        /* CONV: conv_width - 1 + n_spec */
     int64_t     window_blocks = 0;     /* WINDOW: the per-sequence block cap */
-    /* WINDOW: a checkpoint slot carries this group's window (has_window_snapshot). Only a trunk
-     * group of a model with no linear state: a prefix hit there resumes at a checkpoint from the
-     * window behind it. A drafter's own window is recomputed by draft refill, and a model with
-     * linear state re-prefills a hit on a windowed trunk, so neither snapshot would ever be read. */
+    /* WINDOW: a checkpoint slot carries this group's window (has_window_snapshot). Set only for a
+     * trunk group of a model with no linear state. A drafter's window is recomputed by draft
+     * refill, and a model with linear state re-prefills a hit on a windowed trunk, so neither
+     * snapshot would be read. */
     bool        win_snap = false;
 
     int64_t     n_blocks = 0;          /* paged groups: blocks carved from the pool */
-    /* rad_kv_group_zero: this rank keeps no cache for the group. The plan exists for its position
-     * and its block count (one block table serves every rank), its costs are zero and nothing is
-     * carved; no op on this rank names it (issue refuses a group with no pool bound). */
+    /* rad_kv_group_zero: this rank keeps no cache for the group. The plan keeps its position and
+     * block count (one block table serves every rank); its costs are zero and nothing is carved.
+     * No op on this rank names it (issue refuses a group with no pool bound). */
     bool        zero = false;
     int64_t     n_states = 0;          /* LINEAR/CONV: n_seq_states * state_copies */
-    /* HOW MANY PHYSICAL SLOTS ONE LOGICAL STATE COSTS. One, normally: a sequence owns a state.
-     * Under speculation a linear kernel needs somewhere to put what it cannot commit yet -- it
-     * has run 1 + n_spec tokens through the recurrence before anyone knows which survive -- and
-     * the scheme libr4d uses keeps the committed state in one slot and the per-token replay
-     * factors in a second, then folds the accepted prefix in at the start of the next step. Two
-     * slots a sequence, not 1 + n_spec: the factors are a few hundred floats a head against a
-     * 128x128 state, so they fit inside a slot with room to spare and the pool grows by 2x
-     * rather than by 9x. Copy k of logical slot s is the physical slot s + k * n_seq_states. */
+    /* Physical slots per logical state: 1, or 2 under speculation. A verify runs 1 + n_spec
+     * tokens through the recurrence before acceptance is known; libr4d keeps the committed state
+     * in copy 0 and the per-token replay factors in copy 1, and folds the accepted prefix in at
+     * the next step. The factors (a few hundred floats a head, against a 128x128 state) fit in
+     * one slot, so the pool grows 2x rather than (1 + n_spec)x. Copy k of logical slot s is
+     * physical slot s + k * n_seq_states. */
     int64_t     state_copies = 1;
     int64_t n_seq_states() const { return state_copies > 0 ? n_states / state_copies : n_states; }
     int64_t     pool_offset = 0;
@@ -102,18 +89,14 @@ struct KVGroupPlan {
     bool paged() const { return kind == RAD_KV_FULL || kind == RAD_KV_WINDOW; }
     bool stateful() const { return kind == RAD_KV_LINEAR || kind == RAD_KV_CONV; }
 
-    /* THE POOL IS LAYER-MAJOR, and that is not a free choice -- the ABI already made it. A
-     * RAD_OPK_KV operand carries the LAYER as its offset and the core resolves it as
-     * `base + layer * layer_stride` (RadOperand in rad_runtime.h, KVPoolBinding in
-     * core/runtime/ctx.h), because an attention kernel takes ONE base pointer for the layer it is
-     * running and indexes inside it with the block table and the slot mapping. Interleaving the
-     * layers inside a block would mean every kernel needed the layer count and the bundle stride
-     * as well, to reach the same bytes.
+    /* The pool is layer-major, as the ABI requires: a RAD_OPK_KV operand carries the layer as its
+     * offset and resolves to `base + layer * layer_stride` (RadOperand in rad_runtime.h,
+     * KVPoolBinding in core/runtime/ctx.h), so a kernel gets one base pointer per layer and
+     * indexes it with the block table and slot mapping.
      *
-     * So layer i owns [base + i*layer_stride, + layer_stride): n_blocks blocks of
+     * Layer i owns [base + i*layer_stride, + layer_stride): n_blocks blocks of
      * `bytes_per_block / n_layers` for a paged group, n_states states of
-     * `bytes_per_state / n_layers` for a stateful one. The totals are identical either way, which
-     * is why sizing does not care and addressing does. */
+     * `bytes_per_state / n_layers` for a stateful one. */
     int64_t layer_bytes_per_block() const {
         return n_layers > 0 ? bytes_per_block / n_layers : bytes_per_block;
     }
@@ -126,28 +109,21 @@ struct KVGroupPlan {
 };
 
 /* A copy the caller must execute on its copy stream before the destination block is read. The
- * manager does not issue device copies itself: it has no stream, and a memcpy on the step path is
- * a synchronisation the engine spends its whole design avoiding (spec §5.4). */
+ * manager has no stream and issues no device copies, since a memcpy on the step path would
+ * synchronise (spec §5.4). */
 struct BlockCopy {
     int32_t group = -1;
     int32_t src_block = -1;
     int32_t dst_block = -1;
 };
 
-/* A STATE SLOT THAT STILL HOLDS THE PREVIOUS TENANT'S HISTORY. The manager names the work and the
- * engine issues it, for the same reason BlockCopy exists: no stream here, and a synchronisation on
- * the step path is what this design spends itself avoiding (spec §5.4).
+/* A state slot that still holds the previous tenant's state and must be zeroed before first use.
+ * The manager names the work and the engine issues it, as with BlockCopy.
  *
- * WHY A RECURRENT SLOT HAS TO BE CLEARED AND A PAGED ONE DOES NOT. A paged sequence reads only the
- * blocks its own block table names, so a recycled block is unreachable until it is written. A
- * recurrent sequence has no table: `gdn_chunk_scan` reads `h0` out of the slot and there is no
- * operand in its schema that says "this sequence has none". An uncleared slot IS the last
- * sequence's entire compressed history, so the second request a server answers silently continues
- * the first: the same prompt gives a different distribution on a fresh process than it does after
- * another request has run.
- *
- * The conv group carries `has_init` and does not need this. It is cleared anyway: two rules about
- * one pool is how one of them rots. */
+ * A paged sequence reads only the blocks its table names, so a recycled block is unreachable
+ * until written. A recurrent slot has no table: `gdn_chunk_scan` reads `h0` from the slot and has
+ * no operand for "no initial state", so an uncleared slot continues the previous sequence's
+ * history. Conv slots carry `has_init` but are cleared too, so one rule covers the pool. */
 struct StateClear {
     int32_t group = -1;
     int32_t slot  = -1;
@@ -156,41 +132,37 @@ struct StateClear {
 /* ------------------------------------------------------------------ manager */
 class KVManager {
 public:
-    /* Sizes every group out of one pool and refuses, by name and by how much, if the fixed costs
-     * alone do not fit. The split between the paged groups is not a policy: they are sized to
-     * exhaust at the same total token count, and any other split strands memory in whichever
-     * group outlasts the others.
+    /* Sizes every group out of one pool, refusing by name and shortfall if the fixed costs alone
+     * do not fit. The paged groups are sized to run out at the same total token count; any other
+     * split strands memory in whichever group outlasts the others.
      *
-     * The byte budget is the budget resolver's and is not re-derived here: it is whatever
-     * `kv_pool` still has (vram_kv). The linear-state snapshots take none of it -- they live
-     * in pinned host memory (set_checkpoint_store) -- so the pool is the live cache and nothing
-     * else (spec §6, §7.3). */
+     * The budget is whatever `kv_pool` has left (vram_kv), as the budget resolver set it.
+     * Linear-state snapshots live in pinned host memory (set_checkpoint_store), so the pool holds
+     * only the live cache (spec §6, §7.3). */
     int configure(const std::vector& groups, const Config& cfg, Pool& kv_pool);
 
-    /* configure(), split at the seam the budget resolver needs. plan_groups() sizes every group
-     * from the declaration and the run configuration -- no pool, no bytes -- and ceiling() then
-     * says what a FULL cache for `ctx` tokens on max_seqs sequences would cost. Pools are
-     * allocated before carve() runs, so the KV pool has to be decided from these two
-     * and nothing else (core/mem/vram_budget.cpp). carve() spends the pool it is given. */
+    /* configure() in two steps for the budget resolver. plan_groups() sizes every group from the
+     * declaration and run configuration (no pool), and ceiling() gives the cost of a full cache
+     * for `ctx` tokens on max_seqs sequences. Pools are allocated before carve(), so the KV pool
+     * is sized and capped from these two alone (core/mem/vram_budget.cpp); VRAM above the ceiling
+     * would never be addressed. carve() spends the pool it is given. */
     int     plan_groups(const std::vector& groups, const Config& cfg);
     int64_t ceiling(int64_t ctx) const;
-    /* The part of every ceiling that is not context: recurrent and conv state for max_seqs
-     * sequences, and the padding. Set by plan_groups(). */
+    /* The context-independent part of every ceiling: recurrent and conv state for max_seqs
+     * sequences, plus alignment padding. Set by plan_groups(). */
     int64_t fixed_bytes() const { return fixed_; }
-    /* THE TOKEN COUNT THE PAGED GROUPS SETTLE ON for `budget_bytes` of pool -- carve()'s split
-     * with nothing carved. One block table serves every rank, so every rank's paged groups must
-     * hold the SAME number of blocks; under an uneven tensor-parallel split the ranks' pools are
-     * not the same size (a rank with more delta-net heads holds more state and has less left for
-     * pages, and a rank with no attention weights has more). The engine asks each rank this and
-     * cap_paged_tokens() the least on all of them before carve(). 0 is no cap.
-     * kUnboundedTokens when every paged group of this rank is zero (rad_kv_group_zero): its pages
-     * cost it nothing, so it takes what the ranks holding the cache carve and limits nobody. */
+    /* The token count the paged groups settle on for `budget_bytes` of pool (carve()'s split,
+     * without carving). One block table serves every rank, so all ranks must hold the same block
+     * count, but under an uneven tensor-parallel split their pools differ. The engine asks every
+     * rank and passes the least to cap_paged_tokens() before carve(); 0 is no cap.
+     * kUnboundedTokens when every paged group on this rank is zero (rad_kv_group_zero): this rank
+     * then limits nothing. */
     static constexpr int64_t kUnboundedTokens = INT64_MAX;
     int64_t paged_tokens(int64_t budget_bytes) const { return paged_split(budget_bytes, nullptr); }
-    /* THE INVERSE OF paged_tokens: the least whole MiB of pool whose paged split reaches `tokens`,
-     * searched up to max_mib; -1 when even max_mib does not. Pure arithmetic on the plan (no pool,
-     * no cap), for Engine::plan sizing an uneven world's cheaper rank to the token count its
-     * dearest peer sets. paged_split is monotone in the budget, so the search is exact. */
+    /* Inverse of paged_tokens: the least whole MiB of pool whose paged split reaches `tokens`,
+     * searched up to max_mib; -1 if max_mib does not reach it. Pure arithmetic on the plan, used
+     * by Engine::plan to size a cheaper rank to the token count of its dearest peer. Exact,
+     * because paged_split is monotone in the budget. */
     int64_t pool_mib_for_tokens(int64_t tokens, int64_t max_mib) const;
     void    cap_paged_tokens(int64_t tokens) { tokens_cap_ = tokens > 0 ? tokens : 0; }
     int     carve(Pool& kv_pool);
@@ -198,44 +170,39 @@ public:
     const std::vector& plans() const { return plans_; }
     const KVGroupPlan* plan(int32_t group) const;
     int32_t n_groups() const { return (int32_t)plans_.size(); }
-    const BundleComparison& bundling() const { return bundling_; }
     std::string report() const;
 
     /* ---------------- sequences ---------------- */
     int  add_sequence(uint64_t seq);
     bool has_sequence(uint64_t seq) const;
     void free_sequence(uint64_t seq);
-    /* HOW MANY TIMES A SEQUENCE HAS LET GO OF ITS BLOCKS -- freed or preempted -- over the life of
-     * the manager. A block's reference count falls for no other reason the prefix cache cannot
-     * see, so this is what tells it a block it found shared may no longer be. */
+    /* Count of sequence frees and preemptions over the manager's life. These are the only
+     * refcount drops the prefix cache cannot see, so a change tells it a block it saw shared may
+     * no longer be. */
     uint64_t seq_frees() const { return seq_frees_; }
 
     /* Grow the sequence's mapping to cover `n_tokens` in every group. Unshares a shared partial
      * block first (copy-on-write) and appends the copy request to the pending list.
      * RAD_E_FULL when a group's free list is empty -- the caller preempts and retries.
      *
-     * `keep_from` is the position of the FIRST query the coming step runs (the scheduler's
-     * n_computed); -1 means the sequence's current end. A WINDOW group recycles only the blocks no
-     * query at or past it can read -- below keep_from - window + 1 -- and NOT the blocks below the
-     * window of the step's END: a prefill chunk longer than a block would otherwise lose the keys
-     * its first rows attend to (a chunk of C tokens from position 0 rebased the table at
-     * ceil(C/block) - window_blocks and left every position below it with no KV at all). */
+     * `keep_from` is the position of the first query the coming step runs (the scheduler's
+     * n_computed); -1 means the sequence's current end. A WINDOW group recycles only blocks below
+     * keep_from - window + 1, not below the window of the step's end, which would drop keys the
+     * first rows of a multi-block prefill chunk still read. */
     int  ensure(uint64_t seq, int64_t n_tokens, int64_t keep_from = -1);
 
-    /* A WINDOW group's caps: a sequence holds its window behind the step's first query AND the
-     * step's own tokens (window_blocks + ceil(max_tok / block) + 1 at most), and one step carries
-     * at most max_tok tokens across every sequence in it, so the pool needs max_seqs windows plus
-     * one step's worth on top. */
+    /* A WINDOW group's caps. A sequence holds the window behind the step's first query plus the
+     * step's own tokens (at most window_blocks + ceil(max_tok / block) + 1), and one step carries
+     * at most max_tok tokens in total, so the pool needs max_seqs windows plus one step. */
     int64_t window_seq_cap(const KVGroupPlan& p) const;
     int64_t window_pool_cap(const KVGroupPlan& p) const;
+    /* ceil(max_tok / block): the blocks one step's tokens can fill. */
+    int64_t step_blocks(const KVGroupPlan& p) const;
 
-    /* GIVE BACK A FINISHED CHUNK'S BLOCKS once it is committed. ensure() keeps a chunk's own blocks
-     * beside the window behind its first query, and only the sequence's NEXT ensure() recycles
-     * them -- so a prefill waiting a step for its next chunk would sit on a whole chunk of window
-     * blocks while other sequences prefill, and eight of them exhaust the pool (measured on
-     * Gemma 4: "the KV pool cannot hold 12480 tokens" with eight 16K prompts). Called by the
-     * scheduler when it advances n_computed: keep_from is the new n_computed, the first query any
-     * later step can run. */
+    /* Recycles a committed chunk's window blocks. ensure() keeps a chunk's blocks beside the
+     * window and only the next ensure() recycles them, so a prefill waiting for its next chunk
+     * would hold a whole chunk of blocks; several such prefills can exhaust the pool. The
+     * scheduler calls this when it advances n_computed, passing the new n_computed. */
     void trim_window(uint64_t seq, int64_t keep_from);
 
     /* Adopt blocks a prefix-cache hit found. `n_tokens` must be a whole multiple of the group's
@@ -243,45 +210,41 @@ public:
      * corrupt the cache entry. Bumps each block's refcount. */
     int  adopt(uint64_t seq, int32_t group, const std::vector& blocks, int64_t n_tokens);
 
-    /* Fork: the child shares every WHOLE block of the parent and gets its own copy of the
-     * partial one on first write (copy-on-write, spec §7.3). Stateful groups cannot be shared --
-     * a recurrent state is one object, not a chain -- so the child gets its own slot and the
-     * caller must snapshot-restore into it. */
+    /* The child shares every whole block of the parent and copies the partial one on first write
+     * (spec §7.3). A recurrent state cannot be shared, so the child gets its own slot and the
+     * caller must restore a snapshot into it. */
     int  fork(uint64_t parent, uint64_t child);
 
     std::vector take_pending_copies();
 
-    /* The prefix cache's handle on a block. It holds a reference on every block it indexes, and
-     * that reference is the invariant that makes a hit safe: a block named by the cache is never
-     * in the free list, so it can never be handed to another sequence underneath a cache entry.
-     * Nothing else in the engine may call these -- the block table is the manager's property. */
-    /* TAKE A FREE BLOCK, with no sequence attached to it yet. The idle-session tiers need this
-     * and nothing else does: a restore has bytes to put somewhere before any sequence has asked
-     * for them, and the prefix cache takes the reference afterwards. Every other caller reaches
-     * blocks through a sequence, which is why grab_block itself stays private -- this is the one
-     * documented way to hold a block that no Seq owns, and the holder is responsible for
-     * release_block if the restore then fails. */
+    /* Prefix-cache and tier access to blocks. The cache holds a reference on every block it
+     * indexes, so a cached block is never in the free list and cannot be handed to another
+     * sequence under a cache entry. Nothing else may call these. */
+    /* Takes a free block with no sequence attached, for the idle-session tiers: a restore needs
+     * somewhere to put bytes before any sequence asks for them, and the prefix cache takes the
+     * reference afterwards. The holder must release_block() if the restore fails. Does not
+     * recall the loan; it stops at what the cache keeps in hand. */
     int  reserve_block(int32_t group, int32_t* out);
-    /* THE SAME FOR A WHOLE CHAIN AT ONCE: up to `n` blocks appended to `out`, and how many. The
-     * loan is recalled for all of them before the first is taken, because a restore is sized
-     * before it starts and one recall a block would drain the slab a buffer at a time -- the
-     * reserve above stops at whatever the cache kept in hand. */
+    /* Up to `n` blocks appended to `out`; returns how many. Recalls the loan for all of them up
+     * front, since a block-at-a-time recall would drain the slab one buffer at a time. */
     int64_t reserve_blocks(int32_t group, int64_t n, std::vector* out);
-    /* The same, for a block another rank already chose. See the definition. */
+    /* Takes one particular block another rank already chose. Block ids are shared across ranks
+     * (RadBatch carries one table), so under tensor parallelism rank 0 picks and the others take
+     * the same id. Refuses (RAD_E_STATE) a held block or one above the live mark rather than
+     * substituting, since a rank restoring into a different block would corrupt only that rank's
+     * output. */
     int  reserve_specific_block(int32_t group, int32_t block);
     /* The cache's reference on a block a sequence already holds. The block is marked as the
      * cache's for cache_only_blocks(). */
     int  retain_block(int32_t group, int32_t block);
     /* A reserved block's reference handed to the cache as it stands: marked, not counted again. */
     void cache_reserved_block(int32_t group, int32_t block);
-    /* Lets go of the cache's reference on a marked block and of a reservation's on any other. */
+    /* Releases the cache's reference on a marked block, or a reservation's on any other. */
     void release_block(int32_t group, int32_t block);
     int32_t block_refcount(int32_t group, int32_t block) const;
-    /* BLOCKS ONLY THE CACHE HOLDS: marked, and at a reference count of one. This is what an
-     * eviction would give back, and what a dashboard reports as cache rather than as context.
-     * Kept current at every reference-count change so that reading it costs nothing: the figure
-     * is read while the scheduler's lock is held, and a walk of the cache to compute it would
-     * stall the step for as long as it ran. */
+    /* Blocks only the cache holds: marked, at refcount one. This is what an eviction would free.
+     * Maintained at every refcount change because it is read under the scheduler's lock, where a
+     * walk of the cache would stall the step. */
     int64_t cache_only_blocks(int32_t group) const;
 
     const std::vector& block_table(uint64_t seq, int32_t group) const;
@@ -298,168 +261,132 @@ public:
     /* ---------------- accounting ---------------- */
     int64_t free_blocks(int32_t g) const;
 
-    /* HOW MANY BLOCKS OF A GROUP ANYTHING IS HOLDING. free_blocks() is what may be handed out
-     * RIGHT NOW, which while the cache is lending is bounded by the live mark and not by the
-     * carve, so `carve - free` counts every lent block as occupied -- an idle server reading 97%
-     * full. The occupancy question wants this instead: a lent block is neither held nor
-     * unavailable, because the loan is recalled on demand up to the carve. */
+    /* Blocks of a group that something holds. Use this for occupancy, not `carve - free`:
+     * free_blocks() is bounded by the live mark while the cache lends, so that difference would
+     * count lent blocks as occupied. */
     int64_t held_blocks(int32_t g) const;
 
+    /* The carve: the range every block id is addressed against. live_blocks() is what the cache
+     * keeps unlent. */
     int64_t total_blocks(int32_t group) const;
     int64_t free_states(int32_t group) const;
 
-    /* THE POOL IN BYTES, WHICH IS THE ONLY UNIT THE GROUPS CAN BE ADDED IN. Blocks cannot be:
-     * a paged group and a stateful one count different objects, and two paged groups share ONE
-     * token axis -- a token of context takes a slot in each of them -- so summing either measure
-     * reports a pool several times the size of the one the card holds. Bytes are disjoint VRAM
-     * and add up.
+    /* Pool size in bytes, the only unit in which groups can be summed: paged and stateful groups
+     * count different objects, and paged groups share one token axis.
      *
-     * The used figure is what is HELD rather than what is reachable: a block a sequence owns and
-     * a block only the prefix cache still references both count, because both are VRAM the next
-     * request cannot be given. A block stops counting the moment it reaches the free list,
-     * whether it got there because its sequence ended, because the cache evicted it, or because
-     * the idle tiers copied it to host memory and released it. */
+     * pool_bytes() excludes lent blocks, which the expert slab reports as its own. Used bytes
+     * count held blocks, owned by a sequence or referenced only by the prefix cache; a block
+     * stops counting when it reaches the free list. */
     int64_t pool_bytes(int32_t group) const;
     int64_t pool_bytes_used(int32_t group) const;
-    /* THE CARVE, which the cache may not be keeping. pool_bytes() is what the cache keeps for
-     * itself right now; this is what the operator budget gave it to address, and the difference
-     * between them is what it has lent to the expert slab. */
+    /* Bytes the budget carved for the group; the difference from pool_bytes() is lent to the
+     * expert slab. */
     int64_t pool_bytes_carved(int32_t group) const;
     int64_t blocks_for(int32_t group, int64_t n_tokens) const;
 
-    /* Could a sequence of this length EVER fit, in an empty pool? If not, preempting the whole
-     * server would not help and the request is failed immediately rather than the engine
-     * deadlocking on it (spec §17). */
+    /* Whether a sequence of this length fits an empty pool. If not, preemption cannot help and
+     * the request is failed rather than deadlocking the engine (spec §17). */
     bool can_ever_fit(int64_t n_tokens) const;
 
     /* ---------------- the loan ----------------
      *
-     * THE PAGED GROUPS LEND THE EXPERT SLAB WHAT NOTHING HOLDS, AT THE ADDRESSES THEY ALREADY
-     * OWN. The carve decides every address once and backs all of it before anything runs, and
-     * nothing here ever unmaps it. What moves is only how many of a group's blocks the cache may
-     * hand out: the blocks above that mark, in every layer's stripe, are where the slab keeps
-     * expert units -- units the MoE GEMM would otherwise read across the link on every step that
-     * routes to them. No memory is allocated or released in either direction, so no driver call
-     * is made and what the card reports free never changes.
+     * The paged groups lend unheld blocks to the expert slab in place. The carve fixes and backs
+     * every address once and nothing here unmaps it; the loan only lowers how many of a group's
+     * blocks the cache may hand out (the live mark). The slab keeps expert units in the blocks
+     * above the mark in every layer's stripe, so the MoE GEMM need not read them across the link.
+     * No memory is allocated or freed either way, so the loan makes no driver call.
      *
-     * THE LOAN IS STATED IN TOKENS, counted down from the top of the carve. The FULL groups are
-     * sized to run out at the same total token count (carve()), so one number is the same depth
-     * in each of them: a loan of T tokens is the top floor(T / block_size) blocks of every FULL
-     * group. A WINDOW group is sized per sequence rather than on that axis and is never lent.
+     * The loan is in tokens, counted down from the top of the carve. FULL groups are sized to run
+     * out at the same token count, so a loan of T tokens is the top floor(T / block_size) blocks
+     * of every FULL group. WINDOW groups are sized per sequence and never lent.
      *
-     * A BLOCK IS NOT LENT WHILE ANYTHING HOLDS IT, and a held block is a block a sequence owns OR
-     * one the prefix cache still indexes. So a loan cannot evict anything: it is a claim on what
-     * is free. Everything that makes a block free -- a sequence ending, an eviction, an idle-tier
-     * demotion to host memory -- makes it lendable, and the min-heap free list is what
-     * keeps the free blocks at the top, where a loan can reach them.
+     * A held block (owned by a sequence or indexed by the prefix cache) is never lent, so a loan
+     * evicts nothing. The min-heap free list keeps free blocks at the top, where a loan reaches
+     * them.
      *
-     * THE BUFFER IS DERIVED AND NOT STATED. It is the free blocks the cache keeps in hand so that
-     * a request finds room without a recall, and the right size for it is a property of the
-     * workload rather than a number an operator can know: one prefill chunk -- the most KV a
-     * single step can consume -- or the largest recent shortfall, whichever is larger. The second
-     * term decays, so an idle server settles at the floor and a ramping one has the buffer
-     * leading the ramp. */
+     * The buffer is the free blocks the cache keeps in hand so a request finds room without a
+     * recall: the larger of one prefill chunk (the most one step consumes) and the largest recent
+     * shortfall. The shortfall term decays, so an idle server settles at the floor. */
     int64_t buffer_bytes() const;
 
-    /* Is this group lent from? The FULL paged groups, and only those. */
+    /* True for the FULL paged groups only. */
     bool    lendable(int32_t group) const;
 
-    /* HOW MUCH THE CACHE CAN LEND RIGHT NOW, in tokens: the smallest distance, over the lendable
-     * groups, from the top of the carve down to the highest block anything holds plus the buffer.
-     * Rank 0 only -- a follower's held history is empty. Also where the buffer's trend term
-     * decays, so it is called once per arbiter tick. */
+    /* Tokens the cache can lend now: over the lendable groups, the least distance from the top of
+     * the carve down to the highest held block plus the buffer. Rank 0 only (a follower tracks no
+     * held blocks). Also decays the buffer's shortfall term, so call it once per arbiter tick. */
     int64_t spare_tokens();
 
-    /* LEND `tokens` FROM THE TOP, or take back what a smaller number no longer covers. Lending
-     * past a held block is refused (RAD_E_STATE): the arbiter asked for more than spare_tokens()
-     * said there was. Taking back is always allowed here, and it is the caller's to make true --
-     * the slab must have left those blocks before this runs. */
+    /* Lends `tokens` from the top, or takes back what a smaller number no longer covers. Lending
+     * past a held block is refused (RAD_E_STATE). Taking back always succeeds here; the caller
+     * must have moved the slab out of those blocks first. */
     int     set_loan(int64_t tokens);
     int64_t loan_tokens() const { return loan_; }
 
-    /* WHO GIVES IT BACK WHEN A REQUEST CANNOT WAIT. A request that needs more blocks than the
-     * cache kept in hand calls this with the loan it can still afford, and the owner of the
-     * slabs drains them to it before returning -- so admission is decided against the whole
-     * carve, exactly as it would be with nothing lent. Without one, what is lent is not
-     * recalled and the request is refused (RAD_E_FULL). */
+    /* Recall hook. A request needing more blocks than the cache has in hand calls it with the
+     * loan it can still afford, and the slab owner drains to that before returning, so admission
+     * is decided against the whole carve. Without a hook, lent blocks are not recalled and the
+     * request gets RAD_E_FULL. */
     void    set_reclaim(std::function f) { reclaim_ = std::move(f); }
 
-    /* MATCH A LEADER'S LOAN, FOR A RANK THAT DOES NOT KNOW WHAT IT IS HOLDING.
-     *
-     * Block ids are SHARED ACROSS RANKS -- RadBatch carries one block table and every rank indexes
-     * its own shard of the pool with it -- and only rank 0's KVManager tracks sequences. So a
-     * follower takes its mark from the leader instead of computing one: its own slab occupies the
-     * same blocks of its own pool, and an id the leader hands out below the mark has to be one the
-     * follower's slab has left too. */
+    /* Copies the leader's loan onto a follower rank. Block ids are shared across ranks and only
+     * rank 0 tracks sequences, so a follower takes the leader's mark instead of computing one;
+     * its slab occupies the same block ids of its own pool. */
     int     follow(const KVManager& leader);
 
-    /* HOW MANY OF A GROUP'S BLOCKS THE CACHE MAY HAND OUT: the carve less what is lent. */
+    /* Blocks of a group the cache may hand out: the carve less the loan. */
     int64_t live_blocks(int32_t group) const;
-    int64_t committed_bytes() const;
 
     /* ---------------- preemption by recompute (spec §7.1, §17) ---------------- */
-    /* Free the sequence's blocks and take it back to zero tokens. Its state slots are freed too: a
-     * recurrent state that is not snapshotted cannot be resumed, so a preempted sequence replays
-     * from its last checkpoint or from zero.
-     *
-     * IT DOES NOT MARK ANYTHING, and carries no "needs re-prefill" flag. The scheduler's own
-     * `r.n_computed = 0` (preempt_back) is what drives the replay, and a second piece of state
-     * saying the same thing is a second thing to keep true. seq_tokens() == 0 is the reading, and
-     * it cannot drift. */
+    /* Frees the sequence's blocks and state slots and resets it to zero tokens. A recurrent
+     * state that was not snapshotted cannot be resumed, so the sequence replays from its last
+     * checkpoint or from zero. No "needs re-prefill" flag is kept: the scheduler's
+     * `r.n_computed = 0` (preempt_back) drives the replay, and seq_tokens() == 0 reflects it. */
     int  preempt(uint64_t seq);
 
     /* ---------------- speculative rejection (spec §10) ---------------- */
-    /* Bring the sequence back to `n_tokens` and return the paged blocks past it. A verify writes
-     * KV for 1 + n_spec positions and the sampler accepts a prefix of them, so the rest has to go
-     * back; `ensure` is monotone and cannot express it.
+    /* Shrinks the sequence to `n_tokens` and frees the paged blocks past it. A verify writes KV
+     * for 1 + n_spec positions and the sampler accepts a prefix; `ensure` is monotone and cannot
+     * undo the rest.
      *
-     * PAGED GROUPS ONLY, and that is the whole point. The linear state and the conv window have
-     * already absorbed the rejected tokens and are NOT recomputed: libr4d keeps the conv cache as
-     * a rolling window of conv_width-1 + n_spec entries and reads at the slot the last accepted
-     * token left, so a rejection there is a change of read offset that the kernels perform
-     * themselves (core/sample/accept.h). Freeing a state slot here would destroy the state that
-     * offset points into.
-     *
-     * Rolling back is not preemption: the sequence keeps its state slots and its window base.
-     * Without this the pool leaks one block per rejected block-crossing, which is a slow leak and
-     * therefore the worst kind. */
+     * Paged groups only. The linear state and conv window have already absorbed the rejected
+     * tokens: the conv cache is a rolling window of conv_width-1 + n_spec entries, and the kernels
+     * handle a rejection by moving the read offset (core/sample/accept.h). Freeing a state slot
+     * here would destroy the state that offset points into. Unlike preempt, the sequence keeps
+     * its state slots and window base. */
     int  rollback(uint64_t seq, int64_t n_tokens);
 
-    /* The absolute token position that block_table(seq, group)[0] covers. Zero for a FULL group;
-     * non-zero for a WINDOW group, whose blocks below the window have been recycled. The step
-     * batch's slot mapping is (pos - first_block_pos) / block_size, and without the offset every
-     * sliding-window sequence writes its KV to the wrong slot the moment it passes its window. */
+    /* The absolute token position block_table(seq, group)[0] covers: zero for a FULL group, the
+     * recycled prefix for a WINDOW group. The slot mapping is (pos - first_block_pos) /
+     * block_size; without the offset a sliding-window sequence writes to the wrong slot once it
+     * passes its window. */
     int64_t first_block_pos(uint64_t seq, int32_t group) const;
 
-    /* THE ENTRIES OF A SEQUENCE'S TABLE THAT CHANGED since the last call: every entry below the
-     * returned index is what it was then, and kNoDirty says none changed. The call clears the
-     * mark, so it has exactly one reader -- the batch builder, which stages only the changed tail
-     * of a table the device already holds. A sequence it has not seen answers 0. */
+    /* The first table entry changed since the last call; entries below it are unchanged, and
+     * kNoDirty means none changed. The call clears the mark, so it has one reader: the batch
+     * builder, which stages only the changed tail. An unseen sequence returns 0. */
     int64_t take_table_changes(uint64_t seq, int32_t group) const;
     static constexpr int64_t kNoDirty = INT64_MAX;
 
     /* Free victims, in the order given, until `seq` can be extended to `n_tokens`.
      *   RAD_OK        room was made; *preempted lists who paid for it
-     *   RAD_E_FULL    even an empty pool cannot serve it -- fail the request, do not retry
-     * The caller supplies the victim order because priority is the scheduler's business, not the
-     * allocator's. */
+     *   RAD_E_FULL    even an empty pool cannot serve it; fail the request, do not retry
+     * The caller supplies the victim order, since priority is the scheduler's policy. */
     int  make_room(uint64_t seq, int64_t n_tokens,
                    const std::vector& victims,
                    std::vector* preempted);
 
     /* ---------------- linear-state checkpoints (spec §7.3) ----------------
      *
-     * A SNAPSHOT LIVES IN PINNED HOST MEMORY, NOT ON THE CARD. It is a copy of a sequence's state
-     * that no kernel reads -- the step reads the live state slots, and a snapshot only ever goes
-     * back into one of those -- so it has no reason to hold VRAM. Saving it is one copy across the
-     * link after the step that produced the state, restoring it one copy back before the step
-     * that resumes from it, each a few milliseconds on a 50-100 MiB snapshot.
+     * Snapshots live in pinned host memory: no kernel reads them, they are only copied back into
+     * a live state slot. A save is one copy across the link after the step that produced the
+     * state, a restore one copy back before the step that resumes from it (a few ms for a
+     * 50-100 MiB snapshot).
      *
-     * THE STORE IS SHARED BY EVERY RANK and owned by the engine: a slot holds every rank's shard
-     * of one snapshot, each at its own offset (`rank_off`). The slot ids are rank 0's -- its manager hands them out and the others
-     * address the id they are given. Without a store no slot is ever handed out and a hybrid
-     * model's prefix hits replay their linear layers from zero. `checkpoint_bytes()` is THIS
-     * rank's shard. */
+     * The store is owned by the engine and shared by every rank: a slot holds each rank's shard
+     * at its own offset (`rank_off`). Rank 0 hands out slot ids and the other ranks use them.
+     * Without a store no slot is handed out and a hybrid model's prefix hits replay their linear
+     * layers from zero. `checkpoint_bytes()` is this rank's shard. */
     void    set_checkpoint_store(HostArena* store, int64_t rank_off);
     int64_t checkpoint_bytes() const { return checkpoint_bytes_; }
     int64_t checkpoint_slots() const { return ck_store_ ? ck_store_->capacity() : 0; }
@@ -470,46 +397,40 @@ public:
     /* The store holds `slot`: it was allocated and not given back since. */
     bool  checkpoint_held(int32_t slot) const;
 
-    /* SNAPSHOT AND RESUME A SEQUENCE'S WHOLE LINEAR STATE. This is what makes a prefix hit legal
-     * on a hybrid model: the attention half of a hit is carried by the adopted blocks, and the
-     * recurrent half is carried by these two calls and by nothing else. Without them a hit
-     * resumes every recurrent layer from whatever the slot last held -- which reads as fluent
-     * text, so it is not a failure anyone notices without a determinism check.
+    /* Snapshot and resume a sequence's whole linear state. On a hybrid model a prefix hit carries
+     * the attention half in adopted blocks and the recurrent half only through these calls;
+     * without them a hit resumes from whatever the slot last held, which still reads as fluent
+     * text.
      *
-     * The pool is LAYER-MAJOR and a sequence's state is therefore strided, not contiguous, so the
-     * blob is a gather: for every stateful group, in `plans()` order, for every layer, its
-     * `layer_bytes_per_state()` bytes. Both directions walk that identically, which is the whole
-     * requirement -- a checkpoint is only ever read back by this same build.
+     * The pool is layer-major, so the blob is a gather: for each stateful group in `plans()`
+     * order, for each layer, `layer_bytes_per_state()` bytes. Both directions walk it the same
+     * way; a checkpoint is only read back by the same build. Only copy 0 (the committed state) is
+     * saved; the other copies hold replay factors for unaccepted tokens.
      *
-     * COPY 0 ONLY. A speculating sequence owns `state_copies` physical slots and the committed
-     * state is copy 0 (KVGroupPlan); the replay factors in the others describe tokens that have
-     * not been accepted and mean nothing to a later reader.
-     *
-     * Enqueued on `s`, not synchronous: the save has to follow the step that produced the state
-     * and the restore has to precede the step that consumes it, and both are ordered by the
-     * stream rather than by waiting. One pitched copy a stateful group between the card and the
-     * store, at the link's rate. RAD_E_INVAL on a bad slot or an unknown sequence. */
+     * Enqueued on `s`, so stream order puts a save after the step that produced the state and a
+     * restore before the step that reads it. One pitched copy per stateful group. RAD_E_INVAL on
+     * a bad slot or an unknown sequence. */
     int checkpoint_save(const int32_t* state_slots, int n_slots, int32_t ck_slot, RadStream s,
                         const std::vector* win = nullptr);
     int checkpoint_restore(const int32_t* state_slots, int n_slots, int32_t ck_slot, RadStream s,
                            const std::vector* win = nullptr);
 
     /* ---------------- window snapshots (the sliding-window half of a prefix hit) ----------------
-     * A WINDOW group keeps only the blocks its window can still read, so no block list from the
-     * prefix cache describes it. What a later prompt that extends a cached prefix at position P
-     * needs from it is exactly the window behind P: blocks [lo, P/B) with
-     * lo = max(0, P/B - (window_blocks - 1)) -- the floor recycle_window keeps for a query at P.
-     * A checkpoint slot therefore carries, after the linear state, window_blocks pages a WINDOW
-     * group (every layer, layer-major rows), and a hit at a checkpoint restores them into fresh
-     * blocks seeded at that floor.
+     * A WINDOW group keeps only the blocks its window can still read, so the prefix cache's block
+     * lists do not describe it. A prompt extending a cached prefix at position P needs blocks
+     * [lo, P/B), lo = max(0, P/B - (window_blocks - 1)), the floor recycle_window keeps for a
+     * query at P. A checkpoint slot therefore carries, after the linear state, window_blocks pages
+     * per snapshot group (every layer, layer-major rows), restored into fresh blocks seeded at
+     * that floor.
      *
-     * has_window_snapshot(): this rank's slot carries a window section. window_rows() names, from
-     * the LEADER's table, the block ids [lo, P/B) of every non-zero snapshot group (win_snap) in
-     * plans() order, each group padded with -1 to window_blocks -- one vector every rank addresses
-     * with its own pool, because followers keep no sequence tables. False when the sequence does
-     * not hold that range (it is gone, or its floor moved past lo). seed_window() gives a sequence
-     * with an empty table in each snapshot group the blocks [lo, P/B) a restore will fill, before
-     * the ensure that extends it; any other WINDOW group starts at the floor that ensure sets. */
+     * has_window_snapshot(): this rank's slot carries a window section.
+     * window_rows(): from the leader's table, the block ids [lo, P/B) of every non-zero win_snap
+     * group in plans() order, each padded with -1 to window_blocks; every rank addresses its own
+     * pool with it, since followers keep no tables. False if the sequence no longer holds that
+     * range.
+     * seed_window(): gives a sequence with an empty table in each snapshot group the blocks
+     * [lo, P/B) a restore will fill, before the ensure that extends it. Other WINDOW groups start
+     * at the floor ensure sets. */
     bool has_window_snapshot() const { return window_ck_bytes_ > 0; }
     bool window_rows(uint64_t seq, int64_t pos, std::vector* out) const;
     int  seed_window(uint64_t seq, int64_t pos);
@@ -519,19 +440,18 @@ public:
         return b > 0 ? b : 0;
     }
 
-    /* Byte address of a state slot, for the slot-mapping builder. Null when the pool has no
-     * host-visible base (a device pool), which is the normal case -- the offset is what the step
-     * batch actually carries. */
+    /* Byte address of a state slot, for the slot-mapping builder. Null when the group has no
+     * base. */
     void*   state_ptr(int32_t group, int32_t layer, int32_t slot) const;
 
 private:
-    /* carve() is the wrapper and carve_into() is the work, so that a carve which returns part way
-     * through cannot leave plans_ answering guards for block state that was never sized. forget()
-     * empties both together and is what plan_groups() starts from. */
+    /* carve() wraps carve_into() and calls forget() on failure, so a carve that stops part way
+     * cannot leave plans_ passing guards for block state that was never sized. plan_groups() also
+     * starts from forget(). */
     int  carve_into(Pool& kv_pool);
-    /* THE PAGED SPLIT, as arithmetic: the token count the paged groups exhaust at together for
-     * `budget_bytes` of pool, under tokens_cap_, and each group's block count in `blocks` (by group
-     * index; a windowed group capped at its window). carve_into() spends what this says. */
+    /* The token count at which the paged groups run out together for `budget_bytes` of pool,
+     * under tokens_cap_, and each group's block count in `blocks` (by group index; a windowed
+     * group capped at its window). carve_into() spends what this returns. */
     int64_t paged_split(int64_t budget_bytes, std::vector* blocks) const;
     /* A zero group's share of `tokens`: the block count of the shared table, capped at the window
      * for a windowed group. 0 for kUnboundedTokens, which is not a count. */
@@ -549,15 +469,14 @@ private:
         std::vector first_block_pos;       /* WINDOW: token pos of blocks[0] */
         std::vector state;                 /* per group, -1 when not stateful */
         /* Per group, the lowest table entry written since the batch builder last staged this
-         * sequence: everything below it is unchanged. An append or a truncation lowers it to
-         * where it touched; anything that shifts or replaces entries lowers it to zero; kNoDirty
-         * is nothing. Mutable because reading it is what clears it -- take_table_changes. */
+         * sequence. An append or truncation lowers it to where it touched; a shift lowers it to
+         * zero; kNoDirty is unchanged. Mutable because take_table_changes() clears it. */
         mutable std::vector dirty_from;
     };
 
     int  grab_block(int32_t g, int32_t* out);
     void drop_block(int32_t g, int32_t b);
-    /* Every increment of a held block's reference count, so the cache-only count follows it. */
+    /* Increments a held block's refcount and keeps the cache-only count in step. */
     void add_ref(size_t g, int32_t b);
     int  grab_state(int32_t g, int32_t* out);
     void drop_state(int32_t g, int32_t s);
@@ -593,31 +512,23 @@ private:
     int64_t   ckpts_ = 0;      /* --checkpoint-slots, kept for the warning on a model with none */
     int64_t   tokens_cap_ = 0; /* cap_paged_tokens(): the least any rank can carve; 0 is none */
 
-    /* ---- the loan. See the public block for what this is and why a block that anything holds
-     * is never lent. ----
+    /* ---- the loan (see the public block) ----
      *
-     * `live_` is how many of a group's blocks the cache may hand out -- the carve less the loan --
-     * and it gates the free list rather than the carve: every id the carve created is in
-     * `free_blocks_`, and an id at or above live_ is simply not handed out. THAT IS WHY THE FREE
-     * LIST IS A MIN-HEAP. Handing out the lowest free id keeps the held blocks packed at the
-     * bottom of the pool, so the top is what drains and the top is the only part a loan can
-     * reach; a stack would hand back the id freed most recently, which after a busy period is
-     * exactly the high block the loan wants. The heap also makes the gate free: the smallest free
-     * id is below live_ whenever any free id is, so no scan is needed to find one.
+     * `live_` is the carve less the loan. Every carved id stays in `free_blocks_`; ids at or
+     * above live_ are just not handed out. The free list is a min-heap so the lowest free id goes
+     * out first: held blocks pack at the bottom and the top, the only part a loan reaches, drains.
+     * A stack would hand out the most recently freed id, often a high one. The heap also makes the
+     * gate a single check: if any free id is below live_, the smallest one is.
      *
-     * `held_hist_` counts held blocks per bucket, so "what is the highest bucket anything still
-     * holds" is a walk of a few thousand counters instead of a scan of every refcount. It is what
-     * decides how far a loan may reach, and it is maintained on the allocation path because a
-     * scan there is not affordable and a stale answer would lend a block out from under a live
-     * sequence. */
-    /* THE BUFFER, PER GROUP, IN BLOCKS. `chunk_blocks_` is the floor -- one prefill chunk, fixed
-     * at plan time; `short_peak_` is the largest shortfall the admission path has met recently,
-     * raised by grow_for and decayed by every spare_tokens() so it forgets a burst in a few
-     * seconds.
+     * `held_hist_` counts held blocks per bucket, so finding the highest held block is a walk of
+     * a few thousand counters, not a refcount scan. It bounds how far a loan may reach, so it is
+     * maintained on the allocation path; a stale value would lend a held block. */
+    /* The buffer per group, in blocks. `chunk_blocks_` is the floor (one prefill chunk, fixed at
+     * plan time). `short_peak_` is the largest recent admission shortfall, raised by grow_for and
+     * decayed by spare_tokens().
      *
-     * THE SHORTFALL IS THE SIGNAL AND THE RECALL IS NOT. grow_for recalls the shortfall PLUS the
-     * buffer; feeding that back would be a buffer that sizes itself from its own last value and
-     * climbs until it is the carve. What is recorded is what was asked for and not there. */
+     * Only the shortfall is recorded, never the recall: grow_for recalls shortfall plus buffer,
+     * and feeding that back would grow the buffer from its own value until it reached the carve. */
     std::vector  chunk_blocks_;
     std::vector  short_peak_;
     Pool*    pool_ = nullptr;
@@ -632,10 +543,12 @@ private:
     int64_t available_blocks(int32_t g) const;
     /* The buffer this group wants in hand, in blocks. See buffer_bytes(). */
     int64_t  buf_blocks(size_t i) const;
-    /* One past the highest block anything holds, to a bucket. */
+    /* One past the highest held block, rounded up to a bucket. */
     int64_t  held_top(size_t i) const;
     /* The blocks a loan of `tokens` takes off the top of group i. */
     int64_t  lent_blocks(size_t i, int64_t tokens) const;
+    /* Moves every lendable group's mark to a loan of `tokens`, unchecked (set_loan checks). */
+    void     apply_loan(int64_t tokens);
     int  grow_for(int32_t g, int64_t blocks);
     void note_held(int32_t g, int32_t b, int delta);
     bool      configured_ = false;
diff --git a/core/mem/kvtier.cpp b/core/mem/kvtier.cpp
index 72ed6b61..b39144e5 100644
--- a/core/mem/kvtier.cpp
+++ b/core/mem/kvtier.cpp
@@ -35,17 +35,18 @@ int IdleTiers::configure(const Config& c) {
     }
 
     char buf[512];
-    if (!any_on()) {
-        report_ = "kv tiers: off (no --prefix-cache-mib), so a finished conversation's KV stays "
-                  "in VRAM until the cache evicts it under pressure -- it is never copied to host "
-                  "memory, and what the pool is holding is mostly cache rather than live requests";
+    if (!host_on()) {
+        report_ = "kv tiers: off (no --prefix-cache-mib); a finished conversation's KV stays in "
+                  "VRAM until the cache evicts it";
     } else {
         std::snprintf(buf, sizeof buf,
                       "kv tiers: a finished conversation's KV is copied to host memory at once "
-                      "(%s, %lld entries) and its VRAM is given up when the expert loan or a "
-                      "request wants it; a full host tier drops its least recently used entries. "
-                      "One entry is %s",
+                      "(%s, %lld entries, %lld tokens of context) and its VRAM is given up when "
+                      "the expert loan or a request wants it; a full host tier drops its least "
+                      "recently used entries, the end of a conversation before its start. One "
+                      "entry is %s",
                       humanb(arena_.cap_bytes()).c_str(), (long long)arena_.capacity(),
+                      (long long)(arena_.capacity() * cfg_.block_tokens),
                       humanb(cfg_.entry_bytes).c_str());
         report_ = buf;
         if (cfg_.ckpt_bytes > 0) {
@@ -65,7 +66,6 @@ void IdleTiers::close() {
     reset();
 }
 
-/* The body of close(), for the caller that already holds the lock. */
 void IdleTiers::reset() {
     recs_.clear();
     sessions_.clear();
@@ -73,7 +73,7 @@ void IdleTiers::reset() {
     host_lru_.clear();
     wb_q_.clear();
     clean_q_.clear();
-    starved_ = 0;
+    room_.clear();
     wb_stuck_ = false;
     arena_.close();
     cfg_ = Config{};
@@ -88,12 +88,20 @@ void IdleTiers::unlist(Rec& r) {
     r.listed = false;
 }
 
-/* ONLY A RECORD WHOSE BYTES ARE ONLY OFF THE CARD. A device record -- clean or not -- is ordered by
- * the prefix cache's own LRU, and a second ordering of the same entries is the two-owner shape the
- * header's one-record rule exists to rule out. */
+/* Host records only: device records, clean or not, are ordered by the prefix cache's LRU (see the
+ * one-record rule in the header). */
+/* A use: stamps the record and moves a listed (host) one to the back of its list. */
+void IdleTiers::touch(const BlockHash& key, Rec& r, uint64_t now_ns) {
+    r.used_ns = now_ns;
+    if (r.listed) {
+        unlist(r);
+        relist(key, r);
+    }
+}
+
 void IdleTiers::relist(const BlockHash& key, Rec& r) {
     if (r.pending || r.tier == KVTier::Device || r.listed) return;
-    r.it = host_lru_.emplace_hint(host_lru_.end(), r.used_ns, key);
+    r.it = host_lru_.emplace_hint(host_lru_.end(), LruKey{ r.used_ns, r.depth }, key);
     r.listed = true;
 }
 
@@ -127,9 +135,6 @@ void IdleTiers::queue_clean(const BlockHash& key, Rec& r) {
 
 /* ------------------------------------------------------------------ the linear half */
 
-/* RECORDED, NOT MOVED. A snapshot is in host memory from the moment it is saved and stays in its
- * store slot until the cache retires it; the tiers keep its slot and position for the session
- * view. */
 void IdleTiers::note_snapshot(const BlockHash& key, int32_t slot, int64_t pos) {
     if (slot < 0) return;
     std::lock_guard lk(mu_);
@@ -144,49 +149,41 @@ void IdleTiers::release_snapshot(const BlockHash& key) {
     if (it == recs_.end()) return;
     Rec& r = it->second;
     r.ck_slot = -1;
-    /* A RECORD THAT ONLY EVER EXISTED FOR THE SNAPSHOT GOES WITH IT. note_snapshot creates one at
-     * commit time, which is mid-request and long before the chain is published; a request that
-     * never publishes -- a rebased block table, a cancel before the first whole block -- would
-     * otherwise leave a record with no blocks, no storage and no way to be reached again. */
+    /* A record that only existed for the snapshot goes with it. note_snapshot creates one
+     * mid-request; a request that never publishes (a rebased block table, a cancel before the
+     * first whole block) would otherwise leave an unreachable empty record. */
     if (!r.pending && r.tier == KVTier::Device && r.blocks.empty() && r.host_slot < 0)
         recs_.erase(it);
 }
 
 /* ------------------------------------------------------------------ the cache's notices */
 
-void IdleTiers::note_used(const BlockHash& key, const std::vector& blocks, uint64_t now_ns) {
-    if (!any_on()) return;
+void IdleTiers::note_used(const BlockHash& key, const std::vector& blocks, uint64_t now_ns,
+                          int64_t depth) {
+    if (!host_on()) return;
     std::lock_guard lk(mu_);
     Rec& r = recs_[key];
-    r.used_ns = now_ns;
     if (r.tier == KVTier::Device && !r.pending) r.blocks = blocks;
-    /* A record only moves on the host list when it is IN it. A device record is a timestamp and
-     * nothing else, which is what keeps this cheap enough to sit on the publish path -- the hash
-     * insert is the whole cost. */
-    if (r.listed) {
-        unlist(r);
-        relist(key, r);
-    }
+    /* Before touch, which files a host record under it. */
+    r.depth = depth;
+    /* For a device record this is a timestamp and a hash insert, cheap enough for the publish
+     * path. */
+    touch(key, r, now_ns);
     queue_copy(key, r);
 }
 
 void IdleTiers::note_hits(const BlockHash* keys, int64_t n, uint64_t now_ns) {
-    if (!any_on() || !keys || n <= 0) return;
+    if (!host_on() || !keys || n <= 0) return;
     std::lock_guard lk(mu_);
     for (int64_t i = 0; i < n; ++i) {
         auto it = recs_.find(keys[i]);
-        if (it == recs_.end()) continue;
-        Rec& r = it->second;
-        r.used_ns = now_ns;
-        if (r.listed) {
-            unlist(r);
-            relist(keys[i], r);
-        }
+        if (it != recs_.end()) touch(keys[i], it->second, now_ns);
     }
 }
 
-void IdleTiers::rebound(const BlockHash& key, const std::vector& blocks, uint64_t now_ns) {
-    if (!any_on()) return;
+void IdleTiers::rebound(const BlockHash& key, const std::vector& blocks, uint64_t now_ns,
+                        int64_t depth) {
+    if (!host_on()) return;
     std::lock_guard lk(mu_);
     Rec& r = recs_[key];
     if (r.pending) return;
@@ -195,6 +192,7 @@ void IdleTiers::rebound(const BlockHash& key, const std::vector& blocks
     r.tier = KVTier::Device;
     r.blocks = blocks;
     r.used_ns = now_ns;
+    r.depth = depth;
     queue_copy(key, r);
 }
 
@@ -207,18 +205,13 @@ bool IdleTiers::doomed(const BlockHash& key) const {
 IdleTiers::Stats IdleTiers::stats() const {
     std::lock_guard lk(mu_);
     Stats s = stats_;
-    /* What the block arena holds, clean copies included: counted off the arena rather than kept
-     * beside it, because every path that takes or returns a slot would otherwise have to remember
-     * to move a second number. */
+    /* Derived from the arena, clean copies included, so no separate counter can drift. */
     s.host_bytes = arena_.used_slots() * cfg_.entry_bytes;
     return s;
 }
 
-/* AND EVERY CONVERSATION THAT STARTED HERE. A chain whose first block has gone cannot be hit at any
- * length -- a prefix hit starts at position zero. Leaving the row behind would report blocks the
- * pool has already handed to somebody else as this session's, and would hold its whole chain in
- * memory for a conversation that can never come back. Called wherever an entry goes for good: the
- * cache's forget(), and the sites here that drop an off-device entry and tell the cache. */
+/* A chain whose first block has gone can never be hit (see roots_). Called wherever an entry goes
+ * for good: forget(), and the sites here that drop an off-device entry and tell the cache. */
 void IdleTiers::drop_rooted(const BlockHash& key) {
     auto ro = roots_.find(key);
     if (ro == roots_.end()) return;
@@ -233,9 +226,7 @@ void IdleTiers::forget(const BlockHash& key) {
     if (it == recs_.end()) return;
     Rec& r = it->second;
     if (r.pending) {
-        /* The engine is mid-transfer against this record. Erasing it now is exactly the
-         * use-after-free the one-record rule exists to prevent, so mark it and let report()
-         * finish the job and clean up. */
+        /* Mid-transfer: erasing now would be a use-after-free. report() cleans up. */
         r.doomed = true;
         return;
     }
@@ -261,16 +252,15 @@ bool IdleTiers::resident_off_device(const BlockHash& key) const {
 
 bool IdleTiers::writeback_waiting() const {
     std::lock_guard lk(mu_);
-    /* NOT WHILE NOTHING CAN MOVE. An arena full of the copies of entries still in VRAM has nothing
-     * a capacity drop may take, so a plan would pop the queue, find no slot and put it back, every
-     * tick, until a slot is freed or a VRAM copy is given up -- which is what ends the wait. */
+    /* Not while nothing can move: an arena full of copies of entries still in VRAM offers nothing
+     * to drop, so wait until a slot is freed or a VRAM copy is given up. */
     if (wb_stuck_ && arena_.full()) return false;
     return !wb_q_.empty() && host_on();
 }
 
 bool IdleTiers::starved() const {
     std::lock_guard lk(mu_);
-    return starved_ > 0;
+    return !room_.empty();
 }
 
 void IdleTiers::plan_writeback(int64_t max_entries, std::vector* out) {
@@ -293,11 +283,8 @@ void IdleTiers::plan_writeback(int64_t max_entries, std::vector* out) {
         out->push_back(std::move(j));
     }
 
-    /* THE HOST SLOTS, AS RUNS. Taken for the whole batch at once so that entries planned together
-     * sit together in the arena and each run crosses the link as one copy. A batch the arena
-     * cannot hold is cut where the arena ran out: the entries past that point go back to the
-     * front of the queue, and the maintenance plan is told how many copies were refused so it can
-     * make that much room. */
+    /* Allocate host slots for the whole batch as runs, so each run crosses the link as one copy.
+     * Jobs past where the arena ran out are refused; see below. */
     const int64_t want = (int64_t)(out->size() - first);
     std::vector slots;
     slots.reserve((size_t)want);
@@ -316,7 +303,6 @@ void IdleTiers::plan_writeback(int64_t max_entries, std::vector* out) {
             ++i;
             continue;
         }
-        ++starved_;
         refused.push_back(j.key);
         out->erase(out->begin() + (long)i);
     }
@@ -326,14 +312,56 @@ void IdleTiers::plan_writeback(int64_t max_entries, std::vector* out) {
         unlist(r);
         r.pending = true;
     }
-    /* Back where they were, at the front and in order, so the oldest conversation is still the
-     * first copied once there is room. */
+    if (refused.empty()) return;
+
+    /* A refused copy is worth making room for only by dropping a host entry worth less than it.
+     * The most valuable refused copies are matched with the least valuable host entries; one
+     * that finds none leaves the queue, since any room made for it would cost more than it
+     * saves: it would drop a conversation's start to keep its end, or a newer conversation to
+     * keep an older one. Its entry stays in VRAM only and is copied again when a turn uses it. */
+    const LruOrder less;
+    std::vector> by_value;
+    by_value.reserve(refused.size());
+    for (const BlockHash& k : refused) {
+        const Rec& r = recs_[k];
+        by_value.push_back({ LruKey{ r.used_ns, r.depth }, k });
+    }
+    std::sort(by_value.begin(), by_value.end(),
+              [&less](const auto& a, const auto& b) { return less(b.first, a.first); });
+    std::unordered_set keep;
+    int64_t held = 0;
+    auto victim = host_lru_.begin();
+    for (const auto& kv : by_value) {
+        if (victim != host_lru_.end() && less(victim->first, kv.first)) {
+            room_.push_back(kv.first);
+            keep.insert(kv.second);
+            ++victim;
+        } else {
+            ++held;
+        }
+    }
+    /* Requeue at the front, in order, so the oldest is still copied first. */
     for (auto it = refused.rbegin(); it != refused.rend(); ++it) {
+        if (!keep.count(*it)) continue;
         auto ri = recs_.find(*it);
         if (ri == recs_.end() || ri->second.queued) continue;
         wb_q_.push_front(*it);
         ri->second.queued = true;
     }
+    if (held == 0) return;
+    stats_.held_back += held;
+    const uint64_t now = rad_mono_ns();
+    if (held_back_warned_ns_ == 0 || now - held_back_warned_ns_ >= 60ull * 1000000000ull) {
+        held_back_warned_ns_ = now;
+        RAD_WARN("kv tiers: %lld entries (%lld tokens of context) got no host copy: the host "
+                 "tier (--prefix-cache-mib, %s, %lld tokens) is full of context used more "
+                 "recently or nearer the start of its conversation. They stay in VRAM only and "
+                 "are prefilled again once VRAM gives them up; a larger --prefix-cache-mib holds "
+                 "more. Counted in /sessions moved.held_back",
+                 (long long)held, (long long)(held * cfg_.block_tokens),
+                 humanb(arena_.cap_bytes()).c_str(),
+                 (long long)(arena_.capacity() * cfg_.block_tokens));
+    }
 }
 
 void IdleTiers::take_clean(std::vector* out) {
@@ -372,13 +400,14 @@ void IdleTiers::drop_commit(const BlockHash& key) {
 void IdleTiers::plan(int budget, std::vector* out) {
     if (!host_on() || budget <= 0) return;
     std::lock_guard lk(mu_);
-    /* HOW MANY, AND NOT "UNTIL THERE IS ROOM". A queued drop does not free its slot until the
-     * engine reports it, so a loop that tested the arena would queue a drop for every entry on the
-     * list and empty the whole tier to make room for one. The copies refused since the last plan
-     * say how much room was wanted; this frees exactly that much, least recently used first. */
-    const int64_t want = std::min(starved_, budget);
-    starved_ = 0;
+    /* Drop one entry for each copy refused, least valuable first, and only one worth less than
+     * the copy it makes room for (room_ runs most valuable first, the list least valuable first,
+     * so the first pair that fails ends the plan). Looping until the arena has room would empty
+     * the tier, since a queued drop frees its slot only when the engine reports it. */
+    const int64_t want = std::min((int64_t)room_.size(), budget);
+    const LruOrder less;
     for (int64_t k = 0; k < want && !host_lru_.empty();) {
+        if (!less(host_lru_.begin()->first, room_[(size_t)k])) break;
         auto ri = recs_.find(host_lru_.begin()->second);
         if (ri == recs_.end()) { host_lru_.erase(host_lru_.begin()); continue; }
         Rec& r = ri->second;
@@ -392,13 +421,14 @@ void IdleTiers::plan(int budget, std::vector* out) {
         out->push_back(std::move(j));
         ++k;
     }
+    room_.clear();
 }
 
 void IdleTiers::expired(uint64_t cutoff_ns, size_t max, std::vector* out) const {
     std::lock_guard lk(mu_);
-    /* The list holds no record with a job out (relist), so every key it yields can go now. */
+    /* The list holds no pending record (relist), so every key here can go now. */
     for (auto it = host_lru_.begin();
-         it != host_lru_.end() && it->first < cutoff_ns && out->size() < max; ++it)
+         it != host_lru_.end() && it->first.used_ns < cutoff_ns && out->size() < max; ++it)
         out->push_back(it->second);
 }
 
@@ -424,21 +454,19 @@ void IdleTiers::report(const TierJob& job, bool ok, uint64_t now_ns) {
     std::lock_guard lk(mu_);
     auto it = recs_.find(job.key);
     if (it == recs_.end()) {
-        /* Nothing names the slots a copy was handed but the job itself. */
+        /* Only the job names a write-back's slot. */
         if (job.kind == TierJob::Kind::WriteBack) give_slot(job.host_slot);
         return;
     }
     Rec& r = it->second;
     r.pending = false;
-    /* A promotion the chain was cut before is not a failure: nothing was tried. */
+    /* An unstarted promotion is not a failure: nothing was tried. */
     if (!ok && (job.kind != TierJob::Kind::ToDevice || job.started)) ++stats_.failures;
 
-    /* A record that was forgotten mid-transfer is finished off here and nowhere else. Doing it at
-     * the top, before the per-kind handling, means no branch below has to remember to check. */
+    /* A record forgotten mid-transfer is finished off here, before the per-kind handling. */
     if (r.doomed) {
-        /* THE JOB'S SLOT AND THE RECORD'S ARE NOT THE SAME SLOT on every path. A copy's host slot
-         * is the job's until it reports; freeing only the record's would leak it, and freeing the
-         * job's as well where it IS the record's would return one slot twice. */
+        /* The job's slot may or may not be the record's: a write-back's slot belongs to the job
+         * until it reports. Free each distinct slot once. */
         if (job.host_slot >= 0 && job.host_slot != r.host_slot) give_slot(job.host_slot);
         free_host(r);
         recs_.erase(it);
@@ -467,29 +495,22 @@ void IdleTiers::report(const TierJob& job, bool ok, uint64_t now_ns) {
             if (ok) {
                 r.tier = KVTier::Device;
                 r.blocks = job.blocks;
-                /* THE HOST COPY IS KEPT, which is what makes the entry clean the moment it lands:
-                 * its VRAM copy can go again at no cost, and the next copy this conversation needs
-                 * is only of the tokens its next turn adds. */
+                /* The host copy is kept, so the entry is clean on landing. */
                 r.host_slot = job.host_slot;
-                /* THE CLOCK RESTARTS: the entry came back because a request is about to hit it. */
+                /* A request is about to hit it. */
                 if (now_ns) r.used_ns = now_ns;
                 ++stats_.promoted;
                 queue_clean(job.key, r);
                 return;
             }
             if (!job.started) {
-                /* NEVER STARTED: the reservation ran out before this entry, and nothing about it
-                 * was touched. It stays exactly where it was. */
+                /* Never started: the reservation ran out first. It stays on the host tier. */
                 relist(job.key, r);
                 return;
             }
-            /* A FAILED PROMOTION DROPS THE ENTRY, AND THE CACHE MUST HEAR ABOUT IT. Every other
-             * failure here can leave the record where it was, because nothing was consumed. This
-             * one cannot: the scatter may have written some layers and not others, so the blocks
-             * hold a mixture and the cached tensors are no longer a function of the tokens. A miss
-             * is always safe and this is the only way to guarantee one -- but the prefix cache
-             * still holds an entry naming blocks that are not ours any more, and left alone it
-             * would serve them. */
+            /* A started promotion that failed may have scattered some layers and not others, so
+             * the entry is dropped to force a miss, and the cache is told so it stops naming the
+             * blocks. */
             if (job.host_slot >= 0 && job.host_slot != r.host_slot) give_slot(job.host_slot);
             free_host(r);
             recs_.erase(it);
@@ -510,10 +531,8 @@ void IdleTiers::report(const TierJob& job, bool ok, uint64_t now_ns) {
 
 /* ------------------------------------------------------------------ the session view */
 
-/* A PREFIX RELATION IS WHAT MAKES TWO CHAINS THE SAME CONVERSATION. The blocks are content
- * addressed, so turn N's chain is byte for byte turn N-1's with more on the end; anything that
- * diverges anywhere is a different transcript from that point on, however much of a system prompt
- * it shares. */
+/* Two chains are the same conversation when one is a prefix of the other: blocks are content
+ * addressed, so turn N's chain is turn N-1's plus more. */
 static bool chain_extends(const std::vector& shorter,
                           const std::vector& longer) {
     if (shorter.size() > longer.size()) return false;
@@ -526,24 +545,15 @@ void IdleTiers::note_session(uint64_t id, const std::vector& chain, i
     if (chain.empty()) return;
     std::lock_guard lk(mu_);
 
-    /* A SESSION IS A LEAF OF THE PREFIX TRIE, and that is what decides every case here. The turns
-     * of one conversation arrive under different ids -- the id is the request's, and a
-     * conversation is a new request every turn -- so without this the table grows a row a turn,
-     * each holding its own copy of a chain that is a prefix of the next one's and none of them
-     * ever revisited. Candidates are the sessions sharing this root, which is a handful at most.
+    /* A session is a leaf of the prefix trie. Each turn arrives under a new request id, so the
+     * candidates are the sessions sharing this root (a handful at most):
      *
-     * A CHAIN THIS ONE EXTENDS HAS STOPPED BEING A LEAF, so it is absorbed: its blocks are the
-     * first blocks of this one, byte for byte, because the chain is content addressed.
-     *
-     * A CHAIN THAT EXTENDS THIS ONE MEANS THIS ONE IS NOT A LEAF EITHER. That happens when a
-     * preempted request re-prefills and republishes SHORTER than the conversation it belongs to;
-     * recording it would shrink the row to less than the pool is holding, and there may be
-     * several conversations below it -- two clients past the same system prompt -- with nothing
-     * to say which of them republished. So the most recent of them is touched and no row is
-     * added, which is the one answer that is wrong about nothing. */
+     *   - a chain this one extends is no longer a leaf and is absorbed;
+     *   - a chain that extends this one means this is not a leaf either (a preempted request
+     *     republishing shorter). Several conversations may extend it, so the most recent one is
+     *     touched and no row is added. */
     uint64_t first_seen = 0;
-    /* A conversation's label outlives the turn that sent it: a later turn without one keeps the
-     * name an earlier one gave. */
+    /* A label persists across later turns that send none. */
     std::string kept_label = label;
     bool absorbed = false;
     std::vector& at_root = roots_[chain[0]];
@@ -596,20 +606,14 @@ void IdleTiers::drop_session(uint64_t id) {
     sessions_.erase(it);
 }
 
-void IdleTiers::forget_session(uint64_t id) {
-    std::lock_guard lk(mu_);
-    drop_session(id);
-}
-
 std::vector IdleTiers::sessions(Occupancy* occ) const {
-    /* The view's hold on the lock, a slice at a time (YieldingMutex). */
+    /* One slice's hold on the lock (YieldingMutex). */
     struct Slice {
         YieldingMutex& m;
         explicit Slice(YieldingMutex& mu) : m(mu) { m.lock_after_others(); }
         ~Slice() { m.unlock(); }
     };
-    /* Records a slice visits: a few microseconds of hash lookups, the most an engine-side taker
-     * arriving mid-slice waits. */
+    /* Records per slice: a few microseconds of hash lookups, the longest an engine thread waits. */
     constexpr size_t kSliceRecords = 64;
 
     std::vector out;
@@ -628,19 +632,14 @@ std::vector IdleTiers::sessions(Occupancy* occ) const {
             out.push_back(std::move(si));
         }
     }
-    /* SNAPSHOTS IN THE STORE, each once. The store is the engine's and is not read from this
-     * thread -- but this walk visits every record a stored conversation reaches, so it counts them
-     * here. They are sparse, one per checkpoint interval, so the set stays small beside the walk
-     * that fills it. */
+    /* Distinct snapshots reached by the walk, for Occupancy. The store itself is the engine's and
+     * is not read from this thread. One per checkpoint interval, so the set stays small. */
     std::unordered_set host_snaps;
     size_t kept = 0;
     for (size_t k = 0; k < out.size(); ++k) {
         SessionInfo& si = out[k];
-        /* The histogram is computed here and stored nowhere. A session's blocks move one tier at
-         * a time under a bounded plan, so a second copy of this would be stale between the pass
-         * that moves the first block and the pass that moves the last -- which is exactly the
-         * window an operator is looking at the page during. The session is found again at every
-         * slice: between slices it may have been absorbed into a longer one or dropped, and a
+        /* The histogram is computed, never stored, since blocks move a few at a time. The session
+         * is looked up again each slice: in between it may have been absorbed or dropped, and a
          * row that is gone is left out. */
         bool gone = false;
         for (size_t at = 0;;) {
@@ -659,8 +658,7 @@ std::vector IdleTiers::sessions(Occupancy* occ) const {
                     case KVTier::Device: ++si.on_device; break;
                     case KVTier::Host:   ++si.on_host;   break;
                 }
-                /* THE LINEAR HALF, which is in host memory from the moment it is saved, whatever
-                 * tier its blocks are on. */
+                /* Snapshots are in host memory whatever tier the blocks are on. */
                 if (rr.ck_slot >= 0) {
                     ++si.snapshots;
                     if (occ) host_snaps.insert(h);
@@ -683,8 +681,7 @@ std::vector IdleTiers::sessions(Occupancy* occ) const {
         Slice lk(mu_);
         occ->host_bytes = arena_.used_slots() * cfg_.entry_bytes +
                           (int64_t)host_snaps.size() * cfg_.ckpt_bytes;
-        /* What the operator gave the block arena and the snapshot store -- the same scope as
-         * `host_bytes` above, which counts both. */
+        /* Block arena plus snapshot store, the same scope as `host_bytes`. */
         occ->host_cap_bytes = (host_on() ? cfg_.host_cap_bytes : 0) +
                               cfg_.ckpt_slots * cfg_.ckpt_bytes;
     }
diff --git a/core/mem/kvtier.h b/core/mem/kvtier.h
index 3c15e6bd..585eef76 100644
--- a/core/mem/kvtier.h
+++ b/core/mem/kvtier.h
@@ -1,79 +1,51 @@
 /* kvtier.h -- where a finished conversation's KV is kept once VRAM has a better use for it
- * (spec §7.3): VRAM, then host memory, and nowhere else.
+ * (spec §7.3): VRAM, then host memory.
  *
- * The prefix cache holds a KV reference on every block it indexes, so a finished turn's context
- * survives into the next one. That is the whole value of it, and it is also the whole cost: those
- * blocks are the most valuable thing in the pool while the session is live and the least valuable
- * thing in it once the session stops -- and on a card whose experts do not fit, VRAM holding an
- * idle conversation is VRAM every decode step pays for across the link.
+ * The prefix cache keeps a finished turn's blocks referenced for the next turn. They are valuable
+ * while the session is live and dead weight once it stops; on a card whose experts do not fit,
+ * VRAM held by an idle conversation costs every decode step link traffic.
  *
- * ============================== COPY ON IDLE, FREE ON DEMAND ====================================
- *
- * An entry is COPIED to host memory as soon as the request that published it finishes, and its
- * VRAM copy is kept. From then on the entry is CLEAN: the pool and the host hold the same bytes,
- * so giving the VRAM copy up costs nothing at all -- no transfer, no wait, only the cache's
- * reference -- and it is given up the moment something wants the memory: the expert slab's loan,
- * or an allocation the free list cannot serve. A conversation that comes back before either
- * happens resumes from VRAM for free; one that comes back after is restored from its host copy,
- * and KEEPS that copy, so the turn after it copies only the tokens that turn added.
+ * Copy on idle, free on demand. An entry is copied to host memory as soon as the request that
+ * published it finishes, and its VRAM copy is kept. The entry is then clean: giving up the VRAM
+ * copy costs only the cache's reference, and that happens as soon as something wants the memory
+ * (the expert slab's loan, or an allocation the free list cannot serve). A conversation that
+ * returns earlier resumes from VRAM; one that returns later is restored from host and keeps the
+ * host copy, so its next turn copies only the tokens that turn added.
  *
  *     published --(copy, at once)--> clean on device --(memory wanted)--> host
  *                                        ^                                  |
  *                                        +------------(a hit restores)------+
  *
- * HOST MEMORY IS THE LAST TIER. When a copy needs a slot and the arena is full, the oldest
- * entries only the host holds are dropped, as many as the copies refused. Nothing is written to a
- * drive: a tier there wears it at the rate the server prefills -- every block and every snapshot a
- * prompt produces -- to spare a re-prefill only for what outgrows VRAM and host memory together.
+ * Host memory is the last tier. When a copy needs a slot and the arena is full, the least
+ * valuable host-only entries are dropped, one per copy refused, and only ones less valuable than
+ * that copy: older, or as old and deeper in their chain. A copy nothing can make room for is not
+ * taken and its entry stays in VRAM only. A conversation larger than the tier so keeps its start
+ * on the host, the part a lookup reaches first, instead of dropping its first block for its last
+ * one. Nothing goes to disk: a disk tier would be written at the prefill rate to save re-prefills
+ * only for what outgrows VRAM and host memory together. Every entry also expires after
+ * --prefix-cache-ttl seconds unused, from whichever tier holds it (PrefixCache::expire).
  *
- * AND EVERY ENTRY EXPIRES. One no request has used for --prefix-cache-ttl seconds leaves the cache
- * from whichever tier holds it (PrefixCache::expire); it is not moved anywhere first.
+ * There is no idle threshold for leaving VRAM: a clean entry costs nothing to keep until the
+ * memory is wanted and nothing to release once it is. Restoring a 200K-token prefix over PCIe
+ * takes a fraction of a second; re-prefilling it takes minutes.
  *
- * THERE IS NO IDLE THRESHOLD ON THE WAY OUT OF VRAM, and that is the point of the design rather
- * than an omission. A threshold is a guess at when an entry stops being worth its VRAM, made in
- * seconds by an operator; a clean entry answers the question itself, because keeping it costs
- * nothing until the memory is wanted and releasing it costs nothing once it is.
+ * This object moves no bytes. It decides what moves and hands out TierJob lists; the engine runs
+ * them on its transfer stream and reports back, as with KVManager's BlockCopy and
+ * take_pending_copies. core/mem has no stream, and the step path must not synchronise (spec §5.4).
  *
- * WHY MOVING BEATS DROPPING, stated once so the costs can be argued about in the right units:
- * dropping a 200K-token prefix costs a re-prefill, which is minutes. Restoring it costs a copy
- * over PCIe, which is a fraction of a second. The two are not the same order of magnitude.
+ * Addressing: the pool is layer-major (core/mem/kv.h). Layer i of a paged group owns
+ * `[base + i*layer_stride, + layer_stride)`, and a block within it starts at
+ * `block_index * layer_bytes_per_block()`. A logical block is n_layers fragments of a few hundred
+ * bytes, not one extent; `base + block * bytes_per_block` would address n_layers blocks of layer
+ * zero. Such corruption yields fluent, plausible, wrong text. The unit of transfer is therefore
+ * one layer of many blocks: within a layer blocks are dense rows, so packing is gather_rows and
+ * restoring is scatter_rows, one launch per (group, layer) per batch.
  *
- * ============================== THIS OBJECT MOVES NO BYTES ======================================
- *
- * It decides WHAT should move and hands the work out as a list of TierJob. The engine executes
- * them on its transfer stream and reports back. That split is not decoration: `KVManager` already
- * works this way (BlockCopy, take_pending_copies) for the same reason -- core/mem has no stream,
- * and a synchronisation on the step path is what this design spends itself avoiding (spec §5.4).
- * A second mechanism for moving KV bytes would be a second place to get the pool's addressing
- * wrong.
- *
- * ============================== THE ADDRESSING, WHICH IS THE TRAP ==============================
- *
- * THE POOL IS LAYER-MAJOR (core/mem/kv.h). Layer i of a paged group owns
- * `[base + i*layer_stride, + layer_stride)`, and inside that a block is
- * `block_index * layer_bytes_per_block()`. A logical block is therefore NOT a contiguous extent:
- * it is `n_layers` fragments, one per layer, and on a production model a fragment is a few hundred
- * bytes. `base + block * bytes_per_block` addresses something else entirely -- roughly `n_layers`
- * consecutive blocks OF LAYER ZERO -- and a tier built on it moves other sequences' data and
- * restores a jumble. Corrupt KV does not read as babble; it reads as fluent, deterministic,
- * plausible, wrong text, and nothing short of a byte comparison against a known-good run finds it.
- *
- * So the unit of transfer here is not a block. It is A LAYER'S WORTH OF MANY BLOCKS, which is the
- * shape the pool is already in: within one layer the group's blocks are dense rows of
- * `layer_bytes_per_block()` each, so packing an arbitrary set of them is exactly `gather_rows`
- * and restoring them is exactly `scatter_rows`. One launch per (group, layer) per batch, however
- * many entries the batch holds.
- *
- * ============================== ONE RECORD, ONE TIER, ONE LIST ==================================
- *
- * An entry that can live in either of two tiers must not be on BOTH tiers' LRU lists: each tier's
- * eviction path then invalidates references the other holds, and every such pair is a
- * use-after-free. The rule here is that a key has exactly one Rec,
- * a Rec is in exactly one tier, and a Rec is in at most that tier's list. A CLEAN device record
- * is on no list: the copy it keeps off the card is what lets the VRAM copy go, and the tiers'
- * lists are for entries no longer in VRAM. A Rec with a transfer through the pool outstanding is
- * `pending` and is in no list either: it cannot be chosen as a victim, cannot be planned again,
- * and cannot be erased until the engine reports the job finished or failed.
+ * One record, one tier, one list. If an entry sat on two tiers' LRU lists, each tier's eviction
+ * would invalidate the other's references. So a key has exactly one Rec, in exactly one tier, on
+ * at most that tier's list. A clean device record is on no list (the lists hold entries no longer
+ * in VRAM). A Rec with a transfer outstanding is `pending` and on no list: it cannot be a victim,
+ * be planned again or be erased until the engine reports the job.
  */
 #pragma once
 #include "mem/hostarena.h"
@@ -81,11 +53,11 @@
 #include "mem/prefix.h"
 #include "rad_core.h"
 
+#include 
 #include 
 #include 
 #include 
 #include 
-#include 
 #include 
 #include 
 #include 
@@ -97,9 +69,8 @@ namespace rad {
 enum class KVTier : uint8_t { Device = 0, Host = 1 };
 const char* kv_tier_name(KVTier t);
 
-/* What the engine is being asked to do. One job is one entry moving one step. The block ids are
- * carried in the job rather than looked up when it runs, because the whole point of `pending` is
- * that nothing may touch the record in between. */
+/* One entry moving one step. Block ids travel in the job because the record is `pending` and
+ * must not be read until the job reports. */
 struct TierJob {
     enum class Kind : uint8_t {
         WriteBack,      /* gather_rows out of the pool into a host slot; the entry stays in VRAM */
@@ -108,18 +79,15 @@ struct TierJob {
     };
     Kind      kind = Kind::WriteBack;
     BlockHash key;
-    /* Per cached group, in PrefixCache::cached_groups() order. For a write-back these are the
-     * blocks to read; for a promotion they are filled in by the engine with the blocks it
-     * allocated. */
+    /* Per cached group, in PrefixCache::cached_groups() order: the blocks to read for a
+     * write-back, or the blocks the engine allocated for a promotion. */
     std::vector blocks;
     int32_t   host_slot = -1;
     int64_t   bytes = 0;
 
-    /* A PROMOTION THAT WAS NEVER STARTED, as opposed to one that failed part of the way through.
-     * A restore reserves every block before it moves a byte, and a chain that did not fit is cut
-     * where the reservation ran out: the entries past that point were not touched, their host
-     * copies are exactly what they were, and they stay on the host tier. Only an entry whose
-     * scatter may have run is dropped on failure. */
+    /* Whether a promotion's scatter may have run. A restore reserves every block first and cuts
+     * the chain where the reservation ran out; entries past the cut were never started and stay
+     * on the host tier. Only a started promotion drops its entry on failure. */
     bool      started = false;
 };
 
@@ -130,143 +98,117 @@ public:
         int64_t host_cap_bytes  = 0;   /* 0 is off */
         int64_t entry_bytes     = 0;   /* one entry: sum over cached groups of bytes_per_block */
         /* ---- the linear half ----
-         * `ckpt_bytes` is ONE SNAPSHOT, every rank's shard of it, laid out exactly like
-         * `entry_bytes`. The snapshots live in the engine's checkpoint store, `ckpt_slots` deep,
-         * which is reported here and not allocated: --prefix-cache-mib is the blocks' alone. */
+         * `ckpt_bytes` is one snapshot including every rank's shard, like `entry_bytes`. The
+         * snapshots live in the engine's checkpoint store, `ckpt_slots` deep; reported here, not
+         * allocated (--prefix-cache-mib covers blocks only). */
         int64_t ckpt_bytes      = 0;
         int64_t ckpt_slots      = 0;   /* the checkpoint store's capacity, for the report and view */
+        /* Tokens one entry covers (the cache's block size), for the report and the warning when
+         * the tier cannot hold a conversation. */
+        int64_t block_tokens    = 0;
     };
 
     int  configure(const Config& c);
     void close();
     bool host_on() const { return cfg_.host_cap_bytes > 0 && arena_.enabled(); }
-    bool any_on()  const { return host_on(); }
     std::string report() const;
 
-    /* Called by PrefixCache whenever an entry is inserted. The blocks come with it because a copy
-     * needs them and the map is the only place they would otherwise be read from -- at which point
-     * the tiers would hold a second copy of the cache's own bookkeeping and the two could
-     * disagree. A record with no host copy is queued for one here: publishing is the moment a
-     * request has stopped writing the entry, which is the moment it can be copied. */
-    void note_used(const BlockHash& key, const std::vector& blocks, uint64_t now_ns);
-    /* THE HIT HALF OF THAT, for a lookup that matched `n` blocks of a chain. Only the idle clock
-     * moves: a hit carries no new block ids, and it creates no record for an entry the tiers were
-     * never told about. One lock for the whole chain, since a long prefix is thousands of blocks. */
+    /* PrefixCache published this entry with these blocks. A record without a host copy is queued
+     * for one: once published, the request has stopped writing it. `depth` is the entry's block
+     * index in its chain; among entries used at the same moment the deeper one is worth less. */
+    void note_used(const BlockHash& key, const std::vector& blocks, uint64_t now_ns,
+                   int64_t depth = 0);
+    /* A lookup hit `n` blocks of a chain. Only the idle clock moves; no records are created. One
+     * lock for the whole chain, since a long prefix is thousands of blocks. */
     void note_hits(const BlockHash* keys, int64_t n, uint64_t now_ns);
-    /* The entry is gone from the cache for good -- evicted, or its blocks released. Any tier
-     * storage it held is returned. A record with work outstanding is marked instead of erased and
-     * is cleaned up when the job reports. */
+    /* The entry left the cache for good; its tier storage is returned. A record with a job out is
+     * marked `doomed` instead and erased when the job reports. */
     void forget(const BlockHash& key);
-    /* AN OFF-DEVICE ENTRY WAS RECOMPUTED. A request that could not reach the host copy -- a
-     * restore that did not fit, a chain past the point a promotion was cut -- computes the same
-     * tokens again and publishes them, and the cache takes those blocks as the entry's device
-     * copy. The tier copy goes: two copies of one entry computed by two different batches agree
-     * only to the rounding the batch shape allows, and a record that called them the same bytes
-     * would restore the older one over a pool that holds the newer. The record is a fresh device
-     * record, queued for a copy of its own. */
-    void rebound(const BlockHash& key, const std::vector& blocks, uint64_t now_ns);
+    /* An off-device entry was recomputed by a request that could not reach the host copy, and the
+     * cache took its blocks as the device copy. The tier copy is dropped (two batches' results
+     * agree only to batch-shape rounding) and the record is requeued for a fresh copy. */
+    void rebound(const BlockHash& key, const std::vector& blocks, uint64_t now_ns,
+                 int64_t depth = 0);
 
-    /* WHERE IS IT. Device for anything this object has never been told about, which is the right
-     * answer: an entry the cache holds and the tiers have not touched is in the pool. */
+    /* Device for keys this object has never seen: the cache holds them in the pool. */
     KVTier tier_of(const BlockHash& key) const;
     bool   resident_off_device(const BlockHash& key) const;
 
     /* ---------------- copy on idle ----------------
      *
-     * The records waiting for a host copy, up to `max_entries`, as WriteBack jobs with their host
-     * slots already allocated. Oldest first, so a conversation that went idle before another is
-     * copied before it. Blocks only: a snapshot is in host memory from the moment it is saved.
+     * Up to `max_entries` records waiting for a host copy, oldest first, as WriteBack jobs with
+     * host slots allocated. Blocks only: snapshots are already in host memory.
      *
-     * Every record named by a returned job is `pending` until report() is called for it. What an
-     * arena too full to take the batch cannot hold stays queued, and the next maintenance plan
-     * drops that many of the oldest host-only entries. */
+     * Each returned record is `pending` until report(). A job the full arena cannot take stays
+     * queued when a host-only entry is worth less than it, and the next plan() drops one such
+     * entry for it; otherwise it leaves the queue and its entry stays in VRAM only (Stats::
+     * held_back, and a warning naming --prefix-cache-mib). */
     void plan_writeback(int64_t max_entries, std::vector* out);
     bool writeback_waiting() const;
-    /* Has the arena refused a copy since the last maintenance plan? That plan is then due now. */
+    /* The arena refused a copy since the last plan(), so a plan is due now. */
     bool starved() const;
 
-    /* THE VRAM COPIES THAT CAN GO, as the entries that became clean since the last call. The
-     * cache decides whether each one actually goes -- a block a running sequence also holds would
-     * free nothing -- and reports what it did through drop_commit. A key handed out here and not
-     * dropped is the cache's to ask about again. */
+    /* Entries that became clean since the last call. The cache decides whether each VRAM copy
+     * actually goes (a block a running sequence holds would free nothing), reports drops through
+     * drop_commit, and re-asks about the rest itself. */
     void take_clean(std::vector* out);
-    /* Can this entry's blocks leave VRAM for nothing, right now: its host copy has landed and no
-     * job is out on the record. */
+    /* Host copy landed and no job out: the blocks can leave VRAM at no cost. */
     bool droppable(const BlockHash& key) const;
-    /* The cache released the blocks. The record is now a host record with its copy, on the host
-     * tier's list like any other. Its snapshot stays in its slot: the store is not the pool, and
-     * the blocks leaving frees nothing there. */
+    /* The cache released the blocks; the record becomes a host record on the host list. Its
+     * snapshot stays in its store slot. */
     void drop_commit(const BlockHash& key);
 
     /* ---------------- capacity ----------------
      *
-     * The copies the arena refused since the last plan are made room for by dropping that many of
-     * the oldest host-only entries, as DropHost jobs; `budget` bounds one plan. */
+     * Make room for the copies refused since the last plan, one DropHost job each, taking the
+     * least valuable host-only entries and only ones worth less than the copy they make room
+     * for; `budget` bounds one plan. */
     void plan(int budget, std::vector* out);
 
     /* ---------------- expiry ----------------
      *
-     * THE HOST RECORDS NO REQUEST HAS USED SINCE `cutoff_ns`, oldest first, up to `max`: what
-     * --prefix-cache-ttl takes out of host memory. The cache drops each one (drop_offdevice) and
-     * the record goes with it; a record with a job out is passed over and asked about again. */
+     * Host records unused since `cutoff_ns`, oldest first, up to `max` (--prefix-cache-ttl). The
+     * cache drops each one; records with a job out are not listed and are reconsidered later. */
     void expired(uint64_t cutoff_ns, size_t max, std::vector* out) const;
 
-    /* A promotion, asked for by a lookup that hit off-device. Returns false when the entry is not
-     * in host memory or already has work outstanding. */
+    /* A promotion for a lookup that hit off-device. False when the entry is not in host memory or
+     * has a job out. */
     bool plan_promote(const BlockHash& key, TierJob* out);
 
-    /* The engine finished (or failed) a job. On failure the record returns to the state it was in
-     * with its storage intact, EXCEPT for a failed ToDevice that had started, which cannot leave a
-     * half-scattered pool behind and so drops the entry. A successful ToDevice restarts the
-     * record's clock at `now_ns` when one is given: the promotion happened because something is
-     * about to use it. */
+    /* The engine finished or failed a job. A failure restores the record's previous state with
+     * its storage intact, except a started ToDevice, which may have half-scattered and so drops
+     * the entry. A successful ToDevice restarts the record's clock at `now_ns` when nonzero. */
     void report(const TierJob& job, bool ok, uint64_t now_ns = 0);
 
-    /* WAS THIS KEY FORGOTTEN WHILE ITS JOB WAS OUT -- or is it not known at all. The engine asks
-     * before acting on a finished job's blocks: an entry the cache evicted mid-transfer had its
-     * references released by the eviction, and anything done in its name afterwards would be done
-     * to blocks somebody else now holds. */
+    /* The key was forgotten while its job was out, or is unknown. The engine checks this before
+     * touching a finished job's blocks, which may now belong to another sequence. */
     bool doomed(const BlockHash& key) const;
 
-    /* ============================ WHEN THE BYTES ARE GONE, SO IS THE ENTRY ====================
-     *
-     * A record erased while its bytes are OFF-DEVICE -- a capacity drop, a promotion that failed,
-     * an expiry -- leaves the prefix cache holding an entry whose block ids the pool has already
-     * given to somebody else. `resident_off_device` then answers false, because there is no
-     * record any more, and the cache would serve those ids as an ordinary hit: one conversation
-     * gets another's context, as fluent and plausible text.
-     *
-     * So the tiers tell the cache, at every site that erases an off-device record, and the cache
-     * drops the entry WITHOUT releasing blocks -- there are none of its own left to release. */
+    /* Called at every site that erases an off-device record (capacity drop, failed promotion,
+     * expiry). Without it the cache would keep the entry, resident_off_device would answer false,
+     * and the stale block ids would be served as a hit. The cache drops the entry without
+     * releasing blocks. */
     void set_drop_sink(std::function f) { on_drop_ = std::move(f); }
 
     /* ---------------- the linear half of an idle session ----------------
      *
-     * Told by PrefixCache::commit_checkpoint and PrefixCache::retire_ckpt, so the session view can
-     * say which conversations hold a snapshot and where a return resumes from. A snapshot lives in
-     * its checkpoint store slot, in host memory, and never moves: the tiers only record it. A
-     * record may hear of a snapshot BEFORE it hears note_used -- a checkpoint is committed
-     * mid-request and the chain is published when the request closes -- so this creates the
-     * record if it has to. */
+     * Called by PrefixCache::commit_checkpoint and retire_ckpt so the session view can show which
+     * conversations hold a snapshot and where they resume. Snapshots stay in their store slots in
+     * host memory; the tiers only record them. A checkpoint is committed mid-request, before the
+     * chain is published, so this creates the record if needed. */
     void note_snapshot(const BlockHash& key, int32_t slot, int64_t pos);
-    /* The cache is done with the snapshot at `key`. The record's BLOCKS are untouched -- the two
-     * halves are retired by different policies on different clocks, and a snapshot the retention
-     * policy drops says nothing about the prefix. */
+    /* The cache retired the snapshot at `key`. The record's blocks are untouched: blocks and
+     * snapshots are retired by different policies. */
     void release_snapshot(const BlockHash& key);
     int64_t  ckpt_bytes() const { return cfg_.ckpt_bytes; }
     int64_t  ckpt_slots() const { return cfg_.ckpt_slots; }
 
     /* ---------------- the session view ----------------
      *
-     * WHAT A SESSION IS HERE, because it is not what the cache is keyed by. The cache is keyed by
-     * BLOCK, and a 200K-token conversation is twelve thousand of them -- an enumeration nobody can
-     * read and not what anyone means by "session". A session is one PUBLISHED CHAIN: the blocks
-     * one request inserted, named by its tip. That is exactly the leaf of the prefix trie, so two
-     * conversations sharing a system prompt are two sessions and the shared blocks belong to both.
-     *
-     * THE SIZES THEREFORE OVERLAP AND THE TOTAL IS NOT A SUM. Sharing is the point of the cache;
-     * a view that hid it would make a server look like it was storing several times what it is.
-     * Anything reporting these numbers says so. */
+     * The cache is keyed by block; a session is one published chain, the blocks one request
+     * inserted, i.e. a leaf of the prefix trie. Two conversations sharing a system prompt are two
+     * sessions that both own the shared blocks, so per-session sizes overlap and do not sum to
+     * the total. Anything reporting these numbers must say so. */
     struct SessionInfo {
         uint64_t    id = 0;
         std::string model;
@@ -276,82 +218,74 @@ public:
         uint64_t    first_seen_ns = 0;
         uint64_t    last_used_ns = 0;
         int64_t     on_device = 0, on_host = 0;                /* blocks, by tier */
-        /* LINEAR STATE, on a hybrid model. Counted separately from blocks because it is a
-         * different resource with a different scarcity: a snapshot is thousands of blocks' worth
-         * of bytes and there are only --checkpoint-slots of them in host memory. A session showing
-         * blocks in host memory and no snapshot is one that will come back and re-run every
-         * recurrent layer over its whole transcript, which is not what "restored" should mean. */
+        /* Linear state on a hybrid model, counted apart from blocks: a snapshot is thousands of
+         * blocks' worth of bytes and there are only --checkpoint-slots of them. */
         int64_t     snapshots = 0;                             /* this session holds */
         int64_t     snap_bytes = 0;
-        /* WHAT A RETURN REUSES: the token position of the deepest snapshot on the chain. On a
-         * hybrid model the scheduler clamps a hit to the last linear checkpoint it can
-         * reach, so this -- not n_tokens and not the blocks -- is the prefix the next turn skips,
-         * and n_tokens minus it is what that turn prefills. Zero with no snapshot anywhere. */
+        /* Token position of the deepest snapshot on the chain, 0 if none. On a hybrid model hits
+         * clamp to it, so this is what the next turn skips; n_tokens minus it gets prefilled. */
         int64_t     resume_tokens = 0;
         bool        moving = false;                            /* a job is outstanding */
     };
-    /* WHAT HOST MEMORY IS HOLDING FOR THE CACHE, each block counted once. The per-session figures
-     * cannot be summed into this: sessions sharing a prefix share its blocks. The cap is what the
-     * operator configured. A clean entry's host copy is counted: it occupies the arena whether or
-     * not the VRAM copy has gone yet. */
+    /* Host memory held for the cache, each block counted once (including clean entries' copies),
+     * and the configured cap. */
     struct Occupancy {
         int64_t host_bytes = 0;
         int64_t host_cap_bytes = 0;
     };
-    /* Publish one request's chain. Called from PrefixCache::insert, which is the only place that
-     * knows a chain was completed rather than merely touched.
-     *
-     * KEPT WHETHER OR NOT ANY TIER IS ON, because what it records is not a tiering fact. A server
-     * with no --prefix-cache-mib still stores conversations -- it stores them all in VRAM, which
-     * is the case the table most wants to show -- and gating the record on the mover would make
-     * the view report an empty server to every operator who has not opted into tiering.
-     *
-     * ONE CONVERSATION IS ONE ROW, and the rule that makes it one is the trie: a session is a
-     * LEAF, so a chain that a later turn extends has stopped being one and is absorbed into it.
-     * Each turn publishes the chain it grew under its own request id, so without that the table
-     * is a row per turn -- a table nobody can read, holding a copy of every prefix of the
-     * transcript for as long as the newest. */
+    /* Record one request's published chain (from PrefixCache::insert). Kept even with every tier
+     * off, since a VRAM-only server still stores conversations. A session is a leaf, so a chain a
+     * later turn extends is absorbed into it: one row per conversation, not per turn. */
     void note_session(uint64_t id, const std::vector& chain, int64_t n_tokens,
                       uint64_t now_ns, const std::string& label = std::string());
     void set_model(const std::string& m) { model_ = m; }
-    /* Newest activity first. Recomputes each session's tier histogram from the records, so it is
-     * a view and never a second copy of the truth. The walk takes the lock in slices and lets
-     * every other taker go first between them (YieldingMutex), so rows read at different slices
-     * may describe moments a few microseconds apart. */
+    /* Newest activity first, tier histograms recomputed from the records. The walk takes the lock
+     * in slices and yields between them (YieldingMutex), so rows may describe moments a few
+     * microseconds apart. */
     std::vector sessions(Occupancy* occ = nullptr) const;
-    void forget_session(uint64_t id);
 
     struct Stats {
-        /* `to_host` is entries COPIED to host memory; `dropped` is entries whose VRAM copy was
-         * then given up. They are different events: a copy is link traffic and a drop is VRAM
-         * handed to something else, and a conversation that returns before anything wants its
-         * VRAM is copied and never dropped. */
+        /* `to_host` counts copies to host memory (link traffic); `dropped` counts VRAM copies
+         * then given up. An entry can be copied and never dropped. */
         int64_t to_host = 0, dropped = 0, promoted = 0;
-        /* `host_drops` is entries the full arena gave up. */
-        int64_t host_drops = 0, failures = 0;
+        /* `host_drops` is entries the full arena gave up; `held_back` copies it did not take,
+         * because every host entry was worth as much (their entries stay in VRAM only). */
+        int64_t host_drops = 0, failures = 0, held_back = 0;
         int64_t host_bytes = 0;
         int64_t host_hits = 0;
-        /* WHAT THE STEP THREAD SPENT ON THEM, under the scheduler's lock: restores issued at
-         * admission, and copies landed synchronously because pressure could not wait for them.
-         * Host time, not link time -- what every other request waits through. */
+        /* Step-thread host time under the scheduler's lock: restores issued at admission, and
+         * copies landed synchronously under pressure. Not link time. */
         int64_t restores = 0, restore_ns = 0, flushes = 0, flush_ns = 0;
     };
     /* The step thread's own time on the tiers (see Stats). */
     void note_restore(int64_t ns) { std::lock_guard lk(mu_); ++stats_.restores; stats_.restore_ns += ns; }
     void note_flush(int64_t ns)   { std::lock_guard lk(mu_); ++stats_.flushes;  stats_.flush_ns += ns; }
-    /* A copy, taken under the lock: an HTTP thread reads these while the engine thread moves
-     * records. */
+    /* A copy taken under the lock; HTTP threads read it while the engine moves records. */
     Stats        stats() const;
     HostArena&   arena() { return arena_; }
-    /* The size of ONE SLOT, which under tensor parallelism holds every rank's shard. */
+    /* Bytes per slot; under tensor parallelism one slot holds every rank's shard. */
     int64_t      entry_bytes() const { return cfg_.entry_bytes; }
 
 private:
+    /* The host list's order, least valuable first: least recently used, and among entries used
+     * at the same moment (a chain is stamped with one clock) the deepest. */
+    struct LruKey {
+        uint64_t used_ns = 0;
+        int64_t  depth = 0;
+    };
+    struct LruOrder {
+        bool operator()(const LruKey& a, const LruKey& b) const {
+            return a.used_ns != b.used_ns ? a.used_ns < b.used_ns : a.depth > b.depth;
+        }
+    };
+    using HostLru = std::multimap;
+
     struct Rec {
         KVTier   tier = KVTier::Device;
         uint64_t used_ns = 0;
-        /* THE HOST COPY. On a device record it is a copy that makes the record clean; on a host
-         * record it is where the bytes are read from. */
+        int64_t  depth = 0;         /* block index in its chain (note_used) */
+        /* Host copy: on a device record it makes the record clean; on a host record it is the
+         * only copy. */
         int32_t  host_slot = -1;
         bool     pending = false;
         bool     doomed  = false;   /* forget() arrived while pending */
@@ -360,25 +294,24 @@ private:
         bool     listed  = false;   /* on host_lru_; `it` is valid */
         std::vector blocks;
         /* ---- the linear half ----
-         * `ck_slot` is the snapshot's checkpoint store slot and `ck_pos` its token position, for the
-         * session view. -1 when the record carries no snapshot, which is the common case -- one
-         * block in every (interval / block_size) is a checkpoint position. */
+         * Snapshot store slot and token position, for the session view. `ck_slot` is -1 for most
+         * records: one block in (interval / block_size) is a checkpoint position. */
         int32_t  ck_slot = -1;
         int64_t  ck_pos = 0;
-        std::multimap::iterator it;
+        HostLru::iterator it;
     };
 
-    /* Does this record want a host copy it does not have yet? Its blocks are in VRAM with none. */
+    /* Blocks in VRAM with no host copy yet. */
     bool wants_copy(const Rec& r) const;
     void queue_copy(const BlockHash& key, Rec& r);
     void queue_clean(const BlockHash& key, Rec& r);
-    /* GIVE UP A HOST SLOT, the record's or a finished job's. Every block-arena free goes through
-     * `give_slot`, because a freed slot is what unblocks a write-back that found the arena full.
-     * `free_host` is the record's own. */
+    /* Every block-arena free goes through give_slot, because a freed slot unblocks a stuck
+     * write-back. free_host frees the record's own slot. */
     void give_slot(int32_t slot);
     void free_host(Rec& r);
     void unlist(Rec& r);
     void relist(const BlockHash& key, Rec& r);
+    void touch(const BlockHash& key, Rec& r, uint64_t now_ns);
 
     struct Session {
         int64_t  n_tokens = 0;
@@ -395,24 +328,15 @@ private:
     /* The body of close(), for a caller that already holds the lock. */
     void reset();
 
-    /* TWO THREADS REACH THIS OBJECT. The engine loop owns every mutation -- the cache publishes a
-     * chain from the scheduler's close path, the maintenance pass moves records -- and an HTTP
-     * thread drawing the sessions view walks the same containers through sessions(). An
-     * unordered_map rehashed under an iterator is a crash rather than a stale number, so the
-     * state the view reads is held under this and every mutator takes it.
+    /* The engine loop makes every mutation; an HTTP thread walks the same containers in
+     * sessions(), so every mutator takes this lock. No method calls another that takes it, so a
+     * non-recursive mutex suffices; the drop sink runs under it and calls into the prefix cache,
+     * which never calls back.
      *
-     * NOT A BOTTLENECK, and it is worth saying where the cost lands: the per-block calls on the
-     * publish path (note_used) take it once each, uncontended, against a hash insert they were
-     * already paying for. No method here calls another that takes it, which is what keeps a plain
-     * mutex sufficient; the drop sinks are called while it is held and reach into the prefix
-     * cache, which never calls back.
-     *
-     * AND THE VIEW'S WALK MUST NOT DELAY THE ENGINE. It visits every block of every stored
-     * conversation, which is far longer than any engine-side hold, and the engine takes this lock
-     * every step. So the walk takes it for a slice of records at a time and, between slices,
-     * waits until nobody else is waiting for it: an engine-side taker that arrives during a slice
-     * waits for that slice and never for the walk. A plain mutex cannot promise that, because
-     * the walker re-locking the moment it unlocks can win against a woken waiter every time. */
+     * The view's walk is far longer than any engine-side hold, so it locks one slice of records
+     * at a time and, between slices, waits until no other taker is waiting. An engine thread then
+     * waits at most one slice. A plain mutex cannot promise that: the walker could re-lock ahead
+     * of a woken waiter every time. */
     struct YieldingMutex {
         std::mutex       m;
         std::atomic waiting{0};
@@ -437,32 +361,25 @@ private:
     Config   cfg_;
     HostArena arena_;
     std::unordered_map recs_;
-    /* THE HOST-ONLY RECORDS BY LAST USE, begin() the least recently used. Keyed by the clock rather
-     * than kept in the order records arrive, because a record arrives here when its VRAM copy is
-     * given up, which says nothing about when a request last read it -- and both the capacity drop
-     * and the expiry take the oldest by use. */
-    std::multimap host_lru_;
-    /* THE WORK QUEUES, in the order the work arrived. Each holds a key at most once -- the Rec's
-     * flag says whether it is in -- and a key whose record changed under it is skipped when it is
-     * reached rather than searched for, so both stay a push and a pop. */
+    /* Host-only records by value, begin() least valuable (LruOrder). Keyed by the clock, not
+     * arrival order: a record arrives when its VRAM copy goes, which says nothing about its last
+     * use. */
+    HostLru host_lru_;
+    /* Work queues in arrival order. Each key appears at most once (the Rec's flag says so); a
+     * key whose record changed is skipped when reached rather than searched for. */
     std::deque wb_q_;       /* records wanting a host copy */
     std::vector clean_q_;   /* records whose VRAM copy may now go */
-    /* COPIES THE ARENA REFUSED since the last maintenance plan, which is what that plan frees
-     * room for. A count and not a list: any host-only entry makes room for any copy. */
-    int64_t  starved_ = 0;
-    /* A WRITE-BACK FOUND THE ARENA FULL AND NOTHING TO GIVE UP. Waiting again changes nothing until
-     * a slot is freed, so the copy is not planned until one is -- otherwise every tick pops the
-     * queue, finds no slot and puts it back. */
+    /* For each copy the arena refused since the last plan() that a host-only entry is worth less
+     * than, its own value, most valuable first; plan() drops one entry worth less for each. */
+    std::vector room_;
+    uint64_t held_back_warned_ns_ = 0;
+    /* A write-back found the arena full with nothing to drop; no copy is planned until a slot is
+     * freed, so ticks do not spin on the queue. */
     bool     wb_stuck_ = false;
     std::unordered_map sessions_;
-    /* THE DEATH SIGNAL FOR A ROW, and the reason the table is bounded. A published chain is only
-     * ever reachable from position zero, so the moment the cache evicts its FIRST block the
-     * conversation cannot be hit at any length and the row describes blocks that are not there.
-     * The cache announces its evictions and expiries through forget(), and the entries this object
-     * drops itself -- a full arena's, a failed restore's -- go through drop_rooted as well, so the
-     * root is indexed and the row goes with it. Several sessions share a root when
-     * they share a system prompt and all of them are unreachable together, which is why the value
-     * is a list. */
+    /* Sessions by first block. A chain is reachable only from position zero, so once its first
+     * block goes (forget(), or a drop here via drop_rooted) its rows go too; this keeps the table
+     * bounded. Sessions sharing a system prompt share a root, hence a list. */
     std::unordered_map, BlockHashHash> roots_;
     std::string model_;
     std::function on_drop_;
diff --git a/core/mem/pools.cpp b/core/mem/pools.cpp
index 5ad56832..e97e25a2 100644
--- a/core/mem/pools.cpp
+++ b/core/mem/pools.cpp
@@ -1,4 +1,4 @@
-/* pools.cpp -- see pools.h. Every refusal in here names what did not fit and by how much. */
+/* pools.cpp -- see pools.h. */
 #include "mem/pools.h"
 
 #include 
@@ -18,10 +18,8 @@ public:
     const char* name() const override { return "device"; }
 };
 
-/* aligned_alloc, at the pool alignment. Used by the no-ROCm build and by the tests. A pool's base
- * is 2 MiB-aligned either way, because the .rad's pool alignment is 2 MiB and huge-page mappable
- * (spec §4.1) and a slab whose base is not aligned makes every fixed-stride slot inside it
- * misaligned as well. */
+/* aligned_alloc at the 2 MiB pool alignment (the .rad pool alignment, huge-page mappable, spec
+ * §4.2), so fixed-stride slots in a slab stay aligned. Used by the no-ROCm build and the tests. */
 class MallocAllocator final : public MemAllocator {
 public:
     void* alloc(int64_t bytes, int kind) override {
@@ -46,7 +44,7 @@ std::string Shortfall::str() const {
     if (!refused.empty())
         return fmt("%s: %s of %s refused: %s", pool.c_str(), what.c_str(),
                    humanb(wanted).c_str(), refused.c_str());
-    return fmt("%s: %s wanted %s, %s available -- short by %s",
+    return fmt("%s: %s wanted %s, %s available, short by %s",
                pool.c_str(), what.c_str(), humanb(wanted).c_str(),
                humanb(available).c_str(), humanb(missing()).c_str());
 }
@@ -56,9 +54,8 @@ std::string Shortfall::str() const {
 Pool::~Pool() { release(); }
 
 void Pool::release() {
-    /* ELASTIC FIRST, because an elastic pool has no allocator-owned base: vm_ owns the address
-     * range and the pages in it, and handing that pointer to MemAllocator::free would be a free
-     * of memory the allocator never handed out. */
+    /* An elastic pool's base belongs to vm_, not the allocator, so it must not reach
+     * MemAllocator::free. */
     if (elastic_) {
         vm_.release();
         elastic_ = false;
@@ -69,23 +66,23 @@ void Pool::release() {
     bytes_ = used_ = 0;
 }
 
-int Pool::init(std::string_view nm, int64_t bytes, int kind, MemAllocator* a, bool accounting) {
+void Pool::reset(std::string_view nm, int64_t bytes, int kind, MemAllocator* a) {
     release();
     name_ = std::string(nm);
     bytes_ = bytes;
-    used_ = 0;
     kind_ = kind;
-    accounting_ = accounting;
     alloc_ = a;
     shortfalls_.clear();
     res_.clear();
-    if (accounting_ || bytes_ <= 0) return RAD_OK;
+}
+
+int Pool::init(std::string_view nm, int64_t bytes, int kind, MemAllocator* a) {
+    reset(nm, bytes, kind, a);
+    if (bytes_ <= 0) return RAD_OK;
 
     base_ = a->alloc(bytes_, kind);
     if (!base_) {
-        /* Refuse; do not retry smaller. An engine that quietly re-optimises the split is an
-         * engine whose benchmarks do not reproduce (spec §6). The allocator's reason goes with
-         * it: the device layer says what the driver answered. */
+        /* Refuse; never retry smaller (spec §6). Record the driver's reason. */
         const char* why = a == &rad_device_allocator() ? rad_dev_last_error() : nullptr;
         shortfalls_.push_back({name_, "backing allocation", bytes_, 0,
                                why && *why ? why : "the allocator returned nothing"});
@@ -105,38 +102,24 @@ void* Pool::reserve(std::string_view what, int64_t bytes, int64_t align, int64_t
     used_ = off + bytes;
     res_.push_back({std::string(what), off, bytes});
     if (off_out) *off_out = off;
-    if (accounting_) return nullptr;               /* headroom: accounted, never touched */
     return (char*)base_ + off;
 }
 
 /* ------------------------------------------------------------------ elastic */
 
-int64_t Pool::granule() { return VMem::granularity(); }
-
 int Pool::init_elastic(std::string_view nm, int64_t bytes, int kind, MemAllocator* a) {
-    /* WITHOUT VIRTUAL MEMORY MANAGEMENT THIS IS init(). The caller does not branch: it commits
-     * what it wants, the commits succeed against memory that was already there, and the pool
-     * holds its maximum for the whole run. That is worse than elastic and identical to a fixed
-     * pool, which is the right shape for a fallback. */
+    /* Without virtual memory management this is init(): commits succeed against memory that is
+     * already there and the pool holds its maximum for the whole run. */
     if (!VMem::supported() || kind != RAD_MEM_DEVICE)
-        return init(nm, bytes, kind, a, /*accounting=*/false);
+        return init(nm, bytes, kind, a);
 
-    release();
-    name_  = std::string(nm);
-    bytes_ = bytes;
-    used_  = 0;
-    kind_  = kind;
-    accounting_ = false;
-    alloc_ = a;
-    shortfalls_.clear();
-    res_.clear();
+    reset(nm, bytes, kind, a);
     if (bytes_ <= 0) return RAD_OK;
 
     const int rc = vm_.reserve(bytes_, RAD_ALIGN_POOL);
     if (rc < 0) {
-        /* Refuse; do not retry smaller. An address range is not memory -- a reservation that
-         * fails on a 64-bit card is a bug and not a budget, and quietly halving it would hide the
-         * bug behind a pool that cannot grow to what the operator asked for. */
+        /* Refuse; never retry smaller. A failed address reservation on a 64-bit card is a bug,
+         * not a budget limit. */
         const char* why = rad_dev_last_error();
         shortfalls_.push_back({ name_, "address reservation", bytes_, 0,
                                 *why ? why : "the device layer gave no reason" });
@@ -144,45 +127,34 @@ int Pool::init_elastic(std::string_view nm, int64_t bytes, int kind, MemAllocato
         return rc;
     }
     base_ = vm_.base();
-    /* THE RANGE ROUNDS UP AND THE BUDGET DOES NOT. vm_.size() is the reservation rounded to a
-     * whole granule, which is a fact about the driver and not a licence to spend more than the
-     * split allowed. Taking it as the budget lets a pool grow into the headroom by up to a
-     * granule and, worse, GRANT a reservation the budget should have refused -- the same quiet
-     * re-optimisation of the split that init() refuses to make when its allocation fails.
-     *
-     * The rounded tail stays addressable, and that is what it is for: the last reservation can
-     * end mid-granule and its commit rounds outward into a range that is really reserved. */
+    /* bytes_ stays the requested budget, not vm_.size() (rounded up to a granule): using the
+     * rounded size would let reserve() grant more than the split allows. The rounded tail stays
+     * reserved so the last reservation's commit can round outward into it. */
     elastic_ = true;
     return RAD_OK;
 }
 
 int Pool::commit(int64_t off, int64_t bytes) {
     if (!elastic_) {
-        /* A fixed pool is backed everywhere inside it and nowhere outside it, and saying so is
-         * what keeps a caller written against the elastic contract correct here. */
+        /* A fixed pool is backed everywhere inside its range and nowhere outside it. */
         return (off >= 0 && bytes >= 0 && off + bytes <= bytes_) ? RAD_OK : RAD_E_INVAL;
     }
     return vm_.commit(off, bytes);
 }
 
 int Pool::decommit(int64_t off, int64_t bytes) {
-    if (!elastic_) return RAD_OK;       /* nothing to give back, and that is not an error */
+    if (!elastic_) return RAD_OK;       /* nothing to give back */
     return vm_.decommit(off, bytes);
 }
 
-bool Pool::is_committed(int64_t off, int64_t bytes) const {
-    if (!elastic_) return off >= 0 && bytes >= 0 && off + bytes <= bytes_;
-    return vm_.is_committed(off, bytes);
-}
-
 std::string Pool::report() const {
-    std::string s = fmt("%-14s %10s budget, %10s used, %10s free%s\n",
+    std::string s = fmt("%-14s %10s budget, %10s used, %10s free\n",
                         name_.c_str(), humanb(bytes_).c_str(), humanb(used_).c_str(),
-                        humanb(avail()).c_str(), accounting_ ? "   (accounted, not allocated)" : "");
+                        humanb(avail()).c_str());
     for (const auto& r : res_)
         s += fmt("    %-24s %10s @ +%lld\n", r.what.c_str(), humanb(r.bytes).c_str(),
                  (long long)r.off);
-    for (const auto& f : shortfalls_) s += "    REFUSED " + f.str() + "\n";
+    for (const auto& f : shortfalls_) s += "    " + f.str() + "\n";
     return s;
 }
 
@@ -201,12 +173,9 @@ int Pools::configure(const Config& cfg, int64_t vram_capacity,
     const int64_t kv = cfg.vram_kv_mib       * MiB;
     const int64_t hp = cfg.host_pool_total_mib() * MiB;
 
-    /* THE BUDGETS ARE RESOLVED BEFORE THIS RUNS AND THIS DOES NOT RE-DECIDE THEM.
-     * core/mem/vram_budget.cpp derived them from the card, the measured driver residency and the
-     * computed arena, and they arrive here as two numbers with a report behind them. This
-     * component refuses rather than shrinking anything: an engine that quietly re-optimises a
-     * split is an engine whose benchmarks do not reproduce (spec §6). A zero here means the
-     * resolver was never called, which is a wiring bug and gets named as one. */
+    /* The budgets were resolved by core/mem/vram_budget.cpp (from the card, the measured driver
+     * residency and the computed arena); this refuses rather than re-deciding them (spec §6). A
+     * zero means the resolver never ran, which is a wiring bug. */
     std::string missing;
     if (cfg.vram_weights_mib <= 0) missing += "  vram_weights resolved to 0 MiB\n";
     if (cfg.vram_kv_mib      <= 0) missing += "  vram_kv resolved to 0 MiB\n";
@@ -219,7 +188,6 @@ int Pools::configure(const Config& cfg, int64_t vram_capacity,
 
     const int64_t want = w + kv;
     if (vram_capacity > 0 && want > vram_capacity) {
-        /* Name every pool and the total overage. Refuse rather than shrinking any of them. */
         fit_report_ = fmt(
             "VRAM budgets do not fit:\n"
             "  vram_weights   %10s\n"
@@ -227,7 +195,7 @@ int Pools::configure(const Config& cfg, int64_t vram_capacity,
             "  ------------------------\n"
             "  total          %10s\n"
             "  card total     %10s\n"
-            "  OVER BY        %10s\n"
+            "  over by        %10s\n"
             "The resolved split is larger than the card, which the resolver does not produce: a "
             "wiring bug (spec §6).\n",
             humanb(w).c_str(), humanb(kv).c_str(),
@@ -239,39 +207,21 @@ int Pools::configure(const Config& cfg, int64_t vram_capacity,
 
     int st = RAD_OK;
     int s;
-    /* Order matters only for the diagnostic: allocate the two big ones first so a failure names
-     * the one that actually could not be served. */
-    if ((s = weights_.init("vram_weights", w,  RAD_MEM_DEVICE, device, false)) < 0) st = s;
-    /* THE KV POOL IS THE ELASTIC ONE, ALWAYS, AND THERE IS NO OTHER MODE. Its budget is still the
-     * budget: elasticity does not change how much of the card the cache may address, it changes
-     * whether the part it is not addressing has VRAM behind it. What the cache releases is what
-     * the expert plane can promote into, so the split between them stops being a guess made once
-     * at startup and becomes the two pools' actual demand.
-     *
-     * THERE IS NO FLAG, BECAUSE A FLAG IS THE WRONG SHAPE FOR IT. A fixed pool holds every block
-     * it was carved for whether or not a single token is in it, and an expert plane that does not
-     * fit streams weights over the link for the whole run to pay for cache nobody is using. There
-     * is no deployment that wants that. A device with no virtual memory management goes through
-     * the same call -- init_elastic() allocates the range whole there, which is fixed-pool
-     * behaviour under a contract the callers already meet. */
+    /* Order matters only for diagnostics: the two big pools go first so a failure names the one
+     * that could not be served. */
+    if ((s = weights_.init("vram_weights", w,  RAD_MEM_DEVICE, device)) < 0) st = s;
+    /* The KV pool is always elastic. Its budget still caps what the cache may address; elasticity
+     * only decides whether the unused part has VRAM behind it. What the cache releases, the
+     * expert plane can promote into, so the split follows actual demand. There is no fixed-pool
+     * option: it would hold every block whether used or not while experts stream over the link.
+     * Without virtual memory management init_elastic() allocates the range whole. */
     if ((s = kv_.init_elastic("vram_kv", kv, RAD_MEM_DEVICE, device)) < 0) st = s;
-    /* MAPPED, NOT MERELY PINNED, AND THE DIFFERENCE IS A WHOLE TIER.
-     *
-     * This one pool serves two jobs: the mover's staging buffers and O_DIRECT landing zone, which
-     * want pinned memory so a transfer is a DMA with no driver bounce -- and the ZERO-COPY
-     * execution site, row three of spec §5.1's table, where the bytes stay in host memory and the
-     * kernel reads them over the link as it computes. The second needs the allocation to be
-     * addressable FROM A KERNEL, and hipHostMallocDefault does not make it so.
-     *
-     * Getting it wrong is silent and total: Mover::init asks rad_dev_device_ptr for the pool's
-     * base as the card sees it, an unmapped allocation answers null, and the fallback is the host
-     * pointer -- so `assign_expert_tiered`, which routes EVERY pooled expert to
-     * Site::DeviceZeroCopy, would hand a kernel a pointer it cannot dereference. There would be no
-     * hybrid tier, only a plan that says there is one.
-     *
-     * Mapped memory is still pinned, so job one is unaffected; hipHostMallocMapped is strictly the
-     * larger promise. On the host backend all four kinds are the same aligned pages. */
-    if ((s = host_   .init("host_pool",   hp, RAD_MEM_HOST_MAPPED, host, false)) < 0) st = s;
+    /* Mapped, not merely pinned. The host pool holds the mover's staging buffers and O_DIRECT
+     * landing zone, and the zero-copy execution site (spec §5.1), where kernels read weights over
+     * the link and so need a kernel-addressable base: with hipHostMallocDefault,
+     * rad_dev_device_ptr returns null in Mover::init and Site::DeviceZeroCopy experts get an
+     * unusable pointer. On the host backend all memory kinds are the same aligned pages. */
+    if ((s = host_   .init("host_pool",   hp, RAD_MEM_HOST_MAPPED, host)) < 0) st = s;
 
     fit_report_  = weights_.report();
     fit_report_ += kv_.report();
diff --git a/core/mem/pools.h b/core/mem/pools.h
index e141c71c..d0acf35d 100644
--- a/core/mem/pools.h
+++ b/core/mem/pools.h
@@ -1,22 +1,17 @@
 /* pools.h -- explicit pool budgets (spec §6).
  *
- * Every pool is budgeted EXPLICITLY. No profiling pass, no utilisation fraction, no inference
- * about what the workload will be. The trade between KV blocks and resident weights is real and
- * workload-dependent -- a long-context low-concurrency server and a short-context high-concurrency
- * one want opposite splits -- but it is the operator's to make. An engine that quietly
- * re-optimises the split is an engine whose benchmarks do not reproduce.
+ * Every pool is budgeted explicitly: no profiling pass, no utilisation fraction. The KV vs
+ * weights split depends on the workload, and an engine that re-optimises it on its own does not
+ * produce reproducible benchmarks.
  *
- * Two properties this file exists to make STRUCTURAL rather than conventional:
+ * Two structural properties:
  *
- *   1. A Pool holds a base, a size and a cursor, and has no pointer to any other Pool. There is
- *      no allocate-from-wherever call anywhere in this header. Therefore no code path exists
- *      along which the mover's expert promotion (spec §5.4) can reach a KV block: the mover is
- *      handed Pools::weights() and it is not possible to reach Pools::kv() from it. That is the
- *      whole reason the weight slab is a fixed budget.
+ *   1. A Pool holds a base, a size and a cursor, and no pointer to any other Pool. The mover is
+ *      handed Pools::weights() only, so expert promotion (spec §5.4) cannot reach a KV block.
  *
- *   2. A reservation that does not fit returns null and RECORDS the shortfall by name and by how
- *      much. It never falls through to another pool, never shrinks an earlier reservation, and
- *      never silently rounds the request down. The engine refuses to start instead.
+ *   2. A reservation that does not fit returns null and records the shortfall by name and size.
+ *      It never falls through to another pool, shrinks an earlier reservation or rounds down;
+ *      the engine refuses to start instead.
  */
 #pragma once
 #include "rad_core.h"
@@ -30,11 +25,9 @@
 namespace rad {
 
 /* ------------------------------------------------------------------ the allocator seam */
-/* Everything here goes through an allocator object rather than calling rad_dev_alloc directly.
- * The host backend is the primary development target and not a fallback
- * (docs/IMPLEMENTATION.md), and a pool test that cannot run without ROCm is a pool test that does
- * not run. The device allocator is the default; the malloc one is what the no-device build and
- * the tests use. */
+/* Pools allocate through this interface rather than rad_dev_alloc so they run without ROCm: the
+ * host backend is a primary target (docs/IMPLEMENTATION.md). The device allocator is the default;
+ * the malloc one serves the no-device build and the tests. */
 class MemAllocator {
 public:
     virtual ~MemAllocator() = default;
@@ -47,28 +40,22 @@ MemAllocator& rad_device_allocator();   /* rad_dev_alloc / rad_dev_free */
 MemAllocator& rad_malloc_allocator();   /* aligned_alloc; host-only builds and tests */
 
 /* ------------------------------------------------------------------ shortfalls */
-/* What did not fit, by name and by how much. Every refusal in this component produces one of
- * these rather than a bare RAD_E_NOMEM, because "it returned -6" is not a diagnosis. */
+/* What did not fit, by name and by how much. Every refusal here produces one, not just a bare
+ * RAD_E_NOMEM. */
 struct Shortfall {
     std::string pool;       /* which budget: "vram_weights", "vram_kv", ... */
     std::string what;       /* what was being reserved when it ran out */
     int64_t     wanted = 0;
     int64_t     available = 0;
-    /* A backing allocation the allocator refused: there is no "available" to report, only the
-     * allocator's own sentence for why, which is what tells an out-of-memory card from a pinned-
-     * memory limit from a driver that would not map the range. */
+    /* Set when the allocator refused a backing allocation: its reason (out of memory, pinned
+     * limit, mapping failure). `available` is meaningless then. */
     std::string refused;
     int64_t     missing() const { return wanted - available; }
     std::string str() const;
 };
 
 /* ------------------------------------------------------------------ Pool */
-/* One reservation, made once, that never grows, never shrinks and never borrows.
- *
- * `accounting_only` pools hold no memory: the headroom budget is memory we promise NOT to touch,
- * for activations and the arena (spec §6). The arena owner still reserves against it, so an arena
- * that would exceed the headroom refuses at startup by name instead of succeeding here and
- * failing the first prefill on the device. */
+/* One reservation, made once, that never grows, never shrinks and never borrows. */
 class Pool {
 public:
     Pool() = default;
@@ -82,70 +69,55 @@ public:
     int64_t     avail() const { return bytes_ - used_; }
     void*       base()  const { return base_; }
     int         kind()  const { return kind_; }
-    bool        accounting_only() const { return accounting_; }
 
-    /* Carve `bytes` at `align`. Returns the pointer (null for an accounting-only pool, which
-     * still tracks the cursor), or null with a recorded shortfall if it does not fit.
-     * `off_out`, when given, receives the byte offset from base -- which is what a slab of
-     * fixed-stride slots actually wants, since the offset survives a base that is a device
-     * pointer nobody may dereference on the host. */
+    /* Carve `bytes` at `align`. Returns the pointer, or null with a recorded shortfall if it does
+     * not fit.
+     * `off_out` receives the byte offset from base, which fixed-stride slabs use because the base
+     * may be a device pointer the host cannot dereference. */
     void* reserve(std::string_view what, int64_t bytes, int64_t align, int64_t* off_out = nullptr);
 
-    /* True when nothing was refused. Checked once, at the end of startup, so the report names
-     * every failure rather than the first one at the top (spec §3.1's rule, applied here). */
+    /* True when nothing was refused. Checked once at the end of startup so the report names every
+     * failure, not only the first (spec §3.1). */
     bool ok() const { return shortfalls_.empty(); }
 
     /* ---- elastic pools ----------------------------------------------------------------------
      *
-     * An elastic pool reserves its ADDRESS RANGE whole and backs only the part somebody has asked
-     * for. Every offset reserve() hands out is final from the first call, so a slab stride or a
-     * layer stride computed against the full range stays correct while the physical memory behind
-     * the unused part goes back to the card for another pool to take. That is the only way two
-     * pools on one card can trade: the addresses cannot move, so the pages have to.
+     * An elastic pool reserves its whole address range and backs only the parts that are
+     * committed. Offsets from reserve() are final, so strides computed against the full range
+     * stay valid while unused pages go back to the card for another pool. Addresses cannot move
+     * between pools; pages can.
      *
-     * The two pools this exists for are the KV cache and the expert slab, and the trade is not
-     * symmetric. A KV block holds a sequence's state and can only be given back once nothing
-     * holds it; an expert slot holds a COPY of a weight that also lives in the host pool or the
-     * container, so it can be given back whenever the mover can spare it. That asymmetry is the
-     * policy's, not this file's -- what is here is the mechanism and the refusal.
+     * Used by the KV cache and the expert slab. A KV block can be released only once nothing
+     * holds it; an expert slot is a copy of a weight that also lives in host memory or the
+     * container, so the mover can release it at will. That policy lives with the callers.
      *
-     * A pool is elastic only where the device layer has virtual memory management (VMem in
-     * core/device/device.h). Where it does not, init_elastic() allocates the whole range exactly
-     * as init() does and commit()/decommit() are no-ops that succeed: a caller written for an
-     * elastic pool runs unchanged against a fixed one, holding the maximum it was reserved. That
-     * is the degradation spec §6 allows, because the pool is still one explicit budget -- it is
-     * simply one that cannot give anything back. */
+     * Without virtual memory management (VMem in core/device/device.h), init_elastic() allocates
+     * the whole range like init() and commit()/decommit() succeed as no-ops, so callers run
+     * unchanged against a fixed pool that holds its maximum (allowed by spec §6). */
     bool    elastic()   const { return elastic_; }
     int64_t committed() const { return elastic_ ? vm_.committed() : bytes_; }
 
-    /* Back [off, off+bytes) so a kernel may touch it. Rounds OUTWARD to the commit granule, so
-     * what was asked for is certainly backed, and is idempotent: a pool growing to n asks for
-     * [0, n) every time n changes and pays only for the part that is new. */
+    /* Back [off, off+bytes) so a kernel may touch it. Rounds outward to the commit granule and is
+     * idempotent: a pool growing to n may commit [0, n) each time and pays only for the new part. */
     int  commit(int64_t off, int64_t bytes);
 
-    /* Hand the pages back. Rounds INWARD, so a granule holding one byte the caller still wants
-     * stays -- a caller that shrinks to exactly the boundary it is holding is therefore safe, and
-     * one that shrinks between boundaries simply keeps a granule it will use next time. */
+    /* Release the pages. Rounds inward, so a granule with any byte still in use stays backed. */
     int  decommit(int64_t off, int64_t bytes);
 
-    bool is_committed(int64_t off, int64_t bytes) const;
-
-    /* The commit quantum, so a caller can pick grow steps that do not strand a fraction of one in
-     * every stripe. 0 when the pool is not elastic. */
-    static int64_t granule();
-
     const std::vector& shortfalls() const { return shortfalls_; }
 
     std::string report() const;
 
 private:
-    /* Reserve the address range and back nothing. `bytes` is the MAXIMUM the pool may ever hold
-     * and is what reserve() carves against; what it costs the card is committed(). Falls back to
-     * a whole allocation where the device layer has no virtual memory management. */
+    /* Reserve the address range and back nothing. `bytes` is the maximum the pool may ever hold
+     * and what reserve() carves against; committed() is what it costs the card. Falls back to a
+     * whole allocation without virtual memory management. */
     int init_elastic(std::string_view nm, int64_t bytes, int kind, MemAllocator* a);
 
     friend class Pools;
-    int init(std::string_view nm, int64_t bytes, int kind, MemAllocator* a, bool accounting);
+    int init(std::string_view nm, int64_t bytes, int kind, MemAllocator* a);
+    /* release(), then name the pool and set its budget with nothing reserved. */
+    void reset(std::string_view nm, int64_t bytes, int kind, MemAllocator* a);
     void release();
 
     std::string   name_;
@@ -153,7 +125,6 @@ private:
     int64_t       used_  = 0;
     void*         base_  = nullptr;
     int           kind_  = RAD_MEM_DEVICE;
-    bool          accounting_ = false;
     bool          elastic_ = false;
     VMem          vm_;
     MemAllocator* alloc_ = nullptr;
@@ -165,12 +136,11 @@ private:
 /* ------------------------------------------------------------------ Pools */
 class Pools {
 public:
-    /* `vram_capacity` is what the device reports free. Pass 0 to skip the capacity check, which
-     * is what the host backend wants -- it has no meaningful answer and inventing one would be
-     * exactly the inference §6 forbids.
+    /* `vram_capacity` is what the device reports free; 0 skips the capacity check (the host
+     * backend has no meaningful answer).
      *
-     * Refuses, by name and by how much, rather than shrinking anything:
-     *   - if the operator did not state the weight and KV budgets at all;
+     * Refuses, by name and size, rather than shrinking anything:
+     *   - if the weight or KV budget is zero (the resolver did not run);
      *   - if weights + kv exceeds the card;
      *   - if a pool's backing allocation fails.
      */
@@ -187,11 +157,10 @@ public:
 
     bool configured() const { return configured_; }
 
-    /* The line the engine prints at startup and the reason it refuses. Always populated, even on
-     * success, because the placement report wants the pool totals (spec §16). */
+    /* Printed at startup and on refusal. Populated on success too, for the placement report's
+     * pool totals (spec §16). */
     const std::string& fit_report() const { return fit_report_; }
 
-    /* Every shortfall from every pool, gathered. */
     std::vector shortfalls() const;
 
 private:
diff --git a/core/mem/prefix.cpp b/core/mem/prefix.cpp
index 2b894d48..64d4cddf 100644
--- a/core/mem/prefix.cpp
+++ b/core/mem/prefix.cpp
@@ -9,14 +9,11 @@
 namespace rad {
 
 /* ------------------------------------------------------------------ hashing */
-/* A 128-bit chained mix rather than a cryptographic hash. A prefix cache whose store is on disk,
- * shared and long-lived is usually keyed by SHA-256, because a cheap hash's collision would serve
- * one caller another caller's context. We get the same guarantee more cheaply: every entry keeps
- * its BLOCK'S TOKEN IDS and compares them on a hit, so a collision is a miss rather than a wrong
- * answer, and the hash only has to be good enough to keep the bucket chains short.
+/* A 128-bit chained mix, not a cryptographic hash: every entry stores its block's token ids and
+ * compares them on a hit, so a collision is a miss, and the hash only needs to keep buckets short.
  *
- * splitmix64's finaliser, which is a full 64-bit bijection -- so folding one token cannot lose the
- * bits of the previous one, which is the failure mode of a plain multiply-xor chain. */
+ * splitmix64's finaliser is a 64-bit bijection, so folding one token cannot lose the bits of the
+ * previous one (the weakness of a plain multiply-xor chain). */
 static inline uint64_t mix64(uint64_t x) {
     x += 0x9e3779b97f4a7c15ull;
     x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9ull;
@@ -27,24 +24,9 @@ static inline uint64_t mix64(uint64_t x) {
 std::string BlockHash::str() const { return fmt("%016llx%016llx", (unsigned long long)hi,
                                                 (unsigned long long)lo); }
 
-uint64_t mm_content_hash(const void* embedding, int64_t bytes) {
-    const uint8_t* p = (const uint8_t*)embedding;
-    uint64_t h = 0xcbf29ce484222325ull ^ mix64((uint64_t)bytes);
-    int64_t i = 0;
-    for (; i + 8 <= bytes; i += 8) {
-        uint64_t w; std::memcpy(&w, p + i, 8);
-        h = mix64(h ^ w);
-    }
-    uint64_t tail = 0;
-    for (int64_t k = 0; i + k < bytes; ++k) tail |= (uint64_t)p[i + k] << (8 * k);
-    return mix64(h ^ tail);
-}
-
 BlockHash chain_block_hash(const BlockHash& parent, const int32_t* toks, int32_t n,
                            const MMContentKey* mm, int32_t n_mm, int64_t block_begin) {
-    /* The parent seeds both lanes. That is the whole chained-hash property: a block with identical
-     * tokens under a different prefix lands somewhere else, so a block in the middle of another
-     * conversation cannot be served here. */
+    /* The parent seeds both lanes, so identical tokens under a different prefix hash differently. */
     BlockHash h;
     h.hi = mix64(parent.hi ^ 0x243f6a8885a308d3ull);
     h.lo = mix64(parent.lo ^ 0x13198a2e03707344ull);
@@ -56,9 +38,8 @@ BlockHash chain_block_hash(const BlockHash& parent, const int32_t* toks, int32_t
         h.hi = mix64(h.hi + h.lo + t);
     }
 
-    /* Multimodal spans that overlap this block, folded by CONTENT plus the overlap offsets, so the
-     * same image at the same position hashes the same and a different image never aliases behind
-     * the identical placeholder token ids (spec §11). */
+    /* Fold in overlapping multimodal spans by content hash plus offsets, so different images
+     * behind identical placeholder ids never alias (spec §11). */
     const int64_t lo_pos = block_begin, hi_pos = block_begin + n;
     for (int32_t i = 0; i < n_mm; ++i) {
         const MMContentKey& m = mm[i];
@@ -77,10 +58,18 @@ BlockHash chain_block_hash(const BlockHash& parent, const int32_t* toks, int32_t
 void GeometricBackoff::select(const std::vector& pos, std::vector* keep) const {
     keep->clear();
     if (pos.empty()) return;
-    const int64_t tip = (int64_t)pos.size() - 1;
+    const int64_t tip = pos.back();
     std::vector mark(pos.size(), 0);
-    mark[(size_t)tip] = 1;                    /* THE TIP IS ALWAYS KEPT */
-    for (int64_t d = 1; tip - d >= 0; d *= 2) mark[(size_t)(tip - d)] = 1;
+    mark.back() = 1;                          /* the tip is always kept */
+    for (int64_t s = interval_;; s *= 2) {
+        const int64_t b = tip / s;
+        for (int64_t j = b > 0 ? b - 1 : 0; j <= b; ++j) {
+            const auto it = std::lower_bound(pos.begin(), pos.end(), j * s);
+            if (it != pos.end() && *it < (j + 1) * s) mark[(size_t)(it - pos.begin())] = 1;
+        }
+        /* At this scale every position is in bucket 0, and so at every larger one. */
+        if (b == 0 || s > INT64_MAX / 4) break;
+    }
     for (size_t i = 0; i < pos.size(); ++i) if (mark[i]) keep->push_back(pos[i]);
 }
 
@@ -104,12 +93,11 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_
     groups_.clear();
     map_.clear(); lru_.clear();
     ck_by_prefix_.clear(); ck_by_session_.clear();
-    /* THE POLICY COMES FROM THE CONFIG, and set_policy() overrides it -- which is the order a
-     * test wants and the order an operator wants. The three names are checked in config_parse, so
-     * an unknown one cannot reach here and silently become the default. */
+    /* config_parse rejects unknown names, so the else branch is "geometric-backoff".
+     * set_policy() may override this afterwards. */
     if (cfg.checkpoint_policy == "tip-only")      policy_ = std::make_unique();
     else if (cfg.checkpoint_policy == "keep-all") policy_ = std::make_unique();
-    else                                          policy_ = std::make_unique();
+    else policy_ = std::make_unique(checkpoint_interval);
     report_.clear();
 
     if (!kv) return RAD_E_INVAL;
@@ -118,11 +106,8 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_
         return RAD_OK;
     }
 
-    /* The cache's granularity is the block size of the first FULL-attention group, because that is
-     * the group whose content a prefix hit actually reuses. A paged group with a different block
-     * size cannot be indexed at that granularity and is named in the report rather than silently
-     * skipped -- a group that quietly stops being prefix-cached is a hit-rate regression nobody
-     * can attribute. */
+    /* Granularity is the first full-attention group's block size, since that is what a hit
+     * reuses. Paged groups with another block size are not cached and are named in the report. */
     for (const auto& p : kv->plans()) {
         if (p.kind == RAD_KV_FULL && block_size_ == 0) block_size_ = p.block_size;
         if (p.stateful()) has_linear_ = true;
@@ -138,45 +123,35 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_
     std::string skipped;
     for (const auto& p : kv->plans()) {
         if (!p.paged()) continue;
-        /* A WINDOW GROUP CANNOT BE SERVED A PREFIX. Its blocks below the window are recycled, so
-         * the block list a hit hands over does not describe it -- adopt() would take a prefix's
-         * worth of blocks into a table the manager only ever grows to window_blocks, and the slot
-         * mapping is computed against a first_block_pos that a hit does not set. The group is
-         * simply not prefix-cached, which is correct and costs the sequences that hit a drafter
-         * or a windowed layer whose cache starts where the hit ended. */
+        /* A window group is not prefix-cached. Its blocks below the window are recycled, adopt()
+         * would overfill a table capped at window_blocks, and a hit does not set first_block_pos.
+         * A drafter or windowed layer's cache then starts where the hit ended. */
         if (p.kind == RAD_KV_WINDOW) {
-            skipped += fmt("  group '%s' is windowed (%lld blocks) -- NOT cached, a hit's blocks "
-                           "do not describe a cache whose floor moves\n",
+            skipped += fmt("  group '%s' is windowed (%lld blocks): not cached\n",
                            p.name.c_str(), (long long)p.window_blocks);
             continue;
         }
         if (p.block_size == block_size_) groups_.push_back(p.index);
-        else skipped += fmt("  group '%s' block %lld != cache granularity %lld -- NOT cached\n",
+        else skipped += fmt("  group '%s' block %lld != cache granularity %lld: not cached\n",
                             p.name.c_str(), (long long)p.block_size, (long long)block_size_);
     }
 
     interval_ = checkpoint_interval;
-    /* A WINDOW SNAPSHOT is state in the same sense: a hit is reusable at a checkpoint only, where
-     * the slot carries the window behind it (KVManager::has_window_snapshot). */
+    /* A window snapshot is state too: a hit is reusable only at a checkpoint, whose slot carries
+     * the window behind it (KVManager::has_window_snapshot). */
     if (kv->has_window_snapshot() && interval_ > 0) has_linear_ = true;
     if (has_linear_) {
         if (interval_ <= 0) {
-            RAD_ERR("checkpoint_interval is %lld but the model has linear-attention state. A "
-                    "0 interval means no checkpoint is ever written and every hit replays the "
-                    "linear layers from zero.", (long long)interval_);
+            RAD_ERR("checkpoint_interval is %lld but the model has linear-attention state, which "
+                    "needs a checkpoint for a hit to be usable", (long long)interval_);
             return RAD_E_INVAL;
         }
         if (interval_ % block_size_ != 0) {
-            /* A checkpoint that does not land on an attention block boundary can never be found:
-             * the lookup identifies a checkpoint by the chained hash at its position, and that
-             * hash only exists at block boundaries. vLLM's answer is to inflate the block to the
-             * interval, which is what costs it attention hit rate on every short prompt. Ours is
-             * to refuse the misconfiguration by name. */
+            /* A checkpoint is found by the chained hash at its position, which exists only on
+             * block boundaries, so an interval off the block grid would never hit. */
             RAD_ERR("the checkpoint interval resolves to %lld (from --checkpoint-interval %lld, "
-                    "rounded up to the chunk quantum) and that is not a multiple of the attention "
-                    "block size %lld. The linear checkpoint is found by the chained block hash at "
-                    "its position, and that hash exists only on a block boundary, so this interval "
-                    "would never produce a single hit (spec §7.3).",
+                    "rounded up to the chunk quantum), which is not a multiple of the attention "
+                    "block size %lld, so no checkpoint would ever hit (spec §7.3)",
                     (long long)interval_, (long long)cfg.checkpoint_interval,
                     (long long)block_size_);
             return RAD_E_INVAL;
@@ -185,11 +160,11 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_
 
     enabled_ = true;
     report_ = fmt("prefix cache: %zu paged group(s) at %lld-token blocks; linear checkpoints "
-                  "every %lld tokens (%s a rank x %s, pinned host memory), retention '%s'\n",
+                  "every %lld tokens (%lld slots of %s a rank, pinned host memory), retention "
+                  "'%s'\n",
                   groups_.size(), (long long)block_size_,
                   (long long)(has_linear_ ? interval_ : 0),
-                  humanb(kv->checkpoint_bytes()).c_str(),
-                  fmt("%lld slots", (long long)kv->checkpoint_slots()).c_str(),
+                  (long long)kv->checkpoint_slots(), humanb(kv->checkpoint_bytes()).c_str(),
                   policy_->name());
     report_ += skipped;
     return RAD_OK;
@@ -240,35 +215,20 @@ CacheHit PrefixCache::lookup(const std::vector& tokens,
     for (; matched < n_full; ++matched) {
         auto it = map_.find(hs[(size_t)matched]);
         if (it == map_.end()) break;
-        /* AN ENTRY THE TIERS HOLD IS NOT A HIT, and this is the guard that makes demotion safe at
-         * all. Moving an entry off the device releases its KV blocks; the map keeps the entry so
-         * the bytes can be found again, but its `blocks` now name blocks the pool has given to
-         * somebody else. Serving them would hand one conversation another's context -- exactly
-         * the failure the token compare below exists to rule out, arrived at from the other side.
-         *
-         * The prefix simply stops here. The caller may promote and ask again (see
-         * restorable_from), and until it does the answer is an honest shorter hit. An entry with
-         * a promotion still out on it stops the prefix too: its ids are the ones it left with. */
+        /* An off-device entry is not a hit: demotion released its blocks and its recorded ids now
+         * belong to other sequences. The prefix stops here (also while a promotion is in flight);
+         * the caller may promote and look up again (restorable_from). */
         if (!it->second.in_lru) break;
-        /* Compare the token ids, not just the hash. A 128-bit collision is improbable; serving one
-         * conversation's context to another is not a failure anybody would ever diagnose, so it is
-         * made impossible rather than unlikely. */
-        const int32_t* src = tokens.data() + matched * block_size_;
-        if ((int64_t)it->second.tokens.size() != block_size_ ||
-            std::memcmp(it->second.tokens.data(), src, (size_t)block_size_ * sizeof(int32_t)) != 0)
-            break;
+        if (!same_tokens(it->second, tokens.data() + matched * block_size_)) break;
     }
 
-    /* At least one token must remain for the step to compute a logit from. A full hit is backed
-     * off by one block rather than being handed to a caller that would then schedule a zero-token
-     * forward pass. */
+    /* Back a full hit off by one block so one token remains to compute a logit from. */
     if (matched * block_size_ >= (int64_t)tokens.size() && matched > 0) --matched;
 
-    /* OVER THE SNAPSHOTS, NOT OVER THE POSITIONS. A checkpoint sits on the interval or at the
-     * tail of a prompt (Scheduler::plan_chunk), which is any block boundary, so the deepest one
-     * at or below `limit` is found by asking each snapshot whether this chain passes through it:
-     * its key is the chained hash at its own position, which matches only on the same prefix. The
-     * index holds a few hundred snapshots against tens of thousands of block positions. */
+    /* Deepest valid snapshot at or below `limit` on this chain. Checkpoints sit on the interval or
+     * at a prompt's tail (Scheduler::plan_chunk), i.e. on any block boundary, so iterate the
+     * snapshots (a few hundred) rather than the block positions (tens of thousands); a snapshot is
+     * on this chain when its key equals the chain hash at its position. */
     auto deepest = [&](int64_t limit) {
         auto best = ck_by_prefix_.end();
         for (auto it = ck_by_prefix_.begin(); it != ck_by_prefix_.end(); ++it) {
@@ -282,8 +242,8 @@ CacheHit PrefixCache::lookup(const std::vector& tokens,
         }
         return best;
     };
-    /* What a hit of `m` blocks lets a sequence skip: all of it, or with recurrent state only up
-     * to the deepest checkpoint under it (Scheduler::admit_one resumes there). */
+    /* Tokens a hit of `m` blocks lets a sequence skip: all of them, or with recurrent state only
+     * up to the deepest checkpoint (Scheduler::admit_one resumes there). */
     auto reusable = [&](int64_t m) -> int64_t {
         if (!has_linear_) return m * block_size_;
         const auto b = deepest(m * block_size_);
@@ -302,29 +262,26 @@ CacheHit PrefixCache::lookup(const std::vector& tokens,
     }
 
     const uint64_t now = rad_mono_ns();
-    for (int64_t b = 0; b < matched; ++b) {
-        touch(hs[(size_t)b], now);
-        if (!blocks_out) continue;
-        const Entry& e = map_.find(hs[(size_t)b])->second;
-        for (size_t g = 0; g < groups_.size(); ++g)
-            (*blocks_out)[g].push_back(e.blocks[g]);
-    }
-    /* A HIT IS A USE, and the tiers' idle clock has to hear about it: it is what decides when an
-     * entry leaves the device, and without this it runs from when the chain was published, so a
-     * prefix hit on every turn -- or one just promoted back for this very lookup -- would read as
-     * idle and be demoted from under the request using it. */
+    /* Deepest first, so the chain's first block is the most recent: under pressure a conversation
+     * loses its end before its start, and what is left still hits. */
+    for (int64_t b = matched - 1; b >= 0; --b) touch(hs[(size_t)b], now);
+    if (blocks_out)
+        for (int64_t b = 0; b < matched; ++b) {
+            const Entry& e = map_.find(hs[(size_t)b])->second;
+            for (size_t g = 0; g < groups_.size(); ++g)
+                (*blocks_out)[g].push_back(e.blocks[g]);
+        }
+    /* A hit is a use for the tiers' idle clock too; otherwise a prefix hit every turn, or one just
+     * promoted for this lookup, would look idle since its publish. */
     if (tiers_ && matched > 0) tiers_->note_hits(hs.data(), matched, now);
     hit.n_attn_tokens = (int32_t)(matched * block_size_);
     stats_.block_hits += matched;
     stats_.block_misses += n_full - matched;
 
-    /* ---- the split: how far the LINEAR state can be reused ----
-     * The attention blocks are reusable up to n_attn_tokens. The recurrent state is only reusable
-     * at a checkpoint: the deepest snapshot at or below n_attn_tokens on this chain, in its store
-     * slot. The scheduler resumes from there (Scheduler::admit_one) and recomputes the tokens
-     * between the two. */
+    /* ---- the split: how far the linear state can be reused ----
+     * Recurrent state is reusable only at the deepest snapshot at or below n_attn_tokens; the
+     * scheduler resumes there (Scheduler::admit_one) and recomputes the tokens in between. */
     if (!has_linear_) {
-        /* No recurrent state means nothing to replay: the whole attention hit is directly usable. */
         hit.n_linear_tokens = hit.n_attn_tokens;
         return hit;
     }
@@ -335,7 +292,7 @@ CacheHit PrefixCache::lookup(const std::vector& tokens,
     }
     hit.n_linear_tokens = (int32_t)best->second.pos;
     hit.checkpoint_slot = best->second.slot;
-    best->second.used = ++clock_;
+    best->second.used = best->second.resumed = ++clock_;
     best->second.used_ns = now;
     handed_.push_back(best->first);
     ++stats_.ckpt_hits;
@@ -360,12 +317,11 @@ int PrefixCache::insert(uint64_t session,
     for (int64_t b = 0; b < n_full; ++b) {
         const BlockHash& h = hs[(size_t)b];
         auto it = map_.find(h);
-        if (it != map_.end() && it->second.in_lru) { touch(h, now); continue; }
+        if (it != map_.end() && it->second.in_lru) continue;     /* touched below */
         if (it != map_.end()) {
-            /* AN ENTRY WHOSE ONLY COPY IS OFF THE CARD, AND THIS REQUEST JUST COMPUTED IT AGAIN --
-             * a restore that did not fit, or a chain cut short. The request's blocks become the
-             * entry's device copy and the tier copy is let go (IdleTiers::rebound says why). One
-             * with a promotion still out on it is left alone: its record is the transfer's. */
+            /* An off-device entry this request recomputed (a restore that did not fit, or a chain
+             * cut short). Its blocks become the entry's device copy and the tier copy goes
+             * (IdleTiers::rebound). An entry with a promotion in flight is left alone. */
             if (!tiers_ || !tiers_->resident_off_device(h)) continue;
             std::vector mine(groups_.size(), -1);
             size_t held = 0;
@@ -384,7 +340,7 @@ int PrefixCache::insert(uint64_t session,
             lru_.push_back(h);
             e.lru = std::prev(lru_.end());
             e.in_lru = true;
-            tiers_->rebound(h, e.blocks, now);
+            tiers_->rebound(h, e.blocks, now, b);
             continue;
         }
 
@@ -397,9 +353,8 @@ int PrefixCache::insert(uint64_t session,
             e.blocks[held] = blk;
         }
         if (held != groups_.size()) {
-            /* Unwind exactly what was taken. A half-referenced entry leaks a block forever, and a
-             * released block that was never retained frees one out from under a live sequence --
-             * both are silent and neither is diagnosable later. */
+            /* Unwind exactly what was retained: anything else leaks a block or frees one under a
+             * live sequence. */
             for (size_t g = 0; g < held; ++g) kv_->release_block(groups_[g], e.blocks[g]);
             return RAD_E_STATE;
         }
@@ -411,37 +366,27 @@ int PrefixCache::insert(uint64_t session,
         e.in_lru = true;
         map_.emplace(h, std::move(e));
     }
+    /* Deepest first, as in lookup: the first block ends most recent. */
+    for (int64_t b = n_full - 1; b >= 0; --b) touch(hs[(size_t)b], now);
 
-    /* THE TIERS LEARN THE CHAIN HERE AND NOWHERE ELSE. insert() is the one call that knows a chain
-     * was COMPLETED rather than merely touched -- which is what a session is -- and it is also the
-     * only place every entry's block ids are in hand at once.
+    /* The tiers learn the chain only here: insert() is the one call that knows a chain was
+     * completed, and the only place every entry's block ids are in hand.
      *
-     * AND THE IDS COME OUT OF THE MAP, NOT OUT OF `blocks`. The two are the same for an entry this
-     * call just created and DIFFERENT for one that already existed, because the loop above keeps
-     * the entry the cache already holds and lets this request's own copy of those blocks go. Both
-     * block tables describe the same tokens, but only the cache's is REFERENCED: the other belongs
-     * to a sequence that is about to be freed.
-     *
-     * Recording the wrong one is not a bookkeeping detail. The tiers demote what they were told,
-     * so they would gather out of blocks the pool had already handed to somebody else -- putting a
-     * stranger's KV in the tier under this prefix's key -- and then release a reference nobody
-     * took. It shows as a flood of "double free of block N" in the log and, once the entry is
-     * promoted back, as fluent text with one word changed. */
+     * The ids come from the map, not from `blocks`. For an entry that already existed the loop
+     * above kept the cache's blocks, and `blocks` belongs to a sequence about to be freed; the
+     * tiers would copy from blocks reassigned to another sequence. */
     if (tiers_) {
         for (int64_t b = 0; b < n_full; ++b) {
             auto it = map_.find(hs[(size_t)b]);
             if (it == map_.end()) continue;
-            tiers_->note_used(hs[(size_t)b], it->second.blocks, now);
+            tiers_->note_used(hs[(size_t)b], it->second.blocks, now, b);
         }
         tiers_->note_session(session, hs, n_tokens, now, label);
     }
 
-    /* A CONVERSATION'S SNAPSHOTS BELONG TO ITS LATEST TURN. The index keys a session by REQUEST
-     * id, so each turn would otherwise keep its own tip forever: turn N-1's deepest snapshot stays
-     * a "tip" after turn N has resumed from it and written deeper ones, and the retention policy
-     * then guards a dozen dead tips across a long agent run while thinning the one conversation
-     * that is live. Every snapshot on the chain this request just published is a prefix of it,
-     * and is moved under this id, so the policy sees one session with one tip. */
+    /* A conversation's snapshots belong to its latest turn. Sessions are keyed by request id, so
+     * without this each earlier turn's deepest snapshot would stay a protected tip. Every snapshot
+     * on the chain just published moves under this id, so the policy sees one session, one tip. */
     for (auto& kvp : ck_by_prefix_) {
         Ckpt& c = kvp.second;
         if (c.session == session || c.pos <= 0 || c.pos > n_full * block_size_ ||
@@ -467,35 +412,20 @@ std::vector PrefixCache::restorable_from(const std::vector&
     std::vector out;
     if (!enabled_ || !tiers_ || tokens.empty()) return out;
 
-    /* THE BLOCKS A HIT CAN USE: one token must remain to compute a logit from, so a prompt that
-     * ends on a block boundary never reuses its last block (lookup backs off by one) and neither
-     * restoring it would be read. */
+    /* Only blocks a hit can use: one token must remain, so a prompt ending on a block boundary
+     * never reuses its last block (lookup backs off by one). */
     const int64_t n_full = ((int64_t)tokens.size() - 1) / block_size_;
     std::vector hs = chain_all(tokens, mm, n_full);
 
-    /* Walk exactly as lookup does, and keep walking past the point it stopped for as long as the
-     * chain holds. EVERY off-device block in it is collected, not just the first run of them.
-     *
-     * STOPPING AT THE FIRST RESIDENT BLOCK PAST A GAP, on the reasoning that "the run this call is
-     * about has ended", would be wrong, and the way it is wrong is worth stating because the
-     * symptom does not look like a caching bug at all. A hit needs the WHOLE prefix:
-     * restoring blocks 0..99 and stopping leaves block 200 off-device, so the hit ends at 200 and
-     * everything above it is re-prefilled -- and WHICH blocks are off-device at the moment this
-     * runs depends on how far the maintenance pass has got. The same prompt then gets a different
-     * hit length on each restore.
-     *
-     * That is not only a lost prefix. The hit length is what the scheduler chunks the remaining
-     * prefill against, so two restores that recovered different amounts run different GEMM shapes
-     * over the same tokens -- and greedy decoding is tie-level sensitive to that (§19). The
-     * session's answer moves between restores, intermittently, with nothing wrong in the KV at
-     * all. Restoring the whole chain makes the hit length a property of the prompt. */
+    /* Walk as lookup does, past where it stopped, and collect every off-device block on the
+     * chain, not just the first run. Stopping at the first gap would make the hit length depend on
+     * how far the maintenance pass had got; the scheduler chunks the rest of the prefill against
+     * that length, and greedy output is tie-level sensitive to the GEMM shapes (§19). Restoring
+     * the whole chain makes the hit length a function of the prompt. */
     for (int64_t b = 0; b < n_full; ++b) {
         auto it = map_.find(hs[(size_t)b]);
         if (it == map_.end()) break;
-        const int32_t* src = tokens.data() + b * block_size_;
-        if ((int64_t)it->second.tokens.size() != block_size_ ||
-            std::memcmp(it->second.tokens.data(), src, (size_t)block_size_ * sizeof(int32_t)) != 0)
-            break;
+        if (!same_tokens(it->second, tokens.data() + b * block_size_)) break;
         if (tiers_->resident_off_device(hs[(size_t)b])) out.push_back(hs[(size_t)b]);
     }
     return out;
@@ -504,15 +434,13 @@ std::vector PrefixCache::restorable_from(const std::vector&
 void PrefixCache::drop_offdevice(const BlockHash& key) {
     auto it = map_.find(key);
     if (it == map_.end()) return;
-    /* NO release_block HERE, and that is the whole point. The entry has been off-device since it
-     * was demoted; the ids in it name blocks the pool reassigned long ago, so releasing them
-     * would free somebody else's context and serving them would hand it over. */
+    /* No release_block: the ids name blocks the pool has reassigned (see the declaration). */
     if (it->second.in_lru) lru_.erase(it->second.lru);
     map_.erase(it);
     ++stats_.evictions;
-    /* A SNAPSHOT KEYED BY THE SAME HASH STAYS. No lookup reaches it past the missing block, and
-     * the retention policy or the expiry retires it through the path that tells the tiers
-     * (retire_ckpt) -- this one is called by the tiers, holding their lock. */
+    /* A snapshot under the same key stays: no lookup reaches it past the missing block, and
+     * retention or expiry retires it via retire_ckpt. It cannot be retired here because the tiers
+     * call this holding their lock. */
 }
 
 int PrefixCache::rebind(const BlockHash& key, const std::vector& blocks) {
@@ -520,11 +448,9 @@ int PrefixCache::rebind(const BlockHash& key, const std::vector& blocks
     if (it == map_.end()) return RAD_E_NOTFOUND;
     if (blocks.size() != groups_.size()) return RAD_E_SHAPE;
     for (int32_t b : blocks) if (b < 0) return RAD_E_INVAL;
-    /* THE RESERVATION'S REFERENCE BECOMES THE CACHE'S. KVManager::reserve_block left each block at
-     * a refcount of one with no sequence attached; assigning them here is the handover, and the
-     * cache's ordinary release path frees them from now on. Retaining and then releasing to "make
-     * it explicit" would be a round trip to the same number and would only obscure which reference
-     * is which. */
+    /* The reservation's reference becomes the cache's: KVManager::reserve_block left each block at
+     * refcount one with no sequence attached, and the cache's release path frees it from now on.
+     * No extra retain. */
     Entry& e = it->second;
     e.blocks = blocks;
     for (size_t g = 0; g < groups_.size(); ++g) kv_->cache_reserved_block(groups_[g], blocks[g]);
@@ -544,14 +470,22 @@ bool PrefixCache::shared_with_live(const Entry& e) const {
     return false;
 }
 
+/* Token ids are compared too, so a hash collision is a miss rather than another conversation's
+ * context. */
+bool PrefixCache::same_tokens(const Entry& e, const int32_t* src) const {
+    return (int64_t)e.tokens.size() == block_size_ &&
+           std::memcmp(e.tokens.data(), src, (size_t)block_size_ * sizeof(int32_t)) == 0;
+}
+
+void PrefixCache::release_blocks(const Entry& e) {
+    for (size_t g = 0; g < groups_.size(); ++g) kv_->release_block(groups_[g], e.blocks[g]);
+}
+
 int64_t PrefixCache::evict_lru(int64_t n) {
     int64_t done = 0;
-    /* ONE PASS OVER WHAT WAS ON THE LIST WHEN THE CALL BEGAN. An entry a live sequence also holds
-     * goes to the back rather than being evicted: releasing the cache's reference on it frees no
-     * block, and an entry that had no host copy would be erased for nothing. It is in use, which is
-     * what the back of the list means, and moving it is what keeps a caller that asks again from
-     * walking the same shared run every time. It is stamped as used, which keeps the list in the
-     * clock's order. */
+    /* One pass over the list as it was on entry. An entry a live sequence also holds is in use:
+     * it moves to the back, stamped, so the list stays in clock order and the next call does not
+     * walk the same shared run. */
     const uint64_t now = rad_mono_ns();
     for (int64_t seen = (int64_t)lru_.size(); done < n && seen > 0 && !lru_.empty(); --seen) {
         const BlockHash h = lru_.front();
@@ -565,10 +499,9 @@ int64_t PrefixCache::evict_lru(int64_t n) {
         }
         lru_.pop_front();
         e.in_lru = false;
-        for (size_t g = 0; g < groups_.size(); ++g)
-            kv_->release_block(groups_[g], e.blocks[g]);
+        release_blocks(e);
         if (tiers_) {
-            /* THE HOST COPY HAS LANDED: the entry leaves VRAM and stays in the index. */
+            /* Host copy landed: the entry leaves VRAM and stays in the index. */
             if (tiers_->droppable(h)) {
                 tiers_->drop_commit(h);
                 ++stats_.drops;
@@ -585,9 +518,8 @@ int64_t PrefixCache::evict_lru(int64_t n) {
 }
 
 int64_t PrefixCache::trim(int64_t n_blocks) {
-    /* TIERS ATTACHED AND OFF are no tiers: nothing becomes droppable, and waiting for a copy that
-     * nobody will make would leave the reserve unkept for good. */
-    const bool keep = tiers_ && tiers_->any_on();
+    /* Tiers attached but off count as no tiers: no copy will ever land, so do not wait for one. */
+    const bool keep = tiers_ && tiers_->host_on();
     const uint64_t now = rad_mono_ns();
     int64_t done = 0;
     auto it = lru_.begin();
@@ -598,7 +530,7 @@ int64_t PrefixCache::trim(int64_t n_blocks) {
         if (m == map_.end()) { it = lru_.erase(it); continue; }
         Entry& e = m->second;
         if (shared_with_live(e)) {
-            /* In use: to the back, as evict_lru does, and the walk carries on from the next. */
+            /* In use: to the back, as in evict_lru. */
             auto next = std::next(it);
             lru_.splice(lru_.end(), lru_, it);
             e.used_ns = now;
@@ -608,8 +540,7 @@ int64_t PrefixCache::trim(int64_t n_blocks) {
         if (keep && !tiers_->droppable(h)) { ++it; continue; }
         it = lru_.erase(it);
         e.in_lru = false;
-        for (size_t g = 0; g < groups_.size(); ++g)
-            kv_->release_block(groups_[g], e.blocks[g]);
+        release_blocks(e);
         if (keep) {
             tiers_->drop_commit(h);
             ++stats_.drops;
@@ -631,6 +562,10 @@ int64_t PrefixCache::drop_clean() {
     if (frees != frees_seen_ || released_) {
         frees_seen_ = frees;
         released_ = false;
+        for (const BlockHash& h : drop_wait_) {
+            auto it = map_.find(h);
+            if (it != map_.end()) it->second.drop_wait = false;
+        }
         drop_scratch_.insert(drop_scratch_.end(), drop_wait_.begin(), drop_wait_.end());
         drop_wait_.clear();
     }
@@ -639,20 +574,14 @@ int64_t PrefixCache::drop_clean() {
         auto it = map_.find(h);
         if (it == map_.end()) continue;
         Entry& e = it->second;
-        e.drop_wait = false;
         if (!e.in_lru || !tiers_->droppable(h)) continue;
-        /* A BLOCK A RUNNING SEQUENCE ALSO HOLDS WOULD FREE NOTHING, and its entry would then be
-         * off-device in the index while its bytes sat in VRAM under somebody else's table -- the
-         * next lookup would restore a second copy beside them. */
-        bool shared = held_.count(h) > 0;
-        for (size_t g = 0; g < groups_.size() && !shared; ++g)
-            shared = kv_->block_refcount(groups_[g], e.blocks[g]) > 1;
-        if (shared) {
+        /* Skip held entries and blocks a running sequence also holds: dropping would free nothing,
+         * and the next lookup would restore a second copy beside the one still in VRAM. */
+        if (held_.count(h) > 0 || shared_with_live(e)) {
             if (!e.drop_wait) { e.drop_wait = true; drop_wait_.push_back(h); }
             continue;
         }
-        for (size_t g = 0; g < groups_.size(); ++g)
-            kv_->release_block(groups_[g], e.blocks[g]);
+        release_blocks(e);
         lru_.erase(e.lru);
         e.in_lru = false;
         ++stats_.drops;
@@ -662,18 +591,9 @@ int64_t PrefixCache::drop_clean() {
     return n;
 }
 
-/* THE REFCOUNT IS WHAT SEPARATES A CACHE FROM A LEAK. A block the cache indexes and a running
- * sequence is reading is not memory the cache could give back; a block only the cache references
- * is exactly what the next eviction frees. Nothing else distinguishes them -- both are `used`,
- * both are in the index -- so the count is the manager's: it marks the blocks the cache holds and
- * keeps the number of marked blocks at a reference count of one current as the counts move.
- *
- * ONE GROUP, FOR THE REASON THE POOL'S OWN TOKEN FIGURES ARE ONE GROUP'S: the paged groups share
- * a token axis and an entry is one block in each of them, so counting every group would multiply
- * the answer by the group count.
- *
- * OFF-DEVICE ENTRIES COUNT FOR NOTHING. A demoted entry released its blocks, and the mark went
- * with the release; its bytes are in host memory and it is holding none of the card. */
+/* The KV manager tracks how many cache-held blocks are at refcount one. One group only: the paged
+ * groups share a token axis and an entry is one block in each, so summing groups would multiply
+ * the answer. Off-device entries hold no blocks and count for nothing. */
 int64_t PrefixCache::unshared_tokens() const {
     if (!kv_ || groups_.empty() || block_size_ <= 0) return 0;
     return kv_->cache_only_blocks(groups_[0]) * block_size_;
@@ -681,9 +601,7 @@ int64_t PrefixCache::unshared_tokens() const {
 
 void PrefixCache::clear() {
     for (auto& kv : map_) {
-        if (kv.second.in_lru)
-            for (size_t g = 0; g < groups_.size(); ++g)
-                kv_->release_block(groups_[g], kv.second.blocks[g]);
+        if (kv.second.in_lru) release_blocks(kv.second);
         if (tiers_) tiers_->forget(kv.first);
         ++stats_.evictions;
     }
@@ -734,24 +652,35 @@ int64_t PrefixCache::retain(uint64_t session) {
     for (const auto& a : all) pos.push_back(a.first);
     std::vector keep;
     policy_->select(pos, &keep);
+    /* A policy may return its keep set in any order; the lookup below needs it sorted. */
+    std::sort(keep.begin(), keep.end());
+    const uint64_t tip_made = all.empty() ? 0 : ck_by_prefix_.find(all.back().second)->second.made;
 
     int64_t freed = 0;
     for (const auto& a : all) {
         if (std::binary_search(keep.begin(), keep.end(), a.first)) { kept.push_back(a.second); continue; }
-        /* NOR ONE HANDED OUT THIS STEP, whatever the policy says of its position: the admission it
-         * was handed to restores from the slot ahead of the step, and that is after this runs. */
+        /* Keep one handed out this step regardless of policy: its admission restores from the
+         * slot ahead of the step. */
         if (handed(a.second)) { kept.push_back(a.second); continue; }
         auto e = ck_by_prefix_.find(a.second);
         if (e == ck_by_prefix_.end()) continue;
+        /* And one a lookup resumed from since the session's tip was written. The policy places
+         * its ladder from the tip, but a later turn that resumed below the tip has left this
+         * chain there (a rewritten last message), and its next turn most likely resumes there
+         * again. */
+        if (e->second.resumed > tip_made) { kept.push_back(a.second); continue; }
+        RAD_DEBUG("prefix cache: snapshot at %lld of session %llu released by retention '%s' "
+                  "(unused for %.1f s)", (long long)e->second.pos,
+                  (unsigned long long)e->second.session, policy_->name(),
+                  idle_s(e->second.used_ns));
         retire_ckpt(e);
         ++freed;
         ++stats_.ckpt_evictions;
+        ++stats_.ckpt_retired;
     }
-    /* ERASE THE SESSION WHEN NOTHING IS LEFT OF IT, and that is not tidiness. `session` is a
-     * REQUEST id, so without an eraser this map gains an entry for every request that ever writes
-     * a checkpoint: the vector empties, here and in the eviction below, and the key stays. The
-     * cost is not the bytes -- it is that the loop in reserve_checkpoint walks EVERY key on every
-     * allocation failure, which is the one path this cache exists to relieve. */
+    /* Erase an emptied session. Sessions are request ids, so otherwise the map grows by one key
+     * per request that ever checkpointed, and reserve_checkpoint walks every key on each
+     * allocation failure. */
     if (kept.empty()) { ck_by_session_.erase(it); return freed; }
     it->second = std::move(kept);
     return freed;
@@ -761,17 +690,17 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa
                                     int32_t* slot_out) {
     if (!enabled_ || !has_linear_) return RAD_E_UNSUPPORTED;
     if (!slot_out) return RAD_E_INVAL;
-    /* ON A BLOCK BOUNDARY, because the key is the chained hash of whole blocks. The scheduler
-     * places checkpoints on the interval and at the tail of a prompt, both on its chunk quantum,
-     * which is a multiple of the block. */
+    /* The key is the chained hash of whole blocks, so `pos` must be on a block boundary. The
+     * scheduler places checkpoints on its chunk quantum, a multiple of the block. */
     if (interval_ <= 0 || pos <= 0 || pos % block_size_ != 0) {
-        RAD_ERR("checkpoint at %lld is not on a %lld-token block boundary; the scheduler splits "
-                "chunks on its quantum precisely so this cannot happen (spec §7.3)",
+        RAD_ERR("checkpoint at %lld is not on a %lld-token block boundary, which the scheduler's "
+                "chunk quantum rules out (spec §7.3)",
                 (long long)pos, (long long)block_size_);
         return RAD_E_INVAL;
     }
     auto existing = ck_by_prefix_.find(prefix);
     if (existing != ck_by_prefix_.end()) {
+        existing->second.used = ++clock_;
         existing->second.used_ns = rad_mono_ns();
         *slot_out = existing->second.slot;
         return RAD_OK;
@@ -779,64 +708,48 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa
 
     int32_t slot = -1;
     if (kv_->alloc_checkpoint(&slot) < 0) {
-        /* Budgeted retention: run the policy over every session before giving up. The tip of each
-         * session survives it by construction, because that is what an appending agent transcript
-         * needs (spec §7.3).
-         *
-         * Over a SNAPSHOT of the keys, because retain() erases a session it empties and a
-         * range-for over the map would be iterating a container it is erasing from. */
+        /* Run retention over every session. Iterate a copy of the keys: retain() erases sessions
+         * it empties. */
         std::vector sessions;
         sessions.reserve(ck_by_session_.size());
         for (const auto& s : ck_by_session_) sessions.push_back(s.first);
         for (uint64_t s : sessions) retain(s);
         if (kv_->alloc_checkpoint(&slot) < 0) {
-            /* Still nothing. Drop the globally least-recently-used snapshot, PREFERRING a non-tip
-             * one -- but falling back to a tip rather than giving up.
-             *
-             * MAKING A TIP UNEVICTABLE OUTRIGHT WEDGES THE POOL PERMANENTLY. A session here is a
-             * REQUEST id (PCBinding passes r.id), and a finished request's checkpoints are meant
-             * to outlive it -- they are keyed by chained prefix hash, which is exactly how the
-             * next turn of an agent transcript finds them. So every request that writes a
-             * checkpoint leaves a tip behind and nothing ever retires one: after
-             * --checkpoint-slots such requests, every slot holds a dead session's tip and this
-             * would return RAD_E_FULL for the life of the process. The scheduler ignores the
-             * failure (scheduler.cpp: `>= 0 && cs >= 0`), so linear prefix caching would simply
-             * stop, with nothing in the log.
-             *
-             * Two passes rather than one comparison, because "prefer a non-tip" is a tier and not
-             * a tiebreak: the oldest tip must lose to the newest non-tip. */
+            /* Evict the least recently used snapshot, where a use is its reservation or a lookup
+             * resuming from it, and never one handed out this step (its admission restores from
+             * the slot ahead of the step). A tip gets no protection beyond its recency: sessions
+             * are request ids, and a client that rewrites its last message leaves one tip per
+             * turn that no later turn reaches, while the anchor every turn resumes from is used
+             * each turn. */
             const Ckpt* victim = nullptr;
-            const Ckpt* tip_victim = nullptr;
             for (const auto& kvp : ck_by_prefix_) {
-                /* NOT ONE A LOOKUP HANDED OUT THIS STEP: its admission restores from the slot
-                 * ahead of the step, and a slot freed under it restores nothing. */
                 if (handed(kvp.first)) continue;
-                auto sit = ck_by_session_.find(kvp.second.session);
-                bool is_tip = false;
-                if (sit != ck_by_session_.end()) {
-                    int64_t tip = -1;
-                    for (const BlockHash& h : sit->second) {
-                        auto e = ck_by_prefix_.find(h);
-                        if (e != ck_by_prefix_.end()) tip = std::max(tip, e->second.pos);
-                    }
-                    is_tip = (kvp.second.pos == tip);
-                }
-                const Ckpt*& best = is_tip ? tip_victim : victim;
-                if (!best || kvp.second.used < best->used) best = &kvp.second;
+                if (!victim || kvp.second.used < victim->used) victim = &kvp.second;
             }
-            if (!victim) victim = tip_victim;
-            if (!victim) return RAD_E_FULL;
+            if (!victim) {
+                ++stats_.ckpt_refused;
+                RAD_DEBUG("prefix cache: no snapshot at %lld for session %llu: every one of the "
+                          "%lld slots was handed out this step", (long long)pos,
+                          (unsigned long long)session, (long long)ck_by_prefix_.size());
+                return RAD_E_FULL;
+            }
+            RAD_DEBUG("prefix cache: store full, snapshot at %lld of session %llu (%s) evicted "
+                      "as the least recently used, unused for %.1f s", (long long)victim->pos,
+                      (unsigned long long)victim->session,
+                      is_tip(*victim) ? "its tip" : "below its tip", idle_s(victim->used_ns));
             const BlockHash vh = victim->prefix;
             const uint64_t vs = victim->session;
             retire_ckpt(ck_by_prefix_.find(vh));
             ++stats_.ckpt_evictions;
+            ++stats_.ckpt_lru;
             unindex_ckpt(vs, vh);
-            if (kv_->alloc_checkpoint(&slot) < 0) return RAD_E_FULL;
+            if (kv_->alloc_checkpoint(&slot) < 0) { ++stats_.ckpt_refused; return RAD_E_FULL; }
         }
     }
 
     Ckpt c;
-    c.session = session; c.pos = pos; c.prefix = prefix; c.slot = slot; c.used = ++clock_;
+    c.session = session; c.pos = pos; c.prefix = prefix; c.slot = slot;
+    c.used = c.made = ++clock_;
     c.used_ns = rad_mono_ns();
     ck_by_prefix_.emplace(prefix, c);
     ck_by_session_[session].push_back(prefix);
@@ -847,12 +760,10 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa
 void PrefixCache::commit_checkpoint(const BlockHash& prefix) {
     auto it = ck_by_prefix_.find(prefix);
     if (it == ck_by_prefix_.end()) return;
-    /* One that lost its slot between the reservation and now holds nothing to serve. */
+    /* One that lost its slot since the reservation holds nothing to serve. */
     if (it->second.slot < 0) return;
     it->second.valid = true;
-    /* THE TIERS LEARN THE SNAPSHOT HERE, for the session view: before the commit the slot still
-     * holds the previous tenant's state, so this is the earliest moment at which telling them
-     * would be true. */
+    /* Tell the tiers (for the session view) only now that the slot holds this state. */
     if (tiers_) tiers_->note_snapshot(prefix, it->second.slot, it->second.pos);
 }
 
@@ -861,14 +772,27 @@ void PrefixCache::commit_checkpoint(const BlockHash& prefix) {
 
 void PrefixCache::retire_ckpt(std::unordered_map::iterator it) {
     if (it == ck_by_prefix_.end()) return;
-    /* THE TIERS ARE TOLD, because they name the slot too: note_snapshot records it for the session
-     * view, and a view that kept it would count a slot the store has since given to another
-     * session as this one's resume point. */
+    /* The tiers record the slot for the session view and must stop naming it before it is reused. */
     if (tiers_) tiers_->release_snapshot(it->first);
     if (it->second.slot >= 0) kv_->free_checkpoint(it->second.slot);
     ck_by_prefix_.erase(it);
 }
 
+bool PrefixCache::is_tip(const Ckpt& c) const {
+    auto s = ck_by_session_.find(c.session);
+    if (s == ck_by_session_.end()) return false;
+    for (const BlockHash& h : s->second) {
+        auto e = ck_by_prefix_.find(h);
+        if (e != ck_by_prefix_.end() && e->second.pos > c.pos) return false;
+    }
+    return true;
+}
+
+double PrefixCache::idle_s(uint64_t used_ns) {
+    const uint64_t now = rad_mono_ns();
+    return now > used_ns ? (double)(now - used_ns) * 1e-9 : 0.0;
+}
+
 void PrefixCache::unindex_ckpt(uint64_t session, const BlockHash& key) {
     auto sit = ck_by_session_.find(session);
     if (sit == ck_by_session_.end()) return;
@@ -885,24 +809,12 @@ void PrefixCache::hold(uint64_t req, const std::vector& tokens,
     for (int64_t b = 0; b < n_full; ++b) {
         auto it = map_.find(hs[(size_t)b]);
         if (it == map_.end()) break;
-        const int32_t* src = tokens.data() + b * block_size_;
-        if ((int64_t)it->second.tokens.size() != block_size_ ||
-            std::memcmp(it->second.tokens.data(), src, (size_t)block_size_ * sizeof(int32_t)) != 0)
-            break;
+        if (!same_tokens(it->second, tokens.data() + b * block_size_)) break;
         mine.push_back(hs[(size_t)b]);
         ++held_[hs[(size_t)b]];
     }
 }
 
-size_t PrefixCache::resident_prefix(const std::vector& chain) const {
-    size_t n = 0;
-    for (; n < chain.size(); ++n) {
-        auto it = map_.find(chain[n]);
-        if (it == map_.end() || !it->second.in_lru) break;
-    }
-    return n;
-}
-
 void PrefixCache::release(uint64_t req) {
     auto it = holds_.find(req);
     if (it == holds_.end()) return;
@@ -921,9 +833,8 @@ int64_t PrefixCache::expire(uint64_t now_ns, uint64_t ttl_ns) {
     const uint64_t cutoff = now_ns - ttl_ns;
     int64_t n = 0;
 
-    /* ---- in VRAM: the LRU list is in the clock's order, so the walk stops at the first entry it
-     * keeps. A block a running sequence also holds stays allocated -- releasing the cache's
-     * reference is not freeing the block -- and that sequence publishes it again when it ends. */
+    /* ---- in VRAM: the LRU is in clock order, so stop at the first entry kept. A block a running
+     * sequence also holds stays allocated; that sequence republishes it when it ends. */
     while (!lru_.empty()) {
         const BlockHash h = lru_.front();
         auto it = map_.find(h);
@@ -932,15 +843,14 @@ int64_t PrefixCache::expire(uint64_t now_ns, uint64_t ttl_ns) {
         if (e.used_ns >= cutoff) break;
         lru_.pop_front();
         e.in_lru = false;
-        for (size_t g = 0; g < groups_.size(); ++g)
-            kv_->release_block(groups_[g], e.blocks[g]);
+        release_blocks(e);
         /* The host copy goes with it: an expired entry is not demoted. */
         if (tiers_) tiers_->forget(h);
         map_.erase(it);
         ++n;
     }
 
-    /* ---- only in host memory: the tiers keep these in the clock's order too. */
+    /* ---- only in host memory: the tiers keep these in clock order too. */
     if (tiers_) {
         std::vector keys;
         tiers_->expired(cutoff, (size_t)-1, &keys);
@@ -953,10 +863,8 @@ int64_t PrefixCache::expire(uint64_t now_ns, uint64_t ttl_ns) {
         }
     }
 
-    /* ---- snapshots, used when their prefix entry is or when a lookup hands them out. Not one
-     * that is still being written (a reservation not yet committed) and not one handed out this
-     * step: its admission restores from the slot ahead of the step. There are --checkpoint-slots
-     * of them at most, so the whole index is walked. */
+    /* ---- snapshots: skip uncommitted reservations and ones handed out this step. At most
+     * --checkpoint-slots of them, so walk the whole index. */
     std::vector gone;
     for (const auto& kvp : ck_by_prefix_) {
         const Ckpt& c = kvp.second;
diff --git a/core/mem/prefix.h b/core/mem/prefix.h
index 3856e337..90c40efb 100644
--- a/core/mem/prefix.h
+++ b/core/mem/prefix.h
@@ -1,54 +1,38 @@
-/* prefix.h -- prefix caching (spec §7.3). TWO mechanisms, because full attention and linear
- * attention cannot share one.
+/* prefix.h -- prefix caching (spec §7.3). Full and linear attention need separate mechanisms.
  *
- * FULL ATTENTION: content-hashed blocks with a CHAINED hash, so a block's identity includes its
- * whole prefix. LRU eviction, copy-on-write on fork, and multimodal inputs hashed BY CONTENT --
- * an image is a cache hit, because the hash is taken over the EMBEDDING span rather than the
- * image bytes.
+ * Full attention: content-hashed blocks with a chained hash, so a block's identity includes its
+ * whole prefix. LRU eviction and copy-on-write on fork. Multimodal spans are keyed by their
+ * processed patches, not the file bytes (MMContentKey).
  *
- * LINEAR ATTENTION: a state checkpoint. A GDN layer's recurrent state at position N depends on
- * all of 0..N and is one fixed-size object per sequence -- 32 heads of 128x128 fp32 is 2 MiB a
- * layer, roughly 96 MiB across the 48 linear layers of a Qwen3-Next. Snapshotting that per 16-token
- * block is not affordable at any block count. We take vLLM's `--mamba-cache-mode align` mechanism
- * and change two things:
+ * Linear attention: state checkpoints. A GDN layer's recurrent state at position N depends on all
+ * of 0..N and is one fixed-size object per sequence (on Qwen3.5-27B, 48 heads of 128x128 fp32 is
+ * 3 MiB a layer, 144 MiB across its 48 linear layers), far too large to snapshot per 16-token
+ * block. This follows vLLM's `--mamba-cache-mode align` with two changes:
  *
- *   (a) THE CHECKPOINT INTERVAL IS DECOUPLED FROM THE ATTENTION BLOCK SIZE. vLLM inflates the
- *       attention block to match the mamba page -- 528 tokens for Qwen3.5, 2240 for the 35B-A3B --
- *       and since prefix caching is block-granular, every prompt shorter than that gets a 0% hit
- *       rate on ATTENTION as well. We could not inflate the attention block even if we wanted to:
- *       §7.2 takes it from the resolved kernel and libr4d's paged attention is compiled for 16.
- *       So attention caches at 16-token granularity and Config::checkpoint_interval is a separate,
- *       much larger number. A hit landing BETWEEN checkpoints reuses the attention blocks and
- *       replays only the linear layers forward from the last checkpoint. That is what CacheHit's
- *       two token counts are: `n_attn_tokens` is free, `[n_linear_tokens, n_attn_tokens)` costs a
- *       linear-layers-only forward pass, and the rest is an ordinary prefill.
+ *   (a) The checkpoint interval is decoupled from the attention block size. vLLM inflates the
+ *       attention block to the mamba page (528 tokens for Qwen3.5, 2240 for the 35B-A3B), so
+ *       shorter prompts get no attention hits either. Here the attention block stays 16 (§7.2
+ *       takes it from the kernel; libr4d's paged attention is compiled for 16) and
+ *       Config::checkpoint_interval is a separate, larger number. A hit between checkpoints
+ *       reuses the attention blocks and replays only the linear layers from the last checkpoint:
+ *       in CacheHit, `n_attn_tokens` is free, `[n_linear_tokens, n_attn_tokens)` costs a
+ *       linear-layers-only pass, and the rest is ordinary prefill.
  *
- *   (b) CHECKPOINTS ARE TAKEN DELIBERATELY, NOT OPPORTUNISTICALLY. vLLM writes one only when a
- *       scheduler step happens to end on a boundary, which is why a checkpoint landing in
- *       request-unique tokens silently drops caching to zero. Our scheduler owns chunk boundaries
- *       (spec §7.1) and splits a chunk AT the interval, so one is always written. The cost is an
- *       occasional short chunk; the benefit is that hit rate is a property of the workload rather
- *       than of scheduling luck. `next_checkpoint_after()` is what the scheduler splits on.
+ *   (b) Checkpoints are taken deliberately. vLLM writes one only when a step happens to end on a
+ *       boundary. The scheduler here owns chunk boundaries (spec §7.1) and splits a chunk at the
+ *       interval (next_checkpoint_after()), so a checkpoint is always written, at the cost of an
+ *       occasional short chunk.
  *
- * ============================== WHAT IT COSTS TO HOLD, AND WHEN IT STOPS WORKING ==============
+ * Sizing: the cache holds a KV reference on every block it indexes, so pool demand scales with
+ * live sessions, not running requests. Hit rate falls off a cliff with pool utilisation: intact
+ * below about 75%, half gone by about 81%, and zero once the sessions no longer fit, because each
+ * turn evicts the prefixes the next one needs. Output is unaffected; TTFT grows 10-100x. A context
+ * of T tokens occupies about 1.8 x T pool-tokens across the paged groups. The budget gives the
+ * cache what the experts can spare (core/mem/vram_budget.h); --host-pool-mib moves that.
  *
- * The cache takes a KV REFERENCE on every block it indexes, so a finished sequence's blocks stay
- * held for the next turn. That is the whole point -- and it means the pool's demand is the number
- * of LIVE SESSIONS, not of running requests. Size it the other way and the failure is not graceful.
- *
- * THE THRESHOLD IS POOL UTILISATION, and it is a CLIFF rather than a slope. Below roughly 75%
- * utilisation the cache is whole; by around 81% half of it is gone; once the sessions no longer
- * fit at all the cache is not degraded but DEFEATED -- each turn evicts the prefixes the next turn
- * wants, so every turn re-prefills its whole context and the hit rate is zero. The generated text
- * is unaffected either way; the only difference is whether the prefixes still exist when the next
- * turn asks for them, and that difference is one to two orders of magnitude of time to first
- * token. Size the cache so live sessions fit with room to spare -- a context of T tokens occupies
- * roughly 1.8 x T pool-tokens across the paged groups. The budget gives the cache everything the
- * experts can do without (core/mem/vram_budget.h); --host-pool-mib is what moves that.
- *
- * WHAT TO WATCH: `kv_util` (/stats, or vllm:kv_cache_usage_perc) is the predictor, and
- * `radiance:prefix_cache_evictions_total` is the event -- the hit rate is neither, because it only
- * falls once a prefix that would have been reused is already gone.
+ * Monitoring: `kv_util` (/stats, or vllm:kv_cache_usage_perc) predicts trouble and
+ * `radiance:prefix_cache_evictions_total` counts it. The hit rate lags: it falls only after a
+ * reusable prefix is already gone.
  */
 #pragma once
 #include "mem/kv.h"
@@ -67,10 +51,8 @@ namespace rad {
 class IdleTiers;
 
 /* ------------------------------------------------------------------ block identity */
-/* 128 bits, chained. A block's identity includes its whole prefix, so two identical 16-token spans
- * sitting at the same offset under different prefixes are DIFFERENT blocks and cannot be served
- * for one another. That is the property; the width is only there to make an accidental collision
- * improbable, and the stored token ids below make it impossible. */
+/* 128 bits, chained: identical spans under different prefixes are different blocks. The width
+ * makes a collision improbable; the token compare on lookup makes a wrong hit impossible. */
 struct BlockHash {
     uint64_t hi = 0, lo = 0;
     bool operator==(const BlockHash& o) const { return hi == o.hi && lo == o.lo; }
@@ -83,21 +65,16 @@ struct BlockHashHash {
     size_t operator()(const BlockHash& h) const { return (size_t)(h.lo ^ (h.hi * 0x9e3779b97f4a7c15ull)); }
 };
 
-/* A multimodal span, keyed BY CONTENT. The placeholder token ids inside an image span are
- * identical for every image, so hashing token ids alone would serve one request another's picture.
- * The hash is taken over the ENCODER OUTPUT for the span -- the embedding bytes -- not over the
- * image file, so a re-encode of the same picture at the same resolution hits even when the JPEG
- * differs byte-for-byte, and two different pictures never alias (spec §7.3, §11).
- *
- * The cost, stated: a non-deterministic encoder produces different embedding bytes for the same
- * image and therefore MISSES. A miss is the safe direction; the alternative -- hashing the image
- * bytes -- gets a hit and the wrong embeddings when the preprocessing changes. */
+/* A multimodal span, keyed by content. Placeholder token ids are the same for every image, so
+ * `hash` is the item's content key (core/mm: its processed patches, grid and tiling) mixed with
+ * the run's row offset, by media_keys in core/sched/mem_iface.h (spec §7.3, §11). The same picture
+ * at the same resolution and place hits even if the file bytes differ, and different pictures
+ * never alias. Hashing the file instead would hit with stale KV whenever preprocessing changes. */
 struct MMContentKey {
     int32_t  tok_begin = 0;    /* [begin, end) in prompt-token coordinates */
     int32_t  tok_end = 0;
     uint64_t hash = 0;
 };
-uint64_t mm_content_hash(const void* embedding, int64_t bytes);
 
 /* The chained hash of one block. `parent` is the previous block's hash (a zeroed BlockHash for
  * block 0), `block_begin` is the block's first token position. */
@@ -112,42 +89,47 @@ struct CacheHit {
     int32_t given_back      = 0;   /* reusable tokens a HitCap took off the whole hit */
 };
 
-/* A HIT ENDED EARLY ON PURPOSE. The hit ends no later than `tokens` -- at a block and, for a model
- * with recurrent state, at the deepest checkpoint at or below it -- unless that gives back more
- * than `max_give_back` of what the whole hit would reuse, in which case the whole hit stands. It
- * exists for a drafter whose own KV the cache does not hold (Scheduler::init, --draft-refill):
- * recomputing the prompt's tail gives it context, and a cap whose nearest checkpoint is far below
- * would recompute far more than that tail. */
+/* Ends a hit early on purpose: at or below `tokens`, on a block and (with recurrent state) on the
+ * deepest checkpoint at or below it, unless that gives back more than `max_give_back` reusable
+ * tokens, in which case the whole hit stands. For a drafter whose KV the cache does not hold
+ * (Scheduler::init, --draft-refill): recomputing the prompt's tail gives it context, and the
+ * give-back limit stops a far-off checkpoint from turning that into a long recompute. */
 struct HitCap {
     int64_t tokens = 0;
     int64_t max_give_back = 0;
 };
 
 /* ------------------------------------------------------------------ retention policy */
-/* Spec §19.1 records geometric backoff as a GUESS until there is a workload to measure. It is
- * therefore a policy OBJECT and not an if-statement, so replacing it is writing a class rather
- * than rewriting the cache. Two alternatives ship alongside it for exactly that reason. */
+/* Which checkpoints a session keeps. Spec §19.1 treats geometric backoff as unmeasured, so the
+ * policy is a replaceable class with two alternatives alongside it. */
 class CheckpointPolicy {
 public:
     virtual ~CheckpointPolicy() = default;
     virtual const char* name() const = 0;
-    /* `positions` ascending, one entry per checkpoint the session holds. Fill `keep` with the
-     * subset to retain. THE TIP -- positions.back() -- MUST ALWAYS BE KEPT, because an appending
-     * agent transcript is what this cache is for and the tip is the only thing it needs. */
+    /* `positions` ascending, one per checkpoint the session holds; fill `keep` with the subset to
+     * retain. The tip, positions.back(), must always be kept: an appending transcript resumes
+     * from it. */
     virtual void select(const std::vector& positions, std::vector* keep) const = 0;
 };
 
-/* Keep the tip, then 1x, 2x, 4x, 8x checkpoints back. Bounds the snapshot count at log(n) and the
- * recompute at one interval-doubling, which is the trade §19.1 describes. Distances are counted in
- * CHECKPOINTS rather than in tokens: the scheduler splits chunks at the interval so the spacing is
- * uniform, and counting in checkpoints stays correct if it ever is not. */
+/* Keep the tip and, at every scale S = interval x 2^k, the shallowest checkpoint in the tip's
+ * bucket [j*S, (j+1)*S) and in the bucket before it. Depths behind the tip grow geometrically, a
+ * session keeps about log2(tip / interval) + 2 snapshots, and a turn that diverges d tokens behind
+ * the tip resumes less than max(2d, 2 x interval) below the divergence (spec §7.3). Buckets are
+ * fixed token ranges, so the rule applied again after more checkpoints keeps the same ladder, and
+ * a snapshot it drops is never one it would select later. */
 class GeometricBackoff final : public CheckpointPolicy {
 public:
+    /* `interval` is the resolved checkpoint interval, the smallest scale. */
+    explicit GeometricBackoff(int64_t interval) : interval_(interval > 0 ? interval : 1) {}
     const char* name() const override { return "geometric-backoff"; }
     void select(const std::vector& positions, std::vector* keep) const override;
+
+private:
+    int64_t interval_;
 };
 
-/* The two obvious ends of the trade, kept so a measurement can be run against them. */
+/* The two ends of the trade, for comparison. */
 class KeepTipOnly final : public CheckpointPolicy {
 public:
     const char* name() const override { return "tip-only"; }
@@ -162,18 +144,12 @@ public:
 /* ------------------------------------------------------------------ the cache */
 class PrefixCache {
 public:
-    /* `kv` must already be configured: the cache holds a KV-manager reference on every block it
-     * indexes, which is the invariant that makes a hit safe -- a block in the map is never in the
-     * free list, so it can never be handed to another sequence underneath a cache entry.
+    /* `kv` must already be configured. The cache holds a KV reference on every block it indexes,
+     * so an indexed block is never on the free list and cannot be handed to another sequence.
      *
-     * `checkpoint_interval` IS THE SCHEDULER'S RESOLVED INTERVAL, NOT cfg.checkpoint_interval.
-     * The two are different numbers: chunk_geometry_resolve rounds the operator's request UP to
-     * the chunk quantum so that "split at the interval" is always also a legal chunk split. If
-     * this cache read the raw config value while the scheduler split on the rounded one, every
-     * checkpoint would be refused by reserve_checkpoint -- with an error saying the scheduler
-     * splits at the interval precisely so this cannot happen -- and restore() would walk back in
-     * the wrong stride looking for snapshots nothing had written. It is a parameter rather than a
-     * config read so that there is one place the number comes from. */
+     * `checkpoint_interval` is the scheduler's resolved interval, not cfg.checkpoint_interval:
+     * chunk_geometry_resolve rounds the flag up to the chunk quantum. Using the raw value would
+     * make reserve_checkpoint refuse every checkpoint and lookups search the wrong stride. */
     int configure(const Config& cfg, KVManager* kv, int64_t checkpoint_interval);
     bool enabled() const { return enabled_; }
     int64_t block_size() const { return block_size_; }
@@ -181,9 +157,8 @@ public:
     const std::vector& cached_groups() const { return groups_; }
     std::string report() const;
 
-    /* AFTER configure(), which installs the one Config::checkpoint_policy names. This is the
-     * in-process override -- a policy that is not one of the three, or one a test wants to
-     * substitute -- and calling it first would be undone. */
+    /* Overrides the policy configure() installed from Config::checkpoint_policy (custom policies,
+     * tests). Call after configure(), which would undo it. */
     void set_policy(std::unique_ptr p);
     const CheckpointPolicy& policy() const { return *policy_; }
 
@@ -192,9 +167,8 @@ public:
      * for a prefix of it. `blocks_out`, when given, receives the block ids per cached group, in
      * cached_groups() order, ready for KVManager::adopt().
      *
-     * NEVER returns the whole prompt: at least one token must remain for the step to compute a
-     * logit from, so a full hit is backed off by one block. That is not a subtlety the caller
-     * should have to know. `cap`, when given, ends the hit early (HitCap). */
+     * Never returns the whole prompt: one token must remain to compute a logit from, so a full
+     * hit is backed off by one block. `cap`, when given, ends the hit early (HitCap). */
     CacheHit lookup(const std::vector& tokens,
                     const std::vector& mm,
                     std::vector>* blocks_out = nullptr,
@@ -209,123 +183,86 @@ public:
                int64_t n_tokens,
                const std::string& label = std::string());
 
-    /* Drop the least recently used entries, releasing their KV references. Returns how many were
-     * dropped. Blocks a live sequence still holds stay allocated -- releasing the cache's
-     * reference is not freeing the block.
-     *
-     * A CLEAN ENTRY IS RELEASED AND KEPT. With the idle tiers on, an entry whose host copy has
-     * landed loses nothing by leaving VRAM, so pressure on the pool moves it to the host tier
-     * instead of forgetting it: the next turn restores it rather than re-prefilling it. Only an
-     * entry with no host copy yet is lost. Either way the blocks go back to the pool. */
+    /* Release up to `n_entries` least recently used entries' KV references; returns how many went.
+     * Entries a live sequence also holds are skipped, since releasing them frees nothing. With the
+     * idle tiers on, an entry whose host copy has landed moves to the host tier instead of being
+     * forgotten; only one with no host copy is lost. */
     int64_t evict_lru(int64_t n_entries);
-    /* FREE UP TO `n_blocks` BLOCKS OF THE POOL for the reserve the scheduler keeps, losing nothing
-     * a later turn could have reused. One walk of the LRU list, oldest first, that takes only what
-     * gives the pool a block back without costing a conversation:
-     *
-     *   - an entry a live sequence also holds is passed over. Releasing the cache's reference on
-     *     it frees nothing, and without a host copy it erases the entry -- which, right after a
-     *     publish, is the conversation that request just finished;
-     *   - with the idle tiers on, an entry whose host copy has not landed is passed over too. It
-     *     is the next turn's context with nowhere else to come from, and in a moment it is clean
-     *     and can leave VRAM for nothing.
-     *
-     * Pressure that cannot wait -- an admission or a step that needs the blocks now -- is
-     * evict_lru's. Returns how many blocks went back. */
+    /* Free up to `n_blocks` pool blocks for the scheduler's reserve without losing anything a
+     * later turn could reuse. One oldest-first walk that skips entries a live sequence also holds
+     * and, with the tiers on, entries whose host copy has not landed yet. Pressure that cannot
+     * wait goes to evict_lru. Returns how many blocks went back. */
     int64_t trim(int64_t n_blocks);
-    /* GIVE UP EVERY VRAM COPY THAT CAN GO FOR NOTHING: the entries whose host copy has landed and
-     * that no running sequence is still reading. Called when the memory has a better use -- the
-     * expert slab's loan -- and returns how many entries left VRAM. An entry a sequence still
-     * holds would free nothing, so it is asked about again once a sequence has let go of blocks. */
+    /* Give up every VRAM copy that costs nothing to drop: host copy landed and no running sequence
+     * reading it. Used when the memory has a better use (the expert slab's loan). Entries still
+     * shared are retried after a sequence frees blocks. Returns how many entries left VRAM. */
     int64_t drop_clean();
     int64_t size() const { return (int64_t)map_.size(); }
-    /* How many entries hold blocks in the pool, as opposed to only a copy off the card. */
+    /* Entries holding blocks in the pool, as opposed to only a copy off the card. */
     int64_t resident() const { return (int64_t)lru_.size(); }
-    /* HOW MUCH OF THE POOL THIS CACHE IS HOLDING ON ITS OWN, in tokens of context. The entry
-     * count cannot answer that: an entry's blocks are SHARED with every live sequence that hit on
-     * them, and on a server carrying long conversations that is most of the index -- so an index
-     * size read as "memory the cache is keeping back" says a request reading its own context is
-     * the cache refusing to release it. What an eviction would actually free is the blocks
-     * nothing else references, which is what this counts. */
+    /* Pool held by the cache alone, in tokens: blocks nothing else references, i.e. what an
+     * eviction would actually free. The entry count overstates this, because entries share blocks
+     * with every live sequence that hit them. */
     int64_t unshared_tokens() const;
     /* Forget every entry, in VRAM or off it, and give back whatever the tiers held for them. */
     void    clear();
     /* Diagnostic: the LRU order, oldest first. */
     std::vector lru_order() const;
+    /* Diagnostic: clean entries drop_clean() is waiting to recheck, each listed once. */
+    size_t drop_waiting() const { return drop_wait_.size(); }
 
     /* ---------------- idle session tiers (core/mem/kvtier.h) ---------------- */
-    /* Installed after configure() when the tiers are on. A null pointer is the whole of the "off"
-     * path: every call site below is guarded, and with no tiers the cache is a plain VRAM-only
-     * prefix cache. */
+    /* Installed after configure() when the tiers are on. Null means a plain VRAM-only cache;
+     * every use is guarded. */
     void set_tiers(IdleTiers* t) { tiers_ = t; }
 
-    /* THE CHAIN THIS PROMPT WOULD HIT IF THE TIERS GAVE IT BACK, in order, starting at the block
-     * `lookup` stopped on. The caller promotes them and asks again; an empty answer means the
-     * prefix stopped for an ordinary reason -- a miss, or a token compare -- and no amount of
-     * restoring would lengthen it.
-     *
-     * It is a separate call rather than something lookup does because lookup is const and has no
-     * device: a promotion allocates blocks and runs a scatter, which is the engine's to do
-     * between steps and not something a cache query may trigger under the caller. */
+    /* The off-device entries this prompt's chain would hit if restored, in order, from where
+     * lookup stopped. The caller promotes them and looks up again; empty means the prefix ended
+     * on a miss or token mismatch. Separate from lookup because lookup is const and has no
+     * device; a promotion allocates blocks and runs a scatter between steps. */
     std::vector restorable_from(const std::vector& tokens,
                                            const std::vector& mm) const;
 
-    /* THE TIERS LOST THE BYTES. Erase the entry WITHOUT releasing blocks: an off-device entry
-     * owns none -- demotion released them -- and its recorded ids belong to whoever the pool gave
-     * them to since. Releasing those would free another sequence's block; leaving the entry in
-     * the map would serve them. Installed as IdleTiers::set_drop_sink. */
+    /* The tiers lost the bytes. Erases the entry without releasing blocks: an off-device entry
+     * owns none, and its recorded ids now belong to other sequences. Installed as
+     * IdleTiers::set_drop_sink. */
     void drop_offdevice(const BlockHash& key);
 
-    /* A restore finished: the entry's blocks live at these ids now. The cache takes a reference on
-     * each, because the restore holds them only as raw reservations (KVManager::reserve_block) and
-     * this is where they become cache-held blocks with the usual invariant. */
+    /* A restore finished and the entry's blocks now live at these ids. The restore's raw
+     * reservations (KVManager::reserve_block) become cache-held references. */
     int rebind(const BlockHash& key, const std::vector& blocks);
 
 
     /* ---------------- the linear half of an idle session ----------------
      *
-     * ON A HYBRID MODEL THE BLOCKS ARE ONLY HALF OF WHAT A SESSION NEEDS BACK. The other half is
-     * the recurrent state, and it lives in a CHECKPOINT SLOT: a slot of the engine's snapshot
-     * store in pinned host memory, KVManager::checkpoint_bytes() a rank, of which there are
-     * --checkpoint-slots IN TOTAL for the whole server. What the session loses without it is not
-     * part of its hit, it is ALL of it -- the scheduler clamps reuse to the last checkpoint a hit
-     * can reach, because RadBatch carries one query length for every KV group and the linear
-     * layers cannot be replayed over a longer range than the attention ones (core/sched/
-     * scheduler.cpp, admit_one). A restored session with no reachable snapshot reuses zero tokens
-     * and re-prefills its whole transcript.
-     *
-     * A snapshot never needs to follow its blocks: it is restored straight out of its slot into
-     * the new sequence's state, wherever the blocks are. There is no tier below the store: a
-     * snapshot the store retires is gone, and a session that needed it replays its recurrent
-     * layers from an older one. */
+     * On a hybrid model a session also needs its recurrent state back, held in a checkpoint slot:
+     * the engine's snapshot store in pinned host memory, KVManager::checkpoint_bytes() per rank,
+     * --checkpoint-slots in total for the server. Without a reachable snapshot a session reuses
+     * nothing: the scheduler clamps reuse to the last reachable checkpoint because RadBatch has
+     * one query length for all KV groups (Scheduler::admit_one). A snapshot is restored straight
+     * from its slot wherever the blocks are. There is no tier below the store; a retired snapshot
+     * is gone and the session replays from an older one. */
 
-    /* KEEP A WAITING REQUEST'S CHAIN ON THE CARD. An admission that restored a chain and was then
-     * refused -- no free sequence, no room in the pool -- gives its hit back, and its entries are
-     * clean: drop_clean would let them go at the next pass and the next attempt would restore the
-     * same chain again, every step for as long as the request waits. A held entry is passed over
-     * by drop_clean until release(); trim and evict_lru still take it under pressure, which costs
-     * a restore and loses nothing. Idempotent per request. */
+    /* Keep a waiting request's chain on the card. An admission that restored a chain and was then
+     * refused gives its hit back with clean entries; without a hold, drop_clean would drop them
+     * and every retry would restore the chain again. drop_clean skips held entries until
+     * release(); trim and evict_lru still take them. Idempotent per request. */
     void hold(uint64_t req, const std::vector& tokens, const std::vector& mm);
-    /* How many of `chain`'s leading entries are in VRAM: as far as a lookup's hit can reach. */
-    size_t resident_prefix(const std::vector& chain) const;
     void release(uint64_t req);
-    /* A step's admissions begin. The snapshots the last step's lookups handed out have been read
-     * by its forward, which committed before this step was planned. Until then a handed snapshot
-     * keeps its slot through every path that would give one up: retention, the eviction in
-     * reserve_checkpoint, and the expiry. */
+    /* Start of a step's admissions. Snapshots the previous step's lookups handed out have been
+     * read by its forward by now; until this call they keep their slots against retention,
+     * reserve_checkpoint's eviction and expiry. */
     void begin_step() { handed_.clear(); }
 
     /* ---------------- expiry ----------------
      *
-     * TAKE OUT EVERYTHING NO REQUEST HAS USED FOR `ttl_ns`: entries in VRAM (their blocks go back
-     * to the pool), entries only the host holds (their slots go back to the arena), and snapshots
-     * (their store slots go back). An entry is used when a lookup hits it or a request publishes
-     * it, and a snapshot when its prefix entry is or when a lookup hands it out. Nothing is moved
-     * anywhere first: an expired conversation is one the operator has said is not coming back.
+     * Remove everything no request has used for `ttl_ns`: VRAM entries, host-only entries and
+     * snapshots, each returned to its pool. An entry is used by a hit or a publish; a snapshot by
+     * a use of its prefix entry or a lookup handing it out. Nothing is demoted first.
      *
-     * A PREFIX IS NEVER OLDER THAN WHAT FOLLOWS IT. A hit or a publish stamps every block of the
-     * chain up to where it ends with one clock, so a conversation expires from its tip inwards and
-     * a shared system prompt outlives every conversation that still reads it. Returns how many
-     * entries went. */
+     * A hit or publish stamps every block of the chain with one clock, so a prefix is never older
+     * than what follows it: conversations expire from the tip inwards and a shared system prompt
+     * outlives its readers. Returns how many entries went. */
     int64_t expire(uint64_t now_ns, uint64_t ttl_ns);
     /* ---------------- linear checkpoints ---------------- */
     /* The next position strictly after `pos` at which the scheduler must split a chunk so that a
@@ -333,38 +270,38 @@ public:
     int64_t next_checkpoint_after(int64_t pos) const;
     bool    is_checkpoint(int64_t pos) const { return interval_ > 0 && pos > 0 && pos % interval_ == 0; }
 
-    /* Reserve a snapshot slot for `session` at `pos`. Applies the retention policy when the slot
-     * pool is exhausted, then evicts the least recently used snapshot, a session's tip last. A
-     * snapshot a lookup handed out this step is never given up: the admission it was handed to
-     * restores from the slot ahead of the step, after this reservation was made. RAD_E_FULL when
-     * nothing else can be given up. */
+    /* Reserve a snapshot slot for `session` at `pos`. When the store is full, applies the
+     * retention policy, then evicts the least recently used snapshot (a use is its reservation or
+     * a lookup resuming from it), a tip like any other. A snapshot handed out this step is never
+     * evicted: its admission restores from the slot ahead of the step. RAD_E_FULL when nothing
+     * can be given up. */
     int  reserve_checkpoint(uint64_t session, int64_t pos, const BlockHash& prefix,
                             int32_t* slot_out);
-    /* The state named by `prefix` is now IN its slot. Until this is called the reservation is only
-     * a promise and lookup() will not offer it -- see Ckpt::valid. */
+    /* The state for `prefix` is now in its slot; lookup() offers it only after this (Ckpt::valid). */
     void commit_checkpoint(const BlockHash& prefix);
     /* Every checkpoint of a session, ascending. */
     std::vector checkpoints(uint64_t session) const;
-    /* Apply the retention policy to one session now. Returns how many snapshots were released.
-     * A session left holding nothing is forgotten -- see the note at the definition for why that
-     * matters more than the bytes. */
+    /* Apply the retention policy to one session now, keeping also what a lookup resumed from
+     * since the session's tip was written. Returns how many snapshots were released. A session
+     * left with none is erased from the index. */
     int64_t retain(uint64_t session);
 
-    /* How many sessions the checkpoint index still knows about. Exposed because it is an
-     * INVARIANT rather than a statistic: a session is a request id, so this must track the
-     * sessions holding a live snapshot and not the number of requests the process has served. */
+    /* Sessions in the checkpoint index. Invariant: since a session is a request id, this tracks
+     * sessions holding a live snapshot, not every request served. */
     int64_t sessions_tracked() const { return (int64_t)ck_by_session_.size(); }
 
     struct Stats {
         int64_t lookups = 0, block_hits = 0, block_misses = 0;
         int64_t ckpt_hits = 0, ckpt_misses = 0;
         int64_t evictions = 0, ckpt_evictions = 0;
-        /* Entries whose VRAM copy was given up with their host copy kept. Not evictions: nothing
-         * was lost, and a counter that mixed the two would read a working tier as a thrashing
-         * cache. */
+        /* ckpt_evictions by reason: released by the retention policy, or taken as the least
+         * recently used of a store retention left full. `ckpt_refused` counts reservations that
+         * found every slot handed out this step and went without a snapshot. */
+        int64_t ckpt_retired = 0, ckpt_lru = 0, ckpt_refused = 0;
+        /* Entries whose VRAM copy was given up with the host copy kept; not evictions, since
+         * nothing was lost. */
         int64_t drops = 0;
-        /* Entries and snapshots --prefix-cache-ttl took, from whichever tier held them. Not
-         * evictions either: nothing wanted the memory. */
+        /* Entries and snapshots removed by --prefix-cache-ttl, from any tier. */
         int64_t expired = 0, ckpt_expired = 0;
     };
     const Stats& stats() const { return stats_; }
@@ -373,15 +310,12 @@ private:
     struct Entry {
         std::vector blocks;    /* one per cached group, in groups_ order */
         std::vector tokens;    /* the block's token ids, compared on hit */
-        /* ON THE LRU EXACTLY WHILE THE CACHE HOLDS THE BLOCKS. An entry whose bytes are only off
-         * the card owns no block, so it has nothing an eviction could free, and walking past it
-         * under pressure would erase the tier's copy to make room it never occupied. `lru` is
-         * valid only while this is set. */
+        /* On the LRU exactly while the cache holds the blocks; `lru` is valid only then. An
+         * off-device entry owns no block, so eviction must not reach it. */
         bool in_lru = false;
         bool drop_wait = false;         /* in drop_wait_: clean, but a sequence still reads it */
-        /* LAST USE, on the monotonic clock: a hit or a publish. The LRU list is in this order --
-         * every path that puts an entry at its back stamps it -- which is what lets the expiry
-         * stop at the first entry it keeps. */
+        /* Last hit or publish, monotonic clock. Every path that moves an entry to the LRU's back
+         * stamps it, so the list is in this order and expiry stops at the first entry it keeps. */
         uint64_t used_ns = 0;
         std::list::iterator lru;
     };
@@ -390,12 +324,13 @@ private:
         int64_t   pos = 0;
         BlockHash prefix;
         int32_t   slot = -1;
-        uint64_t  used = 0;
+        /* `clock_` values: the last use (reservation or hand-out, the eviction order), the
+         * reservation, and the last hand-out (0 if none). */
+        uint64_t  used = 0, made = 0, resumed = 0;
         uint64_t  used_ns = 0;          /* reserved, or handed out by a lookup */
-        /* HAS THE STATE ACTUALLY BEEN WRITTEN INTO THE SLOT YET. reserve_checkpoint runs when the
-         * scheduler PLANS the chunk; the copy happens after the step that computes the state. A
-         * lookup between those two points would hand out a slot holding the previous tenant's
-         * history, which is the exact failure this whole mechanism exists to prevent. */
+        /* The state has been written into the slot. Reservation happens when the chunk is
+         * planned and the copy after the step that computes it; in between the slot still holds
+         * the previous tenant's state and must not be handed out. */
         bool      valid = false;
     };
 
@@ -403,14 +338,21 @@ private:
                                      const std::vector& mm,
                                      int64_t n_blocks) const;
     void touch(const BlockHash& h, uint64_t now_ns) const;
-    /* Does a live sequence hold any of this entry's blocks as well? Then releasing the cache's
-     * reference frees nothing. */
+    /* A live sequence also holds one of this entry's blocks, so releasing it frees nothing. */
     bool shared_with_live(const Entry& e) const;
-    /* Retire one snapshot: its slot goes back to the store and the tiers stop naming it. The
-     * session index is the caller's, since every caller is already rebuilding or erasing it. */
+    /* Whether `e` holds the block_size_ token ids at `src`, so a hash collision is a miss. */
+    bool same_tokens(const Entry& e, const int32_t* src) const;
+    /* Gives the entry's block in every group back to the KV manager. */
+    void release_blocks(const Entry& e);
+    /* Retire one snapshot: free its slot and tell the tiers. The session index is left to the
+     * caller. */
     void retire_ckpt(std::unordered_map::iterator it);
     /* Take one key out of a session's index entry, and the entry when it empties. */
     void unindex_ckpt(uint64_t session, const BlockHash& key);
+    /* For the debug lines: whether `c` is its session's deepest snapshot, and seconds since a
+     * monotonic stamp. */
+    bool is_tip(const Ckpt& c) const;
+    static double idle_s(uint64_t used_ns);
 
     KVManager*  kv_ = nullptr;
     IdleTiers*  tiers_ = nullptr;
@@ -422,20 +364,19 @@ private:
 
     mutable std::unordered_map map_;
     mutable std::list lru_;    /* front = oldest; resident entries only */
-    /* CLEAN ENTRIES A SEQUENCE WAS STILL READING when drop_clean last looked, and the pool's count
-     * of freed sequences at that moment. Only a sequence letting go of blocks can make one of them
-     * droppable, so they are looked at again only when that count has moved. */
+    /* Clean entries a sequence was still reading at drop_clean's last pass, and the pool's
+     * sequence-free count then. They are rechecked only once that count moves. */
     std::vector drop_wait_;
     std::vector drop_scratch_;
     uint64_t    frees_seen_ = 0;
-    /* hold(): the keys each waiting request holds, and how many requests hold each key. A release
-     * makes drop_wait_ worth looking at again, as a freed sequence does. */
+    /* hold(): keys per waiting request, and holders per key. A release also triggers a recheck
+     * of drop_wait_. */
     std::unordered_map> holds_;
     std::unordered_map held_;
     bool        released_ = false;
     mutable std::unordered_map ck_by_prefix_;
     std::unordered_map> ck_by_session_;
-    /* Snapshots lookup handed out since begin_step: kept in their slots until then (begin_step). */
+    /* Snapshots lookup handed out since begin_step; kept in their slots until the next one. */
     mutable std::vector handed_;
     bool handed(const BlockHash& h) const {
         return std::find(handed_.begin(), handed_.end(), h) != handed_.end();
diff --git a/core/mem/vram_budget.cpp b/core/mem/vram_budget.cpp
index e302b801..5e613167 100644
--- a/core/mem/vram_budget.cpp
+++ b/core/mem/vram_budget.cpp
@@ -1,5 +1,5 @@
-/* vram_budget.cpp -- see vram_budget.h for why a derived budget is not the §6 violation it looks
- * like. This file is the arithmetic and the receipt. */
+/* vram_budget.cpp -- the budget arithmetic and its printed report. See vram_budget.h for why a
+ * derived budget does not violate §6. */
 #include "mem/vram_budget.h"
 
 #include 
@@ -10,48 +10,38 @@ namespace rad {
 namespace {
 constexpr int64_t kMiB = 1024 * 1024;
 
-/* DOWN, ALWAYS. The pools take MiB and multiply back up, so a budget rounded up is a budget that
- * asks the card for more than the arithmetic said was there -- which fails at the allocation
- * rather than here, with the driver's message instead of ours. */
+/* Rounds down: the pools multiply MiB back up, and rounding up would ask the card for more than
+ * the arithmetic found, failing at allocation with the driver's message instead of ours. */
 int64_t to_mib(int64_t bytes) { return bytes > 0 ? bytes / kMiB : 0; }
 
-/* UP, FOR THE ONE BUDGET THAT IS A FLOOR. The KV budget is a CAPACITY -- truncated, the cache
- * addresses a few fewer tokens and nothing else changes. The weights budget is `statics +
- * experts`, a figure the pool must COVER, and a byte short is a tensor with nowhere to land. An
- * expert share pads the number enough to hide that; a dense model is budgeted its static
- * footprint to the byte, and there the rounding direction decides whether it loads. The MiB this
- * claims comes out of the headroom, which is what the headroom is for. */
+/* Rounds up, for the weights budget only. The KV budget is a capacity and may be truncated; the
+ * weights budget (`statics + experts`) must cover every tensor, and a dense model is budgeted its
+ * static footprint to the byte. The extra MiB comes out of the headroom. */
 int64_t to_mib_up(int64_t bytes) { return bytes > 0 ? (bytes + kMiB - 1) / kMiB : 0; }
 
-/* WHAT THE DRIVER'S OWN HOLDING MOVES BY AFTER IT IS READ. `already_held` is one reading, and on
- * ROCm 7.2 the same server started twice has read 4 MiB less than it later held (and once 30 MiB
- * more): a budget that split the difference away came up a few MiB short of the headroom the
- * first launches of kernels allocate from. Four times the drift seen, and charged before anything
- * is split. */
+/* How much the driver's own holding moves after `already_held` is read. On ROCm 7.2 the reading
+ * has come in 4 MiB below what the driver later held, leaving the first kernel launches short of
+ * headroom. Four times that, charged before anything is split. */
 constexpr int64_t kDriverDrift = 16 * kMiB;
 }  /* namespace */
 
-/* WHAT THE CACHE BACKS, counted on its PAGED part. The ceiling is the recurrent and conv state of
- * max_seqs sequences plus their context, and the state is spent before a single token is cached --
- * on a hybrid model at a few dozen sequences it is gigabytes a card. A ratio over the whole
- * ceiling counts that state as context and reports full-length sessions the cache cannot hold. */
+/* The fraction of the paged (context) part of the ceiling the cache backs. The ceiling also
+ * includes fixed recurrent and conv state (gigabytes per card on a hybrid model), which a ratio
+ * over the whole ceiling would wrongly count as context. */
 static double paged_share(const VramBudget& b) {
     const double ctx = (double)(b.kv_ceiling - b.kv_fixed);
     return ctx > 0 ? std::max(0.0, (double)(b.kv - b.kv_fixed)) / ctx : 0.0;
 }
 
-/* The resolver, with its log lines behind `log`: vram_budget_trial asks the same question
- * of a configuration it may not use, and a refusal printed for a split nobody takes reads as the
- * startup failing. */
+/* The resolver. `log` is false for vram_budget_trial, whose split may never be used, so its
+ * refusals must not print as startup failures. */
 static int resolve(Config& cfg, const std::vector& per_rank, VramBudget* out, bool log) {
     VramBudget b;
     if (per_rank.empty()) { if (out) *out = b; return RAD_OK; }
 
-    /* THE SMALLEST CARD AND THE LARGEST PROGRAM, because one split is derived for every rank. Ranks
-     * of one deployment normally hold the same shard shapes and the same program, so these folds
-     * are no-ops -- they exist so that a mixed pair degrades to the card that binds instead of
-     * overcommitting the smaller one on the first allocation. An uneven world's cheaper ranks are
-     * re-split from this answer afterwards (vram_budget_rank_split, called by Engine::plan). */
+    /* The smallest card and the largest program, since one split serves every rank. Normally a
+     * no-op; a mixed pair degrades to the card that binds. An uneven world's cheaper ranks are
+     * re-split afterwards (vram_budget_rank_split, from Engine::plan). */
     b.capacity   = per_rank[0].capacity;
     int64_t freeb = per_rank[0].free;
     int64_t layer_max = 0, kv_one = 0;
@@ -71,7 +61,7 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg
         b.statics    = std::max(b.statics, f.statics);
         b.expert_ceiling = std::max(b.expert_ceiling, f.experts);
         layer_max        = std::max(layer_max, f.expert_layer_max);
-        /* THE RANK THAT NEEDS MOST ON THE CARD SETS THE FLOOR. */
+        /* The rank that needs most on the card sets the floor. */
         b.expert_floor = std::max(b.expert_floor, f.expert_floor);
         kv_one = std::max(kv_one, f.kv_one);
     }
@@ -83,11 +73,10 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg
     const bool shared = host_reserve > b.headroom;
     if (shared) b.headroom = host_reserve;
 
-    /* A DEVICE THAT REPORTS NO CAPACITY HAS NOTHING TO SPLIT, and inventing a capacity would be
-     * exactly the inference §6 forbids. What each pool needs is still known: the weights pool
-     * holds what the planner would copy out of the container -- the statics and experts
-     * weight_footprint counts -- and the cache is its ceiling, every sequence at the full context.
-     * (The host backend reports half the machine's memory and is split like a card.) */
+    /* A device that reports no capacity has nothing to split, and inventing one is the inference
+     * §6 forbids. Each pool gets what it needs: weights what the planner copies out of the
+     * container (weight_footprint), the cache its ceiling. (The host backend reports half the
+     * machine's memory and is split like a card.) */
     if (b.capacity <= 0) {
         b.weights = std::max(b.statics + b.expert_ceiling, kMiB);
         b.kv      = std::max(b.kv_ceiling, kMiB);
@@ -102,14 +91,12 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg
         return RAD_OK;
     }
 
-    /* MEASURED, NOT ASSUMED, AND IT IS THE ONLY TERM THAT IS. Everything the driver and the loaded
-     * code objects already hold shows up here, including a desktop compositor on the same card --
-     * which is a real configuration on a workstation and the reason this is a line in the report
-     * rather than a constant folded into the headroom. Read after declare(), so every kernel
-     * plugin's init has run and its code object is resident. */
+    /* The only measured term: the driver, loaded code objects and anything else on the card (e.g.
+     * a desktop compositor), so it is reported on its own line rather than folded into the
+     * headroom. Read after declare(), once every kernel plugin's code object is resident. */
     b.already_held = std::max(b.capacity - freeb, 0);
 
-    /* What is left after the terms nobody gets to spend. */
+    /* What is left after the fixed terms. */
     b.drift = kDriverDrift;
     b.claimable = b.capacity - (b.already_held + b.drift + b.headroom + b.arena + b.staging +
                                 b.queues + b.prefetch);
@@ -126,7 +113,7 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg
             "  hardware queues    %10s   (%d at %s each, measured)\n"
             "  expert prefetch    %10s   (its ring of expert units and buffers)\n"
             "  ------------------------------\n"
-            "  SHORT BY           %10s\n"
+            "  short by           %10s\n"
             "Lower --gpu-headroom-mib, lower --max-num-batched-tokens (the arena scales with it), "
             "or free the card.\n",
             humanb(b.capacity).c_str(), humanb(b.already_held).c_str(), humanb(b.drift).c_str(),
@@ -138,41 +125,37 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg
         return RAD_E_NOMEM;
     }
 
-    /* ---- the static weights come off the top ------------------------------------------------
-     *
-     * They are a floor and not a share. */
+    /* ---- the static weights come off the top, as a floor ------------------------------------ */
     b.statics = std::min(b.statics, b.claimable);
     if (b.statics >= b.claimable && b.claimable > 0) {
-        /* Not fatal: the planner will demote what does not fit and the model still serves,
-         * badly. Name it, because "why is this model 8x slower than it should be" has no other
-         * answer at startup. */
-        if (log) RAD_WARN("the static (non-expert) weights alone want %s of the %s this card has to "
-                 "give. Every expert will stream from host memory and the KV cache has "
-                 "nothing left -- this model wants more VRAM, fewer ranks of it, or a smaller "
-                 "--max-num-batched-tokens.",
-                 humanb(b.statics).c_str(), humanb(b.claimable).c_str());
+        /* Not fatal: the planner demotes what does not fit and the model serves slowly. Warn so
+         * the slowdown is explained at startup. */
+        if (log) RAD_WARN("the static (non-expert) weights alone want %s of the %s this card can "
+                          "give, so every expert streams from host memory and the KV cache gets "
+                          "nothing; use more cards or a smaller --max-num-batched-tokens",
+                          humanb(b.statics).c_str(), humanb(b.claimable).c_str());
     }
     b.elastic = b.claimable - b.statics;
     if (b.elastic < 0) b.elastic = 0;
 
-    /* ---- and only what is left is divided --------------------------------------------------- */
+    /* ---- the rest is divided ---------------------------------------------------------------- */
     {
-        /* An unset cache ceiling (plan_groups failed) bounds nothing; zero experts is a ceiling of
-         * zero, which weight_footprint always measures. */
+        /* An unset cache ceiling (plan_groups failed) bounds nothing. An expert ceiling of zero is
+         * real: weight_footprint always measures it. */
         const int64_t kv_cap = b.kv_ceiling > 0 ? b.kv_ceiling : b.elastic;
         int64_t kv = 0, exp = 0;
         if (kv_cap + b.expert_ceiling <= b.elastic) {
-            /* BOTH FIT: nothing trades. */
+            /* Both fit: nothing trades. */
             kv  = kv_cap;
             exp = b.expert_ceiling;
         } else if (b.lends) {
-            /* THE CACHE LENDS, so it is sized for what live requests could need and gives back
-             * whatever they do not. The experts keep what the host pool cannot hold. */
+            /* The cache lends: size it for what live requests could need; it gives back what
+             * they do not. The experts keep what the host pool cannot hold. */
             exp = std::min(b.expert_floor, b.elastic);
             kv  = std::min(kv_cap, std::max(b.elastic - exp, kv_one));
             exp = std::min(std::max(b.expert_ceiling, b.expert_floor), b.elastic - kv);
-            /* THE ONE SEQUENCE WINS, and the experts it pushes off the card have no tier: the
-             * planner refuses them by name. Said here too, with what moves it. */
+            /* One full-length sequence wins; experts it pushes off the card have no tier and the
+             * planner refuses them. Warn here too, with the flags that fix it. */
             if (log && b.expert_floor > 0 && exp < b.expert_floor)
                 RAD_WARN("one --max-model-len sequence's cache (%s) leaves the experts %s, short of "
                          "the %s the pinned host pool cannot hold: raise --host-pool-mib or lower "
@@ -180,8 +163,8 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg
                          humanb(kv_one).c_str(), humanb(exp).c_str(),
                          humanb(b.expert_floor).c_str());
         } else {
-            /* NO LENDER: a block the cache does not use would sit empty, so the experts come
-             * first and the cache keeps one --max-model-len sequence. */
+            /* No lender: an unused block would sit empty, so experts come first and the cache
+             * keeps one --max-model-len sequence. */
             kv  = std::min(kv_cap, std::max(b.elastic - b.expert_ceiling, kv_one));
             exp = std::min(b.expert_ceiling, b.elastic - kv);
         }
@@ -192,35 +175,29 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg
         b.weights  = b.statics + exp;
         b.unusable = std::max(b.elastic - kv - exp, 0);
     }
-    /* A POOL NOTHING IS PLACED IN STILL HAS TO EXIST. Where every weight is read where the
-     * container's mapping has it -- every op on the host, on the host backend -- the statics and
-     * experts are zero, and the pools refuse a zero budget as a resolver that never ran. A MiB,
-     * out of the headroom as the rounding's is. */
+    /* The weights pool must exist even when empty (every weight read from the container's
+     * mapping on the host backend), since the pools treat a zero budget as an unresolved one. One
+     * MiB, out of the headroom. */
     b.weights = std::max(b.weights, kMiB);
 
-    /* ---- THE PREFILL STAGING REGION, out of the expert share ---------------------------------
+    /* ---- the prefill staging region ----------------------------------------------------------
      *
-     * A prefill chunk routes to nearly every expert of every layer, so the part of each layer the
-     * budget leaves off the card is read across the link by the layer's GEMM -- on the critical
-     * path, at the link's rate, while the rest of the layer's work leaves the link idle. Two
-     * buffers of one layer's share of that let the next layer's copy run behind the current one
-     * (core/place/stager.h). They come out of the expert share because they exist only for the
-     * experts that do not fit, and they sit at the top of the activation arena, which every step
-     * smaller than the full plan lends back to the expert slab: a decode step keeps the residency
-     * they cost.
+     * Two layers' share of the experts left off the card, for the prefill stager's ring
+     * (core/place/stager.h). It exists only for experts that do not fit, so it comes out of the
+     * expert share (or, when the cache lends, the cache's). It sits at the top of the activation
+     * arena, which steps smaller than the full plan lend back to the expert slab, so decode keeps
+     * the residency.
      *
-     * The share is the budget's -- what the slab alone leaves off -- which is the most a step can
-     * see: the loans the KV cache and the smaller arena levels make only ever add residency. A
-     * layer whose pooled part is larger than a buffer stages what fits and streams the rest. */
+     * The share is what the slab alone leaves off, the most a step can see: KV and arena loans only
+     * add residency. A layer larger than its share stages what fits and streams the rest. */
     if (layer_max > 0 && b.expert_ceiling > b.experts && cfg.placement != "all_vram" &&
         cfg.placement != "layer_offload") {
         const double f = (double)(b.expert_ceiling - b.experts) / (double)b.expert_ceiling;
         const int64_t one = ((int64_t)std::ceil(f * (double)layer_max) + RAD_ALIGN_UNIT - 1) /
                             RAD_ALIGN_UNIT * RAD_ALIGN_UNIT;
         if (b.lends) {
-            /* A LENDING CACHE PAYS FOR IT: the experts are at their floor and a byte less would
-             * leave one with no tier, while the region is lent to the slab whenever the steps are
-             * small -- the same memory the cache would have lent. */
+            /* With a lending cache the cache pays: experts are at their floor, and the region is
+             * lent to the slab in small steps, as the cache would have lent it. */
             if (b.kv - 2 * one >= kv_one) {
                 b.stage = 2 * one;
                 b.kv   -= b.stage;
@@ -232,45 +209,31 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg
         }
     }
 
-    /* HOW MUCH OF THE ADVERTISED CONTEXT THE POOL BACKS, AND IT IS A PROVISIONING CHOICE RATHER
-     * THAN A SHORTFALL.
-     *
-     * A KV share under max_seqs x max_ctx is not a warning. The argument that it would be -- that
-     * the server accepts at the door what it cannot serve -- is wrong for a PAGED cache, and the
-     * difference is the whole of vLLM's block manager: a sequence holds only the blocks its tokens
-     * actually occupy (KVManager::ensure grows it by ceil_div(n_tokens, block_size) as it runs,
-     * drops them at completion, and returns RAD_E_FULL for the scheduler to preempt rather than
-     * failing the request). Every sequence reaching max_ctx at the same moment is the worst case,
-     * not the workload -- real loads run well under half backing -- and sizing for the worst case
-     * spends VRAM that a model whose experts do not fit would rather have for them.
-     *
-     * So it is reported and not warned about. What IS still checked, and belongs in the KV manager
-     * because it is a real limit rather than a ratio, is that ONE max-length sequence fits: a
-     * context no single request can complete is a configuration error however much slack the pool
-     * has (core/engine_bringup.cpp, configure_kv). */
+    /* How much of max_seqs x max_ctx the pool backs: a provisioning choice, reported, not warned
+     * about. A paged cache holds only the blocks a sequence occupies (KVManager::ensure grows it,
+     * and RAD_E_FULL makes the scheduler preempt), so all sequences at max_ctx at once is the
+     * worst case, not the workload, and sizing for it takes VRAM from experts that do not fit.
+     * The real limit, that one max-length sequence fits, is checked in configure_kv
+     * (core/engine_bringup.cpp). */
     if (log && b.kv_ceiling > 0 && cfg.max_ctx > 0)
         RAD_INFO("kv: the pool backs %.0f%% of the worst case (%lld sequences all at %lld tokens), "
-                 "%.1f full-length sessions. That is concurrency at length before the scheduler "
-                 "preempts, not a bound on any one request. WITH PREFIX CACHING a finished "
-                 "sequence's blocks stay held so the next turn can reuse them, so the demand is "
-                 "live SESSIONS and not running requests -- when they do not all fit, the cache "
-                 "evicts prefixes the next turn wanted and that turn re-prefills its whole "
-                 "context. --host-pool-mib moves it: the experts the host pool cannot hold are the "
-                 "part of the card the cache cannot have.",
+                 "%.1f full-length sessions; a larger --host-pool-mib gives the cache more",
                  100.0 * paged_share(b),
                  (long long)cfg.max_seqs, (long long)cfg.max_ctx,
                  (double)cfg.max_seqs * paged_share(b));
-    /* Rounding the floor up claims up to a MiB the split did not hand out. Take it back from the
-     * cache -- a paged pool a MiB smaller addresses a handful fewer tokens and nothing else -- so
-     * the headroom stays whole. */
+    /* Rounding the weights up claims up to a MiB the split did not hand out; take it back from
+     * the cache so the headroom stays whole. */
     cfg.vram_weights_mib = to_mib_up(b.weights);
     const int64_t w_over = cfg.vram_weights_mib * kMiB - b.weights;
     cfg.vram_kv_mib      = to_mib(std::max(b.kv - w_over, 0));
+    /* A cache given its whole ceiling is rounded up to cover it, out of the headroom as the
+     * weights' MiB is: truncated, a ceiling under a MiB would be an empty pool and one just over a
+     * whole MiB a pool short of its own context. */
+    if (b.kv_ceiling > 0 && b.kv >= b.kv_ceiling && cfg.vram_kv_mib * kMiB < b.kv_ceiling)
+        cfg.vram_kv_mib = to_mib_up(b.kv_ceiling);
 
-    /* THE RECEIPT. Every term, in the order it was spent, so that a split anybody disagrees with
-     * can be argued about against numbers instead of re-derived from sysfs by hand. The unclaimed
-     * line is not padding: to_mib truncates, and what it drops is real VRAM that ends up beside
-     * the headroom. */
+    /* The report: every term in the order spent. `unclaimed` includes what to_mib truncated,
+     * which stays beside the headroom. */
     const int64_t granted   = cfg.vram_weights_mib * kMiB + cfg.vram_kv_mib * kMiB;
     const int64_t unclaimed = b.capacity - b.already_held - b.drift - b.arena - b.staging - b.queues -
                               b.prefetch - b.stage - granted;
@@ -326,22 +289,16 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg
                   "                                  more would be unusable",
                   (long long)cfg.max_seqs, (long long)cfg.max_ctx).c_str()
             : (b.kv_ceiling > 0
-                   /* SAID AS A SESSION COUNT, because that is the number to compare against
-                    * --max-num-seqs, and "28%" makes the reader do the arithmetic.
-                    *
-                    * AND IT NAMES SESSIONS, NOT RUNNING REQUESTS. "Paged blocks are held only
-                    * while a sequence occupies them" stops being true once prefix caching takes a
-                    * KV reference on every block it indexes: a finished sequence's blocks stay
-                    * held so the next turn can reuse them. So the demand of a multi-turn workload
-                    * is the number of LIVE SESSIONS, and counting running requests instead
-                    * under-counts by exactly the thing that makes agent turns cheap. When the pool
-                    * cannot hold them all, the cache evicts prefixes the next turn wants and that
-                    * turn re-prefills its whole context (radiance:prefix_cache_evictions_total). */
+                   /* Given as a session count, comparable with --max-num-seqs. Sessions, not
+                    * running requests: prefix caching holds a finished sequence's blocks for the
+                    * next turn, so multi-turn demand is live sessions. When they do not fit, the
+                    * cache evicts prefixes and the next turn re-prefills its whole context
+                    * (radiance:prefix_cache_evictions_total). */
                    ? fmt(" -- %.0f%% backing of the %lld x %lld worst case: %.1f full-length\n"
                          "                                  sessions. With prefix caching a "
                          "finished sequence's blocks stay held\n"
-                         "                                  for reuse, so the demand is LIVE "
-                         "SESSIONS and not running requests",
+                         "                                  for reuse, so the demand is live "
+                         "sessions, not running requests",
                          100.0 * paged_share(b),
                          (long long)cfg.max_seqs, (long long)cfg.max_ctx,
                          (double)cfg.max_seqs * paged_share(b)).c_str()
@@ -381,9 +338,8 @@ RankSplit vram_budget_rank_split(int64_t common_weights_mib, int64_t common_kv_m
     s.kv_mib      = common_kv_mib;
     if (need_kv_mib < 0 || need_kv_mib >= common_kv_mib) return s;
     const int64_t saved = common_kv_mib - need_kv_mib;
-    /* NEVER LESS THAN THE COMMON WEIGHTS POOL, and never more than every weight resident: a weights
-     * pool is one whole allocation, so MiB past what this rank could ever place are left unclaimed
-     * rather than allocated empty. */
+    /* At least the common weights pool and at most every weight resident: the weights pool is one
+     * allocation, so MiB this rank could never place stay unclaimed rather than allocated empty. */
     const int64_t cap   = std::max(common_weights_mib, to_mib_up(weights_cap_bytes));
     const int64_t grown = std::min(common_weights_mib + saved, cap);
     s.kv_mib       = need_kv_mib;
diff --git a/core/mem/vram_budget.h b/core/mem/vram_budget.h
index 4e327f60..55f8cc46 100644
--- a/core/mem/vram_budget.h
+++ b/core/mem/vram_budget.h
@@ -1,62 +1,45 @@
 /* vram_budget.h -- how many bytes each VRAM pool gets, decided once and printed in full.
  *
- * ============================== WHY THIS IS NOT THE §6 VIOLATION IT LOOKS LIKE ==============================
+ * Spec §6 forbids deriving budgets by inference, such as from the free VRAM at startup, which
+ * moves whenever another process touches the card. This is arithmetic on known, printed, stable
+ * terms instead:
  *
- * Spec §6 says the engine does not derive its budgets, and core/mem/pools.cpp still refuses to
- * re-optimise the split it is handed. The reason given there is exact and worth repeating:
- * a budget derived from the FREE VRAM at startup is a benchmark that moves when somebody opens a
- * window on the machine's desktop.
+ *   capacity             totalGlobalMem, fixed for the part.
+ *   already held         capacity - free VRAM, measured once after every kernel plugin has
+ *                        initialised and its code objects are resident: the driver context and
+ *                        loaded code. The only observed term, printed on its own line so a
+ *                        desktop on the card shows up there instead of shrinking a pool.
+ *   --gpu-headroom-mib   what the operator leaves alone (default 96 MiB).
+ *   arena                activation arena plus scratch, from arena_plan_bytes() on the buffer
+ *                        plan, the same call that later allocates it.
  *
- * What that argument forbids is inference. It does not forbid arithmetic on numbers that are all
- * known, all printed, and all stable:
+ * What is left is claimable, spent in two steps:
  *
- *   capacity        totalGlobalMem. A fixed property of the part.
- *   already held    capacity - the free VRAM this process can see, MEASURED once, after every
- *                   kernel plugin has initialised and its code objects are resident. This is the
- *                   driver's context and the loaded code, and it is the one term that is observed
- *                   rather than computed -- so it is printed on its own line, and a machine with a
- *                   desktop on the card shows up in it instead of silently eating a pool.
- *   --gpu-headroom-mib   what the operator wants left alone. Stated, defaulted to 96 MiB.
- *   arena           the activation arena and the scratch beside it, computed from the buffer plan
- *                   by arena_plan_bytes() -- the same call that later allocates it.
+ *   1. Static weights come off the top. Every non-expert weight (attention projections, norms,
+ *      embedding, head) must be resident; the one exception is a token embedding that
+ *      --embedding-placement puts in the pinned host pool, which weight_footprint then excludes.
+ *      Under tensor parallelism each rank's share is already divided (declare runs per rank,
+ *      spec §9). They are a floor, not a share, so the cache can never push attention weights to
+ *      host memory. If they do not fit, startup refuses with the shortfall named.
  *
- * What is left over is claimable, and it is spent in TWO STEPS, not one.
+ *   2. The rest is divided between the expert plane and the KV cache. When the cache lends idle
+ *      blocks to the expert slab, the experts get what the pinned host pool cannot hold and the
+ *      cache gets the rest up to its ceiling, lending back every block no live request holds.
+ *      Without a lender an unused block would sit empty, so experts come first and the cache keeps
+ *      one --max-model-len sequence. The cache never gets less than that sequence.
  *
- * THE STATIC WEIGHTS COME OFF THE TOP. Everything that is not an expert -- the attention
- * projections, the norms, the embedding, the head -- has to be resident for the model to run at a
- * sensible speed at all (the one exception is a token embedding --embedding-placement puts in the
- * pinned host pool, which a lookup reads a few rows of in place; weight_footprint counts it out of
- * the statics then), and under tensor parallel each rank already holds its own even share of
- * them (declare runs per rank with every dimension divided, spec §9). They are a FLOOR, not a
- * share of anything: dividing the weights as a whole would let the cache's side demote the
- * attention projections to host memory to make room for blocks nothing will fill. If they do not
- * fit, that is a refusal with the shortfall named.
+ * Both sides are capped at what they can use (the cache at max_seqs x max_ctx tokens,
+ * KVManager::ceiling; the experts at the whole plane) and one side's excess goes to the other.
  *
- * ONLY WHAT IS LEFT AFTER THAT IS DIVIDED: the expert plane against the KV cache. Where the cache
- * lends its idle blocks to the expert slab, that division has nothing to guess. The experts keep
- * on the card exactly what the pinned host pool cannot hold -- they have nowhere else to be -- and
- * the cache takes the rest, up to what it could ever address; every block no live request holds
- * is lent back to the experts in place. So the cache is as large as the work needs at the moment
- * and the experts have everything else, for a long-context server and a high-concurrency one
- * alike. Without a lender the cache would hold that memory empty, so there the experts come first
- * and the cache keeps one --max-model-len sequence. The cache never gets less than that sequence.
+ * No flag states a pool size: unbudgeted VRAM is unusable, and on a model whose experts do not
+ * fit every unbudgeted GiB costs decode time. Operators move the inputs instead: --gpu-headroom-mib,
+ * --max-model-len and --max-num-seqs (cache bound), --host-pool-mib (which experts must stay on
+ * the card).
  *
- * BOTH SIDES ARE CAPPED AT WHAT THEY COULD USE, and whatever one side cannot take goes to the
- * other rather than nowhere. A cache cannot address past max_seqs x max_ctx tokens
- * (KVManager::ceiling), and an expert plane that fits entirely in VRAM has no use for more; when
- * both fit, both are whole.
- *
- * THERE IS NO FLAG THAT STATES A POOL. The split is a full card rather than a guess: VRAM left
- * unbudgeted is VRAM no pool can use, and on a model whose experts do not fit, every unbudgeted
- * GiB costs measurable decode time. What an operator moves is the inputs -- --gpu-headroom-mib
- * takes card space away, --max-model-len and --max-num-seqs bound the cache, --host-pool-mib
- * decides which experts must stay on the card -- and the arithmetic follows from them.
- *
- * A HOST BACKEND HAS NO CARD, and half the machine's memory stands in for one (host_vram_bytes),
- * split as a card's is. Its weights pool is host memory and holds what a host kernel cannot read
- * where the container stores it (mapped_unit in core/place/planner.h). A device that reports no
- * capacity at all is sized at what each pool needs: the weights the planner copies, and the cache
- * at its ceiling.
+ * The host backend uses half the machine's memory as its capacity (host_vram_bytes) and splits it
+ * like a card; its weights pool holds what a host kernel cannot read where the container stores it
+ * (mapped_unit in core/place/planner.h). A device reporting no capacity gets what each pool needs:
+ * the weights the planner copies, and the cache at its ceiling.
  */
 #pragma once
 #include "../rad_core.h"
@@ -66,50 +49,44 @@
 
 namespace rad {
 
-/* One rank's card and program, as the resolver needs to see them. Every field is either read from
- * the device or computed from the declared program; none of it is a policy. */
+/* One rank's card and program. Every field is read from the device or computed from the declared
+ * program; none is policy. */
 struct VramFacts {
     int64_t capacity   = 0;   /* RadDeviceProps::vram_bytes -- totalGlobalMem */
     int64_t free       = 0;   /* RadDeviceProps::vram_free, measured now */
     int64_t arena      = 0;   /* arena_plan_bytes() for this rank's program, total incl. scratch */
     int64_t staging    = 0;   /* BatchBuilder::device_bytes(): the step slab and the media staging,
                                * and TierExec::device_bytes() when a KV tier is configured */
-    /* THE HARDWARE QUEUES this rank creates after `free` was read -- its compute stream, the expert
-     * mover's, and the second compute lane where the program declares one -- at `queue_bytes`
-     * each. MEASURED, by making one: a queue's kernel-argument ring is the engine's, and the
-     * driver backs every queue with VRAM of its own beside it (33 MiB a queue on an R9700, eight
-     * times the ring). */
+    /* Hardware queues this rank creates after `free` was read (compute stream, expert mover, and
+     * the second compute lane if declared), at `queue_bytes` each. Measured by creating one: the
+     * driver backs every queue with its own VRAM beside the engine's kernel-argument ring (33 MiB
+     * per queue on an R9700, 8x the ring). */
     int     n_queues    = 0;
     int64_t queue_bytes = 0;
-    /* THE NEXT-LAYER EXPERT PREFETCH's ring of expert units and its buffers (xprefetch.h), where it
-     * will be on; its stream is one of `n_queues`. */
+    /* The next-layer expert prefetch's ring and buffers (xprefetch.h), when enabled; its stream is
+     * one of `n_queues`. */
     int64_t prefetch    = 0;
     int64_t kv_ceiling = 0;   /* KVManager::ceiling(max_ctx) for this rank's declared groups */
     int64_t kv_fixed   = 0;   /* KVManager::fixed_bytes(): the part of the ceiling that is state */
-    /* weight_footprint() for this rank, which under tensor parallel is already this card's even
-     * share: declare runs per rank with every dimension already divided. */
+    /* weight_footprint() for this rank; under tensor parallelism already this card's share. */
     int64_t statics    = 0;   /* non-expert weights -- the floor, not a share of anything */
     int64_t experts    = 0;   /* the expert plane: what trades against the KV cache */
     int64_t expert_layer_max = 0;   /* the most expert bytes one routed layer holds */
-    /* THE EXPERTS THE PINNED HOST POOL CANNOT HOLD on this rank, with the slab's spare slots
-     * beside them: they have nowhere to be but the card, so this is the floor under the expert
-     * slab when the cache lends (expert_vram_floor, core/place/planner.h). */
+    /* Experts the pinned host pool cannot hold, plus the slab's spare slots: the expert slab's
+     * floor when the cache lends (expert_vram_floor, core/place/planner.h). */
     int64_t expert_floor = 0;
-    int64_t kv_one     = 0;   /* the cache for ONE --max-model-len sequence: the least it may get */
-    /* WILL THE CACHE LEND ITS IDLE BLOCKS TO THE EXPERT SLAB: a placement that moves units
-     * (expert_tiered, or auto), not --deterministic, on a device with virtual memory management.
-     * Decides the split: a cache that lends gives back what it does not use, so it can be sized
-     * for what live requests could need; one that does not would hold it empty. */
+    int64_t kv_one     = 0;   /* the cache for one --max-model-len sequence: the least it may get */
+    /* The cache lends idle blocks to the expert slab: a placement that moves units (expert_tiered
+     * or auto), not --deterministic, on a device with virtual memory management. A lending cache
+     * can be sized for what live requests could need; a non-lending one would hold it empty. */
     bool    lends      = false;
-    /* Integrated graphics: what of the host's memory the card leaves to the host. Its device
-     * memory IS the host's, so an unclaimed MiB is the operating system's and every other
-     * process's to run in, not slack. 0 on a discrete card. */
+    /* Integrated graphics: host memory the card must leave to the host, since device memory is
+     * host memory there. 0 on a discrete card. */
     int64_t host_reserve = 0;
 };
 
-/* The resolved split, in bytes, beside every term it came from. Always filled, including for a
- * device that reports no capacity -- the placement report and the pool report both want the
- * totals. */
+/* The resolved split in bytes, with every term it came from. Always filled, including for a
+ * device that reports no capacity, because the placement and pool reports want the totals. */
 struct VramBudget {
     int64_t capacity = 0, already_held = 0, headroom = 0, arena = 0, staging = 0;
     int64_t drift = 0;                /* kDriverDrift: what already_held moves by after it is read */
@@ -126,36 +103,30 @@ struct VramBudget {
     int64_t kv_fixed = 0;             /* the state part of kv_ceiling, which no context uses */
     int64_t experts = 0, kv = 0;      /* the two shares, each capped at its ceiling */
     int64_t unusable = 0;             /* elastic neither side could take -- both were full */
-    /* THE PREFILL STAGING REGION: two buffers, each one layer's share of the experts the budget
-     * leaves off the card, taken out of the expert share and appended to the top of the activation
-     * arena (core/place/stager.h). Zero when every expert is resident or the placement cannot move
-     * any. */
+    /* Prefill staging region: two buffers, each one layer's share of the experts left off the
+     * card, appended to the top of the activation arena (core/place/stager.h). Zero when every
+     * expert is resident or the placement cannot move any. */
     int64_t stage = 0;
     int64_t weights = 0;              /* statics + experts: what vram_weights is set to */
     std::string report;       /* the block the engine prints at startup */
 };
 
-/* Writes the answer into cfg.vram_weights_mib / cfg.vram_kv_mib -- ONE resolved number that every
- * consumer downstream reads, so the planner, the KV manager and the pool report cannot disagree
- * (an uneven world's cheaper rank takes its own copy of it: vram_budget_rank_split below).
- * Takes the SMALLEST capacity and free across ranks and the LARGEST arena, because a split has to
- * fit on every card it is applied to.
- *
- * Refuses, by name and by how much, when the fixed terms alone exceed the card. */
+/* Writes cfg.vram_weights_mib / cfg.vram_kv_mib, the one number every downstream consumer reads
+ * (an uneven world's cheaper rank re-splits it with vram_budget_rank_split). Takes the smallest
+ * capacity and free VRAM across ranks and the largest arena, so the split fits every card.
+ * Refuses, by name and size, when the fixed terms alone exceed the card. */
 int vram_budget_resolve(Config& cfg, const std::vector& per_rank, VramBudget* out);
 
-/* The same split worked out on a copy of `cfg`, written nowhere and printed nowhere: for a caller
- * deciding between two programs before it resolves the one it keeps (Engine::plan's table
- * placement). */
+/* The same split on a copy of `cfg`, without writing or logging anything: for choosing between
+ * two programs before resolving one (Engine::plan's table placement). */
 int vram_budget_trial(const Config& cfg, const std::vector& per_rank, VramBudget* out);
 
-/* AN UNEVEN WORLD'S CHEAPER RANK. The resolver above derives one split, the dearest rank's, and one
- * block table serves every rank -- so a rank whose cache costs less per token (an attention-zero
- * rank keeps no attention cache) would reserve the common KV pool for tokens configure_kv then caps
- * away. Given the common split, the MiB that rank's pool needs to page the SAME tokens, and what
- * every one of its weights would take resident (statics + all experts + their spare slots), this
- * moves the difference to its weights pool, no further than that cap; what the cap leaves stays
- * unclaimed. Nothing changes when the need is not below the common pool. */
+/* Re-split for an uneven world's cheaper rank. The resolver derives the most expensive rank's
+ * split, and one block table serves every rank, so a rank whose cache costs less per token (e.g.
+ * one with no attention cache) would over-reserve KV. Given the common split, the MiB this rank
+ * needs to page the same tokens, and the bytes of all its weights resident (statics + all experts
+ * + spare slots), moves the difference to the weights pool up to that cap; the remainder stays
+ * unclaimed. No change when the need is not below the common pool. */
 struct RankSplit {
     int64_t weights_mib  = 0;
     int64_t kv_mib       = 0;
diff --git a/core/mm/imaging.cpp b/core/mm/imaging.cpp
index 49942406..585e6438 100644
--- a/core/mm/imaging.cpp
+++ b/core/mm/imaging.cpp
@@ -82,6 +82,12 @@ inline unsigned muldiv255(unsigned a, unsigned b) {
 
 void resize_lanczos_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA* out) {
     const int iw = src.w, ih = src.h;
+    /* Image.resize returns a copy at the same size. The premultiplied round trip below is not
+     * lossless where alpha is below 255. */
+    if (w == iw && h == ih) {
+        *out = src;
+        return;
+    }
     /* RGBA -> RGBa: the colour premultiplied by the alpha */
     std::vector pre((size_t)iw * ih * 4);
     for (size_t i = 0; i < (size_t)iw * ih; ++i) {
diff --git a/core/mm/imaging.h b/core/mm/imaging.h
index 212da477..637f0e13 100644
--- a/core/mm/imaging.h
+++ b/core/mm/imaging.h
@@ -1,15 +1,15 @@
-/* imaging.h -- the picture arithmetic an image generator's reference pipeline does in PIL, done the
- * way PIL does it, so a picture reaches the model as the reference's would.
+/* imaging.h -- image arithmetic done the way PIL does it, so a picture reaches the model exactly
+ * as the reference pipeline's would.
  *
- * THE RESIZE IS PIL's Image.resize WITH LANCZOS, bit for bit: per-axis filter coefficients
- * computed in double (support 3 times the downscale, normalised to sum one), turned into 22-bit
- * fixed point, a horizontal pass then a vertical one over 8-bit values, each output rounded and
- * clipped -- and an RGBA picture premultiplied by its alpha first and divided back after, which is
- * what PIL's resize does to RGBA. Diffusers' VaeImageProcessor resizes a picture exactly this way.
+ * Resize: PIL's Image.resize with LANCZOS, bit for bit. Per-axis coefficients are computed in
+ * double (support 3x the downscale, normalised to sum one) and converted to 22-bit fixed point;
+ * a horizontal then a vertical pass run over 8-bit values, rounding and clipping each output.
+ * RGBA is premultiplied by alpha first and divided back after, as PIL does. Diffusers'
+ * VaeImageProcessor resizes this way.
  *
- * THE COMPOSITE is Image.paste(picture, mask=alpha) onto white: each channel
- * (c * a + 255 * (255 - a)) / 255 in PIL's rounding -- how the reference flattens a transparent
- * picture for a text encoder that reads RGB. */
+ * Composite: Image.paste(picture, mask=alpha) onto white, each channel
+ * (c * a + 255 * (255 - a)) / 255 with PIL's rounding. The reference flattens a transparent
+ * picture this way for an RGB text encoder. */
 #pragma once
 #include "mm/media.h"
 
diff --git a/core/mm/item.cpp b/core/mm/item.cpp
index ced6ad86..df461703 100644
--- a/core/mm/item.cpp
+++ b/core/mm/item.cpp
@@ -1,19 +1,22 @@
-/* item.cpp -- the parts of an Item the step path uses, in a unit of their own. The batch builder
- * links against this and nothing else in core/mm, so a test that fakes the device layer does not
- * pull the processor -- and through its metadata reader, the real device layer -- in with it. */
+/* item.cpp -- the parts of Item the step path uses. The batch builder links only this unit from
+ * core/mm, so a test that fakes the device layer does not pull in the processor and, through its
+ * metadata reader, the real device layer. */
 #include "mm/processor.h"
 
 namespace rad {
 namespace mm {
 
 void Item::coords(int64_t first, int64_t count, int32_t* planes) const {
-    /* AN AUDIO CLIP IS 1-D (RadBatch::enc): the frame's index, whether it is real, the clip's real
-     * frames and its staged ones. */
+    /* An audio clip is 1-D (RadBatch::enc): frame index, whether the frame takes part in the
+     * convolution, the clip's real frame count and its staged frame count. A clip staged in
+     * chunks (AudioFamily::Qwen3ASR) reads each chunk's first `chunk_read` frames; the rest of the
+     * chunk is alignment the encoder reads as zero. */
     if (kind == Kind::Audio) {
         for (int64_t k = 0; k < count; ++k) {
             const int64_t f = first + k;
             planes[k]             = (int32_t)f;
-            planes[count + k]     = f < valid ? 1 : 0;
+            planes[count + k]     = chunk_staged > 0 ? (f % chunk_staged < chunk_read ? 1 : 0)
+                                                     : (f < valid ? 1 : 0);
             planes[2 * count + k] = valid;
             planes[3 * count + k] = grid_h;
         }
diff --git a/core/mm/media.cpp b/core/mm/media.cpp
index 85343792..7ba705cd 100644
--- a/core/mm/media.cpp
+++ b/core/mm/media.cpp
@@ -1,4 +1,5 @@
-/* media.cpp -- image and video decoding through libavformat / libavcodec / libswscale. */
+/* media.cpp -- image, video and audio decoding and image encoding through libavformat,
+ * libavcodec, libswscale and libswresample. */
 #include "mm/media.h"
 
 #include "rad_internal.h"
@@ -56,10 +57,9 @@ bool decoder_available() { return true; }
 
 namespace {
 
-/* THE DEMUXERS A REQUEST MAY REACH, and nothing else. A container format that can name another
- * file -- a playlist, a concat script, an image sequence pattern -- would otherwise let a request
- * make the server open a path of its choosing, so the probe only ever considers these, and the
- * protocol list below is empty so none of them can open anything either. */
+/* The only demuxers a request may reach. A format that can name another file (a playlist, a
+ * concat script, an image-sequence pattern) would let a request make the server open a path of
+ * its choosing. The empty protocol whitelist also stops these from opening anything. */
 constexpr const char* kFormats =
     "mov,mp4,m4a,3gp,3g2,mj2,matroska,webm,avi,mpegts,flv,ogg,gif,apng,image2pipe,png_pipe,"
     "jpeg_pipe,jpegls_pipe,jpegxl_pipe,webp_pipe,bmp_pipe,tiff_pipe,qoi_pipe,pgm_pipe,ppm_pipe,"
@@ -152,8 +152,8 @@ struct Input {
         if (!dec) { *why = "out of memory"; return RAD_E_NOMEM; }
         e = avcodec_parameters_to_context(dec, fmt->streams[stream]->codecpar);
         if (e < 0) { *why = "decoder setup failed (" + averr(e) + ")"; return RAD_E_INVAL; }
-        /* A few threads a decode: this runs on a server worker, one per request in flight, so
-         * handing each one every core would oversubscribe the machine the engine runs on. */
+        /* Decodes run on server workers, one per request in flight; a few threads each avoids
+         * oversubscribing the machine. */
         dec->thread_count = 4;
         e = avcodec_open2(dec, codec, nullptr);
         if (e < 0) { *why = std::string("no decoder for ") + codec->name + " (" + averr(e) + ")"; return RAD_E_UNSUPPORTED; }
@@ -161,68 +161,19 @@ struct Input {
     }
 };
 
-/* One decoded frame to packed RGB24 at its own size. The YUV coefficients and range are the
- * frame's own, so a BT.709 video and a full-range JPEG both come out with the colours they were
- * encoded with.
+/* One decoded frame to packed `fmt` (RGB24 or RGBA, `ch` bytes a pixel) at its own size, rows
+ * tight. The YUV coefficients and range are the frame's own, so a BT.709 video and a full-range
+ * JPEG keep the colours they were encoded with.
  *
- * THE SCALER FLAGS ARE THE REFERENCE PIPELINE'S: transformers decodes video through PyAV
- * (`to_ndarray(format="rgb24")`, its default backend), which converts with plain SWS_BILINEAR.
- * The flags decide how chroma is upsampled, and at a sharp colour edge two choices differ by up to
- * 70 levels: measured on an EmbeddingGemma 2 clip, SWS_BICUBIC | ACCURATE_RND | FULL_CHR_H_INT
- * left the embedding at cosine 0.9995 against the reference, these at 0.99998 with every patch
- * within one level. */
-int to_rgb(const AVFrame* f, SwsContext** sws, Frame* out, std::string* why) {
+ * The scaler flags match the reference pipeline: transformers decodes video through PyAV
+ * (`to_ndarray(format="rgb24")`), which converts with plain SWS_BILINEAR. The flags decide chroma
+ * upsampling, which can differ by up to 70 levels at a sharp colour edge; with these flags every
+ * patch lands within one level of the reference. */
+int to_packed(const AVFrame* f, SwsContext** sws, AVPixelFormat fmt, size_t ch,
+              std::vector* out, std::string* why) {
     const AVPixelFormat src = (AVPixelFormat)f->format;
-    *sws = sws_getCachedContext(*sws, f->width, f->height, src, f->width, f->height,
-                                AV_PIX_FMT_RGB24,
-                                SWS_BILINEAR, nullptr,
-                                nullptr, nullptr);
-    if (!*sws) { *why = "no colour conversion from this pixel format"; return RAD_E_UNSUPPORTED; }
-    int cs = f->colorspace;
-    if (cs == AVCOL_SPC_UNSPECIFIED || cs == AVCOL_SPC_RGB) cs = AVCOL_SPC_BT470BG;
-    const int* coef = sws_getCoefficients(cs);
-    const int src_full = f->color_range == AVCOL_RANGE_JPEG ||
-                         src == AV_PIX_FMT_YUVJ420P || src == AV_PIX_FMT_YUVJ422P ||
-                         src == AV_PIX_FMT_YUVJ444P || src == AV_PIX_FMT_YUVJ440P;
-    sws_setColorspaceDetails(*sws, coef, src_full, sws_getCoefficients(SWS_CS_DEFAULT), 1, 0,
-                             1 << 16, 1 << 16);
-    /* THE SCALER WRITES INTO A FRAME FFMPEG ALLOCATED, and the rows are copied out. Its SIMD paths
-     * store whole vectors, so a row ends wherever the last vector does: a 4:2:0 or 4:2:2 picture
-     * 1788 wide converted with these flags writes 12 bytes past 1788 x 3, and into a buffer of
-     * exactly width x height x 3 those land on the next heap chunk's header -- the process aborts
-     * at a later allocation ("malloc(): corrupted top size"). av_frame_get_buffer pads every line
-     * and the end as the scaler expects. */
-    AVFrame* rgb = av_frame_alloc();
-    if (!rgb) { *why = "out of memory"; return RAD_E_NOMEM; }
-    rgb->format = AV_PIX_FMT_RGB24;
-    rgb->width = f->width;
-    rgb->height = f->height;
-    if (av_frame_get_buffer(rgb, 0) < 0) {
-        av_frame_free(&rgb);
-        *why = "out of memory";
-        return RAD_E_NOMEM;
-    }
-    const int e = sws_scale(*sws, f->data, f->linesize, 0, f->height, rgb->data, rgb->linesize);
-    if (e != f->height) {
-        av_frame_free(&rgb);
-        *why = "colour conversion failed";
-        return RAD_E_INVAL;
-    }
-    out->w = f->width;
-    out->h = f->height;
-    const size_t row = (size_t)f->width * 3;
-    out->rgb.resize(row * (size_t)f->height);
-    for (int y = 0; y < f->height; ++y)
-        std::memcpy(out->rgb.data() + (size_t)y * row, rgb->data[0] + (ptrdiff_t)y * rgb->linesize[0], row);
-    av_frame_free(&rgb);
-    return RAD_OK;
-}
-
-/* The same conversion to packed RGBA, for a picture whose alpha is kept. */
-int to_rgba(const AVFrame* f, SwsContext** sws, FrameRGBA* out, std::string* why) {
-    const AVPixelFormat src = (AVPixelFormat)f->format;
-    *sws = sws_getCachedContext(*sws, f->width, f->height, src, f->width, f->height,
-                                AV_PIX_FMT_RGBA, SWS_BILINEAR, nullptr, nullptr, nullptr);
+    *sws = sws_getCachedContext(*sws, f->width, f->height, src, f->width, f->height, fmt,
+                                SWS_BILINEAR, nullptr, nullptr, nullptr);
     if (!*sws) { *why = "no colour conversion from this pixel format"; return RAD_E_UNSUPPORTED; }
     int cs = f->colorspace;
     if (cs == AVCOL_SPC_UNSPECIFIED || cs == AVCOL_SPC_RGB) cs = AVCOL_SPC_BT470BG;
@@ -231,9 +182,13 @@ int to_rgba(const AVFrame* f, SwsContext** sws, FrameRGBA* out, std::string* why
                          src == AV_PIX_FMT_YUVJ444P || src == AV_PIX_FMT_YUVJ440P;
     sws_setColorspaceDetails(*sws, sws_getCoefficients(cs), src_full,
                              sws_getCoefficients(SWS_CS_DEFAULT), 1, 0, 1 << 16, 1 << 16);
+    /* Convert into an FFmpeg-allocated frame, then copy the rows out. The scaler's SIMD paths
+     * store whole vectors and overrun a tight row (a 4:2:0 or 4:2:2 picture 1788 wide writes
+     * 12 bytes past 1788 x 3), which corrupts the heap in a buffer of exactly w x h x 3.
+     * av_frame_get_buffer pads every line and the end as the scaler expects. */
     AVFrame* dst = av_frame_alloc();
     if (!dst) { *why = "out of memory"; return RAD_E_NOMEM; }
-    dst->format = AV_PIX_FMT_RGBA;
+    dst->format = fmt;
     dst->width = f->width;
     dst->height = f->height;
     if (av_frame_get_buffer(dst, 0) < 0) {
@@ -247,24 +202,34 @@ int to_rgba(const AVFrame* f, SwsContext** sws, FrameRGBA* out, std::string* why
         *why = "colour conversion failed";
         return RAD_E_INVAL;
     }
-    out->w = f->width;
-    out->h = f->height;
-    const size_t row = (size_t)f->width * 4;
-    out->rgba.resize(row * (size_t)f->height);
+    const size_t row = (size_t)f->width * ch;
+    out->resize(row * (size_t)f->height);
     for (int y = 0; y < f->height; ++y)
-        std::memcpy(out->rgba.data() + (size_t)y * row, dst->data[0] + (ptrdiff_t)y * dst->linesize[0],
+        std::memcpy(out->data() + (size_t)y * row, dst->data[0] + (ptrdiff_t)y * dst->linesize[0],
                     row);
     av_frame_free(&dst);
     return RAD_OK;
 }
 
-/* THE DECODE LOOP, for both kinds: every frame in presentation order, `keep(i, frame)` told the
- * index of each and whether to stop.
+int to_rgb(const AVFrame* f, SwsContext** sws, Frame* out, std::string* why) {
+    out->w = f->width;
+    out->h = f->height;
+    return to_packed(f, sws, AV_PIX_FMT_RGB24, 3, &out->rgb, why);
+}
+
+/* As to_rgb, to packed RGBA, for a picture whose alpha is kept. */
+int to_rgba(const AVFrame* f, SwsContext** sws, FrameRGBA* out, std::string* why) {
+    out->w = f->width;
+    out->h = f->height;
+    return to_packed(f, sws, AV_PIX_FMT_RGBA, 4, &out->rgba, why);
+}
+
+/* The decode loop for images and video: every frame in presentation order goes to
+ * `keep(i, frame)`, which returns < 0 to fail, > 0 to stop and 0 to continue.
  *
- * AN EMPTY PACKET REPEATS THE FRAME BEFORE IT: it is how Ogg Theora stores a frame that does not
- * change. Sent to a decoder, an empty packet would read as the end of the stream and the next one
- * would be refused; it is passed to `keep` as another copy of the last frame instead, so the
- * frame indices and the stream's length are the ones the frame count promised. */
+ * An empty packet repeats the previous frame (Ogg Theora stores an unchanged frame this way).
+ * The decoder would read it as end of stream, so it is passed to `keep` as another copy of the
+ * last frame instead, keeping indices and length consistent with the stated frame count. */
 template 
 int decode_frames(Input& in, Keep&& keep, std::string* why) {
     AVPacket* pkt = av_packet_alloc();
@@ -388,10 +353,9 @@ int decode_image_rgba(const uint8_t* data, size_t n, int64_t max_pixels, FrameRG
     return RAD_OK;
 }
 
-/* ONE PICTURE THROUGH ONE ENCODER. The pixels are converted to the pixel format the encoder takes
- * (swscale, full-range BT.601 for jpeg's YUV, as PIL writes it), sent as one frame, and the one
- * packet that comes back is the file: png, mjpeg and libwebp all write a complete image file a
- * packet. */
+/* One picture through one encoder: convert to the encoder's pixel format (swscale; full-range
+ * BT.601 for jpeg's YUV, as PIL writes it) and send one frame. png, mjpeg and libwebp each write
+ * a complete image file per packet, so the packet that comes back is the file. */
 int encode_image(const uint8_t* px, int32_t w, int32_t h, int32_t ch, const std::string& format,
                  int32_t quality, std::vector* out, std::string* why) {
     std::string wy;
@@ -440,9 +404,8 @@ int encode_image(const uint8_t* px, int32_t w, int32_t h, int32_t ch, const std:
             cx->flags |= AV_CODEC_FLAG_QSCALE;
             cx->global_quality = FF_QP2LAMBDA * qs;
         }
-        /* PNG AT zlib LEVEL 1 WITH PER-ROW PREDICTION: a 2048^2 picture in 0.16 s and 5.9 MB, where
-         * the encoder's default (level 6) takes 1.0 s for 5.3 MB -- a second of a few-step image
-         * model's request, on one core, for a tenth of the bytes. */
+        /* zlib level 1 with per-row prediction: a 2048^2 picture takes 0.16 s for 5.9 MB, against
+         * 1.0 s for 5.3 MB at the default level 6, on one core. */
         if (format == "png") {
             cx->compression_level = 1;
             av_opt_set(cx->priv_data, "pred", "mixed", 0);
@@ -498,9 +461,9 @@ int decode_video(const uint8_t* data, size_t n, SampleFn sample, const void* use
     if (!why) why = &w;
     if (!data || n == 0) { *why = "empty"; return RAD_E_INVAL; }
 
-    /* THE FRAME COUNT FIRST, because which frames to keep depends on it. Many containers state it;
-     * those that do not are demuxed once without decoding, which counts packets -- one a frame for
-     * every codec a request is going to send -- at the cost of reading the bytes twice. */
+    /* Frame count first, since the sample choice depends on it. A container that does not state
+     * it is demuxed once without decoding to count packets (one per frame for the codecs requests
+     * send), at the cost of reading the bytes twice. */
     VideoInfo info;
     {
         Input probe;
@@ -547,8 +510,8 @@ int decode_video(const uint8_t* data, size_t n, SampleFn sample, const void* use
             *why = "a frame is larger than the server's pixel limit";
             return RAD_E_INVAL;
         }
-        /* The same frame may be sampled twice when the stream is shorter than its own header
-         * says; each slot that names this index takes a copy. */
+        /* A frame may be sampled twice when the stream is shorter than its header says; each
+         * slot naming this index takes a copy. */
         bool converted = false;
         while (next < out->index.size() && out->index[next] == i) {
             if (!converted) {
@@ -566,9 +529,8 @@ int decode_video(const uint8_t* data, size_t n, SampleFn sample, const void* use
     sws_freeContext(sws);
     if (s < 0) return s;
     if (last_kept < 0) { *why = "the video decoded to no frame"; return RAD_E_INVAL; }
-    /* A STREAM SHORTER THAN ITS HEADER leaves the last sampled indices unreached. They take the
-     * last frame that was decoded, which is what a reader that clamps an index past the end
-     * returns. */
+    /* A stream shorter than its header leaves the last sampled indices unreached. They take the
+     * last decoded frame, as a reader that clamps an index past the end would. */
     for (size_t k = next; k < out->index.size(); ++k) out->frames[k] = out->frames[(size_t)last_kept];
     return RAD_OK;
 }
@@ -577,7 +539,7 @@ int decode_video(const uint8_t* data, size_t n, SampleFn sample, const void* use
 
 namespace {
 
-/* THE AUDIO DEMUXERS A REQUEST MAY REACH, chosen as the video list is: formats that hold one
+/* The only audio demuxers a request may reach, chosen as kFormats is: formats that hold one
  * stream of samples and cannot name another file. */
 constexpr const char* kAudioFormats = "wav,w64,mp3,flac,ogg,mov,mp4,m4a,matroska,webm,aac,aiff";
 
@@ -706,7 +668,7 @@ int decode_audio(const uint8_t* data, size_t n, int32_t rate, int64_t max_sample
         if (st < 0) break;
         if (e != AVERROR(EAGAIN) && e != AVERROR_EOF) { *why = "the audio would not decode (" + averr(e) + ")"; st = RAD_E_INVAL; break; }
     }
-    /* What the resampler still holds. */
+    /* Flush what the resampler still holds. */
     if (st == RAD_OK && (int64_t)out->size() < max_samples) st = take(nullptr, 0);
     av_packet_free(&pkt);
     av_frame_free(&f);
diff --git a/core/mm/media.h b/core/mm/media.h
index 98af3a2c..8473accb 100644
--- a/core/mm/media.h
+++ b/core/mm/media.h
@@ -1,18 +1,17 @@
-/* media.h -- turning the bytes of an image or a video into RGB frames (spec §11).
+/* media.h -- image, video and audio decoding, and picture encoding (spec §11).
  *
- * ONE DECODER FOR BOTH, and it is libavformat/libavcodec. An image is a one-frame stream to it, so
- * PNG, JPEG, WebP, GIF, BMP and TIFF arrive through the same demuxer probe and the same decode loop
- * a video takes, and there is one colour conversion (libswscale) rather than one per format. A
- * build without the libraries has no decoder at all: every call here returns RAD_E_UNSUPPORTED
- * with the reason, and the server refuses a media part by name rather than guessing at its bytes.
+ * One decoder for everything: libavformat/libavcodec. An image is a one-frame stream, so PNG,
+ * JPEG, WebP, GIF, BMP and TIFF take the same demuxer probe, decode loop and colour conversion
+ * (libswscale) as a video. In a build without the libraries every call returns
+ * RAD_E_UNSUPPORTED with the reason, and the server refuses the media part by name.
  *
- * THE BYTES COME FROM THE REQUEST, never from a URL. The server accepts `data:` URLs only, so
- * nothing here opens a file or a network stream: the demuxer reads a memory buffer through its own
- * I/O context, and the protocol whitelist is empty.
+ * Bytes come from the request only (`data:` URLs). Nothing here opens a file or a network
+ * stream: the demuxer reads a memory buffer through its own I/O context, and the protocol
+ * whitelist is empty.
  *
- * WHAT A FRAME IS: packed 8-bit RGB, row-major, no padding. An alpha channel is DROPPED, not
- * composited -- the reference processor converts with PIL's convert("RGB"), which does the same,
- * so a transparent PNG reaches the encoder with the colours under its alpha.
+ * A Frame is packed 8-bit RGB, row-major, no padding. Alpha is dropped, not composited, as the
+ * reference processor's PIL convert("RGB") does, so a transparent PNG reaches the encoder with
+ * the colours under its alpha.
  */
 #pragma once
 #include 
@@ -27,36 +26,34 @@ struct Frame {
     std::vector rgb;          /* [h, w, 3] */
 };
 
-/* A picture with its alpha: packed 8-bit RGBA, row-major, no padding -- what an image generator
- * reads and writes. A source without alpha comes back opaque. */
+/* Packed 8-bit RGBA, row-major, no padding; what an image generator reads and writes. A source
+ * without alpha decodes as opaque. */
 struct FrameRGBA {
     int32_t              w = 0, h = 0;
     std::vector rgba;         /* [h, w, 4] */
 };
 
-/* Is there a decoder in this build. */
+/* Whether this build has a decoder. */
 bool decoder_available();
 
-/* The first frame of an image (or of anything with a video stream). Refuses more than
- * `max_pixels` in the SOURCE, which is what bounds the memory a request can make the server
- * allocate before any resize happens. */
+/* The first frame of an image (or of anything with a video stream). Refuses a source over
+ * `max_pixels`, which bounds what a request can make the server allocate before any resize. */
 int decode_image(const uint8_t* data, size_t n, int64_t max_pixels, Frame* out, std::string* why);
-/* The same, keeping the alpha channel. */
+/* As decode_image, keeping the alpha channel. */
 int decode_image_rgba(const uint8_t* data, size_t n, int64_t max_pixels, FrameRGBA* out,
                       std::string* why);
 
-/* A PICTURE TO A FILE: `px` is [h, w, ch] 8-bit, ch 3 (RGB) or 4 (RGBA), and `format` one of png,
- * jpeg and webp. `quality` 0..100 is jpeg's and lossy webp's (0 or above 100: the format's own
- * default); png is lossless and webp is lossless at 100. jpeg has no alpha and is refused one.
- * RAD_E_UNSUPPORTED, with the reason, for a format this build has no encoder for. */
+/* Encodes `px`, [h, w, ch] 8-bit with ch 3 (RGB) or 4 (RGBA), as an image file; `format` is png,
+ * jpeg or webp. `quality` 0..100 applies to jpeg and lossy webp (0 or above 100 picks the
+ * format's default); png is lossless and webp is lossless at 100. jpeg refuses alpha. Returns
+ * RAD_E_UNSUPPORTED, with the reason, for a format this build cannot encode. */
 int encode_image(const uint8_t* px, int32_t w, int32_t h, int32_t ch, const std::string& format,
                  int32_t quality, std::vector* out, std::string* why);
 
-/* HOW A VIDEO IS SAMPLED, and it happens INSIDE the decode rather than after it: a minute of 1080p
- * is 10 GB of RGB, so frames that are not sampled are never converted or kept. The choice of which
- * frames is the processor's (it depends on the stream's length and rate, which only the decoder
- * knows), so it is a callback: given the stream's frame count and rate, return the frame indices to
- * keep, ascending. */
+/* Video sampling happens inside the decode: a minute of 1080p is 10 GB of RGB, so unsampled
+ * frames are never converted or kept. The processor picks the frames from the stream's length
+ * and rate, which only the decoder knows, so the choice is a callback: given the frame count and
+ * rate, return the frame indices to keep, ascending. */
 struct VideoInfo {
     int64_t n_frames = 0;    /* frames in the stream; counted by demuxing when the header omits it */
     double  fps = 0.0;       /* the stream's average rate */
@@ -73,11 +70,10 @@ struct Video {
 int decode_video(const uint8_t* data, size_t n, SampleFn sample, const void* user,
                  int64_t max_pixels, Video* out, std::string* why);
 
-/* AN AUDIO CLIP as mono float samples at `rate` Hz: the first audio stream, resampled with
- * libswresample at the source's channel layout and then averaged across channels -- the plain
- * mean every reference loader (librosa, torchaudio's to-mono) takes, where swresample's own
- * downmix would weight a stereo pair by 0.707. At most `max_samples` are kept: a longer clip is
- * cut there, as the reference feature extractor truncates. */
+/* The first audio stream as mono float samples at `rate` Hz. Resampled with libswresample at the
+ * source's channel layout, then averaged across channels: the plain mean reference loaders
+ * (librosa, torchaudio's to-mono) take, where swresample's downmix weights a stereo pair by
+ * 0.707. A clip longer than `max_samples` is truncated, as the reference feature extractor does. */
 int decode_audio(const uint8_t* data, size_t n, int32_t rate, int64_t max_samples,
                  std::vector* out, std::string* why);
 
diff --git a/core/mm/processor.cpp b/core/mm/processor.cpp
index e4701ba0..4c304232 100644
--- a/core/mm/processor.cpp
+++ b/core/mm/processor.cpp
@@ -150,9 +150,8 @@ int VisionConfig::from_meta(const RadModelMeta& m, std::string* why) {
                         "vision_start_token_id, vision_end_token_id)";
         return RAD_E_NOTFOUND;
     }
-    /* THE PROCESSOR-ONLY KEYS DEFAULT TO THE FAMILY'S VALUES. They come from the checkpoint's
-     * preprocessor configs, which a container may not carry; the numbers below are what the
-     * Qwen3.x checkpoints ship. */
+    /* Processor-only keys come from the checkpoint's preprocessor configs, which a container may
+     * not carry; the defaults are what the Qwen3.x checkpoints ship. */
     image_min_pixels = rad_meta_geti(&m, "preprocessor.size.shortest_edge",
                                      rad_meta_geti(&m, "preprocessor.min_pixels", 65536));
     image_max_pixels = rad_meta_geti(&m, "preprocessor.size.longest_edge",
@@ -170,11 +169,6 @@ int VisionConfig::from_meta(const RadModelMeta& m, std::string* why) {
         if (why) *why = "the container's preprocessor configuration is inconsistent: " + bad;
         return RAD_E_INVAL;
     }
-    for (int c = 0; c < 3; ++c)
-        if (!(stdv[c] > 0.0f)) {
-            if (why) *why = "preprocessor.image_std must be positive";
-            return RAD_E_INVAL;
-        }
     return RAD_OK;
 }
 
@@ -193,6 +187,8 @@ int VisionConfig::check(std::string* why) const {
                   std::to_string(video_min_pixels));
     if (!(fps > 0.0)) return no("fps must be positive");
     if (min_frames < 1) return no("min_frames must be at least 1");
+    for (int c = 0; c < 3; ++c)
+        if (!(stdv[c] > 0.0f)) return no("image_std must be positive");
     if (max_frames < min_frames)
         return no("max_frames " + std::to_string(max_frames) + " is below min_frames " +
                   std::to_string(min_frames));
@@ -203,8 +199,6 @@ int VisionConfig::check(std::string* why) const {
                       ") is not a range of whole merged patches");
         if (!(max_pixels_tolerance > 0.0) || max_segment_patches <= 0)
             return no("max_pixels_tolerance and max_num_patches must be positive");
-        for (int c = 0; c < 3; ++c)
-            if (!(stdv[c] > 0.0f)) return no("image_std must be positive");
     }
     if (family == Family::Gemma4) {
         if (!soft_budget_ok(image_soft_tokens))
@@ -219,10 +213,27 @@ int VisionConfig::check(std::string* why) const {
 
 /* ================================================================== sizes and sampling */
 
-/* Python's round(), which is round-half-to-even on the double -- the reference computes these in
- * Python, and a size that lands on .5 rounds the way it does there. */
+/* Python's round(): half-to-even on the double, so a size landing on .5 rounds as the Python
+ * reference does. */
 static inline int64_t pyround(double x) { return (int64_t)std::nearbyint(x); }
 
+/* The step the references share after rounding each side to `factor`: a size past `max_px`
+ * shrinks by the area ratio and rounds down, one under `min_px` grows and rounds up. `t` frames
+ * (rounded to `tb`) count toward the area; a picture passes 1 and 1. */
+static void fit_pixels(int64_t t, int64_t tb, int64_t h, int64_t w, int32_t factor,
+                       int64_t min_px, int64_t max_px, int64_t* hb, int64_t* wb) {
+    const double f = factor;
+    if (tb * *hb * *wb > max_px) {
+        const double beta = std::sqrt((double)(t * h * w) / (double)max_px);
+        *hb = std::max(factor, (int64_t)std::floor((double)h / beta / f) * factor);
+        *wb = std::max(factor, (int64_t)std::floor((double)w / beta / f) * factor);
+    } else if (tb * *hb * *wb < min_px) {
+        const double beta = std::sqrt((double)min_px / (double)(t * h * w));
+        *hb = (int64_t)std::ceil((double)h * beta / f) * factor;
+        *wb = (int64_t)std::ceil((double)w * beta / f) * factor;
+    }
+}
+
 int smart_resize_image(int64_t h, int64_t w, int32_t factor, int64_t min_px, int64_t max_px,
                        int64_t* oh, int64_t* ow, std::string* why) {
     if (h <= 0 || w <= 0) { if (why) *why = "the picture has no size"; return RAD_E_INVAL; }
@@ -233,15 +244,7 @@ int smart_resize_image(int64_t h, int64_t w, int32_t factor, int64_t min_px, int
     const double f = factor;
     int64_t hb = pyround((double)h / f) * factor;
     int64_t wb = pyround((double)w / f) * factor;
-    if (hb * wb > max_px) {
-        const double beta = std::sqrt((double)(h * w) / (double)max_px);
-        hb = std::max(factor, (int64_t)std::floor((double)h / beta / f) * factor);
-        wb = std::max(factor, (int64_t)std::floor((double)w / beta / f) * factor);
-    } else if (hb * wb < min_px) {
-        const double beta = std::sqrt((double)min_px / (double)(h * w));
-        hb = (int64_t)std::ceil((double)h * beta / f) * factor;
-        wb = (int64_t)std::ceil((double)w * beta / f) * factor;
-    }
+    fit_pixels(1, 1, h, w, factor, min_px, max_px, &hb, &wb);
     *oh = hb;
     *ow = wb;
     return RAD_OK;
@@ -264,23 +267,15 @@ int smart_resize_video(int64_t t, int64_t h, int64_t w, int32_t tfactor, int32_t
     int64_t hb = pyround((double)h / f) * factor;
     int64_t wb = pyround((double)w / f) * factor;
     const int64_t tb = pyround((double)t / (double)tfactor) * tfactor;
-    if (tb * hb * wb > max_px) {
-        const double beta = std::sqrt((double)(t * h * w) / (double)max_px);
-        hb = std::max(factor, (int64_t)std::floor((double)h / beta / f) * factor);
-        wb = std::max(factor, (int64_t)std::floor((double)w / beta / f) * factor);
-    } else if (tb * hb * wb < min_px) {
-        const double beta = std::sqrt((double)min_px / (double)(t * h * w));
-        hb = (int64_t)std::ceil((double)h * beta / f) * factor;
-        wb = (int64_t)std::ceil((double)w * beta / f) * factor;
-    }
+    fit_pixels(t, tb, h, w, factor, min_px, max_px, &hb, &wb);
     *oh = hb;
     *ow = wb;
     return RAD_OK;
 }
 
-/* THE REFERENCE'S FRAME CHOICE: as many frames as `fps` gives over the clip's duration, clamped to
- * [min_frames, max_frames] and to what the stream has, spread evenly over it -- numpy's linspace,
- * rounded half-to-even. A stream that states no rate is taken at 24, as the reference does. */
+/* The reference's frame choice: as many frames as `fps` gives over the clip's duration, clamped to
+ * [min_frames, max_frames] and to the stream's length, spread evenly (numpy's linspace, rounded
+ * half-to-even). A stream with no stated rate is taken at 24 fps, as the reference does. */
 std::vector sample_frames(const VideoInfo& info, double fps, int32_t min_frames,
                                    int32_t max_frames) {
     const int64_t total = info.n_frames;
@@ -358,11 +353,11 @@ std::vector sample_frames_gemma4(const VideoInfo& info, double fps, int
 
 /* ================================================================== the resample
  *
- * Pillow's ImagingResample for an 8-bit RGB image, transcribed: the coefficient table in double,
- * normalised per output pixel and rounded to 22-bit fixed point; a horizontal pass over only the
- * source rows the vertical pass will read, into an 8-bit intermediate; then the vertical pass. The
- * rounding at the intermediate is part of the function -- a single-pass float resample is a
- * different (and slightly better) function, and not the one the model was trained against. */
+ * Pillow's ImagingResample for 8-bit RGB: coefficients in double, normalised per output pixel and
+ * rounded to 22-bit fixed point; a horizontal pass over only the source rows the vertical pass
+ * reads, into an 8-bit intermediate; then the vertical pass. The intermediate rounding is part of
+ * the function: a single-pass float resample is a different function from the one the model was
+ * trained against. */
 namespace {
 
 constexpr int kPrec = 32 - 8 - 2;
@@ -380,9 +375,9 @@ inline uint8_t clip8(int32_t v, int prec) {
     return (uint8_t)(s < 0 ? 0 : (s > 255 ? 255 : s));
 }
 
-/* One axis: `bounds` gets (first, count) per output pixel and `kk` its fixed-point weights, `ksize`
- * a row, `*prec` their fraction bits: PIL's fixed 22, or -- `torch` -- ATen's per-axis choice, the
- * most bits at which the largest weight still fits an int16. */
+/* One axis: `bounds` gets (first, count) per output pixel and `kk` its fixed-point weights,
+ * `ksize` per row; `*prec` gets their fraction bits. PIL uses a fixed 22; with `torch`, ATen's
+ * per-axis choice: the most bits at which the largest weight still fits an int16. */
 int coeffs(int32_t in_size, int32_t out_size, std::vector* bounds,
            std::vector* kk, bool torch, int* prec) {
     const double scale = (double)in_size / (double)out_size;
@@ -521,15 +516,14 @@ inline uint64_t mix64(uint64_t x) {
 }
 
 /* Two independent 64-bit lanes over the patch bytes and the grid. The prefix cache folds the key
- * into a chained 128-bit block identity; a collision would serve one picture's cache for another,
- * so both lanes are carried. */
+ * into a chained 128-bit block identity, and a collision would serve one picture's cache for
+ * another, so both lanes are kept. */
 void content_key(const Item& it, uint64_t* hi, uint64_t* lo) {
     uint64_t a = 0x6a09e667f3bcc908ull ^ mix64((uint64_t)it.grid_t << 42 ^
                                                (uint64_t)it.grid_h << 21 ^ (uint64_t)it.grid_w);
     uint64_t b = 0xbb67ae8584caa73bull ^
                  mix64(it.kind == Kind::Image ? 1u : it.kind == Kind::Video ? 2u : 3u);
-    /* The tiling, when the segments have sizes of their own: the same patches cut differently
-     * are different encoder inputs. */
+    /* The tiling: the same patches cut into different segments are different encoder inputs. */
     for (const Item::Segment& sg : it.segments)
         a = mix64(a ^ ((uint64_t)(uint32_t)sg.h << 32 | (uint32_t)sg.w)) + (uint64_t)sg.patch0;
     const uint8_t* p = reinterpret_cast(it.pixels.data());
@@ -547,17 +541,29 @@ void content_key(const Item& it, uint64_t* hi, uint64_t* lo) {
     *lo = mix64(b + (uint64_t)n);
 }
 
-/* THE PATCH ROWS, in merge-block order, from `frames` (temporal * grid_t of them, already resized
- * to grid_h * patch by grid_w * patch). Each row is (channel, frame, y, x), each value normalised
- * as the reference does -- (x - 255 mean) / (255 std) in f32 -- and rounded to bf16. */
+/* After its content key, the item's expansion as one run of `rows` copies of `tok` between the
+ * `start` and `end` markers. */
+static void one_run(Item* it, int32_t start, int64_t rows, int32_t tok, int32_t end) {
+    content_key(*it, &it->key_hi, &it->key_lo);
+    it->expand.reserve((size_t)rows + 2);
+    it->expand.push_back(start);
+    it->seg_at.push_back(1);
+    it->expand.insert(it->expand.end(), (size_t)rows, tok);
+    it->expand.push_back(end);
+}
+
+/* The patch rows, in merge-block order, from `frames` (temporal * grid_t of them, already resized
+ * to grid_h * patch by grid_w * patch). Each row is (channel, frame, y, x); each value is
+ * normalised as the reference does, (x - 255 mean) / (255 std) in f32, and rounded to bf16. */
 void patchify(const VisionConfig& c, const std::vector& frames, Item* it) {
     const int P = c.patch, T = c.temporal, M = c.merge;
     const int gh = it->grid_h, gw = it->grid_w;
     float m255[3], s255[3];
     for (int ch = 0; ch < 3; ++ch) {
-        /* torch.tensor(mean) * (1 / rescale_factor), in f32: the fused rescale's own constants. */
-        m255[ch] = c.mean[ch] * (float)(1.0 / (1.0 / 255.0));
-        s255[ch] = c.stdv[ch] * (float)(1.0 / (1.0 / 255.0));
+        /* torch.tensor(mean) * (1 / rescale_factor), in f32: the fused rescale's own constants.
+         * 1 / (1 / 255) rounds to 255 in f32. */
+        m255[ch] = c.mean[ch] * 255.0f;
+        s255[ch] = c.stdv[ch] * 255.0f;
     }
     /* One lookup per (channel, byte): the normalisation is a function of the byte alone. */
     uint16_t lut[3][256];
@@ -586,17 +592,22 @@ void patchify(const VisionConfig& c, const std::vector& frames, It
                     }
 }
 
-/* Gemma 4's patch rows: merge-block order like patchify's (each pooling window's patches are
- * consecutive, which is what lets the pooler be a mean of k^2 consecutive rows; attention and the
- * position terms read each patch's own coordinates, so the order is free), each row (y, x,
- * channel), each value 2 * (u * (1/255)) - 1 in f32 -- the processor's rescale and then the
- * model's own input scaling -- rounded to bf16. One frame a segment. */
-void patchify_gemma4(const VisionConfig& c, const std::vector& frames, Item* it) {
+/* Gemma 4's patch rows, in merge-block order like patchify's: each pooling window's patches are
+ * consecutive, so the pooler is a mean of k^2 consecutive rows (attention and the position terms
+ * read each patch's own coordinates, so the order is otherwise free). Each row is (y, x, channel);
+ * each value is 2 * (p - 0.5) in f32 (the model's input scaling), rounded to bf16, where p is the
+ * processor's rescale u * (1/255). The processors AutoProcessor loads take that product in f32 for
+ * pictures (Gemma4ImageProcessor) and in double, rounded to f32, for video (Gemma 4's and
+ * EmbeddingGemma 2's video processors); `video` picks which, and the two differ for u = 127. One
+ * frame per segment. */
+void patchify_gemma4(const VisionConfig& c, const std::vector& frames, bool video,
+                     Item* it) {
     const int P = c.patch, M = c.merge;
     const int gh = it->grid_h, gw = it->grid_w;
     uint16_t lut[256];
     for (int v = 0; v < 256; ++v) {
-        const float p = (float)v * (float)(1.0 / 255.0);
+        const float p = video ? (float)((double)v * (1.0 / 255.0))
+                              : (float)v * (float)(1.0 / 255.0);
         lut[v] = rad_f32_to_bf16(2.0f * (p - 0.5f));
     }
     const int64_t dim = it->patch_dim;
@@ -637,8 +648,8 @@ int Processor::init(const VisionConfig& cfg,
         return RAD_E_INVAL;
     cfg_ = cfg;
     if (cfg.family == Family::Lfm2) {
-        /* The markers are named, not numbered, in the config: resolved here, every one, so a
-         * vocabulary missing one is refused at startup rather than on the first large picture. */
+        /* The config names the markers rather than numbering them. Resolve all of them here so a
+         * vocabulary missing one is refused at startup, not on the first large picture. */
         if (!token_id) return RAD_E_INVAL;
         cfg_.tok_start = token_id("<|image_start|>");
         cfg_.tok_end   = token_id("<|image_end|>");
@@ -652,7 +663,7 @@ int Processor::init(const VisionConfig& cfg,
                 if (id < 0) return RAD_E_NOTFOUND;
                 tok_tiles_[(size_t)(r - 1) * cfg.max_tiles + (c - 1)] = id;
             }
-        /* A tile and the largest thumbnail are one segment each: of the tower and of a pass. */
+        /* A tile and the largest thumbnail are each one segment, of the tower and of a pass. */
         const int64_t seg = std::max((int64_t)(cfg.tile / cfg.patch) * (cfg.tile / cfg.patch),
                                               cfg.image_max_pixels / ((int64_t)cfg.patch * cfg.patch));
         if (seg > cfg.max_patches || seg > cfg.max_segment_patches) return RAD_E_INVAL;
@@ -667,8 +678,8 @@ int Processor::init(const VisionConfig& cfg,
         encode_text_ = std::move(encode_text);
         return RAD_OK;
     }
-    /* The largest image the encoder takes in one pass, in pixels: the band's ceiling comes down to
-     * it, so smart_resize itself keeps every image inside a pass. */
+    /* The largest image one encoder pass takes, in pixels. Lowering the band's ceiling to it makes
+     * smart_resize keep every image inside a pass. */
     const int64_t pass_px = cfg.max_patches * cfg.patch * cfg.patch;
     if (cfg_.image_max_pixels > pass_px) cfg_.image_max_pixels = pass_px;
     if (cfg_.image_min_pixels > cfg_.image_max_pixels) cfg_.image_min_pixels = cfg_.image_max_pixels;
@@ -683,15 +694,7 @@ void lfm2_size(int64_t h, int64_t w, int32_t factor, int64_t min_px, int64_t max
     const double f = factor;
     int64_t hb = std::max(factor, pyround((double)h / f) * factor);
     int64_t wb = std::max(factor, pyround((double)w / f) * factor);
-    if (hb * wb > max_px) {
-        const double beta = std::sqrt((double)(h * w) / (double)max_px);
-        hb = std::max(factor, (int64_t)std::floor((double)h / beta / f) * factor);
-        wb = std::max(factor, (int64_t)std::floor((double)w / beta / f) * factor);
-    } else if (hb * wb < min_px) {
-        const double beta = std::sqrt((double)min_px / (double)(h * w));
-        hb = (int64_t)std::ceil((double)h * beta / f) * factor;
-        wb = (int64_t)std::ceil((double)w * beta / f) * factor;
-    }
+    fit_pixels(1, 1, h, w, factor, min_px, max_px, &hb, &wb);
     *oh = hb;
     *ow = wb;
 }
@@ -703,9 +706,9 @@ bool lfm2_too_large(int64_t h, int64_t w, int32_t patch, int32_t factor, int64_t
     return (double)(hb * wb) > (double)max_px * tolerance;
 }
 
-/* The reference walks the ratios sorted by tile count; within one count it orders them as a
- * Python set happens to, which this walks by columns. The two can differ only on an exact tie
- * between two grids of one count, both nearest. */
+/* The reference walks the ratios sorted by tile count, and within one count in Python set order;
+ * this walks by columns. The two differ only on an exact tie between two nearest grids of one
+ * count. */
 void lfm2_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32_t tile,
                int32_t* cols, int32_t* rows) {
     const double aspect = (double)w / (double)h;
@@ -725,9 +728,9 @@ void lfm2_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32
 }
 
 /* LFM2-VL's image processor (transformers' Lfm2VlImageProcessor), segment by segment: the tiles
- * in row-major order, then the thumbnail; within one, patches in merge-block order (each
- * merge x merge block's patches consecutive, dy then dx -- which is how the projector's pixel
- * unshuffle reads them, so its merge is a view), each patch (y, x, channel). */
+ * in row-major order, then the thumbnail. Within a segment, patches are in merge-block order (each
+ * merge x merge block consecutive, dy then dx, as the projector's pixel unshuffle reads them, so
+ * its merge is a view); each patch is (y, x, channel). */
 int Processor::image_lfm2(const Frame& f, std::shared_ptr* out, std::string* why) const {
     const VisionConfig& c = cfg_;
     const int32_t F = c.factor(), P = c.patch, M = c.merge;
@@ -823,13 +826,7 @@ int Processor::image_from(const Frame& f, std::shared_ptr* out, std::strin
     /* An image fills the temporal depth by repetition. */
     std::vector frames((size_t)c.temporal, &r);
     patchify(c, frames, it.get());
-    content_key(*it, &it->key_hi, &it->key_lo);
-
-    it->expand.reserve((size_t)it->seg_rows + 2);
-    it->expand.push_back(c.tok_start);
-    it->seg_at.push_back(1);
-    it->expand.insert(it->expand.end(), (size_t)it->seg_rows, c.tok_image);
-    it->expand.push_back(c.tok_end);
+    one_run(it.get(), c.tok_start, it->seg_rows, c.tok_image, c.tok_end);
     *out = std::move(it);
     return RAD_OK;
 }
@@ -856,13 +853,8 @@ int Processor::image_gemma4(const Frame& f, int32_t soft, std::shared_ptr*
         if (why) *why = "the image's soft-token budget is more patches than one encoder pass holds";
         return RAD_E_INVAL;
     }
-    patchify_gemma4(c, { src }, it.get());
-    content_key(*it, &it->key_hi, &it->key_lo);
-    it->expand.reserve((size_t)it->seg_rows + 2);
-    it->expand.push_back(c.tok_start);
-    it->seg_at.push_back(1);
-    it->expand.insert(it->expand.end(), (size_t)it->seg_rows, c.tok_image);
-    it->expand.push_back(c.tok_end);
+    patchify_gemma4(c, { src }, /*video=*/false, it.get());
+    one_run(it.get(), c.tok_start, it->seg_rows, c.tok_image, c.tok_end);
     *out = std::move(it);
     return RAD_OK;
 }
@@ -891,9 +883,9 @@ int Processor::video_gemma4(const Video& v, std::shared_ptr* out, std::str
         resize_bicubic(v.frames[i], (int32_t)w, (int32_t)h, &resized[i]);
         rf.push_back(&resized[i]);
     }
-    patchify_gemma4(c, rf, it.get());
+    patchify_gemma4(c, rf, /*video=*/true, it.get());
     content_key(*it, &it->key_hi, &it->key_lo);
-    /* One  placeholders  run a frame, back to back: the reference's visual-only form
+    /* One  placeholders  run per frame, back to back: the reference's visual-only form
      * (add_timestamps off). */
     for (int32_t g = 0; g < it->grid_t; ++g) {
         it->expand.push_back(c.tok_start);
@@ -909,8 +901,8 @@ int Processor::video_from(const Video& v, std::shared_ptr* out, std::strin
     const VisionConfig& c = cfg_;
     if (c.family == Family::Gemma4) return video_gemma4(v, out, why);
     if (v.frames.empty()) { if (why) *why = "the video decoded to no frames"; return RAD_E_INVAL; }
-    /* The frames and their indices, padded to whole temporal groups by repeating the last. A clip
-     * shorter than one group is padded the same way, so a single-frame video is one group. */
+    /* Pad the frames and their indices to whole temporal groups by repeating the last; a clip
+     * shorter than one group becomes one group. */
     std::vector frames;
     std::vector idx = v.index;
     for (const Frame& f : v.frames) frames.push_back(&f);
@@ -921,8 +913,8 @@ int Processor::video_from(const Video& v, std::shared_ptr* out, std::strin
     const int64_t nf = (int64_t)v.frames.size() < c.temporal ? c.temporal
                                                               : (int64_t)v.frames.size();
 
-    /* THE PER-FRAME CAP: at most `max_frame_rows` output rows' worth of pixels a frame, and the
-     * video budget's even share, but never under the band's floor. */
+    /* Per-frame cap: at most `max_frame_rows` output rows' worth of pixels per frame and at most
+     * the video budget's even share, but never under the band's floor. */
     int64_t max_px = c.video_max_pixels;
     if (c.max_frame_rows > 0) {
         const int64_t f2 = (int64_t)c.factor() * c.factor();
@@ -960,12 +952,11 @@ int Processor::video_from(const Video& v, std::shared_ptr* out, std::strin
     patchify(c, rframes, it.get());
     content_key(*it, &it->key_hi, &it->key_lo);
 
-    /* THE TIMESTAMPED EXPANSION: per temporal group, "" then a run of pads between
-     * vision_start and vision_end, T being the mean of the group's first and last frame times.
-     * It stands for the template's whole <|vision_start|><|video_pad|><|vision_end|>, as the
-     * model's own processor wrote it (transformers 4.57, qwen-vl-utils). transformers 5.x swaps
-     * only the pad and leaves that outer pair around the frames -- two tokens the model was not
-     * trained with. */
+    /* Timestamped expansion: per temporal group, "" then pads between vision_start and
+     * vision_end, T being the mean of the group's first and last frame times. It replaces the
+     * template's whole <|vision_start|><|video_pad|><|vision_end|>, as the model's own processor
+     * does (transformers 4.57, qwen-vl-utils). transformers 5.x replaces only the pad and leaves
+     * an outer start/end pair the model was not trained with. */
     const double vfps = v.info.fps > 0.0 ? v.info.fps : 24.0;
     for (int32_t g = 0; g < it->grid_t; ++g) {
         const double t0 = (double)idx[(size_t)g * c.temporal] / vfps;
@@ -1050,11 +1041,51 @@ static std::vector read_list(const RadModelMeta& m, const char* key) {
     return v;
 }
 
+int64_t AudioConfig::chunk_rows(int64_t frames) {
+    for (int i = 0; i < 3; ++i) frames = frames > 0 ? (frames - 1) / 2 + 1 : 0;
+    return frames;
+}
+
+/* Qwen3ASRFeatureExtractor's framing, from processor_config.json's `feature_extractor` and the
+ * encoder's audio_config. The mel band (0 to 8000 Hz) is the extractor's own constant, not a
+ * key. */
+static int qwen3asr_from_meta(const RadModelMeta& m, AudioConfig* c, std::string* why) {
+    auto gi = [&](const char* k, int64_t d) {
+        char key[128];
+        std::snprintf(key, sizeof key, "processor.feature_extractor.%s", k);
+        return rad_meta_geti(&m, key, d);
+    };
+    c->family       = AudioFamily::Qwen3ASR;
+    c->rate         = (int32_t)gi("sampling_rate", 16000);
+    c->hop          = (int32_t)gi("hop_length", 160);
+    c->fft          = (int32_t)gi("n_fft", 400);
+    c->frame_length = c->fft;
+    c->n_mels       = (int32_t)gi("feature_size", rad_meta_geti(&m, "audio_config.num_mel_bins", 128));
+    c->min_samples  = gi("min_length", 8000);
+    c->chunk        = (int32_t)(2 * gi("n_window", rad_meta_geti(&m, "audio_config.n_window", 50)));
+    c->min_freq     = 0.0;
+    c->max_freq     = 8000.0;
+    c->tok_audio    = (int32_t)rad_meta_geti(&m, "audio_token_id", -1);
+    if (rad_meta_getf(&m, "processor.feature_extractor.dither", 0.0) != 0.0) {
+        if (why) *why = "the feature extractor dithers its input (feature_extractor.dither), which "
+                        "no deterministic front end reproduces";
+        return RAD_E_UNSUPPORTED;
+    }
+    if (c->rate <= 0 || c->hop <= 0 || c->fft < 2 || c->n_mels <= 0 || c->chunk <= 0 ||
+        c->min_samples < 0 || c->tok_audio < 0 || 2.0 * c->max_freq > (double)c->rate) {
+        if (why) *why = "the container's Qwen3-ASR feature configuration is incomplete or "
+                        "inconsistent (rate, hop, n_fft, mel bins, n_window, audio_token_id)";
+        return RAD_E_INVAL;
+    }
+    return RAD_OK;
+}
+
 int AudioConfig::from_meta(const RadModelMeta& m, std::string* why) {
     const char* mt = rad_meta_gets(&m, "audio_config.model_type", "");
+    if (mt && !std::strcmp(mt, "qwen3_asr_encoder")) return qwen3asr_from_meta(m, this, why);
     if (!mt || std::strcmp(mt, "gemma4_audio")) {
         if (why) *why = "the container states no audio tower this processor knows (audio_config."
-                        "model_type gemma4_audio)";
+                        "model_type gemma4_audio or qwen3_asr_encoder)";
         return RAD_E_NOTFOUND;
     }
     rate         = (int32_t)rad_meta_geti(&m, "preprocessor.sampling_rate", 16000);
@@ -1079,8 +1110,8 @@ int AudioConfig::from_meta(const RadModelMeta& m, std::string* why) {
     tok_audio = (int32_t)rad_meta_geti(&m, "audio_token_id", -1);
     tok_start = (int32_t)rad_meta_geti(&m, "boa_token_id", -1);
     tok_end   = (int32_t)rad_meta_geti(&m, "eoa_token_id", rad_meta_geti(&m, "eoa_token_index", -1));
-    /* DITHER IS NOISE: the reference adds Gaussian noise of this deviation to every sample, a
-     * different draw each call, and no fixed input reproduces it. */
+    /* Dither adds Gaussian noise of this deviation to every sample, a new draw each call, so no
+     * deterministic front end can reproduce it. */
     if (rad_meta_getf(&m, "preprocessor.dither", 0.0) != 0.0) {
         if (why) *why = "the feature extractor dithers its input (preprocessor.dither), which no "
                         "deterministic front end reproduces";
@@ -1130,6 +1161,40 @@ void fft_inplace(std::vector& re, std::vector& im,
     }
 }
 
+/* A mixed-radix complex FFT over any length (Whisper's 400 points are 2^4 * 5^2). Decimation in
+ * time over `radix` (the length's prime factors, smallest first): n points at stride s
+ * are p transforms of n / p points at stride s * p, combined by p-point DFTs with twiddles. `tw`
+ * is exp(-2 pi i k / N) for k < N, N the outermost length, read at stride N / n by a level of n
+ * points; `work` is scratch, 2n doubles a level, the levels below reusing what follows. */
+void fft_mixed(const double* in_re, const double* in_im, int64_t stride, int64_t n,
+               double* out_re, double* out_im, const int32_t* radix,
+               const std::vector& tw_re, const std::vector& tw_im, double* work) {
+    if (n == 1) { out_re[0] = in_re[0]; out_im[0] = in_im[0]; return; }
+    const int64_t p = radix[0], m = n / p;
+    for (int64_t q = 0; q < p; ++q)
+        fft_mixed(in_re + q * stride, in_im + q * stride, stride * p, m, out_re + q * m,
+                  out_im + q * m, radix + 1, tw_re, tw_im, work + 2 * n);
+    /* X[k + s m] = sum_q W_n^(q (k + s m)) Y_q[k]: Y_q is periodic in m. */
+    const int64_t step = (int64_t)tw_re.size() / n;
+    double* t_re = work;
+    double* t_im = work + n;
+    for (int64_t k = 0; k < m; ++k)
+        for (int64_t s = 0; s < p; ++s) {
+            const int64_t at = k + s * m;
+            double ar = 0.0, ai = 0.0;
+            for (int64_t q = 0; q < p; ++q) {
+                const int64_t e = (q * at) % n * step;
+                const double yr = out_re[q * m + k], yi = out_im[q * m + k];
+                ar += yr * tw_re[(size_t)e] - yi * tw_im[(size_t)e];
+                ai += yr * tw_im[(size_t)e] + yi * tw_re[(size_t)e];
+            }
+            t_re[at] = ar;
+            t_im[at] = ai;
+        }
+    std::memcpy(out_re, t_re, (size_t)n * sizeof(double));
+    std::memcpy(out_im, t_im, (size_t)n * sizeof(double));
+}
+
 /* numpy.linspace's values: start + i * step, the last exactly `stop`. */
 std::vector linspace(double a, double b, int64_t n) {
     std::vector v((size_t)n);
@@ -1141,52 +1206,102 @@ std::vector linspace(double a, double b, int64_t n) {
 
 }  /* namespace */
 
-int Processor::init_audio(const AudioConfig& cfg) {
-    if (cfg.merge <= 0 || cfg.max_frames <= 0 || cfg.max_frames % cfg.merge) return RAD_E_INVAL;
+int Processor::init_audio(const AudioConfig& cfg, std::string* why) {
+    auto refuse = [&](int rc, std::string w) {
+        if (why) *why = std::move(w);
+        return rc;
+    };
+    if (cfg.merge <= 0 || cfg.max_frames <= 0 || cfg.max_frames % cfg.merge)
+        return refuse(RAD_E_INVAL, "the audio encoder's pass (" + std::to_string(cfg.max_frames) +
+                                       " frames) is not whole rows of " +
+                                       std::to_string(cfg.merge) + " frames");
+    const bool qwen = cfg.family == AudioFamily::Qwen3ASR;
+    /* Gemma 4's FFT is radix 2; Qwen3-ASR's runs mixed radix over any length. */
+    if (!qwen && (cfg.fft < 2 || (cfg.fft & (cfg.fft - 1)) != 0))
+        return refuse(RAD_E_UNSUPPORTED, "the feature extractor's " + std::to_string(cfg.fft) +
+                                             "-point FFT is not a power of two, which this "
+                                             "extractor's radix-2 transform needs");
     acfg_ = cfg;
-    /* np.hanning(frame_length + 1)[:-1], the periodic window, stored as float32. */
+    if (qwen) {
+        /* A whole chunk is staged as merge * chunk_rows(chunk) frames, which must hold it; a
+         * clip's longest is as many whole chunks as one pass takes. */
+        const int64_t staged = (int64_t)cfg.merge * AudioConfig::chunk_rows(cfg.chunk);
+        if (staged < cfg.chunk || cfg.max_frames < staged)
+            return refuse(RAD_E_INVAL, "a whole " + std::to_string(cfg.chunk) + "-frame chunk is "
+                                       "staged as " + std::to_string(staged) + " frames, which "
+                                       "does not hold it or does not fit one " +
+                                       std::to_string(cfg.max_frames) + "-frame encoder pass");
+        if (cfg.tok_start < 0 || cfg.tok_end < 0)
+            return refuse(RAD_E_INVAL, "the clip's opening or closing token is unresolved");
+        acfg_.max_samples = cfg.max_frames / staged * cfg.chunk * cfg.hop;
+    }
+    /* np.hanning(frame_length + 1)[:-1] -- torch.hann_window's periodic window -- stored as
+     * float32. */
     hann_.resize((size_t)cfg.frame_length);
     for (int32_t i = 0; i < cfg.frame_length; ++i)
         hann_[(size_t)i] = (float)(0.5 - 0.5 * std::cos(2.0 * M_PI * (double)i /
                                                         (double)cfg.frame_length));
-    /* transformers' mel_filter_bank(norm=None, mel_scale="htk"): triangles between consecutive
-     * mel points, in Hz, over the FFT bins' frequencies. */
+    /* transformers' mel_filter_bank: triangles between consecutive mel points, in Hz, over the
+     * FFT bins' frequencies -- Gemma 4's on the HTK scale with no area normalisation, Qwen3-ASR's
+     * (Whisper's) on the Slaney scale, each triangle scaled to unit area by 2 / (its width in
+     * Hz). */
     const int64_t nb = cfg.fft / 2 + 1, nm = cfg.n_mels;
-    auto hz2mel = [](double f) { return 2595.0 * std::log10(1.0 + f / 700.0); };
-    auto mel2hz = [](double m) { return 700.0 * (std::pow(10.0, m / 2595.0) - 1.0); };
+    auto htk2mel = [](double f) { return 2595.0 * std::log10(1.0 + f / 700.0); };
+    auto mel2htk = [](double m) { return 700.0 * (std::pow(10.0, m / 2595.0) - 1.0); };
+    const double slaney_step = 27.0 / std::log(6.4);
+    auto slaney2mel = [&](double f) {
+        return f >= 1000.0 ? 15.0 + std::log(f / 1000.0) * slaney_step : 3.0 * f / 200.0;
+    };
+    auto mel2slaney = [&](double m) {
+        return m >= 15.0 ? 1000.0 * std::exp((m - 15.0) / slaney_step) : 200.0 * m / 3.0;
+    };
     const std::vector fft_f = linspace(0.0, (double)(cfg.rate / 2), nb);
-    std::vector filt = linspace(hz2mel(cfg.min_freq), hz2mel(cfg.max_freq), nm + 2);
-    for (double& f : filt) f = mel2hz(f);
+    std::vector filt = qwen ? linspace(slaney2mel(cfg.min_freq), slaney2mel(cfg.max_freq), nm + 2)
+                                    : linspace(htk2mel(cfg.min_freq), htk2mel(cfg.max_freq), nm + 2);
+    for (double& f : filt) f = qwen ? mel2slaney(f) : mel2htk(f);
     mel_.assign((size_t)(nb * nm), 0.0);
     mel_lo_.assign((size_t)nm, 0);
     mel_hi_.assign((size_t)nm, 0);
     for (int64_t i = 0; i < nm; ++i) {
+        const double enorm = qwen ? 2.0 / (filt[(size_t)i + 2] - filt[(size_t)i]) : 1.0;
         int32_t lo = -1, hi = 0;
         for (int64_t k = 0; k < nb; ++k) {
             const double down = -(filt[(size_t)i] - fft_f[(size_t)k]) /
                                 (filt[(size_t)i + 1] - filt[(size_t)i]);
             const double up = (filt[(size_t)i + 2] - fft_f[(size_t)k]) /
                               (filt[(size_t)i + 2] - filt[(size_t)i + 1]);
-            const double w = std::max(0.0, std::min(down, up));
+            const double w = std::max(0.0, std::min(down, up)) * enorm;
             mel_[(size_t)(i * nb + k)] = w;
             if (w != 0.0) { if (lo < 0) lo = (int32_t)k; hi = (int32_t)k + 1; }
         }
-        /* A triangle covers a few bins; the sum skips the zeros, which add nothing to it. */
+        /* A triangle covers a few bins; the sum skips the zeros. */
         mel_lo_[(size_t)i] = lo < 0 ? 0 : lo;
         mel_hi_[(size_t)i] = hi;
     }
-    /* The FFT's twiddles, once: a butterfly that evaluates its own sin and cos makes the
-     * transform cost a 30 s clip over 100 ms. */
-    brev_.assign((size_t)cfg.fft, 0);
-    for (int32_t i = 1, j = 0; i < cfg.fft; ++i) {
-        int32_t bit = cfg.fft >> 1;
-        for (; j & bit; bit >>= 1) j ^= bit;
-        j ^= bit;
-        brev_[(size_t)i] = j;
+    /* Precomputed twiddles: evaluating sin and cos per butterfly costs over 100 ms on a 30 s
+     * clip. Gemma 4's power of two runs radix 2 over half a turn; Qwen3-ASR's FFT runs mixed
+     * radix over the length's prime factors (a power of two included) and a whole turn. */
+    radix_.clear();
+    brev_.clear();
+    const bool pow2 = !qwen;
+    if (pow2) {
+        brev_.assign((size_t)cfg.fft, 0);
+        for (int32_t i = 1, j = 0; i < cfg.fft; ++i) {
+            int32_t bit = cfg.fft >> 1;
+            for (; j & bit; bit >>= 1) j ^= bit;
+            j ^= bit;
+            brev_[(size_t)i] = j;
+        }
+    } else {
+        int32_t r = cfg.fft;
+        for (int32_t f = 2; f * f <= r; ++f)
+            while (r % f == 0) { radix_.push_back(f); r /= f; }
+        if (r > 1) radix_.push_back(r);
     }
-    tw_re_.resize((size_t)cfg.fft / 2);
-    tw_im_.resize((size_t)cfg.fft / 2);
-    for (int32_t k = 0; k < cfg.fft / 2; ++k) {
+    const int32_t n_tw = pow2 ? cfg.fft / 2 : cfg.fft;
+    tw_re_.resize((size_t)n_tw);
+    tw_im_.resize((size_t)n_tw);
+    for (int32_t k = 0; k < n_tw; ++k) {
         const double ang = -2.0 * M_PI * (double)k / (double)cfg.fft;
         tw_re_[(size_t)k] = std::cos(ang);
         tw_im_[(size_t)k] = std::sin(ang);
@@ -1195,10 +1310,124 @@ int Processor::init_audio(const AudioConfig& cfg) {
     return RAD_OK;
 }
 
+/* Qwen3-ASR's clip (AudioFamily::Qwen3ASR): Whisper's log-mel over the whole clip, then staged a
+ * chunk at a time. The spectrum is computed in double, two real frames a complex transform as the
+ * Gemma 4 path does; the reference computes in float32, and the difference is far below the bf16
+ * the features are staged in. */
+int Processor::audio_qwen3asr(const std::vector& samples, std::shared_ptr* out,
+                              std::string* why) const {
+    const AudioConfig& c = acfg_;
+    if ((int64_t)samples.size() > c.max_samples) {
+        if (why) *why = "the clip is longer than one audio encoder pass holds (" +
+                        std::to_string(c.max_samples / c.rate) + " s)";
+        return RAD_E_INVAL;
+    }
+    /* A clip shorter than min_samples is zero-padded to it first; the reflected padding is of the
+     * padded clip. */
+    const int64_t n = std::max((int64_t)samples.size(), c.min_samples);
+    const int64_t pad = c.fft / 2;
+    if (n <= pad) {
+        if (why) *why = "the clip is too short to frame";
+        return RAD_E_INVAL;
+    }
+    /* torch.stft(center=True) makes 1 + n / hop frames and the extractor drops the last. */
+    const int64_t real = n / c.hop;
+    const int64_t full = real / c.chunk, rem = real % c.chunk;
+    const int64_t rows_full = AudioConfig::chunk_rows(c.chunk);
+    const int64_t rows_rem = AudioConfig::chunk_rows(rem);
+    const int64_t staged_full = (int64_t)c.merge * rows_full;
+    const int64_t rows = full * rows_full + rows_rem;
+    const int64_t frames = full * staged_full + (int64_t)c.merge * rows_rem;
+    if (frames > c.max_frames) {
+        if (why) *why = "the clip is more frames than one audio encoder pass holds";
+        return RAD_E_INVAL;
+    }
+
+    /* x[q] of the padded clip, reflected at both ends: torch's "reflect" leaves the edge sample
+     * out, so x[-1] is x[1] and x[n] is x[n - 2]. */
+    auto sample = [&](int64_t p) -> double {
+        int64_t q = p - pad;
+        if (q < 0) q = -q;
+        if (q >= n) q = 2 * (n - 1) - q;
+        return q < (int64_t)samples.size() ? (double)samples[(size_t)q] : 0.0;
+    };
+    const int64_t N = c.fft, nb = N / 2 + 1, nm = c.n_mels;
+    std::vector re((size_t)N), im((size_t)N), ore((size_t)N), oim((size_t)N);
+    std::vector work((size_t)(4 * N));
+    std::vector pw((size_t)nb), pw2((size_t)nb);
+    auto window = [&](int64_t t, double* dst) {
+        for (int64_t j = 0; j < N; ++j)
+            dst[j] = (double)((float)sample(t * c.hop + j) * hann_[(size_t)j]);
+    };
+    std::vector logmel((size_t)(real * nm));
+    double top = -INFINITY;
+    auto emit = [&](int64_t t, const double* p) {
+        double* dst = logmel.data() + t * nm;
+        for (int64_t b = 0; b < nm; ++b) {
+            double s = 0.0;
+            const double* w = mel_.data() + (size_t)b * nb;
+            for (int32_t k = mel_lo_[(size_t)b]; k < mel_hi_[(size_t)b]; ++k) s += p[k] * w[k];
+            const double v = std::log10(std::max(s, 1e-10));
+            dst[b] = v;
+            if (v > top) top = v;
+        }
+    };
+    for (int64_t t = 0; t < real; t += 2) {
+        const bool pair = t + 1 < real;
+        window(t, re.data());
+        if (pair) window(t + 1, im.data());
+        else std::fill(im.begin(), im.end(), 0.0);
+        fft_mixed(re.data(), im.data(), 1, N, ore.data(), oim.data(), radix_.data(), tw_re_,
+                  tw_im_, work.data());
+        for (int64_t k = 0; k < nb; ++k) {
+            const size_t a = (size_t)k, b = k ? (size_t)(N - k) : 0;
+            const double ar = 0.5 * (ore[a] + ore[b]), ai = 0.5 * (oim[a] - oim[b]);
+            const double br = 0.5 * (oim[a] + oim[b]), bi = -0.5 * (ore[a] - ore[b]);
+            pw[a]  = ar * ar + ai * ai;
+            pw2[a] = br * br + bi * bi;
+        }
+        emit(t, pw.data());
+        if (pair) emit(t + 1, pw2.data());
+    }
+
+    auto it = std::make_shared();
+    it->kind = Kind::Audio;
+    it->grid_t = 1;
+    it->grid_h = (int32_t)frames;
+    it->grid_w = 1;
+    it->patch_dim = nm;
+    it->n_patch = frames;
+    it->valid = (int32_t)real;
+    it->chunk_staged = (int32_t)staged_full;
+    it->chunk_read = c.chunk;
+    it->rows_h = (int32_t)rows;
+    it->rows_w = 1;
+    it->seg_rows = (int32_t)rows;
+    it->n_seg = rows > 0 ? 1 : 0;
+    /* Chunk k's real frames at row k * staged_full; everything else stays zero -- the reference's
+     * padding inside the last chunk, and the alignment past a whole one. */
+    it->pixels.assign((size_t)(frames * nm), 0);
+    const double floor_v = top - 8.0;
+    for (int64_t t = 0; t < real; ++t) {
+        uint16_t* dst = it->pixels.data() + ((t / c.chunk) * staged_full + t % c.chunk) * nm;
+        const double* src = logmel.data() + t * nm;
+        for (int64_t b = 0; b < nm; ++b)
+            dst[b] = rad_f32_to_bf16((float)((std::max(src[b], floor_v) + 4.0) / 4.0));
+    }
+    content_key(*it, &it->key_hi, &it->key_lo);
+    it->expand.push_back(c.tok_start);
+    it->seg_at.push_back(1);
+    it->expand.insert(it->expand.end(), (size_t)rows, c.tok_audio);
+    it->expand.push_back(c.tok_end);
+    *out = std::move(it);
+    return RAD_OK;
+}
+
 int Processor::audio_from(const std::vector& samples, std::shared_ptr* out,
                           std::string* why) const {
     if (!audio_on_) { if (why) *why = "this program declares no audio encoder"; return RAD_E_UNSUPPORTED; }
     const AudioConfig& c = acfg_;
+    if (c.family == AudioFamily::Qwen3ASR) return audio_qwen3asr(samples, out, why);
     const int64_t n = std::min((int64_t)samples.size(), c.max_samples);
     const int64_t real = c.real_frames(n);
     const int64_t rows = (real + c.merge - 1) / c.merge;
@@ -1258,11 +1487,11 @@ int Processor::audio_from(const std::vector& samples, std::shared_ptr mag2((size_t)nb);
     const int64_t N = c.fft;
     for (int64_t i = 0; i < real; i += 2) {
@@ -1281,11 +1510,7 @@ int Processor::audio_from(const std::vector& samples, std::shared_ptrkey_hi, &it->key_lo);
-    it->expand.push_back(c.tok_start);
-    it->seg_at.push_back(1);
-    it->expand.insert(it->expand.end(), (size_t)rows, c.tok_audio);
-    it->expand.push_back(c.tok_end);
+    one_run(it.get(), c.tok_start, rows, c.tok_audio, c.tok_end);
     /* A clip too short for one real frame is  and nothing to encode. */
     if (rows == 0) it->encoded = true;
     *out = std::move(it);
@@ -1296,7 +1521,10 @@ int Processor::audio(const uint8_t* bytes, size_t n, std::shared_ptr* out,
                      std::string* why) const {
     if (!audio_on_) { if (why) *why = "this program declares no audio encoder"; return RAD_E_UNSUPPORTED; }
     std::vector s;
-    RAD_TRY(decode_audio(bytes, n, acfg_.rate, acfg_.max_samples, &s, why));
+    /* Gemma 4's extractor truncates at max_samples; Qwen3-ASR's does not, so one sample more is
+     * decoded and a clip past a pass is refused rather than cut. */
+    const bool whole = acfg_.family == AudioFamily::Qwen3ASR;
+    RAD_TRY(decode_audio(bytes, n, acfg_.rate, acfg_.max_samples + (whole ? 1 : 0), &s, why));
     return audio_from(s, out, why);
 }
 
diff --git a/core/mm/processor.h b/core/mm/processor.h
index ab50b2eb..5be2cf42 100644
--- a/core/mm/processor.h
+++ b/core/mm/processor.h
@@ -1,26 +1,26 @@
-/* processor.h -- what an image or a video becomes before an encoder sees it (spec §11).
+/* processor.h -- what an image, video or audio clip becomes before an encoder sees it (spec §11).
  *
- * THIS IS THE QWEN-VL PROCESSOR FAMILY (Qwen2-VL through Qwen3.x), and what is family-specific is
- * the arithmetic, not the numbers: every size, rate and token id comes from the container, which
- * carries the checkpoint's config.json and its two preprocessor configs (rad-convert writes them
- * under `vision_config.*`, `preprocessor.*` and `video_preprocessor.*`). What the family fixes:
+ * The family fixes the arithmetic, not the numbers: every size, rate and token id comes from the
+ * container, which carries the checkpoint's config.json and its two preprocessor configs
+ * (rad-convert writes them under `vision_config.*`, `preprocessor.*` and `video_preprocessor.*`).
+ * The Qwen-VL family (Qwen2-VL through Qwen3.x), the reference shape the others follow:
  *
  *   - A picture is resized so both sides are multiples of patch * merge and its area falls in the
  *     configured band, keeping the aspect ratio (smart_resize), with PIL's antialiased bicubic.
- *   - It is cut into patch x patch squares, `temporal` frames deep -- an image is repeated to fill
- *     the depth -- in MERGE-BLOCK ORDER: the merge x merge patches that become one output row are
+ *   - It is cut into patch x patch squares, `temporal` frames deep (an image is repeated to fill
+ *     the depth), in merge-block order: the merge x merge patches that become one output row are
  *     consecutive. Each patch row is (channel, frame, y, x), normalised by the configured mean and
  *     deviation, in bf16.
  *   - The prompt gets ` pad*N ` where the template put the media, N
- *     being the encoder's output rows. A video gets one such run per temporal group, each after
- *     the text `` giving the group's time -- which is how the model knows when a frame
- *     is, since the groups share one temporal rotary component.
- *   - Rotary positions are three components (temporal, height, width): text counts up in all
+ *     being the encoder's output rows. A video gets one run per temporal group, each after the
+ *     text ``; the groups share one temporal rotary component, so the text is how the
+ *     model knows when a frame is.
+ *   - Rotary positions have three components (temporal, height, width). Text counts up in all
  *     three; a media run holds its start in the first and adds its row and column to the other
- *     two; the text after it continues from start + max(rows, cols). (RopeLayout below.)
+ *     two; the text after it continues from start + max(rows, cols). See RopeLayout.
  *
  * The encoder's input is patches plus each patch's (row, col) in its segment and the segment's
- * size, which is all a learned position table and a 2-D rotary embedding need; the processor
+ * size, which is all a learned position table or a 2-D rotary embedding needs. The processor
  * produces those too, so the core stages them without knowing what they are for.
  */
 #pragma once
@@ -39,7 +39,7 @@ namespace mm {
 
 enum class Kind { Image, Video, Audio };
 
-/* THE PROCESSOR FAMILY, from the container's vision_config.model_type. The two differ in how a
+/* The processor family, from the container's vision_config.model_type. Families differ in how a
  * picture is sized, what a patch value is, and how a video is sampled and spelled in the prompt;
  * the Item they produce and everything after it is shared.
  *
@@ -61,16 +61,16 @@ enum class Family { QwenVL, Gemma4, Lfm2 };
 struct VisionConfig {
     Family  family = Family::QwenVL;
     int32_t patch = 0, temporal = 0, merge = 0;
-    /* Gemma4: soft tokens (output rows) an image, and a video frame, may take. One of 70, 140,
-     * 280, 560, 1120 -- the budgets the model was trained at. */
+    /* Gemma4: soft tokens (output rows) an image and a video frame may take. One of 70, 140,
+     * 280, 560, 1120, the budgets the model was trained at. */
     int32_t image_soft_tokens = 0, video_soft_tokens = 0;
     int64_t image_min_pixels = 0, image_max_pixels = 0;
     int64_t video_min_pixels = 0, video_max_pixels = 0;
     double  fps = 2.0;
     int32_t min_frames = 4, max_frames = 768;
-    /* The per-frame ceiling on a video's resolution, in output rows: a clip that samples few
-     * frames does not spend the whole video budget on near-native frames, so the cost of a video
-     * grows with its length (the reference processor's per-frame cap). 0 turns the cap off. */
+    /* Per-frame ceiling on a video's resolution, in output rows (the reference processor's
+     * per-frame cap). A clip with few frames does not spend the whole video budget on
+     * near-native frames, so a video's cost grows with its length. 0 turns the cap off. */
     int32_t max_frame_rows = 768;
     float   mean[3] = { 0.5f, 0.5f, 0.5f };
     float   stdv[3] = { 0.5f, 0.5f, 0.5f };
@@ -81,62 +81,97 @@ struct VisionConfig {
     double  max_pixels_tolerance = 0.0;
     int64_t max_segment_patches = 0;
 
-    /* THE DEPLOYMENT'S BOUNDS, not the checkpoint's. `max_patches` is the encoder's pass size: an
-     * image is one segment and a segment is never split, so no image may resize past it, and the
-     * image band's ceiling is lowered to fit. `max_source_pixels` bounds what the decoder is asked
-     * to hold before any resize. */
+    /* Deployment bounds, not the checkpoint's. `max_patches` is the encoder's pass size: an image
+     * is one segment and a segment is never split, so the image band's ceiling is lowered to fit
+     * it. `max_source_pixels` bounds what the decoder may hold before any resize. */
     int64_t max_patches = 0;
     int64_t max_source_pixels = (int64_t)1 << 26;
     /* A whole video's patch budget, across all its passes. */
     int64_t max_video_patches = 0;
 
-    /* The pixel bands are non-empty and the frame counts and rate positive. RAD_OK, or
-     * RAD_E_INVAL with the first one that is not in `why`. from_meta runs it on what the
-     * container states, and the engine again after the command line has replaced some of it. */
+    /* Checks the pixel bands are non-empty and the frame counts and rate positive; RAD_E_INVAL
+     * names the first violation in `why`. from_meta runs it on the container's values, and the
+     * engine again after command-line overrides. */
     int check(std::string* why) const;
 
     int64_t patch_dim() const { return 3LL * temporal * patch * patch; }
     int32_t factor() const { return patch * merge; }
 
-    /* Read from the container. Refuses a container that states no vision tower; the defaults for
-     * the processor-only keys are the family's, used only when the container omits them. */
+    /* Read from the container; refuses one with no vision tower. Processor-only keys the
+     * container omits take the family's defaults. */
     int from_meta(const RadModelMeta& m, std::string* why);
 };
 
-/* WHAT AN AUDIO CLIP BECOMES: Gemma 4's feature extractor (Gemma4AudioFeatureExtractor), read
- * from the container's `preprocessor.*` (the checkpoint's preprocessor_config.json) and its
- * audio_config. The samples are mono at `rate`, cut at `max_samples`; `frame_length / 2` zeros go
- * in front; frame i is samples [i * hop, i * hop + frame_length) of that, pre-emphasised when the
- * config says so, times a periodic Hann window, through a `fft`-point real FFT; its magnitudes go
- * through an HTK mel bank (no area normalisation) and log(x + mel_floor), optionally standardised
- * per bin. A frame is real when its last sample is a real one -- the reference's mask -- so a clip
- * of n samples has floor((n - frame_length / 2 - 1) / hop) + 1 real frames and the reference's
- * output keeps ceil(real / merge) rows of it: that many placeholders, between  and .
- * The staged patches are the real frames then zero frames to a whole number of rows -- equal, for
- * every row the reference keeps, to the frames past the end the reference zeroes. */
+/* The audio feature extractor family, from the container's audio_config.model_type. The
+ * families differ in the spectrogram and in how a clip's frames are laid out for the encoder;
+ * the Item they produce is shared.
+ *
+ *   Gemma4    Gemma4AudioFeatureExtractor: a frame_length / 2 zero lead, a periodic Hann window
+ *             through an fft-point FFT, magnitudes through an HTK mel bank, log(x + mel_floor).
+ *             The clip's real frames, then zero frames to whole output rows.
+ *
+ *   Qwen3ASR  Qwen3ASRFeatureExtractor (Whisper's): a clip shorter than `min_samples` is
+ *             zero-padded to it; frames are torch.stft's, centred with a reflected n_fft / 2 at
+ *             each end, a periodic Hann window and power spectra, the last frame dropped, so n
+ *             samples are n / hop frames; a Slaney mel bank with Slaney area normalisation;
+ *             log10(max(x, 1e-10)), floored at the clip's maximum less 8, then (x + 4) / 4.
+ *             The encoder convolves each `chunk` frames (one second) on its own, zero-padded to a
+ *             whole chunk, and keeps `chunk_rows(L)` rows of a chunk of L real frames. A chunk is
+ *             staged as merge * chunk_rows(L) frames: its real frames, the reference's zero
+ *             padding, and, where that exceeds a whole chunk, frames past it that the encoder
+ *             reads as zero. Plane 1 of the coordinates marks those (RadBatch::enc_coord), which
+ *             keeps one chunk's convolution from seeing the next. */
+enum class AudioFamily { Gemma4, Qwen3ASR };
+
+/* Audio features, configured from the container: Gemma 4's framing from `preprocessor.*` (the
+ * checkpoint's preprocessor_config.json), Qwen3-ASR's from `processor.feature_extractor.*`
+ * (processor_config.json), and the encoder's own from audio_config.
+ *
+ * Gemma 4: samples are mono at `rate`, cut at `max_samples`, with `frame_length / 2` zeros in
+ * front. Frame i is samples [i * hop, i * hop + frame_length), pre-emphasised when configured,
+ * times a periodic Hann window, through an `fft`-point real FFT; magnitudes go through an HTK mel
+ * bank (no area normalisation) and log(x + mel_floor), optionally standardised per bin.
+ *
+ * A frame is real when its last sample is (the reference's mask), so an n-sample clip has
+ * floor((n - frame_length / 2 - 1) / hop) + 1 real frames and keeps ceil(real / merge) output
+ * rows: that many placeholders between  and . The staged patches are the real frames
+ * then zero frames up to a whole row, which matches the reference's zeroed frames past the end
+ * for every row it keeps. */
 struct AudioConfig {
+    AudioFamily family = AudioFamily::Gemma4;
     int32_t rate = 0, frame_length = 0, hop = 0, fft = 0, n_mels = 0;
     double  min_freq = 0.0, max_freq = 0.0, mel_floor = 0.0;
     double  preemphasis = 0.0, input_scale = 1.0;
     bool    preemphasis_htk = true;
     std::vector bin_mean, bin_std;      /* empty: no per-bin standardisation */
-    /* The longest clip in samples: Gemma 4's extractor truncates at 480000 (30 s at 16 kHz). */
+    /* The longest clip in samples: Gemma 4's extractor truncates at 480000 (30 s at 16 kHz).
+     * Qwen3-ASR's does not truncate, and its longest clip is what one encoder pass holds. */
     int64_t max_samples = 0;
+    /* Qwen3ASR: a shorter clip is zero-padded to this many samples first (the reference's
+     * min_length); the frames the encoder convolves on their own (2 * n_window). */
+    int64_t min_samples = 0;
+    int32_t chunk = 0;
     int32_t tok_audio = -1, tok_start = -1, tok_end = -1;
 
-    /* THE ENCODER'S: frames an output row, and the most frames a pass carries. */
+    /* The encoder's: frames per output row, and the most frames a pass carries. */
     int32_t merge = 0;
     int64_t max_frames = 0;
 
-    /* Read from the container; refuses one that states no Gemma 4 audio tower. */
+    /* Read from the container; refuses one that states no audio tower this processor knows.
+     * Qwen3-ASR's config names no token around its placeholders, so tok_start and tok_end stay
+     * -1 for the caller to resolve (the architecture plugin spells them; see
+     * RadAudioFormat::audio_open). */
     int from_meta(const RadModelMeta& m, std::string* why);
     /* The real frames of an n-sample clip. */
     int64_t real_frames(int64_t n_samples) const;
+    /* Qwen3ASR: the encoder rows a chunk of `frames` real frames keeps -- three convolutions of
+     * kernel 3, stride 2 and padding 1, so a whole chunk of 100 is 13. */
+    static int64_t chunk_rows(int64_t frames);
 };
 
-/* One media part after processing: its patches, its place in the prompt's token stream, and --
- * once the encoder has run -- its rows. Shared between the request that owns it and the engine
- * thread that encodes it; the engine writes `embd` once and nothing reads it before then. */
+/* One media part after processing: its patches, its place in the prompt's token stream and, once
+ * the encoder has run, its rows. Shared between the owning request and the engine thread that
+ * encodes it; the engine writes `embd` once and nothing reads it before then. */
 struct Item {
     Kind    kind = Kind::Image;
     int32_t grid_t = 0, grid_h = 0, grid_w = 0;   /* in patches; grid_t temporal groups */
@@ -147,14 +182,18 @@ struct Item {
     /* The encoder's output: n_seg segments of seg_rows rows, one segment per temporal group.
      * `rows_w` is a segment's width in output rows, which is where its rotary grid wraps. */
     int32_t n_seg = 0, seg_rows = 0, rows_w = 0, rows_h = 0;
-    /* An audio clip's REAL feature frames; the rest of its `grid_h` are the zero frames that make
-     * it whole output rows. 0 for a picture or a video. */
+    /* An audio clip's real feature frames; the rest of `grid_h` are zero frames padding it to
+     * whole output rows. 0 for a picture or a video. */
     int32_t valid = 0;
+    /* An audio clip staged in chunks (AudioFamily::Qwen3ASR): each chunk but the last is
+     * `chunk_staged` frames, of which the first `chunk_read` take part in the convolution and the
+     * rest read as zero. 0 for a clip staged whole. */
+    int32_t chunk_staged = 0, chunk_read = 0;
 
-    /* SEGMENTS OF THEIR OWN SIZE, when an item's segments differ -- an LFM2-VL picture is its
-     * tiles and a thumbnail -- each `h` x `w` patches from patch `patch0` on. Empty, every segment
-     * is grid_h x grid_w (a picture, a video's temporal groups, an audio clip). The accessors
-     * below are the only way the rest of the engine reads a segment, so both forms look alike. */
+    /* Per-segment sizes, when an item's segments differ (an LFM2-VL picture is its tiles plus a
+     * thumbnail): each is `h` x `w` patches starting at patch `patch0`. Empty means every segment
+     * is grid_h x grid_w. The rest of the engine reads segments only through the accessors below,
+     * so both forms look alike. */
     struct Segment { int32_t h = 0, w = 0; int64_t patch0 = 0; };
     std::vector segments;
     /* The model rotates this item's tokens at their token positions (LFM2-VL's 1-D rotary), not
@@ -175,21 +214,21 @@ struct Item {
     }
     int64_t n_rows() const { return row_at(n_seg); }
 
-    /* THE TOKENS THAT REPLACE THE MEDIA MARKER, and where in them each segment's run of
-     * placeholders starts. Placeholders are the checkpoint's own pad ids, not an arbitrary one:
-     * an n-gram embedding hashes them like any other id. */
+    /* The tokens that replace the media marker, and where in them each segment's placeholder run
+     * starts. Placeholders are the checkpoint's own pad ids, because an n-gram embedding hashes
+     * them like any other id. */
     std::vector expand;
     std::vector seg_at;
 
-    /* A CONTENT KEY over the patches and the grid. It is taken BEFORE the encoder runs, so a
-     * prefix-cache hit over this item skips the encoder as well as the prefill: the patches are
-     * what the encoder is a function of, and they already reflect every preprocessing choice. */
+    /* Content key over the patches and the grid, taken before the encoder runs, so a prefix-cache
+     * hit over this item skips the encoder as well as the prefill. The patches already reflect
+     * every preprocessing choice, and the encoder is a function of them alone. */
     uint64_t key_hi = 0, key_lo = 0;
 
     /* [n_rows, n_embd] bf16, written by the engine after the encoder pass. */
     std::vector embd;
     bool encoded = false;
-    /* Handed to the engine's encoder queue and not yet encoded -- the scheduler's thread only. */
+    /* Handed to the engine's encoder queue and not yet encoded. Scheduler thread only. */
     bool queued = false;
 
     /* The (row, col, rows, cols) of each patch in its segment, for the encoder: component-major,
@@ -197,16 +236,16 @@ struct Item {
     void coords(int64_t first, int64_t count, int32_t* planes) const;
 };
 
-/* THE ROTARY LAYOUT OF ONE PROMPT: which tokens are media and where each run's grid sits. Built
- * once when the prompt is tokenised; `at` is what the batch builder asks for every row of every
- * pass, so it is a binary search over runs rather than an array the length of the prompt. */
+/* The rotary layout of one prompt: which tokens are media and where each run's grid sits. Built
+ * once when the prompt is tokenised. The batch builder calls `at` for every row of every pass,
+ * so it is a binary search over runs rather than an array the length of the prompt. */
 struct RopeLayout {
     struct Run {
         int32_t tok = 0;        /* first placeholder token of the run */
         int32_t n = 0;          /* its length: rows_h * rows_w */
         int32_t w = 0;          /* its width in rows */
         int32_t base = 0;       /* the rotary position of its first token */
-        int32_t shift = 0;      /* rotary minus token index for the text AFTER the run */
+        int32_t shift = 0;      /* rotary minus token index for the text after the run */
         int32_t item = 0;       /* which of PromptMedia::items the run belongs to */
         int32_t row0 = 0;       /* the item's encoder row that its first token takes */
         bool    flat = false;   /* Item::rope_1d: the run's tokens rotate at their positions */
@@ -215,8 +254,8 @@ struct RopeLayout {
 
     bool empty() const { return runs.empty(); }
 
-    /* The last run starting at or before token i, or null. Inline and dependency-free, because
-     * the batch builder asks it for every row of every pass. */
+    /* The last run starting at or before token i, or null. Inline because the batch builder
+     * calls it for every row of every pass. */
     const Run* last_at(int64_t i) const {
         size_t lo = 0, hi = runs.size();
         while (lo < hi) {
@@ -238,11 +277,6 @@ struct RopeLayout {
         }
         out[0] = out[1] = out[2] = (int32_t)(i + r->shift);
     }
-    /* Rotary minus index for text at or after token i -- the one number a decode row needs. */
-    int32_t shift_at(int64_t i) const {
-        const Run* r = last_at(i);
-        return r ? r->shift : 0;
-    }
     /* The run holding token i, or null when i is text. */
     const Run* run_at(int64_t i) const {
         const Run* r = last_at(i);
@@ -250,7 +284,7 @@ struct RopeLayout {
     }
 };
 
-/* THE MEDIA A PROMPT CARRIES, in prompt order, with where each item's expansion begins. */
+/* One media item of a prompt and where its expansion begins. */
 struct Placed {
     std::shared_ptr item;
     int32_t               tok = 0;   /* index of item->expand[0] in the prompt */
@@ -266,30 +300,31 @@ struct PromptMedia {
 class Processor {
 public:
     /* `encode_text` tokenises the timestamp text between a video's groups: plain text, no
-     * special tokens added and none parsed. `token_id` is the id of the vocabulary entry spelled
-     * exactly so, or -1: how a family whose markers the config does not number (LFM2-VL's tile
-     * and thumbnail markers) finds them. */
+     * special tokens added or parsed. `token_id` returns the id of the vocabulary entry spelled
+     * exactly so, or -1; it finds markers the config does not number (LFM2-VL's tile and
+     * thumbnail markers). */
     int init(const VisionConfig& cfg, std::function(const std::string&)> encode_text,
              std::function token_id = {});
     const VisionConfig& config() const { return cfg_; }
 
     /* `image_tokens` is a Gemma 4 soft-token budget for this image (0: the configured one); a
      * processor that sizes images by pixels refuses a non-zero one. `max_pixels`, when set, first
-     * scales a larger picture down to that area (PIL's bicubic), as a caller's own pipeline may. */
+     * scales a larger picture down to that area with PIL's bicubic. */
     int image(const uint8_t* bytes, size_t n, int32_t image_tokens, std::shared_ptr* out,
               std::string* why, int64_t max_pixels = 0) const;
     int video(const uint8_t* bytes, size_t n, std::shared_ptr* out, std::string* why) const;
 
-    /* The pieces, exposed for the test suite: an already-decoded picture or frame list. */
+    /* From an already-decoded picture or frame list; for tests. */
     int image_from(const Frame& f, std::shared_ptr* out, std::string* why) const;
     int video_from(const Video& v, std::shared_ptr* out, std::string* why) const;
 
-    /* AUDIO, when the program declared an audio encoder: `merge` and `max_frames` are its. */
-    int  init_audio(const AudioConfig& cfg);
+    /* Audio, when the program declares an audio encoder; `merge` and `max_frames` are the
+     * encoder's. */
+    int  init_audio(const AudioConfig& cfg, std::string* why = nullptr);
     bool has_audio() const { return audio_on_; }
     const AudioConfig& audio_config() const { return acfg_; }
     int audio(const uint8_t* bytes, size_t n, std::shared_ptr* out, std::string* why) const;
-    /* ...and from samples already decoded (mono at the configured rate), for the test suite. */
+    /* From samples already decoded (mono at the configured rate); for tests. */
     int audio_from(const std::vector& samples, std::shared_ptr* out,
                    std::string* why) const;
 
@@ -305,11 +340,15 @@ private:
     VisionConfig cfg_{};
     AudioConfig  acfg_{};
     bool         audio_on_ = false;
+    int audio_qwen3asr(const std::vector& samples, std::shared_ptr* out,
+                       std::string* why) const;
+
     std::vector  hann_;          /* the window, float32 as the reference stores it */
     std::vector mel_;           /* [n_mels, fft/2 + 1]: filter b's weight on bin k */
     std::vector mel_lo_, mel_hi_;  /* filter b's nonzero bins, [lo, hi) */
     std::vector tw_re_, tw_im_;     /* exp(-2 pi i k / fft), k < fft/2 */
     std::vector brev_;             /* the FFT's bit-reversal permutation */
+    std::vector radix_;            /* a non-power-of-two FFT's factors, smallest first */
     std::function(const std::string&)> encode_text_;
 };
 
diff --git a/core/mm/resample.cpp b/core/mm/resample.cpp
new file mode 100644
index 00000000..c06b3f85
--- /dev/null
+++ b/core/mm/resample.cpp
@@ -0,0 +1,131 @@
+#include "mm/resample.h"
+
+#include 
+#include 
+#include 
+#include 
+
+namespace rad {
+namespace mm {
+
+namespace {
+
+const int32_t kRates[] = { 8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000 };
+/* The sinc's zero crossings either side of an output sample, at the lower of the two rates. */
+constexpr double kLobes = 16.0;
+/* The cut-off as a fraction of the lower Nyquist frequency, and the Kaiser window's shape: about
+ * 80 dB down past the transition band, which leaves nothing a 16-bit stream could show. */
+constexpr double kRolloff = 0.92;
+constexpr double kBeta = 8.0;
+/* Input the output has moved past is dropped once there is this much of it, not sample by
+ * sample: dropping is a move of everything after it. */
+constexpr int64_t kDropAt = 8192;
+
+double bessel_i0(double x) {
+    double sum = 1.0, term = 1.0;
+    for (int k = 1; k < 64; ++k) {
+        term *= (x / (2.0 * k)) * (x / (2.0 * k));
+        sum += term;
+        if (term < 1e-15 * sum) break;
+    }
+    return sum;
+}
+
+}  /* namespace */
+
+bool Resampler::takes(int32_t rate) {
+    return std::find(std::begin(kRates), std::end(kRates), rate) != std::end(kRates);
+}
+
+std::string Resampler::rates() {
+    std::string s;
+    for (int32_t r : kRates) {
+        if (!s.empty()) s += ", ";
+        s += std::to_string(r);
+    }
+    return s;
+}
+
+Resampler::Resampler(int32_t from, int32_t to) {
+    const int32_t g = std::gcd(from, to);
+    up_ = to / g;
+    down_ = from / g;
+    if (up_ != down_) {
+        /* The cut-off in cycles an input sample, and the taps' reach: kLobes zero crossings of a
+         * sinc that narrow, which is wider in input samples the further the rate comes down. */
+        const double fc = 0.5 * kRolloff * std::min(1.0, (double)up_ / down_);
+        half_ = (int32_t)std::ceil(kLobes / (2.0 * fc));
+        taps_.assign((size_t)up_ * 2 * half_, 0.0f);
+        const double i0b = bessel_i0(kBeta);
+        for (int32_t p = 0; p < up_; ++p) {
+            /* Phase p is an output sample p/up_ of an input sample past the input it is centred
+             * on; tap k reads the input half_ - 1 - k before that one. */
+            const double frac = (double)p / up_;
+            float* h = &taps_[(size_t)p * 2 * half_];
+            double sum = 0.0;
+            for (int32_t k = 0; k < 2 * half_; ++k) {
+                const double t = (double)(k - half_ + 1) - frac;
+                const double x = 2.0 * fc * t;
+                const double sinc = x == 0.0 ? 1.0 : std::sin(M_PI * x) / (M_PI * x);
+                const double r = t / half_;
+                const double w = std::fabs(r) >= 1.0
+                                     ? 0.0 : bessel_i0(kBeta * std::sqrt(1.0 - r * r)) / i0b;
+                h[k] = (float)(sinc * w);
+                sum += h[k];
+            }
+            /* Unity gain at DC, phase by phase, so a constant comes out the constant it went in. */
+            for (int32_t k = 0; k < 2 * half_; ++k) h[k] = (float)(h[k] / sum);
+        }
+    }
+    reset();
+}
+
+void Resampler::reset() {
+    /* The history before the first sample is silence. */
+    in_.assign((size_t)std::max(half_ - 1, 0), 0.0f);
+    base_ = -(int64_t)in_.size();
+    next_ = 0;
+    n_in_ = 0;
+}
+
+void Resampler::push(const float* in, size_t n, std::vector* out) {
+    if (up_ == down_) {
+        out->insert(out->end(), in, in + n);
+        return;
+    }
+    in_.insert(in_.end(), in, in + n);
+    n_in_ += (int64_t)n;
+    for (;;) {
+        const int64_t pos = next_ * down_;
+        const int64_t c = pos / up_;
+        if (c + half_ >= n_in_) break;
+        const float* h = &taps_[(size_t)(pos % up_) * 2 * half_];
+        const float* x = &in_[(size_t)(c - half_ + 1 - base_)];
+        float acc = 0.0f;
+        for (int32_t k = 0; k < 2 * half_; ++k) acc += x[k] * h[k];
+        out->push_back(acc);
+        ++next_;
+    }
+    const int64_t keep = (next_ * down_) / up_ - half_ + 1;
+    if (keep - base_ >= kDropAt) {
+        in_.erase(in_.begin(), in_.begin() + (std::ptrdiff_t)(keep - base_));
+        base_ = keep;
+    }
+}
+
+void Resampler::flush(std::vector* out) {
+    if (up_ != down_) {
+        /* Every output sample the input spans, the last ones read against silence. */
+        const int64_t total = (n_in_ * up_ + down_ - 1) / down_;
+        const std::vector silence((size_t)(2 * half_ + down_), 0.0f);
+        std::vector rest;
+        push(silence.data(), silence.size(), &rest);
+        const int64_t want = total - (next_ - (int64_t)rest.size());
+        rest.resize((size_t)std::max(0, std::min(want, (int64_t)rest.size())));
+        out->insert(out->end(), rest.begin(), rest.end());
+    }
+    reset();
+}
+
+}  /* namespace mm */
+}  /* namespace rad */
diff --git a/core/mm/resample.h b/core/mm/resample.h
new file mode 100644
index 00000000..811ad05f
--- /dev/null
+++ b/core/mm/resample.h
@@ -0,0 +1,54 @@
+/* resample.h -- a streaming resampler for mono float audio, between the rates a client sends
+ * and the rate an audio encoder takes.
+ *
+ * A file is resampled by libswresample as it is decoded (media.cpp). A stream arrives a few
+ * milliseconds at a time over a socket, and each piece must continue the last with no edge at the
+ * seam: this keeps the input it still needs between calls, so a stream pushed in pieces comes out
+ * sample for sample as it would if pushed whole.
+ *
+ * The filter is a Kaiser-windowed sinc evaluated at each output sample's position in the input: a
+ * polyphase low-pass with one phase per distinct position, the rate step being a ratio of
+ * integers. The cut-off sits under the lower of the two Nyquist frequencies, so a 24 kHz stream
+ * taken to 16 kHz loses 8-12 kHz rather than folding it onto the band a speech model reads. Only
+ * the common rates are taken: the phase table grows with the ratio's terms, and an arbitrary rate
+ * can make it megabytes. */
+#pragma once
+#include 
+#include 
+#include 
+
+namespace rad {
+namespace mm {
+
+class Resampler {
+public:
+    /* Whether a stream at `rate` can be taken to a common rate: 8, 11.025, 12, 16, 22.05, 24,
+     * 32, 44.1 or 48 kHz. */
+    static bool takes(int32_t rate);
+    /* The rates takes() accepts, for a refusal to name. */
+    static std::string rates();
+
+    /* From `from` Hz to `to` Hz, both rates takes() accepts. Equal rates pass samples through. */
+    Resampler(int32_t from, int32_t to);
+
+    /* Appends to `out` every output sample the input so far determines; the rest waits for more
+     * input or flush(). */
+    void push(const float* in, size_t n, std::vector* out);
+    /* Appends the remaining output, as if the input went on in silence, and starts afresh. */
+    void flush(std::vector* out);
+
+private:
+    void reset();
+
+    int32_t up_ = 1, down_ = 1;   /* out/in as a ratio in lowest terms */
+    int32_t half_ = 0;            /* taps either side of an output sample, in input samples */
+    std::vector taps_;     /* up_ phases of 2 * half_ taps */
+    std::vector in_;       /* input from index base_ on */
+    int64_t base_ = 0;            /* the input index of in_[0]; negative while the history is the
+                                   * silence before the stream */
+    int64_t next_ = 0;            /* the next output sample's index */
+    int64_t n_in_ = 0;            /* input samples pushed since the start */
+};
+
+}  /* namespace mm */
+}  /* namespace rad */
diff --git a/core/place/heat.cpp b/core/place/heat.cpp
index dcb296a5..bde21644 100644
--- a/core/place/heat.cpp
+++ b/core/place/heat.cpp
@@ -1,4 +1,4 @@
-/* heat.cpp -- the heat engine's mechanics. See heat.h for why any of it is shaped this way. */
+/* heat.cpp -- the heat engine's mechanics. See heat.h for the policy and data layout. */
 #include "heat.h"
 
 #include 
@@ -26,7 +26,7 @@ int HeatEngine::init(const Plan& plan, const HeatParams& params) {
     bytes_.assign(n, 0);
     ever_.assign(n, 0u);
 
-    /* The movable units' slab classes, as dense indices -- see heat.h's `cls_`. */
+    /* The movable units' slab classes as dense indices (heat.h: `cls_`). */
     cls_.assign(n, -1);
     {
         std::vector dense;
@@ -46,13 +46,12 @@ int HeatEngine::init(const Plan& plan, const HeatParams& params) {
 
     n_layer_ = 0;
     for (const MoveUnit& mu : plan.units) n_layer_ = std::max(n_layer_, mu.layer + 1);
-    if (n_layer_ < 0) n_layer_ = 0;
     res_count_.assign((size_t)n_layer_, 0);
 
-    /* Each layer's units by expert id, and each slot's other movable units in plan order: a
-     * layer's, then (slot n_layer_) those with no layer. Two units naming one (layer, expert)
-     * leave the later one indexed by the expert -- the one a histogram credits -- and the
-     * earlier, if it can move, among the layer's others. */
+    /* Each layer's units by expert id, and each slot's other movable units in plan order (slot
+     * n_layer_ holds those with no layer). If two units name one (layer, expert), the later one
+     * is indexed by the expert (and credited by histograms); the earlier, if movable, goes among
+     * the layer's others. */
     std::vector> by_expert((size_t)n_layer_);
     std::vector> other((size_t)n_layer_ + 1);
     int64_t movable = 0;
@@ -124,13 +123,12 @@ int HeatEngine::init(const Plan& plan, const HeatParams& params) {
     end_n_cold_.assign((size_t)n_layer_ + 1, 0);
     end_ok_.assign((size_t)n_layer_ + 1, 0);
 
-    /* Two ways to be off, and they are different facts worth different lines. A static plan is a
-     * mode the operator asked for; a plan with nothing movable is a model that does not need this
-     * engine -- the all-in-VRAM degenerate case, where the mover never runs either. */
+    /* Two distinct ways to be off: a static plan (an operator choice), or nothing movable (every
+     * weight fits in VRAM; the mover never runs either). */
     if (!plan.dynamic) {
         enabled_ = false;
-        RAD_INFO("placement is static (--deterministic): the heat engine will not run, so "
-                 "residency -- and therefore the summation order -- is fixed for the run");
+        RAD_INFO("placement is static (--deterministic): residency and summation order are "
+                 "fixed for the run");
         return RAD_OK;
     }
     if (movable == 0) {
@@ -152,7 +150,7 @@ int HeatEngine::init(const Plan& plan, const HeatParams& params) {
 void HeatEngine::observe_ids(int32_t layer, const int32_t* experts, const int32_t* counts,
                              int32_t n) {
     if (!enabled_ || layer < 0 || layer >= n_layer_) return;
-    /* The histogram these name, dense, so both entry points are the one pass. */
+    /* Densify so both entry points share observe(). */
     const int32_t n_ex = n_ex_[(size_t)layer];
     std::vector dense((size_t)n_ex, 0);
     for (int32_t i = 0; i < n; ++i) {
@@ -162,53 +160,43 @@ void HeatEngine::observe_ids(int32_t layer, const int32_t* experts, const int32_
     observe(layer, dense.data(), n_ex, 1.0f);
 }
 
-/* DECAY EVERY POSITION, THEN CREDIT THE ROUTED ONES. Decay first, then credit: the other order
- * gives THIS dispatch's experts a decayed count, which makes min_gain = 1.0 mean 1/decay
- * activations rather than one -- the kind of off-by-a-constant that only ever shows up as a
- * threshold that does not do what it says.
+/* Decay every position, then credit the routed ones. Decay comes first so this dispatch's
+ * credit is not decayed; otherwise min_gain = 1.0 would mean 1/decay activations.
  *
- * THE DECAY IS THE ONLY WORK EVERY POSITION NEEDS, so it is the only dense pass: one multiply a
- * float, vector code at any instruction set. A dispatch routes to a few dozen of a layer's
- * hundreds of experts, and everything else -- the credit, the pricing, the layer's ends -- is a
- * property of those, so it is done for those alone. `h * d` and then `+ c * w` round exactly as
- * the one expression `h * d + c * w` does, so the heats are the same bits either way.
+ * The decay is the only dense pass (one vector multiply per float). A dispatch routes to a few
+ * dozen of a layer's hundreds of experts, so crediting, pricing and the layer's ends touch only
+ * those. `h * d` then `+ c * w` rounds exactly as `h * d + c * w`, so heats are bit-identical.
  *
- * A ROUTED EXPERT IS PRICED HERE TOO. A unit not in VRAM is not a stall -- the GEMM reads it
- * where it lies -- but for every tier above VRAM that read crosses the link, and those are the
- * bytes the mover exists to stop paying. Pricing them on the pass that credits the heat puts the
- * hit rate and the streamed bytes beside the policy's decisions.
+ * Routed experts are priced here too: a unit off the device is read in place across the link,
+ * and those are the bytes the mover exists to save. Pricing on the crediting pass puts hit rate
+ * and streamed bytes beside the policy's decisions.
  *
- * THE LAYER'S ENDS FOLLOW FROM THE CREDITED EXPERTS WHEN THEY WERE VALID. A positive scale keeps
- * every order, and rounding is monotone, so the hottest unit off the device decays to exactly
- * `hot * d` and nothing uncredited passes it: the new hot end is that or a credited unit, whichever
- * is larger. The coldest units on the device decay to exactly `cold * d` likewise, and a credit
- * only raises a unit, so the cold end stands while any unit is left at it. The ends count the
- * units AT the cold value -- equal heats decay to equal heats -- because the common cold end is
- * a crowd: every resident unit no token has routed to yet sits at exactly zero. Only when the
- * last of them is credited is the next coldest unknown here, and the layer is rebuilt from its
- * positions. A tie decay creates is not counted, which can only rebuild a layer that did not need
- * it. */
+ * The layer's ends are updated from the credited experts when they were valid. Decay by a positive
+ * scale with monotone rounding keeps every order, so the hot end becomes `hot * d` or a credited
+ * unit, whichever is larger; the cold end becomes `cold * d` and stands while any unit remains at
+ * it, since credit only raises. The cold end counts units at exactly that value, because it is
+ * usually a crowd (every resident unit not routed to lately sits at zero). When the last is
+ * credited the layer is rebuilt from its positions. Ties created by decay are not counted, which
+ * can only cause an unneeded rebuild. */
 void HeatEngine::observe(int32_t layer, const int32_t* counts, int32_t n_expert, float weight) {
     if (!enabled_ || layer < 0 || layer >= n_layer_ || !counts) return;
     if (!(weight > 0.0f)) weight = 1.0f;
-    /* Passes this histogram stands for -- see observe()'s contract. At least one, so a caller
-     * that does not set it still prices its reads. */
+    /* Routing passes this histogram stands for (see heat.h: observe); at least one. */
     const uint64_t passes = weight >= 1.0f ? (uint64_t)(weight + 0.5f) : 1u;
 
     const size_t l = (size_t)layer;
     const int32_t lo = slot_lo_[l], len = slot_lo_[l + 1] - lo;
-    /* Past the histogram's last expert, and past the layer's, a position is credited nothing. */
+    /* Positions past the histogram's or the layer's last expert get no credit. */
     const int32_t n = std::max(0, std::min(n_expert, n_ex_[l]));
     const float d = params_.decay;
 
-    /* THE HISTOGRAM ARRIVES BY DMA, so none of it is in the cache: every line is a miss, and a
-     * scan that meets them one at a time pays one latency a line. Asked for all at once they
-     * overlap each other and the decay below -- and a caller sweeping layers asks earlier still
-     * (prefetch()), which makes this a no-op. */
+    /* The histogram arrives by DMA and is not in cache. Prefetching every line at once overlaps
+     * the misses with each other and with the decay; a caller sweeping layers may prefetch
+     * earlier still. */
     prefetch(counts, n);
 
-    /* The credit cap (HeatParams::credit_cap) scales the whole histogram, so its experts keep
-     * their order. The pricing below counts every pass whatever the credit is. */
+    /* The credit cap (HeatParams::credit_cap) scales the whole histogram, preserving order.
+     * Pricing ignores the cap. */
     int64_t total = 0;
     for (int32_t j = 0; j < n; ++j) total += counts[j] > 0 ? counts[j] : 0;
     const float cap = params_.credit_cap;
@@ -235,9 +223,8 @@ void HeatEngine::observe(int32_t layer, const int32_t* counts, int32_t n_expert,
         if (rank_as_[q] == 1) hot = std::max(hot, x);
         else if (rank_as_[q] == 2 && was <= cold && --n_cold <= 0) ends = false;
     };
-    /* A dispatch routes to a few dozen of the layer's experts, so the credited ones are found a
-     * block at a time -- a mask of the positive counts is vector code -- and only its set bits are
-     * visited, in increasing order as a scan would meet them. */
+    /* Find credited experts a block at a time via a vectorisable mask of positive counts, then
+     * visit only the set bits, in increasing order. */
     int32_t j0 = 0;
     for (; j0 + kLanes <= n; j0 += kLanes) {
         uint32_t m = 0;
@@ -325,15 +312,13 @@ void HeatEngine::abandon(const Swap& s) {
     set_busy(s.demote, false);
 }
 
-/* THE ONE-PAIR PICK, kept as the definition of the ranking: the hottest movable unit off the device
- * against the coldest one on it, ties broken toward the layer that most needs the slot, and the
- * first unit in index order on a full tie. step() proposes exactly the pairs repeated calls to
- * this would, from one pass. */
+/* The one-pair pick, kept as the reference definition of the ranking: the hottest movable unit
+ * off the device against the coldest on it, ties broken toward the layer that most needs the
+ * slot, then by lowest index. step() proposes exactly the pairs repeated calls to this would. */
 bool HeatEngine::pick(Swap* out) const {
     if (!enabled_ || !warm() || !out) return false;
 
-    /* Each class's hottest unit off the device and coldest one on it: a swap stays in its class
-     * (heat.h's `cls_`). */
+    /* Per class, since a swap stays in its class (heat.h: `cls_`). */
     std::vector hot((size_t)n_cls_, -1), cold((size_t)n_cls_, -1);
     std::vector   hot_h((size_t)n_cls_, 0.0f), cold_h((size_t)n_cls_, 0.0f);
     std::vector hot_res((size_t)n_cls_, 0), cold_res((size_t)n_cls_, 0);
@@ -345,32 +330,27 @@ bool HeatEngine::pick(Swap* out) const {
         const int32_t rc = l >= 0 ? res_count_[(size_t)l] : 0;
         const float h = heat_[(size_t)pos_[i]];
         if (tier_[i] == Tier::VRAM) {
-            /* Colder wins; on an exact tie take from the layer holding the MOST resident units,
-             * which is the layer that can spare it. */
+            /* Colder wins; on a tie, take from the layer holding the most resident units. */
             if (cold[c] < 0 || h < cold_h[c] || (h == cold_h[c] && rc > cold_res[c])) {
                 cold[c] = (int32_t)i; cold_h[c] = h; cold_res[c] = rc;
             }
         } else {
-            /* Hotter wins; on an exact tie the layer with the FEWEST resident units wins, because
-             * that is the layer whose tokens are missing most often. Both halves of this are the
-             * same statement about where capacity should sit.
+            /* Hotter wins; on a tie, the layer with the fewest resident units, whose tokens miss
+             * most often.
              *
-             * Tier::SSD is a candidate here and Tier::HostPinned is too, deliberately: this
-             * engine promotes UP from wherever the unit is, and the mover knows which source that
-             * means. What it never does is push a unit DOWN to the file tier -- banishing
-             * something to disk is a bet that it will not be needed, paid at a full read every
-             * time the bet is wrong, and a frequency counter has no forward-looking confidence to
-             * justify one. Demotion targets the host pool, and only the planner assigns SSD. */
+             * Both Tier::SSD and Tier::HostPinned units are candidates: promotion is from wherever
+             * the unit is, and the mover knows the source. Demotion never targets the file tier,
+             * since a frequency counter cannot justify a bet that a unit will not be needed; it
+             * targets the host pool, and only the planner assigns SSD. */
             if (hot[c] < 0 || h > hot_h[c] || (h == hot_h[c] && rc < hot_res[c])) {
                 hot[c] = (int32_t)i; hot_h[c] = h; hot_res[c] = rc;
             }
         }
     }
 
-    /* BOTH guards, and they answer different failures. The ratio stops a swap that trades one
-     * warm unit for another; the additive floor stops the degenerate case where the victim's heat
-     * is zero, which every ratio passes trivially and which describes most of the resident set
-     * right after warmup. Of the classes whose pair passes, the one with the hotter candidate. */
+    /* Both guards: the ratio stops trading one warm unit for another, and the additive floor
+     * stops swaps against a zero-heat victim, which any ratio passes. Of the classes whose pair
+     * passes, take the one with the hotter candidate. */
     int32_t best = -1;
     for (int32_t c = 0; c < n_cls_; ++c) {
         if (hot[(size_t)c] < 0 || cold[(size_t)c] < 0) continue;
@@ -388,12 +368,10 @@ bool HeatEngine::pick(Swap* out) const {
     return true;
 }
 
-/* THE WHOLE STEP'S PROPOSALS FROM ONE PASS. Marking a pair busy changes neither a unit's heat nor
- * any layer's resident count, so the m-th pair repeated pick() calls would return is simply the
- * m-th entry at each end of the same ranking. One pass keeps the `moves_per_step` best of each
- * end; the proposals, and the counters that say why the list stopped, are the ones the repeated
- * picks produce. This runs once a step on the thread that issues the next one, and the budget is
- * dozens of swaps, so a scan per proposed move would be most of its cost. */
+/* A whole step's proposals from one pass. Marking a pair busy changes no heat or resident
+ * count, so the m-th pair repeated pick() calls would return is the m-th entry at each end of the
+ * same ranking. One pass keeps the `moves_per_step` best of each end and yields the same
+ * proposals and stop counters as repeated picks, without a scan per move on the issuing thread. */
 namespace {
 using Ranked = HeatRanked;
 /* Hotter first, then the layer with fewer residents, then the lower index. */
@@ -425,10 +403,9 @@ int HeatEngine::step(std::vector* out) {
     const int k = params_.moves_per_step;
     if (k <= 0) return RAD_OK;
 
-    /* THE BEST PAIR FROM THE LAYERS' ENDS FIRST. If it fails the guard every pair does -- the
-     * ranking only gets colder at one end and warmer at the other -- and the dispatch proposes
-     * nothing, which is the verdict the full ranking below reaches, from one entry a layer. The
-     * ends also count the candidates at each end, which is all the stop reasons below need. */
+    /* Test the best pair from the layers' ends first. If it fails the guard, every pair does,
+     * and the dispatch proposes nothing after one entry per layer. The ends' counts also give the
+     * stop reasons. */
     int64_t n_off = 0, n_on = 0;
     float bar = 0.0f;
     {
@@ -448,31 +425,21 @@ int HeatEngine::step(std::vector* out) {
         bar = cold_h * params_.hysteresis + params_.min_gain;
     }
 
-    /* THE RANKING, over every movable position. A unit can only enter a full list by reaching
-     * its last entry's heat, so each block of positions is first screened against the two lists'
-     * last heats -- one compare a position, over contiguous floats -- and only what passes the
-     * screen meets the exact comparison, ties and all. The screen passes a tie, so it never drops
-     * a unit the comparison would keep; and the lists are a strict order's best k, so meeting the
-     * units in position order rather than unit order ends in the same lists.
+    /* The ranking over every movable position. Each kLanes block is screened against the two
+     * lists' last heats (one vector compare per position); only what passes meets the exact
+     * comparison. The screen passes ties, so it never drops a unit the comparison would keep, and
+     * since the lists hold a strict order's best k, visiting in position order gives the same
+     * lists. The hot end is also screened against the guard bar: a unit below it cannot be
+     * proposed against any victim.
      *
-     * The hot end is screened against the guard as well. A unit colder than the coldest resident
-     * unit's bar fails the guard against every victim the cold list can hold, so it cannot be
-     * proposed, and the list it is kept out of only ever ends at the pair that fails. A layer's
-     * run is a whole number of kLanes blocks, so every block has the same trip count and the
-     * screen is vector code.
+     * Each layer is first screened by its ends. Most resident units sit exactly at the cold end
+     * (zero), which the position screen passes, so without this nearly every resident unit would
+     * reach the exact comparison. A layer whose hot end is below the hot bar and whose cold end
+     * cannot beat the cold list's last entry is skipped; on a heat tie the comparison falls to the
+     * layer's shared resident count, then to the unit index, bounded by the layer's lowest.
      *
-     * A WHOLE LAYER IS SCREENED FIRST, BY ITS ENDS. Most resident units sit at exactly the cold
-     * end's heat -- zero, for every one no token has routed to lately -- and the position screen
-     * passes a tie, so it would send nearly every resident unit to the exact comparison only for
-     * the tie break to refuse it. The ends are that layer's hottest candidate off the device and
-     * coldest on it, so a layer whose hot end is below the hot list's bar and whose cold end
-     * cannot beat the cold list's last entry holds no unit either list would keep. On a tie the
-     * comparison falls to the layer's resident count, which every unit of the layer shares, and
-     * then to the unit index, which the layer's lowest bounds. */
-    /* ONE PAIR OF LISTS A CLASS, because a swap stays inside its class (heat.h's `cls_`). The
-     * screens below take the loosest of the classes' thresholds, so a unit any class's list would
-     * keep still reaches the exact comparison; with one class they are that class's thresholds
-     * and the screen is exact. */
+     * One pair of lists per class (heat.h: `cls_`). The screens use the loosest threshold across
+     * classes, so they stay conservative; with one class they are exact. */
     const int nc = n_cls_;
     rank_hot_.resize((size_t)(k * nc));
     rank_cold_.resize((size_t)(k * nc));
@@ -484,8 +451,8 @@ int HeatEngine::step(std::vector* out) {
     const int64_t n_pool = n_off, n_vram = n_on;
     const float*   hp = heat_.data();
     const uint8_t* ra = rank_as_.data();
-    /* A hot unit reaches a list at the lowest last entry of a full list, and none below the guard;
-     * a cold one at the highest last entry, and any heat while some list is not full. */
+    /* Hot threshold: the lowest last entry of any full list, never below the guard. Cold
+     * threshold: the highest last entry, or any heat while some list is not full. */
     auto hot_bar = [&]() {
         float t = INFINITY;
         for (int c = 0; c < nc; ++c) t = std::min(t, n_hot[c] == k ? hot[c * k + k - 1].h : -INFINITY);
@@ -537,10 +504,9 @@ int HeatEngine::step(std::vector* out) {
         }
     }
 
-    /* The proposals: each class's m-th hottest against its m-th coldest, for as long as that
-     * passes the guard -- the ranking only gets colder at one end and warmer at the other, so the
-     * first pair that fails ends the class -- and at most `k` of them a class, taken across the
-     * classes hottest first, which is the order repeated pick() calls would return them in. */
+    /* Each class's m-th hottest against its m-th coldest while that passes the guard (the first
+     * failure ends the class), at most `k` per class, taken across classes hottest first: the
+     * order repeated pick() calls would return. */
     int32_t* m_of = m_of_.data();
     for (int c = 0; c < nc; ++c) m_of[c] = 0;
     int made = 0;
@@ -563,7 +529,7 @@ int HeatEngine::step(std::vector* out) {
         s.promote = hot[best * k + m_of[best]].unit;
         s.demote = cold[best * k + m_of[best]].unit;
         ++m_of[best];
-        /* Marked busy on the way out: the caller owns the pair until it publishes or abandons. */
+        /* The caller owns the pair until it publishes or abandons it. */
         set_busy(s.promote, true);
         set_busy(s.demote, true);
         out->push_back(s);
@@ -571,11 +537,8 @@ int HeatEngine::step(std::vector* out) {
         ++made;
     }
     if (short_of_budget) {
-        /* Two ways to propose nothing more and they are different diagnoses. `refused` is the
-         * guard declining -- the healthy steady state. `no_candidate` is one end of the ranking
-         * being empty, which means either everything movable is resident or nothing is, and is a
-         * budget question rather than a policy one. The pairs already proposed are busy by now,
-         * so they are not counted at either end. */
+        /* See HeatStats for `refused` vs `no_candidate`. Pairs already proposed are busy and not
+         * counted at either end. */
         if (n_pool - made > 0 && n_vram - made > 0) ++stats_.refused; else ++stats_.no_candidate;
     }
     return RAD_OK;
@@ -595,20 +558,15 @@ std::string HeatEngine::report() const {
                         (unsigned long long)stats_.demotions);
     s += fmt("  %llu dispatches declined on hysteresis, %llu found no candidate at one end\n",
              (unsigned long long)stats_.refused, (unsigned long long)stats_.no_candidate);
-    /* The one line that says whether the traffic above was worth paying. A readmit is a unit this
-     * engine demoted and then fetched back: both directions of the link spent to return to where
-     * it started, on the link the zero-copy tier needs. High here means the guards are too
-     * loose -- and note that TIGHTENING min_gain to fix it costs more bytes, not fewer. */
+    /* A readmit is a unit demoted and then fetched back: link traffic both ways for nothing. A high
+     * rate means the guards are too loose, though raising min_gain costs more bytes (heat.h). */
     s += fmt("  %llu distinct units promoted, %llu readmits (%.0f%% of promotions were of "
              "something already demoted)\n",
              (unsigned long long)stats_.distinct_promoted, (unsigned long long)stats_.readmits,
              stats_.promotions ? 100.0 * (double)stats_.readmits / (double)stats_.promotions : 0.0);
 
-    /* The histogram this engine exists for. A global profile ranking leaves the per-layer
-     * resident count wherever it happens to fall; a layer starved of slots misses on nearly every
-     * token however good the ranking inside it is, which is how a hit rate lands below what
-     * choosing at random would give. Whether the engine repaired that is a question about this
-     * DISTRIBUTION, not about the mean. */
+    /* The per-layer resident distribution: a layer starved of slots misses on nearly every token
+     * however good its internal ranking, so the spread matters more than the mean. */
     if (!res_count_.empty()) {
         int32_t lo = res_count_[0], hi = res_count_[0];
         double sum = 0;
@@ -618,10 +576,7 @@ std::string HeatEngine::report() const {
         for (int32_t v : res_count_) var += (v - mean) * (v - mean);
         s += fmt("  resident units a layer: min %d max %d mean %.1f sd %.1f\n", (int)lo, (int)hi,
                  mean, std::sqrt(var / (double)res_count_.size()));
-        /* AND WHICH LAYERS, because min/max/sd cannot be joined to anything. A kernel trace can
-         * say which layers run longer than their neighbours; only this line can say whether those
-         * are the starved ones, and without it the two measurements sit in different files saying
-         * nothing to each other. One line, one number a layer, printed once at exit. */
+        /* Per-layer counts, so slow layers in a kernel trace can be matched to starved ones. */
         s += "  per layer:";
         for (size_t i = 0; i < res_count_.size(); ++i) {
             if (i % 12 == 0) s += fmt("\n   L%-3zu ", i);
diff --git a/core/place/heat.h b/core/place/heat.h
index 04d742e9..2436e2f7 100644
--- a/core/place/heat.h
+++ b/core/place/heat.h
@@ -1,49 +1,31 @@
-/* heat.h -- the heat engine: which conditional weight should be in VRAM, decided from what the
- * router actually did.
+/* heat.h -- the heat engine: which conditional weights should be in VRAM, decided from the
+ * router's observed choices.
  *
- * EXPERT OFFLOAD IS A PREDICTION PROBLEM. Layer offload is not -- declare enumerated the whole
- * access sequence and the planner emits an exact prefetch schedule off it. Routing is
- * data-dependent, so for RAD_ACCESS_CONDITIONAL weights there is no schedule to emit and the only
- * thing left is a policy. This file is that policy and nothing else: it sees a tier per unit, a
- * heat per unit and a dispatch count, and it answers one question -- "swap these two."
+ * Layer offload gets an exact prefetch schedule, because declare enumerates the access sequence.
+ * Routing (RAD_ACCESS_CONDITIONAL) is data-dependent, so expert offload needs a policy instead.
+ * This file is that policy: from a tier and a heat per unit and a dispatch count, it proposes
+ * swaps. It is pure host code with no device calls and no knowledge of slabs, streams or events
+ * (that is mover.cpp), so the decision half, hysteresis included, is testable without a card.
  *
- * Deliberately pure host code with no device call in it and no knowledge of slabs, streams or
- * events. Everything about how the bytes get there is mover.cpp. That split is what lets the
- * entire decision half be tested on a machine with no card, which is the only reason the
- * hysteresis behaviour below is checkable at all.
+ * ---- one step behind ---------------------------------------------------------------------------
  *
- * ---- WHAT IT COSTS TO BE ONE STEP BEHIND, HONESTLY -------------------------------------------
+ * Routing runs on device and never blocks the compute stream. The histogram is copied back
+ * asynchronously and consumed on the next step (spec §5.5), so every decision is one step stale.
+ * Ranking is unaffected, since a hot expert stays hot across many steps. But an expert that is not
+ * resident this step cannot be fetched in time: it is served from where it lies, streamed from the
+ * pinned pool or staged off the file tier. A last-moment fetch would have to fit between the
+ * router's output and the expert GEMM's first block, which is microseconds. Hit rate is therefore
+ * a property of the placement policy, and the run phase has no device round-trip.
  *
- * Routing is computed on device and never blocks the compute stream. The histogram is copied back
- * asynchronously and this engine consumes it on the NEXT step (spec §5.5), so every placement
- * decision is one step stale.
+ * ---- why LFU with decay ------------------------------------------------------------------------
  *
- * For heat-based promotion that is irrelevant: a hot expert is hot across many steps, and a
- * ranking built from the step before ranks almost exactly the same as one built from this step.
- * The real cost is different and it is worth being blunt about, because it is what people expect
- * this file to do and it does not:
- *
- *   AN EXPERT THAT IS NOT RESIDENT THIS STEP CANNOT BE FETCHED IN TIME. It is served from
- *   wherever it is -- streamed out of the pinned pool over the link, or staged off the file tier.
- *   There is no last-moment rescue and there is no point adding one: the fetch would have to
- *   finish inside the gap between the router's output and the expert GEMM's first block, which
- *   is microseconds.
- *
- * Hit rate is therefore a property of the PLACEMENT POLICY, not of a rescue path. That is the
- * trade, and what it buys is a run phase with no device round-trip in it.
- *
- * ---- WHY LFU-WITH-DECAY AND NOT SOMETHING CLEVERER --------------------------------------------
- *
- * Replaying real routing traces against cache policies settles the shape of this. Runtime
- * placement beats static profile placement by a wide margin, so it is worth building. What bounds
- * it is the MOVE RATE, not the ranking: held to the same swaps a step at the same step boundaries,
- * an oracle that knows every future routing scores no better than this policy (78.0% against 78.4%
- * at 64 swaps a step, Qwen3.8-Flash-Next TP1 with 40% of the experts resident). The unrestricted
- * Belady figure is far higher -- 92% on the same trace -- because it admits every miss the moment
- * it happens, and a miss admitted here is a second copy of bytes the GEMM has just streamed. So
- * the decay constant and the guards are not where the wins are, and this does not need to be
- * subtle; the budget (RAD_PLACE_MOVES_PER_STEP), the slots behind it, and keeping a prompt's
- * routing from swamping the answer's (HeatParams::credit_cap) are.
+ * In routing-trace replays, runtime placement beats static profile placement by a wide margin, and
+ * the move rate bounds it, not the ranking: at the same swaps a step, an oracle that knows every
+ * future routing scores no better (78.0% vs 78.4% at 64 swaps a step, Qwen3.8-Flash-Next TP1, 40%
+ * of experts resident). Unrestricted Belady reaches 92% only by admitting every miss at once, which
+ * here would copy again bytes the GEMM just streamed. The levers are the move budget
+ * (RAD_PLACE_MOVES_PER_STEP), the slots behind it, and keeping a prompt's routing from swamping the
+ * answer's (HeatParams::credit_cap), not the decay constant or the guards.
  */
 #pragma once
 #include "planner.h"
@@ -54,78 +36,54 @@
 namespace rad {
 
 struct HeatParams {
-    /* Applied to a layer's whole plane each time that layer's histogram is credited. Every layer is
-     * credited once a step, so all planes decay in lockstep and heats stay comparable ACROSS
-     * layers -- which the global ranking below depends on.
-     *
-     * 0.95 is a half-life of about fourteen steps. At 64 swaps a step the replay is flat from 0.8
-     * to 0.95 (77.96% to 78.37%) and falls off above it -- 77.1% at 0.98, 74.2% at 0.99 -- because
-     * a heat that remembers longer ranks the experts a conversation has moved past above the ones
-     * it routes to now. */
+    /* Applied to a layer's whole plane each time its histogram is credited. Every layer is
+     * credited once a step, so planes decay in lockstep and heats stay comparable across layers,
+     * which the global ranking needs. 0.95 is a half-life of about 14 steps. In replay at 64 swaps
+     * a step, hit rate is flat from 0.8 to 0.95 and falls above it (77.1% at 0.98, 74.2% at 0.99):
+     * a longer memory ranks experts the conversation has moved past above the current ones. */
     float decay = 0.95f;
 
-    /* Promote only when the candidate beats the victim by this ratio. Without it the two ends of
-     * the ranking trade places on noise and the engine spends the whole link on churn that
-     * changes nothing. */
+    /* Promote only when the candidate beats the victim by this ratio, so the two ends of the
+     * ranking do not trade places on noise. */
     float hysteresis = 1.25f;
 
-    /* ...and the additive half of the same guard, in units of one activation. It is what stops a
-     * swap when the victim's heat is ZERO, where any ratio test passes trivially -- and right
-     * after warmup that describes most of the resident set, so without this the first dispatch
-     * would try to swap the entire cache.
+    /* The additive half of the guard, in activations. It stops a swap against a zero-heat victim,
+     * where any ratio passes; right after warmup that is most of the resident set.
      *
-     * LINK TRAFFIC IS U-SHAPED IN THIS THRESHOLD. PAST THE BOTTOM OF THE CURVE, RAISING IT MOVES
-     * MORE BYTES, NOT FEWER -- so do not "fix" it by tightening the bar to save traffic. The
-     * economics look one-directional -- a promotion costs an H2D plus a D2H and only pays if the
-     * expert is selected again -- and they are not, because A PROMOTION DECLINED COMES BACK AS A
-     * MISS, and a miss is a shard streamed over the same link on the same budget. A tighter bar
-     * then gives up hit rate and buys no traffic back.
-     *
-     * What a swap costs is its promotion. The link is close to full duplex -- on an R9700, 28.5
-     * GB/s up and 25.0 down at once, against 28.8 up alone -- so a demotion's copy rides the idle
-     * direction, while a promotion shares the upstream one with every miss the GEMM streams. At
-     * the default budget lower values replay within 0.2 points of hit rate and promote a fifth
-     * more. */
+     * Do not raise it to save link traffic: traffic is U-shaped in this threshold. A declined
+     * promotion comes back as a miss, streamed over the same link, so past the minimum a tighter
+     * bar loses hit rate and saves no bytes. A swap costs its promotion: the link is near full
+     * duplex (R9700: 28.5 GB/s up and 25.0 down at once, 28.8 up alone), so a demotion rides the
+     * idle direction while a promotion shares the upstream with every miss. At the default budget,
+     * lower values replay within 0.2 points of hit rate and promote a fifth more. */
     float min_gain = 1.5f;
 
-    /* A BOUNDED MOVE BUDGET PER STEP: step() is called once a step, after every layer's histogram
-     * has been credited, and proposes at most this many swaps a slab class. The value and why it
-     * is that are at RAD_PLACE_MOVES_PER_STEP, which also sizes the free slots a swap lands in
-     * (the shadow and turnover slots); a budget raised here without them is spent on
-     * `starved_slab`.
+    /* Swaps step() may propose per slab class each step, after every layer is credited. The value
+     * and its reason are at RAD_PLACE_MOVES_PER_STEP, which also sizes the free slots a swap lands
+     * in (shadow and turnover slots); a budget raised here without them is spent on
+     * `starved_slab`. Promotions share the link with streamed misses, but each swap saves many
+     * times its own bytes in misses.
      *
-     * The apparent risk is that a high budget makes the mover compete with the tier it is trying
-     * to shrink -- a promotion and a streamed miss are the same bytes over the same link. At this
-     * scale that does not bind: each swap moves an expert the ranking says will be read again
-     * soon, and the misses it saves are many times its own bytes.
-     *
-     * IT IS A BUDGET PER SLAB CLASS. A rank holding an uneven slice of every expert has two expert
-     * classes -- the wider slice of one parity's experts and the narrower slice of the other's --
-     * each about half a whole expert, and a budget shared between them would move half the bytes
-     * a step that whole experts do: residency would converge half as fast. Per class, the two
-     * together move about as many whole experts as one class of whole experts does. */
+     * Per class because a rank holding an uneven slice of every expert has two classes of about
+     * half an expert each; a shared budget would make residency converge half as fast. */
     int moves_per_step = RAD_PLACE_MOVES_PER_STEP;
 
-    /* THE MOST ONE HISTOGRAM CREDITS, in selections: a histogram that routed more is credited
-     * at this total, each expert in proportion to its count. A decode step routes a few rows a
-     * sequence and stays under it; a prefill chunk routes thousands, and at full weight one chunk
-     * outweighs dozens of decode steps, so for that many steps after a prompt the resident set is
-     * the prompt's rather than the answer's. What the resident set buys a prefill is little in
-     * any case: a chunk reads nearly every expert of a layer, and the stager copies whichever are
-     * not resident. Replaying a mixed workload at Qwen3.8-Flash-Next TP1, decode rows hit 77.3%
-     * uncapped, 78.9% at 1024 and 79.0% at 512 or 256. */
+    /* The most one histogram credits, in selections; a larger histogram is scaled to this total.
+     * Decode routes a few rows a sequence and stays under it. A prefill chunk routes thousands
+     * and would otherwise make the resident set the prompt's for dozens of steps, while prefill
+     * gains little from residency (a chunk reads nearly every expert; the stager copies the rest).
+     * Mixed-workload replay, Qwen3.8-Flash-Next TP1: decode hit rate 77.3% uncapped, 78.9% at
+     * 1024, 79.0% at 512 or 256. */
     float credit_cap = 512.0f;
 
-    /* Dispatches to watch before moving anything, and it is 0 because THE GUARD ALREADY DOES THIS
-     * JOB. min_gain means a promotion needs `hot >= cold*hysteresis + 1.5`, and against a
-     * zero-heat victim that is two tokens agreeing in one dispatch -- evidence, not noise,
-     * whatever the dispatch count is. A warmup only postpones convergence. */
+    /* Dispatches to watch before moving anything. 0, because min_gain already requires
+     * `hot >= cold*hysteresis + 1.5`, which against a zero-heat victim is two tokens agreeing in
+     * one dispatch; a warmup only delays convergence. */
     int warmup_dispatches = 0;
 };
 
-/* A swap is returned as a PAIR even though the mover issues two independent transfers, because
- * the DECISION is a comparison between them: promoting without the matching demotion would grow
- * the resident set past the slab. */
+/* A promotion and its matching demotion. The mover issues two transfers, but they are decided
+ * together: a promotion without its demotion would grow the resident set past the slab. */
 struct Swap {
     int32_t promote = -1;   /* unit index */
     int32_t demote = -1;
@@ -137,71 +95,53 @@ struct HeatRanked { float h; int32_t rc; int32_t unit; };
 struct HeatStats {
     uint64_t dispatches = 0;
     uint64_t proposed = 0, promotions = 0, demotions = 0;
-    /* Why a dispatch did NOT move anything, which is the diagnostic that matters once the engine
-     * looks idle. `refused` is the guard declining -- the healthy steady state, and the number
-     * that should dominate once the hot set has settled. */
+    /* Why a dispatch moved nothing. `refused` is the guard declining, the healthy steady state.
+     * `no_candidate` is an empty end of the ranking (everything movable is resident, or nothing
+     * is), a budget question rather than a policy one. */
     uint64_t refused = 0, no_candidate = 0;
-    /* Is the churn PROGRESS or THRASH? The same total move count means two opposite things. If
-     * every promotion is of a unit never promoted before, the engine is still discovering the
-     * working set and the traffic is an investment. If it keeps re-admitting units it demoted a
-     * moment ago, the traffic is pure loss: both directions of the link spent to arrive back
-     * where it started. `readmits` is the second case counted directly, and it is the number that
-     * decides whether the guards are set right. */
+    /* Progress or thrash. `distinct_promoted` counts first-time promotions (still discovering the
+     * working set); `readmits` counts promotions of units demoted earlier, link traffic spent to
+     * return to where it started. Readmits say whether the guards are set right. */
     uint64_t distinct_promoted = 0, readmits = 0;
-    /* WHAT THE ROUTER ASKED FOR, AND WHETHER IT WAS THERE. Counted on the histogram this engine
-     * already walks, so it is one compare per routed expert and no second pass.
-     *
-     * A miss is not an error and nothing stalls on it: the GEMM reads that expert's weights from
-     * whatever tier holds them, which for a host-pinned unit means pulling them across the link
-     * on the critical path of the step. So `stream_bytes` is the OTHER traffic the mover's
-     * promotions were hiding -- a promotion is bytes spent once to stop paying this, and without
-     * both numbers beside each other there is no way to say whether the policy is winning.
-     *
-     * Weighted by the histogram's `weight`, because a draft head's histogram stands for several
-     * routing passes and each of them really did read its experts. The hit RATE is unaffected --
-     * both counters scale together -- and the byte figure is right.
-     */
+    /* Routed experts and how many were resident, counted on the histogram pass observe() already
+     * makes. A miss does not stall: the GEMM reads the expert from its tier, which for a
+     * host-pinned unit crosses the link on the step's critical path. `stream_bytes` is that
+     * traffic, the cost promotions exist to avoid. Weighted by the histogram's `weight`, since a
+     * draft head's histogram stands for several routing passes; the hit rate is unaffected. */
     uint64_t routed = 0, routed_resident = 0, stream_bytes = 0;
 };
 
 class HeatEngine {
 public:
-    /* Binds to the plan. Returns RAD_OK even when the plan is static -- that is a mode, not a
-     * failure, and every caller would otherwise have to special-case it. `enabled()` says which.
-     * Under Config::deterministic the plan is static, this stays off, and step() proposes
+    /* Binds to the plan. A static plan is a mode, not a failure: init returns RAD_OK and
+     * enabled() is false. Under Config::deterministic the plan is static and step() proposes
      * nothing for the whole run (spec §17). */
     int init(const Plan& plan, const HeatParams& params);
     bool enabled() const { return enabled_; }
 
-    /* ---- the input: last step's routing histogram ------------------------------------------
+    /* ---- input: last step's routing histogram ------------------------------------------------
      *
      * `counts[e]` is how many of the step's tokens routed to expert e of this layer. The credit
-     * is that count and not a flat 1.0: cost is per DISTINCT expert -- a dispatch reads an
-     * expert's weights once however many tokens chose it -- but the probability of needing it
-     * again is not. An expert several tokens chose is far likelier to be chosen again soon than
-     * one a single token chose, and most selections are single-token. Weighting by it moves no
-     * extra bytes; it only ranks better. */
-    /* `weight` is how many of that layer's routing passes this histogram stands for -- see
-     * Ctx::last_histogram_reports. It is 1 for every layer of a non-speculative step and n_spec
-     * for a draft head, and it belongs on the CREDIT rather than the decay: the caller sweeps
-     * every layer exactly once a step, so the planes decay in lockstep and heats stay comparable
-     * across layers. Without it a single histogram silently stands for several passes' worth of
-     * activations and under-credits the experts a draft head routed to. */
+     * is the count, not 1: a dispatch reads an expert once however many tokens chose it, but an
+     * expert several tokens chose is far likelier to be chosen again soon.
+     *
+     * `weight` is how many of the layer's routing passes this histogram stands for (see
+     * Ctx::last_histogram_reports): 1 for a non-speculative step, n_spec for a draft head. It
+     * scales the credit, not the decay, because every layer still decays exactly once a step. */
     void observe(int32_t layer, const int32_t* counts, int32_t n_expert, float weight = 1.0f);
     /* The same, sparse: distinct expert ids and their counts. `counts` may be null for one each. */
     void observe_ids(int32_t layer, const int32_t* experts, const int32_t* counts, int32_t n);
-    /* Starts the fetch of a histogram observe() will read: a row the card copied into host
-     * memory is a miss on every line, so a caller that knows its next rows asks for them early. */
+    /* Starts fetching a histogram observe() will read. A row the card copied into host memory
+     * misses on every line, so a caller that knows its next rows asks early. */
     static void prefetch(const int32_t* counts, int32_t n_expert) {
         for (int32_t j = 0; j < n_expert; j += 64 / (int32_t)sizeof(int32_t))
             __builtin_prefetch(counts + j);
     }
 
-    /* ---- the tier map, written by the MOVER when a move PUBLISHES, not when it is issued ----
+    /* ---- tier map, written by the mover when a move publishes, not when it is issued ---------
      *
-     * Between issue and publish both copies of the bytes are valid and the dispatch still reads
-     * the old one, so this engine must agree with dispatch about where a unit is or it will pick
-     * the same one twice. `set_busy` is what excludes an in-flight unit instead. */
+     * Until publish both copies are valid and dispatch reads the old one, so the tier here must
+     * match dispatch's view. `set_busy` is what keeps an in-flight unit from being picked again. */
     void set_tier(int32_t unit, Tier t);
     void set_busy(int32_t unit, bool busy);
     Tier tier(int32_t unit) const { return tier_[(size_t)unit]; }
@@ -210,30 +150,25 @@ public:
     /* The best swap available, or false when the guards refuse. */
     bool pick(Swap* out) const;
 
-    /* One step's worth of proposals, at most `moves_per_step` of them a class.
+    /* One step's proposals, at most `moves_per_step` per class.
      *
-     * CONTRACT: every unit named in the result is marked busy on the way out. The caller must
-     * either issue the transfer -- in which case set_tier() on publish and set_busy(false) after
-     * the quarantine -- or call abandon() for both halves. A proposal that is silently dropped
-     * leaves the pair busy forever and the engine goes quiet with no counter to say why. */
+     * Every unit in the result is marked busy. The caller must either issue the transfer
+     * (set_tier() on publish, set_busy(false) after the quarantine) or abandon() the pair. A
+     * dropped proposal leaves both units busy forever, with no counter to show it. */
     int step(std::vector* out);
     void abandon(const Swap& s);
 
     float heat(int32_t unit) const { return heat_[(size_t)pos_[(size_t)unit]]; }
-    /* How many units of THIS unit's layer are resident. The tiebreak every residency decision
-     * needs: a global ranking with no layer term leaves some layers holding far more than others,
-     * and a layer starved of slots misses on nearly every token however good the ranking inside
-     * it is. `pick` uses it on an exact heat tie and so must anything else that chooses. */
+    /* Resident units in this unit's layer: the tie-break every residency decision needs (see
+     * `res_count_`). `pick` uses it on an exact heat tie, and so must anything else that chooses. */
     int32_t layer_residents(int32_t unit) const {
         const int32_t l = (size_t)unit < layer_of_.size() ? layer_of_[(size_t)unit] : -1;
         return l >= 0 && (size_t)l < res_count_.size() ? res_count_[(size_t)l] : 0;
     }
     const HeatStats& stats() const { return stats_; }
 
-    /* The exit banner. The per-layer residency histogram at the end of it is the one number that
-     * says whether the engine did the thing it exists for: a global profile ranking leaves layers
-     * with wildly different resident counts, and a layer starved of slots misses on nearly every
-     * token however good the ranking inside it is. */
+    /* Exit banner, ending with the per-layer resident counts, which show whether every layer kept
+     * its share of slots. */
     std::string report() const;
 
 private:
@@ -242,20 +177,17 @@ private:
     int32_t    n_layer_ = 0;
     HeatStats  stats_;
 
-    /* THE HEAT, BY POSITION RATHER THAN BY UNIT. Each layer owns one run of positions, and the
-     * front of that run is indexed by EXPERT: expert e of layer l sits at slot_lo_[l] + e, whether
-     * or not the plan has a unit for it and whether or not that unit may move. Then the layer's
-     * other movable units, then padding to a whole number of lanes. After the layers come the
-     * movable units with no layer, padded to a whole screening block, and after them everything
-     * else.
+    /* Heat by position, not by unit. Each layer owns a run of positions whose front is indexed by
+     * expert: expert e of layer l is at slot_lo_[l] + e, whether or not the plan has a unit for it
+     * or that unit may move. Then come the layer's other movable units, then padding to a multiple
+     * of kLanes. After the layers: the movable units with no layer, padded to a screening block,
+     * then everything else.
      *
-     * That lines a histogram up with the positions it credits. observe() walks counts[e] and the
-     * heat at slot_lo_[l] + e side by side, in fixed-width blocks the compiler turns into vector
-     * code, with no unit number looked up and no branch taken per expert. A position with no unit
-     * behind it is a hole: never a candidate, never priced, and its heat is read by nothing.
-     * `pos_` and `unit_at_` translate (-1 for a hole); everything outside the position arrays
-     * stays indexed by MoveUnit index so this file and the plan cannot disagree about what a
-     * number means. */
+     * This lines a histogram up with the positions it credits, so observe() walks counts[e] and
+     * the heat side by side in fixed-width vector blocks, with no unit lookup or per-expert branch.
+     * A position with no unit is a hole: never a candidate, never priced. `pos_` and `unit_at_`
+     * translate (-1 for a hole); everything outside the position arrays is indexed by MoveUnit
+     * index, as in the plan. */
     std::vector   heat_;               /* by position */
     std::vector pos_;                /* unit -> position */
     std::vector unit_at_;            /* position -> unit, -1 for a hole */
@@ -273,30 +205,26 @@ private:
     std::vector slot_lo_;
     std::vector n_ex_;
     void set_place(int32_t unit);
-    /* Unit bytes, from the plan. Here so a miss can be priced where it is detected rather than
-     * joined back to the plan by every reader. */
+    /* Unit bytes from the plan, so a miss is priced where it is detected. */
     std::vector bytes_;
     std::vector    tier_;
     std::vector busy_;
     std::vector movable_;
     std::vector layer_of_;
-    /* Bit 0: promoted before. Bit 1: demoted before. Two bits a unit, so the thrash question
-     * costs nothing on the dispatch path. */
+    /* Bit 0: promoted before. Bit 1: demoted before. Feeds the readmit counters. */
     std::vector ever_;
 
-    /* How many of each layer's units are resident. THE TIE-BREAK IS NOT COSMETIC: most resident
-     * units are cold, so `heat == 0.0f` exactly is the common case at both ends of the ranking,
-     * and whatever breaks that tie IS the policy for most of a run. Breaking it by index order
-     * strips the low-numbered layers first, which replaces the skew this engine exists to fix
-     * with a different one. So ties go to the layer that can most afford it: take the victim from
-     * the layer holding the MOST, promote into the one holding the FEWEST. */
+    /* Resident units per layer. A layer starved of slots misses on nearly every token however
+     * good the ranking inside it is. Most resident units are cold, so exact `heat == 0.0f` ties
+     * are common at both ends and the tie-break is effectively the policy; breaking it by index
+     * would strip low-numbered layers first. Ties take the victim from the layer holding the most
+     * and promote into the layer holding the fewest. */
     std::vector res_count_;
-    /* A SWAP STAYS INSIDE ONE SLAB CLASS. The promoted unit takes a slot of its own class and the
-     * demoted one frees a slot of its own, so a pair across two classes would drain one class's
-     * spare slots into the other's until promotions starve. A model has one expert class when
-     * every expert is the same size on a rank, and two when a rank holds an uneven slice of each
-     * expert's width (three 128-column blocks of one parity, two of the other). `cls_` is the
-     * unit's class as a dense index, -1 for a unit that cannot move. */
+    /* A swap stays inside one slab class: each half uses a slot of its own class, so a pair across
+     * classes would drain one class's spare slots into the other's until promotions starve. A rank
+     * has one expert class when every expert is the same size, two when it holds an uneven slice
+     * of each expert's width (three 128-column blocks of one parity, two of the other). `cls_` is
+     * the dense class index, -1 for a unit that cannot move. */
     std::vector cls_;
     int32_t              n_cls_ = 1;
     /* step()'s two ends of the ranking, `moves_per_step` entries a class, kept between calls so a
@@ -306,16 +234,13 @@ private:
     /* Per slot, its lowest movable unit index: the bound step()'s layer screen needs on a tie. */
     std::vector min_unit_;
 
-    /* EACH LAYER'S TWO ENDS, so a dispatch that proposes nothing -- the guard declining the best
-     * pair, which is nearly every dispatch once the resident set has settled -- is decided from
-     * one entry a layer rather than a scan of every unit. Over the movable units not in flight:
-     * the hottest one off the device and the coldest one on it, and how many there are of each.
+    /* Each slot's two ends, over movable units not in flight: the hottest off the device and the
+     * coldest on it, and how many of each. A dispatch that proposes nothing (nearly all of them
+     * once residency settles) is then decided from one entry a layer, not a scan of every unit.
      * Slot n_layer_ is the movable units with no layer.
      *
-     * observe() recomputes a layer's ends on the pass that decays and credits it, where each is
-     * one more compare on a value already in a register. A change of tier or of being in flight
-     * invalidates the unit's layer, and an invalid entry is rebuilt from its positions when step()
-     * next reads it. */
+     * observe() updates a layer's ends on the pass that credits it. A tier or busy change
+     * invalidates the unit's slot, which step() rebuilds from its positions on its next read. */
     std::vector   end_hot_, end_cold_;
     std::vector end_n_off_, end_n_on_;
     std::vector end_n_cold_;   /* units on the device at exactly the cold end's heat */
diff --git a/core/place/mover.cpp b/core/place/mover.cpp
index 6cf892b5..ea1043d3 100644
--- a/core/place/mover.cpp
+++ b/core/place/mover.cpp
@@ -1,11 +1,8 @@
-/* mover.cpp -- the mover's mechanics. See mover.h for why any of it is shaped this way.
+/* mover.cpp -- the mover's mechanics; mover.h has the design.
  *
- * Everything here runs on the DISPATCH THREAD. The transfers are asynchronous -- their own
- * stream, gated behind an event recorded after the layer's launches -- but every table edit is
- * applied by this thread at a layer boundary, draining a queue of transfers that have landed. No
- * mutex on the read side, because that side is the critical path of every layer, and no
- * background thread mutating placement mid-layer, because placement would then depend on host
- * timing and stop being reproducible.
+ * Everything here runs on the dispatch thread. Transfers run asynchronously on the mover's
+ * stream, gated behind an event recorded after the layer's launches, but every table edit is
+ * applied by this thread at a layer boundary (see Mover::Move).
  */
 #include "mover.h"
 #include "../device/device.h"
@@ -21,10 +18,9 @@ namespace rad {
 
 /* ------------------------------------------------------------------ the file tier */
 int FileTier::open(const std::string& path) {
-    /* No RAD_DIO_ALLOW_BUFFERED. The weight tier is read on the dispatch path in whole movement
-     * units; a silent buffered fallback turns it into a page-cache pump that is several times
-     * slower, evicts the container's own mapped pages, and looks like nothing at all in a
-     * profile. An operator who pointed the tier at tmpfs wants to be told, not accommodated. */
+    /* No RAD_DIO_ALLOW_BUFFERED: a silent buffered fallback would make the tier a page-cache pump
+     * that is several times slower, evicts the container's own mapped pages and does not show in
+     * a profile. A tier pointed at tmpfs gets an error instead. */
     const int rc = f_.open(path.c_str(), RAD_DIO_READ);
     if (rc < 0)
         RAD_ERR("file tier: cannot open %s with O_DIRECT. The tier needs a filesystem that "
@@ -35,8 +31,8 @@ int FileTier::open(const std::string& path) {
 int FileTier::read(uint64_t offset, int64_t bytes, void* dst, int64_t dst_cap) {
     if (!f_.is_open()) return RAD_E_STATE;
     if (!dst || bytes <= 0) return RAD_E_INVAL;
-    /* The whole extent, rounded up: a movement unit's stride is already aligned, and reading the
-     * padding costs one block against a branch on the step path. */
+    /* The extent rounded up to the alignment: the unit stride already covers it, and reading
+     * one extra block is cheaper than a branch on the step path. */
     const int64_t want = direct_align(bytes);
     if (want > dst_cap) {
         RAD_ERR("file tier: a %s read needs a %s aligned buffer, the staging slot is %s",
@@ -44,37 +40,21 @@ int FileTier::read(uint64_t offset, int64_t bytes, void* dst, int64_t dst_cap) {
         return RAD_E_SCRATCH;
     }
     RAD_TRY(f_.read_at(dst, (int64_t)offset, want));
-    ++reads_;
-    bytes_ += (uint64_t)bytes;
     return RAD_OK;
 }
 
 /* ------------------------------------------------------------------ residency */
-void Residency::init(const Program& prog, const Plan& plan) {
-    (void)plan;
+void Residency::init(const Program& prog) {
     slot_.assign(prog.weights.size(), WeightSlot{});
     noted_.assign(prog.weights.size(), 0);
     changed_.clear();
     ++epoch_;
 }
 
-/* The generation bump is the whole of the staleness protocol, and it is deliberately not a lock:
- * at this instant BOTH copies of the bytes are valid -- the mover wrote a shadow slot and has not
- * freed the old one -- so whichever side of this write a reader lands on names bytes that are
- * correct. The quarantine is what makes that sentence stay true.
- *
- * Both writers bump. `publish` settles a slot whose transfer has landed; `begin_transfer` opens
- * one, and it MUST bump too, because the run phase memoises its stream wait per generation and a
- * new event at an old generation is a wait that never happens (residency_iface.h). */
-void Residency::publish(rad_weight w, void* ptr) {
-    if ((size_t)w >= slot_.size()) return;
-    slot_[w].ptr = ptr;
-    slot_[w].ready = nullptr;
-    ++slot_[w].generation;
-    ++epoch_;
-    note(w);
-}
-
+/* The generation bump is the whole staleness protocol, with no lock: at this point both copies of
+ * the bytes are valid (the mover wrote a shadow slot and has not freed the old one), so a reader
+ * on either side of the write names correct bytes. The quarantine keeps that true. Why both
+ * writers bump: mover.h. */
 void Residency::begin_transfer(rad_weight w, void* ptr, RadEvent ready) {
     if ((size_t)w >= slot_.size()) return;
     slot_[w].ptr = ptr;
@@ -86,9 +66,8 @@ void Residency::begin_transfer(rad_weight w, void* ptr, RadEvent ready) {
 
 /* ------------------------------------------------------------------ the mover */
 Mover::~Mover() {
-    /* The stream first, drained. What it still holds are the gate waits and the move records
-     * that name the events below and the copies into and out of the memory below, so each of
-     * those goes only once nothing queued refers to it. */
+    /* Drain the stream first: its queued gate waits, event records and copies refer to the
+     * events and memory freed below. */
     if (mover_) {
         (void)flush_moves();
         rad_stream_sync(mover_);
@@ -98,7 +77,7 @@ Mover::~Mover() {
     for (RadEvent e : lead_) if (e) rad_event_destroy(e);
     for (RadEvent e : win_ev_) if (e) rad_event_destroy(e);
     if (gate_) rad_event_destroy(gate_);
-    /* Only what this object allocated itself. A Pool reservation belongs to the Pool. */
+    /* Only what this object allocated; a Pool reservation belongs to the Pool. */
     if (owns_memory_) {
         for (ClassPools& c : pools_) {
             if (c.slab_base) rad_dev_free(c.slab_base, RAD_MEM_DEVICE);
@@ -109,14 +88,14 @@ Mover::~Mover() {
         if (file_vram_) rad_dev_free(file_vram_, RAD_MEM_DEVICE);
         if (windows_) rad_dev_free(windows_, RAD_MEM_HOST_PINNED);
     }
-    /* The pageable region is always ours: Pools has no pageable pool, because pageable host
-     * memory is not a device-visible budget and nothing else contends for it. */
+    /* The pageable region is always ours: Pools has no pageable pool, since pageable memory is
+     * not a device-visible budget and nothing else contends for it. */
     if (pageable_) rad_dev_free(pageable_, RAD_MEM_HOST);
 }
 
-/* One place the mover asks for memory. Everything device-side and everything pinned comes out of
- * the resolved budgets (spec §6); the fallback exists so the placement test can run without
- * standing a whole Pools up, and it announces itself. */
+/* The one place the mover asks for memory. Device and pinned memory come out of the resolved
+ * budgets (spec §6); the direct allocation is for the placement test, which runs without a Pools
+ * (init() warns). */
 void* Mover::reserve(const char* what, int64_t bytes, int kind) {
     if (bytes <= 0) return nullptr;
     if (budget_) {
@@ -134,9 +113,7 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
     budget_ = budget;
     stats_ = MoverStats{};
     if (!budget_)
-        RAD_WARN("mover: no Pools handed over; allocating its slab and host pool directly. That "
-                 "double-spends the weights pool against whatever else already reserved it, so "
-                 "it is a test path and not a deployment.");
+        RAD_WARN("mover: no Pools given; allocating the slab and host pool directly (test only)");
 
     unit_.assign(plan.units.size(), UnitState{});
     copying_.assign(plan.units.size(), 0);
@@ -158,8 +135,6 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
         us.klass = mu.slab_class;
         us.bytes = mu.bytes;
         if (mu.slab_class < 0) continue;
-        const int64_t stride = plan.classes[(size_t)mu.slab_class].stride;
-
         if (mu.tier == Tier::VRAM && mu.slab_slot >= 0) {
             n_slab[(size_t)mu.slab_class] = std::max(n_slab[(size_t)mu.slab_class],
                                                      (int64_t)mu.slab_slot + 1);
@@ -173,41 +148,34 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
             us.static_off = align_up(pageable_need, RAD_ALIGN_UNIT);
             pageable_need = us.static_off + mu.bytes;
         }
-        (void)stride;
     }
 
     /* ---- allocate ------------------------------------------------------------------------- */
-    int64_t total_shadow = 0, total_turn = 0;
+    int64_t total_shadow = 0, total_turn = 0, total_slab = 0, total_pool = 0;
     for (size_t c = 0; c < plan.classes.size(); ++c) {
         const SlabClass& sc = plan.classes[c];
         ClassPools& cp = pools_[c];
         cp.stride = sc.stride;
 
-        /* Shadow slots sit PAST the resident ones, so a slot index is a slot index and the
-         * resident count is untouched by turning the engine on. Under a static plan the plan
-         * asked for none and the slab is exactly the resident set. */
-        /* THE PLAN'S NUMBER, not a config cap. The planner reserved these out of
-         * the weights pool and the report told the operator how many; allocating a different
-         * count here would mean the mover works against one number while the operator was charged
-         * for another, and the direction that is wrong in is an overrun. */
+        /* Shadow slots follow the resident ones, so resident indices do not depend on the engine;
+         * a static plan has none. Use the plan's count, which the planner budgeted. */
         const int64_t shadow = plan.dynamic ? sc.n_shadow : 0;
-        /* Shadow slots and staging slots are both "slab slots that belong to no unit", and the
-         * mover takes them off one free list because at the point of use they are the same thing:
-         * somewhere to copy into that nothing is reading. They are budgeted separately by the
-         * planner because they are the price of two different features. */
+        /* Shadow and staging slots share one free list: both are somewhere to copy into that
+         * nothing reads. */
         const int64_t slab_slots = n_slab[c] + shadow + sc.n_stage;
-        /* The flex slots are not here: their memory is the KV cache's and is not carved yet.
-         * lend_from() adds them once it is. */
+        /* Flex slots are added later by lend_from(), once the lender's memory is carved. */
         cp.n_fixed = slab_slots;
         cp.n_work = shadow + sc.n_stage;
         cp.n_turn = std::min(std::max(cfg.turnover_slots, 0),
                                       shadow * RAD_PLACE_TURNOVER_SLOTS / RAD_PLACE_SHADOW_SLOTS);
         total_turn += cp.n_turn;
         cp.slab.init(slab_slots, sc.stride);
+        total_slab += slab_slots;
+        total_pool += n_pool[c];
         if (slab_slots > 0) {
-            /* Tail padding: a kernel that assembles a packed code window from a wide read
-             * legitimately reads a few bytes past the last slot's data. Inside the slab that
-             * lands in a neighbour; at the end it runs off the allocation and faults the card. */
+            /* Tail padding: a kernel assembling a packed code window from a wide read may read a
+             * few bytes past the last slot; without padding that runs off the allocation and
+             * faults the card. */
             cp.slab_base = reserve(sc.name.c_str(), slab_slots * sc.stride + RAD_ALIGN_UNIT,
                                    RAD_MEM_DEVICE);
             if (!cp.slab_base) {
@@ -227,49 +195,33 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
                         sc.name.c_str(), (long long)n_pool[c], humanb(sc.stride).c_str());
                 return RAD_E_NOMEM;
             }
-            /* The pool's base as the CARD sees it. On a unified backend this is the host address
-             * itself, but going through the device layer is what makes that a checked fact
-             * rather than an assumption -- and without it a zero-copy expert is a bounce-buffer
-             * memcpy and there is no hybrid tier at all. */
+            /* The pool's base as the card addresses it (equal to the host address on a unified
+             * backend). Without one there is no zero-copy tier. */
             cp.pool_dev = rad_dev_device_ptr(cp.pool_base);
-            /* AND A FAILURE HERE IS NAMED RATHER THAN PAPERED OVER. Falling back silently to the
-             * host pointer hands a kernel an address it cannot dereference -- so a zero-copy
-             * expert would fault, or read whatever the backend happens to map there.
-             *
-             * It is not refused HERE because this is not where the consequence lands: a unit with
-             * no pool address gets a null base from unit_base(), republish() publishes the null,
-             * and the load phase already refuses by name on the first weight that needs one. That
-             * is the right place -- a pool nothing zero-copies out of is not an error. This line
-             * is what turns that refusal from "no address after mover init" into a cause. */
+            /* Warned, not refused: a pool nothing zero-copies out of is not an error. The host
+             * pointer is valid on the device only where the two coincide. A deployment's pool is
+             * RAD_MEM_HOST_MAPPED (core/mem/pools.cpp), so this fires only on the test path. */
             if (!cp.pool_dev) {
-                RAD_WARN("mover: the '%s' host pool did not resolve to a device address; the "
-                         "zero-copy tier cannot be served out of it. In a deployment the pool is "
-                         "RAD_MEM_HOST_MAPPED (core/mem/pools.cpp) and this does not fire; where "
-                         "it does, the pool is ordinary host memory and a kernel handed this "
-                         "address would fault.", sc.name.c_str());
+                RAD_WARN("mover: the '%s' host pool has no device address; a kernel reading it "
+                         "zero-copy would fault", sc.name.c_str());
                 cp.pool_dev = cp.pool_base;
             }
         }
-        /* The pool free list starts EMPTY: every pooled unit occupies its slot. The engine primes
-         * off the shadow slab slots, runs ahead by at most that many, and settles into
-         * alternating pairs -- a promotion frees a pool slot, which is what a demotion needs. */
-
-        /* AND NOTHING HERE IS MEMSET. A fresh pool holds garbage until the load phase writes it,
-         * which is correct -- a weight is read only after it is loaded -- and zeroing it would be
-         * a full pass over the host tier for no information. It is also the one asymmetry between
-         * the two device backends: rad_memset_async on RAD_MEM_HOST refuses on a real card
-         * (pageable memory the GPU has never been shown) and quietly succeeds on the host backend,
-         * so a memset added here passes in tests and fails on a card. If a host buffer ever
-         * genuinely needs clearing, clear it with std::memset on the host. */
+        /* The pool free list starts empty: every pooled unit occupies its slot. The engine primes
+         * off the shadow slots and then alternates, a promotion freeing the pool slot a demotion
+         * needs.
+         *
+         * Nothing is memset; the load phase writes every weight. rad_memset_async on
+         * RAD_MEM_HOST fails on a real card but succeeds on the host backend, so use std::memset
+         * if a host buffer ever needs clearing. */
     }
 
     if (static_need > 0) {
         static_vram_ = reserve("static weights", static_need, RAD_MEM_DEVICE);
         if (!static_vram_) {
-            /* THE ARITHMETIC, not just the refusal: the slab is reserved first and takes its
-             * shadow and staging slots with it, so "no VRAM" here means the budget covered the
-             * resident set and not the fixed weights beside it. An operator cannot act on the
-             * sentence without the two numbers. */
+            /* Log the budget arithmetic too: the slab, with its shadow and staging slots, was
+             * reserved first, so this failure means the budget covered the resident set but not
+             * the static weights beside it. */
             if (budget_)
                 RAD_ERR("mover: the weight budget is %s and the slab already took %s of it, "
                         "leaving %s",
@@ -284,7 +236,11 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
     }
     if (pageable_need > 0) {
         pageable_ = rad_dev_alloc(pageable_need, RAD_MEM_HOST);
-        if (!pageable_) return RAD_E_NOMEM;
+        if (!pageable_) {
+            RAD_ERR("mover: no pageable host memory for %s of weights",
+                    humanb(pageable_need).c_str());
+            return RAD_E_NOMEM;
+        }
         pageable_bytes_ = pageable_need;
     }
 
@@ -293,20 +249,15 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
     for (const MoveUnit& mu : plan.units) if (mu.tier == Tier::SSD) want_file = true;
     if (want_file) {
         if (cfg_.container_path.empty()) {
-            RAD_ERR("mover: the plan put weights on the file tier but no container path was "
-                    "given; a file-tier unit with nowhere to read from is an error, not a slow "
-                    "path");
+            RAD_ERR("mover: the plan puts weights on the file tier but no container path was "
+                    "given");
             return RAD_E_INVAL;
         }
         RAD_TRY(file_.open(cfg_.container_path));
-        /* THE WIDEST UNIT THAT IS ACTUALLY ON THE FILE TIER, not the widest class in the plan.
-         *
-         * A staging slot only ever receives a unit read from the container, so sizing it off every
-         * class charges the host pool for classes that are never staged. The widest class is
-         * typically the embedding table -- its own class, gigabytes wide, and never on the file
-         * tier: in VRAM, or in the pinned host pool by --embedding-placement -- so sizing on it
-         * reserves several times that in pinned memory to receive a weight that never arrives, and
-         * the file tier is then refused for want of memory it did not need. */
+        /* Staging slots are sized by the widest unit actually on the file tier, not the widest
+         * class. The widest class is usually the embedding table (gigabytes, and never on the
+         * file tier), and sizing on it would reserve pinned memory for a weight that never
+         * arrives, possibly failing the file tier for lack of memory. */
         int64_t widest = 0;
         for (const MoveUnit& mu : plan.units) {
             if (mu.tier != Tier::SSD || mu.slab_class < 0) continue;
@@ -325,9 +276,9 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
 
     /* ---- the file stager's buffers ---------------------------------------------------------
      *
-     * Exactly what the plan charged: the two VRAM buffers out of the weight budget and the read
-     * windows out of the host pool's file-staging reserve. Allocated only when a routed unit is
-     * actually on the file tier, which is when the plan sized them. */
+     * Exactly what the plan charged: two VRAM buffers from the weight budget and the read windows
+     * from the host pool's file-staging reserve. The plan sizes them only when a routed unit is
+     * on the file tier. */
     if (plan.file_stage_vram > 0) {
         if (!file_.ok()) {
             RAD_ERR("mover: the plan reads routed experts from the container and the file tier "
@@ -343,7 +294,11 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
         /* Two halves of what was charged, each at least the largest layer and aligned, so the
          * tail pad the plan added stays past the second buffer's end. */
         file_buf_bytes_ = (plan.file_stage_vram - RAD_ALIGN_UNIT) / 2 / RAD_ALIGN_UNIT * RAD_ALIGN_UNIT;
-        if (file_buf_bytes_ < plan.file_layer_max) return RAD_E_STATE;
+        if (file_buf_bytes_ < plan.file_layer_max) {
+            RAD_ERR("mover: the plan charged %s for two file-tier layer buffers of %s",
+                    humanb(plan.file_stage_vram).c_str(), humanb(plan.file_layer_max).c_str());
+            return RAD_E_STATE;
+        }
         if (plan.file_windows < (int64_t)RAD_PLACE_FILE_WINDOWS * RAD_PLACE_FILE_WINDOW_BYTES) {
             RAD_ERR("mover: the plan reads routed experts from the container but reserved no read "
                     "windows for them");
@@ -362,10 +317,9 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
 
     /* ---- streams, events, move records ------------------------------------------------------ */
     RAD_TRY(rad_stream_create(&mover_, /*high_priority=*/0));
-    /* EVERY EVENT HERE IS LOCAL. They order the mover's queue against this card's compute queue
-     * and tell the host WHEN a slot is free; the bytes they order are read by this card's kernels
-     * and never by the host through them. A copy out to host memory carries the system scope on
-     * its own packets. */
+    /* Every event here is local: they order the mover's queue against this card's compute queue
+     * and tell the host when a slot is free, and the host never reads the ordered bytes through
+     * them. A copy out to host memory carries system scope on its own packets. */
     RAD_TRY(rad_event_create_local(&gate_));
     /* A window's event is waited on by the HOST, before the window is read into again. */
     win_ev_.assign((size_t)n_windows_, nullptr);
@@ -376,18 +330,15 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
     lead_.assign((size_t)lead + 1, nullptr);
     for (RadEvent& e : lead_) RAD_TRY(rad_event_create_as(&e, RAD_EVENT_LOCAL | RAD_EVENT_HOST_WAIT));
 
-    /* TWO records per free slot, shadow or turnover, not one. A promotion holds a slab slot for
-     * its whole life, so there can never be more promotions in flight than there are free slots --
-     * but a swap is two transfers, and the matching demotion needs a record of its own or the pair
-     * can never be in flight together and the engine never issues a demotion at all. That failure
-     * is silent: it shows up as `no_record` where the real symptom is a resident set that only ever
-     * grows. The floor is what makes a one-shadow plan still able to hold a swap. */
+    /* Two records per free slot (shadow or turnover): a swap is two transfers, and with one
+     * record per slot the demotion could never be in flight beside its promotion, so the resident
+     * set would only grow. The floor lets a one-shadow plan still hold a swap. */
     const int64_t n_records = std::max(2 * (total_shadow + total_turn), 4);
     moves_.assign((size_t)n_records, Move{});
     for (Move& m : moves_) RAD_TRY(rad_event_create_local(&m.ev));
 
     /* ---- publish the initial addresses ------------------------------------------------------ */
-    res_.init(prog, plan);
+    res_.init(prog);
     for (int32_t u = 0; u < (int32_t)plan.units.size(); ++u) {
         unit_[(size_t)u].slab_slot = plan.units[(size_t)u].slab_slot;
         republish(u);
@@ -395,13 +346,10 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
 
     RAD_INFO("mover: %lld slab slots (%lld shadow, %lld more kept free out of a loan), %lld pinned "
              "pool slots, %s static vram%s",
-             (long long)[&] { int64_t n = 0; for (auto& c : pools_) n += c.slab.size(); return n; }(),
-             (long long)total_shadow, (long long)total_turn,
-             (long long)[&] { int64_t n = 0; for (auto& c : pools_) n += c.pool.size(); return n; }(),
+             (long long)total_slab, (long long)total_shadow, (long long)total_turn,
+             (long long)total_pool,
              humanb(static_bytes_).c_str(), file_.ok() ? ", file tier open" : "");
-    /* The pageable host region is allocated here and charged to no budget -- Pools has no
-     * pageable pool because the memory is not device-visible and nothing else contends for it.
-     * That makes the receipt the only place it is ever named. */
+    /* The pageable region is charged to no budget, so this is the only place it is reported. */
     if (pageable_bytes_ > 0)
         RAD_INFO("mover: %s of pageable host memory for the units no tier could hold",
                  humanb(pageable_bytes_).c_str());
@@ -427,8 +375,8 @@ void* Mover::unit_base(int32_t unit) const {
         return (char*)cp.pool_dev + us.pool_slot * cp.stride;
     if (us.tier == Tier::HostPageable && us.static_off >= 0 && pageable_)
         return (char*)pageable_ + us.static_off;
-    /* A file-tier unit that is not staged has NO address, and saying so is the point: a kernel
-     * cannot read one off disk, so a caller that meets a null here must stage it or refuse. */
+    /* An unstaged file-tier unit has no address; a kernel cannot read from disk, so a caller
+     * that gets null must stage the unit or refuse. */
     return nullptr;
 }
 
@@ -439,17 +387,20 @@ void Mover::republish(int32_t unit) {
         res_.publish(mu.weights[i], base ? base + mu.offset[i] : nullptr);
 }
 
-/* Is a COPY INTO this unit's slot still in flight? The release path needs it: a slot whose
- * staging copy has not landed cannot be given back, because the quarantine barrier is recorded on
- * the COMPUTE stream and would say nothing about an H2D still in flight on the mover's.
- *
- * Copying and only Copying. "Any record that is not Free" is the same question asked too widely:
- * a record past Copying has its bytes in place, and treating it as in-flight holds the slot for
- * as long as the record takes to recycle rather than as long as the copy takes to land. */
+/* Whether a copy into this unit's slot is still in flight. A slot whose staging copy has not
+ * landed cannot be released: the quarantine barrier is on the compute stream and says nothing
+ * about an H2D copy on the mover's. Only Copying counts; a record past it has its bytes in place,
+ * and counting it would hold the slot until the record recycles. */
 bool Mover::unit_in_flight(int32_t unit) const {
     return unit >= 0 && (size_t)unit < copying_.size() && copying_[(size_t)unit] > 0;
 }
 
+bool Mover::stageable(int32_t unit) const {
+    const UnitState& us = unit_[(size_t)unit];
+    return us.tier == Tier::HostPinned && us.pool_slot >= 0 && us.slab_slot < 0 && us.klass >= 0 &&
+           !unit_in_flight(unit);
+}
+
 int Mover::free_move_record() const {
     const size_t n = moves_.size();
     for (size_t k = 0; k < n; ++k) {
@@ -459,10 +410,9 @@ int Mover::free_move_record() const {
     return -1;
 }
 
-/* The ordering event, recorded ONCE PER DISPATCH and only when a move is actually going out.
- * Everything the mover issues this dispatch waits on it, and it is downstream of every launch
- * made up to now. Once per dispatch rather than once per move: re-recording per move is a dozen
- * event records a layer restating one ordering constraint. */
+/* The ordering event, recorded on the compute stream once per dispatch and only when a move goes
+ * out. Everything the mover issues this dispatch waits on it, and it is downstream of every
+ * launch so far; re-recording it per move would restate the same ordering. */
 int Mover::record_gate() {
     if (!compute_) {
         RAD_ERR("mover: no compute stream bound; a transfer cannot be ordered against the "
@@ -480,12 +430,9 @@ int Mover::begin_dispatch(int dispatch, HeatEngine* heat) {
     ++stats_.dispatches;
     RAD_TRY(retire(heat));
 
-    /* THE LEAD GATE. This is a host wait and it is NOT a transfer synchronisation: no transfer
-     * waits on the host and no host thread waits on a transfer. What it bounds is how far ahead
-     * of the cards this thread may queue work, and it exists because a freed slot returns to the
-     * free list only when its quarantine event signals -- and that event is on the compute
-     * stream. Let the host run and the stream carries a whole step, the recycle latency becomes
-     * that depth, and the mover finds no free slot to move into on almost every round. */
+    /* The lead gate: a host wait bounding how far ahead of the cards this thread queues work,
+     * so quarantine events on the compute stream signal soon enough to recycle slots
+     * (MoverConfig::max_lead_dispatches). It never waits on a transfer. */
     if (compute_ && cfg_.max_lead_dispatches > 0) {
         RadEvent old = lead_[(size_t)lead_next_];
         if (stats_.dispatches > (uint64_t)lead_.size()) RAD_TRY(rad_event_sync(old));
@@ -495,26 +442,24 @@ int Mover::begin_dispatch(int dispatch, HeatEngine* heat) {
     return RAD_OK;
 }
 
-/* ---- the exact prefetch, which is the whole of layer offload's policy -------------------------
+/* ---- the exact prefetch: layer offload's whole policy -----------------------------------------
  *
- * Declare enumerated every op with its weight operands in order, so the deadline for each staged
- * unit is a fact and not a guess. WHEN to start is the supply question -- start as early as a
- * slot is free, and stop at the first unit that cannot get one rather than skipping ahead,
- * because the schedule is in deadline order and serving a later unit before an earlier one is how
- * a prefetch turns into a cache.
+ * Declare recorded every op with its weight operands in order, so each staged unit's deadline is
+ * known. Transfers start as soon as a slot is free and stop at the first unit that cannot get
+ * one rather than skipping ahead: the schedule is in deadline order, and serving a later unit
+ * first would turn the prefetch into a cache.
  */
 int Mover::prefetch_to_op(int32_t op_index) {
     if (!plan_) return RAD_E_STATE;
 
-    /* A backwards op index is the next step starting. The schedule is per step, so the cursor
-     * rewinds; nothing else has to know a step boundary happened. */
+    /* A backwards op index means the next step started; the schedule is per step, so the cursor
+     * rewinds. */
     if (op_index < last_op_) prefetch_cursor_ = 0;
     last_op_ = op_index;
 
-    /* RELEASE FIRST, so the slots this op finished with are available to the units it is about to
-     * need. A staged unit's slot goes back once its last_use_op is behind us: the declared order
-     * is what makes that safe, because a weight read outside [first_use_op, last_use_op] would
-     * contradict the order declare recorded. */
+    /* Release first, so slots this op finished with are free for the units it needs next. A
+     * staged unit's slot goes back once its last_use_op has passed; the declared order rules out
+     * a read outside [first_use_op, last_use_op]. */
     for (int32_t u = 0; u < (int32_t)unit_.size(); ++u) {
         const UnitState& us = unit_[(size_t)u];
         if (us.site != Site::DeviceStaged || us.slab_slot < 0) continue;
@@ -556,16 +501,16 @@ int Mover::start_stage(int32_t unit, int64_t slab_slot) {
     else if (us.tier == Tier::HostPageable && us.static_off >= 0)
         src = (char*)pageable_ + us.static_off;
     else if (us.tier == Tier::SSD) {
-        /* The file tier's cliff, and it is a BLOCKING host read in the middle of a dispatch. It
-         * is counted so a run that leans on it is visible as a run to re-budget, not as a mystery
-         * in the throughput. */
+        /* A blocking host read inside the dispatch, counted in ssd_reads. */
         if (!file_.ok() || !stage_) return RAD_E_STATE;
+        /* The ring has wrapped: the copies out of its slots may still be queued on the mover's
+         * stream, and the pread below would overwrite a source they have not read yet. */
+        if (stage_next_ == 0 && stats_.ssd_reads > 0) RAD_TRY(rad_stream_sync(mover_));
         char* stage = (char*)stage_ + (int64_t)stage_next_ * stage_stride_;
         stage_next_ = (stage_next_ + 1) % std::max(1, cfg_.stage_slots);
-        /* WEIGHT BY WEIGHT, each from its own plane into its own place in the unit. A container
-         * entry is a logical weight's planes at 256-byte alignment and a unit lays its weights out
-         * at their declared alignment, so the two arrangements are not the same bytes and one
-         * read of the unit's span would put every weight after the first at the wrong offset. */
+        /* Weight by weight, each to its own offset in the unit. A container entry holds a
+         * weight's planes at 256-byte alignment while a unit lays weights out at their declared
+         * alignment, so one read of the unit's span would misplace every weight after the first. */
         const MoveUnit& mu = plan_->units[(size_t)unit];
         for (size_t k = 0; k < mu.weights.size(); ++k) {
             const WeightInfo& w = prog_->weights[mu.weights[k]];
@@ -593,14 +538,11 @@ int Mover::start_stage(int32_t unit, int64_t slab_slot) {
     stats_.prefetch_bytes += (uint64_t)us.bytes;
     ++stats_.prefetched;
 
-    /* PUBLISH THE DESTINATION NOW, not at retire, and with the event. A staging copy is the one
-     * move whose destination the run phase will read: the old address (the pinned pool) stays
-     * valid for everything already issued, and everything issued from here on names the slab slot
-     * and is ordered behind `ev` on the compute stream. That stream wait is the only thing
-     * standing between a staged weight and a race, and it costs no host time.
-     *
-     * begin_transfer bumps the generation, which is what makes the run phase actually perform
-     * that wait rather than skipping it as already done. */
+    /* Publish the destination now, with the event, not at retire. Staging is the one move whose
+     * destination the run phase reads: work already issued uses the old address (the pinned
+     * pool), and work issued from here on names the slab slot and waits on `ev` on the compute
+     * stream. That wait is the only guard against a race; begin_transfer bumps the generation so
+     * the run phase performs it. */
     us.slab_slot = slab_slot;
     char* base = (char*)unit_base(unit);
     const MoveUnit& mu = plan_->units[(size_t)unit];
@@ -625,23 +567,20 @@ int Mover::stage_units(const std::vector& units, const StageSpan* spans
     stage_picks_.clear();
     for (int32_t u : units) {
         if (u < 0 || (size_t)u >= unit_.size()) return RAD_E_INVAL;
+        if (!stageable(u)) continue;
         const UnitState& us = unit_[(size_t)u];
-        if (us.tier != Tier::HostPinned || us.pool_slot < 0 || us.slab_slot >= 0 || us.klass < 0)
-            continue;
-        if (unit_in_flight(u)) continue;
         const ClassPools& cp = pools_[(size_t)us.klass];
         const char* src = (const char*)cp.pool_base + us.pool_slot * cp.stride;
         stage_picks_.push_back(StagePick{src, u, us.bytes, align_up(us.bytes, RAD_ALIGN_UNIT),
                                          nullptr});
     }
     if (stage_picks_.empty()) return RAD_OK;
-    /* THE SPANS ARE FILLED IN POOL ORDER, so units on neighbouring pool slots land side by side
-     * and go as one copy. A layer's pooled experts were given their slots together and mostly
-     * still hold them, so a layer's ~90 units go as fewer copies -- each one a launch or a DMA
-     * packet whatever its size. A class's stride is its units' aligned size, so a run's source and
-     * destination advance alike, padding included. A unit the span in hand has no room left for
-     * goes to the start of the next; one that no span has room for is read across the link in
-     * place. */
+    /* Spans are filled in pool order, so units on neighbouring pool slots land side by side and
+     * go as one copy. A layer's pooled experts were assigned slots together and mostly keep them,
+     * so its ~90 units take far fewer copies, each a launch or DMA packet whatever its size. A
+     * class's stride is its units' aligned size, so a run's source and destination advance alike.
+     * A unit that does not fit the current span starts the next; one that fits no span is read
+     * across the link in place. */
     std::sort(stage_picks_.begin(), stage_picks_.end(),
               [](const StagePick& a, const StagePick& b) { return a.src < b.src; });
     int k = 0;
@@ -693,12 +632,8 @@ void Mover::unstage_units(const std::vector& staged) {
 int64_t Mover::stage_need(const std::vector& units, int64_t* largest) const {
     int64_t total = 0, most = 0;
     for (int32_t u : units) {
-        if (u < 0 || (size_t)u >= unit_.size()) continue;
-        const UnitState& us = unit_[(size_t)u];
-        if (us.tier != Tier::HostPinned || us.pool_slot < 0 || us.slab_slot >= 0 || us.klass < 0)
-            continue;
-        if (unit_in_flight(u)) continue;
-        const int64_t need = align_up(us.bytes, RAD_ALIGN_UNIT);
+        if (u < 0 || (size_t)u >= unit_.size() || !stageable(u)) continue;
+        const int64_t need = align_up(unit_[(size_t)u].bytes, RAD_ALIGN_UNIT);
         total += need;
         most = std::max(most, need);
     }
@@ -715,12 +650,11 @@ struct FileExt {
     char*   dst = nullptr;
 };
 
-/* THE GAP A RUN READS THROUGH rather than starting another pread. The weights of one routed
- * layer sit together in the container, each starting on RAD_ALIGN_UNIT, so between two that are
- * both on the file tier there is either alignment padding or a run of units that are not -- a
- * resident expert or a pooled one. Reading padding is free next to a second pread; reading a
- * resident expert is a megabyte or ten the drive delivers for nothing. 256 KiB is above every
- * padding and below every expert this engine serves. */
+/* The largest gap a run reads through instead of starting another pread. A routed layer's
+ * weights sit together in the container, each on RAD_ALIGN_UNIT, so a gap between two file-tier
+ * weights is either alignment padding (cheaper to read than a second pread) or units on another
+ * tier (megabytes read for nothing). 256 KiB is above every padding and below every expert this
+ * engine serves. */
 constexpr int64_t kReadThrough = (int64_t)256 << 10;
 
 }  /* namespace */
@@ -756,7 +690,7 @@ int Mover::stage_file_units(const std::vector& units, char* dst, int64_
         off += need;
     }
     if (staged->empty()) return RAD_OK;
-    /* CONTAINER ORDER, so a window is one long run of the drive and not a seek per weight. */
+    /* Container order, so a window is one long run of the drive rather than a seek per weight. */
     std::stable_sort(ext.begin(), ext.end(),
                      [](const FileExt& a, const FileExt& b) { return a.foff < b.foff; });
 
@@ -862,7 +796,7 @@ int Mover::issue(const Swap& s, HeatEngine* heat) {
         if (us.klass < 0) return false;
         ClassPools& cp = pools_[(size_t)us.klass];
 
-        /* A UNIT THAT KEPT ITS HOST COPY IS DROPPED, NOT DEMOTED: its pool slot still holds its
+        /* A unit that kept its host copy is dropped, not demoted: its pool slot still holds its
          * bytes, so there is nothing to copy and no second pool slot to take. */
         if (!promote && us.pool_slot >= 0 && us.slab_slot >= 0) return drop(unit, heat) >= 0;
 
@@ -873,32 +807,26 @@ int Mover::issue(const Swap& s, HeatEngine* heat) {
             return true;
         }
 
+        /* Every refusal comes before pool_slot_for, which may take a donor's host copy
+         * (donor_slot) that a failed demotion could not give back. */
+        if (us.slab_slot < 0) return false;
         const int rec = free_move_record();
         if (rec < 0) { ++stats_.no_record; return false; }
         if (record_gate() < 0) return false;
+        const int64_t g = pool_slot_for(unit, heat);
+        if (g < 0) { ++stats_.starved_pool; return false; }
+        /* D2H out of the slab; the slab layout is the pool layout, so a straight copy. It is not
+         * free even though zero-copy reads use the other direction: both directions share one
+         * budget and a demotion costs about what a promotion does, the exchange rate heat.h's
+         * min_gain is tuned against. */
+        if (rad_event_wait(mover_, gate_) < 0) { cp.pool.add_free(g); return false; }
+        queue_move_copy((char*)cp.pool_base + g * cp.stride, cp.slot_ptr(us.slab_slot), us.bytes,
+                        rec);
         Move& m = moves_[(size_t)rec];
-        {
-            const int64_t g = pool_slot_for(unit, heat);
-            if (g < 0) { ++stats_.starved_pool; return false; }
-            char* dst = (char*)cp.pool_base + g * cp.stride;
-            if (us.slab_slot < 0) { cp.pool.add_free(g); return false; }
-            const void* src = cp.slot_ptr(us.slab_slot);
-            /* D2H out of the slab. The slab layout IS the pool layout, so this is a straight copy
-             * with no transform -- and IT IS NOT FREE. It is tempting to read a demotion as
-             * running in the direction the zero-copy tier leaves idle and therefore as nearly
-             * free; it is not. The two costs are additive: the directions share one budget and a
-             * demotion costs about what a promotion does. That is the exchange rate heat.h's
-             * min_gain is tuned against. */
-            if (rad_event_wait(mover_, gate_) < 0) { cp.pool.add_free(g); return false; }
-            if (queue_move_copy(dst, src, us.bytes, (int)(&m - moves_.data())) < 0) {
-                cp.pool.add_free(g);
-                return false;
-            }
-            m.kind = Move::Kind::Demote;
-            m.slab_slot = us.slab_slot;
-            m.pool_slot = g;
-            stats_.d2h_bytes += (uint64_t)us.bytes;
-        }
+        m.kind = Move::Kind::Demote;
+        m.slab_slot = us.slab_slot;
+        m.pool_slot = g;
+        stats_.d2h_bytes += (uint64_t)us.bytes;
         m.state = Move::State::Copying;
         m.unit = unit;
         ++copying_[(size_t)unit];
@@ -907,10 +835,9 @@ int Mover::issue(const Swap& s, HeatEngine* heat) {
 
     const bool up = one(s.promote, true);
     const bool down = one(s.demote, false);
-    /* A half-issued swap is legal and self-correcting: the two halves create each other's supply,
-     * so the missing one goes out on a later dispatch. What is NOT legal is leaving a unit busy
-     * that no move will ever publish -- the heat engine would never consider it again and would
-     * go quiet with no counter saying why. */
+    /* A half-issued swap is legal: the halves supply each other, so the missing one goes out on
+     * a later dispatch. A unit no move will publish must not stay busy, or the heat engine would
+     * never consider it again, with no counter showing why. */
     if (heat) {
         if (!up) heat->set_busy(s.promote, false);
         if (!down) heat->set_busy(s.demote, false);
@@ -919,6 +846,10 @@ int Mover::issue(const Swap& s, HeatEngine* heat) {
 }
 
 /* ------------------------------------------------------------------ the loan */
+static const char* lender_name(int lender) {
+    return lender == Mover::kLendKV ? "KV cache" : "activation arena";
+}
+
 static char* align_down_ptr(char* p) {
     const uintptr_t v = (uintptr_t)p;
     return (char*)(v - v % (uintptr_t)RAD_ALIGN_UNIT);
@@ -934,9 +865,8 @@ int Mover::lend_from(int lender, const std::vector& strips) {
                 return RAD_E_STATE;
             }
 
-    /* WHO GETS THE SLOTS. A class with units in the pinned pool that could be promoted, in
-     * proportion to their bytes -- and never more slots than it has such units, because a slot no
-     * unit can ever fill is VRAM lent to nothing. */
+    /* Slots go to classes with promotable units in the pinned pool, in proportion to their
+     * bytes, and never more slots than such units, since a slot no unit can fill is wasted. */
     const size_t nc = pools_.size();
     std::vector want(nc, 0), got(nc, 0);
     for (size_t u = 0; u < unit_.size(); ++u) {
@@ -949,9 +879,8 @@ int Mover::lend_from(int lender, const std::vector& strips) {
     for (size_t c = 0; c < nc; ++c)
         weight[c] = pools_[c].stride > 0 ? (double)want[c] * (double)pools_[c].stride : 0.0;
 
-    /* EVERY STRETCH, TOP DOWN. The classes take turns in proportion to their weight, so each
-     * stretch holds each class's share and the share does not depend on the order the stretches
-     * arrive in. */
+    /* Every stretch, top down. Classes take turns in proportion to their weight, so each stretch
+     * holds each class's share regardless of the order the stretches arrive in. */
     struct Cut { int64_t need; char* p; };
     std::vector> cuts(nc);
     for (const LoanStrip& st : strips) {
@@ -959,10 +888,9 @@ int Mover::lend_from(int lender, const std::vector& strips) {
             st.unit_tokens <= 0)
             continue;
         char* const bottom = st.top - st.bytes;
-        /* THE TOP ALIGNMENT UNIT STAYS EMPTY. A kernel assembling a packed code window reads a
-         * few bytes past the end of the slot it was handed; inside the stretch that lands in the
-         * slot above, and above the top of the stretch is memory that is not the slab's -- the
-         * next layer's blocks, or at the end of the carve a region nothing may have mapped. */
+        /* The top alignment unit stays empty. A kernel assembling a packed code window reads a
+         * few bytes past its slot; past the stretch's top is memory that is not the slab's (the
+         * next layer's blocks, or at the end of the carve possibly unmapped memory). */
         char* cur = align_down_ptr(st.top - RAD_ALIGN_UNIT);
         for (;;) {
             int best = -1;
@@ -985,8 +913,8 @@ int Mover::lend_from(int lender, const std::vector& strips) {
         }
     }
 
-    /* SMALLEST LOAN FIRST, so a loan of any size is a prefix of the slots and the one it gives
-     * back first is the deepest -- which is the one the owner wants back first. */
+    /* Smallest loan first, so any loan covers a prefix of the slots and the deepest slot, which
+     * the owner wants back first, is given back first. */
     int64_t n_new = 0, bytes_new = 0;
     for (size_t c = 0; c < nc; ++c) {
         if (cuts[c].empty()) continue;
@@ -997,8 +925,8 @@ int Mover::lend_from(int lender, const std::vector& strips) {
         l.lender = lender;
         l.seg = cp.slab.add_segment((int64_t)cuts[c].size());
         l.first = cp.slab.seg_lo(l.seg);
-        /* THE SLOT NUMBER AND THE POINTER LIST AGREE BY CONSTRUCTION: segments are appended in the
-         * order their pointers are, so slot_ptr's `slot - n_fixed` indexes straight into them. */
+        /* Segments are appended in the same order as their pointers, so slot_ptr's
+         * `slot - n_fixed` indexes flex_ptr directly. */
         if (l.first != cp.n_fixed + (int64_t)cp.flex_ptr.size()) {
             RAD_ERR("mover: a lent segment starts at slot %lld with %zu lent slots before it",
                     (long long)l.first, cp.flex_ptr.size());
@@ -1011,16 +939,16 @@ int Mover::lend_from(int lender, const std::vector& strips) {
     }
     if (n_new <= 0) return RAD_OK;
 
-    /* A RECORD FOR EVERY SLOT THAT CAN BE LENT. A fill issues a promotion into every free slot
-     * at once and a recall drops every unit past the loan at once, and each of those is a record
-     * until its barrier clears; sized at the shadow count, the records -- not the link -- would
-     * decide how fast a loan is used. */
+    /* A record for every lendable slot. A fill promotes into every free slot at once and a recall
+     * drops every unit past the loan at once, each holding a record until its barrier clears;
+     * with only the shadow count, records rather than the link would limit how fast a loan is
+     * used. */
     const size_t had = moves_.size();
     moves_.resize(had + (size_t)n_new);
     for (size_t i = had; i < moves_.size(); ++i) RAD_TRY(rad_event_create_local(&moves_[i].ev));
 
     RAD_INFO("mover: %lld slots can be lent out of the %s (%s), filled as it lends them",
-             (long long)n_new, lender == kLendKV ? "KV cache" : "activation arena",
+             (long long)n_new, lender_name(lender),
              humanb(bytes_new).c_str());
     count_flex();
     return RAD_OK;
@@ -1103,35 +1031,25 @@ int Mover::drop(int32_t unit, HeatEngine* heat) {
     return RAD_OK;
 }
 
-/* THE POOL IS SIZED TO THE UNITS THAT LIVE IN IT, so it has a slot free only while a promotion
- * into a budgeted slot is on its way through the quarantine -- and the budgeted range turns over
- * only as fast as those few slots come round. A budgeted unit that goes cold then stays, and the
- * engine's swap drops the coldest lent unit in its place, which is warmer: replaying a mixed
- * workload's routing at TP1, the hit rate is 72.7% that way against 76.7% with up to n_turn
- * donors a class, and 78.5% for one resident set with no regions at all.
+/* The pool is sized to its units, so it has a free slot only while a promotion passes through
+ * quarantine. Without donors a cold budgeted unit stays and the engine's swap drops a warmer lent
+ * unit instead; replaying mixed routing at TP1, the hit rate is 72.7% that way, 76.7% with up to
+ * n_turn donors per class, and 78.5% for one resident set with no regions.
  *
- * A unit in a lent slot keeps its host copy only so that a recall is a change of address. Giving
- * the copy to the victim costs that for this one unit: a recall moves it, into a free budgeted
- * slot or back across the link (reclaim), and a loan that shrinks under it moves it the same way
- * (balance). There is always somewhere for it to go -- each donor's copy went to a unit
- * whose budgeted slot it left free, so the free budgeted slots and the free pool slots together
- * number at least the donors once the quarantine has emptied (a recall drains it first). The
- * donors are bounded by the turnover slots, and they come out of the KV cache's loan only: the
- * arena takes its loan back at every prompt's first chunk, and that recall stays a change of
- * address.
+ * A donor loses its cheap recall: a recall or shrink must move it into a free budgeted slot or
+ * back across the link (reclaim, balance). There is always room once quarantine has emptied,
+ * since each donation left a budgeted slot free. Donors are capped at the turnover slots and come
+ * only from the KV cache's loan, so the arena's per-prompt recall stays an address change.
  *
- * THE HOTTEST UNIT GIVES ITS COPY -- of the victim's layer, when pool_slot_for asks for one --
- * because a donor the engine later demotes needs a pool slot of its own where it would have been a
- * drop. Its pool slot has no reader: the unit has been resident since its promotion retired, and
- * the copy into the slot waits on the gate besides. */
+ * The hottest unit (of the victim's layer, when asked) donates, since a donor later demoted needs
+ * a pool slot of its own. Its pool slot has no reader: the unit is resident and the copy into the
+ * slot waits on the gate. */
 int64_t Mover::donor_slot(size_t klass, int32_t layer, HeatEngine* heat) {
     ClassPools& cp = pools_[klass];
     if (cp.n_donated >= cp.n_turn) return -1;
-    /* NOT WHILE THE TURNOVER SLOTS ARE HELD: through a prompt and the few steps after it
-     * (Engine::tiering_dispatch). A donation lets a starved demotion go and the swap behind it
-     * with it, two copies on the stream the next prompt stages on; at TP2, where the resident set
-     * is nine tenths of the experts and a donor buys no decode at all, 26K-token prompts back to
-     * back ran 0.3% slower with them. A decode run reaches the count in a few steps. */
+    /* Not while the turnover slots are held (around a prompt): a donation releases a starved
+     * swap, two copies on the stream the next prompt stages on. A decode run reaches the donor
+     * count within a few steps anyway. */
     if (hold_turnover_) return -1;
     DonorRank& d = donors_[klass];
     if (d.at != dispatch_) {
@@ -1176,14 +1094,11 @@ int64_t Mover::donor_slot(size_t klass, int32_t layer, HeatEngine* heat) {
     }
 }
 
-/* THE STAGER COPIES A LAYER'S POOLED UNITS IN RUNS OF NEIGHBOURING POOL SLOTS (stage_units), and
- * the pool is laid out in unit order, so a layer's pooled units start out side by side. A demotion
- * that lands in a slot another layer's unit left breaks one run in that layer and starts a run of
- * one in its own, a copy more in each, for every prompt after it. So a slot one of the unit's own
- * layer started out in comes first, then a donor of the same layer -- its slot most likely one of
- * those -- and only then any free slot, or any donor. At TP1, 26K-token prompts with 256 tokens
- * decoded between them staged a layer in 162 copies without the preference and 112 with it (95
- * when the budget was 8 swaps a step). */
+/* The prefill stager copies runs of neighbouring pool slots, and the pool starts in unit order,
+ * so a demotion into another layer's slot costs an extra copy in both layers on every later
+ * prompt. Prefer a slot the unit's own layer started in, then a same-layer donor, then any free
+ * slot, then any donor. At TP1 (26K-token prompts, 256 decoded tokens between) this takes a
+ * layer's staging from 162 copies to 112. */
 int64_t Mover::pool_slot_for(int32_t unit, HeatEngine* heat) {
     const UnitState& us = unit_[(size_t)unit];
     ClassPools& cp = pools_[(size_t)us.klass];
@@ -1214,12 +1129,12 @@ bool Mover::migrate(int32_t unit, HeatEngine* heat) {
         cp.slab.add_free(to);
         return false;
     }
-    Move& m = moves_[(size_t)rec];
-    if (rad_event_wait(mover_, gate_) < 0 ||
-        queue_move_copy(cp.slot_ptr(to), cp.slot_ptr(us.slab_slot), us.bytes, rec) < 0) {
+    if (rad_event_wait(mover_, gate_) < 0) {
         cp.slab.add_free(to);
         return false;
     }
+    queue_move_copy(cp.slot_ptr(to), cp.slot_ptr(us.slab_slot), us.bytes, rec);
+    Move& m = moves_[(size_t)rec];
     m.state = Move::State::Copying;
     m.kind = Move::Kind::Migrate;
     m.unit = unit;
@@ -1241,13 +1156,13 @@ int Mover::promote_to(int32_t unit, int64_t slot) {
     const void* src = (const char*)cp.pool_base + us.pool_slot * cp.stride;
     Move& m = moves_[(size_t)rec];
     RAD_TRY(rad_event_wait(mover_, gate_));
-    RAD_TRY(queue_move_copy(cp.slot_ptr(slot), src, us.bytes, rec));
+    queue_move_copy(cp.slot_ptr(slot), src, us.bytes, rec);
     m.kind = Move::Kind::Promote;
     m.slab_slot = slot;
-    /* INTO A LENT SLOT, THE HOST COPY STAYS. The loan can be recalled at any time and a unit that
-     * kept its pool slot goes back by a change of address; one that gave it up would need a pool
-     * slot and a copy across the link at the moment the cache is asking for its memory. The
-     * quarantine then has no pool slot to free. */
+    /* Into a lent slot the host copy stays: the loan can be recalled at any time, and a unit
+     * that kept its pool slot goes back by a change of address instead of needing a pool slot and
+     * a link copy just as the cache wants its memory. The quarantine then has no pool slot to
+     * free. */
     m.pool_slot = cp.is_flex(slot) ? -1 : us.pool_slot;
     m.state = Move::State::Copying;
     m.unit = unit;
@@ -1269,11 +1184,10 @@ int Mover::fill(size_t klass, int64_t room, HeatEngine* heat) {
     }
     std::stable_sort(cand.begin(), cand.end(), [](const Cand& a, const Cand& b) { return a.h > b.h; });
 
-    /* HOTTEST FIRST, AND ON AN EXACT TIE THE LAYER HOLDING THE FEWEST RESIDENT UNITS -- the
-     * statement `pick` makes, and it has to keep holding as the batch lands. Every promotion here
-     * is issued before any of them retires, so the heat engine's own count does not move during
-     * the batch; it is counted here instead. Without that a fill of a cold slab, where every heat
-     * is zero, would put its whole batch into whichever layer was thinnest when it began. */
+    /* Hottest first; on an exact tie, the layer with the fewest resident units. Every promotion
+     * here is issued before any retires, so the heat engine's resident count does not move during
+     * the batch and `added` tracks it instead; otherwise a fill of a cold slab (all heats zero)
+     * would put the whole batch into whichever layer was thinnest at the start. */
     std::unordered_map added;
     int64_t issued = 0;
     for (size_t i = 0; i < cand.size() && issued < room;) {
@@ -1293,10 +1207,9 @@ int Mover::fill(size_t klass, int64_t room, HeatEngine* heat) {
             std::vector& us = by_layer[k.second];
             const int32_t u = us.back();
             us.pop_back();
-            /* A LENT SLOT AND NEVER A WORKING ONE. The shadow and staging slots are what lets a
-             * swap happen at all, and a unit filled into one sits in the budgeted range where no
-             * loan can give it back -- the reserve would be gone for good the first time the loan
-             * shrank. */
+            /* A lent slot, never a working one. Shadow and staging slots are what let a swap
+             * happen, and a unit filled into one sits in the budgeted range where no loan shrink
+             * returns it, so the reserve would be lost. */
             const int64_t slot = pools_[klass].slab.take_at_least(pools_[klass].n_fixed);
             if (slot < 0) return RAD_OK;
             if (heat) heat->set_busy(u, true);
@@ -1322,18 +1235,17 @@ int Mover::balance(HeatEngine* heat, bool turnover) {
         if (cp.flex_ptr.empty()) continue;
         bool drained = false;
 
-        /* ---- EMPTY WHAT THE LOAN NO LONGER COVERS, FIRST AND ALL OF IT. Each is a drop -- a
-         * change of address, with no copy -- so there is no link to ration it against, and the
-         * cache is waiting for these bytes. A unit still busy is on its way in; it goes on the
-         * next call, once its promotion has retired. The sweep is over every unit, so it runs
-         * only while a shrink may have stranded one (ClassPools::strand_check). */
+        /* ---- Empty what the loan no longer covers, all of it, first: drops cost no link
+         * traffic and the lender is waiting. A busy unit is still on its way in and goes on a
+         * later call. The sweep walks every unit, so it runs only after a shrink
+         * (ClassPools::strand_check). */
         if (cp.strand_check) {
             bool left = false;
             for (int32_t u = 0; u < (int32_t)unit_.size(); ++u) {
                 const UnitState& us = unit_[(size_t)u];
                 if (us.klass != (int32_t)c || us.slab_slot < 0 || cp.slab.covered(us.slab_slot)) continue;
-                /* Anything else still past the loan -- a promotion that has not retired, a staged
-                 * unit -- becomes droppable later, so the sweep has to come back for it. */
+                /* Anything else past the loan (an unretired promotion, a staged unit) becomes
+                 * droppable later, so the sweep must come back for it. */
                 if (us.tier != Tier::VRAM || us.site != Site::Device || (heat && heat->busy(u))) {
                     left = true;
                     continue;
@@ -1358,27 +1270,20 @@ int Mover::balance(HeatEngine* heat, bool turnover) {
             cp.strand_check = left;
         }
 
-        /* ---- THE WORKING RESERVE. The shadow and staging slots have to stay free whatever the
-         * loan is, or the mover cannot turn over: a loan that shrank past units sitting in the
-         * slots that were serving as the reserve leaves the slab too full by that many, and the
-         * coldest lent units go -- drops, never copies. A slot already on its way back below the
-         * target counts as free, because it is, a barrier from now; draining against it again is
-         * how a slab empties itself.
+        /* ---- The working reserve. Shadow and staging slots must stay free whatever the loan,
+         * or the mover cannot turn over; after a shrink the coldest lent units are dropped to
+         * restore them. A slot already on its way back (`pending`) counts as free, or the drain
+         * would repeat and empty the slab.
          *
-         * THE TURNOVER SLOTS ARE REBUILT THE SAME WAY, out of the lent units alone. They are the
-         * top of the lent range, which is exactly what a cache that wants memory back takes first,
-         * and the loan grows back only a prefill chunk at a time: left to the fill, they would be
-         * gone for as long as requests keep arriving. Dropping the coldest lent units costs
-         * nothing on the link -- each still has its host copy -- and gives up the same residents
-         * the slots would have cost anyway. A swap whose demotion found no pool slot is completed
-         * the same way, by the coldest lent unit instead. */
+         * The turnover slots are rebuilt the same way. They are the top of the lent range, which
+         * a recall takes first, and the loan regrows only a prefill chunk at a time, so the fill
+         * alone would leave them gone. A swap whose demotion found no pool slot is completed the
+         * same way. */
         int64_t pending = 0;
         for (const Move& m : moves_) {
             if (m.state == Move::State::Free || m.unit < 0 || m.slab_slot < 0) continue;
             if (unit_[(size_t)m.unit].klass != (int32_t)c || !cp.slab.covered(m.slab_slot)) continue;
-            if (m.kind == Move::Kind::Drop || m.kind == Move::Kind::Demote ||
-                m.kind == Move::Kind::Release || m.kind == Move::Kind::Migrate)
-                ++pending;
+            if (m.frees_slab()) ++pending;
         }
         const int64_t turn = turnover ? cp.n_turn : 0;
         int64_t short_by = cp.n_work + turn - (cp.slab.n_free() + pending);
@@ -1404,12 +1309,10 @@ int Mover::balance(HeatEngine* heat, bool turnover) {
                 --short_by;
             }
         }
-        /* AND WITH NO LENT UNIT LEFT TO DROP, THE COLDEST BUDGETED ONE GOES BACK TO THE POOL -- a
-         * real demotion, one a call, and for the working reserve only: the turnover slots are the
-         * loan's to give, and a copy across the link to keep them would spend the very link they
-         * exist to save. A swap can leave the free slots in the lent range, and a loan that then
-         * shrinks away takes them with it; the working reserve has to be rebuilt out of the
-         * budgeted slots or the mover stops turning over. */
+        /* With no lent unit left to drop, demote the coldest budgeted unit (a real copy, one per
+         * call), for the working reserve only: link traffic to keep turnover slots would cost what
+         * they save. A shrinking loan can take the free slots a swap left in the lent range, so
+         * the reserve must be rebuildable from the budgeted slots. */
         if (short_by > turn) {
             int32_t victim = -1;
             float coldest = 0.0f;
@@ -1433,7 +1336,7 @@ int Mover::balance(HeatEngine* heat, bool turnover) {
          * trying to hand back. */
         if (drained) continue;
 
-        /* ---- THEN FILL, every free slot past the working reserve and the turnover slots. */
+        /* ---- Then fill every free slot past the working reserve and the turnover slots. */
         RAD_TRY(fill(c, cp.slab.n_free() - cp.n_work - turn, heat));
     }
     count_flex();
@@ -1454,30 +1357,21 @@ int Mover::reclaim(int lender, int64_t amount, HeatEngine* heat) {
                 "the kernels that may still read the slots");
         return RAD_E_STATE;
     }
-    /* NO COPY IS STILL WRITING A SLOT: everything the mover issued has landed, and retiring it
-     * publishes the promotions that landed in slots about to be taken back. */
+    /* No copy may still be writing a slot: drain the mover's stream, then retire to publish
+     * promotions that landed in slots about to be taken back. */
     RAD_TRY(flush_moves());
     RAD_TRY(rad_stream_sync(mover_));
     RAD_TRY(retire(heat));
-    /* AND NO SLOT IS STILL IN QUARANTINE. The slots the donors below are owed come back through
-     * it: a donation's victim leaves its budgeted slot that way, and a promotion that refilled the
-     * slot leaves its pool slot that way (donor_slot). Looked for before the compute stream has
-     * passed their barriers, the slots of the last few dispatches' swaps are not free yet, and a
-     * donor finds nowhere to go. Nothing goes on the compute stream from this drain to the end of
-     * the recall, which issues only the mover's own copies. */
+    /* Drain quarantine too: the slots owed to the donors below come back through it (see
+     * donor_slot). Nothing goes on the compute stream from here to the end of the recall. */
     RAD_TRY(rad_stream_sync(compute_));
     RAD_TRY(retire(heat));
 
-    /* EVERY UNIT PAST THE LOAN GOES BACK TO ITS HOST COPY, which is a change of address -- or,
-     * for a donor (donor_slot), which has none, it moves: into a free budgeted slot, a copy inside
-     * the card, or else back across the link into a free pool slot. One of the two is free for
-     * every donor once the quarantine is empty (donor_slot says why). Nothing is published until
-     * the copies have landed.
-     *
-     * A DONOR WITH NOWHERE TO GO STAYS WHERE IT IS, and the recall still finishes: every other
-     * slot is given back and every moved donor published, so the loan stops short only by that
-     * unit's slot, and a later recall or balance() moves it. Stopping at it instead would leave
-     * the slots already taken off their units held by nothing, for the life of the process. */
+    /* Every unit past the loan goes back to its host copy. A donor has none, so it moves into a
+     * free budgeted slot or else across the link into a free pool slot, published once the
+     * copies land. A donor with nowhere to go stays and the recall finishes short by its slot
+     * (a later recall or balance() moves it); aborting instead would leak the slots already
+     * taken off their units. */
     std::vector> freed;
     std::vector moved;
     int stuck = 0;
@@ -1538,67 +1432,61 @@ int Mover::reclaim(int lender, int64_t amount, HeatEngine* heat) {
         for (int32_t u : moved) republish(u);
     }
 
-    /* AND NO KERNEL STILL NAMES ONE. The compute stream is the only reader of the slab -- the
-     * quarantine barrier rests on the same fact -- and it drained above with nothing issued since,
-     * so nothing can reach a slot past the loan, and everything issued from here reads the host
-     * copies. */
+    /* No kernel still names a freed slot: the compute stream is the slab's only reader (the
+     * quarantine relies on the same fact), it drained above with nothing issued since, and work
+     * issued from here reads the host copies. */
     for (const auto& f : freed) pools_[f.first].slab.add_free(f.second);
 
-    /* EVERY RECORD WAITING ON ONE OF THOSE SLOTS IS DONE WAITING: its barrier is behind the
-     * drain. A promotion's record has nothing to free -- its unit kept the pool slot -- and a
-     * drop's frees the slot it left. */
+    /* Every record waiting on one of those slots is done: its barrier is behind the drain. A
+     * promotion's record has nothing to free (its unit kept the pool slot); a drop's frees the
+     * slot it left. */
     for (Move& m : moves_) {
         if (m.state == Move::State::Free || m.unit < 0 || m.slab_slot < 0) continue;
         const int32_t klass = unit_[(size_t)m.unit].klass;
         if (klass < 0) continue;
         ClassPools& cp = pools_[(size_t)klass];
         if (!cp.is_flex(m.slab_slot) || cp.slab.covered(m.slab_slot)) continue;
-        if (m.kind == Move::Kind::Drop || m.kind == Move::Kind::Demote ||
-            m.kind == Move::Kind::Release || m.kind == Move::Kind::Migrate)
-            cp.slab.add_free(m.slab_slot);
+        if (m.frees_slab()) cp.slab.add_free(m.slab_slot);
         if (heat && m.kind != Move::Kind::Stage && m.kind != Move::Kind::Release)
             heat->set_busy(m.unit, false);
         if (m.state == Move::State::Copying) --copying_[(size_t)m.unit];
-        m.state = Move::State::Free;
-        m.unit = -1;
-        m.slab_slot = m.pool_slot = m.to_slot = -1;
+        m.clear();
     }
     count_flex();
     if (stuck > 0) {
         stats_.stranded += (uint64_t)stuck;
         RAD_ERR("mover: %d unit(s) that gave their host copy away found no free slot to move to; "
                 "the %s loan stops at %lld instead of %lld until they move", stuck,
-                lender == kLendKV ? "KV" : "arena", (long long)loan_held(lender),
+                lender_name(lender), (long long)loan_held(lender),
                 (long long)loan_[lender]);
         return RAD_E_FULL;
     }
     if (loan_held(lender) > loan_[lender]) {
         RAD_ERR("mover: recalled the %s loan to %lld and a slot at %lld is still held",
-                lender == kLendKV ? "KV" : "arena", (long long)loan_[lender],
+                lender_name(lender), (long long)loan_[lender],
                 (long long)loan_held(lender));
         return RAD_E_STATE;
     }
     return RAD_OK;
 }
 
-int Mover::queue_move_copy(void* dst, const void* src, int64_t bytes, int rec) {
+void Mover::queue_move_copy(void* dst, const void* src, int64_t bytes, int rec) {
     move_segs_.push_back(RadCopySeg{ src, dst, bytes });
     move_recs_.push_back((int32_t)rec);
-    return RAD_OK;
 }
 
-/* THE DMA ENGINE AND NOT COPY KERNELS. A copy kernel runs on the compute units beside the step's
- * kernels: at the heat engine's budget of 64 swaps a step, Qwen3.8-Flash-Next at one card spent 10 ms
- * a step in about 68 of them while the step took 36. The engine moves the same bytes at the link's
- * rate and takes nothing from the kernels; decode at one sequence went 34.1 -> 33.0 ms a step, and
- * two cards, prefill and the output were unchanged. A card with no DMA queue of this process's own
- * gets the list as copy kernels (rad_memcpy_list_async), as before. The list yields to the link's
- * collectives like the prefill stager's. */
+/* Swap copies go to the DMA engine as one list. Copy kernels would compete with the step's
+ * kernels: at 64 swaps a step, Qwen3.8-Flash-Next on one card spends about 10 ms of a 36 ms step
+ * in them. Without a DMA queue of this process's own, rad_memcpy_list_async falls back to copy
+ * kernels. The list yields to the link's collectives, like the prefill stager's. */
 int Mover::flush_moves() {
     if (move_segs_.empty()) return RAD_OK;
-    const int rc = rad_memcpy_list_async(move_segs_.data(), (int)move_segs_.size(), RAD_COPY_YIELD,
-                                         mover_);
-    for (int32_t rec : move_recs_) (void)rad_event_record(moves_[(size_t)rec].ev, mover_);
+    int rc = rad_memcpy_list_async(move_segs_.data(), (int)move_segs_.size(), RAD_COPY_YIELD,
+                                   mover_);
+    for (int32_t rec : move_recs_) {
+        const int er = rad_event_record(moves_[(size_t)rec].ev, mover_);
+        if (rc >= 0) rc = er;
+    }
     move_segs_.clear();
     move_recs_.clear();
     return rc;
@@ -1617,8 +1505,8 @@ int Mover::retire(HeatEngine* heat) {
         switch (m.kind) {
             case Move::Kind::Promote:
                 us.slab_slot = m.slab_slot;
-                /* The source slot goes back on quarantine, not to us -- unless the destination
-                 * was lent, in which case it is kept (see issue()). */
+                /* The source pool slot is freed after quarantine, unless the destination was
+                 * lent, in which case the unit keeps it (see promote_to). */
                 if (m.pool_slot >= 0) us.pool_slot = -1;
                 us.tier = Tier::VRAM;
                 us.site = Site::Device;
@@ -1632,35 +1520,22 @@ int Mover::retire(HeatEngine* heat) {
                 us.pool_slot = m.pool_slot;
                 us.slab_slot = -1;
                 us.tier = Tier::HostPinned;
-                /* Demoted, not exiled: the unit is now the zero-copy tier's, so the GEMM streams
-                 * it out of the pinned pool as it computes. There is no third dispatch path. */
+                /* The unit joins the zero-copy tier: the GEMM streams it from the pinned pool as
+                 * it computes. */
                 us.site = Site::DeviceZeroCopy;
                 ++stats_.demotions;
                 if (heat) heat->set_tier(m.unit, Tier::HostPinned);
                 break;
             case Move::Kind::Stage:
-                /* The destination was published at issue, with the event. All that is left is to
-                 * clear the event: the copy has landed, so the wait is no longer needed and the
-                 * common case -- a staged unit read many times before it is released -- costs no
-                 * runtime call at all. No generation bump: the address did not change, and
-                 * bumping would make the run phase re-wait on an event that has already
-                 * signalled. */
+                /* The destination was published at issue with the event. The copy has landed, so
+                 * clear the event and later reads of the staged unit cost no runtime call. No
+                 * generation bump: the address did not change, and a bump would make the run
+                 * phase wait again on an event that has already signalled. */
                 for (rad_weight w : plan_->units[(size_t)m.unit].weights) res_.settle(w);
-                /* ...AND STRAIGHT TO FREE, SKIPPING THE QUARANTINE. The barrier exists to protect
-                 * a slot on its way back to the free list from kernels that still name it; a
-                 * staging copy returns no slot -- the slot stays with the unit until a later
-                 * Release hands it back, and THAT is the move the barrier belongs to.
-                 *
-                 * Sending a Stage through the quarantine anyway is not merely redundant, it
-                 * stalls the prefetch: the record stays occupied for two more dispatches, and
-                 * unit_in_flight() therefore keeps reporting the unit busy, which blocks the very
-                 * Release that would recycle its slot. With a ring two deep that is the whole
-                 * supply. Invisible on the host backend, where every copy lands within the
-                 * dispatch that issued it; on a real card the copies take tens of microseconds
-                 * and the pipeline simply stops turning over. */
-                m.state = Move::State::Free;
-                m.unit = -1;
-                m.slab_slot = m.pool_slot = m.to_slot = -1;
+                /* Straight to Free, skipping quarantine: a staging copy returns no slot (the
+                 * later Release does, and is quarantined). Quarantining it would only hold the
+                 * record for two more dispatches and stall the prefetch on a real card. */
+                m.clear();
                 continue;
             case Move::Kind::Migrate:
                 us.slab_slot = m.to_slot;
@@ -1671,20 +1546,16 @@ int Mover::retire(HeatEngine* heat) {
             case Move::Kind::Drop:
                 break;
         }
-        /* PUBLISH. Both copies of the bytes are valid at this instant -- the mover wrote a shadow
-         * slot and has not freed the source -- which is what makes this edit safe to make from
-         * this thread with nothing synchronised: whichever side of the write a reader lands on
-         * names bytes that are correct. */
+        /* Safe without synchronisation: both copies of the bytes are valid now (see
+         * Residency::publish). */
         republish(m.unit);
         m.state = Move::State::Published;
     }
 
-    /* QUARANTINE, and it is a SECOND pass on purpose. The slot being freed was named by kernels
-     * issued in earlier layers and those may still be running. Re-recording the move's event on
-     * the COMPUTE stream is the barrier: when it signals, every launch made before the publish
-     * has retired and the slot is safe to write. It has to sit downstream of the publish in
-     * stream order for that sentence to be true, which is why it cannot be folded into the loop
-     * above. A slot reused too early is not a crash -- it is fluent text with a new hash. */
+    /* Quarantine, as a separate pass. Kernels issued in earlier layers may still name the freed
+     * slot. Re-recording the move's event on the compute stream is the barrier: when it signals,
+     * every launch made before the publish has retired and the slot is safe to write. It must be
+     * downstream of the publish in stream order, so it is not folded into the loop above. */
     for (Move& m : moves_) {
         if (m.state != Move::State::Published) continue;
         if (!compute_) {
@@ -1703,22 +1574,12 @@ int Mover::retire(HeatEngine* heat) {
         if (q < 0) return RAD_E_DEVICE;
         if (q == 0) continue;
 
-        UnitState& us = unit_[(size_t)m.unit];
-        ClassPools& cp = pools_[(size_t)us.klass];
-        switch (m.kind) {
-            case Move::Kind::Promote: cp.pool.add_free(m.pool_slot); break;
-            case Move::Kind::Demote:  cp.slab.add_free(m.slab_slot); break;
-            case Move::Kind::Release: cp.slab.add_free(m.slab_slot); break;
-            case Move::Kind::Drop:    cp.slab.add_free(m.slab_slot); break;
-            case Move::Kind::Migrate: cp.slab.add_free(m.slab_slot); break;
-            case Move::Kind::Stage:   break;   /* never reaches here; freed as soon as it lands */
-        }
-        if (heat && (m.kind == Move::Kind::Promote || m.kind == Move::Kind::Demote ||
-                     m.kind == Move::Kind::Drop || m.kind == Move::Kind::Migrate))
-            heat->set_busy(m.unit, false);
-        m.state = Move::State::Free;
-        m.unit = -1;
-        m.slab_slot = m.pool_slot = m.to_slot = -1;
+        /* A Stage record never gets here: it is freed as soon as it lands. */
+        ClassPools& cp = pools_[(size_t)unit_[(size_t)m.unit].klass];
+        if (m.kind == Move::Kind::Promote) cp.pool.add_free(m.pool_slot);
+        else if (m.frees_slab())           cp.slab.add_free(m.slab_slot);
+        if (heat && m.kind != Move::Kind::Release) heat->set_busy(m.unit, false);
+        m.clear();
     }
     count_flex();
     return RAD_OK;
@@ -1733,8 +1594,7 @@ std::string Mover::report() const {
                         (unsigned long long)stats_.demotions,
                         (unsigned long long)stats_.prefetched,
                         (double)stats_.h2d_bytes * gib, (double)stats_.d2h_bytes * gib);
-    /* Supply, not policy. These three are the difference between a mover at its budget and one
-     * that never got to spend it, and without them they look identical from the outside. */
+    /* Supply counters: they separate a mover at its budget from one that never got to spend it. */
     s += fmt("  %llu found no free move record, %llu starved of a slab slot, %llu of a pool "
              "slot; %llu slots quarantined\n",
              (unsigned long long)stats_.no_record, (unsigned long long)stats_.starved_slab,
@@ -1748,8 +1608,8 @@ std::string Mover::report() const {
         s += fmt("  file tier: %llu demand reads (%.2f GiB), each a blocking pread in the middle "
                  "of a dispatch. Raise --host-pool-mib.\n",
                  (unsigned long long)stats_.ssd_reads, (double)stats_.ssd_bytes * gib);
-    /* The routed layers read from the container, and what they cost the issuing thread: read is
-     * the drive, wait is a window whose copies had not drained when it came round again. */
+    /* The file stager's cost to the issuing thread: read is time in the drive, wait is time on a
+     * window whose copies had not drained when it came round again. */
     if (stats_.file_layers) {
         const double rs = (double)stats_.file_read_ns * 1e-9;
         s += fmt("  file stager: %llu routed layers read, %llu units, %.2f GiB in %llu preads; "
diff --git a/core/place/mover.h b/core/place/mover.h
index 83eb2b50..aff35c53 100644
--- a/core/place/mover.h
+++ b/core/place/mover.h
@@ -1,48 +1,33 @@
-/* mover.h -- residency and the mover: the substrate every tier stands on.
+/* mover.h -- residency and the mover: where every weight unit lives and how it moves.
  *
  * Three storage tiers, one address space of slots:
  *
- *   FIXED-STRIDE VRAM SLAB SLOTS PER WEIGHT CLASS. A slot is interchangeable within its class, so
- *   a promotion is an integer swap and not an allocation, and a slab that never fragments is a
- *   slab whose hit rate does not depend on the order promotions happened to arrive in.
+ *   VRAM slab: fixed-stride slots per weight class. Slots within a class are interchangeable, so
+ *   a promotion is an integer swap rather than an allocation, and the slab never fragments.
  *
- *   A PINNED HOST POOL, at the same stride. Pinned rather than pageable because the whole point of
- *   the host tier is that a card can DMA out of it: a device-visible pinned pool is what makes a
- *   non-resident expert a zero-copy read inside the GEMM instead of a bounce-buffer memcpy in
- *   front of it. It is also allocated and owned here rather than read through the container's
- *   mmap, because with an mmap the KERNEL decides what stays resident and under real memory
- *   pressure it decides badly for this workload -- the same reads run several times slower inside
- *   a decode run than in isolation, and MADV_WILLNEED makes it worse, which is the tell that the
- *   faults are not too small and that a hint cannot fix a policy disagreement.
+ *   Pinned host pool, same stride. The card reads a non-resident expert from it zero-copy
+ *   inside the GEMM. It is owned here, not read through the container's mmap, because under
+ *   memory pressure the kernel's paging makes decode reads several times slower, and
+ *   MADV_WILLNEED makes it worse.
  *
- *   A FILE TIER READ WITH O_DIRECT INTO PINNED BUFFERS. Predictable latency, no page-cache
- *   double-copy, and the read lands where the mover can DMA from it without a bounce. A buffered
- *   fallback is refused rather than offered: a tier whose latency is the page cache's mood is not
- *   a tier you can budget against.
+ *   File tier: O_DIRECT reads into pinned buffers, with predictable latency and no page-cache
+ *   copy. No buffered fallback: a tier whose latency depends on the page cache cannot be budgeted.
  *
- * ---- THE ONE PROPERTY EVERYTHING ELSE RESTS ON -----------------------------------------------
+ * ---- Transfers never synchronise the host ----------------------------------------------------
  *
- * THE MOVER RUNS ON A DEDICATED STREAM AND THE COMPUTE STREAM WAITS ON ITS EVENTS. NO HOST
- * SYNCHRONISATION IS INVOLVED IN A TRANSFER. That is what lets placement be dynamic without
- * serialising the step, and it is the difference between MoE offload being unusable and being
- * fast. rad_issue waits with rad_event_wait, never rad_event_sync.
+ * The mover runs on its own stream and the compute stream waits on its events (rad_event_wait,
+ * never rad_event_sync), so placement changes without serialising the step. The lead gate is a
+ * host wait on how far the host runs ahead, not on a transfer (MoverConfig::max_lead_dispatches).
  *
- * The lead gate below IS a host wait, and it is not a contradiction: it throttles how far the
- * host runs ahead of the cards. It is a SUPPLY mechanism, not a transfer synchronisation, and the
- * reason it exists is spelled out at MoverConfig::max_lead_dispatches.
+ * ---- Shadow slots and quarantine -------------------------------------------------------------
  *
- * ---- SHADOW SLOTS AND QUARANTINE -------------------------------------------------------------
+ * A promotion copies into a shadow slot (allocated, holding nothing) and only then publishes the
+ * new pointer, so a slot is never overwritten while a kernel may read it. Getting this order
+ * wrong does not crash; it produces fluent output that differs from run to run.
  *
- * A promotion writes into a SHADOW slot -- a slab slot that is allocated but holds nothing -- and
- * only then publishes the new pointer. So a live slot is never DMA'd over while a kernel might
- * still be reading it, and a promotion never invalidates a pointer the run phase is already
- * holding. Getting that ordering wrong does not crash: it produces fluent output with a different
- * hash every run, which is the single most expensive bug class in this design.
- *
- * The freed slot then goes into QUARANTINE rather than straight back to the free list, because
- * kernels issued in earlier layers still name its old address. The barrier is an event recorded
- * on the COMPUTE stream after the publish; when it signals, every launch that could still name
- * the slot has retired.
+ * A freed slot goes into quarantine, because kernels issued in earlier layers still name it. The
+ * barrier is an event recorded on the compute stream after the publish; when it signals, every
+ * launch that could name the slot has retired.
  */
 #pragma once
 #include "../device/device.h"
@@ -61,49 +46,27 @@
 namespace rad {
 
 /* ------------------------------------------------------------------ slot bookkeeping */
-/* Pure host state, no device call in it, so the whole supply half is testable without a card.
- * Used for both the VRAM slab and the pinned host pool -- they are the same structure with
- * different backing memory, and writing it twice is how two free lists come to disagree about
- * what a slot index means.
+/* Free-list bookkeeping for the VRAM slab and the pinned host pool. Pure host state, testable
+ * without a card.
  *
- * ---- SEGMENTS: ONE RANGE FOR THE SLAB'S OWN SLOTS, ONE FOR EACH LENDER ------------------------
+ * Slots are numbered in segments laid end to end. Segment 0 is the budgeted range; each later
+ * one is memory another pool lends (KV cache blocks, the arena's top). Each segment has its own
+ * target, below which slots may be handed out, because lenders reclaim independently.
  *
- * The slots are numbered in SEGMENTS laid end to end. Segment 0 is the budgeted range the pool
- * was built with; every later one is a stretch of another pool's memory lent to this one -- the
- * KV cache's blocks, the activation arena's top -- added once its addresses are known. Each
- * segment has its own TARGET: the slots below it are the ones that may be handed out, and a
- * lender moves only its own. Two lenders cannot share one target, because what one of them can
- * spare says nothing about the other: the arena takes its memory back for every prefill while the
- * cache is still lending, and a single mark over both would either hold the arena's slots past its
- * recall or give up the cache's with it.
+ * The lowest free slot goes first, so occupied slots pack toward a segment's bottom and its top
+ * can be returned; a LIFO would keep handing out high slots. `live` is how far a segment's slots
+ * exist and `target` how far they should: a shrink lowers `live` only past unheld slots, so it
+ * never evicts.
  *
- * ---- WHY THE LOWEST FREE SLOT, AND WHY A LIVE MARK -------------------------------------------
- *
- * A lent segment is VRAM its owner can want back, and it has to be handed back when it does. That
- * is only possible if the occupied slots pack toward the BOTTOM of the segment, so its top is free
- * to retire. Handing out the lowest free slot is what packs them; a LIFO stack hands back the slot
- * released most recently, which after a busy period is exactly the high slot the pool wants to
- * give up, and the mark would never fall.
- *
- * A segment's `live` is how far its slots exist right now and `target` how far they should. They
- * differ while a shrink waits on the units still sitting above the target: the mark stops at the
- * highest slot something holds, so shrinking can never evict -- it only declines to hand a slot
- * out again.
- *
- * THE FREE LIST IS REBUILT WHENEVER A TARGET MOVES, from the held flags, and holds exactly the
- * covered slots nothing holds. Carried across a shrink and a regrow instead, it lists only some of
- * the slots the shrink dropped -- a slot freed while it sat above the target is never pushed, and
- * one the heap still held is discarded by the first take() that walks past it -- and a regrow
- * that trusts it never hands the others out again. The rebuild is a scan of the capacity at the
- * arbiter's cadence; take() and add_free, which the mover calls several times a dispatch, stay
- * heap operations.
+ * The free list is rebuilt from the held flags whenever a target moves; one carried across a
+ * shrink and regrow would lose slots freed above the target. take() and add_free() stay heap
+ * operations.
  */
 class SlotPool {
 public:
-    /* `n_live` slots exist in segment 0 and every one of them is HELD until add_free says
-     * otherwise, which is what the plan's resident set is. `n_cap` is how far segment 0 may ever
-     * grow -- address space the caller has reserved and will back on demand -- and defaults to no
-     * growth at all. */
+    /* Segment 0 starts with `n_live` slots, all held (the plan's resident set) until add_free()
+     * releases them. `n_cap` is how far segment 0 may grow into address space the caller has
+     * reserved and backs on demand; the default is no growth. */
     void init(int64_t n_live, int64_t stride, int64_t n_cap = -1) {
         stride_ = stride;
         n_ = n_cap > n_live ? n_cap : n_live;
@@ -122,9 +85,7 @@ public:
         n_ += n_slots;
         return (int)segs_.size() - 1;
     }
-    int     n_segments() const { return (int)segs_.size(); }
     int64_t seg_lo(int k) const { return segs_[(size_t)k].lo; }
-    int64_t seg_hi(int k) const { return segs_[(size_t)k].hi; }
 
     void add_free(int64_t slot) {
         if (slot < 0 || slot >= n_) return;
@@ -145,53 +106,37 @@ public:
     int64_t capacity() const { return n_; }
     int64_t stride() const { return stride_; }
     int64_t n_free() const { return n_usable_; }
-    /* Slots something is in: a resident unit, a staged one, or a copy still in flight. The
-     * number the fill and drain decisions are made against, because the working slots have to
-     * stay free whatever the target is. */
+    /* Slots in use: a resident unit, a staged one, or a copy in flight. Fill and drain decide
+     * against this, because the working slots must stay free whatever the target is. */
     int64_t held() const { return n_held_; }
     /* Where segment `k`'s covered slots end, as a slot number. */
     int64_t target(int k = 0) const { return segs_[(size_t)k].target; }
-    /* May this slot be handed out -- is it below its segment's target? */
+    /* Whether `slot` is below its segment's target, i.e. may be handed out. */
     bool covered(int64_t slot) const {
         if (slot < 0 || slot >= n_) return false;
         return slot < segs_[(size_t)seg_of(slot)].target;
     }
-    /* -1 when there is none. A caller that treats that as "try again next dispatch" is right;
-     * one that treats it as an error is wrong -- slot starvation is the normal steady state. */
-    int64_t take() {
-        while (!free_.empty()) {
-            std::pop_heap(free_.begin(), free_.end(), std::greater());
-            const int64_t s = free_.back();
-            free_.pop_back();
-            if (!covered(s) || held_[(size_t)s]) continue;   /* never a slot to hand out */
-            held_[(size_t)s] = 1;
-            ++n_held_;
-            --n_usable_;
-            return s;
-        }
-        return -1;
-    }
+    /* The lowest free covered slot, or -1. Starvation is the normal steady state: callers retry
+     * on a later dispatch rather than treat -1 as an error. */
+    int64_t take() { return take_at_least(0); }
 
-    /* Where segment `k`'s covered slots should end, as a slot number inside it. Growing is
-     * immediate -- the caller has already backed the memory. Shrinking is a statement of intent:
-     * the mark falls as far as the slots nothing holds allow, and the rest follows as those
-     * retire. */
+    /* Sets where segment `k`'s covered slots end, as a slot number inside it. Growing is
+     * immediate (the caller has already backed the memory). Shrinking lowers `live` only past
+     * slots nothing holds; the rest follows as those are released. */
     void set_target(int64_t target) { set_target(0, target); }
     void set_target(int k, int64_t target) {
         Seg& g = segs_[(size_t)k];
         g.target = target < g.lo ? g.lo : (target > g.hi ? g.hi : target);
-        /* Nothing ever holds a slot at or past the mark -- take() hands out only covered slots,
-         * and the mark never falls past a held one -- so a set flag there only says the slot has
-         * never existed. */
+        /* Nothing holds a slot at or past `live` (take() hands out only covered slots and `live`
+         * never falls past a held one), so a set flag there only means the slot never existed. */
         for (int64_t s = g.live; s < g.target; ++s) held_[(size_t)s] = 0;
         if (g.target > g.live) g.live = g.target;
         else settle(g);
         rebuild();
     }
 
-    /* take(), restricted to slots at or above `lo`. The slots below it that are free stay free
-     * and stay listed; there are at most the working slots of them, so this is a handful of heap
-     * operations. */
+    /* take(), restricted to slots >= `lo`. Free slots below `lo` stay listed; there are at most
+     * the working slots of them, so this is a few heap operations. */
     int64_t take_at_least(int64_t lo) {
         std::vector keep;
         int64_t got = -1;
@@ -213,8 +158,8 @@ public:
         }
         return got;
     }
-    /* take(), restricted to the free slots `want` accepts: the lowest of them, or -1. A scan of
-     * the free list, which holds the slots on their way back through a swap -- a few dozen. */
+    /* take(), restricted to the lowest free slot `want` accepts, or -1. A linear scan; the free
+     * list holds only slots passing through a swap, a few dozen. */
     template  int64_t take_where(Want want) {
         size_t best = free_.size();
         for (size_t i = 0; i < free_.size(); ++i) {
@@ -232,8 +177,8 @@ public:
         --n_usable_;
         return s;
     }
-    /* The highest slot of segment `k` something holds -- a unit, a copy in flight, a slot in
-     * quarantine -- or -1. A scan down from the segment's mark. */
+    /* The highest held slot of segment `k` (a unit, a copy in flight, a quarantined slot), or
+     * -1. Scans down from `live`. */
     int64_t top_held(int k = 0) const {
         const Seg& g = segs_[(size_t)k];
         for (int64_t s = g.live; s-- > g.lo;)
@@ -277,43 +222,34 @@ private:
 };
 
 /* ------------------------------------------------------------------ the file tier */
-/* A thin skin over the device layer's DirectFile, which is where the O_DIRECT mechanics live and
- * where they belong: the prefix cache reads the same way for the same reasons, and two
- * implementations of "align the offset, the length and the buffer" is two places for the
- * alignment rule to drift. What this adds is the tier's own accounting -- a file-tier read is a
- * blocking pread in the middle of a dispatch and the counter is how a run that leans on it stops
- * being a mystery in the throughput. */
+/* A thin wrapper over the device layer's DirectFile, which owns the O_DIRECT alignment rules
+ * (the prefix cache reads the same way). This adds the tier's accounting: a file-tier read is a
+ * blocking pread inside a dispatch, and the counters make its cost visible. */
 class FileTier {
 public:
-    /* O_DIRECT, and a refusal rather than a buffered fallback: a tier whose latency is the page
-     * cache's mood is not a tier you can budget against. `path` is the container. */
+    /* Opens the container `path` with O_DIRECT; refuses rather than fall back to buffered reads,
+     * whose latency cannot be budgeted. */
     int  open(const std::string& path);
     bool ok() const { return f_.is_open(); }
     void close() { f_.close(); }
 
-    /* One expert-sized read into a pinned buffer. Blocking, counted, and a cliff: a dispatch that
-     * meets a file-tier unit stops until the read returns. That is the price of a bet the plan
-     * made -- give the cold tail to disk and buy a host pool big enough to hold a working set
-     * that can actually move -- paid in full each time the bet is wrong. What changes in response
-     * is the plan, not this function. */
+    /* One expert-sized read into a pinned buffer. Blocking and counted: a dispatch that meets a
+     * file-tier unit stalls until the read returns. This is the cost the plan accepted by putting
+     * the cold tail on disk; frequent reads call for a different plan, not a change here. */
     int  read(uint64_t offset, int64_t bytes, void* pinned_dst, int64_t dst_cap);
 
-    /* Every RadFileEntry offset is RAD_ALIGN_UNIT-aligned by construction (rad_format.h) and that
-     * is DirectFile's alignment, so the mover's reads take the path with no bounce in it. */
+    /* RadFileEntry offsets are RAD_ALIGN_UNIT-aligned (rad_format.h), which is DirectFile's
+     * alignment, so the mover's reads need no bounce buffer. */
     static int64_t direct_align(int64_t v) { return align_up(v, DirectFile::alignment()); }
 
-    uint64_t reads() const { return reads_; }
-    uint64_t bytes_read() const { return bytes_; }
-
 private:
     DirectFile f_;
-    uint64_t   reads_ = 0, bytes_ = 0;
 };
 
 /* ------------------------------------------------------------------ residency */
 class Residency final : public ResidencyTable {
 public:
-    void init(const Program& prog, const Plan& plan);
+    void init(const Program& prog);
 
     const WeightSlot* lookup(rad_weight w) const override {
         return (size_t)w < slot_.size() ? &slot_[w] : nullptr;
@@ -325,14 +261,11 @@ public:
         changed_.clear();
     }
 
-    /* The only two writers, and BOTH BUMP THE GENERATION. `publish` settles a slot -- the bytes
-     * are there, nothing to wait on. `begin_transfer` opens one: a copy into `ptr` is in flight
-     * and `ready` is the event the compute stream must be ordered behind.
-     *
-     * begin_transfer bumping is the part that is easy to get wrong and expensive to debug. The
-     * run phase memoises the wait per generation, so installing a new event at the old generation
-     * makes it skip the wait entirely (residency_iface.h). */
-    void publish(rad_weight w, void* ptr);
+    /* The only two writers; both bump the generation. publish() settles a slot; begin_transfer()
+     * marks a copy into `ptr` in flight that the compute stream must wait on (`ready`). The run
+     * phase memoises its wait per generation, so a new event at an old generation would be
+     * skipped (residency_iface.h). */
+    void publish(rad_weight w, void* ptr) { begin_transfer(w, ptr, nullptr); }
     void begin_transfer(rad_weight w, void* ptr, RadEvent ready);
     void settle(rad_weight w) {
         if ((size_t)w >= slot_.size()) return;
@@ -355,51 +288,34 @@ private:
 
 /* ------------------------------------------------------------------ configuration */
 struct MoverConfig {
-    /* Shadow slots and the staging ring are NOT here. They are budgeted by the planner out of
-     * the weights pool and reported in the plan (SlabClass::n_shadow, n_stage), and a second
-     * knob for the same quantity is a second number for the mover and the operator to disagree
-     * about -- with an overrun as the direction that disagreement goes wrong in.
+    /* Shadow and staging slot counts come from the plan (SlabClass::n_shadow, n_stage), which
+     * budgets them; a second knob here could only cause an overrun.
      *
-     * ---- HOW FAR THE HOST MAY RUN AHEAD OF THE CARDS, IN LAYER DISPATCHES --------------------
-     *
-     * 0 is unbounded, and unbounded STARVES THE MOVER. A freed slot returns to the free list only
-     * after its quarantine event signals, and that event is on the COMPUTE stream -- so the
-     * recycle latency is however deep that stream happens to be queued, and the move rate is
-     * `shadow slots / recycle latency`. Let the host run and the stream carries a whole step's
-     * work, and almost every round finds no free slot to move into. The guard is not what binds;
-     * the engine simply never gets the supply to spend.
-     *
-     * Holding the host near the cards is therefore not a latency measure but a SUPPLY one. 2 is
-     * the smallest depth that recovers the effect while leaving the issue path a dispatch of
-     * margin. A coarser gate -- per step rather than per layer dispatch -- does nothing, because
-     * one step is already the whole model's worth of queued work; the granularity has to be the
-     * layer. */
+     * How far the host may run ahead of the cards, in layer dispatches. A freed slot recycles
+     * only when its quarantine event on the compute stream signals, so the move rate is shadow
+     * slots / compute queue depth; 0 (unbounded) queues a whole step and starves the mover. 2 is
+     * the smallest depth that keeps slots recycling with a dispatch of issue margin. A per-step
+     * gate does nothing, since one step is already the whole model's queued work. */
     int max_lead_dispatches = 2;
 
-    /* Lent slots kept free for swaps to land in, a slab class (planner.h's
-     * RAD_PLACE_TURNOVER_SLOTS; Mover::balance keeps them). A knob here and not in the plan because the planner charges
-     * nothing for them: they are the KV cache's memory, free only while it lends. A class whose
-     * shadow slots the quarter-of-the-slab cap cut keeps at most the same multiple of them, so a
-     * small loan is not left emptier than it is filled. */
+    /* Lent slots per slab class kept free for swaps to land in (Mover::balance). A knob rather
+     * than a plan field because the planner charges nothing for them: they are KV cache memory,
+     * free only while it lends. A class whose shadow slots the quarter-of-the-slab cap reduced
+     * gets proportionally fewer, so a small loan is not left emptier than it is filled. */
     int turnover_slots = RAD_PLACE_TURNOVER_SLOTS;
 
-    /* The container, for the file tier. Empty means there is no file tier and a unit the planner
-     * put there is an error rather than a slow path. */
+    /* The container, for the file tier. Empty means no file tier; a unit planned there is then
+     * an error. */
     std::string container_path;
-    /* Pinned staging buffers for file-tier reads. Each is one class stride, and the count is the
-     * planner's -- RAD_PLACE_FILE_STAGE_SLOTS, which is what the operator was charged for out of
-     * --host-pool-mib. A separate default here would be a second number for one allocation. */
+    /* Pinned staging buffers for file-tier reads, one class stride each; the count the planner
+     * charged to --host-pool-mib. */
     int stage_slots = RAD_PLACE_FILE_STAGE_SLOTS;
 };
 
 /* ------------------------------------------------------------------ the loan */
-/* ONE STRETCH OF ANOTHER POOL'S VRAM THAT MAY BE LENT TO THE SLAB, described from its top down.
- *
- * The owner keeps it backed and lends it from the top downwards, and it states how much it has
- * lent in its own measure -- tokens, for the KV cache -- so the mover can tell which slots a loan
- * covers without knowing what the owner stores there. `unit_bytes` of the stretch are one unit of
- * that measure and a unit is `unit_tokens` tokens: a loan of T tokens is the top
- * floor(T / unit_tokens) * unit_bytes bytes of every stretch. */
+/* One stretch of another pool's VRAM that may be lent to the slab. The owner keeps it backed,
+ * lends from the top down and states the loan in its own measure (tokens, for the KV cache). A
+ * loan of T tokens is the top floor(T / unit_tokens) * unit_bytes bytes of every stretch. */
 struct LoanStrip {
     char*   top = nullptr;       /* one past the stretch's highest byte */
     int64_t bytes = 0;           /* how far below `top` it runs */
@@ -412,29 +328,23 @@ struct MoverStats {
     uint64_t promotions = 0, demotions = 0;
     uint64_t h2d_bytes = 0, d2h_bytes = 0;
     uint64_t prefetched = 0, prefetch_bytes = 0;
-    /* Why a move did not go out. `no_record` is every in-flight move record busy -- the shadow
-     * slots, still waiting on their copies. The two `starved` counts are the free lists empty.
-     * Without these a starved mover is indistinguishable from a satisfied one. */
+    /* Why a move did not go out: every move record busy, or a free list empty. These separate a
+     * starved mover from a satisfied one. */
     uint64_t no_record = 0, starved_slab = 0, starved_pool = 0;
     uint64_t quarantined = 0;
-    /* Demotions that copied nothing: the unit sat in a lent slot and kept its host copy, so going
-     * back to the host tier was a change of address. Counted inside `demotions` as well. */
+    /* Demotions out of a lent slot that copied nothing (the unit kept its host copy). Also
+     * counted in `demotions`. */
     uint64_t dropped = 0;
-    /* Host copies a unit in a lent slot gave to a budgeted victim that had no pool slot to go to
-     * (Mover::donor_slot), and such units moved rather than dropped when their loan was recalled
-     * or shrank. `stranded` counts the recalls that found no free slot for one of them: it stayed
-     * past the loan until a later recall or balance() moved it. */
+    /* Host copies given to budgeted victims (Mover::donor_slot); donors moved rather than
+     * dropped by a recall or shrink; recalls that found no free slot for a donor. */
     uint64_t donated = 0, relocated = 0, stranded = 0;
     uint64_t ssd_reads = 0, ssd_bytes = 0;
-    /* The prefill stager's copies (stage_units): layers staged, units and bytes copied, and
-     * pooled units a buffer had no room left for -- those were read across the link in place.
-     * `stage_copies` is how many copies carried the units: neighbouring pool slots go as one. */
+    /* The prefill stager (stage_units). `stage_overflow`: units no buffer had room for, read in
+     * place. `stage_copies`: copies issued; neighbouring pool slots go as one. */
     uint64_t stage_layers = 0, staged_units = 0, staged_bytes = 0, stage_overflow = 0;
     uint64_t stage_copies = 0;
-    /* The file stager's reads (stage_file_units): routed layers read from the container, the
-     * units and bytes they carried, the preads that carried them, and the host time spent inside
-     * those reads and waiting for a window's copies to drain -- the two halves of what a step
-     * that reads the drive costs the thread issuing it. */
+    /* The file stager (stage_file_units), including the host time spent in preads and waiting
+     * for a window's copies to drain. */
     uint64_t file_layers = 0, file_units = 0, file_bytes = 0, file_preads = 0;
     uint64_t file_read_ns = 0, file_wait_ns = 0;
 };
@@ -447,137 +357,97 @@ public:
     Mover(const Mover&) = delete;
     Mover& operator=(const Mover&) = delete;
 
-    /* Allocates every pool the plan asked for and lays every unit into a slot. Does NOT read a
-     * byte of the model: the load phase fills the addresses this hands it. Returns RAD_E_NOMEM
-     * naming the pool that failed, because "out of memory" without which pool is not a
-     * diagnosis.
+    /* Allocates every pool the plan asks for and assigns every unit a slot; the load phase fills
+     * the published addresses. On RAD_E_NOMEM the log names the pool.
      *
-     * `budget` IS THE PRODUCTION PATH AND SHOULD ALWAYS BE PASSED. Pools already allocated
-     * the weights pool as one block; a mover that called rad_dev_alloc beside it would spend
-     * that budget TWICE and the overrun would surface as an out-of-memory from an unrelated
-     * launch much later. Reserving from Pools::weights() is also what makes it structurally
-     * impossible for a promotion to reach a KV block -- there is no path from the weights pool to
-     * the KV pool (mem/pools.h), which is the whole reason the weight slab is a fixed budget.
-     *
-     * Null is the standalone-test path and says so at Warn. It is not a supported deployment. */
+     * Always pass `budget`: Pools already reserved the weights pool, so allocating beside it
+     * spends the budget twice, and reserving from Pools::weights() keeps promotions out of KV
+     * blocks (mem/pools.h). Null is the standalone-test path and logs a warning. */
     int init(const Program& prog, const Plan& plan, const MoverConfig& cfg, Pools* budget = nullptr);
 
-    /* The compute stream this rank issues on. The mover's transfers are ordered against it and
-     * the quarantine barrier is recorded on it, so without one the mover refuses to move rather
-     * than storing a table edit blind. */
+    /* The compute stream this rank issues on. Transfers are ordered against it and the
+     * quarantine barrier is recorded on it; without one the mover refuses to move. */
     int bind_compute_stream(RadStream s);
 
-    /* THE MAINTENANCE STREAM, AND WHY ANYTHING ELSE MAY HAVE IT.
+    /* The mover's stream, to be shared by any subsystem moving bytes off the critical path. Each
+     * HIP stream costs a hardware queue, and on RDNA4 a fourth one is expensive: on two R9700s
+     * serving Flash-Next, an idle fourth stream takes the decode step from 20.5 to 33.9 ms
+     * (GPU_MAX_HW_QUEUES 1-3 are fine, 4 and 8 are not). The engine already uses three (compute,
+     * the second compute lane, this one).
      *
-     * A HIP stream costs a hardware queue, and on RDNA4 a fourth concurrent queue is not a small
-     * cost: on a two-card R9700 Flash-Next server, a fourth stream that never carries a single
-     * byte takes the decode step from 20.5 ms to 33.9 (GPU_MAX_HW_QUEUES 1, 2 or 3 all run at
-     * full speed; 4 and 8 do not). The engine already issues on three -- compute, the second
-     * compute lane, and this one -- so a subsystem that wants a stream to move bytes off the
-     * critical path must TAKE THIS ONE rather than make a fourth.
-     *
-     * Null before init(), and null on a rank with nothing to move. A caller that gets null must
-     * fall back to its own stream: three streams is under the cliff either way.
-     *
-     * THE MOVER'S RUN PHASE ISSUES ON IT, so this stream is not idle: a sharer queueing a hundred
-     * megabytes on it will sit in front of a transfer the compute stream is waiting on. Gate the
-     * two -- do not answer it by making a fourth queue. */
+     * Null before init() and on a rank with nothing to move; the caller then uses its own stream.
+     * The run phase issues here too, so a sharer's large copy delays transfers the compute stream
+     * waits on; gate the two rather than add a queue. */
     RadStream transfer_stream() const { return mover_; }
 
     ResidencyTable* residency() { return &res_; }
-    /* THE ONE ADDRESS THE MOVER DOES NOT OWN. A Tier::Mapped weight lives in the container's
-     * mapping and the LOAD PHASE is what holds the RadFile, so it publishes the pointer and the
-     * mover only records it -- the residency table is the mover's, and a second table would be a
-     * second answer to "where is this weight". Nothing here ever moves it afterwards: a mapped
-     * unit has no slab class, so unit_base() has no address of its own to republish over this. */
+    /* For Tier::Mapped weights, which live in the container mapping the load phase holds: the
+     * one address the mover does not own, recorded so the residency table stays the only record
+     * of weight addresses. A mapped unit has no slab class, so nothing republishes over it. */
     void publish_mapped(rad_weight w, void* p) { res_.publish(w, p); }
 
     /* ---- the run phase, in the order a layer dispatch calls it -----------------------------
      *
-     * begin_dispatch  retire whatever landed, gate the host's lead, record the ordering event
-     * prefetch_to_op  release what this op has finished with, then start everything the exact
-     *                 schedule says is due -- and keep starting, as long as slots are free
+     * begin_dispatch  retire what landed, gate the host's lead, record the ordering event
+     * prefetch_to_op  release what this op has finished with, then start every transfer the
+     *                 exact schedule says is due, while slots are free
      * issue           one heat proposal
      *
-     * There is no end_dispatch, and the absence is deliberate. The quarantine barrier belongs
-     * DOWNSTREAM of the publish in stream order, and begin_dispatch's retire() is exactly that
-     * point: by the time it runs, every launch the previous dispatch made has been issued. A
-     * symmetric end-of-dispatch hook would record the barrier before those launches and the
-     * quarantine would be satisfied for a reason that has nothing to do with the kernels it is
-     * guarding.
+     * There is deliberately no end_dispatch: the quarantine barrier must be recorded downstream
+     * of the previous dispatch's launches, which begin_dispatch's retire() is.
      *
-     * ---- A CALLER MUST DO ALL OF IT, EVERY DISPATCH -------------------------------------------
+     * A caller must issue as well as retire every dispatch. The pool free list starts empty, so a
+     * loop that only retires promotes into the shadow slots once and never demotes; on the host
+     * backend copies land within their dispatch, so this shows only on a real card. The compute
+     * stream must also carry the dispatch's real work, or the quarantine barrier and the lead
+     * gate are meaningless.
      *
-     * begin_dispatch only RETIRES; it never starts anything. A loop that retires without issuing
-     * is not a slower engine, it is a stuck one: the pool free list starts empty, so the first
-     * round can only promote out of the shadow slots, and the pool slot that promotion frees
-     * arrives several dispatches later -- by which time, if nothing is asking, the resident set
-     * has grown by the shadow count and never shrinks again. The symptom is zero demotions
-     * forever, and it appears only on a real card: on the host backend every copy lands inside
-     * the dispatch that issued it, so the same mistake passes unnoticed.
-     *
-     * The compute stream must also carry the dispatch's actual work. The quarantine barrier is an
-     * event on that stream and its claim is "every kernel that could still name this slot has
-     * retired"; against an empty stream the claim is vacuous and the lead gate paces nothing.
+     * In production, begin_dispatch and issue run once a step from Engine::tiering_dispatch,
+     * since the mover relocates only between steps (Ctx::run_step syncs the residency table at
+     * its top). prefetch_to_op is called only by tests/place_test.cpp; the
+     * exact-schedule path is kept built and tested deliberately.
      */
-    /* `begin_dispatch` and `issue` are the engine's, once a step: Engine::tiering_dispatch is the
-     * seam, and it is a step and not a layer because the mover relocates BETWEEN steps and never
-     * during one (runtime/ctx.cpp honours `weights_dirty_` once, at the top of run_step).
-     *
-     * `prefetch_to_op` has no caller but tests/place_test.cpp, and that is DELIBERATE -- the
-     * exact-schedule path is kept built and tested rather than deleted and rewritten later. Do
-     * not read "no caller" there as the dead-surface shape it resembles elsewhere in this tree. */
     int begin_dispatch(int dispatch, HeatEngine* heat);
     int prefetch_to_op(int32_t op_index);
     int issue(const Swap& s, HeatEngine* heat);
 
     /* ---- the loan: VRAM another pool is not using ------------------------------------------
      *
-     * VRAM some other pool carved and is not using is worth more here than it is there: an
-     * expert unit that does not fit the slab is read across the link on the critical path of
-     * every step that routes to it. The KV cache keeps its whole carve backed and LENDS the slab
-     * the part nothing holds, and the activation arena lends the part a step smaller than the
-     * largest one does not reach -- each at addresses it already owns, so the slab grows into
-     * that memory with no allocation, no mapping and no driver call, and gives it back the same
-     * way. The ONLY caller that may lend is the one that arbitrates the whole card: two callers
-     * with two opinions about how much is spare is the same memory in two pools.
+     * An expert that does not fit the slab is read across the link on every step that routes to
+     * it, so unused VRAM elsewhere is lent to the slab: the part of the KV cache's carve nothing
+     * holds, and the part of the activation arena that steps smaller than the largest do not
+     * reach. Both are addresses the lender already owns, so no allocation or mapping is involved.
+     * Only the caller that arbitrates the whole card may lend.
      *
-     * EACH LENDER LENDS IN ITS OWN MEASURE, into its own segment of the slab (SlotPool): the KV
-     * cache in tokens, the arena in bytes. They move independently -- a prefill takes the arena's
-     * memory back while the cache goes on lending -- so every call names the lender it is about.
+     * Each lender lends in its own measure (KV cache: tokens; arena: bytes) into its own slab
+     * segment, and they move independently, so every call names its lender.
      *
-     * A UNIT IN A LENT SLOT KEEPS ITS HOST COPY. Weights never change, so the pinned pool slot it
-     * was promoted from still holds exactly its bytes, and giving the slot back is a change of
-     * address rather than a copy across the link. That is what makes a loan cheap to recall:
-     * the cache waits for kernels to stop naming the slot, never for bytes to move. */
+     * A unit in a lent slot keeps its host copy (weights never change), so giving the slot back
+     * is a change of address: a recall waits only for kernels to stop naming the slot. */
 
     enum Lender { kLendKV = 0, kLendArena = 1, kLenders = 2 };
 
-    /* The stretches a lender may ever lend, once per lender, after its memory is carved. Carves
-     * every stretch into slots of each class's stride from the top down, so the slots a small loan
-     * covers are the ones a large loan covers first, and the slot a loan gives back first is the
-     * deepest. */
+    /* Registers the stretches a lender may ever lend; once per lender, after its memory is
+     * carved. Each stretch is cut into slots of each class's stride from the top down, so a small
+     * loan covers a prefix of a large loan's slots and the deepest slot is given back first. */
     int     lend_from(int lender, const std::vector& strips);
 
-    /* HOW MUCH A LENDER LENDS, in its own measure. A TARGET, not a transaction: slots the loan
-     * newly covers can be filled at once, while slots it no longer covers are emptied as their
-     * units are dropped and their quarantine clears -- `loan_held` is how far down the lender's
-     * memory the slab still reaches, and the lender may not use those bytes again until it has
-     * fallen. */
+    /* How much a lender lends, in its own measure. A target, not a transaction: newly covered
+     * slots can be filled at once, while uncovered ones empty as their units drop and their
+     * quarantine clears. loan_held() is how far into the lender's memory the slab still reaches;
+     * the lender may not reuse those bytes until it has fallen to the loan. */
     int     set_loan(int lender, int64_t amount);
     int64_t loan_held(int lender) const;
     int64_t loan(int lender) const { return loan_[lender]; }
 
-    /* THE SAME, NOW, for a lender that cannot wait: every unit past `amount` is dropped to its
-     * host copy and both streams that can touch a slot are drained before this returns, so the
-     * memory is the lender's the moment it does. A host wait, taken only when the lender needs
-     * more than it kept in hand -- a request larger than the cache's buffer, a step larger than
-     * the arena's lent level allows. */
+    /* set_loan(), completed before returning: units past `amount` are dropped to their host
+     * copies and both streams drained. A host wait, for when the lender needs more than it kept
+     * in hand (a request larger than the cache's buffer, a step larger than the arena allows). */
     int     reclaim(int lender, int64_t amount, HeatEngine* heat);
 
-    /* What the lent slots hold and what the loan offers, in bytes, and every slot the stretches
-     * could ever hold. Read by the HTTP thread for the dashboard, hence stored rather than
-     * computed from the slot pools, which only this thread may walk. */
+    /* Bytes the lent slots hold, bytes the loans offer, and bytes every carved slot could hold.
+     * The first two are stored because the HTTP thread reads them for the dashboard and only the
+     * rank thread may walk the slot pools. */
     int64_t flex_used_bytes() const { return flex_used_.load(std::memory_order_relaxed); }
     int64_t flex_offered_bytes() const { return flex_offered_.load(std::memory_order_relaxed); }
     int64_t flex_capacity() const;
@@ -588,33 +458,25 @@ public:
         for (const ClassPools& cp : pools_) n += cp.n_turn;
         return n;
     }
-    /* THE LOAN PAST WHICH NOTHING MORE WOULD BE USED, in the lender's measure: the one that
-     * covers every slot carved from it. The slots were carved no deeper than the units the host
-     * pool holds, so a loan this size already has room for every unit that could move -- more VRAM
-     * from the lender would sit empty. Zero with nothing carved. */
+    /* The loan that covers every slot carved from this lender; more would sit empty. Zero when
+     * nothing is carved. */
     int64_t loan_ceiling(int lender) const;
 
-    /* FILL EVERY SLOT THERE IS ROOM IN, AND EMPTY EVERY SLOT THE LOAN NO LONGER COVERS -- the
-     * half-swaps the heat engine never proposes, because its decision is a COMPARISON and a
-     * comparison needs a victim. Not bounded by a count: a slot left empty while a unit streams
-     * across the link is VRAM bought and wasted on every step, so every free slot past the
-     * turnover slots is filled in one call, hottest units first, and the copies run at the rate
-     * the link carries them. The turnover slots are left free because the engine's swaps land in
-     * them; filled, they would cap the move rate at what the shadow slots alone allow. When fewer
-     * than the working and turnover slots are free, the coldest lent units are dropped until
-     * enough are -- a change of address, never a copy.
+    /* Fills free lent slots and empties slots the loan no longer covers: the half-swaps the heat
+     * engine never proposes, since its decisions need a victim. Every free slot past the turnover
+     * slots is filled in one call, hottest units first, since an empty slot wastes VRAM every
+     * step. The turnover slots stay free for the engine's swaps; filled, they would cap the move
+     * rate at the shadow slots. When fewer than the working plus turnover slots are free, the
+     * coldest lent units are dropped (an address change, never a copy).
      *
-     * `turnover` false treats the turnover slots as room, filled like any other: a step bound by
-     * its own staging copies swaps nothing (Engine::tiering_dispatch), and every unit resident is
-     * one its stager does not copy. The next call with it true drops them back out. */
+     * `turnover` false fills the turnover slots too, for steps bound by their own staging copies
+     * (Engine::tiering_dispatch); the next call with true drops them back out. */
     int balance(HeatEngine* heat, bool turnover = true);
 
-    /* balance() for a rank with no step to ride on. Retires what has landed and fills what is
-     * free, so a loan made while the server is idle is filled before the next request rather
-     * than by it -- the turnover slots too while they are held. Only while the rank thread is
-     * parked. */
+    /* retire() then balance() for an idle rank, so a loan made while idle is filled before the
+     * next request. Call only while the rank thread is parked. */
     int idle_tick(HeatEngine* heat);
-    /* Whether idle ticks keep the turnover slots filled: the engine holds them through a prompt
+    /* Whether idle ticks keep the turnover slots filled; the engine holds them through a prompt
      * and the few steps after it (Engine::tiering_dispatch). */
     void hold_turnover(bool held) { hold_turnover_ = held; }
     /* Each class's pinned pool as the card addresses it: [lo, hi) and the unit stride. At most `max`. */
@@ -634,30 +496,23 @@ public:
      * unit that has not been staged. */
     void* unit_base(int32_t unit) const;
 
-    /* ---- STAGING WITHIN A PASS: the prefill stager (core/place/stager.h) ----------------------
+    /* ---- staging within a pass: the prefill stager (core/place/stager.h) ----------------------
      *
-     * Everything else the mover does happens between steps, and a unit's address is fixed for the
-     * length of a step. These two are the exception, and they change only the PUBLISHED address,
-     * never where a unit lives: the unit stays in its pinned pool slot, and for one routed layer's
-     * ops the run phase reads a copy of it in a buffer the caller owns.
+     * The only calls that change a unit's address within a step, and only the published one: the
+     * unit stays in its pinned pool slot, and one routed layer's ops read a copy in a
+     * caller-owned buffer.
      *
-     * stage_units   copy every unit of `units` that lives in the pinned pool, has no slab slot and
-     *               has no copy of its own in flight into `dst`, one after another at the allocation
-     *               unit, until `cap` has no room for the next -- on the mover's stream, behind
-     *               `after` when it is not null, with `done` recorded behind the last copy. Each
-     *               copied unit's weights are then published at the copy, SETTLED: the caller
-     *               orders the ops that read them behind `done` with one stream wait, where an
-     *               event on every weight would cost the run phase one wait per weight -- a few
-     *               hundred a layer. `staged` gets the units copied, in order.
-     * unstage_units publish those units at their pool slots again. The caller must already have
-     *               ordered the next writer of `dst` behind every op that read the copies; this
-     *               only moves the address the NEXT issue resolves.
-     * stage_need    the room stage_units would fill with `units` given room for all of them, so
-     *               a caller packing several layers into one region can size each one's share;
-     *               `largest`, when not null, gets the room the largest of those units takes.
+     * stage_units   copies each pooled unit of `units` with no slab slot and no copy in flight
+     *               into `dst`, packed at the allocation unit; a unit with no room is read in
+     *               place. Runs on the mover's stream behind `after` (if set) and records `done`.
+     *               Copies are published settled: the caller waits on `done` once instead of
+     *               once per weight (a few hundred per layer).
+     * unstage_units publishes those units at their pool slots again. The caller must already have
+     *               ordered the next writer of `dst` behind every reader of the copies.
+     * stage_need    the room stage_units would use with no cap, for sizing shares of a region;
+     *               `largest`, if set, gets the largest unit's room.
      *
-     * The span form packs into up to two stretches, the second taking what the first has no
-     * room left for: a ring's place that wraps past the region's end is two.
+     * The span form packs into up to two stretches (a ring region that wraps is two).
      */
     struct StageSpan { char* dst; int64_t cap; };
     int  stage_units(const std::vector& units, char* dst, int64_t cap, RadEvent after,
@@ -667,24 +522,19 @@ public:
     void unstage_units(const std::vector& staged);
     int64_t stage_need(const std::vector& units, int64_t* largest = nullptr) const;
 
-    /* ---- ROUTED LAYERS READ FROM THE CONTAINER: the file stager (core/place/stager.h) --------
+    /* ---- routed layers read from the container: the file stager (core/place/stager.h) --------
      *
-     * A routed unit the plan put on the file tier has no address at all (unit_base is null), and a
-     * grouped GEMM is handed every expert's pointer at issue -- so before a routed layer's first
-     * expert op, every one of its file-tier units is read into a VRAM buffer and published there,
-     * and after the layer it is published as null again (unstage_units does that half). The
-     * buffers are the two the plan charged out of the weights pool (Plan::file_stage_vram).
+     * A file-tier unit has no address, but a grouped GEMM takes every expert's pointer at issue.
+     * So before a routed layer's first expert op its file-tier units are read into a VRAM buffer
+     * and published there; afterwards unstage_units publishes them as null again. The plan
+     * charges the two buffers to the weights pool (Plan::file_stage_vram).
      *
-     * stage_file_units  read every unit of `units` that is on the file tier into `dst`, packed at
-     *                   RAD_ALIGN_UNIT in the order given, through the pinned read windows: the
-     *                   layer's weights are read in container order as long runs -- a run skips a
-     *                   gap of resident units rather than reading through it -- each window drains
-     *                   to `dst` on the mover's stream while the next fills, behind `after` when it
-     *                   is not null, with `done` recorded behind the last copy. Published SETTLED,
-     *                   for the reason stage_units gives. Refuses with RAD_E_SCRATCH when the units
-     *                   do not fit `cap`, which a buffer sized by the plan never meets. The reads
-     *                   are BLOCKING on this thread; that is the price of the tier and the stats
-     *                   above carry it.
+     * stage_file_units  reads every file-tier unit of `units` into `dst`, packed at RAD_ALIGN_UNIT
+     *                   in the order given, through the pinned read windows: container-order
+     *                   runs, each window draining to `dst` on the mover's stream while the next
+     *                   fills, behind `after` (if set), with `done` recorded last. Published
+     *                   settled. RAD_E_SCRATCH if the units exceed `cap`. The reads block this
+     *                   thread.
      * file_buffer       buffer 0 or 1 of the plan's two, or null when the plan has none. */
     int   stage_file_units(const std::vector& units, char* dst, int64_t cap,
                            RadEvent after, RadEvent done, std::vector* staged);
@@ -697,22 +547,18 @@ public:
     std::string report() const;
 
 private:
-    /* One in-flight relocation. The state machine is Free -> Copying -> Published -> Quarantine
-     * -> Free, and every transition is made by the DISPATCH THREAD at a layer boundary. The
-     * transfers are asynchronous; the table edits are not. No mutex on the read side, because
-     * that side is the critical path of every layer, and no background thread mutating placement
-     * mid-layer, because placement would then depend on host timing and stop being reproducible. */
+    /* One in-flight relocation: Free -> Copying -> Published -> Quarantine -> Free. Transfers
+     * are asynchronous; every transition is made by the dispatch thread at a layer boundary. No
+     * mutex on the read side (it is on every layer's critical path) and no background thread,
+     * which would make placement depend on host timing. */
     struct Move {
         enum class State { Free, Copying, Published, Quarantine };
-        /* Six kinds, one state machine. Promote and Demote are the heat engine's swaps. Stage is
-         * the exact prefetch bringing an offloaded unit into a slot. Release is the same slot
-         * going back once the declared order says nothing will read it again this step -- it
-         * copies nothing and still needs the quarantine, because the barrier is about kernels
-         * already issued and not about bytes in flight. Drop is a unit in a lent slot going back
-         * to the host copy it kept: no copy either, and the same quarantine for the same reason.
-         * Migrate is a donor (Mover::donor_slot) leaving a lent slot the loan no longer covers
-         * for a free budgeted one, a copy inside the card; `slab_slot` is the slot it leaves and
-         * `to_slot` the one it lands in. */
+        /* Promote/Demote: the heat engine's swaps. Stage: the exact prefetch copying an offloaded
+         * unit into a slot; Release: that slot returned after its last use this step. Drop: a
+         * unit in a lent slot back to its kept host copy. Release and Drop copy nothing but still
+         * need the quarantine, which guards issued kernels, not bytes in flight. Migrate: a donor
+         * (Mover::donor_slot) from an uncovered lent slot (`slab_slot`) to a free budgeted one
+         * (`to_slot`). */
         enum class Kind { Promote, Demote, Stage, Release, Drop, Migrate };
         State    state = State::Free;
         Kind     kind = Kind::Promote;
@@ -721,6 +567,14 @@ private:
         int64_t  pool_slot = -1;
         int64_t  to_slot = -1;
         RadEvent ev = nullptr;
+
+        void clear() {
+            state = State::Free;
+            unit = -1;
+            slab_slot = pool_slot = to_slot = -1;
+        }
+        /* Whether the move hands `slab_slot` back once its quarantine clears. */
+        bool frees_slab() const { return kind != Kind::Promote && kind != Kind::Stage; }
     };
 
     struct UnitState {
@@ -733,16 +587,10 @@ private:
         int64_t bytes = 0;
     };
 
-    /* One weight class's memory. The slab is two kinds of slot rather than one: the BUDGETED slots
-     * come out of the weights pool like every other weight allocation and sit at a fixed stride
-     * from one base, and the FLEX slots past them are addresses inside another pool's memory --
-     * the KV cache's carve, the activation arena's top -- lent while that pool is not using them.
-     * They cannot be one range because the flex slots are scattered over every layer's stripe of
-     * the cache, wherever a stripe has room for one.
-     *
-     * A slot index therefore carries no information about which kind it is; slot_ptr is the only
-     * place that distinction exists. Each lender's flex slots are one segment of the slab, ordered
-     * by the loan that covers each, so a loan of any size is a prefix of its segment. */
+    /* One weight class's memory. Budgeted slots sit at a fixed stride from one base in the
+     * weights pool. Flex slots after them are lent addresses scattered over another pool's memory
+     * (KV cache stripes, arena top), so only slot_ptr() can resolve a slot index. Each lender's
+     * flex slots form one segment ordered by covering loan, so any loan covers a prefix. */
     struct ClassPools {
         SlotPool slab, pool;
         void*    slab_base = nullptr;
@@ -757,14 +605,12 @@ private:
         int64_t  n_donated = 0;        /* units in lent slots that gave their host copy away
                                         * (Mover::donor_slot); at most n_turn of them */
         std::vector   flex_ptr;
-        /* ONE SEGMENT OF THE SLAB PER LENDER THAT CARVED SLOTS FOR THIS CLASS. `need[i]` is the
-         * loan, in the lender's measure, that covers the segment's i-th slot; ascending, so a
-         * loan of any size covers a prefix. */
+        /* One slab segment per lender that carved slots for this class. `need[i]` is the loan,
+         * in the lender's measure, that covers the segment's i-th slot; ascending. */
         struct Lent { int lender = 0; int seg = -1; int64_t first = 0; std::vector need; };
         std::vector    lent;
-        /* A slot leaves coverage only when a loan shrinks, and nothing is ever placed in an
-         * uncovered one, so units stranded past the loan exist only after a shrink. Set there, and
-         * cleared by a balance() sweep that dropped every one of them. */
+        /* Units can sit past the loan only after a shrink, since nothing is placed in an
+         * uncovered slot. Set on a shrink; cleared by a balance() sweep that removed them all. */
         bool     strand_check = true;
 
         char* slot_ptr(int64_t slot) const {
@@ -780,8 +626,8 @@ private:
     Residency      res_;
     MoverStats     stats_;
     Pools*         budget_ = nullptr;
-    /* True only when this object called the allocator itself, which is the test path. A Pool
-     * reservation is owned by the Pool and freeing it here would be a double free. */
+    /* True only when this object called the allocator itself (the test path). A Pool
+     * reservation belongs to the Pool; freeing it here would be a double free. */
     bool           owns_memory_ = false;
 
     RadStream mover_ = nullptr;
@@ -792,29 +638,29 @@ private:
     std::vector  stage_picks_;  /* the units stage_units may take, in pool order */
     int       gate_dispatch_ = -1;
 
-    /* A DISPATCH'S SWAP COPIES -- demotions, promotions and migrations -- GO TO THE CARD'S DMA ENGINE
-     * AS ONE LIST (flush_moves), sent at the end of balance() and before anything reads their events.
-     * Each move's event is recorded behind the list, so a move lands with its list. */
+    /* A dispatch's swap copies (demotions, promotions, migrations) go to the card's DMA engine as
+     * one list (flush_moves), sent at the end of balance() and before anything reads their
+     * events. Each move's event is recorded after the list. */
     std::vector move_segs_;
     std::vector    move_recs_;
-    int  queue_move_copy(void* dst, const void* src, int64_t bytes, int rec);
+    void queue_move_copy(void* dst, const void* src, int64_t bytes, int rec);
     int  flush_moves();
     std::vector pools_;
     std::vector  unit_;
     std::vector       moves_;
-    /* Per unit, how many records are Copying it: unit_in_flight() without a walk of the records.
-     * The prefill stager asks for every pooled unit of every layer it stages, and the records
-     * number twice the slots a swap can hold, so a walk would grow with the move budget. */
+    /* Per unit, how many records are Copying it, so unit_in_flight() needs no walk of the
+     * records. The prefill stager asks about every pooled unit it stages, and the record count
+     * grows with the move budget. */
     std::vector   copying_;
     /* balance()'s drop candidates, (heat, unit), kept between calls so a step allocates nothing. */
     std::vector> drop_cand_;
     bool hold_turnover_ = false;
-    /* donor_slot()'s candidates a class, by layer, each layer's coldest first so its hottest is at
-     * the back; ranked once a dispatch, `at` being the dispatch they were ranked for. */
+    /* donor_slot()'s candidates per class, by layer, each layer sorted coldest first (hottest at
+     * the back). Ranked once per dispatch; `at` is that dispatch. */
     struct DonorRank { int at = -1; std::vector>> by_layer; };
     std::vector donors_;
-    /* The layer whose unit each pool slot held when the pool was laid out, a class: the pool is
-     * filled in unit order, so a layer's pooled units start out side by side (pool_slot_for). */
+    /* Per class, the layer of the unit each pool slot held at layout. The pool is filled in unit
+     * order, so a layer's pooled units start out adjacent (pool_slot_for). */
     std::vector> pool_layer_;
     int32_t n_layers_ = 0;
 
@@ -846,13 +692,12 @@ private:
     int32_t               last_op_ = -1;
     int                   dispatch_ = 0;
 
-    /* THE LOAN, in the owner's tokens, and what the dashboard reads of it. */
+    /* Each lender's loan in its own measure, and the totals the dashboard reads. */
     int64_t              loan_[kLenders] = {};
     std::atomic flex_used_{0};
     std::atomic flex_offered_{0};
-    /* Where the last free record was found. Records free up roughly in the order they were taken,
-     * so starting the next search there makes it a step rather than a walk of every record, which
-     * matters once the lent slots have put a record's worth of them in flight. */
+    /* Where the last free record was found. Records free up roughly in the order they were
+     * taken, so starting there keeps the search short when lent slots put many in flight. */
     mutable size_t       rec_cursor_ = 0;
 
     int  retire(HeatEngine* heat);
@@ -863,14 +708,16 @@ private:
     int  start_stage(int32_t unit, int64_t slab_slot);
     void release_slot(int32_t unit);
     bool unit_in_flight(int32_t unit) const;
+    /* Whether stage_units would copy `unit`: pooled, with no slab slot and no copy in flight. */
+    bool stageable(int32_t unit) const;
     /* A unit in a lent slot back to the host copy it kept. See Move::Kind::Drop. */
     int  drop(int32_t unit, HeatEngine* heat);
     /* The pool slot a demotion copies `unit` into: one its layer's units started out in, else a
      * same-layer donor's, else any free one, else any donor's; -1 when there is none. */
     int64_t pool_slot_for(int32_t unit, HeatEngine* heat);
-    /* A pool slot for a budgeted victim when the pool has none free: the host copy of a unit in a
-     * slot the KV cache lent, which keeps its place in VRAM without one -- a unit of `layer`, or
-     * of any layer when it is negative. -1 when no unit may give one. See the definition. */
+    /* A pool slot for a budgeted victim when none is free: the host copy of a unit in a KV-lent
+     * slot, which stays in VRAM without it. From a unit of `layer`, or of any layer when
+     * negative; -1 when no unit may give one. Rationale at the definition. */
     int64_t donor_slot(size_t klass, int32_t layer, HeatEngine* heat);
     /* A donor out of a lent slot into a free budgeted one, if one is free: false when none is. */
     bool migrate(int32_t unit, HeatEngine* heat);
diff --git a/core/place/planner.cpp b/core/place/planner.cpp
index cba67daa..ac68e59f 100644
--- a/core/place/planner.cpp
+++ b/core/place/planner.cpp
@@ -1,19 +1,13 @@
-/* planner.cpp -- the placement planner. See planner.h for the design; this file is the mechanics.
+/* planner.cpp -- the placement planner's mechanics; planner.h has the design.
  *
- * The planner runs once, between declare and load, and it is pure: it reads the Program, the
- * Config and the container's profile, and it writes a Plan. It queries no device, reads no clock
- * and looks at no environment. That is not tidiness -- it is what makes Config::deterministic
- * implementable (spec §17) and what makes the resident set identical on every tensor-parallel
- * rank (planner.h, MoveUnit).
+ * The planner is pure: it reads the Program, the Config and the container's profile and writes a
+ * Plan. It queries no device, clock or environment, which is what makes Config::deterministic
+ * possible (spec §17) and keeps the resident set identical on every TP rank (planner.h, MoveUnit).
  *
- * DO NOT ADD A DEVICE QUERY HERE, and the reason is concrete rather than principled. Every pool is
- * budgeted explicitly from Config (spec §6) -- no profiling pass, no utilisation fraction. A
- * planner that instead derived a budget from RadDeviceProps would have to cope with rad_dev_count()
- * reporting devices that are not the target: an integrated GPU enumerates alongside the discrete
- * ones and reports tens of GiB of "VRAM" that is really system RAM, so summing capacity across
- * devices overstates the budget by that much and produces a plan that cannot load. Any future code
- * that does look at props must be per-device and must filter on RadDeviceProps::arch, never on
- * index and never on capacity.
+ * Do not add a device query. Budgets come from Config (spec §6). rad_dev_count() also enumerates
+ * integrated GPUs, which report tens of GiB of "VRAM" that is system RAM, so summing capacity
+ * overstates the budget. Any code that does read RadDeviceProps must be per device and filter on
+ * RadDeviceProps::arch, never on index or capacity.
  */
 #include "planner.h"
 
@@ -25,8 +19,9 @@
 namespace rad {
 
 /* ------------------------------------------------------------------ names */
-/* These live here because placement is the component that owns what a tier and a site MEAN.
- * rad_core.h declares them; if a second definition appears, one of us is wrong about ownership. */
+constexpr int kSiteCount = (int)Site::Host + 1;
+
+/* Declared in rad_core.h, defined here because placement owns what a tier and a site mean. */
 const char* tier_name(Tier t) {
     switch (t) {
         case Tier::VRAM:         return "vram";
@@ -87,10 +82,8 @@ Budgets Budgets::from(const Config& c) {
 
 /* ------------------------------------------------------------------ sizes and keys */
 int64_t weight_bytes(const WeightInfo& w) {
-    /* The layout pass's answer when it has run: the stored layout is what actually occupies a
-     * tier, and for a kernel that re-layouts its weights it is not the logical size. Before the
-     * layout pass -- which is the state a planner unit test builds -- fall back to the declared
-     * dtype and shape, which is what logical_bytes is. */
+    /* The stored size occupies the tier and differs from the logical size for a relayout. Before
+     * the layout pass (as in planner unit tests), fall back to the declared dtype and shape. */
     if (w.stored_bytes > 0) return w.stored_bytes;
     if (w.logical_bytes > 0) return w.logical_bytes;
     int64_t n = w.decl.rank ? 1 : 0;
@@ -99,9 +92,6 @@ int64_t weight_bytes(const WeightInfo& w) {
 }
 
 
-/* See planner.h. Planner::resolve_sites, Planner::build_units and Planner::pin_mapped, run over
- * the same program without allocating a Plan -- the budget resolver calls this before a Planner
- * exists. Kept adjacent to the three so a change to any of them has this in the same diff. */
 int64_t file_stage_reserve(int64_t widest, bool routed) {
     return (int64_t)RAD_PLACE_FILE_STAGE_SLOTS * widest +
            (routed ? (int64_t)RAD_PLACE_FILE_WINDOWS * RAD_PLACE_FILE_WINDOW_BYTES : 0);
@@ -122,29 +112,49 @@ int plan_check_weights_pool(const Plan& p, int64_t pool_bytes) {
     return RAD_E_STATE;
 }
 
+/* ------------------------------------------------------------------ site availability */
+/* A site is available for an op only if every band resolved a kernel in its domain (spec §5.1),
+ * read from Band::dom rather than a flag. Every band, not just the one that runs: the same op
+ * serves M=1 at decode and M=4096 at prefill (spec §2.2), and placement is decided once for all
+ * steps.
+ *
+ * Host availability is an option the budgets may take. Device availability decides whether the
+ * weight may be on a card at all; without it pin_mapped keeps it in the container's mapping.
+ * Declare rejects only ops with no kernel in either domain, so a host-only op (e.g.
+ * `embed_lookup_q` with no device kernel loaded) does reach the planner. */
+static void resolve_sites(const Program& prog, std::vector* host_ok,
+                          std::vector* device_ok) {
+    host_ok->assign(prog.weights.size(), 1u);
+    device_ok->assign(prog.weights.size(), 1u);
+    for (const OpInfo& o : prog.ops) {
+        bool host = !o.bands.empty();
+        bool dev  = !o.bands.empty();
+        for (const Band& b : o.bands) {
+            if (!b.dom[RAD_DOMAIN_HOST]) host = false;
+            if (!b.dom[RAD_DOMAIN_DEVICE]) dev = false;
+        }
+        for (rad_weight w : o.weights) {
+            if (w == RAD_NULL_HANDLE || w >= host_ok->size()) continue;
+            if (!host) (*host_ok)[w] = 0u;
+            /* No device kernel leaves host as the only option. Declare rejects a band with neither
+             * kernel, so `!dev` here implies `host`. */
+            if (!dev) (*device_ok)[w] = 0u;
+        }
+    }
+}
+
+/* Planner::build_units and pin_mapped replayed without a Plan, for the budget resolver that runs
+ * before a Planner exists. Keep in step with those two; resolve_sites is shared. */
 void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement embedding,
                       TablePlacement ngram, bool host_backend, bool container) {
     if (!out) return;
     *out = WeightFootprint{};
 
-    /* resolve_sites: a weight every one of whose ops lacks a device band cannot be read on the
-     * card, so it is never copied there whatever the budgets say. */
-    std::vector device_ok(prog.weights.size(), 1u), host_ok(prog.weights.size(), 1u);
-    for (const OpInfo& o : prog.ops) {
-        bool dev = !o.bands.empty(), host = !o.bands.empty();
-        for (const Band& b : o.bands) {
-            if (!b.dom[RAD_DOMAIN_DEVICE]) dev = false;
-            if (!b.dom[RAD_DOMAIN_HOST]) host = false;
-        }
-        for (rad_weight w : o.weights) {
-            if (w == RAD_NULL_HANDLE || w >= device_ok.size()) continue;
-            if (!dev) device_ok[w] = 0u;
-            if (!host) host_ok[w] = 0u;
-        }
-    }
+    std::vector host_ok, device_ok;
+    resolve_sites(prog, &host_ok, &device_ok);
 
     /* build_units: a model-level weight is its own unit, everything else groups by the declared
-     * (layer, expert). Ordered, for the same reason build_units is. */
+     * (layer, expert). */
     struct U { int32_t layer = -1, expert = -1; int64_t bytes = 0; bool mapped = false;
                bool emb = false, ngram = false, host = true, direct = true;
                int access = -1; };
@@ -174,7 +184,7 @@ void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement
         U& mu = units[u];
         const int64_t a = wi.align > 0 ? wi.align : RAD_ALIGN_UNIT;
         mu.bytes = align_up(mu.bytes, a) + weight_bytes(wi);
-        /* pin_mapped: THE WHOLE UNIT GOES, not the one weight. */
+        /* pin_mapped: the whole unit is mapped, not the one weight. */
         if (w < device_ok.size() && !device_ok[w]) mu.mapped = true;
         if (!weight_file_direct(wi, prog.ctx.world_size)) mu.direct = false;
         if (w < host_ok.size() && !host_ok[w]) mu.host = false;
@@ -188,22 +198,25 @@ void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement
         }
     }
 
-    /* And one align_up a unit, because that is how Mover::init spends the slab: `us.static_off =
-     * align_up(static_need, RAD_ALIGN_UNIT)` before every unit it places. A budget that summed raw
-     * bytes would be short by one alignment per unit, which on a 512-expert MoE is real. */
     for (U& mu : units) mu.mapped = mapped_unit(mu.mapped, container && mu.direct, host_backend);
     std::map layer_experts;
     std::set expert_strides;
     bool ngram_host = true;
     for (const U& mu : units) if (mu.ngram && !mu.host) ngram_host = false;
     for (const U& mu : units) {
+        /* Each unit is rounded up to RAD_ALIGN_UNIT, as Mover::init aligns before every unit it
+         * places; summing raw bytes would come up short by one alignment per unit. */
         const int64_t b = align_up(mu.bytes, RAD_ALIGN_UNIT);
         /* pin_embedding moves a table out of the statics only where nothing has mapped it. */
         if (mu.emb && !mu.mapped) out->embedding += b;
         if (mu.ngram) out->ngram += b;
         if (mu.ngram && !mu.mapped) out->ngram_device = true;
-        /* pin_towers moves an encoder tower's unit out of the statics on the same test. */
-        if (mu.access == RAD_ACCESS_PER_REQUEST && !mu.mapped && mu.expert < 0) out->tower += b;
+        /* pin_towers moves an encoder tower's unit out of the statics on the same test, except a
+         * lookup table pin_embedding has already pinned (tower_pin_bytes). */
+        if (mu.access == RAD_ACCESS_PER_REQUEST && !mu.mapped && mu.expert < 0) {
+            out->tower += b;
+            if (mu.emb) out->tower_lookup += b;
+        }
         /* pin_mapped: an n-gram table a device kernel reads stays off the card unless it was
          * placed in VRAM. */
         if (mu.mapped || (mu.ngram && ngram != TablePlacement::Vram)) out->mapped += b;
@@ -241,80 +254,30 @@ std::string weight_class_key(const std::string& name) {
     return out;
 }
 
-/* ------------------------------------------------------------------ site availability */
-/* Host-site execution needs a RAD_DOMAIN_HOST kernel from a kernel plugin, and where none
- * resolved that site is UNAVAILABLE for that op (spec §5.1). The planner does not take that as a
- * flag from somewhere; it reads the Band's per-domain resolution, because the resolution IS the
- * fact and anything else can drift from it.
- *
- * EVERY band, not the band that happens to run. A bucket table exists because the same op serves
- * M=1 at decode and M=4096 at prefill (spec §2.2), and a site that is available for one and not
- * the other is a site that changes under load. Placement is decided once; it has to hold for
- * every step the plan is legal for.
- *
- * BOTH DOMAINS ARE TRACKED, and they answer different questions. Host says whether the host SITE
- * is available -- an option the budgets may or may not take. Device says whether the weight may be
- * placed on a card AT ALL, and a weight whose op has no device kernel anywhere may not: it is
- * pinned to the container's mapping by pin_mapped below, before any budget is consulted.
- *
- * Tracking host alone would rest on the argument that a missing device kernel is fatal at declare
- * and never reaches the planner. That is true only of an op with NO kernel in either domain: an op
- * such as `embed_lookup_q` resolves on the host and nowhere else when no device kernel for it is
- * loaded, and declare reports that device band as unserved without refusing the model. */
-void Planner::resolve_sites(const Program& prog) {
-    host_ok_.assign(prog.weights.size(), 1u);
-    device_ok_.assign(prog.weights.size(), 1u);
-
-    for (const OpInfo& o : prog.ops) {
-        bool host = !o.bands.empty();
-        bool dev  = !o.bands.empty();
-        for (const Band& b : o.bands) {
-            if (!b.dom[RAD_DOMAIN_HOST]) host = false;
-            if (!b.dom[RAD_DOMAIN_DEVICE]) dev = false;
-        }
-        for (rad_weight w : o.weights) {
-            if (w == RAD_NULL_HANDLE || w >= host_ok_.size()) continue;
-            if (!host) host_ok_[w] = 0u;
-            /* AND THE OTHER DIRECTION, which is not the same statement. The absence of a host
-             * kernel removes a placement OPTION; the absence of a DEVICE one removes every option
-             * but host, and that is a decision rather than a preference: bytes an op can only be
-             * computed over on the CPU must not be copied to a card that cannot read them.
-             *
-             * Declare's asymmetry still holds -- a band with neither kernel is fatal before the
-             * planner runs -- so reaching here with `!dev` means `host` is true. */
-            if (!dev) device_ok_[w] = 0u;
-        }
-    }
-}
-
 /* ------------------------------------------------------------------ the mapped tier */
-/* A weight no device kernel can read is pinned to the container's mapping BEFORE any budget is
- * consulted, because it is not a budget question -- and so is an n-gram table --ngram-placement put
- * in RAM or on disk, whatever kernels could read it on a card. The other three off-device tiers are
- * what the planner falls back to when VRAM runs out; this one is where the weight has to be
- * whatever the budgets say, and charging a pool for bytes that are never copied would size that
- * pool against a number that does not exist.
+/* A weight no device kernel can read is pinned to the container's mapping before any budget is
+ * consulted, and so is an n-gram table --ngram-placement put in RAM or on disk. This is not a
+ * fallback tier: these bytes are never copied into a pool, so no pool is charged for them.
  *
- * THE WHOLE UNIT GOES, not the one weight. A unit is the movement granularity and a half-mapped one
- * has no meaning -- and it costs nothing here, because `device_ok_` is cleared for EVERY weight
- * operand of a host-only op, so the unit's other members are the same op's scale and constants.
- * What this does exclude is a plugin that groups a host-only weight with a device one: that
- * collapses the whole group onto the host, so the report names it. */
+ * The whole unit is mapped, not the one weight. `device_ok_` is cleared for every operand of a
+ * host-only op, so the unit's other members are normally that op's scales and constants. A plugin
+ * that groups a host-only weight with a device one collapses the group onto the host, and gets a
+ * warning. */
 void Planner::pin_mapped(const Program& prog, Plan* p) {
     const TablePlacement ng = in_.config->ngram_resolved;
     for (MoveUnit& mu : p->units) {
-        bool host_only = false, direct = in_.container;
+        /* `stored`: every weight is in the container exactly as its kernel reads it. */
+        bool host_only = false, stored = true;
         for (rad_weight w : mu.weights) {
             if (w < device_ok_.size() && !device_ok_[w]) host_only = true;
             if (w < prog.weights.size() &&
-                !weight_file_direct(prog.weights[w], prog.ctx.world_size)) direct = false;
+                !weight_file_direct(prog.weights[w], prog.ctx.world_size)) stored = false;
         }
-        /* On the host backend a unit stored in another form than its host kernel reads is placed
-         * like any other weight, in the pool its kernel can read too (mapped_unit). */
-        host_only = mapped_unit(host_only, direct, in_.host_backend);
-        /* --ngram-placement keeps an n-gram table OFF THE CARD unless it says vram, whether or not
-         * a device kernel could read it there: ram and disk are where the operator put it, and the
-         * strategies below would otherwise spend the card on 48 GB of rows read sixteen a token. */
+        /* See mapped_unit: on the host backend a non-direct unit goes to the weights pool. */
+        host_only = mapped_unit(host_only, in_.container && stored, in_.host_backend);
+        /* --ngram-placement keeps an n-gram table off the card unless it says vram, even when a
+         * device kernel could read it; otherwise the strategies would spend VRAM on a huge table
+         * read a few rows a token. */
         const bool ngram = mu.layer < 0 && !mu.weights.empty() &&
                            is_ngram_table(prog, mu.weights.front());
         if (!host_only && !(ngram && ng != TablePlacement::Vram)) continue;
@@ -331,33 +294,26 @@ void Planner::pin_mapped(const Program& prog, Plan* p) {
         } else {
             mu.site = Site::Host;
             mu.reason = "--ngram-placement disk: the host gather reads it from the container";
-            for (rad_weight w : mu.weights)
-                if (w < host_ok_.size() && !host_ok_[w])
-                    note_unfit(p, mu, "--ngram-placement disk needs a host kernel for its gather, "
-                                      "and none was loaded");
+            if (!host_kernel(mu))
+                note_unfit(p, mu, "--ngram-placement disk needs a host kernel for its gather, "
+                                  "and none was loaded");
         }
-        /* --ngram-placement ram: the load phase copies an n-gram table out of the mapping and
-         * publishes the copy -- locked memory the host kernel reads, or pinned memory the card
-         * reads where a device kernel gathers. Every pool still sees the mapped tier; the report
-         * shows what the copy costs. */
+        /* --ngram-placement ram: the load phase copies the table out of the mapping into locked
+         * memory (host gather) or pinned memory (device gather). Pools still see the mapped tier;
+         * the report shows the copy's cost. */
         if (ngram && ng == TablePlacement::Ram) {
             if (host_only) mu.reason = "--ngram-placement ram: a locked copy in RAM, made at load";
             else           p->ngram_copy_card = true;
             p->ngram_copy_bytes += mu.bytes;
         }
-        /* AND ONLY WHAT LIES IN THE CONTAINER AS THE KERNEL READS IT can be read from the mapping,
-         * or copied out of it: a weight its kernel rearranges at load, or a shard of one, has no
-         * place in the file that already looks the way the kernel reads it (spec §5.1). */
+        /* Only a weight stored in the container exactly as its kernel reads it can be read from,
+         * or copied out of, the mapping; a load-time relayout or a shard cannot (spec §5.1). */
         if (!in_.container)
-            note_unfit(p, mu, "it is read from a container's mapping or copied out of one -- and "
-                              "a checkpoint served directly has none; convert it to a container");
-        else
-            for (rad_weight w : mu.weights)
-                if (w < prog.weights.size() &&
-                    !weight_file_direct(prog.weights[w], prog.ctx.world_size))
-                    note_unfit(p, mu, "it is read from the container's mapping or copied out of "
-                                      "it -- and its stored form is not the container's (a "
-                                      "relayout, a widening or a shard)");
+            note_unfit(p, mu, "it must be read from a container's mapping, and a checkpoint served "
+                              "directly has none; convert it to a container");
+        else if (!stored)
+            note_unfit(p, mu, "it must be read from the container's mapping, and its stored form "
+                              "is not the container's (a relayout, a widening or a shard)");
         if (host_only)
             for (rad_weight w : mu.weights)
                 if (w < device_ok_.size() && device_ok_[w])
@@ -375,8 +331,7 @@ int access_strength(int access) {
         case RAD_ACCESS_PER_REQUEST: return 2;
         case RAD_ACCESS_CONDITIONAL: return 1;
         case RAD_ACCESS_RARE:        return 0;
-        default:                     return 4;   /* an access class we do not know is not one to
-                                                  * gamble a demotion on */
+        default:                     return 4;   /* unknown: never risk a demotion */
     }
 }
 
@@ -384,10 +339,8 @@ void Planner::build_units(const Program& prog, Plan* p) {
     p->unit_of_weight.assign(prog.weights.size(), -1);
     p->units.clear();
 
-    /* Keyed on the declared RadWeightGroup, which is the plugin's statement about what moves
-     * together. Ordered, not hashed: the unit order has to be a function of the model and not of
-     * a hash seed, or two ranks can rank the same profile differently and disagree about which
-     * experts are resident. */
+    /* Keyed on the declared RadWeightGroup. Ordered, not hashed: the unit order must depend only
+     * on the model, or TP ranks could disagree about which experts are resident. */
     std::map, int32_t> by_group;
 
     for (rad_weight w = 1; (size_t)w < prog.weights.size(); ++w) {
@@ -395,15 +348,12 @@ void Planner::build_units(const Program& prog, Plan* p) {
         const int32_t layer = wi.decl.group.layer;
         const int32_t expert = wi.decl.group.expert;
 
-        /* A model-level weight is its own unit. Grouping every model-level weight together would
-         * make the embedding table and the output norm one movement unit of wildly different
-         * access classes, and the mover would have to carry the larger of them for the smaller. */
+        /* A model-level weight is its own unit; grouping them would tie, e.g., the embedding table
+         * and the output norm together despite very different sizes and access classes. */
         int32_t u;
         if (layer < 0) {
             u = (int32_t)p->units.size();
             p->units.push_back(MoveUnit{});
-            p->units.back().layer = -1;
-            p->units.back().expert = -1;
         } else {
             auto key = std::make_pair(layer, expert);
             auto it = by_group.find(key);
@@ -434,10 +384,9 @@ void Planner::build_units(const Program& prog, Plan* p) {
         p->unit_of_weight[w] = u;
     }
 
-    /* Warm start from the profile. It ranks which experts BEGIN resident and nothing else: it is
-     * worth about a point of hit rate against an arbitrary order and honestly not more, because
-     * imatrix popularity is not decode popularity and the heat engine re-ranks from real routing
-     * within a few dispatches regardless. A warm start, not a policy (spec §5.3). */
+    /* Warm start from the profile: it only decides which experts begin resident (spec §5.3). It is
+     * worth about a point of hit rate, since imatrix popularity is not decode popularity and heat
+     * re-ranks from real routing within a few dispatches. */
     if (in_.profile && in_.n_profile > 0) {
         std::map, float> share;
         for (int64_t i = 0; i < in_.n_profile; ++i)
@@ -451,21 +400,16 @@ void Planner::build_units(const Program& prog, Plan* p) {
 }
 
 /* ------------------------------------------------------------------ slab classes */
-/* One class per (unit kind, byte size). A slab slot is interchangeable within its class and
- * nowhere else, which is what lets a promotion be an integer swap instead of an allocation, and
- * what lets a slot be LAYER-AGNOSTIC: heat promotes the hottest pooled expert against the coldest
- * resident one wherever they sit, so capacity moves to the layers that need it. A per-layer
- * ranking cannot repair the residency skew a global profile leaves behind, and the slab being
- * layer-agnostic is the whole reason a global ranking is legal.
+/* One class per (unit kind, byte size). Slots are interchangeable within a class, so a promotion
+ * is an integer swap, and they are layer-agnostic: heat swaps the hottest pooled expert for the
+ * coldest resident one wherever they sit, which is what makes a global ranking legal.
  */
 void Planner::build_classes(Plan* p) {
     std::map, int32_t> seen;
 
     for (MoveUnit& mu : p->units) {
-        /* A MAPPED UNIT HAS NO CLASS AND NO SLOT. Classes exist so a slab slot is interchangeable
-         * within one; a unit that is never copied anywhere has nothing to be interchangeable with,
-         * and giving it a stride would charge its whole size to a pool it does not occupy. Its
-         * slot_bytes stays 0, which is what every budget below spends against. */
+        /* A mapped unit has no class and no slot: it occupies no pool, so its slot_bytes stays 0
+         * and no budget is charged for it. */
         if (mu.tier == Tier::Mapped) continue;
         const int kind = mu.expert >= 0 ? 2 : (mu.layer >= 0 ? 1 : 0);
         const int64_t stride = align_up(mu.bytes, RAD_ALIGN_UNIT);
@@ -489,10 +433,8 @@ void Planner::build_classes(Plan* p) {
 }
 
 /* ------------------------------------------------------------------ the ranking */
-/* Rank-invariant by construction. The key is (profile share desc, layer, expert, unit index) and
- * every component of it is a property of the model or of the container -- nothing rank-local,
- * nothing timed, nothing from the device. Under tensor parallel every rank runs this and gets the
- * same order, which is what makes a slab slot mean the same thing on every card. */
+/* Rank-invariant: every sort key comes from the model or the container, never from the rank,
+ * a clock or the device, so all TP ranks get the same order (planner.h, MoveUnit). */
 void Planner::rank_units(Plan* p, std::vector* order) const {
     order->clear();
     order->reserve(p->units.size());
@@ -501,38 +443,13 @@ void Planner::rank_units(Plan* p, std::vector* order) const {
         const MoveUnit& ua = p->units[(size_t)a];
         const MoveUnit& ub = p->units[(size_t)b];
         if (ua.profile_share != ub.profile_share) return ua.profile_share > ub.profile_share;
-        /* EXPERT-MAJOR, NOT LAYER-MAJOR, AND THE TIE-BREAK IS THE WHOLE POLICY WHEN THERE IS NO
-         * PROFILE -- which is the common case, because a container without one gives every unit
-         * share 0.0 and every comparison above falls through to here.
-         *
-         * Layer-major fills every expert of layer 0, then layer 1, and stops wherever the budget
-         * runs out, so the layers past the cut begin the run with NOTHING resident. The heat
-         * engine cannot repair that quickly: a promotion needs the candidate to beat the victim by
-         * `hysteresis * cold + min_gain`, and an expert in a starved layer is routed to rarely
-         * enough that the skew is worked off a few hundred units at a time, paying both link
-         * directions for every one.
-         *
-         * WHAT THE SKEW COSTS IS ON-DEMAND STREAMING, not mover churn. A starved layer misses on
-         * most of what it routes to and streams those shards over the link inside the GEMM, so its
-         * expert projections run several times longer than a well-stocked layer's, every step.
-         *
-         * Expert-major puts expert 0 of every layer before expert 1 of any, so the budget cut
-         * lands at the same expert index in every layer and residency starts balanced. That is
-         * not a better RANKING -- with no profile there is no information to rank on -- it is the
-         * absence of an arbitrary one, and it leaves the heat engine's moves to do the job it
-         * exists for instead of repairing the fill. heat.h makes the same argument about its own
-         * tie-break: ties go to the layer that can most afford it, never to the low index.
-         *
-         * NO CAPACITY IS ADDED BY THIS, and the per-layer residency histogram in HeatEngine::report
-         * is where that shows: the mean resident count a layer is unchanged and only its spread
-         * collapses. Well-stocked layers give up some slots and get slightly slower; starved ones
-         * gain more than that back. The largest single beneficiary is whichever layer runs more
-         * than once a step -- a draft head runs once per draft round -- because every slot there is
-         * spent several times a step.
-         *
-         * Uniform is still the right fill when there is no profile to rank on, and the heat engine
-         * already sees the extra activations of a multiply-run layer in its own counter, so the
-         * planner does not weight for it. */
+        /* Expert-major tie-break, which is the whole policy without a profile (every share is
+         * 0.0). Layer-major would fill layer 0, then layer 1, and leave the layers past the
+         * budget cut with nothing resident; those layers then stream most of their experts over
+         * the link inside the GEMM every step, and heat's hysteresis repairs the skew only slowly.
+         * Expert-major puts expert 0 of every layer before expert 1 of any, so the cut lands at
+         * the same expert index everywhere and residency starts balanced. Layers that run more
+         * than once a step (a draft head) are not weighted here; heat's counters see them. */
         if (ua.expert != ub.expert) return ua.expert < ub.expert;
         return ua.layer < ub.layer;
     });
@@ -541,9 +458,8 @@ void Planner::rank_units(Plan* p, std::vector* order) const {
 /* ------------------------------------------------------------------ assignment */
 namespace {
 
-/* The three ways a unit can live off the device, in the order the planner tries them. Split out
- * so the expert path and the layer path cannot drift: they are the same mechanism at two
- * granularities and they have to spell the fallback the same way. */
+/* The off-device fallback, in the order the planner tries it, shared by the layer and expert
+ * paths so they cannot drift. */
 struct HostFall {
     int64_t host_used = 0;
     int64_t host_budget = 0;
@@ -551,60 +467,45 @@ struct HostFall {
 
     /* Returns true and sets tier/site, or false when nothing below VRAM will take it.
      *
-     * THE SITE DECIDES THE TIER, which is the independent-axes claim made concrete. Only a unit
-     * the DEVICE has to read needs pinned memory; a host-site unit is read by a host kernel and
-     * pinning it buys nothing. That matters because pinned memory is genuinely scarce -- past a
-     * driver-dependent total the registration call starts returning success and leaving the
-     * process broken -- so pinning tens of gigabytes of weights only the CPU touches is not a
-     * waste, it is a failure mode. Both kinds are charged against the same --host-pool-mib,
-     * because an unbudgeted tier is how a process gets OOM-killed. */
+     * The site decides the tier: only a unit the device reads needs pinned memory. Pinned memory
+     * is scarce -- past a driver-dependent total, registration returns success and leaves the
+     * process broken -- so host-site weights stay pageable. Both kinds are charged to
+     * --host-pool-mib so no tier is unbudgeted. */
     bool place(MoveUnit& mu, bool host_kernel, const char** reason) {
         if (host_used + mu.slot_bytes <= host_budget) {
             host_used += mu.slot_bytes;
             if (host_kernel && mu.access == RAD_ACCESS_PER_TOKEN) {
-                /* llama.cpp -ngl: the bytes stay in host memory and the arithmetic happens there
-                 * too, so a weight read every token is never moved at all. It costs the
-                 * activation crossing at the run boundary, which is why runs are the objective. */
+                /* llama.cpp -ngl: bytes and arithmetic both on the host, so the weight never moves;
+                 * the cost is the activation crossing at each run boundary. */
                 mu.tier = Tier::HostPageable;
                 mu.site = Site::Host;
                 *reason = "host kernel resolved; host run";
                 return true;
             }
-            /* Everything below is read by the DEVICE out of host memory, so it must be pinned. */
+            /* The device reads everything below out of host memory, so it must be pinned. */
             mu.tier = Tier::HostPinned;
             if (mu.access == RAD_ACCESS_CONDITIONAL) {
-                /* THE HYBRID TIER. A routed expert that is not resident is NOT copied into
-                 * VRAM and then multiplied: the GEMM's tile names the pinned pool and streams the
-                 * shard over the link as it computes, so the transfer is inside the kernel rather
-                 * than in front of it, and a miss costs one shard rather than a shard plus a
-                 * slab slot plus an eviction. No slot, so it costs no residency either. */
+                /* A non-resident routed expert is not copied to VRAM first: the GEMM streams the
+                 * shard from the pinned pool as it computes, so a miss costs one shard and no
+                 * slab slot or eviction. */
                 mu.site = Site::DeviceZeroCopy;
                 *reason = "pooled expert; streamed over the link";
             } else {
-                /* Read every token with no host kernel: staging into a slab slot is right,
-                 * because zero-copy would re-stream the same bytes every single step while a
-                 * staged copy pays once and the prefetch schedule hides it. */
+                /* Staged rather than zero-copy: zero-copy would re-stream the same bytes every
+                 * step, while the exact prefetch schedule hides a staged copy. */
                 mu.site = Site::DeviceStaged;
                 *reason = "no host kernel; staged into a slab slot";
             }
             return true;
         }
-        /* THE FILE TIER, for a unit that lies in the container as its kernel reads it.
-         *
-         * A Tier::SSD unit has NO ADDRESS until something stages it, and the two kinds of unit
-         * are staged two ways. A SCHEDULED one is `Plan::prefetch` -- an exact schedule built from
-         * first_use_op, because declare enumerated the whole access sequence. A ROUTED one cannot
-         * be scheduled: the router picks it on the card, and a grouped MoE GEMM is handed every
-         * expert's pointer at issue. So the file stager reads ALL of a routed layer's file-tier
-         * experts into a VRAM buffer before the layer's first expert op, on every pass, routed to
-         * or not (place/stager.h). Every pointer then exists at issue; what it costs is the whole
-         * layer's file-tier bytes a pass, which a prefill chunk -- routing to nearly every expert
-         * of a layer -- reads anyway, and which makes a decode step as slow as the drive. That is
-         * the trade --weights-disk-tier asks for by name, and the plan sizes the two buffers it
-         * needs (Plan::file_stage_vram).
-         *
-         * Never MOVABLE: the heat engine promotes out of the pinned pool, and a unit with no pool
-         * slot has nothing to promote from. assign_expert_tiered says so where it sets the bit. */
+        /* The file tier, for a unit stored in the container as its kernel reads it. A Tier::SSD
+         * unit has no address until staged. A scheduled unit is staged by Plan::prefetch. A routed
+         * one cannot be scheduled, since a grouped MoE GEMM needs every expert's pointer at issue,
+         * so the file stager reads all of a routed layer's file-tier experts into a VRAM buffer
+         * before the layer's first expert op, every pass (place/stager.h, Plan::file_stage_vram).
+         * Prefill reads nearly all of them anyway; decode runs at drive speed, which is the trade
+         * --weights-disk-tier asks for. File-tier units are never movable: heat promotes out of
+         * the pinned pool, and they have no pool slot. */
         if (ssd && mu.file_direct) {
             mu.tier = Tier::SSD;
             mu.site = Site::DeviceStaged;
@@ -622,10 +523,7 @@ struct HostFall {
 int Planner::assign_all_vram(Plan* p) {
     int64_t used = 0;
     for (MoveUnit& mu : p->units) {
-        /* A PREPLACED UNIT IS ALREADY PLACED and no strategy may move it: a mapped one has no
-         * device kernel that could read it anywhere else, and a token embedding
-         * --embedding-placement put in the host pool is read there in place. Every assignment pass
-         * below begins with this line. */
+        /* No strategy may move a preplaced unit; every assignment pass starts with this check. */
         if (mu.preplaced()) continue;
         mu.tier = Tier::VRAM;
         mu.site = Site::Device;
@@ -642,17 +540,11 @@ int Planner::assign_all_vram(Plan* p) {
     return RAD_OK;
 }
 
-/* LAYER OFFLOAD IS A SCHEDULING PROBLEM, and this is the whole of the decision half: pick which
- * layers leave VRAM. The prefetch that follows is exact, because declare enumerated every op with
- * its weight operands in order and WeightInfo::first_use_op is that order.
+/* Picks which layers leave VRAM; schedule_prefetch then stages them exactly.
  *
- * CONTIGUOUS HOST RUNS ARE AN EXPLICIT OBJECTIVE (spec §5.3). A host-site op leaves its activation
- * in host memory, so every boundary between a device run and a host run costs a link crossing. A
- * few hundred KB is nothing; alternating per layer is 2L of them. llama.cpp gets this free because
- * -ngl assigns a contiguous suffix; here the suffix is chosen on purpose, and for a second reason
- * as well: the FIRST layers are needed earliest in the step, so a staged prefix has to have landed
- * before the step can start at all, while a staged suffix has the whole step's duration to arrive.
- * Spilling the tail is the only choice that gives the mover any lead at all.
+ * It spills a suffix of the execution order, which is one contiguous host run (spec §5.3; see
+ * Plan::host_runs), and a suffix also gives the mover the longest lead: a staged prefix would have
+ * to land before the step starts, a staged suffix has the whole step to arrive.
  */
 int Planner::assign_layer_offload(Plan* p) {
     for (MoveUnit& mu : p->units) {
@@ -664,47 +556,35 @@ int Planner::assign_layer_offload(Plan* p) {
     for (const MoveUnit& mu : p->units) if (!mu.preplaced()) total += mu.slot_bytes;
     if (p->vram_budget <= 0 || total <= p->vram_budget) return RAD_OK;
 
-    /* Layers in EXECUTION order. The layer index is normally that order already, but the order
-     * declare produced is the authority -- a plugin is free to declare a tower whose layer
-     * numbering is not its issue order, and a run computed against the wrong order is not a run. */
+    /* Layers in execution order (first use), which a plugin's layer numbering need not follow. */
     std::vector layers;
     std::map bytes_of;
     std::map first_of;
     for (const MoveUnit& mu : p->units) {
         if (mu.layer < 0) continue;
-        if (!bytes_of.count(mu.layer)) { layers.push_back(mu.layer); first_of[mu.layer] = mu.first_use_op; }
+        if (!bytes_of.count(mu.layer)) { layers.push_back(mu.layer); first_of[mu.layer] = -1; }
         bytes_of[mu.layer] += mu.slot_bytes;
-        if (mu.first_use_op >= 0 && (first_of[mu.layer] < 0 || mu.first_use_op < first_of[mu.layer]))
-            first_of[mu.layer] = mu.first_use_op;
+        int32_t& first = first_of[mu.layer];
+        if (mu.first_use_op >= 0 && (first < 0 || mu.first_use_op < first)) first = mu.first_use_op;
     }
     std::stable_sort(layers.begin(), layers.end(), [&](int32_t a, int32_t b) {
         if (first_of[a] != first_of[b]) return first_of[a] < first_of[b];
         return a < b;
     });
 
-    /* RESERVE THE STAGING RING BEFORE CHOOSING THE CUT. A spilled layer with no host kernel is
-     * staged, and a staged unit needs a slab slot to be staged into -- so a plan that spills
-     * exactly to the budget and only then discovers it has nowhere to stage is a plan that does
-     * not load. Deciding this before the cut means asking whether ANY layer lacks a host kernel,
-     * which over-reserves when the spill happens to land only on host-capable ones. That is the
-     * right direction to be wrong in. */
-    /* AND THE RING IS PER CLASS, NOT ONE RING FOR THE WIDEST CLASS.
+    /* Reserve the staging ring before choosing the cut: a spilled layer without a host kernel is
+     * staged and needs ring slots. Whether any layer lacks a host kernel is asked before the cut,
+     * which may over-reserve; over-reserving spills one layer too many, under-reserving gives a
+     * plan that does not load.
      *
-     * The mover allocates a staging ring in EVERY slab class that has one (Mover::init sums
-     * n_slab + shadow + n_stage per class, and finish() charges (n_shadow + n_stage) * stride per
-     * class to slab_overhead). A hybrid model has two layer classes -- attention layers and linear
-     * layers are different strides -- so reserving one ring at the widest stride is short by a
-     * whole ring, and the plan then reports a fit that the mover refuses for want of VRAM. A plan
-     * that does not load is worse than one that spills a layer too many, because the second serves.
-     *
-     * Summed over the classes that actually carry a layer unit, which is the same set the mover
-     * builds a slab for. The tail pad is per class too, for the same reason. */
+     * One ring plus tail pad per layer slab class, matching what Mover::init allocates and
+     * finish() charges. A hybrid model has several layer strides (attention vs linear layers). */
     bool any_stage = ssd_;
     std::map stride_of;
     for (const MoveUnit& mu : p->units) {
         if (mu.layer < 0 || mu.slab_class < 0) continue;
         stride_of[mu.slab_class] = p->classes[(size_t)mu.slab_class].stride;
-        for (rad_weight w : mu.weights) if (!host_ok_[w]) { any_stage = true; break; }
+        if (!host_kernel(mu)) any_stage = true;
     }
     int64_t reserve = 0;
     if (any_stage)
@@ -712,8 +592,7 @@ int Planner::assign_layer_offload(Plan* p) {
             reserve += (int64_t)RAD_PLACE_STAGE_RING * kv.second + RAD_ALIGN_UNIT;
 
     int64_t need = total + reserve - p->vram_budget;
-    /* Walk the tail. `cut` is the first layer, in execution order, that leaves VRAM -- so the
-     * spilled set is a suffix of the execution order and therefore ONE run by construction. */
+    /* `cut` is the first layer, in execution order, to leave VRAM; the spilled set is a suffix. */
     size_t cut = layers.size();
     int64_t freed = 0;
     while (cut > 0 && freed < need) { --cut; freed += bytes_of[layers[cut]]; }
@@ -728,9 +607,7 @@ int Planner::assign_layer_offload(Plan* p) {
     for (size_t i = cut; i < layers.size(); ++i) {
         for (MoveUnit& mu : p->units) {
             if (mu.layer != layers[i] || mu.preplaced()) continue;
-            bool host_kernel = true;
-            for (rad_weight w : mu.weights) if (!host_ok_[w]) { host_kernel = false; break; }
-            if (!fall.place(mu, host_kernel, &mu.reason)) {
+            if (!fall.place(mu, host_kernel(mu), &mu.reason)) {
                 mu.reason = "fits in no tier";
                 note_unfit(p, mu, ssd_ ? "neither VRAM nor the host pool has room"
                                        : "the host pool is full and no --weights-disk-tier was given");
@@ -741,11 +618,9 @@ int Planner::assign_layer_offload(Plan* p) {
     return rc;
 }
 
-/* EXPERT OFFLOAD IS A PREDICTION PROBLEM, and this is the initial guess. Everything that is not
- * conditional is pinned to VRAM first: a PER_TOKEN weight is read on every forward pass, so
- * spilling one to buy residency for an expert that MIGHT be routed to is a certain cost against a
- * probabilistic saving. The conditional units then take what is left, ranked by the container's
- * profile, and the heat engine re-ranks from real routing from the first dispatch onward.
+/* The initial expert residency. Non-conditional units go to VRAM first, since they are read
+ * every pass; conditional units take the rest in rank_units order, and heat re-ranks from real
+ * routing from the first dispatch.
  */
 int Planner::assign_expert_tiered(Plan* p) {
     int64_t fixed = 0;
@@ -757,9 +632,8 @@ int Planner::assign_expert_tiered(Plan* p) {
     }
 
     if (p->vram_budget > 0 && fixed > p->vram_budget) {
-        /* The dense part alone does not fit. That is a layer-offload problem wearing an expert
-         * hat, and answering it here with a second copy of the run-picking logic is how two
-         * granularities of one mechanism drift apart. Hand it over. */
+        /* The dense part alone does not fit: delegate to layer offload rather than duplicating
+         * its run-picking logic. */
         RAD_WARN("placement: the non-routed weights alone need %s against a %s weight budget; "
                  "falling through to layer offload for them",
                  humanb(fixed).c_str(), humanb(p->vram_budget).c_str());
@@ -768,10 +642,8 @@ int Planner::assign_expert_tiered(Plan* p) {
         for (const MoveUnit& mu : p->units)
             if (mu.access != RAD_ACCESS_CONDITIONAL && mu.tier == Tier::VRAM) fixed += mu.slot_bytes;
     }
-    /* WHAT LAYER OFFLOAD ALREADY PUT IN THE HOST POOL: the dense units of the layers it spilled.
-     * The routed experts below are placed again whatever it did with them, but the dense units
-     * stay where it put them, so the expert fill spends the pool that is left and not the whole
-     * of --host-pool-mib a second time. */
+    /* Host pool already spent by layer offload on dense units. The expert fill below re-places
+     * the routed experts but keeps the dense units, so it spends only the remainder. */
     int64_t host_spent = 0;
     for (const MoveUnit& mu : p->units)
         if (!mu.preplaced() && mu.access != RAD_ACCESS_CONDITIONAL &&
@@ -781,20 +653,15 @@ int Planner::assign_expert_tiered(Plan* p) {
     std::vector order;
     rank_units(p, &order);
 
-    /* RESERVE THE SPARE SLOTS OUT OF THE BUDGET. The slab has to hold the residents AND the
-     * shadow slots a promotion writes into, and they all come out of the weights pool -- so a
-     * fill that spends the whole budget on residents leaves the mover with nowhere to move into
-     * and, worse, makes the mover's allocation overrun the weights pool.
-     *
-     * Two passes, and the second is enough: the reserve depends only on the first pass's slot
-     * counts, and the first pass over-counts (it had more room), so the reserve it produces is an
-     * upper bound. A third pass can only give slots back, never take more. */
+    /* The spare slots come out of the same weights pool as the residents, or the mover's
+     * allocation would overrun it. Two passes suffice: the first pass had more room, so its
+     * spare count is an upper bound for the second. */
     HostFall fall{host_spent, p->host_budget, ssd_};
     int rc = RAD_OK;
 
-    /* ONE FILL: the conditional units in rank order, at most `cap` of them resident and the rest to
-     * the host pool or the file tier; what it costs the VRAM side comes back -- the residents, the
-     * shadow slots and the staging ring, and the file stager's two buffers. */
+    /* One fill: conditional units in rank order, at most `cap` resident within `room`, the rest
+     * to the host pool or file tier. Returns the VRAM cost: residents, shadow slots and staging
+     * ring, and the file stager's two buffers. */
     struct Cost { int64_t used = 0, spare = 0, file = 0, residents = 0; };
     auto fill = [&](int64_t room, int64_t cap) -> Cost {
         Cost k;
@@ -819,20 +686,16 @@ int Planner::assign_expert_tiered(Plan* p) {
                 mu.tier = Tier::VRAM;
                 mu.site = Site::Device;
                 mu.reason = "resident: ranked by the container's profile";
-                /* Movable is what the heat engine is allowed to touch. Under
-                 * Config::deterministic this is left false everywhere and the resident set is
-                 * exactly what this loop decided, for the whole run. */
+                /* Only movable units are touched by heat; under Config::deterministic none are,
+                 * so this resident set holds for the whole run. */
                 mu.movable = p->dynamic;
                 continue;
             }
-            bool host_kernel = true;
-            for (rad_weight w : mu.weights) if (!host_ok_[w]) { host_kernel = false; break; }
-            if (!fall.place(mu, host_kernel, &mu.reason)) {
+            if (!fall.place(mu, host_kernel(mu), &mu.reason)) {
                 mu.tier = Tier::SSD;
                 mu.site = Site::DeviceStaged;
                 mu.reason = "fits in no tier";
-                /* With the file tier on, only a unit the container does not hold as its kernel
-                 * reads it gets here -- a relayout, a widening or a shard (HostFall::place). */
+                /* With the file tier on, only a non-file-direct unit gets here (HostFall::place). */
                 note_unfit(p, mu, ssd_ ? "neither VRAM nor the host pool has room, and its "
                                          "stored form is not the container's (a relayout, a "
                                          "widening or a shard), so the file tier cannot read it "
@@ -842,29 +705,19 @@ int Planner::assign_expert_tiered(Plan* p) {
                 rc = RAD_E_NOMEM;
                 continue;
             }
-            /* A pooled expert is still MOVABLE: it is exactly what the heat engine promotes.
-             * Movability is about whether placement may change, not about where it is. A
-             * file-tier one is not: the mover promotes out of a pool slot and it has none -- the
-             * file stager reads it a layer at a time instead. */
+            /* A pooled expert is movable, since heat promotes from the pool. A file-tier one has
+             * no pool slot to promote from; the file stager reads it a layer at a time. */
             mu.movable = p->dynamic && mu.tier != Tier::SSD;
         }
 
-        /* How many slots the fill actually used, per class, and therefore how many spares to
-         * keep. A static plan reserves none: nothing moves, so nothing needs somewhere to move
-         * into. */
+        /* Slots used per class, which sizes the spares. A static plan reserves no shadow slots. */
         std::vector resident(p->classes.size(), 0), staged(p->classes.size(), 0);
         for (const MoveUnit& mu : p->units) {
             if (mu.slab_class < 0) continue;
             if (mu.movable && mu.tier == Tier::VRAM) ++resident[(size_t)mu.slab_class];
-            /* THE STAGING RING IS A SLAB ALLOCATION TOO, so this reserve has to charge for it.
-             * finish() sizes it from the units that ended up staged, which is known only after
-             * the fill -- the same chicken-and-egg the shadow slots have, and solved the same way.
-             *
-             * A ring exists only when something falls to the host or file tier, so a model that
-             * fits entirely in VRAM never exercises this. On one that spills, leaving the ring
-             * uncharged overruns the weight budget by a few slots, and the mover then refuses the
-             * statically placed weights on a plan the report called a fit. A ROUTED file-tier
-             * unit is not counted: the file stager reads it into buffers of its own. */
+            /* The staging ring is slab memory too. finish() sizes it from the staged units,
+             * known only after the fill, so it is reserved the same two-pass way as the shadow
+             * slots. Routed file-tier units are excluded; the file stager has its own buffers. */
             if (mu.site == Site::DeviceStaged && mu.access != RAD_ACCESS_CONDITIONAL)
                 ++staged[(size_t)mu.slab_class];
         }
@@ -875,15 +728,13 @@ int Planner::assign_expert_tiered(Plan* p) {
                 : 0;
             p->classes[c].n_shadow = shadow;
             if (shadow + ring <= 0) continue;
-            /* Plus the slab's tail padding, which is a real allocation and therefore a real
-             * charge: a kernel that assembles a packed code window from a wide read legitimately
-             * reads a few bytes past the last slot's data. Inside the slab that lands in a
-             * neighbour; at the end it runs off the allocation and faults the card. */
+            /* Plus the slab's tail pad: a kernel assembling a packed code window from a wide read
+             * reads a few bytes past the last slot, which would fault at the allocation's end. */
             k.spare += (shadow + ring) * p->classes[c].stride + RAD_ALIGN_UNIT;
         }
 
-        /* THE FILE STAGER'S BUFFERS: two, each the largest routed layer's file-tier units at the
-         * stager's packing, and the same tail pad. */
+        /* The file stager's two buffers, each the largest routed layer's file-tier units at the
+         * stager's packing, plus a tail pad. */
         std::map layer_bytes;
         for (const MoveUnit& mu : p->units)
             if (mu.tier == Tier::SSD && mu.access == RAD_ACCESS_CONDITIONAL && mu.layer >= 0)
@@ -900,14 +751,10 @@ int Planner::assign_expert_tiered(Plan* p) {
     Cost k = fill(room0, uncapped);
     if (p->vram_budget > 0) k = fill(room0 - k.spare, uncapped);
 
-    /* THE FILE BUFFERS COME OUT OF THE SAME BUDGET, AND THEY PULL THE OTHER WAY. The two-pass fill
-     * above made as many residents as fit beside the shadow slots; a routed layer it then put on
-     * the file tier needs two buffers it never paid for. Each resident given up pays for some of
-     * them -- and may put one more unit into a layer's file-tier share, growing them again -- so
-     * the resident count steps down, in rank order, from what the fill made until the residents,
-     * the shadow slots and the buffers fit together. Rank order spreads residency over the layers
-     * (rank_units), which is what keeps the largest layer's share -- the buffer -- small. A plan
-     * with nothing on the file tier never enters the loop. */
+    /* The file buffers come out of the same budget, which the two-pass fill did not charge. Each
+     * resident given up frees room but may grow a layer's file-tier share and so the buffers, so
+     * the resident cap steps down in rank order until residents, spares and buffers fit together.
+     * Rank order spreads residency over layers (rank_units), keeping the largest share small. */
     if (p->vram_budget > 0 && k.file > 0) {
         int64_t cap = k.residents;
         while (fixed + k.used + k.spare + k.file > p->vram_budget && cap > 0)
@@ -923,6 +770,12 @@ int Planner::assign_expert_tiered(Plan* p) {
     return rc;
 }
 
+bool Planner::host_kernel(const MoveUnit& mu) const {
+    for (rad_weight w : mu.weights)
+        if (w < host_ok_.size() && !host_ok_[w]) return false;
+    return true;
+}
+
 void Planner::note_unfit(Plan* p, const MoveUnit& mu, const char* why) const {
     const std::string what = mu.weights.empty()
         ? std::string("")
@@ -933,15 +786,16 @@ void Planner::note_unfit(Plan* p, const MoveUnit& mu, const char* why) const {
 }
 
 /* ------------------------------------------------------------------ op-level agreement */
-/* WeightInfo carries the site, but an OP runs in exactly one domain. Two weight operands of one
- * op that disagree about whether the arithmetic is on the host is not a placement the run phase
- * can execute -- a host kernel cannot read a VRAM pointer and a device kernel cannot read a
- * pageable one. So the planner reconciles, and it reconciles DOWNWARD: any disagreement collapses
- * to the device side, staged, because staging is the site that works from every tier.
- *
- * It is a repair and it is reported. A plan that needs it is usually a plugin that put a
- * per-layer weight in a model-level group, and the note is how that gets noticed. */
+/* An op runs in exactly one domain, so its weight operands must agree on the site: a host kernel
+ * cannot read VRAM and a device kernel cannot read pageable memory. A disagreement collapses to
+ * the device side, staged, since staging works from every tier. The repair is logged; it usually
+ * means a plugin put a per-layer weight in a model-level group. */
 void Planner::enforce_op_site_agreement(const Program& prog, Plan* p) {
+    /* On the host backend the weights pool is host memory and every op runs its host kernel, which
+     * reads the pool and the container's mapping alike: an op reading a mapped weight beside a
+     * converted one in the pool (hc_read's norm gain and its joined E4M3 mixing matrices) has no
+     * disagreement to repair. */
+    if (in_.host_backend) return;
     for (const OpInfo& o : prog.ops) {
         bool any_host = false, any_dev = false;
         for (rad_weight w : o.weights) {
@@ -957,11 +811,9 @@ void Planner::enforce_op_site_agreement(const Program& prog, Plan* p) {
             const int32_t u = p->unit_of_weight[w];
             if (u < 0 || p->units[(size_t)u].site != Site::Host) continue;
             MoveUnit& mu = p->units[(size_t)u];
-            /* EXCEPT A MAPPED ONE, which cannot be demoted: staging works from every tier but
-             * this one, because no device kernel for the op exists to read the staged copy. The
-             * op would be unrunnable either way, so the plan says so instead of quietly producing
-             * a placement that cannot serve. A weight reaches here only if the plugin grouped it
-             * with a host-only weight or an op reads both kinds -- both are plugin bugs. */
+            /* A mapped unit cannot be demoted: no device kernel exists to read a staged copy, so
+             * the op is unrunnable and the plan says so. This needs a plugin bug: a weight grouped
+             * with a host-only one, or an op reading both kinds. */
             if (mu.tier == Tier::Mapped) {
                 p->notes.push_back(fmt("op '%s' reads a weight only a host kernel can read "
                                        "alongside one placed on the device; no site serves both",
@@ -972,10 +824,8 @@ void Planner::enforce_op_site_agreement(const Program& prog, Plan* p) {
             }
             mu.site = Site::DeviceStaged;
             mu.reason = "op mixes host and device operands; demoted to staged";
-            /* A repair, not a misfit, so it does not go in the plan's did-not-fit list -- a plan
-             * that was repaired still fits, and marking it otherwise would make a caller treat a
-             * working plan as a failure. It IS visible: the class table shows a `staged` site
-             * where a `host` one was intended, and this line says which op caused it. */
+            /* A repair, not a misfit: the plan still fits, so it is warned about rather than
+             * listed as unfit. The report shows the `staged` site. */
             RAD_WARN("placement: op '%s' mixes host-site and device-site weight operands; layer "
                      "%d demoted to staged", o.op.c_str(), (int)mu.layer);
         }
@@ -983,13 +833,10 @@ void Planner::enforce_op_site_agreement(const Program& prog, Plan* p) {
 }
 
 /* ------------------------------------------------------------------ prefetch */
-/* The exact prefetch schedule. `at_op` is a DEADLINE, not a launch time: declare enumerated the
- * whole access sequence, so the planner knows precisely when each staged unit's bytes are needed
- * and states that. WHEN to start the transfer is the mover's problem, because it is a question
- * about slot supply -- a slot returns to the free list only when its quarantine event signals --
- * and a lead baked in here would be a constant guessing at a queue depth the planner cannot see.
- *
- * No policy and no predictor: a unit appears here exactly once, at the op that first reads it. */
+/* The exact prefetch schedule: each staged, non-routed unit once, at the op that first reads it.
+ * `at_op` is a deadline, not a launch time. When to start the copy is the mover's decision, since
+ * it depends on slot supply (a slot frees only when its quarantine event signals), which the
+ * planner cannot see. */
 void Planner::schedule_prefetch(Plan* p) {
     p->prefetch.clear();
     for (int32_t i = 0; i < (int32_t)p->units.size(); ++i) {
@@ -1007,9 +854,8 @@ void Planner::schedule_prefetch(Plan* p) {
 
 /* ------------------------------------------------------------------ finish */
 void Planner::finish(const Program& prog, Plan* p) {
-    /* Slab slots. Only a MOVABLE unit needs one: a statically resident weight is allocated once
-     * at a fixed offset and never relocates, so giving it a slot would buy nothing and cost the
-     * mover a slot it could have used. WeightInfo::slab_slot == -1 means exactly this. */
+    /* Only a movable unit gets a slab slot; a static resident lives at a fixed offset
+     * (slab_slot == -1). */
     std::vector next(p->classes.size(), 0);
     std::vector staged(p->classes.size(), 0);
     for (MoveUnit& mu : p->units) {
@@ -1018,8 +864,8 @@ void Planner::finish(const Program& prog, Plan* p) {
         } else {
             mu.slab_slot = -1;
         }
-        /* The ring serves the exact prefetch; a routed file-tier unit is read into the file
-         * stager's own buffers instead (Plan::file_stage_vram). */
+        /* The ring serves the exact prefetch; routed file-tier units use the file stager's
+         * buffers (Plan::file_stage_vram). */
         if (mu.site == Site::DeviceStaged && mu.slab_class >= 0 &&
             mu.access != RAD_ACCESS_CONDITIONAL)
             ++staged[(size_t)mu.slab_class];
@@ -1027,13 +873,10 @@ void Planner::finish(const Program& prog, Plan* p) {
     for (size_t c = 0; c < p->classes.size(); ++c) {
         p->classes[c].n_slots = next[c];
         p->classes[c].movable = next[c] > 0;
-        /* The staging ring, capped at the number of units that could use it: a class with one
-         * staged unit does not need two slots to double-buffer a single copy. */
+        /* The staging ring, capped at the number of staged units in the class. */
         p->classes[c].n_stage = std::min(RAD_PLACE_STAGE_RING, staged[c]);
-        /* n_shadow was set by the assignment pass, which is the only place that can reserve it
-         * out of the budget. Recomputing it here from the resident count would produce a second,
-         * differing number, and the mover would allocate against one while the operator was
-         * charged for the other. */
+        /* n_shadow comes from the assignment pass, which reserved it out of the budget; do not
+         * recompute it here, or the mover and the budget would see different numbers. */
         if (!p->classes[c].movable) p->classes[c].n_shadow = 0;
         const int64_t slots = p->classes[c].n_slots + p->classes[c].n_shadow +
                               p->classes[c].n_stage;
@@ -1041,7 +884,7 @@ void Planner::finish(const Program& prog, Plan* p) {
         if (slots > 0) p->slab_overhead += RAD_ALIGN_UNIT;   /* the slab's tail pad */
     }
 
-    /* Host runs, from the final assignment rather than from the intent. One entry is one run. */
+    /* Host runs, from the final assignment. */
     std::vector> host_layers;
     for (const MoveUnit& mu : p->units)
         if (mu.site == Site::Host && mu.layer >= 0) host_layers.push_back({mu.layer, mu.bytes});
@@ -1050,7 +893,6 @@ void Planner::finish(const Program& prog, Plan* p) {
         Plan::HostRun r;
         r.first_layer = host_layers[i].first;
         r.last_layer = host_layers[i].first;
-        r.bytes = 0;
         while (i < host_layers.size() &&
                (host_layers[i].first == r.last_layer || host_layers[i].first == r.last_layer + 1)) {
             r.last_layer = host_layers[i].first;
@@ -1059,13 +901,10 @@ void Planner::finish(const Program& prog, Plan* p) {
         }
         p->host_runs.push_back(r);
     }
-    /* Two crossings a run: the activation goes to host at the run's first layer and comes back at
-     * its last. This is the number the contiguity objective exists to hold down, so it is
-     * computed and printed rather than assumed. */
+    /* Two crossings a run: to the host at its first layer, back after its last. */
     p->link_crossings = 2 * (int32_t)p->host_runs.size();
 
-    /* Push the unit's decision down onto every weight, which is what the rest of the engine
-     * reads. WeightInfo is frozen and the planner is the component that fills these three. */
+    /* Copy each unit's decision onto its weights, which is what the rest of the engine reads. */
     p->weight.assign(prog.weights.size(), Placement{});
     p->totals = Plan::Totals{};
     for (int32_t i = 0; i < (int32_t)p->units.size(); ++i) {
@@ -1096,20 +935,17 @@ bool read_only_by(const Program& prog, rad_weight w, const char* op) {
     return read;
 }
 
-/* --embedding-placement ram: THE TOKEN EMBEDDING goes to the pinned host pool before any strategy
- * runs, and stays there. The site is DeviceZeroCopy: the host pool is mapped (Pools::configure),
- * so the lookup kernel is handed the pool's device-side address and reads its M rows of n_embd
- * over the link in place -- a few KiB a decode step -- while the table, the largest model-level
- * weight a dense model has, gives its VRAM to the KV cache. Every strategy and every VRAM total
- * skips the unit through MoveUnit::preplaced(), as they skip the mapped tier, and weight_footprint
- * has already counted it out of the statics with the same test, so the budget the card was split
- * by is the one the planner spends. A layer unit is never one: is_embedding_table asks for a
- * model-level weight, and a layer belongs to the offload strategies. */
+/* --embedding-placement ram: the token embedding goes to the pinned host pool before any strategy
+ * runs. The host pool is mapped (Pools::configure), so at the DeviceZeroCopy site the lookup
+ * kernel reads its M rows over the link in place, a few KiB a decode step, and the table's VRAM
+ * goes to the KV cache. Strategies skip it via MoveUnit::preplaced(), and weight_footprint counts
+ * it out of the statics with the same test, so budget and plan agree. Only model-level weights
+ * qualify (is_embedding_table). */
 int Planner::pin_embedding(const Program& prog, const Config& cfg, Plan* p) const {
     if (cfg.embedding_resolved != TablePlacement::Ram) return RAD_OK;
     int rc = RAD_OK, found = 0;
     for (MoveUnit& mu : p->units) {
-        /* build_units gives a model-level weight a unit of its own: it is the unit's one weight. */
+        /* A model-level unit holds exactly one weight (build_units). */
         if (mu.layer >= 0 || mu.weights.empty() || mu.tier == Tier::Mapped) continue;
         const rad_weight w = mu.weights.front();
         if (!is_embedding_table(prog, w)) continue;
@@ -1136,25 +972,22 @@ int Planner::pin_embedding(const Program& prog, const Config& cfg, Plan* p) cons
                  "(--embedding-placement ram%s)", name.c_str(), humanb(mu.bytes).c_str(),
                  cfg.embedding_placement_given ? "" : ", the default");
     }
-    /* Engine::plan resolves Ram only where weight_footprint found a table with this same test,
-     * so an empty pass is a plan built from a different program than the budget was: a wiring
-     * fault, said by name rather than leaving the table on the card the budget split without it. */
+    /* Engine::plan resolves Ram only where weight_footprint found a table by the same test, so
+     * finding none means the plan and the budget saw different programs. */
     if (!found) {
-        RAD_ERR("placement: --embedding-placement ram, and this rank's program has no model-level "
-                "weight that only embed_lookup reads");
+        RAD_ERR("placement: --embedding-placement ram found no model-level weight that only "
+                "embed_lookup reads");
         p->notes.push_back("--embedding-placement ram: no token embedding table to place");
         rc = RAD_E_STATE;
     }
     return rc;
 }
 
-/* --vision-tower-placement ram: EVERY UNIT OF AN ENCODER TOWER goes to the pinned host pool before
- * any strategy runs, as the embedding does, at the DeviceZeroCopy site: the encoder's kernels read
- * the weights over the link in place, once an image or a clip, and a text-only request never
- * touches them. A tower's unit is one whose every weight the architecture declared read once per
- * request (RAD_ACCESS_PER_REQUEST) -- the test weight_footprint counted out of the statics with,
- * so the budget the card was split by is the one spent here. The test is the access class and not
- * the unit's level: a tower is model-level weights (a stem, a merger) and a layer unit a block. */
+/* --vision-tower-placement ram: every encoder-tower unit goes to the pinned host pool before any
+ * strategy runs, read in place at the DeviceZeroCopy site once per image or clip; text-only
+ * requests never touch it. A tower unit is a non-expert unit with access RAD_ACCESS_PER_REQUEST,
+ * the same test weight_footprint uses. It is tested by access class, not level, because a tower
+ * has both model-level weights (a stem, a merger) and layer units (its blocks). */
 int Planner::pin_towers(const Config& cfg, Plan* p) const {
     if (cfg.tower_resolved != TablePlacement::Ram) return RAD_OK;
     auto tower = [](const MoveUnit& mu) {
@@ -1164,10 +997,9 @@ int Planner::pin_towers(const Config& cfg, Plan* p) const {
     int64_t need = 0, n = 0;
     for (const MoveUnit& mu : p->units)
         if (tower(mu)) { need += mu.slot_bytes; ++n; }
-    /* Engine::plan resolves Ram only where weight_footprint found a tower with this same test. */
+    /* Engine::plan resolves Ram only where weight_footprint found a tower by the same test. */
     if (!n) {
-        RAD_ERR("placement: --vision-tower-placement ram, and this rank's program has no weight it "
-                "reads once per request");
+        RAD_ERR("placement: --vision-tower-placement ram found no weight read once per request");
         p->notes.push_back("--vision-tower-placement ram: no encoder tower to place");
         return RAD_E_STATE;
     }
@@ -1217,30 +1049,17 @@ int Planner::plan(Plan* out) {
         return RAD_E_INVAL;
     }
 
-    resolve_sites(prog);
+    resolve_sites(prog, &host_ok_, &device_ok_);
     build_units(prog, out);
-    /* BEFORE build_classes and before assign: the mapped tier is not a fallback the budgets
-     * choose, it is where a weight no device kernel can read has to be. */
+    /* Before build_classes and assign: mapped units get no class and no budget. */
     pin_mapped(prog, out);
     build_classes(out);
 
-    /* CHARGE THE FILE TIER'S STAGING POOL BEFORE PLACING ANYTHING IN THE HOST POOL.
-     *
-     * A unit read from the container lands in a pinned buffer, and those come out of
-     * --host-pool-mib. Handing HostFall the whole budget lets it fill the pool with pinned units,
-     * and the mover then asks the exhausted pool for its staging slots and refuses a plan the
-     * report has just called a fit. Reserving here is the same rule the VRAM side follows for the
-     * slab ring: the component that budgets an allocation has to budget ALL of it.
-     *
-     * Sized off the widest class that carries a LAYER unit, because that is the only kind either
-     * offload strategy spills -- model-level weights stay put in both. It is an upper bound on
-     * what the mover will compute from the units that actually land on the file tier, and over-
-     * reserving costs one spilled layer where under-reserving costs the whole plan.
-     *
-     * A model with ROUTED units also gets the read windows a routed layer streams through
-     * (RAD_PLACE_FILE_WINDOWS), whether or not this plan ends up putting one there: which units
-     * land on the file tier is decided by the fill below, and that fill spends the host budget
-     * this line leaves it. */
+    /* Charge the file tier's staging pool (RAD_PLACE_FILE_STAGE_SLOTS) before anything is placed
+     * in the host pool, or the fill could exhaust it and the mover refuse the plan. Sized from the
+     * widest class carrying a layer unit, the only kind either offload strategy spills; this
+     * upper-bounds what the mover computes. A model with routed units also reserves the read
+     * windows, since which units reach the file tier is decided only by the fill below. */
     if (ssd_) {
         int64_t widest = 0;
         bool routed = false;
@@ -1268,7 +1087,7 @@ int Planner::plan(Plan* out) {
         }
     }
 
-    /* NOT a RAD_TRY: a refusal still leaves `out` filled in far enough to print. */
+    /* Not RAD_TRY: a refusal still leaves `out` filled in far enough to print. */
     int hrc = pin_embedding(prog, cfg, out);
     const int trc = pin_towers(cfg, out);
     if (hrc >= 0) hrc = trc;
@@ -1290,10 +1109,8 @@ int Planner::assign(Plan* p) {
 
     Strategy s = p->strategy;
     if (s == Strategy::Auto) {
-        /* `auto` is a choice between three named strategies and nothing more -- it never invents a
-         * fourth. It fits if it can, prefers spilling routed experts over dense layers when there
-         * are experts to spill (a conditional weight is read only when selected; a dense one is
-         * read every token), and offloads layers otherwise. */
+        /* `auto` picks one of the three named strategies: all_vram if it fits, else expert
+         * offload when there are routed experts (read only when selected), else layer offload. */
         if (p->vram_budget <= 0 || total <= p->vram_budget) s = Strategy::AllVram;
         else if (has_conditional)                           s = Strategy::ExpertTiered;
         else                                                s = Strategy::LayerOffload;
@@ -1314,9 +1131,8 @@ int Planner::assign(Plan* p) {
     }
 
     if (s != Strategy::AllVram && p->vram_budget <= 0) {
-        /* Every pool is budgeted explicitly (spec §6). An offload strategy with no number to
-         * spill against would have to infer one from free VRAM, and an engine that quietly
-         * re-optimises its own split is an engine whose benchmarks do not reproduce. */
+        /* Offload needs an explicit budget (spec §6); inferring one from free VRAM would make
+         * runs irreproducible. */
         RAD_ERR("placement: %s needs a weights budget and none was resolved; there is nothing to "
                 "spill against",
                 strategy_name(s));
@@ -1333,13 +1149,11 @@ int Planner::assign(Plan* p) {
 
 /* ------------------------------------------------------------------ the report (spec §16) */
 std::string Plan::report(const Program& prog) const {
-    /* One line per weight CLASS. A model with eleven thousand routed experts has eleven thousand
-     * weights and three lines worth reading; printing one line each is how a report becomes
-     * something nobody opens. */
+    /* One line per weight class (weight_class_key), not per weight. */
     struct Row {
         int64_t n = 0, bytes = 0;
         int64_t per_tier[kTierCount] = {0};
-        int64_t per_site[4] = {0, 0, 0, 0};
+        int64_t per_site[kSiteCount] = {0};
     };
     std::map rows;
     std::vector order;
@@ -1370,7 +1184,7 @@ std::string Plan::report(const Program& prog) const {
             if (r.per_tier[t])
                 tiers += fmt("%s%s %lld", tiers.empty() ? "" : " / ", tier_name((Tier)t),
                              (long long)r.per_tier[t]);
-        for (int t = 0; t < 4; ++t)
+        for (int t = 0; t < kSiteCount; ++t)
             if (r.per_site[t])
                 sites += fmt("%s%s %lld", sites.empty() ? "" : " / ", site_name((Site)t),
                              (long long)r.per_site[t]);
@@ -1390,22 +1204,18 @@ std::string Plan::report(const Program& prog) const {
                  humanb(totals.bytes[(int)Tier::HostPageable]).c_str());
     s += fmt("  ssd tier      %12s  %12s\n", "unbounded",
              humanb(totals.bytes[(int)Tier::SSD]).c_str());
-    /* NO BUDGET COLUMN, and the dash is the statement: a mapped weight occupies the container's
-     * own mapping and no pool at all, so there is nothing for an operator to size. What it does
-     * cost is page cache, which is the OS's to manage. */
+    /* No budget: a mapped weight occupies only page cache, which the OS manages. */
     if (totals.bytes[(int)Tier::Mapped])
         s += fmt("  mapped        %12s  %12s   (the container's mapping; no pool)\n", "-",
                  humanb(totals.bytes[(int)Tier::Mapped]).c_str());
-    /* Taken out of --host-pool-mib before any weight was placed, so the `host pinned` budget above
-     * is smaller than the flag by exactly this. Printed rather than folded in: an operator who
-     * raises --host-pool-mib and sees less of it reach the weights than expected is owed the
-     * reason on the same page. */
+    /* Taken out of --host-pool-mib before placement, so the `host pinned` budget above is smaller
+     * than the flag by this much. */
     if (file_stage_reserve)
         s += fmt("  file staging  %12s  %12s   (%d slots%s, pinned)\n", "-",
                  humanb(file_stage_reserve).c_str(), RAD_PLACE_FILE_STAGE_SLOTS,
                  file_windows ? fmt(" and %d read windows", RAD_PLACE_FILE_WINDOWS).c_str() : "");
-    /* The same, for --embedding-placement ram: out of --host-pool-mib before any strategy, read
-     * in place. And the n-gram copy, which no pool holds: locked RAM the load phase fills. */
+    /* Likewise taken out of --host-pool-mib: the embedding and the encoder towers. The n-gram copy
+     * is in no pool; the load phase fills it. */
     if (embedding_host_bytes)
         s += fmt("  embedding     %12s  %12s   (--embedding-placement ram, pinned, read in place)\n",
                  "-", humanb(embedding_host_bytes).c_str());
@@ -1416,9 +1226,7 @@ std::string Plan::report(const Program& prog) const {
         s += fmt("  n-gram copy   %12s  %12s   (--ngram-placement ram, %s, filled at load)\n",
                  "-", humanb(ngram_copy_bytes).c_str(),
                  ngram_copy_card ? "pinned RAM the card reads" : "locked RAM");
-    /* Out of the VRAM weight budget, beside the residents and not among them: the two buffers a
-     * routed layer's file-tier experts are read into, each sized to the layer that puts the most
-     * there. */
+    /* The file stager's two VRAM buffers, out of the weight budget but not among the residents. */
     if (file_stage_vram)
         s += fmt("  file buffers  %12s  %12s   (two of %s: the most one routed layer reads from "
                  "the container)\n", "-", humanb(file_stage_vram).c_str(),
@@ -1456,9 +1264,7 @@ std::string Plan::report(const Program& prog) const {
     if (!notes.empty() || !unfit.empty()) {
         s += "\n  DID NOT FIT\n";
         for (const std::string& n : notes) s += "    " + n + "\n";
-        /* Aggregated, so nine hundred stranded experts are one line. The count and the bytes are
-         * what an operator needs to size the next run; the identity of expert 107 of layer 47 is
-         * not, and printing it nine hundred times buries the two numbers that are. */
+        /* Aggregated by class and reason: the count and bytes are what sizing the next run needs. */
         for (const Unfit& u : unfit)
             s += fmt("    %lld x %s (%s): %s\n", (long long)u.count, u.what.c_str(),
                      humanb(u.bytes).c_str(), u.why.c_str());
diff --git a/core/place/planner.h b/core/place/planner.h
index 9ac243e8..1eb08958 100644
--- a/core/place/planner.h
+++ b/core/place/planner.h
@@ -1,38 +1,28 @@
-/* planner.h -- the placement planner. Runs ONCE, after declare and before load, and assigns every
+/* planner.h -- the placement planner. Runs once, after declare and before load, and assigns every
  * weight a tier and an execution site against explicit pool budgets (spec §5.3).
  *
- * ---- THE ONE IDEA IN THIS DIRECTORY ------------------------------------------------------------
+ * All-in-VRAM, layer offload and expert offload are one mechanism at three granularities, over
+ * the same tiers. They differ in whether the access is predictable:
  *
- * All-in-VRAM, layer offload to RAM/SSD, and expert offload to RAM/SSD are ONE MECHANISM AT THREE
- * GRANULARITIES. What separates them is not the tiering -- the tiers are the same four -- but
- * whether the access is PREDICTABLE, and that distinction is the shape of this code:
+ *   Layer offload is a scheduling problem. WeightInfo::first_use_op is the full access sequence,
+ *   known statically from declare, so Plan::prefetch is an exact schedule with no predictor.
  *
- *   LAYER OFFLOAD IS A SCHEDULING PROBLEM. Declare already enumerated every op with its weight
- *   operands in order, so WeightInfo::first_use_op is the entire future access sequence, known
- *   statically. The planner emits an exact prefetch schedule off it (Plan::prefetch). No policy,
- *   no predictor, nothing to be wrong about.
+ *   Expert offload is a prediction problem. Routing is data-dependent, so the planner only ranks
+ *   an initial residency and heat.h re-ranks from real routing.
  *
- *   EXPERT OFFLOAD IS A PREDICTION PROBLEM. Routing is data-dependent, so the only thing the
- *   planner can do is rank an initial residency and hand the rest to heat.h. This is why expert
- *   offload needs a heat engine and layer offload (llama.cpp's) does not.
+ *   All-in-VRAM is the degenerate case: every weight on tier 0 and the mover never runs.
  *
- *   ALL-IN-VRAM IS THE DEGENERATE CASE where every weight lands on tier 0 and the mover never
- *   runs. It is not a separate path; it is this one with a budget that fits.
- *
- * ---- TIER AND SITE ARE INDEPENDENT AXES (spec §5.1) --------------------------------------------
- *
- * Tier is where the bytes live. Site is where the arithmetic happens. All four combinations are
- * core behaviour:
+ * Tier (where the bytes live) and site (where the arithmetic runs) are independent axes
+ * (spec §5.1):
  *
  *   VRAM       + Device          vLLM
  *   host/SSD   + DeviceStaged    staged into a slab slot, exact or predicted
  *   host       + DeviceZeroCopy  the GEMM streams the weight over the link as it computes; no
- *                                slab slot, so a read-once weight costs no residency at all
+ *                                slab slot, so a read-once weight costs no residency
  *   host       + Host            llama.cpp -ngl
  *
- * Host-site execution needs a RAD_DOMAIN_HOST kernel. Where declare resolved none, that site is
- * UNAVAILABLE for that op, and the planner is told so by reading Band::dom[RAD_DOMAIN_HOST]
- * rather than by being passed a flag -- the resolution is the fact.
+ * The host site needs a RAD_DOMAIN_HOST kernel; the planner reads its availability from
+ * Band::dom[RAD_DOMAIN_HOST] rather than from a flag.
  */
 #pragma once
 #include "../rad_core.h"
@@ -51,10 +41,9 @@ const char* strategy_name(Strategy s);
 int         strategy_parse(const char* s, Strategy* out);
 
 /* ------------------------------------------------------------------ budgets */
-/* Every pool is budgeted explicitly. No profiling pass, no utilisation fraction, no inference
- * about what the workload will be (spec §6). The one thing a zero means is stated here rather
- * than guessed at each use: zero vram_weights is "no cap", which is answerable only under
- * all_vram -- any offload strategy needs a number to spill against and says so by name.
+/* Every pool is budgeted explicitly: no profiling pass, no utilisation fraction (spec §6). Zero
+ * vram_weights means "no cap", which only all_vram accepts; an offload strategy needs a number
+ * to spill against.
  */
 struct Budgets {
     int64_t vram_weights = 0;    /* bytes; 0 = uncapped, legal only when everything fits */
@@ -65,27 +54,22 @@ struct Budgets {
 };
 
 /* ------------------------------------------------------------------ the movement unit */
-/* THE UNIT OF PLACEMENT IS A GROUP, NOT A TENSOR. An expert's gate/up/down share one
- * RadWeightGroup because a dispatch holding two of the three has nothing it can compute; a
- * layer's weights share one because layer offload is a contiguous run rather than a scatter
- * (spec §4.1). Everything below -- the slab's fixed stride, the mover's copy, heat's ranking --
- * is per unit, and a weight's placement is its unit's placement.
+/* The unit of placement is a weight group, not a tensor. An expert's gate/up/down share one
+ * RadWeightGroup because a dispatch missing one of them cannot compute; a layer's weights share one
+ * because layer offload moves contiguous runs (spec §5.3). Slab stride, mover copies and heat
+ * ranking are all per unit, and a weight's placement is its unit's placement.
  *
- * UNDER TENSOR PARALLEL A UNIT IS THIS RANK'S SHARD OF THE GROUP. The plugin declares dimensions
- * already divided (spec §9), so `bytes` is already per-rank and the planner budgets against this
- * card. What the planner still owes TP is the harder half, and it is an invariant rather than an
- * arithmetic: THE RESIDENT SET MUST BE IDENTICAL ON EVERY RANK. Each rank holds its own half of
- * every resident expert, so a slab slot only means the same thing everywhere if every rank
- * decided the same experts were in it. That is why the ranking below is keyed on the container's
- * profile and the unit's identity and on nothing rank-local -- no free-VRAM query, no timing, no
- * device enumeration. The invariant is a property of how the ranking is computed rather than a
- * condition checked before placement may run.
+ * Under tensor parallel a unit is this rank's shard: dimensions are declared already divided
+ * (spec §9), so `bytes` is per rank. Invariant: the resident set must be identical on every rank,
+ * or a slab slot holds different experts on different cards. The ranking therefore uses only the
+ * container's profile and the unit's identity -- no free-VRAM query, no timing, no device
+ * enumeration.
  */
 struct MoveUnit {
     int32_t layer = -1;          /* RadWeightGroup::layer; -1 for a model-level weight */
     int32_t expert = -1;         /* RadWeightGroup::expert; -1 for a non-expert group */
     int32_t slab_class = -1;     /* index into Plan::classes */
-    int64_t bytes = 0;           /* THIS RANK's shard of the whole group */
+    int64_t bytes = 0;           /* this rank's shard of the whole group */
     int32_t first_use_op = -1;   /* min over the group; the prefetch schedule keys on it */
     int32_t last_use_op = -1;
     int     access = RAD_ACCESS_PER_TOKEN;   /* the group's strongest access class */
@@ -98,43 +82,38 @@ struct MoveUnit {
     bool    host_forced = false; /* a placement flag put it in the pinned pool: the embedding's
                                   * or the encoder tower's */
 
-    /* PLACED BEFORE ANY STRATEGY RAN, so every assignment pass skips it and no VRAM total counts
-     * it: the mapped tier (no device kernel can read it), --embedding-placement ram and
-     * --vision-tower-placement ram. */
+    /* Placed before any strategy runs, so every assignment pass skips it and no VRAM total counts
+     * it: the mapped tier, --embedding-placement ram and --vision-tower-placement ram. */
     bool preplaced() const { return tier == Tier::Mapped || host_forced; }
-    const char* reason = "fits in vram";   /* a fixed string, so the report never guesses */
+    const char* reason = "fits in vram";   /* a fixed string for the report */
 
-    /* The group's INTERNAL LAYOUT, computed once here so the mover never has to. `offset[i]` is
-     * where weights[i] sits inside the unit, honouring that weight's declared alignment, and
-     * `bytes` is the padded total. One definition, because the mover's copy size, the pool offset
-     * it reads and the pointer it publishes must agree and they are written in three places. */
+    /* The group's internal layout, computed once here: `offset[i]` is where weights[i] sits in the
+     * unit at its declared alignment, and `bytes` is the padded total. The mover's copy size, pool
+     * offset and published pointer all derive from it. */
     std::vector weights;
     std::vector    offset;
 
-    /* WHAT THE UNIT ACTUALLY COSTS A POOL, which is its class's slot stride and not `bytes`. The
-     * planner budgets against this and the mover allocates this, so the two cannot drift -- and
-     * the direction they would drift in is an overrun of the weights pool. `bytes` is
-     * still what the report attributes to the weights, because padding is not a weight. */
+    /* What the unit costs a pool: its class's slot stride, not `bytes`. The planner budgets and
+     * the mover allocates this same number, so they cannot drift into a weights-pool overrun. The
+     * report still attributes `bytes`, since padding is not weight. */
     int64_t slot_bytes = 0;
 
-    /* Every weight of it lies in the container exactly as its kernel reads it (weight_file_direct),
-     * so the file tier can stage it with a read. A unit that is not is never placed there. */
+    /* Every weight lies in the container exactly as its kernel reads it (weight_file_direct), so
+     * the file tier can stage it with a read. A unit that is not never goes to the file tier. */
     bool    file_direct = true;
 };
 
-/* The strongest access class in a group decides the group's. Strongest means "read most surely":
- * a group holding one PER_TOKEN weight is read on every forward pass whatever the rest of it is,
- * and calling it conditional would let the heat engine demote something the next token needs.
- * VOCAB ranks with PER_TOKEN -- lm_head and the embedding table are read every token; what makes
- * them their own class is their size and the gather, not their certainty (spec §19.2). */
+/* The strongest access class in a group, "read most surely", decides the group's: a group with
+ * one PER_TOKEN weight is read every forward pass, and calling it conditional would let heat
+ * demote something the next token needs. VOCAB ranks with PER_TOKEN; lm_head and the embedding
+ * are read every token and differ only in size and the gather (spec §5.2). */
 int access_strength(int access);
 
 /* ------------------------------------------------------------------ the slab class */
-/* Fixed-stride VRAM slab slots per weight class (spec §5.4). One stride per class, so a slot is
- * interchangeable within its class and the mover's bookkeeping is an integer rather than an
- * allocator. The stride is the class's largest unit rounded to the movement-unit alignment; the
- * padding that costs is the price of never fragmenting, and a fragmenting slab is a slab whose
- * hit rate depends on the order promotions happened to arrive in.
+/* Fixed-stride VRAM slab slots per weight class (spec §5.4). Slots are interchangeable within a
+ * class, so the mover's bookkeeping is an integer, not an allocator. A class is keyed on the unit
+ * kind and the unit size rounded to the movement-unit alignment, so every unit of a class has
+ * the class's stride and the slab never fragments.
  */
 struct SlabClass {
     std::string name;            /* "expert", "layer", "model" plus the byte size */
@@ -146,78 +125,52 @@ struct SlabClass {
     bool        movable = false;
 };
 
-/* THE STAGING RING. A DeviceStaged unit lives off the device and is copied into a slab slot
- * before its op runs, so a class holding staged units needs slots that belong to no unit. Two is
- * double buffering -- one slot being read by the op that is running, one landing for the op
- * after it -- and it is the minimum depth that overlaps anything at all.
- *
- * More is better hiding at more VRAM, and where the curve flattens is a measurement rather than a
- * principle; it is not a Config field because Config is frozen and this is the honest
- * default rather than a tuned one. If it becomes worth tuning it wants a --stage-ring flag beside
- * the other explicit budgets in spec §6, NOT a heuristic derived from free VRAM. */
+/* Staging ring: slab slots that belong to no unit, which a DeviceStaged unit is copied into
+ * before its op runs. Two is double buffering (one slot read by the running op, one landing for
+ * the next), the minimum that overlaps anything. Deeper hides more at more VRAM; if it needs
+ * tuning it should become an explicit budget flag (spec §6), not a heuristic from free VRAM. */
 #define RAD_PLACE_STAGE_RING 2
 
-/* THE FILE TIER'S STAGING POOL, IN PINNED HOST SLOTS. A unit read from the container lands in a
- * pinned buffer the mover can DMA out of without a bounce (spec §5.4), and those buffers come out
- * of --host-pool-mib like everything else on the host side.
- *
- * It is defined HERE, beside the VRAM ring, because the planner has to charge the operator for it
- * and the mover has to allocate exactly what was charged. Were it a mover-side default instead,
- * the planner would fill the host pool with pinned units and the mover would then ask the
- * exhausted pool for these slots and refuse the plan -- the same shape as the slab overhead on
- * the VRAM side, and the same rule: whoever budgets a thing owns its number. */
+/* The file tier's staging pool, in pinned host slots: a unit read from the container lands in a
+ * pinned buffer the mover can DMA out of without a bounce (spec §5.4). Defined here because the
+ * planner charges it to --host-pool-mib and the mover must allocate exactly that; a mover-side
+ * default would let the planner fill the pool first and the mover then refuse the plan. */
 #define RAD_PLACE_FILE_STAGE_SLOTS 4
 
-/* THE WINDOWS A ROUTED LAYER IS READ THROUGH, when routed experts land on the file tier. A layer's
- * file-tier experts are read as long sequential runs of the container -- a few gigabytes a layer
- * for a bf16 model -- so the read does not go a unit at a time into the slots above: it fills one
- * pinned window while the window before it drains to the card, and the host waits on a window
- * only when it comes round again. Four of 32 MiB keep a drive at its sequential rate (a pread of
- * this size is ~5 ms at 7 GB/s, the copy out of it under 2) for 128 MiB of pinned memory, charged
- * out of --host-pool-mib like the slots. */
+/* Pinned read windows for routed experts on the file tier. A layer's file-tier experts are read
+ * as long sequential runs of the container: one window fills while the previous one drains to the
+ * card. Four of 32 MiB keep a drive at its sequential rate (a 32 MiB pread is ~5 ms at 7 GB/s,
+ * the copy out under 2 ms) for 128 MiB pinned, charged to --host-pool-mib. */
 #define RAD_PLACE_FILE_WINDOWS 4
 #define RAD_PLACE_FILE_WINDOW_BYTES ((int64_t)32 << 20)
 
-/* THE HEAT ENGINE'S MOVE BUDGET: swaps a STEP, a slab class. HeatParams::moves_per_step defaults
- * to it, and the free slots below are sized from it, because the two are one quantity: a swap
- * that finds no free slot does not happen.
- *
- * The engine proposes once a step (Engine::tiering_dispatch), and a step routes every layer, so
- * the budget has to cover the whole model's turnover. Replaying the routing of a mixed workload
- * through the engine's policy at Qwen3.8-Flash-Next TP1 (40% of the experts resident), the hit
- * rate on decode rows is 63.8% at 8 a step, 74.1% at 32, 77.1% at 64 and 77.8% at 128 -- and an
- * oracle that knows every future routing, held to the same 64 swaps a step, reaches 78.0%. Past
- * this the move rate, not the ranking, is what bounds the hit rate. */
+/* Heat engine move budget: swaps per step per slab class. HeatParams::moves_per_step defaults to
+ * it and the free slots below are sized from it, since a swap without a free slot does not happen.
+ * The engine proposes once a step (Engine::tiering_dispatch) for every layer. Replaying a mixed
+ * workload on Qwen3.8-Flash-Next TP1 with 40% of experts resident, the decode hit rate is 63.8% at
+ * 8, 74.1% at 32, 77.1% at 64 and 77.8% at 128; an oracle held to 64 reaches 78.0%, so past 64
+ * the move rate, not the ranking, bounds the hit rate. */
 #define RAD_PLACE_MOVES_PER_STEP 64
 
-/* SHADOW SLOTS: slab slots that are allocated but hold no unit, so a promotion writes into one
- * and only then publishes and never DMAs over a slot a kernel might still be reading (mover.h).
- *
- * THEY COME OUT OF THE WEIGHTS POOL, like everything else in the slab. Taking them from
- * whatever VRAM is left over after the slabs is not an option: spec §6 budgets every pool
- * explicitly and --gpu-headroom-mib is memory the engine promises NOT to touch. So dynamic
- * placement costs a few resident units, and the plan report prints exactly how many.
- *
- * THESE ARE THE SLOTS THE ENGINE CAN ALWAYS COUNT ON, and the expert floor charges for them
- * (expert_vram_floor), so every slot here is one the KV cache can never have. The rest of what the
- * move budget needs is RAD_PLACE_TURNOVER_SLOTS, taken out of the cache's loan instead. The
- * quarter-of-the-slab cap only ever binds on a slab too small for the number to be meaningful. */
+/* Shadow slots: allocated slab slots holding no unit. A promotion writes into one and only then
+ * publishes, so it never DMAs over a slot a kernel may still be reading (mover.h). They come out
+ * of the weights pool, not leftover VRAM: every pool is budgeted (spec §6) and --gpu-headroom-mib
+ * is untouchable. The expert floor charges for them (expert_vram_floor), so the KV cache never
+ * gets them; the rest of the move budget is RAD_PLACE_TURNOVER_SLOTS. The quarter-of-the-slab cap
+ * binds only on very small slabs. */
 #define RAD_PLACE_SHADOW_SLOTS 32
 
-/* THE TURNOVER SLOTS: free slab slots the mover keeps out of a loan (Mover::lend_from), past the
- * shadow slots, by filling the loan's slots only up to them. A swap holds a slot for about three
- * steps -- the copies go out behind the step that proposed them, the next step's retire publishes
- * them, and the slot the demotion left comes back only once the compute stream has passed the
- * quarantine recorded after that publish -- so a budget of RAD_PLACE_MOVES_PER_STEP needs three
- * times as many free slots, and with fewer the budget is smaller than it says. At 64 a step,
- * replaying the routing with 32 slots in all reaches 65.9% against 77.9% with 192.
+/* Turnover slots: free slab slots the mover keeps out of a loan (Mover::lend_from) beyond the
+ * shadow slots. A swap holds a slot for about three steps (copy behind the proposing step,
+ * publish at the next step's retire, then the demoted slot's quarantine), so
+ * RAD_PLACE_MOVES_PER_STEP needs three times as many free slots. At 64 a step, 32 slots in all
+ * give a 65.9% hit rate against 77.9% with 192.
  *
- * Out of the loan because that costs the cache nothing: a lent slot left free is one the experts
- * were borrowing anyway, and charged to the expert floor instead the same slots would come out of
- * the cache's largest size. When the cache takes memory back, the free slots at the loan's top go
- * first and the mover rebuilds them by dropping its coldest lent units, which still have their
- * host copies (Mover::balance); only once nothing is lent does the move rate fall back to what
- * the shadow slots alone allow. */
+ * They come out of the loan because a lent slot left free costs the cache nothing; charged to the
+ * expert floor they would shrink the cache's largest size. When the cache reclaims memory, the
+ * free slots at the loan's top go first and the mover rebuilds them by dropping its coldest lent
+ * units, which keep host copies (Mover::balance). With nothing lent, only the shadow slots
+ * remain. */
 #define RAD_PLACE_TURNOVER_SLOTS (3 * RAD_PLACE_MOVES_PER_STEP - RAD_PLACE_SHADOW_SLOTS)
 
 /* ------------------------------------------------------------------ per-weight result */
@@ -227,7 +180,7 @@ struct Placement {
     int32_t slab_slot = -1;
     int32_t unit = -1;
     int64_t bytes = 0;
-    /* Why this and not VRAM/device, as a fixed string so the report never has to guess. */
+    /* Why this and not VRAM/device, as a fixed string for the report. */
     const char* reason = "";
 };
 
@@ -239,11 +192,9 @@ public:
     /* Why `strategy` is the one it is, when `auto` chose it; empty when it was asked for. */
     std::string strategy_why;
 
-    /* False under Config::deterministic. Dynamic placement sets which experts are resident and
-     * residency sets the summation order, so identical inputs do not give identical outputs
-     * (spec §17). This is that mode as a real property of the plan -- the heat engine reads it
-     * and stays off, and the mover reads it and allocates no shadow slots -- rather than a flag
-     * that is checked nowhere. */
+    /* False under Config::deterministic: residency sets the summation order, so dynamic placement
+     * breaks bitwise reproducibility (spec §17). The heat engine stays off and the mover allocates
+     * no shadow slots when it is false. */
     bool     dynamic = true;
 
     std::vector weight;         /* by rad_weight; index 0 is the sentinel */
@@ -251,63 +202,52 @@ public:
     std::vector   unit_of_weight; /* by rad_weight; -1 for the sentinel */
     std::vector classes;
 
-    /* Host-site work, in EXECUTION ORDER, as runs. A host-site op leaves its activation in host
-     * memory, so a host layer between two device layers costs two link crossings; a few hundred
-     * KB is nothing and alternating per layer is not. llama.cpp gets this free because -ngl
-     * assigns a contiguous suffix. Here it is an explicit objective, and this vector is the
-     * evidence: one entry means one run, and `link_crossings` is what the plan costs a step. */
+    /* Host-site layers in execution order, as runs. A host-site op leaves its activation in host
+     * memory, so every run costs two link crossings and alternating per layer is expensive.
+     * Contiguity is an explicit objective; `link_crossings` is the per-step cost. */
     struct HostRun { int32_t first_layer = 0, last_layer = 0; int64_t bytes = 0; };
     std::vector host_runs;
     int32_t link_crossings = 0;
 
-    /* THE EXACT PREFETCH SCHEDULE. Layer offload is a scheduling problem: this is the whole of
-     * the policy, and it is a sorted list rather than a predictor. `at_op` is the op index by
-     * which the unit's bytes must have landed, already backed off by the configured lead. */
+    /* The exact prefetch schedule for staged, non-routed units, sorted by `at_op`: the op index by
+     * which the unit's bytes must have landed. */
     struct Prefetch { int32_t at_op = 0; int32_t unit = 0; };
     std::vector prefetch;
 
     struct Totals { int64_t bytes[kTierCount] = {0}; };   /* indexed by Tier */
     Totals  totals;
-    /* `host_budget` is what is left for WEIGHTS after the file tier's staging pool is taken out of
-     * --host-pool-mib, so the number the placement passes spend against is the number they may
-     * actually have. `file_stage_reserve` is what was taken, reported so the operator can see
-     * where the difference went: the unit slots, plus the read windows when a routed expert can
-     * land on the file tier. */
+    /* `host_budget` is what --host-pool-mib leaves for weights after the file tier's staging pool.
+     * `file_stage_reserve` is that pool, reported so the difference is visible: the unit slots,
+     * plus the read windows when a routed expert can land on the file tier. */
     int64_t vram_budget = 0, host_budget = 0;
     int64_t file_stage_reserve = 0;
     int64_t file_windows = 0;          /* the read windows' part of it */
-    /* --embedding-placement ram and --vision-tower-placement ram: the pool slots each flag's
-     * units took before any strategy ran, like the file staging above, and reported beside it
-     * rather than among the pooled units. `forced_host_used` is both flags' weight bytes, the unit
-     * the tier totals count in, which the pooled weights' figures leave out. */
+    /* --embedding-placement ram and --vision-tower-placement ram: host-pool bytes each flag's units
+     * took before any strategy ran, reported apart from the pooled units. `forced_host_used` is
+     * both flags' weight bytes, as the tier totals count them; the pooled figures exclude it. */
     int64_t embedding_host_bytes = 0;
     int64_t tower_host_bytes = 0;
     int64_t forced_host_used = 0;
-    /* --ngram-placement ram: the n-gram tables the load phase copies into host memory. They stay
-     * on the mapped tier as far as every pool is concerned; this is what the copy costs in RAM.
-     * `ngram_copy_card` says which copy: pinned memory a device kernel reads in place over the
-     * link, or locked memory the host gather reads. */
+    /* --ngram-placement ram: RAM for the n-gram tables the load phase copies out of the mapping.
+     * Every pool still sees them on the mapped tier. `ngram_copy_card` selects pinned memory a
+     * device kernel reads over the link; otherwise locked memory the host gather reads. */
     int64_t ngram_copy_bytes = 0;
     bool    ngram_copy_card = false;
-    /* ROUTED EXPERTS ON THE FILE TIER have no address of their own: a routed layer's are read into
-     * one of two VRAM buffers before the layer's first expert op and published there until the next
-     * routed layer starts (place/stager.h, FileStager). `file_layer_max` is the most one layer's
-     * file-tier units take in a buffer, each at its own size rounded to RAD_ALIGN_UNIT, which is
-     * how the stager packs them; `file_stage_vram` is the two buffers, taken out of
-     * the weights pool before any expert is made resident. Both 0 when nothing routed is on the
+    /* Routed experts on the file tier have no address of their own: a routed layer's are read into
+     * one of two VRAM buffers before its first expert op and stay published until the next routed
+     * layer starts (place/stager.h, FileStager). `file_layer_max` is the largest layer's share,
+     * each unit rounded to RAD_ALIGN_UNIT as the stager packs them; `file_stage_vram` is both
+     * buffers, taken from the weights pool before residents. Both 0 when no routed unit is on the
      * file tier. */
     int64_t file_layer_max = 0;
     int64_t file_stage_vram = 0;
-    /* VRAM the slab holds that no weight occupies: the shadow slots and the staging ring. It is
-     * reported rather than folded into the tier total because it is the price of dynamic
-     * placement and of offload respectively, and an operator comparing two runs needs to see
-     * which of the two changed. */
+    /* Slab VRAM no weight occupies: shadow slots (the cost of dynamic placement) and the staging
+     * ring (the cost of offload). Reported separately from the tier totals. */
     int64_t slab_overhead = 0;
 
-    /* What did not fit. Two lists because there are two kinds of failure and they read
-     * differently: `notes` is a whole-plan statement ("the budget is 3 GiB short"), and `unfit`
-     * is per unit -- aggregated by class and reason, because a plan that strands nine hundred
-     * experts must print one line about it and not nine hundred (spec §16). */
+    /* What did not fit. `notes` holds whole-plan statements ("the budget is 3 GiB short");
+     * `unfit` holds per-unit misfits aggregated by class and reason, so hundreds of stranded
+     * experts print as one line (spec §16). */
     std::vector notes;
     struct Unfit {
         std::string what;    /* the weight class key */
@@ -318,14 +258,8 @@ public:
     std::vector unfit;
     bool fits() const { return notes.empty() && unfit.empty(); }
 
-    const MoveUnit* unit_for(rad_weight w) const {
-        if (w >= unit_of_weight.size() || unit_of_weight[w] < 0) return nullptr;
-        return &units[(size_t)unit_of_weight[w]];
-    }
-
-    /* THE PLACEMENT PLAN REPORT (spec §16): every weight's tier and site, the pool totals, and
-     * what did not fit. One line per weight CLASS rather than per weight, because a model with
-     * eleven thousand experts has eleven thousand weights and three interesting lines. */
+    /* The placement plan report (spec §16): tier and site per weight class (not per weight), the
+     * pool totals, and what did not fit. */
     std::string report(const Program& p) const;
 };
 
@@ -336,27 +270,23 @@ struct PlannerInput {
     int rank = 0;
     int world_size = 1;
 
-    /* The container's expert-popularity profile, derived from the imatrix's activation counts.
-     * Null is fine and costs about a point of hit rate. See Planner::rank_units. */
+    /* The container's expert-popularity profile, from the imatrix's activation counts. Null is
+     * fine and costs about a point of hit rate. See Planner::rank_units. */
     const RadFileProfile* profile = nullptr;
     int64_t               n_profile = 0;
     /* The weights are in a container, which the file and mapped tiers read in place. A checkpoint
      * served directly is neither grouped by movement unit nor aligned for O_DIRECT, so with this
-     * false no unit is file-direct and both tiers are closed (spec §4.3). */
+     * false both tiers are closed (spec §4.3). */
     bool                  container = true;
-    /* No card is visible and the device backend is the host's own memory (device_is_host()), so a
-     * host kernel can read the weights pool as well as the container's mapping. See
-     * mapped_unit(). */
+    /* No card is visible and the device backend is host memory (device_is_host()), so a host
+     * kernel can read the weights pool as well as the mapping. See mapped_unit(). */
     bool                  host_backend = false;
 };
 
-/* DOES A UNIT STAY IN THE CONTAINER'S MAPPING because only a host kernel can read it? On a card,
- * always: a host kernel cannot read VRAM, and the mapping is the one host address its bytes
- * already have. On the host backend the weights pool is host memory too, and a unit whose stored
- * form is not the container's (a widening or a relayout its host kernel asked for at load, or a
- * checkpoint served directly) has no place in the mapping that looks the way its kernel reads it,
- * so there it takes a converted copy in the weights pool like any other weight. One rule, for the
- * planner and the budget alike. */
+/* Whether a host-only unit stays in the container's mapping. On a card, always: a host kernel
+ * cannot read VRAM. On the host backend the weights pool is host memory, so a unit whose stored
+ * form differs from the container's (a load-time widening or relayout, or a checkpoint served
+ * directly) takes a converted copy in the pool instead. Shared by the planner and the budget. */
 inline bool mapped_unit(bool host_only, bool direct, bool host_backend) {
     return host_only && (direct || !host_backend);
 }
@@ -365,8 +295,8 @@ class Planner {
 public:
     explicit Planner(const PlannerInput& in) : in_(in) {}
 
-    /* Runs the whole plan. Returns RAD_OK, or a negative status with `out` still filled in far
-     * enough to print -- a plan that does not fit is a plan the operator has to read. */
+    /* Returns RAD_OK, or a negative status with `out` still filled in far enough to print the
+     * report. */
     int plan(Plan* out);
 
 private:
@@ -375,11 +305,11 @@ private:
     /* Per-weight facts derived from declare, indexed by rad_weight. */
     std::vector host_ok_;     /* every op reading it resolved a RAD_DOMAIN_HOST kernel */
     std::vector device_ok_;   /* ...and a RAD_DOMAIN_DEVICE one. Cleared means the weight
-                                        * can ONLY be read on the host, which is a decision and
-                                        * not a preference -- see pin_mapped. */
+                                        * can only be read on the host; see pin_mapped. */
     bool                 ssd_ = false; /* --weights-disk-tier was given */
 
-    void resolve_sites(const Program& prog);
+    /* Whether every weight of the unit has a host kernel. */
+    bool host_kernel(const MoveUnit& mu) const;
     void build_units(const Program& prog, Plan* p);
     void pin_mapped(const Program& prog, Plan* p);
     int  pin_embedding(const Program& prog, const Config& cfg, Plan* p) const;
@@ -393,55 +323,49 @@ private:
     void enforce_op_site_agreement(const Program& prog, Plan* p);
     void schedule_prefetch(Plan* p);
     void finish(const Program& prog, Plan* p);
-    /* Fold one stranded unit into the aggregated list. Found-or-appended by (class, reason), so
-     * the cost of reporting nine hundred stranded experts is one line and one counter. */
+    /* Folds one stranded unit into the list aggregated by (class, reason). */
     void note_unfit(Plan* p, const MoveUnit& mu, const char* why) const;
 };
 
-/* Bytes of a declared weight as THIS RANK will hold them: the stored size once the layout pass
- * has run, the logical size before it. Exposed because the mover and the report both need the
- * same answer and two spellings of it is how two components disagree about a budget. */
+/* Bytes of a declared weight as this rank holds them: the stored size once the layout pass has
+ * run, the logical size before it. Shared so the mover and the report agree on budgets. */
 int64_t weight_bytes(const WeightInfo& w);
 
 /* ------------------------------------------------------------------ what the weights would cost
  *
- * ONE RANK'S DECLARED WEIGHTS, SPLIT INTO THE PART THAT IS NOT NEGOTIABLE AND THE PART THAT IS.
+ * One rank's declared weights, split into the fixed part and the elastic part. The VRAM budget
+ * needs this before the planner runs. Static (non-expert) weights must be resident for the model
+ * to run at a sensible speed, so they come off the top; only the expert plane trades against the
+ * KV cache. A single combined total would let the cache demote attention projections to host.
  *
- * The VRAM budget needs this BEFORE the planner runs, because the two questions are asked in that
- * order: how much room is there, and only then what goes in it. And the split matters more than
- * the total. A model's static weights -- everything that is not an expert -- have to be resident
- * for the model to run at a sensible speed at all, so they come off the top; the expert plane is
- * the only thing that trades against the KV cache. Dividing the two together would let the cache's
- * side demote the attention projections to host memory to make room for blocks nothing will fill.
+ * Values are per rank, which under tensor parallel is the shard: declare divides every dimension
+ * per rank (spec §9).
  *
- * The three answers are per RANK, and under tensor parallel that is already the even split across
- * devices: declare runs once per rank with every dimension ALREADY DIVIDED (spec §9), so summing
- * this rank's declared weights is summing its shard.
- *
- * IT MUST AGREE WITH THE PLANNER AND THAT IS WHY IT LIVES HERE. The unit grouping, the alignment
- * accumulation and the mapped-tier rule are Planner::build_units', Planner::resolve_sites' and
- * Planner::pin_mapped's respectively; a second copy of any of them somewhere else would drift and
- * the failure would be a budget that overcommits the card by exactly the difference. */
+ * It must agree with the planner, which is why it lives here: it shares the planner's site test
+ * and repeats the unit grouping and alignment of Planner::build_units and the mapped-tier rule of
+ * Planner::pin_mapped. Any drift overcommits the card by the difference. */
 struct WeightFootprint {
     int64_t statics = 0;   /* non-expert and device-readable -- the floor under any budget */
     int64_t experts = 0;   /* the elastic plane: what streams from host when it does not fit */
     int64_t expert_layer_max = 0;   /* the most expert bytes any one routed layer holds */
     int64_t expert_unit_max  = 0;   /* the largest expert unit's slot */
-    /* THE SLAB'S SPARE SLOTS beside the residents of an expert-tiered plan, at their most: per
-     * expert slab class, the shadow slots and the staging ring and the tail pad
-     * (Planner::assign_expert_tiered). They come out of the same weight budget as the residents. */
+    /* Upper bound on an expert-tiered plan's spare slab: per expert slab class, the shadow slots,
+     * staging ring and tail pad (Planner::assign_expert_tiered). Same weight budget as residents. */
     int64_t expert_spare     = 0;
     int64_t layer_unit_max   = 0;   /* the widest per-layer unit's slot: the file tier's staging */
     bool    routed           = false;   /* a layer has experts: the file tier's read windows */
     int64_t mapped  = 0;   /* no device kernel can read them; they never enter a pool at all */
     int64_t hosted  = 0;   /* --embedding-placement ram: in the pinned host pool, off the card */
-    /* The tables the placement flags move, wherever the buckets above count them: `embedding`
-     * is inside statics or hosted, `ngram` inside statics when a device kernel reads it and it is
-     * placed in VRAM, inside mapped otherwise. `tower` is the encoder towers' units, every weight
-     * of which the architecture declared read once per request, inside statics. */
+    /* The tables the placement flags move, already counted in a bucket above: `embedding` in
+     * statics or hosted; `ngram` in statics when a device kernel reads it and it is placed in
+     * VRAM, else in mapped; `tower` (units the architecture declared read once per request) in
+     * statics. */
     int64_t embedding = 0;
     int64_t ngram     = 0;
     int64_t tower     = 0;
+    /* The part of `tower` that is also `embedding`: a tower's model-level table read once a
+     * request and only by embed_lookup (Gemma 4's patch-position tables). See tower_pin_bytes. */
+    int64_t tower_lookup = 0;
     /* A device kernel reads the n-gram table, so it can be on the card or read over the link from
      * pinned host memory; without one only the host gather reads it, from RAM or the container. */
     bool    ngram_device = false;
@@ -449,40 +373,43 @@ struct WeightFootprint {
     bool    ngram_host = false;
     int64_t n_units = 0;
 };
-/* `embedding` is what the token embedding's placement resolved to; only Ram moves it out of the
- * statics. `ngram` is the n-gram table's; only Vram puts it among them, and only where a device
- * kernel reads it. `host_backend` and `container` are PlannerInput's: whether a host kernel can
- * read the weights pool, and whether the weights lie in a container at all (a checkpoint served
- * directly has no mapping a unit could stay in). Stated by every caller, so the budget and the
- * planner cannot count it differently. */
+/* `embedding` is the token embedding's resolved placement; only Ram moves it out of the statics.
+ * `ngram` is the n-gram table's; only Vram puts it in the statics, and only where a device kernel
+ * reads it. `host_backend` and `container` mean what they do in PlannerInput; every caller passes
+ * them so the budget and the planner count alike. */
 void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement embedding,
                       TablePlacement ngram, bool host_backend, bool container);
 
-/* THE PINNED STAGING THE FILE TIER TAKES OUT OF --host-pool-mib before any unit is placed in it:
- * RAD_PLACE_FILE_STAGE_SLOTS of the widest per-layer unit, and the read windows when a routed
- * layer can stream from the container. Planner::plan spends it; the budget counts it the same. */
+/* The bytes --vision-tower-placement ram moves off one rank's card. With the embedding in RAM,
+ * pin_embedding pins the towers' lookup tables first and pin_towers skips them, so they count
+ * once, with the embedding; a split that takes both `embedding` and `tower` out of the statics
+ * comes up short by those tables. */
+inline int64_t tower_pin_bytes(const WeightFootprint& wf, TablePlacement embedding) {
+    return embedding == TablePlacement::Ram ? wf.tower - wf.tower_lookup : wf.tower;
+}
+
+/* Pinned staging the file tier takes out of --host-pool-mib before any unit is placed:
+ * RAD_PLACE_FILE_STAGE_SLOTS of the widest per-layer unit, plus the read windows when a routed
+ * layer can stream from the container. Shared by Planner::plan and the budget. */
 int64_t file_stage_reserve(int64_t widest, bool routed);
 
-/* THE EXPERT BYTES THE CARD MUST HOLD when `host_room` bytes of the pinned host pool are free for
- * experts: everything the pool cannot take, the slab's spare slots beside them, and one unit of
- * first-fit slack on each side -- the resident fill and the pool fill each skip a unit that does
- * not fit and can leave up to one unit's room unspent. At most every expert and the spare slots.
- * A weight budget of the statics and this much places every expert in VRAM or the host pool. */
+/* Expert bytes the card must hold when `host_room` bytes of the pinned pool are free for experts:
+ * what the pool cannot take, the spare slab slots, and one unit of first-fit slack on each side
+ * (the resident fill and the pool fill can each leave up to one unit's room unspent). Capped at
+ * all experts plus spares. A weight budget of statics plus this places every expert in VRAM or
+ * the host pool. */
 int64_t expert_vram_floor(const WeightFootprint& wf, int64_t host_room);
 
-/* THE PLAN AND ITS RANK'S WEIGHTS POOL READ ONE SPLIT. The planner places against
- * Plan::vram_budget and the mover fills the pool Pools::configure allocated, each from the Config
- * it was handed; a rank given two different Configs plans a slab the pool does not have, or leaves
- * part of the pool unplanned and empty, and nothing downstream would say so. RAD_E_STATE, naming
- * the rank and both sizes, when they differ. */
+/* Checks that the plan and this rank's weights pool used the same split: Plan::vram_budget must
+ * equal the pool Pools::configure allocated, or the slab and the pool disagree silently. Returns
+ * RAD_E_STATE, logging the rank and both sizes, when they differ. */
 int plan_check_weights_pool(const Plan& p, int64_t pool_bytes);
 
-/* THE TABLES THE PLACEMENT FLAGS MOVE, by what reads them and not by name: a model-level weight
- * that at least one op reads and that only `embed_lookup` reads is a token embedding table, and
- * one only `embed_lookup_q` reads is an n-gram table. A lookup reads M rows a step, which is what
- * makes a tier below the card usable for it at all; a weight a GEMM also reads -- an output head
- * tied to the embedding -- would stream whole over the link every step, and is neither. One
- * definition, because the budget resolver and the planner must pick the same weights. */
+/* The tables the placement flags move, identified by their readers rather than by name: a
+ * model-level weight read by at least one op, and only by `embed_lookup`, is a token embedding;
+ * only by `embed_lookup_q`, an n-gram table. A lookup reads M rows a step, so a tier below the
+ * card is usable; a weight a GEMM also reads (an output head tied to the embedding) would stream
+ * whole every step and is neither. Shared by the budget resolver and the planner. */
 bool read_only_by(const Program& prog, rad_weight w, const char* op);
 inline bool is_embedding_table(const Program& prog, rad_weight w) {
     return read_only_by(prog, w, "embed_lookup");
@@ -491,8 +418,8 @@ inline bool is_ngram_table(const Program& prog, rad_weight w) {
     return read_only_by(prog, w, "embed_lookup_q");
 }
 
-/* "blk.12.ffn_gate_exps.3.weight" -> "blk.*.ffn_gate_exps.*.weight". The report's grouping key:
- * one line per weight class rather than per weight (spec §16). */
+/* "blk.12.ffn_gate_exps.3.weight" -> "blk.*.ffn_gate_exps.*.weight": the report's per-class
+ * grouping key (spec §16). */
 std::string weight_class_key(const std::string& name);
 
 }  /* namespace rad */
diff --git a/core/place/residency_iface.h b/core/place/residency_iface.h
index 998ea1e2..566d6d7c 100644
--- a/core/place/residency_iface.h
+++ b/core/place/residency_iface.h
@@ -1,14 +1,10 @@
-/* residency_iface.h -- THE SEAM between placement and the run phase.
+/* residency_iface.h -- forwards the seam between placement and the run phase.
  *
- * core/runtime/ owns the declaration and this file only forwards to it. Placement does not keep a
- * copy: two declarations of a struct that crosses a component boundary is an ODR violation waiting
- * for the first translation unit that includes both, and the symptom would be a WeightSlot whose
- * fields the two components disagree about.
- *
- * The contract itself is documented where it is declared. Read core/runtime/residency.h -- in
- * particular the rule that begin_transfer and publish are the ONLY writers and that BOTH must bump
- * the generation, because the run phase memoises the stream wait per generation and installing a
- * new event at the old generation makes it skip the wait entirely.
+ * core/runtime/residency.h owns the declarations; placement keeps no copy, since two definitions
+ * of a struct that crosses a component boundary are an ODR violation. The contract is documented
+ * there, notably: begin_transfer and publish are the only writers and both must bump the
+ * generation, because the run phase memoises the stream wait per generation and a new event at
+ * the old generation would skip the wait.
  */
 #pragma once
 #include "runtime/residency.h"
diff --git a/core/place/stager.cpp b/core/place/stager.cpp
index e9aa6af4..fb5e703a 100644
--- a/core/place/stager.cpp
+++ b/core/place/stager.cpp
@@ -5,6 +5,34 @@
 
 namespace rad {
 
+namespace {
+
+/* The units `take` accepts, grouped by layer, in first-op order. Sets `*clash` to the first layer
+ * whose span starts inside the one before it, or 0 when no spans interleave. */
+template 
+std::vector routed_layers(const Plan& plan, Take take, size_t* clash) {
+    std::map by_layer;
+    for (size_t u = 0; u < plan.units.size(); ++u) {
+        const MoveUnit& mu = plan.units[u];
+        if (mu.layer < 0 || mu.first_use_op < 0 || mu.last_use_op < 0 || !take(mu)) continue;
+        StagedLayer& L = by_layer[mu.layer];
+        L.layer = mu.layer;
+        L.units.push_back((int32_t)u);
+        L.first_op = L.first_op < 0 ? mu.first_use_op : std::min(L.first_op, mu.first_use_op);
+        L.last_op = std::max(L.last_op, mu.last_use_op);
+    }
+    std::vector out;
+    for (auto& kv : by_layer) out.push_back(std::move(kv.second));
+    std::sort(out.begin(), out.end(),
+              [](const StagedLayer& a, const StagedLayer& b) { return a.first_op < b.first_op; });
+    *clash = 0;
+    for (size_t i = 1; i < out.size() && *clash == 0; ++i)
+        if (out[i].first_op <= out[i - 1].last_op) *clash = i;
+    return out;
+}
+
+}  /* namespace */
+
 PrefillStager::~PrefillStager() {
     for (Place& p : place_) {
         if (p.done) rad_event_destroy(p.done);
@@ -12,45 +40,33 @@ PrefillStager::~PrefillStager() {
     }
     for (RadEvent& g : gate_)
         if (g) rad_event_destroy(g);
+    if (moved_t_) rad_event_destroy(moved_t_);
+    if (moved_c_) rad_event_destroy(moved_c_);
 }
 
 int PrefillStager::init(const Program& prog, const Plan& plan, Mover* mover, char* region,
-                        int64_t bytes, int64_t min_rows) {
+                        char* low, int64_t bytes, int64_t min_rows) {
     layers_.clear();
     if (!mover || !region || bytes <= 0) return RAD_OK;
 
-    /* A ROUTED LAYER IS ITS EXPERT UNITS, and the ops that read it are the span their declared
-     * uses cover: the first is the one that must find the copies, the last the one after which
-     * nothing reads them again -- once the block's last pass of rows has issued it (after_op).
-     * A declared draft head's layer, numbered past the trunk's, is not one (see the top of
-     * stager.h). */
+    /* A routed layer is its expert units; its op span is their declared uses. The first op must
+     * find the copies; after the last (once the block's last pass of rows issued it) nothing reads
+     * them. A draft head's layer, numbered past the trunk's, is excluded (see stager.h). */
     const int32_t trunk = prog.drafter.kind != RAD_DRAFT_NONE && prog.meta.n_layers > 0
                               ? (int32_t)prog.meta.n_layers : INT32_MAX;
-    std::map by_layer;
-    for (size_t u = 0; u < plan.units.size(); ++u) {
-        const MoveUnit& mu = plan.units[u];
-        if (mu.expert < 0 || mu.layer < 0 || mu.first_use_op < 0 || mu.last_use_op < 0) continue;
-        if (mu.layer >= trunk) continue;
-        Layer& L = by_layer[mu.layer];
-        L.layer = mu.layer;
-        L.units.push_back((int32_t)u);
-        L.first_op = L.first_op < 0 ? mu.first_use_op : std::min(L.first_op, mu.first_use_op);
-        L.last_op = std::max(L.last_op, mu.last_use_op);
-    }
-    for (auto& kv : by_layer) layers_.push_back(std::move(kv.second));
-    std::sort(layers_.begin(), layers_.end(),
-              [](const Layer& a, const Layer& b) { return a.first_op < b.first_op; });
+    size_t c = 0;
+    layers_ = routed_layers(
+        plan, [&](const MoveUnit& mu) { return mu.expert >= 0 && mu.layer < trunk; }, &c);
     /* Two layers' spans must not overlap: a layer's copies are given back at the next layer's
      * first op, which must be past every op that reads them. */
-    for (size_t i = 1; i < layers_.size(); ++i)
-        if (layers_[i].first_op <= layers_[i - 1].last_op) {
-            RAD_WARN("prefill staging: routed layers %d and %d are read by interleaved ops (%d..%d "
-                     "and %d..%d); staging is off", layers_[i - 1].layer, layers_[i].layer,
-                     layers_[i - 1].first_op, layers_[i - 1].last_op, layers_[i].first_op,
-                     layers_[i].last_op);
-            layers_.clear();
-            return RAD_OK;
-        }
+    if (c > 0) {
+        RAD_WARN("prefill staging: routed layers %d and %d are read by interleaved ops (%d..%d "
+                 "and %d..%d); staging is off", layers_[c - 1].layer, layers_[c].layer,
+                 layers_[c - 1].first_op, layers_[c - 1].last_op, layers_[c].first_op,
+                 layers_[c].last_op);
+        layers_.clear();
+        return RAD_OK;
+    }
     if (layers_.empty()) return RAD_OK;
 
     first_of_.assign(prog.ops.size(), -1);
@@ -62,6 +78,10 @@ int PrefillStager::init(const Program& prog, const Plan& plan, Mover* mover, cha
 
     mover_ = mover;
     region_ = region;
+    low_ = low ? low : region;
+    base_ = region;
+    want_ = nullptr;
+    rebase_ = false;
     ring_ = bytes / 2 / RAD_ALIGN_UNIT * RAD_ALIGN_UNIT * 2;
     head_ = 0;
     min_rows_ = min_rows;
@@ -83,22 +103,33 @@ int PrefillStager::init(const Program& prog, const Plan& plan, Mover* mover, cha
         }
         gate_li_[i] = -1;
     }
-    /* The backend opens what its first list needs -- the card's DMA queue -- here at bring-up, not
-     * inside the first long prompt's first step. */
+    /* The move's two waits, only where the ring has a second place to move to (rebase). */
+    if (low_ != region_ &&
+        ((!moved_t_ && rad_event_create_local(&moved_t_) < 0) ||
+         (!moved_c_ && rad_event_create_local(&moved_c_) < 0))) {
+        layers_.clear();
+        return RAD_E_DEVICE;
+    }
+    /* An empty list makes the backend open the card's DMA queue now, at bring-up, rather than in
+     * the first long prompt's first step. */
     return rad_memcpy_list_async(nullptr, 0, 0, mover_->transfer_stream());
 }
 
-/* A TRUNK PASS AT THE FULL PLAN AND LARGE ENOUGH, and only that (see the top of stager.h). The
- * next trunk pass's first layers, staged at the end of the last one, are this pass's if it arms
- * and go back to the pool if it does not. */
+/* Arms only for a trunk pass whose level has a ring and with at least min_rows tokens (see
+ * stager.h). Layers the previous pass staged early are kept if it arms with the ring where they
+ * are, and withdrawn if not. */
 bool PrefillStager::begin_pass(const RadBatch* b) {
     if (!b || b->draft_pass != 0) return false;
-    armed_ = full_ && enabled() && b->n_tok >= min_rows_;
+    armed_ = want_ != nullptr && enabled() && b->n_tok >= min_rows_;
     staged_ = armed_;
     if (!armed_) {
         withdraw_early();
         return false;
     }
+    if (want_ != base_) {
+        withdraw_early();
+        rebase_ = true;
+    }
     first_op_ = true;
     next_ = 0;
     first_li_ = -1;
@@ -106,8 +137,7 @@ bool PrefillStager::begin_pass(const RadBatch* b) {
     return true;
 }
 
-/* The early layers' copies back to the pool: nothing has read them, so there is no `free` to
- * record and the next copy over their places needs no wait for them. */
+/* Withdraw the early layers' copies. Nothing has read them, so there is no `free` to record. */
 void PrefillStager::withdraw_early() {
     for (int32_t i : ring_order_) {
         Place& p = place_[i];
@@ -116,17 +146,17 @@ void PrefillStager::withdraw_early() {
     n_early_ = 0;
 }
 
-/* The host half of giving a place back: its units are published at their pool slots again, which
- * the next residency sync hands to the weight tables. The device half is `free`, which the copy
- * that laps the place waits on. */
+/* The host half of giving a place back: its units are published at their pool slots again, for
+ * the next residency sync. The device half is `free`, which the copy that laps the place waits
+ * on. */
 void PrefillStager::retire(Place& p) {
     mover_->unstage_units(p.staged);
     p.staged.clear();
     p.retired = true;
 }
 
-/* The oldest place leaves the ring, and the mover's stream waits on its last reader: whatever is
- * copied there later goes out behind that wait. */
+/* The oldest place leaves the ring; the mover's stream waits on its last reader, so later copies
+ * into it are ordered behind that read. */
 int PrefillStager::recycle_front() {
     const int32_t i = ring_order_.front();
     Place& p = place_[i];
@@ -138,10 +168,27 @@ int PrefillStager::recycle_front() {
     return RAD_OK;
 }
 
-/* A PLACE OF `want` BYTES at the head of the ring, or -- `partial` -- all the room the head can
- * reach when `want` does not fit. The head may write over retired places only: the oldest place
- * still published bounds it a whole ring ahead of where that place starts. *out is -1 when
- * nothing fits. */
+/* Moves the ring (see stager.h) at the first op of a pass whose ring is not where the last armed
+ * pass left it. Nothing in it is published any more (begin_pass withdrew it), so it starts over,
+ * empty, at its new place. Either place is the other level's buffers, hence two waits: the compute
+ * stream does not reach the new step before the copies still going into the old place land, and
+ * the first copy into the new place waits for the compute work already queued, which used it. */
+int PrefillStager::rebase(RadStream s) {
+    rebase_ = false;
+    const RadStream t = mover_->transfer_stream();
+    RAD_TRY(rad_event_record(moved_t_, t));
+    RAD_TRY(rad_event_wait(s, moved_t_));
+    RAD_TRY(rad_event_record(moved_c_, s));
+    RAD_TRY(rad_event_wait(t, moved_c_));
+    while (!ring_order_.empty()) RAD_TRY(recycle_front());
+    head_ = 0;
+    base_ = want_;
+    return RAD_OK;
+}
+
+/* A place of `want` bytes at the head of the ring or, with `partial`, all the room the head can
+ * reach when `want` does not fit. The head may only overwrite retired places: it stays within one
+ * ring of the oldest place still published. *out is -1 when nothing fits. */
 int PrefillStager::take(int64_t want, bool partial, int32_t* out) {
     *out = -1;
     int64_t limit = head_ + ring_;
@@ -151,8 +198,8 @@ int PrefillStager::take(int64_t want, bool partial, int32_t* out) {
     if (len < want && !partial) return RAD_OK;
     if (len < RAD_ALIGN_UNIT) return RAD_OK;
     const int64_t end = head_ + len;
-    /* Every place the new one laps leaves the ring first; then, with the table full, the oldest
-     * retired ones -- their waits only order the mover's stream behind reads long finished. */
+    /* Every place the new one laps leaves the ring first; then, if the table is full, the oldest
+     * retired ones (their waits are on reads long finished). */
     while (!ring_order_.empty() && place_[ring_order_.front()].beg + ring_ < end)
         RAD_TRY(recycle_front());
     while (spare_.empty() && !ring_order_.empty() && place_[ring_order_.front()].retired)
@@ -167,11 +214,10 @@ int PrefillStager::take(int64_t want, bool partial, int32_t* out) {
     return RAD_OK;
 }
 
-/* ONE LAYER INTO THE RING, behind `gate` when it is not null. `now` is the layer the run reaches
- * next, which takes whatever room there is up to all it needs; any other goes only whole and at
- * most half the ring -- so the next layer never finds less room than two buffers of half the ring
- * gave it, and a heavy layer is not cut short for having been reached early. *got is kStaged, kNone
- * when nothing of the layer is pooled, or kLater when the ring has no room for it yet. */
+/* Stage one layer into the ring, behind `gate` when not null. The layer the run reaches next
+ * (`now`) takes whatever room there is up to its need; any other goes only whole and within half
+ * the ring, so the next layer always has at least half the ring. *got is kStaged, kNone when
+ * nothing of the layer is pooled, or kLater when the ring has no room yet. */
 int PrefillStager::stage_layer(int32_t li, bool now, RadEvent gate, int* got) {
     *got = kLater;
     const Layer& L = layers_[(size_t)li];
@@ -179,8 +225,8 @@ int PrefillStager::stage_layer(int32_t li, bool now, RadEvent gate, int* got) {
     const int64_t need = mover_->stage_need(L.units, &unit);
     if (need <= 0) { *got = kNone; return RAD_OK; }
     if (!now && need > ring_ / 2) return RAD_OK;
-    /* A place that runs past the region's end is two stretches, and the first can end in less
-     * room than a unit: it asks for one unit more than the layer needs. */
+    /* A place that wraps past the region's end is two stretches, and the first may end with less
+     * room than a unit, so it asks for one unit extra. */
     const int64_t want = head_ % ring_ + need > ring_ ? need + unit : need;
     int32_t i = -1;
     RAD_TRY(take(want, now, &i));
@@ -188,10 +234,10 @@ int PrefillStager::stage_layer(int32_t li, bool now, RadEvent gate, int* got) {
     Place& p = place_[i];
     p.li = li;
     if (gate) RAD_TRY(rad_event_wait(mover_->transfer_stream(), gate));
-    /* A place that runs past the region's end goes on at its start. */
+    /* A wrapping place continues at the region's start. */
     const int64_t off = p.beg % ring_, len = p.end - p.beg;
-    Mover::StageSpan sp[2] = { { region_ + off, std::min(len, ring_ - off) },
-                               { region_, len - std::min(len, ring_ - off) } };
+    Mover::StageSpan sp[2] = { { base_ + off, std::min(len, ring_ - off) },
+                               { base_, len - std::min(len, ring_ - off) } };
     RAD_TRY(mover_->stage_units(L.units, sp, sp[1].cap > 0 ? 2 : 1, nullptr, p.done, &p.staged));
     if (p.staged.empty()) {
         p.li = -1;
@@ -205,9 +251,9 @@ int PrefillStager::stage_layer(int32_t li, bool now, RadEvent gate, int* got) {
     return RAD_OK;
 }
 
-/* STAGE THE LAYERS AFTER `cur` as far as the pace lets them go and the ring has room. A layer
- * nothing of which is pooled is passed over; one the ring has no room for yet, or whose pace
- * layer the run has not reached, stops the walk until a later op. */
+/* Stage the layers after `cur` as far as the pace and the ring allow. A layer with nothing pooled
+ * is skipped; one without room yet, or whose pace layer the run has not reached, stops the walk
+ * until a later op. */
 int PrefillStager::stage_ahead(int32_t cur, bool* resync) {
     while ((size_t)next_ < layers_.size()) {
         const int32_t g = next_ - kLead;
@@ -228,11 +274,11 @@ int PrefillStager::stage_ahead(int32_t cur, bool* resync) {
 int PrefillStager::before_op(rad_op h, RadStream s, bool* resync) {
     *resync = false;
 
-    /* THE PASS'S FIRST ROUTED LAYER, staged at its first op of any kind, so the copies run behind
-     * whatever the pass issues before the layer -- and the layers after it as far as the pace and
-     * the ring allow. The layers the pass before staged for it are its own from here. */
+    /* At the pass's first op of any kind, stage its first routed layer and the ones after it as
+     * far as the pace and ring allow. Layers the previous pass staged early are adopted here. */
     if (first_op_) {
         first_op_ = false;
+        if (rebase_) RAD_TRY(rebase(s));
         const auto it = std::lower_bound(layers_.begin(), layers_.end(), (int32_t)h,
                                          [](const Layer& L, int32_t op) { return L.first_op < op; });
         if (it != layers_.end()) {
@@ -251,23 +297,22 @@ int PrefillStager::before_op(rad_op h, RadStream s, bool* resync) {
     if ((size_t)h >= first_of_.size()) return RAD_OK;
     const int32_t li = first_of_[(size_t)h];
     if (li < 0) return RAD_OK;
-    /* The run's arrival at this layer, which the copies kLead layers on are paced by. */
+    /* The run's arrival at this layer paces the copies kLead layers on. */
     RAD_TRY(rad_event_record(gate_[li % kGates], s));
     gate_li_[li % kGates] = li;
-    /* This layer's copies were published when they went out: the one wait that orders its ops
-     * behind them. */
+    /* This layer's copies were published when issued; this one wait orders its ops behind them. */
     for (int32_t i : ring_order_) {
         Place& p = place_[i];
         if (!p.retired && p.li == li) RAD_TRY(rad_event_wait(s, p.done));
     }
-    /* The layers before are done with their places: every pass of rows issued their last op, the
-     * last of them recorded `free`, and a layer's ops do not interleave with the next one's. Given
-     * back here and not at that op, whose next run would read copies already overwritten. */
+    /* Earlier layers are done: every pass of rows issued their last op and recorded `free`, and
+     * layers do not interleave. They are retired here, not at their last op, which may repeat for
+     * another pass of rows. */
     for (int32_t i : ring_order_) {
         Place& p = place_[i];
         if (!p.retired && p.li < li && p.read) retire(p);
     }
-    /* And the copies go on ahead of it into the room that gave back. */
+    /* Stage further ahead into the freed room. */
     if (next_ <= li) next_ = li + 1;
     const bool was = *resync;
     RAD_TRY(stage_ahead(li, resync));
@@ -275,9 +320,9 @@ int PrefillStager::before_op(rad_op h, RadStream s, bool* resync) {
     return RAD_OK;
 }
 
-/* THE LAYER'S LAST OP: `free` goes behind it, so a copy that laps its place can start as early as
- * it could -- and goes behind it again if the block issues the op for another pass of rows, which
- * is why the copies themselves are not given back until the next layer starts. */
+/* A layer's last op: record `free` behind it so a lapping copy can start as early as possible.
+ * The op may repeat for another pass of rows, moving `free` again, which is why the copies are
+ * retired only when the next layer starts. */
 int PrefillStager::after_op(rad_op h, RadStream s) {
     if ((size_t)h >= last_of_.size()) return RAD_OK;
     const int32_t li = last_of_[(size_t)h];
@@ -292,9 +337,9 @@ int PrefillStager::after_op(rad_op h, RadStream s) {
     return RAD_OK;
 }
 
-/* Nothing this pass staged outlives it. Then, when the next step goes on with a prompt, its trunk
- * pass's first layers go into the ring behind this pass's last ones -- layer k paced on this
- * pass's layer n - kLead + k, as the run would pace it if the two passes were one. */
+/* Retire everything this pass staged. Then, when the next step continues a prompt, stage its
+ * trunk pass's first layers, layer k paced on this pass's layer n - kLead + k, as if the two
+ * passes were one. */
 int PrefillStager::end_pass(RadStream s) {
     if (!armed_) return RAD_OK;
     armed_ = false;
@@ -332,33 +377,22 @@ int FileStager::init(const Program& prog, const Plan& plan, Mover* mover) {
     layers_.clear();
     if (!mover) return RAD_OK;
 
-    std::map by_layer;
-    for (size_t u = 0; u < plan.units.size(); ++u) {
-        const MoveUnit& mu = plan.units[u];
-        if (mu.tier != Tier::SSD || mu.access != RAD_ACCESS_CONDITIONAL || mu.layer < 0) continue;
-        if (mu.first_use_op < 0 || mu.last_use_op < 0) continue;   /* declared and never read */
-        Layer& L = by_layer[mu.layer];
-        L.layer = mu.layer;
-        L.units.push_back((int32_t)u);
-        L.first_op = L.first_op < 0 ? mu.first_use_op : std::min(L.first_op, mu.first_use_op);
-        L.last_op = std::max(L.last_op, mu.last_use_op);
-    }
-    for (auto& kv : by_layer) layers_.push_back(std::move(kv.second));
+    /* A unit declared and never read has no op span and is left out. */
+    size_t c = 0;
+    layers_ = routed_layers(plan, [](const MoveUnit& mu) {
+        return mu.tier == Tier::SSD && mu.access == RAD_ACCESS_CONDITIONAL;
+    }, &c);
     if (layers_.empty()) return RAD_OK;
-    std::sort(layers_.begin(), layers_.end(),
-              [](const Layer& a, const Layer& b) { return a.first_op < b.first_op; });
-    /* A layer's copies stay published until the next one starts, so two layers whose ops
-     * interleave would need both buffers at once and a third for the read ahead. That is a plugin
-     * shape this tier cannot serve, and a file-tier unit has no address to fall back on. */
-    for (size_t i = 1; i < layers_.size(); ++i)
-        if (layers_[i].first_op <= layers_[i - 1].last_op) {
-            RAD_ERR("file stager: routed layers %d and %d are read by interleaved ops (%d..%d and "
-                    "%d..%d), and a routed layer read from the container is published one layer "
-                    "at a time", layers_[i - 1].layer, layers_[i].layer, layers_[i - 1].first_op,
-                    layers_[i - 1].last_op, layers_[i].first_op, layers_[i].last_op);
-            layers_.clear();
-            return RAD_E_UNSUPPORTED;
-        }
+    /* A layer's copies stay published until the next one starts, so interleaved layers would need
+     * a third buffer for the read-ahead; with no fallback address, such a plan is refused. */
+    if (c > 0) {
+        RAD_ERR("file stager: routed layers %d and %d are read by interleaved ops (%d..%d and "
+                "%d..%d), and a routed layer read from the container is published one layer at a "
+                "time", layers_[c - 1].layer, layers_[c].layer, layers_[c - 1].first_op,
+                layers_[c - 1].last_op, layers_[c].first_op, layers_[c].last_op);
+        layers_.clear();
+        return RAD_E_UNSUPPORTED;
+    }
 
     buf_[0] = mover->file_buffer(0);
     buf_[1] = mover->file_buffer(1);
@@ -382,8 +416,8 @@ int FileStager::init(const Program& prog, const Plan& plan, Mover* mover) {
     return RAD_OK;
 }
 
-/* EVERY PASS: there is no other address for a file-tier unit, so a pass the stager sat out would
- * reach its first routed layer with null expert pointers. */
+/* Arms for every pass: a file-tier unit has no other address, so an unarmed pass would reach its
+ * first routed layer with null expert pointers. */
 bool FileStager::begin_pass(const RadBatch* b) {
     armed_ = enabled() && b;
     if (!armed_) return false;
@@ -424,7 +458,7 @@ int FileStager::before_op(rad_op h, RadStream s, bool* resync) {
     *resync = false;
     if ((int32_t)h > last_issued_) last_issued_ = (int32_t)h;
 
-    /* THE PASS'S FIRST ROUTED LAYER, read at its first op of any kind. */
+    /* Read the pass's first routed layer at its first op of any kind. */
     if (first_op_) {
         first_op_ = false;
         const auto it = std::lower_bound(layers_.begin(), layers_.end(), (int32_t)h,
@@ -445,7 +479,7 @@ int FileStager::before_op(rad_op h, RadStream s, bool* resync) {
     /* Entering layer `li`: the layer before is behind every op issued so far on this stream. */
     for (int b = 0; b < 2; ++b)
         if (holds_[b] >= 0 && holds_[b] != li) { RAD_TRY(finish(b, s)); *resync = true; }
-    /* A layer the read-ahead skipped -- the learned bound said this pass ends before it -- is read
+    /* A layer the read-ahead skipped (the learned bound said the pass ends before it) is read
      * here rather than issued without addresses. */
     if (holds_[li & 1] != li) {
         RAD_TRY(start(li));
@@ -462,12 +496,6 @@ int FileStager::before_op(rad_op h, RadStream s, bool* resync) {
     return RAD_OK;
 }
 
-int FileStager::after_op(rad_op h, RadStream s) {
-    (void)h;
-    (void)s;
-    return RAD_OK;
-}
-
 int FileStager::end_pass(RadStream s) {
     if (!armed_) return RAD_OK;
     armed_ = false;
diff --git a/core/place/stager.h b/core/place/stager.h
index e4433ec3..8ad5fa1d 100644
--- a/core/place/stager.h
+++ b/core/place/stager.h
@@ -1,90 +1,85 @@
 /* stager.h -- the prefill stager: routed layers' non-resident experts copied onto the card ahead
  * of the layers that read them.
  *
- * ---- WHY A PREFILL NEEDS IT -------------------------------------------------------------------
+ * ---- why prefill needs it ---------------------------------------------------------------------
  *
  * An expert the slab has no room for lives in the pinned host pool, and a GEMM that routes to it
- * reads it across the link in place (Site::DeviceZeroCopy). At decode that is the right trade: a
- * step routes a few dozen rows to a few dozen experts and reads a few of them from the host. A
- * prefill chunk routes tens of thousands of rows to nearly EVERY expert of every layer, so the
- * whole pooled part of each layer -- ~85 MB a card on Qwen3.8-Flash-Next -- crosses the link inside
- * the layer's two GEMMs, at the link's rate and on the critical path, while the rest of the layer's
- * work leaves the link idle. Measured with r4d_selftest --perfmoe, the gate_up GEMM of a 2048-token
- * chunk is 1.53 ms with every expert on the card and 4.34 ms with the coldest 13% in host memory.
+ * reads it across the link in place (Site::DeviceZeroCopy). That suits decode, which reads a few
+ * experts per step from the host. A prefill chunk routes to nearly every expert of every layer, so
+ * each layer's whole pooled part (~85 MB per card on Qwen3.8-Flash-Next) crosses the link inside
+ * its two GEMMs, on the critical path, while the rest of the layer leaves the link idle. With
+ * r4d_selftest --perfmoe, a 2048-token gate_up GEMM takes 1.53 ms with every expert on the card
+ * and 4.34 ms with the coldest 13% in host memory.
  *
- * So at a step large enough, the stager copies the pooled experts of the layers ahead into a VRAM
- * ring while the layers before them run, publishes the copies for each layer's ops, and publishes
- * the host addresses again once those ops are behind it. The copy is the same bytes the GEMM would have read, so the output
- * is bit-identical; only when the link carries them moves.
+ * So for large enough steps the stager copies the pooled experts of the layers ahead into a VRAM
+ * ring while earlier layers run, publishes the copies for each layer's ops, and publishes the host
+ * addresses again once those ops are issued. The bytes are the same, so output is bit-identical.
  *
- * ---- WHERE THE RING IS, AND WHEN IT IS ITS ---------------------------------------------------
+ * ---- the region --------------------------------------------------------------------------------
  *
- * One region, the size of two layers' share of the experts the budget leaves off the card, at the
- * top of the activation arena (Program::arena_stage_off, sized by vram_budget_resolve). A step
- * smaller than the arena's full plan LENDS that top to the expert slab, so the region is the
- * stager's only in a step at the full plan -- which is exactly the steps worth staging for -- and
- * the rest of the time it holds resident experts like any other lent slot. The scheduler says
- * which it is, pass by pass (set_full_arena).
+ * One region, two layers' share of the experts the budget leaves off the card, at the top of the
+ * activation arena (Program::arena_stage_off, sized by vram_budget_resolve). A step smaller than
+ * the arena's full plan lends that top to the expert slab, so the region belongs to the stager
+ * only in full-plan steps (the ones worth staging for). The scheduler says which, per pass
+ * (set_ring).
  *
- * ---- WHY A RING AND NOT TWO BUFFERS ------------------------------------------------------------
+ * Under --prefill-span the ring has a second place. The full plan is sized for a spanned step,
+ * and a step of one interval (a chunk that shares its step, a short prompt) runs at the level of
+ * that size (Engine::probe_arena_levels). That level keeps the ring right above its own buffers,
+ * so everything over it, the span's extra rows included, is lent to the slab while such steps
+ * run, and the step is still staged. A pass whose ring is in the other place than the last one's
+ * moves it first (rebase).
  *
- * Layers do not leave equal parts off the card: at depth, with the KV cache's loan taken back, the
- * last third of a Qwen3.8-Flash-Next stack pools about twice the median layer. With two buffers of
- * one share each, layer L+1's copy waits for layer L-1's last op, so the engine idled once a light
- * layer's copy was done -- 60 to 80 ms of a ~280 ms step -- and a heavy layer's copy, longer than
- * the layer before it, made every layer after it wait. The ring packs each layer at its own size,
- * so the copies run as far ahead as the light layers leave room for and the heavy ones start
- * early. A layer staged further ahead than the next one takes at most half the ring, so the next
- * layer always has the room two buffers gave it; the next one takes whatever is free.
+ * ---- why a ring, not two buffers ---------------------------------------------------------------
  *
- * ---- THE ORDER, AND WHAT KEEPS IT SAFE ---------------------------------------------------------
+ * Layers leave unequal parts off the card: at depth, with the KV cache's loan taken back, the last
+ * third of a Qwen3.8-Flash-Next stack pools about twice the median layer. With two fixed buffers,
+ * a light layer's copy finishes early and the engine idles, and a heavy layer's copy delays every
+ * layer after it. The ring packs each layer at its own size, so copies run ahead through light
+ * layers and heavy ones start early. A layer staged beyond the next one takes at most half the
+ * ring, so the next layer always has the room two buffers would give it.
+ *
+ * ---- order and safety --------------------------------------------------------------------------
  *
  *   the pass's first op     stage the first routed layer the pass issues, and the ones after it
  *                           as far as the pace and the ring allow
- *   a layer's first op      wait on its copies; publish the host addresses of the layers before
- *                           it again; stage further layers into the room that gave back
+ *   a layer's first op      wait on its copies; publish the host addresses of earlier layers
+ *                           again; stage further layers into the freed room
  *   a layer's last op       record "free" behind it on the op's stream
- *   the pass's end          the same for anything still staged -- and, when the next step goes on
- *                           with a prompt, stage the first layers of its trunk pass
+ *   the pass's end          the same for anything still staged; and, when the next step continues
+ *                           a prompt, stage the first layers of its trunk pass
  *
- * A layer's place in the ring is counted in bytes the ring has handed out since bring-up, so a
- * place laps the region and a copy finds the places it overwrites from the count alone. Before a
- * copy goes out, the mover's stream waits on the "free" event of every earlier place it laps --
- * recorded behind the last op that read it, in this pass or an earlier one. The layer's ops wait on
- * the copies' event through ONE stream wait, issued before the layer's first op: the copies are
- * published settled (Mover::stage_units says why), and nothing but the layer's own ops ever
- * resolves them.
+ * A layer's place in the ring is counted in bytes handed out since bring-up, so a copy finds the
+ * places it overwrites from the count alone. Before a copy is issued, the mover's stream waits on
+ * the "free" event of every earlier place it laps (recorded behind that place's last reader, in
+ * this pass or an earlier one). The layer's ops wait on the copies' event through one stream wait
+ * before its first op: copies are published settled (see Mover::stage_units), and only the
+ * layer's own ops resolve them.
  *
- * ---- HOW FAR AHEAD ----------------------------------------------------------------------------
+ * ---- how far ahead -----------------------------------------------------------------------------
  *
- * A layer's copies go out once the compute stream has reached the MoE of the layer kLead before it,
- * through an event recorded at that layer's first op. Not as soon as the ring has room: copies that
- * land long before their layer is read cost the layers they overlap more than they save. Measured at
- * TP2 on Qwen3.8-Flash-Next, released as soon as there was room, every class of op ran slower and a
- * 26K-token prompt lost 0.6%; held to one layer ahead, the heavy late layers of a 160K-token prompt
- * waited again and it lost 2.4%. Three layers ahead covered the late layers at the smallest cost
- * to the short prompt.
+ * A layer's copies are released once the compute stream reaches the MoE of the layer kLead before
+ * it (an event recorded at that layer's first op), not as soon as the ring has room: copies that
+ * land long before use slow the layers they overlap. On Qwen3.8-Flash-Next TP2, unpaced copies
+ * cost a 26K-token prompt 0.6% and one layer ahead cost a 160K-token prompt 2.4% (its heavy late
+ * layers waited); three ahead covered the late layers at the least cost to short prompts.
  *
- * ---- THE NEXT STEP'S FIRST LAYERS -------------------------------------------------------------
+ * ---- the next step's first layers --------------------------------------------------------------
  *
- * A step that carries a chunk of a prompt is issued only once the step before it has been read
- * back, so the copies of its first layers would start with it and its first layer would wait for
- * all of them. When the engine says the next step goes on with a prompt (set_next_prefill), the
- * pass's end stages the first layers of the next trunk pass instead, paced on this pass's last
- * layers as if the two passes were one. They are published at once. The next trunk pass adopts them
- * when it is armed; a trunk pass that is not publishes their host addresses again in begin_pass,
- * which the run phase calls before it brings the weight tables up to date. A draft pass in between
- * reads none of the trunk's layers and leaves them be. With both, against two buffers at TP2: 160K
- * 1.0-1.4% faster, 26K unchanged; at TP1, where the link carries every pooled expert each step,
- * 26K 0.6% faster.
+ * A step carrying a prompt chunk is issued only after the previous step is read back, so its first
+ * layer would otherwise wait for all its own copies. When the next step continues a prompt
+ * (set_next_prefill), this pass's end stages the next trunk pass's first layers, paced on this
+ * pass's last layers as if the passes were one, and publishes them at once. The next trunk pass
+ * adopts them when armed; an unarmed trunk pass publishes their host addresses again in
+ * begin_pass, which the run phase calls before updating the weight tables. A draft pass in
+ * between reads none of the trunk's layers and leaves them.
  *
- * ---- ONLY THE TRUNK ---------------------------------------------------------------------------
+ * ---- trunk only --------------------------------------------------------------------------------
  *
- * A draft head's routed layer is not the stager's. The head runs in passes of its own -- over a
- * prefill chunk, the history pass, which needs the head's experts on a prompt's last chunk alone
- * and there only for the rows that draft, a handful however long the chunk -- so its pooled
- * experts are read in place like a decode step's. The head's layer is numbered past the
- * trunk's layers (RadModelMeta::n_layers), left out at bring-up, and a draft pass is never armed.
+ * A draft head's routed layer is not staged. The head runs in its own passes; over a prefill chunk
+ * (the history pass) it needs its experts only on a prompt's last chunk, for the few rows that
+ * draft, so its pooled experts are read in place as at decode. The head's layer is numbered past
+ * the trunk's (RadModelMeta::n_layers) and left out at bring-up; a draft pass is never armed.
  */
 #pragma once
 #include "../runtime/stager.h"
@@ -97,32 +92,44 @@
 
 namespace rad {
 
+/* One routed layer a stager serves: its units and the span of ops that read them. */
+struct StagedLayer {
+    int32_t              layer = -1;
+    std::vector units;
+    int32_t              first_op = -1, last_op = -1;
+};
+
 class PrefillStager final : public OpStager {
 public:
     ~PrefillStager() override;
 
-    /* The routed layers of `plan` and the ops that read them, and `bytes` of device memory at
-     * `region` as the ring. `min_rows` is the smallest pass it arms for. Leaves it disabled --
-     * enabled() false -- when the plan has no routed layer with a pooled unit to stage. */
-    int init(const Program& prog, const Plan& plan, Mover* mover, char* region, int64_t bytes,
-             int64_t min_rows);
+    /* Binds the routed layers of `plan` and the ops that read them, with `bytes` of device memory
+     * at `region` as the ring -- or at `low`, the ring's place under the span's shared level, when
+     * there is one (null otherwise). `min_rows` is the smallest pass it arms for. Leaves enabled()
+     * false when no routed layer has a pooled unit to stage. */
+    int init(const Program& prog, const Plan& plan, Mover* mover, char* region, char* low,
+             int64_t bytes, int64_t min_rows);
 
-    /* Per pass, before it is released: whether the step runs at the arena's full plan, which is
-     * when the region is not lent. */
-    void set_full_arena(bool full) { full_ = full; }
-    /* Per step, before it is released: whether the step after it goes on with a prompt in a pass
-     * this stager arms for, so this step's trunk pass stages that pass's first layers. */
+    /* Per pass, before release: where the ring is for the step -- the region at the full plan,
+     * `low` at the span's shared level -- or null when the step's level lends both. */
+    void set_ring(char* base) { want_ = base; }
+    /* The ring's two places: at the full plan, and at the span's shared level (the same one when
+     * there is no such level). */
+    char*   ring_full() const { return region_; }
+    char*   ring_low() const { return low_; }
+    /* Per step, before release: whether the next step continues a prompt in a pass this stager
+     * arms for, so this step's trunk pass stages that pass's first layers. */
     void set_next_prefill(bool more) { next_prefill_ = more; }
 
     bool    enabled() const { return !layers_.empty(); }
     int64_t ring_bytes() const { return ring_; }
-    /* The smallest pass (in tokens) the stager arms for: a step under it reads every pooled
-     * expert of a routed layer synchronously. The scheduler keeps a held-back prefill chunk at
-     * or above it (Scheduler::set_stage_rows). */
+    /* The smallest pass, in tokens, the stager arms for; smaller steps read pooled experts in
+     * place. The scheduler keeps a held-back prefill chunk at or above it
+     * (Scheduler::set_stage_rows). */
     int64_t min_rows() const { return min_rows_; }
     size_t  n_layers() const { return layers_.size(); }
-    /* Whether the last trunk pass armed: its routed layers' pooled experts were copied onto the
-     * card through the ring. A draft pass leaves it as the trunk pass set it. */
+    /* Whether the last trunk pass armed (copied its pooled experts through the ring). A draft
+     * pass leaves it unchanged. */
     bool    staged() const { return staged_; }
     static constexpr int32_t lead() { return kLead; }
 
@@ -132,17 +139,13 @@ public:
     int  end_pass(RadStream s) override;
 
 private:
-    struct Layer {
-        int32_t              layer = -1;
-        std::vector units;
-        int32_t              first_op = -1, last_op = -1;
-    };
+    using Layer = StagedLayer;
     std::vector   layers_;      /* the routed layers, in first-op order */
     std::vector first_of_;    /* by op: the layer whose first op it is, or -1 */
     std::vector last_of_;     /* by op: the layer whose last op it is, or -1 */
 
-    /* ONE LAYER'S PLACE IN THE RING. [beg, end) is in bytes handed out since bring-up; the
-     * offset in the region is beg modulo its size, and a place never straddles the region's end. */
+    /* One layer's place in the ring. [beg, end) is in bytes handed out since bring-up; the region
+     * offset is beg modulo its size, and a place never straddles the region's end. */
     struct Place {
         int32_t  li = -1;                      /* index into layers_ */
         int64_t  beg = 0, end = 0;
@@ -150,15 +153,15 @@ private:
         RadEvent free = nullptr;               /* behind its last reader */
         bool     free_rec = false;
         /* Its last op has been issued at least once and `free` is recorded behind it. A step
-         * longer than the MoE block's pass of rows issues a layer's ops once per pass, so the
-         * last op can run again: the copies are published away at the NEXT layer's first op,
-         * which is past every pass, while each run of the last op moves `free` behind itself. */
+         * longer than the MoE block's pass of rows issues a layer's ops once per pass, so the last
+         * op can repeat: each repeat moves `free` behind itself, and the copies are published away
+         * only at the next layer's first op. */
         bool     read = false;
         bool     retired = false;              /* its units are published at their pool slots */
         std::vector staged;
     };
-    /* More places than a ring of two shares can hold layers of the smallest share a pass stages;
-     * a full table only stops the copies going further ahead. */
+    /* More places than a two-share ring can hold at the smallest per-layer share; a full table
+     * only stops copies running further ahead. */
     static constexpr int kPlaces = 16;
     Place    place_[kPlaces];
     std::deque  ring_order_;  /* places in the ring, oldest first; retired ones stay until lapped */
@@ -166,22 +169,27 @@ private:
 
     Mover*   mover_ = nullptr;
     char*    region_ = nullptr;
+    char*    low_ = nullptr;           /* the ring's place at the span's shared level, or null */
+    char*    base_ = nullptr;          /* where the places in the ring are */
+    char*    want_ = nullptr;          /* where this pass wants it (set_ring) */
+    bool     rebase_ = false;          /* the pass moves the ring before its first copy */
+    RadEvent moved_t_ = nullptr;       /* the move's two waits: behind the mover's stream, */
+    RadEvent moved_c_ = nullptr;       /* and behind the compute stream */
     int64_t  ring_ = 0;
     int64_t  head_ = 0;                /* bytes handed out since bring-up */
     int64_t  min_rows_ = 0;
 
-    /* THE PACE (see the top of this file): layer k's copies wait on the event recorded at the
-     * first op of layer k - kLead, on the compute stream. A layer within kLead of the pass's first
-     * routed layer has no such layer in its pass and goes at once. */
+    /* The pace (see the file header): layer k's copies wait on the compute-stream event recorded
+     * at the first op of layer k - kLead. A layer within kLead of the pass's first routed layer
+     * goes at once. */
     static constexpr int32_t kLead = 3;
     static constexpr int kGates = 64;
     RadEvent gate_[kGates] = {};
     int32_t  gate_li_[kGates] = {};    /* the layer each gate was recorded at this pass, or -1 */
     int32_t  first_li_ = -1;           /* the pass's first routed layer */
 
-    bool     full_ = false;
     bool     armed_ = false;
-    /* armed_ as the last trunk pass's begin_pass set it, which end_pass leaves alone: the engine
+    /* armed_ as the last trunk pass's begin_pass set it; end_pass leaves it, since the engine
      * asks after the pass has ended. */
     bool     staged_ = false;
     bool     next_prefill_ = false;
@@ -196,45 +204,44 @@ private:
     void withdraw_early();
     int  take(int64_t want, bool partial, int32_t* out);
     int  recycle_front();
+    int  rebase(RadStream s);
     void retire(Place& p);
 };
 
-/* ---- THE FILE STAGER: routed layers read from the container -------------------------------------
+/* ---- the file stager: routed layers read from the container -------------------------------------
  *
- * A routed unit the plan put on the file tier (--weights-disk-tier) has no address of its own, and
- * a grouped GEMM is handed every expert's pointer at issue. So on EVERY pass -- a decode step as
- * much as a prefill chunk -- each routed layer's file-tier units are read into one of the mover's
- * two file buffers before the layer's first expert op and published there, and published as null
- * again when the next routed layer starts. Which experts the router picks cannot be known on the
- * host without a round trip, so the whole layer's file-tier part is read; a prefill chunk routes to
- * nearly all of it anyway, and a decode step is paced by the drive -- the trade the flag names.
+ * A routed unit on the file tier (--weights-disk-tier) has no address of its own, and a grouped
+ * GEMM is handed every expert's pointer at issue. So on every pass, decode included, each routed
+ * layer's file-tier units are read into one of the mover's two file buffers before the layer's
+ * first expert op and published there, then published as null when the next routed layer starts.
+ * The router's picks are not known on the host without a round trip, so the layer's whole
+ * file-tier part is read; decode is then paced by the drive, which is the trade the flag makes.
  *
  *   the pass's first op      read the first routed layer the pass issues
  *   a layer's first op       release the layer before (record its buffer free on the stream, publish
- *                            null), wait on this layer's copies, and read the NEXT layer into the
+ *                            null), wait on this layer's copies, and read the next layer into the
  *                            buffer just released -- its copies queue behind that free event
  *   the pass's end           release whatever is still held
  *
- * A LAYER IS RELEASED WHEN THE NEXT ONE STARTS, not at its own last op: a routed block that slices a
- * large step into passes of `rows` tokens issues its expert ops once a slice, so the last declared
- * op of the layer comes round again, and a release there would leave the second slice reading null.
- * Repeats of the current layer's first op do nothing.
+ * A layer is released when the next one starts, not at its own last op: a routed block that slices
+ * a large step into passes of `rows` tokens issues its expert ops once per slice, so a release at
+ * the last op would leave the next slice reading null. Repeats of the current layer's first op do
+ * nothing.
  *
- * THE READ IS ON THE ISSUING THREAD and blocks it; the card meanwhile runs whatever was issued
- * before it. A routed layer's file-tier part is gigabytes and its compute milliseconds, so the step
- * is the drive's either way, and a reader thread would buy the few percent the layer's own compute
- * is worth at the cost of a second writer of the residency table.
+ * The read blocks the issuing thread while the card runs what was issued before it. A layer's
+ * file-tier part is gigabytes against milliseconds of compute, so the step is drive-bound either
+ * way; a reader thread would gain little and add a second writer of the residency table.
  *
- * A layer is read ahead only when the pass will issue it -- the same learned bound PrefillStager
- * keeps (by draft_pass), so a trunk pass does not read the MTP head's layer for nothing. */
+ * A layer is read ahead only when the pass will issue it (a bound learned per draft_pass from the
+ * last pass of that kind), so a trunk pass does not read the MTP head's layer. */
 class FileStager final : public OpStager {
 public:
     ~FileStager() override;
 
-    /* The routed layers of `plan` that hold a unit on the file tier and the ops that read them,
-     * over the mover's two file buffers. Leaves it disabled -- enabled() false -- when the plan
-     * puts no routed unit there; refuses a plan whose routed layers are read by interleaved ops,
-     * because a file-tier unit has no other address to fall back on. */
+    /* Binds the routed layers with file-tier units and the ops that read them, over the mover's
+     * two file buffers. Leaves enabled() false when no routed unit is on the file tier. Refuses a
+     * plan whose routed layers are read by interleaved ops, since a file-tier unit has no other
+     * address to fall back on. */
     int init(const Program& prog, const Plan& plan, Mover* mover);
 
     bool    enabled() const { return !layers_.empty(); }
@@ -243,15 +250,10 @@ public:
 
     bool begin_pass(const RadBatch* b) override;
     int  before_op(rad_op h, RadStream s, bool* resync) override;
-    int  after_op(rad_op h, RadStream s) override;
     int  end_pass(RadStream s) override;
 
 private:
-    struct Layer {
-        int32_t              layer = -1;
-        std::vector units;
-        int32_t              first_op = -1, last_op = -1;
-    };
+    using Layer = StagedLayer;
     std::vector   layers_;      /* the routed layers with file-tier units, in first-op order */
     std::vector first_of_;    /* by op: the layer whose first op it is, or -1 */
 
@@ -269,7 +271,7 @@ private:
     bool     first_op_ = false;
     int32_t  pass_kind_ = 0;
     int32_t  last_issued_ = -1;
-    std::map pass_last_;
+    std::map pass_last_;   /* by draft_pass: the last op such a pass issued */
 
     bool will_issue(int32_t li) const;
     int  start(int32_t li);
diff --git a/core/plugin/CMakeLists.txt b/core/plugin/CMakeLists.txt
index 5dfcce5d..3575f5f2 100644
--- a/core/plugin/CMakeLists.txt
+++ b/core/plugin/CMakeLists.txt
@@ -1,5 +1,3 @@
-# The plugin layer's own sources (registry.h, loader.cpp, schema.cpp, select.cpp, bands.cpp) are
-# picked up by core/CMakeLists.txt's per-directory glob and compiled into rad_core. This file
-# exists only for the test plugins below it, which must be .so files rather than part of the
-# engine -- the plugin loader cannot be tested by anything it does not dlopen.
+# The plugin layer's sources are compiled into rad_core by core/CMakeLists.txt's glob. This file
+# only adds the test plugins, which must be separate .so files so the loader can dlopen them.
 add_subdirectory(testplugin)
diff --git a/core/plugin/bands.cpp b/core/plugin/bands.cpp
index 0ab795e3..25582d1a 100644
--- a/core/plugin/bands.cpp
+++ b/core/plugin/bands.cpp
@@ -1,27 +1,40 @@
 /* bands.cpp -- the bucket table. spec.md §2.2.
  *
- * A parameter may be declared as a range rather than a value, because some of them are properties
- * of the batch and not of the model. M is the obvious one: a GEMM sees one row at decode,
- * sixty-four at a speculative verify and thousands in a prefill chunk, and libr4d has a different
- * kernel for each band. Resolving once at M = max_tok would pick the prefill kernel and then run
- * it at M = 1, which is exactly the loss that skinny-GEMM specialisation exists to recover.
+ * A parameter may be declared as a range, because some parameters belong to the batch rather
+ * than the model. M is the main one: a GEMM sees one row at decode, 64 at a speculative verify
+ * and thousands in a prefill chunk, and libr4d has a different kernel for each band. Resolving
+ * once at M = max_tok would run the prefill kernel at M = 1.
  *
- * THE BUCKET BOUNDARIES ARE THE CONSTRAINT VALUES THEMSELVES. Nothing here picks a policy, a
- * power-of-two ladder or a bucket count: the kernels already said where their bands end, and this
- * file only collects what they said. A kernel whose fast band sits at an odd boundary gets that
- * boundary, because it said so.
+ * The bucket boundaries are the candidate kernels' own constraint values. There is no
+ * power-of-two ladder or bucket-count policy here.
  */
 #include "registry.h"
 
 #include 
+#include 
+#include 
 
 namespace rad {
 
 namespace {
 
-/* "M <= 64" for the first band, "M in (16, 64]" for a later one -- the half-open form is what a
- * band actually is, and a reader who sees only "<= 64" on the second row will read the table as
- * overlapping. */
+/* The DIV a row places on the ranged parameter, or the least common multiple of several; 0 when
+ * it places none. */
+int64_t ranged_div(const KernelRow* r, std::string_view key) {
+    if (!r || !r->info || key.empty()) return 0;
+    int64_t d = 0;
+    for (int i = 0; i < r->info->n_constraints; ++i) {
+        const RadConstraint& c = r->info->constraints[i];
+        if (c.op != RAD_C_DIV || !c.key || key != c.key || c.ival <= 1) continue;
+        int64_t a = d ? d : 1, b = c.ival;
+        while (b) { const int64_t t = a % b; a = b; b = t; }
+        d = (d ? d : 1) / a * c.ival;
+    }
+    return d;
+}
+
+/* "M <= 64" for the first band, "M in (16, 64]" for a later one, so the printed table does not
+ * read as overlapping. */
 std::string band_span(std::string_view key, int64_t lo_excl, int64_t hi, bool first) {
     if (hi == INT64_MAX) return std::string("any shape");   /* the op has no ranged parameter */
     if (first) return fmt("%.*s <= %lld", (int)key.size(), key.data(), (long long)hi);
@@ -36,9 +49,8 @@ std::vector Registry::build_bands(std::string_view op, std::string_view ra
                                         const RowFilter* accept) {
     std::vector out;
 
-    /* No ranged parameter: one band covering everything. hi is INT64_MAX rather than the declared
-     * value so the issue path's band scan finds it for any issue count -- an op with no range has no
-     * value to index by, and a table that can miss on an op that cannot miss is a trap. */
+    /* No ranged parameter: one band covering everything. hi is INT64_MAX, not the declared value,
+     * so the issue path's band scan finds it for any issue count. */
     if (ranged_key.empty()) {
         lo = 0;
         hi = INT64_MAX;
@@ -49,11 +61,13 @@ std::vector Registry::build_bands(std::string_view op, std::string_view ra
         hi = lo;
     }
 
-    /* The union of the LE, GE and EQ values candidate kernels place on the ranged parameter, from
-     * EVERY plugin and BOTH domains -- the boundaries are a property of the op's candidate set,
-     * not of whichever kernel happens to win a given band. DIV and IN cut nothing: a kernel that
-     * wants K divisible by 128 wants it at every value in the range, and set membership is not an
-     * interval, so neither can be a band edge. */
+    /* The union of the LE, GE and EQ values that candidate kernels from every plugin and both
+     * domains place on the ranged parameter: boundaries belong to the candidate set, not to the
+     * kernel that wins a band. An IN on the ranged parameter lists its values, each an EQ with a
+     * band of its own, so the row wins only values it serves. A DIV is not an interval and cuts no
+     * edge: a row with one is resolved at a band's upper bound, which it divides, and the band
+     * records the divisor so the issue path refuses a value inside it the row does not serve
+     * (Resolved::ranged_div). */
     std::vector bounds;
     auto add = [&](int64_t b) {
         if (b >= lo && b < hi) bounds.push_back(b);   /* clamped to the declared range; hi closes
@@ -67,12 +81,18 @@ std::vector Registry::build_bands(std::string_view op, std::string_view ra
                     if (!c.key || ranged_key != c.key) continue;
                     switch (c.op) {
                         case RAD_C_LE: add(c.ival);     break;
-                        /* A kernel that starts at v ends the band below it at v-1, so the band it
-                         * serves begins exactly where it said it does. */
+                        /* A kernel that starts at v ends the band below it at v-1. */
                         case RAD_C_GE: add(c.ival - 1); break;
-                        /* An EQ needs both edges, or the single value it serves would share a band
-                         * with values it does not. */
+                        /* An EQ needs both edges, so its value gets a band of its own. */
                         case RAD_C_EQ: add(c.ival - 1); add(c.ival); break;
+                        case RAD_C_IN:
+                            for (std::string_view tok : split_ws(c.sval ? c.sval : "")) {
+                                const std::string t(tok);
+                                char* end = nullptr;
+                                const long long v = std::strtoll(t.c_str(), &end, 10);
+                                if (end && *end == '\0' && end != t.c_str()) { add(v - 1); add(v); }
+                            }
+                            break;
                         default: break;
                     }
                 }
@@ -83,9 +103,8 @@ std::vector Registry::build_bands(std::string_view op, std::string_view ra
     bounds.erase(std::unique(bounds.begin(), bounds.end()), bounds.end());
     bounds.push_back(hi);
 
-    /* Each band is resolved AT ITS UPPER BOUND, in both domains. The upper bound is the worst case
-     * in the band, so a kernel that serves it serves the whole band; resolving at the lower bound
-     * would hand a band to a kernel that cannot run its largest value. */
+    /* Each band is resolved at its upper bound, in both domains: the upper bound is the band's
+     * worst case, so a kernel that serves it serves the whole band. */
     int64_t prev = lo - 1;
     for (size_t i = 0; i < bounds.size(); ++i) {
         Band b;
@@ -98,31 +117,22 @@ std::vector Registry::build_bands(std::string_view op, std::string_view ra
         for (int dom = 0; dom < RAD_N_DOMAINS; ++dom) {
             b.dom[dom] = resolve(op, g, dom, &t, accept);
             if (!b.dom[dom]) b.miss[dom] = t.reason;
+            else b.dom[dom].ranged_div = ranged_div(b.dom[dom].row, ranged_key);
         }
 
         b.span = band_span(ranged_key, prev, b.hi, i == 0);
-        if (!b.dom[RAD_DOMAIN_DEVICE]) {
-            /* Fatal, but not here: declare always completes, and the caller reports every miss at
-             * the end rather than the first one at the top (§3.1). A range with a hole in it is
-             * reported as that band, not as the whole op. */
-            RAD_DEBUG("op '%s' %s: no device kernel -- %s", std::string(op).c_str(),
-                      b.span.c_str(), b.miss[RAD_DOMAIN_DEVICE].c_str());
-        }
         if (!b.dom[RAD_DOMAIN_HOST])
             b.miss[RAD_DOMAIN_HOST] += "; site 'host' is unavailable for this band";
         out.push_back(std::move(b));
         prev = bounds[i];
     }
 
-    /* Absence is asymmetric. No device kernel is fatal and the caller says so; no host kernel
-     * removes one placement option -- host-site execution needs a RAD_DOMAIN_HOST kernel, and
-     * where none resolves the planner may not put this op's arithmetic on the host. The host
-     * and SSD TIERS are untouched: a weight can still live there and stage to the device (§5.1).
+    /* No device kernel is fatal. No host kernel only removes host-site execution for this op;
+     * its weights may still live in the host and SSD tiers and stage to the device (§5.1).
      *
-     * NEITHER IS REPORTED HERE. This function runs once per DECLARED OP, so a 64-layer model
-     * calls it 64 times for the same op name, and a warning emitted here would print one line
-     * per (layer, band) -- hundreds of identical sentences at startup. The band's miss string is
-     * the record instead; Builder collects them and reports once, over the whole graph. */
+     * Neither is reported here: this runs once per declared op (64 times for the same op on a
+     * 64-layer model). Declare always completes, and Builder collects the bands' miss strings and
+     * reports once per graph (§3.1), a hole in a range as that band. */
     return out;
 }
 
diff --git a/core/plugin/loader.cpp b/core/plugin/loader.cpp
index 8b6e0ef1..6f2f4a31 100644
--- a/core/plugin/loader.cpp
+++ b/core/plugin/loader.cpp
@@ -19,8 +19,8 @@ namespace rad {
 
 namespace {
 
-/* dlsym returns void*, which is not a function pointer in standard C++ and is one everywhere this
- * engine will ever run. The cast is isolated here so the rest of the file reads. */
+/* dlsym returns void*; converting it to a function pointer is conditionally supported in
+ * standard C++ and works on every target here. The cast is isolated in one place. */
 template 
 Fn dl_fn(void* h, const char* name) {
     dlerror();
@@ -38,8 +38,8 @@ std::string stem_of(const std::string& path) {
 
 const char* or_empty(const char* s) { return s ? s : ""; }
 
-/* Does a plugin's declared coverage include this device's architecture? The field is a list, so a
- * binary built for several is one entry per name, separated by spaces or commas. */
+/* Whether a plugin's declared build target list (separated by spaces, commas or semicolons)
+ * names this device's architecture. */
 bool target_covers(const std::string& declared, const char* arch) {
     for (size_t i = 0; i < declared.size(); ) {
         size_t e = declared.find_first_of(" ,;", i);
@@ -50,11 +50,10 @@ bool target_covers(const std::string& declared, const char* arch) {
     return false;
 }
 
-/* Two schemas for one op name are the SAME schema when every positional slot means the same thing.
- * Parameter keys, types and requiredness are load-bearing: they are the geometry the selector
- * matches on. Operand roles, count and optionality are load-bearing: arguments are positional.
- * Operand NAMES are not -- the ABI says they are for diagnostics -- so two plugins spelling slot 1
- * "b" and "w_gate" agree, and refusing that would be refusing a synonym. */
+/* Two schemas for one op are the same when every positional slot means the same thing: parameter
+ * keys, types and requiredness (what the selector matches on) and operand count, roles and
+ * optionality (arguments are positional). Operand names are for diagnostics only (ABI), so "b"
+ * and "w_gate" in slot 1 agree. */
 bool schema_same(const RadOpSchema& a, const RadOpSchema& b, std::string* diff) {
     if (a.n_params != b.n_params) {
         *diff = fmt("%d parameters vs %d", a.n_params, b.n_params);
@@ -68,9 +67,8 @@ bool schema_same(const RadOpSchema& a, const RadOpSchema& b, std::string* diff)
             return false;
         }
         if (x.type != y.type) {
-            *diff = fmt("parameter '%s' is %s vs %s", or_empty(x.key),
-                        x.type == RAD_P_STR ? "a string" : "an integer",
-                        y.type == RAD_P_STR ? "a string" : "an integer");
+            *diff = fmt("parameter '%s' is %s vs %s", or_empty(x.key), param_kind_name(x.type),
+                        param_kind_name(y.type));
             return false;
         }
         if (x.required != y.required) {
@@ -108,17 +106,16 @@ void Registry::err_(const char* f, ...) {
 }
 
 /* ------------------------------------------------------------------ staging */
-/* dlopen and read the plugin's identity, without registering anything. Two phases, because the
- * hierarchy is ordered by plugin NAME and the name lives inside the .so: the whole directory must
- * be open before anything can be registered, and registration order is what fixes an op's schema. */
+/* dlopen and read the plugin's identity without registering anything. Loading has two phases
+ * because the hierarchy is ordered by plugin name, which lives inside the .so: the whole directory
+ * is opened before anything registers, and registration order fixes an op's schema. */
 int Registry::stage_(const std::string& path, Staged* out) {
     out->path = path;
     out->file = stem_of(path);
 
-    /* RTLD_LOCAL is not a preference. Every kernel plugin exports the same four symbol names --
-     * rad_kernel_count and friends -- so RTLD_GLOBAL would let the first plugin loaded answer for
-     * every plugin after it, and the failure would look like a plugin whose kernels vanished. We
-     * dlsym against the handle instead, which is exactly what RTLD_LOCAL is for. */
+    /* RTLD_LOCAL is required: every kernel plugin exports the same symbol names (rad_kernel_count
+     * and friends), so with RTLD_GLOBAL the first plugin loaded would answer for all later ones.
+     * Symbols are looked up per handle. */
     out->code_from = rad::dev_code_mark();
     out->handle = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL);
     out->code_to = rad::dev_code_mark();
@@ -135,10 +132,8 @@ int Registry::stage_(const std::string& path, Staged* out) {
     }
     const uint32_t v = abi();
     if (v != RAD_ABI_VERSION) {
-        /* Named by FILE, not by RadPluginInfo::name: the struct is exactly the thing that may have
-         * changed shape between ABI versions, so reading it here would be reading a different
-         * layout than the one this build was compiled against. Both versions are printed because
-         * "ABI mismatch" alone does not tell an operator which side is stale. */
+        /* Named by file, not RadPluginInfo::name: that struct's layout may differ across ABI
+         * versions. Both versions are printed so the operator can tell which side is stale. */
         err_("plugin '%s' was built against ABI version %u; this engine is version %u -- refused",
              path.c_str(), v, (unsigned)RAD_ABI_VERSION);
         unstage_(*out);
@@ -209,26 +204,25 @@ int Registry::commit_(Staged& s, int order) {
             unstage_(s);
             return RAD_E_INVAL;
         }
-        /* The second half of the key. OPTIONAL: a plugin written before this export existed serves
-         * an unquantised container, which is what "" means, so its absence is not an error. */
+        /* The second half of the key. Optional: a plugin without it serves an unquantised
+         * container, which "" means. */
         if (auto q_fn = dl_fn(s.handle, "rad_arch_quant"))
             p.arch_quant = or_empty(q_fn());
 
-        /* ALSO OPTIONAL, and for the same reason: it answers what the core needs to know before
-         * it can build the RadBuildCtx that declare runs against. Absent means every answer is
-         * the zero -- see rad_builder.h. */
+        /* Optional: answers what the core needs before it builds the RadBuildCtx for declare.
+         * Absent means every answer is zero (rad_builder.h). */
         p.arch_probe = dl_fn(s.handle,
                                                                          "rad_arch_probe");
-        /* AND THE REPLY FORMAT, optional for the same reason: a plugin that says nothing has its
-         * model's format read off the chat template. */
+        /* Optional: absent means the reply format is read off the chat template. */
         p.arch_chat_format = dl_fn(
             s.handle, "rad_arch_chat_format");
+        /* Optional: absent means the model serves no speech route. */
+        p.arch_audio_format = dl_fn(
+            s.handle, "rad_arch_audio_format");
 
-        /* One plugin implements one architecture id AT ONE QUANTISATION, and no two may claim the
-         * same pair: the pair is what selects the plugin, so two claimants is a coin toss over
-         * which graph a model gets built from (§2.4). Two plugins sharing an id at different
-         * quantisations is the NORMAL case -- qwen35_bf16 and qwen35_fp8 are the same architecture
-         * over two weight formats -- and refusing that would make §2.4 unimplementable. */
+        /* The (architecture id, quantisation) pair selects the plugin, so no two plugins may claim
+         * the same pair (§2.4). Sharing an id at different quantisations is normal (qwen35_bf16
+         * and qwen35_fp8). */
         for (const Plugin& q : plugins_) {
             if (q.arch_id == p.arch_id && q.arch_quant == p.arch_quant) {
                 err_("architecture id '%s' at quantisation '%s' is claimed by both '%s' and '%s' "
@@ -251,9 +245,8 @@ int Registry::commit_(Staged& s, int order) {
             return RAD_E_INVAL;
         }
 
-        /* Schemas are checked WHOLE before any of them is committed. A plugin that conflicts on
-         * its fourth op must not leave its first three registered under its name -- a half-loaded
-         * plugin is a state nobody can reason about afterwards. */
+        /* All schemas are checked before any is committed, so a plugin refused on one op leaves
+         * nothing registered. */
         n_declared_schemas = sc_n();
         for (int i = 0; i < n_declared_schemas; ++i) {
             const RadOpSchema* sch = sc_at(i);
@@ -267,11 +260,9 @@ int Registry::commit_(Staged& s, int order) {
             auto it = schemas_.find(sch->op);
             if (it != schemas_.end()) {
                 if (!schema_same(*it->second.schema, *sch, &diff)) {
-                    /* Refused at load with both plugins named. Since arguments are positional, two
-                     * disagreeing schemas would make the same call mean different things depending
-                     * on which plugin won selection, and that is not a diagnosable failure -- it
-                     * is silent numerical garbage (§2.3). The whole plugin is refused, not just
-                     * the op: a plugin built against a different vocabulary is stale everywhere. */
+                    /* Disagreeing positional schemas would silently change a call's meaning
+                     * (§2.3). The whole plugin is refused, not just the op: it was built against
+                     * a different vocabulary. */
                     err_("op '%s' has two different schemas: '%s' fixed it first, '%s' disagrees "
                          "(%s) -- refusing '%s'",
                          sch->op, it->second.plugin.c_str(), p.name.c_str(), diff.c_str(),
@@ -300,8 +291,7 @@ int Registry::commit_(Staged& s, int order) {
                 unstage_(s);
                 return RAD_E_INVAL;
             }
-            /* A row with no entry point is a row that resolves and then cannot run, which is the
-             * one failure this layer exists to make impossible. */
+            /* A row with no entry point would resolve and then fail to run. */
             if (!k->launch) {
                 err_("kernel '%s' in plugin '%s' has no launch function", k->name, p.name.c_str());
                 unstage_(s);
@@ -313,17 +303,10 @@ int Registry::commit_(Staged& s, int order) {
                 unstage_(s);
                 return RAD_E_INVAL;
             }
-            /* EVERY TUNABLE AXIS CARRIES A DEFAULT, AND THE DEFAULT IS ONE OF ITS OWN VALUES.
-             *
-             * This is what makes an untuned install fast rather than broken (spec §15): a machine
-             * with no cache, a shape nobody measured, a cache from a different card -- all of them
-             * land on the defaults, and there is no other fallback beneath them. A kernel that
-             * declares an axis without a usable default has no answer at all for those cases, so
-             * it is refused here rather than resolving and then launching a zero tile.
-             *
-             * Checked at LOAD and not at first use, for the same reason the missing launch
-             * function above is: a library author finds out when the plugin loads, not when some
-             * shape three hours into a serve happens to miss the cache. */
+            /* Every tunable axis must carry a default that is one of its own values. Untuned
+             * shapes (no cache, an unmeasured shape, another card's cache) run the defaults, with
+             * no other fallback (spec §15). Checked at load rather than first use so a bad axis
+             * fails at startup, not when some shape first misses the cache. */
             for (int v = 0; v < k->n_tunables; ++v) {
                 const RadTunable& t = k->tunables[v];
                 if (!t.key || !t.key[0] || !t.values || t.n_values <= 0) {
@@ -336,9 +319,7 @@ int Registry::commit_(Staged& s, int order) {
                 for (int j = 0; j < t.n_values; ++j) if (t.values[j] == t.deflt) ok = true;
                 if (!ok) {
                     err_("kernel '%s' in plugin '%s': tunable '%s' defaults to %lld, which is not "
-                         "one of the values it declares. The default is what runs when this "
-                         "machine has no measurement for a shape, so it has to be a value the "
-                         "kernel can actually launch",
+                         "one of its declared values",
                          k->name, p.name.c_str(), t.key, (long long)t.deflt);
                     unstage_(s);
                     return RAD_E_INVAL;
@@ -354,14 +335,12 @@ int Registry::commit_(Staged& s, int order) {
             staged_rows.emplace_back(k, i);
         }
 
-        /* A KERNEL LIBRARY WITH NO CODE FOR THIS CARD IS LEFT OUT OF THE CARD'S SELECTION. Its
-         * device rows would otherwise resolve -- a row's constraints say nothing about which card
-         * it was compiled for -- and the first launch would fail, so an installation carrying
-         * libraries for several cards would serve none of them but the first in the hierarchy.
-         * What the library carries is read out of the fat binaries its dlopen registered, which is
-         * what the launch itself will consult (core/device/aql_code.cpp), not out of
-         * build_target, which is prose. Its host rows run anywhere and stay. On the host backend
-         * an engine that serves says no GPU code runs at all (set_no_device_code). */
+        /* A kernel library with no code for this card has its device rows dropped: constraints
+         * do not say which card a row was compiled for, so the rows would resolve and then fail
+         * to launch, and an installation with libraries for several cards would serve only the
+         * first. Coverage is read from the fat binaries its dlopen registered, which the launch
+         * consults (core/device/aql_code.cpp), not from build_target. Host rows stay. On the host
+         * backend no GPU code runs at all (set_no_device_code). */
         int n_device = 0;
         for (const auto& r : staged_rows) n_device += r.first->domain == RAD_DOMAIN_DEVICE;
         std::string why;
@@ -389,8 +368,7 @@ int Registry::commit_(Staged& s, int order) {
             unstage_(s);
             return RAD_E_INVAL;
         }
-        /* Checked WHOLE before any is registered, for the reason the kernel schemas are: a plugin
-         * refused on its third quantiser must not leave the first two answering to a recipe. */
+        /* All checked before any is registered, as with kernel schemas. */
         for (int i = 0, n = q_n(); i < n; ++i) {
             const RadQuantizerInfo* q = q_at(i);
             if (!q || !q->name || !q->name[0] || !q->encoding || !q->quantize) {
@@ -399,8 +377,8 @@ int Registry::commit_(Staged& s, int order) {
                 unstage_(s);
                 return RAD_E_INVAL;
             }
-            /* A NAME IS ONE QUANTISER. A recipe that names it would otherwise mean different
-             * numbers depending on which plugin loaded first. */
+            /* Quantiser names are unique, so a recipe means the same thing whatever the load
+             * order. */
             auto clash = [&](const char* other) { return std::strcmp(other, q->name) == 0; };
             for (const QuantRow& r : quants_)
                 if (clash(r.info->name)) {
@@ -424,13 +402,12 @@ int Registry::commit_(Staged& s, int order) {
         return RAD_E_INVAL;
     }
 
-    /* Once after the plugin is loaded and before any selection (rad_abi.h). A plugin that cannot
-     * open -- no device, no config table -- is refused rather than asked to select. */
+    /* Called once after load, before any selection (rad_abi.h). A plugin that cannot open is
+     * refused. */
     if (auto open = dl_fn(s.handle, "rad_plugin_open")) {
         int st = open();
-        /* RAD_E_UNSUPPORTED is a plugin saying this machine is not one it serves -- a library for
-         * another card, in an installation that ships several. That is a skip, said once, and
-         * not a failure: the next library in the hierarchy is the one that serves this card. */
+        /* RAD_E_UNSUPPORTED: the plugin does not serve this machine (e.g. a library for another
+         * card). A skip, not a failure. */
         if (st == RAD_E_UNSUPPORTED) {
             RAD_INFO("plugin '%s' declines this machine and is not loaded", p.name.c_str());
             unstage_(s);
@@ -443,15 +420,14 @@ int Registry::commit_(Staged& s, int order) {
         }
     }
 
-    /* What the plugin DECLARES, not what it fixed: a plugin below another one re-declares the same
-     * ops with the same shapes, and reporting 0 there would read as a plugin that declares
-     * nothing. Which plugin fixed a given op is schema_owner()'s answer, not a count. */
+    /* What the plugin declares, including ops an earlier plugin already fixed; schema_owner()
+     * answers which plugin fixed an op. */
     p.n_schemas = n_declared_schemas;
     p.n_kernels = (int)staged_rows.size();
     for (const RadOpSchema* sch : staged_schemas) schemas_[sch->op] = SchemaEntry{sch, p.name};
     for (const RadQuantizerInfo* q : staged_quants) {
         quants_.push_back(QuantRow{ q, p.name });
-        /* Its own schemes are read through it, by everything that decodes a weight. */
+        /* Register its decoder so every weight reader can decode its schemes. */
         if (q->decode) enc_add_decoder(q->decode);
     }
     const auto concurrent = dl_fn(s.handle, "rad_kernel_concurrent");
@@ -470,18 +446,10 @@ int Registry::commit_(Staged& s, int order) {
         rows_.push_back(row);
     }
 
-    /* A KERNEL LIBRARY BUILT FOR ANOTHER CARD FAILS AT EVERY LAUNCH, AND THIS IS THE ONE PLACE IT
-     * CAN BE NAMED ONCE. An installed .so travelling to a machine it was not compiled for is
-     * otherwise invisible until the first dispatch, where it surfaces as a driver error carrying a
-     * kernel name and nothing about why.
-     *
-     * A WARNING AND NOT A REFUSAL, deliberately. build_target is text the plugin's author writes;
-     * it is not derived from what the binary actually contains, so a library covering several
-     * architectures may still name only one, and refusing on it would be refusing on a claim the
-     * engine cannot verify. The launch is what is authoritative. This predicts it by name.
-     *
-     * "host" and "" are not claims about a device: the first is a library of CPU kernels, which
-     * run anywhere, and the second is a plugin that declines to claim anything. */
+    /* A library built for another card fails at every launch with an unhelpful driver error;
+     * warn once here instead. Only a warning: build_target is author-written text, not derived
+     * from the binary, so it cannot justify a refusal. "host" (CPU kernels) and "" (no claim) say
+     * nothing about a device. Applies to libraries whose dlopen registered no fat binaries. */
     if (p.kind == RAD_PLUGIN_KERNEL && s.code_to == s.code_from && !p.build_target.empty() &&
         p.build_target != "host") {
         RadDeviceProps dp{};
@@ -502,9 +470,8 @@ int Registry::commit_(Staged& s, int order) {
     return RAD_OK;
 }
 
-/* The per-op index select() walks, in (hierarchy order, declaration order). Rebuilt whole on every
- * registration: loading is startup and the row count is in the hundreds, so the simple thing is
- * also the fast enough thing, and an index that can never be stale is one fewer invariant. */
+/* The per-op index select() walks, in (hierarchy order, declaration order). Rebuilt whole on
+ * every registration; there are only hundreds of rows, at startup. */
 void Registry::index_rows_() {
     by_op_.clear();
     for (const KernelRow& r : rows_) by_op_[r.info->op].push_back(&r);
@@ -534,11 +501,9 @@ int Registry::load_dirs(const std::vector& dirs,
                         const std::vector& hierarchy) {
     int first_error = RAD_OK;
 
-    /* Directory by directory in the order given, and within one in filename order, so a set of
-     * plugins nobody named still loads the same way twice. A file whose name an earlier directory
-     * already supplied is SHADOWED rather than loaded: the first directory is the one the operator
-     * put first -- their own plugins ahead of an installation's -- and loading both would be two
-     * plugins claiming one name, which is refused. */
+    /* Directories in the given order, files in filename order, so an unconfigured set loads
+     * reproducibly. A file name an earlier directory already supplied is shadowed: the operator's
+     * own plugins come ahead of an installation's, and loading both would be a duplicate name. */
     std::vector files, stems;
     std::string where;
     for (const std::string& dir : dirs) {
@@ -571,7 +536,6 @@ int Registry::load_dirs(const std::vector& dirs,
             stems.push_back(stem);
         }
     }
-    const std::string dir = where;
 
     std::vector staged;
     for (const std::string& f : files) {
@@ -584,8 +548,8 @@ int Registry::load_dirs(const std::vector& dirs,
         staged.push_back(s);
     }
 
-    /* An entry names a library by its declared name or by its file, written as the operator sees
-     * it on disk: `libr4d`, `r4d`, `libr4d.so` and a path to it are one library. */
+    /* An entry matches a library's declared name or its file: `libr4d`, `r4d`, `libr4d.so` and a
+     * path to it are one library. */
     auto names = [](const std::string& h, const Staged& s) {
         return h == s.name || h == s.file || stem_of(h) == s.file;
     };
@@ -594,13 +558,10 @@ int Registry::load_dirs(const std::vector& dirs,
         if (s.info && s.info->kind == RAD_PLUGIN_KERNEL)
             found += (found.empty() ? "" : ", ") + s.name;
 
-    /* A HIERARCHY NAMES THE KERNEL LIBRARIES THAT SERVE, AND ONLY THOSE LOAD. Ordering alone
-     * cannot keep a library out: selection runs per domain, so a library named first that has no
-     * device row for an op leaves that op to whichever unnamed library does -- a GPU library on a
-     * machine whose card it was not built for, say -- and an operator who listed what to use gets
-     * something else. A kernel library on the search path that the list leaves out is closed again
-     * before it registers anything, and said once. Architecture and quantiser plugins are not
-     * kernel libraries and no list ranks them. */
+    /* A non-empty hierarchy is exclusive. Ordering alone cannot keep a library out: selection
+     * runs per domain, so an op the named library has no device row for would fall to an unnamed
+     * one. Unnamed kernel libraries are closed before registering anything. Architecture and
+     * quantiser plugins are never ranked. */
     if (!hierarchy.empty()) {
         std::vector kept;
         std::string left_out;
@@ -623,17 +584,10 @@ int Registry::load_dirs(const std::vector& dirs,
                      "does not name, and so not loaded: %s", left_out.c_str());
     }
 
-    /* The hierarchy is configured, not discovered: a library the operator named takes that
-     * position. With no list every kernel library on the search path loads, so dropping an .so
-     * into the directory adds it with no configuration.
-     *
-     * A REFERENCE LIBRARY IS PINNED BELOW EVERY OTHER UNNAMED PLUGIN. It declares a kernel for
-     * every op it knows, so a plugin ranked behind it is unreachable -- an unnamed kernel library
-     * for this machine's card would load, never be selected for anything, and leave the whole
-     * model resolving to the naive implementation. Pinning it is what makes an unconfigured
-     * drop-in work. Naming it in the hierarchy places it where it is named, which is how it is put
-     * in front of a library to compare against. Which library is one is its own declaration
-     * (RadPluginReferenceFn), not its name. */
+    /* A named library takes its position in the list; unnamed ones follow. A reference library
+     * (RadPluginReferenceFn) is pinned below every other unnamed plugin, because it matches every
+     * op it declares and would make anything behind it unreachable. Naming it places it where
+     * named, e.g. ahead of a library to compare against. */
     const size_t kUnnamed = (size_t)INT_MAX - 1;
     std::vector rank(staged.size());
     for (size_t i = 0; i < staged.size(); ++i)
@@ -646,20 +600,19 @@ int Registry::load_dirs(const std::vector& dirs,
                 hit = true;
             }
         }
-        /* The list is what loads, so an entry that matches nothing is a library that is not
-         * there to select -- and a list none of whose entries match loads no kernel library. */
+        /* The list is what loads: an entry that matches nothing loads nothing in its place. */
         if (!hit)
             RAD_WARN("--kernels (or RADIANCE_KERNELS) names '%s', which is no kernel library in "
                      "%s, so nothing loads in its place; the kernel libraries there are: %s",
-                     hierarchy[h].c_str(), dir.c_str(), found.empty() ? "none" : found.c_str());
+                     hierarchy[h].c_str(), where.c_str(), found.empty() ? "none" : found.c_str());
     }
     std::vector idx(staged.size());
     for (size_t i = 0; i < idx.size(); ++i) idx[i] = i;
     std::stable_sort(idx.begin(), idx.end(),
                      [&](size_t a, size_t b) { return rank[a] < rank[b]; });
 
-    /* Orders continue from what is already loaded, so loading kernels/ and then architectures/
-     * does not produce two plugins at position 0. */
+    /* Continue from what is already loaded, so loading kernels/ then architectures/ does not put
+     * two plugins at position 0. */
     int order = 0;
     for (const Plugin& p : plugins_) order = std::max(order, p.order + 1);
 
@@ -683,18 +636,14 @@ int Registry::load_tune(const std::string& radiance_home, const std::string& mac
     const std::string key = machine.empty() ? rad_machine_key() : machine;
     const int s = tune_.load(radiance_home, key);
     if (s < 0) return s;
-    /* A cache measured on another card is not a slower answer, it is a wrong one -- tunecache.h
-     * makes the machine key line 2 of the file for exactly this. `load` already refuses a
-     * mismatch, so reaching here with rows means they are this machine's. */
+    /* `load` refuses a file whose machine key (line 2, tunecache.h) is another machine's, so
+     * these rows are this machine's. */
     return (int)tune_.rows().size();
 }
 
-/* Kernel plugins declare the ops they implement AND the parameter schema for each. A row whose op
- * has no schema anywhere in the loaded set is a plugin that supplied only half of that contract,
- * and the cost is exact: no architecture plugin's parameters for that op can ever be checked, so a
- * typo in them becomes a silent miss instead of a named one. Checked once the set is complete,
- * because an override plugin may legitimately rely on the schema of the plugin BELOW it, which
- * loads later. */
+/* A row whose op has no schema in the loaded set cannot have its parameters checked, so a typo
+ * would become a silent miss. Checked once the set is complete, because an override plugin may
+ * rely on the schema of a plugin below it, which loads later. */
 int Registry::check_complete() {
     int st = RAD_OK;
     for (const KernelRow& r : rows_) {
@@ -729,9 +678,7 @@ void Registry::close() {
     fini_instances();
     for (const QuantRow& q : quants_)
         if (q.info && q.info->decode) enc_remove_decoder(q.info->decode);
-    /* Reverse order: a plugin lower in the hierarchy may have been opened against state a higher
-     * one established, and unwinding in the order things were built is the only order that is
-     * always safe. */
+    /* Reverse load order: a later plugin may depend on state an earlier one established. */
     for (auto it = plugins_.rbegin(); it != plugins_.rend(); ++it) {
         if (it->close) it->close();
         if (it->handle) dlclose(it->handle);
diff --git a/core/plugin/registry.h b/core/plugin/registry.h
index 06d07ae4..ddfc2e6b 100644
--- a/core/plugin/registry.h
+++ b/core/plugin/registry.h
@@ -1,44 +1,38 @@
 /* registry.h -- the plugin layer: dlopen, the configured hierarchy, the op-schema registry, the
  * constraint selector, bucket tables and the selection table. spec.md §2 and §16.
  *
- * Four rules live here and nowhere else, because every one of them is a rule somebody would
- * otherwise reinvent slightly differently in a second place:
+ * Rules enforced here and nowhere else:
  *
- *   THE HIERARCHY IS ABSOLUTE.  Plugins are queried in configured order and the first plugin with
- *   any matching kernel supplies it. A lower-priority plugin never outbids a higher one no matter
- *   how specialised its kernel -- that is what makes a user override an override (§2.1).
+ *   The hierarchy is absolute. Plugins are queried in configured order and the first plugin with
+ *   any matching kernel supplies it; a lower-ranked plugin never outbids a higher one, however
+ *   specialised its kernel. That is what makes a user override an override (§2.1).
  *
- *   SPECIFICITY IS DECLARED, NOT DERIVED.  Within one plugin the highest `priority` among matching
- *   rows wins, ties broken by declaration order. Counting matched constraints gets it backwards:
- *   {head_dim<=1024, gqa>=1, block%16==0, causal in {0,1}} matches four and {head_dim==256, gqa==6}
- *   matches two, and the second is by far the more specialised.
+ *   Specificity is declared, not derived. Within one plugin the highest `priority` among matching
+ *   rows wins, ties by declaration order. Counting matched constraints gets it backwards:
+ *   {head_dim<=1024, gqa>=1, block%16==0, causal in {0,1}} matches four, {head_dim==256, gqa==6}
+ *   matches two, and the second is more specialised.
  *
- *   SCHEMAS ARE FIXED BY FIRST DECLARATION.  The first plugin in hierarchy order to declare an op
- *   fixes its schema; a later plugin declaring the same op name with a different one is refused at
- *   load with both plugins named. Arguments are positional, so two disagreeing schemas make the
- *   same call mean different things depending on which plugin won selection -- silent numerical
- *   garbage rather than a diagnosable failure (§2.3).
+ *   Schemas are fixed by first declaration. The first plugin in hierarchy order to declare an op
+ *   fixes its schema; a later plugin declaring it differently is refused at load with both named.
+ *   Arguments are positional, so disagreeing schemas would give the same call different meanings
+ *   depending on which plugin won selection (§2.3).
  *
- *   THE BUCKET BOUNDARIES ARE THE CONSTRAINT VALUES THEMSELVES.  The union of the LE, GE and EQ
- *   values candidate kernels place on the ranged parameter, clamped to the declared range. No
- *   policy is chosen by anyone (§2.2).
+ *   Bucket boundaries are the constraint values: the union of the LE, GE and EQ values candidate
+ *   kernels place on the ranged parameter, clamped to the declared range (§2.2).
  *
- *   A REFERENCE LIBRARY IS LAST BY CONSTRUCTION.  A library that declares itself one
- *   (RadPluginReferenceFn) matches every op it declares, so anything ranked behind it would be
- *   unreachable. An unnamed plugin sorts after every named one but still ahead of a reference,
- *   which is what makes dropping in a kernel library for a new card work with no configuration
- *   (§2.1). Naming it in the hierarchy still overrides that. The rule is keyed on the declaration,
- *   never on a name: the libraries that ship with radiance load exactly as a third party's do.
+ *   A reference library is last. A library that declares itself one (RadPluginReferenceFn)
+ *   matches every op it declares, so anything ranked behind it would be unreachable. An unnamed
+ *   plugin sorts after every named one but ahead of a reference, so a kernel library for a new
+ *   card works with no configuration (§18); naming it in the hierarchy overrides that. The rule
+ *   is keyed on the declaration, never on a name, so bundled libraries load like third-party ones.
  *
- * LIFETIME. A Resolved, a Band and a KernelRow all point into a plugin's static tables. They are
- * valid exactly as long as the Registry that loaded them: close() dlcloses, and everything handed
- * out before it dangles after. The core keeps one Registry for the life of the process, so this
- * costs nothing; a tool that loads two kernel sets in turn has to finish with the first.
+ * Lifetime: a Resolved, a Band and a KernelRow point into a plugin's static tables and are valid
+ * only as long as the Registry that loaded them; close() dlcloses. The core keeps one Registry for
+ * the process; a tool that loads two kernel sets in turn must finish with the first.
  *
- * THREADING. Loading is startup, single-threaded, before the rank threads exist. select() and
- * init_instance() are called from every rank thread during declare, so the selection log and the
- * instance list are behind one mutex. It is uncontended at declare and never touched on the step
- * path, which is the only place a lock would cost anything.
+ * Threading: loading is single-threaded, before the rank threads exist. select() and
+ * init_instance() run on every rank thread during declare, so the selection log and instance list
+ * share one mutex. It is never taken on the step path.
  */
 #pragma once
 #include "rad_core.h"
@@ -67,7 +61,7 @@ struct Plugin {
     std::string description;
     std::string build_target;
 
-    uint32_t    kind   = 0;    /* RAD_PLUGIN_KERNEL | RAD_PLUGIN_ARCH */
+    uint32_t    kind   = 0;    /* one of RAD_PLUGIN_KERNEL, _ARCH, _QUANT */
     int         order  = 0;    /* hierarchy position; 0 is highest */
     void*       handle = nullptr;
 
@@ -79,32 +73,30 @@ struct Plugin {
     /* A kernel library that declared itself a reference implementation (RadPluginReferenceFn). */
     bool reference = false;
 
-    /* Architecture plugins are loaded and IDENTIFIED here; the build component drives them. The
-     * core never calls declare or step from the registry -- it only guarantees that no two
-     * plugins claim the same (architecture id, quantisation) PAIR (§2.4). The pair, not the id:
-     * qwen35_bf16 and qwen35_fp8 are the same architecture at two weight formats and both answer
-     * "qwen35", which is the whole reason §2.4 splits on quantisation at all. `arch_quant` is ""
-     * for a plugin that serves an unquantised container, including one that predates the export. */
+    /* Architecture plugins are loaded and identified here; the build component drives them. The
+     * registry only guarantees that no two plugins claim the same (architecture id, quantisation)
+     * pair (§2.4): qwen35_bf16 and qwen35_fp8 both answer "qwen35" at two weight formats.
+     * `arch_quant` is "" for a plugin that serves an unquantised container, including one that
+     * predates the export. */
     std::string arch_id;
     std::string arch_quant;
     int  (*arch_declare)(RadBuilder*, const RadModelMeta*, const RadBuildCtx*) = nullptr;
     void (*arch_step)(RadCtx*, const RadBatch*) = nullptr;
-    /* OPTIONAL (rad_builder.h): null when the plugin exports none, and every question then
-     * answers zero. It is what the core asks BEFORE declare, so that a fact which is an input to
-     * declaration and a property of the model is still read by the plugin and not by us. */
+    /* Optional (rad_builder.h); null means every question answers zero. Asked before declare, so
+     * model facts that are inputs to declaration are still read by the plugin, not the core. */
     int  (*arch_probe)(const RadModelMeta*, RadArchProbe*) = nullptr;
-    /* OPTIONAL (rad_builder.h): null when the plugin exports none, and the reply format is then
-     * derived from the chat template. */
+    /* Optional (rad_builder.h); null means the reply format is derived from the chat template. */
     const RadChatFormat* (*arch_chat_format)(const RadModelMeta*) = nullptr;
+    /* Optional (rad_builder.h); null means the model serves no speech route. */
+    const RadAudioFormat* (*arch_audio_format)(const RadModelMeta*) = nullptr;
 
     RadPluginCloseFn close = nullptr;
 };
 
 /* ------------------------------------------------------------------ one selection question */
-/* What select() did, in enough detail to print §16's table and to answer "why did it not pick the
- * kernel I wrote". `candidates` is every row that was CONSIDERED -- rows of the other domain are
- * not, since they answer a different question, and rows behind a plugin that already supplied a
- * match are not either, because the hierarchy stopped there. */
+/* What select() did, in enough detail to print §16's table and explain why a kernel was not
+ * picked. `candidates` holds every row considered: not rows of the other domain, and not rows
+ * behind a plugin that already supplied a match. */
 struct SelectionTrace {
     struct Candidate {
         std::string plugin;
@@ -123,11 +115,10 @@ struct SelectionTrace {
     int         priority = 0;
     std::string reason;         /* on a miss: the constraint(s) that refused it */
 
-    /* A RAD_DERIVED parameter the CALLER did not supply: its constraints were skipped during
-     * matching, and the winning kernel's RAD_C_EQ value for the key was written into the resolved
-     * geometry afterwards. `known` is false when the winner has no EQ on that key -- ref's
-     * `block_size >= 1` is exactly that case -- and an unset derived key is a condition the
-     * caller has to report, not a zero to be read. */
+    /* A RAD_DERIVED parameter the caller did not supply: its constraints were skipped during
+     * matching and the winner's RAD_C_EQ value for the key was written into the resolved
+     * geometry. `known` is false when the winner has no EQ on the key (e.g. ref's
+     * `block_size >= 1`); the caller must report that, not read a zero. */
     struct DerivedParam {
         std::string key;
         long long   value = 0;
@@ -148,53 +139,44 @@ public:
     Registry& operator=(const Registry&) = delete;
 
     /* ---------------------------------------------------------- loading (§2, §18) */
-    /* Scan a directory of .so files and load them in HIERARCHY ORDER. The hierarchy is configured,
-     * not discovered: `hierarchy` is an ordered list of plugin names (RadPluginInfo::name, or the
-     * file as the operator wrote it -- `libr4d`, `r4d`, `libr4d.so`), so substituting a kernel is
-     * dropping an .so in a directory and naming it ahead of the default. A non-empty list is
-     * EXCLUSIVE: a kernel library it does not name is closed before it registers anything, and an
-     * entry that matches nothing is warned about by name. An empty list loads every kernel library
-     * found, in filename order so the result is reproducible, with a reference library last.
+    /* Scan a directory of .so files and load them in hierarchy order. `hierarchy` is an ordered
+     * list of plugin names (RadPluginInfo::name, or the file as written: `libr4d`, `r4d`,
+     * `libr4d.so`), so substituting a kernel means dropping an .so in and naming it ahead of the
+     * default. A non-empty list is exclusive: a kernel library it does not name is closed before
+     * it registers anything, and an entry that matches nothing is warned about. An empty list
+     * loads every kernel library in filename order (reproducible), a reference library last.
      * Architecture and quantiser plugins are not ranked and always load.
      *
-     * Always completes: every plugin that can be loaded is, every refusal is recorded in
-     * load_errors(), and the FIRST negative status is returned. Reporting the whole list beats
-     * reporting the first failure at the top -- an operator with two stale plugins wants to hear
-     * about both in one run (§3.1). */
+     * Always completes: every loadable plugin is loaded, every refusal goes to load_errors(), and
+     * the first negative status is returned, so one run reports every failure (§3.1). */
     int load_dir(const std::string& dir, const std::vector& hierarchy);
-    /* The same over several directories -- a $RADIANCE_HOME search path -- as one set: the
-     * hierarchy orders plugins across all of them, and a file an earlier directory already holds
-     * by the same name is shadowed, not loaded. */
+    /* The same over several directories (a $RADIANCE_HOME search path) as one set: the hierarchy
+     * orders plugins across all of them, and a file name an earlier directory holds shadows later
+     * ones. */
     int load_dirs(const std::vector& dirs, const std::vector& hierarchy);
 
-    /* One plugin at a known hierarchy position. rad-info and rad-kbench load a single .so; the
-     * engine goes through load_dir. 1, and nothing registered, when the plugin declines this
-     * machine (its rad_plugin_open answers RAD_E_UNSUPPORTED). */
+    /* One plugin at a known hierarchy position (rad-info, rad-kbench); the engine uses load_dir.
+     * Returns 1, with nothing registered, when rad_plugin_open answers RAD_E_UNSUPPORTED. */
     int load_plugin(const std::string& path, int order);
 
-    /* Every registered kernel row's op must have a schema SOMEWHERE in the loaded set -- an
-     * override plugin may legitimately ship kernels for an op whose schema the plugin below it
-     * declared, and that plugin loads later, so the check can only run once the set is complete.
-     * load_dir calls this; a caller assembling a set by hand calls it when it is done. */
+    /* Every kernel row's op must have a schema somewhere in the loaded set. An override plugin
+     * may ship kernels for an op whose schema a later-loading plugin declares, so this runs once
+     * the set is complete: load_dir calls it, a caller assembling a set by hand calls it last. */
     int check_complete();
 
-    /* The device a kernel library's device code is checked against when it loads: the first card
-     * the caller will run on. 0 unless the caller says otherwise -- the engine says so before it
-     * loads anything, once it has chosen its cards. */
+    /* The device a kernel library's device code is checked against at load: the first card the
+     * caller will run on. Default 0; the engine sets it after choosing its cards, before loading. */
     void set_code_device(int device) { code_device_ = device; }
 
-    /* THE ENGINE ABOUT TO SERVE ON THE HOST BACKEND SAYS SO: no card is visible, and no GPU code
-     * object runs in this process at all. A kernel library that brought device code then has its
-     * device rows left out of selection at load, its host rows staying, so every op takes its host
-     * kernel. Only the engine says this. A tool that selects without serving -- rad-convert's
-     * recipe check, rad-kbench's tables, a test of a library's constraints -- sees every row, as
-     * it would on the machine the model is served on. */
+    /* Set by the engine when serving on the host backend, where no GPU code object runs: device
+     * rows are left out at load and every op takes its host kernel. Only the engine sets it; tools
+     * that select without serving (rad-convert's recipe check, rad-kbench, constraint tests) see
+     * every row, as on the serving machine. */
     void set_no_device_code(bool v) { no_device_code_ = v; }
-    /* WHAT THE ENGINE MEASURED ABOUT THE RANKS' DEVICES, for the constraints on "device." keys
-     * (rad_types.h). Set before the first selection, by whoever chose the devices; a registry
-     * nobody told anything has no facts, and a kernel constrained on one is not selected. */
+    /* Measured facts about the ranks' devices, for constraints on "device." keys (rad_types.h).
+     * Set before the first selection by whoever chose the devices; without a fact, a kernel
+     * constrained on it is not selected. */
     void set_device_fact(std::string_view key, long long v) { device_facts_.set_i(key, v); }
-    const Geometry& device_facts() const { return device_facts_; }
 
     void close();                       /* fini instances, close hooks, dlclose, forget everything */
 
@@ -202,9 +184,8 @@ public:
     const Plugin*                   plugin(std::string_view name) const;
     const std::vector& load_errors() const { return load_errors_; }
 
-    /* Every quantiser the loaded quantiser plugins offer, in load order. A name is unique across
-     * them -- two plugins naming one quantiser is refused at load -- so the lookup is the answer
-     * and not the first of several. Null when nothing offers it. */
+    /* Every quantiser the loaded quantiser plugins offer, in load order. Names are unique (a
+     * duplicate is refused at load); quantizer() is null when nothing offers the name. */
     struct QuantRow {
         const RadQuantizerInfo* info = nullptr;
         std::string             plugin;
@@ -222,25 +203,19 @@ public:
     const Plugin*      schema_owner(std::string_view op) const;
     std::vector op_names() const;      /* sorted; the vocabulary this set implements */
 
-    /* Check a declared parameter set against the op's schema. Without this, a typo and an
-     * unimplemented op are the same diagnostic; with it, a misspelled op fails declare with the
-     * near-miss named. Returns RAD_OK, RAD_E_NOSCHEMA (no such op) or RAD_E_SCHEMA, and fills
-     * `err` with a sentence an architecture-plugin author can act on. */
+    /* Check a declared parameter set against the op's schema; a misspelled op fails with the
+     * near-miss named. Returns RAD_OK, RAD_E_NOSCHEMA (no such op) or RAD_E_SCHEMA, with `err`
+     * written for an architecture-plugin author. */
     int validate(std::string_view op, const RadParam* p, int n_p, std::string* err) const;
 
-    /* The closest known op name to `op` within a small edit distance, or "" if nothing is close.
-     * Public because the builder wants it in its own messages too. */
+    /* The closest known op name within a small edit distance, or "". Also used by the builder. */
     std::string near_miss(std::string_view op) const;
 
     /* ---------------------------------------------------------- the tuning cache (§15) */
-    /* Load $RADIANCE_HOME/tune/.tune, which rad-tune wrote. resolve() then moves a shape
-     * off each axis's declared default wherever there is a row for it. A missing file is not an
-     * error and leaves every shape on that default, which is what makes an untuned install fast
-     * rather than broken.
-     *
-     * THE CORE OWNS THE CACHE AND THE POLICY, so no plugin has to (tunecache.h; the choice is
-     * applied in select.cpp). Without this call every kernel runs its axis defaults whatever the
-     * file on disk says, which is slow rather than wrong -- but silently so.
+    /* Load $RADIANCE_HOME/tune/.tune (written by rad-tune). resolve() then moves a shape
+     * off each axis's declared default wherever the file has a row for it. A missing file is not
+     * an error; every shape stays on its default. The core owns the cache and the policy
+     * (tunecache.h, applied in select.cpp). Without this call the file is silently ignored.
      *
      * Returns the number of rows loaded, or a negative status. */
     int  load_tune(const std::string& radiance_home, const std::string& machine = std::string());
@@ -251,67 +226,66 @@ public:
      * plugin the highest declared priority wins, ties on declaration order. Null on a miss, with
      * the refusing constraint in `why->reason`. Every call is recorded in the selection table.
      *
-     * RAD_DERIVED parameters (rad_abi.h) are supplied by the KERNEL, so a constraint on one is
-     * SKIPPED here when the caller did not name it, and the winner's RAD_C_EQ value for the key
-     * comes back in `why->derived` -- resolve() is what writes it into the geometry. Without that
-     * skip, spec §7.2 is circular: the block manager reads the block size off the resolved
-     * attention kernel, but a kernel constrained to block_size == 16 can never be selected by a
-     * query that omits block_size, because a constraint whose key the geometry lacks does not
-     * hold. A caller that supplies the key anyway pins it and matches normally, which is how an
-     * operator forces a block size and gets a refusal by name instead of a substitution. */
-    /* `record` is false for a caller asking the selector a question the ENGINE did not ask -- the
-     * graph dump replays every band to recover the candidate list it threw away. The selection
-     * table is a record of what this deployment resolved, and a reporting tool inflating its
-     * counts would make it a record of itself. */
-    /* `accept`, when given, is asked of every row whose constraints hold, and an answer that is
-     * not empty takes the row out as a candidate with that answer as the reason. It is how a
-     * weight's encoding takes part in selection: a kernel whose layout hook does not read the
-     * encoding a weight operand has (RAD_E_DTYPE) is not a candidate, and the next one is chosen
-     * -- a bf16 lm_head goes to the bf16 GEMM instead of being refused by the fp8 one. */
+     * RAD_DERIVED parameters (rad_abi.h) are supplied by the kernel, so a constraint on one is
+     * skipped when the caller did not name it, and the winner's RAD_C_EQ value comes back in
+     * `why->derived` (resolve() writes it into the geometry). This breaks the §7.2 cycle: the
+     * block manager reads the block size off the resolved attention kernel, and a constraint whose
+     * key the geometry lacks does not hold. A caller that supplies the key pins it and matches
+     * normally, so a forced block size is refused by name rather than substituted.
+     *
+     * `record` is false for questions the engine did not ask (the graph dump replaying bands), so
+     * the selection table records only what this deployment resolved.
+     *
+     * `accept`, when given, is asked of every row whose constraints hold; a non-empty answer drops
+     * the row with that reason. This is how a weight's encoding takes part in selection: a kernel
+     * whose layout hook rejects the operand's encoding (RAD_E_DTYPE) is skipped and the next one
+     * chosen, so a bf16 lm_head goes to the bf16 GEMM rather than being refused by the fp8 one. */
     using RowFilter = std::function;
     const KernelRow* select(std::string_view op, const Geometry& g, int domain,
                             SelectionTrace* why = nullptr, bool record = true,
                             const RowFilter* accept = nullptr);
 
-    /* Selection plus the per-instance bookkeeping: the tuned axes, where they came from, and the frozen
-     * geometry -- the query plus whatever the winning kernel supplied for a derived key, so
-     * rad_kv_block_size() and RadArgs.p both see it. init() is NOT called here -- see
-     * init_instance(). */
+    /* The row select() would choose if `plugin` were the whole hierarchy: the same constraint
+     * match, derived-key skip, device facts and filter, restricted to one plugin and never
+     * recorded. rad-kbench asks each library this way so a replay runs the row the engine would
+     * run with that library alone. `why->derived` carries the winner's derived values. */
+    const KernelRow* select_in(std::string_view plugin, std::string_view op, const Geometry& g,
+                               int domain, const RowFilter* accept = nullptr,
+                               SelectionTrace* why = nullptr) const;
+
+    /* Selection plus per-instance bookkeeping: the tuned axes and their source, and the frozen
+     * geometry (the query plus the winner's derived keys, so rad_kv_block_size() and RadArgs.p
+     * both see them). Does not call init(); see init_instance(). */
     Resolved resolve(std::string_view op, const Geometry& g, int domain, SelectionTrace* why = nullptr,
                      const RowFilter* accept = nullptr);
 
     /* ---------------------------------------------------------- bucket tables (§2.2) */
-    /* Resolve a ranged parameter into a bucket table: one resolution per band, per domain, built
-     * at declare and indexed by the actual value at issue. The boundaries are the constraint
-     * values themselves. Each band is resolved AT ITS UPPER BOUND, which is the worst case in the
-     * band and therefore the only value that is safe to size and select on.
+    /* Resolve a ranged parameter into a bucket table: one resolution per band per domain, built
+     * at declare and indexed by the actual value at issue. Each band is resolved at its upper
+     * bound, the band's worst case and so the only value safe to size and select on.
      *
-     * `ranged_key` empty means the op has no ranged parameter: exactly one band is returned, whose
-     * hi is INT64_MAX so the issue path's band scan always finds it.
+     * An empty `ranged_key` returns one band with hi = INT64_MAX, which the issue path's band scan
+     * always finds.
      *
-     * Both domains are resolved wherever both exist, so the core can change execution site at
-     * runtime without re-resolving. Absence is asymmetric: a band with no DEVICE kernel is fatal
-     * and the caller reports it (this function does not abort -- declare always completes); a band
-     * with no HOST kernel is a warning naming the placement options it just removed. */
+     * Both domains are resolved so the execution site can change at runtime without re-resolving.
+     * A band with no device kernel is fatal; one with no host kernel only removes host-site
+     * execution. Neither aborts here: the caller reports misses once declare completes. */
     std::vector build_bands(std::string_view op, std::string_view ranged_key,
                                   int64_t lo, int64_t hi, const Geometry& base,
                                   const RowFilter* accept = nullptr);
 
     /* ---------------------------------------------------------- instances (§2.1) */
-    /* init() once per resolved instance -- one op, one band, one domain -- with the frozen
-     * geometry, the rank and the world size. libr4d's all-reduce needs its peer signal buffers and
-     * IPC handles established across ranks before the first call, and a kernel that JITs or loads
-     * a config table wants somewhere to do it that is not the hot path. A negative return aborts
-     * startup and the caller names the kernel. */
+    /* Calls init() once per resolved instance (one op, band and domain) with the frozen geometry,
+     * rank and world size, off the hot path: e.g. libr4d's all-reduce sets up peer signal buffers
+     * and IPC handles here. A negative return aborts startup; the caller names the kernel. */
     int  init_instance(Resolved& r, int rank, int world_size);
     void fini_instances();
     size_t n_instances() const;
 
     /* ---------------------------------------------------------- the selection table (§16) */
-    /* Every DISTINCT question the selector was asked, in the order first asked, with what it
-     * resolved to and, for a miss, the constraint that refused it. Repeats are folded and counted:
-     * a 64-layer model asks the same question 64 times, and "asked 64 times" says how much of the
-     * model resolved to that kernel. This is the record of why a fallback is running. */
+    /* Every distinct question the selector was asked, in first-asked order, with its answer and,
+     * for a miss, the refusing constraint. Repeats are folded into a count, which shows how much
+     * of the model resolved to each kernel. */
     std::string selection_table() const;
     size_t      n_selections() const;
     void        clear_selections();
@@ -334,8 +308,8 @@ private:
 
     struct SelectionRecord {
         std::string op, query, key, kernel, plugin, reason;
-        std::string derived;      /* "block_size:=16", rendered apart from the query because it
-                                   * was NOT part of the question the selector was asked */
+        std::string derived;      /* "block_size:=16", kept apart from the query because it was
+                                   * not part of the question asked */
         int         domain = 0;
         int         priority = 0;
         long long   count = 1;
@@ -362,14 +336,26 @@ private:
 
     mutable std::mutex           mu_;
     std::vector log_;
+    std::unordered_map log_at_;   /* SelectionRecord::key -> index in log_ */
     std::vector> instances_;
 };
 
 /* The value a kernel's own constraints place on one key, e.g. the paged block size the resolved
- * attention kernel is compiled for. §7.2: the block manager reads that off the resolved kernel and
- * sizes itself accordingly, because a core that picked its own block size would be a core that has
- * to be edited when a kernel changes. Returns false when the kernel says nothing about that key
- * with that operator -- which is not the same as a default, and the caller has to decide. */
+ * attention kernel is compiled for; the block manager sizes itself from it (§7.2). Returns false
+ * when the kernel has no constraint on that key with that operator; that is not a default, and
+ * the caller decides. */
 bool kernel_constraint(const KernelRow& r, std::string_view key, int c_op, long long* out);
 
+/* "an integer", "a string", ... for a RAD_P_* parameter kind, for diagnostics. */
+const char* param_kind_name(int kind);
+
+/* Why kernel `ki` cannot read weight operand `operand` (named `name`) stored as encoding `enc` with
+ * planes `sel` described by `planes` (dtype and extents; data unused), or "" when it can. A row
+ * whose layout hook answers RAD_E_DTYPE does not read the encoding, and a device row with no hook
+ * reads a single plane as stored. A hookless host row reads canonically. The builder's band
+ * resolution and rad-kbench's replay both ask this, so they choose the same row. */
+std::string weight_refusal(const RadKernelInfo* ki, const Geometry& g, int operand,
+                           const RadEncoding& enc, const int* sel, const RadTensor* planes,
+                           int n_sel, std::string_view name);
+
 }  /* namespace rad */
diff --git a/core/plugin/schema.cpp b/core/plugin/schema.cpp
index 105e9ba5..06e97100 100644
--- a/core/plugin/schema.cpp
+++ b/core/plugin/schema.cpp
@@ -1,10 +1,9 @@
 /* schema.cpp -- the op-schema registry and the check an architecture plugin's declared parameters
  * go through. spec.md §2.3.
  *
- * Without a schema, a typo and an unimplemented op are the same diagnostic: both are "nothing
- * resolved". With one, a misspelled op fails declare with the near-miss named, and that is the
- * whole reason this file exists -- new ops still need no core change, because the core learns the
- * vocabulary from the plugins rather than carrying a copy of it.
+ * Without a schema, a typo and an unimplemented op give the same "nothing resolved". With one, a
+ * misspelled op fails declare with the near-miss named. The core learns the op vocabulary from
+ * the plugins, so new ops need no core change.
  */
 #include "registry.h"
 
@@ -15,9 +14,7 @@ namespace rad {
 
 namespace {
 
-/* Levenshtein, bounded by the two lengths. The strings are op and parameter names -- a dozen
- * characters against a few hundred candidates, once per failed declare -- so the textbook O(nm)
- * table is already far below anything worth optimising. */
+/* Levenshtein, O(nm). Runs on short names, once per failed declare. */
 int edit_distance(std::string_view a, std::string_view b) {
     const size_t n = b.size();
     std::vector prev(n + 1), cur(n + 1);
@@ -33,10 +30,8 @@ int edit_distance(std::string_view a, std::string_view b) {
     return prev[n];
 }
 
-/* How wrong a name may be and still be worth suggesting. One edit for a short name, up to three
- * for a long one: "gemm_nt" against "gemm_nq" is a typo worth naming, and "rmsnorm" against
- * "softmax" is not -- a suggestion that is wrong is worse than none, because it sends the reader
- * to check something that was never the problem. */
+/* How far a name may be from a known one and still be suggested: one edit for a short name, up
+ * to three for a long one. A wrong suggestion is worse than none. */
 bool close_enough(std::string_view a, std::string_view b, int d) {
     const size_t len = std::max(a.size(), b.size());
     const int budget = len <= 4 ? 1 : (len <= 10 ? 2 : 3);
@@ -54,7 +49,9 @@ std::string suggest(std::string_view want, const std::vector& known
     return best;
 }
 
-const char* kind_name(int kind) {
+}  /* namespace */
+
+const char* param_kind_name(int kind) {
     switch (kind) {
         case RAD_P_INT:   return "an integer";
         case RAD_P_STR:   return "a string";
@@ -64,8 +61,6 @@ const char* kind_name(int kind) {
     }
 }
 
-}  /* namespace */
-
 const RadOpSchema* Registry::schema(std::string_view op) const {
     auto it = schemas_.find(std::string(op));
     return it == schemas_.end() ? nullptr : it->second.schema;
@@ -80,9 +75,8 @@ std::vector Registry::op_names() const {
     std::vector out;
     out.reserve(schemas_.size());
     for (const auto& kv : schemas_) out.push_back(kv.first);
-    /* Rows may implement an op nobody declared a schema for -- check_complete() calls that out,
-     * but until it is fixed the name should still show up in a near-miss search, or the author of
-     * the broken plugin gets told their own op does not exist. */
+    /* Include ops that have rows but no schema (check_complete() reports those), so a near-miss
+     * search can still name them. */
     for (const KernelRow& r : rows_)
         if (schemas_.find(r.info->op) == schemas_.end()) out.emplace_back(r.info->op);
     std::sort(out.begin(), out.end());
@@ -142,25 +136,24 @@ int Registry::validate(std::string_view op, const RadParam* p, int n_p, std::str
         const bool int_ok = (p[i].kind == RAD_P_INT || p[i].kind == RAD_P_RANGE);
         if (spec->type == RAD_P_INT && !int_ok) {
             *err = fmt("%s: parameter '%s' is %s, but the schema says it is an integer",
-                       name.c_str(), p[i].key, kind_name(p[i].kind));
+                       name.c_str(), p[i].key, param_kind_name(p[i].kind));
             return RAD_E_SCHEMA;
         }
         if (spec->type == RAD_P_STR && p[i].kind != RAD_P_STR) {
             *err = fmt("%s: parameter '%s' is %s, but the schema says it is a string",
-                       name.c_str(), p[i].key, kind_name(p[i].kind));
+                       name.c_str(), p[i].key, param_kind_name(p[i].kind));
             return RAD_E_SCHEMA;
         }
         if (spec->type == RAD_P_STR && !p[i].sval) {
             *err = fmt("%s: string parameter '%s' is null", name.c_str(), p[i].key);
             return RAD_E_SCHEMA;
         }
-        /* A float slot takes a float and nothing else. An integer in it would land in `ival` while
-         * the kernel reads `dval`, which is a zero eps rather than a diagnostic -- exactly the
-         * silent-garbage class the schema exists to catch. Constraints never match on a float
-         * (rad_types.h), so this check is the only thing standing between the two spellings. */
+        /* A float slot takes only a float: an integer would land in `ival` while the kernel
+         * reads `dval` (a silent zero eps). Constraints never match on a float (rad_types.h), so
+         * only this check catches it. */
         if (spec->type == RAD_P_F64 && p[i].kind != RAD_P_F64) {
             *err = fmt("%s: parameter '%s' is %s, but the schema says it is a float -- declare it "
-                       "with RAD_F64()", name.c_str(), p[i].key, kind_name(p[i].kind));
+                       "with RAD_F64()", name.c_str(), p[i].key, param_kind_name(p[i].kind));
             return RAD_E_SCHEMA;
         }
 
@@ -172,9 +165,8 @@ int Registry::validate(std::string_view op, const RadParam* p, int n_p, std::str
             }
             if (++n_ranged == 1) ranged_key = p[i].key;
             else {
-                /* At most one ranged parameter per op. That is what keeps the bucket-table index a
-                 * single integer at issue, and it is a promise the run phase depends on rather
-                 * than a limitation of the table (docs/OPS.md). */
+                /* At most one ranged parameter per op, so the bucket-table index at issue is a
+                 * single integer; the run phase depends on this (docs/OPS.md). */
                 *err = fmt("%s: '%s' and '%s' are both ranges; an op may have at most one ranged "
                            "parameter", name.c_str(), ranged_key.c_str(), p[i].key);
                 return RAD_E_SCHEMA;
@@ -183,10 +175,9 @@ int Registry::validate(std::string_view op, const RadParam* p, int n_p, std::str
     }
 
     for (int j = 0; j < s.n_params; ++j) {
-        /* RAD_REQUIRED and nothing else. RAD_DERIVED is supplied by the KERNEL, so demanding it
-         * from the caller would re-create the circularity it exists to break: the caller cannot
-         * know the block size until a kernel is resolved, and no kernel resolves until the block
-         * size is known (rad_abi.h, spec §7.2). A caller MAY still supply one, which pins it. */
+        /* Only RAD_REQUIRED. RAD_DERIVED is supplied by the kernel: the caller cannot know, e.g.,
+         * the block size before a kernel resolves (rad_abi.h, spec §7.2). A caller may still
+         * supply one, which pins it. */
         if (s.params[j].required != RAD_REQUIRED) continue;
         bool given = false;
         for (int i = 0; i < n_p && !given; ++i) given = (keys[(size_t)j] == p[i].key);
diff --git a/core/plugin/select.cpp b/core/plugin/select.cpp
index beb3388d..edda4446 100644
--- a/core/plugin/select.cpp
+++ b/core/plugin/select.cpp
@@ -1,11 +1,9 @@
 /* select.cpp -- the constraint selector, the selection table, and the per-instance init/fini.
  * spec.md §2.1 and §16.
  *
- * The selector answers one question: is there a kernel compiled for this geometry, in this domain,
- * in the highest plugin that has one. It is a NECESSARY condition and not a sufficient one --
- * strides, contiguity, alignment and buffer sizes are properties of a call rather than of a model
- * and stay in the entry point, which still rejects what it cannot run. libr4d's registry makes the
- * same point at length.
+ * The selector finds a kernel compiled for this geometry and domain in the highest plugin that has
+ * one. A match is necessary, not sufficient: strides, contiguity, alignment and buffer sizes are
+ * properties of a call, and the entry point still rejects what it cannot run.
  */
 #include "registry.h"
 
@@ -20,17 +18,16 @@ namespace rad {
 
 namespace {
 
-/* True when every constraint holds. Otherwise `why` names the FIRST one that did not and what it
- * wanted: "no kernel" on its own is not an answer anyone can act on, and the first failure is the
- * one a reader can fix -- listing all four of a row's unmet constraints buries it. */
+/* True when every constraint holds. Otherwise `why` names the first one that failed and what it
+ * wanted. */
 bool row_matches(const KernelRow& r, const Geometry& g, const Geometry& facts,
                  const std::vector& skip, std::string* why) {
     static const size_t kFact = std::strlen(RAD_DEVICE_FACT_PREFIX);
     for (int i = 0; i < r.info->n_constraints; ++i) {
         const RadConstraint& c = r.info->constraints[i];
-        /* A constraint on a RAD_DERIVED parameter the caller did not name is not a predicate on
-         * the question -- it IS the answer, read back afterwards. Matching on it would make the
-         * kernel unreachable by the only query anyone can ask (rad_abi.h, spec §7.2). */
+        /* A constraint on a RAD_DERIVED parameter the caller did not name is the answer, read back
+         * afterwards, not a predicate; matching on it would make the kernel unreachable
+         * (rad_abi.h, spec §7.2). */
         if (c.key && std::find(skip.begin(), skip.end(), c.key) != skip.end()) continue;
         /* A "device." key is a fact about the machine, read from what the engine measured. */
         if (c.key && std::strncmp(c.key, RAD_DEVICE_FACT_PREFIX, kFact) == 0) {
@@ -50,9 +47,30 @@ bool row_matches(const KernelRow& r, const Geometry& g, const Geometry& facts,
     return true;
 }
 
-/* The question, normalised so two spellings of the same one fold together in the table. The
- * geometry is displayed as asked, because a plugin author writes the parameters in the order that
- * reads best; only the fold key is sorted. */
+/* The op's RAD_DERIVED keys (from its schema) that the caller did not supply. A supplied one is
+ * pinned and matches like any other parameter. */
+std::vector unsupplied_derived(const RadOpSchema* sch, const Geometry& g) {
+    std::vector keys;
+    if (!sch) return keys;
+    for (int i = 0; i < sch->n_params; ++i) {
+        if (sch->params[i].required != RAD_DERIVED || !sch->params[i].key) continue;
+        if (!g.has(sch->params[i].key)) keys.emplace_back(sch->params[i].key);
+    }
+    return keys;
+}
+
+/* The scan select() and select_in() share: the first plugin in hierarchy order with a match
+ * supplies the row, the highest priority within it wins, ties to the row declared first. With
+ * `only` set, rows of every other plugin are passed over. Every row considered goes into
+ * `t.candidates` and each distinct refusal into `misses`. */
+const KernelRow* scan_rows(const std::vector* rows, const Geometry& g,
+                           int domain, const Geometry& facts,
+                           const std::vector& derived_keys,
+                           const Registry::RowFilter* accept, std::string_view only,
+                           SelectionTrace& t, std::vector* misses);
+
+/* The question, normalised so two spellings of it fold together in the table. Only the fold key
+ * is sorted; the geometry is displayed as asked. */
 std::string fold_key(std::string_view op, int domain, const Geometry& g) {
     const std::string q = g.str();     /* named: split_ws returns views into it */
     std::vector kv;
@@ -86,67 +104,18 @@ const KernelRow* Registry::select(std::string_view op, const Geometry& g, int do
     t.query  = g.str();
     t.domain = domain;
 
-    /* The derived keys of this op that the caller did NOT supply. Derivedness is a property of the
-     * op's schema, so it is known here and nowhere else; a caller that supplied one anyway has
-     * pinned it, and it drops out of this list and matches like any other parameter. */
-    std::vector derived_keys;
-    if (const RadOpSchema* sch = schema(op)) {
-        for (int i = 0; i < sch->n_params; ++i) {
-            if (sch->params[i].required != RAD_DERIVED || !sch->params[i].key) continue;
-            if (!g.has(sch->params[i].key)) derived_keys.emplace_back(sch->params[i].key);
-        }
-    }
-
+    const std::vector derived_keys = unsupplied_derived(schema(op), g);
     const std::vector* rows = rows_for(op);
-    const KernelRow* best = nullptr;
     std::vector misses;
-
-    if (rows) {
-        bool in_group = false;
-        int  cur_order = 0;
-        for (const KernelRow* r : *rows) {
-            /* A kernel in the other domain answers a different question. It is not a candidate and
-             * not a refusal -- but the fact that it exists is worth carrying, because "there is a
-             * device kernel and no host one" is the sentence the placement planner needs (§5.1). */
-            if (r->info->domain != domain) { t.other_domain_has_rows = true; continue; }
-
-            if (!in_group || r->plugin_order != cur_order) {
-                /* THE HIERARCHY IS ABSOLUTE. The first plugin with any matching kernel supplies
-                 * it; the moment we would step down to the next plugin with a winner in hand, we
-                 * stop. A lower-priority plugin never outbids a higher one no matter how
-                 * specialised its kernel -- that is what makes a user override an override. */
-                if (best) break;
-                cur_order = r->plugin_order;
-                in_group  = true;
-            }
-
-            std::string whynot;
-            bool ok = row_matches(*r, g, device_facts_, derived_keys, &whynot);
-            if (ok && accept && *accept) {
-                whynot = (*accept)(*r, g);
-                ok = whynot.empty();
-            }
-            if (ok) {
-                t.candidates.push_back({ r->plugin, r->info->name, r->info->priority, true, "ok" });
-                /* SPECIFICITY IS DECLARED, NOT DERIVED: the highest priority wins, and a tie goes
-                 * to the row declared first. Counting matched constraints would get it backwards. */
-                if (!best || r->info->priority > best->info->priority) best = r;
-            } else {
-                t.candidates.push_back({ r->plugin, r->info->name, r->info->priority, false, whynot });
-                if (std::find(misses.begin(), misses.end(), whynot) == misses.end())
-                    misses.push_back(whynot);
-            }
-        }
-    }
+    const KernelRow* best = scan_rows(rows, g, domain, device_facts_, derived_keys, accept, {},
+                                      t, &misses);
 
     if (best) {
         t.kernel   = best->info->name;
         t.plugin   = best->plugin;
         t.priority = best->info->priority;
-        /* The answer to the question that could not be asked: whatever the winner's RAD_C_EQ says
-         * about each skipped derived key. A kernel with no EQ on one -- ref's `block_size >= 1`,
-         * which admits every value -- leaves it UNKNOWN rather than zero, because "any" is not a
-         * number and the caller has to decide rather than be handed a plausible one. */
+        /* Each skipped derived key takes the winner's RAD_C_EQ value. A kernel with no EQ on it
+         * (e.g. ref's `block_size >= 1`) leaves it unknown rather than zero; the caller decides. */
         for (const std::string& key : derived_keys) {
             SelectionTrace::DerivedParam d;
             d.key   = key;
@@ -167,9 +136,111 @@ const KernelRow* Registry::select(std::string_view op, const Geometry& g, int do
     return best;
 }
 
+const KernelRow* Registry::select_in(std::string_view plugin, std::string_view op,
+                                     const Geometry& g, int domain, const RowFilter* accept,
+                                     SelectionTrace* why) const {
+    SelectionTrace local;
+    SelectionTrace& t = why ? *why : local;
+    t = SelectionTrace{};
+    t.op     = std::string(op);
+    t.query  = g.str();
+    t.domain = domain;
+    if (plugin.empty()) {
+        t.reason = "no plugin named";
+        return nullptr;
+    }
+    const std::vector derived_keys = unsupplied_derived(schema(op), g);
+    std::vector misses;
+    const KernelRow* best = scan_rows(rows_for(op), g, domain, device_facts_, derived_keys,
+                                      accept, plugin, t, &misses);
+    if (best) {
+        t.kernel   = best->info->name;
+        t.plugin   = best->plugin;
+        t.priority = best->info->priority;
+        for (const std::string& key : derived_keys) {
+            SelectionTrace::DerivedParam d;
+            d.key   = key;
+            d.known = kernel_constraint(*best, key, RAD_C_EQ, &d.value);
+            t.derived.push_back(std::move(d));
+        }
+    } else {
+        for (size_t i = 0; i < misses.size(); ++i) t.reason += (i ? "; " : "") + misses[i];
+        if (t.reason.empty())
+            t.reason = fmt("no %s kernel for op '%s' in %.*s", domain_name(domain), t.op.c_str(),
+                           (int)plugin.size(), plugin.data());
+    }
+    return best;
+}
+
+namespace {
+
+const KernelRow* scan_rows(const std::vector* rows, const Geometry& g,
+                           int domain, const Geometry& facts,
+                           const std::vector& derived_keys,
+                           const Registry::RowFilter* accept, std::string_view only,
+                           SelectionTrace& t, std::vector* misses) {
+    const KernelRow* best = nullptr;
+    if (!rows) return best;
+    bool in_group = false;
+    int  cur_order = 0;
+    for (const KernelRow* r : *rows) {
+        if (!only.empty() && r->plugin != only) continue;
+        /* Rows of the other domain are neither candidates nor refusals, but their existence is
+         * recorded for the placement planner (§5.1). */
+        if (r->info->domain != domain) { t.other_domain_has_rows = true; continue; }
+
+        if (!in_group || r->plugin_order != cur_order) {
+            /* The hierarchy is absolute: stop at the first plugin with a match, before a lower
+             * plugin can outbid it. */
+            if (best) break;
+            cur_order = r->plugin_order;
+            in_group  = true;
+        }
+
+        std::string whynot;
+        bool ok = row_matches(*r, g, facts, derived_keys, &whynot);
+        if (ok && accept && *accept) {
+            whynot = (*accept)(*r, g);
+            ok = whynot.empty();
+        }
+        if (ok) {
+            t.candidates.push_back({ r->plugin, r->info->name, r->info->priority, true, "ok" });
+            /* Highest declared priority wins; a tie goes to the row declared first. */
+            if (!best || r->info->priority > best->info->priority) best = r;
+        } else {
+            t.candidates.push_back({ r->plugin, r->info->name, r->info->priority, false, whynot });
+            if (std::find(misses->begin(), misses->end(), whynot) == misses->end())
+                misses->push_back(whynot);
+        }
+    }
+    return best;
+}
+
+}  /* namespace */
+
+std::string weight_refusal(const RadKernelInfo* ki, const Geometry& g, int operand,
+                           const RadEncoding& enc, const int* sel, const RadTensor* planes,
+                           int n_sel, std::string_view name) {
+    char es[256];
+    if (!ki->layout) {
+        if (ki->domain == RAD_DOMAIN_DEVICE && n_sel > 1) {
+            rad_enc_format(&enc, es, sizeof es);
+            return fmt("reads '%.*s' as stored, and it is %d planes of %s", (int)name.size(),
+                       name.data(), n_sel, es);
+        }
+        return std::string();
+    }
+    RadLayout L{};
+    if (ki->layout(g.params(), g.n_params(), operand, &enc, sel, planes, n_sel, &L) ==
+        RAD_E_DTYPE) {
+        rad_enc_format(&enc, es, sizeof es);
+        return fmt("does not read '%.*s' encoded %s", (int)name.size(), name.data(), es);
+    }
+    return std::string();
+}
+
 /* "gemm_nt:sk=8,mb=1;all_reduce:drain=3" -> the axes asked for `op`, or empty. Parsed on every
- * resolve rather than once: resolve runs a few thousand times at startup and never again, and a
- * parsed-once cache would need a mutex for a string that does not change. */
+ * resolve: resolve runs only at startup, and a parsed-once cache would need a mutex. */
 static std::string tune_pin_for(const char* spec, std::string_view op) {
     for (const char* p = spec; *p;) {
         const char* semi = std::strchr(p, ';');
@@ -183,7 +254,7 @@ static std::string tune_pin_for(const char* spec, std::string_view op) {
     return {};
 }
 
-/* For an error message, which is the whole value of refusing a bad pin rather than defaulting. */
+/* Every axis and its legal values, for the bad-pin error message. */
 static std::string tunable_names(const RadKernelInfo* k) {
     std::string s;
     for (int i = 0; i < k->n_tunables; ++i) {
@@ -198,15 +269,14 @@ static std::string tunable_names(const RadKernelInfo* k) {
     return s.empty() ? "(nothing tunable)" : s;
 }
 
-/* Is `v` one of the values this axis declares? A cached or pinned value outside the list is not
- * applied: the axis list is the kernel's statement of what it can run, and honouring a number it
- * never offered is how a stale cache launches a shape the kernel cannot serve. */
+/* Whether `v` is one of the axis's declared values. A cached or pinned value outside the list is
+ * never applied, so a stale cache cannot launch a shape the kernel cannot serve. */
 static bool axis_allows(const RadTunable& t, int64_t v) {
     for (int i = 0; i < t.n_values; ++i) if (t.values[i] == v) return true;
     return false;
 }
 
-/* Does this combination survive the kernel's own cross-axis test? Null means yes. */
+/* Whether the combination passes the kernel's cross-axis test; no test means yes. */
 static bool choice_valid(const RadKernelInfo* k, const Geometry& g,
                          const std::vector>& c) {
     if (!k->tune_valid) return true;
@@ -231,28 +301,22 @@ Resolved Registry::resolve(std::string_view op, const Geometry& g, int domain, S
     r.row = select(op, g, domain, &t, true, accept);
     if (!r.row) return r;
 
-    /* The frozen geometry is the query PLUS what the kernel supplied for it. Writing the derived
-     * value here rather than leaving it to the caller is what makes rad_kv_block_size() and
-     * RadArgs.p agree: the kernel is launched with the block size it was compiled for, and the
+    /* The frozen geometry is the query plus the kernel's derived values, so rad_kv_block_size()
+     * and RadArgs.p agree: the kernel launches with the block size it was compiled for, and the
      * block manager sizes itself from the same number. */
     r.geom = g;
     for (const SelectionTrace::DerivedParam& d : t.derived)
         if (d.known) r.geom.set_i(d.key, d.value);
-    /* THE TUNED AXES. A kernel declares a SPACE (RadTunable) and this is where a point in it is
-     * chosen: the cache when this shape has been measured on this machine, each axis's own
-     * `deflt` otherwise -- so an untuned install is fast rather than broken (spec §15). The core
-     * owns the cache and the policy, so no plugin has to.
+    /* Tuned axes. A kernel declares a space (RadTunable); the point chosen is the cached one when
+     * this shape was measured on this machine, else each axis's `deflt` (spec §15).
      *
-     * THE KEY IS THE FROZEN GEOMETRY BEFORE THE CHOICES GO IN, which is why `geom_key` is captured
-     * here and the choices are folded into `geom` afterwards. rad-tune keys its rows on the
-     * geometry the builder recorded; a key that included its own answer could never match. It also
-     * has to sit after the derived parameters are written in, or the two spellings of one shape
-     * would never meet.
+     * The cache key is the frozen geometry after the derived parameters and before the choices
+     * go in: rad-tune keys rows on the geometry the builder recorded, so a key that included its
+     * own answer could never match.
      *
-     * An axis the cached row does not mention keeps its default, and a key the row carries that
-     * this kernel no longer declares is ignored. That is exactly what tunecache.h promises: a
-     * library may add or widen an axis between builds without throwing away the measurements that
-     * still apply, and a cache is an optimisation that must never stop a server. */
+     * An axis the cached row does not mention keeps its default, and a row key the kernel no
+     * longer declares is ignored (tunecache.h), so a library may add or widen axes between builds
+     * and keep the measurements that still apply. */
     r.geom_key = TuneCache::canon_geometry(r.geom);
 
     const RadKernelInfo* ki = r.row->info;
@@ -278,17 +342,14 @@ Resolved Registry::resolve(std::string_view op, const Geometry& g, int domain, S
         }
 
         /* RADIANCE_TUNE=op:key=value[,key=value][;op:...] pins axes for every kernel serving that
-         * op. It is the debug half of the cache, and it exists because an axis is where a kernel's
-         * fences and launch geometry live: the all-reduce's drain depth and acquire ordering are
-         * axes, so questions like "is the missing acquire fence why this deployment is not
-         * reproducible" are answerable without a rebuild.
+         * op, for debugging without a rebuild (e.g. the all-reduce's drain depth and acquire
+         * ordering are axes).
          *
-         * An unknown key, or a value the axis does not offer, is a HARD ERROR rather than a silent
-         * default: a pin that did not take is worse than no pin, because the run looks like it
-         * tested something. A kernel with nothing tunable is not a failed pin, though -- the same
-         * op is served by libr4d on the device and by libref on the host, and libref declares no
-         * axes for anything, so refusing here would take the host band out over a device pin. */
-        if (const char* pin = std::getenv("RADIANCE_TUNE")) {
+         * An unknown key or a value the axis does not offer is a hard error: a pin that silently
+         * did not take is worse than none. A kernel with no axes is not a failed pin (libref
+         * declares none), so a device pin does not remove the host band. */
+        static const char* const pin = std::getenv("RADIANCE_TUNE");
+        if (pin) {
             const std::string want = tune_pin_for(pin, op);
             for (const auto& kv : TuneCache::parse_choice(want)) {
                 int idx = -1;
@@ -306,11 +367,9 @@ Resolved Registry::resolve(std::string_view op, const Geometry& g, int domain, S
             }
         }
 
-        /* A combination the kernel's own cross-axis test refuses is not launched. Falling back to
-         * every axis's default is the one answer that cannot be wrong here: the defaults are what
-         * an untuned install runs, so they are the kernel's own statement of what it can always
-         * do. A cache written for a different build, or a pin that is individually legal on each
-         * axis but not together, lands here. */
+        /* A combination the kernel's cross-axis test refuses (a cache from another build, or a
+         * pin legal per axis but not together) falls back to all defaults, which the kernel must
+         * always be able to run. */
         if (!choice_valid(ki, r.geom, chosen)) {
             std::vector> dflt;
             for (int i = 0; i < ki->n_tunables; ++i)
@@ -326,8 +385,8 @@ Resolved Registry::resolve(std::string_view op, const Geometry& g, int domain, S
         r.choice = TuneCache::canon_choice(chosen);
     }
 
-    /* scratch_bytes stays 0: the scratch hook takes a RadArgs, which needs the operand tensors,
-     * and those belong to the builder. It sizes the arena; this layer only says which kernel. */
+    /* scratch_bytes stays 0: the scratch hook needs a RadArgs with the operand tensors, which the
+     * builder owns and sizes the arena with. */
     return r;
 }
 
@@ -336,9 +395,9 @@ void Registry::record_(const std::string& op, int domain, const Geometry& g,
                        const SelectionTrace& t) {
     const std::string key = fold_key(op, domain, g);
     std::lock_guard lk(mu_);
-    for (SelectionRecord& s : log_) {
-        if (s.key == key) { ++s.count; return; }   /* same question, therefore the same answer */
-    }
+    /* The same question, therefore the same answer. */
+    const auto at = log_at_.try_emplace(key, log_.size());
+    if (!at.second) { ++log_[at.first->second].count; return; }
     SelectionRecord s;
     s.op       = op;
     s.domain   = domain;
@@ -348,10 +407,8 @@ void Registry::record_(const std::string& op, int domain, const Geometry& g,
     s.plugin   = t.plugin;
     s.priority = t.priority;
     s.reason   = t.reason;
-    /* Kept apart from the query. A derived key was not part of the question -- printing it inside
-     * the geometry would read as something the caller asked for, and the next reader would go
-     * looking for the code that passed it. ":=" is the kernel answering, "?" is a winner with no
-     * EQ on the key, which is a hole the caller has to fill and not a value. */
+    /* Derived keys are kept apart from the query because the caller did not ask for them. ":="
+     * is the kernel's answer; "?" is a winner with no EQ on the key, which the caller must fill. */
     for (const SelectionTrace::DerivedParam& d : t.derived) {
         if (!s.derived.empty()) s.derived += ' ';
         s.derived += d.known ? fmt("%s:=%lld", d.key.c_str(), d.value)
@@ -368,6 +425,7 @@ size_t Registry::n_selections() const {
 void Registry::clear_selections() {
     std::lock_guard lk(mu_);
     log_.clear();
+    log_at_.clear();
 }
 
 std::string Registry::selection_table() const {
@@ -400,11 +458,7 @@ std::string Registry::selection_table() const {
 }
 
 /* ------------------------------------------------------------------ instances */
-/* init() once per resolved instance -- one op, one band, one domain -- with the frozen geometry,
- * the rank and the world size. Some kernels have per-instance state that must be established once
- * and not per launch: libr4d's all-reduce needs its peer signal buffers and IPC handles set up
- * across ranks before the first call, and a kernel that JITs or loads a config table wants
- * somewhere to do it that is not the hot path. */
+/* See registry.h: init_instance. */
 int Registry::init_instance(Resolved& r, int rank, int world_size) {
     if (!r.row || !r.row->info) return RAD_E_INVAL;
     const RadKernelInfo* k = r.row->info;
@@ -413,16 +467,13 @@ int Registry::init_instance(Resolved& r, int rank, int world_size) {
     void* inst = nullptr;
     const int st = k->init(r.geom.params(), r.geom.n_params(), rank, world_size, &inst);
     if (st < 0) {
-        /* A negative init aborts startup, and the caller names the kernel -- which it can, because
-         * the message below already did. Continuing would mean launching a kernel whose one-time
-         * setup failed, and that is a fault three frames later instead of here. */
+        /* A negative init aborts startup rather than launching a kernel whose setup failed. */
         RAD_ERR("kernel '%s' (%s) failed to initialise for %s: %s", k->name, r.row->plugin.c_str(),
                 r.geom.str().c_str(), rad_strerror(st));
         return st;
     }
     r.instance = inst;
-    /* Registered even when the kernel returned null: fini pairs 1:1 with a successful init, and a
-     * kernel with global setup and no handle still needs its fini call. */
+    /* Registered even when the instance is null: fini pairs 1:1 with every successful init. */
     std::lock_guard lk(mu_);
     instances_.emplace_back(k, inst);
     return RAD_OK;
diff --git a/core/plugin/testplugin/CMakeLists.txt b/core/plugin/testplugin/CMakeLists.txt
index ff81027e..1681e0e4 100644
--- a/core/plugin/testplugin/CMakeLists.txt
+++ b/core/plugin/testplugin/CMakeLists.txt
@@ -1,10 +1,8 @@
-# Test plugins from one source, so that plugin_test has a hierarchy to load, a schema conflict to
-# refuse and a stale ABI to reject. They go under $RADIANCE_HOME/testkernels rather than kernels/,
-# because the engine scans kernels/ at startup and these rows implement nothing: a test plugin that
-# a real run could select is a fallback nobody knows about (spec.md §17).
-#
-# The two that must be refused live one directory down, so that loading testkernels/ is a clean
-# load and the refusals are asked for explicitly by path.
+# Test plugins built from one source: a hierarchy for plugin_test to load, a schema conflict to
+# refuse and a stale ABI to reject. They go under $RADIANCE_HOME/testkernels, not kernels/, because
+# the engine scans kernels/ at startup and must never select a row that implements nothing
+# (spec.md §17). The two that must be refused live in testkernels/bad, so loading testkernels/ is
+# clean and the refusals are requested by path.
 rad_add_plugin(radtest_base testkernels SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc)
 target_compile_definitions(radtest_base PRIVATE RADTEST_BASE=1)
 
@@ -17,22 +15,18 @@ target_compile_definitions(radtest_conflict PRIVATE RADTEST_CONFLICT=1)
 rad_add_plugin(radtest_badabi testkernels/bad SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc)
 target_compile_definitions(radtest_badabi PRIVATE RADTEST_BADABI=1)
 
-# Two architecture plugins claiming one architecture id, in their own directory so that loading it
-# is the whole test: the first is identified, the second is refused.
+# Two architecture plugins claiming one architecture id: the first is identified, the second
+# refused.
 rad_add_plugin(radtest_arch testarch SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc)
 target_compile_definitions(radtest_arch PRIVATE RADTEST_ARCH=1)
 
 rad_add_plugin(radtest_arch2 testarch SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc)
 target_compile_definitions(radtest_arch2 PRIVATE RADTEST_ARCH2=1)
 
-# Two more from the same source, in a directory of their own, so that a load with NO hierarchy has
-# something to be observed on. One of them declares itself a reference implementation.
-#
-# THE FILE NAMES ARE THE POINT. load_dir reads a directory in sorted order, so `..._a` (the
-# reference) is staged first; if the loader did not pin a reference library below every other
-# kernel plugin, it would keep that position and answer for every op, and the library that actually
-# serves the card would never be selected. Naming them the other way round would make the test pass
-# on alphabetical order alone. Its name is nobody's in particular: the rule is the declaration's.
+# Two plugins for a load with no hierarchy; one declares itself a reference implementation.
+# Do not rename: load_dir reads in sorted order, so the reference (`..._a`) is staged first, and
+# the test checks that the loader still ranks it below every other kernel plugin. The reverse
+# naming would pass on alphabetical order alone.
 rad_add_plugin(radtest_ord_a testkernels/order SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc)
 target_compile_definitions(radtest_ord_a PRIVATE RADTEST_BASE=1 RADTEST_REFERENCE=1
                                                  RADTEST_BASE_NAME=\"radtest_reference\")
@@ -40,12 +34,54 @@ target_compile_definitions(radtest_ord_a PRIVATE RADTEST_BASE=1 RADTEST_REFERENC
 rad_add_plugin(radtest_ord_b testkernels/order SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc)
 target_compile_definitions(radtest_ord_b PRIVATE RADTEST_BASE=1)
 
-# The KV tiers' transfer test. Unlike everything above it COMPUTES -- byte-row gather and scatter
-# registered in the device domain, running on the host backend's memory -- so it lives in a
-# directory of its own that only tests/mem_test.cpp loads, by path. It calls back into the device
-# API for stream order, which the test executable exports.
+# Rows for rules the base plugin does not reach (a non-interval ranged constraint, a cross-axis
+# tune test, a layout hook, a capacity parameter), in their own directory so loading testkernels/
+# is unchanged.
+rad_add_plugin(radtest_extra testkernels/extra SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc)
+target_compile_definitions(radtest_extra PRIVATE RADTEST_EXTRA=1)
+
+# Two tunable axes the loader must refuse, loaded by path, and a library that declines the machine.
+rad_add_plugin(radtest_badtune_default testkernels/bad
+               SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc)
+target_compile_definitions(radtest_badtune_default PRIVATE RADTEST_BADTUNE=1)
+rad_add_plugin(radtest_badtune_twice testkernels/bad SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc)
+target_compile_definitions(radtest_badtune_twice PRIVATE RADTEST_BADTUNE=2)
+rad_add_plugin(radtest_decline testkernels/decline SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc)
+target_compile_definitions(radtest_decline PRIVATE RADTEST_DECLINE=1)
+
+# One architecture family at three quantisations, for the (id, quantisation) selection key.
+foreach(q plain fp8 w4)
+  set(_rad_q "${q}")
+  if(q STREQUAL "plain")
+    set(_rad_q "")
+  endif()
+  rad_add_plugin(radtest_archq_${q} testarchq SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc)
+  target_compile_definitions(radtest_archq_${q} PRIVATE RADTEST_ARCHQ=1
+                             RADTEST_ARCHQ_NAME="radtest_archq_${q}"
+                             RADTEST_ARCHQ_QUANT="${_rad_q}")
+endforeach()
+
+# KV tier transfer test plugin. Unlike the others it computes (byte-row gather and scatter in the
+# device domain, on host backend memory), so only tests/mem_test.cpp loads it, by path. It calls
+# the device API for stream order, which the test executable exports.
 rad_add_plugin(radtest_rows testrows SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/tierrows.cc)
 
-# A quantiser with a scheme of its own, which only its decode hook reads: tests/quant_test.cpp
-# loads it by path to show a weight it wrote decodes through the core's decoder all the same.
+# A quantiser with its own scheme, read only by its decode hook. tests/quant_test.cpp loads it by
+# path to check that its weights decode through the core's decoder.
 rad_add_plugin(radtest_quant testquant SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testquant.cc)
+
+# Deliberately defective kernel libraries, one per defect, for tests/kbench_mutant_test.cpp: a
+# replay must fail each of them (or, for kbm_ok, pass it). One source, as above; KBM_MUTANT picks
+# the defect. Under testkernels/kbmut, loaded only by name.
+set(RAD_KBM_MUTANTS ok scale nan half overrun refuse shape argmax inwrite enc
+    CACHE INTERNAL "the kbmutant.cc builds, read by tests/CMakeLists.txt")
+set(i 0)
+foreach(m ${RAD_KBM_MUTANTS})
+  rad_add_plugin(kbm_${m} testkernels/kbmut SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/kbmutant.cc)
+  target_compile_definitions(kbm_${m} PRIVATE KBM_MUTANT=${i} KBM_NAME=\"kbm_${m}\")
+  math(EXPR i "${i} + 1")
+endforeach()
+
+# An architecture that declares a norm, a projection and an add from a synthetic container, so
+# tests/kbench_mutant_test.cpp can record a fixture on the host with libref alone.
+rad_add_plugin(radtest_kbarch testarch/kbench SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/kbarch.cc)
diff --git a/core/plugin/testplugin/kbarch.cc b/core/plugin/testplugin/kbarch.cc
new file mode 100644
index 00000000..9c476d9f
--- /dev/null
+++ b/core/plugin/testplugin/kbarch.cc
@@ -0,0 +1,93 @@
+/* kbarch.cc -- an architecture small enough to declare from a synthetic container, for
+ * tests/kbench_mutant_test.cpp: rad-kbench records a fixture from it on the host backend, from the
+ * container and again from the container's skeleton, with libref the only kernel library.
+ *
+ * It declares a norm with a gain and a projection, both read from the container, and an add. It
+ * never runs a step. Loaded only by path, from a test's own home.
+ */
+#include "rad_abi.h"
+#include "rad_builder.h"
+
+#include 
+
+namespace {
+
+RadParam p_int(const char* k, long long v) {
+    RadParam p{};
+    p.key = k;
+    p.kind = RAD_P_INT;
+    p.ival = v;
+    return p;
+}
+RadParam p_range(const char* k, long long lo, long long hi) {
+    RadParam p = p_int(k, lo);
+    p.kind = RAD_P_RANGE;
+    p.ihi = hi;
+    return p;
+}
+RadParam p_str(const char* k, const char* v) {
+    RadParam p{};
+    p.key = k;
+    p.kind = RAD_P_STR;
+    p.sval = v;
+    return p;
+}
+RadParam p_f64(const char* k, double v) {
+    RadParam p{};
+    p.key = k;
+    p.kind = RAD_P_F64;
+    p.dval = v;
+    return p;
+}
+
+}  /* namespace */
+
+extern "C" {
+
+static const RadPluginInfo kInfo = {
+    RAD_PLUGIN_ARCH, "radtest_kbarch", "0.1",
+    "declares a norm, a projection and an add from a synthetic container, for rad-kbench's tests",
+    "host",
+};
+
+uint32_t             rad_plugin_abi_version(void) { return RAD_ABI_VERSION; }
+const RadPluginInfo* rad_plugin_info(void) { return &kInfo; }
+const char*          rad_arch_id(void) { return "radtest.kbench"; }
+const char*          rad_arch_quant(void) { return ""; }
+
+int rad_arch_declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx) {
+    const int64_t n = m->n_embd, N = m->n_ff;
+    if (n <= 0 || N <= 0 || ctx->max_tok <= 0) return RAD_E_INVAL;
+    RadWeightDecl g{};
+    g.dtype = RAD_BF16;
+    g.rank = 1;
+    g.shape[0] = n;
+    g.access = RAD_ACCESS_PER_TOKEN;
+    g.shard = RAD_SHARD_NONE;
+    g.group.layer = -1;
+    g.group.expert = -1;
+    const rad_weight wn = rad_decl_weight(b, "norm.weight", &g);
+    RadWeightDecl w = g;
+    w.rank = 2;
+    w.shape[0] = N;
+    w.shape[1] = n;
+    const rad_weight wp = rad_decl_weight(b, "proj.weight", &w);
+    if (!wn || !wp) return RAD_E_INVAL;
+
+    const RadParam pn[] = { p_range("M", 1, ctx->max_tok), p_int("n", n), p_f64("eps", 1e-6),
+                            p_str("dtype", "bf16") };
+    const RadParam pg[] = { p_range("M", 1, ctx->max_tok), p_int("N", N), p_int("K", n),
+                            p_str("dtype", "bf16") };
+    const RadParam pa[] = { p_range("M", 1, ctx->max_tok), p_int("n", N), p_str("dtype", "bf16") };
+    if (!rad_decl_op(b, "rmsnorm", pn, 4, &wn, 1)) return RAD_E_INVAL;
+    if (!rad_decl_op(b, "gemm_nt", pg, 4, &wp, 1)) return RAD_E_INVAL;
+    if (!rad_decl_op(b, "add", pa, 3, nullptr, 0)) return RAD_E_INVAL;
+    return RAD_OK;
+}
+
+void rad_arch_step(struct RadCtx* c, const struct RadBatch* batch) {
+    (void)c;
+    (void)batch;
+}
+
+}  /* extern "C" */
diff --git a/core/plugin/testplugin/kbmutant.cc b/core/plugin/testplugin/kbmutant.cc
new file mode 100644
index 00000000..11777513
--- /dev/null
+++ b/core/plugin/testplugin/kbmutant.cc
@@ -0,0 +1,272 @@
+/* kbmutant.cc -- kernel libraries that are wrong on purpose, for tests/kbench_mutant_test.cpp.
+ *
+ * rad-kbench's verdicts are only worth something if a wrong kernel fails them. Each build of this
+ * file (-DKBM_MUTANT=..., see CMakeLists.txt) is one library implementing a few libref ops, with
+ * one defect: an output scaled past its tolerance, a NaN, an unwritten half, a write one byte past
+ * an output, a refusal of a geometry its constraints accept, a description of an output that
+ * disagrees with the reference's, an id off by one, a write into an input, and a preferred row that
+ * cannot read its weight's encoding. KBM_OK is the same library without a defect.
+ *
+ * It declares no schemas: libref's own fix the ops. Device-domain rows run on the host backend's
+ * memory, after draining the stream, so the guarded allocations and their margins are real; the
+ * gather and scatter device rows instead queue their work on the stream as copies, which the
+ * timing pass's gate can hold. Like
+ * tierrows.cc, a computing library registered in the device domain must never be found by a real
+ * run, so it lives under testkernels/ and is loaded only by name.
+ */
+#include "rad_abi.h"
+#include "rad_device.h"
+#include "rad_plugin.h"
+
+#include 
+#include 
+#include 
+
+#define NELEM(a) (int)(sizeof(a) / sizeof((a)[0]))
+
+#define KBM_OK      0
+#define KBM_SCALE   1
+#define KBM_NAN     2
+#define KBM_HALF    3
+#define KBM_OVERRUN 4
+#define KBM_REFUSE  5
+#define KBM_SHAPE   6
+#define KBM_ARGMAX  7
+#define KBM_INWRITE 8
+#define KBM_ENC     9
+
+#ifndef KBM_MUTANT
+#define KBM_MUTANT KBM_OK
+#endif
+#ifndef KBM_NAME
+#define KBM_NAME "kbm_ok"
+#endif
+
+namespace {
+
+int64_t numel(const RadTensor& t) { return rad_tensor_numel(&t); }
+
+/* A device row runs where a device launch would: after everything enqueued before it. */
+int order(RadStream s) { return s && rad_stream_sync(s) != RAD_OK ? RAD_E_DEVICE : RAD_OK; }
+
+/* y = a + b, with this library's defect. */
+int add_impl(const RadArgs* a, RadStream s, bool device) {
+    if (order(s) != RAD_OK) return RAD_E_DEVICE;
+    if (!a || a->n_t < 3 || !a->t[0].data || !a->t[1].data || !a->t[2].data) return RAD_E_INVAL;
+    if (KBM_MUTANT == KBM_REFUSE) return RAD_E_SHAPE;
+    const RadTensor &x = a->t[0], &y = a->t[1], &o = a->t[2];
+    const int64_t n = numel(o);
+    for (int64_t i = 0; i < n; ++i) {
+        if (KBM_MUTANT == KBM_HALF && i >= n / 2) break;
+        float v = rad_load_f32(x.data, x.dtype, i) + rad_load_f32(y.data, y.dtype, i);
+        /* Three times the bf16 tolerance (6e-3). */
+        if (KBM_MUTANT == KBM_SCALE) v *= 1.018f;
+        rad_store_f32(o.data, o.dtype, i, v);
+    }
+    if (KBM_MUTANT == KBM_NAN) rad_store_f32(o.data, o.dtype, n / 3, std::nanf(""));
+    if (KBM_MUTANT == KBM_OVERRUN && device)
+        ((uint8_t*)o.data)[rad_dtype_bytes(o.dtype, n)] = 0x5A;
+    if (KBM_MUTANT == KBM_INWRITE && !device)
+        rad_store_f32(x.data, x.dtype, 0, rad_load_f32(x.data, x.dtype, 0) + 1.0f);
+    return RAD_OK;
+}
+int add_host(const RadArgs* a, RadStream s)   { return add_impl(a, s, false); }
+int add_device(const RadArgs* a, RadStream s) { return add_impl(a, s, true); }
+
+/* y[i,:] = x[idx[i],:], byte rows. */
+int gather_rows(const RadArgs* a, RadStream s) {
+    if (order(s) != RAD_OK) return RAD_E_DEVICE;
+    if (!a || a->n_t < 3) return RAD_E_INVAL;
+    const RadTensor &x = a->t[0], &idx = a->t[1], &y = a->t[2];
+    if (x.rank != 2 || y.rank != 2 || idx.dtype != RAD_I32) return RAD_E_SHAPE;
+    const int64_t row = rad_dtype_bytes(y.dtype, y.shape[1]);
+    for (int64_t i = 0; i < y.shape[0]; ++i) {
+        const int32_t r = ((const int32_t*)idx.data)[i];
+        if (r < 0 || r >= x.shape[0]) return RAD_E_INVAL;
+        std::memcpy((uint8_t*)y.data + i * row, (const uint8_t*)x.data + r * row, (size_t)row);
+    }
+    return RAD_OK;
+}
+
+/* The same gather as one stream copy a row: a device row whose work is on its stream, which the
+ * timing pass can queue behind a gate (the rows above compute when called, after draining it). It
+ * reads `idx` when called, which only the host backend's device memory allows. */
+int gather_rows_device(const RadArgs* a, RadStream s) {
+    if (!a || a->n_t < 3 || !s) return RAD_E_INVAL;
+    const RadTensor &x = a->t[0], &idx = a->t[1], &y = a->t[2];
+    if (x.rank != 2 || y.rank != 2 || idx.dtype != RAD_I32) return RAD_E_SHAPE;
+    const int64_t row = rad_dtype_bytes(y.dtype, y.shape[1]);
+    for (int64_t i = 0; i < y.shape[0]; ++i) {
+        const int32_t r = ((const int32_t*)idx.data)[i];
+        if (r < 0 || r >= x.shape[0]) return RAD_E_INVAL;
+        if (rad_memcpy_async((uint8_t*)y.data + i * row, (const uint8_t*)x.data + r * row, row, s) !=
+            RAD_OK)
+            return RAD_E_DEVICE;
+    }
+    return RAD_OK;
+}
+
+/* x[idx[i],:] = v[i,:], in place: on the host, and as stream copies (see gather_rows_device). */
+int scatter_rows(const RadArgs* a, RadStream s) {
+    if (order(s) != RAD_OK) return RAD_E_DEVICE;
+    if (!a || a->n_t < 3) return RAD_E_INVAL;
+    const RadTensor &v = a->t[0], &idx = a->t[1], &x = a->t[2];
+    if (v.rank != 2 || x.rank != 2 || idx.dtype != RAD_I32) return RAD_E_SHAPE;
+    const int64_t row = rad_dtype_bytes(v.dtype, v.shape[1]);
+    for (int64_t i = 0; i < v.shape[0]; ++i) {
+        const int32_t r = ((const int32_t*)idx.data)[i];
+        if (r < 0 || r >= x.shape[0]) return RAD_E_INVAL;
+        uint8_t* dst = (uint8_t*)x.data + r * row;
+        const uint8_t* src = (const uint8_t*)v.data + i * row;
+        /* A destination already holding its value was written by an earlier launch, so `x` was
+         * not restored in between: refused, which is how kbench_mutant_test sees that the timing
+         * pass restores in-place operands. Drawn rows never match by chance. */
+        if (std::memcmp(dst, src, (size_t)row) == 0) return RAD_E_STATE;
+        std::memcpy(dst, src, (size_t)row);
+    }
+    return RAD_OK;
+}
+int scatter_rows_device(const RadArgs* a, RadStream s) {
+    if (!a || a->n_t < 3 || !s) return RAD_E_INVAL;
+    const RadTensor &v = a->t[0], &idx = a->t[1], &x = a->t[2];
+    if (v.rank != 2 || x.rank != 2 || idx.dtype != RAD_I32) return RAD_E_SHAPE;
+    const int64_t row = rad_dtype_bytes(v.dtype, v.shape[1]);
+    for (int64_t i = 0; i < v.shape[0]; ++i) {
+        const int32_t r = ((const int32_t*)idx.data)[i];
+        if (r < 0 || r >= x.shape[0]) return RAD_E_INVAL;
+        if (rad_memcpy_async((uint8_t*)x.data + r * row, (const uint8_t*)v.data + i * row, row, s) !=
+            RAD_OK)
+            return RAD_E_DEVICE;
+    }
+    return RAD_OK;
+}
+
+/* token[m] = the lower id of a row's largest logit. */
+int sample_argmax(const RadArgs* a, RadStream s) {
+    if (order(s) != RAD_OK) return RAD_E_DEVICE;
+    if (!a || a->n_t < 3) return RAD_E_INVAL;
+    const RadTensor &l = a->t[0], &tok = a->t[2];
+    if (l.rank != 2 || l.dtype != RAD_F32 || tok.dtype != RAD_I32) return RAD_E_DTYPE;
+    for (int64_t m = 0; m < l.shape[0]; ++m) {
+        const float* row = (const float*)l.data + m * l.shape[1];
+        int32_t best = 0;
+        for (int64_t v = 1; v < l.shape[1]; ++v) if (row[v] > row[best]) best = (int32_t)v;
+        if (KBM_MUTANT == KBM_ARGMAX) best += 1;
+        ((int32_t*)tok.data)[m] = best;
+    }
+    return RAD_OK;
+}
+
+/* y = x * rsqrt(mean(x^2) + eps) * (w + wadd), as libref computes it. */
+int rmsnorm(const RadArgs* a, RadStream s) {
+    if (order(s) != RAD_OK) return RAD_E_DEVICE;
+    if (!a || a->n_t < 3 || !a->t[1].data) return RAD_E_INVAL;
+    const RadTensor &x = a->t[0], &w = a->t[1], &y = a->t[2];
+    const int64_t n = rad_args_geti_or(a, "n", 0);
+    const double eps = rad_args_getf_or(a, "eps", 1e-6);
+    const double wadd = rad_args_getf_or(a, "wadd", 0.0);
+    if (n <= 0 || numel(x) % n) return RAD_E_SHAPE;
+    for (int64_t r = 0; r < numel(x) / n; ++r) {
+        float ss = 0.0f;
+        for (int64_t i = 0; i < n; ++i) {
+            const float v = rad_load_f32(x.data, x.dtype, r * n + i);
+            ss += v * v;
+        }
+        const float inv = 1.0f / std::sqrt(ss / (float)n + (float)eps);
+        for (int64_t i = 0; i < n; ++i)
+            rad_store_f32(y.data, y.dtype, r * n + i,
+                          rad_load_f32(x.data, x.dtype, r * n + i) * inv *
+                              (rad_load_f32(w.data, w.dtype, i) + (float)wadd));
+    }
+    return RAD_OK;
+}
+
+/* A preferred row that reads no encoding a recording carries: its layout hook refuses, so the
+ * engine passes it over, and its launch would fail the comparison if a replay chose it anyway. */
+[[maybe_unused]] int rmsnorm_wrong(const RadArgs* a, RadStream s) {
+    const int rc = rmsnorm(a, s);
+    if (rc == RAD_OK) rad_store_f32(a->t[2].data, a->t[2].dtype, 0, 1e6f);
+    return rc;
+}
+[[maybe_unused]] int refuse_layout(const RadParam*, int, int, const RadEncoding*, const int*,
+                                   const RadTensor*, int, RadLayout*) {
+    return RAD_E_DTYPE;
+}
+
+/* `add` described with an output one column wider than the reference describes it. */
+[[maybe_unused]] int add_shape_wide(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
+    if (operand < 0 || operand > 2) return RAD_E_SHAPE;
+    std::memset(out, 0, sizeof *out);
+    out->idx_const = -1;
+    out->dtype = RAD_BF16;
+    out->rank = 2;
+    out->shape[0] = rad_param_getdim(p, n_p, "M", 0);
+    out->shape[1] = rad_param_getdim(p, n_p, "n", 0) + (operand == 2 ? 1 : 0);
+    return RAD_OK;
+}
+
+const RadConstraint kSmall[] = { RAD_CLE("M", 4) };
+
+}  /* namespace */
+
+extern "C" {
+
+#if KBM_MUTANT == KBM_SHAPE
+#define KBM_ADD_SHAPE add_shape_wide
+#else
+#define KBM_ADD_SHAPE nullptr
+#endif
+
+static const RadKernelInfo kKernels[] = {
+    { .name = "kbm_add", .op = "add", .family = "elem", .computes = "y = a + b",
+      .shape = "any", .dtypes = "bf16", .domain = RAD_DOMAIN_HOST, .priority = 0,
+      .launch = add_host, .opd_shape = KBM_ADD_SHAPE },
+    { .name = "kbm_add_device", .op = "add", .family = "elem", .computes = "y = a + b",
+      .shape = "any", .dtypes = "bf16", .domain = RAD_DOMAIN_DEVICE, .priority = 0,
+      .launch = add_device, .opd_shape = KBM_ADD_SHAPE },
+    /* Reached only at M <= 4, which the recorded cases do not use: --record-rows' target. */
+    { .name = "kbm_add_small", .op = "add", .family = "elem", .computes = "y = a + b",
+      .shape = "M <= 4", .dtypes = "bf16", .domain = RAD_DOMAIN_HOST, .priority = 5,
+      .constraints = kSmall, .n_constraints = NELEM(kSmall), .launch = add_host,
+      .opd_shape = KBM_ADD_SHAPE },
+    { .name = "kbm_gather_rows", .op = "gather_rows", .family = "elem", .computes = "byte rows",
+      .shape = "any", .dtypes = "any", .domain = RAD_DOMAIN_HOST, .priority = 0,
+      .launch = gather_rows },
+    { .name = "kbm_gather_rows_device", .op = "gather_rows", .family = "elem",
+      .computes = "byte rows, one stream copy each", .shape = "any", .dtypes = "any",
+      .domain = RAD_DOMAIN_DEVICE, .priority = 0, .launch = gather_rows_device },
+    { .name = "kbm_scatter_rows", .op = "scatter_rows", .family = "elem", .computes = "byte rows",
+      .shape = "any", .dtypes = "any", .domain = RAD_DOMAIN_HOST, .priority = 0,
+      .launch = scatter_rows },
+    { .name = "kbm_scatter_rows_device", .op = "scatter_rows", .family = "elem",
+      .computes = "byte rows, one stream copy each", .shape = "any", .dtypes = "any",
+      .domain = RAD_DOMAIN_DEVICE, .priority = 0, .launch = scatter_rows_device },
+    { .name = "kbm_sample_argmax", .op = "sample_argmax", .family = "sample",
+      .computes = "greedy", .shape = "any", .dtypes = "f32", .domain = RAD_DOMAIN_HOST,
+      .priority = 0, .launch = sample_argmax },
+#if KBM_MUTANT == KBM_ENC
+    { .name = "kbm_rmsnorm_wide", .op = "rmsnorm", .family = "norm",
+      .computes = "reads a layout no recording carries", .shape = "any", .dtypes = "bf16",
+      .domain = RAD_DOMAIN_HOST, .priority = 10, .launch = rmsnorm_wrong,
+      .layout = refuse_layout },
+#endif
+    { .name = "kbm_rmsnorm", .op = "rmsnorm", .family = "norm", .computes = "rmsnorm",
+      .shape = "any", .dtypes = "bf16", .domain = RAD_DOMAIN_HOST, .priority = 0,
+      .launch = rmsnorm },
+};
+
+static const RadPluginInfo kInfo = {
+    RAD_PLUGIN_KERNEL, KBM_NAME, "0.1",
+    "a deliberately defective kernel library for rad-kbench's own tests", "host",
+};
+
+uint32_t             rad_plugin_abi_version(void) { return RAD_ABI_VERSION; }
+const RadPluginInfo* rad_plugin_info(void) { return &kInfo; }
+int                  rad_kernel_schema_count(void) { return 0; }
+const RadOpSchema*   rad_kernel_schema_at(int) { return nullptr; }
+int                  rad_kernel_count(void) { return NELEM(kKernels); }
+const RadKernelInfo* rad_kernel_at(int i) {
+    return (i < 0 || i >= NELEM(kKernels)) ? nullptr : &kKernels[i];
+}
+
+}  /* extern "C" */
diff --git a/core/plugin/testplugin/testplugin.cc b/core/plugin/testplugin/testplugin.cc
index 351e7eb3..08bb9ea8 100644
--- a/core/plugin/testplugin/testplugin.cc
+++ b/core/plugin/testplugin/testplugin.cc
@@ -7,9 +7,10 @@
  * M<=16, M<=64 and unconstrained -- which is spec.md §2.2's worked example, so the test can assert
  * the exact band table and the paragraph becomes a regression test.
  *
- * One source, six .so files, selected by -D: two kernel plugins that load, two that must be
- * refused, and two architecture plugins that claim one id between them. The rows are worth reading
- * side by side, and six near-copies of this file would drift.
+ * One source, several .so files, selected by -D: kernel plugins that load, kernel plugins that must
+ * be refused or that decline the machine, and architecture plugins that claim one id between them
+ * or one family at several quantisations. The rows are worth reading side by side, and near-copies
+ * of this file would drift.
  *
  * The extension is .cc, not .cpp, and that is load-bearing: core/CMakeLists.txt globs
  * every core/plugin .cpp file into the rad_core static library, and a plugin's exports
@@ -17,18 +18,20 @@
  * exclusion rule in a file this component does not own.
  */
 #include "rad_abi.h"
+#include "rad_planes.h"
 
 #include 
 #include 
 
-#if defined(RADTEST_ARCH) || defined(RADTEST_ARCH2)
+#if defined(RADTEST_ARCH) || defined(RADTEST_ARCH2) || defined(RADTEST_ARCHQ)
 #define RADTEST_IS_ARCH 1
 #include "rad_builder.h"
 #include "rad_runtime.h"
 #endif
 
 #if !defined(RADTEST_BASE) && !defined(RADTEST_OVER) && !defined(RADTEST_CONFLICT) && \
-    !defined(RADTEST_BADABI) && !defined(RADTEST_IS_ARCH)
+    !defined(RADTEST_BADABI) && !defined(RADTEST_IS_ARCH) && !defined(RADTEST_EXTRA) && \
+    !defined(RADTEST_BADTUNE) && !defined(RADTEST_DECLINE)
 #define RADTEST_BASE 1
 #endif
 
@@ -88,7 +91,15 @@ int radtest_init_calls(void) { return g_init_calls; }
 int radtest_fini_calls(void) { return g_fini_calls; }
 long long radtest_instance_m(void* inst) { return inst ? ((TestInstance*)inst)->m : -1; }
 
-int rad_plugin_open(void) { ++g_open_calls; return RAD_OK; }
+/* radtest_decline is a library for another machine: it declines this one at open. */
+int rad_plugin_open(void) {
+    ++g_open_calls;
+#if defined(RADTEST_DECLINE)
+    return RAD_E_UNSUPPORTED;
+#else
+    return RAD_OK;
+#endif
+}
 
 /* ------------------------------------------------------------------ operands */
 /* Roles matter to the core (a weight operand is resolved through a handle, an output feeds the
@@ -333,6 +344,177 @@ static const RadPluginInfo kInfo = {
 extern "C" int rad_plugin_reference(void) { return 1; }
 #endif
 
+/* ================================================================== radtest_extra */
+/* Rows for rules the base plugin's ops do not reach: a constraint on the ranged key that is not an
+ * interval, a tunable axis with a cross-axis test, a kernel that relayouts its weight, and a
+ * capacity parameter. In testkernels/extra, so loading testkernels/ alone is unchanged. */
+#elif defined(RADTEST_EXTRA)
+
+static const RadOperandSpec kOpdCap[] = {
+    { "x", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 },
+};
+static const RadParamSpec kPCap[] = {
+    { "M", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
+    { "cap", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_CAPACITY },
+    { "n", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
+};
+
+static const RadOpSchema kSchemas[] = {
+    { "t_div",  kPTie,  NELEM(kPTie),  kOpdNorm, NELEM(kOpdNorm),
+      "IN and DIV on the ranged key" },
+    { "t_tune", kPGemm, NELEM(kPGemm), kOpdGemm, NELEM(kOpdGemm),
+      "a tunable axis with a cross-axis test" },
+    { "t_lay",  kPGemm, NELEM(kPGemm), kOpdGemm, NELEM(kOpdGemm),
+      "a kernel that stores its weight in its own layout" },
+    { "t_join", kPGemm, NELEM(kPGemm), kOpdGemm, NELEM(kOpdGemm),
+      "a weight of several planes: a device kernel's own form, a host kernel's joined one" },
+    { "t_cap",  kPCap,  NELEM(kPCap),  kOpdCap,  NELEM(kOpdCap),
+      "a capacity a sizing declare may shrink" },
+};
+
+/* M in {8, 24}, and M divisible by 16 up to 64. */
+static const RadConstraint kCDivIn[]  = { RAD_CIN("M", "8 24") };
+static const RadConstraint kCDivM16[] = { RAD_CDIV("M", 16), RAD_CLE("M", 64) };
+
+/* bn = 128 only where the output has at least 128 columns. */
+static int t_tune_valid(const RadParam* p, int n_p, const RadParam* choice, int n_choice) {
+    long long n = 0, bn = 0;
+    for (int i = 0; i < n_p; ++i)
+        if (p[i].key && std::strcmp(p[i].key, "N") == 0) n = p[i].ival;
+    for (int i = 0; i < n_choice; ++i)
+        if (choice[i].key && std::strcmp(choice[i].key, "bn") == 0) bn = choice[i].ival;
+    return bn <= n ? 1 : 0;
+}
+
+/* Stores a bf16 weight, or fp8 codes with their scales, in a "tiled" form of its own, and reads no
+ * other encoding (plain fp8 among them). */
+static int t_lay_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
+                        const int* sel, const RadTensor* planes, int n_planes, RadLayout* out) {
+    (void)p; (void)n_p; (void)operand;
+    if (!enc || !sel || !planes || n_planes < 1 || !out) return RAD_E_INVAL;
+    const uint32_t codes = enc->plane[sel[0]].dtype;
+    const bool bf16 = n_planes == 1 && codes == RAD_BF16;
+    const bool fp8 = n_planes == 2 && codes == RAD_F8E4M3;
+    if (!bf16 && !fp8) return RAD_E_DTYPE;
+    out->tag = bf16 ? "tiled" : "tiled-fp8";
+    out->dtype = codes;
+    out->rank = 2;
+    out->shape[0] = planes[0].shape[0];
+    out->shape[1] = planes[0].shape[1];
+    out->align = 4096;
+    int64_t bytes = 0;
+    for (int i = 0; i < n_planes; ++i)
+        bytes += rad_dtype_bytes(planes[i].dtype, rad_tensor_numel(&planes[i]));
+    out->bytes = bytes > 0 ? bytes : 1;
+    return RAD_OK;
+}
+
+/* The joined form every host library shares (abi/rad_planes.h). */
+static int t_join_host_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
+                              const int* sel, const RadTensor* planes, int n_planes,
+                              RadLayout* out) {
+    (void)p; (void)n_p; (void)operand;
+    return rad_planes_layout(enc, sel, planes, n_planes, out);
+}
+
+static const RadConstraint kCLayTiled[] = { RAD_CLE("M", 16) };
+static const RadConstraint kCLayPlain[] = { RAD_CLE("M", 4096) };
+
+static const RadKernelInfo kKernels[] = {
+    { .name = "t_div_in", .op = "t_div", .family = "norm",
+      .computes = "nothing; a registry row", .shape = "M in {8, 24}", .dtypes = "any",
+      .domain = RAD_DOMAIN_DEVICE, .priority = 40,
+      .constraints = kCDivIn, .n_constraints = NELEM(kCDivIn), .launch = t_launch },
+    { .name = "t_div_m16", .op = "t_div", .family = "norm",
+      .computes = "nothing; a registry row", .shape = "M <= 64, M divisible by 16",
+      .dtypes = "any", .domain = RAD_DOMAIN_DEVICE, .priority = 30,
+      .constraints = kCDivM16, .n_constraints = NELEM(kCDivM16), .launch = t_launch },
+    { .name = "t_div_any", .op = "t_div", .family = "norm",
+      .computes = "nothing; a registry row", .shape = "any", .dtypes = "any",
+      .domain = RAD_DOMAIN_DEVICE, .priority = 10, .launch = t_launch },
+
+    { .name = "t_tune_picky", .op = "t_tune", .family = "gemm",
+      .computes = "nothing; a registry row", .shape = "any", .dtypes = "any",
+      .domain = RAD_DOMAIN_DEVICE, .priority = 10,
+      .tunables = kTGemmM64, .n_tunables = NELEM(kTGemmM64), .tune_valid = t_tune_valid,
+      .launch = t_launch },
+
+    { .name = "t_lay_tiled", .op = "t_lay", .family = "gemm",
+      .computes = "nothing; a registry row", .shape = "M <= 16", .dtypes = "bf16 / fp8 + scale",
+      .domain = RAD_DOMAIN_DEVICE, .priority = 20,
+      .constraints = kCLayTiled, .n_constraints = NELEM(kCLayTiled),
+      .launch = t_launch, .layout = t_lay_layout },
+    { .name = "t_lay_plain", .op = "t_lay", .family = "gemm",
+      .computes = "nothing; a registry row", .shape = "M <= 4096", .dtypes = "as stored",
+      .domain = RAD_DOMAIN_DEVICE, .priority = 10,
+      .constraints = kCLayPlain, .n_constraints = NELEM(kCLayPlain), .launch = t_launch },
+    { .name = "t_lay_host", .op = "t_lay", .family = "gemm",
+      .computes = "nothing; a registry row", .shape = "any", .dtypes = "as stored",
+      .domain = RAD_DOMAIN_HOST, .priority = 10, .launch = t_launch },
+
+    { .name = "t_join_tiled", .op = "t_join", .family = "gemm",
+      .computes = "nothing; a registry row", .shape = "M <= 16", .dtypes = "fp8 + scale",
+      .domain = RAD_DOMAIN_DEVICE, .priority = 20,
+      .constraints = kCLayTiled, .n_constraints = NELEM(kCLayTiled),
+      .launch = t_launch, .layout = t_lay_layout },
+    { .name = "t_join_host", .op = "t_join", .family = "gemm",
+      .computes = "nothing; a registry row", .shape = "any", .dtypes = "planes joined",
+      .domain = RAD_DOMAIN_HOST, .priority = 10, .launch = t_launch,
+      .layout = t_join_host_layout },
+
+    { .name = "t_cap_any", .op = "t_cap", .family = "norm",
+      .computes = "nothing; a registry row", .shape = "any", .dtypes = "any",
+      .domain = RAD_DOMAIN_DEVICE, .priority = 10, .launch = t_launch },
+};
+
+static const RadPluginInfo kInfo = {
+    RAD_PLUGIN_KERNEL, "radtest_extra", "0.1",
+    "non-interval ranged constraints, a cross-axis tune test, layout hooks, a capacity", "host",
+};
+
+/* ================================================================== radtest_badtune_* */
+/* A tunable axis the loader must refuse: a default that is not one of its values
+ * (RADTEST_BADTUNE=1), or one axis declared twice (2). */
+#elif defined(RADTEST_BADTUNE)
+
+static const RadOpSchema kSchemas[] = {
+    { "t_gemm", kPGemm, NELEM(kPGemm), kOpdGemm, NELEM(kOpdGemm), "never registered" },
+};
+#if RADTEST_BADTUNE == 1
+static const RadTunable kTBad[] = {
+    { "bn", kBnValues, NELEM(kBnValues), 96, "a default the axis does not offer" },
+};
+#else
+static const RadTunable kTBad[] = {
+    { "bn", kBnValues, NELEM(kBnValues), 64, "the axis" },
+    { "bn", kBnValues, NELEM(kBnValues), 128, "the same axis again" },
+};
+#endif
+static const RadKernelInfo kKernels[] = {
+    { .name = "t_badtune_gemm", .op = "t_gemm", .family = "gemm",
+      .computes = "nothing; a registry row", .shape = "any", .dtypes = "any",
+      .domain = RAD_DOMAIN_DEVICE, .priority = 10,
+      .tunables = kTBad, .n_tunables = NELEM(kTBad), .launch = t_launch },
+};
+static const RadPluginInfo kInfo = {
+    RAD_PLUGIN_KERNEL, "radtest_badtune", "0.1", "a tunable axis the loader refuses", "host",
+};
+
+/* ================================================================== radtest_decline */
+#elif defined(RADTEST_DECLINE)
+
+static const RadOpSchema kSchemas[] = {
+    { "t_gemm", kPGemm, NELEM(kPGemm), kOpdGemm, NELEM(kOpdGemm), "never registered" },
+};
+static const RadKernelInfo kKernels[] = {
+    { .name = "t_decline_gemm", .op = "t_gemm", .family = "gemm",
+      .computes = "nothing; a registry row", .shape = "any", .dtypes = "any",
+      .domain = RAD_DOMAIN_DEVICE, .priority = 1000, .launch = t_launch },
+};
+static const RadPluginInfo kInfo = {
+    RAD_PLUGIN_KERNEL, "radtest_decline", "0.1", "declines this machine at open", "host",
+};
+
 /* ================================================================== radtest_over */
 #elif defined(RADTEST_OVER)
 
@@ -384,14 +566,26 @@ static const RadPluginInfo kInfo = {
  * how the loader learns that an arch plugin is not a kernel plugin with missing exports. */
 #elif defined(RADTEST_IS_ARCH)
 
-static const RadPluginInfo kInfo = {
-    RAD_PLUGIN_ARCH,
-#if defined(RADTEST_ARCH)
-    "radtest_arch",
+/* RADTEST_ARCHQ plugins are one family at several quantisations, each named, with its
+ * quantisation, by -D. */
+#if defined(RADTEST_ARCHQ)
+#define RADTEST_ARCH_NAME RADTEST_ARCHQ_NAME
+#define RADTEST_ARCH_ID "radtest.q"
+#define RADTEST_ARCH_QUANT RADTEST_ARCHQ_QUANT
+#elif defined(RADTEST_ARCH)
+#define RADTEST_ARCH_NAME "radtest_arch"
 #else
-    "radtest_arch2",
+#define RADTEST_ARCH_NAME "radtest_arch2"
 #endif
-    "0.1", "claims architecture id 'radtest.v1'", "host",
+#ifndef RADTEST_ARCH_ID
+#define RADTEST_ARCH_ID "radtest.v1"
+#endif
+#ifndef RADTEST_ARCH_QUANT
+#define RADTEST_ARCH_QUANT ""
+#endif
+
+static const RadPluginInfo kInfo = {
+    RAD_PLUGIN_ARCH, RADTEST_ARCH_NAME, "0.1", "claims an architecture id", "host",
 };
 
 /* ================================================================== radtest_badabi */
@@ -426,10 +620,9 @@ uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; }
 const RadPluginInfo* rad_plugin_info(void) { return &kInfo; }
 
 #if defined(RADTEST_IS_ARCH)
-const char* rad_arch_id(void) { return "radtest.v1"; }
-/* The other half of the selection key (spec §2.4). This plugin serves an unquantised container,
- * which is what "" means. */
-const char* rad_arch_quant(void) { return ""; }
+const char* rad_arch_id(void) { return RADTEST_ARCH_ID; }
+/* The other half of the selection key (spec §2.4); "" is an unquantised container. */
+const char* rad_arch_quant(void) { return RADTEST_ARCH_QUANT; }
 /* The core loads and identifies architecture plugins; the build component drives them. Neither
  * hook is called by anything this test exercises, and declare refuses rather than pretending. */
 int  rad_arch_declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
diff --git a/core/rad_core.h b/core/rad_core.h
index 7642efb1..c88036f7 100644
--- a/core/rad_core.h
+++ b/core/rad_core.h
@@ -1,14 +1,12 @@
-/* rad_core.h -- the data model shared BETWEEN core components. Each component owns its own
- * header for its own methods; this file owns the structs that cross a component boundary, so
- * two components cannot disagree about what a weight or a band or a request is.
+/* rad_core.h -- the data model shared between core components. Each component owns a header for
+ * its own methods; this file owns the structs that cross a component boundary (weights, bands,
+ * requests, config), so components cannot disagree about them.
  *
- * If you need to add a field here, add it. If you need to CHANGE one, say so loudly -- somebody
- * else is reading it.
+ * Adding a field is fine. Changing one affects other readers; flag it in review.
  */
 #pragma once
 #include "rad_internal.h"
 
-#include 
 #include 
 #include 
 #include 
@@ -41,21 +39,19 @@ class Engine;
 
 /* ================================================================== plugin layer */
 
-/* One kernel row plus where it came from. The hierarchy is absolute: the first plugin with any
- * matching kernel supplies it, and a lower-priority plugin never outbids a higher one no matter
- * how specialised its kernel (spec §2.1). `plugin_order` is that hierarchy position. */
+/* One kernel row plus its origin. The hierarchy is absolute: the first plugin with any matching
+ * kernel supplies it, and a lower-priority plugin never outbids a higher one, however specialised
+ * (spec §2.1). `plugin_order` is the hierarchy position. */
 struct KernelRow {
     const RadKernelInfo* info = nullptr;
     std::string          plugin;
     int                  plugin_order = 0;   /* 0 is highest priority */
     int                  index = 0;          /* declaration order within the plugin */
-    /* The plugin's rad_kernel_concurrent answer for this row: its launches touch nothing but
-     * their operands and their scratch, so one may run beside another that shares none of those
-     * bytes. False when the plugin does not say. */
+    /* rad_kernel_concurrent: launches touch only their operands and scratch, so one may run beside
+     * another that shares none of those bytes. False when the plugin does not say. */
     bool                 concurrent = false;
-    /* The plugin's rad_kernel_collective answer for this row: its launches exchange data with
-     * the other ranks' cards, and -- `releases_link` -- end the engine's hold on the link
-     * themselves, through `link_gate`. False when the plugin does not say. */
+    /* rad_kernel_collective: launches exchange data with other ranks' cards; `releases_link` means
+     * they end the engine's hold on the link themselves, through `link_gate`. False when unsaid. */
     bool                 collective = false;
     bool                 releases_link = false;
     /* The row's plugin declared itself a reference implementation (RadPluginReferenceFn). */
@@ -66,91 +62,86 @@ struct KernelRow {
 struct Resolved {
     const KernelRow* row = nullptr;
     void*            instance = nullptr;
-    /* The frozen geometry, INCLUDING the tuned axes: once selection has picked a point in the
-     * kernel's RadTunable space it is set here, so RadArgs.p carries it and the kernel reads `sk`
-     * with the same rad_args_geti() it reads `M` with. There is no variant index anywhere. */
+    /* The frozen geometry, including the tuned axes, so RadArgs.p carries them and the kernel
+     * reads `sk` with rad_args_geti() like `M`. There is no variant index. */
     Geometry         geom;
     int64_t          scratch_bytes = 0;
-    /* The geometry WITHOUT the tuned axes, in tunecache.h's canonical spelling. The cache keys on
-     * it, so it has to be captured BEFORE the choices are folded into `geom` -- otherwise the key
-     * would depend on the answer it is used to look up. */
+    /* The geometry without the tuned axes, in tunecache.h's canonical spelling. It is the cache
+     * key, so it is captured before the choices are folded into `geom`. */
     std::string      geom_key;
-    /* The chosen axes, `key=value` comma separated and sorted -- the cache's `choice` column --
-     * and where they came from: "axis defaults", "tuned " or "RADIANCE_TUNE" (spec §15).
-     * Both empty for a kernel with nothing to tune. */
+    /* The chosen axes as sorted `key=value,...` (the cache's `choice` column), and their source:
+     * "axis defaults", "tuned " or "RADIANCE_TUNE" (spec §15). Both empty for a kernel
+     * with nothing to tune. */
     std::string      choice;
     std::string      tune_source;
+    /* The row's DIV on the op's ranged parameter (the least common multiple of several), 0 when
+     * it has none. Selection checked it at the band's upper bound only, so the issue path refuses
+     * a value in the band it does not divide (Registry::build_bands). */
+    int64_t          ranged_div = 0;
 
     explicit operator bool() const { return row != nullptr; }
 };
 
-/* One row of a bucket table: a band of the ranged parameter, resolved per domain.
- * The bucket boundaries are the constraint values themselves -- take the union of the LE, GE and
- * EQ values that candidate kernels place on the ranged parameter, and those are the bands. No
- * policy was chosen by anyone (spec §2.2). */
+/* One row of a bucket table: a band of the ranged parameter, resolved per domain. The band
+ * boundaries are the union of the LE, GE and EQ values candidate kernels place on the ranged
+ * parameter; there is no chosen policy (spec §2.2). */
 struct Band {
     int64_t  hi = 0;                          /* inclusive upper bound */
     Resolved dom[RAD_N_DOMAINS];              /* [RAD_DOMAIN_DEVICE], [RAD_DOMAIN_HOST] */
     std::string miss[RAD_N_DOMAINS];          /* why nothing resolved, for the report */
 
-    /* The band as a reader sees it -- "M <= 64", "M in (64, 512]", "any shape". Carried on
-     * the band rather than recomputed at each reporting site, because the exclusive lower
-     * bound is the previous band's hi and only the table's builder has that. */
+    /* Display form: "M <= 64", "M in (64, 512]", "any shape". Stored here because the exclusive
+     * lower bound is the previous band's hi, which only the table's builder has. */
     std::string span;
 };
 
 /* ================================================================== the declared program */
 
-/* MAPPED IS NOT "HOST MEMORY", IT IS THE CONTAINER'S OWN MAPPING, and that is the whole of the
- * difference. The other three off-device tiers all COPY: pinned and pageable allocate an arena and
- * memcpy the weight into it at load, and SSD preads it a slot at a time. A mapped weight is never
- * copied and occupies no pool -- the loader publishes a pointer into the mmap that
- * core/format/radfile.cpp already holds, and the OS page cache decides what is resident.
+/* Weight tiers. HostPinned and HostPageable copy the weight into an arena at load, and SSD preads
+ * it a slot at a time. Mapped is not host memory but the container's own mmap
+ * (core/format/radfile.cpp): never copied, in no pool, and the OS page cache decides residency.
  *
- * It exists for a weight that is tens of gigabytes and read A HANDFUL OF ROWS A TOKEN -- an
- * n-gram embedding table is the shape. Every copying tier is wrong for that: staging the unit
- * moves the whole table to use a few kilobytes of it, pinning it forces all of it resident on a
- * host whose RAM is the same order as the table, and an arena copy wants a second copy of it
- * beside the mapping that already holds one. A sparse Zipfian gather of a dozen rows out of
- * hundreds of millions is exactly what a page cache is good at.
+ * Mapped is for tables of tens of gigabytes read a few rows a token, such as an n-gram embedding.
+ * A copying tier would stage the whole table for a few kilobytes, pin it on a host with RAM of
+ * the same order, or keep a second copy beside the mapping; a sparse Zipfian gather suits a page
+ * cache.
  *
- * Only a HOST kernel can read the mapping -- the bytes are pageable and at no device address -- so
- * the planner assigns this tier where no device kernel for the op exists at all, and where
- * --ngram-placement keeps an n-gram table off the card (embed_lookup_q, libavx/avx_ngram.cpp).
- * Under `ram` the load phase publishes a copy in place of the mapping: locked memory for the host
- * gather, or pinned memory a device kernel reads over the link (the zero-copy site). */
+ * Only a host kernel can read the mapping (pageable, no device address), so the planner assigns
+ * it where no device kernel exists for the op, and where --ngram-placement keeps an n-gram table
+ * off the card (embed_lookup_q, libavx/avx_ngram.cpp). Under `ram` the load phase publishes a
+ * copy instead: locked memory for the host gather, or pinned memory a device kernel reads over
+ * the link (the zero-copy site). */
 enum class Tier { VRAM = 0, HostPinned = 1, HostPageable = 2, SSD = 3, Mapped = 4 };
 
-/* WHERE A LOOKUP TABLE LIVES: the token embedding (--embedding-placement) and an n-gram embedding
- * (--ngram-placement), each a model-level weight that only a row lookup reads, so a step touches M
- * of its rows and never the whole table. That is what makes every tier below the card usable for
- * it, and why the operator gets to choose.
+/* Where a lookup table lives: the token embedding (--embedding-placement) or an n-gram embedding
+ * (--ngram-placement). Only a row lookup reads them, so a step touches M rows, never the whole
+ * table, which makes every tier below the card usable.
  *
- *   Vram   resident on the card, a weight like any other.
- *   Ram    in host memory the card or a host kernel reads in place: the embedding pinned beside
- *          the host pool, read over the link; an n-gram table as a copy made at load.
- *   Disk   read from the container on demand; the n-gram table's only.
- *   Auto   the fastest of the three that has room once every other weight is placed; the n-gram
- *          table's only. Engine::plan decides it and writes the answer into Config, so every rank
- *          plans from one choice. The embedding takes Ram or Vram. */
+ *   Vram   resident on the card, like any other weight.
+ *   Ram    host memory the card or a host kernel reads in place: the embedding pinned beside the
+ *          host pool and read over the link; an n-gram table as a copy made at load.
+ *   Disk   read from the container on demand; n-gram table only.
+ *   Auto   the fastest of the three with room once every other weight is placed; n-gram table
+ *          only. Engine::plan resolves it into Config so every rank plans from one choice. The
+ *          embedding takes Ram or Vram. */
 enum class TablePlacement { Auto = 0, Vram = 1, Ram = 2, Disk = 3 };
 const char* table_placement_name(TablePlacement p);
-/* --draft-window: how many drafts a step verifies for each sequence (core/sched/draft.h).
+/* --draft-window: how many drafts a step verifies per sequence (core/sched/draft.h).
  *   Fixed     every sequence drafts --num-speculative-tokens.
- *   Adaptive  that is the ceiling; each step's head depth and each sequence's stop follow the
- *             measured acceptance and the measured step cost. A serial drafter's policy only.
- * The default is kDraftWindowDefault, and the help text and the startup line read it from there.
+ *   Adaptive  that is the ceiling; head depth per step and each sequence's stop follow measured
+ *             acceptance and step cost. Serial drafters only.
+ * The default is kDraftWindowDefault; the help text and startup line read it from there.
  *
- * FIXED IS THE DEFAULT BECAUSE ADAPTIVE LOSES WHERE A SERVER IS BUSY. Qwen3.8-Flash-Next at TP2 on
- * two R9700, distinct prompts a sequence, tokens a second over a steady window against fixed depth 3:
+ * Fixed is the default because adaptive loses on a busy server. Qwen3.8-Flash-Next, TP2 on two
+ * R9700, distinct prompts, throughput against fixed depth 3:
  *
  *      concurrent sequences        1        2        4        8
  *      adaptive, ceiling 3       +0.4%    -0.1%    +1.7%    -0.3%
  *      adaptive, ceiling 5       +7.1%    -2.3%    +7.4%   -11.9%
  *
- * At eight the head runs five rounds for little more text: 43.0 against 36.3 ms a step (1.18x) for
- * 23.3 against 22.3 tokens. The cost model's prior puts depth 5 over depth 3 at 1.10x, and a depth
- * not yet timed at a load is priced on the prior. */
+ * At eight sequences depth 5 costs 1.18x the step time (43.0 vs 36.3 ms) for 1.04x the tokens
+ * (23.3 vs 22.3). The cost model's prior puts depth 5 at 1.10x depth 3, and a depth not yet timed
+ * at a load is priced on the prior. */
 enum class DraftWindow { Fixed = 0, Adaptive = 1 };
 constexpr DraftWindow kDraftWindowDefault = DraftWindow::Fixed;
 inline const char* draft_window_name(DraftWindow w) {
@@ -158,9 +149,8 @@ inline const char* draft_window_name(DraftWindow w) {
 }
 enum class Site { Device = 0, DeviceStaged = 1, DeviceZeroCopy = 2, Host = 3 };
 
-/* Tier-indexed arrays are sized by this rather than by a literal: the report, the live view and
- * the planner's totals all index by (int)Tier and a fifth tier that fits in four of them is an
- * out-of-bounds write that costs nothing until it costs everything. */
+/* Size of every Tier-indexed array (report, live view, planner totals). Use it rather than a
+ * literal, so a new tier cannot silently write out of bounds. */
 constexpr int kTierCount = 5;
 
 const char* tier_name(Tier t);
@@ -179,10 +169,10 @@ struct WeightInfo {
     int64_t        part_lo[RAD_MAX_ROW_PARTS] = {0}, part_hi[RAD_MAX_ROW_PARTS] = {0};
     int64_t        part_total[RAD_MAX_ROW_PARTS] = {0};
 
-    /* WHAT IT IS A VIEW OF (RadWeightDecl::source and ::planes, spec §4.3). `enc` is the source's
-     * encoding as the model holds it -- or, with nothing behind the builder, plain in the declared
-     * dtype -- and `sel` the planes this declaration takes, in its order. `sel_rows`/`sel_cols`
-     * are each plane's extents for THIS RANK, which is what a layout hook is shown. */
+    /* The view's source (RadWeightDecl::source and ::planes, spec §4.3). `enc` is the source's
+     * encoding as the model holds it, or plain in the declared dtype when nothing is behind the
+     * builder; `sel` lists the planes this declaration takes, in order. `sel_rows`/`sel_cols` are
+     * each plane's extents for this rank, which is what a layout hook is shown. */
     std::string    source;
     RadEncoding    enc{};
     bool           enc_known = false;
@@ -191,21 +181,20 @@ struct WeightInfo {
     int64_t        sel_rows[RAD_ENC_MAX_PLANES] = {0};
     int64_t        sel_cols[RAD_ENC_MAX_PLANES] = {0};
 
-    /* Filled by the layout pass: what the resolved kernel stores for it. `identity` is the
-     * selected plane's bytes unchanged -- the only form the file and mapped tiers can serve,
-     * since they read the container where it lies; `widen` is identity but for an exact widening
-     * (a bf16 norm read as f32) the loader performs. Otherwise the kernel at (lay_op, lay_band,
-     * lay_dom) relayouts it at load, as operand `lay_operand`. */
+    /* Filled by the layout pass: what the resolved kernel stores. `identity` is the selected
+     * plane's bytes unchanged, the only form the file and mapped tiers can serve since they read
+     * the container in place; `widen` is identity plus an exact widening (a bf16 norm read as
+     * f32) done by the loader. Otherwise the kernel at (lay_op, lay_band, lay_dom) relayouts it at
+     * load, as operand `lay_operand`. */
     std::string    layout_tag;
     bool           identity = true;
     bool           widen = false;
     int32_t        lay_op = -1, lay_band = -1, lay_dom = -1, lay_operand = -1;
     uint32_t       stored_dtype = RAD_DT_INVALID;
     uint32_t       stored_rank = 0;
-    int64_t        stored_shape[RAD_MAX_RANK] = {0};   /* what the kernel will receive. A layout
-                                       * hook may reshape -- WMMA fragment order is not the
-                                       * declared shape -- and the kernel has to be handed the
-                                       * shape it actually gets, not the logical one. */
+    int64_t        stored_shape[RAD_MAX_RANK] = {0};   /* the shape the kernel receives, which a
+                                       * layout hook may change (WMMA fragment order is not the
+                                       * declared shape) */
     int64_t        stored_bytes = 0;
     int64_t        align = RAD_ALIGN_UNIT;
 
@@ -214,51 +203,20 @@ struct WeightInfo {
     Site           site = Site::Device;
     int32_t        slab_slot = -1;      /* -1 = not slab-resident */
 
-    /* Filled at load. Under TP this is THIS RANK's shard, not the whole weight. */
+    /* Filled at load. Under TP this is this rank's shard, not the whole weight. */
     void*          ptr = nullptr;
     void*          host_ptr = nullptr;
     uint64_t       file_offset = 0;
-    std::atomic generation{0}; /* bumped when the mover relocates it */
 
-    /* Ordering, so layer offload is a scheduling problem and not a prediction one: this is the
-     * first op index that reads the weight, and prefetch runs off it (spec §5). */
+    /* First and last op index that read the weight. Prefetch runs off these, so layer offload is
+     * scheduling rather than prediction (spec §5). */
     int32_t        first_use_op = -1;
     int32_t        last_use_op  = -1;
-
-    /* The atomic makes the copy hand-written, so a field added above has to be added here too.
-     * The weight list reallocates through this copy as the plugin declares, so a field left out
-     * is reset to its default on every weight declared before the last growth. */
-    WeightInfo() = default;
-    WeightInfo(const WeightInfo& o) { *this = o; }
-    WeightInfo& operator=(const WeightInfo& o) {
-        name = o.name; decl = o.decl; logical_bytes = o.logical_bytes;
-        shard_lo = o.shard_lo; shard_hi = o.shard_hi;
-        n_part_spans = o.n_part_spans;
-        for (int i = 0; i < RAD_MAX_ROW_PARTS; ++i) {
-            part_lo[i] = o.part_lo[i]; part_hi[i] = o.part_hi[i]; part_total[i] = o.part_total[i];
-        }
-        source = o.source; enc = o.enc; enc_known = o.enc_known; n_sel = o.n_sel;
-        for (int i = 0; i < RAD_ENC_MAX_PLANES; ++i) {
-            sel[i] = o.sel[i]; sel_rows[i] = o.sel_rows[i]; sel_cols[i] = o.sel_cols[i];
-        }
-        layout_tag = o.layout_tag; identity = o.identity; widen = o.widen;
-        lay_op = o.lay_op; lay_band = o.lay_band; lay_dom = o.lay_dom; lay_operand = o.lay_operand;
-        stored_dtype = o.stored_dtype;
-        stored_bytes = o.stored_bytes; align = o.align;
-        stored_rank = o.stored_rank;
-        for (int i = 0; i < RAD_MAX_RANK; ++i) stored_shape[i] = o.stored_shape[i];
-        tier = o.tier; site = o.site; slab_slot = o.slab_slot;
-        ptr = o.ptr; host_ptr = o.host_ptr; file_offset = o.file_offset;
-        generation.store(o.generation.load());
-        first_use_op = o.first_use_op; last_use_op = o.last_use_op;
-        return *this;
-    }
 };
 
-/* THIS RANK'S SELECTED PLANES AS A LAYOUT HOOK SEES THEM: dense rank-2 geometry, `data` null
- * unless the caller fills it. One definition, because the builder asks the hook with it at
- * declare and the runtime asks again before moving an op to another domain, and the two
- * questions have to be the same question. */
+/* This rank's selected planes as a layout hook sees them: dense rank-2 geometry, `data` null
+ * unless the caller fills it. Shared by the builder at declare and the runtime before moving an
+ * op to another domain, so both ask the hook the same question. */
 inline void weight_planes(const WeightInfo& w, RadTensor* t) {
     for (int k = 0; k < w.n_sel; ++k) {
         t[k] = RadTensor{};
@@ -271,10 +229,9 @@ inline void weight_planes(const WeightInfo& w, RadTensor* t) {
     }
 }
 
-/* CAN THE BYTES BE READ WHERE THEY LIE IN THE CONTAINER -- the file tier's O_DIRECT stage, the
- * mapped tier's pointer? Only when they are the selected plane's bytes unchanged and this rank
- * holds all of it: a relayout has no place in the file that already looks the way the kernel
- * reads it, and a column shard is not one range of it. */
+/* Whether the bytes can be read where they lie in the container (the file tier's O_DIRECT stage,
+ * the mapped tier's pointer): only when they are the selected plane unchanged and this rank holds
+ * all of it. A relayout is not in the file, and a column shard is not one contiguous range. */
 inline bool weight_file_direct(const WeightInfo& w, int world_size) {
     return w.identity && !w.widen && (w.decl.shard == RAD_SHARD_NONE || world_size <= 1);
 }
@@ -284,8 +241,8 @@ struct BufferInfo {
     RadBufDecl  decl{};
     int64_t     bytes = 0;
 
-    /* From the buffer plan: liveness over the declared op list, and the arena offset the plan
-     * assigned. Two transients whose lives do not overlap share storage (spec §3.1). */
+    /* From the buffer plan: liveness over the declared op list, and the assigned arena offset.
+     * Two transients whose lives do not overlap share storage (spec §3.1). */
     int32_t     first_def = -1;
     int32_t     last_use  = -1;
     int64_t     arena_offset = -1;
@@ -299,13 +256,10 @@ struct OpInfo {
     int64_t               range_lo = 0, range_hi = 0;
     std::vector     bands;
     std::vector weights;
-    /* Which SCHEMA OPERAND POSITION each declared weight belongs to, parallel to `weights`.
-     *
-     * It is NOT the index. The n-th declared weight is not the n-th operand whose role is
-     * RAD_OPD_WEIGHT, because RAD_OPD_WTAB lets one operand position consume a whole RUN of
-     * declared weights (a MoE layer's experts), so the mapping is many-to-one. Recorded once at
-     * declare rather than recomputed at each site that needs it: the recomputation is easy to get
-     * wrong, and one recorded answer is one the sites cannot disagree about. */
+    /* The schema operand position each declared weight belongs to, parallel to `weights`. Not the
+     * index: RAD_OPD_WTAB lets one operand consume a run of declared weights (a MoE layer's
+     * experts), so the mapping is many-to-one. Recorded once at declare so call sites cannot
+     * disagree. */
     std::vector  weight_opd;
     const RadOpSchema*    schema = nullptr;
     int32_t               index = 0;    /* position in the declared order */
@@ -325,14 +279,12 @@ struct KVGroupInfo {
     bool            drafter = false;
 };
 
-/* A RAD_KV_CONV GROUP'S WINDOW, IN ENTRIES: conv_width - 1 of history and one more for every
- * speculative position. It is the last extent of the state tensor the kernels index, and the
- * kernels take the layout from that extent -- a slot is `entries` consecutive entries a channel,
- * and libr4d's conv update derives the verify step's query length from it as
- * entries - (conv_width - 2). So the allocation's slot, the KV manager's view of a slot (its clear
- * when one is handed out, a checkpoint's save and restore) and the cursor conv_state_index derives
- * all take this one number. A slot sized larger on the manager's side than in the tensor puts
- * each of those views across the start of the next sequence's window. */
+/* A RAD_KV_CONV group's window in entries: conv_width - 1 of history plus one per speculative
+ * position. It is the last extent of the state tensor, and kernels derive the layout from it: a
+ * slot is `entries` consecutive entries per channel, and libr4d's conv update derives the verify
+ * query length as entries - (conv_width - 2). The allocation, the KV manager's slot view (clear on
+ * hand-out, checkpoint save and restore) and conv_state_index's cursor must all use this number;
+ * a larger manager-side slot overlaps the next sequence's window. */
 inline int64_t conv_window_entries(const RadKVGroupDecl& d, int64_t n_spec) {
     return (d.conv_width > 0 ? d.conv_width - 1 : 0) + (n_spec > 0 ? n_spec : 0);
 }
@@ -350,39 +302,37 @@ public:
     RadBuildCtx  ctx{};
     RadModelMeta meta{};
 
-    /* The buffer the plugin named as this step's logits (rad_declare_logits). Zero when the
-     * plugin declared none, which is what an encoder-only or embedding-only plugin does on
-     * purpose -- the engine refuses to SERVE such a program and says so at startup, rather
-     * than discovering at the first step that there is nothing to sample. */
+    /* The step's logits buffer (rad_declare_logits). Zero when the plugin declared none, as an
+     * encoder-only or embedding-only plugin does; the engine refuses to serve such a program at
+     * startup. */
     rad_buf logits_buf = 0;
-    /* The buffer the plugin named as this step's pooled vectors (rad_declare_pooled): set only by
-     * an EMBEDDING program, which then has no logits buffer. */
+    /* The step's pooled vectors (rad_declare_pooled): set only by an embedding program, which has
+     * no logits buffer. */
     rad_buf pooled_buf = 0;
 
-    /* THE DRAFT HEAD THIS PLUGIN DECLARED (rad_declare_drafter). `kind == RAD_DRAFT_NONE` when
-     * it declared none, which is the normal case -- the engine then speculates with the
-     * scheduler's prompt-lookup drafter or not at all. `name` is kept beside the decl because
-     * RadDrafterDecl::name points into the plugin's own storage. */
+    /* The declared draft head (rad_declare_drafter). `kind == RAD_DRAFT_NONE` when none, the
+     * normal case: the engine then speculates with the scheduler's prompt-lookup drafter or not at
+     * all. `drafter_name` is a copy because RadDrafterDecl::name points into plugin storage. */
     RadDrafterDecl drafter{};
     std::string    drafter_name;
-    /* A SERIAL HEAD WITH NO CACHE OF ITS OWN (rad_drafter_shared_kv): it reads the trunk's K and V
+    /* A serial head with no cache of its own (rad_drafter_shared_kv): it reads the trunk's K and V
      * and writes none, so the driver owes it no history and runs every round at the committed
-     * position. `drafter_pos_offset` is where those rows sit for the rotary, 0 or 1 past it. Both
-     * are false and 0 for every drafter that did not ask, which is every one that predates it. */
+     * position. `drafter_pos_offset` (0 or 1) is where those rows sit for the rotary. False and 0
+     * for drafters that did not ask. */
     bool           drafter_shared_kv = false;
     int32_t        drafter_pos_offset = 0;
 
-    /* THE MEDIA ENCODER THIS PLUGIN DECLARED (rad_declare_encoder). `modalities == 0` when it
-     * declared none, which is every text-only program and every deployment that asked for no
-     * media (RadBuildCtx::max_enc_patches 0). `encoder_name` for the reason `drafter_name` is. */
+    /* The declared media encoder (rad_declare_encoder). `modalities == 0` when none: every
+     * text-only program, and every deployment with RadBuildCtx::max_enc_patches 0.
+     * `encoder_name` is a copy, as `drafter_name` is. */
     RadEncoderDecl encoder{};
     std::string    encoder_name;
-    /* ...and the audio encoder, the second a program may declare (RAD_MM_AUDIO). */
+    /* The audio encoder, the second a program may declare (RAD_MM_AUDIO). */
     RadEncoderDecl audio_encoder{};
     std::string    audio_encoder_name;
-    /* THE IMAGE GENERATOR THIS PLUGIN DECLARED (rad_declare_generator); `layout` 0 when it declared
-     * none. The strings and the fixed schedule it points at are the copies below, not the plugin's
-     * storage. A generator program has no logits and no pooled vectors. */
+    /* The declared image generator (rad_declare_generator); `layout` 0 when none. Its strings and
+     * fixed schedule point at the copies in `gen_str`, not plugin storage. A generator program has
+     * no logits and no pooled vectors. */
     RadGeneratorDecl generator{};
     struct GenStrings {
         std::string name, tmpl_text, tmpl_edit, tmpl_image, tmpl_image_sep, drop_prefix,
@@ -392,38 +342,33 @@ public:
     bool is_generator() const { return generator.layout != 0; }
 
     /* Two arenas, because a host-site activation cannot index device memory. The buffer plan
-     * colours the domains SEPARATELY -- a transient may share storage only with a transient in the
-     * same domain -- so each of these is a high-water mark in its own offset space and
-     * BufferInfo::arena_offset is relative to the arena of that buffer's declared domain. Both are
-     * sized for max_tok, which is the worst step (spec §3.1). */
+     * colours each domain separately (transients share storage only within a domain), so each is
+     * a high-water mark in its own offset space and BufferInfo::arena_offset is relative to the
+     * arena of the buffer's declared domain. Both are sized for max_tok, the worst step (spec
+     * §3.1). */
     int64_t arena_bytes = 0;         /* RAD_DOMAIN_DEVICE */
-    /* Where the device arena's TRANSIENTS start: everything below is PERSIST and DERIVED, at the
-     * same offset at every size a step can be, and everything above is the part a smaller step
-     * packs smaller (core/build/rad_bufplan.cpp, plan_level). */
+    /* Start of the device arena's transients. PERSIST and DERIVED buffers sit below, at the same
+     * offset at every step size; above is what a smaller step packs smaller
+     * (core/build/rad_bufplan.cpp, plan_level). */
     int64_t arena_fixed_bytes = 0;
-    /* THE PREFILL STAGING REGION, above every buffer the plan placed: where a step at the full
-     * plan copies a routed layer's non-resident experts ahead of the layer (core/place/stager.h).
-     * Sized by the VRAM budget, appended by the engine after it, and part of the top of the arena
-     * that the smaller levels lend to the expert slab. -1 / 0 where there is none. */
+    /* The prefill staging region, above every planned buffer: where a full-size step copies a
+     * routed layer's non-resident experts ahead of the layer (core/place/stager.h). Sized by the
+     * VRAM budget and appended by the engine; part of the arena top that smaller levels lend to
+     * the expert slab. -1 / 0 when absent. */
     int64_t arena_stage_off = -1;
     int64_t arena_stage_bytes = 0;
     int64_t host_arena_bytes = 0;    /* RAD_DOMAIN_HOST */
     int64_t scratch_bytes = 0;       /* the largest single kernel scratch requirement */
-    /* How many scratch regions of that size the arena holds: one per lane the program runs.
-     * Every kernel on a stream is handed the same region, which its in-order launches make safe;
-     * a second lane is a second stream, and a region both lanes wrote would take two kernels'
-     * partials at once. Two when the architecture declared a buffer rad_buf_concurrent. */
+    /* Scratch regions of that size in the arena, one per lane. Kernels on one stream share a
+     * region safely through in-order launch; a second lane is a second stream and needs its own.
+     * Two when the architecture declared a buffer rad_buf_concurrent. */
     int32_t scratch_regions = 1;
 
-    /* Everything that resolved to nothing, reported whole rather than the first failure at the
-     * top (spec §3.1).
-     *
-     * STRUCTURED, not a pre-formatted sentence, because the two domains want two different
-     * reports and one flat list of strings cannot give them. A DEVICE miss is a hole a request
-     * will fall into and deserves its own line; a HOST miss removes one placement option for one
-     * op and deserves a line per OP, not per band. A flat list of strings leaves the reporting
-     * site able only to print all of them, and a deep model at tp2 then opens with thousands of
-     * lines of `E` -- every one of them expected, and a real device hole invisible among them. */
+    /* Everything that resolved to nothing, reported whole rather than stopping at the first
+     * failure (spec §3.1). Structured because the domains are reported differently: a device miss
+     * is a hole a request can hit and gets its own line; a host miss only removes a placement
+     * option and gets one line per op, not per band. Otherwise a deep model at tp2 prints
+     * thousands of expected lines that hide a real device hole. */
     struct Miss {
         std::string op;
         std::string geom;         /* the band's display geometry */
@@ -434,26 +379,20 @@ public:
         std::string line() const; /* "op  geometry  [domain] -> why", the full-detail rendering */
     };
     std::vector misses;
-    /* THE DEVICE MISSES A REQUEST CAN FALL INTO, in `misses` order: the device bands no kernel
-     * serves and no host kernel stands in for. A host kernel for the same band stands in on the
-     * host backend, where every op without a device row runs on the host (Ctx::bind_ops); on a
-     * card it stands in only for an op that has weights, because the planner moves an op to the
-     * host by placing its weights there and has nothing to place for an op without them --
-     * attention over a cache that lives in VRAM is the case that matters. One rule for the engine
-     * that refuses to start on a hole and for the tools that count them. */
+    /* The device misses a request can hit, in `misses` order: device bands no kernel serves and no
+     * host kernel stands in for. On the host backend a host kernel for the band stands in, since
+     * every op without a device row runs on the host (Ctx::bind_ops). On a card it stands in only
+     * for an op with weights, because the planner moves an op to the host by placing its weights
+     * there; attention over a VRAM cache is the case that matters. Shared by the engine's startup
+     * refusal and the tools that count holes. */
     std::vector device_holes(bool host_backend) const;
 
-    /* Every (kernel, shape) pair rad-tune would need to benchmark (spec §15). */
-    /* `info` is the kernel's own row, so rad-tune can read its RadTunable axes and expand the
-     * cross product itself. A count would not do: the tuner has to know the KEYS and their legal
-     * values to build a candidate, and the validity predicate to discard the ones this geometry
-     * cannot run. Plugins outlive the Program, so the pointer is good for the process. */
-    /* ONE PER KERNEL INSTANTIATION: the kernel, the plugin it came from, and the input parameters
-     * it was resolved at. `geom` is what a launch is handed and therefore CARRIES the axis
-     * defaults the selector folded in -- a tuner overrides them per candidate with set_i.
-     * `geom_key` is the instantiation WITHOUT them, in tunecache.h's canonical spelling, and it is
-     * the cache key: the selector looks an instantiation up before it knows what to choose, so a
-     * key that included the choice could never be found. */
+    /* One per kernel instantiation that rad-tune would benchmark (spec §15). `info` is the
+     * kernel's row, so the tuner can read the RadTunable axes, their legal values and the validity
+     * predicate; plugins outlive the Program, so the pointer stays valid. `geom` is what a launch
+     * receives and carries the selector's axis defaults, which the tuner overrides per candidate
+     * with set_i. `geom_key` is the instantiation without them (tunecache.h's spelling) and is the
+     * cache key, because the selector looks up before it knows the choice. */
     struct TuneRequest {
         std::string          kernel, plugin;
         Geometry             geom;
@@ -472,17 +411,15 @@ public:
 
 enum class ReqState { Waiting, Running, Preempted, Finished, Failed, Cancelled };
 
-/* A CHAT REPLY'S REASONING BLOCK, AS TOKENS. The reply parser reads the block in text
- * (core/text/chatparse.h); this is the same block named by token id, so the engine can count it
- * and close it without detokenising. It exists only where both markers the reply needs are
- * single tokens -- `` and `` are, on every model this engine serves -- and
- * `close < 0` says it does not: such a reply's reasoning is still split out as text, but it is
- * not counted and no budget can be held on it.
+/* A chat reply's reasoning block by token id, so the engine can count and close it without
+ * detokenising; the reply parser reads the same block as text (core/text/chatparse.h). It exists
+ * only when both markers are single tokens (``/`` are on every served model).
+ * `close < 0` means no countable block: the reasoning is still split out as text, but is not
+ * counted and cannot carry a budget.
  *
- * The block is read where the parser reads it: at the start of the reply. It is open from the
- * first token when the generation prompt opened it (`starts_open`), or opens on `open` as the
- * reply's first token, and the first `close` ends it. A reply that starts any other way has no
- * block. */
+ * The block starts the reply: open from the first token when the generation prompt opened it
+ * (`starts_open`), or opened by `open` as the first token; the first `close` ends it. A reply that
+ * starts any other way has no block. */
 struct ReasoningSpan {
     int32_t open = -1;            /* the token a reply opens its own block with; -1 for none */
     int32_t close = -1;           /* the token that ends the block; -1: no countable block */
@@ -490,9 +427,8 @@ struct ReasoningSpan {
     bool known() const { return close >= 0; }
 };
 
-/* A reply's position relative to its ReasoningSpan, advanced one emitted token at a time. The
- * server counts with it and the sampler enforces a budget with it, and both must agree on where
- * the block ends, so there is one definition. */
+/* A reply's position relative to its ReasoningSpan, advanced one emitted token at a time. Shared
+ * by the server's count and the sampler's budget so both agree where the block ends. */
 struct ReasoningCount {
     enum State : uint8_t { Lead, Think, Done };
     State   st = Lead;
@@ -516,16 +452,15 @@ struct ReasoningCount {
     bool inside() const { return st == Think; }
 };
 
-/* THE MOST ALTERNATIVES ONE TOKEN'S LOGPROBS MAY CARRY: OpenAI's bound on top_logprobs. A request
- * above it is refused. The sampler declares `sample_logprobs` one wider (Sampler::kLpK), for the
- * width of the row the split-vocabulary gather moves; the extra pair is never reported. */
+/* Most alternatives one token's logprobs may carry: OpenAI's top_logprobs bound; larger requests
+ * are refused. The sampler's `sample_logprobs` is one wider (Sampler::kLpK) for the
+ * split-vocabulary gather; the extra pair is never reported. */
 static constexpr int RAD_MAX_LOGPROBS = 20;
 
-/* One emitted token's log-probability under the model's RAW distribution -- the logits before any
- * penalty, temperature, mask or cut -- and its `n_top` most likely alternatives in descending
- * order, ties to the lower id. What OpenAI's `logprobs` and llama-server's `n_probs` report.
- * `token` -1 is a token whose logprobs could not be computed (a row with no finite logit): the
- * scheduler fails its request rather than report a number for it. */
+/* One emitted token's log-probability under the raw distribution (logits before any penalty,
+ * temperature, mask or cut), and its `n_top` most likely alternatives in descending order, ties to
+ * the lower id. This is OpenAI's `logprobs` and llama-server's `n_probs`. `token` -1 means the
+ * logprobs could not be computed (no finite logit in the row); the scheduler fails the request. */
 struct TokenLogprobs {
     int32_t token = -1;
     float   logprob = 0.0f;
@@ -536,7 +471,7 @@ struct TokenLogprobs {
 
 struct SamplingParams {
     float  temp = 1.0f;
-    int    top_k = 0;                /* 0 = off */
+    int    top_k = 0;                /* 0 = the 1024-candidate width */
     float  top_p = 1.0f;
     float  min_p = 0.0f;
     float  typical_p = 1.0f;
@@ -550,35 +485,31 @@ struct SamplingParams {
     int    dry_penalty_last_n = -1;
     float  xtc_probability = 0.0f;
     float  xtc_threshold = 0.1f;
-    /* TEMPERATURE AFTER THE CUTS rather than before them: top-p, min-p, typical and XTC read the
-     * distribution at temperature 1 and the pick draws at `temp`. llama.cpp's default order; the
-     * default here is vLLM's, temperature first. A request names the order with `samplers`. */
+    /* Temperature after the cuts: top-p, min-p, typical and XTC read the distribution at
+     * temperature 1 and the pick draws at `temp`. This is llama.cpp's order; the default is
+     * vLLM's (temperature first). A request selects it with `samplers`. */
     bool   temp_last = false;
-    /* LOGPROBS: -1 is none; 0..RAD_MAX_LOGPROBS returns every emitted token's logprob and that
-     * many alternatives. Speculation is unaffected: every verified position is a row of its own,
-     * and an accepted draft is the token the target drew there. */
+    /* Logprobs: -1 is none; 0..RAD_MAX_LOGPROBS returns every emitted token's logprob and that
+     * many alternatives. Works under speculation: each verified position is its own row, and an
+     * accepted draft is the token the target drew there. */
     int    n_probs = -1;
     uint64_t seed = 0;
     bool   greedy() const { return top_k == 1 || temp <= 0.0f; }
     std::string grammar;             /* GBNF, or "" */
     std::vector dry_seq_breakers;
 
-    /* THE REPLY'S REASONING BLOCK, and how many tokens its body may run to. -1 is no limit. At
-     * the limit the sampler masks every position still inside the block to `reasoning.close`, so
-     * the block ends there and the answer follows -- vLLM's `thinking_token_budget`. A budget
-     * needs a known span; the server refuses one it cannot hold. */
+    /* The reasoning block and its body's token limit (-1 = none). At the limit the sampler masks
+     * every position still inside the block to `reasoning.close`, so the answer follows (vLLM's
+     * `thinking_token_budget`). A budget needs a known span; the server refuses one otherwise. */
     ReasoningSpan reasoning;
     int32_t       thinking_budget = -1;
 
-    /* A LAZY GRAMMAR CONSTRAINS NOTHING UNTIL A TRIGGER FIRES, and that is the only shape in
-     * which a tool-calling chat template can be enforced: the reply is free prose until the
-     * model starts writing a call, and grammar-shaped from there. Without this a request that
-     * carries `tools` would be constrained to emit a tool call and nothing else, so a lazy
-     * grammar arriving as a non-lazy one is not a small difference -- it is a model that can no
-     * longer answer in words. The trigger types are common_grammar_trigger_type's, kept as ints
-     * because rad_core.h does not include the lift: 0 token, 1 word, 2 pattern, 3 pattern-full.
-     * Resolving a word or a token to vocabulary ids happens in the sampler, which is the layer
-     * that has the vocabulary. */
+    /* A lazy grammar constrains nothing until a trigger fires. That is the only way to enforce a
+     * tool-calling template: free prose until the model starts a call, grammar-shaped after. Treat
+     * a lazy grammar as non-lazy and a request with `tools` can only emit a tool call. Trigger
+     * types are common_grammar_trigger_type's, as ints because this header does not include the
+     * lift: 0 token, 1 word, 2 pattern, 3 pattern-full. The sampler resolves words and tokens to
+     * vocabulary ids. */
     struct GrammarTrigger { int type = 0; std::string value; };
     bool                        grammar_lazy = false;
     std::vector grammar_triggers;
@@ -588,21 +519,18 @@ struct SamplingParams {
      * about to be sampled. See GrammarSpec::prefix in core/sample/grammar.h. */
     std::string                 grammar_prefix;
 
-    /* `grammar` COMPILED, by the thread that admitted the request (core/sample/gbnf.h,
-     * gbnf_compile). Compiling a grammar builds its mask plan, which is host work in the tens to
-     * hundreds of milliseconds, and the sampler starts a request on the scheduler thread with
-     * every other request's step waiting on it. Holding the program here keeps it findable by
-     * the sampler for as long as the request lives, so starting the request there is a lookup.
-     * Null for a request that was not admitted through the server; the sampler then compiles. */
+    /* `grammar` compiled by the admitting thread (core/sample/gbnf.h, gbnf_compile). Building the
+     * mask plan takes tens to hundreds of milliseconds, and the sampler starts requests on the
+     * scheduler thread where every other request's step waits; held here, starting is a lookup.
+     * Null for a request not admitted through the server; the sampler then compiles. */
     std::shared_ptr grammar_program;
 };
 
-/* THE RAW LOGITS AT CHOSEN VOCABULARY IDS, read at the prompt's last position: what a caller
- * that answers from a distribution over a handful of tokens needs (/v1/systemone), and nothing
- * more of the vocabulary. The caller fills `tokens` before submission; the engine writes `logits`
- * in the same order, from the logits row BEFORE the sampler touches it, and before the request's
- * sink finishes. Read them only after a successful finish. Shared, so the result outlives a
- * caller that left mid-step. */
+/* Raw logits at chosen vocabulary ids at the prompt's last position, for a caller that answers
+ * from a distribution over a few tokens (/v1/systemone). The caller fills `tokens` before
+ * submission; the engine writes `logits` in the same order, from the row before the sampler
+ * touches it, before the sink finishes. Read only after a successful finish. Shared so the result
+ * outlives a caller that left mid-step. */
 struct TokenScores {
     std::vector tokens;
     std::vector   logits;
@@ -615,14 +543,9 @@ struct Request {
     SamplingParams       sp;
     int32_t              max_tokens = 0;
     std::vector stop;
-    /* GENERATE PAST THE END-OF-TEXT TOKEN, to max_tokens. It exists so a caller can ask for a
-     * request whose LENGTH IS THE ONE IT ASKED FOR. Without it the length is the model's opinion
-     * and varies from run to run on the same prompt, so a steady-state decode measurement over
-     * such a request may be measuring a mostly idle engine, and its variance reads as a
-     * difference between whatever was being compared.
-     *
-     * It ignores the EOS TOKEN and nothing else: `stop` strings and max_tokens still end a
-     * request, which is vLLM's meaning of the field and the one a client already expects. */
+    /* Generate past the end-of-text token, up to max_tokens, so the output length is fixed (for
+     * example in a steady-state decode measurement). Only the EOS token is ignored: `stop` strings
+     * and max_tokens still end the request, as in vLLM. */
     bool                 ignore_eos = false;
     int                  priority = 0;
     bool                 stream = false;
@@ -633,70 +556,61 @@ struct Request {
     std::vector blocks;              /* per KV group, flattened by group offset */
     int32_t              state_slot = -1;     /* linear/conv state slot */
 
-    /* THE MEDIA THIS PROMPT CARRIES, null for a text prompt: each item's patches, where its
-     * token run sits in `prompt`, the rotary layout those runs give the prompt, and -- once the
-     * encoder has run -- the rows that replace the placeholders' embeddings (core/mm). */
+    /* The prompt's media, null for text (core/mm): each item's patches, where its token run sits
+     * in `prompt`, the rotary layout those runs give, and after the encoder runs, the rows that
+     * replace the placeholders' embeddings. */
     std::shared_ptr media;
 
     int32_t              n_draft = 0;         /* speculative window this step */
-    /* AND THE PROPOSAL ITSELF, because masking a speculative window needs the tokens and not
-     * just the count: Sampler::build_step walks a constraining grammar over these to mask the
-     * position behind each one, then rewinds. Points into the scheduler's own array for this
-     * request -- SchedReq owns this Request, so it outlives it -- and is written beside n_draft,
-     * in the same two places, for the reason the comment there gives. Null when n_draft is 0. */
+    /* The proposal itself: Sampler::build_step walks a constraining grammar over these tokens to
+     * mask each draft position, then rewinds. Points into the scheduler's array for this request
+     * (SchedReq owns this Request, so it outlives it) and is written alongside n_draft. Null when
+     * n_draft is 0. */
     const int32_t*       draft = nullptr;
     int32_t              n_accepted = 0;      /* from the previous verify */
 
-    /* MAY THIS REQUEST BE SPECULATED ON AT ALL. Written by the engine after every step, read by
-     * the scheduler when it sizes the next one. One thing clears it, and it is a property the
-     * scheduler cannot see for itself: its grammar is constraining right now. The mask for draft
-     * position i depends on which of 0..i-1 were accepted, and the host automaton cannot know
-     * that before the verify runs. A LAZY grammar clears this only once its trigger fires, so a
-     * tool-calling request speculates through its prose and stops the moment it starts writing
-     * the call.
+    /* Whether this request may be speculated on. Written by the engine after every step, read by
+     * the scheduler when sizing the next. Only a currently constraining grammar clears it: the
+     * mask at draft position i depends on which of 0..i-1 were accepted, which the host automaton
+     * cannot know before the verify. A lazy grammar clears it only once its trigger fires.
      *
-     * TEMPERATURE DOES NOT CLEAR IT. A sampled target does not need rejection sampling to stay
-     * exact: acceptance compares against the token the target itself drew, and the sampler gives
-     * every verified position its own RNG coordinate. See Engine::collect_step.
+     * Temperature does not clear it: acceptance compares against the token the target itself
+     * drew, and each verified position has its own RNG coordinate (Engine::collect_step).
      *
-     * It is a flag rather than a call because there are two drafters and an n-gram fallback inside
-     * step() itself, and every one of them has to obey: the fallback fills any proposal the others
-     * left empty, so guarding only the drafters guards nothing. */
+     * A flag rather than a call because two drafters and an n-gram fallback inside step() must all
+     * obey it; the fallback fills any proposal the others left empty. */
     bool                 may_speculate = true;
-    /* AND WHETHER THAT ANSWER CAN CHANGE AT A COMMIT, which only a grammar that cannot rewind
-     * makes it do. A step issued ahead is sized before the commit in front of it, so the scheduler
-     * issues ahead for a request only when this is set. Written by the engine when the sampler
-     * starts the request (Sampler::speculation_fixed); false until then. */
+    /* Whether may_speculate can change at a commit, which only a non-rewindable grammar causes. A
+     * step issued ahead is sized before the preceding commit, so the scheduler issues ahead only
+     * when this is set. Written when the sampler starts the request
+     * (Sampler::speculation_fixed); false until then. */
     bool                 speculation_fixed = false;
 
-    /* A LOGITS ROW AT EVERY PROMPT POSITION, not only at the last: each trunk step that carries
-     * this request's prompt names all of its tokens in `out_ids`, after the rows the sampler
-     * reads, and the engine hands them to the KL scorer (core/kld.h). Only the --kld mode sets
-     * it; the logits buffer is sized for it there and nowhere else. */
+    /* A logits row at every prompt position, not only the last: each trunk step carrying this
+     * prompt names all its tokens in `out_ids` after the sampler's rows, and the engine hands them
+     * to the KL scorer (core/kld.h). Set only in --kld mode, which sizes the logits buffer for
+     * it. */
     bool                 score = false;
 
-    /* THE END OF A PREFIX OTHER REQUESTS WILL START FROM, in prompt tokens; 0 for none. On a
-     * model with linear state (convolutions, a recurrence) a prefix hit resumes from a state
-     * checkpoint, and those are written only on the checkpoint interval and at a long prompt's
-     * tail -- neither is where a shared head of a few hundred tokens ends. The scheduler ends a
-     * prefill chunk here, rounded down to its quantum, and writes a checkpoint as it does on the
-     * interval (Scheduler::plan_chunk), so the requests that follow reuse the whole head.
-     * /v1/systemone sets it on the first question of several over one state. */
+    /* End of a prefix other requests will start from, in prompt tokens; 0 for none. With linear
+     * state, a prefix hit resumes from a state checkpoint, written only on the checkpoint interval
+     * and at a long prompt's tail. The scheduler ends a prefill chunk here (rounded down to its
+     * quantum) and writes a checkpoint (Scheduler::plan_chunk), so following requests reuse the
+     * whole head. /v1/systemone sets it on the first of several questions over one state. */
     int64_t              checkpoint_at = 0;
 
-    /* NON-NULL: read the raw logits at these ids at the prompt's last position (TokenScores).
+    /* Non-null: read the raw logits at these ids at the prompt's last position (TokenScores).
      * The request still samples the one token max_tokens allows; the caller discards it. */
     std::shared_ptr token_scores;
 
-    /* AN EMBEDDING REQUEST: the whole prompt in ONE step, never split -- an encoder that attends
-     * both ways cannot be fed half its input -- and finished at that step with its pooled vector
-     * in the sink (Sink::embedding). Nothing is generated and nothing is emitted. Only an
-     * embedding program (rad_declare_pooled) serves these, and it serves nothing else. */
+    /* An embedding request: the whole prompt in one step, never split (a bidirectional encoder
+     * cannot take half its input), finished at that step with its pooled vector in the sink
+     * (Sink::embedding). Nothing is generated. Only an embedding program (rad_declare_pooled)
+     * serves these, and it serves nothing else. */
     bool                 embed = false;
 
-    /* THE CONVERSATION AS THE CLIENT NAMES IT (OpenRouter's `session_id`), "" when it names
-     * none: carried to the session the prefix cache records for it, as a label on /sessions and
-     * the dashboard. It changes nothing about how the request is served. */
+    /* The client's conversation id (OpenRouter's `session_id`), "" when absent. A label for the
+     * prefix cache's session on /sessions and the dashboard; it does not affect serving. */
     std::string          session_label;
 
     std::string          finish_reason;
@@ -715,42 +629,31 @@ struct Config {
     std::vector kernel_hierarchy;   /* ordered; first wins */
 
     int   tp = 1;
-    /* THE TENSOR-PARALLEL WIRE, and it is a deployment choice rather than a tuning one. 1 is the
-     * exact bf16 all-reduce. 0 accepts a LOSSY wire: at two ranks libr4d serves a
-     * Walsh-Hadamard-rotated 6-bit payload -- 6 bits an element plus a bf16 scale per group of
-     * 64, against 16 bits an element -- so the message a prefill chunk pushes across PCIe drops
-     * by 2.4x. The sum a rank receives is then not the sum it would have received and no check
-     * downstream can tell, which is why it is a named flag and not a heuristic. */
+    /* The tensor-parallel wire, a deployment choice. 1 is the exact bf16 all-reduce. 0 accepts a
+     * lossy wire: at two ranks libr4d sends a Walsh-Hadamard-rotated 6-bit payload (6 bits per
+     * element plus a bf16 scale per 64) instead of 16 bits per element, 2.4x fewer bytes over
+     * PCIe. The received sum then differs undetectably, hence a named flag, not a heuristic. */
     int   tp_wire_exact = 1;          /* --tp-wire exact|wht6 */
-    /* WHERE THE LOSSY WIRE STARTS PAYING, in KiB of one all-reduce message. Compression only wins
-     * once the transfer is bandwidth-bound: a decode step all-reduces a handful of residual rows
-     * and the exact kernel already moves that at most of what the link delivers, so rotating it
-     * costs more than the bytes it saves. A prefill chunk's message is orders of magnitude larger
-     * and is squarely on the wire. Below this floor `--tp-wire wht6` therefore serves the message
-     * EXACTLY -- which also means a decode-only serve sees no quality change from the flag at all.
-     *
-     * 128 KiB IS THE KNEE. A decode step's message scales with the number of sequences in the
-     * batch, so concurrency decides which side of the floor a step lands on. Compressing pays for
-     * every message above the floor and costs on the smallest ones, and 128 KiB is the smallest
-     * floor that compresses everything which benefits while leaving single-sequence decode
-     * exact. */
+    /* Smallest all-reduce message, in KiB, that the lossy wire compresses; smaller ones are sent
+     * exact. Compression pays only when the transfer is bandwidth-bound: a decode step's handful
+     * of residual rows costs more to rotate than it saves, while a prefill chunk is far larger.
+     * Decode message size scales with batch size; 128 KiB is the smallest floor that compresses
+     * every message that benefits while keeping single-sequence decode exact. */
     int64_t tp_wire_min_kb = 128;     /* --tp-wire-min-kb */
-    /* HOW THE COLLECTIVES REACH THE OTHER CARDS. Auto asks the driver, for every ordered pair of
-     * the ranks' cards, whether one can address the other's memory, and takes the P2P kernels only
-     * if every pair can. A driver can answer yes on a board where peer traffic is broken or slower
-     * than going through host memory, and that is what `off` is for: it takes the host-mailbox
-     * collectives whatever the driver says. `on` takes the P2P kernels and stops startup naming
-     * the pairs the driver refuses, rather than falling back -- a deployment that was measured on
-     * P2P should not quietly serve on something else. */
+    /* How the collectives reach the other cards. Auto takes the P2P kernels only if the driver
+     * reports peer access for every ordered pair of the ranks' cards. `off` forces the
+     * host-mailbox collectives, for boards where the driver says yes but peer traffic is broken or
+     * slower. `on` forces P2P and stops startup naming the refused pairs instead of falling
+     * back. */
     int   p2p = RAD_P2P_AUTO;         /* --p2p auto|on|off */
     int64_t max_tok = 8192;            /* --max-num-batched-tokens */
     /* --busy-prefill-chunk: how much of a step a prefill chunk may take when other work is
-     * pending in it (decode rows behind it, another prefill, a request waiting to be admitted).
-     * -1 = auto: the chunk leaves those their rows and a share for admission, and keeps at least
-     * the smallest pass the prefill stager arms for. 0 = off: the chunk takes every token the
-     * step has left, as 1.3.0 did. N > 0: the chunk is held to N tokens on such a step.
-     * Scheduler::step, docs/GUIDE.md. */
+     * pending in it (decode rows, another prefill, a request waiting for admission). -1 = auto:
+     * leave those their rows plus a share for admission, but keep at least the smallest pass the
+     * prefill stager arms for. 0 = off: the chunk takes every token the step has left. N > 0: cap
+     * the chunk at N tokens on such a step. See Scheduler::step, docs/GUIDE.md. */
     int64_t busy_prefill_chunk = -1;
+    int64_t prefill_interleave = 0;    /* --prefill-interleave: decode-only steps between chunks */
     int64_t max_seqs = 256;
     int64_t max_ctx = 0;               /* 0 = the model's training context */
     /* --rope-scaling: "yarn:FACTOR[:ORIG]" writes YaRN over the checkpoint's own rotary keys (the
@@ -758,64 +661,50 @@ struct Config {
      * YaRN off; empty serves what the checkpoint says. Engine::apply_rope_scaling. */
     std::string rope_scaling;
 
-    /* THE ENGINE DERIVES THE BUDGET FROM THE CARD, AND IT IS STATED IN FULL BEFORE ANYTHING IS
-     * ALLOCATED.
+    /* VRAM budget, derived from the card and printed in full before anything is allocated.
+     * Spec §6 forbids a budget derived from free VRAM at startup, which moves with other
+     * processes. This one is arithmetic on known numbers: the fixed card total, every non-pool
+     * allocation computed from the program beforehand, and what the driver already holds,
+     * measured. core/mem/vram_budget.cpp writes the result into the two fields below, so the
+     * planner, KV manager and pool report read one number. Engine::plan derives each rank's copy
+     * (rank_cfg_, docs/TP3.md §1), which that rank's pools and planner both read.
      *
-     * Spec §6 forbids a derived budget because a budget derived from the FREE VRAM at startup is
-     * a benchmark that moves when a desktop opens a window. What it does not forbid is arithmetic
-     * on numbers that are all known and all printed: the card total is a fixed property, every
-     * non-pool allocation this engine makes is computed from the program before it is made, and
-     * what the driver already holds is measured rather than assumed. core/mem/vram_budget.cpp does
-     * that sum and writes the answer back into the two fields below, so every consumer downstream
-     * -- the planner, the KV manager, the pool report -- reads one resolved number and there is no
-     * second place for them to disagree. Engine::plan derives each rank's own copy from it
-     * (rank_cfg_, see docs/TP3.md §1), and the rank's pools and planner both read that copy --
-     * still one number per card, and the same number on every card whose cache costs as much per
-     * token as the dearest rank's.
-     *
-     * NO FLAG SETS THEM: zero until the resolver has run. */
+     * No flag sets them; zero until the resolver runs. */
     int64_t vram_weights_mib = 0;
     int64_t vram_kv_mib = 0;
-    int64_t gpu_headroom_mib = 96;     /* --gpu-headroom, left unclaimed on every card */
-    /* --kv-cache-dtype bf16|fp8. fp8 is an E4M3 cache with per-(sequence, head) descales, and it
-     * halves what a token of context costs -- which at a production context is most of the KV
-     * pool. It is a real quantisation and the model computes a slightly different function with
-     * it, so it is stated rather than inferred, and bf16 is the default.
-     *
-     * TWO VALUES AND NOT THREE. An "auto" that resolved to bf16 everywhere in this tree would be
-     * a third name for the second one, and a flag whose values are not all distinct is a flag
-     * whose log line cannot be read back. */
+    int64_t gpu_headroom_mib = 96;     /* --gpu-headroom-mib, left unclaimed on every card */
+    /* --kv-cache-dtype bf16|fp8. fp8 is an E4M3 cache with per-(sequence, head) descales; it
+     * halves the per-token cost, most of the KV pool at production context. It changes the
+     * model's output slightly, so it is explicit and bf16 is the default. No "auto": it would
+     * always resolve to bf16 and only add a third name. */
     std::string kv_cache_dtype = "bf16";
     int64_t host_pool_mib = 0;
-    /* THE FILE TIER FOR WEIGHTS: what fits neither the VRAM slab nor the pinned host pool is read
-     * from the container itself, with O_DIRECT, ahead of the ops that read it -- a scheduled unit by
-     * the exact prefetch, a routed expert a routed layer at a time. Off unless asked for, because a
-     * weight served from disk is a step paced by the drive: a budget that spills there by accident
-     * is a server that is correct and several orders of magnitude slow. The tier needs no directory
-     * of its own; the container is the file. */
+    /* File tier for weights: what fits in neither the VRAM slab nor the pinned host pool is read
+     * from the container with O_DIRECT ahead of the ops that read it (a scheduled unit by the
+     * exact prefetch, a routed expert a routed layer at a time). Off by default because disk
+     * paces the step, so an accidental spill makes the server orders of magnitude slower. */
     bool    weights_disk_tier = false;
 
     std::string placement = "auto";    /* all_vram | layer_offload | expert_tiered | auto */
-    /* --embedding-placement and --ngram-placement, as asked (TablePlacement says what each tier
-     * is), and what Engine::plan resolved them to before any rank planned: never Auto. The
-     * embedding's default is Ram; `embedding_placement_given` says whether the operator named it,
-     * because a named tier that cannot be honoured stops the server where the default gives way
-     * to the card with the reason. */
+    /* --embedding-placement and --ngram-placement as given (see TablePlacement), and their
+     * resolved values from Engine::plan before any rank plans (never Auto). The embedding defaults
+     * to Ram; `embedding_placement_given` records whether the operator named it, because a named
+     * tier that cannot be honoured stops the server, while the default falls back to the card with
+     * the reason. */
     TablePlacement embedding_placement = TablePlacement::Ram;
     bool           embedding_placement_given = false;
     TablePlacement ngram_placement     = TablePlacement::Auto;
     TablePlacement embedding_resolved  = TablePlacement::Vram;
     TablePlacement ngram_resolved      = TablePlacement::Disk;
-    /* SET BY THE RESOLVER: the pinned host room the token embedding takes when it resolves to Ram,
-     * a rank, ON TOP OF host_pool_mib -- so the table never takes the experts' share of the pool,
-     * and a dense model that has no pool still has a place for it. */
+    /* Set by the resolver: pinned host MiB per rank for the token embedding when it resolves to
+     * Ram, on top of host_pool_mib, so it never takes the experts' share and a dense model with no
+     * pool still has room for it. */
     int64_t embedding_host_mib = 0;
-    /* --vision-tower-placement: where a model's encoder towers live. A tower is every weight its
-     * architecture declared read once per request (RAD_ACCESS_PER_REQUEST) -- the vision tower,
-     * and the audio encoder where a model has one -- and Vram, the default, keeps it on the card
-     * with the rest. Ram pins it in host memory of its own, `tower_host_mib` a rank on top of
-     * host_pool_mib as the embedding's is, and the encoder's kernels read it over the link in
-     * place, once an image: what it held on the card goes to the KV cache. */
+    /* --vision-tower-placement: where encoder towers live. A tower is every weight declared
+     * RAD_ACCESS_PER_REQUEST (the vision tower, and an audio encoder where present). Vram, the
+     * default, keeps it on the card. Ram pins it in its own host memory, `tower_host_mib` per rank
+     * on top of host_pool_mib like the embedding; the encoder reads it over the link once per
+     * image, and its VRAM goes to the KV cache. */
     TablePlacement tower_placement = TablePlacement::Vram;
     TablePlacement tower_resolved  = TablePlacement::Vram;
     int64_t        tower_host_mib  = 0;
@@ -823,71 +712,65 @@ struct Config {
     int64_t host_pool_total_mib() const { return host_pool_mib + embedding_host_mib + tower_host_mib; }
     bool    deterministic = false;
     int64_t checkpoint_interval = 2048;   /* linear-state checkpoints (spec §7.3) */
-    /* HOW MANY LINEAR-STATE SNAPSHOTS THE SERVER MAY HOLD AT ONCE -- a CAP and not a charge.
-     * The slots are address space in the KV pool and are backed as they are handed out, so a
-     * run that writes no snapshot pays nothing for them and one holding two pays for two. What
-     * it still bounds is the ADDRESS SPACE: a slot is a sizeable fraction of a gigabyte on a
-     * linear-attention model, and the range it reserves is range the paged groups do not get,
-     * so raising this trades addressable context rather than VRAM (spec 7.3, 19.1). */
+    /* Checkpoint intervals one step may carry of a prefill alone in its step, from an interval
+     * boundary past the first (--prefill-span; 1 splits at every interval). The step's rows stay
+     * on the interval-sized pieces a span of 1 cuts, so an architecture that runs row-local work a
+     * piece at a time computes them identically and can overlap one piece's collectives with the
+     * next piece's work. Every other step is planned at ChunkGeometry::shared_tok. Checkpoints
+     * inside a span are not written; those at its end and at a prompt's tail are, where a span of
+     * 1 writes them. */
+    int64_t prefill_span = 1;
+    /* Cap on linear-state (or sliding-window) snapshots held at once, for the whole server. The
+     * slots are pinned host memory, all allocated at startup and never on the card (spec §7.3).
+     * A slot is a sizeable fraction of a gigabyte on a linear-attention model, so raising the cap
+     * trades host RAM for retained checkpoints. */
     int64_t checkpoint_slots = 8;
     bool    prefix_cache = true;
-    /* geometric-backoff | tip-only | keep-all. §19.1 records the default as a GUESS until there is
-     * a workload to measure, and core/mem/prefix.h ships the two ends of the trade beside it for
-     * exactly that measurement -- which needs a way to select them. */
+    /* geometric-backoff | tip-only | keep-all. §19.1 records the default as unmeasured;
+     * core/mem/prefix.h ships the two extremes so they can be compared. */
     std::string checkpoint_policy = "geometric-backoff";
 
     /* ---------------- IDLE SESSION TIERS (spec §7.3) ----------------
      *
-     * A finished turn leaves its prefix in the cache holding KV blocks, which is what makes the
-     * next turn cheap. Those blocks are the most valuable thing in the pool while a session is
-     * live and the least valuable thing in it once the session stops. With a host tier, a
-     * finished conversation is COPIED to host memory at once and its VRAM given up the moment
-     * something wants it -- the expert slab's loan, or a request -- so no threshold decides when
-     * it leaves the card: the copy makes leaving free. A full host tier drops its least recently
-     * used entries. Nothing is written to a drive.
+     * A finished turn's prefix holds KV blocks in the cache, making the next turn cheap. With a
+     * host tier, a finished conversation is copied to host memory at once and its VRAM released
+     * as soon as something needs it (the expert slab's loan, or a request), so no threshold
+     * decides eviction. A full host tier drops its least recently used entries. Nothing is
+     * written to disk. Restoring a 200K-token turn costs a PCIe copy; recomputing it takes
+     * minutes.
      *
-     * Moving is worth it because the alternative is a re-prefill. Recovering a 200K-token turn
-     * costs a copy over PCIe; recomputing it costs minutes. The two are not the same order.
-     *
-     * CAPACITY IS WHAT TURNS THEM ON. Nothing is copied until the host tier has a size: a tier of
-     * zero bytes holds nothing, so the feature is off until an operator says how much memory it
-     * may have. */
+     * The tier is off until it has a size. */
     int64_t prefix_cache_mib = 0;             /* the host tier's size. 0 is off */
-    /* HOW LONG AN UNUSED CONVERSATION IS KEPT, in seconds, whichever tier holds it: VRAM, host
-     * memory, and its snapshots. 0 keeps everything until the memory is wanted. */
+    /* Seconds an unused conversation is kept in any tier (VRAM, host memory, its snapshots). 0
+     * keeps everything until the memory is needed. */
     int64_t prefix_cache_ttl = 3600;
 
-    /* THE CACHE ALWAYS LENDS AND THERE IS NO FLAG FOR IT. It keeps the blocks it is using plus a
-     * buffer it derives, and lends the rest to the expert plane at the addresses it already owns;
-     * see core/mem/kv.h. The buffer's right size is a property of the workload (a prefill chunk,
-     * or the largest recent shortfall) that nobody can state in advance, which is why it is
-     * derived rather than a number to set.
+    /* The cache always lends; there is no flag. It keeps the blocks in use plus a derived buffer
+     * and lends the rest to the expert plane at addresses it already owns (core/mem/kv.h). The
+     * buffer's size depends on the workload (a prefill chunk, the largest recent shortfall), so it
+     * is derived.
      *
-     * The loan allocates nothing, so it does not touch --gpu-headroom-mib: that reserve stays what
-     * a card keeps for the things this engine does not allocate -- chief among them a kernel's
-     * code object, which HIP loads on the kernel's FIRST LAUNCH and not at startup, and which
-     * faults inside the HIP runtime rather than returning an error when there is no room. */
+     * The loan allocates nothing, so --gpu-headroom-mib is unaffected. That reserve covers what
+     * this engine does not allocate, mainly kernel code objects: HIP loads one on the kernel's
+     * first launch, not at startup, and faults inside the runtime rather than returning an error
+     * when there is no room. */
 
-    /* The speculative window: the depth, or under --draft-window adaptive its ceiling. See
-     * core/sched/draft.h. */
-    /* -1 is `auto`: engine_bringup asks rad_arch_probe for the depth THIS container's drafter was
-     * trained at, and a container with no draft head resolves to 0 with a line saying so.
-     *
-     * IT DEFAULTS TO AUTO BECAUSE MERGING A DRAFTER IS THE STATEMENT OF INTENT. rad-kbench and
-     * rad-tune read the container's own operating point; a serving engine that defaulted to off
-     * would leave a deployment that forgot the flag paying for a draft head at convert time,
-     * paying for it again in VRAM, and then running at one token a step -- a small fraction of
-     * the throughput the same container gives at its declared depth. */
+    /* The speculative window: the depth, or under --draft-window adaptive its ceiling
+     * (core/sched/draft.h). -1 is auto: engine_bringup asks rad_arch_probe for the depth this
+     * container's drafter was trained at; a container without a draft head resolves to 0 with a
+     * log line. Auto is the default because a merged drafter states the intent, and rad-kbench
+     * and rad-tune read the same operating point; defaulting to off would pay for the head in
+     * VRAM and still decode one token a step. */
     int     n_spec = -1;                /* --num-speculative-tokens; -1 = auto, 0 = off */
     DraftWindow draft_window = kDraftWindowDefault;   /* --draft-window */
 
     /* ---------------- KL DIVERGENCE AGAINST A REFERENCE (core/kld.h) ----------------
      *
-     * A MODE, LIKE --debug-graph: the engine starts as it would to serve, then runs a fixed
-     * corpus through prefill instead of listening, with a full-vocabulary logits row at every
-     * scored position. `--kld-record DIR` makes THIS model the yardstick and writes its
-     * log-probabilities to DIR once; `--kld-ref DIR` scores this model against what is there, and
-     * only the candidate's own logits are computed. Exactly one of the two. */
+     * A mode, like --debug-graph: the engine starts as for serving, then runs a fixed corpus
+     * through prefill with a full-vocabulary logits row at every scored position instead of
+     * listening. `--kld-record DIR` writes this model's log-probabilities to DIR as the reference;
+     * `--kld-ref DIR` scores this model against them, computing only its own logits. Exactly one
+     * of the two. */
     std::string kld_record;             /* --kld-record DIR */
     std::string kld_ref;                /* --kld-ref DIR */
     std::string kld_corpus;             /* --kld-corpus FILE, read by --kld-record only */
@@ -905,7 +788,7 @@ struct Config {
 
     std::string host = "0.0.0.0";
     /* The chat endpoint's default `reasoning_effort`, empty for the template's own default.
-     * Passed through verbatim: the legal set belongs to the template, not to us. */
+     * Passed through verbatim: the legal set belongs to the template. */
     std::string reasoning_effort;
     /* --reasoning-effort-map FROM=TO,...: an effort a request sends, replaced before the template
      * sees it. */
@@ -921,26 +804,18 @@ struct Config {
      * model: one model is loaded and every request is served by it. */
     std::string served_model_name;
 
-    /* WHAT A REQUEST THAT SENDS NO SAMPLER SETTINGS IS SERVED WITH.
-     *
-     * A checkpoint states the sampling it was tuned for, and serving it at anything else is a
-     * different model. Left alone these are resolved from the container and from the
-     * `generation_config.json` beside it (resolve_sampling_defaults in engine.cpp); set, they win over
-     * both, which is what makes a deployment able to pin a sampler a container gets wrong.
-     *
-     * -1 IS "NOT SET HERE" RATHER THAN A VALUE, because every one of these has a legal setting
-     * that would otherwise be indistinguishable from silence: 0 is a real temperature (greedy),
-     * 0 is a real top_k (off) and 0 is a real min_p. A flag that cannot say "unset" cannot have
-     * anything resolved underneath it. */
+    /* Sampler defaults for a request that sends none. Unset, they resolve from the container and
+     * the `generation_config.json` beside it (resolve_sampling_defaults in engine.cpp), since a
+     * checkpoint is tuned for its stated sampling; set, they override both. -1 means unset,
+     * because 0 is a legal value for each (greedy temperature, top_k at the candidate width, min_p
+     * off). */
     float   sample_temp  = -1.0f;
     int     sample_top_k = -1;
     float   sample_top_p = -1.0f;
     float   sample_min_p = -1.0f;
-    /* THE REST OF THE SAMPLER, each one the default for a request that does not name the field.
-     * Optional rather than negative-for-unset: a presence penalty of -1 and a DRY multiplier of
-     * -1 are settings a request can send, so no value of the field itself can mean "not set".
-     * Unset, a request that sends nothing gets SamplingParams' own value, exactly as before the
-     * flags existed. */
+    /* The remaining sampler defaults for requests that omit the field. Optional, because -1 is a
+     * legal value for some (presence penalty, DRY multiplier). Unset, SamplingParams' own value
+     * applies. */
     std::optional sample_typical_p, sample_rep_penalty, sample_pres_penalty,
                          sample_freq_penalty, sample_dry_multiplier, sample_dry_base,
                          sample_xtc_probability, sample_xtc_threshold;
@@ -960,9 +835,8 @@ struct Config {
     /* --max-queued-requests: requests admitted and unfinished at once, beyond which the answer is
      * 429. 0 is 8 x --max-num-seqs. */
     int64_t max_queued_requests = 0;
-    /* --max-stop-strings / --max-stop-bytes: how many stop strings a request may send, and how
-     * long each may be. Every stop string is searched for in every stretch of generated text, so
-     * these bound what one request can make that scan cost. */
+    /* --max-stop-strings / --max-stop-bytes: count and length limits on a request's stop strings.
+     * Every stop string is searched in all generated text, so these bound that scan's cost. */
     int64_t max_stop_strings = 64;
     int64_t max_stop_bytes = 4096;
 
@@ -975,7 +849,7 @@ struct Config {
     std::string reasoning_format = "auto";
 
     /* ---------------- THE HTTP TRANSPORT ----------------
-     * The values the transport has always used, settable. See TransportOptions (server/http.h). */
+     * See TransportOptions (server/http.h). */
     int     http_threads = 0;                /* 0: one per core, at least 4 */
     int     http_read_timeout_s = 30;
     int     http_write_timeout_s = 600;
@@ -1001,10 +875,9 @@ struct Config {
 
     /* An operator-supplied generation_config.json, overriding the search described above. */
     std::string generation_config;
-    /* --override-chat-template: a Jinja file whose text replaces the chat template the container
-     * (or the checkpoint directory) carries. Everything that reads the template reads this one:
-     * the chat endpoint's rendering, and the reply format derived from it -- reasoning markers and
-     * tool calls. Empty serves the container's. */
+    /* --override-chat-template: a Jinja file replacing the template the container (or checkpoint
+     * directory) carries, for chat rendering and for the reply format derived from it (reasoning
+     * markers, tool calls). Empty serves the container's. */
     std::string override_chat_template;
 
     bool    debug_graph = false;
@@ -1014,23 +887,21 @@ struct Config {
     /* --live: the live view (spec §16). Off by default like everything else in that section. */
     bool    live_view = false;
 
-    /* libref is the ORACLE and the last resort, not a deployment. An op silently falling
-     * back to it is a model running orders of magnitude below the machine with nothing in the
-     * output to say so, so it is refused unless this says otherwise -- deliberately, and by a
-     * flag with `debug` in its name (startup.h, rad_gate_reference_kernels). */
+    /* libref is the oracle and last resort, not a deployment: an op falling back to it runs orders
+     * of magnitude slower with no visible sign. It is refused unless this debug flag is set
+     * (startup.h, rad_gate_reference_kernels). */
     bool    accept_reference_kernels = false;
 
-    /* WHERE EACH OPTION THE OPERATOR SET CAME FROM, keyed by the option table's spelling:
-     * "command line", or the environment variable that supplied it. An option absent here took
-     * its default or was resolved at startup -- the distinction the startup report
-     * (core/diag/diag.h) prints beside every value. */
+    /* Where each operator-set option came from, keyed by the option table's spelling: "command
+     * line" or the supplying environment variable. Absent means default or resolved at startup;
+     * the startup report (core/diag/diag.h) prints this beside every value. */
     std::map given;
 };
 
 }  /* namespace rad */
 
-/* Declared here because config.cpp is owned by the engine, and every tool parses the same flags
- * so that `rad-info --model X` and `radiance --model X` cannot disagree about what a flag means. */
+/* Declared here because config.cpp is owned by the engine, and every tool parses the same flags,
+ * so `rad-info --model X` and `radiance --model X` agree on what a flag means. */
 namespace rad {
 int  config_parse(int argc, char** argv, Config* c);
 void config_usage(const char* argv0);
diff --git a/core/rad_internal.h b/core/rad_internal.h
index 7ff54077..2b17bc83 100644
--- a/core/rad_internal.h
+++ b/core/rad_internal.h
@@ -1,5 +1,5 @@
-/* rad_internal.h -- shared by everything under core/, tools/ and tests/. NOT installed and NOT
- * visible to plugins: plugins see abi/ and nothing else. C++20 is fine here.
+/* rad_internal.h -- shared by everything under core/, tools/ and tests/. Not installed and not
+ * visible to plugins, which see only abi/. C++20 is fine here.
  */
 #pragma once
 #include "rad_abi.h"
@@ -25,20 +25,14 @@ void log_set_level(Log l);
 Log  log_level();
 void log_emit(Log l, const char* file, int line, const char* fmt, ...)
      __attribute__((format(printf, 4, 5)));
-/* When the last line was written (rad_mono_ns), whatever its level: what StallWatch reads as
- * progress. 0 before the first. */
+/* rad_mono_ns of the last line written at any level; StallWatch reads it as progress. 0 before
+ * the first. */
 uint64_t log_last_line_ns();
 
-/* WHICH RANK IS SPEAKING.
- *
- * Every per-rank component -- the pools, the planner, the mover, the sampler -- prints the same
- * sentence once per rank, so with nothing to distinguish them a tp2 startup prints each of those
- * lines twice with no way to tell which card it is about. The tag is a SCOPE rather than
- * an argument because the components doing the printing are three layers down, and a rank
- * threaded through every log call is a rank that will be missing from the next one.
- *
- * Off unless log_rank_tags(true) is called: at tp 1 there is nothing to disambiguate, and every
- * tool that is not the engine has one rank by construction. */
+/* Rank tags on log lines. Per-rank components (pools, planner, mover, sampler) print the same
+ * line once per rank, so under TP each line needs its rank. LogRank sets the tag as a scope
+ * because the printers are several layers down, where threading a rank argument through every
+ * call is error-prone. Off unless log_rank_tags(true): at tp 1, and in tools, there is one rank. */
 void log_rank_tags(bool on);
 
 class LogRank {
@@ -61,8 +55,8 @@ private:
 #define RAD_DEBUG(...) RAD_LOG(Debug, __VA_ARGS__)
 #define RAD_TRACE(...) RAD_LOG(Trace, __VA_ARGS__)
 
-/* The same with the level as a VALUE rather than an enumerator name, for the sites where whether
- * something is a warning depends on what was found. */
+/* RAD_LOG with the level as a runtime value, for sites where the level depends on what was
+ * found. */
 #define RAD_LOG_AT(lvl, ...)                                                     \
     do { ::rad::Log _l = (lvl);                                                  \
          if ((int)_l <= (int)::rad::log_level())                                 \
@@ -85,17 +79,21 @@ inline int64_t align_up(int64_t v, int64_t a) { return (v + a - 1) / a * a; }
 /* Human-readable byte counts, for every report that prints a size. */
 std::string humanb(int64_t bytes);
 
-/* ONE MONOTONIC CLOCK, so that everything reasoning about elapsed time is reasoning about the
- * same elapsed time. The idle-session tiers write a timestamp when an entry is used and read
- * one when deciding what has gone cold; those two calls live in different translation units,
- * and two clocks there would make the thresholds mean nothing in particular. Monotonic and
- * not wall time: a tier that demoted an hour of sessions because NTP stepped the clock would
- * be correct by its own arithmetic and wrong by any other measure. */
+/* The one monotonic clock for all elapsed-time logic. The idle-session tiers stamp an entry on
+ * use and compare against the stamp in another translation unit, so both sides must use the same
+ * clock. Monotonic so an NTP step cannot age entries. */
 uint64_t rad_mono_ns();
 
-/* Split on whitespace -- what RAD_C_IN's set is encoded as. */
+/* Split on spaces, tabs and commas: the encoding of RAD_C_IN's set. */
 std::vector split_ws(std::string_view s);
 
+/* The strings joined with `sep` between them. */
+inline std::string join(const std::vector& v, const char* sep = ", ") {
+    std::string s;
+    for (size_t i = 0; i < v.size(); ++i) { if (i) s += sep; s += v[i]; }
+    return s;
+}
+
 /* ------------------------------------------------------------------ geometry */
 /* A resolved parameter set: the geometry after ranges are collapsed to a band's upper bound.
  * Owns its strings, because a RadParam's char* may point into a plugin the core outlives. */
@@ -103,18 +101,14 @@ class Geometry {
 public:
     Geometry() = default;
 
-    /* THE RadParam VIEW IS KEPT CURRENT BY EVERY WRITE, never built on first read. It holds char*
-     * into this object's own strings, and a view rebuilt lazily from a const reader is a write
-     * that two readers can make at once: the sizing declares of one rank all read the real
-     * program's geometries side by side (Engine::probe_arena_levels), and one clearing the view
-     * while another filled it is the heap corruption that crashed startup. So params() writes
-     * nothing, and a Geometry nobody is writing can be read from any number of threads.
+    /* Every write keeps the RadParam view current; it is never built lazily on read. A lazy
+     * rebuild from a const reader is a write, and concurrent readers exist (the sizing declares
+     * in Engine::probe_arena_levels read the same geometries in parallel). So params() writes
+     * nothing, and an unwritten Geometry is safe to read from any number of threads.
      *
-     * A copy takes the storage and builds its own view, because the source's points into the
-     * source. A move takes the view along with the storage: the vectors hand over their arrays,
-     * so every string stays where it was and every pointer stays good. The moved-from object is
-     * emptied, view included, so it is a valid empty geometry rather than one whose view names
-     * strings it no longer owns. */
+     * The view holds char* into this object's strings. A copy rebuilds its own view. A move
+     * takes the view too, since the vectors hand over their arrays and the pointers stay valid;
+     * the source is cleared, view included, leaving a valid empty geometry. */
     Geometry(const Geometry& o)
         : keys_(o.keys_), svals_(o.svals_), ivals_(o.ivals_), dvals_(o.dvals_), kinds_(o.kinds_) {
         rebuild();
@@ -149,9 +143,8 @@ public:
 
     void set_i(std::string_view k, long long v);
     void set_s(std::string_view k, std::string_view v);
-    /* eps, rope theta, an attention scale. Carried so they reach RadArgs.p, and NOT matched on:
-     * constraint_holds() never sees a float, because a tolerance is not a predicate and a kernel
-     * that discriminates on eps to that precision has a bug. */
+    /* Floats (eps, rope theta, an attention scale) reach RadArgs.p but are never matched on; see
+     * constraint_holds(). */
     void set_f(std::string_view k, double v);
     bool get_i(std::string_view k, long long* out) const;
     bool get_f(std::string_view k, double* out) const;
@@ -167,6 +160,7 @@ public:
 private:
     std::vector keys_, svals_;
     std::vector    view_;
+    size_t slot(std::string_view k, int kind);   /* find or append k, set its kind */
     void rebuild();
     void clear() noexcept {
         keys_.clear(); svals_.clear(); view_.clear(); ivals_.clear(); dvals_.clear();
@@ -177,13 +171,11 @@ private:
     std::vector         kinds_;
 };
 
-/* Does this geometry satisfy this constraint? The one place the matching rule lives.
- *
- * A float parameter can never satisfy one: get_i and get_s both miss a RAD_P_F64 slot, so a
- * constraint naming a float key does not hold, which is the correct answer. A tolerance is not a
- * predicate, and a kernel that discriminates on eps to that precision has a bug. */
+/* Whether the geometry satisfies the constraint; the one place the matching rule lives. A
+ * constraint on a float key never holds (get_i and get_s miss RAD_P_F64 slots): a tolerance is
+ * not a predicate, and a kernel that discriminates on eps that precisely has a bug. */
 bool constraint_holds(const RadConstraint& c, const Geometry& g);
-/* Why not -- for the selection table's miss column (spec §16). */
+/* Why not, for the selection table's miss column (spec §16). */
 std::string constraint_why(const RadConstraint& c, const Geometry& g);
 
 }  /* namespace rad */
diff --git a/core/runtime/arena.cpp b/core/runtime/arena.cpp
index 82d0919e..19dab4c3 100644
--- a/core/runtime/arena.cpp
+++ b/core/runtime/arena.cpp
@@ -9,16 +9,14 @@ int Arena::init(int64_t plan_bytes, int64_t scratch_bytes, int kind, int regions
     release();
     if (plan_bytes < 0 || scratch_bytes < 0 || regions < 1) return RAD_E_INVAL;
 
-    /* The scratch region starts on a page boundary. Kernels that want 4 KiB alignment for a
-     * workspace get it for free, and the ones that do not are not charged for it -- the padding is
-     * one page against an arena measured in hundreds of megabytes. */
+    /* Scratch starts on a page boundary, so a workspace gets 4 KiB alignment for at most one
+     * page of padding. */
     const int64_t off   = align_up(plan_bytes, RAD_ALIGN_UNIT);
     const int64_t pitch = align_up(scratch_bytes, RAD_ALIGN_UNIT);
     const int64_t tail  = pitch * regions;
     int64_t       total = off + tail;
 
-    /* A zero-byte arena would hand every buffer a null base and turn a plan bug into a segfault
-     * with no name on it. One page instead, so a stray offset lands somewhere reportable. */
+    /* Never zero bytes: a null base would turn a plan bug into an anonymous segfault. */
     if (total == 0) total = RAD_ALIGN_UNIT;
 
     void* p = rad_dev_alloc(total, kind);
@@ -50,13 +48,25 @@ void Arena::release() {
 }
 
 
-/* See arena.h. The walk is Ctx::bind_arena's, lifted here whole so the budget resolver and the
- * allocation cannot disagree.
- *
- * THIS ASSUMES the plan gives host-domain buffers their own offset space. If it interleaves them
- * with device buffers instead, both arenas come out sparse: correct, but paying VRAM for host
- * activations. BufferInfo carries one arena_offset and one total, so the contract has to be stated
- * somewhere and this is it. */
+int64_t arena_host_bytes(const Program& P) {
+    int64_t host_hw = 0;
+    for (size_t i = 1; i < P.buffers.size(); ++i) {
+        const BufferInfo& bi = P.buffers[i];
+        if (bi.arena_offset < 0 || bi.decl.domain != RAD_DOMAIN_HOST) continue;
+        int64_t bytes = bi.bytes;
+        if (bytes <= 0) {
+            int64_t n = 1;
+            for (uint32_t d = 0; d < bi.decl.rank; ++d) n *= bi.decl.shape[d];
+            bytes = rad_dtype_bytes(bi.decl.dtype, n);
+        }
+        host_hw = std::max(host_hw, bi.arena_offset + bytes);
+    }
+    return host_hw;
+}
+
+/* Assumes the plan gives host-domain buffers their own offset space (BufferInfo carries one
+ * arena_offset). If it interleaved them with device buffers, both arenas would come out sparse:
+ * correct, but paying VRAM for host activations. */
 int64_t arena_plan_bytes(const Program& P, int64_t* dev_out, int64_t* total_out) {
     int64_t dev_hw = 0, host_hw = 0;
     for (size_t i = 1; i < P.buffers.size(); ++i) {
@@ -74,8 +84,7 @@ int64_t arena_plan_bytes(const Program& P, int64_t* dev_out, int64_t* total_out)
     /* With no host-domain buffers the plan's own total is authoritative: it may carry alignment
      * slack the high-water mark does not see. */
     int64_t dev_bytes = host_hw > 0 ? dev_hw : std::max(dev_hw, P.arena_bytes);
-    /* The staging region sits above every buffer, so it is its own term, whichever of the two
-     * above set the high-water mark. */
+    /* The staging region sits above every buffer, so it is a separate term. */
     if (P.arena_stage_bytes > 0 && P.arena_stage_off >= 0)
         dev_bytes = std::max(dev_bytes, P.arena_stage_off + P.arena_stage_bytes);
     int64_t total = align_up(dev_bytes, RAD_ALIGN_UNIT) +
@@ -85,4 +94,11 @@ int64_t arena_plan_bytes(const Program& P, int64_t* dev_out, int64_t* total_out)
     if (total_out) *total_out = total;
     return total;
 }
+int arena_level_for(const std::vector& level_rows, int64_t rows) {
+    int level = 0;
+    for (size_t k = 1; k < level_rows.size(); ++k)
+        if (level_rows[k] >= rows && (level == 0 || level_rows[k] < level_rows[(size_t)level]))
+            level = (int)k;
+    return level;
+}
 }  /* namespace rad */
diff --git a/core/runtime/arena.h b/core/runtime/arena.h
index f3e348d2..8eb96a00 100644
--- a/core/runtime/arena.h
+++ b/core/runtime/arena.h
@@ -1,22 +1,16 @@
-/* arena.h -- ONE contiguous allocation, sized by the buffer plan at load and never allocated from
+/* arena.h -- one contiguous allocation, sized by the buffer plan at load and never allocated from
  * at runtime.
  *
- * There is deliberately no allocate() on this class. If there were one somebody would eventually
- * call it from inside rad_arch_step, and an allocator on the step path is precisely the class of
- * dynamic behaviour this engine exists to remove (spec §3.1). Offsets come from the buffer plan,
- * which computed liveness over the declared op list and is conservative on purpose: a plan that is
- * correct for the worst step is correct for every step. The arena only owns the block those
- * offsets index into.
+ * There is deliberately no allocate(): an allocator on the step path is the dynamic behaviour this
+ * engine exists to remove (spec §3.1). Offsets come from the buffer plan, which computes liveness
+ * over the declared op list for the worst step; the arena only owns the block they index into.
  *
- * The scratch region sits at the tail and is shared by every op on a stream. That is safe and not
- * merely convenient: launches on one stream execute in order, so no two kernels' scratch lifetimes
- * overlap. A context's second lane is a second stream, where that order does not hold, so a program
- * that declares one gets a second region and each lane's kernels are handed their own
- * (Program::scratch_regions). A lane used without that declaration shares region 0, and there
- * Ctx::issue orders a scratch user behind one on the other lane that nothing has ordered it after
- * yet. Program::scratch_bytes is the largest single kernel's requirement, so a region of that size
- * serves all of them -- and if a kernel asks for more than the plan reserved, prepare refuses by
- * name rather than handing it a short buffer.
+ * Scratch sits at the tail and is shared by every op on a stream, which is safe because launches
+ * on one stream execute in order. A context's second lane is a second stream, so a program that
+ * declares one gets a second region per lane (Program::scratch_regions). A lane used without that
+ * declaration shares region 0, and Ctx::issue orders a scratch user behind an unordered one on the
+ * other lane. Program::scratch_bytes is the largest single kernel's requirement; a kernel asking
+ * for more is refused by name in prepare.
  */
 #pragma once
 #include "../rad_core.h"
@@ -30,9 +24,9 @@ public:
     Arena(const Arena&) = delete;
     Arena& operator=(const Arena&) = delete;
 
-    /* `kind` is a RAD_MEM_* class. The device arena is RAD_MEM_DEVICE; a program with
-     * RAD_DOMAIN_HOST buffers gets a second arena in RAD_MEM_HOST. `regions` scratch regions of
-     * `scratch_bytes` each sit at the tail, one per lane (Program::scratch_regions). */
+    /* `kind` is a RAD_MEM_* class: RAD_MEM_DEVICE for the device arena, RAD_MEM_HOST for the
+     * second arena a program with RAD_DOMAIN_HOST buffers gets. `regions` scratch regions of
+     * `scratch_bytes` each sit at the tail, one per lane. */
     int  init(int64_t plan_bytes, int64_t scratch_bytes, int kind, int regions = 1);
     void release();
 
@@ -58,14 +52,21 @@ private:
 };
 
 
-/* THE ARENA'S SIZE, COMPUTED WITHOUT ALLOCATING IT. Two callers need the same answer at two
- * different times: Ctx::bind_arena, which allocates it at the end of startup, and the VRAM budget
- * resolver, which has to subtract it from the card BEFORE the pools are allocated near the top of
- * startup. Two copies of this walk would agree today and drift the first time the plan grows a
- * domain -- and the failure would be a budget that overcommits the card by exactly the difference.
+/* The arena's size, computed without allocating it. Shared by Ctx::bind_arena (allocates at the
+ * end of startup) and the VRAM budget resolver (subtracts it before the pools are allocated), so
+ * the two cannot drift apart and overcommit the card.
  *
- * `dev_out` is what the device arena's init() will be given as plan_bytes; `total_out` is what it
- * will actually allocate, plan and scratch both padded to RAD_ALIGN_UNIT as Arena::init pads them.
+ * `dev_out` is the plan_bytes the device arena's init() receives; `total_out` is what it
+ * allocates, plan and scratch both padded to RAD_ALIGN_UNIT as Arena::init pads them.
  * Returns the total. */
 int64_t arena_plan_bytes(const Program& P, int64_t* dev_out, int64_t* total_out);
+
+/* The host activation arena's size (the RAD_DOMAIN_HOST buffers), which Ctx::bind_arena pins and
+ * maps at the end of startup; 0 when the program declares none. */
+int64_t arena_host_bytes(const Program& P);
+
+/* The arena level a step of `rows` tokens runs at: the smallest level that holds it, or 0 (the
+ * full plan) when none does. `level_rows[k]` is the largest step level k serves; entry 0 is the
+ * full plan and is never chosen by size. */
+int arena_level_for(const std::vector& level_rows, int64_t rows);
 }  /* namespace rad */
diff --git a/core/runtime/ctx.cpp b/core/runtime/ctx.cpp
index 83dd451b..aca7f695 100644
--- a/core/runtime/ctx.cpp
+++ b/core/runtime/ctx.cpp
@@ -1,6 +1,5 @@
-/* ctx.cpp -- everything the run phase does that is not the hot path: bringing the arena and the
- * plans up, driving a step, the routing handoff, and the opt-in per-op timing. The hot path itself
- * is issue.cpp, kept in its own translation unit so it stays readable at the size it has to be.
+/* ctx.cpp -- the run phase outside the hot path: arena and plan bring-up, the step driver, the
+ * routing handoff and opt-in per-op timing. The hot path is issue.cpp.
  */
 #include 
 #include "ctx.h"
@@ -27,6 +26,7 @@ int Ctx::init(const CtxDesc& d) {
     device_    = d.device;
     record_passes_ = d.record_passes;
     residency_ = d.residency;
+    registry_ = d.registry;
     kv_        = d.kv;
     arch_step_ = d.arch_step;
     profiling_ = d.profile_ops;
@@ -39,14 +39,13 @@ int Ctx::init(const CtxDesc& d) {
         stream_     = d.stream;
         own_stream_ = false;
     } else {
-        /* Ordinary priority. The mover runs on its own stream and the compute stream waits on its
-         * events (spec §5.4); making compute high-priority would let it preempt the transfers it
-         * is about to wait for, which is exactly backwards. */
+        /* Ordinary priority: compute waits on the mover's events (spec §5.4), so a high-priority
+         * compute stream would preempt the transfers it is about to wait for. */
         RAD_TRY(rad_stream_create(&stream_, 0));
         own_stream_ = true;
     }
 
-    /* The second lane is NOT created here. See lane_init(). */
+    /* The second lane is created lazily; see lane_init(). */
 
     int s = prepare();
     if (s < 0) { shutdown(); return s; }
@@ -56,11 +55,8 @@ int Ctx::init(const CtxDesc& d) {
 void Ctx::shutdown() {
     oracle_close();
     xp_close();
-    /* The one host synchronisation in the whole component, and it is at teardown rather than on
-     * the step path. Everything below frees memory the stream may still be reading or writing --
-     * the routing staging is the destination of a copy nobody waited on by design (spec §5.5), and
-     * the arena is every kernel's operands. Freeing either out from under an in-flight stream is a
-     * use-after-free that reproduces once a week and never under a debugger. */
+    /* Teardown sync, before freeing memory the streams may still use: the routing staging is the
+     * destination of unwaited copies (spec §5.5) and the arena holds every kernel's operands. */
     if (stream_) rad_stream_sync(stream_);
     if (lane1_) rad_stream_sync(lane1_);
 
@@ -80,9 +76,7 @@ void Ctx::shutdown() {
     if (route_pool_) { rad_dev_free(route_pool_, RAD_MEM_HOST_PINNED); route_pool_ = nullptr; }
     if (route_dev_)  { rad_dev_free(route_dev_, RAD_MEM_DEVICE);        route_dev_  = nullptr; }
 
-    /* The expert pointer tables. Freed after the stream syncs above for exactly the reason those
-     * syncs exist: the device half is the source operand of a grouped GEMM and the host half is
-     * the source of a copy on that stream. */
+    /* After the syncs: the device half is a grouped GEMM operand, the host half a copy source. */
     free_weight_tables();
 
     arena_.release();
@@ -113,29 +107,23 @@ int Ctx::prepare() {
     oracle_open();
     RAD_TRY(bind_arena());
     RAD_TRY(bind_buffers());
-    RAD_TRY(bind_weights(/*refresh_only=*/false));
+    RAD_TRY(bind_weights());
     RAD_TRY(bind_weight_tables());
     RAD_TRY(bind_ops());
     RAD_TRY(bind_routing());
     RAD_TRY(bind_profiling());
-    /* Recorded passes need a backend that records, and are off for everything that has to see
-     * each issue: the per-op profile, the oracle, and the argument digest. */
-    tape_on_ = record_passes_ && tape_supported() && !profiling_ && !oracle_ &&
-               std::getenv("RADIANCE_DEBUG_ARGSHA") == nullptr;
+    /* Recorded passes need a recording backend, and are off whenever every issue must be seen:
+     * per-op profile, oracle. */
+    tape_on_ = record_passes_ && tape_supported() && !profiling_ && !oracle_;
     return RAD_OK;
 }
 
 int Ctx::bind_arena() {
     Program& P = *program_;
 
-    /* The buffer plan hands us one offset per buffer, and arena_plan_bytes() turns those into the
-     * two numbers Arena::init wants. THE WALK LIVES THERE AND NOT HERE because the VRAM budget
-     * resolver has to subtract this allocation from the card before any of it exists -- see
-     * core/mem/vram_budget.cpp. What stays here is the part that can only be done at bind time:
-     * refusing a plan that did not run, and filling in a size the plan left at zero.
-     *
-     * Where a program has RAD_DOMAIN_HOST buffers -- host-site execution, spec §5.1 -- those
-     * offsets cannot index the same block, so there are two arenas. */
+    /* Sizing is arena_plan_bytes(), shared with the VRAM budget (core/mem/vram_budget.cpp). Here:
+     * refuse a plan that did not run, and fill in sizes the plan left at zero. RAD_DOMAIN_HOST
+     * buffers (host-site execution, spec §5.1) get a second arena. */
     int64_t host_hw = 0;
     for (size_t i = 1; i < P.buffers.size(); ++i) {
         BufferInfo& bi = P.buffers[i];
@@ -159,40 +147,23 @@ int Ctx::bind_arena() {
     arena_plan_bytes(P, &dev_bytes, &total);
 
     RAD_TRY(arena_.init(dev_bytes, P.scratch_bytes, RAD_MEM_DEVICE, std::max(P.scratch_regions, 1)));
-    /* SAY WHAT THIS COSTS, BECAUSE NOTHING ELSE DOES. The allocation is in no pool, and it is not
-     * something --gpu-headroom-mib can cover: it scales with max_tok, so any round number an
-     * operator picks either under-reserves or wastes VRAM. On a part whose experts do not fit,
-     * waste is not free -- a GiB of headroom nothing uses is about 1.4 ms a decode step, because
-     * that GiB is experts that would otherwise be resident. So it is computed and charged by name:
-     * core/mem/vram_budget.cpp does the charging, this line is the receipt, and the two numbers
-     * must agree. */
+    /* The arena is in no pool and scales with max_tok, so core/mem/vram_budget.cpp charges it by
+     * name rather than leaving it to --gpu-headroom-mib. This log line must agree with that
+     * charge. */
     RAD_INFO("arena: %s device + %d x %s scratch = %s, charged to the VRAM budget before it was "
              "split", humanb(dev_bytes).c_str(), arena_.scratch_regions(),
              humanb(P.scratch_bytes).c_str(), humanb(total).c_str());
 
     if (host_hw > 0) {
-        /* RAD_MEM_HOST_MAPPED AND NOT RAD_MEM_HOST, AND THAT IS THE WHOLE OF HOW A HOST RUN
-         * REACHES THE DEVICE GRAPH.
-         *
-         * A host-site op writes a host-domain buffer and something downstream reads it on the
-         * device. NOTHING IN THIS RUNTIME COPIES BETWEEN THE TWO ARENAS -- there is no transfer op
-         * and no implicit staging in rad_issue, and the planner's `link_crossings` is an objective
-         * it minimises, not a mechanism it provides. With plain RAD_MEM_HOST the host arena is
-         * "ordinary malloc'd pages the GPU has never been shown" (core/device/hip.cpp), so the
-         * device side of that hand-off had no way to read it and host-site execution could not
-         * complete a step. Mapped, the same allocation is addressable from a kernel over the link
-         * and the crossing IS the read -- which is row three of spec 5.1 applied to an activation
-         * rather than to a weight.
-         *
-         * The cost is that every device access to a host-domain buffer is a link read, so this is
-         * for the narrow hand-off at a host run's edge and not for a hot activation. A buffer's
-         * domain is declared by the ARCHITECTURE, so that judgement stays where it belongs. */
+        /* RAD_MEM_HOST_MAPPED, not RAD_MEM_HOST: nothing copies between the two arenas, so device
+         * kernels must read host-domain buffers directly over the link (spec §5.1, row three,
+         * applied to activations). Plain RAD_MEM_HOST pages are not device-visible
+         * (core/device/hip.cpp). Every device access is a link read, so host-domain buffers suit
+         * only the hand-off at a host run's edge; the architecture declares the domain. */
         RAD_TRY(host_arena_.init(host_hw, 0, RAD_MEM_HOST_MAPPED));
-        /* ONE POINTER SERVES BOTH SIDES, AND THAT IS CHECKED RATHER THAN ASSUMED. bind_buffers
-         * stores a single base per buffer, which is correct exactly while the mapped allocation's
-         * host and device views share an address -- true under HIP's unified addressing and true
-         * by construction on the host backend. A backend where they differ gets a refusal here
-         * instead of handing one of the two sides a pointer into nothing. */
+        /* bind_buffers stores one pointer per buffer, valid only while the mapped allocation's
+         * host and device views share an address (true under HIP unified addressing and on the
+         * host backend). Checked, not assumed. */
         void* hb = host_arena_.base();
         void* db = rad_dev_device_ptr(hb);
         if (!db || db != hb) {
@@ -235,8 +206,7 @@ int Ctx::bind_buffers() {
             return RAD_E_FULL;
         }
 
-        /* rad_buf_ptr is arena_base + BufferInfo::arena_offset, and nothing else -- there is no
-         * table walk and no allocator between a handle and its bytes. */
+        /* rad_buf_ptr is arena_base + BufferInfo::arena_offset. */
         t.data  = a.base() + bi.arena_offset;
         bi.ptr  = t.data;
         buf_bits_[i] = rad_dtype_bits(bi.decl.dtype);
@@ -255,7 +225,7 @@ int Ctx::add_level(int64_t rows, const std::vector& offset,
     std::vector t = level_tmpl_[0];
     for (size_t i = 1; i < P.buffers.size(); ++i) {
         const BufferInfo& bi = P.buffers[i];
-        /* THE HOST ARENA AND THE FIXED REGION ARE NOT LEVELLED: their template is level 0's. */
+        /* The host arena and the fixed region are not levelled: level 0's template. */
         if (bi.decl.domain == RAD_DOMAIN_HOST || bi.decl.kind != RAD_BUF_TRANSIENT) {
             if (offset[i] != bi.arena_offset) return RAD_E_STATE;
             continue;
@@ -288,50 +258,33 @@ int Ctx::set_level(int level) {
     return RAD_OK;
 }
 
-int Ctx::bind_weights(bool refresh_only) {
+/* The weights' addresses as the load phase left them. A weight the mover relocates afterwards is
+ * read through the ResidencyTable (sync_residency), never through its template. */
+int Ctx::bind_weights() {
     Program& P = *program_;
-    ++w_tmpl_epoch_;
-    if (!refresh_only) {
-        w_tmpl_.assign(P.weights.size(), RadTensor{});
-        w_bits_.assign(P.weights.size(), 0);
-        w_gen_.assign(P.weights.size(), 0);
-        waited_gen_.assign(P.weights.size(), UINT32_MAX);
-        w_direct_.assign(P.weights.size(), 0);
-    }
+    w_tmpl_.assign(P.weights.size(), RadTensor{});
+    w_bits_.assign(P.weights.size(), 0);
+    waited_gen_.assign(P.weights.size(), UINT32_MAX);
+    w_direct_.assign(P.weights.size(), 0);
 
     for (size_t i = 1; i < P.weights.size(); ++i) {
-        WeightInfo& wi = P.weights[i];
-        const uint32_t gen = wi.generation.load(std::memory_order_acquire);
-        if (refresh_only && w_gen_[i] == gen) continue;
-
+        const WeightInfo& wi = P.weights[i];
         RadTensor& t = w_tmpl_[i];
-        /* The stored dtype is what the resolved kernel's layout hook asked for; the logical dtype
-         * is what the plugin declared. The kernel reads the layout it chose, so the stored one
-         * wins where the layout pass filled it in.
+        /* Stored dtype (from the resolved kernel's layout hook) wins over the declared one, since
+         * the kernel reads the layout it chose.
          *
-         * THE SHAPE IS THE DECLARED ONE and the dtype is the stored one, which is a seam worth
-         * naming rather than a symmetry. WeightInfo DOES carry stored_shape -- the layout pass
-         * fills it beside stored_dtype -- and this deliberately does not use it, because a kernel
-         * whose layout reshapes has to keep working out its own stride from the geometry either
-         * way: a row-sharded weight's stored shape is the whole tensor's, not this rank's.
-         *
-         * So a layout that changes the WIDTH (libr4d's fp8 lm_head appends each row's scales to
-         * its own row) is invisible here, and its kernel derives the stride from the same rule its
-         * layout hook used. What keeps the two honest is the layout TAG the engine checks at load,
-         * not a shape it could compare. The declared shape is already divided by world_size,
-         * because the plugin declares dimensions per rank (spec §9). */
+         * The shape is deliberately the declared one, not WeightInfo::stored_shape: a row-sharded
+         * weight's stored shape is the whole tensor's, not this rank's, so a re-laying kernel
+         * derives its own stride anyway (e.g. libr4d's fp8 lm_head appends row scales to each
+         * row). Consistency is enforced by the layout tag checked at load. The declared shape is
+         * per rank (spec §9). */
         t.dtype = wi.stored_dtype != RAD_DT_INVALID ? wi.stored_dtype : wi.decl.dtype;
         t.rank  = wi.decl.rank;
         for (uint32_t d = 0; d < wi.decl.rank && d < RAD_MAX_RANK; ++d) t.shape[d] = wi.decl.shape[d];
         rad_tensor_pack(&t);
         t.data  = wi.ptr;
         w_bits_[i] = rad_dtype_bits(t.dtype);
-        w_gen_[i]  = gen;
     }
-    /* A rebinding can move any template, and a table entry the residency table has no slot for
-     * reads its template: every table resolves every entry at its next issue. */
-    if (refresh_only)
-        for (WeightTable& t : wtabs_) if (t.checked) { t.full = true; t.pend.clear(); }
     return RAD_OK;
 }
 
@@ -347,11 +300,10 @@ int Ctx::bind_ops() {
     issue_table_.clear();
     gate_params_.clear();
 
-    int64_t n_bands_total = 0, n_plans = 0;
-    for (auto& o : P.ops) { n_bands_total += (int64_t)o.bands.size(); }
-    n_plans = n_bands_total * RAD_N_DOMAINS;
+    int64_t n_bands_total = 0;
+    for (auto& o : P.ops) n_bands_total += (int64_t)o.bands.size();
     band_table_.reserve((size_t)n_bands_total);
-    issue_table_.reserve((size_t)n_plans);
+    issue_table_.reserve((size_t)(n_bands_total * RAD_N_DOMAINS));
 
     for (size_t i = 1; i < P.ops.size(); ++i) {
         OpInfo& oi = P.ops[i];
@@ -361,7 +313,7 @@ int Ctx::bind_ops() {
         p.n_bands  = (int32_t)oi.bands.size();
         p.plan_off = (int32_t)issue_table_.size();
         p.n_opd_schema = oi.schema ? (int32_t)oi.schema->n_operands : -1;
-        /* Matched by name once, here, rather than on the issue path -- see OpPlan::billed. */
+        /* Matched by name once here, not on the issue path; see OpPlan::billed. */
         p.billed     = (oi.op == "all_reduce");
         p.collective = p.billed;
 
@@ -374,11 +326,11 @@ int Ctx::bind_ops() {
                 if (r && r.row && r.row->info && r.row->info->launch) {
                     ip.row     = r.row;
                     ip.launch  = r.row->info->launch;
+                    ip.ranged_div = r.ranged_div;
                     if (r.row->collective) p.collective = true;
 
-                    /* Bound once. args.p views the frozen geometry inside Program::ops, which is
-                     * why declare must not touch a Resolved after this point: the vector would
-                     * reallocate and every one of these would dangle. */
+                    /* args.p views the frozen geometry inside Program::ops; declare must not
+                     * touch a Resolved after this, or these pointers dangle. */
                     ip.args.t             = tbuf_;
                     ip.args.n_t           = 0;
                     ip.args.p             = r.geom.params();
@@ -388,8 +340,8 @@ int Ctx::bind_ops() {
                     ip.args.instance      = r.instance;
                     ip.args.rank          = rank_;
                     ip.args.world_size    = world_size_;
-                    /* A launch that ends its own hold on the link is handed the word the hold is
-                     * kept in, as one parameter more after the geometry's -- when it holds one. */
+                    /* A launch that ends its own link hold gets the hold word as an extra
+                     * `link_gate` parameter after the geometry's. */
                     if (r.row->releases_link)
                         if (void* g = rad_link_gate(stream_)) {
                             std::vector& v =
@@ -417,15 +369,12 @@ int Ctx::bind_ops() {
             }
         }
 
-        /* Execution site. Site is a property of the weights (spec §5.1), so an op whose every
-         * weight operand was placed on the host runs its host kernel and everything else runs on
-         * the device. An op with no weights stays on the device; the planner overrides through
-         * set_op_domain, which is where the "contiguous host runs" objective actually lands.
+        /* Execution site follows the weights (spec §5.1): an op whose every weight is on the host
+         * runs its host kernel, everything else the device. An op with no weights stays on the
+         * device; the planner overrides through set_op_domain.
          *
-         * ON THE HOST BACKEND (no card visible: CPU-only serving) the device domain is the host's
-         * own memory and an op with no device kernel in any band runs its host kernel -- the
-         * whole model on libavx (or libref) with no switch to set. An op that does carry device
-         * rows there is a test registering fakes, and keeps them. */
+         * On the host backend (CPU-only), an op with no device kernel in any band runs its host
+         * kernel (libavx or libref). Device rows there come from tests registering fakes. */
         int dom = RAD_DOMAIN_DEVICE;
         if (device_is_host()) {
             bool any_device = false;
@@ -440,9 +389,8 @@ int Ctx::bind_ops() {
                 const WeightInfo* wi = P.weight(w);
                 if (!wi || wi->site != Site::Host) { all_host = false; break; }
             }
-            /* ...and whether that host kernel can READ the weights, which is a separate question
-             * from whether one exists. The planner asked for the host; the device is always a
-             * correct answer, so this is a fallback and a warning rather than a refusal. */
+            /* The host kernel must also read the stored layout. The device is always correct,
+             * so this falls back with a warning rather than refusing. */
             std::string why;
             if (all_host && check_domain_layout((rad_op)i, RAD_DOMAIN_HOST, &why) < 0) {
                 RAD_WARN("op '%s' was placed on the host and runs on the device instead: %s",
@@ -461,27 +409,16 @@ int Ctx::bind_ops() {
     return RAD_OK;
 }
 
-/* CAN THE KERNEL THAT WOULD SERVE THIS OP ON `domain` READ THE BYTES THE CONTAINER HOLDS?
+/* Whether the kernel serving this op on `domain` can read the bytes the container holds.
  *
- * A weight is stored ONCE, in whatever arrangement the kernel that claimed it at declare asked
- * for (spec 4.2), and that claimant is always a DEVICE row: rad_builder.cpp exempts the host
- * domain from the layout claim deliberately, because libref declares no layout for anything and
- * every re-laying device kernel would otherwise collide with its own reference fallback and no
- * model would declare at all.
+ * A weight is stored once, in the arrangement its claiming kernel asked for (spec 4.3), and the
+ * claimant is a device row wherever one reads the weight: rad_builder.cpp lets a host row claim
+ * only what no device row did. A host kernel reading as declared would see e.g. libr4d's fp8a8
+ * WMMA fragment order -- same N*K bytes, so every shape check passes -- and compute plausible
+ * wrong answers. The load-time tag check in engine_bringup only checks the claiming row.
  *
- * So moving an op to a domain whose kernel reads its weights AS DECLARED hands that kernel a
- * plane it cannot read. libr4d stores an fp8a8 weight in WMMA fragment order -- the same N*K
- * bytes in a different arrangement -- so the byte count matches, every shape check passes, and
- * the op computes a plausible wrong answer for the life of the process. Two readings of one
- * permuted plane are uncorrelated tensors, which is a model that serves and lies.
- *
- * The load-time tag check in engine_bringup cannot see this: it compares the container against
- * the tag the claimant recorded, and both of those are the device row's. This asks the same
- * question of the kernel that will actually run.
- *
- * `why` gets the sentence; the caller decides whether it is a warning or a refusal, because the
- * two callers differ. The planner ASKED for the host and can be given the device instead, which
- * is always a correct answer; an explicit set_op_domain has no such fallback. */
+ * `why` gets the message. The caller picks the severity: the planner's host request falls back
+ * to the device, an explicit set_op_domain has no fallback. */
 int Ctx::check_domain_layout(rad_op h, int domain, std::string* why) const {
     if (h == RAD_NULL_HANDLE || h >= plans_.size()) return RAD_E_INVAL;
     if (domain < 0 || domain >= RAD_N_DOMAINS)      return RAD_E_INVAL;
@@ -504,9 +441,9 @@ int Ctx::check_domain_layout(rad_op h, int domain, std::string* why) const {
             RadLayout L{};
             RadTensor t[RAD_ENC_MAX_PLANES];
             weight_planes(w, t);
-            /* A row with no hook, or one that declines this operand, is asserting that it reads
-             * the selected plane AS IT IS -- the same reading rad_builder.cpp gives the same code.
-             * One that does not read the encoding at all cannot take the op either. */
+            /* A row with no hook, or one that declines this operand, reads the selected plane as
+             * stored (as rad_builder.cpp interprets it). One that cannot read the encoding at all
+             * cannot take the op. */
             const int st = ki->layout ? ki->layout(ip.args.p, ip.args.n_p, opd, &w.enc, w.sel, t,
                                                    w.n_sel, &L)
                                       : RAD_E_UNSUPPORTED;
@@ -548,7 +485,7 @@ int Ctx::check_domain(rad_op h, int domain) const {
         return RAD_E_NOKERNEL;
     }
 
-    /* A kernel existing for the band is not the same as a kernel that can READ THE WEIGHT. */
+    /* A kernel existing for every band does not mean it can read the stored weight. */
     std::string why;
     if (check_domain_layout(h, domain, &why) < 0) {
         RAD_ERR("op '%s' cannot run on the %s domain: %s", p.info->op.c_str(),
@@ -576,20 +513,10 @@ int Ctx::op_domain(rad_op h) const {
 
 int Ctx::bind_routing() {
     const Program& P = *program_;
-    /* THE ROUTED LAYER COUNT IS NOT meta.n_layers, AND A DRAFTER IS WHY.
-     *
-     * `meta.n_layers` counts TRUNK layers. An MTP head is a further block with its own expert
-     * plane, and it reports itself as the layer one past that count. Sized from `meta.n_layers`
-     * this vector is one short, so every one of that head's route reports is refused with an error
-     * and the heat engine never sees a single count for it. The placement plan still knows about
-     * the units but has no measurement to promote on, so they stay wherever the warm start left
-     * them -- and the head's experts stream over the link on EVERY draft round of every step,
-     * which is worth several percent of the decode step on a model that has one.
-     *
-     * The weights know the answer and the header does not, so ask them. A drafter, a shared
-     * expert plane, anything a plugin declares past the trunk lands here by construction rather
-     * than by the core being told about it.
-     */
+    /* The routed layer count comes from the expert weights, not meta.n_layers, which counts only
+     * trunk layers. An MTP head (or any expert block declared past the trunk) reports as a layer
+     * beyond that count; without a slot its reports are refused and the heat engine never places
+     * its experts. */
     int64_t n_layer = P.meta.n_layers;
     for (const WeightInfo& w : P.weights)
         if (w.decl.group.expert >= 0)
@@ -600,15 +527,13 @@ int Ctx::bind_routing() {
     route_n_expert_ = n_expert;
     route_.assign((size_t)n_layer, RouteSlot{});
 
-    /* One pinned block for every bank, and ONE ROW A LAYER on the card. Pinned because the copy
-     * has to be a real asynchronous DMA: a pageable destination makes the driver stage it through
-     * its own buffer and, on some paths, synchronise -- which would put a host sync on the compute
-     * stream, which is the one thing §5.5 says routing must never do.
+    /* One pinned host block for all banks, and one row per layer on the card. Pinned so the copy
+     * is a true async DMA; a pageable destination can make the driver synchronise, and routing
+     * must never host-sync (spec §5.5).
      *
-     * The card's rows are not banked: a pass's reports land in them and the pass's flush carries
-     * them to the step's bank on the host, both on the compute stream, so the next pass's reports
-     * queue behind the flush that reads them. A report's copy then names the same address every
-     * step, which is what lets a recorded pass be replayed without rewriting it. */
+     * The card rows are not banked: reports and the end-of-pass flush are both on the compute
+     * stream, so the next pass's reports queue behind the flush. A report's copy then targets the
+     * same address every step, so recorded passes replay unchanged. */
     const int64_t elems = n_layer * kRouteBanks * n_expert;
     const int64_t bytes = elems * (int64_t)sizeof(int32_t);
     const int64_t dbytes = n_layer * n_expert * (int64_t)sizeof(int32_t);
@@ -629,17 +554,17 @@ int Ctx::bind_routing() {
         RouteSlot& r = route_[(size_t)l];
         for (int i = 0; i < kRouteBanks; ++i) {
             r.staging[i] = route_pool_ + ((int64_t)i * n_layer + l) * n_expert;
-            r.step[i]    = -1;          /* never written, as against written at step 0 */
+            r.step[i]    = -1;          /* never written (distinct from step 0) */
         }
     }
-    /* Local: the host reads the bank on the strength of this event, but the bytes it reads were
-     * put in host memory by the copy in front of it, whose own packets carry the system scope. */
+    /* Local scope is enough: the preceding copy's own packets carry the system-scope release that
+     * makes the bank visible to the host. */
     for (RadEvent& e : route_done_) RAD_TRY(rad_event_create_local(&e));
     return RAD_OK;
 }
 
-/* THE PASS'S HISTOGRAMS GO TO THE HOST IN ONE TRANSFER: the layers it reported, which are
- * contiguous rows of the bank, and then the bank's event. Called at the end of every pass. */
+/* Copies the pass's reported rows [route_lo_, route_hi_] to the step's host bank in one transfer
+ * and records the bank's event. Called at the end of every pass. */
 int Ctx::route_flush() {
     if (route_bank_ < 0 || route_lo_ > route_hi_) return RAD_OK;
     const int64_t n_layer = (int64_t)route_.size();
@@ -677,9 +602,8 @@ int Ctx::route_report_impl(int layer, const RadRouting* r, bool copy) {
     const int step = batch_ ? batch_->step : 0;
     const int bank = ((step % kRouteBanks) + kRouteBanks) % kRouteBanks;
 
-    /* The plugin computed these with ordinary declared ops. This is the handoff, not a
-     * computation: we record the device buffers so the mover can be told what was wanted, and
-     * nothing here reads them. */
+    /* A handoff only: records the plugin's device buffers for the mover; nothing here reads
+     * them. */
     s.routing  = *r;
     s.reported = step;
 
@@ -691,37 +615,23 @@ int Ctx::route_report_impl(int layer, const RadRouting* r, bool copy) {
             n = route_n_expert_;
         }
         if (n > 0) {
-            /* Asynchronous, on the compute stream, and nothing waits on it. The heat engine reads
-             * it on the NEXT step, so placement decisions are always one step stale -- which for
-             * heat-based promotion is irrelevant, because a hot expert is hot across many steps
-             * (spec §5.5).
+            /* Async on the compute stream; the host never waits. The heat engine reads it a step
+             * later, which is fine since hot experts stay hot (spec §5.5).
              *
-             * "NOTHING WAITS ON IT" IS TRUE OF THE HOST AND NOT OF THE STREAM. A copy is a blit
-             * kernel, so it sits in the compute stream's order and every later kernel queues
-             * behind it -- and a copy INTO HOST MEMORY must also make its writes visible to the
-             * host before it completes, which waits out every write still crossing the link. With
-             * the link carrying streamed experts, that release and the event record after it would
-             * cost a routed layer several microseconds of an otherwise idle compute stream.
-             *
-             * So the layer's counts are copied WITHIN THE CARD, into its row of the step's bank,
-             * and the rows this pass wrote cross to the host once, at the end of the pass
-             * (route_flush). One card-local blit a routed layer is the whole cost -- and none when
-             * the router wrote the row itself (rad_route_counts), which is the report naming it.
-             *
-             * MOVING IT OFF THE COMPUTE STREAM IS WORTH LESS THAN IT LOOKS. The second lane would
-             * have to wait on this stream first, or the copy races the routing kernel that writes
-             * `expert_count`. That is a lane_join a routed layer and an event record back on the
-             * compute stream, which costs more than the blit it moves. */
-            /* RECYCLING A BANK NOBODY READ IS THE RING BEING TOO SHALLOW FOR THIS RUN-AHEAD, and
-             * it is the only way evidence is lost, since the drain takes every landed bank. It
-             * is counted here, at the one place it can happen, rather than inferred from a total
-             * that came up short. A second report of the SAME step is not a recycle: the drain
-             * does not take a bank before its step is over, and `reports` carries the pass. */
+             * The copy still sits in stream order, and a copy into host memory must wait out
+             * every in-flight link write before completing. So each layer's counts are copied
+             * within the card into its row, and the pass's rows cross to the host once at the
+             * end (route_flush). No copy at all when the router wrote the row itself
+             * (rad_route_counts). Moving the blit to the second lane would need a lane_join per
+             * layer to avoid racing the routing kernel, which costs more than the blit. */
+            /* Recycling an uncredited bank means the ring is shallower than the host's run-ahead;
+             * it is the only way evidence is lost, so it is counted here. A second report of the
+             * same step is not a recycle (`reports` counts it). */
             const bool again = s.step[bank] == step;
             if (s.step[bank] >= 0 && !again && !s.credited[bank]) ++route_dropped_;
             s.credited[bank] = false;
             if (route_bank_ != bank) {
-                /* Empty: every pass flushes at its end. Not recorded if it were not. */
+                /* Normally a no-op, since every pass flushes at its end; kept out of the tape. */
                 if (rec_) tape_pause(true);
                 const int rf = route_flush();
                 if (rec_) tape_pause(false);
@@ -741,34 +651,19 @@ int Ctx::route_report_impl(int layer, const RadRouting* r, bool copy) {
             s.reports[bank] = again ? s.reports[bank] + 1 : 1;
             s.step[bank] = step;
 
-            /* ==================== WHAT A FAULT LOOKS LIKE IN THIS HISTOGRAM ====================
+            /* RADIANCE_DEBUG_ROUTING=: prints that layer's histogram for the first steps.
+             * It synchronises the stream, so it is off by default.
              *
-             * The sum of a layer's counts is the number of placements, which cannot exceed
-             * n_tok * top_k. Negative counts, or totals orders of magnitude above that bound, say
-             * something OUTSIDE this path wrote over the buffer rather than that the routing
-             * kernel is wrong.
-             *
-             * The shape such an overrun takes is worth knowing, because it hides. A routed expert
-             * plane is one row per (token, slot), so a buffer declared at max_tok rows is written
-             * `rows * top_k` deep and runs past its declaration -- and the overrun only EXISTS
-             * once rows * top_k exceeds the declared extent. A short prefill chunk and a decode
-             * step are therefore clean while a full batch is not, and the discriminator is not
-             * `n_tok == max_tok` but how far past the end the write reaches and what the arena
-             * put there. core/runtime/issue.cpp carries the guard that refuses an operand reaching
-             * past its declaration.
-             *
-             * RADIANCE_DEBUG_ROUTING: a composition fault in a routed model shows up here first.
-             * It SYNCHRONISES THE STREAM, which is exactly what the copy above exists to avoid --
-             * so it is an environment variable, off, and costs nothing when it is not set. The
-             * value is the layer to print. */
+             * A layer's counts sum to at most n_tok * top_k. Negative counts or far larger totals
+             * mean something outside this path overwrote the buffer, e.g. an expert plane declared
+             * at max_tok rows but written rows * top_k deep (refused by the operand guard in
+             * issue.cpp). */
             static const char* dbg = std::getenv("RADIANCE_DEBUG_ROUTING");
             if (copy && dbg && layer == (int)std::strtol(dbg, nullptr, 10) && step < 3) {
                 RAD_TRY(route_flush());
                 rad_stream_sync(stream_);
-                /* READ THE DEVICE BUFFER AGAIN, SYNCHRONOUSLY, and print both totals. The staging
-                 * copy is asynchronous and this print is the only reader of it, so a disagreement
-                 * here says the copy raced and an agreement says the histogram itself is what it
-                 * is. Debug-only, so the extra transfer costs nothing when the variable is off. */
+                /* Also read the device buffer directly: a mismatch with the staged copy means the
+                 * copy raced. */
                 std::vector direct((size_t)n, 0);
                 int64_t dtot = 0;
                 if (rad_memcpy_async(direct.data(), r->expert_count,
@@ -795,28 +690,19 @@ int Ctx::route_report_impl(int layer, const RadRouting* r, bool copy) {
     return RAD_OK;
 }
 
-/* THE OLDEST LANDED BANK THIS LAYER HAS NOT BEEN CREDITED FOR, or -1 when there is none.
- *
- * OLDEST AND NOT NEWEST, because the caller drains in a loop and the heat engine decays a layer's
- * plane on every observation. Fed newest-first, a burst would apply the most recent decay to the
- * oldest evidence and rank the plane by an order the device never produced.
- *
- * A BANK IS SKIPPED UNTIL ITS COPY HAS COMPLETED. `step[b]` is stamped when the copy is ISSUED,
- * which on a long prefill chunk is many steps before the device reaches it; reading the staging
- * then would hand back whatever the bank's previous occupant left in it, which is a histogram from
- * kRouteBanks steps ago wearing this step's number. The event is the only thing that separates
- * the two, so it is queried rather than assumed -- and that also excludes a half-written bank,
- * which a mid-step reader would otherwise see.
- *
- * A BANK OF A STEP STILL BEING ISSUED IS SKIPPED TOO, landed or not: a later pass of that step can
- * still report into it. See `before_step` in ctx.h.
- */
 void Ctx::mark_credited(int layer, int bank) {
     if (layer < 0 || (size_t)layer >= route_.size()) return;
     if (bank < 0 || bank >= kRouteBanks) return;
     route_[(size_t)layer].credited[bank] = true;
 }
 
+/* The oldest landed bank in (after_step, before_step) for this layer, or -1.
+ *
+ * Oldest first, because the heat engine decays a layer's plane on every observation and must see
+ * them in device order. A bank is skipped until its event says the copy completed: `step[b]` is
+ * stamped at issue, and the staging would otherwise still hold the previous occupant's histogram.
+ * A bank of a step still being issued is skipped too (see `before_step` in ctx.h).
+ */
 int Ctx::next_histogram(int layer, int after_step, int before_step, int8_t* landed) const {
     if (layer < 0 || (size_t)layer >= route_.size()) return -1;
     const RouteSlot& s = route_[(size_t)layer];
@@ -869,23 +755,16 @@ int Ctx::bind_profiling() {
     prof_wait_ms_.assign(program_->ops.size(), 0.0);
     if (!profiling_) return RAD_OK;
 
-    /* Printed, not buried in a doc. Anyone reading a profiled run's numbers has to see this on the
-     * same terminal that produced them. */
-    RAD_WARN("per-op timing is ON. It restores synchronisations that change the mover's slot "
-             "supply, so THIS RUN IS NOT COMPARABLE against an unprofiled one (spec §16). "
-             "Anything being measured across builds runs without it.");
+    RAD_WARN("per-op timing is on; it adds synchronisations that change the mover's slot supply, "
+             "so this run is not comparable with an unprofiled one (spec §16)");
 
-    /* A fixed ring, allocated here, because the step path does not allocate. 8192 pairs covers a
-     * 64-layer model at ~20 ops a layer with room for speculation; past that we stop timing and
-     * say so, rather than growing a vector inside a step.
+    /* A fixed ring, since the step path does not allocate. 8192 pairs covers a 64-layer model at
+     * ~20 ops a layer with room for speculation; overflow stops timing with a warning.
      *
-     * CARD-LOCAL EVENTS, NOT HOST-WAIT ONES. A host-wait record takes an interrupt signal, of which
-     * a process has a few thousand, and every pair recorded in a step holds two until the pair is
-     * recorded again a step later: a prefill step on a large model records more pairs than that
-     * across the ranks, and the engine's own staging event then has no signal left to take. The
-     * host never waits on these one at a time -- profile_collect waits for the stream once -- and
-     * a card-scope release keeps the records from waiting out writes still on their way to the
-     * host, which would be charged to the op they bracket. */
+     * Card-local events: a host-wait event takes one of a process's few thousand interrupt
+     * signals, and a large prefill step would exhaust them. The host only waits on the stream
+     * (profile_collect), and a card-scope release does not wait out in-flight host writes that
+     * would be charged to the bracketed op. */
     const size_t cap = 8192;
     prof_ring_.resize(cap);
     for (size_t i = 0; i < cap; ++i) {
@@ -899,18 +778,15 @@ int Ctx::bind_profiling() {
 }
 
 void Ctx::profile_collect() {
-    /* This is the synchronisation the caveat above is about. It is here, at the end of the step,
-     * rather than per launch, so at least the ordering inside a step is undisturbed -- but the
-     * mover's slot supply still sees a step boundary it would not otherwise see. */
+    /* The profiling sync, once at the end of the step so ordering within the step is
+     * undisturbed. */
     if (prof_n_ > 0) {
-        /* Lane 1 is already joined into the compute stream (end of step), so that stream finishing
-         * is every bracketed launch finishing. */
-        ++n_host_syncs_;                     /* counted, so the caveat is a number and not a claim */
+        /* Lane 1 is already joined into the compute stream, so this covers every launch. */
+        ++n_host_syncs_;
         if (rad_stream_sync(stream_) < 0) prof_n_ = 0;
     }
-    /* The idle time before each op, per lane: the first op a lane runs in the step has nothing
-     * before it on that lane, and the gap from the last step is mostly this collection's own
-     * synchronisation, so it is not charged. */
+    /* Idle time before each op, per lane. A lane's first op in the step is not charged: its gap
+     * is mostly this collection's own sync. */
     const ProfSlot* prev[2] = { nullptr, nullptr };
     for (size_t i = 0; i < prof_n_; ++i) {
         ProfSlot& s = prof_ring_[i];
@@ -937,16 +813,16 @@ void Ctx::dump_profile() const {
     if (!program_)   { RAD_WARN("per-op timing: the context has already been shut down"); return; }
 
     fprintf(stderr,
-            "\nper-op timing, rank %d. NOT COMPARABLE against an unprofiled run:\n"
+            "\nper-op timing, rank %d. Not comparable with an unprofiled run:\n"
             "enabling this restores synchronisations that change the mover's slot supply.\n"
-            "A row marked `host` was timed on the HOST CLOCK around a host-site launch and\n"
+            "A row marked `host` was timed on the host clock around a host-site launch and\n"
             "includes everything that call waited on -- page faults, link reads. The rest are\n"
             "device event pairs around a kernel. `wait us` is how long, a call, the op's lane\n"
             "sat idle before it started -- stream waits and issue delays, in no op's time.\n\n"
             "  %10s %12s %10s %5s %10s %10s  %s\n", rank_, "calls", "total ms", "us/call", "site",
             "join us", "wait us", "op / geometry");
 
-    /* Slowest first: the only ordering anybody reads this table in. */
+    /* Slowest first. */
     std::vector order;
     for (size_t i = 1; i < prof_calls_.size(); ++i) if (prof_calls_[i]) order.push_back(i);
     std::sort(order.begin(), order.end(),
@@ -960,10 +836,8 @@ void Ctx::dump_profile() const {
         if (ho && i < prof_join_ms_.size())
             std::snprintf(jbuf, sizeof jbuf, "%10.2f",
                           prof_join_ms_[i] * 1000.0 / (double)prof_calls_[i]);
-        /* The op's position and its first weight name the LAYER: every layer's instance of an
-         * op declares the same geometry, so without them sixty rows read alike and a per-layer
-         * cost -- residency, a pooled expert streamed by one layer and not the next -- cannot be
-         * tied to anything. */
+        /* The op index and first weight identify the layer, since every layer's instance has
+         * the same geometry. */
         const char* wname = !o.weights.empty() && o.weights[0] < program_->weights.size()
                                 ? program_->weights[o.weights[0]].name.c_str() : "-";
         const double wait = i < prof_wait_ms_.size() ? prof_wait_ms_[i] : 0.0;
@@ -980,26 +854,19 @@ void Ctx::dump_profile() const {
 
 /* ================================================================== the step driver */
 
-/* LAZY, AND THAT IS THE POINT: an architecture that never asks for a second lane must take the
- * same code path an architecture with one lane would take if this feature did not exist, so that
- * "the lane costs nothing when unused" is a property of the source rather than a claim about a
- * measurement. Building the stream eagerly would make it one -- and one that is hard to establish,
- * because a second stream's cost is small enough to sit inside the run-to-run spread a warming
- * part produces. */
+/* Lazy, so an architecture that never asks for a second lane runs exactly the single-lane code
+ * path. */
 int Ctx::lane_init() {
     if (lane1_) return RAD_OK;
     RAD_TRY(rad_dev_set(device_));
     RAD_TRY(rad_stream_create(&lane1_, 0));
     own_lane1_ = true;
-    /* Local: a lane join orders one card's two queues and nothing else reads through it. */
+    /* Local scope: a lane join only orders this card's two queues. */
     for (int i = 0; i < 2; ++i)
         if (!lane_ev_[i]) RAD_TRY(rad_event_create_local(&lane_ev_[i]));
-    /* A NEW LANE STARTS BEHIND EVERYTHING LANE 0 HAS ISSUED. Its first use is mid-step, and the
-     * join an architecture puts in front of it -- rad_lane_join(0, 1), then rad_lane(1) -- found no
-     * lane 1 to order and returned without doing anything. Unordered, the first op on the new
-     * stream reads lane 0's output before lane 0 has written it: on Qwen-Image's two-rank pass
-     * the first picture after startup took its first all-reduce of stale rows and came out a
-     * different picture, every later one the right one. */
+    /* A new lane starts behind everything lane 0 has issued. Its first use is mid-step, where a
+     * preceding rad_lane_join(0, 1) found no lane 1 and did nothing, so without this the first op
+     * on the new stream could read lane 0's output before it is written. */
     RAD_TRY(rad_event_record(lane_ev_[0], stream_));
     RAD_TRY(rad_event_wait(lane1_, lane_ev_[0]));
     return RAD_OK;
@@ -1016,9 +883,8 @@ int Ctx::set_lane(int lane) {
 int Ctx::lane_join(int from, int to) {
     if (from == to) return RAD_OK;
     if (from < 0 || from > 1 || to < 0 || to > 1) return RAD_E_INVAL;
-    /* Nothing was ever issued on lane 1, so there is nothing to order against -- and a lane 1
-     * built later starts behind lane 0 (lane_init). This is the arm every unpipelined step takes
-     * at the end of run_step, and it must not build a stream. */
+    /* No lane 1 yet: nothing to order, and a later lane 1 starts behind lane 0 (lane_init). Every
+     * single-lane step takes this at the end of run_step; it must not build a stream. */
     if (!lane1_) return RAD_OK;
     RadStream fs = from ? lane1_ : stream_, ts = to ? lane1_ : stream_;
     RAD_TRY(rad_event_record(lane_ev_[from], fs));
@@ -1030,9 +896,17 @@ int Ctx::lane_join(int from, int to) {
 /* ================================================================== recorded passes */
 /* See "recorded passes" in ctx.h. */
 
+/* The key below reads every RadBatch field a pass's shape or arguments can depend on, by hand. A
+ * field added to RadBatch changes its size: decide whether the key must read it, then update the
+ * size here. */
+static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 312,
+              "RadBatch changed: check that Ctx::pass_key reads every new field a pass depends on");
+static_assert(sizeof(void*) != 8 || sizeof(RadKVGroupBatch) == 72,
+              "RadKVGroupBatch changed: check that Ctx::pass_key reads every new field");
+
 uint64_t Ctx::pass_key(const RadBatch* b) const {
-    /* An encoder pass is shaped by its media, and a pass that carries encoder rows issues the
-     * scatter that puts them in place only when it has some: neither repeats as a tape would. */
+    /* Not recordable: encoder passes are shaped by their media, and passes carrying encoder rows
+     * issue the scatter only when they have some. */
     if (b->enc || b->n_mm_rows > 0) return 0;
     /* A generator pass is shaped by what RadBatch::gen_b carries, which no key below reads. */
     if (b->gen) return 0;
@@ -1059,7 +933,6 @@ uint64_t Ctx::pass_key(const RadBatch* b) const {
         mix((uint64_t)k.state_index_pitch); mix((uint64_t)k.block_size); mix((uint64_t)k.max_blocks);
     }
     mix((uint64_t)level_);
-    mix(w_tmpl_epoch_);
     mix(dense_epoch_);
     mix(domain_epoch_.load(std::memory_order_relaxed));
     ptr(arena_.base());
@@ -1142,18 +1015,18 @@ int Ctx::record_pass(const RadBatch* b, uint64_t key, PassTape* out) {
     return 1;
 }
 
-/* WHICH DISPATCHES OF A RECORDED PASS CAN START BEFORE THE ONES IN FRONT OF THEM FINISH.
+/* Marks which dispatches of a recorded pass may start before the ones ahead of them finish.
  *
- * Walked once, in queue order, per queue: the ops launched since the queue last ordered a packet
- * are in flight together, and the next op may join them when it reads nothing they write and
- * writes nothing they read or write. Anything the walk cannot see into orders its packet: the
- * dispatch after an event, every dispatch after an op's first (an op's own dispatches depend on
- * each other), a dispatch no op owns (a routing copy), and an opaque op on either side. A run is
- * cut at kTapeOverlapRun, the bound the backend reclaims its argument slots on.
+ * One walk per queue, in order. The ops since the queue's last ordered packet are in flight
+ * together; the next op may join them if it reads nothing they write and writes nothing they
+ * read or write. Ordered regardless: the dispatch after an event, every dispatch after an op's
+ * first (an op's dispatches depend on each other), a dispatch no op owns (e.g. a routing copy),
+ * and opaque ops on either side. A run is cut at kTapeOverlapRun, the bound on which the backend
+ * reclaims argument slots.
  *
- * The host work between played stretches needs nothing here. A host op joins the device work it
- * depends on before it runs, and whatever a stretch of host work puts on a queue -- a table patch,
- * a mover wait -- makes the backend order the next played packet on that queue itself. */
+ * Host work between played stretches needs nothing here: a host op joins its dependencies, and
+ * anything host work puts on a queue (table patch, mover wait) makes the backend order the next
+ * played packet on that queue. */
 int Ctx::haz_mark(PassTape& t) {
     const int n = tape_len(t.dev);
     if (n < 0) return n;
@@ -1187,8 +1060,8 @@ int Ctx::haz_mark(PassTape& t) {
         Q* q = nullptr;
         for (Q& x : qs) if (x.id == qid) { q = &x; break; }
         if (!q) { qs.push_back(Q{}); q = &qs.back(); q->id = qid; }
-        /* An event's packet, and the dispatch after it is ordered too: a wait is complete only
-         * once the event it names is, and nothing after it may start before that. */
+        /* An event packet: the next dispatch is ordered, since nothing after a wait may start
+         * before its event completes. */
         if (kind != 0) { q->infl.clear(); q->opaque = true; q->run = 0; continue; }
         ++t.dispatches;
 
@@ -1210,7 +1083,7 @@ int Ctx::haz_mark(PassTape& t) {
             ++t.unordered;
             continue;
         }
-        /* Ordered: everything before it has finished, and it is what is in flight now. */
+        /* Ordered: everything before it has finished; it starts a new in-flight set. */
         const int32_t own = part_of[(size_t)i];
         q->infl.clear();
         if (own >= 0) q->infl.push_back(own);
@@ -1220,7 +1093,7 @@ int Ctx::haz_mark(PassTape& t) {
     return RAD_OK;
 }
 
-/* Two recordings of one key, compared: the backend's records, and the host work between them. */
+/* Compares two recordings of one key: the backend's records and the host work between them. */
 bool Ctx::tapes_agree(const PassTape& a, const PassTape& b, std::string* why) {
     if (a.steps.size() != b.steps.size()) {
         *why = fmt("%zu stretches against %zu", a.steps.size(), b.steps.size());
@@ -1235,6 +1108,11 @@ bool Ctx::tapes_agree(const PassTape& a, const PassTape& b, std::string* why) {
             return false;
         }
     }
+    if (a.host.size() != b.host.size() || a.route.size() != b.route.size()) {
+        *why = fmt("%zu host ops and %zu routing reports against %zu and %zu", a.host.size(),
+                   a.route.size(), b.host.size(), b.route.size());
+        return false;
+    }
     for (size_t i = 0; i < a.host.size(); ++i) {
         const TapeHost& x = a.host[i];
         const TapeHost& y = b.host[i];
@@ -1343,7 +1221,7 @@ int Ctx::play_pass(PassTape& t) {
     return RAD_OK;
 }
 
-/* THE PASS: played from its tape, or issued -- and recorded, or checked against its tape. */
+/* Runs one pass: played from its tape, or issued live (and possibly recorded or audited). */
 int Ctx::run_pass(const RadBatch* b) {
     const auto bump = [](std::atomic& c) { c.fetch_add(1, std::memory_order_relaxed); };
     scratch_cur_[0] = scratch_cur_[1] = 0;
@@ -1368,8 +1246,8 @@ int Ctx::run_pass(const RadBatch* b) {
 
     if (t) {
         bump(pc_audited_);
-        /* The check: issue the pass for real, recording it, and compare. The first comparison
-         * comes before the tape is ever played, and then one every kAuditPlays plays. */
+        /* Audit: issue the pass live, recording it, and compare. Runs before the first play and
+         * then every kAuditPlays plays. */
         PassTape fresh;
         if (!record_pass(b, key, &fresh)) return RAD_OK;
         std::string why;
@@ -1391,13 +1269,9 @@ int Ctx::run_pass(const RadBatch* b) {
         return RAD_OK;
     }
 
-    /* A KEY IS RECORDED THE SECOND TIME IT IS SEEN, so a pass that never recurs -- a prefill
-     * chunk, whose token count and positions are its own -- costs no recording and does not push
-     * a tape that will be played out of the least-recently-used set. A DECODE pass recurs by
-     * construction: the same shape runs every step until a sequence's context crosses its bound's
-     * bucket, and then the new key runs every step after that. Seen-once is a whole live issue
-     * spent learning that, at every crossing, so a decode pass is recorded the first time. The
-     * audit before its first play is unchanged. */
+    /* Non-decode keys are recorded on their second sighting, so one-off passes (prefill chunks)
+     * cost no recording and do not evict useful tapes. Decode passes recur every step until a
+     * bound crosses its bucket, so they are recorded on first sight. */
     if (b->phase != RAD_PHASE_DECODE && !tape_seen(key)) {
         bump(pc_first_);
         arch_step_(this, b);
@@ -1427,36 +1301,31 @@ int Ctx::run_step(const RadBatch* b) {
         return RAD_E_STATE;
     }
 
-    /* BEFORE THE RESIDENCY SYNC: a stager may give back weights it published for this pass when
-     * it turns the pass down (runtime/stager.h), and the sync is what carries that into the
-     * tables the pass resolves. */
+    /* Before the residency sync, which carries any weights a declining stager gave back into the
+     * tables (runtime/stager.h). */
     staging_ = stager_ != nullptr && stager_->begin_pass(b);
 
-    /* The mover relocates between steps, never during one. Honouring WeightInfo::generation here
-     * costs one relaxed atomic load per step instead of one per weight per issue. */
-    if (weights_dirty_.exchange(false, std::memory_order_acq_rel))
-        bind_weights(/*refresh_only=*/true);
     sync_residency();
 
     batch_       = b;
     step_status_ = RAD_OK;
     step_fail_.clear();
     prof_n_      = 0;
-    in_step_     = true;
     {
         const int rc = run_pass(b);
         if (rc < 0 && step_status_ >= 0) step_status_ = rc;
     }
 
-    /* EVERY LANE JOINS BACK BEFORE THE STEP ENDS, whatever the architecture did or forgot to do.
-     * The engine synchronises the COMPUTE stream to know a step is finished; work still queued on
-     * lane 1 would be read by the sampler, or freed under, while it was in flight. Ordering lane 0
-     * behind lane 1 here costs one event record and one wait on a step that never used lane 1 --
-     * and it means a plugin cannot leave the runtime in a state where that is possible. */
+    /* Always join lane 1 back into lane 0 before the step ends: the engine syncs only the
+     * compute stream, so work left on lane 1 could be read by the sampler or freed while in
+     * flight. */
     lane_ = 0;
-    lane_join(1, 0);                    /* a no-op, and allocates nothing, when lane 1 is unbuilt */;
-    /* Behind the join, so the compute stream is behind every reader of what the stager published;
-     * and whatever the pass's status, because a staged weight must never outlive its pass. */
+    {
+        const int lj = lane_join(1, 0);   /* no-op when lane 1 is unbuilt */
+        if (lj < 0 && step_status_ >= 0) step_status_ = lj;
+    }
+    /* After the join, so the compute stream is behind every reader of staged weights; regardless
+     * of status, because a staged weight must never outlive its pass. */
     if (staging_) {
         const int se = stager_->end_pass(stream_);
         if (se < 0 && step_status_ >= 0) step_status_ = se;
@@ -1467,17 +1336,13 @@ int Ctx::run_step(const RadBatch* b) {
         if (rf < 0 && step_status_ >= 0) step_status_ = rf;
     }
 
-    in_step_ = false;
     if (profiling_) profile_collect();
     flush_issued();
     return step_status_;
 }
 
-/* WHICH DECLARED OPS THE RUN PHASE HAS ACTUALLY ISSUED, copied out of the per-step plans into the
- * Program the graph dump reads. Walks only the ops not yet seen issued and drops each one as it
- * fires, so the cost falls away within a few steps to the ops that have never fired -- and those
- * are exactly what a reader of this field is looking for. Shrinking in place, so no allocation on
- * the step path. */
+/* Copies OpPlan::issued into the Program for the graph dump. Walks only ops not yet seen issued
+ * and compacts the list in place (no allocation). */
 void Ctx::flush_issued() {
     size_t w = 0;
     for (size_t r = 0; r < unflushed_.size(); ++r) {
diff --git a/core/runtime/ctx.h b/core/runtime/ctx.h
index cef8e481..e6fb9015 100644
--- a/core/runtime/ctx.h
+++ b/core/runtime/ctx.h
@@ -1,28 +1,19 @@
 /* ctx.h -- the run phase. Ordinary C++ with one rule: it may only issue handles obtained during
- * declare (spec §3.2). Nothing else is constrained, and its whole job is to be cheap.
+ * declare (spec §3.2).
  *
- * Everything expensive already happened. Declare resolved every op against the kernel hierarchy
- * per band and per domain, the buffer plan sized one arena for the worst step, and the planner
- * assigned every weight a tier and a site. What is left for a step is: index a bucket table with
- * an integer, copy a tensor template per operand, patch in the pointers, and launch. The per-issue
- * work is filling a struct we already own, not constructing one.
+ * Declare already resolved every op against the kernel hierarchy per band and domain, the buffer
+ * plan sized one arena for the worst step, and the planner assigned every weight a tier and site.
+ * A step indexes a bucket table, copies a tensor template per operand, patches in pointers and
+ * launches.
  *
- * COST. An issue is single-digit nanoseconds. Nearly all of it is the RadTensor template copies at
- * 112 bytes each; the band scan is one or two compares off a cache line and the RadArgs patch is a
- * single store. tests/runtime_test.cpp times it and prints it, so the number is checkable rather
- * than claimed, and it is a tripwire -- a hundredfold miss means somebody put an allocation or a
- * map lookup back on this path.
+ * Cost: an issue is single-digit nanoseconds, mostly the 112-byte RadTensor template copies.
+ * tests/runtime_test.cpp times it; a hundredfold miss means an allocation or map lookup got onto
+ * this path. A 64-layer model issues ~1280 ops a decode step, ~10 us of core time; launching them
+ * through hipLaunchKernel would cost 1-2 ms of driver time, which the device backend avoids by
+ * writing AQL packets itself (spec §3.2).
  *
- * At a 64-layer model issuing ~20 ops a layer that is ~1280 issues, so order ten microseconds of
- * CORE time per decode step. Spec §3.2 accepts roughly 1-2 ms of launch overhead per step at 64
- * layers; the rest of that budget is the driver's own per-launch dispatch cost -- order 1 us per
- * hipLaunchKernel, which is what 1280 launches actually costs -- and it is not ours to spend. It is
- * also what HIP-graph capture would attack if v1 wanted it, which §3.2 says is a change to that
- * section and not to the ABI. The core is therefore not where the step budget goes, against a
- * Python engine's 10-20 ms of the same thing.
- *
- * A residency table with a pending event adds one rad_event_wait -- once per weight per
- * GENERATION, not per issue, which is why residency.h makes the mover bump it.
+ * A pending residency event adds one rad_event_wait per weight per generation, not per issue
+ * (residency.h).
  */
 #pragma once
 #include "../rad_core.h"
@@ -39,140 +30,107 @@
 #include 
 #include 
 
-/* RadCtx is opaque in the ABI: rad_runtime.h forward-declares it and nothing else. Completing it
- * here as an empty base gives a well-defined static_cast from the C handle to the C++ object,
- * instead of a reinterpret_cast that merely happens to work. The run phase is the only component
- * that ever holds one, so this is the right place for the definition. */
+/* RadCtx is opaque in the ABI (rad_runtime.h only forward-declares it). Completing it as an empty
+ * base makes the C handle to C++ object conversion a well-defined static_cast. */
 struct RadCtx { };
 
 namespace rad {
 
+class Registry;
 struct XpState;
 struct XpLayer;
 
-/* The widest op in the conventional vocabulary is gdn_conv_prep at sixteen operands, with
- * gdn_recurrent_update behind it at fourteen -- both grew when the two kernel plugins' schemas
- * were reconciled (docs/OPS.md, "How a schema is written"). Thirty-two leaves room for an
- * architecture plugin's private ops without putting a variable-length array on the hot path. */
+/* The widest conventional op is gdn_conv_prep at sixteen operands (docs/OPS.md). Thirty-two leaves
+ * room for an architecture plugin's private ops without a variable-length array on the hot path. */
 constexpr int MAX_OPERANDS = 32;
 
 typedef void (*ArchStepFn)(RadCtx*, const RadBatch*);
 
+/* "[shape]/[stride]" of a tensor's live dimensions, for diagnostics. */
+std::string tensor_shape_str(const RadTensor& t);
+
 /* ------------------------------------------------------------------ the issue plan */
-/* One resolved (op, band, domain) with everything that does not change per issue already filled
- * in: the geometry view the kernel reads its parameters out of, the scratch pointer, the instance
- * init() returned, the rank and the world size. Per issue we set `t` and `n_t` and call `launch`.
+/* One resolved (op, band, domain) with everything that does not change per issue filled in: the
+ * geometry view, the scratch pointer, the instance init() returned, rank and world size. Per issue
+ * we set `t` and `n_t` and call `launch`.
  *
- * `launch` is hoisted out of row->info so the fast path chases one pointer rather than two, and
- * `row` is diagnostics only -- it is read when a launch fails and never otherwise. */
+ * `launch` is hoisted out of row->info to save a pointer chase; `row` is read only when a launch
+ * fails. */
 struct IssuePlan {
     RadArgs          args{};
     RadLaunchFn      launch = nullptr;
     const KernelRow* row    = nullptr;
-    /* The parameters a launch that holds the link is handed: the geometry's and `link_gate`, for a
-     * row that ends the hold itself; null for every other. Only such a launch takes them, so a
-     * step that holds nothing -- every decode step -- never pays the kernel's read of the word. */
+    /* For a row that ends the link hold itself: the geometry's parameters plus `link_gate`. Null
+     * for every other row, so a step that holds nothing (every decode step) never reads the word. */
     const RadParam*  gate_p = nullptr;
     int              gate_n_p = 0;
+    /* Resolved::ranged_div: an issued value this does not divide is refused. 0 for most rows. */
+    int64_t          ranged_div = 0;
 };
 
-/* Per declared op. Trivially copyable on purpose: the bucket table and the issue plans live in two
- * flat Ctx-owned arrays and this holds offsets into them, so a step touches one small dense record
- * per op instead of walking two vectors' worth of indirection. */
+/* Per declared op. Trivially copyable: it holds offsets into two flat Ctx-owned arrays (bucket
+ * table, issue plans), so a step touches one small dense record per op. */
 struct OpPlan {
     const OpInfo* info     = nullptr;
     int32_t       band_off = 0;      /* into Ctx::band_table_ */
     int32_t       n_bands  = 0;
     int32_t       plan_off = 0;      /* into Ctx::issue_table_, band * RAD_N_DOMAINS + domain */
-    /* The schema's operand count, copied here so the arity check is a compare against a hot field
-     * rather than two pointer chases into a cold OpInfo. -1 when the op has no schema. */
+    /* The schema's operand count, cached so the arity check avoids a cold OpInfo. -1 when the op
+     * has no schema. */
     int32_t       n_opd_schema = -1;
     bool          issued   = false;  /* did the run phase ever issue it (spec §16's graph dump) */
-    /* IS THIS OP A COLLECTIVE -- i.e. does issuing it put bytes on the interconnect? Set once at
-     * bind, from the rows it resolved to (rad_kernel_collective) and the conventional all_reduce,
-     * so the issue path tests a predicted branch and not a string. The weight stager's copies
-     * share the link, and give way to it while it runs (Ctx::issue_body). */
+    /* Whether issuing it puts bytes on the interconnect. Set at bind from the resolved rows
+     * (rad_kernel_collective) and the conventional all_reduce. The weight stager's copies share
+     * the link and give way to it while it runs (Ctx::issue_body). */
     bool          collective = false;
-    /* The conventional all_reduce, whose `n` IS the message's element count -- the one collective
-     * the link bill can be charged for without guessing its wire format. The link is shared with
-     * the expert mover, so separating "how much of it is the all-reduce" needs this counted. */
+    /* The conventional all_reduce, whose `n` is the message's element count, so its link bytes
+     * can be counted (ar_bytes) apart from the expert mover's. */
     bool          billed = false;
 };
 
 /* ------------------------------------------------------------------ routing handoff */
-/* A RING OF STAGING BANKS, indexed by step, so that the heat engine reads a histogram the device
- * actually wrote rather than one still queued behind it.
+/* A ring of routing-histogram staging banks, indexed by step, so the heat engine reads histograms
+ * the device has actually written.
  *
- * TWO BANKS ARE NOT ENOUGH AND THE REASON IS THE HOST'S RUN-AHEAD. The dispatch that consumes
- * these runs before the step is issued and every issue path returns immediately, so on a long
- * prefill chunk -- most of a second of device time -- the host reaches the end of the prompt while
- * the card is still on its first chunks. With two banks, the copy for step S is overwritten by the
- * one for S+2 long before the device has reached either, the freshest bank always holds a copy in
- * flight, and the engine skips the layer: over 41 chunks of 2048 tokens, two banks credit 79
- * layer-histograms and skip 3800 as not yet landed.
+ * The ring must be as deep as the host's run-ahead. Issue returns immediately, so on a long
+ * prefill the host can be many steps ahead of the card; a shallow ring overwrites a bank before
+ * its copy lands, and the layer's evidence is lost. The drain credits every landed bank, not only
+ * the newest.
  *
- * THE BYTES ARE NOT THE PROBLEM -- the device does execute every copy, in order, spread over its
- * own progress. A shallow ring overwrites them before anyone reads them. A ring as deep as the
- * run-ahead keeps each one until it is credited, and the dispatch drains every landed bank rather
- * than only the newest, so a burst of host steps followed by a wait still credits every histogram
- * the card produced in between.
- *
- * DEPTH IS A MEMORY-FOR-EVIDENCE TRADE AND IT IS CHEAP: one int32 an expert a bank a layer, which
- * on a 49-layer 254-expert plane is about 50 KiB a bank. What it cannot do is exceed the run-ahead
- * for free, so the engine counts what it still loses and prints it -- see the routing-evidence
- * line at shutdown. */
+ * Cost is one int32 per expert per layer per bank (~50 KiB a bank for 49 layers x 254 experts).
+ * Losses still happen past the ring's depth and are counted (route_dropped) and printed at
+ * shutdown. */
 static const int kRouteBanks = 32;
 
 struct RouteSlot {
     RadRouting routing{};
     int32_t*   staging[kRouteBanks] = {};   /* this layer's row of the bank's host copy */
     int        step[kRouteBanks]    = {};
-    /* HOW MANY TIMES THIS LAYER REPORTED INTO THAT BANK, which is not always once. A bank is
-     * indexed by the step, so every report a layer makes WITHIN one step lands in the same one
-     * and overwrites the last -- and a speculative draft head reports once per draft pass, n_spec
-     * times a step. Uncredited, the heat engine sees a fraction of that layer's routing and prices
-     * its experts accordingly, which starves a draft head's resident set relative to every other
-     * layer's. The histogram itself cannot be summed here -- it arrives by an async copy off the
-     * compute stream -- but the COUNT is free, and one pass credited n times is the right
-     * expectation when the passes route from the same distribution.
-     *
-     * THIS IS AN ACCOUNTING FIX, NOT A PERFORMANCE LEVER, and the distinction is the useful part.
-     * Crediting the passes raises that layer's resident expert count and tightens the spread
-     * across layers, and the step time does not move.
-     *
-     * WHY IT IS NULL IS THE THING TO REMEMBER: RESIDENCY AGAINST TIME IS CONVEX, STEEPLY. A cache
-     * whose hot set is already in has nothing left to gain from the marginal entry, and a layer
-     * holding more than half its experts already has its hot set in. Rescuing a layer at 35-45%
-     * residency is worth about a millisecond a step; topping one up from 55% to 63% is worth zero
-     * -- do not price the second from the first.
-     */
+    /* How many times this layer reported into that bank. A draft head reports once per draft
+     * pass (n_spec times a step) into the same step's bank, each overwriting the last. The
+     * histograms arrive by async copy and cannot be summed here, so the bank is credited `reports`
+     * times, which is right when the passes route from the same distribution. Without it the heat
+     * engine undercounts the draft head's routing and starves its resident set. */
     int        reports[kRouteBanks] = {};
-    /* Whether the drain has taken this bank yet, which is what makes "the ring lost one" an exact
-     * count rather than an upper bound: a bank recycled while this is false held evidence nobody
-     * read. */
+    /* Whether the drain has taken this bank. A bank recycled while this is false is an exact
+     * count of one lost histogram. */
     bool       credited[kRouteBanks] = {};
     int        reported   = -1;      /* the last step this layer reported at all */
 };
 
 /* ------------------------------------------------------------------ construction */
-/* Where a KV group's pool lives, per group, bound at load. RAD_OPK_KV resolves through this:
- * RadKVGroupBatch carries the slot mapping, the block table and the sequence lengths, but the pool
- * BASE belongs to the block manager and not to a per-step batch -- it does not change from step to
- * step and rebuilding it every step would be work the arena exists to avoid.
+/* Where a KV group's pool lives, bound at load; RAD_OPK_KV resolves through it. The per-step
+ * RadKVGroupBatch carries slot mapping, block table and lengths; the pool base belongs to the
+ * block manager and does not change between steps.
  *
- * One cache per BOUND LAYER, so the operand's `offset` is the layer and `layer_stride` is what
- * separates two layers of the same group. A group with no bound layers never gets here: the
- * builder refuses it at declare, because its page size would otherwise be a guess. */
-/* ONE LAYER'S CACHE, WITH ITS SHAPE. The shape is here and not in the kernel because the core is
- * where every number in it already lives: the group's RadKVGroupDecl gives the head count, the head
- * dimension, the per-head state geometry and the conv width, and the block manager decided the
- * block size, the block count and the state count. A kernel handed a flat span would have to
- * reconstruct all of that from its own parameters -- and cannot: the conv window's depth is
- * `conv_width - 1 + n_spec` and the slot count is `max_num_seqs`, neither of which appears in any
- * op's parameter list. Shims check a cache operand's rank -- 4 for a paged cache, 3 for a conv
- * window -- and refuse anything else, so a RAD_OPK_KV operand may not arrive as a flat byte span.
+ * One cache per bound layer: the operand's `offset` is the layer, `layer_stride` separates layers.
+ * The builder refuses a group with no bound layers at declare.
  *
- * The layouts are the ones libref/ref_ops.h states once for the whole project:
+ * The shape lives here because the core holds every number in it (RadKVGroupDecl plus the block
+ * manager's sizes); a kernel cannot rebuild it from op parameters, since the conv window depth
+ * (`conv_width - 1 + n_spec`) and slot count (`max_num_seqs`) are in none. Shims refuse a cache
+ * operand that is not rank 4 (paged) or rank 3 (conv), so it never arrives as a flat span.
+ * Layouts, as libref/ref_ops.h defines them:
  *
  *     FULL / WINDOW  [n_blocks, n_head_kv, block_size, 2 * head_dim]   K then V inside a slot
  *     LINEAR         [n_states, n_head_kv, state_dim[0], state_dim[1]]
@@ -183,12 +141,9 @@ struct KVPoolBinding {
     int64_t  layer_stride = 0;      /* bytes between one layer's cache and the next */
     int64_t  bytes = 0;             /* the whole group's pool, for the bounds check */
     uint32_t dtype = RAD_DT_INVALID;
-    /* THE OPERAND NAMES AN ABSOLUTE MODEL LAYER AND THE GROUP HOLDS ONE CACHE PER BOUND LAYER, so
-     * the rebase is a POSITION LOOKUP and not a subtraction. Subtracting the first bound layer is
-     * right only when a group's layers are contiguous, and they need not be -- 15 attention layers
-     * scattered through 64, say, where the fifth of them at absolute index 19 would come out as
-     * slot 16 of a 15-slot pool. Indexed by absolute layer; -1 means the group does not
-     * hold that layer, which is a caller bug rather than a runtime condition. */
+    /* Absolute model layer -> cache slot in this group. A lookup, not a subtraction, because a
+     * group's layers need not be contiguous. -1: the group does not hold that layer (a caller
+     * bug). */
     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};
@@ -204,14 +159,18 @@ struct CtxDesc {
     ArchStepFn      arch_step   = nullptr;  /* the architecture plugin's rad_arch_step */
     bool            profile_ops = false;    /* spec §16, and it changes what you measure */
     /* Whether a repeated pass may be recorded and played back. False for a caller whose pass
-     * body issues work the batch does not describe -- a test driving another component through
-     * run_step -- so every pass is issued, since a recording keyed on the batch would stand for
-     * passes that differ. */
+     * issues work the batch does not describe (e.g. a test driving another component through
+     * run_step), since a recording keyed on the batch would replay the wrong pass. */
     bool            record_passes = true;
 
-    /* By rad_kvgroup. Empty until the KV manager has allocated, which is why it is bound here and
-     * not derived: a Ctx built before the pools exist would resolve every cache operand to null. */
+    /* By rad_kvgroup. Bound rather than derived because the pools may not exist yet when the Ctx
+     * is built. */
     std::vector kv;
+
+    /* The kernel registry, read only by the op oracle (RADIANCE_OP_ORACLE) to resolve the
+     * reference library's host rows. Null: the oracle checks a band only where the reference
+     * library won its host row. */
+    Registry*       registry    = nullptr;
 };
 
 /* ------------------------------------------------------------------ Ctx */
@@ -231,15 +190,14 @@ public:
     void set_stager(OpStager* s) { stager_ = s; }
 
     /* ---------------------------------------------------------- the step driver */
-    /* Sets the batch and calls the architecture plugin's rad_arch_step through the function
-     * pointer the engine handed us. Under tensor parallel N rank threads each own one Ctx and one
-     * device and are released against the SAME RadBatch by pointer (spec §1); the batch is const
-     * and nobody writes it during a step. Returns RAD_OK, or the negative status of the first
-     * kernel that refused -- rad_arch_step is void, so the abort has to be latched. */
+    /* Sets the batch and calls the architecture plugin's rad_arch_step. Under tensor parallel each
+     * rank thread owns one Ctx and device, and all share the same const RadBatch by pointer
+     * (spec §1). Returns RAD_OK or the first refusing kernel's status, latched because
+     * rad_arch_step is void. */
     int run_step(const RadBatch* b);
 
-    /* The rank thread must call this once before its first run_step: the device backend's "current
-     * device" is thread-local, and init may well have run on the engine's thread. */
+    /* Call once on the rank thread before its first run_step: the backend's current device is
+     * thread-local, and init may have run on another thread. */
     int bind_thread();
 
     /* ---------------------------------------------------------- run-phase queries */
@@ -249,18 +207,15 @@ public:
     RadStream       stream()     const { return stream_; }
     Program*        program()    const { return program_; }
 
-    /* The lane subsequent issues launch on, and the stream that is. Lane 0 is `stream_` and is
-     * what every architecture that does not ask for a second lane ever sees. See lane1_ for the
-     * three things a second lane may not do. */
+    /* The lane subsequent issues launch on, and its stream. Lane 0 is `stream_`. See lane1_ for
+     * the constraints on a second lane. */
     RadStream       cur_stream() const { return lane_ ? lane1_ : stream_; }
     int             lane()       const { return lane_; }
     int             set_lane(int lane);
-    /* Builds the second stream and its events on first use. Never called by an architecture that
-     * does not ask for a lane, which is what keeps this feature free when it is unused. */
+    /* Builds the second stream and its events on first use; free when no lane is asked for. */
     int             lane_init();
-    /* Order `to` behind everything already issued on `from`: an event recorded on `from` that
-     * `to` waits for. The HOST does not block, and neither stream is drained -- this is the only
-     * thing that makes two lanes a pipeline rather than a race. */
+    /* Order `to` behind everything already issued on `from` (event record + stream wait). The
+     * host does not block and neither stream is drained. */
     int             lane_join(int from, int to);
 
     void* weight_ptr(rad_weight w);
@@ -276,103 +231,75 @@ public:
             return nullptr;
         return route_dev_ + (int64_t)layer * route_n_expert_;
     }
-    /* How many layers reported routing, which is how many the heat engine has to sweep. Zero on a
-     * dense model, where nothing routes and bind_routing allocated nothing. */
+    /* How many layers report routing (the heat engine's sweep). Zero on a dense model. */
     int               n_route_layers() const { return (int)route_.size(); }
     int64_t           route_n_expert() const { return route_n_expert_; }
 
     /* ---------------------------------------------------- the next-layer expert prefetch
-     * (xprefetch.h). xp_open at bringup, once the placement has made its pinned pools: their device
-     * ranges and unit strides; it stays off -- and the three calls no-ops -- where the backend or the
-     * placement gives it nothing to do. */
+     * (xprefetch.h). xp_open at bringup, after placement has made its pinned pools, with their
+     * device ranges and unit strides. Where there is nothing to do it stays off and the three
+     * calls are no-ops. */
     void xp_open(const uint64_t* lo, const uint64_t* hi, const uint64_t* stride, int n);
     void xp_close();
     int  xp_predict(const RadPrefetchNext* next, rad_buf h, int64_t r0, int64_t rows, int64_t n_embd);
     int  xp_mark();
     int  xp_step(int layer);
-    /* DRAIN, DO NOT SAMPLE. `next_histogram` returns the oldest staging bank holding a LANDED
-     * histogram for a step past `after_step` and before `before_step`, or -1; a caller loops on it
-     * with the step of the last one it credited and so sees every histogram the device produced,
-     * in order, rather than whichever one happened to be newest when it looked. The three readers
-     * below take the bank it returned. Null / -1 / 0 for a layer that has never reported.
+    /* Drain, do not sample. `next_histogram` returns the oldest bank holding a landed histogram
+     * for a step in (`after_step`, `before_step`), or -1. A caller loops on it with the step it
+     * last credited, so it sees every histogram in order. The readers below take that bank; they
+     * return null / -1 / 0 for a layer that never reported.
      *
-     * `before_step` IS THE STEP THE CALLER IS ABOUT TO ISSUE, and a bank of that step or later is
-     * not finished. A step runs as more than one pass when it drafts, every pass reports into the
-     * step's one bank, and the drain runs again before each of them: a bank credited between two
-     * passes stands for the passes so far, and the rest land after `after_step` has moved to that
-     * step, where nothing will ever read them.
+     * `before_step` is the step about to be issued; its bank is unfinished, because a drafting
+     * step runs several passes into one bank and the drain runs before each.
      *
-     * `landed`, when given, is kRouteBanks entries of -1 that this fills in as it asks: whether a
-     * bank's copy has landed is the bank's answer, not the layer's, so a sweep over every layer
-     * asks each bank's event once rather than once a layer. */
+     * `landed`, when given, is kRouteBanks entries initialised to -1 and filled in as banks are
+     * queried, so a sweep over all layers queries each bank's event once. */
     int               next_histogram(int layer, int after_step, int before_step,
                                      int8_t* landed = nullptr) const;
     const int32_t*    last_histogram(int layer, int bank) const;
     int               last_histogram_step(int layer, int bank) const;
-    /* How many times that layer reported into that bank. 1 for every layer of a non-speculative
-     * step; n_spec for a draft head. See RouteSlot::reports. */
+    /* Reports into that bank: 1 normally, n_spec for a draft head. See RouteSlot::reports. */
     int               last_histogram_reports(int layer, int bank) const;
-    /* HISTOGRAMS THE RING LOST: a bank recycled for a later step while it still held an
-     * uncredited copy, which is what says the ring is shallower than the host's run-ahead. Nothing
-     * reads a dropped histogram, so this is the whole of the error in the routing-evidence
-     * accounting. A further pass of the SAME step reporting into its bank is not a loss: the bank
-     * counts it in `reports` and is credited for all of them at once. */
+    /* Histograms the ring lost: banks recycled for a later step while still uncredited, i.e. the
+     * ring is shallower than the host's run-ahead. Another pass of the same step reporting into
+     * its bank is not a loss (it counts in `reports`). */
     uint64_t          route_dropped() const { return route_dropped_; }
-    /* Told by the drain, so the ring knows which banks are still owed a reader. */
+    /* Called by the drain, so the ring knows which banks are still unread. */
     void              mark_credited(int layer, int bank);
     const RadRouting* last_routing(int layer) const;
 
     /* ---------------------------------------------------------- the placement seam */
-    /* Change an op's execution site. Refuses with RAD_E_NOKERNEL, naming the op and the band, if
-     * the requested domain has a hole in its bucket table -- §5.1 says the planner was told at
-     * declare which sites are unavailable, so asking for one anyway is a planner bug and not a
-     * runtime condition to paper over. */
+    /* Change an op's execution site. Refuses with RAD_E_NOKERNEL, naming op and band, if the
+     * domain has a hole in its bucket table: the planner knew the unavailable sites at declare
+     * (§5.1), so this is a planner bug. */
     int  set_op_domain(rad_op h, int domain);
     int  op_domain(rad_op h) const;
-    /* The mover calls this after relocating weights. WeightInfo::generation is honoured BETWEEN
-     * steps rather than per issue: a per-issue atomic load of a cold WeightInfo line costs more
-     * than the relocation it guards against, and within a step the ResidencyTable is the
-     * authority on where a weight is. */
-    void note_weights_moved() { weights_dirty_.store(true, std::memory_order_release); }
-
     /* ---------------------------------------------------------- diagnostics */
-    /* OpPlan::issued -> Program::ops[i].issued, which is what /graph publishes. Called at the end
-     * of every step, and it must be: without it the graph dump reports every op in the model as
-     * never issued, and a reader using that to find a dead declaration gets all of them. */
+    /* OpPlan::issued -> Program::ops[i].issued, which /graph publishes. Must run at the end of
+     * every step, or the graph dump reports every op as never issued. */
     void        flush_issued();
     void        dump_profile() const;      /* spec §16, opt-in, with its caveat printed */
     const char* step_error() const { return step_fail_.c_str(); }
     int64_t     stream_waits() const { return n_stream_waits_; }
-    /* Host synchronisations the runtime performed on the STEP PATH. Zero, always, unless per-op
-     * timing is on -- which is the caveat in spec §16 expressed as a number a test can read,
-     * rather than a claim in a comment. Teardown's drain is not counted; it is not a step. */
+    /* Host synchronisations on the step path. Always zero unless per-op timing is on (spec §16);
+     * tests read it. Teardown's drain is not counted. */
     int64_t     host_syncs()   const { return n_host_syncs_; }
-    /* WHAT THIS RANK PUT ON THE INTERCONNECT, and why it is counted here rather than in the
-     * kernel. The link between the two cards carries two completely different things -- the
-     * tensor-parallel all-reduce after every attention and MLP block, and the expert mover's
-     * promotions and demotions -- and they compete for the same PCIe bytes. The mover counts its
-     * own (MoverStats) and this counts the collective's, so "is the link busy because the model is
-     * wide or because placement is thrashing" has an answer.
+    /* This rank's all-reduce traffic. The inter-card link carries both the tensor-parallel
+     * all-reduce and the expert mover's transfers; the mover counts its own (MoverStats), so the
+     * two can be told apart.
      *
-     * `ar_bytes` is the MESSAGE PAYLOAD: numel * the operand's element size, summed over issues.
-     * At two ranks that IS the bytes this rank pushes across the link -- libr4d's one-shot exact
-     * kernel pushes the whole input into the peer's scratch once, and the two-shot's
-     * reduce-scatter plus all-gather is (N-1)/N of it twice, which is the same at N=2. At more
-     * ranks it is a floor. A lossy wire (--tp-wire) compresses below it and the number stays the
-     * payload, because what a reader is comparing against the mover's bytes is the traffic the
-     * model asked for, not the encoding it got.
+     * `ar_bytes` is the message payload, numel * element size, summed over issues. At two ranks
+     * that equals the bytes pushed across the link (one-shot and two-shot alike); at more ranks it
+     * is a floor. A lossy wire (--tp-wire) still counts the uncompressed payload.
      *
-     * Relaxed atomics: written by this rank's step thread, read by whatever thread is drawing. */
+     * Relaxed atomics: written by this rank's step thread, read by any thread. */
     int64_t     ar_calls() const { return ar_calls_.load(std::memory_order_relaxed); }
     int64_t     ar_bytes() const { return ar_bytes_.load(std::memory_order_relaxed); }
 
-    /* HOW EACH PASS WAS RUN, since the host cost of a pass is almost all in which of these it
-     * took: a play writes the recorded packets, every other outcome walks the architecture's
-     * issue path. `issued_*` split the passes that had no tape to play by why -- the pass had no
-     * key, its key was refused, or its key was seen for the first time. `audited` counts the
-     * plays that re-issued to check the tape. `dispatched` is the kernels the plays wrote and
-     * `unordered` how many of them went without the barrier bit (see haz_mark). Same threading as
-     * ar_calls. */
+    /* How each pass was run. A play writes recorded packets; every other outcome walks the issue
+     * path. `issued_*` split unplayed passes by cause: no key, key refused, key seen first time.
+     * `audited` counts plays re-issued to check the tape. `dispatched` is the kernels plays wrote,
+     * `unordered` those without the barrier bit (haz_mark). Same threading as ar_calls. */
     struct PassCounts {
         int64_t played = 0, recorded = 0, audited = 0;
         int64_t issued_unkeyed = 0, issued_refused = 0, issued_first = 0;
@@ -391,128 +318,108 @@ public:
         return c;
     }
     void*       arena_base()   const { return arena_.base(); }
-    int64_t     arena_bytes()  const { return arena_.bytes(); }
     void*       scratch()      const { return arena_.scratch(); }
 
     /* ---- the arena's levels ------------------------------------------------------------------
      *
-     * Level 0 is the plan the arena was built for: every buffer sized for the largest step. A
-     * later level is the same buffers packed for a step of at most `rows` tokens (ArenaLevel,
-     * core/build/rad_bufplan.cpp), so the arena past its `end` is free while the steps are that
-     * small -- and the engine lends it to the expert slab. The fixed region is at the same address
-     * in every level, which is what lets a persistent buffer outlive a change of level.
+     * Level 0 is the plan the arena was built for, every buffer sized for the largest step. A
+     * later level packs the same buffers for steps of at most `rows` tokens (ArenaLevel,
+     * core/build/rad_bufplan.cpp); the arena past its `end` is then lent to the expert slab. The
+     * fixed region has the same address in every level, so persistent buffers survive a change.
      *
-     * A LEVEL IS CHANGED BETWEEN STEPS, NEVER DURING ONE, and only while this rank's thread is
-     * parked: every issue reads the active table, and a step that saw two would hand one op a
-     * buffer another op of the same step had placed somewhere else. The operand guard in issue
-     * checks against the active level's extents, so a step larger than its level is refused by
-     * name rather than written past the level's end into lent memory. */
+     * Invariant: the level changes only between steps, while this rank's thread is parked. The
+     * operand guard in issue checks the active level's extents, so a step larger than its level
+     * is refused instead of writing into lent memory. */
     int         add_level(int64_t rows, const std::vector& offset,
                           const std::vector& decl);
     int         set_level(int level);
     int         level() const { return level_; }
-    int         n_levels() const { return (int)level_tmpl_.size(); }
+
+    /* The key a pass over `b` is recorded and played under (see "recorded passes" below); 0 for a
+     * pass that is never recorded. Public so tests can check that it reads every dependency. */
+    uint64_t    pass_key(const RadBatch* b) const;
 
 private:
     int  prepare();
     int  bind_arena();
     int  bind_buffers();
-    int  bind_weights(bool refresh_only);
+    int  bind_weights();
     int  bind_ops();
     int  bind_routing();
     int  bind_profiling();
     int  check_domain(rad_op h, int domain) const;
-    /* Whether the kernel serving this op on `domain` reads the layout the weights are STORED in.
-     * A weight is stored once, in the claiming DEVICE row's arrangement, so a domain move can
-     * hand a kernel a plane it cannot read -- same byte count, different order, no shape check
-     * anywhere can see it. Fills `why` with the sentence and leaves the severity to the caller. */
+    /* Whether the kernel serving this op on `domain` reads the layout the weights are stored in.
+     * A weight is stored once, in the claiming device row's arrangement, so a domain move can hand
+     * a kernel a plane of the right size in the wrong order. Fills `why`; the caller picks the
+     * severity. */
     int  check_domain_layout(rad_op h, int domain, std::string* why) const;
     void profile_collect();
-    /* Which staging bank the heat engine may read. Mid-step that is the one this step is NOT
-     * filling; between steps it is simply the freshest, so "one step stale" means exactly one
-     * step and never two. */
     uint64_t route_dropped_ = 0;
 
-    /* The handle-to-pointer resolution, shared by the issue path and rad_weight_ptr. Waits on the
-     * mover's event where one is pending, on the STREAM, never on the host. */
+    /* Handle-to-pointer resolution for the issue path and rad_weight_ptr. Waits on a pending mover
+     * event on the stream, never on the host. */
     void* resolve_weight(rad_weight w);
 
-    /* ---- weight TABLES (RAD_OPK_WTAB), which a routed mixture of experts issues and nothing
-     * else does.
+    /* ---- weight tables (RAD_OPK_WTAB), issued by routed mixture-of-experts layers.
      *
-     * A run of consecutively declared weights becomes a DEVICE ARRAY OF POINTERS, because after
-     * placement a layer's experts are not in one place and `base + e*stride` is true only of the
-     * all-in-VRAM case. One table per (op, operand position), bound at prepare and kept.
+     * A run of consecutively declared weights becomes a device array of pointers, because after
+     * placement a layer's experts are not contiguous. One table per (op, operand position), bound
+     * at prepare.
      *
-     * The first issue resolves every entry and uploads the whole array from `host`, which is
-     * pinned because the copy is asynchronous and never written again. After that the device
-     * array changes only by patch (runtime/wtab.h): the residency table names the weights the
-     * mover changed (ResidencyTable::changes), sync_residency queues each one against the tables
-     * holding it, and the table's next issue resolves those entries and writes the ones whose
-     * pointer differs from `cur`. A step moves a handful of experts, so that is a handful of
-     * resolves, where re-walking every table whenever anything moved would be the whole expert
-     * set of every routed layer on most steps. */
+     * The first issue resolves every entry and uploads the array from `host` (pinned, since the
+     * copy is async). After that the device array changes only by patch (runtime/wtab.h):
+     * sync_residency queues ResidencyTable::changes against the tables holding each weight, and
+     * the next issue resolves those entries and writes the ones that differ from `cur`. */
     struct WeightTable {
         uint64_t   key   = 0;         /* (op << 32) | operand position */
         rad_weight first = 0;
         int64_t    n     = 0;
         void**     host  = nullptr;
         void*      dev   = nullptr;
-        /* THE SHAPE AGREEMENT IS CHECKED ONCE, AT THE FIRST ISSUE, beside the first upload. What
-         * the check compares -- dtype, rank, shape and stride of each entry against entry 0 -- are
-         * declaration facts, fixed before a step has ever run and incapable of changing
-         * afterwards. */
+        /* Entries' dtype, rank, shape and stride are checked against entry 0 once, at the first
+         * issue; they are declaration facts and cannot change. */
         bool       checked = false;
         std::vector   cur;     /* what the device array holds, entry for entry */
         std::vector pend;    /* entries a residency change named since the last issue */
         bool                 full = false;   /* every entry: the templates were rebound */
     };
-    /* Which tables hold a weight, as a list per weight: `wmemb_head_[w]` indexes `wmemb_`, and
-     * -1 means none. A table's entries are declared weights, and nothing stops two ops sharing a
-     * run, so a weight can be in more than one. */
+    /* Which tables hold a weight, as a linked list per weight: `wmemb_head_[w]` indexes `wmemb_`,
+     * -1 means none. Two ops may share a run, so a weight can be in several tables. */
     struct WMemb { int32_t slot, entry, next; };
     std::vector  wmemb_head_;
     std::vector    wmemb_;
-    /* Whether a weight was ever resolved straight into an operand (RAD_W, rad_weight_ptr) rather
-     * than through a table. Such a pointer is part of the pass's arguments, so a move of that
-     * weight bumps `dense_epoch_`; a move of a table-only weight changes one device entry. */
+    /* Whether a weight was ever resolved directly into an operand (RAD_W, rad_weight_ptr) rather
+     * than through a table. Such a pointer is in the pass's arguments, so moving it bumps
+     * `dense_epoch_`; moving a table-only weight changes one device entry. */
     std::vector  w_direct_;
     uint64_t              dense_epoch_ = 0;
-    /* The residency table's changes, queued against the tables they touch. Once a pass, before
-     * any of it is issued. */
+    /* Queues the residency table's changes against the tables they touch. Once per pass, before
+     * anything is issued. */
     void sync_residency();
     /* Brings the table's device array up to date on the current stream: every entry on the first
      * issue, afterwards the queued ones. */
     int  table_refresh(rad_op h, int operand, WeightTable& t);
     /* ------------------------------------------------------------------ recorded passes
      *
-     * A DECODE PASS IS THE SAME PASS STEP AFTER STEP: the same kernels, with the same arguments,
-     * on the same queues. Everything the host does to produce it -- the architecture's block code,
-     * the operand resolution in `issue`, the kernel library's argument packing, the dispatch -- is
-     * therefore the same work repeated, and it is almost the whole of a rank thread's time. So a
-     * pass is recorded once (the backend keeps the finished packets and argument blocks, see
-     * DeviceBackend::tape_begin) and after that written straight into the queues.
+     * A decode pass repeats step after step: same kernels, arguments and queues. The host work
+     * that produces it (block code, operand resolution, argument packing, dispatch) is most of a
+     * rank thread's time, so a pass is recorded once (DeviceBackend::tape_begin keeps the finished
+     * packets and argument blocks) and then written straight into the queues.
      *
-     * WHAT MAKES TWO PASSES THE SAME is the KEY: every field of the batch that a pass's shape or
-     * arguments can depend on -- counts, the host-side bounds, every device pointer, each KV
-     * group's geometry -- and the runtime state the issue path reads: the arena level, the weight
-     * templates, the directly resolved weights (dense_epoch_), the op domains, and the lane and
-     * host-arena bookkeeping a pass starts from. The batch builder rounds the two bounds that grow
-     * with the context (batch.cpp, bound_bucket), which is what keeps a key standing for hundreds
-     * of steps. The step number is not in it: nothing a pass issues depends on it except the
-     * routing bank, which is the host's.
+     * Key: every batch field a pass's shape or arguments can depend on (counts, host-side bounds,
+     * device pointers, KV group geometry) plus the runtime state the issue path reads (arena
+     * level, weight templates, dense_epoch_, op domains, lane and host-arena bookkeeping). The
+     * batch builder rounds the context-growing bounds (batch.cpp, bound_bucket) so a key holds for
+     * many steps. The step number is excluded; only the host-side routing bank depends on it.
      *
-     * WHAT A TAPE CANNOT HOLD is the host work inside a pass, and it is cut around each piece and
-     * replays it: a HOST-site op (joined and run again, on the operands it recorded), a routed
-     * layer's report (the host bookkeeping; the copy is in the tape), and a weight table's refresh
-     * (the patch of whatever the mover changed since, see table_refresh). A table the mover did
-     * not touch costs its step a flag test.
+     * Host work inside a pass is cut out of the tape and replayed: host-site ops (rerun on their
+     * recorded operands), routed-layer reports (host bookkeeping; the copy is in the tape) and
+     * weight-table refreshes (table_refresh). An untouched table costs a flag test.
      *
-     * TRUSTED ONLY AFTER IT IS CHECKED. A key is recorded the second time it is seen, recorded
-     * again and compared the third, and only then played; a played tape is compared against a
-     * fresh issue again every kAuditPlays plays. A difference means the pass depends on something
-     * the key does not carry, and it fails the step naming the first dispatch that differs -- a
-     * silent difference would be wrong output. */
+     * Verification: a key is recorded on its second sighting (first, for decode), recorded again
+     * and compared on the next, and only then played. Every kAuditPlays plays the tape is compared against a fresh
+     * 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 };
     /* A prefetch call (Ctx::xp_predict), run again where the pass made it. */
@@ -550,17 +457,15 @@ private:
         uint64_t used = 0;
         int32_t  dispatches = 0, unordered = 0;   /* its kernels, and those haz_mark left unordered */
     };
-    /* WHAT EACH DEVICE OP OF A PASS BEING RECORDED READS AND WRITES, as byte ranges, so the tape
-     * can be played with the dispatches that depend on nothing still running left unordered
-     * behind it (haz_mark). The packet processor otherwise waits for each kernel to finish before
-     * it launches the next, and on independent kernels that wait is pure idle.
+    /* The byte ranges each device op of a recorded pass reads and writes, so haz_mark can leave
+     * dispatches that depend on nothing still running without the barrier bit. Otherwise the
+     * packet processor waits for each kernel to finish before launching the next.
      *
-     * Ranges come from the operands the op was issued with and the roles its schema gives them --
-     * a weight is never written in a pass, a table's entries are written only between played
-     * stretches -- and the op's scratch is a range like any other. What cannot be bounded makes
-     * the op OPAQUE, ordered on both sides: a kernel whose plugin does not promise it touches
-     * nothing else (rad_kernel_concurrent), a collective (its flags live outside every operand),
-     * an op with no schema, an operand with no extent. */
+     * Ranges come from the issued operands and their schema roles (weights are never written in a
+     * pass; table entries only between played stretches); scratch is a range like any other. An
+     * op is opaque, ordered on both sides, if it cannot be bounded: a kernel not marked
+     * rad_kernel_concurrent, a collective (its flags are outside every operand), an op with no
+     * schema, or an operand with no extent. */
     struct HazOp {
         int32_t  rec0 = 0, rec1 = 0;      /* its dispatches in the tape */
         uint32_t op = 0;
@@ -589,16 +494,26 @@ private:
     int                   rec_mark_ = 0;       /* the backend record its current play step starts at */
     std::atomic domain_epoch_{0};    /* bumped by set_op_domain */
 
-    uint64_t pass_key(const RadBatch* b) const;
     int      run_pass(const RadBatch* b);
     int      record_pass(const RadBatch* b, uint64_t key, PassTape* out);
     int      play_pass(PassTape& t);
     void     tape_cut();                        /* while recording: close the current play step */
+    /* While recording: `st` becomes a host step that re-runs at every play. Closes the current
+     * play step, appends `st` on this lane, and runs `run` with the device tape paused. */
+    template  int tape_host(TapeStep st, F&& run) {
+        tape_cut();
+        st.lane = (uint8_t)lane_;
+        rec_->steps.push_back(st);
+        tape_pause(true);
+        const int rc = run();
+        tape_pause(false);
+        return rc;
+    }
     void     tape_drop(PassTape& t);
     static bool tapes_agree(const PassTape& a, const PassTape& b, std::string* why);
     bool     tape_seen(uint64_t key);           /* true the second time a key is asked about */
-    /* A routed layer's report. With `copy` false it is the host bookkeeping alone, which is what a
-     * replay runs: the copy itself is in the tape. */
+    /* A routed layer's report. `copy` false runs only the host bookkeeping, as a replay does; the
+     * copy is in the tape. */
     int      route_report_impl(int layer, const RadRouting* r, bool copy);
 
     std::vector              wtabs_;
@@ -614,50 +529,49 @@ private:
                             RadTensor* out);
     void free_weight_tables();
 
-    /* Cold, noinline paths. Kept out of issue() so the hot path stays one straight line. */
+    /* Cold, noinline paths, kept out of issue(). */
     int  abort_step(rad_op h, int band, int dom, const IssuePlan& ip, int64_t n, int status);
     int  abort_step_msg(rad_op h, int status, std::string what);
 
 public:
-    /* What rad_step_fail() reaches. Same effect as an operand rejection -- the step stops and the
-     * message is what the engine prints -- with the reason coming from the caller. */
+    /* Backs rad_step_fail(): stops the step like an operand rejection, with the caller's
+     * message. */
     int  step_fail(const char* what);
 private:
     [[noreturn]] void fatal_issue(rad_op h, int64_t n, const char* why) const;
 
-    /* ---- the op oracle. runtime/oracle.cpp; inert unless RADIANCE_OP_ORACLE names an op.
-     * It runs the HOST kernel for the same (op, band) on a host copy of the operands the device
-     * kernel was just given, and compares. Everything about it is off the hot path: `oracle_` is
-     * null in every run that did not ask for it, and the one branch that reads it is the same
-     * predictable not-taken compare as the profiling branch beside it. */
+    /* ---- the op oracle (runtime/oracle.cpp), inert unless RADIANCE_OP_ORACLE names an op. Runs
+     * the host kernel for the same (op, band) on a host copy of the device kernel's operands and
+     * compares. `oracle_` is null otherwise, so the hot path pays one not-taken branch. */
     struct OracleState;
     OracleState* oracle_ = nullptr;
     void  oracle_open();
     void  oracle_close();
     bool  oracle_arm(rad_op h) const;
-    /* Extents, aliasing and the per-operand byte count for one issue. Separate from the copy
-     * because a weight TABLE operand is an array of pointers and its snapshot is the STACKED
-     * plane behind them -- a size the operand itself does not state. */
+    /* Extents, aliasing and per-operand byte counts for one issue. Separate from the copy because
+     * a weight-table operand's snapshot is the stacked plane behind its pointers, a size the
+     * operand does not state. */
     void  oracle_size(rad_op h, int n_opd);
     int64_t oracle_opd_bytes(int i) const;
     void  oracle_snap(int n_opd, bool post);
     void  oracle_run(rad_op h, const IssuePlan& hip, int64_t seq, int n_opd);
-    /* Put a re-laid weight back into the form a dense reference reads, through the DEVICE row's
-     * own inverse, into the logical form the HOST row describes. False when the comparison cannot
-     * be made honestly, which is a named skip. */
+    /* Converts a re-laid weight back, through the device row's inverse, into the logical form the
+     * host row reads. False (a named skip) when no valid comparison is possible. */
     bool  oracle_unrelayout(rad_op h, const IssuePlan& hip, const IssuePlan& dip, int64_t seq,
                           int n_opd);
-    /* Repeat mode (RADIANCE_OP_REPEAT): no host kernel. The DEVICE plan is re-launched on the
-     * restored bytes and the two results are byte-compared, which names a kernel that is not a
-     * function of its inputs. A host-vs-device oracle structurally cannot see that: both of its
-     * sides run once, so a kernel that answers differently on the same bytes agrees with itself
-     * exactly as often as it disagrees. */
+    /* Repeat mode (RADIANCE_OP_REPEAT): re-launches the device plan on the restored inputs and
+     * byte-compares the two results, finding kernels that are not a function of their inputs,
+     * which a host-vs-device comparison cannot detect. */
     void  oracle_repeat(rad_op h, const IssuePlan& dip, int64_t seq, int n_opd);
     const char* ip_kernel_name(rad_op h) const;
+    /* The reference library's host plan for (op, band): the band's own host plan when a reference
+     * library won it, else one resolved from `registry_` on first use. Null when none exists. */
+    const IssuePlan* oracle_reference(rad_op h, int band);
     const IssuePlan* oracle_before(rad_op h, int band, int n_opd);
     void  oracle_after(rad_op h, const IssuePlan& hip, const IssuePlan& dip, int n_opd);
 
     Program*        program_   = nullptr;
+    Registry*       registry_  = nullptr;   /* CtxDesc::registry */
     std::vector kv_;   /* by rad_kvgroup; RAD_OPK_KV resolves through it */
     ResidencyTable* residency_ = nullptr;
     OpStager*       stager_ = nullptr;
@@ -681,82 +595,61 @@ private:
     RadStream stream_     = nullptr;
     bool      own_stream_ = false;
 
-    /* ---- THE SECOND LANE, and it exists for exactly one thing: overlapping the tensor-parallel
-     * all-reduce with compute at prefill, which is worth on the order of 15% of prefill
-     * throughput. Nothing else may use it without reading the three constraints below.
+    /* ---- The second lane: overlaps the tensor-parallel all-reduce with compute at prefill
+     * (order of 15% prefill throughput). Any use must respect these constraints:
      *
-     * ONE: EVERY COLLECTIVE MUST RIDE THE SAME LANE. The all-reduce carries a per-block `seq`
-     * counter and double-buffers its scratch on `seq & 1`, so two launches that race differently
-     * on the two ranks would pick DIFFERENT slots for the same message and deadlock or corrupt.
-     * Both ranks run the same architecture code, so putting every all-reduce on lane 1 keeps them
-     * ordered against each other and therefore identically numbered on both ranks. Splitting the
-     * collectives ACROSS lanes is the bug this comment exists to prevent.
+     * 1. Every collective rides the same lane. The all-reduce double-buffers its scratch on a
+     *    per-block `seq & 1`, so collectives that race differently on two ranks pick different
+     *    slots for the same message and deadlock or corrupt.
      *
-     * TWO: A DEVICE-WIDE ARRIVAL COUNTER MUST BE KEYED ON THE STREAM. `split_ctr` in
-     * r4d_gemm_fp8a8.hip is the split-K finisher's counter, self-resetting, and it is sound only
-     * because two launches of this kernel never overlap -- they are ordered by the same stream.
-     * One counter block for the whole device would hold only with one compute stream a rank; a
-     * second lane running a narrow GEMM beside one on lane 0 breaks it. There is therefore one
-     * counter block a STREAM, so ordering does the work again -- and any OTHER plugin kernel with
-     * a device-wide counter has to do the same or stay off lane 1, because nothing here can check
-     * it.
+     * 2. A device-wide arrival counter must be per stream. `split_ctr` in r4d_gemm_fp8a8.hip (the
+     *    self-resetting split-K finisher counter) is sound only because its launches are ordered
+     *    by one stream, so there is one counter block per stream. Any other plugin kernel with a
+     *    device-wide counter must do the same or stay off lane 1; nothing here can check it.
      *
-     * THREE: THE BUFFER PLANNER PACKS FROM ONE LINEAR ORDER. Two lanes can therefore write the
-     * same arena bytes through two buffers whose declared lifetimes do not overlap. The
-     * architecture names the buffers its second lane touches to `rad_buf_concurrent`, which hands
-     * each of them the whole program -- a few MiB for one block's transients.
+     * 3. The buffer planner packs from one linear order, so two lanes can alias arena bytes
+     *    through buffers with disjoint declared lifetimes. The architecture passes every buffer
+     *    its second lane touches to `rad_buf_concurrent`, which makes it live for the whole
+     *    program.
      *
-     * FOUR: A SLICE MUST LAND IN THE SAME BUCKET-TABLE BAND AS THE WHOLE. This is the one that
-     * would silently change the model's output rather than break it. An op's kernel is chosen by
-     * which band `n` falls in, and `--debug-graph` prints the boundaries a model actually has.
-     * They are sparse and uneven -- a representative set is
+     * 4. A slice must land in the same bucket-table band as the whole, or it picks a kernel with
+     *    a different summation order and silently changes output. `--debug-graph` prints a model's
+     *    band boundaries; a representative set is
      *
-     *     8   16   56   64   256   1024   4096   8192   16384   49152   65536
+     *        8   16   56   64   256   1024   4096   8192   16384   49152   65536
      *
-     * so a 4096-token chunk cut in HALF gives 2048 and 2048, both inside (1024, 4096] and both
-     * resolving to the same kernel -- while cutting it in FOUR gives 1024, which is the TOP of the
-     * band below and picks a different kernel with a different summation order. The ragged last
-     * chunk of a prompt is worse: 16449 tokens is four full chunks and then 65, and halving 65
-     * crosses the boundaries at 64 and 56. So the rule a pipelined path must obey is that every
-     * slice sits strictly above the largest boundary below T, which at a 4096-token chunk means
-     * TWO slices and no more.
+     *    Halving a 4096-token chunk gives 2048 + 2048, inside (1024, 4096]; quartering gives
+     *    1024, the top of the band below. A ragged last chunk of 65 halves across 64 and 56. Every
+     *    slice must sit strictly above the largest boundary below T, which at 4096 means at most
+     *    two slices. The architecture's own T-dependent selections hold at two slices:
+     *    `ar_wire_is_exact` flips only below T = 13, and the gated-GEMM fold and fused attention
+     *    prologue band at T <= 64.
      *
-     * The T-dependent selections inside the architecture hold at two slices: `ar_wire_is_exact`
-     * only flips below T = 13 (`numel * 2 < wire_min_bytes`), and the gated-GEMM fold and the
-     * fused attention prologue both band at T <= 64.
-     *
-     * WHAT MAKES ALL OF THIS WORTH IT: a many-block SPINNING kernel on one stream does not starve
-     * a bandwidth-bound kernel on another. The all-reduce launches min(M, 256) blocks that spin on
-     * a peer flag while the fabric drains, and if those held their CUs there would be nothing to
-     * overlap with. Run a dependent-FMA spinner and a large copy on two streams and the pair costs
-     * the MAX of the two rather than the sum: the copy finishes inside the spinner's window at
-     * every block count, including counts higher than the part can hold resident at once. */
+     * The overlap works because a many-block spinning kernel on one stream does not starve a
+     * bandwidth-bound kernel on another: the all-reduce's min(M, 256) blocks spin on a peer flag,
+     * and a spinner plus a large copy on two streams cost the max of the two, not the sum. */
     RadStream lane1_      = nullptr;
     bool      own_lane1_  = false;
     int       lane_       = 0;
     RadEvent  lane_ev_[2] = { nullptr, nullptr };
-    /* THE LAST DEVICE OP ON EACH LANE THAT TOUCHED HOST-DOMAIN MEMORY. A host op reads and writes
-     * the host arena at issue, on this thread, while the device may still be working through what
-     * this thread issued before it. What it has to be ordered behind is every device op that
-     * touched the host arena before it -- the producer of its input, or a reader of bytes its
-     * output reuses -- and on each lane those complete no later than the last of them. So a device
-     * op with a host-domain buffer operand re-records its lane's event, and a host op waits on the
-     * recorded ones instead of on everything the stream holds (see the host join in Ctx::issue). */
+    /* The last device op on each lane that touched host-domain memory. A host op runs at issue on
+     * this thread and must be ordered behind every earlier device op that touched the host arena;
+     * on each lane those complete no later than the last one. So a device op with a host-domain
+     * operand re-records its lane's event, and a host op waits on those events instead of draining
+     * the streams (see the host join in Ctx::issue). */
     RadEvent  host_touch_ev_[2]      = { nullptr, nullptr };
     bool      host_touch_pending_[2] = { false, false };
     int       host_join(const RadOperand* opd, int n_opd);
     bool      host_join_drains(const RadOperand* opd, int n_opd) const;
     int       host_join_wait(bool drain);
-    /* A lane issued a kernel that uses the shared scratch region and the other lane has not been
-     * joined behind it since. The issue path reads these to keep two scratch users off the region
-     * at once; lane_join clears its `from` side. See the scratch block in Ctx::issue. */
+    /* A lane issued a scratch user and the other lane has not been joined behind it since. Keeps
+     * two lanes off the shared region at once; lane_join clears its `from` side. See the scratch
+     * block in Ctx::issue. */
     bool      scratch_open_[2]    = { false, false };
     bool      scratch_join_warned_ = false;
-    /* WHERE IN ITS REGION THE NEXT SCRATCH USER STARTS. Consecutive users are handed consecutive
-     * slices rather than all the same bytes, wrapping to the start when one does not fit, so two
-     * of them that are otherwise independent share nothing and may run at once (haz_mark). Back
-     * to zero at the start of every pass, so a pass issued twice hands its ops the same slices --
-     * the pointers are in its recording's arguments. */
+    /* Where in its region the next scratch user starts. Consecutive users get consecutive slices,
+     * wrapping when one does not fit, so independent users share no bytes and may overlap
+     * (haz_mark). Reset every pass, so a re-issued pass gets the same slices as its recording. */
     int64_t   scratch_cur_[2]     = { 0, 0 };
     void*     scratch_take(int region, int64_t bytes);
     /* The kernel that last opened each lane's scratch, and its row count, for the warning. */
@@ -768,44 +661,40 @@ private:
 
     const RadBatch* batch_ = nullptr;
 
-    /* Per-issue tensor storage, bound into every IssuePlan::args.t at prepare so an issue stores
-     * n_t and nothing else. One array, because issues do not nest. */
+    /* Per-issue tensor storage, bound into every IssuePlan::args.t at prepare. One array, because
+     * issues do not nest. */
     RadTensor tbuf_[MAX_OPERANDS];
 
-    /* Prebuilt tensor templates, indexed by handle. A buffer's template already carries its arena
-     * pointer, dtype, shape and packed strides; a weight's already carries WeightInfo::ptr. An
-     * issue copies one and patches at most the data pointer and dim 0. */
+    /* Prebuilt tensor templates by handle: a buffer's carries its arena pointer, dtype, shape and
+     * packed strides; a weight's carries WeightInfo::ptr. An issue copies one and patches at most
+     * the data pointer and dim 0. */
     std::vector buf_tmpl_;
     std::vector   buf_bits_;
     std::vector   buf_host_;   /* per handle: a RAD_DOMAIN_HOST buffer */
-    /* Every level's templates; `buf_tmpl_` is a copy of the active one, so the issue path reads
-     * one vector whatever level it is at. */
+    /* Every level's templates; `buf_tmpl_` is a copy of the active one. */
     std::vector> level_tmpl_;
     int                    level_ = 0;
     std::vector w_tmpl_;
     std::vector   w_bits_;
-    std::vector  w_gen_;        /* the generation each template was built from */
     std::vector  waited_gen_;   /* the generation we last made the stream wait on */
 
     std::vector                 plans_;
-    /* THE OPS NOT YET SEEN ISSUED. flush_issued walks this rather than every op, and drops each
-     * index as it fires, so the per-step cost falls to the ops that have never fired -- which
-     * after a few steps is only the ones that never will, and those are the point. */
+    /* Ops not yet seen issued. flush_issued walks only these and drops each once it fires. */
     std::vector               unflushed_;
     std::vector                band_table_;
     std::vector              issue_table_;
-    /* The parameter lists of the launches handed `link_gate`: the geometry's and that one. A deque,
-     * so a plan's pointer into one stays good as the next is added. */
+    /* Parameter lists (geometry plus `link_gate`) for the launches that take the gate. A deque,
+     * so IssuePlan::gate_p stays valid as entries are added. */
     std::deque>   gate_params_;
     std::vector>   op_domain_;   /* sized once, never resized */
 
     std::vector route_;
     int64_t                route_n_expert_ = 0;
-    /* A BANK IS ONE STEP'S HISTOGRAMS FOR EVERY LAYER, [kRouteBanks][n_layer][n_expert] in pinned
-     * host memory. A report copies one layer's counts into that layer's row on the card,
-     * [n_layer][n_expert], which is a copy within the card and orders nothing else; the end of the
-     * pass copies the rows it touched into the step's bank in one transfer and records the bank's
-     * event. See route_report. */
+    /* A bank is one step's histograms for every layer: [kRouteBanks][n_layer][n_expert] in pinned
+     * host memory. A report copies a layer's counts into its row of the card-side
+     * [n_layer][n_expert] (an on-card copy that orders nothing else); the end of the pass copies
+     * the touched rows into the step's bank in one transfer and records the bank's event. See
+     * route_report. */
     int32_t*               route_pool_     = nullptr;   /* host */
     int32_t*               route_dev_      = nullptr;   /* card */
     RadEvent               route_done_[kRouteBanks] = {};
@@ -813,8 +702,8 @@ private:
     int                    route_bank_ = -1, route_lo_ = 1, route_hi_ = 0;
     int                    route_flush();
 
-    /* Profiling. Off by default; when on it restores synchronisations that change the mover's slot
-     * supply, so a profiled run is not comparable against an unprofiled one (spec §16). */
+    /* Profiling. Off by default; when on it adds synchronisations that change the mover's slot
+     * supply, so profiled and unprofiled runs are not comparable (spec §16). */
     bool                 profiling_ = false;
     struct ProfSlot { RadEvent a = nullptr, b = nullptr; int32_t op = 0; uint8_t lane = 0; };
     std::vector prof_ring_;
@@ -822,27 +711,17 @@ private:
     bool                  prof_overflowed_ = false;
     std::vector   prof_ms_;
     std::vector  prof_calls_;
-    /* Which rows were timed on the HOST clock rather than by a device event pair. The two are not
-     * the same measurement -- a host row includes page faults and link reads, a device row is
-     * kernel time -- so the table says which each one is rather than letting a reader assume. */
+    /* Rows timed on the host clock rather than by a device event pair. A host row includes page
+     * faults and link reads, a device row is kernel time, so the table labels each. */
     std::vector  prof_host_;
-    /* The stream drain a host-site op forces, timed apart from the op itself: it is the cost of
-     * the pipeline the op STOPS, not of the arithmetic it does, and the two differ by two orders
-     * of magnitude on the PLE gather. */
+    /* The stream drain a host-site op forces, timed apart from the op: it is the cost of stopping
+     * the pipeline, which can exceed the op itself by 100x (PLE gather). */
     std::vector   prof_join_ms_;
-    /* How long each op's lane sat idle before the op started: from the end of the op before it on
-     * that lane to this one's start. A stream wait (a staged layer's copies, the other lane, a
-     * host op's output) and a host that has not issued the op yet both land here, and neither is
-     * in any op's own time -- so a step whose ops sum to less than its wall time says where the
-     * rest went. */
+    /* Lane idle time before each op: previous op's end on that lane to this one's start. Stream
+     * waits (staged copies, the other lane, a host op) and late host issue land here, accounting
+     * for wall time the ops' own times do not cover. */
     std::vector   prof_wait_ms_;
 
-    std::atomic weights_dirty_{false};
-    /* Bumped whenever bind_weights rewrites the templates: any weight pointer resolved from one
-     * before may have moved. */
-    uint64_t          w_tmpl_epoch_ = 1;
-
-    bool        in_step_     = false;
     int         step_status_ = RAD_OK;
     std::string step_fail_;
 
diff --git a/core/runtime/issue.cpp b/core/runtime/issue.cpp
index 35a8f0d4..71c09b4e 100644
--- a/core/runtime/issue.cpp
+++ b/core/runtime/issue.cpp
@@ -1,17 +1,13 @@
-/* issue.cpp -- THE hot path, and the C surface the architecture plugin actually calls.
+/* issue.cpp -- the hot path, and the C surface the architecture plugin calls.
  *
- * Per rad_issue, in order: index the op's bucket table with `n`, pick the domain from the resolved
- * instance's current execution site, materialise a RadTensor for each operand out of a template
- * built at declare, resolve every weight handle to a pointer (waiting on the mover's event on the
- * STREAM if the weight is in flight), store the operand count into a RadArgs that was already
- * filled in, and launch.
+ * Per rad_issue: index the op's bucket table with `n`, pick the domain from the op's current
+ * execution site, build a RadTensor per operand from its declare-time template, resolve weight
+ * handles (a stream wait on the mover's event if in flight), set the operand count in the
+ * prefilled RadArgs, and launch.
  *
- * NO ALLOCATION. NO HOST SYNCHRONISATION. NO DEVICE ROUND TRIP. Every one of those is a property
- * you lose by accident, so each of them is checkable here: the only writes are into arrays sized
- * at prepare, the only device call besides the launch is rad_event_wait (which orders a stream and
- * does not block the host), and nothing in this file reads a device value back.
- *
- * See ctx.h for the per-issue cost and where it sits against spec §3.2's budget.
+ * No allocation, no host synchronisation, no device read-back: writes go only to arrays sized at
+ * prepare, and the only device call besides the launch is rad_event_wait, which does not block
+ * the host. See ctx.h for the cost budget (spec §3.2).
  */
 #include 
 #include 
@@ -29,28 +25,22 @@
 
 namespace rad {
 
-/* A COLUMN SLICE: `cols` narrows the LAST dimension while every stride is left alone, so the
- * declared width stays the row pitch. That is what makes a fused projection usable without a
- * copy -- q and the attention gate are interleaved per head inside one buffer, and GDN's `a` and
- * `b` are columns of one in-projection. The element offset is what selects the first column, so
- * the two fields compose: offset picks the start, cols picks the width.
+/* Column slice: `cols` narrows the last dimension and leaves every stride alone, so the declared
+ * width stays the row pitch. This reads a fused projection without a copy (q and the attention
+ * gate interleaved per head; GDN's `a` and `b` in one in-projection). The element offset picks the
+ * first column, `cols` the width.
  *
- * Narrowing the last dimension rather than dim 0 is the whole point: shortening the OUTERMOST
- * dimension leaves every stride correct because they are products of the trailing ones, and
- * shortening the INNERMOST one leaves them correct because nothing is a product of it. Any other
- * dimension would need the strides rewritten, so the ABI offers only these two. */
+ * Only the outermost and innermost dimensions can be shortened without rewriting strides, so the
+ * ABI offers only those two. */
 static inline void narrow_cols(const RadOperand& o, RadTensor* t) {
     if (o.cols > 0 && t->rank >= 1) t->shape[t->rank - 1] = o.cols;
 }
 
-/* DOES THE OPERAND FIT THE BUFFER IT NAMES? The span is the largest element index the descriptor
- * can reach, measured from the buffer's base -- `offset` plus the sum of (extent - 1) * stride
- * over every dimension. It is NOT shape[0] against the declared shape[0]: a row count larger than
- * the declared one is legitimate when `cols` is narrower, because a [T, 2560] buffer read at 160
- * columns IS T*16 rows of 160 and the PLE gather does exactly that. The span is the only reading
- * that accepts the legal case and refuses the overrun.
+/* Whether the operand fits the buffer it names. The span is the largest reachable element index,
+ * `offset` + sum((extent - 1) * stride). Comparing shape[0] instead would be wrong: a [T, 2560]
+ * buffer read at 160 columns is legitimately T*16 rows of 160 (the PLE gather does this).
  *
- * An empty extent reaches nothing and is not an error here; the kernel's own bounds decide. */
+ * An empty extent reaches nothing; the kernel's own bounds decide. */
 static inline bool operand_fits(const RadTensor& t, int64_t offset, const RadTensor& decl) {
     if (offset < 0) return false;
     int64_t span = offset;
@@ -61,9 +51,7 @@ static inline bool operand_fits(const RadTensor& t, int64_t offset, const RadTen
     return span < rad_tensor_numel(&decl);
 }
 
-/* Extents and strides, for the message that refuses. oracle.cpp has one of these in an anonymous
- * namespace; duplicating four lines beats exporting a debug formatter across translation units. */
-static inline std::string opd_shape_str(const RadTensor& t) {
+std::string tensor_shape_str(const RadTensor& t) {
     std::string s = "[";
     for (uint32_t d = 0; d < t.rank; ++d)
         s += fmt("%s%lld", d ? "," : "", (long long)t.shape[d]);
@@ -73,10 +61,9 @@ static inline std::string opd_shape_str(const RadTensor& t) {
     return s + "]";
 }
 
-/* Element offset to byte offset. Split out because the sub-byte cases are the interesting ones:
- * a W4 weight has no addressable odd element, and a plugin-private dtype has no size the core
- * knows at all -- both are refused by name rather than silently truncated into a misaligned
- * pointer. Returns false when the offset cannot be expressed. */
+/* Element offset to byte offset. False when it cannot be expressed: a mid-byte offset into a
+ * packed sub-byte weight (e.g. an odd W4 element), or a plugin-private dtype with no core-known
+ * size. */
 static inline bool byte_delta(int bits, int64_t elems, int64_t* out) {
     if (bits >= 8) { *out = elems * (int64_t)(bits >> 3); return true; }
     if (bits <= 0) return false;                      /* plugin-private: the core has no size */
@@ -87,24 +74,21 @@ static inline bool byte_delta(int bits, int64_t elems, int64_t* out) {
 }
 
 void* Ctx::resolve_weight(rad_weight w) {
-    /* The template already carries WeightInfo::ptr, bound at prepare and refreshed between steps
-     * when the mover says it moved something. In the all-in-VRAM case that is the whole answer and
-     * there is no table, no virtual call and no branch beyond this one. */
+    /* The template carries WeightInfo::ptr, refreshed between steps after a move. In the
+     * all-in-VRAM case that is the answer. */
     void* p = w_tmpl_[w].data;
     if (!residency_) return p;
 
     const WeightSlot* s = residency_->lookup(w);       /* never blocks -- residency.h */
     if (s) {
         p = s->ptr;
-        /* Wait once per generation, not once per issue. A stream wait orders everything issued
-         * after it, so repeating it buys nothing and at eight experts a layer across 64 layers it
-         * would be thousands of runtime calls a step. The mover bumps `generation` when it starts
-         * a transfer, which is what makes the memo sound (residency.h). */
+        /* Wait once per generation, not per issue; a stream wait orders everything issued after
+         * it. Sound because the mover bumps `generation` per transfer (residency.h). */
         if (s->ready && waited_gen_[w] != s->generation) {
-            /* Not part of a recording: once issued it orders everything after it, every later
-             * play included, and a move of a weight a pass names directly re-keys the pass. */
+            /* Kept out of a recording: it orders every later play too, and moving a weight a
+             * pass names directly re-keys the pass. */
             if (rec_) tape_pause(true);
-            rad_event_wait(cur_stream(), s->ready);         /* the STREAM waits; the host does not */
+            rad_event_wait(cur_stream(), s->ready);         /* the stream waits, not the host */
             if (rec_) tape_pause(false);
             waited_gen_[w] = s->generation;
             ++n_stream_waits_;
@@ -115,29 +99,15 @@ void* Ctx::resolve_weight(rad_weight w) {
 
 /* ================================================================== weight tables
  *
- * RAD_OPK_WTAB. See the comment on Ctx::WeightTable and the RAD_WTAB macro in rad_runtime.h: this
- * is where a run of declared weights becomes the device pointer array a grouped GEMM walks.
+ * RAD_OPK_WTAB (Ctx::WeightTable, RAD_WTAB in rad_runtime.h): a run of declared weights becomes
+ * the device pointer array a grouped GEMM walks.
  *
- * THE ENTRIES MUST AGREE ABOUT SHAPE AND DTYPE, and the check is not pedantry -- the kernel is
- * given one set of trailing extents for the whole table and strides its way through an entry with
- * them, so a run that mixes two shapes is a run the kernel reads off the end of. A MoE layer
- * declares 256 identical experts, so this holds by construction and a violation is a plugin bug
- * that is worth naming at the first issue rather than debugging from wrong logits. */
-/* THE TABLE'S MEMORY, ALLOCATED ONCE AND NOT ON THE STEP PATH.
- *
- * Allocating it inside resolve_weight_table, which runs at ISSUE, would have the first step of the
- * first request allocate one pinned array and one device array per grouped-GEMM operand -- an
- * allocator on the step path, and spec §3.1 says there is not one. It would also be invisible to
- * the VRAM budget: the pools are sized before a step has ever run, so those bytes would come out
- * of --gpu-headroom-mib without being named in it.
- *
- * Binding every declared table at prepare() avoids both. The run is a property of the DECLARATION
- * (OpInfo::weights with OpInfo::weight_opd naming the operand position), not of the issue, so
- * there is nothing about it that has to wait for a step. resolve_weight_table still handles a
- * miss, because a plugin may legally issue a table the declaration did not describe -- it just
- * does not happen on any model this engine ships.
- *
- * Returns the slot in wtabs_. */
+ * Entries must agree on shape and dtype: the kernel strides every entry with one set of trailing
+ * extents, so a mixed run reads out of bounds. A violation is a plugin bug, named at first issue. */
+/* A table's pinned and device arrays, allocated once. Normally called from prepare
+ * (bind_weight_tables), so no allocation happens on the step path (spec §3.1) and the bytes are
+ * not taken unbudgeted from --gpu-headroom-mib. resolve_weight_table calls it on a miss, which is
+ * legal for a table the declaration did not describe. Returns the slot in wtabs_. */
 int Ctx::ensure_weight_table(uint64_t key, rad_weight first, int64_t n, size_t* slot_out) {
     auto it = wtab_of_.find(key);
     if (it != wtab_of_.end()) { *slot_out = it->second; return RAD_OK; }
@@ -169,11 +139,9 @@ int Ctx::ensure_weight_table(uint64_t key, rad_weight first, int64_t n, size_t*
     return RAD_OK;
 }
 
-/* Every RAD_OPD_WTAB operand of every declared op, bound before the first step. The run is
- * contiguous by construction -- rad_decl_weight hands out consecutive indices and a declaration
- * loop over experts produces exactly such a run -- so it is the smallest declared handle at that
- * operand position and the count of them. A gap would be a plugin bug, and it is named rather
- * than papered over: a table assembled from a non-contiguous run would read the wrong expert. */
+/* Binds every RAD_OPD_WTAB operand of every declared op before the first step. A run is the
+ * smallest declared handle at that operand position plus the count; rad_decl_weight hands out
+ * consecutive indices, so a gap is a plugin bug and is refused (it would read the wrong expert). */
 int Ctx::bind_weight_tables() {
     const Program& P = *program_;
     int64_t tables = 0, bytes = 0;
@@ -194,7 +162,7 @@ int Ctx::bind_weight_tables() {
             if (cnt <= 0) continue;
             if ((int64_t)(hi - lo) + 1 != cnt) {
                 RAD_ERR("op '%s' operand %d is a weight table of %lld entries whose declared "
-                        "handles run [%u, %u] -- a table must be a CONTIGUOUS run, because the "
+                        "handles run [%u, %u]; a table must be a contiguous run, because the "
                         "kernel is handed one base and strides through it",
                         op.op.c_str(), p, (long long)cnt, lo, hi);
                 return RAD_E_INVAL;
@@ -213,16 +181,14 @@ int Ctx::bind_weight_tables() {
         }
     }
     if (tables > 0)
-        RAD_DEBUG("weight tables: %lld bound at prepare, %s of pointer arrays -- none of it "
-                  "allocated on the step path", (long long)tables, humanb(bytes).c_str());
+        RAD_DEBUG("weight tables: %lld bound at prepare, %s of pointer arrays",
+                  (long long)tables, humanb(bytes).c_str());
     return RAD_OK;
 }
 
 static const bool g_dbg_issue = std::getenv("RADIANCE_DEBUG_ISSUE") != nullptr;
-/* THE WEIGHT-TABLE WALK, charged separately from the rest of `own`. A grouped-GEMM operand names a
- * run of experts; the first issue walks every entry and later ones the entries the mover changed
- * (WeightTable::pend). Two counters -- entries walked, and the wall time of the walks -- so that
- * cost is read directly rather than inferred from the difference between two builds. */
+/* RADIANCE_DEBUG_ISSUE: entries walked and wall time spent in weight-table refreshes, reported
+ * separately from the rest of `own`. */
 static double g_wtab_us = 0.0, g_wtab_us_p = 0.0;
 static long   g_wtab_e  = 0,   g_wtab_e_p  = 0;
 
@@ -232,10 +198,8 @@ int Ctx::resolve_weight_table(rad_op h, int operand, rad_weight first, int64_t n
     size_t slot;
     auto it = wtab_of_.find(key);
     if (it == wtab_of_.end()) {
-        /* A MISS IS NOT THE NORMAL PATH ANY MORE -- bind_weight_tables() bound every table the
-         * declaration describes. Reaching here means a plugin issued a table at an operand
-         * position its declaration did not name as one, which is legal and is served, but it is
-         * an allocation on the step path and the log says so once. */
+        /* A plugin issued a table at an operand position its declaration did not name. Legal, but
+         * it allocates on the step path. */
         RAD_DEBUG("op %u operand %d issued a weight table of %lld entries that the declaration did "
                   "not describe; allocating it now", (unsigned)h, operand, (long long)n);
         const int rc = ensure_weight_table(key, first, n, &slot);
@@ -254,8 +218,8 @@ int Ctx::resolve_weight_table(rad_op h, int operand, rad_weight first, int64_t n
                                       first, (long long)n));
     }
     WeightTable& t = wtabs_[slot];
-    /* In a pass being recorded the refresh is host work: the recording is cut and the table named,
-     * so a play refreshes it here, on this lane, with whatever the mover has changed by then. */
+    /* While recording, the refresh is host work: cut the tape and name the table, so a play
+     * refreshes it on this lane with whatever the mover has changed by then. */
     if (rec_) {
         tape_cut();
         TapeStep st;
@@ -276,7 +240,7 @@ int Ctx::resolve_weight_table(rad_op h, int operand, rad_weight first, int64_t n
 
 int Ctx::table_refresh(rad_op h, int operand, WeightTable& t) {
     const RadTensor& e0 = w_tmpl_[t.first];
-    const bool wt_time = g_dbg_issue && rank() == 0;   /* same rule: one thread accumulates */
+    const bool wt_time = g_dbg_issue && rank() == 0;   /* one thread accumulates */
     const auto t_wt0 = wt_time ? std::chrono::steady_clock::now()
                                : std::chrono::steady_clock::time_point{};
     auto resolve = [&](int64_t e, void** out) -> int {
@@ -294,9 +258,8 @@ int Ctx::table_refresh(rad_op h, int operand, WeightTable& t) {
 
     int64_t walked = 0;
     if (!t.checked) {
-        /* THE FIRST ISSUE: agreement, every entry, and the whole array up in one copy. `host` is
-         * never written after this, so the copy reads what was resolved here however late the
-         * card reaches it. */
+        /* First issue: check agreement, resolve every entry, upload the whole array. `host` is
+         * never written again, so the async copy is safe however late it runs. */
         t.cur.assign((size_t)t.n, nullptr);
         for (int64_t e = 0; e < t.n; ++e) {
             const rad_weight w = (rad_weight)(t.first + e);
@@ -327,8 +290,8 @@ int Ctx::table_refresh(rad_op h, int operand, WeightTable& t) {
                                   fmt("operand %d: the weight table could not be uploaded", operand));
         t.checked = true;
     } else {
-        /* THE ENTRIES THAT MAY HAVE MOVED, each resolved -- which is also what orders the stream
-         * behind a transfer still in flight -- and written only if its pointer differs. */
+        /* Entries that may have moved: resolve each (which also orders the stream behind an
+         * in-flight transfer) and patch only those whose pointer differs. */
         WtabPatch pt;
         auto one = [&](int64_t e) -> int {
             void* p = nullptr;
@@ -364,8 +327,8 @@ int Ctx::table_refresh(rad_op h, int operand, WeightTable& t) {
     return RAD_OK;
 }
 
-/* The residency table's changes since the last pass, queued against every table that holds the
- * weight. A weight also resolved straight into an operand moves `dense_epoch_` as well. */
+/* Queues the residency table's changes against every table holding each weight. A weight also
+ * resolved directly into an operand bumps `dense_epoch_`. */
 void Ctx::sync_residency() {
     if (!residency_) return;
     const std::vector& ch = residency_->changes();
@@ -375,8 +338,7 @@ void Ctx::sync_residency() {
         if ((size_t)w >= wmemb_head_.size()) continue;
         for (int32_t m = wmemb_head_[w]; m >= 0; m = wmemb_[(size_t)m].next) {
             WeightTable& t = wtabs_[(size_t)wmemb_[(size_t)m].slot];
-            /* A table not yet issued resolves every entry at its first issue, and one already
-             * marked resolves every entry at its next. */
+            /* Unissued or already-full tables resolve every entry at their next issue. */
             if (!t.checked || t.full) continue;
             if ((int64_t)t.pend.size() >= t.n) { t.full = true; t.pend.clear(); continue; }
             t.pend.push_back(wmemb_[(size_t)m].entry);
@@ -385,9 +347,8 @@ void Ctx::sync_residency() {
     residency_->clear_changes();
 }
 
-/* The operand a kernel is handed for a table: entry 0's dtype and trailing extents, with the
- * expert axis PREPENDED at stride zero -- the marker that says the axis is not addressable by
- * arithmetic and `data` is a pointer array. */
+/* The operand a kernel sees for a table: entry 0's dtype and extents with the expert axis
+ * prepended at stride 0, which marks `data` as a pointer array. */
 int Ctx::weight_table_tensor(rad_op h, int operand, const WeightTable& t, const RadTensor& e0,
                              RadTensor* out) {
     if (e0.rank + 1 > RAD_MAX_RANK)
@@ -415,98 +376,24 @@ void Ctx::free_weight_tables() {
     wtab_of_.clear();
 }
 
-/* RADIANCE_DEBUG_ISSUE: WHAT THE ISSUE PATH ACTUALLY COSTS, split from the launch it wraps.
+/* RADIANCE_DEBUG_ISSUE: host cost of the issue path, split from the launch it wraps. Kernel
+ * traces and the per-op profiler only see device time.
  *
- * A draft pass costs several microseconds a dispatch where a bare `hipLaunchKernelGGL` costs
- * around one and a half (`isa/graphrate.hip` prices one). The difference has to be here, and
- * nothing else in the tree can see it: an op's host cost is invisible in a kernel trace, and the
- * per-op profiler times the DEVICE.
+ * `own` is everything before the launch (band scan, domain lookup, operand resolution); `launch`
+ * is the plugin shim plus HIP. Costs two clock reads (~50 ns) per issue when enabled.
  *
- * `own` is everything before the launch -- the band scan, the domain lookup, the operand
- * resolution loop. `launch` is the plugin shim plus HIP. Two clock reads an issue, ~50 ns on a
- * path this says is microseconds, and only when the variable is set.
- *
- * REPORTED PER WINDOW AND NOT AS A RUNNING MEAN. Load and the first prefill put seconds into the
- * accumulator over relatively few issues, so a cumulative average decays through a series of
- * individually plausible numbers, every one of them the startup transient and none of them the
- * steady state. A statistic that is still moving after a million samples is measuring the warm-up,
- * and printing it as "us each" invites exactly the wrong conclusion. */
-
-/* RADIANCE_DEBUG_ARGSHA: ARE A DRAFTER PASS'S KERNEL ARGUMENTS THE SAME EVERY STEP?
- *
- * This is the one question that decides what a captured graph would cost to maintain. A draft pass
- * is the same op sequence at the same shapes every step -- the concurrency does not change inside a
- * request -- so if the ARGUMENTS are identical too, a graph can be captured once and replayed. If
- * they move, every replay needs `hipGraphExecKernelNodeSetParams` over ~50 nodes, which is most of
- * the submit cost back.
- *
- * The staging arena is DOUBLE BUFFERED, so the expectation is not one digest but TWO, alternating.
- * That still replays -- two graphs, picked by parity -- and it is worth knowing before anyone
- * builds either.
- *
- * Digests the operand bytes and `n` of every issue of pass 1 into one FNV-1a and prints it a step. */
-static const bool g_dbg_argsha = std::getenv("RADIANCE_DEBUG_ARGSHA") != nullptr;
-
-static int        g_argsha_pass = -99;
-static long       g_argsha_seen = 0;
-/* ONE DIGEST AN ISSUE, not one a pass: the pass-wide digest only says "something moved", and what
- * decides whether a captured graph is maintainable is HOW MANY nodes move. Kept per position in
- * the pass and compared against the previous step's. */
-/* TWO digests, not one, and the op handle beside them. A count of moving nodes is enough to SIZE
- * a graph; it is not enough to DESIGN one. A node whose operand pointer moved can be left alone if
- * the pointer can be made stable -- the same address refilled in place -- and then the captured
- * graph replays untouched. A node whose SHAPE moved cannot: the launch geometry is baked into the
- * node at capture, so that one needs a real update, which needs launch params only the plugin shim
- * has. Which kind the ten are decides whether this is a contained change or an ABI change. */
-struct ArgSha { rad_op h; uint64_t ptr; uint64_t shp; };
-static std::vector g_argsha_cur, g_argsha_prev;
-static size_t              g_argsha_i = 0;
-static ArgSha argsha_of(rad_op h, int64_t n, const RadTensor* t, int n_opd) {
-    uint64_t v = 1469598103934665603ull, w = 1469598103934665603ull;
-    auto mix = [&](const void* p, size_t k) {
-        const unsigned char* b = (const unsigned char*)p;
-        for (size_t i = 0; i < k; ++i) { v ^= b[i]; v *= 1099511628211ull; }
-    };
-    auto mixw = [&](const void* p, size_t k) {
-        const unsigned char* b = (const unsigned char*)p;
-        for (size_t i = 0; i < k; ++i) { w ^= b[i]; w *= 1099511628211ull; }
-    };
-    mix(&h, sizeof h);
-    mixw(&h, sizeof h);
-    mixw(&n, sizeof n);   /* the row count IS geometry: it is what the grid is derived from */
-    /* ONLY THE LIVE FIELDS. `RadTensor` carries shape[RAD_MAX_RANK] and stride[RAD_MAX_RANK] of
-     * which only `rank` are meaningful, and `tbuf_` is REUSED across issues -- so hashing the
-     * struct whole picks up whatever the last op left in the tail slots and reports very nearly
-     * every issue as having moved, which is the instrument's own scratch and not the model's
-     * arguments. */
-    for (int i = 0; i < n_opd; ++i) {
-        const RadTensor& tt = t[i];
-        mix(&tt.data, sizeof tt.data);                 /* WHERE  -- a node-update-free fix exists */
-        mixw(&tt.dtype, sizeof tt.dtype);              /* WHAT   -- baked into the node at capture */
-        mixw(&tt.rank, sizeof tt.rank);
-        for (uint32_t d = 0; d < tt.rank && d < RAD_MAX_RANK; ++d) {
-            mixw(&tt.shape[d], sizeof tt.shape[d]);
-            mixw(&tt.stride[d], sizeof tt.stride[d]);
-        }
-    }
-    return ArgSha{h, v, w};
-}
-/* PER OP, because the average is the one number that cannot be acted on. Subtracting the price of
- * a bare fifteen-argument hipLaunchKernelGGL (isa/graphrate.hip has one) from `launch` leaves most
- * of a microsecond an issue in the shim's own prologue -- but that is a subtraction across two
- * different kernels, and an average over a step's ~1850 issues hides whether it is a flat tax or
- * three ops doing something silly. This charges host launch time to the op that spent it. */
+ * Reported per window, not as a running mean, so load and the first prefill do not dominate, and
+ * per op, so host launch time is charged to the op that spent it. */
 struct IssOp { double lau = 0.0, own = 0.0; long n = 0; };
 static std::unordered_map g_iss_by_op;
 static double g_iss_own = 0.0, g_iss_lau = 0.0;
 static double g_iss_own_p = 0.0, g_iss_lau_p = 0.0;
 static long   g_iss_n   = 0;
 
-/* THE STAGER'S TWO CALLS, around an op of a pass it armed for. Before the op, because what it
- * stages for this op has to be in the residency table before the op's tables are resolved -- and
- * sync_residency is what carries a table change into the tables that hold the weight, which the
- * pass otherwise does once, at its start. After the op, on the stream the op went to, because that
- * is where "every reader of this weight is behind us" can be recorded. */
+/* Wraps issue_body with the stager's calls on a pass it armed for. before_op runs before the
+ * op's tables are resolved, followed by sync_residency if the stager changed the residency table.
+ * after_op runs on the op's stream, where "every reader of this weight is behind us" can be
+ * recorded. */
 int Ctx::issue(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
     if (!staging_) return issue_body(h, opd, n_opd, n);
     if (step_status_ < 0) return step_status_;
@@ -526,9 +413,8 @@ int Ctx::issue(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
 int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
     const auto t_iss0 = g_dbg_issue ? std::chrono::steady_clock::now()
                                     : std::chrono::steady_clock::time_point{};
-    /* The step is already aborted. rad_arch_step is void and cannot know, so it will keep issuing
-     * the rest of the layer; launching those would burn a step whose output is already wrong and
-     * bury the first error under fifty more. */
+    /* Step already aborted. rad_arch_step is void and keeps issuing; skip the rest so the first
+     * error stays the reported one. */
     if (step_status_ < 0) return step_status_;
 
     if (h == RAD_NULL_HANDLE || (size_t)h >= plans_.size())
@@ -537,13 +423,12 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
 
     OpPlan& p = plans_[h];
 
-    /* RAD_N_BATCH is what almost every op wants: the ranged parameter is the step's token count. */
+    /* RAD_N_BATCH: the ranged parameter is the step's token count. */
     if (n == RAD_N_BATCH) n = batch_ ? batch_->n_tok : 0;
 
-    /* The bucket table. Bands are sorted by their inclusive upper bound and there are two to four
-     * of them -- the union of the LE/GE/EQ values the candidate kernels placed on the ranged
-     * parameter (spec §2.2). A linear scan is one to three predictable compares off one cache
-     * line, which beats any table or division scheme at this size. */
+    /* The bucket table: two to four bands sorted by inclusive upper bound, from the candidate
+     * kernels' LE/GE/EQ constraints on the ranged parameter (spec §2.2). A linear scan is the
+     * fastest option at this size. */
     const int64_t* hi = band_table_.data() + p.band_off;
     int b = 0;
     while (b < p.n_bands && n > hi[b]) ++b;
@@ -558,6 +443,12 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
                               ? "has no host kernel for this band, and the placement planner put "
                                 "it on the host anyway"
                               : "has no device kernel for this band");
+    /* 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)
+        return abort_step_msg(h, RAD_E_SHAPE,
+                              fmt("issued at %lld, which kernel %s does not serve: it requires a "
+                                  "multiple of %lld and was selected at the band's upper bound",
+                                  (long long)n, ip.row->info->name, (long long)ip.ranged_div));
 
     if (n_opd < 0 || n_opd > MAX_OPERANDS)
         return abort_step_msg(h, RAD_E_INVAL,
@@ -583,8 +474,8 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
                 return abort_step_msg(h, RAD_E_INVAL,
                                       fmt("operand %d names buffer handle %u, which declare never "
                                           "returned", i, bh));
-            /* One struct copy: dtype, rank, shape and packed strides came from the declaration and
-             * the data pointer is already arena_base + BufferInfo::arena_offset. */
+            /* Template: declared dtype, rank, shape and packed strides; data is already
+             * arena_base + BufferInfo::arena_offset. */
             tt = buf_tmpl_[bh];
             touches_host |= buf_host_[bh] != 0;
             if (o.offset) {
@@ -598,50 +489,27 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
                                               rad_dtype_name(tt.dtype)));
                 tt.data = static_cast(tt.data) + d;
             }
-            /* rows > 0 narrows dim 0, which is how a prefill chunk of `rows` tokens issues against
-             * a buffer the plan sized at max_tok. The strides do not change and must not: they are
-             * products of the trailing dimensions, so shortening the outermost one leaves every
-             * one of them correct. That is the whole reason the narrowing is dim 0 only. */
+            /* rows > 0 narrows dim 0, so a prefill chunk issues against a buffer sized at
+             * max_tok. Strides stay valid since they are products of the trailing dimensions. */
             if (o.rows > 0) tt.shape[0] = o.rows;
             narrow_cols(o, &tt);
-            /* AND IT HAS TO FIT THE BUFFER IT NAMES. Narrowing dim 0 is how a chunk of `rows`
-             * tokens issues against a plan sized at max_tok, and the arrow points one way only:
-             * an operand may name FEWER rows than the declaration, never more.
-             *
-             * A read past the end is uninitialised memory. A WRITE past the end is another
-             * buffer's bytes, and the arena packs by liveness -- so what it lands on is whatever
-             * the planner put there, which changes with the graph. That is the worst shape of
-             * bug this runtime can have: it is silent, it is not reproducible across a config
-             * change, and the model can stay correct for as long as the victim happens to be
-             * dead. The canonical shape of it is a MoE expert plane declared at max_tok rows while
-             * the gated quantiser writes rows*top_k of them, which nothing notices until some
-             * later op happens to read the buffer the overrun lands on. */
+            /* An operand may name fewer rows than the declaration, never more. A write past the
+             * end lands on whatever buffer the liveness packing placed there, which changes with
+             * the graph, so the corruption is silent and config-dependent (e.g. a MoE expert plane
+             * declared at max_tok rows but written at rows*top_k). */
             if (!operand_fits(tt, o.offset, buf_tmpl_[bh]))
                 return abort_step_msg(h, RAD_E_SHAPE,
                                       fmt("operand %d reaches past buffer '%s': %s at offset "
                                           "%lld, declared %s", i,
                                           program_->buffers[bh].name.c_str(),
-                                          opd_shape_str(tt).c_str(), (long long)o.offset,
-                                          opd_shape_str(buf_tmpl_[bh]).c_str()));
-            /* AND THE OP HAS TO BE INSIDE THE BUFFER'S PLANNED LIFETIME.
-             *
-             * rad_op_reads/rad_op_writes are what the buffer plan is computed from, and they are
-             * OPT-IN per op -- a buffer nothing declared gets the whole program and shares nothing,
-             * which is the sound default. What is NOT sound is an op that touches a buffer other
-             * ops DID declare, outside the range those declarations produced: the arena has laid
-             * something else over those bytes, and what comes back is whatever the planner put
-             * there. It reads as data, so nothing downstream can tell.
-             *
-             * This defect class recurs, and its shape is always the same: an op acquires a read
-             * its declaration never mentioned. `attn_paged` reading the QSA selection is the
-             * pattern -- the block table arrives as a raw batch pointer, so the op's declared read
-             * set is just the query, and a page id fetched out of a reused buffer is an address
-             * outside every mapping. It survives every step until a wider buffer changes the
-             * packing.
-             *
-             * REFUSED RATHER THAN WARNED, because the failure it prevents is silent and is not
-             * reproducible across a graph change -- the victim buffer is whatever the plan chose
-             * this time. */
+                                          tensor_shape_str(tt).c_str(), (long long)o.offset,
+                                          tensor_shape_str(buf_tmpl_[bh]).c_str()));
+            /* The op must lie inside the buffer's planned lifetime. The plan is computed from the
+             * opt-in rad_op_reads/rad_op_writes; a buffer nothing declared lives for the whole
+             * program. An op touching a declared buffer outside [first_def, last_use] may see
+             * bytes the arena reused for another buffer, typically because the op gained a read
+             * its declaration never mentioned. Refused, not warned: the failure is silent and
+             * depends on the plan's packing. */
             {
                 const BufferInfo& bi = program_->buffers[bh];
                 if (bi.first_def >= 0 &&
@@ -684,26 +552,23 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
             }
             if (o.rows > 0) tt.shape[0] = o.rows;
             narrow_cols(o, &tt);
-            /* THE SAME FIT A BUFFER OPERAND HAS TO PASS, for the same reason. A slice that reaches
-             * past the declared weight reads whatever the loader or the mover put after it -- the
-             * next weight in the slab, or the end of the allocation -- and a GEMM over it produces
-             * plausible numbers. Only a sliced operand can overrun, so the whole-weight case every
-             * RAD_W issue takes skips the arithmetic. */
+            /* Same fit check as a buffer: an overrunning slice reads the next weight in the slab
+             * and yields plausible numbers. Only a sliced operand can overrun, so whole-weight
+             * issues skip it. */
             if ((o.offset || o.rows > 0 || o.cols > 0) &&
                 !operand_fits(tt, o.offset, w_tmpl_[wh]))
                 return abort_step_msg(h, RAD_E_SHAPE,
                                       fmt("operand %d reaches past weight '%s': %s at offset "
                                           "%lld, declared %s", i,
                                           program_->weights[wh].name.c_str(),
-                                          opd_shape_str(tt).c_str(), (long long)o.offset,
-                                          opd_shape_str(w_tmpl_[wh]).c_str()));
+                                          tensor_shape_str(tt).c_str(), (long long)o.offset,
+                                          tensor_shape_str(w_tmpl_[wh]).c_str()));
             break;
         }
 
         case RAD_OPK_WTAB: {
-            /* A RUN of declared weights, handed over as a device array of pointers. `handle` is
-             * the first and `rows` is the count -- rad_decl_weight gives out consecutive indices,
-             * so a declaration loop over experts produces exactly such a run. */
+            /* A run of declared weights, passed as a device array of pointers. `handle` is the
+             * first, `rows` the count. */
             const uint32_t w0  = o.handle;
             const int64_t  cnt = o.rows;
             if (w0 == RAD_NULL_HANDLE || cnt <= 0 ||
@@ -723,10 +588,9 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
         }
 
         case RAD_OPK_RAW:
-            /* A pointer the core did not allocate -- a RadBatch field, almost always. It has no
-             * BufferInfo, so there is no dtype and no shape to derive: the kernel knows both from
-             * the op's schema, which is where that knowledge belongs. The core carries the pointer
-             * and, if the caller gave one, the row count. */
+            /* A pointer the core did not allocate, usually a RadBatch field. No BufferInfo, so
+             * dtype and shape come from the op's schema; the core carries the pointer and the
+             * optional row count. */
             if (o.offset && o.dtype == RAD_DT_INVALID)
                 return abort_step_msg(h, RAD_E_INVAL,
                                       fmt("operand %d is a raw pointer with an element offset of "
@@ -736,13 +600,10 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
                                           i, (long long)o.offset));
             std::memset(&tt, 0, sizeof tt);
             tt.data  = o.raw;
-            tt.dtype = o.dtype;   /* RAD_DT_INVALID unless the caller said, which is the point of
-                                   * the field: libref reads positions, cu_seqlens and
-                                   * num_accepted through the tensor's dtype and cannot guess. */
-            /* `cols` on a RAW operand is the SECOND EXTENT, not a column slice: there is no
-             * declared width to slice out of. RAD_P_T2 is how a batch field that is genuinely
-             * two-dimensional says so, and the block table is why it exists -- [n_seq, max_blocks]
-             * handed over as rank 1 loses its width, and every kernel that reads it then guesses. */
+            tt.dtype = o.dtype;   /* RAD_DT_INVALID unless given; libref reads positions,
+                                   * cu_seqlens and num_accepted through the tensor's dtype. */
+            /* On a raw operand `cols` is the second extent, not a column slice (RAD_P_T2), e.g.
+             * the [n_seq, max_blocks] block table. */
             if (o.rows > 0 && o.cols > 0) {
                 tt.rank = 2;
                 tt.shape[0] = o.rows;   tt.shape[1] = o.cols;
@@ -753,10 +614,9 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
             break;
 
         case RAD_OPK_KV: {
-            /* A KV group's cache for one layer. `handle` is the rad_kvgroup and `offset` is the
-             * ABSOLUTE layer index, which the binding rebases -- a group holds one cache per bound
-             * layer, not one per model layer, and 48 GDN layers interleaved with 16 attention ones
-             * would otherwise index a 64-deep pool that was never allocated. */
+            /* A KV group's cache for one layer. `handle` is the rad_kvgroup, `offset` the absolute
+             * layer index, rebased through the binding because a group holds one cache per bound
+             * layer, not per model layer. */
             const uint32_t g = o.handle;
             if ((size_t)g >= kv_.size() || !kv_[g].base)
                 return abort_step_msg(h, RAD_E_STATE,
@@ -767,10 +627,8 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
                                           "rad_kv_group_zero and then issued against, which the "
                                           "plugin must not do", i, g));
             const KVPoolBinding& b = kv_[g];
-            /* A POSITION LOOKUP, not `o.offset - first_layer`. The subtraction is right only for a
-             * group whose layers are contiguous, and they need not be: with 15 attention layers
-             * interleaved through 64, absolute layer 19 -- the fifth of them -- subtracts to slot
-             * 16 of a 15-slot pool, which the bounds check below refuses. */
+            /* A lookup, not a subtraction: a group's layers need not be contiguous
+             * (KVPoolBinding::layer_slot). */
             const int64_t layer = (o.offset >= 0 && (size_t)o.offset < b.layer_slot.size())
                                       ? b.layer_slot[(size_t)o.offset]
                                       : -1;
@@ -783,11 +641,8 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
             std::memset(&tt, 0, sizeof tt);
             tt.data  = static_cast(b.base) + off;
             tt.dtype = b.dtype;
-            /* THE OPERAND CARRIES THE LAYER'S SHAPE, not a flat byte span. The binding composed it
-             * at load out of the plugin's declaration and the block manager's decisions, because
-             * neither half alone is enough (core/runtime/ctx.h says which numbers and why). Every
-             * libr4d shim refuses a flat span -- `if (kv->rank != 4) return RAD_E_SHAPE` -- and
-             * refuses correctly: a paged cache walked as one dimension is not a cache. */
+            /* The operand carries the layer's shape, composed at load (see KVPoolBinding in
+             * ctx.h); libr4d shims refuse a flat span. */
             if (b.rank) {
                 tt.rank = b.rank;
                 for (uint32_t d = 0; d < b.rank; ++d) tt.shape[d] = b.shape[d];
@@ -811,112 +666,41 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
         }
     }
 
-    /* Everything else in RadArgs -- the geometry view, the scratch pointer and its size, the
-     * instance init() returned, the rank and the world size -- was filled in at prepare and has
-     * not changed. args.t already points at tbuf_. */
+    /* The rest of RadArgs was filled in at prepare; args.t already points at tbuf_. */
     ip.args.n_t = n_opd;
     p.issued    = true;
     ++n_issues_;
 
-    /* RADIANCE_DEBUG_ARGSHA -- see the note by the digest. Pass 1 only, so the sequence compared
-     * step to step is the same sequence. */
-
-    /* RANK 0 ONLY. These accumulators are file-scope statics and `Ctx::issue` runs on EVERY rank
-     * thread, so without this the two ranks interleave into one sequence: the issue COUNT then
-     * varies run to run and every digest differs, which reads exactly like a data-dependent op
-     * sequence and is not one. */
-    if (g_dbg_argsha && batch_ && rank() == 0) {
-        const int dp = batch_->draft_pass;
-        if (dp != g_argsha_pass) {
-            if (g_argsha_pass == 1 && !g_argsha_cur.empty() && g_argsha_seen < 12) {
-                size_t mptr = 0, mshp = 0;
-                const size_t k = g_argsha_cur.size() < g_argsha_prev.size()
-                                     ? g_argsha_cur.size() : g_argsha_prev.size();
-                for (size_t i = 0; i < k; ++i) {
-                    if (g_argsha_cur[i].ptr != g_argsha_prev[i].ptr) ++mptr;
-                    if (g_argsha_cur[i].shp != g_argsha_prev[i].shp) ++mshp;
-                }
-                if (!g_argsha_prev.empty()) {
-                    std::fprintf(stderr,
-                                 "D argsha: draft pass 1 -- %zu issues, %zu moved a POINTER, "
-                                 "%zu moved a SHAPE\n",
-                                 g_argsha_cur.size(), mptr, mshp);
-                    if (g_argsha_seen < 2) {
-                        auto nm = [&](rad_op oh) -> const char* {
-                            return (oh != RAD_NULL_HANDLE && (size_t)oh < plans_.size() &&
-                                    plans_[oh].info)
-                                       ? plans_[oh].info->op.c_str() : "";
-                        };
-                        for (size_t i = 0; i < k; ++i) {
-                            const bool p = g_argsha_cur[i].ptr != g_argsha_prev[i].ptr;
-                            const bool q = g_argsha_cur[i].shp != g_argsha_prev[i].shp;
-                            if (p || q)
-                                std::fprintf(stderr, "D argsha:   %2zu %-24s %s%s\n", i,
-                                             nm(g_argsha_cur[i].h), p ? "ptr " : "",
-                                             q ? "shape" : "");
-                        }
-                    }
-                }
-                ++g_argsha_seen;
-                g_argsha_prev = g_argsha_cur;
-            } else if (g_argsha_pass == 1) {
-                g_argsha_prev = g_argsha_cur;
-            }
-            if (dp == 1) { g_argsha_cur.clear(); g_argsha_i = 0; }
-            g_argsha_pass = dp;
-        }
-        if (dp == 1) { g_argsha_cur.push_back(argsha_of(h, n, t, n_opd)); ++g_argsha_i; }
-    }
-
-    /* THE LINK BILL, charged where the message size is known and nothing has to be guessed: `n`
-     * IS the collective's `numel` (every all_reduce declares it as the ranged parameter) and
-     * operand 0 carries the dtype it is sent in, which is the ACTIVATION's dtype and not the op's
-     * `dtype` key -- that key is the architecture's operand-combination spelling ("w4a8"), which
-     * is not an element width. Two relaxed adds on seventeen issues a step. */
+    /* All-reduce link accounting: `n` is the collective's numel (its ranged parameter) and operand
+     * 0's dtype is the wire element type. The op's `dtype` key ("w4a8") is not an element
+     * width. */
     if (p.billed && n_opd > 0) {
         const int bits = rad_dtype_bits(t[0].dtype);
         ar_calls_.fetch_add(1, std::memory_order_relaxed);
         if (bits > 0) ar_bytes_.fetch_add(n * bits / 8, std::memory_order_relaxed);
     }
 
-    /* The oracle, if this issue is one it was asked about. It snapshots every operand to the host
-     * before the launch so the host kernel can be given the same bytes -- an in-place op would
-     * otherwise be compared against its own output. Null in every run that did not arm it. */
+    /* The oracle snapshots every operand before the launch, so the host kernel sees the same
+     * input bytes even for an in-place op. */
     const IssuePlan* horacle = oracle_ ? oracle_before(h, b, n_opd) : nullptr;
 
-    /* ============================== A HOST LAUNCH IS A JOIN ==============================
+    /* ============================== a host launch is a join ==============================
      *
-     * THE HOST THREAD RUNS AHEAD OF THE DEVICE. Every device launch is asynchronous, so by the
-     * time this function is called for op N the GPU may still be somewhere back at op N-200 --
-     * that gap is the whole reason the issue path is allowed to cost a microsecond. A HOST-SITE op
-     * is the one place it stops being harmless: it runs NOW, on this thread, and reads and writes
-     * the host arena NOW.
+     * The host runs ahead of the device, but a host-site op reads and writes the host arena now,
+     * on this thread. Without a join it reads stale data, e.g. a host PLE gather
+     * (`embed_lookup_q`) reading row ids a device `ngram_ids` has not yet written: valid ids,
+     * wrong rows, fluent wrong output.
      *
-     * A PLE gather on the host is exactly that shape. `ngram_ids` writes the hashed row ids into a
-     * host-domain buffer on the device, and `embed_lookup_q` reads them on the host. With no join
-     * the host reads whatever the arena holds from an earlier step and gathers the rows of the
-     * wrong n-gram -- valid ids, valid rows, every kernel agreeing with its oracle, and fluent text
-     * that is a stable wrong answer rather than an intermittent one.
+     * The join waits on the last device op per lane that touched the host arena (host_touch_ev_),
+     * not the whole stream: every hazard is with such an op, and draining would idle the device
+     * while the host works. An architecture can issue the producer early and keep the device busy
+     * meanwhile. A host op naming an untracked operand (raw pointer, KV cache, device-domain
+     * buffer) drains its stream instead (host_join).
      *
-     * WHAT THE JOIN WAITS FOR is the last device op on each lane that touched the host arena
-     * (host_touch_ev_), not the whole stream. Every hazard a host op has is with such an op -- the
-     * producer of an input, or a device reader of bytes its output reuses -- and on one lane they
-     * all complete no later than the last of them. Draining the stream instead waits for
-     * everything issued before the op, which on a decode step is every layer in front of it, and
-     * then the device runs dry while the host works, because nothing after the host op has been
-     * issued yet. Waiting on the producer alone lets an architecture issue it early and keep the
-     * device busy with the layers issued in between while the host gathers.
-     *
-     * AN OPERAND THE ARENA DOES NOT DESCRIBE IS NOT TRACKED -- a raw batch pointer, a KV cache, a
-     * device-domain buffer -- so a host op that names one drains its stream (host_join).
-     *
-     * AND THE HOST'S WRITES HAVE TO REACH THE DEVICE. Host-arena memory is cached on the device like
-     * any other memory, and with no host wait between the host op and the kernel that reads its
-     * output, nothing would make that kernel look past a stale line: rad_dev_host_wrote, after the
-     * launch below, is what does. */
+     * The device caches host-arena memory, so rad_dev_host_wrote after the launch makes the
+     * host's writes visible to later kernels. */
     if (dom == RAD_DOMAIN_HOST) {
-        /* TIMED APART FROM THE OP, because it is not the op's cost -- it is the cost of the
-         * PIPELINE this op stops. */
+        /* Timed apart from the op: it is the cost of stopping the pipeline. */
         if (profiling_) {
             const auto j0 = std::chrono::steady_clock::now();
             const int js = host_join(opd, n_opd);
@@ -929,22 +713,17 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
         }
     }
 
-    /* A SCRATCH REGION IS ONE STREAM'S. The kernels on a lane are handed consecutive slices of it
-     * (scratch_take), and two that could run at once on the lane are kept apart by the slices
-     * being disjoint -- the pass's recording orders any pair whose slices meet (haz_mark). A
-     * scratch user on each lane with no join between them overlaps with nothing recorded to order
-     * it, and the two would overwrite each other's partials with nothing downstream able to tell.
-     * A split-K router GEMM on lane 0 and the shared arm's split-K GEMM on lane 1 meet exactly
-     * like that on every MoE layer.
+    /* A scratch region belongs to one stream. Kernels on a lane get consecutive slices
+     * (scratch_take); a recorded pass orders any pair whose slices meet (haz_mark). Scratch users
+     * on two unjoined lanes would overwrite each other's partials (e.g. split-K router GEMM on
+     * lane 0 and the shared arm's split-K GEMM on lane 1, every MoE layer).
      *
-     * So a program that declares its second lane gets a region per lane, and each launch is
-     * pointed at its own lane's. A lane used WITHOUT that declaration shares region 0, and there
-     * the second of such a pair is ordered behind the first instead -- the overlap is given up for
-     * that launch, never the numbers. That fallback is kept on lane 0 before lane 1 exists as well:
-     * a lane built later starts with nothing ordering it behind what lane 0 already issued. */
+     * A program that declares its second lane gets a region per lane. Otherwise both lanes share
+     * region 0 and the second user is ordered behind the first, giving up the overlap but not
+     * correctness. That also covers lane 0 before lane 1 exists, since a lane built later has
+     * nothing ordering it behind lane 0's earlier work. */
     if (ip.args.scratch_bytes > 0 && dom != RAD_DOMAIN_HOST && arena_.scratch_regions() > 1) {
-        /* Each lane has its own region, so two scratch users on two lanes never share bytes and
-         * nothing has to be ordered. The plan entry serves whichever lane issues it. */
+        /* Per-lane regions: nothing to order. */
         ip.args.scratch = scratch_take(lane_, ip.args.scratch_bytes);
     } else if (ip.args.scratch_bytes > 0 && dom != RAD_DOMAIN_HOST) {
         ip.args.scratch = scratch_take(0, ip.args.scratch_bytes);
@@ -968,9 +747,9 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
         scratch_n_[lane_] = n;
     }
 
-    /* A HOST-SITE OP IN A PASS BEING RECORDED is host work a tape cannot hold: the recording is
-     * cut here and the op kept, to be joined and run again on these operands at every play. Its
-     * launch is not recorded either way -- anything it submitted would be submitted twice. */
+    /* A host-site op while recording: cut the tape and keep the op, to be joined and rerun on
+     * these operands at every play. Its launch is not recorded, or anything it submitted would be
+     * submitted twice. */
     if (rec_ && dom == RAD_DOMAIN_HOST) {
         tape_cut();
         TapeHost th;
@@ -991,10 +770,9 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
     if (host_paused) tape_pause(true);
     const int rec0 = rec_ && !host_paused ? tape_mark() : 0;
 
-    /* A COLLECTIVE HAS THE CARD'S LINK TO ITSELF in a pass the stager copies weights through: the
-     * stager's lists yield while the hold is in force (rad_link_hold says why). Taken here, after
-     * every wait this op's operands put on the stream, so the stream waits on nothing between the
-     * hold and its release -- a weight it waited on could be behind a yielding list. */
+    /* In a staged pass a collective holds the card's link; the stager's copy lists yield meanwhile
+     * (see rad_link_hold). Taken after every wait this op's operands put on the stream, so nothing
+     * between hold and release can wait on a weight stuck behind a yielding list. */
     const bool hold = staging_ && p.collective && dom == RAD_DOMAIN_DEVICE;
     const RadArgs* la = &ip.args;
     RadArgs gate_args;
@@ -1012,18 +790,9 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
     int s;
     if (profiling_ && dom == RAD_DOMAIN_HOST) {
 
-        /* A HOST-SITE OP IS TIMED ON THE HOST CLOCK, because device events cannot see it: they
-         * record when the STREAM reaches them and the stream does not stall for a host call, so an
-         * event pair around this launch measures nothing and the op vanishes from the table.
-         *
-         * Without this the most expensive thing in the step vanishes from the table. The PLE
-         * gather reads sixteen 160-byte rows out of a multi-gigabyte mapping per token, so its
-         * layer costs milliseconds a step against tens of microseconds of device kernels -- and a
-         * device-event profile shows only the tens of microseconds. A host kernel's cost is a
-         * STALL in the middle of the step, which is the one thing an operator most needs named.
-         *
-         * Wall clock and not a device event, so it includes whatever the host call waits on:
-         * page faults, the link read of its input, everything. That is the number that matters. */
+        /* A host-site op is timed on the host wall clock; a device event pair around it would
+         * measure nothing. It includes page faults and link reads, which can make a host op (e.g.
+         * the PLE gather) the most expensive thing in the step. */
         const auto t0 = std::chrono::steady_clock::now();
         s = ip.launch(la, cur_stream());
         const auto t1 = std::chrono::steady_clock::now();
@@ -1032,9 +801,8 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
         prof_calls_[(size_t)h] += 1;
         if ((size_t)h < prof_host_.size()) prof_host_[(size_t)h] = 1;
     } else if (profiling_) {
-        /* One predictable branch in exchange for §16's per-op timing. The events go on the compute
-         * stream around the launch; the synchronisation that reads them is at the end of the step,
-         * and it is what makes a profiled run incomparable to an unprofiled one. */
+        /* Spec §16 per-op timing: events around the launch, read by a sync at the end of the
+         * step (which is why profiled runs are not comparable). */
         if (prof_n_ < prof_ring_.size()) {
             ProfSlot& ps = prof_ring_[prof_n_++];
             ps.op = (int32_t)h;
@@ -1046,11 +814,8 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
             prof_overflowed_ = true;
             s = ip.launch(la, cur_stream());
         }
-    /* RANK 0 ONLY, FOR THE SECOND TIME IN THIS FILE. `Ctx::issue` runs on every rank thread, so a
-     * file-scope accumulator is written by both. Unguarded, the digest above gives wrong NUMBERS
-     * -- two ranks interleaving into one sequence -- and the per-op std::unordered_map here gives
-     * a SEGFAULT within a window. Doubles race benignly enough to mislead, a hash map does not
-     * race at all. Anything this instrument accumulates belongs to one thread. */
+    /* Rank 0 only: these file-scope accumulators (including an unordered_map) are not
+     * thread-safe, and every rank thread runs this. */
     } else if (g_dbg_issue && rank() == 0) {
         const auto ta = std::chrono::steady_clock::now();
         s = ip.launch(la, cur_stream());
@@ -1068,7 +833,7 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
                                  "an issue (%.3f total)\n",
                          g_iss_n, (g_iss_own - g_iss_own_p) / w, (g_iss_lau - g_iss_lau_p) / w,
                          (g_iss_own - g_iss_own_p + g_iss_lau - g_iss_lau_p) / w);
-            /* The walk is inside `own`, so this says how much of `own` it IS. */
+            /* The table walk is part of `own`. */
             std::fprintf(stderr, "D issue:   of which weight tables: %.3f us an issue over "
                                  "%.1f entries (%.1f ns an entry)\n",
                          (g_wtab_us - g_wtab_us_p) / w,
@@ -1076,9 +841,7 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
                          (g_wtab_e - g_wtab_e_p) > 0
                              ? (g_wtab_us - g_wtab_us_p) * 1000.0 / (double)(g_wtab_e - g_wtab_e_p)
                              : 0.0);
-            /* Top by TOTAL host launch time, not by the per-issue mean: an op issued 48 times a
-             * step at 2 us costs more than one issued twice at 20. Both columns are printed so a
-             * fat prologue and a fat call count can be told apart. */
+            /* Top ops by total host launch time, with the per-issue mean beside it. */
             std::vector> ord;
             ord.reserve(g_iss_by_op.size());
             for (const auto& kv : g_iss_by_op) ord.push_back({kv.second.lau, kv.first});
@@ -1103,8 +866,8 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
         s = ip.launch(la, cur_stream());
     }
     if (hold) {
-        /* Released whatever the launch said, by a barrier unless the launch said it ended the hold
-         * itself (RAD_LINK_ENDED): a list waiting on the hold would otherwise never end. */
+        /* Always released, by a barrier unless the launch ended the hold itself
+         * (RAD_LINK_ENDED); otherwise a list waiting on the hold never ends. */
         const int hr = rad_link_hold(cur_stream(), la != &ip.args && s == RAD_LINK_ENDED ? 2 : 0);
         if (hr < 0 && s >= 0) s = hr;
     }
@@ -1191,13 +954,12 @@ void Ctx::haz_note(const OpPlan& p, const IssuePlan& ip, const RadTensor* t, int
     haz_ops_.push_back(o);
 }
 
-/* THE HOST OP'S JOIN; see "A HOST LAUNCH IS A JOIN" in Ctx::issue. */
+/* See "a host launch is a join" in Ctx::issue_body. */
 int Ctx::host_join(const RadOperand* opd, int n_opd) {
     return host_join_wait(host_join_drains(opd, n_opd));
 }
 
-/* Whether an operand is one the arena does not track, which the join can only cover by draining
- * the stream. */
+/* Whether any operand is untracked by the host arena, so the join must drain the stream. */
 bool Ctx::host_join_drains(const RadOperand* opd, int n_opd) const {
     for (int i = 0; i < n_opd; ++i) {
         const RadOperand& o = opd[i];
@@ -1228,9 +990,7 @@ int Ctx::abort_step(rad_op h, int band, int dom, const IssuePlan& ip, int64_t n,
     const Resolved& r     = o.bands[(size_t)band].dom[dom];
     const char*     key   = o.ranged_key.empty() ? "n" : o.ranged_key.c_str();
 
-    /* std::string here, on a path that has already lost the step. The hot path above allocates
-     * nothing; this one is allowed to, because the alternative is a truncated diagnostic on the
-     * one occasion anybody needs a complete one. */
+    /* Allocating is fine here: the step is already lost, and the diagnostic must be complete. */
     step_fail_ = fmt("kernel %s (%s, %s, %s domain) refused op '%s' at %s=%lld "
                      "[band %s<=%lld] geometry {%s}: %s",
                      kname, pname, r.choice.empty() ? "no tunables" : r.choice.c_str(),
@@ -1239,11 +999,10 @@ int Ctx::abort_step(rad_op h, int band, int dom, const IssuePlan& ip, int64_t n,
                      (long long)o.bands[(size_t)band].hi, r.geom.str().c_str(),
                      rad_strerror(status));
 
-    RAD_ERR("%s", step_fail_.c_str());
-    RAD_ERR("a kernel returning negative at issue is a bug in SELECTION, not a runtime condition. "
-            "The step is aborted and the requests in it fail. There is no fallback here, silent "
-            "or otherwise -- a silent fallback is how you ship a slow path nobody knows about "
-            "(spec §17).");
+    /* A kernel refusing at issue is a selection bug, not a runtime condition: the step fails
+     * and there is no fallback (spec §17). */
+    RAD_ERR("%s; the step is aborted (a kernel that refuses at issue was selected wrongly)",
+            step_fail_.c_str());
 
     step_status_ = status;
     return status;
@@ -1296,9 +1055,8 @@ void* Ctx::buf_ptr(rad_buf b) {
 }  /* namespace rad */
 
 /* ================================================================== the C surface */
-/* rad_runtime.h is C, and this is the whole of its implementation. Ctx derives from RadCtx, so
- * every one of these is a static_cast and a forwarded call -- the compiler sees straight through
- * it, which is the point of the empty base rather than a reinterpret_cast. */
+/* rad_runtime.h's implementation. Ctx derives from RadCtx, so each entry is a static_cast and a
+ * forwarded call. */
 extern "C" {
 
 int rad_issue(RadCtx* c, rad_op op, const RadOperand* opd, int n_opd, int64_t n) {
@@ -1308,7 +1066,7 @@ int rad_issue(RadCtx* c, rad_op op, const RadOperand* opd, int n_opd, int64_t n)
 
 int rad_step_fail(RadCtx* c, const char* what) {
     if (!c) rad::fatal("rad_step_fail: null RadCtx");
-    return static_cast(c)->step_fail(what ? what : "the architecture block refused this batch");
+    return static_cast(c)->step_fail(what);
 }
 
 const RadBatch* rad_batch(RadCtx* c)      { return c ? static_cast(c)->batch() : nullptr; }
@@ -1316,12 +1074,10 @@ int             rad_rank(RadCtx* c)       { return c ? static_cast(c)
 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; }
 
-/* The second lane. `rad_lane` says which one subsequent issues launch on; `rad_lane_join` orders
- * one behind the other with an event and blocks neither the host nor either stream. The runtime
- * joins lane 1 back into lane 0 at the end of every step whatever the plugin did, so forgetting
- * the join is a performance bug and not a correctness one. Read Ctx::lane1_ before using this:
- * every collective must ride ONE lane, a second lane may not carry a split-K GEMM, and the buffer
- * planner packs from a single linear order. */
+/* The second lane. `rad_lane` selects the lane subsequent issues launch on; `rad_lane_join`
+ * orders one behind the other with an event, blocking neither the host nor a stream. The runtime
+ * joins lane 1 back into lane 0 at the end of every step, so a missing join costs performance,
+ * not correctness. See Ctx::lane1_ for the constraints before using it. */
 int rad_lane(RadCtx* c, int lane) {
     if (!c) return RAD_E_INVAL;
     return static_cast(c)->set_lane(lane);
diff --git a/core/runtime/kvbind.cpp b/core/runtime/kvbind.cpp
new file mode 100644
index 00000000..406e77ab
--- /dev/null
+++ b/core/runtime/kvbind.cpp
@@ -0,0 +1,61 @@
+/* kvbind.cpp -- see kvbind.h. */
+#include "kvbind.h"
+
+#include "mem/kv.h"
+
+namespace rad {
+
+void bind_kv_pools(const Program& p, const std::function& plan_of,
+                   std::vector* out) {
+    out->assign(p.kv_groups.size(), KVPoolBinding{});
+    for (size_t g = 0; g < p.kv_groups.size(); ++g) {
+        const KVGroupPlan* gp = plan_of((int32_t)g);
+        if (!gp) continue;
+        KVPoolBinding& b = (*out)[g];
+        b.base         = gp->base;
+        b.layer_stride = gp->layer_stride();
+        b.bytes        = gp->pool_bytes;
+        b.dtype        = p.kv_groups[g].decl.dtype;
+
+        /* The position of every bound layer, indexed by its absolute number. */
+        const std::vector& ls = p.kv_groups[g].layers;
+        int32_t hi = -1;
+        for (int32_t l : ls) if (l > hi) hi = l;
+        b.layer_slot.assign((size_t)(hi + 1), -1);
+        for (size_t i = 0; i < ls.size(); ++i) b.layer_slot[(size_t)ls[i]] = (int32_t)i;
+
+        /* One layer's cache shape, in the layout libref/ref_ops.h defines. Built here because only
+         * this point has both the plugin's declaration (heads, head_dim, state_dim, conv_width)
+         * and the block manager's decisions (block_size, n_blocks, n_states, conv_slots); a
+         * kernel cannot derive the conv depth or slot count from op parameters. */
+        const RadKVGroupDecl& d = p.kv_groups[g].decl;
+        switch (gp->kind) {
+        case RAD_KV_FULL:
+        case RAD_KV_WINDOW:
+            b.rank = 4;
+            b.shape[0] = gp->n_blocks;
+            b.shape[1] = d.n_head_kv;
+            b.shape[2] = gp->block_size;
+            b.shape[3] = 2 * d.head_dim;
+            break;
+        case RAD_KV_LINEAR:
+            b.rank = 4;
+            b.shape[0] = gp->n_states;
+            b.shape[1] = d.n_head_kv;
+            b.shape[2] = d.state_dim[0];
+            b.shape[3] = d.state_dim[1];
+            break;
+        case RAD_KV_CONV:
+            b.rank = 3;
+            b.shape[0] = gp->n_states;
+            b.shape[1] = d.n_head_kv * d.head_dim;
+            b.shape[2] = gp->conv_slots;
+            break;
+        default:
+            b.rank = 0;   /* the null sentinel at handle 0; nothing issues against it */
+            break;
+        }
+    }
+}
+
+}  /* namespace rad */
diff --git a/core/runtime/kvbind.h b/core/runtime/kvbind.h
new file mode 100644
index 00000000..22027005
--- /dev/null
+++ b/core/runtime/kvbind.h
@@ -0,0 +1,19 @@
+/* kvbind.h -- the KV group pools as the run phase addresses them (KVPoolBinding, ctx.h). */
+#pragma once
+#include "ctx.h"
+
+#include 
+#include 
+
+namespace rad {
+
+struct KVGroupPlan;
+
+/* One binding per KV group of `p`, from the block manager's plan for it (`plan_of(g)`, null for a
+ * group with none). An operand names an absolute model layer while a pool holds only its group's
+ * layers, so each bound layer maps to its position in the group: in a group of layers 3, 7, ...,
+ * layer 7 is the second; subtracting the first bound layer would give the fifth. */
+void bind_kv_pools(const Program& p, const std::function& plan_of,
+                   std::vector* out);
+
+}  /* namespace rad */
diff --git a/core/runtime/oracle.cpp b/core/runtime/oracle.cpp
index 7d7b9674..ac43fe33 100644
--- a/core/runtime/oracle.cpp
+++ b/core/runtime/oracle.cpp
@@ -1,95 +1,83 @@
-/* oracle.cpp -- run the HOST kernel beside the device one, on the same bytes, every issue.
+/* oracle.cpp -- run the host kernel beside the device one, on the same bytes, at every issue.
  *
  * ================================================================= why this exists
  *
- * rad-kbench falsifies one op at a time against libref, with operands rad-kbench invented. A build
- * can pass nearly every configuration it knows while the engine answers the same token to every
- * prompt. That gap is structural and not a gap in coverage: rad-kbench's operands are ITS shapes, dense and
- * rank-2 and freshly filled, and the engine's are row slices of a max_tok buffer, column slices of
- * a fused projection, rank-3 views a scan kernel required, and weights that came off a file. An op
- * can be correct at every shape rad-kbench knows and wrong at the one shape the model issues.
+ * rad-kbench checks one op at a time against libref with operands it invents: dense, rank-2,
+ * freshly filled. The engine's operands are row slices of a max_tok buffer, column slices of a
+ * fused projection, rank-3 views and weights read from a file, so an op can be right at every
+ * shape rad-kbench knows and wrong at the one the model issues. This checks the issued shape. For
+ * a matching op it
  *
- * So this checks the shape the model actually issued. For a matching op it
- *
- *   1. copies every operand to the host BEFORE the launch -- inputs, outputs, weights, all of it;
+ *   1. copies every operand (inputs, outputs, weights) to the host before the launch;
  *   2. lets the device kernel run and synchronises;
  *   3. copies every operand back into a second host buffer;
- *   4. puts every weight the device row stores RELAID back through that row's own
- *      RadUnrelayoutFn, because the kernel rearranged it at load and a dense reference reads the
- *      canonical planes (see oracle_unrelayout -- this step is not optional, it is the
- *      difference between checking a kernel and comparing a permutation against itself);
- *   5. runs the HOST kernel for the same (op, band) on the copy from step 1 -- same RadTensor
- *      shapes, same strides, same parameters, only the pointers differ;
- *   6. compares, per operand, the host result against the device result.
+ *   4. passes every weight the device row stores re-laid through that row's RadUnrelayoutFn, so
+ *      the dense reference reads canonical planes (see oracle_unrelayout; without this it would
+ *      compare a permuted plane against itself);
+ *   5. runs the host kernel for the same (op, band) on the step-1 copy, with the same shapes,
+ *      strides and parameters;
+ *   6. compares each operand's host result against the device result.
  *
- * Step 5 is the part that has no substitute. The host row is libref's, resolved by the same
- * selector into the same bucket table -- `issue_table_[plan_off + band*RAD_N_DOMAINS + HOST]` is
- * already sitting there beside the device plan, filled in at prepare and never used, because the
- * placement planner put every op on the device. It is a second implementation of the op, against
- * the same schema, and it is free.
+ * The host row is the reference library's (the plugin flagged `reference`, as rad-kbench resolves
+ * it): the band's own host row when the reference library won it, otherwise the reference row the
+ * registry selects at the band's geometry (oracle_reference). A band's host winner may be another
+ * host library under test (libavx), and on the host backend it is the kernel being checked.
  *
- * ================================================================= what it costs
+ * ================================================================= cost
  *
- * Everything. Two device-to-host copies of every operand -- a fused gate_up weight is 170 MiB --
- * a host synchronisation per issue, and a reference kernel that is not trying to be fast. A step
- * with the oracle on takes minutes. It is a debugging instrument and it is off unless asked.
+ * Two device-to-host copies of every operand (a fused gate_up weight is 170 MiB), a host sync per
+ * issue and a slow reference kernel. A step takes minutes. Off unless requested.
  *
- * ================================================================= how to ask
+ * ================================================================= usage
  *
  *   RADIANCE_OP_ORACLE=gemm_nt_q,rmsnorm   op names, comma separated; `*` for every op
  *   RADIANCE_OP_ORACLE_MAX=32              stop after this many checks (default 32)
- *   RADIANCE_OP_ORACLE_FROM=0              first ISSUE INDEX to consider (default 0)
+ *   RADIANCE_OP_ORACLE_FROM=0              first issue index to consider (default 0)
  *   RADIANCE_OP_ORACLE_TO=100000           last issue index to consider
  *   RADIANCE_OP_ORACLE_TOL=0.02            relative tolerance below which an operand is silent
  *   RADIANCE_OP_ORACLE_MAXBYTES            the largest operand a check will copy (default 4 GiB)
  *
- * The issue index is the same counter Ctx tracks internally and the same order --debug-graph
- * prints, so a failure names a position in the graph and not just an op.
+ * The issue index is Ctx's internal counter, in the order --debug-graph prints, so a failure names
+ * a position in the graph.
  *
- * ================================================================= the repeat mode
+ * ================================================================= repeat mode
  *
- * RADIANCE_OP_REPEAT asks a different question with the same machinery: not "does this kernel
- * agree with libref" but "does this kernel agree with ITSELF". It snapshots the operands, lets
- * the device kernel run, puts the operands back exactly as they were, runs the SAME DEVICE KERNEL
- * again, and byte-compares the two results.
- *
- * That is the one fault class every other instrument here is structurally blind to. The oracle,
- * rad-kbench and the residual probe all run an op ONCE per side, so a kernel with an unordered
- * reduction, a workgroup reading what another workgroup is writing, or a workspace it assumed was
- * zeroed passes them at exactly the rate it happens to be right. Byte-exact, no tolerance: the
- * same kernel on the same bytes has no licence to move, and one mantissa bit is a different token
- * a few hundred greedy steps later.
+ * RADIANCE_OP_REPEAT asks whether a kernel agrees with itself: it snapshots the operands, runs the
+ * device kernel, restores the operands, runs the same device kernel again and byte-compares. This
+ * catches unordered reductions, cross-workgroup races and unzeroed workspaces, which instruments
+ * that run an op once per side pass whenever the kernel happens to be right. No tolerance: one
+ * mantissa bit becomes a different token a few hundred greedy steps later.
  *
  *   RADIANCE_OP_REPEAT=*                   op names, comma separated; `*` for every op
  *   RADIANCE_OP_REPEAT_MAX=1000000         stop after this many checks
  *   RADIANCE_OP_REPEAT_FROM / _TO          issue index window
  *   RADIANCE_OP_REPEAT_MAXBYTES=8388608    operands above this are not copied, restored or
- *                                          compared -- which is what keeps a 170 MiB fused weight
- *                                          from making the mode unaffordable, and is right only
- *                                          because such an operand is read-only.
+ *                                          compared; valid only because such operands (fused
+ *                                          weights) are read-only.
  *
- * ================================================================= what it cannot see
+ * ================================================================= blind spots
  *
- * An op ISSUED ON A LANE THE SNAPSHOT DOES NOT SYNCHRONISE -- fixed for lane 1, which is the only
- * one the ABI has, and a third would need the same line.
- *
- * An op with no host kernel for the band -- the oracle skips it and says so once. An op whose
- * dtype the core cannot size (a plugin-private one) -- skipped, since a byte span is the one thing
- * this needs to know. An op whose device row re-lays a weight and publishes no inverse -- skipped
- * BY NAME, because the alternative is a page of false mismatches that drowns the true ones. And
- * an op that is wrong in the SAME WAY on both sides, which is what a shared misreading of the
- * schema would look like; that is what rad-kbench's independent operands
- * are for, and the two instruments are complementary rather than redundant.
+ * - Ops issued on a lane the snapshot does not synchronise. Lane 1, the only one the ABI has, is
+ *   handled; a third lane would need the same line.
+ * - Ops the reference library does not serve in the band (skipped, logged once).
+ * - Operands whose dtype the core cannot size (plugin-private) and that are not a sized weight.
+ * - Device rows that re-lay a weight without publishing an inverse (skipped by name, to avoid
+ *   false mismatches).
+ * - Ops wrong the same way on both sides (a shared misreading of the schema); rad-kbench's
+ *   independent operands cover that.
  */
 #include "ctx.h"
 #include "format/encoding.h"
+#include "plugin/registry.h"
 #include "rad_plugin.h"
 
 #include 
 #include 
 #include 
 #include 
+#include 
 #include 
+#include 
 #include 
 
 namespace rad {
@@ -102,30 +90,32 @@ struct Ctx::OracleState {
     double  tol = 2e-2;
     int64_t checked = 0, skipped_nohost = 0;
     bool    said_nohost = false;
-    /* ---- repeat mode. `maxbytes` is what makes it affordable: a fused gate_up operand is 170 MiB
-     * and a weight is read-only, so an operand past the cap is not snapshotted, not restored and
-     * not compared. Every activation this graph carries at decode is far below it. */
+    /* Reference host plans resolved for bands another library's host row won, keyed by
+     * (op << 16) | band, -1 for a band the reference library does not serve. Deques: an
+     * IssuePlan's parameters point into its Resolved's geometry. */
+    std::unordered_map ref_at;
+    std::deque              ref_res;
+    std::deque             ref_plans;
+    /* ---- repeat mode. Operands over `maxbytes` (read-only weights, e.g. a 170 MiB fused gate_up)
+     * are not snapshotted, restored or compared. Decode activations are far below it. */
     bool    repeat = false;
     int64_t maxbytes = 8 << 20;
-    /* ---- AN OPERAND THE HOST CANNOT HOLD, which is the oracle mode's own cap and not the one
-     * above. A snapshot is two host copies of every operand, plus a third for a weight stored
-     * re-laid, so an operand of tens of gigabytes does not make a check slow -- it ends the
-     * process with nothing reported. Four gibibytes clears a routed layer's whole expert table,
-     * which is the largest operand a check has to hold. */
+    /* ---- oracle-mode cap. A snapshot is two host copies of every operand (three for a re-laid
+     * weight), so a huge operand would OOM the process. 4 GiB covers a routed layer's whole
+     * expert table, the largest operand a check needs. */
     int64_t maxopd = 4LL << 30;
     int64_t differed = 0, unchecked = 0;
     int     skip[MAX_OPERANDS] = {0};
 
     std::vector              scratch;    /* the host kernel's, sized per launch */
-    /* A re-laid weight inverted back into the form a dense reference reads, one buffer per
-     * operand that needed it, and which operands those were. See oracle_unrelayout. */
+    /* Re-laid weights inverted to the form a dense reference reads; see oracle_unrelayout. */
     std::vector> logical;
     int                               unlaid[MAX_OPERANDS] = {0};
     std::vector> pre, post;  /* one snapshot per operand */
     int64_t                           span[MAX_OPERANDS] = {0};   /* elements, stacked */
-    int64_t                           ent [MAX_OPERANDS] = {0};   /* bytes, ONE entry */
-    /* Entries when the operand is a weight TABLE and 0 when it is a plane. See oracle_size: a
-     * table is materialised stacked, because the operand itself is an array of pointers. */
+    int64_t                           ent [MAX_OPERANDS] = {0};   /* bytes, one entry */
+    /* Entry count for a weight table, 0 for a plane. A table is materialised stacked because the
+     * operand is an array of pointers; see oracle_size. */
     int64_t                           tab [MAX_OPERANDS] = {0};
     int                               alias[MAX_OPERANDS] = {0};   /* which operand owns the copy */
     RadTensor                         ht[MAX_OPERANDS]{};
@@ -133,9 +123,8 @@ struct Ctx::OracleState {
 
 namespace {
 
-/* The number of ELEMENTS a tensor's strides can reach, which is what has to be copied. Not
- * numel: a row slice of a [max_tok, n] buffer is dense, but a column slice of a fused projection
- * is not, and copying numel elements of one of those copies the wrong bytes. */
+/* Elements a tensor's strides can reach, which is what must be copied. Not numel: a column slice
+ * of a fused projection is not dense. */
 int64_t span_of(const RadTensor* t) {
     if (!t->data || t->rank == 0) return 0;
     int64_t s = 1;
@@ -147,47 +136,12 @@ int64_t span_of(const RadTensor* t) {
     return s;
 }
 
-float f8e4m3_to_f32(uint8_t b) {
-    const uint32_t sgn = (uint32_t)(b & 0x80u) << 24;
-    const int      e   = (b >> 3) & 0x0F;
-    const uint32_t m   = b & 0x07u;
-    float f;
-    uint32_t u;
-    if (e == 0) {                                   /* subnormal: m * 2^-9 */
-        if (!m) { u = sgn; std::memcpy(&f, &u, 4); return f; }
-        int ex = -6; uint32_t mm = m;
-        while (!(mm & 0x08u)) { mm <<= 1; --ex; }   /* normalise into 1.mmm */
-        u = sgn | ((uint32_t)(ex + 127) << 23) | ((mm & 0x07u) << 20);
-    } else if (e == 0x0F && m == 0x07) {            /* the two NaN encodings */
-        u = sgn | 0x7FC00000u;
-    } else {
-        u = sgn | ((uint32_t)(e - 7 + 127) << 23) | (m << 20);
-    }
-    std::memcpy(&f, &u, 4);
-    return f;
-}
-
-/* One element as a double, by dtype. Returns false for a dtype with no meaningful value -- the
- * comparison then falls back to a byte compare, which is the right answer for an index plane. */
+/* One element as a double. False for a dtype with no scalar value; the caller then byte-compares. */
 bool elem(const uint8_t* p, uint32_t dt, int64_t i, double* out) {
     switch (dt) {
-    case RAD_F32:  { float v;    std::memcpy(&v, p + i * 4, 4); *out = v; return true; }
-    case RAD_BF16: { uint32_t u = (uint32_t)((uint16_t)(p[i * 2] | (p[i * 2 + 1] << 8))) << 16;
-                     float v; std::memcpy(&v, &u, 4); *out = v; return true; }
-    case RAD_F16:  { uint16_t h = (uint16_t)(p[i * 2] | (p[i * 2 + 1] << 8));
-                     const uint32_t s = (uint32_t)(h & 0x8000u) << 16;
-                     const int      e = (h >> 10) & 0x1F;
-                     const uint32_t m = h & 0x3FFu;
-                     uint32_t u;
-                     if (e == 0)        u = s | (m ? ((uint32_t)(127 - 15 + 1) << 23) | (m << 13) : 0u);
-                     else if (e == 31)  u = s | 0x7F800000u | (m << 13);
-                     else               u = s | ((uint32_t)(e - 15 + 127) << 23) | (m << 13);
-                     float v; std::memcpy(&v, &u, 4); *out = v; return true; }
-    case RAD_F8E4M3: *out = f8e4m3_to_f32(p[i]); return true;
-    case RAD_I8:   *out = (double)(int8_t)p[i];  return true;
-    case RAD_U8:
-    case RAD_BOOL: *out = (double)p[i];          return true;
-    case RAD_I16:  { int16_t v; std::memcpy(&v, p + i * 2, 2); *out = v; return true; }
+    case RAD_F32: case RAD_BF16: case RAD_F16: case RAD_F8E4M3: case RAD_F8E5M2:
+    case RAD_I8:  case RAD_U8:   case RAD_BOOL: case RAD_I16:
+        *out = rad_load_f32(p, dt, i); return true;
     case RAD_I32:  { int32_t v; std::memcpy(&v, p + i * 4, 4); *out = v; return true; }
     case RAD_U32:  { uint32_t v; std::memcpy(&v, p + i * 4, 4); *out = v; return true; }
     case RAD_I64:  { int64_t v; std::memcpy(&v, p + i * 8, 8); *out = (double)v; return true; }
@@ -201,24 +155,14 @@ double row_at(const uint8_t* p, uint32_t dt, int64_t base, int64_t k, int64_t n)
     return v;
 }
 
-std::string shape_str(const RadTensor* t) {
-    std::string s = "[";
-    for (uint32_t d = 0; d < t->rank; ++d)
-        s += fmt("%s%lld", d ? "," : "", (long long)t->shape[d]);
-    s += "]/[";
-    for (uint32_t d = 0; d < t->rank; ++d)
-        s += fmt("%s%lld", d ? "," : "", (long long)t->stride[d]);
-    return s + "]";
-}
 
 }  /* namespace */
 
 /* ------------------------------------------------------------------ open / close */
 void Ctx::oracle_open() {
-    /* REPEAT MODE IS THE SAME MACHINERY WITH THE SECOND SIDE SWAPPED, so it shares the arming,
-     * the op filter and the snapshot and differs only in what it runs and how it compares. Named
-     * separately because the two answer different questions: the oracle asks whether a kernel is
-     * RIGHT, this asks whether it is a FUNCTION. */
+    /* Repeat mode shares arming, filtering and snapshots with the oracle and differs only in the
+     * second run and the comparison: the oracle asks whether a kernel is right, repeat whether it
+     * is deterministic. */
     const char* spec = std::getenv("RADIANCE_OP_REPEAT");
     const bool  rep  = spec && *spec;
     if (!rep) spec = std::getenv("RADIANCE_OP_ORACLE");
@@ -252,10 +196,9 @@ void Ctx::oracle_open() {
                  (long long)oracle_->budget, (long long)oracle_->maxbytes);
         return;
     }
-    RAD_WARN("op oracle ARMED for {%s}: issues [%lld,%lld], at most %lld checks, tolerance %.3g, "
-             "operands up to %lld MiB. Every matching issue copies all its operands to the host "
-             "twice and runs the host kernel beside the device one -- this run is not a "
-             "measurement of anything.",
+    RAD_WARN("op oracle armed for {%s}: issues [%lld,%lld], at most %lld checks, tolerance %.3g, "
+             "operands up to %lld MiB; every matching issue also runs on the host, so this run "
+             "measures nothing",
              spec, (long long)oracle_->from, (long long)oracle_->to,
              (long long)oracle_->budget, oracle_->tol, (long long)(oracle_->maxopd >> 20));
 }
@@ -263,13 +206,13 @@ void Ctx::oracle_open() {
 void Ctx::oracle_close() {
     if (!oracle_) return;
     if (oracle_->repeat)
-        RAD_WARN("op REPEAT: %lld issue(s) run twice, %lld of them ANSWERED DIFFERENTLY; %lld "
-                 "more were NOT JUDGED because an operand was over the copy cap (raise "
-                 "RADIANCE_OP_REPEAT_MAXBYTES to cover those)",
+        RAD_WARN("op repeat: %lld issue(s) run twice, %lld of them answered differently; %lld "
+                 "more were not judged because an operand was over the copy cap "
+                 "(RADIANCE_OP_REPEAT_MAXBYTES)",
                  (long long)oracle_->checked, (long long)oracle_->differed,
                  (long long)oracle_->unchecked);
     else
-        RAD_WARN("op oracle: %lld op(s) checked, %lld skipped for want of a host kernel",
+        RAD_WARN("op oracle: %lld op(s) checked, %lld skipped for want of a reference kernel",
                  (long long)oracle_->checked, (long long)oracle_->skipped_nohost);
     delete oracle_;
     oracle_ = nullptr;
@@ -288,31 +231,21 @@ bool Ctx::oracle_arm(rad_op h) const {
 
 /* ------------------------------------------------------------------ sizing the snapshot
  *
- * WHAT IS BEING SIZED IS NOT ALWAYS WHAT THE OPERAND POINTS AT, and a routed mixture is where the
- * difference is total. A grouped GEMM's weight operand is a TABLE (Ctx::WeightTable): after
- * placement a layer's experts are in different places, so the operand handed to the kernel is a
- * device array of POINTERS with a zero leading stride, and `base + e*stride` describes only the
- * all-in-VRAM case, which stops being true the moment anything is offloaded.
+ * A grouped GEMM's weight operand is a table (Ctx::WeightTable): after placement a layer's experts
+ * live in different places, so the operand is a device array of pointers with a zero leading
+ * stride. Copied as a plane it would read far past the pointer array and the host kernel would
+ * dereference device pointers. Instead every entry is copied into one contiguous host buffer with
+ * a non-zero leading stride, the stacked form libref's expert_entry() also accepts.
  *
- * Read as a plane that operand is n*8 bytes pretending to be N*K of weight. Copying it as one
- * reads far past the pointer array, and the host kernel then dereferences DEVICE pointers -- so
- * the largest weight in the model would be the one the instrument cannot be pointed at without
- * reading out of bounds. What it gets instead is the STACKED form: every entry copied into one
- * contiguous host buffer behind a non-zero leading stride, which is the other reading libref's
- * expert_entry() already accepts and the one a fixture uses.
- *
- * A PLUGIN-PRIVATE DTYPE HAS NO BYTE COUNT IN THE CORE, by design -- a 4-bit expert plane is two
- * elements to a byte and the core deliberately knows nothing about the packing (spec 4.2). The
- * container does: the layout pass wrote the resolved kernel's own answer into WeightInfo, so an
- * operand the core cannot size is sized from the weight it is bound to, and only an operand that
- * is neither sizeable nor a weight is declined. */
+ * A plugin-private dtype has no byte count in the core by design (spec 19.6). Such an operand is
+ * sized from the weight it is bound to (the layout pass records the stored size in WeightInfo);
+ * only an operand that is neither sizeable nor a weight is declined. */
 void Ctx::oracle_size(rad_op h, int n_opd) {
     OracleState& o = *oracle_;
     const OpInfo& oi = *plans_[h].info;
 
-    /* The stored byte count of the weight at each operand position, from the layout pass. Every
-     * entry of a table maps to one position and they are proven identical at first issue, so the
-     * last writer and the first agree. */
+    /* Stored byte count of the weight at each operand position, from the layout pass. All entries
+     * of a table map to one position and are proven identical at first issue. */
     int64_t wb[MAX_OPERANDS] = {0};
     int     wlaid[MAX_OPERANDS] = {0};
     if (program_)
@@ -327,38 +260,31 @@ void Ctx::oracle_size(rad_op h, int n_opd) {
 
     for (int i = 0; i < n_opd; ++i) {
         const RadTensor& t = tbuf_[i];
-        /* A ZERO LEADING STRIDE IS THE MARKER. resolve_weight_table() prepends the expert axis
-         * that way precisely to say "this axis is not addressable by arithmetic". */
+        /* A zero leading stride marks a table: resolve_weight_table() prepends the expert axis
+         * that way to say it is not addressable by arithmetic. */
         o.tab[i] = (t.data && t.rank >= 2 && t.stride[0] == 0 && t.shape[0] > 0) ? t.shape[0] : 0;
         const int64_t es = span_of(&t);           /* one entry, or the whole plane when not a table */
         o.span[i] = o.tab[i] ? es * o.tab[i] : es;
         o.ent[i]  = es > 0 ? rad_dtype_bytes(t.dtype, es) : 0;
         if (o.ent[i] <= 0 && es > 0) o.ent[i] = wb[i];
-        /* A RE-LAID WEIGHT IS AS BIG AS THE CONTAINER SAYS, NOT AS BIG AS ITS DECLARED PLANE, and
-         * the two differ even where the dtype has a byte count. The fp8 lm_head pads each stored
-         * row to a 16-byte boundary and carries that row's block scales inside it, so the plane
-         * is 2608 bytes a row where n_embd * 1 says 2560 -- and the inverse, which checks the
-         * byte count it is handed against the stride it wrote, refuses a snapshot sized from the
-         * declared plane. The layout pass records the resolved kernel's own answer for exactly
-         * this; where a weight is stored re-laid, it wins. */
+        /* A re-laid weight's size is the stored size, not the declared plane's. E.g. the fp8
+         * lm_head pads each row to 16 bytes and embeds its block scales (2608 bytes per row, not
+         * n_embd = 2560), and the inverse rejects a buffer of the wrong size. */
         if (wlaid[i] && wb[i] > 0) o.ent[i] = wb[i];
         o.ht[i] = t;
         /* The stacked reading: the expert axis becomes addressable and its stride is one entry. */
         if (o.tab[i]) o.ht[i].stride[0] = es;
 
-        /* ALIASED OPERANDS SHARE ONE HOST BUFFER. A residual add is issued {x, h} -> {x}: two
-         * of its three operands are the same device bytes, and giving each its own copy makes
-         * the host kernel write into a buffer the device kernel's own read-modify-write also
-         * wrote -- which reports the op as a mismatch of exactly the size of the addend, every
-         * time, on an op that is correct. The first operand with a given pointer owns the
-         * copy and the rest point into it, which is what the device sees. */
+        /* Aliased operands share one host buffer, as on the device. A residual add {x, h} -> {x}
+         * with separate copies would report a false mismatch the size of the addend. The first
+         * operand with a given pointer owns the copy. */
         o.alias[i] = i;
         for (int j = 0; j < i; ++j)
             if (t.data && tbuf_[j].data == t.data) { o.alias[i] = o.alias[j]; break; }
     }
 }
 
-/* Bytes the snapshot of operand `i` occupies, which for a table is every entry of it. */
+/* Bytes the snapshot of operand `i` occupies; for a table, all entries. */
 int64_t Ctx::oracle_opd_bytes(int i) const {
     const OracleState& o = *oracle_;
     if (o.span[i] <= 0 || o.ent[i] <= 0) return 0;
@@ -370,44 +296,29 @@ void Ctx::oracle_snap(int n_opd, bool post) {
     std::vector>& into = post ? o.post : o.pre;
     into.resize(MAX_OPERANDS);
     std::vector ptr;
-    /* THE SECOND LANE IS DRAINED FIRST, AND THE ORDER IS THE WHOLE POINT. An architecture may
-     * issue on lane 1 -- the MoE shared expert does -- and the copies below go on `stream_`, which
-     * is not ordered against it. Draining lane 1 AFTER them leaves the copy racing the kernel
-     * that writes what it is copying, which is not a fix: the copy has already returned its bytes.
-     *
-     * Both snapshots need it and for different reasons. In `post` the race reads an OUTPUT before
-     * its kernel wrote it, and a correct kernel reports as having produced nothing. In `pre` it
-     * reads an INPUT before its producer wrote it, and then the two sides are not even given the
-     * same problem -- the host kernel gets a half-written operand, the device kernel gets the
-     * whole one, and the operand the oracle prints is an INPUT that disagrees with itself. The
-     * oracle already costs a host synchronisation per issue; one more stream is free. */
+    /* Drain lane 1 before the copies. Ops may run on lane 1 (the MoE shared expert does), and the
+     * copies below go on `stream_`, which is not ordered against it. Otherwise `post` could read an
+     * output before it is written, and `pre` an input before its producer wrote it. */
     if (lane1_) rad_stream_sync(lane1_);
     for (int i = 0; i < n_opd; ++i) {
         const RadTensor& t = tbuf_[i];
         if (o.alias[i] != i) continue;
         const int64_t bytes = oracle_opd_bytes(i);
-        /* THE CAP IS A REPEAT-MODE THING ONLY. The oracle has to see every operand or its host
-         * kernel has nothing to read; the repeat re-launches the device kernel on the operands
-         * still in place, so an operand it declines to copy is simply one it cannot restore and
-         * will not compare -- which is right for a weight and would be wrong for an output. */
+        /* The maxbytes cap applies to repeat mode only: the oracle's host kernel needs every
+         * operand, while repeat re-launches on the device operands in place and just skips
+         * restoring and comparing the capped ones. */
         if (!post) o.skip[i] = o.repeat && bytes > o.maxbytes;
         if (o.skip[i]) { into[(size_t)i].clear(); continue; }
-        /* A SLOT KEEPS THE HIGH-WATER CAPACITY OF EVERY OPERAND THAT EVER LANDED IN IT, and on a
-         * large model that is not a rounding error: operand 2 of one op is a 170 MiB fused weight
-         * and operand 2 of the next is a few kilobytes, so thirty-two slots across `pre`, `post`
-         * and `logical` hold the sum of the largest thing each has ever seen -- on a container
-         * of well over a hundred GiB, enough for the host OOM killer to end a sweep part way
-         * through. Shrinking when the slot is grossly oversized bounds the footprint by the
-         * largest SINGLE issue instead of by the sum over the graph; the reallocation costs
-         * nothing against a synchronised copy. */
+        /* Shrink a grossly oversized slot. Otherwise each slot in `pre`, `post` and `logical`
+         * keeps the high-water capacity of every operand it ever held, which on a large model
+         * can OOM the host. This bounds the footprint by the largest single issue. */
         into[(size_t)i].assign((size_t)bytes, 0);
         if (into[(size_t)i].capacity() > (size_t)bytes * 2 + (1u << 20))
             into[(size_t)i].shrink_to_fit();
         if (bytes <= 0) continue;
         if (!o.tab[i]) { rad_memcpy_async(into[(size_t)i].data(), t.data, bytes, stream_); continue; }
-        /* The entries are wherever placement put them, so their pointers come back first and the
-         * copies are issued against those. An entry may be device- or host-resident and the
-         * direction is inferred from the pointer, which is what makes one call serve both. */
+        /* Fetch the entry pointers first, then copy each entry. An entry may be device- or
+         * host-resident; the copy infers the direction from the pointer. */
         ptr.assign((size_t)o.tab[i], nullptr);
         rad_memcpy_async(ptr.data(), t.data, o.tab[i] * (int64_t)sizeof(void*), stream_);
         rad_stream_sync(stream_);
@@ -424,35 +335,28 @@ void Ctx::oracle_snap(int n_opd, bool post) {
 
 /* ------------------------------------------------------------------ the stored layout
  *
- * THE HOST KERNEL READS A WEIGHT CANONICALLY AND THE ENGINE DOES NOT HOLD IT THAT WAY.
+ * A kernel may rearrange a weight's canonical planes at load (spec §4.3); libr4d's fp8a8 GEMMs
+ * store WMMA fragment order, the same N*K bytes permuted so a wave's 16 rows arrive in lane order
+ * from one coalesced load. libref reads [N, K] row-major, so passing the stored bytes unchanged
+ * compares uncorrelated tensors (rel error ~1.35 on a correct kernel).
  *
- * A container holds each weight's encoding as canonical planes, and the kernel that reads it may
- * rearrange them at load (spec §4.3): libr4d's fp8a8 GEMMs claim WMMA FRAGMENT ORDER, the same N*K
- * bytes permuted so a wave's sixteen rows arrive in lane order off one coalesced load. libref
- * declares no layout for anything and reads [N, K] row-major. Handing it the operand pointer
- * unchanged therefore compares two readings of one permuted plane, which are uncorrelated tensors
- * -- a relative error around 1.35 on every operand from element zero, on a kernel that is not
- * wrong.
+ * The stored bytes therefore go through the device row's inverse back to canonical planes, then to
+ * the form the host row reads: one plane converted element-wise (e.g. int4 expert codes as
+ * integers), or a whole encoding decoded by the core (e.g. an lm_head of codes and scales).
  *
- * So the stored bytes go back through the device row's own inverse to the canonical planes, and
- * from those to the form the HOST row reads: a single plane converted element by element -- an
- * expert's int4 codes as the integers the reference multiplies -- or a whole encoding decoded by
- * the core's decoder, which is what a reference reading an lm_head of codes and scales together
- * wants. Both sides then see the same values, expressed the way each of them reads.
+ * No inverse means no check: returns false, logs a named skip, and the issue is not counted.
  *
- * NO INVERSE MEANS NO CHECK, and it is a named skip rather than a tolerance: a comparison that
- * cannot be made honestly is worse than one not made, because a page of false failures drowns the
- * true ones. Returns false in that case, and the issue is not counted as checked.
+ * The logical shape comes from the host row's `opd_shape` first, the device row's as fallback:
+ * `opd_shape` describes the operand the kernel is handed, which for the device row is the stored
+ * form being inverted. libref describes every op in docs/OPS.md. Extents come from this issue's
+ * parameters, not the weight declaration, so a tensor-parallel shard uses per-rank N and K.
  *
- * WHICH LOGICAL FORM, AND WHO SAYS SO. `opd_shape` describes the operand the kernel is HANDED --
- * for a relayed weight that is the stored form, which is the thing being inverted and cannot also
- * be the answer. The form wanted here is the one the READER reads, so the host row is asked first
- * and the device row is the fallback. libref publishes a shape for the whole conventional
- * vocabulary, so an op inside docs/OPS.md is describable even when the kernel under test
- * describes nothing.
- *
- * The extents come from the parameters AT THIS ISSUE, not from the weight's declaration: a
- * tensor-parallel shard's op carries the per-rank N and K. */
+ * Two forms skip the description. A host row whose layout hook joins the planes
+ * (abi/rad_planes.h: a quantised lm head, a zero-point grid's scale and zero) is handed its own
+ * stored form of the inverted planes, as the engine would hand it, at the weight's declared shape.
+ * A single plane the host reads as stored, where no description exists (a zero-point grid's codes),
+ * is handed the canonical plane itself. A weight table, or a plane widened at load, takes the
+ * description. */
 bool Ctx::oracle_unrelayout(rad_op h, const IssuePlan& hip, const IssuePlan& dip, int64_t seq,
                             int n_opd) {
     OracleState& o = *oracle_;
@@ -481,10 +385,56 @@ bool Ctx::oracle_unrelayout(rad_op h, const IssuePlan& hip, const IssuePlan& dip
                      w.layout_tag.c_str(), ki->unrelayout ? "RadShapeFn" : "RadUnrelayoutFn");
             return false;
         }
+        if (!o.tab[i] && hk && !w.widen) {
+            RadTensor pt[RAD_ENC_MAX_PLANES];
+            weight_planes(w, pt);
+            RadLayout hl{};
+            const int hst = hk->layout ? hk->layout(hip.args.p, hip.args.n_p, i, &w.enc, w.sel,
+                                                    pt, w.n_sel, &hl)
+                                       : RAD_E_UNSUPPORTED;
+            RadOpdDesc probe{};
+            const bool described =
+                shape(dip.args.p, dip.args.n_p, i, &probe) == RAD_OK && probe.rank > 0;
+            const bool joins = hst == RAD_OK && hk->relayout && hl.bytes > 0;
+            const bool as_stored = hst == RAD_E_UNSUPPORTED && w.n_sel == 1 && !described;
+            if (joins || as_stored) {
+                std::vector> pl((size_t)w.n_sel);
+                for (int k = 0; k < w.n_sel; ++k) {
+                    pl[(size_t)k].assign((size_t)(w.sel_rows[k] *
+                                                  rad_enc_row_bytes(pt[k].dtype, w.sel_cols[k])), 0);
+                    pt[k].data = pl[(size_t)k].data();
+                }
+                const std::vector& src = o.pre[(size_t)o.alias[i]];
+                int rc = ki->unrelayout(dip.args.p, dip.args.n_p, i, &w.enc, w.sel, src.data(),
+                                        (int64_t)src.size(), pt, w.n_sel);
+                if (rc >= 0 && joins) {
+                    o.logical[(size_t)i].assign((size_t)hl.bytes, 0);
+                    rc = hk->relayout(hip.args.p, hip.args.n_p, i, &w.enc, w.sel, pt, w.n_sel,
+                                      o.logical[(size_t)i].data(), hl.bytes);
+                } else if (rc >= 0) {
+                    o.logical[(size_t)i] = pl[0];
+                }
+                if (rc < 0) {
+                    RAD_WARN("oracle #%lld op '%s': NOT CHECKED. '%s' could not be brought from "
+                             "%s's stored form to %s's (%s).", (long long)seq, oi.op.c_str(),
+                             w.name.c_str(), ki->name, hk->name, rad_strerror(rc));
+                    return false;
+                }
+                RadTensor lg{};
+                lg.dtype = joins ? hl.dtype : pt[0].dtype;
+                lg.rank = w.decl.rank;
+                for (uint32_t k = 0; k < w.decl.rank && k < RAD_MAX_RANK; ++k)
+                    lg.shape[k] = w.decl.shape[k];
+                rad_tensor_pack(&lg);
+                lg.data = o.logical[(size_t)i].data();
+                o.ht[i] = lg;
+                o.unlaid[i] = 1;
+                continue;
+            }
+        }
         RadOpdDesc d{};
         if (shape(dip.args.p, dip.args.n_p, i, &d) != RAD_OK || d.rank == 0) {
-            /* A shape hook declines without a reason (RadShapeFn), so the geometry it declined is
-             * printed, the dtype with it -- a description refuses a dtype it knows no grid for. */
+            /* RadShapeFn gives no reason when it declines, so log the geometry. */
             RAD_WARN("oracle #%lld op '%s': NOT CHECKED. nothing could describe the logical form "
                      "of '%s' at this geometry {%s}, so there is nothing to invert its layout "
                      "into.", (long long)seq, oi.op.c_str(), w.name.c_str(),
@@ -499,9 +449,8 @@ bool Ctx::oracle_unrelayout(rad_op h, const IssuePlan& hip, const IssuePlan& dip
         for (int k = (int)d.rank - 1; k >= 0; --k) { lg.stride[k] = acc; acc *= lg.shape[k]; }
         const int64_t bytes = rad_dtype_bytes(lg.dtype, n);
         if (bytes <= 0) return false;
-        /* A TABLE'S DESCRIPTION MUST BE THE STACKED PLANE. The two agree on every other axis, so
-         * a disagreement here is a description that answered for one expert where the operand
-         * carries the layer's whole set -- and inverting into it would write past the buffer. */
+        /* A table's logical form must be the stacked plane; a single-expert description would
+         * make the inverse write past the buffer. */
         if (o.tab[i] && (d.rank < 2 || lg.shape[0] != o.tab[i])) {
             RAD_WARN("oracle #%lld op '%s': NOT CHECKED. '%s' is a table of %lld experts and the "
                      "logical form offered for it leads with %lld, so the two are not the same "
@@ -514,10 +463,8 @@ bool Ctx::oracle_unrelayout(rad_op h, const IssuePlan& hip, const IssuePlan& dip
             o.logical[(size_t)i].shrink_to_fit();
         lg.data = o.logical[(size_t)i].data();
 
-        /* ONE CALL PER ENTRY FOR A TABLE. The hook answers for a weight, and an expert IS the
-         * weight -- the table is the engine's way of saying where the experts ended up, not a
-         * shape the plugin ever agreed to. So each entry's stored bytes are inverted on their own
-         * and land at their own offset in the stacked tensor. */
+        /* One inverse call per table entry: the hook describes one weight (one expert), and the
+         * table is an engine construct. Each entry lands at its offset in the stacked tensor. */
         const std::vector& src = o.pre[(size_t)o.alias[i]];
         const int64_t n_ent = o.tab[i] ? o.tab[i] : 1;
         const int64_t ent_bytes = o.tab[i] ? o.ent[i] : (int64_t)src.size();
@@ -543,9 +490,7 @@ bool Ctx::oracle_unrelayout(rad_op h, const IssuePlan& hip, const IssuePlan& dip
                                        lg.dtype, ent_n, dst, &why);
         }
         if (rc < 0) {
-            /* THE TWO NUMBERS IT DISAGREED ABOUT. An inverse refuses on a shape far more often
-             * than on anything else, and "shape this kernel does not serve" without them says
-             * only that one of the two sides is wrong -- which is the whole question. */
+            /* Inverses mostly refuse on size, so log both sizes. */
             RAD_WARN("oracle #%lld op '%s': NOT CHECKED. %s could not invert its own layout for "
                      "'%s' (%s%s%s): %lld stored bytes into %lld %s elements, so the reference has "
                      "nothing it can read.",
@@ -565,8 +510,7 @@ void Ctx::oracle_run(rad_op h, const IssuePlan& hip, int64_t seq, int n_opd) {
     OracleState& o = *oracle_;
     const OpInfo& oi = *plans_[h].info;
 
-    /* The host kernel writes into the PRE copy: same shapes, same strides, same parameters, and
-     * pointers that are the only thing about the call that differs from the device's. */
+    /* The host kernel writes into the `pre` copy; only the pointers differ from the device call. */
     RadArgs a = hip.args;
     a.t   = o.ht;
     a.n_t = n_opd;
@@ -575,28 +519,23 @@ void Ctx::oracle_run(rad_op h, const IssuePlan& hip, int64_t seq, int n_opd) {
 
     const int rc = hip.launch(&a, nullptr);
     if (rc < 0) {
-        /* RAD_E_UNSUPPORTED IS NOT A FINDING. It is the reference saying "not this contract" --
-         * an op whose parameters name a form it does not implement, which `gdn_recurrent_update`'s
-         * two state layouts are the live example of. Reported as the coverage gap it is, because
-         * the alternative is a reader treating a declined comparison as a passed one. Any OTHER
-         * code is the reference refusing shapes it claims to serve, and that is about the engine's
-         * operands rather than about the oracle. */
+        /* RAD_E_UNSUPPORTED: the reference does not implement this form (e.g. one of
+         * `gdn_recurrent_update`'s two state layouts); a coverage gap, logged as not checked. Any
+         * other code is the reference refusing shapes it claims to serve: a finding about the
+         * engine's operands. */
         if (rc == RAD_E_UNSUPPORTED)
             RAD_WARN("oracle #%lld op '%s': NOT CHECKED. the host kernel (%s) does not implement "
                      "what these parameters ask for {%s}, so there is no comparison to make.",
                      (long long)seq, oi.op.c_str(),
                      hip.row && hip.row->info ? hip.row->info->name : "?", oi.base.str().c_str());
         else {
-            /* AND THE SHAPES IT REFUSED, since that is what this line says the finding is about.
-             * An error name on its own leaves no way to tell an engine operand the reference
-             * genuinely cannot serve from a geometry it was handed wrongly, which is the whole
-             * thing a reader comes to this line for. */
+            /* Log the refused shapes along with the error. */
             std::string sh;
             for (int i = 0; i < n_opd; ++i)
                 if (o.ht[i].data)
-                    sh += fmt("%s%d:%s", sh.empty() ? "" : " ", i, shape_str(&o.ht[i]).c_str());
-            RAD_WARN("oracle #%lld op '%s': the host kernel (%s) REFUSED the engine's own operands "
-                     "with %s. That is a finding about the shapes, not about the oracle: {%s} %s",
+                    sh += fmt("%s%d:%s", sh.empty() ? "" : " ", i, tensor_shape_str(o.ht[i]).c_str());
+            RAD_WARN("oracle #%lld op '%s': the host kernel (%s) refused the engine's own operands "
+                     "with %s: {%s} %s",
                      (long long)seq, oi.op.c_str(),
                      hip.row && hip.row->info ? hip.row->info->name : "?", rad_strerror(rc),
                      oi.base.str().c_str(), sh.c_str());
@@ -604,22 +543,18 @@ void Ctx::oracle_run(rad_op h, const IssuePlan& hip, int64_t seq, int n_opd) {
         return;
     }
 
-    /* Per operand: the largest disagreement, scaled by the device side's own magnitude. A pure
-     * input comes out at zero because neither side touched it, which is the check that the
-     * snapshot itself is sound. */
+    /* Per operand: the largest disagreement relative to the device side's max magnitude. A pure
+     * input must come out at zero, which validates the snapshot itself. */
     std::string line;
     bool bad = false;
     for (int i = 0; i < n_opd; ++i) {
         if (o.span[i] <= 0) continue;
-        /* AN INVERTED WEIGHT IS NOT COMPARED. `pre` holds the stored plane and `post` the device's
-         * copy of the same read-only bytes, so there is nothing here the two sides could disagree
-         * about -- what the host kernel actually read is the separate logical buffer, in a form
-         * neither of those two holds. Printed rather than dropped, so that a reader can see the
-         * operand was handled and know which shape the host side saw. */
+        /* An inverted weight is read-only and the host read a separate logical buffer, so there is
+         * nothing to compare. It is still printed, with the shape the host saw. */
         if (o.unlaid[i]) {
             line += fmt("  opd%d~ %-6s %-22s  read through %s's own inverse; not compared\n",
-                        i, rad_dtype_name(o.ht[i].dtype), shape_str(&o.ht[i]).c_str(),
-                        ip_kernel_name(h) ? ip_kernel_name(h) : "?");
+                        i, rad_dtype_name(o.ht[i].dtype), tensor_shape_str(o.ht[i]).c_str(),
+                        ip_kernel_name(h));
             continue;
         }
         const uint32_t dt = o.ht[i].dtype;
@@ -634,25 +569,15 @@ void Ctx::oracle_run(rad_op h, const IssuePlan& hip, int64_t seq, int n_opd) {
         if (!elem(hp, dt, 0, &x)) {
             const bool same = std::memcmp(hp, dp, o.pre[(size_t)o.alias[i]].size()) == 0;
             line += fmt("  opd%d %-6s %s %s\n", i, rad_dtype_name(dt),
-                        shape_str(&o.ht[i]).c_str(), same ? "bytes equal" : "BYTES DIFFER");
+                        tensor_shape_str(o.ht[i]).c_str(), same ? "bytes equal" : "bytes differ");
             bad = bad || !same;
             continue;
         }
-        /* ONE CODE STEP IN AN fp8 PLANE IS THE FORMAT, NOT A DISAGREEMENT.
-         *
-         * E4M3 has three mantissa bits, so the gap between neighbouring codes is between 1/16 and
-         * 1/8 of the value -- four to eight times the tolerance a comparison of continuous values
-         * is held to. Any difference at all in the bf16 the quantiser reads, down to a single ulp
-         * from a different summation order, moves an element that sits near a rounding boundary
-         * onto the next code, and the reported relative error is then a whole quantum on a kernel
-         * that is right -- typically a handful of elements in ten thousand, one code apart (host
-         * 176, device 192), on an fp8 output plane such as rmsnorm_quant_fp8's or hc_read's.
-         *
-         * So the two sides are compared in CODE space for these dtypes, where adjacent is a
-         * question with an exact answer: same sign bit, magnitude codes one apart. Those are
-         * COUNTED and reported and do not set the verdict; anything further apart is a real
-         * disagreement and is measured like any other. A kernel whose arithmetic is actually
-         * wrong does not land one code away on six elements in ten thousand. */
+        /* fp8 planes are compared in code space. E4M3's code gap is 1/16 to 1/8 of the value, well
+         * above the tolerance, so a one-ulp bf16 difference before quantisation can move an element
+         * to the adjacent code (e.g. host 176, device 192) on a correct kernel. Codes with the same
+         * sign and magnitudes one apart are counted and reported but do not fail the check;
+         * anything further apart is measured normally. */
         const bool fp8 = (dt == RAD_F8E4M3 || dt == RAD_F8E5M2);
         int64_t ulp1 = 0;
         for (int64_t k = 0; k < n; ++k) {
@@ -669,8 +594,8 @@ void Ctx::oracle_run(rad_op h, const IssuePlan& hip, int64_t seq, int n_opd) {
                 worst = std::isnan(x) != std::isnan(y) ? INFINITY : d;
                 at = k; hv = x; dv = y;
             }
-            /* The individually bad elements, not just the worst: WHERE they sit says whether a
-             * whole operand is wrong or one lane of it is, and those are different bugs. */
+            /* Record the first few bad indices too: their positions tell a wrong operand from a
+             * wrong lane. */
             if (d > 1e-30 && (std::isnan(x) != std::isnan(y) || d > o.tol * std::fabs(x))) {
                 if (nbad < 4) badix[nbad] = k;
                 ++nbad;
@@ -680,11 +605,8 @@ void Ctx::oracle_run(rad_op h, const IssuePlan& hip, int64_t seq, int n_opd) {
         if (rel > o.tol) bad = true;
         double f[4] = {0, 0, 0, 0};
         for (int64_t k = 0; k < 4 && k < n; ++k) elem(dp, dt, k, &f[k]);
-        /* PER-ROW SUMS, up to three rows. A whole-tensor sum is a weak fingerprint and the first
-         * four values only ever describe row 0, so between them they can say "token 0 is exactly
-         * right and the total is wrong" -- a statement about the OTHER tokens that neither column
-         * can localise. A row here is dim 0, which is the token for every activation the graph
-         * carries. */
+        /* Per-row sums for up to three rows (dim 0, the token for activations), to localise errors
+         * beyond row 0 that the head values and whole-tensor sum cannot. */
         std::string rows;
         if (o.ht[i].rank >= 2 && o.ht[i].shape[0] > 1 && o.ht[i].stride[0] > 0) {
             const int64_t nr = o.ht[i].shape[0] < 3 ? o.ht[i].shape[0] : 3;
@@ -700,19 +622,16 @@ void Ctx::oracle_run(rad_op h, const IssuePlan& hip, int64_t seq, int n_opd) {
                 const int64_t last = (r + 1) * w < n ? (r + 1) * w : n;
                 for (int j = 0; j < 3; ++j)
                     if (last - 3 + j >= r * w) elem(dp, dt, last - 3 + j, &t[j]);
-                /* HEAD AND TAIL OF EVERY ROW, which is exactly what llama.cpp's eval-callback
-                 * prints -- three at each end and an ellipsis. A sum agrees between two vectors
-                 * that are not the same vector, which is the shape these mismatches take. */
+                /* Three values at each end of the row, as llama.cpp's eval-callback prints, since
+                 * equal sums do not imply equal vectors. */
                 rows += fmt("\n      row%lld sum %.6g head [%.5g %.5g %.5g] tail [%.5g %.5g %.5g]",
                             (long long)r, rs,
                             row_at(dp, dt, r * w, 0, n), row_at(dp, dt, r * w, 1, n),
                             row_at(dp, dt, r * w, 2, n), t[0], t[1], t[2]);
             }
         }
-        /* WHERE the worst element is, and what each side said there. Without it a mismatch is a
-         * number: "rel 2 on a gate cumsum" cannot distinguish a whole tensor that is wrong from
-         * one padding lane that is, and those want different fixes. The index is flat over the
-         * operand, which is the same order the row sums above walk. */
+        /* The worst element's flat index and both values, to tell a wrong tensor from one wrong
+         * padding lane. */
         std::string at_s;
         if (at >= 0 && rel > o.tol) {
             at_s = fmt("\n      worst at [%lld]: host %.9g  device %.9g  (diff %.4g)"
@@ -721,14 +640,12 @@ void Ctx::oracle_run(rad_op h, const IssuePlan& hip, int64_t seq, int n_opd) {
                        (long long)at, hv, dv, worst, (long long)nbad, (long long)n, hsum, sum);
             for (int b = 0; b < 4 && badix[b] >= 0; ++b) at_s += fmt(" %lld", (long long)badix[b]);
         }
-        /* The one-code-step count is PRINTED whether or not anything else disagreed. Silently
-         * absorbing them would make the operand look byte-equal, and a reader comparing two runs
-         * of the same build wants to see that six elements moved. */
+        /* The one-code-step count is always printed, so absorbed differences stay visible. */
         const std::string u1 = ulp1 ? fmt("  %lld at one fp8 code step", (long long)ulp1)
                                     : std::string();
         line += fmt("  opd%d %-6s %-22s n=%-9lld amax %.4g sum %.6g [%.5g %.5g %.5g %.5g]%s"
                     "  rel %.4g%s%s%s\n",
-                    i, rad_dtype_name(dt), shape_str(&o.ht[i]).c_str(), (long long)n, scale,
+                    i, rad_dtype_name(dt), tensor_shape_str(o.ht[i]).c_str(), (long long)n, scale,
                     sum, f[0], f[1], f[2], f[3], rows.c_str(), rel, u1.c_str(),
                     rel > o.tol ? "  <-- MISMATCH" : "", at_s.c_str());
     }
@@ -751,58 +668,32 @@ const char* Ctx::ip_kernel_name(rad_op h) const {
     return "?";
 }
 
-/* The one entry point issue() calls. Returns the host plan to check against, or null. */
 /* ------------------------------------------------------------------ the repeat check */
-/* RUN THE DEVICE KERNEL A SECOND TIME ON THE BYTES THE FIRST ONE SAW, AND COMPARE.
- *
- * The oracle above asks whether a kernel agrees with libref. This asks a question no two-sided
- * comparison can: whether the kernel agrees with ITSELF. A kernel with an unordered reduction, a
- * workgroup that reads what another workgroup is writing, or a workspace it assumed was zeroed is
- * CORRECT on the run the oracle happens to look at and wrong on the next one, and every
- * instrument in this tree that runs an op once is blind to it.
- *
- * BYTE-EXACT AND NO TOLERANCE, deliberately. "Within 2%" is the right question for an
- * implementation and the wrong one here: the same kernel on the same bytes has no licence to move
- * at all, and a difference in the last mantissa bit is the finding, because greedy decoding
- * amplifies it into a different token a few hundred steps later.
- *
- * WHAT IT CANNOT SEE. A race between the two ranks of a tensor-parallel step: both Ctxs walk the
- * same graph and both re-launch, so a collective still meets itself and does not deadlock, but
- * what the second launch measures is the pair re-running together rather than either one alone.
- * And a kernel whose output depends on a buffer this declined to restore -- see the cap. */
+/* Runs the device kernel a second time on the bytes the first saw and byte-compares (see the file
+ * header). Blind spots: under tensor parallelism both ranks re-launch together, so a collective
+ * does not deadlock but the pair is measured, not either rank alone; and outputs that depend on an
+ * operand over the restore cap. */
 void Ctx::oracle_repeat(rad_op h, const IssuePlan& dip, int64_t seq, int n_opd) {
     OracleState& o = *oracle_;
 
-    /* AN OPERAND THIS COULD NOT COPY MAKES THE WHOLE ISSUE UNJUDGEABLE, and saying so is the
-     * difference between an instrument and a rumour. The cap exists for read-only weights, but
-     * nothing here knows that an operand IS a weight -- and a GDN recurrent state is both an input
-     * and an output and is far over the default cap. Left unrestored it hands the second launch a
-     * state the first one already advanced, and every GDN issue in the model then reports as
-     * non-deterministic when what actually happened is that it was asked a different question.
-     * Raise RADIANCE_OP_REPEAT_MAXBYTES to check those ops; do not guess about them. */
+    /* Any uncopied operand makes the issue unjudgeable: it is counted, not guessed at. The cap is
+     * meant for read-only weights, but e.g. a GDN recurrent state is in/out and far over it; left
+     * unrestored, the second launch would see an advanced state. Raise
+     * RADIANCE_OP_REPEAT_MAXBYTES to cover such ops. */
     for (int i = 0; i < n_opd; ++i)
         if (o.skip[i]) { ++o.unchecked; return; }
 
-    /* The first result, before anything is put back. oracle_snap writes `post`, so it is moved
-     * aside rather than copied: the second launch needs the same destination. */
+    /* First result; moved aside because oracle_snap writes `post` again for the second launch. */
     oracle_snap(n_opd, true);
     std::vector> first;
     first.swap(o.post);
 
-    /* PUT BACK ONLY WHAT THE KERNEL ACTUALLY CHANGED, and decide that by comparing rather than by
-     * believing the schema. An op issued {x, h} -> {x} has already overwritten one of its own
-     * inputs, so without a restore the second launch is not given the same problem and every
-     * in-place op in the graph reports as non-deterministic.
+    /* Restore only operands whose bytes actually changed (decided by comparison, not the schema).
+     * In-place ops such as {x, h} -> {x} must be restored or they report as non-deterministic,
+     * while restoring everything would segfault writing a Tier::Mapped weight (a read-only mmap).
      *
-     * Restoring everything SEGFAULTS instead: a small weight is a perfectly ordinary operand under
-     * the size cap, and a weight on Tier::Mapped is the container's read-only mmap. A kernel never
-     * writes an operand it only reads, so "changed" is both the safe test and the cheap one.
-     *
-     * A WEIGHT TABLE IS NEVER RESTORED WHATEVER THE COMPARISON SAYS. Its snapshot is the STACKED
-     * plane behind an array of pointers (oracle_size), so a byte-for-byte write back would put
-     * gigabytes of expert weight over a few kilobytes of pointers. No op writes one, which is
-     * why the comparison alone is enough; if one ever did, a write back would take every weight
-     * in the graph off its address. */
+     * Never restore a weight table: its snapshot is the stacked plane, and writing it back would
+     * overwrite the pointer array with expert weights. */
     bool wrote[MAX_OPERANDS] = {false};
     for (int i = 0; i < n_opd; ++i) {
         if (o.alias[i] != i || o.skip[i] || o.span[i] <= 0 || o.tab[i]) continue;
@@ -815,13 +706,13 @@ void Ctx::oracle_repeat(rad_op h, const IssuePlan& dip, int64_t seq, int n_opd)
     }
     rad_stream_sync(stream_);
 
-    /* THE SAME PLAN, THE SAME ARGS, THE SAME STREAM. dip.args.t still points at tbuf_ -- the
-     * device pointers -- because the oracle's rebinding only ever touched its own `ht`. */
+    /* Same plan, args and stream; dip.args.t still points at the device tbuf_ (the oracle only
+     * rebinds its own `ht`). */
     RadArgs a = dip.args;
     a.n_t = n_opd;
     const int rc = dip.launch(&a, cur_stream());
     if (rc < 0) {
-        RAD_WARN("repeat #%lld op '%s': the second launch was REFUSED with %s, so this issue says "
+        RAD_WARN("repeat #%lld op '%s': the second launch was refused with %s, so this issue says "
                  "nothing about determinism", (long long)seq, plans_[h].info->op.c_str(),
                  rad_strerror(rc));
         return;
@@ -830,17 +721,15 @@ void Ctx::oracle_repeat(rad_op h, const IssuePlan& dip, int64_t seq, int n_opd)
 
     std::string line;
     for (int i = 0; i < n_opd; ++i) {
-        /* ONLY THE OPERANDS THE KERNEL WROTE. One it merely read is equal by construction, and
-         * saying so for every input on every issue buries the finding. */
+        /* Only operands the kernel wrote; read-only ones are equal by construction. */
         if (!wrote[i]) continue;
         const std::vector& A = first[(size_t)i];
         const std::vector& B = o.post[(size_t)i];
         if (A.size() != B.size() || A.empty()) continue;
         if (std::memcmp(A.data(), B.data(), A.size()) == 0) continue;
 
-        /* WHICH ELEMENTS AND BY HOW MUCH. One lane apart at the last bit and a whole tensor of
-         * garbage are both "BYTES DIFFER", and they are different bugs: the first is a reduction
-         * order, the second is a read of memory another workgroup owns. */
+        /* Count and locate differing elements: a last-bit difference points to reduction order,
+         * widespread garbage to a cross-workgroup read. */
         const uint32_t dt = o.ht[i].dtype;
         const int64_t  n  = o.span[i];
         int64_t nbad = 0, at = -1;
@@ -855,22 +744,74 @@ void Ctx::oracle_repeat(rad_op h, const IssuePlan& dip, int64_t seq, int n_opd)
             scale = std::max(scale, std::fabs(y));
         }
         if (nbad < 0)
-            line += fmt("  opd%d %-6s %s BYTES DIFFER (dtype not scalar)\n", i,
-                        rad_dtype_name(dt), shape_str(&o.ht[i]).c_str());
+            line += fmt("  opd%d %-6s %s bytes differ (dtype not scalar)\n", i,
+                        rad_dtype_name(dt), tensor_shape_str(o.ht[i]).c_str());
         else
             line += fmt("  opd%d %-6s %s  %lld of %lld element(s) differ; worst at [%lld] "
                         "run1 %.9g run2 %.9g (diff %.4g, rel %.3g)\n",
-                        i, rad_dtype_name(dt), shape_str(&o.ht[i]).c_str(),
+                        i, rad_dtype_name(dt), tensor_shape_str(o.ht[i]).c_str(),
                         (long long)nbad, (long long)n, (long long)at, av, bv, worst,
                         worst / (scale > 0 ? scale : 1.0));
     }
     if (line.empty()) return;
     ++o.differed;
-    RAD_ERR("REPEAT #%lld op '%s' (kernel %s) IS NOT A FUNCTION OF ITS INPUTS: two launches on the "
+    RAD_ERR("repeat #%lld op '%s' (kernel %s) is not a function of its inputs: two launches on the "
             "same bytes disagreed.\n%s", (long long)seq, plans_[h].info->op.c_str(),
-            ip_kernel_name(h) ? ip_kernel_name(h) : "?", line.c_str());
+            ip_kernel_name(h), line.c_str());
 }
 
+const IssuePlan* Ctx::oracle_reference(rad_op h, int band) {
+    OracleState& o = *oracle_;
+    const OpPlan& p = plans_[h];
+    const IssuePlan& hip =
+        issue_table_[(size_t)p.plan_off + (size_t)band * RAD_N_DOMAINS + RAD_DOMAIN_HOST];
+    if (hip.launch && hip.row && hip.row->reference) return &hip;
+    if (!registry_) return nullptr;
+
+    const uint64_t key = ((uint64_t)h << 16) | (uint64_t)(uint16_t)band;
+    if (const auto it = o.ref_at.find(key); it != o.ref_at.end())
+        return it->second >= 0 ? &o.ref_plans[(size_t)it->second] : nullptr;
+    o.ref_at[key] = -1;
+
+    /* The question the bucket table asked of this band (Registry::build_bands), with every row
+     * but a reference library's refused. */
+    const OpInfo& oi = *p.info;
+    Geometry g = oi.base;
+    if (!oi.ranged_key.empty()) g.set_i(oi.ranged_key, oi.bands[(size_t)band].hi);
+    const Registry::RowFilter only_reference = [](const KernelRow& r, const Geometry&) {
+        return r.reference ? std::string() : std::string("not a reference library");
+    };
+    Resolved r = registry_->resolve(oi.op, g, RAD_DOMAIN_HOST, nullptr, &only_reference);
+    if (!r || !r.row->info || !r.row->info->launch) return nullptr;
+    if (r.row->info->scratch) {
+        RadArgs a{};
+        a.p          = r.geom.params();
+        a.n_p        = r.geom.n_params();
+        a.rank       = rank_;
+        a.world_size = world_size_;
+        const int64_t s = r.row->info->scratch(&a);
+        if (s < 0) return nullptr;
+        r.scratch_bytes = s;
+    }
+    if (registry_->init_instance(r, rank_, world_size_) < 0) return nullptr;
+
+    o.ref_res.push_back(std::move(r));
+    const Resolved& kept = o.ref_res.back();
+    IssuePlan ip{};
+    ip.row                = kept.row;
+    ip.launch             = kept.row->info->launch;
+    ip.args.p             = kept.geom.params();
+    ip.args.n_p           = kept.geom.n_params();
+    ip.args.scratch_bytes = kept.scratch_bytes;
+    ip.args.instance      = kept.instance;
+    ip.args.rank          = rank_;
+    ip.args.world_size    = world_size_;
+    o.ref_plans.push_back(ip);
+    o.ref_at[key] = (int)o.ref_plans.size() - 1;
+    return &o.ref_plans.back();
+}
+
+/* The entry point issue() calls. Returns the host plan to check against, or null. */
 const IssuePlan* Ctx::oracle_before(rad_op h, int band, int n_opd) {
     if (!oracle_ || !oracle_arm(h)) return nullptr;
     oracle_size(h, n_opd);
@@ -878,33 +819,27 @@ const IssuePlan* Ctx::oracle_before(rad_op h, int band, int n_opd) {
         for (int i = 0; i < n_opd; ++i)
             if (tbuf_[i].data && oracle_opd_bytes(i) <= 0) return nullptr;
         oracle_snap(n_opd, false);
-        /* REPEAT MODE NEEDS NO HOST KERNEL, and the issue path carries this pointer back only to
-         * say "armed". oracle_after re-launches the DEVICE plan it is handed instead. */
+        /* Repeat mode needs no host kernel; this pointer only signals "armed". oracle_after
+         * re-launches the device plan. */
         static const IssuePlan kRepeatArmed{};
         return &kRepeatArmed;
     }
-    /* NOT GATED ON THE DEVICE DOMAIN. On the host backend the launch IS the host kernel,
-     * so the comparison is host against host and agrees by construction -- but the per-operand
-     * lines are still the only ordered trace of what the graph computed, and diffing those
-     * against another engine's is what the whole-model reference exists for. */
-    const OpPlan& p = plans_[h];
-    const IssuePlan& hip =
-        issue_table_[(size_t)p.plan_off + (size_t)band * RAD_N_DOMAINS + RAD_DOMAIN_HOST];
-    if (!hip.launch) {
+    /* Not gated on the device domain: on the host backend this checks the host library that
+     * serves the op (libavx) against the reference library. */
+    const IssuePlan* ref = oracle_reference(h, band);
+    if (!ref) {
         ++oracle_->skipped_nohost;
         if (!oracle_->said_nohost) {
             oracle_->said_nohost = true;
-            RAD_WARN("oracle: op '%s' has no host kernel in this band, so it cannot be checked. "
-                     "A library with host kernels -- a reference one, or the host library -- "
-                     "must be on the kernel search path for the oracle to see anything.", plans_[h].info->op.c_str());
+            RAD_WARN("oracle: op '%s' has no reference library row in this band, so it cannot be "
+                     "checked. A reference kernel library (libref) must be on the kernel search "
+                     "path for the oracle to see anything.", plans_[h].info->op.c_str());
         }
         return nullptr;
     }
-    /* AN OPERAND WITH NO BYTE COUNT IS A NAMED SKIP, not a silent one. The count is missing when
-     * the dtype is plugin-private and the operand is not a weight the layout pass sized -- a
-     * packed plane the core is not meant to understand (spec 4.2). Dropping the whole issue
-     * without saying so would report a routed model's expert GEMM as "0 checked" beside a page of
-     * agreements, which reads as nothing to check rather than as a gap. */
+    const IssuePlan& hip = *ref;
+    /* An operand with no byte count (plugin-private dtype, not a sized weight; spec 19.6) is a
+     * logged skip, so a gap is not mistaken for nothing to check. */
     for (int i = 0; i < n_opd; ++i) {
         if (!tbuf_[i].data || oracle_opd_bytes(i) > 0) continue;
         RAD_WARN("oracle #%lld op '%s': NOT CHECKED. operand %d is %s and the core cannot size "
@@ -914,11 +849,8 @@ const IssuePlan* Ctx::oracle_before(rad_op h, int band, int n_opd) {
                  rad_dtype_name(tbuf_[i].dtype));
         return nullptr;
     }
-    /* AND AN OPERAND THE HOST CANNOT HOLD IS A NAMED SKIP TOO. The snapshot is two host copies
-     * of every operand and a third for a weight stored re-laid, so an operand of tens of
-     * gigabytes is not a slow check -- it is the process being killed with nothing reported, and
-     * no reason in the log because there is no chance to write one. A 47 GiB n-gram table read
-     * at decode is such an operand. */
+    /* An operand over maxopd is a logged skip: snapshotting it (e.g. a 47 GiB n-gram table) would
+     * get the process OOM-killed with nothing logged. */
     for (int i = 0; i < n_opd; ++i) {
         if (!tbuf_[i].data || oracle_->alias[i] != i) continue;
         const int64_t b = oracle_opd_bytes(i);
@@ -949,9 +881,8 @@ void Ctx::oracle_after(rad_op h, const IssuePlan& hip, const IssuePlan& dip, int
         return;
     }
     oracle_snap(n_opd, true);
-    /* The pre snapshot's tensors still point into `pre`, which oracle_snap(false) bound -- except
-     * for a weight the device row stores re-laid, which this repoints at its own inverse. A row
-     * that cannot be inverted is not checked at all, and not counted as checked either. */
+    /* `ht` still points into `pre`, except re-laid weights, which oracle_unrelayout repoints at
+     * their inverse. An issue that cannot be inverted is neither checked nor counted. */
     if (!oracle_unrelayout(h, hip, dip, n_issues_, n_opd)) return;
     oracle_run(h, hip, n_issues_, n_opd);
     --oracle_->budget;
diff --git a/core/runtime/rank_barrier.cpp b/core/runtime/rank_barrier.cpp
index 41b01d73..9cce37b9 100644
--- a/core/runtime/rank_barrier.cpp
+++ b/core/runtime/rank_barrier.cpp
@@ -9,9 +9,8 @@ void RankBarrier::arrive_and_wait() {
 
     const uint64_t my_gen = gen_;
     if (++waiting_ == n_) {
-        /* Last one in flips the generation and releases the rest. The counter is reset here rather
-         * than by the wakers, so a rank that re-enters immediately observes a generation it has
-         * not seen and blocks instead of racing through. */
+        /* Last one in resets the counter and flips the generation, so a rank that re-enters at
+         * once waits on the new generation instead of racing through. */
         waiting_ = 0;
         ++gen_;
         lk.unlock();
diff --git a/core/runtime/rank_barrier.h b/core/runtime/rank_barrier.h
index fb4a041a..bf32bbe8 100644
--- a/core/runtime/rank_barrier.h
+++ b/core/runtime/rank_barrier.h
@@ -1,21 +1,13 @@
 /* rank_barrier.h -- the release point for the tensor-parallel rank threads.
  *
- * WHY THIS IS NOT IPC. Radiance is one process. One thread per rank, each owning one device
- * (spec §1). The ranks therefore share an address space, so the step batch is shared BY POINTER
- * rather than broadcast: there is nothing to serialise, no shared-memory segment to map, no file
- * descriptor, no pickling, and no handshake protocol that can get out of step with itself. All
- * that is left for the barrier to do is establish happens-before between the scheduler's release
- * and each rank's first rad_issue, and between the ranks' last issue and the scheduler's next
- * batch build.
+ * Radiance is one process with one thread per rank, each owning one device (spec §1), so the step
+ * batch is shared by pointer rather than serialised to other processes. The barrier only
+ * establishes happens-before between the scheduler's release and each rank's first rad_issue, and
+ * between the ranks' last issue and the scheduler's next batch build. A condvar round trip costs
+ * ~1-2 us; an IPC broadcast of the batch costs tens of microseconds per step.
  *
- * A futex round trip through a condvar is ~1-2 us on this class of machine. The multiprocessing
- * equivalent -- serialise the batch, write it down a pipe, wake N processes, have each one
- * deserialise it -- is tens of microseconds per step before any work happens, and it is most of
- * what a Python engine's multiprocessing budget actually buys. That difference is the reason §1
- * is written the way it is, and this class is the whole of the cost on our side.
- *
- * Sense reversal, not a counter reset, so a fast rank that comes back round for the next step
- * cannot slip through the barrier its slower peers have not left yet.
+ * Generation-based (sense reversal), so a fast rank re-entering for the next step cannot slip
+ * through a barrier its slower peers have not left yet.
  */
 #pragma once
 #include "../rad_core.h"
@@ -34,11 +26,9 @@ public:
 
     void arrive_and_wait();
 
-    /* Release everyone regardless of how many have arrived, and refuse every later arrival. The
-     * engine calls this on shutdown and on a device fault: a rank that has already exited must not
-     * leave its peers parked on a barrier that can no longer be completed (spec §17 -- a device
-     * fault is not recoverable in-process, and the engine exits rather than serving from a wedged
-     * queue, which it cannot do while a thread is blocked here). */
+    /* Release everyone regardless of how many have arrived, and make every later arrival return
+     * at once. Called on shutdown and on a device fault, so ranks are not left parked on a barrier
+     * an exited rank can no longer complete; the engine must be able to exit (spec §17). */
     void abort();
 
 
diff --git a/core/runtime/residency.h b/core/runtime/residency.h
index bd734312..7e60678e 100644
--- a/core/runtime/residency.h
+++ b/core/runtime/residency.h
@@ -1,16 +1,11 @@
 /* residency.h -- the seam the placement component plugs into.
  *
- * The run phase takes weight HANDLES, never pointers (spec §3.2). It resolves a handle to a
- * pointer at issue time, which is the only reason the mover is allowed to relocate a weight while
- * the model is serving. This header is the whole of the contract between the two: the run phase
- * asks a question that never blocks, and the placement component answers it out of a table it
- * owns.
+ * The run phase takes weight handles, never pointers (spec §3.2), and resolves them at issue time,
+ * which is what lets the mover relocate a weight while serving. The run phase asks a non-blocking
+ * question; the placement component answers from a table it owns.
  *
- * The degenerate case matters as much as the interesting one. In the all-in-VRAM deployment the
- * planner assigned everything to tier 0 and the mover never runs, so no ResidencyTable is
- * installed at all and the lookup collapses to WeightInfo::ptr -- a pointer the run phase already
- * baked into its per-weight tensor template. There is no virtual call, no branch on a table entry,
- * and nothing to pay for a feature that deployment is not using.
+ * In an all-in-VRAM deployment no ResidencyTable is installed and the lookup collapses to
+ * WeightInfo::ptr, already baked into the per-weight tensor template: no virtual call, no cost.
  */
 #pragma once
 #include "../rad_core.h"
@@ -19,22 +14,16 @@
 
 namespace rad {
 
-/* Where a weight's bytes are RIGHT NOW, and whether they have arrived.
+/* Where a weight's bytes are now, and whether they have arrived.
  *
- * `ready` is the mover's event. Null means resident and settled: nothing to wait on, which is the
- * common case even under expert offload because a hot expert stays put for many steps. Non-null
- * means a transfer into `ptr` is in flight and the compute stream must be ordered behind it -- a
- * STREAM wait, never a host sync, which is what lets placement be dynamic without serialising the
- * step (spec §5.4).
+ * `ready` is the mover's event. Null means resident and settled (the common case, even under
+ * expert offload). Non-null means a transfer into `ptr` is in flight and the compute stream must
+ * wait on it -- a stream wait, never a host sync (spec §5.4).
  *
- * `generation` is what makes that wait cheap, and it is a contract the mover has to keep: it MUST
- * be bumped whenever a new transfer into this slot begins. The run phase memoises "the compute
- * stream has already been made to wait on generation g of weight w" and skips the wait every time
- * afterwards. That is sound because a stream wait orders everything issued after it, so one wait
- * per generation is sufficient and per-issue waits are pure cost -- at 64 layers and eight experts
- * a step they would be thousands of runtime calls buying nothing. A mover that reuses an event
- * without bumping the generation silently loses the ordering, and the symptom is garbage output
- * three layers later with no way to bisect it.
+ * Invariant: the mover bumps `generation` whenever a new transfer into the slot begins. The run
+ * phase waits once per (weight, generation) and skips later waits, since a stream wait orders
+ * everything issued after it. Reusing an event without bumping the generation silently loses the
+ * ordering and corrupts output.
  */
 struct WeightSlot {
     void*    ptr;
@@ -46,27 +35,22 @@ class ResidencyTable {
 public:
     virtual ~ResidencyTable() = default;
 
-    /* NEVER blocks. Not "usually does not block" -- this is called once per weight operand per
-     * issue, inside the step, and a lock here would serialise the mover against compute, which is
-     * the exact failure this design exists to avoid. Returning null means "I have nothing for this
-     * handle" and the run phase falls back to WeightInfo::ptr. */
+    /* Never blocks: called once per weight operand per issue, and a lock would serialise the
+     * mover against compute. Null means no entry; the run phase falls back to WeightInfo::ptr. */
     virtual const WeightSlot* lookup(rad_weight) const = 0;
 
-    /* A count that changes whenever any slot's pointer, event or generation does. Everything
-     * lookup() returns is a function of it, so a caller that resolved a run of weights at one
-     * epoch may reuse that answer for as long as the epoch stands -- which is what keeps a routed
-     * layer's expert table from being walked, entry by entry, at every issue. */
+    /* Changes whenever any slot's pointer, event or generation does. Lookups resolved at one
+     * epoch stay valid while it stands, so a routed layer's expert table is not re-walked at
+     * every issue. */
     virtual uint64_t epoch() const = 0;
 
-    /* THE SLOTS WHOSE POINTER OR EVENT CHANGED since the run phase last cleared the list, each
-     * named once. A routed layer's weight table holds its whole expert set and a step moves a
-     * handful of experts, so the run phase updates the entries named here rather than resolving
-     * every entry of every table whenever the epoch moves -- which, with experts moving on most
-     * steps, would be every entry of every table on most steps.
+    /* The slots whose pointer or event changed since the last clear_changes(), each named once.
+     * A step moves a handful of experts, so the run phase updates only these entries instead of
+     * re-resolving every table when the epoch moves. A slot that only settled (same pointer) is
+     * not named.
      *
-     * One reader: the run phase of the rank this table belongs to, on the thread that also drives
-     * the writers, so neither call races the other. A slot that only SETTLED -- its transfer
-     * landed, the pointer stayed -- is not named, because nothing a reader holds becomes wrong. */
+     * One reader: this rank's run phase, on the thread that also drives the writers, so the two
+     * calls do not race. */
     virtual const std::vector& changes() const = 0;
     virtual void clear_changes() = 0;
 };
diff --git a/core/runtime/stager.h b/core/runtime/stager.h
index 34a216be..dd564e51 100644
--- a/core/runtime/stager.h
+++ b/core/runtime/stager.h
@@ -1,15 +1,13 @@
 /* stager.h -- the seam a step-time weight stager plugs into.
  *
- * The run phase resolves weights through the residency table (runtime/residency.h), and the mover
- * changes that table between steps. A stager changes it WITHIN a step: it copies a weight that
- * lives off the card into VRAM ahead of the op that reads it and publishes the copy for that op,
- * then publishes the host address again once the op is behind it. The run phase does not know what
- * is staged or why; it calls the stager around the ops of a pass it armed for and re-reads the
- * residency table when the stager says it changed it.
+ * The mover changes the residency table (runtime/residency.h) between steps; a stager changes it
+ * within a step. It copies an off-card weight into VRAM ahead of the op that reads it, publishes
+ * the copy for that op, and republishes the host address once the op is behind it. The run phase
+ * calls the stager around the ops of a pass it armed for and re-reads the residency table when
+ * told it changed.
  *
- * A PASS THE STAGER ARMS FOR IS ISSUED LIVE, never recorded or played from a tape: a tape replays
- * the packets of the pass it recorded and not the host work between them, and the copies and
- * publishes here are exactly that host work.
+ * A pass the stager arms for is issued live, never recorded or replayed from a tape: a tape
+ * replays only packets, not the host work (copies, publishes) between them.
  */
 #pragma once
 #include "../rad_core.h"
@@ -31,7 +29,7 @@ public:
     virtual int before_op(rad_op h, RadStream s, bool* resync) = 0;
 
     /* After op `h` was issued on stream `s`: the point a staged weight's last reader is behind. */
-    virtual int after_op(rad_op h, RadStream s) = 0;
+    virtual int after_op(rad_op, RadStream) { return RAD_OK; }
 
     /* The pass has been issued, on `s`: nothing the stager published for it may outlive it. It
      * may publish weights for a later pass it expects to arm for, which that pass's begin_pass
@@ -39,11 +37,9 @@ public:
     virtual int end_pass(RadStream s) = 0;
 };
 
-/* TWO STAGERS ON ONE PASS, each called only on the passes it armed for. A stager that declined a
- * pass is not handed its ops: one that arms only for large passes -- because its buffers are lent
- * out the rest of the time -- must not stage into memory it does not own because another stager
- * armed. The order is fixed, so the copies and stream waits each issues land in the same order on
- * every pass. */
+/* Two stagers on one pass, each called only on the passes it armed for, so a stager whose
+ * buffers are lent out on small passes never stages because the other one armed. The call order
+ * is fixed, so copies and stream waits land in the same order on every pass. */
 class StagerChain final : public OpStager {
 public:
     void set(OpStager* a, OpStager* b) { s_[0] = a; s_[1] = b; }
diff --git a/core/runtime/tierexec.cpp b/core/runtime/tierexec.cpp
index 3c563b3f..b4d4c90a 100644
--- a/core/runtime/tierexec.cpp
+++ b/core/runtime/tierexec.cpp
@@ -10,11 +10,9 @@ namespace rad {
 
 TierExec::~TierExec() { close(); }
 
-/* The two ops are resolved ONCE, at configure, and at the width they will actually be called at.
- * `n` is the fragment in bytes and it is a per-group constant, so nothing here re-resolves on the
- * maintenance path -- a selector call between steps would be affordable and is still the wrong
- * shape: the kernel that serves a transfer must not be able to change underneath a half-finished
- * batch. */
+/* gather_rows and scatter_rows are resolved once here, at the width they are called at (`n` is the
+ * per-group fragment in bytes). Nothing re-resolves on the maintenance path, so the kernel serving
+ * a transfer cannot change in the middle of a batch. */
 int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers,
                         const std::vector& groups, int max_batch, int64_t max_copy,
                         int64_t max_chain, bool leader, int device, int64_t slot_off,
@@ -47,9 +45,8 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers,
             gi_.push_back(gi);
             continue;
         }
-        /* THE FRAGMENT WIDTH IS THE CONSTRAINT THE KERNEL IS PICKED ON. libr4d's byte-row pair
-         * takes n as a multiple of 4; a geometry that does not satisfy it resolves to nothing
-         * here rather than failing at launch inside a batch. */
+        /* The kernel is picked on the fragment width (libr4d's byte-row pair needs n % 4 == 0).
+         * An unsupported width fails here rather than at launch inside a batch. */
         Geometry q;
         q.set_s("dtype", "u8");
         q.set_i("n", gi.frag);
@@ -67,9 +64,8 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers,
         gi_.push_back(gi);
     }
     if (gi_.empty()) return RAD_E_UNSUPPORTED;
-    /* EVERY CACHED GROUP ZERO ON THIS RANK: it would hold nothing of any entry, and an empty
-     * entry is a zero-width copy on every path below. Said, and the tiers are off -- one rank
-     * that cannot take part takes them off for all. */
+    /* Every cached group is zero on this rank, so its entry would be empty. One rank that cannot
+     * take part turns the tiers off for all. */
     if (off == 0) {
         RAD_WARN("kv tiers: this rank keeps no cache for any group the prefix cache holds "
                  "(rad_kv_group_zero), so it has no part of an entry to move. The tiers are off.");
@@ -78,10 +74,7 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers,
     }
     entry_bytes_ = off;
 
-    /* NOTHING IS BUILT ON THE DEVICE HERE -- see device_init(). A tier that is configured but has
-     * no job to run must cost the step nothing, and on this engine that is not a figure of speech:
-     * building the staging buffer and the stream at bringup costs 13.3 ms of a 20.5 ms decode step
-     * on a two-card R9700 Flash-Next server, whether or not a single byte ever moves. */
+    /* Nothing is built on the device here; see device_init(). */
     verify_ = leader && std::getenv("RADIANCE_DEBUG_TIER_VERIFY") != nullptr;
 
     char buf[320];
@@ -97,9 +90,8 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers,
 TierExec::Sizes TierExec::sizes(int64_t entry_bytes, int64_t max_ctx, int64_t block_size) {
     Sizes s;
     if (entry_bytes <= 0) return s;
-    /* 16 MiB of staging a rank, as entries, between 64 and 4096 of them: the reasons are at the
-     * call in bringup. A copy out is four batches, and a restore is a whole chain, as long as the
-     * longest context the server takes. */
+    /* 16 MiB of staging per rank, clamped to 64..4096 entries (rationale at the bringup call site).
+     * A copy out is four batches; a restore is a whole chain as long as the longest context. */
     s.max_batch = (int)std::min(4096, std::max(64, (16ll << 20) / entry_bytes));
     s.max_copy  = 4ll * s.max_batch;
     const int64_t bs = std::max(1, block_size);
@@ -107,8 +99,7 @@ TierExec::Sizes TierExec::sizes(int64_t entry_bytes, int64_t max_ctx, int64_t bl
     return s;
 }
 
-/* What device_init() allocates, each allocation rounded to the pool granule the card hands VRAM
- * out in. */
+/* What device_init() allocates, each allocation rounded to the VRAM pool granule. */
 int64_t TierExec::device_bytes(int64_t entry_bytes, int n_groups, const Sizes& s) {
     if (entry_bytes <= 0 || n_groups <= 0 || s.max_batch <= 0) return 0;
     const int64_t idx_n = (int64_t)n_groups * (s.max_copy + (int64_t)kRing * s.max_chain);
@@ -117,21 +108,11 @@ int64_t TierExec::device_bytes(int64_t entry_bytes, int n_groups, const Sizes& s
 }
 
 void TierExec::close() {
-    /* Nothing may still be reading the buffers about to be freed. */
+    /* Drain before freeing buffers the stream may still read. */
     if (stream_) (void)rad_stream_sync(stream_);
     if (stream_ && own_stream_) rad_stream_destroy(stream_);
     stream_ = nullptr; shared_ = nullptr; own_stream_ = false;
-    if (stage_)    { rad_dev_free(stage_, RAD_MEM_DEVICE); stage_ = nullptr; }
-    if (idx_dev_)  { rad_dev_free(idx_dev_, RAD_MEM_DEVICE); idx_dev_ = nullptr; }
-    if (idx_host_) { rad_dev_free(idx_host_, RAD_MEM_HOST_PINNED); idx_host_ = nullptr; }
-    for (int i = 0; i < kRing; ++i) {
-        if (ring_ev_[i]) rad_event_destroy(ring_ev_[i]);
-        ring_ev_[i] = nullptr;
-        ring_used_[i] = false;
-    }
-    if (ev_compute_) { rad_event_destroy(ev_compute_); ev_compute_ = nullptr; }
-    if (ev_copy_)    { rad_event_destroy(ev_copy_);    ev_copy_ = nullptr; }
-    if (ev_restore_) { rad_event_destroy(ev_restore_); ev_restore_ = nullptr; }
+    release_device();
     copy_out_ = false;
     gi_.clear();
     order_.clear();
@@ -143,26 +124,25 @@ void TierExec::close() {
     report_.clear();
 }
 
-/* THE DEVICE SIDE, BUILT ON FIRST USE AND NOT BEFORE.
- *
- * Ctx::lane_init() makes the same argument for the second compute lane: a stream is cheap
- * enough that its cost hides inside the run-to-run spread of a warming part, so the only honest
- * way to claim the lane costs nothing when unused is to not build it. The tiers follow the same
- * rule, and here the cost is not small enough to hide in anything. Decode step time with the
- * device side built at bringup, on a two-card R9700 Flash-Next server at 200K context:
- *
- *   no tiers                                             20.54 ms/step   collect 14.66
- *   tiers on, 512 MiB host arena                         33.94 ms/step   collect 26.78
- *   tiers on, idle threshold a day -- NOTHING EVER MOVED 33.88 ms/step   collect 26.66
- *
- * In the third line not one byte crosses the link, and the step is still 65% longer. The cost is
- * in `collect` -- device time -- and a configured tier that has nothing to do pays it on every
- * step. It is not the transfers, not the pinned host arena (512 MiB costs exactly what 12 GiB
- * does) and not the VRAM the staging takes (with no tiers and --gpu-headroom-mib lowered to leave
- * the same 17 MiB free, the step runs at full speed).
- *
- * So the device side is built when the first job needs it, and a server whose conversations never
- * finish pays nothing for the tiers. */
+void TierExec::release_device() {
+    if (stage_)    { rad_dev_free(stage_, RAD_MEM_DEVICE); stage_ = nullptr; }
+    if (idx_dev_)  { rad_dev_free(idx_dev_, RAD_MEM_DEVICE); idx_dev_ = nullptr; }
+    if (idx_host_) { rad_dev_free(idx_host_, RAD_MEM_HOST_PINNED); idx_host_ = nullptr; }
+    for (int i = 0; i < kRing; ++i) {
+        if (ring_ev_[i]) rad_event_destroy(ring_ev_[i]);
+        ring_ev_[i] = nullptr;
+        ring_used_[i] = false;
+    }
+    if (ev_compute_) { rad_event_destroy(ev_compute_); ev_compute_ = nullptr; }
+    if (ev_copy_)    { rad_event_destroy(ev_copy_);    ev_copy_ = nullptr; }
+    if (ev_restore_) { rad_event_destroy(ev_restore_); ev_restore_ = nullptr; }
+}
+
+/* Builds the device side on first use, never at bringup (same rule as Ctx::lane_init()). Built
+ * eagerly, it makes every decode step 65% longer even when nothing ever moves: on two R9700s with
+ * Flash-Next at 200K context, 20.5 -> 33.9 ms/step, all of it device time. The cost is not the
+ * transfers, the pinned arena size or the staging VRAM; it is the extra hardware queue (see
+ * stream_ in tierexec.h). */
 int TierExec::device_init() {
     if (stream_) return RAD_OK;
     RAD_TRY(rad_dev_set(device_));
@@ -176,21 +156,10 @@ int TierExec::device_init() {
     bool ev = rad_event_create(&ev_compute_) == RAD_OK && rad_event_create(&ev_copy_) == RAD_OK &&
               rad_event_create(&ev_restore_) == RAD_OK;
     for (int i = 0; i < kRing && ev; ++i) ev = rad_event_create(&ring_ev_[i]) == RAD_OK;
-    auto undo = [&] {
-        if (stage_)    { rad_dev_free(stage_, RAD_MEM_DEVICE); stage_ = nullptr; }
-        if (idx_dev_)  { rad_dev_free(idx_dev_, RAD_MEM_DEVICE); idx_dev_ = nullptr; }
-        if (idx_host_) { rad_dev_free(idx_host_, RAD_MEM_HOST_PINNED); idx_host_ = nullptr; }
-        for (int i = 0; i < kRing; ++i) { if (ring_ev_[i]) rad_event_destroy(ring_ev_[i]); ring_ev_[i] = nullptr; }
-        if (ev_compute_) { rad_event_destroy(ev_compute_); ev_compute_ = nullptr; }
-        if (ev_copy_)    { rad_event_destroy(ev_copy_);    ev_copy_ = nullptr; }
-        if (ev_restore_) { rad_event_destroy(ev_restore_); ev_restore_ = nullptr; }
-    };
-    if (!stage_ || !idx_dev_ || !idx_host_ || !ev) { undo(); return RAD_E_NOMEM; }
-    /* THE MOVER'S STREAM IF THERE IS ONE, AND A NEW ONE ONLY IF THERE IS NOT. Both move bytes
-     * nobody is waiting for, so one maintenance stream a rank serves both -- and the fourth
-     * hardware queue a second one would claim costs about 13 ms a decode step (see
-     * device_init). Never the step's own stream: a copy out would then be a dependency of the
-     * next token. */
+    if (!stage_ || !idx_dev_ || !idx_host_ || !ev) { release_device(); return RAD_E_NOMEM; }
+    /* Borrow the mover's maintenance stream if there is one; both move bytes nobody waits for,
+     * and a fourth hardware queue costs about 13 ms per decode step. Never the step's own
+     * stream, or a copy out would become a dependency of the next token. */
     if (shared_) {
         stream_ = shared_;
         own_stream_ = false;
@@ -198,24 +167,14 @@ int TierExec::device_init() {
         own_stream_ = true;
     } else {
         stream_ = nullptr;
-        undo();
+        release_device();
         return RAD_E_DEVICE;
     }
     return RAD_OK;
 }
 
-int64_t tier_entry_bytes(const KVManager& kv, const std::vector& groups) {
-    int64_t n = 0;
-    for (int32_t g : groups) {
-        const KVGroupPlan* p = kv.plan(g);
-        if (p && p->paged()) n += p->bytes_per_block;
-    }
-    return n;
-}
-
-/* One (group, layer) launch. `stage_base` is the first entry's staging slot; the rows this call
- * writes (or reads) are at a stride of entry_bytes_ from it, which is what puts each entry's
- * fragment inside its own contiguous staging entry. */
+/* One (group, layer) launch. Staging rows are at stride entry_bytes_ from `stage_base` (the first
+ * entry's slot), so each fragment lands inside its own contiguous staging entry. */
 int TierExec::run_rows(const Resolved& r, bool scatter, const GroupInfo& gi, int64_t layer,
                        void* stage_base, const int32_t* d_idx, int64_t n_jobs) {
     RadTensor pool{};
@@ -234,7 +193,7 @@ int TierExec::run_rows(const Resolved& r, bool scatter, const GroupInfo& gi, int
     pack.dtype = RAD_U8;
     pack.rank = 2;
     pack.shape[0] = n_jobs;      pack.shape[1] = gi.frag;
-    pack.stride[0] = entry_bytes_;   /* <-- the whole trick: one entry's stride, not one row's */
+    pack.stride[0] = entry_bytes_;   /* one entry's stride, not one row's */
     pack.stride[1] = 1;
     pack.data = (char*)stage_base + gi.off + layer * gi.frag;
 
@@ -242,10 +201,8 @@ int TierExec::run_rows(const Resolved& r, bool scatter, const GroupInfo& gi, int
     if (scatter) { t3[0] = pack; t3[1] = idx; t3[2] = pool; }
     else         { t3[0] = pool; t3[1] = idx; t3[2] = pack; }
 
-    /* THE RESOLVED GEOMETRY, not a hand-built one. It carries whatever the winning kernel
-     * supplied for a derived key as well as the query, and M in it is the band's upper bound --
-     * which is correct and is the convention: both implementations take the row count from the
-     * OPERAND extent, because M is ranged and the value in the args is the worst case. */
+    /* Pass the resolved geometry, which carries the winning kernel's derived keys. Its M is the
+     * band's upper bound; kernels take the row count from the operand extent. */
     RadArgs a{};
     a.t = t3; a.n_t = 3;
     a.p = r.geom.params(); a.n_p = r.geom.n_params();
@@ -273,17 +230,15 @@ void TierExec::verify_check(const BlockHash& key, const void* p, int64_t n) {
     if (it == out_sum_.end()) return;               /* never went out through this process */
     const uint64_t back = tier_fnv(p, n);
     if (back == it->second) return;
-    RAD_ERR("kv tiers: the attention blocks for %s came back DIFFERENT (%016llx out, %016llx in). "
-            "The tier is moving the wrong bytes, not the engine choosing differently downstream.",
+    RAD_ERR("kv tiers: the attention blocks for %s came back different (%016llx out, %016llx in); "
+            "the tier moved the wrong bytes",
             key.str().c_str(), (unsigned long long)it->second, (unsigned long long)back);
 }
 
 /* ------------------------------------------------------------------ helpers */
 
-/* WHY THIS IS NOT RAD_TRY. A tier that fails is invisible: the entry stays where it was, the pool
- * keeps its blocks, and everything still works -- just slower, forever, with a counter nobody is
- * looking at. The first failure names the call it came from, because "5824 failures" and nothing
- * else is a day of bisecting. */
+/* Like RAD_TRY, but the first failure is logged with the call it came from. A failing tier is
+ * otherwise invisible: entries stay put and the server only gets slower. */
 #define TIER_TRY(call, what)                                                                  \
     do { const int _s = (call);                                                               \
          if (_s != RAD_OK) { warn_once(what, _s); return _s; } } while (0)
@@ -339,9 +294,8 @@ int TierExec::issue_copy(std::vector& jobs, RadStream compute) {
     TIER_TRY(rad_dev_set(device_), "selecting the rank device");
     TIER_TRY(device_init(), "building the transfer staging");
     const int st = enqueue_copy(jobs, compute);
-    /* A COPY THAT FAILED PART OF THE WAY IN IS DRAINED BEFORE ITS SLOTS GO BACK. The report frees
-     * every host slot the batch was handed, and a transfer already queued into one would land on
-     * whatever the arena gives that slot to next. */
+    /* Drain a partly enqueued copy before its host slots are freed by the report, or a queued
+     * transfer would land on the slot's next owner. */
     if (st != RAD_OK) (void)rad_stream_sync(stream_);
     return st;
 }
@@ -351,13 +305,11 @@ int TierExec::enqueue_copy(std::vector& jobs, RadStream compute) {
     for (TierJob& j : jobs) if (!j.blocks.empty()) order_.push_back(&j);
     const int64_t n = (int64_t)order_.size();
     if (n > copy_idx_) return RAD_E_INVAL;
-    /* EVERY ID FIRST, BEFORE ANY OF THEM IS LAUNCHED AGAINST. A gather over an unbacked id faults
-     * the whole card rather than failing the transfer. */
+    /* Check every id before any launch: a gather over an unbacked id faults the whole card. */
     for (TierJob* j : order_)
         if (!blocks_backed(j->blocks, "copy to host")) return RAD_E_STATE;
 
-    /* AFTER EVERYTHING THE COMPUTE STREAM HAS BEEN GIVEN, which includes the step that wrote these
-     * blocks. A stream wait, not a host wait. */
+    /* Stream-ordered after everything given to compute, including the step that wrote these. */
     TIER_TRY(rad_event_record(ev_compute_, compute), "ordering the copy after the step");
     TIER_TRY(rad_event_wait(stream_, ev_compute_), "ordering the copy after the step");
 
@@ -435,15 +387,13 @@ int TierExec::issue_restore(std::vector& jobs, RadStream compute,
     TIER_TRY(device_init(), "building the transfer staging");
     const size_t ng = gi_.size();
 
-    /* WHO CHOOSES THE BLOCKS, AND WHO KEEPS THE BOOKS. Ids are shared across ranks -- one block
-     * table indexes every rank's shard -- so exactly one rank may choose, and that same rank is
-     * the only one whose allocator means anything: the prefix cache holds the KV references and
-     * the prefix cache is rank 0's. A follower writes into the ids it is handed and reserves
-     * nothing.
+    /* Block ids are shared across ranks (one block table indexes every shard), so only the leader
+     * chooses and reserves them; its allocator is the one the prefix cache (rank 0's) references.
+     * Followers write into the ids they are handed.
      *
-     * THE WHOLE CHAIN IS RESERVED BEFORE ANY OF IT MOVES, one recall of the loan for all of it.
-     * Where the pool runs short the chain is cut at that point and the rest stay unstarted: a hit
-     * needs a contiguous prefix, so an entry past a gap would be restored for nothing. */
+     * The whole chain is reserved before anything moves, with one loan recall. If the pool runs
+     * short the chain is cut there: a hit needs a contiguous prefix, so entries past a gap are
+     * useless. */
     if (leader_) {
         const int64_t n = (int64_t)jobs.size();
         std::vector> ids(ng);
@@ -463,15 +413,13 @@ int TierExec::issue_restore(std::vector& jobs, RadStream compute,
     }
     size_t m = 0;
     while (m < jobs.size() && jobs[m].blocks.size() == ng) ++m;
-    /* AND WHETHER THIS RANK CAN ADDRESS WHAT IT WAS HANDED. The leader chose these ids against its
-     * own live mark and the recall moved every follower's with it; this is the check that it did. */
+    /* The leader chose ids against its own live mark and the recall should have moved every
+     * follower's with it; verify that here. */
     for (size_t i = 0; i < m; ++i)
         if (!blocks_backed(jobs[i].blocks, "restore")) { m = i; break; }
 
-    /* THE CUT IS WHAT THE FOLLOWERS READ. They find their chain by which jobs carry block ids,
-     * so every job past the point the leader stopped gives its ids back and carries none. A
-     * follower handed ids for an entry the leader could not address would copy into blocks that
-     * are not the cache's. */
+    /* Followers find the chain by which jobs carry block ids, so every job past the cut releases
+     * its ids and carries none; otherwise a follower would copy into blocks the cache does not own. */
     if (leader_) {
         for (size_t i = m; i < jobs.size(); ++i) {
             for (size_t k = 0; k < ng && k < jobs[i].blocks.size(); ++k)
@@ -487,11 +435,10 @@ int TierExec::issue_restore(std::vector& jobs, RadStream compute,
         verify_check(jobs[i].key, (char*)tiers_->arena().at(jobs[i].host_slot) + slot_off_,
                      entry_bytes_);
 
-    /* FROM HERE ON A FAILURE LEAVES A MIXTURE, so every job about to be written is marked started
-     * first -- report() drops a started job that failed rather than trusting its host copy to
-     * describe blocks some layers of which were overwritten. And the compute stream is made to
-     * wait on whatever was enqueued, success or not: a failed job's blocks go back to the pool,
-     * and nothing may be written into them before the transfers already queued against them. */
+    /* From here a failure leaves blocks partly overwritten. Mark jobs started first, so report()
+     * drops a failed started job instead of trusting its host copy. The compute stream waits on
+     * whatever was enqueued, success or not, because a failed job's blocks return to the pool and
+     * must not be reused before the queued transfers into them. */
     for (size_t i = 0; i < m; ++i) jobs[i].started = true;
     const int ri = ring_next_;
     ring_next_ = (ring_next_ + 1) % kRing;
@@ -522,8 +469,8 @@ int TierExec::issue_restore(std::vector& jobs, RadStream compute,
     for (size_t i = 0; i < done; ++i) (*ok)[i] = 1;
     st_.bytes_in += (int64_t)done * entry_bytes_;
 
-    /* THE STEP THAT READS THESE WAITS FOR THEM, on the device. If even the marker cannot be
-     * enqueued the only ordering left is the host's. */
+    /* The reading step waits on the device; if the event cannot be enqueued, fall back to a host
+     * wait. */
     if (rad_event_record(ev_restore_, stream_) != RAD_OK ||
         rad_event_wait(compute, ev_restore_) != RAD_OK) {
         (void)rad_stream_sync(stream_);
@@ -542,9 +489,8 @@ void TierExec::report_pass(std::vector& jobs, const std::vector&
     for (size_t i = 0; i < jobs.size(); ++i) {
         TierJob& j = jobs[i];
         const bool good = i < ok.size() && ok[i];
-        /* A PROMOTION THAT FAILED AS A WHOLE gives back the blocks the leader took for it, once
-         * nothing queued against them can still land: report() drops or keeps the record, and
-         * nothing will ever name these blocks again. */
+        /* A failed promotion releases the leader's blocks once nothing queued against them can
+         * still land; after report() nothing names them again. */
         if (j.kind == TierJob::Kind::ToDevice && !good) {
             if (!quiet) { quiesce(); quiet = true; }
             for (size_t k = 0; k < gi_.size() && k < j.blocks.size(); ++k)
diff --git a/core/runtime/tierexec.h b/core/runtime/tierexec.h
index c25c1712..b070cb80 100644
--- a/core/runtime/tierexec.h
+++ b/core/runtime/tierexec.h
@@ -1,39 +1,28 @@
-/* tierexec.h -- the side of the KV tiers that actually moves bytes.
+/* tierexec.h -- executes KV tier transfers.
  *
- * core/mem/kvtier.h decides WHAT should move and hands out TierJobs; this executes them. The split
- * is the one KVManager already uses for BlockCopy and it is not decoration: core/mem has no stream
- * and must not acquire one, because a synchronisation on the step path is what this design spends
- * itself avoiding (spec §5.4).
+ * core/mem/kvtier.h decides what moves and hands out TierJobs; this runs them. core/mem has no
+ * stream and must not get one, because the design avoids host synchronisation on the step path
+ * (spec §5.4). Same split as KVManager and BlockCopy.
  *
- * ============================== NOTHING HERE WAITS ON THE HOST ================================
+ * Nothing here waits on the host. Copies are enqueued and ordered by events:
+ *   - a copy out waits on the transfer stream for everything the compute stream had been given
+ *     when it was issued (including the step that wrote the blocks) and signals an event the
+ *     engine polls between steps. The engine keeps building steps meanwhile and the scheduler
+ *     lock is not held;
+ *   - a restore in makes the compute stream wait for it, so the step reading the restored blocks
+ *     runs after they land.
  *
- * A copy out and a restore in are both ENQUEUED and ordered by events, never by a host wait:
+ * Transfer shape. A paged pool is layer-major: layer l of group g owns
+ * `[base + l*layer_stride, + layer_stride)` and a block in it is at
+ * `block * layer_bytes_per_block()`. A logical block is thus `n_layers` fragments of a few hundred
+ * bytes, too small to move one at a time. Within a layer, blocks are dense rows of a matrix, so
+ * packing a set is `gather_rows` and restoring it is `scatter_rows`: one launch per (group, layer)
+ * per staging batch.
  *
- *   - a copy out waits, on the transfer stream, for everything the compute stream had been given
- *     when it was issued -- the step that wrote the blocks is in there -- and signals an event the
- *     engine polls between steps. The engine thread goes on building steps the whole time, and the
- *     scheduler's lock is not held while it runs;
- *   - a restore in makes the COMPUTE stream wait for it, so the step that reads the restored
- *     blocks runs after they land without the host having waited for anything.
- *
- * ============================== THE TRANSFER, AND WHY IT IS SHAPED THIS WAY ====================
- *
- * A paged pool is LAYER-MAJOR: layer l of group g owns `[base + l*layer_stride, + layer_stride)`
- * and a block inside it is `block * layer_bytes_per_block()`. So a logical block is `n_layers`
- * fragments of a few hundred bytes, and moving one block at a time means a few hundred bytes a
- * transfer -- dispatch cost with the data as a rounding error.
- *
- * Turned around, WITHIN a layer the blocks are dense rows of a matrix. That makes packing an
- * arbitrary set of them exactly `gather_rows` and restoring them exactly `scatter_rows`, and the
- * transfer count becomes ONE LAUNCH PER (GROUP, LAYER) for a whole staging batch rather than per
- * block.
- *
- * THE STAGING BUFFER'S LAYOUT IS WHAT MAKES THE HOST COPY CONTIGUOUS. Device staging is
- * `max_batch * entry_bytes`, and one entry's bytes are [group][layer][fragment] laid end to end.
- * For a given (group, layer) the destination rows are then at a stride of `entry_bytes` from a
- * base inside the first entry -- which is exactly `gather_rows`'s `y` pitch, so one launch writes
- * every entry's fragment for that layer directly into the place it will be copied from. The host
- * side is then one strided copy per run of consecutive arena slots.
+ * Staging layout. Device staging is `max_batch * entry_bytes`; one entry is [group][layer][fragment]
+ * end to end. For a given (group, layer) the destination rows sit at stride `entry_bytes` from a
+ * base in the first entry, which is `gather_rows`'s `y` pitch, so one launch writes every entry's
+ * fragment in place and the host side is one strided copy per run of consecutive arena slots.
  */
 #pragma once
 #include "mem/kv.h"
@@ -52,12 +41,9 @@ class TierExec {
 public:
     ~TierExec();
     /* `groups` is PrefixCache::cached_groups(): the paged groups an entry holds a block in, in the
-     * order the entry's `blocks` vector uses. The staging layout is derived from them once here,
-     * because a second derivation of the same offsets is a second place to get them wrong.
-     *
-     * `max_batch` is the staging buffer in entries, `max_copy` the most entries one copy out may
-     * carry, and `max_chain` the longest chain one restore brings back -- the index buffers are
-     * sized from the last two. */
+     * order of the entry's `blocks` vector. The staging layout is derived from them here only.
+     * `max_batch` is the staging buffer in entries, `max_copy` the most entries per copy out and
+     * `max_chain` the longest restore chain; the index buffers are sized from the last two. */
     int  configure(Registry* reg, KVManager* kv, IdleTiers* tiers,
                    const std::vector& groups, int max_batch, int64_t max_copy,
                    int64_t max_chain, bool leader, int device, int64_t slot_off,
@@ -66,53 +52,44 @@ public:
     bool enabled() const { return enabled_; }
     std::string report() const { return report_; }
 
-    /* THE SIZES A CONFIGURE IS GIVEN, from one entry's bytes on this rank, the longest context and
-     * the block size, and the VRAM device_init() then takes for them. The VRAM budget reserves
-     * device_bytes() before any of this exists and bringup configures with sizes(), so the two
-     * cannot drift apart. */
+    /* configure()'s sizes from one entry's bytes on this rank, the longest context and the block
+     * size, and the VRAM device_init() takes for them. The VRAM budget reserves device_bytes() and
+     * bringup configures with sizes(), so the two cannot drift apart. */
     struct Sizes { int max_batch = 0; int64_t max_copy = 0, max_chain = 0; };
     static Sizes   sizes(int64_t entry_bytes, int64_t max_ctx, int64_t block_size);
     static int64_t device_bytes(int64_t entry_bytes, int n_groups, const Sizes& s);
 
-    /* DECIDING AND DOING ARE SEPARATE, and under tensor parallelism that is the point. The policy
-     * is one object describing CONVERSATIONS, which are not sharded; the transfer is per rank,
-     * because each rank holds its own shard of every block. So the leader plans, every rank runs
-     * the same job list, and the leader reports the outcome once.
-     *
-     * A follower that consulted the policy itself would find each record already pending -- or
-     * already reported -- and would move nothing, silently, leaving its shard of the pool holding
-     * whatever was there before. That is corrupt KV on one card and not the other, which is the
-     * worst shape this failure can take. */
+    /* Planning and transfer are separate for tensor parallelism. The policy describes conversations,
+     * which are not sharded; the transfer is per rank, since each rank holds its own shard of every
+     * block. The leader plans, every rank runs the same job list, and the leader reports once. A
+     * follower consulting the policy itself would find records already pending and silently move
+     * nothing, corrupting KV on one card only. */
 
     /* ---------------- copy on idle ----------------
      *
-     * Enqueue a batch of WriteBack jobs on this rank and return. The copy is ordered after
-     * everything `compute` had been given, and `copy_state` says when it has landed. One batch
-     * at a time: the engine does not issue the next until this one has reported, which is what
-     * lets the staging and index buffers be reused without a wait. */
+     * Enqueues a batch of WriteBack jobs on this rank, ordered after everything `compute` had been
+     * given; `copy_state` says when it has landed. One batch at a time: the engine issues the next
+     * only after this one reports, so the staging and index buffers are reused without a wait. */
     int  issue_copy(std::vector& jobs, RadStream compute);
     /* 1 when nothing is out or the last batch has landed, 0 while it is in flight, negative when
      * the transfer stream reported an error. Taking the answer clears it. */
     int  copy_state();
-    bool copy_out() const { return copy_out_; }
-    /* copy_state, after waiting for the batch to land. For a caller that cannot go on until the
-     * copy has a host slot to show for it -- an eviction that would otherwise lose the entry. */
+    /* copy_state after waiting for the batch to land, for a caller that needs the host copy
+     * first (an eviction that would otherwise lose the entry). */
     int  wait_copy();
-    /* EVERYTHING THIS RANK ENQUEUED HAS LANDED. For a block given back on a failure path while a
-     * copy into it may still be in flight: the pool would hand it to a sequence whose writes the
-     * late copy then overwrites. */
+    /* Waits until everything this rank enqueued has landed. Used before a block is given back on a
+     * failure path, where a late in-flight copy would overwrite its next owner's writes. */
     void quiesce();
 
     /* ---------------- restore ----------------
      *
-     * Enqueue a chain of ToDevice jobs, in chain order, and make `compute` wait for them. The
-     * leader chooses every block first, recalling the loan for the
-     * whole chain at once; a chain the pool cannot hold is cut where the reservation ran out, and
-     * the jobs past the cut are left unstarted. `ok[i]` is whether job i was fully enqueued on
-     * this rank. */
+     * Enqueues a chain of ToDevice jobs in chain order and makes `compute` wait for them. The
+     * leader chooses every block first, recalling the loan for the whole chain at once; a chain
+     * the pool cannot hold is cut where the reservation ran out and the rest left unstarted.
+     * `ok[i]` is whether job i was fully enqueued on this rank. */
     int  issue_restore(std::vector& jobs, RadStream compute, std::vector* ok);
-    /* Leader only. Gives back what a failed job held -- a restore's blocks -- and reports every
-     * job to the policy. `now_ns` is when the pass ran: a promotion is a use. */
+    /* Leader only. Gives back a failed restore's blocks and reports every job to the policy.
+     * `now_ns` is the pass time; a promotion counts as a use. */
     void report_pass(std::vector& jobs, const std::vector& ok, uint64_t now_ns);
 
     /* A lookup hit off-device: the job that would bring it back, or false when the entry is not
@@ -131,24 +108,21 @@ private:
         int64_t  n_blocks = 0;
         void*    base = nullptr;
         int64_t  off = 0;           /* this group's start inside one entry's staging bytes */
-        /* rad_kv_group_zero: no shard on this rank. Kept in its place, because a job's block ids
-         * are one per cached group in the same order on every rank; nothing is gathered or
-         * scattered for it and it is no part of this rank's entry. */
+        /* rad_kv_group_zero: no shard on this rank. Kept in place because a job's block ids are
+         * one per cached group in the same order on every rank; it moves no bytes. */
         bool     zero = false;
         Resolved gather, scatter;
     };
 
-    /* The staging buffer, the index buffers, the events and the transfer stream, built on the
-     * first pass that has a job and never at bringup. The cost of building them eagerly is quoted
-     * where it is defined; it is not small. */
+    /* Builds the staging and index buffers, events and transfer stream lazily on the first pass
+     * with a job, never at bringup (see the definition for the cost). */
     int  device_init();
-    /* WHETHER EVERY ID THIS RANK IS ABOUT TO ADDRESS IS THE CACHE'S TO WRITE.
-     *
-     * THE KERNEL'S BOUND IS THE CARVE AND NOT THE LIVE MARK. gather_rows and scatter_rows refuse
-     * an index outside [0, n_blocks), which is every id the carve created -- but the blocks above
-     * live_blocks() are lent to the expert slab, and a restore into one writes over weights a
-     * kernel is reading. That reads as fluent text with a new hash on whichever rank is behind
-     * rather than as a failed transfer, so it is tested here, where the job can still be refused. */
+    /* Frees what device_init() allocated; the stream is the caller's to drain first. */
+    void release_device();
+    /* Whether every id this rank is about to address belongs to the cache. The kernels only bound
+     * ids by the carve, [0, n_blocks), but blocks above live_blocks() are lent to the expert slab,
+     * and a restore into one overwrites weights in use. That corrupts output silently, so it is
+     * checked here, where the job can still be refused. */
     bool blocks_backed(const std::vector& blocks, const char* what);
     void warn_once(const char* what, int st);
     int  run_rows(const Resolved& r, bool scatter, const GroupInfo& gi, int64_t layer,
@@ -161,19 +135,15 @@ private:
     bool      enabled_ = false;
     bool      leader_ = false;   /* this rank chooses block ids; the others follow */
     bool      warned_ = false;
-    /* Separate from `warned_`: a transfer that failed and an id this rank cannot address are
-     * different reports, and the second is a broken invariant rather than a tier having trouble.
-     * Said once, so a refusal the pass retries every tick does not fill the log with it. */
+    /* Separate from `warned_`: an unaddressable id is a broken invariant, not a transfer failure.
+     * Logged once, since the pass retries the refusal every tick. */
     bool      warned_unbacked_ = false;
-    /* THE CARD THIS RANK OWNS. Every allocation and every launch below takes the CURRENT device,
-     * and the engine loop leaves whatever device the last rank used current. Pinned here rather
-     * than assumed. */
+    /* This rank's card. Allocations and launches use the current device, and the engine loop leaves
+     * the last rank's device current, so it is set explicitly. */
     int       device_ = -1;
-    /* WHERE THIS RANK'S BYTES LIVE INSIDE A SHARED SLOT. One host slot holds an entry for the
-     * WHOLE ENGINE, and under tensor parallelism an entry is n_ranks shards of KV that are not
-     * interchangeable. Every rank writing at offset zero would mean the last one to run wins and
-     * every rank scatters back somebody else's half. So the slot is n_ranks entries wide and a
-     * rank only ever touches its own window. */
+    /* This rank's offset inside a shared host slot. A slot holds the whole engine's entry, which
+     * under tensor parallelism is n_ranks distinct KV shards, so the slot is n_ranks entries wide
+     * and each rank touches only its own window. */
     int64_t   slot_off_ = 0;
     int64_t   slot_bytes_ = 0;   /* the whole shared slot: n_ranks * entry_bytes_ */
     Registry* reg_ = nullptr;
@@ -187,13 +157,10 @@ private:
     void*     stage_ = nullptr;     /* device, max_batch_ * entry_bytes_ */
     /* ---- the block indices ----
      *
-     * ONE REGION FOR THE COPY OUT AND A RING OF THEM FOR RESTORES, pinned on the host and mirrored
-     * on the device. An index list is uploaded with the transfer it serves and read by kernels
-     * later in the same stream, so a region may be refilled only once the upload that last read
-     * it has run: one copy is out at a time, so its region is always free when the next is
-     * issued; several restores can be issued in one step, so each takes the next region of the
-     * ring and waits on that region's event -- the upload of a restore issued kRing restores ago,
-     * which has long since run. */
+     * One region for the copy out and a ring of kRing for restores, pinned on the host and mirrored
+     * on the device. A region may be refilled only after the upload that last read it has run. One
+     * copy is out at a time, so its region is always free; several restores can be issued per step,
+     * so each takes the next ring region and waits on its event (the upload kRing restores ago). */
     static constexpr int kRing = 4;
     int32_t*  idx_host_ = nullptr;  /* pinned: copy region, then kRing restore regions */
     int32_t*  idx_dev_ = nullptr;
@@ -206,28 +173,19 @@ private:
     RadEvent  ev_copy_ = nullptr;     /* the last copy out, landed */
     RadEvent  ev_restore_ = nullptr;  /* the last restore, landed */
     bool      copy_out_ = false;
-    /* THE TRANSFER STREAM, WHICH IS USUALLY SOMEBODY ELSE'S. A stream costs a hardware queue and
-     * a fourth queue costs this card 65% of its decode step, so the tier takes the expert mover's
-     * maintenance stream when there is one (Mover::transfer_stream) and only makes its own when
-     * there is not. `own_stream_` is which of those happened, because close() must not destroy a
-     * stream it was lent. */
+    /* Transfer stream. Each stream costs a hardware queue, and a fourth queue costs this card 65% of
+     * its decode step, so the tier borrows the expert mover's maintenance stream
+     * (Mover::transfer_stream) when there is one. `own_stream_` tells close() whether to destroy it. */
     RadStream stream_ = nullptr;
     RadStream shared_ = nullptr;
     bool      own_stream_ = false;
     std::vector order_;
     /* ---- RADIANCE_DEBUG_TIER_VERIFY ----
      *
-     * DID THE BYTES SURVIVE THE ROUND TRIP. A tier that corrupts reads back as fluent, plausible,
-     * wrong text and nothing about the engine says which of a dozen steps lost the bytes. This
-     * hashes what went out and what came back and names the entry when they differ, which splits
-     * the only question worth asking first: is the tier moving the wrong bytes, or is it moving
-     * the right ones and something downstream is choosing differently?
-     *
-     * A DIAGNOSTIC, NOT A GUARD. It hashes on the host, which is a cost on every entry --
-     * affordable when a run is being bisected and not otherwise. Off
-     * unless the variable is set, and leader-only, because the map is keyed by an object the
-     * followers do not own. A copy out is hashed when it has LANDED, which is when copy_state
-     * first sees it done. */
+     * Round-trip check: hashes each entry going out and coming back and names the entry when they
+     * differ, separating "the tier moved wrong bytes" from a downstream fault. A diagnostic, not a
+     * guard: host hashing costs on every entry. Off unless set; leader-only because the map is keyed
+     * by an object followers do not own. A copy out is hashed once landed (first seen by copy_state). */
     bool      verify_ = false;
     std::unordered_map out_sum_;
     struct VerifyNote { BlockHash key; int32_t host_slot = -1; };
diff --git a/core/runtime/wtab.cpp b/core/runtime/wtab.cpp
index bfbed040..360c88ef 100644
--- a/core/runtime/wtab.cpp
+++ b/core/runtime/wtab.cpp
@@ -8,8 +8,8 @@ namespace rad {
 
 int wtab_patch(const WtabPatch& p, RadStream s) {
     if (p.n == 0) return RAD_OK;
-    /* After the stream's queued work, for the reason step_advance gives: a host stream is a queue
-     * with a worker, and a write made ahead of it changes a table that work issued earlier reads. */
+    /* A host stream is a queue with a worker: write only after its queued work, which may read
+     * the old table (same reason as step_advance). */
     if (device_is_host()) {
         RAD_TRY(rad_stream_sync(s));
         for (uint32_t i = 0; i < p.n; ++i) *p.dst[i] = p.val[i];
diff --git a/core/runtime/wtab.h b/core/runtime/wtab.h
index 34dd9398..904dfaf9 100644
--- a/core/runtime/wtab.h
+++ b/core/runtime/wtab.h
@@ -1,10 +1,10 @@
 /* wtab.h -- writing entries of a device weight table in stream order.
  *
- * A routed layer's weight table is a device array of expert pointers, and the mover changes a few
- * of its entries on most steps. The new values travel IN THE KERNEL'S ARGUMENTS, which the backend
- * copies when the dispatch is enqueued. A copy out of a host array would read that array when the
- * card reaches the copy instead -- and the host runs ahead of the card, so by then it may hold the
- * NEXT step's pointers, including one whose transfer that earlier step was never ordered behind.
+ * A routed layer's weight table is a device array of expert pointers; the mover changes a few
+ * entries on most steps. The new values travel in the kernel arguments, which the backend copies
+ * at enqueue. A copy from a host array would read it when the card reaches the copy, and since the
+ * host runs ahead, it could then hold the next step's pointers, including one whose transfer this
+ * step is not ordered behind.
  */
 #pragma once
 #include 
diff --git a/core/runtime/xp_state.h b/core/runtime/xp_state.h
index 4c2875b3..eba9f251 100644
--- a/core/runtime/xp_state.h
+++ b/core/runtime/xp_state.h
@@ -59,8 +59,8 @@ struct XpState {
     std::vector layers;
     uint32_t     seq[kXpGroups] = {};
     int          last_layer = -1;      /* the last layer predicted for: a lower one starts a pass */
-    /* WHETHER IT PAYS: the share of its copies the steps use, judged every kXpWindow predictions from
-     * the counters (stats_h, one window on their way to the host); under kXpMinUse it rests. */
+    /* Payoff: the share of copies the steps use, judged every kXpWindow predictions from the
+     * counters (stats_h lags one window); below kXpMinUse the prefetch rests. */
     int64_t      passes = 0, rest_until = 0, rests = 0;
     int64_t      calls = 0;
     uint32_t     snap_copied = 0, snap_routed = 0;
diff --git a/core/runtime/xprefetch.cpp b/core/runtime/xprefetch.cpp
index 0960965e..30198a14 100644
--- a/core/runtime/xprefetch.cpp
+++ b/core/runtime/xprefetch.cpp
@@ -30,21 +30,18 @@ namespace {
 
 /* A pool class wider than this holds whole tables (the token embedding read in place), not experts. */
 constexpr uint64_t kXpMaxUnit = (uint64_t)64 << 20;
-/* Lists the queue may be behind before a request is dropped. Nothing waits for these lists, so
- * nothing slows a queue that falls behind but this: its copies could not land in time anyway, and a
- * queue that only grows would end up polling marks that have long gone back to the pool. */
+/* Lists the queue may be behind before a request is dropped. Nothing else throttles a lagging
+ * queue: its copies would land too late anyway, and an ever-growing queue would end up polling
+ * marks already returned to the pool. */
 constexpr int64_t kXpBehind = 3;
-/* Dispatches past a dropped request's mark before the signal can be made again: far more than the
+/* Dispatches after a dropped request's mark before its signal may be reused; far more than the
  * pass that completes it. */
 constexpr int64_t kXpMarkHold = 4096;
-/* WHETHER IT PAYS. A copy the step uses saves the link time of reading that expert under the GEMM;
- * one it does not use costs link time the GEMMs wanted, and the prediction costs a little whatever
- * comes of it. Measured on Qwen3.8-Flash-Next, the two balance near a quarter of the copies used: at
- * --tp 1 the steps used half of them and the decode step was 3.6% faster, at --tp 2 -- where each card
- * keeps most experts and its pool holds the ones the steps rarely route -- a sixth, and it was 4-6%
- * slower. So every kXpWindow predictions the prefetch looks at the share of its copies used over the
- * last window, and under kXpMinUse it rests for kXpRest passes -- no prediction, no copy -- and then
- * measures again. */
+/* Payoff. A used copy saves link time under the GEMM; an unused one costs link time the GEMMs
+ * wanted, and the prediction always costs a little. On Qwen3.8-Flash-Next break-even is near a
+ * quarter of copies used (--tp 1 used half and decode was 3.6% faster; --tp 2, where the pool holds
+ * rarely routed experts, used a sixth and was 4-6% slower). Every kXpWindow predictions the share
+ * used over the last window is judged; below kXpMinUse the prefetch rests for kXpRest passes. */
 constexpr int64_t  kXpWindow    = 2048;
 constexpr double   kXpMinUse    = 0.30;
 constexpr uint32_t kXpMinJudged = 512;
@@ -65,8 +62,8 @@ void Ctx::xp_free(XpState& x) {
     if (x.stream) rad_stream_destroy(x.stream);
 }
 
-/* At bringup, once the placement has made its pinned pools: everything the prefetch needs, or nothing
- * and a line saying why it is off. */
+/* At bringup, after placement has made its pinned pools: allocates everything, or nothing and logs
+ * why the prefetch is off. */
 void Ctx::xp_open(const uint64_t* lo, const uint64_t* hi, const uint64_t* stride, int n) {
     if (xp_ || device_is_host() || route_.empty()) return;
     if (!rad_xp_supported(device_)) {
@@ -122,8 +119,8 @@ void Ctx::xp_open(const uint64_t* lo, const uint64_t* hi, const uint64_t* stride
 void Ctx::xp_close() {
     if (!xp_) return;
     XpState& x = *xp_;
-    /* NOTHING MAY READ OR WRITE THE RING WHEN IT GOES: the compute work issued so far can read it
-     * through entries still pointed at it, and the queue's lists write it until they finish. */
+    /* Nothing may touch the ring when it is freed: issued compute work can read it through entries
+     * still pointing at it, and queued DMA lists write it until they finish. */
     if (stream_) rad_stream_sync(stream_);
     if (lane1_) rad_stream_sync(lane1_);
     {
@@ -141,7 +138,7 @@ void Ctx::xp_close() {
         }
         std::this_thread::sleep_for(std::chrono::milliseconds(1));
     }
-    /* What it came to: copies planned, and of the restored ones how many the step routed. */
+    /* Summary: copies planned, and how many restored copies the step routed. */
     if (x.stream && rad_memcpy_async(x.stats_h, x.stats, sizeof(XpStats), x.stream) >= 0 &&
         rad_stream_sync(x.stream) >= 0 && x.stats_h->planned)
         RAD_INFO("rank %d: expert prefetch: %u copies planned, %u of %u looked back on routed (%.1f%%), %lld "
@@ -152,7 +149,7 @@ void Ctx::xp_close() {
     xp_.reset();
 }
 
-/* The host thread: each request's mailbox, once the plan has written it, to the DMA queue. */
+/* Host thread: hands each request's mailbox to the DMA queue once the plan has written it. */
 void Ctx::xp_serve(XpState& x) {
     for (;;) {
         XpReq r;
@@ -163,14 +160,14 @@ void Ctx::xp_serve(XpState& x) {
             r = x.q.front();
             x.q.pop_front();
         }
-        /* The marks of finished lists go back to the pool. */
+        /* Return the marks of finished lists to the pool. */
         const int64_t behind = rad_xp_behind(x.device);
         while (!x.marks.empty() && x.marks.front().second <= x.lists - behind) {
             rad_ride_release(x.marks.front().first, nullptr, 0);
             x.marks.pop_front();
         }
-        /* The mailbox reaches the request's number once the plan has run; a number past it means it
-         * was written over by a later request and this one is stale. */
+        /* The mailbox reaches the request number once the plan has run; a higher number means a
+         * later request overwrote it and this one is stale. */
         volatile XpBox* b = x.box + r.g;
         const auto t0 = std::chrono::steady_clock::now();
         bool got = true;
@@ -215,8 +212,8 @@ void Ctx::xp_serve(XpState& x) {
     }
 }
 
-/* The layer's map from expert to table entries, once all its tables are bound; false until then. An
- * expert whose weights are not each in exactly one table stays out of the map. */
+/* Builds the layer's expert -> table-entry map; false until all its tables are bound. An expert
+ * whose weights are not each in exactly one table is left out. */
 bool Ctx::xp_bind(XpLayer& L, int layer) {
     const RadPrefetchNext& nx = L.next;
     std::vector hm((size_t)kXpMaxNe * kXpParts, nullptr);
@@ -241,7 +238,7 @@ bool Ctx::xp_bind(XpLayer& L, int layer) {
     XpState& x = *xp_;
     void** map = x.maps + (size_t)layer * kXpMaxNe * kXpParts;
     int32_t* place = x.places + (size_t)layer * kXpMaxNe;
-    /* Once a layer, at its first issue: the one host wait here is not on the step path. */
+    /* Runs once per layer at first issue, so this host wait is off the step path. */
     if (rad_memcpy_async(map, hm.data(), (int64_t)hm.size() * (int64_t)sizeof(void*), stream_) < 0 ||
         rad_memcpy_async(place, hp.data(), (int64_t)hp.size() * 4, stream_) < 0 || rad_stream_sync(stream_) < 0)
         return false;
@@ -251,9 +248,9 @@ bool Ctx::xp_bind(XpLayer& L, int layer) {
     return true;
 }
 
-/* The counters the last judgement sent to the host are a window old: the share of copies used is
- * judged from them, then the next window's are sent. A window that follows a rest is not judged --
- * its counters left before the rest -- so a rest is followed by one full window measured afresh. */
+/* Judges the share of copies used from the counters sent to the host one window ago, then sends the
+ * next window's. The first window after a rest is not judged (its counters predate the rest), so
+ * each rest is followed by one full fresh window. */
 void Ctx::xp_judge(XpState& x) {
     if (x.have_snap) {
         const volatile XpStats* h = x.stats_h;
@@ -275,14 +272,12 @@ void Ctx::xp_judge(XpState& x) {
     if (rad_memcpy_async(x.stats_h, x.stats, sizeof(XpStats), x.stream) >= 0) x.have_snap = true;
 }
 
-/* A pass being recorded keeps each of the three calls as a step of its own, run again where the tape
- * plays it: what a call issues -- on its own stream, or a ride on the next played dispatch -- is
- * issued again at every play rather than recorded. */
+/* When recording, each of the three calls becomes its own tape step and is re-run at every play:
+ * its stream work and rides are issued afresh, not recorded. */
 int Ctx::xp_predict(const RadPrefetchNext* nx, rad_buf h, int64_t r0, int64_t rows, int64_t n_embd) {
-    /* A pass this wide predicts nothing, and its tape is better without a step that does nothing. */
+    /* Too wide to predict; keep the tape free of an empty step. */
     if (!xp_ || !nx || rows <= 0 || rows > kXpMaxRows) return RAD_OK;
     if (!rec_) return xp_predict_run(*nx, h, r0, rows, n_embd);
-    tape_cut();
     TapeXp p;
     p.next = *nx;
     p.h = h;
@@ -291,43 +286,26 @@ int Ctx::xp_predict(const RadPrefetchNext* nx, rad_buf h, int64_t r0, int64_t ro
     p.n_embd = n_embd;
     TapeStep st;
     st.kind = kTapeXp;
-    st.lane = (uint8_t)lane_;
     st.a = (int32_t)rec_->xp.size();
     rec_->xp.push_back(p);
-    rec_->steps.push_back(st);
-    tape_pause(true);
-    const int rc = xp_predict_run(*nx, h, r0, rows, n_embd);
-    tape_pause(false);
-    return rc;
+    return tape_host(st, [&] { return xp_predict_run(*nx, h, r0, rows, n_embd); });
 }
 
 int Ctx::xp_mark() {
     if (!xp_) return RAD_OK;
     if (!rec_) return xp_mark_run();
-    tape_cut();
     TapeStep st;
     st.kind = kTapeXpMark;
-    st.lane = (uint8_t)lane_;
-    rec_->steps.push_back(st);
-    tape_pause(true);
-    const int rc = xp_mark_run();
-    tape_pause(false);
-    return rc;
+    return tape_host(st, [&] { return xp_mark_run(); });
 }
 
 int Ctx::xp_step(int layer) {
     if (!xp_) return RAD_OK;
     if (!rec_) return xp_step_run(layer);
-    tape_cut();
     TapeStep st;
     st.kind = kTapeXpStep;
-    st.lane = (uint8_t)lane_;
     st.a = layer;
-    rec_->steps.push_back(st);
-    tape_pause(true);
-    const int rc = xp_step_run(layer);
-    tape_pause(false);
-    return rc;
+    return tape_host(st, [&] { return xp_step_run(layer); });
 }
 
 int Ctx::xp_predict_run(const RadPrefetchNext& nx, rad_buf h, int64_t r0, int64_t rows, int64_t n_embd) {
@@ -346,8 +324,8 @@ int Ctx::xp_predict_run(const RadPrefetchNext& nx, rad_buf h, int64_t r0, int64_
     const char* hb = (const char*)buf_ptr(h);
     if (!w || !hb) return RAD_OK;
     const RadStream cs = cur_stream();
-    /* A NEW PASS waits for the prefetch stream's work of the last one, so that stream is never a pass
-     * behind the compute stream: the records and mailboxes a request reuses are three layers old. */
+    /* A new pass waits for the prefetch stream's work from the last pass, so that stream is never a
+     * pass behind: the records and mailboxes a request reuses are three layers old. */
     if (layer <= x.last_layer) {
         if (x.tail_live) {
             RAD_TRY(rad_event_record(x.tail, x.stream));
@@ -358,8 +336,8 @@ int Ctx::xp_predict_run(const RadPrefetchNext& nx, rad_buf h, int64_t r0, int64_
     }
     x.last_layer = layer;
     if (x.passes < x.rest_until) return RAD_OK;
-    /* THE ROUTER INPUT IS READ IN PLACE, behind the next dispatch on the compute stream -- the router,
-     * which reads it -- by a ride rather than a barrier packet between two kernels. */
+    /* The router input is read in place, riding behind the next compute dispatch (the router, which
+     * reads it) rather than via a barrier packet between two kernels. */
     void* rt = nullptr;
     if (rad_ride(cs, &rt) == RAD_OK) {
         RAD_TRY(rad_ride_wait(x.stream, rt));
@@ -367,7 +345,7 @@ int Ctx::xp_predict_run(const RadPrefetchNext& nx, rad_buf h, int64_t r0, int64_
         RAD_TRY(rad_event_record(x.sync, cs));
         RAD_TRY(rad_event_wait(x.stream, x.sync));
     }
-    /* An earlier request still waiting for its mark goes now, unmarked. */
+    /* An earlier request still waiting for its mark is sent now, unmarked. */
     if (x.pend.valid) {
         {
             std::lock_guard lk(x.mu);
@@ -405,7 +383,7 @@ int Ctx::xp_predict_run(const RadPrefetchNext& nx, rad_buf h, int64_t r0, int64_
 int Ctx::xp_mark_run() {
     XpState& x = *xp_;
     if (!x.pend.valid) return RAD_OK;
-    /* Refused only while another ride waits on the stream: the list then starts without one. */
+    /* Refused only while another ride waits on the stream; the list then starts unmarked. */
     void* mark = nullptr;
     if (rad_ride(cur_stream(), &mark) == RAD_OK) {
         x.pend.mark = mark;
diff --git a/core/runtime/xprefetch.h b/core/runtime/xprefetch.h
index 3221a33d..91b459f5 100644
--- a/core/runtime/xprefetch.h
+++ b/core/runtime/xprefetch.h
@@ -1,31 +1,28 @@
-/* xprefetch.h -- the next-layer expert prefetch at decode: what the host half (xprefetch.cpp) and the
+/* xprefetch.h -- next-layer expert prefetch at decode: what the host half (xprefetch.cpp) and the
  * kernels (xprefetch.hip) share.
  *
- * WHAT IT DOES. Under expert-tiered placement a routed layer's GEMMs read the experts that are not on
- * the card from the pinned host pool, across the link, while they run. A layer's router input predicts
- * the NEXT routed layer's choice well: that layer's router applied to it ranks the experts the next
- * layer will route. So at each routed layer the prefetch applies the next layer's router to this
- * layer's router input, takes the likeliest experts that sit in the pinned pool, copies them onto the
- * card with the DMA engine while the rest of this layer runs, and points the next layer's weight tables
- * at the copies just before its GEMMs. The GEMMs then read those experts from the card.
+ * Under expert-tiered placement, a routed layer's GEMMs read off-card experts from the pinned host
+ * pool across the link. A layer's router input predicts the next routed layer's choice well, so at
+ * each routed layer the prefetch applies the next layer's router to this layer's router input,
+ * copies the likeliest pinned-pool experts onto the card with the DMA engine, and points the next
+ * layer's weight tables at the copies just before its GEMMs.
  *
- * NOTHING IT DOES CHANGES A RESULT. A copy holds the bytes of the pool slot it was made from, and an
- * entry is pointed at it only where it still names that slot (a compare-and-swap: a heat-engine move
- * since then wins) and only once the copy has landed. Late copies are not used; nothing waits for them.
+ * Results never change: a copy holds the bytes of the pool slot it came from, and an entry is
+ * redirected only where it still names that slot (compare-and-swap; a heat-engine move wins) and
+ * only once the copy has landed. Late copies go unused; nothing waits for them.
  *
- * THE PIECES, per routed layer l predicting layer l+1:
- *   - at l's router input (Ctx::xp_predict): on a stream of its own, behind the compute stream's
- *     dispatch that reads the input (a ride), xp_logits applies l+1's router to the input rows and
- *     xp_plan picks the copies and writes them to a mailbox in pinned host memory;
- *   - after l's routed down GEMM (Ctx::xp_mark): a ride on the compute stream that the DMA list polls,
- *     so the copies cross the link under l+1's attention rather than under l's own streamed experts;
- *   - a host thread hands each mailbox to the card's prefetch DMA queue: wait for the mark, copy, then
- *     write the request's number to the group's done word;
- *   - ahead of l+1's routed GEMMs (Ctx::xp_step, on the compute stream): xp_step puts the previous
- *     layer's entries back (its GEMMs are behind it in the stream) and points l+1's at the copies if
- *     the done word says they have landed.
- * The ring holds kXpGroups layers' copies, kXpSlots each; a group is copied into again three layers
- * later, after the step that put its entries back. */
+ * Pieces, per routed layer l predicting l+1:
+ *   - at l's router input (Ctx::xp_predict): on its own stream, riding behind the compute dispatch
+ *     that reads the input, xp_logits applies l+1's router and xp_plan writes the chosen copies to
+ *     a mailbox in pinned host memory;
+ *   - after l's routed down GEMM (Ctx::xp_mark): a ride on the compute stream that the DMA list
+ *     polls, so the copies cross the link under l+1's attention, not under l's streamed experts;
+ *   - a host thread hands each mailbox to the prefetch DMA queue: wait for the mark, copy, then
+ *     write the request number to the group's done word;
+ *   - before l+1's routed GEMMs (Ctx::xp_step, compute stream): restore the previous layer's
+ *     entries (its GEMMs are earlier in the stream) and redirect l+1's if the done word matches.
+ * The ring holds kXpGroups layers of kXpSlots copies; a group is reused three layers later, after
+ * the step that restored its entries. */
 #pragma once
 #include 
 
@@ -67,9 +64,9 @@ struct XpStats {
     unsigned int copied, routed, planned, pad;
 };
 
-/* What the prefetch takes on the card for a model of `layers` routed layers whose largest expert unit
- * is `unit` bytes: the ring and the buffers beside it (Ctx::xp_open allocates exactly these), in the
- * 2 MiB grains the card's allocations come in -- the ring its own, the small buffers sharing theirs. */
+/* Device bytes the prefetch takes for `layers` routed layers with largest expert unit `unit` bytes:
+ * the ring and its side buffers (exactly what Ctx::xp_open allocates), each rounded to the card's
+ * 2 MiB allocation grain. */
 inline int64_t xp_device_bytes(int64_t unit, int64_t layers) {
     constexpr int64_t kGrain = (int64_t)2 << 20;
     auto grains = [](int64_t b) { return (b + kGrain - 1) / kGrain * kGrain; };
diff --git a/core/runtime/xprefetch.hip b/core/runtime/xprefetch.hip
index 1d7c74b2..71ac30da 100644
--- a/core/runtime/xprefetch.hip
+++ b/core/runtime/xprefetch.hip
@@ -8,17 +8,15 @@ namespace {
 
 __device__ __forceinline__ float xp_bf(uint32_t x) { return __uint_as_float(x << 16); }
 
-/* logits[r, e] = h[r, :] . w[e, :], h and w bf16. A block takes 16 experts, two a 32-lane group. Every
- * lane issues all of its weight loads first -- n_embd / 256 sixteen-byte loads an expert, kept in
- * registers -- so the kernel waits on memory once rather than once a K chunk; the rows are staged in
- * LDS in as few chunks as 40 KiB allows (one at sixteen rows of 2560 needs two). fp32 accumulation.
- * Requires n_embd % 256 == 0 and n_embd <= 4096 (rad_xp_logits_launch checks). WIDE ON PURPOSE: the
- * router input is read in place and the block overwrites it once its GEMMs are done, so a narrower
- * grid that waits longer for CUs beside the compute stream reads it too late and predicts badly. */
+/* logits[r, e] = h[r, :] . w[e, :], bf16 in, fp32 accumulation. A block takes 16 experts, two per
+ * 32-lane group. Each lane issues all its weight loads first (n_embd / 256 16-byte loads per expert,
+ * held in registers) so the kernel waits on memory once; rows are staged in LDS in as few 40 KiB
+ * chunks as fit (16 rows of 2560 need two). Requires n_embd % 256 == 0 and n_embd <= 4096 (the
+ * launcher checks). The grid is wide on purpose: the router input is read in place and overwritten
+ * once the block's GEMMs finish, so a narrower grid waiting for CUs reads it too late. */
 constexpr uint32_t kLgE = 16, kLgJ = 16, kLgLds = 40u << 10;
-/* For gfx9-4-generic, one of rad_core's portable targets, LLVM leaves the row loop inside the
- * unrolled K loop a loop and warns once a copy; every other target unrolls it. The warning is
- * silenced for this kernel only, which changes no code. */
+/* On gfx9-4-generic LLVM does not unroll the row loop inside the unrolled K loop and warns per
+ * copy; other targets unroll it. Silenced for this kernel only. */
 #pragma clang diagnostic push
 #pragma clang diagnostic ignored "-Wpass-failed"
 __global__ __launch_bounds__(256) void xp_logits(const uint16_t* __restrict__ h,
@@ -80,7 +78,7 @@ __global__ __launch_bounds__(256) void xp_logits(const uint16_t* __restrict__ h,
 #pragma unroll
     for (int a = 0; a < 2; ++a) {
         const uint32_t e = e0 + (uint32_t)a;
-        /* No unroll pragma: the exit at `rows` keeps this a loop, and the compiler refuses one. */
+        /* No unroll pragma: the early exit at `rows` makes the compiler refuse it. */
         for (int r = 0; r < rad::kXpMaxRows; ++r) {
             if ((uint32_t)r >= rows) break;
             float v = acc[a][r];
@@ -91,11 +89,11 @@ __global__ __launch_bounds__(256) void xp_logits(const uint16_t* __restrict__ h,
 }
 #pragma clang diagnostic pop
 
-/* One block. Count what the group's previous records came to (whether the step routed them), take each
- * row's top-k with its softmax probability, keep the distinct experts whose entries all sit in one
- * pinned pool slot, score each by its highest probability -- half as much again where the previous
- * pass routed it at this layer -- and write the kXpSlots best into the ring's group as jobs, then the
- * mailbox's number. The previous records' entries are back already: xp_step puts them back. */
+/* One block. Counts whether the step routed the group's previous records, takes each row's top-k
+ * with softmax probabilities, keeps distinct experts whose entries all sit in one pinned pool slot,
+ * scores each by its highest probability (x1.5 if the previous pass routed it at this layer), and
+ * writes the kXpSlots best as jobs, then the mailbox number. xp_step has already restored the
+ * previous records' entries. */
 constexpr float kXpPrevBoost = 0.5f;
 __global__ __launch_bounds__(256) void xp_plan(const float* __restrict__ lg, uint32_t rows, uint32_t ne,
                                                uint32_t k, void** const* __restrict__ map,
@@ -176,8 +174,8 @@ __global__ __launch_bounds__(256) void xp_plan(const float* __restrict__ lg, uin
                 int pi = -1;
                 for (int i = 0; i < pools.n; ++i)
                     if (p >= pools.lo[i] && p < pools.hi[i]) { pi = i; break; }
-                /* Every entry of the unit in the same pool slot: the mover patches a layer's tables
-                 * one at a time, and a unit caught between two of its patches is left alone. */
+                /* All entries of the unit must sit in one pool slot: the mover patches tables one
+                 * at a time, so skip a unit caught between two of its patches. */
                 if (pi >= 0) {
                     const uint64_t lo = pools.lo[pi], st = pools.stride[pi];
                     const uint64_t base = lo + ((p - lo) / st) * st;
@@ -203,8 +201,7 @@ __global__ __launch_bounds__(256) void xp_plan(const float* __restrict__ lg, uin
                 if (u < o) first = false;
                 best = fmaxf(best, s_pr[u]);
             }
-        /* The previous pass routed it here: the counts row still holds that pass until this layer's
-         * router runs. */
+        /* The counts row holds the previous pass until this layer's router runs. */
         if (first && cnt && place && e >= 0 && (uint32_t)e < ne) {
             const int pl = place[e];
             if (pl >= 0 && cnt[pl] > 0) best *= 1.f + kXpPrevBoost;
@@ -231,9 +228,9 @@ __global__ __launch_bounds__(256) void xp_plan(const float* __restrict__ lg, uin
         const uint64_t base = lo + ((s_p[o] - lo) / st) * st;
         const uint64_t dst = ring + (uint64_t)j * rs;
         if (q == 0) {
-            /* System-scope stores write through to host memory themselves, so the tag needs only their
-             * completion, not a writeback of the whole L2 -- which would take the compute stream's dirty
-             * lines with it, every layer. */
+            /* System-scope stores write through to host memory, so the tag needs only their
+             * completion, not a full L2 writeback (which would flush the compute stream's dirty
+             * lines every layer). */
             __hip_atomic_store(&box->jobs[j].src, base, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
             __hip_atomic_store(&box->jobs[j].dst, dst, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
             __hip_atomic_store(&box->jobs[j].bytes, st, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
@@ -247,7 +244,7 @@ __global__ __launch_bounds__(256) void xp_plan(const float* __restrict__ lg, uin
             rec[j].oldv[q] = (void*)old;
             rec[j].newv[q] = (void*)(dst + (old - base));
         }
-        /* The tag after the job's own stores have completed: a tag the host sees vouches for them. */
+        /* Tag after the job's stores complete, so a visible tag implies a complete job. */
         if (q == 0) {
             __builtin_amdgcn_fence(__ATOMIC_RELEASE, "agent");
             __hip_atomic_store(&box->jobs[j].tag, (uint64_t)seq, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
@@ -263,10 +260,10 @@ __global__ __launch_bounds__(256) void xp_plan(const float* __restrict__ lg, uin
     }
 }
 
-/* On the compute stream ahead of a layer's routed GEMMs. The previous layer's patches go back -- its
- * GEMMs are behind this in the stream -- then this layer's units point at the ring, only where an entry
- * still holds what the plan read (a heat-engine move since wins) and only if the copies have landed:
- * the list's last write before its number puts the request's number in `done`. */
+/* Compute stream, before a layer's routed GEMMs. Restores the previous layer's patches (its GEMMs
+ * are earlier in the stream), then points this layer's units at the ring, only where an entry still
+ * holds what the plan read (a later heat-engine move wins) and only if `done` holds the request
+ * number, which the DMA list writes after its copies. */
 __global__ __launch_bounds__(128) void xp_step(const rad::XpRec* __restrict__ rrec, const int32_t* __restrict__ rn,
                                                const rad::XpRec* __restrict__ prec, const int32_t* __restrict__ pn,
                                                const uint32_t* done, uint32_t seq) {
diff --git a/core/sample/accept.cpp b/core/sample/accept.cpp
index b7294dab..ef78eb9b 100644
--- a/core/sample/accept.cpp
+++ b/core/sample/accept.cpp
@@ -1,11 +1,6 @@
-/* accept.cpp -- greedy and rejection-sampling acceptance for speculative decoding. See accept.h
- * for which rule is correct when, and for why `n_accepted` is a read offset and not a recompute.
+/* accept.cpp -- acceptance for speculative decoding. See accept.h for why the rule is exact.
  */
 #include "accept.h"
-#include "host_ref.h"
-
-#include 
-#include 
 
 namespace rad {
 
@@ -19,134 +14,11 @@ int accept_greedy(const int32_t* draft, int n_draft, const int32_t* target,
         if (draft[i] != target[i]) break;
         out[i] = draft[i];
     }
-    /* The bonus token. Whether every draft token was accepted or the run stopped at i, the
-     * target's own answer AT position i is correct to emit -- on a full run that is the free
-     * extra token speculation buys, and on a rejection it is the correction. One code path for
-     * both, which is what stops the bonus from being an off-by-one nobody notices until the
-     * acceptance rate looks a percent low. */
+    /* The target's token at position i is correct to emit either way: the bonus token on a full
+     * run, the correction on a rejection. */
     out[i] = target[i];
     *n_accepted = i;
     return RAD_OK;
 }
 
-/* Draw from a distribution given as a callable over token ids, walking in ASCENDING TOKEN ID.
- * Any fixed order samples correctly; a distribution over the whole vocabulary has no candidate
- * order to follow, and ascending id is the one that needs no sort to be a total order.
- *
- * Two passes over the vocabulary and NO intermediate array: the residual after a rejection would
- * otherwise be a 151K-float allocation on the step path, which the arena discipline (spec §3.1)
- * exists to forbid. Returns -1 if the total mass is zero. */
-template 
-static int32_t draw_from(Weight w, int64_t n, float u) {
-    double total = 0.0;
-    for (int64_t v = 0; v < n; ++v) {
-        const float x = w(v);
-        if (x > 0.0f) total += (double)x;
-    }
-    if (!(total > 0.0)) return -1;
-
-    const double want = (double)u * total;
-    double  acc  = 0.0;
-    int32_t last = -1;
-    for (int64_t v = 0; v < n; ++v) {
-        const float x = w(v);
-        if (!(x > 0.0f)) continue;
-        last = (int32_t)v;
-        acc += (double)x;
-        if (acc >= want) return (int32_t)v;
-    }
-    /* Float drift can leave the walk a hair short at the very top of the range; the last token
-     * with mass is the right answer there, not token 0. */
-    return last;
-}
-
-int accept_stochastic(const SpecAcceptParams& p, const int32_t* draft,
-                      const float* target_probs, const float* draft_probs,
-                      int32_t* out, int32_t* n_accepted) {
-    if (!target_probs || !out || !n_accepted) return RAD_E_INVAL;
-    if (p.n_draft < 0 || p.n_vocab <= 0) return RAD_E_INVAL;
-    if (p.n_draft > 0 && !draft) return RAD_E_INVAL;
-
-    const int64_t V = p.n_vocab;
-
-    for (int i = 0; i < p.n_draft; ++i) {
-        const int32_t x = draft[i];
-        if (x < 0 || x >= V) return RAD_E_INVAL;
-
-        const float* prow = target_probs + (int64_t)i * V;
-        const float  px   = prow[x];
-        /* A greedy drafter is a point mass: q(x) = 1, q(everything else) = 0. Passing null for
-         * `draft_probs` says so, and it is the case worth being fast at -- every MTP head that
-         * ships inside a target checkpoint drafts greedily. */
-        const float  qx   = draft_probs ? draft_probs[(int64_t)i * V + x] : 1.0f;
-
-        const float u = rng_uniform(p.seed, p.pos + (uint64_t)i, RAD_RNG_ACCEPT);
-        const bool  accept = !(qx > 0.0f) || (double)u < (double)px / (double)qx;
-
-        if (accept) { out[i] = x; continue; }
-
-        /* Rejected. The emitted token comes from the residual norm(max(0, p - q)); anything else
-         * -- re-sampling p, or emitting the target's argmax -- changes the distribution the
-         * scheme emits, which is the one property speculative decoding is supposed to preserve. */
-        const float* qrow = draft_probs ? draft_probs + (int64_t)i * V : nullptr;
-        auto resid = [&](int64_t v) -> float {
-            const float q = qrow ? qrow[v] : (v == x ? 1.0f : 0.0f);
-            const float r = prow[v] - q;
-            return r > 0.0f ? r : 0.0f;
-        };
-
-        const int32_t tok =
-            draw_from(resid, V, rng_uniform(p.seed, p.pos + (uint64_t)i, RAD_RNG_RESID));
-        if (tok < 0) {
-            /* The residual is empty: the target has no mass the drafter did not already claim,
-             * and the uniform landed on the acceptance boundary anyway. Accepting is the correct
-             * answer there -- the drafted token is in the target's support by construction -- so
-             * take it and carry on rather than emitting nothing. */
-            out[i] = x;
-            continue;
-        }
-        out[i] = tok;
-        *n_accepted = i;
-        return RAD_OK;
-    }
-
-    /* Every draft token accepted: the bonus position is an ordinary pick from the target's own
-     * distribution, drawn on the ORDINARY pick stream at its own output position, so it is the
-     * same token a non-speculative step would have produced there for this seed. */
-    const float* brow = target_probs + (int64_t)p.n_draft * V;
-    const int32_t bonus =
-        draw_from([&](int64_t v) { return brow[v]; }, V,
-                  rng_uniform(p.seed, p.pos + (uint64_t)p.n_draft, RAD_RNG_PICK));
-    if (bonus < 0) {
-        RAD_ERR("speculative accept: target distribution at the bonus position has no mass "
-                "(a grammar admitting nothing); the request cannot be continued");
-        return RAD_E_STATE;
-    }
-
-    out[p.n_draft] = bonus;
-    *n_accepted = p.n_draft;
-    return RAD_OK;
-}
-
-int accept_sequence(const SpecAcceptParams& p, const int32_t* draft,
-                    const int32_t* target_argmax,
-                    const float* target_probs, const float* draft_probs,
-                    int32_t* out, int32_t* n_accepted) {
-    if (p.greedy) {
-        if (!target_argmax) {
-            RAD_ERR("speculative accept: greedy acceptance was asked for without the target's "
-                    "argmax; a silent switch to rejection sampling would change the output "
-                    "distribution and nothing would say so");
-            return RAD_E_INVAL;
-        }
-        return accept_greedy(draft, p.n_draft, target_argmax, out, n_accepted);
-    }
-    if (!target_probs) {
-        RAD_ERR("speculative accept: rejection sampling was asked for without target "
-                "probabilities");
-        return RAD_E_INVAL;
-    }
-    return accept_stochastic(p, draft, target_probs, draft_probs, out, n_accepted);
-}
-
 }  /* namespace rad */
diff --git a/core/sample/accept.h b/core/sample/accept.h
index b22c824d..9272a6e2 100644
--- a/core/sample/accept.h
+++ b/core/sample/accept.h
@@ -1,49 +1,24 @@
-/* accept.h -- speculative acceptance. Verification is a declared op; ACCEPTANCE IS CORE SAMPLER
- * LOGIC (spec §10), which is why it lives here beside the chain that produced the distributions
- * it compares.
+/* accept.h -- speculative acceptance. Verification is a declared op; acceptance is core sampler
+ * logic (spec §10), so it lives beside the chain that produced the distributions it compares.
  *
- * Three rules, and the cheapest one is exact everywhere.
+ * Agreement with the target's own token. A drafted token is accepted when it equals the token the
+ * target produced at that position: the argmax at temperature 0, the target's sampled draw above
+ * it. Both are exact, provided each verified position draws from its own RNG coordinate
+ * (`p.pos = n_out + k` in sampler.cpp): the first emitted token is the target's draw whether the
+ * draft agreed or not, and every later position is conditioned on a prefix accepted only because
+ * it matched. Exact given the same logits; a verify step computes logits at a different M than a
+ * decode step, so text matches a non-speculative run exactly at temperature 0 and mostly above it
+ * (see Engine::collect_step). The cost is acceptance rate, P(y == x) instead of rejection
+ * sampling's min(1, p/q), and no probability planes are needed.
  *
- * AGREEMENT WITH THE TARGET'S OWN TOKEN -- what accept_greedy below actually implements, and what
- * this engine uses. A drafted token is accepted when it equals the token the target produced at
- * that position. At temperature 0 that token is the argmax, which is where the name came from.
- * ABOVE ZERO IT IS THE TARGET'S SAMPLED DRAW, AND ACCEPTING ON IT IS STILL EXACT -- provided each
- * verified position draws from its own RNG coordinate, which core/sample/sampler.cpp guarantees
- * (`p.pos = n_out + k`). Then the target's draw at position k is the one its own distribution
- * specifies there, the first emitted token is that draw whether the draft agreed or not, and every
- * later position is conditioned on a prefix accepted only because it matched. The emitted sequence
- * is a draw from the target, not an approximation of one.
+ * Accepting on argmax at a positive temperature is not exact: it replaces the target's
+ * distribution with its mode. Do not conflate it with the rule above.
  *
- * Exact given the same logits -- which is not the same as byte-identical to a non-speculative run,
- * because a verify step's logits are computed at a different M than a decode step's. The text
- * matches exactly at temperature 0 and mostly above it. See Engine::collect_step.
- *
- * What it costs is acceptance RATE: P(y == x) rather than the optimal min(1, p/q). What it costs
- * in machinery is nothing, which is why the engine computes no probability planes for it.
- *
- * ACCEPTING ON ARGMAX AT A POSITIVE TEMPERATURE is the rule that is NOT exact -- it replaces the
- * target's distribution with its mode. That is a different thing from the above, and the two are
- * easy to conflate.
- *
- * REJECTION SAMPLING. At temperature > 0 the drafted token x is accepted with probability
- * min(1, p(x)/q(x)) where p is the target's filtered distribution and q the drafter's. On
- * rejection the emitted token is drawn from the residual, norm(max(0, p - q)), which is what
- * makes the whole scheme emit exactly the target's distribution. With a GREEDY DRAFTER q is a
- * point mass, so the accept probability collapses to p(x) and the residual is p with x removed
- * and the rest renormalised -- which is the case the fast path is written for.
- *
- * Worth stating plainly because it looks like a regression and is not: acceptance FALLS relative
- * to greedy-against-greedy, because a proposal the target agrees with is still only accepted with
- * probability p(x) rather than always. That is the price of emitting the target's true
- * distribution.
- *
- * WHAT THE ANSWER IS FOR. `n_accepted` is consumed by two components that do different things
- * with it. The scheduler frees paged KV blocks past the accepted position -- a slot-table edit.
- * The linear-attention kernels do NOT recompute: the recurrent state and the conv window have
- * already absorbed the rejected tokens, and libr4d handles that by treating the conv state cache
- * as a rolling window of `conv_width-1 + n_spec` entries and READING AT THE SLOT THE LAST
- * ACCEPTED TOKEN LEFT. A rejection is a change of read offset, not a recompute, and `num_accepted`
- * is a required operand of `gdn_conv_update` and `gdn_recurrent_update` for exactly that reason
+ * Consumers of `n_accepted`: the scheduler frees paged KV blocks past the accepted position. The
+ * linear-attention kernels do not recompute: the recurrent state and conv window have absorbed the
+ * rejected tokens, and libr4d keeps the conv state as a rolling window of `conv_width-1 + n_spec`
+ * entries read at the slot the last accepted token left. A rejection is a read-offset change, which
+ * is why `num_accepted` is an operand of `gdn_conv_update` and `gdn_recurrent_update`
  * (docs/OPS.md, spec §10).
  */
 #pragma once
@@ -53,46 +28,27 @@
 
 namespace rad {
 
-struct SpecAcceptParams {
-    int      n_draft   = 0;      /* draft tokens proposed for this sequence */
-    int64_t  n_vocab   = 0;      /* row stride of the probability planes */
-    uint64_t seed      = 0;      /* the request's seed */
-    uint64_t pos       = 0;      /* output position of draft token 0 */
-    bool     greedy    = false;  /* temperature 0: argmax acceptance instead of rejection */
-};
-
-/* Acceptance by agreement, over precomputed target tokens. `target` is [n_draft+1] -- the token
- * the target model produced at each verified position, including the bonus position past the last
- * draft token, which is why the buffer is one longer than the draft. That token is the argmax at
- * temperature 0 and the target's own sampled draw above it; both are exact, for the reason at the
- * top of this file. The name describes the temperature-0 case; the rule is correct above it too.
+/* Acceptance by agreement over precomputed target tokens. `target` is [n_draft+1]: the token the
+ * target produced at each verified position plus the bonus position past the last draft token.
+ * It is the argmax at temperature 0 and the sampled draw above it; the name describes the
+ * temperature-0 case, but the rule is exact for both (see the file header).
  *
  * Writes n_accepted+1 tokens into `out` (capacity n_draft+1) and sets *n_accepted. Returns
- * RAD_OK. Always emits at least one token: the position after the last accepted one is the
- * target's own answer, which is always correct to emit. */
+ * RAD_OK. Always emits at least one token: the target's own token after the last accepted one. */
 int accept_greedy(const int32_t* draft, int n_draft, const int32_t* target,
                   int32_t* out, int32_t* n_accepted);
 
-/* Rejection sampling. `target_probs` is [(n_draft+1) * n_vocab], each row a NORMALISED
- * distribution as the sampler chain left it -- filtered, renormalised over the survivors, zero
- * elsewhere. `draft_probs` is [n_draft * n_vocab] on the same terms, or null for a greedy drafter
- * (a point mass on the drafted token), which is the common case and the cheap one.
- *
- * Writes n_accepted+1 tokens into `out` and sets *n_accepted. Returns RAD_OK, or RAD_E_INVAL on
- * a malformed argument. A target row that sums to zero -- everything masked out by a grammar --
- * is RAD_E_STATE: there is no token to emit and the request must fail rather than receive one. */
-int accept_stochastic(const SpecAcceptParams& p, const int32_t* draft,
-                      const float* target_probs, const float* draft_probs,
-                      int32_t* out, int32_t* n_accepted);
-
-/* The one a caller reaches for: dispatches on p.greedy. The greedy path needs `target_argmax`
- * (which the `sample_argmax` op already produced) and ignores the probability planes; the
- * stochastic path needs the planes and ignores the argmax. Passing the wrong one for the mode is
- * RAD_E_INVAL rather than a quiet fallback, because a verify step that silently switched
- * acceptance rules would change the output distribution and nothing would say so. */
-int accept_sequence(const SpecAcceptParams& p, const int32_t* draft,
-                    const int32_t* target_argmax,
-                    const float* target_probs, const float* draft_probs,
-                    int32_t* out, int32_t* n_accepted);
+/* Where a verify step's emission ends: at the first end-of-generation token among `out`'s
+ * n_accepted + 1 tokens (accept_greedy's output), which is emitted, or after all of them. Returns
+ * the number of accepted drafts to commit, at most `n_accepted`. A drafter that predicts the stop
+ * token agrees with the target, so without the cut the run would continue into the next turn.
+ * The card's acceptance (sched/advance_impl.h, ADV_ACCEPT) applies the same rule, and the engine
+ * refuses a step where the two disagree. */
+template 
+inline int32_t accept_cut_at_eog(const int32_t* out, int32_t n_accepted, IsEog&& is_eog) {
+    for (int32_t j = 0; j <= n_accepted; ++j)
+        if (is_eog(out[j])) return j;
+    return n_accepted;
+}
 
 }  /* namespace rad */
diff --git a/core/sample/gbnf.cpp b/core/sample/gbnf.cpp
index 93a3039a..455449d5 100644
--- a/core/sample/gbnf.cpp
+++ b/core/sample/gbnf.cpp
@@ -8,7 +8,6 @@
 #include 
 #include 
 #include 
-#include 
 #include 
 #include 
 #include 
@@ -138,14 +137,10 @@ PartialUtf8 decode_utf8(const std::string& src, PartialUtf8 partial_start,
 
 /* ================================================================== the per-vocabulary cache
  *
- * EVERYTHING GBNF DERIVES FROM A VOCABULARY, IN ONE OBJECT WHOSE LIFETIME IS THE VOCABULARY'S.
- * The vocabulary index (gbnf_mask.cpp) and the programs compiled against it are kept on the
- * VocabView itself rather than in a process-global table keyed on its POINTER. A pointer is not
- * an identity: a view destroyed and another constructed in the same storage answers to the same
- * key, and the second one is served the first one's work -- a mask over a vocabulary it is not
- * sampling from, which admits the wrong token set or none at all with nothing anywhere reporting
- * it. Hanging it off the view makes that unaskable, and it makes the program cap mean thirty-two
- * schemas PER VOCABULARY rather than thirty-two shared between every vocabulary a process holds.
+ * Everything GBNF derives from a vocabulary (the vocabulary index and the programs compiled
+ * against it) lives on the VocabView itself, with the vocabulary's lifetime. A global table keyed
+ * on the view's pointer would serve a stale index or program to a new view allocated at the same
+ * address, silently admitting the wrong token set. It also makes the program cap per vocabulary.
  */
 struct GbnfProgram;
 
@@ -154,13 +149,10 @@ struct VocabGbnf {
     std::shared_ptr index;
     double index_ms = 0.0;
 
-    /* One program per (text, root). The cache PINS the most recently used ones -- capped, because
-     * the key comes from client requests and a caller sending a thousand distinct schemas must
-     * not be able to grow it without bound -- and REMEMBERS every other one that is still alive.
-     * A program is kept alive by every request compiled against it (SamplingParams holds it from
-     * admission on), so a request is always served the program it was admitted with, however
-     * many other grammars were compiled in between, and the scheduler thread never recompiles
-     * one. */
+    /* One program per (text, root). The cache pins the most recently used ones (capped, since
+     * keys come from clients) and remembers every other one still alive. Each request holds its
+     * program from admission on (SamplingParams), so it always runs the program it was admitted
+     * with and the scheduler thread never recompiles. */
     struct Cached {
         std::shared_ptr pinned;
         std::weak_ptr   alive;
@@ -170,10 +162,8 @@ struct VocabGbnf {
     uint64_t clock = 0;
 };
 
-/* Created on first use under one process-wide lock; read under the cache's own. Two locks rather
- * than one because the outer one is taken once per grammar and the inner one is taken for the
- * duration of a vocabulary index build, which on a quarter-million-piece vocabulary is not
- * brief. */
+/* Created on first use under a process-wide lock; contents are guarded by the cache's own lock,
+ * which is held for a whole vocabulary index build (slow on a quarter-million-piece vocabulary). */
 static VocabGbnf& gbnf_cache_for(const VocabView* v) {
     static std::mutex m;
     std::lock_guard lk(m);
@@ -211,6 +201,20 @@ int gbnf_prepare_vocab(const VocabView* vocab, GbnfVocabInfo* info) {
 
 /* ================================================================== lexing helpers */
 
+/* Where a parse error is, for its message: the rest of the line, at most 40 bytes. Not the rest
+ * of the grammar, which can be megabytes for a generated one. The cut backs up to a character
+ * boundary: the message reaches a JSON error body, whose encoder refuses broken UTF-8. */
+static std::string where(const char* p) {
+    size_t n = 0;
+    while (p[n] && p[n] != '\n' && p[n] != '\r' && n < 40) ++n;
+    const bool cut = p[n] && p[n] != '\n' && p[n] != '\r';
+    if (cut)
+        while (n > 0 && ((unsigned char)p[n] & 0xC0u) == 0x80u) --n;
+    std::string s(p, n);
+    if (cut) s += "...";
+    return s;
+}
+
 static bool is_digit_char(char c) { return '0' <= c && c <= '9'; }
 static bool is_word_char(char c) {
     return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '-' || is_digit_char(c);
@@ -229,7 +233,7 @@ static std::pair parse_hex(const char* src, int size) {
         else break;
     }
     if (pos != end)
-        throw std::runtime_error("expecting " + std::to_string(size) + " hex chars at " + src);
+        throw std::runtime_error("expecting " + std::to_string(size) + " hex chars at " + where(src));
     return { value, pos };
 }
 
@@ -246,20 +250,20 @@ static const char* parse_space(const char* src, bool newline_ok) {
 static const char* parse_name(const char* src) {
     const char* pos = src;
     while (is_word_char(*pos)) pos++;
-    if (pos == src) throw std::runtime_error(std::string("expecting name at ") + src);
+    if (pos == src) throw std::runtime_error(std::string("expecting name at ") + where(src));
     return pos;
 }
 
 static const char* parse_int(const char* src) {
     const char* pos = src;
     while (is_digit_char(*pos)) pos++;
-    if (pos == src) throw std::runtime_error(std::string("expecting integer at ") + src);
+    if (pos == src) throw std::runtime_error(std::string("expecting integer at ") + where(src));
     return pos;
 }
 
-/* The repetition count written in [src, end), which parse_int has checked is digits. A count past
- * 2^64 - 2 is refused here; any smaller one is the compile budget's to judge, by what it expands
- * to (handle_repetitions). UINT64_MAX itself is reserved for "no maximum". */
+/* The repetition count in [src, end), already checked to be digits. A count past 2^64 - 2 is
+ * refused here (UINT64_MAX means "no maximum"); smaller ones are judged by the compile budget in
+ * handle_repetitions. */
 static uint64_t parse_count(const char* src, const char* end) {
     uint64_t v = 0;
     for (const char* p = src; p < end; ++p)
@@ -282,7 +286,7 @@ static std::pair parse_char(const char* src) {
             case '\\': case '"': case '[': case ']':
                 return { (uint32_t)(uint8_t)src[1], src + 2 };
             default:
-                throw std::runtime_error(std::string("unknown escape at ") + src);
+                throw std::runtime_error(std::string("unknown escape at ") + where(src));
         }
     } else if (*src) {
         return decode_utf8(src);
@@ -291,10 +295,10 @@ static std::pair parse_char(const char* src) {
 }
 
 /* `<[id]>` is a literal token id; `` resolves through the vocabulary and must tokenise to
- * exactly one token, because a rule element is one terminal. */
+ * exactly one token, since a rule element is one terminal. */
 static std::pair parse_token(const VocabView* vocab, const char* src) {
     const char* pos = src;
-    if (*pos != '<') throw std::runtime_error(std::string("expecting '<' at ") + pos);
+    if (*pos != '<') throw std::runtime_error(std::string("expecting '<' at ") + where(pos));
     pos++;
 
     if (*pos == '[') {
@@ -302,17 +306,17 @@ static std::pair parse_token(const VocabView* vocab, cons
         const char* int_end = parse_int(pos);
         const uint32_t id = (uint32_t)std::stoul(std::string(pos, (size_t)(int_end - pos)));
         pos = int_end;
-        if (*pos != ']') throw std::runtime_error(std::string("expecting ']' at ") + pos);
+        if (*pos != ']') throw std::runtime_error(std::string("expecting ']' at ") + where(pos));
         pos++;
-        if (*pos != '>') throw std::runtime_error(std::string("expecting '>' at ") + pos);
+        if (*pos != '>') throw std::runtime_error(std::string("expecting '>' at ") + where(pos));
         pos++;
         return { id, pos };
     }
 
-    if (!vocab) throw std::runtime_error(std::string("no vocabulary to parse token at ") + src);
+    if (!vocab) throw std::runtime_error(std::string("no vocabulary to parse token at ") + where(src));
 
     while (*pos != 0 && *pos != '>') pos++;
-    if (*pos != '>') throw std::runtime_error(std::string("expecting '>' at ") + pos);
+    if (*pos != '>') throw std::runtime_error(std::string("expecting '>' at ") + where(pos));
     pos++;
 
     std::vector toks;
@@ -324,11 +328,11 @@ static std::pair parse_token(const VocabView* vocab, cons
 
 /* ================================================================== the parser */
 
-/* What a symbol costs beyond its name: the map node that holds it and the rule slot it owns. */
+/* Bytes a symbol costs beyond its name: its map node and its rule slot. */
 static constexpr uint64_t kSymbolOverhead = 64 + sizeof(GbnfRule);
 
-/* Saturating: `bytes` may be a count from the grammar text times a size, and a sum that wrapped
- * would pass. budget_used_ never exceeds the budget, so the comparison cannot overflow. */
+/* Written as a subtraction so a huge `bytes` (a client count times a size) cannot wrap the sum;
+ * budget_used_ never exceeds the budget, so the subtraction cannot underflow. */
 void GbnfParser::charge(uint64_t bytes) {
     if (bytes > kMaxCompileBytes - budget_used_)
         throw std::runtime_error("the grammar expands past " +
@@ -344,8 +348,8 @@ uint32_t GbnfParser::get_symbol_id(const char* src, size_t len) {
     return r.first->second;
 }
 
-/* A generated name repeats its base, so a long rule name times many generated rules is an
- * amplification the text does not pay for; it is charged like any other. */
+/* A generated name repeats its base, so many generated rules under a long name amplify the text;
+ * charged accordingly. */
 uint32_t GbnfParser::generate_symbol_id(const std::string& base) {
     charge(base.size() + 12 + kSymbolOverhead);
     const uint32_t next_id = (uint32_t)symbol_ids_.size();
@@ -377,26 +381,23 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
     size_t last_sym_start = rule.size();
     const char* pos = src;
 
-    /* S{m,n} is rewritten into rules rather than counted at match time, which is what keeps the
-     * state machine a pushdown automaton with no counters in it:
+    /* S{m,n} is rewritten into rules rather than counted at match time, so the machine stays a
+     * pushdown automaton without counters:
      *   S{m,n} -> S S ... (m times) S'(n-m),  S'(x) ::= S S'(x-1) |
      *   S{m,}  -> S S ... (m times) S',       S'    ::= S S' |
      *   S*     -> S{0,}     S+ -> S{1,}       S? -> S{0,1}
      *
-     * WHAT BOUNDS THE EXPANSION IS ITS SIZE, charged to the compile budget before any of it is
-     * made, and not a count of repetitions. Upstream refuses any count past 2000, and a JSON
-     * schema's `maxLength: 8000` -- an ordinary bound on a tool's free-text argument -- failed
-     * every request carrying the tool. The expansion is linear in the count: each optional link
-     * is a rule of a few elements and a generated name, and nothing after the parse is worse than
-     * linear in the rules (find_left_recursion, and the mask plan, which gives every link past
-     * the longest token one class). So `[^"]{0,8000}` costs about a megabyte and compiles to the
-     * plan `[^"]{0,1999}` does, and a count the budget cannot hold is refused naming its rule. */
+     * The expansion is bounded by its size, charged to the compile budget before it is built, not
+     * by a repetition count (upstream's cap of 2000 rejects ordinary schemas such as
+     * `maxLength: 8000`). It is linear in the count, and nothing after the parse is worse than
+     * linear in the rules; the mask plan gives every link past the longest token one class. So
+     * `[^"]{0,8000}` costs about a megabyte and yields the same plan as `[^"]{0,1999}`. */
     auto handle_repetitions = [&](uint64_t min_times, uint64_t max_times) {
         const bool no_max = max_times == UINT64_MAX;
         if (last_sym_start == rule.size())
-            throw std::runtime_error(std::string("expecting preceding item to */+/?/{ at ") + pos);
+            throw std::runtime_error(std::string("expecting preceding item to */+/?/{ at ") + where(pos));
 
-        /* `n_opt` below is max - min, which a reversed range would wrap to about 1.8e19 rules. */
+        /* `n_opt` below is max - min, which a reversed range would wrap to ~1.8e19 rules. */
         if (!no_max && max_times < min_times)
             throw std::runtime_error("repetition {" + std::to_string(min_times) + "," +
                                      std::to_string(max_times) + "} has its minimum above its "
@@ -404,14 +405,12 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
 
         const GbnfRule prev_rule(rule.begin() + (std::ptrdiff_t)last_sym_start, rule.end());
 
-        /* A refusal names the repetition: the count is what a client wrote. */
+        /* A refusal names the repetition the client wrote. */
         try {
-            /* The copies about to be made: the operand once per required count beyond the
-             * first, and once more in each optional rule with its reference, ALT and END. The
-             * counts are the grammar's own, up to 2^64 - 2, so the arithmetic saturates where it
-             * would wrap: a count past the budget is refused here, before the loops below start.
-             * Each generated rule's name and slot are charged again as it is made
-             * (generate_symbol_id). */
+            /* Charge the copies up front: the operand once per required count beyond the first,
+             * and once per optional rule plus its reference, ALT and END. Counts reach 2^64 - 2,
+             * so overflow saturates and is refused before the loops run. Each generated rule's
+             * name and slot are charged again in generate_symbol_id. */
             {
                 const uint64_t w      = prev_rule.size();
                 const uint64_t n_rest = no_max ? 1 : max_times - min_times;
@@ -506,7 +505,7 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
             --depth_;
             last_sym_start = rule.size();
             rule.push_back({ GRE_RULE_REF, sub_rule_id });
-            if (*pos != ')') throw std::runtime_error(std::string("expecting ')' at ") + pos);
+            if (*pos != ')') throw std::runtime_error(std::string("expecting ')' at ") + where(pos));
             pos = parse_space(pos + 1, is_nested);
         } else if (*pos == '.') {                            /* any char */
             last_sym_start = rule.size();
@@ -524,7 +523,7 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
         } else if (*pos == '{') {
             pos = parse_space(pos + 1, is_nested);
             if (!is_digit_char(*pos))
-                throw std::runtime_error(std::string("expecting an int at ") + pos);
+                throw std::runtime_error(std::string("expecting an int at ") + where(pos));
             const char* int_end = parse_int(pos);
             const uint64_t min_times = parse_count(pos, int_end);
             pos = parse_space(int_end, is_nested);
@@ -540,10 +539,10 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
                     max_times = parse_count(pos, e);
                     pos = parse_space(e, is_nested);
                 }
-                if (*pos != '}') throw std::runtime_error(std::string("expecting '}' at ") + pos);
+                if (*pos != '}') throw std::runtime_error(std::string("expecting '}' at ") + where(pos));
                 pos = parse_space(pos + 1, is_nested);
             } else {
-                throw std::runtime_error(std::string("expecting ',' at ") + pos);
+                throw std::runtime_error(std::string("expecting ',' at ") + where(pos));
             }
             handle_repetitions(min_times, max_times);
         } else {
@@ -561,12 +560,11 @@ const char* GbnfParser::parse_rule(const char* src) {
     const std::string name(src, name_len);
 
     if (!(pos[0] == ':' && pos[1] == ':' && pos[2] == '='))
-        throw std::runtime_error(std::string("expecting ::= at ") + pos);
+        throw std::runtime_error(std::string("expecting ::= at ") + where(pos));
     pos = parse_space(pos + 3, true);
 
-    /* An error inside a rule names the rule. A grammar written from a JSON schema or a tool list
-     * names its rules after the tool and the property, so this is what tells a client which part
-     * of its request the grammar could not hold. */
+    /* An error inside a rule names the rule. Grammars generated from a schema or tool list name
+     * rules after the tool and property, so this points the client at the failing part. */
     try {
         pos = parse_alternates(pos, name, rule_id, false);
     } catch (const std::runtime_error& ex) {
@@ -575,7 +573,7 @@ const char* GbnfParser::parse_rule(const char* src) {
 
     if (*pos == '\r')      pos += pos[1] == '\n' ? 2 : 1;
     else if (*pos == '\n') pos++;
-    else if (*pos)         throw std::runtime_error(std::string("expecting newline or end at ") + pos);
+    else if (*pos)         throw std::runtime_error(std::string("expecting newline or end at ") + where(pos));
     return parse_space(pos, true);
 }
 
@@ -587,8 +585,7 @@ int GbnfParser::parse(const char* src, std::string* err) {
         const char* pos = parse_space(src, true);
         while (*pos) pos = parse_rule(pos);
 
-        /* Every referenced rule must exist. Upstream reports the missing NAME rather than the
-         * index, which is the difference between a diagnostic and a number. */
+        /* Every referenced rule must exist; report the missing rule by name, as upstream does. */
         for (const auto& rule : rules_) {
             if (rule.empty()) throw std::runtime_error("undefined rule");
             for (const auto& e : rule) {
@@ -601,8 +598,8 @@ int GbnfParser::parse(const char* src, std::string* err) {
             }
         }
     } catch (const std::exception& ex) {
-        /* The parser is recursive descent and throws, as upstream's does. Nothing escapes: a
-         * parse failure is a status and a message, because errors are values here. */
+        /* The parser throws internally, as upstream's does; a failure leaves as a status and
+         * message. */
         if (err) *err = ex.what();
         rules_.clear();
         return RAD_E_FORMAT;
@@ -614,8 +611,8 @@ int GbnfParser::parse(const char* src, std::string* err) {
 
 namespace gbnf {
 
-/* Every bound is an O(1) check on the path each stack already takes, and a grammar that reaches
- * one throws GbnfLimit (see "what a grammar may cost" in gbnf_internal.h). */
+/* Each bound is an O(1) check on the existing path; a grammar that reaches one throws GbnfLimit
+ * ("what a grammar may cost", gbnf_internal.h). */
 void advance_stack(const GbnfRuleSet& rules, const GbnfStack& stack, GbnfStacks& out,
                    SetBuild& build) {
     auto too_wide = [] {
@@ -663,9 +660,8 @@ void advance_stack(const GbnfRuleSet& rules, const GbnfStack& stack, GbnfStacks&
                 build.insert(out, std::move(curr));
                 break;
             default:
-                /* END, ALT, CHAR_ALT and CHAR_RNG_UPPER can never be the top of a stack. Reaching
-                 * one is a broken invariant in this file, not a runtime condition, so it aborts
-                 * rather than returning a status nobody could act on. */
+                /* END, ALT, CHAR_ALT and CHAR_RNG_UPPER are never a stack top; reaching one is a
+                 * broken invariant, so abort. */
                 fatal("gbnf: stack left on element type %d, which cannot be a stack top",
                       (int)pos->type);
         }
@@ -674,29 +670,24 @@ void advance_stack(const GbnfRuleSet& rules, const GbnfStack& stack, GbnfStacks&
 
 }  /* namespace gbnf */
 
-/* LEFT RECURSION MAKES advance_stack GROW A STACK FOREVER, so it is found up front rather than
- * run into. Returns the index of a rule on such a cycle, or -1.
+/* Left recursion makes advance_stack grow a stack forever, so it is detected up front. Returns
+ * the index of a rule on such a cycle, or -1.
  *
- * The epsilon closure expands the rule reference on top of a stack into the first element of
- * each alternative, and when that first element can match nothing it moves on to the second --
- * so a reference is in a rule's LEFT CORNER if everything before it in its alternative is
- * NULLABLE. Expanding a reference also pushes whatever follows it in the alternative, unless it
- * is the last element; so following a left-corner reference grows the stack by one exactly when
- * it is not in TAIL position. A cycle of left-corner references therefore grows the stack without
- * end iff one of its references is not in tail position. A cycle of tail references only revisits
- * stacks it has already seen, which the closure's `seen` set stops -- `S ::= ("a"?)*` is such a
- * cycle, and runs.
+ * A reference is in a rule's left corner if everything before it in its alternative is nullable.
+ * Expanding it also pushes what follows it, so it grows the stack exactly when it is not in tail
+ * position. A cycle of left-corner references therefore diverges iff one of its references is not
+ * in tail position; a cycle of tail references only revisits stacks the closure's `seen` set
+ * already stops (`S ::= ("a"?)*` runs).
  *
- * NULLABILITY IS A FIXED POINT, not a property of one rule read on its own: `e ::= f` is nullable
- * because `f ::= "b" |` is, and a check that only recognises an empty alternative misses
- * `root ::= e root "c" | "a"` and hangs on it. It is computed with a worklist, and the cycle
- * search is an iterative strongly-connected-components pass, so both are linear in the grammar
- * and neither recurses: a 100,000-rule chain is a 100,000-frame recursion otherwise. */
+ * Nullability is a fixed point (`e ::= f` is nullable because `f ::= "b" |` is; checking only for
+ * an empty alternative misses `root ::= e root "c" | "a"`). It uses a worklist and the cycle search
+ * an iterative SCC pass, so both are linear and non-recursive (a 100,000-rule chain would
+ * otherwise recurse 100,000 frames deep). */
 static int64_t find_left_recursion(const GbnfRules& rules) {
     const size_t n = rules.size();
 
-    /* 1. Which rules can match the empty string. An alternative with a terminal in it never can;
-     *    one made only of rule references can once each of them can, so it waits on a count. */
+    /* 1. Which rules can match the empty string. An alternative with a terminal never can; one of
+     *    only rule references can once all of them can, tracked by a pending count. */
     std::vector     nullable(n, 0);
     std::vector alt_owner, alt_pending, work;
     std::vector> waiting(n);     /* rule -> alternatives it holds up */
@@ -735,8 +726,8 @@ static int64_t find_left_recursion(const GbnfRules& rules) {
     }
     waiting = {};
 
-    /* 2. The left-corner graph, one edge per reference that can come first, marked by whether it
-     *    is in tail position. */
+    /* 2. The left-corner graph: one edge per reference that can come first, marked `grows` when
+     *    not in tail position. */
     struct Edge { uint32_t to; bool grows; };
     std::vector edge_off(n + 1, 0);
     std::vector   edges;
@@ -754,8 +745,8 @@ static int64_t find_left_recursion(const GbnfRules& rules) {
         edge_off[r + 1] = edges.size();
     }
 
-    /* 3. Strongly connected components (Tarjan's, with an explicit call stack). A growing edge
-     *    between two rules of one component -- a self-loop included -- is the cycle. */
+    /* 3. Strongly connected components (Tarjan's, explicit call stack). A growing edge within one
+     *    component, self-loops included, is the cycle. */
     std::vector  idx(n, -1), low(n, 0), comp(n, -1);
     std::vector     on_stack(n, 0);
     std::vector scc;
@@ -805,26 +796,17 @@ static int64_t find_left_recursion(const GbnfRules& rules) {
 
 /* ================================================================== the compiled program */
 
-/* THE COMPILED GRAMMAR IS NOT PER-REQUEST.
+/* The compiled program is shared, not per request. Its rules, initial stack set, mask plan and
+ * the mask of each reachable state are a pure function of (text, root, vocabulary). A
+ * GbnfGrammar per request holds only the position in it. Sharing means:
+ *   - repeated calls with the same grammar parse and plan it once;
+ *   - tensor-parallel ranks share one plan and mask cache, so every rank past the first hits;
+ *   - a state one request reached is never recomputed by a later one;
+ *   - the plan is built on the admitting thread, never the scheduler thread.
  *
- * Everything here is a pure function of (grammar text, root, vocabulary): the rules, the initial
- * stack set, the mask plan, and the token mask each reachable state admits. None of it depends on
- * which request is asking. A GbnfGrammar is created per request all the same, because the
- * POSITION in the program is per-request; what a grammar must NOT carry is a private copy of the
- * program, or an agent that calls the same tool twenty times parses the same grammar twenty times
- * and builds the same plan twenty times over.
- *
- * So the program is shared, and three things fall out of that beyond the obvious one: every
- * TENSOR-PARALLEL RANK shares one plan and one mask cache (the ranks hold separate grammars over
- * the same program and ask for the same full-vocabulary mask, so every rank past the first is a
- * hit); a state one request reached is a state no later request recomputes; and the plan -- the
- * expensive part, built once per grammar -- is built on the thread that ADMITS the first request
- * for it, which is never the scheduler thread.
- *
- * The stacks hold pointers into `rules`, so `rules` is immutable after publication and the
- * program is held by shared_ptr: a live grammar keeps its program alive even after the cache has
- * stopped pinning it, and those pointers are what makes a state comparable across requests at
- * all. */
+ * Stacks point into `rules`, so `rules` is immutable after publication and the program is held by
+ * shared_ptr: a live grammar keeps it alive after the cache unpins it. Those pointers are also
+ * what makes a state comparable across requests. */
 struct GbnfState {
     GbnfStacks  stacks;      /* sorted, so the key does not depend on the order a walk produced */
     PartialUtf8 partial;
@@ -838,10 +820,9 @@ struct GbnfState {
     }
 };
 
-/* A STATE AS fill_mask HOLDS IT, NOT COPIED: the stacks through pointers, in the order the key
- * sorts them into. It hashes and compares as the GbnfState it would become, so the cache is
- * probed without building a key -- a copy of every stack, per mask -- and one is built only for a
- * mask that is stored. */
+/* A state as fill_mask holds it, uncopied: the stacks through pointers, in the key's sorted
+ * order. It hashes and compares like the GbnfState it would become, so a probe copies no stacks;
+ * a key is built only to store a mask. */
 struct GbnfStateView {
     const std::vector* stacks;
     PartialUtf8                          partial;
@@ -911,25 +892,21 @@ struct GbnfProgram {
     gbnf::MaskPlanPtr  plan;                 /* see gbnf_mask.cpp */
     GbnfProgramInfo    info;
 
-    /* Masks computed rather than served from the memo below, for the sampler's instrument.
-     * Atomic because it is read and written off the lock; relaxed because it is a counter and
-     * nothing is ordered against it. */
+    /* Masks computed rather than served from the memo below (the sampler's instrument). Atomic
+     * because it is used outside the lock; relaxed because nothing is ordered against it. */
     mutable std::atomic   computed{0};
 
-    /* THE MASK CACHE IS SHARED BETWEEN THREADS: every rank reaches it. A mask is a few kilobytes,
-     * so entries are handed out by value under the lock and computed OUTSIDE it -- two threads
-     * racing the same state both compute it and agree, which wastes a plan lookup and cannot
-     * produce a wrong mask. It saves every rank past the first the plan work for a state, and a
-     * speculative window revisiting a state the work again. */
+    /* The mask cache is shared by every rank's thread. Masks are a few KiB, copied out under the
+     * lock and computed outside it; two threads racing on one state both compute the same mask,
+     * which only wastes work. */
     mutable std::mutex mu;
     struct Entry { std::vector mask; uint64_t used = 0; };
     mutable std::unordered_map masks;
     mutable uint64_t clock = 0;
 
-    /* A tool-calling schema's working set is on the order of a hundred states; 512 is room for a
-     * schema several times larger, at a few megabytes of host memory for a large vocabulary. Past
-     * it, evict the least recently used -- a linear scan, on a path that only runs behind a mask
-     * that was computed. */
+    /* A tool-calling schema's working set is about a hundred states; 512 leaves room for one
+     * several times larger, at a few MB of host memory for a large vocabulary. Past it, the least
+     * recently used entry is evicted by a linear scan, which runs only after a computed mask. */
     static constexpr size_t kMaxMasks = 512;
 
     bool lookup(const GbnfStateView& k, uint32_t* dst, int64_t n_words) const {
@@ -961,12 +938,12 @@ GbnfProgramInfo gbnf_program_info(const GbnfProgram& p) { return p.info; }
 
 namespace {
 
-/* Thirty-two schemas PINNED PER VOCABULARY. Capped because the key comes from client requests: a
- * caller sending a thousand distinct schemas must not be able to grow this without bound. */
+/* Programs pinned per vocabulary. Capped because keys come from clients, who must not be able to
+ * grow the cache without bound. */
 constexpr size_t kMaxPrograms = 32;
 
-/* Unpin the least recently used past either cap, and forget what nothing holds any more. The
- * caller holds C.mu. */
+/* Unpin least recently used programs past either cap, and forget those nothing holds. Caller
+ * holds C.mu. */
 void cache_trim(VocabGbnf& C) {
     for (;;) {
         size_t pinned = 0, bytes = 0;
@@ -986,8 +963,8 @@ void cache_trim(VocabGbnf& C) {
     }
 }
 
-/* The program for (text, root) if one is pinned or still alive, re-pinned as the most recently
- * used. The caller holds C.mu. */
+/* The program for (text, root) if pinned or still alive, re-pinned as most recently used. Caller
+ * holds C.mu. */
 std::shared_ptr cache_find(VocabGbnf& C,
                                               const std::pair& key) {
     auto it = C.programs.find(key);
@@ -1010,11 +987,8 @@ std::shared_ptr cache_find(VocabGbnf& C,
 static int program_for_impl(const std::string& text, const std::string& root,
                             const VocabView* vocab, std::shared_ptr* out,
                             std::string* err) {
-    /* KEYED ON (text, root) INSIDE THE VOCABULARY'S OWN CACHE, and not on (text, root, address)
-     * in a table outside it. A compiled program embeds the vocabulary index and a plan over it,
-     * so a table keyed on an address serves one vocabulary's whole compiled grammar to whichever
-     * later view lands in the same storage -- and the mask that comes out is over a vocabulary
-     * the request is not sampling from. */
+    /* Keyed on (text, root) inside the vocabulary's own cache; see "the per-vocabulary cache"
+     * for why not on the view's address. */
     VocabGbnf& C = gbnf_cache_for(vocab);
     const std::pair key{ text, root };
     {
@@ -1025,8 +999,8 @@ static int program_for_impl(const std::string& text, const std::string& root,
         }
     }
 
-    /* Compiled outside the lock: two callers racing the same new grammar would otherwise
-     * serialise behind the plan build. The loser's copy is dropped on insert. */
+    /* Compiled outside the lock so callers do not serialise behind a plan build. If two race on
+     * the same grammar, the loser's copy is dropped on insert. */
     const auto t0 = std::chrono::steady_clock::now();
     GbnfParser parser(vocab);
     std::string perr;
@@ -1062,8 +1036,8 @@ static int program_for_impl(const std::string& text, const std::string& root,
         return RAD_E_UNSUPPORTED;
     }
 
-    /* `rules` is final from here: the stacks hold pointers INTO it, so any later reallocation
-     * would dangle every one of them. Upstream makes the same point with a move. */
+    /* `rules` is final from here: stacks point into it, so a later reallocation would dangle
+     * them. */
     auto p = std::make_shared();
     for (const GbnfRule& r : parser.rules()) {
         p->rules.start.push_back((uint32_t)p->rules.elems.size());
@@ -1116,10 +1090,9 @@ static int program_for_impl(const std::string& text, const std::string& root,
     return RAD_OK;
 }
 
-/* NOTHING THROWN WHILE COMPILING LEAVES HERE. The parser catches its own errors, but the stack
- * machinery after it throws GbnfLimit on a grammar that outgrows its bounds, and any step can run
- * out of memory -- and this runs on the thread that admits the request, where an escaping
- * exception is std::terminate for every request on the server. */
+/* No exception escapes compiling. The stack machinery throws GbnfLimit and any step can throw
+ * bad_alloc; this runs on the admitting thread, where an escaping exception would terminate the
+ * server. */
 static int program_for(const std::string& text, const std::string& root, const VocabView* vocab,
                        std::shared_ptr* out, std::string* err) {
     try {
@@ -1150,10 +1123,15 @@ int GbnfGrammar::create(const std::string& text, const std::string& root, const
                         const std::vector& trigger_tokens,
                         std::unique_ptr* out, std::string* err) {
     if (!out) return RAD_E_INVAL;
+    /* A lazy grammar constrains nothing until a trigger fires, so without one it never would. */
+    if (lazy && trigger_words.empty() && trigger_tokens.empty()) {
+        if (err) *err = "a lazy grammar needs at least one word or token trigger; without one it "
+                        "never constrains";
+        return RAD_E_INVAL;
+    }
 
-    /* The parse, the left-recursion check and the initial stack set are all shared, and so is the
-     * mask cache behind them: this is a lookup on the second request that asks for the same
-     * schema. What stays per-request is the position in the program and the triggers. */
+    /* The compiled program is shared, so a repeated grammar is a cache lookup. Only the position
+     * in the program and the triggers are per request. */
     std::shared_ptr prog;
     const int st = program_for(text, root, vocab, &prog, err);
     if (st < 0) return st;
@@ -1205,10 +1183,9 @@ static void accept_chr(const GbnfRuleSet& rules, const GbnfStack& stack, uint32_
     advance_stack(rules, next, out, build);
 }
 
-/* A grammar that outgrew its bounds while accepting cannot be continued: the state it would be
- * in was never built. It is left with no live stack, so the next mask reports it and the request
- * is failed there, and the status says which of the two this was. A speculative walk rewinds
- * over it like any other refusal. */
+/* A grammar that outgrows its bounds while accepting cannot continue, since its next state was
+ * never built. It is left with no live stack, so the next mask fails the request; the status says
+ * which bound was hit. A speculative walk rewinds over it like any other refusal. */
 int GbnfGrammar::accept_token_piece(int32_t token, const std::string& piece) {
     try {
         return accept_token_piece_impl(token, piece);
@@ -1234,23 +1211,18 @@ int GbnfGrammar::accept_token_piece_impl(int32_t token, const std::string& piece
     GbnfStacks new_stacks;
     SetBuild   new_set(work);
 
-    /* THE STACKS THAT MATCH CODE POINTS ARE ADVANCED TOGETHER, one code point at a time, as
-     * accept_str does. Advancing each through the whole piece on its own gives the same set --
-     * the union of the parts is the part of the union -- but when many stacks converge on one
-     * continuation, as every alternative of a wide rule does once it matches, each of them
-     * re-expands that continuation, and the token costs the square of the width.
+    /* Code-point stacks advance together, one code point at a time, as in accept_str. Advancing
+     * each through the whole piece alone gives the same set, but stacks converging on one
+     * continuation (e.g. the alternatives of a wide rule) would each re-expand it, quadratic in
+     * the width.
      *
-     * AND THEY ARE ADVANCED THROUGH THE MASK PLAN'S AUTOMATON (plan_step), which holds each stack
-     * set as a state with its successors memoised per interval of code points. The set is the
-     * one accept_chr builds; what changes is that a state seen before -- the same free-text
-     * value, token after token -- is a lookup per code point rather than every closure rebuilt,
-     * allocated and de-duplicated again. The set comes back sorted, which nothing reads: the
-     * mask cache sorts its key, and a mask is a union over the stacks.
+     * They step through the mask plan's automaton (plan_step), which memoises each state's
+     * successors per code-point interval, so a seen state costs a lookup per code point instead
+     * of rebuilding closures. The result equals what accept_chr builds; its sorted order is
+     * incidental (the mask cache sorts its own key).
      *
-     * The new set is written over the one the previous token left (`spare_`) and the two are
-     * swapped, so a set of the same shape, token after token, allocates nothing; and when the
-     * automaton says the token left the set the state it was -- the steady state of a free-text
-     * value -- the set is not touched at all. */
+     * The new set overwrites the previous token's (`spare_`) and the two are swapped, so a
+     * steady-state set allocates nothing; when the state is unchanged the set is not touched. */
     current_.clear();
     for (const auto& stack : stacks_) {
         if (stack.empty()) continue;
@@ -1267,7 +1239,7 @@ int GbnfGrammar::accept_token_piece_impl(int32_t token, const std::string& piece
     }
     GbnfStacks& out = spare_;
     if (n_cps > 0 && !current_.empty()) {
-        /* `at_` names a state only when every stack steps over code points, so with it known no
+        /* `at_` names a state only when every stack steps over code points, so when it is known no
          * stack matched a token terminal above and the set is the stepped stacks alone. */
         gbnf::PlanState at{ at_.gen, at_.id };
         const bool same = gbnf::plan_step(*prog_->plan, current_, &at, cps_.data(), n_cps, &out,
@@ -1283,9 +1255,9 @@ int GbnfGrammar::accept_token_piece_impl(int32_t token, const std::string& piece
                                                                    current_[i]->end());
         at_ = At{};
     }
-    /* What a token terminal matched goes first, then the rest without the ones it already holds;
-     * with nothing matched by token, `out` is the set as it stands -- a state of the automaton,
-     * or a subset of the set before, and either way without duplicates. */
+    /* Stacks from token terminals go first, then the rest, de-duplicated against them. With no
+     * token match, `out` is already duplicate-free (an automaton state, or a subset of the
+     * previous set). */
     if (!new_stacks.empty()) {
         for (auto& s : out) new_set.insert(new_stacks, std::move(s));
         out.swap(new_stacks);
@@ -1295,18 +1267,10 @@ int GbnfGrammar::accept_token_piece_impl(int32_t token, const std::string& piece
     partial_utf8_ = partial;
 
     if (stacks_.empty()) {
-        /* NOT AN ERROR HERE, WHICH IS WHY IT LOGS AT DEBUG. This is reached as a matter of course
-         * by the SPECULATIVE WALK: Sampler::build_step advances the grammar over each PROPOSAL to
-         * mask the position behind it, and a drafter is free to propose a token the grammar
-         * forbids -- that is precisely what verification is for, and build_step handles it by
-         * setting `dead` and masking no further. A speculative window on a constrained request
-         * reaches this many times a second while behaving perfectly, producing correct, closed
-         * JSON and stopping cleanly. At error level it reads as a defect and is not one.
-         *
-         * A token that is genuinely EMITTED against the mask IS a defect, and only the engine can
-         * tell the two apart -- it alone knows the token was verified and is leaving. Engine::step
-         * checks this status on the post-verification accept and reports it there, which is why
-         * that status must not be dropped. */
+        /* Debug level: the speculative walk (Sampler::build_step) reaches this routinely when a
+         * drafter proposes a forbidden token, and handles it by setting `dead`. An emitted token
+         * that is forbidden is a defect, but only Engine::step can tell, so it reports this
+         * status on the post-verification accept; the status must not be dropped. */
         RAD_DEBUG("gbnf: token %d (\"%s\") left no live stack", token, piece.c_str());
         return RAD_E_STATE;
     }
@@ -1329,8 +1293,8 @@ int GbnfGrammar::accept_token(int32_t token) {
         recent_.push_back(Recent{ token, scan_.off });
         const uint64_t start = scanner_->feed(scan_, piece.data(), piece.size());
         if (start == WordScanner::npos) {
-            /* Keep only the tokens a word completing later could begin in: one that ends at or
-             * before (fed - longest + 1) cannot hold the first byte of any word still to come. */
+            /* Keep only tokens a later word could begin in: one ending at or before
+             * (fed - longest + 1) cannot hold the first byte of a word still to come. */
             const uint64_t reach = scanner_->max_len() - 1;
             const uint64_t keep  = scan_.off > reach ? scan_.off - reach : 0;
             size_t drop = 0;
@@ -1343,8 +1307,8 @@ int GbnfGrammar::accept_token(int32_t token) {
             return RAD_OK;
         }
 
-        /* Replay from the first byte of the word, splitting the token it begins inside: the bytes
-         * in front of it were free-form output and the grammar never claimed them. */
+        /* Replay from the word's first byte, splitting the token it begins in; the bytes before it
+         * are free-form output outside the grammar. */
         awaiting_trigger_ = false;
         std::vector replay;
         replay.swap(recent_);
@@ -1364,12 +1328,10 @@ int GbnfGrammar::accept_token(int32_t token) {
 
     if (vocab_->is_eog(token)) {
         if (complete()) return RAD_OK;
-        /* DEBUG FOR THE SAME REASON AS "left no live stack" in accept_token_piece. The mask admits
-         * an end-of-generation token only once a stack has completed, so an emitted one does not
-         * land here; what does is the speculative walk over a drafter's PROPOSAL, and a drafter
-         * proposes the end of the turn whenever the text looks finished -- often, on a reply that
-         * its token limit cuts off mid-structure. The emitted case is the defect, and
-         * Engine::step reports it from this status. */
+        /* Debug level, as for "left no live stack" in accept_token_piece. The mask admits EOG
+         * only once a stack has completed, so this is normally a drafter's proposal in the
+         * speculative walk; an emitted one is a defect that Engine::step reports from this
+         * status. */
         RAD_DEBUG("gbnf: end-of-generation token %d offered while no stack had completed", token);
         return RAD_E_STATE;
     }
@@ -1407,7 +1369,6 @@ int GbnfGrammar::accept_str(const std::string& piece) {
     return RAD_OK;
 }
 
-
 void GbnfGrammar::push_state() {
     saved_.push_back(Snapshot{ stacks_, partial_utf8_, awaiting_trigger_, scan_, recent_, at_ });
 }
@@ -1432,17 +1393,15 @@ int GbnfGrammar::rollback() {
 int GbnfGrammar::mask_compute(uint32_t* bitmask, int64_t n_words) const {
     std::fill(bitmask, bitmask + n_words, 0u);
 
-    /* A DEAD STACK SET ADMITS NOTHING. It is reachable: accept_token_piece assigns the empty set
-     * on the paths where it reports a failure, so anything that keeps asking for masks after that
-     * arrives here, and the answer is the status the state deserves -- not a mask. */
+    /* A dead (empty) stack set admits nothing. accept_token_piece leaves one after a failure, so
+     * a later mask request gets a status here, not a mask. */
     if (stacks_.empty()) {
         RAD_ERR("gbnf: the grammar has no live parse left; the request cannot be continued");
         return RAD_E_STATE;
     }
 
-    /* A mask that outgrows the bounds in "what a grammar may cost" throws from deep inside the
-     * stack machinery, and this is on the scheduler thread: it becomes a status that fails the
-     * request, never an exception that ends the process. */
+    /* On the scheduler thread, so a mask past the bounds in "what a grammar may cost" becomes a
+     * status that fails the request, never an escaping exception. */
     try {
         return gbnf::plan_fill(*prog_->plan, stacks_, partial_utf8_, complete(), bitmask, n_words);
     } catch (const GbnfLimit& e) {
@@ -1459,21 +1418,17 @@ int GbnfGrammar::fill_mask(uint32_t* bitmask, int64_t n_words) const {
     const int64_t n_tok = vocab_->n_tokens();
     if (n_words < bitmask_words(n_tok)) return RAD_E_SHAPE;
 
-    /* A lazy grammar that has not triggered constrains nothing, so every token is admissible and
-     * the sampler skips the mask op entirely for this sequence. Saying "all ones" rather than
-     * "no mask" keeps one code path in the driver. */
+    /* An untriggered lazy grammar admits every token. The sampler skips the mask op for it anyway;
+     * all ones keeps the driver to one code path. */
     if (awaiting_trigger_) {
         std::fill(bitmask, bitmask + n_words, 0xFFFFFFFFu);
         return RAD_OK;
     }
 
-    /* THE STATE CACHE, ahead of the plan. Keyed on everything fill_mask reads that can change --
-     * the stack set, the carried partial and allow_eog -- and hashed but then compared EXACTLY,
-     * because a collision accepted on the hash alone would hand back a mask for a state the
-     * sequence is not in and admit the wrong token set. The key sorts the stacks: two requests
-     * that reach the same state by the same path produce the same order anyway, but the sort is
-     * what makes that a guarantee rather than an observation. The probe sorts pointers to the
-     * stacks, in storage of the calling thread's own, and copies them only to store. */
+    /* The state cache, ahead of the plan. Keyed on everything fill_mask reads that can change
+     * (stack set, carried partial, allow_eog) and compared exactly after hashing, since a hash
+     * collision would return the wrong mask. Stacks are sorted so equal sets give equal keys. The
+     * probe sorts pointers in thread-local storage and copies stacks only to store. */
     thread_local std::vector sorted;
     sorted.clear();
     for (const GbnfStack& s : stacks_) sorted.push_back(&s);
@@ -1486,7 +1441,7 @@ int GbnfGrammar::fill_mask(uint32_t* bitmask, int64_t n_words) const {
     const int st = mask_compute(bitmask, n_words);
     if (st < 0) return st;
 
-    /* Store only a mask that stands: a dead state is not worth an entry and returns above. */
+    /* A failed state returned above and is not cached. */
     prog_->store(state_of(key), bitmask, n_words);
     return RAD_OK;
 }
diff --git a/core/sample/gbnf.h b/core/sample/gbnf.h
index daa25778..89b47b5d 100644
--- a/core/sample/gbnf.h
+++ b/core/sample/gbnf.h
@@ -1,69 +1,54 @@
 /* gbnf.h -- the GBNF grammar state machine.
  *
- * LIFTED from llama.cpp `src/llama-grammar.{h,cpp}` at upstream commit 06938ac12 (MIT). It lives
- * under core/sample/ rather than vendor/ because it is on the sampling path and the sampler owns
- * it; vendor/ belongs to the text frontend. It is vendor-SHAPED all the same: the algorithm is
- * upstream's, element for element, and the changes are listed here so a future re-lift knows what
- * to re-apply.
- *
- * What changed and why:
+ * Lifted from llama.cpp `src/llama-grammar.{h,cpp}` at upstream commit 06938ac12 (MIT). It lives
+ * in core/sample/ because the sampler owns it, but the algorithm is upstream's element for
+ * element. Changes, for a future re-lift:
  *   - `llama_vocab` became `VocabView` (vocab_view.h), so the sampler does not depend on the
- *     tokeniser's concrete type and a grammar test can state its vocabulary in four lines.
- *   - `GGML_ASSERT` / `GGML_ABORT` became this project's status returns and `fatal()`. Errors are
- *     values (docs/IMPLEMENTATION.md); upstream's aborts inside the stack walk stay aborts,
- *     because they are broken invariants rather than runtime conditions.
- *   - The parser still throws internally -- it is a recursive-descent parser and that is what
- *     upstream does -- but nothing escapes: `parse()` catches and returns a status with the
- *     message in an out-parameter.
+ *     tokeniser's concrete type and a test can state its vocabulary in a few lines.
+ *   - `GGML_ASSERT` / `GGML_ABORT` became status returns and `fatal()` (errors are values,
+ *     docs/IMPLEMENTATION.md). Aborts inside the stack walk stay aborts: they are broken
+ *     invariants, not runtime conditions.
+ *   - The recursive-descent parser still throws internally; `parse()` catches and returns a
+ *     status with the message in an out-parameter.
  *   - `llama_grammar_apply_impl`, which edited a candidate array in place, became `fill_mask`,
- *     which writes a token bitmask. That is the whole reason the state machine stays on host: at
- *     a 151K vocab the mask is 19 KiB, cheap enough to upload every step, where a candidate array
- *     is not (spec §13).
- *   - Everything a client's grammar can make the machine do is BOUNDED (gbnf_internal.h, "what a
- *     grammar may cost"): what a repetition expands to, how deep parentheses nest, how large a
- *     stack set grows, how much an epsilon closure explores, how much work one mask, one accepted
- *     token or one compile does, and how large the automaton and the mask plan grow. A grammar
- *     past a bound is refused at compile time or fails its request at run time; it never takes
- *     the process with it.
- *   - Left recursion is found with nullability computed as a fixed point and an iterative
- *     strongly-connected-components pass. Upstream's recursive check missed recursion through an
- *     indirectly nullable rule, and recursed once per rule of a chain.
- *   - A closure's explored stacks are shared by every closure that builds the same set, the
- *     stacks that match code points are advanced together rather than one at a time, and a
- *     large set is de-duplicated through an index. Each gives the same set as upstream; without
- *     them, stacks that converge on one continuation re-expand it once each.
- *   - Accepting a token steps the stacks that match code points through the mask plan's
- *     stack-set automaton (gbnf_mask.cpp, plan_step) rather than through a closure per stack per
- *     code point, and the grammar remembers which automaton state its stacks are. The set is the
- *     one upstream's accept builds; the test oracle keeps upstream's accept and every accepted
- *     token is held to it.
- *   - The token mask is not upstream's candidate walk. It is served from a plan precomputed when
- *     the grammar is compiled (gbnf_mask.cpp): per stack suffix, the tokens it admits whatever lies
- *     below it, and a small trie of what depends on what does. Upstream's walk survives only as
- *     the test oracle (tests/gbnf_oracle.cpp), and every mask is held to it bit for bit.
+ *     which writes a token bitmask: 19 KiB at a 151K vocab, cheap enough to upload every step
+ *     where a candidate array is not (spec §13).
+ *   - Everything a client grammar can make the machine do is bounded (gbnf_internal.h, "what a
+ *     grammar may cost"): repetition expansion, nesting depth, stack-set size, closure
+ *     exploration, work per mask, per accepted token and per compile, and automaton and plan
+ *     size. A grammar past a bound is refused at compile time or fails its request at run time;
+ *     it never takes the process down.
+ *   - Left recursion is found with nullability as a fixed point and an iterative SCC pass.
+ *     Upstream's recursive check missed recursion through an indirectly nullable rule and
+ *     recursed once per rule of a chain.
+ *   - A closure's explored stacks are shared by every closure that builds the same set, stacks
+ *     that match code points advance together, and a large set is de-duplicated through an
+ *     index. Each gives upstream's set; without them, stacks that converge on one continuation
+ *     re-expand it once each.
+ *   - Accepting a token steps the code-point stacks through the mask plan's stack-set automaton
+ *     (gbnf_mask.cpp, plan_step) instead of a closure per stack per code point, and the grammar
+ *     remembers which automaton state its stacks are. The set is the one upstream's accept
+ *     builds; the test oracle keeps upstream's accept and checks every accepted token against it.
+ *   - The token mask is served from a plan precomputed at compile time (gbnf_mask.cpp): per stack
+ *     suffix, the tokens it admits whatever lies below it, and a small trie of the tokens that
+ *     depend on what does. Upstream's candidate walk survives only as the test oracle
+ *     (tests/gbnf_oracle.cpp), and every mask is checked against it bit for bit.
  *
- * THE COST OF THE MASK IS ON THE STEP. The mask is built on the scheduler thread with the rank
- * threads parked at the barrier, so whatever it takes is added to the step time of a constrained
- * request -- up to four times a step under speculation. A mask that walks the vocabulary costs
- * more than the decode step it sits inside, and a constrained tool call then runs at many times the
- * per-token cost of the same model writing prose.
- *
- * What it costs as written:
- *
- *   - Compiling a grammar builds its mask plan, which walks the vocabulary once per place in the
- *     grammar a mask can start. That is milliseconds to a few hundred of them, bounded, and done on
- *     the thread that ADMITS the request (gbnf_compile), never on the scheduler thread.
+ * Cost. The mask is built on the scheduler thread with the rank threads parked at the barrier,
+ * so its cost adds to the step time of a constrained request, up to four times a step under
+ * speculation. A mask that walks the vocabulary costs more than the decode step it sits in.
+ *   - Compiling builds the mask plan, walking the vocabulary once per place in the grammar a mask
+ *     can start: milliseconds to a few hundred of them, bounded, on the thread that admits the
+ *     request (gbnf_compile), never on the scheduler thread.
  *   - A mask is then a key lookup per live stack, an OR of precomputed token sets, and a walk of
- *     the few tokens whose admissibility depends on the stack below the key -- the same cost for
- *     a state seen before and one never seen. A state seen before is also a memcpy from the
- *     program's mask cache, shared by every request and rank that uses the grammar.
- *   - The vocabulary index the plan is built over is computed once per vocabulary and shared.
- *     Nothing is per request and nothing is on the device.
+ *     the few tokens whose admissibility depends on the stack below the key, at the same cost for
+ *     a new state as for a seen one. A seen state is also a memcpy from the program's mask cache,
+ *     shared by every request and rank that uses the grammar.
+ *   - The vocabulary index is computed once per vocabulary and shared. Nothing is per request and
+ *     nothing is on the device.
  *
- * So the state machine stays on host: the cost that would argue for a device-side grammar is a
- * mask computed by walking the vocabulary per step, and the answer to that is to precompute the
- * walk (XGrammar's adaptive token-mask cache, carried over to this machine's stacks), not a
- * different place to run it (spec §13).
+ * So the state machine stays on host: the walk is precomputed (XGrammar's adaptive token-mask
+ * cache, adapted to this machine's stacks) rather than moved to the device (spec §13).
  */
 #pragma once
 #include "../rad_internal.h"
@@ -98,8 +83,8 @@ struct GbnfElement {
     uint32_t value;           /* code point, rule id, or token id */
 };
 
-/* A UTF-8 sequence split across token boundaries. Byte-level BPE emits partial sequences all the
- * time, so a grammar that could not carry one between tokens would reject perfectly good text. */
+/* A UTF-8 sequence split across token boundaries. Byte-level BPE emits these routinely, so the
+ * grammar carries one from token to token. */
 struct PartialUtf8 {
     uint32_t value    = 0;    /* bits so far, unshifted */
     int      n_remain = 0;    /* bytes still needed; -1 marks an invalid sequence */
@@ -110,16 +95,15 @@ using GbnfRules  = std::vector;
 using GbnfStack  = std::vector;
 using GbnfStacks = std::vector;
 
-/* THE COMPILED GRAMMAR, SHARED BY EVERY REQUEST THAT ASKS FOR IT, with its mask plan and its mask
- * cache. Defined in gbnf.cpp, which says what it is worth; the short version is that nothing
- * inside it is per-request. `GbnfState` is the mask cache's key: the whole of what fill_mask
- * reads. */
+/* The compiled grammar with its mask plan and mask cache, shared by every request that uses it;
+ * nothing in it is per-request (gbnf.cpp). `GbnfState` is the mask cache's key: everything
+ * fill_mask reads. */
 struct GbnfProgram;
 struct GbnfState;
 
 /* What compiling a grammar cost and what the compiled program holds. */
 struct GbnfProgramInfo {
-    double   compile_ms    = 0.0;   /* all of it: parse, checks and the mask plan */
+    double   compile_ms    = 0.0;   /* parse, checks and mask plan */
     double   plan_ms       = 0.0;   /* of which, the mask plan */
     uint64_t plan_work     = 0;     /* units the plan charged against its bound */
     size_t   rules         = 0;
@@ -150,15 +134,14 @@ public:
     const std::map& symbol_ids() const { return symbol_ids_; }
     const GbnfRules& rules() const { return rules_; }
 
-
 private:
     const VocabView*                vocab_ = nullptr;
     std::map symbol_ids_;
     GbnfRules                       rules_;
 
-    /* What the parse has built beyond the text itself, and how deep the parentheses are right
-     * now. Both are bounded (gbnf_internal.h, "what a grammar may cost"), because the text is
-     * client data and the parser runs on shared threads. */
+    /* Bytes built beyond the text itself, and the current parenthesis depth. Both are bounded
+     * (gbnf_internal.h, "what a grammar may cost") because the text is client data parsed on
+     * shared threads. */
     uint64_t budget_used_ = 0;
     uint32_t depth_       = 0;
     void     charge(uint64_t bytes);
@@ -178,61 +161,55 @@ private:
 
 class GbnfGrammar {
 public:
-    /* Build from grammar text. `root` names the start symbol. Returns RAD_OK, or RAD_E_FORMAT /
-     * RAD_E_NOTFOUND / RAD_E_UNSUPPORTED with the reason in *err -- left recursion is
-     * RAD_E_UNSUPPORTED, because it is a grammar this machine cannot run rather than one that is
-     * malformed, and the distinction is what the user needs to fix it.
+    /* Build from grammar text; `root` names the start symbol. Returns RAD_OK, or RAD_E_FORMAT /
+     * RAD_E_NOTFOUND / RAD_E_UNSUPPORTED with the reason in *err. Left recursion is
+     * RAD_E_UNSUPPORTED: the grammar is well-formed but this machine cannot run it.
      *
-     * A LAZY grammar constrains nothing until a trigger fires, which is how a tool-calling
-     * template stays free-form until the model starts writing a call. A trigger is a token id, or
-     * a literal word found in the generated bytes; parsing resumes from where the word begins. */
+     * A lazy grammar constrains nothing until a trigger fires, so a tool-calling template stays
+     * free-form until the model starts writing a call. A trigger is a token id or a literal word
+     * in the generated bytes; parsing resumes where the word begins. A lazy grammar with no
+     * trigger is RAD_E_INVAL, since it would never constrain. */
     static int create(const std::string& text, const std::string& root, const VocabView* vocab,
                       bool lazy,
                       const std::vector& trigger_words,
                       const std::vector& trigger_tokens,
                       std::unique_ptr* out, std::string* err);
 
-    /* Advance the state machine over one accepted token. Returns RAD_OK, or RAD_E_STATE if the
-     * token left no stack alive -- which means the sampler emitted a token the grammar forbade,
-     * a bug in the mask rather than in the request. RAD_E_FULL (or RAD_E_NOMEM) means the parse
-     * outgrew the bounds in gbnf_internal.h: the grammar is left dead, and the request cannot go
-     * on. */
+    /* Advance over one accepted token. RAD_E_STATE means the token left no stack alive: the
+     * sampler emitted a forbidden token, a mask bug rather than a bad request. RAD_E_FULL or
+     * RAD_E_NOMEM means the parse outgrew the bounds in gbnf_internal.h; the grammar is left dead
+     * and the request cannot continue. */
     int accept_token(int32_t token);
 
     /* Advance over a raw string, for replaying a prompt prefix into the grammar. */
     int accept_str(const std::string& piece);
 
-    /* Fill a token bitmask: bit set means admissible. `n_words` must be at least
-     * ceil(n_tokens/32). Returns RAD_OK, or RAD_E_STATE if the grammar admits no token at all,
-     * which is a dead grammar and must fail the request rather than produce a random token, or
-     * RAD_E_FULL / RAD_E_NOMEM if the mask outgrew its bounds, which must fail it the same way. */
+    /* Fill a token bitmask, bit set = admissible; `n_words` >= ceil(n_tokens/32). RAD_E_STATE if
+     * no token is admissible (a dead grammar), RAD_E_FULL / RAD_E_NOMEM if the mask outgrew its
+     * bounds. Each must fail the request rather than let a random token through. */
     int fill_mask(uint32_t* bitmask, int64_t n_words) const;
 
     /* Some stack has run to completion, so an end-of-generation token is admissible. */
     bool complete() const;
 
-    /* Masks this grammar's PROGRAM has had to compute rather than serve from its memo. Shared
-     * with every other request on the same program, which is the point: see grammar.h. */
+    /* Masks this grammar's program has computed rather than served from its memo. Shared with
+     * every request on the same program; see grammar.h. */
     uint64_t masks_walked() const;
 
     /* A lazy grammar that has not seen its trigger yet constrains nothing. */
     bool awaiting_trigger() const { return awaiting_trigger_; }
 
-    /* The state as it stands, read-only: what a mask is a function of. The test oracle computes
-     * the same mask from these by upstream's candidate walk. */
+    /* The current state, read-only: what a mask is a function of. The test oracle recomputes the
+     * mask from these with upstream's candidate walk. */
     const GbnfStacks&  stacks() const { return stacks_; }
     PartialUtf8        partial() const { return partial_utf8_; }
     const VocabView*   vocab() const { return vocab_; }
     const GbnfProgram& program() const { return *prog_; }
 
-    /* PUSH AND POP THE WHOLE MUTABLE STATE, so a speculative window can be walked forward and
-     * rewound (grammar.h says why). Everything create() fixes -- the rules, the vocabulary, the
-     * decoded vocabulary, the trigger words -- is absent from the snapshot by construction;
-     * what is here is exactly what accepting one token can change. The trigger fields are in it
-     * because a draft token may fire the trigger mid-window, which is a state change like any
-     * other and has to rewind with the rest.
-     *
-     * Nestable, though the sampler only ever needs one level. */
+    /* Push and pop the whole mutable state, so a speculative window can be walked forward and
+     * rewound (see grammar.h). What create() fixes (rules, vocabulary, trigger words) is not in the
+     * snapshot; what accepting a token can change is. That includes the trigger fields, since a
+     * draft token may fire the trigger mid-window. Nestable; the sampler uses one level. */
     void push_state();
     int  rollback();
 
@@ -244,11 +221,10 @@ private:
         uint64_t start;
     };
 
-    /* The state of the mask plan's automaton `stacks_` is exactly, when it is one: which
-     * automaton (`gen`) and which state in it, or an id of -1 when that is not known. It lets
-     * accepting skip canonicalising the set, and skip rewriting it when a token leaves it where
-     * it was. Everything that sets `stacks_` other than accepting through the automaton resets
-     * it, or restores it with the stacks it describes. */
+    /* The mask plan's automaton state that `stacks_` is, when known: the automaton (`gen`) and
+     * the state in it, or id -1. Lets accepting skip canonicalising the set, and skip rewriting
+     * it when a token leaves the state unchanged. Anything that sets `stacks_` other than an
+     * automaton step resets it, or restores it together with the stacks it describes. */
     struct At {
         uint64_t gen = 0;
         int32_t  id  = -1;
@@ -265,10 +241,10 @@ private:
 
     const VocabView* vocab_ = nullptr;
 
-    /* THE RULES ARE SHARED AND THE POSITION IN THEM IS NOT. `stacks_` holds pointers INTO
-     * prog_->rules, so the program has to outlive every grammar positioned in it and must never
-     * be mutated once published -- which is what the shared_ptr and the const are here to say,
-     * and also why the mask cache can be keyed on those pointers across requests at all. */
+    /* The rules are shared; the position in them is not. `stacks_` points into prog_->rules, so
+     * the program must outlive every grammar positioned in it and never change once published
+     * (hence shared_ptr to const). That is also what lets the mask cache key on those pointers
+     * across requests. */
     std::shared_ptr prog_;
     GbnfStacks       stacks_;
     PartialUtf8      partial_utf8_{};
@@ -276,15 +252,13 @@ private:
 
     std::vector   saved_;
 
-    /* The mask itself, from the program's plan, with no memo. */
+    /* The mask from the program's plan, bypassing the memo. */
     int mask_compute(uint32_t* bitmask, int64_t n_words) const;
 
-    /* THE TRIGGER, while the grammar is lazy and waiting. The words are scanned as the bytes
-     * arrive and nothing already scanned is kept except the few tokens a word could still be
-     * starting in -- at most the longest word's length of them -- which is also all a match
-     * replays. So waiting costs the same on the ten-thousandth token of a reply as on the first,
-     * and so does copying it into a snapshot. The scanner is fixed at create() and shared by
-     * every copy of the state. */
+    /* The trigger, while a lazy grammar waits. Words are scanned as bytes arrive; only the tokens
+     * a word could still be starting in are kept (at most the longest word's length of them),
+     * which is all a match replays. So waiting, and snapshotting it, cost the same on every token.
+     * The scanner is fixed at create() and shared by every copy of the state. */
     bool                                awaiting_trigger_ = false;
     std::vector                trigger_tokens_;
     std::shared_ptr  scanner_;
@@ -294,30 +268,29 @@ private:
     int accept_token_piece(int32_t token, const std::string& piece);
     int accept_token_piece_impl(int32_t token, const std::string& piece);
 
-    /* Scratch for accepting, kept so a token in the steady state of a value allocates nothing:
-     * the piece's code points, the stacks that step over them, and the set before the last one
-     * accepted, whose storage the next one is written into. None of it is state. */
+    /* Scratch for accepting, so a steady-state token allocates nothing: the piece's code points,
+     * the stacks that step over them, and the previous set, whose storage the next one reuses.
+     * None of it is state. */
     std::vector          cps_;
     std::vector  current_;
     GbnfStacks                     spare_;
 };
 
-/* COMPILE A GRAMMAR, on the calling thread, into the program every GbnfGrammar::create for the
- * same (text, root, vocabulary) will be served from while `out` -- or any other holder -- keeps it
- * alive. This is the whole of the host work a grammar costs before its first mask: the parse, the
- * checks and the mask plan. The server calls it on the thread that admits the request, so the
- * scheduler thread never compiles. Returns what GbnfGrammar::create returns. */
+/* Compile a grammar on the calling thread into the program every GbnfGrammar::create for the
+ * same (text, root, vocabulary) is served from while `out`, or any other holder, keeps it alive.
+ * This is all the host work before a grammar's first mask: parse, checks and mask plan. The
+ * server calls it on the admitting thread, so the scheduler thread never compiles. Returns what
+ * GbnfGrammar::create returns. */
 int gbnf_compile(const std::string& text, const std::string& root, const VocabView* vocab,
                  std::shared_ptr* out, std::string* err);
 
 GbnfProgramInfo gbnf_program_info(const GbnfProgram& p);
 
-/* Build the vocabulary index every grammar's plan is compiled against, if it is not built yet.
- * Worth calling once at startup: otherwise the first grammar to arrive pays for it. */
+/* Build the vocabulary index every grammar's plan is compiled against, if not built yet. Call
+ * once at startup, or the first grammar to arrive pays for it. */
 int gbnf_prepare_vocab(const VocabView* vocab, GbnfVocabInfo* info);
 
-/* Words a bitmask needs for this vocabulary. 19 KiB at 151K tokens, which is the number spec §13
- * quotes and the reason the state machine stays on host. */
+/* Words a bitmask needs for this vocabulary: 19 KiB at 151K tokens (spec §13). */
 inline int64_t bitmask_words(int64_t n_vocab) { return (n_vocab + 31) / 32; }
 
 }  /* namespace rad */
diff --git a/core/sample/gbnf_internal.h b/core/sample/gbnf_internal.h
index db6d95b1..f255bd84 100644
--- a/core/sample/gbnf_internal.h
+++ b/core/sample/gbnf_internal.h
@@ -1,17 +1,15 @@
-/* gbnf_internal.h -- what the GBNF state machine's three translation units share, and nothing
- * else includes.
+/* gbnf_internal.h -- shared by the GBNF state machine's three translation units only.
  *
  *   gbnf.cpp        the lifted machine: parser, stack machinery, accepting tokens, the compiled
  *                   program and its caches.
  *   gbnf_mask.cpp   the mask engine: the vocabulary index, the stack-set automaton and the
  *                   precomputed mask plan every fill_mask is served from.
  *   tests/gbnf_oracle.cpp
- *                   upstream's candidate walk, kept as the oracle the mask engine is tested
- *                   against and nowhere on a serving path.
+ *                   upstream's candidate walk, the test oracle for the mask engine; never on a
+ *                   serving path.
  *
- * The stack machinery lives here rather than in one of them because all three must run the SAME
- * closure and the same character tests: the oracle is a second implementation of the mask, not of
- * the parse, and a difference between the two has to mean a defect in the mask engine.
+ * The stack machinery is here so all three run the same closure and character tests: the oracle
+ * reimplements the mask, not the parse, so any disagreement is a mask-engine defect.
  */
 #pragma once
 #include "gbnf.h"
@@ -30,80 +28,70 @@ namespace gbnf {
 
 /* ============================================================ what a grammar may cost
 
- * THE GRAMMAR TEXT IS CLIENT DATA, AND IT IS COMPILED AND WALKED ON SHARED THREADS: the HTTP
- * thread that admits the request, and the scheduler thread every other request's tokens come
- * from. So nothing a grammar says may make either one use unbounded memory, time or stack -- a
- * few hundred bytes of text that exhausts the machine is a request that ends every other
- * request with it. Every bound below is one of those, and each is set well above what real
- * grammars reach: a JSON schema of 500 tool calls compiles to about 1.3 MB of text, 22,000 rules
- * and a few megabytes of compiled grammar, nests parentheses two deep, and never holds more than
- * about 1,500 stacks at once; a schema nested 128 objects deep holds stacks about 130 frames
- * tall.
+ * Grammar text is client data, compiled and walked on shared threads: the HTTP thread that
+ * admits the request and the scheduler thread that serves every request. So no grammar may make
+ * either use unbounded memory, time or stack. Each bound below is set well above real grammars:
+ * a JSON schema of 500 tool calls compiles to about 1.3 MB of text, 22,000 rules and a few MB of
+ * compiled grammar, nests parentheses two deep, and holds at most about 1,500 stacks at once; a
+ * schema nested 128 objects deep holds stacks about 130 frames tall.
  *
- * WHAT A GRAMMAR MAY COMPILE TO, BEYOND ITS OWN TEXT. The parse itself is linear in the text
- * except where a construct amplifies it: a repetition copies its operand once per count, and a
- * generated rule's name repeats the name of the rule it came from. Those are charged here, so a
- * 100 KB literal under `{1999}` is refused before it allocates the 1.6 GB it asks for, and what
- * a program in the cache can hold is bounded by its text plus this. */
+ * Bytes a grammar may compile to beyond its own text. The parse is linear in the text except
+ * where a construct amplifies it: a repetition copies its operand once per count, and a
+ * generated rule's name repeats its parent's name. Those are charged here, so a 100 KB literal
+ * under `{1999}` is refused before it allocates 1.6 GB, and a cached program is bounded by its
+ * text plus this. */
 inline constexpr uint64_t kMaxCompileBytes = 32ull << 20;
 
-/* How deeply parentheses may nest. The parser is recursive descent, a pair of frames per level,
- * so an unbounded depth is a stack overflow that 40 KB of '(' reaches. */
+/* Maximum parenthesis nesting. The recursive-descent parser uses two frames per level, so
+ * unbounded depth lets 40 KB of '(' overflow the stack. */
 inline constexpr uint32_t kMaxNesting = 256;
 
-/* One SET OF STACKS, which is the whole state of the pushdown automaton at a position: how many
- * distinct stacks it may hold, and how many elements across all of them. A grammar can make the
- * set grow without end -- ambiguity that forks a stack per token, or a closure whose paths
- * multiply -- and every accept, every mask and every cached state copies it. */
+/* Limits on one stack set (the automaton's whole state at a position): distinct stacks, and
+ * elements across all of them. Ambiguity or multiplying closure paths can grow the set without
+ * end, and every accept, mask and cached state copies it. */
 inline constexpr size_t kMaxStacks   = 1u << 14;
 inline constexpr size_t kMaxSetElems = 1u << 18;
 
-/* Stack elements one epsilon closure may push while exploring, and one set may hold as explored,
- * which bounds the memory a closure holds. A grammar with no left recursion still has closures
- * whose PATHS multiply (each level of `r ::= s "x" | s "y"` doubles them), so the set bound above
- * is reached only after the exploring has been done; this is what stops it. */
+/* Stack elements one epsilon closure may push while exploring, and one set may hold as explored.
+ * Without left recursion, closure paths can still multiply (each level of
+ * `r ::= s "x" | s "y"` doubles them), and the set bound above is only checked after exploring;
+ * this bound stops the exploring itself. */
 inline constexpr size_t kMaxClosureWork = 1u << 20;
 
-/* THE WORK ONE OPERATION MAY DO: one accepted token, one mask. The bounds above cap sizes, and
- * sizes do not cap time: a closure pays for every stack it builds, and a walk pays for every trie
- * node it visits. So the machinery counts what it does against one budget per operation, in units
- * of roughly a nanosecond of the thread it runs on: a stack element copied or a char-range element
- * tested is one; creating a stack -- an allocation and an insertion into the explored set -- costs
- * kStackCost more. A grammar that needs more than this at one position fails the request rather
- * than holding the scheduler thread for more than about half a second. */
+/* Work one operation (one accepted token, one mask) may do. Size bounds do not cap time, so work
+ * is counted per operation in units of roughly a nanosecond: one per stack element copied or
+ * char-range element tested, plus kStackCost per stack created (an allocation and an insertion
+ * into the explored set). Past the limit the request fails rather than hold the scheduler thread
+ * for more than about half a second. */
 inline constexpr uint64_t kStackCost = 64;
 inline constexpr uint64_t kMaxOpWork = 1ull << 29;
 
-/* THE WORK ONE COMPILE MAY DO, in the same units. Compiling precomputes the mask plan (see
- * gbnf_mask.cpp), which walks the vocabulary once for every place in the grammar where a mask can
- * start: on a quarter-million-piece vocabulary a tool-calling grammar needs a few tens of millions
- * of units, 200 tools about two hundred million, and a string bounded past the length of the
- * vocabulary's longest token -- the most a grammar can make the plan walk -- under two billion.
- * It runs on the thread that admits the request, never on the scheduler thread, and a grammar
- * that needs more than this is refused there, in a few seconds at most. */
+/* Work one compile may do, in the same units. The mask plan (gbnf_mask.cpp) walks the vocabulary
+ * once per place a mask can start. On a quarter-million-piece vocabulary a tool-calling grammar
+ * needs tens of millions of units, 200 tools about 200 million, and the worst case (a string
+ * bounded past the longest token's length) under two billion. Compiling runs on the admitting
+ * thread, never the scheduler thread; a grammar past this is refused within a few seconds. */
 inline constexpr uint64_t kMaxCompileWork = 1ull << 31;
 
-/* WHAT ONE COMPILED PLAN MAY HOLD: its precomputed masks and remainder tries. A plan is shared by
- * every request that uses the grammar and is kept for later ones, so this is what one grammar may
- * cost the process while it is cached. A 200-tool grammar holds about 16 MiB on a
- * quarter-million-piece vocabulary, and a string bounded past the longest token about 40. */
+/* Bytes one compiled plan may hold (precomputed masks and remainder tries), i.e. what one cached
+ * grammar may cost the process. On a quarter-million-piece vocabulary a 200-tool grammar holds
+ * about 16 MiB, and a string bounded past the longest token about 40 MiB. */
 inline constexpr size_t kMaxPlanBytes = 64ull << 20;
 
-/* What the programs a vocabulary's cache keeps PINNED may hold together, beside the count it pins.
- * A program some request still holds is kept whatever this says; one that nothing holds is what
- * this bounds. */
+/* Total bytes of the programs a vocabulary's cache pins, alongside its pin count. Bounds only
+ * programs no request holds; a held program is always kept. */
 inline constexpr size_t kMaxPinnedBytes = 256ull << 20;
 
-/* The stack-set automaton is a memo that grows as states are discovered, and a grammar whose
- * stacks deepen with every token discovers new states forever. Past the soft bound it is dropped
- * and rebuilt lazily at the next mask, which costs warm-up and nothing else; the hard bound is
- * what one operation may add before it is refused. */
+/* The stack-set automaton is a memo that grows as states are discovered, without end for a
+ * grammar whose stacks deepen every token. Past the soft bound it is dropped and rebuilt lazily
+ * at the next mask (costing only warm-up); the hard bound is what one operation may add before
+ * it is refused. */
 inline constexpr size_t kMaxDfaElems     = 1u << 22;
 inline constexpr size_t kMaxDfaWalkElems = 1u << 23;
 
-/* A bound above was reached. Thrown from inside the stack machinery, which has no status path
- * (it is lifted code, recursive in places), and caught at every public entry point, where it
- * becomes a status and the request is refused or failed -- never the process. */
+/* A bound above was reached. Thrown from the stack machinery, which is lifted, partly recursive
+ * code with no status path, and caught at every public entry point, where it becomes a status
+ * that refuses or fails the request. */
 struct GbnfLimit : std::runtime_error {
     using std::runtime_error::runtime_error;
 };
@@ -133,16 +121,14 @@ struct StackLess {
     }
 };
 
-/* ONE STACK SET WHILE IT IS BUILT, shared by every call that adds to that set: its running size,
- * which is what makes the set bounds exact rather than per call; the operation it is built for,
- * whose work every addition is charged to; and the stacks already explored for it.
+/* One stack set under construction, shared by every call that adds to it: its running size (so
+ * the set bounds apply to the whole set, not per call), the operation whose work each addition is
+ * charged to, and the stacks already explored.
  *
- * THE EXPLORED STACKS ARE THE SET'S, NOT ONE CLOSURE'S. Every stack a closure pops has had its
- * whole closure added to the set, so a later closure into the same set that reaches it has
- * nothing left to add there. Keeping `seen` per call instead re-derives it every time -- and when
- * many stacks converge on one continuation, as every alternative of a wide rule does once it
- * matches, that is one full re-expansion per stack, quadratic in a width the bounds allow. The
- * set that comes out, and the order it comes out in, are the same either way. */
+ * `seen` belongs to the set, not to one closure: a stack a closure has popped already has its
+ * whole closure in the set, so a later closure reaching it adds nothing. A per-call `seen` would
+ * re-expand a shared continuation once per converging stack (e.g. every alternative of a wide
+ * rule), quadratic in the width. The resulting set and its order are the same either way. */
 struct SetBuild {
     explicit SetBuild(OpWork& w) : work(w) {}
 
@@ -158,13 +144,10 @@ struct SetBuild {
         if (stacks > kMaxStacks || elems > kMaxSetElems) throw_set_limit();
     }
 
-    /* Append `s` to `out` -- the set this belongs to -- unless it is already there.
-     *
-     * A SET OF A FEW STACKS IS SEARCHED, A LARGE ONE IS INDEXED. The search is what the lifted
-     * code does and is the fastest thing at the sizes real states have; but many stacks that
-     * converge on one continuation each re-expand it into the same set, and a linear search per
-     * insertion makes that quadratic in a set size the bounds allow. Past kIndexFrom the set is
-     * indexed by hash, and the order stacks land in `out` is the same either way. */
+    /* Append `s` to `out` (this build's set) unless already present. Small sets use the lifted
+     * linear search, fastest at real state sizes; past kIndexFrom the set is indexed by hash,
+     * since converging stacks would make linear search quadratic. Insertion order is the same
+     * either way. */
     void insert(GbnfStacks& out, GbnfStack s);
 
 private:
@@ -221,8 +204,8 @@ inline std::pair match_char(const GbnfElement* pos, ui
     return { found == is_positive, pos };
 }
 
-/* True iff SOME completion of a partial UTF-8 sequence could satisfy the range at pos. This is
- * what lets a byte-level BPE token that ends mid-codepoint stay admissible. */
+/* True iff some completion of a partial UTF-8 sequence could satisfy the range at pos, so a
+ * byte-level BPE token ending mid-codepoint stays admissible. */
 inline bool match_partial_char(const GbnfElement* pos, PartialUtf8 partial) {
     const bool is_positive = pos->type == GRE_CHAR || pos->type == GRE_CHAR_ANY;
 
@@ -252,8 +235,8 @@ inline bool match_partial_char(const GbnfElement* pos, PartialUtf8 partial) {
     return !is_positive;
 }
 
-/* How many elements the char range at pos spans, which is what one match_char on it costs: it
- * walks the whole range whatever the code point. */
+/* Elements the char range at pos spans: the cost of one match_char, which walks the whole range
+ * whatever the code point. */
 inline size_t char_range_len(const GbnfElement* pos) {
     return (size_t)(match_char(pos, 0).second - pos);
 }
@@ -266,11 +249,9 @@ inline bool match_token(const GbnfElement* pos, int32_t token) {
 
 /* ============================================================ the compiled rules
 
- * EVERY RULE IN ONE ARENA, so an element's address is also its index. The stacks hold element
- * pointers, and the mask engine needs a fact about every element a stack names -- which class of
- * continuation it is (gbnf_mask.cpp) -- on every mask; with the rules held as separate vectors
- * that is a search per element, with one arena it is a subtraction. The arena is final once the
- * program is published: every stack points into it. */
+ * Every rule in one arena, so an element's address gives its index by subtraction. The mask
+ * engine looks up each stack element's continuation class (gbnf_mask.cpp) on every mask. The
+ * arena is final once the program is published, since every stack points into it. */
 struct GbnfRuleSet {
     std::vector elems;
     std::vector    start;     /* rule id -> index of its first element */
@@ -280,9 +261,9 @@ struct GbnfRuleSet {
     size_t   n_rules() const { return start.size(); }
 };
 
-/* Expand a stack into the N stacks that each end at a terminal. This is the pushdown automaton's
- * epsilon closure and it is where rule references are resolved. `build` is `out` while it is
- * built; see SetBuild. Throws GbnfLimit past the bounds above. */
+/* Expand a stack into the stacks that each end at a terminal: the epsilon closure, where rule
+ * references are resolved. `build` tracks `out` under construction (SetBuild). Throws GbnfLimit
+ * past the bounds above. */
 void advance_stack(const GbnfRuleSet& rules, const GbnfStack& stack, GbnfStacks& out,
                    SetBuild& build);
 
@@ -300,8 +281,7 @@ struct VocabIndex;
 std::shared_ptr vocab_index_build(const VocabView& v);
 size_t vocab_index_bytes(const VocabIndex& x);
 
-/* What compiling a grammar's mask plan cost and holds, for the log line and the acceptance
- * tool. */
+/* What building a mask plan cost and what it holds, for logging and the acceptance tool. */
 struct PlanStats {
     double   ms          = 0.0;   /* wall time of the plan build */
     uint64_t work        = 0;     /* units charged against kMaxCompileWork */
@@ -310,49 +290,46 @@ struct PlanStats {
     size_t   max_depth   = 0;     /* the deepest of them, in stack entries */
     size_t   dense       = 0;     /* of them, held as a full bitmask */
     size_t   rem_nodes   = 0;     /* nodes across every remainder trie */
-    size_t   max_rem     = 0;     /* the largest one remainder trie */
+    size_t   max_rem     = 0;     /* the largest remainder trie */
     size_t   bytes       = 0;     /* what the plan holds */
 };
 
-/* A grammar's compiled mask plan. Its runtime half -- an automaton over stack sets and the scratch
- * a mask needs -- is a memo guarded by the plan's own lock, so a plan is shared by every request
- * and every rank that uses the grammar. */
+/* A grammar's compiled mask plan. Its runtime part (the stack-set automaton and mask scratch) is
+ * a memo under the plan's own lock, so one plan serves every request and rank using the
+ * grammar. */
 struct MaskPlan;
 struct MaskPlanDeleter { void operator()(MaskPlan* p) const; };
 using MaskPlanPtr = std::unique_ptr;
 
-/* Build the plan for a grammar whose rules are final. Returns RAD_OK or RAD_E_UNSUPPORTED with
- * the reason in *err, naming the rule from `rule_names` (by rule id) where it can: a grammar whose
- * masks cannot be precomputed within the bounds above is refused here rather than served slowly
- * later. Throws GbnfLimit or std::bad_alloc, which the caller turns into a status. */
+/* Build the plan for a grammar whose rules are final. Returns RAD_OK, or RAD_E_UNSUPPORTED with
+ * the reason in *err (naming the rule from `rule_names`, by rule id, where possible) when the
+ * masks cannot be precomputed within the bounds above. Throws GbnfLimit or std::bad_alloc, which
+ * the caller turns into a status. */
 int plan_build(const GbnfRuleSet& rules, uint32_t root, const std::shared_ptr& vx,
                const std::vector* rule_names, MaskPlanPtr* out, PlanStats* stats,
                std::string* err);
 
-/* The mask for a stack set: bit set means admissible. `n_words` covers the vocabulary. Returns
- * RAD_OK, or RAD_E_STATE if no token at all is admissible; throws GbnfLimit past the per-operation
- * bounds. Thread-safe: it takes the plan's lock. */
+/* The mask for a stack set, bit set = admissible; `n_words` covers the vocabulary. Returns
+ * RAD_OK, or RAD_E_STATE if no token is admissible; throws GbnfLimit past the per-operation
+ * bounds. Thread-safe (takes the plan's lock). */
 int plan_fill(const MaskPlan& plan, const GbnfStacks& stacks, PartialUtf8 partial, bool allow_eog,
               uint32_t* bitmask, int64_t n_words);
 
-/* STEP A STACK SET OVER CODE POINTS through the plan's automaton: `out` is the set accepting
- * cps[0..n) one at a time leaves -- what accept_chr over every stack, code point by code point,
- * builds -- sorted, without duplicates, written over what `out` held so its capacity is reused.
- * `stacks` need not be sorted and must not point into `out`.
+/* Step a stack set over code points through the plan's automaton. `out` receives the set left by
+ * accepting cps[0..n) one at a time (what accept_chr over every stack builds), sorted and
+ * de-duplicated, overwriting `out` so its capacity is reused. `stacks` need not be sorted and
+ * must not point into `out`.
  *
- * `at` IS THE STATE THE CALLER'S SET IS, when it knows: on entry, a state an earlier step on this
- * plan returned, which spares canonicalising the set, or an id of -1; on return, the state
- * reached, or an id of -1 when that state holds an empty stack or a token terminal on top -- a
- * set the caller does not step whole, so not one it can name next time. Valid only while the
- * automaton that issued it lives; `gen` says which one that was. Returns true when the state
- * reached is the one `at` named on entry: the caller's set already is it, and `out` is left
- * alone. That is the steady state of a free-text value.
+ * `at` is the caller's automaton state, if known. On entry: a state an earlier step on this plan
+ * returned (skips canonicalising the set), or id -1. On return: the state reached, or id -1 when
+ * it holds an empty stack or a token terminal on top (a set the caller does not step whole). Valid
+ * only while the issuing automaton lives; `gen` identifies it. Returns true when the reached
+ * state equals the entry `at`; `out` is then left untouched (the steady state of a free-text
+ * value).
  *
- * The automaton memoises each state's successor per
- * interval of code points, so a state seen before costs a lookup per code point where the stack
- * machinery would rebuild every closure; inside a free-text value the state is the same one
- * token after token. Throws GbnfLimit past the per-operation bounds. Thread-safe: it takes the
- * plan's lock. */
+ * The automaton memoises each state's successor per code-point interval, so a seen state costs a
+ * lookup per code point instead of rebuilding closures. Throws GbnfLimit past the per-operation
+ * bounds. Thread-safe (takes the plan's lock). */
 struct PlanState {
     uint64_t gen = 0;
     int32_t  id  = -1;
diff --git a/core/sample/gbnf_mask.cpp b/core/sample/gbnf_mask.cpp
index 0cbd1c25..cc11e4d2 100644
--- a/core/sample/gbnf_mask.cpp
+++ b/core/sample/gbnf_mask.cpp
@@ -1,79 +1,56 @@
 /* gbnf_mask.cpp -- the token mask, precomputed per grammar so that no mask walks the vocabulary.
  *
- * THE COST OF A MASK IS ON THE STEP. fill_mask runs on the scheduler thread with the rank threads
- * parked at the barrier, so whatever it takes is added to the decode step of a constrained
- * request -- up to four times a step under speculation. A mask that descends the whole vocabulary
- * trie for a state it has not seen costs milliseconds on a quarter-million-piece vocabulary, and a
- * tool call reaches dozens of such states in its first steps. So nothing here descends the whole
- * vocabulary at run time: the grammar's compile does that, once per place a mask can start, and a
- * mask is assembled from the answers.
+ * A mask's cost adds to the decode step (gbnf.h, "Cost"). Descending the whole vocabulary trie for
+ * a new state costs milliseconds on a quarter-million-piece vocabulary, so only the compile does
+ * that, once per place a mask can start; a mask is assembled from the answers.
  *
- * WHAT A MASK IS MADE OF. The state is a set of stacks, and a token is admissible iff SOME stack
- * admits it, so the mask is the union of one mask per stack. A stack's mask depends on its whole
- * contents in principle and on very little of them in practice: a token of a dozen characters
- * either stays inside the few frames nearest the top -- a string's content and its closing
- * quote, a free-text parameter and its end tag -- or leaves them through a delimiter. So a stack
- * S is split into a KEY, the frames nearest its top, and the CONTEXT below them:
+ * Mask structure. A token is admissible iff some stack admits it, so the mask is the union of
+ * per-stack masks. A short token either stays within the few frames nearest the top (a string's
+ * content and closing quote, a free-text parameter and its end tag) or leaves them through a
+ * delimiter. So a stack S is split into a key (the frames nearest the top) and the context below:
  *
  *     S = context ++ key
  *     mask(S) = accepted(key)  U  { t : t leaves the key after a prefix u, and the rest of
  *                                       t is admitted by the context }
  *
- * accepted(key) does not depend on the context at all -- every path through the key's own frames
- * is a path through S -- so it is computed at compile time, by descending the vocabulary trie
- * with the key alone and an explicit bottom marker under it. What leaves the key is the
- * REMAINDER: for every token, the text after each point where it pops the key's last frame. Those
- * are kept as a small trie of their own, and at run time only that trie is walked, against the
- * real context. This is XGrammar's adaptive token mask cache (Dong et al., 2024) -- tokens split
- * into accepted, rejected and context-dependent per grammar position, with only the last checked
- * at run time -- carried over to a machine whose positions are stack SUFFIXES.
+ * accepted(key) is independent of the context, so it is computed at compile time by descending
+ * the vocabulary trie with the key over a bottom marker. The remainder (for every token, the text
+ * after each point where it pops the key's last frame) is kept as a small trie, and only that is
+ * walked at run time against the real context. This is XGrammar's adaptive token mask cache
+ * (Dong et al., 2024), with stack suffixes as positions.
  *
- * WHY SUFFIXES AND NOT SINGLE ELEMENTS. The parser rewrites `x*` into a rule of its own and a
- * group into another, so the element on top of a stack is usually the one character class of a
- * one-element rule: `[^"\\]` inside a JSON string is the whole of its rule, and every token longer
- * than one character leaves it. Keyed on the top element alone, nearly the whole vocabulary would
- * be context-dependent at the positions that matter most. Keyed on the top three frames -- the
- * class, the repetition that loops over it and the closing quote below that -- the only tokens that
- * leave are the ones that close the string and keep going, a few hundred of them. The depth is
- * ADAPTIVE: a key is extended one frame down, into every frame that can sit below it, for as long
- * as its remainder is too large to walk on the step, and not otherwise.
+ * Suffixes, not single elements. The parser gives `x*` and groups rules of their own, so a stack
+ * top is often a one-element rule such as `[^"\\]` in a JSON string, which every multi-character
+ * token leaves. Keyed on the top three frames (the class, its repetition, the closing quote) only
+ * the few hundred tokens that close the string leave. Depth is adaptive: a key is extended one
+ * frame down, into every frame that can sit below it, while its remainder is too large to walk.
  *
- * WHAT A KEY IS. Stack entries are element pointers, and two entries at different places in the
- * rules behave identically when what remains of their alternatives is the same sequence of
- * elements -- `"\n"` closes every parameter of every tool, and its entries differ only
- * by address. Entries are therefore replaced by their CLASS, the hash-consed remainder of their
- * alternative, and keys are sequences of classes. Rules are hash-consed the same way first, so a
- * clause a template writes once per tool is one clause; and a repetition longer than the longest
- * token is one class whatever its count, because no token can tell the difference. A grammar of
- * fifty free-text parameters has one free-text key, not fifty, and `x{0,1000}` costs what
- * `x{0,128}` does on a vocabulary whose longest token is 128 characters.
+ * Keys. Two stack entries behave identically when the rest of their alternatives is the same
+ * element sequence (`"\n"` closes every tool parameter). Entries are replaced by their
+ * class, the hash-consed remainder of their alternative, and keys are class sequences. Rules are
+ * hash-consed first, and a repetition longer than the longest token is one class whatever its
+ * count. So fifty free-text parameters share one key, and `x{0,1000}` costs what `x{0,128}` does
+ * when the longest token is 128 characters.
  *
- * WHAT A MASK THEN COSTS. For each stack: a lookup of its key, a few class comparisons deep; the
- * key's accepted set OR'ed in, which is a word-wise OR for a permissive key and a handful of bits
- * for a restrictive one; and, where the key has a remainder and the stack has a context, a walk of
- * the remainder trie from the context's state, which visits only the remainders the context keeps
- * alive. Nothing is proportional to the vocabulary except the OR, and nothing depends on whether
- * this state was seen before.
+ * Mask cost. Per stack: a key lookup a few classes deep; an OR of the key's accepted set (word-wise
+ * for a permissive key, a few bits for a restrictive one); and, if the key has a remainder and the
+ * stack a context, a remainder-trie walk visiting only what the context keeps alive. Only the OR
+ * scales with the vocabulary, and the cost is the same for new and seen states.
  *
- * A STATE CARRYING A SPLIT CHARACTER is the one exception to the plan, because what a token means
- * depends on the bytes carried in: only tokens that begin with the bytes that finish the
- * character are admissible at all. Those are a few hundred pieces in a byte-level vocabulary, kept
- * in a trie of their own per number of missing bytes, and walked with the full stack set.
+ * Split characters. A state carrying a partial UTF-8 character admits only tokens that begin with
+ * the missing bytes. Those few hundred pieces are kept in a trie per missing-byte count and walked
+ * with the full stack set.
  *
- * THE AUTOMATON. Every walk here steps a set of stacks over code points. The successor of a set
- * depends only on WHICH of its stacks match the code point, and a set's character classes cut the
- * code points into a few intervals on which that answer is constant; so each state carries its
- * interval boundaries and the successor per interval, built on first use. A trie node's children
- * are sorted by code point, so the walk takes a whole run of children per interval -- an interval
- * no stack matches is skipped with one binary search, which is what makes a restrictive state
- * cost nothing at the vocabulary's widest node.
+ * The automaton. A set's successor depends only on which of its stacks match the code point, and
+ * its character classes cut the code points into intervals where that is constant; each state
+ * stores its intervals and per-interval successor, built on first use. Trie children are sorted by
+ * code point, so a walk takes a run of children per interval and skips a non-matching interval
+ * with one binary search, making a restrictive state cheap even at the widest node.
  *
- * WHAT IS REFUSED. A grammar whose keys cannot be made small within kMaxKeyDepth frames -- one
- * where how much a token may take depends on how deep the parse is, without bound -- or whose
- * plan outgrows kMaxCompileWork, kMaxPlanBytes or the bound on one stack set, is refused when it
- * is compiled, naming the rule where it can: the alternative would be masks that are slow for as
- * long as the grammar is in use. What is refused is ambiguity and unbounded context, which the
- * grammars chat templates and the JSON-schema converter write do not have.
+ * Refusal. A grammar whose keys cannot be made small within kMaxKeyDepth frames (token reach
+ * depends on unbounded parse depth), or whose plan exceeds kMaxCompileWork, kMaxPlanBytes or the
+ * stack-set bound, is refused at compile time, naming the rule where possible, rather than served
+ * with slow masks. Grammars from chat templates and the JSON Schema converter are not affected.
  */
 #include "gbnf_internal.h"
 
@@ -92,22 +69,20 @@ namespace {
 constexpr uint32_t kNone    = 0xFFFFFFFFu;
 constexpr int32_t  kUnbuilt = -2;
 
-/* HOW LARGE A KEY'S REMAINDER MAY BE, which is what the run-time half of a mask may cost for one
- * key: a remainder trie is walked from the context's state, and in the worst case -- a context
- * that admits every remainder -- visits every node of it. Past either bound the key is extended
- * one frame down instead, where more of what leaves it is decided at compile time. */
+/* Maximum size of a key's remainder, which bounds a mask's run-time cost per key: the remainder
+ * trie walk visits every node in the worst case. Past either bound the key is extended one frame
+ * down, so more is decided at compile time. */
 constexpr size_t kMaxRemEntries = 1u << 13;
 constexpr size_t kMaxRemNodes   = 1u << 13;
 
-/* A walk whose remainder is already far past the bound is stopped where it is: the key will be
- * extended whatever the rest of the walk finds, and a key that leaves after its first character
- * would otherwise walk the whole vocabulary to learn that. Counted as tokens under the nodes where
- * the key has been left, so it is an overestimate and never stops a walk that could have fitted. */
+/* A walk whose remainder is already far past the bound stops early, since the key will be extended
+ * anyway (otherwise a key left after one character walks the whole vocabulary). Counted as tokens
+ * under nodes where the key was left, an overestimate, so it never stops a walk that would fit. */
 constexpr uint64_t kAbortRemTokens = 1u << 15;
 
-/* How many frames a key may span. Real grammars settle within three or four: a string inside its
- * repetition inside its quotes, a whitespace run inside its optional. A key still too permissive
- * this deep is a grammar whose masks depend on unbounded stack context, which is refused. */
+/* Maximum frames per key. Real grammars settle within three or four (a string in its repetition in
+ * its quotes; whitespace in its optional). A key still too permissive this deep means masks depend
+ * on unbounded stack context, and the grammar is refused. */
 constexpr uint16_t kMaxKeyDepth = 12;
 
 inline void set_bit(uint32_t* bits, int32_t id) {
@@ -127,26 +102,22 @@ double ms_since(std::chrono::steady_clock::time_point t0) {
 
 /* ============================================================ token tries
 
- * A trie over code-point sequences, one terminal per token. The vocabulary is one; each key's
- * remainder is another; the pieces that resume a split character are three more.
+ * A trie over code-point sequences, one terminal per token: one for the vocabulary, one per key
+ * remainder, and three for pieces that resume a split character.
  *
- * Nodes are in BREADTH-FIRST order, which buys two things: a node's children occupy a CONTIGUOUS
- * id range, so an edge scan is a sequential read and no child pointers are stored; and a whole
- * level is contiguous, so a walk -- which is also breadth-first -- reads the node array front to
- * back. ONE STRUCT PER NODE AND NOT FOUR ARRAYS, because a visit reads all four fields; and the
- * terminals are held in NODE ORDER, so a level's terminals are read in increasing order too. The
- * walk is bound on how it touches memory rather than on work per node, and a pointer-linked
- * layout is slower than the rescanning walk a trie exists to replace.
+ * Nodes are in breadth-first order, so a node's children are a contiguous id range (no child
+ * pointers) and a breadth-first walk reads the node array front to back. Fields are one struct
+ * per node since a visit reads all four, and terminals are in node order. The walk is
+ * memory-bound; a pointer-linked layout is slower than the rescanning walk the trie replaces.
  *
- * Beside the breadth-first layout, every node knows its subtree's range in LEXICOGRAPHIC order,
- * `lo..hi` into `lex`. A walk never reads it; the compile does, to list what is under a node where
- * a key has been left, and so does the one construct that admits a whole subtree at once -- a
- * token element (`<[id]>`, `!<[id]>`), which matches a token's id wherever it is reached. */
+ * Each node also records its subtree's range `lo..hi` in lexicographic order (`lex`). The walk
+ * never reads it; the compile uses it to list what lies under a node where a key was left, as
+ * do token elements (`<[id]>`, `!<[id]>`), which match a token's id wherever reached. */
 struct TrieNode {
-    uint32_t cp;        /* the code point on the edge INTO this node */
+    uint32_t cp;        /* the code point on the edge into this node */
     uint32_t first;     /* its first child's node id */
     uint32_t n_child;   /* how many children follow it */
-    uint32_t tbeg;      /* its first terminal slot; it ends at the NEXT node's tbeg */
+    uint32_t tbeg;      /* its first terminal slot; it ends at the next node's tbeg */
 };
 
 struct TokenTrie {
@@ -172,10 +143,9 @@ struct TrieEntry {
     int32_t     id;
 };
 
-/* LEXICOGRAPHIC ORDER IS WHAT MAKES A NODE A RANGE: two sequences share a d-code-point prefix iff
- * they are adjacent in this order and agree to depth d, so every node of the trie is a contiguous
- * slice of the sorted entries and the build never needs a per-node map. The sequences are
- * 0-terminated in the arena, which stops the comparison. */
+/* Sorted lexicographically, every trie node is a contiguous slice of the entries (sequences
+ * sharing a prefix are adjacent), so the build needs no per-node map. Sequences are 0-terminated
+ * in the arena, which stops the comparison. */
 static void trie_build(TokenTrie& t, const uint32_t* cps, std::vector& ents,
                        int32_t unique_over) {
     const uint32_t n = (uint32_t)ents.size();
@@ -198,10 +168,9 @@ static void trie_build(TokenTrie& t, const uint32_t* cps, std::vector
     t.hi.push_back(n);
     cur.push_back({ 0u, n });
 
-    /* Level d's nodes were appended in the order their ranges appear in `cur`, so node id
-     * `level_lo + i` is the node whose range is cur[i]. Children are appended in the same sweep,
-     * which keeps each node's children -- and the next whole level -- contiguous, and makes node
-     * ids increase with the order nodes are PROCESSED, which the terminal slots depend on. */
+    /* Node `level_lo + i` has range cur[i]. Children are appended in the same sweep, keeping each
+     * node's children and the next level contiguous, and making node ids follow processing order,
+     * which the terminal slots depend on. */
     uint32_t level_lo = 0;
     for (uint32_t d = 0; !cur.empty(); ++d) {
         nxt.clear();
@@ -251,26 +220,24 @@ struct VocabIndex {
     std::vector eog;          /* end-of-generation: admissible once a stack completes */
 
     /* Every piece decoded from a clean start, 0-terminated, in one arena that opens with a pad
-     * element. `off` is kNone for a token the walk never considers: end-of-generation, and a
-     * control token with no text, which can satisfy no character. */
+     * element. `off` is kNone for tokens the walk skips: end-of-generation, and control tokens
+     * with no text. */
     std::vector    cps;
     std::vector    off;
     std::vector tail;
     TokenTrie                trie;
 
-    /* Pieces that decode to no characters and carry nothing out: an overlong sequence for U+0000
-     * first, which ends a decoded sequence. Every live stack admits one -- a completed one too,
-     * which admits nothing else -- so a state with a completed stack admits these whatever its
-     * keys do. */
+    /* Pieces that decode to no characters and carry nothing out (e.g. an overlong U+0000 first,
+     * which ends a decoded sequence). Every live stack admits them, a completed one included, so
+     * a state with a completed stack admits these regardless of its keys. */
     std::vector     blank;
 
-    /* THE PIECES THAT RESUME A SPLIT CHARACTER, per number of bytes the carried character still
-     * needs. With r bytes missing, a piece is admissible only if its first r bytes are
-     * continuation bytes and the rest decodes on its own; its first code point is then the
-     * carried bits followed by those r bytes' bits, and everything after it is fixed. So each
-     * trie's root edges hold the r bytes' bits (plus one, since 0 ends a sequence) and the walk
-     * ORs the carried bits in. A piece of fewer than r continuation bytes and nothing else leaves
-     * the character still unfinished, and is admissible iff some stack could still take it. */
+    /* Pieces that resume a split character, indexed by bytes still missing (r). A piece is
+     * admissible only if its first r bytes are continuation bytes and the rest decodes alone; its
+     * first code point is the carried bits followed by those r bytes' bits. So root edges hold
+     * the r bytes' bits plus one (0 ends a sequence) and the walk ORs the carried bits in. A piece
+     * of fewer than r continuation bytes only (`shorts`) leaves the character unfinished and is
+     * admissible iff some stack could still take it. */
     struct Resume {
         std::vector cps;
         TokenTrie             trie;
@@ -315,10 +282,8 @@ std::shared_ptr vocab_index_build(const VocabView& v) {
         x->cps.insert(x->cps.end(), dec.first.begin(), dec.first.end());
         ents.push_back({ x->off[(size_t)id], dec.second, id });
 
-        /* Leading continuation bytes, and what they contribute to a character carried in. The
-         * decode reads the piece as a C string, as decode_utf8 does, so a NUL ends the piece: it
-         * stops the run like any other non-continuation byte, and a piece of continuation bytes
-         * and then a NUL is as short as the bytes before it. */
+        /* Leading continuation bytes and their bits. Like decode_utf8, the piece is read as a C
+         * string, so a NUL ends it: continuation bytes followed by a NUL count as a short piece. */
         const size_t len = ::strnlen(piece.c_str(), piece.size());
         size_t k = 0;
         uint32_t bits = 0;
@@ -331,8 +296,8 @@ std::shared_ptr vocab_index_build(const VocabView& v) {
         for (int r = 1; r <= 3; ++r) {
             VocabIndex::Resume& R = x->resume[r - 1];
             if ((int)k == r && !more_cont) {
-                /* Finishes the character with exactly its first r bytes; the rest decodes from a
-                 * clean start, and an invalid rest takes the whole piece with it. */
+                /* Finishes the character with exactly r bytes; the rest decodes from a clean
+                 * start, and an invalid rest disqualifies the piece. */
                 const auto rest = decode_utf8(piece.substr((size_t)r), PartialUtf8{});
                 if (rest.second.n_remain < 0) continue;
                 const uint32_t o = (uint32_t)R.cps.size();
@@ -361,22 +326,20 @@ std::shared_ptr vocab_index_build(const VocabView& v) {
 
 /* ============================================================ the stack-set automaton
 
- * A set of stacks is one state of the pushdown automaton's subset construction: walking the set
- * forward is the same answer as walking every stack and OR-ing, because admissibility is the
- * existence of a path, and the union of successors is exactly the set of stacks some path reaches.
- * States are interned by value, so a set reached twice is one state.
+ * A stack set is one state of the subset construction: walking the set gives the same answer as
+ * walking each stack and OR-ing, since admissibility is the existence of a path. States are
+ * interned by value, so a set reached twice is one state.
  *
- * THE SUCCESSOR OF A STACK DOES NOT DEPEND ON THE CODE POINT. Stepping a char-range top pops the
- * range and pushes what follows it, which `match_char(top, 0).second` finds whatever the code
- * point; the code point decides only WHETHER the stack steps. So each stack's successor is a
- * closure computed once per state, and a state's transition depends only on which stacks fire.
- * The character classes of a state's tops cut the code points into intervals over which that
- * answer is constant, and the successor is kept per interval. A state holds:
+ * A stack's successor does not depend on the code point: stepping a char-range top pops it and
+ * pushes what follows (`match_char(top, 0).second`); the code point only decides whether the
+ * stack steps. So each stack's successor closure is computed once per state, and a transition
+ * depends only on which stacks fire, which is constant over the intervals the tops' character
+ * classes cut. The successor is kept per interval. A state holds:
  *
  *   ctop     the char-range tops, which step over code points and test a carried partial;
  *   ttop     the token tops (`<[id]>`, `!<[id]>`), which match a token's id wherever reached;
- *   has_empty whether the set holds the empty stack: a completed parse, or -- in a key's walk --
- *            the bottom marker, meaning the key has been left.
+ *   has_empty whether the set holds the empty stack: a completed parse, or in a key's walk the
+ *            bottom marker, meaning the key has been left.
  *
  * States live in a deque, so a reference to one survives interning another. */
 class SetDfa {
@@ -399,21 +362,19 @@ public:
 
     explicit SetDfa(const GbnfRuleSet* rules) : rules_(rules) {}
 
-    /* The operation whose work every step is charged to, and the mark its growth is measured
-     * from. */
+    /* Set the operation every step is charged to, and the mark its growth is measured from. */
     void begin(OpWork* w) { work_ = w; walk_base_ = elems_; }
 
     size_t elems() const { return elems_; }
     size_t n_states() const { return st_.size(); }
     const St& st(int32_t sid) const { return st_[(size_t)sid]; }
 
-    /* Canonicalise a stack set and return its state, or -1 for the empty set -- the dead state,
-     * represented by absence so a caller can prune on the sign alone. */
+    /* Canonicalise a stack set and return its state, or -1 for the empty (dead) set, so callers
+     * can prune on the sign. */
     int32_t intern(GbnfStacks s) {
         if (s.empty()) return -1;
-        /* WHAT A SORT COSTS, which is not its length: n log n comparisons of stacks, each as long
-         * as the stacks' common prefix. Charged as every element once per level of the sort, so
-         * a set too wide to sort within the bound is refused rather than sorted anyway. */
+        /* A sort is n log n stack comparisons, each as long as the common prefix; charged as every
+         * element once per sort level, so a set too wide to sort within the bound is refused. */
         size_t elems = 0;
         for (const GbnfStack& k : s) elems += k.size() + 1;
         work_->add(elems * (1 + (uint64_t)std::bit_width(s.size())));
@@ -430,8 +391,8 @@ public:
         return intern_ptrs(ps, &s);
     }
 
-    /* The same, from pointers to the stacks. They are copied only if the set is a new state --
-     * moved out of `owned` when the caller holds them in a vector of its own. */
+    /* The same, from pointers to the stacks. They are copied only for a new state, or moved out
+     * of `owned` when the caller passes its own vector. */
     int32_t intern_ptrs(const std::vector& ps, GbnfStacks* owned = nullptr) {
         if (ps.empty()) return -1;
         uint64_t h = 1469598103934665603ull;
@@ -486,9 +447,9 @@ public:
         return id;
     }
 
-    /* advance_stack(s) as a state. Memoised on the stack, because many stacks -- in one state or
-     * in many -- close to the same place: every alternative of a wide rule that has just matched
-     * returns to one continuation, and every token of a context is resolved from it. */
+    /* advance_stack(s) as a state, memoised on the stack: many stacks, in one state or many,
+     * close to the same place (every matched alternative of a wide rule returns to one
+     * continuation). */
     int32_t closure(const GbnfStack& s) {
         auto it = closure_ids_.find(s);
         if (it != closure_ids_.end()) return it->second;
@@ -501,14 +462,11 @@ public:
         return r;
     }
 
-    /* The state whose stacks are the union of these states' stacks.
-     *
-     * The union is memoised on the states united -- a state's successors over two intervals, or
-     * the closures of two contexts, are united again and again -- and built by MERGING POINTERS:
-     * every state's stacks are already sorted, so a balanced tree of pairwise merges compares each
-     * stack once per level where sorting the concatenation would compare them n log n times, and
-     * no stack is copied until the union turns out to be a state not seen before. The bounds are
-     * checked after every merge, so a union that will not fit is refused before it is built. */
+    /* The state whose stacks are the union of these states' stacks. Memoised on the input
+     * states, since the same unions recur. Each state's stacks are sorted, so the union is a
+     * balanced tree of pairwise pointer merges (each stack compared once per level, not n log n)
+     * and stacks are copied only for a new state. Bounds are checked after every merge, so an
+     * oversized union is refused before it is built. */
     int32_t unite(std::vector& ids) {
         std::sort(ids.begin(), ids.end());
         ids.erase(std::unique(ids.begin(), ids.end()), ids.end());
@@ -552,9 +510,8 @@ public:
         return r;
     }
 
-    /* The state's intervals, built on first use: every boundary of every char-range top. Over
-     * each interval every top either matches every code point or none, because each of its items
-     * starts or ends at a boundary. */
+    /* The state's intervals, built on first use from every boundary of every char-range top, so
+     * each top matches either all or none of the code points in an interval. */
     const St& parted(int32_t sid) {
         St& S = st_[(size_t)sid];
         if (S.parted) return S;
@@ -586,9 +543,9 @@ public:
         return S;
     }
 
-    /* The successor over interval i of a parted state, computed on first use. The firing pattern
-     * is memoised as well as the interval: many intervals fire the same stacks -- everything
-     * that is not a quote or a backslash, in a JSON string -- and their union is built once. */
+    /* The successor over interval i of a parted state, computed on first use. Also memoised by
+     * firing pattern, since many intervals fire the same stacks (in a JSON string, everything but
+     * a quote or backslash). */
     int32_t next(int32_t sid, size_t i) {
         St& S = st_[(size_t)sid];
         if (S.next[i] != kUnbuilt) return S.next[i];
@@ -663,9 +620,8 @@ private:
 
 /* ============================================================ the walk
 
- * Descend a trie breadth-first carrying one automaton state per live node, setting a bit for every
- * token the state admits there. A node's tokens are admitted as follows, which is the candidate
- * walk's rule stated the other way up:
+ * Descend a trie breadth-first with one automaton state per live node, setting a bit for every
+ * token the state admits there (the candidate walk's rule, inverted):
  *
  *   ending here         admitted iff nothing is carried out, or some char-range top could take
  *                       some completion of what is;
@@ -691,8 +647,7 @@ struct Walk {
     uint64_t                                    frontier_limit = UINT64_MAX;
     bool                                        aborted = false;
 
-    /* The admitted ids in the order they were first set, while there are few enough to be worth
-     * listing; past `list_cap` only the bits are kept. */
+    /* Admitted ids in first-set order, up to `list_cap`; past it only the bits are kept. */
     std::vector* list = nullptr;
     size_t                list_cap = 0;
     bool                  list_full = false;
@@ -712,10 +667,9 @@ static inline void admit(Walk& w, int32_t id) {
     }
 }
 
-/* What a visit needs of the state it is made in. Read once per RUN of children -- every child in
- * one interval of the parent's state shares its successor -- rather than once per child: a
- * permissive walk visits every node of the vocabulary trie, and at that count the lookup of a
- * state is a measurable part of a visit. */
+/* What a visit needs of its state. Read once per run of children sharing an interval (and so a
+ * successor), not per child: a permissive walk visits every vocabulary trie node, where the state
+ * lookup is a measurable part of a visit. */
 struct VisitState {
     const SetDfa::St* S = nullptr;
     bool              expand = false;    /* it has char-range tops, so children can be stepped */
@@ -732,8 +686,8 @@ static inline VisitState visit_state(const SetDfa& dfa, const Walk& w, int32_t s
     return v;
 }
 
-/* The tokens ending at a node whose state is live: admitted outright unless they carry out a
- * partial character, which some char-range top must be able to finish. */
+/* Tokens ending at a live node: admitted unless they carry out a partial character that no
+ * char-range top can finish. */
 static void visit_terminals(Walk& w, OpWork& work, const VisitState& vs, uint32_t t0,
                             uint32_t t1) {
     const TokenTrie& T = *w.trie;
@@ -750,7 +704,7 @@ static void visit_terminals(Walk& w, OpWork& work, const VisitState& vs, uint32_
     }
 }
 
-/* What a token top admits from below node n, `t1 - t0` of whose tokens end at n itself. */
+/* What a token top admits from below node n; `n_end` of n's subtree tokens end at n itself. */
 static __attribute__((noinline)) void visit_token_tops(Walk& w, OpWork& work,
                                                        const VisitState& vs, uint32_t n,
                                                        uint32_t n_end) {
@@ -778,8 +732,8 @@ static __attribute__((noinline)) void visit_token_tops(Walk& w, OpWork& work,
     }
 }
 
-/* Visit node n: admit what ends here and what a token top takes from below, record an exit.
- * Returns whether the node's children are worth stepping. */
+/* Visit node n: admit what ends here and what a token top takes from below, and record an exit.
+ * Returns whether the node's children should be stepped. */
 static inline __attribute__((always_inline)) bool walk_visit(Walk& w, OpWork& work,
                                                              const TrieNode* nd, uint32_t n,
                                                              const VisitState& vs,
@@ -825,10 +779,10 @@ static void walk(SetDfa& dfa, int32_t start, Walk& w, OpWork& work, WalkScratch&
             const uint32_t  c1 = nd[n].first + nd[n].n_child;
             size_t          i  = 0;
 
-            /* One run of children per interval: the children are sorted, so the interval only
-             * moves forward -- a step at a time among a few intervals, by binary search among
-             * many -- a dead one is skipped by a binary search over the children, and a live one
-             * hands every child in it the same state. */
+            /* One run of children per interval. Children are sorted, so the interval only moves
+             * forward (linear among few intervals, binary search among many). A dead interval is
+             * skipped by binary search over the children; a live one gives all its children the
+             * same state. */
             while (c < c1) {
                 const uint64_t cp = cp_of(c);
                 if (m <= 16) {
@@ -863,11 +817,11 @@ static void walk(SetDfa& dfa, int32_t start, Walk& w, OpWork& work, WalkScratch&
 
 /* ============================================================ the plan */
 
-/* A KEY: a suffix of stack entries by class, bottom first. Held as a tree grown downward -- a
- * node is its bottom class plus the node for the entries above it -- which is also how a stack
- * is looked up: from its top, one entry down per level, until a node that is not extended.
+/* A key: a suffix of stack entries by class, bottom first. Held as a tree grown downward (a node
+ * is its bottom class plus the node for the entries above it); a stack is looked up from its top,
+ * one entry down per level, until a node that is not extended.
  *
- * `mask` is the accepted set: of a final node, used with any context; of an extended node that
+ * `mask` is the accepted set: for a final node, used with any context; for an extended node that
  * can be a whole stack, used only when the stack ends there. `rem` is the remainder trie, walked
  * from the context's state when there is a context. */
 struct KeyNode {
@@ -897,9 +851,9 @@ struct MaskPlan {
     std::vector            rems;
     PlanStats                         stats;
 
-    /* THE RUN-TIME HALF IS A MEMO. The automaton here holds the states contexts close to and the
-     * remainders step into; it grows as they are discovered and every state in it is a fact about
-     * the grammar, so one lock covers it and every request and rank shares it. */
+    /* Run-time memo: the automaton holding the states contexts close to and remainders step
+     * into. It grows as states are discovered; each is a fact about the grammar, so one lock
+     * covers it and every request and rank shares it. */
     mutable std::mutex              mu;
     mutable std::unique_ptr dfa;
     mutable WalkScratch             ws;
@@ -941,27 +895,23 @@ struct Grammar {
     }
 };
 
-/* WHICH RULES ARE THE SAME RULE. A generated grammar repeats itself: every tool's
- * undeclared-parameter clause is `("] | ">" [^\n])* ">\n")`, and the parser gives
- * each copy -- the group, the repetition, the alternatives inside it -- rules of its own. Their
- * entries would be distinct classes, and each would get a key and a walk of the vocabulary of
- * its own, one per tool, for identical answers.
+/* Merge identical rules. Generated grammars repeat clauses (every tool's undeclared-parameter
+ * clause `("] | ">" [^\n])* ">\n")`), and the parser gives each copy its own
+ * rules, which would otherwise mean a key and a vocabulary walk per copy.
  *
- * So rules are hash-consed on their bodies with references replaced by the referenced rule's
- * canonical id, bottom-up over the reference graph's strongly connected components. A rule that
- * refers only to itself -- which is what a repetition is -- is hashed with its self-references
- * marked as such, so identical repetitions merge too. A larger cycle of rules is left distinct:
- * mutual recursion is rare in what generators emit and is correct unmerged. Returns the canonical
- * id of each rule; ids of merged rules are equal, and no id is a rule index. */
+ * Rules are hash-consed on their bodies, with references replaced by the target's canonical id,
+ * bottom-up over the reference graph's SCCs. A self-referencing rule (a repetition) is hashed
+ * with its self-references marked, so identical repetitions merge. Larger cycles are left
+ * distinct (rare in generated grammars, and correct unmerged). Returns each rule's canonical id;
+ * merged rules share one, and no id is a rule index. */
 static std::vector canonical_rules(const Grammar& G, const std::vector& nullable,
                                              uint32_t max_cps, OpWork& work) {
     const GbnfRuleSet& R = G.R;
     const size_t NR = R.n_rules(), NE = R.elems.size();
     auto rule_end = [&](size_t r) { return r + 1 < NR ? R.start[r + 1] : (uint32_t)NE; };
 
-    /* Tarjan's strongly connected components over references, iteratively. Components come out
-     * in reverse topological order: every rule a component refers to outside itself is already
-     * canonical when it is reached. */
+    /* Tarjan's SCCs over references, iteratively. Components come out in reverse topological
+     * order, so every rule a component refers to outside itself is already canonical. */
     std::vector  idx(NR, -1), low(NR, 0);
     std::vector     on(NR, 0);
     std::vector stk;
@@ -1019,14 +969,12 @@ static std::vector canonical_rules(const Grammar& G, const std::vector
         out.append((const char*)&v, 4);
     };
 
-    /* A BOUNDED REPETITION IS A STAR, AS FAR AS ANY TOKEN CAN TELL. The parser writes x{0,n} as a
-     * chain, `S(k) ::= x S(k-1) |` down to `S(1) ::= x |`, and every link is a rule of its own --
-     * so `[^"]{0,1000}` would be a thousand keys, each walking the vocabulary. But a token holds
-     * at most `max_cps` code points, and when x always consumes at least one, a token can take at
-     * most that many repetitions: with more than that left, no token can tell the link from
-     * `x*`. Such links are given the star's canonical id; the shorter ones stay what they are.
-     * `depth` and `operand` hold, per link, how many repetitions it allows and the signature of
-     * what it repeats; a star, which refers to itself, is not a link. */
+    /* A bounded repetition looks like a star to any token. The parser writes x{0,n} as a chain
+     * `S(k) ::= x S(k-1) |` down to `S(1) ::= x |`, one rule per link. A token holds at most
+     * `max_cps` code points, so if x always consumes one, a link with more repetitions left than
+     * that is indistinguishable from `x*` and gets the star's canonical id. `depth` and `operand`
+     * hold, per link, its remaining repetitions and the signature of what it repeats; a star
+     * (self-referencing) is not a link. */
     std::vector    depth(NR, 0);
     std::vector operand(NR);
     auto consumes = [&](uint32_t a, uint32_t e) {
@@ -1097,9 +1045,7 @@ static std::vector canonical_rules(const Grammar& G, const std::vector
     return canon;
 }
 
-/* Which rules can match the empty string: a fixed point, as in find_left_recursion. An
- * alternative with a terminal in it never can; one of rule references only can once all of them
- * can, so it waits on a count. */
+/* Which rules can match the empty string: a fixed point, as in find_left_recursion. */
 static std::vector nullable_rules(const GbnfRuleSet& R, OpWork& work) {
     const size_t NR = R.n_rules(), NE = R.elems.size();
     std::vector     nullable(NR, 0);
@@ -1142,16 +1088,13 @@ static std::vector nullable_rules(const GbnfRuleSet& R, OpWork& work) {
     return nullable;
 }
 
-/* THE CLASS OF AN ENTRY is what remains of its alternative from it on, element for element with
- * rule references by canonical rule, hash-consed from the end of each alternative backward. Two
- * entries of one class behave identically wherever they are: what a stack does next is fixed by
- * the elements its entries have left and the rules those reference. Class 0 is the end of an
- * alternative and is never an entry.
+/* An entry's class is the rest of its alternative from it on, with rule references by canonical
+ * rule, hash-consed backward from the end of each alternative. Entries of one class behave
+ * identically anywhere. Class 0 is the end of an alternative and is never an entry.
  *
- * A RUN OF ONE UNIT is capped the way a repetition chain is (canonical_rules): x{1000} is a
- * thousand x in a row, and an entry with more than `max_cps` of a unit that always consumes a
- * code point still ahead of it behaves, for every token, like one with one fewer. Such an entry
- * takes the class of the entry after it. */
+ * A run of one unit is capped like a repetition chain (canonical_rules): x{1000} is a thousand x
+ * in a row, and an entry with more than `max_cps` of a code-point-consuming unit ahead of it
+ * behaves, for every token, like one with one fewer, so it takes the next entry's class. */
 static void compute_classes(Grammar& G, MaskPlan& P, const std::vector& nullable,
                             uint32_t max_cps, OpWork& work) {
     const GbnfRuleSet& R = G.R;
@@ -1209,19 +1152,15 @@ static void compute_classes(Grammar& G, MaskPlan& P, const std::vector& nu
     }
 }
 
-/* A RULE THAT CAN NEVER MATCH ANYTHING, and cannot be left either: every way into it comes back
- * into it without reaching a character or its own end -- `r ::= r` is the shortest. A stack that
- * enters one closes to nothing at all, and upstream's candidate walk reads a stack set that is
- * empty as rejecting nothing, so the mask past such a point admits every token while accepting
- * any of them ends the parse. A mask built from stack suffixes cannot reproduce that reading --
- * it depends on whether the rest of one particular stack is empty -- and nothing a grammar means
- * depends on it, so a grammar that can reach such a rule is refused, by the rule's name.
+/* A blind rule can neither match anything nor be left (`r ::= r` is the shortest). A stack that
+ * enters one closes to nothing, which upstream's candidate walk reads as admitting every token
+ * while accepting any of them ends the parse. Suffix-based masks cannot reproduce that, and no
+ * meaningful grammar depends on it, so a grammar that can reach such a rule is refused by name.
  *
- * A rule can POP past itself iff it is nullable, and its closure YIELDS a stack iff some element
- * it can reach before a first element that cannot pop is a terminal or a rule that yields. Both are
- * least fixed points computed with worklists, linear in the grammar -- a chain of a hundred
- * thousand rules is one pass, not one per link. A rule doing neither is blind. Returns a blind
- * rule reachable from the root, or kNone. */
+ * A rule can pop past itself iff it is nullable; its closure yields a stack iff some element
+ * reachable before the first non-nullable one is a terminal or a yielding rule. Both are least
+ * fixed points computed with worklists in one linear pass. A rule doing neither is blind.
+ * Returns a blind rule reachable from the root, or kNone. */
 static uint32_t blind_rule(const Grammar& G, const std::vector& nullable, OpWork& work) {
     const GbnfRuleSet& R = G.R;
     const size_t NR = R.n_rules();
@@ -1270,8 +1209,8 @@ static void analyse(Grammar& G, MaskPlan& P, OpWork& work) {
     }
     work.add(NE);
 
-    /* Reachable rules. A reference inside an unreachable rule is not a place any stack can be,
-     * and counting it would give frames predecessors they never have. */
+    /* Reachable rules. References inside unreachable rules must not count, or frames would get
+     * predecessors no stack has. */
     G.reach.assign(NR, 0);
     std::vector todo{ G.root };
     G.reach[G.root] = 1;
@@ -1288,7 +1227,7 @@ static void analyse(Grammar& G, MaskPlan& P, OpWork& work) {
         }
     }
 
-    /* Tail references (a frame REPLACED rather than stacked on), and every reference by target. */
+    /* Tail references (a frame replaced rather than stacked on), and every reference by target. */
     G.rev_tail.assign(NR, {});
     G.refs_to.assign(NR, {});
     std::vector> tail_to(NR);
@@ -1311,8 +1250,8 @@ static void analyse(Grammar& G, MaskPlan& P, OpWork& work) {
         }
     }
 
-    /* The frames a stack can have at its bottom: the root's, and whatever it hands over to by
-     * tail reference. */
+    /* Frames a stack can have at its bottom: the root's, and whatever it hands over to by tail
+     * reference. */
     G.bottom_ok.assign(NR, 0);
     todo.assign(1, G.root);
     G.bottom_ok[G.root] = 1;
@@ -1323,7 +1262,7 @@ static void analyse(Grammar& G, MaskPlan& P, OpWork& work) {
             if (!G.bottom_ok[t]) { G.bottom_ok[t] = 1; todo.push_back(t); }
     }
 
-    /* The terminals, by class: every place a stack's top can be. */
+    /* Terminals by class: every place a stack's top can be. */
     G.tops.assign(G.rep.size(), {});
     for (size_t r = 0; r < NR; ++r) {
         if (!G.reach[r]) continue;
@@ -1345,16 +1284,14 @@ static void analyse(Grammar& G, MaskPlan& P, OpWork& work) {
     G.stamp.assign(NR, 0);
 }
 
-/* THE ENTRIES THAT CAN SIT DIRECTLY BELOW A FRAME OF RULE r: the element after every reference to
- * r, or to a rule that hands over to r by tail reference. Every entry below a stack's top is such
- * an element -- where the frame below resumes.
+/* Entries that can sit directly below a frame of rule r: the element after every reference to r,
+ * or to a rule that hands over to r by tail reference (where the frame below resumes).
  *
- * KEPT BY ELEMENT, NOT BY CLASS, and a key's bottom entry carries the elements it can be. Classes
- * merge elements of different rules, and so merge what can sit below them: the `space` that ends
- * `integer` and the `space` after `integer` in the rule that uses it are one class, and below the
- * first is the second, so by class that class can sit below itself without end -- a chain no real
- * stack holds, and one a key would be extended along until it was refused. By element, adjacency
- * is exact, and a key grows only as deep as real stacks do. */
+ * Kept by element, not class; a key's bottom entry carries the elements it can be. Classes merge
+ * elements of different rules: the `space` ending `integer` and the `space` after `integer` in its
+ * user are one class, so by class it could sit below itself without end, and a key would be
+ * extended along that phantom chain until refused. By element, keys grow only as deep as real
+ * stacks. */
 static const std::vector& below_of(Grammar& G, uint32_t r, OpWork& work) {
     if (G.below_done[r]) return G.below[r];
     std::vector& out = G.below[r];
@@ -1380,13 +1317,11 @@ static const std::vector& below_of(Grammar& G, uint32_t r, OpWork& wor
 
 /* The entries that can sit directly below any of `pos`, as (class, element), sorted.
  *
- * ONE WALK FROM ALL OF `pos`'s RULES, not one below_of per rule. The links of a repetition chain
- * hand over to each other by tail reference, so the walk up from one link climbs every link above
- * it; and every link past the longest token is one class, so one key's positions are all n links
- * of `x{0,n}`. Walked a rule at a time that is n^2/2 steps -- `maxLength: 32000` took two seconds
- * to compile, and 48000 was refused for the work. Walked from every rule at once, each rule is
- * visited once. A rule whose own set is already known contributes it and is not climbed past. A
- * key of one rule, the common case, keeps the memo. */
+ * One walk from all of `pos`'s rules, not below_of per rule. Repetition-chain links hand over by
+ * tail reference, so climbing from one link visits every link above it, and one key's positions
+ * can be all n links of `x{0,n}`; per rule that is n^2/2 steps. Walking from all rules at once
+ * visits each rule once. A rule whose set is already known contributes it and is not climbed
+ * past. A single-rule key (the common case) uses the below_of memo. */
 static void preds_of(Grammar& G, const MaskPlan& P, const std::vector& pos,
                      std::vector>* out, OpWork& work) {
     out->clear();
@@ -1440,9 +1375,9 @@ static std::string rule_name_of(const std::vector* names, uint32_t
 
 /* ============================================================ building the keys */
 
-/* What one key's walk decided. A final key keeps its accepted set, which holds whatever the
- * context, and its remainder trie. A key that is not final is extended; it keeps an accepted set
- * only if it can also be a whole stack, where there is no context and that set is the mask. */
+/* What one key's walk decided. A final key keeps its accepted set (valid for any context) and its
+ * remainder trie. A non-final key is extended, and keeps an accepted set only if it can also be a
+ * whole stack, where that set is the mask. */
 struct Outcome {
     bool    final_ = false;
     int32_t mask   = -1;
@@ -1467,8 +1402,8 @@ public:
         } else if (!w.aborted) {
             o.mask = store(w);
         } else {
-            /* The walk was cut short once the key was known to be extended; as a whole stack it
-             * needs the rest. */
+            /* The walk stopped early because the key will be extended; as a whole stack it needs
+             * a full walk. */
             clear(w);
             Walk whole = start_walk(false);
             walk(dfa_, s0, whole, work_, ws_);
@@ -1492,8 +1427,8 @@ private:
         return w;
     }
 
-    /* Keep an accepted set: listed when the walk listed it, as a bitmask otherwise. Clears the
-     * scratch bits either way. */
+    /* Keep an accepted set: as a list if the walk listed it, else as a bitmask. Clears the scratch
+     * bits either way. */
     int32_t store(Walk& w) {
         KeyMask m;
         if (!w.list_full) {
@@ -1527,10 +1462,9 @@ private:
             return true;
         }
         if (!w.aborted) {
-            /* What leaves the key and is not already admitted without it: the tokens under each
-             * node where the key was left, from that depth on. A token that ends exactly there
-             * leaves an empty remainder, which only a carried-out partial character can make
-             * worth keeping. */
+            /* The remainder: tokens under each node where the key was left, from that depth on,
+             * that are not already admitted. A token ending exactly there leaves an empty
+             * remainder, kept only if it carries out a partial character. */
             rents_.clear();
             bool too_many = false;
             for (const auto& f : frontier_) {
@@ -1601,7 +1535,7 @@ int plan_build(const GbnfRuleSet& R, uint32_t root, const std::shared_ptr 0 ? X.trie.depth - 1 : 0;
     const std::vector nullable = nullable_rules(R, work);
     compute_classes(G, P, nullable, max_cps, work);
@@ -1639,14 +1573,13 @@ int plan_build(const GbnfRuleSet& R, uint32_t root, const std::shared_ptr kMaxDfaElems) dfa = SetDfa(&R);
         dfa.begin(&work);
 
-        /* A node's class is its BOTTOM entry and `up` is the suffix above it, so following `up`
-         * lists the key bottom-first, which is a stack's order. */
+        /* A node's class is its bottom entry and `up` the suffix above it, so following `up`
+         * lists the key bottom-first, in stack order. */
         local.clear();
         for (int32_t k = ki; k >= 0; k = P.keys[(size_t)k].up)
             local.push_back(&R.elems[G.rep[P.keys[(size_t)k].cls]]);
@@ -1715,9 +1648,9 @@ int plan_build(const GbnfRuleSet& R, uint32_t root, const std::shared_ptr 0 && nd[nd[0].first].cp == 1;
     if (nul) {
         std::vector todo{ nd[0].first };
@@ -1843,11 +1774,9 @@ static void fill_resume(const MaskPlan& P, SetDfa& dfa, const GbnfStacks& stacks
     }
 }
 
-/* The plan's automaton, for one operation charged to `work`. The caller holds P.mu.
- *
- * The automaton is a memo, so past its bound it is dropped and rebuilt rather than refused: every
- * state in it can be rediscovered, and a grammar whose stacks deepen with every token would
- * otherwise hold a new state per token for as long as it is cached. */
+/* The plan's automaton, for one operation charged to `work`. Caller holds P.mu. Past its bound
+ * the memo is dropped and rebuilt rather than refused, since every state can be rediscovered and
+ * a grammar whose stacks deepen every token would otherwise add a state per token. */
 static SetDfa& plan_dfa(const MaskPlan& P, OpWork& work) {
     if (!P.dfa || P.dfa->elems() > kMaxDfaElems) {
         if (P.dfa)
@@ -1865,9 +1794,8 @@ bool plan_step(const MaskPlan& P, const std::vector& stacks, P
     std::lock_guard lk(P.mu);
     SetDfa& dfa = plan_dfa(P, work);
 
-    /* The set as a state: the one the caller names, or canonicalised through pointers -- sorted,
-     * without duplicates, and copied only if the automaton has not seen it. Charged as intern()
-     * charges a sort. */
+    /* The set as a state: the one the caller names, or canonicalised through pointers (sorted,
+     * de-duplicated, copied only if new). The sort is charged as in intern(). */
     const bool named = at->id >= 0 && at->gen == P.dfa_gen;
     int32_t s0;
     if (named) {
@@ -1891,8 +1819,7 @@ bool plan_step(const MaskPlan& P, const std::vector& stacks, P
     }
     int32_t s = s0;
 
-    /* One successor per code point: the interval the code point falls in, then that interval's
-     * successor, each built on first use and served from the memo after. */
+    /* Per code point: find its interval, then that interval's successor (both memoised). */
     for (size_t k = 0; k < n && s >= 0; ++k) {
         const SetDfa::St& S = dfa.parted(s);
         const size_t i = (size_t)(std::upper_bound(S.lo.begin(), S.lo.end(), cps[k]) -
diff --git a/core/sample/grammar.cpp b/core/sample/grammar.cpp
index 465a24cc..4a2afa11 100644
--- a/core/sample/grammar.cpp
+++ b/core/sample/grammar.cpp
@@ -1,4 +1,4 @@
-/* grammar.cpp -- the GBNF backend that ships, and the schema seam onto it.
+/* grammar.cpp -- the GBNF grammar backend and the JSON Schema entry point onto it.
  */
 #include "grammar.h"
 #include "gbnf.h"
@@ -7,23 +7,20 @@
 #include 
 
 #include 
+#include 
 #include 
-#include 
 
 namespace rad {
 
 int64_t grammar_mask_words(int64_t n_vocab) { return bitmask_words(n_vocab); }
 
-/* HOW DEEPLY A SCHEMA MAY NEST, in objects and arrays. The converter recurses once per level and
- * names each rule after its whole path, so its output grows with the square of the depth: a
- * 72 KB schema 3,000 levels deep compiles to 67 MB of grammar, and deeper ones exhaust the
- * memory or the stack of the thread that admits the request. A schema nested as deep as this one
- * allows converts in tens of milliseconds to a couple of megabytes, and a schema written to
- * describe data nests far less. */
+/* Maximum schema nesting, in objects and arrays. The converter recurses once per level and names
+ * each rule after its full path, so output grows with the square of the depth (a 72 KB schema
+ * 3,000 levels deep gives 67 MB of grammar) and deeper ones exhaust the admitting thread's memory
+ * or stack. At this depth a schema converts in tens of milliseconds to a couple of megabytes. */
 static constexpr size_t kMaxSchemaDepth = 512;
 
-/* Walked with an explicit stack, because the values it exists to catch are the ones too deep to
- * recurse over. */
+/* Iterative, because the values it must catch are too deep to recurse over. */
 static size_t json_depth(const nlohmann::ordered_json& root) {
     std::vector> todo{ { &root, 1 } };
     size_t deepest = 0;
@@ -37,26 +34,16 @@ static size_t json_depth(const nlohmann::ordered_json& root) {
     return deepest;
 }
 
-/* ONE JSON-SCHEMA COMPILER, AND IT IS THE VENDORED ONE.
- *
- * `response_format` on /v1/chat/completions goes to the chat template, which compiles it with the
- * vendored converter; on /v1/completions it is refused by the accept-list (kAcceptedCompletion)
- * before parse_output_format runs, and that is the only path to this seam. A second, separately
- * maintained copy of the same upstream compiler would therefore be the copy no request reaches,
- * while the vendored one serves every schema. The hardening that belongs on a schema compiler
- * fed client data -- vendor/patches 0003 and 0004, which close a hang and two out-of-bounds
- * reads and refuse three constructs upstream accepts and then gets wrong -- lives in the
- * vendored copy, which is the copy that runs.
- *
- * This function is the seam response_format would go through if /v1/completions accepted it.
- * No request reaches it.
- *
- * The vendored entry point throws; errors are values by the time a caller sees them. */
+/* Uses the vendored converter, the only JSON Schema compiler in the tree; its hardening for
+ * client data is in vendor/patches 0003 and 0004. Client schemas reach it from /v1/completions
+ * (`json_schema`, `response_format`) through the server's grammar bridge; on
+ * /v1/chat/completions the chat template compiles them instead. The converter throws; errors
+ * are returned as statuses. */
 int grammar_from_json_schema(const std::string& schema_json, const std::string& root,
                              std::string* out_gbnf, std::string* err) {
     if (!out_gbnf) return RAD_E_INVAL;
-    /* The converter names its top rule "root" and takes no say in it. Every caller in the tree
-     * asks for "root"; anything else would silently get that instead, so it is refused. */
+    /* The converter always names its top rule "root"; any other name is refused rather than
+     * silently ignored. */
     if (!root.empty() && root != "root") {
         if (err) *err = "this converter always names the top rule 'root'";
         return RAD_E_UNSUPPORTED;
@@ -88,16 +75,14 @@ class GbnfBackend : public GrammarBackend {
 public:
     explicit GbnfBackend(std::unique_ptr g) : g_(std::move(g)) {}
 
-    const char* name() const override { return "gbnf"; }
     int  accept_token(int32_t token) override { return g_->accept_token(token); }
     int  fill_mask(uint32_t* m, int64_t n) const override { return g_->fill_mask(m, n); }
     bool complete() const override { return g_->complete(); }
     bool constrains() const override { return !g_->awaiting_trigger(); }
     uint64_t masks_walked() const override { return g_->masks_walked(); }
 
-    /* The GBNF machine's state is a stack set and a carried UTF-8 partial, both copyable, so a
-     * rewind is a copy back -- there is nothing to reconstruct and no cost that scales with how
-     * far the window went. */
+    /* The state is a stack set and a carried UTF-8 partial, both copyable, so a rewind is a copy
+     * whose cost does not depend on how far the window went. */
     bool can_speculate() const override { return true; }
     int  push_state() override { g_->push_state(); return RAD_OK; }
     int  rollback() override   { return g_->rollback(); }
@@ -110,9 +95,7 @@ int gbnf_ctor(const GrammarSpec& spec, const VocabView& vocab,
               std::unique_ptr* out, std::string* err) {
     std::string text = spec.text;
 
-    /* A JSON Schema is compiled to GBNF here rather than being a second backend, because it is
-     * not a different state machine -- it is the same one fed different text. Carrying it as a
-     * backend would mean two places that can disagree about what a schema admits. */
+    /* A JSON Schema is compiled to GBNF and run on the same machine, not a second backend. */
     if (spec.kind == GrammarKind::JsonSchema) {
         std::string gbnf;
         const int st = grammar_from_json_schema(spec.text, spec.root, &gbnf, err);
@@ -129,9 +112,8 @@ int gbnf_ctor(const GrammarSpec& spec, const VocabView& vocab,
     if (!spec.prefix.empty()) {
         const int ps = g->accept_str(spec.prefix);
         if (ps < 0) {
-            /* The grammar does not admit the prompt it was supposed to have been generating.
-             * Constraining from here would mask against a state that does not describe this
-             * request, so it is refused rather than run in the wrong place. */
+            /* The grammar rejects the generation prompt; masking from here would use a state
+             * that does not describe this request, so refuse. */
             if (err) *err = "the grammar does not admit this template's generation prompt, so it "
                             "cannot be positioned at the start of the reply";
             return ps;
@@ -152,9 +134,8 @@ int grammar_create(const GrammarSpec& spec, const VocabView& vocab,
         return RAD_E_INVAL;
     }
 
-    /* The compiler below turns its own failures into statuses; what is left is running out of
-     * memory on the way, and this is called on the admission thread and the scheduler thread,
-     * where an escaping exception ends every request on the server rather than this one. */
+    /* The compiler returns its own failures as statuses; only bad_alloc can escape. This runs on
+     * the admission and scheduler threads, where an escaping exception would end every request. */
     try {
         return gbnf_ctor(spec, vocab, out, err);
     } catch (const std::bad_alloc&) {
diff --git a/core/sample/grammar.h b/core/sample/grammar.h
index c7671081..76cb9441 100644
--- a/core/sample/grammar.h
+++ b/core/sample/grammar.h
@@ -1,18 +1,13 @@
 /* grammar.h -- structured output: the grammar backend interface, and the bitmask that crosses to
  * the device.
  *
- * Structured output is GBNF, with JSON-schema compiled to a grammar. THE GRAMMAR STATE MACHINE
- * STAYS ON HOST, where it belongs -- it is a pushdown automaton over a rule set, it branches per
- * candidate, and none of that is work a GPU is good at. What crosses is a TOKEN BITMASK PER
- * SEQUENCE, which at a 151K vocab is 19 KiB, cheap enough to upload every step (spec §13). The
- * mask lands as the `sample_mask` op (docs/OPS.md), which is an ordinary declared op resolved
- * through the ordinary hierarchy.
+ * Structured output is GBNF, with JSON Schema compiled to a grammar. The grammar state machine
+ * stays on host: it is a pushdown automaton that branches per candidate, which suits a CPU. What
+ * crosses is a token bitmask per sequence, 19 KiB at a 151K vocab, cheap enough to upload every
+ * step (spec §13). The mask is applied by the ordinary `sample_mask` op (docs/OPS.md).
  *
- * The backend is a small interface so an alternative can be dropped in, and it is small on
- * purpose: three calls. GBNF is the shipped one and there is no reason to carry xgrammar for it.
- * If a device-side grammar ever earns its place, it implements this and nothing above it changes
- * -- at which point it gets a way to be selected, which is a thing to add then rather than a
- * registry to carry now for an entry that never arrived.
+ * The backend interface is kept small so an alternative (e.g. a device-side grammar) can
+ * implement it without changes above it. GBNF is the only backend, so there is no registry.
  */
 #pragma once
 #include "../rad_internal.h"
@@ -34,22 +29,18 @@ struct GrammarSpec {
     std::string text;
     std::string root = "root";
 
-    /* Lazy grammars constrain nothing until a trigger fires, which is how a tool-calling template
-     * stays free-form until the model starts emitting a call. A trigger is a token id or a literal
-     * word in the emitted bytes; see sampler.cpp for how a template's triggers become these. */
+    /* A lazy grammar constrains nothing until a trigger fires, so a tool-calling template stays
+     * free-form until the model starts a call. A trigger is a token id or a literal word in the
+     * emitted bytes; sampler.cpp maps a template's triggers to these. */
     bool                     lazy = false;
     std::vector trigger_words;
     std::vector     trigger_tokens;
 
-    /* TEXT THE GRAMMAR HAS ALREADY SEEN, replayed into it before it constrains anything.
-     *
-     * A chat template's grammar describes the whole assistant turn, generation prompt included:
-     * its root really does begin `"<|im_start|>assistant\n"`, because that is where the turn
-     * begins. But those bytes are in the PROMPT, not in what the model is about to generate, so a
-     * grammar started at its root demands them again -- and the model, obediently masked, emits
-     * the literal text `<|im_start|>assistant` as its answer. Replaying the prefix is what puts
-     * the automaton where the sampler actually is. Empty for a caller-supplied grammar, which
-     * describes the reply and nothing before it. */
+    /* Text replayed into the grammar before it constrains anything. A chat template's grammar
+     * covers the whole assistant turn, so its root begins with the generation prompt (e.g.
+     * `"<|im_start|>assistant\n"`), which is already in the prompt. Without the replay the mask
+     * would force the model to emit it again. Empty for a caller-supplied grammar, which
+     * describes only the reply. */
     std::string              prefix;
 };
 
@@ -57,51 +48,38 @@ class GrammarBackend {
 public:
     virtual ~GrammarBackend() = default;
 
-    virtual const char* name() const = 0;
-
-    /* Advance over the token the sampler just emitted. Returns RAD_OK, or RAD_E_STATE if that
-     * token was not admissible -- which means the mask and the pick disagreed, a bug on this side
-     * rather than a bad request. RAD_E_FULL or RAD_E_NOMEM means the parse outgrew the backend's
-     * bounds; the backend is then dead and its next fill_mask fails. */
+    /* Advance over the token the sampler just emitted. RAD_E_STATE means the token was not
+     * admissible: the mask and the pick disagreed, a bug here rather than a bad request.
+     * RAD_E_FULL or RAD_E_NOMEM means the parse outgrew the backend's bounds; the backend is then
+     * dead and its next fill_mask fails. */
     virtual int accept_token(int32_t token) = 0;
 
-    /* Fill `bitmask` ([n_words] words, bit set means admissible). RAD_E_STATE if nothing at all is
-     * admissible, RAD_E_FULL or RAD_E_NOMEM if the state is past the backend's bounds; any of them
-     * fails the request rather than emitting a token the grammar forbids. */
+    /* Fill `bitmask` ([n_words] words, bit set = admissible). RAD_E_STATE if nothing is
+     * admissible, RAD_E_FULL or RAD_E_NOMEM if the state is past the backend's bounds; each fails
+     * the request rather than emit a forbidden token. */
     virtual int fill_mask(uint32_t* bitmask, int64_t n_words) const = 0;
 
     /* Some parse has run to completion, so the sequence may stop here. */
     virtual bool complete() const = 0;
 
-    /* INSTRUMENT: how many masks this backend has had to COMPUTE rather than serve from a memo,
-     * monotonic over the life of whatever the memo belongs to. Diff it around a fill_mask to learn
-     * which of the two that call was.
-     *
-     * It is a counter and not a duration. Inferring computed-versus-hit from how long a fill_mask
-     * took needs a cost threshold, and no threshold holds: a mask computed on a small grammar
-     * finishes inside the time a memo hit on a large one takes, so the classification is wrong and
-     * any per-mask cost derived from it is wrong by the same factor. A backend with no memo counts
-     * every mask. */
+    /* Instrument: masks computed rather than served from a memo, monotonic over the memo's
+     * lifetime. Diff it around a fill_mask to classify that call. A counter, because timing cannot
+     * classify: a computed mask on a small grammar can be faster than a memo hit on a large one.
+     * A backend with no memo counts every mask. */
     virtual uint64_t masks_walked() const { return 0; }
 
-    /* False while a lazy grammar is still waiting for its trigger. The driver skips the mask op
-     * for a sequence that is not being constrained, which is the only reason this is on the
-     * interface rather than folded into fill_mask returning all-ones. */
+    /* False while a lazy grammar waits for its trigger. Lets the driver skip the mask op for an
+     * unconstrained sequence instead of applying an all-ones mask. */
     virtual bool constrains() const = 0;
 
     /* ---------------------------------------------------------- speculation
 
-     * A CONSTRAINED SEQUENCE SPECULATES BY WALKING THE WINDOW AND REWINDING. The mask for draft
-     * position i is the mask of the state reached by accepting drafts 0..i-1, so the sampler
-     * pushes the state, advances over each proposal in turn to mask the position behind it, and
-     * pops back to where the sequence really is. Without it a grammar-constrained request decodes
-     * one token at a time, at several times the per-token cost of the same model generating
-     * unconstrained prose.
+     * A constrained sequence speculates by walking the window and rewinding. The mask for draft
+     * position i comes from the state after accepting drafts 0..i-1, so the sampler pushes the
+     * state, advances over each proposal to mask the next position, then pops back.
      *
-     * A backend that cannot do this says so and is driven unspeculated -- the sampler decodes
-     * such a request a token at a time rather than masking a draft position against a state the
-     * sequence is not in, which would admit the wrong token set and read as a model that writes
-     * malformed calls. */
+     * A backend that cannot do this returns false and its requests decode one token at a time;
+     * masking a draft position against the wrong state would admit the wrong token set. */
     virtual bool can_speculate() const { return false; }
 
     /* Push the current state. Nestable; `rollback` pops the most recent. */
@@ -112,15 +90,13 @@ public:
 /* Words a mask needs for a vocabulary of this size. */
 int64_t grammar_mask_words(int64_t n_vocab);
 
-/* Compile a JSON Schema to GBNF text. Separated from create() so a caller that wants to SEE the
- * grammar -- `--debug-graph`, or a user asking why their schema behaves as it does -- can get it
- * without building a state machine. */
+/* Compile a JSON Schema to GBNF text, without building a state machine, so the grammar can be
+ * inspected (e.g. `--debug-graph`). */
 int grammar_from_json_schema(const std::string& schema_json, const std::string& root,
                              std::string* out_gbnf, std::string* err);
 
-/* Build the grammar backend. Returns RAD_OK, or a negative status with a human-readable reason
- * in *err. There is ONE backend and it is GBNF: a name-keyed registry over a single entry with no
- * second registration site is a lookup that can only ever resolve to that entry. */
+/* Build the grammar backend (always GBNF). Returns RAD_OK, or a negative status with a
+ * human-readable reason in *err. */
 int grammar_create(const GrammarSpec& spec, const VocabView& vocab,
                    std::unique_ptr* out, std::string* err);
 
diff --git a/core/sample/host_ref.cpp b/core/sample/host_ref.cpp
index 72e9f9f7..153fc873 100644
--- a/core/sample/host_ref.cpp
+++ b/core/sample/host_ref.cpp
@@ -1,9 +1,8 @@
 /* host_ref.cpp -- llama.cpp's sampling chain, ported to plain C++ over a float array.
  *
  * Source: llama.cpp `src/llama-sampler.cpp` at upstream commit 06938ac12 (MIT). Ported rather
- * than linked: this is the oracle the device samplers are checked against, and an oracle that
- * drags a second inference engine in is a dependency rather than a reference. See host_ref.h for
- * the two places this deliberately differs from upstream -- the chain order and the RNG.
+ * than linked, so the oracle carries no second engine as a dependency. host_ref.h lists the two
+ * deliberate deviations: chain order and RNG.
  */
 #include "host_ref.h"
 
@@ -29,10 +28,8 @@ void CandidateSet::from_logits(const float* logits, int64_t n_vocab) {
     selected = -1;
 }
 
-/* Upstream sorts on the logit alone and leaves equal logits in whatever order the partial sort
- * happened to produce. That is fine for a single-threaded reference and useless for one that has
- * to agree with a device kernel, where the order equal elements land in is a property of the
- * block size. The id tie-break makes the sort a total order, so the two agree. */
+/* Upstream sorts on the logit alone, leaving ties in arbitrary order; on the device that order
+ * depends on the block size. The id tie-break makes it a total order both sides share. */
 void CandidateSet::sort_desc() {
     if (sorted) return;
     std::stable_sort(c.begin(), c.end(), [](const Candidate& a, const Candidate& b) {
@@ -44,29 +41,25 @@ void CandidateSet::sort_desc() {
 
 /* ================================================================== reproducible randomness */
 
-/* The stream's key, from abi/rad_sample.h. A stream this file does not know gets a key of its
- * own rather than the pick's, so it can never silently repeat the pick's draw. */
+/* The stream's key from abi/rad_sample.h. An unknown stream gets a key of its own, never the
+ * pick's. */
 static uint64_t stream_key(uint32_t stream) {
     switch (stream) {
         case RAD_RNG_PICK:   return RAD_SAMPLE_KEY_PICK;
         case RAD_RNG_XTC:    return RAD_SAMPLE_KEY_XTC;
-        case RAD_RNG_ACCEPT: return RAD_SAMPLE_KEY_ACCEPT;
-        case RAD_RNG_RESID:  return RAD_SAMPLE_KEY_RESID;
         default:             return rad_sample_splitmix64((uint64_t)stream);
     }
 }
 
-/* rad_sample_uniform01's bits, before the float conversion: one splitmix64 round over
- * ((seed ^ key) * golden ratio + pos). The same handful of integer ops a sampler kernel runs,
- * which is what makes it affordable there where a Mersenne twister's state is not. */
+/* rad_sample_uniform01's bits before the float conversion: one splitmix64 round over
+ * ((seed ^ key) * golden ratio + pos), cheap and stateless enough for a kernel. */
 uint64_t rng_bits(uint64_t seed, uint64_t pos, uint32_t stream) {
     return rad_sample_splitmix64((seed ^ stream_key(stream)) * 0x9E3779B97F4A7C15ull + pos);
 }
 
 float rng_uniform(uint64_t seed, uint64_t pos, uint32_t stream) {
-    /* 24 bits, which is every bit a float can hold. Drawing 32 and dividing by 2^32 would round
-     * to 1.0f for the top values, and a uniform that can return 1.0 walks off the end of an
-     * inverse CDF. Written as rad_sample_uniform01 itself, so the two cannot drift apart. */
+    /* 24 bits: 32 bits divided by 2^32 can round to 1.0f, which walks off the end of an inverse
+     * CDF. Calls rad_sample_uniform01 itself so host and device cannot drift apart. */
     return rad_sample_uniform01(seed ^ stream_key(stream), pos);
 }
 
@@ -86,22 +79,27 @@ void host_softmax(CandidateSet& s, bool do_sort) {
         e.p = p;
         cum += p;
     }
-    if (cum <= 0.0) return;   /* every candidate masked out; leave p at zero and let the pick say so */
+    if (cum <= 0.0) return;   /* everything masked; p stays zero and the pick reports it */
     for (auto& e : s.c) e.p = (float)(e.p / cum);
 }
 
+/* Index of the highest logit, ties to the lowest id whatever the set's order, as the argmax
+ * kernel breaks them. The set must not be empty. */
+static size_t best_index(const CandidateSet& s) {
+    size_t best = 0;
+    for (size_t i = 1; i < s.c.size(); ++i) {
+        if (s.c[i].logit > s.c[best].logit) best = i;
+        else if (s.c[i].logit == s.c[best].logit && s.c[i].id < s.c[best].id) best = i;
+    }
+    return best;
+}
+
 void host_temp(CandidateSet& s, float temp) {
     if (s.c.empty()) return;
 
-    /* temp <= 0 is greedy and stays a real path rather than a caller's special case: the argmax
-     * it produces must use the SAME tie-break the argmax kernel uses (lowest id wins), or a
-     * temperature-0 request stops matching a greedy run. */
+    /* temp <= 0 is greedy, so a temperature-0 request matches a greedy run. */
     if (temp <= 0.0f) {
-        size_t max_i = 0;
-        for (size_t i = 1; i < s.c.size(); ++i) {
-            const Candidate& e = s.c[i];
-            if (e.logit > s.c[max_i].logit) max_i = i;
-        }
+        const size_t max_i = best_index(s);
         for (size_t i = 0; i < s.c.size(); ++i)
             if (i != max_i) s.c[i].logit = -INFINITY;
         return;
@@ -118,14 +116,14 @@ void host_top_k(CandidateSet& s, int32_t k) {
 }
 
 void host_top_p(CandidateSet& s, float p, size_t min_keep) {
-    if (p >= 1.0f || s.c.empty()) return;
+    /* p <= 0 is off, as in sample_topp; upstream would keep min_keep candidates. */
+    if (p >= 1.0f || !(p > 0.0f) || s.c.empty()) return;
 
     s.sort_desc();
     host_softmax(s, false);
 
-    /* Upstream has an adaptive partial sort that grows k until the nucleus closes; it is a
-     * performance path over a 151K vocab and produces the same set as a full sort, so the
-     * reference takes the full sort and the device kernel takes the radix threshold. */
+    /* Upstream's adaptive partial sort is a performance path that yields the same set; the
+     * reference does a full sort and the device kernel a radix threshold. */
     float  cum = 0.0f;
     size_t last_idx = s.c.size();
     for (size_t i = 0; i < s.c.size(); ++i) {
@@ -138,10 +136,8 @@ void host_top_p(CandidateSet& s, float p, size_t min_keep) {
 void host_min_p(CandidateSet& s, float p, size_t min_keep) {
     if (p <= 0.0f || s.c.empty()) return;
 
-    /* Upstream has an unsorted fast path that filters in place and falls back to the sorted one
-     * when too few survive. Both select the same SET and differ only in the order they leave it
-     * in; the reference takes the sorted path because an order that depends on which path ran is
-     * an order a device kernel cannot reproduce. */
+    /* Upstream also has an unsorted fast path. It selects the same set but leaves a different
+     * order, which a device kernel cannot reproduce, so the reference always sorts. */
     s.sort_desc();
 
     const float min_logit = s.c[0].logit + std::log(p);   /* p_i >= p * p_max */
@@ -153,7 +149,7 @@ void host_min_p(CandidateSet& s, float p, size_t min_keep) {
 }
 
 void host_typical(CandidateSet& s, float p, size_t min_keep) {
-    if (p >= 1.0f || s.c.empty()) return;
+    if (p >= 1.0f || !(p > 0.0f) || s.c.empty()) return;
 
     host_softmax(s, true);
 
@@ -161,13 +157,12 @@ void host_typical(CandidateSet& s, float p, size_t min_keep) {
     for (const auto& e : s.c)
         if (e.p > 0.0f) entropy += -e.p * std::log(e.p);
 
-    /* The distance between a candidate's surprisal and the distribution's entropy. Sorting by it
-     * is what makes typical sampling different from every other cut here: it keeps the tokens
-     * that are AS surprising as expected, not the least surprising ones. */
+    /* Distance between each candidate's surprisal and the entropy; typical sampling keeps the
+     * tokens closest to the expected surprisal. A zero-probability candidate has none. */
     std::vector shifted(s.c.size());
     for (size_t i = 0; i < s.c.size(); ++i) {
         const float pi = s.c[i].p;
-        shifted[i] = std::fabs(-(pi > 0.0f ? std::log(pi) : -INFINITY) - entropy);
+        shifted[i] = pi > 0.0f ? std::fabs(-std::log(pi) - entropy) : INFINITY;
     }
 
     std::vector idx(s.c.size());
@@ -177,18 +172,26 @@ void host_typical(CandidateSet& s, float p, size_t min_keep) {
         return s.c[a].id < s.c[b].id;      /* total order, same reason as sort_desc */
     });
 
+    /* The cut is a distance, not a count: the smallest distance whose candidates at or below it
+     * carry at least p, with every candidate at that distance kept. sample_typical keeps the tied
+     * set the same way, so the result does not depend on an order among equal distances. With no
+     * such distance (rounding leaves the whole mass below p) nothing is cut. */
     float  cum = 0.0f;
-    size_t last_idx = idx.size();
+    size_t keep = idx.size();
     for (size_t i = 0; i < idx.size(); ++i) {
+        if (!(s.c[idx[i]].p > 0.0f)) break;
         cum += s.c[idx[i]].p;
-        if (cum > p && (min_keep == 0 || i >= min_keep - 1)) { last_idx = i + 1; break; }
+        const bool tie_next = i + 1 < idx.size() && shifted[idx[i + 1]] == shifted[idx[i]];
+        if (cum >= p && !tie_next) { keep = i + 1; break; }
     }
+    keep = std::max(keep, std::min(min_keep, idx.size()));
 
     std::vector kept;
-    kept.reserve(last_idx);
-    for (size_t i = 0; i < last_idx; ++i) kept.push_back(s.c[idx[i]]);
+    kept.reserve(keep);
+    for (size_t i = 0; i < keep; ++i) kept.push_back(s.c[idx[i]]);
     s.c = std::move(kept);
     s.sorted = false;                       /* surprisal order is not logit order */
+    s.sort_desc();
 }
 
 void host_penalties(CandidateSet& s, const int32_t* history, int64_t n_history,
@@ -207,9 +210,8 @@ void host_penalties(CandidateSet& s, const int32_t* history, int64_t n_history,
         if (it == count.end()) continue;
         const int n = it->second;
 
-        /* The paper divides. Dividing makes a token with a negative logit MORE likely, which is
-         * obviously wrong, so everyone multiplies below zero instead. Upstream's comment says the
-         * same thing and the reference has to reproduce the fix, not the paper. */
+        /* The paper always divides, which makes a negative logit more likely; upstream
+         * multiplies below zero instead, and the reference follows upstream. */
         if (e.logit <= 0.0f) e.logit *= rep;
         else                 e.logit /= rep;
 
@@ -248,8 +250,7 @@ bool DryBreakers::is_single(int32_t t) const {
 }
 
 /* The longest prefix of `s` of at most `max` bytes that does not end inside a UTF-8 sequence.
- * Upstream truncates at the byte; cutting a character in half leaves a tail the tokeniser may
- * refuse, and a refused tail fails the whole request. */
+ * Upstream cuts at the byte, which can leave a tail the tokeniser refuses, failing the request. */
 static std::string utf8_prefix(const std::string& s, size_t max) {
     if (s.size() <= max) return s;
     size_t n = max;
@@ -270,17 +271,15 @@ int dry_prepare_breakers(const VocabView& vocab, const std::vector&
         return RAD_E_INVAL;
     }
 
-    /* Upstream: get_overlapping_token_sequences. A full vocabulary scan per breaker string, which
-     * is why this runs once per request on admission and never on the step path. */
+    /* Upstream: get_overlapping_token_sequences. A full vocabulary scan per breaker, so this runs
+     * once per request, never on the step path. */
     const int32_t n = vocab.n_tokens();
     for (const std::string& given : breakers) {
         const std::string str = utf8_prefix(given, kDryBreakerMaxBytes);
         if (str.empty()) continue;
 
-        /* THE TAIL DEPENDS ONLY ON WHERE THE BREAKER WAS SPLIT, not on which token covered its
-         * head: every token whose suffix is the breaker's first i bytes is completed by the
-         * tokenisation of the remaining bytes. So each split point is tokenised once rather than
-         * once per matching token -- a breaker that starts with a common byte matches thousands
+        /* The tail depends only on the split point i, not on which token covered the head, so
+         * each split is tokenised once. A breaker starting with a common byte matches thousands
          * of tokens, and tokenising is the expensive half of the scan. */
         std::vector> tail_at(str.size());
         std::vector have(str.size(), 0);
@@ -304,9 +303,7 @@ int dry_prepare_breakers(const VocabView& vocab, const std::vector&
                     std::vector& fresh = tail_at[i];
                     const int st = vocab.tokenize(str.substr(i), &fresh);
                     if (st < 0) {
-                        /* A breaker that cannot be tokenised is a breaker that silently stops
-                         * working, and a DRY request whose breakers vanished is a DRY request
-                         * that quietly changed behaviour. Say so. */
+                        /* Fail loudly rather than run DRY with a breaker missing. */
                         RAD_WARN("dry: sequence breaker \"%s\" does not tokenise (%s)",
                                  str.c_str(), rad_strerror(st));
                         out->seqs.clear();
@@ -363,26 +360,24 @@ void host_dry(CandidateSet& s, const int32_t* history, int64_t n_history,
     if (!history || n_history <= 0) return;
     if (total_context <= 0) total_context = n_history;
 
-    const int64_t effective = (p.penalty_last_n == -1) ? total_context
-                                                       : std::max(p.penalty_last_n, 0);
+    /* Any negative window is the whole context, as in sample_dry; upstream reads only -1 so. */
+    const int64_t effective = p.penalty_last_n < 0 ? total_context : (int64_t)p.penalty_last_n;
     const int n_rep = (int)std::min(std::min(n_history, effective), total_context);
     if (n_rep <= p.allowed_length) return;
 
-    /* rat(i): the i-th token counting back from the end of the window. Upstream reads it off a
-     * ring buffer; here the history is a flat array the scheduler already owns. */
+    /* rat(i): the i-th token counting back from the end of the window. Upstream reads a ring
+     * buffer; here the history is the scheduler's flat array. */
     auto rat = [&](int i) -> int32_t { return history[n_history - 1 - i]; };
 
     std::vector repeat_count((size_t)n_rep, 0);
     std::unordered_map max_token_repeat;
 
-    /* Step 1: a restart sequence bounds how long a repetition may be counted. Walking back from
-     * the end, the first token that heads a complete breaker sequence caps it. */
+    /* Step 1: the most recent complete breaker sequence caps the counted repeat length. */
     const int rep_limit = dry_rep_limit(breakers, history + (n_history - n_rep), n_rep);
     if (rep_limit < p.allowed_length) return;
 
-    /* Step 2: the Z-algorithm, run in reverse, giving for every position the length of the
-     * suffix that also appears ending there. Linear despite the nested loops, because lt/rt bound
-     * each token to one visit. */
+    /* Step 2: the Z-algorithm in reverse, giving for every position the length of the suffix
+     * that also ends there. Linear: lt/rt bound each token to one visit. */
     {
         const int last = n_rep - 1;
         int rt = 0, lt = 0;
@@ -408,8 +403,8 @@ void host_dry(CandidateSet& s, const int32_t* history, int64_t n_history,
         }
     }
 
-    /* Step 3: for every position that ends a long-enough repeat, the NEXT token would extend it.
-     * That token is the one to penalise, and by the length it would reach. */
+    /* Step 3: the token after each long-enough repeat would extend it; record the longest
+     * repeat per such token. */
     for (int i = 0; i < n_rep - 1; ++i) {
         const int len = repeat_count[(size_t)i];
         if (len < p.allowed_length) continue;
@@ -418,18 +413,17 @@ void host_dry(CandidateSet& s, const int32_t* history, int64_t n_history,
         if (it == max_token_repeat.end() || it->second < len) max_token_repeat[tok] = len;
     }
 
-    /* Step 4: an exponential penalty in the excess length, clamped so pow() cannot overflow a
-     * float -- log(FLT_MAX) is 88.72, and past that the penalty is infinite anyway. */
-    const float FLOAT_MAX_LOG = 88.7228391f;
+    /* Step 4: a penalty exponential in the excess length, with the exponent clamped so pow()
+     * cannot overflow a float (log(FLT_MAX) = 88.72). */
+    const float kFloatMaxLog = 88.7228391f;
     int max_exponent = 0;
-    if (p.base > 1.000001f) max_exponent = (int)(FLOAT_MAX_LOG / std::log(p.base));
+    if (p.base > 1.000001f) max_exponent = (int)(kFloatMaxLog / std::log(p.base));
 
     for (auto& e : s.c) {
         auto it = max_token_repeat.find(e.id);
         if (it == max_token_repeat.end()) continue;
 
-        /* A token that is itself a single-token breaker is exempt: penalising it would penalise
-         * the very thing that ends the repetition. */
+        /* A single-token breaker is exempt: it is what ends the repetition. */
         if (breakers.is_single(e.id)) continue;
 
         int exp_n = it->second - p.allowed_length;
@@ -443,12 +437,13 @@ void host_dry(CandidateSet& s, const int32_t* history, int64_t n_history,
 
 void host_xtc(CandidateSet& s, float probability, float threshold, size_t min_keep,
               uint64_t seed, uint64_t pos) {
-    if (probability <= 0.0f || threshold > 0.5f || s.c.size() < 2) return;
+    /* threshold <= 0 is off, as in sample_xtc. Upstream fires and keeps only the least probable
+     * candidate, since every candidate is at or above 0. */
+    if (probability <= 0.0f || !(threshold > 0.0f) || threshold > 0.5f || s.c.size() < 2) return;
 
-    /* Its own RNG stream: XTC's coin and the pick must not be the same number, or a request
-     * whose XTC fires becomes a request whose pick is correlated with that fact. It fires when
-     * the uniform is BELOW the probability, the comparison `sample_xtc` makes, so the two agree
-     * on the draw that lands exactly on it. */
+    /* A separate RNG stream, so the pick is not correlated with XTC firing. Fires when the
+     * uniform is below the probability, the comparison `sample_xtc` makes, so a draw exactly on
+     * it agrees. */
     if (rng_uniform(seed, pos, RAD_RNG_XTC) >= probability) return;
 
     host_softmax(s, true);
@@ -459,8 +454,7 @@ void host_xtc(CandidateSet& s, float probability, float threshold, size_t min_ke
         else break;
     }
 
-    /* Drop everything above the threshold EXCEPT the least probable of them. That is the whole
-     * idea: remove the obvious continuation, not the unlikely ones. */
+    /* Drop everything above the threshold except the least probable of them. */
     if (s.c.size() - pos_last >= min_keep && pos_last > 0)
         s.c.erase(s.c.begin(), s.c.begin() + (std::ptrdiff_t)pos_last);
 }
@@ -485,17 +479,14 @@ int32_t host_pick(CandidateSet& s, uint64_t seed, uint64_t pos) {
     float max_l = -INFINITY;
     for (const auto& e : s.c) max_l = std::max(max_l, e.logit);
     if (!(max_l > -INFINITY)) {
-        /* Every candidate is -inf. That is a fully-masked distribution, which is a grammar that
-         * admits nothing -- a real failure, not a token. The caller fails the request. */
+        /* Fully masked: the grammar admits nothing. The caller fails the request. */
         s.selected = -1;
         return -1;
     }
     if (s.c.size() == 1) { s.selected = 0; s.c[0].p = 1.0f; return s.c[0].id; }
 
-    /* DESCENDING LOGIT, ties to the lower id, not the set's current order. Any fixed order
-     * samples correctly, but a total order makes the answer a property of the uniform rather than
-     * of how the previous stage happened to permute the set -- and this is the order sample_pick
-     * walks, since sample_topk leaves its candidates in it. */
+    /* Walk in descending logit, ties to the lower id, independent of the set's current order.
+     * This is the order sample_pick walks, since sample_topk leaves its candidates in it. */
     std::vector order(s.c.size());
     std::iota(order.begin(), order.end(), (size_t)0);
     std::stable_sort(order.begin(), order.end(), [&](size_t a, size_t b) {
@@ -509,9 +500,8 @@ int32_t host_pick(CandidateSet& s, uint64_t seed, uint64_t pos) {
 
     const double want = (double)rng_uniform(seed, pos, RAD_RNG_PICK) * total;
 
-    /* A candidate at -infinity is never chosen, and the fall-through is the last one above it: a
-     * draw at the very top of the range can walk past every comparison in floating point, and
-     * the candidates behind the last real one are the grammar-masked ones. */
+    /* A -inf candidate is never chosen. A draw at the top of the range can pass every
+     * comparison in floating point, so the fall-through is the last finite candidate. */
     double  acc = 0.0;
     size_t  chosen = order.front();
     for (size_t i : order) {
@@ -538,59 +528,52 @@ int32_t host_argmax(const float* logits, int64_t n_vocab) {
 
 /* ================================================================== the chain */
 
-static int32_t argmax_of(const CandidateSet& s) {
-    if (s.c.empty()) return -1;
-    size_t best = 0;
-    for (size_t i = 1; i < s.c.size(); ++i) {
-        if (s.c[i].logit > s.c[best].logit) best = i;
-        else if (s.c[i].logit == s.c[best].logit && s.c[i].id < s.c[best].id) best = i;
-    }
-    if (!(s.c[best].logit > -INFINITY)) return -1;   /* everything masked out */
-    return s.c[best].id;
-}
-
 int32_t host_sample_into(CandidateSet& s, const SamplingParams& sp, const HostRefInput& in,
                          ChainOrder order) {
-    /* Penalties first in both orders, because they act on raw logits and every cut below acts on
-     * probabilities derived from them. */
+    /* Penalties first in both orders: they act on raw logits, the cuts on probabilities. */
     host_penalties(s, in.history, in.n_history, sp.penalty_last_n,
                    sp.rep_penalty, sp.freq_penalty, sp.pres_penalty);
 
-    if (sp.dry_multiplier > 0.0f && in.dry_breakers) {
+    /* DRY runs without breakers, as the device chain does; breakers only cap the repeat length.
+     * An allowed length below 1 is 2, as sample_dry reads it (admission refuses one). */
+    if (sp.dry_multiplier > 0.0f) {
+        static const DryBreakers kNone;
         DryParams dp;
         dp.multiplier     = sp.dry_multiplier;
         dp.base           = sp.dry_base;
-        dp.allowed_length = sp.dry_allowed_length;
+        dp.allowed_length = sp.dry_allowed_length > 0 ? sp.dry_allowed_length : 2;
         dp.penalty_last_n = sp.dry_penalty_last_n;
-        host_dry(s, in.history, in.n_history, in.total_context, dp, *in.dry_breakers);
+        host_dry(s, in.history, in.n_history, in.total_context, dp,
+                 in.dry_breakers ? *in.dry_breakers : kNone);
     }
 
-    /* THE GREEDY PATH SKIPS THE CHAIN, and it masks BEFORE it picks. Ordering matters here in a
-     * way that is easy to get wrong: temperature 0 collapses every other logit to -inf, so a
-     * mask applied afterwards can leave nothing at all. A greedy sequence is therefore
-     * penalties -> mask -> argmax, not the chain with temp=0 threaded through it. */
+    /* Greedy skips the chain: penalties -> mask -> argmax. Temperature 0 collapses every other
+     * logit to -inf, so a mask applied after it could leave nothing. */
     if (sp.greedy()) {
         host_mask(s, in.bitmask, in.n_words);
-        const int32_t tok = argmax_of(s);
-        for (size_t i = 0; i < s.c.size(); ++i) if (s.c[i].id == tok) { s.selected = (int)i; break; }
-        return tok;
+        if (s.c.empty()) return -1;
+        const size_t best = best_index(s);
+        if (!(s.c[best].logit > -INFINITY)) return -1;   /* everything masked out */
+        s.selected = (int)best;
+        return s.c[best].id;
     }
 
     if (order == ChainOrder::Radiance) {
         /* `temp_last` moves temperature behind the cuts, as the device chain moves it onto the
-         * candidate plane (Sampler::issue); the cuts keep this order either way. */
+         * candidate plane (Sampler::run). */
         if (!sp.temp_last) host_temp(s, sp.temp);
         host_mask(s, in.bitmask, in.n_words);
-        host_top_k(s, sp.top_k);
+        /* sample_topk narrows every row to the candidate width; top_k 0 is that width. */
+        const int64_t width = in.max_candidates > 0 ? in.max_candidates : (int64_t)s.c.size();
+        host_top_k(s, (int32_t)(sp.top_k > 0 ? std::min(sp.top_k, width) : width));
         host_top_p(s, sp.top_p, 1);
         host_min_p(s, sp.min_p, 1);
         host_typical(s, sp.typical_p, 1);
         host_xtc(s, sp.xtc_probability, sp.xtc_threshold, 1, sp.seed, in.pos);
         if (sp.temp_last) host_temp(s, sp.temp);
     } else {
-        /* llama.cpp's default order, for checking this port against llama.cpp itself. Note the
-         * absence of top-n-sigma: it is not in SamplingParams and radiance does not ship it, so a
-         * comparison that enables it upstream will disagree here and should. */
+        /* llama.cpp's default order, for checking this port against llama.cpp. Top-n-sigma is
+         * not in SamplingParams, so a comparison that enables it upstream will disagree. */
         host_mask(s, in.bitmask, in.n_words);
         host_top_k(s, sp.top_k);
         host_typical(s, sp.typical_p, 1);
diff --git a/core/sample/host_ref.h b/core/sample/host_ref.h
index b5ceff76..c7155d16 100644
--- a/core/sample/host_ref.h
+++ b/core/sample/host_ref.h
@@ -1,39 +1,28 @@
 /* host_ref.h -- the host reference sampling chain.
  *
- * Sampling runs on device (spec §13): at a 151K vocab and batch 256 the logits are ~77 MiB a
- * step, and moving them across the link to run a host chain costs the bandwidth AND a
- * synchronisation, on the step path, at exactly the concurrency the engine exists to serve. So
- * every sampler is a kernel, not a lift.
+ * Sampling runs on device (spec §13) through the declared sampler ops, whose oracle is libref
+ * (spec §17). This is a second, independent formulation of the same chain: llama.cpp's samplers
+ * ported to plain C++ over a float array, with no llama.cpp or ggml dependency, following
+ * `src/llama-sampler.cpp` at upstream commit 06938ac12 (MIT). sample_test holds the sampler
+ * driver's chain (Sampler over libref) to it row by row, and Sampler::logprobs_for uses host_dry to
+ * undo DRY.
  *
- * This file is the other half of that sentence. A fallback you cannot test against is just an
- * untested slow path (spec §17), so the device samplers need an oracle, and the oracle is
- * llama.cpp's chain ported to plain C++ over a float array. Ported, not linked: there are no
- * llama.cpp headers here and no ggml, because a reference that drags a second engine in is a
- * dependency, and this is a reference. Each individual sampler below reproduces the semantics of
- * its counterpart in llama.cpp `src/llama-sampler.cpp` at upstream commit 06938ac12 (MIT),
- * including its edge cases, because reproducing the happy path only is how a comparison harness
- * agrees with the thing it is checking and both are wrong.
+ * Where upstream and the op chain differ, this follows the chain, which is the contract:
  *
- * TWO THINGS DEVIATE FROM UPSTREAM, DELIBERATELY.
+ * 1. Chain order. llama.cpp's default is penalties, DRY, top-n-sigma, top-k, typical, top-p,
+ *    min-p, XTC, temperature last. Radiance follows the spec and vLLM (see ChainOrder::Radiance).
+ *    Top-p, min-p and typical cut on probabilities, so running temperature first changes which
+ *    tokens survive. ChainOrder::LlamaCpp keeps upstream's order for checking this port against
+ *    llama.cpp itself.
  *
- * 1. THE CHAIN ORDER. llama.cpp's default chain is penalties, DRY, top-n-sigma, top-k, typical,
- *    top-p, min-p, XTC, TEMPERATURE LAST. Radiance's order is the spec's and vLLM's: penalties,
- *    temperature, grammar mask, top-k, then top-p / min-p / typical, then the pick. The
- *    difference is not cosmetic -- top-p, min-p and typical all cut on probabilities, so whether
- *    temperature ran first changes which tokens survive. Radiance's device kernels run the
- *    radiance order (it is the order every OpenAI-compatible server is measured against), so
- *    ChainOrder::Radiance is what rad-kbench compares against. ChainOrder::LlamaCpp exists so
- *    this file can also be checked against llama.cpp itself, which is the only way to know the
- *    port is faithful.
+ * 2. RNG. Upstream keeps a stateful std::mt19937 per sampler, which a kernel cannot hold per
+ *    sequence and which makes results depend on batch composition. Here randomness is a pure
+ *    function of (seed, position, stream): abi/rad_sample.h's draw, bit for bit, with the same
+ *    per-stream keys, so the host sees exactly the uniforms the device stages see.
  *
- * 2. THE RNG. Upstream carries a stateful std::mt19937 per sampler. That cannot be a device
- *    kernel: a kernel has no place to keep a Mersenne twister's 624 words of state per sequence,
- *    and a stateful generator makes the answer depend on how many draws happened earlier, which
- *    makes a comparison run irreproducible the moment the batch composition changes. Here the
- *    randomness is a pure function of (seed, position, stream) -- counter-based, stateless, and
- *    reproducible across a run with different batching. It is abi/rad_sample.h's draw, bit for
- *    bit, with the same per-stream keys, so the pick and XTC's coin here see exactly the uniforms
- *    the device stages see.
+ * 3. Values. top_p, typical_p or xtc_threshold at or below 0 turns the stage off; typical keeps
+ *    every candidate tied at its cut; a negative DRY window is the whole context; and top_k 0 is
+ *    the candidate width (HostRefInput::max_candidates), not the whole vocabulary.
  */
 #pragma once
 #include "../rad_core.h"
@@ -49,16 +38,15 @@ namespace rad {
 /* ================================================================== the candidate set */
 
 /* One candidate. `p` is meaningless until a softmax has run over the set; the samplers that need
- * it call one themselves, exactly as upstream's do. */
+ * it call one themselves, as upstream's do. */
 struct Candidate {
     int32_t id    = 0;
     float   logit = 0.0f;
     float   p     = 0.0f;
 };
 
-/* The set the chain narrows. `sorted` tracks descending-by-logit order, because half the
- * samplers upstream have a fast path that depends on it and a slow path that does not, and
- * dropping the flag silently changes which one runs. */
+/* The set the chain narrows. `sorted` tracks descending-by-logit order; many upstream samplers
+ * take a different path when it is set, so it must stay accurate. */
 struct CandidateSet {
     std::vector c;
     bool sorted   = false;
@@ -71,26 +59,21 @@ struct CandidateSet {
 
 /* ================================================================== reproducible randomness */
 
-/* A counter-based generator: bits are a pure function of the three coordinates, so the same draw
- * comes out on the host reference and in the device kernel, in any batch order, at any batch
- * size. It IS rad_sample_uniform01 from abi/rad_sample.h -- splitmix64 over
- * ((seed ^ key) * golden ratio + pos) -- because a reference with its own generator agrees with
- * the device on no seeded draw at all.
+/* Counter-based generator: bits are a pure function of the three coordinates, so host and device
+ * draw the same number in any batch order or size. It is rad_sample_uniform01 from
+ * abi/rad_sample.h, splitmix64 over ((seed ^ key) * golden ratio + pos).
  *
- * `pos` is the sequence's output position -- token index within this request's generation -- so
- * a request's draws depend on where it is, not on when it was scheduled. `stream` separates
- * independent draws taken at the same position (the pick, XTC's coin, speculative acceptance's
- * uniforms) so they are not the same number; each maps to its RAD_SAMPLE_KEY_* key. */
+ * `pos` is the output position (token index within this request's generation), so draws depend on
+ * where a request is, not when it was scheduled. `stream` separates independent draws at the same
+ * position; each maps to its RAD_SAMPLE_KEY_* key. */
 enum : uint32_t {
     RAD_RNG_PICK    = 0,   /* the final categorical draw */
-    RAD_RNG_XTC     = 1,   /* XTC's "does this fire at all" coin */
-    RAD_RNG_ACCEPT  = 2,   /* speculative acceptance, one per draft position (see accept.h) */
-    RAD_RNG_RESID   = 3    /* the residual draw after a speculative rejection */
+    RAD_RNG_XTC     = 1    /* XTC's "does this fire at all" coin */
 };
 
 uint64_t rng_bits(uint64_t seed, uint64_t pos, uint32_t stream);
-/* Uniform in [0,1). 24 bits of mantissa: a float cannot resolve more, and pretending otherwise
- * would make the host and the device disagree in the last place. */
+/* Uniform in [0,1) with 24 bits, the most a float resolves; more would let host and device
+ * disagree in the last place. */
 float    rng_uniform(uint64_t seed, uint64_t pos, uint32_t stream);
 
 /* ================================================================== individual samplers */
@@ -99,39 +82,42 @@ float    rng_uniform(uint64_t seed, uint64_t pos, uint32_t stream);
 void host_softmax(CandidateSet& s, bool do_sort);
 
 /* Upstream: llama_sampler_temp_impl. temp <= 0 collapses to the argmax by setting every other
- * logit to -inf, which is what keeps a temperature-0 request bit-identical to a greedy one. */
+ * logit to -inf, keeping a temperature-0 request identical to a greedy one. */
 void host_temp(CandidateSet& s, float temp);
 
-/* Upstream: llama_sampler_top_k_impl. k <= 0 is off. */
+/* Upstream: llama_sampler_top_k_impl. k <= 0 is off; host_sample passes the candidate width for
+ * top_k 0 (see HostRefInput::max_candidates). */
 void host_top_k(CandidateSet& s, int32_t k);
 
-/* Upstream: llama_sampler_top_p_apply. Ties AT the threshold are all kept, which can overshoot
- * p by the mass of the tie -- the alternative is inventing an order among equal probabilities. */
+/* Upstream: llama_sampler_top_p_apply. Keeps the shortest prefix in descending logit order, ties
+ * to the lower id, whose mass reaches p, so a tie at the threshold is split by id as sample_topp
+ * splits it. p <= 0 is off. */
 void host_top_p(CandidateSet& s, float p, size_t min_keep);
 
 /* Upstream: llama_sampler_min_p_apply. A floor relative to the mode, not an absolute one. */
 void host_min_p(CandidateSet& s, float p, size_t min_keep);
 
-/* Upstream: llama_sampler_typical_apply. Keeps the candidates whose surprisal is closest to the
- * distribution's entropy, which is not the same set as the most probable ones. */
+/* Upstream: llama_sampler_typical_apply, with sample_typical's cut. Keeps the candidates whose
+ * surprisal is closest to the distribution's entropy, not the most probable ones: everything at or
+ * below the smallest distance whose candidates carry at least p, ties at that distance included
+ * (upstream cuts a prefix at mass > p). Zero-probability candidates go. p <= 0 is off. The result
+ * is in descending logit order. */
 void host_typical(CandidateSet& s, float p, size_t min_keep);
 
-/* Upstream: llama_sampler_penalties_apply, with the history passed in rather than accumulated in
- * a ring buffer. The scheduler already owns each request's token history, and a sampler that
- * kept its own copy would be a second place for it to be wrong.
- *
- * `history` is the sequence's tokens, oldest first; only the last `last_n` are counted. */
+/* Upstream: llama_sampler_penalties_apply, with the history passed in instead of kept in a ring
+ * buffer; the scheduler owns each request's token history. `history` is oldest first; only the
+ * last `last_n` tokens are counted. */
 void host_penalties(CandidateSet& s, const int32_t* history, int64_t n_history,
                     int32_t last_n, float rep, float freq, float pres);
 
-/* DRY's sequence breakers, resolved to token sequences once per request rather than per step.
- * Upstream calls this `dry_processed_breakers` and builds it from the vocabulary; the cost is a
- * full vocabulary scan per breaker string, which is why it does not belong on the step path.
+/* DRY's sequence breakers, resolved to token sequences once per request (upstream's
+ * `dry_processed_breakers`). Each breaker costs a full vocabulary scan, so this stays off the
+ * step path.
  *
- * `seqs` maps a HEAD token to the tails that complete a breaker after it; an empty tail means the
- * head token contains a whole breaker by itself. The two bitsets over the vocabulary answer the
- * two questions the step path asks per token -- "does anything start here" and "is this token a
- * whole breaker" -- with one load, where the multimap is a hash lookup a token. */
+ * `seqs` maps a head token to the tails that complete a breaker after it; an empty tail means the
+ * head token holds a whole breaker. The bitsets answer the step path's two per-token questions
+ * (does a breaker start here, is this token a whole breaker) with one load instead of a hash
+ * lookup. */
 struct DryBreakers {
     std::unordered_multimap> seqs;
     std::vector heads;     /* bit t: token t heads at least one breaker sequence */
@@ -140,7 +126,7 @@ struct DryBreakers {
     bool empty() const { return seqs.empty(); }
 
     /* Build the two bitsets from `seqs`. dry_prepare_breakers calls it; a set filled by hand is
-     * answered from the multimap until it is indexed, so the two ways of building one agree. */
+     * answered from the multimap until indexed, so both answer the same. */
     void index(int32_t n_vocab);
     bool is_head(int32_t t) const;
     bool is_single(int32_t t) const;
@@ -152,29 +138,25 @@ private:
     }
 };
 
-/* THE BOUNDS ON WHAT A REQUEST MAY ASK THE BREAKER SCAN TO DO. Each breaker costs a pass over the
- * whole vocabulary on the scheduler thread, once per rank, so an unbounded list stalls every
- * sequence on the server for as long as the scan takes. Upstream truncates a breaker to 40 bytes
- * and its token tail to 20 tokens (llama_sampler_init_dry); the count bound is this engine's own,
- * well above the four breakers clients send by default, and a request over it is refused at
- * admission by name rather than silently shortened. */
+/* Bounds on the breaker scan. Each breaker is a full-vocabulary pass on the scheduler thread,
+ * once per rank, stalling every sequence while it runs. Upstream truncates a breaker to 40 bytes
+ * and its tail to 20 tokens (llama_sampler_init_dry). The count bound is this engine's own, well
+ * above the four breakers clients send by default; a request over it is refused at admission. */
 constexpr size_t kDryMaxBreakers      = 16;
 constexpr size_t kDryBreakerMaxBytes  = 40;
 constexpr int    kDryBreakerMaxTail   = 20;
 
-/* Upstream: get_overlapping_token_sequences, per breaker, with upstream's truncation of each
- * breaker to kDryBreakerMaxBytes (cut back to a UTF-8 boundary, so the tail still tokenises) and
- * of each tail to `max_tail_len` tokens. Refuses more than kDryMaxBreakers breakers with
- * RAD_E_INVAL. Returns RAD_E_UNSUPPORTED if the view has no tokeniser, because a DRY request
- * whose breakers silently became empty is a DRY request that quietly stopped working. */
+/* Upstream: get_overlapping_token_sequences, per breaker, truncating each breaker to
+ * kDryBreakerMaxBytes (cut back to a UTF-8 boundary so the tail still tokenises) and each tail to
+ * `max_tail_len` tokens. More than kDryMaxBreakers is RAD_E_INVAL. RAD_E_UNSUPPORTED if the view
+ * has no tokeniser, rather than silently running DRY without breakers. */
 int dry_prepare_breakers(const VocabView& vocab, const std::vector& breakers,
                          DryBreakers* out, int max_tail_len = kDryBreakerMaxTail);
 
-/* Upstream's step 1 of llama_sampler_dry_apply: walking back from the end of `window` (n tokens,
- * oldest first), the first token that heads a COMPLETE breaker sequence caps how long a repeat
- * may be counted. Returns that cap, or n when no breaker completes inside the window. Shared by
- * host_dry and the sampler's per-step staging, so the reference and the device stage are handed
- * the same limit. */
+/* Step 1 of upstream's llama_sampler_dry_apply: walking back from the end of `window` (n tokens,
+ * oldest first), the first token that heads a complete breaker sequence caps the counted repeat
+ * length. Returns that cap, or n when no breaker completes in the window. Shared by host_dry and
+ * the sampler's per-step staging, so reference and device use the same limit. */
 int dry_rep_limit(const DryBreakers& breakers, const int32_t* window, int n);
 
 struct DryParams {
@@ -190,39 +172,39 @@ void host_dry(CandidateSet& s, const int32_t* history, int64_t n_history,
               int64_t total_context, const DryParams& p, const DryBreakers& breakers);
 
 /* Upstream: llama_sample_xtc_apply. Fires with probability `probability`; when it fires it drops
- * every candidate above the threshold except the least probable of them, which is the point --
- * it removes the obvious continuation rather than the unlikely ones. */
+ * every candidate above the threshold except the least probable of them, removing the obvious
+ * continuations. threshold <= 0 is off, as in sample_xtc. */
 void host_xtc(CandidateSet& s, float probability, float threshold, size_t min_keep,
               uint64_t seed, uint64_t pos);
 
-/* The grammar mask. One bit per token, set means admissible; a cleared bit takes the logit to
- * -inf rather than removing the candidate, so the mask composes with everything downstream
- * without renumbering anything. `n_words` is ceil(n_vocab/32). */
+/* The grammar mask. One bit per token, set means admissible; a cleared bit sets the logit to -inf
+ * instead of removing the candidate, so nothing downstream is renumbered. `n_words` is
+ * ceil(n_vocab/32). */
 void host_mask(CandidateSet& s, const uint32_t* bitmask, int64_t n_words);
 
-/* The pick. Inverse CDF over the surviving candidates in DESCENDING LOGIT ORDER, ties to the lower
- * id -- a total order, so the answer is a property of the uniform rather than of how the previous
- * stage happened to permute the set, and the order `sample_pick` walks the candidate set the
- * top-k leaves (and the order upstream's dist sampler walks a sorted set in). A candidate at
- * -infinity -- a grammar-masked logit -- is never returned, including by the fall-through a draw
- * at the very top of the range takes. Returns the token id, or -1 for an empty or fully masked
- * set. */
+/* The pick. Inverse CDF over the surviving candidates in descending logit order, ties to the
+ * lower id. A total order makes the result depend only on the uniform, and it is the order
+ * `sample_pick` walks top-k's output (and upstream's dist sampler walks a sorted set). A -inf
+ * (grammar-masked) candidate is never returned, even by the fall-through at the top of the range.
+ * Returns the token id, or -1 for an empty or fully masked set. */
 int32_t host_pick(CandidateSet& s, uint64_t seed, uint64_t pos);
 
-/* Argmax over raw logits, lowest id winning a tie. The greedy path skips the chain entirely, so
- * this must agree with what host_temp(0) + host_pick would produce or a temperature-0 request
- * stops matching a greedy one. */
+/* Argmax over raw logits, lowest id winning a tie. The greedy path skips the chain, so this must
+ * agree with host_temp(0) + host_pick. */
 int32_t host_argmax(const float* logits, int64_t n_vocab);
 
 /* ================================================================== the chain */
 
+/* The candidate width every stage after top-k works in, SamplerConfig::max_candidates' default. */
+constexpr int64_t kSampleCandidates = 1024;
+
 enum class ChainOrder {
     Radiance = 0,   /* penalties, DRY, temperature, mask, top-k, top-p/min-p/typical, XTC, pick */
     LlamaCpp = 1    /* penalties, DRY, top-k, typical, top-p, min-p, XTC, temperature, pick */
 };
 
-/* Everything the chain needs that is not in SamplingParams. Kept separate because SamplingParams
- * is frozen in rad_core.h and these are per-step facts, not per-request settings. */
+/* Per-step inputs the chain needs beyond SamplingParams, which is frozen in rad_core.h and holds
+ * per-request settings. */
 struct HostRefInput {
     const int32_t* history   = nullptr;   /* the sequence's tokens so far, oldest first */
     int64_t        n_history = 0;
@@ -230,16 +212,18 @@ struct HostRefInput {
     const uint32_t* bitmask  = nullptr;   /* grammar mask, or null */
     int64_t        n_words   = 0;
     uint64_t       pos       = 0;         /* output position: the RNG's second coordinate */
-    const DryBreakers* dry_breakers = nullptr;
+    const DryBreakers* dry_breakers = nullptr;   /* null runs DRY with no breakers */
+    /* The chain's candidate width (SamplerConfig::max_candidates): top-k narrows every row to
+     * at most this many, so top_k 0 samples from the most likely kSampleCandidates tokens. 0 is
+     * the whole vocabulary. Read by ChainOrder::Radiance only. */
+    int64_t        max_candidates = kSampleCandidates;
 };
 
-/* Run the whole chain over one row of logits and return the token. This is what rad-kbench
- * compares the device sampler against, per sequence, on the same logits. */
+/* Run the whole chain over one row of logits and return the token. */
 int32_t host_sample(const float* logits, int64_t n_vocab, const SamplingParams& sp,
                     const HostRefInput& in, ChainOrder order = ChainOrder::Radiance);
 
-/* The same, leaving the narrowed candidate set behind for a caller that wants to inspect it --
- * rad-kbench reports which stage diverged, and it cannot do that from a token id alone. */
+/* As host_sample, leaving the narrowed candidate set for inspection. */
 int32_t host_sample_into(CandidateSet& s, const SamplingParams& sp, const HostRefInput& in,
                          ChainOrder order = ChainOrder::Radiance);
 
diff --git a/core/sample/sampler.cpp b/core/sample/sampler.cpp
index 1432bc21..68b58a2e 100644
--- a/core/sample/sampler.cpp
+++ b/core/sample/sampler.cpp
@@ -1,5 +1,5 @@
 /* sampler.cpp -- the sampler driver: declare the sampler ops, build the per-sequence parameter
- * array once per step, issue the chain. No sampler is implemented here; see sampler.h for why.
+ * array once per step, issue the chain. No sampler is implemented here; see sampler.h.
  */
 #include "sampler.h"
 #include "gbnf.h"
@@ -13,22 +13,18 @@ namespace rad {
 
 /* ================================================================== grammar triggers
  *
- * A chat template names its triggers the way a person would -- "the call starts at the word
- * " -- while GbnfGrammar wants them in the two forms it checks as tokens arrive: token
- * ids to compare against the id just emitted, and literal words to find in the emitted bytes.
- * The translation needs a vocabulary, so it happens here and not in the server.
+ * Translates a chat template's triggers into the two forms GbnfGrammar checks as tokens arrive:
+ * token ids compared against the emitted id, and literal words searched in the emitted bytes.
+ * This needs the vocabulary, so it happens here rather than in the server.
  *
- * A WORD IS A TOKEN WHEN THE VOCABULARY SAYS SO. The word is tokenised with special tokens
- * recognised, since a template's markers are usually special tokens and a split of ``
- * into `<`, `tool`, `_call`, `>` is not what the model emits. One token makes an id trigger, which
- * costs a comparison; anything longer is scanned for as bytes, because the tokeniser may split it
- * differently depending on what came before it. Getting this wrong does not fail loudly -- it
- * yields a trigger that never fires, so the call comes out unconstrained, which reads as a model
- * that writes malformed calls.
+ * A word is tokenised with special tokens recognised, since template markers such as
+ * `` are usually special tokens. If it is one token it becomes an id trigger;
+ * otherwise it is matched as bytes, because the tokeniser may split it differently depending on
+ * context. A wrong translation fails silently: the trigger never fires and the call comes out
+ * unconstrained.
  *
- * A REGULAR-EXPRESSION TRIGGER IS REFUSED. Its matcher would run over the reply once per token
- * on the scheduler thread; the templates in service all trigger on words. A request whose
- * template needs one is refused at admission, naming the pattern. */
+ * Regular-expression triggers are refused at admission, naming the pattern; their matcher would
+ * run over the reply once per token on the scheduler thread. */
 static int resolve_triggers(const VocabView& vocab,
                             const std::vector& triggers,
                             std::vector* words, std::vector* tokens,
@@ -69,12 +65,16 @@ static int resolve_triggers(const VocabView& vocab,
     return RAD_OK;
 }
 
+/* A lazy grammar waits for a trigger before it constrains anything, so one without a trigger
+ * would leave the whole reply unconstrained. */
+static const char* const kLazyNoTrigger =
+    "a lazy grammar needs at least one word or token trigger; without one it never constrains";
+
 /* ================================================================== small helpers */
 
-/* Copy this rank's window out of a whole-vocabulary bitmask. `vocab_off` is word-aligned for
- * every shard this engine builds (the head is split on a multiple of 32), so the aligned arm is
- * the one that runs; the bit-shifting arm exists because a shard boundary is a placement decision
- * and not a promise, and a mask that is silently off by a few bits admits the wrong tokens. */
+/* Copy this rank's window out of a whole-vocabulary bitmask. The engine splits the head on a
+ * multiple of 32, so `vocab_off` is normally word-aligned; the bitwise path covers any other
+ * shard boundary, where a misaligned copy would admit the wrong tokens. */
 void Sampler::shard_mask(uint32_t* dst) const {
     const int64_t full = (int64_t)mask_full_.size();
     std::memset(dst, 0, (size_t)mask_words_ * 4);
@@ -92,21 +92,14 @@ void Sampler::shard_mask(uint32_t* dst) const {
     }
 }
 
-/* rad_runtime.h's RAD_B / RAD_W macros are C compound literals. They are legal C++ only as a
- * compiler extension, and this file is core code that has to build with -Wall -Wextra clean, so
- * the operands are built the ordinary way. */
-/* NARROWED TO THIS STEP'S ROWS, always.  arch/common/rad_arch.h says why for the model's own
- * buffers and the reason is the sampler's too: a kernel cannot read the row count out of `M`,
- * because `M` is the band's upper bound, so every shim takes it off the operand.  Handed over at
- * its DECLARED extent -- max_seqs * (max_spec + 1) rows -- an operand makes every stage compute a
- * full candidate set for rows that have no request behind them, over params the upload never
- * wrote.  The extra rows are discarded, so nothing downstream is wrong and no bench can see it,
- * but each phantom row costs a vocabulary-wide reduction, and at one sequence every row but one
- * is a phantom.
+/* rad_runtime.h's RAD_B / RAD_W macros are C compound literals, legal C++ only as an extension,
+ * and core code builds -Wall -Wextra clean, so operands are built the ordinary way. */
+/* Operands are always narrowed to this step's rows. `M` is only the band's upper bound, so
+ * kernels take the row count from the operand (arch/common/rad_arch.h); at the declared extent,
+ * max_seqs * (max_spec + 1), every stage would do a vocabulary-wide reduction for each empty row.
  *
- * `rows` is dim 0 for every buffer here -- logits, params, history, mask, candidates, pairs, the
- * gather and the token output all count sampled POSITIONS first -- and the strides below it are
- * products of the trailing dimensions, so shortening the outermost one leaves them correct. */
+ * Every buffer here has sampled positions as dim 0, and its strides are products of the trailing
+ * dimensions, so shortening dim 0 leaves them correct. */
 static RadOperand opd_rows(rad_buf h, int64_t rows) {
     RadOperand o{};
     o.kind = RAD_OPK_BUF;
@@ -115,9 +108,8 @@ static RadOperand opd_rows(rad_buf h, int64_t rows) {
     return o;
 }
 
-/* An optional operand this issue does not pass. The runtime holds every issue to its schema's
- * operand COUNT -- operands are positional -- so an absent trailing optional is spelled, not
- * dropped. */
+/* An absent optional operand. Operands are positional and the runtime checks an issue against
+ * the schema's operand count, so a missing trailing optional must be passed as this. */
 static RadOperand opd_none() {
     RadOperand o{};
     o.kind = RAD_OPK_NONE;
@@ -125,9 +117,8 @@ static RadOperand opd_none() {
 }
 
 static int64_t rows_for(const SamplerConfig& c) {
-    /* One row per SAMPLED POSITION, not per sequence: a speculative verify samples n_spec+1
-     * positions for a sequence and each one has its own output position, hence its own RNG
-     * coordinate. Sizing for the worst step is the same rule the arena follows (spec §3.1). */
+    /* One row per sampled position: a verify samples n_spec+1 positions per sequence, each with
+     * its own RNG coordinate. Sized for the worst step, as the arena is (spec §3.1). */
     return c.max_seqs * (int64_t)(c.max_spec + 1);
 }
 
@@ -144,15 +135,11 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
     cfg_ = cfg;
     if (cfg_.n_vocab_local <= 0) cfg_.n_vocab_local = cfg_.n_vocab / cfg_.world_size;
 
-    /* THE STAGED MASK IS THIS RANK'S SHARD, AND THE GRAMMAR'S IS THE WHOLE VOCABULARY. Those are
-     * different lengths the moment the head is sharded, and conflating them is silent: every
-     * vocab-scoped sampler op is declared over `n_vocab_local` (op_vocab, below) and `sample_mask`
-     * indexes its bitmask from bit zero, so a full-vocabulary mask handed to rank 1 masks its
-     * logits with the admissibility of tokens 0..n_local -- ids that belong to rank 0. The result
-     * is not a diagnosable error, it is a rank sampling from the wrong permission set.
-     *
-     * So the grammar fills `mask_full_` over the whole vocabulary, which is also where the "no
-     * token is admissible anywhere" check belongs, and only this rank's window of it is staged. */
+    /* The staged mask covers this rank's shard; the grammar's covers the whole vocabulary.
+     * `sample_mask` indexes its bitmask from bit zero over `n_vocab_local`, so handing rank 1 the
+     * full mask would apply rank 0's token admissibility to it. The grammar therefore fills
+     * `mask_full_` (where the "nothing admissible anywhere" check belongs) and only this rank's
+     * window is staged. */
     mask_words_ = grammar_mask_words(cfg_.n_vocab_local);
     mask_full_.assign((size_t)grammar_mask_words(cfg_.n_vocab), 0u);
 
@@ -161,10 +148,9 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
     const int64_t ncand = cfg_.max_candidates;
 
     /* ---------------------------------------------------------- buffers */
-    /* PERSIST, not TRANSIENT: the parameter, history and mask planes are written by an upload
-     * that happens BEFORE the run phase issues anything, so liveness over the declared op list
-     * would conclude they are dead where they are in fact being filled. A transient whose first
-     * definition is invisible to the planner is a transient the planner will happily overwrite. */
+    /* The staging planes are PERSIST: they are filled by an upload before any op is issued, which
+     * the planner's liveness over the op list cannot see, so as TRANSIENT they would be
+     * overwritten. */
     auto decl = [&](const char* name, uint32_t dt, int64_t d0, int64_t d1, int kind) -> rad_buf {
         RadBufDecl d{};
         d.dtype = dt;
@@ -181,44 +167,39 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
     buf_params_late_ = decl("sampler.params_late", RAD_U32, rows,
                             (int64_t)(sizeof(DeviceSampleParams) / 4), RAD_BUF_PERSIST);
     buf_hist_   = decl("sampler.history", RAD_I32, rows, cfg_.max_hist, RAD_BUF_PERSIST);
-    /* One byte beside every history token: nonzero where that token is a whole DRY sequence
-     * breaker, which DRY never penalises. Resolving a token against the breaker strings needs the
-     * vocabulary, so it happens here on the host and the kernel reads the answer. */
+    /* One byte per history token, nonzero where the token is a whole DRY sequence breaker (never
+     * penalised). Resolved on the host, which has the vocabulary. */
     buf_brk_    = decl("sampler.dry_breakers", RAD_U8, rows, cfg_.max_hist, RAD_BUF_PERSIST);
     buf_mask_   = decl("sampler.mask", RAD_U32, rows, mask_words_, RAD_BUF_PERSIST);
     buf_cand_i_ = decl("sampler.cand_idx", RAD_I32, rows, ncand, RAD_BUF_TRANSIENT);
     buf_cand_v_ = decl("sampler.cand_val", RAD_F32, rows, ncand, RAD_BUF_TRANSIENT);
     if (vocab_parallel()) {
-        /* THE PAIR PLANE AND THE GATHERED PLANE. sample_topk packs this rank's candidates into
-         * `pairs` as (u32 global id, f32 logit); the all-gather places every rank's pairs for a
-         * row SIDE BY SIDE, which is the one layout the merge can read at a single row stride. */
+        /* sample_topk packs this rank's candidates into `pairs` as (u32 global id, f32 logit);
+         * the all-gather lays every rank's pairs for a row side by side, so the merge reads one
+         * row at a single stride. */
         buf_pairs_  = decl("sampler.cand_pairs", RAD_U32, rows, ncand * 2, RAD_BUF_TRANSIENT);
         buf_gather_ = decl("sampler.cand_gathered", RAD_U32, rows,
                            ncand * cfg_.world_size * 2, RAD_BUF_TRANSIENT);
     }
 
-    /* THE LOGPROBS SUMMARY, PERSIST for the reason the staging planes are: nothing in the
-     * declared op list reads it -- rank 0 copies it to the host behind the pick -- so liveness
-     * over the op list would hand its bytes to the candidate planes the stages after it write. */
+    /* The logprobs summary is PERSIST too: no declared op reads it (rank 0 copies it to the host
+     * behind the pick), so liveness would let the candidate planes reuse its bytes. */
     buf_lp_ = decl("sampler.logprobs", RAD_F32, rows, lp_width(), RAD_BUF_PERSIST);
     if (vocab_parallel())
         buf_lp_g_ = decl("sampler.logprobs_gathered", RAD_F32, rows,
                          lp_width() * cfg_.world_size, RAD_BUF_PERSIST);
 
     if (!buf_params_ || !buf_params_late_ || !buf_hist_ || !buf_brk_ || !buf_mask_ ||
-        !buf_cand_i_ || !buf_cand_v_ || !buf_lp_) {
+        !buf_cand_i_ || !buf_cand_v_ || !buf_lp_ ||
+        (vocab_parallel() && (!buf_pairs_ || !buf_gather_ || !buf_lp_g_))) {
         RAD_ERR("sampler: a staging buffer failed to declare");
         return RAD_E_NOMEM;
     }
 
     /* ---------------------------------------------------------- ops */
-    /* Every one of these is declared unconditionally and may fail to resolve. That is not an
-     * error here: a deployment that never sends `typical_p` has no use for a typical kernel, and
-     * failing declare over it would make an absent sampler an absent model. check_request turns
-     * an unresolved sampler into a named refusal at admission instead. */
-    /* `M` is the ranged parameter and it is the number of SAMPLED POSITIONS, not tokens: one row
-     * at decode, n_spec+1 per sequence at a verify, and a kernel written for a single row is a
-     * different kernel from one written for a batch of 256 (spec §2.2). */
+    /* Every op is declared unconditionally and may fail to resolve; check_request refuses the
+     * requests that need a missing one. `M` is ranged over sampled positions, so a kernel may
+     * specialise for one row versus a batch of 256 (spec §2.2). */
     auto op_vocab = [&](const char* name) -> rad_op {
         RadParam p[2] = {
             RadParam{ "M", RAD_P_RANGE, 1, rows, nullptr },
@@ -226,12 +207,9 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
         };
         return rad_decl_op(b, name, p, 2, nullptr, 0);
     };
-    /* THE VOCABULARY OFFSET, on the three stages that cross between a token id and a column of
-     * this rank's logits row: top-k turns a column into a token id, and the penalties and DRY turn
-     * the history's token ids into columns. Without it a rank past the first penalises the
-     * columns of whatever ids happen to be small, which are other tokens entirely. Declared only
-     * when the vocabulary is sharded, so a single-rank graph carries no parameter it has no use
-     * for. */
+    /* `vocab_off` for the three stages that map between token ids and this rank's columns:
+     * top-k (column to id), penalties and DRY (history id to column). Declared only when the
+     * vocabulary is sharded. */
     auto op_vocab_off = [&](const char* name) -> rad_op {
         if (!vocab_parallel())
             return op_vocab(name);
@@ -242,8 +220,7 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
         };
         return rad_decl_op(b, name, p, 3, nullptr, 0);
     };
-    /* The stages after top-k read a candidate set, not the vocabulary, so their geometry is the
-     * candidate width. That is what makes them cheap: 1024 entries rather than 151K. */
+    /* Stages after top-k work on the candidate set, so their geometry is the candidate width. */
     auto op_cand = [&](const char* name) -> rad_op {
         RadParam p[2] = {
             RadParam{ "M", RAD_P_RANGE, 1, rows, nullptr },
@@ -264,8 +241,8 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
     op_typical_   = op_cand("sample_typical");
     op_xtc_       = op_cand("sample_xtc");
     op_pick_      = op_cand("sample_pick");
-    /* THE SAME TEMPERATURE KERNEL OVER THE CANDIDATE PLANE: its `n_vocab` is the candidate width,
-     * which is all the kernel reads it as -- a row length. */
+    /* The temperature kernel again, over the candidate plane: `n_vocab` is only a row length to
+     * it, so the candidate width works. */
     {
         RadParam p[2] = {
             RadParam{ "M", RAD_P_RANGE, 1, rows, nullptr },
@@ -275,24 +252,21 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
     }
 
     if (vocab_parallel()) {
-        /* lm_head is vocab-sharded, so each rank reduces ITS OWN shard and only the candidate
-         * sets are combined -- k * world_size pairs, 2 KiB at k=64 and world_size=4, against the
-         * ~77 MiB a full-logits gather would move (spec §9). */
+        /* Each rank reduces its own shard and only the candidate sets are gathered: 2 KiB at
+         * k=64 and world_size=4, versus ~148 MiB for full logits (spec §9). */
         RadParam ag[4] = {
             RadParam{ "world_size", RAD_P_INT, (long long)cfg_.world_size, 0, nullptr },
             RadParam{ "numel", RAD_P_INT, (long long)(rows * ncand * 2), 0, nullptr },
             RadParam{ "dtype", RAD_P_STR, 0, 0, "f32" },
-            /* ROW-INTERLEAVED. One sampled position's pairs from every rank have to land side by
-             * side, because sample_merge_topk reads one row at one row stride. */
+            /* Row-interleaved, so each position's pairs from every rank are adjacent. */
             RadParam{ "row", RAD_P_INT, (long long)(ncand * 2), 0, nullptr },
         };
         op_allgather_ = rad_decl_op(b, "all_gather", ag, 4, nullptr, 0);
         op_merge_     = op_cand("sample_merge_topk");
     }
 
-    /* THE RAW DISTRIBUTION'S SUMMARY, at the one width every request's top_logprobs fits in. A
-     * deployment whose kernels lack it serves every request that does not ask for logprobs;
-     * check_request refuses the ones that do, by name. */
+    /* The raw-distribution summary, at a width that fits every request's top_logprobs. If it
+     * does not resolve, check_request refuses only requests that ask for logprobs. */
     {
         RadParam p[4] = {
             RadParam{ "M", RAD_P_RANGE, 1, rows, nullptr },
@@ -303,8 +277,8 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
         op_logprobs_ = rad_decl_op(b, "sample_logprobs", p, vocab_parallel() ? 4 : 3, nullptr, 0);
     }
     if (vocab_parallel()) {
-        /* Each rank summarised its own shard; rank 0 merges them on the host, so every rank's
-         * row lands beside the others' as the candidate pairs do. */
+        /* Each rank summarises its own shard; rank 0 merges them on the host. Laid out side by
+         * side, like the candidate pairs. */
         RadParam ag[4] = {
             RadParam{ "world_size", RAD_P_INT, (long long)cfg_.world_size, 0, nullptr },
             RadParam{ "numel", RAD_P_INT, (long long)(rows * lp_width()), 0, nullptr },
@@ -327,9 +301,8 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
 int Sampler::stage_alloc() {
     const int64_t rows = rows_for(cfg_);
 
-    /* Pinned, because these are uploaded every step and a pageable source turns an async copy
-     * into a staged one with a host bounce -- which is exactly the per-step cost the step batch
-     * exists to remove (spec §8). */
+    /* Pinned: uploaded every step, and a pageable source turns the async copy into a staged one
+     * with a host bounce (spec §8). */
     params_stage_ = (DeviceSampleParams*)rad_dev_alloc(
         rows * (int64_t)sizeof(DeviceSampleParams), RAD_MEM_HOST_PINNED);
     greedy_stage_ = (DeviceSampleParams*)rad_dev_alloc(
@@ -341,8 +314,7 @@ int Sampler::stage_alloc() {
     brk_stage_    = (uint8_t*)rad_dev_alloc(rows * cfg_.max_hist, RAD_MEM_HOST_PINNED);
     mask_stage_   = (uint32_t*)rad_dev_alloc(rows * mask_words_ * 4, RAD_MEM_HOST_PINNED);
 
-    /* Rank 0's landing place for the logprobs copies, and only rank 0's: it is the rank that
-     * reads them. */
+    /* Logprobs readback; only rank 0 reads it. */
     if (cfg_.rank == 0) {
         const int64_t w = lp_width() * (vocab_parallel() ? cfg_.world_size : 1);
         lp_host_    = (float*)rad_dev_alloc(rows * w * 4, RAD_MEM_HOST_PINNED);
@@ -393,10 +365,9 @@ Sampler::~Sampler() { stage_free(); }
 
 /* ================================================================== admission */
 
-/* WHEN THE TWO HISTORY STAGES RUN, in one place, because admission, request setup and the step
- * staging each ask and must not disagree. llama.cpp's meaning throughout: a window of 0 turns the
- * stage off, and DRY also needs a base of at least 1. The multiplier is taken as positive because
- * a negative one rewards repetition, which is not a request anyone makes on purpose. */
+/* Whether the two history stages run, shared by admission, request setup and step staging so
+ * they agree. As in llama.cpp, a window of 0 turns a stage off and DRY needs a base >= 1. DRY
+ * also requires a positive multiplier; a negative one would reward repetition. */
 static bool penalties_on(const SamplingParams& sp) {
     return sp.penalty_last_n != 0 &&
            (sp.rep_penalty != 1.0f || sp.freq_penalty != 0.0f || sp.pres_penalty != 0.0f);
@@ -412,24 +383,40 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
         return st;
     };
 
+    /* Each range is tested as "inside", so a NaN fails it. top_p and typical_p are (0, 1], as
+     * the server takes them: the chain reads 0 as off, where llama.cpp keeps one candidate, so
+     * 0 has no single meaning to honour. */
     if (sp.top_k < 0)                       return refuse("top_k is negative", RAD_E_INVAL);
-    if (sp.top_p < 0.0f || sp.top_p > 1.0f) return refuse("top_p is outside [0,1]", RAD_E_INVAL);
-    if (sp.min_p < 0.0f || sp.min_p > 1.0f) return refuse("min_p is outside [0,1]", RAD_E_INVAL);
-    if (sp.typical_p < 0.0f || sp.typical_p > 1.0f)
-        return refuse("typical_p is outside [0,1]", RAD_E_INVAL);
-    if (sp.temp < 0.0f)                     return refuse("temperature is negative", RAD_E_INVAL);
-    if (sp.top_k > cfg_.max_candidates)
-        return refuse("top_k exceeds the sampler's candidate width (--max-candidates)",
-                      RAD_E_INVAL);
+    if (!(sp.top_p > 0.0f && sp.top_p <= 1.0f))
+        return refuse("top_p is outside (0,1]", RAD_E_INVAL);
+    if (!(sp.min_p >= 0.0f && sp.min_p <= 1.0f))
+        return refuse("min_p is outside [0,1]", RAD_E_INVAL);
+    if (!(sp.typical_p > 0.0f && sp.typical_p <= 1.0f))
+        return refuse("typical_p is outside (0,1]", RAD_E_INVAL);
+    if (!(sp.temp >= 0.0f))                 return refuse("temperature must be >= 0", RAD_E_INVAL);
+    if (!(sp.xtc_probability >= 0.0f && sp.xtc_probability <= 1.0f))
+        return refuse("xtc_probability is outside [0,1]", RAD_E_INVAL);
+    if (!(sp.xtc_threshold >= 0.0f && sp.xtc_threshold <= 1.0f))
+        return refuse("xtc_threshold is outside [0,1]", RAD_E_INVAL);
+    if (sp.top_k > cfg_.max_candidates) {
+        if (why)
+            *why = "top_k " + std::to_string(sp.top_k) + " is wider than the sampler's candidate "
+                   "width of " + std::to_string(cfg_.max_candidates) + " tokens";
+        return RAD_E_INVAL;
+    }
+    /* The penalty divides a positive logit by rep_penalty, so 0 would make it infinite. */
+    if (penalties_on(sp) && !(sp.rep_penalty > 0.0f))
+        return refuse("rep_penalty must be > 0", RAD_E_INVAL);
+    /* The DRY kernels read an allowed length below 1 as 2; refused rather than rewritten. */
+    if (dry_on(sp) && sp.dry_allowed_length < 1)
+        return refuse("dry_allowed_length must be >= 1", RAD_E_INVAL);
     if (sp.n_probs > RAD_MAX_LOGPROBS) {
         if (why) *why = "at most " + std::to_string(RAD_MAX_LOGPROBS) +
                         " logprobs alternatives may be asked for";
         return RAD_E_INVAL;
     }
-    /* Every breaker is a pass over the whole vocabulary on the scheduler thread, and every other
-     * sequence on the server waits for it; see kDryMaxBreakers. Refused here, before any of that
-     * work is queued, rather than truncated -- a request whose breakers quietly went missing is a
-     * request whose output changed. */
+    /* Each breaker is a full-vocabulary scan on the scheduler thread (see kDryMaxBreakers).
+     * Refused rather than truncated, which would silently change the output. */
     if (dry_on(sp) && sp.dry_seq_breakers.size() > kDryMaxBreakers) {
         if (why)
             *why = "dry_sequence_breakers has " + std::to_string(sp.dry_seq_breakers.size()) +
@@ -437,18 +424,14 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
         return RAD_E_INVAL;
     }
 
-    /* An unresolved sampler is a named refusal, not a silent skip. A request whose min_p quietly
-     * stopped being applied is a request whose output changed and nothing said so. */
+    /* An unresolved sampler is a named refusal, never a silent skip. */
     auto need = [&](bool wanted, rad_op h, const char* n) -> const char* {
         return (wanted && !h) ? n : nullptr;
     };
-    /* A SPLIT VOCABULARY MOVES GREEDY ONTO THE CHAIN, so what a greedy request needs moves with
-     * it: not the argmax, but the temperature stage, the top-k, the merge and the pick that
-     * build_step's top_k = 1 sends it through -- run() issues the temperature stage for every
-     * batch with a chain row, even though its kernel leaves a greedy row (temperature 0) as it
-     * is. Admission has to check what will actually be issued. */
-    /* AND SO DOES ONE ASKING FOR LOGPROBS, which build_step stages as a top-1 chain row so its
-     * token comes off a candidate plane (sampler.h). */
+    /* Under a split vocabulary, or when it asks for logprobs, a greedy request is staged as a
+     * top-1 chain row (see build_step), so it needs the chain ops (temperature, top-k, pick)
+     * rather than the argmax. run() issues the temperature stage for any chain row, even though
+     * it leaves a temperature-0 row unchanged. */
     const bool lp = sp.n_probs >= 0;
     const bool greedy_chain = sp.greedy() && (vocab_parallel() || lp);
     const char* missing = nullptr;
@@ -456,9 +439,8 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
     if (!missing) missing = need(sp.greedy() && !greedy_chain, op_argmax_, "sample_argmax");
     if (!missing) missing = need(!sp.greedy() || greedy_chain, op_temp_, "sample_temp");
     if (!missing) missing = need(!sp.greedy() || greedy_chain, op_pick_, "sample_pick");
-    /* EVERY CHAIN ROW NEEDS THE TOP-K, whatever its own top_k says: it is the stage that writes
-     * the candidate set every later stage reads. top_k = 0 asks for the whole candidate width,
-     * not for no candidates. */
+    /* Every chain row needs top-k, whatever its top_k: it writes the candidate set the later
+     * stages read. top_k = 0 means the whole candidate width (max_candidates). */
     if (!missing) missing = need(!sp.greedy() || greedy_chain, op_topk_, "sample_topk");
     if (!missing) missing = need(sp.top_p < 1.0f, op_topp_, "sample_topp");
     if (!missing) missing = need(sp.min_p > 0.0f, op_minp_, "sample_minp");
@@ -478,10 +460,9 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
     if (!sp.grammar.empty() && !vocab_)
         return refuse("a grammar was requested before the vocabulary was attached", RAD_E_STATE);
 
-    /* The triggers are resolved here as well as at begin_request, so a template whose triggers
-     * this machine cannot run is a refusal at admission rather than a request cancelled on the
-     * scheduler thread. */
-    if (!sp.grammar.empty() && !sp.grammar_triggers.empty()) {
+    /* Resolved here as well as in begin_request, so unsupported triggers are refused at
+     * admission rather than cancelling the request on the scheduler thread. */
+    if (!sp.grammar.empty() && (sp.grammar_lazy || !sp.grammar_triggers.empty())) {
         std::vector words;
         std::vector     tokens;
         std::string              e;
@@ -490,6 +471,8 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
             if (why) *why = e;
             return st;
         }
+        if (sp.grammar_lazy && words.empty() && tokens.empty())
+            return refuse(kLazyNoTrigger, RAD_E_INVAL);
     }
 
     return RAD_OK;
@@ -508,32 +491,24 @@ int Sampler::begin_request(uint64_t req_id, const SamplingParams& sp, std::strin
         spec.text = sp.grammar;
         spec.root = "root";
         spec.lazy = sp.grammar_lazy;
-        /* ONLY A NON-LAZY GRAMMAR IS POSITIONED AT THE START OF THE TURN. An eager grammar's root
-         * describes the whole assistant turn and therefore opens with the generation prompt, which
-         * is already in the prompt -- so it has to be replayed or the model is made to write it
-         * out again. A LAZY one describes only the region after its trigger: its root begins at
-         * ``, and feeding it a prefix it never claimed to match fails outright, taking
-         * every tool-calling request with it. */
+        /* Only an eager grammar replays the generation prompt prefix: its root describes the
+         * whole assistant turn, which opens with text already in the prompt. A lazy grammar's
+         * root starts at its trigger (e.g. ``) and would fail on that prefix. */
         spec.prefix = sp.grammar_lazy ? std::string() : sp.grammar_prefix;
         RAD_TRY(resolve_triggers(*vocab_, sp.grammar_triggers, &spec.trigger_words,
                                  &spec.trigger_tokens, err));
         RAD_TRY(grammar_create(spec, *vocab_, &st.grammar, err));
     }
 
-    /* BREAKERS ARE OPTIONAL. DRY runs whenever the request turns it on, as llama.cpp's does with an
-     * empty breaker list; the breakers only limit how far back a repeat may be counted and exempt
-     * the tokens that are breakers themselves. */
+    /* Breakers are optional; DRY runs without them, as llama.cpp's does. They only cap how far
+     * back a repeat is counted and exempt whole-breaker tokens. */
     if (dry_on(sp) && !sp.dry_seq_breakers.empty()) {
         if (!vocab_) {
             if (err) *err = "DRY needs a vocabulary to resolve its sequence breakers";
             return RAD_E_STATE;
         }
-        if (sp.dry_seq_breakers.size() > kDryMaxBreakers) {
-            if (err) *err = "too many DRY sequence breakers";
-            return RAD_E_INVAL;
-        }
-        /* Once per request, never per step: a full vocabulary scan per breaker string is
-         * milliseconds at a 151K vocab and has no business on the step path. */
+        /* Once per request: a full vocabulary scan per breaker costs milliseconds at a 151K
+         * vocab. */
         const int s = dry_prepare_breakers(*vocab_, sp.dry_seq_breakers, &st.dry,
                                            kDryBreakerMaxTail);
         if (s < 0) {
@@ -560,8 +535,8 @@ int Sampler::accept_token(uint64_t req_id, int32_t token) {
     auto it = seqs_.find(req_id);
     if (it == seqs_.end()) return RAD_OK;      /* no grammar, nothing to advance */
     if (!it->second.grammar) return RAD_OK;
-    /* TIMED for the same reason build_step is: this runs once per ACCEPTED token per rank, on the
-     * step thread, so it is wall time on every constrained token. */
+    /* Timed at Debug, like build_step: runs once per accepted token per rank on the step thread,
+     * so it is wall time on every constrained token. */
     if ((int)log_level() < (int)Log::Debug) return it->second.grammar->accept_token(token);
     const auto t0 = std::chrono::steady_clock::now();
     const int s = it->second.grammar->accept_token(token);
@@ -574,11 +549,9 @@ int Sampler::accept_token(uint64_t req_id, int32_t token) {
     return s;
 }
 
-/* A CONSTRAINING GRAMMAR DOES NOT MEAN NO SPECULATION. build_step masks draft position i
- * against the state reached by accepting drafts 0..i-1 and then rewinds, so a backend that can
- * push and pop its state speculates like any other request -- which is worth several times the
- * per-token cost on a constrained request. What IS refused is a backend that cannot rewind:
- * masking its window would mean masking against a state the sequence is not in. */
+/* A constraining grammar does not rule out speculation: build_step masks draft position i
+ * against the state after drafts 0..i-1 and then rewinds. Only a backend that cannot rewind is
+ * refused. */
 bool Sampler::allows_speculation(uint64_t req_id) const {
     auto it = seqs_.find(req_id);
     if (it == seqs_.end() || !it->second.grammar) return true;
@@ -603,17 +576,14 @@ int Sampler::build_step(const std::vector& reqs) {
     cur_stage_ = params_stage_;
     lp_rows_.clear();
 
-    /* DRY'S HOST HALF, for one row whose history `h[0, take)` is already staged. The breakers are
-     * strings resolved against the vocabulary, so what they mean for this window is worked out
-     * here and handed to the kernel as data: the repeat limit the most recent breaker imposes
-     * (llama.cpp's step 1), and one byte per position marking the tokens that are whole breakers
-     * and therefore never penalised. The window is the one the kernel will take -- the tail of
-     * the staged row, `dry_penalty_last_n` long when that is positive.
+    /* DRY's host half for one row whose history `h[0, take)` is staged. Over the window the
+     * kernel uses (the tail of the row, `dry_penalty_last_n` long when positive) it computes the
+     * repeat limit from the most recent breaker (llama.cpp's step 1) and marks whole-breaker
+     * tokens, which are never penalised.
      *
-     * Returns false when the breakers rule DRY out for the row altogether: a breaker closer to the
-     * end than `allowed_length` leaves no repeat long enough to count. A row with no breakers
-     * gets zero marks, because the plane is shared by the whole batch and another row may have
-     * some. */
+     * Returns false when a breaker closer to the end than `allowed_length` rules DRY out for the
+     * row. A row without breakers still gets zero marks, because the plane is shared by the
+     * batch. */
     auto stage_dry = [&](DeviceSampleParams& p, const int32_t* h, int64_t take,
                          const DryBreakers* brk, int64_t row) -> bool {
         const int64_t last_n  = p.dry_penalty_last_n;
@@ -640,12 +610,9 @@ int Sampler::build_step(const std::vector& reqs) {
         const int n_pos = r->n_draft + 1;
 
         if (n_pos > 1 && !allows_speculation(r->id)) {
-            RAD_ERR("sampler: request %llu carries a constraining grammar its backend cannot "
-                    "snapshot, and %d draft tokens. The mask for draft position i is the mask of "
-                    "the state reached by accepting drafts 0..i-1, so masking the window needs "
-                    "push_state/rollback. The scheduler must consult allows_speculation() and "
-                    "decode this one a token at a time.",
-                    (unsigned long long)r->id, r->n_draft);
+            RAD_ERR("sampler: request %llu has %d draft tokens and a constraining grammar that "
+                    "cannot snapshot its state; the scheduler must decode it a token at a time "
+                    "(allows_speculation)", (unsigned long long)r->id, r->n_draft);
             return RAD_E_UNSUPPORTED;
         }
 
@@ -665,25 +632,19 @@ int Sampler::build_step(const std::vector& reqs) {
         SeqState* st = it == seqs_.end() ? nullptr : &it->second;
         const DryBreakers* brk = st && !st->dry.empty() ? &st->dry : nullptr;
 
-        /* THE WINDOW IS WALKED, THEN REWOUND. Position 0 is masked against the state the sequence
-         * is really in; position k against the state reached by accepting drafts 0..k-1. The push
-         * happens whatever the grammar's current mode, because a draft token can fire a lazy
-         * grammar's trigger mid-window -- at which point the positions behind it DO need a mask,
-         * and without the push they would be sampled unconstrained.
+        /* The window is walked, then rewound: position k is masked against the state after
+         * accepting drafts 0..k-1. The push happens even when the grammar is not yet
+         * constraining, because a draft can fire a lazy grammar's trigger mid-window.
          *
-         * `dead` is not a failure. A draft the grammar forbids simply cannot be accepted: the
-         * target's own masked pick at that position will differ from it, so verification rejects
-         * there and every position behind it is discarded. Masking stops and the rest of the
-         * window is left unconstrained, which is what "discarded" needs it to be. */
+         * `dead` is not a failure: a draft the grammar forbids will be rejected at verification
+         * and every later position discarded, so masking stops for the rest of the window. */
         GrammarBackend* gr = st && st->grammar ? st->grammar.get() : nullptr;
         const bool walk = gr && n_pos > 1;
         if (walk) gr->push_state();
         bool dead = false;
 
-        /* THE REASONING BUDGET, walked over the window as the grammar is. Position k is inside the
-         * block or not according to the committed reply and drafts 0..k-1, which is the only
-         * history under which its token is ever emitted; a draft that ends the block early is
-         * accepted or rejected like any other. */
+        /* The reasoning budget is walked over the window like the grammar: position k is
+         * judged by the committed reply plus drafts 0..k-1. */
         const bool budget = st && sp.thinking_budget >= 0 && sp.reasoning.known();
         ReasoningCount think;
         if (budget) {
@@ -705,9 +666,8 @@ int Sampler::build_step(const std::vector& reqs) {
             std::memset(&p, 0, sizeof p);
 
             p.seed = sp.seed;
-            /* The output position, advanced across the speculative window: draft position k is
-             * the (n_out + k)-th token this request will emit, so its randomness is the same
-             * whether it arrived through speculation or one token at a time. */
+            /* Output position: draft position k is token n_out + k, so its draw is the same with
+             * or without speculation. */
             p.pos = (uint64_t)(n_out + k);
 
             p.temp        = sp.temp;
@@ -727,21 +687,15 @@ int Sampler::build_step(const std::vector& reqs) {
             p.dry_penalty_last_n = sp.dry_penalty_last_n;
             p.mask_row = -1;
 
-            /* GREEDY OVER A SPLIT VOCABULARY IS A TOP-1 CHAIN, not an argmax. sample_argmax reads a
-             * whole logits row and writes the winning COLUMN, which under vocab parallelism is
-             * this rank's local index into its own shard -- a fluent answer built from the wrong
-             * token ids. Staging top_k = 1 sends the row through top-k, the pair plane, the
-             * gather and the merge instead, which is where a local index becomes a global one;
-             * sample_pick over a single live candidate returns it deterministically, so the
-             * result is the argmax it was always meant to be.
+            /* Greedy over a split vocabulary is a top-1 chain row, not an argmax: sample_argmax
+             * writes a column of this rank's shard, not a token id. Top-k plus the merge produce
+             * global ids, and the pick over one candidate is deterministic. A greedy row asking
+             * for logprobs is staged the same way, because logprobs_for reads the drawn value
+             * from the candidate plane; the argmax and top-k share a tie rule, so the token is
+             * unchanged.
              *
-             * Such a row is a CHAIN row and does not carry RAD_SP_GREEDY: every candidate stage
-             * skips a row that does, because in an unsplit batch that flag is what keeps the pick
-             * from overwriting the argmax's answer with a draw. */
-            /* A GREEDY ROW ASKING FOR LOGPROBS IS A TOP-1 CHAIN ROW TOO, for a reason of its own:
-             * its token has to come off a candidate plane, which is where logprobs_for reads the
-             * value it was drawn at. The argmax's tie rule is the top-k's, so the token is the
-             * same. */
+             * Such a row does not carry RAD_SP_GREEDY: candidate stages skip flagged rows, so the
+             * pick does not overwrite the argmax's token. */
             const bool want_lp = sp.n_probs >= 0;
             if (sp.greedy()) {
                 if (vocab_parallel() || want_lp) p.top_k = 1;
@@ -749,9 +703,9 @@ int Sampler::build_step(const std::vector& reqs) {
             }
             if (want_lp) p.flags |= RAD_SP_LOGPROBS;
             if (sp.xtc_probability > 0.0f) p.flags |= RAD_SP_XTC;
-            /* TEMPERATURE LAST: the row's own temperature in the late stage's row, and 1 -- which
-             * the temperature stage skips -- in whichever of the two it does not run in. Every row
-             * gets a late row, because the late stage is issued over the whole batch. */
+            /* Temperature last: the row's temperature goes in the late row and 1 (skipped) in the
+             * early one; otherwise the reverse. Every row gets a late row, because the late stage
+             * is issued over the whole batch. */
             const bool late = sp.temp_last && !sp.greedy() && sp.temp != 1.0f;
             DeviceSampleParams& lp = late_stage_[row];
             lp = p;
@@ -761,17 +715,11 @@ int Sampler::build_step(const std::vector& reqs) {
                 any_late_ = true;
             }
 
-            /* THE HISTORY THE PENALTIES AND DRY READ, staged only for a row that runs one of them
-             * -- the copy is scheduler-thread work and the upload is step-path bytes, and neither
-             * buys anything for a row that reads none of it. It is the prompt, everything
-             * generated so far and, at draft position k, the k drafted tokens in front of it: the
-             * token sampled there is emitted only if those drafts are, so they are part of the
-             * output it is penalised against, exactly as they would be one token at a time. Oldest
-             * first, truncated to the declared window -- a bound on the buffer, not a policy on
-             * the sampler; penalty_last_n still decides how much of it counts. The row owns its
-             * own row of the plane, so the window starts at offset 0 within it. */
-            p.hist_off = 0;
-            p.hist_len = 0;
+            /* History for the penalties and DRY, staged only for rows that run one of them:
+             * prompt, output so far and, at draft position k, the k drafts before it (they are
+             * emitted only if accepted, as one token at a time). Oldest first, truncated to
+             * max_hist; penalty_last_n still decides how much counts. Each row owns its row of the
+             * plane, so hist_off stays 0. */
             if (pen || dry) {
                 const int64_t len  = n_total + k;
                 const int64_t take = std::min(len, cfg_.max_hist);
@@ -790,18 +738,13 @@ int Sampler::build_step(const std::vector& reqs) {
             if (gr && !dead && gr->constrains()) {
                 uint32_t* dst = mask_stage_ + row * mask_words_;
                 int s;
-                /* WHAT THE MASK COSTS, MEASURED RATHER THAN ASSUMED. The mask is scheduler-thread
-                 * work with the rank threads waiting at the barrier, so it is wall time on every
-                 * constrained token and would decide the step if it were slow. Reported at Debug,
-                 * per 256 masks, mean and worst. */
+                /* Mask cost, reported at Debug per 256 masks (mean and worst). It runs on the
+                 * scheduler thread while the rank threads wait at the barrier. */
                 const bool   inst = (int)log_level() >= (int)Log::Debug;
                 const auto   t0   = std::chrono::steady_clock::now();
-                /* ASK THE GRAMMAR WHETHER IT COMPUTED THE MASK, rather than inferring it from how
-                 * long the call took. No duration threshold separates the two: a mask computed
-                 * from the plan can finish inside the time a memo hit costs on a large
-                 * vocabulary, so a timing test counts computed masks as hits and any per-mask
-                 * cost derived from the split is wrong by that factor. The counter is exact and
-                 * costs a relaxed load. */
+                /* Memo hits and computed masks are told apart by the grammar's walk counter, not
+                 * by duration: a computed mask can be as fast as a memo hit on a large
+                 * vocabulary. */
                 const uint64_t w0 = inst ? st->grammar->masks_walked() : 0;
                 if (!vocab_parallel()) {
                     s = st->grammar->fill_mask(dst, mask_words_);
@@ -812,15 +755,13 @@ int Sampler::build_step(const std::vector& reqs) {
                 if (inst) {
                     const double us = std::chrono::duration(
                                           std::chrono::steady_clock::now() - t0).count();
-                    mask_us_ += us; mask_worst_us_ = mask_us_n_ && us < mask_worst_us_
-                                                   ? mask_worst_us_ : us;
+                    mask_us_ += us;
+                    mask_worst_us_ = std::max(mask_worst_us_, us);
                     if (st->grammar->masks_walked() != w0) { ++mask_slow_; mask_walk_us_ += us; }
                     else                                     ++mask_fast_;
                     if (++mask_us_n_ == 256) {
-                        /* Mean per MASK and mean per COMPUTED mask are different questions and
-                         * the second is the one that says what a new state costs: a window's
-                         * masks are mostly memo hits, so the first tracks how many positions
-                         * asked. */
+                        /* Mean per computed mask is what a new state costs; the overall mean
+                         * is dominated by memo hits. */
                         RAD_DEBUG("sampler: grammar mask %.2f ms mean, %.2f ms worst over 256; "
                                   "%lld memo hits, %lld computed at %.2f ms mean (%lld vocab, "
                                   "%lld words)",
@@ -833,19 +774,13 @@ int Sampler::build_step(const std::vector& reqs) {
                     }
                 }
                 if (s < 0 && k > 0) {
-                    /* A SPECULATIVE POSITION IS NOT A DEAD REQUEST. This is the state reached by
-                     * accepting drafts the sequence has not committed to, so "nothing is
-                     * admissible here" says the draft is wrong, not that the request is stuck.
-                     * Verification will reject at or before this position; stop masking and leave
-                     * the rest of the window unconstrained, since it is about to be discarded. */
+                    /* At a draft position this only means a draft is wrong; verification
+                     * rejects at or before here, so stop masking the rest of the window. */
                     dead = true;
                 } else if (s < 0) {
-                    /* A DEAD GRAMMAR FAILS ITS REQUEST, NOT THE STEP. Returning a status here
-                     * would reach the step loop as an engine fault and stop it stepping, so every
-                     * other client on the server would stop receiving tokens because one of them
-                     * sent a schema the model painted itself out of. The row is left unmasked for
-                     * this step -- it is about to be cancelled -- and the id goes to the engine
-                     * to close. */
+                    /* A dead grammar fails its request, not the step: an error status would stop
+                     * the step loop for every client. The row stays unmasked and the engine
+                     * cancels the request. */
                     RAD_WARN("sampler: request %llu has no admissible token under its grammar; "
                              "failing that request", (unsigned long long)r->id);
                     failed_.push_back(r->id);
@@ -853,10 +788,8 @@ int Sampler::build_step(const std::vector& reqs) {
                     p.mask_row = (int32_t)row;
                     p.flags |= RAD_SP_MASK;
                     if ((int)log_level() >= (int)Log::Trace) {
-                        /* How many tokens the grammar allows THIS RANK to pick. Zero is legal
-                         * under sharding -- the admissible set can live entirely on another rank
-                         * -- and is the first thing to check when a grammar-constrained answer
-                         * comes out unconstrained. */
+                        /* Tokens the grammar allows on this rank. Zero is legal under sharding,
+                         * when the admissible set lives on another rank. */
                         int64_t bits = 0;
                         for (int64_t w = 0; w < mask_words_; ++w)
                             bits += __builtin_popcount(dst[w]);
@@ -872,8 +805,8 @@ int Sampler::build_step(const std::vector& reqs) {
                 force_close(p, row, sp.reasoning.close);
 
             if (want_lp) {
-                /* The temperature the candidate value carries: the early stage's and the late
-                 * one's, each only where its kernel runs (temp > 0 and not 1). */
+                /* Temperature the candidate value carries: early and late, each counted only
+                 * where its kernel applies it (temp > 0 and not 1). */
                 auto t_of = [](float t) { return t > 0.0f && t != 1.0f ? t : 1.0f; };
                 LpRow L;
                 L.row   = row;
@@ -889,15 +822,11 @@ int Sampler::build_step(const std::vector& reqs) {
             }
         }
 
-        /* Back to where the sequence actually is. The tokens it really accepted are applied by
-         * Sampler::accept_token after the step verifies, so anything the walk did must be gone
-         * before then or the grammar would be ahead of the sequence by the whole window. */
+        /* Rewind the walk; accepted tokens are applied by accept_token after verification. */
         if (walk) RAD_TRY(gr->rollback());
     }
 
-    /* THE WHOLE OF IT, not just the mask, because that is what the rank threads wait for. Without
-     * this the mask's own number could fall to nothing and the step stay slow with no way to see
-     * which side of the barrier the time was on. */
+    /* Whole build time, which is what the rank threads wait for at the barrier. */
     if ((int)log_level() >= (int)Log::Debug) {
         build_us_ += std::chrono::duration(
                          std::chrono::steady_clock::now() - t_build).count();
@@ -915,8 +844,8 @@ void Sampler::force_close(DeviceSampleParams& p, int64_t row, int32_t close) {
     const int64_t at = (int64_t)close - cfg_.vocab_off;
     const bool local = at >= 0 && at < cfg_.n_vocab_local;
     if (p.flags & RAD_SP_MASK) {
-        /* The grammar's mask for this row. Under a split vocabulary the whole one is still in
-         * mask_full_, and the close may be another rank's column. */
+        /* Check the grammar's mask. Under a split vocabulary use mask_full_, since the close may
+         * be another rank's column. */
         const bool admitted =
             vocab_parallel()
                 ? close < (int64_t)mask_full_.size() * 32 &&
@@ -924,9 +853,8 @@ void Sampler::force_close(DeviceSampleParams& p, int64_t row, int32_t close) {
                 : local && (dst[at >> 5] >> (uint32_t)(at & 31)) & 1u;
         if (!admitted) return;
     }
-    /* ONE ADMISSIBLE TOKEN, on whichever rank holds its column. The others mask the whole row
-     * out, which the candidate merge reads as no candidate from them (the grammar's own masks do
-     * the same when the admissible set lives on one shard). */
+    /* One admissible token, on the rank that holds its column. Other ranks mask the whole row,
+     * which the candidate merge reads as no candidates from them. */
     std::memset(dst, 0, (size_t)mask_words_ * 4);
     if (local) dst[at >> 5] |= 1u << (uint32_t)(at & 31);
     p.mask_row = (int32_t)row;
@@ -944,18 +872,16 @@ int Sampler::build_greedy(int64_t n) {
     }
     n_seq_ = n;
     any_brk_ = false;
+    any_late_ = false;
     cur_stage_ = greedy_stage_;
     if (greedy_ready_) return RAD_OK;
     for (int64_t i = 0; i < cap; ++i) {
         DeviceSampleParams& p = greedy_stage_[i];
         std::memset(&p, 0, sizeof p);
-        p.temp     = 0.0f;
         p.top_k    = 1;
-        p.hist_off = 0;
-        p.hist_len = 0;
         p.mask_row = -1;
-        /* Over a split vocabulary a greedy row is a top-1 CHAIN row, for the reason build_step
-         * gives, and so it does not carry the flag every candidate stage skips. */
+        /* Over a split vocabulary a greedy row is an unflagged top-1 chain row (see
+         * build_step). */
         p.flags    = vocab_parallel() ? 0 : RAD_SP_GREEDY;
     }
     greedy_ready_ = true;
@@ -987,24 +913,21 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
         }
     }
 
-    /* A GREEDY ROW OVER A SPLIT VOCABULARY is staged as a top-1 chain row, never with the flag:
-     * the argmax would return this rank's column for a token id. build_step and build_greedy both
-     * hold that, so a flagged row here is a staging bug, and it is refused rather than served. */
+    /* A greedy-flagged row under a split vocabulary is a staging bug (the argmax would return a
+     * shard column), so it is refused. */
     if (any_greedy && vocab_parallel()) {
         RAD_ERR("sampler: a greedy-flagged row reached a split vocabulary, where the argmax "
                 "returns a column of this rank's shard rather than a token id");
         return RAD_E_STATE;
     }
 
-    /* Async copies on the compute stream and no host synchronisation, and only of what some row
-     * will read: the history and the breaker marks for the penalties and DRY, the mask for a
-     * grammar. The mask upload is 19 KiB a constrained sequence at a 151K vocab, which is the
-     * number that makes a host-side grammar affordable at all (spec §13). */
+    /* Async copies on the compute stream, only of what some row reads. The mask is 19 KiB per
+     * constrained sequence at a 151K vocab, which keeps a host-side grammar affordable
+     * (spec §13). */
     RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_params_), cur_stage_,
                              n_seq_ * (int64_t)sizeof(DeviceSampleParams), s));
-    /* The late temperature's rows only when this build staged one: a greedy build's rows come
-     * from greedy_stage_, and late_stage_ then holds an older build's. */
-    const bool late = any_late_ && cur_stage_ == params_stage_;
+    /* Late rows only for a build_step build; build_greedy clears any_late_. */
+    const bool late = any_late_;
     if (late)
         RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_params_late_), late_stage_,
                                  n_seq_ * (int64_t)sizeof(DeviceSampleParams), s));
@@ -1033,9 +956,9 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
         return rad_issue(c, op, v.data(), (int)v.size(), n_seq_);
     };
 
-    /* THE LOGPROBS SUMMARY, ON THE LOGITS AS THE MODEL WROTE THEM: every stage below writes them in
-     * place. Only for a trunk build that staged a logprobs row -- a draft pass's greedy build
-     * stages none, and must not overwrite the summary rank 0 is about to copy back. */
+    /* The logprobs summary reads the raw logits, before any stage writes them in place. Only for
+     * a build_step build with logprobs rows: a draft pass must not overwrite the summary rank 0
+     * is about to copy back. */
     const bool lp = !lp_rows_.empty() && cur_stage_ == params_stage_ && op_logprobs_;
     const RadOperand o_lp = opd_rows(buf_lp_, n_seq_);
     if (lp) {
@@ -1044,24 +967,17 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
             RAD_TRY(issue(op_lp_gather_, { o_lp, opd_rows(buf_lp_g_, n_seq_) }));
     }
 
-    /* Penalties act on raw logits, before anything derives a probability from them. DRY takes the
-     * breaker marks only when some row in the batch has breakers; its fourth operand is optional
-     * and absent means no token is exempt. */
+    /* Penalties act on raw logits. DRY gets the breaker marks only when some row has breakers;
+     * absent means no token is exempt. */
     if (any_penalty) RAD_TRY(issue(op_penalties_, { o_logits, o_params, o_hist }));
     if (any_dry)
         RAD_TRY(issue(op_dry_, { o_logits, o_params, o_hist, pass_brk ? o_brk : opd_none() }));
 
-    /* The greedy rows take the argmax after penalties and the mask and never see temperature.
-     * When the batch is mixed, BOTH the argmax and the chain are issued over the whole batch: the
-     * argmax writes every row's token, and then every candidate stage skips the greedy rows
-     * (RAD_SP_GREEDY) so the pick overwrites only the rows the chain owns. The cost is one extra
-     * pass over the logits for the rows the other op owns -- ~77 MiB read at batch 256 -- against
-     * one kernel launch per distinct parameter set, which at batch 256 is up to 256 launches. The
-     * pass wins.
-     *
-     * Under vocab parallelism there is no greedy shortcut at all: build_step staged those rows at
-     * top_k = 1, without the flag, so they take the chain, where the merge turns a local candidate
-     * index into a global token id. */
+    /* Greedy rows take the argmax after penalties and the mask. In a mixed batch both the argmax
+     * and the chain run over the whole batch: the argmax writes every row, then the candidate
+     * stages skip RAD_SP_GREEDY rows so the pick overwrites only chain rows. One extra logits
+     * pass (~148 MiB at batch 256) beats up to 256 launches, one per parameter set. Under vocab
+     * parallelism no row is flagged greedy (see build_step). */
     if (any_greedy) {
         if (any_mask) RAD_TRY(issue(op_mask_, { o_logits, o_params, o_mask }));
         RAD_TRY(issue(op_argmax_, { o_logits, o_params, o_tok }));
@@ -1073,26 +989,20 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
     if (any_mask && !any_greedy)
         RAD_TRY(issue(op_mask_, { o_logits, o_params, o_mask }));
 
-    /* top-k reduces the vocabulary to a candidate set, and everything after it works on that set.
-     * Under tensor parallel this is the LOCAL top-k over this rank's shard; the candidate sets
-     * are combined below and full logits are never gathered (spec §9).
-     *
-     * IT IS ISSUED WHENEVER THE CHAIN RUNS, not only when some row sets top_k. A row at
-     * top_k = 0 asks for the whole candidate width, and the candidate planes are transient: a
-     * step that skipped this would hand the pick whatever the planes last held -- the previous
-     * step's candidates, or another op's bytes. */
+    /* Top-k reduces the vocabulary to the candidate set the rest works on; under tensor parallel
+     * it is per shard and the sets are merged below (spec §9). Always issued when the chain runs:
+     * top_k = 0 means the full candidate width, and the transient candidate planes hold stale
+     * bytes otherwise. */
     if (vocab_parallel()) {
-        /* The fifth operand is the pair plane: this rank's candidates with GLOBAL ids, which is
-         * what crosses the wire. cand_idx and cand_val still come back LOCAL and the merge
-         * overwrites both, so nothing downstream ever sees a local id. */
+        /* The fifth operand is the pair plane (global ids), which is what is gathered.
+         * cand_idx/cand_val come back local and the merge overwrites both. */
         const RadOperand o_p = opd_rows(buf_pairs_, n_seq_);
         const RadOperand o_g = opd_rows(buf_gather_, n_seq_);
         RAD_TRY(issue(op_topk_,      { o_logits, o_params, o_ci, o_cv, o_p }));
         RAD_TRY(issue(op_allgather_, { o_p, o_g }));
         RAD_TRY(issue(op_merge_,     { o_g, o_params, o_ci, o_cv }));
     } else {
-        /* No pair plane on a whole vocabulary, and it is passed as absent rather than left off:
-         * the schema has five operands and an issue of four is refused. */
+        /* No pair plane; passed as absent because the schema has five operands. */
         RAD_TRY(issue(op_topk_, { o_logits, o_params, o_ci, o_cv, opd_none() }));
     }
 
@@ -1105,10 +1015,9 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
 
     RAD_TRY(issue(op_pick_, { o_ci, o_cv, o_params, o_tok }));
 
-    /* AND THE LOGPROBS ROWS ON THEIR WAY TO THE HOST, behind the pick on the same stream: the
-     * summary, and the candidate planes the pick drew from (logprobs_for reads a token's value
-     * there when the summary does not hold it). Only the rows between the first and the last
-     * that asked, and only on rank 0, which is the rank collect_step asks. */
+    /* Copy the logprobs rows to the host behind the pick, on rank 0 only (collect_step asks
+     * it): the summary and the candidate planes, which logprobs_for reads when the summary lacks
+     * the token. Only rows from the first to the last that asked. */
     if (lp && cfg_.rank == 0) {
         lp_lo_ = lp_rows_.front().row;
         lp_hi_ = lp_rows_.back().row + 1;
@@ -1130,9 +1039,8 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
 float Sampler::raw_logit(const LpRow& L, int32_t token, float v) const {
     const DeviceSampleParams& p = L.p;
     double y = (double)v * (double)L.temp;
-    /* DRY subtracted a penalty that depends on the token and the window alone, so the host
-     * reference computes it for this one token: a single candidate at 0 comes back at minus the
-     * penalty. */
+    /* DRY's penalty depends only on the token and the window, so the host reference recomputes
+     * it on a single candidate at 0, which comes back as minus the penalty. */
     if (p.flags & RAD_SP_DRY) {
         static const DryBreakers kNone;
         CandidateSet s;
@@ -1146,9 +1054,9 @@ float Sampler::raw_logit(const LpRow& L, int32_t token, float v) const {
                  L.dry ? *L.dry : kNone);
         y -= (double)s.c[0].logit;
     }
-    /* The penalties, inverted: presence and frequency added back, then the repetition penalty
-     * undone on the side of zero the logit is on -- it never changes sign. The window is the
-     * stage's: the tail of the staged history, penalty_last_n long when that is positive. */
+    /* Penalties inverted: presence and frequency added back, then repetition undone on the
+     * logit's side of zero (it never changes sign). Window: the tail of the staged history,
+     * penalty_last_n long when positive. */
     if (p.flags & RAD_SP_PENALTY) {
         int64_t n = (int64_t)L.hist.size(), o = 0;
         if (p.penalty_last_n > 0 && n > p.penalty_last_n) { o = n - p.penalty_last_n; n = p.penalty_last_n; }
@@ -1177,8 +1085,8 @@ int merge_logprob_rows(const float* st, int W, int k, double* log_z, int32_t* id
         if (live(r)) sum += (double)st[r * w + 1] * std::exp((double)st[r * w] - mx);
     *log_z = sum > 0.0 ? mx + std::log(sum) : NAN;
 
-    /* On the stack for every split the engine runs (eight ranks of 21 pairs is 168); a call for
-     * more takes the heap rather than a bound. Once per emitted token, on collect_step's path. */
+    /* Stack buffer covers up to eight ranks of 21 pairs (168); more falls back to the heap.
+     * Runs once per emitted token on collect_step's path. */
     struct Pair { float v; int32_t id; };
     Pair buf[256];
     std::vector heap;
@@ -1214,16 +1122,14 @@ int Sampler::logprobs_for(int64_t row, int32_t token, TokenLogprobs* out) const
         if (x.row == row) { L = &x; break; }
     if (!L) return RAD_E_STATE;
 
-    /* Every rank's summary of its shard, merged: the maxima and normalisers by the usual
-     * rescale, the largest by value with the lower id first. */
+    /* Merge every rank's shard summary. */
     const int W = vocab_parallel() ? cfg_.world_size : 1;
     double log_z = 0.0;
     int32_t ids[kLpK * 8];
     float   vals[kLpK * 8];
     const int n = merge_logprob_rows(lp_host_ + row * W * lp_width(), W, kLpK, &log_z, ids, vals,
                                      (int)(sizeof ids / sizeof ids[0]));
-    /* A ROW WITH NO FINITE LOGIT HAS NO DISTRIBUTION to report against -- NaN logits out of the
-     * model, or every one at -inf -- and any number sent for it would be invented. */
+    /* No finite logit (NaN from the model, or all -inf) means no distribution to report. */
     if (!std::isfinite(log_z)) {
         RAD_WARN("sampler: row %lld has no finite logit; its logprobs cannot be computed",
                  (long long)row);
@@ -1238,8 +1144,8 @@ int Sampler::logprobs_for(int64_t row, int32_t token, TokenLogprobs* out) const
         out->top_lp[j] = (float)((double)vals[j] - log_z);
     }
 
-    /* The token's own raw logit: exact when it is among the largest, and otherwise recovered
-     * from the value the pick drew it at. */
+    /* The token's raw logit: exact if among the largest, else recovered from the value the pick
+     * drew it at. */
     double own = NAN;
     for (int j = 0; j < n && std::isnan(own); ++j)
         if (ids[j] == token) own = (double)vals[j];
diff --git a/core/sample/sampler.h b/core/sample/sampler.h
index 9a55de11..87c1c65a 100644
--- a/core/sample/sampler.h
+++ b/core/sample/sampler.h
@@ -1,14 +1,12 @@
 /* sampler.h -- the sampler driver.
  *
- * SAMPLING RUNS ON DEVICE (spec §13). At a 151K vocab and batch 256 the logits are ~77 MiB a
- * step; moving them across the link to run a host chain costs both the bandwidth and a
- * synchronisation, on the step path, at exactly the concurrency the engine exists to serve. So
- * every sampler is a kernel, not a lift -- and this file does not implement one. It ISSUES the
- * declared sampler ops in order, exactly as an architecture plugin issues a GEMM: declared
- * through the ordinary builder, resolved through the ordinary hierarchy, serviced by
- * `libref` on the host domain or by a device plugin on the fast one.
+ * Sampling runs on device (spec §13): at a 151K vocab and batch 256 the f32 logits are ~148 MiB a
+ * step, too much to move to the host and synchronise on the step path. This file implements no
+ * sampler. It issues the declared sampler ops in order, as an architecture plugin issues a GEMM:
+ * declared through the ordinary builder and resolved through the ordinary hierarchy to `libref`
+ * on the host domain or to a device plugin.
  *
- * THE ORDER, and it is not a detail -- reordering changes which tokens survive:
+ * Chain order (reordering changes which tokens survive):
  *
  *     penalties (repetition / frequency / presence, then DRY)
  *     temperature
@@ -18,38 +16,33 @@
  *     XTC
  *     the pick
  *
- * TEMPERATURE MAY RUN AFTER THE CUTS INSTEAD, per sequence: llama.cpp's order, which a request
- * names with `samplers` (SamplingParams::temp_last). Such a row's temperature is staged at 1 for
- * the stage above, which skips it, and at its own value for a second `sample_temp` over the
- * candidate plane after XTC -- the same kernel at the candidate width, so no plugin needs a
- * second implementation of it. Every other row is 1 there.
+ * Temperature last: a request may ask for llama.cpp's order with `samplers`
+ * (SamplingParams::temp_last). Such a row is staged with temperature 1 for the stage above, which
+ * then skips it, and with its own value for a second `sample_temp` over the candidate plane after
+ * XTC (the same kernel at the candidate width). Every other row is 1 there.
  *
- * LOGPROBS ARE READ OFF THE RAW LOGITS, before the first stage: `sample_logprobs` summarises each
- * row that asks (RAD_SP_LOGPROBS) as its maximum, its normaliser and its kLpK largest (one more
- * than RAD_MAX_LOGPROBS, for the row's width below), and rank 0 copies that back behind the pick.
- * The emitted token's own logprob is its raw logit less the log normaliser. When it is not among the largest its raw logit is no longer on the card
- * -- every stage wrote the logits in place -- so it is recovered from the value the pick drew it
- * at, the candidate plane's, by undoing temperature, DRY and the penalties on the host
- * (logprobs_for). Such a row is never a greedy-flagged one: a greedy row asking for logprobs is
- * staged as a top-1 chain row, so that its token is drawn from a candidate plane too.
+ * Logprobs: `sample_logprobs` summarises the raw logits, before the first stage, for each row
+ * flagged RAD_SP_LOGPROBS: its maximum, its normaliser and its kLpK largest (one more than
+ * RAD_MAX_LOGPROBS, see kLpK). Rank 0 copies the summary back behind the pick. The emitted
+ * token's logprob is its raw logit minus the log normaliser. When the token is not among the
+ * largest, its raw logit is gone (every stage writes the logits in place), so logprobs_for
+ * recovers it from the candidate-plane value the pick drew it at, undoing temperature, DRY and
+ * the penalties on the host. Such a row is therefore never greedy-flagged: a greedy row asking
+ * for logprobs is staged as a top-1 chain row.
  *
- * A GREEDY SEQUENCE SKIPS ALL OF IT and takes `sample_argmax` -- after penalties and the mask,
- * because temperature 0 collapses every other logit to -inf and a mask applied afterwards would
- * leave nothing at all. host_ref.cpp makes the same choice for the same reason and the two must
- * agree, or a temperature-0 request stops matching a greedy run.
+ * Greedy: a greedy sequence skips the chain and takes `sample_argmax`, after penalties and the
+ * mask. Temperature 0 collapses every other logit to -inf, so a mask applied afterwards would
+ * leave nothing. host_ref.cpp makes the same choice and the two must agree, or a temperature-0
+ * request stops matching a greedy run.
  *
- * PARAMETERS ARE DATA, NOT BRANCHES. Sequences in one batch have different sampling parameters,
- * so the parameters are a device-side per-sequence array built once per step from a pinned
- * staging buffer -- the same discipline the step batch uses (spec §8). A kernel that branched on
- * a host-side parameter would need one launch per distinct parameter set, which at batch 256 is
- * up to 256 launches for what is one kernel's worth of work.
+ * Parameters are data, not branches. They are a per-sequence device array built once per step
+ * from pinned staging, as the step batch is (spec §8). Branching on host-side parameters would
+ * need one launch per distinct parameter set, up to 256 at batch 256.
  *
- * THE SCHEMA THIS DRIVER ISSUES AGAINST (docs/OPS.md, "Sampling"). No per-sequence value is an
- * op PARAMETER, because parameters are geometry -- the thing the selector matches constraints
- * against and freezes at declare. A per-sequence value cannot live there: two requests in one
- * batch with different top_p would be two different geometries and therefore two different
+ * Schema (docs/OPS.md, "Sampling"). Op parameters are geometry, matched and frozen at declare,
+ * so no per-sequence value can be one: two requests with different top_p would be two
  * resolutions of the same op. The seed and output position `sample_pick` draws from are in the
- * parameter row too. So every sampler op takes the row array as an operand:
+ * row too. Every sampler op therefore takes the row array as an operand:
  *
  *   sample_penalties   M(range) n_vocab vocab_off?   logits, params, history  -> logits (inout)
  *   sample_dry         M(range) n_vocab vocab_off?   logits, params, history, breakers?
@@ -67,15 +60,14 @@
  *   sample_merge_topk  M(range) n_cand    gathered, params                -> cand_idx, cand_val
  *   sample_logprobs    M(range) n_vocab k vocab_off?   logits, params     -> stats
  *
- * `M` is the number of SAMPLED POSITIONS, not tokens: one per sequence at decode, n_spec+1 per
- * sequence at a verify. `params` is [M] rows of DeviceSampleParams below; `history` is
- * [M, max_hist] int32 of GLOBAL token ids, row m addressed by row m's hist_off/hist_len;
- * `breakers` is [M, max_hist] uint8 beside it, nonzero where that position's token is a whole DRY
- * sequence breaker; `bitmask` is [M, mask_words] uint32 addressed by the row's mask_row.
- * `vocab_off` is this rank's first vocabulary row and is declared only when the vocabulary is
- * split: the three ops that turn a token id into a column of this rank's logits subtract it.
- * Every one of these has a libref implementation: a sampler with no ref implementation has no
- * fallback and no oracle (spec §17).
+ * `M` counts sampled positions, not tokens: one per sequence at decode, n_spec+1 per sequence at
+ * a verify. `params` is [M] DeviceSampleParams rows. `history` is [M, max_hist] int32 global
+ * token ids, row m addressed by its hist_off/hist_len. `breakers` is [M, max_hist] uint8 beside
+ * it, nonzero where that token is a whole DRY sequence breaker. `bitmask` is [M, mask_words]
+ * uint32, addressed by the row's mask_row. `vocab_off` is this rank's first vocabulary row,
+ * declared only when the vocabulary is split; the three ops that map between token ids and this
+ * rank's logit columns use it. Every op has a libref implementation, which is both its fallback
+ * and its oracle (spec §17).
  */
 #pragma once
 #include "rad_sample.h"
@@ -94,32 +86,29 @@ namespace rad {
 
 /* ================================================================== the per-sequence row */
 
-/* THE ROW AND ITS FLAGS LIVE IN abi/rad_sample.h, because they are the wire format of
- * an OPERAND and therefore part of the ABI: libref reads these rows and a kernel plugin
- * cannot include a core header. The alias keeps this file's spelling. */
+/* The row and its flags live in abi/rad_sample.h: they are an operand's wire format, read by
+ * libref and by kernel plugins, which cannot include a core header. */
 using DeviceSampleParams = RadSampleParams;
 
 /* ================================================================== configuration */
 
 struct SamplerConfig {
-    int64_t n_vocab       = 0;    /* the WHOLE vocabulary */
-    int64_t n_vocab_local = 0;    /* THIS RANK's shard of it; == n_vocab when world_size == 1 */
+    int64_t n_vocab       = 0;    /* the whole vocabulary */
+    int64_t n_vocab_local = 0;    /* this rank's shard of it; == n_vocab when world_size == 1 */
     int64_t max_seqs      = 0;    /* the largest number of sequences one step may carry */
     int64_t max_hist      = 2048; /* the penalty window bound; a longer request is truncated */
     int     max_spec      = 0;
     int     rank          = 0;
     int     world_size    = 1;
-    /* This rank's first vocabulary row, which sample_topk adds to every candidate id it packs
-     * into the pair plane so the merge sees GLOBAL ids, and which sample_penalties and sample_dry
-     * subtract from the GLOBAL ids in the history to find this rank's column. Zero unless lm_head
-     * is row-sharded. */
+    /* This rank's first vocabulary row. sample_topk adds it to the candidate ids it packs into
+     * the pair plane, so the merge sees global ids; sample_penalties and sample_dry subtract it
+     * from the history's global ids. Zero unless lm_head is row-sharded. */
     int64_t vocab_off     = 0;
 
-    /* The candidate-set width the cuts work over. Every sampler after top-k operates on
-     * candidates rather than the vocabulary, so this bounds the buffers they read and write. It
-     * is a bound, not a policy: a request asking for a larger top-k than this is refused at
-     * admission, by name, rather than silently narrowed. */
-    int64_t max_candidates = 1024;
+    /* Candidate-set width for every stage after top-k; sizes their buffers. top_k 0 samples
+     * from this many of the most likely tokens, not the whole vocabulary. A request asking for a
+     * larger top-k is refused at admission, not silently narrowed. */
+    int64_t max_candidates = kSampleCandidates;
 };
 
 /* ================================================================== the driver */
@@ -131,139 +120,116 @@ public:
 
     /* ---------------------------------------------------------- declare phase */
 
-    /* Declare every sampler op and every buffer the chain needs, and allocate the pinned staging.
-     * Runs once, alongside the architecture plugin's declare, so the sampler's kernels resolve
-     * through the same hierarchy at the same time as everything else and a missing one is in the
-     * same missing-list (spec §3.1).
-     *
-     * A sampler op that does not resolve is NOT a declare failure: a deployment that never sends
-     * `typical_p` does not need a typical kernel. It becomes a failure when a request asks for
-     * it, which `check_request` reports by name. */
+    /* Declare every sampler op and buffer the chain needs and allocate the pinned staging. Runs
+     * alongside the architecture plugin's declare, so a missing kernel lands in the same
+     * missing-list (spec §3.1). An unresolved op is not a declare failure; check_request refuses
+     * the requests that need it, by name. */
     int declare(RadBuilder* b, const SamplerConfig& cfg);
 
-    /* The vocabulary view the grammar backends walk. Set after the tokeniser loads, before the
-     * first request. */
+    /* The vocabulary the grammar backends walk. Set after the tokeniser loads, before the first
+     * request. */
     void attach_vocab(const VocabView* v) { vocab_ = v; }
 
     /* ---------------------------------------------------------- admission */
 
-    /* Can this request's sampling parameters be served? Returns RAD_OK, or RAD_E_NOKERNEL naming
-     * the sampler that did not resolve, or RAD_E_INVAL naming the parameter that is out of range.
-     * Called on admission, so a request fails at the door rather than three steps in. */
+    /* Admission check. RAD_OK, RAD_E_NOKERNEL naming the sampler that did not resolve, or
+     * RAD_E_INVAL naming the out-of-range parameter. */
     int check_request(const SamplingParams& sp, std::string* why) const;
 
-    /* Build this request's grammar state, if it has a grammar. Runs on the scheduler thread, so
-     * it must not compile: a request admitted through the server carries its grammar compiled
-     * (SamplingParams::grammar_program), and this finds that program and positions a grammar in
-     * it. A request that arrives without one is compiled here, which costs its mask plan. */
+    /* Build the request's grammar state, if it has a grammar. Runs on the scheduler thread, so it
+     * should not compile: a server request carries its grammar compiled
+     * (SamplingParams::grammar_program) and this only positions a grammar in it. A request
+     * without one is compiled here, at the cost of its mask plan. */
     int begin_request(uint64_t req_id, const SamplingParams& sp, std::string* err);
     void end_request(uint64_t req_id);
-    /* Does this request already have state here? The step loop reaches a request on every step it
-     * is scheduled in, and begin_request is not idempotent -- calling it twice would rebuild the
-     * automaton and throw away everything it had accepted, which silently unconstrains a
-     * generation from its second token onward. */
+    /* begin_request is not idempotent: a second call rebuilds the automaton and discards what it
+     * accepted, unconstraining the rest of the generation. The step loop checks this first. */
     bool has_request(uint64_t req_id) const;
 
-    /* Requests build_step could not serve: a grammar that reached a state admitting no token.
-     * Returned and cleared; the caller cancels them. Empty on almost every step. */
+    /* Requests whose grammar reached a state admitting no token. Returned and cleared; the
+     * caller cancels them. */
     std::vector take_failed();
 
     /* Advance a request's grammar over the token it just emitted. */
     int accept_token(uint64_t req_id, int32_t token);
 
-    /* May the scheduler speculate on this request? Yes, unless it carries a constraining grammar
-     * whose backend cannot snapshot its state. The mask for draft position i depends on which of
-     * positions 0..i-1 were accepted, so masking a window means walking the grammar forward over
-     * the proposals and rewinding afterwards; a backend without push_state/rollback cannot, and
-     * such a request decodes one token at a time rather than silently emitting drafts the grammar
-     * forbids. */
+    /* False only for a constraining grammar whose backend cannot snapshot its state. Masking a
+     * draft window walks the grammar over the drafts and rewinds, which needs
+     * push_state/rollback; without it the request decodes one token at a time. */
     bool allows_speculation(uint64_t req_id) const;
-    /* Is allows_speculation's answer fixed for this request? It changes only when a grammar whose
-     * backend cannot rewind starts to constrain, which is a commit's doing; a request with no
-     * grammar, or one whose backend rewinds, answers the same at every step. */
+    /* Whether allows_speculation's answer can no longer change. It changes only when a grammar
+     * whose backend cannot rewind starts to constrain (on a commit). */
     bool speculation_fixed(uint64_t req_id) const;
 
     /* ---------------------------------------------------------- step path */
 
-    /* Build the per-sequence parameter array, the packed penalty history and the grammar
-     * bitmasks for this step, into pinned staging. Scheduler-thread work: it touches request
-     * state and host grammar automata, and it must be done before the rank threads are released
-     * at the barrier.
-     *
-     * Allocates nothing -- every buffer was sized at declare against max_seqs (spec §3.1). */
+    /* Stage this step's parameter rows, penalty history and grammar bitmasks into pinned memory.
+     * Scheduler thread, before the rank threads are released at the barrier. Allocates nothing;
+     * every buffer was sized at declare against max_seqs (spec §3.1). */
     int build_step(const std::vector& reqs);
 
-    /* THE SAME STAGING, FILLED FOR A GREEDY DRAFTER. `n` rows of argmax: no penalties, no
-     * grammar mask, no history, and the RNG untouched -- so the chain resolves to op_argmax and
-     * nothing else runs.
-     *
-     * It exists because a DRAFT round is not a request's own sampling. Its output is a
-     * proposal the target then verifies, and the verifier is greedy (core/sample/accept.h): a
-     * drafter that sampled at the request's temperature would spend the request's RNG stream
-     * on tokens that may never be emitted, and would lower acceptance for nothing. Every MTP
-     * head that ships inside a target checkpoint is greedy for the same reason. */
+    /* Stage `n` greedy rows for a drafter: no penalties, mask or history, and no RNG use, so
+     * only the argmax runs. Draft output is a proposal checked by a greedy verifier
+     * (core/sample/accept.h); sampling it at the request's temperature would spend the request's
+     * RNG stream on tokens that may never be emitted and lower acceptance. */
     int build_greedy(int64_t n);
 
-    /* Upload the staging and issue the chain. Rank-thread work, on the compute stream, with no
-     * host synchronisation in it.
-     *
-     * `logits` holds [n_seq, n_vocab_local] and `out_tokens` receives [n_seq] token ids. Under
-     * tensor parallel the candidate merge (`sample_merge_topk`, or `row_topk_merge` fused with the
-     * top-k) happens between the top-k and the cuts; full logits are never gathered. */
+    /* Upload the staging and issue the chain. Rank thread, compute stream, no host sync.
+     * `logits` is [n_seq, n_vocab_local]; `out_tokens` receives [n_seq] token ids. Under tensor
+     * parallel the candidate merge (`sample_merge_topk`, or `row_topk_merge` fused with the
+     * top-k) runs between the top-k and the cuts; full logits are never gathered. */
     int run(RadCtx* c, rad_buf logits, rad_buf out_tokens);
 
-    /* THE EMITTED TOKEN'S LOGPROBS, after the step the last build_step staged has completed on the
-     * card: row `row` must have been staged for a request with SamplingParams::n_probs >= 0, and
-     * `token` is what the step sampled there. Rank 0's sampler only -- it is the one that copies
-     * the summary back. RAD_E_STATE for a row that was not staged for logprobs; RAD_E_INVAL, with
-     * `out->token` -1, for one whose numbers are not finite -- a row with no finite logit, or a
-     * token drawn where none was -- which is a number no client should be sent. */
+    /* The emitted token's logprobs, once the step the last build_step staged has completed.
+     * `row` must have been staged with SamplingParams::n_probs >= 0 and `token` is what was
+     * sampled there. Rank 0 only, since it holds the copy. RAD_E_STATE for a row not staged for
+     * logprobs; RAD_E_INVAL with `out->token` = -1 when the numbers are not finite (no finite
+     * logit in the row, or none for the token). */
     int logprobs_for(int64_t row, int32_t token, TokenLogprobs* out) const;
-    /* Did `sample_logprobs` resolve? What the server advertises as logprobs support. */
+    /* Whether `sample_logprobs` resolved; what the server advertises as logprobs support. */
     bool has_logprobs() const { return op_logprobs_ != RAD_NULL_HANDLE; }
     const SamplerConfig& config() const { return cfg_; }
 
-    /* The parameter rows the last build_step or build_greedy staged, and how many. What `run`
-     * uploads, readable so the staging can be checked without a device behind it. */
+    /* The rows the last build_step or build_greedy staged, as `run` uploads them; lets the
+     * staging be checked without a device. */
     const DeviceSampleParams* staged_params(int64_t* n) const {
         if (n) *n = n_seq_;
         return cur_stage_;
     }
+    /* Staged row `row`'s bitmask as `run` uploads it: this rank's shard, `mask_words()` words,
+     * meaningful only where the row carries RAD_SP_MASK. */
+    const uint32_t* staged_mask(int64_t row) const { return mask_stage_ + row * mask_words_; }
+    int64_t         mask_words() const { return mask_words_; }
 
 private:
-    /* IS THE VOCABULARY ACTUALLY SPLIT? Not the same question as "is there more than one rank".
-     * A tensor-parallel deployment whose plugin declares `output.weight` replicated gives every
-     * rank the whole vocabulary, and then the candidate merge is not just unnecessary but wrong:
-     * every rank would contribute the SAME k candidates and the gather would count them once per
-     * rank. The declared width of this rank's logits is the fact, so that is what this asks. */
+    /* Whether the vocabulary is split, judged by this rank's logit width rather than the rank
+     * count: with `output.weight` replicated every rank holds the whole vocabulary, and a merge
+     * would count each candidate once per rank. */
     bool vocab_parallel() const {
         return cfg_.world_size > 1 && cfg_.n_vocab_local < cfg_.n_vocab;
     }
 
-    /* `dry` holds the request's resolved sequence breakers, empty when it sent none -- which is
-     * not "DRY off": DRY runs whenever its multiplier is set, with or without breakers. */
+    /* `dry` holds the resolved sequence breakers, empty when the request sent none. Empty does
+     * not mean DRY is off; DRY runs whenever its multiplier is set. */
     struct SeqState {
         std::unique_ptr grammar;
         DryBreakers                     dry;
-        /* Where the reply stands against its reasoning block, over `output[0, think_seen)`.
-         * Advanced by build_step over what each commit appended, so a step costs the tokens it
-         * added and not the reply's length. Read only when the request carries a budget. */
+        /* Reasoning-block state over `output[0, think_seen)`. build_step advances it over the
+         * newly committed tokens only. Read only when the request carries a thinking budget. */
         ReasoningCount                  think;
         size_t                          think_seen = 0;
     };
 
-    /* Mask staged row `row` to the reasoning block's close token: the budget is spent and the
-     * sampled position is still inside the block. A grammar already masking the row keeps the
-     * last word -- the close is forced only where the grammar admits it, and a row whose grammar
-     * forbids it is left to the grammar and forced at a later position. */
+    /* Mask staged row `row` to the reasoning block's close token, once the budget is spent
+     * inside the block. A grammar mask on the row wins: the close is forced only where the
+     * grammar admits it, otherwise at a later position. */
     void force_close(DeviceSampleParams& p, int64_t row, int32_t close);
 
     SamplerConfig    cfg_{};
     const VocabView* vocab_ = nullptr;
     bool             declared_ = false;
 
-    /* Declared op handles. RAD_NULL_HANDLE means the op did not resolve; the admission check
-     * turns that into a named refusal rather than a silent skip. */
+    /* Declared op handles; RAD_NULL_HANDLE means unresolved, which admission refuses by name. */
     rad_op op_penalties_ = RAD_NULL_HANDLE;
     rad_op op_dry_       = RAD_NULL_HANDLE;
     rad_op op_temp_      = RAD_NULL_HANDLE;
@@ -278,7 +244,7 @@ private:
     rad_op op_argmax_    = RAD_NULL_HANDLE;
     rad_op op_allgather_ = RAD_NULL_HANDLE;
     rad_op op_merge_     = RAD_NULL_HANDLE;   /* the candidate merge, under tensor parallel */
-    rad_op op_logprobs_  = RAD_NULL_HANDLE;   /* the raw distribution's summary */
+    rad_op op_logprobs_  = RAD_NULL_HANDLE;   /* summary of the raw distribution */
     rad_op op_lp_gather_ = RAD_NULL_HANDLE;   /* every rank's summary, under a split vocabulary */
 
     /* Device-side buffers, from the ordinary buffer plan. */
@@ -294,17 +260,16 @@ private:
     rad_buf buf_lp_      = RAD_NULL_HANDLE;   /* sample_logprobs' stats, [rows, lp_width()] */
     rad_buf buf_lp_g_    = RAD_NULL_HANDLE;   /* and every rank's side by side */
 
-    /* Pinned staging. One allocation each, at declare, never on the step path. */
+    /* Pinned staging, allocated once at declare. */
     DeviceSampleParams* params_stage_ = nullptr;
-    /* The late temperature's rows: params_stage_'s, with each row's temperature at 1 unless it
-     * runs last. Uploaded only by a step where some row does (any_late_). */
+    /* Copies of params_stage_'s rows with temperature 1 unless the row runs temperature last.
+     * Uploaded only when some row does (any_late_). */
     DeviceSampleParams* late_stage_   = nullptr;
     bool                any_late_     = false;
-    /* THE GREEDY ROWS HAVE STAGING OF THEIR OWN, written once. A draft pass is staged while the
-     * step before it -- whose sampler uploads `params_stage_` when the card reaches it -- may not
-     * have run yet; rows written into the same staging would reach that step's sampler instead.
-     * Every greedy row is the same row, so this one is filled on first use and never again, and
-     * no upload of it can ever see a later build. */
+    /* Greedy rows have their own staging, filled once on first use. A draft pass is staged
+     * while the previous step's upload of params_stage_ may still be pending, so writing there
+     * would change that step's rows. Every greedy row is identical, so no upload of this buffer
+     * can observe a later build. */
     DeviceSampleParams* greedy_stage_ = nullptr;
     bool                greedy_ready_ = false;
     const DeviceSampleParams* cur_stage_ = nullptr;   /* what the last build staged */
@@ -312,46 +277,42 @@ private:
     uint8_t*            brk_stage_    = nullptr;
     uint32_t*           mask_stage_   = nullptr;
 
-    int64_t mask_words_ = 0;      /* words for THIS RANK's shard; what the mask op indexes */
+    int64_t mask_words_ = 0;      /* words for this rank's shard; what the mask op indexes */
     int64_t n_seq_      = 0;
-    /* Does any DRY row this step carry breakers? Only then is the breaker plane uploaded and
-     * handed to sample_dry; a batch whose DRY requests sent none issues it without the operand. */
+    /* Whether any DRY row this step has breakers; only then is the breaker plane uploaded and
+     * passed to sample_dry. */
     bool    any_brk_    = false;
 
-    /* The whole-vocabulary mask the grammar fills, from which the staged shard is cut. Only used
-     * when the head is sharded; see the note in declare(). */
+    /* The whole-vocabulary mask the grammar fills, from which this rank's shard is cut. Used
+     * only when the head is sharded; see declare(). */
     std::vector mask_full_;
 
-    /* The grammar mask's cost, accumulated for the Debug line in build_step. Not state the step
-       path reads -- a diagnostic, and one worth carrying: the mask walk is scheduler-thread work
-       large enough to decide the step time of a constrained request, so it has to be visible
-       rather than assumed. */
+    /* Debug-level timing of the grammar mask, build_step and accept_token. The mask walk is
+       scheduler-thread work that can set the step time of a constrained request. */
     double  mask_us_       = 0.0;
     double  mask_worst_us_ = 0.0;
     int64_t mask_us_n_     = 0;
     int64_t mask_fast_     = 0;   /* memo hits */
     int64_t mask_slow_     = 0;   /* walks    */
-    double  mask_walk_us_  = 0.0; /* and what only the walks cost */
+    double  mask_walk_us_  = 0.0; /* time spent in walks only */
     double  build_us_      = 0.0;
     int64_t build_n_       = 0;
     double  accept_us_     = 0.0;
     int64_t accept_n_      = 0;
     void shard_mask(uint32_t* dst) const;
 
-    /* Requests whose grammar died this step. Drained by the engine, which cancels them -- one bad
-     * request must not stop the step loop for everyone else. */
+    /* Requests whose grammar died this step. The engine drains and cancels them, so one bad
+     * request does not stop the step loop. */
     std::vector failed_;
 
     /* ---------------------------------------------------------- logprobs */
-    /* THE SUMMARY'S WIDTH: RAD_MAX_LOGPROBS + 1 pairs, not RAD_MAX_LOGPROBS, so that a row is 44
-     * floats -- whole 16-byte words, which is what the all-gather of a split vocabulary moves (and
-     * libr4d's refuses anything else). The extra pair is never reported. */
+    /* RAD_MAX_LOGPROBS + 1 pairs, so a summary row is 44 floats: whole 16-byte words, which
+     * libr4d's all-gather of a split vocabulary requires. The extra pair is never reported. */
     static constexpr int kLpK = RAD_MAX_LOGPROBS + 1;
     static int64_t lp_width() { return 2 + 2 * (int64_t)kLpK; }
-    /* WHAT UNDOING A ROW'S CHAIN NEEDS, kept from build_step for each row staged with
-     * RAD_SP_LOGPROBS: the staged row itself, the temperature the candidate value carries, the
-     * history window both history stages read, and the request's DRY breakers. Copied rather
-     * than pointed at, because the staging is rebuilt by the next step. */
+    /* What raw_logit needs to undo a RAD_SP_LOGPROBS row's chain, saved by build_step: the
+     * staged row, the temperature the candidate value carries, the history window and the DRY
+     * breakers. Copied, because the next step rebuilds the staging. */
     struct LpRow {
         int64_t            row = -1;
         int32_t            n_top = 0;
@@ -368,24 +329,22 @@ private:
     float*   lp_cv_host_ = nullptr;
     int64_t  lp_lo_ = 0, lp_hi_ = 0;             /* the rows copied, [lo, hi) */
     /* A token's raw logit from the value the pick drew it at: temperature, DRY and the penalties
-     * undone, in the reverse of the order the chain applied them. */
+     * undone in reverse order. */
     float raw_logit(const LpRow& L, int32_t token, float v) const;
 
-    /* Per-request grammar and DRY state, keyed by request id. Held here rather than in Request
-     * because Request is a frozen struct shared across components and a unique_ptr in it would
-     * make the scheduler's copies a compile error. */
+    /* Per-request grammar and DRY state. Not in Request, a frozen struct the scheduler copies,
+     * which a unique_ptr member would make non-copyable. */
     std::unordered_map seqs_;
 
     int stage_alloc();
     void stage_free();
 };
 
-/* SPLIT-VOCABULARY SUMMARIES, MERGED: `W` ranks' `sample_logprobs` rows of `k` pairs each, side by
- * side in `st` (W * (2 + 2k) floats). Sets the shared log normaliser and fills up to `cap` of the
- * largest (id, logit) pairs over every rank, descending, ties to the lower id; returns how many. A
- * rank whose maximum or normaliser is not finite contributes nothing, nor does a pair whose logit
- * is not finite, and `*log_z` comes back NaN when no rank contributes. One rank is the same
- * arithmetic. What Sampler::logprobs_for reads a step's summaries with. */
+/* Merge `W` ranks' `sample_logprobs` rows of `k` pairs each, side by side in `st`
+ * (W * (2 + 2k) floats). Sets the combined log normaliser and fills up to `cap` of the largest
+ * (id, logit) pairs, descending, ties to the lower id; returns how many. Ranks with a non-finite
+ * maximum or normaliser and pairs with a non-finite logit are skipped; `*log_z` is NaN when no
+ * rank contributes. W = 1 is valid. Used by Sampler::logprobs_for. */
 int merge_logprob_rows(const float* st, int W, int k, double* log_z, int32_t* ids, float* vals,
                        int cap);
 
diff --git a/core/sample/vocab_view.h b/core/sample/vocab_view.h
index 7cb9d2db..69ff07c1 100644
--- a/core/sample/vocab_view.h
+++ b/core/sample/vocab_view.h
@@ -1,15 +1,11 @@
-/* vocab_view.h -- what the sampler needs to know about a vocabulary, and nothing else.
+/* vocab_view.h -- what the sampler needs to know about a vocabulary.
  *
- * The tokeniser lives in core/text/ and belongs to the text frontend. The sampler needs exactly
- * three facts about a token -- how many there are, its printable piece, and whether it ends
- * generation -- plus, for DRY's sequence breakers and GBNF's `` syntax, the ability to
- * tokenise a short literal. Taking a dependency on the whole tokeniser for that would put a
- * component boundary on the step path and make every sampler test drag a real vocabulary behind
- * it. An abstract view costs one virtual call per token per grammar step, which is host work the
- * device is not waiting on.
+ * The sampler needs the token count, each token's piece and whether it ends generation, plus
+ * tokenising a short literal for DRY's sequence breakers and GBNF's `` syntax. This view
+ * keeps the tokeniser (core/text/) out of the sampler and its tests; a virtual call per token per
+ * grammar step is host work the device does not wait on.
  *
- * core/text/ implements this over the real vocab; SimpleVocab below implements it over a table,
- * which is what the tests use.
+ * text/token_view.h implements it over the real vocab; SimpleVocab over a table, for tests.
  */
 #pragma once
 #include "../rad_internal.h"
@@ -27,10 +23,8 @@ public:
 
     virtual int32_t n_tokens() const = 0;
 
-    /* The token's bytes as they would be appended to the output stream. The grammar walks these,
-     * so a view that returns a display form rather than the exact bytes will admit the wrong
-     * token set -- and the failure mode is plausible text with wrong structure, which is the
-     * hardest kind to notice. */
+    /* The token's exact bytes as appended to the output stream. The grammar walks these; a
+     * display form would make it admit the wrong token set. */
     virtual const std::string& token_piece(int32_t id) const = 0;
 
     /* End-of-generation: EOS, EOT, and whatever else this model ends on. A grammar admits one
@@ -38,15 +32,14 @@ public:
     virtual bool is_eog(int32_t id) const = 0;
 
     /* Tokenise a short literal. Only DRY's sequence breakers and GBNF's `` form need it,
-     * and both are optional features, so a view that has no tokeniser returns
-     * RAD_E_UNSUPPORTED rather than pretending. */
+     * both optional, so a view without a tokeniser returns RAD_E_UNSUPPORTED. */
     virtual int tokenize(const std::string& text, std::vector* out) const {
         (void)text; (void)out;
         return RAD_E_UNSUPPORTED;
     }
 
-    /* The same with special tokens recognised in the text, so `` comes back as the
-     * one control token a template means by it. Grammar triggers are resolved through this. */
+    /* As tokenize, but recognising special tokens, so `` comes back as the one control
+     * token. Grammar triggers resolve through this. */
     virtual int tokenize_special(const std::string& text, std::vector* out) const {
         (void)text; (void)out;
         return RAD_E_UNSUPPORTED;
@@ -54,25 +47,16 @@ public:
 
     /* ---------------- what a grammar backend derives from this vocabulary ----------------
      *
-     * A GBNF mask is built over a DECODED form of the whole vocabulary -- every piece as code
-     * points, plus a trie over them -- which costs a full vocabulary scan and is therefore
-     * computed once and kept. It is kept HERE, with the vocabulary's own lifetime, because the
-     * only other place to keep it is a table outside, and the only key such a table has is this
-     * object's ADDRESS. An address is not an identity: a view destroyed and another constructed
-     * in the same storage answers to the same key, and the second one is then served what was
-     * derived for the first -- the decoded vocabulary, the trie over it, and the grammars
-     * compiled against both. The mask that comes out is a mask over another model's tokens: it
-     * admits the wrong set, or nothing at all, and nothing downstream can tell. Tying the cache
-     * to the object makes the question unaskable.
-     *
-     * Opaque and mutable: what is cached is the backend's business and this header is the
-     * sampler's interface, and filling it does not change what the vocabulary says. A backend
-     * that caches nothing pays one null pointer. */
+     * A GBNF mask works over a decoded form of the whole vocabulary (pieces as code points plus a
+     * trie), which costs a full scan and is computed once. It is cached here, with the view's own
+     * lifetime, because an external table could only key on the view's address, and a new view
+     * built in the same storage would then be served the old model's decoded vocabulary and
+     * compiled grammars. Opaque and mutable: its contents are the backend's business and filling
+     * it does not change what the vocabulary says. */
     mutable std::shared_ptr gbnf_cache;
 };
 
-/* A vocabulary held as a table. Not a toy: it is what the sampler tests are written against, and
- * being able to state a vocabulary in four lines is what makes a grammar test readable. */
+/* A vocabulary held as a table, for the sampler and grammar tests. */
 class SimpleVocab : public VocabView {
 public:
     SimpleVocab() = default;
@@ -85,8 +69,6 @@ public:
         return id;
     }
 
-    void mark_eog(int32_t id) { eog_.push_back(id); }
-
     int32_t n_tokens() const override { return (int32_t)pieces_.size(); }
 
     const std::string& token_piece(int32_t id) const override {
@@ -100,14 +82,13 @@ public:
         return false;
     }
 
-    /* Longest-match over the table, which is not BPE and does not pretend to be. It exists so a
-     * DRY sequence breaker or a `` literal resolves in a test; a real vocabulary's merge
-     * machinery lives in core/text/. */
     /* A table has no special tokens of its own: every piece is matched as written. */
     int tokenize_special(const std::string& text, std::vector* out) const override {
         return tokenize(text, out);
     }
 
+    /* Longest match over the table, not BPE. Enough for a DRY breaker or a `` literal in a
+     * test; real tokenisation lives in core/text/. */
     int tokenize(const std::string& text, std::vector* out) const override {
         if (!out) return RAD_E_INVAL;
         size_t pos = 0;
diff --git a/core/sample/word_scan.cpp b/core/sample/word_scan.cpp
index 5487b28b..358022af 100644
--- a/core/sample/word_scan.cpp
+++ b/core/sample/word_scan.cpp
@@ -26,8 +26,8 @@ int WordScanner::build(const std::vector& words, std::string* err)
                 cls_[c] = (uint8_t)ncls_++;
             }
 
-    /* The trie, with its edges held densely from the start: a missing edge is kUnset until the
-     * breadth-first pass below resolves it through the failure link. */
+    /* The trie with dense edges; a missing edge is kUnset until the breadth-first pass resolves
+     * it through the failure link. */
     constexpr uint32_t kUnset = ~0u;
     next_.assign(ncls_, kUnset);
     out_len_.assign(1, 0u);
@@ -47,9 +47,9 @@ int WordScanner::build(const std::vector& words, std::string* err)
         max_len_    = std::max(max_len_, (uint32_t)w.size());
     }
 
-    /* Failure links in breadth-first order, so a state's link is final before any deeper state
-     * reads it. A state's longest match is its own word if it ends one, which is longer than any
-     * proper suffix, and otherwise its failure state's. */
+    /* Failure links in breadth-first order, so a state's link is final before a deeper state
+     * reads it. A state's longest match is its own word if it ends one, else its failure
+     * state's. */
     const uint32_t n_states = (uint32_t)out_len_.size();
     std::vector fail(n_states, 0u);
     std::vector queue;
diff --git a/core/sample/word_scan.h b/core/sample/word_scan.h
index 5fb353b9..0d9dc01e 100644
--- a/core/sample/word_scan.h
+++ b/core/sample/word_scan.h
@@ -1,23 +1,20 @@
 /* word_scan.h -- find the first of a set of literal words in a byte stream that arrives in pieces.
  *
- * A lazy grammar waits for its trigger word -- `\n` on the Qwen templates -- and until
- * the word appears every generated token passes through here. The stream is the whole reply, so
- * anything that looks back over what has already arrived turns a long reply into quadratic host
- * work on the step path. This looks back at nothing: the scan state is one integer, each byte is
- * one table load, and what a match needs to be replayed is bounded by the longest word.
+ * A lazy grammar waits for its trigger word (`\n` on the Qwen templates), and every
+ * generated token passes through here until it appears. Looking back over the stream would make a
+ * long reply quadratic host work, so the scan keeps one integer of state and does one table load
+ * per byte; replaying a match needs at most the longest word.
  *
- * THE AUTOMATON is Aho-Corasick compiled to a full DFA over byte classes. The trie of the words
- * gets failure links in breadth-first order, and every missing edge is resolved through them once,
- * at build time, so the scan never follows a failure chain. Bytes that occur in no word share one
- * class, which keeps the table at (states x distinct word bytes + 1) entries -- a few hundred for
- * any real trigger set, so it stays in L1 however long the reply runs.
+ * Automaton: Aho-Corasick compiled to a full DFA over byte classes. Failure links are built
+ * breadth-first and every missing edge is resolved through them at build time, so the scan never
+ * follows a failure chain. Bytes in no word share one class, so the table has
+ * states x (distinct word bytes + 1) entries: a few hundred for a real trigger set, so it stays
+ * in L1.
  *
- * THE MATCH REPORTED is the leftmost START among the occurrences that complete inside one fed
- * piece. That is the answer a search of the whole stream so far gives after each piece: nothing
- * completed in an earlier piece (the caller would have stopped), so every complete occurrence ends
- * in this one, and of those the leftmost is the one that begins first. Each state carries the
- * length of the LONGEST word ending there, because the longest word ending at a byte is the one
- * that starts earliest.
+ * Match reported: the leftmost start among occurrences that complete inside one fed piece. Since
+ * the caller stops at the first match, nothing completed earlier, so this equals a search of the
+ * whole stream so far. Each state carries the length of the longest word ending there, which is
+ * the one that starts earliest.
  */
 #pragma once
 #include "../rad_internal.h"
@@ -33,8 +30,8 @@ class WordScanner {
 public:
     static constexpr uint64_t npos = ~(uint64_t)0;
 
-    /* Where a stream is: the automaton state and how many bytes have been fed. Plain data, so a
-     * speculative window can copy it and put it back. */
+    /* Automaton state and bytes fed so far. Plain data, so a speculative window can copy and
+     * restore it. */
     struct State {
         uint32_t s   = 0;
         uint64_t off = 0;
diff --git a/core/sched/advance.cpp b/core/sched/advance.cpp
index d4b5e8c3..ad87fa33 100644
--- a/core/sched/advance.cpp
+++ b/core/sched/advance.cpp
@@ -7,11 +7,9 @@ namespace rad {
 
 int step_advance(const AdvanceArgs& a, RadStream s) {
     if (a.n_seq <= 0) return RAD_OK;
-    /* THE HOST BACKEND'S STREAMS ARE QUEUES, each run by its own worker thread (device/host.cpp),
-     * and its device memory is host memory. So the rows run here once the stream has finished
-     * everything issued before this call, which is where the kernel would run in stream order.
-     * Without the wait they can read a sampled token or a staged row whose copy is still queued,
-     * and the next step then continues from the token before it. */
+    /* Host backend streams are queues run by worker threads (device/host.cpp), and device memory
+     * is host memory. Drain the stream first so the rows run where the kernel would in stream
+     * order; otherwise they can read a sampled token or staged row whose copy is still queued. */
     if (device_is_host()) {
         RAD_TRY(rad_stream_sync(s));
         for (int i = 0; i < a.n_seq; ++i) adv_row(a, i);
diff --git a/core/sched/advance.h b/core/sched/advance.h
index 44a3cf16..ec6dc705 100644
--- a/core/sched/advance.h
+++ b/core/sched/advance.h
@@ -1,27 +1,23 @@
 /* advance.h -- the card's own bookkeeping between passes: which drafts a verify step accepted, and
  * the inputs of every pass that follows from it.
  *
- * WHY THE CARD DOES THIS AND NOT THE HOST. A speculative step is a verify pass and the draft passes
- * behind it, and every pass after the verify depends on how many drafts it accepted: the draft
- * head continues from the accepted position, and the next verify starts after it. Deciding that on
- * the host means reading the sampled tokens back, waiting for them, and only then staging the next
- * pass -- a synchronisation per step during which the card has nothing queued. Deciding it here
- * lets the host stage and issue every pass of a step, and the next step, before any of them has
- * run: the rule is a compare of a few integers a sequence, and the card already holds all of them.
+ * Why on the card: every pass after a verify depends on how many drafts it accepted (the draft
+ * head continues from the accepted position, the next verify starts after it). Deciding that on
+ * the host costs a readback and a sync per step with the card idle. On the card it is a compare
+ * of a few integers per sequence, so the host can stage and issue every pass of a step, and the
+ * next step, before any of them runs.
  *
- * THE STATE IS PER SEQUENCE SLOT (StepSlot), in device memory on every rank, and it carries exactly
- * what a pass needs that the host cannot know in advance: where the next verify starts, what it
- * rolls back, which tokens it verifies, and where the draft head continues from. Every rank keeps
- * its own copy and computes the same numbers from the same sampled tokens, so no rank ever reads
- * another's memory.
+ * State: one StepSlot per sequence slot, in device memory on every rank. It holds what the host
+ * cannot know in advance: where the next verify starts, what it rolls back, which tokens it
+ * verifies and where the draft head continues. Each rank computes the same numbers from the same
+ * sampled tokens, so no rank reads another's memory.
  *
- * A PASS NAMES ITS DEVICE ROWS. A batch can mix rows whose inputs the host staged -- a prefill
- * chunk, a history row for positions the host already knows -- with rows whose positions come from
- * the card; `rows[0][i]` says which, and the advance leaves a host row exactly as it was uploaded.
+ * Device rows: a batch can mix host-staged rows (a prefill chunk, a history row at known
+ * positions) with rows whose positions come from the card. `rows[0][i]` says which; the advance
+ * leaves a host row as uploaded.
  *
- * The same code runs on the host backend, where device memory is host memory: the rows run on the
- * issuing thread once the stream has drained, which is their place in stream order
- * (advance_impl.h is shared by both builds).
+ * On the host backend, device memory is host memory and the rows run on the issuing thread once
+ * the stream has drained (advance_impl.h is shared by both builds).
  */
 #pragma once
 #include 
@@ -87,18 +83,17 @@ struct AdvanceArgs {
     int64_t src_pitch = 1;
     const int32_t* eog = nullptr;   /* end-of-generation ids, sorted */
     int32_t n_eog = 0;
-    /* THE ROTARY PLANES (RadBatch::rope_pos), [3][rope_pitch] at rope_off, or rope_off -1 when the
-     * build carries none. A row whose position the card moves carries its rotary position along
-     * by the offset the host staged for it: the rows the card owns are decode and draft rows, all
-     * text, and text rotates at its index plus one per-sequence shift. A row the card leaves at
-     * the host's position keeps the host's three components, which is what a media token needs. */
+    /* Rotary planes (RadBatch::rope_pos), [3][rope_pitch] at rope_off; rope_off -1 when the build
+     * has none. A row the card moves keeps the host-staged offset between its position and its
+     * rotary position: card-owned rows are decode and draft rows, all text, which rotate at their
+     * index plus a per-sequence shift. A row left at the host's position keeps the host's three
+     * components, as a media token needs. */
     int64_t rope_off = -1;
     int32_t rope_pitch = 0;
-    /* A SERIAL HEAD WITH NO CACHE OF ITS OWN (rad_drafter_shared_kv), read by ADV_HIST and
-     * ADV_ROUND alone: its history pass is one row a sequence at the committed position, and every
-     * round sits there too, its context ending at that position. `rot_shift` is where those rows
-     * sit for the rotary, 0 or 1 past the committed position. Zero for every other head, whose
-     * passes advance exactly as they always did. */
+    /* A serial head with no cache of its own (rad_drafter_shared_kv), read by ADV_HIST and
+     * ADV_ROUND only: its history pass is one row per sequence at the committed position, and
+     * every round sits there too, with context ending at that position. `rot_shift` is the rotary
+     * position of those rows, 0 or 1 past the committed position. Zero for every other head. */
     int32_t shared_kv = 0;
     int32_t rot_shift = 0;
 };
diff --git a/core/sched/advance.hip b/core/sched/advance.hip
index 24519305..463fd95f 100644
--- a/core/sched/advance.hip
+++ b/core/sched/advance.hip
@@ -1,7 +1,7 @@
-/* advance.hip -- the advance kernel: one thread a row of the batch it patches. See advance.h.
+/* advance.hip -- the advance kernel: one thread per row of the batch it patches. See advance.h.
  *
- * Launched through hipLaunchKernel like any kernel library's, which the AQL backend intercepts, so
- * it is one dispatch on the rank's own queue in stream order with the pass it belongs to.
+ * Launched through hipLaunchKernel, which the AQL backend intercepts, so it is one dispatch on the
+ * rank's own queue, in stream order with its pass.
  */
 #include 
 
diff --git a/core/sched/advance_impl.h b/core/sched/advance_impl.h
index 667e6b03..df289759 100644
--- a/core/sched/advance_impl.h
+++ b/core/sched/advance_impl.h
@@ -1,8 +1,8 @@
 /* advance_impl.h -- one row of an advance, shared by the kernel (advance.hip) and the host backend
- * (advance.cpp). See advance.h for what the modes are and why the card computes them.
+ * (advance.cpp). See advance.h for the modes.
  *
- * Every row is independent: it reads its own slot's state and writes only its own positions,
- * tokens and slots, so the kernel runs one thread a row and the host a loop.
+ * Rows are independent: each reads its own slot's state and writes only its own positions, tokens
+ * and slots, so the kernel runs one thread per row and the host a loop.
  */
 #pragma once
 #include "advance.h"
@@ -28,10 +28,9 @@ RAD_ADV_FN bool adv_is_eog(const AdvanceArgs& a, int32_t t) {
     return lo < a.n_eog && a.eog[lo] == t;
 }
 
-/* Every group's slots for the row's `n` positions, read from the positions just written, and its
- * length from `base`. A position its block table does not reach gets slot -1, which the kernels
- * read as "no slot" -- the builder sized the tables for the furthest position a pass can reach,
- * so it only happens to a row that is being computed for nothing. */
+/* Every group's slots for the row's `n` positions (from the positions just written) and its
+ * length from `base`. A position past the block table gets slot -1 ("no slot"); the builder sizes
+ * tables for the furthest reachable position, so only a row whose output is unused hits this. */
 RAD_ADV_FN void adv_groups(const AdvanceArgs& a, int i, int32_t k, int32_t base, int32_t n) {
     const AdvGroup* G = reinterpret_cast(a.slab + a.grp_off);
     const int32_t* pos = adv_i32(a, a.pos_off);
@@ -51,8 +50,8 @@ RAD_ADV_FN void adv_groups(const AdvanceArgs& a, int i, int32_t k, int32_t base,
     }
 }
 
-/* A row's position, written, with its rotary components moved by the same amount -- only when it
- * moved, so a row the host placed exactly keeps whatever components the host gave it. */
+/* Writes a row's position and moves its rotary components by the same amount. A row whose
+ * position does not change keeps the host's components. */
 RAD_ADV_FN void adv_pos(const AdvanceArgs& a, int32_t* pos, int32_t row, int32_t p) {
     const int32_t was = pos[row];
     pos[row] = p;
@@ -83,9 +82,9 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
 
     switch (a.mode) {
     case ADV_ACCEPT: {
-        /* THE RULE accept_greedy states, and then the end-of-generation cut collect_step applies:
-         * a draft is accepted while it equals the target's own pick at its position, and the run
-         * stops AT an end-of-generation token rather than after it. */
+        /* accept_greedy's rule, then collect_step's end-of-generation cut: a draft is accepted
+         * while it equals the target's pick at its position, and the run stops at an
+         * end-of-generation token, not after it. */
         const int32_t* y = a.src + rout;
         const int32_t* d = tok + rtok + 1;
         int32_t acc = 0;
@@ -110,13 +109,12 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
     }
     case ADV_HIST: {
         if (a.shared_kv) {
-            /* A HEAD THAT READS THE TRUNK'S CACHE AND KEEPS NONE (rad_drafter_shared_kv). There is
-             * no history to fill, so the pass is round 1 alone and its one row is the last one of
-             * the run below: the committed position, the trunk's row there, the token the trunk
-             * chose after it. Its context is the committed positions and NOT the verify step's
-             * whole run -- the cache past the committed position holds the K and V of the drafts
-             * this verify rejected. The host staged the run's first trunk row; the card adds the
-             * drafts it accepted. */
+            /* A head that reads the trunk's cache and keeps none (rad_drafter_shared_kv). With no
+             * history to fill, the pass is round 1 alone: one row at the committed position, with
+             * the trunk's row there and the token chosen after it. Its context ends at the
+             * committed position, not the verify step's whole run, because the cache past it
+             * holds K/V of rejected drafts. The host staged the run's first trunk row; the card
+             * adds the accepted drafts. */
             int32_t* out = adv_i32(a, a.out_off);
             tok[k] = a.src[rout + S.acc];
             adv_pos(a, pos, k, S.head + a.rot_shift);
@@ -125,14 +123,12 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
             adv_groups(a, i, k, S.head, 1);
             return;
         }
-        /* `aux` positions the host already knew the tokens of, then the verify step's own
-         * positions up to the last one it committed, each with the token committed after it --
-         * the sampler's pick there, since the drafts before it agreed with it. The pass has a
-         * row for every position the step COULD have committed, and the ones past the last
-         * committed repeat it: a position past it would take a rejected draft's hidden state
-         * into the head's cache. The repeat is also what makes the run's LAST row draft round
-         * 1's -- the committed position, its hidden state and the token after it -- whatever
-         * the acceptance was (RadBatch::draft_out_ids). */
+        /* `aux` host-known positions, then the verify step's positions up to the last committed
+         * one, each with the token committed after it (the sampler's pick there). The pass has a
+         * row for every position the step could have committed; rows past the last committed
+         * repeat it, so no rejected draft's hidden state enters the head's cache. The repeat also
+         * makes the run's last row draft round 1's input whatever the acceptance was
+         * (RadBatch::draft_out_ids). */
         const int32_t base = S.head - S.acc - aux;
         const int32_t last = aux + S.acc;
         int32_t* out = adv_i32(a, a.out_off);
@@ -148,10 +144,9 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
         return;
     }
     case ADV_ROUND: {
-        /* Round 2 onward: round 1 is the history pass's last row (ADV_HIST above), so every
-         * round embeds the proposal of the round before it. A head with no cache of its own does
-         * not step forward: it stays at the committed position over the committed context, and
-         * what it proposed reaches the next round through its own hidden state. */
+        /* Round 2 onward (round 1 is the history pass's last row); each round embeds the previous
+         * round's proposal. A head with no cache of its own stays at the committed position over
+         * the committed context; its proposal reaches the next round through its hidden state. */
         const int32_t base = a.shared_kv ? S.head : S.head + a.round - 1;
         const int32_t t = a.src[(int64_t)i * a.src_pitch];
         S.tok[a.round - 1] = t;
diff --git a/core/sched/batch.cpp b/core/sched/batch.cpp
index 3fcb64b2..3140c197 100644
--- a/core/sched/batch.cpp
+++ b/core/sched/batch.cpp
@@ -1,4 +1,4 @@
-/* batch.cpp -- building the step batch once. See batch.h for why.
+/* batch.cpp -- builds the step batch once per step. See batch.h.
  */
 #include "batch.h"
 #include "mm/processor.h"
@@ -11,35 +11,27 @@
 
 namespace rad {
 
-/* Staging arrays are carved out of one slab per set rather than allocated one by one: the copies
- * are still per array (each carries only the prefix this step used, and those lengths differ by an
- * order of magnitude between a decode step and a prefill chunk), but the allocator is called twice
- * at init instead of two dozen times and every array in a set shares one mapping. */
+/* 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;
 
-/* The longest range a build's upload names: one round of the workgroup that copies it, whose loads
- * are all in flight before its first store (rad_memcpy_ranges_async). */
+/* Longest range in a build's upload: one round of the copying workgroup, which issues all its
+ * loads before its first store (rad_memcpy_ranges_async). */
 static const int64_t k_range_max = 16384;
 
-/* A HOST-SIDE BOUND, ROUNDED UP ONTO A COARSE GRID: to a multiple of `min_q`, and above 64 of
- * 1/32 to 1/64 of the value's power of two if that is coarser -- so ~3% over at a long context and
- * at most `min_q` over at a short one.
+/* Rounds a host-side bound up to a multiple of `min_q`, or above 64 to 1/32..1/64 of the value's
+ * power of two if that is coarser: ~3% slack at long context, at most `min_q` at short.
  *
- * `max_ctx_len` and the block-table pitch are ceilings -- a kernel reads each row's own length off
- * the card -- and they are the only arguments of a decode pass that move while a request runs:
- * attention and the QSA indexer size their grids by them. Exact, they change the pass's arguments
- * every step or two; rounded, a pass is the same dispatches with the same arguments for many steps
- * at a time, which is what lets a recorded pass be played instead of issued (see Ctx::run_step).
- * The price is grid slack that exits on its first compare, and at a short context, where the
- * floor is most of the bound, the whole attention term is small. */
-/* THE FLOOR IS 1024 TOKENS. Every crossing re-records each kind of pass a step runs, twice -- the
- * recording and the audit before its first play -- at a few hundred microseconds of a rank thread
- * each, and at a 256-token floor a short-context decode crosses often enough to spend a tenth of
- * its rank threads recording. It is not higher because a block may choose its PATH by this bound
- * and not only its grid: rad_block_attn_gated_fp8.h keeps the cheaper dense attention while the
- * bound says every sequence is inside the indexer's budget, and a floor at that budget takes the
- * dense path away from every short context -- a verify step's attention at eight sequences takes
- * 48 us a layer at 2048 instead of 15. */
+ * `max_ctx_len` and the block-table pitch are ceilings (kernels read each row's length from the
+ * card) and the only decode-pass arguments that move as a request runs. Rounded, a pass keeps the
+ * same arguments for many steps, so a recorded pass can be replayed (Ctx::run_step); the cost is
+ * grid slack that exits on its first compare.
+ *
+ * Floor of 1024 tokens: every crossing re-records each pass kind twice (recording plus audit), a
+ * few hundred microseconds of rank thread each, which a 256 floor makes frequent at short context.
+ * Not higher, because a block may pick its path by this bound: rad_block_attn_gated_fp8.h keeps
+ * dense attention while every sequence is inside the indexer's budget; with a 2048 floor, a
+ * verify step's attention at eight sequences costs 48 us a layer instead of 15. */
 static const int64_t k_bound_tokens = 1024;
 
 static inline int64_t bound_bucket(int64_t v, int64_t min_q) {
@@ -52,8 +44,8 @@ static inline int64_t bound_bucket(int64_t v, int64_t min_q) {
     return (v + q - 1) / q * q;
 }
 
-/* A negative device status inside build() aborts the step; there is nothing to fall back to and a
- * partially staged batch is worse than no batch. */
+/* A negative device status inside build() aborts the step: there is no fallback, and a partially
+ * staged batch is worse than none. */
 #define RAD_TRY_NULL(expr)                                                                     \
     do { int _s = (expr);                                                                      \
          if (_s < 0) { RAD_ERR("step batch: %s -> %s", #expr, rad_strerror(_s));               \
@@ -67,14 +59,11 @@ static T* carve(char* base, int64_t& off, int64_t n) {
     return base ? reinterpret_cast(base + o) : nullptr;
 }
 
-/* The full token sequence of a request is prompt ++ output ++ draft, and n_computed indexes into
- * it. One accessor for all three keeps prefill, decode, recompute-after-preemption and speculative
- * verify on the same path: a preempted request re-prefills its own generated output because that
- * is simply the tail of the same sequence, and a verify reads past the committed end into the
- * drafter's proposal. No special case anywhere. */
+/* Token i of prompt ++ output ++ draft, the sequence n_computed indexes. One accessor keeps
+ * prefill, decode, recompute after preemption and speculative verify on one path. */
 static inline int32_t token_at(const StepEntry& e, int64_t i) {
-    /* A placeholder entry -- a drafter context row whose request has already gone -- has no
-     * tokens, and the pass it belongs to reads none. */
+    /* A placeholder entry (a drafter context row whose request is gone) has no tokens, and its
+     * pass reads none. */
     if (!e.req) return 0;
     const Request& r = *e.req;
     int64_t np = (int64_t)r.prompt.size();
@@ -87,23 +76,19 @@ static inline int32_t token_at(const StepEntry& e, int64_t i) {
 }
 
 /* ------------------------------------------------------------------ set layout */
-/* Walked with null bases to measure and with real ones to assign. Keeping both in one function is
- * what stops them drifting, which is the classic way a hand-carved slab ends up with two arrays
- * sharing bytes. Every array is carved in PAIRS, host and device at the same offset, including the
- * host-only ones: that is what lets one copy of a prefix move a whole build, and it puts the
- * block tables -- the only part whose size moves from build to build -- last. */
+/* Called with null bases to measure and with real ones to assign, so the two cannot drift. Every
+ * array is carved as a host/device pair at the same offset, host-only ones included, so one copy
+ * of a prefix moves a whole build. The block tables, whose size varies per build, go last. */
 void BatchBuilder::carve(Set& s, char* h) {
     char* const d = s.dev.empty() ? nullptr : static_cast(s.dev[0]);
     const int64_t T = max_tok_, S = max_seqs_;
-    /* The most logit rows one step can want: one per sequence, or one per verified draft position
-     * per sequence at a speculative step. It is what bounds Geom::max_logit_rows on the plugin
-     * side, and the two have to agree or the plugin gathers into a buffer smaller than out_ids. */
-    /* ...or one row a TOKEN, which an MTP history pass is: it gathers the trunk`s hidden state
-     * for every position the step just computed, and names those rows through the same array. */
+    /* Most logit rows one step can want: one per verified position per sequence, or one per
+     * token for an MTP history pass. Must agree with Geom::max_logit_rows on the plugin side, or
+     * the plugin gathers into a buffer smaller than out_ids. */
     int64_t O = S * (1 + (cfg_.n_spec > 0 ? (int64_t)cfg_.n_spec : 0));
     if (O < T) O = T;
-    /* ...and in the KL mode a row at every token as well, after the sampled ones
-     * (Request::score). RadBuildCtx::max_out_rows says the same number to the plugin. */
+    /* KL mode adds a row at every token after the sampled ones (Request::score); keep in sync
+     * with RadBuildCtx::max_out_rows. */
     if (cfg_.kld()) O = T + S;
 
     int64_t oh = 0, od = 0;
@@ -111,7 +96,7 @@ 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 prompt that follows
+    /* 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);
     pair(&s.h_pos,    &s.d_pos,    T);
@@ -135,14 +120,12 @@ void BatchBuilder::carve(Set& s, char* h) {
         pair(&g.h_used, &g.d_used, S);
         pair(&g.h_sidx, &g.d_sidx, S * g.sidx_pitch);
     }
-    /* THE ROTARY PLANES AND THE ENCODER-ROW TARGETS, only for a program with an encoder: nothing
-     * else can move a rotary position off the token index, and a text-only deployment should not
-     * upload twelve bytes a token of copies of `positions` every step. */
+    /* Rotary planes and encoder-row targets, only for a program with an encoder; nothing else
+     * moves a rotary position off the token index. */
     pair(&s.h_rope,  &s.d_rope,  mm_on_ ? 3 * T : 0);
     pair(&s.h_mmrow, &s.d_mmrow, mm_on_ ? T : 0);
-    /* Host-only: derived metadata is copied into the arena the buffer plan already placed. Carved
-     * in the pair anyway, so the device offsets stay the host's -- a few kilobytes of slab nobody
-     * reads. */
+    /* Host-only (derived metadata is copied into the planned arena), but carved on both sides to
+     * keep device offsets equal to host offsets. */
     {
         int32_t* unused = nullptr;
         char* hd = ::rad::carve(h, oh, derived_bytes_);
@@ -150,18 +133,14 @@ void BatchBuilder::carve(Set& s, char* h) {
         s.h_derived = hd;
         pair(&s.h_convslot, &unused, S * (int64_t)kvgeom_.g.size());
     }
-    /* ---- the block tables, LAST ------------------------------------------------------------
+    /* ---- the block tables, last ------------------------------------------------------------
      *
-     * A group's table is carved for the worst step -- max_seqs rows of max_ctx/block_size entries
-     * -- because the slab has to hold one. At a long context and a small block that is over a
-     * megabyte per paged group, and a model may declare several: the tables are nearly the whole
-     * slab. A build fills n_seq rows of `pitch`, THIS step's longest table, and the device reads
-     * them at that pitch (block_table_pitch below).
-     *
-     * ON THE CARD each group's rows have a FIXED place in this region, so the rows a build leaves
-     * alone are still there for the next one (BtMirror). IN THE HOST SPAN the region is the
-     * build's payload and range list instead, sized by what changed: the carve's host half only
-     * says where the payload starts. */
+     * Each group's table is carved for the worst step (max_seqs rows of max_ctx/block_size
+     * entries), nearly the whole slab at long context. A build fills n_seq rows at `pitch`, this
+     * step's longest table, and the device reads them at that pitch (block_table_pitch below).
+     * On the card each group's rows have a fixed place, so rows a build leaves alone persist
+     * (BtMirror). In the host span this region holds the payload and range list, sized by what
+     * changed; the host half of the carve only marks where the payload starts. */
     {
         int64_t bt_n = 0;
         s.bt_base = od;
@@ -185,9 +164,8 @@ void BatchBuilder::size_set(Set& s, const std::vector& groups) {
         s.groups[gi].block_size = e.block_size;
         int64_t mb = 1;
         if (e.paged) {
-            /* A WINDOW row holds the window behind the step's first query AND the step's own
-             * tokens (KVManager::ensure keeps both), so it is sized for a whole chunk past the
-             * window -- plus the speculative lookahead, which a verify row carries on top. */
+            /* A window row holds the window behind the step's first query plus the step's own
+             * tokens (KVManager::ensure keeps both), plus a verify row's speculative lookahead. */
             const int64_t wspan = e.window + max_tok_ + 2 * ((int64_t)std::max(cfg_.n_spec, 0) + 1);
             int64_t span = (e.kind == RAD_KV_WINDOW && e.window > 0 && wspan < max_ctx_)
                          ? wspan : max_ctx_;
@@ -202,8 +180,7 @@ void BatchBuilder::size_set(Set& s, const std::vector& groups) {
 int BatchBuilder::alloc_set(Set& s, const std::vector& groups) {
     size_set(s, groups);
 
-    /* ONE SLAB PER RANK, on that rank's card. rad_dev_alloc has no device argument and uses the
-     * current one, so the bind is part of the allocation. */
+    /* One slab per rank, on its card. rad_dev_alloc uses the current device, hence the bind. */
     s.dev.assign(ranks_.size(), nullptr);
     for (size_t r = 0; r < ranks_.size(); ++r) {
         RAD_TRY(rad_dev_set(ranks_[r].device));
@@ -216,9 +193,8 @@ int BatchBuilder::alloc_set(Set& s, const std::vector& groups) {
     }
     RAD_TRY(rad_dev_set(ranks_[0].device));
 
-    /* THE RING HOLDS THREE WORST-CASE BUILDS, which is the most a host running ahead of the card
-     * can have in flight before a long-context prefill has to wait for its own upload two builds
-     * back; a decode build's span is its fixed prefix and a few rows of tables, so hundreds fit. */
+    /* The ring holds three worst-case builds before a long-context prefill waits on an upload two
+     * builds back. A decode build's span is far smaller, so hundreds fit. */
     int64_t worst_pay = 0;
     for (const Group& g : s.groups) worst_pay += max_seqs_ * g.max_blocks * (int64_t)sizeof(int32_t);
     const int64_t worst_ranges = worst_pay / k_range_max + max_seqs_ * (int64_t)s.groups.size() + 1;
@@ -234,8 +210,7 @@ int BatchBuilder::alloc_set(Set& s, const std::vector& groups) {
     ring_.first = 0;
     ring_.live = 0;
 
-    /* Local: the host waits on these only to know an upload has READ its span, which a card-wide
-     * release says as well as a system-wide one. */
+    /* Local events suffice: the host waits on them only to know an upload has read its span. */
     ev_.assign(kFlights, std::vector(ranks_.size(), nullptr));
     ev_free_.clear();
     ev_free_.reserve(kFlights);
@@ -291,10 +266,9 @@ void BatchBuilder::free_set(Set& s) {
     for (Out& o : out_) { o.kv.clear(); o.batch.clear(); }
 }
 
-/* A SPAN OF THE RING, contiguous, of `need` bytes. A span that would run past the end starts over
- * at zero. Every flight overlapping the span is retired first -- its uploads have run, on every
- * rank -- oldest first, which is the order they were issued in and so the order the card
- * finishes them. */
+/* A contiguous span of `need` bytes, wrapping to zero if it would run past the end. Every flight
+ * overlapping it is retired first (its uploads have run on every rank), oldest first, which is
+ * issue order and so completion order. */
 int BatchBuilder::reserve(int64_t need, int64_t* off) {
     if (need > ring_.bytes) {
         RAD_ERR("step batch staging: a build of %s does not fit the %s ring",
@@ -320,15 +294,14 @@ int BatchBuilder::reserve(int64_t need, int64_t* off) {
         if (!clash) break;
         RAD_TRY(retire_oldest());
     }
-    /* And a flight needs an event row: out of rows is out of flights. */
+    /* A flight also needs a free event row. */
     while (ev_free_.empty() || ring_.live == kFlights) RAD_TRY(retire_oldest());
     *off = at;
     return RAD_OK;
 }
 
-/* THE SAME ARRAY ON ANOTHER RANK'S SLAB. Every slab is carved by the same walk() from the same
- * sizes, so an array's offset is rank-independent: the byte offset off rank 0's base, re-applied
- * to rank r's. */
+/* The same array on another rank's slab. Every slab has the same carve, so the byte offset from
+ * rank 0's base applies to rank r's. */
 template 
 static inline T* on_rank(void* base_r, void* base_0, T* p0) {
     return p0 ? (T*)((char*)base_r + ((char*)p0 - (char*)base_0)) : nullptr;
@@ -343,8 +316,8 @@ int BatchBuilder::init(Program& prog, const Config& cfg, const ChunkGeometry& ge
     kvgeom_ = kvg;
     ranks_ = ranks;
     if (ranks_.empty()) return RAD_E_INVAL;
-    /* A null stream is the default stream and is legal; a null Program is not -- a derived
-     * buffer would have no arena to land in. */
+    /* A null stream (the default stream) is legal; a null Program is not, since derived buffers
+     * need its arena. */
     for (const RankIO& r : ranks_)
         if (!r.prog) return RAD_E_INVAL;
     RAD_TRY(layout(prog, cfg));
@@ -353,25 +326,20 @@ int BatchBuilder::init(Program& prog, const Config& cfg, const ChunkGeometry& ge
     out_last_ = -1;
     if (mm_on_) RAD_TRY(alloc_media());
 
-    /* THE RESERVATION AND WHAT ACTUALLY CROSSES ARE DIFFERENT NUMBERS, so the line says both.
-     * Nearly all of the slab is block-table rectangles carved for the worst step, and a step
-     * copies only the rows it filled -- an operator reading the reservation alone would price
-     * the per-step cost far above what it is. */
-    RAD_INFO("step batch: %s pinned staging ring + %s device slab a rank, %d KV group(s), "
-             "%d derived buffer(s); of the slab, %s is block tables carved for the worst step "
-             "and only the filled rows cross",
+    /* Report both the reservation and the block-table share of it: tables are carved for the
+     * worst step, but a step uploads only the rows it filled. */
+    RAD_INFO("step batch: %s pinned staging ring + %s device slab a rank (%s of it block "
+             "tables), %d KV group(s), %d derived buffer(s)",
              humanb(ring_.bytes).c_str(), humanb(set_.dev_bytes).c_str(),
-             (int)prog.kv_groups.size(), (int)derived_.size(),
-             humanb(set_.dev_bytes - set_.bt_base).c_str());
+             humanb(set_.dev_bytes - set_.bt_base).c_str(), (int)prog.kv_groups.size(),
+             (int)derived_.size());
     return RAD_OK;
 }
 
-/* WHAT init() WILL ALLOCATE ON EVERY RANK'S CARD, before any of it exists: the VRAM budget is
- * resolved before the builder is, and a reservation it does not charge comes out of
- * --gpu-headroom-mib -- the room a kernel's first launch allocates from, where running out is a
- * fault inside the HIP runtime rather than an error. The slab's block tables grow with
- * --max-num-seqs and the media staging with --max-num-batched-tokens, so neither is small enough
- * to leave to the headroom. The same layout() and carve walk as init(), so the two cannot drift. */
+/* What init() will allocate on every rank's card, for the VRAM budget, which is resolved before
+ * the builder. An uncharged reservation would eat --gpu-headroom-mib, where running out faults
+ * inside the HIP runtime; the block tables grow with --max-num-seqs and the media staging with
+ * --max-num-batched-tokens. Uses the same layout() and carve as init(). */
 int64_t BatchBuilder::device_bytes(Program& prog, const Config& cfg, const KVGeom& kvg) {
     BatchBuilder b;
     b.prog_ = &prog;
@@ -395,17 +363,14 @@ int BatchBuilder::layout(Program& prog, const Config& cfg) {
     }
     if (kvgeom_.g.size() != prog.kv_groups.size()) return RAD_E_INVAL;
 
-    /* The block-table staging rectangle. A sequence never holds more blocks than its context (or
-     * its window, which is the whole point of declaring one: a 4K-window layer in a 128K context
-     * needs a row 32x shorter). The +1 is because a window's blocks are not aligned to the
-     * window's start, so it can straddle one extra block. */
+    /* Block-table rows are sized by context, or by window for a window group (size_set). The +1
+     * block there is because a window is not block-aligned and can straddle one extra block. */
     max_ctx_ = cfg.max_ctx > 0 ? cfg.max_ctx : prog.meta.n_ctx_train;
     if (max_ctx_ <= 0) max_ctx_ = cfg.max_tok;
 
-    /* The conv rolling window: width-1 entries of history plus room for the whole speculative
-     * window, and a rejection then reads back at the slot the last accepted token left (spec §10).
-     * The state tensor's own extent (conv_window_entries), so the cursor derived from it stays
-     * inside the slot the kernels index. */
+    /* Conv rolling window: width-1 entries of history plus the whole speculative window, so a
+     * rejection reads back at the slot the last accepted token left (spec §10). Taken from the
+     * state tensor's extent (conv_window_entries) so the derived cursor stays inside the slot. */
     conv_window_.assign(prog.kv_groups.size(), 1);
     conv_group_ = -1;
     n_conv_ = 0;
@@ -458,11 +423,9 @@ int BatchBuilder::layout(Program& prog, const Config& cfg) {
         d.buf = &b;
         d.off = derived_bytes_;
 
-        /* WHICH CONV GROUP THIS ONE IS ABOUT. `conv_state_index` is the derivation that reads a
-         * rolling window, and a model may declare several of different depths -- so the buffer
-         * names its group and 0 means "the only one of its kind". With more than one conv group
-         * and no name the answer is a guess between two windows, and the wrong depth produces a
-         * plausible cursor pointing at history the kernel never wrote. Refused instead. */
+        /* `conv_state_index` reads a rolling window, and conv groups may differ in depth, so the
+         * buffer names its group; 0 means the only conv group. With several conv groups and no
+         * name, refuse: the wrong depth yields a cursor into history never written. */
         if (std::strcmp(d.name, "conv_state_index") == 0) {
             if (b.decl.kv != 0) {
                 if (b.decl.kv >= prog.kv_groups.size() ||
@@ -475,10 +438,9 @@ int BatchBuilder::layout(Program& prog, const Config& cfg) {
             } else if (n_conv_ == 1) {
                 d.conv_grp = conv_group_;
             } else {
-                RAD_ERR("derived buffer '%s' runs 'conv_state_index' and names no KV group, but "
-                        "%d RAD_KV_CONV groups are declared. Set RadBufDecl::kv -- a cursor "
-                        "computed against the wrong window's depth points at history that was "
-                        "never written.", b.name.c_str(), n_conv_);
+                RAD_ERR("derived buffer '%s' runs 'conv_state_index' with %d RAD_KV_CONV "
+                        "groups declared; set RadBufDecl::kv to the one it reads",
+                        b.name.c_str(), n_conv_);
                 return RAD_E_INVAL;
             }
         }
@@ -486,13 +448,10 @@ int BatchBuilder::layout(Program& prog, const Config& cfg) {
         derived_bytes_ = align_up(derived_bytes_ + n * (int64_t)sizeof(int32_t), k_carve_align);
     }
 
-    /* Two layers declaring the same derivation get two BufferInfos and two arena slots -- that is
-     * what the buffer plan produced -- but they share ONE computation: run_derivations computes
-     * each distinct derivation once per step and copies the result to every destination. The cost
-     * §8 is about is the recomputation, not the bytes.
-     *
-     * SORTED BY (derivation, GROUP), because two buffers running one derivation over different
-     * conv groups are different answers and the sharing rule below is "same as the previous". */
+    /* Buffers declaring the same derivation keep separate arena slots but share one computation
+     * per step (run_derivations copies the result; §8). Sorted by (derivation, group), since
+     * run_derivations shares a result only with the previous entry and different conv groups
+     * give different answers. */
     std::sort(derived_.begin(), derived_.end(),
               [](const Derived& a, const Derived& b) {
                   return a.fn_index != b.fn_index ? a.fn_index < b.fn_index
@@ -505,8 +464,7 @@ int BatchBuilder::layout(Program& prog, const Config& cfg) {
 
 /* ------------------------------------------------------------------ media staging */
 BatchBuilder::MediaBytes BatchBuilder::media_bytes() {
-    /* The larger of the two encoders' passes, field by field: they run one at a time. Both write
-     * rows of the model's embedding width. */
+    /* The larger of the two encoders' passes, field by field, since they run one at a time. */
     enc_patches_ = enc_pix_elems_ = enc_segs_ = 0;
     n_embd_ = 0;
     for (const RadEncoderDecl* e : { &prog_->encoder, &prog_->audio_encoder }) {
@@ -514,7 +472,7 @@ BatchBuilder::MediaBytes BatchBuilder::media_bytes() {
         n_embd_ = std::max(n_embd_, e->n_embd);
         enc_patches_ = std::max(enc_patches_, e->max_patches);
         enc_pix_elems_ = std::max(enc_pix_elems_, e->max_patches * e->patch_dim);
-        /* The most segments one pass can hold: a segment is at least one output row. */
+        /* Most segments one pass can hold; a segment is at least one output row. */
         enc_segs_ = std::max(enc_segs_, e->max_patches / (e->merge > 0 ? e->merge : 1) + 1);
     }
     MediaBytes m;
@@ -580,10 +538,9 @@ void BatchBuilder::free_media() {
     mm_ev_live_ = false;
 }
 
-/* THE ENCODER ROWS OF ONE ENTRY. A row reads its embedding at token `ctx_len + j + shift` -- the
- * draft head's history pass shifts its tokens one ahead, and its embeddings with them -- and the
- * rows that land in a media run take that run's encoder row instead. Consecutive tokens of one run
- * are consecutive rows of its item, so a run is one copy. */
+/* Row j reads its embedding at token `ctx_len + j + shift` (the draft head's history pass shifts
+ * by one); rows inside a media run take that run's encoder row instead. Consecutive tokens of a
+ * run are consecutive rows of its item, so each run is one copy. */
 int64_t BatchBuilder::stage_mm_rows(const StepEntry& e, int64_t k, int64_t shift, int64_t n_rows,
                                     int32_t* rows) {
     const mm::PromptMedia& pm = *e.req->media;
@@ -600,7 +557,7 @@ int64_t BatchBuilder::stage_mm_rows(const StepEntry& e, int64_t k, int64_t shift
                     (unsigned long long)e.seq);
             return RAD_E_STATE;
         }
-        /* The rest of this run inside this entry, and inside the prompt. */
+        /* The rest of this run within this entry and the prompt. */
         int64_t take = std::min((int64_t)run->tok + run->n - ti, e.n_tokens - j);
         take = std::min(take, prompt - ti);
         const int64_t row = (int64_t)run->row0 + (ti - run->tok);
@@ -631,20 +588,16 @@ int BatchBuilder::run_derivations(const StepPlan& plan, Set& s) {
     in.n_seq = (int64_t)plan.e.size();
     in.state_chunk = geo_.state_chunk;
 
-    /* derived_ is sorted by derivation, so "the same one as the previous entry" is the whole
-     * sharing rule and it needs no map. IT IS A PAIR NOW: two buffers running the same derivation
-     * over DIFFERENT KV GROUPS are different answers, and sharing them would give one group the
-     * other's cursors. */
+    /* derived_ is sorted by (derivation, group), so an entry matching the previous one on both
+     * reuses its result. Different groups never share. */
     int     last_fn = -1;
     int32_t last_grp = -1;
     const Derived* last = nullptr;
     for (Derived& d : derived_) {
         int32_t* host = (int32_t*)(s.h_derived + d.off);
 
-        /* THE GROUP'S OWN SLOTS AND ITS OWN WINDOW. `conv_state_index` computes a cursor inside a
-         * rolling window, so the depth has to be that group's: one number shared across groups
-         * fits only one of them, and the wrong depth produces a plausible cursor pointing at
-         * history the kernel never wrote. */
+        /* The group's own slots and window depth; `conv_state_index` computes a cursor inside
+         * that group's rolling window. */
         const int32_t grp = d.conv_grp;
         in.conv_slot   = (grp >= 0) ? s.h_convslot + (int64_t)grp * max_seqs_ : nullptr;
         in.conv_window = (grp >= 0 && grp < (int32_t)conv_window_.size()) ? conv_window_[grp] : 1;
@@ -667,9 +620,7 @@ int BatchBuilder::run_derivations(const StepPlan& plan, Set& s) {
             last = &d;
         }
 
-        /* INTO EVERY RANK'S ARENA, on that rank's stream. A derived buffer is an ordinary
-         * transient the core fills, so it lives in the per-rank arena the buffer plan placed --
-         * copying only into rank 0's leaves every other rank reading whatever its arena held. */
+        /* Copy into every rank's arena on that rank's stream; each rank has its own slot. */
         for (const RankIO& io : ranks_) {
             if (d.handle >= io.prog->buffers.size()) return RAD_E_STATE;
             void* dst = io.prog->buffers[d.handle].ptr;
@@ -685,16 +636,15 @@ int BatchBuilder::run_derivations(const StepPlan& plan, Set& s) {
     return RAD_OK;
 }
 
-
 /* ------------------------------------------------------------------ per-group fill */
 int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set& s, Out& o) {
     const int64_t n_seq = (int64_t)plan.e.size();
-    int32_t* const pay = s.bt_h0;   /* the payload: the table entries this build restages */
+    int32_t* const pay = s.bt_h0;   /* payload: the table entries this build restages */
     int64_t np = 0;
     ranges_.clear();
-    /* `n` entries of the payload from word `src` to word `dst` of the card's table region, as
-     * ranges of at most k_range_max bytes. A run that continues the last range extends it, which
-     * is what makes a whole restage of consecutive rows a handful of ranges and not one a row. */
+    /* Stage `n` payload words from word `src` to word `dst` of the card's table region, as ranges
+     * of at most k_range_max bytes. A run continuing the last range extends it, so consecutive
+     * whole rows become a few ranges instead of one per row. */
     auto stage = [&](int64_t dst, int64_t src, int64_t n) {
         int64_t db = s.bt_base + dst * (int64_t)sizeof(int32_t);
         int64_t sb = s.bt_base + src * (int64_t)sizeof(int32_t);
@@ -713,8 +663,8 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
         }
     };
 
-    /* Every group's row, not just the first: a sequence with no state in a group must read -1
-     * there, and a stale slot from the previous step is the worst possible value. */
+    /* Reset every group's row: a sequence with no state in a group must read -1, not a stale slot
+     * from the previous step. */
     for (int64_t gi = 0; gi < (int64_t)kvgeom_.g.size(); ++gi)
         for (int64_t i = 0; i < n_seq; ++i) s.h_convslot[gi * max_seqs_ + i] = -1;
 
@@ -722,9 +672,8 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
         Group& g = s.groups[gi];
         const KVGeom::G& L = kvgeom_.g[gi];
 
-        /* THIS STEP's pitch, which build() measured before it sized the span. RadKVGroupBatch
-         * carries it, so the device reads the rows at the width they were staged. A new pitch
-         * moves every row, so nothing the card holds is where this build reads it. */
+        /* This step's pitch, set by build() before it sized the span and passed in
+         * RadKVGroupBatch. A new pitch moves every row, invalidating the mirror. */
         const int64_t pitch = pitch_[gi];
         BtMirror& m = bt_mirror_[gi];
         if (L.paged && m.pitch != pitch) {
@@ -738,19 +687,17 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
 
             int64_t first = 0;
             if (L.paged) {
-                /* The block table is the MANAGER's, read by sequence id. Request::blocks is not
-                 * the source of truth: two allocators disagreeing about what a sequence owns is
-                 * the bug where a freed sequence's blocks are handed out from under it. */
+                /* The manager's block table, by sequence id; Request::blocks is not the source
+                 * of truth (see IKVManager). */
                 const std::vector& bt = kv.block_table(e.seq, (int32_t)gi);
                 first = kv.first_block_pos(e.seq, (int32_t)gi);
                 for (int32_t j = 0; j < e.n_tokens; ++j)
                     g.h_slot[t + j] = kvgeom_.slot((int)gi, bt, first, (int64_t)e.ctx_len + j);
-                /* THE ROW, FROM WHAT THE CARD ALREADY HOLDS OF IT. The same sequence in the same
-                 * row keeps every entry below the lowest one the manager changed and below the end
-                 * of both the old and the new table; a decode step's row is then nothing, or the
-                 * one block it appended. Anything else -- a new sequence, one that moved rows -- is
-                 * the whole row, and its copies in other rows stop being current, since its marks
-                 * are taken here. The marks are taken for every row either way. */
+                /* Restage relative to what the card holds (BtMirror). The same sequence in the
+                 * same row keeps entries below the first changed one and below the end of both
+                 * old and new tables, so a decode step stages nothing or one appended block. A
+                 * new or moved sequence restages the whole row, and its copies in other rows go
+                 * unknown. Change marks are taken for every row. */
                 const int64_t nb = std::min((int64_t)bt.size(), pitch);
                 const int64_t chg = kv.take_table_changes(e.seq, (int32_t)gi);
                 int64_t lo = 0, hi = pitch;
@@ -764,7 +711,9 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
                 if (lo < hi) {
                     int32_t* w = pay + np;
                     const int64_t nc = nb > lo ? nb - lo : 0;
-                    std::memcpy(w, bt.data() + lo, (size_t)nc * sizeof(int32_t));
+                    /* Guarded: an empty table's data() may be null, and memcpy's source must
+                     * not be, even for zero bytes. */
+                    if (nc > 0) std::memcpy(w, bt.data() + lo, (size_t)nc * sizeof(int32_t));
                     std::fill(w + nc, w + (hi - lo), -1);
                     stage(g.bt_fix + i * pitch + lo, np, hi - lo);
                     np += hi - lo;
@@ -772,43 +721,27 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
                 m.seq[(size_t)i] = e.seq;
                 m.len[(size_t)i] = nb;
             } else {
-                /* A linear or conv group owns one state instance per sequence, so every token of
-                 * the sequence maps to it and the "block table" row is that slot -- a kernel that
-                 * only reads block tables then needs no second path. */
+                /* A linear or conv group has one state slot per sequence; every token maps to it
+                 * and the block-table row is that slot, so table-reading kernels need no second
+                 * path. */
                 int32_t st = kv.state_slot(e.seq, (int32_t)gi);
                 for (int32_t j = 0; j < e.n_tokens; ++j) g.h_slot[t + j] = st;
                 pay[np + i] = st;
-                /* EVERY conv group, at its own row. This array feeds `DeriveInput::conv_slot`
-                 * and NOTHING ELSE -- a conv KERNEL reads its slot from
-                 * RadKVGroupBatch::state_index, which is filled per group a few lines below and
-                 * always has been. See the note at conv_window_ in init(). */
+                /* Every conv group, at its own row. Feeds only DeriveInput::conv_slot; conv
+                 * kernels read RadKVGroupBatch::state_index (see conv_window_ in batch.h). */
                 if (kvgeom_.g[gi].kind == RAD_KV_CONV)
                     s.h_convslot[(int64_t)gi * max_seqs_ + i] = st;
             }
             s.h_first[(int64_t)gi * max_seqs_ + i] = (int32_t)first;
             t += e.n_tokens;
 
-            /* THE TOKENS THIS SEQUENCE ACTUALLY HOLDS, WHICH IS NOT min(length, window).
-             *
-             * `seqused` is a count from index 0 of the BLOCK TABLE, and the table of a windowed
-             * group is REBASED at `first_block_pos` once the window slides -- kvgeom_.slot() above
-             * subtracts exactly that. So the count the kernel needs is the held span, and the held
-             * span is a whole number of BLOCKS: recycling leaves `window_blocks` of them, whose
-             * last one is partially filled by however far past a block boundary the sequence has
-             * got. `min(length, window)` reports the full window every time and therefore claims
-             * up to block_size - 1 positions that were never written this pass -- and they are the
-             * ones at the END of the table, which every attention kernel reads as the NEWEST
-             * context. Their bytes are whatever the recycled block held.
-             *
-             * A NON-CAUSAL windowed group is where this bites: every query row attends to those
-             * stale slots at full weight, and acceptance falls off a cliff at exactly the context
-             * where the window first slides. A causal group hides the same defect, because a stale
-             * slot past the query is masked anyway.
-             *
-             * No clamp to `window` any more: block granularity means the held span can exceed the
-             * window by less than a block, and dropping that from the FRONT of the count would
-             * drop the NEWEST tokens rather than the oldest. Attending to a few extra old
-             * positions is what paging a sliding window costs, and it is what vLLM does too. */
+            /* Tokens the sequence holds in this table, not min(length, window). `seqused` counts
+             * from index 0 of the block table, which a window group rebases at `first_block_pos`
+             * (as slot() does above). min(length, window) would claim up to block_size - 1
+             * unwritten slots at the end of the table, read as the newest context; a non-causal
+             * window group would attend to them. Do not clamp to `window` either: the held span
+             * may exceed it by under a block, and clamping would drop the newest tokens. Attending
+             * a few extra old positions is the cost of paging a window (vLLM does the same). */
             int64_t used = (int64_t)e.ctx_len + e.n_tokens - first;
             if (used < 0) used = 0;
             g.h_used[i] = (int32_t)used;
@@ -819,8 +752,7 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
                                    (int)g.sidx_pitch);
             }
         }
-        /* A state group's rows are one slot a sequence: restaged whole, since they are n_seq
-         * words and one range. */
+        /* A state group's rows are one slot per sequence: n_seq words, restaged whole. */
         if (!L.paged) {
             stage(g.bt_fix, np, n_seq);
             np += n_seq;
@@ -852,8 +784,7 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
             b.block_size = L.block_size;
             b.max_blocks = pitch;
 
-            /* The bytes cross in build()'s one slab copy: a group's arrays are carved out of
-             * the same slab as everything else and there is nothing group-shaped about them. */
+            /* The group's arrays are uploaded with the rest of the slab in build(). */
         }
     }
     pay_words_ = np;
@@ -870,10 +801,9 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
         return nullptr;
     }
     if (plan.spec_is_tree) {
-        /* spec_parent is in the ABI and its pool is allocated, but no drafter in v1 emits a tree,
-         * so the parent chain and the positions a tree implies are not written. Saying so beats
-         * filling the array with the linear-chain answer, which would verify a tree against the
-         * wrong causal mask and produce fluent wrong text. */
+        /* spec_parent is in the ABI and allocated, but no drafter emits a tree, so tree parents
+         * and positions are not written. Filling in the linear-chain answer would verify a tree
+         * against the wrong causal mask. */
         RAD_ERR("tree-layout speculation was requested but is not implemented in this build");
         return nullptr;
     }
@@ -881,7 +811,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
     Set& s = set_;
     const int64_t n_seq = (int64_t)plan.e.size();
 
-    /* THE CONTEXT BOUND, rounded (see bound_bucket), before anything that derives from it. */
+    /* The context bound, rounded (see bound_bucket), before anything that derives from it. */
     int32_t max_ctx = 0, max_q = 0;
     for (const StepEntry& e : plan.e) {
         if (e.ctx_len > max_ctx) max_ctx = e.ctx_len;
@@ -889,20 +819,15 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
     }
     const int64_t ctx_bound = std::min(bound_bucket(max_ctx, k_bound_tokens), max_ctx_);
 
-    /* THE BLOCK-TABLE PITCH OF EVERY GROUP FIRST, because it sizes the build's span of the ring:
-     * the span is the fixed prefix and exactly the rows build_groups will pack. The pitch is a
-     * property of THIS STEP, not of the deployment -- a rectangle wide enough for max_ctx would be
-     * megabytes staged and copied on every decode step to carry a few hundred live entries.
+    /* Every group's block-table pitch comes first because it sizes the ring span. The pitch is
+     * per step, not max_ctx wide, so decode does not stage megabytes of empty rows.
      *
-     * IT IS A FUNCTION OF THE CONTEXT BOUND, so the two move on the same step. Both are in a
-     * recorded pass's key, and rounded separately they cross their buckets on different steps --
-     * every crossing of either is a pass recorded again, so twice the recordings for nothing. A
-     * row holds the sequence's context plus this step's tokens plus the scheduler's draft
-     * lookahead, which is at most two speculative windows, and the pitch is that rounded up to
-     * the bound's own grid. A table longer than that (none is, today) takes its own rounded
-     * length, which is correct and only costs the alignment. */
+     * It derives from the context bound so both cross their buckets on the same step (both key a
+     * recorded pass; separate rounding would double the re-recordings). A row holds context plus
+     * this step's tokens plus at most two speculative windows of draft lookahead, rounded up to
+     * the bound's grid. A longer table takes its own rounded length. */
     const int64_t reach = ctx_bound + max_q + 2 * ((int64_t)std::max(plan.n_spec, 0) + 1);
-    int64_t pay_need = 0;   /* the payload if every row were restaged whole */
+    int64_t pay_need = 0;   /* payload if every row were restaged whole */
     for (size_t gi = 0; gi < s.groups.size(); ++gi) {
         int64_t pitch = 1;
         if (kvgeom_.g[gi].paged) {
@@ -920,9 +845,9 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
         pitch_[gi] = pitch;
         pay_need += n_seq * pitch * (int64_t)sizeof(int32_t);
     }
-    /* THE SPAN: the fixed prefix, the payload, and the range list behind it, each at its bound --
-     * a range a row or state group plus one a k_range_max of payload. What the build turns out to
-     * use is usually far less, and only that is held once it is known. */
+    /* The span: fixed prefix, payload and range list, each at its bound (one range per row or
+     * state group plus one per k_range_max of payload). Only what the build uses is held once
+     * known. */
     const int64_t max_ranges = pay_need / k_range_max + n_seq * (int64_t)s.groups.size() + 1;
     int64_t off = 0;
     const int64_t need = align_up(s.bt_base + align_up(pay_need, 16) +
@@ -935,8 +860,8 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
 
     /* ---------------------------------------------------------- tokens, positions, boundaries */
     int64_t k = 0;
-    /* PER HALF as well as overall: a mixed step`s max_q is its prefill chunk, and a block that
-     * issues the decode rows separately must not select their kernel band with it. */
+    /* Also per half: a mixed step's max_q is its prefill chunk, which must not select the kernel
+     * band for separately issued decode rows. */
     int32_t max_q_dec = 0, max_q_pf = 0;
     int n_ck = 0;
     int64_t n_out = 0, n_dout = 0;
@@ -952,26 +877,24 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
     }
     for (int64_t i = 0; i < n_seq; ++i) {
         const StepEntry& e = plan.e[(size_t)i];
-        /* The advance indexes the card's StepSlots by this, and there are max_seqs of them. */
+        /* The advance indexes the card's max_seqs StepSlots by this. */
         if (e.card < 0 || e.card >= max_seqs_) {
             RAD_ERR("step plan row %lld: sequence %llu has card index %d, outside the %lld step "
                     "slots", (long long)i, (unsigned long long)e.seq, (int)e.card,
                     (long long)max_seqs_);
             return nullptr;
         }
-        /* THE MTP HEAD READS ONE POSITION AHEAD. Its index i pairs the trunk`s hidden state at i
-         * with the EMBEDDING OF THE TOKEN AT i + 1, and predicts i + 2 (rad_block_mtp_fp8.h). The
-         * shift is applied once, here, so that no kernel and no plugin carries it -- and
-         * token_at() reaches the drafter`s own earlier rounds through `draft` exactly as a verify
-         * step reaches its proposal. StepPlan::tok_shift says how far, because it is the HEAD's
-         * indexing and not the draft round's: DFlash2 is a draft pass that shifts by nothing. */
+        /* Token shift (StepPlan::tok_shift): the MTP head pairs hidden state i with the token
+         * at i + 1 and predicts i + 2 (rad_block_mtp_fp8.h). Applied only here, so no kernel or
+         * plugin carries it; token_at() reaches earlier draft rounds through `draft`. DFlash2
+         * passes use 0. */
         const int64_t shift = plan.tok_shift;
         for (int32_t j = 0; j < e.n_tokens; ++j) {
             s.h_tok[k + j] = token_at(e, (int64_t)e.ctx_len + j + shift);
             s.h_pos[k + j] = e.ctx_len + j;
         }
-        /* THE ROTARY POSITION OF EACH ROW, at the row's own position -- the draft head's rows
-         * rotate at the index they write, not at the token they embed. Planes of n_tok. */
+        /* Rotary position of each row at its own position (draft-head rows rotate at the index
+         * they write, not the token they embed). Three planes of n_tok. */
         if (mm_on_) {
             const mm::RopeLayout* rl =
                 (e.req && e.req->media && !e.req->media->rope.empty()) ? &e.req->media->rope : nullptr;
@@ -986,7 +909,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
                 if (v[1] != v[0] || v[2] != v[0]) rope_mixed = 1;
             }
             if (e.req && e.req->media && !e.req->media->items.empty()) {
-                /* The staging is the last upload's until that upload has run. */
+                /* Wait until the last upload from the staging has run. */
                 if (mm_ev_live_) {
                     if (rad_event_sync(mm_ev_) < 0) return nullptr;
                     mm_ev_live_ = false;
@@ -997,23 +920,16 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
             }
         }
         if (e.ckpt_tok >= 0 && e.ckpt_slot >= 0) {
-            /* checkpoint_tok indexes THIS STEP's tokens, so it is the sequence's base plus the
-             * offset the scheduler chose -- which the chunk split guarantees is the last token of
-             * a checkpoint interval (§7.3). */
+            /* checkpoint_tok indexes this step's tokens: the sequence's base plus the offset the
+             * scheduler chose, the last token of a checkpoint interval (§7.3). */
             s.h_cktok[n_ck]  = (int32_t)(k + e.ckpt_tok);
             s.h_ckslot[n_ck] = e.ckpt_slot;
             ++n_ck;
         }
-        /* Which of this step's tokens the sampler wants logits for. `produces_token` is the
-         * scheduler's answer to "is this entry's last token the sequence's last" -- false for the
-         * middle chunk of a long prefill, which therefore contributes no row and does not touch
-         * the lm_head at all. At a speculative verify every drafted position needs a distribution
-         * to accept against, so the entry contributes 1 + n_spec rows and not one. */
-        /* AN MTP PASS NAMES ITS OWN ROWS, and they are rows of the PREVIOUS step: the head
-         * gathers the trunk`s hidden state for the positions it continues from, and which those
-         * are is not a function of this batch at all. One per token of the pass, consecutive from
-         * `hidden_row` -- which is a single row for a draft round and a whole chunk for a history
-         * pass. See StepEntry::hidden_row. */
+        /* Rows the sampler wants logits for. An entry with `hidden_row` names its own rows
+         * (StepEntry::hidden_row), consecutive from it. Otherwise a `produces_token` entry gives
+         * 1 + n_spec rows (every drafted position needs a distribution), and a mid-prefill chunk
+         * gives none. */
         if (e.hidden_row >= 0) {
             const int32_t nr = e.hidden_n > 0 ? e.hidden_n : e.n_tokens;
             for (int32_t j = 0; j < nr; ++j) s.h_out[n_out++] = e.hidden_row + j;
@@ -1022,13 +938,9 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
             for (int32_t j = 0; j <= e.n_spec; ++j) s.h_out[n_out++] = first + j;
         }
         if (e.draft_out) s.h_dout[n_dout++] = (int32_t)(k + e.n_tokens - 1);
-        /* RADIANCE_DFLASH_TRACE prints what a drafter pass actually consumes -- the pass kind, the
-         * absolute positions, and the token ids at them. A block-diffusion drafter reads an ANCHOR
-         * the target has already chosen followed by mask ids, and every way of getting that wrong
-         * (an anchor one token stale, a mask id that is an ordinary token, a position base that
-         * disagrees with the KV the context pass wrote) produces the same symptom from outside:
-         * acceptance near zero and output still exactly correct. So it is printed rather than
-         * reasoned about. */
+        /* RADIANCE_DFLASH_TRACE logs each drafter pass's kind, positions and token ids. A wrong
+         * anchor, mask id or position base shows only as near-zero acceptance with correct
+         * output. */
         static const bool trace = std::getenv("RADIANCE_DFLASH_TRACE") != nullptr;
         if (trace && plan.draft_pass != 0) {
             std::string ln = fmt("df %s seq %d pos %d..%d tok",
@@ -1053,11 +965,9 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
         return nullptr;
     }
 
-    /* THE SCORED ROWS (Request::score), after every row the sampler reads: a row at each token of
-     * a scoring entry's prefill chunk, in entry order, which is the order Engine::score_rows walks
-     * to map them back to a request and a position. They come after so that nothing indexing the
-     * sampled rows -- the sampler, the card's acceptance (dev_out) -- sees them at all. A trunk
-     * pass only: a draft pass's rows are the head's, not the model's. */
+    /* Scored rows (Request::score): one per token of a scoring entry's prefill chunk, in entry
+     * order (the order Engine::score_rows maps back). Appended after the sampled rows so the
+     * sampler and the card's acceptance (dev_out) never see them. Trunk passes only. */
     if (cfg_.kld() && plan.draft_pass == 0 && plan.tok_shift == 0) {
         int64_t at = 0;
         for (int64_t i = 0; i < n_seq; ++i) {
@@ -1073,11 +983,10 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
         }
     }
 
-    /* THE PROMPT THAT FOLLOWS: the last sequence's next tokens, up to a step of them, after this
-     * step's own (RadBatch::n_ahead). Only on a trunk pass whose last entry is a prefill chunk with
-     * more of its sequence still to run -- a draft pass's tokens are shifted and it reads no such
-     * data -- and bounded by the tokens the request has, so a re-prefill after preemption reads
-     * its own output as the prompt's continuation, as token_at does. */
+    /* 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. */
     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)];
@@ -1089,8 +998,8 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
         }
     }
 
-    /* From here the manager's change marks are taken, so a build that stops before its upload
-     * is issued on every rank leaves the card's tables unknown to the next one. */
+    /* build_groups consumes the manager's change marks, so any failure before every rank's
+     * upload is issued must forget_tables(). */
     if (int st = build_groups(plan, kv, s, o); st < 0) {
         forget_tables();
         RAD_ERR("step batch: build_groups -> %s", rad_strerror(st));
@@ -1105,41 +1014,21 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
         return nullptr;
     }
     RadCopyRange* const rng = reinterpret_cast(ring_.host + off + rng_at);
-    std::memcpy(rng, ranges_.data(), (size_t)n_rng * sizeof(RadCopyRange));
+    if (n_rng > 0) std::memcpy(rng, ranges_.data(), (size_t)n_rng * sizeof(RadCopyRange));
     const int64_t used = align_up(rng_at + n_rng * (int64_t)sizeof(RadCopyRange), k_carve_align);
 
-    /* ---------------------------------------------------------- ONE COPY PER RANK
+    /* ---------------------------------------------------------- one copy per rank
      *
-     * carve() lays out the host span and every rank's device slab in the same order, at the same
-     * sizes, aligning the OFFSET and not the pointer. So below bt_base the device slab is a
-     * byte-for-byte mirror of the host span, and a whole step's staging -- the token and position
-     * arrays, the per-sequence arrays, and every KV group's slot map, seqused and state index --
-     * crosses in one transfer, with the block-table entries that changed riding the same dispatch
-     * as ranges.
+     * Below bt_base the device slab mirrors the host span byte for byte (carve() aligns offsets,
+     * not pointers), so a step's whole staging crosses in one transfer, with changed block-table
+     * entries as ranges in the same dispatch. Copying per array would move fewer bytes, but a
+     * decode step has about 2 KB live across dozens of arrays, where per-transfer dispatch cost
+     * dominates; the unused tail costs a few microseconds of DMA. Since everything crosses every
+     * step, `num_accepted` needs no gate.
      *
-     * One copy per ARRAY would carry only the prefix the step used, which is the right trade when
-     * the arrays are full and the wrong one when they are not. A decode step has about two
-     * kilobytes of live staging spread over dozens of arrays -- one per array, per KV group, per
-     * rank -- and at that size the bytes are the smallest part of the cost: each transfer costs a
-     * dispatch plus the dependent gap behind it, which together dominate the DMA.
-     *
-     * The over-copy is the unused tail of the arrays sized by max_num_batched_tokens. At a full
-     * prefill chunk it is nothing at all -- the same bytes cross either way and only the launch
-     * count differs -- and at decode a few microseconds of DMA buys back dozens of dispatches.
-     *
-     * It also removes the need for a gate on `num_accepted`: the kernels read that operand
-     * whenever the DEPLOYMENT speculates, not only when the step drafted, so copying it
-     * conditionally leaves them reading the arena on exactly the step that had something to roll
-     * back. Everything in the slab crosses on every step.
-     *
-     * AND IT STAYS ON THE COMPUTE STREAM, which is not an oversight. Moving it to a third,
-     * staging stream -- so that a producer on the second lane could see its batch without
-     * queueing behind compute -- is substantially SLOWER at every concurrency, byte-identical.
-     * Sharing the queue is load-bearing: the split has to pay for two orderings the queue gives
-     * away, and the one that hurts is the copy waiting on the event that says the step which last
-     * read this slab is done -- it cannot start until the previous step has drained, where riding
-     * the compute stream lets it issue in line. That is three cross-stream round-trips a step a
-     * rank against a prize of a few percent. Do not rebuild the staging stream. */
+     * The copy stays on the compute stream. A separate staging stream is slower at every
+     * concurrency: the copy must wait on an event for the step that last read the slab, adding
+     * cross-stream round-trips, while on the compute stream it issues in line. Do not move it. */
     for (size_t r = 0; r < ranks_.size(); ++r) {
         const int st = rad_memcpy_ranges_async(s.dev[r], ring_.host + off, s.bt_base, rng, n_rng,
                                                ranks_[r].stream);
@@ -1150,13 +1039,12 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
         }
     }
 
-    /* Derived metadata reads the host staging, so it runs after the fills and before the event. */
+    /* Derivations read the host staging: after the fills, before the event. */
     RAD_TRY_NULL(run_derivations(plan, s));
 
     /* ---------------------------------------------------------- encoder rows
-     * Behind the slab on every rank's stream, so the rows are on the card before any kernel of the
-     * pass reads them: rank 0 takes the staged rows, every other rank the zeros that make the
-     * vocabulary reduction count each row once. */
+     * Behind the slab on every rank's stream. Rank 0 gets the staged rows, the others zeros, so the
+     * vocabulary reduction counts each row once. */
     if (n_mm > 0) {
         const int64_t bytes = n_mm * n_embd_ * (int64_t)sizeof(uint16_t);
         for (size_t r = 0; r < ranks_.size(); ++r) {
@@ -1200,11 +1088,9 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
         B.kv = o.kv[r].data();
         B.draft_pass = plan.draft_pass;
         B.n_spec = plan.n_spec;
-        /* PASSED WHENEVER THE DEPLOYMENT SPECULATES, not only on the steps that drafted. A step that
-         * declines to draft still FOLLOWS one that did, and the linear kernels need to know how much
-         * of that step survived before they can start. Gating this on the step's own draft count
-         * makes the kernels fall back to their absent-operand default of 1 on exactly the step that
-         * had something to roll back. */
+        /* Passed whenever the deployment speculates, not only on steps that drafted: a step
+         * without drafts may follow one that had drafts, and the linear kernels need its accepted
+         * count instead of their absent-operand default of 1. */
         B.num_accepted = cfg_.n_spec > 0 ? on_rank(base, b0, s.d_acc) : nullptr;
         B.spec_parent = nullptr;      /* a linear chain; the tree case is refused above */
         B.rope_pos = mm_on_ ? on_rank(base, b0, s.d_rope) : nullptr;
@@ -1224,8 +1110,8 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
         B.checkpoint_slot = n_ck ? on_rank(base, b0, s.d_ckslot) : nullptr;
         B.n_ahead = n_ahead;
     }
-    /* THE FLIGHT, behind everything that reads this span: the upload, and the derivation copies
-     * run_derivations issued above. */
+    /* Record the flight behind everything reading this span: the upload and the derivation
+     * copies. */
     const int ev = ev_free_.back();
     ev_free_.pop_back();
     for (size_t r = 0; r < ranks_.size(); ++r) {
@@ -1245,8 +1131,6 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
     return &o.batch[0];
 }
 
-/* The batch the last build produced for one rank. Same numbers as build()'s return; different
- * device pointers, because each rank reads its own slab. */
 const RadBatch* BatchBuilder::batch_for(int rank) const {
     if (out_last_ < 0) return nullptr;
     const Out& o = out_[out_last_];
@@ -1315,9 +1199,9 @@ const RadBatch* BatchBuilder::build_encoder(const std::vector& part
             if (seg_p > max_seg) max_seg = seg_p;
         }
     }
-    /* Coordinates in planes of n_patch, which is what makes planes 0 and 1 a dense [2, n_patch]. */
+    /* Coordinates in planes of n_patch, so planes 0 and 1 form a dense [2, n_patch]. */
     {
-        std::vector tmp;
+        std::vector& tmp = enc_coord_tmp_;
         int64_t at = 0;
         for (const EncoderPart& p : parts) {
             const mm::Item& it = *p.item;
diff --git a/core/sched/batch.h b/core/sched/batch.h
index 91e66b0e..68d9b060 100644
--- a/core/sched/batch.h
+++ b/core/sched/batch.h
@@ -1,20 +1,11 @@
-/* batch.h -- the step batch, built ONCE PER STEP BY THE CORE and shared by every layer and every
- * KV group (spec §8).
+/* batch.h -- the step batch, built once per step by the core and shared by every layer and every
+ * KV group (spec §8). Unlike vLLM, which rebuilds the metadata per KV-cache group, there is one
+ * build and every consumer reads the same buffers.
  *
- * vLLM builds this per KV-cache group, per layer, in Python, and that shape is what this file
- * exists to avoid: a model whose linear-attention layers fall into several KV-cache groups runs
- * the metadata builder once per group, and every run after the first produces values identical to
- * it -- dozens of tiny dispatches a step for numbers already computed, and host time on the step
- * path is time the GPU spends idle.
- *
- * So: one build, one owner, every consumer reads the same buffers.
- *
- * Everything here comes out of pools sized at max_tok / max_seqs at init. Nothing on this path
- * allocates. Staging is PINNED HOST memory crossing in one async copy a rank, out of a RING so
- * that a build is never written while an earlier build's copy is still reading it -- the cost of
- * getting that wrong is a torn block table, which shows up as a sequence reading another
- * sequence's KV and reads as a model quality problem -- and so that the host can stage several
- * passes ahead of the card without waiting for any of them.
+ * Everything comes from pools sized at max_tok / max_seqs at init; nothing on this path
+ * allocates. Staging is pinned host memory, uploaded in one async copy per rank, carved from a
+ * ring so that a build never overwrites staging an earlier upload is still reading (that would
+ * tear a block table) and the host can stage several passes ahead of the card.
  */
 #pragma once
 #include "advance.h"
@@ -26,63 +17,52 @@
 namespace rad {
 
 /* One sequence's participation in one step. The scheduler fills these; the builder turns them
- * into device arrays and touches nothing else. */
+ * into device arrays. */
 struct StepEntry {
     const Request* req = nullptr;
-    uint64_t seq = 0;             /* the KV manager's key -- the request id */
-    int32_t slot = -1;            /* scheduler slot: where the scheduler keeps the request */
+    uint64_t seq = 0;             /* the KV manager's key (the request id) */
+    int32_t slot = -1;            /* the scheduler's slot for the request */
     int32_t card = -1;            /* the card's StepSlot index, [0, max_seqs): the sequence
                                    * identity in this batch (SchedReq::card) */
     int32_t n_tokens = 0;         /* query length this step */
-    int32_t ctx_len = 0;          /* computed tokens BEFORE this step -- the first token's position */
+    int32_t ctx_len = 0;          /* tokens computed before this step: the first token's position */
     int32_t n_spec = 0;           /* draft tokens included in n_tokens (decode only) */
-    /* HOW MANY TOKENS THE PREVIOUS STEP COMMITTED, and it is ONE-BASED: the token that step was
-     * given plus however many of its drafts survived. Both linear kernels read it that way --
+    /* Tokens the previous step committed, one-based: its input token plus its accepted drafts.
      * gdn_conv_update reads its rolling window at `num_accepted - 1` and gdn_recurrent_update
-     * takes the state the (num_accepted)th token left -- so 1 is the ordinary decode step that
-     * drafted nothing, which is exactly what they assume when the operand is absent. Zero is not
-     * a value either of them can read; the scheduler's own `SchedReq::n_accepted` counts DRAFTS,
-     * which is one less. */
+     * takes the state the (num_accepted)th token left, so 1 is a plain decode step (also their
+     * default when the operand is absent) and 0 is invalid. SchedReq::n_accepted counts drafts
+     * only, one less. */
     int32_t n_accepted = 1;
     int32_t conv_cursor = 0;      /* read offset inside the rolling conv window (§10) */
     int32_t ckpt_tok = -1;        /* token index WITHIN this entry to snapshot at, or -1 */
     int32_t ckpt_slot = -1;
-    /* THE SNAPSHOT THIS ENTRY RESUMES FROM, or -1. Set on the first step after a prefix hit and
-     * never again: the recurrent half of a hit is carried by this and by nothing else, because
-     * the adopted blocks describe the attention layers only. */
+    /* Snapshot this entry resumes from, or -1. Set only on the first step after a prefix hit; the
+     * adopted blocks cover attention only, so this is the sole carrier of the recurrent state. */
     int32_t ckpt_restore = -1;
     const int32_t* draft = nullptr;   /* the drafter's proposal, appended after the committed tail */
     int32_t n_draft = 0;
-    /* WHICH LOGITS ROW OF THE STEP JUST RUN holds the hidden state this entry continues from,
-     * or -1 for the ordinary rule. It exists for the MTP drafter's history pass: the trunk step
-     * produced 1 + n_spec rows for a verifying sequence, and the head gathers the run of them
-     * starting here. Filled into `out_ids`, so the head's gather picks them out of the same
-     * buffer.
-     *
-     * A pass that gathers its OWN output names rows of itself through the same field -- the
-     * DFlash2 query pass does, because the rows it wants logits for are the mask positions of the
-     * block it just ran. Which buffer out_ids indexes is the architecture block's business; this
-     * is only the list. */
+    /* First logits row, written into `out_ids`, that this entry reads, or -1 for the default
+     * rule. The MTP history pass uses it to gather the 1 + n_spec trunk rows of a verifying
+     * sequence; the DFlash2 query pass uses it to name the mask rows of its own block. Which
+     * buffer out_ids indexes is up to the architecture block. */
     int32_t hidden_row = -1;
-    /* HOW MANY ROWS FROM `hidden_row`, or 0 for the rule that predates it: one a token. The MTP
-     * history pass wants exactly its n_tokens and says 0; the DFlash2 query pass runs `block`
-     * tokens and wants the block-1 mask rows, so it says block-1 and starts one row in. */
+    /* Rows from `hidden_row`, or 0 for one per token. The MTP history pass uses 0; the DFlash2
+     * query pass runs `block` tokens and uses block-1, starting one row in. */
     int32_t hidden_n = 0;
-    /* THIS ENTRY'S LAST ROW IS DRAFT ROUND 1 (RadBatch::draft_out_ids): set on a history-pass
-     * entry whose sequence drafts, whose rows end with the position round 1 continues from. */
+    /* This entry's last row is where draft round 1 continues from (RadBatch::draft_out_ids).
+     * Set on a history-pass entry whose sequence drafts. */
     bool    draft_out = false;
     bool    is_prefill = false;
     bool    produces_token = false;   /* this entry's last token is the sequence's last */
-    /* ITS DRAFTS CAME FROM PROMPT LOOKUP, not from the declared drafter. Their outcome is counted
-     * in the reported acceptance like any other, and kept out of the adaptive window's estimate,
-     * which describes the draft head (DraftController, draft.h). */
+    /* The drafts came from prompt lookup, not the declared drafter. They count toward reported
+     * acceptance but not the adaptive window's estimate of the draft head (DraftController,
+     * draft.h). */
     bool    ngram = false;
-    /* A DEVICE ROW: the card fills its tokens, positions, rollback count and slots from the slot's
-     * StepSlot before the pass runs (advance.h), and what the host staged for them is replaced.
-     * `ctx_len` is then an upper bound, which is what the host-side ceilings read. The other three
-     * are advance.h's row descriptor: the verify step's token row of the row's first verified
-     * position, its first sampled row (-1 for none), and the mode's own number. A verify step's
-     * entries always carry them, for its acceptance. */
+    /* Device row: the card overwrites its tokens, positions, rollback count and slots from the
+     * StepSlot before the pass runs (advance.h); `ctx_len` is then only an upper bound for the
+     * host-side ceilings. dev_tok/dev_out/dev_aux are advance.h's row descriptor: the verify
+     * step's token row of the first verified position, the first sampled row (-1 for none), and
+     * the mode's own number. A verify step's entries always carry them. */
     bool    dev = false;
     int32_t dev_tok = 0;
     int32_t dev_out = -1;
@@ -93,20 +73,17 @@ struct StepPlan {
     std::vector e;
     int64_t n_tok = 0;
     int     phase = RAD_PHASE_DECODE;
-    /* THE DRAFT PASS, straight through to RadBatch::draft_pass. 0 is a trunk step; r > 0 runs
-     * only the draft head, r < 0 is a history pass. */
+    /* Passed to RadBatch::draft_pass. 0 is a trunk step, r > 0 runs only the draft head, r < 0
+     * is a history pass. */
     int     draft_pass = 0;
-    /* HOW FAR AHEAD OF ITS POSITION A ROW READS ITS TOKEN. The MTP head pairs the trunk's hidden
-     * state at index i with the embedding of the token at i + 1 (rad_block_mtp_fp8.h), so its
-     * passes say 1 and the shift is applied once, here, rather than in a kernel. It is NOT a
-     * property of "being a draft pass": DFlash2's query block embeds the token at its own
-     * position -- the anchor at the row that holds it and a mask everywhere after -- and says 0.
-     * Deriving it from `draft_pass` instead feeds such a drafter the token one past its anchor. */
+    /* How far past its position a row reads its token. The MTP head pairs hidden state i with
+     * the token at i + 1 (rad_block_mtp_fp8.h), so its passes use 1. Do not derive this from
+     * `draft_pass`: DFlash2's query block embeds the token at its own position and uses 0. */
     int     tok_shift = 0;
     int     n_spec = 0;               /* the batch-wide speculative window */
     bool    spec_is_tree = false;     /* a tree drafter fills spec_parent; a chain leaves it null */
-    /* THE SPLIT, for a block that issues over each half separately. Sorted above, so the decode
-     * rows are sequences [0, n_seq_decode) and the prefill chunks are the rest. */
+    /* Decode/prefill split, for a block that issues each half separately. Entries are sorted so
+     * decode rows are sequences [0, n_seq_decode) and prefill chunks follow. */
     int64_t n_seq_decode = 0;
     int64_t n_tok_decode = 0;
     int32_t max_q_len = 0;
@@ -122,58 +99,52 @@ struct StepPlan {
 /* ------------------------------------------------------------------ the builder */
 class BatchBuilder {
 public:
-    /* `prog` is non-const because derived buffers are written into the arena, and the arena
-     * pointer lands in BufferInfo::ptr after the buffer plan runs. */
-    /* What the builder needs about one rank: which card its slab lives on, which stream its
-     * upload rides, and which Program holds the arena a derived buffer is copied into. */
+    /* One rank: the card its slab lives on, the stream its upload runs on, and the Program whose
+     * arena derived buffers are copied into. */
     struct RankIO {
         int       device = 0;
         RadStream stream = nullptr;
         Program*  prog   = nullptr;
     };
 
+    /* `prog` is non-const because derived buffers are written into its arena, whose pointer lands
+     * in BufferInfo::ptr after the buffer plan runs. */
     int  init(Program& prog, const Config& cfg, const ChunkGeometry& geo,
               const KVGeom& kvg, const std::vector& ranks);
     void fini();
 
-    /* The bytes init() allocates on each rank's card -- the step slab and, with an encoder, the
-     * media staging -- computed without allocating, for the VRAM budget. -1 when the program is
-     * one init() would refuse. */
+    /* Bytes init() allocates on each rank's card (the step slab and, with an encoder, the media
+     * regions), computed without allocating, for the VRAM budget. -1 if init() would refuse. */
     static int64_t device_bytes(Program& prog, const Config& cfg, const KVGeom& kvg);
 
-    /* Build the batch for this step. The returned pointer is stable until the kOut-th next call
-     * and is the pointer the rank threads share -- because the ranks share an address space, the
-     * batch is shared by pointer rather than broadcast (spec §1). Null on a device failure, which
-     * is fatal for the step. */
+    /* Build the batch for this step. The returned pointer stays valid for the next kOut - 1
+     * calls and is shared by pointer across rank threads (spec §1). Null on a device failure,
+     * which is fatal for the step. */
     const RadBatch* build(const StepPlan& plan, const IKVManager& kv, int step);
 
-    /* The batch the LAST build produced for one rank. Same contents as build()'s return
-     * except for the device pointers, which name that rank's staging slab. */
+    /* The last build's batch for one rank: build()'s result with that rank's slab pointers. */
     const RadBatch* batch_for(int rank) const;
 
-    /* THE ADVANCE'S VIEW OF THE LAST BUILD on one rank: the slab and every offset in it. The mode,
-     * the round, the slot state and the inputs are the caller's (advance.h). */
+    /* The last build's slab and offsets on one rank, for the advance. The caller supplies mode,
+     * round, slot state and inputs (advance.h). */
     AdvanceArgs advance_args(int rank) const;
 
-    /* THE LONGEST SEQUENCE A BATCH CAN DESCRIBE, in tokens: what the block-table rows were sized
-     * for at init. A position at or past it has no column to be addressed through. */
+    /* Longest sequence a batch can describe, in tokens, as sized into the block-table rows at
+     * init. A position at or past it cannot be addressed. */
     int64_t max_ctx() const { return max_ctx_; }
 
-    /* AN ENCODER PASS (RadBatch::enc): the patches of whole segments of one or more media items,
-     * staged into every rank's encoder input -- each rank runs the tower on its own card, so none
-     * waits on another's output. Returns rank 0's batch like build(); batch_for() serves the rest.
-     * The caller synchronises every rank's stream before the next encoder build, which it has to
-     * anyway to read the pass's rows back. */
+    /* An encoder pass (RadBatch::enc): patches of whole segments of one or more media items,
+     * staged into every rank's encoder input, since each rank runs the tower itself. Returns rank
+     * 0's batch like build(); batch_for() serves the rest. The caller must synchronise every
+     * rank's stream before the next encoder build. */
     struct EncoderPart {
         const mm::Item* item = nullptr;
         int32_t         seg0 = 0, n_seg = 0;
     };
-    /* `enc` is the encoder the pass runs: its patch width, pass size and merge bound the parts,
-     * and its modalities are RadBatch::enc. */
+    /* `enc` is the encoder the pass runs: its patch width, pass size and merge bound the parts;
+     * its modalities become RadBatch::enc. */
     const RadBatch* build_encoder(const std::vector& parts, int step,
                                   const RadEncoderDecl& enc);
-    bool    has_encoder() const { return mm_on_; }
-
 
 private:
     struct Group {
@@ -181,9 +152,8 @@ private:
         int64_t     block_size = 0;
         int64_t     max_blocks = 0;
         int32_t*    h_slot = nullptr;  int32_t* d_slot = nullptr;
-        /* The group's block tables on the card: a fixed place in the table region, `bt_fix`
-         * int32 past its start, max_seqs rows of this build's pitch. They have no host twin -- a
-         * build stages only what changed. */
+        /* The group's block tables on the card: max_seqs rows of this build's pitch, `bt_fix`
+         * int32 into the table region. No host twin; a build stages only what changed. */
         int64_t     bt_fix = 0;
         int32_t*    d_bt   = nullptr;
         int32_t*    h_used = nullptr;  int32_t* d_used = nullptr;
@@ -191,38 +161,27 @@ private:
         int64_t     sidx_pitch = 1;    /* columns per sequence in h_sidx/d_sidx */
     };
 
-    /* THE LAYOUT OF A BUILD: every array's place on the card and in host staging, at the same
-     * offset in both, so that one copy moves a whole build.
+    /* Layout of a build: every array at the same offset on the card and in host staging, so one
+     * copy moves a whole build.
      *
-     * THE DEVICE SLAB IS ONE PER RANK AND IS NEVER DOUBLE BUFFERED. A build's upload and every
-     * kernel that reads it are on that rank's compute stream, so the next build's upload is
-     * ordered behind the kernels of the last one by the queue itself: nothing on the card can
-     * read a slab another build is writing. What does need more than one copy is the HOST side,
-     * which the upload reads when the stream reaches it and not when it is issued -- and the host
-     * may be several passes ahead of the card. That staging is carved out of a ring (see Ring),
-     * so any number of builds can be in flight and a build only waits when the ring is full.
-     *
-     * `h_*` are re-carved for every build at its place in the ring; `d_*` are rank 0's slab and
-     * never move. */
+     * The device slab is one per rank and never double buffered: uploads and the kernels reading
+     * them share the rank's compute stream, so stream order protects it. The host side is read
+     * when the stream reaches the upload, possibly several passes later, so it comes from a ring
+     * (see Ring). `h_*` are re-carved for every build at its ring position; `d_*` are rank 0's
+     * slab and never move. */
     struct Set {
         int64_t host_bytes = 0, dev_bytes = 0;
-        /* THE BLOCK TABLES ARE NOT PART OF THE FIXED LAYOUT'S COPY. `bt_base` is where they
-         * start, and everything below it crosses whole every build. On the card the region past
-         * it is every group's tables at a fixed place; in the host span it is the build's
-         * PAYLOAD -- the table entries that changed, packed -- followed by the list of ranges
-         * saying where each run of it lands (see BtMirror). `dev_bytes` is the ALLOCATION, which
-         * holds every group's worst table. */
+        /* Everything below `bt_base` is uploaded whole every build. Past it, the card holds every
+         * group's block tables at fixed places, while the host span holds the payload (changed
+         * table entries, packed) followed by the ranges saying where each run lands (see
+         * BtMirror). `dev_bytes` is the allocation, sized for every group's largest table. */
         int32_t* bt_h0 = nullptr;  int32_t* bt_d0 = nullptr;
         int64_t  bt_base = 0;
-        /* ONE DEVICE SLAB PER RANK, and this is not an optimisation.
-         *
-         * The batch is built once and shared BY POINTER (spec §1), which is right for the host
-         * side and wrong for the device side. A single slab on rank 0's card, filled by async
-         * copies on rank 0's stream and read by every rank's kernels off its own stream, has
-         * nothing ordering the other ranks' reads after rank 0's copies. A slab per rank makes
-         * each rank's upload an ordinary same-stream dependency and puts the metadata on the card
-         * that reads it, instead of behind PCIe. The carve is identical on every rank, so d_*
-         * below are rank 0's pointers AND the offset basis for the rest. */
+        /* One device slab per rank, required for correctness: a single slab on rank 0 would leave
+         * other ranks' reads unordered against rank 0's copies. Per rank, each upload is a
+         * same-stream dependency and the metadata sits on the card that reads it. The carve is
+         * identical on every rank, so d_* below are rank 0's pointers and the offset basis for
+         * the rest. */
         std::vector dev;
 
         int32_t *h_tok = nullptr, *h_pos = nullptr, *h_cu = nullptr, *h_sid = nullptr;
@@ -246,18 +205,16 @@ private:
          * mm_rows): carved only when the program declared an encoder, empty otherwise. */
         int32_t   *h_rope = nullptr, *d_rope = nullptr;
         int32_t   *h_mmrow = nullptr, *d_mmrow = nullptr;
-        /* [n_kv_groups][max_seqs]: EVERY conv group's state slot per sequence, not just one, since
-         * a model may have more than one conv group -- see init(). */
+        /* [n_kv_groups][max_seqs]: every conv group's state slot per sequence (see init()). */
         int32_t*   h_convslot = nullptr;
 
         std::vector           groups;
     };
 
-    /* THE HOST STAGING RING. A build takes the bytes it will upload -- the fixed prefix and the
-     * block-table rows it fills -- as one contiguous span, fills it, and records an event per rank
-     * behind the upload. A span is reusable once every rank's upload of it has run, which is what
-     * `reserve` waits for when the ring is full; at steady state it never is, because a decode
-     * build's span is a small fraction of the ring. */
+    /* Host staging ring. A build takes one contiguous span for what it uploads (the fixed prefix
+     * and its block-table payload), fills it, and records an event per rank behind the upload. A
+     * span is reusable once every rank's upload has run; `reserve` waits for that only when the
+     * ring is full. */
     struct Flight {
         int64_t begin = 0, end = 0;
         int     ev = -1;               /* row of ev_ holding one event per rank */
@@ -271,9 +228,9 @@ private:
         int     first = 0, live = 0;
     };
 
-    /* What a build hands the ranks: the ABI views and the batch, ONE PER RANK, since they differ
-     * only in the device pointers. kOut of them so a batch stays valid while later ones are
-     * built: a step's own batch is read after its draft passes and the next step's batch are. */
+    /* A build's ABI views and batch, one per rank (they differ only in device pointers). kOut of
+     * them, because a step's batch is still read after its draft passes and the next step have
+     * been built. */
     static constexpr int kOut = RAD_SCHED_MAX_SPEC + 4;
     struct Out {
         std::vector> kv;
@@ -282,8 +239,8 @@ private:
 
     struct Derived {
         rad_buf     handle = 0;
-        /* WHICH conv group this derivation is about, or -1 for none. From RadBufDecl::kv, or the
-         * only conv group when the plugin left that 0 and there IS only one. */
+        /* Conv group this derivation is about, or -1. From RadBufDecl::kv, or the only conv
+         * group when the plugin left it 0 and there is exactly one. */
         int32_t     conv_grp = -1;
         const char* name = nullptr;
         int         fn_index = -1;
@@ -300,16 +257,12 @@ private:
     std::vector ranks_;
 
     int64_t max_tok_ = 0, max_seqs_ = 0, max_ctx_ = 0;
-    /* Per KV GROUP, indexed by group, and 0 for a group that is not RAD_KV_CONV.
-     *
-     * THIS AND `h_convslot` FEED `DeriveInput` AND NOTHING ELSE. A conv KERNEL reads its slot from
-     * RadKVGroupBatch::state_index, which is per group. What reads these two is the
-     * `conv_state_index` DERIVATION, which no architecture plugin currently calls --
-     * rad_block_gdn_fp8.h takes `cv->state_index` straight off the group batch. Keeping them per
-     * group is what makes the derivation correct, and usable, for a model with a second conv
-     * group. */
+    /* Per KV group, 0 for a non-conv group. This and `h_convslot` only feed DeriveInput for the
+     * `conv_state_index` derivation, which no plugin calls at present; conv kernels read
+     * RadKVGroupBatch::state_index instead. Kept per group so the derivation is correct with more
+     * than one conv group. */
     std::vector conv_window_;
-    int32_t conv_group_ = -1;    /* the ONLY conv group, when there is exactly one; else -1 */
+    int32_t conv_group_ = -1;    /* the conv group when there is exactly one, else -1 */
     int32_t n_conv_ = 0;
 
     Set  set_;
@@ -323,22 +276,17 @@ private:
     /* Per group, this build's block-table pitch: sized before the span is reserved. */
     std::vector pitch_;
 
-    /* WHAT EVERY RANK'S SLAB HOLDS IN ITS BLOCK-TABLE REGION, so a build stages only what changed.
+    /* What every rank's slab holds in its block-table region, so a build stages only what changed.
+     * At long context a table is thousands of entries per group, too many to restage every build.
+     * The slab outlives the build and uploads land in build order, so it holds the last build's
+     * rows. A row still holding the same sequence at the same pitch is restaged from the first
+     * entry the manager changed (take_table_changes) to the end of what it or the card holds; any
+     * other row is restaged whole.
      *
-     * A sequence's table is its whole context in blocks, thousands of entries a group at long
-     * context, and restaging every row whole every build cost the scheduler time in proportion
-     * to context times sequences times the several builds of a speculative step -- and the card
-     * as much in upload. But the slab is one per rank and outlives the build, the uploads reach it
-     * in the order the builds were made, and a group's tables have a fixed place in it, so it
-     * already holds the last build's rows. A row that still holds the same sequence at the same
-     * pitch is restaged from the lowest entry the manager changed (take_table_changes) to the end
-     * of what it or the card holds; any other row is restaged whole.
-     *
-     * `len[i]` is how many entries of row i are the table of `seq[i]`, and the rest of the row is
-     * -1, which is what a whole restage leaves; -1 in `len` is "unknown". A sequence is current in
-     * at most one row: its change marks are consumed where it is written, so a copy of it left
-     * in another row goes unknown. A layout change -- the group's pitch -- and a build that fails
-     * after taking marks make every row unknown. */
+     * `len[i]` is how many entries of row i are the table of `seq[i]`; the rest of the row is -1.
+     * -1 in `len` means unknown. A sequence is current in at most one row, because its change marks
+     * are consumed where it is written; a copy left in another row becomes unknown. A pitch change,
+     * or a build that fails after taking marks, makes every row unknown. */
     struct BtMirror {
         int64_t pitch = -1;
         std::vector seq;
@@ -347,54 +295,53 @@ private:
     std::vector bt_mirror_;
     /* This build's upload ranges, host-side, until build() writes them behind the payload. */
     std::vector ranges_;
-    int64_t pay_words_ = 0;   /* the payload build_groups wrote, in int32 */
+    int64_t pay_words_ = 0;   /* payload build_groups wrote, in int32 words */
     void forget_tables();
     int64_t last_n_seq_ = 0;
 
     int64_t               derived_bytes_ = 0;
     std::vector  derived_;
 
-    /* THE MEDIA STAGING, allocated only when the program declared an encoder (mm_on_).
+    /* Media staging, allocated only when the program declares an encoder (mm_on_).
      *
-     * The encoder rows a pass overwrites its embeddings with are NOT in the slab: the slab's
-     * prefix crosses whole on every build, and max_tok rows of an embedding are megabytes a decode
-     * step would copy for nothing. They have a device region of their own on every rank, filled
-     * only by a build that carries them -- rank 0 from pinned staging, every other rank with zeros
-     * (RadBatch::mm_embd says why). The staging is refilled only once the last upload out of it
-     * has run, which `mm_ev_` records. */
+     * Encoder rows are kept out of the slab, whose prefix is uploaded every build; max_tok
+     * embedding rows would be megabytes per decode step. Each rank has its own device region,
+     * filled only by a build that carries rows: rank 0 from pinned staging, the others with zeros
+     * (see RadBatch::mm_embd). The staging is refilled only after its last upload has run
+     * (`mm_ev_`). */
     bool                   mm_on_ = false;
     int64_t                n_embd_ = 0;
     std::vector     mm_dev_;
     uint16_t*              mm_host_ = nullptr;
     RadEvent               mm_ev_ = nullptr;
     bool                   mm_ev_live_ = false;
-    /* ...and the encoders' inputs: patches, their coordinates and the segment boundaries, sized
-     * for the larger of the passes the plugin declared (a vision tower's and an audio encoder's
-     * run one at a time and share it). One copy a rank, since each runs the tower itself. */
+    /* Encoder inputs: patches, their coordinates and segment boundaries, sized for the largest
+     * declared pass (encoder passes run one at a time and share it). One copy per rank. */
     int64_t                enc_patches_ = 0, enc_pix_elems_ = 0, enc_segs_ = 0;
     std::vector     enc_pix_dev_, enc_coord_dev_, enc_cu_dev_;
     uint16_t*              enc_pix_host_ = nullptr;
     int32_t*               enc_coord_host_ = nullptr;
     int32_t*               enc_cu_host_ = nullptr;
+    std::vector   enc_coord_tmp_;   /* one item's coordinates; kept for its capacity */
     int64_t                last_n_tok_ = 0;
     struct MediaBytes { int64_t mm = 0, pix = 0, crd = 0, cu = 0; };
-    MediaBytes media_bytes();   /* the four device regions alloc_media reserves, per rank */
+    MediaBytes media_bytes();   /* the four per-rank device regions alloc_media reserves */
     int  alloc_media();
     void free_media();
-    /* The encoder rows of one entry: the media tokens among its positions, their rows copied into
-     * the staging from `n_rows` on. Returns how many it added, or negative. */
+    /* Stage the encoder rows of one entry's media tokens, starting at row `n_rows`. Returns how
+     * many it added, or negative on error. */
     int64_t stage_mm_rows(const StepEntry& e, int64_t k, int64_t shift, int64_t n_rows,
                           int32_t* rows);
 
-    /* The members init() derives from the program and the config, allocating nothing. */
+    /* Derive the members init() needs from the program and config, without allocating. */
     int  layout(Program& prog, const Config& cfg);
-    /* The set's groups and its carve with no base: dev_bytes and host_bytes, nothing reserved. */
+    /* Fill the set's groups and sizes (dev_bytes, host_bytes) without reserving anything. */
     void size_set(Set& s, const std::vector& groups);
     int  alloc_set(Set& s, const std::vector& groups);
     void free_set(Set& s);
     /* Point every h_* at host staging based at `base`, and every d_* at rank 0's slab. */
     void carve(Set& s, char* base);
-    /* A span of `need` bytes of the ring, waiting for old uploads when it is full. */
+    /* Reserve `need` bytes of the ring, waiting for old uploads when it is full. */
     int  reserve(int64_t need, int64_t* off);
     int  run_derivations(const StepPlan& plan, Set& s);
     int  build_groups(const StepPlan& plan, const IKVManager& kv, Set& s, Out& o);
diff --git a/core/sched/derive.cpp b/core/sched/derive.cpp
index 1cf0c09d..2b7a6d97 100644
--- a/core/sched/derive.cpp
+++ b/core/sched/derive.cpp
@@ -1,4 +1,4 @@
-/* derive.cpp -- the derivation table. One row per name; adding one is adding a row.
+/* derive.cpp -- the derivation table, one row per name.
  */
 #include "derive.h"
 
@@ -8,9 +8,7 @@ namespace rad {
 
 /* ------------------------------------------------------------------ seq_start_index */
 /* [n_seq+1] -- where each sequence's tokens begin in this step's flat token array, and the total.
- * This is cu_seqlens, exposed as a declared buffer so a plugin can name it as an operand instead
- * of reaching into RadBatch. It costs a copy of n_seq+1 int32 and it means an op's operand list
- * says what it reads. */
+ * A copy of cu_seqlens, so a plugin can name it as an operand instead of reaching into RadBatch. */
 static int d_seq_start_index(const DeriveInput& in, int32_t* out, int64_t cap, int64_t* n_out) {
     int64_t n = in.n_seq + 1;
     if (n > cap) return RAD_E_FULL;
@@ -20,13 +18,12 @@ static int d_seq_start_index(const DeriveInput& in, int32_t* out, int64_t cap, i
 }
 
 /* ------------------------------------------------------------------ conv_state_index */
-/* [n_seq] -- the entry of the conv state cache this sequence's update reads from.
+/* [n_seq] -- the conv state cache entry this sequence's update reads from.
  *
- * libr4d treats the conv state as a rolling window of `width-1 + num_spec` entries and reads at
- * the slot the last accepted token left, so a speculative rejection is a change of READ OFFSET
- * rather than a recompute (spec §10). The window base is the sequence's state slot; the offset is
- * the cursor the scheduler advances by 1 + num_accepted per verify. Both numbers live in the
- * request's bookkeeping, which is why this is a scheduler-side derivation and not a kernel one. */
+ * The conv state is a rolling window of `width-1 + num_spec` entries read at the slot the last
+ * accepted token left, so a speculative rejection moves the read offset instead of recomputing
+ * (spec §10). Base is the sequence's state slot; offset is the cursor the scheduler advances by
+ * 1 + num_accepted per verify. Both live in request bookkeeping, hence a scheduler derivation. */
 static int d_conv_state_index(const DeriveInput& in, int32_t* out, int64_t cap, int64_t* n_out) {
     if (in.n_seq > cap) return RAD_E_FULL;
     if (!in.conv_slot) return RAD_E_STATE;
@@ -41,15 +38,11 @@ static int d_conv_state_index(const DeriveInput& in, int32_t* out, int64_t cap,
 }
 
 /* ------------------------------------------------------- the linear-state chunk walk */
-/* The chunked linear-attention kernels tile a sequence in fixed chunks measured from the
- * sequence's own origin, not from the start of the step's token array. In a varlen batch those two
- * disagree, so the boundaries have to be derived: a chunk may never cross a sequence boundary, and
- * a chunk boundary must land on an absolute multiple of the chunk length or the recurrent state
- * carried into the next chunk is the state of a partial tile.
- *
- * The scheduler already guarantees a prefill chunk ends on a multiple of the quantum (geometry.h),
- * so in a pure prefill step the interior boundaries are exactly the multiples; the walk still runs
- * because a mixed step's decode rows start at arbitrary positions. */
+/* Chunked linear-attention kernels tile each sequence in fixed chunks from the sequence's own
+ * origin, not the step's token array. A chunk never crosses a sequence boundary, and interior
+ * boundaries land on absolute multiples of the chunk length, or the carried recurrent state would
+ * be that of a partial tile. Prefill chunks already end on the quantum (geometry.h); the walk is
+ * still needed because a mixed step's decode rows start at arbitrary positions. */
 template 
 static int chunk_walk(const DeriveInput& in, int32_t* out, int64_t cap, int64_t* n_out) {
     const int64_t C = in.state_chunk > 0 ? in.state_chunk : 1;
@@ -77,14 +70,13 @@ static int chunk_walk(const DeriveInput& in, int32_t* out, int64_t cap, int64_t*
 }
 
 /* [n_chunks+1] token indices: chunk c covers [out[c], out[c+1]). out[0] is 0 and the last entry is
- * n_tok, so the array reads exactly like cu_seqlens does. */
+ * n_tok, like cu_seqlens. */
 static int d_state_chunk_bounds(const DeriveInput& in, int32_t* out, int64_t cap, int64_t* n_out) {
     return chunk_walk(in, out, cap, n_out);
 }
 
-/* [n_chunks] -- which sequence each chunk belongs to. Recoverable from the bounds by a search
- * against cu_seqlens, but the search is per chunk in every layer that wants it, and this is one
- * pass shared by all of them. */
+/* [n_chunks] -- which sequence each chunk belongs to. Derivable from the bounds, but one shared
+ * pass here saves a per-chunk search in every layer. */
 static int d_state_chunk_seq(const DeriveInput& in, int32_t* out, int64_t cap, int64_t* n_out) {
     return chunk_walk(in, out, cap, n_out);
 }
diff --git a/core/sched/derive.h b/core/sched/derive.h
index 50f69655..02f41cd6 100644
--- a/core/sched/derive.h
+++ b/core/sched/derive.h
@@ -1,25 +1,19 @@
-/* derive.h -- per-step metadata the core computes ONCE, by name, into the arena.
+/* derive.h -- per-step metadata the core computes once, by name, into the arena.
  *
- * An architecture plugin that needs linear-state chunk boundaries or conv-state indices declares
- * them at build time as a RAD_BUF_DERIVED buffer and names the derivation. The core computes it
- * once per step; it is NOT recomputed per layer, and layers that share a geometry share the buffer.
+ * A plugin that needs linear-state chunk boundaries or conv-state indices declares a
+ * RAD_BUF_DERIVED buffer naming the derivation. The core fills it once per step, not per layer,
+ * and layers that share a geometry share the buffer. The step batch is the natural owner of
+ * "once per step"; vLLM has no such object and keys it off a module-level counter.
  *
- * Sharing like this is what vLLM has no natural place for: it has to establish "same step" through
- * a module-level counter, because nothing there is an object that belongs to a step, and a marker
- * held per metadata-builder instead removes nothing -- every KV-cache group is still the first one
- * its own builder sees. Here the step batch IS that place.
- *
- * Adding a derivation is a row in the table in derive.cpp. The core is not the thing you edit to
- * add a kernel; it is the thing you edit to add a shape of per-step metadata, and that list is
- * short and shared.
+ * Adding a derivation is a row in the table in derive.cpp.
  */
 #pragma once
 #include "batch.h"
 
 namespace rad {
 
-/* Everything a derivation may read. All host memory, already staged for this step: a derivation
- * that needed a device read would be a synchronisation on the step path. */
+/* Everything a derivation may read. All host memory, already staged for this step, so no
+ * derivation adds a device sync to the step path. */
 struct DeriveInput {
     const StepPlan* plan = nullptr;
     const int32_t*  cu_seqlens = nullptr;   /* [n_seq+1] */
@@ -32,8 +26,7 @@ struct DeriveInput {
 };
 
 /* Writes at most `cap` int32 elements to `out` and reports how many. Returns RAD_OK or negative;
- * negative aborts the step, because a plugin issuing an op against a half-filled derived buffer is
- * the silent-wrong-output failure this engine exists to remove. */
+ * negative aborts the step rather than let an op read a half-filled buffer. */
 typedef int (*DeriveFn)(const DeriveInput& in, int32_t* out, int64_t cap, int64_t* n_out);
 
 struct DeriveRow {
@@ -42,8 +35,8 @@ struct DeriveRow {
     const char* doc;
 };
 
-/* -1 if the name is not a derivation the core knows. Reported at declare, by name, with the known
- * list -- the same treatment a misspelled op gets (spec §2.3). */
+/* -1 for an unknown name. Reported at declare with the known list, like a misspelled op
+ * (spec §2.3). */
 int              derive_index(const char* name);
 const DeriveRow* derive_row(int index);
 int              derive_count();
diff --git a/core/sched/draft.cpp b/core/sched/draft.cpp
index 9b8a146f..f7ce5dee 100644
--- a/core/sched/draft.cpp
+++ b/core/sched/draft.cpp
@@ -1,5 +1,5 @@
-/* draft.cpp -- the static draft-depth policy, and the adaptive one `--draft-window adaptive` turns
- * on. See draft.h for why the first is the default and what the second changes.
+/* draft.cpp -- the static draft-depth policy and the adaptive one (`--draft-window adaptive`).
+ * See draft.h.
  */
 #include "draft.h"
 
@@ -11,33 +11,33 @@ namespace rad {
 
 namespace {
 
-/* THE STEP-COST PRIOR, a shape and not a measurement: every draft adds six percent to a step --
- * one round of a serial head and one more verify row against a weight-bound step. It prices a
- * depth nothing has measured yet, and only its RATIOS are read once anything has been measured:
- * an unmeasured depth is the nearest measured one scaled by prior(d) / prior(d'). */
+/* Step-cost prior, a shape rather than a measurement: each draft adds 6% to a step (one serial
+ * head round plus one verify row on a weight-bound step). Once anything is measured only its
+ * ratios are used: an unmeasured depth is the nearest measured one scaled by prior(d) / prior(d'). */
 constexpr double kCostSlope = 0.06;
 double cost_prior(int d) { return 1.0 + kCostSlope * (double)d; }
 
-/* A STEP TIME'S MEAN IS A RUNNING MEAN FOR ITS FIRST STEPS AND THEN A MOVING AVERAGE WITH A
- * HALF-LIFE OF 32 STEPS. Long enough that the scatter of one step against the next -- a tier
- * copy, a recording, a prefix-cache trim -- averages out; short enough to follow a context that
- * grows by a few thousand tokens over a reply. */
+/* A step-time mean is a running mean for the first steps, then a moving average with a half-life
+ * of 32 steps: long enough to average out one-off costs (a tier copy, a recording, a prefix-cache
+ * trim), short enough to follow a context growing by a few thousand tokens over a reply. */
 constexpr double kCostHalfLife = 32.0;
-/* AND ONE STEP COUNTS FOR AT MOST FOUR TIMES THE KEY'S MEAN, once the mean is over four steps. A
- * step that waited on something other than its own work -- a first recording, an allocation, a
- * host stall -- says nothing about what its depth costs, and one such step would otherwise move a
- * short mean by more than any depth. A mean over fewer steps is not yet a reference to clip
- * against: its first step may itself be the odd one. */
+/* Once a key has 4 samples, one step counts for at most 4x its mean. A step that waited on
+ * something else (a first recording, an allocation, a host stall) says nothing about its depth's
+ * cost. Below 4 samples the mean is not a trustworthy reference to clip against. */
 constexpr double kCostOutlier = 4.0;
 constexpr int64_t kCostClipAfter = 4;
 
-/* THE PRIOR WEIGHS AS MUCH AS THIS MANY VERIFIES. The (n+1)-th real one moves an estimate by
- * 1 / (n + k + 1) -- a running mean over the prior and the evidence -- until that step falls below
- * the half-life's, and from then on it is the moving average it is meant to be. Without it a
- * sequence would spend its first ~16 verifies at whatever window the prior chose, which is most of
- * a short answer. */
+/* The prior weighs as much as this many verifies. The (n+1)-th verify moves an estimate by
+ * 1 / (n + k + 1), a running mean over prior and evidence, until that falls below the half-life's
+ * step and the moving average takes over. Without it a sequence would spend its first ~16
+ * verifies at the prior's window, most of a short answer. */
 constexpr double kPriorWeight = 4.0;
 
+/* The weight of the (n+1)-th sample in an estimate that is a running mean until 1 / (n + 1)
+ * falls below a moving average's step at half-life `h` samples, and that average after. */
+double settle_weight(double h, int64_t n) {
+    return std::fmax(1.0 - std::exp2(-1.0 / h), 1.0 / (double)(n + 1));
+}
 
 }  /* namespace */
 
@@ -64,10 +64,8 @@ int DraftController::configure(const Params& p) {
         for (int c = 0; c < kCostClasses; ++c) { cost_ms_[d][c] = 0.0; cost_n_[d][c] = 0; }
     }
     if (adapt_)
-        RAD_INFO("draft depth: ADAPTIVE (--draft-window adaptive), %d..%d -- the step's head depth "
-                 "maximises the tokens its sequences are expected to emit over the step's measured "
-                 "cost, and a sequence stops at the first draft emitted less than %.0f%% of the "
-                 "time; moves at +%.0f%% and at most every %d steps",
+        RAD_INFO("draft depth: adaptive, %d..%d; a sequence stops at the first draft emitted less "
+                 "than %.0f%% of the time, and the depth moves at +%.0f%% at most every %d steps",
                  kMinDepth, p_.max_depth, 100.0 * kDraftMinChance, 100.0 * kHyst, kHold);
     return RAD_OK;
 }
@@ -80,9 +78,9 @@ void DraftController::observe(int drafted, int accepted) {
     tot_drafted_  += drafted;
     tot_accepted_ += accepted;
 
-    /* Position j was EVALUATED only if every position before it was accepted, so this verify
-     * produces exactly: 0..accepted-1 evaluated and accepted, and -- when the prefix was not the
-     * whole draft -- position `accepted` evaluated and rejected. Nothing past that was reached. */
+    /* Position j is evaluated only if every earlier position was accepted: 0..accepted-1 are
+     * evaluated and accepted, position `accepted` (if drafted) evaluated and rejected, and nothing
+     * past it is reached. */
     const int last = accepted < drafted ? accepted : drafted - 1;
     for (int j = 0; j <= last; ++j) {
         ++reach_[j];
@@ -107,7 +105,7 @@ void DraftController::step_time(int depth, int n_rows, double ms) {
     double&  m = cost_ms_[depth][c];
     int64_t& n = cost_n_[depth][c];
     if (n >= kCostClipAfter && ms > kCostOutlier * m) ms = kCostOutlier * m;
-    const double w = std::fmax(1.0 - std::exp2(-1.0 / kCostHalfLife), 1.0 / (double)(n + 1));
+    const double w = settle_weight(kCostHalfLife, n);
     m = n ? m + w * (ms - m) : ms;
     ++n;
 }
@@ -121,10 +119,9 @@ double DraftController::step_cost(int depth, int n_rows) const {
     if (depth < 1 || depth > RAD_SCHED_MAX_SPEC) return 0.0;
     const int c = n_rows >= 1 ? cost_class(n_rows) : 0;
     if (cost_n_[depth][c] > 0) return cost_ms_[depth][c];
-    /* THE NEAREST MEASURED KEY: in this class first, the nearest depth and the shallower on a
-     * tie; then the nearest class. Only its ratio to the prior is borrowed, so a class whose steps
-     * are twice as dear prices every depth twice as dear, and the comparison D makes -- depths at
-     * ONE class -- reads the prior's shape until its own depths are measured. */
+    /* Nearest measured key: this class first (nearest depth, shallower on a tie), then the
+     * nearest class. Only its ratio to the prior is borrowed, so D's comparison across depths in
+     * one class follows the prior's shape until those depths are measured. */
     for (int dc = 0; dc < kCostClasses; ++dc) {
         for (int sgn = 0; sgn < 2; ++sgn) {
             const int k = sgn ? c + dc : c - dc;
@@ -158,8 +155,7 @@ double DraftController::prior_at(int j) const {
 }
 
 void DraftController::start(DraftAdapt& s) const {
-    /* Each position from the sequences that finished before it once there are enough of them
-     * (adapt_retire); otherwise from the fixed prior, which is optimistic on purpose (kPrior). */
+    /* From finished sequences once there are enough (adapt_retire), else the fixed kPrior. */
     for (int j = 0; j < p_.max_depth; ++j) {
         s.a[j] = (float)prior_at(j);
         s.n[j] = 0;
@@ -170,8 +166,7 @@ void DraftController::start(DraftAdapt& s) const {
 
 void DraftController::adapt_retire(const DraftAdapt& s) {
     if (!adapt_ || s.depth <= 0 || (double)s.n[0] < kHalfLife) return;
-    const double w = std::fmax(1.0 - std::exp2(-1.0 / kPriorHalfLifeSeqs),
-                               1.0 / (double)(prior_n_ + 1));
+    const double w = settle_weight(kPriorHalfLifeSeqs, prior_n_);
     for (int j = 0; j < p_.max_depth; ++j)
         prior_[j] = prior_n_ ? (float)((double)prior_[j] + w * ((double)s.a[j] - (double)prior_[j]))
                              : s.a[j];
@@ -207,9 +202,8 @@ int DraftController::adapt_observe(DraftAdapt& s, int drafted, int accepted) con
     if (accepted < 0) accepted = 0;
     if (accepted > drafted) accepted = drafted;
 
-    /* THE POSITIONS THIS VERIFY EVALUATED, by observe()'s rule: every one before the first
-     * rejection, taken, and the rejected one, refused. A position behind the rejection was drafted
-     * and never looked at, and says nothing either way. */
+    /* The positions this verify evaluated, by observe()'s rule. Positions past the first
+     * rejection were never evaluated and are not updated here. */
     const int last = accepted < drafted ? accepted : drafted - 1;
     for (int j = 0; j <= last; ++j) {
         const double w = std::fmax(alpha_, 1.0 / ((double)s.n[j] + kPriorWeight + 1.0));
@@ -217,17 +211,15 @@ int DraftController::adapt_observe(DraftAdapt& s, int drafted, int accepted) con
         s.a[j] = (float)((double)s.a[j] + w * (x - (double)s.a[j]));
         if (s.n[j] < UINT16_MAX) ++s.n[j];
     }
-    /* AND THE POSITIONS THE WINDOW DID NOT REACH DRIFT TOWARD THE DEEPEST ONE IT DID. Nothing is
-     * learned about them while the window is shorter -- and a sequence held at three by prose that
-     * turns into code would otherwise keep pricing positions four and up at whatever they read
-     * before, and never draft deep enough to find out. The guess is that acceptance decays with
-     * position rather than falling off a cliff, so the window's edge stands in for what lies past
-     * it. Where that is wrong it costs a move out, the verifies that refute it, and a move back. */
+    /* Positions past the window drift toward its deepest one. Otherwise a sequence held shallow
+     * by prose that turns into code would keep its stale deep estimates and never draft deep
+     * enough to update them. Assumes acceptance decays smoothly with position; when wrong it costs
+     * a move out and back. */
     const double edge = (double)s.a[drafted - 1];
     for (int j = drafted; j < D; ++j)
         s.a[j] = (float)((double)s.a[j] + alpha_ * (edge - (double)s.a[j]));
 
-    /* THE STOP MOVES ONLY PAST THE HOLD: it is this sequence's share of the step's shape. */
+    /* The stop moves only past the hold: it is this sequence's share of the step's shape. */
     if (s.held < INT32_MAX) ++s.held;
     if (s.held < kHold) return s.depth;
     const int d = stop_of(s.a);
@@ -244,9 +236,8 @@ int DraftController::plan_step(DraftAdapt* const* seq, int n_seq, int n_rows) {
     if (n_rows < n_seq) n_rows = n_seq;
     const int M = p_.max_depth;
 
-    /* THE STEP'S EXPECTED TOKENS AT EVERY HEAD DEPTH: sum_i E_i(min(D, stop_i)), plus one for
-     * every row that does not draft. A depth past every stop is the deepest stop's step -- no
-     * sequence drafts further and the head runs no further -- so the candidates end there. */
+    /* Expected tokens at each head depth: sum_i E_i(min(D, stop_i)), plus one per non-drafting
+     * row. Candidates end at the deepest stop, since a deeper D changes nothing. */
     double tok[RAD_SCHED_MAX_SPEC + 1] = {};
     int top = kMinDepth;
     for (int i = 0; i < n_seq; ++i) {
@@ -269,8 +260,8 @@ int DraftController::plan_step(DraftAdapt* const* seq, int n_seq, int n_rows) {
         if (g > best_g) { best_g = g; best = d; }
     }
 
-    /* THE MOVE, rate-limited twice: not within kHold steps of the last one, and only for a depth
-     * worth kHyst more than the one in force. The first step that drafts takes the best outright. */
+    /* Move only after kHold steps and only for kHyst more yield than the current depth. The
+     * first drafting step takes the best outright. */
     if (step_d_ <= 0) {
         step_d_ = best;
         step_held_ = 0;
diff --git a/core/sched/draft.h b/core/sched/draft.h
index 182a789e..af26e02c 100644
--- a/core/sched/draft.h
+++ b/core/sched/draft.h
@@ -1,74 +1,52 @@
 /* draft.h -- the speculative draft-depth controller.
  *
- * BY DEFAULT IT IS STATIC. The depth is `--num-speculative-tokens` and nothing moves it.
+ * Static by default: the depth is `--num-speculative-tokens`. A dynamic policy that gates on the
+ * drafter's own top-1 confidences cannot work here, because the scheduler picks the depth before
+ * the drafter runs; measured acceptance arrives a step late and pooled across sequences. With a
+ * draft head whose cost is nearly flat in depth (one extra verify row on a weight-bound step), the
+ * best depth is a property of the model pair and is known up front, so it is a flag. The
+ * controller still keeps acceptance accounting, a reported metric (spec §14).
  *
- * No dynamic policy sits there, and the reason is structural rather than a tuning failure. The
- * dynamic policy this engine is otherwise modelled on -- a confidence-product gate against a
- * decayed per-position acceptance estimate, plus a batch-size ceiling schedule -- gates on the
- * DRAFTER's own top-1 confidences, per slot, on device, after the drafter has run. The scheduler
- * decides the depth BEFORE the drafter runs and cannot see them; the only substitute available
- * here is measured acceptance, which is the right quantity in expectation but arrives one step
- * late and pooled across sequences. Against a draft head whose cost is nearly flat in depth (one
- * extra verify row on a step that is weight-bound, not compute-bound) that estimate has nothing to
- * buy: the best depth is a property of the model pair, it is known before the serve starts, and it
- * is a flag. A controller that can only pick a worse depth than the constant contributes only the
- * risk that it picks one.
+ * `--draft-window adaptive` is for when that premise fails: with streamed weights (a MoE reading
+ * experts per verify row, a serial head running one pass per round) each draft costs a head round
+ * and a verify row, and the best depth depends on the text (deep on code and JSON, shallow on
+ * prose). The adaptive policy has two halves:
  *
- * What survives is the accounting, because the acceptance rate is a reported metric (spec §14)
- * and because a verify that accepts nothing has to be visible.
+ *   Per sequence (DraftAdapt): a smoothed estimate of each draft position's conditional
+ *   acceptance, fed by the verify outcomes, and the sequence's stop -- the deepest draft whose
+ *   chance of being emitted still pays for its verify row (kDraftMinChance).
  *
- * UNDER `--draft-window adaptive` THE PREMISE ABOVE IS WHAT DOES NOT HOLD. On a model whose
- * weights stream -- a MoE that reads experts per verify row, a serial head that runs one pass a
- * round -- a step is NOT flat in depth: each draft is one more round of the head and one more
- * verify row. And the best depth is not a property of the model pair but of the TEXT:
- * per-position acceptance stays high deep into the window on code and JSON and falls off after a
- * position or two on prose and summaries. No constant is right for all of them, and the one that
- * is right for one costs the others either rounds nobody accepts or tokens nobody drafted.
+ *   Per step (plan_step): the head depth D. A serial head runs as many rounds as the deepest
+ *   window in the step, so D maximises sum_i E_i(min(D, stop_i)) / T(D, n), with
+ *   E(d) = 1 + sum_k prod_{j<=k} a_j and T measured online (step_time). Each sequence then
+ *   drafts min(D, stop_i).
  *
- * So the adaptive window is a policy on the host, in two halves:
+ * Both move only past a hold, and D also past a hysteresis, because a new window is a new pass
+ * shape that must be recorded before it plays (runtime/ctx.h). `max_depth` stays the ceiling and
+ * everything is sized for it.
  *
- *   PER SEQUENCE (DraftAdapt): a smoothed estimate of each draft position's conditional
- *   acceptance, fed by the same verify outcomes observe() counts, and the sequence's STOP -- the
- *   deepest draft whose chance of being emitted still pays for the verify row it adds
- *   (kDraftMinChance).
+ * The policy is for serial drafters only (Scheduler::init): a block drafter proposes its block in
+ * one pass and prompt lookup runs none, so neither pays per-round cost.
  *
- *   PER STEP (plan_step): the HEAD DEPTH D. A serial head runs as many rounds as the deepest
- *   window in the step, so depth is a property of the step and not of one sequence: D maximises
- *   the tokens the whole step is expected to emit, sum_i E_i(min(D, stop_i)), over what a step
- *   at that depth and that many sequences costs, T(D, n) -- with E(d) = 1 + sum_k prod_{j<=k} a_j
- *   and T measured online (step_time). Every sequence then drafts min(D, stop_i).
- *
- * Both move only past a hold, and D also past a hysteresis, because a window is a pass shape and
- * a new shape is a new recording before it plays (runtime/ctx.h). `max_depth` stays the ceiling,
- * and everything sized for it stays sized for it.
- *
- * IT IS THE SERIAL DRAFTER'S POLICY. A block drafter proposes its whole block in one pass, and
- * prompt lookup runs no pass at all, so neither pays the rounds the policy prices; the scheduler
- * turns it on only for a serial drafter (Scheduler::init) and says so when it does not.
- *
- * IT CHANGES HOW MANY DRAFTS A STEP VERIFIES AND NOTHING ELSE. Acceptance is the rule in
- * core/sample/accept.h, so what a step emits is the target's own token at every position whatever
- * window it verified. At temperature 0 that is the same text at every window, to exactly the
- * degree a speculative run matches a plain one at all: exact given the same logits, and a verify
- * row's logits are computed at an M that now moves with the window (accept.h says what that does
- * and does not change).
+ * It changes only how many drafts a step verifies. Acceptance follows core/sample/accept.h, so
+ * every emitted token is the target's own; at temperature 0 the text matches a plain run as far
+ * as the logits do, and a verify row's logits are computed at an M that moves with the window
+ * (see accept.h).
  */
 #pragma once
 #include "rad_core.h"
 
 namespace rad {
 
-/* libr4d's decode kernel serves up to 64 query rows precisely because a verify step falls in that
- * band (spec §10), so 64 is the largest window any batch can carry. */
+/* libr4d's decode kernel serves up to 64 query rows, the verify-step band (spec §10), so 64 is
+ * the largest window any batch can carry. */
 enum { RAD_SCHED_MAX_SPEC = 64 };
 
-/* ONE SEQUENCE'S HALF OF THE ADAPTIVE POLICY: what the drafter has done on this sequence's own
- * text, and how deep that makes it worth drafting. It lives in the scheduler's per-request state
- * and the controller does the arithmetic, so neither has to look the other up.
+/* One sequence's half of the adaptive policy: the drafter's record on this sequence's text and the
+ * resulting stop. Stored in the scheduler's per-request state; the controller does the arithmetic.
  *
- * `depth` 0 is "not started": the first ask fills the estimate from the prior and sets the stop.
- * It belongs to the REQUEST, not to the cache it holds -- a preemption keeps it, because the text
- * it describes is still the text the request is writing -- and a recycled slot starts it over. */
+ * `depth` 0 means not started: the first ask fills the estimate from the prior and sets the stop.
+ * It belongs to the request, not its cache: preemption keeps it, a recycled slot resets it. */
 struct DraftAdapt {
     int32_t  depth = 0;                       /* the sequence's stop; 0 = not started */
     int32_t  held  = 0;                       /* verifies since `depth` last moved */
@@ -80,132 +58,112 @@ class DraftController {
 public:
     struct Params {
         int  max_depth = 0;       /* the deployment's window; 0 disables speculation entirely */
-        /* THE ADAPTIVE POLICY (see the top of this file): `--draft-window adaptive` with a serial
-         * drafter, which Scheduler::init decides. Off, the depth is max_depth, as it always was. */
+        /* The adaptive policy: `--draft-window adaptive` with a serial drafter, decided by
+         * Scheduler::init. Off, the depth is max_depth. */
         bool adapt = false;
     };
 
     /* ---------------------------------------------------------- the policy's constants
-     * Named rather than configurable: each is a property of how the policy works, not of a
-     * deployment, and the one property that IS a deployment's -- what a step costs -- is
-     * measured (step_time). */
+     * Not configurable: each is a property of the policy, not of a deployment. The one
+     * deployment property, step cost, is measured (step_time). */
 
-    /* A WINDOW MOVES ONLY FOR TWO PERCENT MORE YIELD. One draft more or less moves E/T by several
-     * percent on any drafter worth speculating with, while a smoothed estimate wobbles by about
-     * a percent verify to verify; below two percent a move would flip D between two near-equal
-     * neighbours and pay a recording each time. */
+    /* A window moves only for 2% more yield. One draft more or less moves E/T by several percent,
+     * while a smoothed estimate wobbles about 1% per verify; a lower threshold would flip D
+     * between near-equal neighbours and pay a recording each time. */
     static constexpr double kHyst = 0.02;
-    /* AND NOT WITHIN EIGHT VERIFIES (steps, for D) OF THE LAST MOVE. A pass shape is recorded the
-     * second time its key is seen and played from the third (runtime/ctx.h), so a shape held for
-     * eight steps plays from the tape for most of them; and eight verifies at the half-life below
-     * move an estimate by about a third of the way to a new rate, which is a trend rather than
-     * one rejection. */
+    /* And not within 8 verifies (steps, for D) of the last move. A pass shape is recorded on its
+     * second sighting and played from the third (runtime/ctx.h), so a shape held 8 steps mostly
+     * plays from the recording; 8 verifies at kHalfLife move an estimate about a third of the way
+     * to a new rate, a trend rather than one rejection. */
     static constexpr int kHold = 8;
-    /* EACH POSITION'S ESTIMATE HAS A HALF-LIFE OF SIXTEEN VERIFIES THAT EVALUATE IT. At a few
-     * tokens a verify that is some fifty tokens of text: short enough to follow a reply from prose
-     * into a code block and back, long enough that a single rejection moves an estimate by four
-     * percent rather than resetting it. */
+    /* Each position's estimate has a half-life of 16 verifies that evaluate it (about 50 tokens of
+     * text): short enough to follow a reply from prose into code and back, long enough that one
+     * rejection moves an estimate by about 4%. */
     static constexpr double kHalfLife = 16.0;
-    /* A POSITION NOTHING HAS MEASURED STARTS AT 0.8, optimistic on purpose: a window that starts
-     * deep evaluates every position and learns all of them, one that starts shallow learns nothing
-     * about the positions it never drafts to. 0.8 sits between what draft heads measure on prose
-     * and on code at the first positions, so a wrong start is corrected within a hold. */
+    /* An unmeasured position starts at 0.8, optimistic on purpose: a window that starts deep
+     * learns every position, one that starts shallow never learns the deep ones. 0.8 lies between
+     * typical first-position acceptance on prose and on code, so a wrong start corrects within a
+     * hold. */
     static constexpr double kPrior = 0.8;
-    /* ONCE FOUR SEQUENCES HAVE FINISHED, A NEW ONE STARTS FROM WHAT THEY ENDED ON (adapt_retire):
-     * the mean of their estimates, a running mean and then a moving average with a half-life of 32
-     * sequences, so a deployment that moves from one kind of traffic to another follows it within
-     * a few dozen requests. Four, because a mean over fewer is one text's. A sequence counts only
-     * once it has had a half-life of verifies: before that its estimate is mostly the prior it
-     * started from, and folding it back would feed the prior to itself. */
+    /* Once 4 sequences have finished, new ones start from the mean of their final estimates
+     * (adapt_retire): a running mean, then a moving average with a half-life of 32 sequences, so
+     * the prior follows a change of traffic within a few dozen requests. A sequence counts only
+     * after kHalfLife verifies; before that its estimate is mostly the prior itself. */
     static constexpr int    kPriorMinSeqs = 4;
     static constexpr double kPriorHalfLifeSeqs = 32.0;
-    /* NEVER FEWER THAN ONE DRAFT. A sequence at zero would evaluate no position, so nothing could
-     * ever move its estimate off zero again. */
+    /* Never fewer than one draft: at zero no position is evaluated, so the estimate could never
+     * recover. */
     static constexpr int kMinDepth = 1;
-    /* A SEQUENCE STOPS AT THE FIRST DRAFT WHOSE CHANCE OF BEING EMITTED -- every draft before it
-     * and itself accepted, prod_{j<=d} a_j -- IS UNDER ONE IN TEN. The draft adds a verify row to
-     * the step whatever D is, and that row is the only cost a sequence adds once the head runs D
-     * rounds for its deepest neighbour. At one sequence the step-cost prior (1 + 0.06 d) already
-     * breaks even near that chance -- one more draft is worth it while p_d / E exceeds the 5-6 %
-     * it adds to the step, with E around two -- and a verify row alone costs less than a round
-     * plus a row, so the threshold is never stricter than D's own trade. A constant rather than a
-     * measurement: a row's share of the step is not separable from the head's rounds in step
-     * times keyed by depth, and the measured T(D, n) already prices the rounds. */
+    /* A sequence stops at the first draft whose chance of being emitted, prod_{j<=d} a_j, is
+     * under 1 in 10. Once the head runs D rounds for the deepest neighbour, a sequence's only
+     * added cost is its verify row. At one sequence the step-cost prior (1 + 0.06 d) breaks even
+     * near this chance (a draft pays while p_d / E exceeds the ~6% it adds, with E around 2), and
+     * a row alone costs less than a round plus a row, so this is never stricter than D's own
+     * trade. A constant because a row's share cannot be separated from the head's rounds in step
+     * times keyed by depth. */
     static constexpr double kDraftMinChance = 0.1;
-    /* STEP TIMES ARE KEPT IN THESE RUNNING-SEQUENCE CLASSES: 1, 2-3, 4-7, 8-15, 16 and up. A
-     * step's cost moves with how many rows share its weight reads, and a class a power of two
-     * wide keeps every key fed often enough to mean something. */
+    /* Step times are kept per running-row class: 1, 2-3, 4-7, 8-15, 16+. Cost moves with how many
+     * rows share the weight reads; power-of-two classes keep every key fed. */
     static constexpr int kCostClasses = 5;
 
     int  configure(const Params& p);
     const Params& params() const { return p_; }
 
-    /* The draft depth for the next step. 0 means "do not speculate". Constant by construction:
-     * under the adaptive policy it is the CEILING, and window_for() is the window. */
+    /* The draft depth for the next step; 0 means do not speculate. Constant: under the adaptive
+     * policy it is the ceiling, and window_for() is the window. */
     int  next_depth() const { return p_.max_depth; }
 
     /* ---------------------------------------------------------- the adaptive policy */
     bool adaptive() const { return adapt_; }
     /* The window this sequence may draft into: min(D, its stop), starting its estimate on the
-     * first ask; max_depth when the policy is off. Before any step has chosen D, D is the
-     * ceiling. */
+     * first ask; max_depth when the policy is off. Before any step chooses D, D is the ceiling. */
     int  window_for(DraftAdapt& s) const;
-    /* The same for a sequence whose estimate has started, without starting one: 0 when it has
-     * not. For reporting. */
+    /* As window_for() but never starts an estimate; 0 if not started. For reporting. */
     int  window_of(const DraftAdapt& s) const;
-    /* One verify of this sequence: `drafted` proposed, a prefix of `accepted` taken. Moves its
-     * estimate, and its stop past the hold. Returns the stop after. */
+    /* One verify of this sequence: `drafted` proposed, a prefix of `accepted` taken. Updates the
+     * estimate, and the stop once past the hold. Returns the stop. */
     int  adapt_observe(DraftAdapt& s, int drafted, int accepted) const;
-    /* A SEQUENCE THAT HAS FINISHED: its estimate joins the prior the next sequences start from.
+    /* A finished sequence: its estimate joins the prior that new sequences start from.
      *
-     * PER SEQUENCE, NOT PER VERIFY. The deployment's own counts -- accepted(j) / reached(j) over
-     * every verify -- are what a fixed window would want, and under this policy they are biased:
-     * only a sequence whose drafts keep being accepted is given a window that reaches the deep
-     * positions, so those positions are measured almost only on the texts that predict well, and
-     * a new sequence would start as if every text did. Each finished sequence counts once here, at
-     * every position, and at a position it never reached its estimate is the extrapolation from
-     * its own window's edge (adapt_observe) -- a shallow text pulls the deep positions down as
-     * much as a deep one holds them up. */
+     * Per sequence, not per verify. Under this policy, pooled accepted(j) / reached(j) is biased:
+     * only well-predicted texts get windows deep enough to measure deep positions. Here each
+     * finished sequence counts once at every position, using its edge extrapolation where it never
+     * reached (adapt_observe), so shallow texts pull deep positions down as much as deep ones hold
+     * them up. */
     void adapt_retire(const DraftAdapt& s);
     /* The prior a sequence starting now is given at position `j`. For tests and logs. */
     double prior_at(int j) const;
 
-    /* D FOR THE STEP THAT IS OPENING. `seq` are the estimates of the `n_seq` sequences that will
-     * draft in it, `n_rows` the decode rows it carries in all (the rest emit one token each and
-     * draft nothing). Started here if they have not been. Moves D past the hold and the
-     * hysteresis; with no sequence to draft, D stays. Returns D. */
+    /* D for the step being opened. `seq` holds the estimates of the `n_seq` drafting sequences
+     * (started here if needed), `n_rows` all decode rows (the rest emit one token and draft
+     * nothing). Moves D past the hold and hysteresis; with nothing to draft, D stays. Returns D. */
     int  plan_step(DraftAdapt* const* seq, int n_seq, int n_rows);
     /* The step depth in force: 0 before the first step chose one. */
     int  step_depth() const { return step_d_; }
-    /* The deepest window a step at that depth carries: D, but no deeper than the deepest stop it
-     * was chosen over, since no head-drafting sequence drafts past its stop; the ceiling before
-     * any step chose one, and with the policy off. What a proposal from outside the head (prompt
-     * lookup) is held to, so it adds no deeper pass shape than the head's own. */
+    /* The deepest window a step at depth D carries: D capped at the deepest stop it was chosen
+     * over; the ceiling before the first choice or with the policy off. Proposals from outside
+     * the head (prompt lookup) are held to it, so they add no deeper pass shape. */
     int  step_window() const { return adapt_ && step_w_ > 0 ? step_w_ : p_.max_depth; }
 
-    /* T(depth, n): a decode step whose deepest window was `depth`, with `n_rows` decode rows,
-     * took `ms` from the end of the step before it. Fed by Scheduler::step_finished; only the
-     * adaptive policy reads it. */
+    /* T(depth, n): a decode step with deepest window `depth` and `n_rows` decode rows took `ms`
+     * since the end of the previous step. Fed by Scheduler::step_finished; adaptive policy only. */
     void step_time(int depth, int n_rows, double ms);
-    /* What a step at `depth` with `n_rows` rows is expected to cost, in ms when anything has
-     * been measured: the key's own mean when it has samples; the nearest measured key scaled by
-     * the prior's ratio (1 + 0.06 d) when it does not; the prior itself when nothing has been
-     * measured. */
+    /* Expected cost of a step at `depth` with `n_rows` rows: the key's mean (ms) if it has
+     * samples; else the nearest measured key scaled by the prior's ratio (1 + 0.06 d); else the
+     * unitless prior itself. */
     double step_cost(int depth, int n_rows) const;
     /* Samples behind a key: for tests and logs. */
     int64_t cost_samples(int depth, int n_rows) const;
 
-    /* E(d) for `s`'s estimate as it stands: the tokens a verify of d drafts is expected to emit,
-     * the verified token included. For tests and logs. */
+    /* E(d) for `s`'s current estimate: expected tokens emitted by a verify of d drafts, the
+     * verified token included. For tests and logs. */
     double yield(const DraftAdapt& s, int d) const;
-    /* Verifies by the window they carried, counted only under the policy: the histogram of the
-     * depths it actually chose, which the mean gauge on its own cannot show. */
+    /* Histogram of verifies by window, counted only under the adaptive policy. */
     int64_t verified_at(int d) const {
         return (d >= 0 && d <= RAD_SCHED_MAX_SPEC) ? by_depth_[d] : 0;
     }
 
-    /* One verify's outcome: `drafted` tokens were proposed and a prefix of `accepted` of them was
-     * taken. Feeds the reported metrics and nothing else. */
+    /* One verify's outcome: `drafted` proposed, a prefix of `accepted` taken. Metrics only. */
     void observe(int drafted, int accepted);
 
     /* Metrics (spec §14). Cumulative and exact. */
@@ -215,25 +173,19 @@ public:
         return tot_drafted_ ? (float)((double)tot_accepted_ / (double)tot_drafted_) : 0.0f;
     }
 
-    /* PER-POSITION ACCEPTANCE, and it is a diagnostic rather than a policy input.
+    /* Per-position acceptance, a diagnostic rather than a policy input. The pooled ratio cannot
+     * tell a drafter that decays gradually from one that fails at a specific position.
      *
-     * The pooled ratio above cannot tell a drafter that decays from one that falls off a cliff,
-     * and the difference is the difference between "this is what the head is worth" and "round
-     * three is broken". A drafter whose accepted-tokens-per-step stops rising past some depth has
-     * a hazard that goes to zero there; pooled over the whole window that reads as a uniformly
-     * mediocre drafter, which is a different diagnosis and a different fix.
-     *
-     * `reached` is "every earlier position was accepted, so this one was evaluated"; `hits` is
-     * "and it was accepted too". Their ratio is the conditional hazard. A position the draft
-     * never reached is charged nothing, which is why a rejection at position 0 does not libel
-     * every position behind it. */
+     * `reached`: every earlier position was accepted, so this one was evaluated. `hits`: and it
+     * was accepted. Their ratio is the conditional acceptance. Unreached positions are not
+     * charged, so a rejection at position 0 does not count against later positions. */
     int64_t reached(int j) const {
         return (j >= 0 && j < RAD_SCHED_MAX_SPEC) ? reach_[j] : 0;
     }
     int64_t hits(int j) const {
         return (j >= 0 && j < RAD_SCHED_MAX_SPEC) ? hit_[j] : 0;
     }
-    /* The deepest position any draft has ever reached; how much of the two arrays is meaningful. */
+    /* The deepest position any draft has reached; bounds the meaningful part of both arrays. */
     int     depth_seen() const { return seen_; }
 
 private:
diff --git a/core/sched/geometry.cpp b/core/sched/geometry.cpp
index a70e1595..e4a4b472 100644
--- a/core/sched/geometry.cpp
+++ b/core/sched/geometry.cpp
@@ -1,29 +1,24 @@
-/* geometry.cpp -- reconciling the linear-state chunk geometry with the attention block size.
- * See geometry.h for why this is computed and not configured.
+/* geometry.cpp -- reconciles the linear-state chunk length with the attention block size.
+ * See geometry.h.
  */
 #include "geometry.h"
 
+#include 
 #include 
+#include 
 
 namespace rad {
 
-static int64_t gcd64(int64_t a, int64_t b) {
-    while (b) { int64_t t = a % b; a = b; b = t; }
-    return a < 0 ? -a : a;
-}
+/* lcm, with a non-positive side meaning "no constraint yet". */
 static int64_t lcm64(int64_t a, int64_t b) {
     if (a <= 0) return b;
     if (b <= 0) return a;
-    return a / gcd64(a, b) * b;
+    return std::lcm(a, b);
 }
 
-/* WHICH PARAMETER OF THIS OP IS ITS SEQUENCE-CHUNK LENGTH, asked of the op's own schema. The
- * scheduler must cut its steps on a multiple of it or a linear-state chunk straddles a sequence
- * boundary, so this is the one parameter the core reads by MEANING rather than carrying opaquely.
- *
- * The schema names it (RAD_PROLE_SEQ_CHUNK), so the core holds no vocabulary of its own. Matching
- * a list of likely parameter spellings here instead would silently miss any op that spells it
- * differently, and a missed contributor is a quantum that does not divide the kernel's tile. */
+/* The op's sequence-chunk parameter, found by role (RAD_PROLE_SEQ_CHUNK) in its schema. Steps
+ * must be cut on a multiple of it or a linear-state chunk straddles a step boundary. Matching
+ * parameter names instead would silently miss an op that spells it differently. */
 static const char* chunk_key_of(const RadOpSchema* s) {
     if (!s) return nullptr;
     for (int i = 0; i < s->n_params; ++i)
@@ -31,22 +26,25 @@ static const char* chunk_key_of(const RadOpSchema* s) {
     return nullptr;
 }
 
-/* One contributor, appended to the explanation. Kept to a line each so the refusal prints as a
- * short list and not a wall. */
+/* Appends one contributor to the explanation. */
 static void note(std::string& why, const char* what, int64_t v, const char* from) {
     if (!why.empty()) why += "; ";
     why += fmt("%s=%lld from %s", what, (long long)v, from);
 }
 
+int64_t prefill_shared_tok(const Config& cfg) {
+    if (cfg.prefill_span <= 1 || cfg.checkpoint_interval <= 0) return cfg.max_tok;
+    const int64_t I = cfg.checkpoint_interval;
+    return std::max(std::min(cfg.max_tok, I), cfg.max_tok - (cfg.prefill_span - 1) * I);
+}
+
 int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry* out) {
     if (!out) return RAD_E_INVAL;
     ChunkGeometry g;
 
     /* ---------------------------------------------------------------- attention block size */
-    /* One lcm across every paged group. In practice every paged group on a given kernel set has
-     * the same block size -- libr4d's is 16 for all of them -- but a hybrid model with a
-     * sliding-window group served by a different kernel is exactly the case §7.2 is written for,
-     * and lcm is the answer that is right for both. */
+    /* lcm across every paged group. libr4d uses 16 for all of them, but a sliding-window group
+     * served by a different kernel may differ (§7.2). */
     bool has_linear = false, has_window = false;
     for (const KVGroupInfo& kg : prog.kv_groups) {
         if (kg.decl.kind == RAD_KV_FULL || kg.decl.kind == RAD_KV_WINDOW) {
@@ -64,9 +62,8 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
     }
 
     /* ---------------------------------------------------------------- linear-state chunk */
-    /* Two sources, both already resolved: what the plugin declared the op with, and what the
-     * kernel that won selection constrains. The first is the model's statement, the second is the
-     * kernel's, and a chunk that is a multiple of both satisfies both. */
+    /* Two sources: the geometry the plugin declared the op with, and the constraints of the
+     * kernel selected for it. The lcm satisfies both. */
     for (const OpInfo& op : prog.ops) {
         const char* ckey = chunk_key_of(op.schema);
         if (!ckey) continue;
@@ -87,9 +84,8 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
                     const RadConstraint& c = ki->constraints[i];
                     if (!c.key || std::strcmp(c.key, ckey) != 0 || c.ival <= 0) continue;
                     switch (c.op) {
-                        /* DIV and EQ are both "a legal chunk is a multiple of this". GE is folded
-                         * in the same way rather than as a separate floor: a multiple of N is
-                         * >= N, so one number carries both facts and the arithmetic stays lcm. */
+                        /* DIV and EQ mean "a legal chunk is a multiple of this". GE folds in the
+                         * same way, since a multiple of N is >= N. */
                         case RAD_C_DIV:
                         case RAD_C_EQ:
                         case RAD_C_GE:
@@ -97,8 +93,7 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
                             note(g.why, c.key, c.ival, ki->name);
                             break;
                         case RAD_C_LE:
-                            g.max_chunk = g.max_chunk ? (g.max_chunk < c.ival ? g.max_chunk
-                                                                              : (int64_t)c.ival)
+                            g.max_chunk = g.max_chunk ? std::min(g.max_chunk, c.ival)
                                                       : (int64_t)c.ival;
                             break;
                         default: break;
@@ -113,8 +108,8 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
     if (g.quantum < 1) g.quantum = 1;
 
     if (g.max_chunk > 0 && g.quantum > g.max_chunk) {
-        /* Two kernels that cannot both be fed. Naming it is the whole value: the alternative is a
-         * chunk that is legal for one of them and silently wrong for the other. */
+        /* No chunk length satisfies both kernels; report it instead of serving a chunk that is
+         * wrong for one of them. */
         out->why = fmt("chunk quantum %lld exceeds the %lld a resolved kernel accepts (%s)",
                        (long long)g.quantum, (long long)g.max_chunk, g.why.c_str());
         out->quantum = g.quantum;
@@ -122,51 +117,74 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
         return RAD_E_SHAPE;
     }
 
-    /* The checkpoint interval is the operator's number rounded up to a legal chunk length, so that
-     * "split at the interval" is always also "split at a quantum". Rounding UP rather than down
-     * because down can reach zero and because a longer interval costs retention, not correctness.
+    /* Round the operator's interval up to a multiple of the quantum, so a split at the interval
+     * is a legal chunk split. Up, not down: down can reach zero, and a longer interval costs only
+     * retention.
      *
-     * No linear state means no checkpoints: the interval is a property of a state kind that this
-     * model does not have, and pretending otherwise would split chunks for nothing. The one
-     * exception is a trunk window under a prefix cache, which snapshots the window behind a
-     * prompt's tail (window_ckpt) and does not split chunks for it. */
+     * Without linear state there are no checkpoints, except for a trunk window under a prefix
+     * cache, which snapshots the window behind a prompt's tail (window_ckpt) without splitting
+     * chunks. */
     if ((has_linear || (has_window && cfg.prefix_cache)) && cfg.checkpoint_interval > 0)
         g.checkpoint_interval = align_up(cfg.checkpoint_interval, g.quantum);
     else
         g.checkpoint_interval = 0;
     g.window_ckpt = !has_linear && g.checkpoint_interval > 0;
+    /* A window snapshot splits no chunk (plan_chunk), so there is no interval grid to span. */
+    g.span = (g.checkpoint_interval > 0 && !g.window_ckpt && cfg.prefill_span > 1)
+           ? cfg.prefill_span : 1;
+    g.shared_tok = prefill_shared_tok(cfg);
 
-    /* One full quantum has to fit in one step. Below that, every chunk is short, no chunk ever
-     * ends on a boundary, and the checkpoint lands wherever the step happened to end -- which is
-     * precisely the vLLM failure §7.3 exists to remove. Refusing is the honest response. */
+    /* One full quantum must fit in one step; otherwise no chunk ends on a boundary and
+     * checkpoints land wherever a step ends (§7.3). */
     g.min_max_tok = g.quantum;
 
     *out = g;
 
     if (cfg.max_tok < g.min_max_tok) {
         RAD_ERR("--max-num-batched-tokens is %lld but this model's chunk geometry needs at least "
-                "%lld: %s", (long long)cfg.max_tok, (long long)g.min_max_tok, g.why.c_str());
-        RAD_ERR("a smaller budget cannot end a chunk on a linear-state boundary, so every "
-                "checkpoint would land in request-unique tokens and the linear prefix hit rate "
-                "would be zero. Refusing rather than serving that.");
+                "%lld, so a chunk can end on a linear-state boundary: %s",
+                (long long)cfg.max_tok, (long long)g.min_max_tok, g.why.c_str());
         return RAD_E_INVAL;
     }
 
-    /* AND THE CHUNK AN OPERATOR ACTUALLY GETS, which is not --max-num-batched-tokens whenever the
-     * checkpoint interval is smaller: `plan_chunk` splits at the interval so a checkpoint is
-     * always written, and that clamp comes FIRST. Printing only the budget would hide it -- every
-     * budget above the interval runs the same chunk length, so a sweep over them reads as
-     * "prefill is flat against the chunk" when nothing about the chunk changed. The clamp itself
-     * is correct; a budget that silently does nothing is what has to be visible. A window
-     * snapshot is taken at the prompt's tail and splits nothing. */
-    const int64_t eff = (g.checkpoint_interval > 0 && !g.window_ckpt &&
-                         g.checkpoint_interval < cfg.max_tok)
-                      ? g.checkpoint_interval : cfg.max_tok;
+    /* Log the effective chunk length. `plan_chunk` splits at the checkpoint interval first, so
+     * when the interval is below --max-num-batched-tokens, raising the budget does not change the
+     * chunk; the log line makes that visible. A window snapshot splits nothing. */
+    const int64_t span_tok = g.checkpoint_interval * g.span;
+    const int64_t eff = (g.checkpoint_interval > 0 && !g.window_ckpt && span_tok < cfg.max_tok)
+                      ? span_tok : cfg.max_tok;
     RAD_INFO("chunk geometry: quantum %lld (attn block %lld, state chunk %lld), checkpoint "
              "interval %lld, max_tok %lld -> prefill chunks of at most %lld%s",
              (long long)g.quantum, (long long)g.attn_block, (long long)g.state_chunk,
              (long long)g.checkpoint_interval, (long long)cfg.max_tok, (long long)eff,
-             eff < cfg.max_tok ? " (the checkpoint interval, not the budget)" : "");
+             eff >= cfg.max_tok ? ""
+             : g.span > 1 ? " (the checkpoint interval times the span, not the budget)"
+                          : " (the checkpoint interval, not the budget)");
+    if (cfg.prefill_span > 1) {
+        /* What the span does here, said once: the intervals the budget holds can be fewer than
+         * the flag asks for, and a model without an interval grid spans nothing. */
+        const int64_t held = g.span > 1 ? std::min(g.span, cfg.max_tok / g.checkpoint_interval) : 0;
+        if (g.span <= 1)
+            RAD_WARN("--prefill-span %lld: this model has no checkpoint interval grid (%s), so no "
+                     "chunk spans; a prefill alone in its step may still take the whole budget, "
+                     "and every other step is planned at %lld tokens", (long long)cfg.prefill_span,
+                     g.checkpoint_interval > 0 ? "its snapshots are taken at a prompt's end"
+                                               : "it keeps no linear state",
+                     (long long)g.shared_tok);
+        else if (held < 2)
+            RAD_WARN("--prefill-span %lld does nothing: --max-num-batched-tokens %lld holds one "
+                     "checkpoint interval of %lld tokens, and a span of %lld needs %lld",
+                     (long long)cfg.prefill_span, (long long)cfg.max_tok,
+                     (long long)g.checkpoint_interval, (long long)cfg.prefill_span,
+                     (long long)(cfg.prefill_span * g.checkpoint_interval));
+        else
+            RAD_INFO("chunk geometry: a prefill alone in its step spans up to %lld intervals%s "
+                     "from its second interval on; every other step is planned at %lld tokens",
+                     (long long)held,
+                     held < g.span ? fmt(" (all the budget holds of the %lld asked)",
+                                         (long long)g.span).c_str() : "",
+                     (long long)g.shared_tok);
+    }
     return RAD_OK;
 }
 
diff --git a/core/sched/geometry.h b/core/sched/geometry.h
index c11ba385..a0bb327c 100644
--- a/core/sched/geometry.h
+++ b/core/sched/geometry.h
@@ -1,17 +1,11 @@
-/* geometry.h -- the chunk geometry, COMPUTED from the resolved kernels rather than documented as
- * a minimum an operator has to know.
+/* geometry.h -- the prefill chunk geometry, computed from the resolved kernels.
  *
- * vLLM makes a hybrid model's operator pass a minimum `--max-num-batched-tokens` by hand, because
- * it inflates the attention block size until it matches the mamba page and then asserts the batch
- * budget covers it. The constraint is real; the fact that a human has to carry the number is not.
- * Here declare has already resolved every kernel, so the constraints that produce it are in hand:
- * the attention block size comes off the resolved attention kernel (§7.2) and the linear-state
- * chunk length off whichever resolved kernels mark a parameter RAD_PROLE_SEQ_CHUNK, and the
- * reconciliation is arithmetic.
- *
- * If the resolved geometry needs more tokens than the operator budgeted, that is said at startup
- * with the number and the engine refuses -- rather than running something subtly wrong, which here
- * means chunks that never land on a checkpoint boundary and a linear prefix hit rate of zero.
+ * The attention block size comes from the resolved attention kernel (§7.2) and the linear-state
+ * chunk length from every resolved kernel that marks a parameter RAD_PROLE_SEQ_CHUNK, so the
+ * operator never has to supply a minimum --max-num-batched-tokens by hand (as vLLM requires for
+ * hybrid models). If the budget is below what the geometry needs, startup prints the number and
+ * refuses: a smaller budget means chunks never land on a checkpoint boundary and the linear
+ * prefix hit rate is zero.
  */
 #pragma once
 #include "rad_core.h"
@@ -19,50 +13,64 @@
 namespace rad {
 
 struct ChunkGeometry {
-    /* The attention block size, reconciled across every paged KV group. Taken from the resolved
-     * kernel; libr4d's paged attention is compiled for 16 and rejects anything else. */
+    /* Attention block size, the lcm across every paged KV group. libr4d's paged attention is
+     * compiled for 16 only. */
     int64_t attn_block = 1;
 
-    /* The length a linear-state scan tiles at -- libr4d's gated delta net is the one that has
-     * one, at 64. Scanned off the constraints of every op whose schema marks a parameter
-     * RAD_PROLE_SEQ_CHUNK, and off the geometry the architecture plugin declared them with. */
+    /* Tile length of a linear-state scan (64 for libr4d's gated delta net). Taken from the
+     * declared geometry and kernel constraints of every op whose schema marks a parameter
+     * RAD_PROLE_SEQ_CHUNK. */
     int64_t state_chunk = 1;
 
-    /* What a NON-FINAL prefill chunk must be a multiple of: lcm(attn_block, state_chunk). A chunk
-     * that ends here ends on an attention block boundary and on a linear chunk boundary at once,
-     * so neither kernel is handed a partial tile it has to special-case. */
+    /* lcm(attn_block, state_chunk); every non-final prefill chunk is a multiple of it, so no
+     * kernel is handed a partial tile. */
     int64_t quantum = 1;
 
-    /* The linear-state checkpoint interval (§7.3), rounded UP from the operator's request to a
-     * multiple of `quantum`, so splitting at an interval is automatically a legal chunk split.
-     * Zero when the model has no linear state and checkpointing means nothing. */
+    /* Linear-state checkpoint interval (§7.3): the operator's request rounded up to a multiple
+     * of `quantum`, so a split at the interval is a legal chunk split. Zero without linear state
+     * (see window_ckpt for the exception). */
     int64_t checkpoint_interval = 0;
 
+    /* How many intervals one prefill chunk may carry from an interval boundary past the first
+     * (Config::prefill_span); 1 without an interval grid. plan_chunk is where it acts. */
+    int64_t span = 1;
+
+    /* The budget of every step a span does not take (prefill_shared_tok). A span is for a prefill
+     * alone in its step (Scheduler::step); a step carrying anything else is planned at this
+     * budget as a deployment without a span plans it, so the span's extra rows never lengthen a
+     * step other requests wait on. */
+    int64_t shared_tok = 0;
+
     /* The smallest --max-num-batched-tokens this geometry can be served with. */
     int64_t min_max_tok = 1;
 
-    /* An upper bound some kernel placed on the chunk length, or 0. Used only to detect a
-     * contradiction, which is a kernel-set bug worth naming rather than clamping around. */
+    /* Smallest upper bound a kernel places on the chunk length, or 0. Used only to report a
+     * contradiction with `quantum`, never to clamp. */
     int64_t max_chunk = 0;
 
-    /* Every contributor by name, for the startup line and for the refusal. Built once. */
+    /* Every contributor by name, for the startup line and the refusal. */
     std::string why;
 
-    /* NO LINEAR STATE, A SLIDING WINDOW: the checkpoint snapshots the window behind a prompt's
-     * tail (KVManager::has_window_snapshot) and nothing else. Chunks are not split at the
-     * interval -- a window snapshot in the middle of a prompt buys a later hit nothing its tail
-     * does not -- and the interval is only the shortest prompt worth a snapshot. */
+    /* No linear state but a sliding window: the checkpoint snapshots only the window behind a
+     * prompt's tail (KVManager::has_window_snapshot). Chunks are not split at the interval, since
+     * a mid-prompt window snapshot gains nothing; the interval is only the shortest prompt worth
+     * a snapshot. */
     bool window_ckpt = false;
 
     bool checkpoints() const { return checkpoint_interval > 0; }
 };
 
+/* The budget of a step a span does not take (ChunkGeometry::shared_tok), from the configuration
+ * alone: --max-num-batched-tokens less the span's extra intervals, at least one interval, and the
+ * whole budget without a span. The engine states it to the plugin before declare
+ * (RadBuildCtx::max_mixed_tok) and the scheduler plans by it, so the two agree. */
+int64_t prefill_shared_tok(const Config& cfg);
+
 /* Resolve the geometry from the declared program and the operator's budgets.
  *
- * Returns RAD_OK, or RAD_E_INVAL when cfg.max_tok cannot serve the geometry -- in which case the
- * required number is in out->min_max_tok and the reason in out->why, and the caller is expected to
- * print both and stop. Returns RAD_E_SHAPE when two kernels' constraints cannot be satisfied at
- * once, which is a kernel-set bug and not an operator one. */
+ * Returns RAD_E_INVAL when cfg.max_tok is too small (the required number is in
+ * out->min_max_tok, the reason in out->why; the caller stops), and RAD_E_SHAPE when two kernels'
+ * constraints contradict each other, which is a kernel-set bug. */
 int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry* out);
 
 }  /* namespace rad */
diff --git a/core/sched/mem_iface.h b/core/sched/mem_iface.h
index 3296f4cf..94336f00 100644
--- a/core/sched/mem_iface.h
+++ b/core/sched/mem_iface.h
@@ -1,24 +1,14 @@
 /* mem_iface.h -- the seam between core/sched and core/mem.
  *
- * core/mem owns the concrete `KVManager` and `PrefixCache`. The scheduler binds to the pure-virtual
- * mirrors below rather than to those classes directly, for two reasons and neither is abstraction
- * for its own sake:
+ * The scheduler binds to pure-virtual mirrors of core/mem's `KVManager` (kv.h) and `PrefixCache`
+ * (prefix.h) instead of the classes themselves:
  *
- *   - it lets tests/sched_test.cpp drive the scheduler against a block pool it can make
- *     arbitrarily small, which is the only way to test admission refusal and preemption at all;
- *   - it costs one indirect call per SEQUENCE per step (at most max_seqs, a few hundred), not one
- *     per token, so it is off the part of the step path that is actually hot.
+ *   - tests/sched_test.cpp can drive the scheduler against an arbitrarily small block pool, the
+ *     only way to test admission refusal and preemption;
+ *   - the cost is one indirect call per sequence per step, not per token.
  *
- * `KVBinding` / `PCBinding` at the bottom adapt the concrete classes and require no change on
- * their side. They are templates so that they are only type-checked where the engine instantiates
- * them -- so a method core/mem does not provide is a compile error at exactly one line rather
- * than a comment nobody reads.
- *
- * The interface below mirrors core/mem/kv.h and core/mem/prefix.h.
- *
- * `CacheHit` comes from core/mem/prefix.h and is NOT redefined here. Two identical definitions of
- * a struct that crosses a component boundary is an ODR violation that costs nothing today and
- * becomes a silent layout mismatch the first time one side adds a field.
+ * `KVBinding` / `PCBinding` at the bottom adapt the concrete classes. `CacheHit` comes from
+ * core/mem/prefix.h; do not redefine it here (ODR).
  */
 #pragma once
 #include 
@@ -31,10 +21,9 @@
 namespace rad {
 
 /* ------------------------------------------------------------------ the KV manager */
-/* Keyed by SEQUENCE ID, which is the request id. The manager owns the block tables; Request::blocks
- * is not the source of truth and the scheduler does not read it. Two allocators disagreeing about
- * what a sequence owns is not a leak, it is the bug where a freed sequence's state slot is handed
- * to the next request while the first still reads it. */
+/* Keyed by sequence id (the request id). The manager owns the block tables; the scheduler does
+ * not read Request::blocks, so there is one owner and a freed state slot cannot be handed out
+ * while its previous sequence still reads it. */
 struct IKVManager {
     virtual ~IKVManager() = default;
 
@@ -43,98 +32,80 @@ struct IKVManager {
     virtual void free_sequence(uint64_t seq) = 0;
 
     /* Grow the sequence's mapping to cover `n_tokens` in every group. RAD_E_FULL when a group's
-     * free list is empty, which is a scheduling signal and not an error: the caller preempts a
-     * victim and retries. */
+     * free list is empty; the caller preempts a victim and retries. */
     virtual int  ensure(uint64_t seq, int64_t n_tokens) = 0;
-    /* The same, for a step whose first query sits at `keep_from` (the request's n_computed): a
-     * WINDOW group then keeps every block that query can still read, however long the step is.
-     * See KVManager::ensure. The default is for a manager with no windowed group. */
+    /* As ensure(), for a step whose first query is at `keep_from` (the request's n_computed): a
+     * window group keeps every block that query can still read (KVManager::ensure). The default
+     * suits a manager with no windowed group. */
     virtual int  ensure_from(uint64_t seq, int64_t n_tokens, int64_t keep_from) {
         (void)keep_from;
         return ensure(seq, n_tokens);
     }
-    /* A committed step: a WINDOW group gives back what no later query can read. A no-op for a
-     * manager with no windowed group. See KVManager::trim_window. */
+    /* After a committed step, a window group frees what no later query can read
+     * (KVManager::trim_window). */
     virtual void trim_window(uint64_t seq, int64_t keep_from) { (void)seq; (void)keep_from; }
-    /* The window snapshot of a prefix hit (KVManager::has_window_snapshot / seed_window). The
-     * defaults are a manager with none: no hit on a windowed trunk is ever resumed. */
+    /* Window snapshot of a prefix hit (KVManager::has_window_snapshot / seed_window). The
+     * defaults mean no hit on a windowed trunk is ever resumed. */
     virtual bool has_window_snapshot() const { return false; }
     virtual int  seed_window(uint64_t seq, int64_t pos) { (void)seq; (void)pos; return -1; }
 
-    /* Adopt blocks a prefix-cache hit found. `n_tokens` must be a whole multiple of the group's
-     * block size -- a partial block is never shared, because the next token written into it would
-     * corrupt the cache entry. */
+    /* Adopt blocks a prefix-cache hit found. `n_tokens` must be a multiple of the group's block
+     * size; a shared partial block would be corrupted by the next token written into it. */
     virtual int  adopt(uint64_t seq, int32_t group, const std::vector& blocks,
                        int64_t n_tokens) = 0;
 
     /* Free the blocks and mark the sequence for re-prefill. */
     virtual int  preempt(uint64_t seq) = 0;
 
-    /* Could a sequence of this length EVER fit, in an empty pool? If not, preempting the whole
-     * server would not help and the request is failed immediately rather than the engine
-     * deadlocking on it (spec §17). */
+    /* Whether a sequence of this length fits an empty pool. If not, the request fails at once
+     * instead of deadlocking the engine (spec §17). */
     virtual bool can_ever_fit(int64_t n_tokens) const = 0;
 
     virtual const std::vector& block_table(uint64_t seq, int32_t group) const = 0;
     virtual int32_t state_slot(uint64_t seq, int32_t group) const = 0;
 
-    /* THE WHOLE state_index ROW FOR A SEQUENCE, and how wide it is. One entry, normally: the
-     * sequence's state. A group whose kernel asked for scratch beside the state names that too,
-     * and the manager owns the mapping from column to physical slot because it owns the pool --
-     * the scheduler stages the row and does not read it. Returns the width written, 0 for a
-     * paged group. `max` bounds the write. */
+    /* The sequence's state_index row: normally one entry (its state slot), plus any scratch
+     * slots the group's kernel asked for. The manager owns the column-to-slot mapping; the
+     * scheduler stages the row without reading it. Returns the width written (0 for a paged
+     * group), at most `max`. */
     virtual int state_index_row(uint64_t seq, int32_t group, int32_t* out, int max) const = 0;
     virtual int64_t state_index_width(int32_t group) const = 0;
 
     virtual int64_t free_blocks(int32_t group) const = 0;
     virtual int64_t total_blocks(int32_t group) const = 0;
-    /* What anything is HOLDING, as against what may be handed out right now. See
-     * KVManager::held_blocks: on an elastic pool the two differ by whatever the cache has
-     * released, and an occupancy figure built from the second reads an idle server as full. */
+    /* Blocks held by anything, as opposed to free_blocks (what can be handed out now). On an
+     * elastic pool they differ by what the cache released (KVManager::held_blocks). */
     virtual int64_t held_blocks(int32_t group) const = 0;
 
-    /* THE SAME POOL IN BYTES. Blocks and tokens are both un-summable across groups -- a stateful
-     * group has neither, and two paged groups share one token axis -- so bytes are the only
-     * measure a reader can add up to "how much of the card is the KV cache holding". Asked of the
-     * manager rather than derived here, because the manager owns the plan that knows whether a
-     * group is counted in blocks or in states. */
+    /* The pool in bytes, the only unit that sums across groups. Asked of the manager because its
+     * plan knows whether a group counts blocks or states. */
     virtual int64_t pool_bytes(int32_t group) const = 0;
     virtual int64_t pool_bytes_used(int32_t group) const = 0;
-    /* What the carve gave the group, which an elastic pool may have released part of. */
+    /* What the carve gave the group; an elastic pool may have released part of it. */
     virtual int64_t pool_bytes_carved(int32_t group) const = 0;
 
-    /* HOW MANY TOKENS ONE BLOCK OF THIS GROUP COVERS, or 0 for a stateful group. The pool's
-     * capacity in blocks is already here; the live request table wants it in TOKENS, because that
-     * is the unit a request is measured in and the only one the two can be compared in. */
+    /* Tokens one block covers, or 0 for a stateful group. */
     virtual int64_t block_tokens(int32_t group) const = 0;
 
-    /* SPECULATIVE REJECTION ROLLBACK (spec §10). A verify writes KV for 1 + n_spec
-     * positions and the sampler accepts a prefix of them; the sequence's length must come back to
-     * the accepted position and the blocks past it must go to the free list. `ensure` is monotone
-     * and cannot express it.
-     *
-     * It is a slot-table edit and nothing else -- crucially it does NOT touch the linear or conv
-     * groups, whose rollback is a change of read offset the kernels perform themselves. Without
-     * this the pool leaks one block per rejected block-crossing, which is a slow leak and
-     * therefore the worst kind. */
+    /* Speculative rejection rollback (spec §10). A verify writes KV for 1 + n_spec positions and
+     * the sampler accepts a prefix; this shrinks the sequence to `n_tokens` and frees blocks past
+     * it, which the monotone ensure() cannot. Only the slot table changes: linear and conv groups
+     * roll back by read offset inside their kernels. */
     virtual int  rollback(uint64_t seq, int64_t n_tokens) = 0;
 
-    /* THE ABSOLUTE TOKEN POSITION that block_table(seq, group)[0] covers. Zero for a
-     * FULL group and non-zero for a WINDOW group, whose blocks below the window are recycled: the
-     * step batch's slot mapping is `(pos - first_block_pos) / block_size`, and with the offset
-     * missing every sliding-window sequence writes its KV to the wrong slot the moment it passes
-     * its window. KVManager::Seq already tracks this privately as `first_block_pos`. */
+    /* Absolute token position that block_table(seq, group)[0] covers: zero for a full group,
+     * non-zero for a window group once blocks below the window are recycled. The step batch maps
+     * a slot as `(pos - first_block_pos) / block_size`. */
     virtual int64_t first_block_pos(uint64_t seq, int32_t group) const = 0;
 
-    /* THE ENTRIES OF block_table(seq, group) THAT CHANGED since the previous call: everything
-     * below the returned index is unchanged, and INT64_MAX says nothing changed. Reading clears
-     * it, so the batch builder is its one caller: it keeps the device's copy of a table and
-     * stages only what moved. 0 is always a correct answer -- it restages the whole table. */
+    /* Index of the first entry of block_table(seq, group) changed since the previous call;
+     * INT64_MAX if none.
+     * Reading clears it, so the batch builder, which keeps the device copy and stages only the
+     * changed tail, must be the only caller. 0 is always correct (restage the whole table). */
     virtual int64_t take_table_changes(uint64_t seq, int32_t group) const = 0;
 
-    /* THE SNAPSHOT STORE STILL HOLDS `slot`: it was allocated and not given back since. A step
-     * that restores from a slot the store gave back would read another session's state or
-     * nothing, so the scheduler asks before it builds one. */
+    /* Whether the snapshot store still holds `slot`. The scheduler checks before building a
+     * restore step, since a released slot may hold another session's state. */
     virtual bool checkpoint_held(int32_t slot) const = 0;
 };
 
@@ -142,53 +113,42 @@ struct IKVManager {
 struct IPrefixCache {
     virtual ~IPrefixCache() = default;
 
-    /* Longest cached prefix, plus the checkpoint covering the linear state for a prefix of it.
-     * `blocks_out` receives the block ids per cached group, in cached_groups() order, ready for
-     * IKVManager::adopt. */
-    /* GIVE BACK WHATEVER THE TIERS HOLD FOR THIS PROMPT, before the lookup that would otherwise
-     * stop at it.
-     *
-     * The scheduler calls it and must not know what a tier is: a restore allocates blocks and
-     * runs a device scatter, so it is the engine's to perform and is installed as a callable
-     * rather than reached through this header. A failure is not an error here -- it leaves a
-     * shorter prefix, and a shorter prefix is always safe. */
+    /* Bring back whatever the idle tiers hold for this prompt, before the lookup. The engine
+     * performs it (it allocates blocks and runs a device scatter). A failure only leaves a
+     * shorter prefix, which is always safe. */
     virtual void restore(const Request&) {}
-    /* A step's admissions begin: what the last step's lookups handed out has been read. */
+    /* A step's admissions begin; the last step's lookup results have been consumed. */
     virtual void begin_step() {}
-    /* KEEP THIS WAITING REQUEST'S CHAIN WHERE IT IS until release(). Called when an admission is
-     * refused after restore(): the request gives its hit back, and without the hold the chain it
-     * just had restored would leave VRAM again before the next attempt restores it once more. */
+    /* Keep this waiting request's chain in VRAM until release(). Called when admission is refused
+     * after restore(), so the restored chain is not moved out again before the next attempt. */
     virtual void hold(const Request&) {}
-    /* The request is gone -- finished, failed or cancelled -- and holds nothing any more. */
+    /* The request finished, failed or was cancelled and holds nothing any more. */
     virtual void release(const Request&) {}
 
-    /* `cap`, when not null, ends the hit early (HitCap, core/mem/prefix.h). */
+    /* Longest cached prefix, plus the checkpoint covering the linear state for a prefix of it.
+     * `blocks_out` receives block ids per cached group, in cached_groups() order, for
+     * IKVManager::adopt. `cap`, when not null, ends the hit early (HitCap, core/mem/prefix.h). */
     virtual CacheHit lookup(const Request& r, std::vector>* blocks_out,
                             const HitCap* cap) const = 0;
     virtual const std::vector& cached_groups() const = 0;
 
-    /* PUBLISH what this sequence computed, so the next request sharing the prefix can adopt it.
-     * Without this the cache is only ever read: every lookup misses, `cached_tokens` is always
-     * zero, and a chat client re-prefills its whole history on every turn, which for a long
-     * conversation is seconds a message. `blocks[i]` is the block table of cached_groups()[i], and
-     * `n_tokens` how many of them are backed. Takes a KV reference on every newly indexed block,
-     * so it must be called BEFORE the sequence's own blocks are released. */
+    /* Publish what this sequence computed so a later request sharing the prefix can adopt it.
+     * `blocks[i]` is the block table of cached_groups()[i]; `n_tokens` is how many tokens are
+     * backed. Takes a KV reference on every newly indexed block, so call it before the sequence's
+     * own blocks are released. */
     virtual int insert(const Request& r, const std::vector>& blocks,
                        int64_t n_tokens) = 0;
 
-    /* Release the least recently used entries, and with them their KV references. The cache holds
-     * blocks no live sequence needs, so this is what the scheduler tries BEFORE preempting a
-     * running request: a cached prefix is a saving, a running request is work already done. */
+    /* Release the least recently used entries and their KV references. The scheduler tries this
+     * before preempting a running request. */
     virtual int64_t evict(int64_t n_entries) = 0;
-    /* FREE UP TO `n_blocks` FOR THE RESERVE, and nothing a later turn needs. Unlike evict(), which
-     * answers a shortfall that cannot wait, this passes over an entry a live sequence still holds
-     * (releasing it frees no block) and one whose only copy is in VRAM (it is the next turn's
-     * context). Returns how many blocks went back to the pool. */
+    /* Free up to `n_blocks` for the reserve without losing anything a later turn needs. Unlike
+     * evict(), it skips entries a live sequence still holds (no block would be freed) and entries
+     * whose only copy is in VRAM. Returns the number of blocks freed. */
     virtual int64_t trim(int64_t n_blocks) = 0;
 
-    /* FORGET EVERYTHING, wherever it is. Not a loop over evict(): with idle tiers an eviction moves
-     * an entry whose host copy has landed off the card and keeps it, so a reset built out of
-     * evictions would leave every such conversation behind. Returns how many entries went. */
+    /* Drop every entry in every tier. Implementations with idle tiers must override this: there,
+     * evict() keeps an entry whose host copy has landed. Returns the number of entries dropped. */
     virtual int64_t reset() {
         int64_t dropped = 0;
         for (int guard = 0; guard < 65536; ++guard) {
@@ -199,60 +159,50 @@ struct IPrefixCache {
         return dropped;
     }
 
-    /* HOW MANY ENTRIES THE CACHE HAS THROWN AWAY, which is the leading indicator of the failure
-     * mode that matters operationally: once the pool is utilised past the reserve the scheduler
-     * keeps free (a quarter of it), the cache begins evicting prefixes that are about to be
-     * reused, and an agent's next turn re-prefills its whole context -- turning a cached turn of
-     * a few seconds into a full prefill of a very long prompt. `prefix_hit_rate` only falls AFTER
-     * that has happened; this count rises first. */
+    /* Entries evicted, cumulative. Once the pool fills past the scheduler's reserve (a quarter of
+     * it), the cache evicts prefixes about to be reused; this count rises before the hit rate
+     * falls. */
     virtual int64_t evictions() const = 0;
     virtual int64_t ckpt_evictions() const = 0;
-    /* And what --prefix-cache-ttl took: not memory pressure, so not evictions. */
+    /* ckpt_evictions by reason, and reservations that found nothing to give up
+     * (PrefixCache::Stats). */
+    struct CkptCounts { int64_t retired = 0, lru = 0, refused = 0; };
+    virtual CkptCounts ckpt_counts() const { return {}; }
+    /* Entries expired by --prefix-cache-ttl; not counted as evictions. */
     virtual int64_t expired() const { return 0; }
     virtual int64_t ckpt_expired() const { return 0; }
 
-    /* WHAT IT IS HOLDING ON ITS OWN RIGHT NOW, in tokens of context, as against the counters
-     * above which are cumulative. A finished turn's blocks stay held so the next turn can reuse
-     * them, so on any server serving conversations MOST of a full KV pool is this rather than the
-     * live sequences -- and with one number for the pool there is no way to see that, which makes
-     * a working cache indistinguishable from a leak.
-     *
-     * ON ITS OWN is the whole of it. A cached block a running sequence is also reading is not
-     * memory the cache is keeping back from anybody, and counting those would make a single 200K
-     * request look like a cache refusing to release 200K. */
+    /* Tokens of context held only by the cache right now. Blocks a running sequence also reads
+     * are excluded. Separates a working cache from a leak in the pool figures. */
     virtual int64_t held_tokens() const = 0;
 
     /* The next position strictly after `pos` at which the scheduler must split a chunk so that a
      * checkpoint lands on a boundary. */
     virtual int64_t next_checkpoint_after(int64_t pos) const = 0;
 
-    /* Reserve the snapshot slot the scheduler is about to WRITE. Retention is budgeted (§7.3:
-     * ~96 MiB a snapshot, so 64 of them is 6 GiB), which makes RAD_E_FULL an ordinary condition
-     * and not a failure -- the scheduler simply does not write a checkpoint at that boundary and
-     * the next hit replays from the previous one. */
+    /* Reserve the snapshot slot the scheduler is about to write. Retention is budgeted (§7.3: on
+     * Qwen3.5-27B a snapshot is 144 MiB, and a 128K session at the default interval is 64 of them,
+     * about 9 GiB), so RAD_E_FULL is ordinary: no checkpoint is written at that boundary and a
+     * later hit replays from the previous one. */
     virtual int reserve_checkpoint(const Request& r, int64_t pos, int32_t* slot_out) = 0;
 
-    /* The state that reservation named is now IN its slot. A reservation is made when the chunk is
-     * PLANNED and the state exists only after the step that computes it, so a lookup in between
-     * would adopt a slot holding the previous tenant's history. Until this is called, the
-     * reservation is a promise and lookup will not offer it. */
+    /* The reserved state is now in its slot. Reservation happens at planning, before the step
+     * computes the state, so lookup does not offer the slot until this is called. */
     virtual void commit_checkpoint(const Request& r, int64_t pos) = 0;
 };
 
 /* ------------------------------------------------------------------ block geometry */
-/* Everything the step batch needs to turn a token position into a KV slot, read off the declared
- * program rather than off the manager: block size is KVGroupInfo::block_size, which the build
- * component already took from the resolved attention kernel's constraints (§7.2). Duplicating it
- * through a second interface would be a second place for it to be wrong. */
+/* What the step batch needs to turn a token position into a KV slot, read from the declared
+ * program: KVGroupInfo::block_size comes from the resolved attention kernel's constraints
+ * (§7.2). */
 struct KVGeom {
     struct G {
         int     kind = RAD_KV_FULL;
         int64_t block_size = 1;
         int64_t window = 0;
         bool    paged = true;
-        /* Columns in this group's state_index row. The MANAGER decides it -- it depends on what
-         * the group's kernel wants beside the state -- so KVGeom::of leaves it at 1 and the
-         * scheduler fills it in from the configured pool. */
+        /* Columns in this group's state_index row. The manager decides it, so KVGeom::of leaves
+         * it at 1 and the scheduler fills it in from the configured pool. */
         int64_t sidx_width = 1;
     };
     std::vector g;
@@ -282,8 +232,7 @@ struct KVGeom {
 };
 
 /* ------------------------------------------------------------------ binding the concrete classes */
-/* Templates, so nothing here is type-checked until the engine instantiates it against the real
- * classes. That instantiation is where a mismatch with core/mem is reported. */
+/* Templates, so a mismatch with core/mem is reported where the engine instantiates them. */
 template 
 struct KVBinding final : IKVManager {
     KV* m;
@@ -330,11 +279,9 @@ struct KVBinding final : IKVManager {
     bool checkpoint_held(int32_t slot) const override { return m->checkpoint_held(slot); }
 };
 
-/* The prefix cache's own lookup takes tokens and content-hashed multimodal keys rather than a
- * Request, because the placeholder ids inside a media run are identical for every picture: hashing
- * the ids alone would serve one request another's image. Each run is keyed by its item's content
- * key (core/mm, taken over the processed patches) and its segment, so the same picture at the same
- * place hits -- and skips the encoder along with the prefill -- and two pictures never alias. */
+/* Content keys for a request's media runs. Placeholder ids are identical for every picture, so
+ * the prefix cache also hashes each run's item content key (core/mm, over the processed patches)
+ * and segment: the same picture at the same place hits, two pictures never alias. */
 inline void media_keys(const Request& r, std::vector* out) {
     out->clear();
     if (!r.media) return;
@@ -376,9 +323,8 @@ struct PCBinding final : IPrefixCache {
     void release(const Request& r) override { m->release(r.id); }
     const std::vector& cached_groups() const override { return m->cached_groups(); }
 
-    /* prompt ++ output, for the same reason reserve_checkpoint chains both: the next turn of a
-     * conversation sends the reply back as part of its prompt, so a cache that indexed only the
-     * prompt would stop hitting at the first assistant token and re-prefill everything after it. */
+    /* Indexes prompt ++ output: the next turn sends the reply back in its prompt, so indexing the
+     * prompt alone would stop hitting at the first assistant token. */
     int insert(const Request& r, const std::vector>& blocks,
                int64_t n_tokens) override {
         std::vector toks;
@@ -386,20 +332,16 @@ struct PCBinding final : IPrefixCache {
         toks.insert(toks.end(), r.prompt.begin(), r.prompt.end());
         toks.insert(toks.end(), r.output.begin(), r.output.end());
         if (n_tokens > (int64_t)toks.size()) n_tokens = (int64_t)toks.size();
-        /* r.id is the session, and it is the SAME id reserve_checkpoint keys its snapshots by --
-         * so the tiers' session view and the checkpoint index are talking about one thing. */
+        /* r.id is the session, the same id reserve_checkpoint keys its snapshots by. */
         media_keys(r, &mm_);
         return m->insert(r.id, toks, mm_, blocks, n_tokens, r.session_label);
     }
-    /* Installed by the engine when the idle tiers are on: lands every host copy that is waiting,
-     * now, and says whether any landed. Called on the step thread under the scheduler's lock. */
+    /* Installed by the engine when the idle tiers are on: lands every pending host copy now and
+     * returns whether any landed. Runs on the step thread under the scheduler's lock. */
     std::function flush_fn;
-    uint64_t lost_warned_ns_ = 0;
-    /* PRESSURE TAKES WHAT CAN LEAVE VRAM AND STAY, FIRST. An entry whose host copy has landed is
-     * dropped and kept (trim); a copy still on its way is landed and that entry dropped too; only
-     * what the tiers then still cannot take -- an arena with no room, or no tiers at all -- is
-     * erased, and an erase with the tiers on is said, because it is a conversation a later turn
-     * will prefill again. */
+    /* Under pressure, first drop entries whose host copy has landed (trim), then land pending
+     * copies and trim again. Only the rest is erased; with tiers on, an erase is warned about,
+     * since a later turn will prefill that conversation again. */
     int64_t evict(int64_t n) override {
         int64_t k = m->trim(n);
         if (k < n && flush_fn && flush_fn()) k += m->trim(n - k);
@@ -427,23 +369,20 @@ struct PCBinding final : IPrefixCache {
     }
     int64_t evictions() const override { return m->stats().evictions; }
     int64_t ckpt_evictions() const override { return m->stats().ckpt_evictions; }
+    CkptCounts ckpt_counts() const override {
+        const auto& st = m->stats();
+        return { st.ckpt_retired, st.ckpt_lru, st.ckpt_refused };
+    }
     int64_t expired() const override { return m->stats().expired; }
     int64_t ckpt_expired() const override { return m->stats().ckpt_expired; }
     int64_t held_tokens() const override { return m->unshared_tokens(); }
 
     int64_t next_checkpoint_after(int64_t p) const override { return m->next_checkpoint_after(p); }
     int reserve_checkpoint(const Request& r, int64_t pos, int32_t* slot_out) override {
-        /* The cache keys a snapshot by the CHAINED HASH of the prefix it covers, and the chain is
-         * built here rather than inside the cache because the cache does not hold the tokens --
-         * that is the whole reason this interface passes a Request. It must be the SAME chain
-         * lookup() walks, or a checkpoint reserved at `pos` and a later hit at `pos` name two
-         * different entries and the linear cache silently never hits.
-         *
-         * The prefix is prompt ++ output: a checkpoint written during decode covers tokens the
-         * request has generated, and keying it on the prompt alone would alias every continuation
-         * of the same prompt onto one snapshot -- which is one session's recurrent state served to
-         * another. Whole blocks only; a partial block is never keyed, because the next token
-         * written into it would change what the key stands for. */
+        /* A snapshot is keyed by the chained hash of the prefix it covers, built here because the
+         * cache does not hold the tokens. It must match the chain lookup() walks, or the linear
+         * cache never hits. The prefix is prompt ++ output, so continuations of one prompt do not
+         * share a snapshot; whole blocks only, since a partial block's key would change. */
         return m->reserve_checkpoint(r.id, pos, prefix_hash(r, pos), slot_out);
     }
 
@@ -452,9 +391,11 @@ struct PCBinding final : IPrefixCache {
     }
 
 private:
-    /* The chain reserve_checkpoint keys on, factored out so commit cannot drift from it: two
-     * copies of this walk that agreed when written would be two copies that could stop agreeing,
-     * and the symptom would be a checkpoint that is written and never found. */
+    uint64_t lost_warned_ns_ = 0;
+    mutable std::vector blk_;   /* prefix_hash's block of tokens, kept for its capacity */
+
+    /* The chain reserve_checkpoint and commit_checkpoint both key on; shared so they cannot
+     * drift apart. */
     BlockHash prefix_hash(const Request& r, int64_t pos) const {
         media_keys(r, &mm_);
         const int64_t bs = m->block_size();
@@ -463,14 +404,14 @@ private:
         const int64_t np = (int64_t)r.prompt.size(), no = (int64_t)r.output.size();
         const int64_t have = np + no;
         const int64_t n_blocks = (pos < have ? pos : have) / bs;
-        std::vector blk((size_t)bs);
+        blk_.resize((size_t)bs);
         for (int64_t b = 0; b < n_blocks; ++b) {
             const int64_t base = b * bs;
             for (int64_t j = 0; j < bs; ++j) {
                 const int64_t k = base + j;
-                blk[(size_t)j] = k < np ? r.prompt[(size_t)k] : r.output[(size_t)(k - np)];
+                blk_[(size_t)j] = k < np ? r.prompt[(size_t)k] : r.output[(size_t)(k - np)];
             }
-            h = chain_block_hash(h, blk.data(), (int32_t)bs, mm_.data(), (int32_t)mm_.size(), base);
+            h = chain_block_hash(h, blk_.data(), (int32_t)bs, mm_.data(), (int32_t)mm_.size(), base);
         }
         return h;
     }
diff --git a/core/sched/metrics.h b/core/sched/metrics.h
index 9bb78ba8..81dfeff8 100644
--- a/core/sched/metrics.h
+++ b/core/sched/metrics.h
@@ -1,9 +1,7 @@
-/* metrics.h -- the scheduler's snapshot, for the server's /metrics endpoint (spec §14).
+/* metrics.h -- the scheduler's snapshot for the server's /metrics endpoint (spec §14).
  *
- * A plain struct of numbers with no strings built and nothing formatted. Formatting belongs to
- * whoever is exporting -- Prometheus wants vLLM-compatible names, the live view wants a terminal
- * line, and a scheduler that rendered either would have to be edited to add the other. Fixed
- * arrays, so a scrape allocates nothing and cannot contend with the step path for the allocator.
+ * Plain numbers only; each exporter (Prometheus, the live view) does its own formatting. Fixed
+ * arrays, so a scrape allocates nothing and never contends with the step path for the allocator.
  */
 #pragma once
 #include "rad_core.h"
@@ -28,45 +26,28 @@ struct SchedMetrics {
     int64_t preemptions = 0;
     int64_t steps = 0;
 
-    /* STEPS BY SHAPE, AND WHAT SPECULATION DID NOT REACH. `steps_mixed` over `steps` says how
-     * often the load produces a step carrying both a prefill chunk and decode rows; an agentic
-     * load produces them often enough to be worth measuring.
-     *
-     * `decode_rows_unspeculated` counts every decode row that took no draft, whatever the reason
-     * -- depth 0, a request that may not speculate, a drafter with nothing to propose. Counting
-     * ROWS rather than any one reason keeps it the answer to "how much of my decode is running
-     * unspeculated" as the set of reasons changes. Without it the loss is invisible: throughput
-     * falls and every explanation fits. */
+    /* Steps by shape. `steps_mixed` counts steps carrying both a prefill chunk and decode rows.
+     * `decode_rows_unspeculated` counts every decode row that took no draft, for any reason
+     * (depth 0, a request that may not speculate, a drafter with nothing to propose). */
     int64_t steps_prefill = 0;
     int64_t steps_mixed = 0;
     int64_t steps_decode = 0;
+    /* --prefill-interleave: decode-only steps the hold inserted, issued ahead or not; each kept a
+     * ready chunk out. */
+    int64_t steps_held = 0;
     int64_t decode_rows_unspeculated = 0;
-    /* STEPS ISSUED AHEAD: a step whose forward pass went onto the card behind the step before it,
-     * before that step committed (Scheduler::step_next). Every other step waits for the host's
-     * commit and staging with the card idle, so steps_ahead against steps is how much of the run
-     * kept the card fed through the host's part of it. */
+    /* Steps whose forward pass was enqueued behind the previous step before it committed
+     * (Scheduler::step_next). Every other step leaves the card idle during the host's commit and
+     * staging. */
     int64_t steps_ahead = 0;
-    /* PREFILL CHUNKS HELD BACK for other work in the same step (--busy-prefill-chunk): each is a
-     * chunk that would have taken more of the step and left decode rows behind it, or a request
-     * waiting to be admitted, with nothing. Zero under `off`, and on a load that never overlaps a
-     * prefill with anything else. */
+    /* Prefill chunks capped to leave room for decode rows or a waiting admission in the same
+     * step (--busy-prefill-chunk). Zero under `off`. */
     int64_t prefill_chunks_capped = 0;
 
-    /* HOW LONG THE ENGINE SPENT INSIDE A STEP, cumulative nanoseconds, and the decode half of it
-     * separately. Neither is a derived rate -- they are counters, and that is the point.
-     *
-     * A STEP TIME IS NOT WALL TIME OVER A STEP COUNT, and a gauge that computes it that way is
-     * wrong in two directions at once. An engine that idles between requests -- which is every
-     * agent, every chat client, every tool loop -- charges the idle gap to the steps around it,
-     * inflating the step time by however long nothing was running. And a prefill chunk costs an
-     * order of magnitude more than a decode step, so a load that mixes them averages two
-     * populations and calls the result the step time. Both faults are invisible without an
-     * instrument: the number is plausible, it moves with load, and nothing contradicts it.
-     *
-     * With these, `step_ns_decode / steps_decode` is a decode step time that needs no window, no
-     * saturation assumption and no second endpoint. Charged from the scheduler's own
-     * `step_start_`, which is the same clock `decode_tps` already uses -- so this adds no
-     * synchronisation and no timing mode (spec §16). */
+    /* Cumulative nanoseconds spent inside steps, total and for decode steps only. Wall time over
+     * a step count is not a step time: it charges idle gaps between requests to steps and mixes
+     * prefill with decode. `step_ns_decode / steps_decode` is the decode step time. Measured from
+     * `step_start_`, the clock `decode_tps` uses, so no extra synchronisation (spec §16). */
     int64_t step_ns = 0;
     int64_t step_ns_decode = 0;
 
@@ -77,44 +58,44 @@ struct SchedMetrics {
         int64_t blocks_total = 0;
         int64_t blocks_free = 0;
         float   utilisation = 0.0f;   /* 1 - free/total */
-        /* Tokens one block covers, 0 for a stateful group. A pool measured in blocks cannot be
-         * compared with a request measured in tokens, and every reader wants that comparison. */
+        /* Tokens one block covers, 0 for a stateful group. */
         int64_t block_tokens = 0;
-        /* A WINDOWED GROUP recycles its blocks below the window, so its carve says how far back a
-         * sequence keeps context and nothing about how much context fits. */
+        /* A windowed group recycles blocks below the window, so its size bounds how far back a
+         * sequence sees, not how much context fits. */
         bool    window = false;
-        /* AND THE SAME GROUP IN BYTES, which is the measure that survives being added to the next
-         * group's. Neither blocks nor tokens does: a stateful group has no token axis, and two
-         * paged groups share one, so a token of context takes a slot in both and summing them
-         * reports a pool the card does not have. */
+        /* The group in bytes, the only unit that sums across groups: a stateful group has no
+         * token axis, and paged groups share one, so summed tokens overcount. */
         int64_t bytes_total = 0;
         int64_t bytes_used = 0;
-        /* WHAT IT WAS CARVED TO ADDRESS, as against bytes_total, which is what the card is
-         * actually holding for it. The two differ by what the elastic pool has released: the
-         * cache releases the VRAM behind blocks nothing holds, and the difference between these
-         * two numbers is exactly what it gave back. Equal otherwise. */
+        /* Bytes the group was carved to address. bytes_total is what the card holds now; the
+         * difference is the VRAM the elastic pool released behind unheld blocks. */
         int64_t bytes_carved = 0;
     } kv[RAD_SCHED_MAX_KV_GROUPS];
 
     /* Prefix caching (§7.3). Attention and linear are reported separately because they hit at
-     * different granularities and a single number would hide exactly the effect the decoupling
-     * was for. */
+     * different granularities. */
     int64_t prompt_tokens = 0;
     int64_t attn_cached_tokens = 0;
     int64_t linear_cached_tokens = 0;
     float   attn_hit_rate = 0.0f;
-    /* Cumulative, from the prefix cache itself. Rising evictions under a steady workload
-     * mean the pool cannot hold the working set and turn-2 latency is about to collapse. */
+    /* Cumulative, from the prefix cache. Rising evictions under a steady workload mean the pool
+     * cannot hold the working set. */
     int64_t prefix_evictions = 0;
     int64_t prefix_ckpt_evictions = 0;
+    /* prefix_ckpt_evictions by reason (retention policy, least recently used of a full store),
+     * and reservations that went without a snapshot. */
+    int64_t prefix_ckpt_retired = 0, prefix_ckpt_lru = 0, prefix_ckpt_refused = 0;
     int64_t prefix_expired = 0, prefix_ckpt_expired = 0;   /* --prefix-cache-ttl */
-    /* WHAT THE CACHE IS HOLDING ON ITS OWN NOW, in tokens of context: the part of the pool that
-     * an eviction would actually free, because no live sequence is reading it. The pool figure
-     * above counts a held block whoever holds it, and on a server serving conversations most of
-     * it is this rather than the running requests -- so without it a working cache and a leak are
-     * the same picture. Blocks shared with a running sequence are NOT in it; counting them would
-     * make one long request read as a cache that would not release its context. Same token axis
-     * as the paged groups, so it is comparable with kv_tokens_used. */
+    /* Admissions whose attention hit was cut to nothing: no snapshot at or below it (recurrent
+     * state or a window snapshot), a windowed trunk group no window snapshot covers, or blocks
+     * that could not be adopted. `hit_cut_tokens` is the checkpoint shortfall: prompt tokens the
+     * attention cache held and the admission computed again, because the hit resumed at a
+     * snapshot below it or was cut to nothing. */
+    int64_t hit_cut_no_snapshot = 0, hit_cut_window = 0, hit_cut_adopt = 0;
+    int64_t hit_cut_tokens = 0;
+    /* Tokens of context held only by the cache, i.e. what eviction would free. Excludes blocks
+     * shared with a running sequence. Same token axis as the paged groups, so comparable with
+     * kv_tokens_used. */
     int64_t prefix_held_tokens = 0;
     float   linear_hit_rate = 0.0f;
     int64_t checkpoints_written = 0;
@@ -135,18 +116,16 @@ struct SchedMetrics {
     int64_t draft_refill_tokens = 0;
     float   draft_acceptance = 0.0f;
     int     draft_depth = 0;          /* what the controller would choose right now */
-    /* Per draft POSITION, so a cliff can be told from a decay: `reached` is how often every
-     * earlier position was accepted and this one was therefore evaluated, `accepted` how often it
-     * was then taken. Their ratio is the conditional hazard, which is the number that says what a
-     * deeper draft would actually buy. `draft_depth_seen` bounds how much of the arrays is real. */
+    /* Per draft position: `reached` counts verifies where every earlier position was accepted,
+     * `accepted` how often this one was then taken. Their ratio is the conditional acceptance,
+     * which says what a deeper draft would buy. `draft_depth_seen` bounds the valid entries. */
     enum { RAD_METRICS_MAX_SPEC = 64 };
     int     draft_depth_seen = 0;
     int64_t draft_pos_reached [RAD_METRICS_MAX_SPEC] = {};
     int64_t draft_pos_accepted[RAD_METRICS_MAX_SPEC] = {};
-    /* THE ADAPTIVE WINDOW (--draft-window adaptive, draft.h), all zero while it is off. The mean
-     * window it gives the sequences running now -- at one sequence, that sequence's window -- and
-     * the verifies by the window they carried, index = drafts verified, cumulative: the gauge says
-     * where the policy stands, the histogram where it has been. */
+    /* Adaptive window (--draft-window adaptive, draft.h); all zero while off. The gauge is the
+     * mean window over running sequences; the cumulative histogram counts verifies by window,
+     * index = drafts verified. */
     bool    draft_adaptive = false;
     float   draft_depth_adaptive = 0.0f;
     int64_t draft_verify_depth[RAD_METRICS_MAX_SPEC + 1] = {};
diff --git a/core/sched/scheduler.cpp b/core/sched/scheduler.cpp
index 9bca6b15..6f5d92d3 100644
--- a/core/sched/scheduler.cpp
+++ b/core/sched/scheduler.cpp
@@ -13,19 +13,22 @@
 
 namespace rad {
 
-/* Wall-clock microseconds on a monotonic base. Used only by the live request table -- the step
- * path measures with its own steady_clock points and never calls this. */
+/* Microseconds on the monotonic clock, for the live request table only; the step path keeps its
+ * own steady_clock points. */
 static int64_t mono_us() {
     return (int64_t)std::chrono::duration_cast(
                std::chrono::steady_clock::now().time_since_epoch()).count();
-
 }
+
+/* Reclaiming KV from the prefix cache for a request: at most kEvictRounds rounds of
+ * kEvictBlocks blocks each. Bounded, because an unbounded loop on the scheduler thread stalls the
+ * server silently; batched, so a large shortfall does not walk the LRU list block by block. */
+static constexpr int kEvictRounds = 256;
+static constexpr int kEvictBlocks = 256;
+
 /* ------------------------------------------------------------------ ordering */
-/* Priority first, arrival second, and arrival is what makes preemption fair without a special
- * case: a preempted request re-enters the queue carrying its ORIGINAL arrival number, which is
- * smaller than every request admitted after it, so it lands at the front of its priority class
- * rather than at the back of the queue. It has already been served once and its blocks were taken
- * from it; sending it to the back would be charging it twice. */
+/* Priority first, then arrival. A preempted request keeps its original arrival number, so it
+ * re-enters at the front of its priority class instead of the back. */
 bool Scheduler::ahead_of(int32_t a, int32_t b) const {
     const SchedReq& x = *reqs_[(size_t)a];
     const SchedReq& y = *reqs_[(size_t)b];
@@ -53,11 +56,9 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
     kv_ = kv;
     pc_ = pc;
 
-    /* The engine resolves this once and hands it over, because the prefix cache needs the
-     * checkpoint interval out of it before this runs. A caller that passes nothing (the tests)
-     * resolves its own -- harmless, it is a pure function of prog and cfg. What must not happen is
-     * two independent reads of the operator's RAW interval: the cache is given the resolved
-     * number, so there is one answer to "where does a chunk split". */
+    /* The engine resolves the geometry once, because the prefix cache needs its checkpoint
+     * interval first; a caller without one (tests) resolves its own from prog and cfg. Both
+     * must use the resolved interval, never the raw flag, so chunks split in one place. */
     if (geo) geo_ = *geo;
     else RAD_TRY(chunk_geometry_resolve(prog, cfg, &geo_));
 
@@ -69,27 +70,24 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
     has_linear_state_ = false;
     for (const auto& g : kvgeom_.g) if (!g.paged) has_linear_state_ = true;
 
-    /* A hit can only leave a drafter's own cache short where a PAGED group is not prefix-cached;
-     * see scheduler.h at hit_holes_draft_. With the cache off, cached_groups() is empty and this
-     * is true -- which costs nothing, because a run with no cache takes no hits and every
-     * sequence's first block pass sits at ctx_len 0 anyway. */
+    /* A hit can leave a drafter's own cache short only where a paged group is not prefix-cached
+     * (scheduler.h, hit_holes_draft_). With the cache off cached_groups() is empty and this is
+     * true, which costs nothing: no hits are taken, and every first block pass is at ctx_len 0. */
     {
-        /* PAGED AS THE CACHE COUNTS IT, which is KVGroupPlan::paged() and reaches here through
-         * block_tokens(). NOT kvgeom_'s `paged` flag: that one is also true for an empty
-         * placeholder group (0 layers, no plan), which a model is free to declare, so counting it
-         * overstates the paged groups and pins this predicate true. That is exactly the drift the
-         * comment in scheduler.h warns about. */
+        /* Paged as the cache counts it (KVGroupPlan::paged(), via block_tokens()), not kvgeom_'s
+         * `paged` flag, which is also true for an empty placeholder group and would pin this
+         * predicate true. */
         size_t n_paged = 0;
         for (size_t i = 0; i < kvgeom_.g.size(); ++i)
             if (kv->block_tokens((int32_t)i) > 0) ++n_paged;
         hit_holes_draft_ = pc->cached_groups().size() < n_paged;
         RAD_INFO("draft floor: %zu paged group(s), %zu prefix-cached -> a hit %s",
                  n_paged, pc->cached_groups().size(),
-                 hit_holes_draft_ ? "LEAVES a hole in a drafter's own KV" : "leaves no hole");
+                 hit_holes_draft_ ? "leaves a hole in a drafter's own KV" : "leaves no hole");
     }
-    /* THE TRUNK'S SHARE of that question: a paged group a TRUNK layer reads (a bound layer below
-     * the trunk's layer count — a drafter borrows from base_layer and above) that the cache does
-     * not index. Its hole is not repairable by recomputing the tail; see scheduler.h. */
+    /* The trunk's share: a paged group a trunk layer reads (a bound layer below the trunk's layer
+     * count; a drafter borrows from base_layer up) that the cache does not index. Recomputing the
+     * tail cannot repair that hole; see scheduler.h. */
     hit_holes_trunk_ = false;
     for (size_t i = 0; i < prog.kv_groups.size(); ++i) {
         if (kv->block_tokens((int32_t)i) <= 0) continue;
@@ -102,6 +100,13 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
     if (hit_holes_trunk_ && cfg.prefix_cache)
         RAD_INFO("prefix cache: a trunk layer's windowed group is not prefix-cached -- a hit "
                  "resumes from a window snapshot (a checkpoint slot) or re-prefills");
+    if (cfg.prefill_interleave > 0)
+        RAD_INFO("scheduler: --prefill-interleave %lld: after a prefill chunk that leaves its "
+                 "prompt unfinished while other sequences decode, the next %lld steps carry "
+                 "decode rows only and admit nothing", (long long)cfg.prefill_interleave,
+                 (long long)cfg.prefill_interleave);
+    interleave_left_ = 0;
+    held_prefill_ = 0;
     draft_refill_ = 0;
     if (cfg.n_spec > 0 && prog.drafter.kind == RAD_DRAFT_BLOCK && prog.drafter.window > 0 &&
         hit_holes_draft_) {
@@ -120,18 +125,11 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
 
     DraftController::Params dp;
     dp.max_depth = cfg.n_spec;
-    /* THE ADAPTIVE WINDOW (draft.h) prices a draft by what the step it adds to costs, measured.
-     * For a serial head that is a round of the head and a verify row. For a BLOCK drafter the
-     * block is proposed in one pass whatever is verified, but each verified draft is still a
-     * verify row -- and on a model whose verify streams weights per row, a MoE that reads the
-     * experts every row routes to, a row is not free: sixteen rows read ten times the experts one
-     * does. So a block drafter takes the same policy with its rounds fixed: each sequence verifies
-     * the first min(D, its stop) of the block, its stop from its own measured acceptance, and D
-     * from the measured step times. Deep where the text is predictable (code, JSON, greedy), a few
-     * drafts where it is not (prose at temperature 1, where a point-mass draft survives a position
-     * with probability p(x) and a fifteen-token chain dies after one or two). Prompt lookup runs
-     * no pass and keeps the fixed window, decided here, once, and said, because a flag that
-     * changes nothing reads exactly like a flag that made no difference. */
+    /* The adaptive window (draft.h) prices a draft by the measured cost of the step it adds to.
+     * A block drafter proposes its block in one pass, but each verified draft is still a verify
+     * row, which is not free on a MoE that reads each row's routed experts. So it takes the same
+     * policy with fixed rounds: each sequence verifies the first min(D, its stop) of the block.
+     * Prompt lookup runs no pass and keeps the fixed window; the outcome is logged either way. */
     if (cfg.draft_window == DraftWindow::Adaptive) {
         const RadDrafterDecl& dd = prog.drafter;
         if (cfg.n_spec <= 0)
@@ -154,16 +152,34 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
     draft_est_.reserve((size_t)cfg.max_seqs);
 
     RAD_TRY(builder_.init(prog, cfg, geo_, kvgeom_, ranks));
-    /* The builder's bound and not a second derivation of it: it is what the block tables were
-     * sized for, so it is the one number that says which positions exist. */
+    /* The builder's bound, not a second derivation: the block tables were sized for it. */
     ctx_limit_ = builder_.max_ctx();
+    /* The pool's own bound on one sequence, searched once (can_ever_fit is monotonic in the
+     * length): add_locked refuses a prompt past it. */
+    pool_tokens_ = -1;
+    pool_refusal_.clear();
+    if (const int64_t top = ctx_limit_ > 0 ? ctx_limit_ : ((int64_t)1 << 40);
+        !kv->can_ever_fit(top)) {
+        int64_t lo = 0, hi = top;
+        if (!kv->can_ever_fit(0)) hi = 0;
+        while (hi - lo > 1) {
+            const int64_t mid = lo + (hi - lo) / 2;
+            if (kv->can_ever_fit(mid)) lo = mid; else hi = mid;
+        }
+        pool_tokens_ = hi == 0 ? 0 : lo;
+        /* Worded for clients that compact a conversation on a context overflow by its message. */
+        pool_refusal_ = fmt("This model's maximum context length is %lld tokens, all the KV cache "
+                            "holds for one sequence: the prompt exceeds the available context "
+                            "size; shorten it or give the cache more room",
+                            (long long)pool_tokens_);
+    }
     n_deferred_ = 0;
     closed_ = false;
     closed_status_ = RAD_E_STATE;
 
-    /* Everything the step path touches is reserved here. A vector that grows during a step is an
-     * allocator call on the path this whole component exists to keep clear. */
+    /* Everything the step path touches is reserved here, so a step never calls the allocator. */
     plan_.e.reserve((size_t)cfg.max_seqs);
+    part_.reserve((size_t)cfg.max_seqs);
     running_.reserve((size_t)cfg.max_seqs);
     waiting_.reserve((size_t)cfg.max_seqs * 4 + 64);
     free_slots_.reserve((size_t)cfg.max_seqs);
@@ -196,10 +212,9 @@ int Scheduler::add(std::unique_ptr r) {
     return add_locked(std::move(r));
 }
 
-/* ONE LOCK FOR ALL OF THEM, so the step that admits the first finds every one waiting. Taken one
- * at a time, a step can begin between two of them and admit a prefix of the set, and which prefix
- * depends on thread timing -- so the batch a request's sequences decode in, and with it their
- * tie-level rounding, would vary between identical runs. */
+/* One lock for all of them, so the step that admits the first finds them all waiting. Otherwise a
+ * step could start between two adds and admit a timing-dependent subset, and the batch (and its
+ * tie-level rounding) would vary between identical runs. */
 void Scheduler::add_all(std::unique_ptr* rs, size_t n, int* rc) {
     std::lock_guard lk(mu_);
     for (size_t i = 0; i < n; ++i) rc[i] = add_locked(std::move(rs[i]));
@@ -209,20 +224,33 @@ int Scheduler::add_locked(std::unique_ptr r) {
     if (!r) return RAD_E_INVAL;
     if (r->prompt.empty()) return RAD_E_INVAL;
     if (by_id_.count(r->id)) return RAD_E_DUPLICATE;
-    /* AN EMBEDDING INPUT RUNS IN ONE STEP OR NOT AT ALL (Request::embed), so one longer than a
-     * step could never be admitted and would wait for good. */
+    /* An embedding input runs in one step or not at all (Request::embed); one longer than a step
+     * could never be admitted. */
     if (r->embed && (int64_t)r->prompt.size() > cfg_.max_tok) return RAD_E_INVAL;
-    /* A SCORED PROMPT names real vocabulary rows, and one step's decision is all it needs:
-     * drafts would be proposed for a continuation nobody reads. */
+    /* Nor could a prompt the KV pool cannot hold even alone: admission takes only what the pool
+     * holds, so it would wait at the head of the queue, and everything behind it, forever. The
+     * prompt is the least a request needs: its first token comes from the prefill's last row.
+     * RAD_E_FULL with the sink failed here, so the caller answers it as a context overflow. */
+    if (!kv_->can_ever_fit((int64_t)r->prompt.size())) {
+        RAD_WARN("request %llu refused: its %zu-token prompt is longer than the KV cache can hold "
+                 "for one sequence (%lld tokens)", (unsigned long long)r->id, r->prompt.size(),
+                 (long long)pool_tokens_);
+        server::sink_fail(r->sink, RAD_E_FULL,
+                          pool_refusal_.empty() ? "the prompt is longer than the KV cache can "
+                                                  "hold for one sequence"
+                                                : pool_refusal_.c_str());
+        return RAD_E_FULL;
+    }
+    /* A scored prompt names real vocabulary rows and needs one step's decision; drafts would be
+     * proposed for a continuation nobody reads. */
     if (r->token_scores) {
         if (r->embed || r->token_scores->tokens.empty()) return RAD_E_INVAL;
         for (int32_t t : r->token_scores->tokens)
             if (t < 0 || t >= prog_->meta.n_vocab) return RAD_E_INVAL;
         r->may_speculate = false;
     }
-    /* NO ENGINE BEHIND THE QUEUE ANY MORE. Accepting would leave the caller waiting on a step
-     * that is never coming, so the sink is failed here -- it is the one thing the caller is
-     * listening to -- and the refusal says why. */
+    /* The engine has stopped. Fail the sink, which is what the caller listens to, so it is not
+     * left waiting on a step that never comes. */
     if (closed_) {
         RAD_WARN("request %llu refused: %s", (unsigned long long)r->id, closed_reason_);
         server::sink_fail(r->sink, closed_status_, closed_reason_);
@@ -243,7 +271,7 @@ int Scheduler::add_locked(std::unique_ptr r) {
     s.card = -1;
     s.running = false;
     s.drafter_reset();
-    /* A NEW REQUEST'S TEXT, so a new estimate: the slot's last tenant was writing something else. */
+    /* A new request's text, so a new estimate. */
     s.adapt.depth = 0;
     s.adapt.held  = 0;
     s.sched_tokens = 0;
@@ -256,18 +284,17 @@ int Scheduler::add_locked(std::unique_ptr r) {
     s.hit_owed = false;
     s.req->state = ReqState::Waiting;
 
-    /* The output vector is the one thing the step path appends to, so its capacity is settled
-     * here, on the arrival thread, and never again. Bounded by what the context can still hold:
-     * max_tokens is the caller's number, and reserving it as given lets one request ask this
-     * thread for gigabytes it could never fill. */
+    /* The step path appends to `output`, so its capacity is settled here, on the arrival thread.
+     * Bounded by the context's remaining room: reserving a caller's max_tokens as given could ask
+     * for gigabytes. */
     int64_t out_cap = s.req->max_tokens > 0 ? (int64_t)s.req->max_tokens : 1;
     const int64_t ctx_room = ctx_limit_ - (int64_t)s.req->prompt.size();
     if (ctx_limit_ > 0 && out_cap > ctx_room) out_cap = ctx_room > 1 ? ctx_room : 1;
     s.req->output.reserve((size_t)out_cap + (size_t)RAD_SCHED_MAX_SPEC);
 
     by_id_[s.req->id] = slot;
-    /* Keep enough headroom that a step which preempts every running request cannot grow the
-     * queue's storage while it holds the lock. */
+    /* Enough headroom that a step preempting every running request does not grow the queue under
+     * the lock. */
     if (waiting_.capacity() < waiting_.size() + (size_t)cfg_.max_seqs + 1)
         waiting_.reserve(waiting_.size() + (size_t)cfg_.max_seqs + 1);
     queue_insert(waiting_, slot);
@@ -287,15 +314,11 @@ int Scheduler::set_draft(uint64_t id, const int32_t* tokens, int n) {
     SchedReq& s = *reqs_[(size_t)it->second];
     if (n < 0) return RAD_E_INVAL;
 
-    /* THE NEXT STEP ALREADY VERIFIES THESE. It was planned with the count the drafter issued, and
-     * the card already put the tokens in its batch; the host copy is what that step's commit
-     * emits the accepted ones from, so it takes exactly those, unclamped.
-     *
-     * UNDER THE ADAPTIVE WINDOW THE DRAFTER RAN AS MANY ROUNDS AS THE DEEPEST SEQUENCE WANTED,
-     * and expect_draft() already cut this one's count to its own window -- the card verifies the
-     * FIRST draft_next of the proposals, which are these. So a longer proposal is cut to that
-     * count here, against the number the step was planned with: the window itself may have moved
-     * at the commit in between, and the planned step is what these tokens are for. */
+    /* The step issued ahead already verifies these: it was planned with the drafter's count and
+     * the card has the tokens. The host copy is what its commit emits accepted tokens from, so it
+     * must match that count, unclamped. Under the adaptive window the rounds ran for the deepest
+     * sequence and expect_draft() cut this one's count to its window, so a longer proposal is cut
+     * to the planned count (the window may have moved at the commit since). */
     if (next_open_ && s.entry_next >= 0) {
         if (draft_.adaptive() && n > s.draft_next) n = s.draft_next;
         if (n != s.draft_next) {
@@ -310,10 +333,9 @@ int Scheduler::set_draft(uint64_t id, const int32_t* tokens, int n) {
         return RAD_OK;
     }
 
-    /* An ineligible request is given no proposal at all rather than a refusal: it decodes one
-     * token a step, exactly as it would on a server started without a drafter. See
-     * Request::may_speculate for the two reasons, and step() for the gate that catches the n-gram
-     * fallback as well. */
+    /* An ineligible request gets no proposal rather than a refusal, so it decodes one token a step
+     * as without a drafter. See Request::may_speculate, and step() for the gate that also catches
+     * the n-gram fallback. */
     if (!s.req->may_speculate) {
         s.n_draft = 0; s.req->n_draft = 0; s.req->draft = nullptr;
         return RAD_OK;
@@ -332,19 +354,10 @@ int Scheduler::set_draft(uint64_t id, const int32_t* tokens, int n) {
 /* ------------------------------------------------------------------ cancellation */
 /* ------------------------------------------------------------------ the sink
  *
- * THE TOKENS HAVE TO REACH THE CONNECTION, and this is where they leave the engine. `Request::sink`
- * is the server's per-request channel (core/server/sink.h) and it is a `void*` on Request precisely
- * so that core/sched does not depend on the server's types; the inline helpers there are the call
- * sites. A null sink is legal and means nobody is listening -- an offline or benchmark request.
- *
- * Appending to `Request::output` is not enough on its own: without a push the engine generates
- * correctly, step after step, while the HTTP thread waits in `Sink::wait()` until the client times
- * out. Every sink_* call -- push, finish, prompt stats, admission and drafts -- is made from this
- * file and nowhere else.
- *
- * A push returns false ONLY on overflow, and an overflowing sink has already failed the request --
- * a stream missing tokens in the middle is worse than one that stops and says so -- so the return
- * is what tells the scheduler to stop generating for it. */
+ * `Request::sink` is the server's per-request channel (core/server/sink.h), a `void*` so core/sched
+ * does not depend on server types; null means nobody is listening. Tokens reach the client only
+ * through a push, and every sink_* call is made from this file. A push returns false only on
+ * overflow, after the sink has already failed the request, so false means stop generating. */
 static server::Finish finish_of(ReqState st, const std::string& reason) {
     if (st == ReqState::Cancelled) return server::Finish::Cancelled;
     if (st == ReqState::Failed)    return server::Finish::Error;
@@ -352,29 +365,18 @@ static server::Finish finish_of(ReqState st, const std::string& reason) {
     return server::Finish::Stop;
 }
 
-/* THE CACHE IS NOT ALLOWED TO OWN THE WHOLE POOL, and that is a policy decision rather than an
- * optimisation. Every block the cache indexes is a block it holds a reference on, so a cache free
- * to grow without limit drives the pool to full occupancy and keeps it there: admission then pays
- * eviction on every chunk of every prefill, `kv_cache_usage_perc` pins at 1.0, the scheduler
- * spends its time reclaiming rather than running, and a long enough run of distinct large prompts
- * wedges.
+/* The cache may not own the whole pool: it holds a reference on every block it indexes, and an
+ * unbounded cache keeps the pool full, so admission pays eviction on every chunk and a run of
+ * distinct large prompts wedges. A fraction of the pool is kept free (what it protects is the
+ * ability to admit any sequence), trimmed after a publish rather than during admission.
  *
- * So a reserve is kept free. It is a fraction of the pool rather than a token count because the
- * thing being protected is the ability to admit ANY sequence, and how big that is depends on the
- * deployment. Trimming happens after a publish, off the step path, where the blocks were just
- * added -- not during admission, where the cost lands on a request that did nothing wrong.
- *
- * THE RESERVE IS NOT ALWAYS THE CACHE'S TO MEET. Live sequences count against it too, and once they
- * hold more than three quarters of the pool -- five or six agent sessions at 70K tokens each -- no
- * amount of trimming reaches it. Evicting in LRU order until it did would take everything on the
- * list: the entries running sequences share, which frees no block, and the conversation the
- * request being closed has just published, before its host copy can land -- so every agent's next
- * turn would re-prefill its whole context. The trim therefore asks the cache for the blocks it is
- * short and nothing more, and the cache gives only what frees a block without losing a
- * conversation (PrefixCache::trim). */
+ * Live sequences count against the reserve too and can put it out of reach; evicting in LRU
+ * order until it is met would drop shared entries (freeing nothing) and the conversation just
+ * published. So the trim asks only for the blocks it is short, and the cache gives only what
+ * frees a block without losing a conversation (PrefixCache::trim). */
 
-/* Drop every entry, in VRAM or off it -- IPrefixCache::reset, because an eviction does not
- * mean "forgotten" for an entry the idle tiers hold a copy of. */
+/* Drop every entry, in VRAM or not (IPrefixCache::reset): an eviction does not forget an entry
+ * the idle tiers hold a copy of. */
 int64_t Scheduler::reset_prefix_cache() {
     std::lock_guard lk(mu_);
     if (!pc_ || !cfg_.prefix_cache) return RAD_E_UNSUPPORTED;
@@ -391,30 +393,27 @@ void Scheduler::trim_prefix_cache() {
     const int64_t total = kv_->total_blocks(g);
     if (total <= 0) return;
     const int64_t reserve = total / 4;              /* a quarter of the pool stays free */
-    /* FREE AGAINST THE CARVE, not free_blocks(). On an elastic pool free_blocks() is bounded by
-     * the live mark, so a pool that has handed its unused top back reads as nearly full however
-     * little anything holds -- and the trim would then drain the whole cache to make room the pool
-     * can grow back into on demand. */
+    /* Free against the carve, not free_blocks(): on an elastic pool free_blocks() is bounded by
+     * the live mark, so a pool that returned its unused top would read as nearly full and the
+     * trim would drain the cache for room the pool can grow back into. */
     const int64_t short_by = reserve - (total - kv_->held_blocks(g));
     if (short_by > 0) (void)pc_->trim(short_by);
 }
 
 void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool defer_free,
                               bool publish, int status, const char* why) {
-    /* PUBLISH BEFORE FREEING. This is the only moment the sequence's whole prefix is both
-     * computed and still owned, and it is what makes the cache a cache rather than a permanently
-     * empty lookup: insert() takes its own KV references, so the blocks survive the free below.
-     * A cancelled or failed request is published too -- its prompt was computed either way, and
-     * an agent client that hangs up mid-answer is exactly who asks for that prefix again. */
+    /* Publish before freeing: this is the only moment the whole prefix is both computed and still
+     * owned. insert() takes its own KV references, so the blocks survive the free below. Cancelled
+     * and failed requests are published too; their prompts were computed, and a client that hangs
+     * up mid-answer is likely to ask for that prefix again. */
     if (publish && cfg_.prefix_cache && pc_ && kv_->has_sequence(s.req->id) &&
         s.req->n_computed > 0) {
         const std::vector& cg = pc_->cached_groups();
         pub_blocks_.assign(cg.size(), {});
         bool ok = !cg.empty();
         for (size_t i = 0; i < cg.size(); ++i) {
-            /* A rebased table does not describe the prefix from position zero, so it cannot be
-             * published. cached_groups() already excludes windowed groups, which is where a
-             * moving floor comes from; this is the belt to that. */
+            /* A rebased table does not describe the prefix from position 0, so it cannot be
+             * published. cached_groups() already excludes windowed groups; this is a backstop. */
             if (kv_->first_block_pos(s.req->id, cg[i]) != 0) { ok = false; break; }
             pub_blocks_[i] = kv_->block_table(s.req->id, cg[i]);
         }
@@ -428,8 +427,8 @@ void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool
     }
 
     if (cfg_.prefix_cache && pc_) pc_->release(*s.req);
-    /* What the draft head did on this text is now part of what the next text starts from --
-     * once: the estimate is marked unstarted, so a second close of the same request adds nothing. */
+    /* Fold what the draft head did on this text into the next text's starting estimate, once:
+     * marking it unstarted makes a second close add nothing. */
     if (draft_.adaptive()) {
         draft_.adapt_retire(s.adapt);
         s.adapt.depth = 0;
@@ -439,9 +438,9 @@ void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool
         if (!s.pending_free) ++n_deferred_;
         s.pending_free = true;
     } else if (kv_->has_sequence(s.req->id)) {
-        /* A preempted request has already had its blocks taken but the manager still knows the
-         * sequence, and it may still own a state slot. Asking first is what keeps this from
-         * depending on free_sequence() being idempotent. */
+        /* A preempted request has had its blocks taken, but the manager may still know the
+         * sequence and a state slot; asking first avoids relying on free_sequence() being
+         * idempotent. */
         kv_->free_sequence(s.req->id);
     }
     if (!defer_free) drop_card(s);
@@ -452,11 +451,25 @@ void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool
     queue_erase(waiting_, s.slot);
     s.n_draft = 0;
 
-    /* Terminal, and idempotent on the sink's side: the first call wins, so a cancel racing a
-     * natural stop does not produce two finish reasons. This is the last thing the producer does
-     * to the sink, and the HTTP thread is waiting on exactly it. */
+    /* Terminal. The sink keeps the first finish, so a cancel racing a natural stop yields one
+     * reason. This is the producer's last touch of the sink, which the HTTP thread waits on. */
     if (st == ReqState::Failed && status < 0) server::sink_fail(s.req->sink, status, why);
     else server::sink_finish(s.req->sink, finish_of(st, s.req->finish_reason));
+
+    if (st == ReqState::Failed)         ++m_.failed;
+    else if (st == ReqState::Cancelled) ++m_.cancelled;
+    else                                ++m_.finished;
+    completed_.push_back(s.req->id);
+}
+
+/* Reserve a checkpoint slot for the state at `pos`, written after the entry's row `tok`. A
+ * refusal leaves the entry without one. */
+void Scheduler::reserve_ckpt(StepEntry& e, const Request& r, int64_t pos, int32_t tok) {
+    int32_t cs = -1;
+    if (pc_->reserve_checkpoint(r, pos, &cs) < 0 || cs < 0) return;
+    e.ckpt_tok = tok;
+    e.ckpt_slot = cs;
+    ++m_.checkpoints_written;
 }
 
 int Scheduler::cancel(uint64_t id) {
@@ -467,24 +480,10 @@ int Scheduler::cancel(uint64_t id) {
     if (s.req->state == ReqState::Finished || s.req->state == ReqState::Cancelled)
         return RAD_OK;
 
-    /* Blocks go back NOW, not when the step that would have finished this request runs. A
-     * cancelled request that keeps its pool share until completion is a pool that shrinks under
-     * exactly the load that generates cancellations (spec §14).
-     *
-     * The one exception is a request whose tokens are in the step the device is still executing.
-     * Its blocks are released at commit instead -- one step later, not one request later. Handing
-     * a live block to a new sequence mid-step is a race, and it is the kind that presents as a
-     * model quality problem rather than as a crash.
-     *
-     * AND A DRAFTER'S SNAPSHOT IS THE OTHER. The drafter builds its passes one at a time after
-     * commit, releasing this lock between them, so a cancel can land after one pass was built
-     * and before the next. Freeing then leaves the next pass naming a sequence with no blocks:
-     * its block-table row is all -1 while its length is not, and attention reads block -1. The
-     * blocks are released once the drafter is done with the sequence (sweep_deferred). */
+    /* Blocks go back now (spec §14), unless a step in flight or a drafter snapshot still names
+     * the request; then commit or sweep_deferred releases them (SchedReq::pending_free). */
     const bool in_flight = in_step(s) || block_holds(id);
     close_request(s, ReqState::Cancelled, "cancelled", in_flight);
-    ++m_.cancelled;
-    completed_.push_back(id);
     return RAD_OK;
 }
 
@@ -493,9 +492,8 @@ void Scheduler::take_completed(std::vector* out) {
     out->clear();
     std::lock_guard lk(mu_);
     if (!next_open_) { out->swap(completed_); return; }
-    /* A REQUEST THE NEXT STEP STILL CARRIES IS HELD BACK. That step's sampler is staged for it
-     * after this one commits, so its sampler state has to outlive the finish by one step; it is
-     * handed out once the step that carries it has committed. */
+    /* A request the next step still carries is held back: that step's sampler is staged for it
+     * after this one commits, so its sampler state must outlive the finish by one step. */
     size_t keep = 0;
     for (uint64_t id : completed_) {
         auto it = by_id_.find(id);
@@ -546,8 +544,8 @@ void Scheduler::sweep_deferred() {
         if (in_step(s)) continue;
         if (block_holds(s.req->id)) continue;
         if (s.reap_pending) { release_locked(s); continue; }
-        /* A free deferred on a drafter snapshot, for a request nobody has reaped yet. The Request
-         * stays until the reap; only the blocks go back. */
+        /* A free deferred on a drafter snapshot, for a request not yet reaped: only the blocks
+         * go back. */
         free_kv(s);
         s.pending_free = false;
         --n_deferred_;
@@ -577,8 +575,6 @@ void Scheduler::shutdown(const char* reason, int status) {
         if (!s.req) continue;
         close_request(s, ReqState::Failed, closed_reason_, /*defer_free=*/false,
                       /*publish=*/false, closed_status_, closed_reason_);
-        ++m_.failed;
-        completed_.push_back(s.req->id);
     }
     /* Nothing will commit again, so no entry of the last step still owns its slot. */
     step_open_ = false;
@@ -598,23 +594,9 @@ int Scheduler::reap(uint64_t id) {
     if (s.req->state == ReqState::Running || s.req->state == ReqState::Waiting ||
         s.req->state == ReqState::Preempted)
         return RAD_E_STATE;
-    /* NOT WHILE ANYTHING STILL POINTS AT THE SLOT, and two things can. The server reaps as soon as
-     * the sink is finished, and cancel() finishes the sink at once, so a client that hangs up
-     * mid-generation gets here at an arbitrary point in the step loop.
-     *
-     *   - a StepEntry, if the device is still running the step this request is in. Destroying the
-     *     Request there segfaults commit() on `r.state`; returning the slot there is worse,
-     *     because a request admitted before the commit lands would be handed the entry and the
-     *     tokens.
-     *   - the DRAFTER'S SNAPSHOT. block_begin takes it under the lock and block_context,
-     *     block_query and block_end read it again after releasing and retaking the lock; a
-     *     Request freed in that window leaves BatchBuilder::build reading tokens off freed
-     *     memory. Keeping it alive rather than dropping the row is what
-     *     preserves the drafter's row mapping -- the engine already sized its readback from
-     *     block_begin's answer, so a query pass with one fewer row would attribute one
-     *     sequence's drafts to another.
-     *
-     * Both are the same one-step window `pending_free` covers, and both close the same way. */
+    /* Not while a step in flight or a drafter snapshot still points at the slot
+     * (SchedReq::reap_pending). For a drafter snapshot, keeping the Request alive rather than
+     * dropping the row also preserves the row mapping the engine sized its readback from. */
     if (in_step(s) || block_holds(id)) {
         if (!s.reap_pending) ++n_deferred_;
         s.reap_pending = true;
@@ -634,12 +616,7 @@ int Scheduler::queue_snapshot(uint64_t* out, int max) const {
     return n;
 }
 
-
-/* WHAT EVERY REQUEST IS DOING RIGHT NOW. Copied out under the step lock rather than handed out as
- * pointers: a caller holding a SchedReq* across a step is holding one that commit() may reap.
- *
- * Oldest first. A dashboard's reader is looking for the one that is stuck, and the one that is
- * stuck is the one that has been here longest. */
+/* Copied out under the step lock rather than handed out as pointers; see ReqStat. */
 int Scheduler::requests(ReqStat* out, int max) const {
     std::lock_guard lk(mu_);
     return requests_locked(out, max);
@@ -665,13 +642,10 @@ int Scheduler::requests_locked(ReqStat* out, int max) const {
         o.output_tokens   = (int64_t)r.output.size();
         o.max_tokens      = r.max_tokens;
         o.ctx_tokens      = s.seq_len();
-        /* BLOCKS ADD UP AND TOKENS DO NOT. Each paged group was carved its own blocks, so a count
-         * of them is a sum; but the paged groups SHARE ONE TOKEN AXIS -- one token of context
-         * takes a slot in every one of them -- so summing their tokens reports a request holding
-         * as many times its own context as there are paged groups. Against a pool capacity that
-         * is correctly one group's, two 100K requests then read as 95% of a pool that is 72%
-         * full. The token figure is the largest group's, which is the context the request is
-         * holding, and it is comparable with SchedMetrics::kv_tokens_used by construction. */
+        /* Blocks add up across paged groups, tokens do not: the groups share one token axis, so
+         * summing tokens would count the context once per group against a pool capacity that is
+         * one group's. The token figure is the largest group's, comparable with
+         * SchedMetrics::kv_tokens_used. */
         o.kv_blocks = o.kv_tokens = 0;
         for (int32_t g = 0; g < n_groups; ++g) {
             const int64_t bt = kv_->block_tokens(g);
@@ -684,8 +658,8 @@ int Scheduler::requests_locked(ReqStat* out, int max) const {
         o.slot            = s.slot;
         o.age_s           = (double)(now - s.arrived_us) / 1e6;
         o.ttft_s          = s.first_tok_us ? (double)(s.first_tok_us - s.arrived_us) / 1e6 : -1.0;
-        /* Since its FIRST token, not since admission: a request that waited thirty seconds in the
-         * queue did not decode slowly, and dividing by the wait would say it did. */
+        /* Since the first token, not admission, so time spent queued does not read as slow
+         * decode. */
         const double dec = s.first_tok_us ? (double)(now - s.first_tok_us) / 1e6 : 0.0;
         o.decode_tps      = dec > 1e-3 ? (double)r.output.size() / dec : 0.0;
     }
@@ -694,28 +668,15 @@ int Scheduler::requests_locked(ReqStat* out, int max) const {
 }
 
 /* ------------------------------------------------------------------ drafting */
-/* PROMPT-LOOKUP DRAFTING, and it needs no second model. Take the last few committed tokens of a
- * sequence, find where that pattern last occurred in the SAME sequence, and propose whatever
- * followed it. On the workloads this engine is for -- a coder model quoting the file it was given,
- * a model rewriting a diff, JSON with repeated keys -- that guess is right often enough to pay,
- * and when it is wrong the verify step still emits the target's own token, so it can only cost
- * bandwidth. It is here rather than behind the drafter plugin interface because it is not a model:
- * there is nothing to load, nothing to place, and no second forward pass.
+/* Prompt-lookup drafting: find where the last few committed tokens last occurred in the same
+ * sequence and propose what followed. On code, diffs and JSON it is right often enough to pay,
+ * and a wrong guess costs only bandwidth, since the verify still emits the target's token. Built
+ * in rather than a plugin because there is no model to load and no extra forward pass.
  *
- * Longest pattern first: a longer match is a stronger prediction, and dropping to a shorter one
- * only when the longer finds nothing is what keeps the acceptance rate from collapsing on common
- * bigrams. Most recent occurrence first, for the same reason.
- *
- * A draft head, when one is declared, replaces this by calling set_draft() before step() -- which
- * is why this only fills a proposal that is still empty. */
+ * Longest pattern and most recent occurrence first: a longer match predicts better, and falling
+ * back to shorter ones only on a miss keeps common bigrams from dragging acceptance down. A
+ * declared draft head calls set_draft() before step(), so this only fills an empty proposal. */
 int Scheduler::draft_ngram(SchedReq& s, int depth) const {
-    /* RADIANCE_NO_DRAFT separates the two halves of speculation. With it set the deployment is
-     * still speculative -- the state pool is laid out for it and the linear kernels take the
-     * path that defers the state -- but no step ever carries a draft, so every step is an
-     * ordinary one-token decode and the output must match a non-speculative run exactly. It
-     * answers 'is the deferred state right' without 'is the rollback right' on top of it. */
-    static const bool none = [] { const char* e = getenv("RADIANCE_NO_DRAFT"); return e && *e == '1'; }();
-    if (none) return 0;
     if (depth <= 0 || !s.req) return 0;
     const Request& r = *s.req;
     const int64_t np = (int64_t)r.prompt.size(), no = (int64_t)r.output.size();
@@ -739,14 +700,12 @@ int Scheduler::draft_ngram(SchedReq& s, int depth) const {
 }
 
 /* ------------------------------------------------------------------ chunking */
-/* A prefill chunk splits at the linear-state checkpoint interval so that a checkpoint is always
- * WRITTEN. vLLM writes one only when a scheduler step happens to end on a boundary, which is why
- * a checkpoint landing in request-unique tokens silently drops caching to zero (spec §7.3).
+/* A prefill chunk splits at the linear-state checkpoint interval so a checkpoint is always
+ * written (spec §7.3; see scheduler.h).
  *
- * The order of the two clamps matters. The checkpoint clamp comes first because the interval is a
- * multiple of the quantum, so a chunk clamped to an interval is already quantum-aligned and the
- * second clamp is a no-op on it. Reversing them would round a chunk PAST the checkpoint down and
- * then miss the boundary, which is the exact failure this is written to avoid. */
+ * The checkpoint clamp comes before the quantum clamp. The interval is a multiple of the quantum,
+ * so a chunk clamped to it is already aligned; in the other order a chunk past the checkpoint
+ * would be rounded down and miss the boundary. */
 int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budget,
                               int64_t* checkpoint_pos, int64_t keep_at) const {
     if (checkpoint_pos) *checkpoint_pos = -1;
@@ -759,25 +718,42 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg
         const int64_t I = geo_.checkpoint_interval;
         int64_t next = ((n_computed / I) + 1) * I;      /* strictly after n_computed */
         if (geo_.window_ckpt) next = INT64_MAX;          /* a window snapshot: the tail only */
-        if (n_computed + want > next) want = next - n_computed;
-        if (n_computed + want == next) {
-            if (checkpoint_pos) *checkpoint_pos = next;
+        /* A span (ChunkGeometry::span) starts only on an interval boundary past the first
+         * interval, and its chunk is the span's intervals in a row, each the piece a span of 1
+         * makes a chunk of its own. Not from a prompt's start: the first interval may be served on
+         * another path (QSA's dense attention below its exactness bound). Not from a tail
+         * checkpoint: the pieces after it would no longer start on the interval. A chunk the
+         * budget cuts short of the span's end steps back to the last boundary it crosses. */
+        int64_t far = next;
+        if (geo_.span > 1 && span_now_ && n_computed >= I && n_computed % I == 0)
+            far = n_computed + geo_.span * I;
+        if (n_computed + want > far)
+            want = far - n_computed;
+        else if (n_computed + want > next && n_computed + want < n_target)
+            want = (n_computed + want) / I * I - n_computed;
+        if (!geo_.window_ckpt && (n_computed + want) % I == 0) {
+            if (checkpoint_pos) *checkpoint_pos = n_computed + want;
         } else if (n_computed + want == n_target) {
-            /* AND ONE AT THE TAIL OF THE PROMPT. The next turn of a conversation is this prompt
-             * with more on the end, and it resumes from the deepest snapshot under its hit -- on
-             * the interval alone that is up to an interval short of where this prompt ended, and
-             * every one of those tokens is prefilled again on every turn. The last quantum
-             * boundary is as far as a chunk may end short of the target, so the final chunk is
-             * split there and the remainder, under a quantum, runs as the next step's chunk
-             * (tail_checkpoint says where it is worth that step). */
+            /* Also one at the prompt's tail. The next turn resumes from the deepest snapshot
+             * under its hit, which on the interval alone can be nearly an interval short of this
+             * prompt's end, re-prefilled every turn. The final chunk splits at the last quantum
+             * boundary, and the remainder (under a quantum) runs as the next step's chunk
+             * (tail_checkpoint decides when that is worth it). */
             const int64_t tail = tail_checkpoint(n_target);
             if (tail > n_computed) {
                 want = tail - n_computed;
                 if (checkpoint_pos) *checkpoint_pos = tail;
+            } else if (n_computed + want > next) {
+                /* A spanned last chunk with no tail checkpoint still ends on the last boundary it
+                 * crosses, where a span of 1 writes the prompt's deepest checkpoint, and the rest
+                 * (under a quarter interval) is the next chunk; otherwise the next turn would
+                 * resume up to an interval earlier. */
+                want = (n_computed + want) / I * I - n_computed;
+                if (checkpoint_pos) *checkpoint_pos = n_computed + want;
             }
         }
-        /* AND ONE WHERE THE REQUEST ASKED (Request::checkpoint_at), on its quantum: the end of a
-         * prefix other requests are about to start from. Same split as the interval's. */
+        /* And one where the request asked (Request::checkpoint_at), on its quantum: the end of a
+         * prefix other requests are about to start from. */
         const int64_t keep = keep_at / geo_.quantum * geo_.quantum;
         if (keep > n_computed && keep <= n_computed + want && keep <= n_target) {
             want = keep - n_computed;
@@ -786,10 +762,9 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg
     }
 
     if (want < remaining) {
-        /* A non-final chunk has to end on a quantum boundary measured from the SEQUENCE origin,
-         * not from the start of the step, or the next chunk hands the linear kernel a partial
-         * tile and the attention kernel a partial block. The final chunk of a request is allowed
-         * to be short: that is the accepted cost of owning the boundaries. */
+        /* A non-final chunk must end on a quantum boundary measured from the sequence origin,
+         * or the next chunk hands the linear kernel a partial tile and attention a partial
+         * block. The final chunk may be short. */
         const int64_t Q = geo_.quantum;
         int64_t end = n_computed + want;
         int64_t aligned = end / Q * Q;
@@ -805,18 +780,17 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg
     return want;
 }
 
-/* THE TAIL CHECKPOINT OF A PROMPT OF `target` TOKENS, or -1: its last quantum boundary, past the
- * first interval -- a shorter prompt is cheap to prefill again -- and only where it buys a quarter
- * of an interval or more over the interval checkpoint below it, which is worth the extra step. */
+/* The tail checkpoint of a `target`-token prompt, or -1: its last quantum boundary, only past the
+ * first interval (a shorter prompt is cheap to redo) and only where it gains at least a quarter
+ * interval over the interval checkpoint below it, which pays for the extra step. */
 int64_t Scheduler::tail_checkpoint(int64_t target) const {
     const int64_t I = geo_.checkpoint_interval, Q = geo_.quantum;
     if (I <= 0 || Q <= 0) return -1;
     const int64_t tail = target / Q * Q;
-    /* A WINDOW SNAPSHOT is taken at the tail of any prompt of an interval or more. */
-    /* A block short of the end: the next turn re-renders the last few tokens (a generation
-     * prompt it replaces with the reply), and a snapshot past where the two renderings part is
-     * one no hit can reach -- measured: every prompt whose length left fewer than ~8 tokens in
-     * its last block missed. */
+    /* A window snapshot is taken at the tail of any prompt of an interval or more, a block short
+     * of the end: the next turn re-renders the last few tokens (the generation prompt is replaced
+     * by the reply), and a snapshot past where the two renderings diverge is unreachable. Prompts
+     * that left fewer than ~8 tokens in their last block always missed. */
     if (geo_.window_ckpt) {
         const int64_t t = (target - std::max(Q, 16)) / Q * Q;
         return t >= I ? t : -1;
@@ -825,6 +799,14 @@ int64_t Scheduler::tail_checkpoint(int64_t target) const {
 }
 
 /* ------------------------------------------------------------------ a prefill sharing a step */
+void Scheduler::set_span_min(int64_t tokens) {
+    span_min_ = tokens > 0 ? tokens : 0;
+    if (span_min_ > 0 && geo_.span > 1)
+        RAD_INFO("scheduler: --prefill-span: a prefill spans when it is %lld tokens or longer -- "
+                 "routed experts are read from host memory, and the arena a spanned step takes is "
+                 "room they lose for it", (long long)span_min_);
+}
+
 void Scheduler::set_stage_rows(int64_t rows) {
     stage_rows_ = rows > 0 ? rows : 0;
     const int64_t n = cfg_.busy_prefill_chunk;
@@ -851,45 +833,34 @@ void Scheduler::set_stage_rows(int64_t rows) {
              stage_rows_ > 0 ? " (the prefill stager's smallest pass)" : "");
 }
 
-/* HOW MUCH OF THE STEP A PREFILL CHUNK MAY TAKE WHEN OTHER WORK WANTS IN.
+/* How much of the step a prefill chunk may take when other work wants in.
  *
- * Without a cap the running loop hands a prefill row every token the step has left
- * (plan_chunk(..., budget)). On a step budget of a few thousand tokens and a prompt of a few
- * hundred thousand, that is every step for a minute or more, and in that time a decode row behind
- * the prefill in running_ gets nothing (`want > budget` -> break) and admission never runs
- * (`budget > 0`): a mostly-cached turn that needs a few hundred tokens waits for the whole of
- * somebody else's prefill. The cap leaves `reserve` -- the rows behind it and a share for
- * admission, worked out by step() -- and never goes under the floor.
+ * Uncapped, a prefill row takes every token the step has left, and on a prompt of a few hundred
+ * thousand tokens that lasts a minute or more, during which decode rows behind it get nothing and
+ * admission never runs. The cap leaves `reserve` (computed by step()) and never goes under the
+ * floor: the smallest step the prefill stager overlaps, rounded down to the quantum, or one
+ * quantum with no stager. A smaller step reads every routed layer's pooled experts
+ * synchronously, which costs a long prefill far more than sharing saves.
  *
- * THE FLOOR is the smallest step the prefill stager overlaps (rounded down to the quantum: the
- * rows the chunk shares the step with make up the difference). A step under it reads every
- * routed layer's pooled experts synchronously, and on an expert-tiered placement that costs a
- * long prefill far more than the shared step saves -- a budget set one token under the threshold
- * measured -65 % prefill (#61). With no stager the floor is one quantum.
- *
- * AND THE REST OF THE INTERVAL STAYS ABOVE IT. A chunk ends on the checkpoint interval
- * (plan_chunk), so a chunk held short of the boundary leaves a remainder that is the next step's
- * whole chunk. Held to `budget - reserve`, that remainder is the size of the reserve -- a few
- * hundred tokens, under the floor, and the slowest step of all. When the cap would leave such a
- * remainder the interval is split into two chunks each at or above the floor instead: two staged
- * steps, each with room for the rest of the step's work. */
+ * Chunks end on the checkpoint interval (plan_chunk), so a chunk held short leaves a remainder,
+ * about the size of the reserve, as the next step's whole chunk. When that would be under the
+ * floor, the interval is split into two chunks at or above the floor instead. */
 int64_t Scheduler::busy_cap(int64_t n_computed, int64_t n_target, int64_t budget,
                             int64_t reserve, bool shared, bool rows_only) const {
     const int64_t mode = cfg_.busy_prefill_chunk;
     if (mode == 0 || budget <= 0) return budget;
-    /* auto holds a chunk back only for work that would otherwise get NOTHING this step -- rows
-     * behind it, a request waiting to start. Rows already planned ahead of it are in the step
-     * whatever the chunk takes, so auto leaves the chunk alone for them (it was never what
-     * starved them). An explicit N is the operator trading prefill speed for the latency of every
-     * other row, so it applies whenever the chunk shares the step at all. */
+    /* Auto holds a chunk back only for work that would otherwise get nothing this step: rows
+     * behind it, or a request waiting to start. Rows planned ahead of it are in the step anyway.
+     * An explicit N trades prefill speed for every other row's latency, so it applies whenever
+     * the chunk shares the step. */
     if (reserve <= 0 && !(mode > 0 && shared)) return budget;
     reserve = std::max(reserve, 0);
     const int64_t Q = std::max(geo_.quantum, 1);
 
     int64_t cap = budget - reserve;
     if (mode > 0) {
-        /* The operator's number. No floor: --busy-prefill-chunk N under the stager's step is a
-         * choice set_stage_rows warns about, not one this overrides. */
+        /* The operator's number, with no floor; set_stage_rows warns when it is under the
+         * stager's step. */
         cap = std::min(cap, mode);
     } else {
         const int64_t floor = std::max(Q, stage_rows_ / Q * Q);
@@ -900,19 +871,15 @@ int64_t Scheduler::busy_cap(int64_t n_computed, int64_t n_target, int64_t budget
             const int64_t I = geo_.checkpoint_interval;
             span = std::min(span, ((n_computed / I) + 1) * I - n_computed);
         }
-        /* ...but not for decode rows alone. Their reserve is a few tokens, the chunk ends a
-         * quantum short of the boundary and the next step finishes the interval: the same pair of
-         * steps a prefill already runs whenever decode rows are planned AHEAD of it, so it adds
-         * no step shape the engine does not already pay for. Halving instead would hold a long
-         * prompt to half-interval chunks for as long as any request decodes behind it -- measured
-         * as the larger cost (NOTES: prefill-share run 2). The split is for a share (a request
-         * waiting to start, another prefill), which lasts a step or two. */
+        /* ...but not for decode rows alone: their reserve is a few tokens, so the chunk ends a
+         * quantum short and the next step finishes the interval, a step pair a prefill already
+         * runs when decode rows are ahead of it. Halving would hold a long prompt to
+         * half-interval chunks while anything decodes behind it, which costs more. The split is
+         * for a share (a waiting request, another prefill), which lasts a step or two. */
         if (!rows_only && cap < span && span - cap < floor && span - floor >= floor)
             cap = span - floor;
     }
-    cap = std::min(cap, budget);
-    cap = std::max(cap, Q);
-    return std::min(cap, budget);
+    return std::min(std::max(cap, Q), budget);
 }
 
 /* ------------------------------------------------------------------ preemption */
@@ -921,9 +888,8 @@ void Scheduler::preempt_back() {
     SchedReq& s = *reqs_[(size_t)slot];
     Request& r = *s.req;
 
-    /* Preemption by RECOMPUTE: the blocks go back to the pool and the request restarts from zero.
-     * Its generated output is simply the tail of its token sequence, so recompute needs no special
-     * path -- it re-prefills prompt ++ output through the same chunker. */
+    /* Preemption by recompute: the blocks go back and the request restarts from zero. Its output
+     * is the tail of its token sequence, so it simply re-prefills prompt ++ output. */
     kv_->preempt(r.id);
     drop_card(s);
     r.n_computed = 0;
@@ -931,10 +897,10 @@ void Scheduler::preempt_back() {
     r.n_accepted = 0;
     r.state = ReqState::Preempted;
     s.drafter_reset();
-    /* AND THE REQUEST'S OWN COPY OF THE WINDOW. The sampler stages 1 + Request::n_draft rows for
-     * a request (Sampler::build_step), and a drafter may have set it for the step this preemption
-     * just took away. Left standing, the recompute's first sampled step stages rows its batch does
-     * not have, and every request after it in the step samples another's logits row. */
+    /* Also clear the request's own window. The sampler stages 1 + Request::n_draft rows
+     * (Sampler::build_step), and a drafter may have set it for the step this preemption removed;
+     * left standing, the recompute's first sampled step stages rows its batch lacks and every
+     * later request in the step samples another's logits row. */
     r.n_draft = 0;
     r.draft = nullptr;
     s.running = false;
@@ -945,34 +911,33 @@ void Scheduler::preempt_back() {
 }
 
 /* ------------------------------------------------------------------ admission */
-/* Admission checks the KV budget BEFORE a request enters running. A request admitted without the
- * blocks to run it is a request that will be preempted on its first step, which costs a full
- * recompute for nothing. */
+/* Admission checks the KV budget before a request enters running; a request admitted without the
+ * blocks to run would be preempted on its first step, a full recompute for nothing. */
 int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
     Request& r = *s.req;
 
     if (!kv_->has_sequence(r.id)) RAD_TRY(kv_->add_sequence(r.id));
 
-    /* A FRESH ATTEMPT: nothing looked up yet, nothing counted yet. A request that kept an
-     * earlier attempt's hit (n_computed > 0) keeps what that attempt found as well. */
+    /* A fresh attempt: nothing looked up or counted yet. A request that kept an earlier
+     * attempt's hit (n_computed > 0) keeps what it found. */
     if (r.n_computed == 0) {
         s.ckpt_src = -1;
         s.hit_attn = 0;
         s.hit_owed = true;
+        s.hit_cut = SchedReq::HitCut::None;
     }
 
-    /* WHAT NO HIT CAN CHANGE IS ASKED FIRST: a free sequence and a budget that can take a chunk.
-     * A restore copies the whole context back, and an admission refused after it would give that
-     * hit back and copy it again on the next attempt. */
+    /* Check what no hit can change first (a free card index, a budget that fits a chunk): a
+     * restore copies the whole context back, and an admission refused after it would repeat the
+     * copy on the next attempt. */
     if (s.card < 0 && free_cards_.empty()) return RAD_E_FULL;
     if (budget < std::max(geo_.quantum, 1) && budget < s.seq_len() - r.n_computed)
         return RAD_E_FULL;
 
     if (r.n_computed == 0 && cfg_.prefix_cache) {
-        /* BEFORE the lookup, because the lookup stops at the first block the tiers hold -- an
-         * honest shorter hit, but a shorter one. This is where a cold session gets its
-         * context back instead of re-prefilling it: it costs a copy, and the alternative
-         * costs a prefill. */
+        /* Restore before the lookup, which stops at the first block the tiers hold. This is
+         * where a cold session gets its context back for the cost of a copy instead of a
+         * prefill. */
         pc_->restore(r);
         HitCap cap;
         if (draft_refill_ > 0) {
@@ -986,77 +951,71 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
         }
         int32_t reuse = h.n_attn_tokens;
         if (geo_.checkpoints() && h.n_linear_tokens < reuse) {
-            /* A hit landing between checkpoints reuses the attention blocks and must replay the
-             * linear layers forward from the last checkpoint (§7.3). RadBatch carries ONE query
-             * length for every group, so this build cannot run the linear layers over a longer
-             * range than the attention layers: that would need per-group q_lens on
-             * RadKVGroupBatch. Without them, the conservative and correct answer is to recompute
-             * from the checkpoint. */
+            /* A hit between checkpoints reuses the attention blocks but must replay the linear
+             * layers from the last checkpoint (§7.3). RadBatch carries one query length for all
+             * groups (per-group q_lens on RadKVGroupBatch would be needed), so recompute from
+             * the checkpoint instead. */
             reuse = h.n_linear_tokens;
         }
         int32_t last = (int32_t)r.prompt.size() - 1;   /* one token must remain to produce logits */
         if (reuse > last) reuse = last;
         if (reuse < 0) reuse = 0;
 
-        /* A HIT ON A HYBRID MODEL IS ONLY LEGAL BECAUSE OF THE CHECKPOINT. Reuse skips recomputing
-         * the prefix, which the adopted blocks cover for the paged attention groups and NOTHING
-         * covers for a recurrent group -- its state lives in a per-sequence slot. So a hit that
-         * skips tokens must also restore that state, which is what `ckpt_src` carries into the
-         * entry below and what KVManager::checkpoint_restore performs.
-         *
-         * Refusing to reuse without one is therefore not conservatism, it is the only correct
-         * answer: `reuse` is already clamped to `h.n_linear_tokens` above, so a hit that found no
-         * valid checkpoint clamps to zero on its own. What must never happen is reuse > 0 with no
-         * snapshot to resume from -- that is every recurrent layer continuing from whatever the
-         * slot last held, and it reads as fluent text rather than as a failure. */
+        /* A hit on a hybrid model needs a checkpoint. The adopted blocks cover the paged
+         * attention groups, but nothing covers a recurrent group, whose state lives in a
+         * per-sequence slot; skipping tokens also requires restoring that state (`ckpt_src`,
+         * then KVManager::checkpoint_restore). `reuse` is already clamped to h.n_linear_tokens;
+         * this guarantees reuse > 0 never happens without a snapshot, which would continue every
+         * recurrent layer from stale state and produce fluent but wrong text. */
         if (reuse > 0 && has_linear_state_ && h.checkpoint_slot < 0) reuse = 0;
-        /* A WINDOW SNAPSHOT COVERS THE TRUNK'S WINDOWED GROUPS -- at the checkpoint and nowhere
-         * else. The lookup clamped the hit to it (PrefixCache: a window counts as state there),
-         * so a hit with a slot is exactly at a snapshot; one without is no hit. */
+        if (h.n_attn_tokens > 0 && reuse == 0 && geo_.checkpoints()) {
+            s.hit_cut = SchedReq::HitCut::NoSnapshot;
+            RAD_DEBUG("admit %llu: prefix hit of %lld tokens reuses nothing -- no snapshot at or "
+                      "below it", (unsigned long long)r.id, (long long)h.n_attn_tokens);
+        } else if (reuse < h.n_attn_tokens) {
+            RAD_DEBUG("admit %llu: prefix hit of %lld tokens resumes at the snapshot at %lld",
+                      (unsigned long long)r.id, (long long)h.n_attn_tokens, (long long)reuse);
+        }
+        /* A window snapshot covers the trunk's windowed groups at the checkpoint only. The lookup
+         * clamped the hit to it (a window counts as state there), so a hit with a slot is exactly
+         * at a snapshot; one without is no hit. */
         const bool win_hit = geo_.window_ckpt && kv_->has_window_snapshot() && reuse > 0 &&
                              h.checkpoint_slot >= 0 && reuse == h.n_linear_tokens;
 
-        /* THE WINDOWED-GROUP CLAMP — a prefix hit on a model whose OWN (trunk) KV includes a
-         * paged group the cache does not index. prefix.cpp skips RAD_KV_WINDOW groups — their
-         * blocks below the window are recycled, so no block list describes them; the comment
-         * there says a hit "costs the sequences ... a windowed layer whose cache starts where
-         * the hit ended" — this is that cost in KV corruption. The adopted blocks cover the
-         * cached groups ONLY, while `used = ctx_len + n_tokens` (batch.cpp) makes every
-         * windowed trunk layer read the positions below ctx_len that this sequence NEVER WROTE
-         * — and grab_block's min-heap (kv.cpp) hands this sequence the very blocks the most
-         * recent tenant wrote. The model then attends to the PREVIOUS REQUEST'S KV as its own
-         * prefix: fluent text carrying the last request's CONTENT. Zero the reuse; the whole
-         * prompt re-prefills, which is what a window snapshot (below) exists to avoid -- seconds
-         * to minutes of first-token time on a long agent turn.
+        /* Windowed-group clamp: the trunk's own KV includes a paged group the cache does not
+         * index. prefix.cpp skips RAD_KV_WINDOW groups (their blocks below the window are
+         * recycled), so the adopted blocks cover the cached groups only, while `used = ctx_len +
+         * n_tokens` (batch.cpp) makes each windowed trunk layer read positions below ctx_len this
+         * sequence never wrote. grab_block's min-heap (kv.cpp) hands out the blocks the latest
+         * tenant wrote, so the model would attend to the previous request's KV. Zero the reuse
+         * and re-prefill unless a window snapshot covers it.
          *
-         * NOT the drafter's hole. A drafter's own group (bound at base_layer and above — see
-         * scheduler.h) is repaired by draft refill, which CAPS the hit so the recompute covers
-         * the drafter's window while the trunk reuses the rest; zeroing here would delete that
-         * design. The trunk's hole, which no tail-recompute can fix, is this clamp's own. */
+         * A drafter's own group (bound at base_layer and above) is not this clamp's business:
+         * draft refill caps the hit so the recompute covers the drafter's window. */
         if (reuse > 0 && hit_holes_trunk_ && !win_hit) {
             reuse = 0;
+            s.hit_cut = SchedReq::HitCut::Window;
             RAD_DEBUG("admit %llu: prefix hit %lld zeroed -- a trunk paged group is not "
                       "prefix-cached (windowed) and no window snapshot covers it; re-prefilling",
                       (unsigned long long)r.id,
                       (long long)h.n_attn_tokens);
         }
 
-        /* Claim the cached blocks. Without this the hit is only an accounting entry: the sequence
-         * would skip computing those tokens and then attend to blocks it does not own. adopt()
-         * takes a whole block multiple, which `reuse` is -- a whole number of blocks, or a
-         * checkpoint position, which is on the interval or on a quantum boundary at a prompt's tail
-         * (plan_chunk), and geometry.h made both multiples of the block size. */
+        /* Claim the cached blocks; otherwise the sequence would skip those tokens and attend to
+         * blocks it does not own. adopt() takes a whole block multiple, which `reuse` is: a whole
+         * number of blocks, or a checkpoint position (on the interval, or on a quantum boundary at
+         * a prompt's tail per plan_chunk), both block multiples by geometry.h. */
         if (reuse > 0) {
             const std::vector& cg = pc_->cached_groups();
             for (size_t i = 0; i < cg.size() && i < hit_blocks_.size(); ++i) {
                 int64_t nb = reuse / kvgeom_.g[(size_t)cg[i]].block_size;
                 if ((int64_t)hit_blocks_[i].size() > nb) hit_blocks_[i].resize((size_t)nb);
                 if (kv_->adopt(r.id, cg[i], hit_blocks_[i], reuse) < 0) {
-                    /* AND WHAT THE EARLIER GROUPS ADOPTED GOES BACK. Left in the table, those
-                     * blocks would be the first blocks of a sequence that now starts from zero,
-                     * and the recompute would write its KV into the cache's own blocks. */
+                    /* Return what earlier groups adopted, or the recompute would write its KV
+                     * into the cache's own blocks. */
                     kv_->preempt(r.id);
                     reuse = 0;
+                    s.hit_cut = SchedReq::HitCut::Adopt;
                     break;
                 }
             }
@@ -1065,6 +1024,7 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
             if (reuse > 0 && win_hit && kv_->seed_window(r.id, reuse) < 0) {
                 kv_->preempt(r.id);
                 reuse = 0;
+                s.hit_cut = SchedReq::HitCut::Adopt;
             }
         }
 
@@ -1077,41 +1037,46 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
 
     int64_t target = s.seq_len();
     int64_t ckpt = -1;
-    /* AN ADMISSION SHARES THE STEP THE SAME WAY. A cold prompt admitted with requests queued
-     * behind it would otherwise take every token left, and the queue behind it would wait a step
-     * for nothing; the hit above is known by now, so the cap is on what really has to run. */
-    const int64_t cap = r.embed ? budget   /* whole input or nothing: never held back (below) */
-                                : busy_cap(r.n_computed, target, budget, reserve, !plan_.e.empty());
-    int64_t want = plan_chunk(r.n_computed, target, cap, &ckpt, r.checkpoint_at);
-    if (cap < budget && want > 0)
-        admit_full_ = plan_chunk(r.n_computed, target, budget, nullptr, r.checkpoint_at);
-    /* The whole input or nothing this step (Request::embed): the next step starts with a whole
-     * budget, and add_locked refused an input no budget holds. */
-    if (r.embed && want < target - (int64_t)r.n_computed) want = 0;
+    int64_t want;
+    if (r.embed) {
+        /* The whole input or nothing this step (Request::embed): the next step starts with a
+         * whole budget, and add_locked refused an input no budget holds. Not through plan_chunk,
+         * whose checkpoint splits would cut every input longer than the interval short, and an
+         * input that can only run whole would then never be admitted, nor anything queued behind
+         * it. An embedding input is never resumed, so it takes no checkpoint. */
+        const int64_t rest = target - (int64_t)r.n_computed;
+        want = rest <= budget ? rest : 0;
+    } else {
+        /* An admission shares the step the same way: otherwise a cold prompt with requests
+         * queued behind it takes every token left. The hit is known by now, so the cap applies
+         * to what really has to run. */
+        const int64_t cap = busy_cap(r.n_computed, target, budget, reserve, !plan_.e.empty());
+        want = plan_chunk(r.n_computed, target, cap, &ckpt, r.checkpoint_at);
+        if (cap < budget && want > 0)
+            admit_full_ = plan_chunk(r.n_computed, target, budget, nullptr, r.checkpoint_at);
+    }
     int rc = RAD_OK;
     if (want <= 0)                                          rc = RAD_E_FULL;
     else if (s.card < 0 && free_cards_.empty())             rc = RAD_E_FULL;
     else {
-        /* THE CACHE GIVES WAY TO A NEW REQUEST as it does to a running one: with nothing running,
-         * no other path would ever take blocks back from it, and the request would wait for good. */
+        /* The cache gives way to a new request as it does to a running one; with nothing
+         * running, no other path would reclaim from it and the request would wait forever. */
         int rounds = 0;
         while (kv_->ensure_from(r.id, r.n_computed + want, r.n_computed) < 0) {
-            if (++rounds > 256 || !cfg_.prefix_cache || pc_->evict(256) <= 0) {
+            if (++rounds > kEvictRounds || !cfg_.prefix_cache || pc_->evict(kEvictBlocks) <= 0) {
                 rc = RAD_E_NOMEM;
                 break;
             }
         }
     }
     if (rc < 0) {
-        /* A HIT THAT RESUMES FROM A SNAPSHOT IS NOT KEPT ACROSS A FAILED ATTEMPT. The slot is
-         * named by id only, and until this request's first step restores from it nothing stops
-         * the cache retiring it and handing it to another sequence's checkpoint -- so a later
-         * attempt that trusted the id would restore somebody else's recurrent state, which reads
-         * as fluent text about the wrong conversation. Giving the hit back costs the next attempt
-         * a lookup; the attention-only hit of a model with no recurrent state holds only
+        /* A hit that resumes from a snapshot is not kept across a failed attempt. The slot is
+         * named by id only, and until the first step restores from it the cache may retire it
+         * and reuse it for another sequence, so a later attempt would restore someone else's
+         * recurrent state. Giving the hit back costs a lookup. An attention-only hit holds only
          * refcounted blocks and is kept. */
         if (s.ckpt_src >= 0) undo_hit(s);
-        /* AND WHAT THE RESTORE BROUGHT BACK STAYS for the next attempt (IPrefixCache::hold). */
+        /* What the restore brought back stays for the next attempt (IPrefixCache::hold). */
         if (cfg_.prefix_cache) pc_->hold(r);
         return rc;
     }
@@ -1122,6 +1087,13 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
         if (cfg_.prefix_cache) {
             m_.attn_cached_tokens += s.hit_attn;
             m_.linear_cached_tokens += r.n_cached;
+            if (s.hit_attn > r.n_cached) m_.hit_cut_tokens += s.hit_attn - r.n_cached;
+            switch (s.hit_cut) {
+                case SchedReq::HitCut::NoSnapshot: ++m_.hit_cut_no_snapshot; break;
+                case SchedReq::HitCut::Window:     ++m_.hit_cut_window;      break;
+                case SchedReq::HitCut::Adopt:      ++m_.hit_cut_adopt;       break;
+                case SchedReq::HitCut::None:       break;
+            }
         }
         s.hit_owed = false;
     }
@@ -1139,8 +1111,8 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
 
 void Scheduler::undo_hit(SchedReq& s) {
     Request& r = *s.req;
-    /* preempt() rather than free_sequence(): the sequence stays known to the manager, at zero
-     * tokens and holding nothing, which is exactly where a fresh attempt starts from. */
+    /* preempt(), not free_sequence(): the sequence stays known to the manager at zero tokens,
+     * where a fresh attempt starts. */
     if (kv_->has_sequence(r.id)) kv_->preempt(r.id);
     r.n_computed = 0;
     r.n_cached = 0;
@@ -1154,13 +1126,12 @@ const RadBatch* Scheduler::step() {
     /* A cycle opens here, so its head depth is chosen here (scheduler.h, draft_cycle). */
     draft_cycle();
 
-    /* The drafter's snapshots describe the step before this one and nothing reads them from here
-     * on. block_end() and serial_end() clear them already; this covers a drafter that stopped
-     * part way through, so a stale snapshot cannot keep deferring a release. */
+    /* The drafter's snapshots describe the previous step and nothing reads them now. block_end()
+     * and serial_end() normally clear them; this covers a drafter that stopped part way, so a
+     * stale snapshot cannot keep deferring a release. */
     block_.clear();
     serial_.clear();
-    /* And the snapshots the last step's admissions were handed have been read by its forward,
-     * which committed before this was called. */
+    /* The last step's admissions have read their snapshots: its forward committed before this. */
     if (pc_) pc_->begin_step();
 
     plan_.reset();
@@ -1169,29 +1140,71 @@ const RadBatch* Scheduler::step() {
 
     int64_t budget = cfg_.max_tok;
     bool preempted_here = false;
+    /* --prefill-interleave: after a step that carried a chunk beside decoding sequences, with the
+     * prompt continuing, the next N steps carry decode rows only and admit nothing. With nothing
+     * decoding there is nothing to give steps to, and the hold is dropped. */
+    bool any_decoding = false;
+    bool hold_prefill = false;
+    held_prefill_ = 0;
+    if (cfg_.prefill_interleave > 0) {
+        for (int32_t slot : running_) {
+            const SchedReq& s = *reqs_[(size_t)slot];
+            if (!s.req || !s.running) continue;
+            const Request& r = *s.req;
+            if (r.n_computed < (int64_t)r.prompt.size() || r.n_computed + 1 < s.seq_len()) continue;
+            any_decoding = true;
+            break;
+        }
+        if (!any_decoding) interleave_left_ = 0;
+        hold_prefill = interleave_left_ > 0;
+    }
 
-    /* A STEP THAT ALSO CARRIES A PREFILL TAKES A DRAFT LIKE ANY OTHER, and that rests on how the
-     * linear blocks issue a mixed step.
-     *
-     * The blocks issue the RECURRENT path over the decode rows of a mixed step and the CHUNKED
-     * path over the prefill ones, so a verifying decode row carries num_accepted and rolls back
-     * exactly as it does in a pure decode step. Were a mixed step prefill-shaped for every
-     * sequence in it, a verifying row would take the chunked path -- which has no num_accepted
-     * operand, because a chunk has nothing to reject -- and its recurrent state and conv window
-     * would advance over all 1 + n_spec tokens with no way back. The rejected tokens stay folded
-     * into the state and the model is then conditioned on text it never emitted: fluent, and
-     * drifting, so it surfaces as concurrent requests disagreeing with the same requests run
-     * alone rather than as anything failing. */
+    /* A span is for a prefill alone in its step (ChunkGeometry::span). A spanned step takes as
+     * long as the intervals it carries, so a decode row riding along would wait that long for its
+     * token. The span is taken only when the step can hold nothing but the one prefill (a single
+     * running request with prompt left and no admission possible, or a single request in an empty
+     * engine); every other step is planned at ChunkGeometry::shared_tok as a deployment without a
+     * span plans it, --busy-prefill-chunk included. Both kinds of chunk end on the same interval
+     * grid, so a prompt may switch between them at any step. */
+    span_now_ = true;
+    struct SpanReset { bool& f; ~SpanReset() { f = true; } } span_reset{span_now_};
+    /* Keyed on the flag, not on whether this model has intervals to span: the engine told the
+     * plugin that a step wider than shared_tok is one sequence (RadBuildCtx::max_mixed_tok),
+     * whatever the geometry turned out to be. */
+    if (cfg_.prefill_span > 1) {
+        bool lone = false;
+        const bool admit_possible = !waiting_.empty() && !free_cards_.empty() &&
+                                    (int64_t)running_.size() < cfg_.max_seqs;
+        if (running_.size() == 1 && !admit_possible) {
+            const SchedReq& s0 = *reqs_[(size_t)running_[0]];
+            lone = s0.req->n_computed < (int64_t)s0.req->prompt.size() ||
+                   s0.req->n_computed + 1 < s0.seq_len();
+            /* By the whole prefill, not what is left of it, so a prompt keeps spanning through
+             * its last intervals (set_span_min). */
+            if (lone && span_min_ > 0)
+                lone = std::max((int64_t)s0.req->prompt.size(), s0.seq_len()) >= span_min_;
+        } else if (running_.empty() && waiting_.size() == 1) {
+            const SchedReq& w = *reqs_[(size_t)waiting_[0]];
+            lone = span_min_ == 0 || (w.req && (int64_t)w.req->prompt.size() >= span_min_);
+        }
+        span_now_ = lone;
+        if (!lone) budget = geo_.shared_tok;
+    }
+
+    /* A mixed step takes drafts like any other: the linear blocks run the recurrent path over its
+     * decode rows and the chunked path over its prefill rows, so a verifying row rolls back as in
+     * a pure decode step. Run through the chunked path (which has no num_accepted operand), its
+     * rejected tokens would stay folded into the recurrent state and conv window. */
     const int depth = draft_.next_depth();
 
-    /* WHAT ELSE WANTS INTO THIS STEP, for --busy-prefill-chunk (busy_cap). The rows still to be
-     * walked -- each decode row's 1 + the deepest window it can take, each prefill row a share --
-     * and one share when a request is waiting and a sequence slot is free for it. Counted down as
-     * the loop walks, so a row's reserve is what is BEHIND it. No allocation: two counters. */
+    /* What else wants into this step, for --busy-prefill-chunk (busy_cap): each decode row still
+     * to be walked needs 1 + the deepest window it can take, each prefill row a share, plus one
+     * share when a request waits and a slot is free. Counted down as the loop walks, so a row's
+     * reserve is what is behind it. */
     const bool share_step = cfg_.busy_prefill_chunk != 0;
-    const int64_t share_tok = std::max(std::max(geo_.quantum, 1),
-                                                cfg_.max_tok / 8 / std::max(geo_.quantum, 1)
-                                                    * std::max(geo_.quantum, 1));
+    const int64_t Q = std::max(geo_.quantum, 1);
+    /* An eighth of this step's budget, which under a span is shared_tok for a shared step. */
+    const int64_t share_tok = std::max(Q, budget / 8 / Q * Q);
     const int64_t dec_row_tok = 1 + std::max(depth, draft_.step_window());
     int64_t behind_dec = 0, behind_pf = 0;
     if (share_step) {
@@ -1210,8 +1223,8 @@ const RadBatch* Scheduler::step() {
     int64_t capped_full = 0;
 
     /* ---------------------------------------------------------- running requests first */
-    /* Continuous batching: a request already holding blocks is served before a new one is let in,
-     * because the alternative is admitting work that then preempts work already half done. */
+    /* Continuous batching: requests already holding blocks are served before new ones are
+     * admitted, so new work never preempts work half done. */
     for (size_t i = 0; i < running_.size(); ) {
         if ((int64_t)plan_.e.size() >= cfg_.max_seqs || budget <= 0) break;
 
@@ -1229,6 +1242,7 @@ const RadBatch* Scheduler::step() {
 
         int64_t ckpt = -1;
         int64_t want;
+        if (prefill && hold_prefill) { ++held_prefill_; ++i; continue; }
         if (prefill) {
             const int64_t shares = share_step ? behind_pf + (admit_waits ? 1 : 0) : 0;
             const int64_t reserve = share_step ? behind_dec + share_tok * shares : 0;
@@ -1240,23 +1254,21 @@ const RadBatch* Scheduler::step() {
                                                 r.checkpoint_at);
                 if (want < full) { capped_at = (int32_t)plan_.e.size(); capped_full = full; }
             }
-            /* A PREFILL WITH NO ROOM LEFT DOES NOT STOP THE WALK. Under a quantum of budget it can
-             * take nothing this step, but a decode row behind it needs only 1 + its window -- so
-             * it is passed over rather than ending the loop (off keeps the old `break`). */
+            /* A prefill with no room left does not end the walk: it takes nothing this step, but
+             * a decode row behind it needs only 1 + its window. With --busy-prefill-chunk off the
+             * walk stops here. */
             if (want <= 0 && share_step) { ++i; continue; }
         } else {
             /* A verify step is 1 + n_draft query rows, which is why attention kernels take a
-             * query length rather than assuming one (spec §10). */
-            /* THE LAST GATE, and it has to be here rather than only at set_draft, because the
-             * n-gram fallback below fills any proposal a drafter left empty -- so refusing a
-             * draft upstream and stopping there hands the request a different draft instead of
-             * none. Request::may_speculate says why a request can be ineligible.
+             * query length (spec §10). */
+            /* The final speculation gate. It must be here, not only in set_draft, because the
+             * n-gram fallback below fills any empty proposal; refusing upstream alone would just
+             * swap in a different draft. See Request::may_speculate.
              *
-             * AND THE CAP IS THE SEQUENCE'S OWN WINDOW, which is `depth` unless the adaptive
-             * policy is on -- then it is what this sequence's acceptance of the HEAD's drafts pays
-             * for. The n-gram fallback is not the head and that estimate says nothing about it, so
-             * it is held to the step's window instead: as deep as the head drafts this step and no
-             * deeper, which adds no pass shape the head's own windows do not. */
+             * The cap is the sequence's own window: `depth`, or under the adaptive policy what
+             * its acceptance of the head's drafts pays for. That estimate says nothing about the
+             * n-gram fallback, so the fallback is held to the step's window, as deep as the head
+             * drafts this step and no deeper. */
             const int cap = draft_.adaptive() ? draft_cap(s) : depth;
             bool ngram = false;
             if (!r.may_speculate) s.n_draft = 0;
@@ -1266,10 +1278,9 @@ const RadBatch* Scheduler::step() {
             }
             if (!ngram && s.n_draft > cap) s.n_draft = cap;
             s.draft_ngram = ngram;
-            /* NO VERIFIED POSITION AT OR PAST THE CONTEXT. The step computes positions n_computed
-             * .. n_computed + n_draft, and nothing past ctx_limit_ - 1 has a rotary row or a
-             * block-table column. commit() finishes a sequence before its length reaches the
-             * limit, so there is always room for the one token itself. */
+            /* No verified position at or past the context end: nothing past ctx_limit_ - 1 has a
+             * rotary row or block-table column. commit() finishes a sequence before it reaches
+             * the limit, so the one token itself always fits. */
             const int64_t spare = ctx_limit_ - 1 - (int64_t)r.n_computed;
             if (ctx_limit_ > 0 && s.n_draft > spare) s.n_draft = spare > 0 ? (int32_t)spare : 0;
             want = 1 + s.n_draft;
@@ -1277,48 +1288,41 @@ const RadBatch* Scheduler::step() {
         }
         if (want <= 0) break;   /* the budget is spent; the rest of running_ waits a step */
 
-        /* KV first, and preempt from the BACK on refusal -- the lowest priority, latest arrival
-         * running request, which is the one that would be re-admitted last anyway. */
-        /* BOUNDED, because this loop is the scheduler thread and an unbounded one is a server that
-         * stops stepping with nothing in the log to say why. Reclaiming from the cache is tried
-         * first (a cached prefix is a saving; a running request is work in flight), but only so
-         * many times -- past that the shortfall is not the cache's to fix and preemption is. */
-        static const int kMaxEvictRounds = 256;
+        /* KV first; on refusal preempt from the back (lowest priority, latest arrival), the one
+         * that would be re-admitted last anyway. Reclaiming from the cache is tried first, but
+         * only kEvictRounds times; past that the shortfall is preemption's to fix. */
         int evict_rounds = 0;
-        bool failed = false;
+        bool failed = false, yielded = false;
         while (kv_->ensure_from(r.id, r.n_computed + want, r.n_computed) < 0) {
-            /* THE CACHE GIVES ITS BLOCKS BACK BEFORE A RUNNING REQUEST DOES. Everything the prefix
-             * cache holds is a saving on work that has already been done once; everything a
-             * running request holds is work in flight. Evicting first is therefore strictly the
-             * cheaper order, and it is also what keeps publishing from turning into a leak -- the
-             * cache retains a reference on every block it indexes and nothing else ever releases
-             * one. Batched rather than one at a time so a large shortfall does not walk the LRU
-             * list a hundred times. */
-            if (++evict_rounds <= kMaxEvictRounds && pc_ && cfg_.prefix_cache &&
-                pc_->evict(256) > 0)
+            /* The cache gives blocks back before a running request does: a cached prefix saves
+             * work done once, a running request is work in flight. Nothing else releases the
+             * cache's references, so this also keeps publishing from leaking. */
+            if (++evict_rounds <= kEvictRounds && pc_ && cfg_.prefix_cache &&
+                pc_->evict(kEvictBlocks) > 0)
                 continue;
-            if (!kv_->can_ever_fit(r.n_computed + want) || running_.size() - 1 <= i) {
-                /* Nothing left to take. §17: if the smallest running request cannot fit, it is
-                 * failed rather than the engine deadlocking on a pool that cannot grow. */
-                /* §17: either an empty pool could not serve this length at all, or there is no
-                 * lower-priority request left to take blocks from. Failing the request beats
-                 * deadlocking on a pool that cannot grow. */
+            const bool last = running_.size() - 1 <= i;
+            if (!kv_->can_ever_fit(r.n_computed + want) || (last && i == 0)) {
+                /* §17: either no pool could serve this length, or the request runs alone and
+                 * still cannot grow. Fail the request rather than deadlock. */
                 RAD_WARN("request %llu failed: the KV pool cannot hold %lld tokens%s",
                          (unsigned long long)r.id, (long long)(r.n_computed + want),
                          kv_->can_ever_fit(r.n_computed + want)
-                             ? " and nothing lower-priority is left to preempt"
+                             ? " and nothing else is left to preempt"
                              : " at any occupancy");
                 close_request(s, ReqState::Failed, "kv_exhausted", false, true, RAD_E_FULL,
                               "the KV pool cannot hold it");
-                ++m_.failed;
-                completed_.push_back(r.id);
                 failed = true;
                 break;
             }
+            /* The back of the running set gives its blocks up. When that is this request, the
+             * requests ahead of it hold the pool: it is preempted by recompute and waits for
+             * them, rather than failed. */
             preempt_back();
             preempted_here = true;
+            if (last) { yielded = true; break; }
         }
-        if (failed) continue;   /* close_request removed it from running_; i now indexes the next */
+        /* close_request or preempt_back removed it from running_; i now indexes the next. */
+        if (failed || yielded) continue;
 
         StepEntry e;
         e.req = &r;
@@ -1328,25 +1332,18 @@ const RadBatch* Scheduler::step() {
         e.n_tokens = (int32_t)want;
         e.ctx_len = (int32_t)r.n_computed;
         e.n_spec = prefill ? 0 : s.n_draft;
-        /* AND THE REQUEST SAYS THE SAME NUMBER. Sampler::build_step sizes its per-row staging from
-         * `Request::n_draft` -- one row per sampled position, so 1 + n_draft of them -- while the
-         * batch sizes its logits rows from `n_spec`. The two are the same window and must be kept
-         * equal by one writer: setting only the scheduler`s copy leaves the sampler staging one
-         * row for a step that produces several, and setting only the request`s leaves it staging
-         * rows for a window a later clamp to the controller`s depth took away. Set here, once,
-         * where the window is decided. */
+        /* Keep the request's window equal to the entry's. Sampler::build_step sizes its staging
+         * from Request::n_draft (1 + n_draft rows) while the batch sizes its logits rows from
+         * `n_spec`; setting only one makes the sampler stage the wrong number of rows. Set here,
+         * once, where the window is decided. */
         r.n_draft = e.n_spec;
         r.draft   = e.n_spec ? s.draft : nullptr;
-        /* ONE-BASED, AND A PREFILL ROW IS 1 AND NOT 0. See StepEntry: the value is "how many
-         * tokens the previous step committed", the rolling windows are read at `n_accepted - 1`,
-         * and zero is not a value any of them can read. A prefill has nothing to roll back, which
-         * is offset zero, which is ONE -- the same thing the kernels assume when the operand is
-         * absent, and what ple_conv's contract states for exactly this case.
-         *
-         * IT IS NOT ONLY THE FIRST CHUNK THAT IS AFFECTED. `has_init` is the context length, so
-         * every chunk after the first of a chunked prefill is WARM, and a warm window read at -1
-         * is one element before the slot: ple_conv takes the previous channel's last sample and
-         * ngram_ids hashes a token the slot never held. A 200K prompt is a hundred chunks. */
+        /* One-based: the number of tokens the previous step committed, with the rolling windows
+         * read at `n_accepted - 1`, so 0 is never valid. A prefill rolls nothing back, which is
+         * 1, as the kernels assume when the operand is absent (ple_conv's contract). Every chunk
+         * after the first is warm (`has_init` is the context length), and a warm read at -1 would
+         * take the slot before: the previous channel's sample in ple_conv, a foreign token in
+         * ngram_ids. */
         e.n_accepted = prefill ? 1 : r.n_accepted + 1;
         e.conv_cursor = s.conv_cursor;
         e.draft = s.draft;
@@ -1358,16 +1355,9 @@ const RadBatch* Scheduler::step() {
          * sequence after this, and restoring it again on a later chunk would rewind it. */
         e.ckpt_restore = s.ckpt_src;
         s.ckpt_src = -1;
-        if (ckpt > 0) {
-            /* The checkpoint is the state AFTER the last token of the chunk, and that token sits
-             * at the interval boundary because the split put it there. */
-            int32_t cs = -1;
-            if (pc_->reserve_checkpoint(r, ckpt, &cs) >= 0 && cs >= 0) {
-                e.ckpt_tok = (int32_t)(want - 1);
-                e.ckpt_slot = cs;
-                ++m_.checkpoints_written;
-            }
-        }
+        /* The checkpoint is the state after the chunk's last token, which the split put at the
+         * interval boundary. */
+        if (ckpt > 0) reserve_ckpt(e, r, ckpt, (int32_t)(want - 1));
         s.entry = (int32_t)plan_.e.size();
         s.sched_tokens = (int32_t)want;
         plan_.e.push_back(e);
@@ -1378,10 +1368,9 @@ const RadBatch* Scheduler::step() {
     }
 
     /* ---------------------------------------------------------- admission */
-    /* Skipped entirely in a step that preempted: the pool just refused a request that already had
-     * blocks, so it will refuse a new one, and the front of the queue is now the request we just
-     * took them from. Probing would cost a lookup per step and admit nothing. */
-    if (!preempted_here) {
+    /* Skipped in a step that preempted: the pool just refused a request that already had blocks,
+     * so it would refuse a new one, and the queue's front is now the preempted request. */
+    if (!preempted_here && !hold_prefill) {
         /* `at` walks the queue and `took_` is what it admitted: a request whose media is not
          * encoded yet stays where it is and the one behind it is asked, so the queue is compacted
          * after the walk rather than cut at its front. */
@@ -1389,31 +1378,28 @@ const RadBatch* Scheduler::step() {
         size_t at = 0;
         while (at < waiting_.size() &&
                (int64_t)plan_.e.size() < cfg_.max_seqs && budget > 0) {
+            /* A step planned for one prefill holds that one (span_now_ above). */
+            if (cfg_.prefill_span > 1 && span_now_ && !plan_.e.empty()) break;
             int32_t slot = waiting_[at];
             SchedReq& s = *reqs_[(size_t)slot];
-            /* A SEQUENCE THE CONTEXT CANNOT HOLD IS NEVER RUN. Its prompt alone reaches the last
-             * position this deployment can address, so there is no room to generate into, and
-             * prefilling it would write positions the block tables and rotary tables do not
-             * have. The server refuses such a prompt at the door; this is the scheduler's own
-             * bound for any caller that did not. close_request takes it out of waiting_, so the
-             * same index now names the next request. */
+            /* A sequence the context cannot hold never runs: its prompt alone reaches the last
+             * addressable position, so prefilling it would write positions the block and rotary
+             * tables lack. The server refuses such prompts; this is the scheduler's own bound.
+             * close_request removes it from waiting_, so `at` now names the next request. */
             if (ctx_limit_ > 0 && s.seq_len() >= ctx_limit_) {
                 RAD_WARN("request %llu failed: %lld tokens leave no room in a %lld-token context",
                          (unsigned long long)s.req->id, (long long)s.seq_len(),
                          (long long)ctx_limit_);
                 close_request(s, ReqState::Failed, "context_length_exceeded", false, true,
                               RAD_E_FULL, "it leaves no room in the context");
-                ++m_.failed;
-                completed_.push_back(s.req->id);
                 continue;
             }
-            /* ITS MEDIA FIRST. A request whose items are not encoded keeps its place and the one
-             * behind it is asked; the engine runs the encoder before the next step
-             * (encodes_pending). */
+            /* Media first: a request whose items are not encoded keeps its place and the next is
+             * asked; the engine encodes before the next step (encodes_pending). */
             if (s.req->media && !media_ready(s)) { ++at; continue; }
-            /* One share left for the next request in the queue, when there is one and a slot
-             * for it (busy_cap). The embed path takes a whole input or nothing, so it is not
-             * held back: a share could only turn its admission into a refusal. */
+            /* Leave one share for the next queued request when there is one and a slot for it
+             * (busy_cap). Embed inputs are whole-or-nothing, so a share could only turn their
+             * admission into a refusal. */
             const int64_t areserve =
                 share_step && !s.req->embed && at + 1 < waiting_.size() &&
                 (int64_t)plan_.e.size() + 1 < cfg_.max_seqs && free_cards_.size() > 1
@@ -1435,9 +1421,8 @@ const RadBatch* Scheduler::step() {
             e.n_tokens = s.sched_tokens;
             e.ctx_len = (int32_t)r.n_computed;
             e.n_spec = 0;
-            /* The sampler sizes its staging off the Request's own window, so it is said here as
-             * well: a request coming back from preemption may still carry a proposal a drafter
-             * set before it was taken off the device. */
+            /* The sampler sizes its staging off the Request's own window, and a request back from
+             * preemption may still carry a drafter's proposal. */
             r.n_draft = 0;
             r.draft = nullptr;
             e.n_accepted = 1;               /* one-based; a prefill rolls nothing back */
@@ -1446,20 +1431,11 @@ const RadBatch* Scheduler::step() {
             e.n_draft = 0;
             e.is_prefill = true;
             e.produces_token = (r.n_computed + s.sched_tokens >= s.seq_len());
-            /* THE ADMISSION PATH IS THE ONE THAT MATTERS for a restore -- admit_one set ckpt_src
-             * moments ago and this is the entry it applies to. Consumed once: the state is in the
-             * slot for the rest of the sequence, and restoring it again on a later chunk would
-             * rewind the recurrence to where the hit started. */
+            /* admit_one just set ckpt_src, and this is the entry it applies to. Consumed once:
+             * restoring again on a later chunk would rewind the recurrence to the hit. */
             e.ckpt_restore = s.ckpt_src;
             s.ckpt_src = -1;
-            if (s.pending_ckpt > 0) {
-                int32_t cs = -1;
-                if (pc_->reserve_checkpoint(r, s.pending_ckpt, &cs) >= 0 && cs >= 0) {
-                    e.ckpt_tok = s.sched_tokens - 1;
-                    e.ckpt_slot = cs;
-                    ++m_.checkpoints_written;
-                }
-            }
+            if (s.pending_ckpt > 0) reserve_ckpt(e, r, s.pending_ckpt, s.sched_tokens - 1);
             s.entry = (int32_t)plan_.e.size();
             plan_.e.push_back(e);
             plan_.n_tok += s.sched_tokens;
@@ -1478,20 +1454,18 @@ const RadBatch* Scheduler::step() {
         }
     }
 
-    /* WHAT THE HELD-BACK CHUNK LEFT FOR OTHERS AND THEY DID NOT TAKE GOES BACK TO IT. The reserve
-     * is a forecast: a decode row drafts less than its window, an admission is refused (the pool
-     * is short, the head of the queue waits on a read), a step preempts and skips admission. A
-     * chunk held to the stager's floor in a step that then carries nothing else is a pass under
-     * the threshold -- exactly the slow step the floor exists to avoid -- so the unused budget is
-     * handed back, as far as the chunk's own geometry allows (plan_chunk) and only if the pool
-     * grants the blocks without a preemption; otherwise the chunk stays as planned. */
+    /* Budget the held-back chunk reserved for others but they did not use goes back to it. The
+     * reserve is a forecast: a decode row drafts less than its window, an admission is refused,
+     * a step preempts and skips admission. A chunk held to the stager's floor in a step with
+     * nothing else is the slow pass the floor exists to avoid, so the unused budget is returned,
+     * as far as plan_chunk allows and only if the pool grants the blocks without preempting. */
     if (capped_at >= 0) {
         StepEntry& e = plan_.e[(size_t)capped_at];
         const Request& r = *e.req;
         SchedReq& s = *reqs_[(size_t)e.slot];
         const int64_t had = e.n_tokens;
-        /* An explicit --busy-prefill-chunk N is a ceiling the operator chose, not a forecast:
-         * the chunk grows back to it at most. */
+        /* An explicit --busy-prefill-chunk N is a ceiling, not a forecast: the chunk grows back
+         * to it at most. */
         int64_t limit = std::min(capped_full, had + budget);
         if (cfg_.busy_prefill_chunk > 0) limit = std::min(limit, std::max(had, cfg_.busy_prefill_chunk));
         int64_t ckpt = -1;
@@ -1500,14 +1474,7 @@ const RadBatch* Scheduler::step() {
         if (grown > had && kv_->ensure_from(r.id, r.n_computed + grown, r.n_computed) >= 0) {
             e.n_tokens = (int32_t)grown;
             e.produces_token = (r.n_computed + grown >= s.seq_len());
-            if (ckpt > 0) {
-                int32_t cs = -1;
-                if (pc_->reserve_checkpoint(r, ckpt, &cs) >= 0 && cs >= 0) {
-                    e.ckpt_tok = (int32_t)(grown - 1);
-                    e.ckpt_slot = cs;
-                    ++m_.checkpoints_written;
-                }
-            }
+            if (ckpt > 0) reserve_ckpt(e, r, ckpt, (int32_t)(grown - 1));
             s.sched_tokens = (int32_t)grown;
             plan_.n_tok += grown - had;
             budget -= grown - had;
@@ -1515,60 +1482,66 @@ const RadBatch* Scheduler::step() {
         if (e.n_tokens < capped_full) ++m_.prefill_chunks_capped;
     }
 
-    if (plan_.e.empty()) return nullptr;
+    if (plan_.e.empty()) { interleave_left_ = 0; held_prefill_ = 0; return nullptr; }
 
-    /* THE DECODE ROWS FIRST, and both halves therefore contiguous.
+    /* Decode rows first, so each half is contiguous. The running loop walks `running_` in
+     * priority order, interleaving the two kinds; sorted, a block can issue the recurrent path
+     * over one run of sequences and the chunked path over the other. cu_seqlens holds absolute
+     * row offsets, so a sub-array needs no rebasing (RadBatch::n_seq_decode).
      *
-     * A mixed step is prefill-shaped for every sequence in it only because the two kinds of row
-     * are interleaved: the running loop walks `running_` in priority order and a request part way
-     * through its prompt sits wherever its priority put it. Sorted, each half is a contiguous run
-     * of sequences, and a block can issue the recurrent path over one and the chunked path over
-     * the other -- cu_seqlens holds absolute row offsets, so a sub-array of it needs no rebasing
-     * and no kernel change (RadBatch::n_seq_decode).
-     *
-     * Stable, so the order within each half is still the order the scheduler chose. `s.entry` is
-     * the index into this vector and every entry's was assigned before the sort, so all of them
-     * are rewritten here -- a stale entry index is a request reading another request's result.
-     *
-     * A pure step sorts to itself and pays one pass over at most max_seqs entries. */
-    std::stable_partition(plan_.e.begin(), plan_.e.end(),
-                          [](const StepEntry& e) { return !e.is_prefill; });
+     * Stable, so each half keeps the scheduler's order. `s.entry` indexes this vector and was
+     * assigned before the sort, so every one is rewritten here; a stale index makes a request
+     * read another's result. */
+    {
+        part_.clear();
+        size_t w = 0;
+        for (size_t i = 0; i < plan_.e.size(); ++i) {
+            if (plan_.e[i].is_prefill) part_.push_back(plan_.e[i]);
+            else plan_.e[w++] = plan_.e[i];
+        }
+        for (const StepEntry& e : part_) plan_.e[w++] = e;
+    }
     for (size_t i = 0; i < plan_.e.size(); ++i) {
         StepEntry& e = plan_.e[i];
         if (e.slot >= 0 && (size_t)e.slot < reqs_.size()) reqs_[(size_t)e.slot]->entry = (int32_t)i;
     }
 
-    /* Phase, from what actually got scheduled. The run phase uses it to index bucket tables, so a
-     * step with one prefill chunk in it is MIXED and not DECODE -- calling it decode would pick
-     * the skinny-GEMM band for a thousand-row GEMM. */
+    /* Phase from what was scheduled; the run phase indexes bucket tables by it. A step with one
+     * prefill chunk is MIXED, not DECODE, or it would pick the skinny-GEMM band for a large
+     * GEMM. */
     bool any_pf = false; int64_t n_dec = 0;
     for (const StepEntry& e : plan_.e) { if (e.is_prefill) any_pf = true; else ++n_dec; }
     plan_.phase = any_pf && n_dec ? RAD_PHASE_MIXED
                 : any_pf         ? RAD_PHASE_PREFILL
                                  : RAD_PHASE_DECODE;
 
-    /* WHAT THE STEP SHAPE COSTS, AND WHAT SPECULATION DID NOT REACH. `steps_mixed` over `steps`
-     * says how often the load produces a step carrying both kinds of row; an agentic load produces
-     * them often enough that it is worth letting such a step draft.
-     *
-     * `decode_rows_unspeculated` is every decode row that took no draft, whatever the reason:
-     * the controller at depth 0, a request that may not speculate, a drafter with nothing to
-     * propose. It counts ROWS rather than any one reason, so it stays the answer to "how much of
-     * my decode is running unspeculated" whatever the current set of reasons is. */
+    /* Step-shape counters. `steps_mixed` / `steps` shows how often a step carries both kinds of
+     * row. `decode_rows_unspeculated` counts every decode row that took no draft, whatever the
+     * reason (depth 0, an ineligible request, nothing to propose). */
     switch (plan_.phase) {
         case RAD_PHASE_PREFILL: ++m_.steps_prefill; break;
         case RAD_PHASE_MIXED:   ++m_.steps_mixed;   break;
         default:                ++m_.steps_decode;  break;
     }
+    if (cfg_.prefill_interleave > 0) {
+        /* Armed only while a prompt continues past this step: after a last chunk nothing is left
+         * to interleave, and holding would only keep the next request out. */
+        bool continues = false;
+        for (const StepEntry& e : plan_.e)
+            if (e.is_prefill && !e.produces_token) continues = true;
+        if (any_pf) interleave_left_ = any_decoding && continues ? cfg_.prefill_interleave : 0;
+        else if (interleave_left_ > 0) --interleave_left_;
+        if (held_prefill_ > 0) ++m_.steps_held;
+    }
     for (const StepEntry& e : plan_.e)
         if (!e.is_prefill && e.n_spec == 0) ++m_.decode_rows_unspeculated;
     plan_.n_seq_decode = n_dec;
     plan_.n_tok_decode = 0;
     for (int64_t i = 0; i < n_dec; ++i) plan_.n_tok_decode += plan_.e[(size_t)i].n_tokens;
-    /* THE ROWS THE CARD'S ACCEPTANCE READS (advance.h), in the final order: each entry's token row
-     * of its first verified position, its first sampled row, and its draft count. Sampled rows
-     * go to the entries that produce a token, 1 + n_spec each, which is the order the builder
-     * writes out_ids in and the engine reads them back in. */
+    /* The rows the card's acceptance reads (advance.h), in final order: each entry's token row of
+     * its first verified position, its first sampled row, and its draft count. Entries that
+     * produce a token get 1 + n_spec sampled rows each, in the order the builder writes out_ids
+     * and the engine reads them back. */
     {
         int64_t k = 0;
         int32_t row = 0;
@@ -1580,27 +1553,11 @@ const RadBatch* Scheduler::step() {
             k += e.n_tokens;
         }
     }
-    /* DIAGNOSTIC, not a policy: RADIANCE_FORCE_MIXED=1 labels a pure-decode step MIXED, which is
-     * the one thing that changes about it -- every sequence still carries one token. It exists to
-     * ask whether the ops an architecture block issues for MIXED are correct at decode lengths,
-     * without needing a concurrent workload to produce a real mixed step. */
-    static const bool force_mixed = [] {
-        const char* v = std::getenv("RADIANCE_FORCE_MIXED");
-        const bool on = v && *v && *v != '0';
-        /* SAID OUT LOUD. A diagnostic whose only evidence is the output it changes cannot be told
-         * apart from one that never took -- and "identical output" is exactly the result this
-         * flag is used to look for, so a silent no-op reads as a pass. */
-        if (on) RAD_WARN("RADIANCE_FORCE_MIXED is set: every pure-decode step is labelled MIXED");
-        return on;
-    }();
-    if (force_mixed && plan_.phase == RAD_PHASE_DECODE) plan_.phase = RAD_PHASE_MIXED;
-
-    /* EVERY SNAPSHOT THIS STEP RESTORES FROM IS STILL IN THE STORE. The prefix cache keeps a
+    /* Every snapshot this step restores from must still be in the store. The prefix cache keeps a
      * handed-out snapshot's slot until the next step begins (PrefixCache::begin_step), so this
-     * holds by construction; it is checked because a restore from a slot the store gave back
-     * reads another session's state or nothing, and the engine can only stop on it. A step that
-     * finds one is abandoned like a failed staging, below: the request gives its hit back and is
-     * prefilled again, and the rest re-schedule unchanged. */
+     * should always hold; it is checked because restoring from a released slot reads another
+     * session's state. A step that fails it is abandoned like a failed staging (below): the
+     * request gives its hit back and is prefilled again. */
     bool lost_restore = false;
     for (const StepEntry& e : plan_.e) {
         if (e.ckpt_restore < 0 || kv_->checkpoint_held(e.ckpt_restore)) continue;
@@ -1614,14 +1571,12 @@ const RadBatch* Scheduler::step() {
     const RadBatch* b = lost_restore ? nullptr : builder_.build(plan_, *kv_, step_);
     if (!b) {
         /* Staging failed. Nothing was computed, so nothing is committed and n_computed did not
-         * advance: the next step re-schedules the same chunks and the KV allocations already made
-         * cover them. Leaving the step OPEN would deadlock the engine on a commit that will never
-         * come, which is worse than losing a step.
+         * advance: the next step re-schedules the same chunks on the KV already allocated. The
+         * step is not left open, or the engine would deadlock waiting for its commit.
          *
-         * THE ONE THING THE RETRY CANNOT RE-SCHEDULE IS A RESTORE. An entry admitted off a
-         * checkpoint carried the slot to resume from, and that was consumed here; the next step
-         * would run the sequence on as if its recurrent state were in place. Such a request goes
-         * back to the queue and gives its hit back, so the next admission looks it up again. */
+         * A restore cannot be re-scheduled: the entry consumed its checkpoint slot, and the next
+         * step would run on as if the recurrent state were in place. Such a request gives its
+         * hit back and returns to the queue for a fresh lookup. */
         for (StepEntry& e : plan_.e) {
             SchedReq& s = *reqs_[(size_t)e.slot];
             s.entry = -1;
@@ -1645,6 +1600,9 @@ const RadBatch* Scheduler::step() {
 bool Scheduler::prefill_continues() const {
     std::lock_guard lk(mu_);
     if (stage_rows_ <= 0) return false;
+    /* The next step is held to decode rows (--prefill-interleave): experts staged for a chunk now
+     * would be dropped by that step. */
+    if (interleave_left_ > 0) return false;
     for (const StepEntry& e : plan_.e) {
         if (!e.is_prefill || e.slot < 0 || (size_t)e.slot >= reqs_.size() || !reqs_[(size_t)e.slot])
             continue;
@@ -1682,9 +1640,9 @@ void Scheduler::take_encodes(std::vector>* out) {
 /* ------------------------------------------------------------------ the step's head depth */
 void Scheduler::draft_cycle() {
     if (!draft_.adaptive()) return;
-    /* THE ROWS THE OPENING STEP WILL DECODE: every running sequence past its prompt. Those that
-     * may speculate draft, and their estimates choose D; the rest emit one token each, which is
-     * part of what the step yields and of what it costs. A sequence still prefilling is neither. */
+    /* The rows the opening step will decode: every running sequence past its prompt. Those that
+     * may speculate choose D through their estimates; the rest emit one token each, which still
+     * counts in the step's yield and cost. A sequence still prefilling is neither. */
     draft_est_.clear();
     int n_rows = 0;
     for (int32_t slot : running_) {
@@ -1704,9 +1662,9 @@ void Scheduler::expect_draft(uint64_t id, int n) {
     auto it = by_id_.find(id);
     if (it == by_id_.end()) return;
     SchedReq& s = *reqs_[(size_t)it->second];
-    /* UNDER THE ADAPTIVE WINDOW THE ROUNDS RAN FOR THE DEEPEST SEQUENCE, and this one verifies the
-     * first of them up to its own window -- the cap serial_begin sized the rounds from, unchanged
-     * since: nothing commits between the two, and D is the cycle's (draft_cycle). */
+    /* Under the adaptive window the rounds ran for the deepest sequence; this one verifies the
+     * first of them up to its own window. That is the cap serial_begin used: nothing commits
+     * between the two, and D is the cycle's (draft_cycle). */
     if (draft_.adaptive() && n > 0) {
         const int cap = draft_cap(s);
         if (n > cap) n = cap;
@@ -1728,6 +1686,9 @@ const RadBatch* Scheduler::step_next_locked() {
     if (!step_open_ || next_open_ || plan_.e.empty()) return nullptr;
     /* An admission is a decision about the pool and the queue that the full step makes. */
     if (!waiting_.empty()) return nullptr;
+    /* Once the hold is spent, the held chunk goes into the next full step rather than waiting
+     * behind decode steps issued ahead. */
+    if (held_prefill_ > 0 && interleave_left_ == 0) return nullptr;
 
     plan_next_.reset();
     for (const StepEntry& e : plan_.e) {
@@ -1735,16 +1696,15 @@ const RadBatch* Scheduler::step_next_locked() {
         SchedReq& s = *reqs_[(size_t)e.slot];
         if (!s.req || s.req->state != ReqState::Running || !s.running) return nullptr;
         Request& r = *s.req;
-        /* A chunk in the middle of a prompt continues as a prefill, from where the host knows it
-         * is. And a grammar that cannot rewind decides, when this step commits, whether the next
-         * may speculate; one that can -- and a request with no grammar -- answers as it did. */
+        /* A mid-prompt chunk continues as a prefill from where the host knows it is. A grammar
+         * that cannot rewind decides at commit whether the next step may speculate; one that can,
+         * or no grammar, keeps its answer. */
         if (!e.produces_token || !r.speculation_fixed) return nullptr;
 
-        /* THE FURTHEST CONTEXT THE ROW CAN REACH: every position this step verifies committed,
-         * counted from where the host knows the sequence is -- the last commit -- and not from
-         * this step's own bound, which would add a window of slack every step it is issued
-         * ahead. The card's acceptance says where it really is; this is what the pool, the
-         * block tables and every host-side ceiling are sized for. */
+        /* The furthest context the row can reach: every position this step verifies committed,
+         * counted from the last commit rather than this step's own bound (which would add a
+         * window of slack per step issued ahead). The card knows the real position; this sizes
+         * the pool, the block tables and every host-side ceiling. */
         const int64_t ctx_up = r.n_computed + e.n_tokens;
         const int32_t d      = s.draft_next;
         const int64_t want   = 1 + d;
@@ -1795,9 +1755,8 @@ const RadBatch* Scheduler::step_next_locked() {
 void Scheduler::promote_next() {
     std::lock_guard lk(mu_);
     if (!next_open_) return;
-    /* The other place a cycle opens: the step issued ahead becomes this one, and step() is not
-     * called. Its proposals were counted under the last cycle's D; the next ones are drafted
-     * under this one. */
+    /* The other place a cycle opens: the step issued ahead becomes current without step(). Its
+     * proposals were counted under the last cycle's D; the next ones are drafted under this one. */
     draft_cycle();
     std::swap(plan_, plan_next_);
     plan_next_.reset();
@@ -1812,6 +1771,11 @@ void Scheduler::promote_next() {
         if (s.req) { s.req->n_draft = plan_.e[i].n_spec; s.req->draft = s.draft; }
     }
     ++m_.steps_decode;
+    /* A step issued ahead during a hold is one of its decode-only steps. */
+    if (interleave_left_ > 0) {
+        --interleave_left_;
+        if (held_prefill_ > 0) ++m_.steps_held;
+    }
     ++m_.steps_ahead;
     for (const StepEntry& e : plan_.e)
         if (e.n_spec == 0) ++m_.decode_rows_unspeculated;
@@ -1833,29 +1797,18 @@ int Scheduler::commit(const StepResult& res) {
 
     const int32_t W = conv_window();
 
-    /* A MIXED STEP DOES NOT RUN THE CHUNKED PATH OVER A SEQUENCE THAT WAS ONLY DECODING, so the
-     * scratch beside its state is not invalidated here.
-     *
-     * The blocks issue the recurrent path over the decode rows of a mixed step and the chunked
-     * path over the prefill ones (RadBatch::n_seq_decode), so those rows leave exactly the replay
-     * factors a decode step leaves, and discarding them would throw away the rollback the next
-     * verify needs. Invalidation would only be correct if a mixed step were prefill-shaped for
-     * everyone in it: the chunked path commits the state directly and leaves no replay factors,
-     * so anything in the scratch would then describe tokens the state already had.
-     *
-     * The one thing that must stay true for that is the ordering: the recurrent path is issued
-     * over sequences [0, n_seq_decode) and nothing else, so a decode row that sorted into the
-     * prefill half would silently take the chunked path and leave stale factors behind it. That
-     * is what the sort in step() and its test are for. */
+    /* A mixed step leaves decode rows the same replay factors as a decode step (recurrent path
+     * over [0, n_seq_decode), chunked over the rest), so their scratch is not invalidated; the
+     * next verify needs it for rollback. This relies on step() sorting decode rows first: one
+     * sorted into the prefill half would take the chunked path and leave stale factors. */
     for (int i = 0; i < res.n_seq; ++i) {
         const StepEntry& e = plan_.e[(size_t)i];
         SchedReq& s = *reqs_[(size_t)e.slot];
         Request& r = *s.req;
         if (r.state != ReqState::Running) {
-            /* Cancelled between step and commit. Its blocks were held until the device finished
-             * with them; that is now. Its SLOT may also be owed back, if the server reaped it in
-             * the same window -- the sweep at the end of this function does that, once every
-             * entry has been retired. */
+            /* Cancelled between step and commit; its blocks were held until the device finished
+             * with them. If the server also reaped it, the sweep at the end of this function
+             * returns the slot once every entry is retired. */
             s.entry = -1;
             /* Unless the drafter's snapshot still names it, or the next step carries it: the
              * sweep below, or that step's commit, releases it once nothing does. */
@@ -1872,31 +1825,27 @@ int Scheduler::commit(const StepResult& res) {
         bool eos = res.eos && res.eos[i] && !r.ignore_eos;
 
         bool overflowed = false;
-        /* A token whose logprobs the engine could not compute (TokenLogprobs::token -1) for a
-         * request that asked for them: the request fails with the reason rather than send that
-         * token without the numbers it was asked for, and nothing after it is sent. */
+        /* A token whose requested logprobs could not be computed (TokenLogprobs::token -1) fails
+         * the request with the reason; that token and everything after it is not sent. */
         bool lp_failed = false;
 
-        /* THE SNAPSHOT THE ENGINE JUST TOOK IS NOW READABLE. Marking it here rather than at
-         * reservation is the difference between a checkpoint and a promise: reserve_checkpoint
-         * runs when the chunk is PLANNED, and a lookup between then and now would adopt a slot
-         * still holding the previous tenant's state. Stream ordering does the rest -- a later
-         * restore is enqueued on the same stream behind this save, so validity does not have to
-         * wait on the copy landing, only on it being issued. */
+        /* The snapshot the engine just took is now readable. Marked here, not at reservation
+         * (which happens at planning), so a lookup in between cannot adopt a slot still holding
+         * the previous tenant's state. A later restore is enqueued on the same stream behind this
+         * save, so issuing the copy is enough. */
         if (e.ckpt_slot >= 0 && e.ckpt_tok >= 0 && pc_)
             pc_->commit_checkpoint(r, (int64_t)e.ctx_len + e.ckpt_tok + 1);
 
         if (e.is_prefill) {
             r.n_computed += e.n_tokens;
-            /* The chunk is committed: a window group gives its blocks below the window back now,
-             * not at this sequence's next ensure(), which may be steps away while others
-             * prefill. */
+            /* The chunk is committed: a window group returns its blocks below the window now,
+             * not at this sequence's next ensure(), which may be steps away. */
             kv_->trim_window(r.id, r.n_computed);
             step_prefill_tok_ += e.n_tokens;
             server::sink_prompt_progress(r.sink, r.n_computed, (int32_t)r.prompt.size(),
                                          r.n_cached);
-            /* Once, when the prompt is fully placed: the admission accounting the usage block
-             * reports. `n_cached` is what the prefix cache supplied and is not recomputed here. */
+            /* Once, when the prompt is fully placed: the usage block's admission accounting.
+             * `n_cached` is what the prefix cache supplied. */
             if (r.n_computed >= (int64_t)r.prompt.size())
                 server::sink_prompt_stats(r.sink, (int32_t)r.prompt.size(), r.n_cached);
             if (e.produces_token && res.token && r.embed) {
@@ -1911,31 +1860,28 @@ int Scheduler::commit(const StepResult& res) {
                         ? &res.lp[res.first_row[i]] : nullptr;
                 if (lp && lp->token < 0) lp_failed = true;
                 else overflowed = !server::sink_push(r.sink, res.token[i], lp);
-                /* The conv window absorbed this chunk; the cursor advances by one committed
-                 * position, exactly as it does in decode. */
+                /* The conv window absorbed this chunk; the cursor advances one committed
+                 * position, as in decode. */
                 s.conv_cursor = (int32_t)((s.conv_cursor + 1) % (W ? W : 1));
             }
         } else {
             int32_t a = res.n_accepted ? res.n_accepted[i] : 0;
             if (a < 0) a = 0;
             if (a > e.n_spec) a = e.n_spec;
-            /* A ROW ISSUED AHEAD was staged at the furthest context it could reach; it really
-             * continued from the committed end, which is where the host's sequence is. */
+            /* A row issued ahead was staged at the furthest reachable context; it really
+             * continued from the committed end. */
             const int64_t ctx0 = e.dev ? r.n_computed : (int64_t)e.ctx_len;
 
-            /* PAGED KV rolls back: free the blocks past the accepted position, because the KV
-             * written for the rejected tokens is garbage a later step would attend to.
+            /* Paged KV rolls back: blocks past the accepted position are freed, since KV written
+             * for rejected tokens would be attended to later.
              *
-             * LINEAR STATE DOES NOT. The recurrent state and the conv window have already absorbed
-             * the rejected tokens and there is nothing to undo: libr4d's conv update treats the
-             * state cache as a rolling window of width-1 + num_spec entries and reads at the slot
-             * the last accepted token left, so a rejection is a change of READ OFFSET rather than
-             * a recompute (spec §10). The two kinds roll back differently and conflating them is
-             * how you get a model that is subtly wrong only after a rejection. */
+             * Linear state does not. The recurrent state and conv window already absorbed the
+             * rejected tokens; libr4d's conv update treats the state cache as a rolling window of
+             * width-1 + num_spec entries and reads at the slot the last accepted token left, so a
+             * rejection changes the read offset instead of recomputing (spec §10). */
             int64_t valid = ctx0 + 1 + a;
-            /* NOT WHILE THE NEXT STEP IS WRITING PAST IT. A step already issued behind this one
-             * continues the sequence from `valid` and writes its keys and values there and on;
-             * its own commit rolls back to the end it reaches. */
+            /* Not while a step issued ahead writes past `valid`; that step's commit rolls back to
+             * the end it reaches. */
             if (a < e.n_spec && !(next_open_ && s.entry_next >= 0)) {
                 int st = kv_->rollback(r.id, valid);
                 if (st < 0) RAD_WARN("kv rollback for request %llu: %s",
@@ -1944,19 +1890,15 @@ int Scheduler::commit(const StepResult& res) {
             s.conv_cursor = (int32_t)((s.conv_cursor + 1 + a) % (W ? W : 1));
             r.n_accepted = a;
 
-            /* The accepted drafts FIRST and then the verified token, in generation order: the
-             * sink is a stream and a reordering here is a reordering in the client's text.
+            /* Accepted drafts first, then the verified token: the sink is a stream, so order here
+             * is order in the client's text.
              *
-             * AND THE BUDGET IS CHECKED PER TOKEN, because a verify step emits 1 + a of them at
-             * once. Pushing them all and trimming `output` afterwards leaves the SINK holding the
-             * overshoot -- the client has already been streamed tokens it did not ask for, so the
-             * same prompt at the same max_tokens comes back longer with speculation than without.
-             * The same tokens in the same order, just more of them, which is the one way greedy
-             * speculation is allowed to differ and should not. */
+             * The budget is checked per token, because a verify step emits 1 + a at once.
+             * Trimming `output` afterwards would leave the overshoot already streamed, so the
+             * same prompt at the same max_tokens would come back longer with speculation. */
             int64_t room = r.max_tokens > 0
                          ? r.max_tokens - (int64_t)r.output.size() : (int64_t)1 << 62;
-            /* AND THE CONTEXT BOUNDS IT WHATEVER max_tokens SAYS, including "no limit": a
-             * sequence may not grow past the positions this deployment can address. */
+            /* The context bounds it whatever max_tokens says, including no limit. */
             if (ctx_limit_ > 0 && ctx_limit_ - s.seq_len() < room) room = ctx_limit_ - s.seq_len();
             /* `j` is the token's place in the step's emission: its logprobs row is the entry's
              * j-th, when the request asked for them. */
@@ -1978,12 +1920,9 @@ int Scheduler::commit(const StepResult& res) {
 
             if (e.n_spec > 0) {
                 draft_.observe(e.n_spec, a);
-                /* AND THIS SEQUENCE'S OWN ESTIMATE, from the same outcome, under the adaptive
-                 * window -- when the head drafted it. A prompt-lookup proposal is accepted on
-                 * different text by a different rule, and folding it in would price the head's
-                 * next window on what the lookup found. A move takes effect at the next draft:
-                 * this step's drafter has already run, sized from the estimate as it stood before
-                 * this commit. */
+                /* And this sequence's own estimate under the adaptive window, only when the head
+                 * drafted: a prompt-lookup proposal is accepted on different text by a different
+                 * rule. A move takes effect at the next draft; this step's drafter already ran. */
                 if (draft_.adaptive() && !e.ngram) {
                     const int was = s.adapt.depth;
                     const int now = draft_.adapt_observe(s.adapt, e.n_spec, a);
@@ -2009,45 +1948,30 @@ int Scheduler::commit(const StepResult& res) {
         r.n_draft = 0;
         s.entry = -1;
 
-        /* A REQUEST THE NEXT STEP CARRIES FINISHES NOW AND KEEPS ITS BLOCKS: that step is writing
-         * them. Its commit finds the request no longer running and gives them back. */
+        /* A request the next step carries finishes now but keeps its blocks, which that step
+         * writes; its commit finds the request not running and returns them. */
         const bool carried = next_open_ && s.entry_next >= 0;
 
-        /* Finish. The emit above already stops at max_tokens, so `output` cannot run past it --
-         * the resize below is the belt to that braces, kept because a >= test that can only ever
-         * be == is the kind of thing a later change makes wrong quietly. */
+        /* Finish. emit() already stops at max_tokens, so the resize below is a backstop: a >=
+         * test that can only be == is easy to break quietly later. */
         if (overflowed) {
-            /* The sink has already failed the request -- a consumer that far behind is gone --
-             * so all that is left is to stop generating for it and give its blocks back. */
+            /* The sink has already failed the request; stop generating and return its blocks. */
             close_request(s, ReqState::Failed, "sink_overflow", carried);
-            ++m_.failed;
-            completed_.push_back(r.id);
         } else if (lp_failed) {
             close_request(s, ReqState::Failed, "logprobs", carried, true, RAD_E_STATE,
                           "the logprobs of a token it generated could not be computed");
-            ++m_.failed;
-            completed_.push_back(r.id);
         } else if (server::sink_cancelled(r.sink)) {
-            /* The client hung up. Spec §14: the blocks go back now rather than at the end of a
-             * generation nobody will read. */
+            /* The client hung up: the blocks go back now (spec §14). */
             close_request(s, ReqState::Cancelled, "cancelled", carried);
-            ++m_.cancelled;
-            completed_.push_back(r.id);
         } else if (r.max_tokens > 0 && (int64_t)r.output.size() >= r.max_tokens) {
             r.output.resize((size_t)r.max_tokens);
             close_request(s, ReqState::Finished, "length", carried);
-            ++m_.finished;
-            completed_.push_back(r.id);
         } else if (ctx_limit_ > 0 && s.seq_len() >= ctx_limit_) {
-            /* The context is full. The same finish as max_tokens, because to the caller it is
-             * the same thing: the generation ran out of room. */
+            /* The context is full: the same finish as max_tokens, since the generation ran out
+             * of room. */
             close_request(s, ReqState::Finished, "length", carried);
-            ++m_.finished;
-            completed_.push_back(r.id);
         } else if (eos) {
             close_request(s, ReqState::Finished, "stop", carried);
-            ++m_.finished;
-            completed_.push_back(r.id);
         }
     }
 
@@ -2055,47 +1979,27 @@ int Scheduler::commit(const StepResult& res) {
     m_.decode_tokens += step_decode_tok_;
     ++m_.steps;
 
-    /* Every entry is retired now, so anything whose reap or free was deferred on THIS step is
-     * releasable, and so is anything deferred on the last drafter snapshot, which block_end() or
-     * serial_end() has cleared since. Every pass that named them was issued before this step's
-     * readback, which waited for the compute stream. */
+    /* Every entry is retired, so anything deferred on this step, or on a drafter snapshot that
+     * block_end() / serial_end() has since cleared, can be released: every pass naming them was
+     * issued before this step's readback, which waited for the compute stream. */
     sweep_deferred();
     return RAD_OK;
 }
 
 /* ------------------------------------------------------------------ the end of a step */
-/* THE STEP IS NOT OVER AT COMMIT, and timing it there is wrong by the whole draft pass.
+/* Closes the step's timing after the drafter has run. The next step's drafter runs after commit,
+ * the first moment its inputs exist, and its rounds are real forward passes; timed at commit they
+ * would be charged to nothing, so step time would read short and `decode_tps` high. A caller that
+ * drives only commit() (the scheduler tests) gets counters and no timing.
  *
- * The drafter for the NEXT step runs after commit, because that is the first moment both of its
- * inputs exist -- the token the sampler chose, and which drafted position it came from. Its rounds
- * are real forward passes through the draft head. Timed at commit they fall between that commit
- * and the next step(), a gap the engine loop charges to nothing at all: the reported step time
- * comes out short by the draft pass and `decode_tps` -- which divides by the same interval --
- * comes out correspondingly high, which is the direction of error nobody reports.
+ * The rate is tokens over wall time across a decayed window, not an average of step rates: the
+ * host does not wait on the card every step (a prefill chunk that samples nothing commits while
+ * the card still runs it), so per-step rates are skewed by short intervals. Wall time runs from
+ * the last step's end (so a step issued ahead is counted once), or from this step's start after
+ * an idle gap. A step with no tokens of a kind still adds its time, or that rate would freeze.
  *
- * So the engine says when the iteration is genuinely finished and the accounting happens here.
- * Separate from commit() rather than folded into it because they answer different questions:
- * commit() retires a step's tokens, and this closes the engine's loop around it. A caller that
- * only drives commit() -- the scheduler tests -- gets correct counters and no timing, which is
- * the honest answer for a step that never ran on a device.
- *
- * THE RATE IS TOKENS OVER WALL TIME ACROSS A WINDOW, NOT AN AVERAGE OF STEP RATES. A step's
- * interval is host time, and the host does not wait on the card at every step: a prefill chunk
- * that samples nothing is committed while the card is still on it, and a later step's wait pays
- * for it. Averaged as rates, those short intervals dominate -- a 2048-token chunk committed 70 ms
- * after it began reads 30K tok/s -- while the step that absorbed the wait counts once, and the
- * same skew reads decode high. Summed, all of the time is there: each kind's tokens and the wall
- * time since the last step ended -- which also covers a step issued ahead, whose start precedes
- * its predecessor's end, without counting that overlap twice -- or since this step began, when
- * the engine sat idle in between; all three decayed with one time constant.
- *
- * A STEP WITH NO TOKENS OF A KIND STILL ADDS ITS TIME. Skipping it instead would freeze the rate
- * at whatever it last was, so a server that prefilled once long ago would report that prefill
- * throughput for the rest of its life, and a busy engine can read as an idle one.
- *
- * Not a device measurement: enabling per-op timing restores synchronisations that change the
- * mover's slot supply, so a profiled run is not comparable anyway (spec §16). This is the number
- * an operator can always have. */
+ * Host timing, always available. Per-op device timing adds synchronisations that change the
+ * mover's slot supply, so profiled runs are not comparable (spec §16). */
 void Scheduler::step_finished() {
     std::lock_guard lk(mu_);
     if (step_start_.time_since_epoch().count() == 0) return;   /* no step has run */
@@ -2109,9 +2013,8 @@ void Scheduler::step_finished() {
     const auto   from = step_start_ - last_step_at_ < std::chrono::milliseconds(500)
                             ? last_step_at_ : step_start_;
     const double wall = std::chrono::duration(step_end - from).count();
-    /* The window ages by the time that PASSED, idle included, so a phase that ended -- a prefill
-     * burst before a decode run -- leaves it at the window's own rate; only the busy part is
-     * added as time the tokens took. */
+    /* The window ages by all elapsed time, idle included; only the busy part is added as time the
+     * tokens took. */
     const double aged = std::chrono::duration(step_end - last_step_at_).count();
     if (wall > 0) {
         constexpr double kWindowS = 1.0;
@@ -2119,23 +2022,21 @@ void Scheduler::step_finished() {
         tps_win_prefill_ = tps_win_prefill_ * f + (double)step_prefill_tok_;
         tps_win_decode_  = tps_win_decode_  * f + (double)step_decode_tok_;
         tps_win_time_    = tps_win_time_    * f + wall;
-        /* AT LEAST HALF A SECOND OF TIME UNDER THE RATE. After an idle spell the window starts
-         * over, and a burst's first chunk is committed as soon as it is issued: 2048 tokens over
-         * those few milliseconds is exactly the spike this replaces. Held to half a second the
-         * first reads are low instead, and the steady window (about a second) is not touched. */
+        /* At least half a second of time under the rate. After an idle spell the window starts
+         * over and a burst's first chunk commits as soon as it is issued, which would spike the
+         * rate; with the floor the first reads are low instead, and the steady (~1 s) window is
+         * unaffected. */
         const double t = std::max(tps_win_time_, 0.5);
         m_.prefill_tps = (float)(tps_win_prefill_ / t);
         m_.decode_tps  = (float)(tps_win_decode_  / t);
-        /* An exponential decay approaches zero and never arrives, and 7e-14 tok/s is a number
-         * nobody wants to read. Below a twentieth of a token a second it IS zero. */
+        /* The decay never reaches zero; below 0.05 tok/s it reads as zero. */
         if (m_.prefill_tps < 0.05f) m_.prefill_tps = 0.0f;
         if (m_.decode_tps  < 0.05f) m_.decode_tps  = 0.0f;
     }
-    /* AND WHAT THE STEP COST AT ITS DEPTH, for the adaptive window (draft.h): the same wall time,
-     * which is the step's share of the loop -- the draft rounds that followed it included, and a
-     * step issued ahead counted from the end of the one before rather than twice. A decode step
-     * only: a prefill chunk's time is the chunk's, not the window's. Keyed by the deepest window
-     * the step verified, which is the head depth it ran at whenever D held from the step before. */
+    /* The step's cost at its depth, for the adaptive window (draft.h): the same wall time,
+     * including the draft rounds after it, with a step issued ahead counted once. Decode steps
+     * only. Keyed by the deepest window the step verified, which is the head depth it ran at
+     * whenever D held from the step before. */
     if (draft_.adaptive() && plan_.phase == RAD_PHASE_DECODE && plan_.n_spec > 0 && wall > 0) {
         int rows = 0;
         for (const StepEntry& e : plan_.e) rows += (e.produces_token && !e.is_prefill) ? 1 : 0;
@@ -2147,40 +2048,33 @@ void Scheduler::step_finished() {
 }
 
 /* ------------------------------------------------------------------ the serial drafter */
-/* Which sequences may take a serial draft after the step just committed, and what each of them
- * needs. Called while plan() still describes that step, because everything here is a coordinate
- * INTO it: the head reads the trunk's hidden states out of the buffer the step just filled.
+/* Which sequences may take a serial draft after the step just run, and what each needs. Called
+ * while plan() still describes that step, since everything here indexes into it: the head reads
+ * the trunk's hidden states from the buffer the step filled.
  *
- * THE HEAD'S INDEXING, which StepPlan::tok_shift carries: head index i reads hidden(i) and the
- * token at i + 1, writes its K and V at KV position i, and predicts i + 2. So after a step that
- * committed `n_computed` positions, the newest index the head can serve is n_computed - 1 --
- * its hidden state is the last row the trunk produced and the token one on is the one the
- * sampler just chose. That is draft round 1, and each round after it steps one position further out.
- */
+ * Head indexing (StepPlan::tok_shift): head index i reads hidden(i) and the token at i + 1,
+ * writes K and V at position i, and predicts i + 2. After a step that committed `n_computed`
+ * positions the newest index the head can serve is n_computed - 1; that is draft round 1, and
+ * each later round is one position further. */
 int Scheduler::serial_begin(int* rounds, SerialRow* out, int max) {
     std::lock_guard lk(mu_);
     serial_.clear();
     if (!rounds || *rounds <= 0 || !out || max <= 0) return 0;
 
-    /* MAY ANYTHING DRAFT AT ALL? The controller decides depth from measured acceptance, and 0 means
-     * it has turned drafting off. That is the whole test: a step carrying a prefill chunk is not
-     * itself a reason to refuse, because its decode rows still take the recurrent path.
-     *
-     * Neither answer stops the HISTORY pass. The head's own K and V have to be filled whether or
-     * not this particular step drafts -- a sequence three chunks into a long prompt is exactly the
-     * case where nothing can draft yet and the history is exactly what will be needed. */
+    /* May anything draft? The controller sets depth from measured acceptance; 0 means drafting is
+     * off. A step carrying a prefill chunk is no reason to refuse, since its decode rows still
+     * take the recurrent path. Neither answer skips the history pass: the head's K and V must be
+     * filled either way, e.g. for a sequence still in the middle of a long prompt. */
     const int depth = draft_.next_depth();
     bool may_draft = depth > 0;
     if (depth > 0 && *rounds > depth) *rounds = depth;
     if (*rounds > RAD_SCHED_MAX_SPEC) *rounds = RAD_SCHED_MAX_SPEC;
 
-    /* UNDER THE ADAPTIVE WINDOW, NO MORE ROUNDS THAN THE DEEPEST SEQUENCE WANTS. A round is one
-     * pass of the head over every drafting row, so the step runs as many as its deepest window,
-     * and a sequence that wants fewer verifies the first of them (expect_draft, set_draft); a
-     * round past the deepest window is a pass whose proposal nobody verifies. Only a row that will
-     * draft and be given its drafts counts. When no row does, the rounds stay as they are: round 0
-     * is the history pass, and that still has to run. The reservation below is then made for the
-     * rounds that will actually run, which is what it is for. */
+    /* Under the adaptive window, no more rounds than the deepest sequence wants. A round is one
+     * head pass over every drafting row, and a sequence that wants fewer verifies the first of
+     * them (expect_draft, set_draft); a round past the deepest window drafts for nobody. Only a
+     * row that will draft counts. With none, the rounds stay as they are, because round 0 is the
+     * history pass. The lookahead reservation below then matches the rounds that will run. */
     if (may_draft && draft_.adaptive()) {
         int want = 0;
         for (const StepEntry& e : plan_.e) {
@@ -2208,45 +2102,32 @@ int Scheduler::serial_begin(int* rounds, SerialRow* out, int max) {
         if (!s.req || s.req->state != ReqState::Running || !s.running) continue;
         Request& r = *s.req;
 
-        /* THE VERIFIED POSITIONS: the last 1 + n_spec of the entry. Round 1 continues from the
-         * last committed one, which is the first of them plus however many drafts were accepted
-         * -- a number the card has and the host does not yet, so the host bounds it by all of
-         * them. A chunk in the middle of a prompt verified nothing and continues nothing. */
+        /* The verified positions are the entry's last 1 + n_spec. Round 1 continues from the last
+         * committed one, which depends on acceptance the card knows and the host does not yet,
+         * so the host bounds it by all of them. A mid-prompt chunk verified nothing. */
         const int64_t vstart = (int64_t)e.ctx_len + e.n_tokens - 1 - e.n_spec;
         const int64_t head_max = vstart + e.n_spec;
         bool can_draft = may_draft && e.produces_token;
 
-        /* THE LOOKAHEAD KV. Round k writes the head's K and V at position head + k - 1, which runs
-         * past the committed end, so the blocks have to exist before the round does -- for the
-         * furthest head acceptance could leave. They are the same blocks the next verify step
-         * writes the trunk's own K and V into, so this reservation is one the next step would
-         * have made anyway.
-         *
-         * A ROW THAT CANNOT HAVE THEM STILL OWES ITS HISTORY. The history pass writes positions
-         * the sequence already holds blocks for, so a refused lookahead is a reason not to draft
-         * and not a reason to skip the row: skipping it would leave the positions this step added
-         * unwritten in the head's layer for good. The same goes for a row too near the end of the
-         * context for its rounds, whose last positions do not exist. */
+        /* Lookahead KV: round k writes the head's K and V at head + k - 1, past the committed end,
+         * so blocks must exist up to the furthest head acceptance could leave. The next verify
+         * writes the trunk's K and V there, so it would reserve them anyway. A row refused
+         * lookahead (or too near the context end) still owes its history, which writes positions
+         * it already has blocks for; skipping it would leave them unwritten in the head's layer. */
         if (can_draft && ctx_limit_ > 0 && head_max + *rounds > ctx_limit_) can_draft = false;
         if (can_draft && kv_->ensure_from(r.id, head_max + *rounds, r.n_computed) < 0)
             can_draft = false;
 
-        /* THE HISTORY THIS STEP OWES, in two parts. Before the verified positions, the positions
-         * the step computed whose next token the host holds -- a prefill chunk's prompt -- from
-         * the watermark on, clamped to the rows this step produced: a prefix-cache hit adopts
-         * blocks whose head layer somebody else wrote, and there are no hidden states here to
-         * redo those from. Then the verified positions themselves, all 1 + n_spec of them, whose
-         * next tokens are the sampler's picks and exist only on the card.
+        /* The history this step owes: first the positions whose next token the host holds (a
+         * prefill chunk's prompt), from the watermark on, clamped to rows this step produced (a
+         * prefix hit's adopted blocks have no hidden states here to redo them from); then all
+         * 1 + n_spec verified positions, whose next tokens exist only on the card.
          *
-         * ALL OF THEM, AND THE LAST ROW IS DRAFT ROUND 1. The card fills the rows past the last
-         * committed position with that position again (advance.h, ADV_HIST), so the final row of
-         * the run always holds exactly round 1's inputs -- the committed position, the trunk's
-         * hidden state there and the token it chose after it -- and a drafting row takes its
-         * round-1 proposal from it (RadBatch::draft_out_ids) instead of from a pass of its own.
-         *
-         * THE VERIFIED PART HAS A FIXED SHAPE. The repeats write the committed position's key and
-         * value again, identical to the first; nothing past it is written, so no query can reach
-         * a rejected draft's state. */
+         * The last row is draft round 1: the card fills rows past the last committed position
+         * with that position again (advance.h, ADV_HIST), so the final row holds round 1's inputs
+         * and a drafting row takes its proposal from it (RadBatch::draft_out_ids). The repeats
+         * rewrite identical K and V and nothing past it is written, so no query can see a
+         * rejected draft's state. */
         const int64_t owed_end = e.produces_token ? vstart : (int64_t)e.ctx_len + e.n_tokens;
         int64_t hs = s.draft_filled > e.ctx_len ? s.draft_filled : (int64_t)e.ctx_len;
         if (hs > owed_end) hs = owed_end;
@@ -2254,9 +2135,8 @@ int Scheduler::serial_begin(int* rounds, SerialRow* out, int max) {
         const int64_t verified = e.produces_token ? e.n_spec + 1 : 0;
         int64_t hist_n = lead + verified;
 
-        /* A HEAD WITH NO CACHE OF ITS OWN IS OWED NO HISTORY (rad_drafter_shared_kv). Its one row
-         * is round 1's -- the committed position, whichever of the verified ones the card says it
-         * is -- and a sequence that does not draft has nothing to run at all. */
+        /* A head with no cache of its own owes no history (rad_drafter_shared_kv). Its one row is
+         * round 1's at the committed position, and a non-drafting sequence runs nothing. */
         if (serial_shared_) {
             if (!can_draft) continue;
             hs = vstart;
@@ -2272,8 +2152,8 @@ int Scheduler::serial_begin(int* rounds, SerialRow* out, int max) {
         m.card       = e.card;
         m.hist_row   = (int32_t)(base + (hs - e.ctx_len));
         m.hist_n     = (int32_t)hist_n;
-        /* The shared head's one row sits wherever the card's acceptance puts it; the host stages
-         * the furthest that can be, as it does for every round. */
+        /* The shared head's one row sits where the card's acceptance puts it; the host stages
+         * the furthest it can be, as for every round. */
         m.hist_pos   = serial_shared_ ? head_max : hs;
         m.dev        = e.produces_token;
         m.dev_tok    = (int32_t)(base + (vstart - e.ctx_len));
@@ -2311,10 +2191,10 @@ const RadBatch* Scheduler::serial_batch(int round, int step) {
     serial_plan_.tok_shift  = 1;           /* the head's own indexing; see StepPlan::tok_shift */
     serial_plan_.e.reserve(serial_.size());
 
-    /* THE DRAFTING SEQUENCES FIRST, in draft order, then the ones that only owe history. Every
-     * round's rows are the drafting sequences in that order, and at depth 1 the history pass is a
-     * group's last pass -- so its first rows are where the advance that takes the last proposal
-     * (ADV_TAKE) reads them, whichever pass that is. */
+    /* Drafting sequences first, in draft order, then history-only ones. Every round's rows are
+     * the drafting sequences in that order, and at depth 1 the history pass is the group's last
+     * pass, so its first rows are where the advance that takes the last proposal (ADV_TAKE)
+     * reads them. */
     for (int part = 0; part < 2; ++part)
     for (size_t i = 0; i < serial_.size(); ++i) {
         const SerialSeq& m = serial_[i];
@@ -2322,8 +2202,8 @@ const RadBatch* Scheduler::serial_batch(int round, int step) {
         if (round == 0 && m.hist_n <= 0) continue;      /* nothing owed for this sequence */
         if (round > 0 && m.draft_idx < 0) continue;     /* history only: no token to propose */
         const Request* rq = serial_req(m);
-        /* Cannot happen while reap() defers on block_holds(), and this is what says so: a whole
-         * round skipped is a lost draft, which costs acceptance for one step and nothing else. */
+        /* Unreachable while reap() defers on block_holds(); if it happens the round is skipped,
+         * costing one step's draft. */
         if (!rq) return nullptr;
 
         StepEntry e;
@@ -2332,20 +2212,19 @@ const RadBatch* Scheduler::serial_batch(int round, int step) {
         e.slot     = m.slot;
         e.card     = m.card;
         e.n_tokens = round == 0 ? m.hist_n : 1;
-        /* A round's position is the card's; the host stages the furthest it can be, which is what
-         * every host-side ceiling reads. The history's are known here exactly. A head with no
-         * cache of its own does not step forward, so neither does its ceiling. */
+        /* A round's position is the card's; the host stages the furthest it can be, which every
+         * host-side ceiling reads. History positions are exact. A head with no cache of its own
+         * does not step forward, so neither does its ceiling. */
         e.ctx_len  = (int32_t)(round == 0 ? m.hist_pos
                                           : m.base_pos + (serial_shared_ ? 0 : round - 1));
         e.n_spec   = 0;
-        /* One-based and constant: a head pass commits exactly the tokens it was handed. The head
-         * issues no linear-state op, so nothing reads it; it is set rather than left at a value
-         * the kernels cannot take. */
+        /* One-based and constant: a head pass commits exactly the tokens it was given. The head
+         * has no linear-state op to read it; it is set to a value the kernels accept. */
         e.n_accepted  = 1;
         e.conv_cursor = 0;
-        /* NO DRAFT ARRAY. A history row's tokens past its lead, and every round's token, are the
-         * card's (advance.h); token_at() stages a 0 in their place, and the positions before the
-         * lead are the prompt, which it stages exactly. */
+        /* No draft array: a history row's tokens past its lead, and every round's token, come
+         * from the card (advance.h); token_at() stages 0 for them, and the positions before the
+         * lead are the prompt, staged exactly. */
         e.draft   = nullptr;
         e.n_draft = 0;
         e.is_prefill     = false;
@@ -2363,14 +2242,9 @@ const RadBatch* Scheduler::serial_batch(int round, int step) {
     }
     if (serial_plan_.e.empty()) return nullptr;
 
-    /* RADIANCE_DEBUG_STAGE: THE BATCH HALF, AND IT IS NOT THE COST. Splits a draft pass into the
-     * plan loop above and `builder_.build`, which stages the block tables and slots, and reports
-     * the average of each. Both are small fractions of what a pass spends ISSUING it
-     * (engine_draft.cpp has the five-way split): staging a draft batch is effectively free, and
-     * the block-table rectangle it copies -- sized for the worst step, not this one -- is not on
-     * any critical path worth shrinking.
-     *
-     * Off by default and it costs two clock reads when it is on, so it can stay. */
+    /* RADIANCE_DEBUG_STAGE: splits a draft pass's host staging into the plan loop above and
+     * `builder_.build`, reporting the average of each. Both are small next to issuing the pass
+     * (engine_draft.cpp has that split). Off by default; two clock reads when on. */
     if (!stg) return builder_.build(serial_plan_, *kv_, step);
 
     static double acc_plan = 0.0, acc_build = 0.0;
@@ -2381,19 +2255,17 @@ const RadBatch* Scheduler::serial_batch(int round, int step) {
     acc_plan  += std::chrono::duration(t1 - t_stage0).count();
     acc_build += std::chrono::duration(t2 - t1).count();
     if (++n_calls % 400 == 0)
-        std::fprintf(stderr, "D stage: %ld draft batches, plan %.1f us, build %.1f us a call\n",
-                     n_calls, acc_plan / (double)n_calls, acc_build / (double)n_calls);
+        RAD_INFO("stage: %ld draft batches; plan %.1f us, build %.1f us a call",
+                 n_calls, acc_plan / (double)n_calls, acc_build / (double)n_calls);
     return b;
 }
 
-/* The watermark moves to what actually ran, and it is read off the COMMITTED sequence: the history
- * pass wrote the head's K and V at the last committed index, n_computed - 1, from the trunk's own
- * hidden state and the committed token, so after it the head's history is exact up to
- * n_computed. The rounds past it write SPECULATIVELY -- correct only for the drafts that turn out
- * to be accepted -- and are deliberately not counted: redoing them next step costs one head pass
- * over a couple of tokens and removes the whole question. A row that only owed history is exact
- * up to where the history reached; that is n_computed too when it covered the verified positions,
- * and its host-known end when it did not. */
+/* The watermark moves to what actually ran, read off the committed sequence: the history pass
+ * wrote the head's K and V at n_computed - 1 from the trunk's hidden state and the committed
+ * token, so the history is exact up to n_computed. Rounds past it write speculatively and are not
+ * counted; redoing them next step costs one head pass over a few tokens. A history-only row is
+ * exact up to where its history reached: n_computed if it covered the verified positions, its
+ * host-known end otherwise. */
 void Scheduler::serial_end(int rounds_done) {
     std::lock_guard lk(mu_);
     for (const SerialSeq& m : serial_) {
@@ -2405,23 +2277,18 @@ void Scheduler::serial_end(int rounds_done) {
         const bool counts = m.dev ? (rounds_done >= 1 || m.draft_idx < 0) : true;
         if (counts && filled > s.draft_filled) s.draft_filled = filled;
     }
-    /* THE SNAPSHOT ENDS HERE. Every pass that names these rows has been built, so nothing reads
-     * them again, and holding them any longer would keep deferring the release of a request that
-     * was cancelled or reaped while the rounds ran. */
+    /* The snapshot ends here: every pass naming these rows is built, and keeping them would keep
+     * deferring the release of a request cancelled or reaped while the rounds ran. */
     serial_.clear();
 }
 
 /* ------------------------------------------------------------------- the block drafter */
-/* Which sequences the drafter runs over after the step just committed, and which of those may also
- * propose. Called while plan() still describes that step, because the context pass MIRRORS it.
- *
- * The mirror is exact, including a verify step's rejected suffix. That is not sloppiness, it is
- * what keeps the pass free of coordinates: the drafter reads the trunk's tapped hidden states
- * positionally out of a buffer of its own, so batch row i must be buffer row i, and trimming
- * one entry would slide every entry after it. The rejected positions are all inside [n_computed,
- * n_computed + block), which the query pass overwrites before anything reads it -- and the one
- * ensure() below covers them, because n_computed + block is at least the trunk step's own end.
- */
+/* Which sequences the drafter runs over after the step just committed, and which of them may
+ * also propose. Called while plan() still describes that step, because the context pass mirrors
+ * it exactly, rejected suffix included: the drafter reads hidden states positionally from its
+ * own buffer, so batch row i must be buffer row i. The rejected positions lie in [n_computed,
+ * n_computed + block), which the query pass overwrites before anything reads them, and the
+ * ensure() below covers them since n_computed + block reaches the trunk step's own end. */
 int Scheduler::block_begin(int block, int depth, int window, int32_t mask, BlockRow* out, int max) {
     std::lock_guard lk(mu_);
     block_.clear();
@@ -2432,14 +2299,16 @@ int Scheduler::block_begin(int block, int depth, int window, int32_t mask, Block
     block_depth_ = (int32_t)depth;
     block_mask_.assign((size_t)(block - 1), mask);
 
-    /* NOT the drafter's declared `depth` above -- this is how many tokens the draft POLICY wants
-     * out of this step, which is zero when it has backed off. The two were both called `depth`. */
+    /* Not the drafter's declared `depth`: whether the draft policy wants any tokens this step
+     * (0 when it has backed off). */
     const bool may_draft = draft_.next_depth() > 0;
-    /* THE QUERY PASS IS `block` TOKENS A DRAFTING SEQUENCE, and the builder's staging arrays are
-     * sized at max_tok. A decode step is one token a sequence, so nothing before this could ever
-     * put more rows in a batch than sequences -- this pass can, and eight rows a sequence against
-     * a small token budget is exactly the shape that would run off the end of h_tok. */
-    if ((int64_t)max * block > cfg_.max_tok) max = (int)(cfg_.max_tok / block);
+    /* The query pass is `block` tokens per drafting sequence, and the builder's staging arrays
+     * are sized at max_tok. Unlike a decode step it can put more rows than sequences in a batch,
+     * which on a small token budget would overrun h_tok. Under --prefill-span a step of several
+     * sequences is bounded by the shared budget instead (RadBuildCtx::max_mixed_tok), which is
+     * max_tok without a span. */
+    const int64_t mixed = geo_.shared_tok > 0 ? geo_.shared_tok : cfg_.max_tok;
+    if ((int64_t)max * block > mixed) max = (int)(mixed / block);
     if (max <= 0) return 0;
 
     int n_draft_rows = 0;
@@ -2453,12 +2322,10 @@ int Scheduler::block_begin(int block, int depth, int window, int32_t mask, Block
         d.ctx_len  = e.ctx_len;
         d.n_tokens = e.n_tokens;
 
-        /* EVERY ENTRY OF THE TRUNK STEP GETS A ROW, IN ORDER, whether or not its sequence is
-         * still running. The drafter reads the trunk's hidden states positionally out of a buffer
-         * of its own, so the context pass's row i has to be the trunk's row i; a sequence the
-         * commit just finished that was left out would put every sequence after it onto its
-         * neighbour's hidden states. It stays as a placeholder row that stores nothing -- see
-         * BlockSeq::mirror. */
+        /* Every entry of the trunk step gets a row, in order, running or not: the context pass's
+         * row i must be the trunk's row i, so leaving out a sequence the commit just finished
+         * would shift every later one onto its neighbour's hidden states. It stays as a
+         * placeholder (BlockSeq::mirror). */
         SchedReq* sp = (e.slot >= 0 && (size_t)e.slot < reqs_.size()) ? reqs_[(size_t)e.slot].get()
                                                                         : nullptr;
         if (!sp || !sp->req || sp->req->id != e.seq || sp->req->state != ReqState::Running ||
@@ -2471,25 +2338,22 @@ int Scheduler::block_begin(int block, int depth, int window, int32_t mask, Block
         Request& r = *s.req;
         d.base_pos = r.n_computed;
 
-        /* MAY IT PROPOSE? It needs a token to anchor on -- which is the one the sampler just
-         * chose, so the entry has to have produced one -- and it needs a draft cache that covers
-         * what the block's attention will read. The high end is this step's own context pass,
-         * which has not run yet and is about to cover everything up to the trunk's end. The low
-         * end is draft_lo, which is non-zero only after a prefix-cache hit THAT LEFT A HOLE. */
+        /* May it propose? It needs an anchor token (the one the sampler just chose, so the entry
+         * produced one) and a draft cache covering what the block's attention reads. The high end
+         * is this step's context pass, about to cover everything up to the trunk's end. The low
+         * end is draft_lo, non-zero only after a prefix-cache hit that left a hole. */
         const bool have_tok = e.produces_token && !r.output.empty() && r.n_computed >= 1;
-        /* Where this sequence's draft cache will start once the context pass about to run has
-         * written: its own floor, or -- for a sequence that has never had one -- wherever this
-         * step's first row sits, which is 0 for an ordinary prefill and the hit length for a
-         * prefix-cache hit. The binding query row is the LOWEST one, at n_computed, and it reads
-         * back to n_computed - window + 1. */
+        /* Where this sequence's draft cache starts once the context pass has run: its own floor,
+         * or for a sequence that never had one, this step's first row (0 for an ordinary prefill,
+         * the hit length after a prefix-cache hit). The binding query row is the lowest, at
+         * n_computed, and it reads back to n_computed - window + 1. */
         const int64_t lo = draft_floor(s, (int64_t)e.ctx_len);
         const bool reach = lo <= 0 ? true
                                    : (window > 0 && r.n_computed - window + 1 >= lo);
 
-        /* RADIANCE_DEBUG_DRAFT: WHICH GATE DECLINED. A drafter that quietly stops proposing reads
-         * downstream as "acceptance collapsed" -- the accept% metric is conditional on having
-         * drafted at all, so it stays healthy while tok/step falls to 1. No counter distinguishes
-         * the two, and nothing else tells the five gates below apart. */
+        /* RADIANCE_DEBUG_DRAFT counts which gate declined. A drafter that silently stops
+         * proposing looks like collapsed acceptance downstream (accept% is conditional on
+         * drafting), and no other counter tells the five gates apart. */
         const bool ok_room = n_draft_rows < max;
         /* The query block writes positions n_computed .. n_computed + block - 1, and none of them
          * may be at or past the end of the context. */
@@ -2540,11 +2404,10 @@ const RadBatch* Scheduler::block_context(int step) {
 
     for (const BlockSeq& d : block_) {
         const Request* rq = block_req(d);
-        /* Cannot happen while reap() defers on block_holds(), and this is what says so: a whole
-         * round skipped is a lost draft, which costs acceptance for one step and nothing else.
-         * A placeholder row may have lost its Request before block_begin ran -- the server reaps
-         * a finished request as soon as its sink is done -- and needs none: this pass reads no
-         * token ids, and its KV is gone, so the builder stages it as padding. */
+        /* Unreachable for a live row while reap() defers on block_holds(); if it happens the pass
+         * is skipped, costing one step's draft. A placeholder row may have lost its Request
+         * before block_begin (the server reaps a finished request as soon as its sink is done)
+         * and needs none: this pass reads no token ids and the builder stages it as padding. */
         if (!rq && !d.mirror) return nullptr;
         StepEntry e;
         e.req        = rq;
@@ -2555,8 +2418,8 @@ const RadBatch* Scheduler::block_context(int step) {
         e.ctx_len    = d.ctx_len;
         e.n_spec     = 0;
         e.n_accepted = 1;               /* one-based; nothing in this pass reads it */
-        /* The context pass touches no token ids at all -- it starts from the tapped hidden states
-         * -- so there is nothing to shift and no draft to reach into. */
+        /* The context pass reads tapped hidden states, not token ids: nothing to shift and no
+         * draft. */
         e.produces_token = false;
         block_plan_.e.push_back(e);
         block_plan_.n_tok += e.n_tokens;
@@ -2565,15 +2428,15 @@ const RadBatch* Scheduler::block_context(int step) {
     return builder_.build(block_plan_, *kv_, step);
 }
 
-/* One entry a drafting sequence, `block` tokens: the anchor at the sequence's next position, then
- * `block - 1` masks. `out_ids` names THE LAST `depth` ROWS.
+/* One entry per drafting sequence, `block` tokens: the anchor at the sequence's next position,
+ * then `block - 1` masks. `out_ids` names the last `depth` rows.
  *
- * AT block = depth + 1 that is rows 1..depth, the mask rows: the anchor row predicts nothing and
- * each mask row predicts the token at ITS OWN position (vLLM's _prepare_dflash_inputs_kernel:
- * is_sample = query_off >= 1, sample_pos = query_pos). AT block = depth it is every row, anchor
- * included, and each predicts the token AFTER it -- the ordinary next-token relation, which is
- * what a drafter whose reference reads `hidden[:, -block_size:, :]` was trained in. One rule,
- * both conventions; rad_builder.h argues why the plugin is what states which. */
+ * At block = depth + 1 those are the mask rows: the anchor predicts nothing and each mask row
+ * predicts the token at its own position (vLLM's _prepare_dflash_inputs_kernel: is_sample =
+ * query_off >= 1, sample_pos = query_pos). At block = depth it is every row, anchor included,
+ * each predicting the token after it: the ordinary next-token relation that a drafter whose
+ * reference reads `hidden[:, -block_size:, :]` was trained in. rad_builder.h explains why the
+ * plugin states which. */
 const RadBatch* Scheduler::block_query(int step) {
     std::lock_guard lk(mu_);
     if (block_.empty() || block_len_ < 2 || block_depth_ <= 0) return nullptr;
@@ -2604,21 +2467,9 @@ const RadBatch* Scheduler::block_query(int step) {
         e.draft      = block_mask_.data();
         e.n_draft    = steps;
         e.produces_token = false;
-        /* THE LAST `depth` ROWS OF THE BLOCK. At block = depth + 1 that skips the anchor; at
-         * block = depth it starts on it, because there the anchor row is a predicting row.
-         *
-         * RADIANCE_DFLASH_ANCHOR=1 slides the head one row EARLIER, onto the anchor, and so does
-         * nothing at block = depth where it already sits there. The anchor is an ordinary row: a
-         * real token, embedded, with the whole context behind it -- so its hidden state predicts
-         * the token at base_pos + 1, which is exactly what draft[0] is verified against. A healthy
-         * backbone therefore accepts at position 0 most of the time, and a broken one does not. It
-         * is the same measurement the hazard counter already makes, pointed at a row whose answer
-         * is known. Debug-only: it drafts `depth` tokens for `depth` positions starting one too
-         * early, so positions 1.. are deliberately misaligned and only position 0 means anything. */
-        static const bool anchor_head = std::getenv("RADIANCE_DFLASH_ANCHOR") != nullptr;
-        int32_t head0 = block - depth;
-        if (anchor_head && head0 > 0) head0 = 0;
-        e.hidden_row = row + head0;
+        /* The last `depth` rows of the block: at block = depth + 1 this skips the anchor; at
+         * block = depth it starts on it. */
+        e.hidden_row = row + block - depth;
         e.hidden_n   = depth;
         block_plan_.e.push_back(e);
         block_plan_.n_tok += block;
@@ -2628,10 +2479,9 @@ const RadBatch* Scheduler::block_query(int step) {
     return builder_.build(block_plan_, *kv_, step);
 }
 
-/* The filled range moves over what the context pass wrote. The query pass's own K and V are
- * SPECULATIVE -- correct only for the positions that turn out to be accepted -- and are
- * deliberately not counted: the next step's context pass rewrites them from the trunk's real
- * hidden states, which is one pass over a handful of rows and removes the whole question. */
+/* The filled range moves over what the context pass wrote. The query pass's K and V are
+ * speculative and not counted; the next step's context pass rewrites them from the trunk's real
+ * hidden states. */
 void Scheduler::block_end() {
     std::lock_guard lk(mu_);
     for (const BlockSeq& d : block_) {
@@ -2643,9 +2493,8 @@ void Scheduler::block_end() {
         const int64_t hi = (int64_t)d.ctx_len + d.n_tokens;
         if (hi > s.draft_hi) s.draft_hi = hi;
     }
-    /* THE SNAPSHOT ENDS HERE. Both passes are built, so nothing reads these rows again, and
-     * holding them any longer would keep deferring the release of a request that was cancelled
-     * or reaped while the passes ran. */
+    /* The snapshot ends here: both passes are built, and keeping the rows would keep deferring
+     * the release of a request cancelled or reaped while the passes ran. */
     block_.clear();
 }
 
@@ -2700,14 +2549,9 @@ SchedMetrics Scheduler::metrics_locked() const {
     for (int32_t slot : waiting_)
         if (reqs_[(size_t)slot]->req->state == ReqState::Preempted) ++m.preempted_waiting;
 
-    /* AND AN IDLE ENGINE RUNS NO STEPS AT ALL, so the window never moves and the last rate would
-     * stand forever. Decayed on the way out rather than mutated in place: the stored window is a
-     * property of the steps that ran, and this is the honest reading of "tokens a second over the
-     * recent past" when the recent past contains no tokens -- to 37% after half a second of
-     * silence, to nothing after a few.
-     *
-     * NOT WHILE A STEP IS OPEN: a 2048-token prefill chunk runs for a third of a second, and a
-     * read halfway through it is not a read of an idle engine. */
+    /* An idle engine runs no steps, so the window would hold the last rate forever. Decay it on
+     * the way out (to 37% after half a second idle) without touching the stored window. Not while
+     * a step is open: a long prefill chunk is not idleness. */
     const bool   open = step_start_.time_since_epoch().count() != 0;
     const double idle = open ? 0.0
         : std::chrono::duration(std::chrono::steady_clock::now() - last_step_at_).count();
@@ -2719,16 +2563,14 @@ SchedMetrics Scheduler::metrics_locked() const {
         if (m.decode_tps  < 0.05f) m.decode_tps  = 0.0f;
     }
 
-
     const std::vector& gs = prog_->kv_groups;
     m.n_kv_groups = (int)gs.size();
     if (m.n_kv_groups > RAD_SCHED_MAX_KV_GROUPS) m.n_kv_groups = RAD_SCHED_MAX_KV_GROUPS;
     for (int i = 0; i < m.n_kv_groups; ++i) {
-        /* AGAINST THE CARVE AND WHAT IS HELD OF IT, not against the live mark. An elastic pool
-         * grows back on demand, so a block it has released is not occupied and is not
-         * unavailable; counting it as either makes an idle server read almost full and makes
-         * every decision downstream that watches kv_util read the pool's own arbitration as
-         * pressure from the workload. */
+        /* Against the carve and what is held of it, not the live mark. An elastic pool grows
+         * back on demand, so a released block is neither occupied nor unavailable; counting it
+         * would make an idle server read nearly full and turn the pool's own arbitration into
+         * apparent workload pressure for anything watching kv_util. */
         const int64_t tot = kv_->total_blocks(i);
         const int64_t fr  = tot - kv_->held_blocks(i);
         m.kv[i].name = gs[(size_t)i].name.c_str();
@@ -2744,6 +2586,10 @@ SchedMetrics Scheduler::metrics_locked() const {
 
     if (pc_) { m.prefix_evictions = pc_->evictions();
                m.prefix_ckpt_evictions = pc_->ckpt_evictions();
+               const IPrefixCache::CkptCounts cc = pc_->ckpt_counts();
+               m.prefix_ckpt_retired = cc.retired;
+               m.prefix_ckpt_lru = cc.lru;
+               m.prefix_ckpt_refused = cc.refused;
                m.prefix_expired = pc_->expired();
                m.prefix_ckpt_expired = pc_->ckpt_expired();
                m.prefix_held_tokens = pc_->held_tokens(); }
@@ -2753,12 +2599,9 @@ SchedMetrics Scheduler::metrics_locked() const {
         ? (float)((double)m.linear_cached_tokens / (double)m.prompt_tokens) : 0.0f;
     m.draft_acceptance = draft_.acceptance();
     m.draft_depth = draft_.next_depth();
-    /* THE LOOP BOUND IS THE ARRAY'S OWN EXTENT, not a constant that happens to equal it. Clamping
-     * against RAD_SCHED_MAX_SPEC is correct -- depth_seen() is capped at it and both arrays are
-     * that long -- but the bound and the extent merely being the same number leaves gcc unable to
-     * rule out the boundary index through the inlined accessors, which guard with
-     * `j < RAD_SCHED_MAX_SPEC ? reach_[j] : 0`, and it warns. Writing the cap as the extent makes
-     * the two provably the same rather than coincidentally equal. */
+    /* The loop bound is the array's extent, not RAD_SCHED_MAX_SPEC: the values are equal, but gcc
+     * cannot prove the boundary index safe through the inlined accessors (which guard with
+     * `j < RAD_SCHED_MAX_SPEC ? reach_[j] : 0`) and warns. */
     const int kPos = (int)(sizeof m.draft_pos_reached / sizeof m.draft_pos_reached[0]);
     m.draft_depth_seen = draft_.depth_seen();
     if (m.draft_depth_seen > kPos) m.draft_depth_seen = kPos;
diff --git a/core/sched/scheduler.h b/core/sched/scheduler.h
index 733064f1..bcfe6106 100644
--- a/core/sched/scheduler.h
+++ b/core/sched/scheduler.h
@@ -1,21 +1,15 @@
-/* scheduler.h -- continuous batching, chunked prefill, a priority queue, preemption by recompute.
- * ONE scheduler decision per step, producing ONE RadBatch (spec §7.1).
+/* scheduler.h -- continuous batching, chunked prefill, a priority queue and preemption by
+ * recompute. One scheduler decision per step, producing one RadBatch (spec §7.1).
  *
- * Host time spent here is time the GPU spends idle, so this component is written to be cheap and
- * to build things once. Everything on the step path comes out of a pool sized at max_tok /
- * max_seqs; the only allocation the scheduler performs is on arrival and completion, which are
- * the HTTP thread's problem and not the step's.
+ * Host time spent here is GPU idle time. The step path allocates nothing: its storage is sized at
+ * max_tok / max_seqs, and allocation happens only on arrival and completion (HTTP threads).
  *
- * Two things it owns that vLLM's does not:
- *
- *   - CHUNK BOUNDARIES, and it uses that. A prefill chunk splits at a linear-state checkpoint
- *     interval, so a checkpoint is always WRITTEN rather than landing wherever a step happened to
- *     end. vLLM writes one only when a step's end coincides with a boundary, which is why a
- *     checkpoint landing in request-unique tokens silently drops linear caching to zero. The cost
- *     of doing it this way is an occasional short chunk; the benefit is that hit rate is a
- *     property of the workload rather than of scheduling luck (§7.3).
- *
- *   - DRAFT DEPTH, controlled against measured acceptance (draft.h, §10).
+ * Unlike vLLM's scheduler it also owns:
+ *   - Chunk boundaries. A prefill chunk splits at a linear-state checkpoint interval, so a
+ *     checkpoint is always written instead of only when a step happens to end on a boundary.
+ *     The cost is an occasional short chunk; the hit rate then depends on the workload, not on
+ *     scheduling luck (§7.3).
+ *   - Draft depth, controlled against measured acceptance (draft.h, §10).
  */
 #pragma once
 #include "batch.h"
@@ -30,26 +24,20 @@
 namespace rad {
 
 /* The scheduler's own per-request state. Request (rad_core.h) is shared across components and
- * frozen; anything only the scheduler needs lives here, so adding a scheduling concept never
- * touches a struct three other components read. */
+ * frozen; state only the scheduler needs lives here. */
 struct SchedReq {
     std::unique_ptr req;
-    uint64_t arrival = 0;        /* monotonic; the tiebreak below priority, and what makes a
-                                  * preempted request re-enter AHEAD of everything admitted after
-                                  * it rather than at the back of the queue */
+    uint64_t arrival = 0;        /* monotonic; the tiebreak below priority. A preempted request
+                                  * keeps it, so it re-enters ahead of later arrivals */
     int32_t  slot = -1;
-    /* THE CARD'S INDEX FOR THIS SEQUENCE: which StepSlot the advance reads and writes (advance.h),
-     * and so the sequence identity a batch carries. It is NOT `slot`. A slot is taken on arrival,
-     * so a queue behind the admission limit -- or a burst arriving while the last one's requests
-     * are still held for their final commit -- numbers slots past max_seqs, and the card has
-     * max_seqs StepSlots. The card index is taken on admission from a pool of exactly that many
-     * and given back with the sequence's KV (free_kv, preempt_back), so it lives as long as any
-     * step in flight can still name it and never longer. */
+    /* The card's index for this sequence: the StepSlot the advance reads and writes (advance.h),
+     * and the sequence identity a batch carries. Not `slot`, which is taken on arrival and can
+     * exceed the card's max_seqs StepSlots. Taken on admission from a pool of max_seqs and
+     * returned with the sequence's KV (free_kv, preempt_back). */
     int32_t  card = -1;
     bool     running = false;
 
-    /* WALL CLOCK, for the live request table. `arrival` above is a monotonic COUNTER -- it
-     * orders the queue and cannot say how long anything has been in it. */
+    /* Wall clock, for the live request table; `arrival` is a counter and cannot measure time. */
     int64_t  arrived_us = 0;
     int64_t  first_tok_us = 0;   /* 0 until the first output token: this request's TTFT */
 
@@ -59,47 +47,22 @@ struct SchedReq {
     int32_t  n_draft = 0;
     int32_t  conv_cursor = 0;
 
-    /* HOW MUCH OF A SERIAL DRAFTER`S OWN ATTENTION HISTORY IS VALID: positions [0, draft_filled)
-     * of the head`s layer hold K and V computed from the tokens the sequence actually has. The
-     * head attends to its own layer and nothing else in the engine writes it -- a prefill fills
-     * the trunk`s layers and leaves the head`s untouched -- so the drafter runs a history pass
-     * over whatever the last step added before it drafts. Zero on admission and on preemption,
-     * which is what makes a recomputed sequence refill it rather than trust a stale watermark. */
+    /* A serial drafter's valid history: positions [0, draft_filled) of the head's own layer hold
+     * K and V for the sequence's real tokens. Only the head writes that layer, so before drafting
+     * it runs a history pass over what the last step added. */
     int64_t  draft_filled = 0;
 
-    /* THE RANGE OF A BLOCK DRAFTER'S OWN KV CACHE THAT HOLDS REAL K AND V, as [draft_lo,
-     * draft_hi). Two numbers rather than a serial head's one because the low end CAN move: such a
-     * drafter has a KV group of its own, and whether a hit leaves that group short depends on
-     * whether prefix.cpp caches it -- see hit_holes_draft_. A WINDOWED drafter's group is skipped
-     * (a hit's blocks do not describe a cache whose floor moves), so a sequence that hits at
-     * position P has trunk K and V from 0 and draft K and V only from P, and drafting waits until
-     * the drafter's window has slid past P rather than attending to blocks nobody wrote.
-     *
-     * A FULL-ATTENTION DRAFTER'S GROUP IS CACHED LIKE THE TRUNK'S and the floor stays 0. Treating
-     * one as windowed disables drafting outright: a windowless drafter has no window to slide, so
-     * "wait until the window has passed P" is a condition that can never come true, and a workload
-     * that hits the prefix cache on every turn would then never draft again.
-     * Both zero on admission and on preemption, which is what makes a recomputed sequence refill
-     * rather than trust a stale watermark. */
+    /* The range [draft_lo, draft_hi) of a block drafter's own KV cache that holds real K and V.
+     * The low end is non-zero when a prefix hit left the drafter's group uncached
+     * (hit_holes_draft_); drafting then waits until the window has slid past it. */
     int64_t  draft_lo = 0;
     int64_t  draft_hi = 0;
 
-    /* EVERY PIECE OF DRAFTER STATE THAT DESCRIBES THE SEQUENCE IN THIS SLOT, cleared together.
-     *
-     * A slot is RECYCLED: add() takes one off `free_slots_` and the SchedReq in it is the last
-     * request's object, so anything not reset here is inherited by a sequence that has nothing to
-     * do with it. Both watermarks above say "zero on admission and on preemption", and a list of
-     * fields spelled out at each call site is what lets one of them go unreset; hence one function,
-     * called from both.
-     *
-     * WHAT A SURVIVING WATERMARK COSTS. `draft_filled` carried into the next request at the
-     * previous one's total length makes its prefill compute `hs = max(draft_filled, ctx_len)` =
-     * the stale watermark, `he` clamps up to meet it, and the history pass comes out EMPTY -- so
-     * the MTP head's layer of the attention cache is never written for the whole prompt and the
-     * head drafts against whatever the pool last held. The drafts are then wrong, so acceptance
-     * moves, so the committed lengths move, so the arithmetic of every later step moves: the same
-     * greedy prompt yields a different completion per request, reproducible request-for-request
-     * across processes, and only ever with speculation on. */
+    /* Clears all drafter state for the sequence in this slot, on admission and on preemption.
+     * Slots are recycled, so anything not reset here leaks into an unrelated sequence: a stale
+     * `draft_filled`, for one, empties the next prefill's history pass (hs = max(draft_filled,
+     * ctx_len)), and the MTP head drafts against stale pool contents, making greedy output vary
+     * per request with speculation on. */
     void drafter_reset() {
         n_draft      = 0;
         draft_next   = 0;
@@ -109,56 +72,44 @@ struct SchedReq {
         draft_hi     = 0;
     }
 
-    /* THE ADAPTIVE DRAFT WINDOW'S ESTIMATE FOR THIS REQUEST (--draft-window adaptive, draft.h), and
-     * deliberately NOT in drafter_reset(): it describes the text the request is writing, which a
-     * preemption does not change, rather than any cache the request holds. A recycled slot starts
-     * it over in add_locked. Untouched while the policy is off. */
+    /* The adaptive draft window's estimate (--draft-window adaptive, draft.h). Not reset by
+     * drafter_reset(): it describes the text, which preemption does not change. */
     DraftAdapt adapt;
     /* The proposal the step being planned carries came from prompt lookup (StepEntry::ngram). */
     bool       draft_ngram = false;
 
     int32_t  sched_tokens = 0;   /* tokens given to this request in the current step */
     int32_t  entry = -1;         /* its index in the current StepPlan, or -1 */
-    /* Its index in the NEXT step, already issued while this one runs (step_next), or -1; and the
+    /* Its index in the next step, already issued while this one runs (step_next), or -1; and the
      * drafts the drafter issued for it, which that step verifies. */
     int32_t  entry_next = -1;
     int32_t  draft_next = 0;
 
-    /* Cancelled while its tokens were in the step the device is still running, or while a
-     * drafter's snapshot still names it. Its blocks are released at commit rather than now,
-     * because handing a block to another sequence while a kernel is still writing it is a data
-     * race whose symptom is one sequence's KV appearing in another's attention -- and it would
-     * present as a model quality problem. A drafter pass built after the free would be worse
-     * still: its block-table row is all -1 with a non-zero length, and attention reads block -1,
-     * which is below the layer's region of the pool. */
+    /* Cancelled while a step in flight or a drafter snapshot still names it; its blocks are
+     * released once nothing does. Freed earlier, a kernel still writing a block would put one
+     * sequence's KV in another's attention, and a drafter pass built after the free would carry
+     * an all -1 block-table row with a non-zero length, reading block -1 below the pool. */
     bool     pending_free = false;
-    /* REAPED WHILE ITS TOKENS WERE IN THE STEP THE DEVICE IS STILL RUNNING, which is the same
-     * window `pending_free` covers and a strictly worse thing to get wrong. The server reaps a
-     * generation as soon as its sink is finished, and cancelling a request finishes the sink
-     * immediately -- so a client that disconnects mid-decode has its Request destroyed and its
-     * slot handed back while commit() still holds a StepEntry pointing at that slot. commit() then
-     * dereferences a null `req`, or worse, finds the slot re-admitted and commits one client's
-     * tokens into another's output. The release is deferred to commit instead. */
+    /* Reaped in the same window. A disconnect finishes the sink and the server reaps at once;
+     * destroying the Request then would leave commit() reading a null `req`, or committing one
+     * client's tokens into a re-admitted slot. */
     bool     reap_pending = false;
     int64_t  pending_ckpt = -1;  /* absolute position this step's chunk checkpoints at */
 
-    /* The checkpoint the linear state should be SEEDED from on admission. Neither Request nor
-     * KVManager::ensure carries it, so the scheduler holds the answer here and hands it to the
-     * sequence's first entry as StepEntry::ckpt_restore.
-     *
-     * NEVER HELD ACROSS A STEP. A checkpoint slot is only the cache's until the cache retires it,
-     * and between two steps the retention policy, another admission's reservation or an idle
-     * tier can retire it, reallocate it and save a different sequence into it -- nothing pins it.
-     * So an admission that fails after the lookup gives the hit back (admit_one) and the next
-     * attempt looks it up again, rather than restoring whatever the slot holds by then. */
+    /* The checkpoint the linear state is seeded from on admission, handed to the sequence's first
+     * entry as StepEntry::ckpt_restore. Never held across a step: nothing pins a checkpoint slot,
+     * so a failed admission gives the hit back (admit_one) and the next attempt looks it up
+     * again. */
     int32_t  ckpt_src = -1;
 
     /* The prefix hit this admission attempt found, in tokens, and whether its accounting is still
-     * owed. Counted once, when the admission SUCCEEDS: a request at the head of the queue that
-     * does not fit is retried every step, and counting each attempt would inflate the prompt and
-     * hit totals by however long it waited. */
+     * owed. Counted once, when admission succeeds; counting each retry of a request that does not
+     * fit would inflate the prompt and hit totals. */
     int32_t  hit_attn = 0;
     bool     hit_owed = false;
+    /* Why that hit was cut to nothing, for the counters (SchedMetrics::hit_cut_*). */
+    enum class HitCut : uint8_t { None, NoSnapshot, Window, Adopt };
+    HitCut   hit_cut = HitCut::None;
 
     /* The whole sequence is prompt ++ output; n_computed indexes into it. */
     int64_t  seq_len() const {
@@ -168,31 +119,30 @@ struct SchedReq {
 
 class Scheduler {
 public:
-    /* What the sampler hands back after a step. The scheduler needs three numbers per sequence and
-     * no logits: how many drafted tokens survived, the token sampled at the accepted position, and
-     * whether the sequence ended. Everything else is the sampler's business. */
+    /* What the sampler hands back after a step: per sequence, how many drafts survived, the token
+     * sampled at the accepted position, and whether the sequence ended. No logits. */
     struct StepResult {
         int             n_seq = 0;
         const int32_t*  n_accepted = nullptr;  /* [n_seq] drafted tokens accepted, 0..n_spec */
         const int32_t*  token = nullptr;       /* [n_seq] token sampled at the accepted position */
         const uint8_t*  eos = nullptr;         /* [n_seq] 1 when the sequence ended */
-        /* LOGPROBS, null on a step where no request asked: entry i's j-th emitted token (its
+        /* Logprobs, null on a step where no request asked: entry i's j-th emitted token (its
          * accepted drafts first, then the sampled token) is lp[first_row[i] + j]. */
         const TokenLogprobs* lp = nullptr;
         const int32_t*       first_row = nullptr;  /* [n_seq] */
     };
 
-    /* `geo` is the already-resolved chunk geometry. The engine resolves it once and passes it,
-     * because PrefixCache::configure needs the checkpoint interval out of it and runs first;
-     * pass nullptr to resolve one here instead. */
+    /* `geo` is the already-resolved chunk geometry. The engine resolves it once because
+     * PrefixCache::configure runs first and needs its checkpoint interval; pass nullptr to
+     * resolve one here. */
     int  init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCache* pc,
               const std::vector& ranks,
               const ChunkGeometry* geo = nullptr);
 
     /* The batch the last build produced for one rank; see BatchBuilder::batch_for. */
     const RadBatch* batch_for(int rank) const { return builder_.batch_for(rank); }
-    /* The advance's view of that build on one rank; see BatchBuilder::advance_args. It carries
-     * the serial head's shape as well, which only the draft passes' modes read. */
+    /* The advance's view of that build on one rank; see BatchBuilder::advance_args. Also carries
+     * the serial head's shape, which only the draft passes' modes read. */
     AdvanceArgs advance_args(int rank) const {
         AdvanceArgs a = builder_.advance_args(rank);
         a.shared_kv = serial_shared_ ? 1 : 0;
@@ -204,39 +154,30 @@ public:
     /* ---------------------------------------------------------- off the step path */
     int      add(std::unique_ptr r);
     /* `n` requests under one hold of the queue lock, each accepted or refused as add() would, with
-     * its result in rc[i]. For the sequences of one API request, which have to reach the same
-     * step. */
+     * its result in rc[i]. For the sequences of one API request, which must reach the same step. */
     void     add_all(std::unique_ptr* rs, size_t n, int* rc);
-    /* Cancellation propagates to the scheduler and frees blocks IMMEDIATELY rather than at
-     * completion (spec §14). A cancelled request holding its blocks until the step that would
-     * have finished it is a pool that shrinks under exactly the load that cancels. */
+    /* Frees blocks immediately rather than at completion (spec §14); otherwise the pool shrinks
+     * under exactly the load that cancels. */
     int      cancel(uint64_t id);
     Request* find(uint64_t id);
 
-    /* Requests that reached a terminal state since the last call, oldest first, SWAPPED OUT under
-     * the lock into `out` (whose old contents are discarded). The engine drains this to drop its
-     * per-request sampler state; it is the only consumer. The server does not read it -- it
-     * learns of a terminal request through the sink and calls reap(), which is what finally
-     * releases the Request object.
-     *
-     * A swap rather than a reference: an HTTP thread's cancel() appends to this list under the
-     * lock, and a caller walking a reference to it without the lock walks a vector another thread
-     * may be reallocating. Handing the same vector back and forth also keeps both capacities, so
-     * a steady state allocates nothing. */
+    /* Requests that reached a terminal state since the last call, oldest first, swapped into
+     * `out` under the lock (old contents discarded). Only the engine consumes it, to drop
+     * per-request sampler state; the server learns through the sink and calls reap(). A swap
+     * because cancel() appends from HTTP threads; swapping the same vectors keeps both
+     * capacities, so steady state allocates nothing. */
     void     take_completed(std::vector* out);
     int      reap(uint64_t id);
 
     /* ---------------------------------------------------------- the lock, for the engine
      *
-     * EVERY MUTATION OF THE KV MANAGER AND THE PREFIX CACHE HAPPENS UNDER THIS LOCK. Neither has
-     * a lock of its own, and both are reached from two kinds of thread: the step path, and HTTP
-     * threads running cancel(), reap() and reset_prefix_cache(), which publish into the cache,
-     * evict from it and free sequences. The engine's own passes between steps -- the idle tiers,
-     * the elastic rebalance, the checkpoint copies -- mutate the same structures, so they run
-     * inside this too. Taken once per pass that has work, never per sequence.
+     * Every mutation of the KV manager and the prefix cache happens under this lock; neither has
+     * its own, and both are reached from the step path, from HTTP threads (cancel(), reap(),
+     * reset_prefix_cache()) and from the engine's passes between steps (idle tiers, elastic
+     * rebalance, checkpoint copies). Taken once per pass that has work, never per sequence.
      *
-     * NOTHING RUN UNDER IT MAY CALL BACK INTO THE SCHEDULER: the mutex is not recursive, and
-     * every public method here takes it. */
+     * Nothing run under it may call back into the scheduler: the mutex is not recursive and every
+     * public method takes it. */
     template  auto locked(Fn&& fn) {
         std::lock_guard lk(mu_);
         return fn();
@@ -247,32 +188,25 @@ public:
     /* ---------------------------------------------------------- work the device still owes
      *
      * A request cancelled while a drafter pass was being built keeps its blocks until the passes
-     * that name them are done (see SchedReq::pending_free). commit() releases them once nothing
-     * refers to them; an engine that has gone idle runs no commit, so it drains its streams and
-     * calls release_deferred() instead. has_deferred() is the cheap test for whether that is
-     * needed at all. */
+     * that name them are done (SchedReq::pending_free). commit() releases them; an idle engine
+     * runs no commit, so it drains its streams and calls release_deferred() instead.
+     * has_deferred() is the cheap test for whether that is needed. */
     bool     has_deferred() const;
     void     release_deferred();
 
-    /* THE ENGINE HAS STOPPED AND WILL RUN NO MORE STEPS. Every request still queued or running is
-     * failed with `reason` so its connection is answered rather than left waiting on a step that
-     * will never come, and any request submitted afterwards is refused the same way. `status` is
-     * what stopped it, and what each of those requests reports. */
+    /* The engine has stopped and will run no more steps. Every queued or running request is
+     * failed with `reason` so its connection gets an answer, and later submissions are refused the
+     * same way. `status` is the cause, and what each of those requests reports. */
     void     shutdown(const char* reason, int status = RAD_E_STATE);
 
-    /* The waiting queue in SERVICE order, by request id -- what the live view shows and what a
-     * test asserts a preempted request re-entered at the front of. Returns how many were written. */
+    /* The waiting queue's request ids in service order, for the live view and for tests (a
+     * preempted request re-enters at the front). Returns how many were written. */
     int      queue_snapshot(uint64_t* out, int max) const;
 
     /* ---------------------------------------------------------- who is in flight
      *
-     * WHAT EVERY REQUEST IS DOING RIGHT NOW, for the dashboard and for anyone debugging a stall.
-     * The aggregate metrics answer "is the engine busy"; they cannot answer "which of these eight
-     * is stuck", and a request that has been in `Waiting` for forty seconds because its prompt
-     * does not fit is invisible in every number above.
-     *
-     * A snapshot under the step lock, copied out: holding a pointer into the scheduler's storage
-     * across a step is holding a pointer to a request that may be reaped. */
+     * Per-request state for the dashboard and for debugging a stall. Copied out under the step
+     * lock, since a pointer into scheduler storage could outlive a reaped request. */
     struct ReqStat {
         uint64_t id = 0;
         int      state = 0;            /* ReqState, as an int -- the caller has the enum */
@@ -283,9 +217,9 @@ public:
         int64_t  output_tokens = 0;
         int64_t  max_tokens = 0;
         int64_t  ctx_tokens = 0;       /* prompt ++ output */
-        /* THIS REQUEST'S SHARE OF THE PAGED POOLS, summed over every paged group: the blocks it
-         * holds and the tokens they cover. `ctx_tokens` is what it is USING; this is what it has
-         * TAKEN, and they differ by a partial block and by whatever a rejected draft left. */
+        /* This request's share of the paged pools: the blocks it holds and the tokens they cover.
+         * It differs from `ctx_tokens` (what it uses) by a partial block and by whatever a
+         * rejected draft left. */
         int64_t  kv_blocks = 0;
         int64_t  kv_tokens = 0;
         int32_t  n_draft = 0;          /* the proposal standing for the next step */
@@ -294,8 +228,8 @@ public:
         double   ttft_s = -1;          /* negative until the first token */
         double   decode_tps = 0;       /* this request's own, since its first token */
     };
-    /* Newest first is wrong here: a dashboard wants the oldest at the top, because the oldest is
-     * the one that is stuck. Returns how many were written. */
+    /* Oldest first, since the oldest is the one most likely stuck. Returns how many were
+     * written. */
     int requests(ReqStat* out, int max) const;
 
     /* The drafter's proposal for a request's next step. n is clamped to the sequence's window
@@ -303,11 +237,9 @@ public:
     int      set_draft(uint64_t id, const int32_t* tokens, int n);
 
     /* ---------------------------------------------------------- media the encoder owes
-     * A REQUEST CARRYING MEDIA IS ADMITTED ONLY ONCE EVERY ITEM IS ENCODED. Until then it keeps
-     * its place in the queue, the requests behind it are admitted around it, and its items wait
-     * here for the engine, which runs the encoder between steps and marks them done (take_encodes).
-     * Encoding before admission rather than chunk by chunk keeps the encoder off the step path:
-     * a step never waits for a tower, and the batch builder only ever copies rows that exist. */
+     * A request carrying media is admitted only once every item is encoded; until then it keeps
+     * its queue position and later requests are admitted around it. The engine takes the items
+     * (take_encodes) and encodes them between steps, which keeps the encoder off the step path. */
     bool     encodes_pending() const;
     void     take_encodes(std::vector>* out);
     /* An encoder pass over whole segments; see BatchBuilder::build_encoder. */
@@ -317,79 +249,61 @@ public:
         return builder_.build_encoder(parts, step, enc);
     }
 
-    /* Drop every prefix-cache entry, returning how many were dropped, or RAD_E_UNSUPPORTED when
-     * this engine has no prefix cache. Under the step lock: releasing the cache's references is
-     * safe against a running step -- a block a live sequence holds stays allocated because the
-     * sequence holds its own reference -- but the map itself is not, and the step path inserts
-     * into it. See IScheduler::reset_prefix_cache for why the endpoint exists. */
+    /* Drop every prefix-cache entry; returns how many, or RAD_E_UNSUPPORTED without a prefix
+     * cache. Takes the step lock because the step path inserts into the map (live sequences hold
+     * their own block references). See IScheduler::reset_prefix_cache. */
     int64_t  reset_prefix_cache();
 
     /* ---------------------------------------------------------- the step path */
     /* One decision, one batch. Null when there is nothing to run, which is not an error. */
     const RadBatch* step();
 
-    /* ---------------------------------------------------- THE NEXT STEP, BEFORE THIS ONE COMMITS
+    /* ---------------------------------------------------- the next step, before this one commits
      *
-     * A decode step's successor does not need anything the host learns from the step: every row
-     * continues where the card's acceptance leaves it (sched/advance.h), with the drafts the
-     * drafter proposed on the card, and the host can bound how far that is. So the engine issues
-     * the next step's forward pass while this one is still running, and the card goes straight
-     * from one to the other.
+     * A decode step's successor needs nothing the host learns from it: every row continues where
+     * the card's acceptance leaves it (sched/advance.h), with drafts proposed on the card, and the
+     * host can bound how far that is. So the next forward pass is issued while this one runs.
      *
-     *   expect_draft   after the drafter is issued: how many drafts it proposes for a sequence,
-     *               which is how many the next step verifies -- capped at the sequence's window,
-     *               which under the adaptive policy can be fewer than the rounds that ran.
+     *   expect_draft   after the drafter is issued: how many drafts the next step verifies for a
+     *               sequence, capped at its window (under the adaptive policy possibly fewer
+     *               than the rounds that ran).
      *   step_next      plans and builds that step: every row of this one, as a device row, at
-     *               the furthest context it can reach. Null -- and the engine plans with step()
-     *               after this one commits -- whenever the step needs a decision only a
-     *               committed state can make: a request waiting for admission, a prefill chunk
-     *               to continue, a grammar, the context's end, or a pool that cannot grow.
+     *               the furthest context it can reach. Null (step() runs after the commit
+     *               instead) when only committed state can decide: a request awaiting admission,
+     *               a prefill chunk to continue, a grammar, the context's end, or a pool that
+     *               cannot grow.
      *   promote_next   once this step has committed: the next step becomes the open one.
      *
-     * While the next step is open, commit() leaves each continuing request's blocks where they
-     * are -- the next step is writing past the committed end -- and a request that finishes keeps
-     * them until the next step has run. */
+     * While the next step is open, commit() leaves continuing requests' blocks in place, and a
+     * finished request keeps them until that step has run. */
     void            expect_draft(uint64_t id, int n);
     const RadBatch* step_next();
     const RadBatch* step_next_locked();
     void            promote_next();
-    bool            next_open() const { return next_open_; }
     /* Fold the step's outcome back in: append tokens, roll back rejected speculation, retire
      * finished requests, feed the draft controller. */
     int             commit(const StepResult& r);
-    /* THE ENGINE'S LOOP IS ROUND, AND THE STEP ENDS HERE -- after the drafter, not at commit.
-     * A serial draft head runs as extra steps AFTER the trunk step that fed it (see below), so
-     * closing the step at commit would leave those rounds in no step at all: their time is charged
-     * to nothing, `decode_tps` reads high and the reported step time reads short. The definition in
-     * scheduler.cpp is the argument. Call it once per loop iteration that ran a step; a caller that
-     * does not is left with correct counters and no timing. */
+    /* Ends the step for timing; call once per loop iteration that ran a step, after the drafter,
+     * so the draft rounds are charged to the step (see the definition). Without it the counters
+     * stay correct but there is no timing. */
     void            step_finished();
 
-    /* ---------------------------------------------------- the SERIAL drafter (spec §10)
+    /* ---------------------------------------------------- the serial drafter (spec §10)
      *
-     * A serial draft head (RAD_DRAFT_SERIAL) runs as EXTRA STEPS of its own, after the
-     * trunk step that fed it. It cannot run inside that step: round 1 consumes the token the
-     * sampler chose and the hidden state of the position that token came from, and which position
-     * that is depends on how many drafts the verify accepted -- neither is known until the trunk
-     * step has been sampled and committed.
+     * A serial draft head (RAD_DRAFT_SERIAL) runs as extra steps after the trunk step that fed it,
+     * because round 1 needs the sampled token and its position, which depends on how many drafts
+     * the verify accepted. The engine drives it through:
      *
-     * So the engine drives it, and these three calls are the scheduler's half:
-     *
-     *   serial_begin   BEFORE commit(), right after the step is issued, while plan() describes it.
-     *               Says which sequences may draft, reserves the lookahead KV they may write
-     *               into -- for the furthest position acceptance could reach, since how far it
-     *               reached is the card's to decide -- and clamps `rounds` to the controller's
-     *               current depth.
-     *   serial_batch   one batch per pass: 0 the history, which also carries round 1 for the
-     *               rows that draft (RadBatch::draft_out_ids), then the rounds from 2. Every row
-     *               that continues a sampled verify is a DEVICE row (advance.h): the card fills
-     *               its positions from the acceptance it computed, and its tokens from the sampled
-     *               ids and each round's proposal, so no pass waits on the host.
-     *   serial_end     AFTER commit(), with the rounds that ran: moves the history watermark to
-     *               the last position the committed acceptance says the history pass wrote.
-     *   set_draft   the engine publishes each row's tokens through the ordinary door, so a head's
-     *               draft and a prompt-lookup draft are the same thing to the next step. A row
-     *               the head declined leaves n_draft at 0 and the n-gram drafter fills in.
+     *   serial_begin   before commit(), right after the step is issued, while plan() describes it.
+     *               Says which sequences may draft, reserves lookahead KV up to the furthest
+     *               position acceptance could reach, and clamps `rounds` to the current depth.
+     *   serial_batch   one batch per pass: 0 is the history, which also carries round 1 for the
+     *               drafting rows (RadBatch::draft_out_ids), then rounds from 2. Rows continuing
+     *               a sampled verify are device rows (advance.h): the card fills their positions
+     *               and tokens, so no pass waits on the host.
+     *   serial_end     after commit(), with the rounds that ran: moves the history watermark.
+     *   set_draft   publishes each row's tokens like any other draft. A row the head declined
+     *               keeps n_draft 0 and the n-gram drafter fills in.
      */
     struct SerialRow {
         uint64_t seq = 0;
@@ -398,48 +312,37 @@ public:
     };
     int serial_begin(int* rounds, SerialRow* out, int max);
     const RadBatch* serial_batch(int round, int step);
-    /* Round 0 is the HISTORY pass -- null when no row needs one -- and round 1 is always null,
-     * because round 0 carries it. Call serial_end() once the step has committed so the watermark
-     * moves. */
+    /* Round 0 is the history pass (null when no row needs one); round 1 is always null, because
+     * round 0 carries it. Call serial_end() once the step has committed. */
     void serial_end(int rounds_done);
 
-    /* ----------------------------------------------------- the BLOCK drafter (spec §10)
+    /* ----------------------------------------------------- the block drafter (spec §10)
      *
-     * A block-diffusion drafter (RAD_DRAFT_BLOCK), and the shape is the whole point: ONE pass
-     * over a block of `block` positions proposes all of them, so depth costs nothing and there is
-     * no chain of rounds. What replaces it is TWO passes with different shapes, and the scheduler's
-     * half is telling each of them which rows it runs over.
+     * A block-diffusion drafter (RAD_DRAFT_BLOCK) proposes a whole block of `block` positions in
+     * one pass, so there are no rounds; instead it runs two passes of different shapes.
      *
      *   block_begin       right after commit(), while plan() still describes the step just run.
-     *                  Reserves the block of draft KV the query pass will write, and answers
-     *                  which sequences may draft.
-     *   block_context     the CONTEXT pass, draft_pass -1. Its entries MIRROR that trunk step's --
-     *                  same sequence, same ctx_len, same n_tokens -- because the drafter reads
-     *                  the trunk's tapped hidden states positionally out of a buffer of its own,
-     *                  and a mirror is what makes row i of the batch row i of it. No gather,
-     *                  no offset, and no special case for a rejected suffix: those positions are
-     *                  inside the block the query pass is about to overwrite.
-     *   block_query       the QUERY pass, draft_pass +1. One entry a drafting sequence, `block`
-     *                  tokens: the anchor at the sequence's own next position and a mask at each
-     *                  of the `block - 1` after it. `out_ids` names THE LAST `depth` ROWS, which
-     *                  is the one rule both trained conventions reduce to: at block = depth + 1
-     *                  the anchor row predicts nothing and each mask row predicts the token at
-     *                  ITS OWN position, and at block = depth every row predicts the token AFTER
-     *                  it and the anchor is not wasted. rad_builder.h argues the pair.
+     *                  Reserves the draft KV block the query pass writes, and returns which
+     *                  sequences may draft.
+     *   block_context     the context pass, draft_pass -1. Its entries mirror the trunk step's
+     *                  row for row (BlockSeq).
+     *   block_query       the query pass, draft_pass +1. One entry per drafting sequence: the
+     *                  anchor at its next position, then `block - 1` masks; `out_ids` names the
+     *                  last `depth` rows.
      *   block_end         moves the filled range over what actually ran.
      *
-     * The proposal does not come back through the sampler: the drafter writes it to the buffer it
-     * declared as its proposal, and the engine publishes it through set_draft() like any other.
+     * The drafter writes its proposal to its declared proposal buffer, not through the sampler,
+     * and the engine publishes it through set_draft().
      */
     struct BlockRow {
         uint64_t seq = 0;
         int32_t  slot = -1;
         int32_t  card = -1;
     };
-    /* `block` is the drafter's trained block in ROWS and `depth` how many tokens it proposes out
-     * of them -- the head takes the last `depth` -- and `window` is its attention window (0 for
-     * none); `mask` is the token id its masked query slots embed. Returns how many sequences may
-     * draft, and fills `out` with those -- in the order block_query() will emit them. */
+    /* `block` is the drafter's trained block in rows, `depth` how many tokens it proposes (the
+     * last `depth` rows), `window` its attention window (0 for none) and `mask` the token id its
+     * masked query slots embed. Returns how many sequences may draft and fills `out` with them,
+     * in the order block_query() emits them. */
     int block_begin(int block, int depth, int window, int32_t mask, BlockRow* out, int max);
     const RadBatch* block_context(int step);
     const RadBatch* block_query(int step);
@@ -450,15 +353,11 @@ public:
     DraftController&     draft() { return draft_; }
     SchedMetrics         metrics() const;
 
-    /* THE OBSERVERS' COPY. A dashboard, a scraper or an admin call reads what the engine thread
-     * last published and never the scheduler's own state, because that state is behind the lock
-     * every step takes: a reader holding it for as long as its own work takes delays the step by
-     * exactly that long, and an observer must not be able to slow what it observes.
-     *
-     * publish() is the engine thread's, once a step and at most every 20 ms while idle. It builds
-     * the copy under the scheduler's lock -- the engine thread's own lock, so nothing waits -- and
-     * swaps it in only if no reader is copying out at that moment; a swap it skips is made at the
-     * next call. The readers take only the copy's lock, which the engine thread never waits on. */
+    /* The observers' copy. Dashboards, scrapers and admin calls read what the engine thread last
+     * published, never the scheduler's state behind the step lock, so an observer cannot slow
+     * the step. publish() runs on the engine thread once a step (at most every 20 ms while idle),
+     * builds the copy under mu_ and swaps it in only if no reader holds the copy's lock; a
+     * skipped swap happens at the next call. */
     void                 publish(bool idle);
     SchedMetrics         observed_metrics() const;
     int                  observed_requests(ReqStat* out, int max) const;
@@ -471,10 +370,15 @@ public:
     int64_t plan_chunk(int64_t n_computed, int64_t n_target, int64_t budget,
                        int64_t* checkpoint_pos, int64_t keep_at = 0) const;
 
-    /* THE SMALLEST STEP THE PREFILL STAGER OVERLAPS, in tokens (0 = no stager), set once by the
-     * engine after init. --busy-prefill-chunk keeps a held-back chunk at or above it; see
-     * busy_cap. Also where the resolved policy is stated at startup. */
+    /* The smallest step the prefill stager overlaps, in tokens (0 = no stager), set once by the
+     * engine after init. --busy-prefill-chunk keeps a held-back chunk at or above it (busy_cap).
+     * Also logs the resolved policy at startup. */
     void    set_stage_rows(int64_t rows);
+    /* The shortest prefill that spans, in tokens (0: every one alone in its step), set once by
+     * the engine after init. Where routed experts are read from host memory, the arena a spanned
+     * step takes is room the experts lose for it, which on a short prompt costs more than the span
+     * saves (Engine::serve). */
+    void    set_span_min(int64_t tokens);
     /* Whether the step just planned leaves a prompt with at least the stager's smallest pass still
      * to prefill, so the next step most likely carries a chunk the stager arms for. */
     bool    prefill_continues() const;
@@ -494,76 +398,63 @@ private:
     bool          has_linear_state_ = false;
     /* set_stage_rows: the prefill stager's smallest pass, 0 when it is not armed. */
     int64_t       stage_rows_ = 0;
+    /* set_span_min: the shortest prefill a span is taken for, 0 for any. */
+    int64_t       span_min_ = 0;
     /* Set by admit_one when it held the admitted chunk back: what it would have taken. */
     int64_t       admit_full_ = 0;
+    /* Whether this step's prefill may span (ChunkGeometry::span): set by step() for the step it
+     * plans, true only for a prefill alone in its step, and read by plan_chunk. True outside a
+     * step, so plan_chunk called directly answers for a span. */
+    bool          span_now_ = true;
     IKVManager*   kv_ = nullptr;
     IPrefixCache* pc_ = nullptr;
 
-    /* DOES A PREFIX-CACHE HIT LEAVE A HOLE IN A BLOCK DRAFTER'S OWN KV? Only if some PAGED group
-     * is not prefix-cached. prefix.cpp skips a WINDOWED group -- "a hit's blocks do not describe
-     * a cache whose floor moves" -- so a windowed drafter really does start at the hit position
-     * and really must wait for its window to slide past it. A FULL-attention drafter's group is
-     * cached exactly like the trunk's: the hit hands over blocks the PREVIOUS sequence's own
-     * context pass wrote, so the content is there and the floor is 0.
-     *
-     * Read off IPrefixCache::cached_groups() rather than re-deriving prefix.cpp's rule, which
-     * also skips on a block-size mismatch. A bound like this lives in exactly one place; a second
-     * copy is free to drift out of step with the first. */
+    /* Does a prefix-cache hit leave a hole in a block drafter's own KV? Only if some paged group
+     * is not prefix-cached. prefix.cpp skips windowed groups, so a windowed drafter has K and V
+     * only from the hit position and must wait for its window to slide past it. A full-attention
+     * drafter's group is cached like the trunk's and its floor is 0; treating it as windowed
+     * would stop drafting for good, since it has no window to slide. Read off
+     * IPrefixCache::cached_groups() so prefix.cpp's rule lives in one place. */
     bool          hit_holes_draft_ = true;
-    /* DOES A HIT HOLE THE TRUNK ITSELF? hit_holes_draft_ is the drafter's guard, and draft_refill_
-     * repairs a drafter hole by recomputing the prompt's TAIL. A TRUNK group the cache does not
-     * index admits no such repair: the adopted blocks cover the cached groups only, while the
-     * windowed trunk layers read the positions below ctx_len this sequence never wrote — the KV of
-     * whoever held these blocks last. So a trunk hole refuses the hit outright.
-     *
-     * THE TRUNK IS WHICH GROUPS? The one a drafter borrows is bound at `base_layer` and above —
-     * the drafter's layers run after the trunk's (rad_bind_layer_kv at the drafter declare), so a
-     * group with a bound layer below meta.n_layers belongs to the trunk and a hit must cover it;
-     * a drafter's own group is the refill's business, not this clamp's. Read off the Program,
-     * which carries both the bindings and the trunk's layer count. */
+    /* Does a hit leave a hole in the trunk: a paged group with a trunk layer (bound below
+     * meta.n_layers; drafter layers bind from `base_layer` up) that the cache does not index?
+     * Unlike a drafter hole, recomputing the tail cannot repair it; see admit_one. */
     bool          hit_holes_trunk_ = false;
-    /* DRAFT REFILL. Where a hit leaves a hole in a WINDOWED block drafter's cache, the drafter is
-     * declined until its window has slid past the hole, which on the follow-up turn of a chat --
-     * the turn a prefix hit is for -- is most or all of the reply. So the hit is ended one window
-     * before the end of the prompt (HitCap): the trunk recomputes that window, the drafter's
-     * context pass covers it, and the sequence drafts from its first decode step. Output is
-     * unchanged; only which tokens are recomputed moves. A hit whose nearest checkpoint below
-     * that point would give back more than two windows is kept whole. The drafter's window, or 0
-     * where no hit can leave such a hole. */
+    /* Draft refill: the drafter's window where a hit can leave a hole in a windowed block
+     * drafter's cache, else 0. The drafter would be declined until its window slid past the hole,
+     * which on a chat's follow-up turn is most of the reply, so the hit ends one window before the
+     * prompt's end (HitCap) and the recompute fills the drafter's window too. Output is unchanged.
+     * A hit whose nearest checkpoint below that point gives back more than two windows is kept
+     * whole. */
     int64_t       draft_refill_ = 0;
-    /* A SERIAL HEAD WITH NO CACHE OF ITS OWN (rad_drafter_shared_kv), off the Program at init. It
-     * owes no history, so serial_begin gives it one row a drafting sequence and none to a sequence
-     * that does not draft, and its rounds stay at the committed position (advance.h). False and 0
-     * for every other drafter, whose passes are staged exactly as before. */
+    /* A serial head with no cache of its own (rad_drafter_shared_kv). It owes no history, so
+     * serial_begin gives it one row per drafting sequence and none otherwise, and its rounds stay
+     * at the committed position (advance.h). False and 0 for every other drafter. */
     bool          serial_shared_ = false;
     int32_t       serial_rot_shift_ = 0;
     BatchBuilder  builder_;
     DraftController draft_;
 
-    /* Where this sequence's block-drafter cache begins, as the guard in block_begin reads it
-     * and block_end records it. One rule, one place. */
+    /* Where this sequence's block-drafter cache begins; block_begin's guard reads it and
+     * block_end records it. */
     int64_t draft_floor(const SchedReq& s, int64_t ctx_len) const {
         if (s.draft_hi != 0 || s.draft_lo != 0) return s.draft_lo;
         return hit_holes_draft_ ? ctx_len : 0;
     }
 
-    /* THE WINDOW A SEQUENCE MAY DRAFT INTO: the configured depth, or under the adaptive window
-     * min(D, its stop) (DraftController::window_for, which starts the estimate on the first ask).
-     * It is the rule every site that caps a proposal applies -- step(), set_draft(),
-     * expect_draft() and the rounds in serial_begin() -- and with the policy off it is
-     * next_depth(), exactly as before. */
+    /* The window a sequence may draft into: the configured depth, or under the adaptive window
+     * min(D, its stop) (DraftController::window_for, which starts the estimate on first use).
+     * Every site that caps a proposal applies it: step(), set_draft(), expect_draft() and the
+     * rounds in serial_begin(). With the policy off it is next_depth(). */
     int draft_cap(SchedReq& s) const {
         return draft_.adaptive() ? draft_.window_for(s.adapt) : draft_.next_depth();
     }
 
-    /* THE STEP'S HEAD DEPTH D IS CHOSEN ONCE A CYCLE AND HELD, by draft_cycle(), which is the
-     * first thing step() and promote_next() do -- every cycle opens with exactly one of the two.
-     * A cycle's proposal passes through four sites -- the plan that verifies it, the rounds that
-     * draft the next one, expect_draft() and set_draft() -- and the step issued ahead holds them
-     * to agree: it was built with the count expect_draft() gave it, and set_draft() refuses a
-     * different one. A D read live could move between them, because a commit or a client hanging
-     * up changes the running set mid-cycle; held, it moves only where a cycle starts, and a
-     * proposal drafted under one D and planned under the next is only ever cut shorter.
+    /* The step's head depth D is chosen once per cycle by draft_cycle(), the first thing step()
+     * and promote_next() do. A proposal passes four sites that must agree on it: the verifying
+     * plan, the drafting rounds, expect_draft() and set_draft(). A commit or a disconnect changes
+     * the running set mid-cycle, so a D read live could move between them; held, a proposal
+     * drafted under one D and planned under the next is only ever cut shorter.
      *
      * `draft_est_` is the list plan_step reads, reserved at init so the step path does not
      * allocate. */
@@ -601,14 +492,13 @@ private:
     std::vector waiting_;
     std::vector completed_;
 
-    /* Requests whose release is waiting on something that still refers to them -- a deferred
-     * reap or a deferred free. A count, so the sweeps that look for them cost nothing on the
-     * steps where there are none, which is nearly all of them. */
+    /* Requests whose release waits on something that still refers to them (a deferred reap or a
+     * deferred free). A count, so the sweeps cost nothing on the steps where there are none. */
     int      n_deferred_ = 0;
     /* Items a waiting request needs encoded, in the order its requests reached the queue's head;
      * each at most once (Item::queued). mu_ held. */
     std::vector> enc_want_;
-    /* Are all of this request's items encoded; the ones that are not are queued for the encoder. */
+    /* Are all of this request's items encoded? The ones that are not are queued for the encoder. */
     bool media_ready(SchedReq& s);
 
     /* Set by shutdown(); add() refuses from then on. */
@@ -616,10 +506,15 @@ private:
     const char* closed_reason_ = "";
     int      closed_status_ = RAD_E_STATE;
 
-    /* THE LONGEST SEQUENCE THIS DEPLOYMENT CAN ADDRESS, prompt and output together. The batch
-     * builder sizes its block tables for it and the rotary tables are this long, so no position
-     * at or past it may be scheduled -- whatever max_tokens a request carries, including none. */
+    /* The longest sequence (prompt plus output) this deployment can address. The batch builder's
+     * block tables and the rotary tables are sized for it, so no position at or past it may be
+     * scheduled, whatever max_tokens a request carries. */
     int64_t  ctx_limit_ = 0;
+    /* The longest sequence the KV pool can ever hold alone, when that is less than ctx_limit_,
+     * else -1; and the refusal a longer prompt gets, naming it (a sink keeps the pointer, so it
+     * lives here). See add_locked. */
+    int64_t     pool_tokens_ = -1;
+    std::string pool_refusal_;
 
     /* Scratch for a prefix-cache hit's block ids, one row per cached group. Reserved at init so
      * an admission does not reach the allocator. */
@@ -636,9 +531,7 @@ private:
         return (step_open_ && s.entry >= 0) || (next_open_ && s.entry_next >= 0);
     }
 
-    /* The serial drafter's rows, valid between serial_begin() and serial_end(). `base_pos`
-     * is the position round 1 writes at: the emitted token's own position, which is exactly the
-     * committed length because that token has not been fed to the model yet. */
+    /* The serial drafter's rows, valid between serial_begin() and serial_end(). */
     struct SerialSeq {
         uint64_t       seq = 0;
         int32_t        slot = -1;
@@ -646,32 +539,29 @@ private:
         int32_t        hist_row = -1;   /* the trunk row the history pass starts at */
         int32_t        hist_n = 0;      /* how many positions it has to fill, 0 for none */
         int64_t        hist_pos = 0;    /* the head index that first row is */
-        /* THE VERIFY STEP THIS ROW CONTINUES FROM, as the card's advance reads it (advance.h):
+        /* The verify step this row continues from, as the card's advance reads it (advance.h):
          * whether it sampled, the token row of its first verified position, its first sampled
          * row, and how many history positions come before the verified ones. */
         bool           dev = false;
         int32_t        dev_tok = 0;
         int32_t        dev_out = -1;
         int32_t        lead = 0;
-        /* ITS INDEX AMONG THE DRAFTING ROWS, or -1 for a row that only owes history. A sequence
-         * in the middle of a long prompt has hidden states worth turning into the head`s K and V
-         * and no token to draft from yet, and so does every sequence when a prefill is queued
-         * behind this step -- so the two sets are not the same set. */
+        /* Its index among the drafting rows, or -1 for a row that only owes history (e.g. a
+         * sequence mid-prompt, with hidden states but no token to draft from). */
         int32_t        draft_idx = -1;
-        /* NO Request* HERE, for the reason BlockSeq gives: serial_ is taken under the lock in
-         * serial_begin and read again by serial_batch, once a round, after the lock has been
-         * released and retaken -- and a client can disconnect in any of those windows. */
-        /* THE FURTHEST POSITION ROUND 1 CAN WRITE AT: the verify step's last position, reached
+        /* No Request* here, as for BlockSeq: serial_batch reads serial_ after the lock was
+         * released and retaken. */
+        /* The furthest position round 1 can write at: the verify step's last position, reached
          * when every draft is accepted. The card knows the real one; this bounds it. */
         int64_t        base_pos = 0;
     };
     std::vector serial_;
     StepPlan            serial_plan_;
 
-    /* The block drafter's rows, valid between block_begin() and block_end(). One entry for EVERY
-     * entry of the trunk step just run, in its order; `can_draft` says whether it also gets a
-     * query pass. `ctx_len`/`n_tokens` mirror that step's entry, which is the whole contract with
-     * the drafter's own source buffer. */
+    /* The block drafter's rows, valid between block_begin() and block_end(): one per entry of the
+     * trunk step just run, in order, with `ctx_len`/`n_tokens` mirroring it. The drafter reads
+     * the trunk's tapped hidden states positionally from its own buffer, so row i must be the
+     * trunk's row i. `can_draft` says whether the row also gets a query pass. */
     struct BlockSeq {
         uint64_t       seq = 0;
         int32_t        slot = -1;
@@ -680,35 +570,36 @@ private:
         int32_t        n_tokens = 0;
         int64_t        base_pos = 0;      /* the anchor's position: the sequence's next one */
         bool           can_draft = false;
-        /* A ROW KEPT ONLY TO HOLD ITS PLACE. The trunk step finished this sequence -- it ended,
-         * failed or was cancelled at commit -- so its KV is gone and it drafts nothing. It is
-         * still a row of the context pass, because the drafter reads the trunk's hidden states
-         * positionally: dropping it would slide every later sequence onto its neighbour's rows.
-         * With no blocks behind it the pass stores nothing for it (a negative slot is padding). */
+        /* A placeholder: the trunk step finished this sequence, so it has no KV and drafts
+         * nothing, but keeps its row so later rows stay aligned with the trunk's. The pass stores
+         * nothing for it (a negative slot is padding). */
         bool           mirror = false;
-        /* NO Request* HERE, DELIBERATELY. block_ is taken under the lock in block_begin and read
-         * again in block_context, block_query and block_end, and the lock is RELEASED between
-         * them -- so a client that disconnects in that window can have its Request destroyed
-         * under the second pass, leaving BatchBuilder::build reading tokens off freed memory.
-         * The snapshot is a WEAK reference: `slot` plus `seq`, resolved through block_req(). */
+        /* No Request* here: block_ is read by later passes with the lock released in between,
+         * and a disconnect could free the Request. Rows hold `slot` plus `seq`, resolved through
+         * block_req(). */
     };
     std::vector block_;
     StepPlan           block_plan_;
     int32_t            block_len_ = 0;
-    int32_t            block_depth_ = 0;   /* tokens proposed; the head takes the LAST this many */
-    /* `block` - 1 copies of the drafter's mask token, which is what a query entry's `draft` array
-     * points at: token_at() walks prompt ++ output ++ draft, so the mask positions fall straight
-     * out of the accessor every other pass already uses. */
+    int32_t            block_depth_ = 0;   /* tokens proposed; the head takes the last this many */
+    /* `block` - 1 copies of the drafter's mask token, which a query entry's `draft` points at:
+     * token_at() walks prompt ++ output ++ draft, so the mask positions come from the accessor
+     * every other pass uses. */
     std::vector block_mask_;
     int      step_ = 0;
     uint64_t arrival_ = 0;
 
     SchedMetrics m_{};
     std::chrono::steady_clock::time_point step_start_{};
-    /* When the last step ended. An idle engine runs no steps, so the throughput window has
-     * nothing adding time to it, and metrics() decays what it reports by this. */
+    /* When the last step ended. An idle engine runs no steps, so nothing adds time to the
+     * throughput window; metrics() decays what it reports by this. */
     std::chrono::steady_clock::time_point last_step_at_ = std::chrono::steady_clock::now();
     int64_t step_prefill_tok_ = 0, step_decode_tok_ = 0;
+    /* --prefill-interleave: decode-only steps still owed before the next chunk, and how many
+     * prefilling requests the last step() held back. step_next_locked stops issuing ahead once
+     * the hold is spent, or the chunk would wait as long as the decoders keep stepping ahead. */
+    int64_t interleave_left_ = 0;
+    int64_t held_prefill_ = 0;
     /* The throughput window (step_finished): each kind's tokens and the wall time the steps
      * covered, both decayed with the same time constant, so their ratio is tokens over time. */
     double  tps_win_prefill_ = 0.0, tps_win_decode_ = 0.0, tps_win_time_ = 0.0;
@@ -723,28 +614,26 @@ private:
     static void queue_erase(std::vector& q, int32_t slot);
 
     /* lifecycle */
-    /* `publish` is false only when the engine is shutting down: a sequence the device may have
-     * left half-computed is not worth indexing, and nothing will ever hit it.
-     *
-     * A FAILED REQUEST SAYS WHAT FAILED: its sink is failed with `status` and `why`, which the
-     * server puts in the error the client gets. RAD_OK leaves a sink that has failed already (an
-     * overflow) as it is. */
+    /* Ends a request: counts it by `st` and queues its id for take_completed. `publish` is
+     * false only at shutdown, where a possibly half-computed sequence is not worth indexing. A
+     * failed request's sink is failed with `status` and `why`, which reach the client's error;
+     * RAD_OK leaves an already-failed sink (an overflow) as it is. */
     void close_request(SchedReq& s, ReqState st, const char* reason, bool defer_free = false,
                        bool publish = true, int status = RAD_OK, const char* why = nullptr);
-    /* What reap() does once nothing points at the slot any more: give the blocks back, forget the
-     * id, destroy the Request and return the slot. Called by reap() directly, or by the sweep in
+    void reserve_ckpt(StepEntry& e, const Request& r, int64_t pos, int32_t tok);
+    /* What reap() does once nothing points at the slot: give the blocks back, forget the id,
+     * destroy the Request and return the slot. Called by reap() directly, or by the sweep in
      * commit() for a request whose reap arrived while something still pointed at it. */
     void release_locked(SchedReq& s);
-    /* The sequence's KV back to the manager and its card index back to the pool, together:
-     * both are what a step in flight still addresses, so both wait for the same moment. */
+    /* The sequence's KV back to the manager and its card index back to the pool, together: a step
+     * in flight still addresses both, so both wait for the same moment. */
     void free_kv(SchedReq& s);
     void drop_card(SchedReq& s);
-    /* Is this request still referenced by a drafter's snapshot? block_ and serial_ outlive the
-     * lock. */
+    /* Is this request still named by a drafter snapshot? block_ and serial_ outlive the lock. */
     bool block_holds(uint64_t id) const;
-    /* Release every deferred reap and every deferred free whose request nothing refers to any
-     * more. At most one step late: the reference that blocked it is either the step just
-     * committed or a drafter snapshot that block_end() / serial_end() has since cleared. */
+    /* Release every deferred reap and free whose request nothing refers to any more. At most one
+     * step late: what blocked it is either the step just committed or a drafter snapshot that
+     * block_end() / serial_end() has since cleared. */
     void sweep_deferred();
     /* Give back a prefix hit an admission attempt took and then could not use: the adopted
      * blocks, the checkpoint it would have restored, and the position it would have resumed at.
@@ -758,13 +647,15 @@ private:
     void preempt_back();
     /* Give blocks back from the prefix cache until the pool has headroom again. */
     void trim_prefix_cache();
-    /* RAD_OK, or a negative status when the request cannot be admitted now -- nothing behind it is
-     * either. */
-    /* `reserve`: tokens of the step to leave for the requests queued behind this one
-     * (--busy-prefill-chunk; busy_cap). 0 plans the chunk on the whole budget, as before. */
+    /* RAD_OK, or a negative status when the request cannot be admitted now, nor anything behind
+     * it. `reserve`: tokens of the step to leave for the requests queued behind this one
+     * (--busy-prefill-chunk; busy_cap); 0 plans the chunk on the whole budget. */
     int  admit_one(SchedReq& s, int64_t budget, int64_t reserve = 0);
     /* The queue positions one step's admission took, kept to reuse the allocation. */
     std::vector took_;
+    /* A step's prefill entries while step() moves its decode entries first; reserved at init,
+     * since std::stable_partition would take a temporary buffer from the allocator every step. */
+    std::vector part_;
 
     /* The conv rolling window, width-1 + num_spec + 1 entries (spec §10). */
     int32_t conv_window() const;
diff --git a/core/server/adapters.h b/core/server/adapters.h
index f882f934..e2d2839f 100644
--- a/core/server/adapters.h
+++ b/core/server/adapters.h
@@ -1,22 +1,20 @@
 /* core/server/adapters.h -- bind the real components onto the server's interfaces.
  *
- * iface.h deliberately knows nothing about core/sched or core/text, so that the HTTP layer can be
- * compiled and tested against fakes with no engine present. This file is where the two sides
- * actually meet, and it is included by exactly one translation unit: whoever wires the engine
- * (core/engine.cpp). Nothing in core/server/ includes it, so the server's own build stays
- * independent of those components' headers.
+ * iface.h knows nothing about core/sched or core/text, so the HTTP layer can be built and tested
+ * against fakes. This file joins the two sides and is included only by the translation unit that
+ * wires the engine (core/engine.cpp); nothing in core/server/ includes it.
  *
  *   rad::server::SchedulerBridge  sched(&engine_scheduler);
  *   rad::server::TokenizerBridge  tok(vocab);
  *   rad::server::Deps d; d.sched = &sched; d.tok = &tok; ...
  *
- * Every impedance mismatch between what the server wants and what those components provide is
- * resolved here, in one place, with the reason written down -- rather than being smeared across
- * either component as a special case for the other.
+ * Mismatches between what the server wants and what the components provide are resolved here
+ * rather than as special cases inside either side.
  */
 #pragma once
 #include "iface.h"
 #include "mem/kvtier.h"
+#include "sink.h"
 
 #if !defined(RAD_SERVER_NO_ENGINE_BRIDGE) && \
     __has_include("sched/scheduler.h") && __has_include("text/tokenizer.h")
@@ -37,6 +35,7 @@
 
 #include 
 #include 
+#include 
 #include 
 
 namespace rad {
@@ -44,15 +43,111 @@ namespace server {
 
 /* ================================================================== scheduler */
 
+/* The scheduler's snapshot in the server's terms (SchedulerBridge::metrics). */
+inline SchedMetrics bridge_metrics(const rad::SchedMetrics& m) {
+    SchedMetrics o;
+    o.waiting = m.queue_depth;
+    o.running = m.running;
+    o.preempted = m.preempted_waiting;
+
+    /* KV utilisation is the maximum over groups, not the mean: a hybrid model's attention
+     * and linear-state groups have different geometries (spec §7.2) and exhausting either
+     * one preempts.
+     *
+     * Token capacity is not a sum either. Paged groups share one token axis: each context
+     * token takes a slot in every paged group (e.g. Qwen4-Exp's `kv_attn` and `kv_qsa_bkey`),
+     * so summing overcounts by the number of paged groups. The token figures are the binding
+     * group's: the paged group nearest full, which decides the next preemption. A windowed group
+     * never binds: it recycles blocks below its window, so its fill bounds lookback, not how much
+     * context fits (a drafter's window sits full for the server's whole life). */
+    o.kv_util = 0.0;
+    int bind = -1;
+    for (int i = 0; i < m.n_kv_groups; ++i) {
+        if (m.kv[i].block_tokens <= 0) continue;     /* a linear state has no token axis */
+        if (m.kv[i].window) continue;
+        if (bind < 0 || m.kv[i].utilisation > m.kv[bind].utilisation) bind = i;
+    }
+    for (int i = 0; i < m.n_kv_groups; ++i)
+        o.kv_util = std::max(o.kv_util, (double)m.kv[i].utilisation);
+    if (bind >= 0) {
+        const int64_t bt = m.kv[bind].block_tokens;
+        o.kv_tokens_total = m.kv[bind].blocks_total * bt;
+        o.kv_tokens_used  = (m.kv[bind].blocks_total - m.kv[bind].blocks_free) * bt;
+    }
+
+    /* Bytes, unlike tokens, do sum: each group has its own extent of VRAM, so every group
+     * (recurrent ones included) is added. */
+    for (int i = 0; i < m.n_kv_groups; ++i) {
+        o.kv_bytes_total += m.kv[i].bytes_total;
+        o.kv_bytes_used  += m.kv[i].bytes_used;
+        o.kv_bytes_carved += m.kv[i].bytes_carved;
+        if (m.kv[i].block_tokens <= 0 || m.kv[i].window) continue;
+        const int64_t t = m.kv[i].blocks_total * m.kv[i].block_tokens;
+        if (o.kv_tokens_max == 0 || t < o.kv_tokens_max) o.kv_tokens_max = t;
+    }
+
+    /* vLLM's gpu_prefix_cache_hit_rate means attention caching. The linear-checkpoint hit
+     * rate has a different granularity (spec §7.3) and is reported separately, not averaged
+     * in. */
+    o.prefix_hit_rate = m.attn_hit_rate;
+    o.prefix_evictions = m.prefix_evictions;
+    /* What only the cache holds (SchedMetrics::prefix_held_tokens), clamped to the pool's
+     * used figure: the two are counted at different moments in a step, and cached > used
+     * would show a negative live share. */
+    o.kv_tokens_cached = std::min(m.prefix_held_tokens, o.kv_tokens_used);
+    o.prefix_ckpt_evictions = m.prefix_ckpt_evictions;
+    o.prefix_ckpt_retired = m.prefix_ckpt_retired;
+    o.prefix_ckpt_lru = m.prefix_ckpt_lru;
+    o.prefix_ckpt_refused = m.prefix_ckpt_refused;
+    o.hit_cut_no_snapshot = m.hit_cut_no_snapshot;
+    o.hit_cut_window = m.hit_cut_window;
+    o.hit_cut_adopt = m.hit_cut_adopt;
+    o.hit_cut_tokens = m.hit_cut_tokens;
+    o.prefix_expired = m.prefix_expired;
+    o.prefix_ckpt_expired = m.prefix_ckpt_expired;
+
+    o.prefill_tps = m.prefill_tps;
+    o.decode_tps = m.decode_tps;
+    o.draft_acceptance = m.draft_acceptance;
+    o.prefill_tokens = m.prefill_tokens;   o.decode_tokens = m.decode_tokens;
+    o.draft_tokens = m.draft_tokens;       o.draft_accepted = m.draft_accepted;
+    o.draft_refills = m.draft_refills;     o.draft_refill_tokens = m.draft_refill_tokens;
+    o.linear_hit_rate = m.linear_hit_rate;
+    o.attn_cached_tokens = m.attn_cached_tokens;
+    o.linear_cached_tokens = m.linear_cached_tokens;
+    o.checkpoints_written = m.checkpoints_written;
+    o.draft_depth_seen = m.draft_depth_seen;
+    if (o.draft_depth_seen > SchedMetrics::MAX_DRAFT_POS)
+        o.draft_depth_seen = SchedMetrics::MAX_DRAFT_POS;
+    for (int j = 0; j < o.draft_depth_seen; ++j) {
+        o.draft_pos_reached [j] = m.draft_pos_reached [j];
+        o.draft_pos_accepted[j] = m.draft_pos_accepted[j];
+    }
+    o.draft_adaptive = m.draft_adaptive;
+    o.draft_depth_adaptive = m.draft_depth_adaptive;
+    for (size_t d = 0;
+         d < std::size(m.draft_verify_depth) && d < std::size(o.draft_verify_depth); ++d)
+        o.draft_verify_depth[d] = m.draft_verify_depth[d];
+    o.preemptions = m.preemptions;
+    o.total_requests = m.admitted;
+    o.steps = m.steps;
+    o.steps_prefill = m.steps_prefill;  o.steps_mixed = m.steps_mixed;
+    o.steps_decode = m.steps_decode;
+    o.steps_ahead = m.steps_ahead;
+    o.prefill_chunks_capped = m.prefill_chunks_capped;
+    o.steps_held = m.steps_held;
+    o.decode_rows_unspeculated = m.decode_rows_unspeculated;
+    o.step_ns = m.step_ns;  o.step_ns_decode = m.step_ns_decode;
+    return o;
+}
+
 class SchedulerBridge final : public IScheduler {
 public:
-    /* `sampler` is the rank-0 sampler, and it is optional only so that a caller with no engine
-     * behind it still compiles. Every rank declares the same chain against the same hierarchy, so
-     * whether a stage resolved is not a per-rank fact and asking one of them is asking all. */
-    /* `tiers` is rank 0's IdleTiers, and it is given whether or not a tier can move anything:
-     * the object holds the session table either way, and a server with no --prefix-cache-mib is
-     * one whose every stored session is in VRAM rather than one with no sessions. Null only when
-     * there is no engine behind this at all. */
+    /* `sampler` is the rank-0 sampler; optional only for callers with no engine. Every rank
+     * declares the same chain against the same hierarchy, so rank 0 answers for all.
+     * `tiers` is rank 0's IdleTiers, passed even when no tier can move anything: it holds the
+     * session table either way (without --prefix-cache-mib every session is in VRAM). Null only
+     * with no engine. */
     explicit SchedulerBridge(Scheduler* s, const Sampler* sampler = nullptr,
                              const IdleTiers* tiers = nullptr)
         : s_(s), sampler_(sampler), tiers_(tiers) {}
@@ -62,33 +157,29 @@ public:
         return sampler_->check_request(sp, why);
     }
 
-    /* Request ids are the server's to allocate: Scheduler::add refuses a duplicate id and does
-     * not mint one, which is the right split -- the id has to exist before submission so that a
-     * connection dropped during submission still has something to cancel. */
     uint64_t submit(Request&& r) override {
-        auto p = std::make_unique(std::move(r));
-        p->id = next_.fetch_add(1, std::memory_order_relaxed);
-        const uint64_t id = p->id;
-        int st = s_->add(std::move(p));
-        if (st < 0) {
-            /* Failing here means the request never entered the queue, so nothing will ever finish
-             * its sink. Tell the sink itself, or the HTTP thread waits forever. */
-            RAD_WARN("server: scheduler refused request %llu: %s",
-                     (unsigned long long)id, rad_strerror(st));
-            return 0;
-        }
-        return id;
+        std::vector one;
+        one.push_back(std::move(r));
+        std::vector ids;
+        submit_all(one, &ids);
+        return ids[0];
     }
 
+    /* The server allocates request ids (Scheduler::add refuses duplicates and mints none), so
+     * the id exists before submission and a connection dropped mid-submission can cancel it.
+     * A refused request gets id 0 and a failed sink: it never entered the queue, so nothing
+     * else would finish the sink, and the HTTP thread waiting on it would hang. */
     void submit_all(std::vector& rs, std::vector* ids) override {
         const size_t n = rs.size();
         std::vector> ps(n);
+        std::vector sinks(n);
         std::vector rc(n, RAD_OK);
         ids->assign(n, 0);
         for (size_t i = 0; i < n; ++i) {
             ps[i] = std::make_unique(std::move(rs[i]));
             ps[i]->id = next_.fetch_add(1, std::memory_order_relaxed);
             (*ids)[i] = ps[i]->id;
+            sinks[i] = ps[i]->sink;
         }
         s_->add_all(ps.data(), n, rc.data());
         for (size_t i = 0; i < n; ++i) {
@@ -96,6 +187,9 @@ public:
             RAD_WARN("server: scheduler refused request %llu: %s",
                      (unsigned long long)(*ids)[i], rad_strerror(rc[i]));
             (*ids)[i] = 0;
+            /* A stopped engine has already failed the sink with its own reason. */
+            Sink* k = static_cast(sinks[i]);
+            if (k && !k->done()) k->fail(rc[i], "the scheduler refused the request");
         }
     }
 
@@ -104,15 +198,15 @@ public:
 
     int64_t reset_prefix_cache() override { return s_->reset_prefix_cache(); }
 
-    /* THE STORED CONVERSATIONS. Idle time is computed here rather than carried, because the tiers
-     * keep a monotonic timestamp and a browser wants "how long ago" -- converting at the edge
-     * means one clock is authoritative and the other never has to be trusted. */
+    /* The stored conversations. The tiers keep monotonic timestamps; idle and age are converted
+     * to "seconds ago" here, so only the monotonic clock is authoritative. */
     TierCounters tier_counters() const override {
         TierCounters c;
         if (!tiers_) return c;
         const IdleTiers::Stats& s = tiers_->stats();
         c.to_host = s.to_host; c.dropped = s.dropped; c.promoted = s.promoted;
         c.host_drops = s.host_drops; c.failures = s.failures;
+        c.held_back = s.held_back;
         c.host_bytes = s.host_bytes;
         c.restores = s.restores; c.restore_ns = s.restore_ns;
         c.flushes = s.flushes; c.flush_ns = s.flush_ns;
@@ -153,10 +247,8 @@ public:
         return (int)out->size();
     }
 
-    /* THE STATE NAME IS DERIVED, not stored: ReqState has no `Prefill`, because to the scheduler
-     * prefill is not a state -- it is a running request whose prompt is not yet all in the KV.
-     * That distinction is the single most useful thing this table shows, so it is made here
-     * rather than left for every reader to reconstruct from two integers. */
+    /* The state name is derived: ReqState has no `Prefill`, since to the scheduler prefill is a
+     * running request whose prompt is not yet all in the KV. The table reports it separately. */
     int requests(std::vector* out) const override {
         std::vector raw(256);
         const int n = s_->observed_requests(raw.data(), (int)raw.size());
@@ -195,109 +287,11 @@ public:
     /* Both read the copy the engine thread publishes (Scheduler::publish), never the
      * scheduler's live state: every caller is an observer. */
     SchedMetrics metrics() const override {
-        const rad::SchedMetrics m = s_->observed_metrics();
-        SchedMetrics o;
-        o.waiting = m.queue_depth;
-        o.running = m.running;
-        o.preempted = m.preempted_waiting;
-
-        /* One KV utilisation number, and it is the MAXIMUM over groups rather than the mean. A
-         * hybrid model has a full-attention group and a linear-state group with different
-         * geometries (spec §7.2), and exhausting either one preempts -- so the number a dashboard
-         * should be watching is the closest one to the wall, not the average of it with the one
-         * that has room.
-         *
-         * AND THE TOKEN CAPACITY IS NOT A SUM, for the same reason, which is easier to get wrong
-         * because the units look additive. PAGED GROUPS SHARE ONE TOKEN AXIS: on Qwen4-Exp
-         * `kv_attn` and `kv_qsa_bkey` are both 129216 blocks of 4 tokens, and one token of context
-         * takes a slot in BOTH of them (26.00 KiB + 3.25 KiB a block, 7.31 KiB a token together).
-         * Adding them would report 1,033,728 tokens of capacity for a pool that holds 516,864 --
-         * off by exactly the number of paged groups, an error that is invisible on a one-group
-         * model.
-         *
-         * So the figure is the BINDING group's: the one nearest the wall, which is the one that
-         * decides when the next sequence is preempted, and the same group `kv_util` reports. */
-        o.kv_util = 0.0;
-        int bind = -1;
-        for (int i = 0; i < m.n_kv_groups; ++i) {
-            if (m.kv[i].block_tokens <= 0) continue;     /* a linear state has no token axis */
-            if (bind < 0 || m.kv[i].utilisation > m.kv[bind].utilisation) bind = i;
-        }
-        for (int i = 0; i < m.n_kv_groups; ++i)
-            o.kv_util = std::max(o.kv_util, (double)m.kv[i].utilisation);
-        if (bind >= 0) {
-            const int64_t bt = m.kv[bind].block_tokens;
-            o.kv_tokens_total = m.kv[bind].blocks_total * bt;
-            o.kv_tokens_used  = (m.kv[bind].blocks_total - m.kv[bind].blocks_free) * bt;
-        }
-
-        /* AND THE WHOLE POOL IN BYTES, WHICH IS THE ONE FIGURE THAT IS A SUM. The paragraph above
-         * is about why tokens are not: the groups share a token axis. Bytes do not overlap -- each
-         * group was carved its own extent of the card -- so every group is added here, the
-         * recurrent ones included, and the answer is how much VRAM the KV cache is holding. */
-        for (int i = 0; i < m.n_kv_groups; ++i) {
-            o.kv_bytes_total += m.kv[i].bytes_total;
-            o.kv_bytes_used  += m.kv[i].bytes_used;
-            o.kv_bytes_carved += m.kv[i].bytes_carved;
-            if (m.kv[i].block_tokens <= 0 || m.kv[i].window) continue;
-            const int64_t t = m.kv[i].blocks_total * m.kv[i].block_tokens;
-            if (o.kv_tokens_max == 0 || t < o.kv_tokens_max) o.kv_tokens_max = t;
-        }
-
-        /* vLLM's gpu_prefix_cache_hit_rate is a single number and attention caching is what it
-         * has always meant. The linear-checkpoint hit rate is a different measurement at a
-         * different granularity (spec §7.3) and averaging the two would hide exactly the effect
-         * the decoupling exists to expose, so it is not folded in here. */
-        o.prefix_hit_rate = m.attn_hit_rate;
-        o.prefix_evictions = m.prefix_evictions;
-        /* WHAT ONLY THE CACHE IS HOLDING -- see SchedMetrics::prefix_held_tokens. Clamped to what
-         * the pool reports held: they are counted at different moments in a step and a cached
-         * figure above the used one would draw a negative live share. */
-        o.kv_tokens_cached = std::min(m.prefix_held_tokens, o.kv_tokens_used);
-        o.prefix_ckpt_evictions = m.prefix_ckpt_evictions;
-        o.prefix_expired = m.prefix_expired;
-        o.prefix_ckpt_expired = m.prefix_ckpt_expired;
-
-        o.prefill_tps = m.prefill_tps;
-        o.decode_tps = m.decode_tps;
-        o.draft_acceptance = m.draft_acceptance;
-        o.prefill_tokens = m.prefill_tokens;   o.decode_tokens = m.decode_tokens;
-        o.draft_tokens = m.draft_tokens;       o.draft_accepted = m.draft_accepted;
-        o.draft_refills = m.draft_refills;     o.draft_refill_tokens = m.draft_refill_tokens;
-        o.linear_hit_rate = m.linear_hit_rate;
-        o.attn_cached_tokens = m.attn_cached_tokens;
-        o.linear_cached_tokens = m.linear_cached_tokens;
-        o.checkpoints_written = m.checkpoints_written;
-        o.draft_depth_seen = m.draft_depth_seen;
-        if (o.draft_depth_seen > SchedMetrics::MAX_DRAFT_POS)
-            o.draft_depth_seen = SchedMetrics::MAX_DRAFT_POS;
-        for (int j = 0; j < o.draft_depth_seen; ++j) {
-            o.draft_pos_reached [j] = m.draft_pos_reached [j];
-            o.draft_pos_accepted[j] = m.draft_pos_accepted[j];
-        }
-        o.draft_adaptive = m.draft_adaptive;
-        o.draft_depth_adaptive = m.draft_depth_adaptive;
-        {
-            const int ka = (int)(sizeof m.draft_verify_depth / sizeof m.draft_verify_depth[0]);
-            const int kb = (int)(sizeof o.draft_verify_depth / sizeof o.draft_verify_depth[0]);
-            for (int d = 0; d < ka && d < kb; ++d) o.draft_verify_depth[d] = m.draft_verify_depth[d];
-        }
-        o.preemptions = m.preemptions;
-        o.total_requests = m.admitted;
-        o.steps = m.steps;
-        o.steps_prefill = m.steps_prefill;  o.steps_mixed = m.steps_mixed;
-        o.steps_decode = m.steps_decode;
-        o.steps_ahead = m.steps_ahead;
-        o.prefill_chunks_capped = m.prefill_chunks_capped;
-        o.decode_rows_unspeculated = m.decode_rows_unspeculated;
-        o.step_ns = m.step_ns;  o.step_ns_decode = m.step_ns_decode;
-        return o;
+        return bridge_metrics(s_->observed_metrics());
     }
 
 private:
-    /* DECLARED IN CONSTRUCTION ORDER. Members initialise in declaration order whatever the
-     * initialiser list says, so a list that disagrees with it draws a -Wreorder warning and
-     * becomes a use-before-initialisation the first time one of these is derived from another. */
+    /* Declared in the constructor's initialiser order (-Wreorder). */
     Scheduler*            s_;
     const Sampler*        sampler_ = nullptr;
     const IdleTiers*      tiers_ = nullptr;
@@ -332,9 +326,8 @@ public:
         std::vector out;
         int st = tok_.encode(text, out, add_special, parse_special);
         if (st < 0) {
-            /* The caller checks for an empty result and answers 400. Returning a partial
-             * tokenisation would be worse than returning none: it is a prompt that is silently
-             * not the prompt that was sent. */
+            /* The caller answers 400 on an empty result. A partial tokenisation would silently
+             * serve a different prompt. */
             RAD_WARN("server: tokenise failed: %s", rad_strerror(st));
             out.clear();
         }
@@ -342,9 +335,8 @@ public:
     }
 
     std::string decode(const std::vector& ids) const override {
-        /* Sanitised for the same reason Detokenizer::push is: a token array naming byte-fallback
-         * ids need not decode to well-formed UTF-8, and this text is echoed back inside a JSON
-         * string, where a malformed byte costs the client the whole response. */
+        /* Sanitised like Detokenizer::push: byte-fallback ids need not decode to valid UTF-8,
+         * and one malformed byte in a JSON string breaks the whole response. */
         return utf8_sanitize(tok_.decode(ids, /*render_special=*/false));
     }
     int32_t eos() const override { return vocab_->eos(); }
@@ -366,9 +358,8 @@ public:
         return i;
     }
 
-    /* Vocab::text, sanitised: a byte-level BPE piece is a mapped codepoint sequence that is valid
-     * UTF-8, but a byte-fallback vocabulary's piece need not be, and this goes into a JSON string
-     * where one malformed byte costs the client the whole response. */
+    /* Vocab::text, sanitised: a byte-fallback vocabulary's piece need not be valid UTF-8 (a
+     * byte-level BPE piece always is), and this goes into a JSON string. */
     std::string piece(int32_t id) const override {
         if (id < 0 || id >= vocab_->n_tokens()) return std::string();
         return utf8_sanitize(vocab_->text(id));
@@ -395,25 +386,19 @@ private:
 
 /* ================================================================== chat
  *
- * THE ONE PLACE THE TWO CHAT INTERFACES MEET. core/text's ChatTemplate renders the prompt and the
- * generation prompt; the model's reply format (chatfmt.h) says how the reply is spelled, and
- * everything that depends on the spelling -- the grammar, its trigger words, the tokens the
- * decoder must render, and the parser that reads the reply back -- is derived from that one
- * description here. Two decisions worth stating:
+ * core/text's ChatTemplate renders the prompt and generation prompt. The model's reply format
+ * (chatfmt.h) says how the reply is spelled, and everything depending on the spelling (grammar,
+ * trigger words, tokens the decoder must render, the reply parser) is derived from it here.
  *
- *   * `preserved_tokens` IS CARRIED, and the reason is not the one it has upstream. Upstream it
- *     stops a sampler that bans special tokens from banning the ones a tool-call format is made
- *     of; this sampler has no ban stage at all (core/sample/sampler.h), so there is nothing to
- *     preserve them FROM. It is carried because the DECODER suppresses control tokens, and a
- *     format can be built out of them -- MiniCPM5 writes ` name="city">Berlin`, every tag gone, and comes back to the client as prose.
- *     These, and only these, are decoded as text. If a ban stage is ever added it wants this
- *     same field, for the original reason.
+ *   * `preserved_tokens` lists control tokens the decoder must render as text. The decoder
+ *     suppresses control tokens, and some formats are built from them: MiniCPM5 writes
+ *     `* out) override {
         s_->finish(out ? &ev_ : nullptr);
         move_out(out);
-        /* A reply that left the grammar still came back whole -- a call to a function that is
-         * not a tool, text inside a call, a call after a closing sentence -- but it is worth a
-         * line: it is either a model writing its format loosely or a format described wrongly,
-         * and nothing in the response says which. */
+        /* A reply outside the format (a call to an unknown function, text inside a call, a call
+         * after closing prose) is still returned whole, but logged once: either the model writes
+         * its format loosely or the format is described wrongly. */
         if (!s_->strict() && !warned_) {
             warned_ = true;
             RAD_WARN("server: a reply left the '%s' reply format and was read by its recovery "
@@ -495,13 +479,11 @@ private:
 
 class ChatTemplateBridge final : public IChatTemplate {
 public:
-    /* Returns RAD_OK, or the status ChatTemplate::load_from_vocab gave. A server whose template
-     * did not compile must not be wired: the endpoint answering 501 is a better outcome than one
-     * answering 200 with ChatML-shaped nonsense.
+    /* Returns RAD_OK, or ChatTemplate::load_from_vocab's status. A server whose template did not
+     * compile must not wire it: a 501 beats a 200 with ChatML-shaped nonsense.
      *
      * `declared` is the architecture plugin's reply format (rad_arch_chat_format), or null to
-     * derive it from the template. A declaration the parser cannot run is refused here, at
-     * startup, rather than at the first request that needs it. */
+     * derive it from the template. A declaration the parser cannot run is refused at startup. */
     int init(const Vocab& v, const RadChatFormat* declared = nullptr,
              const std::string& plugin = std::string()) {
         /* The spellings, resolved once. See ReplyOptions::terminators. */
@@ -587,9 +569,8 @@ public:
         ChatPrompt p;
         const int st = t_.apply(messages, tools, o, &p);
         if (st < 0) {
-            /* THE TEMPLATE'S OWN SENTENCE WHERE THERE IS ONE. A jinja `raise_exception` names the
-             * field and the values it accepts; the generic line below names neither, and a caller
-             * reading a 400 has no other way to find out. */
+            /* Prefer the template's own message: a jinja `raise_exception` names the field and
+             * its accepted values, which the generic lines below do not. */
             if (why)
                 *why = !p.error.empty()
                            ? p.error
@@ -680,9 +661,8 @@ private:
 
 /* ================================================================== grammar
  *
- * Compiles at ADMISSION, not at first token, so a schema that cannot be compiled is a 400 naming
- * it rather than a request that starts and then dies on the step path -- and so the scheduler
- * thread never compiles one.
+ * Compiles at admission, not at first token, so an uncompilable schema is a 400 rather than a
+ * request that fails on the step path, and the scheduler thread never compiles.
  */
 class GrammarBridge final : public IGrammarCompiler {
 public:
@@ -692,9 +672,8 @@ public:
         return grammar_from_json_schema(schema.dump(), "root", &out, &err);
     }
 
-    /* The whole compile -- parse, checks and mask plan -- on the admission thread. The program
-     * goes back to ride on the request; the sampler finds it by its text when the request starts,
-     * for as long as the request holds it. */
+    /* The whole compile (parse, checks, mask plan) runs on the admission thread. The program
+     * rides on the request; the sampler finds it by its text while the request holds it. */
     int compile(const std::string& gbnf, std::shared_ptr* out,
                 std::string& err) const override {
         if (gbnf.empty()) return RAD_OK;
@@ -706,10 +685,9 @@ private:
     const VocabView* v_;
 };
 
-/* MEDIA, through the processor the container describes (core/mm). Present only when the program
- * declared an encoder: `accepts` answers from what that encoder said it serves, so a request for
- * video against an image-only tower is refused by the server with a reason rather than processed
- * into patches nothing can encode. */
+/* Media, through the container's processor (core/mm). Present only when the program declares an
+ * encoder; `accepts` follows the modalities that encoder serves, so e.g. video against an
+ * image-only tower is refused with a reason instead of processed into unencodable patches. */
 class MultimodalBridge final : public IMultimodal {
 public:
     MultimodalBridge(const mm::Processor* p, uint32_t modalities) : p_(p), mod_(modalities) {}
@@ -732,6 +710,30 @@ public:
                    : p_->video(bytes.data(), bytes.size(), out, why);
     }
 
+    int32_t audio_rate() const override {
+        return accepts(MediaKind::Audio) ? p_->audio_config().rate : 0;
+    }
+    int64_t audio_max_samples() const override {
+        return accepts(MediaKind::Audio) ? p_->audio_config().max_samples : 0;
+    }
+    int decode_audio(const std::vector& bytes, int64_t max_samples,
+                     std::vector* out, std::string* why) override {
+        if (!accepts(MediaKind::Audio)) { if (why) *why = "audio is not served"; return RAD_E_UNSUPPORTED; }
+        /* One sample past the bound is decoded, so a longer file is refused rather than cut. */
+        RAD_TRY(mm::decode_audio(bytes.data(), bytes.size(), p_->audio_config().rate,
+                                 max_samples + 1, out, why));
+        if ((int64_t)out->size() > max_samples) {
+            if (why) *why = "the recording is longer than this server transcribes";
+            return RAD_E_INVAL;
+        }
+        return RAD_OK;
+    }
+    int prepare_audio(const std::vector& samples, std::shared_ptr* out,
+                      std::string* why) override {
+        if (!accepts(MediaKind::Audio)) { if (why) *why = "audio is not served"; return RAD_E_UNSUPPORTED; }
+        return p_->audio_from(samples, out, why);
+    }
+
 private:
     const mm::Processor* p_;
     uint32_t             mod_;
diff --git a/core/server/admin.cpp b/core/server/admin.cpp
index 505450f8..ff803505 100644
--- a/core/server/admin.cpp
+++ b/core/server/admin.cpp
@@ -1,20 +1,15 @@
 /* core/server/admin.cpp -- vLLM's and llama-server's non-generation endpoints.
  *
  * /version /ping /load /tokenize /detokenize /get_tokenizer_info /server_info /reset_prefix_cache
- * /props.
+ * /props /diagnostics.
  *
- * Separate from server.cpp because none of it touches the step path: no admission, no Sink, no
- * cancellation, nothing that outlives the handler. They are questions ABOUT the server, answered
- * on the HTTP thread and finished before they return, and mixing them into the file that owns the
- * streaming lifetime would make that file harder to read for no shared code at all.
+ * None of these touch the step path (no admission, no Sink, no cancellation); each is answered on
+ * the HTTP thread before it returns, so they are kept out of server.cpp.
  *
- * WHAT IS DELIBERATELY NOT HERE. vLLM's surface also carries /pooling, /classify, /score and
- * /rerank (a classifier or cross-encoder head, which this engine does not load), /sleep, /wake_up
- * and /is_sleeping (there is no sleep mode: weights are placed once, see spec §5), the LoRA
- * adapter endpoints (no LoRA), /invocations (a SageMaker envelope around the others) and the
- * Responses API's stored responses (retrieved or deleted by id: a conversation store, which is a
- * component and not an endpoint); llama-server's carries /slots (its own slot state). Each would
- * be a lie in the shape of a 200, so each is absent and answers 404 rather than pretending.
+ * Deliberately absent, answering 404: vLLM's /pooling, /classify, /score and /rerank (no
+ * classifier or cross-encoder head), /sleep, /wake_up and /is_sleeping (no sleep mode; weights
+ * are placed once, spec §5), the LoRA endpoints (no LoRA), /invocations (a SageMaker envelope),
+ * stored Responses-API responses (would need a conversation store), and llama-server's /slots.
  */
 #include "server.h"
 
@@ -28,18 +23,12 @@ namespace server {
 
 namespace {
 
-/* The body every "how loaded is this server" answer shares. /health and /ping are the same
- * question asked by a load balancer and by a human, and vLLM answers both, so both exist here and
- * neither is a redirect to the other -- a probe that follows a redirect is a probe that reports
- * the redirect's latency. */
-/* `queue_cap` AND NOT `queue_depth`. The value is the CEILING -- `opt_.queue_depth` or
- * max_seqs * 8 -- and it never changes while the server runs. Spelling it "queue_depth" would
- * collide head-on with `radiance:http_queue_depth`, which is the OCCUPANCY ("admitted by the HTTP
- * layer and not yet finished"): one name for two opposite quantities on the same server, so a
- * dashboard graphing both plots a flat ceiling beside a number that moves and calls them the same
- * thing. `queue_depth` therefore means occupancy everywhere it appears, and the occupancy is
- * carried here too under its own names -- `in_flight` on /health and /server_info, `server_load`
- * on /load. */
+/* The body /health and /ping share. vLLM answers both, and neither redirects to the other, so a
+ * probe never measures a redirect.
+ *
+ * `queue_cap` is the admission ceiling (`opt_.queue_depth` or max_seqs * 8), fixed while the
+ * server runs. It is not called `queue_depth` because `radiance:http_queue_depth` is the occupancy;
+ * the occupancy appears here as `in_flight` (and as `server_load` on /load). */
 json health_body(const std::string& model, bool stopping, int64_t in_flight, int64_t depth) {
     json o;
     o["status"]      = stopping ? "stopping" : "ok";
@@ -49,35 +38,15 @@ json health_body(const std::string& model, bool stopping, int64_t in_flight, int
     return o;
 }
 
-/* nlohmann parses "3" and "[1,2]" happily, and both are the wrong shape for every endpoint here.
- * Checking is_object() at the door means each handler's field reads can be plain rather than each
- * one re-deciding what a non-object body means. Bounded like the generation endpoints' bodies
- * (parse_json_bounded): /detokenize takes a token array, which is the body that grows most. */
-bool parse_object(const std::string& body, int64_t max_ctx, json* out, ApiError* err) {
-    *out = json::object();
-    if (body.empty()) return true;              /* {} -- every field takes its default */
-    bool over = false, deep = false;
-    json j = parse_json_bounded(body, max_ctx, &over, &deep);
-    if (deep) {
-        *err = err_bad("body", "the request body nests more than " +
-                                   std::to_string(kJsonMaxDepth) + " levels deep");
-        return false;
+/* Parses a body that must be a JSON object (an empty body is {}, so every field takes its
+ * default). Bounded like a generation body (parse_request_object), since /detokenize takes a
+ * token array of any length. */
+bool parse_object(const std::string& body, const OaiLimits& lim, json* out, ApiError* err) {
+    if (body.empty()) {
+        *out = json::object();
+        return true;
     }
-    if (over) {
-        *err = err_bad("body", "the request body holds more than " +
-                                   std::to_string(json_value_budget(max_ctx)) + " JSON values");
-        return false;
-    }
-    if (j.is_discarded()) {
-        *err = err_bad("body", "the request body is not valid JSON");
-        return false;
-    }
-    if (!j.is_object()) {
-        *err = err_bad("body", "the request body must be a JSON object");
-        return false;
-    }
-    *out = std::move(j);
-    return true;
+    return parse_request_object(body, lim, out, err) == RAD_OK;
 }
 
 bool get_bool_or(const json& b, const char* key, bool def) {
@@ -88,10 +57,8 @@ bool get_bool_or(const json& b, const char* key, bool def) {
 }  /* namespace */
 
 /* ================================================================== /version */
-/* vLLM answers {"version": "..."} and a client that checks compatibility reads exactly that key,
- * so it keeps the name and the shape. The rest is what this engine is, and it is here rather than
- * in /server_info because a client deciding whether to talk to us at all should not have to ask
- * for the whole configuration to find out which ABI the kernels were built against. */
+/* vLLM's {"version": "..."}, which compatibility checks read, plus the engine name and kernel ABI
+ * version so a client need not fetch the whole /server_info for them. */
 HttpResponse Server::handle_version(const HttpRequest&) {
     json o;
     o["version"]     = opt_.version;
@@ -102,10 +69,8 @@ HttpResponse Server::handle_version(const HttpRequest&) {
 }
 
 /* ================================================================== /load */
-/* vLLM's key is `server_load` and it means requests admitted and not yet finished -- which is
- * this server's `in_flight`, the same number admission control refuses on. `queue_cap` comes
- * along because a load figure without its ceiling cannot answer the question a load balancer is
- * actually asking, which is "how much room is left". */
+/* vLLM's `server_load`: requests admitted and not yet finished, i.e. `in_flight`, which admission
+ * control refuses on. `queue_cap` is included so a load balancer can tell how much room is left. */
 HttpResponse Server::handle_load(const HttpRequest&) {
     json o;
     o["server_load"] = in_flight_.load(std::memory_order_relaxed);
@@ -120,18 +85,13 @@ HttpResponse Server::handle_load(const HttpRequest&) {
 }
 
 /* ================================================================== /tokenize */
-/* Two request shapes under one path, exactly as vLLM has it: `prompt` is the completion form and
- * `messages` is the chat form, which renders the template first and tokenises what it produced.
+/* vLLM's two request shapes: `prompt` (completion form) and `messages` (chat form, rendered
+ * through the template, then tokenised), plus llama-server's `content`.
  *
- * `add_special_tokens` DEFAULTS DIFFERENTLY BETWEEN THEM, and that is not an inconsistency to
- * tidy away: a raw prompt wants BOS prepended because nothing else will, while a rendered chat
- * template already contains whatever opening the model expects, and adding another is a prompt
- * with two beginnings. vLLM's defaults are true and false respectively for that reason.
- *
- * PARSE_SPECIAL IS NOT THE CALLER'S CHOICE. The chat form tokenises a string this server rendered
- * and its control tokens must be recognised as themselves; the completion form tokenises text the
- * caller sent, where they must NOT be, or a caller who writes "<|im_start|>system" into `prompt`
- * finds out what this endpoint's token ids do to a subsequent /v1/completions. */
+ * `add_special_tokens` defaults to true for `prompt` and false for `messages`, as in vLLM: a raw
+ * prompt needs BOS prepended, while a rendered template already contains the model's opening.
+ * `parse_special` is not the caller's choice: each form tokenises exactly as /v1/completions or
+ * /v1/chat/completions would, so the count matches what that endpoint sees. */
 HttpResponse Server::handle_tokenize(const HttpRequest& req) {
     if (!deps_.tok)
         return error_response(err_not_implemented("the server has no tokenizer attached"),
@@ -139,7 +99,7 @@ HttpResponse Server::handle_tokenize(const HttpRequest& req) {
 
     json b;
     ApiError err;
-    if (!parse_object(req.body, opt_.max_ctx, &b, &err)) return error_response(err, req.peer);
+    if (!parse_object(req.body, lim_, &b, &err)) return error_response(err, req.peer);
 
     const bool want_strs = get_bool_or(b, "return_token_strs", false);
     std::vector toks;
@@ -151,11 +111,9 @@ HttpResponse Server::handle_tokenize(const HttpRequest& req) {
         return error_response(err_bad("prompt", "send one of `prompt`, `messages` or `content`"),
                               req.peer);
 
-    /* THE THIRD SHAPE IS llama-server's: `content` -- a string, or strings and token ids mixed,
-     * as its /completion takes a prompt -- with its own two flags and its own defaults (no BOS,
-     * control tokens recognised), answered under its own key, `tokens`, as ids or with
-     * `with_pieces` as {id, piece} objects. A piece that is not whole UTF-8 is its bytes, as
-     * llama-server sends it. */
+    /* llama-server's shape: `content` is a string, or strings and token ids mixed (as its
+     * /completion prompt), with its own flags and defaults (no BOS, control tokens recognised).
+     * Answered as `tokens`: ids, or with `with_pieces` {id, piece} objects. */
     if (cont != b.end()) {
         const bool add_special   = get_bool_or(b, "add_special", false);
         const bool parse_special = get_bool_or(b, "parse_special", true);
@@ -256,8 +214,8 @@ HttpResponse Server::handle_tokenize(const HttpRequest& req) {
 }
 
 /* ================================================================== /detokenize */
-/* vLLM's response key is `prompt` -- not `text` -- because the endpoint's purpose is to show what
- * a token array would arrive as. The name is odd and it is the name clients read. */
+/* vLLM's response key is `prompt`, not `text` (the text a token array would arrive as); clients
+ * read that name. */
 HttpResponse Server::handle_detokenize(const HttpRequest& req) {
     if (!deps_.tok)
         return error_response(err_not_implemented("the server has no tokenizer attached"),
@@ -265,7 +223,7 @@ HttpResponse Server::handle_detokenize(const HttpRequest& req) {
 
     json b;
     ApiError err;
-    if (!parse_object(req.body, opt_.max_ctx, &b, &err)) return error_response(err, req.peer);
+    if (!parse_object(req.body, lim_, &b, &err)) return error_response(err, req.peer);
 
     auto t = b.find("tokens");
     if (t == b.end() || !t->is_array())
@@ -292,19 +250,17 @@ HttpResponse Server::handle_detokenize(const HttpRequest& req) {
 }
 
 /* ================================================================== /props */
-/* llama-server's /props, for the clients built against it: a front-end that sizes its context
- * from default_generation_settings.n_ctx, shows an image button when modalities.vision is set,
- * and reads what a request that sends no sampler fields inherits. /server_info says all of it and
- * more, but nothing written for llama-server knows to ask there.
+/* llama-server's /props, for clients built against it: front-ends size their context from
+ * default_generation_settings.n_ctx, show an image button for modalities.vision, and read the
+ * default sampler settings. /server_info has all of it, but llama-server clients do not ask there.
  *
  * Only what this server can fill honestly, under llama-server's names: no GGUF metadata, no
- * per-slot state. n_ctx is the context ONE request may use, which is what llama-server's per-slot
- * n_ctx means to the clients reading it; left out when the server does not know its length. */
+ * per-slot state. n_ctx is the context one request may use (llama-server's per-slot n_ctx);
+ * omitted when the context length is unknown. */
 HttpResponse Server::handle_props(const HttpRequest&) {
     const SamplingParams& sp = opt_.default_sampling;
-    /* EVERY FIELD llama-server's `params` CARRIES, so a client that reads one does not find it
-     * missing. The samplers this server does not run are reported at their off values -- which
-     * is what it serves -- and `samplers` is its own order, temperature first. */
+    /* Every field llama-server's `params` carries, so no client finds one missing. Samplers this
+     * server does not run are reported at their off values, which is what it serves. */
     const int64_t n_predict = opt_.default_max_tokens > 0 ? opt_.default_max_tokens : -1;
     json params;
     params["n_predict"]           = n_predict;
@@ -329,9 +285,8 @@ HttpResponse Server::handle_props(const HttpRequest&) {
     params["dry_base"]            = sp.dry_base;
     params["dry_allowed_length"]  = sp.dry_allowed_length;
     params["dry_penalty_last_n"]  = sp.dry_penalty_last_n;
-    params["dry_sequence_breakers"] = sp.dry_seq_breakers.empty() && !opt_.default_dry_breakers_set
-                                    ? std::vector{ "\n", ":", "\"", "*" }
-                                    : sp.dry_seq_breakers;
+    params["dry_sequence_breakers"] = dry_breakers(sp.dry_seq_breakers,
+                                                   opt_.default_dry_breakers_set);
     params["mirostat"]            = 0;
     params["mirostat_tau"]        = 5.0;
     params["mirostat_eta"]        = 0.1;
@@ -395,10 +350,9 @@ HttpResponse Server::handle_props(const HttpRequest&) {
 }
 
 /* ================================================================== /get_tokenizer_info */
-/* vLLM returns the HuggingFace tokenizer config verbatim, which this engine does not have: a .rad
- * container carries a normalised vocabulary and not the JSON it was built from. So this answers
- * the questions that config is actually READ for -- how big is the vocabulary, which ids end a
- * generation, is a chat template available -- and says nothing it would have to invent. */
+/* vLLM returns the HuggingFace tokenizer config verbatim, which a .rad container does not carry
+ * (it holds a normalised vocabulary). This answers what that config is read for: vocabulary size,
+ * the special ids, and whether a chat template is available. */
 HttpResponse Server::handle_tokenizer_info(const HttpRequest& req) {
     if (!deps_.tok)
         return error_response(err_not_implemented("the server has no tokenizer attached"),
@@ -429,8 +383,8 @@ json Server::capabilities() const {
     caps["chat"]      = deps_.chat != nullptr;
     caps["tools"]     = deps_.chat && deps_.chat->supports_tools();
     caps["reasoning"] = deps_.chat && deps_.chat->supports_reasoning();
-    /* An image model reads pictures for its edits and nothing else, and writes no text a grammar
-     * could constrain -- whatever its conditioning network's processor would take. */
+    /* An image model reads pictures only for edits and writes no text a grammar could constrain,
+     * whatever its conditioning network's processor would take. */
     const bool img = opt_.image_model;
     caps["grammar"]   = !img && deps_.grammar != nullptr;
     caps["embedding"] = deps_.embed != nullptr;
@@ -440,8 +394,8 @@ json Server::capabilities() const {
     caps["logprobs"]  = opt_.supports_logprobs;
     caps["image_generation"] = deps_.images != nullptr;
     caps["image_edit"]       = deps_.images != nullptr && deps_.images->info().max_refs > 0;
-    /* THE EFFORTS A CHAT REQUEST MAY SEND, as probed from the template at startup: null when it
-     * takes any word. "none" and "minimal" are this server's, and turn thinking off. */
+    /* The efforts a chat request may send, probed from the template at startup; null when it
+     * takes any word. "none" and "minimal" are this server's and turn thinking off. */
     if (lim_.reasoning_efforts.empty()) {
         caps["reasoning_efforts"] = nullptr;
     } else {
@@ -453,14 +407,10 @@ json Server::capabilities() const {
 }
 
 /* ================================================================== /server_info */
-/* vLLM returns the repr() of its config object, which is a Python string a client can only print.
- * This returns the same information as JSON, in two halves: what the SERVER decided, which is
- * this component's own state, and what the ENGINE decided, which arrives pre-rendered because the
- * server knows nothing about devices, containers or placement (ServerOptions::engine_info).
- *
- * `endpoints` is the router's own table rather than a list kept beside it. A hand-written list is
- * a list that goes stale the first time somebody adds a route, and this endpoint exists precisely
- * so that a client does not have to guess what is served. */
+/* vLLM returns the repr() of its config; this returns the information as JSON: the server's own
+ * state, plus the engine's, pre-rendered because the server knows nothing about devices,
+ * containers or placement (ServerOptions::engine_info). `endpoints` is the router's own table, so
+ * it cannot go stale. */
 HttpResponse Server::handle_server_info(const HttpRequest&) {
     json srv;
     srv["model"]              = opt_.model_id;
@@ -480,8 +430,7 @@ HttpResponse Server::handle_server_info(const HttpRequest&) {
 
     json caps = capabilities();
 
-    /* WHAT A REQUEST THAT LEAVES A FIELD OUT GETS, under the request's own spelling of each
-     * field, so a client can read off exactly what leaving one out means on this deployment. */
+    /* What a request that omits a field gets, under the request's own field names. */
     const SamplingParams& sp = opt_.default_sampling;
     json defs;
     defs["temperature"]        = sp.temp;
@@ -497,9 +446,8 @@ HttpResponse Server::handle_server_info(const HttpRequest&) {
     defs["dry_base"]           = sp.dry_base;
     defs["dry_allowed_length"] = sp.dry_allowed_length;
     defs["dry_penalty_last_n"] = sp.dry_penalty_last_n;
-    defs["dry_sequence_breakers"] = opt_.default_dry_breakers_set
-                                        ? json(sp.dry_seq_breakers)
-                                        : json(std::vector{ "\n", ":", "\"", "*" });
+    defs["dry_sequence_breakers"] = dry_breakers(sp.dry_seq_breakers,
+                                                 opt_.default_dry_breakers_set);
     defs["xtc_probability"]    = sp.xtc_probability;
     defs["xtc_threshold"]      = sp.xtc_threshold;
     defs["max_tokens"]         = srv["default_max_tokens"];
@@ -524,10 +472,8 @@ HttpResponse Server::handle_server_info(const HttpRequest&) {
     o["capabilities"]     = std::move(caps);
     o["endpoints"]    = router_.routes();
 
-    /* Spliced rather than re-parsed field by field: the engine owns what it says about itself and
-     * this component is a pipe for it. A blob that is not an object is dropped with a warning
-     * instead of corrupting the response -- an unparseable /server_info is worse than one that is
-     * missing a section. */
+    /* Spliced in whole; the engine owns its contents. A blob that is not a JSON object is dropped
+     * with a warning rather than corrupting the response. */
     if (!opt_.engine_info.empty()) {
         json e = json::parse(opt_.engine_info, nullptr, false);
         if (e.is_discarded() || !e.is_object())
@@ -540,13 +486,10 @@ HttpResponse Server::handle_server_info(const HttpRequest&) {
 }
 
 /* ================================================================== /diagnostics */
-/* The startup report, read again for this request (ServerOptions::diagnostics_json). Behind the
- * bearer key like /server_info: it names the machine's devices and boot parameters.
- *
- * AND WITHOUT A KEY, ONLY TO THIS MACHINE. /server_info without a key describes the model a
- * client is already talking to; this describes the host -- its kernel, its boot parameters, its
- * PCI layout, its memory limits -- which a server bound to 0.0.0.0 with no key would otherwise
- * hand to anyone who can reach the port. A key is the operator's statement of who may ask. */
+/* The startup report, regenerated per request (ServerOptions::diagnostics_json), behind the API
+ * key like /server_info. Without a key it is served to loopback clients only: it describes the
+ * host (kernel, boot parameters, PCI layout, memory limits), which a keyless server bound to
+ * 0.0.0.0 would otherwise hand to anyone who can reach the port. */
 HttpResponse Server::handle_diagnostics(const HttpRequest& req) {
     if (!opt_.diagnostics_json)
         return error_response(err_not_implemented(
@@ -556,9 +499,8 @@ HttpResponse Server::handle_diagnostics(const HttpRequest& req) {
         ApiError e;
         e.status = 403;
         e.type = "permission_error";
-        e.message = "/diagnostics describes this machine, and a server started without --api-key "
-                    "answers it only to a client on the same machine (a loopback address); start "
-                    "it with --api-key to read it from elsewhere";
+        e.message = "without --api-key, /diagnostics answers only loopback clients; start the "
+                    "server with --api-key to read it from elsewhere";
         return error_response(e, req.peer);
     }
     metrics_.observe_http(200);
@@ -566,9 +508,8 @@ HttpResponse Server::handle_diagnostics(const HttpRequest& req) {
 }
 
 /* ================================================================== /reset_prefix_cache */
-/* 501 when there is no prefix cache to reset, and that is the point: vLLM answers 200 with an
- * empty body whether or not anything happened, so a benchmark that thinks it started cold has no
- * way to find out it did not. This says how many entries went. */
+/* 501 when there is no prefix cache to reset (vLLM answers 200 regardless, so a benchmark cannot
+ * tell whether it started cold). Reports how many entries were dropped. */
 HttpResponse Server::handle_reset_prefix_cache(const HttpRequest& req) {
     if (!deps_.sched)
         return error_response(err_not_implemented("the server has no engine attached"), req.peer);
@@ -586,9 +527,8 @@ HttpResponse Server::handle_reset_prefix_cache(const HttpRequest& req) {
 }
 
 /* ================================================================== /health, /ping */
-/* NOT counted in the HTTP status metrics, and neither is /metrics. A load balancer probing every
- * second would otherwise dominate `request_success_total` and make the 2xx/5xx ratio a statement
- * about the probe rather than about the service. */
+/* Not counted in the HTTP status metrics (nor is /metrics): a load balancer probing every second
+ * would dominate the 2xx/5xx ratio. */
 HttpResponse Server::handle_health(const HttpRequest& req) { return handle_ping(req); }
 
 HttpResponse Server::handle_ping(const HttpRequest&) {
diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp
index 3c7ab84b..4c4e24b2 100644
--- a/core/server/dashboard.cpp
+++ b/core/server/dashboard.cpp
@@ -1,22 +1,16 @@
 /* core/server/dashboard.cpp -- the web view of a running engine.
  *
- * Two routes: `/` serves a page, `/stats` serves the JSON it polls. Nothing else, and no
- * framework: the page is a string literal in this file, so there is no asset directory to install,
- * no build step that can go stale against the binary, and no network fetch at all. This engine is
- * deployed on machines with no route to a CDN, and a dashboard that renders blank without one is
- * a dashboard that does not exist.
+ * `/` serves the page and `/stats` the JSON it polls (plus `/sessions` and `/graph`). No
+ * framework: the page is a string literal in this file, so there is no asset directory, no build
+ * step that can go stale against the binary, and no network fetch; the engine runs on machines
+ * with no route to a CDN.
  *
- * WHY IT IS NOT JUST /metrics. Prometheus exposition is the right answer for an operator who has
- * a Prometheus, and this server serves it. It is the wrong answer for the question
- * being asked here -- "what is this process doing right now" -- because getting to that answer
- * costs a scrape config, a time-series database and a Grafana dashboard somebody has to build.
- * The engine already has a terminal view for exactly this (liveview.h, spec §16); this is the
- * same snapshot in a browser, which is where it can be looked at from another machine.
+ * /metrics serves Prometheus, but answering "what is this process doing right now" from it needs a
+ * scrape config, a time-series database and a Grafana dashboard. This is the terminal view's
+ * snapshot (liveview.h, spec §16) in a browser, viewable from another machine.
  *
- * THE PER-POSITION DRAFT PANEL IS THE POINT. Everything else here is visible in some other tool.
- * The conditional acceptance at each draft position is not: it is in SchedMetrics and in /metrics
- * as a labelled gauge, and no ordinary reading of either shows that one late position collapsed
- * while the pooled rate stayed plausible. As a bar chart it is the first thing seen.
+ * The per-position draft panel shows what no pooled metric does: one late draft position
+ * collapsing while the pooled acceptance rate stays plausible.
  */
 #include "server.h"
 
@@ -30,22 +24,17 @@ namespace rad {
 namespace server {
 
 /* ================================================================== /stats */
-/* One object, polled. It carries the scheduler's metrics, the per-position draft table and
- * whatever the engine's snapshot function could see -- and it is deliberately NOT a stable
- * public API: /metrics is that, with vLLM's names, and this is free to say whatever the page
- * needs. A client automating against radiance should scrape /metrics.
+/* One polled object: the scheduler's metrics, the per-position draft table and whatever the
+ * engine's snapshot function provides. Not a stable public API; automation should scrape /metrics.
  *
- * DERIVED RATES ARE THE PAGE'S JOB, not this handler's. Tokens a second and milliseconds a step
- * are differences of counters over wall time, and the browser has both endpoints of the interval
- * while this handler has neither -- computing them here would mean holding per-client state for
- * something the client can subtract. */
+ * Derived rates are the page's job: they are counter differences over wall time, and only the
+ * browser holds both ends of its poll interval. Computing them here would need per-client state. */
 
 /* ------------------------------------------------------------------ /sessions
  *
- * ITS OWN ROUTE, not a field in /stats. The dashboard polls /stats every second and a stored
- * session changes on the scale of its idle thresholds -- tens of seconds at the fastest. Folding
- * a table of conversations into the per-second poll would carry the same bytes a hundred times
- * for each change in them, and the view that reads it is not even on screen most of the time. */
+ * A separate route, not a /stats field: /stats is polled every second, while a stored session
+ * changes on the scale of its idle thresholds (tens of seconds at the fastest), and the view that
+ * reads this is usually off screen. */
 HttpResponse Server::handle_sessions(const HttpRequest&) {
     json o;
     std::vector v;
@@ -67,9 +56,8 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
         e["on_device"] = s.on_device;
         e["on_host"]   = s.on_host;
         e["moving"]    = s.moving;
-        /* THE RECURRENT HALF. On a hybrid model a session's attention blocks are only part of
-         * what it needs back; the rest is its linear-state snapshots, which are a different size
-         * of object in a different store, in host memory. */
+        /* On a hybrid model a session also needs its linear-state snapshots back: a different
+         * object size, kept in a separate store in host memory. */
         e["snapshots"]   = s.snapshots;
         e["snap_bytes"]  = s.snap_bytes;
         e["resume_tokens"] = s.resume_tokens;
@@ -79,19 +67,15 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
         bytes += s.bytes;
     }
     o["sessions"] = std::move(a);
-    /* SAID HERE SO A READER DOES NOT HAVE TO INFER IT. Two sessions sharing a system prompt share
-     * the blocks for it, so these per-session sizes overlap and adding them up over-counts -- on
-     * a server carrying long agent transcripts by more than an order of magnitude. The field
-     * names say so rather than pretending the sums are totals. */
+    /* Sessions sharing a prefix share its blocks, so these sums over-count (by more than an order
+     * of magnitude with long agent transcripts); the field names say so. */
     o["blocks_sum_overlapping"] = { { "device", dev }, { "host", host } };
     o["snapshots_sum_overlapping"] = snaps;
     o["bytes_sum_overlapping"] = bytes;
     const SchedMetrics sm = deps_.sched ? deps_.sched->metrics() : SchedMetrics{};
-    /* AND THE ONE FIGURE THAT IS NOT A SUM, because a view about what the conversations cost has
-     * to be able to say what the card is actually holding. The pool counts a block once however
-     * many sessions name it, which is the number an operator is asking for and the only one the
-     * per-session rows cannot be made to yield. One group's, the binding one -- see
-     * SchedMetrics::kv_tokens_used for why tokens across paged groups are not additive. */
+    /* What the card actually holds: the pool counts a block once however many sessions name it,
+     * which the per-session rows cannot yield. Tokens are the binding group's only; see
+     * SchedMetrics::kv_tokens_used for why paged groups are not additive. */
     o["pool"] = { { "tokens_used",     sm.kv_tokens_used },
                   { "tokens_total",    sm.kv_tokens_total },
                   { "unshared_tokens", sm.kv_tokens_cached },
@@ -101,31 +85,36 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
         deps_.sched ? deps_.sched->tier_counters() : IScheduler::TierCounters{};
     o["moved"] = { { "to_host", c.to_host }, { "dropped", c.dropped },
                    { "promoted", c.promoted }, { "host_drops", c.host_drops },
+                   { "held_back", c.held_back },
                    { "failures", c.failures } };
-    /* THE SNAPSHOT STORE, on a hybrid model: what one snapshot costs and how many the store
-     * holds. `bytes_each` is 0 on a model with no recurrent state. */
+    /* Snapshot store on a hybrid model: bytes per snapshot and slot count. `bytes_each` is 0
+     * on a model with no recurrent state. */
     o["snapshot_store"] = { { "bytes_each", c.ck_bytes }, { "slots", c.ck_slots } };
-    /* WHAT --prefix-cache-ttl TOOK, entries and snapshots, from whichever tier held them. */
+    /* Entries and snapshots removed by --prefix-cache-ttl, from whichever tier held them. */
     o["expired"] = { { "entries", sm.prefix_expired }, { "snapshots", sm.prefix_ckpt_expired } };
-    /* THE STEP THREAD'S TIME ON THE TIERS: every request waits through it. */
+    /* Step-thread time spent on tier moves; every request waits through it. */
     o["stall"] = { { "restores", c.restores }, { "restore_ms", (double)c.restore_ns / 1e6 },
                    { "flushes", c.flushes }, { "flush_ms", (double)c.flush_ns / 1e6 } };
-    /* AND WHETHER ANY OF IT IS BEING READ. Moving a snapshot and restoring it proves the bytes
-     * travelled; this is the number that says a lookup then SERVED one. A hybrid server can move
-     * snapshots all day and still replay from token zero if the checkpoint the restore put back
-     * is not the one a hit can reach. */
+    /* Whether restored snapshots are served. A hybrid server can move snapshots and still replay
+     * from token zero if the restored checkpoint is not one a hit can reach. */
     o["linear"] = { { "hit_rate", sm.linear_hit_rate },
                     { "cached_tokens", sm.linear_cached_tokens },
-                    { "checkpoints_written", sm.checkpoints_written } };
-    /* WHETHER ANYTHING MOVES, which is not whether anything is STORED. A session is recorded
-     * whether or not it can be demoted, so a non-empty table says only that something is held;
-     * these say whether a tier exists that can move it. */
+                    { "checkpoints_written", sm.checkpoints_written },
+                    { "evictions", { { "retention", sm.prefix_ckpt_retired },
+                                     { "store_full", sm.prefix_ckpt_lru } } },
+                    { "refused", sm.prefix_ckpt_refused },
+                    { "hit_cuts", { { "no_snapshot", sm.hit_cut_no_snapshot },
+                                    { "windowed_group", sm.hit_cut_window },
+                                    { "adopt_failed", sm.hit_cut_adopt } } },
+                    { "hit_cut_tokens", sm.hit_cut_tokens } };
+    /* Whether a tier exists to move sessions to. A session is recorded whether or not it can be
+     * demoted, so a non-empty table only says something is held. */
     o["tiers"] = { { "host", c.host_on } };
-    /* WHAT IS OFF THE CARD, counted once -- see SessionOccupancy. */
+    /* Off-card bytes, counted once; see SessionOccupancy. */
     o["occupancy"] = { { "host_bytes", occ.host_bytes },
                        { "host_cap_bytes", occ.host_cap_bytes } };
-    /* THE ATTENTION HIT RATE, for a model with no recurrent state, where it is the whole answer
-     * to how much of the prompt the cache served. On a hybrid model `linear.hit_rate` is. */
+    /* The attention hit rate: the whole answer on a model with no recurrent state. On a hybrid
+     * model, read `linear.hit_rate`. */
     o["prefix_hit_rate"] = sm.prefix_hit_rate;
     o["enabled"] = c.host_on;
     return HttpResponse::json_body(200, json_dump(o));
@@ -148,34 +137,36 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
         o["kv_util"]         = m.kv_util;
         o["kv_tokens_used"]  = m.kv_tokens_used;
         o["kv_tokens_total"] = m.kv_tokens_total;
-        /* AND THE PART OF `used` THAT NO RUNNING REQUEST IS READING. Held is held, so a finished
-         * turn's blocks are in the figure above for exactly as long as the cache keeps them --
-         * and on a server carrying conversations that is most of a full pool. Without the split
-         * a cache doing its job and a pool that never releases draw the same bar. */
+        /* The part of `used` no running request reads: cached blocks of finished turns. Without
+         * the split, a working cache and a pool that never releases look the same. */
         o["kv_tokens_cached"] = m.kv_tokens_cached;
-        /* THE POOL IN BYTES BESIDE THE POOL IN TOKENS, because they answer different questions and
-         * only one of them is about the card. Tokens say how much context fits; bytes say how much
-         * VRAM is being held, which is what a reader comparing the cache against the weights and
-         * against the card's total is asking. The two are not a unit conversion of each other:
-         * tokens are the binding paged group's and bytes are every group's, recurrent included. */
+        /* The pool in bytes beside tokens: tokens say how much context fits, bytes how much VRAM
+         * is held. Not a unit conversion: tokens are the binding paged group's, bytes are every
+         * group's, recurrent included. */
         o["kv_bytes_used"]   = (double)m.kv_bytes_used;
         o["kv_bytes_total"]  = (double)m.kv_bytes_total;
         o["kv_bytes_carved"] = (double)m.kv_bytes_carved;
         o["kv_tokens_max"]   = m.kv_tokens_max;
         o["prefix_hit_rate"] = m.prefix_hit_rate;
-        /* The leading indicator beside the lagging one: past ~75% kv utilisation the cache
-         * begins dropping prefixes the next turn wants, and the hit rate only falls once
-         * that has happened. An agent turn that re-prefills from scratch costs orders of
-         * magnitude more than one that resumes from the cache. */
+        /* Leading indicator beside the lagging hit rate: past ~75% kv utilisation the cache
+         * starts dropping prefixes the next turn wants. */
         o["prefix_evictions"] = (double)m.prefix_evictions;
-        /* THE LINEAR HALF, WHICH THE ATTENTION HIT RATE SAYS NOTHING ABOUT. On a hybrid model a
-         * prompt can be 100% attention-cached and still re-run every recurrent layer over its
-         * whole prefix, because the two hit at different granularities. Without these a
-         * deployment cannot tell whether linear checkpointing is working at all. Zero throughout
-         * on a model with no recurrent state. */
+        /* Linear-state caching, separate from the attention hit rate: a hybrid prompt can be
+         * fully attention-cached and still re-run every recurrent layer over its prefix, since
+         * the two hit at different granularities. Zero on a model with no recurrent state. */
         o["linear_hit_rate"] = m.linear_hit_rate;
         o["linear_cached_tokens"] = (double)m.linear_cached_tokens;
         o["checkpoints_written"] = (double)m.checkpoints_written;
+        /* Why snapshots went and why hits reused nothing: on a hybrid model these say why a
+         * long prompt was prefilled again. `hit_cut_tokens` is the checkpoint shortfall,
+         * prompt tokens the attention cache held and admission computed again. */
+        o["ckpt_evictions"]  = { { "retention", m.prefix_ckpt_retired },
+                                 { "store_full", m.prefix_ckpt_lru } };
+        o["ckpt_refused"]    = m.prefix_ckpt_refused;
+        o["hit_cuts"]        = { { "no_snapshot", m.hit_cut_no_snapshot },
+                                 { "windowed_group", m.hit_cut_window },
+                                 { "adopt_failed", m.hit_cut_adopt } };
+        o["hit_cut_tokens"]  = (double)m.hit_cut_tokens;
         o["prefill_tps"]     = m.prefill_tps;
         o["decode_tps"]      = m.decode_tps;
         o["draft_accept"]    = m.draft_acceptance;
@@ -186,18 +177,15 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
         o["steps_mixed"]     = m.steps_mixed;
         o["prefill_chunks_capped"] = m.prefill_chunks_capped;
         o["steps_decode"]    = m.steps_decode;
-        /* WHAT THE STEPS COST, so the page does not have to divide wall clock by a step count.
-         * That is the derivation this handler's header calls the page's job, and it is the one
-         * derivation the page cannot do: the browser's two endpoints bracket the engine's IDLE
-         * time as well as its work, and an agent client is idle between turns. See
-         * SchedMetrics::step_ns. */
+        o["steps_held"]      = m.steps_held;
+        /* Time inside steps. The one rate the page cannot derive: wall clock between polls also
+         * covers idle time (see SchedMetrics::step_ns). */
         o["step_ns"]         = m.step_ns;
         o["step_ns_decode"]  = m.step_ns_decode;
         o["rows_unspec"]     = m.decode_rows_unspeculated;
 
-        /* THE CONDITIONAL RATE AT EACH POSITION, with the reach count beside it. Both are needed
-         * and neither alone means anything: a position with a rate of 0.0 and a reach of 3 is
-         * noise, and one with a rate of 0.0 and a reach of 40000 is a broken draft round. */
+        /* Conditional rate per position with its reach count: a rate of 0.0 over a reach of 3 is
+         * noise, over a reach of 40000 a broken draft round. */
         json pos = json::array();
         for (int j = 0; j < m.draft_depth_seen && j < SchedMetrics::MAX_DRAFT_POS; ++j) {
             json p;
@@ -209,9 +197,8 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
         }
         o["draft_positions"] = std::move(pos);
 
-        /* THE LIVE REQUEST TABLE. Counters and timestamps, not rates the page could not check:
-         * `decode_tps` is this request's own average since its first token, which is the number
-         * that stays meaningful when a request has been running for four minutes. */
+        /* Live request table: counters and timestamps. `decode_tps` is the request's own average
+         * since its first token. */
         std::vector rq;
         deps_.sched->requests(&rq);
         json reqs = json::array();
@@ -237,9 +224,8 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
         o["requests"] = std::move(reqs);
     }
 
-    /* The engine's half. Absent when nothing supplied a snapshot function, in which case the page
-     * omits the panels rather than drawing zeroes -- an empty VRAM bar reads as "no memory used",
-     * which is a much worse answer than no bar. */
+    /* The engine's snapshot. Absent without a snapshot function, and the page then omits those
+     * panels rather than drawing zeroes (an empty VRAM bar would read as "no memory used"). */
     if (deps_.live) {
         LiveSnapshot s;
         deps_.live(s);
@@ -259,11 +245,8 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
         }
         o["cards"] = std::move(cards);
 
-        /* THE EXPERT PANEL'S DATA. The plane is the picture; everything beside it is what the
-         * picture cannot say -- how much of the model is resident in BYTES, whether the residency
-         * is spread across layers or piled into the first ones, and whether the move traffic is
-         * discovery or thrash. Counted in the engine (liveview.h), not here and not in the page:
-         * three tallies of one snapshot is three chances to disagree. */
+        /* Expert panel data (see ExpertPlane in liveview.h). Tallied once in the engine, not here
+         * or in the page, so all views agree. */
         if (s.experts.n_layers > 0 && s.experts.n_experts > 0) {
             json e;
             e["n_layers"]   = s.experts.n_layers;
@@ -273,8 +256,7 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
             e["bytes"]      = s.experts.total_bytes;
             e["movable"]    = s.experts.movable;
             e["heat"]       = s.experts.heat_enabled;
-            /* One row per tier, named -- the page must not hold its own copy of the enum's order,
-             * which is the kind of duplication that survives a reordering and then lies. */
+            /* One named row per tier, so the page holds no copy of the enum's order. */
             json tiers = json::array();
             for (int t = 0; t < kTierCount; ++t) {
                 json r;
@@ -309,8 +291,7 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
             o["experts"] = std::move(e);
         }
 
-        /* THE LINK. Cumulative byte counters and nothing derived: both ends of the poll interval
-         * are in the browser and neither is here, exactly as for step time above. */
+        /* Link traffic: cumulative byte counters only; the page derives rates. */
         if (s.link.present) {
             json l;
             l["world"]          = s.link.world;
@@ -340,21 +321,17 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
         }
     }
 
-    /* No metrics_.observe_http here, and the same reasoning as /health: a page polling twice a
-     * second would make request_success_total a statement about the dashboard. */
+    /* Not counted in metrics_.observe_http, as for /health: a page polling twice a second would
+     * make the request counters describe the dashboard. */
     return HttpResponse::json_body(200, json_dump(o));
 }
 
 
 /* ================================================================== /graph */
-/* THE DECLARED COMPUTE GRAPH: every op, its bucket table, the kernel that resolved each band, the
- * library it came from, the constraints it matched on and the chain it stands in for.
- *
- * `--debug-graph` prints all of this, but printing it is not the same as being able to look at it:
- * the text dump answers the question on a terminal, at startup, on the machine the engine is on.
- * This is the same walk (dump_graph_json shares every helper with the text one) served from the
- * process that is actually running, which is where the question is usually asked. Static after
- * declare, so it is rendered once and handed over. */
+/* The declared compute graph: every op, its bucket table, the kernel that resolved each band, its
+ * library, the constraints it matched and the chain it stands in for. The same walk as
+ * `--debug-graph` (dump_graph_json shares its helpers), served from the running process. Static
+ * after declare, so it is rendered once. */
 HttpResponse Server::handle_graph(const HttpRequest& req) {
     if (!opt_.graph_json)
         return error_response(err_not_implemented(
@@ -367,21 +344,16 @@ HttpResponse Server::handle_graph(const HttpRequest& req) {
 }
 
 /* ================================================================== the page */
-/* One string. It is long, and every alternative is worse: a file on disk is a file that can be
- * missing or stale against the binary, a generated header is a build step, and a framework is a
- * network fetch. It parses no untrusted input -- every value it renders comes from /stats on the
- * same origin and goes in through textContent or a numeric attribute, never innerHTML.
+/* One string, so it cannot go missing or stale against the binary and needs no build step or
+ * network fetch. It parses no untrusted input: every value comes from same-origin /stats and goes
+ * in through textContent or a numeric attribute, never innerHTML.
  *
- * IT IS BUILT ONCE AND UPDATED IN PLACE. A dashboard that rebuilds its DOM twice a second lays
- * the document out twice a second, drops the reader's text selection every time, and flickers --
- * and it does that on the machine the engine is being watched from. Elements are created when
- * their SHAPE changes (a different draft depth, a different card count) and after that only
- * textContent and one style property are written.
+ * Built once and updated in place: elements are created only when a panel's shape changes (draft
+ * depth, card count); after that only textContent and one style property are written. Rebuilding
+ * the DOM every poll would relayout, flicker and drop the reader's text selection.
  *
- * The design rules are the terminal view's (spec §16) in a browser: a number nobody sampled is
- * blank rather than zero, a section with no data is hidden rather than empty, and nothing moves
- * that is not actually changing. Black, one weight, one accent -- the numbers are the content and
- * everything else on the page is there to not compete with them. */
+ * Display rules: an unsampled number is blank, not zero; a section without data is hidden;
+ * nothing moves that is not changing. Black, one weight, one accent. */
 static const char* const kPage = R"HTML(
 
 
@@ -2996,8 +2968,8 @@ HttpResponse Server::handle_dashboard(const HttpRequest&) {
     r.status = 200;
     r.content_type = "text/html; charset=utf-8";
     r.body = kPage;
-    /* No caching: the page and the binary ship together, so a browser holding yesterday's copy
-     * against today's /stats is a shape mismatch with no symptom other than blank panels. */
+    /* No caching: the page must match the binary's /stats shape, and a stale copy shows only
+     * blank panels. */
     r.set_header("Cache-Control", "no-store");
     return r;
 }
diff --git a/core/server/http.cpp b/core/server/http.cpp
index e44a09e1..a3c605a2 100644
--- a/core/server/http.cpp
+++ b/core/server/http.cpp
@@ -1,8 +1,8 @@
 #include "http.h"
 #include "rad_internal.h"
+#include "text/tokenizer.h"
 
-/* httplib pulls in ,  and a great deal else. It is included in exactly this
- * translation unit so that nothing above the transport seam pays for it. */
+/* httplib pulls in ,  and much else; only this unit includes it. */
 #include "cpp-httplib/httplib.h"
 
 #include 
@@ -33,6 +33,12 @@ std::string HttpRequest::header(const std::string& k, const std::string& def) co
     return it == headers.end() ? def : it->second;
 }
 
+const FormPart* HttpRequest::part(const std::string& k) const {
+    for (const FormPart& p : form)
+        if (p.name == k) return &p;
+    return nullptr;
+}
+
 std::string HttpRequest::param(const std::string& k, const std::string& def) const {
     auto it = params.find(k);
     if (it != params.end()) return it->second;
@@ -77,11 +83,9 @@ HttpResponse HttpResponse::text(int status, std::string body) {
 
 /* ------------------------------------------------------------------ target parsing */
 
-/* `+` IS A SPACE IN A QUERY STRING AND A PLUS SIGN IN A PATH. The two halves of a target are
- * decoded by different rules: the form encoding that gives `+` its second meaning applies to
- * `application/x-www-form-urlencoded` data, which is what a query string is and what a path is
- * not. Decoding a path the query's way renames a route -- /v1/models/gpt+4 becomes a request for
- * "gpt 4", which resolves to nothing and reports the name it was not asked about. */
+/* `+` is a space in a query string and a plus sign in a path: the form encoding
+ * (application/x-www-form-urlencoded) applies to a query only. Decoding a path the query's way
+ * would turn /v1/models/gpt+4 into a request for "gpt 4". */
 std::string url_decode(const std::string& s, bool plus_is_space) {
     std::string out;
     out.reserve(s.size());
@@ -137,6 +141,22 @@ void Router::add(std::string method, std::string path, Handler h) {
     routes_.push_back(Route{std::move(method), split_path(path), std::move(h)});
 }
 
+void Router::socket(std::string path, SocketHandler h) {
+    sockets_.emplace_back(std::move(path), std::move(h));
+}
+
+const SocketHandler* Router::socket_for(const std::string& path) const {
+    for (const auto& s : sockets_)
+        if (s.first == path) return &s.second;
+    return nullptr;
+}
+
+std::vector Router::socket_routes() const {
+    std::vector out;
+    for (const auto& s : sockets_) out.push_back(s.first);
+    return out;
+}
+
 std::vector Router::routes() const {
     std::vector out;
     for (auto& r : routes_) {
@@ -147,46 +167,87 @@ std::vector Router::routes() const {
     return out;
 }
 
-static std::string error_body(const char* type, const std::string& msg) {
-    /* Hand-rolled rather than routed through nlohmann, because this is the one error path that
-     * must work even if the JSON layer is what failed. */
+bool anthropic_path(const std::string& path) {
+    return path == "/v1/messages" || path.rfind("/v1/messages/", 0) == 0;
+}
+
+const char* anthropic_error_type(int status) {
+    return status == 401 ? "authentication_error"
+         : status == 403 ? "permission_error"
+         : status == 404 ? "not_found_error"
+         : status == 413 ? "request_too_large"
+         : status == 429 ? "rate_limit_error"
+         : status >= 500 ? "api_error"
+                         : "invalid_request_error";
+}
+
+/* A refusal the transport or the router writes itself. `type` is OpenAI's; on an Anthropic path
+ * the status picks Anthropic's instead. Hand-rolled, not nlohmann: this error path must work even
+ * if the JSON layer failed. The message can quote a request's decoded path, so bytes that are not
+ * UTF-8 become U+FFFD; a JSON body must be UTF-8 for a client to parse it. */
+static std::string error_body(const std::string& path, int status, const char* type,
+                              const std::string& msg) {
     std::string esc;
-    for (char c : msg) {
+    for (char c : utf8_sanitize(msg)) {
         if (c == '"' || c == '\\') { esc.push_back('\\'); esc.push_back(c); }
         else if (c == '\n') esc += "\\n";
         else if ((unsigned char)c < 0x20) esc += "?";
         else esc.push_back(c);
     }
+    if (anthropic_path(path))
+        return std::string("{\"type\":\"error\",\"error\":{\"type\":\"") +
+               anthropic_error_type(status) + "\",\"message\":\"" + esc + "\"}}";
     return std::string("{\"error\":{\"message\":\"") + esc + "\",\"type\":\"" + type +
            "\",\"param\":null,\"code\":null}}";
 }
 
-HttpResponse Router::dispatch(HttpRequest req) const {
-    auto segs = split_path(req.path);
-    bool path_matched = false;
-
+const Router::Route* Router::match(const std::string& method, const std::vector& segs,
+                                   std::map* caps,
+                                   bool* path_matched) const {
+    *path_matched = false;
     for (const auto& r : routes_) {
-        if (r.segs.size() != segs.size()) continue;
-        std::map caps;
+        const bool rest = !r.segs.empty() && r.segs.back()[0] == '*';
+        if (rest ? segs.size() < r.segs.size() : segs.size() != r.segs.size()) continue;
+        const size_t fixed = rest ? r.segs.size() - 1 : r.segs.size();
+        std::map c;
         bool ok = true;
-        for (size_t i = 0; i < segs.size(); ++i) {
-            if (!r.segs[i].empty() && r.segs[i][0] == ':') caps[r.segs[i].substr(1)] = segs[i];
+        for (size_t i = 0; i < fixed; ++i) {
+            if (!r.segs[i].empty() && r.segs[i][0] == ':') c[r.segs[i].substr(1)] = segs[i];
             else if (r.segs[i] != segs[i]) { ok = false; break; }
         }
         if (!ok) continue;
-        path_matched = true;
-        if (r.method != req.method) continue;
+        if (rest) {
+            std::string& v = c[r.segs.back().substr(1)];
+            for (size_t i = fixed; i < segs.size(); ++i) v += (i > fixed ? "/" : "") + segs[i];
+        }
+        *path_matched = true;
+        if (r.method != method) continue;
+        if (caps) *caps = std::move(c);
+        return &r;
+    }
+    return nullptr;
+}
 
+bool Router::allows(const std::string& method, const std::string& path) const {
+    bool path_matched = false;
+    return match(method, split_path(path), nullptr, &path_matched) != nullptr;
+}
+
+HttpResponse Router::dispatch(HttpRequest req) const {
+    bool path_matched = false;
+    std::map caps;
+    if (const Route* r = match(req.method, split_path(req.path), &caps, &path_matched)) {
         req.params.insert(caps.begin(), caps.end());
-        return r.h(req);
+        return r->h(req);
     }
 
     if (path_matched)
         return HttpResponse::json_body(
-            405, error_body("invalid_request_error",
+            405, error_body(req.path, 405, "invalid_request_error",
                             req.method + " is not allowed on " + req.path));
     return HttpResponse::json_body(
-        404, error_body("not_found_error", "no route for " + req.method + " " + req.path));
+        404, error_body(req.path, 404, "not_found_error",
+                        "no route for " + req.method + " " + req.path));
 }
 
 HttpResponse Router::call(const std::string& method, const std::string& path,
@@ -201,18 +262,16 @@ HttpResponse Router::call(const std::string& method, const std::string& path,
 
 /* ------------------------------------------------------------------ the worker pool */
 
-/* A WORKER FOR EVERY CONNECTION, UP TO A BOUND, STARTED THE MOMENT THE CONNECTION HAS NONE.
+/* A worker for every connection, up to a bound, started as soon as a connection has none.
  *
- * httplib's own ThreadPool starts an extra worker only when it counts no idle one, and a worker
- * counts as idle from the moment it is woken until it has taken its job. Two connections arriving
- * inside that window leave the second queued with no worker started for it -- and a generation
- * holds its worker for minutes, so that connection waits for the next one to arrive or for a
- * generation to end. This pool compares the queue with the number of workers free to take from
+ * httplib's ThreadPool counts a worker as idle from its wake-up until it takes its job, so two
+ * connections arriving in that window leave the second queued with no new worker, possibly for
+ * minutes behind a generation. This pool compares the queue with the workers free to take from
  * it, so a connection waits only once the pool is at its bound.
  *
- * `keep` workers stay up; the rest exit after kIdleExit with nothing to do. Past `most` workers,
- * `queued` connections may wait (0: any number) and further ones are refused, which httplib
- * answers by closing the socket. */
+ * `keep` workers stay up; the rest exit after kIdleExit idle. Past `most` workers, `queued`
+ * connections may wait (0: any number) and further ones are refused, which httplib answers by
+ * closing the socket. */
 class ConnectionPool final : public httplib::TaskQueue {
 public:
     ConnectionPool(size_t keep, size_t most, size_t queued)
@@ -236,8 +295,8 @@ public:
         return true;
     }
 
-    /* Runs what is queued, then joins every worker. Idempotent: httplib calls it and then
-     * destroys the pool, which calls it again. */
+    /* Runs what is queued, then joins every worker. Idempotent: httplib calls it, then the
+     * destructor calls it again. */
     void shutdown() override {
         std::list live;
         {
@@ -254,7 +313,7 @@ public:
 private:
     static constexpr std::chrono::seconds kIdleExit{5};
 
-    /* With m_ held. False when the system will not give us a thread; the job then waits. */
+    /* With m_ held. False when no thread can be created; the job then waits. */
     bool start() {
         reap();
         try {
@@ -267,8 +326,8 @@ private:
         return true;
     }
 
-    /* With m_ held: join the workers that exited idle. They left m_ before exiting, so this
-     * waits only for their last instructions. */
+    /* With m_ held: join the workers that exited idle. They released m_ before exiting, so the
+     * join is short. */
     void reap() {
         for (auto& t : finished_) t.join();
         finished_.clear();
@@ -325,25 +384,95 @@ HttpTransport::~HttpTransport() { stop(); }
 
 void HttpTransport::stop() { if (impl_) impl_->svr.stop(); }
 
-/* Not before the accept loop is running: until then httplib's stop() has nothing to stop and
- * does nothing, so a caller that took the port as "up" and then stopped would wait forever. */
+/* 0 until the accept loop runs: before that httplib's stop() is a no-op, and a caller that
+ * stopped a server it believed up would wait forever. */
 int HttpTransport::port() const {
     return impl_ && impl_->svr.is_running() ? impl_->port.load() : 0;
 }
 
+/* Compares a credential with the key in time independent of where they differ, so a client
+ * cannot find the key a byte at a time by timing refusals. The length is not secret. */
+static bool same_secret(const std::string& got, const std::string& key) {
+    if (got.size() != key.size()) return false;
+    unsigned char d = 0;
+    for (size_t i = 0; i < key.size(); ++i) d |= (unsigned char)(got[i] ^ key[i]);
+    return d == 0;
+}
+
 static void apply(const HttpResponse& r, httplib::Response& res) {
     res.status = r.status;
     for (auto& h : r.headers) res.set_header(h.first, h.second);
 }
 
+/* httplib's WebSocket as a WsConn. Sending from another thread is httplib's own practice -- its
+ * writes are under a mutex and its heartbeat pings from a thread of its own -- and so is closing
+ * from one: its heartbeat closes on a pong timeout while the route's thread is reading. */
+class HttplibConn final : public WsConn {
+public:
+    explicit HttplibConn(httplib::ws::WebSocket& ws) : ws_(ws) {}
+    bool read(std::string* msg, bool* binary) override {
+        const httplib::ws::ReadResult r = ws_.read(*msg);
+        if (r == httplib::ws::Fail) return false;
+        *binary = r == httplib::ws::Binary;
+        return true;
+    }
+    bool send(const std::string& text) override { return ws_.send(text); }
+    void close(int code, const std::string& reason) override {
+        ws_.close((httplib::ws::CloseStatus)code, reason);
+    }
+
+private:
+    httplib::ws::WebSocket& ws_;
+};
+
+static std::string lower_ascii(std::string s) {
+    for (char& c : s) c = (char)std::tolower((unsigned char)c);
+    return s;
+}
+
+/* The API key a browser's socket carries. A browser cannot set a header on a WebSocket, so
+ * OpenAI's browser clients offer it as a subprotocol, `openai-insecure-api-key.`, beside
+ * `realtime`; the subprotocol chosen is never that one. Compared in constant time, as the header
+ * key is. */
+static bool offers_key(const std::string& protocols, const std::string& key) {
+    static const std::string kPrefix = "openai-insecure-api-key.";
+    size_t i = 0;
+    while (i <= protocols.size()) {
+        size_t j = protocols.find(',', i);
+        if (j == std::string::npos) j = protocols.size();
+        size_t a = i, b = j;
+        while (a < b && protocols[a] == ' ') ++a;
+        while (b > a && protocols[b - 1] == ' ') --b;
+        if (b - a >= kPrefix.size() && protocols.compare(a, kPrefix.size(), kPrefix) == 0 &&
+            same_secret(protocols.substr(a + kPrefix.size(), b - a - kPrefix.size()), key))
+            return true;
+        i = j + 1;
+    }
+    return false;
+}
+
+/* httplib's own test for a WebSocket upgrade (RFC 6455 §4.2.1), which it applies before the
+ * pre-routing handler and does not export. A request it rejects is routed as a plain GET, so the
+ * pre-routing handler must not leave such a request to httplib either. */
+static bool is_socket_upgrade(const httplib::Request& q) {
+    if (q.method != "GET" || lower_ascii(q.get_header_value("Upgrade")) != "websocket") return false;
+    if (lower_ascii(q.get_header_value("Connection")).find("upgrade") == std::string::npos)
+        return false;
+    const std::string key = q.get_header_value("Sec-WebSocket-Key");
+    if (key.size() != 24 || key[22] != '=' || key[23] != '=') return false;
+    static const std::string b64 =
+        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+    for (size_t i = 0; i < 22; ++i)
+        if (b64.find(key[i]) == std::string::npos) return false;
+    return q.get_header_value("Sec-WebSocket-Version") == "13";
+}
+
 int HttpTransport::serve(const Router& router, const TransportOptions& o) {
     auto& svr = impl_->svr;
 
-    /* A REQUEST LINE LONGER THAN httplib's LINE LIMIT (CPPHTTPLIB_MAX_LINE_LENGTH) GETS NO STATUS.
-     * Its line reader gives up before the request exists, and no handler, error handler or logger
-     * runs, so there is nothing here that could answer 414: the connection is closed unanswered.
-     * With the build's CPPHTTPLIB_REQUEST_URI_MAX_LENGTH equal to that limit, httplib's own 414
-     * cannot fire either, because a target that long never fits in a line that is read. */
+    /* A request line longer than CPPHTTPLIB_MAX_LINE_LENGTH is closed with no status: httplib's
+     * line reader gives up before any handler, error handler or logger runs. The build sets
+     * CPPHTTPLIB_REQUEST_URI_MAX_LENGTH to the same limit, so httplib's own 414 never fires. */
     svr.set_read_timeout(o.read_timeout_s, 0);
     svr.set_write_timeout(o.write_timeout_s, 0);
     svr.set_keep_alive_timeout(o.keep_alive_timeout_s);
@@ -354,9 +483,9 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
     const size_t queued = (size_t)std::max(o.max_queued, 0);
     svr.new_task_queue = [nt, most, queued] { return new ConnectionPool((size_t)nt, most, queued); };
 
-    /* A handler must never throw across the transport: an exception here closes the connection
-     * with no body at all, which is the least diagnosable failure a client can get. */
-    svr.set_exception_handler([](const httplib::Request&, httplib::Response& res,
+    /* An exception escaping a handler would close the connection with no body; answer 500 with
+     * an error object instead. */
+    svr.set_exception_handler([](const httplib::Request& req, httplib::Response& res,
                                  std::exception_ptr ep) {
         std::string what = "unhandled exception in handler";
         try { std::rethrow_exception(ep); }
@@ -364,40 +493,54 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
         catch (...) {}
         RAD_ERR("server: %s", what.c_str());
         res.status = 500;
-        res.set_content(error_body("internal_server_error", what), "application/json");
+        res.set_content(error_body(req.path, 500, "internal_server_error", what),
+                        "application/json");
     });
 
     const std::string api_key = o.api_key;
     const bool cors = o.cors;
+    /* The headers a cross-origin client sends: the body type, either form of the API key, and the
+     * anthropic-version and anthropic-beta headers of Anthropic's clients, which nothing reads. */
+    static const char* const kCorsHeaders =
+        "Content-Type, Authorization, X-Api-Key, anthropic-version, anthropic-beta";
+    static const char* const kCorsMethods = "GET, POST, OPTIONS";
+
+    /* Whether a request carries the API key: `Authorization: Bearer` (OpenAI; the scheme is
+     * case-insensitive, RFC 9110) or `X-Api-Key` (Anthropic, also accepted by llama-server). */
+    auto key_ok = [api_key](const httplib::Request& hreq) -> bool {
+        const std::string auth = hreq.get_header_value("Authorization");
+        const size_t sp = auth.find(' ');
+        const size_t cred = sp == std::string::npos ? sp : auth.find_first_not_of(' ', sp);
+        const bool bearer = cred != std::string::npos && sp == 6 &&
+                            std::equal(auth.begin(), auth.begin() + 6, "bearer",
+                                       [](char a, char b) {
+                                           return std::tolower((unsigned char)a) == b;
+                                       });
+        return (bearer && same_secret(auth.substr(cred), api_key)) ||
+               same_secret(hreq.get_header_value("X-Api-Key"), api_key);
+    };
 
     /* What a request must pass before its body is read, so a refused one never has it buffered. */
-    auto gate = [api_key, cors](const httplib::Request& hreq, httplib::Response& hres) -> bool {
+    auto gate = [api_key, cors, key_ok](const httplib::Request& hreq,
+                                        httplib::Response& hres) -> bool {
         if (cors) {
             hres.set_header("Access-Control-Allow-Origin", "*");
-            hres.set_header("Access-Control-Allow-Headers", "Content-Type, Authorization");
-            hres.set_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
+            hres.set_header("Access-Control-Allow-Headers", kCorsHeaders);
+            hres.set_header("Access-Control-Allow-Methods", kCorsMethods);
         }
-        /* THE PROBE PATHS ARE EXEMPT, AND THE DASHBOARD PAGE. A load balancer cannot carry a
-         * bearer token, so an authenticated /health is a server that reports itself down. The
-         * page is the one static document the server has: it holds no data, and a browser opening
-         * it cannot send a header, so it loads and then sends the key on every fetch of data it
-         * makes. Everything else is guarded. vLLM's middleware guards only paths under /v1,
-         * leaving /tokenize open, which hands an unauthenticated caller the vocabulary and the
-         * chat template. This does not. */
+        /* The probe paths and the dashboard page are exempt. A load balancer cannot send a
+         * bearer token, and a browser opening the page cannot send a header; the page holds no
+         * data and sends the key on every data fetch. Everything else is guarded, including
+         * /tokenize, which vLLM leaves open (it only guards /v1). */
         const std::string& p = hreq.path;
         if (!api_key.empty() && p != "/health" && p != "/v1/health" && p != "/ping" && p != "/" &&
             p != "/dashboard") {
-            /* `Authorization: Bearer` is OpenAI's spelling and `X-Api-Key` Anthropic's, which
-             * llama-server takes as well; either one carrying the key is enough. */
-            const bool ok = hreq.get_header_value("Authorization") == "Bearer " + api_key ||
-                            hreq.get_header_value("X-Api-Key") == api_key;
-            if (!ok) {
-                /* Said like every other refusal (Server::error_response), which this one never
-                 * reaches: the gate answers before the router does. */
+            if (!key_ok(hreq)) {
+                /* Logged in Server::error_response's format; the gate answers before the router. */
                 RAD_INFO("req refused from %s:%d -> 401 authentication_error: invalid api key",
                          hreq.remote_addr.c_str(), hreq.remote_port);
                 hres.status = 401;
-                hres.set_content(error_body("authentication_error", "invalid api key"),
+                hres.set_content(error_body(p, 401, "authentication_error", "invalid api key"),
                                  "application/json");
                 return false;
             }
@@ -408,7 +551,8 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
     auto bridge = [&router](const httplib::Request& hreq, std::string body,
                             httplib::Response& hres, std::vector form = {}) {
         HttpRequest req;
-        req.method = hreq.method;
+        /* HEAD is GET without the body, which httplib leaves off the wire. */
+        req.method = hreq.method == "HEAD" ? "GET" : hreq.method;
         req.path = hreq.path;
         req.body = std::move(body);
         req.form = std::move(form);
@@ -428,9 +572,9 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
             return;
         }
 
-        /* Streaming. The provider owns the handler's state via the shared_ptr, because httplib
-         * keeps it alive past this function; `releaser` is what tells us whether the peer went
-         * away, and it is the hook cancellation hangs off. */
+        /* Streaming. The shared_ptr keeps the handler's state alive, because httplib calls the
+         * provider after this function returns. The releaser reports whether the peer went away
+         * and is where cancellation hooks in. */
         auto st = std::make_shared(std::move(res));
         hres.set_chunked_content_provider(
             st->content_type,
@@ -440,77 +584,148 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
                 if (!chunk.empty()) {
                     if (!sink.write(chunk.data(), chunk.size())) return false;  /* peer gone */
                 }
+                /* The end is done() and true: false cancels the response, and httplib closes a
+                 * connection the client would reuse for its next request. */
                 if (!more) sink.done();
-                return more;
+                return true;
             },
             [st](bool ok) { if (st->on_close) st->on_close(ok); });
     };
 
-    for (const auto& sig : router.routes()) {
-        size_t sp = sig.find(' ');
-        std::string method = sig.substr(0, sp);
-        std::string path = sig.substr(sp + 1);
-        /* ":name" is httplib's own wildcard spelling too, so the pattern carries across. */
-        if (method == "GET") {
-            svr.Get(path, [gate, bridge](const httplib::Request& q, httplib::Response& s) {
-                if (gate(q, s)) bridge(q, q.body, s);
-            });
-            continue;
-        }
-        /* A POST BODY IS READ STRAIGHT INTO THE STRING THE HANDLER PARSES. Left to httplib it
-         * lands in its own Request first, which only hands it out const, so it would be copied
-         * into ours: a body at the size limit held twice before a byte of it is looked at. A
-         * multipart body (an image upload) is read as its parts, each straight into its own
-         * string, under the same size limit. */
-        svr.Post(path, [gate, bridge](const httplib::Request& q, httplib::Response& s,
-                                      const httplib::ContentReader& read) {
-            if (!gate(q, s)) return;
-            std::string body;
-            std::vector form;
-            const bool ok = q.is_multipart_form_data()
-                ? read([&form](const httplib::FormData& f) {
-                           form.push_back(FormPart{ f.name, f.filename, f.content_type, {} });
-                           return true;
-                       },
-                       [&form](const char* p, size_t n) {
-                           if (!form.empty()) form.back().data.append(p, n);
-                           return true;
-                       })
-                : read([&body](const char* p, size_t n) { body.append(p, n); return true; });
-            if (!ok) {
-                /* httplib has already set 413 for a body over the limit; anything else is a peer
-                 * that stopped sending partway, which has to be answered as something. */
-                if (s.status < 0) {
-                    s.status = 400;
-                    s.set_content(error_body("invalid_request_error",
-                                             "the request body could not be read"),
-                                  "application/json");
-                }
-                return;
+    /* A body is read straight into the string the handler parses. httplib's own Request hands
+     * it out only const, so it would be copied and held twice. A multipart body (an image
+     * upload) is read part by part, each into its own string, under the same limit. */
+    auto read_and_bridge = [bridge](const httplib::Request& q, httplib::Response& s,
+                                    const httplib::ContentReader& read) {
+        std::string body;
+        std::vector form;
+        const bool ok = q.is_multipart_form_data()
+            ? read([&form](const httplib::FormData& f) {
+                       form.push_back(FormPart{ f.name, f.filename, f.content_type, {} });
+                       return true;
+                   },
+                   [&form](const char* p, size_t n) {
+                       if (!form.empty()) form.back().data.append(p, n);
+                       return true;
+                   })
+            : read([&body](const char* p, size_t n) { body.append(p, n); return true; });
+        if (!ok) {
+            /* httplib has already set 413 for a body over the limit; anything else is a peer
+             * that stopped sending partway. */
+            if (s.status < 0) {
+                s.status = 400;
+                s.set_content(error_body(q.path, 400, "invalid_request_error",
+                                         "the request body could not be read"),
+                              "application/json");
             }
-            bridge(q, std::move(body), s, std::move(form));
-        });
-    }
-    /* THE PREFLIGHT ALLOWS WHATEVER HEADERS IT IS ASKED ABOUT. A browser client sends more than
-     * the two this server reads -- the OpenAI SDK adds its x-stainless-* set -- and a preflight
-     * that does not list one fails the request before it is sent. A wildcard would not do: CORS
-     * never lets `*` stand for Authorization, so the requested list is echoed back. */
-    svr.Options(".*", [cors](const httplib::Request& req, httplib::Response& res) {
+            return;
+        }
+        bridge(q, std::move(body), s, std::move(form));
+    };
+
+    /* The preflight allows whatever headers it is asked about. Browser clients send more than
+     * the two this server reads (the OpenAI SDK adds x-stainless-*), and an unlisted one fails
+     * the request. `*` cannot stand for Authorization in CORS, so the requested list is echoed. */
+    auto preflight = [cors](const httplib::Request& req, httplib::Response& res) {
         if (cors) {
             const std::string asked = req.get_header_value("Access-Control-Request-Headers");
             res.set_header("Access-Control-Allow-Origin", "*");
-            res.set_header("Access-Control-Allow-Headers",
-                           asked.empty() ? "Content-Type, Authorization, X-Api-Key" : asked);
-            res.set_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
+            res.set_header("Access-Control-Allow-Headers", asked.empty() ? kCorsHeaders : asked);
+            res.set_header("Access-Control-Allow-Methods", kCorsMethods);
             res.set_header("Access-Control-Max-Age", "86400");
         }
         res.status = 204;
-    });
+    };
 
-    /* A PATH NO ROUTE NAMES is answered by httplib before the router sees it, with no body. Every
-     * other refusal this server makes is an error object, and a client reading one finds an
-     * empty 404 unparseable; so an error with no body gets one here. A response that already
-     * carries a body -- the router's own 404 and 405, the gate's 401 -- is left as it is. */
+    /* Socket routes. An upgrade is gated before httplib answers 101 by the same key, carried the
+     * ways a socket client can carry it, and, with CORS off, by its Origin: a browser lets any
+     * page open a socket to any host, and CORS is what would otherwise keep another site's page
+     * out. True when the upgrade may proceed; false with the refusal in `s`. */
+    auto socket_gate = [api_key, cors, key_ok](const httplib::Request& q,
+                                               httplib::Response& s) -> bool {
+        auto refuse = [&](int status, const char* type, const std::string& why) {
+            RAD_INFO("req refused from %s:%d -> %d %s: %s", q.remote_addr.c_str(), q.remote_port,
+                     status, type, why.c_str());
+            s.status = status;
+            s.set_content(error_body(q.path, status, type, why), "application/json");
+            return false;
+        };
+        if (!cors && q.has_header("Origin")) {
+            std::string origin = q.get_header_value("Origin");
+            const size_t at = origin.find("://");
+            if (at != std::string::npos) origin = origin.substr(at + 3);
+            if (lower_ascii(origin) != lower_ascii(q.get_header_value("Host")))
+                return refuse(403, "permission_error",
+                              "a page on another origin may not open this socket (--no-cors)");
+        }
+        if (!api_key.empty() && !key_ok(q) &&
+            !offers_key(q.get_header_value("Sec-WebSocket-Protocol"), api_key))
+            return refuse(401, "authentication_error", "invalid api key");
+        return true;
+    };
+    for (const std::string& path : router.socket_routes()) {
+        const SocketHandler h = *router.socket_for(path);
+        svr.WebSocket(
+            path,
+            [h](const httplib::Request& hreq, httplib::ws::WebSocket& ws) {
+                HttpRequest req;
+                req.method = hreq.method;
+                req.path = hreq.path;
+                req.peer = hreq.remote_addr + ":" + std::to_string(hreq.remote_port);
+                for (auto& hd : hreq.headers) req.headers[hd.first] = hd.second;
+                for (auto& p : hreq.params) req.query[p.first] = p.second;
+                HttplibConn conn(ws);
+                try {
+                    h(req, conn);
+                } catch (const std::exception& e) {
+                    RAD_ERR("server: %s on %s", e.what(), req.path.c_str());
+                    conn.close(1011, "internal error");
+                }
+            },
+            /* `realtime` when it is offered, as OpenAI's server answers; otherwise none. */
+            [](const std::vector& offered) -> std::string {
+                for (const auto& p : offered)
+                    if (p == "realtime") return p;
+                return std::string();
+            });
+    }
+
+    /* The router routes every request, not httplib: registered under its own method, a route
+     * would make httplib answer the same path under another method 404, where the router answers
+     * 405 (http.h). So a request is answered here, before httplib routes it, unless a route takes
+     * it with a body to read: httplib hands its body reader only to a route's handler, so those
+     * routes are registered below and left to it. A request no route takes is answered without
+     * its body being read. */
+    svr.set_pre_routing_handler([&router, gate, socket_gate, bridge,
+                                 preflight](const httplib::Request& q, httplib::Response& s) {
+        /* A WebSocket upgrade to a socket route is left to httplib, which then answers 101 and
+         * runs the route's socket handler. */
+        if (is_socket_upgrade(q) && router.socket_for(q.path))
+            return socket_gate(q, s) ? httplib::Server::HandlerResponse::Unhandled
+                                     : httplib::Server::HandlerResponse::Handled;
+        if (q.method == "OPTIONS") {
+            preflight(q, s);
+            return httplib::Server::HandlerResponse::Handled;
+        }
+        if (!gate(q, s)) return httplib::Server::HandlerResponse::Handled;
+        if (q.method != "GET" && q.method != "HEAD" && router.allows(q.method, q.path))
+            return httplib::Server::HandlerResponse::Unhandled;
+        bridge(q, std::string(), s);
+        return httplib::Server::HandlerResponse::Handled;
+    });
+    for (const auto& sig : router.routes()) {
+        const size_t sp = sig.find(' ');
+        const std::string method = sig.substr(0, sp), path = sig.substr(sp + 1);
+        if (method == "POST") svr.Post(path, read_and_bridge);
+        else if (method == "PUT") svr.Put(path, read_and_bridge);
+        else if (method == "PATCH") svr.Patch(path, read_and_bridge);
+        else if (method == "DELETE") svr.Delete(path, read_and_bridge);
+    }
+
+    /* What httplib answers itself (a malformed request, a body over the limit, a body sent to a
+     * path its route pattern does not spell) has no body. Give such errors an OpenAI error object
+     * like every other refusal; a response that already has a body (the router's 404 and 405,
+     * the gate's 401) is left as it is. */
     svr.set_error_handler([cors](const httplib::Request& req, httplib::Response& res) {
         if (!res.body.empty()) return httplib::Server::HandlerResponse::Unhandled;
         if (cors) res.set_header("Access-Control-Allow-Origin", "*");
@@ -519,12 +734,13 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
                                                    : "invalid_request_error";
         const std::string what = res.status == 404 ? "no route for " + req.method + " " + req.path
                                                    : httplib::status_message(res.status);
-        res.set_content(error_body(type.c_str(), what), "application/json");
+        res.set_content(error_body(req.path, res.status, type.c_str(), what),
+                        "application/json");
         return httplib::Server::HandlerResponse::Handled;
     });
 
-    /* Bound once: asking for a named port and then for any port would leave the first socket
-     * bound and unused. */
+    /* Bind once: binding a named port and then any port would leave the first socket bound and
+     * unused. */
     const int port = o.port == 0 ? svr.bind_to_any_port(o.host.c_str())
                      : svr.bind_to_port(o.host.c_str(), o.port) ? o.port : -1;
     if (port <= 0) {
diff --git a/core/server/http.h b/core/server/http.h
index c6f11ff1..a3f06829 100644
--- a/core/server/http.h
+++ b/core/server/http.h
@@ -1,10 +1,8 @@
 /* core/server/http.h -- the transport seam.
  *
- * Everything above this line (routing, OpenAI translation, metrics) is written against these
- * plain structs and never sees a socket. That is what lets tests/server_test.cpp drive the real
- * handlers in-process: `Router::dispatch` is the same call the transport makes, minus the port.
- * The alternative -- testing by binding a loopback socket -- tests cpp-httplib, which is already
- * tested, and makes the suite depend on a free port.
+ * Routing, OpenAI translation and metrics are written against these plain structs and never see
+ * a socket, so tests/server_test.cpp drives the real handlers in-process: `Router::dispatch` is
+ * the same call the transport makes. Tests need no free port and do not re-test cpp-httplib.
  */
 #pragma once
 
@@ -39,21 +37,20 @@ struct HttpRequest {
     std::map query;
     std::map params;           /* from a ":name" route segment */
     std::string peer;                                    /* "addr:port"; empty in-process */
-    /* WHEN THE WHOLE BODY HAD ARRIVED, in steady-clock nanoseconds: where the server's own time
-     * for the request starts, before it is parsed, rendered or tokenised, so the time the body
-     * spent on the network is not in it. -1 for a request made in-process. */
+    /* Steady-clock nanoseconds at which the whole body had arrived. The server's own time for
+     * the request starts here, before parsing, so network time is excluded. -1 in-process. */
     int64_t     t_received_ns = -1;
 
-    /* True once the peer is gone. The transport supplies it; in-process it is absent and the
-     * waiting paths simply never see a drop. A dropped connection is a cancellation (spec §14),
-     * so every path that waits polls this. */
+    /* True once the peer is gone; absent in-process. A dropped connection is a cancellation
+     * (spec §14), so every path that waits polls this. */
     std::function closed;
 
     std::string header(const std::string& k, const std::string& def = "") const;
     std::string param(const std::string& k, const std::string& def = "") const;
+    /* The first form part named `k` (a field or a file), or null. */
+    const FormPart* part(const std::string& k) const;
     bool        peer_gone() const { return closed && closed(); }
-    /* True when the peer is this machine: 127.0.0.0/8, ::1, or either written as an IPv4-mapped
-     * IPv6 address -- and for a request made in-process, which has no peer. */
+    /* True for 127.0.0.0/8, ::1, an IPv4-mapped 127.x address, and an in-process request. */
     bool        peer_is_loopback() const;
 };
 
@@ -64,12 +61,11 @@ struct HttpResponse {
     std::vector> headers;
 
     /* Streaming. When `next` is set, `body` is ignored and the transport pulls chunks until next()
-     * returns false. A chunk may legitimately be empty (nothing produced this poll), in which case
-     * nothing is written but the connection is checked. */
+     * returns false. An empty chunk writes nothing but still checks the connection. */
     std::function next;
 
-    /* Runs exactly once when the connection ends, with `ok` false if the peer went away before the
-     * stream finished. This is where a dropped stream becomes a scheduler cancellation. */
+    /* Runs exactly once when the connection ends; `ok` is false if the peer left before the
+     * stream finished. A dropped stream becomes a scheduler cancellation here. */
     std::function on_close;
 
     bool streaming() const { return next != nullptr; }
@@ -82,47 +78,88 @@ struct HttpResponse {
 
 using Handler = std::function;
 
-/* Exact-match routing plus a single ":name" wildcard segment, which is all the OpenAI surface
- * needs (/v1/models/:id). No regex, no priority rules, nothing to reason about. */
+/* One WebSocket connection, as a socket route sees it: messages in, messages out, and a close.
+ * The route runs for the connection's whole life on the transport's thread for it. It reads on
+ * that thread and may send and close from another, so it can answer while it listens. A test
+ * hands the route a connection of its own. */
+class WsConn {
+public:
+    virtual ~WsConn() = default;
+    /* Blocks for the next message: true with it in `*msg` and `*binary` saying which frame it came
+     * in, false once the connection is gone. */
+    virtual bool read(std::string* msg, bool* binary) = 0;
+    /* A text message. Safe from any thread; false once the connection is gone. */
+    virtual bool send(const std::string& text) = 0;
+    /* Ends the connection with a close code and reason (RFC 6455 §7.4); a read() blocked on it
+     * returns false once the peer has answered or gone. Safe from any thread. */
+    virtual void close(int code, const std::string& reason) = 0;
+};
+
+/* A socket route: the upgrade request, and the connection it became. */
+using SocketHandler = std::function;
+
+/* Exact-match routing plus ":name" wildcard segments and a final "*name" that takes the rest of
+ * the path, which is all the OpenAI surface needs (a model id may hold a slash, so the model
+ * entry's route ends in "*id"). No regex and no priority rules. */
 class Router {
 public:
     void add(std::string method, std::string path, Handler h);
     void get(std::string path, Handler h)  { add("GET",  std::move(path), std::move(h)); }
     void post(std::string path, Handler h) { add("POST", std::move(path), std::move(h)); }
+    /* A WebSocket route, exact path. An upgrade request to it becomes a connection the handler
+     * is given; a plain GET to the same path is whatever add() registered there, if anything. */
+    void socket(std::string path, SocketHandler h);
+    /* The handler for an upgrade to `path`, or null. */
+    const SocketHandler* socket_for(const std::string& path) const;
+    std::vector socket_routes() const;
 
-    /* 404 with a body naming the path, 405 when the path exists under another method. By value,
-     * so the transport can move a request -- body included -- into the handler rather than copy
-     * a body that may be hundreds of megabytes. */
+    /* 404 with a body naming the path, 405 when the path exists under another method. Takes the
+     * request by value so the transport can move a body of up to hundreds of MB into the handler. */
     HttpResponse dispatch(HttpRequest req) const;
 
-    /* Convenience for tests and for anything that speaks in whole request lines. */
+    /* Convenience for tests. */
     HttpResponse call(const std::string& method, const std::string& path,
                       const std::string& body = "") const;
 
+    /* Whether a route takes `method` on `path`, as dispatch would match it. */
+    bool allows(const std::string& method, const std::string& path) const;
+
     std::vector routes() const;
 
 private:
     struct Route {
         std::string method;
-        std::vector segs;   /* ":name" segments are wildcards */
+        std::vector segs;   /* ":name" is any one segment, a final "*name" the rest */
         Handler h;
     };
+    /* The route taking `method` on the path `segs`, with its captures; null when none.
+     * `*path_matched` says whether a route takes the path under any method. */
+    const Route* match(const std::string& method, const std::vector& segs,
+                       std::map* caps, bool* path_matched) const;
     std::vector routes_;
+    std::vector> sockets_;
 };
 
+/* Anthropic's clients read Anthropic's error envelope, `{"type":"error","error":{"type",
+ * "message"}}`, so every refusal on one of its paths (/v1/messages and below) is written in it,
+ * the transport's own included; every other path gets OpenAI's. */
+bool        anthropic_path(const std::string& path);
+/* Anthropic's error `type` for an HTTP status. */
+const char* anthropic_error_type(int status);
+
 /* Split "/v1/models/foo?x=1" into path and decoded query parameters. */
 void parse_target(const std::string& target, std::string* path,
                   std::map* query);
-/* Percent-decode. `plus_is_space` is the form encoding, which applies to a query string and
- * not to a path -- see the definition. */
+/* Percent-decode. `plus_is_space` is the form encoding: true for a query string, false for a
+ * path. */
 std::string url_decode(const std::string& s, bool plus_is_space = true);
 
 /* ================================================================== the cpp-httplib binding */
 
-/* ONE WORKER PER CONNECTION, for the connection's whole life: httplib reads a request, runs the
- * handler and writes the response on the same thread, and a generation's handler runs until the
- * generation ends. So the pool bounds are connection counts, and Server::run derives them from
- * the admission ceiling rather than from the core count. */
+/* One worker per connection for the connection's whole life: httplib reads, handles and writes
+ * on one thread, and a generation's handler runs until the generation ends. The pool bounds are
+ * therefore connection counts, which Server::run derives from the admission ceiling, not the
+ * core count. */
 struct TransportOptions {
     std::string host = "0.0.0.0";
     int         port = 8000;              /* 0 -> any free port; see HttpTransport::port */
@@ -132,9 +169,8 @@ struct TransportOptions {
     int64_t     max_queued = 0;           /* accepted connections that may wait for a worker once
                                            * it has grown to max_threads; past that they are
                                            * closed. 0 -> unbounded */
-    /* The longest the peer may go silent while its REQUEST is being read. It bounds nothing about
-     * generation, which is written, not read. A connection that sends part of a request and then
-     * goes quiet holds a worker until this runs out, so it is short. */
+    /* Longest silence allowed while the request is being read; generation is not bounded by it.
+     * A peer that stalls mid-request holds a worker until this expires, so it is short. */
     int         read_timeout_s = 30;
     int         write_timeout_s = 600;
     int         keep_alive_timeout_s = 5; /* an idle connection's hold on a worker between requests */
@@ -143,9 +179,8 @@ struct TransportOptions {
     bool        cors = true;
 };
 
-/* The workers the pool keeps while idle for TransportOptions::n_threads: that many, one a
- * hardware thread for 0, and never fewer than 4. One definition, so the number the startup
- * report states is the number the transport runs. */
+/* Idle workers kept for TransportOptions::n_threads: that many, one per hardware thread for 0,
+ * never fewer than 4. Shared so the startup report states what the transport runs. */
 int idle_workers(int n_threads);
 
 class HttpTransport {
@@ -159,9 +194,8 @@ public:
     int  serve(const Router& r, const TransportOptions& o);
     void stop();
 
-    /* The port serve() bound, which is the only way to learn it when it was asked for port 0.
-     * 0 until the server is accepting connections, so a non-zero answer also means stop() will
-     * take effect. */
+    /* The port serve() bound (the only way to learn it for port 0). 0 until the server accepts
+     * connections, so a non-zero answer also means stop() will take effect. */
     int  port() const;
 
 private:
diff --git a/core/server/iface.h b/core/server/iface.h
index 6f952663..6566ed41 100644
--- a/core/server/iface.h
+++ b/core/server/iface.h
@@ -1,15 +1,12 @@
 /* core/server/iface.h -- everything the server needs from components it does not own.
  *
- * The server is written against pure-virtual interfaces rather than against core/sched and
- * core/text directly, for two reasons worth stating. The first is that the HTTP layer then carries
- * no header dependency on those components and can be compiled without them. The second is that a
- * test can drive every endpoint against a fake scheduler in-process, which is the only way to
- * check cancellation and the streaming wire format without binding a port and loading a model.
+ * The server is written against pure-virtual interfaces rather than core/sched and core/text, so
+ * the HTTP layer has no header dependency on them, and tests can drive every endpoint against a
+ * fake scheduler in-process (cancellation and the streaming wire format, with no port or model).
  *
- * The cost is one virtual call per operation. That is paid on the admission path and on the HTTP
- * thread, never inside rad_arch_step and never per token on the step path, so it is free where it
- * would matter. The concrete types (rad::Scheduler, rad::Tokenizer, ...) are bound to these by
- * the adapters in adapters.h: one line each at the wiring site.
+ * The cost is one virtual call per operation, on the admission path and the HTTP thread, never
+ * inside rad_arch_step or per token on the step path. adapters.h binds the concrete types
+ * (rad::Scheduler, rad::Tokenizer, ...) to these.
  */
 #pragma once
 #include "rad_core.h"
@@ -27,141 +24,118 @@ namespace gen { struct Request; }
 namespace mm { struct Frame; struct Item; }
 namespace server {
 
-/* ordered_json, not json, and the reason is not cosmetic: a tool's parameter schema is rendered
- * into the prompt in the order the caller wrote it, and property order in a JSON schema changes
- * what the model emits. An unordered map would silently re-sort every caller's tool definitions. */
+/* ordered_json, not json: a tool's parameter schema is rendered into the prompt in the caller's
+ * order, and property order in a schema changes what the model emits. */
 using json = nlohmann::ordered_json;
 
 /* ================================================================== the scheduler
  *
- * ASSUMED of core/sched. `submit` takes the request by value and returns the id it assigned;
- * `cancel` is idempotent and must free the request's KV blocks immediately rather than at the
- * next completion (spec §14), because an agent client abandoning a long generation is the normal
- * case, not an edge case.
+ * Contract with core/sched: `submit` takes the request by value and returns its assigned id;
+ * `cancel` is idempotent and frees the request's KV blocks immediately, not at the next
+ * completion (spec §14), since abandoned generations are routine for agent clients.
  */
 struct SchedMetrics {
     int64_t waiting = 0;
     int64_t running = 0;
     int64_t preempted = 0;
     double  kv_util = 0.0;            /* 0..1 of the paged KV pool */
-    /* The paged pools in TOKENS. A percentage answers "how close to preemption"; tokens answer
-     * "how much context fits", and an operator sizing a deployment is asking the second. */
+    /* The paged pools in tokens: how much context fits, which kv_util does not say. */
     int64_t kv_tokens_used = 0;
     int64_t kv_tokens_total = 0;
-    /* AND HOW MUCH OF `used` NO RUNNING REQUEST IS READING, which is the difference between a
-     * cache doing its job and a leak. A finished turn's blocks stay held so the next turn can
-     * reuse them, so on a server carrying conversations this is most of the pool -- and with one
-     * number for the whole of it there is no way to tell that from a pool that never releases.
-     * It is the cache's UNSHARED holding: a block a running request is also reading belongs to
-     * that request in this split, because evicting it would free nothing. */
+    /* The part of `used` no running request reads: the prefix cache's unshared holding of
+     * finished turns. It separates a working cache from a pool that never releases. A block a
+     * running request also reads counts as that request's, since evicting it frees nothing. */
     int64_t kv_tokens_cached = 0;
-    /* AND THE PAGED AND STATEFUL POOLS TOGETHER, IN BYTES: how much of the card the KV cache is
-     * holding, which is the question an operator watching VRAM is actually asking and the one
-     * neither figure above can answer. Tokens cannot be summed across groups -- two paged groups
-     * share one token axis and a recurrent group has none -- so the totals above are one group's,
-     * the binding one. Bytes are disjoint allocations and add up, so these are every group.
+    /* Paged and stateful pools together, in bytes: how much VRAM the KV cache holds. Tokens do
+     * not sum across groups (paged groups share one token axis, a recurrent group has none), so
+     * the token figures above are the binding group's; bytes are disjoint and cover every group.
      *
-     * USED IS WHAT IS HELD, not what a live request is reading. A finished turn's blocks stay held
-     * by the prefix cache so the next turn can reuse them, and they are occupying VRAM for exactly
-     * as long; they stop counting when they reach the free list, which is where an eviction, a
-     * cancellation and an idle-tier demotion all put them. */
+     * Used means held, including prefix-cache blocks of finished turns; a block stops counting
+     * when it reaches the free list (eviction, cancellation or idle-tier demotion). */
     int64_t kv_bytes_used = 0;
     int64_t kv_bytes_total = 0;
     /* What the pool was carved to address, which an elastic pool may not be holding. */
     int64_t kv_bytes_carved = 0;
-    /* THE MOST CONTEXT THE CACHE CAN HOLD: every block of its carve, the ones lent to the expert
-     * slab taken back. `kv_bytes_carved` is the same figure in bytes. The paged groups share one
-     * token axis, so it is the smallest of theirs; a windowed group is left out, because its carve
-     * bounds how far back a sequence keeps context rather than how much fits. */
+    /* The most context the cache can hold: every block of its carve, including those lent to the
+     * expert slab (`kv_bytes_carved` in bytes). The smallest over the paged groups, which share
+     * one token axis; windowed groups are excluded, since their carve bounds lookback, not fit. */
     int64_t kv_tokens_max = 0;
 
     double  prefix_hit_rate = 0.0;    /* 0..1 */
-    /* Cumulative prefix-cache evictions. `prefix_hit_rate` falls only AFTER a prefix that
-     * would have been reused is gone; this rises as it happens, which is the difference
-     * between an alert and a post-mortem. */
+    /* Cumulative prefix-cache evictions. They rise as reusable prefixes are dropped, while
+     * `prefix_hit_rate` falls only afterwards. */
     int64_t prefix_evictions = 0;
     int64_t prefix_ckpt_evictions = 0;
-    /* What --prefix-cache-ttl took, cumulative. Not evictions: nothing wanted the memory. */
+    /* Snapshot evictions by reason (the retention policy; the least recently used of a store
+     * retention left full) and reservations that went without a snapshot. */
+    int64_t prefix_ckpt_retired = 0, prefix_ckpt_lru = 0, prefix_ckpt_refused = 0;
+    /* Admissions whose prefix hit was cut to nothing, by reason, and the checkpoint shortfall:
+     * attention-cached prompt tokens computed again (rad::SchedMetrics::hit_cut_tokens). */
+    int64_t hit_cut_no_snapshot = 0, hit_cut_window = 0, hit_cut_adopt = 0;
+    int64_t hit_cut_tokens = 0;
+    /* Removed by --prefix-cache-ttl, cumulative. Not evictions: nothing wanted the memory. */
     int64_t prefix_expired = 0, prefix_ckpt_expired = 0;
-    /* PREFIX CACHING, DECOUPLED (spec §7.3). `prefix_hit_rate` above is the ATTENTION one, because
-     * that is what vLLM's single number has always meant. The linear side hits at a different
-     * granularity -- whole checkpoints, not blocks -- and averaging the two would hide exactly the
-     * effect the decoupling exists to expose. So both are carried, and the token counts beside
-     * them, and the checkpoints actually written. Without all of it a deployment cannot tell
-     * whether linear checkpointing is working at all. */
+    /* Decoupled prefix caching (spec §7.3). `prefix_hit_rate` is the attention hit rate, as in
+     * vLLM. The linear side hits at a different granularity (whole checkpoints, not blocks), so
+     * it is reported separately, with token counts and checkpoints written. */
     double  linear_hit_rate = 0.0;
     int64_t attn_cached_tokens = 0;
     int64_t linear_cached_tokens = 0;
     int64_t checkpoints_written = 0;
     double  prefill_tps = 0.0;
     double  decode_tps = 0.0;
-    /* AND THE EXACT COUNTS BEHIND THEM. The two rates above are EWMAs, which is the right thing
-     * for a dashboard and the wrong thing for anything that has to compare two runs: a gauge
-     * describes whatever mix the engine happened to be in when it was read. These cumulative
-     * totals are the comparable form, and the only one: `vllm:generation_tokens_total` is charged
-     * when a request FINISHES and is therefore identically zero over any steady-state window. */
+    /* Exact cumulative counts behind the EWMA rates above, for comparing runs.
+     * `vllm:generation_tokens_total` is charged when a request finishes, so it cannot serve. */
     int64_t prefill_tokens = 0;
     int64_t decode_tokens = 0;
     double  draft_acceptance = 0.0;   /* 0..1, spec §10 */
-    /* The exact pair the ratio is computed from, for the same reason. */
+    /* The exact pair the ratio is computed from. */
     int64_t draft_tokens = 0;
     int64_t draft_accepted = 0;
     /* Prefix hits ended early for a windowed block drafter, and the tokens they gave back. */
     int64_t draft_refills = 0;
     int64_t draft_refill_tokens = 0;
-    /* THE PER-POSITION DRAFT HAZARD. `draft_acceptance` above is pooled over the whole window and
-     * cannot distinguish a drafter that decays with depth from one whose later rounds are broken:
-     * both read as one small number. These carry the conditional rate at each position -- of the
-     * verifies that reached j because every earlier position was accepted, the fraction that took
-     * j as well -- and the reach counts that say how much evidence each one has. */
+    /* Per-position draft acceptance. The pooled `draft_acceptance` cannot tell a drafter that
+     * decays with depth from one whose later rounds are broken. Per position j: verifies that
+     * reached j (every earlier position accepted) and how many of those took j. */
     static const int MAX_DRAFT_POS = 64;
     int     draft_depth_seen = 0;
     int64_t draft_pos_reached [MAX_DRAFT_POS] = {};
     int64_t draft_pos_accepted[MAX_DRAFT_POS] = {};
-    /* THE ADAPTIVE DRAFT WINDOW (--draft-window adaptive), all zero while it is off: the mean window
-     * of the running sequences, and the verifies by the window they carried (index = drafts). */
+    /* Adaptive draft window (--draft-window adaptive), zero while off: the running sequences'
+     * mean window, and verifies by the window they carried (index = drafts). */
     bool    draft_adaptive = false;
     double  draft_depth_adaptive = 0.0;
     int64_t draft_verify_depth[MAX_DRAFT_POS + 1] = {};
     int64_t preemptions = 0;
     int64_t total_requests = 0;
-    /* ENGINE STEPS. One forward pass of the model plus whatever draft rounds followed it, which
-     * with speculation is more than one token -- so tokens a second cannot answer "how long is a
-     * step" and the two questions have to be asked separately. */
+    /* Engine steps: one forward pass plus any draft rounds after it. With speculation a step
+     * emits more than one token, so step time cannot be derived from tokens per second. */
     int64_t steps = 0;
-    /* STEPS BY SHAPE. A step carrying a prefill chunk cannot roll back a rejected draft, so
-     * nothing in it speculates, decode rows included. These say how often the load produces that
-     * shape and how many decode rows paid for it. */
+    /* Steps by shape. A mixed step carries a prefill chunk and decode rows, and its decode rows
+     * take drafts like a decode step's (Scheduler::step). */
     int64_t steps_prefill = 0;
     int64_t steps_mixed = 0;
     int64_t steps_decode = 0;
     int64_t steps_ahead = 0;          /* issued behind the step before, ahead of its commit */
     int64_t prefill_chunks_capped = 0; /* held back for other work in the step (--busy-prefill-chunk) */
+    int64_t steps_held = 0;           /* decode-only steps --prefill-interleave inserted */
     int64_t decode_rows_unspeculated = 0;
-    /* WHAT THE STEPS COST: cumulative nanoseconds spent inside a step, and the decode half of it
-     * separately. A step time is not wall clock over a step count -- the engine idles between an
-     * agent's turns and a prefill chunk costs an order of magnitude more than a decode step, and
-     * a gauge that divides charges both to the decode step. `step_ns_decode / steps_decode` is
-     * what a decode step cost, whatever the load was doing around it. */
+    /* Cumulative nanoseconds inside steps, all shapes and decode-only. Wall clock over a step
+     * count is not a step time: the engine idles between turns, and a prefill chunk costs an
+     * order of magnitude more than a decode step. `step_ns_decode / steps_decode` is the cost of
+     * a decode step regardless of load. */
     int64_t step_ns = 0;
     int64_t step_ns_decode = 0;
 };
 
 
-/* WHAT ONE REQUEST IS DOING RIGHT NOW. The aggregate metrics answer "is the engine busy"; they
- * cannot answer "which of these eight is stuck", and a request sitting in Waiting because its
- * prompt will never fit is invisible in every one of them. */
-
-/* ONE STORED CONVERSATION. Not a request: a request is in flight and is gone when it answers,
- * while this is what the engine is still HOLDING on a session's behalf between turns -- which is
- * the thing that decides whether the next turn costs a copy or a re-prefill.
+/* One stored conversation: what the engine still holds for a session between turns, which
+ * decides whether the next turn costs a copy or a re-prefill.
  *
- * THE SIZES OVERLAP AND THE TOTAL IS NOT A SUM. Sessions that share a system prompt share the
- * blocks for it, which is the entire point of a prefix cache; a view that hid that would make a
- * server look like it was storing several times what it holds. Anything rendering these says so.
- *
- * A SESSION IS ROUTINELY SPLIT ACROSS TIERS, because a maintenance pass is bounded and moves a
- * long conversation over several of them. So "where is it" is three counts and not a label. */
+ * Sizes overlap: sessions sharing a system prompt share its blocks, so a total is not a sum, and
+ * anything rendering these must say so. A session is routinely split across tiers (a maintenance
+ * pass is bounded), so its location is block counts, not a label. */
 struct SessionStat {
     uint64_t    id = 0;
     std::string model;            /* the container it was built against */
@@ -171,10 +145,9 @@ struct SessionStat {
     double      idle_s = 0;       /* since its last turn */
     double      age_s = 0;        /* since it was first seen */
     int64_t     on_device = 0, on_host = 0;   /* blocks */
-    /* LINEAR STATE, on a hybrid model, and counted apart from blocks because the two are not
-     * interchangeable. A session showing every block in host memory and no snapshot will come
-     * back and re-run every recurrent layer over its whole transcript -- which the hit rate will
-     * report as a hit. Zero everywhere on a model that has no recurrent state. */
+    /* Linear-state snapshots on a hybrid model, counted apart from blocks: a session with its
+     * blocks kept but no snapshot re-runs every recurrent layer over its transcript, though the
+     * hit rate reports a hit. Zero on a model with no recurrent state. */
     int64_t     snapshots = 0;
     int64_t     snap_bytes = 0;
     /* The prefix a return skips: the deepest snapshot's position (IdleTiers::SessionInfo). */
@@ -182,13 +155,15 @@ struct SessionStat {
     bool        moving = false;   /* a transfer is outstanding */
 };
 
-/* WHAT THE STORED CONVERSATIONS OCCUPY OFF THE CARD, blocks and snapshots each counted once --
- * the one total the per-session rows cannot be summed into. Caps are 0 for a tier that is off. */
+/* What stored conversations occupy off the card, blocks and snapshots each counted once (the
+ * per-session rows cannot be summed into this). Caps are 0 for a tier that is off. */
 struct SessionOccupancy {
     int64_t host_bytes = 0;
     int64_t host_cap_bytes = 0;
 };
 
+/* One in-flight request, for the live request table: shows which request is stuck, e.g. one
+ * waiting on a prompt that will never fit, which no aggregate metric reveals. */
 struct RequestStat {
     uint64_t    id = 0;
     std::string state;             /* waiting | prefill | decode | preempted | done */
@@ -199,8 +174,7 @@ struct RequestStat {
     int64_t     max_tokens = 0;
     int64_t     ctx_tokens = 0;
     int64_t     kv_blocks = 0;    /* summed over the paged groups: they are disjoint allocations */
-    /* The context it is holding, on the token axis the paged groups share -- NOT their sum. See
-     * the note at the definition: the two figures are in different units on purpose. */
+    /* Context held, on the token axis the paged groups share (not their sum). */
     int64_t     kv_tokens = 0;
     int32_t     n_draft = 0;
     int32_t     slot = -1;
@@ -213,10 +187,9 @@ class IScheduler {
 public:
     virtual ~IScheduler() = default;
     virtual uint64_t     submit(Request&& r) = 0;
-    /* THE SEQUENCES OF ONE API REQUEST, all admitted before a step can see any of them: a prompt
-     * array or `n` > 1 submitted one call at a time can have a step begin between two calls, so
-     * the batch they decode in -- and its tie-level rounding -- would depend on thread timing.
-     * ids[i] is what submit() would have returned for rs[i]. This default is that loop, for a
+    /* Admits all sequences of one API request before a step can see any of them; submitted one
+     * at a time, a step could start between calls and the batch (and its tie-level rounding)
+     * would depend on thread timing. ids[i] is submit()'s id for rs[i]. The default loop suits a
      * scheduler whose steps cannot interleave with submission. */
     virtual void submit_all(std::vector& rs, std::vector* ids) {
         ids->clear();
@@ -225,65 +198,53 @@ public:
     virtual void         cancel(uint64_t id) = 0;
     virtual SchedMetrics metrics() const = 0;
 
-    /* "I am finished with this request's sink; you may drop the Request." core/sched keeps a
-     * terminal request alive precisely because the HTTP thread still holds its sink, so somebody
-     * has to say when that stops being true, and the HTTP thread is the only one who knows.
-     * Called at most once per submitted id, after the response has been written. Default no-op,
-     * for a scheduler that frees at completion. */
+    /* The HTTP thread is done with this request's sink; the scheduler may drop the Request it
+     * keeps alive after termination. Called at most once per id, after the response is written.
+     * Default no-op, for a scheduler that frees at completion. */
     virtual void reap(uint64_t /*id*/) {}
 
-    /* CAN THIS REQUEST'S SAMPLING PARAMETERS BE SERVED AT ALL?
+    /* Whether this request's sampling parameters can be served at all. An unresolved sampler op
+     * is not a declare failure (a deployment that never sends `typical_p` needs no typical
+     * kernel; core/sample/sampler.h), only a request that asks for it is refused. The step loop
+     * treats an unresolved stage as unreachable and relies on this check.
      *
-     * A sampler op that does not resolve is deliberately not a declare failure -- a deployment
-     * that never sends `typical_p` does not need a typical kernel (core/sample/sampler.h). It
-     * becomes a failure when a request asks for it, and Sampler::check_request exists to say so
-     * by name. This is what the step loop relies on when it treats an unresolved stage as
-     * unreachable: without the check here, such a request is admitted, runs, and is cancelled
-     * mid-step with the reason in the log and a dead stream at the client.
-     *
-     * Asked once per submission, on the HTTP thread, before the first Request is built. Returns
-     * RAD_OK, or a negative status with `why` set. The default admits everything so a test's fake
-     * scheduler needs no change; the real answer comes from SchedulerBridge. */
+     * Called once per submission on the HTTP thread, before any Request is built. RAD_OK, or a
+     * negative status with `why` set. The default admits everything (test fakes); the real
+     * answer comes from SchedulerBridge. */
     virtual int admit(const SamplingParams& /*sp*/, std::string* /*why*/) const { return RAD_OK; }
 
-    /* DROP EVERY PREFIX-CACHE ENTRY, returning how many were dropped -- or a negative status when
-     * this build has no prefix cache, which is a 501 rather than a lie about having cleared one.
-     *
-     * vLLM has this endpoint and it exists for the same reason: the second run of a benchmark is
-     * not measuring what the first one measured, and an operator who cannot say "start cold"
-     * cannot compare two numbers. Releasing the cache's references is safe against a running step
-     * -- a block a live sequence holds stays allocated -- but it still takes the scheduler's lock,
-     * because the alternative is an HTTP thread walking the map a step is inserting into. */
+    /* Drops every prefix-cache entry and returns how many, or a negative status (501) when there
+     * is no prefix cache. Lets a benchmark start cold, as vLLM's endpoint does. Releasing the
+     * cache's references is safe against a running step (blocks a live sequence holds stay
+     * allocated), but it takes the scheduler's lock because a step may be inserting into the map. */
     virtual int64_t reset_prefix_cache() { return RAD_E_UNSUPPORTED; }
 
-    /* The live request table. Fills `out` and returns how many, oldest first; the default answers
-     * "this scheduler does not keep one", which is an empty table and not a wrong one. */
+    /* The live request table, oldest first; returns the count. Default: none kept. */
     virtual int requests(std::vector* /*out*/) const { return 0; }
 
-    /* The stored conversations: what the engine is still holding between turns, and where. The
-     * default answers "this build has no idle tiers", which is an empty table and not a wrong
-     * one -- with the tiers off, everything the cache holds is in VRAM by definition. */
+    /* The stored conversations and where they are held. Default: no idle tiers, so an empty
+     * table (everything the cache holds is in VRAM). */
     virtual int sessions(std::vector* /*out*/, SessionOccupancy* /*occ*/) const {
         return 0;
     }
 
-    /* WHAT THE TIERS HAVE ACTUALLY DONE. Without it the session table looks the same whether the
-     * tiers are working, switched off, or trying and failing every pass -- three very different
-     * situations that all render as "everything is in VRAM". */
+    /* What the idle tiers have done. Without it the session table looks the same whether the
+     * tiers work, are off, or fail every pass. */
     struct TierCounters {
-        /* `to_host` counts COPIES; `dropped` is VRAM given up after one. A conversation that
-         * returns before anything wants its VRAM is copied and never dropped. `host_drops` is
-         * entries a full host tier gave up; `promoted` counts restores. */
+        /* `to_host` counts copies; `dropped` is VRAM given up after one (a conversation that
+         * returns before its VRAM is wanted is copied but never dropped). `host_drops` is entries
+         * a full host tier gave up; `promoted` counts restores. */
         int64_t to_host = 0, dropped = 0, promoted = 0;
         int64_t host_drops = 0, failures = 0;
+        /* Copies a full host tier did not take, every host entry being worth as much; their
+         * entries stay in VRAM only (IdleTiers::Stats::held_back). */
+        int64_t held_back = 0;
         int64_t host_bytes = 0;
-        /* THE SNAPSHOT STORE, which lives in host memory and moves nothing. */
+        /* The snapshot store, in host memory; it moves nothing. */
         int64_t ck_bytes = 0;      /* one snapshot; 0 on a model with no recurrent state */
         int64_t ck_slots = 0;
         int64_t restores = 0, restore_ns = 0, flushes = 0, flush_ns = 0;   /* IdleTiers::Stats */
-        /* WHETHER ANYTHING CAN MOVE AT ALL, which no counter above can answer: a tier that is on
-         * and has had nothing to do reads the same as one that was never given a size, and the
-         * two call for opposite responses from whoever is looking. */
+        /* Whether a host tier exists; an idle tier and an unconfigured one have equal counters. */
         bool host_on = false;
     };
     virtual TierCounters tier_counters() const { return TierCounters{}; }
@@ -291,19 +252,18 @@ public:
 
 /* ================================================================== text frontend
  *
- * ASSUMED of core/text. Detokenisation is incremental and streaming-safe (spec §12): byte-level
- * BPE emits partial UTF-8 sequences, so `push` returns "" until the bytes resolve into a
- * character, and `flush` drains whatever is left at the end of a generation.
+ * Contract with core/text. Detokenisation is incremental and streaming-safe (spec §12): byte-level
+ * BPE emits partial UTF-8, so `push` returns "" until the bytes form a character, and `flush`
+ * drains the rest at the end of a generation.
  */
 class IDetokenizer {
 public:
     virtual ~IDetokenizer() = default;
     virtual std::string push(int32_t token) = 0;
     virtual std::string flush() = 0;
-    /* True once the decoder itself swallowed a stop string. core/text's Detokenizer can be built
-     * with the request's stop strings and then never emits one; without this the server would
-     * search text that can no longer contain what it is searching for, and the generation would
-     * run to max_tokens. Default false, for a decoder that leaves stop handling to us. */
+    /* True once the decoder itself swallowed a stop string. core/text's Detokenizer, built with
+     * the stop strings, never emits one, so the server cannot find it in the text and relies on
+     * this. Default false, for a decoder that leaves stop handling to the server. */
     virtual bool stopped() const { return false; }
     /* The stop string that stopped it, "" when none has. */
     virtual std::string stop_hit() const { return std::string(); }
@@ -317,24 +277,18 @@ public:
     virtual ~ITokenizer() = default;
 
     /* `parse_special` decides whether a control token spelled out in the text is that token or
-     * its characters, and there is no default because a default is how the wrong one gets picked
-     * silently. Text the server is sent as a whole prompt is parsed: a rendered chat template
-     * carries the control tokens that frame its turns, and a raw /v1/completions prompt is the
-     * client's own rendering of the same, as vLLM and llama.cpp read it. Text that must reach the
-     * model as characters is encoded with false. */
+     * its characters; it has no default so every caller chooses. Whole prompts are parsed (a
+     * rendered chat template, or a raw /v1/completions prompt, as vLLM and llama.cpp read it).
+     * Text that must reach the model as characters is encoded with false. */
     virtual std::vector encode(const std::string& text, bool add_special,
                                         bool parse_special) const = 0;
     virtual std::string          decode(const std::vector& toks) const = 0;
     virtual int32_t              eos() const = 0;
     virtual int32_t              bos() const = 0;
 
-    /* WHAT THIS VOCABULARY IS, for /tokenize and /get_tokenizer_info. Off every hot path: asked
-     * once per request to those two endpoints and never during generation.
-     *
-     * A struct rather than eight accessors because the set will grow, and a client that reads
-     * this to decide how to build a prompt would otherwise be reading it across eight virtual
-     * calls that can disagree about which vocabulary they describe. The default is "I do not
-     * know", which is what a fake tokenizer in a test honestly is. */
+    /* Vocabulary facts for /tokenize and /get_tokenizer_info; never called during generation.
+     * One struct, so the fields describe one vocabulary consistently. The default is "unknown"
+     * (test fakes). */
     struct VocabInfo {
         int32_t     n_tokens = 0;
         int32_t     bos = -1, eos = -1, eot = -1, unk = -1, pad = -1;
@@ -343,32 +297,26 @@ public:
     };
     virtual VocabInfo vocab_info() const { return VocabInfo{}; }
 
-    /* The raw piece an id stands for, NOT its decoded text: /tokenize's `return_token_strs` shows
-     * what the tokeniser actually chose, and decoding each id one at a time would render a
-     * byte-fallback token as a replacement character and lose exactly the detail the caller
-     * turned the flag on to see. "" when the id is out of range. */
+    /* The raw piece an id stands for, not its decoded text: /tokenize's `return_token_strs` shows
+     * what the tokeniser chose, and decoding one id at a time would turn a byte-fallback token
+     * into a replacement character. "" when the id is out of range. */
     virtual std::string piece(int32_t /*id*/) const { return std::string(); }
 
-    /* THE BYTES ONE ID DECODES TO, unsanitised, control tokens rendered: llama-server's
-     * `with_pieces`. Not necessarily whole UTF-8 -- a byte-fallback or a split multi-byte
-     * character is a fragment -- so the caller checks before putting it in a JSON string. */
+    /* The bytes one id decodes to, unsanitised, control tokens rendered (llama-server's
+     * `with_pieces`). Not necessarily whole UTF-8, so the caller checks before putting it in a
+     * JSON string. */
     virtual std::string token_bytes(int32_t /*id*/) const { return std::string(); }
-    /* The bytes one id adds to a REPLY: token_bytes with control tokens rendered as nothing, as
-     * the decoder renders them -- what a logprobs entry spells the token as, so the entries'
-     * texts add up to the reply, as llama-server's do. */
+    /* The bytes one id adds to a reply: token_bytes with control tokens rendered as nothing, as
+     * the decoder does. Used for logprobs entries, so their texts add up to the reply, as
+     * llama-server's do. */
     virtual std::string reply_bytes(int32_t id) const { return token_bytes(id); }
 
-    /* One incremental decoder per in-flight generation. It is made by the tokenizer rather than
-     * default-constructed by the caller, because it needs the vocabulary to decode anything.
-     * `stops` is passed down because core/text's Detokenizer can suppress a stop string that
-     * straddles a token boundary, which is strictly better than the server finding it after the
-     * fact -- and IDetokenizer::stopped() is how it tells us it did.
+    /* One incremental decoder per in-flight generation. `stops` lets core/text's Detokenizer
+     * suppress a stop string that straddles a token boundary; IDetokenizer::stopped() reports it.
      *
-     * `preserved` is the control tokens this generation must decode as TEXT. A tool-calling
-     * format can be built out of control tokens -- MiniCPM5 writes ` detokenizer(
         const std::vector& stops,
         const std::vector& preserved = {}) const = 0;
@@ -376,12 +324,11 @@ public:
 
 class IReplyParser;
 
-/* What a chat template needs told, beyond the messages themselves.
+/* What a chat template needs beyond the messages.
  *
- * `template_kwargs` VALUES ARE JSON TEXT, not display text: `"false"`, `"\"high\""`, `"3"`. That
- * is the shape the request carries them in and the shape the template context wants them in, and
- * converting in between would mean this layer deciding that the string "false" is a boolean --
- * which is exactly the guess that makes `enable_thinking: "false"` silently enable thinking. */
+ * `template_kwargs` values are JSON text, not display text: `"false"`, `"\"high\""`, `"3"`, as
+ * the request carries them and the template context wants them. Converting would mean guessing
+ * that the string "false" is a boolean, which makes `enable_thinking: "false"` enable thinking. */
 struct ChatRenderOptions {
     bool        add_generation_prompt = true;
     bool        enable_thinking = true;
@@ -391,20 +338,17 @@ struct ChatRenderOptions {
     std::string grammar;                     /* the caller's GBNF, or "" */
     std::string json_schema;                 /* a response_format schema, as JSON text, or "" */
     std::string reasoning_format = "auto";
-    /* ASSISTANT PREFILL: continue the conversation's last (assistant) message rather than open a
-     * new turn. "" off, else llama.cpp's "auto", "content" or "reasoning_content". */
+    /* Assistant prefill: continue the last (assistant) message rather than open a new turn. ""
+     * off, else llama.cpp's "auto", "content" or "reasoning_content". */
     std::string continue_final;
     std::map template_kwargs;
-    /* A render whose refusal is an answer and not an error -- the startup probes of what the
-     * template takes -- so the template's refusal is not logged. */
+    /* Startup probes, where a refusal is an answer, not an error: do not log it. */
     bool        quiet = false;
 };
 
-/* What it gives back. A STRING IS NOT ENOUGH, and that is the whole reason this struct exists: a
- * tool-calling template emits a prompt AND the grammar that makes the model's call parseable AND
- * the triggers that keep that grammar off the prose AND the stop strings the format ends on. A
- * seam that returns only the prompt drops the other three silently, which is a chat endpoint that
- * accepts `tools` and then produces calls no client can read. */
+/* A render's result. A tool-calling template produces more than a prompt: the grammar that keeps
+ * the model's call parseable, the triggers that keep it off the prose, and the format's stop
+ * strings. Dropping them yields tool calls no client can read. */
 struct ChatRender {
     std::string prompt;
 
@@ -414,21 +358,21 @@ struct ChatRender {
     std::vector additional_stops;
 
     /* The assistant prefix already inside `prompt`. The grammar describes the whole turn, so it
-     * has to be advanced over this before it constrains the first generated token. */
+     * is advanced over this before constraining the first generated token. */
     std::string generation_prompt;
 
-    /* The reply parser this render implies: the model's reply format bound to THESE tools and
-     * THIS generation prompt, so it cannot be a server-wide singleton. It reads calls only when
-     * the request sent tools. Null when nothing needs parsing. */
+    /* The reply parser for this render: the model's reply format bound to these tools and this
+     * generation prompt, hence per request. It reads calls only when the request sent tools.
+     * Null when nothing needs parsing. */
     std::shared_ptr parser;
 
-    /* The tokens that parser must be able to SEE. See ITokenizer::detokenizer. */
+    /* Control tokens the parser must see as text. See ITokenizer::detokenizer. */
     std::vector preserved_tokens;
 
-    /* THE REASONING BLOCK THIS RENDER LEAVES THE REPLY FACING, as the parser reads it: the
-     * markers with their optional whitespace trimmed, and whether the reply starts inside the
-     * block. Empty `think_close` is a model with no reasoning block. The server turns these into
-     * token ids (ReasoningSpan) to count the block and to hold a budget on it. */
+    /* The reasoning block the reply faces, as the parser reads it: markers with optional
+     * whitespace trimmed, and whether the reply starts inside the block. Empty `think_close`
+     * means no reasoning block. The server maps these to token ids (ReasoningSpan) to count the
+     * block and enforce a budget. */
     std::string think_open, think_close;
     bool        think_starts_open = false;
 };
@@ -437,24 +381,22 @@ class IChatTemplate {
 public:
     virtual ~IChatTemplate() = default;
 
-    /* Render. Returns RAD_OK, or a negative status with `why` naming what the template refused --
-     * which becomes the 400's message, so it has to read like something a caller can act on. */
+    /* Render. RAD_OK, or a negative status with `why` naming what the template refused; `why`
+     * becomes the 400's message, so it must be actionable for the caller. */
     virtual int apply(const json& messages, const json& tools, const ChatRenderOptions& opt,
                       ChatRender* out, std::string* why) const = 0;
 
     virtual bool supports_tools() const = 0;
     virtual bool supports_reasoning() const = 0;
 
-    /* WHY THIS MODEL'S TOOL CALLS CANNOT BE READ, or "" when they can. A template may declare tool
-     * support in a format the reply parser does not describe; such a model still chats, and a
-     * request that sends tools is refused with this sentence rather than answered with calls
-     * nobody can read back. */
+    /* Why this model's tool calls cannot be read, or "" when they can. A template may support
+     * tools in a format the reply parser does not know; the model still chats, and a request that
+     * sends tools is refused with this sentence. */
     virtual std::string tool_refusal() const { return std::string(); }
 
-    /* THE TEMPLATE'S SOURCE TEXT and what the capability probe found in it, for /props: what
-     * llama-server reports as `chat_template` and `chat_template_caps`, so a client built against
-     * it can render a prompt the way this server will. "" when unknown; the caps are a JSON
-     * object as text, "{}" when unknown. */
+    /* The template's source and its probed capabilities, for /props (llama-server's
+     * `chat_template` and `chat_template_caps`), so clients can render prompts as this server
+     * does. "" and "{}" (a JSON object as text) when unknown. */
     virtual std::string source() const { return std::string(); }
     virtual std::string caps() const { return "{}"; }
 };
@@ -474,9 +416,9 @@ struct ParsedMessage {
     bool                  open_call = false;
 };
 
-/* One increment of a reply that is being read as it is generated. What has been delivered is
- * never revised: the concatenated increments of each kind ARE the finished values, which is what
- * lets the streaming endpoint forward each one as it comes. */
+/* One increment of a reply read as it is generated. Delivered increments are never revised: the
+ * concatenated increments of each kind are the finished values, so streaming forwards each as it
+ * comes. */
 struct ReplyDelta {
     enum Kind : uint8_t {
         Reasoning,   /* text: a reasoning delta */
@@ -490,9 +432,9 @@ struct ReplyDelta {
     std::string text;
 };
 
-/* One choice's reply, read once, in order, as it is generated. feed() appends generated text
- * and finish() says there is no more; each appends the increments it completes. The cost is
- * linear in the reply however it is cut up -- the text is never read from the top again. */
+/* One choice's reply, read once, in order, as it is generated. feed() appends generated text and
+ * finish() ends it; each appends the increments it completes. Linear in the reply however it is
+ * split; the text is never re-read from the top. */
 class IReplyReader {
 public:
     virtual ~IReplyReader() = default;
@@ -500,14 +442,14 @@ public:
     virtual void finish(std::vector* out) = 0;
     /* The whole reply, once finish() has run. */
     virtual ParsedMessage message() const = 0;
-    /* Once finish() has run: the content with an open last call (ParsedMessage::open_call) read
-     * as the text it was written as -- the content before the call, then the call's own bytes
-     * from `reply`, the whole text fed. The content alone when no call is open. */
+    /* After finish(): the content with an open last call (ParsedMessage::open_call) restored as
+     * text, i.e. the content before the call plus the call's own bytes from `reply` (the whole
+     * text fed). The content alone when no call is open. */
     virtual std::string content_with_open_call(std::string_view reply) const = 0;
 };
 
-/* A request's reply format. Each choice opens its own reader, and a request that sent no tools
- * gets a parser that reads no calls: call syntax in its reply is text to that request. */
+/* A request's reply format. Each choice opens its own reader. A request that sent no tools gets
+ * a parser that reads no calls, so call syntax in its reply is plain text. */
 class IReplyParser {
 public:
     virtual ~IReplyParser() = default;
@@ -521,26 +463,25 @@ public:
     virtual ~IGrammarCompiler() = default;
     virtual int from_json_schema(const json& schema, std::string& out, std::string& err) const = 0;
 
-    /* Compile this GBNF, here, on the admitting thread, and hand back the program for the request
-     * to carry (SamplingParams::grammar_program). Compiling is where a grammar is found not to
-     * run -- left recursion, a construct the mask engine cannot serve, a bound it outgrows -- and
-     * where its mask plan is built, which is host work in the tens to hundreds of milliseconds.
-     * The alternative is doing both on the scheduler thread, where the only thing left to do about
-     * a failure is kill the request three tokens into its answer, and every other request's step
-     * waits for the build. A grammar that cannot be compiled is a 400 that names why. */
+    /* Compiles this GBNF on the admitting thread into the program the request carries
+     * (SamplingParams::grammar_program). Compiling finds grammars that cannot run (left
+     * recursion, constructs the mask engine cannot serve, bounds it outgrows) and builds the mask
+     * plan, tens to hundreds of milliseconds of host work. On the scheduler thread a failure
+     * could only kill the request mid-answer and the build would stall every step. Failure is a
+     * 400 naming why. */
     virtual int compile(const std::string& gbnf, std::shared_ptr* out,
                         std::string& err) const = 0;
 };
 
 /* ================================================================== optional backends */
 
-/* /v1/embeddings: WHAT THE LOADED MODEL EMBEDS, present only when it is an embedding model
- * (rad_declare_pooled). Absent, the endpoint is 501 naming that -- not an empty 200.
+/* /v1/embeddings, present only for an embedding model (rad_declare_pooled); absent, the endpoint
+ * is 501.
  *
- * The vectors themselves come through the scheduler like any other request: the server submits
- * one Request a input with Request::embed set, and each finishes at its one step with its pooled
- * vector in its sink (Sink::embedding). So batching, admission, media encoding and cancellation
- * are the scheduler's, exactly as they are for a completion. */
+ * Vectors come through the scheduler: the server submits one Request per input with
+ * Request::embed set, and each finishes after one step with its pooled vector in its sink
+ * (Sink::embedding). Batching, admission, media encoding and cancellation work as for a
+ * completion. */
 class IEmbedder {
 public:
     virtual ~IEmbedder() = default;
@@ -548,8 +489,8 @@ public:
     virtual int64_t dim() const = 0;
     /* The longest input one step carries: an input is never split, so a longer one is refused. */
     virtual int64_t max_input() const = 0;
-    /* THE MODEL'S NAMED PROMPTS (sentence-transformers' `prompts`): the text a `prompt_name` puts
-     * in front of an input -- "query" -> "task: search result | query: ". False when the model
+    /* The model's named prompts (sentence-transformers' `prompts`): the text a `prompt_name`
+     * prepends to an input, e.g. "query" -> "task: search result | query: ". False when the model
      * states no prompt of that name. */
     virtual bool prompt(const std::string& name, std::string* text) const {
         (void)name; (void)text;
@@ -557,8 +498,7 @@ public:
     }
     /* The prompt an input takes when the request names none, "" for none. */
     virtual std::string default_prompt() const { return std::string(); }
-    /* The template a `messages` input renders through -- the model's chat template -- or null
-     * when it has none. */
+    /* The chat template a `messages` input renders through, or null. */
     virtual IChatTemplate* message_template() const { return nullptr; }
 };
 
@@ -568,13 +508,12 @@ public:
  * for a video, the timestamps between its frames. */
 enum class MediaKind { Image, Video, Audio };
 
-/* The placeholder a chat template renders where a media part sat. Both the template and the
- * server have to agree on the spelling or the prompt silently loses its images, so it is declared
- * once, here, rather than twice. llama.cpp's mtmd uses the same string, which is not an accident:
- * the templates are the same templates. */
+/* The placeholder a chat template renders where a media part sat. Template and server must agree
+ * on it, so it is declared once, here. It is llama.cpp mtmd's string, since the templates are
+ * shared. */
 #define RAD_MEDIA_MARKER "<__media__>"
 
-/* WHAT A REQUEST ASKED OF ITS MEDIA, beside the bytes. Zero is the server's default. */
+/* Per-request media options beside the bytes. Zero is the server's default. */
 struct MediaOpts {
     /* Soft tokens (encoder output rows) an image may become, for a processor that sizes images
      * by a token budget (Gemma 4's: 70, 140, 280, 560 or 1120). */
@@ -593,13 +532,48 @@ public:
      * token run that replaces the marker; on failure `why` says what is wrong with the media. */
     virtual int prepare(MediaKind k, const std::vector& bytes, const MediaOpts& opts,
                         std::shared_ptr* out, std::string* why) = 0;
+
+    /* Audio in two halves, for a route that cuts a long recording into clips itself
+     * (/v1/audio/transcriptions): the file decoded to mono samples at audio_rate(), at most
+     * `max_samples` of them (RAD_E_INVAL past that, never a silent cut), and a clip of at most
+     * audio_max_samples() processed as prepare() would. Zero rate: no audio is served. */
+    virtual int32_t audio_rate() const { return 0; }
+    virtual int64_t audio_max_samples() const { return 0; }
+    virtual int decode_audio(const std::vector& bytes, int64_t max_samples,
+                             std::vector* out, std::string* why) {
+        (void)bytes; (void)max_samples; (void)out;
+        if (why) *why = "this server decodes no audio";
+        return RAD_E_UNSUPPORTED;
+    }
+    virtual int prepare_audio(const std::vector& samples, std::shared_ptr* out,
+                              std::string* why) {
+        (void)samples; (void)out;
+        if (why) *why = "this server serves no audio";
+        return RAD_E_UNSUPPORTED;
+    }
+};
+
+/* How the model takes audio, as the architecture plugin states it (RadAudioFormat,
+ * abi/rad_builder.h), copied out at startup. It is all the speech routes know of the model. */
+struct SpeechFormat {
+    std::string transcribe_prompt;   /* {context}, {audio}, {language} */
+    std::string language_prompt;     /* {language} */
+    std::string transcript_open;
+    std::string language_lead;
+    /* (ISO 639-1 code, the model's name for it) */
+    std::vector> languages;
+
+    bool transcribes() const { return !transcribe_prompt.empty(); }
+    /* The model's name for `lang`, which may be a code or a name in any case; "" when the model
+     * names no such language. */
+    std::string language_name(const std::string& lang) const;
 };
 
 
-/* THE IMAGE GENERATOR (core/gen), for a model that makes pictures rather than text: what the
- * model declared about its prompts and sizes, and the queue a request goes into. The server turns
- * an OpenAI images request into a gen::Request -- the prompt rendered and tokenised, the reference
- * pictures resized for both of the model's readers -- and reads the pictures back off its ticket. */
+/* The image generator (core/gen), for a model that makes pictures: its declared prompt templates
+ * and sizes, and its request queue. The server turns an OpenAI images request into a gen::Request
+ * (prompt rendered and tokenised, reference pictures resized for both of the model's readers) and
+ * reads the pictures back off its ticket. */
 struct ImageGenInfo {
     std::string name, tmpl_text, tmpl_edit, tmpl_image, tmpl_image_sep, drop_prefix,
                 tmpl_transparent;
diff --git a/core/server/images.cpp b/core/server/images.cpp
index e095e0d6..8d953c5f 100644
--- a/core/server/images.cpp
+++ b/core/server/images.cpp
@@ -1,24 +1,22 @@
 /* images.cpp -- OpenAI's images API over an image generator (core/gen): /v1/images/generations
  * and /v1/images/edits.
  *
- * WHAT A REQUEST BECOMES. The prompt goes into the model's own template (ImageGenInfo), with the
- * fixed system turn the generator drops; a transparent background asks for one in the words the
- * model was trained on. An edit's pictures are each resized to the model's reference area at their
- * own aspect -- with PIL's premultiplied Lanczos, as diffusers resizes them -- and read twice: as
- * RGBA pixels by the generator's encoder, and composited on white by the conditioning network's.
- * With a mask, the first picture is repainted: the mask's transparent pixels are where it may
- * change, the rest is put back exactly after decoding.
+ * Request: the prompt goes into the model's own template (ImageGenInfo), including the fixed
+ * system turn the generator drops; a transparent background is requested in the model's trained
+ * wording. Each edit picture is resized to the model's reference area at its own aspect (PIL's
+ * premultiplied Lanczos, as diffusers does) and read twice: as RGBA by the generator's encoder,
+ * and composited on white by the conditioning network's. With a mask, the first picture is
+ * repainted where the mask is transparent; the rest is restored exactly after decoding.
  *
- * WHAT IS EXTENDED, beside OpenAI's fields, by vLLM-Omni's names: `seed`, `negative_prompt` with
- * `true_cfg_scale` (guidance), `num_inference_steps`, and `width` / `height` in place of `size`.
- * A model with a fixed schedule (a distilled one) takes no step count but its own.
+ * Extensions, under vLLM-Omni's names: `seed`, `negative_prompt` with `true_cfg_scale`
+ * (guidance), `num_inference_steps`, and `width` / `height` instead of `size`. A fixed-schedule
+ * (distilled) model accepts only its own step count.
  *
- * WHAT IS REFUSED: `response_format: url` -- nothing here stores an image to serve later, so the
- * picture comes back in the response (b64_json) or not at all.
+ * Refused: `response_format: url`, since no image is stored to serve later; only b64_json.
  *
- * STREAMING is OpenAI's: `image_generation.partial_image` (`image_edit.partial_image`) events
- * for the `partial_images` previews -- the step's estimate of the finished latent, decoded -- and
- * one `.completed` event an image.
+ * Streaming follows OpenAI: `image_generation.partial_image` (`image_edit.partial_image`) events
+ * for the `partial_images` previews (each step's decoded estimate of the final latent), and one
+ * `.completed` event per image.
  */
 #include "server.h"
 #include "oai.h"
@@ -28,6 +26,7 @@
 #include "mm/media.h"
 #include "mm/processor.h"
 #include "rad_internal.h"
+#include "rad_plugin.h"
 
 #include 
 
@@ -46,9 +45,9 @@ namespace {
 /* The largest picture a request may upload, before any resize. */
 constexpr int64_t kMaxSourcePixels = (int64_t)1 << 26;
 
-/* Below this alpha a pixel is transparent: where a mask lets the picture change, and what makes a
- * picture one with transparency. A decoder's alpha is not exactly 255 on an opaque picture, so a
- * picture this model made and is given back to edit stays opaque. */
+/* Below this alpha a pixel counts as transparent, both in a mask and when deciding whether a
+ * picture has transparency. A threshold, not 255, because a decoder's alpha on an opaque picture is
+ * not exactly 255, so this model's own output stays opaque when edited. */
 constexpr uint8_t kTransparentBelow = 128;
 
 struct ImgReq {
@@ -91,7 +90,7 @@ json form_value(const std::string& key, const std::string& v) {
     return json(v);
 }
 
-/* diffusers' calculate_dimensions: a target area at an aspect, each side rounded to 32. */
+/* diffusers' calculate_dimensions: a target area at an aspect, each side rounded to `mult`. */
 void dims_for(double area, double ratio, int32_t mult, int32_t* w, int32_t* h) {
     const double wd = std::sqrt(area * ratio);
     const double hd = wd / ratio;
@@ -107,15 +106,8 @@ std::string replace_all(std::string s, const std::string& what, const std::strin
     return s;
 }
 
-uint16_t f32_bf16(float f) {
-    uint32_t u;
-    std::memcpy(&u, &f, 4);
-    u += 0x7FFFu + ((u >> 16) & 1u);
-    return (uint16_t)(u >> 16);
-}
-
 /* A picture as the generator's encoder reads it: each channel u -> 2 * (u / 255) - 1 in f32, then
- * bf16 -- VaeImageProcessor's preprocess, cast to the VAE's dtype. */
+ * bf16 (VaeImageProcessor's preprocess, cast to the VAE's dtype). */
 gen::Pixels to_pixels(const mm::FrameRGBA& f) {
     gen::Pixels p;
     p.w = f.w;
@@ -123,7 +115,7 @@ gen::Pixels to_pixels(const mm::FrameRGBA& f) {
     p.ch = 4;
     p.bf16.resize(f.rgba.size());
     for (size_t i = 0; i < f.rgba.size(); ++i)
-        p.bf16[i] = f32_bf16(2.0f * ((float)f.rgba[i] / 255.0f) - 1.0f);
+        p.bf16[i] = rad_f32_to_bf16(2.0f * ((float)f.rgba[i] / 255.0f) - 1.0f);
     return p;
 }
 
@@ -168,15 +160,11 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
             }
         }
     } else {
-        try {
-            body = json::parse(req.body);
-        } catch (const std::exception& e) {
-            return error_response(err_bad("", std::string("the body is not JSON: ") + e.what()),
-                                  req.peer);
-        }
-        if (!body.is_object()) return error_response(err_bad("", "the body is not a JSON object"), req.peer);
-        /* An edit's pictures as JSON: `images: [{image_url: "data:..."}]` and `mask: {image_url}`,
-         * the newer form of the API, or `image` as one data URL or a list of them. */
+        ApiError err;
+        if (parse_request_object(req.body, lim_, &body, &err) < 0)
+            return error_response(err, req.peer);
+        /* An edit's pictures as JSON: `images: [{image_url: "data:..."}]` and `mask: {image_url}`
+         * (the newer API form), or `image` as one data URL or a list. */
         auto url_of = [](const json& v, std::string* u) {
             if (v.is_string()) { *u = v.get(); return true; }
             if (v.is_object() && v.contains("image_url") && v["image_url"].is_string()) {
@@ -252,13 +240,13 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
         return 1;
     };
     if (str("prompt", &r.prompt) < 0)
-        return error_response(err_bad("prompt", "a string"), req.peer);
+        return error_response(err_bad("prompt", "expected a string"), req.peer);
     if (!body.contains("prompt"))
         return error_response(err_bad("prompt", "the prompt is required"), req.peer);
     if (r.prompt.empty()) r.prompt = " ";
     std::string rf;
     if (str("response_format", &rf) < 0 || (!rf.empty() && rf != "b64_json" && rf != "url"))
-        return error_response(err_bad("response_format", "b64_json"), req.peer);
+        return error_response(err_bad("response_format", "expected b64_json"), req.peer);
     if (rf == "url") {
         ApiError e = err_unsupported("response_format",
                                      "url is not served: this server keeps no image to serve "
@@ -268,17 +256,18 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
     }
     int64_t v = 0;
     if (num("n", 1, info.max_lanes, &v) < 0)
-        return error_response(err_bad("n", "1.." + std::to_string(info.max_lanes)), req.peer);
+        return error_response(
+            err_bad("n", "expected an integer in 1.." + std::to_string(info.max_lanes)), req.peer);
     r.n = body.contains("n") && !body["n"].is_null() ? (int32_t)v : 1;
     if (str("background", &r.background) < 0 ||
         (r.background != "auto" && r.background != "transparent" && r.background != "opaque")) {
-        ApiError e = err_bad("background", "auto, transparent or opaque");
+        ApiError e = err_bad("background", "expected auto, transparent or opaque");
         e.supported = { "auto", "transparent", "opaque" };
         return error_response(e, req.peer);
     }
     if (str("output_format", &r.format) < 0 ||
         (r.format != "png" && r.format != "jpeg" && r.format != "webp")) {
-        ApiError e = err_bad("output_format", "png, jpeg or webp");
+        ApiError e = err_bad("output_format", "expected png, jpeg or webp");
         e.supported = { "png", "jpeg", "webp" };
         return error_response(e, req.peer);
     }
@@ -286,14 +275,16 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
         return error_response(err_bad("background", "jpeg has no transparency; ask for png or "
                                                     "webp"), req.peer);
     if (num("output_compression", 0, 100, &v) < 0)
-        return error_response(err_bad("output_compression", "0..100"), req.peer);
+        return error_response(err_bad("output_compression", "expected an integer in 0..100"),
+                              req.peer);
     if (body.contains("output_compression")) r.compression = (int32_t)v;
     if (body.contains("stream") && !body["stream"].is_null()) {
-        if (!body["stream"].is_boolean()) return error_response(err_bad("stream", "a boolean"), req.peer);
+        if (!body["stream"].is_boolean())
+            return error_response(err_bad("stream", "expected a boolean"), req.peer);
         r.stream = body["stream"].get();
     }
     if (num("partial_images", 0, 3, &v) < 0)
-        return error_response(err_bad("partial_images", "0..3"), req.peer);
+        return error_response(err_bad("partial_images", "expected an integer in 0..3"), req.peer);
     if (body.contains("partial_images")) r.previews = (int32_t)v;
     if (r.previews > 0 && !r.stream)
         return error_response(err_bad("partial_images", "partial images are sent on a stream; "
@@ -301,14 +292,15 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
     if (str("quality", &r.quality) < 0 ||
         (r.quality != "auto" && r.quality != "low" && r.quality != "medium" &&
          r.quality != "high" && r.quality != "standard" && r.quality != "hd")) {
-        ApiError e = err_bad("quality", "auto, low, medium, high (standard, hd)");
+        ApiError e = err_bad("quality", "expected auto, low, medium or high (or standard, hd)");
         e.supported = { "auto", "low", "medium", "high", "standard", "hd" };
         return error_response(e, req.peer);
     }
     /* The step count: the request's, or what its quality asks for, or the model's. */
     int64_t steps = 0;
     if (num("num_inference_steps", 1, 200, &steps) < 0)
-        return error_response(err_bad("num_inference_steps", "1..200"), req.peer);
+        return error_response(err_bad("num_inference_steps", "expected an integer in 1..200"),
+                              req.peer);
     if (info.fixed_schedule) {
         if (steps != 0 && steps != info.fixed_steps)
             return error_response(err_unsupported("num_inference_steps",
@@ -322,23 +314,25 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
         else if (r.quality == "medium") steps = std::max(1, info.default_steps * 3 / 4);
     }
     r.steps = (int32_t)steps;
+    /* -1 asks for a random seed, as llama-server and the chat endpoints read it. */
     if (body.contains("seed") && !body["seed"].is_null()) {
         if (!body["seed"].is_number_integer())
-            return error_response(err_bad("seed", "an integer"), req.peer);
+            return error_response(err_bad("seed", "expected an integer"), req.peer);
         r.seed = (uint64_t)body["seed"].get();
-        r.seed_given = true;
+        r.seed_given = body["seed"].is_number_unsigned() || body["seed"].get() != -1;
     }
     if (str("negative_prompt", &r.negative) < 0)
-        return error_response(err_bad("negative_prompt", "a string"), req.peer);
+        return error_response(err_bad("negative_prompt", "expected a string"), req.peer);
     if (body.contains("true_cfg_scale") && !body["true_cfg_scale"].is_null()) {
         if (!body["true_cfg_scale"].is_number())
-            return error_response(err_bad("true_cfg_scale", "a number"), req.peer);
+            return error_response(err_bad("true_cfg_scale", "expected a number"), req.peer);
         r.cfg = body["true_cfg_scale"].get();
         if (!(r.cfg >= 1.0 && r.cfg <= 30.0))
-            return error_response(err_bad("true_cfg_scale", "1..30"), req.peer);
+            return error_response(err_bad("true_cfg_scale", "expected a number in 1..30"),
+                                  req.peer);
     }
-    /* Guidance needs both halves, as the reference pipeline does: a scale above one and a
-     * negative prompt (an empty one is " "). */
+    /* Guidance needs a scale above one and a negative prompt (empty becomes " "), as in the
+     * reference pipeline. */
     r.has_neg = r.cfg > 1.0 && body.contains("negative_prompt");
     if (r.has_neg && r.negative.empty()) r.negative = " ";
     if (r.cfg > 1.0 && !r.has_neg)
@@ -374,9 +368,8 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
     } else if (!files.empty() || have_mask) {
         return error_response(err_bad("image", "pictures go to /v1/images/edits"), req.peer);
     }
-    /* `auto` is decided by what was sent: an edit of a picture with transparency keeps it, and
-     * anything else is opaque -- a picture made without asking for transparency carries only the
-     * decoder's noise in its alpha. */
+    /* `auto`: an edit of a picture with transparency keeps it; anything else is opaque, since an
+     * image generated without transparency has only decoder noise in its alpha. */
     if (r.background == "auto") {
         bool alpha = false;
         if (r.format != "jpeg")
@@ -386,14 +379,17 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
         r.background = alpha ? "transparent" : "opaque";
     }
 
-    /* ---- the size: `width`/`height`, or `size` "WxH", or auto -- the native size, at the last
-     * picture's aspect for an edit. Sides are rounded down to the model's multiple. */
+    /* ---- the size: `width`/`height`, `size` "WxH", or auto (the native area, at the last
+     * picture's aspect for an edit). Sides are rounded down to the model's multiple. */
     const int32_t mult = (int32_t)info.size_multiple;
     std::string size = "auto";
-    if (str("size", &size) < 0) return error_response(err_bad("size", "\"WxH\" or \"auto\""), req.peer);
+    if (str("size", &size) < 0)
+        return error_response(err_bad("size", "expected \"WxH\" or \"auto\""), req.peer);
     int64_t bw = 0, bh = 0;
-    if (num("width", 1, 16384, &bw) < 0 || num("height", 1, 16384, &bh) < 0)
-        return error_response(err_bad("width", "1..16384"), req.peer);
+    if (num("width", 1, 16384, &bw) < 0)
+        return error_response(err_bad("width", "expected an integer in 1..16384"), req.peer);
+    if (num("height", 1, 16384, &bh) < 0)
+        return error_response(err_bad("height", "expected an integer in 1..16384"), req.peer);
     if ((bw > 0) != (bh > 0))
         return error_response(err_bad(bw ? "height" : "width", "width and height go together"),
                               req.peer);
@@ -404,7 +400,7 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
         int a = 0, b = 0;
         char x = 0;
         if (std::sscanf(size.c_str(), "%d%c%d", &a, &x, &b) != 3 || x != 'x' || a <= 0 || b <= 0)
-            return error_response(err_bad("size", "\"WxH\" or \"auto\""), req.peer);
+            return error_response(err_bad("size", "expected \"WxH\" or \"auto\""), req.peer);
         r.w = a;
         r.h = b;
     } else if (edit) {
@@ -427,8 +423,8 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
                                                   std::to_string(info.max_tokens * ls * ls) +
                                                   " pixels)"), req.peer);
     if (!r.seed_given) {
-        /* 53 bits: the seed goes back in the response to be sent again, and a JavaScript client
-         * reads a JSON number as a double -- a 64-bit seed would come back as another picture. */
+        /* 53 bits: the seed is returned for reuse, and JavaScript reads JSON numbers as doubles,
+         * so a wider seed would not round-trip. */
         std::random_device rd;
         r.seed = (((uint64_t)rd() << 32) ^ rd()) & (((uint64_t)1 << 53) - 1);
     }
@@ -461,8 +457,8 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
                                   req.peer);
         items.push_back(std::move(it));
     }
-    /* Repainting: the first picture at the size being made, and per latent token the share of
-     * its 16 x 16 pixels the mask leaves transparent -- those are repainted, the rest kept. */
+    /* Repainting: the first picture at the output size, and per latent token the fraction of
+     * its ls x ls pixels the mask leaves transparent. Those are repainted, the rest kept. */
     std::vector keep_px, src_px;
     if (r.has_mask) {
         mm::FrameRGBA src, msk;
@@ -498,8 +494,8 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
             tmpl = replace_all(tmpl, "{images}", imgs);
         }
         const std::string rendered = replace_all(tmpl, "{prompt}", text);
-        /* Tokenised piece by piece around the markers, each marker replaced by its picture's
-         * token run -- the chat path's tokenize_with_media, with pictures already processed. */
+        /* Tokenised around the markers, each marker replaced by its picture's token run: the
+         * chat path's tokenize_with_media, with the pictures already processed. */
         auto pm = std::make_shared();
         size_t pos = 0, mi = 0;
         for (;;) {
@@ -522,12 +518,12 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
             pm->layout();
             out->media = std::move(pm);
         }
-        /* The fixed turn the generator does not see, which must be where the prompt starts. */
+        /* The fixed turn the generator drops; the prompt must start with it. */
         const auto drop = deps_.tok->encode(info.drop_prefix, false, true);
         if (drop.size() > out->tokens.size() ||
             !std::equal(drop.begin(), drop.end(), out->tokens.begin())) {
-            *err = err_bad("prompt", "the prompt does not start with the model's fixed turn");
-            err->status = 500;
+            /* The model's own templates disagree; nothing the request did. */
+            *err = err_internal("the prompt does not start with the model's fixed turn");
             return RAD_E_STATE;
         }
         out->n_drop = (int32_t)drop.size();
@@ -547,12 +543,7 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
     }
 
     /* ---- admitted and queued */
-    sweep_abandoned();
-    if (!admit(1)) {
-        metrics_.observe_rejected();
-        return error_response(err_overloaded("the admission queue is full; retry after " +
-                                             std::to_string(opt_.retry_after_s) + "s"), req.peer);
-    }
+    if (auto no = admit(1, req.peer)) return *no;
     std::shared_ptr ticket = g->ticket;
     {
         std::string why;
@@ -632,9 +623,9 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
         }
         release(1);
         if (ticket->status() < 0 || (int32_t)done.size() != r.n) {
-            /* RAD_E_INVAL is the driver's refusal at admission -- a request this deployment can
-             * never serve, such as a conditioning longer than the cache -- and the client's to
-             * change; anything else failed while it ran. */
+            /* RAD_E_INVAL is the driver's admission refusal (a request this deployment can never
+             * serve, e.g. conditioning longer than the cache), so a 400; anything else failed
+             * while running. */
             ApiError e;
             const bool client = ticket->status() == RAD_E_INVAL;
             e.status = client ? 400 : 500;
@@ -669,7 +660,7 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
         return HttpResponse::json_body(200, json_dump(out));
     }
 
-    /* ---- streamed: partial images as the previews arrive, a completed event an image */
+    /* ---- streamed: partial images as previews arrive, one completed event per image */
     HttpResponse res;
     res.status = 200;
     res.content_type = "text/event-stream";
diff --git a/core/server/json_partial.cpp b/core/server/json_partial.cpp
index d4cdefda..4ffb934b 100644
--- a/core/server/json_partial.cpp
+++ b/core/server/json_partial.cpp
@@ -67,8 +67,8 @@ struct Scanner {
     }
 
     bool value(int depth) {
-        /* A hard depth cap, because the input is model output and a runaway "[[[[[..." would
-         * otherwise recurse until the stack ends. 256 is far past any real tool schema. */
+        /* Depth cap: the input is model output, and a runaway "[[[[..." would otherwise recurse
+         * until the stack overflows. 256 is far past any real tool schema. */
         if (depth > 256) return false;
         ws();
         if (eof()) return false;
@@ -159,9 +159,8 @@ size_t json_stable_prefix(std::string_view s) {
     while (bs < n && s[n - 1 - bs] == '\\') ++bs;
     if (bs % 2 == 1) return n - 1;
 
-    /* Back out of an unfinished "\uXXXX". `k` is how many characters have arrived after the 'u',
-     * so the escape is complete at k == 4 and short before it. Only six bytes ever need looking
-     * at, which is why this is a loop and not a parser. */
+    /* Back out of an unfinished "\uXXXX". `k` counts the characters after the 'u'; the escape is
+     * complete at k == 4. At most six bytes are examined. */
     for (size_t k = 0; k <= 4 && n >= k + 2; ++k) {
         if (s[n - 1 - k] != 'u') continue;
         if (s[n - 2 - k] != '\\') break;
@@ -185,8 +184,8 @@ bool json_quote_append(std::string& out, std::string_view s) {
     while (p < e) {
         const unsigned char c = *p;
         if (c >= 0x80) {
-            /* Length, and the range the SECOND byte is restricted to, which is what rejects
-             * overlong forms, surrogates and anything past U+10FFFF without decoding. */
+            /* Sequence length and the allowed range of the second byte, which rejects overlong
+             * forms, surrogates and code points past U+10FFFF without decoding. */
             size_t len;
             unsigned char lo = 0x80, hi = 0xBF;
             if (c >= 0xC2 && c <= 0xDF)      len = 2;
diff --git a/core/server/json_partial.h b/core/server/json_partial.h
index cdfcbdbe..75be5081 100644
--- a/core/server/json_partial.h
+++ b/core/server/json_partial.h
@@ -1,21 +1,15 @@
-/* core/server/json_partial.h -- what may be sent, and what may be called a tool call.
+/* core/server/json_partial.h -- scanning JSON text that is still arriving.
  *
- * Two questions about text that is still arriving, and they are different questions:
+ *   json_complete       Is this a tool call? A call is reported as `finish_reason:
+ *                       "tool_calls"` only if its arguments parse whole; a malformed call is
+ *                       returned as ordinary content, so a tool is never called with truncated
+ *                       arguments.
+ *   json_stable_prefix  How much may be streamed now? A fragment is JSON-encoded into the SSE
+ *                       payload, so it must end on a UTF-8 boundary; a split code point corrupts
+ *                       this delta and the next.
+ *   json_quote_append   Writes a string literal exactly as nlohmann does, for delta chunks.
  *
- *   1. "Is this a tool call?"  -- answered by `json_complete`. Nothing is ever reported to a
- *      client as `finish_reason: "tool_calls"` unless the arguments parse whole. A malformed call
- *      is returned as ordinary content, because a client that gets a truncated arguments object
- *      and is told it is a tool call will call the tool with the wrong arguments.
- *
- *   2. "How much of it can I put on the wire right now?" -- answered by `json_stable_prefix`.
- *      A streamed fragment is itself JSON-encoded into the SSE payload, so it must end on a UTF-8
- *      boundary: cutting a multi-byte code point in half turns one delta into mojibake and the
- *      next into a decode error.
- *
- * And one way to write it: `json_quote_append`, a string literal exactly as nlohmann writes one,
- * for the chunks that carry a delta.
- *
- * This is a scanner, not a parser: it allocates nothing and builds no DOM.
+ * A scanner, not a parser: it allocates nothing and builds no DOM.
  */
 #pragma once
 
@@ -29,25 +23,24 @@ namespace server {
 /* Does `s` parse as exactly one complete JSON value, with only whitespace after it? */
 bool json_complete(std::string_view s);
 
-/* Largest n <= s.size() such that s[0,n) ends on a UTF-8 code point boundary. Bytes that are not
- * valid UTF-8 at all are left alone -- this backs out of a truncation, it does not validate. */
+/* Largest n <= s.size() such that s[0,n) ends on a UTF-8 code point boundary. Invalid UTF-8 is
+ * left alone: this backs out of a truncation, it does not validate. */
 size_t utf8_trunc(std::string_view s);
 
-/* Largest prefix of `s` that is safe to emit as one streaming fragment: a UTF-8 boundary, and not
- * in the middle of a "\uXXXX" escape or on a lone trailing backslash. The escape rule buys
- * nothing for a client that only concatenates, and costs four bytes of latency; it is here
- * because a client that pretty-prints each delta is a client that would otherwise print a broken
- * escape, and the class of bug that produces is unbisectable from the server side. */
+/* Largest prefix of `s` that is safe to emit as one streaming fragment: on a UTF-8 boundary, not
+ * inside a "\uXXXX" escape and not on a lone trailing backslash. The escape rule costs up to four
+ * bytes of latency; it keeps a client that renders each delta separately from seeing a broken
+ * escape. */
 size_t json_stable_prefix(std::string_view s);
 
 /* Append `s` to `out` as a JSON string literal, quotes included, byte for byte as nlohmann's
- * dump() writes one: `\b \t \n \f \r \" \\` as two characters, every other control character
- * as `\u00xx` in lowercase hex, and everything else -- DEL and non-ASCII included -- as itself.
- * Returns false, with `out` as it was, when `s` is not well-formed UTF-8 (overlong forms,
- * surrogates and code points past U+10FFFF included), which nlohmann refuses rather than writes.
+ * dump() writes one: `\b \t \n \f \r \" \\` as two characters, other control characters as
+ * `\u00xx` in lowercase hex, everything else (DEL and non-ASCII included) as itself. Returns
+ * false with `out` unchanged when `s` is not well-formed UTF-8 (including overlong forms,
+ * surrogates and code points past U+10FFFF), which nlohmann refuses.
  *
- * A streamed chunk is written with this around a fixed frame instead of through a DOM: building
- * and dumping a tree per token cost more than every other part of the token's host work. */
+ * Streamed chunks use this around a fixed frame: building and dumping a DOM per token cost more
+ * than the rest of the token's host work. */
 bool json_quote_append(std::string& out, std::string_view s);
 
 }  /* namespace server */
diff --git a/core/server/liveview.cpp b/core/server/liveview.cpp
index f10c53be..4cfb13fd 100644
--- a/core/server/liveview.cpp
+++ b/core/server/liveview.cpp
@@ -26,9 +26,8 @@ void snapshot_from(const SchedMetrics& m, LiveSnapshot* out) {
     out->draft_acceptance = m.draft_acceptance;
     out->total_requests = m.total_requests;
     out->preemptions = m.preemptions;
-    /* The step counter is the one field a stalled loop moves and everything else does not:
-     * throughput decays toward zero on its own, but a step count frozen between two draws says
-     * the loop itself stopped. It comes from the same metrics as the rest. */
+    /* Throughput decays toward zero on its own; a step count frozen between two draws is what
+     * shows the loop itself stopped. */
     out->step = m.steps;
 }
 
@@ -36,9 +35,8 @@ void snapshot_from(const SchedMetrics& m, LiveSnapshot* out) {
 
 namespace {
 
-/* Tier -> colour. The order matches rad::Tier: VRAM, HostPinned, HostPageable, SSD, Mapped. Green is
- * resident and fast, red is on a disk; the gradient is the point, so a glance at the plane says
- * how much of the model is where without reading a number. */
+/* Tier -> colour, in rad::Tier order: VRAM, HostPinned, HostPageable, SSD, Mapped. Green is
+ * resident, red is on disk, so the plane shows at a glance where the model lives. */
 const char* tier_colour(uint8_t t) {
     switch (t) {
         case 0: return "\033[32m";   /* VRAM */
@@ -48,6 +46,13 @@ const char* tier_colour(uint8_t t) {
         default: return "\033[31m";  /* SSD */
     }
 }
+/* Tier names, in rad::Tier order. */
+const char* const kTierNames[kLiveTiers] = {"vram", "pinned", "host", "ssd", "mapped"};
+
+/* How slow a tier is to read, in rad::Tier order, for a column's worst tier: SSD is the slowest,
+ * so it outranks the mapping though it comes first in the enum. */
+const uint8_t kTierRank[kLiveTiers] = {0, 1, 2, 4, 3};
+
 char tier_glyph(uint8_t t) {
     switch (t) {
         case 0: return '#';
@@ -81,8 +86,8 @@ std::string f2(double v) {
     return b;
 }
 
-/* Tokens a second, never scaled by a prefix: rates are read against each other digit by digit,
- * and 6.12k beside 5.98k hides the difference 6116 beside 5979 shows. */
+/* Tokens per second, never SI-scaled: rates are compared digit by digit, and 6.12k beside 5.98k
+ * hides what 6116 beside 5979 shows. */
 std::string tps(double v) {
     char b[32];
     snprintf(b, sizeof b, v >= 99.95 ? "%.0f" : "%.1f", v);
@@ -91,14 +96,13 @@ std::string tps(double v) {
 
 /* ---- the terminal form's figures.
  *
- * THE WEB PAGE'S RULES (dashboard.cpp), so the two views of one snapshot print one figure. Three
- * significant figures and at most two decimals, ROUNDED BEFORE THE UNIT IS CHOSEN -- choosing the
- * unit first prints 1023.7 MiB as "1024 MiB". Sizes in binary units, because the card and every
- * --*-mib flag count in them. Counters exact and grouped in threes by a narrow space past four
- * digits, as SI writes them. A share never rounds onto 0% or 100%.
+ * Same rules as the web page (dashboard.cpp), so both views print the same figure. Three
+ * significant figures and at most two decimals, rounded before the unit is chosen (otherwise
+ * 1023.7 MiB prints as "1024 MiB"). Sizes in binary units, as the card and every --*-mib flag
+ * count. Counters exact, grouped in threes by a narrow space past four digits, as SI writes them.
+ * A share never rounds onto 0% or 100%.
  *
- * The piped form above keeps its own formatting: it is parsed as well as read, and its keys and
- * value shapes are what a log consumer already matches. */
+ * The piped form keeps its own formatting, since log consumers parse its keys and value shapes. */
 
 /* The digits of 0 <= a < 999.5; the thresholds are where the rounded value gains a digit. */
 std::string sig3(double a) {
@@ -108,7 +112,7 @@ std::string sig3(double a) {
 }
 
 /* A value on a unit ladder: steps up while the value would round to four digits. `exact` prints
- * the first rung as a whole number -- "5.00 B" is a precision that does not exist. */
+ * the first rung as a whole number (no "5.00 B"). */
 std::string ladder(double v, double base, const char* const* units, int n_units, bool exact,
                    const char* sep) {
     if (!std::isfinite(v)) return "-";
@@ -141,8 +145,8 @@ std::string size_of(int64_t used, int64_t total) {
     return a + " / " + b;
 }
 
-/* A continuous quantity -- watts, degrees -- to three figures and an SI prefix. Not tokens a
- * second: tps() prints those whole. */
+/* A continuous quantity (watts, degrees) to three figures and an SI prefix. Not for tokens per
+ * second, which tps() prints whole. */
 std::string num_si(double v) { return ladder(v, 1000.0, kPfx, 6, false, ""); }
 
 /* A counter, exact, grouped in threes by U+202F past four digits. */
@@ -155,7 +159,8 @@ std::string grouped(int64_t n) {
     return n < 0 ? "-" + o : o;
 }
 
-/* A share of one to one decimal. Only exactly 0 reads 0 and only exactly 1 reads 100. */
+/* A fraction as a percentage to one decimal. Only exactly 0 reads 0 and only exactly 1 reads
+ * 100. */
 std::string share(double f) {
     if (!std::isfinite(f)) return "-";
     char b[32];
@@ -210,8 +215,8 @@ void LiveView::loop() {
 
 /* ------------------------------------------------------------------ the piped form
  *
- * One ordinary line per interval, key=value, no escape sequences, no cursor movement. This is
- * what a log file or a `| tee` gets, and it is greppable and diffable by construction.
+ * One line per interval, key=value, no escape sequences or cursor movement, so a log file or a
+ * `| tee` stays greppable and diffable.
  */
 std::string LiveView::render_line(const LiveSnapshot& s) const {
     std::string o = "live";
@@ -235,20 +240,17 @@ std::string LiveView::render_line(const LiveSnapshot& s) const {
     }
 
     if (s.experts.n_units > 0) {
-        /* THE SNAPSHOT'S OWN TALLY, not a second walk of the plane. Walking it would count CELLS,
-         * which is not the same as counting UNITS: the plane is a rectangle and a model need not
-         * fill it -- a draft head carrying fewer experts than the trunk leaves empty cells, and
-         * those cells would be charged to whatever tier their row was initialised at. The engine
-         * counts the units it actually placed (liveview.h) and both renderers read that. */
-        o += " experts vram=" + std::to_string(s.experts.units[0]);
-        o += " pinned=" + std::to_string(s.experts.units[1]);
-        o += " host=" + std::to_string(s.experts.units[2]);
-        o += " ssd=" + std::to_string(s.experts.units[3]);
+        /* The snapshot's own unit tally, not a walk of the plane. The plane is a rectangle a
+         * model need not fill (a draft head with fewer experts than the trunk leaves empty
+         * cells), so counting cells would charge empty ones to some tier. */
+        o += " experts";
+        for (int t = 0; t < kLiveTiers; ++t)
+            o += std::string(" ") + kTierNames[t] + "=" + std::to_string(s.experts.units[t]);
         o += " resident=" + f2(s.experts.n_units
                                    ? 100.0 * (double)s.experts.units[0] / (double)s.experts.n_units
                                    : 0.0) + "%";
-        /* THE HIT RATE, which residency does not imply: a plan holding most of the units still
-         * misses on most tokens if the hot ones are the ones outside. */
+        /* Hit rate, which residency does not imply: a plan holding most units still misses on
+         * most tokens if the hot ones are outside. */
         if (s.experts.routed > 0)
             o += " hit=" + f2(100.0 * (double)s.experts.routed_resident /
                               (double)s.experts.routed) + "%";
@@ -258,10 +260,8 @@ std::string LiveView::render_line(const LiveSnapshot& s) const {
             o += " readmit=" + std::to_string(s.experts.readmits);
         }
     }
-    /* THE LINK, and the THREE things sharing it: the collective, the mover, and the MoE GEMM
-     * reading an expert that was not resident. Cumulative, so a `| tee` of this line is a time
-     * series a reader can difference -- which is the only form that says which of them is
-     * filling the bus. */
+    /* Link traffic by consumer (collective, mover, MoE GEMM streaming), cumulative so a `| tee`
+     * of these lines can be differenced into rates. */
     if (s.link.present &&
         (s.link.ar_bytes || s.link.h2d_bytes || s.link.d2h_bytes || s.link.stream_bytes)) {
         o += " link ar=" + std::to_string(s.link.ar_bytes);
@@ -308,10 +308,8 @@ std::string LiveView::render_screen(const LiveSnapshot& s) const {
     o += "\n";
     o += "  kv      [" + bar(s.kv_util, std::max(10, W / 4), true) + "] " +
          share(s.kv_util) + "   prefix hit " + share(s.prefix_hit_rate);
-    /* THE NUMBER THAT PREDICTS THE CLIFF, beside the one that reports it afterwards. Past
-     * ~75% kv the cache starts dropping prefixes the next turn wants and an agent's turn goes
-     * from seconds to minutes; the hit rate only falls once that has already happened. Shown
-     * only when non-zero -- a cache that has never evicted has nothing to say. */
+    /* Evictions predict a prefix-cache collapse that the hit rate reports only afterwards: past
+     * ~75% kv the cache drops prefixes the next turn wants. Shown only when non-zero. */
     if (s.prefix_evictions) o += "   evicted " + grouped(s.prefix_evictions);
     o += "\n";
     o += "  prefill " + tps(s.prefill_tps) + " tok/s    decode " + tps(s.decode_tps) + " tok/s";
@@ -322,16 +320,14 @@ std::string LiveView::render_screen(const LiveSnapshot& s) const {
     if (s.experts.n_layers > 0 && s.experts.n_experts > 0) {
         o += "\n  experts by tier  " + grouped(s.experts.n_units) + " units  " +
              size_iec(s.experts.total_bytes) + "\n  ";
-        /* RESIDENCY, ABSOLUTE AND PROPORTIONAL, so it can be read off the legend rather than by
-         * counting glyphs in the plane. Units and their share, plus the bytes -- a tier's unit
-         * count and its byte share are not the same ratio, because the tiers hold different
-         * weight classes. */
+        /* Residency per tier in the legend: units, their share, and bytes. Unit share and byte
+         * share differ because the tiers hold different weight classes. */
         char tl[192];
-        for (int t = 0; t < 4; ++t) {
+        for (int t = 0; t < kLiveTiers; ++t) {
             if (!s.experts.units[t]) continue;
             snprintf(tl, sizeof tl, "%s%c %-6s\033[0m %s  %s  %s   ",
                      tier_colour((uint8_t)t), tier_glyph((uint8_t)t),
-                     t == 0 ? "vram" : t == 1 ? "pinned" : t == 2 ? "host" : "ssd",
+                     kTierNames[t],
                      grouped(s.experts.units[t]).c_str(),
                      share((double)s.experts.units[t] / (double)s.experts.n_units).c_str(),
                      size_iec(s.experts.bytes[t]).c_str());
@@ -339,10 +335,9 @@ std::string LiveView::render_screen(const LiveSnapshot& s) const {
         }
         o += "\n";
 
-        /* The plane is usually wider than the terminal (128 experts x 48 layers is normal), so it
-         * is downsampled by taking the worst tier in each column group. Worst, not average: the
-         * question the plane answers is "what is going to be slow", and one SSD expert in a group
-         * of four is what makes that group slow. */
+        /* The plane is usually wider than the terminal (128 experts x 48 layers is typical), so
+         * each column group shows its worst tier, not the average: one SSD expert makes the
+         * group slow. */
         const int avail = W - 8;
         const int stride = std::max(1, (s.experts.n_experts + avail - 1) / std::max(1, avail));
         for (int l = 0; l < s.experts.n_layers; ++l) {
@@ -353,7 +348,9 @@ std::string LiveView::render_screen(const LiveSnapshot& s) const {
                 uint8_t worst = 0;
                 for (int k = 0; k < stride && e + k < s.experts.n_experts; ++k) {
                     size_t idx = (size_t)l * s.experts.n_experts + e + k;
-                    if (idx < s.experts.tier.size()) worst = std::max(worst, s.experts.tier[idx]);
+                    if (idx >= s.experts.tier.size()) continue;
+                    const uint8_t t = s.experts.tier[idx];
+                    if (t < kLiveTiers && kTierRank[t] > kTierRank[worst]) worst = t;
                 }
                 o += tier_colour(worst);
                 o += tier_glyph(worst);
diff --git a/core/server/liveview.h b/core/server/liveview.h
index 496364de..9469df7c 100644
--- a/core/server/liveview.h
+++ b/core/server/liveview.h
@@ -1,16 +1,14 @@
 /* core/server/liveview.h -- the live view (spec §16).
  *
  * Per-card utilisation and VRAM, throughput, draft acceptance, and the expert plane coloured by
- * tier. It is a terminal view and nothing else: no web page, no port, no JSON.
+ * tier. A terminal view only: no web page, no port, no JSON.
  *
- * The rule that shapes the implementation is the last sentence of §16 -- piped or redirected it
- * prints ordinary lines instead. So there are two renderers, chosen once by isatty(), and the
- * non-interactive one emits no escape sequence at all. A log file full of cursor-home sequences
- * is a log file you cannot grep, and the failure is silent: it looks fine on the terminal where
- * it was written.
+ * Piped or redirected, it prints ordinary lines instead (spec §16). There are two renderers,
+ * chosen once by isatty(), and the non-interactive one emits no escape sequences, so a log file
+ * stays greppable.
  *
- * The view owns no data. A snapshot function supplied by the engine fills a LiveSnapshot; this
- * component only draws it, which keeps the server free of any device dependency.
+ * The view owns no data: an engine-supplied snapshot function fills a LiveSnapshot and this only
+ * draws it, which keeps the server free of any device dependency.
  */
 #pragma once
 
@@ -37,55 +35,50 @@ struct CardStat {
     double      temp_c = 0.0;      /* 0 = not sampled */
 };
 
-/* rad::kTierCount, restated. This header deliberately does not include the program description --
- * a tier arrives here as a byte -- so the size is written out and liveview.cpp static_asserts the
- * two against each other. A fifth tier that fits in four slots is an out-of-bounds write that
- * costs nothing until it costs everything. */
+/* rad::kTierCount, restated so this header need not include the program description (a tier
+ * arrives here as a byte). liveview.cpp static_asserts that the two agree, since the per-tier
+ * arrays below are indexed by tier. */
 enum { kLiveTiers = 5 };
 
-/* THE EXPERT PLANE, and what the placement engine has been doing to it.
+/* The expert plane and the placement engine's activity on it.
  *
- * The plane itself -- one cell per (layer, expert), valued by rad::Tier -- is the picture. The
- * counters beside it are the things the picture cannot say. Residency per tier says how much of
- * the model is actually in VRAM; the per-layer counts say whether that residency is SPREAD, since
- * a fill that walks the model in order can starve the last layers and the draft head while the
- * global count still looks healthy; and the move counters say whether the traffic on the link is
- * the engine discovering a working set or re-admitting what it just evicted.
+ * The plane is one cell per (layer, expert), valued by rad::Tier. The counters say what the
+ * picture cannot: residency per tier (how much of the model is in VRAM), per-layer counts
+ * (whether residency is spread, since an in-order fill can starve the last layers and the draft
+ * head while the global count looks healthy), and moves (whether link traffic is the engine
+ * finding a working set or re-admitting what it just evicted).
  *
- * Counted ONCE, here, rather than by each renderer: the terminal view and the web page are two
- * drawings of the same snapshot and two independent tallies are two chances to disagree.
+ * Counted once, here, so the terminal view and the web page draw the same tallies.
  */
 struct ExpertPlane {
     int                  n_layers = 0;
     int                  n_experts = 0;
     std::vector tier;     /* row-major, size n_layers * n_experts */
 
-    /* Residency, by rad::Tier. Sized by kTierCount and not by 4: folding an unknown tier into the
-     * SSD bucket would report a weight as on disk when it is not. `bytes` is this rank's shard,
-     * which is the number that has to add up against the VRAM bar beside it. */
+    /* Residency by rad::Tier, sized by the tier count so an unknown tier is never folded into the
+     * SSD bucket. `bytes` is this rank's shard, which is what must add up against the VRAM bar. */
     int64_t units[kLiveTiers] = {0};
     int64_t bytes[kLiveTiers] = {0};
-    int64_t n_units = 0;           /* expert units in the plan; NOT n_layers * n_experts, which
+    int64_t n_units = 0;           /* expert units in the plan; not n_layers * n_experts, which
                                     * counts cells a ragged model never had */
     int64_t total_bytes = 0;
     int64_t movable = 0;           /* how many of them the heat engine is allowed to relocate */
 
-    /* Per layer, so a starved layer is visible as a number and not only as a dark band. */
+    /* Per layer, so a starved layer shows as a number, not only as a dark band. */
     std::vector layer_units;
     std::vector layer_resident;
 
-    /* What the mover did. Cumulative since start: a rate over a poll interval is the reader's
-     * subtraction, and a counter is the only form that survives being read twice. */
+    /* Mover activity, cumulative since start; readers take rates by subtracting two polls. */
     int64_t promotions = 0, demotions = 0;
-    /* Is the churn PROGRESS or THRASH? Same move count, opposite meanings -- see HeatStats. */
+    /* Separate progress from thrash at the same move count; see HeatStats. */
     int64_t distinct_promoted = 0, readmits = 0;
-    /* Why a dispatch moved nothing. `refused` is the guard declining, which is the healthy steady
-     * state; the starved counts are the mover having nowhere to put the bytes. */
+    /* Why a dispatch moved nothing. `refused` is the guard declining (the healthy steady state);
+     * the starved counts mean the mover had nowhere to put the bytes. */
     int64_t dispatches = 0, refused = 0, no_candidate = 0;
-    /* DID THE ROUTER FIND THE EXPERT IN VRAM. `routed` is expert selections seen by the heat
-     * engine and `routed_resident` the subset that was already there; the difference is what the
-     * MoE GEMM had to stream across the link, which LinkStat::stream_bytes prices. A residency
-     * percentage says how much of the model is close; this says how much of the WORK is. */
+    /* Whether the router found the expert in VRAM. `routed` counts expert selections seen by the
+     * heat engine, `routed_resident` the subset already resident; the difference was streamed
+     * across the link (priced by LinkStat::stream_bytes). This measures how much of the work, not
+     * of the model, is resident. */
     int64_t routed = 0, routed_resident = 0;
     int64_t no_record = 0, starved_slab = 0, starved_pool = 0, quarantined = 0;
     /* The prefill stager's copies (Mover::stage_units), rank 0: layers staged, units and bytes
@@ -93,26 +86,23 @@ struct ExpertPlane {
      * the units. */
     int64_t stage_layers = 0, staged_units = 0, staged_bytes = 0, stage_overflow = 0;
     int64_t stage_copies = 0;
-    /* HOW MUCH OF THE SLAB IS BORROWED. `flex_bytes` is what the slab holds in VRAM the KV cache
-     * lent it; `flex_capacity` is how much the cache is lending right now. The pair is what says
-     * whether the boundary between the two pools is moving, and whether what was lent is being
-     * used -- a gap between them is lent VRAM holding nothing. */
+    /* Slab VRAM borrowed from the KV cache: `flex_bytes` is what the slab holds in lent VRAM,
+     * `flex_capacity` what the cache lends right now. A gap between them is lent VRAM holding
+     * nothing. */
     int64_t flex_bytes = 0, flex_capacity = 0;
     bool    heat_enabled = false;  /* false = the plan is static and none of the above will move */
 };
 
-/* WHAT IS ON THE INTERCONNECT, and in what proportion.
+/* Interconnect traffic by consumer.
  *
- * Three things share it and they are never discussed together: the tensor-parallel all-reduce,
- * which is a property of the model's width and the batch; the expert mover's promotions and
- * demotions, which are a property of the placement policy; and the MoE GEMM streaming an expert
- * the router asked for and placement had not put in VRAM, which is what the policy is spending
- * the moves to avoid. All three are cumulative byte counts from the same wall clock, so a reader
- * who subtracts two polls gets rates that can be compared -- which is the whole question "is the
- * link busy because the model is wide, or because placement is thrashing".
+ * Three things share the link: the tensor-parallel all-reduce (set by model width and batch), the
+ * expert mover's promotions and demotions (set by placement policy), and the MoE GEMM streaming a
+ * routed expert that is not in VRAM (what the moves try to avoid). All are cumulative byte counts
+ * on one clock, so rates from two polls compare directly: is the link busy because the model is
+ * wide or because placement is thrashing?
  *
- * `ar_bytes` is the message payload summed over issues; Ctx::ar_bytes documents exactly what that
- * is and is not. `h2d`/`d2h` are the mover's own measured copy sizes.
+ * `ar_bytes` is the message payload summed over issues (see Ctx::ar_bytes). `h2d`/`d2h` are the
+ * mover's measured copy sizes.
  */
 struct LinkStat {
     bool    present = false;       /* false when nothing measured any of it */
@@ -120,19 +110,18 @@ struct LinkStat {
     int64_t ar_calls = 0, ar_bytes = 0;
     int64_t h2d_bytes = 0, d2h_bytes = 0;
     int64_t ssd_reads = 0, ssd_bytes = 0;
-    /* The MoE GEMM reading a routed expert that was not resident. Not a move and not a
-     * collective: the third consumer of the link, and the one a promotion is spent to remove. */
+    /* The MoE GEMM reading a routed expert that was not resident: the traffic promotions aim to
+     * remove. */
     int64_t stream_bytes = 0;
     int64_t prefetched = 0, prefetch_bytes = 0;
-    /* The prefill stager's copies of the next layer's pooled experts (core/place/stager.h). Part
-     * of `h2d_bytes`, like `prefetch_bytes`: the mover counts every copy it makes there, and a
-     * reader that wants the promotions alone takes both out. */
+    /* The prefill stager's copies of the next layer's pooled experts (core/place/stager.h).
+     * Included in `h2d_bytes`, like `prefetch_bytes`; subtract both for promotions alone. */
     int64_t staged_bytes = 0;
 };
 
-/* HOW THE RANKS RAN THEIR PASSES, summed over ranks: Ctx::PassCounts says what each is. A played
- * pass costs the host a packet copy; every other kind walks the architecture's issue path, so the
- * share that is not `played` is where a step's host time goes. */
+/* How the ranks ran their passes, summed over ranks (see Ctx::PassCounts). A played pass costs
+ * the host a packet copy; every other kind walks the architecture's issue path, so the non-played
+ * share is where a step's host time goes. */
 struct PassStat {
     bool    present = false;
     int64_t played = 0, recorded = 0, audited = 0;
@@ -143,8 +132,8 @@ struct PassStat {
 struct LiveSnapshot {
     int64_t     step = 0;
     std::string model;
-    /* Duplicated rather than referenced so that a snapshot is a value the drawing thread can hold
-     * without racing the scheduler that produced it. */
+    /* Copied, not referenced, so the drawing thread can hold a snapshot without racing the
+     * scheduler. */
     int64_t waiting = 0, running = 0, preempted = 0;
     double  kv_util = 0.0, prefix_hit_rate = 0.0;
     int64_t prefix_evictions = 0;
@@ -163,8 +152,8 @@ class LiveView {
 public:
     using Source = std::function;
 
-    /* `out` defaults to stdout. `interval_ms` is the redraw period; 250 ms is fast enough to see
-     * a stall and slow enough that the view costs nothing measurable. */
+    /* `out` defaults to stdout. `interval_ms` is the redraw period; 250 ms shows a stall and
+     * costs nothing measurable. */
     LiveView(Source src, int interval_ms = 250, FILE* out = nullptr);
     ~LiveView();
 
@@ -172,8 +161,7 @@ public:
     void stop();
 
 
-    /* Both renderers are public because they are the testable part: a snapshot in, a string out,
-     * no terminal involved. */
+    /* Public for tests: a snapshot in, a string out, no terminal involved. */
     std::string render_screen(const LiveSnapshot& s) const;
     std::string render_line(const LiveSnapshot& s) const;
 
diff --git a/core/server/metrics.cpp b/core/server/metrics.cpp
index 98408ff0..9fdcd15f 100644
--- a/core/server/metrics.cpp
+++ b/core/server/metrics.cpp
@@ -17,11 +17,16 @@ Histogram::Histogram(std::vector bounds) : bounds_(std::move(bounds)) {
 
 void Histogram::observe(double v) {
     if (!std::isfinite(v)) return;    /* a NaN latency is a bug upstream, not a data point */
-    /* Cumulative: every bucket whose bound is >= v counts this observation. Linear because the
-     * bucket lists are twenty-odd entries and a binary search plus a fixup loop is not faster. */
-    for (size_t i = 0; i < bounds_.size(); ++i)
-        if (v <= bounds_[i]) cnt_[i].fetch_add(1, std::memory_order_relaxed);
-    n_.fetch_add(1, std::memory_order_relaxed);
+    /* Cumulative: every bucket whose bound is >= v counts this observation. A linear scan, since
+     * the lists are twenty-odd entries.
+     *
+     * The count first, then the buckets widest first, each with release. A scrape reads the
+     * buckets narrowest first and the count last, with acquire, so an observation it sees in one
+     * bucket it also sees in every wider one and in the count: the buckets it renders never
+     * decrease and never exceed the count. */
+    n_.fetch_add(1, std::memory_order_release);
+    for (size_t i = bounds_.size(); i-- > 0 && v <= bounds_[i];)
+        cnt_[i].fetch_add(1, std::memory_order_release);
     double cur = sum_.load(std::memory_order_relaxed);
     while (!sum_.compare_exchange_weak(cur, cur + v, std::memory_order_relaxed)) {}
 }
@@ -41,8 +46,8 @@ std::vector buckets_latency() {
             30.0, 40.0, 50.0, 60.0, 120.0, 240.0, 480.0, 960.0, 1920.0, 7680.0};
 }
 
-/* vLLM's build_1_2_5_buckets: mantissas 1, 2, 5 at every decade, stopping at the first value past
- * max_value. A 32K-context model therefore gets 1..20000 and no more. */
+/* vLLM's build_1_2_5_buckets: mantissas 1, 2, 5 at every decade, up to max_value (a 32K-context
+ * model gets 1..20000). */
 std::vector buckets_1_2_5(int64_t max_value) {
     std::vector out;
     if (max_value < 1) max_value = 1;
@@ -106,9 +111,8 @@ void Metrics::observe_request(int64_t n_prompt, int64_t n_generated,
     if (max_tokens > 0) h_params_max_tokens_.observe((double)max_tokens);
 
     if (ttft_s >= 0.0) h_ttft_.observe(ttft_s);
-    /* TPOT is undefined for a one-token generation -- there is no inter-token interval to
-     * measure. Recording a zero there would drag every quantile down, so it is simply not an
-     * observation. */
+    /* TPOT is undefined for a one-token generation; recording a zero would drag every quantile
+     * down. */
     if (tpot_s >= 0.0 && n_generated > 1) h_tpot_.observe(tpot_s);
     if (e2e_s >= 0.0) h_e2e_.observe(e2e_s);
     if (decode_s >= 0.0 && n_generated > 1) h_decode_.observe(decode_s);
@@ -157,37 +161,38 @@ void Metrics::sample(const SchedMetrics& m) {
         draft_vdepth_top_.store(top, std::memory_order_release);
         draft_adapt_on_.store(true, std::memory_order_release);
     }
-    c_preemptions_.inc(std::max(0.0, (double)m.preemptions - c_preemptions_.get()));
-    c_steps_.inc(std::max(0.0, (double)m.steps - c_steps_.get()));
-    c_steps_prefill_.inc(std::max(0.0, (double)m.steps_prefill - c_steps_prefill_.get()));
-    c_steps_mixed_.inc(std::max(0.0, (double)m.steps_mixed - c_steps_mixed_.get()));
-    c_steps_decode_.inc(std::max(0.0, (double)m.steps_decode - c_steps_decode_.get()));
-    c_steps_ahead_.inc(std::max(0.0, (double)m.steps_ahead - c_steps_ahead_.get()));
-    c_prefill_capped_.inc(std::max(0.0, (double)m.prefill_chunks_capped - c_prefill_capped_.get()));
-    c_rows_unspec_.inc(std::max(0.0,
-        (double)m.decode_rows_unspeculated - c_rows_unspec_.get()));
-    c_step_secs_.inc(std::max(0.0, (double)m.step_ns * 1e-9 - c_step_secs_.get()));
-    c_step_secs_decode_.inc(std::max(0.0,
-        (double)m.step_ns_decode * 1e-9 - c_step_secs_decode_.get()));
-    c_prefill_tokens_.inc(std::max(0.0, (double)m.prefill_tokens - c_prefill_tokens_.get()));
-    c_decode_tokens_.inc(std::max(0.0, (double)m.decode_tokens - c_decode_tokens_.get()));
-    c_draft_tokens_.inc(std::max(0.0, (double)m.draft_tokens - c_draft_tokens_.get()));
-    c_draft_accepted_.inc(std::max(0.0, (double)m.draft_accepted - c_draft_accepted_.get()));
-    c_draft_refills_.inc(std::max(0.0, (double)m.draft_refills - c_draft_refills_.get()));
-    c_draft_refill_tokens_.inc(
-        std::max(0.0, (double)m.draft_refill_tokens - c_draft_refill_tokens_.get()));
-    c_attn_cached_.inc(std::max(0.0, (double)m.attn_cached_tokens - c_attn_cached_.get()));
-    c_linear_cached_.inc(std::max(0.0, (double)m.linear_cached_tokens - c_linear_cached_.get()));
-    c_checkpoints_.inc(std::max(0.0, (double)m.checkpoints_written - c_checkpoints_.get()));
-    /* The cache's own cumulative counts, so the delta is taken the same way the others are.
-     * A prefix cache that is evicting under steady load is one that cannot hold the working
-     * set, and the next turn of every session it drops re-prefills from scratch. */
-    c_prefix_evict_.inc(std::max(0.0, (double)m.prefix_evictions - c_prefix_evict_.get()));
-    c_prefix_ckpt_evict_.inc(std::max(0.0,
-        (double)m.prefix_ckpt_evictions - c_prefix_ckpt_evict_.get()));
-    c_prefix_expired_.inc(std::max(0.0, (double)m.prefix_expired - c_prefix_expired_.get()));
-    c_prefix_ckpt_expired_.inc(std::max(0.0,
-        (double)m.prefix_ckpt_expired - c_prefix_ckpt_expired_.get()));
+    c_preemptions_.advance_to(m.preemptions);
+    c_steps_.advance_to(m.steps);
+    c_steps_prefill_.advance_to(m.steps_prefill);
+    c_steps_mixed_.advance_to(m.steps_mixed);
+    c_steps_decode_.advance_to(m.steps_decode);
+    c_steps_ahead_.advance_to(m.steps_ahead);
+    c_prefill_capped_.advance_to(m.prefill_chunks_capped);
+    c_steps_held_.advance_to(m.steps_held);
+    c_rows_unspec_.advance_to(m.decode_rows_unspeculated);
+    c_step_secs_.advance_to((double)m.step_ns * 1e-9);
+    c_step_secs_decode_.advance_to((double)m.step_ns_decode * 1e-9);
+    c_prefill_tokens_.advance_to(m.prefill_tokens);
+    c_decode_tokens_.advance_to(m.decode_tokens);
+    c_draft_tokens_.advance_to(m.draft_tokens);
+    c_draft_accepted_.advance_to(m.draft_accepted);
+    c_draft_refills_.advance_to(m.draft_refills);
+    c_draft_refill_tokens_.advance_to(m.draft_refill_tokens);
+    c_attn_cached_.advance_to(m.attn_cached_tokens);
+    c_linear_cached_.advance_to(m.linear_cached_tokens);
+    c_checkpoints_.advance_to(m.checkpoints_written);
+    /* The cache's own cumulative counts, turned into deltas like the others. */
+    c_prefix_evict_.advance_to(m.prefix_evictions);
+    c_prefix_ckpt_evict_.advance_to(m.prefix_ckpt_evictions);
+    c_prefix_expired_.advance_to(m.prefix_expired);
+    c_prefix_ckpt_expired_.advance_to(m.prefix_ckpt_expired);
+    c_ckpt_retired_.advance_to(m.prefix_ckpt_retired);
+    c_ckpt_lru_.advance_to(m.prefix_ckpt_lru);
+    c_ckpt_refused_.advance_to(m.prefix_ckpt_refused);
+    c_cut_no_snapshot_.advance_to(m.hit_cut_no_snapshot);
+    c_cut_window_.advance_to(m.hit_cut_window);
+    c_cut_adopt_.advance_to(m.hit_cut_adopt);
+    c_cut_tokens_.advance_to(m.hit_cut_tokens);
     g_linear_hit_.set(m.linear_hit_rate);
 }
 
@@ -226,6 +231,8 @@ struct Writer {
         help(name, doc, "counter");
         out += name; out += labels; out += ' '; out += num(v); out += '\n';
     }
+    /* The buckets in ascending order, then the count once for both +Inf and _count, the order
+     * Histogram::observe makes consistent. */
     void hist(const char* name, const char* doc, const std::string& labels, const Histogram& h) {
         help(name, doc, "histogram");
         for (size_t i = 0; i < h.bounds().size(); ++i) {
@@ -234,13 +241,14 @@ struct Writer {
             out += ",le=\""; out += num(h.bounds()[i]); out += "\"} ";
             out += num((double)h.bucket(i)); out += '\n';
         }
+        const double n = (double)h.count();
         out += name; out += "_bucket";
         out += labels.substr(0, labels.size() - 1);
         out += ",le=\"+Inf\"} ";
-        out += num((double)h.count()); out += '\n';
+        out += num(n); out += '\n';
         out += name; out += "_sum"; out += labels; out += ' '; out += num(h.sum()); out += '\n';
         out += name; out += "_count"; out += labels; out += ' ';
-        out += num((double)h.count()); out += '\n';
+        out += num(n); out += '\n';
     }
 };
 
@@ -294,8 +302,7 @@ std::string Metrics::render() const {
            "Histogram of time to first token in seconds.", L, h_ttft_);
     w.hist("vllm:time_per_output_token_seconds",
            "Histogram of time per output token in seconds.", L, h_tpot_);
-    /* The name current vLLM uses for the same measurement. Same data, both spellings, so a
-     * dashboard written against either version works unchanged. */
+    /* Current vLLM's name for the same measurement; both spellings are emitted. */
     w.hist("vllm:inter_token_latency_seconds",
            "Histogram of inter-token latency in seconds.", L, h_tpot_);
     w.hist("vllm:e2e_request_latency_seconds",
@@ -312,8 +319,7 @@ std::string Metrics::render() const {
            "Histogram of the max_tokens request parameter.", L, h_params_max_tokens_);
 
     /* ---------------- radiance-specific ----------------
-     * Under our own prefix, never under vllm:. A dashboard that finds an unfamiliar vllm: name is
-     * a dashboard that has been lied to about which engine it is looking at. */
+     * Under our own prefix, never under vllm:. */
     w.gauge("radiance:prefill_tokens_per_second",
             "Prefill throughput over the scheduler's recent window.", L, g_prefill_tps_.get());
     w.gauge("radiance:decode_tokens_per_second",
@@ -322,10 +328,10 @@ std::string Metrics::render() const {
               "Scheduler steps executed. One forward pass of the model, plus whatever draft "
               "rounds followed it; with speculation a step emits more than one token.",
               L, c_steps_.get());
-    /* STEPS BY SHAPE, and how much of the decode ran unspeculated.
-     * `radiance:decode_rows_unspeculated_total` counts rows that took no draft for ANY reason --
-     * depth 0, a request that may not speculate, a drafter with nothing to propose. Its rate
-     * against engine_steps_total says how much of the decode speculation is not reaching. */
+    /* Steps by shape, and how much of the decode ran unspeculated.
+     * `radiance:decode_rows_unspeculated_total` counts rows that took no draft for any reason
+     * (depth 0, a request that may not speculate, a drafter with nothing to propose); its rate
+     * against engine_steps_total shows how much of the decode speculation misses. */
     w.counter("radiance:engine_steps_prefill_total",
               "Scheduler steps carrying only prefill chunks.", L, c_steps_prefill_.get());
     w.counter("radiance:engine_steps_mixed_total",
@@ -340,24 +346,24 @@ std::string Metrics::render() const {
               "Prefill chunks held back so decode rows and waiting requests got into the step "
               "(--busy-prefill-chunk).",
               L, c_prefill_capped_.get());
+    w.counter("radiance:engine_steps_held_total",
+              "Decode-only steps run after a prefill chunk while other sequences decode "
+              "(--prefill-interleave).", L, c_steps_held_.get());
     w.counter("radiance:decode_rows_unspeculated_total",
               "Decode rows that took no draft, for any reason.",
               L, c_rows_unspec_.get());
-    /* THE STEP TIME, AS A COUNTER AND NOT A RATE. Divide by engine_steps_decode_total for the
-     * milliseconds a decode step costs. Wall clock over a step count answers that only for a
-     * window that was saturated and carried no prefill, and says nothing when it was not. */
+    /* Step time as a counter. Divided by engine_steps_decode_total it gives the cost of a decode
+     * step; wall clock over a step count does so only for a saturated window with no prefill. */
     w.counter("radiance:engine_step_seconds_total",
               "Seconds spent inside a scheduler step, all shapes.", L, c_step_secs_.get());
     w.counter("radiance:engine_step_seconds_decode_total",
               "Seconds spent inside a scheduler step carrying only decode rows.",
               L, c_step_secs_decode_.get());
 
-    /* THE EXACT TOTALS, beside the rate gauges above rather than instead of them. A gauge is what
-     * a dashboard wants; a counter is what a comparison wants, because two runs that settled into
-     * different mixes of prefill and decode have incomparable rates and perfectly comparable
-     * totals. These are the only counters that answer it: vllm:generation_tokens_total is charged
-     * when a request FINISHES, and is therefore identically zero over a window in which nothing
-     * finishes. */
+    /* Exact totals beside the rate gauges. Two runs with different prefill/decode mixes have
+     * incomparable rates but comparable totals. vllm:generation_tokens_total is charged when a
+     * request finishes, so it reads zero over a window in which nothing finishes; these are
+     * charged per step. */
     w.counter("radiance:prefill_tokens_total",
               "Prompt tokens the engine has computed, exact.", L, c_prefill_tokens_.get());
     w.counter("radiance:decode_tokens_total",
@@ -375,11 +381,9 @@ std::string Metrics::render() const {
               "Cached prompt tokens those hits gave back to be recomputed.",
               L, c_draft_refill_tokens_.get());
 
-    /* PREFIX CACHING, DECOUPLED (spec §7.3). vllm:gpu_prefix_cache_hit_rate is the ATTENTION one,
-     * because that is what vLLM's single number has always meant. The linear side hits at a
-     * different granularity -- whole checkpoints, not blocks -- and averaging them would hide the
-     * effect the decoupling exists to expose. Without these a deployment cannot tell whether
-     * linear checkpointing is working at all. */
+    /* Decoupled prefix caching (spec §7.3). vllm:gpu_prefix_cache_hit_rate is the attention hit
+     * rate, as in vLLM. The linear side hits at a different granularity (whole checkpoints, not
+     * blocks), so it is reported separately rather than averaged in. */
     w.gauge("radiance:linear_prefix_cache_hit_rate",
             "Fraction of prompt tokens served from a linear-state checkpoint (spec 7.3).",
             L, g_linear_hit_.get());
@@ -389,10 +393,9 @@ std::string Metrics::render() const {
               "Prompt tokens served from a linear-state checkpoint.", L, c_linear_cached_.get());
     w.counter("radiance:linear_checkpoints_written_total",
               "Linear-state checkpoints written.", L, c_checkpoints_.get());
-    /* THE LEADING INDICATOR FOR A PREFIX-CACHE COLLAPSE. `gpu_prefix_cache_hit_rate` falls
-     * only after a reusable prefix is already gone; this rises as it is dropped. Above ~75%
-     * pool utilisation the cache starts evicting prefixes that the next turn wants, and an
-     * agent's turn-2 latency goes from seconds to minutes. */
+    /* Leading indicator of prefix-cache collapse: the hit rate falls only after a reusable prefix
+     * is gone, while evictions rise as it is dropped. Above ~75% pool utilisation the cache
+     * starts evicting prefixes the next turn wants. */
     w.counter("radiance:prefix_cache_evictions_total",
               "Prefix-cache entries evicted (attention blocks).", L, c_prefix_evict_.get());
     w.counter("radiance:prefix_cache_ckpt_evictions_total",
@@ -403,14 +406,44 @@ std::string Metrics::render() const {
     w.counter("radiance:prefix_cache_ckpt_expired_total",
               "Prefix-cache linear-state checkpoints taken out by --prefix-cache-ttl.", L,
               c_prefix_ckpt_expired_.get());
+    /* Why snapshots went, and why hits were cut: a hybrid server that re-prefills long prompts
+     * shows it here before the linear hit rate says so. */
+    {
+        const std::string base = L.substr(0, L.size() - 1);
+        auto labelled = [&](const char* name, const char* label, const char* value, double v) {
+            w.out += name; w.out += base; w.out += ','; w.out += label; w.out += "=\"";
+            w.out += value; w.out += "\"} "; w.out += num(v); w.out += '\n';
+        };
+        w.help("radiance:prefix_cache_ckpt_evictions_by_reason_total",
+               "Linear-state checkpoints evicted, by reason: released by --checkpoint-policy, or "
+               "the least recently used of a store retention left full.", "counter");
+        labelled("radiance:prefix_cache_ckpt_evictions_by_reason_total", "reason", "retention",
+                 c_ckpt_retired_.get());
+        labelled("radiance:prefix_cache_ckpt_evictions_by_reason_total", "reason", "store_full",
+                 c_ckpt_lru_.get());
+        w.counter("radiance:prefix_cache_ckpt_refused_total",
+                  "Checkpoints not written because every snapshot slot was in use by a restore "
+                  "in the same step.", L, c_ckpt_refused_.get());
+        w.help("radiance:prefix_hit_cuts_total",
+               "Admissions whose prefix hit reused nothing, by reason: no snapshot at or below "
+               "the hit, a windowed group no window snapshot covers, or blocks that could not be "
+               "adopted.", "counter");
+        labelled("radiance:prefix_hit_cuts_total", "reason", "no_snapshot",
+                 c_cut_no_snapshot_.get());
+        labelled("radiance:prefix_hit_cuts_total", "reason", "windowed_group", c_cut_window_.get());
+        labelled("radiance:prefix_hit_cuts_total", "reason", "adopt_failed", c_cut_adopt_.get());
+        w.counter("radiance:prefix_hit_cut_tokens_total",
+                  "Prompt tokens the attention cache held and admission computed again, because "
+                  "the hit resumed at a snapshot below it or reused nothing.", L,
+                  c_cut_tokens_.get());
+    }
     w.gauge("radiance:draft_acceptance_ratio",
-            "Fraction of speculative draft tokens accepted (spec 10).", L, g_draft_accept_.get());
-    /* CONDITIONAL, per draft position: of the verifies that reached position j -- every earlier
-     * one accepted -- the fraction that took j as well. The pooled ratio above cannot tell a
-     * drafter that decays from one whose later rounds are broken; these can, and the companion
-     * `_reached_total` says how much evidence each position carries. `_accepted_total` gives the
-     * same ratio over any window: at a fixed depth the next position's reach would do, but an
-     * adaptive window can end at j with j taken. */
+            "Fraction of speculative draft tokens accepted.", L, g_draft_accept_.get());
+    /* Conditional acceptance per draft position: of the verifies that reached position j (every
+     * earlier one accepted), the fraction that took j too. Unlike the pooled ratio, this tells a
+     * drafter that decays from one whose later rounds are broken. `_reached_total` is the evidence
+     * per position; `_accepted_total` gives the ratio over any window (an adaptive window can end
+     * at j with j taken, so the next position's reach is not enough). */
     const int seen = draft_pos_seen_.load(std::memory_order_acquire);
     if (seen > 0) {
         const std::string base = L.substr(0, L.size() - 1);
@@ -431,9 +464,8 @@ std::string Metrics::render() const {
             w.out += "radiance:draft_position_accepted_total" + base + ",position=\"" +
                      std::to_string(j) + "\"} " + num(g_draft_pos_accepted_[j].get()) + '\n';
     }
-    /* THE ADAPTIVE DRAFT WINDOW, only while --draft-window adaptive is in force: where the policy stands --
-     * at one sequence, that sequence's window -- and where it has been, as verifies by the
-     * number of drafts they carried. */
+    /* Adaptive draft window, only under --draft-window adaptive: the current mean window (at one
+     * sequence, that sequence's window) and its history as verifies by drafts carried. */
     if (draft_adapt_on_.load(std::memory_order_acquire)) {
         w.gauge("radiance:draft_depth_adaptive",
                 "Mean draft window the adaptive policy gives the running sequences.",
diff --git a/core/server/metrics.h b/core/server/metrics.h
index 5d276bbc..9387e59b 100644
--- a/core/server/metrics.h
+++ b/core/server/metrics.h
@@ -1,24 +1,20 @@
 /* core/server/metrics.h -- Prometheus /metrics, with vLLM's metric names.
  *
- * The names are not ours to choose. There is a published Grafana dashboard for vLLM and a great
- * deal of alerting built on `vllm:time_to_first_token_seconds_bucket` and friends, and the point
- * of matching them is that swapping vLLM for radiance behind an existing deployment changes
- * nothing on the observability side. So: the vLLM names, the vLLM bucket boundaries, and the
- * vLLM label set (`model_name`, `engine`), copied exactly. Where vLLM renamed something we emit
- * both spellings -- `vllm:gpu_cache_usage_perc` is what every dashboard in the wild queries and
- * `vllm:kv_cache_usage_perc` is what current vLLM emits, and two gauges cost nothing.
+ * Names, bucket boundaries and the label set (`model_name`, `engine`) are copied exactly from vLLM,
+ * so existing vLLM dashboards and alerts work unchanged against radiance. Where vLLM renamed a
+ * metric both spellings are emitted (`vllm:gpu_cache_usage_perc`, which dashboards query, and
+ * `vllm:kv_cache_usage_perc`, which current vLLM emits).
  *
- * Anything vLLM does not have goes under `radiance:`. Inventing a new `vllm:` name would be worse
- * than useless: it would look to a dashboard like a metric it knows and is not.
+ * Anything vLLM lacks goes under `radiance:`; a new `vllm:` name would pass for a metric a
+ * dashboard knows.
  *
- * What is deliberately NOT emitted is as important. `vllm:iteration_tokens_total` and
- * `vllm:request_queue_time_seconds` are properties of the scheduler's step loop, not of the HTTP
- * boundary, and the server cannot observe them. Emitting a plausible-looking approximation of a
- * latency breakdown is how a dashboard ends up lying, so they are absent until the scheduler
- * reports them, and their absence is documented rather than papered over.
+ * Not emitted: `vllm:iteration_tokens_total` and `vllm:request_queue_time_seconds`. They belong to
+ * the scheduler's step loop, which the HTTP boundary cannot observe, and an approximation would
+ * mislead. They stay absent until the scheduler reports them.
  */
 #pragma once
 
+#include 
 #include 
 #include 
 #include 
@@ -39,6 +35,8 @@ public:
         double cur = v_.load(std::memory_order_relaxed);
         while (!v_.compare_exchange_weak(cur, cur + v, std::memory_order_relaxed)) {}
     }
+    /* Raises the count to `total`, a cumulative value kept elsewhere; never lowers it. */
+    void advance_to(double total) { inc(std::max(0.0, total - get())); }
     double get() const { return v_.load(std::memory_order_relaxed); }
 private:
     std::atomic v_{0.0};
@@ -52,17 +50,18 @@ private:
     std::atomic v_{0.0};
 };
 
-/* Cumulative buckets, the Prometheus convention: bucket i counts observations <= bounds[i], and
- * the implicit +Inf bucket is `count`. Atomics rather than a lock because /metrics is scraped
- * from one thread while every HTTP thread observes into it. */
+/* Cumulative buckets, the Prometheus convention: bucket i counts observations <= bounds[i] and
+ * the implicit +Inf bucket is `count`. Atomic, since every HTTP thread observes while /metrics
+ * is scraped. */
 class Histogram {
 public:
     explicit Histogram(std::vector bounds);
     void observe(double v);
 
     const std::vector& bounds() const { return bounds_; }
-    uint64_t bucket(size_t i) const { return cnt_[i].load(std::memory_order_relaxed); }
-    uint64_t count() const { return n_.load(std::memory_order_relaxed); }
+    /* Read the buckets in ascending order, then the count, for a consistent picture (observe). */
+    uint64_t bucket(size_t i) const { return cnt_[i].load(std::memory_order_acquire); }
+    uint64_t count() const { return n_.load(std::memory_order_acquire); }
     double   sum() const { return sum_.load(std::memory_order_relaxed); }
 
 private:
@@ -72,8 +71,8 @@ private:
     std::atomic   sum_{0.0};
 };
 
-/* vLLM's bucket layouts, verbatim. Changing one of these silently invalidates every histogram
- * quantile a dashboard computes across a version boundary, so they are constants, not options. */
+/* vLLM's bucket layouts, verbatim. Changing one breaks every histogram quantile a dashboard
+ * computes across versions, so they are constants, not options. */
 std::vector buckets_ttft();          /* vllm:time_to_first_token_seconds */
 std::vector buckets_tpot();          /* vllm:time_per_output_token_seconds */
 std::vector buckets_latency();       /* every vllm:request_*_seconds */
@@ -81,8 +80,8 @@ std::vector buckets_1_2_5(int64_t max_value);   /* token-count histogram
 
 /* ------------------------------------------------------------------ the registry */
 
-/* The finish reasons `vllm:request_success_total` is broken down by. Fixed, because a label whose
- * cardinality depends on user input is a Prometheus outage waiting to happen. */
+/* The finish reasons `vllm:request_success_total` is broken down by. A fixed set, because label
+ * cardinality must never depend on user input. */
 enum class SuccessReason { Stop = 0, Length, ToolCalls, Abort, Error, N_ };
 
 class Metrics {
@@ -115,48 +114,42 @@ private:
     Gauge   g_kv_max_tokens_, g_kv_max_bytes_;
     Gauge   g_prefill_tps_, g_decode_tps_, g_draft_accept_, g_preempted_;
     Gauge   queue_depth_;
-    /* The per-position draft hazard, kept as plain gauges because that is what it is: a
-     * conditional acceptance rate at each draft position, which is the only number that separates
-     * a drafter that decays from one whose later rounds are broken. See core/sched/draft.h. */
+    /* Per-position conditional draft acceptance (see render() and core/sched/draft.h). */
     enum { MAX_DRAFT_POS = 64 };
     Gauge   g_draft_pos_[MAX_DRAFT_POS];
     Gauge   g_draft_pos_reached_[MAX_DRAFT_POS];
     Gauge   g_draft_pos_accepted_[MAX_DRAFT_POS];
     std::atomic draft_pos_seen_{0};
-    /* THE ADAPTIVE DRAFT WINDOW (--draft-window adaptive): the mean window of the running sequences,
-     * and the verifies by the window they carried, index = drafts. Rendered only while the policy
-     * is on, so a deployment without it exposes exactly what it always did. */
+    /* Adaptive draft window (--draft-window adaptive): the running sequences' mean window, and
+     * verifies by the window they carried (index = drafts). Rendered only while the policy is on. */
     Gauge   g_draft_depth_adapt_;
     Gauge   g_draft_vdepth_[MAX_DRAFT_POS + 1];
     std::atomic draft_adapt_on_{false};
     std::atomic  draft_vdepth_top_{0};   /* the deepest window with a verify counted */
 
-    /* sample() turns the scheduler's cumulative totals into counter increments by reading each
-     * counter and adding the difference. Two scrapes doing that at once both read the old value
-     * and both add the whole difference, so they are serialised. */
+    /* sample() turns the scheduler's cumulative totals into counter increments (read, add the
+     * difference). Concurrent scrapes would both add the same difference, so they are serialised. */
     std::mutex sample_mu_;
 
     Counter c_prompt_tokens_, c_generation_tokens_, c_preemptions_;
-    /* ENGINE STEPS. Tokens a second cannot answer "how long is a step", and with speculation the
-     * two stop being the same question: a step emits 1 + however many drafts survived. Exposed as
-     * a counter so two scrapes and a clock give the step time directly. */
+    /* Engine steps. With speculation a step emits 1 + the accepted drafts, so tokens/s does not
+     * give step time; two scrapes of this counter and a clock do. */
     Counter c_steps_;
-    /* STEPS BY SHAPE, and the decode rows a mixed step cost speculation. Exposed as counters so
-     * two scrapes give the rate over a window rather than a number dominated by startup. */
+    /* Steps by shape, and decode rows that ran unspeculated. Counters, so two scrapes give the
+     * rate over a window rather than an average dominated by startup. */
     Counter c_steps_prefill_, c_steps_mixed_, c_steps_decode_, c_rows_unspec_, c_steps_ahead_;
-    Counter c_prefill_capped_;
-    /* SECONDS SPENT INSIDE A STEP, and the decode half of it. A step time is not wall clock over
-     * a step count -- SchedMetrics::step_ns says why -- and without these every scraper has to
-     * assume a saturated window and no prefill in it. */
+    Counter c_prefill_capped_, c_steps_held_;
+    /* Seconds inside a step, all shapes and decode-only. Wall clock over a step count is not a
+     * step time (see SchedMetrics::step_ns). */
     Counter c_step_secs_, c_step_secs_decode_;
-    /* THE EXACT TOTALS BEHIND THE RATE GAUGES. A gauge answers "how fast right now"; a counter
-     * answers "how much between these two scrapes", and only the second survives a comparison
-     * between two runs that settled into different mixes. */
+    /* Exact totals behind the rate gauges; see render(). */
     Counter c_prefill_tokens_, c_decode_tokens_, c_draft_tokens_, c_draft_accepted_;
     Counter c_draft_refills_, c_draft_refill_tokens_;
     Counter c_attn_cached_, c_linear_cached_, c_checkpoints_;
     Counter c_prefix_evict_, c_prefix_ckpt_evict_;
     Counter c_prefix_expired_, c_prefix_ckpt_expired_;
+    Counter c_ckpt_retired_, c_ckpt_lru_, c_ckpt_refused_;
+    Counter c_cut_no_snapshot_, c_cut_window_, c_cut_adopt_, c_cut_tokens_;
     Gauge   g_linear_hit_;
     Counter c_success_[(size_t)SuccessReason::N_];
     Counter c_rejected_, c_disconnect_, c_overflow_;
diff --git a/core/server/oai.cpp b/core/server/oai.cpp
index b71d3a26..fde2682e 100644
--- a/core/server/oai.cpp
+++ b/core/server/oai.cpp
@@ -1,4 +1,5 @@
 #include "oai.h"
+#include "http.h"
 #include "json_partial.h"
 #include "rad_internal.h"
 #include "mm/processor.h"
@@ -12,6 +13,7 @@
 #include 
 #include 
 #include 
+#include 
 
 namespace rad {
 namespace server {
@@ -60,9 +62,8 @@ std::string base64_encode(const void* data, size_t len) {
 }
 
 bool base64_decode(const std::string& in, std::vector* out) {
-    /* One table lookup a character: 0..63 a digit, -2 padding or whitespace (skipped wherever it
-     * stands), -1 anything else. A media part is megabytes of this, and a branch ladder a
-     * character decoded a 30 s clip at about 120 MB/s. */
+    /* One table lookup per character: 0..63 a digit, -2 padding or whitespace (skipped anywhere),
+     * -1 invalid. Media parts are megabytes, so a per-character branch ladder is too slow. */
     static const auto kVal = [] {
         std::array t{};
         t.fill(-1);
@@ -80,7 +81,7 @@ bool base64_decode(const std::string& in, std::vector* out) {
     uint32_t acc = 0;
     int bits = 0;
     while (p < end) {
-        /* Four digits at once while they are four digits: the body of any real payload. */
+        /* Fast path: four valid digits at once. */
         if (bits == 0 && end - p >= 4) {
             const int a = kVal[p[0]], b = kVal[p[1]], c = kVal[p[2]], d = kVal[p[3]];
             if ((a | b | c | d) >= 0) {
@@ -105,34 +106,28 @@ bool base64_decode(const std::string& in, std::vector* out) {
     return true;
 }
 
-/* THE PARSED TREE IS BOUNDED, NOT ONLY THE BODY. A JSON value costs the tree a 16-byte node plus
- * its container's growth slack however few bytes it took on the wire, so `[1,1,1,...]` grows
- * about eightfold in parsing, and a body at the transport's size limit becomes gigabytes before
- * a single field has been read -- let alone a prompt checked against the context. Nothing a
- * request can legitimately carry needs many values per token of context: a token-id prompt is
- * one per token and must fit the context, and everything else (messages, tools, schemas, stop
- * strings) is small beside it. So past a budget scaled from the context the parse stops keeping
- * values, and the request is refused having cost a bounded tree. */
+/* The parsed tree is bounded, not only the body. Each JSON value costs a 16-byte node plus
+ * container slack however short its text, so `[1,1,1,...]` grows about eightfold and a body at
+ * the transport limit could become gigabytes before any field is checked. A legitimate request
+ * needs few values per context token (a token-id prompt is one per token; everything else is
+ * small), so past a budget scaled from the context the parse keeps nothing and is refused. */
 int64_t json_value_budget(int64_t max_ctx) {
     const int64_t kFloor = 1 << 20;        /* what a request needs with no context to scale by */
     const int64_t kPerToken = 16;          /* a batch of up to this many full-context prompts */
     return kFloor + kPerToken * std::max(max_ctx, 0);
 }
 
-/* AND ITS DEPTH IS BOUNDED, because the parser is the only thing here that walks a tree without
- * recursing. Serialising one (`dump`) and destroying a copy made field by field both recurse once
- * a level, and a request's schema is serialised on the way to its grammar -- so a body of a few
- * hundred kilobytes of brackets, well inside the value budget, would overflow the worker's stack.
- * Nothing a request carries nests anywhere near the bound: a schema deep enough to matter is
- * refused by the grammar compiler at half of it. */
+/* Depth is bounded too: the parser does not recurse, but `dump` and destroying a field-by-field
+ * copy recurse once per level, and a request's schema is serialised on the way to its grammar.
+ * A few hundred KB of brackets, well inside the value budget, would overflow the worker's stack.
+ * No legitimate request nests near it; the grammar compiler refuses schemas at half the bound. */
 json parse_json_bounded(const std::string& body, int64_t max_ctx, bool* over, bool* deep) {
     const int64_t budget = json_value_budget(max_ctx);
     int64_t n = 0;
     *over = false;
     *deep = false;
-    /* Every completed value is counted once: a scalar at `value`, a container at its end. Once
-     * over or too deep, every event answers false, which tells the parser to keep nothing
-     * further. */
+    /* Each completed value counts once: a scalar at `value`, a container at its end. Once over
+     * or too deep, every event returns false so the parser keeps nothing more. */
     json::parser_callback_t keep = [&](int depth, json::parse_event_t ev, json&) {
         if (!*deep && depth > kJsonMaxDepth) *deep = true;
         if (!*over && (ev == json::parse_event_t::value ||
@@ -201,27 +196,37 @@ ApiError err_overloaded(const std::string& why) {
     return e;
 }
 
+std::vector dry_breakers(const std::vector& deployment, bool set) {
+    if (set || !deployment.empty()) return deployment;
+    return { "\n", ":", "\"", "*" };
+}
+
+ApiError err_internal(const std::string& why) {
+    ApiError e;
+    e.status = 500;
+    e.type = "internal_server_error";
+    e.message = why;
+    return e;
+}
+
 /* ================================================================== key vetting
  *
- * FOUR KINDS OF FIELD, and the lists below are the whole policy.
+ * Four kinds of field; the lists below are the whole policy.
  *
- * `kAccepted*` is what this server reads and honours, in OpenAI's, vLLM's and llama.cpp's
- * spellings alike (`repetition_penalty` and `repeat_penalty`, `max_tokens` and `n_predict`).
+ * `kAccepted*`: read and honoured, in OpenAI's, vLLM's and llama.cpp's spellings alike
+ * (`repetition_penalty` and `repeat_penalty`, `max_tokens` and `n_predict`).
  *
- * `kInert` changes nothing about the answer: routing and bookkeeping labels (`user`, `metadata`,
- * OpenRouter's `session_id`), and llama.cpp's knobs for its own speed and slot management
- * (`cache_prompt`, `id_slot`, `speculative.*`, ...) -- this server caches prefixes and speculates
- * on its own terms, and the output is the same either way. Accepted and ignored.
+ * `kInert`: cannot change the answer. Routing and bookkeeping labels (`user`, `metadata`), and
+ * llama.cpp's speed and slot knobs (`cache_prompt`, `id_slot`, `speculative.*`, ...); this server
+ * caches and speculates on its own terms. Accepted and ignored.
  *
- * `kGuarded` is what this server knows and does not implement, where honouring it WOULD change
- * the answer: mirostat, top-n-sigma, dynamic temperature, a logit bias. llama.cpp-built clients
- * send every one of them on every request at its "off" value, so each is accepted at that value
- * and refused by name at any other -- a 200 still means every field that could change the answer
- * was honoured, and a client that turned mirostat on learns that it was not.
+ * `kGuarded`: known, not implemented, and would change the answer (mirostat, top-n-sigma,
+ * dynamic temperature, logit bias). llama.cpp-built clients send them on every request at their
+ * "off" value, so each is accepted at that value and refused by name at any other. A 200 thus
+ * means every answer-changing field was honoured.
  *
- * ANYTHING ELSE IS IGNORED, as llama.cpp and vLLM ignore it. A field this server has never heard
- * of is a client's own extension far more often than a request it has misunderstood, and refusing
- * it breaks the client for nothing (#47). The ignored names are logged at debug.
+ * Anything else is ignored, as llama.cpp and vLLM do: an unknown field is far more often a
+ * client's own extension than a misunderstood request. Ignored names are logged at debug.
  */
 namespace {
 
@@ -246,16 +251,16 @@ const char* kAcceptedChat[] = {
 };
 
 /* `preserved_tokens` is llama-server's: control tokens a raw completion's text keeps. On chat the
- * reply format decides them (the guarded entry below); a raw completion has no format, and a
- * client that renders its own template and parses its own reply -- a tool-call sidecar -- has no
- * other way to see a format built of control tokens. */
+ * reply format decides them (guarded below); a raw completion has no format, and a client that
+ * renders its own template and parses its own reply (e.g. a tool-call sidecar) needs it to see
+ * a format built from control tokens. */
 const char* kAcceptedCompletion[] = { "prompt", "echo", "preserved_tokens" };
 
 const char* kAcceptedEmbedding[] = { "model", "input", "messages", "encoding_format",
                                       "dimensions", "image_tokens", "prompt_name" };
 
-/* Named explicitly so that "we ignore it" is a decision in the source and not an accident of a
- * missing branch -- and so the debug line of ignored names lists only what nobody decided on. */
+/* Listed explicitly so ignoring them is a recorded decision, and the debug line of ignored names
+ * shows only undecided fields. */
 const char* kInert[] = {
     /* OpenAI's and OpenRouter's bookkeeping */
     "user", "metadata", "store", "service_tier", "safety_identifier", "prompt_cache_key",
@@ -280,8 +285,10 @@ struct Guarded {
 bool is_zero(const json& v)      { return v.is_null() || (v.is_number() && v.get() == 0.0); }
 bool non_positive(const json& v) { return v.is_null() || (v.is_number() && v.get() <= 0.0); }
 bool falsy(const json& v)        { return v.is_null() || (v.is_boolean() && !v.get()); }
+/* json::empty() is false for every string, the empty one included, so a string is tested as one. */
 bool empty_value(const json& v) {
-    return v.is_null() || ((v.is_object() || v.is_array() || v.is_string()) && v.empty());
+    if (v.is_string()) return v.get_ref().empty();
+    return v.is_null() || ((v.is_object() || v.is_array()) && v.empty());
 }
 bool at_most_one(const json& v)  { return v.is_null() || (v.is_number() && v.get() <= 1.0); }
 bool text_only(const json& v) {
@@ -293,11 +300,11 @@ bool text_only(const json& v) {
 
 const Guarded kGuarded[] = {
     { "logit_bias", empty_value, "an empty object",
-      "the device sampler (spec 13) has no per-token bias stage" },
-    { "mirostat", is_zero, "0", "mirostat is not one of the device samplers (spec 13)" },
-    { "top_n_sigma", non_positive, "-1", "top-n-sigma is not one of the device samplers (spec 13)" },
+      "the device sampler has no per-token bias stage" },
+    { "mirostat", is_zero, "0", "mirostat is not one of the device samplers" },
+    { "top_n_sigma", non_positive, "-1", "top-n-sigma is not one of the device samplers" },
     { "dynatemp_range", non_positive, "0",
-      "dynamic temperature is not one of the device samplers (spec 13)" },
+      "dynamic temperature is not one of the device samplers" },
     { "min_keep", is_zero, "0", "the cut stages keep no minimum candidate count" },
     { "post_sampling_probs", falsy, "false",
       "logprobs are the raw distribution's; the distribution after the sampler's stages is not "
@@ -321,28 +328,26 @@ const Guarded kGuarded[] = {
       "the chat format names the control tokens a reply keeps" },
 };
 
-bool in_list(const char* const* list, size_t n, const std::string& k) {
-    for (size_t i = 0; i < n; ++i) if (k == list[i]) return true;
+template 
+bool in_list(const char* const (&list)[N], const std::string& k) {
+    for (const char* s : list) if (k == s) return true;
     return false;
 }
-#define ARRN(a) (sizeof(a) / sizeof((a)[0]))
 
 int vet_keys(const json& body, Endpoint ep, ApiError* err, bool native = false) {
     std::string ignored;
     for (auto it = body.begin(); it != body.end(); ++it) {
         const std::string& k = it.key();
-        if (in_list(kInert, ARRN(kInert), k)) continue;
+        if (in_list(kInert, k)) continue;
         bool prefixed = false;
         for (const char* p : kInertPrefixes) prefixed = prefixed || k.rfind(p, 0) == 0;
         if (prefixed) continue;
         if (ep == Endpoint::Embedding) {
-            if (in_list(kAcceptedEmbedding, ARRN(kAcceptedEmbedding), k)) continue;
+            if (in_list(kAcceptedEmbedding, k)) continue;
         } else {
-            if (in_list(kAcceptedCommon, ARRN(kAcceptedCommon), k)) continue;
-            if (ep == Endpoint::Chat &&
-                in_list(kAcceptedChat, ARRN(kAcceptedChat), k)) continue;
-            if (ep == Endpoint::Completion &&
-                in_list(kAcceptedCompletion, ARRN(kAcceptedCompletion), k)) continue;
+            if (in_list(kAcceptedCommon, k)) continue;
+            if (ep == Endpoint::Chat && in_list(kAcceptedChat, k)) continue;
+            if (ep == Endpoint::Completion && in_list(kAcceptedCompletion, k)) continue;
         }
         /* llama-server's native completion returns the token ids, so the field is served there. */
         if (native && k == "return_tokens") continue;
@@ -362,8 +367,8 @@ int vet_keys(const json& body, Endpoint ep, ApiError* err, bool native = false)
     return RAD_OK;
 }
 
-/* Typed getters that refuse rather than coerce: OpenAI clients that send "0.7" as a string are
- * sending a bug, and silently accepting it hides it until the day the string is "warm". */
+/* Typed getters that refuse rather than coerce: a client sending "0.7" as a string has a bug,
+ * and accepting it would hide the bug. */
 bool get_num(const json& b, const char* k, double* out, ApiError* err) {
     auto it = b.find(k);
     if (it == b.end() || it->is_null()) return true;
@@ -371,11 +376,9 @@ bool get_num(const json& b, const char* k, double* out, ApiError* err) {
     *out = it->get();
     return true;
 }
-/* EVERY INTEGER FIELD THIS FILE READS IS STORED IN 32 BITS, so a value that does not fit is
- * refused here rather than narrowed at the call site. Narrowing is not a clamp: 2^32 becomes 0
- * and 2^31 becomes negative, and for `max_tokens` both of those read downstream as "no limit".
- * The unsigned branch matters too -- nlohmann keeps a literal above INT64_MAX as unsigned, and
- * reading that as int64 wraps it negative. */
+/* Every integer field read here is stored in 32 bits, so a value that does not fit is refused
+ * rather than narrowed: 2^32 would become 0 and 2^31 negative, both "no limit" for `max_tokens`.
+ * nlohmann keeps a literal above INT64_MAX as unsigned, hence the unsigned branch. */
 bool get_int(const json& b, const char* k, int64_t* out, ApiError* err) {
     auto it = b.find(k);
     if (it == b.end() || it->is_null()) return true;
@@ -404,9 +407,9 @@ bool get_str(const json& b, const char* k, std::string* out, ApiError* err) {
     *out = it->get();
     return true;
 }
-/* A MEMBER OF A NESTED OBJECT -- a message, a content block, a tool -- read as a string: absent or
- * null leaves `*out` as it was, any other type is refused, named by `param`. json::value() throws
- * on a type it cannot convert, and a throw out of a handler is a 500 in the library's words. */
+/* A string member of a nested object (a message, a content block, a tool): absent or null leaves
+ * `*out` unchanged, any other type is refused under `param`. Used instead of json::value(),
+ * which throws on a type mismatch and would surface as a 500. */
 bool member_str(const json& o, const char* k, const char* param, std::string* out, ApiError* err) {
     auto it = o.find(k);
     if (it == o.end() || it->is_null()) return true;
@@ -414,16 +417,15 @@ bool member_str(const json& o, const char* k, const char* param, std::string* ou
     *out = it->get();
     return true;
 }
-/* The same read where the type is checked later, by the validation the value goes through: here a
- * member that is not a string reads as `def`. */
+/* The same read where later validation checks the type: a non-string member reads as `def`. */
 std::string str_or(const json& o, const char* k, const std::string& def = std::string()) {
     auto it = o.find(k);
     return it != o.end() && it->is_string() ? it->get() : def;
 }
 
-/* A conversation's label as /sessions shows it: at most 128 bytes, cut where a character starts,
- * because the label is serialised into JSON that refuses a string split inside one. */
-static std::string session_label_of(const std::string& s) {
+/* A conversation's label for /sessions: at most 128 bytes, cut at a UTF-8 character boundary
+ * because the label is serialised into JSON. */
+std::string session_label_of(const std::string& s) {
     constexpr size_t kMax = 128;
     if (s.size() <= kMax) return s;
     size_t cut = kMax;
@@ -431,37 +433,22 @@ static std::string session_label_of(const std::string& s) {
     return s.substr(0, cut);
 }
 
-/* ONE FIELD, SEVERAL SPELLINGS: OpenAI's, vLLM's and llama.cpp's name for the same thing. Any of
- * them may be sent; two that disagree are refused, because there is no order in which to read
- * them that the caller could have meant. */
-bool get_num_any(const json& b, std::initializer_list keys, double* out,
-                 ApiError* err) {
+/* One field under several spellings (OpenAI's, vLLM's, llama.cpp's), read as a number (double)
+ * or a 32-bit integer (int64_t). Any may be sent; two that disagree are refused, since no reading
+ * order could be what the caller meant. */
+template 
+bool get_any(const json& b, std::initializer_list keys, T* out, bool* present,
+             ApiError* err) {
     const char* named = nullptr;
-    double v = *out;
+    T v = *out;
     for (const char* k : keys) {
         auto it = b.find(k);
         if (it == b.end() || it->is_null()) continue;
-        double x = 0;
-        if (!get_num(b, k, &x, err)) return false;
-        if (named && x != v) {
-            *err = err_bad(k, std::string("disagrees with ") + named + ", which is the same field");
-            return false;
-        }
-        v = x;
-        named = k;
-    }
-    *out = v;
-    return true;
-}
-bool get_int_any(const json& b, std::initializer_list keys, int64_t* out,
-                 bool* present, ApiError* err) {
-    const char* named = nullptr;
-    int64_t v = *out;
-    for (const char* k : keys) {
-        auto it = b.find(k);
-        if (it == b.end() || it->is_null()) continue;
-        int64_t x = 0;
-        if (!get_int(b, k, &x, err)) return false;
+        T x = 0;
+        bool ok;
+        if constexpr (std::is_same_v) ok = get_num(b, k, &x, err);
+        else ok = get_int(b, k, &x, err);
+        if (!ok) return false;
         if (named && x != v) {
             *err = err_bad(k, std::string("disagrees with ") + named + ", which is the same field");
             return false;
@@ -476,6 +463,18 @@ bool get_int_any(const json& b, std::initializer_list keys, int64_t
 
 }  /* namespace */
 
+KeyPolicy request_key_policy() {
+    KeyPolicy p;
+    p.common.assign(std::begin(kAcceptedCommon), std::end(kAcceptedCommon));
+    p.chat.assign(std::begin(kAcceptedChat), std::end(kAcceptedChat));
+    p.completion.assign(std::begin(kAcceptedCompletion), std::end(kAcceptedCompletion));
+    p.embedding.assign(std::begin(kAcceptedEmbedding), std::end(kAcceptedEmbedding));
+    p.inert.assign(std::begin(kInert), std::end(kInert));
+    p.inert_prefixes.assign(std::begin(kInertPrefixes), std::end(kInertPrefixes));
+    for (const Guarded& g : kGuarded) p.guarded.push_back(g.key);
+    return p;
+}
+
 /* The body of every generation endpoint: one JSON object, parsed into a bounded tree. */
 int parse_request_object(const std::string& body, const OaiLimits& lim, json* b, ApiError* err) {
     bool over = false, deep = false;
@@ -505,8 +504,7 @@ int parse_request_object(const std::string& body, const OaiLimits& lim, json* b,
 namespace {
 
 /* One row per bounded sampler field. `lo_open` excludes the lower bound; `hi` of infinity is no
- * upper bound. `why` is the refusal when the range alone does not say it well, and null for a
- * closed interval, whose refusal names the interval and the value. */
+ * upper bound. `why` is the refusal text, or null to print the closed interval and the value. */
 struct SamplerRange {
     const char* field;
     double      lo, hi;
@@ -519,7 +517,8 @@ constexpr double kInf = std::numeric_limits::infinity();
 const SamplerRange kSamplerRanges[] = {
     { "temperature",        0.0,  2.0,  false, nullptr },
     { "top_p",              0.0,  1.0,  true,  "must be in (0, 1]" },
-    { "top_k",              0.0,  kInf, false, "must be >= 0 (0 disables it)" },
+    { "top_k",              0.0,  kInf, false,
+      "must be >= 0 (0 samples from the 1024 most likely tokens, the sampler's candidate width)" },
     { "min_p",              0.0,  1.0,  false, nullptr },
     { "typical_p",          0.0,  1.0,  true,  "must be in (0, 1]" },
     { "presence_penalty",   -2.0, 2.0,  false, nullptr },
@@ -529,13 +528,14 @@ const SamplerRange kSamplerRanges[] = {
     { "xtc_probability",    0.0,  1.0,  false, nullptr },
     { "xtc_threshold",      0.0,  1.0,  false, nullptr },
     { "dry_base",           1.0,  kInf, false, "must be >= 1" },
+    { "dry_allowed_length", 1.0,  kInf, false, "must be >= 1" },
     { "dry_penalty_last_n", -1.0, kInf, false, "must be >= -1" },
 };
 
 }  /* namespace */
 
-/* Written as "inside the range" and negated, so a NaN -- which a flag can parse and JSON cannot
- * carry -- fails every row rather than passing them all. */
+/* Tested as "inside the range" so a NaN (which a flag can parse, though JSON cannot carry one)
+ * fails every row. */
 bool sampler_value_ok(const char* field, double v, std::string* why) {
     for (const SamplerRange& r : kSamplerRanges) {
         if (std::strcmp(r.field, field)) continue;
@@ -557,17 +557,16 @@ bool sampler_value_ok(const char* field, double v, std::string* why) {
 /* ================================================================== the sampler order
  *
  * llama.cpp's `samplers`: which stages run and in what order, as names ("top_k", "temperature",
- * with llama.cpp's aliases) or as one string of its letters ("kypmxt"). A stage the list leaves
- * out does not run, whatever its own field says -- llama.cpp's meaning, and the reason a client
- * sends the list.
+ * with llama.cpp's aliases) or a string of letters ("kypmxt"). A stage the list leaves out does
+ * not run, whatever its own field says (llama.cpp's meaning).
  *
- * THE CHAIN HERE IS FIXED BUT FOR ONE THING (core/sample/sampler.h): penalties, DRY, top-k, then
- * top-p, min-p, typical and XTC, with temperature either before the cuts (vLLM's order, the
- * default) or after them (llama.cpp's). So a list is honoured when the stages it enables appear in
- * that relative order with temperature at either end of the cuts, and refused by name otherwise.
- * Only ENABLED stages are compared: a stage at its identity value is the same wherever it sits,
- * which is what lets llama.cpp's default list -- typ_p before top_p -- through whenever typical
- * is off. top-n-sigma is guarded at its off value (kGuarded), so it is free to appear anywhere. */
+ * The chain here is fixed (core/sample/sampler.h): penalties, DRY, top-k, top-p, min-p, typical,
+ * XTC, with temperature either before the cuts (vLLM's order, the default) or after them
+ * (llama.cpp's). A list is honoured when its enabled stages appear in that relative order with
+ * temperature at either end of the cuts, and refused by name otherwise. Only enabled stages are
+ * compared, since a stage at its identity value commutes with everything; this admits
+ * llama.cpp's default list (typ_p before top_p) whenever typical is off. top-n-sigma is guarded
+ * at its off value (kGuarded), so it may appear anywhere. */
 static int apply_sampler_order(const json& b, SamplingParams* sp, ApiError* err) {
     auto it = b.find("samplers");
     if (it == b.end() || it->is_null()) return RAD_OK;
@@ -596,27 +595,23 @@ static int apply_sampler_order(const json& b, SamplingParams* sp, ApiError* err)
             default:  return -1;
         }
     };
+    auto unknown = [&](const std::string& what) {
+        *err = err_unsupported("samplers", what + " names no sampler this server runs (infill and "
+                                                  "adaptive_p are not served)");
+        return RAD_E_UNSUPPORTED;
+    };
     std::vector list;
     if (it->is_string()) {
         for (char c : it->get()) {
             const int st = by_char(c);
-            if (st < 0) {
-                *err = err_unsupported("samplers", std::string("'") + c + "' names no sampler this "
-                                       "server runs (infill and adaptive_p are not served)");
-                return RAD_E_UNSUPPORTED;
-            }
+            if (st < 0) return unknown(std::string("'") + c + "'");
             list.push_back(st);
         }
     } else if (it->is_array()) {
         for (const json& n : *it) {
             if (!n.is_string()) { *err = err_bad("samplers", "expected sampler names"); return RAD_E_INVAL; }
             const int st = by_name(n.get());
-            if (st < 0) {
-                *err = err_unsupported("samplers", "\"" + n.get() + "\" names no "
-                                       "sampler this server runs (infill and adaptive_p are not "
-                                       "served)");
-                return RAD_E_UNSUPPORTED;
-            }
+            if (st < 0) return unknown("\"" + n.get() + "\"");
             list.push_back(st);
         }
     } else {
@@ -625,8 +620,8 @@ static int apply_sampler_order(const json& b, SamplingParams* sp, ApiError* err)
     }
 
     auto listed = [&](int st) { return std::find(list.begin(), list.end(), st) != list.end(); };
-    /* What the list leaves out is off. Greedy stays greedy: temperature 0 is the argmax in either
-     * engine whatever surrounds it. */
+    /* Stages the list leaves out are off. Temperature 0 stays greedy: it is the argmax either
+     * way. */
     if (!listed(PEN))  { sp->rep_penalty = 1.0f; sp->freq_penalty = 0.0f; sp->pres_penalty = 0.0f; }
     if (!listed(DRY))  sp->dry_multiplier = 0.0f;
     if (!listed(TOPK)) sp->top_k = 0;
@@ -672,8 +667,8 @@ static int apply_sampler_order(const json& b, SamplingParams* sp, ApiError* err)
         last_st = st;
     }
     if (!on[TEMP]) return RAD_OK;
-    /* Temperature: after the penalties, and before every enabled cut or after every one. top-k
-     * commutes with it -- a monotone rescale keeps the same k largest -- so it is not a cut here. */
+    /* Temperature: after the penalties, and before all enabled cuts or after all of them. top-k
+     * commutes with it (a monotone rescale keeps the same k largest), so it is not a cut here. */
     const int pt = pos(TEMP);
     for (int st : { PEN, DRY })
         if (on[st] && pos(st) > pt) return refuse(st, TEMP);
@@ -700,11 +695,9 @@ static int parse_sampling(const json& b, const OaiLimits& lim, OaiRequest* r, Ap
         return false;
     };
 
-    /* THE DEPLOYMENT'S DEFAULTS ARE THE SEED, and every field below reads its current value
-     * before looking for one in the body -- so a field the request names overrides, and a field
-     * it omits keeps what the checkpoint asked for. Done here rather than at each call site
-     * because a sampler default that reached one endpoint and not the other would make the same
-     * model answer differently through /v1/completions than through /v1/chat/completions. */
+    /* Start from the deployment's defaults; each field below overrides only when the request
+     * names it. Done here, not per endpoint, so /v1/completions and /v1/chat/completions sample
+     * identically. */
     r->sp = lim.default_sampling;
 
     d = r->sp.temp;
@@ -743,7 +736,8 @@ static int parse_sampling(const json& b, const OaiLimits& lim, OaiRequest* r, Ap
     r->sp.freq_penalty = (float)d;
 
     d = r->sp.rep_penalty;
-    if (!get_num_any(b, { "repetition_penalty", "repeat_penalty" }, &d, err)) return RAD_E_INVAL;
+    if (!get_any(b, { "repetition_penalty", "repeat_penalty" }, &d, nullptr, err))
+        return RAD_E_INVAL;
     if (!ok("repetition_penalty", d)) return RAD_E_INVAL;
     r->sp.rep_penalty = (float)d;
 
@@ -771,20 +765,18 @@ static int parse_sampling(const json& b, const OaiLimits& lim, OaiRequest* r, Ap
     r->sp.dry_base = (float)d;
     i64 = r->sp.dry_allowed_length;
     if (!get_int(b, "dry_allowed_length", &i64, err)) return RAD_E_INVAL;
+    if (!ok("dry_allowed_length", (double)i64)) return RAD_E_INVAL;
     r->sp.dry_allowed_length = (int)i64;
     i64 = r->sp.dry_penalty_last_n;
     if (!get_int(b, "dry_penalty_last_n", &i64, err)) return RAD_E_INVAL;
     if (!ok("dry_penalty_last_n", (double)i64)) return RAD_E_INVAL;
     r->sp.dry_penalty_last_n = (int)i64;
 
-    /* ABSENT MEANS llama.cpp's FOUR, not none. A client that turns DRY on and names no breakers
-     * gets what llama-server gives it -- newline, colon, quote and asterisk end a repeat -- and a
-     * list that is sent replaces them outright, an empty one included. The default costs nothing
-     * with DRY off: the sampler resolves breakers only for a request that runs DRY. */
+    /* Absent means llama.cpp's four breakers (newline, colon, quote, asterisk), not none; a sent
+     * list, even empty, replaces them. The sampler resolves breakers only when DRY runs. */
     auto dsb = b.find("dry_sequence_breakers");
     if (dsb == b.end() || dsb->is_null()) {
-        if (r->sp.dry_seq_breakers.empty() && !lim.default_dry_breakers_set)
-            r->sp.dry_seq_breakers = { "\n", ":", "\"", "*" };
+        r->sp.dry_seq_breakers = dry_breakers(r->sp.dry_seq_breakers, lim.default_dry_breakers_set);
     } else {
         r->sp.dry_seq_breakers.clear();
         if (!dsb->is_array()) {
@@ -800,21 +792,25 @@ static int parse_sampling(const json& b, const OaiLimits& lim, OaiRequest* r, Ap
         }
     }
 
-    /* An unset seed must not mean seed 0, or every request in a deployment that never sets one
-     * would draw the identical sample. Absent means "pick one", which is what OpenAI's contract
-     * says and what makes `seed` meaningful when it IS set. */
+    /* An absent seed is random, per OpenAI's contract; seed 0 would make every unseeded request
+     * draw the same sample. -1 is random too: llama-server's spelling of "no seed", which its
+     * clients send back from /props. */
     auto sit = b.find("seed");
-    if (sit != b.end() && !sit->is_null()) {
-        if (!sit->is_number_integer()) { *err = err_bad("seed", "expected an integer"); return RAD_E_INVAL; }
+    if (sit != b.end() && !sit->is_null() && !sit->is_number_integer()) {
+        *err = err_bad("seed", "expected an integer");
+        return RAD_E_INVAL;
+    }
+    if (sit != b.end() && !sit->is_null() &&
+        !(!sit->is_number_unsigned() && sit->get() == -1)) {
         r->sp.seed = (uint64_t)sit->get();
     } else {
         static thread_local std::mt19937_64 rng{std::random_device{}()};
         r->sp.seed = rng();
     }
 
-    /* n. Implemented by fan-out: n independent requests over the same prompt, which the prefix
-     * cache makes nearly free after the first (spec 7.3). Their seeds are offset from the
-     * request's, because n identical seeds would produce n identical completions. */
+    /* n is served by fan-out: n independent requests over one prompt, nearly free after the first
+     * through the prefix cache (spec 7.3). Their seeds are offset from the request's so the n
+     * completions differ. */
     i64 = 1;
     if (!get_int(b, "n", &i64, err)) return RAD_E_INVAL;
     if (i64 < 1 || i64 > lim.max_n) {
@@ -829,13 +825,12 @@ static int parse_sampling(const json& b, const OaiLimits& lim, OaiRequest* r, Ap
     if (!get_int(b, "priority", &i64, err)) return RAD_E_INVAL;
     r->priority = (int)i64;
 
-    /* max_tokens, with max_completion_tokens as OpenAI's newer spelling and n_predict as
-     * llama.cpp's. A NEGATIVE VALUE IS llama.cpp's "no limit": whatever the context leaves, which
-     * is what 0 resolves to in clamp_max_tokens -- and unlike an absent field it does not take the
-     * deployment's --default-max-tokens. */
+    /* max_tokens, also spelled max_completion_tokens (OpenAI) and n_predict (llama.cpp). A
+     * negative value is llama.cpp's "no limit": stored as 0, which clamp_max_tokens resolves to
+     * what the context leaves; unlike an absent field it ignores --default-max-tokens. */
     int64_t mt = 0;
     bool mt_named = false;
-    if (!get_int_any(b, { "max_tokens", "max_completion_tokens", "n_predict" }, &mt, &mt_named,
+    if (!get_any(b, { "max_tokens", "max_completion_tokens", "n_predict" }, &mt, &mt_named,
                      err))
         return RAD_E_INVAL;
     if (mt_named && mt == 0) { *err = err_bad("max_tokens", "must be >= 1, or -1 for no limit"); return RAD_E_INVAL; }
@@ -844,14 +839,10 @@ static int parse_sampling(const json& b, const OaiLimits& lim, OaiRequest* r, Ap
     /* ignore_eos: generate to max_tokens whatever the model emits. See Request::ignore_eos. */
     if (!get_bool(b, "ignore_eos", &r->ignore_eos, err)) return RAD_E_INVAL;
 
-    /* stop: a string or an array of strings.
-     *
-     * BOUNDED IN COUNT AND LENGTH, because every stop string is searched for in each stretch of
-     * text a choice produces -- by the decoder and again by the server's own scan -- so what one
-     * request costs per token is its number of stop strings times the longest of them. OpenAI
-     * allows four. The bounds here are far past anything a client sends and exist so that no
-     * request can buy that scan without limit. The deployment may move them (--max-stop-strings,
-     * --max-stop-bytes). */
+    /* stop: a string or an array of strings. Bounded in count and length because every stop
+     * string is searched in each piece of generated text (by the decoder and the server's scan),
+     * so per-token cost is count x longest. OpenAI allows four; the bounds are far above that
+     * and configurable (--max-stop-strings, --max-stop-bytes). */
     const size_t max_stops = (size_t)lim.max_stops, max_stop_bytes = (size_t)lim.max_stop_bytes;
     auto st = b.find("stop");
     if (st != b.end() && !st->is_null()) {
@@ -888,14 +879,12 @@ static int parse_sampling(const json& b, const OaiLimits& lim, OaiRequest* r, Ap
     if (!get_bool(b, "stream", &bl, err)) return RAD_E_INVAL;
     r->stream = bl;
 
-    /* llama.cpp's streaming extras: the timings on every chunk rather than the last, and the
-     * prompt's progress as chunks while it is being read. */
+    /* llama.cpp's streaming extras: timings on every chunk, and prompt progress chunks. */
     if (!get_bool(b, "timings_per_token", &r->timings_per_token, err)) return RAD_E_INVAL;
     if (!get_bool(b, "return_progress", &r->return_progress, err)) return RAD_E_INVAL;
 
-    /* OpenRouter's `session_id`: which conversation the request belongs to, as the client names
-     * it. It labels the conversation on /sessions and the dashboard and changes nothing else. A
-     * value that is not a string is not a label and is ignored, as the field is everywhere. */
+    /* OpenRouter's `session_id`: the client's conversation name, used only as a label on
+     * /sessions and the dashboard. A non-string value is ignored. */
     auto sid = b.find("session_id");
     if (sid != b.end() && sid->is_string()) r->session_label = session_label_of(sid->get());
 
@@ -914,27 +903,20 @@ static int parse_sampling(const json& b, const OaiLimits& lim, OaiRequest* r, Ap
 
 /* ================================================================== thinking
  *
- * Three spellings reach this server for one question -- does the model reason before it answers.
- * `chat_template_kwargs: {"enable_thinking": false}` is what vLLM's clients send and is the one
- * that matters here; `enable_thinking` at the top level is the shorthand several clients grew;
- * `reasoning_effort` is OpenAI's own, and "none"/"minimal" is the only value of it this server
- * can honour, because the rest ask the model to think HARDER and no chat template exposes a dial
- * for that.
+ * Three spellings ask whether the model reasons before answering:
+ * `chat_template_kwargs: {"enable_thinking": false}` (vLLM's clients), top-level
+ * `enable_thinking` (a common shorthand), and OpenAI's `reasoning_effort`, whose "none" and
+ * "minimal" turn thinking off.
  *
- * THE KWARG ALONE IS NOT ENOUGH, and this is the trap the whole function exists for. The vendored
- * llama.cpp chat layer copies chat_template_kwargs into the template context and THEN overwrites
- * the key `enable_thinking` with its own boolean field (chat-auto-parser-helpers.cpp). So a
- * caller who sends the kwarg and nothing else has it silently overwritten with the default true,
- * and sees the model think anyway -- a 200 that did not honour the request, which is the one
- * outcome this file's header forbids. Lifting the kwarg into the field is what makes it real.
+ * The kwarg alone is not enough: the vendored llama.cpp chat layer copies chat_template_kwargs
+ * into the template context and then overwrites `enable_thinking` with its own boolean field
+ * (chat-auto-parser-helpers.cpp). The kwarg is therefore lifted into that field.
  *
- * THE DEPLOYMENT'S DEFAULTS GO IN FIRST AND THE REQUEST OVERWRITES THEM, key by key -- except that
- * thinking is one setting with three spellings, and a default in one spelling must not survive a
- * request that used another. A request that says anything about thinking (either enable_thinking,
- * or a reasoning effort) drops the deployment's enable_thinking; one that names an effort drops
- * the deployment's effort too. Otherwise `--chat-template-kwargs '{"enable_thinking":false}'`
- * would turn off thinking for a caller who sent `reasoning_effort: "high"`, and
- * `--reasoning-effort none` would do the same to one who sent `enable_thinking: true`.
+ * Deployment defaults go in first and the request overwrites them key by key, but a default in
+ * one spelling must not survive a request using another. A request that says anything about
+ * thinking drops the deployment's enable_thinking; one that names an effort also drops the
+ * deployment's effort. Otherwise `--chat-template-kwargs '{"enable_thinking":false}'` would
+ * disable thinking for a caller sending `reasoning_effort: "high"`.
  */
 RequestThinking request_thinking(const json& b) {
     auto kw = b.find("chat_template_kwargs");
@@ -981,10 +963,8 @@ void map_reasoning_effort(const OaiLimits& lim, ChatRenderOptions* opt) {
 
 ApiError template_refusal(const ChatRenderOptions& opt, const OaiLimits& lim, int rs,
                           const std::string& why) {
-    /* AN EFFORT OUTSIDE THE SET IS THE REASON, when the set is known and the word is not in it:
-     * the render that refused carried no other variable the template was probed for. The
-     * template's own sentence is a traceback through its source, which says nothing a client can
-     * act on that the set does not. */
+    /* With a known set and an effort outside it, the effort is the reason: no other probed
+     * variable was in the render. The set is more actionable than the template's traceback. */
     auto it = opt.template_kwargs.find("reasoning_effort");
     if (it != opt.template_kwargs.end() && !lim.reasoning_efforts.empty()) {
         const json v = json::parse(it->second, nullptr, false);
@@ -1023,8 +1003,8 @@ static int parse_thinking(const json& b, const OaiLimits& lim, ChatRenderOptions
 
     if (has_kw) {
         for (auto it = kw->begin(); it != kw->end(); ++it) {
-            /* dump(), not get(): the template context wants JSON, so a string value has
-             * to arrive still quoted. See ChatRenderOptions. */
+            /* dump(), not get(): the template context takes JSON, so strings stay
+             * quoted. See ChatRenderOptions. */
             opt->template_kwargs[it.key()] = it.value().dump();
             if (it.key() == "enable_thinking") {
                 if (!it.value().is_boolean()) {
@@ -1041,12 +1021,9 @@ static int parse_thinking(const json& b, const OaiLimits& lim, ChatRenderOptions
     if (!get_bool(b, "enable_thinking", &think, err)) return RAD_E_INVAL;
     opt->enable_thinking = think;
 
-    /* `preserve_thinking` AT THE TOP LEVEL is the template variable of that name, the same
-     * shorthand `enable_thinking` is: llama.cpp maps the field into the template, and clients
-     * written against it (oh-my-pi, for every Qwen model) send it there as well as in
-     * chat_template_kwargs. The Qwen3.6 and later templates read it to keep earlier assistant
-     * turns' reasoning in the prompt; a template that does not read it ignores it, as it ignores
-     * any variable it does not name. Like enable_thinking, the top-level spelling wins. */
+    /* Top-level `preserve_thinking` is shorthand for the template variable, as llama.cpp maps it
+     * and as some clients send it. Qwen3.6+ templates read it to keep earlier assistant turns'
+     * reasoning in the prompt; other templates ignore it. The top-level spelling wins. */
     auto pt = b.find("preserve_thinking");
     if (pt != b.end() && !pt->is_null()) {
         if (!pt->is_boolean()) {
@@ -1056,30 +1033,23 @@ static int parse_thinking(const json& b, const OaiLimits& lim, ChatRenderOptions
         opt->template_kwargs["preserve_thinking"] = pt->dump();
     }
 
-    /* REASONING EFFORT IS THE TEMPLATE'S VOCABULARY, NOT OURS, so there is no allow-list here.
-     * One would be wrong in both directions: OpenAI's ladder is none/minimal/low/medium/high,
-     * while a model's template may accept a different set -- Qwen3.8's takes xhigh/medium/low and
-     * raise_exception's on anything else. An allow-list would admit `"high"` only for the template
-     * to refuse it, and refuse `"xhigh"`, which that template would have taken.
+    /* Reasoning effort is the template's vocabulary, so there is no allow-list: OpenAI's ladder is
+     * none/minimal/low/medium/high, while e.g. Qwen3.8's template takes xhigh/medium/low and
+     * raises on anything else.
      *
-     * What this layer actually owns is the one mapping that is a SERVER semantic and not a
-     * template one: "none" and "minimal" mean do not think, which is `enable_thinking = false`
-     * and is honoured whatever the template's dial is called. Everything else is passed through
-     * as template context, and a template that does not read it ignores it -- exactly as the
-     * kwarg path already does. A template that DOES read it and refuses says so in its own words,
-     * because ChatPrompt::error carries the sentence out (core/text/chat.h).
-     *
-     * An explicit chat_template_kwargs entry still wins: emplace does not overwrite. */
+     * The server owns one mapping: "none" and "minimal" mean enable_thinking = false. Every other
+     * word is passed as template context; a template that refuses it says so through
+     * ChatPrompt::error (core/text/chat.h). An explicit chat_template_kwargs entry wins, since
+     * emplace does not overwrite. */
     std::string effort;
     if (!get_str(b, "reasoning_effort", &effort, err)) return RAD_E_INVAL;
     /* --reasoning-effort-map, before "none" and "minimal" are read, so a map can name either. */
     if (auto m = lim.reasoning_effort_map.find(effort);
         !effort.empty() && m != lim.reasoning_effort_map.end())
         effort = m->second;
-    /* The deployment's default, where the request did not say. Last, so every explicit spelling
-     * above it wins; emplace, so a chat_template_kwargs entry that already set the key stands.
-     * "none" and "minimal" are an enable_thinking default, so any word about thinking drops them;
-     * a level is an effort default, dropped by an effort. */
+    /* The deployment's default, where the request is silent. "none" and "minimal" act as an
+     * enable_thinking default, dropped by any word about thinking; a level is an effort default,
+     * dropped by an effort. */
     if (effort.empty()) {
         const std::string& def = lim.default_reasoning_effort;
         const bool off = def == "none" || def == "minimal";
@@ -1094,19 +1064,34 @@ static int parse_thinking(const json& b, const OaiLimits& lim, ChatRenderOptions
 
 /* ================================================================== grammar / response_format */
 
-/* `schema_json`, when non-null, means "hand me the schema instead of compiling it" -- which is
- * what the chat endpoint needs. A chat template BUILDS the grammar itself, from the schema and
- * from its own tool-call syntax together, and it takes the schema as a schema
- * (chat-auto-parser-generator.cpp keys `has_response_format` off `inputs.json_schema`). Handing
- * it a pre-compiled GBNF in the `grammar` slot instead means it sees no response format at all,
- * emits no grammar, and the compiled one is then overwritten by that empty result -- a
- * `response_format` that returns 200 and constrains nothing. /v1/completions has no template, so
- * it passes null and the schema is compiled here. */
+/* A non-null `schema_json` returns the schema instead of compiling it, for the chat endpoint:
+ * the chat layer builds the grammar from the schema and its tool-call syntax together, and keys
+ * `has_response_format` off `inputs.json_schema` (chat-auto-parser-generator.cpp). A precompiled
+ * GBNF would be overwritten by its empty result. /v1/completions has no template, passes null,
+ * and the schema is compiled here. */
 static int parse_output_format(const json& b, const OaiDeps& d, OaiRequest* r, ApiError* err,
                                std::string* schema_json = nullptr) {
     std::string gram;
     if (!get_str(b, "grammar", &gram, err)) return RAD_E_INVAL;
 
+    /* A schema goes back as JSON for the template path, or is compiled into the grammar. */
+    auto use_schema = [&](const json& schema, const char* param) -> int {
+        if (schema_json) { *schema_json = schema.dump(); return RAD_OK; }
+        if (!d.grammar) {
+            *err = err_not_implemented(std::string(param) + " requires the JSON-schema to GBNF "
+                                       "compiler, which this build was wired without");
+            return RAD_E_UNSUPPORTED;
+        }
+        std::string out, why;
+        const int st = d.grammar->from_json_schema(schema, out, why);
+        if (st < 0) {
+            *err = err_bad(param, "the schema could not be compiled to a grammar: " + why);
+            return st;
+        }
+        r->sp.grammar = std::move(out);
+        return RAD_OK;
+    };
+
     auto rf = b.find("response_format");
     const bool has_rf = rf != b.end() && !rf->is_null();
     if (!gram.empty() && has_rf) {
@@ -1122,18 +1107,7 @@ static int parse_output_format(const json& b, const OaiDeps& d, OaiRequest* r, A
             return RAD_E_INVAL;
         }
         if (!js->is_object()) { *err = err_bad("json_schema", "expected a JSON Schema object"); return RAD_E_INVAL; }
-        json schema = *js;
-        if (schema_json) { *schema_json = schema.dump(); return RAD_OK; }
-        if (!d.grammar) {
-            *err = err_not_implemented("json_schema requires the JSON-schema to GBNF compiler "
-                                       "(spec 13), which this build was wired without");
-            return RAD_E_UNSUPPORTED;
-        }
-        std::string out, why;
-        const int st = d.grammar->from_json_schema(schema, out, why);
-        if (st < 0) { *err = err_bad("json_schema", "could not be compiled to a grammar: " + why); return st; }
-        r->sp.grammar = out;
-        return RAD_OK;
+        return use_schema(*js, "json_schema");
     }
     if (!gram.empty()) { r->sp.grammar = gram; return RAD_OK; }
     if (!has_rf) return RAD_OK;
@@ -1165,35 +1139,41 @@ static int parse_output_format(const json& b, const OaiDeps& d, OaiRequest* r, A
                        type + "\"");
         return RAD_E_INVAL;
     }
+    return use_schema(schema, "response_format");
+}
 
-    if (schema_json) { *schema_json = schema.dump(); return RAD_OK; }
-
-    if (!d.grammar) {
-        *err = err_not_implemented(
-            "response_format requires the JSON-schema to GBNF compiler (spec 13), which this "
-            "build was wired without");
-        return RAD_E_UNSUPPORTED;
+/* Appends a token-id array, refused under `param` unless every element is a valid id. */
+static int token_ids(const json& arr, const char* param, std::vector* out,
+                     ApiError* err) {
+    for (const auto& v : arr) {
+        int32_t id = 0;
+        if (!v.is_number_integer()) {
+            *err = err_bad(param, "token arrays must contain integers only");
+            return RAD_E_INVAL;
+        }
+        if (!token_id(v, &id)) {
+            *err = err_bad(param, "a token id must be in [0, 2147483647], got " + v.dump());
+            return RAD_E_INVAL;
+        }
+        out->push_back(id);
     }
-    std::string out, why;
-    int s = d.grammar->from_json_schema(schema, out, why);
-    if (s < 0) {
-        *err = err_bad("response_format", "schema could not be compiled to a grammar: " + why);
-        return s;
-    }
-    r->sp.grammar = out;
     return RAD_OK;
 }
 
+/* Compiles the request's grammar at admission, while failure is still a 400; on the step path
+ * it would fail a request that is already streaming. `param` names the field it came from. */
+static int compile_grammar(const OaiDeps& d, OaiRequest* r, const char* param, ApiError* err) {
+    if (r->sp.grammar.empty() || !d.grammar) return RAD_OK;
+    std::string why;
+    if (d.grammar->compile(r->sp.grammar, &r->sp.grammar_program, why) >= 0) return RAD_OK;
+    *err = err_bad(param, "the grammar this request implies cannot be run: " + why);
+    return RAD_E_INVAL;
+}
+
 /* ================================================================== multimodal content parts */
 
-/* The marker the chat template renders for a media part. Both sides have to agree on it; it is
- * declared here and in iface.h so that neither component owns it privately. */
-static const char* const MEDIA_MARKER = RAD_MEDIA_MARKER;
-
-/* Pull the bytes out of an OpenAI image_url. Only `data:` URLs are accepted: fetching an
- * arbitrary http(s) URL on a caller's behalf turns the inference server into an SSRF proxy with
- * network access to everything the deployment can reach, and no amount of allowlisting makes
- * that a good default. */
+/* Only `data:` URLs are accepted: fetching arbitrary http(s) URLs would make the server an SSRF
+ * proxy into everything the deployment can reach. */
 int decode_media_url(const std::string& url, const std::string& field,
                      std::vector* out, ApiError* err) {
     if (url.rfind("data:", 0) != 0) {
@@ -1218,8 +1198,8 @@ int decode_media_url(const std::string& url, const std::string& field,
     return RAD_OK;
 }
 
-/* THE DEEPEST NESTING IN A JSON TEXT, counted without parsing it: brackets outside string
- * literals, whether or not the text is valid JSON. */
+/* The deepest bracket nesting in a JSON text, counted without parsing (brackets outside string
+ * literals, valid JSON or not). */
 static int json_text_depth(const std::string& s) {
     int d = 0, most = 0;
     bool in_str = false, esc = false;
@@ -1237,20 +1217,16 @@ static int json_text_depth(const std::string& s) {
     return most;
 }
 
-/* A STRING THAT PARSES INTO A TREE DEEPER THAN THE BOUND. Only valid JSON becomes a tree: text
- * that is not JSON never becomes one (a tool result that does not parse is rendered as the
- * string it is), so its brackets are not nesting, however they count. The count
- * runs first and the validation (json::accept, which builds nothing and does not recurse) only
- * when it is over. */
+/* True when `s` is valid JSON nesting deeper than the bound. Invalid JSON is rendered as a plain
+ * string, so its brackets do not count. The cheap count runs first; json::accept (no tree, no
+ * recursion) only when it is over. */
 static bool json_text_too_deep(const std::string& s) {
     return json_text_depth(s) > kJsonMaxDepth && json::accept(s);
 }
 
-/* STRINGS THE CHAT TEMPLATE PARSES AS JSON are bounded like the body is (parse_json_bounded). An
- * assistant message's tool-call arguments and a tool message's content arrive as strings, one
- * level deep in the request, and the template layer parses them into trees and serialises those
- * again when it renders -- recursively, one call a level. Their nesting is checked here, before
- * that happens, so a string of brackets cannot take the worker's stack. */
+/* Strings the chat template parses as JSON are depth-bounded like the body (parse_json_bounded).
+ * Tool-call arguments and tool-message content arrive as strings; the template layer parses and
+ * re-serialises them recursively, so a string of brackets could overflow the worker's stack. */
 static int check_template_json(const json& msg, const std::string& role, ApiError* err) {
     if (role == "assistant") {
         auto tcs = msg.find("tool_calls");
@@ -1283,23 +1259,35 @@ static int check_template_json(const json& msg, const std::string& role, ApiErro
     return RAD_OK;
 }
 
-/* Rewrite content parts in place: text stays, media becomes the marker and its bytes are handed
- * to the encoder. `media` collects (kind, bytes) in the order they appear, which is the order the
- * markers appear in the rendered prompt. */
-/* ONE MEDIA CONTENT PART, read and decoded: 1 with `*kind` and `*bytes` set when `part` is an
- * image, video or audio part, 0 when it is some other type (the caller's to judge), negative with
- * `*err` set when it is a media part that cannot be served. `field` prefixes the error's field
- * name -- "messages[].content[]" for chat, "input[]" for embeddings.
+/* Read and decode one media content part. Returns 1 with `*kind` and `*bytes` set for an image,
+ * video or audio part, 0 for any other type (the caller decides), negative with `*err` for a
+ * media part that cannot be served. `field` prefixes the error's field name
+ * ("messages[].content[]" for chat, "input[]" for embeddings).
  *
- * IMAGE AND VIDEO PARTS, in the two spellings clients send: OpenAI's
- * {"type":"image_url","image_url":{"url":...}} (and the bare-string form), the Responses API's
- * "input_image", and the video equivalents vLLM's clients use -- {"type":"video_url",
- * "video_url":{"url":...}} and "input_video". AUDIO is OpenAI's {"type":"input_audio",
- * "input_audio":{"data": base64, "format": "wav"|"mp3"}} -- and the other formats the decoder
- * admits by the same spelling -- or vLLM's {"type":"audio_url","audio_url":{"url": data URL}}. */
+ * Image and video: OpenAI's {"type":"image_url","image_url":{"url":...}} (or a bare string), the
+ * Responses API's "input_image", and vLLM's {"type":"video_url","video_url":{"url":...}} and
+ * "input_video". Audio: OpenAI's {"type":"input_audio","input_audio":{"data": base64, "format":
+ * ...}} with any format the decoder admits, or vLLM's {"type":"audio_url","audio_url":{"url":
+ * data URL}}. */
 static int read_media_part(const json& part, const std::string& type, const std::string& field,
                            const OaiDeps& d, const OaiLimits& lim, MediaKind* kind,
                            std::vector* bytes, ApiError* err) {
+    /* A {"url": ...} object or a bare string under `key`, decoded from its data: URL. */
+    auto from_url = [&](const char* key) -> int {
+        const std::string fld = field + "." + key;
+        auto it = part.find(key);
+        std::string url;
+        if (it != part.end() && it->is_object() && it->contains("url") && it->at("url").is_string())
+            url = it->at("url").get();
+        else if (it != part.end() && it->is_string())
+            url = it->get();
+        else {
+            *err = err_bad(fld, "expected {\"url\": ...}");
+            return RAD_E_INVAL;
+        }
+        RAD_TRY(decode_media_url(url, fld + ".url", bytes, err));
+        return 1;
+    };
     const bool is_image = type == "image_url" || type == "input_image";
     const bool is_video = type == "video_url" || type == "input_video";
     if (is_image || is_video) {
@@ -1308,52 +1296,21 @@ static int read_media_part(const json& part, const std::string& type, const std:
         const bool allowed = is_image ? lim.allow_image : lim.allow_video;
         if (!allowed || !d.mm || !d.mm->accepts(*kind)) {
             *err = err_not_implemented(
-                std::string(what) + " input requires a vision encoder (spec 11); this "
+                std::string(what) + " input requires a vision encoder; this "
                 "model was loaded without one");
             return RAD_E_UNSUPPORTED;
         }
-        const std::string key = is_image ? "image_url" : "video_url";
-        const std::string fld = field + "." + key;
-        std::string url;
-        auto iu = part.find(key);
-        if (iu == part.end() && type == "input_image") iu = part.find("image_url");
-        if (iu == part.end() && type == "input_video") iu = part.find("video_url");
-        if (iu != part.end() && iu->is_object() && iu->contains("url") &&
-            iu->at("url").is_string())
-            url = iu->at("url").get();
-        else if (iu != part.end() && iu->is_string())
-            url = iu->get();
-        else {
-            *err = err_bad(fld, "expected {\"url\": ...}");
-            return RAD_E_INVAL;
-        }
-        RAD_TRY(decode_media_url(url, fld + ".url", bytes, err));
-        return 1;
+        return from_url(is_image ? "image_url" : "video_url");
     }
     if (type == "input_audio" || type == "audio_url") {
         *kind = MediaKind::Audio;
         if (!lim.allow_audio || !d.mm || !d.mm->accepts(MediaKind::Audio)) {
             *err = err_not_implemented(
-                "audio input requires an audio encoder (spec 11); this model was loaded "
+                "audio input requires an audio encoder; this model was loaded "
                 "without one");
             return RAD_E_UNSUPPORTED;
         }
-        if (type == "audio_url") {
-            const std::string fld = field + ".audio_url";
-            auto au = part.find("audio_url");
-            std::string url;
-            if (au != part.end() && au->is_object() && au->contains("url") &&
-                au->at("url").is_string())
-                url = au->at("url").get();
-            else if (au != part.end() && au->is_string())
-                url = au->get();
-            else {
-                *err = err_bad(fld, "expected {\"url\": ...}");
-                return RAD_E_INVAL;
-            }
-            RAD_TRY(decode_media_url(url, fld + ".url", bytes, err));
-            return 1;
-        }
+        if (type == "audio_url") return from_url("audio_url");
         auto ia = part.find("input_audio");
         if (ia == part.end() || !ia->is_object() || !ia->contains("data") ||
             !ia->at("data").is_string()) {
@@ -1363,15 +1320,15 @@ static int read_media_part(const json& part, const std::string& type, const std:
         auto fit = ia->find("format");
         const std::string fmt =
             fit != ia->end() && fit->is_string() ? fit->get() : std::string();
-        /* The decoder recognises the container by its bytes; the format is checked against
-         * what it admits so a typo is named here rather than as an undecodable clip. */
+        /* The decoder detects the container from its bytes; the format is checked anyway so a
+         * typo is reported as such rather than as an undecodable clip. */
         static const char* const kAudioFormats[] = { "wav", "mp3", "flac", "ogg", "opus",
                                                      "m4a", "aac", "webm", "aiff" };
-        bool known = false;
-        for (const char* f : kAudioFormats) known = known || fmt == f;
-        if (!known) {
-            *err = err_bad(field + ".input_audio.format",
-                           "must be one of wav, mp3, flac, ogg, opus, m4a, aac, webm, aiff");
+        if (!in_list(kAudioFormats, fmt)) {
+            std::string names;
+            for (const char* f : kAudioFormats)
+                names += (names.empty() ? "" : ", ") + std::string(f);
+            *err = err_bad(field + ".input_audio.format", "must be one of " + names);
             return RAD_E_INVAL;
         }
         if (!base64_decode(ia->at("data").get(), bytes)) {
@@ -1383,6 +1340,32 @@ static int read_media_part(const json& part, const std::string& type, const std:
     return 0;
 }
 
+/* Whether any string in `v` (a key or a value, the media parts' own markers aside) contains
+ * RAD_MEDIA_MARKER. Iterative: the tree is up to kJsonMaxDepth deep. */
+static bool spells_media_marker(const json& v) {
+    std::vector todo = { &v };
+    while (!todo.empty()) {
+        const json* j = todo.back();
+        todo.pop_back();
+        if (j->is_string()) {
+            if (j->get_ref().find(RAD_MEDIA_MARKER) != std::string::npos)
+                return true;
+        } else if (j->is_object()) {
+            auto t = j->find("type");
+            if (t != j->end() && *t == "media_marker") continue;
+            for (auto it = j->begin(); it != j->end(); ++it) {
+                if (it.key().find(RAD_MEDIA_MARKER) != std::string::npos) return true;
+                todo.push_back(&it.value());
+            }
+        } else if (j->is_array()) {
+            for (const json& e : *j) todo.push_back(&e);
+        }
+    }
+    return false;
+}
+
+/* Rewrite content parts in place: text stays, media becomes the marker and its bytes go to
+ * `media` as (kind, bytes) in the order the markers appear in the rendered prompt. */
 static int lower_content_parts(json& messages, const OaiDeps& d, const OaiLimits& lim,
                                std::vector>>* media,
                                ApiError* err) {
@@ -1435,12 +1418,10 @@ static int lower_content_parts(json& messages, const OaiDeps& d, const OaiLimits
                 }
                 continue;
             }
-            /* IMAGE, VIDEO AND AUDIO PARTS (read_media_part). A MEDIA MARKER, NOT TEXT, takes the
-             * part's place: the chat layer flattens a message's parts into one string and joins
-             * TEXT parts with a newline; it joins a marker to its neighbours with nothing, which
-             * is what the model's own template does with an image part (<|vision_end|> runs
-             * straight into the text after it). Joined as text, every picture would cost one
-             * '\n' token the model's own prompt does not have. */
+            /* Media parts (read_media_part) become a media_marker part, not text: the chat layer
+             * joins text parts with a newline but a marker with nothing, matching the model's own
+             * template (<|vision_end|> runs straight into the following text). As text, each
+             * picture would add a '\n' token the model never saw. */
             {
                 MediaKind kind;
                 std::vector bytes;
@@ -1454,7 +1435,7 @@ static int lower_content_parts(json& messages, const OaiDeps& d, const OaiLimits
                                : (type == "image_url" || type == "input_image") ? "image_url"
                                                                                 : "video_url");
                     part["type"] = "media_marker";
-                    part["text"] = MEDIA_MARKER;
+                    part["text"] = RAD_MEDIA_MARKER;
                     continue;
                 }
             }
@@ -1463,32 +1444,38 @@ static int lower_content_parts(json& messages, const OaiDeps& d, const OaiLimits
             return RAD_E_INVAL;
         }
     }
+    /* Beside media, text that spells the marker would be taken for a media part's place in the
+     * rendered prompt (tokenize_with_media); refused, as the embeddings endpoint refuses it. With
+     * no media the marker is plain text. */
+    if (!media->empty() && spells_media_marker(messages)) {
+        *err = err_bad("messages", std::string("a message contains \"") + RAD_MEDIA_MARKER +
+                                       "\", which this server reserves for the place of a media "
+                                       "part, in a request that carries media");
+        return RAD_E_INVAL;
+    }
     return RAD_OK;
 }
 
-/* Tokenise a rendered prompt that contains media markers, replacing each marker with the token
- * run its media part became: the processor's placeholders -- the model's own pad ids, which a
- * hashed n-gram embedding reads like any other -- with whatever markers and timestamps the model
- * wants around them. The encoder's rows replace the placeholders' embeddings later (spec §11);
- * here only the ids and their offsets are fixed, and with them the prompt's rotary layout.
+/* Each marker becomes its media part's token run: the processor's placeholders (the model's pad
+ * ids, which a hashed n-gram embedding reads like any other) with the model's surrounding markers
+ * and timestamps. The encoder's rows replace the placeholder embeddings later (spec §11); here
+ * only the ids and offsets, and so the rotary layout, are fixed.
  *
- * Each media part is processed HERE, on the request's own worker, because decoding a video and
- * resizing its frames is the most expensive host work a request can bring: it must not reach the
- * scheduler's thread, where every other request's step would wait on it. */
+ * Media is processed here, on the request's worker, because decoding and resizing video is the
+ * most expensive host work a request brings and must not stall the scheduler thread. */
 int tokenize_with_media(const std::string& rendered, const OaiDeps& d,
                         std::vector>>& media,
                         const MediaOpts& opts, PromptInput* out, ApiError* err) {
     out->text = rendered;
     auto pm = std::make_shared();
-    const std::string marker = MEDIA_MARKER;
+    const std::string marker = RAD_MEDIA_MARKER;
     size_t pos = 0, mi = 0;
     for (;;) {
         size_t at = rendered.find(marker, pos);
         std::string seg = rendered.substr(pos, at == std::string::npos ? std::string::npos : at - pos);
         if (!seg.empty()) {
-            /* add_special is false for every segment, the first included: the template renders
-             * whatever special tokens the model wants, and an extra BOS would shift every
-             * position after it -- the same reason the text-only path gives. */
+            /* add_special is false for every segment: the template already renders the special
+             * tokens, and an extra BOS would shift every position after it. */
             auto ids = d.tok->encode(seg, false, /*parse_special=*/true);
             out->tokens.insert(out->tokens.end(), ids.begin(), ids.end());
         }
@@ -1531,34 +1518,20 @@ int tokenize_with_media(const std::string& rendered, const OaiDeps& d,
 
 /* ================================================================== the context bound
  *
- * THE CONTEXT CLAMPS max_tokens RATHER THAN REFUSING THE REQUEST.
+ * The context clamps max_tokens instead of refusing the request. max_tokens is an upper bound and
+ * the context is another that holds regardless, so refusing yields no tokens where clamping
+ * yields the same ones. Clients commonly send a fixed large max_tokens and cannot compute the
+ * remaining window without the tokeniser.
  *
- * `max_tokens` is an upper bound -- "stop by here at the latest" -- and the context is a second
- * upper bound that holds whether or not the request acknowledges it: a sequence cannot run past
- * it however many tokens were asked for. So refusing does not produce more tokens than clamping
- * does, it produces none, and the field that caused the refusal could not have been honoured at
- * any value the caller might have sent instead.
+ * A prompt that does not fit on its own is still an error, naming how much to cut.
  *
- * That matters because a fixed `max_tokens` is what clients actually send. A caller whose default
- * is 128k gets a 400 on every prompt long enough to matter -- exactly the requests a long-context
- * server exists for -- and the only fix available to them is to compute the server's remaining
- * window themselves, which they cannot do without knowing the tokeniser.
- *
- * A PROMPT THAT DOES NOT FIT ON ITS OWN IS STILL AN ERROR. There is no window left to generate
- * into, nothing about the request is servable, and the caller has to shorten the prompt -- so that
- * case keeps its refusal and names how much has to go.
- *
- * This is the one deliberate exception to the rule the key vetting above enforces, that a 200
- * means every field of the request was honoured. It is an exception because those keys are
- * SETTINGS -- dropping one serves a different model than the caller asked for -- and this one is a
- * BOUND, whose purpose is to stop generation early and which the context was going to stop earlier
- * anyway. What the caller gets back still says so: the completion ends with finish_reason
- * "length" and `usage` reports the tokens it actually produced.
+ * This is the one exception to "a 200 means every field was honoured": the vetted keys are
+ * settings, this is a bound the context would hit anyway. The reply still says so through
+ * finish_reason "length" and `usage`.
  */
-/* THE DEPLOYMENT'S CAP IS A THIRD BOUND OF THE SAME KIND, clamped for the same reason: a request
- * asking for more than the operator allows is still a request worth serving up to the cap. And a
- * max_tokens of 0 is the `--default-max-tokens auto` default, which is "what the context leaves" --
- * resolved here, against this prompt, so that the scheduler always sees a finite bound. */
+/* The deployment's cap (OaiLimits::max_tokens_cap) clamps the same way. A max_tokens of 0
+ * (the `--default-max-tokens auto` default) means what the context leaves, resolved here
+ * against this prompt so the scheduler always sees a finite bound. */
 static int clamp_max_tokens(size_t n_prompt, const OaiLimits& lim, const char* field,
                             OaiRequest* out, ApiError* err) {
     if (lim.max_tokens_cap > 0 &&
@@ -1569,11 +1542,9 @@ static int clamp_max_tokens(size_t n_prompt, const OaiLimits& lim, const char* f
 
     const int64_t room = lim.max_ctx - (int64_t)n_prompt;
     if (room <= 0) {
-        /* WORDED FOR THE CLIENTS THAT READ IT. An agent compacts its history when a request
-         * overflows, and it recognises the overflow by the error's text: OpenAI's "maximum
-         * context length is N tokens" and llama-server's "exceeds the available context size"
-         * are the two phrases those matchers look for, so the sentence carries both, beside
-         * OpenAI's code and llama-server's two numbers. */
+        /* Agents detect overflow by the message text to compact their history, so the sentence
+         * carries both OpenAI's "maximum context length is N tokens" and llama-server's
+         * "exceeds the available context size", beside OpenAI's code and llama-server's numbers. */
         char msg[384];
         snprintf(msg, sizeof msg,
                  "This model's maximum context length is %lld tokens: the request (%zu tokens) "
@@ -1591,9 +1562,8 @@ static int clamp_max_tokens(size_t n_prompt, const OaiLimits& lim, const char* f
     if (out->max_tokens <= 0) {
         out->max_tokens = (int32_t)std::min(room, INT32_MAX);
     } else if ((int64_t)out->max_tokens > room) {
-        /* Debug rather than Warn: on a long-context deployment whose clients send a constant
-         * max_tokens this fires on every request that is working correctly, and a line printed
-         * per request is how a server's log stops being read at all. */
+        /* Debug, not Warn: clients sending a constant max_tokens trigger this on every normal
+         * request. */
         RAD_DEBUG("max_tokens %d does not fit beside %zu prompt tokens in a %lld token context; "
                   "serving %lld", (int)out->max_tokens, n_prompt, (long long)lim.max_ctx,
                   (long long)room);
@@ -1604,18 +1574,16 @@ static int clamp_max_tokens(size_t n_prompt, const OaiLimits& lim, const char* f
 
 /* ================================================================== chat */
 
-/* THE REASONING BLOCK BY TOKEN ID, and the budget on it.
+/* The reasoning block by token id, and its budget.
  *
- * The render names the block's markers as text; the engine counts and closes it by token, so
- * the markers are encoded here, once per request. A marker that is not one token leaves the span
- * unknown: the reply's reasoning is still split out, but it is not counted and cannot be closed
- * by forcing a token. The opener matters only to a reply that must open its own block.
+ * The render names the markers as text; the engine counts and closes the block by token, so the
+ * markers are encoded here once per request. A marker that is not one token leaves the span
+ * unknown: reasoning is still split out, but not counted and not closable by forcing a token.
+ * The opener matters only when the reply must open its own block.
  *
- * `thinking_token_budget` is vLLM's name for the field and `thinking_budget` Qwen's API's; both
- * are read, as max_tokens and max_completion_tokens are. A budget the span cannot hold is a 400
- * naming why -- accepting it and generating unbounded reasoning is the outcome this file's
- * header forbids. The deployment's default applies only where it can be held: a reply whose
- * block cannot be counted gets none, as it would on a model with no reasoning block at all. */
+ * Budget spellings: vLLM's `thinking_token_budget`, Qwen's `thinking_budget`, and llama.cpp's.
+ * A budget on an unknown span is a 400 naming why, not unbounded reasoning. The deployment's
+ * default applies only where the span is known. */
 static int parse_thinking_budget(const json& b, const OaiDeps& d, const OaiLimits& lim,
                                  const ChatRender& render, SamplingParams* sp, ApiError* err) {
     ReasoningSpan span;
@@ -1626,11 +1594,9 @@ static int parse_thinking_budget(const json& b, const OaiDeps& d, const OaiLimit
         if (!render.think_open.empty()) o = d.tok->encode(render.think_open, false, true);
         n_close = c.size();
         n_open  = o.size();
-        /* AN OPENER THAT IS ONE CONTROL TOKEN AND THEN TEXT -- Gemma 4's `<|channel>thought` --
-         * is found by that first token: it is what a reply opening its own block writes first,
-         * and no text can be. The text after it counts as reasoning, as the markers do. An opener
-         * with a second control token in it (a channel and a message marker) is not read this
-         * way, since its first token may open something other than the reasoning. */
+        /* An opener that is one control token followed by text (Gemma 4's `<|channel>thought`)
+         * is found by that first token; the text after it counts as reasoning. An opener with a
+         * second control token is not, since its first token may open something else. */
         bool open_first = o.size() > 1 && d.tok->reply_bytes(o[0]).empty() &&
                           !d.tok->token_bytes(o[0]).empty();
         for (size_t i = 1; open_first && i < o.size(); ++i)
@@ -1651,8 +1617,8 @@ static int parse_thinking_budget(const json& b, const OaiDeps& d, const OaiLimit
         if (it == b.end() || it->is_null()) continue;
         int64_t v = 0;
         if (!get_int(b, k, &v, err)) return RAD_E_INVAL;
-        /* llama.cpp's spellings take a negative budget for "none": said, it overrides the
-         * deployment's default as a number does. */
+        /* A negative budget means "none" (llama.cpp) and still overrides the deployment's
+         * default. */
         if (v < 0) v = -1;
         if (named && v != budget) {
             *err = err_bad(k, std::string("disagrees with ") + named + ", which is the same field");
@@ -1685,15 +1651,15 @@ static int parse_thinking_budget(const json& b, const OaiDeps& d, const OaiLimit
     return RAD_OK;
 }
 
-/* LOGPROBS, in each endpoint's spelling, into one count.
+/* Logprobs, in each endpoint's spelling, into one count.
  *
  *   chat         `logprobs` true, with `top_logprobs` alternatives (0 when absent, OpenAI's default)
  *   completions  `logprobs` the number of alternatives, OpenAI's legacy integer
  *   any          llama-server's `n_probs`, which wins over both
  *
- * A count of 0 still returns each token's own logprob on chat (OpenAI's meaning) and returns
- * nothing on completions (llama-server's: its `logprobs` 0 and `n_probs` 0 are both "off"). The
- * numbers are the RAW distribution's, as OpenAI and llama-server report them. */
+ * A count of 0 still returns each token's own logprob on chat (OpenAI's meaning) and nothing on
+ * completions (llama-server treats `logprobs` 0 and `n_probs` 0 as off). Values are the raw
+ * distribution's, as OpenAI and llama-server report them. */
 static int parse_logprobs(const json& b, const OaiLimits& lim, Endpoint ep, OaiRequest* out,
                           ApiError* err) {
     bool want = false;
@@ -1766,7 +1732,7 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
 
     if (!d.chat) {
         *err = err_not_implemented(
-            "/v1/chat/completions requires a chat template (spec 12); this model was loaded "
+            "/v1/chat/completions requires a chat template; this model was loaded "
             "without one. Use /v1/completions");
         return RAD_E_UNSUPPORTED;
     }
@@ -1774,9 +1740,8 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
     auto mit = b.find("messages");
     if (mit == b.end()) { *err = err_bad("messages", "is required"); return RAD_E_INVAL; }
     json messages = *mit;
-    /* The deprecated functions API's turns, as the current API spells them: an assistant
-     * message's `function_call` is one tool call, and a `function` message is the result of the
-     * call before it. The call ids pair them; the old API has none. */
+    /* Deprecated functions-API turns in current form: an assistant `function_call` becomes one
+     * tool call and a `function` message its result, paired by synthesised call ids. */
     if (messages.is_array()) {
         std::string call_id;
         int n_calls = 0;
@@ -1800,9 +1765,8 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
             if (!it->is_object() || !it->contains("role") || it->at("role") != "user") continue;
             const auto cit = it->find("content");
             if (cit == it->end()) break;
-            /* At most 160 bytes are kept, so no more than that is copied out of a message that
-             * may be a whole document, and the cut lands on a UTF-8 lead byte: a log line split
-             * inside a character is not valid text. */
+            /* Keep at most 160 bytes, copying no more than that from a possibly huge message,
+             * and cut on a UTF-8 lead byte. */
             constexpr size_t kKeep = 160;
             std::string t;
             auto take = [&t](const std::string& s) {
@@ -1824,10 +1788,10 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
         }
     }
 
-    /* OpenAI's DEPRECATED functions API, which older clients still send: `functions` is `tools`
-     * with each entry unwrapped, and `function_call` is `tool_choice` -- "none", "auto", or
-     * {"name": ...}. Rewritten into the current fields, and refused beside them. The old API
-     * answers one call at most, so the grammar admits one. */
+    /* OpenAI's deprecated functions API: `functions` is `tools` with each entry unwrapped, and
+     * `function_call` is `tool_choice` ("none", "auto" or {"name": ...}). Rewritten into the
+     * current fields and refused alongside them. The old API returns at most one call, so the
+     * grammar admits one. */
     auto fns = b.find("functions");
     if (fns != b.end() && !fns->is_null()) {
         if (b.contains("tools") && !b.at("tools").is_null()) {
@@ -1878,10 +1842,9 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
         out->n_tools = (int)tools.size();
     }
 
-    /* A forced choice -- "required", or an object naming one function -- makes the call grammar
-     * the whole reply instead of a lazy one: the reasoning block, then the calls (one when
-     * `parallel_tool_calls` is false), then nothing, so the reply ends at the last call. A named
-     * function narrows the calls to that one. */
+    /* A forced choice ("required", or an object naming one function) makes the call grammar the
+     * whole reply instead of a lazy one: reasoning, then the calls (one when
+     * `parallel_tool_calls` is false), then the end. A named function narrows the calls to it. */
     std::string tool_choice = "auto", named;
     auto tcit = b.find("tool_choice");
     if (tcit != b.end() && !tcit->is_null()) {
@@ -1927,9 +1890,8 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
         return RAD_E_INVAL;
     }
 
-    /* Honoured by the grammar rather than by a prompt instruction: the auto-parser emits a
-     * repeatable call section only when this is true (chat-auto-parser-generator.cpp), so false
-     * genuinely admits one call and not several. */
+    /* Enforced by the grammar: the auto-parser emits a repeatable call section only when this is
+     * true (chat-auto-parser-generator.cpp). */
     bool parallel = true;
     if (!get_bool(b, "parallel_tool_calls", ¶llel, err)) return RAD_E_INVAL;
 
@@ -1955,9 +1917,9 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
     const bool agp_named = b.contains("add_generation_prompt") && !b.at("add_generation_prompt").is_null();
     if (!get_bool(b, "add_generation_prompt", &opt.add_generation_prompt, err)) return RAD_E_INVAL;
 
-    /* llama.cpp's `reasoning_format`. "none" leaves the reasoning in `content` between the
-     * template's own markers; "auto" and "deepseek" move it to `reasoning_content`, which is what
-     * this server does anyway. "deepseek-legacy" -- both at once -- is not served. */
+    /* llama.cpp's `reasoning_format`: "none" leaves reasoning in `content` between the template's
+     * markers; "auto" and "deepseek" move it to `reasoning_content` (the default behaviour).
+     * "deepseek-legacy" (both at once) is not served. */
     std::string rfmt;
     if (!get_str(b, "reasoning_format", &rfmt, err)) return RAD_E_INVAL;
     if (rfmt == "deepseek-legacy") {
@@ -1970,12 +1932,11 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
         return RAD_E_INVAL;
     }
 
-    /* ASSISTANT PREFILL. A conversation that ends in an assistant message is continued, not
-     * answered: the reply picks up where that message stops. llama.cpp's default and the
-     * Anthropic API's meaning; vLLM's `continue_final_message` names it explicitly, true or
-     * llama.cpp's "content" / "reasoning_content". A request that names `add_generation_prompt`
-     * true opens a new turn after it instead, as vLLM does; naming that and
-     * `continue_final_message` both is a contradiction, refused as llama.cpp refuses it. */
+    /* Assistant prefill: a conversation ending in an assistant message is continued, not
+     * answered (llama.cpp's default and Anthropic's meaning). vLLM's `continue_final_message`
+     * requests it explicitly: true, or llama.cpp's "content" / "reasoning_content". Naming
+     * `add_generation_prompt` opens a new turn instead, as in vLLM; naming it true together with
+     * `continue_final_message` is refused, as in llama.cpp. */
     {
         std::string cont;
         auto cf = b.find("continue_final_message");
@@ -2024,16 +1985,14 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
         }
     }
 
-    /* The template's grammar and the caller's are ONE grammar, not two, and the template is the
-     * one that knows how to combine them -- a tool-calling format has to leave room for the call
-     * syntax around whatever the caller constrained. So both halves go IN and the merged result
-     * comes back out: a raw GBNF as `grammar`, a `response_format` as the schema it started as. */
+    /* The caller's constraint goes into the render, which merges it with the format's tool-call
+     * syntax into one grammar: a raw GBNF as `grammar`, a `response_format` as its schema. */
     opt.grammar     = out->sp.grammar;
     opt.json_schema = schema_json;
 
     RAD_TRY(parse_thinking(b, lim, &opt, err));
-    /* The request's reasoning_format over the deployment's (--reasoning-format), which the
-     * template defaults above have just applied. */
+    /* The request's reasoning_format overrides the deployment's (--reasoning-format), applied by
+     * parse_thinking's template defaults. */
     if (!rfmt.empty()) opt.reasoning_format = rfmt;
 
     std::vector>> media;
@@ -2051,15 +2010,8 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
         return RAD_E_INVAL;
     }
 
-    /* Everything the render decided that the rest of the request has to carry. The grammar can
-     * come back non-empty when none went in -- that is a tool-calling template constraining its
-     * own call syntax -- and it arrives LAZY, so the reply is free prose until the model starts
-     * writing a call. Dropping `grammar_lazy` here would constrain the whole reply to be a tool
-     * call, which is a model that can no longer answer in words. */
-    /* A REQUEST THAT ASKED TO BE CONSTRAINED AND CAME BACK UNCONSTRAINED IS A REFUSAL, not a 200.
-     * `response_format` and `grammar` are promises about the shape of the answer; a template that
-     * returns no grammar for one has not kept it, and returning the answer anyway would leave the
-     * caller parsing free prose against a schema they were told was enforced. */
+    /* A requested constraint that came back without a grammar is refused, not served
+     * unconstrained. */
     if (render.grammar.empty() && !(opt.grammar.empty() && opt.json_schema.empty())) {
         *err = err_unsupported(opt.json_schema.empty() ? "grammar" : "response_format",
                                "this model's chat template produced no grammar for it, so the "
@@ -2067,6 +2019,9 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
         return RAD_E_UNSUPPORTED;
     }
 
+    /* What the render decided. A tool-calling template may return a grammar when none went in;
+     * it is lazy, so the reply is free prose until a call starts. Dropping `grammar_lazy` would
+     * force every reply to be a tool call. */
     out->sp.grammar          = render.grammar;
     out->sp.grammar_lazy     = render.grammar_lazy;
     out->sp.grammar_triggers = render.grammar_triggers;
@@ -2076,39 +2031,27 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
     out->parse_tools         = out->tools_present && render.parser != nullptr;
     RAD_TRY(parse_thinking_budget(b, d, lim, render, &out->sp, err));
 
-    /* The format's own end-of-turn markers join the caller's stop strings rather than living in a
-     * second list: both end the generation and both report `finish_reason: "stop"` (sink.cpp), so
-     * a separate list would be a distinction with no observable difference. */
+    /* The format's end-of-turn markers join the caller's stop strings; both end generation with
+     * `finish_reason: "stop"` (sink.cpp). n_client_stops records where the caller's end. */
     out->n_client_stops = out->stop.size();
     for (const auto& s : render.additional_stops)
         if (std::find(out->stop.begin(), out->stop.end(), s) == out->stop.end())
             out->stop.push_back(s);
 
-    /* A reply that starts inside the reasoning block: its stop strings are the answer's, so they
-     * apply only after the block's closer (Detokenizer::defer_stops_until). The chat format says
-     * whether the rendered prompt leaves the block open and what closes it. */
+    /* A reply starting inside the reasoning block applies its stop strings only after the
+     * block's closer (Detokenizer::defer_stops_until). */
     if (render.think_starts_open && !render.think_close.empty())
         out->stops_after = render.think_close;
 
-    /* Checked HERE, where the answer is still a 400. The grammar being validated may be the
-     * caller's, or one the template produced for its own tool-call syntax; either way the first
-     * moment it can fail is when the automaton is built, and building it on the step path would
-     * mean failing a request that is already streaming. */
-    if (!out->sp.grammar.empty() && d.grammar) {
-        std::string gerr;
-        if (d.grammar->compile(out->sp.grammar, &out->sp.grammar_program, gerr) < 0) {
-            *err = err_bad(out->tools_present ? "tools" : "grammar",
-                           "the grammar this request implies cannot be run: " + gerr);
-            return RAD_E_INVAL;
-        }
-    }
+    /* The grammar may be the caller's or the template's own. */
+    RAD_TRY(compile_grammar(d, out, out->tools_present ? "tools" : "grammar", err));
 
     const std::string& rendered = render.prompt;
 
     PromptInput p;
     if (media.empty()) {
-        /* add_special is false: a chat template renders whatever special tokens the model wants,
-         * including its BOS. Adding another is a silent off-by-one in every position. */
+        /* add_special is false: the template renders the model's special tokens, BOS included;
+         * another would shift every position. */
         p.tokens = d.tok->encode(rendered, false, /*parse_special=*/true);
         p.text = rendered;
     } else {
@@ -2143,23 +2086,13 @@ int parse_completion_request(const std::string& body, const OaiDeps& d, const Oa
     RAD_TRY(parse_sampling(b, lim, out, err));
     RAD_TRY(parse_output_format(b, d, out, err));
 
-    /* Checked HERE for the same reason as on the chat path: a grammar the machine refuses is a
-     * 400 while the request can still be refused, rather than a compile on the scheduler thread
-     * that cancels a request the client was told had been accepted. */
-    if (!out->sp.grammar.empty() && d.grammar) {
-        std::string gerr;
-        if (d.grammar->compile(out->sp.grammar, &out->sp.grammar_program, gerr) < 0) {
-            *err = err_bad(b.contains("grammar") ? "grammar" : "response_format",
-                           "the grammar this request implies cannot be run: " + gerr);
-            return RAD_E_INVAL;
-        }
-    }
+    RAD_TRY(compile_grammar(d, out, b.contains("grammar") ? "grammar" : "response_format", err));
 
     if (!get_bool(b, "echo", &out->echo, err)) return RAD_E_INVAL;
 
-    /* The control tokens this completion's text keeps (llama-server's field): each string is
-     * tokenised by the decoder and every control token in it is rendered rather than dropped.
-     * Bounded as the stop strings are, since the decoder looks each one up per token. */
+    /* llama-server's `preserved_tokens`: control tokens in these strings are rendered in the
+     * text rather than dropped. Bounded like stop strings, since the decoder checks each per
+     * token. */
     {
         auto pt = b.find("preserved_tokens");
         if (pt != b.end() && !pt->is_null()) {
@@ -2181,8 +2114,7 @@ int parse_completion_request(const std::string& body, const OaiDeps& d, const Oa
     }
 
     RAD_TRY(parse_logprobs(b, lim, Endpoint::Completion, out, err));
-    /* `echo` with logprobs asks for the PROMPT's logprobs too, which are not computed: a prompt
-     * position's distribution never leaves the card. */
+    /* `echo` with logprobs would need the prompt's logprobs, which never leave the card. */
     if (out->echo && out->want_logprobs) {
         *err = err_unsupported("echo", "logprobs for the prompt are not returned; send echo "
                                        "without logprobs, or logprobs without echo");
@@ -2195,38 +2127,25 @@ int parse_completion_request(const std::string& body, const OaiDeps& d, const Oa
         return RAD_E_INVAL;
     }
 
-    /* A raw prompt is the client's whole input: no template wraps it and no role is the server's
-     * to protect, so its control tokens are parsed, as vLLM and llama.cpp parse them. A client
-     * that renders its own chat template sends "<|im_start|>" meaning the token; read as text it
-     * reaches the model as six pieces of punctuation. Token ids could name any control token
-     * already. */
+    /* A raw prompt has no template or roles to protect, so control tokens in it are parsed, as
+     * in vLLM and llama.cpp: a client rendering its own template means "<|im_start|>" as the
+     * token. Token ids can name any control token anyway. */
     auto push_text = [&](const std::string& s) {
         PromptInput p;
         p.text = s;
         p.tokens = d.tok->encode(s, true, /*parse_special=*/true);
         out->prompts.push_back(std::move(p));
     };
-    auto push_ids = [&](const json& arr, ApiError* e) -> bool {
+    auto push_ids = [&](const json& arr) -> int {
         PromptInput p;
-        for (const auto& v : arr) {
-            if (!v.is_number_integer()) {
-                *e = err_bad("prompt", "token arrays must contain integers only");
-                return false;
-            }
-            int32_t id = 0;
-            if (!token_id(v, &id)) {
-                *e = err_bad("prompt", "a token id must be in [0, 2147483647], got " + v.dump());
-                return false;
-            }
-            p.tokens.push_back(id);
-        }
+        RAD_TRY(token_ids(arr, "prompt", &p.tokens, err));
         p.text = d.tok->decode(p.tokens);
         out->prompts.push_back(std::move(p));
-        return true;
+        return RAD_OK;
     };
 
-    /* llama-server's mixed prompt: strings and token ids in one array are ONE prompt, the strings
-     * tokenised in place, only the first of them with the BOS. */
+    /* llama-server's mixed prompt: strings and token ids in one array form one prompt, strings
+     * tokenised in place, BOS only on the first element. */
     bool mixed = false;
     if (native && pit->is_array()) {
         bool s = false, n = false;
@@ -2265,14 +2184,14 @@ int parse_completion_request(const std::string& body, const OaiDeps& d, const Oa
                 push_text(s.get());
             }
         } else if (pit->front().is_number_integer()) {
-            if (!push_ids(*pit, err)) return RAD_E_INVAL;
+            RAD_TRY(push_ids(*pit));
         } else if (pit->front().is_array()) {
             for (const auto& a : *pit) {
                 if (!a.is_array()) {
                     *err = err_bad("prompt", "a batch of token arrays must be all arrays");
                     return RAD_E_INVAL;
                 }
-                if (!push_ids(a, err)) return RAD_E_INVAL;
+                RAD_TRY(push_ids(a));
             }
         } else {
             *err = err_bad("prompt", "expected a string, an array of strings, an array of token "
@@ -2284,10 +2203,7 @@ int parse_completion_request(const std::string& body, const OaiDeps& d, const Oa
         return RAD_E_INVAL;
     }
 
-    /* THE LONGEST PROMPT SETS THE CLAMP. This endpoint takes a BATCH of prompts and `max_tokens`
-     * is one field shared by all of them, so clamping against each in turn would leave the last
-     * one's room standing as the answer for every prompt before it -- and a short prompt would be
-     * cut off for a window it was never short of. */
+    /* The batch shares one `max_tokens`, so the longest prompt sets the clamp. */
     size_t longest = 0;
     for (const auto& p : out->prompts) {
         if (p.tokens.empty()) { *err = err_bad("prompt", "tokenised to nothing"); return RAD_E_INVAL; }
@@ -2299,6 +2215,33 @@ int parse_completion_request(const std::string& body, const OaiDeps& d, const Oa
 
 /* ================================================================== embeddings */
 
+/* One embedding input from text and its media, with the tokenizer's special tokens around the
+ * whole. tokenize_with_media adds none, and with no template to place them the tokenizer's own
+ * BOS/EOS rule applies; a BOS shifts the media runs by one. */
+static int embedding_input(const std::string& text,
+                           std::vector>>& media,
+                           const OaiDeps& d, int32_t image_tokens, OaiRequest* out,
+                           ApiError* err) {
+    PromptInput p;
+    if (media.empty()) {
+        p.text = text;
+        p.tokens = d.tok->encode(text, true, /*parse_special=*/true);
+    } else {
+        MediaOpts mo;
+        mo.image_tokens = image_tokens;
+        RAD_TRY(tokenize_with_media(text, d, media, mo, &p, err));
+        const ITokenizer::VocabInfo vi = d.tok->vocab_info();
+        if (vi.add_bos && vi.bos >= 0) {
+            p.tokens.insert(p.tokens.begin(), vi.bos);
+            for (auto& pl : p.media->items) pl.tok += 1;
+            p.media->layout();
+        }
+        if (vi.add_eos && vi.eos >= 0) p.tokens.push_back(vi.eos);
+    }
+    out->prompts.push_back(std::move(p));
+    return RAD_OK;
+}
+
 int parse_embeddings_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim,
                              OaiRequest* out, ApiError* err) {
     json b;
@@ -2329,8 +2272,8 @@ int parse_embeddings_request(const std::string& body, const OaiDeps& d, const Oa
         /* Bounded by the model's width in the handler, which knows it. */
         out->dimensions = dv.get();
     }
-    /* A soft-token budget for this request's images (Gemma 4's processor); the processor refuses
-     * it on a model that sizes images otherwise. */
+    /* A soft-token budget for this request's images (Gemma 4's processor); other processors
+     * refuse it. */
     if (b.contains("image_tokens") && !b.at("image_tokens").is_null()) {
         const json& iv = b.at("image_tokens");
         const int64_t n = iv.is_number_integer() ? iv.get() : 0;
@@ -2341,15 +2284,14 @@ int parse_embeddings_request(const std::string& body, const OaiDeps& d, const Oa
         out->image_tokens = (int32_t)n;
     }
 
-    /* THE NAMED PROMPT: sentence-transformers' `prompt_name`, the model's own text in front of
-     * each text or content-part input. A model that states a default prompt applies it to a
-     * request that names none, as its reference library does. */
+    /* sentence-transformers' `prompt_name`: the model's own text in front of each text or
+     * content-part input. A model's default prompt applies when none is named, as in its
+     * reference library. */
     std::string prefix;
     const bool prompt_named = b.contains("prompt_name") && !b.at("prompt_name").is_null();
     {
         std::string pname;
-        const bool named = prompt_named;
-        if (named) {
+        if (prompt_named) {
             if (!b.at("prompt_name").is_string()) {
                 *err = err_bad("prompt_name", "expected a string");
                 return RAD_E_INVAL;
@@ -2364,15 +2306,15 @@ int parse_embeddings_request(const std::string& body, const OaiDeps& d, const Oa
         }
     }
 
-    /* THE MESSAGES FORM, vLLM's chat embedding: one input rendered through the model's own chat
-     * template (EmbeddingGemma 2's concatenates the system text and then every message's text and
-     * media placeholders), the tokenizer's special tokens around the whole as for an input. */
+    /* vLLM's chat embedding (`messages`): one input rendered by the model's chat template
+     * (EmbeddingGemma 2's concatenates the system text, then each message's text and media
+     * placeholders), with the tokenizer's special tokens around the whole. */
     if (b.contains("messages") && !b.at("messages").is_null()) {
         if (b.contains("input") && !b.at("input").is_null()) {
             *err = err_bad("messages", "a request takes `input` or `messages`, not both");
             return RAD_E_INVAL;
         }
-        if (b.contains("prompt_name") && !b.at("prompt_name").is_null()) {
+        if (prompt_named) {
             *err = err_bad("prompt_name", "a `messages` input is rendered by the chat template "
                                           "and takes no prompt");
             return RAD_E_INVAL;
@@ -2394,59 +2336,34 @@ int parse_embeddings_request(const std::string& body, const OaiDeps& d, const Oa
                                            (why.empty() ? std::string() : ": " + why));
             return RAD_E_INVAL;
         }
-        PromptInput p;
-        if (media.empty()) {
-            p.text = render.prompt;
-            p.tokens = d.tok->encode(render.prompt, true, /*parse_special=*/true);
-        } else {
-            MediaOpts mo;
-            mo.image_tokens = out->image_tokens;
-            RAD_TRY(tokenize_with_media(render.prompt, d, media, mo, &p, err));
-            const ITokenizer::VocabInfo vi = d.tok->vocab_info();
-            if (vi.add_bos && vi.bos >= 0) {
-                p.tokens.insert(p.tokens.begin(), vi.bos);
-                for (auto& pl : p.media->items) pl.tok += 1;
-                p.media->layout();
-            }
-            if (vi.add_eos && vi.eos >= 0) p.tokens.push_back(vi.eos);
-        }
-        out->prompts.push_back(std::move(p));
-        return RAD_OK;
+        return embedding_input(render.prompt, media, d, out->image_tokens, out, err);
     }
 
     auto it = b.find("input");
     if (it == b.end() || it->is_null()) { *err = err_bad("input", "is required"); return RAD_E_INVAL; }
 
-    auto push_ids = [&](const json& arr, ApiError* e) -> bool {
-        /* A prompt is text; token ids take none, and asking for one by name is refused rather
-         * than dropped. A model's default prompt applies to text inputs only. */
+    auto push_ids = [&](const json& arr) -> int {
+        /* A named prompt cannot precede token ids and is refused; a default prompt applies to
+         * text inputs only. */
         if (prompt_named && !prefix.empty()) {
-            *e = err_bad("prompt_name", "a prompt is text and cannot go in front of token ids");
-            return false;
+            *err = err_bad("prompt_name", "a prompt is text and cannot go in front of token ids");
+            return RAD_E_INVAL;
         }
         PromptInput p;
-        for (const auto& v : arr) {
-            if (!v.is_number_integer()) {
-                *e = err_bad("input", "token arrays must contain integers only");
-                return false;
-            }
-            int32_t id = 0;
-            if (!token_id(v, &id)) {
-                *e = err_bad("input", "a token id must be in [0, 2147483647], got " + v.dump());
-                return false;
-            }
-            p.tokens.push_back(id);
-        }
+        RAD_TRY(token_ids(arr, "input", &p.tokens, err));
         out->prompts.push_back(std::move(p));
-        return true;
+        return RAD_OK;
+    };
+    /* Control tokens are parsed as for a /v1/completions prompt: no template wraps the input. */
+    auto push_text = [&](const std::string& s) {
+        std::vector>> none;
+        return embedding_input(prefix + s, none, d, out->image_tokens, out, err);
     };
 
-    /* ONE INPUT OF CONTENT PARTS -- text, images, video, audio, in order -- the same parts a chat
-     * message carries, and one vector for the lot. The parts are joined with nothing between
-     * them and each media part becomes its processor's token run, which is what an embedding
-     * model's own template does (EmbeddingGemma 2's concatenates text and placeholders), and the
-     * tokenizer's own special tokens go around the whole: what HuggingFace's processor feeds the
-     * model. */
+    /* One input of content parts (text, image, video, audio, in order) yields one vector. Parts
+     * are joined with nothing between them, each media part becoming its token run, and the
+     * tokenizer's special tokens go around the whole, matching what HuggingFace's processor feeds
+     * the model (EmbeddingGemma 2's template concatenates text and placeholders). */
     auto push_parts = [&](const json& parts, ApiError* e) -> int {
         std::vector>> media;
         std::string rendered = prefix;
@@ -2467,10 +2384,9 @@ int parse_embeddings_request(const std::string& body, const OaiDeps& d, const Oa
                     return RAD_E_INVAL;
                 }
                 const std::string t = part.at("text").get();
-                /* The marker is how a media part's position survives into tokenisation, so text
-                 * that spells it would be taken for one. */
-                if (t.find(MEDIA_MARKER) != std::string::npos) {
-                    *e = err_bad("input[].text", std::string("contains \"") + MEDIA_MARKER +
+                /* Text containing the marker would be taken for a media part. */
+                if (t.find(RAD_MEDIA_MARKER) != std::string::npos) {
+                    *e = err_bad("input[].text", std::string("contains \"") + RAD_MEDIA_MARKER +
                                                      "\", which this server reserves for media");
                     return RAD_E_INVAL;
                 }
@@ -2486,57 +2402,29 @@ int parse_embeddings_request(const std::string& body, const OaiDeps& d, const Oa
                 return RAD_E_INVAL;
             }
             media.emplace_back(kind, std::move(bytes));
-            rendered += MEDIA_MARKER;
+            rendered += RAD_MEDIA_MARKER;
         }
-        PromptInput p;
-        if (media.empty()) {
-            p.text = rendered;
-            p.tokens = d.tok->encode(rendered, true, /*parse_special=*/true);
-        } else {
-            MediaOpts mo;
-            mo.image_tokens = out->image_tokens;
-            RAD_TRY(tokenize_with_media(rendered, d, media, mo, &p, e));
-            /* tokenize_with_media adds no special tokens (a chat template renders its own);
-             * this input has no template, so the tokenizer's own rule applies around it. */
-            const ITokenizer::VocabInfo vi = d.tok->vocab_info();
-            if (vi.add_bos && vi.bos >= 0) {
-                p.tokens.insert(p.tokens.begin(), vi.bos);
-                for (auto& pl : p.media->items) pl.tok += 1;
-                p.media->layout();
-            }
-            if (vi.add_eos && vi.eos >= 0) p.tokens.push_back(vi.eos);
-        }
-        out->prompts.push_back(std::move(p));
-        return RAD_OK;
+        return embedding_input(rendered, media, d, out->image_tokens, out, e);
     };
     auto is_parts = [](const json& a) { return a.is_array() && !a.empty() && a.front().is_object(); };
 
-    /* Parsed like a /v1/completions prompt, and for the same reason: the input is the client's
-     * own text with no template around it. */
     if (it->is_string()) {
-        PromptInput p;
-        p.text = prefix + it->get();
-        p.tokens = d.tok->encode(p.text, true, /*parse_special=*/true);
-        out->prompts.push_back(std::move(p));
+        RAD_TRY(push_text(it->get()));
     } else if (it->is_array()) {
         if (it->empty()) { *err = err_bad("input", "must not be empty"); return RAD_E_INVAL; }
         if (it->front().is_number_integer()) {
-            if (!push_ids(*it, err)) return RAD_E_INVAL;
+            RAD_TRY(push_ids(*it));
         } else if (is_parts(*it)) {
             RAD_TRY(push_parts(*it, err));
         } else {
-            /* A BATCH: each element its own input -- a string, a token array or an array of
-             * content parts. */
+            /* A batch: each element is one input (a string, a token array or content parts). */
             for (const auto& el : *it) {
                 if (el.is_string()) {
-                    PromptInput p;
-                    p.text = prefix + el.get();
-                    p.tokens = d.tok->encode(p.text, true, /*parse_special=*/true);
-                    out->prompts.push_back(std::move(p));
+                    RAD_TRY(push_text(el.get()));
                 } else if (is_parts(el)) {
                     RAD_TRY(push_parts(el, err));
                 } else if (el.is_array()) {
-                    if (!push_ids(el, err)) return RAD_E_INVAL;
+                    RAD_TRY(push_ids(el));
                 } else {
                     *err = err_bad("input", "expected strings, token arrays or arrays of content "
                                             "parts");
@@ -2549,11 +2437,16 @@ int parse_embeddings_request(const std::string& body, const OaiDeps& d, const Oa
         return RAD_E_INVAL;
     }
 
-    for (const auto& p : out->prompts) {
-        if (p.tokens.empty()) { *err = err_bad("input", "tokenised to nothing"); return RAD_E_INVAL; }
-        if (lim.max_ctx > 0 && (int64_t)p.tokens.size() > lim.max_ctx) {
-            *err = err_bad("input", "exceeds the model context");
+    for (size_t i = 0; i < out->prompts.size(); ++i) {
+        const int64_t n = (int64_t)out->prompts[i].tokens.size();
+        if (n == 0) { *err = err_bad("input", "tokenised to nothing"); return RAD_E_INVAL; }
+        if (lim.max_ctx > 0 && n > lim.max_ctx) {
+            *err = err_bad("input", "input " + std::to_string(i) + " is " + std::to_string(n) +
+                                        " tokens, more than the model context of " +
+                                        std::to_string(lim.max_ctx));
             err->code = "context_length_exceeded";
+            err->n_prompt_tokens = n;
+            err->n_ctx = lim.max_ctx;
             return RAD_E_INVAL;
         }
     }
@@ -2585,9 +2478,8 @@ static json usage_json(const UsageOut& u) {
     o["completion_tokens"] = u.completion;
     o["total_tokens"] = u.prompt + u.completion;
     o["prompt_tokens_details"] = d;
-    /* HOW MUCH OF completion_tokens THE CLIENT NEVER SEES AS CONTENT. Without it a reply cut at
-     * max_tokens inside its reasoning reads as a model that answered nothing; with it the client
-     * can tell the budget went to reasoning. */
+    /* The share of completion_tokens spent reasoning, so a reply cut at max_tokens inside its
+     * reasoning can be told apart from one that answered nothing. */
     if (u.reasoning >= 0) {
         json c;
         c["reasoning_tokens"] = u.reasoning;
@@ -2623,26 +2515,26 @@ json timings_json(const TimingsOut& t) {
     return o;
 }
 
-/* THE USAGE CHUNKS.
- *
- * `stream_options.include_usage` is parsed, validated and accepted on both endpoints, so both
- * streams have to emit it; accepting the field and then not honouring it is the outcome
- * core/server/oai.h's header forbids in its opening paragraph.
- *
- * One contract for both, OpenAI's: an empty choices array, sent after the last content chunk
- * and before [DONE]. Only the `object` differs, because it is a different endpoint's stream. */
-static std::string usage_chunk(const OaiRequest& r, const UsageOut& u, const TimingsOut& t,
-                               const char* object) {
+/* OpenAI's completion object of type `object` around `choices`, as JSON text. */
+static std::string completion_object(const OaiRequest& r, const char* object, json choices,
+                                     const UsageOut& u, const TimingsOut& t) {
     json o;
     o["id"] = r.id;
     o["object"] = object;
     o["created"] = r.created;
     o["model"] = r.model;
     if (!r.system_fingerprint.empty()) o["system_fingerprint"] = r.system_fingerprint;
-    o["choices"] = json::array();
+    o["choices"] = std::move(choices);
     o["usage"] = usage_json(u);
     if (t.valid) o["timings"] = timings_json(t);
-    return sse_event(o.dump());
+    return o.dump();
+}
+
+/* The usage chunk for `stream_options.include_usage`, on both endpoints. OpenAI's contract: an
+ * empty choices array, after the last content chunk and before [DONE]. Only `object` differs. */
+static std::string usage_chunk(const OaiRequest& r, const UsageOut& u, const TimingsOut& t,
+                               const char* object) {
+    return sse_event(completion_object(r, object, json::array(), u, t));
 }
 
 std::string text_usage_chunk(const OaiRequest& r, const UsageOut& u, const TimingsOut& t) {
@@ -2683,9 +2575,9 @@ std::string logprobs_content(const LogprobEntry* e, size_t n) {
     return s;
 }
 
-/* OpenAI's legacy shape: parallel arrays, and the alternatives as one {text: logprob} object a
- * token. Two alternatives with the same text -- distinct ids that decode alike -- collapse to the
- * likelier, which is what that shape can say. */
+/* OpenAI's legacy shape: parallel arrays, and the alternatives as one {text: logprob} object per
+ * token. Alternatives with the same text (distinct ids that decode alike) collapse to the
+ * likelier. */
 static json lp_legacy(const LogprobEntry* e, size_t n, size_t offset) {
     json toks = json::array(), lps = json::array(), tops = json::array(), offs = json::array();
     for (size_t i = 0; i < n; ++i) {
@@ -2695,8 +2587,8 @@ static json lp_legacy(const LogprobEntry* e, size_t n, size_t offset) {
         for (const LogprobAlt& a : e[i].top)
             if (!t.contains(a.text)) t[a.text] = a.logprob;
         tops.push_back(std::move(t));
-        /* Where the token's text starts in the choice's, which is where the one before it ended:
-         * its own `text` can be shorter than what it added (half a character, held back). */
+        /* The token's offset is where the previous one ended: its own `text` can be shorter than
+         * what it added (half a character, held back). */
         offs.push_back(offset);
         offset = e[i].end;
     }
@@ -2739,16 +2631,7 @@ std::string chat_completion_body(const OaiRequest& r, const std::vector& choices,
@@ -2766,16 +2649,7 @@ std::string text_completion_body(const OaiRequest& r, const std::vector>& vecs,
@@ -2835,10 +2709,9 @@ std::string sse_event(const std::string& json_text) {
 }
 
 std::string sse_error(const ApiError& e) {
-    /* A failure after the headers have gone out cannot change the status code, so the error has
-     * to travel in the stream. Clients that ignore it still see the stream end; clients that read
-     * it get the reason instead of a truncated answer. */
-    return "data: " + e.dump() + "\n\n";
+    /* After the headers are sent the status cannot change, so the error travels in the
+     * stream. */
+    return sse_event(e.dump());
 }
 
 /* ================================================================== the streaming path */
@@ -2847,9 +2720,8 @@ ReplyStream::ReplyStream(const OaiRequest& r, int index, const IReplyParser* par
     : reader_(parser ? parser->open() : nullptr), id_(r.id), model_(r.model),
       fingerprint_(r.system_fingerprint), created_(r.created), index_(index) {}
 
-/* What one increment adds to the message the stream adds up to, and the id a call is announced
- * with: minted here, because the parser reads the model's text and the model writes none. Returns
- * false for an increment that adds nothing and is not sent. */
+/* Fold one increment into `last_`. Call ids are minted here, since the model writes none.
+ * Returns false for an increment that adds nothing and is not sent. */
 bool ReplyStream::absorb(const ReplyDelta& d) {
     switch (d.kind) {
     case ReplyDelta::Reasoning:
@@ -2881,7 +2753,7 @@ std::string ReplyStream::push(std::string_view appended, bool is_final) {
     if (finished_) return std::string();
     std::string out;
     if (!reader_) {
-        /* Nothing to parse: the text is the answer, as it arrives. */
+        /* No parser: the text is the content as it arrives. */
         if (!appended.empty()) {
             ev_.clear();
             ReplyDelta d;
@@ -2899,8 +2771,7 @@ std::string ReplyStream::push(std::string_view appended, bool is_final) {
     out = emit(ev_);
     if (is_final) {
         finished_ = true;
-        /* The reader's message is the reply by definition; the deltas above add up to it, and
-         * the ids are the ones this stream minted. */
+        /* The reader's message is authoritative; keep the call ids this stream minted. */
         ParsedMessage m = reader_->message();
         for (size_t i = 0; i < m.tool_calls.size() && i < last_.tool_calls.size(); ++i)
             m.tool_calls[i].id = last_.tool_calls[i].id;
@@ -2922,9 +2793,8 @@ bool calls_complete(const ParsedMessage& m) {
 
 Finish ReplyStream::adjusted_finish(Finish f) const {
     if (f != Finish::Stop && f != Finish::StopString) return f;
-    /* Only claim tool_calls if every call closed and its arguments parse. A truncated arguments
-     * object reported as a tool call is a tool invoked with the wrong arguments (json_partial.h).
-     * The deltas of an open call have gone out already; the finish reason says not to run it. */
+    /* Claim tool_calls only if every call closed and its arguments parse (json_partial.h), so a
+     * truncated call is not run. Its deltas have already been sent. */
     return calls_complete(last_) ? Finish::ToolCalls : f;
 }
 
@@ -2952,8 +2822,8 @@ std::string ChatDeltaStream::chunk(json delta, const char* finish_reason, const
 }
 
 void ChatDeltaStream::delta_open(std::string& out) {
-    /* Built from nlohmann's own serialisation of each field, on first use rather than in the
-     * constructor, so a field nlohmann refuses throws where chunk() would have. */
+    /* Built from nlohmann's serialisation of each field, on first use rather than in the
+     * constructor, so a field nlohmann refuses throws where chunk() would. */
     if (head_.empty())
         head_ = "data: {\"id\":" + json(id_).dump() +
                 ",\"object\":\"chat.completion.chunk\",\"created\":" + json(created_).dump() +
@@ -2989,30 +2859,39 @@ void ChatDeltaStream::set_timings(const TimingsOut& t) {
     if (t.valid) timings_ = "\"timings\":" + timings_json(t).dump();
 }
 
-/* Text that is not well-formed UTF-8 goes to nlohmann, which refuses it with the exception the
- * tree in chunk() raises for it. */
+/* Malformed UTF-8 falls back to nlohmann, which throws the same exception chunk() would. */
 void ReplyStream::quote(std::string& out, std::string_view s) {
     if (!json_quote_append(out, s)) out += json(std::string(s)).dump();
 }
 
-std::string ChatDeltaStream::first_chunk() {
-    json d;
-    d["role"] = "assistant";
-    d["content"] = "";
-    return chunk(std::move(d), nullptr);
+std::string ChatDeltaStream::first_chunk() { return std::string(); }
+
+std::string ChatDeltaStream::started() {
+    std::string out;
+    open_role(out);
+    return out;
 }
 
-/* One SSE chunk per increment, in the order the reader completed them. A call is announced with
- * its id, name and empty arguments before any of its arguments flow -- an entry with no name is
- * an index the client can never resolve. */
+/* The bytes chunk() writes for this delta, without taking the pending logprobs or timings,
+ * which belong to the output chunk that follows. */
+void ChatDeltaStream::open_role(std::string& out) {
+    if (role_sent_) return;
+    role_sent_ = true;
+    delta_open(out);
+    out += "{\"role\":\"assistant\",\"content\":\"\"},\"finish_reason\":null}]}\n\n";
+}
+
+/* One SSE chunk per increment, in reader order. A call is announced with its id, name and empty
+ * arguments before its arguments flow, since clients cannot resolve an unnamed entry. */
 std::string ChatDeltaStream::emit(const std::vector& ev) {
     std::string out;
     for (const ReplyDelta& d : ev) {
         if (!absorb(d) || d.kind == ReplyDelta::CallEnd) continue;
-        /* The functions API has one call; a second one past the grammar's one is not sent. */
+        /* The functions API has one call; any further call is not sent. */
         if (legacy_ && (d.kind == ReplyDelta::CallBegin || d.kind == ReplyDelta::CallArgs) &&
             (d.kind == ReplyDelta::CallBegin ? last_.tool_calls.size() - 1 : d.call) > 0)
             continue;
+        open_role(out);
         delta_open(out);
         switch (d.kind) {
         case ReplyDelta::Reasoning:
@@ -3064,9 +2943,9 @@ std::string ChatDeltaStream::emit(const std::vector& ev) {
 }
 
 std::string ChatDeltaStream::final_chunk(Finish f, const TimingsOut& t, const UsageOut&) {
-    /* The generation is over, so whatever the reader was holding is resolved now. A caller that
-     * already said so gets nothing twice. */
+    /* Resolve whatever the reader holds; a no-op if push already saw is_final. */
     std::string out = push(std::string_view(), true);
+    open_role(out);
     const Finish a = adjusted_finish(f);
     out += chunk(json::object(), legacy_ && a == Finish::ToolCalls ? "function_call"
                                                                    : finish_reason_oai(a), &t);
@@ -3077,11 +2956,10 @@ std::string ChatDeltaStream::final_chunk(Finish f, const TimingsOut& t, const Us
 
 namespace {
 
-/* CLAUDE CODE STAMPS EVERY REQUEST'S SYSTEM PROMPT. Its first block opens
- * `x-anthropic-billing-header: cc_version=...; cc_entrypoint=cli; cch=a5145;` and the cch value
- * changes per request, so the very first tokens of the prompt differ every turn and the prefix
- * cache can never reuse a conversation. It is an integrity stamp for Anthropic's billing and
- * means nothing to a model; held constant, as llama-server holds it. */
+/* Claude Code's system prompt opens with
+ * `x-anthropic-billing-header: cc_version=...; cc_entrypoint=cli; cch=a5145;` where cch changes
+ * per request, so the prompt's first tokens differ every turn and defeat the prefix cache. It is
+ * a billing stamp meaningless to the model, held constant as in llama-server. */
 void hold_billing_stamp(std::string& s) {
     static const char kHead[] = "x-anthropic-billing-header:";
     if (s.rfind(kHead, 0) != 0) return;
@@ -3092,9 +2970,8 @@ void hold_billing_stamp(std::string& s) {
     for (size_t i = at + 4; i < end; ++i) s[i] = 'f';
 }
 
-/* An image block's source as the content part the chat path reads. A URL source stays a URL,
- * which the chat path refuses as it refuses every remote fetch (decode_media_url). `at` names the
- * block in a refusal. */
+/* An image block's source as a chat content part. A URL source stays a URL, which the chat path
+ * refuses like every remote fetch (decode_media_url). `at` names the block in a refusal. */
 int anthropic_image(const json& block, const std::string& at, json* out, ApiError* err) {
     auto sit = block.find("source");
     if (sit == block.end() || !sit->is_object()) {
@@ -3117,22 +2994,314 @@ int anthropic_image(const json& block, const std::string& at, json* out, ApiErro
     return RAD_OK;
 }
 
+/* The top-level fields of a Messages request. Anthropic's API refuses a field it does not
+ * define, and its clients send beta fields that change what the request means (a `thread`
+ * continuation sends only the tail of the conversation), so a field outside these lists is
+ * refused by name rather than ignored. The refusal says "Extra inputs are not permitted", as
+ * Anthropic's does; Claude Code matches those words to retry without a beta field it can
+ * drop. */
+const char* kAnthropicFields[] = {
+    "model", "messages", "system", "max_tokens", "temperature", "top_p", "top_k", "stream",
+    "stop_sequences", "tools", "tool_choice", "thinking", "metadata", "output_config",
+    "output_format", "context_management", "thread",
+};
+
+/* Accepted and not acted on: none of them can change the answer here. Capacity and placement
+ * (`service_tier`, `inference_geo`, `speed`), prompt-cache control (`cache_control`,
+ * `diagnostics`; the prefix cache is the server's own), and the inputs of Anthropic's
+ * classifiers and refusal fallbacks (`safeguards`, `fallbacks`, `context_hint`), which do not
+ * run here. */
+const char* kAnthropicInert[] = {
+    "service_tier", "inference_geo", "speed", "cache_control", "diagnostics",
+    "safeguards", "fallbacks", "context_hint",
+};
+
+struct AnthropicRefusal {
+    const char* key;
+    const char* why;
+};
+/* Known, not served, and able to change the answer. */
+const AnthropicRefusal kAnthropicRefused[] = {
+    { "mcp_servers", "remote MCP servers are not connected from here; send their tools in "
+                     "`tools` and their results back as tool_result blocks" },
+    { "container", "code execution containers are not served" },
+};
+
+int vet_anthropic_fields(const json& b, ApiError* err) {
+    for (auto it = b.begin(); it != b.end(); ++it) {
+        const std::string& k = it.key();
+        if (in_list(kAnthropicFields, k) || in_list(kAnthropicInert, k)) continue;
+        for (const AnthropicRefusal& r : kAnthropicRefused) {
+            if (k != r.key) continue;
+            *err = err_unsupported(k, r.why);
+            return RAD_E_UNSUPPORTED;
+        }
+        *err = err_unsupported(k, "Extra inputs are not permitted: this server does not serve "
+                                  "the field, and one it does not know could change the answer");
+        return RAD_E_UNSUPPORTED;
+    }
+    return RAD_OK;
+}
+
+/* Anthropic's effort levels. */
+bool anthropic_effort(const json& v) {
+    if (!v.is_string()) return false;
+    const std::string& s = v.get_ref();
+    return s == "low" || s == "medium" || s == "high" || s == "xhigh" || s == "max";
+}
+
+/* `output_config` (or the deprecated top-level `output_format`, the same schema): `effort`
+ * becomes the chat request's `reasoning_effort`, which the chat template takes as its own level
+ * names (a level it does not take is refused there, and --reasoning-effort-map renames them);
+ * `format` becomes `response_format`. `task_budget` is a pacing hint the model is shown on
+ * Anthropic's side; nothing here shows it, so it is accepted and not acted on. */
+int anthropic_output_config(const json& b, json* o, ApiError* err) {
+    auto put_format = [o, err](const json& f, const std::string& at) {
+        std::string type;
+        if (!f.is_object() || !member_str(f, "type", (at + ".type").c_str(), &type, err)) {
+            if (!f.is_object()) *err = err_bad(at, "expected an object");
+            return false;
+        }
+        auto s = f.find("schema");
+        if (type != "json_schema" || s == f.end() || !s->is_object()) {
+            *err = err_bad(at, "expected {\"type\":\"json_schema\",\"schema\":{...}}");
+            return false;
+        }
+        (*o)["response_format"] = json{ { "type", "json_schema" },
+                                        { "json_schema", { { "name", "output" },
+                                                           { "schema", *s } } } };
+        return true;
+    };
+    auto of = b.find("output_format");
+    const bool legacy = of != b.end() && !of->is_null();
+    auto oc = b.find("output_config");
+    if (oc == b.end() || oc->is_null()) {
+        if (legacy && !put_format(*of, "output_format")) return RAD_E_INVAL;
+        return RAD_OK;
+    }
+    if (!oc->is_object()) { *err = err_bad("output_config", "expected an object"); return RAD_E_INVAL; }
+    for (auto it = oc->begin(); it != oc->end(); ++it) {
+        const std::string& k = it.key();
+        const json& v = it.value();
+        if (k == "effort") {
+            if (!anthropic_effort(v)) {
+                *err = err_bad("output_config.effort",
+                               "must be \"low\", \"medium\", \"high\", \"xhigh\" or \"max\"");
+                return RAD_E_INVAL;
+            }
+            (*o)["reasoning_effort"] = v;
+        } else if (k == "format") {
+            if (legacy) {
+                *err = err_bad("output_format", "cannot be combined with output_config.format");
+                return RAD_E_INVAL;
+            }
+            if (!put_format(v, "output_config.format")) return RAD_E_INVAL;
+        } else if (k == "task_budget") {
+            if (!v.is_object()) {
+                *err = err_bad("output_config.task_budget", "expected an object");
+                return RAD_E_INVAL;
+            }
+        } else {
+            *err = err_unsupported("output_config." + k, "Extra inputs are not permitted");
+            return RAD_E_UNSUPPORTED;
+        }
+    }
+    if (legacy && !o->contains("response_format") && !put_format(*of, "output_format"))
+        return RAD_E_INVAL;
+    return RAD_OK;
+}
+
+/* `context_management` asks for edits of the conversation's history (clearing old tool uses or
+ * thinking) before the model reads it. The conversation is served as sent, so the request is
+ * taken and its answer reports that no edit was applied (`applied_edits: []`), which is
+ * Anthropic's own report for a request no edit triggered on. */
+int anthropic_context_management(const json& b, bool* sent, ApiError* err) {
+    auto cm = b.find("context_management");
+    if (cm == b.end() || cm->is_null()) return RAD_OK;
+    if (!cm->is_object()) {
+        *err = err_bad("context_management", "expected an object");
+        return RAD_E_INVAL;
+    }
+    auto ed = cm->find("edits");
+    if (ed != cm->end() && !ed->is_null()) {
+        if (!ed->is_array()) {
+            *err = err_bad("context_management.edits", "expected an array");
+            return RAD_E_INVAL;
+        }
+        for (const json& e : *ed)
+            if (!e.is_object() || !e.contains("type") || !e.at("type").is_string()) {
+                *err = err_bad("context_management.edits[]", "expected an object with a `type`");
+                return RAD_E_INVAL;
+            }
+    }
+    if (sent) *sent = true;
+    return RAD_OK;
+}
+
+/* `thread` asks Anthropic to keep the conversation server-side. `create` sends the whole
+ * conversation and is served as any request; `continue` sends only what follows a stored
+ * message, and nothing is stored here. */
+int anthropic_thread(const json& b, ApiError* err) {
+    auto th = b.find("thread");
+    if (th == b.end() || th->is_null()) return RAD_OK;
+    std::string type;
+    if (!th->is_object() || !member_str(*th, "type", "thread.type", &type, err)) {
+        if (!th->is_object()) *err = err_bad("thread", "expected an object");
+        return RAD_E_INVAL;
+    }
+    if (type == "create") return RAD_OK;
+    if (type == "continue") {
+        *err = err_unsupported("thread", "conversations are not stored here, so a thread cannot "
+                               "be continued; send the whole conversation in `messages`");
+        return RAD_E_UNSUPPORTED;
+    }
+    *err = err_bad("thread.type", "must be \"create\" or \"continue\", got \"" + type + "\"");
+    return RAD_E_INVAL;
+}
+
+/* A system message's text: a string or text blocks, joined with newlines. An effort-only
+ * message (no text beside an `output_config`) yields "" and sets `*effort`. */
+int system_message(const json& m, std::string* out, json* effort, ApiError* err) {
+    for (auto it = m.begin(); it != m.end(); ++it)
+        if (it.key() != "role" && it.key() != "content" && it.key() != "clear_at" &&
+            it.key() != "output_config") {
+            *err = err_unsupported("messages[]." + it.key(), "Extra inputs are not permitted "
+                                   "on a system message");
+            return RAD_E_UNSUPPORTED;
+        }
+    auto oc = m.find("output_config");
+    if (oc != m.end() && !oc->is_null()) {
+        if (!oc->is_object() || oc->size() != 1 || !oc->contains("effort") ||
+            !anthropic_effort(oc->at("effort"))) {
+            *err = err_bad("messages[].output_config",
+                           "expected {\"effort\": \"low\"|\"medium\"|\"high\"|\"xhigh\"|\"max\"}");
+            return RAD_E_INVAL;
+        }
+        *effort = oc->at("effort");
+    }
+    auto c = m.find("content");
+    std::string t;
+    if (c == m.end() || c->is_null()) {
+    } else if (c->is_string()) {
+        t = c->get();
+    } else if (c->is_array()) {
+        for (const json& blk : *c) {
+            const std::string type = str_or(blk, "type");
+            if (type != "text") {
+                *err = err_unsupported("messages[].content[].type", "a system message carries "
+                                       "text blocks only, not \"" + type + "\"");
+                return RAD_E_UNSUPPORTED;
+            }
+            std::string bt;
+            if (!member_str(blk, "text", "messages[].content[].text", &bt, err)) return RAD_E_INVAL;
+            if (!t.empty()) t += "\n";
+            t += bt;
+        }
+    } else {
+        *err = err_bad("messages[].content", "expected a string or text blocks");
+        return RAD_E_INVAL;
+    }
+    if (t.empty() && effort->is_null()) {
+        *err = err_bad("messages[].content", "must not be empty");
+        return RAD_E_INVAL;
+    }
+    *out = std::move(t);
+    return RAD_OK;
+}
+
+bool user_after(const json& msgs, size_t at) {
+    for (size_t j = at + 1; j < msgs.size(); ++j)
+        if (msgs[j].is_object() && str_or(msgs[j], "role") == "user") return true;
+    return false;
+}
+
+/* A system message as the conversation reads it: its text, "" when there is none to render,
+ * and the effort it sets. `clear_at: "next_user_message"` renders the text until a later user
+ * message (a tool_result-only one included) exists, then never again. An effort applies from
+ * the next user message on, so one after the last user message does not apply to this reply. */
+int system_turn(const json& msgs, size_t at, std::string* text, json* effort, ApiError* err) {
+    json e;
+    RAD_TRY(system_message(msgs[at], text, &e, err));
+    std::string when = "never";
+    if (!member_str(msgs[at], "clear_at", "messages[].clear_at", &when, err)) return RAD_E_INVAL;
+    if (when != "never" && when != "next_user_message") {
+        *err = err_bad("messages[].clear_at",
+                       "must be \"never\" or \"next_user_message\", got \"" + when + "\"");
+        return RAD_E_INVAL;
+    }
+    const bool later = user_after(msgs, at);
+    if (when == "next_user_message" && later) text->clear();
+    if (!e.is_null() && later) *effort = std::move(e);
+    return RAD_OK;
+}
+
+/* Marks, while the conversation is lowered, a user message that holds a system message's text. */
+const char kLowered[] = "rad_lowered_system";
+
+/* Each run of system texts lowered from later system messages joins a neighbouring user message
+ * as text blocks, in order: the user message right after the run, else the one right before
+ * it, else one user message of their own. A user message of its own beside another would be
+ * two user turns in a row, which templates that enforce alternation refuse. A newline sits
+ * between a folded text and the user's own, since some templates join text blocks with
+ * nothing. */
+json fold_lowered_system(json msgs) {
+    json out = json::array();
+    auto blocks = [](json& m) {
+        if (m["content"].is_string())
+            m["content"] = json::array({ json{ { "type", "text" }, { "text", m["content"] } } });
+    };
+    auto text = [](std::string t) { return json{ { "type", "text" }, { "text", std::move(t) } }; };
+    for (size_t k = 0; k < msgs.size();) {
+        if (!msgs[k].contains(kLowered)) {
+            out.push_back(std::move(msgs[k++]));
+            continue;
+        }
+        std::vector run;
+        for (; k < msgs.size() && msgs[k].contains(kLowered); ++k)
+            run.push_back(msgs[k]["content"].get());
+        if (k < msgs.size() && str_or(msgs[k], "role") == "user") {
+            json& next = msgs[k];
+            blocks(next);
+            json parts = json::array();
+            for (std::string& t : run) parts.push_back(text(std::move(t) + "\n"));
+            for (json& p : next["content"]) parts.push_back(std::move(p));
+            next["content"] = std::move(parts);
+        } else if (!out.empty() && str_or(out.back(), "role") == "user") {
+            blocks(out.back());
+            for (std::string& t : run) out.back()["content"].push_back(text("\n" + t));
+        } else {
+            std::string joined;
+            for (const std::string& t : run) joined += (joined.empty() ? "" : "\n") + t;
+            out.push_back(json{ { "role", "user" }, { "content", joined } });
+        }
+    }
+    return out;
+}
+
 }  /* namespace */
 
 int anthropic_to_chat(const std::string& body, const OaiLimits& lim, std::string* chat,
-                      std::string* label, ApiError* err) {
+                      std::string* label, ApiError* err, bool* context_management) {
     json b;
     RAD_TRY(parse_request_object(body, lim, &b, err));
+    RAD_TRY(vet_anthropic_fields(b, err));
+    RAD_TRY(anthropic_thread(b, err));
+    RAD_TRY(anthropic_context_management(b, context_management, err));
     json o = json::object();
     json msgs = json::array();
 
-    /* The system prompt: a string or text blocks, which become one system message. */
+    /* The system prompt: the `system` field (a string or text blocks) and the system messages
+     * at the head of the conversation, as one system message. The templates read a system
+     * message only where it leads, so the text of a later one joins a user message at its
+     * position (fold_lowered_system). */
+    std::string sys_text;
+    bool has_system = false;
     auto sys = b.find("system");
     if (sys != b.end() && !sys->is_null()) {
-        std::string text;
+        has_system = true;
         if (sys->is_string()) {
-            text = sys->get();
-            hold_billing_stamp(text);
+            sys_text = sys->get();
+            hold_billing_stamp(sys_text);
         } else if (sys->is_array()) {
             for (const json& blk : *sys) {
                 if (str_or(blk, "type") != "text") {
@@ -3142,14 +3311,13 @@ int anthropic_to_chat(const std::string& body, const OaiLimits& lim, std::string
                 std::string t;
                 if (!member_str(blk, "text", "system[].text", &t, err)) return RAD_E_INVAL;
                 hold_billing_stamp(t);
-                if (!text.empty()) text += "\n";
-                text += t;
+                if (!sys_text.empty()) sys_text += "\n";
+                sys_text += t;
             }
         } else {
             *err = err_bad("system", "expected a string or text blocks");
             return RAD_E_INVAL;
         }
-        msgs.push_back(json{ { "role", "system" }, { "content", text } });
     }
 
     auto mit = b.find("messages");
@@ -3157,12 +3325,37 @@ int anthropic_to_chat(const std::string& body, const OaiLimits& lim, std::string
         *err = err_bad("messages", "is required, as an array");
         return RAD_E_INVAL;
     }
-    for (const json& m : *mit) {
+    /* The effort a system message sets, which overrides the top-level one. */
+    json effort;
+    size_t i = 0;
+    for (; i < mit->size(); ++i) {
+        const json& m = (*mit)[i];
+        if (!m.is_object() || str_or(m, "role") != "system") break;
+        std::string t;
+        RAD_TRY(system_turn(*mit, i, &t, &effort, err));
+        if (t.empty()) continue;
+        hold_billing_stamp(t);
+        if (!sys_text.empty()) sys_text += "\n\n";
+        sys_text += t;
+        has_system = true;
+    }
+    if (has_system) msgs.push_back(json{ { "role", "system" }, { "content", sys_text } });
+
+    for (; i < mit->size(); ++i) {
+        const json& m = (*mit)[i];
         if (!m.is_object()) { *err = err_bad("messages[]", "expected an object"); return RAD_E_INVAL; }
         std::string role;
         if (!member_str(m, "role", "messages[].role", &role, err)) return RAD_E_INVAL;
+        if (role == "system") {
+            std::string t;
+            RAD_TRY(system_turn(*mit, i, &t, &effort, err));
+            if (!t.empty())
+                msgs.push_back(json{ { "role", "user" }, { "content", t }, { kLowered, true } });
+            continue;
+        }
         if (role != "user" && role != "assistant") {
-            *err = err_bad("messages[].role", "must be \"user\" or \"assistant\", got \"" + role + "\"");
+            *err = err_bad("messages[].role",
+                           "must be \"user\", \"assistant\" or \"system\", got \"" + role + "\"");
             return RAD_E_INVAL;
         }
         const json content = m.contains("content") ? m.at("content") : json();
@@ -3174,10 +3367,9 @@ int anthropic_to_chat(const std::string& body, const OaiLimits& lim, std::string
             *err = err_bad("messages[].content", "expected a string or content blocks");
             return RAD_E_INVAL;
         }
-        /* THE TOOL RESULTS GO FIRST. Anthropic carries them in the user turn that follows the
-         * calls, beside whatever the user says next; the chat format wants each one as a tool
-         * message directly after the assistant turn that made the call, and the user's own words
-         * after them. */
+        /* Tool results go first. Anthropic puts them in the user turn after the calls, beside the
+         * user's next words; the chat format wants each as a tool message right after the calling
+         * assistant turn, with the user's words after them. */
         json parts = json::array(), calls = json::array(), results = json::array();
         std::string reasoning;
         for (const json& blk : content) {
@@ -3207,10 +3399,15 @@ int anthropic_to_chat(const std::string& body, const OaiLimits& lim, std::string
                 if (!member_str(blk, "id", "messages[].content[].id", &id, err) ||
                     !member_str(blk, "name", "messages[].content[].name", &name, err))
                     return RAD_E_INVAL;
+                const json input = blk.value("input", json::object());
+                if (!input.is_object()) {
+                    *err = err_bad("messages[].content[].input", "expected an object");
+                    return RAD_E_INVAL;
+                }
                 calls.push_back(json{ { "id", id },
                                       { "type", "function" },
                                       { "function", { { "name", name },
-                                                      { "arguments", blk.value("input", json::object()).dump() } } } });
+                                                      { "arguments", input.dump() } } } });
             } else if (type == "tool_result") {
                 std::string use_id;
                 if (!member_str(blk, "tool_use_id", "messages[].content[].tool_use_id", &use_id, err))
@@ -3256,8 +3453,8 @@ int anthropic_to_chat(const std::string& body, const OaiLimits& lim, std::string
                                         { "tool_call_id", use_id },
                                         { "content", tc } });
             } else {
-                /* A block that would change the answer and that this server cannot serve --
-                 * documents, server tools' results -- is refused by name, not dropped. */
+                /* Unservable blocks that would change the answer (documents, server tool
+                 * results) are refused by name, not dropped. */
                 *err = err_unsupported("messages[].content[].type",
                                        "a content block of type \"" + type + "\" is not served");
                 return RAD_E_UNSUPPORTED;
@@ -3267,7 +3464,7 @@ int anthropic_to_chat(const std::string& body, const OaiLimits& lim, std::string
         if (parts.empty() && calls.empty() && reasoning.empty()) continue;
         json nm = { { "role", role } };
         if (role == "assistant") {
-            /* An assistant turn's text is one string, which is what every template renders. */
+            /* An assistant turn's text is one string, as every template renders it. */
             std::string text;
             for (const json& p : parts)
                 if (p.at("type") == "text") text += p.at("text").get();
@@ -3279,11 +3476,15 @@ int anthropic_to_chat(const std::string& body, const OaiLimits& lim, std::string
         if (!reasoning.empty()) nm["reasoning_content"] = reasoning;
         msgs.push_back(std::move(nm));
     }
-    o["messages"] = std::move(msgs);
+    o["messages"] = fold_lowered_system(std::move(msgs));
 
-    /* Client tools are functions. A server tool -- Anthropic's own web search or code
-     * execution, named by `type` -- runs on Anthropic's side and has no counterpart here. */
+    /* Client tools become functions. Server tools (Anthropic's web search, code execution,
+     * named by `type`) run on Anthropic's side and are refused. */
     auto tit = b.find("tools");
+    if (tit != b.end() && !tit->is_null() && !tit->is_array()) {
+        *err = err_bad("tools", "expected an array");
+        return RAD_E_INVAL;
+    }
     if (tit != b.end() && tit->is_array() && !tit->empty()) {
         json tools = json::array();
         for (const json& t : *tit) {
@@ -3304,7 +3505,21 @@ int anthropic_to_chat(const std::string& body, const OaiLimits& lim, std::string
         o["tools"] = std::move(tools);
     }
     auto tc = b.find("tool_choice");
-    if (tc != b.end() && tc->is_object()) {
+    if (tc != b.end() && tc->is_string()) {
+        /* The string form: "auto" and "none" as the chat path takes them, "any" as its
+         * "required". Naming a tool takes the object form. */
+        const std::string v = tc->get();
+        if (v == "auto" || v == "none") o["tool_choice"] = v;
+        else if (v == "any") o["tool_choice"] = "required";
+        else {
+            *err = err_bad("tool_choice", "must be \"auto\", \"any\", \"none\" or an object, got "
+                                           "\"" + v + "\"");
+            return RAD_E_INVAL;
+        }
+    } else if (tc != b.end() && !tc->is_null() && !tc->is_object()) {
+        *err = err_bad("tool_choice", "expected a string or an object");
+        return RAD_E_INVAL;
+    } else if (tc != b.end() && tc->is_object()) {
         std::string type = "auto", name;
         if (!member_str(*tc, "type", "tool_choice.type", &type, err) ||
             !member_str(*tc, "name", "tool_choice.name", &name, err))
@@ -3322,29 +3537,49 @@ int anthropic_to_chat(const std::string& body, const OaiLimits& lim, std::string
         if (one) o["parallel_tool_calls"] = false;
     }
 
-    /* `model` too, which the reply names back as Anthropic's does. */
+    /* `model` included, since the reply names it back as Anthropic's does. */
     for (const char* k : { "model", "max_tokens", "temperature", "top_p", "top_k", "stream" })
         if (b.contains(k)) o[k] = b.at(k);
     if (b.contains("stop_sequences")) o["stop"] = b.at("stop_sequences");
 
-    /* Extended thinking: on with a budget, off, or on with the template's own judgement. */
+    /* Extended thinking: on with a budget, off, or on with the template's own judgement;
+     * `between_tools` is how the newest models turn it off. `display` and `block_binding` are
+     * about how Anthropic returns and checks its signed thinking blocks; a local model's
+     * reasoning comes back whole and unsigned, so they change nothing here. */
     auto th = b.find("thinking");
-    if (th != b.end() && th->is_object()) {
+    if (th != b.end() && !th->is_null()) {
+        if (!th->is_object()) { *err = err_bad("thinking", "expected an object"); return RAD_E_INVAL; }
+        for (auto it = th->begin(); it != th->end(); ++it)
+            if (it.key() != "type" && it.key() != "budget_tokens" && it.key() != "display" &&
+                it.key() != "block_binding") {
+                *err = err_unsupported("thinking." + it.key(), "Extra inputs are not permitted");
+                return RAD_E_UNSUPPORTED;
+            }
         std::string type;
         if (!member_str(*th, "type", "thinking.type", &type, err)) return RAD_E_INVAL;
-        if (type == "disabled") {
+        if (type == "disabled" || type == "between_tools") {
             o["enable_thinking"] = false;
         } else if (type == "enabled" || type == "adaptive") {
             o["enable_thinking"] = true;
             if (th->contains("budget_tokens")) o["thinking_token_budget"] = th->at("budget_tokens");
+        } else {
+            *err = err_bad("thinking.type", "must be \"enabled\", \"adaptive\", \"disabled\" or "
+                                            "\"between_tools\", got \"" + type + "\"");
+            return RAD_E_INVAL;
         }
     }
 
-    /* The caller's own name for whoever is asking, which Claude Code fills with its session. */
+    RAD_TRY(anthropic_output_config(b, &o, err));
+    if (!effort.is_null()) o["reasoning_effort"] = effort;
+
+    /* metadata.user_id labels the conversation (Claude Code puts its session there). */
     auto md = b.find("metadata");
-    if (label && md != b.end() && md->is_object() && md->contains("user_id") &&
-        md->at("user_id").is_string())
-        *label = session_label_of(md->at("user_id").get());
+    if (md != b.end() && !md->is_null()) {
+        if (!md->is_object()) { *err = err_bad("metadata", "expected an object"); return RAD_E_INVAL; }
+        std::string uid;
+        if (!member_str(*md, "user_id", "metadata.user_id", &uid, err)) return RAD_E_INVAL;
+        if (label && !uid.empty()) *label = session_label_of(uid);
+    }
 
     *chat = o.dump();
     return RAD_OK;
@@ -3355,8 +3590,8 @@ const char* anthropic_stop_reason(const OaiRequest& r, Finish f, const std::stri
         case Finish::ToolCalls: return "tool_use";
         case Finish::Length:    return "max_tokens";
         case Finish::StopString: {
-            /* The client's own stop sequence is stop_sequence; the chat format's end-of-turn marker
-             * is the turn ending, which is end_turn. */
+            /* A client stop sequence is stop_sequence; the format's end-of-turn marker is
+             * end_turn. */
             const auto end = r.stop.begin() + (long)std::min(r.n_client_stops, r.stop.size());
             if (!stop_word.empty() && std::find(r.stop.begin(), end, stop_word) != end)
                 return "stop_sequence";
@@ -3397,20 +3632,15 @@ std::string anthropic_message_body(const OaiRequest& r, const ChoiceOut& c, cons
     o["stop_reason"] = sr;
     o["stop_sequence"] = std::strcmp(sr, "stop_sequence") == 0 ? json(c.stop_word) : json(nullptr);
     o["usage"] = anthropic_usage(u);
+    if (r.context_management)
+        o["context_management"] = json{ { "applied_edits", json::array() } };
     return o.dump();
 }
 
 std::string anthropic_error_body(const ApiError& e) {
-    const char* type = e.status == 401 ? "authentication_error"
-                     : e.status == 403 ? "permission_error"
-                     : e.status == 404 ? "not_found_error"
-                     : e.status == 413 ? "request_too_large"
-                     : e.status == 429 ? "rate_limit_error"
-                     : e.status >= 500 ? "api_error"
-                                       : "invalid_request_error";
     json o;
     o["type"] = "error";
-    o["error"] = json{ { "type", type }, { "message", e.message } };
+    o["error"] = json{ { "type", anthropic_error_type(e.status) }, { "message", e.message } };
     return o.dump();
 }
 
@@ -3427,7 +3657,11 @@ void AnthropicStream::event(std::string& out, const char* type, const json& data
     out += "\n\n";
 }
 
-std::string AnthropicStream::first_chunk() {
+std::string AnthropicStream::first_chunk() { return std::string(); }
+
+std::string AnthropicStream::started() {
+    if (started_) return std::string();
+    started_ = true;
     json m;
     m["id"] = id_;
     m["type"] = "message";
@@ -3445,7 +3679,8 @@ std::string AnthropicStream::first_chunk() {
 void AnthropicStream::open(std::string& out, Block b, const ToolCall* tc) {
     close(out);
     json cb;
-    if (b == Block::Thinking)  cb = { { "type", "thinking" }, { "thinking", "" } };
+    if (b == Block::Thinking)
+        cb = { { "type", "thinking" }, { "thinking", "" }, { "signature", "" } };
     else if (b == Block::Text) cb = { { "type", "text" }, { "text", "" } };
     else cb = { { "type", "tool_use" }, { "id", tc->id }, { "name", tc->name },
                 { "input", json::object() } };
@@ -3457,9 +3692,8 @@ void AnthropicStream::open(std::string& out, Block b, const ToolCall* tc) {
 
 void AnthropicStream::close(std::string& out) {
     if (block_ == Block::None) return;
-    /* A thinking block ends with its signature, which a client hands back with the block on the
-     * next turn. Anthropic's is cryptographic and verified by Anthropic; a local model has none,
-     * and the empty one is what llama-server sends. */
+    /* A thinking block ends with its signature, which clients send back next turn. A local model
+     * has none; the empty one matches llama-server. */
     if (block_ == Block::Thinking)
         event(out, "content_block_delta",
               json{ { "type", "content_block_delta" }, { "index", n_blocks_ - 1 },
@@ -3469,7 +3703,7 @@ void AnthropicStream::close(std::string& out) {
 }
 
 std::string AnthropicStream::emit(const std::vector& ev) {
-    std::string out;
+    std::string out = ev.empty() ? std::string() : started();
     for (const ReplyDelta& d : ev) {
         if (!absorb(d)) continue;
         switch (d.kind) {
@@ -3480,25 +3714,25 @@ std::string AnthropicStream::emit(const std::vector& ev) {
                         { "delta", { { "type", "thinking_delta" }, { "thinking", d.text } } } });
             break;
         case ReplyDelta::Content: {
-            /* The prefill is the caller's own text; Anthropic's API answers what follows it. */
-            std::string_view text = d.text;
+            /* The prefill is the caller's own text; Anthropic's API answers what follows it, and
+             * the buffered body drops it when the reply repeats the whole of it. A start that
+             * matches the prefill so far is held until the reply completes the prefill (dropped)
+             * or departs from it (sent whole). */
+            std::string text = d.text;
             if (!skip_.empty()) {
-                const size_t n = std::min(skip_.size(), text.size());
-                if (skip_.compare(0, n, text.substr(0, n)) == 0) {
-                    skip_.erase(0, n);
-                    text.remove_prefix(n);
-                } else {
-                    skip_.clear();
-                }
+                held_ += text;
+                const size_t n = std::min(held_.size(), skip_.size());
+                const bool same = held_.compare(0, n, skip_, 0, n) == 0;
+                if (same && held_.size() < skip_.size()) break;
+                text = same ? held_.substr(skip_.size()) : held_;
+                held_.clear();
+                skip_.clear();
             }
-            if (text.empty()) break;
-            if (block_ != Block::Text) open(out, Block::Text, nullptr);
-            event(out, "content_block_delta",
-                  json{ { "type", "content_block_delta" }, { "index", n_blocks_ - 1 },
-                        { "delta", { { "type", "text_delta" }, { "text", std::string(text) } } } });
+            text_delta(out, text);
             break;
         }
         case ReplyDelta::CallBegin:
+            release_held(out);
             open(out, Block::Tool, &last_.tool_calls.back());
             break;
         case ReplyDelta::CallArgs:
@@ -3514,21 +3748,43 @@ std::string AnthropicStream::emit(const std::vector& ev) {
     return out;
 }
 
+void AnthropicStream::text_delta(std::string& out, const std::string& text) {
+    if (text.empty()) return;
+    if (block_ != Block::Text) open(out, Block::Text, nullptr);
+    event(out, "content_block_delta",
+          json{ { "type", "content_block_delta" }, { "index", n_blocks_ - 1 },
+                { "delta", { { "type", "text_delta" }, { "text", text } } } });
+}
+
+/* Content held against the prefill is the reply's own text once nothing more can complete the
+ * prefill: the reply ended, or moved on to a call. */
+void AnthropicStream::release_held(std::string& out) {
+    if (held_.empty()) return;
+    std::string text;
+    text.swap(held_);
+    skip_.clear();
+    text_delta(out, text);
+}
+
 std::string AnthropicStream::final_chunk(Finish f, const TimingsOut&, const UsageOut& u) {
-    std::string out = push(std::string_view(), true);
+    std::string out = started();
+    out += push(std::string_view(), true);
+    release_held(out);
     close(out);
     const char* sr = anthropic_stop_reason(*r_, adjusted_finish(f), stop_word_);
     json delta = { { "stop_reason", sr },
                    { "stop_sequence", std::strcmp(sr, "stop_sequence") == 0 ? json(stop_word_)
                                                                              : json(nullptr) } };
-    event(out, "message_delta",
-          json{ { "type", "message_delta" }, { "delta", delta }, { "usage", anthropic_usage(u) } });
+    json md = { { "type", "message_delta" }, { "delta", delta }, { "usage", anthropic_usage(u) } };
+    if (r_->context_management)
+        md["context_management"] = json{ { "applied_edits", json::array() } };
+    event(out, "message_delta", md);
     event(out, "message_stop", json{ { "type", "message_stop" } });
     return out;
 }
 
 std::string AnthropicStream::error_chunk(const ApiError& e, const TimingsOut&, const UsageOut&) {
-    return "event: error\ndata: " + anthropic_error_body(e) + "\n\n";
+    return started() + "event: error\ndata: " + anthropic_error_body(e) + "\n\n";
 }
 
 /* ================================================================== OpenAI's Responses API */
@@ -3622,9 +3878,9 @@ int responses_to_chat(const std::string& body, const OaiLimits& lim, std::string
                                "send the conversation as `input`");
         return RAD_E_UNSUPPORTED;
     }
-    /* WHAT A RESPONSE OBJECT CANNOT CARRY is refused, not computed and dropped: several choices
-     * (a response is one), and logprobs, which the Responses API reports per output_text part --
-     * a split of the reply's tokens this server does not make. */
+    /* Refused rather than computed and dropped: several choices (a response is one reply), and
+     * logprobs, which the Responses API reports per output_text part, a token split this server
+     * does not make. */
     {
         int64_t n = 1;
         if (!get_int(b, "n", &n, err)) return RAD_E_INVAL;
@@ -3648,11 +3904,10 @@ int responses_to_chat(const std::string& body, const OaiLimits& lim, std::string
             return RAD_E_UNSUPPORTED;
         }
     }
-    /* EVERY FIELD THE RESPONSES API DOES NOT DEFINE PASSES THROUGH to the chat request, as
-     * llama-server passes it: a client that adds chat_template_kwargs or top_k to a Responses
-     * request means them. The Responses API's own fields are translated below, and the chat
-     * stream's own extras -- the usage chunk and the prompt progress chunks, which a Responses
-     * stream has no frame for -- are dropped: response.completed carries the usage. */
+    /* Fields the Responses API does not define pass through to the chat request, as in
+     * llama-server (e.g. chat_template_kwargs, top_k). Its own fields are translated below. The
+     * chat stream's usage and progress chunks have no Responses frame and are dropped;
+     * response.completed carries the usage. */
     json o = b;
     for (const char* k : { "input", "instructions", "tools", "tool_choice", "max_output_tokens",
                            "reasoning", "text", "previous_response_id", "store", "metadata",
@@ -3681,8 +3936,8 @@ int responses_to_chat(const std::string& body, const OaiLimits& lim, std::string
                 if (!member_str(item, "role", "input[].role", &role, err)) return RAD_E_INVAL;
                 const json content = item.contains("content") ? item.at("content") : json("");
                 if (role == "assistant") {
-                    /* A turn the model gave earlier: its text, joined to a reasoning item or a
-                     * call of the same turn that came before it. */
+                    /* An earlier model turn: its text joins any preceding reasoning item or call
+                     * of the same turn. */
                     std::string text;
                     if (content.is_string()) {
                         text = content.get();
@@ -3749,8 +4004,8 @@ int responses_to_chat(const std::string& body, const OaiLimits& lim, std::string
                 if (!member_str(item, "call_id", "input[].call_id", &id, err)) return RAD_E_INVAL;
                 msgs.push_back(json{ { "role", "tool" }, { "tool_call_id", id }, { "content", content } });
             } else if (type == "reasoning") {
-                /* The reasoning of a turn the model gave earlier, which a template that keeps
-                 * reasoning across turns renders. Its text is the content, else the summary. */
+                /* An earlier turn's reasoning, for templates that keep it across turns: the
+                 * content's text, else the summary's. */
                 std::string text;
                 for (const char* k : { "content", "summary" }) {
                     if (!text.empty() || !item.contains(k) || !item.at(k).is_array()) continue;
@@ -3775,7 +4030,7 @@ int responses_to_chat(const std::string& body, const OaiLimits& lim, std::string
     o["messages"] = std::move(msgs);
 
     /* Function tools only. Built-in tools (web search, file search, computer use) and freeform
-     * custom tools have no chat-completions counterpart; the model is offered what it can call. */
+     * custom tools have no chat-completions counterpart and are left out. */
     json echo_tools = json::array();
     auto tit = b.find("tools");
     if (tit != b.end() && tit->is_array()) {
@@ -3874,9 +4129,7 @@ void ResponsesStream::event(std::string& out, const char* type, json data) {
 
 json ResponsesStream::response(const char* status) const {
     const bool done = std::strcmp(status, "in_progress") != 0;
-    json items = json::array();
-    for (const std::string& it : items_) items.push_back(json::parse(it));
-    return response_object(*r_, status, items, done ? &usage_ : nullptr, incomplete_);
+    return response_object(*r_, status, json(items_), done ? &usage_ : nullptr, incomplete_);
 }
 
 std::string ResponsesStream::first_chunk() {
@@ -3936,13 +4189,17 @@ void ResponsesStream::close(std::string& out) {
                     { "part", text_part(text_) } });
         item = message_item(item_id_, text_, "completed");
     } else {
+        /* A call the reply ended inside was announced but never closed. Its item is
+         * "incomplete", the Responses API's status for an item cut short, so a client acting on
+         * the terminal response does not run it with truncated arguments. */
         const ToolCall& tc = last_.tool_calls[call_];
+        const bool cut = finished_ && last_.open_call && call_ + 1 == last_.tool_calls.size();
         event(out, "response.function_call_arguments.done",
               json{ { "item_id", item_id_ }, { "output_index", at }, { "arguments", tc.arguments } });
-        item = call_item(tc, "completed");
+        item = call_item(tc, cut ? "incomplete" : "completed");
     }
     event(out, "response.output_item.done", json{ { "output_index", at }, { "item", item } });
-    items_.push_back(item.dump());
+    items_.push_back(std::move(item));
     item_ = Item::None;
 }
 
@@ -3950,20 +4207,21 @@ std::string ResponsesStream::emit(const std::vector& ev) {
     std::string out;
     for (const ReplyDelta& d : ev) {
         if (!absorb(d)) continue;
-        const int64_t at = (int64_t)items_.size();
+        /* The open item's index; read after open(), which may close one first. */
+        auto at = [this] { return (int64_t)items_.size(); };
         switch (d.kind) {
         case ReplyDelta::Reasoning:
             if (item_ != Item::Reasoning) open(out, Item::Reasoning, 0);
             text_ += d.text;
             event(out, "response.reasoning_text.delta",
-                  json{ { "item_id", item_id_ }, { "output_index", (int64_t)items_.size() },
+                  json{ { "item_id", item_id_ }, { "output_index", at() },
                         { "content_index", 0 }, { "delta", d.text } });
             break;
         case ReplyDelta::Content:
             if (item_ != Item::Message) open(out, Item::Message, 0);
             text_ += d.text;
             event(out, "response.output_text.delta",
-                  json{ { "item_id", item_id_ }, { "output_index", (int64_t)items_.size() },
+                  json{ { "item_id", item_id_ }, { "output_index", at() },
                         { "content_index", 0 }, { "delta", d.text }, { "logprobs", json::array() } });
             break;
         case ReplyDelta::CallBegin:
@@ -3971,7 +4229,7 @@ std::string ResponsesStream::emit(const std::vector& ev) {
             break;
         case ReplyDelta::CallArgs:
             event(out, "response.function_call_arguments.delta",
-                  json{ { "item_id", item_id_ }, { "output_index", at }, { "delta", d.text } });
+                  json{ { "item_id", item_id_ }, { "output_index", at() }, { "delta", d.text } });
             break;
         case ReplyDelta::CallEnd:
             close(out);
diff --git a/core/server/oai.h b/core/server/oai.h
index b92be847..29689452 100644
--- a/core/server/oai.h
+++ b/core/server/oai.h
@@ -1,19 +1,13 @@
 /* core/server/oai.h -- the OpenAI schema, in and out.
  *
- * Two rules shape everything here.
+ * Errors are values. Nothing here throws; every entry point returns RAD_OK or a negative status
+ * and fills an ApiError carrying its HTTP status, `param` and a message naming the problem. An
+ * exception crossing the transport would close the connection with no body.
  *
- * Errors are values. Nothing in this file throws; every entry point returns RAD_OK or a negative
- * status and fills an ApiError that already knows its HTTP status, its `param`, and a message
- * that names what was wrong. The HTTP layer turns that into a status code and a body. An
- * exception crossing the transport is a connection closed with no body, which is the least
- * diagnosable thing a client can be handed.
- *
- * A parameter that would change the answer and is not served is a 400 that names it, not a
- * silent ignore: a client that sends a `logit_bias` and gets a 200 has been told its bias was
- * applied, and the bug report that follows ("the model ignores my bias") is unanswerable from the
- * server side. Such a field is accepted at its "off" value, which is what llama.cpp-built clients
- * send on every request. A field this server has never heard of is ignored, as llama.cpp and vLLM
- * ignore it (oai.cpp, key vetting).
+ * A parameter that would change the answer and is not served is a 400 naming it, never a silent
+ * ignore, so a client is not told its `logit_bias` was applied when it was not. Such a field is
+ * accepted at its "off" value, which llama.cpp-built clients send on every request. An unknown
+ * field is ignored, as llama.cpp and vLLM do (oai.cpp, key vetting).
  */
 #pragma once
 #include "iface.h"
@@ -37,12 +31,11 @@ struct ApiError {
     std::string message;
     std::string param;      /* "" when the error is not about one field */
     std::string code;       /* "" when there is nothing more specific to say */
-    /* The values `param` takes, when the error is a value outside a known set: `supported` in the
-     * envelope, so a client can retry with one rather than parse the sentence. */
+    /* The legal values of `param` when the error is a value outside a known set; sent as
+     * `supported` so a client can retry with one. */
     std::vector supported;
-    /* A prompt the context cannot hold: its length and the context's, under llama-server's names,
-     * so a client that compacts its history on overflow reads the numbers rather than the
-     * sentence. -1 leaves them out. */
+    /* For a prompt the context cannot hold: its length and the context's, under llama-server's
+     * names, for clients that compact their history on overflow. -1 leaves them out. */
     int64_t     n_prompt_tokens = -1;
     int64_t     n_ctx = -1;
 
@@ -52,22 +45,25 @@ struct ApiError {
 ApiError err_bad(const std::string& param, const std::string& why);
 ApiError err_unsupported(const std::string& param, const std::string& why);
 ApiError err_not_implemented(const std::string& what);
-
-/* SERIALISE OUT OF LINE. nlohmann's dump() inlines a shared_ptr release that GCC 16 speculatively
- * devirtualises onto std::mutex and then reports as an out-of-bounds destroy -- a false positive
- * in a vendored header, which appears or not depending on how deeply the CALLING function
- * inlined. That makes "is this file warning-clean" a property of how short its handlers are,
- * which is not something anybody can act on. One definition, in one translation unit. */
-std::string json_dump(const json& j);
 ApiError err_overloaded(const std::string& why);
+ApiError err_internal(const std::string& why);
+
+/* DRY's sequence breakers when a request names none: the deployment's when it set any (`set`, even
+ * to an empty list), otherwise llama.cpp's four (newline, colon, quote, asterisk). */
+std::vector dry_breakers(const std::vector& deployment, bool set);
+
+/* Out of line on purpose: inlined, nlohmann's dump() trips a GCC 16 false-positive warning
+ * (a speculatively devirtualised shared_ptr release reported as an out-of-bounds destroy) that
+ * comes and goes with how deeply the caller inlines. */
+std::string json_dump(const json& j);
 
 /* ================================================================== a parsed request */
 
 enum class Endpoint { Chat, Completion, Embedding };
 
-/* WHICH API A CHAT REQUEST CAME IN THROUGH, and so which shape its answer goes out in. Every shape
- * is parsed into the same chat request (Anthropic's is translated first, anthropic_to_chat) and
- * served by the same path; only the bytes on the wire differ. */
+/* The API a chat request came in through, which decides the shape of its answer. Every shape is
+ * parsed into the same chat request (Anthropic's is translated first, anthropic_to_chat) and
+ * served by the same path; only the wire bytes differ. */
 enum class ApiShape { OpenAI, Anthropic, Responses, LlamaNative };
 
 struct PromptInput {
@@ -90,31 +86,33 @@ struct OaiRequest {
      * `prompt_progress` chunks while the prompt is read. */
     bool timings_per_token = false;
     bool return_progress = false;
-    /* The conversation as the client names it (OpenRouter's `session_id`), "" when it names none:
-     * a label on /sessions, nothing else. */
+    /* The client's conversation name (OpenRouter's `session_id`), "" if none; only a label on
+     * /sessions. */
     std::string session_label;
-    /* The build, as OpenAI's `system_fingerprint` and llama.cpp's own: what produced the reply. */
+    /* The build, as OpenAI's and llama.cpp's `system_fingerprint`. */
     std::string system_fingerprint;
 
     int             n = 1;
     SamplingParams  sp;
     int32_t         max_tokens = 0;
     std::vector stop;
-    /* Of `stop`, how many the client sent; the rest are the chat format's own end-of-turn
-     * markers. A reply cut on one of the first is Anthropic's `stop_sequence`, on the rest its
-     * `end_turn`. */
+    /* How many of `stop` the client sent; the rest are the chat format's end-of-turn markers.
+     * A cut on a client stop is Anthropic's `stop_sequence`, on the rest its `end_turn`. */
     size_t          n_client_stops = 0;
     /* The assistant text a continued conversation ends in (assistant prefill), "" otherwise. The
-     * OpenAI shape answers the whole message, as llama-server does; Anthropic's answers what
+     * OpenAI shape answers the whole message, as llama-server does; Anthropic's answers only what
      * follows it, as Anthropic's API does. */
     std::string     continued;
-    /* The Responses API's request fields its response object echoes (instructions, tools,
+    /* Anthropic's `context_management` was sent: the answer reports `applied_edits: []`, as the
+     * conversation is served as sent. */
+    bool            context_management = false;
+    /* The Responses API request fields its response object echoes (instructions, tools,
      * tool_choice, text, reasoning, ...), as a JSON object; "" for the other shapes. */
     std::string     echo_json;
     /* llama-server's native /completion: the generated token ids beside the text. */
     bool            return_tokens = false;
     /* The reasoning block's closer when the reply starts inside the block, else "": the stop
-     * strings above then apply only after it (IDetokenizer::defer_stops_until). */
+     * strings then apply only after it (IDetokenizer::defer_stops_until). */
     std::string stops_after;
     /* Generate past end-of-text, to max_tokens. See Request::ignore_eos. */
     bool        ignore_eos = false;
@@ -130,29 +128,28 @@ struct OaiRequest {
     /* OpenAI's deprecated functions API: the request sent `functions`, so the reply carries its
      * call as `function_call` (one at most) and ends in finish_reason "function_call". */
     bool legacy_functions = false;
-    /* FOR THE REQUEST LOG, counted while the parse walks the body anyway: the messages and tools
-     * a chat request carried, and the last user message's opening (one line, bounded) that the
-     * debug level prints so a log line can be matched to what was typed. Completion requests
-     * leave them at zero and empty. */
+    /* For the request log, counted during the parse: the messages and tools a chat request
+     * carried, and a bounded one-line opening of the last user message for the debug level.
+     * Zero and empty for completion requests. */
     int         n_messages = 0;
     int         n_tools = 0;
     std::string last_user;
     std::string peer;             /* the handler sets it from the transport; "" in-process */
     int64_t     t_received_ns = -1;   /* HttpRequest::t_received_ns, for timings' ttft and total */
     bool parse_tools = false;
-    /* The reply parser this request's render produced. Per request and not per server: it is the
-     * model's format bound to the tools THIS call sent, so two concurrent requests against the
-     * same model can legitimately need different parsers. */
+    /* The reply parser this request's render produced. Per request, not per server: it binds the
+     * model's format to the tools this call sent, so concurrent requests may need different
+     * parsers. */
     std::shared_ptr reply_parser;
 
-    /* The control tokens this request's reply must be decoded AS TEXT, so `tool_parser` can see
-     * the structure it is looking for. See ITokenizer::detokenizer. */
+    /* Control tokens this reply must be decoded as text, so `tool_parser` can see its structure.
+     * See ITokenizer::detokenizer. */
     std::vector preserved_tokens;
 
     /* /v1/embeddings */
     bool base64_embeddings = false;
-    /* OpenAI's `dimensions`: the vector's first `dimensions` components, renormalised -- a
-     * Matryoshka-trained model's shorter embedding. 0 is the model's own width. */
+    /* OpenAI's `dimensions`: the vector's first `dimensions` components, renormalised (a
+     * Matryoshka-trained model's shorter embedding). 0 is the model's own width. */
     int64_t dimensions = 0;
     /* /v1/embeddings: a soft-token budget for the request's images, 0 the server's. */
     int32_t image_tokens = 0;
@@ -165,13 +162,10 @@ struct OaiLimits {
     std::string model_id = "radiance";
     std::string version;                  /* the build, for `system_fingerprint` */
     int64_t     max_ctx = 0;              /* 0 = unknown, no length check */
-    /* What a request that names no max_tokens may generate. 0 is "whatever the context leaves",
-     * resolved against the prompt in clamp_max_tokens, which needs max_ctx to resolve against.
-     *
-     * 0 BY DEFAULT, as vLLM's is: many clients send no max_tokens, and a reasoning model spends
-     * the first thousands of tokens of an answer thinking. A fixed default of 512 ended those
-     * answers inside the reasoning, with finish_reason "length" that a chat client does not show,
-     * so they read as a model that stops at random. */
+    /* What a request that names no max_tokens may generate. 0, the default as in vLLM, is
+     * "whatever the context leaves", resolved against the prompt and max_ctx in
+     * clamp_max_tokens. A small fixed default ends a reasoning model's answer inside its
+     * reasoning with finish_reason "length", which chat clients do not show. */
     int64_t     default_max_tokens = 0;
     /* The most any request may generate; a larger max_tokens is clamped, not refused. 0 = none. */
     int64_t     max_tokens_cap = 0;
@@ -184,67 +178,58 @@ struct OaiLimits {
     bool        allow_audio = false;
     bool        supports_logprobs = false;
 
-    /* THE DEPLOYMENT'S DEFAULT REASONING EFFORT, empty for "whatever the template's own default
-     * is". It exists because the template's default is not always a servable one: Qwen3.8's is
-     * `xhigh`, which on a short task reliably spends the whole token budget inside  and
-     * returns a turn with EMPTY content and finish_reason "length" -- an agent turn that carries
-     * no answer and no tool call. The per-request field is the right control and most OpenAI
-     * clients never send it, so without this an operator serving such a client cannot reach the
-     * dial at all. Seeded only when the request says nothing, so a caller always wins. */
+    /* The deployment's default reasoning effort; empty uses the template's own default. Needed
+     * because a template's default is not always servable: Qwen3.8's is `xhigh`, which on a
+     * short task can spend the whole budget inside  and return empty content with
+     * finish_reason "length". Most OpenAI clients never send the field. Applied only when the
+     * request says nothing, so a caller always wins. */
     std::string default_reasoning_effort;
 
-    /* THE WORDS THE CHAT TEMPLATE TAKES AS `reasoning_effort`, found at startup by rendering each
-     * word this server knows of (Server::probe_reasoning_efforts). Empty when the template takes
-     * any word -- it does not read the variable, or reads it without refusing one -- and when
-     * nothing was probed. A request whose effort the template refuses is answered with this set
-     * rather than with the template's traceback (template_refusal). */
+    /* The words the chat template accepts as `reasoning_effort`, found at startup by rendering
+     * each known word (Server::probe_reasoning_efforts). Empty when the template takes any word
+     * or nothing was probed. A refused effort is answered with this set instead of the
+     * template's traceback (template_refusal). */
     std::vector reasoning_efforts;
 
-    /* --reasoning-effort-map: an effort a request sends, replaced by the deployment's word before
-     * the template sees it. For a client that always sends a word of OpenAI's ladder ("high")
-     * to a model whose template has its own ("xhigh"). */
+    /* --reasoning-effort-map: a request's effort word replaced by the deployment's before the
+     * template sees it, e.g. OpenAI's "high" to a template's "xhigh". */
     std::map reasoning_effort_map;
 
-    /* A STARTUP PROBE, NOT A REQUEST: what the template refuses is the answer being asked for, so
-     * its refusal is not logged (ChatRenderOptions::quiet). */
+    /* A startup probe, not a request: the template's refusal is the expected answer and is not
+     * logged (ChatRenderOptions::quiet). */
     bool        probe = false;
 
-    /* THE DEPLOYMENT'S DEFAULT `thinking_token_budget`, -1 for none. For the same reason the
-     * effort default exists: an agent framework sizes max_tokens per turn and sends no budget, and
-     * a reasoning block that spends the whole of max_tokens returns a turn with no answer in it.
-     * Applied only to a request that names no budget, and only where the reply's reasoning block
-     * can be counted. */
+    /* The deployment's default `thinking_token_budget`, -1 for none. Agent frameworks size
+     * max_tokens per turn and send no budget, and a reasoning block that spends all of max_tokens
+     * leaves no answer. Applied only to a request that names no budget, and only where the
+     * reply's reasoning block can be counted. */
     int64_t     default_thinking_budget = -1;
 
-    /* WHAT A REQUEST THAT SENDS NO SAMPLER FIELDS IS SERVED WITH, field by field.
+    /* The sampler a request that sends no sampler fields is served with, field by field.
      *
-     * The struct's own defaults are an untruncated sampler -- temperature 1, top_k off, top_p 1
-     * -- which is the right thing to fall back to and the wrong thing to serve a checkpoint
-     * with: a model tuned against a truncated tail, sampled without one, will occasionally draw
-     * a token from far down its distribution. End-of-turn is one of those tokens, and drawing it
-     * early ends an agent's turn with prose and no tool call, which reads as the server dropping
-     * the request. The deployment resolves this from what the checkpoint itself states and hands
-     * the result over here.
+     * The struct's own defaults truncate only to the sampler's 1024 candidates (temperature 1,
+     * top_k 0, top_p 1). A model tuned against a tighter cut occasionally draws from far down its
+     * distribution without one, and an early end-of-turn ends an agent's turn with no tool call.
+     * The deployment resolves these from what the checkpoint states.
      *
-     * Only the sampler knobs are read: the grammar fields are per request and are filled in
-     * after this is copied. A request that names a field always wins, exactly as with
-     * default_reasoning_effort. */
+     * Only the sampler knobs are read; grammar fields are per request and filled in after this is
+     * copied. A field the request names always wins. */
     SamplingParams default_sampling;
-    /* SamplingParams cannot tell an empty breaker list that was stated from one that was not, and
-     * the two mean different things: unstated is llama-server's four, stated-empty is none. */
+    /* SamplingParams cannot tell a stated empty breaker list from an unstated one: unstated is
+     * llama-server's four, stated-empty is none. */
     bool           default_dry_breakers_set = false;
 
-    /* THE DEPLOYMENT'S CHAT TEMPLATE VARIABLES, key -> JSON text, applied under the request's own
-     * chat_template_kwargs so a key the request names is the request's. The thinking keys follow
-     * parse_thinking's rule: a request that says anything about thinking replaces them whole. */
+    /* The deployment's chat template variables, key -> JSON text, applied under the request's own
+     * chat_template_kwargs so the request wins per key. The thinking keys follow parse_thinking's
+     * rule: a request that says anything about thinking replaces them whole. */
     std::map default_template_kwargs;
     /* "auto" returns reasoning as reasoning_content; "none" leaves it inline in content. */
     std::string reasoning_format = "auto";
 };
 
-/* WHAT A REQUEST SAYS ABOUT THINKING, in any of its three spellings: `effort` when it names a
- * reasoning effort (top-level or in chat_template_kwargs, non-empty), `thinking` when it says
- * anything at all -- an effort, or enable_thinking in either place. */
+/* What a request says about thinking, in any of its three spellings: `effort` when it names a
+ * non-empty reasoning effort (top-level or in chat_template_kwargs), `thinking` when it says
+ * anything at all (an effort, or enable_thinking in either place). */
 struct RequestThinking {
     bool thinking = false;
     bool effort = false;
@@ -254,27 +239,25 @@ RequestThinking request_thinking(const json& b);
 /* The deployment's template variables and reply format, onto `opt`, before the request's own
  * chat_template_kwargs are written over them. A request that says anything about thinking keeps
  * the deployment's enable_thinking out; one that names an effort keeps its reasoning_effort out.
- * The chat endpoint and /tokenize both render through this, so a prompt counted by one is the
- * prompt served by the other. */
+ * The chat endpoint and /tokenize both render through this, so both count the same prompt. */
 void apply_template_defaults(const json& b, const OaiLimits& lim, ChatRenderOptions* opt);
 
-/* --reasoning-effort-map, on the effort chat_template_kwargs put in the render options: a mapped
- * word replaces it, and a word mapped to "none" or "minimal" turns thinking off instead. The chat
- * endpoint maps the top-level `reasoning_effort` itself, before it reads "none" and "minimal";
- * this is the kwargs spelling, for it and for /tokenize. */
+/* --reasoning-effort-map, applied to the effort chat_template_kwargs put in `opt`: a mapped word
+ * replaces it, and one mapped to "none" or "minimal" turns thinking off instead. The chat endpoint
+ * maps the top-level `reasoning_effort` itself; this handles the kwargs spelling for it and for
+ * /tokenize. */
 void map_reasoning_effort(const OaiLimits& lim, ChatRenderOptions* opt);
 
-/* THE 400 FOR A TEMPLATE THAT REFUSED A RENDER. An effort outside the template's known set
- * (OaiLimits::reasoning_efforts) is named as `reasoning_effort` with the set in `supported`, the
- * way OpenAI answers an unsupported value; anything else is `messages` with the template's own
- * sentence. */
+/* The 400 for a template that refused a render. An effort outside OaiLimits::reasoning_efforts is
+ * reported against `reasoning_effort` with the set in `supported`, as OpenAI reports an
+ * unsupported value; anything else against `messages` with the template's own sentence. */
 ApiError template_refusal(const ChatRenderOptions& opt, const OaiLimits& lim, int rs,
                           const std::string& why);
 
-/* True when `v` is a legal value of the sampler field a request spells `field`; otherwise `why`
- * says what the legal set is, in the words a 400 carries. The same table checks a request and the
- * command-line flag that sets the field's default, so a default the command line accepts is one
- * every request omitting the field can be served with. A field with no bounds takes any value. */
+/* True when `v` is legal for the sampler field a request spells `field`; otherwise `why` states
+ * the legal set as a 400 would. The same table checks requests and the command-line flag that
+ * sets the field's default, so an accepted default is always servable. A field with no bounds
+ * takes any value. */
 bool sampler_value_ok(const char* field, double v, std::string* why);
 
 struct OaiDeps {
@@ -285,17 +268,25 @@ struct OaiDeps {
     IEmbedder*        embed = nullptr;
 };
 
+/* The request-key policy (oai.cpp, key vetting) as lists, so a test can cover every key. */
+struct KeyPolicy {
+    std::vector common, chat, completion, embedding;   /* accepted per endpoint */
+    std::vector inert, inert_prefixes;
+    std::vector guarded;   /* refused unless at their neutral value */
+};
+KeyPolicy request_key_policy();
+
 /* Parse. `body` is the raw request body; a malformed body is a 400 that says where. */
 int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim,
                        OaiRequest* out, ApiError* err);
-/* `native` is llama-server's /completion: its `return_tokens`, and a prompt array of strings and
- * token ids mixed as ONE prompt, as llama-server reads it. */
+/* `native` is llama-server's /completion: `return_tokens`, and a prompt array of strings and
+ * token ids mixed as one prompt, as llama-server reads it. */
 int parse_completion_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim,
                              OaiRequest* out, ApiError* err, bool native = false);
 /* A media part's bytes out of a data: URL; any other URL is refused, never fetched. */
 int decode_media_url(const std::string& url, const std::string& field,
                      std::vector* out, ApiError* err);
-/* A prompt holding RAD_MEDIA_MARKER once a media part, tokenised with each marker replaced by its
+/* Tokenise a prompt holding one RAD_MEDIA_MARKER per media part, replacing each marker with its
  * part's processed token run; `media` is consumed in order. */
 int tokenize_with_media(const std::string& rendered, const OaiDeps& d,
                         std::vector>>& media,
@@ -306,11 +297,10 @@ int parse_embeddings_request(const std::string& body, const OaiDeps& d, const Oa
 
 /* ================================================================== responses */
 
-/* One emitted token's logprobs as the wire carries them. `bytes` is the token's own bytes and
- * `text` is their longest well-formed UTF-8 prefix -- a byte-level token can hold half a
- * character, and a JSON string cannot -- llama-server's spelling. `end` is where the token's
- * decoded text ends in the choice's text, which is what decides whether it went out before a stop
- * string cut the reply. */
+/* One emitted token's logprobs as the wire carries them. `bytes` is the token's bytes and `text`
+ * their longest well-formed UTF-8 prefix (a byte-level token can hold half a character, which a
+ * JSON string cannot), as llama-server spells it. `end` is where the token's text ends in the
+ * choice's text, which decides whether it went out before a stop string cut the reply. */
 struct LogprobAlt {
     int32_t     token = 0;
     std::string text, bytes;
@@ -324,11 +314,11 @@ struct LogprobEntry {
     size_t      end = 0;
 };
 
-/* The entries as a JSON array's elements, comma-joined, in OpenAI's chat shape with llama-server's
- * `id` beside each token -- which is also llama-server's native `completion_probabilities`. */
+/* The entries as comma-joined JSON array elements, in OpenAI's chat shape with llama-server's
+ * `id` beside each token; also llama-server's native `completion_probabilities`. */
 std::string logprobs_content(const LogprobEntry* e, size_t n);
-/* OpenAI's legacy /v1/completions `logprobs` object for the entries, `offset` the text offset of
- * the first, with llama-server's `content` array beside the legacy arrays. */
+/* OpenAI's legacy /v1/completions `logprobs` object, `offset` the text offset of the first entry,
+ * with llama-server's `content` array beside the legacy arrays. */
 std::string logprobs_legacy(const LogprobEntry* e, size_t n, size_t offset);
 
 struct ChoiceOut {
@@ -344,35 +334,31 @@ struct UsageOut {
     int64_t prompt = 0;
     int64_t completion = 0;
     int64_t cached = 0;
-    /* Of `completion`, the tokens inside the reply's reasoning block, its markers included: OpenAI's
-     * completion_tokens_details.reasoning_tokens. -1 when the block cannot be counted, and the
+    /* Of `completion`, the tokens inside the reasoning block, markers included (OpenAI's
+     * completion_tokens_details.reasoning_tokens). -1 when the block cannot be counted; the
      * breakdown is then left out. */
     int64_t reasoning = -1;
 };
 
-/* WHERE ONE REQUEST'S TIME WENT, in llama.cpp's `timings` shape, which proxies and dashboards
- * built against llama-server already read (llama-swap's activity view is one). /metrics holds the
- * same quantities summed over every request, and two overlapping requests cannot be told apart
- * there; this is the per-request half.
+/* One request's timing, in llama.cpp's `timings` shape (read by proxies and dashboards built for
+ * llama-server, e.g. llama-swap). /metrics holds the same quantities summed over all requests.
  *
- *   prompt_n      prompt tokens computed, the prefix cache's excluded; cache_n is those
- *   prompt_ms     from the first step the scheduler gave the request to its first token -- the
- *                 prefill, without the time it waited for admission
+ *   prompt_n      prompt tokens computed, excluding prefix-cache hits; cache_n is those
+ *   prompt_ms     from the request's first scheduled step to its first token: the prefill,
+ *                 without the admission wait
  *   predicted_n   tokens generated: usage.completion_tokens
  *   predicted_ms  from the first token to the last
  *   draft_n, draft_n_accepted
  *                 speculative tokens proposed for this request and accepted; present when any
- *                 were proposed, as llama.cpp does
- *   ttft_ms       from the moment the server had the whole request body to the first token: the
- *                 parse, the chat template, tokenisation, the wait for admission and the prefill.
- *                 The time the body took to arrive is not in it, so a client far from the server
- *                 reads the server's own share of what it measured
+ *                 were proposed, as in llama.cpp
+ *   ttft_ms       from having the whole request body to the first token: parse, chat template,
+ *                 tokenisation, admission wait and prefill. Body transfer time is excluded, so
+ *                 a remote client sees the server's own share
  *   total_ms      from the same moment to the last token
  *
- * The rates divide the tokens by the time that produced them: prompt_n by prompt_ms, and the
- * predicted_n - 1 tokens after the first by predicted_ms, since the first token is the prompt
- * phase's product -- the same figure as /metrics' time per output token. A rate whose count or
- * time is zero is null. Over several choices the counts are summed and each time runs from the
+ * Rates are prompt_n / prompt_ms and (predicted_n - 1) / predicted_ms, since the first token
+ * belongs to the prompt phase; the latter matches /metrics' time per output token. A rate with a
+ * zero count or time is null. Over several choices the counts are summed and each time spans the
  * earliest choice's start to the latest choice's end. */
 struct TimingsOut {
     bool    valid = false;       /* some choice produced a token; nothing is reported otherwise */
@@ -392,23 +378,19 @@ std::string text_completion_body(const OaiRequest& r, const std::vector>& vecs,
                             const UsageOut& u);
-/* ONE MODEL ENTRY: what /v1/models lists and /v1/models/:id returns on its own. */
+/* One model entry: what /v1/models lists and /v1/models/:id returns. */
 struct ModelCard {
     std::string id;
     int64_t     created = 0;
-    /* The context the server was started with (--max-model-len, else the container's trained
-     * length), the field vLLM's model card carries. Clients size their own context from it -- an
-     * agent that compresses its history at the window's edge, a UI that shows how much is left --
-     * and without it they guess from the model's name, which is wrong whenever the deployment sets
-     * its own length. 0 leaves the field out rather than reporting a length the server does not
-     * know. */
+    /* The served context (--max-model-len, else the container's trained length), vLLM's model
+     * card field. Clients size their own context from it (history compression, UI meters);
+     * without it they guess from the model name. 0 leaves the field out. */
     int64_t     max_model_len = 0;
     /* What the server loaded (ServerOptions::model_path), vLLM's `root`. Empty leaves it out. */
     std::string root;
-    /* What the model can be asked for -- tools, reasoning, images -- as /server_info reports it.
-     * There is no field for it in OpenAI's model object, so without this a client learns it by
-     * sending a request and reading the refusal; the entry it already fetches can say so up
-     * front. A JSON object as text, spliced in as it is; empty leaves it out. */
+    /* What the model can be asked for (tools, reasoning, images), as /server_info reports it.
+     * OpenAI's model object has no such field. A JSON object as text, spliced in verbatim; empty
+     * leaves it out. */
     std::string capabilities;
 };
 /* The list, for GET /v1/models. */
@@ -417,10 +399,9 @@ std::string models_body(const ModelCard& m);
  * list of one, and its SDK reads `id` off the top level. */
 std::string model_body(const ModelCard& m);
 
-/* The usage chunk of each endpoint's stream: an SSE event whose choices array is empty and whose
- * only payload is `usage`. Emitted when the request asked for stream_options.include_usage, ONCE
- * per stream and after every choice's final chunk -- `n` choices share one prompt and one total,
- * so a chunk per choice would count the prompt n times and interleave with the choices. */
+/* The usage chunk of each endpoint's stream: an SSE event with an empty choices array and only
+ * `usage`. Sent when stream_options.include_usage is set, once per stream after every choice's
+ * final chunk, since `n` choices share one prompt and one total. */
 std::string text_usage_chunk(const OaiRequest& r, const UsageOut& u,
                              const TimingsOut& t = TimingsOut());
 std::string chat_usage_chunk(const OaiRequest& r, const UsageOut& u,
@@ -428,55 +409,58 @@ std::string chat_usage_chunk(const OaiRequest& r, const UsageOut& u,
 /* The `timings` object, for a stream's final chunks. */
 json timings_json(const TimingsOut& t);
 
-/* Whether a parsed reply's calls are all calls a client can run: none left open, each named,
- * each one's arguments one JSON value (json_partial.h). A reply is answered `tool_calls` by this
- * alone, streamed or not. */
+/* Whether every call in a parsed reply is runnable: none left open, each named, each one's
+ * arguments a single JSON value (json_partial.h). This alone decides finish_reason
+ * `tool_calls`, streamed or not. */
 bool calls_complete(const ParsedMessage& m);
 
 /* ================================================================== streaming
  *
- * One of these per choice. It feeds the generated text to the choice's reply reader as it grows
- * and forwards each increment the reader completes as an SSE chunk. The reader never revises
- * what it has delivered, so nothing here diffs, holds back or reconciles: a delta is the next
- * piece of the answer, and the chunks a client concatenates are the answer the buffered path
- * returns.
+ * One per choice. Feeds the generated text to the choice's reply reader as it grows and writes
+ * each increment the reader completes as an SSE chunk. The reader never revises what it has
+ * delivered, so nothing here diffs or holds back: the concatenated deltas equal the buffered
+ * answer.
  *
- * THE WIRE SHAPE IS THE SUBCLASS'S. Reading the reply -- the reader, the message it adds up to,
- * the finish it implies -- is the same for every API this server speaks, so it lives here once;
- * what one increment looks like on the wire is OpenAI's chunk (ChatDeltaStream) or Anthropic's
- * event (AnthropicStream).
+ * Reading the reply is shared by every API; the subclass owns the wire shape of an increment:
+ * OpenAI's chunk (ChatDeltaStream), Anthropic's event (AnthropicStream) or the Responses API's
+ * (ResponsesStream).
  */
 class ReplyStream {
 public:
     ReplyStream(const OaiRequest& r, int index, const IReplyParser* parser);
     virtual ~ReplyStream() = default;
 
-    /* What opens the stream: OpenAI's `role: assistant` chunk, Anthropic's message_start. */
+    /* What the stream sends when it opens, before the request has run: the Responses API's
+     * response.created and response.in_progress, which report the response object's state as
+     * OpenAI's do. The chat and Anthropic streams send nothing here. */
     virtual std::string first_chunk() = 0;
+    /* What the stream sends once the reply's first token exists, ahead of any of its text, which
+     * a reader or a stop string may still hold back: OpenAI's opening chunk, Anthropic's
+     * message_start. A client that times its first event then times the first token. */
+    virtual std::string started() { return std::string(); }
 
     /* Feed the text generated since the last push; returns the bytes for what it completed.
      * `is_final` says the generation is over, which resolves whatever the reader was holding. */
     std::string push(std::string_view appended, bool is_final);
 
-    /* What closes the choice: the finish reason, and this choice's `timings` when they are valid
+    /* What closes the choice: the finish reason, and this choice's `timings` when valid
      * (llama.cpp sends them on the final chunk). `u` is the request's usage, for the shapes that
      * close a message with it. */
     virtual std::string final_chunk(Finish f, const TimingsOut& t, const UsageOut& u) = 0;
-    /* What closes a choice the engine failed, in place of final_chunk: the shape's own failure,
-     * so a client reading to the terminal event never takes a truncated reply as complete.
-     * OpenAI's chunks have none, so theirs is the final chunk with finish_reason "error" and the
-     * error object after it. */
+    /* Closes a choice the engine failed, in place of final_chunk, with the shape's own failure so
+     * a client never takes a truncated reply as complete. OpenAI's chunks have no failure event,
+     * so the default is the final chunk with finish_reason "error" followed by the error object. */
     virtual std::string error_chunk(const ApiError& e, const TimingsOut& t, const UsageOut& u);
 
-    /* What the whole generation parsed to -- the non-streaming shape. Complete once push has
-     * been called with is_final. */
+    /* The whole generation parsed (the non-streaming shape). Complete once push has been called
+     * with is_final. */
     const ParsedMessage& parsed() const { return last_; }
     Finish adjusted_finish(Finish f) const;
 
     /* llama.cpp's `timings_per_token`, for the shapes that carry timings. */
     virtual void set_timings(const TimingsOut&) {}
-    /* Logprobs entries (logprobs_content's elements) for the next chunk this stream writes, for
-     * the shapes that carry them; the others drop them. */
+    /* Logprobs entries (logprobs_content's elements) for the next chunk written, for the shapes
+     * that carry them; the others drop them. */
     virtual void add_logprobs(const std::string&) {}
 
 protected:
@@ -496,20 +480,21 @@ protected:
     std::vector  ev_;
 };
 
-/* ANTHROPIC'S MESSAGES API, translated into the chat request it means (`*chat`, a /v1/chat/completions
- * body) so that every refusal and default is the chat endpoint's. `*label` is the conversation's
- * label if the request carries one (metadata.user_id). Claude Code's per-request billing stamp in
- * the system prompt is held constant, as llama-server holds it, or no turn of a conversation could
- * reuse the one before it. */
+/* Anthropic's Messages API, translated into the equivalent /v1/chat/completions body (`*chat`),
+ * so every refusal and default is the chat endpoint's. `*label` is the conversation label if the
+ * request carries one (metadata.user_id); `*context_management` is set when the request sent
+ * one (OaiRequest::context_management). Claude Code's per-request billing stamp in the system
+ * prompt is held constant, as llama-server does, so consecutive turns can reuse the prefix
+ * cache. */
 int anthropic_to_chat(const std::string& body, const OaiLimits& lim, std::string* chat,
-                      std::string* label, ApiError* err);
+                      std::string* label, ApiError* err, bool* context_management = nullptr);
 /* The non-streaming answer, and an error, in Anthropic's shapes. */
 std::string anthropic_message_body(const OaiRequest& r, const ChoiceOut& c, const UsageOut& u);
 std::string anthropic_error_body(const ApiError& e);
-/* OPENAI'S RESPONSES API, translated into the chat request it means, as Anthropic's is. `*echo` is
- * the request's fields the response object repeats back. previous_response_id needs responses
- * stored server-side and is refused; tool types other than function have no chat equivalent and
- * are left out, as llama-server leaves them out. */
+/* OpenAI's Responses API, translated into the equivalent chat request like Anthropic's. `*echo`
+ * holds the request fields the response object repeats. previous_response_id needs server-side
+ * storage and is refused; non-function tool types have no chat equivalent and are dropped, as
+ * llama-server does. */
 int responses_to_chat(const std::string& body, const OaiLimits& lim, std::string* chat,
                       std::string* echo, ApiError* err);
 std::string responses_body(const OaiRequest& r, const ChoiceOut& c, const UsageOut& u);
@@ -517,19 +502,24 @@ std::string responses_body(const OaiRequest& r, const ChoiceOut& c, const UsageO
 /* Anthropic's stop_reason for a finish and the stop string that caused it. */
 const char* anthropic_stop_reason(const OaiRequest& r, Finish f, const std::string& stop_word);
 
-/* OpenAI's chat.completion.chunk. */
+/* OpenAI's chat.completion.chunk. The opening chunk (`role: assistant`, empty content) goes out
+ * with the choice's first token (started), not when the stream opens, as vLLM and llama-server
+ * send it: a client that times its first data chunk (llama-benchy's ttfr) then times the first
+ * token, not the start of the prefill. It precedes every other chunk of the choice, also when
+ * the reply has no text. */
 class ChatDeltaStream final : public ReplyStream {
 public:
     ChatDeltaStream(const OaiRequest& r, int index, const IReplyParser* parser)
         : ReplyStream(r, index, parser), legacy_(r.legacy_functions) {}
     std::string first_chunk() override;
+    std::string started() override;
     std::string final_chunk(Finish f, const TimingsOut& t, const UsageOut& u) override;
 
-    /* llama.cpp's `timings_per_token`: the timings the next pushes' chunks carry, beside
-     * `choices` as the final chunk carries them. Invalid timings carry nothing. */
+    /* llama.cpp's `timings_per_token`: the timings the next chunks carry beside `choices`, as the
+     * final chunk does. Invalid timings carry nothing. */
     void set_timings(const TimingsOut& t) override;
-    /* OpenAI's `logprobs.content` on the next chunk out: entries wait for one, because a push may
-     * complete no delta (a tool call's opening, a held-back byte) and the tokens still count. */
+    /* OpenAI's `logprobs.content` on the next chunk out. Entries wait for a chunk because a
+     * push may complete no delta (a tool call's opening, a held-back byte). */
     void add_logprobs(const std::string& elems) override;
 
 private:
@@ -537,23 +527,27 @@ private:
     std::string chunk(json delta, const char* finish_reason, const TimingsOut* t = nullptr);
     std::string lp_;       /* pending logprobs entries, comma-joined */
 
-    /* A delta's chunk is written, not built: the frame around the delta object is the same in
-     * every one, so it is serialised once, and the delta between is written with
-     * json_quote_append. The bytes are the ones chunk() writes for the same delta. */
+    /* Delta chunks are written, not built: the frame around the delta object is serialised once
+     * and the delta written with json_quote_append. The bytes match what chunk() writes. */
     void delta_open(std::string& out);
     void delta_close(std::string& out);
+    /* The opening chunk, once, ahead of the first one written. */
+    void open_role(std::string& out);
+    bool        role_sent_ = false;
     std::string head_;     /* `data: {...,"choices":[{"index":N,"delta":`, built on first use */
     std::string timings_;  /* `"timings":{...}` for every delta chunk, or "" */
     bool        legacy_;   /* OaiRequest::legacy_functions */
 };
 
-/* ANTHROPIC'S EVENTS: message_start, then a content block a kind -- thinking, text, each tool_use
- * -- opened, filled by deltas and stopped, then message_delta with the stop reason and the usage,
- * and message_stop. The prefill a continued conversation ends in is not repeated (`continued`). */
+/* Anthropic's events: message_start once the first token exists (started); each content block
+ * (thinking, text, each tool_use) opened, filled by deltas and stopped; then message_delta with
+ * the stop reason and usage, and message_stop. message_start precedes every other event, an
+ * error included. The prefill of a continued conversation is not repeated (`continued`). */
 class AnthropicStream final : public ReplyStream {
 public:
     AnthropicStream(const OaiRequest& r, int index, const IReplyParser* parser);
     std::string first_chunk() override;
+    std::string started() override;
     std::string final_chunk(Finish f, const TimingsOut& t, const UsageOut& u) override;
     /* Anthropic's `error` event, which ends the stream with no message_stop. */
     std::string error_chunk(const ApiError& e, const TimingsOut& t, const UsageOut& u) override;
@@ -565,21 +559,25 @@ private:
     std::string emit(const std::vector& ev) override;
     void open(std::string& out, Block b, const ToolCall* tc);
     void close(std::string& out);
+    void text_delta(std::string& out, const std::string& text);
+    void release_held(std::string& out);
     static void event(std::string& out, const char* type, const json& data);
 
     const OaiRequest* r_;
     int64_t     n_input_ = 0;
     std::string skip_;           /* the prefill still to be passed over */
+    std::string held_;           /* content matching the start of `skip_` so far, not yet sent */
     std::string stop_word_;
     Block       block_ = Block::None;
     int         n_blocks_ = 0;   /* blocks opened so far: the next one's index */
+    bool        started_ = false;   /* message_start sent */
 };
 
-/* THE RESPONSES API'S EVENTS: response.created and .in_progress; an output item a kind --
- * reasoning, the message, each function call -- added, its content part added, filled by deltas,
- * and done; then response.completed (or .incomplete at the token limit) with the whole response.
- * Every event carries its output_index, content_index and sequence_number, which the OpenAI SDK's
- * stream accumulator places deltas by. */
+/* The Responses API's events: response.created and .in_progress; per output item (reasoning, the
+ * message, each function call) item added, content part added, deltas, done; then
+ * response.completed (or .incomplete at the token limit) with the whole response. Every event
+ * carries output_index, content_index and sequence_number, by which the OpenAI SDK's stream
+ * accumulator places deltas. */
 class ResponsesStream final : public ReplyStream {
 public:
     ResponsesStream(const OaiRequest& r, int index, const IReplyParser* parser);
@@ -600,14 +598,14 @@ private:
     Item        item_ = Item::None;
     std::string item_id_, text_;  /* the open item's id and its text so far */
     size_t      call_ = 0;            /* the open call's index into last_.tool_calls */
-    std::vector items_;  /* every closed item, serialised, in output order */
+    std::vector items_;  /* every closed item, in output order */
     int64_t     seq_ = 0;
     UsageOut    usage_;
     const char* incomplete_ = nullptr;
 };
 
-/* The SSE terminator. Written once at the end of every stream, including a failed one, because a
- * client blocked on the reader has no other way to learn the stream is over. */
+/* The SSE terminator. Written once at the end of every stream, failed ones included, since a
+ * blocked client reader has no other way to learn the stream is over. */
 extern const char* const SSE_DONE;
 
 std::string sse_event(const std::string& json_text);
@@ -617,18 +615,17 @@ std::string sse_error(const ApiError& e);
 
 std::string base64_encode(const void* data, size_t len);
 bool        base64_decode(const std::string& in, std::vector* out);
-/* A token id as a request spells it: an integer in [0, INT32_MAX]. False for anything else, and
- * the caller refuses the request -- narrowing instead would make 2^32 + 5 an alias of token 5. */
+/* A token id as a request spells it: an integer in [0, INT32_MAX]. False otherwise, and the
+ * caller refuses the request; narrowing would make 2^32 + 5 an alias of token 5. */
 bool        token_id(const json& v, int32_t* out);
 
 /* Parse a request body into a tree of at most json_value_budget(max_ctx) values, nested at most
- * kJsonMaxDepth deep. A syntax error comes back discarded, as json::parse's would; a body with
- * more values than the budget sets `*over`, and one nested deeper than the bound sets `*deep`,
- * and either comes back holding only what fitted, which the caller refuses. See the definition
- * for why the tree is bounded rather than the body alone. */
+ * kJsonMaxDepth deep. A syntax error returns discarded, as json::parse does. Exceeding the value
+ * budget sets `*over`, exceeding the depth sets `*deep`, and either returns a partial tree the
+ * caller refuses. See the definition for why the tree, not just the body, is bounded. */
 json        parse_json_bounded(const std::string& body, int64_t max_ctx, bool* over, bool* deep);
-/* The body of a generation endpoint: parse_json_bounded, and a 400 saying which bound it broke or
- * that it is not one JSON object. */
+/* The body of a generation endpoint: parse_json_bounded, and a 400 naming the broken bound or
+ * saying it is not one JSON object. */
 int         parse_request_object(const std::string& body, const OaiLimits& lim, json* b,
                                  ApiError* err);
 int64_t     json_value_budget(int64_t max_ctx);
diff --git a/core/server/realtime.cpp b/core/server/realtime.cpp
new file mode 100644
index 00000000..ad613d6c
--- /dev/null
+++ b/core/server/realtime.cpp
@@ -0,0 +1,978 @@
+/* realtime.cpp -- OpenAI's realtime transcription session, over a WebSocket at /v1/realtime.
+ *
+ * The upload route (speech.cpp) transcribes a recording once it has ended. This one is sent the
+ * audio as it is captured and answers with the words as they settle, as OpenAI's live
+ * transcription does: deltas while the audio arrives, and a completed transcript for each turn
+ * once it is committed.
+ *
+ * Protocol: OpenAI's realtime one in its transcription form. The client sends `session.update`
+ * (session.type "transcription", or the beta's `transcription_session.update`) and
+ * `input_audio_buffer.append` / `.commit` / `.clear`. The server sends `session.created` /
+ * `.updated`, `input_audio_buffer.committed` / `.cleared` / `.speech_started` /
+ * `.speech_stopped`, `conversation.item.input_audio_transcription.delta` / `.completed` /
+ * `.failed`, and `error`. Audio is 16-bit little-endian mono PCM, base64 in an append or the same
+ * bytes as a binary frame, at the session's rate (24 kHz unless it names another), resampled to
+ * the model's.
+ *
+ * Settling: the encoder takes a clip whole, so a turn in progress is heard again from its start
+ * each time enough new audio has come in, one short pass whose prompt is the turn so far. Each
+ * pass is held to what the earlier ones settled (the settled reply tokens follow the prompt as the
+ * start of the reply, so the pass decodes only what comes after them) and settles all of its reply
+ * but the last few tokens, which the end of the audio can still change: a word cut off mid-sound,
+ * or the full stop the model puts after what it has heard so far. Settled text is sent as a delta
+ * and never taken back; the rest is sent as `radiance.input_audio_transcription.tentative`, which
+ * each pass replaces. OpenAI's protocol has no such event, and a client that does not know it
+ * ignores it.
+ *
+ * A turn ends at the client's commit, or at a pause with server_vad turn detection, and is then
+ * heard once more, whole, for its completed transcript. A turn that reaches the length of one
+ * encoder pass is committed at its quietest point in the last five seconds, and the rest goes on
+ * as the next turn.
+ *
+ * The model's side comes from its plugin (RadAudioFormat) through the helpers the upload route
+ * uses; this file knows OpenAI's side.
+ *
+ * Threads: the connection's thread reads messages and queues them. The session's thread does
+ * everything else (the audio, the passes, every event sent), so the session's state has one owner
+ * and its events go out in the order they happen.
+ */
+#include "server.h"
+#include "server_priv.h"
+
+#include "mm/processor.h"
+#include "mm/resample.h"
+#include "rad_internal.h"
+
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace rad {
+namespace server {
+
+namespace {
+
+using ojson = nlohmann::ordered_json;
+using Clock = std::chrono::steady_clock;
+
+/* A pass once this much audio has come in since the turn's last one began. */
+constexpr double kStepSeconds = 0.5;
+/* No pass hears less than this. */
+constexpr double kFirstPassSeconds = 0.5;
+/* Nothing settles before the turn has this much audio: the first words of a turn heard on their
+ * own are where the model guesses most. */
+constexpr double kSettleAfterSeconds = 1.0;
+/* The most one pass may decode. Thirty seconds of the fastest speech is a few hundred tokens. */
+constexpr int32_t kMaxTokensPerPass = 512;
+/* The client messages a session may have queued and not yet taken in. */
+constexpr size_t kMaxQueuedBytes = 16u << 20;
+/* Committed turns not yet transcribed: past either bound the session has fallen behind its
+ * audio for good, and is closed with an error rather than left to grow. */
+constexpr double kMaxBehindSeconds = 120.0;
+constexpr size_t kMaxBehindTurns = 64;
+/* A client commit needs at least this much audio, as OpenAI's does. */
+constexpr int64_t kMinCommitMs = 100;
+/* Pause detection: a frame, the speech that starts a turn, and the level nothing under counts as
+ * speech however quiet the room. */
+constexpr int32_t kFrameMs = 20;
+constexpr int kStartFrames = 3;
+constexpr double kSpeechFloorDb = -55.0;
+
+/* The reply tokens left unsettled, by OpenAI's `delay`: how far behind the speech the settled
+ * text may run. A settled word is never taken back, even when the rest of the sentence would have
+ * changed it, so the default leaves a few words open: on LibriSpeech, four tokens settled
+ * "The English forwarded" once as "The English voted", and six did not. The tentative text shows
+ * the open words meanwhile. */
+int unsettled_for(const std::string& delay) {
+    if (delay == "minimal") return 3;
+    if (delay == "low") return 4;
+    if (delay == "high") return 8;
+    if (delay == "xhigh") return 10;
+    return 6;   /* medium */
+}
+
+bool starts_with(const std::string& s, const std::string& p) {
+    return s.size() >= p.size() && s.compare(0, p.size(), p) == 0;
+}
+
+std::string rtrim(std::string s) {
+    while (!s.empty() && std::isspace((unsigned char)s.back())) s.pop_back();
+    return s;
+}
+
+/* A string member, or `def` when it is absent or not a string. */
+std::string str_of(const ojson& o, const char* k, const std::string& def) {
+    return o.contains(k) && o[k].is_string() ? o[k].get() : def;
+}
+
+ojson event(const char* type) {
+    ojson o;
+    o["type"] = type;
+    o["event_id"] = random_id("event_");
+    return o;
+}
+
+}  /* namespace */
+
+/* One turn: its audio at the model's rate, and what of its transcript has gone out. */
+struct RtTurn {
+    std::string id;
+    std::vector audio;
+    int64_t start_ms = 0;               /* on the session's clock */
+    bool    committed = false;
+    bool    dropped = false;            /* cleared before it was committed */
+    Clock::time_point committed_at;
+    std::vector settled;       /* reply tokens every later pass is held to */
+    std::string sent;                   /* transcript text sent as deltas */
+    std::string tentative;              /* the tentative text last sent */
+    size_t  heard = 0;                  /* audio.size() when its last pass began */
+    int64_t n_prompt = 0, n_gen = 0;
+    int     passes = 0;
+};
+
+struct Server::RealtimeSession {
+    std::string id;
+    std::string peer;
+
+    /* The connection's thread to the session's: messages, and whether the peer is gone. */
+    std::mutex m;
+    std::condition_variable cv;
+    std::deque> inbox;   /* (message, binary) */
+    size_t inbox_bytes = 0;
+    bool   peer_gone = false;
+    bool   overflow = false;
+
+    /* Everything below is the session thread's alone. */
+    std::string model;
+    bool        beta = false;            /* answers in the beta's event names */
+    int32_t     rate = 24000;            /* the client's audio */
+    std::string language_code;           /* as the client named it, "" for none */
+    std::string language;                /* the model's name for it, "" to detect */
+    std::string prompt;
+    std::vector keywords;
+    std::string delay;
+    int         unsettled = 6;
+    bool        vad = false;
+    double      threshold = 0.5;
+    int         prefix_ms = 300;
+    int         silence_ms = 500;
+
+    int32_t model_rate = 16000;
+    std::unique_ptr rs;
+    int64_t clock = 0;                   /* samples at the model's rate heard so far */
+    std::vector frame;            /* pause detection's frame in progress */
+    std::vector recent;           /* the audio before speech, for the turn's lead-in */
+    double floor_db = NAN;
+    bool   speaking = false;
+    int    run = 0, quiet = 0;
+
+    std::shared_ptr open;        /* the turn the audio goes into */
+    std::deque> turns;   /* committed, not yet completed */
+    std::string last_item;
+
+    struct Pass {
+        std::shared_ptr turn;
+        bool   final = false;
+        size_t heard = 0;
+        OaiRequest r;
+        std::vector gens;
+        bool   running = false;
+    } pass;
+
+    int64_t n_turns = 0;
+
+    int64_t ms(int64_t samples) const { return samples * 1000 / model_rate; }
+    std::string context() const {
+        std::string c = prompt;
+        if (!keywords.empty()) {
+            if (!c.empty()) c += "\n";
+            for (size_t i = 0; i < keywords.size(); ++i) c += (i ? ", " : "") + keywords[i];
+        }
+        return c;
+    }
+};
+
+/* ------------------------------------------------------------------ the connection's thread */
+
+void Server::handle_realtime(const HttpRequest& req, WsConn& ws) {
+    auto refuse = [&](const char* type, const char* code, const std::string& why, int close_code) {
+        ojson o = event("error");
+        ojson e;
+        e["type"] = type;
+        e["code"] = code;
+        e["message"] = why;
+        e["param"] = nullptr;
+        e["event_id"] = nullptr;
+        o["error"] = std::move(e);
+        ws.send(json_dump(o));
+        RAD_INFO("realtime refused from %s: %s", req.peer.c_str(), why.c_str());
+        ws.close(close_code, code);
+    };
+    if (stopping_.load()) return refuse("server_error", "shutting_down",
+                                        "the server is shutting down", 1001);
+    if (!deps_.sched || !deps_.tok || !deps_.speech || !deps_.speech->transcribes() || !deps_.mm ||
+        !deps_.mm->accepts(MediaKind::Audio) || deps_.mm->audio_rate() <= 0)
+        return refuse("invalid_request_error", "model_not_supported",
+                      "this model does not transcribe: its architecture plugin states no "
+                      "transcription format (rad_arch_audio_format), or it was started without "
+                      "its audio encoder", 1008);
+    /* A session holds a connection's thread and one of its own for its whole life, and runs one
+     * pass at a time: more sessions than the engine has sequences would only queue. */
+    const int64_t cap = std::max(1, opt_.max_seqs);
+    if (realtime_sessions_.fetch_add(1) >= cap) {
+        realtime_sessions_.fetch_sub(1);
+        return refuse("server_error", "session_limit",
+                      fmt("this server holds %lld realtime sessions at once; try again later",
+                          (long long)cap), 1013);
+    }
+    struct Count {
+        std::atomic& n;
+        ~Count() { n.fetch_sub(1); }
+    } count{ realtime_sessions_ };
+    /* One admission place for the session's whole life, which its passes run in, so a session
+     * counts against the queue (and the HTTP workers sized from it) like any request. */
+    if (admit(1, req.peer))
+        return refuse("server_error", "rate_limit_exceeded",
+                      "the admission queue is full; try again later", 1013);
+    struct Place {
+        Server& srv;
+        ~Place() { srv.release(1); }
+    } place{ *this };
+
+    RealtimeSession s;
+    s.id = random_id("sess_");
+    s.peer = req.peer;
+    s.model = opt_.model_id;
+    s.model_rate = deps_.mm->audio_rate();
+    std::thread worker([this, &s, &ws] { realtime_run(s, ws); });
+    /* The session's thread ends once the peer is gone, however this one leaves. */
+    struct Join {
+        RealtimeSession& s;
+        std::thread& t;
+        ~Join() {
+            {
+                std::lock_guard lk(s.m);
+                s.peer_gone = true;
+            }
+            s.cv.notify_one();
+            if (t.joinable()) t.join();
+        }
+    } join{ s, worker };
+
+    std::string msg;
+    bool binary = false;
+    while (ws.read(&msg, &binary)) {
+        std::lock_guard lk(s.m);
+        if (s.inbox_bytes + msg.size() > kMaxQueuedBytes) {
+            s.overflow = true;
+            s.cv.notify_one();
+            break;
+        }
+        s.inbox_bytes += msg.size();
+        s.inbox.emplace_back(std::move(msg), binary);
+        s.cv.notify_one();
+    }
+}
+
+/* ------------------------------------------------------------------ the session's thread */
+
+void Server::realtime_run(RealtimeSession& s, WsConn& ws) {
+    bool server_closed = true;
+    try {
+        server_closed = realtime_loop(s, ws);
+    } catch (const std::exception& e) {
+        RAD_ERR("realtime %s failed: %s", s.id.c_str(), e.what());
+        ojson o = event("error");
+        ojson err;
+        err["type"] = "server_error";
+        err["code"] = "internal_error";
+        err["message"] = std::string("the session failed: ") + e.what();
+        err["param"] = nullptr;
+        err["event_id"] = nullptr;
+        o["error"] = std::move(err);
+        ws.send(json_dump(o));
+        ws.close(1011, "internal error");
+    }
+    if (s.pass.running) {
+        cancel_all(s.pass.gens, !server_closed);
+        record(s.pass.r, s.pass.gens, Finish::Cancelled, /*quiet=*/true);
+        retire(s.pass.gens);
+        s.pass.running = false;
+    }
+    RAD_INFO("realtime %s closed: %lld turns, %.1fs of audio", s.id.c_str(),
+             (long long)s.n_turns, (double)s.clock / s.model_rate);
+}
+
+bool Server::realtime_loop(RealtimeSession& s, WsConn& ws) {
+    const SpeechFormat& f = *deps_.speech;
+    const int64_t max_clip = deps_.mm->audio_max_samples();
+    const int64_t frame_n = (int64_t)s.model_rate * kFrameMs / 1000;
+    /* Where a turn that reaches the length of a pass is cut: its last five seconds, or half of it
+     * if that is less. Nothing in this stretch settles, so whatever has gone out as a delta was
+     * heard before the cut, wherever in the stretch the cut lands. */
+    const int64_t cut_zone =
+        max_clip > 0 ? std::min(max_clip / 2, 5 * (int64_t)s.model_rate) : 0;
+    s.rs.reset(new mm::Resampler(s.rate, s.model_rate));
+
+    auto send = [&](const ojson& o) { ws.send(json_dump(o)); };
+    auto error = [&](const char* type, const std::string& code, const std::string& why,
+                     const std::string& param, const ojson& client_event) {
+        ojson o = event("error");
+        ojson e;
+        e["type"] = type;
+        e["code"] = code;
+        e["message"] = why;
+        e["param"] = param.empty() ? ojson(nullptr) : ojson(param);
+        e["event_id"] = client_event.is_string() ? client_event : ojson(nullptr);
+        o["error"] = std::move(e);
+        send(o);
+    };
+
+    /* ---- the session as the client sees it */
+    auto session_json = [&]() {
+        ojson tr;
+        tr["model"] = s.model;
+        tr["language"] = s.language_code.empty() ? ojson(nullptr) : ojson(s.language_code);
+        tr["prompt"] = s.prompt;
+        ojson td = nullptr;
+        if (s.vad) {
+            td = ojson::object();
+            td["type"] = "server_vad";
+            td["threshold"] = s.threshold;
+            td["prefix_padding_ms"] = s.prefix_ms;
+            td["silence_duration_ms"] = s.silence_ms;
+        }
+        ojson o;
+        if (s.beta) {
+            o["id"] = s.id;
+            o["object"] = "realtime.transcription_session";
+            o["input_audio_format"] = "pcm16";
+            o["input_audio_transcription"] = std::move(tr);
+            o["turn_detection"] = std::move(td);
+            o["input_audio_noise_reduction"] = nullptr;
+            return o;
+        }
+        if (!s.keywords.empty()) tr["keywords"] = s.keywords;
+        if (!s.delay.empty()) tr["delay"] = s.delay;
+        ojson fmt_o;
+        fmt_o["type"] = "audio/pcm";
+        fmt_o["rate"] = s.rate;
+        ojson in;
+        in["format"] = std::move(fmt_o);
+        in["transcription"] = std::move(tr);
+        in["turn_detection"] = std::move(td);
+        in["noise_reduction"] = nullptr;
+        o["type"] = "transcription";
+        o["object"] = "realtime.transcription_session";
+        o["id"] = s.id;
+        o["audio"]["input"] = std::move(in);
+        return o;
+    };
+
+    /* ---- turns */
+    auto new_turn = [&](int64_t start_ms) {
+        auto t = std::make_shared();
+        t->id = random_id("item_");
+        t->start_ms = start_ms;
+        return t;
+    };
+    auto commit_open = [&]() {
+        std::shared_ptr t = std::move(s.open);
+        s.open.reset();
+        t->committed = true;
+        t->committed_at = Clock::now();
+        ojson o = event("input_audio_buffer.committed");
+        o["previous_item_id"] = s.last_item.empty() ? ojson(nullptr) : ojson(s.last_item);
+        o["item_id"] = t->id;
+        send(o);
+        s.last_item = t->id;
+        s.turns.push_back(std::move(t));
+        ++s.n_turns;
+    };
+    /* A turn as long as one pass takes is committed at its quietest point in the last five
+     * seconds of that pass; what follows that point goes on as the next turn. */
+    auto bound_open = [&]() {
+        while (s.open && max_clip > 0 && (int64_t)s.open->audio.size() >= max_clip) {
+            std::vector& a = s.open->audio;
+            const int64_t cut = speech_quiet_point(a, max_clip - cut_zone, max_clip, s.model_rate);
+            std::vector rest(a.begin() + cut, a.end());
+            a.resize((size_t)cut);
+            const int64_t start = s.open->start_ms + s.ms(cut);
+            commit_open();
+            s.open = new_turn(start);
+            s.open->audio = std::move(rest);
+            if (s.vad) {
+                ojson o = event("input_audio_buffer.speech_started");
+                o["audio_start_ms"] = start;
+                o["item_id"] = s.open->id;
+                send(o);
+            }
+        }
+    };
+
+    /* ---- pause detection: a frame's level against the room's, tracked as its quietest */
+    auto vad_frame = [&](const float* x, int64_t n) {
+        double e = 0.0;
+        for (int64_t i = 0; i < n; ++i) e += (double)x[i] * x[i];
+        const double db = 10.0 * std::log10(e / (double)n + 1e-12);
+        if (std::isnan(s.floor_db) || db < s.floor_db) s.floor_db = db;
+        else s.floor_db += s.speaking ? 0.002 : 0.02;   /* 0.1 dB/s in speech, 1 dB/s out of it */
+        const double margin = 6.0 + 18.0 * s.threshold;
+        const bool voiced = db > std::max(s.floor_db + margin, kSpeechFloorDb);
+        s.clock += n;
+        if (!s.speaking) {
+            s.recent.insert(s.recent.end(), x, x + n);
+            s.run = voiced ? s.run + 1 : 0;
+            const size_t lead = (size_t)((int64_t)s.model_rate * s.prefix_ms / 1000 +
+                                         kStartFrames * n);
+            if (s.run >= kStartFrames) {
+                const size_t take = std::min(lead, s.recent.size());
+                s.open = new_turn(s.ms(s.clock) - s.ms((int64_t)take));
+                s.open->audio.assign(s.recent.end() - (std::ptrdiff_t)take, s.recent.end());
+                s.recent.clear();
+                s.speaking = true;
+                s.quiet = 0;
+                ojson o = event("input_audio_buffer.speech_started");
+                o["audio_start_ms"] = s.open->start_ms;
+                o["item_id"] = s.open->id;
+                send(o);
+            } else if (s.recent.size() > lead + (size_t)s.model_rate) {
+                s.recent.erase(s.recent.begin(), s.recent.end() - (std::ptrdiff_t)lead);
+            }
+            return;
+        }
+        s.open->audio.insert(s.open->audio.end(), x, x + n);
+        s.quiet = voiced ? 0 : s.quiet + 1;
+        if ((int64_t)s.quiet * kFrameMs >= s.silence_ms) {
+            s.speaking = false;
+            s.run = 0;
+            ojson o = event("input_audio_buffer.speech_stopped");
+            o["audio_end_ms"] = s.ms(s.clock);
+            o["item_id"] = s.open->id;
+            send(o);
+            commit_open();
+            return;
+        }
+        bound_open();
+    };
+
+    /* Audio at the model's rate, into the open turn or through pause detection. */
+    auto take = [&](const std::vector& x) {
+        if (x.empty()) return;
+        if (!s.vad) {
+            if (!s.open) s.open = new_turn(s.ms(s.clock));
+            s.open->audio.insert(s.open->audio.end(), x.begin(), x.end());
+            s.clock += (int64_t)x.size();
+            bound_open();
+            return;
+        }
+        size_t i = 0;
+        while (i < x.size()) {
+            const size_t k = std::min(x.size() - i, (size_t)frame_n - s.frame.size());
+            s.frame.insert(s.frame.end(), x.begin() + (std::ptrdiff_t)i,
+                           x.begin() + (std::ptrdiff_t)(i + k));
+            i += k;
+            if ((int64_t)s.frame.size() == frame_n) {
+                vad_frame(s.frame.data(), frame_n);
+                s.frame.clear();
+            }
+        }
+    };
+    auto append_pcm = [&](const uint8_t* p, size_t n, const ojson& eid) {
+        if (n % 2) {
+            error("invalid_request_error", "invalid_value",
+                  "the audio is 16-bit PCM, two bytes a sample; this chunk has an odd length",
+                  "audio", eid);
+            return;
+        }
+        std::vector in(n / 2), out;
+        for (size_t i = 0; i < n / 2; ++i)
+            in[i] = (float)(int16_t)(uint16_t)(p[2 * i] | (p[2 * i + 1] << 8)) / 32768.0f;
+        s.rs->push(in.data(), in.size(), &out);
+        take(out);
+    };
+    /* The pause detector's half-heard frame, into the open turn when there is one. */
+    auto flush_frame = [&]() {
+        if (s.speaking && s.open) s.open->audio.insert(s.open->audio.end(), s.frame.begin(),
+                                                      s.frame.end());
+        s.clock += (int64_t)s.frame.size();
+        s.frame.clear();
+    };
+
+    /* ---- session.update: checked whole, then applied whole */
+    auto update = [&](const ojson& j, bool beta) {
+        const ojson eid = j.contains("event_id") ? j["event_id"] : ojson(nullptr);
+        const char* ack = beta ? "transcription_session.updated" : "session.updated";
+        if (!j.contains("session") || !j["session"].is_object())
+            return error("invalid_request_error", "missing_required_parameter",
+                         "the update carries no session object", "session", eid);
+        const ojson& se = j["session"];
+        int32_t rate = s.rate;
+        std::string code = s.language_code, name = s.language, prompt = s.prompt, delay = s.delay;
+        std::vector keywords = s.keywords;
+        bool vad = s.vad;
+        double threshold = s.threshold;
+        int prefix = s.prefix_ms, silence = s.silence_ms;
+        std::string model = s.model;
+        auto bad = [&](const std::string& param, const std::string& why) {
+            error("invalid_request_error", "invalid_value", why, param, eid);
+        };
+        const ojson* tr = nullptr;
+        const ojson* td = nullptr;
+        bool has_td = false;
+        if (!beta) {
+            if (se.contains("type") && se["type"] != "transcription")
+                return bad("session.type", "this server's realtime sessions transcribe: "
+                                           "session.type is \"transcription\"");
+            if (se.contains("audio") && se["audio"].is_object() && se["audio"].contains("input") &&
+                se["audio"]["input"].is_object()) {
+                const ojson& in = se["audio"]["input"];
+                if (in.contains("format") && in["format"].is_object()) {
+                    const ojson& fo = in["format"];
+                    if (str_of(fo, "type", "audio/pcm") != "audio/pcm")
+                        return bad("session.audio.input.format.type",
+                                   "the audio is \"audio/pcm\": 16-bit little-endian mono");
+                    if (fo.contains("rate")) {
+                        if (!fo["rate"].is_number_integer() ||
+                            !mm::Resampler::takes(fo["rate"].get()))
+                            return bad("session.audio.input.format.rate",
+                                       "the rate is one of " + mm::Resampler::rates() + " Hz");
+                        rate = fo["rate"].get();
+                    }
+                }
+                if (in.contains("transcription") && in["transcription"].is_object())
+                    tr = &in["transcription"];
+                if (in.contains("turn_detection")) { td = &in["turn_detection"]; has_td = true; }
+            }
+        } else {
+            if (se.contains("input_audio_format") && se["input_audio_format"] != "pcm16")
+                return bad("session.input_audio_format",
+                           "the audio is \"pcm16\": 16-bit little-endian mono at 24 kHz");
+            if (se.contains("input_audio_format")) rate = 24000;
+            if (se.contains("input_audio_transcription") &&
+                se["input_audio_transcription"].is_object())
+                tr = &se["input_audio_transcription"];
+            if (se.contains("turn_detection")) { td = &se["turn_detection"]; has_td = true; }
+        }
+        if (tr) {
+            const ojson& t = *tr;
+            model = str_of(t, "model", model);
+            std::string want = str_of(t, "language", "");
+            bool detect = t.contains("language") && t["language"].is_null();
+            /* The live models' `languages`: one is a forced language; several, detection. */
+            if (t.contains("languages") && t["languages"].is_array()) {
+                if (t["languages"].size() == 1 && t["languages"][0].is_string())
+                    want = t["languages"][0].get();
+                else
+                    detect = true;
+            }
+            if (detect && want.empty()) {
+                code.clear();
+                name.clear();
+            }
+            if (!want.empty()) {
+                const std::string n = f.language_name(want);
+                if (n.empty()) {
+                    std::string known;
+                    for (const auto& l : f.languages)
+                        known += (known.empty() ? "" : ", ") + l.first;
+                    return bad("session.audio.input.transcription.language",
+                               "this model names no language '" + want + "'; it knows " + known);
+                }
+                code = want;
+                name = n;
+            }
+            prompt = str_of(t, "prompt", prompt);
+            if (t.contains("keywords") && t["keywords"].is_array()) {
+                keywords.clear();
+                for (const auto& k : t["keywords"])
+                    if (k.is_string()) keywords.push_back(k.get());
+            }
+            if (t.contains("delay") && t["delay"].is_string()) {
+                delay = str_of(t, "delay", "");
+                if (delay != "minimal" && delay != "low" && delay != "medium" && delay != "high" &&
+                    delay != "xhigh")
+                    return bad("session.audio.input.transcription.delay",
+                               "delay is minimal, low, medium, high or xhigh");
+            }
+        }
+        if (has_td) {
+            const ojson& t = *td;
+            if (t.is_null()) {
+                vad = false;
+            } else if (t.is_object()) {
+                const std::string type = str_of(t, "type", "server_vad");
+                if (type != "server_vad")
+                    return bad("turn_detection.type",
+                               "turn detection is server_vad, or null for turns the client "
+                               "commits; not '" + type + "'");
+                vad = true;
+                if (t.contains("threshold") && t["threshold"].is_number()) {
+                    threshold = t["threshold"].get();
+                    if (!(threshold >= 0.0 && threshold <= 1.0))
+                        return bad("turn_detection.threshold", "threshold is between 0 and 1");
+                }
+                if (t.contains("prefix_padding_ms") && t["prefix_padding_ms"].is_number_integer())
+                    prefix = std::clamp(t["prefix_padding_ms"].get(), 0, 2000);
+                if (t.contains("silence_duration_ms") &&
+                    t["silence_duration_ms"].is_number_integer())
+                    silence = std::clamp(t["silence_duration_ms"].get(), 100, 5000);
+            } else {
+                return bad("turn_detection", "turn detection is an object or null");
+            }
+        }
+
+        /* Applied. Audio already in at the old rate comes out before the new rate's. */
+        if (rate != s.rate) {
+            std::vector tail;
+            s.rs->flush(&tail);
+            take(tail);
+            s.rate = rate;
+            s.rs.reset(new mm::Resampler(s.rate, s.model_rate));
+        }
+        if (vad != s.vad) {
+            if (s.vad) flush_frame();            /* off: the open turn waits for a commit */
+            s.speaking = vad && s.open && !s.open->audio.empty();
+            s.run = s.quiet = 0;
+            s.recent.clear();
+            s.vad = vad;
+        }
+        s.beta = beta;
+        s.model = model;
+        s.language_code = code;
+        s.language = name;
+        s.prompt = prompt;
+        s.keywords = keywords;
+        s.delay = delay;
+        s.unsettled = unsettled_for(delay);
+        s.threshold = threshold;
+        s.prefix_ms = prefix;
+        s.silence_ms = silence;
+        ojson o = event(ack);
+        o["session"] = session_json();
+        send(o);
+    };
+
+    auto handle = [&](const std::string& msg, bool binary) {
+        if (binary) return append_pcm((const uint8_t*)msg.data(), msg.size(), nullptr);
+        const ojson j = ojson::parse(msg, nullptr, /*allow_exceptions=*/false);
+        if (j.is_discarded() || !j.is_object() || !j.contains("type") || !j["type"].is_string())
+            return error("invalid_request_error", "invalid_json",
+                         "a client event is a JSON object with a string `type`", "", nullptr);
+        const std::string type = j["type"].get();
+        const ojson eid = j.contains("event_id") ? j["event_id"] : ojson(nullptr);
+        if (type == "input_audio_buffer.append") {
+            std::vector pcm;
+            if (!j.contains("audio") || !j["audio"].is_string() ||
+                !base64_decode(j["audio"].get(), &pcm))
+                return error("invalid_request_error", "invalid_value",
+                             "`audio` is base64 of 16-bit little-endian PCM", "audio", eid);
+            return append_pcm(pcm.data(), pcm.size(), eid);
+        }
+        if (type == "input_audio_buffer.commit") {
+            /* The turn ends here: what the resampler still holds back belongs to it. */
+            std::vector tail;
+            s.rs->flush(&tail);
+            take(tail);
+            if (s.vad) flush_frame();
+            if (!s.open || s.ms((int64_t)s.open->audio.size()) < kMinCommitMs)
+                return error("invalid_request_error", "input_audio_buffer_commit_empty",
+                             fmt("the buffer holds less than %lld ms of audio",
+                                 (long long)kMinCommitMs), "", eid);
+            commit_open();
+            s.speaking = false;
+            s.run = s.quiet = 0;
+            return;
+        }
+        if (type == "input_audio_buffer.clear") {
+            if (s.open) s.open->dropped = true;
+            s.open.reset();
+            s.frame.clear();
+            s.recent.clear();
+            s.speaking = false;
+            s.run = s.quiet = 0;
+            send(event("input_audio_buffer.cleared"));
+            return;
+        }
+        if (type == "session.update") return update(j, false);
+        if (type == "transcription_session.update") return update(j, true);
+        error("invalid_request_error", "unknown_event",
+              "this session takes session.update, input_audio_buffer.append, "
+              "input_audio_buffer.commit and input_audio_buffer.clear; not '" + type + "'",
+              "type", eid);
+    };
+
+    /* ---- passes */
+    auto detok = [&](const std::vector& ids, bool flush) {
+        std::unique_ptr d = deps_.tok->detokenizer({});
+        std::string t;
+        for (int32_t id : ids) t += d->push(id);
+        if (flush) t += d->flush();
+        return t;
+    };
+    auto usage = [](const RtTurn& t) {
+        ojson u;
+        u["type"] = "tokens";
+        u["input_tokens"] = t.n_prompt;
+        u["output_tokens"] = t.n_gen;
+        u["total_tokens"] = t.n_prompt + t.n_gen;
+        return u;
+    };
+    auto delta = [&](RtTurn& t, const std::string& d) {
+        if (d.empty()) return;
+        ojson o = event("conversation.item.input_audio_transcription.delta");
+        o["item_id"] = t.id;
+        o["content_index"] = 0;
+        o["delta"] = d;
+        send(o);
+        t.sent += d;
+    };
+    auto failed = [&](RtTurn& t, const std::string& why) {
+        ojson o = event("conversation.item.input_audio_transcription.failed");
+        o["item_id"] = t.id;
+        o["content_index"] = 0;
+        ojson e;
+        e["type"] = "server_error";
+        e["code"] = nullptr;
+        e["message"] = why;
+        e["param"] = nullptr;
+        o["error"] = std::move(e);
+        send(o);
+        RAD_WARN("realtime %s %s failed: %s", s.id.c_str(), t.id.c_str(), why.c_str());
+    };
+    auto drop_front = [&](const std::shared_ptr& t) {
+        if (!s.turns.empty() && s.turns.front() == t) s.turns.pop_front();
+    };
+
+    /* What to hear next: the oldest committed turn whole, else the open turn once enough new
+     * audio has come in. */
+    auto next_work = [&](bool* final) -> std::shared_ptr {
+        if (s.pass.running) return nullptr;
+        if (!s.turns.empty()) { *final = true; return s.turns.front(); }
+        if (!s.open) return nullptr;
+        const size_t n = s.open->audio.size();
+        if ((double)n < kFirstPassSeconds * s.model_rate ||
+            (double)n < (double)s.open->heard + kStepSeconds * s.model_rate)
+            return nullptr;
+        *final = false;
+        return s.open;
+    };
+
+    auto start_pass = [&](const std::shared_ptr& t, bool final) {
+        const size_t n = t->audio.size();
+        std::shared_ptr item;
+        std::string why;
+        PromptInput p;
+        const int st = deps_.mm->prepare_audio(t->audio, &item, &why);
+        if (st < 0 || !item ||
+            speech_prompt(f, *deps_.tok, s.context(),
+                          s.language.empty() ? std::string() : speech_language_text(f, s.language),
+                          item, &p) < 0) {
+            t->heard = n;
+            if (final) {
+                failed(*t, st < 0 ? "the audio could not be used: " + why
+                                  : "the model's transcription template has no {audio} slot");
+                drop_front(t);
+            }
+            return;
+        }
+        p.tokens.insert(p.tokens.end(), t->settled.begin(), t->settled.end());
+        OaiRequest& r = s.pass.r;
+        r = OaiRequest{};
+        r.endpoint = Endpoint::Completion;
+        r.shape = ApiShape::OpenAI;
+        r.model = opt_.model_id;
+        r.id = random_id("rt-");
+        r.created = (int64_t)std::time(nullptr);
+        r.peer = s.peer;
+        r.n = 1;
+        r.sp = SamplingParams{};
+        r.sp.temp = 0.0f;
+        r.sp.top_k = 1;
+        r.return_tokens = true;
+        r.max_tokens = kMaxTokensPerPass;
+        if (lim_.max_ctx > 0) {
+            if ((int64_t)p.tokens.size() >= lim_.max_ctx) {
+                t->heard = n;
+                if (final) {
+                    failed(*t, "the turn's prompt is longer than the context");
+                    drop_front(t);
+                }
+                return;
+            }
+            r.max_tokens = (int32_t)std::min(r.max_tokens,
+                                                      lim_.max_ctx - (int64_t)p.tokens.size());
+        }
+        r.prompts.assign(1, std::move(p));
+        s.pass.gens.clear();
+        ApiError err;
+        if (submit_all(r, &s.pass.gens, &err) < 0) {
+            retire(s.pass.gens);
+            t->heard = n;
+            if (final) {
+                failed(*t, err.message);
+                drop_front(t);
+            }
+            return;
+        }
+        s.pass.turn = t;
+        s.pass.final = final;
+        s.pass.heard = n;
+        s.pass.running = true;
+        t->heard = n;
+        ++t->passes;
+    };
+
+    auto finish_pass = [&]() {
+        Generation& g = s.pass.gens[0];
+        std::shared_ptr t = s.pass.turn;
+        const Finish fin = g.finish;
+        const std::string why = fin == Finish::Error ? engine_failure(*g.sink) : std::string();
+        t->n_prompt += (int64_t)s.pass.r.prompts[0].tokens.size();
+        t->n_gen += g.sink->n_produced();
+        std::vector ids = t->settled;
+        ids.insert(ids.end(), g.tokens.begin(), g.tokens.end());
+        /* The end of the turn, which the decoder renders as nothing, is no part of the reply. */
+        while (!ids.empty() && deps_.tok->reply_bytes(ids.back()).empty()) ids.pop_back();
+        record(s.pass.r, s.pass.gens, fin, /*quiet=*/true);
+        retire(s.pass.gens);
+        s.pass.running = false;
+        s.pass.turn.reset();
+        if (t->dropped) return;
+        const bool forced = !s.language.empty();
+        if (fin == Finish::Error) {
+            if (s.pass.final) {
+                failed(*t, why);
+                drop_front(t);
+            }
+            return;
+        }
+        if (s.pass.final) {
+            const std::string text = detok(ids, /*flush=*/true);
+            const size_t at = speech_transcript_start(f, text, forced, /*closed=*/true);
+            const std::string transcript = rtrim(text.substr(std::min(at, text.size())));
+            if (starts_with(transcript, t->sent)) delta(*t, transcript.substr(t->sent.size()));
+            ojson o = event("conversation.item.input_audio_transcription.completed");
+            o["item_id"] = t->id;
+            o["content_index"] = 0;
+            o["transcript"] = transcript;
+            o["usage"] = usage(*t);
+            send(o);
+            RAD_INFO("realtime %s %s: %.1fs of audio, %d passes, prompt=%lld gen=%lld, final "
+                     "%.2fs after the commit", s.id.c_str(), t->id.c_str(),
+                     (double)t->audio.size() / s.model_rate, t->passes, (long long)t->n_prompt,
+                     (long long)t->n_gen,
+                     std::chrono::duration(Clock::now() - t->committed_at).count());
+            drop_front(t);
+            return;
+        }
+        /* An interim pass: settle all but the last few tokens -- none in the turn's first second,
+         * none once the turn is where it may be cut (cut_zone), and none of a reply that ran to its
+         * bound, which is a model looping. */
+        if ((double)s.pass.heard >= kSettleAfterSeconds * s.model_rate && fin != Finish::Length &&
+            (max_clip <= 0 || (int64_t)s.pass.heard <= max_clip - cut_zone) &&
+            ids.size() > (size_t)s.unsettled)
+            t->settled.assign(ids.begin(),
+                              ids.begin() + (std::ptrdiff_t)std::max(t->settled.size(),
+                                                                     ids.size() - s.unsettled));
+        const std::string settled_text = detok(t->settled, /*flush=*/false);
+        const size_t a = speech_transcript_start(f, settled_text, forced, /*closed=*/false);
+        const std::string settled = a == std::string::npos ? std::string()
+                                                           : rtrim(settled_text.substr(a));
+        if (settled.size() > t->sent.size() && starts_with(settled, t->sent))
+            delta(*t, settled.substr(t->sent.size()));
+        const std::string all_text = detok(ids, /*flush=*/false);
+        const size_t b = speech_transcript_start(f, all_text, forced, /*closed=*/false);
+        const std::string all = b == std::string::npos ? std::string()
+                                                       : rtrim(all_text.substr(b));
+        const std::string tentative = starts_with(all, t->sent) ? all.substr(t->sent.size())
+                                                                : std::string();
+        if (tentative != t->tentative) {
+            ojson o = event("radiance.input_audio_transcription.tentative");
+            o["item_id"] = t->id;
+            o["content_index"] = 0;
+            o["text"] = tentative;
+            send(o);
+            t->tentative = tentative;
+        }
+    };
+
+    /* ---- the loop */
+    RAD_INFO("realtime %s open from %s", s.id.c_str(), s.peer.c_str());
+    {
+        ojson o = event("session.created");
+        o["session"] = session_json();
+        send(o);
+    }
+    for (;;) {
+        std::deque> got;
+        bool gone = false, overflow = false;
+        {
+            std::unique_lock lk(s.m);
+            bool final = false;
+            if (s.inbox.empty() && !s.peer_gone && !s.overflow && !s.pass.running &&
+                !next_work(&final))
+                s.cv.wait_for(lk, std::chrono::milliseconds(100));
+            got.swap(s.inbox);
+            s.inbox_bytes = 0;
+            gone = s.peer_gone;
+            overflow = s.overflow;
+        }
+        if (overflow) {
+            /* The reader stopped at the message that overflowed; what it queued before is
+             * dropped with the session. */
+            error("invalid_request_error", "buffer_overflow",
+                  fmt("the session fell more than %zu MiB of messages behind",
+                      kMaxQueuedBytes >> 20), "", nullptr);
+            ws.close(1008, "buffer overflow");
+            return true;
+        }
+        for (const auto& m : got) handle(m.first, m.second);
+        if (gone) return false;
+        {
+            double behind = 0.0;
+            for (const auto& t : s.turns) behind += (double)t->audio.size() / s.model_rate;
+            if (s.turns.size() > kMaxBehindTurns || behind > kMaxBehindSeconds) {
+                error("invalid_request_error", "buffer_overflow",
+                      fmt("the session is %zu committed turns (%.0f s of audio) behind its "
+                          "transcription; the most is %zu turns or %.0f s",
+                          s.turns.size(), behind, kMaxBehindTurns, kMaxBehindSeconds),
+                      "", nullptr);
+                ws.close(1008, "buffer overflow");
+                return true;
+            }
+        }
+        if (stopping_.load()) {
+            error("server_error", "shutting_down", "the server is shutting down", "", nullptr);
+            ws.close(1001, "closing");
+            return true;
+        }
+        if (s.pass.running) {
+            pump(s.pass.gens, s.pass.r);
+            if (all_done(s.pass.gens)) {
+                finish_pass();
+                continue;
+            }
+            bool idle;
+            {
+                std::lock_guard lk(s.m);
+                idle = s.inbox.empty() && !s.peer_gone;
+            }
+            if (idle) s.pass.gens[0].sink->wait(10);
+            continue;
+        }
+        sweep_abandoned();
+        bool final = false;
+        if (std::shared_ptr t = next_work(&final)) start_pass(t, final);
+    }
+}
+
+}  /* namespace server */
+}  /* namespace rad */
diff --git a/core/server/server.cpp b/core/server/server.cpp
index 1eb81500..bef9adee 100644
--- a/core/server/server.cpp
+++ b/core/server/server.cpp
@@ -1,4 +1,5 @@
 #include "server.h"
+#include "server_priv.h"
 
 #include 
 #include "json_partial.h"
@@ -16,46 +17,6 @@
 namespace rad {
 namespace server {
 
-/* ------------------------------------------------------------------ per-choice state */
-
-struct Server::Generation {
-    std::shared_ptr         sink;
-    std::unique_ptr detok;
-    std::unique_ptr delta;   /* chat streaming only, in the request's API shape */
-    uint64_t    id = 0;
-    int         index = 0;
-    int         prompt_index = 0;
-    std::string text;
-    std::vector logprobs;
-    size_t      lp_sent = 0;         /* streaming: how many of `logprobs` a chunk already carried */
-    /* The reply against its reasoning block, every token the sink delivers: what
-     * completion_tokens_details.reasoning_tokens reports. */
-    ReasoningCount think;
-    Finish      finish = Finish::None;
-    bool        closed = false;      /* the server has decided this choice is over */
-    size_t      scanned = 0;         /* how far the stop-string scan has reached */
-    /* OaiRequest::stops_after: where in `text` the reasoning block's closer ends (npos until it
-     * has been generated) and how far the search for it has reached. */
-    size_t      stops_floor = std::string::npos;
-    size_t      closer_scanned = 0;
-    size_t      stop_cut = std::string::npos;
-    std::string stop_word;           /* the stop string at stop_cut, "" when the decoder cut it */
-    size_t      emitted = 0;         /* streaming: text already handed to the delta stream */
-    std::vector tokens;     /* llama-server's native shape: the ids generated */
-    size_t      tokens_sent = 0;     /* ...and how many of them a stream chunk carried */
-    int32_t     progress_sent = -1;  /* streaming: the prompt_progress last sent, -1 for none */
-    bool        retired = false;     /* reap() has been said for this id, at most once */
-};
-
-struct Server::StreamState {
-    OaiRequest              r;
-    std::vector gens;
-    std::function   peer_closed;
-    bool opened = false;
-    bool done_sent = false;
-    bool released = false;
-};
-
 /* ------------------------------------------------------------------ construction */
 
 Server::Server(const Deps& d, const ServerOptions& o)
@@ -94,15 +55,11 @@ Server::Server(const Deps& d, const ServerOptions& o)
 
 Server::~Server() { stop(); }
 
-/* Sinks the engine may still be writing into must not be freed. `Request::sink` is a raw pointer
- * the scheduler holds for the life of the request, so the only safe moment to release one is
- * after the scheduler has reported it terminal. At shutdown we wait a bounded time for that and,
- * if it never comes, we leak the remainder on purpose and say so.
- *
- * A deliberate leak of a few KiB at process exit is the cheap failure. Freeing under a running
- * step is the expensive one: it corrupts whatever the allocator hands out next, and it surfaces
- * as garbage in an unrelated request several steps later, which is precisely the class of bug
- * spec §17 exists to keep out of this engine. */
+/* A sink may be freed only after the scheduler reports its request terminal, since
+ * `Request::sink` is a raw pointer the scheduler holds for the request's life. At shutdown this
+ * waits a bounded time, then deliberately leaks the remainder (a few KiB at exit) rather than
+ * free memory a running step may write into, which would corrupt an unrelated allocation
+ * (spec §17). */
 void Server::drain_graveyard(int timeout_ms) {
     const int slice = 5;
     for (int waited = 0; waited <= timeout_ms; waited += slice) {
@@ -126,13 +83,11 @@ void Server::drain_graveyard(int timeout_ms) {
     grave_.clear();
 }
 
-/* WHAT IS SERVED. One table, and /server_info answers with it rather than with a copy -- a list
- * kept beside this one is a list that goes stale on the next route added.
+/* Every route, in one table that /server_info also reports.
  *
- * Method spellings follow vLLM's, including the ones that look wrong: /tokenize and /detokenize
- * are POST because their input is a body, /reset_prefix_cache is POST because it changes state,
- * and /ping answers both GET and POST because different load balancers send different ones and
- * neither is worth a 405 on a health probe. */
+ * Methods follow vLLM's: /tokenize and /detokenize are POST (their input is a body),
+ * /reset_prefix_cache is POST (it changes state), and /ping takes GET and POST because load
+ * balancers differ. */
 void Server::register_routes() {
     router_.post("/v1/chat/completions", [this](const HttpRequest& q) { return handle_chat(q); });
     router_.post("/v1/completions",      [this](const HttpRequest& q) { return handle_completion(q); });
@@ -140,37 +95,61 @@ void Server::register_routes() {
     router_.post("/v1/images/generations", [this](const HttpRequest& q) { return handle_images(q, false); });
     router_.post("/v1/images/edits",     [this](const HttpRequest& q) { return handle_images(q, true); });
     router_.post("/v1/systemone",        [this](const HttpRequest& q) { return handle_systemone(q); });
+    /* Speech to text, for a model whose plugin says how it transcribes (RadAudioFormat). */
+    router_.post("/v1/audio/transcriptions",
+                 [this](const HttpRequest& q) { return handle_transcription(q); });
+    /* The same, live over a WebSocket (OpenAI's realtime transcription session). A plain GET
+     * there is told what the path wants. */
+    router_.socket("/v1/realtime", [this](const HttpRequest& q, WsConn& c) { handle_realtime(q, c); });
+    router_.get ("/v1/realtime", [this](const HttpRequest& q) {
+        ApiError e;
+        e.status = 426;
+        e.type = "invalid_request_error";
+        e.message = "/v1/realtime is a WebSocket: connect with an Upgrade: websocket request";
+        HttpResponse r = error_response(e, q.peer);
+        r.set_header("Upgrade", "websocket");
+        return r;
+    });
     router_.get ("/v1/models",           [this](const HttpRequest& q) { return handle_models(q); });
-    router_.get ("/v1/models/:id",       [this](const HttpRequest& q) { return handle_models(q); });
-    /* THE SAME ROUTES WITHOUT /v1, as llama-server answers them: a client configured with the
-     * bare host as its base URL appends the path alone. */
+    router_.get ("/v1/models/*id",       [this](const HttpRequest& q) { return handle_models(q); });
+    /* The same routes without /v1, as llama-server answers them, for clients whose base URL is
+     * the bare host. */
     router_.post("/chat/completions",    [this](const HttpRequest& q) { return handle_chat(q); });
-    /* llama-server's native completion, under both of its names: /completions without /v1 is
-     * the native endpoint there, not OpenAI's. */
+    /* llama-server's native completion under both its names; /completions without /v1 is the
+     * native endpoint there, not OpenAI's. */
     router_.post("/completion",          [this](const HttpRequest& q) { return handle_native_completion(q); });
     router_.post("/completions",         [this](const HttpRequest& q) { return handle_native_completion(q); });
     router_.post("/infill",              [this](const HttpRequest& q) { return handle_infill(q); });
     router_.post("/embeddings",          [this](const HttpRequest& q) { return handle_embeddings(q); });
     router_.post("/images/generations",  [this](const HttpRequest& q) { return handle_images(q, false); });
     router_.post("/images/edits",        [this](const HttpRequest& q) { return handle_images(q, true); });
+    router_.post("/audio/transcriptions", [this](const HttpRequest& q) { return handle_transcription(q); });
     router_.get ("/models",              [this](const HttpRequest& q) { return handle_models(q); });
     /* llama-server's: the prompt a chat request renders to, and how many tokens it is. */
     router_.post("/apply-template",      [this](const HttpRequest& q) { return handle_apply_template(q); });
-    router_.post("/v1/chat/completions/input_tokens",
-                 [this](const HttpRequest& q) { return handle_input_tokens(q); });
-    router_.post("/chat/completions/input_tokens",
-                 [this](const HttpRequest& q) { return handle_input_tokens(q); });
+    auto chat_tokens = [this](const HttpRequest& q) {
+        return count_tokens(q, nullptr, ApiShape::OpenAI, "response.input_tokens");
+    };
+    router_.post("/v1/chat/completions/input_tokens", chat_tokens);
+    router_.post("/chat/completions/input_tokens", chat_tokens);
     /* Anthropic's Messages API, translated onto the chat path (anthropic_to_chat). */
     router_.post("/v1/messages",         [this](const HttpRequest& q) { return handle_messages(q); });
-    router_.post("/v1/messages/count_tokens",
-                 [this](const HttpRequest& q) { return handle_count_tokens(q); });
+    router_.post("/v1/messages/count_tokens", [this](const HttpRequest& q) {
+        return count_tokens(q,
+                            [](const std::string& b, const OaiLimits& l, std::string* c,
+                               std::string* lb, ApiError* e) {
+                                return anthropic_to_chat(b, l, c, lb, e);
+                            },
+                            ApiShape::Anthropic, nullptr);
+    });
     /* OpenAI's Responses API, translated the same way (responses_to_chat). */
     router_.post("/v1/responses",        [this](const HttpRequest& q) { return handle_responses(q); });
     router_.post("/responses",           [this](const HttpRequest& q) { return handle_responses(q); });
-    router_.post("/v1/responses/input_tokens",
-                 [this](const HttpRequest& q) { return handle_responses_tokens(q); });
-    router_.post("/responses/input_tokens",
-                 [this](const HttpRequest& q) { return handle_responses_tokens(q); });
+    auto responses_tokens = [this](const HttpRequest& q) {
+        return count_tokens(q, responses_to_chat, ApiShape::OpenAI, "response.input_tokens");
+    };
+    router_.post("/v1/responses/input_tokens", responses_tokens);
+    router_.post("/responses/input_tokens", responses_tokens);
 
     router_.get ("/metrics",             [this](const HttpRequest& q) { return handle_metrics(q); });
     router_.get ("/health",              [this](const HttpRequest& q) { return handle_health(q); });
@@ -189,9 +168,7 @@ void Server::register_routes() {
 
     router_.post("/reset_prefix_cache",  [this](const HttpRequest& q) { return handle_reset_prefix_cache(q); });
 
-    /* The dashboard. `/` rather than only `/dashboard` because a person who has the host and port
-     * of a running engine types exactly that, and answering it with a 404 is answering the
-     * question "is this thing alive" with "no". */
+    /* The dashboard, also at `/`, since that is what a person with the host and port types. */
     router_.get ("/",                    [this](const HttpRequest& q) { return handle_dashboard(q); });
     router_.get ("/dashboard",           [this](const HttpRequest& q) { return handle_dashboard(q); });
     router_.get ("/stats",               [this](const HttpRequest& q) { return handle_stats(q); });
@@ -199,16 +176,11 @@ void Server::register_routes() {
     router_.get ("/sessions",            [this](const HttpRequest& q) { return handle_sessions(q); });
 }
 
-/* WORKERS FOR EVERYTHING ADMISSION CAN LET IN, AND A RESERVE BESIDE THEM.
- *
- * A generation holds its connection's worker for as long as it runs -- a stream writes from it, a
- * blocking request waits on its sink in it -- so a pool no larger than the admission ceiling runs
- * out of workers before admission refuses anyone. The 429 can then never happen, and every
- * connection after that waits in the pool's queue behind generations that may run for minutes,
- * /health included. So the pool may grow to the ceiling plus a reserve no admitted generation can
- * occupy: that is what keeps a probe, the dashboard, a request about to be told 429 and a
- * client's idle keep-alive connections answerable while every admitted request is running. The
- * same number bounds the connections that may wait once even the reserve is busy. */
+/* Workers beyond the admission ceiling. A generation holds its connection's worker for its whole
+ * run, so a pool capped at the ceiling would run out before admission refuses anyone: no 429, and
+ * every later connection (/health included) queued behind minutes-long generations. The reserve
+ * keeps probes, the dashboard, 429 answers and idle keep-alive connections serviceable. The same
+ * number bounds the connections that may wait once the reserve is busy too. */
 static const int64_t kSpareWorkers = 64;
 
 int Server::run() {
@@ -266,8 +238,8 @@ std::vector Server::probe_reasoning_efforts() {
         ApiError e;
         return parse_chat_request(body, odeps_, l, &r, &e) >= 0;
     };
-    /* A render that fails with no effort at all says nothing about efforts, and one that takes a
-     * word no ladder has takes every word. */
+    /* A render that fails without an effort says nothing about efforts; one that takes a
+     * nonsense word takes every word. */
     if (!takes("") || takes("radiance-probe-not-a-level")) return {};
     std::vector set;
     for (const char* w : { "low", "medium", "high", "xhigh", "max" })
@@ -312,14 +284,26 @@ void Server::stop() {
 
 /* ------------------------------------------------------------------ admission */
 
-bool Server::admit(int64_t n) {
+std::optional Server::admit(int64_t n, const std::string& peer, ApiShape shape,
+                                          const char* field) {
+    sweep_abandoned();
+    if (n > queue_depth_)
+        return error_response(err_bad(field, "this request needs " + std::to_string(n) +
+                                                 " admission places, and this server admits at "
+                                                 "most " + std::to_string(queue_depth_) +
+                                                 " requests at once (--max-queued-requests); "
+                                                 "split it"),
+                              peer, shape);
     int64_t cur = in_flight_.fetch_add(n, std::memory_order_acq_rel) + n;
     if (cur > queue_depth_) {
         in_flight_.fetch_sub(n, std::memory_order_acq_rel);
-        return false;
+        metrics_.observe_rejected();
+        return error_response(err_overloaded("the admission queue is full; retry after " +
+                                             std::to_string(opt_.retry_after_s) + "s"),
+                              peer, shape);
     }
     metrics_.set_queue_depth(cur);
-    return true;
+    return std::nullopt;
 }
 
 void Server::release(int64_t n) {
@@ -345,17 +329,15 @@ void Server::sweep_abandoned() {
 
 /* ------------------------------------------------------------------ errors */
 
-/* " from " for the request log, or nothing in-process, where no transport names a
- * peer. */
+/* " from " for the request log, or "" in-process. */
 static std::string from_peer(const std::string& peer) {
     return peer.empty() ? std::string() : " from " + peer;
 }
 
 HttpResponse Server::error_response(const ApiError& e, const std::string& peer, ApiShape shape) {
     metrics_.observe_http(e.status);
-    /* A refusal is the line the operator is looking for when a client says "rejected": the
-     * status, the type, the message, and who asked. 4xx is the client's doing and said at info;
-     * 5xx is ours and said as a warning. */
+    /* Log every refusal with status, type, message and peer: 4xx at info (the client's doing),
+     * 5xx as a warning (ours). */
     if (e.status >= 500)
         RAD_WARN("req refused%s -> %d %s: %s", from_peer(peer).c_str(), e.status, e.type.c_str(),
                  e.message.c_str());
@@ -394,12 +376,9 @@ int Server::submit_all(const OaiRequest& r, std::vector* gens, ApiEr
     const int n_choices = r.n_choices();
     gens->reserve((size_t)n_choices);
 
-    /* THE SAMPLER GETS A SAY BEFORE ANYTHING IS QUEUED. A stage that did not resolve is not a
-     * declare failure -- it becomes one when a request asks for it. Refusing here makes that a
-     * 400 naming the parameter, instead of an admitted request that the step loop cancels three
-     * steps in with a dead stream at the client.
-     *
-     * Once, not per choice: `n` varies only the seed, and no check here reads it. */
+    /* The sampler vets the parameters before anything is queued (IScheduler::admit), so an
+     * unresolved stage is a 400 naming the parameter rather than a mid-stream cancellation.
+     * Once, not per choice: `n` varies only the seed, which no check reads. */
     {
         std::string why;
         if (deps_.sched->admit(r.sp, &why) < 0) {
@@ -431,12 +410,12 @@ int Server::submit_all(const OaiRequest& r, std::vector* gens, ApiEr
             Request rq;
             rq.prompt = r.prompts[p].tokens;
             rq.sp = r.sp;
-            /* n identical seeds would give n identical completions, which is not what `n` means.
-             * Offsetting is enough: the sampler's stream is seeded, not chained. */
+            /* Distinct seeds per choice, or `n` identical completions. An offset suffices: the
+             * sampler's stream is seeded, not chained. */
             rq.sp.seed = r.sp.seed + (uint64_t)k;
             rq.max_tokens = r.max_tokens;
-            /* With the stop strings deferred past the reasoning block, the scheduler -- which
-             * cannot tell reasoning from answer -- gets none; the decoder and pump() cut. */
+            /* With stop strings deferred past the reasoning block, the scheduler (which cannot
+             * tell reasoning from answer) gets none; the decoder and pump() cut instead. */
             rq.stop = r.stops_after.empty() ? r.stop : std::vector{};
             rq.ignore_eos = r.ignore_eos;
             rq.priority = r.priority;
@@ -455,9 +434,38 @@ int Server::submit_all(const OaiRequest& r, std::vector* gens, ApiEr
         g.id = ids[i];
         g.sink->id = g.id;
     }
+    /* Refused because the prompt is longer than the KV cache can ever hold (RAD_E_FULL at
+     * submission): the client's error, answered now as a context overflow, with the choices
+     * the scheduler did take cancelled. */
+    for (size_t i = 0; i < ids.size(); ++i) {
+        const Generation& g = (*gens)[first + i];
+        if (ids[i] != 0 || g.sink->status() != RAD_E_FULL) continue;
+        const std::string why = g.sink->why() ? g.sink->why() : "the prompt is too long";
+        cancel_all(*gens, false);
+        *err = err_bad("prompt", why);
+        err->message = why;
+        err->code = "context_length_exceeded";
+        err->n_prompt_tokens = (int64_t)r.prompts[(size_t)g.prompt_index].tokens.size();
+        return RAD_E_FULL;
+    }
     return RAD_OK;
 }
 
+std::optional Server::abandoned(const HttpRequest& req,
+                                              std::vector& gens, int64_t n,
+                                              ApiShape shape, const OaiRequest* r) {
+    const bool gone = req.peer_gone();
+    if (!gone && !stopping_.load()) return std::nullopt;
+    cancel_all(gens, gone);
+    if (r) record(*r, gens, Finish::Cancelled);
+    retire(gens);
+    release(n);
+    if (!gone)
+        return error_response(err_overloaded("the server is shutting down"), req.peer, shape);
+    metrics_.observe_http(499);
+    return HttpResponse::text(499, "client closed request\n");
+}
+
 void Server::cancel_all(std::vector& gens, bool count_disconnect) {
     for (auto& g : gens) {
         if (g.sink->done()) continue;
@@ -467,15 +475,17 @@ void Server::cancel_all(std::vector& gens, bool count_disconnect) {
     if (count_disconnect) metrics_.observe_disconnect();
 }
 
-/* Every exit from a request goes through here exactly once. A generation the engine has finished
- * is reaped -- that is the server telling the scheduler it may drop the Request, which it cannot
- * know on its own because we are the ones holding the sink. One the engine has not finished moves
- * to the graveyard, and is reaped by the sweep when it does. */
+/* Every exit from a request goes through here exactly once. A finished generation is reaped
+ * (the scheduler may drop the Request; only the server knows the sink is released). An
+ * unfinished one moves to the graveyard and is reaped by the sweep once it finishes. Id 0 is a
+ * request the scheduler refused or never received: it holds nothing, so there is nothing to
+ * reap and nothing to wait for. */
 void Server::retire(std::vector& gens) {
     std::vector> pending;
     for (auto& g : gens) {
         if (g.retired) continue;
         g.retired = true;
+        if (!g.id) continue;
         if (g.sink->done()) deps_.sched->reap(g.id);
         else pending.push_back(g.sink);
     }
@@ -497,9 +507,8 @@ static void lp_text(const ITokenizer& tok, int32_t id, std::string* text, std::s
     *text = bytes->substr(0, utf8_valid_prefix(*bytes));
 }
 
-/* How many of the entries from `from` went out with the reply: under a stop string, every one
- * whose text BEGAN before the cut -- one that straddles it contributed text the client got, and
- * the stop string's own tokens did not -- and otherwise all of them. */
+/* How many entries from `from` went out with the reply: with a stop cut, every entry whose text
+ * began before the cut (a straddling token contributed text the client got); otherwise all. */
 static size_t lp_before_cut(const std::vector& lp, size_t from, size_t cut) {
     if (cut == std::string::npos) return lp.size() - from;
     size_t start = from ? lp[from - 1].end : 0, n = 0;
@@ -524,12 +533,19 @@ bool Server::pump(std::vector& gens, const OaiRequest& r) {
     for (auto& g : gens) {
         if (g.closed) continue;
 
+        /* Read before the drain: the producer pushes its last tokens and then finishes, so once
+         * the finish is seen every token is in the sink and the drain below takes them all. Read
+         * after it, a finish landing between the last read and the check would close the choice
+         * with those tokens unread, and the reply would lose its end. */
+        const bool finished = g.sink->done();
+
         size_t n;
         while ((n = g.sink->read(buf, 128, r.want_logprobs ? alts.data() : nullptr)) > 0) {
             progress = true;
             for (size_t i = 0; i < n; ++i) {
                 g.think.push(r.sp.reasoning, buf[i].token);
-                if (r.shape == ApiShape::LlamaNative) g.tokens.push_back(buf[i].token);
+                if (r.shape == ApiShape::LlamaNative || r.return_tokens)
+                    g.tokens.push_back(buf[i].token);
                 std::string piece = g.detok->push(buf[i].token);
                 if (!piece.empty()) g.text += piece;
                 if (!r.want_logprobs) continue;
@@ -550,8 +566,8 @@ bool Server::pump(std::vector& gens, const OaiRequest& r) {
             }
         }
 
-        /* The decoder may have swallowed the stop string itself, in which case our own scan below
-         * can never find it -- it is searching text the stop string was already removed from. */
+        /* The decoder may have swallowed the stop string itself; the scan below cannot find it
+         * in text it was already removed from. */
         if (maxstop && !g.closed && g.stop_cut == std::string::npos && g.detok->stopped()) {
             g.stop_cut = g.text.size();
             g.stop_word = g.detok->stop_hit();
@@ -563,13 +579,13 @@ bool Server::pump(std::vector& gens, const OaiRequest& r) {
             continue;
         }
 
-        /* Stop strings. The scheduler is given Request::stop and may stop first, but a stop
-         * string straddles token boundaries and only the detokenised text can be searched, so the
-         * authoritative cut is made here. Scanning restarts (maxstop-1) bytes behind the previous
-         * end so a match spanning two drains is still found. */
-        /* Stop strings deferred past the reasoning block match only after its closer. The closer
-         * is searched for incrementally, from (closer length - 1) bytes behind the previous end,
-         * so a reply that thinks for a long time is not rescanned from its start every drain. */
+        /* Stop strings. The scheduler gets Request::stop and may stop first, but a stop string
+         * can straddle tokens, so the authoritative cut is made here on the detokenised text.
+         * Scanning restarts (maxstop - 1) bytes behind the previous end so a match spanning two
+         * drains is found.
+         *
+         * Stop strings deferred past the reasoning block match only after its closer, which is
+         * searched incrementally from (closer length - 1) bytes behind the previous end. */
         size_t floor = 0;
         if (!r.stops_after.empty()) {
             if (g.stops_floor == std::string::npos) {
@@ -599,15 +615,14 @@ bool Server::pump(std::vector& gens, const OaiRequest& r) {
                 g.finish = Finish::StopString;
                 g.closed = true;
                 progress = true;
-                /* The client will never see another token of this choice, so the blocks it holds
-                 * are dead weight the moment we decide that (spec §14). */
+                /* No further token reaches the client, so free its blocks now (spec §14). */
                 g.sink->request_cancel();
                 deps_.sched->cancel(g.id);
                 continue;
             }
         }
 
-        if (g.sink->done()) {
+        if (finished) {
             std::string tail = g.detok->flush();
             if (!tail.empty()) { g.text += tail; progress = true; }
             g.finish = g.sink->finish_reason();
@@ -621,10 +636,9 @@ bool Server::pump(std::vector& gens, const OaiRequest& r) {
 
 /* ------------------------------------------------------------------ usage */
 
-/* THE REQUEST'S TOKENS, ONCE FOR BOTH PATHS. `n` choices share a prompt, so the prompt and its
- * cached part are counted once per prompt. Reasoning is reported only where the reply's block can
- * be counted by token (ReasoningSpan); a model without one reports no breakdown rather than a
- * zero that would claim there was no reasoning. */
+/* The request's token usage, shared by both paths. `n` choices share a prompt, so prompt and
+ * cached tokens count once per prompt. Reasoning is reported only when the block can be counted
+ * by token (ReasoningSpan); otherwise no breakdown rather than a misleading zero. */
 UsageOut Server::usage_of(const OaiRequest& r, const std::vector& gens) {
     UsageOut u;
     for (const auto& p : r.prompts) u.prompt += (int64_t)p.tokens.size();
@@ -637,10 +651,9 @@ UsageOut Server::usage_of(const OaiRequest& r, const std::vector& ge
     return u;
 }
 
-/* WHERE THE REQUEST'S TIME WENT, from its sinks: one for a choice's final chunk, all of them for
- * the request. Every time is moved onto one clock first -- each sink counts from its own
- * construction, and `received_ns` (the body's arrival, -1 when unknown) is on that clock already.
- * See TimingsOut for what each field means. */
+/* Where the request's time went, from its sinks (one for a choice's final chunk, all for the
+ * request). Each sink counts from its own construction, so times are moved onto the steady clock
+ * first; `received_ns` (body arrival, -1 when unknown) is already on it. Fields: TimingsOut. */
 TimingsOut Server::timings_of(const Sink* const* sinks, size_t n, int64_t received_ns) {
     TimingsOut t;
     int64_t admit = INT64_MAX, first_lo = INT64_MAX, first_hi = INT64_MIN, last = INT64_MIN;
@@ -683,14 +696,19 @@ TimingsOut Server::timings_of(const std::vector& gens, int64_t recei
 
 /* ------------------------------------------------------------------ metrics bookkeeping */
 
-/* WHAT FAILED, for the client: the sentence the failing component gave, and the status. A failed
- * request always carries a status -- an engine that stopped carries the one that stopped it -- so
- * this never reads "ok". */
-static std::string engine_failure(const Sink& s) {
-    const int st = s.status() < 0 ? s.status() : RAD_E_STATE;
-    const char* why = s.why();
-    return why ? fmt("the engine failed this request: %s (%s)", why, rad_strerror(st))
-               : fmt("the engine failed this request: %s", rad_strerror(st));
+/* A request's outcome over its choices, for record() and /metrics: an error over a cancellation
+ * over a cut at max_tokens over a tool call over a plain stop. */
+static Finish outcome(Finish overall, Finish f) {
+    auto rank = [](Finish x) {
+        switch (x) {
+            case Finish::Error:     return 4;
+            case Finish::Cancelled: return 3;
+            case Finish::Length:    return 2;
+            case Finish::ToolCalls: return 1;
+            default:                return 0;
+        }
+    };
+    return rank(f) > rank(overall) ? f : overall;
 }
 
 static SuccessReason to_reason(Finish f) {
@@ -703,7 +721,8 @@ static SuccessReason to_reason(Finish f) {
     }
 }
 
-void Server::record(const OaiRequest& r, const std::vector& gens, Finish overall) {
+void Server::record(const OaiRequest& r, const std::vector& gens, Finish overall,
+                    bool quiet) {
     int64_t n_prompt = 0;
     for (const auto& p : r.prompts) n_prompt += (int64_t)p.tokens.size();
 
@@ -728,9 +747,8 @@ void Server::record(const OaiRequest& r, const std::vector& gens, Fi
     metrics_.observe_request(n_prompt, n_gen, ttft, tpot, e2e, decode,
                              r.n, r.max_tokens, to_reason(overall));
 
-    /* THE OTHER HALF OF THE REQUEST LOG. The same figures /metrics aggregates, for this one
-     * request: how it ended, what the prefix cache spared, the reasoning share when the parser
-     * knows it, time to first token, the decode rate after it, and the whole. */
+    /* The request log's closing line: this request's share of what /metrics aggregates (finish,
+     * cached prompt, reasoning tokens when known, TTFT, decode rate, total time). */
     const TimingsOut t = timings_of(gens, r.t_received_ns);
     const UsageOut u = usage_of(r, gens);
     const double rate = (decode > 0.0 && n_gen > 1) ? (double)(n_gen - 1) / decode : -1.0;
@@ -740,10 +758,11 @@ void Server::record(const OaiRequest& r, const std::vector& gens, Fi
     if (ttft >= 0) std::snprintf(ttft_s, sizeof ttft_s, "ttft=%.2fs", ttft);
     char rate_s[32] = "";
     if (rate > 0) std::snprintf(rate_s, sizeof rate_s, " %.1f tok/s", rate);
-    RAD_INFO("req %s done%s finish=%s prompt=%lld (cache %lld) gen=%lld%s %s%s %.2fs",
-             r.id.c_str(), from_peer(r.peer).c_str(), finish_reason_oai(overall),
-             (long long)n_prompt, (long long)(t.valid ? t.cache_n : 0), (long long)n_gen, reason,
-             ttft_s, rate_s, e2e);
+    RAD_LOG_AT(quiet ? Log::Debug : Log::Info,
+               "req %s done%s finish=%s prompt=%lld (cache %lld) gen=%lld%s %s%s %.2fs",
+               r.id.c_str(), from_peer(r.peer).c_str(), finish_reason_oai(overall),
+               (long long)n_prompt, (long long)(t.valid ? t.cache_n : 0), (long long)n_gen,
+               reason, ttft_s, rate_s, e2e);
 }
 
 /* ------------------------------------------------------------------ non-streaming */
@@ -762,22 +781,8 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r)
         pump(gens, r);
         if (all_done(gens)) break;
 
-        /* A client that hangs up before the answer is ready is a cancellation, not something to
-         * finish computing for nobody. */
-        if (req.peer_gone()) {
-            cancel_all(gens, true);
-            retire(gens);
-            release(r.n_choices());
-            metrics_.observe_http(499);
-            HttpResponse res = HttpResponse::text(499, "client closed request\n");
-            return res;
-        }
-        if (stopping_.load()) {
-            cancel_all(gens, false);
-            retire(gens);
-            release(r.n_choices());
-            return error_response(err_overloaded("the server is shutting down"), req.peer, r.shape);
-        }
+        /* A client that hangs up before the answer is ready cancels the request. */
+        if (auto no = abandoned(req, gens, r.n_choices(), r.shape, &r)) return *no;
         /* Wait on whichever choice is still running. Bounded, so the peer check above runs. */
         for (auto& g : gens) if (!g.closed) { g.sink->wait(); break; }
     }
@@ -796,28 +801,24 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r)
         if (r.want_logprobs) c.logprobs = kept_logprobs(g.logprobs, g.stop_cut);
 
         if (r.endpoint == Endpoint::Chat) {
-            /* Parse whenever there is a parser, not only when tools were sent: the same parser
-             * separates the reasoning block from the answer, and a request with no tools still
-             * wants `reasoning_content` split out rather than glued to the front of the reply.
-             * It is the same reader the streaming path feeds a piece at a time, fed the whole
-             * reply at once, so the two agree by construction. With no tools in the request the
-             * parser reads no calls and the tool bookkeeping below finds none. */
+            /* Parse whenever there is a parser, not only with tools: it also splits
+             * `reasoning_content` from the answer. It is the reader the streaming path feeds
+             * piecewise, fed the whole reply, so both paths agree. Without tools it reads no
+             * calls. */
             if (r.reply_parser) {
                 std::unique_ptr rd = r.reply_parser->open();
                 rd->feed(g.text, nullptr);
                 rd->finish(nullptr);
                 c.msg = rd->message();
-                /* Only claim a tool call when every call closed and its arguments parse
-                 * (json_partial.h) -- the streaming path's rule (calls_complete). */
+                /* Claim a tool call only when every call closed and its arguments parse
+                 * (json_partial.h), the streaming path's rule (calls_complete). */
                 const bool complete = r.parse_tools && calls_complete(c.msg);
                 if (complete && (c.finish == Finish::Stop || c.finish == Finish::StopString))
                     c.finish = Finish::ToolCalls;
                 if (c.msg.open_call) {
-                    /* A half-finished call is content, not a call: the client gets what the model
-                     * wrote instead of a tool invocation with truncated arguments. Only that call
-                     * -- the reply ended inside it, so it is the last -- and only its own text:
-                     * the reasoning stays reasoning, and the calls before it, which closed, stay
-                     * calls, as the stream announced them. The finish reason is the stream's. */
+                    /* A half-finished call (necessarily the last) becomes content, so no tool is
+                     * invoked with truncated arguments. Reasoning and earlier closed calls are
+                     * kept, as the stream announced them; the finish reason is the stream's. */
                     c.msg.content = rd->content_with_open_call(g.text);
                     c.msg.tool_calls.pop_back();
                     c.msg.open_call = false;
@@ -829,11 +830,7 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r)
         } else {
             c.text = r.echo ? r.prompts[g.prompt_index].text + g.text : g.text;
         }
-        /* The request's outcome for record() and /metrics: a failure or a cancellation over
-         * anything, else a tool call over a plain stop -- the same promotion the streaming path
-         * makes, so a blocking tool call is not counted as "stop". */
-        if (c.finish == Finish::Error || c.finish == Finish::Cancelled) overall = c.finish;
-        else if (c.finish == Finish::ToolCalls && overall == Finish::Stop) overall = c.finish;
+        overall = outcome(overall, c.finish);
         choices.push_back(std::move(c));
     }
 
@@ -844,11 +841,7 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r)
             retire(gens);
             release(r.n_choices());
             record(r, gens, Finish::Error);
-            ApiError e;
-            e.status = 500;
-            e.type = "internal_server_error";
-            e.message = why;
-            return error_response(e, req.peer, r.shape);
+            return error_response(err_internal(why), req.peer, r.shape);
         }
     }
 
@@ -923,9 +916,8 @@ static const char* native_stop_type(Finish f) {
     }
 }
 
-/* llama-server's final result for one choice: the text, how it ended, the prompt it ran on and
- * where the time went. A stream's last chunk is this with `content` empty -- the text went out
- * in the chunks before it. */
+/* llama-server's final result for one choice: text, finish, prompt and timings. A stream's last
+ * chunk is this with `content` empty, the text having gone out in earlier chunks. */
 json Server::native_result(const OaiRequest& r, const Generation& g, const std::string& content) {
     const Sink* one = g.sink.get();
     const TimingsOut t = timings_of(&one, 1, r.t_received_ns);
@@ -947,8 +939,8 @@ json Server::native_result(const OaiRequest& r, const Generation& g, const std::
     o["stopping_word"] = g.stop_word;
     o["tokens_cached"] = n_prompt + g.sink->n_produced();
     if (t.valid) o["timings"] = timings_json(t);
-    /* The whole reply's probabilities on the answer, as llama-server sends them: a stream
-     * carried them chunk by chunk instead. */
+    /* The whole reply's probabilities, as llama-server sends them; a stream sent them per
+     * chunk instead. */
     if (r.want_logprobs && !r.stream) {
         const std::vector kept = kept_logprobs(g.logprobs, g.stop_cut);
         o["completion_probabilities"] =
@@ -979,24 +971,27 @@ static std::string text_chunk(const OaiRequest& r, int index, const std::string&
     return sse_event(o.dump());
 }
 
-/* llama-server's `prompt_progress` chunk: the endpoint's opening chunk -- an assistant role with
- * no content, or an empty text -- carrying how much of the prompt is in the cache, of how much,
- * how much of that the prefix cache supplied, and the time since the prompt phase began. */
+/* llama-server's `prompt_progress` chunk: the endpoint's opening chunk (an assistant role with no
+ * content, or empty text) carrying prompt tokens processed, the total, how many the prefix cache
+ * supplied, and the time since the prompt phase began. */
 static std::string progress_chunk(const OaiRequest& r, int index, const Sink& s) {
-    nlohmann::ordered_json ch;
+    const int64_t ta = s.t_admitted_ns();
+    nlohmann::ordered_json pp;
+    pp["total"]     = s.progress_total();
+    pp["cache"]     = s.progress_cached();
+    pp["processed"] = s.progress_processed();
+    pp["time_ms"]   = ta >= 0 ? (s.age_ns() - ta) / 1000000 : 0;
     if (r.shape == ApiShape::LlamaNative) {
         /* llama-server's native chunk carries the progress at its top level. */
-        const int64_t ta = s.t_admitted_ns();
         nlohmann::ordered_json o;
         o["index"] = index;
         o["content"] = "";
         o["tokens"] = nlohmann::ordered_json::array();
         o["stop"] = false;
-        o["prompt_progress"] = { { "total", s.progress_total() }, { "cache", s.progress_cached() },
-                                 { "processed", s.progress_processed() },
-                                 { "time_ms", ta >= 0 ? (s.age_ns() - ta) / 1000000 : 0 } };
+        o["prompt_progress"] = std::move(pp);
         return sse_event(o.dump());
     }
+    nlohmann::ordered_json ch;
     if (r.endpoint == Endpoint::Chat) {
         ch["index"] = index;
         ch["delta"] = { { "role", "assistant" }, { "content", nullptr } };
@@ -1006,12 +1001,6 @@ static std::string progress_chunk(const OaiRequest& r, int index, const Sink& s)
         ch["logprobs"] = nullptr;
     }
     ch["finish_reason"] = nullptr;
-    const int64_t ta = s.t_admitted_ns();
-    nlohmann::ordered_json pp;
-    pp["total"]     = s.progress_total();
-    pp["cache"]     = s.progress_cached();
-    pp["processed"] = s.progress_processed();
-    pp["time_ms"]   = ta >= 0 ? (s.age_ns() - ta) / 1000000 : 0;
     nlohmann::ordered_json o;
     o["id"] = r.id;
     o["object"] = r.endpoint == Endpoint::Chat ? "chat.completion.chunk" : "text_completion";
@@ -1049,8 +1038,7 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
     res.content_type = "text/event-stream; charset=utf-8";
     res.set_header("Cache-Control", "no-cache");
     res.set_header("Connection", "keep-alive");
-    /* nginx buffers proxied responses by default, which turns a token stream into one large
-     * delivery at the end. This header is the documented opt-out and costs nothing elsewhere. */
+    /* nginx buffers proxied responses by default; this header is its documented opt-out. */
     res.set_header("X-Accel-Buffering", "no");
 
     Server* self = this;
@@ -1064,14 +1052,9 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
             if (st->r.endpoint == Endpoint::Chat) {
                 for (auto& g : st->gens) out += g.delta->first_chunk();
             } else if (st->r.echo) {
-                /* `echo`, ON THE STREAMING PATH. The buffered path applies it by prepending the
-                 * prompt to the choice's text; this is the equivalent, and without it the same
-                 * request would answer differently depending on `stream`.
-                 *
-                 * The prompt goes out as the first content chunk, before any token, which is what
-                 * "echo" means and what a client reassembling the deltas needs: concatenating the
-                 * stream gives the same string the buffered response returns.
-                 * Empty prompts emit nothing rather than an empty chunk. */
+                /* `echo` on the streaming path: the prompt goes out as the first content chunk,
+                 * so the concatenated stream equals the buffered response. Empty prompts emit
+                 * nothing. */
                 for (auto& g : st->gens) {
                     const std::string& p = st->r.prompts[(size_t)g.prompt_index].text;
                     if (!p.empty()) out += text_chunk(st->r, g.index, p, nullptr);
@@ -1089,8 +1072,8 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
         for (const auto& s : st->r.stop) maxstop = std::max(maxstop, s.size());
 
         for (auto& g : st->gens) {
-            /* The prompt's progress first, so a client sees it before the first token: every
-             * advance the scheduler reported, as llama-server sends one a prefill batch. */
+            /* Prompt progress first, before the first token: one chunk per reported advance, as
+             * llama-server sends one per prefill batch. */
             if (st->r.return_progress) {
                 const int32_t done = g.sink->progress_processed();
                 if (done > g.progress_sent) {
@@ -1098,14 +1081,13 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
                     g.progress_sent = done;
                 }
             }
-            /* Hold back the longest stop string minus one byte while the choice is still running:
-             * otherwise the first half of a stop sequence is already on the wire by the time we
-             * recognise it, and it cannot be taken back.
+            if (g.delta && g.sink->n_produced() > 0) out += g.delta->started();
+            /* While the choice runs, hold back the longest stop string minus one byte, or the
+             * start of a stop sequence would already be on the wire when it is recognised.
              *
-             * ONLY WHILE IT IS RUNNING. Every hold-back rule here waits for bytes that may still
-             * arrive, and a closed choice has none coming, so its whole text is the answer. That
-             * includes a tail the escape rule would keep -- a trailing `\` or a partial `\uXXXX`
-             * is ordinary text in a completion, and holding it back at the end drops it. */
+             * Only while running: a closed choice has no more bytes coming, so its whole text is
+             * the answer, including a trailing `\` or partial `\uXXXX` the escape rule would
+             * otherwise hold back. */
             size_t safe = g.text.size();
             if (!g.closed) {
                 if (maxstop > 1) safe = safe > maxstop - 1 ? safe - (maxstop - 1) : 0;
@@ -1113,9 +1095,9 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
                 if (safe <= g.emitted) continue;
             }
 
-            /* THE LOGPROBS OF THE TOKENS WHOSE TEXT THIS CHUNK CARRIES: every entry ending inside
-             * it while the choice runs, and once it is closed the rest of what went out with the
-             * reply (lp_before_cut). */
+            /* Logprobs for the tokens whose text this chunk carries: entries ending inside it
+             * while the choice runs; once closed, the rest that went out with the reply
+             * (lp_before_cut). */
             size_t lp_n = 0, lp_off = 0;
             if (st->r.want_logprobs) {
                 lp_off = g.lp_sent ? g.logprobs[g.lp_sent - 1].end : 0;
@@ -1136,8 +1118,7 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
                 if (g.delta) g.delta->set_timings(now);
             }
             if (st->r.endpoint == Endpoint::Chat) {
-                /* Only what is new: the reader keeps its own place in the reply, which is what
-                 * makes a long reply cost its length rather than its length squared. */
+                /* Only the new text: the reader keeps its place, so a reply costs linear time. */
                 if (lp_n) g.delta->add_logprobs(logprobs_content(lp_at, lp_n));
                 out += g.delta->push(std::string_view(g.text).substr(g.emitted, safe - g.emitted),
                                      g.closed);
@@ -1167,9 +1148,8 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
                                   lp_n ? logprobs_legacy(lp_at, lp_n, lp_off) : std::string());
             }
             g.emitted = safe;
-            /* A sent entry is read again only as the one before the next, for where that one
-             * starts; keeping the rest would hold ~1.7 KB a token at 20 alternatives for the
-             * whole of a long stream. */
+            /* Of the sent entries only the last is read again (for where the next one starts);
+             * keeping all would hold ~1.7 KB per token at 20 alternatives for a long stream. */
             if (g.lp_sent > 1) {
                 g.logprobs.erase(g.logprobs.begin(), g.logprobs.begin() + (long)(g.lp_sent - 1));
                 g.lp_sent = 1;
@@ -1180,18 +1160,15 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
             const UsageOut u = usage_of(st->r, st->gens);
             Finish overall = Finish::Stop;
             for (auto& g : st->gens) {
-                /* EACH CHOICE'S OWN TIMINGS ON ITS FINAL CHUNK, so a client that asked for no
-                 * usage chunk still has them, as llama.cpp sends them. */
+                /* Each choice's own timings on its final chunk, as llama.cpp sends them, so they
+                 * arrive even without a usage chunk. */
                 const Sink* one = g.sink.get();
                 const TimingsOut gt = timings_of(&one, 1, st->r.t_received_ns);
-                /* A failed generation cannot become a non-200 -- the headers left long ago -- so
-                 * it travels as an error event in the stream. Silence would look like a normal
-                 * end of stream and the client would use a truncated answer. */
+                /* The 200 headers are already sent, so a failed generation becomes an error event
+                 * in the stream; a silent end would pass a truncated answer as complete. */
                 ApiError e;
                 if (g.finish == Finish::Error) {
-                    e.status = 500;
-                    e.type = "internal_server_error";
-                    e.message = engine_failure(*g.sink);
+                    e = err_internal(engine_failure(*g.sink));
                     overall = Finish::Error;
                 }
                 if (st->r.endpoint == Endpoint::Chat) {
@@ -1201,27 +1178,21 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
                         out += g.delta->error_chunk(e, gt, u);
                     } else {
                         out += g.delta->final_chunk(g.finish, gt, u);
-                        const Finish adj = g.delta->adjusted_finish(g.finish);
-                        if (overall != Finish::Error &&
-                            (adj == Finish::Cancelled || adj == Finish::ToolCalls))
-                            overall = adj;
+                        overall = outcome(overall, g.delta->adjusted_finish(g.finish));
                     }
                 } else if (st->r.shape == ApiShape::LlamaNative) {
                     out += sse_event(json_dump(self->native_result(st->r, g, "")));
                     if (g.finish == Finish::Error) out += sse_error(e);
+                    overall = outcome(overall, g.finish);
                 } else {
                     out += text_chunk(st->r, g.index, "", finish_reason_oai(g.finish), >);
                     if (g.finish == Finish::Error) out += sse_error(e);
+                    overall = outcome(overall, g.finish);
                 }
             }
-            /* THE USAGE CHUNK. `stream_options.include_usage` is parsed and validated on both
-             * endpoints, so both have to honour it -- accepting a field and then ignoring it is
-             * the outcome oai.h's header forbids.
-             *
-             * After the per-generation final chunks and before [DONE], which is where OpenAI puts
-             * it, and once for the request rather than once per choice: `n` completions share one
-             * prompt and one total, so emitting it per generation would count the prompt n times
-             * and interleave usage between the choices' final chunks. */
+            /* The usage chunk (`stream_options.include_usage`, honoured on both endpoints).
+             * After the final chunks and before [DONE], where OpenAI puts it, and once per
+             * request: the `n` choices share one prompt and one total. */
             if (st->r.include_usage) {
                 const TimingsOut t = timings_of(st->gens, st->r.t_received_ns);
                 out += st->r.endpoint == Endpoint::Chat ? chat_usage_chunk(st->r, u, t)
@@ -1240,8 +1211,8 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
         }
 
         if (!progress && out.empty()) {
-            /* Nothing to send: sleep on the first live sink rather than spinning. The bounded
-             * wait is what makes the peer-closed check above run a few times a second. */
+            /* Nothing to send: sleep on the first live sink. The wait is bounded so the
+             * peer-closed check above runs a few times a second. */
             for (auto& g : st->gens) if (!g.closed) { g.sink->wait(); break; }
         }
         return true;
@@ -1249,8 +1220,7 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
 
     res.on_close = [self, st](bool ok) {
         if (!st->done_sent) {
-            /* Either the peer went away or the write failed. Both are cancellations, and the
-             * blocks have to go back now rather than when the generation would have ended. */
+            /* The peer went away or the write failed: cancel now so the blocks are freed. */
             self->cancel_all(st->gens, true);
             self->record(st->r, st->gens, Finish::Cancelled);
             self->retire(st->gens);
@@ -1265,39 +1235,31 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
 
 /* ------------------------------------------------------------------ endpoints */
 
-HttpResponse Server::handle_chat(const HttpRequest& req) {
-    if (!deps_.sched || !deps_.tok)
-        return error_response(err_not_implemented("the server has no engine attached"), req.peer);
-    if (opt_.embedding_model)
-        return error_response(err_not_implemented("this is an embedding model: it serves "
-                                                  "/v1/embeddings and generates no text"),
-                              req.peer);
-    if (opt_.image_model)
-        return error_response(err_not_implemented("this is an image model: it serves "
-                                                  "/v1/images/generations and /v1/images/edits "
-                                                  "and generates no text"),
-                              req.peer);
+/* The 501 for a text-generation endpoint this deployment cannot serve, or nothing. */
+std::optional Server::refuse_text(const std::string& peer, ApiShape shape) {
+    const char* why =
+        !deps_.sched || !deps_.tok ? "the server has no engine attached"
+        : opt_.embedding_model     ? "this is an embedding model: it serves /v1/embeddings and "
+                                     "generates no text"
+        : opt_.image_model         ? "this is an image model: it serves /v1/images/generations "
+                                     "and /v1/images/edits and generates no text"
+                                   : nullptr;
+    if (!why) return std::nullopt;
+    return error_response(err_not_implemented(why), peer, shape);
+}
 
+HttpResponse Server::handle_chat(const HttpRequest& req) {
+    if (auto no = refuse_text(req.peer)) return *no;
     OaiRequest r;
     ApiError err;
     if (parse_chat_request(req.body, odeps_, lim_, &r, &err) < 0)
         return error_response(err, req.peer);
-    r.peer = req.peer;
-
-    sweep_abandoned();
-    if (!admit(r.n_choices())) {
-        metrics_.observe_rejected();
-        return error_response(err_overloaded(
-            "the admission queue is full; retry after " + std::to_string(opt_.retry_after_s) +
-            "s. The server refuses rather than queueing without bound"), req.peer);
-    }
-    log_admitted(r);
-    return r.stream ? streaming_completion(req, r) : blocking_completion(req, r);
+    return serve(req, r);
 }
 
-/* llama-server's /apply-template and its token count. Both parse the request exactly as
- * /v1/chat/completions does -- the same template defaults, the same refusals -- and stop before
- * anything is queued, so the prompt they report is the prompt a chat request would run. */
+/* llama-server's /apply-template and its token count. Both parse exactly as /v1/chat/completions
+ * does (same defaults, same refusals) and stop before queueing, so they report the prompt a chat
+ * request would run. */
 HttpResponse Server::handle_apply_template(const HttpRequest& req) {
     if (!deps_.tok || !deps_.chat)
         return error_response(err_not_implemented("rendering a chat requires a chat template; "
@@ -1312,87 +1274,69 @@ HttpResponse Server::handle_apply_template(const HttpRequest& req) {
     return HttpResponse::json_body(200, json_dump(o));
 }
 
-HttpResponse Server::handle_input_tokens(const HttpRequest& req) {
+/* The token count of the prompt a request would run, parsed as a chat request and not queued.
+ * `to_chat` translates another API's body first (null for a chat body); `object` is the
+ * response's `object` field, or null for none. */
+HttpResponse Server::count_tokens(const HttpRequest& req, ToChat to_chat, ApiShape shape,
+                                  const char* object) {
     if (!deps_.tok || !deps_.chat)
         return error_response(err_not_implemented("rendering a chat requires a chat template; "
-                                                  "this model was loaded without one"), req.peer);
-    OaiRequest r;
+                                                  "this model was loaded without one"),
+                              req.peer, shape);
+    std::string chat;
     ApiError err;
-    if (parse_chat_request(req.body, odeps_, lim_, &r, &err) < 0)
-        return error_response(err, req.peer);
+    OaiRequest r;
+    if ((to_chat && to_chat(req.body, lim_, &chat, nullptr, &err) < 0) ||
+        parse_chat_request(to_chat ? chat : req.body, odeps_, lim_, &r, &err) < 0)
+        return error_response(err, req.peer, shape);
     json o;
-    o["object"] = "response.input_tokens";
+    if (object) o["object"] = object;
     o["input_tokens"] = r.prompts.empty() ? 0 : (int64_t)r.prompts[0].tokens.size();
     metrics_.observe_http(200);
     return HttpResponse::json_body(200, json_dump(o));
 }
 
-/* ANTHROPIC'S MESSAGES API. The request is translated into the chat request it means and parsed by
- * the chat endpoint's own parser, so every default, refusal and template rule is that endpoint's;
- * the answer and the errors go out in Anthropic's shapes. */
+/* Anthropic's Messages API: translated into the equivalent chat request and parsed by the chat
+ * parser, so every default, refusal and template rule is the chat endpoint's; answers and errors
+ * go out in Anthropic's shapes. */
 HttpResponse Server::handle_messages(const HttpRequest& req) {
-    if (!deps_.sched || !deps_.tok)
-        return error_response(err_not_implemented("the server has no engine attached"), req.peer,
-                              ApiShape::Anthropic);
-    if (opt_.embedding_model)
-        return error_response(err_not_implemented("this is an embedding model: it serves "
-                                                  "/v1/embeddings and generates no text"),
-                              req.peer, ApiShape::Anthropic);
-    if (opt_.image_model)
-        return error_response(err_not_implemented("this is an image model: it serves "
-                                                  "/v1/images/generations and /v1/images/edits "
-                                                  "and generates no text"),
-                              req.peer, ApiShape::Anthropic);
+    if (auto no = refuse_text(req.peer, ApiShape::Anthropic)) return *no;
     std::string chat, label;
+    bool cm = false;
     ApiError err;
     OaiRequest r;
-    if (anthropic_to_chat(req.body, lim_, &chat, &label, &err) < 0 ||
+    if (anthropic_to_chat(req.body, lim_, &chat, &label, &err, &cm) < 0 ||
         parse_chat_request(chat, odeps_, lim_, &r, &err) < 0)
         return error_response(err, req.peer, ApiShape::Anthropic);
     r.shape = ApiShape::Anthropic;
+    r.context_management = cm;
     r.id = random_id("msg_");
     if (r.session_label.empty()) r.session_label = label;
-    return serve_translated(req, r);
+    return serve(req, r);
 }
 
-HttpResponse Server::serve_translated(const HttpRequest& req, OaiRequest& r) {
+HttpResponse Server::serve(const HttpRequest& req, OaiRequest& r) {
     r.peer = req.peer;
-    sweep_abandoned();
-    if (!admit(r.n_choices())) {
-        metrics_.observe_rejected();
-        return error_response(err_overloaded(
-            "the admission queue is full; retry after " + std::to_string(opt_.retry_after_s) +
-            "s. The server refuses rather than queueing without bound"), req.peer, r.shape);
-    }
+    if (auto no = admit(r.n_choices(), req.peer, r.shape, r.prompts.size() > 1 ? "prompt" : "n"))
+        return *no;
     log_admitted(r);
     return r.stream ? streaming_completion(req, r) : blocking_completion(req, r);
 }
 
-/* llama-server's NATIVE /completion: the completions parser with llama-server's prompt forms,
+/* llama-server's native /completion: the completions parser with llama-server's prompt forms,
  * answered in its shape (native_result). */
 HttpResponse Server::handle_native_completion(const HttpRequest& req) {
-    if (!deps_.sched || !deps_.tok)
-        return error_response(err_not_implemented("the server has no engine attached"), req.peer);
-    if (opt_.embedding_model)
-        return error_response(err_not_implemented("this is an embedding model: it serves "
-                                                  "/v1/embeddings and generates no text"),
-                              req.peer);
-    if (opt_.image_model)
-        return error_response(err_not_implemented("this is an image model: it serves "
-                                                  "/v1/images/generations and /v1/images/edits "
-                                                  "and generates no text"),
-                              req.peer);
+    if (auto no = refuse_text(req.peer)) return *no;
     OaiRequest r;
     ApiError err;
     if (parse_completion_request(req.body, odeps_, lim_, &r, &err, /*native=*/true) < 0)
         return error_response(err, req.peer);
     r.shape = ApiShape::LlamaNative;
-    return serve_translated(req, r);
+    return serve(req, r);
 }
 
-/* A control token by the spellings model families give it, or -1: what llama.cpp's vocabulary
- * loader recognises the fill-in-the-middle tokens by. A spelling counts only when it is ONE token
- * that renders as itself. */
+/* The first of `names` (the spellings llama.cpp's vocabulary loader recognises for a FIM token)
+ * that is one token rendering as itself, or -1. */
 static int32_t special_token(const ITokenizer& tok, std::initializer_list names) {
     for (const char* n : names) {
         const std::vector t = tok.encode(n, false, /*parse_special=*/true);
@@ -1401,17 +1345,16 @@ static int32_t special_token(const ITokenizer& tok, std::initializer_list", "", "",
                                              "<|fim▁begin|>", "
", "▁
", "<|code_prefix|>" });
@@ -1498,8 +1441,8 @@ HttpResponse Server::handle_infill(const HttpRequest& req) {
         extra.insert(extra.end(), t.begin(), t.end());
     }
 
-    /* THE EXTRA FILES GIVE WAY FIRST, newest kept, when the whole does not fit beside what the
-     * reply may generate: they are context, and the prefix and suffix are the edit. */
+    /* When everything does not fit beside the reply's budget, the extra files are trimmed first
+     * (newest kept): they are context, while prefix and suffix are the edit. */
     int64_t reserve = 256;
     for (const char* k : { "max_tokens", "n_predict" }) {
         auto it = b.find(k);
@@ -1532,23 +1475,13 @@ HttpResponse Server::handle_infill(const HttpRequest& req) {
     if (parse_completion_request(b.dump(), odeps_, lim_, &r, &err, /*native=*/true) < 0)
         return error_response(err, req.peer);
     r.shape = ApiShape::LlamaNative;
-    return serve_translated(req, r);
+    return serve(req, r);
 }
 
-/* OPENAI'S RESPONSES API, as the Messages API: translated into the chat request it means, served
- * by the chat path, answered as a response object or its event stream. */
+/* OpenAI's Responses API, like the Messages API: translated into the equivalent chat request,
+ * served by the chat path, answered as a response object or its event stream. */
 HttpResponse Server::handle_responses(const HttpRequest& req) {
-    if (!deps_.sched || !deps_.tok)
-        return error_response(err_not_implemented("the server has no engine attached"), req.peer);
-    if (opt_.embedding_model)
-        return error_response(err_not_implemented("this is an embedding model: it serves "
-                                                  "/v1/embeddings and generates no text"),
-                              req.peer);
-    if (opt_.image_model)
-        return error_response(err_not_implemented("this is an image model: it serves "
-                                                  "/v1/images/generations and /v1/images/edits "
-                                                  "and generates no text"),
-                              req.peer);
+    if (auto no = refuse_text(req.peer)) return *no;
     std::string chat, echo;
     ApiError err;
     OaiRequest r;
@@ -1558,71 +1491,16 @@ HttpResponse Server::handle_responses(const HttpRequest& req) {
     r.shape = ApiShape::Responses;
     r.id = random_id("resp_");
     r.echo_json = std::move(echo);
-    return serve_translated(req, r);
-}
-
-HttpResponse Server::handle_responses_tokens(const HttpRequest& req) {
-    if (!deps_.tok || !deps_.chat)
-        return error_response(err_not_implemented("rendering a chat requires a chat template; "
-                                                  "this model was loaded without one"), req.peer);
-    std::string chat;
-    ApiError err;
-    OaiRequest r;
-    if (responses_to_chat(req.body, lim_, &chat, nullptr, &err) < 0 ||
-        parse_chat_request(chat, odeps_, lim_, &r, &err) < 0)
-        return error_response(err, req.peer);
-    json o;
-    o["object"] = "response.input_tokens";
-    o["input_tokens"] = r.prompts.empty() ? 0 : (int64_t)r.prompts[0].tokens.size();
-    metrics_.observe_http(200);
-    return HttpResponse::json_body(200, json_dump(o));
-}
-
-HttpResponse Server::handle_count_tokens(const HttpRequest& req) {
-    if (!deps_.tok || !deps_.chat)
-        return error_response(err_not_implemented("rendering a chat requires a chat template; "
-                                                  "this model was loaded without one"), req.peer,
-                              ApiShape::Anthropic);
-    std::string chat;
-    ApiError err;
-    OaiRequest r;
-    if (anthropic_to_chat(req.body, lim_, &chat, nullptr, &err) < 0 ||
-        parse_chat_request(chat, odeps_, lim_, &r, &err) < 0)
-        return error_response(err, req.peer, ApiShape::Anthropic);
-    json o;
-    o["input_tokens"] = r.prompts.empty() ? 0 : (int64_t)r.prompts[0].tokens.size();
-    metrics_.observe_http(200);
-    return HttpResponse::json_body(200, json_dump(o));
+    return serve(req, r);
 }
 
 HttpResponse Server::handle_completion(const HttpRequest& req) {
-    if (!deps_.sched || !deps_.tok)
-        return error_response(err_not_implemented("the server has no engine attached"), req.peer);
-    if (opt_.embedding_model)
-        return error_response(err_not_implemented("this is an embedding model: it serves "
-                                                  "/v1/embeddings and generates no text"),
-                              req.peer);
-    if (opt_.image_model)
-        return error_response(err_not_implemented("this is an image model: it serves "
-                                                  "/v1/images/generations and /v1/images/edits "
-                                                  "and generates no text"),
-                              req.peer);
-
+    if (auto no = refuse_text(req.peer)) return *no;
     OaiRequest r;
     ApiError err;
     if (parse_completion_request(req.body, odeps_, lim_, &r, &err) < 0)
         return error_response(err, req.peer);
-    r.peer = req.peer;
-
-    sweep_abandoned();
-    if (!admit(r.n_choices())) {
-        metrics_.observe_rejected();
-        return error_response(err_overloaded(
-            "the admission queue is full; retry after " + std::to_string(opt_.retry_after_s) +
-            "s. The server refuses rather than queueing without bound"), req.peer);
-    }
-    log_admitted(r);
-    return r.stream ? streaming_completion(req, r) : blocking_completion(req, r);
+    return serve(req, r);
 }
 
 HttpResponse Server::handle_embeddings(const HttpRequest& req) {
@@ -1645,8 +1523,8 @@ HttpResponse Server::handle_embeddings(const HttpRequest& req) {
     if (r.dimensions > dim)
         return error_response(err_bad("dimensions", "this model's vectors are " +
                                                         std::to_string(dim) + " wide"), req.peer);
-    /* AN INPUT IS NEVER SPLIT (Request::embed), so one longer than a step is refused here, with
-     * the number, rather than by the scheduler with none. */
+    /* An input is never split (Request::embed), so one longer than a step is refused here, with
+     * the limit in the message. */
     for (size_t i = 0; i < r.prompts.size(); ++i) {
         const int64_t n = (int64_t)r.prompts[i].tokens.size();
         if (n > deps_.embed->max_input()) {
@@ -1660,17 +1538,11 @@ HttpResponse Server::handle_embeddings(const HttpRequest& req) {
         }
     }
 
-    sweep_abandoned();
     const int n_in = (int)r.prompts.size();
-    if (!admit(n_in)) {
-        metrics_.observe_rejected();
-        return error_response(err_overloaded(
-            "the admission queue is full; retry after " + std::to_string(opt_.retry_after_s) +
-            "s. The server refuses rather than queueing without bound"), req.peer);
-    }
+    if (auto no = admit(n_in, req.peer, ApiShape::OpenAI, "input")) return *no;
     log_admitted(r);
 
-    /* EVERY INPUT AT ONCE, so the scheduler can put them in one step. */
+    /* Submit every input at once so the scheduler can batch them in one step. */
     std::vector gens;
     std::vector rqs;
     gens.reserve((size_t)n_in);
@@ -1696,13 +1568,11 @@ HttpResponse Server::handle_embeddings(const HttpRequest& req) {
         gens[i].id = ids[i];
         gens[i].sink->id = ids[i];
         if (!ids[i]) {
+            cancel_all(gens, false);
             retire(gens);
             release(n_in);
-            ApiError e;
-            e.status = 500;
-            e.type = "internal_server_error";
-            e.message = "the scheduler refused input " + std::to_string(i);
-            return error_response(e, req.peer);
+            return error_response(err_internal("the scheduler refused input " + std::to_string(i)),
+                                  req.peer);
         }
     }
 
@@ -1713,25 +1583,13 @@ HttpResponse Server::handle_embeddings(const HttpRequest& req) {
             all = all && g.closed;
         }
         if (all) break;
-        if (req.peer_gone()) {
-            cancel_all(gens, true);
-            retire(gens);
-            release(n_in);
-            metrics_.observe_http(499);
-            return HttpResponse::text(499, "client closed request\n");
-        }
-        if (stopping_.load()) {
-            cancel_all(gens, false);
-            retire(gens);
-            release(n_in);
-            return error_response(err_overloaded("the server is shutting down"), req.peer);
-        }
+        if (auto no = abandoned(req, gens, n_in)) return *no;
         for (auto& g : gens) if (!g.closed) { g.sink->wait(); break; }
     }
 
-    /* THE VECTORS, truncated to `dimensions` and L2-normalised: what OpenAI's endpoint returns and
-     * what a sentence-transformers model's Normalize module does. Truncating a unit vector does
-     * not keep it unit, so the normalisation comes after. */
+    /* Vectors truncated to `dimensions`, then L2-normalised (as OpenAI's endpoint and
+     * sentence-transformers' Normalize module return them); truncation breaks unit length, so
+     * normalisation comes after. */
     std::vector> vecs;
     vecs.reserve((size_t)n_in);
     UsageOut u;
@@ -1744,11 +1602,7 @@ HttpResponse Server::handle_embeddings(const HttpRequest& req) {
                                           std::to_string(g.index);
             retire(gens);
             release(n_in);
-            ApiError e;
-            e.status = 500;
-            e.type = "internal_server_error";
-            e.message = why;
-            return error_response(e, req.peer);
+            return error_response(err_internal(why), req.peer);
         }
         std::vector out(v.begin(), v.begin() + keep);
         double ss = 0.0;
@@ -1764,14 +1618,14 @@ HttpResponse Server::handle_embeddings(const HttpRequest& req) {
     return HttpResponse::json_body(200, embeddings_body(r, vecs, u));
 }
 
-/* /v1/systemone (systemone.h): one request a question, each reading its answer's candidates at
- * the prompt's last position (Request::token_scores) and sampling one token nobody reads.
+/* /v1/systemone (systemone.h): one engine request per question, each reading its answer
+ * candidates at the prompt's last position (Request::token_scores) and sampling one discarded
+ * token.
  *
- * SEVERAL QUESTIONS SHARE THE STATE THEY ARE ASKED OVER, and it is read once. The first question
- * runs alone and leaves the state at the end of that shared head in the prefix cache -- its
- * attention blocks, and a checkpoint of the convolutions there (Request::checkpoint_at) -- and the
- * rest are submitted together once it has finished, each starting from that head and computing
- * only its own tail. d1's own runner shares the head the same way, as one batched tree. */
+ * Questions share the state they are asked over, and it is read once: the first question runs
+ * alone and leaves the shared head in the prefix cache (attention blocks plus a convolution
+ * checkpoint, Request::checkpoint_at); the rest are then submitted together and compute only their
+ * own tails. d1's runner shares the head the same way, as one batched tree. */
 HttpResponse Server::handle_systemone(const HttpRequest& req) {
     if (!deps_.sched || !deps_.tok)
         return error_response(err_not_implemented("the server has no engine attached"), req.peer);
@@ -1785,14 +1639,8 @@ HttpResponse Server::handle_systemone(const HttpRequest& req) {
     if (parse_decision_request(req.body, odeps_, lim_, opt_.model_id, &r, &err) < 0)
         return error_response(err, req.peer);
 
-    sweep_abandoned();
     const int n = (int)r.questions.size();
-    if (!admit(n)) {
-        metrics_.observe_rejected();
-        return error_response(err_overloaded(
-            "the admission queue is full; retry after " + std::to_string(opt_.retry_after_s) +
-            "s. The server refuses rather than queueing without bound"), req.peer);
-    }
+    if (auto no = admit(n, req.peer, ApiShape::OpenAI, "questions")) return *no;
     RAD_INFO("systemone admitted%s questions=%d prompt=%lld tok", from_peer(req.peer).c_str(), n,
              (long long)r.input_tokens);
 
@@ -1817,22 +1665,18 @@ HttpResponse Server::handle_systemone(const HttpRequest& req) {
         gens.push_back(std::move(g));
         scores.push_back(std::move(ts));
     }
-    /* The questions handed to the scheduler so far: an early exit retires those and drops the
-     * rest, whose sinks nothing will ever finish. */
+    /* Questions handed to the scheduler so far. An early exit retires those and drops the rest,
+     * whose sinks would never finish. */
     size_t submitted = 0;
     auto fail = [&](const std::string& why) {
         gens.resize(submitted);
         retire(gens);
         release(n);
-        ApiError e;
-        e.status = 500;
-        e.type = "internal_server_error";
-        e.message = why;
-        return error_response(e, req.peer);
+        return error_response(err_internal(why), req.peer);
     };
 
-    /* Questions [first, last) submitted together and waited for. A non-null response is the
-     * call's answer already: the scheduler refused one, the client left, or the server stops. */
+    /* Submits questions [first, last) together and waits for them. Sets `early` to the call's
+     * response when the scheduler refuses one, the client leaves or the server stops. */
     std::unique_ptr early;
     auto run = [&](int first, int last) {
         std::vector part(std::make_move_iterator(rqs.begin() + first),
@@ -1858,23 +1702,10 @@ HttpResponse Server::handle_systemone(const HttpRequest& req) {
                 all = all && g.closed;
             }
             if (all) return;
-            if (req.peer_gone()) {
+            /* Both conditions only ever turn true, so abandoned() answers once either holds. */
+            if (req.peer_gone() || stopping_.load()) {
                 gens.resize(submitted);
-                cancel_all(gens, true);
-                retire(gens);
-                release(n);
-                metrics_.observe_http(499);
-                early = std::make_unique(
-                    HttpResponse::text(499, "client closed request\n"));
-                return;
-            }
-            if (stopping_.load()) {
-                gens.resize(submitted);
-                cancel_all(gens, false);
-                retire(gens);
-                release(n);
-                early = std::make_unique(
-                    error_response(err_overloaded("the server is shutting down"), req.peer));
+                early = std::make_unique(*abandoned(req, gens, n));
                 return;
             }
             for (int i = first; i < last; ++i)
@@ -1941,8 +1772,8 @@ HttpResponse Server::handle_metrics(const HttpRequest&) {
     metrics_.set_queue_depth(in_flight_.load(std::memory_order_relaxed));
     HttpResponse r;
     r.status = 200;
-    /* The exposition format version is part of the content type; Prometheus uses it to decide how
-     * to parse, and omitting it makes some scrapers fall back to OpenMetrics and fail. */
+    /* The exposition format version belongs in the content type: Prometheus parses by it, and
+     * without it some scrapers fall back to OpenMetrics and fail. */
     r.content_type = "text/plain; version=0.0.4; charset=utf-8";
     r.body = metrics_.render();
     return r;
diff --git a/core/server/server.h b/core/server/server.h
index cd33d41d..bec348d9 100644
--- a/core/server/server.h
+++ b/core/server/server.h
@@ -1,19 +1,16 @@
 /* core/server/server.h -- the OpenAI-compatible server (spec §14).
  *
- * Threading, in the spec's terms (§1): HTTP threads feed a request queue, one scheduler thread
- * produces one step. This object owns the HTTP thread pool and the admission queue; it does not
- * own the step loop and never calls into it. Output comes back per request through a Sink the
- * scheduler pushes into (sink.h), which `Request::sink` points at.
+ * Threading (spec §1): HTTP threads feed a request queue and one scheduler thread runs the steps.
+ * This object owns the HTTP thread pool and the admission queue, never the step loop. Output
+ * returns per request through a Sink (sink.h) that `Request::sink` points at.
  *
- * Backpressure is admission control, not buffering. A full queue is a 429 with Retry-After. The
- * alternative -- accepting everything and letting the waiting list grow -- turns a load spike
- * into an out-of-memory kill twenty minutes later, at which point every in-flight request dies
- * rather than the marginal ones being refused up front.
+ * Backpressure is admission control, not buffering: a full queue answers 429 with Retry-After.
+ * Accepting everything would turn a load spike into a later out-of-memory kill of every in-flight
+ * request instead of refusing the marginal ones.
  *
- * Cancellation is not an edge case. An agent client that abandons a long generation is the normal
- * case, so a dropped connection is detected on the streaming path (a failed write, or a closed
- * socket seen while waiting) and turned into IScheduler::cancel, which frees the request's KV
- * blocks immediately rather than at completion.
+ * Cancellation is the normal case for agent clients. A dropped connection, seen on the streaming
+ * path as a failed write or a closed socket, becomes IScheduler::cancel, which frees the request's
+ * KV blocks immediately.
  */
 #pragma once
 #include 
@@ -27,6 +24,7 @@
 #include 
 #include 
 #include 
+#include 
 #include 
 #include 
 
@@ -41,41 +39,36 @@ struct Deps {
     IEmbedder*        embed   = nullptr;   /* absent -> /v1/embeddings is 501 */
     IMultimodal*      mm      = nullptr;   /* absent -> image and audio parts are 501 */
     IImageGen*        images  = nullptr;   /* absent -> the images endpoints are 501 */
+    const SpeechFormat* speech = nullptr;  /* absent -> /v1/audio/transcriptions is 501 */
 
-    /* WHAT ONLY THE ENGINE CAN SEE: per-card VRAM, the expert plane. The server holds interfaces
-     * and no device handle, so this dependency is a function rather than an object -- there is
-     * nothing to name it after. Absent, the dashboard shows the scheduler's half and omits the
-     * cards rather than drawing zeroes.
-     *
-     * The SAME function the live view is built with (liveview.h), so the terminal view and the
-     * web page cannot drift into disagreeing about what the engine is doing. */
+    /* Engine-side state the server cannot see (per-card VRAM, the expert plane), as a snapshot
+     * function since the server holds no device handle. The same function feeds the live view
+     * (liveview.h), so the terminal and the web page agree. Absent, the dashboard shows only the
+     * scheduler's metrics and omits the cards. */
     LiveView::Source  live;
 };
 
 struct ServerOptions {
     std::string model_id = "radiance";
-    /* AN EMBEDDING MODEL (rad_declare_pooled) GENERATES NOTHING: /v1/chat/completions and
-     * /v1/completions answer 501 naming /v1/embeddings, rather than queueing a request the engine
-     * would finish after one step with no text. */
+    /* An embedding model (rad_declare_pooled) generates nothing: /v1/chat/completions and
+     * /v1/completions answer 501 naming /v1/embeddings. */
     bool        embedding_model = false;
-    /* AN IMAGE GENERATOR (rad_declare_generator) GENERATES NO TEXT either: the text endpoints
-     * answer 501 naming /v1/images/generations and /v1/images/edits. */
+    /* An image generator (rad_declare_generator) generates no text: the text endpoints answer
+     * 501 naming /v1/images/generations and /v1/images/edits. */
     bool        image_model = false;
-    /* WHICH DECISION PROTOCOL THE MODEL WAS TRAINED ON, from the container's `decision.type`:
-     * "d1" serves /v1/systemone (systemone.h); empty answers it 501. Never inferred from a name. */
+    /* The decision protocol from the container's `decision.type`: "d1" serves /v1/systemone
+     * (systemone.h); empty answers it 501. Never inferred from a name. */
     std::string decision_type;
-    /* What --model named, reported as the model entry's `root` the way vLLM reports the path it
-     * loaded: a served name chosen for clients says nothing about which file is behind it. Empty
-     * leaves the field out. */
+    /* What --model named, reported as the model entry's `root` as vLLM reports its loaded path
+     * (the served name says nothing about the file behind it). Empty omits the field. */
     std::string model_path;
     std::string host = "0.0.0.0";
     int         port = 8000;
     int         n_threads = 0;
 
-    /* How many requests may be admitted and unfinished at once. Beyond this the answer is 429.
-     * Defaults to 8x max_seqs: enough that the scheduler always has a full batch to choose from
-     * and a queue to prefill out of, and small enough that the memory held by waiting requests is
-     * bounded by a number the operator picked. */
+    /* Requests that may be admitted and unfinished at once; beyond it, 429. Defaults to 8 x
+     * max_seqs: enough for a full batch plus a prefill queue, while bounding the memory waiting
+     * requests hold. */
     int64_t     queue_depth = 0;
     int64_t     max_seqs = 256;
     int         retry_after_s = 1;
@@ -88,14 +81,14 @@ struct ServerOptions {
     int64_t     max_stop_bytes = 4096;
 
     bool        supports_logprobs = false;
-    /* The deployment default for `reasoning_effort`, empty for the template's own. See
-     * OaiLimits::default_reasoning_effort for why a server-side default is needed at all. */
+    /* Deployment default for `reasoning_effort`; empty for the template's own. See
+     * OaiLimits::default_reasoning_effort. */
     std::string default_reasoning_effort;
-    /* The deployment default for `thinking_token_budget`, -1 for none. See
+    /* Deployment default for `thinking_token_budget`, -1 for none. See
      * OaiLimits::default_thinking_budget. */
     int64_t     default_thinking_budget = -1;
-    /* What a request that sends no sampler fields is served with. See
-     * OaiLimits::default_sampling; only the sampler knobs are read from it. */
+    /* Sampling for a request that sends no sampler fields; only the sampler knobs are read. See
+     * OaiLimits::default_sampling. */
     SamplingParams default_sampling;
     bool        default_dry_breakers_set = false;
     /* The deployment's chat template variables and reply format. See OaiLimits. */
@@ -107,33 +100,24 @@ struct ServerOptions {
     bool        allow_video = false;
     bool        allow_audio = false;
 
-    /* WHAT /server_info AND /version REPORT ABOUT THE ENGINE BEHIND THIS SERVER.
-     *
-     * `engine_info` is a JSON OBJECT as text, spliced in verbatim under "engine". The server
-     * cannot derive any of it -- it deliberately knows nothing about the device layer, the
-     * container or the placement plan -- and a struct with a field per fact would be a struct
-     * this component has to grow every time the engine learns something new about itself. */
+    /* What /server_info and /version report about the engine. `engine_info` is a JSON object as
+     * text, spliced in verbatim under "engine": the server knows nothing of the device layer,
+     * container or placement plan, and an opaque blob need not grow with every new engine fact. */
     std::string version = RAD_VERSION;
     std::string engine_info;
-    /* The declared compute graph, as JSON, for the Model view. A PROVIDER, called per request,
-     * rather than a string rendered once after declare.
+    /* The declared compute graph as JSON, for the Model view. A provider called per request, not
+     * a string rendered once: the dump includes `OpInfo::issued`, which a pre-first-step snapshot
+     * would report as false for every op, hiding dead declarations.
      *
-     * The declaration itself does not change while the server runs, but the dump also carries what
-     * the run phase has DONE with it -- `OpInfo::issued` -- and a snapshot taken before the first
-     * step reports every op in the model as never issued, permanently, which makes /graph useless
-     * for finding a dead declaration.
-     *
-     * Regenerating reads the Program from the HTTP thread while the step path writes that one
-     * field. It is a monotonic false -> true bool, so the worst case is a graph fetched mid-step
-     * showing an op as unissued one step before it flips. Registry::select is asked with
-     * record = false and mutates nothing else. */
+     * Regenerating reads the Program on the HTTP thread while the step path writes that field. It
+     * is a monotonic false -> true bool, so at worst a mid-step fetch shows an op unissued one step
+     * early. Registry::select is called with record = false and mutates nothing else. */
     std::function graph_json;
-    /* THE STARTUP REPORT READ AGAIN, as JSON (core/diag/diag.h): the options in force, the machine
-     * as it is now (the provider may reuse a reading for a second), and what on it costs speed.
-     * Without a key it is answered to loopback clients only (Server::handle_diagnostics). A
-     * provider like the graph's, because a card's link speed and clock only say anything under
-     * load -- a request made during a long prefill is how a link parked below its maximum is told
-     * from one at rest. */
+    /* The startup report as JSON (core/diag/diag.h): options in force, the machine as it is now
+     * (the provider may reuse a reading for a second), and what on it costs speed. Without an API
+     * key, loopback clients only (Server::handle_diagnostics). A provider because link speed and
+     * clock only mean something under load: queried during a long prefill, it tells a link parked
+     * below its maximum from one at rest. */
     std::function diagnostics_json;
 
     std::string api_key;
@@ -149,37 +133,34 @@ struct ServerOptions {
 class Server {
 public:
     Server(const Deps& d, const ServerOptions& o);
-    /* Lifetime rule, and it is load-bearing: stop the scheduler before destroying the Server.
-     * `Request::sink` is a raw pointer into storage this object owns, and a request the scheduler
-     * has not finished is a request still writing into it. The destructor waits a bounded time
-     * for anything it cancelled and then deliberately leaks the rest rather than free memory a
+    /* Stop the scheduler before destroying the Server: `Request::sink` is a raw pointer into
+     * storage this object owns, and an unfinished request still writes into it. The destructor
+     * waits a bounded time for cancelled requests, then leaks the rest rather than free memory a
      * running step may touch. */
     ~Server();
 
-    /* Every endpoint, registered. Tests drive this directly -- same handlers, no socket. */
+    /* Every endpoint. Tests drive this directly: same handlers, no socket. */
     const Router& router() const { return router_; }
 
     int  run();            /* binds, serves, blocks. RAD_OK or negative. */
 
-    /* THE DEPLOYMENT'S TEMPLATE DEFAULTS, RENDERED ONCE BEFORE A CALLER DEPENDS ON THEM. A value
-     * the chat template refuses is a 400 on every request that leaves it to the default, so a
-     * one-message chat is parsed exactly as a request would be: first with no template defaults,
-     * then with the --chat-template-kwargs ones, then with the --reasoning-effort one as well.
-     * A render that fails at the first step says nothing about the defaults and is not reported.
-     * `kwargs_why` / `effort_why` are left empty, or hold the template's refusal at that step. */
+    /* Renders the deployment's template defaults once at startup, since a default the template
+     * refuses would 400 every request relying on it. A one-message chat is parsed as a request
+     * would be: with no defaults, then with --chat-template-kwargs, then also --reasoning-effort.
+     * A failure at the first stage is not about the defaults and is not reported. `kwargs_why` /
+     * `effort_why` stay empty or hold the template's refusal at that stage. */
     void check_template_defaults(std::string* kwargs_why, std::string* effort_why) const;
-    /* THE DEPLOYMENT'S thinking_token_budget, asked for by a one-message chat the way a request
-     * would ask for it. Empty when this model's reasoning block can hold one; otherwise the 400 a
-     * request naming the budget would get, which says why. */
+    /* Checks the deployment's thinking_token_budget with a one-message chat, as a request would
+     * send it. Empty when the model's reasoning block can take one; otherwise the 400 message a
+     * request naming the budget would get. */
     std::string check_thinking_budget() const;
-    /* THE EFFORTS THE CHAT TEMPLATE TAKES, found by parsing a one-message chat with each word this
-     * server knows of (low, medium, high, xhigh, max) the way a request would send it, with no
-     * deployment defaults. A template that takes a word nobody uses takes any word, and the answer
-     * is empty. Kept for the refusal of a word outside the set and for /server_info; called once,
-     * before run(). */
+    /* The reasoning efforts the chat template takes, found by parsing a one-message chat with each
+     * known word (low, medium, high, xhigh, max), with no deployment defaults. If the template
+     * also takes a nonsense word it takes any word, and the result is empty. Used to refuse words
+     * outside the set and for /server_info; called once, before run(). */
     std::vector probe_reasoning_efforts();
-    /* --reasoning-effort-map's targets, each rendered as a request's effort would be. Empty when
-     * the template takes every one; otherwise the first refusal, naming the target. */
+    /* Renders each --reasoning-effort-map target as a request's effort. Empty when the template
+     * takes all of them; otherwise the first refusal, naming the target. */
     std::string check_reasoning_effort_map() const;
     void stop();
     int  port() const { return transport_.port(); }   /* 0 until run() is accepting */
@@ -190,6 +171,8 @@ public:
 
 private:
     struct Generation;
+    struct TranscriptionJob;   /* speech.cpp */
+    struct RealtimeSession;    /* realtime.cpp */
     struct StreamState;
 
     static UsageOut usage_of(const OaiRequest& r, const std::vector& gens);
@@ -198,62 +181,77 @@ private:
 
     void register_routes();
 
+    /* ------------------------------------------------------------------ server.cpp */
     HttpResponse handle_chat(const HttpRequest& req);
     HttpResponse handle_completion(const HttpRequest& req);
+    HttpResponse handle_messages(const HttpRequest& req);
+    HttpResponse handle_responses(const HttpRequest& req);
+    HttpResponse handle_native_completion(const HttpRequest& req);
+    HttpResponse handle_infill(const HttpRequest& req);
     HttpResponse handle_embeddings(const HttpRequest& req);
-    /* ------------------------------------------------------------------ images.cpp */
-    HttpResponse handle_images(const HttpRequest& req, bool edit);
     HttpResponse handle_systemone(const HttpRequest& req);
+    HttpResponse handle_apply_template(const HttpRequest& req);
+    using ToChat = int (*)(const std::string& body, const OaiLimits& lim, std::string* chat,
+                           std::string* extra, ApiError* err);
+    HttpResponse count_tokens(const HttpRequest& req, ToChat to_chat, ApiShape shape,
+                              const char* object);
+    /* OpenAI's /v1/audio/transcriptions, from the model's own RadAudioFormat (speech.cpp). */
+    HttpResponse handle_transcription(const HttpRequest& req);
+    /* OpenAI's realtime transcription session over a WebSocket at /v1/realtime: audio streamed
+     * in, the transcript streamed out while it is spoken (realtime.cpp). */
+    void handle_realtime(const HttpRequest& req, WsConn& ws);
+    /* The session's thread: realtime_loop, an exception turned into an error event and a close,
+     * and the pass in flight cancelled however the loop ends. The loop returns true when the
+     * server ended the session, false when the peer left. */
+    void realtime_run(RealtimeSession& s, WsConn& ws);
+    bool realtime_loop(RealtimeSession& s, WsConn& ws);
     HttpResponse handle_models(const HttpRequest& req);
     HttpResponse handle_metrics(const HttpRequest& req);
+    std::optional refuse_text(const std::string& peer,
+                                            ApiShape shape = ApiShape::OpenAI);
+    /* A parsed generation request, in any API's shape: admitted, run, answered in `r.shape`. */
+    HttpResponse serve(const HttpRequest& req, OaiRequest& r);
+    json native_result(const OaiRequest& r, const Generation& g, const std::string& content);
+
+    /* ------------------------------------------------------------------ images.cpp */
+    HttpResponse handle_images(const HttpRequest& req, bool edit);
 
     /* ------------------------------------------------------------------ admin.cpp
-     * vLLM's non-generation surface. Separate because none of it touches the scheduler's step
-     * path, the admission queue or a Sink: these are questions about the server, answered on the
-     * HTTP thread and finished before they return. */
+     * vLLM's non-generation surface, answered on the HTTP thread without the step path, the
+     * admission queue or a Sink. */
     HttpResponse handle_health(const HttpRequest& req);
     HttpResponse handle_ping(const HttpRequest& req);
     HttpResponse handle_version(const HttpRequest& req);
     HttpResponse handle_props(const HttpRequest& req);
-    HttpResponse handle_apply_template(const HttpRequest& req);
-    HttpResponse handle_input_tokens(const HttpRequest& req);
-    HttpResponse handle_messages(const HttpRequest& req);
-    HttpResponse handle_count_tokens(const HttpRequest& req);
-    HttpResponse handle_responses(const HttpRequest& req);
-    HttpResponse handle_responses_tokens(const HttpRequest& req);
-    /* A request another API's shape was translated into: admitted and served like a chat one,
-     * answered in `r.shape`. */
-    HttpResponse serve_translated(const HttpRequest& req, OaiRequest& r);
-    HttpResponse handle_native_completion(const HttpRequest& req);
-    HttpResponse handle_infill(const HttpRequest& req);
-    json native_result(const OaiRequest& r, const Generation& g, const std::string& content);
     HttpResponse handle_load(const HttpRequest& req);
     HttpResponse handle_tokenize(const HttpRequest& req);
     HttpResponse handle_detokenize(const HttpRequest& req);
     HttpResponse handle_tokenizer_info(const HttpRequest& req);
     HttpResponse handle_server_info(const HttpRequest& req);
     HttpResponse handle_diagnostics(const HttpRequest& req);
-    /* What this deployment can do -- chat, tools, reasoning, grammar, media, logprobs, the
-     * reasoning efforts it takes -- as /server_info's `capabilities` and the model entry both
-     * report it, built in one place so the two cannot disagree. */
+    /* What this deployment can do (chat, tools, reasoning, grammar, media, logprobs, reasoning
+     * efforts), shared by /server_info's `capabilities` and the model entry so they agree. */
     json capabilities() const;
-    HttpResponse handle_sessions(const HttpRequest& req);
     HttpResponse handle_reset_prefix_cache(const HttpRequest& req);
 
     /* ------------------------------------------------------------------ dashboard.cpp */
     HttpResponse handle_dashboard(const HttpRequest& req);
     HttpResponse handle_stats(const HttpRequest& req);
     HttpResponse handle_graph(const HttpRequest& req);
+    HttpResponse handle_sessions(const HttpRequest& req);
 
     HttpResponse error_response(const ApiError& e, const std::string& peer,
                                 ApiShape shape = ApiShape::OpenAI);
-    /* THE REQUEST LOG. One line when a request is admitted and one from record() when it ends,
-     * at the info level, so `docker logs` answers "who asked what, how long, how did it end"
-     * without the engine's own levels. The debug level adds the last user message's opening. */
+    /* Request log: one info line at admission and one from record() at the end (who asked what,
+     * how long, how it ended). The debug level adds the opening of the last user message. */
     void log_admitted(const OaiRequest& r) const;
 
-    /* Admission. Returns false when the queue is full; the caller answers 429. */
-    bool  admit(int64_t n);
+    /* Admission: reserves `n` places in the queue, or returns the 429 to answer when it is full.
+     * More places than the queue has can never be admitted, so that is a 400 under `field` (the
+     * request field that multiplied them) naming the bound, not a 429 retried forever. Sweeps the
+     * graveyard first. */
+    std::optional admit(int64_t n, const std::string& peer,
+                                      ApiShape shape = ApiShape::OpenAI, const char* field = "n");
     void  release(int64_t n);
     void  sweep_abandoned();
     /* Wait, bounded, for the scheduler to finish everything it was told to cancel. */
@@ -262,6 +260,13 @@ private:
     /* Turn a parsed request into `n_choices` submitted engine requests. */
     int   submit_all(const OaiRequest& r, std::vector* gens, ApiError* err);
     void  cancel_all(std::vector& gens, bool count_disconnect);
+    /* While `gens` run: once the client has left (499) or the server is stopping, every
+     * generation is cancelled and retired, `n` queue places are released, and the answer is
+     * returned. Nothing otherwise. A generation request (`r`) is recorded as an abort, as a
+     * dropped stream is. */
+    std::optional abandoned(const HttpRequest& req, std::vector& gens,
+                                          int64_t n, ApiShape shape = ApiShape::OpenAI,
+                                          const OaiRequest* r = nullptr);
     void  retire(std::vector& gens);
 
     /* Drain sinks into decoded text. Returns true if anything new arrived. */
@@ -271,7 +276,10 @@ private:
     HttpResponse blocking_completion(const HttpRequest& req, OaiRequest& r);
     HttpResponse streaming_completion(const HttpRequest& req, OaiRequest& r);
 
-    void  record(const OaiRequest& r, const std::vector& gens, Finish overall);
+    /* `quiet` says the request's line at the debug level: one of the many small passes a
+     * realtime session makes, which its own lines account for. */
+    void  record(const OaiRequest& r, const std::vector& gens, Finish overall,
+                 bool quiet = false);
 
     Deps           deps_;
     ServerOptions  opt_;
@@ -283,12 +291,13 @@ private:
 
     std::atomic in_flight_{0};
     int64_t              queue_depth_ = 0;
+    std::atomic realtime_sessions_{0};
     std::atomic    stopping_{false};
     int64_t              started_at_ = 0;
 
     /* Sinks whose HTTP side is gone but whose engine side may still be mid-step. Held until the
      * scheduler reports the request terminal, because Request::sink is a raw pointer and freeing
-     * it under a running step is a use-after-free in the one place it is unbisectable. */
+     * it under a running step is a use-after-free. */
     std::mutex                          grave_m_;
     std::vector>  grave_;
 };
diff --git a/core/server/server_priv.h b/core/server/server_priv.h
new file mode 100644
index 00000000..a695db40
--- /dev/null
+++ b/core/server/server_priv.h
@@ -0,0 +1,88 @@
+/* server_priv.h -- the Server's per-request state, shared by the units that serve requests
+ * (server.cpp, speech.cpp, realtime.cpp). Not part of the server's interface: nothing outside
+ * core/server includes it. */
+#pragma once
+#include "server.h"
+#include "rad_internal.h"
+
+#include 
+#include 
+#include 
+#include 
+
+namespace rad {
+namespace mm { struct Item; }
+namespace server {
+
+/* ------------------------------------------------------------------ per-choice state */
+
+struct Server::Generation {
+    std::shared_ptr         sink;
+    std::unique_ptr detok;
+    std::unique_ptr delta;   /* chat streaming only, in the request's API shape */
+    uint64_t    id = 0;
+    int         index = 0;
+    int         prompt_index = 0;
+    std::string text;
+    std::vector logprobs;
+    size_t      lp_sent = 0;         /* streaming: how many of `logprobs` a chunk already carried */
+    /* Tracks every delivered token against the reasoning block, for
+     * completion_tokens_details.reasoning_tokens. */
+    ReasoningCount think;
+    Finish      finish = Finish::None;
+    bool        closed = false;      /* the server has decided this choice is over */
+    size_t      scanned = 0;         /* how far the stop-string scan has reached */
+    /* OaiRequest::stops_after: where in `text` the reasoning block's closer ends (npos until it
+     * has been generated) and how far the search for it has reached. */
+    size_t      stops_floor = std::string::npos;
+    size_t      closer_scanned = 0;
+    size_t      stop_cut = std::string::npos;
+    std::string stop_word;           /* the stop string at stop_cut, "" when the decoder cut it */
+    size_t      emitted = 0;         /* streaming: text already handed to the delta stream */
+    std::vector tokens;     /* llama-server's native shape: the ids generated */
+    size_t      tokens_sent = 0;     /* ...and how many of them a stream chunk carried */
+    int32_t     progress_sent = -1;  /* streaming: the prompt_progress last sent, -1 for none */
+    bool        retired = false;     /* reap() has been said for this id, at most once */
+};
+
+struct Server::StreamState {
+    OaiRequest              r;
+    std::vector gens;
+    std::function   peer_closed;
+    bool opened = false;
+    bool done_sent = false;
+    bool released = false;
+};
+
+/* The failure message for the client: the failing component's sentence and the status. A failed
+ * request always carries a negative status (RAD_E_STATE if none was set), so this never reads
+ * "ok". */
+inline std::string engine_failure(const Sink& s) {
+    const int st = s.status() < 0 ? s.status() : RAD_E_STATE;
+    const char* why = s.why();
+    return why ? fmt("the engine failed this request: %s (%s)", why, rad_strerror(st))
+               : fmt("the engine failed this request: %s", rad_strerror(st));
+}
+
+/* ------------------------------------------------------------------ speech (speech.cpp)
+ * The model's transcription format, used by the upload route and the realtime one alike. */
+
+/* The plugin's template with its three slots filled (`context` as plain text, the clip's
+ * placeholder run, and `language_text`, from speech_language_text or ""), as tokens with the clip
+ * placed. RAD_E_INVAL when the template has no {audio} slot. */
+int speech_prompt(const SpeechFormat& f, ITokenizer& tok, const std::string& context,
+                  const std::string& language_text, const std::shared_ptr& item,
+                  PromptInput* out);
+/* What a forced language puts in the {language} slot: the plugin's language_prompt naming it. */
+std::string speech_language_text(const SpeechFormat& f, const std::string& name);
+/* Where the transcript starts in a reply so far: past the transcript's opener, once it has been
+ * generated, and past the whitespace after it. npos while a reply that is not `closed` has not
+ * named it yet; a closed reply that never named it is all transcript. */
+size_t speech_transcript_start(const SpeechFormat& f, const std::string& text, bool forced,
+                               bool closed);
+/* The centre of the quietest 100 ms of x[lo, hi): where a recording too long for one pass is cut,
+ * between words when there is a pause to cut in. */
+int64_t speech_quiet_point(const std::vector& x, int64_t lo, int64_t hi, int32_t rate);
+
+}  /* namespace server */
+}  /* namespace rad */
diff --git a/core/server/sink.cpp b/core/server/sink.cpp
index 85a06d57..6d051b02 100644
--- a/core/server/sink.cpp
+++ b/core/server/sink.cpp
@@ -39,12 +39,11 @@ Sink::Sink(size_t capacity) {
 }
 
 Sink::~Sink() {
-    /* Only a sink the producer actually terminated can have a notify in flight; one that was
-     * never handed to the scheduler quiesces trivially. */
+    /* Only a sink the producer terminated can have a notify in flight. */
     if (finish_.load(std::memory_order_acquire) == (int)Finish::None) return;
     for (int spins = 0; !quiesced_.load(std::memory_order_acquire); ++spins) {
-        /* The window is a handful of instructions wide, so a short spin covers it; the sleep is
-         * there so a descheduled producer cannot burn a core. */
+        /* The window is a few instructions wide, so a short spin covers it; the sleep keeps a
+         * descheduled producer from burning a core. */
         if (spins > 256) std::this_thread::sleep_for(std::chrono::microseconds(20));
     }
 }
@@ -52,9 +51,8 @@ Sink::~Sink() {
 int64_t Sink::age_ns() const { return now_ns() - t_start_ns_; }
 
 void Sink::notify() {
-    /* Deliberately not holding m_. See the header: this can lose a wake-up, and the consumer's
-     * bounded wait is what pays for that. Taking the lock here would put the scheduler thread
-     * behind whatever an HTTP thread happens to be doing. */
+    /* Deliberately without m_ (see sink.h): a lost wake-up is covered by the consumer's bounded
+     * wait, and the scheduler thread never waits on an HTTP thread. */
     cv_.notify_one();
 }
 
@@ -68,7 +66,7 @@ bool Sink::push(int32_t token, const TokenLogprobs* lp) {
     const uint64_t h = head_.load(std::memory_order_relaxed);
     const uint64_t t = tail_.load(std::memory_order_acquire);
     if (h - t > mask_) {
-        /* The consumer is not draining. Failing loudly beats a stream with a hole in it. */
+        /* The consumer is not draining; fail rather than leave a hole in the stream. */
         overflow_.store(true, std::memory_order_release);
         fail(RAD_E_FULL);
         return false;
@@ -96,9 +94,8 @@ void Sink::finish(Finish f) {
     /* First terminal state wins: a cancel racing an EOS must not be reported twice. */
     if (finish_.compare_exchange_strong(expected, (int)f, std::memory_order_acq_rel)) {
         notify();
-        /* The last write the producer ever makes to this object, and the one the destructor
-         * waits on. It has to come after the notify, not before it: the point is to publish that
-         * the condition variable is no longer being touched. */
+        /* The producer's last write to this object, which the destructor waits on. It must
+         * follow the notify: it publishes that the condition variable is no longer in use. */
         quiesced_.store(true, std::memory_order_release);
     }
 }
@@ -126,7 +123,7 @@ void Sink::mark_admitted() {
         t_admit_.store(now_ns() - t_start_ns_, std::memory_order_release);
 }
 
-/* One producer, so a load and a store is the whole of the update. */
+/* One producer, so a load and a store suffice. */
 void Sink::add_drafts(int32_t n, int32_t accepted) {
     n_draft_.store(n_draft_.load(std::memory_order_relaxed) + n, std::memory_order_release);
     n_draft_acc_.store(n_draft_acc_.load(std::memory_order_relaxed) + accepted,
diff --git a/core/server/sink.h b/core/server/sink.h
index dd047812..4d22f422 100644
--- a/core/server/sink.h
+++ b/core/server/sink.h
@@ -1,22 +1,18 @@
 /* core/server/sink.h -- the per-request channel from the scheduler thread to the HTTP thread.
  *
- * `Request::sink` is the void* hook for this (rad_core.h). Exactly one scheduler thread writes it
- * and exactly one HTTP thread reads it, so it is a single-producer single-consumer ring and needs
- * no lock on the data path: a relaxed load of the head, a store into a slot, a release store of
- * the head. The producer never allocates and never blocks, which is the requirement -- a step
- * that can be delayed by a slow HTTP client is a step that has coupled every request in the batch
- * to the worst one.
+ * `Request::sink` is the void* hook for this (rad_core.h). One scheduler thread writes and one
+ * HTTP thread reads, so it is a lock-free single-producer single-consumer ring: relaxed load of
+ * the head, store into a slot, release store of the head. The producer never allocates or
+ * blocks, so a slow HTTP client cannot delay a step for the whole batch.
  *
- * The wake-up is the one place a mutex appears, and only on the consumer's side of it. The
- * producer calls notify_one() without holding the lock, which can lose a wake-up in the window
- * between the consumer testing the predicate and sleeping; the consumer therefore waits with a
- * bounded timeout (RAD_SINK_POLL_MS) rather than indefinitely. The cost is named: a lost wake-up
- * adds at most that many milliseconds to one token's latency. The benefit is that the scheduler
- * thread never takes a lock an HTTP thread might be holding, and the same timeout doubles as the
- * interval at which the streaming path polls whether the client is still there.
+ * Only the consumer takes the mutex. The producer calls notify_one() without it, which can lose
+ * a wake-up between the consumer's predicate test and its sleep, so the consumer waits at most
+ * RAD_SINK_POLL_MS. A lost wake-up costs at most that much latency on one token; in exchange the
+ * scheduler never waits on a lock an HTTP thread holds. The same timeout is the streaming path's
+ * client-liveness poll interval.
  *
  * Tokens, not text: detokenisation is stateful and per-request (spec §12) and belongs on the HTTP
- * thread. Pushing an int32 keeps the producer's write to eight bytes and no allocation.
+ * thread, and the producer's write stays a fixed-size SinkToken.
  */
 #pragma once
 #include "rad_core.h"
@@ -43,8 +39,8 @@ enum class Finish : int {
     Error,         /* the engine failed the request; `status` says why */
 };
 
-/* The OpenAI `finish_reason` string. Cancelled has no OpenAI spelling; vLLM reports "abort" and
- * dashboards key off that, so we match vLLM rather than inventing one. */
+/* The OpenAI `finish_reason` string. Cancelled has no OpenAI spelling; it is "abort" as in vLLM,
+ * which dashboards key off. */
 const char* finish_reason_oai(Finish f);
 
 struct SinkToken {
@@ -61,21 +57,17 @@ struct SinkAlt {
 
 class Sink {
 public:
-    /* `capacity` is rounded up to a power of two. 8192 tokens is ~64 KiB and is far more than any
-     * HTTP consumer can fall behind by without being dead: at 100 tok/s that is 80 seconds of
-     * slack. Overflow is not silently dropped -- it fails the request, because a stream missing
-     * tokens in the middle is worse than a stream that stops and says so. */
+    /* `capacity` is rounded up to a power of two. 8192 tokens is 80 s of slack at 100 tok/s, far
+     * more than a live consumer falls behind. Overflow fails the request rather than dropping
+     * tokens from the middle of the stream. */
     explicit Sink(size_t capacity = 8192);
 
-    /* Waits for the producer to be finished touching this object before letting it go.
+    /* Waits until the producer has stopped touching this object.
      *
-     * Observing `done()` is not enough. The producer publishes the terminal state and only then
-     * wakes the consumer, so between those two instructions the consumer can already be inside
-     * this destructor -- and destroying a condition_variable while another thread is inside
-     * notify_one() on it is a use-after-free in pthread_cond_signal. The producer therefore sets
-     * a quiesced flag as its genuinely last act, and this waits for that flag rather than for the
-     * state. The window is a handful of instructions wide, so only a data-race detector reports
-     * it. */
+     * Observing `done()` is not enough: the producer publishes the terminal state and only then
+     * calls notify_one(), and destroying the condition_variable in between is a use-after-free in
+     * pthread_cond_signal. The producer's last act is to set a quiesced flag, which this waits
+     * for. The window is a few instructions wide. */
     ~Sink();
 
     /* ------------------------------------------------------------------ producer: scheduler */
@@ -84,30 +76,28 @@ public:
      * logprobs when the request asked for them (enable_logprobs), and null otherwise. */
     bool push(int32_t token, const TokenLogprobs* lp = nullptr);
 
-    /* Terminal. Idempotent -- the first call wins, so a cancel racing a natural stop does not
+    /* Terminal and idempotent: the first call wins, so a cancel racing a natural stop does not
      * produce two finish reasons. */
     void finish(Finish f);
-    /* `why` says what failed, in a sentence a client can read; a string that outlives the sink
-     * (a literal), or null. */
+    /* `why` is a client-readable sentence that outlives the sink (a literal), or null. */
     void fail(int rad_status, const char* why = nullptr);
 
-    /* The scheduler polls this to learn that the client hung up, and frees the blocks (spec §14).
-     * It is also told by IScheduler::cancel(); this is the cheap path that needs no lookup. */
+    /* The scheduler polls this to learn the client hung up, then frees the blocks (spec §14).
+     * IScheduler::cancel() also tells it; this is the cheap path with no lookup. */
     bool cancel_requested() const { return cancel_.load(std::memory_order_acquire); }
 
     /* Admission accounting, set once by the scheduler when the prompt is placed. */
     void set_prompt_stats(int32_t n_prompt, int32_t n_cached);
 
-    /* THE FIRST TIME THE SCHEDULER GIVES THIS REQUEST A STEP: where its prompt phase starts, so
-     * the time it waited in the queue is not counted as prefill. A preempted request admitted
-     * again keeps the first mark. */
+    /* Marks the first step the scheduler gives this request, where its prompt phase starts, so
+     * queue time is not counted as prefill. A preempted request keeps its first mark. */
     void mark_admitted();
-    /* A verify step's speculation for this request: `n` tokens proposed, `accepted` of them
-     * taken. Summed over the request, the per-request half of /metrics' draft counters. */
+    /* One verify step: `n` draft tokens proposed, `accepted` taken. Summed per request for
+     * /metrics' draft counters. */
     void add_drafts(int32_t n, int32_t accepted);
-    /* HOW MUCH OF THE PROMPT IS IN THE CACHE: at admission (what the prefix cache supplied) and
-     * after every prefill step, of `total`, of which `cached` came from the prefix cache. What
-     * llama-server streams as `prompt_progress` when a request asks for it; wakes the consumer. */
+    /* Prompt tokens processed of `total`, `cached` of them from the prefix cache. Set at
+     * admission and after every prefill step; streamed as llama-server's `prompt_progress` when
+     * a request asks for it. Wakes the consumer. */
     void set_prompt_progress(int32_t processed, int32_t total, int32_t cached);
     int32_t progress_processed() const { return prog_done_.load(std::memory_order_acquire); }
     int32_t progress_total() const    { return prog_total_.load(std::memory_order_acquire); }
@@ -115,9 +105,8 @@ public:
 
     /* ------------------------------------------------------------------ consumer: HTTP */
 
-    /* Copies up to `max` tokens out. Returns how many. Never blocks. With `alts`, each token's
-     * alternatives too: token i's n_alt of them at alts[i * alt_width()], which needs room for
-     * max * alt_width(). */
+    /* Copies up to `max` tokens out and returns how many; never blocks. With `alts`, token i's
+     * n_alt alternatives go to alts[i * alt_width()], which needs room for max * alt_width(). */
     size_t read(SinkToken* out, size_t max, SinkAlt* alts = nullptr);
 
     /* Sleeps until there is something to read, the request is terminal, or `timeout_ms` elapses.
@@ -130,8 +119,8 @@ public:
     const char* why() const { return why_.load(std::memory_order_acquire); }
     bool   overflowed() const { return overflow_.load(std::memory_order_acquire); }
 
-    /* The HTTP thread calls this when the peer disappears. It does NOT free anything itself --
-     * the server calls IScheduler::cancel(id) as well; this only stops the producer sooner. */
+    /* Called by the HTTP thread when the peer disappears. Frees nothing: the server also calls
+     * IScheduler::cancel(id); this only stops the producer sooner. */
     void request_cancel();
 
     /* Timings, in steady-clock nanoseconds since the sink was constructed. -1 until observed. */
@@ -139,7 +128,7 @@ public:
     int64_t t_last_token_ns() const  { return t_last_.load(std::memory_order_acquire); }
     int64_t t_admitted_ns() const    { return t_admit_.load(std::memory_order_acquire); }
     int64_t age_ns() const;
-    /* The steady clock at construction, which the times above count from: what puts two sinks'
+    /* The steady clock at construction, which the times above count from; puts two sinks'
      * times on one axis. */
     int64_t t_start_ns() const { return t_start_ns_; }
 
@@ -150,19 +139,18 @@ public:
     int32_t n_prompt() const { return n_prompt_.load(std::memory_order_acquire); }
     int32_t n_cached() const { return n_cached_.load(std::memory_order_acquire); }
 
-    /* THE ALTERNATIVES' RING, sized for `n` a token, beside the token ring: allocated only for a
-     * request that asks for them, because at RAD_MAX_LOGPROBS it is twenty times the token ring.
-     * Called by the consumer before the request is handed to the scheduler. */
+    /* Allocates the alternatives ring, `n` per token, beside the token ring. Only requests that
+     * ask for logprobs get one: at RAD_MAX_LOGPROBS it is twenty times the token ring. The
+     * consumer calls this before handing the request to the scheduler. */
     void enable_logprobs(int n);
     int  alt_width() const { return alt_w_; }
 
     /* The engine's request id, so a dropped connection can reach IScheduler::cancel. */
     uint64_t id = 0;
 
-    /* AN EMBEDDING REQUEST'S ANSWER: the pooled vector, written once by the engine before the
-     * step's commit finishes the request, and read by the consumer only after done(). finish()
-     * publishes with a release store and done() reads with an acquire load, so the vector is
-     * visible to anyone who has seen the request finish. Empty for every generating request. */
+    /* An embedding request's pooled vector; empty for generating requests. Written once by the
+     * engine before the request finishes and read only after done(): finish()'s release store
+     * and done()'s acquire load publish it. */
     void set_embedding(const float* v, int64_t n) { embd_.assign(v, v + n); }
     const std::vector& embedding() const { return embd_; }
 
@@ -203,8 +191,8 @@ private:
     std::condition_variable cv_;
 };
 
-/* The scheduler's call sites, so core/sched needs one include and no casts of its own. A null
- * sink is legal and means nobody is listening -- an offline or benchmark request. */
+/* The scheduler's call sites, so core/sched needs no casts. A null sink means nobody is
+ * listening (an offline or benchmark request). */
 inline bool sink_push(void* s, int32_t token, const TokenLogprobs* lp = nullptr) {
     return s ? static_cast(s)->push(token, lp) : true;
 }
diff --git a/core/server/speech.cpp b/core/server/speech.cpp
new file mode 100644
index 00000000..24202aa2
--- /dev/null
+++ b/core/server/speech.cpp
@@ -0,0 +1,589 @@
+/* speech.cpp -- OpenAI's POST /v1/audio/transcriptions, over the model's own speech format.
+ *
+ * What this route knows about the model is what its plugin states: the turn a transcription is
+ * asked in, how a language is forced and named, and where the transcript starts in the reply
+ * (rad_arch_audio_format, copied into SpeechFormat at startup). This file knows OpenAI's side: the
+ * form, the response shapes and the stream's events.
+ *
+ * Request: multipart/form-data, as OpenAI's is: `file` (required), `model`, `language` (a code or
+ * a name the model knows), `prompt` (context for the recognition: a name, a domain),
+ * `response_format` (json, text or verbose_json), `stream`, and `temperature`, which must be 0
+ * because the decode is greedy, as the reference model's is. Word timestamps are refused rather
+ * than answered with nothing.
+ *
+ * A recording longer than one encoder pass is cut into clips, each ending at the quietest 100 ms of
+ * the last five seconds before the pass would be full, so a cut lands in a pause where there is
+ * one. Each clip is one prompt; the clips run a wave at a time and their transcripts are joined
+ * with a space.
+ *
+ * Prompt: the plugin's template with its three slots filled: the request's `prompt` as plain text
+ * (tokenised with no special tokens parsed, so a caller cannot write the model's control tokens
+ * into it), the clip's placeholder run, and the forced-language text or nothing.
+ */
+#include "server.h"
+#include "server_priv.h"
+
+#include "mm/processor.h"
+#include "rad_internal.h"
+
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace rad {
+namespace server {
+
+std::string SpeechFormat::language_name(const std::string& lang) const {
+    auto lower = [](std::string s) {
+        for (char& c : s) c = (char)std::tolower((unsigned char)c);
+        return s;
+    };
+    const std::string l = lower(lang);
+    for (const auto& p : languages)
+        if (lower(p.first) == l || lower(p.second) == l) return p.second;
+    return std::string();
+}
+
+namespace {
+
+/* The most a clip's transcript may run to. Thirty seconds of the fastest speech is a few hundred
+ * tokens; the bound is there for a model that loops, not for one that talks. */
+constexpr int32_t kMaxTokensPerClip = 512;
+/* The longest recording one request transcribes. */
+constexpr int64_t kMaxSeconds = 3600;
+/* Clips submitted together. */
+constexpr size_t kWave = 8;
+
+std::string trim(const std::string& s) {
+    size_t a = 0, b = s.size();
+    while (a < b && std::isspace((unsigned char)s[a])) ++a;
+    while (b > a && std::isspace((unsigned char)s[b - 1])) --b;
+    return s.substr(a, b - a);
+}
+
+/* Where a long recording is cut: [start, end) clips of at most `max_n` samples, each ending at the
+ * quietest point in the last five seconds (or half a clip, if that is shorter) before the clip
+ * would be full. */
+std::vector> cut_clips(const std::vector& x, int64_t max_n,
+                                                   int32_t rate) {
+    std::vector> out;
+    const int64_t n = (int64_t)x.size();
+    const int64_t search = std::min(max_n / 2, (int64_t)rate * 5);
+    int64_t start = 0;
+    while (n - start > max_n) {
+        const int64_t hi = start + max_n;
+        const int64_t best = speech_quiet_point(x, hi - search, hi, rate);
+        out.emplace_back(start, best);
+        start = best;
+    }
+    out.emplace_back(start, n);
+    return out;
+}
+
+/* What one clip's reply says: the transcript, and the language when the model named it. A reply
+ * the language was forced in is the transcript alone. */
+struct Heard {
+    std::string language;
+    std::string text;
+};
+
+Heard read_reply(const SpeechFormat& f, const std::string& reply, const std::string& forced) {
+    if (!forced.empty() || f.transcript_open.empty()) return { forced, trim(reply) };
+    const size_t at = reply.find(f.transcript_open);
+    if (at == std::string::npos) return { std::string(), trim(reply) };
+    Heard h;
+    h.text = trim(reply.substr(at + f.transcript_open.size()));
+    const std::string head = reply.substr(0, at);
+    const size_t lead = f.language_lead.empty() ? std::string::npos : head.rfind(f.language_lead);
+    const std::string said = trim(lead == std::string::npos ? head
+                                                            : head.substr(lead + f.language_lead.size()));
+    /* A name the model does not list (its own "None" for a clip with no speech) is no
+     * language. */
+    h.language = f.language_name(said);
+    return h;
+}
+
+std::string lower(std::string s) {
+    for (char& c : s) c = (char)std::tolower((unsigned char)c);
+    return s;
+}
+
+}  /* namespace */
+
+/* ------------------------------------------------------------------ shared with realtime.cpp */
+
+int speech_prompt(const SpeechFormat& f, ITokenizer& tok, const std::string& context,
+                  const std::string& language_text, const std::shared_ptr& item,
+                  PromptInput* out) {
+    auto pm = std::make_shared();
+    const std::string& t = f.transcribe_prompt;
+    auto add = [&](const std::string& text, bool special) {
+        if (text.empty()) return;
+        const std::vector ids = tok.encode(text, /*add_special=*/false, special);
+        out->tokens.insert(out->tokens.end(), ids.begin(), ids.end());
+        out->text += text;
+    };
+    size_t pos = 0;
+    bool placed = false;
+    while (pos < t.size()) {
+        size_t at = t.find('{', pos);
+        if (at == std::string::npos) at = t.size();
+        add(t.substr(pos, at - pos), true);
+        if (at == t.size()) break;
+        if (!t.compare(at, 9, "{context}")) {
+            add(context, false);
+            pos = at + 9;
+        } else if (!t.compare(at, 10, "{language}")) {
+            add(language_text, true);
+            pos = at + 10;
+        } else if (!t.compare(at, 7, "{audio}")) {
+            mm::Placed pl;
+            pl.item = item;
+            pl.tok = (int32_t)out->tokens.size();
+            out->tokens.insert(out->tokens.end(), item->expand.begin(), item->expand.end());
+            out->text += RAD_MEDIA_MARKER;
+            pm->items.push_back(std::move(pl));
+            placed = true;
+            pos = at + 7;
+        } else {
+            add("{", true);
+            pos = at + 1;
+        }
+    }
+    if (!placed) return RAD_E_INVAL;
+    pm->layout();
+    out->media = std::move(pm);
+    return RAD_OK;
+}
+
+std::string speech_language_text(const SpeechFormat& f, const std::string& name) {
+    std::string t = f.language_prompt;
+    const size_t at = t.find("{language}");
+    if (at != std::string::npos) t.replace(at, 10, name);
+    return t;
+}
+
+size_t speech_transcript_start(const SpeechFormat& f, const std::string& text, bool forced,
+                               bool closed) {
+    size_t s = 0;
+    if (!forced && !f.transcript_open.empty()) {
+        const size_t at = text.find(f.transcript_open);
+        if (at == std::string::npos) return closed ? 0 : std::string::npos;
+        s = at + f.transcript_open.size();
+    }
+    while (s < text.size() && std::isspace((unsigned char)text[s])) ++s;
+    return s;
+}
+
+int64_t speech_quiet_point(const std::vector& x, int64_t lo, int64_t hi, int32_t rate) {
+    const int64_t win = std::max(2, rate / 10);
+    lo = std::max(lo, 0);
+    int64_t best = hi;
+    double best_e = INFINITY;
+    for (int64_t a = lo; a + win <= hi; a += win / 2) {
+        double e = 0.0;
+        for (int64_t i = a; i < a + win; ++i) e += (double)x[(size_t)i] * x[(size_t)i];
+        if (e < best_e) { best_e = e; best = a + win / 2; }
+    }
+    return best;
+}
+
+/* One transcription request: the recording, where it is cut, and what each clip heard. Clips
+ * are prepared a wave at a time, so a long recording holds its samples and one wave's features,
+ * not every clip's at once. The request holds `places` admission places from its first wave to
+ * its last, so a later wave is never refused once the first has run. Shared between the handler
+ * and, for a stream, the transport's callbacks. */
+struct Server::TranscriptionJob {
+    OaiRequest              base;        /* everything but the prompts and max_tokens */
+    std::vector      samples;     /* the whole recording at the model's rate */
+    std::vector> cuts;   /* each clip's [start, end) in samples */
+    int32_t                 rate = 0;
+    std::string             context;     /* the request's `prompt`, plain text */
+    std::string             language_text;
+    std::string             forced;      /* the forced language's name, "" for none */
+    std::vector replies;    /* each clip's whole reply, once its wave is done */
+    std::vector      heard;
+    int64_t n_prompt = 0, n_gen = 0;
+    size_t  next = 0;                    /* the first clip not yet submitted */
+    int64_t places = 0;                  /* admission places held, 0 once released */
+
+    /* The wave in flight. */
+    OaiRequest r;
+    std::vector gens;
+    bool    running = false;
+
+    /* Streaming: how much of the stream's text has gone out, and the clip it is reading. */
+    size_t  stream_clip = 0;
+    size_t  stream_off = 0;
+    bool    stream_started = false;
+    bool    done_sent = false;
+    std::string streamed;
+};
+
+HttpResponse Server::handle_transcription(const HttpRequest& req) {
+    if (!deps_.sched || !deps_.tok)
+        return error_response(err_not_implemented("the server has no engine attached"), req.peer);
+    if (!deps_.speech || !deps_.speech->transcribes() || !deps_.mm ||
+        !deps_.mm->accepts(MediaKind::Audio) || deps_.mm->audio_rate() <= 0)
+        return error_response(err_not_implemented(
+                                  "this model does not transcribe: its architecture plugin states "
+                                  "no transcription format (rad_arch_audio_format), or it was "
+                                  "started without its audio encoder"),
+                              req.peer);
+    const SpeechFormat& f = *deps_.speech;
+
+    /* ---- the form */
+    if (req.form.empty())
+        return error_response(err_bad("file", "expected multipart/form-data with a `file` part, "
+                                              "as OpenAI's transcription API takes"),
+                              req.peer);
+    auto field = [&](const char* k) {
+        const FormPart* p = req.part(k);
+        return p ? trim(p->data) : std::string();
+    };
+    const FormPart* file = req.part("file");
+    if (!file || file->data.empty())
+        return error_response(err_bad("file", "the audio file is missing or empty"), req.peer);
+    const std::string fmt = field("response_format").empty() ? "json" : field("response_format");
+    if (fmt != "json" && fmt != "text" && fmt != "verbose_json")
+        return error_response(err_unsupported("response_format",
+                                              "json, text or verbose_json; not '" + fmt + "'"),
+                              req.peer);
+    const std::string stream_s = lower(field("stream"));
+    const bool stream = stream_s == "true" || stream_s == "1";
+    if (!stream_s.empty() && !stream && stream_s != "false" && stream_s != "0")
+        return error_response(err_bad("stream", "expected true or false"), req.peer);
+    if (const std::string t = field("temperature"); !t.empty()) {
+        char* end = nullptr;
+        const double v = std::strtod(t.c_str(), &end);
+        if (end == t.c_str() || *end != '\0' || !std::isfinite(v))
+            return error_response(err_bad("temperature", "expected a number, not '" + t + "'"),
+                                  req.peer);
+        if (v != 0.0)
+            return error_response(err_unsupported("temperature",
+                                                  "this route decodes greedily, as the model's "
+                                                  "reference does; send 0 or leave it out"),
+                                  req.peer);
+    }
+    for (const FormPart& p : req.form)
+        if ((p.name == "timestamp_granularities[]" || p.name == "timestamp_granularities") &&
+            trim(p.data) == "word")
+            return error_response(err_unsupported("timestamp_granularities",
+                                                   "word timestamps are not produced; verbose_json "
+                                                   "carries one segment a clip"),
+                                  req.peer);
+    std::string forced;
+    if (!field("language").empty()) {
+        forced = f.language_name(field("language"));
+        if (forced.empty()) {
+            std::string known;
+            for (const auto& l : f.languages) known += (known.empty() ? "" : ", ") + l.first;
+            return error_response(err_bad("language", "this model names no language '" +
+                                                          field("language") + "'; it knows " +
+                                                          known),
+                                  req.peer);
+        }
+    }
+
+    /* ---- the recording, and where it is cut into clips one encoder pass each */
+    auto job = std::make_shared();
+    job->rate = deps_.mm->audio_rate();
+    const int32_t rate = job->rate;
+    const int64_t max_clip = deps_.mm->audio_max_samples();
+    {
+        std::string why;
+        const std::vector bytes(file->data.begin(), file->data.end());
+        const int s = deps_.mm->decode_audio(bytes, kMaxSeconds * rate, &job->samples, &why);
+        if (s < 0) return error_response(err_bad("file", "the audio could not be used: " + why),
+                                         req.peer);
+    }
+    if (job->samples.empty())
+        return error_response(err_bad("file", "the recording holds no audio"), req.peer);
+    job->cuts = cut_clips(job->samples, max_clip > 0 ? max_clip : (int64_t)job->samples.size(),
+                          rate);
+    job->context = field("prompt");
+    job->forced = forced;
+    job->language_text = forced.empty() ? std::string() : speech_language_text(f, forced);
+    job->replies.assign(job->cuts.size(), std::string());
+    job->heard.assign(job->cuts.size(), Heard{});
+
+    OaiRequest& b = job->base;
+    b.endpoint = Endpoint::Completion;
+    b.shape = ApiShape::OpenAI;
+    b.model = opt_.model_id;
+    b.id = random_id("tr-");
+    b.created = (int64_t)std::time(nullptr);
+    b.peer = req.peer;
+    b.n = 1;
+    b.sp = SamplingParams{};
+    b.sp.temp = 0.0f;
+    b.sp.top_k = 1;
+
+    /* A wave is at most kWave clips and never more than the admission queue holds. */
+    const size_t wave = (size_t)std::max(
+        1, std::min({ (int64_t)kWave, (int64_t)job->cuts.size(), queue_depth_ }));
+    if (auto no = admit((int64_t)wave, req.peer)) return *no;
+    job->places = (int64_t)wave;
+
+    sweep_abandoned();
+    Server* self = this;
+    const SpeechFormat* fp = &f;
+    auto release_job = [self, job]() {
+        if (job->places > 0) { self->release(job->places); job->places = 0; }
+    };
+    /* Prepare and submit the next wave; false with `*err` set when it could not be. */
+    auto start_wave = [self, job, fp, wave](ApiError* err) -> bool {
+        const size_t n = std::min(wave, job->cuts.size() - job->next);
+        job->r = job->base;
+        job->r.prompts.clear();
+        int64_t longest = 0;
+        for (size_t i = job->next; i < job->next + n; ++i) {
+            const std::vector clip(job->samples.begin() + job->cuts[i].first,
+                                          job->samples.begin() + job->cuts[i].second);
+            std::shared_ptr item;
+            std::string why;
+            if (self->deps_.mm->prepare_audio(clip, &item, &why) < 0 || !item) {
+                *err = err_bad("file", "the audio could not be used: " + why);
+                return false;
+            }
+            PromptInput p;
+            if (speech_prompt(*fp, *self->deps_.tok, job->context, job->language_text, item,
+                              &p) < 0) {
+                *err = err_not_implemented("the model's transcription template has no {audio} "
+                                           "slot");
+                return false;
+            }
+            longest = std::max(longest, (int64_t)p.tokens.size());
+            job->n_prompt += (int64_t)p.tokens.size();
+            job->r.prompts.push_back(std::move(p));
+        }
+        job->r.max_tokens = kMaxTokensPerClip;
+        if (self->lim_.max_ctx > 0) {
+            if (longest >= self->lim_.max_ctx) {
+                *err = err_bad("file", "a clip's prompt (" + std::to_string(longest) +
+                                           " tokens) is longer than the context");
+                return false;
+            }
+            job->r.max_tokens = (int32_t)std::min(job->r.max_tokens,
+                                                           self->lim_.max_ctx - longest);
+        }
+        if (job->next == 0) self->log_admitted(job->r);
+        job->gens.clear();
+        if (self->submit_all(job->r, &job->gens, err) < 0) {
+            self->retire(job->gens);
+            return false;
+        }
+        job->running = true;
+        return true;
+    };
+    /* A wave that has finished: its replies kept, its sequences retired. Error when one failed. */
+    auto finish_wave = [self, job, fp](std::string* failure) -> bool {
+        Finish overall = Finish::Stop;
+        for (const auto& g : job->gens) {
+            const size_t k = job->next + (size_t)g.prompt_index;
+            job->replies[k] = g.text;
+            job->heard[k] = read_reply(*fp, g.text, job->forced);
+            job->n_gen += g.sink->n_produced();
+            if (g.finish == Finish::Error) {
+                overall = Finish::Error;
+                if (failure) *failure = engine_failure(*g.sink);
+            }
+        }
+        self->record(job->r, job->gens, overall);
+        self->retire(job->gens);
+        job->next += job->r.prompts.size();
+        job->running = false;
+        return overall != Finish::Error;
+    };
+    auto joined = [job]() {
+        std::string t;
+        for (const Heard& h : job->heard) {
+            if (h.text.empty()) continue;
+            if (!t.empty()) t += ' ';
+            t += h.text;
+        }
+        return t;
+    };
+    auto usage = [job]() {
+        nlohmann::ordered_json u;
+        u["type"] = "tokens";
+        u["input_tokens"] = job->n_prompt;
+        u["output_tokens"] = job->n_gen;
+        u["total_tokens"] = job->n_prompt + job->n_gen;
+        return u;
+    };
+    auto internal = [](const std::string& why) {
+        ApiError e;
+        e.status = 500;
+        e.type = "internal_server_error";
+        e.message = why;
+        return e;
+    };
+
+    if (!stream) {
+        while (job->next < job->cuts.size()) {
+            ApiError err;
+            if (!start_wave(&err)) {
+                release_job();
+                return error_response(err, req.peer);
+            }
+            for (;;) {
+                pump(job->gens, job->r);
+                if (all_done(job->gens)) break;
+                if (req.peer_gone() || stopping_.load()) {
+                    cancel_all(job->gens, req.peer_gone());
+                    record(job->r, job->gens, Finish::Cancelled);
+                    retire(job->gens);
+                    release_job();
+                    if (req.peer_gone()) {
+                        metrics_.observe_http(499);
+                        return HttpResponse::text(499, "client closed request\n");
+                    }
+                    return error_response(err_overloaded("the server is shutting down"), req.peer);
+                }
+                for (auto& g : job->gens) if (!g.closed) { g.sink->wait(); break; }
+            }
+            std::string failure;
+            if (!finish_wave(&failure)) {
+                release_job();
+                return error_response(internal(failure), req.peer);
+            }
+        }
+        release_job();
+        const std::string text = joined();
+        metrics_.observe_http(200);
+        if (fmt == "text") return HttpResponse::text(200, text + "\n");
+        nlohmann::ordered_json o;
+        if (fmt == "verbose_json") {
+            std::string lang = forced;
+            for (const Heard& h : job->heard)
+                if (lang.empty() && !h.language.empty()) lang = h.language;
+            o["task"] = "transcribe";
+            o["language"] = lower(lang);
+            o["duration"] = (double)job->samples.size() / rate;
+            o["text"] = text;
+            nlohmann::ordered_json segs = nlohmann::ordered_json::array();
+            for (size_t i = 0; i < job->heard.size(); ++i) {
+                nlohmann::ordered_json s;
+                s["id"] = (int64_t)i;
+                s["start"] = (double)job->cuts[i].first / rate;
+                s["end"] = (double)job->cuts[i].second / rate;
+                s["text"] = job->heard[i].text;
+                segs.push_back(std::move(s));
+            }
+            o["segments"] = std::move(segs);
+        } else {
+            o["text"] = text;
+        }
+        o["usage"] = usage();
+        return HttpResponse::json_body(200, json_dump(o));
+    }
+
+    /* ---- the stream: transcript.text.delta events as each clip's transcript settles, in clip
+     * order, then transcript.text.done with the whole text. */
+    {
+        ApiError err;
+        if (!start_wave(&err)) {
+            release_job();
+            return error_response(err, req.peer);
+        }
+    }
+    HttpResponse res;
+    res.status = 200;
+    res.content_type = "text/event-stream; charset=utf-8";
+    res.set_header("Cache-Control", "no-cache");
+    res.set_header("Connection", "keep-alive");
+    res.set_header("X-Accel-Buffering", "no");
+    auto peer_closed = req.closed;
+    res.next = [self, job, peer_closed, fp, start_wave, finish_wave, joined, usage, internal,
+                release_job](std::string& out) -> bool {
+        out.clear();
+        if (job->done_sent) return false;
+        if (peer_closed && peer_closed()) return false;
+        auto delta = [&](const std::string& d) {
+            if (d.empty()) return;
+            nlohmann::ordered_json o;
+            o["type"] = "transcript.text.delta";
+            o["delta"] = d;
+            out += sse_event(json_dump(o));
+            job->streamed += d;
+        };
+        const bool progress = job->running && self->pump(job->gens, job->r);
+        /* Whatever of the clip being read has settled; the clips after it wait their turn. */
+        while (job->stream_clip < job->cuts.size()) {
+            const size_t k = job->stream_clip;
+            const bool in_wave = k >= job->next && k < job->next + job->gens.size() && job->running;
+            const Generation* g = in_wave ? &job->gens[k - job->next] : nullptr;
+            const bool closed = g ? g->closed : k < job->next;
+            const std::string& text = g ? g->text : job->replies[k];
+            const size_t s = speech_transcript_start(*fp, text, !job->forced.empty(), closed);
+            if (s != std::string::npos) {
+                std::string end = closed ? trim(text.substr(std::min(s, text.size())))
+                                         : text.substr(s);
+                if (closed && end.size() < job->stream_off) end.clear();
+                if (end.size() > job->stream_off) {
+                    std::string d = end.substr(job->stream_off);
+                    if (!job->stream_started && !job->streamed.empty() && job->stream_off == 0)
+                        d = " " + d;
+                    if (job->stream_off == 0 && !d.empty()) job->stream_started = true;
+                    job->stream_off = end.size();
+                    delta(d);
+                }
+            }
+            if (!closed) break;
+            ++job->stream_clip;
+            job->stream_off = 0;
+            job->stream_started = false;
+        }
+        if (job->running && self->all_done(job->gens)) {
+            std::string failure;
+            if (!finish_wave(&failure)) {
+                out += sse_error(internal(failure));
+                job->done_sent = true;
+                release_job();
+                return true;
+            }
+            if (job->next < job->cuts.size()) {
+                ApiError err;
+                if (!start_wave(&err)) {
+                    out += sse_error(err);
+                    job->done_sent = true;
+                    release_job();
+                    return true;
+                }
+            }
+            return true;
+        }
+        if (!job->running && job->stream_clip >= job->cuts.size()) {
+            release_job();
+            nlohmann::ordered_json o;
+            o["type"] = "transcript.text.done";
+            o["text"] = joined();
+            o["usage"] = usage();
+            out += sse_event(json_dump(o));
+            job->done_sent = true;
+            self->metrics_.observe_http(200);
+            return true;
+        }
+        if (!progress && out.empty() && job->running)
+            for (auto& g : job->gens) if (!g.closed) { g.sink->wait(); break; }
+        return true;
+    };
+    res.on_close = [self, job, release_job](bool) {
+        if (job->running) {
+            self->cancel_all(job->gens, true);
+            self->record(job->r, job->gens, Finish::Cancelled);
+            self->retire(job->gens);
+            job->running = false;
+        }
+        release_job();
+    };
+    return res;
+}
+
+}  /* namespace server */
+}  /* namespace rad */
diff --git a/core/server/systemone.cpp b/core/server/systemone.cpp
index ee0f73ea..16d2533e 100644
--- a/core/server/systemone.cpp
+++ b/core/server/systemone.cpp
@@ -1,19 +1,18 @@
 /* systemone.cpp -- d1's prompt and readout (systemone.h).
  *
- * EVERY STRING BELOW IS d1's OWN, from prompt.py in the model's repository: the user turn, the
- * state block, the three question blocks, the option codes and their fallback codebook, the
- * yes/no spellings. The model was trained on exactly these, so a reworded instruction or a
- * different code for an option is a different (and worse-calibrated) question.
+ * Every prompt string below is d1's own, from prompt.py in the model's repository: the user turn,
+ * the state block, the three question blocks, the option codes and their fallback codebook, and the
+ * yes/no spellings. The model was trained on exactly these; a reworded instruction or a different
+ * option code is a different, worse-calibrated question.
  *
- * THAT TEXT IS LIQUID AI'S, under the LFM Open License v1.0 (core/server/LICENSE.lfm, and NOTICE):
- * this file is a C++ rewrite of prompt.py's and api.py's logic, modified from them, with their
+ * That text is Liquid AI's, under the LFM Open License v1.0 (core/server/LICENSE.lfm, and NOTICE).
+ * This file is a C++ rewrite of prompt.py's and api.py's logic, modified from them, with their
  * strings kept as they are.
  *
- * AND SO IS THE TOKENISATION SPLIT. d1 tokenises a single question's prompt as one text, and a
- * request with several as the shared head (the state and the pictures) followed by each question's
- * tail, tokenised separately -- its runner reads the head once and branches. The two are not the
- * same ids where BPE would merge across the join, so each case is tokenised the way the model's
- * own runner does.
+ * The tokenisation split also follows d1's runner: a single question's prompt is tokenised as one
+ * text; with several, the shared head (state and pictures) and each question's tail are tokenised
+ * separately, and the runner reads the head once and branches. BPE can merge across the join, so
+ * the two give different ids.
  */
 #include "systemone.h"
 
@@ -253,7 +252,7 @@ int parse_decision_request(const std::string& body, const OaiDeps& d, const OaiL
         return RAD_E_INVAL;
     }
 
-    /* THE PICTURES, decoded here and processed when the head is tokenised. */
+    /* Pictures are decoded here and processed when the head is tokenised. */
     std::vector>> media;
     if (b.contains("images")) {
         const json& im = b["images"];
@@ -302,8 +301,8 @@ int parse_decision_request(const std::string& body, const OaiDeps& d, const OaiL
         suffixes.push_back(std::move(suffix));
     }
 
-    /* runner.py, VISION_MAX_PIXELS: d1 bounds every picture at 1024 x 1024 pixels' area before
-     * its processor, so a larger one is a different input unless it is bounded here too. */
+    /* runner.py, VISION_MAX_PIXELS: d1 caps every picture at 1024 x 1024 pixels' area before its
+     * processor, so the same cap applies here. */
     MediaOpts opts;
     opts.max_pixels = 1024 * 1024;
     auto tokenize = [&](const std::string& text, std::vector* ids) -> int {
@@ -330,7 +329,7 @@ int parse_decision_request(const std::string& body, const OaiDeps& d, const OaiL
             out->input_tokens += (int64_t)tail.size();
         }
     }
-    /* One position stays free: the request samples a token, which nobody reads. */
+    /* One position stays free for the token the request samples and discards. */
     for (const DecisionQuestion& q : out->questions)
         if (lim.max_ctx > 0 && (int64_t)q.tokens.size() >= lim.max_ctx) {
             ApiError e = err_bad("questions." + q.name,
@@ -347,10 +346,7 @@ int parse_decision_request(const std::string& body, const OaiDeps& d, const OaiL
 int decision_answer(const DecisionQuestion& q, const std::vector& logits, json* out,
                     ApiError* err) {
     if (logits.size() != q.candidates.size() || q.groups.size() != q.labels.size()) {
-        *err = ApiError{};
-        err->status = 500;
-        err->type = "internal_server_error";
-        err->message = "the engine returned no scores for question " + q.name;
+        *err = err_internal("the engine returned no scores for question " + q.name);
         return RAD_E_STATE;
     }
     std::vector p;
@@ -358,10 +354,7 @@ int decision_answer(const DecisionQuestion& q, const std::vector& logits,
         double best = -std::numeric_limits::infinity();
         for (size_t i : g) best = std::max(best, (double)logits[i]);
         if (!std::isfinite(best)) {
-            *err = ApiError{};
-            err->status = 500;
-            err->type = "internal_server_error";
-            err->message = "question " + q.name + " scored a non-finite logit";
+            *err = err_internal("question " + q.name + " scored a non-finite logit");
             return RAD_E_STATE;
         }
         p.push_back(best);
diff --git a/core/server/systemone.h b/core/server/systemone.h
index ce54f146..ff58dac2 100644
--- a/core/server/systemone.h
+++ b/core/server/systemone.h
@@ -1,13 +1,13 @@
 /* systemone.h -- POST /v1/systemone: LiquidAI d1's decisions, a distribution read off one position.
  *
  * d1 is a decision model. It is given a state (text, any JSON value, pictures, or a mix) and named
- * questions, and each answer is a softmax over a handful of tokens at the position right after the
- * assistant header: `yes` / `no` for a noul, one code a option for a choice, a digit a level for a
- * score. Nothing is generated. The API and the prompt are the model's own (its prompt.py and api.py
- * on the Hub); this file is that adapter, and the engine knows nothing of it beyond
- * Request::token_scores -- "read these ids' raw logits at the prompt's last position".
+ * questions; each answer is a softmax over a few tokens at the position right after the assistant
+ * header: `yes` / `no` for a noul, one code per option for a choice, one digit per level for a
+ * score. Nothing is generated. The API and prompt are the model's own (prompt.py and api.py on the
+ * Hub). The engine sees only Request::token_scores: read these ids' raw logits at the prompt's last
+ * position.
  *
- * A container serves it only when it says it is d1 (`decision.type` = `d1`, set at convert with
+ * Served only when the container declares d1 (`decision.type` = `d1`, set at convert with
  * `--set decision.type=d1`); the HF config does not declare it.
  */
 #pragma once
@@ -23,12 +23,12 @@ namespace server {
 
 struct DecisionQuestion {
     std::string name, type;                     /* type: noul | choice | score */
-    /* One entry an answer, in the response's order: "true"/"false", the option names, the
-     * levels "0".."n-1". */
+    /* One entry per answer, in response order: "true"/"false", the option names, or the levels
+     * "0".."n-1". */
     std::vector labels;
     std::vector legend;            /* score: each level's description */
-    /* The ids read at the answer slot, and for each answer the indices into them of the
-     * spellings it scores as: an answer's score is its best spelling's. */
+    /* The ids read at the answer slot, and per answer the indices of its spellings among them;
+     * an answer scores as its best spelling. */
     std::vector             candidates;
     std::vector> groups;
     std::vector             tokens;    /* the whole prompt */
@@ -41,7 +41,7 @@ struct DecisionRequest {
     /* How many leading tokens every question's prompt shares: the state, tokenised once. 0 for
      * a single question, which d1 tokenises as one text. */
     int32_t trunk = 0;
-    /* What the model reads, as d1 counts it: the shared head once and each question's own tail. */
+    /* Input tokens as d1 counts them: the shared head once plus each question's tail. */
     int64_t input_tokens = 0;
 };
 
@@ -50,8 +50,8 @@ struct DecisionRequest {
 int parse_decision_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim,
                            const std::string& model_id, DecisionRequest* out, ApiError* err);
 
-/* One answer from its candidates' raw logits: each answer scores its best spelling, a softmax over
- * the answers is the distribution. Non-finite logits are an error, not a distribution. */
+/* One question's answer from its candidates' raw logits: each answer scores its best spelling and
+ * a softmax over the answers is the distribution. A non-finite logit is an error. */
 int decision_answer(const DecisionQuestion& q, const std::vector& logits, json* out,
                     ApiError* err);
 
diff --git a/core/text/chat.cpp b/core/text/chat.cpp
index 5b781a07..2986dc5e 100644
--- a/core/text/chat.cpp
+++ b/core/text/chat.cpp
@@ -1,9 +1,9 @@
 #include "text/chat.h"
 #include "text/tokenizer.h"
 
-/* The lifted headers live here and nowhere else in core/. See chat.h for why. */
+/* Lifted headers: only this file, chatfmt.cpp and chatparse.cpp include them (see chat.h). */
 #include "llama/common/chat.h"
-/* For jinja::enable_debug only -- see RADIANCE_DEBUG_JINJA below. */
+/* For jinja::enable_debug (RADIANCE_DEBUG_JINJA). */
 #include "llama/common/jinja/runtime.h"
 #include "shim/log.h"
 
@@ -16,7 +16,6 @@ namespace rad {
 
 using ojson = nlohmann::ordered_json;
 
-
 struct ChatTemplate::Impl {
     common_chat_templates_ptr tmpls;
     ChatCaps                  caps;
@@ -28,9 +27,8 @@ ChatTemplate::ChatTemplate() : impl_(std::make_unique()) {}
 ChatTemplate::~ChatTemplate() = default;
 
 const char* ChatTemplate::chatml_source() {
-    /* Byte-identical to CHATML_TEMPLATE_SRC in the lift. Duplicated rather than exported because
-     * exporting it would mean editing the lifted header; the string is stable upstream, and if it
-     * ever moves this is the single place that has to follow it. */
+    /* Byte-identical to CHATML_TEMPLATE_SRC in the lift, copied so the lifted header stays
+     * unedited. Keep in sync on a vendor refresh. */
     return
         "{%- for message in messages -%}\n"
         "  {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' -}}\n"
@@ -42,35 +40,29 @@ const char* ChatTemplate::chatml_source() {
 
 int ChatTemplate::load(const std::string& jinja_source, const std::string& bos,
                        const std::string& eos, bool add_bos, bool add_eos) {
-    /* The vendored files' LOG_DBG goes to stderr behind this switch. It has to be set HERE, where
-     * the template is first touched: the auto-parser analyses the template inside apply() and
-     * again when the reply format is derived (chatfmt.cpp), and a switch set any later comes too
-     * late to trace a format the analyzer could not crack. */
+    /* Gates the vendored LOG_DBG to stderr. Set here, where the template is first touched,
+     * because the auto-parser analyses it in apply() and again in chatfmt.cpp; any later is too
+     * late to trace a format the analyzer could not handle. */
     rad_vendor_log::verbose() = (int)log_level() >= (int)Log::Debug;
 
-    /* THE TEMPLATE ENGINE'S OWN TRACE, and there is no other way to get at this one.
-     * common_chat_templates_init runs a capability PROBE: it renders the template with a
-     * synthetic tool and a synthetic tool call and watches which values were read. It SWALLOWS
-     * every exception -- "ignore exceptions during capability analysis" -- so a template that
-     * genuinely has no tool support and a template that THROWS on the probe both arrive here as
-     * tools=0, and the difference is the difference between a model that cannot call tools and a
-     * gap in the engine. Loud: every statement of every render, the serving ones included. */
+    /* The template engine's own trace. The capability probe in common_chat_templates_init
+     * swallows every exception, so a template without tool support and one that throws on the
+     * probe both report tools=0; this trace tells them apart. Very verbose: it logs every
+     * statement of every render, serving ones included. */
     if (const char* dbg = std::getenv("RADIANCE_DEBUG_JINJA"); dbg && *dbg && *dbg != '0')
         jinja::enable_debug(true);
 
     const bool fallback = jinja_source.empty();
     if (fallback) {
-        /* A model with no template is a model whose prompt format we are guessing. ChatML is the
-         * best guess there is and it is still a guess, so it is said out loud once rather than
-         * discovered later from output that reads fine and is formatted wrong. */
+        /* ChatML is only a guess at the prompt format, so warn once. */
         RAD_WARN("chat: the model declares no chat template; falling back to ChatML. "
                  "If the model was not trained on ChatML its replies will be subtly wrong.");
     }
     const std::string src = fallback ? std::string(chatml_source()) : jinja_source;
 
     try {
-        /* model = nullptr: everything common_chat_templates_init() would read off a llama_model
-         * is passed in as an override instead. See vendor/shim/llama.h. */
+        /* model = nullptr: what would be read off a llama_model is passed in as overrides
+         * (vendor/shim/llama.h). */
         impl_->tmpls = common_chat_templates_init(nullptr, src, bos, eos);
     } catch (const std::exception& e) {
         RAD_ERR("chat: template did not compile: %s", e.what());
@@ -106,9 +98,8 @@ int ChatTemplate::load(const std::string& jinja_source, const std::string& bos,
 }
 
 int ChatTemplate::load_from_vocab(const Vocab& v) {
-    /* The template references bos_token and eos_token by TEXT, not by id, so what goes in is the
-     * piece -- and a control token's piece is its literal spelling, which is what Vocab::text()
-     * returns for it. */
+    /* Templates reference bos_token/eos_token by text; Vocab::text() returns a control token's
+     * literal spelling. */
     const std::string bos = v.bos() >= 0 ? v.text(v.bos()) : std::string();
     const std::string eos = v.eos() >= 0 ? v.text(v.eos()) : std::string();
     return load(v.chat_template(), bos, eos, v.add_bos(), v.add_eos());
@@ -118,16 +109,14 @@ bool ChatTemplate::ready() const { return impl_ && impl_->tmpls != nullptr; }
 const ChatCaps& ChatTemplate::caps() const { return impl_->caps; }
 const std::string& ChatTemplate::source() const { return impl_->src; }
 
-/* HOW DEEPLY A CLIENT'S SCHEMA MAY NEST, in objects and arrays. The tools' parameter schemas and
- * a response format's schema reach the JSON-schema converter, which recurses once per level and
- * names each rule after its whole path, so its output grows with the square of the depth; a few
- * thousand levels exhaust the memory or the stack of the thread rendering the request. At this
- * depth it still converts in tens of milliseconds, far deeper than a schema describing data
- * nests. grammar.cpp bounds the same converter on the path that bypasses the template. */
+/* Maximum nesting (objects and arrays) of a client's tool or response schema. The JSON-schema
+ * converter recurses once per level and names each rule after its full path, so its output grows
+ * with the square of the depth; a few thousand levels exhaust memory or the rendering thread's
+ * stack. 512 still converts in tens of milliseconds. grammar.cpp bounds the same converter on the
+ * path that bypasses the template. */
 static constexpr size_t kMaxSchemaDepth = 512;
 
-/* Walked with an explicit stack, because the values it exists to catch are the ones too deep to
- * recurse over. */
+/* Iterative, because the values it must catch are too deep to recurse over. */
 static size_t json_depth(const ojson& root) {
     std::vector> todo{ { &root, 1 } };
     size_t deepest = 0;
@@ -149,8 +138,8 @@ int ChatTemplate::apply(const ojson& messages, const ojson& tools, const ChatOpt
     }
     if (!out) return RAD_E_INVAL;
 
-    /* Checked before either schema reaches the converter. The response format arrives as text;
-     * one that does not parse is left for the template to refuse in its own words. */
+    /* Checked before either schema reaches the converter. A response format that does not parse
+     * is left for the template to refuse. */
     {
         const ojson schema = opt.json_schema.empty()
                            ? ojson()
@@ -166,19 +155,17 @@ int ChatTemplate::apply(const ojson& messages, const ojson& tools, const ChatOpt
     common_chat_templates_inputs in;
     try {
         in.messages = common_chat_msgs_parse_oaicompat(messages);
-        if (!tools.is_null() && tools.is_array() && !tools.empty())
+        if (tools.is_array() && !tools.empty())
             in.tools = common_chat_tools_parse_oaicompat(tools);
         in.tool_choice = common_chat_tool_choice_parse_oaicompat(opt.tool_choice);
     } catch (const std::exception& e) {
-        /* A malformed request, not a broken engine. It must come back as a 400 rather than as a
-         * throw through the request loop. */
+        /* A malformed request: return a 400, never throw through the request loop. */
         RAD_WARN("chat: request did not parse: %s", e.what());
         out->error = e.what();
         return RAD_E_INVAL;
     }
     if (!in.tools.empty() && !impl_->caps.tools) {
-        RAD_WARN("chat: the model's template declares no tool support; refusing the request "
-                 "rather than dropping the tools silently");
+        RAD_WARN("chat: the model's template declares no tool support; request refused");
         out->error = "this model's chat template declares no tool support";
         return RAD_E_UNSUPPORTED;
     }
@@ -228,11 +215,8 @@ int ChatTemplate::apply(const ojson& messages, const ojson& tools, const ChatOpt
               out->grammar.size(), out->grammar_lazy ? " (lazy)" : "",
               out->additional_stops.size());
     if ((int)log_level() >= (int)Log::Trace) {
-        /* THE PROMPT ITSELF, at Trace and nowhere else. A chat endpoint that answers fluently in
-         * the wrong format looks exactly like a chat endpoint that works, and the only way to tell
-         * the two apart is to read what the template actually produced -- control tokens included,
-         * which is why this prints the raw bytes rather than the detokenised form. It is at Trace
-         * because it is user content and does not belong in an ordinary server log. */
+        /* The rendered prompt as raw bytes, control tokens included, for checking the template's
+         * output format. Trace only, because it is user content. */
         RAD_TRACE("chat: prompt <<<%s>>>", out->prompt.c_str());
         if (!out->grammar.empty()) RAD_TRACE("chat: grammar <<<%s>>>", out->grammar.c_str());
         for (const auto& s : out->additional_stops) RAD_TRACE("chat: extra stop <<<%s>>>", s.c_str());
diff --git a/core/text/chat.h b/core/text/chat.h
index 6192f20a..469142b8 100644
--- a/core/text/chat.h
+++ b/core/text/chat.h
@@ -1,22 +1,19 @@
 /* chat.h -- rendering a message list to a prompt, and what the template can do.
  *
- * This is a thin face over the lifted `common_chat_*` API (vendor/llama/common/chat.*, jinja/,
- * see vendor/UPSTREAM). It does three things the lift does not:
+ * A thin layer over the lifted `common_chat_*` API (vendor/llama/common/chat.*, jinja/, see
+ * vendor/UPSTREAM). It adds three things:
  *
- *   1. ERRORS ARE VALUES. Upstream throws -- a bad template, a message the template rejects, a
- *      malformed OAI request are all std::runtime_error, and a throw crossing the server's
- *      request loop is not a failure mode this project accepts. Everything here returns a
- *      negative RAD_E_* and logs once.
- *   2. It takes the template out of the .rad instead of out of a llama_model. RadVocabHeader
- *      carries the chat template, the BOS/EOS spellings and the add_bos/add_eos flags, which is
- *      exactly the four things common_chat_templates_init() would otherwise read off a model.
- *   3. It keeps the lifted headers out of the rest of core/. Only chat.cpp, chatfmt.cpp and
- *      chatparse.cpp include them, the last only to resolve schema types when a request's tools
- *      are bound, so a vendor refresh cannot ripple into the server.
+ *   1. Errors are values. Upstream throws std::runtime_error for a bad template, a rejected
+ *      message or a malformed OAI request; a throw must not cross the server's request loop, so
+ *      everything here returns a negative RAD_E_* and logs once.
+ *   2. The template comes from the .rad, not a llama_model. RadVocabHeader carries the chat
+ *      template, the BOS/EOS spellings and the add_bos/add_eos flags, the four things
+ *      common_chat_templates_init() would otherwise read off a model.
+ *   3. The lifted headers stay out of the rest of core/. Only chat.cpp, chatfmt.cpp and
+ *      chatparse.cpp include them (the last only to resolve schema types for bound tools), so a
+ *      vendor refresh cannot ripple into the server.
  *
- * Messages and tools arrive as OpenAI-shaped JSON, because that is what the server has and the
- * lift already knows how to read it. Converting to a struct here and back inside would be a
- * translation nobody asked for.
+ * Messages and tools are OpenAI-shaped JSON, which is what the server has and what the lift reads.
  */
 #pragma once
 #include "rad_internal.h"
@@ -32,10 +29,9 @@ namespace rad {
 
 class Vocab;
 
-/* What the template supports, PROBED rather than assumed -- jinja/caps.cpp renders the template
- * against synthetic inputs and watches what it does with them (spec §12, "template capability
- * probe"). The server reports this on /props, and the message adapter uses it to decide whether
- * to hand the template a string content or a typed content array. */
+/* What the template supports, probed rather than assumed: jinja/caps.cpp renders the template
+ * against synthetic inputs and watches what it reads (spec §12, "template capability probe").
+ * Reported on /props; the message adapter uses it to choose string or typed-array content. */
 struct ChatCaps {
     bool tools = true;
     bool tool_calls = true;
@@ -45,7 +41,6 @@ struct ChatCaps {
     bool string_content = true;
     bool typed_content = false;
     bool object_arguments = false;
-
 };
 
 struct ChatOptions {
@@ -81,22 +76,16 @@ struct ChatPrompt {
     bool        supports_thinking = false;
     std::string thinking_start_tag, thinking_end_tag;
 
-    /* The auto-parser's own verdict on this render: `format` is a common_chat_format value and
-     * deliberately opaque here, `parser` the PEG grammar it derived. The engine reads replies
-     * with chatparse.h instead; these are kept for the differential tests that compare the two. */
+    /* The auto-parser's verdict on this render: `format` is an opaque common_chat_format value,
+     * `parser` the PEG grammar it derived. The engine parses replies with chatparse.h; these are
+     * kept for the differential tests that compare the two. */
     int         format = 0;
     std::string parser;
 
-    /* WHY THE TEMPLATE REFUSED, in the template's own words.
-     *
-     * A jinja `raise_exception` carries the one sentence that says what the caller got wrong --
-     * "Unexpected reasoning effort high. Supported types are xhigh (default), medium, and low."
-     * -- and it is carried out to the caller here rather than only into the log, so a 400 names
-     * the field at fault instead of saying only that the template refused the request. Filled
-     * only on a failure return; empty otherwise.
-     *
-     * It is the TEMPLATE'S text and therefore model-controlled, not attacker-controlled: it comes
-     * from the container's own jinja, which the operator chose along with the weights. */
+    /* Why the template refused, in its own words (a jinja `raise_exception` message such as
+     * "Unexpected reasoning effort high. Supported types are ..."), so a 400 names the field at
+     * fault. Set only on a failure return. The text comes from the container's jinja, so it is
+     * model-controlled, not attacker-controlled. */
     std::string error;
 };
 
@@ -105,29 +94,27 @@ public:
     ChatTemplate();
     ~ChatTemplate();
 
-    /* Compile a Jinja source. `bos`/`eos` are the token TEXTS, which templates reference as
-     * `bos_token` / `eos_token`. An empty source loads the ChatML fallback and says so at Warn:
-     * a model with no template is a model whose prompt format we are guessing, and guessing
-     * quietly is how a chat endpoint produces fluent nonsense. */
+    /* Compile a Jinja source. `bos`/`eos` are the token texts, which templates reference as
+     * `bos_token` / `eos_token`. An empty source loads the ChatML fallback with a Warn, since the
+     * prompt format is then a guess. */
     int load(const std::string& jinja_source, const std::string& bos, const std::string& eos,
              bool add_bos = false, bool add_eos = false);
-    /* The same, from a loaded vocab: template, bos text, eos text and the add flags all come off
-     * RadVocabHeader. This is the path the engine uses. */
+    /* The same, with template, bos/eos text and add flags taken from the vocab's RadVocabHeader.
+     * The engine uses this path. */
     int load_from_vocab(const Vocab& v);
 
     bool ready() const;
     const ChatCaps& caps() const;
     const std::string& source() const;
 
-    /* Render. `messages` and `tools` are OpenAI-shaped JSON (`tools` may be null or an empty
-     * array). Returns RAD_OK, or RAD_E_INVAL when the request does not parse, or
-     * RAD_E_UNSUPPORTED when the template refuses what was asked of it -- a system message to a
-     * template with no system role, tools to a template that has none. */
+    /* Render. `messages` and `tools` are OpenAI-shaped JSON (`tools` may be null or empty).
+     * Returns RAD_OK, RAD_E_INVAL when the request does not parse, or RAD_E_UNSUPPORTED when the
+     * template refuses it (e.g. a system message without a system role, or tools without tool
+     * support). */
     int apply(const nlohmann::ordered_json& messages, const nlohmann::ordered_json& tools,
               const ChatOptions& opt, ChatPrompt* out) const;
 
-    /* ChatML, the fallback. Named rather than inlined so the server can report which template it
-     * is running. */
+    /* The ChatML fallback, named so the server can report which template it runs. */
     static const char* chatml_source();
 
 private:
diff --git a/core/text/chatfmt.cpp b/core/text/chatfmt.cpp
index d86943ee..df5a7b54 100644
--- a/core/text/chatfmt.cpp
+++ b/core/text/chatfmt.cpp
@@ -3,8 +3,8 @@
 
 #include "rad_builder.h"
 
-/* The analyser and the grammar builder, at load and admission time only -- never while a reply
- * is being read. */
+/* The analyser and grammar builder, used at load and admission only, never while reading a
+ * reply. */
 #include "llama/common/chat.h"
 #include "llama/common/chat-auto-parser.h"
 #include "llama/common/json-schema-to-grammar.h"
@@ -44,6 +44,12 @@ bool starts_with(const std::string& s, const std::string& p) {
     return s.size() >= p.size() && s.compare(0, p.size(), p) == 0;
 }
 
+/* Two delimiters an automaton scanning for both cannot report in start order: one begins or
+ * occurs inside the other. */
+bool confusable(const std::string& a, const std::string& b) {
+    return starts_with(a, b) || starts_with(b, a) || occurs_inside(a, b) || occurs_inside(b, a);
+}
+
 std::string show(const std::string& s) { return nlohmann::json(s).dump(); }
 
 int refuse(std::string* why, const std::string& s) {
@@ -56,11 +62,11 @@ bool object_byte(unsigned char c) {
     return c == 0 || std::isalnum(c) || is_ws(c) || std::strchr("-+._'\"{}[],:", (int)c) != nullptr;
 }
 
-/* An argument object, as the streaming parser reads it (chatparse.cpp). Where a key or a value
- * may begin, it tells three literals apart by their first bytes: a dialect string's opener, and
- * the call's close and end, which a reply that leaves its object unclosed writes there. None may
- * begin another. A bare word ends at the object's punctuation or at the call's close; one
- * automaton finds both in the order they start only when the close holds none of it. */
+/* Checks an argument object against how chatparse.cpp reads it. Where a key or value may begin,
+ * the parser tells three literals apart by their first bytes: the dialect's string opener, and
+ * the call's close and end (a reply that leaves its object unclosed writes them there). None may
+ * begin another. A bare word ends at the object's punctuation or the call's close; one automaton
+ * reports both in start order only if the close contains no punctuation. */
 int object_check(const ChatFormat& f, std::string* why) {
     const std::string& so = f.object_string_open;
     const std::string& sc = f.object_string_close;
@@ -90,16 +96,15 @@ int object_check(const ChatFormat& f, std::string* why) {
             return refuse(why, show(*s) + " both opens an object string and closes the call");
     }
     for (size_t i = 0; i < lits.size(); ++i)
-        for (size_t j = 0; j < lits.size(); ++j)
-            if (i != j && (starts_with(lits[i], lits[j]) || occurs_inside(lits[j], lits[i])))
-                return refuse(why, show(lits[j]) + " and " + show(lits[i]) + " cannot be told "
+        for (size_t j = i + 1; j < lits.size(); ++j)
+            if (confusable(lits[i], lits[j]))
+                return refuse(why, show(lits[i]) + " and " + show(lits[j]) + " cannot be told "
                                    "apart inside an argument object");
     return RAD_OK;
 }
 
-/* Content is scanned for a later reasoning block's opener and for a stray close beside the call
- * openers, in one automaton, which reports them in the order they start only when none occurs
- * inside another or begins it. */
+/* Content is scanned for a later reasoning opener, a stray close and the call openers in one
+ * automaton, which reports them in start order only if none begins or occurs inside another. */
 int reasoning_anywhere_check(const ChatFormat& f, std::string* why) {
     if (!f.reasoning_anywhere) return RAD_OK;
     std::vector d = { trim_ws(f.reasoning_open), trim_ws(f.reasoning_close) };
@@ -108,9 +113,9 @@ int reasoning_anywhere_check(const ChatFormat& f, std::string* why) {
         d.push_back(f.name_prefix);
     }
     for (size_t i = 0; i < d.size(); ++i)
-        for (size_t j = 0; j < d.size(); ++j)
-            if (i != j && (starts_with(d[i], d[j]) || occurs_inside(d[j], d[i])))
-                return refuse(why, show(d[j]) + " and " + show(d[i]) + " cannot be told apart in "
+        for (size_t j = i + 1; j < d.size(); ++j)
+            if (confusable(d[i], d[j]))
+                return refuse(why, show(d[i]) + " and " + show(d[j]) + " cannot be told apart in "
                                    "content, which a reasoning block may open anywhere in");
     return RAD_OK;
 }
@@ -120,10 +125,7 @@ int reasoning_anywhere_check(const ChatFormat& f, std::string* why) {
 /* ================================================================== validity */
 
 int chat_format_check(const ChatFormat& f, std::string* why) {
-    auto no = [&](const std::string& s) {
-        if (why) *why = s;
-        return RAD_E_UNSUPPORTED;
-    };
+    auto no = [why](const std::string& s) { return refuse(why, s); };
 
     if (!f.reasoning_open.empty() && f.reasoning_close.empty())
         return no("reasoning_open " + show(f.reasoning_open) + " has no reasoning_close");
@@ -202,8 +204,7 @@ int chat_format_check(const ChatFormat& f, std::string* why) {
     if (!f.call_open.empty()) {
         const std::string co = trim_ws(f.call_open);
         if (co.empty()) return no("call_open is only whitespace");
-        if (starts_with(co, f.name_prefix) || starts_with(f.name_prefix, co) ||
-            occurs_inside(co, f.name_prefix) || occurs_inside(f.name_prefix, co))
+        if (confusable(co, f.name_prefix))
             return no("call_open " + show(f.call_open) + " and name_prefix " +
                       show(f.name_prefix) + " cannot be told apart");
     }
@@ -216,25 +217,22 @@ int chat_format_check(const ChatFormat& f, std::string* why) {
     for (const std::string& t : f.triggers)
         if (t.empty()) return no("an empty grammar trigger");
 
-    /* The delimiter sets scanned together must be read in the order they START, which an
-     * automaton reports correctly only when no delimiter occurs inside another. */
+    /* Delimiters scanned together must be reported in start order, which an automaton does only
+     * when no delimiter occurs inside another. */
     if (f.has_reasoning()) {
         const std::string close = trim_ws(f.reasoning_close);
         for (const std::string& b : f.reasoning_breaks)
-            if (occurs_inside(close, b) || occurs_inside(b, close) || starts_with(b, close) ||
-                starts_with(close, b))
+            if (confusable(close, b))
                 return no("reasoning break " + show(b) + " overlaps reasoning_close " +
                           show(close));
     }
     if (!object) {
-        /* Inside a call the next tag is an argument or the close, and the close is recognised by
-         * its core as well: the whitespace around it is optional when a reply leaves the
-         * format. */
+        /* Inside a call the next tag is an argument or the close. The close also matches by its
+         * trimmed core, since a reply that strays from the format may drop its whitespace. */
         const std::string end = trim_ws(f.call_end);
         if (end.empty()) return no("call_end is only whitespace");
         for (const std::string* e : { &f.call_end, &end })
-            if (starts_with(f.arg_prefix, *e) || starts_with(*e, f.arg_prefix) ||
-                occurs_inside(f.arg_prefix, *e) || occurs_inside(*e, f.arg_prefix))
+            if (confusable(f.arg_prefix, *e))
                 return no("arg_prefix " + show(f.arg_prefix) + " and call_end " +
                           show(f.call_end) + " cannot be told apart");
     }
@@ -299,9 +297,9 @@ int chat_format_from_abi(const RadChatFormat* in, ChatFormat* out, std::string*
 int chat_format_from_template(const std::string& jinja, const std::string& bos,
                               const std::string& eos, ChatFormat* out,
                               std::string* tools_refused, std::string* why) {
-    std::string dummy;
-    if (!tools_refused) tools_refused = &dummy;
-    if (!why) why = &dummy;
+    std::string refused_unused, why_unused;
+    if (!tools_refused) tools_refused = &refused_unused;
+    if (!why) why = &why_unused;
     tools_refused->clear();
     const std::string src = jinja.empty() ? std::string(ChatTemplate::chatml_source()) : jinja;
 
@@ -367,10 +365,9 @@ int chat_format_from_template(const std::string& jinja, const std::string& bos,
             c.string_value     = ChatValue::Cdata;
             c.other_value      = ChatValue::Json;
             c.value_newlines   = true;
-            /* What opens a call is what both the lazy grammar waits for and what ends an
-             * unclosed reasoning block -- the section or per-call opener. A format with neither
-             * gets no grammar and no break: its calls open with the function name prefix, which
-             * a model also writes in prose. */
+            /* The section or per-call opener both triggers the lazy grammar and ends an
+             * unclosed reasoning block. A format with neither gets no grammar and no break,
+             * since its calls open with the name prefix, which a model also writes in prose. */
             const std::string& marker = !t.format.section_start.empty() ? t.format.section_start
                                                                          : t.format.per_call_start;
             if (!marker.empty()) {
@@ -437,11 +434,10 @@ std::vector chat_format_markers(const ChatFormat& f) {
 
 /* ================================================================== grammar
  *
- * The grammar is built as an expression tree and rendered by the rules the vendored PEG-to-GBNF
- * pass uses, so a format derived from a template yields the same text the vendored generator
- * produces for it: sequences and alternations are flattened as they are built, a sequence or
- * alternation nested in a sequence is parenthesised, only an alternation nested in an
- * alternation is, and a repeated sequence or alternation is. */
+ * The grammar is an expression tree rendered by the vendored PEG-to-GBNF rules, so a
+ * template-derived format yields the same text as the vendored generator. Sequences and
+ * alternations flatten as they are built. Parentheses go around a sequence or alternation inside
+ * a sequence, an alternation inside an alternation, and a repeated sequence or alternation. */
 namespace {
 
 struct G {
@@ -449,7 +445,6 @@ struct G {
     std::string s;               /* Lit: the text; Leaf: rendered GBNF */
     std::vector kids;
     int min = 0, max = -1;
-    bool compound = false;       /* Leaf/Wrap: renders like a sequence for parenthesising */
 };
 
 G eps() { return G{}; }
@@ -458,26 +453,21 @@ G leaf(const std::string& s) { G g; g.k = G::Leaf; g.s = s; return g; }
 G space() { return leaf("space"); }
 G rule_ref(const std::string& name) { return leaf(name); }
 
-/* A tag or an atomic around a node: it renders as the node, is parenthesised as the node would
- * be, but a sequence built around it does not flatten into it. */
+/* A tag or atomic around a node: renders and parenthesises as the node, but an enclosing
+ * sequence does not flatten into it. */
 G wrap(G inner) { G g; g.k = G::Wrap; g.kids.push_back(std::move(inner)); return g; }
 
-G seq(std::vector parts) {
-    G g; g.k = G::Seq;
+/* A sequence or alternation of `parts`, a part of the same kind spliced in flat. */
+G flat(G::K k, std::vector parts) {
+    G g; g.k = k;
     for (G& p : parts) {
-        if (p.k == G::Seq) for (G& c : p.kids) g.kids.push_back(std::move(c));
-        else g.kids.push_back(std::move(p));
-    }
-    return g;
-}
-G alt(std::vector parts) {
-    G g; g.k = G::Alt;
-    for (G& p : parts) {
-        if (p.k == G::Alt) for (G& c : p.kids) g.kids.push_back(std::move(c));
+        if (p.k == k) for (G& c : p.kids) g.kids.push_back(std::move(c));
         else g.kids.push_back(std::move(p));
     }
     return g;
 }
+G seq(std::vector parts) { return flat(G::Seq, std::move(parts)); }
+G alt(std::vector parts) { return flat(G::Alt, std::move(parts)); }
 G rep(G child, int min, int max) {
     G g; g.k = G::Rep; g.min = min; g.max = max; g.kids.push_back(std::move(child)); return g;
 }
@@ -542,10 +532,9 @@ std::string class_char(uint32_t c) {
     if (c == '\r') return "\\r";
     if (c >= 0x20 && c <= 0x7E) return std::string(1, (char)c);
     static const char* hex = "0123456789ABCDEF";
-    std::string s;
-    if (c <= 0xFF) { s = "\\x"; for (int i = 1; i >= 0; --i) s += hex[(c >> (4 * i)) & 15]; }
-    else if (c <= 0xFFFF) { s = "\\u"; for (int i = 3; i >= 0; --i) s += hex[(c >> (4 * i)) & 15]; }
-    else { s = "\\U"; for (int i = 7; i >= 0; --i) s += hex[(c >> (4 * i)) & 15]; }
+    const int digits = c <= 0xFF ? 2 : c <= 0xFFFF ? 4 : 8;
+    std::string s = digits == 2 ? "\\x" : digits == 4 ? "\\u" : "\\U";
+    for (int i = digits - 1; i >= 0; --i) s += hex[(c >> (4 * i)) & 15];
     return s;
 }
 
@@ -636,10 +625,9 @@ std::string until_pattern(const std::vector& delims) {
     return "(" + pattern + ")*";
 }
 
-/* The rules the vendored generator emits for its generic JSON parser whenever an argument or a
- * document is typed by a schema. Nothing references them -- the schema's own rules do the
- * constraining -- but the vendored grammar carries them, and so does this one, so the two can be
- * compared byte for byte. */
+/* The generic JSON rules the vendored generator emits whenever a schema types an argument or
+ * document. Nothing references them (the schema's own rules constrain), but they are emitted so
+ * the output compares byte for byte with the vendored grammar. */
 void add_json_rules(const common_grammar_builder& b) {
     b.add_rule("json-array", "\"[\" space (\"]\" | json-value (\",\" space json-value)* space "
                              "\"]\") space");
@@ -656,12 +644,10 @@ void add_json_rules(const common_grammar_builder& b) {
                              "json-null");
 }
 
-/* THE ARGUMENT OBJECT of the object family, in its dialect: JSON, or strings between the
- * declared delimiters and keys written bare. As llama.cpp's own Gemma 4 grammar does, it fixes
- * the syntax and leaves the values to the model: a tool's schema says what JSON a value must be,
- * and the dialect is not JSON, so the schema converter has nothing to say about it. Whitespace
- * goes where the dialect's writers put it -- after a separator and inside the brackets -- and
- * nowhere else. */
+/* The object family's argument object in its dialect: JSON, or strings between the declared
+ * delimiters and bare keys. Like llama.cpp's Gemma 4 grammar, it fixes the syntax and leaves
+ * values unconstrained, since a tool's schema describes JSON and the dialect is not JSON.
+ * Whitespace is allowed only after a separator and inside the brackets. */
 void add_object_rules(const common_grammar_builder& b, const ChatFormat& f) {
     const std::string& so = f.object_string_open;
     if (!so.empty())
@@ -672,10 +658,10 @@ void add_object_rules(const common_grammar_builder& b, const ChatFormat& f) {
         b.add_rule("obj-string", "\"\\\"\" ( [^\"\\\\] | \"\\\\\" ( [\"\\\\/ bfnrt] | \"u\" "
                                  "[0-9a-fA-F]{4} ) )* \"\\\"\"");
     b.add_rule("obj-number", "\"-\"? (\"0\" | [1-9] [0-9]*) (\".\" [0-9]+)? ([eE] [+-]? [0-9]+)?");
-    /* A dialect with strings of its own still gets a value in Python's quotes, `'...'`, which
-     * is how Gemma 4 writes arguments it was handed as JSON (measured). Refused, the model
-     * takes the next token the grammar allows -- a `-` -- and every such string becomes a
-     * number; the parser reads the quoted text verbatim but for an escaped quote. */
+    /* A dialect with its own strings also admits Python-quoted `'...'` values, which Gemma 4
+     * writes for arguments it was given as JSON. Without this the model takes the next allowed
+     * token, `-`, and the string becomes a number. The parser reads the quoted text verbatim
+     * except for an escaped quote. */
     const char* sq = so.empty() ? "" : " | obj-sqstring";
     if (!so.empty()) b.add_rule("obj-sqstring", "\"'\" ( [^'\\\\] | \"\\\\\" [^\\x00] )* \"'\"");
     b.add_rule("obj-value", std::string("obj-object | obj-array | obj-string") + sq +
@@ -728,6 +714,11 @@ G reasoning_expr(const ChatFormat& f, const std::vector& breaks) {
 
 }  /* namespace */
 
+bool chat_function_tool(const ojson& tool) {
+    return tool.is_object() && tool.contains("type") && tool.at("type") == "function" &&
+           tool.contains("function");
+}
+
 int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, ChatGrammar* out,
                         std::string* why) {
     *out = ChatGrammar{};
@@ -751,9 +742,7 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
     try {
         out->text = build_grammar([&](const common_grammar_builder& b) {
             for (const auto& tool : tools) {
-                if (!tool.is_object() || !tool.contains("type") || tool.at("type") != "function" ||
-                    !tool.contains("function"))
-                    continue;
+                if (!chat_function_tool(tool)) continue;
                 const auto& fn = tool.at("function");
                 auto schema = fn.contains("parameters") ? fn.at("parameters") : ojson::object();
                 b.resolve_refs(schema);
@@ -796,9 +785,7 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
             std::vector choices;
             bool typed = false;
             for (const auto& tool : tools) {
-                if (!tool.is_object() || !tool.contains("type") || tool.at("type") != "function" ||
-                    !tool.contains("function"))
-                    continue;
+                if (!chat_function_tool(tool)) continue;
                 const auto& fn = tool.at("function");
                 const std::string name = fn.at("name");
                 if (!req.only_tool.empty() && name != req.only_tool) continue;
@@ -824,11 +811,11 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
 
                 std::vector req_arms, opt_arms;
                 for (const auto& [pname, pschema] : properties.items()) {
-                    /* An optional argument no value satisfies -- `false`, or the `not` of a schema
-                     * every value satisfies, an Arktype or TypeBox `never` -- is one no call
-                     * writes, so it gets no arm; a model that writes it anyway reaches the
-                     * undeclared arm below. The template path does the same (vendor/patches/0012,
-                     * 0014); required, it goes through the schema and is refused there by name. */
+                    /* An optional argument no value satisfies (`false`, or the `not` of an
+                     * always-true schema, e.g. Arktype or TypeBox `never`) gets no arm; a model
+                     * that writes it reaches the undeclared arm. The template path does the same
+                     * (vendor/patches/0012, 0014). A required one goes through the schema and is
+                     * refused there by name. */
                     if (!required.count(pname) && info.unsatisfiable(pschema)) continue;
                     G value;
                     if (f.other_value != ChatValue::Json || info.resolves_to_string(pschema)) {
@@ -849,8 +836,8 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
                 }
                 std::vector any = req_arms;
                 any.insert(any.end(), opt_arms.begin(), opt_arms.end());
-                /* The generic arm for an undeclared name. A tool that declares no parameters
-                 * takes no arguments at all, so its arm is never reached and not emitted. */
+                /* The generic arm for an undeclared name; not emitted for a tool that declares
+                 * no parameters, since it takes no arguments. */
                 if (!any.empty()) {
                     G arm = wrap(seq({ wrap(seq({ lit(f.arg_prefix),
                                                   wrap(leaf(until_pattern({ name_end }))),
@@ -892,8 +879,8 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
             }
             b.add_rule("tool-call", render(calls));
             if (req.require_call) {
-                /* The calls and nothing after them: a complete grammar admits only the end of
-                 * the turn, so the reply stops at the last call's closer. */
+                /* Nothing after the calls: a complete grammar admits only the end of the turn,
+                 * so the reply stops at the last call's closer. */
                 std::vector root = whole_reply();
                 root.push_back(rule_ref("tool-call"));
                 b.add_rule("root", render(seq(std::move(root))));
diff --git a/core/text/chatfmt.h b/core/text/chatfmt.h
index b81ab275..43903b35 100644
--- a/core/text/chatfmt.h
+++ b/core/text/chatfmt.h
@@ -1,59 +1,51 @@
-/* chatfmt.h -- how a model spells a turn: reasoning, tool calls, arguments. As DATA.
+/* chatfmt.h -- how a model spells a turn (reasoning, tool calls, arguments), as data.
  *
- * Everything the engine knows about a model's reply syntax is in one plain struct, ChatFormat,
- * and everything that depends on that syntax is DERIVED from it: the streaming reply parser
- * (chatparse.h), the lazy tool-call grammar and the literal words that trigger it (below), and the
- * tokens the decoder must render as text so the parser can see the structure. A new model is
- * supported by stating its format once.
+ * Everything the engine knows about a model's reply syntax is in one struct, ChatFormat, and
+ * everything that depends on it is derived from it: the streaming reply parser (chatparse.h), the
+ * lazy tool-call grammar and its trigger words, and the tokens the decoder must render as text so
+ * the parser can see the structure.
  *
- * TWO PRODUCERS, IN ORDER OF PRECEDENCE.
+ * Two producers, in order of precedence:
  *
  *   1. The architecture plugin, through the optional `rad_arch_chat_format` export
- *      (abi/rad_builder.h). A plugin that knows its model's syntax says so and nothing is guessed.
+ *      (abi/rad_builder.h).
  *   2. Analysis of the chat template. llama.cpp's differential analyser renders the template with
  *      and without a reasoning block, a call and its arguments, and diffs the renders to find the
- *      delimiters (vendor/llama/common/chat-diff-analyzer.cpp). Its derived MARKERS are read here;
+ *      delimiters (vendor/llama/common/chat-diff-analyzer.cpp). Its derived markers are read here;
  *      its PEG parser is not used.
  *
- * If neither yields a format the parser can run, the model still chats -- the reply is content --
- * but a request that sends tools is refused, naming why. There is no second parser to fall back
- * to: a reply format the engine cannot describe is a reply it cannot read, and saying so at
- * admission is better than returning a call as prose.
+ * If neither yields a format the parser can run, the model still chats (the reply is content) but
+ * a request with tools is refused, naming why. There is no fallback parser.
  *
- * THE FAMILY THIS DESCRIBES is the tagged one, which covers every model this engine serves:
+ * Tagged family:
  *
  *   Qwen3.6 / Qwen3.8    \n\n\nVALUE\n\n
  *                        \n
  *   MiniCPM5             VALUE
  *
- * A call's name is written between a prefix and a suffix and it ends with its own close; each
- * argument is a name between a prefix and a suffix and a value ending at its own suffix; calls may
- * be wrapped one by one. Arguments are typed by the tool's JSON schema: a string-typed argument is
- * the raw text (optionally CDATA-wrapped), any other type is JSON, and text that does not parse as
- * JSON is taken raw -- a model writing into an XML tag writes Python as often as JSON.
+ * A call's name sits between a prefix and a suffix and the call ends with its own close; each
+ * argument is a name between a prefix and a suffix, then a value ending at its own suffix; calls
+ * may be wrapped one by one. Arguments are typed by the tool's JSON schema: a string-typed one is
+ * raw text (optionally CDATA-wrapped), any other type is JSON, and text that does not parse as
+ * JSON is taken raw, since models often write Python literals into a tag.
  *
- * THE OBJECT FAMILY writes a call as its name and one object holding the arguments
- * (ChatArgs::Object):
+ * Object family (ChatArgs::Object): a call is its name and one object holding the arguments.
  *
  *   Gemma 4              <|tool_call>call:NAME{key:<|"|>text<|"|>,n:3}
  *
- * The object is JSON or a dialect of it -- strings between two declared delimiters with their
- * text verbatim, keys written bare -- and the arguments a client receives are that object in
- * JSON. Here the values carry their own types, so no schema is consulted to read them; a bare
- * word that is no JSON literal or number is read as a string, as a typed argument that is not
- * JSON is in the tagged family.
+ * The object is JSON or a dialect of it (strings verbatim between two declared delimiters, bare
+ * keys), and the client receives it as JSON. Values carry their own types, so no schema is
+ * consulted; a bare word that is not a JSON literal or number is read as a string.
  *
- * The analyser also recognises formats outside these families (a JSON object per call with its
- * name inside it, call ids). For those chat_format_from_template keeps the reasoning split and
- * names why tool calls are refused, and a model that needs one gets it by adding the shape to the
- * parser, not by a fallback. */
+ * The analyser also recognises formats outside these families (a JSON object per call with the
+ * name inside it, call ids). For those, chat_format_from_template keeps the reasoning split and
+ * names why tool calls are refused; supporting one means adding the shape to the parser. */
 #pragma once
 #include "rad_internal.h"
 
 #include 
 
 #include 
-#include 
 #include 
 #include 
 
@@ -70,10 +62,10 @@ enum class ChatValue : uint32_t {
 
 /* Whether the reply starts inside a reasoning block. The numbering is the ABI's. */
 enum class ChatThink : uint32_t {
-    /* Search the rendered generation prompt for `reasoning_open`: whatever follows its first
-     * occurrence is the start of the reply's own text. A template that opens the block for the
-     * model (Qwen writes "\n" at the end of the prompt) and one that closes it again when
-     * thinking is off ("\n\n\n\n") are both read correctly this way. */
+    /* Search the rendered generation prompt for `reasoning_open`; what follows its first
+     * occurrence is the start of the reply's text. Handles both a template that opens the block
+     * for the model (Qwen ends the prompt with "\n") and one that closes it again when
+     * thinking is off ("\n\n\n\n"). */
     FromPrompt = 0,
     Always     = 1,  /* the reply is inside a reasoning block from its first byte */
     Never      = 2,  /* the model opens its own block, if any */
@@ -95,35 +87,34 @@ struct ChatFormat {
      * and the close ends it. */
     std::string reasoning_open;
     std::string reasoning_close;
-    /* Literals that end an UNCLOSED block when a call starts there. A model that forgets to close
-     * its reasoning and goes straight to a call must not have the call swallowed as reasoning.
-     * Must name the call opener (`call_open`) when non-empty. */
+    /* Literals that end an unclosed block when a call starts there, so a model that skips the
+     * close and goes straight to a call does not have the call read as reasoning. When non-empty,
+     * must include the call opener (`call_open`). */
     std::vector reasoning_breaks;
     ChatThink   reasoning_in_prompt = ChatThink::FromPrompt;
-    /* A block may also open later in the reply -- after the answer, between calls -- and is read
-     * as reasoning there; a close with no block open is dropped. Gemma 4 writes an empty block
-     * after its answer now and then, and a lone close. Needs `reasoning_open`. */
+    /* A block may also open later in the reply (after the answer, between calls) and is read as
+     * reasoning there; a close with no block open is dropped. Gemma 4 sometimes writes an empty
+     * block after its answer, or a lone close. Needs `reasoning_open`. */
     bool        reasoning_anywhere = false;
 
     /* ------------------------------------------------------------------ tool calls
      * `name_prefix` is what opens a call (after `call_open`, when there is one). Empty means the
      * format has no tool calls. */
-    std::string section_open, section_close;  /* around ALL calls; not read yet, must be empty */
-    /* Between two calls beyond whitespace. Tagged calls are self-delimiting, so this is empty;
-     * a JSON-array format would say ", ". Not read yet, must be empty. */
+    std::string section_open, section_close;  /* around all calls; not read yet, must be empty */
+    /* Between two calls, beyond whitespace (a JSON-array format would use ", "). Tagged calls are
+     * self-delimiting. Not read yet, must be empty. */
     std::string call_separator;
-    /* Around EACH call: "\n", "". When set, a call written without it --
-     * name_prefix alone -- is still read as a call, leniently (chatparse.h). */
+    /* Around each call: "\n", "". When set, a call written without it
+     * (name_prefix alone) is still read as a call (chatparse.h). */
     std::string call_open, call_close;
-    /* "\n". In the object family name_suffix may be empty: the name then ends
-     * where the object begins, at its `{`. */
+    /* "\n". In the object family name_suffix may be empty; the name then ends at
+     * the object's `{`. */
     std::string name_prefix, name_suffix;
     std::string call_end;                     /* "\n"; may be empty for an object */
 
-    /* How the arguments are written. Object: the arg_* fields below are empty, and these three
-     * describe the object's dialect -- a string delimiter besides JSON's `"`, between which the
-     * text is verbatim ("<|\"|>" twice for Gemma 4; empty for JSON strings only), and whether a
-     * key may be written bare. */
+    /* How the arguments are written. For Object the arg_* fields below are empty and these three
+     * describe the dialect: a string delimiter besides JSON's `"` with verbatim text between
+     * ("<|\"|>" twice for Gemma 4; empty for JSON strings only), and whether keys may be bare. */
     ChatArgs    args_form = ChatArgs::Tagged;
     std::string object_string_open, object_string_close;
     bool        object_bare_keys = false;
@@ -135,13 +126,13 @@ struct ChatFormat {
 
     ChatValue   string_value = ChatValue::Cdata;  /* a string-typed argument: Raw or Cdata */
     ChatValue   other_value  = ChatValue::Json;   /* any other type: Json */
-    /* One newline at each end of a value is punctuation: the template writes the value on its own
-     * lines, and exactly the first and last newline belong to the tags. A tag that ends with its
-     * newline (Qwen's `>\n`) has written the first one already, and the value starts after it. */
+    /* One newline at each end of a value belongs to the tags, since the template writes the
+     * value on its own lines. A tag that ends with its newline (Qwen's `>\n`) has already
+     * consumed the first one. */
     bool        value_newlines = true;
 
-    /* The literal words that start constrained decoding of a call. Empty means no lazy grammar:
-     * the reply is unconstrained and the parser reads whatever arrives. */
+    /* Literal words that start constrained decoding of a call. Empty means no lazy grammar: the
+     * reply is unconstrained. */
     std::vector triggers;
 
     bool has_reasoning() const { return !reasoning_close.empty(); }
@@ -150,22 +141,22 @@ struct ChatFormat {
 };
 
 /* Can the streaming parser run this format? RAD_OK, or RAD_E_UNSUPPORTED with *why naming the
- * field. A format with no tool calls is valid (reasoning split only); a format with tool calls
- * must describe them completely enough that every delimiter is unambiguous. */
+ * field. A format without tool calls is valid (reasoning split only); one with tool calls must
+ * make every delimiter unambiguous. */
 int chat_format_check(const ChatFormat& f, std::string* why);
 
-/* The plugin's declaration, copied out of the ABI struct. Fields past the plugin's
- * `struct_size` read as their zero. Returns RAD_E_INVAL with *why when the struct is unusable. */
+/* Copy the plugin's declaration out of the ABI struct. Fields past the plugin's `struct_size`
+ * read as zero. RAD_E_INVAL with *why when the struct is unusable. */
 int chat_format_from_abi(const RadChatFormat* in, ChatFormat* out, std::string* why);
 
 /* Derive the format from a chat template by the vendored differential analysis.
  *
- * RAD_OK with *out filled. A template whose tool calls the analysis found but this family cannot
- * express still yields its reasoning split, with the tool fields empty and *tools_refused saying
- * why -- the model chats, and a request with tools is refused with that sentence. RAD_E_UNSUPPORTED
- * with *why when the template routes to one of llama.cpp's hand-written handlers, whose formats
- * the analysis does not describe at all; RAD_E_FORMAT when the template does not compile. An
- * empty source is the ChatML fallback, which has neither reasoning nor calls. */
+ * RAD_OK with *out filled. If the analysis finds tool calls this family cannot express, the
+ * reasoning split is still returned with the tool fields empty and *tools_refused saying why;
+ * requests with tools are then refused with that sentence. RAD_E_UNSUPPORTED with *why when the
+ * template routes to one of llama.cpp's hand-written handlers, which the analysis does not
+ * describe; RAD_E_FORMAT when the template does not compile. An empty source is the ChatML
+ * fallback, which has neither reasoning nor calls. */
 int chat_format_from_template(const std::string& jinja, const std::string& bos,
                               const std::string& eos, ChatFormat* out,
                               std::string* tools_refused, std::string* why);
@@ -175,21 +166,19 @@ std::string chat_format_describe(const ChatFormat& f);
 
 /* ================================================================== grammar
  *
- * The GBNF that constrains a reply to the format, generated from the description. For a tool
- * request it is LAZY: the reply is free until one of `triggers` appears, and from there the
- * grammar admits the call syntax with each argument constrained by its schema. For a response
- * format, and for a request that requires a call, it is the whole reply. Rule names and structure
- * follow the vendored generator so the two produce the same grammar for a template-analysed
- * format. */
+ * The GBNF that constrains a reply to the format. For a tool request it is lazy: the reply is free
+ * until one of `triggers` appears, then the grammar admits the call syntax with each argument
+ * constrained by its schema. For a response format, or a request that requires a call, it covers
+ * the whole reply. Rule names and structure follow the vendored generator, so both produce the
+ * same grammar for a template-analysed format. */
 struct ChatGrammarRequest {
     const nlohmann::ordered_json* tools = nullptr;        /* the request's tools, or null */
     const nlohmann::ordered_json* json_schema = nullptr;  /* a response format's schema, or null */
     std::string generation_prompt;
     bool        parallel_tool_calls = true;
     bool        extract_reasoning = true;  /* reasoning_format != "none" */
-    /* tool_choice "required" or a named function: the grammar is the whole reply rather than lazy,
-     * the reasoning block and then the calls with nothing after them, and `only_tool` (when set)
-     * narrows the calls to that one function. */
+    /* tool_choice "required" or a named function: the grammar covers the whole reply (reasoning,
+     * then calls, nothing after), and `only_tool` when set restricts calls to that function. */
     bool        require_call = false;
     std::string only_tool;
 };
@@ -200,15 +189,18 @@ struct ChatGrammar {
     std::vector trigger_words;
 };
 
+/* A tool the grammar and the reply parser both read, {"type":"function","function":{...}}; both
+ * skip any other. */
+bool chat_function_tool(const nlohmann::ordered_json& tool);
+
 /* RAD_OK, or RAD_E_INVAL with *why when a tool or schema cannot be expressed. */
 int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, ChatGrammar* out,
                         std::string* why);
 
-/* The markers the decoder must render as text for the parser to see them: a format built from
- * control tokens reaches the parser with its structure gone otherwise, because the decoder
- * suppresses control tokens. Every non-empty delimiter, whitespace-trimmed, deduplicated, in the
- * order the vendored analyser lists them -- a marker that is not a single token is harmless, the
- * decoder only compares it with the spellings of control tokens. */
+/* The markers the decoder must render as text so the parser sees them; the decoder otherwise
+ * suppresses control tokens, and a format built from them would lose its structure. Every
+ * non-empty delimiter, whitespace-trimmed and deduplicated, in the vendored analyser's order. A
+ * multi-token marker is fine: the decoder only compares markers with control-token spellings. */
 std::vector chat_format_markers(const ChatFormat& f);
 
 }  /* namespace rad */
diff --git a/core/text/chatparse.cpp b/core/text/chatparse.cpp
index 1d2dd59b..d65c1c1d 100644
--- a/core/text/chatparse.cpp
+++ b/core/text/chatparse.cpp
@@ -1,14 +1,15 @@
 #include "text/chatparse.h"
 #include "text/chatfmt.h"
 
-/* Bind time only: the schema resolution that decides which arguments are strings. The same
- * function the grammar generator uses, so the parser and the grammar never disagree about a
- * type. Nothing from vendor/ runs while a reply is being read. */
+/* Bind time only: the schema resolution that decides which arguments are strings. The grammar
+ * generator uses the same function, so parser and grammar agree on every type. Nothing from
+ * vendor/ runs while a reply is read. */
 #include "llama/common/json-schema-to-grammar.h"
 
 #include 
 
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -29,15 +30,14 @@ inline bool is_blank(unsigned char c) { return c == ' ' || c == '\n' || c == '\r
 
 /* ================================================================== delimiter automaton
  *
- * A deterministic Aho-Corasick automaton over a handful of delimiters. The state is the longest
- * suffix of the text scanned so far that is a prefix of some delimiter, so its depth is exactly
- * how many trailing bytes might still become one -- the bytes a streaming scan must hold -- and a
- * state whose string IS a delimiter is a match.
+ * A deterministic Aho-Corasick automaton over a few delimiters. The state is the longest suffix
+ * of the scanned text that is a prefix of some delimiter, so its depth is the number of trailing
+ * bytes a streaming scan must hold, and a state whose string is a delimiter is a match.
  *
- * That last step is exact only because chat_format_check refuses delimiter sets in which one
- * delimiter occurs inside another at a non-zero offset. Then a match ends at the first byte where
- * any delimiter completes, and no earlier-starting match can still be in progress: the automaton
- * reports matches in the order of their START, which is the order the grammar reads them in. */
+ * Reporting matches this way is exact only because chat_format_check refuses delimiter sets in
+ * which one delimiter occurs inside another at a non-zero offset. A match then ends at the first
+ * byte where any delimiter completes with no earlier-starting match in progress, so matches come
+ * out in start order, the order the grammar reads them. */
 class Dfa {
 public:
     void build(const std::vector& pats) {
@@ -132,19 +132,18 @@ private:
  * format's grammar accepts as a JSON-typed argument, quirks included, because the answer decides
  * whether the argument is typed or text:
  *
- *   * no whitespace before the value, any whitespace after it and inside it;
- *   * a number may not be followed by a character that could have continued it -- `01`, `1.`,
- *     `1-` are not numbers -- while `true` and `null` may be followed by anything;
- *   * a raw control character fails a string, as the schema's string rule refuses one and JSON
- *     has none: a client's JSON parser rejects a raw newline in a string. Any escape but the
- *     JSON ones fails it too.
+ *   * no whitespace before the value, any whitespace after and inside it;
+ *   * a number may not be followed by a character that could have continued it (`01`, `1.`, `1-`
+ *     are not numbers), while `true` and `null` may be followed by anything;
+ *   * a raw control character or a non-JSON escape fails a string, as the schema's string rule
+ *     does (a client's JSON parser rejects a raw newline in a string).
  *
- * A value accepted here is still checked whole by a JSON parser before it is written as JSON
- * (json_value_done): the grammar admits a few spellings a client cannot read.
+ * An accepted value is still checked whole by a JSON parser before it is written as JSON
+ * (json_value_done), since the grammar admits a few spellings a client cannot read.
  *
- * push() answers More while the bytes are still a JSON value or its trailing whitespace, Fail at
- * the first byte that cannot be, and Done at the first byte after a complete value -- which is
- * NOT consumed. */
+ * push() returns More while the bytes are still a JSON value or its trailing whitespace, Fail at
+ * the first byte that cannot be, and Done at the first byte after a complete value, which is not
+ * consumed. */
 class JsonScan {
 public:
     enum Res : uint8_t { More, Fail, Done };
@@ -305,8 +304,8 @@ private:
 /* ================================================================== JSON text helpers */
 
 /* A string's JSON encoding without its quotes, byte for byte what nlohmann::json::dump writes:
- * the two-character escapes where JSON has one, \u00XX in lower-case hex for the other control
- * characters, and everything else -- DEL and UTF-8 included -- verbatim. */
+ * two-character escapes where JSON has one, \u00XX in lower-case hex for other control
+ * characters, and everything else (DEL and UTF-8 included) verbatim. */
 void json_escape_into(std::string& out, const char* p, size_t n) {
     static const char hex[] = "0123456789abcdef";
     const char* run = p;
@@ -340,8 +339,8 @@ std::string json_quote(std::string_view s) {
     return out;
 }
 
-/* How many trailing bytes of `s` from `from` on form an unfinished UTF-8 sequence. A delta
- * becomes a JSON string on the wire, and half a code point there is a malformed payload. */
+/* How many trailing bytes of `s` (from `from` on) form an unfinished UTF-8 sequence. A delta
+ * becomes a JSON string on the wire, where half a code point is malformed. */
 size_t utf8_tail(const std::string& s, size_t from) {
     const size_t n = s.size();
     for (size_t back = 1; back <= 3 && back <= n - from; ++back) {
@@ -356,8 +355,8 @@ size_t utf8_tail(const std::string& s, size_t from) {
     return 0;
 }
 
-/* The value transforms the format's grammar applies, on a whole value. Used for values short
- * enough to be held entire and for the held ends of long ones. */
+/* The grammar's value transforms, on a whole value: used for values short enough to hold entire
+ * and for the held ends of long ones. */
 std::string_view strip_leading_newline(std::string_view v) {
     if (!v.empty() && v.front() == '\n') v.remove_prefix(1);
     else if (v.size() >= 2 && v[0] == '\r' && v[1] == '\n') v.remove_prefix(2);
@@ -378,16 +377,10 @@ constexpr std::string_view kCdClose = "]]>";
 constexpr std::string_view kFenceOpen  = "```json";
 constexpr std::string_view kFenceClose = "```";
 
-/* A CDATA section is punctuation, not content, and its two ends are stripped independently. A
- * value still arriving holds back what could yet become the opener, and a trailing `]` or `]]`
- * that could be the start of the closer. */
-void unwrap_cdata(std::string_view& v, bool partial) {
-    if (v.size() < kCdOpen.size()) {
-        if (partial && !v.empty() && kCdOpen.compare(0, v.size(), v) == 0) v = std::string_view();
-        return;
-    }
-    if (v.compare(0, kCdOpen.size(), kCdOpen) != 0) return;
-    v.remove_prefix(kCdOpen.size());
+/* A CDATA section is punctuation, not content; its two ends are stripped independently. A value
+ * still arriving holds back what could become the opener, and a trailing `]` or `]]` that could
+ * start the closer. */
+void strip_cdata_close(std::string_view& v, bool partial) {
     if (v.size() >= kCdClose.size() &&
         v.compare(v.size() - kCdClose.size(), kCdClose.size(), kCdClose) == 0) {
         v.remove_suffix(kCdClose.size());
@@ -399,8 +392,18 @@ void unwrap_cdata(std::string_view& v, bool partial) {
     v.remove_suffix(hold);
 }
 
-/* The name of an argument, as the grammar reads it: one leading whitespace character and every
- * trailing one are not part of it. */
+void unwrap_cdata(std::string_view& v, bool partial) {
+    if (v.size() < kCdOpen.size()) {
+        if (partial && !v.empty() && kCdOpen.compare(0, v.size(), v) == 0) v = std::string_view();
+        return;
+    }
+    if (v.compare(0, kCdOpen.size(), kCdOpen) != 0) return;
+    v.remove_prefix(kCdOpen.size());
+    strip_cdata_close(v, partial);
+}
+
+/* An argument name as the grammar reads it: without one leading whitespace character and all
+ * trailing ones. */
 std::string_view trim_arg_name(std::string_view v) {
     if (!v.empty() && is_ws((unsigned char)v.front())) v.remove_prefix(1);
     while (!v.empty() && is_ws((unsigned char)v.back())) v.remove_suffix(1);
@@ -414,28 +417,28 @@ std::string_view trim_trailing_ws(std::string_view v) {
 
 /* ================================================================== an argument value
  *
- * The bytes of one value as the delimiters bound it, turned into its JSON encoding in the
- * arguments object. Two encodings: a STRING (quoted, escaped) and RAW JSON text, which is either
- * a value that parsed as JSON or a non-string argument that did not.
+ * One value's bytes, as the delimiters bound them, turned into its JSON encoding in the arguments
+ * object: a string (quoted, escaped), or raw JSON text (a value that parsed as JSON, or a
+ * non-string argument that did not).
  *
- * A NON-STRING ARGUMENT THAT DID NOT PARSE IS MADE JSON, never passed through: the arguments
- * object is the one thing a client parses, and a single bare token in it makes the whole call
- * unreadable -- the server then cannot report it as a call at all. The grammar admits text for a
- * typed argument, and what these models write there is Python: `True`, `False`, `None`, and
- * single-quoted containers. A scalar is held while it could still be a Python literal -- `True`
- * as true, `False`, `None` as null -- or a JSON number or literal, up to kScalar bytes, and is
- * then written as that; anything else, or anything longer, streams as a JSON string of its text.
- * An empty one is null. A CONTAINER -- its first byte after at most a few blanks is `[` or `{` --
- * is held whole, because whether it is JSON once its quotes are normalised to double ones and its
- * Python literals to JSON's is known only at its end: a trailing comma, a bare word, an escape
- * JSON has not or a missing bracket each leave it no JSON, and then it is a JSON string of its
- * text. A value the reply was cut off inside is written as it arrived: it has no end to read it
- * to, and the call it is in is not complete. A value the JSON reader ACCEPTED (json_value_done)
- * is written as it is.
+ * A non-string argument that did not parse is converted to JSON, never passed through: one bare
+ * token makes the client's arguments object unparseable, and the call cannot be reported at all.
+ * The grammar admits text for a typed argument, and models write Python there: `True`, `False`,
+ * `None` and single-quoted containers.
  *
- * The transforms touch only the ends of a value -- one newline at each end, the CDATA opener and
- * closer -- so the middle streams straight through and only a short head and tail are held: the
- * first kHead bytes until the head is decided, and the last kTail after that. */
+ *   * Scalar: held while it could still be a Python literal (`True` as true, `False`, `None` as
+ *     null) or a JSON number or literal, up to kScalar bytes, then written as that. Anything
+ *     else, or longer, streams as a JSON string of its text. An empty value is null.
+ *   * Container (first byte after at most four blanks is `[` or `{`): held whole, because only at
+ *     its end is it known whether it is JSON once its quotes and Python literals are normalised.
+ *     If it is not, it becomes a JSON string of its text.
+ *   * A value the reply was cut off inside is written as it arrived, since there is no end to
+ *     read and its call is incomplete. A value the JSON scanner accepted (json_value_done) is
+ *     written as is.
+ *
+ * The transforms touch only the ends (one newline at each end, the CDATA opener and closer), so
+ * the middle streams through and only the first kHead bytes (until the head is decided) and the
+ * last kTail are held. */
 class ValueOut {
 public:
     enum Mode : uint8_t { String, Raw };
@@ -484,18 +487,7 @@ public:
             if (cdata_) unwrap_cdata(v, partial);
         } else {
             if (trail_) v = strip_trailing_newline(v);
-            if (opened_) {
-                if (v.size() >= kCdClose.size() &&
-                    v.compare(v.size() - kCdClose.size(), kCdClose.size(), kCdClose) == 0) {
-                    v.remove_suffix(kCdClose.size());
-                } else if (partial) {
-                    size_t hold = 0;
-                    while (hold + 1 < kCdClose.size() && v.size() > hold &&
-                           v[v.size() - 1 - hold] == ']')
-                        ++hold;
-                    v.remove_suffix(hold);
-                }
-            }
+            if (opened_) strip_cdata_close(v, partial);
         }
         emit(v.data(), v.size(), out);
         if (mode_ == Raw && !json_) {
@@ -660,10 +652,10 @@ private:
 
 /* ================================================================== the answer text
  *
- * Content is trimmed at the end: trailing spaces and newlines, then one turn terminator. Trimming
- * the END of a stream means holding what might be the end -- the trailing whitespace, and a
- * terminator or the part of one that has arrived -- until something that is not whitespace
- * follows it. The terminator automaton tracks the longest suffix that could still become one. */
+ * Content is trimmed at the end: trailing spaces and newlines, then one turn terminator. On a
+ * stream that means holding the trailing whitespace and any whole or partial terminator until a
+ * non-whitespace byte follows. The terminator automaton tracks the longest suffix that could
+ * still become one. */
 class ContentOut {
 public:
     void init(const Dfa* terms, const std::vector* list) { terms_ = terms; list_ = list; }
@@ -729,43 +721,43 @@ struct ReplyFormat::Impl {
     /* Each tag split into its core and the whitespace around it that is optional to match. */
     std::string open_core, open_trail, close_core, close_trail, ns_core, ns_trail, end_core,
                 end_trail, co_core, co_trail;
-    /* What begins a call in content. The first is the format's own opener: call_open's core, or
+    /* What begins a call in content. First the format's own opener: call_open's core, or
      * name_prefix when calls are not wrapped. A wrapped format also takes name_prefix alone,
-     * second: a model writes the call without its wrapper often enough that its calls must not
-     * be lost to it, and a wrapper written without its trailing whitespace is read too. */
+     * second, since models often write a call without its wrapper; a wrapper written without
+     * its trailing whitespace is read too. */
     std::vector openers;
     std::string name_end;     /* what ends an argument name */
-    /* The same two, whitespace-trimmed. A loose call is one the grammar never opened, so the
-     * model wrote it unconstrained, and its argument tags are read with the whitespace around
-     * them optional -- as its name and its close are. */
+    /* The same two, whitespace-trimmed. A loose call is one the grammar never opened, so it was
+     * written unconstrained; its argument tags, like its name and close, are read with their
+     * surrounding whitespace optional. */
     std::string name_end_core, value_core;
-    /* call_close's core, when it can be told apart from what else may follow inside a call: a
-     * wrapped call whose own close is missing is ended by its wrapper's. */
+    /* call_close's core, when distinct from what else may follow inside a call, so a wrapped
+     * call missing its own close is ended by its wrapper's. */
     std::string cc_core;
     Dfa think, think_breaks, text, arg_name, value, junk, arg_name_loose, value_loose;
     size_t longest = 0;       /* the longest delimiter */
 
-    /* THE OBJECT FAMILY. `object`: a call's arguments are one object; `ns_object`: the object's
-     * own `{` is what ends the name (name_suffix empty), and ns_core is "{". */
+    /* Object family. `object`: a call's arguments are one object. `ns_object`: the object's own
+     * `{` ends the name (name_suffix empty), and ns_core is "{". */
     bool object = false, ns_object = false;
-    /* Where a key or a value may begin, besides the object's punctuation: the dialect string's
-     * opener, and the call's close and end -- a reply that leaves its object unclosed writes them
-     * there. Read anchored, by their first bytes (chat_format_check keeps them apart). */
+    /* Where a key or value may begin, besides the object's punctuation: the dialect string's
+     * opener, and the call's close and end (written there by a reply that leaves its object
+     * unclosed). Matched anchored, by first byte; chat_format_check keeps them distinct. */
     enum : uint8_t { LitString, LitClose, LitEnd };
     std::vector obj_lits;
     std::vector     obj_lit_kind;
     /* A dialect string runs to its close. A bare value ends at `,` `}` `]` and a bare key at `:`
-     * `,` `}` -- patterns 0..2 -- or at the call's close or end, which follow at the indices
-     * below (-1: none). */
+     * `,` `}` (patterns 0..2), or at the call's close or end, whose pattern indices are below
+     * (-1: none). */
     Dfa obj_str, obj_bare, obj_key;
-    /* A value the model opened with a plain `"` -- or `'` (obj_sqstr) -- in a dialect that has
-     * strings of its own: read as that dialect's strings are, verbatim, to a quote the object's
-     * syntax goes on after. Patterns: the quote, the escaped quote, the dialect's string close,
-     * the call's close (if any). */
+    /* A value opened with a plain `"` (or `'`, obj_sqstr) in a dialect with strings of its own:
+     * read verbatim, like the dialect's strings, up to a quote after which the object's syntax
+     * continues. Patterns: the quote, the escaped quote, the dialect's string close, the call's
+     * close (if any). */
     Dfa obj_qstr, obj_sqstr;
     int bare_cc = -1, bare_ce = -1, key_cc = -1, key_ce = -1;
 
-    /* REASONING ANYWHERE: content is scanned for a later block's opener and a stray close too,
+    /* reasoning_anywhere: content is also scanned for a later block's opener and a stray close,
      * after the call openers (text_think) or alone when the request has no calls (think_only). */
     Dfa text_think, think_only;
 };
@@ -931,9 +923,9 @@ ReasoningMarkers ReplyParser::reasoning() const {
     if (!F.f.has_reasoning()) return m;
     m.open  = F.open_core;
     m.close = F.close_core;
-    /* `tail` starts at the opener when the prompt holds one, and a prompt that also closed the
-     * block -- thinking turned off -- leaves the reply after it. With no opener at all the stream
-     * starts in the block (after_lead). */
+    /* `tail` starts at the opener when the prompt holds one; a prompt that also closed the block
+     * (thinking off) leaves the reply after it. With no opener the stream starts in the block
+     * (after_lead). */
     const std::string& t = impl_->tail;
     m.starts_open = F.open_core.empty() ||
                     (!t.empty() && t.find(F.close_core, F.open_core.size()) == std::string::npos);
@@ -945,9 +937,7 @@ ReasoningMarkers ReplyParser::reasoning() const {
 static int bind_tools(const ReplyFormat::Impl& F, const ojson& tools, ReplyParser::Impl* P,
                       std::string* why) {
     for (const auto& tool : tools) {
-        if (!tool.is_object() || !tool.contains("type") || tool.at("type") != "function" ||
-            !tool.contains("function"))
-            continue;
+        if (!chat_function_tool(tool)) continue;
         try {
             const auto& func = tool.at("function");
             Tool t;
@@ -961,8 +951,8 @@ static int bind_tools(const ReplyFormat::Impl& F, const ojson& tools, ReplyParse
             info.resolve_refs(params);
             std::vector optional;
             for (const auto& [pname, pschema] : properties.items()) {
-                /* An optional argument no value satisfies has no arm in the grammar, which reads
-                 * it by the undeclared arm, as text (chatfmt.cpp); so does the parser. */
+                /* An optional argument no value satisfies has no grammar arm and is read by the
+                 * undeclared arm as text (chatfmt.cpp); the parser does the same. */
                 if (!required.count(pname) && info.unsatisfiable(pschema)) continue;
                 Param p;
                 p.typed = F.f.other_value == ChatValue::Json && !info.resolves_to_string(pschema);
@@ -973,9 +963,9 @@ static int bind_tools(const ReplyFormat::Impl& F, const ojson& tools, ReplyParse
                 } else {
                     optional.push_back(pname);
                 }
-                /* A name the argument's own delimiter could end early would be read as a
-                 * different name. An object's keys are delimited by its own punctuation, and
-                 * one that holds it is written as a string. */
+                /* A name its own delimiter could end early would be read as a different name.
+                 * Object keys are delimited by the object's punctuation instead, and a key
+                 * containing it is written as a string. */
                 const std::string probe = pname + F.name_end;
                 if (!F.object && probe.find(F.name_end) != pname.size()) {
                     *why = "parameter '" + pname + "' of tool '" + t.name + "' contains '" +
@@ -1121,8 +1111,8 @@ struct ReplyStream::Impl {
         }
     }
 
-    /* What content is scanned with: the call openers when calls are on, then -- reasoning
-     * anywhere -- a later block's opener and a stray close. Null: content is every byte. */
+    /* What content is scanned with: the call openers when calls are on, then (reasoning_anywhere)
+     * a later block's opener and a stray close. Null when every byte is content. */
     const Dfa* text_dfa = nullptr;
     size_t     n_open = 0;
 
@@ -1144,12 +1134,12 @@ struct ReplyStream::Impl {
     size_t      lpos = 0, trail = 0;
     /* a call being opened */
     St          origin = St::Text;
-    /* LOOSE: opened by what the format's grammar does not open a call with -- name_prefix alone,
-     * or call_open without its trailing whitespace. Such an opener is also ordinary text often
-     * enough ("the `` syntax") that it becomes a call only once what follows the
-     * name tag is an argument or the call's close; until then it is held, and if it is not a
-     * call it is content, as the grammar says, and the reply is still within it. WRAPPED: the
-     * call was opened with call_open, so its close is followed by call_close. */
+    /* `loose`: opened by something the grammar does not open a call with (name_prefix alone, or
+     * call_open without its trailing whitespace). Such an opener is also ordinary text often
+     * enough ("the `` syntax") that it becomes a call only once an argument or the
+     * call's close follows the name tag. Until then it is held; if it is not a call it is
+     * content, as the grammar says, and the reply stays strict. `wrapped`: opened with
+     * call_open, so its close is followed by call_close. */
     bool        loose = false, wrapped = false;
     size_t      tag_end = 0;            /* where a loose call's name tag ends in `att` */
     bool        name_lt = false;        /* a loose call's argument name holds a '<' */
@@ -1168,23 +1158,23 @@ struct ReplyStream::Impl {
     size_t      vs_pos = 0;
     bool        fenced = false;
 
-    /* THE ARGUMENT OBJECT being read: its open brackets, whether a key (rather than a value) is
-     * being read, a separator read but not yet written -- it is written only once the next
-     * member shows the object goes on, so a trailing one never reaches the JSON -- whether the
-     * container was just opened, and whether a key's `:` went out with no value yet. */
+    /* The argument object being read: its open brackets; whether a key (not a value) is being
+     * read; a separator read but not yet written (written only once the next member shows the
+     * object continues, so a trailing one never reaches the JSON); whether the container was
+     * just opened; and whether a key's `:` went out with no value yet. */
     std::vector ostack;
     bool        okey = false, ocomma = false, ofirst = false, vpending = false;
-    /* A bare value's first bytes, to tell at its end whether it was a JSON number or literal --
-     * which the grammar admits -- or a word read as a string, which it does not. */
+    /* A bare value's first bytes, to tell at its end whether it was a JSON number or literal
+     * (which the grammar admits) or a word read as a string (which it does not). */
     std::string bare_txt;
-    /* A JSON string's escape being read -- the backslash, and a "u" escape's four hex digits,
-     * in vheld -- and a high surrogate's escape, held until the low one shows it is a pair. */
+    /* A high surrogate's escape, held until the low one shows it is a pair. The escape being
+     * read (the backslash and a "u" escape's four hex digits) is in vheld. */
     std::string jhi;
-    /* INSIDE A STRING: its trailing run of whitespace, closing brackets and quotes, held -- the
-     * brackets are the object's own if the call's close follows (srun) -- the quotes and
-     * backticks it has written (nq, nb), the bytes after a plain quote while they decide what it
-     * was (qtail), and how a plain-quoted value writes its quotes: 0 not yet seen, 1 as \" (one
-     * is unescaped), 2 as they are. */
+    /* Inside a string: `srun` holds its trailing run of whitespace, closing brackets and quotes
+     * (the brackets are the object's own if the call's close follows); `nq`, `nb`, `ns` count the
+     * double quotes, backticks and single quotes it has written; `qtail` holds the bytes after a
+     * plain quote while they decide what it was; `qmode` is how a plain-quoted value writes its
+     * quotes: 0 not yet seen, 1 as \" (one is unescaped), 2 as they are. */
     std::string srun, qtail;
     size_t      nq = 0, nb = 0, ns = 0;
     uint8_t     qmode = 0;
@@ -1194,9 +1184,9 @@ struct ReplyStream::Impl {
     size_t sent_r = 0, sent_c = 0, sent_a = 0;
     int    cur = -1;                    /* the channel last published: 0 r, 1 c, 2 args */
 
-    /* bytes to read again, ahead of the rest. Bytes read again are always the last ones read,
-     * so each segment knows where its first byte is in the stream: the generation prompt's tail,
-     * then the reply. */
+    /* Bytes to read again, ahead of the rest. They are always the last bytes read, so each
+     * segment knows its first byte's position in the stream (the generation prompt's tail, then
+     * the reply). */
     struct Seg { const char* p; size_t n; size_t at; };
     std::vector        stack;
     const char*             seg_p = nullptr;   /* the segment being read */
@@ -1206,6 +1196,7 @@ struct ReplyStream::Impl {
     size_t here(const char* p) const { return seg_at + (size_t)(p - seg_p); }
     std::deque owned;
     std::string             refeed;
+    size_t                  reread = 0;        /* every byte ever queued in refeed */
 
     void lenient() { strict = false; }
 
@@ -1324,7 +1315,10 @@ struct ReplyStream::Impl {
         return p;
     }
 
-    void read_again(std::string_view bytes) { refeed.append(bytes); }
+    void read_again(std::string_view bytes) {
+        refeed.append(bytes);
+        reread += bytes.size();
+    }
 
     /* ------------------------------------------------------------ calls */
 
@@ -1373,8 +1367,8 @@ struct ReplyStream::Impl {
         }
     }
 
-    /* The whitespace a loose opener may be followed by: whatever sorts at or below a space, as a
-     * model's stray control characters do. */
+    /* Whitespace after a loose opener: any byte at or below a space, which covers a model's stray
+     * control characters. */
     static bool loose_ws(unsigned char c) { return c <= ' '; }
 
     /* Not a call after all: the opener's first byte is text of the region it was found in, and
@@ -1432,14 +1426,13 @@ struct ReplyStream::Impl {
 
     /* ------------------------------------------------------------ the argument object
      *
-     * The object of the object family, read as it streams and written as JSON as it is read:
-     * brackets and separators as they come, a key as soon as its `:` shows it is one, a string
-     * as its bytes arrive, and a bare value as the tagged family writes a typed one (ValueOut,
-     * Raw): held while it could still be a literal or a number, else a string. What the dialect
-     * spells otherwise -- its string delimiters, its bare keys -- is respelled; what leaves it
-     * -- a missing separator, a trailing one, a bracket of the wrong kind, an object the call's
-     * close cuts off -- is repaired locally and said so (strict). The arguments a closed call
-     * reports are JSON whatever was written. */
+     * The object family's argument object, read as it streams and written as JSON as it is read:
+     * brackets and separators as they come, a key once its `:` shows it is one, a string as its
+     * bytes arrive, and a bare value like a typed tagged value (ValueOut, Raw): held while it
+     * could still be a literal or a number, else a string. Dialect spellings (string delimiters,
+     * bare keys) are respelled. Departures from the dialect (a missing or trailing separator, a
+     * mismatched bracket, an object cut off by the call's close) are repaired locally and clear
+     * strict(). A closed call's arguments are always JSON. */
 
     void obj_out(std::string_view s) {
         if (s.empty()) return;
@@ -1512,8 +1505,7 @@ struct ReplyStream::Impl {
 
     /* A bare value ended: one that is no JSON number or literal was read by the recovery rule. */
     void bare_done() {
-        std::string_view v(bare_txt);
-        while (!v.empty() && is_ws((unsigned char)v.back())) v.remove_suffix(1);
+        const std::string_view v = trim_trailing_ws(bare_txt);
         const bool json = bare_txt.size() < kBareKeep && !v.empty() &&
                           (v == "true" || v == "false" || v == "null" ||
                            ((v[0] == '-' || (v[0] >= '0' && v[0] <= '9')) &&
@@ -1549,9 +1541,10 @@ struct ReplyStream::Impl {
         else end_core_done();
     }
 
-    /* A JSON string's text goes out as it is, its escapes checked: one JSON has not is the
-     * backslash and the letter as text, a raw control character is escaped, and a surrogate
-     * escape that is not half of a pair is U+FFFD -- a client's JSON parser refuses all three. */
+    /* A JSON string's text goes out as is, with its escapes checked, since a client's JSON parser
+     * refuses all three of: a non-JSON escape (written as the backslash and letter as text), a
+     * raw control character (escaped), and a surrogate escape that is not half of a pair
+     * (written as U+FFFD). */
     void jstr_char(const char* q, size_t n) {
         if (n == 0) return;
         if (!jhi.empty()) { lenient(); jhi.clear(); obj_out("\\ufffd"); }
@@ -1610,9 +1603,9 @@ struct ReplyStream::Impl {
         }
     }
 
-    /* Where the held run stops being text: the closers after it close every open bracket of the
-     * object, innermost first, as the model writes them before the call's close -- read from the
-     * end, the last closes the outermost. npos: they do not. */
+    /* Where the held run stops being text: the closers after that point close every open bracket
+     * of the object, innermost first, as a model writes them before the call's close (read from
+     * the end, the last closes the outermost). npos if they do not. */
     size_t run_cut() const {
         size_t i = srun.size(), k = 0;
         while (i > 0 && k < ostack.size()) {
@@ -1625,15 +1618,11 @@ struct ReplyStream::Impl {
         return k == ostack.size() && k > 0 ? i : std::string::npos;
     }
 
-    static bool starts(std::string_view a, std::string_view b) {
-        return a.size() >= b.size() && a.compare(0, b.size(), b) == 0;
-    }
-
     /* The call's close in a string whose held run closes the whole object: the model left the
-     * string open (measured: the close delimiter at p=0.86, `}` at p=0.08), and this is where
-     * the call ends -- as vLLM's and HF's Gemma 4 parsers end it, at the first `}`.
-     * The closers are the object's. A quote or backtick just before them that leaves the string
-     * with an odd count of its kind was the string's close, written in the wrong spelling. */
+     * string open (here it writes the close delimiter with p=0.86, `}` with p=0.08), and the call
+     * ends here, as vLLM's and HF's Gemma 4 parsers end it at the first `}`. The
+     * closers are the object's. A quote or backtick just before them that leaves an odd count of
+     * its kind in the string was the string's close in the wrong spelling. */
     void cut_begin() {
         const size_t cut = run_cut();
         if (cut == std::string::npos) { str_flush(); str_emit(F.cc_core.data(), F.cc_core.size()); return; }
@@ -1647,7 +1636,7 @@ struct ReplyStream::Impl {
         }
         str_emit(srun.data(), keep);
         srun.clear();
-        if (!jhi.empty()) jhi.clear();
+        jhi.clear();
         obj_out(okey ? "\":null" : "\"");
         vpending = false;
         ocomma = false;
@@ -1655,9 +1644,8 @@ struct ReplyStream::Impl {
         end_call();
     }
 
-    /* After a plain quote in a plain-quoted value: 0 not yet known, 1 it closed the value -- the
-     * object goes on with a member, an element, its closers and the call's close -- 2 it was
-     * text. */
+    /* After a plain quote in a plain-quoted value: 0 not yet known; 1 it closed the value (the
+     * object goes on with a member, an element, its closers or the call's close); 2 it was text. */
     int q_verdict() const {
         const std::string& q = qtail;
         if (q.size() > kLookKeep) return 2;
@@ -1670,8 +1658,8 @@ struct ReplyStream::Impl {
         const std::string& so = F.f.object_string_open;
         std::string_view r(q.data() + i, n - i);
         if (!F.cc_core.empty()) {
-            if (starts(r, F.cc_core)) return 1;
-            if (starts(F.cc_core, r)) return 0;
+            if (r.starts_with(F.cc_core)) return 1;
+            if (std::string_view(F.cc_core).starts_with(r)) return 0;
         }
         if (top == 0 || q[i] != ',') return 2;
         ++i;
@@ -1679,8 +1667,8 @@ struct ReplyStream::Impl {
         if (i == n) return 0;
         r = std::string_view(q.data() + i, n - i);
         const unsigned char c = (unsigned char)q[i];
-        if (starts(r, so)) return 1;
-        if (starts(so, r)) return 0;
+        if (r.starts_with(so)) return 1;
+        if (std::string_view(so).starts_with(r)) return 0;
         if (ostack[top - 1] == '{') {
             if (!(std::isalpha(c) || c == '_')) return 2;
             while (i < n && (std::isalnum((unsigned char)q[i]) || q[i] == '_')) ++i;
@@ -1713,9 +1701,8 @@ struct ReplyStream::Impl {
     }
 
     /* The core of call_end has matched. The whitespace the format writes after it is part of the
-     * tag, so the call closes when that has arrived too -- a reply that ends in between leaves the
-     * call open, as the grammar does -- and a reply that goes straight on without it has closed
-     * the call all the same. */
+     * tag, so the call closes once that arrives too (a reply that ends in between leaves the call
+     * open, as the grammar does); a reply that goes straight on without it still closes the call. */
     void end_core_done() {
         trail = 0;
         if (F.end_trail.empty() || loose) end_call();
@@ -1750,9 +1737,9 @@ struct ReplyStream::Impl {
         else after_loose_call();
     }
 
-    /* The wrapper's close inside a wrapped call, whose own close is missing: it ends the call
-     * and the wrapper both. Read leniently -- the grammar requires call_end first -- but as the
-     * close it is, or the next call's arguments would be read into this one. */
+    /* The wrapper's close inside a wrapped call whose own close is missing ends both the call and
+     * the wrapper. Lenient, since the grammar requires call_end first, but it must be read as a
+     * close or the next call's arguments would be read into this one. */
     void end_call_at_close() {
         lenient();
         end_call();
@@ -1848,6 +1835,11 @@ struct ReplyStream::Impl {
         return F.f.value_newlines && (ne.empty() || ne.back() != '\n');
     }
 
+    /* `lit` continues the literal held in lhold (lpos bytes) with `c`. */
+    bool extends(const std::string& lit, char c) const {
+        return lpos < lit.size() && lit[lpos] == c && lit.compare(0, lpos, lhold) == 0;
+    }
+
     void begin_value_out(ValueOut::Mode m, bool json = false) {
         val.begin(m, cdata(), lead_newline(), F.f.value_newlines, scratch, json);
     }
@@ -1861,20 +1853,13 @@ struct ReplyStream::Impl {
         st = St::ValText;
     }
 
-    /* A JSON-typed value that parsed and then met its suffix: the value is the JSON text and the
-     * whitespace after it. What a client's JSON parser takes is a little narrower than what
-     * JsonScan reads as the grammar's JSON -- a number past a double's range (`1e400`), an
-     * unpaired UTF-16 surrogate escape, a vertical tab or form feed after the value -- and such a
-     * value is read by the grammar's other arm, as text, so the arguments stay JSON. */
+    /* A JSON-typed value that parsed and then met its suffix: the JSON text and the whitespace
+     * after it. A client's JSON parser is slightly stricter than JsonScan's reading of the
+     * grammar's JSON (a number past a double's range such as `1e400`, an unpaired UTF-16
+     * surrogate escape, a vertical tab or form feed after the value). Such a value is read by the
+     * grammar's other arm, as text, so the arguments stay JSON. */
     void json_value_done(std::string_view text) {
-        if (!nlohmann::json::accept(text)) {
-            begin_value_out(ValueOut::Raw);
-            val.add(text.data(), text.size(), scratch);
-            val.finish(false, scratch);
-            flush_scratch();
-            return;
-        }
-        begin_value_out(ValueOut::Raw, /*json=*/true);
+        begin_value_out(ValueOut::Raw, /*json=*/nlohmann::json::accept(text));
         val.add(text.data(), text.size(), scratch);
         val.finish(false, scratch);
         flush_scratch();
@@ -2035,8 +2020,8 @@ struct ReplyStream::Impl {
             att.push_back(c);
             const std::string& ap = F.f.arg_prefix;
             const std::string& fc = F.end_core;
-            const bool a_ok = lpos < ap.size() && ap[lpos] == c && ap.compare(0, lpos, lhold) == 0;
-            const bool f_ok = lpos < fc.size() && fc[lpos] == c && fc.compare(0, lpos, lhold) == 0;
+            const bool a_ok = extends(ap, c);
+            const bool f_ok = extends(fc, c);
             if (!a_ok && !f_ok) { fail_attempt(); return p + 1; }
             lhold.push_back(c);
             ++lpos;
@@ -2051,9 +2036,9 @@ struct ReplyStream::Impl {
         }
 
         case St::OpenPeekArg: {
-            /* The first argument's name, which is where prose that merely looks like a call
-             * shows itself: a name that runs into a tag is no name. On one that closes, the call
-             * is read -- the bytes after the name tag replayed through the call itself. */
+            /* The first argument's name is where prose that only looks like a call shows itself:
+             * a name that runs into a tag is no name. Once the name closes, the call is read by
+             * replaying the bytes after the name tag through it. */
             const char c = *p;
             att.push_back(c);
             lhold.push_back(c);
@@ -2084,10 +2069,9 @@ struct ReplyStream::Impl {
             const std::string& ap = F.f.arg_prefix;
             const std::string& fc = F.end_core;
             const std::string& cc = F.cc_core;
-            const bool a_ok = lpos < ap.size() && ap[lpos] == c && ap.compare(0, lpos, lhold) == 0;
-            const bool f_ok = lpos < fc.size() && fc[lpos] == c && fc.compare(0, lpos, lhold) == 0;
-            const bool c_ok = wrapped && lpos < cc.size() && cc[lpos] == c &&
-                              cc.compare(0, lpos, lhold) == 0;
+            const bool a_ok = extends(ap, c);
+            const bool f_ok = extends(fc, c);
+            const bool c_ok = wrapped && extends(cc, c);
             if (!a_ok && !f_ok && !c_ok) {
                 lenient();
                 st = St::Junk;
@@ -2251,8 +2235,7 @@ struct ReplyStream::Impl {
             p = scan(F.obj_key, p, e, &hit, [this](const char* q, size_t n) { name.append(q, n); });
             if (hit < 0) return p;
             if (hit <= 2) {
-                std::string_view k(name);
-                while (!k.empty() && is_ws((unsigned char)k.back())) k.remove_suffix(1);
+                const std::string_view k = trim_trailing_ws(name);
                 if (k.empty()) lenient();
                 obj_sep();
                 std::string out = json_quote(k);
@@ -2321,9 +2304,9 @@ struct ReplyStream::Impl {
                 return p + 1;
             }
             if ((c == '"' || c == '\'') && !F.f.object_string_open.empty()) {
-                /* Measured on Gemma 4: such a quote -- `"`, or `'` as Python and JavaScript
-                 * write strings -- is followed by the text verbatim, or with only its quotes
-                 * escaped, never JSON's other escapes. */
+                /* Gemma 4 follows such a quote (`"`, or `'` as Python and JavaScript write
+                 * strings) with the text verbatim, or with only its quotes escaped, never with
+                 * JSON's other escapes. */
                 obj_sep();
                 vpending = false;
                 lenient();
@@ -2581,12 +2564,11 @@ struct ReplyStream::Impl {
         st = St::ArgName;
     }
 
-    /* The reply ended inside an argument name. A name is only a name once it is closed -- except
-     * that where the format writes nothing between a name and its value's own prefix
-     * (arg_name_suffix empty), the grammar's opening tag for a DECLARED argument is complete as
-     * soon as the declared name is: the reply `= again.size() ? fed - again.size() : 0);
+        };
+        /* The reply ended while a close was being decided: it was one. */
+        while (st == St::ObjQLook) {
+            q_done(true);
+            rerun();
         }
         if (st == St::ObjStr || st == St::ObjQStr) str_flush();
         while (in_loose_attempt()) {
             fail_attempt();
-            std::string again = std::move(refeed);
-            refeed.clear();
-            run(again, fed >= again.size() ? fed - again.size() : 0);
+            rerun();
         }
         switch (st) {
         case St::OpenWs: case St::OpenPrefix: case St::OpenName: case St::OpenTail:
@@ -2787,6 +2771,8 @@ std::string ReplyStream::content_with_open_call(std::string_view reply) const {
 
 bool ReplyStream::strict() const { return impl_->strict; }
 
+size_t ReplyStream::reread() const { return impl_->reread; }
+
 ReplyHeld ReplyStream::held() const {
     const Impl& m = *impl_;
     ReplyHeld h;
@@ -2795,9 +2781,9 @@ ReplyHeld ReplyStream::held() const {
     const size_t lhold = m.st == St::OpenPeekArg ? 0 : m.lhold.size();
     h.delimiter = m.hold.size() + lhold + m.val.held() + m.content.held_other() +
                   (m.msg.reasoning.size() - m.sent_r) + (m.msg.content.size() - m.sent_c) +
-                  (m.msg.calls.empty() ? 0 : m.msg.calls.back().arguments.size() - m.sent_a);
+                  (m.msg.calls.empty() ? 0 : m.msg.calls.back().arguments.size() - m.sent_a) +
+                  m.srun.size() + m.qtail.size();
     h.space = m.content.held_space() + m.think_pend.size();
-    h.delimiter += m.srun.size() + m.qtail.size();
     h.structure = m.att.size() + m.name.size() + m.vheld.size() + m.val.held_container() +
                   m.jhi.size();
     return h;
diff --git a/core/text/chatparse.h b/core/text/chatparse.h
index 4d820ea2..9d60b73d 100644
--- a/core/text/chatparse.h
+++ b/core/text/chatparse.h
@@ -1,55 +1,52 @@
-/* chatparse.h -- reading a model's reply back as it streams: reasoning, content, tool calls.
+/* chatparse.h -- reading a model's reply as it streams: reasoning, content, tool calls.
  *
- * ONE PASS, ONE PARSER. A reply is fed as it is generated, in pieces of any size, and every byte
- * is examined a bounded number of times: the whole reply costs O(its length), whether it arrives
- * in one piece or one byte at a time. Nothing is re-parsed, nothing is matched with a regular
- * expression, and there is no second pass that repairs what the first one missed -- the malformed
- * shapes a model actually writes are states of this machine, not fallbacks around it.
+ * One pass, one parser. A reply is fed in pieces of any size as it is generated, and each byte is
+ * examined a bounded number of times, so the whole reply costs O(length) however it is split.
+ * Nothing is re-parsed, nothing is matched with a regular expression, and there is no repair
+ * pass: the malformed shapes models actually write are states of this machine.
  *
- * It is driven by a ChatFormat (chatfmt.h) and built from three pieces:
+ * Driven by a ChatFormat (chatfmt.h), it has three parts:
  *
- *   * DELIMITER RECOGNITION is a deterministic Aho-Corasick automaton over the delimiters that can
- *     end the current region -- "" and the call opener inside reasoning, the call opener
- *     in content, the value suffix inside a value. In the automaton's root state the scan skips
- *     straight to the next byte that can begin a delimiter (memchr for the common one-byte case),
- *     so a long run of prose or file content costs a memchr and a copy.
- *   * THE TAG STRUCTURE is a transducer over those regions: call opener, name, arguments, close.
- *   * A JSON-TYPED ARGUMENT is recognised by an incremental JSON scanner with an explicit stack.
+ *   * Delimiter recognition: a deterministic Aho-Corasick automaton over the delimiters that can
+ *     end the current region ("" and the call opener in reasoning, the call opener in
+ *     content, the value suffix in a value). In the root state the scan skips to the next byte
+ *     that can begin a delimiter (memchr for the common one-byte case), so a long run of prose
+ *     costs a memchr and a copy.
+ *   * Tag structure: a transducer over those regions (call opener, name, arguments, close).
+ *   * JSON-typed arguments: an incremental JSON scanner with an explicit stack.
  *
- * WHAT IT PRODUCES is exactly what the format's grammar says the reply means, including the
- * places where the grammar is lenient on purpose: an argument the schema does not declare is
- * still an argument, a non-string argument that is not valid JSON is taken as text, a reasoning
- * block the model never closed ends where a call begins, prose before, between and after calls is
- * content. Where the reply leaves the grammar altogether -- a call to a function that is not a
- * tool, text inside a call, a missing close -- it recovers locally and says so (strict()).
+ * The output is what the format's grammar says the reply means, including where the grammar is
+ * deliberately lenient: an undeclared argument is still an argument, a non-string argument that
+ * is not valid JSON is text, an unclosed reasoning block ends where a call begins, and prose
+ * before, between and after calls is content. Where the reply leaves the grammar (a call to a
+ * function that is not a tool, text inside a call, a missing close) it recovers locally and
+ * clears strict().
  *
- * That includes a call written WITHOUT its wrapper. In a format whose calls are wrapped (Qwen's
- * `\n`) the grammar, and constrained decoding with it, begins only at the wrapper, so a
- * call the model writes as a bare ``, or with the wrapper run straight into it, is
- * unconstrained -- and it is the one most likely to be lost. In content, name_prefix alone and
- * call_open without its trailing whitespace also open a call, with every tag's surrounding
- * whitespace optional inside it. Because such an opener is also ordinary text, it becomes a call
- * only once the name tag is closed and an argument or the call's close follows; until then it is
- * held (a bounded number of bytes), and if it is not a call it is content.
+ * Unwrapped calls. In a wrapped format (Qwen's `\n`) the grammar, and so constrained
+ * decoding, starts only at the wrapper, so a call written as a bare ``, or with the
+ * wrapper run into it, is unconstrained and the most likely to be lost. In content, name_prefix
+ * alone and call_open without its trailing whitespace also open a call, with every tag's
+ * surrounding whitespace optional inside it. Because such an opener is also ordinary text, it
+ * becomes a call only once the name tag is closed and an argument or the call's close follows;
+ * until then it is held (a bounded number of bytes), and if it is not a call it is content.
  *
- * THE STREAMING CONTRACT: what has been emitted is final. A delta is never taken back, so every
- * emitted prefix of content, reasoning or arguments is a prefix of the finished value, and the
- * concatenated deltas ARE the finished values. That forces some bytes to be held until their
- * meaning is known, and the holds are bounded:
+ * Streaming contract: what has been emitted is final. A delta is never retracted, so the
+ * concatenated deltas are the finished content, reasoning and arguments. Bytes whose meaning is
+ * not yet known are held, within these bounds:
  *
- *   * a possible delimiter prefix -- at most the longest delimiter, less one byte;
- *   * an unfinished UTF-8 sequence -- at most three bytes, because a delta goes into a JSON string;
- *   * whitespace whose fate depends on what follows -- the trailing whitespace of content, which
- *     is trimmed if nothing follows it, and the whitespace that opens a reasoning block, which is
- *     dropped if the block holds nothing else;
- *   * a tag's own name while it is being read, since a name is only a name once it is closed;
- *   * a JSON-typed argument value until its closing delimiter: `30` and `30 seconds` differ from
- *     their first byte (a number, or the string "30 seconds"), so the value is emitted whole once
+ *   * a possible delimiter prefix: at most the longest delimiter less one byte;
+ *   * an unfinished UTF-8 sequence: at most three bytes, since a delta goes into a JSON string;
+ *   * whitespace that depends on what follows: content's trailing whitespace (trimmed if nothing
+ *     follows) and the whitespace opening a reasoning block (dropped if the block holds nothing
+ *     else);
+ *   * a tag's name while it is read, since it is a name only once closed;
+ *   * a JSON-typed argument value until its closing delimiter. `30` and `30 seconds` differ from
+ *     the first byte (a number, or the string "30 seconds"), so the value is emitted whole once
  *     its type is known. A value that stops being JSON part-way is streamed as text from there,
- *     except a container (`[`, `{`), which is held to its end: only there is it known whether
- *     it is JSON once its Python quoting is normalised, or the JSON string of its text.
+ *     except a container (`[`, `{`), which is held to its end: only then is it known whether it
+ *     is JSON once its Python quoting is normalised, or becomes the JSON string of its text.
  *
- * Streaming emits in the reply's order; a call's arguments are streamed as they are parsed. */
+ * Events are emitted in reply order; a call's arguments stream as they are parsed. */
 #pragma once
 #include "rad_internal.h"
 
@@ -83,9 +80,9 @@ struct ReplyCall {
     std::string name;
     std::string arguments;    /* JSON text, as the OpenAI API carries it */
     bool        closed = false;
-    /* Where the call's text begins in the reply, and the content up to it: `content_at` bytes
-     * of the message's content and the untrimmed whitespace held after them. What the content
-     * is when the call is read as text (ReplyStream::content_with_open_call). */
+    /* Where the call's text begins in the reply (`at`), and the content before it: `content_at`
+     * bytes of the message's content plus the untrimmed whitespace held after them. Used to read
+     * the call back as text (ReplyStream::content_with_open_call). */
     size_t      at = 0;
     size_t      content_at = 0;
     std::string content_held;
@@ -119,16 +116,16 @@ struct ReplyOptions {
     /* A response_format was requested: the reply is one JSON document, optionally fenced as
      * ```json ... ```, and the document is the content. */
     bool        response_format = false;
-    /* The model's turn terminators. The decoder renders one only when the format needs it, and
-     * one left on the end of content is not part of the answer. */
+    /* The model's turn terminators. The decoder renders one only when the format needs it; one
+     * left at the end of content is not part of the answer. */
     std::vector terminators;
 };
 
 class ReplyStream;
 
-/* The reasoning block as one request's reply meets it: its markers with the optional whitespace
- * around them trimmed, and whether the reply starts inside it -- the generation prompt opened it,
- * or the format has no opener. Empty `close` is a format with no reasoning block. */
+/* The reasoning block as one request's reply sees it: the markers with their optional
+ * surrounding whitespace trimmed, and whether the reply starts inside the block (the generation
+ * prompt opened it, or the format has no opener). An empty `close` means no reasoning block. */
 struct ReasoningMarkers {
     std::string open, close;
     bool        starts_open = false;
@@ -155,19 +152,19 @@ private:
 class ReplyParser {
 public:
     ~ReplyParser();
-    /* RAD_OK, or RAD_E_INVAL with *why when a tool cannot be read unambiguously in this format --
-     * a function or parameter name containing the delimiter that ends it -- and
-     * RAD_E_UNSUPPORTED when the request sends tools and the format has no tool calls. */
+    /* RAD_OK; RAD_E_INVAL with *why when a tool cannot be read unambiguously in this format (a
+     * function or parameter name containing the delimiter that ends it); RAD_E_UNSUPPORTED when
+     * the request sends tools and the format has no tool calls. */
     static int create(std::shared_ptr fmt, const ReplyOptions& opt,
                       std::shared_ptr* out, std::string* why);
     std::unique_ptr open() const;
     const ChatFormat& format() const;
-    /* The most bytes ReplyHeld::delimiter can reach for this request: a delimiter or terminator
-     * prefix in each place one can be pending at once, a value's undecided head, and an
-     * unfinished UTF-8 sequence on each output. A constant of the format, not of the reply. */
+    /* Upper bound on ReplyHeld::delimiter for this request: a delimiter or terminator prefix in
+     * each place one can be pending at once, a value's undecided head, and an unfinished UTF-8
+     * sequence per output. Depends on the format, not the reply. */
     size_t hold_bound() const;
-    /* Read from the generation prompt exactly as a stream's first bytes are, so a reply this
-     * says starts in the block is one the stream reads as reasoning from its first byte. */
+    /* Read from the generation prompt the same way a stream reads its first bytes, so a reply
+     * this says starts in the block is read as reasoning from its first byte. */
     ReasoningMarkers reasoning() const;
 
     struct Impl;
@@ -187,14 +184,17 @@ public:
     void finish(std::vector* out);
 
     const ReplyMessage& message() const;
-    /* After finish(): the content were the last call text, when the reply ended inside that call
-     * -- the content before it, then the call as `reply` (every byte fed) spells it, trimmed at
-     * the end as content is. A call that never closed cannot be reported as a call, and its text
-     * is what the model wrote. The message's content when the last call closed, or there is none. */
+    /* After finish(): the content with the last call read as text. If the reply ended inside an
+     * unclosed call, that is the content before the call followed by the call as `reply` (every
+     * byte fed) spells it, end-trimmed like content, since an unclosed call cannot be reported as
+     * a call. Otherwise (last call closed, or no calls) the message's content. */
     std::string content_with_open_call(std::string_view reply) const;
     /* False once the reply left the format's grammar and was read by a recovery rule. */
     bool strict() const;
     ReplyHeld held() const;
+    /* Bytes queued so far to be read a second time. Each step of the parser consumes a byte or
+     * queues bytes again, so it takes at most as many steps as the bytes fed plus these. */
+    size_t reread() const;
 
     struct Impl;
 private:
diff --git a/core/text/gguf.cpp b/core/text/gguf.cpp
index 820d5eac..fe66cad1 100644
--- a/core/text/gguf.cpp
+++ b/core/text/gguf.cpp
@@ -12,10 +12,9 @@
 namespace rad {
 
 /* ------------------------------------------------------------------ dtype geometry */
-/* Transcribed from ggml.c `type_traits` at llama.cpp 06938ac12 by running ggml_blck_size() and
- * ggml_type_size() over the whole enum, so it is the values the producer actually used rather
- * than the values the format documentation claims. Rows 42..44 are local to that checkout and
- * are carried so a file written by it is readable; upstream stops at 41. */
+/* Produced by running ggml_blck_size() and ggml_type_size() over the whole enum at llama.cpp
+ * 06938ac12, so these are the values the producer used, not the documented ones. Rows 42..44 are
+ * local to that checkout and kept so files it wrote stay readable; upstream stops at 41. */
 static const GgufDtype k_dtypes[] = {
     {   1,   4, "f32"     }, /*  0 */
     {   1,   2, "f16"     }, /*  1 */
@@ -71,9 +70,8 @@ const GgufDtype* gguf_dtype(uint32_t t) {
 }
 
 uint32_t gguf_to_rad_dtype(uint32_t t) {
-    /* Only the types whose bytes mean the same thing on both sides. Everything block-quantised
-     * is deliberately absent: reinterpreting a q4_K block as RAD_I4 would produce a tensor that
-     * loads and computes and is wrong, which is the failure mode this project exists to remove. */
+    /* Block-quantised types are deliberately absent: a q4_K block reinterpreted as RAD_I4 would
+     * load and compute, and be wrong. */
     switch (t) {
         case 0:  return RAD_F32;
         case 1:  return RAD_F16;
@@ -87,9 +85,8 @@ uint32_t gguf_to_rad_dtype(uint32_t t) {
 }
 
 /* ------------------------------------------------------------------ cursor */
-/* A bounds-checked forward cursor over the mmap. Every read returns false at the end of the
- * file instead of faulting, because a truncated GGUF is a thing that happens to people and
- * "SIGSEGV in the loader" is not a diagnosis. */
+/* A bounds-checked forward cursor over the mmap. Reads return false at the end of the file
+ * instead of faulting, so a truncated GGUF gets an error message, not a SIGSEGV. */
 namespace {
 struct Cursor {
     const uint8_t* p = nullptr;
@@ -128,15 +125,13 @@ size_t gguf_scalar_bytes(uint32_t t) {
     }
 }
 
-/* The smallest a KV and a tensor record can be encoded in, which is what a count in the header is
- * checked against: a key or name length and a type, then one value byte, or a dimension count
- * and an offset. */
+/* Smallest encodings of a KV (key length, type, one value byte) and a tensor record (name length,
+ * dimension count, type, offset). The header's counts are checked against them. */
 constexpr uint64_t kMinKvBytes     = sizeof(uint64_t) + sizeof(uint32_t) + 1;
 constexpr uint64_t kMinTensorBytes = sizeof(uint64_t) + 2 * sizeof(uint32_t) + sizeof(uint64_t);
 
-/* A count read from the file sizes a reservation only up to a point. Past it the table grows as
- * entries are actually read, so its memory follows the file's content rather than what the file
- * claims about it. */
+/* Caps a reservation sized by a count from the file. Past the cap the table grows as entries are
+ * read, so memory follows the file's content, not its claims. */
 size_t reserve_hint(uint64_t n) { return (size_t)std::min(n, 1u << 16); }
 
 /* Widen one fixed-width scalar into the KV's integer or float lane. */
@@ -202,6 +197,11 @@ int GgufFile::open(const char* path) {
     }
     base_ = static_cast(m);
     file_bytes_ = (uint64_t)st.st_size;
+    /* Every refusal from here on unmaps the file. */
+    auto fail = [this] {
+        close();
+        return RAD_E_FORMAT;
+    };
 
     Cursor c{ base_, 0, file_bytes_ };
 
@@ -209,32 +209,28 @@ int GgufFile::open(const char* path) {
     uint64_t n_tensors = 0, n_kv = 0;
     if (!c.raw(magic, 4) || !c.pod(&version_) || !c.pod(&n_tensors) || !c.pod(&n_kv)) {
         RAD_ERR("gguf: %s is too short to hold a header", path_.c_str());
-        close();
-        return RAD_E_FORMAT;
+        return fail();
     }
     if (std::memcmp(magic, "GGUF", 4) != 0) {
         RAD_ERR("gguf: %s is not a GGUF file (magic %02x%02x%02x%02x)", path_.c_str(),
                 (unsigned)(uint8_t)magic[0], (unsigned)(uint8_t)magic[1],
                 (unsigned)(uint8_t)magic[2], (unsigned)(uint8_t)magic[3]);
-        close();
-        return RAD_E_FORMAT;
+        return fail();
     }
-    /* v1 laid its counts out as 32-bit and nothing produces it any more; v2 and v3 differ only
-     * in the sign of a tensor dimension, which we read as int64 either way. */
+    /* v1 used 32-bit counts and is no longer produced. v2 and v3 differ only in the signedness
+     * of a tensor dimension, which is read as int64 either way. */
     if (version_ < 2 || version_ > 3) {
         RAD_ERR("gguf: %s is version %u; this reader handles 2 and 3", path_.c_str(), version_);
-        close();
-        return RAD_E_FORMAT;
+        return fail();
     }
-    /* Both counts index heap tables, so a corrupt one has to be refused before it is trusted as
-     * a loop bound. What is left of the file has to hold every entry at its smallest encoding. */
+    /* Both counts bound loops that fill heap tables, so refuse them unless the rest of the file
+     * can hold every entry at its smallest encoding. */
     const uint64_t rest = c.end - c.off;
     if (n_kv > rest / kMinKvBytes || n_tensors > rest / kMinTensorBytes) {
         RAD_ERR("gguf: %s declares %llu KVs and %llu tensors in %llu bytes", path_.c_str(),
                 (unsigned long long)n_kv, (unsigned long long)n_tensors,
                 (unsigned long long)file_bytes_);
-        close();
-        return RAD_E_FORMAT;
+        return fail();
     }
 
     kv_.reserve(reserve_hint(n_kv));
@@ -243,39 +239,33 @@ int GgufFile::open(const char* path) {
         uint32_t t = 0;
         if (!c.str(&e.key) || !c.pod(&t)) {
             RAD_ERR("gguf: %s: truncated in KV %llu", path_.c_str(), (unsigned long long)k);
-            close();
-            return RAD_E_FORMAT;
+            return fail();
         }
         uint64_t n = 1;
         if (t == GGUF_ARR) {
             e.is_array = true;
             if (!c.pod(&t) || !c.pod(&n)) {
                 RAD_ERR("gguf: %s: truncated array header for '%s'", path_.c_str(), e.key.c_str());
-                close();
-                return RAD_E_FORMAT;
+                return fail();
             }
             if (t == GGUF_ARR) {
                 RAD_ERR("gguf: %s: '%s' is an array of arrays, which GGUF does not define",
                         path_.c_str(), e.key.c_str());
-                close();
-                return RAD_E_FORMAT;
+                return fail();
             }
-            /* Every element has a smallest encoding -- its width, or a string's length prefix --
-             * so a bogus count is caught here, against what is left of the file, rather than
-             * after a reserve sized by it has exhausted memory. A type with no encoding at all
-             * fails on its first element, so it is refused before anything is sized for it. */
+            /* Each element takes at least its width (a string, its length prefix), so a bogus
+             * count is refused against the remaining bytes before anything is reserved for it.
+             * An undefined element type is refused here for the same reason. */
             const size_t w = t == GGUF_STR ? sizeof(uint64_t) : gguf_scalar_bytes(t);
             if (!w) {
                 RAD_ERR("gguf: %s: '%s' is an array of type %u, which GGUF does not define",
                         path_.c_str(), e.key.c_str(), t);
-                close();
-                return RAD_E_FORMAT;
+                return fail();
             }
             if (n > (c.end - c.off) / w) {
                 RAD_ERR("gguf: %s: '%s' claims %llu elements, past the end of the file",
                         path_.c_str(), e.key.c_str(), (unsigned long long)n);
-                close();
-                return RAD_E_FORMAT;
+                return fail();
             }
         }
         e.type = t;
@@ -287,20 +277,25 @@ int GgufFile::open(const char* path) {
             if (!read_scalar(c, t, e)) {
                 RAD_ERR("gguf: %s: truncated value %llu of '%s' (type %u)", path_.c_str(),
                         (unsigned long long)j, e.key.c_str(), t);
-                close();
-                return RAD_E_FORMAT;
+                return fail();
             }
         }
-        /* Later duplicates lose. GGUF does not forbid them and a rewriter can leave one behind;
-         * the first is the one every other reader takes. */
+        /* The first of duplicate keys wins, as in other readers. GGUF does not forbid
+         * duplicates and a rewriter can leave one behind. */
         if (!kv_index_.count(e.key)) kv_index_[e.key] = kv_.size();
         kv_.push_back(std::move(e));
     }
 
-    /* The alignment KV moves the data section, so it has to be read before the directory's
-     * offsets mean anything. 32 is the format's default. */
-    int64_t al = 0;
-    if (get_i64("general.alignment", &al) && al > 0 && (al & (al - 1)) == 0) {
+    /* general.alignment moves the data section, so it is read before the directory's offsets.
+     * The format's default is 32. A value that is not one integer power of two is refused, as
+     * ggml's reader refuses it: no writer places the data section by it, and falling back to
+     * the default would read every tensor from the wrong bytes. */
+    if (const GgufKV* a = find("general.alignment")) {
+        const int64_t al = !a->is_array && a->type != GGUF_BOOL && a->i.size() == 1 ? a->i[0] : 0;
+        if (al <= 0 || (al & (al - 1)) != 0) {
+            RAD_ERR("gguf: %s: general.alignment is not a power of two", path_.c_str());
+            return fail();
+        }
         alignment_ = (uint64_t)al;
     }
 
@@ -309,47 +304,39 @@ int GgufFile::open(const char* path) {
         GgufTensor ti;
         if (!c.str(&ti.name) || !c.pod(&ti.n_dims)) {
             RAD_ERR("gguf: %s: truncated in tensor %llu", path_.c_str(), (unsigned long long)t);
-            close();
-            return RAD_E_FORMAT;
+            return fail();
         }
         if (ti.n_dims > 4) {
             RAD_ERR("gguf: %s: tensor '%s' has %u dimensions; GGUF allows 4",
                     path_.c_str(), ti.name.c_str(), ti.n_dims);
-            close();
-            return RAD_E_FORMAT;
+            return fail();
         }
         for (uint32_t d = 0; d < ti.n_dims; ++d) {
             if (!c.pod(&ti.ne[d]) || ti.ne[d] < 0) {
                 RAD_ERR("gguf: %s: tensor '%s' has a bad dimension %u", path_.c_str(),
                         ti.name.c_str(), d);
-                close();
-                return RAD_E_FORMAT;
+                return fail();
             }
         }
         if (!c.pod(&ti.ggml_type) || !c.pod(&ti.offset)) {
             RAD_ERR("gguf: %s: truncated type/offset for '%s'", path_.c_str(), ti.name.c_str());
-            close();
-            return RAD_E_FORMAT;
+            return fail();
         }
         const GgufDtype* dt = gguf_dtype(ti.ggml_type);
         if (!dt) {
-            RAD_ERR("gguf: %s: tensor '%s' has dtype %u, which this build does not know. "
-                    "Refusing rather than guessing its byte size.",
+            RAD_ERR("gguf: %s: tensor '%s' has dtype %u, which this build does not know",
                     path_.c_str(), ti.name.c_str(), ti.ggml_type);
-            close();
-            return RAD_E_FORMAT;
+            return fail();
         }
         if (ti.ne[0] % dt->blck != 0) {
             RAD_ERR("gguf: %s: tensor '%s' row is %lld elements, not a multiple of the %s block "
                     "of %d", path_.c_str(), ti.name.c_str(), (long long)ti.ne[0], dt->name,
                     dt->blck);
-            close();
-            return RAD_E_FORMAT;
+            return fail();
         }
-        /* The product of four file-supplied dimensions, and its size in bytes, can each wrap --
-         * to a small tensor that passes the bounds check below while its dimensions say it is
-         * vast. Both are checked, and the count also has to fit the signed type every consumer
-         * of `ne` computes it in. */
+        /* The product of four file-supplied dimensions and its byte size can each wrap to a
+         * small value that passes the bounds check below. Check both, and that the element
+         * count fits int64, the type consumers of `ne` compute it in. */
         uint64_t nelem = 1;
         bool     wraps = false;
         for (int d = 0; d < 4; ++d)
@@ -362,10 +349,14 @@ int GgufFile::open(const char* path) {
                     "does not fit in 64 bits", path_.c_str(), ti.name.c_str(),
                     (long long)ti.ne[0], (long long)ti.ne[1], (long long)ti.ne[2],
                     (long long)ti.ne[3]);
-            close();
-            return RAD_E_FORMAT;
+            return fail();
         }
-        if (!tensor_index_.count(ti.name)) tensor_index_[ti.name] = tensors_.size();
+        /* A second entry under one name could never be looked up. */
+        if (tensor_index_.count(ti.name)) {
+            RAD_ERR("gguf: %s: tensor '%s' is listed twice", path_.c_str(), ti.name.c_str());
+            return fail();
+        }
+        tensor_index_[ti.name] = tensors_.size();
         tensors_.push_back(std::move(ti));
     }
 
@@ -373,19 +364,24 @@ int GgufFile::open(const char* path) {
     if (data_off_ > file_bytes_) {
         RAD_ERR("gguf: %s: data section starts at %llu, past the end of a %llu-byte file",
                 path_.c_str(), (unsigned long long)data_off_, (unsigned long long)file_bytes_);
-        close();
-        return RAD_E_FORMAT;
+        return fail();
     }
-    /* Every tensor must lie inside the file. Checking it once here is what lets tensor_data()
-     * hand out a raw pointer without every caller re-deriving the bound. */
+    /* Every tensor must lie inside the file, so tensor_data() can hand out raw pointers, and
+     * start on the file's alignment, as ggml's reader requires, so those pointers are aligned
+     * for the vector loads of whatever reads them. */
     for (const GgufTensor& ti : tensors_) {
+        if (ti.offset % alignment_ != 0) {
+            RAD_ERR("gguf: %s: tensor '%s' starts at +%llu, off the file's %llu-byte alignment",
+                    path_.c_str(), ti.name.c_str(), (unsigned long long)ti.offset,
+                    (unsigned long long)alignment_);
+            return fail();
+        }
         if (ti.offset > file_bytes_ - data_off_ ||
             ti.bytes  > file_bytes_ - data_off_ - ti.offset) {
             RAD_ERR("gguf: %s: tensor '%s' (%llu bytes at +%llu) leaves the file",
                     path_.c_str(), ti.name.c_str(),
                     (unsigned long long)ti.bytes, (unsigned long long)ti.offset);
-            close();
-            return RAD_E_FORMAT;
+            return fail();
         }
     }
 
diff --git a/core/text/gguf.h b/core/text/gguf.h
index 8e57a4ec..a9187ee8 100644
--- a/core/text/gguf.h
+++ b/core/text/gguf.h
@@ -1,18 +1,15 @@
-/* gguf.h -- a reader for the GGUF container, and nothing else.
+/* gguf.h -- a reader for the GGUF container.
  *
- * spec §12 lists `ggml/src/gguf.cpp` as a lift, but that file is a reader, a writer and a
- * ggml_context builder welded together: it fills `struct ggml_tensor`, calls `ggml_blck_size`,
- * and pulls in `ggml.h` for both. Taking it whole would mean taking ggml, which §12 says
- * explicitly we do not. So the reader is rewritten here under our own name -- the wire format is
- * a header, a KV table, a tensor directory and a padded blob, and that is a page of code -- and
- * `vendor/UPSTREAM` records the file it was read from rather than copied from.
+ * A rewrite of `ggml/src/gguf.cpp` (spec §12), not a lift: that file is also a writer and a
+ * ggml_context builder (it fills `struct ggml_tensor` and needs `ggml.h`), and §12 excludes ggml.
+ * The format is a header, a KV table, a tensor directory and a padded data blob. `vendor/UPSTREAM`
+ * records the file it was written against.
  *
- * What we keep from upstream is the one thing that is genuinely data rather than code: the block
- * geometry of every ggml dtype, without which a tensor's byte size cannot be computed. That table
- * is transcribed from `ggml_blck_size`/`ggml_type_size` and is marked as such below.
+ * The only thing taken from upstream is data: the block geometry of every ggml dtype, needed to
+ * compute a tensor's byte size (GgufDtype).
  *
- * The file is mmapped whole and never copied. rad-convert walks the directory, reads what it
- * wants through `tensor_data()`, and writes the .rad; nothing here interprets tensor CONTENT.
+ * The file is mmapped whole and never copied. rad-convert walks the directory, reads tensors
+ * through `tensor_data()` and writes the .rad; nothing here interprets tensor content.
  */
 #pragma once
 #include "rad_internal.h"
@@ -24,34 +21,29 @@
 
 namespace rad {
 
-/* GGUF's own value type numbering. These are wire values -- fixed by the format, not by us. */
+/* GGUF's value type numbering (wire values, fixed by the format). */
 enum GgufType {
     GGUF_U8 = 0, GGUF_I8 = 1, GGUF_U16 = 2, GGUF_I16 = 3, GGUF_U32 = 4, GGUF_I32 = 5,
     GGUF_F32 = 6, GGUF_BOOL = 7, GGUF_STR = 8, GGUF_ARR = 9, GGUF_U64 = 10,
     GGUF_I64 = 11, GGUF_F64 = 12
 };
 
-/* One metadata entry.
- *
- * A scalar is stored as a one-element vector, so a caller reading `tokenizer.ggml.tokens` and a
- * caller reading `general.name` write the same code and neither branches on `is_array`. The cost
- * is one heap allocation per scalar KV at open, against a KV table that is a few hundred rows;
- * the benefit is that the every-caller path has no special case in it, and a special case in a
- * metadata reader is where a truncated vocab comes from. */
+/* One metadata entry. A scalar is stored as a one-element vector, so callers read scalars and
+ * arrays the same way without branching on `is_array`. */
 struct GgufKV {
     std::string key;
-    uint32_t    type = GGUF_U8;   /* for an array, the ELEMENT type; GGUF_ARR never appears here */
+    uint32_t    type = GGUF_U8;   /* for an array, the element type; never GGUF_ARR */
     bool        is_array = false;
 
-    /* Populated according to `type`: integers and bools widen into `i`, floats into `f`,
-     * strings into `s`. The other two stay empty. */
+    /* By `type`: integers and bools widen into `i`, floats into `f`, strings into `s`. The
+     * other two stay empty. */
     std::vector     i;
     std::vector      f;
     std::vector s;
 };
 
-/* One tensor directory row. `offset` is from the start of the data section, which is where GGUF
- * puts it; `data_off() + offset` is the file offset, and `tensor_data()` does that arithmetic. */
+/* One tensor directory row. `offset` is relative to the data section; the file offset is
+ * `data_off() + offset` (see `tensor_data()`). */
 struct GgufTensor {
     std::string name;
     uint32_t    ggml_type = 0;
@@ -61,9 +53,9 @@ struct GgufTensor {
     uint64_t    bytes = 0;                /* computed from ne and the block geometry */
 };
 
-/* Block geometry for a ggml dtype. Transcribed from ggml.c's `type_traits` at llama.cpp
- * 06938ac12 -- see vendor/UPSTREAM. `blck` of 0 marks a removed or unknown type, and a tensor
- * carrying one is refused at open rather than silently mis-sized. */
+/* Block geometry for a ggml dtype, transcribed from ggml.c's `type_traits` at llama.cpp
+ * 06938ac12 (vendor/UPSTREAM). `blck` 0 marks a removed or unknown type; open() refuses a tensor
+ * of that type rather than mis-size it. */
 struct GgufDtype {
     int         blck;        /* logical elements per stored block */
     size_t      block_bytes; /* bytes per stored block */
@@ -71,9 +63,8 @@ struct GgufDtype {
 };
 const GgufDtype* gguf_dtype(uint32_t ggml_type);   /* null if out of range */
 
-/* Map a ggml dtype onto RAD_* where the two agree exactly. Returns RAD_DT_INVALID for the
- * k-quants and the iq-quants: those have no RAD_* equivalent, and rad-convert has to dequantise
- * or refuse rather than reinterpret the bytes. */
+/* Map a ggml dtype onto RAD_* where the bytes agree exactly. RAD_DT_INVALID for block-quantised
+ * types (k-quants, iq-quants), which rad-convert must dequantise or refuse, never reinterpret. */
 uint32_t gguf_to_rad_dtype(uint32_t ggml_type);
 
 class GgufFile {
@@ -83,8 +74,8 @@ public:
     GgufFile(const GgufFile&) = delete;
     GgufFile& operator=(const GgufFile&) = delete;
 
-    /* RAD_OK, or a negative RAD_E_*: RAD_E_IO if the file will not open or map,
-     * RAD_E_FORMAT if the magic, version, or directory does not hold together. */
+    /* RAD_OK, RAD_E_IO if the file will not open or map, or RAD_E_FORMAT if the magic, version
+     * or directory is invalid. */
     int  open(const char* path);
     void close();
     bool is_open() const { return base_ != nullptr; }
@@ -103,8 +94,7 @@ public:
     const GgufTensor* tensor(std::string_view name) const;
 
     /* Typed reads. Each returns false and leaves *out untouched when the key is absent or holds
-     * the wrong shape of value -- absence and a type mismatch are the same thing to a caller that
-     * has a default, and the ones that do not have a default check the return. */
+     * the wrong kind of value; a caller with a default treats both the same. */
     bool get_i64(std::string_view key, int64_t* out) const;
     bool get_f64(std::string_view key, double* out) const;
     bool get_str(std::string_view key, std::string* out) const;
@@ -112,8 +102,8 @@ public:
     bool get_i64s(std::string_view key, std::vector* out) const;
     bool get_f32s(std::string_view key, std::vector* out) const;
 
-    /* A pointer into the mmap. Null if the tensor's extent leaves the file, which is a corrupt
-     * container rather than a caller error -- open() already refused those, so this is belt. */
+    /* A pointer into the mmap, or null if the tensor's extent leaves the file (a corrupt
+     * container, which open() already refuses). */
     const void* tensor_data(const GgufTensor& t) const;
 
 private:
diff --git a/core/text/token_view.h b/core/text/token_view.h
new file mode 100644
index 00000000..093ef5dd
--- /dev/null
+++ b/core/text/token_view.h
@@ -0,0 +1,52 @@
+/* token_view.h -- the sampler's VocabView over a real vocabulary (sample/vocab_view.h). */
+#pragma once
+#include "sample/vocab_view.h"
+#include "text/tokenizer.h"
+
+#include 
+#include 
+#include 
+
+namespace rad {
+
+class TokenView final : public VocabView {
+public:
+    /* Pieces are built once (token_piece returns a reference), saving a string per candidate per
+     * grammar step on the step path.
+     *
+     * They come from piece(), not Vocab::text(): text() is the vocab's own encoding (for
+     * byte-level BPE the GPT-2 alphabet, where a space is 'Ġ'), while piece() runs the decoder
+     * chain and yields the output bytes vocab_view.h asks for. With text() every grammar would
+     * forbid tokens containing spaces or newlines. Special tokens are rendered, because an empty
+     * piece would satisfy any grammar position. */
+    int init(std::shared_ptr v) {
+        v_ = std::move(v);
+        RAD_TRY(tok_.init(v_));
+        pieces_.resize((size_t)v_->n_tokens());
+        for (int32_t i = 0; i < v_->n_tokens(); ++i)
+            pieces_[(size_t)i] = tok_.piece(i, /*render_special=*/true);
+        return RAD_OK;
+    }
+    int32_t n_tokens() const override { return v_ ? v_->n_tokens() : 0; }
+    const std::string& token_piece(int32_t id) const override {
+        static const std::string kEmpty;
+        return (id >= 0 && (size_t)id < pieces_.size()) ? pieces_[(size_t)id] : kEmpty;
+    }
+    bool is_eog(int32_t id) const override { return v_ && v_->is_eog(id); }
+    int  tokenize(const std::string& s, std::vector* out) const override {
+        return out ? tok_.encode(s, *out, /*add_special=*/false, /*parse_special=*/false)
+                   : RAD_E_INVAL;
+    }
+    int  tokenize_special(const std::string& s, std::vector* out) const override {
+        return out ? tok_.encode(s, *out, /*add_special=*/false, /*parse_special=*/true)
+                   : RAD_E_INVAL;
+    }
+    const Tokenizer& tok() const { return tok_; }
+
+private:
+    std::shared_ptr v_;
+    Tokenizer                    tok_;
+    std::vector     pieces_;
+};
+
+}  /* namespace rad */
diff --git a/core/text/tokenizer.cpp b/core/text/tokenizer.cpp
index b5acc4c4..7cfeee0e 100644
--- a/core/text/tokenizer.cpp
+++ b/core/text/tokenizer.cpp
@@ -18,14 +18,12 @@ namespace rad {
 
 /* ================================================================== byte level
  *
- * GPT-2's byte alphabet, exactly. The printable ASCII range, Latin-1 punctuation and the
- * accented Latin-1 letters map to themselves; the remaining 68 bytes map to U+0100 upward in
- * ascending byte order. Getting this wrong is not a crash -- it is a vocab lookup that misses
- * for one byte in four, which shows up as a 20% longer prompt and nothing else. It is
- * reproduced from llama.cpp's unicode_byte_to_utf8_map(), which is itself HuggingFace's table.
- *
- * We do not call llama.cpp's version because its inverse throws std::out_of_range on an
- * unmapped string, and in this engine errors are values (docs/IMPLEMENTATION.md). */
+ * GPT-2's byte alphabet. Printable ASCII, Latin-1 punctuation and the accented Latin-1 letters
+ * map to themselves; the remaining 68 bytes map to U+0100 upward in ascending byte order. A
+ * mistake here does not crash: vocab lookups silently miss and prompts grow longer. Reproduced
+ * from llama.cpp's unicode_byte_to_utf8_map() (HuggingFace's table), not called, because its
+ * inverse throws std::out_of_range on an unmapped string and errors here are values
+ * (docs/IMPLEMENTATION.md). */
 namespace {
 
 struct ByteLevelAlphabet {
@@ -65,15 +63,13 @@ std::string byte_encode(std::string_view raw) {
     return out;
 }
 
-/* Inverse. An unmapped codepoint is passed through as its own UTF-8, which is what a
- * user-defined token spelt in real text needs; it cannot be confused with a mapped one because
- * the mapped set is closed. */
+/* Inverse. An unmapped codepoint passes through as its own UTF-8, as a user-defined token spelt
+ * in real text needs; the mapped set is closed, so the two cannot be confused. */
 std::string byte_decode(const std::string& enc) {
-    /* Unit by unit, a unit being what the lead byte says, cut short at the end. A unit is mapped
-     * iff it is exactly some byte's spelling in the alphabet -- one ASCII byte, or a two-byte
-     * sequence (lead C2..DF, a continuation byte) whose code point is below U+0144 -- so the
-     * code point table answers what a lookup of the unit's bytes in `from` would, without
-     * building a string per character. Anything else is passed through as its own bytes. */
+    /* Unit by unit, a unit's length given by its lead byte and cut short at the end. A unit is
+     * mapped iff it is one ASCII byte or a two-byte sequence (lead C2..DF) below U+0144, so the
+     * codepoint table gives the same answer as looking the bytes up in `from`, without building
+     * a string per character. Anything else passes through as its own bytes. */
     const ByteLevelAlphabet& a = alphabet();
     const uint8_t* p = (const uint8_t*)enc.data();
     const size_t   n = enc.size();
@@ -95,10 +91,10 @@ std::string byte_decode(const std::string& enc) {
     return out;
 }
 
-/* The raw bytes a byte-level token stands for, when EVERY character of it is in the alphabet.
- * Only such a token can equal a byte-level word -- mapping puts every byte of a word into the
- * alphabet -- so a table of these by their raw bytes answers every lookup the mapped text would,
- * and the encoder can merge raw bytes and never build the mapped text at all. */
+/* The raw bytes a byte-level token stands for, when every character of it is in the alphabet.
+ * Only such a token can equal a mapped word, so a table keyed by these raw bytes answers every
+ * lookup the mapped text would, and the encoder can merge raw bytes without building the mapped
+ * text. */
 bool byte_decode_strict(const std::string& enc, std::string* out) {
     const ByteLevelAlphabet& a = alphabet();
     out->clear();
@@ -140,16 +136,34 @@ void replace_all(std::string& s, std::string_view from, std::string_view to) {
 constexpr const char* k_gpt2_pattern =
     "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+";
 
+/* HuggingFace's character-class pre-tokenisers, as the patterns they equal, so they run through
+ * the Split machinery:
+ *   Whitespace   \w+|[^\w\s]+ in Rust's regex crate (not Oniguruma), its matches kept and the rest
+ *                removed. Rust's \w is Alphabetic, marks, Nd, Pc and the joiners: Alphabetic is
+ *                the letters, Nl and a few symbol letters (circled and squared Latin), so No
+ *                ("²", "½") is not a word character as it is in Oniguruma.
+ *   whitespace   Rust's char::is_whitespace, the White_Space property, which is \s
+ *   punctuation  char::is_ascii_punctuation or a Unicode P* category (not symbols: "$" is
+ *                ASCII punctuation, "€" is not punctuation)
+ *   digits       char::is_numeric, the N* categories */
+#define RAD_RUST_WORD "\\p{L}\\p{Nl}\\p{M}\\p{Nd}\\p{Pc}\\x{200C}\\x{200D}\\x{24B6}-\\x{24E9}" \
+                      "\\x{1F130}-\\x{1F149}\\x{1F150}-\\x{1F169}\\x{1F170}-\\x{1F189}"
+constexpr const char* k_word_runs   = "[" RAD_RUST_WORD "]+|[^" RAD_RUST_WORD "\\s]+";
+#undef RAD_RUST_WORD
+constexpr const char* k_space_runs  = "\\s+";
+constexpr const char* k_punctuation = "[\\p{P}\\x21-\\x2F\\x3A-\\x40\\x5B-\\x60\\x7B-\\x7E]";
+constexpr const char* k_digit       = "\\p{N}";
+constexpr const char* k_digit_runs  = "\\p{N}+";
+
 }  /* namespace */
 
 /* ================================================================== the compiled encoder
  *
- * Everything encode() needs that can be decided once per vocab: each Split pattern compiled to
- * its DFA, the token and merge tables flattened into open-addressed arrays keyed the way the merge
- * loop asks, the special-token matcher, and the segment cache. Built by Vocab::load and shared by
- * every Tokenizer over the vocab. Two things in it change afterwards and both are safe to share:
- * the segment cache, which locks, and the memo of which tokens merge back to themselves, whose
- * entries are written once with relaxed atomics. */
+ * Everything encode() needs that is fixed per vocab: each Split pattern compiled to its DFA, the
+ * token and merge tables as open-addressed arrays keyed for the merge loop, the special-token
+ * matcher and the segment cache. Built by Vocab::load and shared by every Tokenizer over the
+ * vocab. Only two parts change afterwards, both safe to share: the segment cache, which locks,
+ * and the self-merge memo, whose entries are written once with relaxed atomics. */
 
 namespace {
 
@@ -157,13 +171,12 @@ namespace {
 
 struct SpecialFrag { int32_t id; uint32_t off, len; };
 
-/* The text is cut at every special token before any other step sees it. WHICH occurrences are
- * cut is decided by priority, not position: longest token first (then lowest id), and a token
- * only claims occurrences that no higher-priority token has already claimed and that do not
- * overlap one of its own claimed to their left. That is the result of splitting the text once
- * per token, longest first, and it is why "<|im_start|>" is never cut in half by a shorter token
- * that is a prefix of it. Finding the occurrences is one pass over the text with a
- * trie of every special token, started only at a byte some token begins with. */
+/* The text is cut at every special token before any other step sees it. Occurrences are claimed
+ * by priority, not position: longest token first (then lowest id), and a token claims only
+ * occurrences that overlap neither a higher-priority claim nor one of its own claims to the
+ * left. This equals splitting once per token, longest first, so "<|im_start|>" is never cut by a
+ * shorter token that is its prefix. Occurrences are found in one pass with a trie of all special
+ * tokens, started only at bytes some token begins with. */
 class SpecialMatcher {
 public:
     void build(const std::vector& special, const std::vector& tokens,
@@ -254,13 +267,13 @@ private:
 
 /* --- the segment cache ------------------------------------------------------------------- */
 
-/* Segment bytes -> ids. See Tokenizer's header for why a hit is exact. Entries are keyed by the
- * whole segment: the hash picks the bucket and the bytes decide the match. The bound is on bytes
- * held (key, ids and bookkeeping), and eviction is least recently used.
+/* Segment bytes -> ids; tokenizer.h explains why a hit is exact. Keyed by the whole segment (the
+ * hash picks the bucket, the bytes decide the match), bounded in bytes held (key, ids and
+ * bookkeeping), LRU eviction.
  *
- * The lock covers the index and nothing else. An entry is built before it is locked in, and a hit
- * takes a reference to the entry's ids and copies them after the lock is released, so a
- * 100,000-id segment copied into one admission never holds up another. */
+ * The lock covers only the index. An entry is built before it is locked in, and a hit copies the
+ * ids through a shared reference after unlocking, so copying a large segment never blocks
+ * another encode. */
 class SegmentCache {
 public:
     using Ids = std::shared_ptr>;
@@ -342,8 +355,7 @@ private:
         uint64_t    hash;
         size_t      cost;
     };
-    /* A list node, a hash node, the shared vector's control block and the heap headers, rounded
-     * up. */
+    /* A list node, a hash node, the shared vector's control block and heap headers, rounded up. */
     static constexpr size_t kOverhead = 160;
 
     /* Moves the least recently used entries into `out` until the bound holds; the caller frees
@@ -373,16 +385,19 @@ private:
 struct TokEncoder {
     struct Step {
         VocabStep                 step;
-        std::unique_ptr re;        /* Split, a regex Replace, ByteLevel with use_regex */
+        /* Split, a regex Replace, ByteLevel with use_regex, and the character-class
+         * pre-tokenisers; `re2` is BertPreTokenizer's punctuation after its whitespace split. */
+        std::unique_ptr re, re2;
     };
     std::vector norm, pre;
     uint32_t kind = RAD_TOK_BPE;
     bool     bytelevel = false;              /* the chain has a ByteLevel pre-tokeniser */
     bool     byte_fallback = false;
     bool     ignore_merges = false;          /* VocabBuild::ignore_merges */
-    /* The ByteLevel step at this index is the last step that rewrites text, so the mapping is
-     * never materialised: the BPE merges raw bytes against `raw` instead. -1 when that does not
-     * hold (no ByteLevel, or a step after it that reads the mapped text). */
+    bool     prepend_first = false;          /* a Metaspace step prepends to the first segment only */
+    /* Index of a ByteLevel step that is the last step rewriting text; its mapping is never
+     * materialised and the BPE merges raw bytes against `raw`. -1 when there is no ByteLevel or
+     * a later step reads the mapped text. */
     int      defer_bytelevel = -1;
 
     TokTable   text;                         /* token text -> lowest id */
@@ -392,11 +407,14 @@ struct TokEncoder {
     MergeTable merges;
     std::vector types;
     int32_t    unk = -1;
+    size_t     longest = 0;                  /* bytes in the longest token text */
+    /* Unigram: SentencePiece's unknown-token score, the lowest score minus 10. Derived, not
+     * stored in the .rad, so it cannot disagree with the scores. */
+    double     unk_penalty = 0.0;
 
-    /* Per token: whether its own text merges back to exactly itself -- 0 not yet known, 1 yes,
-     * 2 no. Most words of real text ARE a token, and the merge loop's answer for a token's text
-     * never changes, so once it has been worked out for one word it is looked up for every later
-     * one, by every thread, for the life of the vocab. Relaxed atomics: two threads that race
+    /* Per token: whether its own text merges back to exactly itself (0 unknown, 1 yes, 2 no).
+     * Most words of real text are a token and the answer never changes, so it is computed once
+     * and reused by every thread for the life of the vocab. Relaxed atomics: racing threads
      * store the same value. */
     std::unique_ptr[]> self_merges;
 
@@ -425,17 +443,26 @@ int TokEncoder::build(const VocabBuild& b, const std::vector& special)
 
     for (const VocabStep& s : b.steps) {
         if (step_is_norm(s.kind)) {
-            Step st{ s, nullptr };
+            Step st{ s, nullptr, nullptr };
             if (s.kind == RAD_NORM_REPLACE && (s.flags & 1)) RAD_TRY(compile(s.arg0, "Replace", &st.re));
             norm.push_back(std::move(st));
         } else if (step_is_pre(s.kind)) {
-            Step st{ s, nullptr };
+            Step st{ s, nullptr, nullptr };
             if (s.kind == RAD_PRE_SPLIT) RAD_TRY(compile(s.arg0, "Split", &st.re));
+            if (s.kind == RAD_PRE_WHITESPACE) {
+                RAD_TRY(compile(s.flags == kPreWhitespace ? k_word_runs : k_space_runs,
+                                "Whitespace", &st.re));
+                if (s.flags == kPreBert) RAD_TRY(compile(k_punctuation, "Bert", &st.re2));
+            }
+            if (s.kind == RAD_PRE_PUNCTUATION) RAD_TRY(compile(k_punctuation, "Punctuation", &st.re));
+            if (s.kind == RAD_PRE_DIGITS)
+                RAD_TRY(compile((s.flags & 1) ? k_digit : k_digit_runs, "Digits", &st.re));
             if (s.kind == RAD_PRE_BYTELEVEL) {
                 bytelevel = true;
                 if (s.flags & 2) RAD_TRY(compile(k_gpt2_pattern, "ByteLevel", &st.re));
             }
             if (s.kind == RAD_PRE_BYTE_FALLBACK) byte_fallback = true;
+            if (s.kind == RAD_PRE_METASPACE && s.iarg == 1) prepend_first = true;
             pre.push_back(std::move(st));
         }
     }
@@ -450,7 +477,12 @@ int TokEncoder::build(const VocabBuild& b, const std::vector& special)
 
     const size_t n = b.tokens.size();
     text.reserve(n);
-    for (size_t i = 0; i < n; ++i) text.insert(b.tokens[i], (int32_t)i);
+    for (size_t i = 0; i < n; ++i) {
+        text.insert(b.tokens[i], (int32_t)i);
+        longest = std::max(longest, b.tokens[i].size());
+    }
+    if (!b.scores.empty())
+        unk_penalty = *std::min_element(b.scores.begin(), b.scores.end()) - 10.0;
 
     const ByteLevelAlphabet& a = alphabet();
     for (int c = 0; c < 256; ++c) {
@@ -466,9 +498,9 @@ int TokEncoder::build(const VocabBuild& b, const std::vector& special)
             if (!b.tokens[i].empty() && byte_decode_strict(b.tokens[i], &r)) raw.insert(r, (int32_t)i);
     }
 
-    /* Keyed by the pair exactly as the vocab lists it, the lowest rank winning a duplicate. A
-     * symbol's id is always the LOWEST id spelling its text, so a merge listed against a higher
-     * id with the same text is never looked up. */
+    /* Keyed by the pair as the vocab lists it; the lowest rank wins a duplicate. A symbol's id is
+     * always the lowest id spelling its text, so a merge listed against a higher id with the same
+     * text is never looked up. */
     merges.reserve(b.merges.size());
     std::string cat;
     for (size_t r = 0; r < b.merges.size(); ++r) {
@@ -505,6 +537,39 @@ int Vocab::load(VocabBuild b) {
                 b_.kind);
         return RAD_E_UNSUPPORTED;
     }
+    /* A step this tokenizer does not run would silently change the text or the token boundaries,
+     * so a vocabulary that declares one does not load. */
+    for (const VocabStep& s : b_.steps) {
+        const uint32_t k = s.kind;
+        if ((k >= RAD_NORM_NFC && k <= RAD_NORM_PREPEND) ||
+            (k >= RAD_PRE_BYTELEVEL && k <= RAD_PRE_BYTE_FALLBACK) ||
+            (k >= RAD_DEC_BYTELEVEL && k <= RAD_DEC_BYTE_FALLBACK))
+            continue;
+        RAD_ERR("vocab: %s is not implemented", step_describe(s).c_str());
+        return RAD_E_UNSUPPORTED;
+    }
+    /* Values a step does not define would run as some other behaviour, so they do not load
+     * either. A Strip after Fuse strips the text as a whole, which a stream can do only at its
+     * start (see Detokenizer). */
+    {
+        bool fused = false, fused_strip = false;
+        for (const VocabStep& s : b_.steps) {
+            const bool behavior_step = s.kind == RAD_PRE_SPLIT || s.kind == RAD_PRE_PUNCTUATION;
+            const bool bad =
+                (behavior_step && (s.iarg < TOK_SPLIT_REMOVED || s.iarg > TOK_SPLIT_CONTIGUOUS)) ||
+                (s.kind == RAD_PRE_WHITESPACE && s.flags > kPreBert) ||
+                (s.kind == RAD_DEC_REPLACE &&
+                 (s.flags & ~(kDecWordPiece | kDecWordPieceCleanup | kDecBpeSuffix)) != 0) ||
+                (s.kind == RAD_DEC_STRIP && fused && ((s.iarg >> 32) != 0 || fused_strip));
+            if (bad) {
+                RAD_ERR("vocab: %s is not a step this tokenizer runs (flags %u)",
+                        step_describe(s).c_str(), s.flags);
+                return RAD_E_UNSUPPORTED;
+            }
+            if (s.kind == RAD_DEC_FUSE) fused = true;
+            if (s.kind == RAD_DEC_STRIP && fused) fused_strip = true;
+        }
+    }
     if (b_.types.empty()) b_.types.assign(b_.tokens.size(), (uint8_t)RAD_TT_NORMAL);
     if (b_.types.size() != b_.tokens.size()) {
         RAD_ERR("vocab: %zu tokens but %zu token types", b_.tokens.size(), b_.types.size());
@@ -516,11 +581,10 @@ int Vocab::load(VocabBuild b) {
         return RAD_E_FORMAT;
     }
 
-    /* A SPECIAL ID IS EMITTED AS IT STANDS -- bos and eos by encode, unk by every encoder on text
-     * no piece covers -- so one that names no token puts an id outside the vocabulary into a
-     * sequence. Every source of a vocabulary arrives here, and a GGUF or a container carries these
-     * ids as plain integers nothing else checks, so one out of range is treated as absent, which
-     * every reader of these fields already handles, and said so. */
+    /* Special ids are emitted as they stand (bos/eos by encode, unk by every encoder on uncovered
+     * text), so an out-of-range one would put an id outside the vocabulary into a sequence. GGUF
+     * and container sources carry them as unchecked integers; every vocabulary passes through
+     * here, so an out-of-range id is treated as absent, with a warning. */
     {
         const struct { const char* name; int32_t* id; } specials[] = {
             { "bos", &b_.bos }, { "eos", &b_.eos }, { "eot", &b_.eot },
@@ -536,28 +600,33 @@ int Vocab::load(VocabBuild b) {
 
     text_to_id_.reserve(b_.tokens.size() * 2);
     for (size_t i = 0; i < b_.tokens.size(); ++i) {
-        /* First spelling wins. A duplicate is a producer bug, but it is not ours to fail on:
-         * llama.cpp's own vocabs contain them, and the lower id is the one the merge table and
-         * every published token count refer to. */
+        /* First spelling wins. Duplicates are a producer bug but occur in llama.cpp's own vocabs,
+         * and the merge table and published token counts refer to the lower id. */
         text_to_id_.emplace(b_.tokens[i], (int32_t)i);
     }
 
-    /* Merge ranks are stored as an id pair rather than a string pair: the string pair would be
-     * a 248K-entry map of concatenated strings hashed on every bigram push, and the bigram push
-     * is the tokeniser's inner loop. */
+    /* Keyed by id pair rather than string pair, so a lookup hashes one integer instead of a
+     * concatenated string. */
     merge_rank_.reserve(b_.merges.size() * 2);
     for (size_t r = 0; r < b_.merges.size(); ++r) {
         const uint64_t key = ((uint64_t)b_.merges[r].first << 32) | (uint64_t)b_.merges[r].second;
         merge_rank_.emplace(key, (int32_t)r);
     }
 
+    /* A ByteFallback decoder turns "<0xNN>" pieces into their bytes whatever their type: a
+     * tokenizer.json types every model token alike, so its byte pieces arrive NORMAL. */
+    bool dec_byte_fallback = false;
+    for (const VocabStep& s : b_.steps) dec_byte_fallback |= s.kind == RAD_DEC_BYTE_FALLBACK;
+
     byte_of_.assign(b_.tokens.size(), -1);
     const ByteLevelAlphabet& a = alphabet();
     for (size_t i = 0; i < b_.tokens.size(); ++i) {
         const std::string& t = b_.tokens[i];
-        if (b_.types[i] == RAD_TT_BYTE) {
-            /* Two spellings in the wild: SPM's "<0xF0>" and byte-level BPE's single mapped
-             * codepoint. Both are byte tokens and both have to decode to one byte. */
+        const bool spm_byte = dec_byte_fallback && b_.types[i] == RAD_TT_NORMAL && t.size() == 6 &&
+                              t.compare(0, 3, "<0x") == 0 && t.back() == '>';
+        if (b_.types[i] == RAD_TT_BYTE || spm_byte) {
+            /* Two spellings: SPM's "<0xF0>" and byte-level BPE's single mapped codepoint. Both
+             * decode to one byte. */
             if (t.size() == 6 && t.compare(0, 3, "<0x") == 0 && t.back() == '>') {
                 const int hi = t[3], lo = t[4];
                 auto hex = [](int c) { return c >= '0' && c <= '9' ? c - '0'
@@ -575,9 +644,8 @@ int Vocab::load(VocabBuild b) {
         }
     }
 
-    /* Longest first. Special-token partitioning scans the text once per special token, and a
-     * shorter token that is a prefix of a longer one would otherwise cut the longer one in half
-     * -- "<|im_start|>" losing to "<|im" is the classic version of this bug. */
+    /* Longest first: this is SpecialMatcher's priority order, so a shorter token that is a prefix
+     * of a longer one ("<|im" vs "<|im_start|>") never cuts it. */
     std::sort(special_.begin(), special_.end(), [&](int32_t x, int32_t y) {
         const size_t nx = b_.tokens[x].size(), ny = b_.tokens[y].size();
         return nx != ny ? nx > ny : x < y;
@@ -585,39 +653,30 @@ int Vocab::load(VocabBuild b) {
 
     /* ------------------------------------------------------------------ end of generation
      *
-     * A MODEL ENDS ITS TURN ON MORE THAN ONE TOKEN AND THE CONTAINER CARRIES ROOM FOR ONE. The
-     * header has `eos` and `eot` and nothing else, but a Qwen container declares
-     * eos_token_id: [<|im_end|>, <|endoftext|>] and will end a turn on either -- and its
-     * `<|endoftext|>` lands in `pad_id`, which nothing treats as terminal. The engine then
-     * generates straight past the end of the turn into a hallucinated next one, which does not
-     * read as a bug: it reads as a model that rambles.
+     * A model can end its turn on several tokens, but the header has only `eos` and `eot`. A Qwen
+     * container declares eos_token_id: [<|im_end|>, <|endoftext|>], and its `<|endoftext|>` lands
+     * in `pad_id`, which is not terminal; without it, generation runs past the turn into an
+     * invented next one.
      *
-     * So the set is completed here, from the ONE piece of evidence in the container that is not a
-     * guess -- a CONTROL token whose spelling is a known end-of-generation marker. Both halves of
-     * that matter. Restricting it to control tokens means ordinary text can never become
-     * terminal, and matching an explicit list of spellings rather than a pattern means a token
-     * named `<|end_of_thinking|>` does not silently end generations. This is the same list, and
-     * the same reasoning, that llama.cpp's vocabulary loader applies.
-     *
-     * WHAT IS ADDED IS LOGGED. A token that silently gained the power to end every generation is
-     * exactly the kind of change that should be visible in a startup log, so it is. */
+     * The set is completed from control tokens whose spelling is a known end-of-generation
+     * marker (llama.cpp's loader uses the same list). Only control tokens qualify, so ordinary
+     * text never becomes terminal, and the list is explicit rather than a pattern, so a token
+     * like `<|end_of_thinking|>` does not end generations. Every addition is logged. */
     eog_.clear();
     if (b_.eos >= 0) eog_.push_back(b_.eos);
     if (b_.eot >= 0 && b_.eot != b_.eos) eog_.push_back(b_.eot);
     {
-        /* Gemma 4 ends a turn on `` and a tool-calling turn on `<|tool_response>` -- the
-         * opener of the result the CALLER supplies, which the model writes after its last
-         * `` -- and declares neither: its eos is ``. llama.cpp's loader lists
-         * both for it, and both are control tokens nothing else spells. */
+        /* Gemma 4 ends a turn on ``, and a tool-calling turn on `<|tool_response>` (the
+         * opener of the caller's result, written after its last ``), but declares
+         * only ``. llama.cpp's loader lists both; both are control tokens. */
         static const char* const kEogNames[] = {
             "<|endoftext|>", "<|im_end|>", "<|eot_id|>", "<|end_of_text|>", "",
             "<|end|>", "<|EOT|>", "<|eom_id|>", "<|return|>", "", "",
             "", "<|tool_response>",
         };
-        /* `` IS A DOCUMENT'S END, NOT A TURN'S. A vocabulary with a turn marker of its own
-         * ends a reply on that marker, and there `` -- where it is a control token at all
-         * and not the declared eos -- is text a reply may write: Gemma 4 spells the HTML tag with
-         * it. So it joins the set only in a vocabulary that has no turn marker. */
+        /* `` ends a document, not a turn. In a vocabulary with its own turn marker, a
+         * control `` that is not the declared eos is text a reply may write (Gemma 4 spells
+         * the HTML tag with it), so it joins the set only when there is no turn marker. */
         static const char* const kTurnEnds[] = {
             "<|im_end|>", "<|eot_id|>", "", "<|end|>", "<|EOT|>", "",
         };
@@ -642,11 +701,10 @@ int Vocab::load(VocabBuild b) {
                      "neither as eos nor eot; without this a turn ending on it runs on)",
                      added.c_str());
 
-        /* AND WHAT THE CHECKPOINT ITSELF NAMES. generation_config.json's eos_token_id is the
-         * model's own list of tokens a generation ends on, and the one that is not a guess:
-         * Gemma 4 names <|tool_response> there beside  and , because after its calls
-         * the model writes it and waits for the response -- a turn that runs past it answers
-         * its own call. Every id in range is honoured, as transformers honours them. */
+        /* Plus the checkpoint's own list, generation_config.json's eos_token_id. Gemma 4 names
+         * <|tool_response> there beside  and : after a call the model writes it and
+         * waits, and a turn that runs past it answers its own call. Every id in range is
+         * honoured, as in transformers. */
         std::string named;
         for (int32_t id : b_.eos_ids) {
             if (id < 0 || id >= (int32_t)b_.tokens.size()) continue;
@@ -659,9 +717,7 @@ int Vocab::load(VocabBuild b) {
                      "generation_config.json)", named.c_str());
     }
 
-    /* The encoder: the chain compiled and the tables flattened. A pattern the regex compiler
-     * refuses refuses the vocab, with the construct named -- there is no slower matcher to hand
-     * it to instead. */
+    /* A pattern the regex compiler refuses fails the vocab load, with the construct named. */
     enc_ = std::make_shared();
     RAD_TRY(enc_->build(b_, special_));
 
@@ -729,8 +785,7 @@ std::string step_describe(const VocabStep& s) {
             return fmt("ByteLevel(add_prefix_space=%d use_regex=%d)",
                        (s.flags & 1) ? 1 : 0, (s.flags & 2) ? 1 : 0);
         case RAD_PRE_SPLIT: {
-            /* What the pattern compiled to is part of the description: the size of its DFA, or
-             * the construct that refused it. */
+            /* Includes the compiled DFA's size, or the construct that refused it. */
             std::unique_ptr re;
             std::string why;
             const std::string dfa = TokRegex::compile(s.arg0, &re, &why) < 0
@@ -742,7 +797,11 @@ std::string step_describe(const VocabStep& s) {
         case RAD_PRE_METASPACE:
             return fmt("Metaspace('%s' prepend=%lld split=%d)", s.arg0.c_str(),
                        (long long)s.iarg, (s.flags & 1) ? 1 : 0);
-        case RAD_PRE_WHITESPACE:   return "Whitespace";
+        case RAD_PRE_WHITESPACE:
+            return s.flags == kPreWhitespaceSplit ? "WhitespaceSplit"
+                 : s.flags == kPreBert            ? "BertPreTokenizer"
+                 : s.flags == kPreWhitespace      ? "Whitespace"
+                                                  : fmt("Whitespace(flags=%u)", s.flags);
         case RAD_PRE_PUNCTUATION:  return fmt("Punctuation(behavior=%lld)", (long long)s.iarg);
         case RAD_PRE_DIGITS:
             return fmt("Digits(individual=%d)", (s.flags & 1) ? 1 : 0);
@@ -751,6 +810,10 @@ std::string step_describe(const VocabStep& s) {
         case RAD_DEC_METASPACE:
             return fmt("decode Metaspace('%s' prepend=%lld)", s.arg0.c_str(), (long long)s.iarg);
         case RAD_DEC_REPLACE:
+            if (s.flags & kDecWordPiece)
+                return fmt("decode WordPiece(prefix='%s' cleanup=%d)", s.arg0.c_str(),
+                           (s.flags & kDecWordPieceCleanup) ? 1 : 0);
+            if (s.flags & kDecBpeSuffix) return fmt("decode BPEDecoder(suffix='%s')", s.arg0.c_str());
             return fmt("decode Replace('%s' -> '%s')", s.arg0.c_str(), s.arg1.c_str());
         case RAD_DEC_STRIP:
             return fmt("decode Strip('%s' start=%lld stop=%lld)", s.arg0.c_str(),
@@ -781,8 +844,7 @@ void apply_norm(std::string& text, const TokEncoder::Step& st) {
             break;
         }
         case RAD_NORM_STRIP: {
-            /* Whitespace by the unicode definition, not isspace(): a non-breaking space in a
-             * pasted prompt is whitespace to HuggingFace and would not be to isspace(). */
+            /* Unicode whitespace, not isspace(): HuggingFace strips a non-breaking space too. */
             std::vector cpts = unicode_cpts_from_utf8(text);
             size_t a = 0, b = cpts.size();
             if (s.flags & 1) while (a < b && unicode_cpt_flags_from_cpt(cpts[a]).is_whitespace) ++a;
@@ -794,8 +856,8 @@ void apply_norm(std::string& text, const TokEncoder::Step& st) {
         }
         case RAD_NORM_REPLACE:
             if (s.flags & 1) {
-                /* HuggingFace's Replace: every match of the compiled pattern becomes the content,
-                 * verbatim -- the content is text, not a substitution template. */
+                /* HuggingFace's Replace: each match becomes the content verbatim (text, not a
+                 * substitution template). */
                 std::string canon, out;
                 std::string_view v = text;
                 if (!utf8_is_canonical(v)) { utf8_canonicalize(v, canon); v = canon; }
@@ -806,18 +868,14 @@ void apply_norm(std::string& text, const TokEncoder::Step& st) {
             }
             break;
         case RAD_NORM_PREPEND: text = s.arg0 + text; break;
-        default:
-            RAD_WARN("tokenizer: normaliser step %u is not implemented; text passed through",
-                     s.kind);
-            break;
     }
 }
 
 /* --- pre-tokenisers ----------------------------------------------------------------------
  *
- * The pieces are spans of one buffer rather than a string each: a 500 KB prompt is 150,000
- * pieces, and a string each would be 150,000 allocations. A step that has to rewrite text
- * appends the new text to the buffer (or builds a new buffer) and points its spans there. */
+ * Pieces are spans of one buffer, not a string each, to avoid an allocation per piece (a 500 KB
+ * prompt is about 150,000 pieces). A step that rewrites text appends it to the buffer (or builds
+ * a new buffer) and points its spans there. */
 
 struct Pieces {
     std::string          buf;
@@ -835,9 +893,9 @@ struct EncodeScratch {
     std::vector  syms;
 };
 
-/* One Split step over every piece. The pieces it produces are canonical UTF-8: a piece that is
- * not is decoded and re-encoded first -- invalid bytes to U+FFFD, overlong forms shortest -- piece
- * by piece, by the rules of the decoder the other steps use (utf8_canonicalize). */
+/* One Split step over every piece. The output pieces are canonical UTF-8: a piece that is not is
+ * first re-encoded by utf8_canonicalize (invalid bytes to U+FFFD, overlong forms shortest), the
+ * same rules the other steps' decoder uses. */
 void apply_split(Pieces& p, const TokRegex& re, int behavior, bool invert, EncodeScratch& sc) {
     if (!p.canonical) p.canonical = utf8_is_canonical(p.buf);
     const bool whole = p.canonical;
@@ -880,6 +938,14 @@ std::vector words_of(const Pieces& p) {
     return w;
 }
 
+/* A step that rewrites words: the pieces as words, `f` over them, the pieces rebuilt. */
+template 
+void rewrite(Pieces& p, F&& f) {
+    std::vector w = words_of(p);
+    f(w);
+    rebuild(p, w);
+}
+
 void apply_bytelevel(Pieces& p, const TokEncoder::Step& st, bool defer, EncodeScratch& sc) {
     const bool add_prefix_space = (st.step.flags & 1) != 0;
     if (add_prefix_space && !p.spans.empty() && p.spans[0].end > p.spans[0].begin &&
@@ -888,24 +954,26 @@ void apply_bytelevel(Pieces& p, const TokEncoder::Step& st, bool defer, EncodeSc
         p.spans[0] = { (uint32_t)p.buf.size(), (uint32_t)(p.buf.size() + first.size()) };
         p.buf += first;
     }
-    /* HuggingFace's ByteLevel carries the GPT-2 pattern inside it. rad-convert normally splits
-     * that out into an explicit Split step so the chain reads as what it does, but a chain that
-     * declares it inline still has to work. */
+    /* HuggingFace's ByteLevel carries the GPT-2 pattern inside it. rad-convert normally emits it
+     * as an explicit Split step, but a chain that declares it inline must still work. */
     if (st.re) apply_split(p, *st.re, TOK_SPLIT_ISOLATED, false, sc);
     if (defer) return;
-    std::vector w = words_of(p);
-    for (std::string& x : w) x = byte_encode(x);
-    rebuild(p, w);
+    rewrite(p, [](std::vector& w) {
+        for (std::string& x : w) x = byte_encode(x);
+    });
 }
 
-void apply_metaspace(std::vector& words, const VocabStep& s) {
+/* `at_start`: the words are the text's first segment. HuggingFace's "first" scheme prepends only
+ * there (a segment after a special token has a non-zero original offset); "always" prepends to
+ * every segment. */
+void apply_metaspace(std::vector& words, const VocabStep& s, bool at_start) {
     const std::string rep = s.arg0.empty() ? std::string(k_metaspace) : s.arg0;
     const int64_t prepend = s.iarg;            /* 0 never, 1 first, 2 always */
     const bool    split   = (s.flags & 1) != 0;
 
     for (size_t i = 0; i < words.size(); ++i) {
         std::string& w = words[i];
-        if (prepend == 2 || (prepend == 1 && i == 0)) {
+        if (prepend == 2 || (prepend == 1 && i == 0 && at_start)) {
             if (w.empty() || w.compare(0, 1, " ") != 0) w.insert(0, " ");
         }
         replace_all(w, " ", rep);
@@ -925,82 +993,10 @@ void apply_metaspace(std::vector& words, const VocabStep& s) {
     words.swap(out);
 }
 
-/* Whitespace pre-tokeniser: HuggingFace's is the regex \w+|[^\w\s]+ with Isolated behaviour,
- * written here over the category flags. */
-void apply_whitespace(std::vector& words) {
-    std::vector out;
-    for (const std::string& w : words) {
-        const std::vector cpts = unicode_cpts_from_utf8(w);
-        size_t i = 0;
-        while (i < cpts.size()) {
-            const auto f = unicode_cpt_flags_from_cpt(cpts[i]);
-            if (f.is_whitespace) { ++i; continue; }
-            const bool word = f.is_letter || f.is_number || cpts[i] == '_';
-            size_t j = i;
-            while (j < cpts.size()) {
-                const auto g = unicode_cpt_flags_from_cpt(cpts[j]);
-                if (g.is_whitespace) break;
-                const bool wj = g.is_letter || g.is_number || cpts[j] == '_';
-                if (wj != word) break;
-                ++j;
-            }
-            std::string piece;
-            for (size_t k = i; k < j; ++k) piece += unicode_cpt_to_utf8(cpts[k]);
-            out.push_back(std::move(piece));
-            i = j;
-        }
-    }
-    words.swap(out);
-}
-
-void apply_punctuation(std::vector& words, const VocabStep& s) {
-    const int64_t behavior = s.iarg;
-    std::vector out;
-    for (const std::string& w : words) {
-        const std::vector cpts = unicode_cpts_from_utf8(w);
-        std::string acc;
-        for (uint32_t c : cpts) {
-            const auto f = unicode_cpt_flags_from_cpt(c);
-            const bool punct = f.is_punctuation || f.is_symbol;
-            if (punct) {
-                if (!acc.empty()) { out.push_back(acc); acc.clear(); }
-                if (behavior != TOK_SPLIT_REMOVED) out.push_back(unicode_cpt_to_utf8(c));
-            } else {
-                acc += unicode_cpt_to_utf8(c);
-            }
-        }
-        if (!acc.empty()) out.push_back(acc);
-    }
-    words.swap(out);
-}
-
-void apply_digits(std::vector& words, const VocabStep& s) {
-    const bool individual = (s.flags & 1) != 0;
-    std::vector out;
-    for (const std::string& w : words) {
-        const std::vector cpts = unicode_cpts_from_utf8(w);
-        std::string acc;
-        bool acc_digit = false;
-        for (uint32_t c : cpts) {
-            const bool d = unicode_cpt_flags_from_cpt(c).is_number;
-            if (acc.empty()) { acc_digit = d; acc += unicode_cpt_to_utf8(c); continue; }
-            if (d != acc_digit || (d && individual)) {
-                out.push_back(acc);
-                acc.clear();
-                acc_digit = d;
-            }
-            acc += unicode_cpt_to_utf8(c);
-        }
-        if (!acc.empty()) out.push_back(acc);
-    }
-    words.swap(out);
-}
-
 /* --- models ------------------------------------------------------------------------------ */
 
-/* Word -> ids within one encode() call. Prose and code repeat their words heavily, so most words
- * are merged once per call and then copied; the ids depend on nothing but the word, so the copy
- * is exact. */
+/* Word -> ids within one encode() call. Prose and code repeat words heavily, so most words are
+ * merged once per call and then copied; ids depend only on the word, so the copy is exact. */
 class WordCache {
 public:
     static constexpr size_t kMaxKey = 128;
@@ -1054,24 +1050,21 @@ private:
     }
 };
 
-/* One word through the merge. The ids a symbol carries are the LOWEST id spelling its text, which
- * is what the merge table is keyed on and what the word finally emits. */
+/* One word through the merge. A symbol carries the lowest id spelling its text, which is what the
+ * merge table is keyed on and what the word emits. */
 void bpe_word(const TokEncoder& e, std::string_view w, std::vector& out,
               EncodeScratch& sc) {
     const bool raw = e.defer_bytelevel >= 0;
     const TokTable& table = raw ? e.raw : e.text;
 
-    /* A user-defined token is taken whole rather than re-split. Added tokens are exact strings
-     * the vocabulary promises to round-trip; decomposing one into codepoints and merging back
-     * can land on a different sequence, because the merge table was never fitted over them.
+    /* A user-defined token is taken whole: added tokens must round-trip, and the merge table was
+     * never fitted over them, so re-merging can give a different sequence.
      *
-     * ORDINARY VOCABULARY ENTRIES GO THROUGH THE MERGE LOOP unless the vocabulary sets
-     * `ignore_merges`, which is HuggingFace's short-circuit for a word that is already a token:
-     * the merge table can reach a different split of a rare word than the entry it ships. The
-     * word is the pre-token after the declared chain, and the raw-byte table looks the same entry
-     * up under its byte spelling. A CONTROL entry is not taken whole even then: one that reaches
-     * this loop is text the caller asked to have read as text, and the flag must not turn it back
-     * into the marker. */
+     * Ordinary entries go through the merge loop unless the vocab sets `ignore_merges`,
+     * HuggingFace's short-circuit for a pre-token that is already a token (the merges can reach a
+     * different split of a rare word). The raw-byte table finds the same entry by its byte
+     * spelling. A control entry is never taken whole: reaching here means the caller asked for
+     * it to be read as text. */
     const int32_t whole = table.find(w);
     if (whole >= 0 && (e.types[whole] == RAD_TT_USER_DEFINED ||
                        (e.ignore_merges && e.types[whole] != RAD_TT_CONTROL))) {
@@ -1107,9 +1100,9 @@ void bpe_word(const TokEncoder& e, std::string_view w, std::vector& out
         if (s.id >= 0) { out.push_back(s.id); continue; }
         const std::string_view str = w.substr(s.start, s.len);
 
-        /* Miss. Decompose into single-byte tokens; how a byte is SPELT depends on the chain.
-         * Under ByteLevel every byte is already its own mapped codepoint, so the piece splits at
-         * codepoint boundaries; under byte fallback it is "<0xNN>". */
+        /* Miss: decompose into byte tokens, spelt per the chain. Under ByteLevel each byte is its
+         * own mapped codepoint, so the piece splits at codepoint boundaries; under byte fallback
+         * a byte is "<0xNN>". */
         if (raw) {
             for (unsigned char c : str) {
                 const int32_t b = e.byte_sym[c];
@@ -1147,8 +1140,8 @@ void bpe(const TokEncoder& e, const Pieces& p, std::vector& out, Encode
     for (const TokSpan& s : p.spans) {
         const std::string_view w = p.at(s);
         if (w.empty()) continue;
-        /* A one-byte word of a byte-level vocab is the token of that byte: the whole-word lookup
-         * and the merge both land on byte_sym, and a missing one is the fallback's warning. */
+        /* A one-byte word of a byte-level vocab is that byte's token; the lookup and the merge
+         * would both land on byte_sym. A missing one takes the warning path in bpe_word. */
         if (raw && w.size() == 1 && e.byte_sym[(unsigned char)w[0]] >= 0) {
             out.push_back(e.byte_sym[(unsigned char)w[0]]);
             continue;
@@ -1162,9 +1155,9 @@ void bpe(const TokEncoder& e, const Pieces& p, std::vector& out, Encode
     }
 }
 
-/* Unigram, by Viterbi over a prefix trie -- SentencePiece's algorithm, in shape from
- * llama.cpp's llm_tokenizer_ugm_session. Scores are summed in double precision because the
- * reference implementation does and the argmax genuinely differs in float on long inputs. */
+/* Unigram by Viterbi, SentencePiece's algorithm, shaped after llama.cpp's
+ * llm_tokenizer_ugm_session. Scores are summed in double as the reference does; in float the
+ * argmax differs on long inputs. */
 void unigram(const Vocab& v, const TokEncoder& e, const std::string& text,
              std::vector& out) {
     if (text.empty()) return;
@@ -1174,20 +1167,12 @@ void unigram(const Vocab& v, const TokEncoder& e, const std::string& text,
     std::vector best(n + 1, { v.unk(), 0, -DBL_MAX });
     best[0] = { v.unk(), 0, 0.0 };
 
-    /* The unknown-token penalty: SentencePiece uses (min score - 10). Recomputing it here rather
-     * than storing it keeps the .rad from carrying a derived number that could disagree. */
-    double unk_penalty = 0.0;
-    if (!v.build().scores.empty()) {
-        unk_penalty = *std::min_element(v.build().scores.begin(), v.build().scores.end()) - 10.0;
-    }
-
     for (size_t i = 0; i < n; ) {
         const size_t cp_len = std::min(unicode_len_utf8(text[i]), n - i);
         bool matched_whole_cp = false;
-        /* Longest-prefix scan. A trie would beat this on a large vocab; the substring lookup is
-         * O(len) with a bounded len because no vocab entry is longer than the longest token, and
-         * that bound is what keeps it linear. */
-        const size_t max_len = std::min(n - i, (size_t)256);
+        /* Prefix scan by hash lookup, up to the longest token. A trie would be faster on a large
+         * vocab. */
+        const size_t max_len = std::min(n - i, e.longest);
         for (size_t l = 1; l <= max_len; ++l) {
             const int32_t id = e.text.find(std::string_view(text.data() + i, l));
             if (id < 0) continue;
@@ -1197,17 +1182,16 @@ void unigram(const Vocab& v, const TokEncoder& e, const std::string& text,
             if (cand > best[i + l].score) best[i + l] = { id, i, cand };
         }
         if (!matched_whole_cp) {
-            const double cand = best[i].score + unk_penalty;
+            const double cand = best[i].score + e.unk_penalty;
             if (cand > best[i + cp_len].score) best[i + cp_len] = { v.unk(), i, cand };
         }
         i += cp_len;
     }
 
-    /* A VOCABULARY WITH NO UNK TOKEN HAS NO ID FOR TEXT NO PIECE COVERS, and the Viterbi above
-     * still routes such text through the unk transition -- whose id is then -1, which is not a
-     * token and must never reach the output. The span is spelled as byte tokens when the chain
-     * declares byte fallback and dropped otherwise, as bpe() does with a piece it cannot match.
-     * Built back to front like the rest of the backtrack, so the bytes go in reversed. */
+    /* Without an unk token, uncovered text still takes the unk transition above, with id -1,
+     * which must never reach the output. Such a span is spelt as byte tokens when the chain
+     * declares byte fallback and dropped otherwise, as in bpe(). The backtrack runs back to
+     * front, so the bytes go in reversed. */
     const int32_t unk = v.unk();
     const bool byte_fallback = unk < 0 && e.byte_fallback;
 
@@ -1238,36 +1222,47 @@ void unigram(const Vocab& v, const TokEncoder& e, const std::string& text,
                  byte_fallback ? "lacks a byte token for them" : "declares no byte fallback");
 }
 
-/* WordPiece: greedy longest-match-first with a continuation prefix. Kept because BERT-family
- * embedding models are a real deployment and they are all WordPiece; it is 30 lines. */
+/* WordPiece: greedy longest-match-first with a "##" continuation prefix, for BERT-family
+ * embedding models. */
+constexpr size_t kWordPieceMaxChars = 100;
+
 void wordpiece(const Vocab& v, const TokEncoder& e, const Pieces& p, std::vector& out) {
+    std::string cont;               /* "##" and the rest of the word, reused for every piece */
+    std::vector piece;
     for (const TokSpan& s : p.spans) {
-        const std::string w(p.at(s));
+        const std::string_view w = p.at(s);
         if (w.empty()) continue;
-        size_t i = 0;
-        std::vector piece;
-        bool ok = true;
-        while (i < w.size()) {
-            size_t j = w.size();
-            int32_t id = -1;
-            for (; j > i; --j) {
-                std::string sub = w.substr(i, j - i);
-                if (i > 0) sub = "##" + sub;
-                id = e.text.find(sub);
-                if (id >= 0) break;
+        piece.clear();
+        /* HuggingFace's max_input_chars_per_word: a longer word is one unknown token. */
+        size_t n_chars = 0;
+        for (unsigned char ch : w) n_chars += (ch & 0xC0) != 0x80;
+        bool ok = n_chars <= kWordPieceMaxChars;
+        for (size_t i = 0; ok && i < w.size(); ) {
+            /* Longest first; a piece after the first is looked up with "##" in front. */
+            std::string_view rest = w.substr(i);
+            if (i > 0) {
+                cont.assign("##");
+                cont.append(rest);
+                rest = cont;
             }
+            const size_t pre = i > 0 ? 2 : 0;
+            size_t len = rest.size();
+            int32_t id = -1;
+            for (; len > pre; --len)
+                if ((id = e.text.find(rest.substr(0, len))) >= 0) break;
             if (id < 0) { ok = false; break; }
             piece.push_back(id);
-            i = j;
+            i += len - pre;
         }
         if (ok) out.insert(out.end(), piece.begin(), piece.end());
         else if (v.unk() >= 0) out.push_back(v.unk());
     }
 }
 
-/* One segment -- the text between two special tokens -- through the whole chain. */
+/* One segment -- the text between two special tokens -- through the whole chain. `at_start`:
+ * the segment begins the text (see apply_metaspace). */
 int encode_segment(const Vocab& v, const TokEncoder& e, std::string_view seg,
-                   std::vector& out, EncodeScratch& sc, WordCache& words) {
+                   std::vector& out, EncodeScratch& sc, WordCache& words, bool at_start) {
     Pieces& p = sc.p;
     p.buf.assign(seg.data(), seg.size());
     for (const TokEncoder::Step& st : e.norm) apply_norm(p.buf, st);
@@ -1287,37 +1282,26 @@ int encode_segment(const Vocab& v, const TokEncoder& e, std::string_view seg,
             case RAD_PRE_BYTELEVEL:
                 apply_bytelevel(p, st, (int)k == e.defer_bytelevel, sc);
                 break;
-            case RAD_PRE_METASPACE: {
-                std::vector w = words_of(p);
-                apply_metaspace(w, st.step);
-                rebuild(p, w);
+            case RAD_PRE_METASPACE:
+                rewrite(p, [&](std::vector& w) { apply_metaspace(w, st.step, at_start); });
                 break;
-            }
-            case RAD_PRE_WHITESPACE: {
-                std::vector w = words_of(p);
-                apply_whitespace(w);
-                rebuild(p, w);
+            case RAD_PRE_WHITESPACE:
+                if (st.step.flags == kPreWhitespace) {
+                    apply_split(p, *st.re, TOK_SPLIT_REMOVED, /*invert=*/true, sc);
+                } else {
+                    apply_split(p, *st.re, TOK_SPLIT_REMOVED, false, sc);
+                    if (st.re2) apply_split(p, *st.re2, TOK_SPLIT_ISOLATED, false, sc);
+                }
                 break;
-            }
-            case RAD_PRE_PUNCTUATION: {
-                std::vector w = words_of(p);
-                apply_punctuation(w, st.step);
-                rebuild(p, w);
+            case RAD_PRE_PUNCTUATION:
+                apply_split(p, *st.re, (int)st.step.iarg, false, sc);
                 break;
-            }
-            case RAD_PRE_DIGITS: {
-                std::vector w = words_of(p);
-                apply_digits(w, st.step);
-                rebuild(p, w);
+            case RAD_PRE_DIGITS:
+                apply_split(p, *st.re, TOK_SPLIT_ISOLATED, false, sc);
                 break;
-            }
             case RAD_PRE_BYTE_FALLBACK:
-                /* A declaration about what the MODEL does with an unknown piece, not a split.
-                 * The fallback itself lives in bpe_word, where the miss happens. */
+                /* Declares how an unknown piece is encoded, not a split; bpe_word handles it. */
                 break;
-            default:
-                RAD_ERR("tokenizer: pre-tokeniser step %u is not implemented", st.step.kind);
-                return RAD_E_UNSUPPORTED;
         }
     }
 
@@ -1325,8 +1309,8 @@ int encode_segment(const Vocab& v, const TokEncoder& e, std::string_view seg,
         case RAD_TOK_BPE:       bpe(e, p, out, sc, words); break;
         case RAD_TOK_WORDPIECE: wordpiece(v, e, p, out); break;
         case RAD_TOK_UNIGRAM: {
-            /* Unigram runs Viterbi over the whole normalised segment; the pre-tokeniser's job
-             * there is only to insert the metaspace, so the pieces are rejoined. */
+            /* Unigram runs Viterbi over the whole segment; its pre-tokeniser only inserts the
+             * metaspace, so the pieces are rejoined. */
             std::string joined;
             for (const TokSpan& s : p.spans) joined += p.at(s);
             unigram(v, e, joined, out);
@@ -1361,19 +1345,14 @@ int Tokenizer::encode(std::string_view text, std::vector& out,
     if (!v_ || !v_->ready()) return RAD_E_STATE;
     const TokEncoder& e = *v_->enc_;
 
-    /* Special-token partitioning. The text is cut into (raw, token, raw, token, ...) around any
-     * declared special token that appears literally, before any other step touches it, because a
-     * special token is not something the pre-tokeniser is allowed to split.
-     *
-     * `parse_special == false` means a control token typed by a user is ordinary text. That is
-     * not a nicety: without it, user content containing "<|im_start|>system" reaches the model
-     * as an actual role switch. */
+    /* Cut the text into (raw, token, raw, ...) around special tokens before any other step, so
+     * the pre-tokeniser never splits one. With parse_special off, control tokens are ordinary
+     * text (see encode() in tokenizer.h). */
     std::vector frags;
     e.specials.split(text, parse_special, frags);
 
-    /* A text that already opens with BOS gets no second one. A client that renders its own chat
-     * template writes the template's BOS into the prompt, and a doubled BOS is a sequence the
-     * model never saw in training. */
+    /* No second BOS when the text already opens with one (a client-rendered chat template); a
+     * doubled BOS is a sequence the model never saw in training. */
     if (add_special && v_->add_bos() && v_->bos() >= 0) {
         int32_t first = -1;
         for (const SpecialFrag& f : frags) {
@@ -1390,14 +1369,17 @@ int Tokenizer::encode(std::string_view text, std::vector& out,
         if (f.id >= 0) { out.push_back(f.id); continue; }
         if (f.len == 0) continue;
         const std::string_view seg = text.substr(f.off, f.len);
-        if (!use_cache_ || seg.size() < kSegmentCacheMin) {
-            RAD_TRY(encode_segment(*v_, e, seg, out, sc, words));
+        /* The cache is keyed on the segment's bytes, so a segment whose ids also depend on
+         * starting the text bypasses it. */
+        const bool at_start = f.off == 0;
+        if (!use_cache_ || seg.size() < kSegmentCacheMin || (at_start && e.prepend_first)) {
+            RAD_TRY(encode_segment(*v_, e, seg, out, sc, words, at_start));
             continue;
         }
         const uint64_t h = tok_hash(seg);
         if (e.cache.lookup(seg, h, out)) continue;
         const size_t start = out.size();
-        RAD_TRY(encode_segment(*v_, e, seg, out, sc, words));
+        RAD_TRY(encode_segment(*v_, e, seg, out, sc, words, at_start));
         e.cache.insert(seg, h, out.data() + start, out.size() - start);
     }
 
@@ -1420,34 +1402,108 @@ void Tokenizer::clear_cache() const {
 /* ================================================================== decode */
 
 std::string Tokenizer::piece(int32_t id, bool render_special) const {
+    return piece_at(id, render_special, At{});
+}
+
+namespace {
+
+/* HuggingFace's WordPiece `cleanup`, on one token: spaced punctuation and contractions closed. */
+void wordpiece_cleanup(std::string& s) {
+    static const char* const kPairs[][2] = {
+        { " .", "." }, { " ?", "?" }, { " !", "!" }, { " ,", "," }, { " ' ", "'" },
+        { " n't", "n't" }, { " 'm", "'m" }, { " do not", " don't" }, { " 's", "'s" },
+        { " 've", "'ve" }, { " 're", "'re" },
+    };
+    for (const auto& p : kPairs) replace_all(s, p[0], p[1]);
+}
+
+/* A Strip after Fuse strips the decoded text as a whole; HuggingFace's Fuse joins the tokens into
+ * one before it. Returns how many leading copies of `*content` it strips, 0 when there is none.
+ * Vocab::load refuses one that strips the end, which a stream cannot take back. */
+int fused_strip(const Vocab& v, std::string* content) {
+    bool fused = false;
+    for (const VocabStep& st : v.steps()) {
+        if (st.kind == RAD_DEC_FUSE) fused = true;
+        if (st.kind != RAD_DEC_STRIP || !fused) continue;
+        *content = st.arg0.empty() ? std::string(" ") : st.arg0;
+        return (int)(st.iarg & 0xFFFFFFFF);
+    }
+    return 0;
+}
+
+/* Up to `*left` leading copies of `c` removed from `s`; `*left` drops to 0 once `s` shows a
+ * character that is not `c`, since HuggingFace's Strip stops there. */
+void strip_leading(std::string& s, const std::string& c, int* left) {
+    size_t at = 0;
+    while (*left > 0 && s.size() - at >= c.size() && s.compare(at, c.size(), c) == 0) {
+        at += c.size();
+        --*left;
+    }
+    s.erase(0, at);
+    if (!s.empty()) *left = 0;
+}
+
+/* Whether a decode leaves the token out, as HuggingFace's skip_special_tokens does. */
+bool left_out(const Vocab& v, int32_t id, bool render_special) {
+    const uint8_t t = v.type(id);
+    return !render_special && (t == RAD_TT_CONTROL || t == RAD_TT_UNKNOWN);
+}
+
+bool has_bpe_suffix(const Vocab& v) {
+    for (const VocabStep& st : v.steps())
+        if (st.kind == RAD_DEC_REPLACE && (st.flags & kDecBpeSuffix)) return true;
+    return false;
+}
+
+}  /* namespace */
+
+std::string Tokenizer::piece_at(int32_t id, bool render_special, At at) const {
     if (!v_ || !v_->ready()) return {};
     if (id < 0 || id >= v_->n_tokens()) return {};
 
     const uint8_t t = v_->type(id);
     if (!render_special && (t == RAD_TT_CONTROL || t == RAD_TT_UNKNOWN)) return {};
 
-    /* A byte token is one byte and no decoder step applies to it -- running ByteLevel over
-     * "<0x0A>" would produce the literal text. */
+    /* A byte token is one byte and skips the decoder chain; ByteLevel over "<0x0A>" would give
+     * the literal text. */
     const int32_t b = v_->token_byte(id);
     if (b >= 0) return std::string(1, (char)b);
 
     std::string s = v_->text(id);
-    /* A user-defined or control token is stored as the literal text it stands for; only NORMAL
-     * tokens are in the vocab's own encoding and need the decoder chain. */
+    /* User-defined and control tokens are stored as literal text; only normal tokens are in the
+     * vocab's own encoding and need the decoder chain. */
     if (t == RAD_TT_CONTROL || t == RAD_TT_UNKNOWN || t == RAD_TT_USER_DEFINED) return s;
 
-    bool any = false;
+    /* No declared decoder means the tokens are already text (true for unigram and wordpiece, not
+     * byte-level BPE). rad-convert emits the chain it read, so the absence is declared. */
+    bool fused = false;
     for (const VocabStep& st : v_->steps()) {
         if (!step_is_dec(st.kind)) continue;
-        any = true;
         switch (st.kind) {
             case RAD_DEC_BYTELEVEL: s = byte_decode(s); break;
             case RAD_DEC_METASPACE:
-                replace_all(s, st.arg0.empty() ? std::string(k_metaspace) : st.arg0, " ");
+                replace_all(s, st.arg0.empty() ? std::string_view(k_metaspace) : st.arg0,
+                            at.first && st.iarg != 0 ? "" : " ");
+                break;
+            case RAD_DEC_REPLACE:
+                if (st.flags & kDecWordPiece) {
+                    if (!at.first) {
+                        if (!st.arg0.empty() && s.compare(0, st.arg0.size(), st.arg0) == 0)
+                            s.erase(0, st.arg0.size());
+                        else
+                            s.insert(0, " ");
+                    }
+                    if (st.flags & kDecWordPieceCleanup) wordpiece_cleanup(s);
+                } else if (st.flags & kDecBpeSuffix) {
+                    replace_all(s, st.arg0, at.last ? "" : " ");
+                } else {
+                    replace_all(s, st.arg0, st.arg1);
+                }
                 break;
-            case RAD_DEC_REPLACE:   replace_all(s, st.arg0, st.arg1); break;
             case RAD_DEC_STRIP: {
-                const std::string c = st.arg0.empty() ? std::string(" ") : st.arg0;
+                /* After Fuse it strips the whole text once (fused_strip), not every token. */
+                if (fused) break;
+                const std::string_view c = st.arg0.empty() ? std::string_view(" ") : st.arg0;
                 int32_t start = (int32_t)(st.iarg & 0xFFFFFFFF);
                 int32_t stop  = (int32_t)(st.iarg >> 32);
                 while (start-- > 0 && s.size() >= c.size() && s.compare(0, c.size(), c) == 0)
@@ -1458,26 +1514,33 @@ std::string Tokenizer::piece(int32_t id, bool render_special) const {
                 break;
             }
             case RAD_DEC_FUSE:
-            case RAD_DEC_BYTE_FALLBACK:
-                /* Both are sequence-level: Fuse concatenates adjacent pieces and ByteFallback
-                 * reassembles "<0xNN>" runs. Per-token there is nothing to do, and the
-                 * sequence-level behaviour is what Detokenizer's buffering already is. */
+                /* Fuse concatenates pieces, which streaming does anyway; it changes only how a
+                 * later Strip applies. */
+                fused = true;
                 break;
-            default:
-                RAD_WARN("tokenizer: decoder step %u is not implemented", st.kind);
+            case RAD_DEC_BYTE_FALLBACK:
+                /* Reassembling "<0xNN>" runs is Detokenizer's UTF-8 buffering. */
                 break;
         }
     }
-    /* A vocab with no declared decoder is a vocab whose tokens are already text -- which is
-     * true for unigram and wordpiece and false for byte-level BPE, so the absence is only safe
-     * when it was declared. It is; rad-convert emits the chain it read. */
-    (void)any;
     return s;
 }
 
 std::string Tokenizer::decode(const std::vector& ids, bool render_special) const {
     std::string out;
-    for (int32_t id : ids) out += piece(id, render_special);
+    if (!v_ || !v_->ready()) return out;
+    size_t last = ids.size();
+    for (size_t i = ids.size(); i-- > 0; )
+        if (!left_out(*v_, ids[i], render_special)) { last = i; break; }
+    bool first = true;
+    for (size_t i = 0; i < ids.size(); ++i) {
+        if (left_out(*v_, ids[i], render_special)) continue;
+        out += piece_at(ids[i], render_special, At{ first, i == last });
+        first = false;
+    }
+    std::string content;
+    int left = fused_strip(*v_, &content);
+    if (left > 0) strip_leading(out, content, &left);
     return out;
 }
 
@@ -1486,13 +1549,10 @@ std::string Tokenizer::decode(const std::vector& ids, bool render_speci
 Detokenizer::Detokenizer(std::shared_ptr v, std::vector stops,
                          bool render_special, const std::vector& preserved)
     : v_(std::move(v)), stops_(std::move(stops)), render_special_(render_special) {
-    /* RESOLVED BY TOKENISING THE MARKER, NOT BY LOOKING IT UP. What the chat format hands over
-     * are the MARKERS its parser scans for -- ``,
+     * ``), which are not necessarily tokens: MiniCPM5 spells the first as the control
+     * token `ready() && !preserved.empty()) {
         Tokenizer t;
         if (t.init(v_) >= 0) {
@@ -1502,12 +1562,10 @@ Detokenizer::Detokenizer(std::shared_ptr v, std::vector<|im_end|>` -- so a decoder that
-                     * drops `<|im_end|>` hands the parser a string its grammar can never
-                     * complete, and every tool call comes back as prose. The parser consumes it
-                     * on a match; core/server strips it on a miss. */
+                    /* The turn terminator is preserved too: a derived format can fold it into its
+                     * last marker (MiniCPM5's `<|im_end|>`), and without it the
+                     * parser's grammar never completes. The parser consumes it on a match;
+                     * core/server strips it on a miss. */
                     if (v_->type(id) == RAD_TT_CONTROL) preserved_.insert(id);
                 }
             }
@@ -1518,25 +1576,16 @@ Detokenizer::Detokenizer(std::shared_ptr v, std::vectorready()) {
+        strip_left_ = fused_strip(*v_, &strip_);
+        hold_space_ = has_bpe_suffix(*v_);
+    }
 }
 
-void Detokenizer::reset() {
-    pending_.clear();
-    all_.clear();
-    stopped_ = false;
-    stop_hit_.clear();
-    first_ = true;
-}
-
-/* How many bytes of pending_ are final.
- *
- * Two separate reasons to hold bytes back and they compose, so the answer is the smaller of the
- * two cut points:
- *   1. a trailing INCOMPLETE UTF-8 sequence. Byte-level BPE hands out one byte at a time, so a
- *      three-byte CJK codepoint arrives across three pushes. Emitting a lone continuation byte
- *      puts U+FFFD in the user's stream and there is no way to take it back.
- *   2. a trailing PROPER PREFIX of a stop string. "" arrives as ""; emitting "" arrives as "ready() || stopped_) return {};
 
-    /* One Tokenizer for the stream, set up on the first push: it holds the vocab's shared_ptr
-     * and nothing else, and piece() is a pure function of the vocab, so one built per push only
-     * added a reference-count round trip to every token. */
+    /* One Tokenizer per stream, set up on the first push, to avoid a shared_ptr refcount round
+     * trip per token; piece() depends only on the vocab. */
     if (!tok_ready_) {
         if (tok_.init(v_) < 0) return {};
         tok_ready_ = true;
     }
-    std::string p = tok_.piece(token, render_special_ ||
-                                          (!preserved_.empty() && preserved_.count(token) != 0));
-
-    /* HuggingFace's decoders strip the leading space that Metaspace's prepend added. Only the
-     * first piece of a stream can carry it, which is why this is a member flag and not a
-     * property of the piece. */
-    if (first_) {
-        first_ = false;
-        for (const VocabStep& s : v_->steps()) {
-            if (s.kind == RAD_DEC_METASPACE && s.iarg != 0 && !p.empty() && p[0] == ' ') {
-                p.erase(0, 1);
-                break;
-            }
-        }
-    }
+    const bool render = render_special_ || (!preserved_.empty() && preserved_.count(token) != 0);
+    /* The stream is decoded as HuggingFace decodes the whole list (Tokenizer::piece_at): the
+     * first token that is not left out reads as the first. A Strip after Fuse strips the stream's
+     * start. */
+    const bool counts = !left_out(*v_, token, render);
+    std::string p = tok_.piece_at(token, render, Tokenizer::At{ first_ && counts, false });
+    if (counts) first_ = false;
+    if (strip_left_ > 0 && !p.empty()) strip_leading(p, strip_, &strip_left_);
 
     all_ += p;
     pending_ += p;
 
     /* Inside the reasoning block no stop string applies (defer_stops_until). The closer is
-     * searched for incrementally in all_, from (closer length - 1) bytes behind the previous end.
-     * Once it has been generated, matching starts in the text AFTER it: the closer may still be in
-     * pending_, and nothing before its end may count. */
+     * searched for incrementally in all_, from (closer length - 1) bytes before the previous end.
+     * Once found, matching starts after it; the closer may still be in pending_. */
     size_t from = 0;
     if (!armed_) {
         const size_t n = arm_after_.size();
@@ -1681,8 +1724,7 @@ std::string Detokenizer::push(int32_t token) {
         }
     }
 
-    /* A complete stop string inside pending_ ends the stream. Everything before it is emitted;
-     * the stop string and anything after it never is. */
+    /* A complete stop string in pending_ ends the stream; only the text before it is emitted. */
     if (!stops_.empty() && from != std::string::npos) {
         size_t best = std::string::npos;
         const std::string* which = nullptr;
@@ -1708,13 +1750,13 @@ std::string Detokenizer::push(int32_t token) {
 }
 
 std::string Detokenizer::flush() {
-    /* End of stream: whatever is held back will never resolve, so it goes out. An incomplete
-     * UTF-8 tail here means the model stopped mid-codepoint, which is a real thing a length limit
-     * does; it leaves as one U+FFFD rather than as the raw bytes, because the raw bytes do not
-     * survive being put into a JSON string and the client would get an error in place of the
-     * whole answer. */
+    /* End of stream: release everything held back. An incomplete UTF-8 tail (a length limit can
+     * stop mid-codepoint) leaves as U+FFFD, since raw invalid bytes cannot go into a JSON
+     * string. */
     std::string out;
     out.swap(pending_);
+    /* The held space was a suffix on the last token, which HuggingFace's BPEDecoder drops. */
+    if (hold_space_ && !out.empty() && out.back() == ' ') out.pop_back();
     return utf8_sanitize(out);
 }
 
diff --git a/core/text/tokenizer.h b/core/text/tokenizer.h
index 8d686c40..e7c5aaae 100644
--- a/core/text/tokenizer.h
+++ b/core/text/tokenizer.h
@@ -1,30 +1,24 @@
 /* tokenizer.h -- the tokeniser, driven by the step chain baked into the .rad.
  *
- * spec §12: "The tokenizer is the one place llama.cpp's answer is Python." Their vocab is
- * GGUF-shaped, the tokenizer.json -> vocab mapping lives in convert_hf_to_gguf.py, and at RUNTIME
- * they identify the pre-tokeniser by HASHING tokenizer.json against a hardcoded enum. An
- * unrecognised model therefore gets the default split, and the symptom of that is plausible text
- * with wrong token boundaries -- the hardest kind of wrong to notice, because nothing crashes and
- * the perplexity moves by a few percent.
+ * spec §12. llama.cpp identifies a pre-tokeniser at runtime by hashing tokenizer.json against a
+ * hardcoded enum, so an unrecognised model silently gets the default split: plausible text with
+ * wrong token boundaries. Here the chain is declared instead. rad-convert reads tokenizer.json's
+ * normalizer / pre_tokenizer / decoder sections and emits them as RadVocabStep rows, which this
+ * file executes in order. A chain that cannot be expressed fails at convert time with the step
+ * named.
  *
- * So the chain is DECLARED rather than recognised. rad-convert reads tokenizer.json's
- * normalizer / pre_tokenizer / decoder sections and emits them as RadVocabStep rows; this file
- * executes those rows in order. A model nobody has ever seen tokenises correctly if its
- * tokenizer.json is honest, and a model whose chain we cannot express fails at CONVERT time with
- * the step named, which is a diagnosis rather than a silent 2% regression.
+ * A `Split` step's regex is compiled at load (tokenizer_regex.h) into a DFA that reproduces what
+ * HuggingFace tokenizers' Oniguruma reports, over Oniguruma's own Unicode tables. A pattern
+ * outside that dialect does not load; the refusal names the construct and there is no fallback
+ * matcher.
  *
- * A `Split` step is a regex, and it is COMPILED at load (tokenizer_regex.h) into a DFA that
- * reproduces what HuggingFace tokenizers' Oniguruma reports for it, over Oniguruma's own Unicode
- * tables. A pattern outside the dialect that compiler implements does not load: the refusal names
- * the construct, and there is no second matcher behind it.
- *
- * What is lifted from llama.cpp (06938ac12, MIT -- see vendor/UPSTREAM):
+ * Lifted from llama.cpp (06938ac12, MIT -- see vendor/UPSTREAM):
  *   - the byte-level alphabet and the unicode category tables the non-regex steps read
  *                                                                        (vendor/llama/src/unicode*)
  *   - the shape of the BPE bigram queue and the UGM Viterbi              (src/llama-vocab.cpp)
- * The last of those is re-expressed here rather than vendored: llama-vocab.cpp is welded to
- * llama_model_loader, GGML_ASSERT and the llama_vocab class, so it is a file we would have had
- * to modify heavily, and spec §12 says such a file belongs in core/ under our own name.
+ * The latter is re-expressed rather than vendored: llama-vocab.cpp depends on
+ * llama_model_loader, GGML_ASSERT and llama_vocab, and spec §12 puts a heavily modified file in
+ * core/ under our own name.
  */
 #pragma once
 #include "rad_internal.h"
@@ -46,10 +40,10 @@ struct TokEncoder;
 
 /* One row of the declared chain, in the form rad-convert builds and the .rad bakes.
  *
- * `kind` is a RAD_NORM_* / RAD_PRE_* / RAD_DEC_* value from rad_format.h and its numeric range
- * says which of the three chains the row belongs to, so the three are ONE list in declared order
- * and no reader has to reassemble them. Per-kind meaning of flags/args is documented at
- * `step_describe()` in tokenizer.cpp; it is the contract rad-convert writes against. */
+ * `kind` is a RAD_NORM_* / RAD_PRE_* / RAD_DEC_* value from rad_format.h; its numeric range says
+ * which of the three chains the row belongs to, so all three are one list in declared order.
+ * The per-kind meaning of flags/args is documented at `step_describe()` in tokenizer.cpp, the
+ * contract rad-convert writes against. */
 struct VocabStep {
     uint32_t    kind = 0;
     uint32_t    flags = 0;
@@ -57,6 +51,22 @@ struct VocabStep {
     int64_t     iarg = 0;
 };
 
+/* RAD_PRE_WHITESPACE's flags: which of HuggingFace's whitespace pre-tokenisers the step is.
+ * Whitespace is 0, so a container written before the other two had flags reads as what it ran. */
+enum : uint32_t {
+    kPreWhitespace      = 0,   /* the matches of \w+|[^\w\s]+, the rest removed */
+    kPreWhitespaceSplit = 1,   /* split on whitespace, removed */
+    kPreBert            = 2    /* WhitespaceSplit, then every punctuation character isolated */
+};
+
+/* RAD_DEC_REPLACE's flags: 0 is a plain Replace of arg0 by arg1 in every token. The others are the
+ * HuggingFace decoders converted to it, which also read the token's place in the list. */
+enum : uint32_t {
+    kDecWordPiece        = 1,  /* arg0 is the continuation prefix; other words join with a space */
+    kDecWordPieceCleanup = 2,  /* with kDecWordPiece: WordPiece's `cleanup` of spaced punctuation */
+    kDecBpeSuffix        = 4   /* arg0 is the end-of-word suffix: a space, none after the last */
+};
+
 /* Kind ranges, matching the enum blocks in rad_format.h. */
 inline bool step_is_norm(uint32_t k) { return k >= 1  && k < 32; }
 inline bool step_is_pre (uint32_t k) { return k >= 32 && k < 64; }
@@ -64,10 +74,9 @@ inline bool step_is_dec (uint32_t k) { return k >= 64 && k < 96; }
 
 /* Everything the tokeniser needs, in a form that can be built, inspected, written and read.
  *
- * The engine could bind directly to the mmapped .rad and save copying 248K token strings, and
- * deliberately does not: one construction path means the tokeniser that rad-convert tests with is
- * byte-for-byte the tokeniser the server runs. The cost is a few megabytes and a few tens of
- * milliseconds at load, against a model measured in gigabytes -- which is not a cost. */
+ * The engine copies this out of the mmapped .rad instead of binding to it, so rad-convert and the
+ * server share one construction path and run byte-for-byte the same tokeniser. The copy costs a
+ * few megabytes and a few tens of milliseconds at load. */
 struct VocabBuild {
     uint32_t kind = RAD_TOK_BPE;
     bool     ignore_merges = false;           /* BPE: a whole pre-token in the vocab is not merged */
@@ -87,9 +96,9 @@ struct VocabBuild {
     /* Diagnostics only: what rad-convert thought it was reading. Not baked. */
     std::string source;
 
-    /* The ids the checkpoint's generation_config.json names as eos_token_id, which the container
-     * carries as metadata (`generation.eos_token_id`) rather than in the vocabulary section. The
-     * engine fills it from there before load(); not baked. */
+    /* generation_config.json's eos_token_id ids, carried as container metadata
+     * (`generation.eos_token_id`) rather than in the vocab section. The engine fills them before
+     * load(); not baked. */
     std::vector eos_ids;
 };
 
@@ -107,10 +116,9 @@ public:
     uint8_t            type(int32_t id) const;
     float              score(int32_t id) const;
     bool               is_eog(int32_t id) const;       /* eos, eot, or a declared extra */
-    /* Every one of them, by id. The server needs the SPELLINGS: a chat format can fold the turn
-     * terminator into its last marker, so the decoder has to render it for the reply parser --
-     * and then whatever the parser did not consume has to come back off the content, because a
-     * terminator is never something the user asked to read. */
+    /* All end-of-generation ids. The server needs their spellings: a chat format can fold the
+     * turn terminator into its last marker, so the decoder renders it for the reply parser, and
+     * whatever the parser does not consume is stripped from the content. */
     const std::vector& eog() const { return eog_; }
 
     /* -1 when the exact text is not a token. */
@@ -132,7 +140,8 @@ public:
     const VocabBuild&             build() const { return b_; }
 
     /* The byte a RAD_TT_BYTE token stands for, or -1. Both spellings are recognised: SPM's
-     * "<0xF0>" and byte-level BPE's single mapped codepoint. */
+     * "<0xF0>" and byte-level BPE's single mapped codepoint. Under a ByteFallback decoder a NORMAL
+     * "<0xNN>" token is a byte too. */
     int32_t token_byte(int32_t id) const;
 
 private:
@@ -142,12 +151,11 @@ private:
     std::unordered_map    merge_rank_;   /* (lhs id << 32 | rhs id) -> rank */
     std::vector special_;                          /* ids the pre-splitter must isolate */
     std::vector byte_of_;                          /* id -> byte, or -1 */
-    /* Every token that ends a generation, not just the one the header had room for. Built in
-     * load(); see the comment there for why a container's `eos` alone is not the whole set. */
+    /* Every token that ends a generation, not just the header's `eos`; see load(). */
     std::vector eog_;
-    /* The chain compiled for encoding: the Split DFAs, the flat token and merge tables, the
-     * special-token matcher and the segment cache. Built in load(), shared by every Tokenizer
-     * over this vocab and by every copy of it. */
+    /* The chain compiled for encoding: Split DFAs, flat token and merge tables, special-token
+     * matcher and segment cache. Built in load(); shared by every Tokenizer over this vocab and
+     * every copy of it. */
     std::shared_ptr enc_;
     friend class Tokenizer;
     friend class Detokenizer;
@@ -159,38 +167,44 @@ class Tokenizer {
 public:
     int init(std::shared_ptr v);
 
-    /* `add_special` prepends BOS / appends EOS as the vocab declares. `parse_special` lets
-     * control tokens in the raw text be recognised as themselves -- which the server wants for a
-     * rendered chat template and must NOT have for user content, because otherwise a user can
-     * type "<|im_start|>system" and reach the system role. */
+    /* `add_special` prepends BOS / appends EOS as the vocab declares. `parse_special` recognises
+     * control tokens in the raw text. Use it for a rendered chat template, never for user
+     * content, or a user can type "<|im_start|>system" and reach the system role. */
     int encode(std::string_view text, std::vector& out,
                bool add_special, bool parse_special) const;
 
-    /* Non-streaming detokenise. The streaming one is Detokenizer below and it is the one the
-     * server uses; this exists for tests, logging and the /v1/completions echo path. */
+    /* Non-streaming detokenise, for tests, logging and the /v1/completions echo path. The server
+     * streams through Detokenizer. */
     std::string decode(const std::vector& ids, bool render_special = false) const;
 
-    /* One token's text after the decoder chain. Does not resolve partial UTF-8 -- that is
-     * exactly what Detokenizer is for. */
+    /* One token's text after the decoder chain, as it reads in the middle of a text. Partial
+     * UTF-8 is not resolved; Detokenizer does that. */
     std::string piece(int32_t id, bool render_special = false) const;
 
+    /* Where a token sits in the list being decoded. HuggingFace's decoders read it: Metaspace
+     * drops the first token's replacement characters instead of turning them into spaces,
+     * WordPiece joins every token but the first with a space, and BPEDecoder drops the last
+     * token's suffix instead of turning it into a space. Special tokens left out of the text do
+     * not count. */
+    struct At {
+        bool first = false;
+        bool last  = false;
+    };
+    std::string piece_at(int32_t id, bool render_special, At at) const;
+
     const Vocab& vocab() const { return *v_; }
 
-    /* THE SEGMENT CACHE. encode() cuts its text at special tokens before anything else touches
-     * it, and every piece between two of them is normalised, pre-tokenised and merged on its own:
-     * no step of the chain reads across a special token, and none reads anything but the piece
-     * (a Metaspace "first" prepend, a ByteLevel prefix space and every normaliser apply to each
-     * piece as if it were the whole text). A piece's ids are therefore a function of its bytes
-     * and the vocab alone, and a cache from the bytes to the ids returns exactly what encoding
-     * them again would. That is what makes a re-sent conversation cost only what is new in it: an
-     * agent's history arrives as the same pieces between the same `<|im_start|>` markers, turn
-     * after turn.
+    /* Segment cache. encode() first cuts the text at special tokens, and each piece between them
+     * is normalised, pre-tokenised and merged on its own: no step reads across a special token,
+     * and a ByteLevel prefix space and every normaliser treat each piece as the whole text. A
+     * piece's ids are therefore a function of its bytes and the vocab, so a re-sent conversation
+     * only pays for its new pieces. The one exception is a Metaspace "first" prepend, which as in
+     * HuggingFace applies only to the piece that starts the text; that piece is not cached.
      *
-     * The cache belongs to the vocab, so every Tokenizer over it shares it. It is keyed on the
-     * whole piece (the hash only picks the bucket), bounded in bytes with least-recently-used
-     * eviction, and locked for concurrent encodes. Pieces under kSegmentCacheMin bytes are not
-     * cached: re-encoding them costs less than the lookup. `set_segment_cache(false)` makes this
-     * Tokenizer bypass it, which is how the tests and rad-tokcheck compare the two. */
+     * The cache belongs to the vocab and is shared by every Tokenizer over it. It is keyed on the
+     * whole piece (the hash only picks the bucket), bounded in bytes with LRU eviction, and locked
+     * for concurrent encodes. Pieces under kSegmentCacheMin bytes are cheaper to re-encode than to
+     * look up. `set_segment_cache(false)` bypasses it, for tests and rad-tokcheck to compare. */
     static constexpr size_t kSegmentCacheMin     = 64;
     static constexpr size_t kSegmentCacheDefault = size_t(64) << 20;
     void set_segment_cache(bool on) { use_cache_ = on; }
@@ -209,42 +223,32 @@ private:
 
 /* ================================================================== streaming decode */
 
-/* Replace every byte that is not part of a well-formed UTF-8 sequence with U+FFFD, and leave
- * everything else alone. A byte-fallback vocab can emit a byte that no continuation completes --
- * `<0xC1>` is a lead byte for an encoding that is overlong and therefore never legal -- and the
- * generated text goes straight into a JSON string, where an invalid byte is not a mojibake
- * character but a 500: nlohmann::json::dump throws type_error.316 on it and the client gets an
- * engine error instead of the model's answer. Sanitising is the only option that keeps the
- * response: the bytes cannot be held back (nothing will complete them) and dropping them silently
- * would hide that the model produced something undecodable. Well-formed input is returned byte for
- * byte, so this is a no-op on every normal completion. */
+/* Replace every byte that is not part of a well-formed UTF-8 sequence with U+FFFD; well-formed
+ * input is returned unchanged. A byte-fallback vocab can emit a byte no continuation completes
+ * (`<0xC1>` only starts overlong, never-legal encodings), and nlohmann::json::dump throws
+ * type_error.316 on it, failing the whole response. Such bytes cannot be held back, and dropping
+ * them would hide that the model produced something undecodable. */
 std::string utf8_sanitize(std::string_view s);
-/* How much of `s` is well-formed UTF-8 from its start, by the same rules: what a JSON string can
- * carry of a byte-level token that ends inside a character. */
+/* Length of the well-formed UTF-8 prefix of `s`, by the same rules: how much of a byte-level
+ * token that ends inside a character a JSON string can carry. */
 size_t utf8_valid_prefix(std::string_view s);
 
 
-/* Byte-level BPE emits partial UTF-8 sequences -- a single token can be one byte of a
- * three-byte codepoint -- and a stop string can straddle a chunk boundary. Both are buffered
- * until they resolve (spec §12). Emitting either one early is a visible bug: the first puts a
- * replacement character in the user's stream, the second leaks "".
+/* Streaming detokeniser (spec §12). Byte-level BPE emits partial UTF-8 (one token can be one byte
+ * of a three-byte codepoint), and a stop string can straddle a chunk boundary; both are buffered
+ * until they resolve, so the stream never shows a stray U+FFFD or leaks "".
  *
- * The contract: push() returns text that is FINAL. It will never be retracted, it is always
- * WELL-FORMED UTF-8, and it is never a prefix of a stop string. Whatever is still ambiguous stays
- * inside until a later push resolves it or flush() gives up on it. A sequence that turns out to be
- * malformed rather than merely unfinished -- a byte-fallback vocab can emit one -- leaves as
- * U+FFFD (utf8_sanitize above) instead of as raw bytes, since the raw bytes cannot be put into a
- * JSON string and would cost the client the whole response. */
+ * Contract: push() returns final text. It is never retracted, always well-formed UTF-8, and never
+ * a prefix of a stop string. Ambiguous text stays inside until a later push resolves it or
+ * flush() gives up on it. A sequence that is malformed rather than unfinished leaves as U+FFFD
+ * (utf8_sanitize), since raw invalid bytes cannot go into a JSON string. */
 class Detokenizer {
 public:
     Detokenizer() = default;
-    /* `preserved` is the tokens that must reach the caller as TEXT even though they are CONTROL.
-     * A tool-calling format is MADE of them -- MiniCPM5 writes its calls with ``, ``, every one a control token -- so suppressing them the
-     * way a control token is normally suppressed hands the reply parser the arguments with the
-     * structure removed, and the call comes back to the client as prose. The chat template says
-     * which ones it needs (common_chat_params::preserved_tokens); nothing else is unsuppressed. */
+    /* `preserved`: control tokens rendered as text anyway. Some tool-call formats are built from
+     * control tokens (MiniCPM5: ``, ``); suppressing
+     * them would strip the call's structure and hand the reply parser prose. The chat template
+     * names them (common_chat_params::preserved_tokens); nothing else is unsuppressed. */
     Detokenizer(std::shared_ptr v, std::vector stops = {},
                 bool render_special = false, const std::vector& preserved = {});
 
@@ -256,25 +260,20 @@ public:
     bool               stopped() const { return stopped_; }
     const std::string& stop_hit() const { return stop_hit_; }
 
-    /* STOP STRINGS ARE THE ANSWER'S, NOT THE REASONING'S. A generation that starts inside its
-     * reasoning block is matched against its stop strings only after `marker` -- the block's
-     * closer -- has been generated, and only in the text after it. Otherwise a stop string the
-     * model happens to write while thinking ends the request with the reasoning cut short and no
-     * answer at all: a few-shot harness that stops on "Q:" loses every reply whose reasoning
-     * restates the question. "" = match from the first token, the behaviour of every request that
-     * does not start in a block. */
+    /* Stop strings apply to the answer, not the reasoning. For a generation that starts inside its
+     * reasoning block, stops are matched only in the text after `marker` (the block's closer).
+     * Otherwise a stop string written while thinking (e.g. a few-shot "Q:") ends the request with
+     * no answer. "" matches from the first token. */
     void defer_stops_until(std::string marker) {
         arm_after_ = std::move(marker);
         armed_ = arm_after_.empty();
         arm_scanned_ = 0;
     }
 
-    /* Everything pushed so far, stop string included. The scheduler wants this to decide whether
-     * a request finished on a stop or on a length limit. */
+    /* Everything pushed so far, stop string included; the scheduler uses it to tell a stop from
+     * a length limit. */
     const std::string& text() const { return all_; }
 
-    void reset();
-
 private:
     std::shared_ptr v_;
     std::vector     stops_;
@@ -285,7 +284,14 @@ private:
     bool        stopped_ = false;
     std::string stop_hit_;
     size_t      max_stop_ = 0;
-    bool        first_ = true;
+    bool        first_ = true;     /* no token has counted as the first yet */
+    /* A Strip after Fuse in the decoder chain strips the text as a whole: up to `strip_left_`
+     * copies of `strip_` at its start. */
+    std::string strip_;
+    int         strip_left_ = 0;
+    /* BPEDecoder turns a suffix into a space except on the last token, which a stream cannot
+     * know, so a trailing space is held until the next token and dropped by flush(). */
+    bool        hold_space_ = false;
     std::string arm_after_;        /* see defer_stops_until */
     bool        armed_ = true;
     size_t      arm_scanned_ = 0;  /* how far into all_ the search for arm_after_ has reached */
@@ -297,9 +303,9 @@ private:
 
 /* ================================================================== sources and sinks */
 
-/* rad-convert owns the .rad's single string blob; the vocab section only needs to intern into
- * it. Passing the interner rather than a blob keeps the two writers from disagreeing about who
- * owns offset 0. */
+/* rad-convert owns the .rad's single string blob; the vocab section only interns into it.
+ * Passing the interner rather than a blob keeps the two writers from disagreeing about who owns
+ * offset 0. */
 struct StringSink {
     virtual ~StringSink() = default;
     virtual rad_stroff intern(std::string_view s) = 0;
@@ -307,27 +313,24 @@ struct StringSink {
 
 /* Build a VocabBuild from a HuggingFace tokenizer.json.
  *
- * This is the function spec §12 is about: it INTERPRETS the declared normalizer / pre_tokenizer /
- * decoder chain instead of hashing the file. Returns RAD_OK, or a negative RAD_E_*; in
- * particular RAD_E_UNSUPPORTED when the file declares a component we cannot express as a
- * RadVocabStep, with the component named in the log. Failing there is the point -- a chain we
- * cannot express must not become a chain we silently approximate. */
+ * Interprets the declared normalizer / pre_tokenizer / decoder chain (spec §12). Returns RAD_OK
+ * or a negative RAD_E_*, notably RAD_E_UNSUPPORTED, with the component named in the log, for a
+ * component that has no RadVocabStep form. Such a chain is refused, never approximated. */
 int parse_tokenizer_json(const char* path, VocabBuild& out);
 /* Same, from an in-memory buffer, for a tokenizer.json that arrived some other way. */
 int parse_tokenizer_json_buf(std::string_view json, const char* origin, VocabBuild& out);
 
 /* Build a VocabBuild from a GGUF's tokenizer.ggml.* metadata.
  *
- * GGUF has no declared chain -- it has `tokenizer.ggml.pre`, a name llama.cpp derived by hashing
- * the original tokenizer.json. So this reconstructs the chain from that name against a table of
- * the ones we know, and returns RAD_E_UNSUPPORTED for a name we do not, rather than falling back
- * to a default split. That refusal is the whole difference from llama.cpp's behaviour, and it is
- * why converting from the original tokenizer.json is the preferred path. */
+ * GGUF has no declared chain, only `tokenizer.ggml.pre`, a name llama.cpp derived by hashing the
+ * original tokenizer.json. The chain is reconstructed from a table of known names; an unknown
+ * name returns RAD_E_UNSUPPORTED instead of a default split. Converting from tokenizer.json is
+ * the preferred path. */
 int vocab_from_gguf(const GgufFile& g, VocabBuild& out);
 
 /* Serialise into the .rad's vocab section. `section_file_off` is where rad-convert will place
- * the section; every offset written into the RadVocabHeader is absolute from the start of the
- * file, per rad_format.h's rule that "every offset is from the start of the file". */
+ * the section; every offset in the RadVocabHeader is absolute from the start of the file, per
+ * rad_format.h. */
 int vocab_serialize(const VocabBuild& in, StringSink& strings, uint64_t section_file_off,
                     std::vector& section_out);
 /* Read it back. `file_base` is the mmapped .rad; `h` points inside it. */
diff --git a/core/text/tokenizer_bpe.h b/core/text/tokenizer_bpe.h
index ba4d6bcf..b153d973 100644
--- a/core/text/tokenizer_bpe.h
+++ b/core/text/tokenizer_bpe.h
@@ -1,15 +1,15 @@
 /* tokenizer_bpe.h -- the tables and the merge loop under Tokenizer's BPE.
  *
- * The merge is the textbook one and the one every reference implements: repeatedly merge the
- * adjacent pair with the lowest merge rank, the leftmost pair on a tie, until no adjacent pair
- * has a rank. It is kept rather than replaced by a linear-time encoder (GitHub's `bpe` crate)
- * because those are exact only for vocabularies whose every token re-encodes to itself, and a
- * vocabulary is not checked for that; this loop is exact for all of them. What makes it fast is
- * what it runs on: symbols are token ids, a rank lookup is one probe of an open-addressed table
- * keyed by the id pair, and a word of up to kLinearMax symbols is merged by a scan over a small
- * array instead of a heap, which for the four-to-eight-symbol words of real text is several times
- * cheaper. Long words take the heap. Both pick the same pair at every step -- lowest rank, then
- * lowest position -- so they produce the same merges.
+ * The merge is the textbook one every reference implements: repeatedly merge the adjacent pair
+ * with the lowest merge rank, leftmost on a tie, until no adjacent pair has a rank. Linear-time
+ * encoders (GitHub's `bpe` crate) are exact only for vocabularies whose every token re-encodes to
+ * itself, which is not checked; this loop is exact for all of them.
+ *
+ * Symbols are token ids, and a rank lookup is one probe of an open-addressed table keyed by the
+ * id pair. Words of up to kBpeLinearMax symbols are merged by scanning a small array, several
+ * times cheaper than a heap for the 4-8 symbol words of real text; longer words use the heap.
+ * Both pick the same pair at every step (lowest rank, then lowest position), so they produce the
+ * same merges.
  */
 #pragma once
 #include 
@@ -45,9 +45,9 @@ inline uint64_t tok_hash(const void* data, size_t n) {
 }
 inline uint64_t tok_hash(std::string_view s) { return tok_hash(s.data(), s.size()); }
 
-/* Byte string -> id, open-addressed, keys packed in one buffer. FIRST INSERT WINS, which is the
- * rule every lookup in the tokeniser follows: when two ids spell the same text, the lower one is
- * the one the merge table and every published count refer to. */
+/* Byte string -> id, open-addressed, keys packed in one buffer. First insert wins, as for every
+ * lookup in the tokeniser: when two ids spell the same text, the merge table and every published
+ * count refer to the lower one. */
 class TokTable {
 public:
     void    reserve(size_t n);
@@ -64,7 +64,7 @@ private:
     void grow();
 };
 
-/* (left id, right id) -> (rank, id of the merged text or -1). FIRST INSERT WINS here too: a
+/* (left id, right id) -> (rank, id of the merged text or -1). First insert wins here too: a
  * duplicated merge keeps its lowest rank. */
 class MergeTable {
 public:
@@ -103,8 +103,8 @@ struct BpeSym { uint32_t start, len; int32_t id; };
 /* Words up to this many symbols are merged by linear scan; longer ones by heap. */
 constexpr size_t kBpeLinearMax = 64;
 
-/* Merge `syms` in place until no adjacent pair has a rank. `force_heap` exists for the test that
- * holds the two strategies to the same answer. */
+/* Merge `syms` in place until no adjacent pair has a rank. `force_heap` lets a test check that
+ * both strategies agree. */
 void bpe_merge(std::vector& syms, const MergeTable& merges, bool force_heap = false);
 
 }  /* namespace rad */
diff --git a/core/text/tokenizer_json.cpp b/core/text/tokenizer_json.cpp
index b46b4dc0..10cc61ca 100644
--- a/core/text/tokenizer_json.cpp
+++ b/core/text/tokenizer_json.cpp
@@ -1,11 +1,11 @@
 /* tokenizer_json.cpp -- reading a vocab in, and writing it into the .rad.
  *
  * Three sources and one sink:
- *   parse_tokenizer_json()  the HuggingFace file, interpreted rather than hashed. This is the
- *                           preferred path and the one spec §12 is about.
- *   vocab_from_gguf()       GGUF metadata, where the chain has already been lost and has to be
- *                           reconstructed from `tokenizer.ggml.pre`, a name llama.cpp derived by
- *                           hashing the original tokenizer.json.
+ *   parse_tokenizer_json()  the HuggingFace file, interpreted rather than hashed; the preferred
+ *                           path (spec §12).
+ *   vocab_from_gguf()       GGUF metadata, where the chain is lost and is reconstructed from
+ *                           `tokenizer.ggml.pre`, a name llama.cpp derived by hashing the
+ *                           original tokenizer.json.
  *   vocab_serialize()       into the .rad's vocab section, and back.
  */
 #include "text/tokenizer.h"
@@ -25,21 +25,61 @@ using json = nlohmann::json;
 
 namespace {
 
-/* HuggingFace's SplitDelimiterBehavior, in the order our iarg encodes. */
+/* HuggingFace's SplitDelimiterBehavior, in the order our iarg encodes; -1 for another name. */
 int behavior_from_name(const std::string& s) {
     if (s == "Removed")            return 0;
     if (s == "Isolated")           return 1;
     if (s == "MergedWithPrevious") return 2;
     if (s == "MergedWithNext")     return 3;
     if (s == "Contiguous")         return 4;
-    return 1;   /* Isolated is the default in every tokenizer.json that omits it */
+    return -1;
 }
 
+/* Metaspace's prepend scheme, in the order our iarg encodes; -1 for another name. */
 int prepend_scheme_from_name(const std::string& s) {
     if (s == "never")  return 0;
     if (s == "first")  return 1;
     if (s == "always") return 2;
-    return 2;
+    return -1;
+}
+
+/* A field value the tokenizer has no encoding for: guessing one would change the token
+ * boundaries, so the vocabulary is refused like an unknown step. */
+int refuse_value(const char* origin, const char* field, const std::string& v) {
+    RAD_ERR("%s: %s '%s' is not supported", origin, field, v.c_str());
+    return RAD_E_UNSUPPORTED;
+}
+
+/* Merges read by token text into ids: a pair naming a text that is not a token is dropped and
+ * counted, since some vocabs ship merges over strings that are not tokens. */
+struct MergeIds {
+    std::unordered_map id_of;
+    size_t dropped = 0;
+
+    explicit MergeIds(const std::vector& tokens) {
+        id_of.reserve(tokens.size() * 2);
+        for (size_t i = 0; i < tokens.size(); ++i) id_of.emplace(tokens[i], (uint32_t)i);
+    }
+    void add(const std::string& l, const std::string& r, VocabBuild& out) {
+        auto li = id_of.find(l), ri = id_of.find(r);
+        if (li == id_of.end() || ri == id_of.end()) { ++dropped; return; }
+        out.merges.emplace_back(li->second, ri->second);
+    }
+    /* The "a b" spelling, split at the first space. */
+    void add_spaced(const std::string& s, VocabBuild& out) {
+        const size_t sp = s.find(' ');
+        if (sp == std::string::npos) { ++dropped; return; }
+        add(s.substr(0, sp), s.substr(sp + 1), out);
+    }
+};
+
+/* A Metaspace step over U+2581 that always prepends it, as a SentencePiece vocab reads. */
+VocabStep metaspace(uint32_t kind) {
+    VocabStep s;
+    s.kind = kind;
+    s.arg0 = "\xe2\x96\x81";
+    s.iarg = 2;
+    return s;
 }
 
 const json* get(const json& o, const char* k) {
@@ -58,9 +98,9 @@ bool bool_or(const json& o, const char* k, bool dflt) {
     return v && v->is_boolean() ? v->get() : dflt;
 }
 
-/* A regex a step carries is compiled HERE as well as when the vocab loads, so that rad-convert
- * refuses a pattern outside the compiler's dialect with the construct named, instead of writing a
- * container no engine will load. */
+/* A step's regex is compiled here as well as at vocab load, so rad-convert refuses an
+ * unsupported pattern with the construct named instead of writing a container that cannot
+ * load. */
 int check_regex(const std::string& pat, const char* what, const char* origin) {
     std::unique_ptr re;
     std::string why;
@@ -84,9 +124,9 @@ bool read_pattern(const json& o, std::string* pat, bool* is_regex) {
     return false;
 }
 
-/* A token id out of the file, which indexes the token table as soon as it is read: a negative
- * one, or one that is not an integer, writes outside it, and a huge one sizes it. `limit` is
- * one past the largest id accepted (see parse_tokenizer_json_buf). */
+/* A token id from the file. It indexes the token table as soon as it is read, so a negative or
+ * non-integer id would write outside it and a huge one would size it. `limit` is one past the
+ * largest id accepted (see parse_tokenizer_json_buf). */
 bool read_id(const json& v, uint64_t limit, int32_t* out) {
     if (!v.is_number_integer()) return false;
     if (!v.is_number_unsigned() && v.get() < 0) return false;
@@ -143,9 +183,8 @@ int read_normalizer(const json& n, std::vector& out, const char* orig
         out.push_back(s);
         return RAD_OK;
     }
-    /* Everything else is refused BY NAME rather than ignored. An ignored normaliser is a
-     * tokeniser that runs, produces different boundaries, and says nothing -- exactly the
-     * failure this component exists to remove (spec §12). */
+    /* Anything else is refused by name: ignoring a normaliser silently changes token boundaries
+     * (spec §12). */
     RAD_ERR("%s: normalizer '%s' has no RadVocabStep. Refusing rather than approximating it; "
             "add a RAD_NORM_* for it if a model needs it.", origin, t.c_str());
     return RAD_E_UNSUPPORTED;
@@ -176,8 +215,8 @@ int read_pretok(const json& n, std::vector& out, const char* origin)
             return RAD_E_FORMAT;
         }
         if (!is_regex) {
-            /* A literal delimiter is a regex with every metacharacter escaped. Doing the escape
-             * at convert time keeps the runtime with one kind of Split instead of two. */
+            /* A literal delimiter becomes a regex with every metacharacter escaped, so the
+             * runtime has one kind of Split. */
             std::string q;
             for (char c : s.arg0) {
                 if (std::strchr("\\^$.|?*+()[]{}", c)) q += '\\';
@@ -187,7 +226,9 @@ int read_pretok(const json& n, std::vector& out, const char* origin)
         }
         s.kind  = RAD_PRE_SPLIT;
         s.flags = bool_or(n, "invert", false) ? 1u : 0u;
-        s.iarg  = behavior_from_name(str_or(n, "behavior", "Isolated"));
+        const std::string bh = str_or(n, "behavior", "Isolated");
+        s.iarg  = behavior_from_name(bh);
+        if (s.iarg < 0) return refuse_value(origin, "Split behavior", bh);
         RAD_TRY(check_regex(s.arg0, "Split", origin));
         out.push_back(s);
         return RAD_OK;
@@ -195,7 +236,9 @@ int read_pretok(const json& n, std::vector& out, const char* origin)
     if (t == "Metaspace") {
         s.kind  = RAD_PRE_METASPACE;
         s.arg0  = str_or(n, "replacement", "\xe2\x96\x81");
-        s.iarg  = prepend_scheme_from_name(str_or(n, "prepend_scheme", "always"));
+        const std::string ps = str_or(n, "prepend_scheme", "always");
+        s.iarg  = prepend_scheme_from_name(ps);
+        if (s.iarg < 0) return refuse_value(origin, "Metaspace prepend_scheme", ps);
         s.flags = bool_or(n, "split", true) ? 1u : 0u;
         /* The pre-0.14 spelling: add_prefix_space instead of prepend_scheme. */
         if (!get(n, "prepend_scheme")) s.iarg = bool_or(n, "add_prefix_space", true) ? 2 : 0;
@@ -203,13 +246,17 @@ int read_pretok(const json& n, std::vector& out, const char* origin)
         return RAD_OK;
     }
     if (t == "Whitespace" || t == "WhitespaceSplit" || t == "BertPreTokenizer") {
-        s.kind = RAD_PRE_WHITESPACE;
+        s.kind  = RAD_PRE_WHITESPACE;
+        s.flags = t == "Whitespace" ? kPreWhitespace
+                : t == "WhitespaceSplit" ? kPreWhitespaceSplit : kPreBert;
         out.push_back(s);
         return RAD_OK;
     }
     if (t == "Punctuation") {
         s.kind = RAD_PRE_PUNCTUATION;
-        s.iarg = behavior_from_name(str_or(n, "behavior", "Isolated"));
+        const std::string bh = str_or(n, "behavior", "Isolated");
+        s.iarg = behavior_from_name(bh);
+        if (s.iarg < 0) return refuse_value(origin, "Punctuation behavior", bh);
         out.push_back(s);
         return RAD_OK;
     }
@@ -219,8 +266,7 @@ int read_pretok(const json& n, std::vector& out, const char* origin)
         out.push_back(s);
         return RAD_OK;
     }
-    RAD_ERR("%s: pre_tokenizer '%s' has no RadVocabStep. Refusing rather than falling back to a "
-            "default split -- a default split is llama.cpp's failure mode, not ours.",
+    RAD_ERR("%s: pre_tokenizer '%s' is not supported; no RAD_PRE_* step implements it",
             origin, t.c_str());
     return RAD_E_UNSUPPORTED;
 }
@@ -241,7 +287,9 @@ int read_decoder(const json& n, std::vector& out, const char* origin)
     if (t == "Metaspace") {
         s.kind = RAD_DEC_METASPACE;
         s.arg0 = str_or(n, "replacement", "\xe2\x96\x81");
-        s.iarg = prepend_scheme_from_name(str_or(n, "prepend_scheme", "always"));
+        const std::string ps = str_or(n, "prepend_scheme", "always");
+        s.iarg = prepend_scheme_from_name(ps);
+        if (s.iarg < 0) return refuse_value(origin, "Metaspace prepend_scheme", ps);
         if (!get(n, "prepend_scheme")) s.iarg = bool_or(n, "add_prefix_space", true) ? 2 : 0;
         out.push_back(s);
         return RAD_OK;
@@ -274,20 +322,22 @@ int read_decoder(const json& n, std::vector& out, const char* origin)
         return RAD_OK;
     }
     if (t == "WordPiece") {
-        /* WordPiece's decoder is a Replace of the continuation prefix plus a leading strip.
-         * Expressing it as the two steps it is keeps the runtime free of a per-model branch. */
+        /* A Replace of the continuation prefix that also joins words with a space, as
+         * HuggingFace's WordPiece decoder does (kDecWordPiece). `cleanup` defaults to true. */
         VocabStep r;
-        r.kind = RAD_DEC_REPLACE;
-        r.arg0 = str_or(n, "prefix", "##");
-        r.arg1 = "";
+        r.kind  = RAD_DEC_REPLACE;
+        r.arg0  = str_or(n, "prefix", "##");
+        r.flags = kDecWordPiece | (bool_or(n, "cleanup", true) ? kDecWordPieceCleanup : 0u);
         out.push_back(r);
         return RAD_OK;
     }
     if (t == "BPEDecoder") {
+        /* The end-of-word suffix becomes a space, except on the last token (kDecBpeSuffix). */
         VocabStep r;
-        r.kind = RAD_DEC_REPLACE;
-        r.arg0 = str_or(n, "suffix", "");
-        r.arg1 = " ";
+        r.kind  = RAD_DEC_REPLACE;
+        r.arg0  = str_or(n, "suffix", "");
+        r.arg1  = " ";
+        r.flags = kDecBpeSuffix;
         out.push_back(r);
         return RAD_OK;
     }
@@ -305,9 +355,8 @@ int read_model(const json& m, VocabBuild& out, const char* origin, uint64_t id_l
         return RAD_E_FORMAT;
     }
 
-    /* {text: id}, the BPE and WordPiece shape. The ids are dense, but nothing guarantees the
-     * JSON order matches the id order, so each is placed by id -- which is why every one is
-     * checked before the table is sized from them. */
+    /* {text: id}, the BPE and WordPiece shape. JSON order need not match id order, so each
+     * entry is placed by id; every id is checked before the table is sized from them. */
     auto read_text_to_id = [&](const char* kind) -> int {
         if (!vocab->is_object()) {
             RAD_ERR("%s: %s vocab is not an object of {text: id}", origin, kind);
@@ -336,6 +385,14 @@ int read_model(const json& m, VocabBuild& out, const char* origin, uint64_t id_l
     if (type == "BPE") {
         out.kind = RAD_TOK_BPE;
         out.ignore_merges = bool_or(m, "ignore_merges", false);
+        /* Subword affixes change what every merge produces, and dropout makes encoding random;
+         * the encoder implements neither. */
+        for (const char* k : { "continuing_subword_prefix", "end_of_word_suffix" }) {
+            const std::string v = str_or(m, k, "");
+            if (!v.empty()) return refuse_value(origin, (std::string("BPE ") + k).c_str(), v);
+        }
+        if (const json* d = get(m, "dropout"); d && d->is_number() && d->get() > 0.0)
+            return refuse_value(origin, "BPE dropout", d->dump());
         RAD_TRY(read_text_to_id("BPE"));
     } else if (type == "Unigram") {
         out.kind = RAD_TOK_UNIGRAM;
@@ -354,8 +411,7 @@ int read_model(const json& m, VocabBuild& out, const char* origin, uint64_t id_l
             out.scores.push_back(e[1].get());
         }
         out.types.assign(out.tokens.size(), (uint8_t)RAD_TT_NORMAL);
-        /* The encoder emits this id for text no piece covers, so one that names no token would
-         * put an id outside the vocabulary into the output. */
+        /* The encoder emits this id for uncovered text, so it must name a token. */
         const json* u = get(m, "unk_id");
         if (u && !read_id(*u, out.tokens.size(), &out.unk)) {
             RAD_ERR("%s: Unigram unk_id %.64s is not an id in its %zu-token vocab", origin,
@@ -364,6 +420,13 @@ int read_model(const json& m, VocabBuild& out, const char* origin, uint64_t id_l
         }
     } else if (type == "WordPiece") {
         out.kind = RAD_TOK_WORDPIECE;
+        /* The encoder spells continuations "##" and takes words of up to 100 characters,
+         * HuggingFace's defaults. */
+        const std::string prefix = str_or(m, "continuing_subword_prefix", "##");
+        if (prefix != "##") return refuse_value(origin, "WordPiece continuing_subword_prefix", prefix);
+        if (const json* mc = get(m, "max_input_chars_per_word");
+            mc && !(mc->is_number_integer() && mc->get() == 100))
+            return refuse_value(origin, "WordPiece max_input_chars_per_word", mc->dump());
         RAD_TRY(read_text_to_id("WordPiece"));
     } else {
         RAD_ERR("%s: model type '%s' is not implemented (BPE, Unigram and WordPiece are)",
@@ -371,8 +434,8 @@ int read_model(const json& m, VocabBuild& out, const char* origin, uint64_t id_l
         return RAD_E_UNSUPPORTED;
     }
 
-    /* Byte fallback is a property of the MODEL in tokenizer.json and a step for us, because it
-     * changes what the encoder does on a miss and the encoder is where the miss happens. */
+    /* Byte fallback is a model property in tokenizer.json but a step here: it changes what the
+     * encoder does on a miss. */
     if (bool_or(m, "byte_fallback", false)) {
         VocabStep s;
         s.kind = RAD_PRE_BYTE_FALLBACK;
@@ -381,52 +444,42 @@ int read_model(const json& m, VocabBuild& out, const char* origin, uint64_t id_l
 
     if (type != "BPE") return RAD_OK;
 
-    /* Merges. Two spellings in the wild: ["a b", ...] and [["a","b"], ...]. The second exists
-     * because a token can contain a space. */
+    /* Merges come as ["a b", ...] or, since a token can contain a space, [["a","b"], ...]. */
     const json* merges = get(m, "merges");
     if (!merges || !merges->is_array()) return RAD_OK;
 
-    std::unordered_map id_of;
-    id_of.reserve(out.tokens.size() * 2);
-    for (size_t i = 0; i < out.tokens.size(); ++i) id_of.emplace(out.tokens[i], (uint32_t)i);
-
-    size_t dropped = 0;
+    MergeIds ids(out.tokens);
     out.merges.reserve(merges->size());
     for (const json& e : *merges) {
-        std::string l, r;
-        if (e.is_array() && e.size() == 2 && e[0].is_string() && e[1].is_string()) {
-            l = e[0].get();
-            r = e[1].get();
-        } else if (e.is_string()) {
-            const std::string s = e.get();
-            const size_t sp = s.find(' ');
-            if (sp == std::string::npos) { ++dropped; continue; }
-            l = s.substr(0, sp);
-            r = s.substr(sp + 1);
-        } else {
-            ++dropped;
-            continue;
-        }
-        auto li = id_of.find(l), ri = id_of.find(r);
-        if (li == id_of.end() || ri == id_of.end()) { ++dropped; continue; }
-        out.merges.emplace_back(li->second, ri->second);
+        if (e.is_array() && e.size() == 2 && e[0].is_string() && e[1].is_string())
+            ids.add(e[0].get(), e[1].get(), out);
+        else if (e.is_string())
+            ids.add_spaced(e.get(), out);
+        else
+            ++ids.dropped;
     }
-    if (dropped) {
-        /* Every dropped merge is a merge the tokeniser will not make, so the boundary moves.
-         * It is a warning rather than an error only because a handful of vocabs genuinely ship
-         * merges over strings they never added as tokens. */
+    /* A dropped merge moves token boundaries; only a warning, as MergeIds says why. */
+    if (ids.dropped)
         RAD_WARN("%s: %zu of %zu merges reference text that is not in the vocab and were "
                  "dropped; token boundaries may differ from the reference tokeniser",
-                 origin, dropped, merges->size());
-    }
+                 origin, ids.dropped, merges->size());
     return RAD_OK;
 }
 
-/* Added tokens override the model vocab and may extend past it. `special` decides whether the
- * pre-splitter treats them as control (isolated even when parse_special is off is NOT the rule --
- * see Tokenizer::encode) or as user-defined. */
-int read_added(const json& arr, VocabBuild& out, const char* origin, uint64_t id_limit) {
+/* Added tokens override the model vocab and may extend past it. `special` makes a token control
+ * (isolated only when parse_special is on; see Tokenizer::encode) rather than user-defined.
+ *
+ * The encoder matches an added token against the raw text, exactly as written. HuggingFace's
+ * AddedToken flags each change that: `single_word` matches only between word boundaries,
+ * `normalized` matches against the normalised text (the same thing when there is no normaliser),
+ * and `lstrip` / `rstrip` take the whitespace beside a match into it. Most files spell out every
+ * flag, so a flag is refused only at a value that changes the result. lstrip and rstrip would
+ * also refuse released models (Phi-3's chat markers carry rstrip), and the container has no field
+ * to carry them, so they are warned about instead. */
+int read_added(const json& arr, VocabBuild& out, const char* origin, uint64_t id_limit,
+               bool has_normalizer) {
     if (!arr.is_array()) return RAD_OK;
+    std::string stripped;
     for (const json& e : arr) {
         const json* idv = get(e, "id");
         const json* cv  = get(e, "content");
@@ -443,17 +496,28 @@ int read_added(const json& arr, VocabBuild& out, const char* origin, uint64_t id
             out.types.resize(id + 1, (uint8_t)RAD_TT_NORMAL);
             if (out.kind == RAD_TOK_UNIGRAM) out.scores.resize(id + 1, 0.0f);
         }
-        out.tokens[id] = cv->get();
-        out.types[id]  = bool_or(e, "special", false) ? (uint8_t)RAD_TT_CONTROL
-                                                      : (uint8_t)RAD_TT_USER_DEFINED;
+        const std::string content = cv->get();
+        const bool special = bool_or(e, "special", false);
+        if (bool_or(e, "single_word", false))
+            return refuse_value(origin, "added token single_word=true on", content);
+        if (has_normalizer && bool_or(e, "normalized", false))
+            return refuse_value(origin, "added token normalized=true (under a normalizer) on",
+                                content);
+        if (bool_or(e, "lstrip", false) || bool_or(e, "rstrip", false))
+            stripped += (stripped.empty() ? "" : " ") + content;
+        out.tokens[id] = content;
+        out.types[id]  = special ? (uint8_t)RAD_TT_CONTROL : (uint8_t)RAD_TT_USER_DEFINED;
     }
+    if (!stripped.empty())
+        RAD_WARN("%s: added tokens %s take the whitespace beside them in HuggingFace (lstrip / "
+                 "rstrip); this tokenizer keeps it as text, so prompts with whitespace next to "
+                 "them tokenise differently", origin, stripped.c_str());
     return RAD_OK;
 }
 
-/* tokenizer_config.json is where the ids live. tokenizer.json holds the vocab and the chain but
- * not which token is BOS, so a convert that reads only tokenizer.json produces a vocab that
- * cannot start a sequence. Reading the sibling is opportunistic: absent, the ids stay -1 and
- * rad-convert can fill them from elsewhere. */
+/* tokenizer_config.json names the special tokens; tokenizer.json does not say which is BOS.
+ * The sibling is optional: when it is absent the ids stay -1 and rad-convert can fill them from
+ * elsewhere. */
 void read_config_json(const std::string& dir, VocabBuild& out) {
     const std::string path = dir + "tokenizer_config.json";
     std::ifstream f(path);
@@ -493,8 +557,8 @@ void read_config_json(const std::string& dir, VocabBuild& out) {
     const json* ct = get(c, "chat_template");
     if (ct && ct->is_string()) out.chat_template = ct->get();
     else if (ct && ct->is_array() && !ct->empty()) {
-        /* The multi-template form: a list of {name, template}. The one named "default" wins,
-         * else the first, which is what every renderer does. */
+        /* The multi-template form, a list of {name, template}: "default" wins, else the first,
+         * as renderers do. */
         for (const json& e : *ct) {
             if (str_or(e, "name", "") == "default") { out.chat_template = str_or(e, "template", ""); break; }
         }
@@ -503,13 +567,9 @@ void read_config_json(const std::string& dir, VocabBuild& out) {
 }
 
 
-/* THE TEMPLATE MAY NOT BE IN tokenizer_config.json AT ALL. Recent transformers versions write it
- * to a standalone chat_template.jinja and omit the key, so a checkpoint saved by one of those
- * converts with NO template at all unless this sibling is read -- and the only symptom is the
- * server answering /v1/chat/completions with 501, a long way from the cause.
- *
- * The file wins where it exists, which is what transformers itself does; in a checkpoint that
- * carries both, the config key is the superseded copy. */
+/* Recent transformers versions write the template to a standalone chat_template.jinja and omit
+ * the config key; without it, /v1/chat/completions answers 501. The file wins over the config
+ * key, as in transformers. */
 void read_chat_template_file(const std::string& dir, VocabBuild& out) {
     const std::string path = dir + "chat_template.jinja";
     std::ifstream f(path);
@@ -544,10 +604,9 @@ int interpret_tokenizer_json(const json& j, uint64_t id_limit, const char* origi
     }
     RAD_TRY(read_model(*model, out, origin, id_limit));
 
-    /* Order matters and it is the file's order: normaliser, then pre-tokeniser, then decoder.
-     * They land in one list because that is what RadVocabHeader holds, and the kind ranges keep
-     * them separable. read_model may already have pushed a ByteFallback step, which belongs
-     * with the pre-tokenisers; it is re-sorted below. */
+    /* One list, as RadVocabHeader holds it: normaliser, pre-tokeniser, then decoder steps, each
+     * in file order; the kind ranges keep them separable. A ByteFallback step pushed by
+     * read_model belongs with the pre-tokenisers and is moved there. */
     std::vector pre_from_model;
     pre_from_model.swap(out.steps);
 
@@ -562,15 +621,38 @@ int interpret_tokenizer_json(const json& j, uint64_t id_limit, const char* origi
     out.steps.insert(out.steps.end(), pre.begin(),  pre.end());
     out.steps.insert(out.steps.end(), dec.begin(),  dec.end());
 
-    if (const json* a = get(j, "added_tokens")) RAD_TRY(read_added(*a, out, origin, id_limit));
+    if (const json* a = get(j, "added_tokens"))
+        RAD_TRY(read_added(*a, out, origin, id_limit, !norm.empty()));
 
-    /* WHAT `add_special_tokens` ADDS, when the file says it in its post-processor rather than in
-     * tokenizer_config.json. HuggingFace's encode runs the post-processor, so a TemplateProcessing
-     * whose single-sequence template is ` $A ` IS the model's add-BOS-and-EOS rule --
-     * Gemma states it there and nowhere else, and an embedding model fed its input without the
-     *  it was trained to pool over computes a different vector. Only the two shapes that map
-     * onto add_bos / add_eos are read: one special token before the sequence, one after. The
-     * config's own add_bos_token / add_eos_token, read later, win where present. */
+    /* The model's unknown token, by text. The encoder emits it for text no token covers, which
+     * HuggingFace does too; tokenizer_config.json's unk_token, read later, agrees or is absent. */
+    if (out.unk < 0) {
+        const std::string unk = str_or(*model, "unk_token", "");
+        for (size_t i = 0; !unk.empty() && i < out.tokens.size(); ++i)
+            if (out.tokens[i] == unk) { out.unk = (int32_t)i; break; }
+    }
+
+    /* A Strip after Fuse strips the decoded text as a whole. Its start can be stripped as text
+     * streams; its end cannot be taken back once streamed, and two of them would interleave. */
+    {
+        bool fused = false, stripped = false;
+        for (const VocabStep& s : dec) {
+            if (s.kind == RAD_DEC_FUSE) fused = true;
+            if (s.kind != RAD_DEC_STRIP || !fused) continue;
+            if ((s.iarg >> 32) != 0 || stripped) {
+                RAD_ERR("%s: a Strip decoder after Fuse that strips the end of the text, or a "
+                        "second one, is not supported", origin);
+                return RAD_E_UNSUPPORTED;
+            }
+            stripped = true;
+        }
+    }
+
+    /* What `add_special_tokens` adds, when the post-processor says it. HuggingFace's encode runs
+     * the post-processor, so a TemplateProcessing single template ` $A ` is the model's
+     * add-BOS/EOS rule; Gemma states it only there, and an embedding model pools over that .
+     * Only a special token before and/or after the sequence is read. The config's
+     * add_bos_token / add_eos_token, read later, win where present. */
     if (const json* pp = get(j, "post_processor")) {
         if (str_or(*pp, "type", "") == "TemplateProcessing") {
             const json* single = get(*pp, "single");
@@ -604,15 +686,13 @@ int parse_tokenizer_json_buf(std::string_view text, const char* origin, VocabBui
     out = VocabBuild{};
     out.source = origin;
 
-    /* NO ID PAST THE SIZE OF THE FILE. Ids are dense, so a vocabulary that names one beyond the
-     * number of bytes listing it would leave more ids unused than the file has bytes; bounding
-     * them by it is what bounds the token table they size to a multiple of the input, whatever
-     * the ids claim. */
+    /* No id may exceed the file size in bytes. Ids are dense, so a valid file never needs a
+     * larger one, and the bound keeps the token table proportional to the input. */
     const uint64_t id_limit = text.size();
 
-    /* A value of the wrong JSON type throws out of nlohmann on the first get<>() that meets it.
-     * The reader checks the shapes that decide what is written where; this turns any other one
-     * into the refusal it is rather than into std::terminate in the converter. */
+    /* nlohmann throws on the first get<>() of a value with the wrong JSON type. The reader checks
+     * the shapes that decide where things are written; this turns any other mismatch into a
+     * format error instead of std::terminate. */
     try {
         return interpret_tokenizer_json(j, id_limit, origin, out);
     } catch (const json::exception& e) {
@@ -654,73 +734,71 @@ namespace {
 
 /* `tokenizer.ggml.pre` -> the pre-tokeniser regex list.
  *
- * These are llama.cpp's ADAPTED patterns, copied verbatim from llm_tokenizer_bpe's constructor
- * (06938ac12). Copying rather than deriving is deliberate: the adaptation llama.cpp applied is
- * part of the pattern's identity for a GGUF -- gpt-4o's `((?=[\p{L}])([^a-z]))*` is not o200k's
- * `[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*`, and a GGUF tokenises the way llama.cpp runs it. They
+ * llama.cpp's adapted patterns, copied verbatim from llm_tokenizer_bpe's constructor
+ * (06938ac12). They are copied, not derived, because a GGUF tokenises the way llama.cpp runs
+ * it: gpt-4o's `((?=[\p{L}])([^a-z]))*` is not o200k's `[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*`. They
  * go through the same compiler as a tokenizer.json pattern.
  *
- * The one exception is kimi-k2. llama.cpp spells it `\p{Han}+` and uses that string only as the
- * key of a hand-written splitter approximating Kimi-K2's real pattern; as a regex it would split
- * Han runs and nothing else. The entry is the real pattern, from the model's tokenization_kimi.py,
- * which is what that splitter was written to stand in for.
+ * Exception: kimi-k2. llama.cpp's `\p{Han}+` is only the key of a hand-written splitter that
+ * approximates Kimi-K2's pattern; as a regex it would split only Han runs. The entry here is the
+ * real pattern from the model's tokenization_kimi.py.
  *
- * The list is not exhaustive and does not try to be. A GGUF whose `pre` is not here is REFUSED,
- * with the instruction to convert from tokenizer.json instead -- which is the path that does not
- * depend on this table at all. */
+ * The list is not exhaustive. A GGUF whose `pre` is missing is refused, with the advice to
+ * convert from tokenizer.json. */
 struct PreEntry { const char* name; const char* regex[4]; bool byte_encode; };
 
+/* The patterns several entries share. */
+constexpr const char* kGpt2 =
+    "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)";
+constexpr const char* kLlama3 =
+    "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+";
+constexpr const char* kQwen2 =
+    "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+";
+constexpr const char* kGpt4o =
+    "[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))*((?=[\\p{L}])([^A-Z]))+(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))+((?=[\\p{L}])([^A-Z]))*(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+";
+constexpr const char* kLines = "[^\\n]+|[\\n]+";
+
 const PreEntry k_pre[] = {
-    { "default", {
-        "[\\p{P}\\$\\+<=>\\^~\\|]+",
-        "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)",
-        "\\p{N}+",
-        "[0-9][0-9][0-9]" }, true },
-    { "llama3", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
-    { "llama-bpe", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
-    { "llama-v3",  { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
-    { "falcon3",   { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
-    { "pixtral",   { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
-    { "lfm2",      { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
-    { "dbrx",      { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
-    { "smaug-bpe", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
-    { "glm4",      { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
-    { "chatglm-bpe", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
-
-    { "gpt-2", { "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true },
-    { "phi-2", { "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true },
-    { "mpt",   { "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true },
-    { "olmo",  { "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true },
-    { "jais",  { "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true },
-    { "trillion", { "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true },
-    { "granite-docling", { "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true },
-
-    { "starcoder", { "\\p{N}", "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true },
-    { "refact",    { "\\p{N}", "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true },
-    { "command-r", { "\\p{N}", "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true },
-    { "smollm",    { "\\p{N}", "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true },
-    { "codeshell", { "\\p{N}", "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true },
-    { "exaone",    { "\\p{N}", "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true },
-    { "minerva-7b",{ "\\p{N}", "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true },
-
-    { "qwen2",            { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
-    { "stablelm2",        { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
-    { "deepseek-r1-qwen", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
-    { "hunyuan",          { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
-    { "solar-open",       { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
-    { "grok-2",           { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
-
-    { "qwen35",           { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
-
-    { "gpt-4o",     { "[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))*((?=[\\p{L}])([^A-Z]))+(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))+((?=[\\p{L}])([^A-Z]))*(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
-    { "llama4",     { "[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))*((?=[\\p{L}])([^A-Z]))+(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))+((?=[\\p{L}])([^A-Z]))*(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
-    { "tekken",     { "[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))*((?=[\\p{L}])([^A-Z]))+|[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))+((?=[\\p{L}])([^A-Z]))*|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
-
+    { "default", { "[\\p{P}\\$\\+<=>\\^~\\|]+", kGpt2, "\\p{N}+", "[0-9][0-9][0-9]" }, true },
+    { "llama3", { kLlama3 }, true },
+    { "llama-bpe", { kLlama3 }, true },
+    { "llama-v3", { kLlama3 }, true },
+    { "falcon3", { kLlama3 }, true },
+    { "pixtral", { kLlama3 }, true },
+    { "lfm2", { kLlama3 }, true },
+    { "dbrx", { kLlama3 }, true },
+    { "smaug-bpe", { kLlama3 }, true },
+    { "glm4", { kLlama3 }, true },
+    { "chatglm-bpe", { kLlama3 }, true },
+    { "gpt-2", { kGpt2 }, true },
+    { "phi-2", { kGpt2 }, true },
+    { "mpt", { kGpt2 }, true },
+    { "olmo", { kGpt2 }, true },
+    { "jais", { kGpt2 }, true },
+    { "trillion", { kGpt2 }, true },
+    { "granite-docling", { kGpt2 }, true },
+    { "starcoder", { "\\p{N}", kGpt2 }, true },
+    { "refact", { "\\p{N}", kGpt2 }, true },
+    { "command-r", { "\\p{N}", kGpt2 }, true },
+    { "smollm", { "\\p{N}", kGpt2 }, true },
+    { "codeshell", { "\\p{N}", kGpt2 }, true },
+    { "exaone", { "\\p{N}", kGpt2 }, true },
+    { "minerva-7b", { "\\p{N}", kGpt2 }, true },
+    { "qwen2", { kQwen2 }, true },
+    { "stablelm2", { kQwen2 }, true },
+    { "deepseek-r1-qwen", { kQwen2 }, true },
+    { "hunyuan", { kQwen2 }, true },
+    { "solar-open", { kQwen2 }, true },
+    { "grok-2", { kQwen2 }, true },
+    { "qwen35", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
+    { "gpt-4o", { kGpt4o }, true },
+    { "llama4", { kGpt4o }, true },
+    { "tekken", { "[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))*((?=[\\p{L}])([^A-Z]))+|[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))+((?=[\\p{L}])([^A-Z]))*|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
     { "seed-coder", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1}| ?[^\\s\\p{L}\\p{N}\\r\\n]+|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
-    { "kimi-k2",    { "[\\p{Han}]+|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}&&[^\\p{Han}]]*[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}&&[^\\p{Han}]]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}&&[^\\p{Han}]]+[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}&&[^\\p{Han}]]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
+    { "kimi-k2", { "[\\p{Han}]+|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}&&[^\\p{Han}]]*[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}&&[^\\p{Han}]]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}&&[^\\p{Han}]]+[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}&&[^\\p{Han}]]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
     { "whitespace", { "\\S+" }, false },
-    { "gemma4",     { "[^\\n]+|[\\n]+" }, false },
-    { "sarvam-moe", { "[^\\n]+|[\\n]+" }, false },
+    { "gemma4", { kLines }, false },
+    { "sarvam-moe", { kLines }, false },
 };
 
 }  /* namespace */
@@ -772,8 +850,7 @@ int vocab_from_gguf(const GgufFile& g, VocabBuild& out) {
         const PreEntry* e = nullptr;
         for (const PreEntry& p : k_pre) if (pre == p.name) { e = &p; break; }
         if (!e) {
-            /* This is the refusal spec §12 asks for. llama.cpp would fall back to `default` here
-             * and produce plausible text with wrong boundaries; we would rather not run. */
+            /* Refused per spec §12; llama.cpp falls back to `default` and splits wrongly. */
             RAD_ERR("gguf: tokenizer.ggml.pre = '%s' is not in this build's table, and guessing "
                     "would give a silently different split. Convert from the model's "
                     "tokenizer.json instead, which needs no table.", pre.c_str());
@@ -797,85 +874,49 @@ int vocab_from_gguf(const GgufFile& g, VocabBuild& out) {
             out.steps.push_back(d);
         } else {
             /* SPM-shaped BPE: the vocab is raw UTF-8 with U+2581 for space. */
-            VocabStep s;
-            s.kind = RAD_PRE_METASPACE;
-            s.arg0 = "\xe2\x96\x81";
-            s.iarg = 2;
-            out.steps.push_back(s);
-            VocabStep d;
-            d.kind = RAD_DEC_METASPACE;
-            d.arg0 = "\xe2\x96\x81";
-            d.iarg = 2;
-            out.steps.push_back(d);
+            out.steps.push_back(metaspace(RAD_PRE_METASPACE));
+            out.steps.push_back(metaspace(RAD_DEC_METASPACE));
         }
 
         std::vector merges;
         g.get_strs("tokenizer.ggml.merges", &merges);
-        std::unordered_map id_of;
-        id_of.reserve(out.tokens.size() * 2);
-        for (size_t i = 0; i < out.tokens.size(); ++i) id_of.emplace(out.tokens[i], (uint32_t)i);
-
-        size_t dropped = 0;
+        MergeIds ids(out.tokens);
         out.merges.reserve(merges.size());
-        for (const std::string& m : merges) {
-            const size_t sp = m.find(' ');
-            if (sp == std::string::npos) { ++dropped; continue; }
-            auto l = id_of.find(m.substr(0, sp));
-            auto r = id_of.find(m.substr(sp + 1));
-            if (l == id_of.end() || r == id_of.end()) { ++dropped; continue; }
-            out.merges.emplace_back(l->second, r->second);
-        }
-        if (dropped)
-            RAD_WARN("gguf: %zu of %zu merges dropped (a half is not a token); token boundaries "
-                     "may differ from the reference tokeniser", dropped, merges.size());
+        for (const std::string& m : merges) ids.add_spaced(m, out);
+        if (ids.dropped)
+            RAD_WARN("gguf: %zu of %zu merges dropped (one side of the merge is not a token); "
+                     "token boundaries may differ from the reference tokeniser",
+                     ids.dropped, merges.size());
     } else if (model == "llama") {
         out.kind = RAD_TOK_BPE;
-        /* SPM proper: whitespace escaped to U+2581, byte fallback for the rest. Expressed as
-         * steps so the runtime has no per-model branch. */
-        VocabStep m;
-        m.kind = RAD_PRE_METASPACE;
-        m.arg0 = "\xe2\x96\x81";
-        m.iarg = 2;
-        out.steps.push_back(m);
+        /* SPM: whitespace escaped to U+2581, byte fallback for the rest, expressed as steps so
+         * the runtime has no per-model branch. */
+        out.steps.push_back(metaspace(RAD_PRE_METASPACE));
         VocabStep bf;
         bf.kind = RAD_PRE_BYTE_FALLBACK;
         out.steps.push_back(bf);
-        VocabStep d;
-        d.kind = RAD_DEC_METASPACE;
-        d.arg0 = "\xe2\x96\x81";
-        d.iarg = 2;
-        out.steps.push_back(d);
-        RAD_WARN("gguf: '%s' is a SentencePiece vocab and this build tokenises it as BPE over the "
-                 "same pieces. That is right for the vocabs that ship as GGUF today and it is "
-                 "not the SPM bigram algorithm; convert from tokenizer.json to be sure.",
+        out.steps.push_back(metaspace(RAD_DEC_METASPACE));
+        RAD_WARN("gguf: '%s' is a SentencePiece vocab, tokenised as BPE over its pieces rather "
+                 "than by the SPM bigram algorithm; convert from tokenizer.json for an exact match",
                  model.c_str());
     } else if (model == "t5") {
         out.kind = RAD_TOK_UNIGRAM;
-        VocabStep m;
-        m.kind = RAD_PRE_METASPACE;
-        m.arg0 = "\xe2\x96\x81";
-        m.iarg = 2;
-        out.steps.push_back(m);
-        VocabStep d;
-        d.kind = RAD_DEC_METASPACE;
-        d.arg0 = "\xe2\x96\x81";
-        d.iarg = 2;
-        out.steps.push_back(d);
+        out.steps.push_back(metaspace(RAD_PRE_METASPACE));
+        out.steps.push_back(metaspace(RAD_DEC_METASPACE));
     } else if (model == "bert") {
         out.kind = RAD_TOK_WORDPIECE;
         VocabStep n;
         n.kind = RAD_NORM_LOWERCASE;
         out.steps.push_back(n);
+        /* BertPreTokenizer and the WordPiece decoder, as a BERT tokenizer.json declares them. */
         VocabStep w;
-        w.kind = RAD_PRE_WHITESPACE;
+        w.kind  = RAD_PRE_WHITESPACE;
+        w.flags = kPreBert;
         out.steps.push_back(w);
-        VocabStep p;
-        p.kind = RAD_PRE_PUNCTUATION;
-        p.iarg = 1;
-        out.steps.push_back(p);
         VocabStep d;
-        d.kind = RAD_DEC_REPLACE;
-        d.arg0 = "##";
+        d.kind  = RAD_DEC_REPLACE;
+        d.arg0  = "##";
+        d.flags = kDecWordPiece | kDecWordPieceCleanup;
         out.steps.push_back(d);
     } else {
         RAD_ERR("gguf: tokenizer.ggml.model = '%s' is not implemented", model.c_str());
@@ -906,8 +947,8 @@ int vocab_serialize(const VocabBuild& in, StringSink& strings, uint64_t off,
     if (in.tokens.size() > UINT32_MAX || in.merges.size() > UINT32_MAX ||
         in.steps.size() > UINT32_MAX) return RAD_E_INVAL;
 
-    /* Every string goes into the file's one blob and only its offset is stored here, per
-     * rad_format.h. That is what makes the section fixed-stride and mmap-walkable. */
+    /* Strings go into the file's one blob and only their offsets are stored here (rad_format.h),
+     * so the section is fixed-stride and mmap-walkable. */
     std::vector tok_off(in.tokens.size());
     for (size_t i = 0; i < in.tokens.size(); ++i) tok_off[i] = strings.intern(in.tokens[i]);
 
@@ -935,8 +976,9 @@ int vocab_serialize(const VocabBuild& in, StringSink& strings, uint64_t off,
     h.flags = in.ignore_merges ? RAD_VOCAB_IGNORE_MERGES : 0;
     out.resize(sizeof(RadVocabHeader), 0);
 
-    /* Each array is aligned to its own element so a mapped reader can point a typed pointer at
-     * it. RAD_ALIGN_SUB would be enough for the container's rules; 8 is what the types need. */
+    /* Each array is aligned to its element type so a mapped reader can use a typed pointer.
+     * The largest alignment needed is 8; the container's own rule would only require
+     * RAD_ALIGN_SUB. */
     auto place = [&](size_t align, const void* p, size_t bytes) -> uint64_t {
         pad_to(out, (size_t)off, align);
         const uint64_t at = off + out.size();
@@ -972,9 +1014,8 @@ int vocab_deserialize(const void* file_base, uint64_t file_bytes, const RadVocab
     const char* strs = nullptr;
     uint64_t str_bytes = 0;
     {
-        /* The string blob's extent comes from the file header, which sits at offset 0. Reading
-         * it here rather than taking it as an argument keeps the caller from having to keep the
-         * two in sync. */
+        /* The string blob's extent is read from the file header at offset 0 rather than passed
+         * in, so the caller cannot pass a mismatched one. */
         if (file_bytes < sizeof(RadFileHeader)) return RAD_E_FORMAT;
         const RadFileHeader* fh = reinterpret_cast(base);
         if (fh->str_off + fh->str_bytes > file_bytes) return RAD_E_FORMAT;
diff --git a/core/text/tokenizer_nfc.cpp b/core/text/tokenizer_nfc.cpp
index 8572e925..24640185 100644
--- a/core/text/tokenizer_nfc.cpp
+++ b/core/text/tokenizer_nfc.cpp
@@ -11,25 +11,25 @@ namespace {
 
 /* NFC, applied only where it can change something.
  *
- * UAX #15's quick check: a codepoint whose NFC_QC is Yes and whose combining class is 0 is a
- * BOUNDARY -- nothing before it can compose with it or reorder across it, and nothing it becomes
- * can reach back past it -- so normalising the text between two boundaries on its own gives exactly
- * the bytes normalising the whole text gives there. The text is scanned for the codepoints that
- * are not boundaries (NFC_QC No or Maybe, a mark out of canonical order, anything not strictly
- * well-formed), and only the stretch from the boundary before each one to the boundary after it
- * goes through unorm_utf8; everything else is already NFC and is copied. The properties are
- * derived from the same tables unorm_utf8 runs on -- "No" is a codepoint NFC does not leave alone
- * by itself, "Maybe" is one that can compose with what precedes it -- so the scan agrees with that
- * implementation rather than with some other one. Invalid bytes are never at a boundary, so the
- * decoder's replacement of them happens inside a normalised stretch, byte for byte as it does when
- * the whole text is normalised. */
+ * UAX #15 quick check: a codepoint with NFC_QC Yes and combining class 0 is a boundary. Nothing
+ * before it can compose with it or reorder across it, and nothing it becomes reaches back past
+ * it, so normalising the text between two boundaries alone gives the same bytes as normalising
+ * the whole text. The scan finds the non-boundary codepoints (NFC_QC No or Maybe, a mark out of
+ * canonical order, ill-formed UTF-8) and runs unorm_utf8 only from the boundary before each one
+ * to the boundary after it; the rest is copied. The properties are derived from the tables
+ * unorm_utf8 uses ("No": NFC changes the codepoint on its own; "Maybe": it can compose with what
+ * precedes it), so the scan agrees with that implementation. Invalid bytes are never boundaries,
+ * so their replacement happens inside a normalised stretch, exactly as for the whole text. */
 class NfcQuick {
 public:
     NfcQuick() : not_yes_(kWords, 0), marked_(kWords, 0) {
         for (size_t i = 0; i < k_decomp_rows_n; ++i) {
             const DecompRow& r = k_decomp_rows[i];
             if (r.len_c == 0) continue;
-            if (unorm_nfc({ r.cpt }) != std::vector{ r.cpt }) set(not_yes_, r.cpt);
+            std::vector v{ r.cpt };
+            unorm_decompose(v, false);
+            unorm_compose(v);
+            if (v != std::vector{ r.cpt }) set(not_yes_, r.cpt);
         }
         for (size_t i = 0; i < k_compose_n; ++i) set(not_yes_, k_compose[i].b);
         for (uint32_t c = 0x1161; c <= 0x1175; ++c) set(not_yes_, c);   /* Hangul V, composes after L */
diff --git a/core/text/tokenizer_nfc.h b/core/text/tokenizer_nfc.h
index 7d18e571..2032ba96 100644
--- a/core/text/tokenizer_nfc.h
+++ b/core/text/tokenizer_nfc.h
@@ -1,13 +1,12 @@
 /* tokenizer_nfc.h -- NFC for the tokeniser's normaliser chain, applied only where it can change
- * something. Byte for byte what unorm_utf8(text, false, true) returns; see tokenizer_nfc.cpp for
- * why normalising the stretches around the codepoints that are not NFC boundaries is the same as
- * normalising the whole text. */
+ * something. The result is byte for byte unorm_utf8(text, false, true); tokenizer_nfc.cpp explains
+ * why normalising only the stretches around non-boundary codepoints is equivalent. */
 #pragma once
 #include 
 
 namespace rad {
 
-/* Normalise `text` in place. False when it was already NFC and has not been touched. */
+/* Normalise `text` in place. Returns false when it was already NFC and is untouched. */
 bool tok_nfc(std::string& text);
 
 }  /* namespace rad */
diff --git a/core/text/tokenizer_regex.cpp b/core/text/tokenizer_regex.cpp
index fef43a8f..a56a7632 100644
--- a/core/text/tokenizer_regex.cpp
+++ b/core/text/tokenizer_regex.cpp
@@ -241,8 +241,7 @@ struct Flags { bool i = false, m = false, x = false; };
 
 /* Recursive descent over the pattern's codepoints. Every refusal goes through fail(), which
  * records the first reason and makes every caller unwind; the message names the construct and
- * the byte where it starts, because "unsupported pattern" alone sends the reader to a
- * 200-character regex with no idea where to look. */
+ * the byte where it starts. */
 class Parser {
 public:
     explicit Parser(std::string_view pat) : pat_(pat) {}
@@ -345,8 +344,8 @@ private:
         return add(n);
     }
 
-    /* `(?imx-imx)` with no colon. Oniguruma reads the REST of the enclosing group -- every `|`
-     * after it included -- as one group with the new flags, so `a(?i)b|c` is `a(?i:b|c)` and not
+    /* `(?imx-imx)` with no colon. Oniguruma reads the rest of the enclosing group, every later `|`
+     * included, as one group with the new flags: `a(?i)b|c` is `a(?i:b|c)`, not
      * `a(?i:b)|(?i:c)`. The caller parses that rest as a nested alternation. */
     bool try_inline_flags(const Flags& f, Flags* g) {
         if (peek() != '(' || peek(1) != '?') return false;
@@ -727,7 +726,7 @@ private:
 
     /* `[` already consumed. Oniguruma's classes: a leading `^`, nested classes as union, `&&` as
      * intersection, `-` literal at either end. Under `(?i)` the class is closed over the case
-     * orbits BEFORE it is negated, which is what makes `(?i:[^a-z])` exclude 'A'. */
+     * orbits before it is negated, so `(?i:[^a-z])` excludes 'A'. */
     bool parse_class(const Flags& f, CpSet* out) {
         const size_t at = start_;
         const bool neg = peek() == '^';
@@ -944,7 +943,7 @@ inline uint32_t decode_canon(const uint8_t* p, uint32_t* len) {
 struct TokRegex::Dfa {
     static constexpr uint32_t kMatch = 0x80000000u;
 
-    /* States are named by their ROW OFFSET, state * ncls, so the inner loop indexes the table
+    /* States are named by their row offset, state * ncls, so the inner loop indexes the table
      * with one add. The dead state is row 0. */
     uint32_t ncls = 0;
     std::vector trans;          /* row + class -> next row | kMatch */
@@ -1107,11 +1106,10 @@ int TokRegex::compile(std::string_view pattern, std::unique_ptr* out,
      *
      * A DFA state is the ordered list of NFA states reached by consuming the last codepoint
      * (before their epsilon closure), plus what is remembered of that codepoint. The closure is
-     * taken on the TRANSITION, when the next codepoint's class is known, so a lookahead is
-     * decided exactly. Walking the closure in priority order, reaching MATCH means a match ends
-     * here and every thread after it is dropped: a lower-priority thread can never produce the
-     * match a backtracking engine would report once a higher one has matched. The threads before
-     * it survive, and a later match from one of them replaces this one. */
+     * taken on the transition, when the next codepoint's class is known, so a lookahead is
+     * decided exactly. Walking the closure in priority order, reaching MATCH records a match and
+     * drops every lower-priority thread, which a backtracking engine would never reach. Higher-
+     * priority threads survive, and a later match from one of them replaces this one. */
     std::vector mark(nfa.size(), 0), mark2(nfa.size(), 0);
     uint32_t stamp = 0, stamp2 = 0;
     std::vector stack, chars, next_kernel;
@@ -1186,12 +1184,13 @@ int TokRegex::compile(std::string_view pattern, std::unique_ptr* out,
         d->trans.resize((size_t)kernels.size() * d->ncls, 0);
         d->eoi_match.resize(kernels.size(), 0);
         if (s == 0) continue;
+        /* A copy: intern() may reallocate `kernels`. Row s of `trans` exists from the resize
+         * above, and the states intern() adds get theirs on their own iteration. */
         const std::vector kernel = kernels[s];
         const uint32_t lb = lbs[s];
         for (uint32_t c = 0; c < d->ncls; ++c) {
             const bool m = closure(kernel, lb, (int)c, &next_kernel);
             const uint32_t t = intern(next_kernel, uses_behind ? lb_after[c] : 0);
-            d->trans.resize((size_t)kernels.size() * d->ncls, 0);
             d->trans[(size_t)s * d->ncls + c] = t | (m ? Dfa::kMatch : 0);
         }
         d->eoi_match[s] = closure(kernel, lb, -1, nullptr) ? 1 : 0;
@@ -1234,7 +1233,7 @@ int64_t TokRegex::match_at(std::string_view text, size_t pos) const {
 
 void TokRegex::find_iter(std::string_view text, std::vector& out) const {
     /* Oniguruma's iteration as the `onig` crate drives it: search from the end of the previous
-     * match for the leftmost position with a match; an EMPTY match exactly at the end of the
+     * match for the leftmost position with a match; an empty match exactly at the end of the
      * previous one is skipped by advancing one codepoint and searching again. */
     const uint8_t* s = (const uint8_t*)text.data();
     const size_t n = text.size();
@@ -1400,8 +1399,8 @@ void utf8_canonicalize(std::string_view str, std::string& out) {
         out += (char)(0x80 | ((c >> 6) & 0x3F));
         out += (char)(0x80 | (c & 0x3F));
     };
-    /* unicode_cpts_from_utf8's rules, the decoder the rest of the chain uses: a lead byte with
-     * the continuations it announces decodes (overlong forms and surrogates included), anything
+    /* unicode_cpts_from_utf8's rules, as used by the rest of the chain: a lead byte followed by
+     * the continuations it announces decodes (overlong forms and surrogates included); anything
      * else is one U+FFFD per byte. */
     for (size_t i = 0; i < n; ) {
         const uint8_t b = p[i];
diff --git a/core/text/tokenizer_regex.h b/core/text/tokenizer_regex.h
index cd653e51..a9c1f90a 100644
--- a/core/text/tokenizer_regex.h
+++ b/core/text/tokenizer_regex.h
@@ -2,27 +2,26 @@
  *
  * A tokenizer.json `Split` carries a regex in Oniguruma's Ruby syntax, and HuggingFace tokenizers
  * runs it through Oniguruma's backtracking matcher. This compiles the same pattern into a DFA over
- * codepoint classes and reproduces what that matcher reports, match for match:
+ * codepoint classes that reports the same matches:
  *
  *   - Unicode properties are Oniguruma's own (tokenizer_ucd.h), so `\p{L}`, `\s`, `\w` and the
- *     `(?i)` orbits mean exactly what they mean there.
- *   - Alternation is leftmost-FIRST, not leftmost-longest: the DFA carries its NFA threads in
- *     priority order and a match cuts every thread below it, which is the backtracking order
- *     without the backtracking (the construction RE2 and regex-automata use). Greedy and lazy
- *     quantifiers are the same priority order read the other way.
- *   - Lookaround of ONE codepoint (`\s+(?!\S)`, `(?=[\p{L}])`, `(?<=x)`), `^`, `$`, `\A`, `\z`,
- *     `\b` and `\B` are assertions on the neighbouring codepoints. The DFA carries what it needs
- *     of the previous codepoint in its state and decides a lookahead on the transition that reads
- *     the next one, so a match is reported one transition late, when that codepoint is known.
- *   - find_iter reproduces Oniguruma's iteration exactly, empty matches included: a match is
- *     reported at the leftmost position where one exists, and an empty match at the end of the
- *     previous match is skipped by one codepoint, as the `onig` crate does.
+ *     `(?i)` orbits mean what they mean there.
+ *   - Alternation is leftmost-first, not leftmost-longest: the DFA carries its NFA threads in
+ *     priority order and a match cuts every lower thread, giving backtracking order without
+ *     backtracking (the RE2 / regex-automata construction). Lazy quantifiers reverse the priority.
+ *   - One-codepoint lookaround (`\s+(?!\S)`, `(?=[\p{L}])`, `(?<=x)`), `^`, `$`, `\A`, `\z`, `\b`
+ *     and `\B` are assertions on the neighbouring codepoints. The state carries what it needs of
+ *     the previous codepoint, and a lookahead is decided on the transition that reads the next
+ *     one, so a match is reported one transition late.
+ *   - find_iter follows Oniguruma's iteration, empty matches included: each match is the leftmost
+ *     one, and an empty match at the end of the previous match is skipped by one codepoint, as
+ *     the `onig` crate does.
  *
- * Anything else is REFUSED at compile time with the construct named: backreferences, atomic
+ * Anything else is refused at compile time with the construct named: backreferences, atomic
  * groups and possessive quantifiers, lookaround wider than one codepoint, unbounded repetition of
- * something that can match empty, `(?i)` over a character that folds to several (U+00DF against
- * "ss"), and properties the tables do not carry. There is no second matcher to fall back to; a
- * pattern either compiles to this or the vocabulary does not load.
+ * something that can match empty, `(?i)` over a character that folds to several (U+00DF vs "ss"),
+ * and properties the tables do not carry. There is no fallback matcher; a pattern that does not
+ * compile fails the vocabulary load.
  */
 #pragma once
 #include 
@@ -69,8 +68,7 @@ enum TokSplitBehavior {
 };
 
 /* NormalizedString::split: the non-empty pieces of `text` that `behavior` keeps, appended to
- * `out` as spans of `text`. `scratch` is reused between calls to keep the hot path free of
- * allocation. */
+ * `out` as spans of `text`. `scratch` is reused between calls to avoid allocation. */
 void tok_split(const TokRegex& re, std::string_view text, int behavior, bool invert,
                std::vector& out, std::vector& scratch);
 
@@ -83,9 +81,9 @@ void tok_replace(const TokRegex& re, std::string_view text, std::string_view con
 bool utf8_is_canonical(std::string_view s);
 
 /* Append that round trip of `s` to `out`: each byte that does not start a decodable sequence
- * becomes U+FFFD, an overlong form becomes its shortest one. These are the rules of
- * unicode_cpts_from_utf8, the decoder the normalisers and the other pre-tokenisers use, so a
- * Split sees the same text they do. */
+ * becomes U+FFFD, and an overlong form becomes its shortest one. These are the rules of
+ * unicode_cpts_from_utf8, the decoder the normalisers and other pre-tokenisers use, so a Split
+ * sees the same text they do. */
 void utf8_canonicalize(std::string_view s, std::string& out);
 
 }  /* namespace rad */
diff --git a/core/text/tokenizer_ucd.h b/core/text/tokenizer_ucd.h
index ca3a726d..df6b03c7 100644
--- a/core/text/tokenizer_ucd.h
+++ b/core/text/tokenizer_ucd.h
@@ -1,10 +1,9 @@
 /* tokenizer_ucd.h -- the Unicode properties a pre-tokeniser pattern can name.
  *
- * The tables are generated (tools/gen_tokenizer_ucd.cpp) by asking Oniguruma, the engine
- * HuggingFace tokenizers matches Split patterns with, what each property contains. A pattern in a
- * tokenizer.json means whatever it means THERE, so that is the one definition this compiler has:
- * the general categories at Oniguruma's Unicode version, its `\s`, `\d` and `\w`, its scripts, and
- * its case-folding orbits for `(?i)`.
+ * The tables are generated (tools/gen_tokenizer_ucd.cpp) by querying Oniguruma, the engine
+ * HuggingFace tokenizers matches Split patterns with. A tokenizer.json pattern means what it means
+ * there, so Oniguruma is the only definition used: its general categories at its Unicode version,
+ * its `\s`, `\d` and `\w`, its scripts, and its case-folding orbits for `(?i)`.
  */
 #pragma once
 #include 
diff --git a/core/text/unicode_norm.cpp b/core/text/unicode_norm.cpp
index 11881090..a67345bb 100644
--- a/core/text/unicode_norm.cpp
+++ b/core/text/unicode_norm.cpp
@@ -5,15 +5,14 @@
 
 namespace rad {
 
-/* Hangul, per UAX #15. 11172 syllables that would otherwise be 11172 table rows. */
+/* Hangul syllables are (de)composed arithmetically per UAX #15 instead of with 11172 table rows. */
 static constexpr uint32_t k_s_base = 0xAC00, k_l_base = 0x1100, k_v_base = 0x1161,
                           k_t_base = 0x11A7, k_l_count = 19, k_v_count = 21, k_t_count = 28,
                           k_n_count = k_v_count * k_t_count,          /* 588 */
                           k_s_count = k_l_count * k_n_count;          /* 11172 */
 
 uint32_t unorm_ccc(uint32_t cpt) {
-    /* Binary search over runs. Class 0 is the common case and is not in the table, so the
-     * miss path is the fast path -- which is what a run of ASCII wants. */
+    /* Binary search over runs. Class 0, the common case, is not in the table. */
     size_t lo = 0, hi = k_ccc_n;
     while (lo < hi) {
         size_t mid = (lo + hi) / 2;
@@ -35,9 +34,8 @@ static const DecompRow* decomp_row(uint32_t cpt) {
     return nullptr;
 }
 
-/* Canonical ordering: a stable sort of each run of non-starters by combining class. Written as
- * an insertion sort over the run rather than std::stable_sort because the runs are almost always
- * length 0 or 1 and the comparison is the whole cost. */
+/* Canonical ordering: a stable sort of each run of non-starters by combining class. Insertion
+ * sort rather than std::stable_sort, because runs are almost always of length 0 or 1. */
 static void canonical_order(std::vector& v) {
     for (size_t i = 1; i < v.size(); ++i) {
         const uint32_t ccc_i = unorm_ccc(v[i]);
@@ -65,7 +63,7 @@ void unorm_decompose(std::vector& cpts, bool compat) {
             continue;
         }
         const DecompRow* r = decomp_row(c);
-        /* The pool holds fully-expanded sequences, so this is one lookup and not a fixed point.
+        /* The pool holds fully expanded sequences, so one lookup suffices (no fixed-point loop).
          * A row with only a canonical decomposition serves the K forms too. */
         const uint32_t off = (compat && r && r->len_k) ? r->off_k : (r ? r->off_c : 0);
         const uint32_t len = (compat && r && r->len_k) ? r->len_k : (r ? r->len_c : 0);
@@ -77,7 +75,7 @@ void unorm_decompose(std::vector& cpts, bool compat) {
 }
 
 static bool compose_pair(uint32_t a, uint32_t b, uint32_t* out) {
-    /* Hangul first: arithmetic beats a lookup and it is the only algorithmic composition. */
+    /* Hangul, the only algorithmic composition, is computed before the table lookup. */
     if (a - k_l_base < k_l_count && b - k_v_base < k_v_count) {
         *out = k_s_base + ((a - k_l_base) * k_v_count + (b - k_v_base)) * k_t_count;
         return true;
@@ -106,16 +104,15 @@ void unorm_compose(std::vector& cpts) {
     out.push_back(cpts[0]);
     size_t starter = 0;                 /* index in `out` of the last starter */
     uint32_t last_ccc = unorm_ccc(cpts[0]);
-    /* A leading non-starter is not a starter and can never be a composition target; marking it
-     * with a ccc that blocks everything is how the standard says to say that. */
+    /* A leading non-starter is never a composition target (the standard treats it as blocked). */
     bool have_starter = (last_ccc == 0);
 
     for (size_t i = 1; i < cpts.size(); ++i) {
         const uint32_t c = cpts[i];
         const uint32_t ccc = unorm_ccc(c);
         uint32_t composed = 0;
-        /* Blocked when a character of equal or greater combining class already sits between the
-         * starter and this one -- that is the whole of the blocking rule. */
+        /* Blocked when a character of equal or greater combining class sits between the starter
+         * and this one. */
         const bool blocked = (last_ccc != 0 && last_ccc >= ccc) || (ccc == 0 && last_ccc != 0);
         if (have_starter && !blocked && compose_pair(out[starter], c, &composed)) {
             out[starter] = composed;
@@ -128,23 +125,9 @@ void unorm_compose(std::vector& cpts) {
     cpts.swap(out);
 }
 
-std::vector unorm_nfd(const std::vector& in) {
-    std::vector v = in; unorm_decompose(v, false); return v;
-}
-std::vector unorm_nfkd(const std::vector& in) {
-    std::vector v = in; unorm_decompose(v, true); return v;
-}
-std::vector unorm_nfc(const std::vector& in) {
-    std::vector v = in; unorm_decompose(v, false); unorm_compose(v); return v;
-}
-std::vector unorm_nfkc(const std::vector& in) {
-    std::vector v = in; unorm_decompose(v, true); unorm_compose(v); return v;
-}
-
 std::string unorm_utf8(const std::string& in, bool compat, bool compose) {
-    /* ASCII is in every normalisation form already, and it is most of every prompt. Skipping the
-     * decode/normalise/encode round trip for it is the difference between normalisation costing
-     * nothing and costing a pass over the prompt. */
+    /* ASCII is unchanged by every normalisation form and is most of every prompt, so pure-ASCII
+     * text skips the decode/normalise/encode round trip. */
     bool ascii = true;
     for (unsigned char ch : in) { if (ch >= 0x80) { ascii = false; break; } }
     if (ascii) return in;
diff --git a/core/text/unicode_norm.h b/core/text/unicode_norm.h
index d8012ffe..f72d7544 100644
--- a/core/text/unicode_norm.h
+++ b/core/text/unicode_norm.h
@@ -1,9 +1,8 @@
 /* unicode_norm.h -- NFC / NFD / NFKC / NFKD over codepoint vectors.
  *
- * The four forms are declared steps in a HuggingFace normaliser chain, so the tokeniser has to
- * be able to run them or a model that declares one gets silently different token boundaries --
- * the exact failure class spec §12 exists to remove. llama.cpp has no equivalent, so this is
- * ours; the tables it reads live in unicode_norm_data.cpp and say there how they were made.
+ * The four forms are declared steps in a HuggingFace normaliser chain; a model that declares one
+ * and is tokenised without it gets silently different token boundaries (spec §12). llama.cpp has
+ * no equivalent. The tables live in unicode_norm_data.cpp, which documents how they were made.
  */
 #pragma once
 #include 
@@ -30,18 +29,12 @@ extern const size_t     k_ccc_n;
 
 uint32_t unorm_ccc(uint32_t cpt);
 
-/* In place, on codepoints. `compat` selects the K forms, `compose` selects the C forms, so the
- * four public names below are the four corners of that square. */
+/* In place, on codepoints. `compat` selects the K forms; following with unorm_compose gives the
+ * C forms. */
 void unorm_decompose(std::vector& cpts, bool compat);
 void unorm_compose(std::vector& cpts);
 
-std::vector unorm_nfd (const std::vector& in);
-std::vector unorm_nfkd(const std::vector& in);
-std::vector unorm_nfc (const std::vector& in);
-std::vector unorm_nfkc(const std::vector& in);
-
-/* UTF-8 in, UTF-8 out. The tokeniser's step chain works on strings, so this is the form it
- * calls; the codepoint forms above are what the tests pin. */
+/* UTF-8 in and out: the form the tokeniser's string-based step chain calls. */
 std::string unorm_utf8(const std::string& in, bool compat, bool compose);
 
 }  /* namespace rad */
diff --git a/core/util/kernel_list.h b/core/util/kernel_list.h
new file mode 100644
index 00000000..0175450f
--- /dev/null
+++ b/core/util/kernel_list.h
@@ -0,0 +1,31 @@
+/* kernel_list.h -- how a kernel hierarchy is spelt in --kernels and $RADIANCE_KERNELS.
+ *
+ * The engine (core/config.cpp) and the tools (tools/iface.cpp) both read it here, so a list a
+ * plugin was validated with in rad-kbench loads the same libraries when the engine serves. Entries
+ * are separated by ',' or ':'; empty entries (a doubled or trailing separator) are dropped, since an
+ * entry of "" matches no library and would warn on every start.
+ */
+#pragma once
+
+#include 
+#include 
+#include 
+
+namespace rad {
+
+inline std::vector rad_split_kernel_list(std::string_view s) {
+    std::vector out;
+    std::string cur;
+    for (char c : s) {
+        if (c == ',' || c == ':') {
+            if (!cur.empty()) out.push_back(cur);
+            cur.clear();
+        } else {
+            cur.push_back(c);
+        }
+    }
+    if (!cur.empty()) out.push_back(cur);
+    return out;
+}
+
+}  /* namespace rad */
diff --git a/core/util/rad_util.cpp b/core/util/rad_util.cpp
index 81b8667b..76fbdf8b 100644
--- a/core/util/rad_util.cpp
+++ b/core/util/rad_util.cpp
@@ -1,6 +1,4 @@
-/* rad_util.cpp -- logging, error strings, dtype arithmetic and tensor helpers. The bedrock every
- * other translation unit links against.
- */
+/* rad_util.cpp -- logging, string formatting, Geometry and constraint matching. */
 #include 
 #include 
 #include "../rad_internal.h"
@@ -10,20 +8,16 @@
 #include 
 #include 
 #include 
+#include 
 #include 
 
 namespace rad {
 
 /* ------------------------------------------------------------------ logging */
 
-/* THE LEVEL COMES FROM THE ENVIRONMENT, because nothing in the tree calls `log_set_level`. Without
- * that, the level is Info for the life of every process and every RAD_DEBUG and RAD_TRACE site in
- * the engine is unreachable code that reads like a diagnostic somebody could turn on -- the
- * sampler's mask timing, the grammar's admissible-token count, the drafter's per-position trace,
- * the step loop's batch dump. RADIANCE_LOG=error|warn|info|debug|trace reaches them.
- *
- * Read once, on first use, because this is called from the step path on every logged line. The
- * setter stays: a host embedding the engine as a library has no environment to speak through. */
+/* The initial level comes from RADIANCE_LOG=error|warn|info|debug|trace (default info), so
+ * RAD_DEBUG / RAD_TRACE sites are reachable in any process. Read once at startup; log_set_level
+ * overrides it (command-line -v, tests, embedding hosts). */
 static Log level_from_env() {
     const char* v = std::getenv("RADIANCE_LOG");
     if (!v || !*v) return Log::Info;
@@ -32,8 +26,7 @@ static Log level_from_env() {
     if (!std::strcmp(v, "info"))  return Log::Info;
     if (!std::strcmp(v, "debug")) return Log::Debug;
     if (!std::strcmp(v, "trace")) return Log::Trace;
-    /* Not a level. Said at the level that is always on, rather than silently ignored -- a
-     * misspelt knob that changes nothing looks exactly like a knob that does not work. */
+    /* Report a misspelt level instead of silently ignoring it. */
     std::fprintf(stderr, "E RADIANCE_LOG='%s' is not error|warn|info|debug|trace; using info\n", v);
     return Log::Info;
 }
@@ -52,8 +45,7 @@ static const char* level_tag(Log l) {
     }
 }
 
-/* Colour only when stderr is a terminal. Piped or redirected it prints ordinary lines, which is
- * the same rule the live view follows (spec §16). */
+/* Colour only when stderr is a terminal, as the live view does (spec §16). */
 static const char* level_colour(Log l) {
     if (!isatty(2)) return "";
     switch (l) {
@@ -65,8 +57,7 @@ static const char* level_colour(Log l) {
     }
 }
 
-/* Thread-local because the ranks' declare threads run concurrently; a plain global would have
- * whichever rank last entered a scope tagging every other rank's lines. */
+/* Thread-local: the ranks' declare threads run concurrently and each tags its own lines. */
 static thread_local int  g_log_rank  = -1;
 static bool              g_rank_tags = false;
 
@@ -93,8 +84,7 @@ void log_emit(Log l, const char* file, int line, const char* fmt, ...) {
     char rank[16] = "";
     if (g_rank_tags && g_log_rank >= 0) snprintf(rank, sizeof rank, "[%d]", g_log_rank);
 
-    /* Debug and Trace carry the source site; Info and above do not, because an operator reading
-     * a normal startup does not care which file said it. */
+    /* Debug and Trace carry the source site; Info and above do not. */
     if ((int)l >= (int)Log::Debug)
         fprintf(stderr, "%s%s%s%s %s:%d  %s\n", col, level_tag(l), rank, rst, base, line, msg);
     else
@@ -157,38 +147,26 @@ std::vector split_ws(std::string_view s) {
 }
 
 /* ------------------------------------------------------------------ Geometry */
-/* Small, linear-scanned, and that is correct: an op has a handful of parameters and the selector
- * touches this at declare, not per step. A hash map here would be slower and less predictable. */
-void Geometry::set_i(std::string_view k, long long v) {
-    for (size_t i = 0; i < keys_.size(); ++i)
-        if (keys_[i] == k) { kinds_[i] = RAD_P_INT; ivals_[i] = v; rebuild(); return; }
-    keys_.emplace_back(k);
-    svals_.emplace_back();
-    ivals_.push_back(v);
-    dvals_.push_back(0.0);
-    kinds_.push_back(RAD_P_INT);
-    rebuild();
-}
-
-void Geometry::set_f(std::string_view k, double v) {
-    for (size_t i = 0; i < keys_.size(); ++i)
-        if (keys_[i] == k) { kinds_[i] = RAD_P_F64; dvals_[i] = v; rebuild(); return; }
-    keys_.emplace_back(k);
-    svals_.emplace_back();
-    ivals_.push_back(0);
-    dvals_.push_back(v);
-    kinds_.push_back(RAD_P_F64);
-    rebuild();
+/* Linear scan on purpose: an op has a handful of parameters and the selector reads this at
+ * declare, not per step. */
+size_t Geometry::slot(std::string_view k, int kind) {
+    size_t i = 0;
+    while (i < keys_.size() && keys_[i] != k) ++i;
+    if (i == keys_.size()) {
+        keys_.emplace_back(k);
+        svals_.emplace_back();
+        ivals_.push_back(0);
+        dvals_.push_back(0.0);
+        kinds_.push_back(kind);
+    }
+    kinds_[i] = kind;
+    return i;
 }
 
+void Geometry::set_i(std::string_view k, long long v) { ivals_[slot(k, RAD_P_INT)] = v; rebuild(); }
+void Geometry::set_f(std::string_view k, double v)    { dvals_[slot(k, RAD_P_F64)] = v; rebuild(); }
 void Geometry::set_s(std::string_view k, std::string_view v) {
-    for (size_t i = 0; i < keys_.size(); ++i)
-        if (keys_[i] == k) { kinds_[i] = RAD_P_STR; svals_[i] = std::string(v); rebuild(); return; }
-    keys_.emplace_back(k);
-    svals_.emplace_back(v);
-    ivals_.push_back(0);
-    dvals_.push_back(0.0);
-    kinds_.push_back(RAD_P_STR);
+    svals_[slot(k, RAD_P_STR)] = std::string(v);
     rebuild();
 }
 
@@ -215,9 +193,8 @@ bool Geometry::has(std::string_view k) const {
     return false;
 }
 
-/* Every key and every string value may have moved: an append can reallocate keys_ and svals_, and
- * a short string lives inside its element. So the whole view is redone, which is the same handful
- * of entries the setter's scan already walked. */
+/* Rebuild the whole view: an append can reallocate keys_ and svals_, and short strings live
+ * inside their element, so every c_str() may have moved. */
 void Geometry::rebuild() {
     view_.clear();
     view_.reserve(keys_.size());
@@ -246,10 +223,8 @@ std::string Geometry::str() const {
 }
 
 /* ------------------------------------------------------------------ constraint matching */
-/* A constraint whose key the geometry does not carry does NOT hold. That is libr4d's rule: a row
- * that constrains an optional parameter serves only a caller that states it, so the more
- * constrained of two rows is reached only when it is asked for, and a caller that leaves the
- * parameter out is handed the row that does not need it. */
+/* A constraint on a key the geometry lacks does not hold (libr4d's rule): a row constraining an
+ * optional parameter serves only callers that state it, and others get a row without it. */
 bool constraint_holds(const RadConstraint& c, const Geometry& g) {
     if (c.op == RAD_C_IN) {
         const char* v = g.get_s(c.key);
@@ -279,7 +254,7 @@ bool constraint_holds(const RadConstraint& c, const Geometry& g) {
 
 std::string constraint_why(const RadConstraint& c, const Geometry& g) {
     static const char* opname[] = { "==", "<=", ">=", "%", "in" };
-    const char* on = (c.op >= 0 && c.op <= 4) ? opname[c.op] : "?";
+    const char* on = (c.op >= 0 && c.op < (int)std::size(opname)) ? opname[c.op] : "?";
 
     if (c.op == RAD_C_IN) {
         const char* v = g.get_s(c.key);
@@ -299,11 +274,7 @@ std::string constraint_why(const RadConstraint& c, const Geometry& g) {
 
 /* ------------------------------------------------------------------ the C surface
  *
- * EMPTY, AND THAT IS THE POINT. rad_strerror, the four dtype helpers, the three tensor helpers
- * and rad_args_geti/gets are `static inline` in the ABI headers. Defined here instead -- declared
- * in abi/, defined in rad_core -- they would be callable by everything EXCEPT the plugins that
- * want them most; see the long note above rad_strerror in rad_types.h for the failure that
- * motivates the arrangement and for what it costs.
- *
- * Nothing belongs here. A helper a plugin may need belongs in the header; a helper only the
- * core needs belongs in namespace rad above, not behind extern "C". */
+ * Intentionally empty. rad_strerror, the dtype and tensor helpers and rad_args_geti/gets are
+ * `static inline` in the ABI headers; defined in rad_core they would be unreachable from plugins
+ * (see the note above rad_strerror in rad_types.h). A helper plugins need goes in the header; a
+ * core-only helper goes in namespace rad, not behind extern "C". */
diff --git a/core/util/stallwatch.cpp b/core/util/stallwatch.cpp
index 018007b3..d76ffa3f 100644
--- a/core/util/stallwatch.cpp
+++ b/core/util/stallwatch.cpp
@@ -3,6 +3,7 @@
 
 #include "rad_internal.h"
 
+#include 
 #include 
 #include 
 #include 
@@ -31,8 +32,8 @@ std::string read_first_line(const std::string& path) {
     return s;
 }
 
-/* The ioctl numbers of the KFD (type 'K'), as  assigns them. By number rather
- * than by macro, because the header a build sees can be older than the driver it runs on. */
+/* KFD ioctl numbers (type 'K') from , listed by number because the build's
+ * header can be older than the running driver. */
 const char* kfd_ioctl_name(unsigned nr) {
     static const char* const k[] = {
         nullptr, "GET_VERSION", "CREATE_QUEUE", "DESTROY_QUEUE", "SET_MEMORY_POLICY",
@@ -70,14 +71,7 @@ const char* syscall_name(long nr) {
 #endif
 }
 
-bool is_ioctl(long nr) {
-#if defined(__x86_64__)
-    return nr == 16;
-#else
-    (void)nr;
-    return false;
-#endif
-}
+bool is_ioctl(long nr) { return nr == SYS_ioctl; }
 
 /* ---- the stack of a thread that waits in user space, taken by a signal it handles itself ---- */
 
@@ -133,10 +127,9 @@ std::string stack_of(pid_t tid) {
 }  /* namespace */
 
 std::string stall_module_offset(uintptr_t addr) {
-    /* RELATIVE TO WHERE THE MODULE IS LOADED, which is what addr2line takes for a position-
-     * independent binary or library: the start of its first mapping, less that mapping's file
-     * offset. The offset into the file is not the same number wherever the linker puts a segment
-     * at a different address than its file position, as lld does. */
+    /* Relative to the module's load base (lowest mapping start minus its file offset), which is
+     * what addr2line takes for PIC code. The file offset differs where the linker places a
+     * segment at an address unlike its file position, as lld does. */
     struct Map { unsigned long lo, hi, off; std::string path; };
     std::vector maps;
     {
@@ -212,8 +205,8 @@ std::string stall_describe_thread(pid_t tid, bool stack) {
     s += ", " + stall_decode_syscall(sc);
     long nr = -1;
     std::sscanf(sc.c_str(), "%ld", &nr);
-    /* A thread in a driver call is not signalled: the call already says where it is, and a wait
-     * the signal interrupts may end the call early instead of restarting it. */
+    /* A thread in a driver call is not signalled: the call already says where it waits, and the
+     * signal could end the wait early instead of restarting it. */
     if (stack && !is_ioctl(nr) && state != 'D') s += "\n    stack: " + stack_of(tid);
     return s;
 }
@@ -221,6 +214,7 @@ std::string stall_describe_thread(pid_t tid, bool stack) {
 struct StallWatch::Impl {
     std::string             phase;
     uint64_t                quiet_ns = 0;
+    uint64_t                poll_ns = 0;
     pid_t                   holder = 0;
     std::mutex              mu;
     std::condition_variable cv;
@@ -256,7 +250,7 @@ struct StallWatch::Impl {
         uint64_t own = 0;                     /* the time of this watch's own last report */
         uint64_t next = quiet_ns;             /* the silence that is reported next */
         std::unique_lock lk(mu);
-        while (!cv.wait_for(lk, std::chrono::seconds(1), [&] { return stop; })) {
+        while (!cv.wait_for(lk, std::chrono::nanoseconds(poll_ns), [&] { return stop; })) {
             const uint64_t last = log_last_line_ns();
             if (last > since && last != own) { since = last; next = quiet_ns; }
             const uint64_t now = rad_mono_ns();
@@ -273,6 +267,9 @@ struct StallWatch::Impl {
 StallWatch::StallWatch(const char* phase, uint64_t quiet_ms) : p_(std::make_unique()) {
     p_->phase = phase ? phase : "phase";
     p_->quiet_ns = quiet_ms * 1000000ull;
+    /* A quarter of the quiet interval, so a report is at most that late, and at most a second. */
+    p_->poll_ns = std::max(1000000ull, std::min(1000000000ull,
+                                                                    p_->quiet_ns / 4));
     p_->holder = (pid_t)syscall(SYS_gettid);
     install_stack_handler();
     p_->th = std::thread([this] { p_->run(); });
diff --git a/core/util/stallwatch.h b/core/util/stallwatch.h
index b0240e8e..945c839e 100644
--- a/core/util/stallwatch.h
+++ b/core/util/stallwatch.h
@@ -1,13 +1,11 @@
 /* stallwatch.h -- naming where a phase that has gone quiet is waiting.
  *
- * A startup that stops printing leaves the hardest report to act on: the log ends on the last line
- * that was printed, and whatever came after it -- a driver call that never returned, a lock inside a
- * runtime library -- leaves no trace. The machine it happens on is often one this project cannot
- * run (a guest kernel, a card passed through to a VM), so where it waits has to come from the
- * process itself.
+ * A hang (a driver call that never returns, a lock inside a runtime library) leaves no trace in
+ * the log, often on machines that cannot be reproduced locally (a guest kernel, a passed-through
+ * card), so the process reports where it waits.
  *
  * A StallWatch is held across a phase by the thread doing it. When nothing has been logged for the
- * quiet interval it says what that thread is doing:
+ * quiet interval it reports what that thread is doing:
  *   - its scheduler state and kernel wait channel;
  *   - the system call it is in, an ioctl with its device and request, and the library that made
  *     the call;
@@ -17,8 +15,9 @@
  *     early;
  *   - the process's other threads that are inside an ioctl, since a lock in a runtime library is
  *     usually held by one of them.
- * It says it again each time the silence doubles, so a later log shows whether the thread moved.
- * The watch reads only its own process's /proc entries and costs one wake-up a second while held.
+ * It reports again each time the silence doubles, showing whether the thread moved. The watch
+ * reads only its own process's /proc entries and wakes every quarter of the quiet interval, at most
+ * once a second, while held.
  */
 #pragma once
 
diff --git a/data/kbench_rows/kbench_rows_kernels_libavx.txt b/data/kbench_rows/kbench_rows_kernels_libavx.txt
new file mode 100644
index 00000000..e861c07d
--- /dev/null
+++ b/data/kbench_rows/kbench_rows_kernels_libavx.txt
@@ -0,0 +1,45 @@
+# Kernel rows a replay of this fixture reaches (rad-kbench --coverage).
+# A row listed here and not reached fails the replay; regenerate with
+# --coverage-write when a row is added or deliberately retired.
+avx_add
+avx_attn_dense
+avx_attn_paged
+avx_cast
+avx_dflash_select
+avx_embed_lookup
+avx_gated_quant_fp8
+avx_gather_rows
+avx_gdn_chunk_scan
+avx_gdn_conv_update
+avx_gdn_gated_rmsnorm
+avx_gdn_kkt_solve
+avx_gdn_recurrent_update
+avx_gemm_nt
+avx_gemm_nt_bias
+avx_gemm_nt_q
+avx_gemm_nt_q_gated
+avx_grid_embed
+avx_kv_store
+avx_layernorm
+avx_logits_gemm
+avx_quant_act_fp8
+avx_quant_act_i8
+avx_rmsnorm
+avx_rmsnorm_quant_fp8
+avx_rope
+avx_rope_table
+avx_row_topk
+avx_sample_argmax
+avx_sample_dry
+avx_sample_logprobs
+avx_sample_mask
+avx_sample_minp
+avx_sample_penalties
+avx_sample_pick
+avx_sample_temp
+avx_sample_topk
+avx_sample_topp
+avx_sample_typical
+avx_sample_xtc
+avx_scatter_rows
+avx_silu_mul
diff --git a/data/kbench_rows/kbench_rows_kernels_libr4d.txt b/data/kbench_rows/kbench_rows_kernels_libr4d.txt
new file mode 100644
index 00000000..ff67a7ac
--- /dev/null
+++ b/data/kbench_rows/kbench_rows_kernels_libr4d.txt
@@ -0,0 +1,51 @@
+# Kernel rows a replay of this fixture reaches (rad-kbench --coverage).
+# A row listed here and not reached fails the replay; regenerate with
+# --coverage-write when a row is added or deliberately retired.
+add_bf16
+attn_decode_h128_gqa4_fp8kv
+attn_decode_h256_gqa6_fp8kv
+attn_prefill_h256_gqa6_fp8kv
+attn_vit_h72_bf16
+cast_bf16_bf16
+dflash_select_bf16
+embed_lookup_bf16
+gated_quant_fp8
+gather_rows_bf16
+gdn_chunk_scan_k128_v128_c64_bf16
+gdn_conv_update_w4_h128_bf16
+gdn_gated_rmsnorm_h128_bf16
+gdn_kkt_solve_k128_c64_bf16
+gdn_recurrent_update_k128_v128_bf16_fp32state
+gemm_bf16_nt_bias_tiled
+gemm_bf16_nt_m16
+gemm_bf16_nt_m64
+gemm_fp8a8_gated_nt_m16
+gemm_fp8a8_nt_m16
+gemm_fp8a8_tiled
+gemm_mxfp4a8_decode
+gemm_mxfp4a8_tiled
+grid_embed_bf16
+kv_store_fp8
+layernorm_bf16
+logits_gemm_fp8
+quant_act_fp8
+quant_act_i8
+rmsnorm_bf16
+rmsnorm_quant_fp8
+rope_bf16
+rope_table_f32
+rowtopk_bf16
+sample_argmax_f32
+sample_dry_f32
+sample_logprobs_f32
+sample_mask_f32
+sample_minp_f32
+sample_penalties_f32
+sample_pick_f32
+sample_temp_f32
+sample_topk_f32
+sample_topp_f32
+sample_typical_f32
+sample_xtc_f32
+scatter_rows_bf16
+silu_mul_bf16
diff --git a/data/kbench_rows/kbench_rows_kernels_libref.txt b/data/kbench_rows/kbench_rows_kernels_libref.txt
new file mode 100644
index 00000000..32ae0e25
--- /dev/null
+++ b/data/kbench_rows/kbench_rows_kernels_libref.txt
@@ -0,0 +1,45 @@
+# Kernel rows a replay of this fixture reaches (rad-kbench --coverage).
+# A row listed here and not reached fails the replay; regenerate with
+# --coverage-write when a row is added or deliberately retired.
+ref_add
+ref_attn_dense
+ref_attn_paged
+ref_cast
+ref_dflash_select
+ref_embed_lookup
+ref_gated_quant_fp8
+ref_gather_rows
+ref_gdn_chunk_scan
+ref_gdn_conv_update
+ref_gdn_gated_rmsnorm
+ref_gdn_kkt_solve
+ref_gdn_recurrent_update
+ref_gemm_nt
+ref_gemm_nt_bias
+ref_gemm_nt_q
+ref_gemm_nt_q_gated
+ref_grid_embed
+ref_kv_store
+ref_layernorm
+ref_logits_gemm
+ref_quant_act_fp8
+ref_quant_act_i8
+ref_rmsnorm
+ref_rmsnorm_quant_fp8
+ref_rope
+ref_rope_table
+ref_row_topk
+ref_sample_argmax
+ref_sample_dry
+ref_sample_logprobs
+ref_sample_mask
+ref_sample_minp
+ref_sample_penalties
+ref_sample_pick
+ref_sample_temp
+ref_sample_topk
+ref_sample_topp
+ref_sample_typical
+ref_sample_xtc
+ref_scatter_rows
+ref_silu_mul
diff --git a/data/kbench_rows/kbench_rows_kernels_moe_libavx.txt b/data/kbench_rows/kbench_rows_kernels_moe_libavx.txt
new file mode 100644
index 00000000..de8c0017
--- /dev/null
+++ b/data/kbench_rows/kbench_rows_kernels_moe_libavx.txt
@@ -0,0 +1,46 @@
+# Kernel rows a replay of this fixture reaches (rad-kbench --coverage).
+# A row listed here and not reached fails the replay; regenerate with
+# --coverage-write when a row is added or deliberately retired.
+avx_add
+avx_attn_dense
+avx_attn_paged
+avx_cast
+avx_embed_lookup
+avx_gated_quant_fp8
+avx_gather_rows
+avx_gdn_chunk_scan
+avx_gdn_conv_update
+avx_gdn_gated_rmsnorm
+avx_gdn_kkt_solve
+avx_gdn_recurrent_update
+avx_gemm_nt
+avx_gemm_nt_bias
+avx_gemm_nt_q
+avx_grid_embed
+avx_kv_store
+avx_layernorm
+avx_logits_gemm
+avx_moe_gather
+avx_moe_gemm_q
+avx_moe_scatter
+avx_quant_act_fp8
+avx_quant_act_i8
+avx_rmsnorm
+avx_rmsnorm_quant_fp8
+avx_rope
+avx_rope_table
+avx_router_topk
+avx_row_topk
+avx_sample_argmax
+avx_sample_dry
+avx_sample_logprobs
+avx_sample_mask
+avx_sample_minp
+avx_sample_penalties
+avx_sample_pick
+avx_sample_temp
+avx_sample_topk
+avx_sample_topp
+avx_sample_typical
+avx_sample_xtc
+avx_scatter_rows
diff --git a/data/kbench_rows/kbench_rows_kernels_moe_libr4d.txt b/data/kbench_rows/kbench_rows_kernels_moe_libr4d.txt
new file mode 100644
index 00000000..59047519
--- /dev/null
+++ b/data/kbench_rows/kbench_rows_kernels_moe_libr4d.txt
@@ -0,0 +1,50 @@
+# Kernel rows a replay of this fixture reaches (rad-kbench --coverage).
+# A row listed here and not reached fails the replay; regenerate with
+# --coverage-write when a row is added or deliberately retired.
+add_bf16
+attn_decode_h256_gqa8_fp8kv
+attn_prefill_h256_gqa8_fp8kv
+attn_vit_h72_bf16
+cast_bf16_bf16
+embed_lookup_bf16
+gated_quant_fp8
+gather_rows_bf16
+gdn_chunk_scan_k128_v128_c64_bf16
+gdn_conv_update_w4_h128_bf16
+gdn_gated_rmsnorm_h128_bf16
+gdn_kkt_solve_k128_c64_bf16
+gdn_recurrent_update_k128_v128_bf16_fp32state
+gemm_bf16_nt_bias_tiled
+gemm_bf16_nt_m16
+gemm_bf16_nt_m64
+gemm_bf16_nt_tiled
+gemm_fp8a8_nt_m16
+gemm_fp8a8_tiled
+grid_embed_bf16
+kv_store_fp8
+layernorm_bf16
+logits_gemm_fp8
+moe_gather_bf16
+moe_gemm_fp8a8
+moe_scatter_i32
+quant_act_fp8
+quant_act_i8
+rmsnorm_bf16
+rmsnorm_quant_fp8
+rope_bf16
+rope_table_f32
+router_topk_bf16
+rowtopk_bf16
+sample_argmax_f32
+sample_dry_f32
+sample_logprobs_f32
+sample_mask_f32
+sample_minp_f32
+sample_penalties_f32
+sample_pick_f32
+sample_temp_f32
+sample_topk_f32
+sample_topp_f32
+sample_typical_f32
+sample_xtc_f32
+scatter_rows_bf16
diff --git a/data/kbench_rows/kbench_rows_kernels_moe_libref.txt b/data/kbench_rows/kbench_rows_kernels_moe_libref.txt
new file mode 100644
index 00000000..0b78297b
--- /dev/null
+++ b/data/kbench_rows/kbench_rows_kernels_moe_libref.txt
@@ -0,0 +1,46 @@
+# Kernel rows a replay of this fixture reaches (rad-kbench --coverage).
+# A row listed here and not reached fails the replay; regenerate with
+# --coverage-write when a row is added or deliberately retired.
+ref_add
+ref_attn_dense
+ref_attn_paged
+ref_cast
+ref_embed_lookup
+ref_gated_quant_fp8
+ref_gather_rows
+ref_gdn_chunk_scan
+ref_gdn_conv_update
+ref_gdn_gated_rmsnorm
+ref_gdn_kkt_solve
+ref_gdn_recurrent_update
+ref_gemm_nt
+ref_gemm_nt_bias
+ref_gemm_nt_q
+ref_grid_embed
+ref_kv_store
+ref_layernorm
+ref_logits_gemm
+ref_moe_gather
+ref_moe_gemm_q
+ref_moe_scatter
+ref_quant_act_fp8
+ref_quant_act_i8
+ref_rmsnorm
+ref_rmsnorm_quant_fp8
+ref_rope
+ref_rope_table
+ref_router_topk
+ref_row_topk
+ref_sample_argmax
+ref_sample_dry
+ref_sample_logprobs
+ref_sample_mask
+ref_sample_minp
+ref_sample_penalties
+ref_sample_pick
+ref_sample_temp
+ref_sample_topk
+ref_sample_topp
+ref_sample_typical
+ref_sample_xtc
+ref_scatter_rows
diff --git a/data/kernels.rkb b/data/kernels.rkb
index ec30ae5a..c71d522b 100644
Binary files a/data/kernels.rkb and b/data/kernels.rkb differ
diff --git a/data/kernels_moe.rkb b/data/kernels_moe.rkb
index 8699238a..90e42689 100644
Binary files a/data/kernels_moe.rkb and b/data/kernels_moe.rkb differ
diff --git a/data/recipes/q38-27b-nvfp4-df2.recipe b/data/recipes/q38-27b-nvfp4-df2.recipe
new file mode 100644
index 00000000..148bdc29
--- /dev/null
+++ b/data/recipes/q38-27b-nvfp4-df2.recipe
@@ -0,0 +1,44 @@
+# q38-27b-nvfp4-df2.recipe -- unsloth's Qwen3.8-27B-NVFP4 with the DFlash2 drafter.
+#
+#   rad-convert  --draft-model  \
+#       --recipe q38-27b-nvfp4-df2.recipe -o q38-27b-nvfp4-df2.rad
+#
+# The checkpoint is compressed-tensors mixed precision: the MLPs of layers 0-55 are NVFP4 (e2m1
+# codes, an e4m3 scale per 16 of K, an f32 global scale per tensor); the attention and delta-net
+# projections, the MLPs of layers 56-63 and the lm_head are FP8 with a bf16 scale per row; the
+# delta net's a/b projections, the vision tower and the MTP head are bf16. The core decodes each
+# exactly, and every rule below quantises the decoded value, so one recipe covers all forms.
+#
+#   - The trunk's linears at MXFP4 (`fp4_e2m1`, an e8m0 scale per 32 of K, the OCP exponent
+#     rule): the encoding and kernel of q38-27b-quark-mxfp4-df2.recipe. No kernel serves NVFP4.
+#     NVFP4 to MXFP4 rounds twice: on a synthetic Gaussian tensor the result is 0.14 relative
+#     RMS from the source, against 0.12 for MXFP4 made from the source and 0.10 for NVFP4. At
+#     model scale, against the block-fp8 Qwen3.8-27B on four documents: mean KL 0.287, top-1
+#     87.5% (the Quark MXFP4 container: 0.206, 89.3%).
+#   - The delta net's a/b projections stay bf16, as shipped: 96 rows of 5120, read as their own
+#     projection beside [q|k|v|z].
+#   - The lm_head at block fp8 (from its per-row FP8), as in the other 27B recipes.
+#
+# The drafter as q38-27b-quark-mxfp4-df2.recipe makes it: its linears at MXFP4, and a 2-bit copy
+# of the target's head (u2 with a u8 zero, least-squares clip search) whose top 32 the engine
+# rescores against the target's fp8 head.
+
+blk.*.ffn_gate_up.weight                 rtn  codes=fp4_e2m1 group=32 scale=e8m0
+blk.*.ffn_down.weight                    rtn  codes=fp4_e2m1 group=32 scale=e8m0
+blk.*.attn_qg.weight                     rtn  codes=fp4_e2m1 group=32 scale=e8m0
+blk.*.attn_k.weight                      rtn  codes=fp4_e2m1 group=32 scale=e8m0
+blk.*.attn_v.weight                      rtn  codes=fp4_e2m1 group=32 scale=e8m0
+blk.*.attn_output.weight                 rtn  codes=fp4_e2m1 group=32 scale=e8m0
+blk.*.ssm_inz.weight                     rtn  codes=fp4_e2m1 group=32 scale=e8m0
+blk.*.ssm_out.weight                     rtn  codes=fp4_e2m1 group=32 scale=e8m0
+
+output.weight                            rtn  codes=fp8_e4m3 block=128x128 scale=bf16
+dflash.draft_head.weight                 rtn  codes=u2 zero=u8 group=128 scale=f16 rule=search
+
+dflash.fc.weight                         rtn  codes=fp4_e2m1 group=32 scale=e8m0
+dflash.blk.*.attn_q.weight               rtn  codes=fp4_e2m1 group=32 scale=e8m0
+dflash.blk.*.attn_k.weight               rtn  codes=fp4_e2m1 group=32 scale=e8m0
+dflash.blk.*.attn_v.weight               rtn  codes=fp4_e2m1 group=32 scale=e8m0
+dflash.blk.*.attn_output.weight          rtn  codes=fp4_e2m1 group=32 scale=e8m0
+dflash.blk.*.ffn_gate_up.weight          rtn  codes=fp4_e2m1 group=32 scale=e8m0
+dflash.blk.*.ffn_down.weight             rtn  codes=fp4_e2m1 group=32 scale=e8m0
diff --git a/data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe b/data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe
index f35c61cd..d0576ab9 100644
--- a/data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe
+++ b/data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe
@@ -14,7 +14,7 @@
 #
 # DIR holds each layer's pooled Grams, recorded from ten million tokens of the bf16 model, and each
 # expert's own down Gram, from one million tokens with the per-expert tap, side by side; libquant
-# takes an expert's own wherever it holds at least 4096 rows and the layer's otherwise
+# takes an expert's own wherever it holds at least 4 x K rows (2560 for down) and the layer's otherwise
 # (docs/MOE-W4.md, "Calibration"). A variant of this recipe converted with --reuse w4nl64-i8lm.rad
 # re-quantises only the weights whose rule changed.
 #
diff --git a/deploy/compose/common.yaml b/deploy/compose/common.yaml
index 4c9d1cf8..461fb16a 100644
--- a/deploy/compose/common.yaml
+++ b/deploy/compose/common.yaml
@@ -1,5 +1,5 @@
-# The service every model file in this directory extends. It holds what any radiance container
-# needs on an AMD host; a model file adds only its container and its flags.
+# The service every model file in this directory extends: what any radiance container needs on an
+# AMD host. A model file adds only its container and its flags.
 #
 # Each model takes both cards (--tp 2; a -tp1 file one) and the same port, so run one at a time:
 #   docker compose -f flashnext.yaml up -d        start (it comes back after a reboot)
@@ -15,7 +15,7 @@ services:
     # Host networking: the server binds the host's own addresses, IPv4 and IPv6, with no NAT
     # between it and a reverse proxy.
     network_mode: host
-    # The host user, so the prefix cache's files on disk belong to that user and not to root.
+    # Run as the host user so files the server writes belong to that user, not root.
     user: "${RADIANCE_UID:-1000}:${RADIANCE_GID:-1000}"
     devices:
       - /dev/kfd
@@ -23,9 +23,9 @@ services:
     group_add:
       - "${RENDER_GID:?set RENDER_GID in .env}"
       - "${VIDEO_GID:?set VIDEO_GID in .env}"
-    # Docker's default seccomp profile refuses io_uring, which the n-gram table's reads from the
-    # container go through, and the NUMA binding calls (mbind, set_mempolicy) the ROCm runtime
-    # makes for host memory.
+    # Docker's default seccomp profile refuses io_uring (used for the n-gram table's reads from the
+    # model file) and the NUMA binding calls (mbind, set_mempolicy) the ROCm runtime makes for
+    # host memory.
     security_opt:
       - seccomp=unconfined
     ulimits:
diff --git a/deploy/compose/flashnext-tp1.yaml b/deploy/compose/flashnext-tp1.yaml
index 51e46278..47988b1a 100644
--- a/deploy/compose/flashnext-tp1.yaml
+++ b/deploy/compose/flashnext-tp1.yaml
@@ -3,9 +3,9 @@
 # 49 GiB of host memory and wants a host with 64 GB of RAM; the n-gram table is read from the
 # model file on the drive.
 #
-# A prefill step copies every pooled expert across the link once, so on one card prefill is bound
-# by the link, and a 4096-token step pays that once for twice the tokens of a 2048-token one: 26K
-# prompts prefill at 2545 tok/s against 1413. The checkpoint interval matches the step, since a
+# A prefill step copies every pooled expert across the link once, so one-card prefill is
+# link-bound; a 4096-token step amortises that copy over twice the tokens of a 2048-token one
+# (26K-token prompts: 2545 vs 1413 tok/s). The checkpoint interval matches the step because a
 # prefill chunk never crosses a checkpoint. At 4 sequences the cache holds 301K tokens, one and a
 # half 200K-token sessions.
 name: radiance-flashnext-tp1
diff --git a/deploy/compose/gemma4-31b-w4a8.yaml b/deploy/compose/gemma4-31b-w4a8.yaml
index 92a61cd7..3b1d810e 100644
--- a/deploy/compose/gemma4-31b-w4a8.yaml
+++ b/deploy/compose/gemma4-31b-w4a8.yaml
@@ -2,8 +2,8 @@
 # assistant head merged in as the MTP drafter (depth 3), and the vision tower. Sampling defaults are
 # the checkpoint's generation_config; thinking is switched per request (chat_template_kwargs).
 # For the full 262,144-token context use --max-model-len 262144 --max-num-seqs 2.
-# Prefill runs in 2048-token chunks: measured at TP2 on two R9700s, 1% faster than the 8192-token
-# default and no step long enough to hold a running decode for seconds.
+# Prefill runs in 2048-token chunks: at TP2 on two R9700s this is 1% faster than the 8192-token
+# default, and no step holds a running decode for seconds.
 name: radiance-gemma4-31b-w4a8
 services:
   radiance:
diff --git a/deploy/compose/qwen-image-2.1.yaml b/deploy/compose/qwen-image-2.1.yaml
index f81f6537..233841c3 100644
--- a/deploy/compose/qwen-image-2.1.yaml
+++ b/deploy/compose/qwen-image-2.1.yaml
@@ -1,9 +1,9 @@
 # Qwen-Image 2.1 (Qwen/Qwen-Image-2.1) as block fp8: pictures from a prompt and edits of up to ten
 # pictures on OpenAI's /v1/images/generations and /v1/images/edits, 2048x2048 by default. Two
-# cards: the conditioning cache then holds all ten reference pictures, where one card holds four.
-# 2.1-Turbo is qwen-image-2.1-turbo.yaml; the bf16 container needs both cards. The engine sizes
-# the step, the batch and the context for an image generator itself (docs/GUIDE.md §5.6). --tp-wire
-# wht6 sends the DiT's all-reduces as 6-bit: about 10% off every picture for a few tenths of a dB
+# cards: the conditioning cache holds all ten reference pictures (one card holds four). 2.1-Turbo
+# is qwen-image-2.1-turbo.yaml; the bf16 container needs both cards. The engine sizes the step,
+# batch and context for an image generator itself (docs/GUIDE.md §5.6). --tp-wire wht6 sends the
+# DiT's all-reduces as 6-bit: about 10% faster per picture at a cost of a few tenths of a dB
 # against diffusers; drop it for the exact wire.
 name: radiance-qwen-image
 services:
diff --git a/deploy/compose/qwen3-asr-1.7b.yaml b/deploy/compose/qwen3-asr-1.7b.yaml
new file mode 100644
index 00000000..927f4877
--- /dev/null
+++ b/deploy/compose/qwen3-asr-1.7b.yaml
@@ -0,0 +1,15 @@
+# Qwen3-ASR 1.7B (Qwen/Qwen3-ASR-1.7B-hf) served from its checkpoint as it ships, no conversion:
+# speech to text on OpenAI's /v1/audio/transcriptions and live over /v1/realtime, 30 languages.
+# The model is small and runs on one card, RADIANCE_GPU in .env (default 0). Each live session holds
+# one sequence, so --max-num-seqs is the most sessions served at once.
+name: radiance-qwen3-asr
+services:
+  radiance:
+    extends: { file: common.yaml, service: radiance }
+    container_name: radiance-qwen3-asr
+    environment:
+      ROCR_VISIBLE_DEVICES: "${RADIANCE_GPU:-0}"
+    command: >
+      --model /models/Qwen3-ASR-1.7B-hf
+      --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env}
+      --tp 1 --max-num-seqs 16
diff --git a/deploy/grafana/README.md b/deploy/grafana/README.md
index f402dda2..af45d0f9 100644
--- a/deploy/grafana/README.md
+++ b/deploy/grafana/README.md
@@ -2,13 +2,13 @@
 
 ![The overview row, one hour of a four-rank server](overview.png)
 
-`radiance.json` is a Grafana dashboard for `/metrics`: throughput, prompt tokens by source, speculative
-decoding by draft position, scheduler steps, latency, the prefix cache and HTTP. The whole dashboard:
-[dashboard.png](dashboard.png).
+`radiance.json` is a Grafana dashboard for `/metrics`: throughput, prompt tokens by source,
+speculative decoding by draft position, scheduler steps, latency, the prefix cache and HTTP. The
+whole dashboard: [dashboard.png](dashboard.png).
 
-Import it (Dashboards → New → Import) and pick a Prometheus data source. Every query is plain PromQL,
-so VictoriaMetrics added as a Prometheus data source works the same. Checked with Grafana 13.2 against
-Prometheus 3.15 and VictoriaMetrics 1.153 scraping one server.
+Import it (Dashboards → New → Import) and pick a Prometheus data source. Every query is plain
+PromQL, so VictoriaMetrics added as a Prometheus data source works the same. Checked with Grafana
+13.2 against Prometheus 3.15 and VictoriaMetrics 1.153 scraping one server.
 
 ```yaml
 scrape_configs:
@@ -21,7 +21,8 @@ scrape_configs:
       credentials: ""
 ```
 
-Window values are counter ratios with the definitions of the since-start gauges:
+Window values are ratios of counters (named here without their `radiance:`/`vllm:` prefix and
+`_total` suffix) with the same definitions as the since-start gauges:
 
 | panel | over the window | since start |
 |---|---|---|
@@ -30,9 +31,10 @@ Window values are counter ratios with the definitions of the since-start gauges:
 | draft acceptance | `draft_accepted` / `draft_tokens` | `radiance:draft_acceptance_ratio` |
 | conditional acceptance at j | `draft_position_accepted`(j) / `draft_position_reached`(j) | `radiance:draft_position_acceptance_ratio` |
 
-Draft blocks per decode step is the reach of position 0 over `engine_steps_decode_total` (GUIDE §6.3).
-The adaptive draft window and verifies by draft depth have data only under `--draft-window adaptive`.
+Draft blocks per decode step is the reach of position 0 over `engine_steps_decode`
+([`docs/GUIDE.md`](../../docs/GUIDE.md) §6.3). The adaptive draft window and verifies by draft depth
+have data only under `--draft-window adaptive`.
 
 Prometheus extrapolates `rate()` inside the window and VictoriaMetrics does not, so short windows at
-the edge of a burst differ between the two. The overview's ratios are taken over the dashboard's time
-range, where both agree.
+the edge of a burst differ between the two. The overview's ratios are taken over the dashboard's
+time range, where both agree.
diff --git a/docker/build.sh b/docker/build.sh
index ead01197..5a632e7e 100755
--- a/docker/build.sh
+++ b/docker/build.sh
@@ -1,10 +1,10 @@
 #!/bin/sh
 # docker/build.sh -- build the radiance image from a commit with BuildKit (docker buildx) and tag it.
 #
-# The build context is `git archive` of the commit, so the image holds exactly what is committed:
-# no build trees, no uncommitted edits, no model files. With -s the archive is streamed over ssh
-# to another machine's own `docker buildx`, which builds and keeps the image; that machine needs
-# Docker with buildx and nothing else.
+# The build context is `git archive` of the commit, so the image holds only committed files (no
+# build trees, uncommitted edits or model files). With -s the archive is streamed over ssh to
+# another machine's `docker buildx`, which builds and keeps the image; that machine needs only
+# Docker with buildx.
 #
 #   docker/build.sh                       HEAD, here
 #   docker/build.sh -s HOST               HEAD, built on and kept by HOST
diff --git a/docker/licenses.sh b/docker/licenses.sh
index 0e91775c..18b4abf3 100755
--- a/docker/licenses.sh
+++ b/docker/licenses.sh
@@ -1,15 +1,14 @@
 #!/bin/sh
-# docker/licenses.sh ROOT FILE... -- the licenses of everything in the runtime image that radiance
-# did not write.
+# docker/licenses.sh ROOT FILE... -- record the licenses of all third-party software in the
+# runtime image.
 #
-# FILE... are the paths, in the build image, of every file copied into ROOT from outside the
-# radiance install: the shared libraries, comgr, busybox, curl, jq and the CA bundle's directory.
-# Each is traced to the package that installed it, or to the FFmpeg stage's /opt/ffmpeg. Every package's license files
-# are copied to ROOT/usr/share/doc//, the license texts Debian's copyright files refer to
-# go to ROOT/usr/share/common-licenses/, and ROOT/usr/share/doc/THIRD-PARTY lists each component
-# with its version, its license files and where its source is. A file that no package owns, or a
-# package that ships no license file, stops the build: the image would hold software whose license
-# is not recorded.
+# FILE... are the build-image paths of every file copied into ROOT from outside the radiance
+# install: the shared libraries, comgr, busybox, curl, jq and the CA bundle's directory. Each is
+# traced to its installing package, or to the FFmpeg stage's /opt/ffmpeg. Package license files go
+# to ROOT/usr/share/doc//, the texts Debian's copyright files refer to go to
+# ROOT/usr/share/common-licenses/, and ROOT/usr/share/doc/THIRD-PARTY lists each component with its
+# version, license files and source. A file no package owns, or a package with no license file,
+# fails the build, so no software ships with an unrecorded license.
 set -eu
 R=$1; shift
 D=$R/usr/share/doc
diff --git a/docker/llvm-check.sh b/docker/llvm-check.sh
index 9876d7c6..84f6c6ab 100755
--- a/docker/llvm-check.sh
+++ b/docker/llvm-check.sh
@@ -1,11 +1,11 @@
 #!/bin/bash
-# docker/llvm-check.sh BUILD -- the image's HIP compiler held to the two things it is for, on one of
-# the build's own compile commands: r4d_hc_bf16.hip, the file whose code varied from build to build
-# under ROCm's own clang. The command is run again four ways, outputs in a scratch directory:
+# docker/llvm-check.sh BUILD -- check the image's HIP compiler on the build's compile command for
+# r4d_hc_bf16.hip, a file whose device code is not repeatable under ROCm's stock clang. The command
+# is rerun four ways, outputs in a scratch directory:
 #   1. pairing off, by ROCm's clang and by the image's: the device code must match byte for byte,
-#      so the llvm stage's libLLVM is ROCm's but for the patch;
-#   2. pairing on, exactly as the build ran it, twice more by the image's clang: both must match
-#      the build's own object, so the pairing is repeatable.
+#      so the llvm stage's libLLVM is ROCm's apart from the patch;
+#   2. pairing on, as the build ran it, twice by the image's clang: both must match the build's own
+#      object, so pairing is repeatable.
 # A mismatch fails the image build.
 set -euo pipefail
 B=$1
@@ -27,8 +27,8 @@ for a in "${args[@]}"; do
     case "$a" in *amdgpu-enable-vopd*) fail "the build turned VOPD pairing off ($a)" ;; esac
 done
 
-# variant NAME COMPILER [FLAG]: the build's command with this compiler, its object and depfile in
-# the scratch directory, and FLAG appended; then the object's device code as NAME.fb.
+# variant NAME COMPILER [FLAG]: rerun the build's command with COMPILER, object and depfile in the
+# scratch directory and FLAG appended; dump the object's device code to NAME.fb.
 variant() {
     local name=$1 cc=$2 extra=${3:-} i=1
     local v=("$cc")
diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md
index 324a5e64..10444b05 100644
--- a/docs/ARCHITECTURES.md
+++ b/docs/ARCHITECTURES.md
@@ -1,68 +1,64 @@
-# Architectures — the geometry, and the traps that stay plausible when wrong
+# Architectures: geometry and traps
 
-One architecture plugin claims one **(architecture id, quantisation descriptor)** pair — that is the
-selection key of `spec.md` §2.4, and it is why a family with two checkpoint formats is two `.so`
-files rather than one that branches. `rad-convert` normalises whatever it read (safetensors or GGUF)
-into the id an architecture plugin claims.
+An architecture plugin claims one **(architecture id, quantisation descriptor)** pair, the
+selection key of `spec.md` §2.4, so a family with two checkpoint formats is two `.so` files rather
+than one that branches. `rad-convert` normalises what it reads (safetensors or GGUF) into the id a
+plugin claims.
 
 | plugin | id | quantisation | what it serves |
 |---|---|---|---|
-| `arch/llama_fp8` | `llama` | `fp8_e4m3` | the plain LLaMA decoder, from a checkpoint that already holds E4M3 codes and a `weight_scale_inv` plane |
-| `arch/llama_dense_fp8` | `llama` | *(empty)* | the same graph from a bf16 checkpoint; `rad-convert` quantises. MiniCPM5-2B |
+| `arch/llama_fp8` | `llama` | `fp8_e4m3` | the plain LLaMA decoder, from a checkpoint that holds E4M3 codes and a `weight_scale_inv` plane |
+| `arch/llama_dense_fp8` | `llama` | *(empty)* | the same graph from a bf16 checkpoint, linears made block fp8 by a recipe or kept bf16. MiniCPM5-2B |
 | `arch/qwen35_bf16` | `qwen35` | *(empty)* | the Qwen3.5/3.6/3.8 dense hybrid, served bf16 |
 | `arch/qwen35_fp8` | `qwen35` | `fp8_e4m3` | the same, block-scaled FP8 weights and activations |
 | `arch/qwen35moe_fp8` | `qwen35moe` | `fp8_e4m3` | `qwen35_fp8` with the feed-forward routed |
 | `arch/qwen4exp_fp8` | `qwen4exp` | *(empty)* | Qwen4-Exp (Qwen3.8-Flash-Next), a bf16 checkpoint quantised at convert |
+| `arch/lfm2_bf16` | `lfm2` | *(empty)* | LiquidAI's LFM2 and LFM2-VL, bf16, one rank |
 | `arch/embgemma2` | `embeddinggemma2` | *(empty)* | EmbeddingGemma 2: a bidirectional encoder with Gemma 4's vision tower and audio conformer, pooled to one vector |
-| `arch/gemma4_bf16` | `gemma4` | `compressed-tensors` | Gemma 4 31B dense (text): two attention classes — sliding-window and proportional-RoPE global (`attention_k_eq_v`) — over one GemmaRMSNorm stream, GELU ffn, two KV groups, softcapped logits, tied scaled embedding; served from a CT-INT4 (QAT w4a16) checkpoint as group-128 int4 codes with an f16 scale. Optional draft head: Google's assistant (`rad-convert --draft-model`), a serial head with no cache of its own (`rad_drafter_shared_kv`) |
-| `arch/gemma4` | `gemma4` | *(empty)* | Gemma 4 text from Google's bf16 checkpoint — the 26B-A4B MoE (a dense and a routed arm side by side) and the dense sizes without per-layer embeddings — with z-lab's DFlash drafter; routed experts bf16 or block fp8, as the recipe chose |
-| `arch/qwenimage21` | `qwenimage21` | *(empty)* | Qwen-Image 2.1 and 2.1-Turbo, an image GENERATOR: a Qwen3-VL-8B text encoder, a 32-block single-stream DiT and an RGBA VAE, from the diffusers pipeline directory; the DiT and text encoder bf16 or block fp8, as the recipe chose |
+| `arch/gemma4_bf16` | `gemma4` | `compressed-tensors` | Gemma 4 31B dense with its vision tower: sliding-window and proportional-RoPE global (`attention_k_eq_v`) attention, GELU ffn, softcapped logits; int4 codes with an f16 scale per 128 from Google's CT-INT4 (QAT) release, served w4a8. Optional draft head: Google's assistant (`rad-convert --draft-model`), with no cache of its own (`rad_drafter_shared_kv`) |
+| `arch/gemma4` | `gemma4` | *(empty)* | Gemma 4 text from Google's bf16 checkpoint (the 26B-A4B MoE and the dense sizes without per-layer embeddings) with z-lab's DFlash drafter; routed experts bf16 or block fp8 |
+| `arch/qwenimage21` | `qwenimage21` | *(empty)* | Qwen-Image 2.1 and 2.1-Turbo, an image generator, from the diffusers pipeline directory; DiT and text encoder bf16 or block fp8 |
+| `arch/qwen3asr_bf16` | `qwen3asr` | *(empty)* | Qwen3-ASR: a Whisper-style audio encoder over a dense Qwen3 decoder, speech to text |
 
-This document is the geometry of each, and the handful of readings that are **arithmetically
-silent** — wrong in a way that produces fluent output and no error anywhere.
+The traps below are readings that are wrong without any error: the model produces fluent output.
 
-## The rule that applies to all of them
+## Common rule
 
-**`head_dim` is READ, never derived.** On the Qwen hybrids `head_dim` is 256 while
-`hidden_size / num_attention_heads` is 213, so a derived value makes every downstream shape silently
-wrong — the projection widths, the KV page size, the attention kernel's band. `core/engine_bringup.cpp`
-takes it from the container's meta and says so at the line that does it.
+**`head_dim` is read, never derived.** On the Qwen hybrids `head_dim` is 256 while
+`hidden_size / num_attention_heads` is 213, and a derived value silently breaks the projection
+widths, the KV page size and the attention kernel's band. `core/engine_bringup.cpp` takes it from
+the container's meta.
 
 ---
 
-# `llama` — the plain decoder
+# `llama`: the plain decoder
 
-`model_type: llama` with `LlamaForCausalLM`, the most widely shared decoder shape there is. Every
-layer is full attention; there is no gated delta net, no layer schedule, no output gate and no
-per-head q/k norm, which is precisely what separates this plugin from `qwen35_fp8`.
+`model_type: llama` with `LlamaForCausalLM`. Every layer is full attention; unlike `qwen35_fp8`
+there is no gated delta net, layer schedule, output gate or per-head q/k norm.
 
-MiniCPM5-2B is what it exists for: 42 layers, hidden 2048, 16 query heads over 2 KV heads at
-`head_dim` 128, SwiGLU at 6144, RMS norms, full rotary at theta 5e6, an untied 130560-row head, and
-no biases anywhere.
+MiniCPM5-2B: 42 layers, hidden 2048, 16 query heads over 2 KV heads at `head_dim` 128, SwiGLU at
+6144, RMS norms, full rotary at theta 5e6, an untied 130560-row head, no biases.
 
-**Two checkpoint formats, one graph.** OpenBMB publishes MiniCPM5-2B in bf16 and nothing else, so
-"MiniCPM5-2B FP8A8" is a statement about what this engine *runs*, not about what the checkpoint
-holds. `llama_dense_fp8` declares the empty quantisation descriptor and the recipe
-`data/recipes/minicpm5-2b-dspark.recipe` does the work at conversion — libquant's `rtn`, one amax
-per 128x128 block, `scale = amax/448` rounded to bf16 — so the container holds the encoding a
-checkpoint that shipped fp8 would. Both plugins declare the same ops over the same encoding, and the
-kernels lay it out the same way at load, so nothing downstream can tell which one ran. For the same
-reason the bf16 checkpoint itself is not served directly: its linears are not the fp8 this plugin
-reads.
+**Two checkpoint formats, one graph.** OpenBMB publishes MiniCPM5-2B only in bf16, so
+`llama_dense_fp8` declares the empty quantisation descriptor and the recipe
+`data/recipes/minicpm5-2b-dspark.recipe` quantises at convert (libquant's `rtn`, one amax per
+128x128 block, `scale = amax/448` rounded to bf16). The container then holds what an fp8 release
+would, both plugins declare the same ops over it, and nothing downstream can tell which one ran. A
+container whose linears are left bf16 (`minicpm5-2b-bf16-dspark.recipe`) is read by `gemm_nt`.
 
-What is fp8: `self_attn.{q,k,v,o}_proj` and `mlp.{gate,up,down}_proj`, each with a bf16
-`[N/128][K/128]` scale plane. What is not: every norm and the embedding. The lm_head is declared at
-whatever the source holds — bf16 from a checkpoint, fp8 where the recipe made it so — and the
-selection picks the GEMM that reads it. Both vocabulary edges are row-sharded.
+fp8: `self_attn.{q,k,v,o}_proj` and `mlp.{gate,up,down}_proj`, each with a bf16 `[N/128][K/128]`
+scale plane. Not fp8: every norm and the embedding. The lm_head is declared at whatever the source
+holds (bf16 from a checkpoint, fp8 where the recipe made it so), and the GEMM that reads that
+encoding is selected. Both vocabulary edges are row-sharded.
 
 ---
 
-# `qwen35` — the hybrid Gated DeltaNet / gated-attention family
+# `qwen35`: the hybrid Gated DeltaNet / gated-attention family
 
-Qwen3.5, Qwen3.6 and Qwen3.8 dense models share this architecture; HuggingFace calls it
-`model_type: qwen3_5` (`Qwen3_5ForConditionalGeneration`) and GGUF calls it `qwen35`.
+Qwen3.5, Qwen3.6 and Qwen3.8 dense models. HuggingFace calls it `model_type: qwen3_5`
+(`Qwen3_5ForConditionalGeneration`); GGUF calls it `qwen35`.
 
-## Qwen3.8-27B-FP8, exactly
+## Qwen3.8-27B-FP8
 
 ```
 64 layers, full_attention_interval 4  ->  layers 3,7,...,63 are FULL ATTENTION (16 of them)
@@ -82,10 +78,7 @@ quantization: fp8 e4m3, activation_scheme "dynamic", per-weight `weight_scale_in
 vision: 27 blocks, hidden 1152, 16 heads -> head_dim 72, patch 16, out_hidden_size 5120
 ```
 
-### Why this lines up with libr4d
-
-Every geometry above lines up with a libr4d entry point, which is the strongest available evidence
-that the kernel-plugin constraint model is the right shape.
+### libr4d entry points
 
 | model geometry | libr4d entry point |
 |---|---|
@@ -97,11 +90,12 @@ that the kernel-plugin constraint model is the right shape.
 | GDN gated norm over an interleaved z | `gdn_gated_norm_had_quant_i8` (`zgrp`/`zblk`) |
 | vision head_dim 72 | `attn_vit_h72_bf16` |
 
-## Tensor names — the FP8 safetensors checkpoint
+## Tensor names: the FP8 safetensors checkpoint
 
 Sharded one file per layer (`layers-N.safetensors`), plus `outside.safetensors` and
-`mtp.safetensors`. Every FP8 weight carries a companion `weight_scale_inv`; the norms, biases,
-`A_log`, `dt_bias` and `conv1d` stay bf16.
+`mtp.safetensors`. Every FP8 weight has a companion `weight_scale_inv`; the norms, biases, `A_log`,
+`dt_bias` and `conv1d` stay bf16. Linear shapes below are `[in, out]`, as the plugins write them;
+the safetensors tensors are stored `[out, in]`.
 
 **Full-attention layer** (`model.language_model.layers.N.`):
 ```
@@ -129,14 +123,14 @@ mlp.{gate,up,down}_proj  as above
 ```
 
 **Model level**: `model.language_model.embed_tokens.weight`, `model.language_model.norm.weight`,
-`lm_head.weight` (**not tied** on this model), and the MTP head: `mtp.fc.weight`,
-`mtp.norm.weight`, `mtp.pre_fc_norm_embedding.weight`, `mtp.pre_fc_norm_hidden.weight`.
+`lm_head.weight` (not tied on this model), and the MTP head: `mtp.fc.weight`, `mtp.norm.weight`,
+`mtp.pre_fc_norm_embedding.weight`, `mtp.pre_fc_norm_hidden.weight`.
 
-## The full-attention layer — gated attention
+## Full-attention layer: gated attention
 
 `q_proj` produces the query **and a gate, interleaved per head**: for each of the 24 heads the
-first 256 elements are the query and the next 256 are the gate, so both are strided views with
-pitch 512 rather than a contiguous split.
+first 256 elements are the query and the next 256 the gate, so both are strided views with pitch
+512.
 
 ```
 qg      = gemm(x, q_proj)                  [n_tok, 12288]
@@ -151,11 +145,11 @@ o       = o * sigmoid(gate)                <-- the gate. output_gate_type "swish
 out     = gemm(o, o_proj)
 ```
 
-`qk_norm_rope_gate` does the two norms, the rope and the gate extraction in one kernel and takes the
-interleaving off the `q_gate` operand's own row pitch, so the projection is declared as it is laid
-out rather than converted at load. Declare it first and fall back to the unfused sequence.
+`qk_norm_rope_gate` does the two norms, the rope and the gate extraction in one kernel, taking the
+interleave from the `q_gate` operand's row pitch, so the projection is declared as laid out rather
+than converted at load. Declare it first and fall back to the unfused sequence.
 
-## The linear layer — gated delta net
+## Linear layer: gated delta net
 
 ```
 qkv     = gemm(x, in_proj_qkv)             [n_tok, 10240]
@@ -171,29 +165,27 @@ o       = rmsnorm(o, linear_attn.norm) * silu(z)           the gated norm
 out     = gemm(o, out_proj)
 ```
 
-`linear_num_value_heads` (48) is three times `linear_num_key_heads` (16), so q and k are shared
-across three value heads. libr4d's GDN kernels take `H` and `Hg` separately for exactly this.
+`linear_num_value_heads` (48) is three times `linear_num_key_heads` (16), so each q/k head serves
+three value heads; libr4d's GDN kernels take `H` and `Hg` separately for this.
 
-## Things that stay plausible when wrong, so get them right
+## Traps
 
-- **`q`/`k` use L2 normalisation, not RMS.** Different op, different arithmetic.
-- **`A_log` is a log.** In the GGUF conversion `ssm_a` is already `-exp(A_log)`; in *this*
-  safetensors checkpoint the tensor is named `A_log` and the exponent has **not** been taken. The
-  converter is the component that decides which convention reaches the kernel, and it must say so.
+- **`q`/`k` use L2 normalisation, not RMS.**
+- **`A_log` is a log.** In the GGUF conversion `ssm_a` is already `-exp(A_log)`; in this safetensors
+  checkpoint the tensor is `A_log` with the exponent not taken. The converter decides which
+  convention reaches the kernel, and must say so.
 - **The GDN output gate is `silu` here and `sigmoid` on Qwen4-Exp.** `RMSNormGated` defaults to silu
-  and every Qwen3.5/3.6 release leaves it there; Qwen4-Exp states `output_gate_type: "sigmoid"` and
-  means it. A gate of `sigmoid(z)` where the model wants `silu(z)` rescales every value head's
-  output — a config read, not a kernel to write. `arch/common/rad_block_gdn_fp8.h` refuses anything
-  but those two names.
-- **Two readings the checkpoint cannot settle by inspection.** The rope convention (`neox`, halves,
-  against `gptj`, adjacent pairs) and which half of each head's `q|gate` pair is the query are both
-  self-consistent either way, and the sigmoid accepts either half — so no per-op check can reach
-  them. The MTP head's concat order (hidden-first or embedding-first) is the third of the same kind.
-  Each is a declared knob at the site that reads it, for the same reason.
+  and every Qwen3.5/3.6 release keeps it; Qwen4-Exp sets `output_gate_type: "sigmoid"`. The wrong
+  gate rescales every value head's output. `arch/common/rad_block_gdn_fp8.h` refuses any other
+  name.
+- **Readings no per-op check can settle.** The rope convention (`neox`, halves, against `gptj`,
+  adjacent pairs), which half of each head's `q|gate` pair is the query (the sigmoid accepts
+  either), and the MTP head's concat order (hidden-first or embedding-first) are all
+  self-consistent either way. Each is a declared knob at the site that reads it.
 
 ## KV groups
 
-Three of them, which is why hybrid KV groups are first-class rather than an extension:
+Three groups, which is why hybrid KV groups are first-class:
 
 | group | kind | geometry |
 |---|---|---|
@@ -201,59 +193,52 @@ Three of them, which is why hybrid KV groups are first-class rather than an exte
 | GDN recurrent state | `RAD_KV_LINEAR` | 48 layers, 48 states of 128 x 128 |
 | GDN conv state | `RAD_KV_CONV` | 48 layers, 2*16 + 48 = 80 heads x 128 = 10240 channels, a rolling `conv_width - 1 + n_spec` window |
 
-**The recurrent state is f32 by default**, which is 48 x 128 x 128 x 4 = 3 MiB a layer and
-**144 MiB across the 48 linear layers, per sequence** — and it is what the prefix-cache checkpoint
-of `spec.md` §7.3 snapshots. Its read and write are most of what the two GDN kernels do, so halving
-its width halves one of the largest kernels after the fp8 GEMMs. libr4d compiles an f16 form and
-argues the numerics where the kernel lives — the elements are O(0.1) with no range problem and
-f16's eleven mantissa bits put the round-trip error at 5e-4 relative. It is **off by default
-anyway**, because it changes generated text without being asked to; nothing about the container
-changes between the two, so there is no re-convert. How a speculative step keeps the state it can
-roll back is `docs/OPS.md`'s `state_form`.
+**The recurrent state is f32**: 48 x 128 x 128 x 4 = 3 MiB per layer, **144 MiB per sequence**
+across the 48 linear layers, and it is what the prefix-cache checkpoint of `spec.md` §7.3
+snapshots. Its reads and writes dominate the two GDN kernels. libr4d also compiles an f16 form
+(elements are O(0.1); the f16 round trip is about 5e-4 relative) that would halve that traffic,
+but the plugins declare f32 because f16 changes the generated text. How a speculative step keeps a
+state it can roll back is `docs/OPS.md`'s `state_form`.
 
 ## FP8
 
 `quant_method: fp8`, `fmt: e4m3`, `activation_scheme: dynamic`, and a `weight_scale_inv` beside
-every quantised weight — DeepSeek-style block scaling, 128x128. Activations are quantised at
-runtime, which is what "dynamic" means and what makes the activation quantiser an op rather than a
-constant. The vision tower's first several blocks are in `modules_to_not_convert` and stay bf16.
+every quantised weight: DeepSeek-style 128x128 block scaling. Activations are quantised at runtime
+("dynamic"), so the activation quantiser is an op. The vision tower's first several blocks are in
+`modules_to_not_convert` and stay bf16.
 
-**libr4d reads those bytes directly, so `rad-convert` COPIES**: no permutation, no repacking, no
-dequantisation, and a `.rad` costs what the checkpoint does. That is the whole reason this plugin
-family exists — widening a 27B FP8 checkpoint to bf16 doubles the weight bytes; `qwen35_bf16` is the
-plugin for a checkpoint that is bf16 to begin with.
-The rows are `gemm_fp8a16_nt_m1`, `gemm_fp8a8_nt_m16`, `gemm_fp8a8_gated_nt_m16` and
+**libr4d reads those bytes directly, so `rad-convert` copies them**: no permutation, repacking or
+dequantisation, and a `.rad` costs what the checkpoint does. Widening a 27B FP8 checkpoint to bf16
+would double the weight bytes; `qwen35_bf16` is for checkpoints that are bf16 to begin with. The
+rows are `gemm_fp8a16_nt_m1`, `gemm_fp8a8_nt_m16`, `gemm_fp8a8_gated_nt_m16` and
 `gemm_fp8a8_tiled`.
 
-**The shipped path is `fp8a8`**, and the reason is a band and not a preference. `dtype` is ONE string
-per declared op, so a linear is `fp8a16` or `fp8a8` and cannot be both. `fp8a16` reads a bf16
-activation directly and needs no quantise launch, which is strictly better — and its kernel serves
-`M <= 1`, which is a single-sequence decode and nothing else. `fp8a8`'s two kernels cover every M
-between them, and the price is one `quant_act_fp8` launch per activation that feeds a GEMM — *per
-activation*, not per linear, which is why the quantiser is its own struct rather than a step inside
-the linear.
+**The shipped path is `fp8a8`.** `dtype` is one string per declared op, so a linear is `fp8a16` or
+`fp8a8`, not both. `fp8a16` reads the bf16 activation directly with no quantise launch, but its
+kernel serves only `M <= 1` (single-sequence decode). `fp8a8`'s two kernels cover every M, at the
+price of one `quant_act_fp8` launch per activation that feeds a GEMM. That cost is per activation,
+not per linear, which is why the quantiser is its own struct rather than a step inside the linear.
 
-**The scale plane is a WEIGHT operand**: `gemm_nt_q` takes `a, a_scale, b, b_scale`, and `b` and
+**The scale plane is a weight operand**: `gemm_nt_q` takes `a, a_scale, b, b_scale`, and `b` and
 `b_scale` are two declarations over the planes of one logical weight (`RadWeightDecl::planes`).
-Each is placed, moved and sharded on its own — the engine cuts a row-sharded scale plane on its
-block boundary exactly as it cuts the codes beside it.
+Each is placed, moved and sharded on its own; the engine cuts a row-sharded scale plane on its
+block boundary as it cuts the codes.
 
 ## `qwen35moe`
 
-This architecture with the MLP replaced by a router plus experts, and *only* that: the gated
-attention, the gated delta net, the layer schedule, the rope, the vocabulary edges and the MTP head
-are identical, and the places where a routed feed-forward differs are behind one conditional in the
-shared source. It is a second translation unit rather than a branch on `n_expert` because the id is
-half the selection key — one `.so` cannot claim both, and an operator looking at what is installed
-should see two plugins for two architectures.
+The same architecture with the MLP replaced by a router plus experts; the gated attention, the
+gated delta net, the layer schedule, the rope, the vocabulary edges and the MTP head are identical,
+and every difference is behind `#if QWEN35_MOE` in the shared source. It is a second translation
+unit rather than a branch on `n_expert` because the id is half the selection key, and one `.so`
+cannot claim both ids.
 
 ---
 
-# `qwen4exp` — Qwen4-Exp / Qwen3.8-Flash-Next
+# `qwen4exp`: Qwen4-Exp / Qwen3.8-Flash-Next
 
-`model_type: qwen4_exp`, a subclass of `Qwen3_5MoeTextModel` — so most of it is composition over the
-blocks above. What is genuinely new is small and named: the gated residual, the n-gram/PLE layer,
-QSA's indexer, stacked dense expert tensors, GQA 12, and the delta net's sigmoid output gate.
+`model_type: qwen4_exp`, a subclass of `Qwen3_5MoeTextModel`, so most of it composes the blocks
+above. New: the gated residual, the n-gram/PLE layer, QSA's indexer, stacked dense expert tensors,
+GQA 12, and the delta net's sigmoid output gate.
 
 ```
 48 layers of 12 x (3 x GatedDeltaNet -> MoE, then 1 x QSA -> MoE)
@@ -265,146 +250,116 @@ indexer_n_heads 4  indexer_head_dim 128  indexer_budget 2048  indexer_compress_r
 mtp_num_hidden_layers 1        output_gate_type sigmoid
 ```
 
-**The residual stream is four times as wide, and the blocks do not own their norms.** There is no
-`input_layernorm`, no `post_attention_layernorm` and no final `norm` in this checkpoint. In their
-place every block has a gated residual connection — a grouped norm over the 10240 stream, a low-rank
-data-dependent read gate that mixes the four sub-streams down to 2560, and four data-dependent
-scalars that gain the block's output back into all four. 96 of them, plus a 97th with no write half
-that collapses the stream for the lm_head. The consequence for the blocks is that they run in their
-"input is already normed and quantised" mode and therefore give up two fusions — the residual add
-folded into the next norm, and the all-reduce folded into it.
+**The residual stream is four times as wide, and the blocks do not own their norms.** The
+checkpoint has no `input_layernorm`, `post_attention_layernorm` or final `norm`. Each block has a
+gated residual connection instead: a grouped norm over the 10240 stream, a low-rank data-dependent
+read gate that mixes the four sub-streams down to 2560, and four data-dependent scalars that add
+the block's output back into all four. There are 96, plus a 97th with no write half that collapses
+the stream for the lm_head. The blocks run in their "input already normed and quantised" mode and
+so give up two fusions: the residual add and the all-reduce folded into the next norm.
+
+**Each weight's storage is the recipe's choice.** The checkpoint is bf16 with no
+`quantization_config`, so the descriptor is empty; `rad-convert` quantises by a recipe, and the
+plugin reads each weight's encoding from the container and declares the op that reads it:
+
+- block linears (`self_attn.{q,k,v,o}_proj`, `linear_attn.{in_proj_qkv, in_proj_z, out_proj}`,
+  the shared expert's three): fp8 or int8 (served W8A8);
+- routed experts' gate_up and down: fp8, bf16, or one of the four- and five-bit forms of
+  `docs/MOE-W4.md`;
+- each connection's two mixing matrices and the MTP head's `fc_hidden` / `fc_embedding`: E4M3 rows
+  or bf16. The low-rank width is 320, 2.5 scale blocks, so they are scaled a row group at a time;
+- the lm_head: whatever a `logits_gemm` kernel reads;
+- bf16: every norm gain, `A_log`, `dt_bias`, `conv1d`, `in_proj_a` and `in_proj_b` (48 rows is not
+  a whole scale block), the router, `shared_expert_gate` and `embed_tokens`.
 
-**What each weight is stored as is the recipe's decision.** The checkpoint is bf16 throughout and
-carries no `quantization_config` at all, so the plugin's descriptor is the empty one: `rad-convert`
-quantises by a recipe, and the plugin reads each weight's encoding from the container and declares
-the op that reads it. The block linears — `self_attn.{q,k,v,o}_proj`,
-`linear_attn.{in_proj_qkv, in_proj_z, out_proj}`, the shared expert's three — are block fp8 or
-int8 (served W8A8). Every routed expert's gate_up and down is fp8, bf16, or one of the four- and
-five-bit forms of `docs/MOE-W4.md`.
-Each connection's two mixing matrices and the MTP head's `fc_hidden` / `fc_embedding` are E4M3 rows
-or bf16: the low-rank width is 320, which is 2.5 scale blocks, so they are scaled a row group at a
-time rather than block-scaled. The lm_head is whatever a `logits_gemm` kernel reads. Every norm
-gain, `A_log`, `dt_bias`, `conv1d`, `in_proj_a` and `in_proj_b` (48 rows is not a whole scale
-block), the router, `shared_expert_gate` and `embed_tokens` stay bf16.
 `data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe` is the served choice: four-bit codebook experts with
 ten protected experts left bf16, int8 block linears and lm_head, E4M3 mixing and MTP fc matrices,
 and the n-gram table at one fixed E4M3 scale.
 
-**Tensor parallel at two ranks splits every expert's width, unevenly.** `moe_intermediate_size` is
-640 = 5 x 128, so an even share at tp2 is 320, which is not a whole number of 128-column blocks —
-and the fp8 scale block, the four-bit scale group and the rotation all sit on them. So each rank
-takes three blocks of the experts of one parity and two of the other's (`moe_gemm_q`'s two tables in
-`docs/OPS.md`), the router stays replicated so both ranks agree on the routing, each rank computes
-its slice of every routed expert, and the block's existing end-of-block all-reduce sums the
-partials. No all-to-all, no extra collective. The shared expert's 640 columns split the same way,
-three blocks on rank 0 and two on rank 1.
+**Tensor parallelism splits every expert's width.** `moe_intermediate_size` is 640 = 5 x 128, and
+the fp8 scale block, the four-bit scale group and the rotation all sit on 128-column blocks, so an
+even tp2 share (320) does not work. Each parity's five blocks are cut contiguously across the
+ranks, and the rank taking the extra block alternates with the parity: at tp2 a rank takes three
+blocks of the experts of one parity and two of the other's (`moe_gemm_q`'s two tables in
+`docs/OPS.md`). The router is replicated, each rank computes its slice of every routed expert, and
+the block's existing all-reduce sums the partials: no all-to-all, no extra collective. A world
+above the block count is refused at declare, since an empty slice would still join the
+all-reduce. The shared expert splits as evenly as whole blocks allow: three blocks on rank 0 and
+two on rank 1 at tp2; at tp4, rank 2 `[0, 256)` and one block each on ranks 3, 0 and 1.
 
-**Five blocks do not divide evenly, and an even share is not required.** 5 is odd, so at tp4 an
-even share is 160 columns, 1.25 blocks — but the split is TWO SLICES per expert, not one slice a
-rank: each parity's blocks are cut contiguously across the ranks and the rank taking the odd block
-alternates with the parity, so every rank's share is whole blocks, every block of every expert has
-exactly one owner, and each rank still computes a slice of every routed expert. At four ranks and
-five blocks an even-parity expert is `[0, 2)` blocks on rank 0, `[2, 3)` on rank 1, `[3, 4)` on
-rank 2, `[4, 5)` on rank 3, and each rank's place on the odd parity shifts by one — rank 1 takes the
-fat block there instead of rank 0 — so no rank takes the extra block of both parities. A world
-above the block count is refused at declare, by name: a rank with an empty slice computes nothing
-and still joins the all-reduce. The shared expert's 640 columns split as evenly as whole blocks
-allow: five blocks over four ranks is rank 2 `[0, 256)` and one block each on ranks 3, 0 and 1.
-
-**At four ranks the classes are four.** Parity gives the extra block only two places to go, so
-ranks 0 and 1 would compute three blocks of every even/odd pair of routed experts and ranks 2 and 3
-two, and every block's all-reduce would have 2 and 3 wait. So at four ranks the cut above is made
-per class of the expert's number mod 4, the rank's place shifted by the class: rank `r` takes
-`[0, 2)` blocks of class `r` and one block of each other class, five blocks of every four experts
-on every rank. That is `moe_gemm_q_mod4`, four slice tables where `moe_gemm_q` takes two
-(`docs/OPS.md`), and every slice is one a rank already took of some parity. A layer that keeps two
-experts plain bf16 has 510 quantised ones, and its first two classes are one expert longer. What
-does not divide elsewhere stays apart: the shared expert's extra block is rank 2's and the
+**At four ranks the classes are four.** Parity alone would give ranks 0 and 1 three blocks of every
+expert pair and ranks 2 and 3 two. So at tp4 the cut is made per class of the expert's number
+mod 4: rank `r` takes blocks `[0, 2)` of class `r` and one block of each other class, five blocks
+of every four experts on every rank (`moe_gemm_q_mod4`, four slice tables). A layer that keeps two
+experts plain bf16 has 510 quantised ones, and its first two classes are one expert longer. The
 protected bf16 experts' ten 64-wide tiles go 3, 3, 2, 2.
-Expert parallelism — whole experts a rank — is what this replaced, and why it stays replaced: the
-recipe protects its bf16 experts in pairs precisely so each rank's quantised count stays even, and
-sharding experts by rank breaks that parity property the weight tables rest on.
 
-**Attention splits by KV head, and replicates once the ranks outrun the heads.** There are 2 KV
-heads of 256 rows, so each rank declares `n_head_kv 1` and reads one head's row-span of `k_proj` and
-`v_proj`. At tp2 that is the ordinary row shard. At tp4 the heads cannot divide four ways, so they
-are replicated in rank pairs: ranks {0,1} carry KV head 0, ranks {2,3} carry KV head 1, and both
-ranks of a pair hold byte-identical KV weights — more read traffic, no extra VRAM. `n_head` is 12 a
-rank at tp2 and 6 at tp4, so gqa is 12 at tp2 and 6 at tp4 and the attention kernel is a different
-instantiation (`attn_{prefill,decode}_h256_gqa6_bs4`, the QSA page of 4) than the gqa12 pair tp2
-resolves to, not the same kernel over fewer heads. Any world size above the KV head count must be a
-multiple of it: 4 is a multiple of 2, 3 and 5 are not, and those widths are refused at declare
-time.
+Expert parallelism (whole experts per rank) is not used: random routing leaves ranks whole experts
+apart and waiting at the all-reduce, and it would break the parity tables, for which the recipe
+protects bf16 experts in pairs.
 
-**The fused all-reduce forms are two-rank, except the exact write.** At four ranks `ar_hc_write`
-exists on the exact wire only (`ar_hc_write_4rank`, the 4-rank one-shot with the write as its
-epilogue), and so does `ar_gather_hc_write` (`ar_gather_hc_write_4rank`, the same with
-`moe_gather` as its prologue), which the MoE connections take wherever the step is one MoE pass.
-Both are declared over the rows of a decode or verify step — `--max-num-seqs` × (1 +
-`--num-speculative-tokens`) — because a one-shot is for those messages, and a step within that
-bound takes them wherever its message goes out exact: always with `--tp-wire exact`, and with
-`--tp-wire wht6` under `--tp-wire-min-kb`. They run on an all-reduce instance keyed by that bound,
-not on the standalone all-reduce's unless the two bounds agree; the wide family's flag, sequence
-and slot discipline is what makes either safe on one stream. A prefill chunk, and every message
-that goes out lossy, keeps the standalone sequence — `moe_gather` on the MoE connections,
-`all_reduce` (whose size bands pick the 4-rank one-shot or two-shot, or ti8 on the lossy wire),
-then `hc_write_bf16`. The unfused sequence is declared beside the fused one, so nothing is
-unresolved at boot. The attention's own fusion is not a collective and does carry over: the sparse
-decode with the output gate and the quantiser in its merge (`attn_paged_gate_quant`) has gqa-6,
-page-4 rows. The per-step cost against tp2 on the same cards is unmeasured.
+**Attention splits by KV head.** There are 2 KV heads of 256 rows; each rank declares
+`n_head_kv 1` and reads one head's row span of `k_proj` and `v_proj`. At tp2 that is the ordinary
+row shard. At tp4 the heads are replicated in rank pairs (ranks {0,1} carry KV head 0, {2,3} KV
+head 1; both ranks of a pair hold identical KV weights, at no extra VRAM per rank). `n_head` is 12
+per rank at tp2 and 6 at tp4, so tp4 resolves a different instantiation
+(`attn_{prefill,decode}_h256_gqa6_bs4`, the QSA page of 4) than tp2's gqa12 pair. A world that
+neither divides nor is a multiple of the KV head count (3, 5) runs attention on the largest
+multiple below it and leaves the other ranks attention-zero; `docs/TP3.md` describes this and the
+uneven delta-net head split.
 
-**One collective does generalise, because it has to.** The lm_head is vocab-sharded, so the sampler
-gathers the ranks' candidate sets rather than their logits (`core/sample/sampler.cpp`) and an
-`all_gather` is on every step's sample path at any world size above one. libr4d shipped a two-rank
-form only — one peer flag, a `1 - rank` peer index, a destination stride of `2 * row16` — so the
-N-rank gather is a new kernel, not a fallback: at four ranks nothing but the reference
-implementation resolves and the engine refuses to serve rather than run a naive gather. It is the
-same one-shot push as the N-rank all-reduce with the reduction removed, and it moves the
-(u32 id, f32 logit) pairs without ever adding them.
+**Fused all-reduce forms at four ranks.** The fused forms are two-rank except on the exact wire:
+`ar_hc_write_4rank` (the 4-rank one-shot with the gated-residual write as its epilogue) and
+`ar_gather_hc_write_4rank` (the same with `moe_gather` as its prologue, taken by the MoE
+connections when the step is one MoE pass). Both are declared over the rows of a decode or verify
+step, `--max-num-seqs` x (1 + `--num-speculative-tokens`), and used whenever a step within that
+bound sends its message exact: always with `--tp-wire exact`, and with `--tp-wire wht6` under
+`--tp-wire-min-kb`. They run on an all-reduce instance keyed by that bound. A prefill chunk, and
+every lossy message, uses the standalone sequence: `moe_gather`, `all_reduce` (4-rank one-shot or
+two-shot by size, or ti8 on the lossy wire), then `hc_write_bf16`. The unfused sequence is
+declared beside the fused one, so nothing is unresolved at boot. The sparse decode's fused output
+gate and quantiser (`attn_paged_gate_quant`) has gqa-6, page-4 rows.
 
-**Four-bit experts are what make it fit.** 512 experts of 640 over 48 layers is 112.8 GiB of expert
+**Candidate gather.** The lm_head is vocab-sharded, so the sampler gathers the ranks' candidate
+sets rather than their logits (`core/sample/sampler.cpp`), and every step at a world above one runs
+an `all_gather`. libr4d serves it at 2 ranks (`r4d_ar_gather_2rank.hip`) and at 3, 4 and 8
+(`r4d_ar_gather_Nrank.hip`, moving (u32 id, f32 logit) pairs without adding them). Where no device
+row resolves, only libref's host gather does, and the serve is refused.
+
+**Four-bit experts are what make it fit.** 512 experts of 640 over 48 layers is 112.5 GiB of expert
 weight at E4M3 and twice that at bf16. `--weights-disk-tier` serves what fits neither VRAM nor the
-host pool from the container file, but a routed expert is then read a layer at a time and a step is
-paced by the drive. At four bits an expert unit is 2.42 MiB instead of 4.69 and the per-rank share
+host pool from the container file, but then a routed expert is read a layer at a time and a step is
+paced by the drive. At four bits an expert unit is 2.42 MiB instead of 4.69, and the per-rank share
 fits VRAM plus a few GiB of pinned host. `docs/MOE-W4.md` is the format.
 
-**PLE / the n-gram embedding is 51B of the model's 180B parameters** — a 320,001,536-row table of
-160-dim embeddings, gathered 16 rows a token by a hash of the last three token ids, read once at
-layer 1 and injected into the wide stream. Without it this is a 125B model missing a third of its
-parameters.
+**PLE, the n-gram embedding, is 51B of the model's 180B parameters**: a 320,001,536-row table of
+160-dim embeddings, gathered 16 rows per token by a hash of the last three token ids, read once at
+layer 1 and injected into the wide stream.
 
 **QSA** picks the best `indexer_budget / indexer_compress_ratio` = 512 blocks of 4 tokens for each
 query and attends to those alone. Below `indexer_budget + indexer_compress_ratio - 1` = 2051 tokens
-of context every complete block is selected, so QSA is dense causal attention bit for bit — which is
-why a prefill below the bound runs the cheaper dense attention, and is the property any change to it
-is argued against. `docs/QSA.md` is the decomposition.
+of context every complete block is selected and QSA equals dense causal attention bit for bit, so
+a prefill below the bound runs the cheaper dense attention, and every change is tested against
+that equality. `docs/QSA.md` is the decomposition.
 
 The vision tower is declared when the container carries one and `--mm-max-patches` is not 0
 (`arch/common/rad_block_vit.h`, `spec.md` §11).
 
 ---
 
-# Two rules about measuring these
+# Sample size
 
-**A bisect knob is not a deployment knob.** Several switches here ablate a block or a layer range;
-they produce a DIFFERENT MODEL and exist so that a wrong distribution can be attributed to a block
-when nothing compares a whole layer against an oracle. A serve that sets one is a serve that is not
-running the model, and the plugin says so at declare time. **Knobs are documented where they are
-read** — a table of them in a document goes stale silently and ends up naming variables nothing
-reads.
-
-**THE SAMPLE SIZE IS PART OF THE RESULT.** Top-1 agreement between two numeric formats is one
-Bernoulli trial per prompt, so at p ≈ 0.93 its standard error is 2.8 points at N = 80 and 2.0 at
-N = 160 — wide enough that formats which differ by less than that rank in any order. Rank with a
-graded statistic that has thousands of samples rather than hundreds (the mean |delta| over the
-logits row, or the per-position KL of `radiance --kld-ref`), and confirm any ordering at N ≥ 160
-before acting on it.
+Top-1 agreement between two numeric formats is one Bernoulli trial per prompt, so at p ≈ 0.93 its
+standard error is 2.8 points at N = 80 and 2.0 at N = 160: formats that differ by less than that
+rank in any order. Rank with a graded statistic that has thousands of samples (the mean |delta|
+over the logits row, or the per-position KL of `radiance --kld-ref`), and confirm any ordering at
+N ≥ 160 before acting on it.
 
 ---
 
-# `embeddinggemma2` — an embedding model
+# `embeddinggemma2`: an embedding model
 
-`arch/embgemma2` declares a POOLED output (`rad_declare_pooled`) and no logits, which makes the
+`arch/embgemma2` declares a pooled output (`rad_declare_pooled`) and no logits, which makes the
 program an embedding program: the engine runs it with no sampler and no KV cache, carries every
 input whole in one step, and returns each sequence's pooled row on `/v1/embeddings`
 ([GUIDE §5.6](GUIDE.md)). One card (`--tp 1`).
@@ -425,39 +380,41 @@ audio     Gemma 4's USM conformer: two stride-2 3 x 3 convolutions over (time, m
           embedder -> 512; 4 frames (40 ms) a token, clips cut at 30 s
 ```
 
-The traps:
+Traps:
 
 - **The embedding scale is the bf16 of sqrt(512)**, 22.625, because the reference stores it as a
-  bf16 buffer. sqrt(512) itself is off by one part in 800 on every embedding.
+  bf16 buffer. sqrt(512) itself is off by about 1e-4 relative on every embedding.
 - **A media row replaces its placeholder's embedding before the per-layer inputs are projected.**
-  The per-layer input of an image token is computed from its image row, not from the placeholder
-  id's embedding.
-- **The vision rotary is two independent neox rotaries**, one over each half of a head (`qk_norm_rope`
-  mode `blocks`). `rope` mode `axial` pairs across the halves and is a different function.
-- **The vision pooler stores the mean in bf16 before scaling it by sqrt(768)** (`pool_rows`), and
-  the processor lays each 3 x 3 window's patches out consecutively so the pooler is a mean of nine
+  An image token's per-layer input is computed from its image row, not from the placeholder id's
+  embedding.
+- **The vision rotary is two independent neox rotaries**, one over each half of a head
+  (`qk_norm_rope` mode `blocks`). `rope` mode `axial` pairs across the halves and is a different
+  function.
+- **The vision pooler stores the mean in bf16 before scaling it by sqrt(768)** (`pool_rows`). The
+  processor lays each 3 x 3 window's patches out consecutively, so the pooler is a mean of nine
   consecutive rows; attention and both position terms read each patch's own coordinates.
 - **The audio subsampler masks its input to the clip's real frames before each convolution**: the
   second convolution reads the first one's output at frame 2t's validity (`conv2d`'s `valid`
-  operand, stride 2), which zeroes the one row past the real ones that the zero padding alone
-  would not.
+  operand, stride 2), which zeroes the one row past the real ones that zero padding alone would
+  not.
 - **The audio attention reaches 11 rows back, not 12.** The config says `attention_context_left`
-  13 and the chunked layout fetches 12 keys behind each block, but the mask transformers applies
-  keeps a key only when `0 <= q - k < context_left - 1`. Twelve back drifts a few percent a block
-  and leaves rows at cosine 0.6 by the last one.
+  13 and the chunked layout fetches 12 keys behind each block, but transformers' mask keeps a key
+  only when `0 <= q - k < context_left - 1`. Twelve back drifts a few percent per block and leaves
+  rows at cosine 0.6 by the last one.
 - **An audio clip's tokens are ceil(real frames / 4)**, real frames being those whose last sample
-  is a real one; the processor stages exactly those plus zero frames to whole rows, which
-  reproduces every row the reference keeps.
+  is real; the processor stages exactly those plus zero frames to whole rows, which reproduces
+  every row the reference keeps.
 
 ---
 
-# `gemma4` — Gemma 4 text, and its DFlash drafter
+# `gemma4`: Gemma 4 text and its DFlash drafter
 
-`arch/gemma4` serves a container converted from Google's bf16 checkpoint (`Gemma4ForConditionalGeneration`
-or `Gemma4ForCausalLM`), the recipe choosing what is fp8: gemma-4-26B-A4B-it, and the dense sizes
-without per-layer embeddings. The CT-INT4 31B release is `arch/gemma4_bf16`'s. A z-lab DFlash
-drafter is merged at convert time (`--draft-model`); the recipes are
-`data/recipes/gemma4-26b-a4b-df*.recipe`. The reference is transformers' `modeling_gemma4`.
+`arch/gemma4` serves a container converted from Google's bf16 checkpoint
+(`Gemma4ForConditionalGeneration` or `Gemma4ForCausalLM`), the recipe choosing what is fp8:
+gemma-4-26B-A4B-it, and the dense sizes without per-layer embeddings. The CT-INT4 31B release is
+`arch/gemma4_bf16`'s. A z-lab DFlash drafter is merged at convert time (`--draft-model`); the
+recipes are `data/recipes/gemma4-26b-a4b-df*.recipe`. The reference is transformers'
+`modeling_gemma4`.
 
 ```
 gemma-4-26B-A4B-it
@@ -478,115 +435,111 @@ DFlash    a small Qwen3-shaped block drafter: an anchor and block - 1 mask token
           pass over the trunk's hidden states at target_layer_ids; drafts read off the TARGET's head
 ```
 
-The readings that stay plausible when wrong:
+Traps:
 
 - **Proportional rope is not a partial rotary.** The full layers rotate the first 64 frequency
-  pairs of the 512-wide head at theta^(-2j/512) — the exponent divides by the HEAD — with pair j
-  channels (j, j + 256), and leave the other 192 pairs at frequency zero. `rope` with
-  `rotary_dim` 128 pairs (j, j + 64) at theta^(-2j/128): a different function that still produces
+  pairs of the 512-wide head at theta^(-2j/512) (the exponent divides by the head width), with pair
+  j at channels (j, j + 256), and leave the other 192 pairs at frequency zero. `rope` with
+  `rotary_dim` 128 pairs (j, j + 64) at theta^(-2j/128), a different function that still produces
   fluent text. The plugin declares a full-width NeoX `rope` whose frequencies past pair 63 are
   divided by 1e30 through the YaRN ramp `rope` already carries, a step at 63.5..64.
 - **V on a full layer is the un-normed, un-rotated k projection**, RMS-normed with a unit gain, so
   the value norm reads `k` before the key norm writes it.
 - **The router does not read the feed-forward's input.** It reads the residual stream through a
   gainless norm times its own `scale` vector times hidden^-0.5, while the experts read
-  pre_feedforward_layernorm_2's output. `per_expert_scale` multiplies the weight AFTER the
+  pre_feedforward_layernorm_2's output. `per_expert_scale` multiplies the weight after the
   renormalised top-k.
 - **The arms' two post-norms are per arm**, so under tensor parallel each arm's partial sum is
-  reduced before its norm. The partials share one [2T, hidden] buffer, dense rows first -- each
-  slice's own run of it when a prefill chunk is cut in two -- so one all-reduce carries both.
+  reduced before its norm. The partials share one [2T, hidden] buffer, dense rows first (each
+  slice's own run of it when a prefill chunk is cut in two), so one all-reduce carries both.
 - **The embedding scale is sqrt(hidden) rounded to bf16**: 53.0, not 53.066. The drafter reads the
   same scaled embedding.
 - **The sliding layers' KV group is `RAD_KV_FULL`**, with the window on the attention op. A
-  `RAD_KV_WINDOW` group is not prefix-cached, so a hit on it reuses nothing and re-prefills; as
-  FULL the hit is kept. The planner gives every paged group the same block count, so the recycling
-  a window group would buy is worth nothing here.
+  `RAD_KV_WINDOW` group is not prefix-cached, so a hit on it reuses nothing and re-prefills. The
+  planner gives every paged group the same block count, so the recycling a window group would buy
+  is worth nothing here.
 - **The drafter's sliding layers are causal and its full layer is not**, and its logits' softcap
   is ignored on purpose: a draft is an argmax and the cap is strictly increasing.
 
 **Tensor parallel.** Heads split by rank, o and down by column with an all-reduce, the vocabulary
 by row. The full layers' two KV heads are replicated past two ranks. Routed experts are
-expert-parallel, 128 / world whole experts a rank, because a 704-wide expert has no block-aligned
+expert-parallel, 128 / world whole experts per rank, because a 704-wide expert has no block-aligned
 width split; the router is replicated, so every rank agrees on the routing without a collective.
 The drafter's head is vocab-sharded with the trunk's: each rank's top-2 are all-gathered and
-`pair_argmax` picks the winner (two a rank, because a row-interleaved `all_gather` moves 16-byte
+`pair_argmax` picks the winner (two per rank, because a row-interleaved `all_gather` moves 16-byte
 words and one pair is 8 bytes).
 
-**The prefill overlap.** At more than one rank, a prefill chunk of two routed passes or more (4096
-tokens, at the 2048-token pass) runs as two slices, and the trunk's all-reduces ride the runtime's
-second lane beside the other slice's compute: slice A's attention reduction runs under slice B's
-output projection, slice B's under slice A's two arms, and so on through the layer. Attention runs
-whole, since it reads every row's keys. The cut is a whole number of routed passes and both slices
-are above every row band the sliced kernels have, so the step issues the same kernels over the
-same rows and its output is the whole step's, bit for bit. On 4x R9700 the reductions were 47% of
-a 20K-token prefill under `--profile-ops`; a model of the measured times puts the overlap at up to
-a quarter off an unprofiled prefill. The per-op profile syncs every op, so it cannot show it --
-time a prefill without `--profile-ops`. A step that runs whole -- every decode and verify step --
-takes the second lane for the dense arm instead, beside the routed arm, which needs nothing of it
-until the feed-forward join: at decode the dense arm's GEMMs are a few rows, latency-bound and far
-from the bandwidth the experts take, and its reductions stay on lane 0. On two R9700s the sliced
-prefill gives the whole chunk's text and logprobs exactly, at 2048- and 8192-token chunks; the
-startup notes say which form each step takes.
+**Prefill overlap.** At more than one rank on the exact wire, with every join fused, a prefill chunk
+of two routed passes or more (4096 tokens at the 2048-token pass) runs as two slices, and the
+trunk's all-reduces ride the runtime's second lane beside the other slice's compute (slice A's
+attention reduction under slice B's output projection, and so on). Attention runs whole, since it
+reads every row's keys. The slices issue the same kernels over the same rows, so the output equals
+the whole step's bit for bit. On 4x R9700 the reductions are 47% of a 20K-token prefill under
+`--profile-ops`, and the overlap is modelled at up to a quarter off; `--profile-ops` syncs every op
+and cannot show it, so time a prefill without it. A step that runs whole (every decode and verify
+step) puts the dense arm on the second lane instead, beside the routed arm, with its reductions on
+lane 0. The startup notes say which form each step takes.
 
 **The draft head in fp8.** The drafter's head is the widest read on the draft path: the target's
-bf16 table, 352 MiB a rank at tp 4, every draft pass. A container converted with the line
+bf16 table, 352 MiB per rank at tp 4, every draft pass. A container converted with the line
 `dflash.draft_head.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16` (the three `-df` recipes
-carry it) stores a block-fp8 copy of the table under that name, and the head reads the copy at
-fp8a8 instead -- half the bytes, for 176 MiB a rank more. Drafts are verified, so the coarser
-logits can change what is proposed and never what is accepted; `draft_n_accepted` says whether
-they propose worse. A container without the copy reads the bf16 table as before, and the startup
-note names which head is in use.
+carry it) stores a block-fp8 copy under that name, and the head reads it at fp8a8 instead: half
+the bytes, for 176 MiB per rank more. Drafts are verified, so the coarser logits can change what is
+proposed, never what is accepted; `draft_n_accepted` shows whether they propose worse. Without the
+copy the head reads the bf16 table, and the startup note names which head is in use.
 
 **FP8 experts.** The experts are ~90% of the weight bytes, so each projection is served as the
-container holds it, per layer: bf16 by `moe_gemm`, block fp8 by `moe_gemm_q`. gate_up `[1408, 2816]`
-is whole 64-row tiles and 128-blocks. down `[2816, 704]` is not — the fp8 grouped GEMM reads K in
-whole 128-column blocks — so it stays bf16 unless the checkpoint's experts were padded to 768 before
-conversion (zero rows of gate and up, zero columns of down: exact). The fp8 tables are split by
-expert parity, so a rank holds an even number of experts.
+container holds it, per layer: bf16 by `moe_gemm`, block fp8 by `moe_gemm_q`. gate_up
+`[1408, 2816]` is whole 64-row tiles and 128-blocks. down `[2816, 704]` is not (the fp8 grouped
+GEMM reads K in whole 128-column blocks), so it stays bf16 unless the checkpoint's experts were
+padded to 768 before conversion (zero rows of gate and up, zero columns of down: exact;
+`gemma4-26b-a4b-df-pad768.recipe`). The fp8 tables are split by expert parity, so a rank holds an
+even number of experts.
 
-**Kernels.** libr4d serves all of the trunk's attention on its windowed kernels -- the sliding
-layers (h256, gqa 2) and the full layers at gqa 8, 4 and 2 (one or two, four, eight ranks) --
-plus `pair_argmax` and the fusions: the two sandwich-norm joins (`norm_add_norm`,
-`join_add_scale`), `norm_add_norm_route` -- on a layer whose gate_up is block fp8, the attention
-join writing the router's input and the experts' fp8 codes from the norm it already takes, in place
-of an `rmsnorm` and an `rmsnorm_quant_fp8` -- `expert_scale`, and `attn_paged_qrow`, the sliding
-layers' attention reading q where the fused qkv projection left it. The plugin declares each one's
-unfused form where nothing serves it -- the rmsnorm / add chain, `embed_lookup` + `mul`, a `cast`
-lifting q for `attn_paged` -- and the startup notes say which were taken. libref and libavx do not
-declare these ops, so the plugin asks whether one is declared before it asks for it
-(`rad_op_declared`), and a deployment without libr4d's device rows -- a CPU-only build, the host
-backend -- runs the chains. On a card the fused joins and libr4d's chain differ by the order of
-the chain's reductions, not bit for bit: the joins round as the host chain does (tests/r4d_emu).
-The drafter's residual add, norm and fp8 quantiser of x are one libr4d `rmsnorm_quant_fp8` launch
-an input (ten a draft pass), and the `add` / `rmsnorm` / `quant_act_fp8` chain where nothing serves
-it. The sliding layers' attention stays on the windowed kernel because only it reads q in place:
-plain `attn_paged` at h256/gqa2 -- the dense 31B's sliding layers -- takes libr4d's h256/gqa2
-leg, which rad-kbench times at 0.26-0.71 of the windowed kernel at decode and 0.43-0.67 at
-prefill. A drafter head sharded over more than one rank needs `pair_argmax` on the card.
+**Kernels.** libr4d serves all of the trunk's attention on its windowed kernels (the sliding layers
+at h256, gqa 2, and the full layers at gqa 8, 4 and 2 for one or two, four and eight ranks), plus
+`pair_argmax` and the fusions:
 
-**A drafter that is not working still writes fluent text.** Every draft is verified, so a broken
-drafter costs speed and nothing else: judge it by `draft_n_accepted` (about a third of `draft_n` on
-prose, at about two tokens a step), not by the reply. The trap that showed it: the buffer planner
-takes liveness from DECLARATION order, so the tap copy into `dflash_src` is declared at the end of
-the layer it taps, where it is issued. Declared once after the trunk, it let the planner share
-`dflash_src` with `moe_edn`, which every MoE layer writes, whenever the sizes allowed it
-(`--max-num-seqs 16` did): 2% acceptance, slower than no speculation, and nothing in the text to
-say so. arch_test holds the two live ranges to overlap.
+- the two sandwich-norm joins (`norm_add_norm`, `join_add_scale`);
+- `norm_add_norm_route`: on a layer whose gate_up is block fp8, the attention join also writes the
+  router's input and the experts' fp8 codes from the norm it already takes, in place of an
+  `rmsnorm` and an `rmsnorm_quant_fp8`;
+- `expert_scale`;
+- `attn_paged_qrow`, the sliding layers' attention reading q where the fused qkv projection left it.
 
-**Not declared.** The vision tower (`arch/embgemma2` declares Gemma 4's, for an encoder): a container
-that carries one is served with `--mm-max-patches 0`. An fp8 attention or dense arm — under a tenth
-of the weight bytes, and the dense arm's 2112 is not whole 128-blocks either.
+Where nothing serves a fusion the plugin declares its unfused form (the rmsnorm / add chain,
+`embed_lookup` + `mul`, a `cast` lifting q for `attn_paged`), and the startup notes say which were
+taken. libref and libavx do not declare these ops, so the plugin checks `rad_op_declared` first,
+and a deployment without libr4d's device rows (a CPU-only build, the host backend) runs the chains.
+On a card the fused joins and libr4d's chain differ in reduction order, not bit for bit; the joins
+round as the host chain does (`tests/r4d_emu`). The drafter's residual add, norm and fp8 quantiser
+of x are one `rmsnorm_quant_fp8` launch per input (ten per draft pass), or the `add` / `rmsnorm` /
+`quant_act_fp8` chain. The sliding layers' attention stays on the windowed kernel because only it
+reads q in place; plain `attn_paged` at h256/gqa2 (the dense 31B's sliding layers) takes libr4d's
+h256/gqa2 leg, which rad-kbench times at 0.26-0.71 of the windowed kernel at decode and 0.43-0.67
+at prefill. A drafter head sharded over more than one rank needs `pair_argmax` on the card.
+
+**A broken drafter still writes fluent text**, since every draft is verified; judge it by
+`draft_n_accepted` (about a third of `draft_n` on prose, at about two tokens per step), not by the
+reply. The buffer planner takes liveness from declaration order, so the tap copy into `dflash_src`
+is declared at the end of the layer it taps, where it is issued. Declared after the trunk, it would
+let the planner share `dflash_src` with `moe_edn`, which every MoE layer writes, and acceptance
+would collapse silently. arch_test holds the two live ranges to overlap.
+
+**Not declared.** The vision tower (`arch/gemma4_bf16` and `arch/embgemma2` declare Gemma 4's): a
+container that carries one is served with `--mm-max-patches 0`. An fp8 attention or dense arm:
+under a tenth of the weight bytes, and the dense arm's 2112 is not whole 128-blocks either.
 
 ---
 
-# `qwenimage21` — Qwen-Image 2.1 and 2.1-Turbo, an image generator
+# `qwenimage21`: Qwen-Image 2.1 and 2.1-Turbo, an image generator
 
-`arch/qwenimage21` declares a GENERATOR (`rad_declare_generator`), which makes the program a
-three-pass one the engine drives through `core/gen`: COND once a request (the text encoder over the
-prompt and its pictures, then the DiT over that prefix into the KV cache), DENOISE once a step (the
-image's latent rows against the cached prefix), DECODE once an image (the VAE). It is served on
-`/v1/images/generations` and `/v1/images/edits` ([GUIDE §5.6](GUIDE.md)); fp8 on one or two cards,
-bf16 on two. The checkpoint is the diffusers pipeline directory, read as one.
+`arch/qwenimage21` declares a generator (`rad_declare_generator`), which makes the program a
+three-pass one the engine drives through `core/gen`: COND once per request (the text encoder over
+the prompt and its pictures, then the DiT over that prefix into the KV cache), DENOISE once per step
+(the image's latent rows against the cached prefix), DECODE once per image (the VAE). It is served
+on `/v1/images/generations` and `/v1/images/edits` ([GUIDE §5.6](GUIDE.md)); fp8 on one or two
+cards, bf16 on two. The checkpoint is the diffusers pipeline directory, read as one.
 
 ```
 text      Qwen3-VL-8B-Instruct as released: 36 layers of 4096 (32 x 128, 8 kv heads), interleaved
@@ -607,28 +560,83 @@ schedule  flow-matching Euler, exponential dynamic shift (0.5 at 256 tokens to 0
           shift_terminal 0.02, 40 steps; Turbo: the 8 sigmas model_index.json lists, no guidance
 ```
 
-The traps:
+Traps:
 
 - **The noise is radiance's, not torch's.** A seed is a Philox stream (`abi/rad_philox.h`), element
   (k, c) of image row k drawn at k * 64 + c, identical on every card count. Parity against diffusers
-  means handing diffusers the same latents; a NumPy port of the stream does.
+  means handing diffusers the same latents; a NumPy port of the stream does that.
 - **The conditioning is modulated at t = 0**, not at the step's timestep: the prefix is written once,
-  and a step that re-modulated it would differ from the reference at every step after the first.
-- **The text encoder's output skips the final norm.** Taking the normed output scales every row by
-  the norm's gain and leaves a picture that is plausible and wrong.
+  and re-modulating it would differ from the reference at every step after the first.
+- **The text encoder's output skips the final norm.** The normed output scales every row by the
+  norm's gain and gives a plausible, wrong picture.
 - **A reference picture is read twice**: by the VAE as RGBA in [-1, 1], and by the vision tower
   composited on white, both after PIL's premultiplied Lanczos resize to the 1024x1024 area at its
   own aspect, sides rounded to 32. A different resampler changes every token the picture becomes.
 - **The Euler step rounds where diffusers does**: x' = bf16(x + bf16(bf16(sigma_next - sigma) * v)),
-  and guidance bf16(neg + bf16(cfg * bf16(pos - neg))). Unrounded is not more accurate here; it is a
-  different trajectory.
+  and guidance bf16(neg + bf16(cfg * bf16(pos - neg))). Unrounded is a different trajectory, not a
+  more accurate one.
 - **The VAE config's `temperal_downsample` is a boolean array**; a reader that drops booleans makes
   every level look unscaled.
-- **Alpha off the decoder is never exactly 255** (243..255 on an opaque picture). Reading it as
-  transparency makes every picture the model made a transparent one when it is edited again; the
-  server's cutoff is alpha 128, the mask's.
+- **Alpha off the decoder is never exactly 255** (243..255 on an opaque picture). Read as
+  transparency, it makes every picture the model made transparent when edited again; the server's
+  cutoff is alpha 128, the mask's.
 
-Measured against diffusers' own pipeline in bf16, from the same latents (1024x1024, 20 steps, PSNR):
-bf16 TP2 33.9 dB for a prompt and 42.2 for an edit, where diffusers differs from itself by 32.6 to
-34.4 dB across its own attention kernels; fp8 28.7 to 29.3 and 37.6 to 38.4; Turbo fp8 33.4 and
-38.9 at its 8 steps.
+Against diffusers' own pipeline in bf16, from the same latents (1024x1024, 20 steps, PSNR): bf16
+TP2 33.9 dB for a prompt and 42.2 for an edit, where diffusers differs from itself by 32.6 to 34.4
+dB across its own attention kernels; fp8 28.7 to 29.3 and 37.6 to 38.4; Turbo fp8 33.4 and 38.9 at
+its 8 steps.
+
+---
+
+# `qwen3asr`: speech to text
+
+`model_type: qwen3_asr` (`Qwen3ASRForConditionalGeneration`), served from the checkpoint as it
+ships: Qwen3-ASR 1.7B is a Whisper-style audio encoder, a two-layer projector and a dense Qwen3-1.7B
+decoder, all bf16. The reference is transformers' `modeling_qwen3_asr` with its
+`Qwen3ASRFeatureExtractor`, which core/mm reproduces (`AudioFamily::Qwen3ASR`).
+
+```
+features   Whisper log-mel, 128 bins: n_fft 400, hop 160, torch.stft centred with reflected padding,
+           power spectra, the last frame dropped (n samples -> n / 160 frames), Slaney mel bank and
+           area norm, log10 floored at the clip's maximum less 8, then (x + 4) / 4; a clip under
+           8000 samples zero-padded to 8000 first
+encoder    each second (100 frames) convolved on its own: 3 x Conv2d 3x3 / stride 2 / pad 1, 480
+           channels, exact gelu, over [mel, time] -> 16 mel x 13 rows a second; 7680 -> 1024 linear
+           (no bias); sinusoidal positions 0..12 added to every second's rows; 24 pre-LayerNorm
+           layers, d_model 1024, 16 heads of 64, biased q/k/v/o and FFN 4096 with exact gelu,
+           bidirectional in blocks of 104 rows (8 s) from the clip's start; LayerNorm
+projector  1024 -> 1024, gelu, 1024 -> 2048
+decoder    28 layers, hidden 2048, 16 heads over 8 KV heads of 128 (GQA 2), per-head q/k RMS norms,
+           NeoX rope over the whole head at theta 1e6, SwiGLU 6144, RMS eps 1e-6, vocab 151936,
+           lm_head tied to the embedding
+prompt     <|im_start|>system\n{context}<|im_end|>\n<|im_start|>user\n<|audio_start|> pads
+           <|audio_end|><|im_end|>\n<|im_start|>assistant\n[language English]
+```
+
+Traps (each loads and transcribes plausibly when wrong):
+
+- **A second's convolution must not see the next second.** The reference pads every second to 100
+  frames and convolves the batch; one convolution over the clip with no seam reads one second's
+  frames into the next's. core/mm stages a whole second as 104 frames whose last four the encoder
+  reads as zero (`conv2d`'s `valid`, at strides 1, 2 and 4), and the last, shorter second as 8 x
+  the rows the reference keeps of it, so the rows the tower writes are the rows the reference
+  keeps and nothing is compacted. The zero frames inside the last second's window are real input
+  (the reference's padding) and are read: its last kept row depends on them.
+- **The kernels are [mel, time]**, so PyTorch's weight is `[cout, cin, mel, time]` with time last,
+  where `conv2d` convolves (time, width). `t_last` reads it as stored; reading it the other way is a
+  transposed kernel, which still produces text.
+- **The 7680 -> 1024 linear takes channel-major features** (`c * 16 + f`) where the convolution
+  writes frequency-major ones. Declared as a 1 x 16 convolution over frequency, its weight is
+  PyTorch's `[1024, 480, 1, 16]`; declared as a GEMM, it would need a permutation the name map has
+  no form for.
+- **Positions restart every second** (`seg_sinusoid`, period 13) and **attention runs in blocks of
+  104 rows**, the last one short (`attn_dense`'s `block`). Positions counted over the whole clip,
+  or attention over all of it, is a different model that still writes text.
+- **The decoder's positions are the tokens' indices**: plain Qwen3, no M-RoPE; the audio
+  placeholders count up like text.
+
+A pass carries 30 s (3120 staged frames); `/v1/audio/transcriptions` cuts longer recordings into
+clips at their pauses (docs/GUIDE.md §5.14). Against transformers on LibriSpeech test-clean and
+test-other clips, the encoder's rows are within 1.1-1.3% relative L2 of the bf16 reference's; on
+the one clip where they differed by 5%, the reference itself was 5.3% from a float32 run of the
+same model and this engine 0.8%. The transcripts match word for word.
diff --git a/docs/DOCKER.md b/docs/DOCKER.md
index 35e08ae4..14fedaf3 100644
--- a/docs/DOCKER.md
+++ b/docs/DOCKER.md
@@ -1,9 +1,10 @@
 # Radiance in a container
 
 The repository builds into one Docker image that holds the engine, its plugins, its tools and the
-recipes, and nothing else: it is assembled from scratch out of the install tree and exactly the
-shared libraries that tree loads. The host needs Docker, an AMD GPU and an `amdgpu` kernel driver
-that supports ROCm 10.1. It does not need ROCm itself, a compiler, or ffmpeg.
+recipes. It is assembled from scratch out of the install tree, exactly the shared libraries that
+tree loads, a static busybox, and `curl`, `jq` and a CA bundle for `hfget.sh`. The host needs
+Docker, an AMD GPU and an `amdgpu` kernel driver that supports ROCm 10.1. It does not need ROCm, a
+compiler or FFmpeg.
 
 The image is published as [`stilldeadcode/radiance`](https://hub.docker.com/r/stilldeadcode/radiance),
 with its kernels built for `gfx1201`: `docker pull stilldeadcode/radiance`. Build it yourself for
@@ -11,10 +12,10 @@ other cards or another commit. The examples below use `radiance`, the tag a loca
 the published image, write `stilldeadcode/radiance` instead.
 
 Besides radiance (Apache-2.0, `/opt/radiance/share/doc/radiance/`), the image holds glibc,
-libstdc++, the ROCm runtime, FFmpeg, busybox and a few other libraries, each under its own license,
-GPL and LGPL among them. `/usr/share/doc/THIRD-PARTY` in the image lists every one with its exact
-version, its license files and where its source is; `docker/licenses.sh` writes it during the build
-and stops the build if a file in the image cannot be traced to a package.
+libstdc++, the ROCm runtime, FFmpeg, busybox, curl, jq and a few other libraries, each under its own
+license, GPL and LGPL among them. `/usr/share/doc/THIRD-PARTY` in the image lists each one with its
+version, its license files and its source. `docker/licenses.sh` writes it during the build and fails
+the build if a file in the image cannot be traced to a package.
 
 ## Build the image
 
@@ -27,37 +28,37 @@ docker/build.sh -r             # any other commit
 docker/build.sh --target build         # stop at a stage, tagged radiance-
 ```
 
-The context the script sends is `git archive` of the commit, so the image holds exactly what is
-committed: no build directory, no uncommitted edit, no model file. It builds with BuildKit
-(`docker buildx`), which runs independent stages side by side and caches each one; with `-s` only
-the remote machine needs buildx.
+The build context is `git archive` of the commit, so the image holds only what is committed: no
+build directory, no uncommitted edit, no model file. It builds with BuildKit (`docker buildx`), which
+runs independent stages in parallel and caches each one; with `-s` only the remote machine needs
+buildx.
 
-The `Dockerfile` has these stages:
+The `Dockerfile` stages:
 
 | stage | what it does |
 |---|---|
-| `ffmpeg` | FFmpeg 8.1 with only the demuxers `core/mm/media.cpp` admits and the decoders their streams carry (still images, H.264, HEVC, VP8, VP9, AV1 through dav1d, MPEG-1/2/4, Theora, FLV/H.263). The distribution's build brings about 200 packages of encoders, filters and display libraries the engine never calls |
-| `llvm` | ROCm's `libLLVM` rebuilt from ROCm's own llvm-project, at the exact commit the image's `clang --version` names, with `docker/llvm-vopd-pairing.patch` applied and configured as ROCm ships it. ROCm 10.1's clang does not compile the same source to the same code twice (its VOPD pairing follows heap addresses); the patch makes it repeatable. The library is the only file of the compiler that changes |
-| `build` | `rocm/dev-ubuntu-24.04:10.1.0-full` plus cmake, ninja and g++-14. Every device source is compiled by ROCm's clang from `/opt/rocm-repeatable`, a shadow of the ROCm tree whose `libLLVM` is the `llvm` stage's (`-DRAD_HIP_VOPD_REPEATABLE=ON`, `--rocm-path=/opt/rocm`); the HIP runtime and comgr in the image stay ROCm's own. Configures with the kernels compiled for `GPU_TARGETS`, builds, and installs to `/opt/radiance`. Device code is not stored compressed: the engine's AQL backend reads the fat binaries itself and refuses a compressed bundle |
-| `test` | `docker/llvm-check.sh`, then `ctest -LE gpu`: every suite that runs without a card. The check recompiles one kernel file four ways -- with pairing off the image's compiler must emit ROCm's device code byte for byte, with pairing on three compiles must agree. The image is only produced if both pass |
-| `rootfs` | The install tree, stripped, plus every shared library its binaries and plugins load (resolved by `ldd`, glibc and the ROCm runtime included) in one directory the loader searches by default, and a static busybox. ROCm's `libdrm_amdgpu` carries the card name table compiled in, so no `amdgpu.ids` is needed. Every ELF file is then resolved from inside a chroot of the tree, so the build fails on a library the image lacks |
+| `ffmpeg` | FFmpeg 8.1 with only the demuxers `core/mm/media.cpp` admits, the decoders their streams carry (still images, H.264, HEVC, VP8, VP9, AV1 through dav1d, MPEG-1/2/4, Theora, FLV/H.263, and audio) and the three encoders the images API writes (PNG, JPEG, WebP). The distribution's build brings about 200 packages the engine never uses |
+| `llvm` | ROCm's `libLLVM` rebuilt from ROCm's llvm-project at the commit the image's `clang --version` names, configured as ROCm ships it, with `docker/llvm-vopd-pairing.patch` applied. ROCm 10.1's clang does not compile the same source to the same code twice (its VOPD pairing follows heap addresses); the patch makes it repeatable. This library is the only compiler file that changes |
+| `build` | `rocm/dev-ubuntu-24.04:10.1.0-full` plus cmake, ninja and g++-14. Device code is compiled by ROCm's clang from `/opt/rocm-repeatable`, a shadow of the ROCm tree whose `libLLVM` is the `llvm` stage's (`-DRAD_HIP_VOPD_REPEATABLE=ON`, `--rocm-path=/opt/rocm`); the HIP runtime and comgr in the image are ROCm's own. Configures with kernels for `GPU_TARGETS`, builds, and installs to `/opt/radiance` with the recipes. Device code is not stored compressed: the engine's AQL backend reads the fat binaries itself and refuses a compressed bundle |
+| `test` | `docker/llvm-check.sh`, then `ctest -LE 'gpu\|oot'`: every suite that runs without a card. The check recompiles one kernel file four ways: with pairing off, the image's compiler must emit ROCm's device code byte for byte; with pairing on, two compiles must match the build's own object. The image is produced only if both pass |
+| `rootfs` | The stripped install tree, every shared library its binaries and plugins load (resolved by `ldd`, glibc and the ROCm runtime included) in one directory the loader searches by default, a static busybox, and `curl`, `jq` and the CA bundle. ROCm's `libdrm_amdgpu` has the card name table compiled in, so no `amdgpu.ids` is needed. Every ELF file is then resolved from inside a chroot of the tree, so the build fails on a library the image lacks |
 | `runtime` | `FROM scratch` and the rootfs. This is the image that ships |
 
-The largest files are the LLVM and Clang libraries comgr loads (about 130 MB and 90 MB), which the
-HIP runtime cannot initialise a device without. There is no distribution in the shipped image: no
-package manager and no shell beyond busybox (`docker exec -it  sh`). JPEG XL input is refused
-by name, since its decoder needs libjxl.
+The largest files are the LLVM and Clang libraries comgr loads (about 130 MB and 90 MB), without
+which the HIP runtime cannot initialise a device. The shipped image has no distribution: no package
+manager and no shell beyond busybox (`docker exec -it  sh`). JPEG XL input is refused by name,
+since its decoder needs libjxl.
 
-A build container has no card to enumerate, so the GPU architecture must be named. A bare-metal
-`./build.sh` detects it instead. `libr4d` builds for gfx12 targets only; any other target in the
-list just gets no RDNA4 kernels.
+A build container has no card to enumerate, so the GPU architecture must be named; a bare-metal
+`./build.sh` detects it. `libr4d` builds for gfx12 targets only; any other target in the list gets
+no RDNA4 kernels.
 
-The ROCm version in the image has to be one the host's kernel driver supports. It is a build
-argument (`ROCM_VERSION`, default `10.1.0-full`; from ROCm 10 on, the development image is published
-only with the `-full` suffix).
+The ROCm version in the image must be one the host's kernel driver supports. It is a build argument
+(`ROCM_VERSION`, default `10.1.0-full`; from ROCm 10 on, the development image is published only
+with the `-full` suffix).
 
-The GPU suites (`mem_test`, `r4d_selftest`, `kbench`) need the card to themselves. They run from
-the `build` stage:
+The GPU suites (`mem_test`, `r4d_selftest`, `kbench`, `kbench_moe`) need the card to themselves.
+They run from the `build` stage:
 
 ```sh
 docker/build.sh --target build
@@ -67,14 +68,14 @@ docker run --rm --device /dev/kfd --device /dev/dri --security-opt seccomp=uncon
 
 ## Run it
 
-The entrypoint is `radiance`. Every other tool (`rad-convert`, `rad-info`, `rad-kbench`,
-`rad-tune`, `rad-schemas`, `rad-tokcheck`) is on `PATH`, and the recipes are in
+The entrypoint is `radiance`. The other installed tools (`rad-convert`, `rad-info`, `rad-kbench`,
+`rad-tune`, `rad-schemas`, `rad-tokcheck`) are on `PATH`, and the recipes are in
 `/opt/radiance/share/radiance/recipes/`.
 
 ```sh
 docker run --rm -v /srv/models/rad:/models:ro --entrypoint rad-info radiance /models/m.rad
 
-docker run -d --name radiance --network host --init \
+docker run -d --name radiance --network host --init --ulimit memlock=-1 \
     --device /dev/kfd --device /dev/dri --security-opt seccomp=unconfined \
     --group-add "$(getent group render | cut -d: -f3)" \
     --group-add "$(getent group video | cut -d: -f3)" \
@@ -82,28 +83,28 @@ docker run -d --name radiance --network host --init \
     radiance --model /models/m.rad --tp 2 --host :: --port 8000
 ```
 
-Every one of these options is needed:
+The options:
 
-- **`--device /dev/kfd --device /dev/dri`**, plus the `render` and `video` groups, give the
-  container the GPUs.
-- **`--security-opt seccomp=unconfined`**: Docker's default seccomp profile refuses io_uring.
-  Qwen3.8-Flash-Next's n-gram embedding table is read from the container through io_uring, so
-  without this the model cannot serve. The profile also refuses the NUMA binding calls the ROCm
-  runtime makes for host memory.
-- **`--init`**: the engine is not PID 1. It finishes its step and releases the cards on SIGTERM.
-- **`--ulimit memlock=-1`**: where no device kernel gathers the n-gram table (a run on the host
-  backend), `--ngram-placement ram` locks a copy of it in RAM -- 47.7 GiB for
-  Qwen3.8-Flash-Next, far past Docker's default memlock limit -- and without the limit raised
-  `auto` reads it from the container and `ram` refuses the start. On the cards the copy is pinned
-  memory the cards read, which the limit does not count. `deploy/compose/common.yaml` sets it.
-- **`--network host`**: the server binds the host's addresses directly, IPv4 and IPv6, with no
-  NAT in front of it.
+- `--device /dev/kfd --device /dev/dri`, with the `render` and `video` groups, give the container
+  the GPUs.
+- `--security-opt seccomp=unconfined`: Docker's default seccomp profile refuses io_uring and the
+  NUMA binding calls the ROCm runtime makes for host memory. Qwen3.8-Flash-Next's n-gram embedding
+  table is read from the container through io_uring, so without this the model cannot serve.
+- `--init`: an init process runs as PID 1 and forwards SIGTERM to the engine, which finishes its
+  step and releases the cards.
+- `--ulimit memlock=-1`: where no device kernel gathers the n-gram table (a run on the host
+  backend), `--ngram-placement ram` locks a copy of it in RAM (47.7 GiB for Qwen3.8-Flash-Next, far
+  past Docker's default memlock limit). Without the limit raised, `auto` reads the table from the
+  container and `ram` refuses the start. On the cards the copy is pinned memory the cards read,
+  which the limit does not count. `deploy/compose/common.yaml` sets it.
+- `--network host`: the server binds the host's addresses directly, IPv4 and IPv6, with no NAT in
+  front of it.
 
-The image sets `GPU_MAX_ALLOC_PERCENT=100` and `GPU_MAX_HEAP_SIZE=100`. The HIP runtime's defaults
-cap one allocation, and the heap, below what the placement plan hands out.
+The image sets `GPU_MAX_ALLOC_PERCENT=100` and `GPU_MAX_HEAP_SIZE=100`, because the HIP runtime's
+defaults cap one allocation, and the heap, below what the placement plan hands out.
 
-**A plugin of your own** — a kernel library for another card, an architecture, a quantiser — is
-mounted and put first on the search path; nothing in the image changes:
+A plugin of your own (a kernel library for another card, an architecture, a quantiser) is mounted
+and put first on the search path; nothing in the image changes:
 
 ```sh
 docker run ... -v /srv/radiance-plugins:/plugins:ro \
@@ -122,30 +123,31 @@ the cards the engine runs on.
 
 | file | container | what it is |
 |---|---|---|
-| `flashnext.yaml` | `qwen3.8-next-flash-fp8-iq4r-moe.rad` | Qwen3.8-Flash-Next, 4-bit codebook experts and an int8 trunk; MTP depth 3; idle sessions kept in host memory and on disk |
+| `flashnext.yaml` | `qwen3.8-next-flash-fp8-iq4r-moe.rad` | Qwen3.8-Flash-Next, 4-bit codebook experts and an int8 trunk; MTP depth 3; finished conversations kept in host memory (`--prefix-cache-mib`) |
 | `flashnext-tp1.yaml` | `qwen3.8-next-flash-fp8-iq4r-moe.rad` | The same on one card: a 42 GiB pinned host pool for the experts that do not fit, 4096-token prefill steps, 4 sequences |
 | `flashnext-bf16.yaml` | `qwen3.8-flash-next-bf16.rad` | Qwen3.8-Flash-Next in bf16, streamed from the disk tier. A reference, not a production server |
 | `qwen3.6-35b-a3b.yaml` | `qwen3.6-35b-a3b-fp8.rad` | Qwen3.6-35B-A3B, FP8 |
 | `qwen3.8-27b-fp8.yaml` | `qwen3.8-27b-fp8.rad` | Qwen3.8-27B FP8 with its DFlash2 drafter and vision tower |
 | `qwen3.8-27b-mxfp4.yaml` | `qwen3.8-27b-mxfp4.rad` | Qwen3.8-27B with AMD's Quark AWQ-MXFP4 trunk, its DFlash2 drafter and vision tower |
-| `qwen3.8-27b-paro.yaml` | `qwen3.8-27b-paro-int4.rad` | Qwen3.8-27B ParoQuant int4 (learned rotations) with its DFlash2 drafter and vision tower; the int5 and MXFP4 containers serve from it too |
+| `qwen3.8-27b-paro.yaml` | `qwen3.8-27b-paro-int4.rad` | Qwen3.8-27B ParoQuant int4 (learned rotations) with its DFlash2 drafter and vision tower, on one card; the int5 and MXFP4 containers serve from it too |
 | `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 |
 | `minicpm5-2b.yaml` | `minicpm5-2b-fp8.rad` | MiniCPM5-2B FP8 with its DSpark drafter |
 | `minicpm5-2b-bf16.yaml` | `minicpm5-2b-bf16.rad` | MiniCPM5-2B in bf16 with its DSpark drafter |
-| `embeddinggemma2.yaml` | `embeddinggemma2-bf16.rad` | EmbeddingGemma 2 in bf16: text, image, video and audio embeddings on one card |
+| `embeddinggemma2.yaml` | `embeddinggemma2-bf16.rad` | EmbeddingGemma 2 in bf16: text, image, video and audio embeddings on one card (`RADIANCE_GPU`) |
 | `qwen-image-2.1.yaml` | `qwen-image-2.1-fp8.rad` | Qwen-Image 2.1 as block fp8 on two cards: OpenAI's images API, generation and edits |
 | `qwen-image-2.1-turbo.yaml` | `qwen-image-2.1-turbo-fp8.rad` | Qwen-Image 2.1 Turbo, the same in 8 steps |
+| `qwen3-asr-1.7b.yaml` | `Qwen3-ASR-1.7B-hf/` (the checkpoint) | Qwen3-ASR 1.7B: `/v1/audio/transcriptions` and live `/v1/realtime`, on one card (`RADIANCE_GPU`) |
 
 The container names are the files the README's model table downloads or converts.
 
 Copy the directory to the serving host and fill in `.env` from `.env.example`. It sets the image,
-the models directory (mounted read-only at `/models`), the API key, the port, and the user and GPU
-groups the server runs as. The models directory has to be on a local filesystem that does direct I/O, such as ext4,
-XFS or btrfs: Qwen3.8-Flash-Next reads its n-gram table from the container that way. On btrfs with
-compression on, the extents it stored compressed are read through the page cache instead, which
-works but loses what the direct reads are for; a container copied into a directory set `chattr +C`
-is stored uncompressed. Then:
+the models directory (mounted read-only at `/models`), the API key, the port, the user and GPU
+groups the server runs as, and the card a one-card model uses. The models directory must be on a
+local filesystem that does direct I/O, such as ext4, XFS or btrfs: Qwen3.8-Flash-Next reads its
+n-gram table from the container that way. On btrfs with compression on, extents stored compressed
+are read through the page cache instead, which works but loses the benefit of direct reads; a
+container copied into a directory set `chattr +C` is stored uncompressed. Then:
 
 ```sh
 docker compose -f flashnext.yaml up -d      # start; restarts with the Docker daemon
@@ -153,6 +155,8 @@ docker compose -f flashnext.yaml logs -f    # follow the log
 docker compose -f flashnext.yaml down       # stop
 ```
 
-Each model takes both cards and the same port, 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`.
+Every model listens on the same port and most take both cards (`flashnext-tp1.yaml`,
+`qwen3.8-27b-paro.yaml` and `embeddinggemma2.yaml` take one), 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`.
diff --git a/docs/GUIDE.md b/docs/GUIDE.md
index 8c3ea6e2..8dfc5357 100644
--- a/docs/GUIDE.md
+++ b/docs/GUIDE.md
@@ -1,75 +1,67 @@
-# Radiance — user guide
+# radiance user guide
 
-Radiance is an inference server: it loads a model and answers OpenAI-compatible HTTP requests.
-This guide takes you from an empty machine to a running server, and then through operating one.
+radiance is an inference server: it loads a model and answers OpenAI-compatible HTTP requests. This
+guide covers building it, getting a model in, serving it and operating the server. The engine, the
+tools and the build are C++, CMake and shell; nothing needs Python.
 
-There is no Python anywhere — not in the engine, not in the tools, not in the build. Everything
-below is C++, CMake and shell.
-
-**Where to go from here**
-
-| If you want | Read |
+| To | Read |
 |---|---|
-| to get something running | this file, in order |
-| every flag of one tool | [TOOLS.md](TOOLS.md) |
-| to write a kernel library for your card | [PLUGIN.md](PLUGIN.md) |
-| to know why it is built this way | `../spec.md` — the design, and it is binding |
+| get something running | this file, in order |
+| see every flag of one tool | [TOOLS.md](TOOLS.md) |
+| write a kernel library for your card | [PLUGIN.md](PLUGIN.md) |
+| know why it is built this way | `../spec.md`, the binding design |
 
 ---
 
-## 0. The whole thing in five commands
+## 0. Quick start
 
 ```sh
 ./build.sh                                          # build and test
 export RADIANCE_HOME=$PWD/build/radiance_home
 
-scripts/hfget.sh Qwen/Qwen3.8-Flash-Next ~/ckpt     # get a checkpoint
-build/bin/rad-convert ~/ckpt -o ~/m.rad \
-    --recipe data/recipes/qwen4exp-w4.recipe        # quantise it into a container
-build/bin/radiance --model ~/m.rad --port 8000      # serve it
+scripts/hfget.sh Qwen/Qwen3.8-Flash-Next /srv/models/ckpt      # get a checkpoint
+build/bin/rad-convert /srv/models/ckpt -o /srv/models/m.rad \
+    --recipe data/recipes/qwen4exp-w4.recipe                   # quantise it into a container
+build/bin/radiance --model /srv/models/m.rad --port 8000       # serve it
 ```
 
-A checkpoint served at its own precision needs no container at all: `radiance --model ~/ckpt`
+A checkpoint served at its own precision needs no container: `radiance --model /srv/models/ckpt`
 reads it as it stands (§3.4).
 
-Then:
-
 ```sh
 curl -s localhost:8000/v1/chat/completions -H 'Content-Type: application/json' \
   -d '{"model":"m","messages":[{"role":"user","content":"hi"}],"max_tokens":50}' \
   | jq -r '.choices[0].message.content'
 ```
 
-and open `http://localhost:8000/` for the dashboard. Everything below is the detail behind those
-five lines.
+The dashboard is at `http://localhost:8000/`.
 
 ---
 
 ## 1. Install
 
-**Or skip this section and run the container image**: `docker/build.sh` builds the engine inside
-the ROCm toolchain image, tests it and produces an image that needs only Docker and the `amdgpu`
-driver on the host. [`DOCKER.md`](DOCKER.md) covers it, along with ready compose files per model.
+To avoid building on the host, use the container image: `docker/build.sh` builds and tests the
+engine in the ROCm toolchain image and produces an image that needs only Docker and the `amdgpu`
+driver. [`DOCKER.md`](DOCKER.md) covers it, with compose files per model.
 
-### 1.1 What you need
+### 1.1 Requirements
 
 | | |
 |---|---|
-| **Required** | Linux, a C++20 compiler, CMake 3.21+, Ninja, pthreads |
-| **Optional** | ROCm with `hipcc`, for AMD device kernels. Without it you get the host backend. Set `ROCM_PATH` if it is not at `/opt/rocm` |
-| **With a card** | Resizable BAR on (Above 4G Decoding and Resizable BAR in the firmware setup): the host writes every dispatch's arguments into VRAM, and startup refuses a card whose memory the CPU cannot reach |
-| **Optional** | OpenMP, used by the host kernel libraries if present |
-| **For the shell harnesses** | `curl` and `jq` |
+| Required | Linux, a C++20 compiler, CMake 3.21+, Ninja, pthreads |
+| Optional | ROCm with `hipcc`, for AMD device kernels; without it you get the host backend. Set `ROCM_PATH` if ROCm is not at `/opt/rocm` |
+| With a card | Resizable BAR on (Above 4G Decoding and Resizable BAR in the firmware setup). The host writes every dispatch's arguments into VRAM, and startup refuses a card whose memory the CPU cannot reach |
+| Optional | OpenMP, used by the host kernel libraries if present |
+| Optional | `clang++` (or ROCm's), for `tests/r4d_emu` when the C++ compiler is g++; CMake 3.25+ for `CMakePresets.json` |
+| Shell harnesses | `curl` and `jq` |
 
-Everything else is vendored in `vendor/` — the HTTP server, the JSON library and the llama.cpp
-lifts. There is nothing to `apt install` beyond a toolchain.
+The HTTP server, the JSON library and the llama.cpp parts are vendored in `vendor/`.
 
-**A machine with no GPU is a supported configuration.** The host backend is a real implementation,
-not a stub: the core, scheduler, planner, tokeniser, server and `libref` all run through it and
-the full test suite passes. It is slow, and it will not serve a production model — but it is a
-complete development and inspection environment. A build with ROCm, or the container image, runs
-the same host backend on a machine where no card is visible: the GPU library's kernels are left out
-there and every op takes its host kernel.
+A machine with no GPU is supported. The host backend is complete: the core, scheduler, planner,
+tokeniser and server run on it, `libavx` (AVX-512 and AVX2 kernels, chosen at run time) serves
+every shipped model, and the full test suite passes. Small models run at interactive speed on a
+desktop CPU; the 27B and larger models run far more slowly than on a card. A ROCm build, or the container image, uses it on a machine where no card is
+visible: the GPU library's kernels are left out and every op takes its host kernel.
 
 ### 1.2 Build
 
@@ -78,48 +70,104 @@ git clone  radiance && cd radiance
 ./build.sh
 ```
 
-That configures, builds and runs the tests. It detects your situation: if `hipcc` is present and a
-card can be enumerated, device kernels are compiled for that card's architecture; otherwise you
-get the host backend.
-
-Options:
+`build.sh` configures, builds and runs the fast tests (§1.3). If `hipcc` is present and a card can
+be enumerated, device kernels are compiled for that card's architecture; otherwise you get the host
+backend.
 
 ```sh
 ./build.sh -c          # wipe the build directory first
 ./build.sh --no-hip    # force the host backend even where hipcc exists
 ./build.sh --debug     # -DCMAKE_BUILD_TYPE=Debug
-./build.sh --asan      # AddressSanitizer
+./build.sh --asan      # AddressSanitizer + UBSan, host backend, in build-asan/
+./build.sh --tsan      # ThreadSanitizer, host backend, in build-tsan/
 ./build.sh -b mybuild  # build into mybuild/ instead of build/
 ```
 
-Or drive CMake yourself:
+Or with CMake directly (`CMakePresets.json` names the same three configurations: `cmake --preset
+default`, `asan` or `tsan`):
 
 ```sh
 cmake -S . -B build -G Ninja
 cmake --build build -j
-ctest --test-dir build --output-on-failure
+ctest --test-dir build -L fast -j8 --output-on-failure
 ```
 
 ### 1.3 Check that it works
 
+The tests are grouped into tiers by label, and `CMakePresets.json` names the usual runs. A preset
+reads `build/`; add `--test-dir mybuild` for another tree (CMake 3.30+), or pass the labels shown.
+Times are wall clock on a 16-core (32-thread) host build with other work running:
+
+| Run | Selects | Time |
+|---|---|---|
+| `ctest --preset fast` (`-L fast -j8`) | the inner loop; what `build.sh` runs | about 10 s |
+| `ctest --preset host` (`-LE 'gpu\|oot' -j8`) | everything that runs without a card | about 1.5 minutes, most of it `r4d_emu_attn_sweep` and, after libref changes, `kbench_ref` |
+| `ctest --preset gpu` (`-L gpu`) | the tests that need a card, one at a time | minutes |
+| `ctest --preset perf` (`-L perf`) | the wall-clock checks, each alone | seconds |
+| `ctest --preset full` | every test | the above plus `oot` |
+| `ctest --preset asan` | the fast tier in `build-asan/` (`./build.sh --asan` first) | about 4 minutes |
+
+| Label | Tests |
+|---|---|
+| `unit` | one binary per `tests/*_test.cpp` except `engine_e2e_test`, always on the host backend (`ROCR_VISIBLE_DEVICES=99`) |
+| `fast` | every test with none of `slow`, `gpu`, `oot`, `perf`, `e2e` and `kbench` |
+| `perf` | `_perf`: a binary's cases named `perf_...`, which assert wall-clock costs; each runs alone |
+| `e2e` | `engine_e2e_test`: the `radiance` binary serving tiny synthetic checkpoints on the host backend |
+| `kbench` | `kbench`, `kbench_moe` and `kbench_ref`, the kernel replays (below) |
+| `slow` | `kbench_ref`, `r4d_selftest` and `r4d_emu_attn_sweep` |
+| `gpu` | `device_test_card`, `mem_test_card`, `place_test_card`, `runtime_test_card`, `device_test_nosvm`, `r4d_selftest`, and `kbench`/`kbench_moe` when libr4d is built; one at a time, and a server must not hold the card |
+| `oot` | `oot_plugins`: every bundled plugin rebuilt out of tree against an install |
+| `r4d_emu` | libr4d kernel sources run on the host by a SIMT emulator; registered where a clang++ is found |
+
+Each binary built on `tests/rad_test.h` takes the same arguments:
+
 ```sh
-ctest --test-dir build --output-on-failure        # everything (a few minutes)
-ctest --test-dir build -LE slow                   # the fast inner loop (~1 s)
-ctest --test-dir build -LE gpu                    # skip anything needing a card
+build/tests/gbnf_test --list                   # its cases
+build/tests/gbnf_test oracle -tool             # the cases containing "oracle" but not "tool"
+build/tests/gbnf_test --shard 1/4              # every fourth case, from the second
+RAD_TEST_FILTER=oracle build/tests/gbnf_test   # patterns from the environment
+RAD_TEST_LEVEL=2 build/tests/gbnf_test         # the exhaustive sizes, where a test has them
 ```
 
-Three of them are worth knowing by name, because they are the ones that actually check kernels:
+A case taking 0.1 s or more prints its time, and a binary ends with its wall and CPU time and its
+three slowest cases. A binary that checked nothing exits 77, which ctest reports as skipped, not
+passed. ctest sets, for each unit test:
 
-- **`kbench` / `kbench_moe`** (label `slow`) replay a recorded fixture — every kernel every loaded
-  library supplies, checked against `libref`'s recorded answers on seeded inputs. **No model file is
-  needed**, which is what makes this runnable on a build machine. It also regression-tests `libref`
-  itself, which a live oracle never can.
-- **`r4d_selftest`** (labels `slow`, `gpu`) checks libr4d's fusion claims by `memcmp` against the
-  unfused kernels it says it replaces.
-- **`ops_doc`** (fast) checks that `docs/OPS.md` still agrees with what the plugins declare. A
-  document that is wrong is worse than one that is missing, because it is read instead of the source.
+- `OMP_WAIT_POLICY=passive` and `OMP_NUM_THREADS=4`: the host kernel libraries' OpenMP teams spin
+  at every barrier by default, which makes a 0.2 s test take a minute on a busy machine.
+- `RAD_TEST_STRICT=1`: a plugin or fixture this build makes that a test cannot find fails it; run by
+  hand, the test skips.
+- `RAD_TEST_TMPDIR=build/tmp`: where `radtest::tmpdir()` is made. It is removed when the binary
+  passes and kept, with its path printed, when it fails.
+- `RAD_TEST_CPU_BUDGET=10`: a binary that spends more CPU seconds than this fails, so a slow case or
+  a spinning thread pool is caught when it lands. `tests/CMakeLists.txt` lists the few binaries
+  allowed more. Sanitised and Debug builds have no budget.
 
-You can also run the kernel check by hand:
+The sanitised tiers are host-only. `./build.sh --asan` builds `build-asan/` with AddressSanitizer
+and UBSan and runs the fast tier there; `--tsan` does the same with ThreadSanitizer in
+`build-tsan/`, where OpenMP runs one thread because libgomp is not instrumented. The `r4d_emu`
+tests are compiled without a sanitiser in both.
+
+The tests that check kernels:
+
+- `kbench` / `kbench_moe` (label `kbench`) replay a recorded fixture: every kernel every loaded
+  library other than `libref` supplies, checked against `libref`'s recorded answers on seeded
+  inputs. They need no model file. `--strict` fails a stale case (one whose operands or schema
+  moved, or that the reference no longer serves or now describes differently), and `--coverage`
+  fails when a kernel row the fixture reached (`data/kbench_rows/`) is no longer reached.
+- `kbench_ref` (labels `kbench`, `slow`) replays `libref` against its own recordings at tolerance
+  zero, so any change to the reference shows before it becomes the next recording's target. Its
+  answers are cached under `$RADIANCE_HOME/cache/kbench` by `libref`'s build, so an unchanged
+  `libref` replays in seconds.
+- `r4d_selftest` (labels `slow`, `gpu`) checks libr4d's fusions by `memcmp` against the unfused
+  kernels they replace.
+- `avx_check` (fast) compares libavx with libref op by op at every ISA level the CPU supports.
+- `r4d_emu_*` (fast, `r4d_emu_attn_sweep` slow) run libr4d's kernels on the host: those with no
+  libref oracle (the windowed attention, the sandwich-norm joins, expert_scale, pair_argmax), and
+  the QSA block selection's four kernels against libref's rule.
+- `ops_doc` (fast) checks that `docs/OPS.md` agrees with what the plugins declare.
+
+The kernel check by hand:
 
 ```sh
 build/bin/rad-kbench --home build/radiance_home --max-cases 1
@@ -133,19 +181,18 @@ cmake --build build -j
 sudo cmake --install build
 ```
 
-What lands where:
-
 ```
 /bin/                      radiance, rad-convert, rad-info,
                                    rad-kbench, rad-tune, rad-schemas, rad-tokcheck
-/include/                  the ABI headers — all a plugin compiles against
+/libexec/radiance/         hfget.sh, the downloader behind --model  (§3.1)
+/include/radiance/         the ABI headers, all a plugin compiles against
 /lib/cmake/radiance/       the package config, for find_package(radiance)
 /share/radiance/           $RADIANCE_HOME: kernels/, architectures/, quantizers/, kernels*.rkb
 ```
 
 ### 1.5 `$RADIANCE_HOME`
 
-This is the directory the engine and every tool scan at startup:
+The directory the engine and every tool scan at startup:
 
 ```
 $RADIANCE_HOME/
@@ -156,26 +203,26 @@ $RADIANCE_HOME/
   tune/            per-machine tuning caches rad-tune writes
 ```
 
-It defaults to the install prefix's `share/radiance`. Override it with `--radiance-home DIRS` or the
-`RADIANCE_HOME` environment variable — a search path: homes separated by `:`, the first winning,
-each holding any of the directories above. A directory of your own plugins goes ahead of an
-installation's without copying it, and `rad-info --plugins` prints what the path offers:
+It defaults to the install prefix's `share/radiance`. `--radiance-home DIRS` or `RADIANCE_HOME`
+override it with a search path: homes separated by `:`, the first winning, each holding any of the
+directories above, so a directory of your own plugins can go ahead of an installation's.
+`rad-info --plugins` prints what the path offers:
 
 ```sh
 RADIANCE_HOME=$HOME/radiance-plugins:/opt/radiance/share/radiance rad-info --plugins
 ```
 
-**Running from a build tree**, the home is `build/radiance_home` and the plugins are already in it:
+In a build tree the home is `build/radiance_home`:
 
 ```sh
 export RADIANCE_HOME=$PWD/build/radiance_home
 build/bin/radiance --model m.rad
 ```
 
-Adding support for a new card means dropping an `.so` into `kernels/` — not forking the engine.
-The engine's own device code is built for every AMD GPU family, so one engine binary starts on any
-card; a kernel library whose code objects hold nothing for the card is left out of selection when
-it loads, and says so. `docs/PLUGIN.md` §10 is a library for a card the engine has never seen.
+Supporting a new card takes an `.so` in `kernels/`, not a fork of the engine. The engine's own device
+code is built for every AMD GPU family, so one binary starts on any card; a kernel library with no
+code object for the card leaves itself out of selection at load and says so. `docs/PLUGIN.md` §10
+walks through a library for a card the engine has never seen.
 
 ### 1.6 Building for a card you do not have
 
@@ -185,59 +232,59 @@ Device kernels are compiled for the architectures the machine reports. To target
 cmake -S . -B build -G Ninja -DRAD_GPU_TARGETS='gfx1201;gfx1200'
 ```
 
-Which of those actually get kernels is decided by the libraries present; each one declares the
-architectures it serves and stays out of a build targeting anything else. The engine's own device
-code is built for every family's generic target besides, whatever is named here.
+Each kernel library declares the architectures it serves and stays out of a build targeting anything
+else. The engine's own device code is built for every family's generic target regardless.
 
 ---
 
-## 2. Five things to know before you start
+## 2. Concepts
 
-**1. A model is a checkpoint served as it stands, or a `.rad` container.** A checkpoint whose
-weights are bf16, f16, f32, block-scaled fp8 or Quark's MXFP4 is served at that precision straight
-from its directory. Anything that needs quantising is quantised once, by `rad-convert` and a recipe, into a
-container. A container holds each weight as the planes of its *encoding* — codes, scales, zero
-points, a rotation — in one canonical arrangement, plus the tokeniser, the chat template, the
-metadata, the recipe it was quantised with and optionally a draft head. No kernel library is named
-in either: the kernels rearrange the planes into their own layouts as the model loads, so a kernel
-library can change without a reconvert.
+**1. A model is a checkpoint served as it stands, or a `.rad` container.** A checkpoint whose weights
+are bf16, f16, f32, block-scaled fp8 or Quark's MXFP4 is served at that precision from its directory.
+Anything that needs quantising is quantised once, by `rad-convert` and a recipe, into a container. A
+container holds each weight as the planes of its encoding (codes, scales, zero points, a rotation) in
+one canonical arrangement, plus the tokeniser, the chat template, the metadata, the recipe and
+optionally a draft head. Neither names a kernel library: kernels rearrange the planes into their own
+layouts at load, so a kernel library can change without a reconvert.
 
-**2. Kernels are plugins, and the order matters.** The engine resolves every op in the model
-against an ordered list of kernel libraries: first one that matches an op wins. `--kernels
-mylib,libref` names the libraries to use and their order; a library it leaves out is not loaded.
-With no list, every library found loads, and the loader puts one that declares itself a reference
-implementation last.
-
-Three ship with the tree:
+**2. Kernels are plugins, and their order matters.** Every op is resolved against an ordered list of
+kernel libraries; the first that matches wins. `--kernels mylib,libref` names the libraries to load,
+in order; a library it leaves out is not loaded. Without a list every library found loads, with one
+that declares itself a reference implementation last.
 
 | library | |
 |---|---|
-| `libr4d` | the device library: AMD RDNA4 (`gfx12xx`). Paged and dense attention, gated delta net, all-reduce over P2P or a host-memory mailbox, skinny and tiled quantised GEMM, rotate-and-quantise fusions. Built when ROCm is present and the build targets a `gfx12` card |
-| `libref` | every op naively and generically. The last-resort fallback **and** the correctness oracle `rad-kbench` measures against |
-| `libavx` | the host library: the same vocabulary in hand-written x86 SIMD, dispatched by CPU feature at load. Serves every op placed on the host, the n-gram embedding's gather among them. Built on x86-64 |
+| `libr4d` | the device library for AMD RDNA4 (`gfx12xx`): paged and dense attention, gated delta net, all-reduce over P2P or a host-memory mailbox, skinny and tiled quantised GEMM, rotate-and-quantise fusions. Built when ROCm is present and the build targets a `gfx12` card |
+| `libref` | every op, naively and generically: the last-resort fallback and the correctness oracle `rad-kbench` measures against |
+| `libavx` | the host library: the same vocabulary in x86 SIMD, dispatched by CPU feature at load. Serves every op placed on the host, including the n-gram embedding's gather. Built on x86-64 |
 
-A library states the architectures it serves and stays out of a build targeting anything else, so a
-tree configured for a card it does not cover still builds and still runs.
+A library that does not cover the configured card stays out of the build, so the tree still builds
+and runs.
 
-**3. Architectures are plugins too.** `arch//` declares a model family's graph. Six ship:
+**3. Architectures are plugins too.** `arch//` declares a model family's graph:
 
 | plugin | serves |
 |---|---|
-| `llama_fp8`, `llama_dense_fp8` | LLaMA-shaped decoders — MiniCPM5, Llama 3, anything reporting `model_type: llama` |
+| `llama_fp8`, `llama_dense_fp8` | LLaMA-shaped decoders: MiniCPM5, Llama 3, anything reporting `model_type: llama` |
 | `qwen35_bf16` | Qwen3.5 / 3.6 / 3.8 dense (0.8B–27B), bf16 |
 | `qwen35_fp8` | the same, block-scaled fp8 |
 | `qwen35moe_fp8` | Qwen3.5 / 3.6 MoE (35B-A3B), 256 experts, 8 a token |
-| `qwen4exp_fp8` | Qwen4-Exp / Qwen3.8-Flash-Next — hybrid Gated DeltaNet + gated attention, 512 experts |
+| `qwen4exp_fp8` | Qwen4-Exp / Qwen3.8-Flash-Next: hybrid Gated DeltaNet + gated attention, 512 experts |
+| `gemma4` | Gemma 4 text decoders (26B-A4B MoE and the dense members): bf16 trunk, routed experts bf16 or block fp8, and the DFlash drafter |
+| `gemma4_bf16` | Gemma 4 dense in bf16, with its vision tower |
+| `lfm2_bf16` | LiquidAI LFM2 and LFM2-VL in bf16, including d1 (§5.13) |
+| `embgemma2` | EmbeddingGemma 2, an embedding model (§5.6) |
+| `qwenimage21` | Qwen-Image 2.1 and 2.1-Turbo, an image model (§5.6) |
+| `qwen3asr_bf16` | Qwen3-ASR, speech to text from the checkpoint as it ships (§5.14) |
 
-**4. Falling back to the reference library is a fatal error, not a warning.** `libref` implements
-every op naively and generically. It is the oracle and the last resort. If your model resolves any
-op to it, the engine **refuses to start** and names the ops, because serving from it would be
-orders of magnitude slow with nothing in the output to say so. That list of ops is exactly the
-work a new kernel library has to do. `--debug-accept-reference-kernels` overrides it for bring-up.
+**4. Falling back to the reference library is fatal.** If any op resolves to `libref`, the engine
+refuses to start and names the ops, because serving from it is orders of magnitude slower with nothing
+in the output to say so. That list is the work a new kernel library has to do.
+`--debug-accept-reference-kernels` overrides it for bring-up.
 
-**5. Every pool is budgeted explicitly.** There is no profiling pass and no utilisation fraction.
-The trade between KV blocks and resident weights is real, workload-dependent and **yours to make**.
-An engine that quietly re-optimises the split is an engine whose benchmarks do not reproduce.
+**5. Every pool is budgeted explicitly.** There is no profiling pass and no utilisation fraction. The
+trade between KV blocks and resident weights depends on the workload and is the operator's to make;
+a split the engine re-optimised on its own would make benchmarks irreproducible.
 
 ---
 
@@ -246,163 +293,177 @@ An engine that quietly re-optimises the split is an engine whose benchmarks do n
 ### 3.1 Download a checkpoint
 
 ```sh
-scripts/hfget.sh Qwen/Qwen3.8-Flash-Next ~/models/Qwen/Qwen3.8-Flash-Next
+scripts/hfget.sh Qwen/Qwen3.8-Flash-Next /srv/models/Qwen/Qwen3.8-Flash-Next
 ```
 
-`curl` and `jq`, nothing else. Re-running resumes: a file whose local size already matches is
-skipped and a short one is continued. It also skips duplicate weight formats — if a repo carries
-`.safetensors` it will not also pull the `.bin`, the ONNX export and the GGUF.
+It needs only `curl` and `jq`. Re-running resumes: a file whose local size matches is skipped and a
+short one is continued. When a repo carries `.safetensors`, other weight formats (`.bin`, ONNX, GGUF,
+...) are not fetched. `HF_TOKEN` authenticates a gated or private repo; `HFGET_JOBS` sets concurrency
+(default 4). A complete fetch records each file's content key (its LFS sha256, or a small file's size)
+in `.hfget-manifest`, so the next run also fetches a file that changed at the same size. The
+free-space check counts only what is still to fetch.
 
-Set `HF_TOKEN` for a gated or private repo. `HFGET_JOBS` sets concurrency (default 4).
-
-A complete fetch records each file's content key (its LFS sha256, or the size of a small file) in
-`.hfget-manifest`, so the next run also fetches a file that changed at the same size. The free-space
-check counts only what is still to fetch.
-
-**The server can do this itself.** `--model` takes a repo id where it would take a path:
+`--model` also takes a repo id:
 
 ```sh
 radiance --model StillDeadcode/minicpm5-2b-fp8 --port 8000
 ```
 
-It runs the same script (installed beside the binary, in `libexec/radiance/`) into
+The server runs the same script (installed in `libexec/radiance/`) into
 `--download-dir//` before bring-up, then serves the one `.rad` at the repo's top level,
 or the directory as a checkpoint (§3.4) when it holds none. A repo with several containers is
-refused by name; pass the file. Every start checks the hub and fetches what changed. A start that
-cannot read the listing, or whose update does not fit, serves the copy a complete earlier fetch
-left and says so; a transfer that fails part-way stops startup. A path that exists is always a
+refused, naming them; pass the file. Every start checks the hub and fetches what changed. A start that
+cannot read the listing, or whose update does not fit on disk, serves the copy a complete earlier
+fetch left and says so; a transfer that fails part-way stops startup. A path that exists is always a
 path, and a name ending in `.rad`, `.safetensors`, `.gguf` or `.json` is never looked up.
 
 ### 3.2 Convert it
 
 ```sh
-rad-convert ~/models/Qwen/Qwen3.8-27B-FP8 -o ~/models/rad/q38-27b-fp8.rad --home $RADIANCE_HOME
+rad-convert /srv/models/Qwen/Qwen3.8-27B-FP8 -o /srv/models/rad/q38-27b-fp8.rad --home $RADIANCE_HOME
 ```
 
-Input is a `.gguf`, a `.safetensors`, or a directory holding a checkpoint. What happens: the
-architecture plugin declares the model's graph and its name map says which checkpoint tensors make
-each weight; every op is resolved against the kernel hierarchy and every resolved kernel is asked
-whether it reads the encoding each weight will have; then each weight is written once, as its
-encoding's planes, and the tokeniser and chat template are baked in.
+Input is a `.gguf`, a `.safetensors`, an index or a checkpoint directory. The architecture plugin
+declares the graph and maps checkpoint tensors to weights, every op is resolved and each kernel is
+asked whether it reads its weight's encoding, then each weight is written once as its encoding's
+planes, with the tokeniser and chat template.
 
-**A recipe decides what is quantised.** With none, every weight keeps the checkpoint's encoding,
-which is right for a bf16 or block-fp8 checkpoint served at its own precision. A model whose served
-form needs quantisation work — Flash-Next's four-bit experts, an fp8 head made from a bf16 one —
-names it in rules from weight names to quantisers:
+**A recipe decides what is quantised**, in rules from weight names to quantisers. Without one,
+every weight keeps the checkpoint's encoding, which suits a bf16 or block-fp8 checkpoint served at
+its own precision. Flash-Next's four-bit experts need one:
 
 ```sh
-rad-convert ~/models/Qwen/Qwen3.8-Flash-Next -o ~/models/rad/flashnext-w4.rad \
+rad-convert /srv/models/Qwen/Qwen3.8-Flash-Next -o /srv/models/rad/flashnext-w4.rad \
     --recipe data/recipes/qwen4exp-w4.recipe --home $RADIANCE_HOME
 ```
 
-`qwen4exp-w4.recipe` rounds the experts to nearest and needs nothing but the checkpoint. The
-production Flash-Next container, `w4nl64-i8lm.rad`, is built by
-`data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe`, whose expert rule is GPTQ against recorded Grams:
-it expands `$CALIB` from the environment, so it is run as `CALIB=DIR rad-convert ...` with `DIR`
-holding a calibration run's files. The recipe's header and [MOE-W4.md](MOE-W4.md) say what that
-directory must hold and how it is recorded.
-
 ```
-# data/recipes/... -- PATTERN  QUANTISER  OPTIONS; the first match decides
-blk.*.ffn_*_exps.*.weight   gptq  codes=i4 group=128 scale=bf16 transform=fwht128 calib=$CALIB
-output.weight               rtn   codes=fp8_e4m3 block=128x128 scale=bf16
-blk.*.weight                rtn   codes=fp8_e4m3 block=128x128 scale=bf16
+# data/recipes/qwen4exp-w4.recipe (excerpt): PATTERN  QUANTISER  OPTIONS; the first match decides
+blk.*.ffn_*_exps.*.weight            rtn  codes=i4 group=128 scale=bf16 transform=fwht128
+blk.*.attn_qg.weight                 rtn  codes=fp8_e4m3 block=128x128 scale=bf16
+output.weight                        rtn  codes=fp8_e4m3 block=128x128 scale=bf16
 ```
 
-Every weight it quantises is measured against the source and the worst are printed. The recipe
-syntax, the quantisers and their options are in [TOOLS.md](TOOLS.md#recipes).
+`qwen4exp-w4.recipe` rounds the experts to nearest and needs only the checkpoint. The production
+Flash-Next container, `w4nl64-i8lm.rad`, is built by `data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe`,
+whose expert rule is GPTQ against recorded Grams. It expands `$CALIB` from the environment, so it
+runs as `CALIB=DIR rad-convert ...` with `DIR` holding a calibration run's files; the recipe's header
+and [MOE-W4.md](MOE-W4.md) say what that directory holds and how it is recorded.
 
-Because it runs the same declare phase the engine does, everything that can refuse has refused by
-the time the I/O starts — including a recipe no loaded kernel can serve. On a large checkpoint that
-I/O is an hour, so check the plan first:
+Every quantised weight is measured against the source and the worst are printed. The recipe syntax,
+the quantisers and their options are in [TOOLS.md](TOOLS.md#recipes).
+
+`rad-convert` runs the engine's declare phase, so anything that would be refused (including a
+recipe no loaded kernel can serve) is refused before the I/O, which takes an hour on a large
+checkpoint. To check the plan only:
 
 ```sh
 rad-convert  -o out.rad --recipe r.recipe --plan-only -v
 ```
 
-Useful variants:
+Other conversions:
 
 ```sh
 # Merge a separate drafter checkpoint (DSpark, DFlash2) into the container
-rad-convert $SRC -o out.rad --draft-model ~/models/openbmb/MiniCPM5-2B-DSpark
+rad-convert $SRC -o out.rad --draft-model /srv/models/openbmb/MiniCPM5-2B-DSpark
 
 # Re-quantise some weights and copy the rest from an earlier container
 rad-convert $SRC -o new.rad --recipe new.recipe --reuse old.rad
 
-# A bf16 Qwen3.8-27B -- the base release or a finetune of it -- as Qwen's block fp8: the recipe
-# writes the linears, and --set states the format, which is what selects the fp8 plugin
-rad-convert ~/models/ukisai/Swift-1.5-Qwen3.8-27b -o swift-27b-fp8.rad \
-    --draft-model ~/models/z-lab/Qwen3.8-27B-DFlash2 --recipe data/recipes/q38-27b-fp8block-df2.recipe \
+# A bf16 Qwen3.8-27B (the base release or a finetune) as Qwen's block fp8: the recipe writes the
+# linears, and --set states the format, which selects the fp8 plugin
+rad-convert /srv/models/ukisai/Swift-1.5-Qwen3.8-27b -o swift-27b-fp8.rad \
+    --draft-model /srv/models/z-lab/Qwen3.8-27B-DFlash2 --recipe data/recipes/q38-27b-fp8block-df2.recipe \
     --set quantization_config.quant_method=fp8 --set quantization_config.fmt=e4m3 \
     --set "quantization_config.weight_block_size=128 128" --set quantization_config.activation_scheme=dynamic
 
 # gemma-4-26B-A4B-it with z-lab's DFlash drafter, the routed experts' gate_up as block fp8 (served by
 # arch/gemma4; docs/ARCHITECTURES.md says why down stays bf16 unless the experts were padded to 768)
-rad-convert ~/models/google/gemma-4-26B-A4B-it -o gemma4-26b-a4b-df.rad \
-    --draft-model ~/models/z-lab/gemma-4-26B-A4B-it-DFlash --recipe data/recipes/gemma4-26b-a4b-df.recipe
+rad-convert /srv/models/google/gemma-4-26B-A4B-it -o gemma4-26b-a4b-df.rad \
+    --draft-model /srv/models/z-lab/gemma-4-26B-A4B-it-DFlash --recipe data/recipes/gemma4-26b-a4b-df.recipe
 
 # Qwen-Image 2.1 or 2.1-Turbo, an image model (§5.6): the diffusers pipeline directory is the
-# checkpoint -- text encoder, DiT, VAE and the tokenizer together. fp8 blocks for the text encoder
-# and the DiT (17 GB, one card or two), or the checkpoint's bf16 (31 GB, two cards)
-rad-convert ~/models/Qwen/Qwen-Image-2.1 -o qwen-image-2.1-fp8.rad \
+# checkpoint (text encoder, DiT, VAE and tokenizer). fp8 blocks for the text encoder and the DiT
+# (17 GB, one card or two), or the checkpoint's bf16 (31 GB, two cards)
+rad-convert /srv/models/Qwen/Qwen-Image-2.1 -o qwen-image-2.1-fp8.rad \
     --recipe data/recipes/qwen-image-2.1-fp8.recipe
-rad-convert ~/models/Qwen/Qwen-Image-2.1-Turbo -o qwen-image-2.1-turbo-fp8.rad \
+rad-convert /srv/models/Qwen/Qwen-Image-2.1-Turbo -o qwen-image-2.1-turbo-fp8.rad \
     --recipe data/recipes/qwen-image-2.1-fp8.recipe
 ```
 
 A checkpoint directory's `model.safetensors.index.json` decides which shard each tensor is read
-from. A finetune that changed only some tensors can be assembled from them and the base model: its
-changed tensors in shards of their own, links to the base model's shards for the rest, and an index
-that points each name at its copy. A name two shards hold that no index entry settles is refused.
+from, so a finetune that changed only some tensors can be assembled from shards of its changed
+tensors, links to the base model's shards, and an index pointing each name at its copy. A name held
+by two shards and not settled by the index is refused.
 
-The conversions of record live in `scripts/convfn.sh` and `scripts/convdspark.sh`, with their
-recipes in `data/recipes/`.
+The conversions of record are `scripts/convfn.sh` and `scripts/convdspark.sh`, with their recipes in
+`data/recipes/`.
 
-**A release someone else already quantised is read as it ships.** Four forms are imported weight
-by weight, so their quantised linears need no recipe rule:
+**A release someone else quantised is read as it ships.** These forms are imported weight by
+weight (`Checkpoint::Import`, core/format/checkpoint.h). rad-convert writes each quantised linear
+in the encoding below unless a recipe rule names it; a rule re-quantises from the exact
+dequantisation where the architecture's kernels read another form, and NVFP4 always needs one:
 
 | `quantization_config` | read as | |
 |---|---|---|
 | `quark`, MXFP4 weights (fp4, per_group 32, e8m0) | `fp4_e2m1*e8m0[1x32]` | byte for byte: the same codes and exponents. A checkpoint of this form is also served as it stands (§3.4) |
-| `paroquant_mxfp4` (z-lab's ParoQuant on the MXFP4 grid: `format mxfp4`, `mxfp4_block 32`, `group_size 128`) | `fp4_e2m1*e8m0[1x32]/givens` | the codes and exponents byte for byte, plus the learned rotation as the encoding's `givens` tables: per checkpoint tensor the Givens pairs (made whole-row columns), angles and `1 / channel_scales`, a fused gate\|up or qkv\|z carrying one set a part. Convert-time only (the tables are built, not mapped); served by the rotating activation quantiser `givens_dense_quant` and the ordinary MXFP4 GEMM (docs/OPS.md). Its fp8 heads and embedding (one f32 scale a row) are read exactly, for a recipe's `cast`/`rtn` rule |
-| `paroquant`, `format int5-bitplane` (bits 5, group 128) and z-lab's plain `paroquant` (bits 4, group 128) | `u5*f16[1x128]-u8[1x128]/givens` and `u4*f16[1x128]-u8[1x128]/givens` | the AWQ-packed low nibbles (plus the fifth-bit plane) re-laid as a code bit stream along K, the f16 scales and the integer zero points transposed to `[N, K/128]`, and the rotation as the `givens` tables above. Convert-time only; served by `givens_rotate` and `gemm_nt_q` at `w5a16` / `w4a16_asym` over an f16 activation (docs/OPS.md) |
+| `paroquant_mxfp4` (z-lab's ParoQuant on the MXFP4 grid: `format mxfp4`, `mxfp4_block 32`, `group_size 128`) | `fp4_e2m1*e8m0[1x32]/givens` | the codes and exponents byte for byte, plus the learned rotation as the encoding's `givens` tables: per checkpoint tensor the Givens pairs (made whole-row columns), angles and `1 / channel_scales`, a fused gate\|up or qkv\|z carrying one set a part. Convert-time only (the tables are built, not mapped); served by the rotating activation quantiser `givens_dense_quant` and the MXFP4 GEMM (docs/OPS.md). Its fp8 heads and embedding (one f32 scale a row) are read exactly, for a recipe's `cast`/`rtn` rule |
+| `paroquant`, `format int5-bitplane` (bits 5, group 128) and z-lab's plain `paroquant` (bits 4, group 128) | `u5*f16[1x128]-u8[1x128]/givens` and `u4*f16[1x128]-u8[1x128]/givens` | the AWQ-packed low nibbles (plus the fifth-bit plane) re-laid as a code bit stream along K, the f16 scales and integer zero points transposed to `[N, K/128]`, and the rotation as the `givens` tables above. Convert-time only; served by `givens_rotate` and `gemm_nt_q` at `w5a16` / `w4a16_asym` over an f16 activation (docs/OPS.md) |
+| `compressed-tensors`, `format: pack-quantized` with every config group 4-bit `int` weights, `symmetric`, `strategy: group`, not `dynamic`, no `actorder` and no `input_activations` (e.g. Google's Gemma 4 QAT w4a16-ct) | `i4*[1xG]`, G the groups' one group size | `X.weight_packed` (int32 `[N, K/8]`, eight codes a word from the low bits, offset 8) made signed, beside `X.weight_scale` (`[N, K/G]`, f16, bf16 or f32) as shipped. A zero point is refused by name, and an `X.weight_shape` must state the codes' `[N, K]`. Convert-time only; `data/recipes/gemma4-31b-dense-w4a8.recipe` re-quantises the group-32 release to the group-128 grid the w4a8 kernels read |
 | `auto-round` with `packing_format: auto_round:auto_gptq`, and `gptq` (v1) | `i4*bf16[1x128]` or `i8*bf16[1x128]` | the GPTQ-packed codes transposed and made signed, the f16 scales rounded to bf16. Symmetric, group 128 or a multiple of it (per channel included), no act-order. Convert-time only, because the scales are not served as shipped |
+| `compressed-tensors` with an `nvfp4-pack-quantized` config group (`weights`: 4-bit float, group 16) | `fp4_e2m1*f32[1x16]` | the packed e2m1 codes beside an f32 scale per 16 of K, `weight_scale / weight_global_scale`: the global scale is a divisor, as compressed-tensors' dequantise and vLLM read it. Each piece keeps its own global, so a fused gate\|up reads both exactly. No kernel serves NVFP4, so every NVFP4 weight takes a recipe rule (`data/recipes/q38-27b-nvfp4-df2.recipe` makes it MXFP4) |
+| `compressed-tensors` whose config groups are all `float-quantized` with 8-bit `float` weights | `fp8_e4m3*[1x*]` or `[RxC]` | nothing is imported: each `X.weight` reads stock as FP8 with `X.weight_scale` beside it, one scale a row (`[N, 1]` or `[N]`, the channel strategy) or a block plane; a per-tensor scale is refused at the weight. The quantisation is still the tool's, so the family's quantised plugin serves it |
 
 The width is read per tensor, so a release mixing int4 experts with int8 projections imports both.
-What an import cannot read — an asymmetric zero point, an act-order index, a group under 128 — is
-refused by name at the weight. The release's `quantization_config` names the tool, not a served
-form, so it is kept in the container as `imported_quantization_config.*`, and the model is served by
-its family's quantised plugin (`qwen35_fp8` for Qwen3.8-27B; `qwen4exp_fp8` for Flash-Next).
+A mixed-precision release (NVFP4 MLPs beside FP8 or bf16 linears, the usual NVFP4 layout) reads
+every weight by its own form: a weight without `X.weight_packed` is not NVFP4 and reads stock, its
+`float-quantized` FP8 with the per-row (`[N, 1]`) or block scale beside it. A compressed-tensors
+release whose groups are all `float-quantized` FP8 reads the same way, with nothing to import.
+What an import cannot read (an asymmetric zero point, an act-order index, a group under 128, a
+missing or zero global scale, a compressed-tensors format not listed here) is refused by name. The release's `quantization_config` names the tool, not a served
+form, so it is kept as `imported_quantization_config.*`, and the model is served by its family's
+quantised plugin (`qwen35_fp8` for Qwen3.8-27B, `qwen4exp_fp8` for Flash-Next).
 
 A weight the architecture declares in another form than the release holds still takes a rule: the
-recipe dequantises the import exactly and quantises from that. The recipes of record:
+recipe dequantises the import exactly and quantises from that. A rule names the target form, not
+the source, so one recipe covers a mixed release in one pass. NVFP4 to MXFP4 rounds twice (e4m3
+scales per 16 to a power of two per 32), so it loses more than MXFP4 made from the bf16 original:
+against the block-fp8 Qwen3.8-27B on the same four documents, unsloth's NVFP4 release made MXFP4
+scores mean KL 0.287 and top-1 agreement 87.5%, AMD's calibrated Quark MXFP4 container 0.206 and
+89.3%. Prefer the Quark container unless you need that particular checkpoint. The recipes of
+record:
 
 ```sh
 # AMD's Quark AWQ-MXFP4 Qwen3.8-27B with the DFlash2 drafter
-rad-convert ~/models/amd/Qwen3.8-27B-Quark-AWQ-MXFP4 --draft-model ~/models/z-lab/Qwen3.8-27B-DFlash2 \
+rad-convert /srv/models/amd/Qwen3.8-27B-Quark-AWQ-MXFP4 --draft-model /srv/models/z-lab/Qwen3.8-27B-DFlash2 \
     --recipe data/recipes/q38-27b-quark-mxfp4-df2.recipe -o q38-27b-quark-mxfp4-df2.rad
 
 # A ParoQuant MXFP4 Qwen3.8-27B (rotated MXFP4 trunk imported with its rotations; fp16 parts cast to bf16)
-rad-convert ~/models/MisterSnrub/Qwen3.8-27B-PARO-MXFP4-v2 --draft-model ~/models/z-lab/Qwen3.8-27B-DFlash2 \
+rad-convert /srv/models/MisterSnrub/Qwen3.8-27B-PARO-MXFP4-v2 --draft-model /srv/models/z-lab/Qwen3.8-27B-DFlash2 \
     --recipe data/recipes/q38-27b-paro-mxfp4-df2.recipe -o q38-27b-paro-mxfp4-df2.rad
 
 # ParoQuant int5 (Launch80/Qwen3.8-27B-PARO-int5) and z-lab's int4 (z-lab/Qwen3.8-27B-PARO): same recipe
-rad-convert ~/models/Launch80/Qwen3.8-27B-PARO-int5 --draft-model ~/models/z-lab/Qwen3.8-27B-DFlash2 \
+rad-convert /srv/models/Launch80/Qwen3.8-27B-PARO-int5 --draft-model /srv/models/z-lab/Qwen3.8-27B-DFlash2 \
     --recipe data/recipes/q38-27b-paro-mxfp4-df2.recipe -o q38-27b-paro-int5-df2.rad
 
+# unsloth's NVFP4 Qwen3.8-27B with the DFlash2 drafter: the NVFP4 MLPs and the FP8 linears beside
+# them made MXFP4 by one recipe, the head block fp8
+rad-convert /srv/models/unsloth/Qwen3.8-27B-NVFP4 --draft-model /srv/models/z-lab/Qwen3.8-27B-DFlash2 \
+    --recipe data/recipes/q38-27b-nvfp4-df2.recipe -o q38-27b-nvfp4-df2.rad
+
 # An AutoRound int4 Qwen3.8-Flash-Next: its experts imported, its int4 projections made int8
-rad-convert ~/models/ukisai/Swift-1.5-Qwen3.8-Flash-Next-W4A16-AutoRound \
+rad-convert /srv/models/ukisai/Swift-1.5-Qwen3.8-Flash-Next-W4A16-AutoRound \
     --recipe data/recipes/qwen4exp-autoround-i8-hc8m.recipe -o swift-autoround.rad
 ```
 
-### 3.3 Look at what you built
+### 3.3 Inspect a container
 
 ```sh
-rad-info ~/models/rad/flashnext-w4.rad
+rad-info /srv/models/rad/flashnext-w4.rad
 ```
 
 ```
-flashnext-w4.rad
+/srv/models/rad/flashnext-w4.rad
   format        RAD2, 166.4 GiB, little-endian
   architecture  qwen4exp
   model         Qwen3.8-Flash-Next
@@ -411,35 +472,35 @@ flashnext-w4.rad
   created by    rad-convert ...
 
   section          offset        bytes    count
-  strings             256      1.2 MiB        -
-  metadata        1258752      8.4 KiB      214
+  strings            256      1.2 MiB        -
+  metadata       1258752      8.4 KiB      214
   ...
 ```
 
 `rad-info` opens the file read-only and loads no plugins. It lists every weight with its encoding
-and what made it — the checkpoint as it stood, or the recipe rule's quantiser and options.
+and what made it: the checkpoint as it stood, or the recipe rule's quantiser and options.
 
 ```sh
-rad-info --meta m.rad                  # just the metadata table
+rad-info --meta m.rad                  # the metadata table
 rad-info --vocab m.rad                 # vocab summary and normaliser chain
 rad-info --recipe m.rad                # the recipe it was converted with
 rad-info -v m.rad                      # every tensor
 ```
 
-### 3.4 Or skip the container
+### 3.4 Serving a checkpoint without a container
 
 ```sh
-radiance --model ~/models/Qwen/Qwen3.8-27B-FP8
+radiance --model /srv/models/Qwen/Qwen3.8-27B-FP8
 ```
 
-`--model` takes a checkpoint directory, a `.safetensors`, an index or a `.gguf`, and serves it at
-its own precision. Its `config.json` (or the GGUF header) is the metadata, the `tokenizer.json` and
-chat template beside it are the tokeniser, and `generation_config.json` gives the sampling defaults.
-The weights are read once, at load, by every relayout worker at once.
+`--model` takes a checkpoint directory, a `.safetensors`, an index or a `.gguf`, and serves it at its
+own precision. `config.json` (or the GGUF header) is the metadata, the `tokenizer.json` and chat
+template beside it are the tokeniser, and `generation_config.json` gives the sampling defaults. The
+weights are read once at load, by all relayout workers in parallel.
 
-**Nothing is quantised at load.** A weight the architecture plugin reads in another encoding than
-the checkpoint holds is named at startup, and the remedy is a container with a recipe that says
-what it becomes. MiniCPM5-2B is one: OpenBMB ships it in bf16, and `llama_dense_fp8` reads fp8.
+Nothing is quantised at load. A weight the architecture plugin reads in another encoding than the
+checkpoint holds is named at startup, and needs a container with a recipe. MiniCPM5-2B is one case:
+OpenBMB ships it in bf16, and `llama_dense_fp8` reads fp8.
 
 What a container has that a checkpoint does not:
 
@@ -450,19 +511,19 @@ What a container has that a checkpoint does not:
 | a placement profile | worth about a point of expert hit rate |
 
 A GGUF is read when its architecture plugin maps llama.cpp's tensor names; the shipped plugins map
-HuggingFace's, so a model of a shipped architecture is converted from its safetensors release.
+Hugging Face's, so a model of a shipped architecture is converted from its safetensors release.
 
 ---
 
 ## 4. Serve it
 
-### 4.1 The simplest run
+### 4.1 Minimal run
 
 ```sh
-radiance --model ~/models/rad/flashnext-w4.rad
+radiance --model /srv/models/rad/flashnext-w4.rad
 ```
 
-It claims the card (less `--gpu-headroom-mib`, default 96 MiB), splits it between weights and KV
+It claims the card less `--gpu-headroom-mib` (default 96 MiB), splits it between weights and KV
 cache, loads, and serves on `http://0.0.0.0:8000`. The startup log states every budget before
 anything is allocated.
 
@@ -470,233 +531,196 @@ anything is allocated.
 radiance --model m.rad --port 8100 --host 127.0.0.1
 ```
 
-### 4.2 Look before you leap
+### 4.2 Checking the plan
 
 ```sh
 radiance --model m.rad --debug-graph
 ```
 
-Prints the entire declared graph — every op, the kernel each one resolved to, and why — then exits
-without serving. This is the first thing to run against a new container or a new kernel library.
+Prints the declared graph (every op, the kernel it resolved to, and why) and exits without serving.
+Run it first against a new container or a new kernel library.
 
 ```sh
-radiance --model m.rad --debug-selection    # just the selection table
-radiance --model m.rad --debug-placement    # just the placement plan
+radiance --model m.rad --debug-selection    # the selection table only
+radiance --model m.rad --debug-placement    # the placement plan only
 ```
 
-### 4.3 Memory: how the card gets split
+### 4.3 Memory: how the card is split
 
-The card is split into **resident weights** and the **paged KV pool**, and the engine derives the
-split from the card and the model; no flag states either pool. What you move are its inputs:
-`--gpu-headroom-mib` leaves card space alone, `--max-model-len` and `--max-num-seqs` bound the
-cache, and `--host-pool-mib` decides which experts must stay on the card. The startup receipt
-prints every term. On a machine with no visible card (the host backend) half of RAM stands in for
-the card and is split the same way; the weights pool is then host memory, holding the weights a
-host kernel cannot read where the container stores them.
+The card is split into resident weights and the paged KV pool. The engine derives the split from the
+card and the model; no flag states either pool. Its inputs: `--gpu-headroom-mib` leaves card space
+alone, `--max-model-len` and `--max-num-seqs` bound the cache, and `--host-pool-mib` decides which
+experts must stay on the card. The startup receipt prints every term. With no visible card (the host
+backend) half of RAM stands in for the card and is split the same way; the weights pool is then host
+memory, holding the weights a host kernel cannot read where the container stores them.
 
-The non-expert weights come off the top of what is claimed. The rest — the `elastic` line of the startup receipt — is shared by
-the expert slab and the KV cache, and no flag divides it:
+The non-expert weights come off the top. The rest (the receipt's `elastic` line) is shared by the
+expert slab and the KV cache:
 
-- **The cache lends** under `--placement auto` or `expert_tiered`, without `--deterministic`, on a
-  device with virtual memory management. The experts keep on the card exactly what the pinned host
-  pool (`--host-pool-mib`) cannot hold, plus one expert unit of packing slack; they have nowhere
-  else to be. The cache takes everything else, up to what it could ever address
-  (`--max-num-seqs` x `--max-model-len`), and every block no live request holds is lent back to the
-  expert slab in place. The prefill staging region comes out of the cache's side.
-- **Without a lender** — `--deterministic`, a stated `--placement all_vram` or `layer_offload`, or
-  no virtual memory management — a block the cache does not use would sit empty, so the experts
-  come first and the cache keeps one `--max-model-len` sequence.
+- **With a lending cache** (`--placement auto` or `expert_tiered`, no `--deterministic`, a device
+  with virtual memory management), the experts keep on the card what the pinned host pool cannot
+  hold, plus one expert unit of packing slack. The cache takes the rest, up to what it could ever
+  address (`--max-num-seqs` x `--max-model-len`), and lends every block no live request holds back
+  to the expert slab in place. The prefill staging region comes out of the cache's side.
+- **Without a lender** (`--deterministic`, an explicit `--placement all_vram` or `layer_offload`, or
+  no virtual memory management), the experts come first and the cache keeps one `--max-model-len`
+  sequence.
 
 The cache never gets less than one `--max-model-len` sequence, and when both sides fit, both are
-whole. With a lending cache, `--host-pool-mib` is what moves the split: a larger pool takes experts
-off the card and gives the cache more.
+whole. With a lending cache, a larger `--host-pool-mib` takes experts off the card and gives the
+cache more.
 
-**The next layer's experts are fetched ahead at decode.** The experts kept only in the pinned host
-pool are read across the link by the routed GEMMs that need them, while those GEMMs run. At each
-routed layer of a decode pass of up to 16 rows, the engine applies the *next* routed layer's router
-to this layer's router input -- it predicts that layer's choice well -- and the card's second DMA
-engine copies the two likeliest experts that are only in the pool onto the card while the rest of
-this layer runs. Just before the next layer's GEMMs, their weight tables point at the copies that
-have landed, so those GEMMs read them from VRAM. A copy holds the bytes of the pool slot it was made
-from, so this changes no output; a copy that lands late is not used. It is on wherever the pool
-holds experts (`--placement expert_tiered` or `auto`), off under `--deterministic` and where the
-device backend has no second DMA engine, and the startup log says which (`expert prefetch on` /
-`off`). It costs one hardware queue and a ring of six expert units on the card, both in the VRAM
-receipt (`hardware queues`, `expert prefetch`).
+**Next-layer expert prefetch.** Experts held only in the pinned host pool are read across the link by
+the routed GEMMs that need them. At each routed layer of a decode pass of up to 16 rows, the engine
+applies the next routed layer's router to this layer's router input, which predicts that layer's
+choice well, and the card's second DMA engine copies the two likeliest pool-only experts onto the
+card while the layer runs. The next layer's GEMMs read the copies that have landed from VRAM; a copy
+holds the pool slot's bytes, so outputs do not change, and a late copy is not used.
 
-It pays only where the steps use enough of what it copies, so it measures that: every 2048
-predictions it looks at the share of its copies the steps routed, and under 30% it rests -- no
-prediction, no copy -- for 8192 passes before measuring again (`expert prefetch resting`, once, in
-the log). On Qwen3.8-Flash-Next at `--tp 1` with the `flashnext-tp1` flags the steps use about half
-of the copies, and the decode step goes from 29.0 to 28.0 ms at one sequence and from 101.3 to 95.3
-ms at four. At `--tp 2` each card keeps most of its experts and the pool holds the ones the steps
-rarely route; under a quarter of the copies were used, it was a loss, and the prefetch rests there.
+It is on wherever the pool holds experts (`--placement expert_tiered` or `auto`), and off under
+`--deterministic` or without a second DMA engine; the log says which (`expert prefetch on` / `off`).
+It costs one hardware queue and a ring of six expert units on the card (receipt lines `hardware
+queues` and `expert prefetch`). Every 2048 predictions it checks the share of its copies the steps
+routed; under 30% it rests (no prediction, no copy) for 8192 passes and logs `expert prefetch
+resting` once. On Qwen3.8-Flash-Next at `--tp 1` with the `flashnext-tp1` flags about half the
+copies are used, and the decode step goes from 29.0 to 28.0 ms at one sequence and from 101.3 to
+95.3 ms at four. At `--tp 2` each card keeps most of its experts, under a quarter of the copies are
+used, and the prefetch rests.
 
-**An uneven world re-splits its cheaper ranks.** The split above is worked out once, for the rank
-whose cache costs most, and one block table serves every rank. Where a rank's cache costs less per
-token -- an attention-zero rank at `--tp 3` keeps no attention cache -- it gets, under
-`expert_tiered`, a KV pool that pages exactly the common token count and the
-difference in its weights pool, up to every one of its weights resident; the startup log names the
-rank and both sizes (`kv: rank N's cache costs ...`). It holds with or without a lending cache:
-under `--deterministic`, or on a device without virtual memory management, the bytes that rank
-would never page go to its experts all the same. A rank whose cache costs as much per token as the dearest
-rank's is never re-split -- which at `--tp 2` and `--tp 4` is every rank. A rank that costs less and
-keeps the common split says why on the same `kv: rank N's cache costs ...` line. Every rank still
-allocates its whole `--host-pool-mib`, a re-split rank whose weights all fit on the card included,
-and that rank's log says its pinned host pool holds no weights ([`TP3.md`](TP3.md) §1).
+**Uneven ranks.** The split is computed for the rank whose cache costs most, and one block table
+serves every rank. A rank whose cache costs less per token (an attention-zero rank at `--tp 3` keeps
+no attention cache) gets, under `expert_tiered`, a KV pool that pages exactly the common token count,
+and the difference goes to its weights, up to all of them resident, with or without a lending cache.
+The log names the rank and both sizes (`kv: rank N's cache costs ...`), or says on the same line why
+a cheaper rank kept the common split. At `--tp 2` and `--tp 4` every rank costs the same and nothing
+is re-split. Every rank still allocates its whole `--host-pool-mib`; a re-split rank whose weights
+all fit on the card logs that its pinned host pool holds no weights ([`TP3.md`](TP3.md) §1).
 
-**The cache's size decides whether multi-turn works.** The KV side is not only concurrency: prefix
-caching holds a finished sequence's blocks so the next turn can reuse them. When the pool cannot
-hold the *live sessions*, the cache drops prefixes the next turn wanted and that turn re-prefills
-its whole context. At long contexts that is two orders of magnitude of time-to-first-token.
-Measured on Qwen3.8-Flash-Next at a 200K context with two ~184K-token sessions and byte-identical
-text, the second turn took 173.0 s at a 0.0% prefix hit with a pool that could not hold both
-sessions, and 3.0 s at 99.0% with one that could. The fall-off is sharp, and `kv_util` shows a
-pool approaching it.
+**Cache size and multi-turn.** Prefix caching holds a finished sequence's blocks for the next turn.
+When the pool cannot hold the live sessions, it drops prefixes the next turn wanted and that turn
+re-prefills its whole context. On Qwen3.8-Flash-Next at a 200K context with two ~184K-token sessions,
+the second turn took 173.0 s at a 0.0% prefix hit with a pool too small for both sessions, and 3.0 s
+at 99.0% with one large enough. The fall-off is sharp; `kv_util` shows a pool approaching it.
 
-To size it yourself: work out what a token of context costs across **all** paged groups for your
-model (the startup log prints this), multiply by the context you actually serve, multiply by the
-sessions you want live at once, and compare that with the cache the receipt reports. The cache
-already has everything the experts can do without; a larger `--host-pool-mib` (RAM permitting) or
-`--kv-cache-dtype fp8` gives it more.
+To size it: multiply what a token of context costs across all paged groups (the startup log prints
+it) by the context you serve and by the sessions you want live at once, and compare with the cache
+the receipt reports. The cache already has everything the experts can spare; a larger
+`--host-pool-mib` (RAM permitting) or `--kv-cache-dtype fp8` gives it more. For example, on
+Qwen3.8-Flash-Next two paged groups share one token axis, `kv_attn` at 26.00 KiB and `kv_qsa_bkey` at
+3.25 KiB per 4-token block, so a token costs 7.32 KiB and a 200K-token sequence 1.43 GiB. A
+prefix-cached session occupies about 1.8x its context in pool tokens, so two live 184K sessions need
+~662K pool tokens.
 
-Worked, on Qwen3.8-Flash-Next: two paged groups share one token axis — `kv_attn` at 26.00 KiB and
-`kv_qsa_bkey` at 3.25 KiB per 4-token block — so a token of context costs **7.32 KiB**, and a
-200K-token sequence is 1.43 GiB. A prefix-cached session occupies roughly 1.8x its context in pool
-tokens, so two live 184K sessions want ~662K pool-tokens. That is the number the KV side has to
-clear.
-
-What is claimed is not all of the card. The **activation arena** — scratch for the largest step
-the engine may run — is taken off the budget *before* it is split, so it is paid for by both
-sides. It grows with `--max-num-batched-tokens`, which is why raising the prefill chunk costs
-resident experts (§4.5).
-
-**Most of the arena is lent back while the steps are small.** A decode step is a few dozen rows
-of the 2048 a prefill chunk carries, so the engine asks the architecture plugin to declare its
-activations again at smaller step sizes (the decode rows rounded up to a power of two and at least
-256, then four times that, up to the step budget) and packs each into the bottom of the arena. While the recent steps fit a smaller size, the top of the arena holds expert
-weights; the first step that needs more takes it back before it runs — a change of address for
-the units there, not a copy. Startup prints what each size lends (`activation arena: lends ...`).
-A plugin opts in (`RadArchProbe::shape_probe_ok`); one that does not keeps its whole arena.
+**The activation arena**, scratch for the largest step the engine may run, comes off the budget
+before the split, so both sides pay for it. It grows with `--max-num-batched-tokens`, which is why a
+larger prefill chunk costs resident experts (§4.5). While steps are small most of it is lent back: the
+architecture plugin declares its activations again at smaller step sizes (the decode rows rounded up
+to a power of two, at least 256, then each level 4x the one below, up to the step budget), each packed
+into the bottom of the arena. While recent steps fit a smaller size, the top of the arena holds expert
+weights; the first larger step takes it back before it runs (an address change, not a copy). Startup
+prints what each size lends (`activation arena: lends ...`). A plugin opts in with
+`RadArchProbe::shape_probe_ok`; one that does not keeps its whole arena.
 
 Related flags:
 
 ```sh
---gpu-headroom-mib 96      # VRAM left unclaimed on every card
---kv-cache-dtype fp8       # halve what a token of context costs (a real quantisation)
---host-pool-mib 8192       # pinned host tier for weights
---embedding-placement vram  # keep the token embedding on the card (below)
---ngram-placement ram       # an n-gram table in RAM instead of read from disk (below)
+--gpu-headroom-mib 96         # VRAM left unclaimed on every card
+--kv-cache-dtype fp8          # halve what a token of context costs (a real quantisation)
+--host-pool-mib 8192          # pinned host tier for weights
+--embedding-placement vram    # keep the token embedding on the card (below)
+--ngram-placement ram         # an n-gram table in RAM instead of read from disk (below)
 --vision-tower-placement ram  # the encoder towers in host memory, their VRAM to the KV cache (below)
---weights-disk-tier       # stream what fits neither from the container; needs O_DIRECT
+--weights-disk-tier           # stream what fits neither from the container; needs O_DIRECT
 ```
 
-**Two lookup tables have a placement of their own**, because a step reads only M of their rows and
-never the whole table, so a tier below the card serves them at little or no cost:
+**Lookup tables.** A step reads only M rows of a lookup table, so a tier below the card serves it
+cheaply. Two have their own placement:
 
 | | `vram` | `ram` | `disk` |
 |---|---|---|---|
 | `--embedding-placement` | on the card, with the other weights | pinned host memory of its own, read over the link in place (the default) | refused |
 | `--ngram-placement` | on the card, every card holding all of it | a copy in RAM made at load, read by the card over the link | read from the container through a row cache |
 
-The embedding defaults to `ram`; the n-gram table defaults to `auto`, the fastest tier that has
-room once every other weight is placed. Startup prints what each resolved to and why. A tier the
-flag names that cannot be honoured stops the server with the reason.
+The n-gram table defaults to `auto`, the fastest tier with room once every other weight is placed.
+Startup prints what each table resolved to and why; a named tier that cannot be honoured stops the
+server with the reason.
 
-**The token embedding** is the largest model-level weight a dense model has -- 248320 x 5120 in bf16
-is 1.18 GiB a card at `--tp 2`. By default (`ram`) it is pinned in host memory of its own, every
-rank its own shard, on top of `--host-pool-mib` -- the experts' pool keeps all of that -- and the
-lookup reads a step's rows over the link in place, so the table costs no VRAM and the KV pool and
-the experts get its share. The table is found by what reads it: a model-level weight only
-`embed_lookup` reads. A head tied to it is read by a GEMM too and is never moved, since it would
-stream whole every step, so such a model keeps it on the card; so does a host that cannot pin it
-(available memory and memory cgroups, after the pools, with 4 GiB to spare). Startup says which
-and why. Naming `ram` turns either case into a refusal; `vram` keeps the table on the card.
-`disk` is refused: the lookup writes activations the card reads, and a host kernel reading the
-container cannot write them.
+*The token embedding* is a dense model's largest model-level weight: 248320 x 5120 in bf16 is 1.18
+GiB a card at `--tp 2`. Under `ram` each rank pins its own shard in host memory on top of
+`--host-pool-mib`, and the lookup reads a step's rows over the link, so the table costs no VRAM. The
+table is the model-level weight only `embed_lookup` reads. A model whose head is tied to it keeps it
+on the card (the head's GEMM would stream it whole every step), and so does a host that cannot pin
+it (available memory and memory cgroups, after the pools, with 4 GiB to spare); startup says which.
+An explicit `ram` turns either case into a refusal. `disk` is refused: the lookup writes activations
+the card reads, which a host kernel reading the container cannot do.
 
 ```sh
 radiance --model m.rad --tp 2 --embedding-placement vram   # the table on the cards
 ```
 
-**The encoder towers** -- a vision tower, and an audio encoder where a model has one -- are read
-once an image, a clip or a recording, never on a text step. On the card (`vram`, the default) they
-are weights like any other and the KV pool is carved from what is left: Qwen3.8-27B's vision tower
-is 0.86 GiB a card, about 24,000 tokens of fp8 context. `--vision-tower-placement ram` pins them in
-host memory of their own, every rank a whole tower, on top of `--host-pool-mib`, and their kernels
-read the weights over the link in place: that VRAM goes to the KV cache, and every image costs one
-read of the tower over the link (about 55 ms for 0.86 GiB on PCIe 4.0 x16). Text-only requests do
-not touch it. A tower is every weight the model's architecture declares read once per request.
-`ram` is refused, naming the reason, where the model has no tower, where `--mm-max-patches 0`
-declared none, or where the host cannot pin it.
+*The encoder towers* (vision, and audio where a model has one) are read once per image, clip or
+recording, never on a text step. Under `vram`, the default, they are ordinary weights: Qwen3.8-27B's
+vision tower is 0.86 GiB a card, about 24,000 tokens of fp8 context. `--vision-tower-placement ram`
+pins a whole tower per rank in host memory, on top of `--host-pool-mib`, and its kernels read the
+weights over the link. That VRAM goes to the KV cache, and each image costs one read of the tower
+over the link (about 55 ms for 0.86 GiB on PCIe 4.0 x16). A tower is every weight the architecture
+declares read once per request. `ram` is refused, with the reason, where the model has no tower,
+where `--mm-max-patches 0` declared none, or where the host cannot pin it.
 
 ```sh
 radiance --model qwen3.8-27b-fp8.rad --tp 1 --vision-tower-placement ram
 ```
 
-**An n-gram table** (Qwen3.8-Flash-Next's is 47.7 GiB) is read a few rows a token, which is why it
-can live off the card at all. `disk` reads its rows from the container through a row cache and
-direct reads on the host; about half of a step's rows are first-seen, so steps wait on the drive.
-`ram` copies the whole table into host memory at load -- 12 to 40 s more startup, depending on the
-page cache -- and every gather reads memory: the card's own gather kernel reads a pinned copy over
-the link, so a step has no host work in it at all. `vram` puts it on the card, every card holding
-all of it, which needs a card that large. `ram` needs the table's size in memory after the pinned
-host pools and the prefix cache's host tier, with 4 GiB to spare, and room under every memory cgroup
-the process sits in; it refuses the start short of either and names which. `auto` takes the first
-of `vram`, `ram` and `disk` that holds the table. Without a device kernel for the gather (a build
-with no libr4d), the table is read on the host: `vram` is refused, and `ram` is a copy in locked
-huge pages, which also needs a memlock limit that large (`--ulimit memlock=-1` in Docker,
-`LimitMEMLOCK=infinity` under systemd).
+*An n-gram table* (Qwen3.8-Flash-Next's is 47.7 GiB) is read a few rows a token. `disk` reads rows
+from the container through a row cache with direct reads on the host; about half of a step's rows
+are first-seen, so steps wait on the drive. `ram` copies the table into host memory at load (12 to
+40 s more startup, depending on the page cache) and the card's gather kernel reads the pinned copy,
+so a step has no host work. `vram` puts all of it on every card. `ram` needs the table's size free
+after the pinned host pools and the prefix cache's host tier, with 4 GiB to spare, under every
+memory cgroup the process sits in, and refuses the start otherwise. `auto` takes the first of `vram`,
+`ram` and `disk` that holds the table. Without a device kernel for the gather (no libr4d) the table is
+read on the host: `vram` is refused, and `ram` is a copy in locked huge pages, which also needs a
+memlock limit that large (`--ulimit memlock=-1` in Docker, `LimitMEMLOCK=infinity` under systemd).
 
-**A model larger than the card and the host pool together still serves with
-`--weights-disk-tier`** -- and every step is then paced by the drive, which is the trade the flag
-names. A routed expert that fits neither VRAM nor the pinned pool lives in the container and
-nowhere else; before each routed layer's first expert op, on every pass, the engine reads all of
-that layer's on-disk experts into one of two VRAM buffers (a router's picks are not known on the
-host, and a prefill chunk routes to nearly all of them anyway). The two buffers come out of the
-weight budget -- the plan report's `file buffers` line -- and the reads go through four 32 MiB
-pinned windows out of `--host-pool-mib` as long runs of the container, skipping resident experts.
-What it is for: serving a checkpoint as it ships to calibrate or compare against, not a
-production deployment. The bf16 Qwen3.8-Flash-Next (335 GiB) runs at two cards this way at about
-28 s a step, and that step costs the same at one token as at 32K, so give it large prefill steps:
+**`--weights-disk-tier`** serves a model larger than the card and the host pool together, with every
+step paced by the drive. A routed expert that fits neither lives only in the container. Before each
+routed layer's first expert op, on every pass, the engine reads all that layer's on-disk experts into
+one of two VRAM buffers (a router's picks are not known on the host, and a prefill chunk routes to
+nearly all of them). The buffers come out of the weight budget (the plan's `file buffers` line), and
+the reads go through four 32 MiB pinned windows out of `--host-pool-mib`, as long runs that skip
+resident experts. It is meant for running a checkpoint as shipped, to calibrate or compare against.
+The bf16 Qwen3.8-Flash-Next (335 GiB) runs on two cards at about 28 s a step, the same at one token as
+at 32K, so use large prefill steps:
 
 ```sh
-rad-convert ~/models/Qwen/Qwen3.8-Flash-Next -o flashnext-bf16.rad --max-ctx 4096   # no recipe: bf16
+rad-convert /srv/models/Qwen/Qwen3.8-Flash-Next -o flashnext-bf16.rad --max-ctx 4096   # no recipe: bf16
 radiance --model flashnext-bf16.rad --tp 2 --placement expert_tiered --weights-disk-tier \
     --host-pool-mib 12288 --deterministic --gpu-headroom-mib 768 \
     --max-num-seqs 32 --max-num-batched-tokens 32768 --num-speculative-tokens 0
 ```
 
-A production server leaves the flag off, so a budget that does not fit is refused at startup
-rather than served from the drive.
+Without the flag, a budget that does not fit is refused at startup.
 
-**The KV pool is elastic on every run and there is no flag for it.** It holds the blocks it is
-actually using plus a buffer it derives — one prefill chunk, or the largest shortfall the
-admission path has met in the last few seconds, whichever is larger — and the expert plane grows
-into whatever it releases. A pool that held every block it was carved for whether or not a token
-was in it would, on a model whose experts do not fit, stream weight over the link for the whole
-run to pay for cache nobody is using.
+**The KV pool is always elastic.** It holds the blocks in use plus a buffer (one prefill chunk, or
+the largest shortfall admission met in the last few seconds, whichever is larger), and the expert
+plane grows into what it releases, so a model whose experts do not fit never streams weights to pay
+for unused cache.
 
-What it leans on is `--gpu-headroom-mib`. That reserve is what the card keeps for allocations
-this engine does not make — chief among them a kernel's code object, which HIP loads on the
-kernel's *first launch*, not at startup. A card with too little of it left collides with the
-first kernel that has never run: a draft head's, a sampler chain's, whatever the early requests
-did not reach. It fails its load and faults inside the HIP runtime, which arrives as a segfault in
-a kernel that is correct, on a server that had been serving fine.
+**Headroom.** `--gpu-headroom-mib` is kept for allocations the engine does not make, chiefly a
+kernel's code object, which HIP loads at the kernel's first launch. With too little left, the first
+kernel that has never run (a draft head's, a sampler chain's) fails its load and faults inside the
+HIP runtime: a segfault in a correct kernel on a server that had been serving.
 
-Startup checks what is left once everything is allocated (`card N settled at ... free`). Memory
-taken after the budget read the card — another process on it, such as a desktop, or a driver
-allocation — comes out of the headroom, and the line says how much. It warns only when the room
-left for first launches is under the 96 MiB the engine allows for its own, and then names the
-`--gpu-headroom-mib` value that clears it: what is left rises one for one with the flag, so that
-value is a fixed point. A larger headroom that lost part of itself to another process is reported
-on the INFO line and not warned.
+Once everything is allocated, startup logs `card N settled at ... free`. Memory taken after the budget
+read the card (another process such as a desktop, or a driver allocation) comes out of the headroom,
+and the line says how much. It warns when the room left for first launches is under the 96 MiB the
+engine allows for its own, naming the `--gpu-headroom-mib` value that clears it (what is left rises
+one for one with the flag); a larger headroom that lost part of itself is reported at INFO.
 
-What the engine itself allocates after the card is read is charged before the split, so it never
-comes out of the headroom: the step staging, the KV tiers' copy staging, and its hardware queues.
-A queue costs more than its ring — the driver backs each one with VRAM of its own, 33 MiB on an
-R9700 — so startup measures one and the receipt's `hardware queues` line shows how many a card
-holds at that price.
+What the engine allocates after reading the card is charged before the split, not to the headroom:
+the step staging, the KV tiers' copy staging and the hardware queues. The driver backs each queue
+with VRAM beyond its ring (33 MiB on an R9700), so startup measures one and the receipt's `hardware
+queues` line shows the count and price.
 
 ### 4.4 Long context
 
@@ -704,42 +728,37 @@ holds at that price.
 radiance --model m.rad --max-model-len 200000 --kv-cache-dtype fp8 --max-num-seqs 8
 ```
 
-`--max-model-len` does not reserve anything per request — it sets the worst case the pool is sized
-against. `0` takes the model's training context.
+`--max-model-len` reserves nothing per request; it is the worst case the pool is sized against. `0`
+takes the model's training context.
 
-`--kv-cache-dtype fp8` is an E4M3 cache with per-(sequence, head) descales. It halves what a token
-of context costs, which at a production context is most of the pool. It is a real quantisation and
-the model computes a slightly different function with it, so it is stated rather than inferred.
-Every architecture serves both widths, and the flag sets every attention cache of the deployment —
-a drafter's (DSpark, DFlash2) as well as the trunk's. The delta-net state and the QSA indexer's
-key tail are recurrent state rather than an attention cache and keep their own widths.
+`--kv-cache-dtype fp8` is an E4M3 cache with per-(sequence, head) descales. It halves what a token of
+context costs, which at a production context is most of the pool. It is a real quantisation that
+changes the output slightly, so it is only ever set explicitly. Every architecture serves both
+widths, and the flag sets every attention cache of the deployment, a drafter's (DSpark, DFlash2)
+included. The delta-net state and the QSA indexer's key tail are recurrent state and keep their own
+widths.
 
-**Many sequences against a long context.** `--max-num-seqs` runs to 32 on every model here, and
-what it costs is not context — a sequence holds only the blocks its tokens occupy — but what exists
-per sequence whether it is used or not:
+**Many sequences.** Every model here serves `--max-num-seqs` up to 32. A sequence holds only the
+blocks its tokens occupy, but two costs exist per sequence regardless:
 
-- **Recurrent state.** On a hybrid model every sequence owns its delta-net state, and with
-  speculation two copies of it. Qwen3.8-Flash-Next keeps 54 MiB a copy on each card, so 32
-  sequences take 3.4 GiB of the cache share before a single token is cached. The 27B in bf16,
-  with no experts to give way, then holds about 117K tokens of attention cache, less than one 200K
-  request, and startup warns that a longer one would be refused. The 27B in FP8 holds 2.8
-  full-length sessions at 32, the 35B-A3B ten.
-- **Block tables.** The step batch's tables are carved for every sequence at the full context.
-  They are charged to the VRAM budget (`step staging` in the startup receipt), so they come out of
-  the cache share and not out of `--gpu-headroom-mib`.
+- **Recurrent state.** On a hybrid model every sequence owns its delta-net state, two copies with
+  speculation. Qwen3.8-Flash-Next keeps 54 MiB a copy on each card, so 32 sequences take 3.4 GiB of
+  the cache share. The 27B in bf16, with no experts to give way, then holds about 117K tokens of
+  attention cache, less than one 200K request, and startup warns that a longer one would be refused.
+  The 27B in FP8 holds 2.8 full-length sessions at 32, the 35B-A3B ten.
+- **Block tables.** The step batch's tables are carved for every sequence at the full context and
+  charged to the VRAM budget (`step staging` in the receipt), so they come out of the cache share.
 
-The startup line `the pool backs N% of the worst case ... M full-length sessions` counts only the
-part of the pool that holds context, so M is the number to compare with the sessions you expect
-to keep live. With `--tp-wire wht6`, a decode step above the row count startup names is
-all-reduced lossily like a prefill chunk, which a busy step reaches: at 8 sequences and depth 3,
-Flash-Next's decode steps are already over it.
+The line `kv: the pool backs N% of the worst case ... M full-length sessions` counts only the part of
+the pool that holds context; compare M with the sessions you expect to keep live. With `--tp-wire
+wht6`, a decode step above the row count startup names is all-reduced lossily like a prefill chunk;
+at 8 sequences and depth 3, Flash-Next's decode steps are above it.
 
-### 4.5 Prefill speed: the chunk
+### 4.5 Prefill chunk size
 
-A long prompt is prefilled in chunks, and `--max-num-batched-tokens` is how big one is. It is the
-single biggest lever on time-to-first-token on a mixture-of-experts model, because a chunk sweeps
-the whole expert plane once however many tokens are in it — so four times the chunk is a quarter
-of the sweeps.
+A long prompt is prefilled in chunks of at most `--max-num-batched-tokens`. On a mixture-of-experts
+model this is the largest lever on time to first token: a chunk sweeps the whole expert plane once
+however many tokens it carries.
 
 ```sh
 radiance --model m.rad --max-num-batched-tokens 2048
@@ -749,92 +768,141 @@ On a 48-layer MoE at 200K context on two cards, prompts of 8K and 24K tokens:
 
 | chunk asked for | 512 | 1024 | **2048** | 4096 |
 |---|---|---|---|---|
-| chunk actually run | 512 | 1024 | **2048** | 2048 |
+| chunk run | 512 | 1024 | **2048** | 2048 |
 | prefill | 1750 tok/s | 2200 | **2706** | 2620 |
 
-At full context the same change is the difference between waiting and waiting a lot: a
-185,253-token prompt prefills in **91 s at a 2048 chunk against 138 s at 512**.
+A 185,253-token prompt prefills in 91 s at a 2048 chunk and 138 s at 512.
 
-**The 4096 column is the trap, and the engine warns about it.** On a hybrid model the chunk is
-clamped to `--checkpoint-interval` (2048 by default) *before* the token budget, so asking for 4096
-runs 2048 chunks and pays for 4096 anyway: the activation arena grows with the budget and is
-charged to the VRAM budget *before* it is split between weights and KV, so the expert plane loses
-residency for a chunk it never got. Startup prints which of the two bound it:
+**The checkpoint interval caps the chunk.** On a hybrid model a prompt's chunk is clamped to
+`--checkpoint-interval` (default 2048) before the token budget, so asking for 4096 runs 2048-token
+chunks with an activation arena sized for 4096, and the expert plane loses residency for a chunk it
+never gets (§4.3). Startup prints which bound applies:
 
 ```
 chunk geometry: quantum 64 (attn block ..., state chunk ...), checkpoint interval 2048,
 max_tok 4096 -> prefill chunks of at most 2048 (the checkpoint interval, not the budget)
 ```
 
-Read that line, and `RADIANCE_LOG_STEPS=1` prints the token count of every step if you want to see
-it per step.
+`RADIANCE_LOG_STEPS=1` prints the token count of every step. Raising both
+(`--max-num-batched-tokens 4096 --checkpoint-interval 4096`) runs 4096 chunks but gave 2610 tok/s
+against 2748, because the arena took another 239 resident experts (9219 to 8980). Where prefill is
+bound by the link carrying non-resident experts, a larger chunk stops paying once it costs residency.
 
-Raising both — `--max-num-batched-tokens 4096 --checkpoint-interval 4096`, which does run 4096
-chunks — does not help either: 2610 tok/s against 2748, because the arena takes
-another 239 resident experts (9219 to 8980) and the extra amortisation does not pay for them. On
-a model whose prefill is bound by the link carrying non-resident experts, the chunk stops winning
-as soon as it starts costing residency.
+A longer chunk holds the device longer per step, but the prefill a decode step waits behind finishes
+sooner: four decoders with a long prompt beside them finished in 29.5 s at a 2048 chunk and 31.9 s at
+512.
 
-**It does not cost the requests already running.** A longer chunk holds the device longer per
-step, so a decode step queued behind one waits longer — but the prefill it is queued behind
-finishes sooner, and that is the larger term. Four decoders with a long prompt landing beside
-them finished in 29.5 s at a 2048 chunk against 31.9 s at 512.
+**Decoders beside a chunk: `--prefill-interleave N`.** A step that carries a chunk takes the
+chunk's time, and every sequence decoding beside it waits that long for its next token. With
+`--prefill-interleave 2`, after a step that carried a chunk while other sequences were decoding,
+the next two steps carry decode rows only and admit nothing, then the next chunk is scheduled. The prompt's time to first token grows by those steps and the
+decoders keep their cadence. A lone prefill is not held, nor is the step after a prompt's last
+chunk. `0` (the default) schedules as before. `/stats` counts the decode-only steps the hold
+inserted as `steps_held`, `/metrics` as `radiance:engine_steps_held_total`.
 
-**Nor does a long prefill lock out the work behind it** (`--busy-prefill-chunk`, default `auto`).
-A chunk used to take every token the step had left, so for the whole of a long prompt's prefill —
-a minute or more at 256K — a decode row behind it in the batch got no rows and a request that
-arrived was not even admitted: a mostly-cached turn that needed a few hundred tokens waited for
-somebody else's prompt to finish. Now, when other work is pending in a step, the chunk leaves it
-room: one row plus the draft window for every decode row behind it, and a share of the budget
-(an eighth, at least one quantum) for each prefill behind it and for the next request waiting to
-start. It never drops under the smallest step the prefill stager overlaps (1025 tokens by
-default), because under that every routed layer reads its pooled experts synchronously and the
-prefill slows far more than the shared step saves; and where holding a chunk back for a waiting
-request or another prefill would leave a short remainder before the checkpoint boundary, the
-interval is split into two staged halves instead. Decode rows alone only take their few tokens: the
-chunk ends a quantum short of the boundary and the next step finishes it, the same pair of steps a
-prefill already runs when decode rows are ahead of it. A prompt with nothing beside it is planned exactly as before. `off` restores the old
-behaviour; `--busy-prefill-chunk N` holds a shared chunk to N tokens (the startup line warns when
-N is under the stager's step). `radiance:engine_prefill_chunks_capped_total` counts the chunks
-held back.
+**A prefill alone in its step can carry several intervals** (`--prefill-span N`, default 1). A
+chunk ends on every checkpoint interval, so a prompt is otherwise prefilled one interval a step.
+With
 
-**And check it did not cost you the prefix cache.** The arena it grows is charged before the
-split (§4.3), so the KV pool shrinks a little — here 516,864 → 499,920 pool tokens, 3.3% — and
-§4.3's cliff is sharp enough that 3% is worth confirming rather than assuming. On this shape it
-costs nothing: two ~180K sessions, first turns back to back, then the first session's second turn.
+```sh
+radiance --model m.rad --max-num-batched-tokens 4096 --prefill-span 2
+```
 
-| chunk | session A turn 1 | session B turn 1 | A turn 2 | cached | evictions |
-|---|---|---|---|---|---|
-| 512 | 137.7 s | 130.0 s | 1.42 s | 178,176 of 179,585 | 0 |
-| 2048 | **90.6 s** | **93.2 s** | **0.97 s** | 178,176 of 179,585 | 0 |
+a prefill that is alone in its step carries up to N intervals a step, from the prompt's second
+interval on (the first is never spanned). Every other step -- one with decode rows, another prefill,
+or a request waiting to be admitted -- is planned at the shared budget, `--max-num-batched-tokens`
+less the extra intervals (here 2048), as without the span, `--busy-prefill-chunk` included. The
+checkpoints at a span's end and at a prompt's tail are written where a span of 1 writes them, so a
+follow-up turn resumes where it did. Startup states both budgets:
 
-Identical hit, no evictions, `kv_util` 0.70 → 0.73. Turn one is 34% faster and turn two stays
-where it was. Do this on your own shape before you keep the change: `prefix_hit_rate` and
-`prefix_evictions` on `/stats` are the two numbers, and the failure looks like turn two taking
-as long as turn one.
+```
+chunk geometry: a prefill alone in its step spans up to 2 intervals from its second interval on;
+every other step is planned at 2048 tokens
+```
 
-**What it does cost is decode, and it is small.** The 239 resident experts the arena takes have to
-come from somewhere, and steady-state decode is where. Decode step time from `scripts/cstep2.sh`,
-which divides by the decode step counter rather than by wall clock, two passes each, generations
-long enough that no sequence retires inside the window:
+Flash-Next (`qwen4exp_fp8`) runs a spanned step in pieces of one MoE pass (2048 rows): every
+connection read takes a pass, and the indexer's score plane stays a pass tall and is scored in
+windows. Above two ranks the step is also pipelined: everything row-local runs a pass at a time and
+every all-reduce goes out on the second lane, beside the other piece's work (at TP4 a chunk's 97
+tiered-int8 all-reduces are about a quarter of its time). Each piece then computes what a 2048-token
+chunk computes, so at the default `--checkpoint-interval 2048` greedy output is that of
+`--max-num-batched-tokens 2048`. At two ranks the gated residual's fused write takes every
+all-reduce, so a spanned step runs as one wider step; there, at one rank, and on every other
+architecture, a spanned step is a wider chunk and may differ from 2048 chunks at tie level.
 
-| chunk | one stream | eight streams |
+On Flash-Next (`fp8-iq4r-moe`, R9700 at 215 W, fp8 KV, MTP 3, `--tp-wire wht6`), the change in time
+to the first token of one prompt, `--max-num-batched-tokens 4096 --prefill-span 2` against
+`--max-num-batched-tokens 2048`:
+
+| prompt | TP4, all_vram | TP2, expert_tiered, 12 GiB host pool |
 |---|---|---|
-| 512 | 22.35 / 22.29 ms/step | 39.52 / 40.52 ms/step |
-| 2048 | 22.42 / 22.48 ms/step | 39.52 / 40.73 ms/step |
+| 2K | +0.4 % | -6.1 % |
+| 8K | +4.1 % | -1.0 % |
+| 18K | +8.0 % | +2.3 % |
+| 64K | +9.3 % | +9.0 % |
+| 250K | +8.8 % | +49.1 % |
 
-**+0.6% on a single-stream decode step**; at eight streams the difference is 0.11 ms, below what
-the harness resolves. Against a prefill that is 55% faster and a first turn that goes from 138 s
-to 91 s, that is the right side of the trade — but it is a real cost and it lands on every turn,
-so measure it on your own shape rather than taking the sign on faith.
+A positive figure is a shorter time. The gain depends on the box and the container: on another
+2x R9700 at 210 W serving the w4nl64 Flash-Next container at TP2 (`expert_tiered`, 12 GiB host
+pool), the same span took 2.61 s against 2.56 s to the first token of an 18K-token prompt and
+10.72 s against 10.55 s at 75K, and `--max-num-batched-tokens 8192 --prefill-span 4` took 3.30 s
+and 10.82 s. Measure the prompts you serve before turning it on at two ranks.
 
-**Changing it changes the text.** A different chunk is a different batch shape, so the sums inside
-a prefill run in a different order, and at a tie that is a different token. A fixed prompt at a
-fixed seed gives one answer at 512 and a different one at 2048, and each is byte-identical across
-runs and server restarts at its own setting. Reproducibility holds *at a configuration*, which is what it claims; this flag is part of the
-configuration in the same way `--tp` and `--num-speculative-tokens` are. Pin it before you record
-anything you intend to compare against later.
+What it costs:
 
+- **The checkpoints inside a span are not written.** A later request that shares only part of a
+  prompt -- a long system prompt with a different question -- resumes up to one interval earlier.
+- **Activation memory.** The arena is sized for N-interval steps. On Flash-Next the largest buffer,
+  the score plane, and the connection reads' scratch stay a pass tall; at TP4 and 256K context the
+  KV pool goes from 12.42 GiB a card at a 2048 budget to 12.14 (11.53 for a 4096 budget without the
+  span).
+- **Decode steps.** The step's token, position, output and slot-map arrays are carved for the budget
+  and uploaded whole every step, so at 4096 a decode step uploads twice the bytes it does at 2048.
+- **Expert residency, where routed experts are in host memory** (`--placement expert_tiered`). The
+  span's extra rows are VRAM the expert slab does not get (320 MiB a card on Flash-Next at TP2).
+  Every step but a spanned one runs at an arena level of the shared size, which lends those rows to
+  the slab and keeps the prefill stager's ring right above its own buffers. A prefill there spans
+  only from eight intervals (16K tokens on), where the span starts to win. Startup says so:
+
+  ```
+  scheduler: --prefill-span: a prefill spans when it is 16384 tokens or longer -- routed experts
+  are read from host memory, and the arena a spanned step takes is room they lose for it
+  ```
+
+A model without an interval grid (no linear state, or window snapshots at a prompt's end, as on
+Gemma 4) spans nothing; there the flag only plans every step but a lone prefill at the shared
+budget, and startup warns.
+
+**Sharing a step** (`--busy-prefill-chunk`, default `auto`). When other work is pending, a prefill
+chunk leaves room for one row plus the draft window per decode row behind it, and a share of the
+budget (an eighth, at least one quantum) for each prefill behind it and for the next request waiting
+to start, so a long prompt (a minute or more at 256K) does not starve decode rows or admission. The
+chunk never drops under the smallest step the prefill stager overlaps (one more than the largest
+arena level, named on the startup line `prefill staging: ...`); below that every routed layer reads
+its pooled experts synchronously and the prefill slows far more than sharing saves. Where holding a
+chunk back would leave a short remainder before the checkpoint boundary, the interval is split into
+two staged halves instead. Decode rows alone take only their few tokens: the chunk ends a quantum
+short of the boundary and the next step finishes it. A prompt with nothing beside it is unaffected.
+`off` lets a chunk take the whole step; `N` holds a shared chunk to N tokens (startup warns when N is
+under the stager's step). `radiance:engine_prefill_chunks_capped_total` counts the chunks held back.
+
+**Check the prefix cache after changing the chunk.** The larger arena shrinks the KV pool (here
+516,864 to 499,920 pool tokens, 3.3%), and §4.3's cliff is sharp. With two ~180K sessions (first
+turns back to back, then the first session's second turn), a 512 chunk took 137.7 s, 130.0 s and
+1.42 s, and 2048 took 90.6 s, 93.2 s and 0.97 s; both cached 178,176 of 179,585 tokens with no
+evictions, and `kv_util` went from 0.70 to 0.73. Check your own shape with `prefix_hit_rate` and
+`prefix_evictions` on `/stats`; the failure looks like turn two taking as long as turn one.
+
+**The cost is decode.** The 239 experts the arena displaces slow steady-state decode. Measured
+with `scripts/cstep2.sh` (decode step time from the decode step counter, no sequence retiring inside
+the window), a 2048 chunk against 512 cost 0.6% of a single-stream decode step (22.3 to 22.4 ms) and
+nothing measurable at eight streams (about 40 ms).
+
+**Changing it changes the text.** A different chunk is a different batch shape, so the sums inside a
+prefill run in a different order, and at a tie that is a different token. Each setting is
+byte-identical across runs and restarts; reproducibility holds per configuration, and this flag is
+part of the configuration like `--tp` and `--num-speculative-tokens`. Pin it before recording
+anything you will compare against later.
 
 ### 4.6 Speculative decoding
 
@@ -846,154 +914,136 @@ radiance --model m.rad --num-speculative-tokens 0   # off
 radiance --model m.rad --num-speculative-tokens 3   # a stated depth
 ```
 
-There is **no `--draft-model`**. This engine loads its drafter from the container — merge one at
-conversion time with `rad-convert --draft-model DIR`, or use an MTP head that already ships inside
-the target checkpoint, which needs no flag at all. Passing `--draft-model` to the engine is an
-error that says so rather than being quietly ignored.
-
-When you measure speculation, **measure step time, not tokens per second.**
+The drafter comes from the container: merge one with `rad-convert --draft-model DIR`, or use an MTP
+head inside the target checkpoint, which needs no flag. `radiance --draft-model` is an error that
+says so. Measure speculation by step time, not tokens per second.
 
 A drafter with a sliding window over its own cache (DFlash2) keeps that cache outside the prefix
-cache, so a prefix hit leaves it with nothing to attend to for the cached part of the prompt, and
-it cannot draft until its window has slid past the hit. On the follow-up turn of a chat that is
-most of the reply. Such a hit is therefore ended one drafter window before the end of the prompt,
-at a checkpoint: the window is recomputed, which costs that much prefill, and the drafter drafts
-from the first token. The reply is the same either way. A hit whose nearest checkpoint below that
-point would give back more than two windows is kept whole. `radiance:draft_refills_total` counts
-the hits ended early and `radiance:draft_refill_tokens_total` the tokens they recomputed.
+cache, so after a prefix hit it cannot draft until its window has slid past the hit, which on a
+chat's follow-up turn is most of the reply. Such a hit is therefore ended one drafter window before
+the end of the prompt, at a checkpoint, and the window is recomputed; the reply is the same. A hit
+whose nearest checkpoint below that point would give back more than two windows is kept whole.
+`radiance:draft_refills_total` counts the hits ended early and `radiance:draft_refill_tokens_total`
+the tokens recomputed.
 
-**One depth for every request is a compromise; `--draft-window adaptive` lets the text decide.**
-Acceptance depends on the text: code and JSON keep accepting deep into the window, prose and
-summaries fall off after a position or two. With the adaptive window, `--num-speculative-tokens` is
-the ceiling and the engine keeps a smoothed acceptance per draft position for every sequence:
+**Adaptive window.** Code and JSON keep accepting deep into the window; prose falls off after a
+position or two. With `--draft-window adaptive`, `--num-speculative-tokens` is the ceiling and the
+engine keeps a smoothed acceptance per draft position for every sequence:
 
 ```sh
 radiance --model m.rad --num-speculative-tokens 6 --draft-window adaptive
 ```
 
-A serial draft head runs as many rounds as the deepest window in the step, so the depth is chosen
-for the step, not for one sequence: each step's head depth is the one that maximises the tokens all
-its sequences are expected to emit over what such a step costs. The cost is measured as the server
-runs — the time of every decode step, by its depth and by how many sequences it carried — so there
-is nothing to enter; a depth not yet measured is priced from the nearest one that was. Under that
-depth each sequence stops at the first draft that would be emitted — it and every draft before it
-accepted — less than one time in ten, so a prose reply beside a code reply does not pay verify rows
-for drafts nobody takes. The depth moves only after eight steps and for a two-percent gain, because
-every new window is a new pass shape and a new recording. A new sequence starts from what the
-sequences before it finished on, each counted once.
+A serial draft head runs as many rounds as the deepest window in the step, so the depth is chosen per
+step: the one that maximises the tokens its sequences are expected to emit over the measured cost of
+such a step (every decode step's time by depth and sequence count; an unmeasured depth is priced from
+the nearest measured one). Under that depth each sequence stops at the first draft whose chance of
+being emitted is under one in ten. The depth moves only after eight steps and for a 2% gain, since
+each new window is a new pass shape and a new recording. A new sequence starts from what earlier
+sequences finished on.
 
-The adaptive window is the serial draft head's policy. With a block drafter, with prompt lookup
-alone, or with speculation off the window stays fixed, and the server says so at startup. Prompt
-lookup proposals made when the head declines are counted in the acceptance metrics but do not move
-the head's window. At temperature 0 the text is that of a fixed depth wherever fixed depths agree
-with each other; above 0 it is distribution-exact. `radiance:draft_depth_adaptive` and
-`radiance:draft_verify_depth_total` (§6.3) show where the windows stand. The default is `fixed`.
+The adaptive window needs a serial draft head; with a block drafter, prompt lookup alone, or
+speculation off, the window stays fixed and startup says so. Prompt-lookup proposals made when the
+head declines count in the acceptance metrics but do not move the window. At temperature 0 the text
+is that of a fixed depth wherever fixed depths agree; above 0 it is distribution-exact.
+`radiance:draft_depth_adaptive` and `radiance:draft_verify_depth_total` (§6.3) show the windows.
 
-### 4.7 Two cards
+### 4.7 Multiple cards
 
 ```sh
 radiance --model m.rad --tp 2
 radiance --model m.rad --tp 2 --tp-wire wht6 --tp-wire-min-kb 128
 ```
 
-`--tp-wire` chooses the cross-rank all-reduce payload. `exact` (default) is the bf16 all-reduce.
-`wht6` accepts a lossy wire: a Walsh-Hadamard-rotated 6-bit payload, 2.4× smaller over PCIe. The
-sum a rank receives is then not the sum it would have received and nothing downstream can tell,
-which is why it is a named flag and not a heuristic.
+`--tp-wire` chooses the all-reduce payload. `exact` (default) is bf16. `wht6` is lossy: a
+Walsh-Hadamard-rotated 6-bit payload, 2.4x smaller over PCIe. The sum a rank receives is then not
+the exact sum and nothing downstream can detect it, so it is an explicit flag. `--tp-wire-min-kb` is
+the size below which messages stay exact; 128 KiB keeps single-sequence decode exact and compresses
+prefill.
 
-`--tp-wire-min-kb` is the floor below which messages are still served exactly — 128 KiB leaves
-single-sequence decode exact and compresses prefill, which is where the win is.
+At three and four ranks `wht6` selects tiered int8 over a two-shot all-reduce, both hops quantised
+(at three ranks the shards are whole 32-element groups, one uneven where the message does not
+divide), with the same floor. Eight ranks have no lossy wire; `--tp 8 --tp-wire wht6` stops at
+startup naming the all-reduce it found no kernel for, and `--tp-wire exact`. The exact wire at three,
+four and eight ranks is one-shot up to 1 MiB a message and two-shot above it, which sends
+2·(ranks−1)/ranks of the message per rank instead of (ranks−1) times it, with the same bits.
 
-At three and four ranks `wht6` selects a different lossy wire with the same floor: tiered int8
-over a two-shot all-reduce, both hops quantised (at three the shards are whole 32-element groups,
-one group uneven where the message does not divide). Eight ranks have no lossy wire, and
-`--tp 8 --tp-wire wht6` stops at startup naming the all-reduce it found no kernel for, and
-`--tp-wire exact`. The exact wire at three, four and eight ranks is one-shot up to 1 MiB a message
-and two-shot above it, which sends 2·(ranks−1)/ranks of the message per rank instead of
-(ranks−1) times it; the two produce the same bits.
+On a model with a gated residual (Qwen3.8-Flash-Next) the all-reduce runs inside the residual's
+write, with the MoE gather in front of it. At two ranks the rotated forms of `ar_hc_write` and
+`ar_gather_hc_write` produce the same bytes as the unfused chain on either wire; there `wht6` gains
+5.6–6.3% of prefill at a 2048-token chunk (20K prompt 5556 to 5908 tok/s; a 23K extension at 81K
+depth 4998 to 5278) and 1.3% of the eight-stream decode step, and one-stream decode stays exact. At
+four ranks only the exact wire has a fused form, used for decode and verify steps of up to
+`--max-num-seqs` x (1 + `--num-speculative-tokens`) rows; prefill chunks and tiered-int8 messages run
+the unfused chain.
 
-On a model with a gated residual (Qwen3.8-Flash-Next) the all-reduce rides inside the residual's
-write, with the MoE gather in front of it. At two ranks that holds on either wire: the rotated
-forms of `ar_hc_write` and `ar_gather_hc_write` produce the same bytes as the unfused chain on the
-same wire. There `wht6` is worth +5.6–6.3% of prefill at a 2048-token chunk (20K prompt 5556 →
-5908 tok/s; a 23K extension at 81K depth 4998 → 5278) and −1.3% of the eight-stream decode step;
-one-stream decode stays exact. At four ranks only the exact wire has a fused form, and it takes
-the decode and verify steps — up to `--max-num-seqs` × (1 + `--num-speculative-tokens`) rows. A
-prefill chunk, and a message that goes out on the tiered-int8 wire, runs the unfused chain, where
-the all-reduce's own size choice between one-shot and two-shot applies.
+**Cards without peer access.** The all-reduce kernels normally write into the other card's memory
+directly (P2P). At launch radiance asks the driver whether each pair of cards can, and logs the
+answer; the IOMMU setting, the PCIe topology and any switch between the cards decide. Where a pair
+cannot, the same kernels run with their exchange buffers in pinned host memory: each card writes its
+share to host RAM over its own link and reads the others' back. The startup line names the failed
+pairs, and the selection report names the `_host` rows that took the collectives. The results are the
+same bytes; a message crosses two links instead of one. On two R9700s on PCIe 4.0 that is within
+run-to-run noise for decode at one and four streams, and 2–10% on a 23.6K-token prefill, since there
+the peer link is no faster than the host link. Cards whose host link is narrower than their peer
+link pay more.
 
-**Cards that cannot reach each other's memory still serve.** The all-reduce kernels normally push
-into the other card's memory directly (peer to peer, P2P). At launch radiance asks the driver,
-for every pair of the cards it will use, whether that works, and logs the answer. Whether it does
-is decided by the platform: the IOMMU setting, the PCIe topology, and whether the cards sit behind
-a switch that allows peer traffic. When some pair cannot, the same kernels run with their
-exchange buffers in pinned host memory instead: every card writes its share to host RAM over its
-own link and reads the others' back the same way, and no card touches another card's VRAM. The
-startup line names the pairs that failed, and the selection report names the `_host` rows that
-took the collectives. The results are the same bytes either way; the cost is a message crossing
-two links instead of one. On two R9700s on PCIe 4.0 that cost is within run-to-run noise for
-decode, at one stream and at four, and 2–10% on a 23.6K-token prefill, because there the peer
-link is no faster than the host link. A machine whose cards reach host memory over a narrower
-link than they reach each other pays more.
+`--p2p` overrides the driver. `off` takes the host-memory path even where the driver reports peer
+access, for a board where peer traffic is broken or slow. `on` requires peer access and stops at
+startup, naming the pairs, if the driver refuses any. `auto`, the default, trusts the driver.
 
-`--p2p` overrides the driver's answer. `off` takes the host-memory path even where the driver
-reports peer access, for a board where peer traffic is broken or slow while the driver still says
-it works. `on` takes the peer-to-peer kernels and stops at startup, naming the pairs, if the driver
-refuses any of them, so a deployment measured on P2P never quietly serves on host memory. `auto`,
-the default, trusts the driver.
+### 4.8 Host tier for finished conversations
 
-### 4.8 Finished conversations: copied to host, VRAM given up on demand
+By default a finished conversation's KV blocks stay in VRAM, held by the prefix cache, until evicted
+under pressure; an evicted prefix is re-prefilled next turn.
 
-By default a finished conversation's KV blocks stay in VRAM, held by the prefix cache, until the
-cache evicts them under pressure — and an evicted prefix is re-prefilled from scratch next turn.
+With a host tier, a conversation is copied to host memory when its request finishes and keeps its
+VRAM copy. Its VRAM can then be given up at no cost, and is, as soon as something wants it (the
+expert slab's loan, or a request the pool cannot otherwise serve). A conversation that returns
+before that resumes from VRAM; one that returns after is restored from host memory and keeps its host
+copy, so its next turn copies only what that turn added. A full host tier drops its least recently
+used conversations. Nothing is written to a drive.
 
-With a host tier, a conversation is **copied** to host memory the moment its request finishes, and
-keeps its VRAM copy. From then on it is *clean*: its VRAM can be given up for nothing, and it is,
-as soon as something wants it — the expert slab's loan, or a request the pool cannot otherwise
-serve. A conversation that comes back before that resumes from VRAM; one that comes back after is
-restored from host memory and keeps its host copy, so its next turn copies only what that turn
-added. There is no idle threshold on the way out of VRAM.
-
-A full host tier drops its least recently used conversations to make room. Nothing is written to a
-drive: the prefix cache lives in VRAM and host memory only.
-
-**Every stored conversation expires.** One that no request has used for `--prefix-cache-ttl`
-seconds (an hour by default) is taken out of whichever tier holds it — its VRAM blocks go back to
-the pool, its host slot back to the arena, its snapshots back to the store. It is not moved
-anywhere first. A conversation in use stays: a hit or a new turn counts as a use, and a system
-prompt that several conversations share stays for as long as any of them is used.
+Every stored conversation expires: one unused for `--prefix-cache-ttl` seconds is removed from
+whichever tier holds it (VRAM blocks to the pool, host slot to the arena, snapshots to the store). A
+hit or a new turn counts as a use, and a system prompt shared by several conversations stays while
+any of them is used.
 
 ```sh
 radiance --model m.rad --prefix-cache-mib 8192 --prefix-cache-ttl 3600
 ```
 
-- `--prefix-cache-mib N` — **this is the switch.** Without a size, nothing is copied. It holds
-  attention blocks only; a hybrid model's linear-state snapshots are in host memory already, in the
-  `--checkpoint-slots` store. Size it for the conversations you expect to come back: one that does
-  not fit is prefilled again.
-- `--prefix-cache-ttl S` — seconds an unused conversation is kept (default 3600). `0` keeps
-  everything until the memory is wanted.
-- Recovering a 200K-token turn costs a copy over PCIe; recomputing it costs minutes.
+- `--prefix-cache-mib N` enables the host tier, up to N MiB. It holds attention blocks only; a hybrid
+  model's linear-state snapshots are already in host memory, in the `--checkpoint-slots` store. A
+  conversation larger than the tier keeps its start there and is prefilled again past it once VRAM
+  gives the rest up; the startup log warns when the tier holds less than one `--max-model-len`
+  conversation and says how many MiB would, and a `kv tiers: ... got no host copy` line appears when
+  it happens (`/sessions` `moved.held_back`).
+- `--prefix-cache-ttl S`: seconds an unused conversation is kept (default 3600); `0` keeps it until
+  the memory is wanted.
 
-On a hybrid model the recurrent state matters as much as the attention blocks — restoring the
-blocks alone leaves the session re-running every linear layer over its whole transcript, which
-every hit-rate counter reports as a hit. The snapshots never take VRAM: each is copied to host
-memory after the step that produced it and back before the step that resumes from it. `/sessions` shows what is stored, where, and whether the
-linear half is being served.
+Restoring a 200K-token turn costs a copy over PCIe; recomputing it costs minutes.
 
-### 4.9 What a request that leaves a field out gets
+On a hybrid model the recurrent state matters as much as the attention blocks: restoring the blocks
+alone re-runs every linear layer over the whole transcript, which hit-rate counters still report as a
+hit. Snapshots never take VRAM: each is copied to host memory after the step that produced it and
+back before the step that resumes from it. `/sessions` shows what is stored, where, and whether the
+linear half is served.
 
-Every default below applies only to a request that does not name the field. A request that names
-it wins. Without any of these flags, the server behaves exactly as it always has.
+### 4.9 Request defaults
 
-**Temperature, top-k, top-p, min-p.** First one that exists wins:
+Each default applies only to a request that does not name the field.
 
-1. `--temp` / `--top-k` / `--top-p` / `--min-p` on the command line
-2. `--generation-config PATH` — a `generation_config.json`
+**Temperature, top-k, top-p, min-p**, in order of precedence:
+
+1. `--temp` / `--top-k` / `--top-p` / `--min-p`, field by field
+2. `--generation-config PATH`, a `generation_config.json`
 3. `.generation.json` beside the container
 4. the container's own `generation.*` metadata
 5. the built-in defaults
 
+Of sources 2 to 4, the first that states anything is used whole.
+
 ```sh
 radiance --model m.rad --temp 0.7 --top-p 0.8 --top-k 20
 ```
@@ -1001,115 +1051,104 @@ radiance --model m.rad --temp 0.7 --top-p 0.8 --top-k 20
 **The rest of the sampler** has a flag per field, spelled like the request field:
 `--presence-penalty`, `--frequency-penalty`, `--repetition-penalty`, `--repeat-last-n`,
 `--typical-p`, `--dry-multiplier`, `--dry-base`, `--dry-allowed-length`, `--dry-penalty-last-n`,
-`--dry-sequence-breakers` (a JSON array), `--xtc-probability`, `--xtc-threshold`. They are checked
-against the same ranges a request is, at startup:
+`--dry-sequence-breakers` (a JSON array), `--xtc-probability`, `--xtc-threshold`, checked at startup
+against the ranges a request is held to:
 
 ```sh
 radiance --model m.rad --presence-penalty 1.5 --repetition-penalty 1.05
 ```
 
-**How much a request may generate.**
-
-- `--default-max-tokens N` sets `max_tokens` for a request that sends none. The default, `auto`,
-  is whatever the context leaves after the prompt, as in vLLM. Many clients send no `max_tokens`,
-  and a reasoning model can think for thousands of tokens before it answers: a small default ends
-  those answers inside the reasoning, with a `finish_reason: "length"` that chat clients do not
-  show.
-- `--max-tokens-cap N` is the most any request may generate. A larger `max_tokens` is cut to it
-  rather than refused, and the reply ends with `finish_reason: "length"`, the same as the context
-  bound (§5.8).
+**Generation length.** `--default-max-tokens N` sets `max_tokens` for a request that sends none. The
+default, `auto`, is what the context leaves after the prompt, as in vLLM: many clients send no
+`max_tokens`, and a small default ends a reasoning model's answer inside its reasoning, with a
+`finish_reason: "length"` chat clients do not show. `--max-tokens-cap N` is the most any request may
+generate; a larger `max_tokens` is cut to it, not refused, and the reply ends with `finish_reason:
+"length"` (§5.8).
 
 ```sh
 radiance --model m.rad --default-max-tokens auto --max-tokens-cap 32768
 ```
 
-**Chat template variables.** `--chat-template-kwargs` hands variables to the chat template on
-every chat request, the way a request's own `chat_template_kwargs` does:
+**Chat template variables.** `--chat-template-kwargs` passes variables to the chat template on every
+chat request, as a request's `chat_template_kwargs` does:
 
 ```sh
 radiance --model m.rad --chat-template-kwargs '{"enable_thinking": false}'
 radiance --model m.rad --chat-template-kwargs @template-vars.json
 ```
 
-- It takes a JSON object, or `@FILE` to read one. Give it more than once and a later key replaces
-  an earlier one.
+- It takes a JSON object, or `@FILE`. It may be repeated; a later key replaces an earlier one.
 - A key the request's own `chat_template_kwargs` names is the request's.
-- Thinking is one setting with three spellings. A request that says anything about thinking
-  (`enable_thinking`, at the top level or in `chat_template_kwargs`, or `reasoning_effort`)
-  replaces the server's `enable_thinking`. One that names a `reasoning_effort` replaces the
-  server's effort too.
-- `messages`, `tools`, `bos_token`, `eos_token` and `add_generation_prompt` are refused: the
-  server sets those itself.
-- At startup a one-message chat is rendered with the variables. A value the template refuses
-  stops startup with the template's own message, instead of failing every request.
-- `/tokenize` renders `messages` with the same variables, so the count it gives is the prompt
-  chat serves.
+- A request that says anything about thinking (`enable_thinking` at the top level or in
+  `chat_template_kwargs`, or `reasoning_effort`) replaces the server's `enable_thinking`; one that
+  names a `reasoning_effort` replaces the server's effort too.
+- `messages`, `tools`, `bos_token`, `eos_token` and `add_generation_prompt` are refused: the server
+  sets them.
+- At startup a one-message chat is rendered with the variables; a value the template refuses stops
+  startup with the template's message.
+- `/tokenize` renders `messages` with the same variables.
 
-**`--reasoning-effort` is worth knowing about.** It is the default for chat requests that do not
-set one, and the value goes to the model's chat template verbatim — so the legal set is the
-template's. Qwen3.8 takes `xhigh|medium|low` and **defaults to `xhigh`**, which on a short task can
-spend the entire token budget inside `` and return a turn with empty content and
-`finish_reason: "length"`. `"none"` turns thinking off. It cannot be combined with a
-`reasoning_effort` or `enable_thinking` key in `--chat-template-kwargs`. A value the template
-refuses is a warning at startup: requests that send their own effort still work.
+**`--reasoning-effort`** is the default for chat requests that set none, passed to the chat template
+verbatim, so the legal set is the template's. Qwen3.8 takes `xhigh|medium|low` and defaults to
+`xhigh`, which on a short task can spend the whole token budget inside `` and return empty
+content with `finish_reason: "length"`. `"none"` turns thinking off. It cannot be combined with a
+`reasoning_effort` or `enable_thinking` key in `--chat-template-kwargs`. A value the template refuses
+is a startup warning.
 
 ```sh
 radiance --model m.rad --reasoning-effort medium
 ```
 
-**The template's set is probed at startup** by rendering each of `low`, `medium`, `high`, `xhigh`
-and `max`, and startup names the ones it takes. `/server_info` publishes them as
-`capabilities.reasoning_efforts` (with `none` and `minimal`, which are the server's own; `null`
-when the template takes any word). A request outside the set gets a 400 with `param:
-"reasoning_effort"`, `code: "unsupported_value"` and the set in `error.supported`, rather than the
-template's traceback.
+At startup the template is probed with `low`, `medium`, `high`, `xhigh` and `max`, and the ones it
+takes are logged and published on `/server_info` as `capabilities.reasoning_efforts` (with the
+server's own `none` and `minimal`; `null` when the template takes any word). A request outside the set
+gets a 400 with `param: "reasoning_effort"`, `code: "unsupported_value"` and the set in
+`error.supported`.
 
-**`--reasoning-effort-map FROM=TO,...`** rewrites a request's effort before the template sees it,
-for a client that always sends a word of OpenAI's ladder. Qwen3.8 has no `high`, so:
+**`--reasoning-effort-map FROM=TO,...`** rewrites a request's effort before the template sees it, for
+clients that send OpenAI's levels. Qwen3.8 has no `high`, so:
 
 ```sh
 radiance --model m.rad --reasoning-effort-map high=xhigh
 ```
 
-It applies to both spellings (`reasoning_effort` and `chat_template_kwargs.reasoning_effort`), and
-before `none` and `minimal` are read, so `minimal=low` keeps thinking on. A `TO` the template
-refuses stops startup.
+It applies to `reasoning_effort` and `chat_template_kwargs.reasoning_effort`, before `none` and
+`minimal` are read, so `minimal=low` keeps thinking on. A `TO` the template refuses stops startup.
 
-**`--thinking-token-budget N`** caps the reasoning instead of its depth. At N tokens inside the
-reasoning block the block is closed, by masking the next position to its end token
-(``), and the answer follows. This makes a client's `max_tokens` buy an answer, where
-otherwise the reasoning could use all of it. It is the default for chat requests that send no
-`thinking_token_budget` of their own (§5.2). It needs a reasoning block that ends in a single
-token, as Qwen's and MiniCPM's do. On a model whose block does not, startup stops and says why.
+**`--thinking-token-budget N`** caps the reasoning length: at N tokens inside the reasoning block the
+next position is masked to the block's end token (``) and the answer follows. It is the
+default for chat requests that send no `thinking_token_budget` (§5.2), and needs a reasoning block
+that ends in a single token, as Qwen's and MiniCPM's do; otherwise startup stops and says why.
 
-**`--reasoning-format none`** leaves a reasoning block inline in `content` instead of returning it
-as `reasoning_content`, for a client that reads it there.
+**`--reasoning-format none`** leaves a reasoning block inline in `content` instead of returning it as
+`reasoning_content`.
 
-`/server_info` lists every effective default under `request_defaults` (§6.2), and startup prints
-one line naming each one the command line moved.
+`/server_info` lists every effective default under `request_defaults` (§6.2), and startup logs one
+line naming each default the command line changed.
 
 ### 4.10 Every flag
 
-`radiance --help` prints this table. Grouped here by what you are doing:
+`radiance --help` prints these. Grouped by purpose:
 
 **Model and plugins**
 
 | flag | |
 |---|---|
-| `--model PATH` | the `.rad` container, a checkpoint served as it stands (§3.4), or a Hugging Face repo id fetched before startup (§3.1) (**required**) |
+| `--model PATH` | required: the `.rad` container, a checkpoint served as it stands (§3.4), or a Hugging Face repo id fetched before startup (§3.1) |
 | `--download-dir DIR` | where a repo id is fetched to. Default `$XDG_CACHE_HOME/radiance/hf`, else `~/.cache/radiance/hf` |
-| `--radiance-home DIR` | where `kernels/` and `architectures/` live |
-| `--kernels LIST` | the kernel libraries to use, comma-separated, first wins; a library not named is not loaded. Default: every library found |
+| `--radiance-home DIRS` | where `kernels/`, `architectures/` and `quantizers/` live; homes separated by `:` are searched in order, the first winning (§1.5) |
+| `--kernels LIST` | the kernel libraries to use, separated by `,` or `:`, first wins; a library not named is not loaded. Default: every library found |
 
 **Batch shape**
 
 | flag | default | |
 |---|---|---|
 | `--max-num-batched-tokens N` | 8192 | largest token count one step may carry |
-| `--busy-prefill-chunk MODE` | auto | a prefill chunk's share of a step that has other work: `auto` leaves decode rows behind it and waiting requests their room (§4.5), `off` takes the whole step, `N` holds it to N tokens |
+| `--prefill-interleave N` | 0 (off) | decode-only steps after each prefill chunk while other sequences decode (§4.5), at most 64 |
+| `--busy-prefill-chunk MODE` | auto | a prefill chunk's share of a step that has other work: `auto` leaves decode rows and waiting requests their room (§4.5), `off` takes the whole step, `N` holds it to N tokens |
 | `--max-num-seqs N` | 256 | largest number of sequences one step may carry |
 | `--max-model-len N` | 0 | context bound; 0 takes the model's training context |
-| `--rope-scaling SPEC` | — | `yarn:FACTOR[:ORIG]`: static YaRN over the container's own rotary keys, no reconvert; `none` takes a checkpoint's YaRN off ([YARN.md](YARN.md)) |
+| `--rope-scaling SPEC` | the checkpoint's | `yarn:FACTOR[:ORIG]`: static YaRN over the container's own rotary keys, no reconvert; `none` takes a checkpoint's YaRN off ([YARN.md](YARN.md)) |
 
 **Memory**
 
@@ -1118,16 +1157,16 @@ one line naming each one the command line moved.
 | `--gpu-headroom-mib N` | 96 | VRAM left unclaimed on every card |
 | `--kv-cache-dtype T` | bf16 | `bf16` or `fp8` |
 | `--host-pool-mib N` | 0 | pinned host tier (weights) |
-| `--embedding-placement WHERE` | ram | `ram` or `vram`: the token embedding pinned in host memory beside `--host-pool-mib` and read in place, or on the card. See §4.3 |
-| `--ngram-placement WHERE` | auto | `auto`, `vram`, `ram` or `disk`: an n-gram table on the card, as a copy in RAM made at load and read by the card, or read from the container. See §4.3 |
-| `--vision-tower-placement WHERE` | vram | `vram` or `ram`: the encoder towers (vision, and audio where a model has one) on the card, or pinned in host memory beside `--host-pool-mib` and read in place once an image. See §4.3 |
+| `--embedding-placement WHERE` | ram | `ram` or `vram`: the token embedding pinned in host memory beside `--host-pool-mib` and read in place, or on the card (§4.3) |
+| `--ngram-placement WHERE` | auto | `auto`, `vram`, `ram` or `disk`: an n-gram table on the card, as a copy in RAM made at load and read by the card, or read from the container (§4.3) |
+| `--vision-tower-placement WHERE` | vram | `vram` or `ram`: the encoder towers (vision, and audio where a model has one) on the card, or pinned in host memory beside `--host-pool-mib` and read in place once an image (§4.3) |
 | `--weights-disk-tier` | off | read weights that fit neither VRAM nor the host pool from the container (O_DIRECT); routed experts a layer at a time |
 
-**Idle session tiers**
+**Host tier for finished conversations**
 
 | flag | default | |
 |---|---|---|
-| `--prefix-cache-mib N` | 0 (off) | copy finished conversations' KV to host memory |
+| `--prefix-cache-mib N` | 0 (off) | copy finished conversations' KV to host memory, up to N MiB (§4.8) |
 | `--prefix-cache-ttl S` | 3600 | seconds an unused conversation is kept, in VRAM or host memory; `0` never expires |
 
 **Placement and state**
@@ -1137,9 +1176,10 @@ one line naming each one the command line moved.
 | `--placement MODE` | auto | `all_vram`, `layer_offload`, `expert_tiered`, `auto` |
 | `--deterministic` | off | pin placement to the loader's plan, so the resident set cannot change under the heat engine |
 | `--checkpoint-interval N` | 2048 | linear-attention state checkpoint interval, in tokens |
-| `--checkpoint-slots N` | 8 | linear-state (hybrid) or sliding-window snapshots the server may hold at once, **in total**, not per sequence. They live in pinned host memory, not VRAM: one slot is a snapshot of every rank's shard (113 MB on Flash-Next at `--tp 2`; on Gemma 4 31B the 1024-token window of every sliding layer, 406 MiB at `--tp 2`), allocated at startup. A snapshot is copied off the card after the step that produced it and back before the step that resumes from it. A full store retires its least recently used snapshot |
+| `--prefill-span N` | 1 | checkpoint intervals one step may carry of a prefill alone in its step, from the prompt's second interval on; needs `--max-num-batched-tokens` of N intervals. Every other step is planned at the budget less the extra intervals, and the checkpoints inside a span are not written (§4.5) |
+| `--checkpoint-slots N` | 8 | linear-state (hybrid) or sliding-window snapshots the server may hold at once, in total, not per sequence. They live in pinned host memory, allocated at startup: one slot is a snapshot of every rank's shard (113 MB on Flash-Next at `--tp 2`; on Gemma 4 31B the 1024-token window of every sliding layer, 406 MiB at `--tp 2`). A full store retires its least recently used snapshot. A store the host memory cannot hold or pin stops the start, and a table placed in host memory leaves room for it; `0` serves with none, every prefix hit then prefilling from the start |
 | `--checkpoint-policy NAME` | geometric-backoff | also `tip-only`, `keep-all` |
-| `--no-prefix-cache` | — | disable prefix caching |
+| `--no-prefix-cache` | prefix cache on | disable prefix caching |
 
 **Parallel**
 
@@ -1147,7 +1187,7 @@ one line naming each one the command line moved.
 |---|---|---|
 | `--tp N` | 1 | tensor-parallel ranks |
 | `--tp-wire MODE` | exact | `exact` or `wht6`, the lossy wire (§4.7) |
-| `--tp-wire-min-kb N` | 128 | smallest all-reduce the lossy wire is used for |
+| `--tp-wire-min-kb N` | 128 | smallest all-reduce, in KiB, the lossy wire is used for |
 | `--p2p MODE` | auto | `auto` asks the driver, `on` requires peer access, `off` exchanges through host memory (§4.7) |
 
 **Speculation**
@@ -1156,7 +1196,7 @@ one line naming each one the command line moved.
 |---|---|---|
 | `--num-speculative-tokens N` | auto | speculative window; 0 disables. The ceiling under `--draft-window adaptive` |
 | `--draft-window MODE` | fixed | `fixed` drafts N every step; `adaptive` follows each sequence's acceptance and the measured step cost, serial draft heads only (§4.6) |
-| `--draft-model PATH` | — | **not implemented** — merge at convert time |
+| `--draft-model PATH` | | not implemented: merge the drafter at convert time |
 
 **Server**
 
@@ -1164,12 +1204,12 @@ one line naming each one the command line moved.
 |---|---|---|
 | `--host ADDR` | 0.0.0.0 | listen address |
 | `--port N` | 8000 | listen port |
-| `--api-key KEY` | — | require `Authorization: Bearer KEY` or `X-Api-Key: KEY` on every request but `/health`, `/v1/health`, `/ping` and the dashboard page (§6.6) |
-| `--served-model-name NAME` | container's name | the model id `/v1/models` lists, the metrics carry and a response names when its request named none. A request may name any model; the one loaded serves it |
+| `--api-key KEY` | none | require `Authorization: Bearer KEY` or `X-Api-Key: KEY` on every request but `/health`, `/v1/health`, `/ping` and the dashboard page (§6.6) |
+| `--served-model-name NAME` | container's name | the model id `/v1/models` lists, the metrics carry and a response names when its request named none. A request may name any model; the loaded one serves it |
 | `--mm-max-patches N` | auto | patches one vision-encoder pass carries, and so the largest image (a patch is 16x16 pixels). `auto` is 16384 when the container carries a vision tower; 0 serves text only and keeps the tower off the card |
-| `--override-chat-template PATH` | container's | a Jinja chat template file served in place of the one the container carries. The reply format (reasoning markers, tool calls) is derived from it too, unless the architecture plugin declares one. An unreadable or empty file stops startup |
+| `--override-chat-template PATH` | container's | a Jinja chat template file served in place of the container's. The reply format (reasoning markers, tool calls) is derived from it too, unless the architecture plugin declares one. An unreadable or empty file stops startup |
 | `--max-queued-requests N` | 8 × `--max-num-seqs` | requests admitted and unfinished at once; past it, 429 |
-| `--http-threads N` | one per core, at least 4 | HTTP workers kept while idle |
+| `--http-threads N` | one per hardware thread, at least 4 | HTTP workers kept while idle |
 | `--read-timeout S` | 30 | seconds a client may go silent while sending a request |
 | `--write-timeout S` | 600 | seconds one write to a client may block |
 | `--keep-alive-timeout S` | 5 | seconds an idle connection is held open between requests |
@@ -1177,43 +1217,43 @@ one line naming each one the command line moved.
 | `--retry-after S` | 1 | the `Retry-After` a 429 carries |
 | `--no-cors` | CORS on | send no CORS headers (§6.6) |
 
-**Request defaults and bounds** — what a request that leaves a field out gets (§4.9). A request
-that names the field wins.
+**Request defaults and bounds** (§4.9). A request that names the field wins.
 
 | flag | default | |
 |---|---|---|
-| `--generation-config PATH` | — | sampler defaults from a `generation_config.json` |
-| `--temp F`, `--top-k N`, `--top-p F`, `--min-p F` | from container | sampler defaults |
+| `--generation-config PATH` | none | sampler defaults from a `generation_config.json` |
+| `--temp F`, `--top-k N`, `--top-p F`, `--min-p F` | from the model | sampler defaults; unset, they come from the sources in §4.9 |
 | `--presence-penalty F`, `--frequency-penalty F` | 0 | [-2, 2] |
 | `--repetition-penalty F`, `--repeat-last-n N` | 1, 64 | > 0; ≥ -1 (-1 is all) |
 | `--typical-p F` | 1 | (0, 1] |
-| `--dry-multiplier F`, `--dry-base F`, `--dry-allowed-length N`, `--dry-penalty-last-n N` | 0, 1.75, 2, -1 | DRY; a multiplier of 0 is off |
+| `--dry-multiplier F`, `--dry-base F`, `--dry-allowed-length N`, `--dry-penalty-last-n N` | 0, 1.75, 2, -1 | DRY; a multiplier of 0 is off, the base ≥ 1, the allowed length ≥ 1, a last-n of -1 is the whole context |
 | `--dry-sequence-breakers JSON` | `["\n", ":", "\"", "*"]` | a JSON array of at most 16 strings |
 | `--xtc-probability F`, `--xtc-threshold F` | 0, 0.1 | [0, 1] |
 | `--default-max-tokens N` | `auto` | `max_tokens` for a request that sends none; `auto` is what the context leaves |
-| `--max-tokens-cap N` | none | the most any request may generate; a larger `max_tokens` is cut to it, not refused |
+| `--max-tokens-cap N` | 0 (none) | the most any request may generate; a larger `max_tokens` is cut to it, not refused |
 | `--max-n N` | the larger of 8 and `--max-num-seqs` | the largest `n` a request may ask for |
 | `--max-stop-strings N`, `--max-stop-bytes N` | 64, 4096 | how many stop strings a request may send, and how long each may be |
-| `--chat-template-kwargs JSON` | — | variables for the chat template on every chat request; a JSON object or `@FILE`, repeatable |
+| `--chat-template-kwargs JSON` | none | variables for the chat template on every chat request; a JSON object or `@FILE`, repeatable |
 | `--reasoning-effort S` | template's own | default `reasoning_effort` for chat |
-| `--reasoning-effort-map MAP` | — | `FROM=TO,...`: a request's `reasoning_effort` rewritten before the template sees it; `TO` is checked at startup |
+| `--reasoning-effort-map MAP` | none | `FROM=TO,...`: a request's `reasoning_effort` rewritten before the template sees it; `TO` is checked at startup. Repeatable |
 | `--thinking-token-budget N` | none | default `thinking_token_budget` for chat: the reasoning block is closed at N tokens |
 | `--reasoning-format MODE` | auto | `auto` returns reasoning as `reasoning_content`; `none` leaves it inline in `content` |
 
-**Media** — each replaces what the container's preprocessor configuration states. They do nothing
-for a model that takes no images or video.
+**Media.** Each replaces what the container's preprocessor configuration states, and does nothing for
+a model that takes no images or video. A Qwen-VL container that states none uses 2 frames a second,
+4 to 768 frames and 768 tokens a frame.
 
 | flag | default | |
 |---|---|---|
 | `--image-min-pixels N`, `--image-max-pixels N` | container's | the band an image is resized into; one encoder pass (`--mm-max-patches`) still bounds the top |
 | `--video-min-pixels N`, `--video-max-pixels N` | container's | the same for a video's sampled frames together |
-| `--video-fps F` | container's, else 2 | frames sampled per second of video |
-| `--video-min-frames N`, `--video-max-frames N` | container's, else 4 and 768 | the fewest and most frames sampled from a video |
-| `--video-max-frame-tokens N` | container's, else 768 | the most prompt tokens one frame may become; 0 is no cap. A token-budget processor (Gemma 4's) takes 70, 140, 280, 560 or 1120 |
+| `--video-fps F` | container's | frames sampled per second of video |
+| `--video-min-frames N`, `--video-max-frames N` | container's | the fewest and most frames sampled from a video |
+| `--video-max-frame-tokens N` | container's | the most prompt tokens one frame may become; 0 is no cap. A token-budget processor (Gemma 4's) takes 70, 140, 280, 560 or 1120 |
 | `--image-tokens N` | container's | a token-budget processor's image budget (Gemma 4's: 70, 140, 280, 560, 1120); a request's `image_tokens` overrides it. The pixel-band flags are refused on such a model |
 | `--max-source-pixels N` | 67108864 | the largest image or frame the decoder accepts, before any resize |
 
-**Quality measurement** — instead of serving; see [TOOLS.md](TOOLS.md#the-kl-mode)
+**Quality measurement**, instead of serving; see [TOOLS.md](TOOLS.md#the-kl-mode)
 
 | flag | |
 |---|---|
@@ -1226,54 +1266,57 @@ for a model that takes no images or video.
 
 | flag | |
 |---|---|
-| `--debug-graph` | print the declared graph and exit |
+| `--debug-graph` | print the declared graph and the selection table, and exit |
 | `--debug-selection` | print the selection table |
 | `--debug-placement` | print the placement plan |
-| `--debug-accept-reference-kernels` | serve even when ops resolve to `libref`. **Not a production configuration** |
+| `--debug-accept-reference-kernels` | serve even when ops resolve to `libref`. Not a production configuration |
 | `--profile-ops` | per-op device timing |
-| `--live` | the live terminal view |
+| `--live` | the live terminal view (§6.4) |
 | `-v` / `-vv` | verbose / very verbose |
 
 ---
 
-## 5. Talk to it
+## 5. API
 
-### 5.1 The endpoints
+### 5.1 Endpoints
 
 | | |
 |---|---|
 | `POST /v1/chat/completions` | chat, with tools, reasoning and streaming |
 | `POST /v1/completions` | raw text completion |
 | `POST /v1/embeddings` | needs a model with an embedding head, else 501 |
-| `POST /v1/images/generations`, `POST /v1/images/edits` | OpenAI's images API, needs an image model (Qwen-Image 2.1), else 501 — §5.6 |
-| `POST /v1/systemone` | LiquidAI d1's decisions over a state: named yes/no, choice and score questions answered as probabilities, nothing generated; needs a container converted as d1, else 501 — §5.12 |
-| `POST /v1/messages`, `POST /v1/messages/count_tokens` | Anthropic's Messages API, for Claude Code and the Anthropic SDKs — §5.9 |
-| `POST /v1/responses`, `POST /v1/responses/input_tokens` | OpenAI's Responses API, for Codex and the OpenAI SDKs' `responses` client — §5.9 |
-| `POST /completion`, `/completions`, `POST /infill` | llama-server's native completion and fill-in-the-middle, for llama.vim, llama.vscode and the clients built on llama-server's own API — §5.9 |
-| `GET /v1/models`, `/v1/models/:id` | what is loaded, with `max_model_len` (the context it serves) and `root` (the `--model` path), as vLLM reports them, and `capabilities` (the same object `/server_info` reports); `:id` answers the entry itself, as OpenAI's retrieve does |
+| `POST /v1/images/generations`, `POST /v1/images/edits` | OpenAI's images API; needs an image model (Qwen-Image 2.1), else 501 (§5.6) |
+| `POST /v1/systemone` | LiquidAI d1's decisions over a state: named yes/no, choice and score questions answered as probabilities, nothing generated; needs a container converted as d1, else 501 (§5.13) |
+| `POST /v1/audio/transcriptions` | OpenAI's speech to text, for a model whose plugin transcribes (Qwen3-ASR), else 501 (§5.14) |
+| `GET /v1/realtime` (WebSocket) | OpenAI's realtime transcription session: audio streamed in, the words back as they are spoken (§5.14) |
+| `POST /v1/messages`, `POST /v1/messages/count_tokens` | Anthropic's Messages API, for Claude Code and the Anthropic SDKs (§5.9, §5.11) |
+| `POST /v1/responses`, `POST /v1/responses/input_tokens` | OpenAI's Responses API, for Codex and the OpenAI SDKs' `responses` client (§5.9) |
+| `POST /completion`, `/completions`, `POST /infill` | llama-server's native completion and fill-in-the-middle, for llama.vim, llama.vscode and clients of llama-server's own API (§5.9) |
+| `GET /v1/models`, `/v1/models/:id` | what is loaded, with `max_model_len` (the context it serves) and `root` (the `--model` path) as vLLM reports them, and `capabilities` (the same object `/server_info` reports); `:id` returns the entry itself, as OpenAI's retrieve does |
 | `GET /health`, `/v1/health`, `/ping`, `POST /ping` | liveness |
 | `GET /load` | current load |
 | `GET /version` | server version |
-| `GET /props` | llama-server's props for the clients built against it: `n_ctx`, `total_slots`, `modalities`, `model_path`, the chat template and its capabilities, `bos_token`/`eos_token`, and the request defaults under llama-server's names |
-| `POST /apply-template` | the prompt a chat request renders to, as llama-server answers it |
+| `GET /props` | llama-server's props: `n_ctx`, `total_slots`, `modalities`, `model_path`, the chat template and its capabilities, `bos_token`/`eos_token`, and the request defaults under llama-server's names |
+| `POST /apply-template` | the prompt a chat request renders to, as llama-server returns it |
 | `POST /v1/chat/completions/input_tokens` | how many tokens that prompt is |
 | `GET /server_info` | the whole configuration of the running engine |
-| `GET /diagnostics` | the startup report as JSON — every option and its source, the hardware read again now, the findings — §7.1. Without `--api-key` it answers only a client on the same machine (§6.6) |
+| `GET /diagnostics` | the startup report as JSON: every option and its source, the hardware read again now, the findings (§7.1). Without `--api-key` it answers only a client on the same machine (§6.6) |
 | `GET /metrics` | Prometheus |
 | `POST /tokenize`, `POST /detokenize` | vLLM's shape (`prompt` or `messages` in, `prompt` out) and llama-server's (`content` in and out, `with_pieces`) |
-| `GET /get_tokenizer_info` | |
+| `GET /get_tokenizer_info` | the tokeniser's configuration |
 | `POST /reset_prefix_cache` | drop every cached prefix |
 | `GET /` or `/dashboard` | the web dashboard |
 | `GET /stats`, `/graph`, `/sessions` | the JSON the dashboard is drawn from |
 
-Method spellings follow vLLM's, including the ones that look odd: `/tokenize` is POST because its
-input is a body, and `/ping` answers both GET and POST because different load balancers send
-different ones. As llama-server does, `/chat/completions`, `/embeddings` and `/models` answer without the `/v1`
-too, for a client configured with the bare host as its base URL -- and `/completions` without it is
+Methods follow vLLM's: `/tokenize` is POST because its input is a body, and `/ping` answers GET and
+POST because load balancers differ. As in llama-server, `/chat/completions`,
+`/chat/completions/input_tokens`, `/embeddings`, `/images/generations`, `/images/edits`,
+`/audio/transcriptions`, `/models`, `/responses` and `/responses/input_tokens` also answer without
+`/v1`, for a client configured with the bare host as its base URL; `/completions` without `/v1` is
 llama-server's native completion, as it is there. A path nothing serves is a JSON 404.
 
-A text prompt to `/v1/completions`, `/v1/embeddings` or `/tokenize` reads the model's control
-tokens as tokens, as vLLM and llama.cpp do: a client that renders its own chat template can send
+A text prompt to `/v1/completions`, `/v1/embeddings` or `/tokenize` reads the model's control tokens
+as tokens, as vLLM and llama.cpp do: a client that renders its own chat template can send
 `<|im_start|>user\n…` and the model sees the turn markers. The BOS the model declares is prepended
 unless the prompt already opens with it.
 
@@ -1290,10 +1333,10 @@ curl -s http://localhost:8000/v1/chat/completions \
   }' | jq -r '.choices[0].message.content'
 ```
 
-If the container carries no chat template this endpoint answers **501** and the startup log says
-so — use `/v1/completions` instead.
+If the container carries no chat template this endpoint answers 501 and the startup log says so; use
+`/v1/completions` instead.
 
-**Turning thinking off.** Three spellings reach the server for one question; all work:
+**Turning thinking off.** Any of three spellings works:
 
 ```json
 {"chat_template_kwargs": {"enable_thinking": false}}
@@ -1303,26 +1346,24 @@ so — use `/v1/completions` instead.
 
 Reasoning text comes back in `choices[].message.reasoning_content`, separate from `content`.
 
-**Reasoning counts against `max_tokens`**, as in OpenAI's API, vLLM and llama.cpp: every
-generated token does. A reply that runs out inside its reasoning comes back with empty
-`content` and `finish_reason: "length"`. `usage.completion_tokens_details.reasoning_tokens` says
-how many of `completion_tokens` were reasoning, the block's end token included, so a client can
-tell that case from a model that answered nothing.
+**Reasoning counts against `max_tokens`**, as in OpenAI's API, vLLM and llama.cpp. A reply that runs
+out inside its reasoning has empty `content` and `finish_reason: "length"`;
+`usage.completion_tokens_details.reasoning_tokens` (the block's end token included) tells that case
+from a model that answered nothing.
 
-**Capping the reasoning.** `thinking_token_budget` (vLLM's name; `thinking_budget`, Qwen's, is
-read as the same field) is how many tokens the reasoning may run to. At that count the block is
-closed and the model answers from what it has reasoned so far:
+**Capping the reasoning.** `thinking_token_budget` (vLLM's name; Qwen's `thinking_budget` is read as
+the same field) is how many tokens the reasoning may run to. At that count the block is closed and
+the model answers from what it has reasoned so far:
 
 ```json
 {"max_tokens": 4096, "thinking_token_budget": 2048}
 ```
 
-The count starts after the opening ``. A reasoning block that ends sooner is not
-affected. The close is forced by the sampler, so it holds under speculative decoding and at any
-temperature. A `grammar` or `response_format` that does not allow the close at some position
-keeps that position, and the close comes at the next position that allows it. The budget and
-`reasoning_tokens` need the block's end to be one token. A model whose end is not one token
-reports no `completion_tokens_details` and refuses a budget with a 400 that says why.
+The count starts after the opening ``. The sampler forces the close, so it holds under
+speculative decoding and at any temperature; where a `grammar` or `response_format` does not allow
+it, the close comes at the next position that does. The budget and `reasoning_tokens` need the
+block's end to be one token; otherwise the response has no `completion_tokens_details` and a budget
+is refused with a 400 that says why.
 
 ### 5.3 Streaming
 
@@ -1334,7 +1375,11 @@ curl -N http://localhost:8000/v1/chat/completions \
        "stream_options":{"include_usage":true}}'
 ```
 
-Server-sent events, OpenAI's delta format, terminated by `data: [DONE]`.
+Server-sent events in OpenAI's delta format, terminated by `data: [DONE]`. Nothing is sent while
+the prompt is read: the first event, the `role: assistant` chunk, goes out when the first token
+is generated, as vLLM and llama-server send it, so a client that times its first event
+(llama-benchy's `ttfr`) measures the time to the first token. `return_progress` adds
+llama-server's `prompt_progress` chunks during the prompt (§5.7).
 
 ### 5.4 Tool calls
 
@@ -1360,21 +1405,18 @@ curl -s http://localhost:8000/v1/chat/completions \
 ```
 
 Calls come back in `message.tool_calls` with `finish_reason: "tool_calls"`. No `` or
-`` markup ever reaches `content`. `scripts/mctools.sh` and `scripts/mcstream.sh` assert
-exactly that, including on raw streamed fragments — content cannot be retracted once sent, so a
-repair applied at the end is not a fix.
+`` markup reaches `content`, streamed fragments included; `scripts/mctools.sh` and
+`scripts/mcstream.sh` check this.
 
 A tool's `parameters` schema shapes the grammar the call is written under. A property whose schema
-accepts no value — `false`, or `{"not": {}}`, which is how TypeBox and Arktype export `never` — is
-an argument no call writes. Any other `not` is refused with a 400 naming it: the grammar cannot
-express a complement, and dropping the constraint silently would serve a call the tool forbids.
+accepts no value (`false`, or `{"not": {}}`, as TypeBox and Arktype export `never`) is never written.
+Any other `not` is refused with a 400 naming it, since the grammar cannot express a complement.
 
-Length bounds are held exactly: `maxLength`, `minLength`, `maxItems` and `minItems` up to about
-200,000, which costs the first request carrying the tool under a second to compile on a
-quarter-million-token vocabulary and nothing per token after that. A bound past 2^31 (as
-`Number.MAX_SAFE_INTEGER` is) is no bound, since no context holds that much. One in between is
-refused with a 400 naming the property's rule and the count. The same holds for `response_format`
-schemas and `{m,n}` in a GBNF grammar.
+`maxLength`, `minLength`, `maxItems` and `minItems` are held exactly up to about 200,000 (under a
+second to compile on the first request carrying the tool, at a quarter-million-token vocabulary, and
+nothing per token after). A bound past 2^31 (such as `Number.MAX_SAFE_INTEGER`) is treated as none;
+one in between is refused with a 400 naming the rule and the count. The same holds for
+`response_format` schemas and `{m,n}` in a GBNF grammar.
 
 ### 5.5 Constrained output
 
@@ -1393,21 +1435,19 @@ schemas and `{m,n}` in a GBNF grammar.
 -d '{"model":"m","prompt":"...","grammar":"root ::= \"yes\" | \"no\""}'
 ```
 
-**On chat, a constraint passes through the chat template and may not survive it.** The template
-gets to rewrite or drop `grammar` and `response_format` — a tool-calling template produces its own
-grammar, for instance — so whether a constraint can be enforced is a property of the model's
-template and not only of the server. When the one you asked for is not there at the end, the
-request is **refused**:
+**On chat, a constraint passes through the chat template.** The template may rewrite or drop
+`grammar` and `response_format` (a tool-calling template produces its own grammar, for instance), so
+whether a constraint can be enforced depends on the model's template. When the requested constraint
+is not there after rendering, the request is refused:
 
 ```
 grammar: this model's chat template produced no grammar for it, so the constraint could not
 be enforced
 ```
 
-That is §5.8's rule doing its job -- a field that would change the answer is honoured or
-refused, never dropped: an unconstrained 200 would leave you
-parsing free prose against a schema you were told was enforced. `/v1/completions` has no template
-in the way, so the same grammar works there — which is why the example above uses it.
+(`response_format:` for a schema.) This is §5.8's rule: a field that would change the answer is
+honoured or refused, never dropped. `/v1/completions` has no template in the way, so the same grammar
+works there, which is why the example above uses it.
 
 ### 5.6 Completions, embeddings, images, tokenising
 
@@ -1432,13 +1472,13 @@ curl -s http://localhost:8000/tokenize -H 'Content-Type: application/json' \
 ```
 
 `/tokenize` takes one of `prompt`, `messages` or llama-server's `content` (a string, or strings and
-token ids mixed, with its `add_special` and `parse_special` and their defaults); the `content`
-form answers `tokens` as llama-server does, as `{id, piece}` objects with `with_pieces`.
-`/detokenize` answers the text as both `prompt` (vLLM) and `content` (llama-server).
+token ids mixed, with its `add_special` and `parse_special` and their defaults); the `content` form
+returns `tokens` as llama-server does, as `{id, piece}` objects with `with_pieces`. `/detokenize`
+returns the text as both `prompt` (vLLM) and `content` (llama-server).
 
-**An embedding model** (EmbeddingGemma 2) serves `/v1/embeddings` and nothing else; completions and
-chat answer 501. One input is one vector, and an input is never split: it has to fit one step
-(`--max-num-batched-tokens`), and a longer one is refused with `context_length_exceeded`.
+**An embedding model** (EmbeddingGemma 2) serves `/v1/embeddings` only; completions and chat answer
+501. One input is one vector and must fit one step (`--max-num-batched-tokens`); a longer one is
+refused with `context_length_exceeded`.
 
 ```sh
 # text, a batch of texts, or token ids
@@ -1465,19 +1505,22 @@ curl -s http://localhost:8000/v1/embeddings -H 'Content-Type: application/json'
         "input_audio":{"data":"","format":"wav"}}]}]}'
 ```
 
-`input` is a string, an array of token ids, one array of content parts, or a batch of any of
-those. A content part is `text`, `image_url`, `video_url`, `input_audio` (wav, mp3, flac, ogg,
-opus, m4a, aac, webm or aiff, base64) or `audio_url`; media comes as `data:` URLs, never fetched.
-An image becomes up to 280 tokens by default (`--image-tokens`, or a request's `image_tokens`: 70,
-140, 280, 560 or 1120), a video one frame a second, at most 32 frames of 140 tokens
-(`--video-fps`, `--video-max-frames`, `--video-max-frame-tokens`), and audio 25 tokens a second,
-cut at 30 seconds. `prompt_name` takes the names the model's sentence-transformers configuration
-states (`query`, `document`, `Retrieval-query`, `STS`, ...) and applies to text and content-part
-inputs; a model that states a default prompt applies it when the request names none.
+`input` is a string, an array of token ids, one array of content parts, or a batch of any of those.
+A content part is `text`, `image_url`, `video_url`, `input_audio` (wav, mp3, flac, ogg, opus, m4a,
+aac, webm or aiff, base64) or `audio_url`; media comes as `data:` URLs and is never fetched. An image
+becomes up to 280 tokens by default (`--image-tokens`, or a request's `image_tokens`: 70, 140, 280,
+560 or 1120), a video one frame a second, at most 32 frames of 140 tokens (`--video-fps`,
+`--video-max-frames`, `--video-max-frame-tokens`), and audio 25 tokens a second, cut at 30 seconds.
+`prompt_name` takes the names the model's sentence-transformers configuration states (`query`,
+`document`, `Retrieval-query`, `STS`, ...) and applies to text and content-part inputs; a model that
+states a default prompt applies it when the request names none.
 
-**An image model** (Qwen-Image 2.1 or 2.1-Turbo) serves OpenAI's images API and nothing else;
-completions, chat and embeddings answer 501. Clients written against OpenAI's images endpoints
-(Open WebUI, the OpenAI SDKs) work as they are; the picture always comes back in the response.
+**An image model** (Qwen-Image 2.1 or 2.1-Turbo) serves OpenAI's images API only; completions, chat
+and embeddings answer 501. OpenAI images clients (Open WebUI, the OpenAI SDKs) work unchanged; the
+picture always comes back in the response. The engine sizes the step, batch and context for an image
+model itself (`--max-num-batched-tokens` and `--max-model-len` from the model's largest pass,
+`--max-num-seqs` 16), keeps any of the three given on the command line, and turns off drafting and
+the prefix cache.
 
 ```sh
 # a picture from a prompt: b64_json, 2048x2048 unless `size` says otherwise
@@ -1512,91 +1555,89 @@ curl -sN http://localhost:8000/v1/images/generations -H 'Content-Type: applicati
 | `stream`, `partial_images` | OpenAI's `image_generation.partial_image` / `image_edit.partial_image` events, 0..3 previews of the clean picture the step predicts, then `.completed` |
 | `image`, `image[]`, `mask` | an edit's pictures (png, jpeg, webp; up to ten) and the first picture's mask: alpha below 128 is where the picture may change |
 
-`response_format: url` is refused: nothing here stores a picture to serve later. The response
-carries `usage` (input tokens: the prompt and the pictures' tokens; output: latent tokens) and
-each picture's `seed` and `revised_prompt` (the prompt as given).
+`response_format: url` is refused, since nothing here stores a picture to serve later. The response
+carries `usage` (input tokens: the prompt and the pictures' tokens; output: latent tokens) and each
+picture's `seed` and `revised_prompt` (the prompt as given).
 
-On two cards the step's two all-reduces of the image's rows (128 MB each at 2048x2048, over the
-cards' link) run on a second stream: the rows go through each block in two halves, and one half's
-all-reduce travels while the card computes the other's. `--tp-wire wht6` sends them as 6-bit and
-makes a picture about 9% faster still (2048x2048, 40 steps: 61 -> 56 s; Turbo 12.9 -> 11.9 s, at
-1024x1024 2.6 -> 2.2 s), within a dB of the exact wire against diffusers. Exact is the default.
-The VAE decoder is split by rows across the cards after its mid-block, with the same pixels.
+On two cards each step's two all-reduces of the image's rows (128 MB each at 2048x2048) run on a
+second stream, overlapped with compute by sending the rows through each block in two halves.
+`--tp-wire wht6` sends them as 6-bit and makes a picture about 9% faster (2048x2048, 40 steps: 61 to
+56 s; Turbo 12.9 to 11.9 s, at 1024x1024 2.6 to 2.2 s), within a dB of the exact wire against
+diffusers; exact is the default. The VAE decoder is split by rows across the cards after its
+mid-block, with the same pixels.
 
 On an fp8 container the denoising attention computes its scores in int8 (about 16% faster
-attention); a picture moves by less than switching between two exact attention implementations
-moves it. A bf16 container keeps bf16 scores.
+attention); a picture moves by less than switching between two exact attention implementations moves
+it. A bf16 container keeps bf16 scores.
 
-Two cards (`--tp 2`) are the fastest picture; two servers of one card each make the most
-pictures an hour (each takes 1.7x as long and there are two). A card runs these models at its
-300 W limit, in the DiT's GEMMs and attention alike.
+`--tp 2` gives the fastest picture; two one-card servers give the most pictures an hour (each takes
+1.7x as long). A card runs these models at its 300 W limit.
 
-A reference picture costs 4096 rows of the conditioning's KV cache at the model's 1024x1024
-reference area -- its latent rows, which take its vision tokens' places. One card holds the fp8
-container and a cache of 20256 rows: four pictures with their prompt. Two cards (`--tp 2`) hold
-all ten the model takes, and the bf16 container. A request the cache can never hold is a 400
-that says how many rows it needed. The models are under Qwen's research license,
-non-commercial.
+A reference picture costs 4096 rows of the conditioning's KV cache at the model's 1024x1024 reference
+area (its latent rows replace its vision tokens). One card holds the fp8 container and a cache of
+20256 rows: four pictures with their prompt. Two cards hold all ten the model takes, and the bf16
+container. A request the cache can never hold is a 400 naming the rows it needed. The models are
+under Qwen's research license, non-commercial.
 
 ### 5.7 Request fields
 
 | field | notes |
 |---|---|
-| `model` | accepted and not enforced — one server serves one model |
+| `model` | accepted and not enforced: one server serves one model |
 | `messages` / `prompt` / `input` | chat / completion / embedding |
-| `max_tokens`, `max_completion_tokens`, `n_predict` | default: what the context leaves after the prompt (`--default-max-tokens`); -1 is llama-server's "no limit", the same without the default. Clamped to what the context leaves, and to `--max-tokens-cap`, rather than refused — see §5.8 |
+| `max_tokens`, `max_completion_tokens`, `n_predict` | default: what the context leaves after the prompt (`--default-max-tokens`); -1 is llama-server's "no limit", the same without the default. Clamped to what the context leaves, and to `--max-tokens-cap`, rather than refused (§5.8) |
 | `temperature` | [0, 2] |
 | `top_p` | (0, 1] |
-| `top_k` | ≥ 0, 0 disables |
+| `top_k` | ≥ 0; 0 is the 1024 most likely tokens, the sampler's candidate width |
 | `min_p`, `typical_p` | |
 | `presence_penalty`, `frequency_penalty` | [-2, 2] |
 | `repetition_penalty` (or `repeat_penalty`), `repeat_last_n` | |
 | `xtc_probability`, `xtc_threshold` | |
 | `dry_multiplier`, `dry_base`, `dry_allowed_length`, `dry_penalty_last_n`, `dry_sequence_breakers` | |
-| `seed` | absent means "pick one" — **not** seed 0 |
-| `n` | 1 to `--max-n`, by default the larger of 8 and `--max-num-seqs`. Fan-out over the same prompt; the prefix cache makes it nearly free after the first |
+| `seed` | absent means "pick one", not seed 0 |
+| `n` | 1 to `--max-n` (by default the larger of 8 and `--max-num-seqs`). Fan-out over the same prompt; the prefix cache makes it nearly free after the first |
 | `priority` | |
 | `stop` | a string or an array; at most 64 strings of 4096 bytes (`--max-stop-strings`, `--max-stop-bytes`) |
 | `ignore_eos` | generate to `max_tokens` whatever the model emits |
 | `stream`, `stream_options.include_usage` | |
 | `timings_per_token`, `return_progress` | llama-server's: `timings` on every chunk, and `prompt_progress` chunks while the prompt is read |
-| `samplers` | llama-server's sampler order, names or letters. A stage it leaves out is off. The chain here is penalties, DRY, top-k, top-p, min-p, typical, XTC with temperature first (the default) or last (llama-server's default), so a list in either of those orders is honoured and any other is refused by name |
+| `samplers` | llama-server's sampler order, names or letters. A stage it leaves out is off. The chain here is penalties, DRY, top-k, top-p, min-p, typical, XTC, with temperature first (the default) or last (llama-server's default), so a list in either order is honoured and any other is refused by name |
 | `session_id` | OpenRouter's conversation id: labels the conversation on `/sessions` and the dashboard |
-| `logprobs`, `top_logprobs`, `n_probs` | each generated token's logprob and up to 20 alternatives — see §5.11. Chat: `logprobs: true` with `top_logprobs` alternatives (0 when absent); completions: `logprobs: N`; any endpoint: llama-server's `n_probs: N`, which wins. Not with `echo` (the prompt's logprobs are not computed) |
+| `logprobs`, `top_logprobs`, `n_probs` | each generated token's logprob and up to 20 alternatives (§5.12). Chat: `logprobs: true` with `top_logprobs` alternatives (0 when absent); completions: `logprobs: N`; any endpoint: llama-server's `n_probs: N`, which wins. Not with `echo` (the prompt's logprobs are not computed) |
 | `tools`, `tool_choice`, `parallel_tool_calls` | chat only. `tool_choice` is `auto`, `none`, `required` or `{"type":"function","function":{"name":...}}`; the last two hold the whole reply to calls (after the reasoning block), the named form to that one function, and cannot be combined with `response_format` or `grammar` |
 | `add_generation_prompt`, `chat_template_kwargs` | chat only |
-| `continue_final_message` | chat only. A conversation ending in an assistant message is continued rather than answered, as llama-server and the Anthropic API do -- the reply carries that message's text and what follows it. `true`, `"content"` or `"reasoning_content"` names it explicitly; `add_generation_prompt: true` opens a new turn instead |
+| `continue_final_message` | chat only. A conversation ending in an assistant message is continued rather than answered, as llama-server and the Anthropic API do; the reply carries that message's text and what follows it. `true`, `"content"` or `"reasoning_content"` names it explicitly; `add_generation_prompt: true` opens a new turn instead |
 | `reasoning_format` | chat only, llama-server's: `none` keeps the reasoning in `content`; `auto` and `deepseek` split it into `reasoning_content`, the default |
 | `reasoning_effort`, `enable_thinking` | chat only. The levels are the template's (`capabilities.reasoning_efforts` on `/server_info`); `none` and `minimal` turn thinking off |
-| `thinking_token_budget`, `thinking_budget`, `thinking_budget_tokens`, `reasoning_budget_tokens` | chat only. ≥ 0: the reasoning tokens after which the block is closed — see §5.2; -1 is none. Default `--thinking-token-budget`, else none |
+| `thinking_token_budget`, `thinking_budget`, `thinking_budget_tokens`, `reasoning_budget_tokens` | chat only. ≥ 0: the reasoning tokens after which the block is closed (§5.2); -1 is none. Default `--thinking-token-budget`, else none |
 | `preserve_thinking` | chat only. The chat template variable of that name, as llama.cpp maps it; Qwen3.6 and later keep earlier turns' reasoning in the prompt with it |
 | `response_format`, `json_schema` | chat only. `json_schema` is llama-server's shorthand: the schema itself. Mutually exclusive with `grammar` |
-| `functions`, `function_call` | chat only: OpenAI's deprecated spellings of `tools` and `tool_choice`. The reply answers in the old shape too: one call at most, as `message.function_call` with `finish_reason: "function_call"`; the next turn's assistant `function_call` and `function` message are read as the call and its result |
-| `grammar` | a GBNF grammar directly. On chat it passes through the chat template and a template that drops it makes the request a refusal — see §5.5 |
+| `functions`, `function_call` | chat only: OpenAI's deprecated spellings of `tools` and `tool_choice`. The reply uses the old shape too: one call at most, as `message.function_call` with `finish_reason: "function_call"`; the next turn's assistant `function_call` and `function` message are read as the call and its result |
+| `grammar` | a GBNF grammar. On chat it passes through the chat template, and a template that drops it makes the request a refusal (§5.5) |
 | `echo` | `/v1/completions` only |
+| `preserved_tokens` | `/v1/completions` only, llama-server's: control tokens the completion's text keeps. On chat it is guarded (§5.8) |
 | `encoding_format` | `/v1/embeddings` only: `float` or `base64` |
 | `dimensions`, `prompt_name`, `image_tokens` | `/v1/embeddings` only (an embedding model, §5.6). `dimensions` truncates to the first N and renormalises; it cannot exceed the model's width |
 
-Any field the request omits keeps the deployment default (§4.9). A field the request names wins.
+A field the request omits takes the deployment default (§4.9).
 
-### 5.8 What a field this server does not implement does
+### 5.8 Unimplemented fields
 
-Four kinds of field, and the rule they serve is that **a request that returns 200 had every field
-that could change its answer honoured**:
+The rule: a request that returns 200 had every field that could change its answer honoured. Fields
+fall into four kinds:
 
-- **Accepted** — the table above, in OpenAI's, vLLM's and llama-server's spellings.
-- **Inert** — fields that change nothing about the answer, accepted and ignored: OpenAI's and
-  OpenRouter's bookkeeping (`user`, `metadata`, `store`, `service_tier`, `safety_identifier`,
-  `prompt_cache_key`, `prediction`), and llama-server's knobs for its own speed and slots
-  (`cache_prompt`, `id_slot`, `n_cache_reuse`, `backend_sampling`, `reasoning_control`, `n_keep`,
-  `n_discard`, `speculative.*`, ...). The prefix cache and speculation here are the server's own
-  and never change the output.
-- **Guarded** — known, not implemented, and able to change the answer. llama-server's clients send
-  every one of them on every request at its off value, so each is accepted there and refused,
-  naming it, at any other:
+- **Accepted**: the table above, in OpenAI's, vLLM's and llama-server's spellings.
+- **Inert**: fields that cannot change the answer, accepted and ignored. OpenAI's and OpenRouter's
+  bookkeeping (`user`, `metadata`, `store`, `service_tier`, `safety_identifier`, `prompt_cache_key`,
+  `prediction`), and llama-server's knobs for its own speed and slots (`cache_prompt`, `id_slot`,
+  `n_cache_reuse`, `backend_sampling`, `reasoning_control`, `n_keep`, `n_discard`, `speculative.*`,
+  ...). The prefix cache and speculation here are the server's own and never change the output.
+- **Guarded**: known, not implemented, and able to change the answer. llama-server's clients send
+  them on every request at their off value, so each is accepted there and refused, by name, at any
+  other:
 
 ```json
-{"error": {"message": "mirostat: mirostat is not one of the device samplers (spec 13); it is accepted only at 0, where it does nothing", ...}}
+{"error": {"message": "mirostat: mirostat is not one of the device samplers; it is accepted only at 0, where it does nothing", ...}}
 ```
 
 | guarded | accepted at | because |
@@ -1604,104 +1645,90 @@ that could change its answer honoured**:
 | `logit_bias` | empty | the device sampler has no per-token bias stage |
 | `mirostat` | 0 | not one of the device samplers |
 | `top_n_sigma` | ≤ 0 | not one of the device samplers |
-| `dynatemp_range` | 0 | not one of the device samplers |
+| `dynatemp_range` | ≤ 0 | not one of the device samplers |
 | `min_keep` | 0 | the cuts keep no minimum count |
 | `post_sampling_probs` | false | logprobs are the raw distribution's; the sampler's are not returned |
-| `best_of` | 1 | not implemented |
+| `best_of` | ≤ 1 | not implemented |
 | `suffix` | empty | infilling through `/v1/completions` is not implemented |
-| `lora` | empty | explicitly out of scope |
+| `lora` | empty | out of scope |
 | `modalities`, `audio` | `["text"]`, null | output other than text is not implemented |
-| `n_indent`, `t_max_predict_ms`, `return_tokens` | 0, 0, false | not implemented |
-| `grammar_lazy`, `grammar_triggers`, `preserved_tokens` | off, empty | the chat format decides them |
+| `n_indent`, `t_max_predict_ms`, `return_tokens` | 0, ≤ 0, false | not implemented (`return_tokens` is served on `/completion`, §5.9) |
+| `grammar_lazy`, `grammar_triggers`, `preserved_tokens` | off, empty, empty | the chat format decides them |
 
-- **Anything else is ignored**, as llama-server and vLLM ignore it: a field this server has never
-  heard of is a client's own extension far more often than a request it misunderstood. The names
-  are logged at debug.
+- **Anything else is ignored**, as llama-server and vLLM ignore it: an unknown field is far more often
+  a client's own extension than a misunderstood request. The names are logged at debug.
 
-**The one exception is `max_tokens`.** If `prompt + max_tokens` would exceed the context, the
-server clamps `max_tokens` to what is left and serves the request:
+**The exception is `max_tokens`.** If `prompt + max_tokens` would exceed the context, the server
+clamps `max_tokens` to what is left and serves the request:
 
 ```
 prompt 72,170 + max_tokens 128,000  >  200,000 context
                                     ->  served with max_tokens 127,830
 ```
 
-It is an exception because the other keys are *settings* — dropping one serves a different model
-than the caller asked for — and this one is a *bound*, whose whole purpose is to stop generation
-early and which the context was going to stop earlier anyway. Refusing would not produce more
-tokens than clamping does; it would produce none. The completion ends with `finish_reason:
-"length"` and `usage` reports what it actually got, so the caller can still see what happened, and
-`-v` logs the adjustment.
+The other fields are settings, and dropping one serves a different request than the caller asked
+for. `max_tokens` is a bound whose purpose is to stop generation early, and the context stops it
+earlier anyway; refusing would produce no tokens instead of fewer. The completion ends with
+`finish_reason: "length"`, `usage` reports what it got, and `-v` logs the adjustment.
 
-A prompt that does not fit **on its own** is still a 400 — there is no window to generate into, so
-no `max_tokens` would have made it servable — and the error names how many tokens have to go:
+A prompt that does not fit on its own is still a 400 (`code: "context_length_exceeded"`, with
+`n_prompt_tokens` and `n_ctx`), since no `max_tokens` would make it servable. The message names how
+many tokens have to go:
 
 ```
-prompt: 220470 prompt tokens does not fit the 200000 token context, which leaves nothing to
-generate into; shorten the prompt by at least 20471 tokens
+This model's maximum context length is 200000 tokens: the request (220470 tokens) exceeds the
+available context size (200000 tokens) and leaves nothing to generate into; shorten the prompt by
+at least 20471 tokens
 ```
 
-At the boundary, where an off-by-one would hide: a 198,729-token prompt asking for `max_tokens`
-128,000 against a 200,000 context is served, generates **1,271** tokens — exactly the room left —
-and ends `finish_reason: "length"`. `POST /tokenize` is how to size a prompt that
-precisely without running the model.
-
----
-
+At the boundary: a 198,729-token prompt asking for `max_tokens` 128,000 against a 200,000 context is
+served, generates 1,271 tokens (the room left) and ends with `finish_reason: "length"`. `POST
+/tokenize` sizes a prompt that precisely without running the model.
 
 ### 5.9 Anthropic's, OpenAI's Responses and llama-server's native APIs
 
-`POST /v1/messages` takes Anthropic's request and answers in Anthropic's shapes, streamed
-(`message_start`, content blocks, `message_delta`, `message_stop`) or not, so Claude Code and the
-Anthropic SDKs work against radiance as they do against llama-server:
+`POST /v1/messages` is Anthropic's Messages API, streamed (`message_start`, content blocks,
+`message_delta`, `message_stop`) or not, for Claude Code and the Anthropic SDKs:
 
 ```sh
 ANTHROPIC_BASE_URL=http://localhost:8000 ANTHROPIC_API_KEY="$KEY" claude
 ```
 
-It is translated into the chat request it means and served by the chat path, so the template
-defaults, refusals and limits are the chat endpoint's. `system` (a string or text blocks), text and
-image blocks, `tool_use` and `tool_result`, client tools and `tool_choice`, `stop_sequences`,
-`thinking` (`enabled` with a `budget_tokens`, `disabled`, `adaptive`) and `metadata.user_id` (the
-conversation's label on `/sessions`) are honoured. A conversation that ends in an assistant message
-is continued, and the answer carries what follows it. Thinking blocks come back with an empty
-`signature`. Claude Code's per-request billing stamp at the head of the system prompt is held
-constant, as llama-server holds it, or no turn could reuse the prefix of the one before.
-`document` blocks and Anthropic's server tools (`web_search_…`, `code_execution_…`) run on
-Anthropic's side and are refused by name. `POST /v1/messages/count_tokens` answers the prompt's
-length. The key may come as `X-Api-Key` (§6.6).
+It is translated into a chat request, so the chat endpoint's template defaults, refusals and
+limits apply; §5.11 lists what it reads, takes and refuses. `POST /v1/messages/count_tokens`
+returns the prompt's length. The key may come as `X-Api-Key` (§6.6).
 
 `POST /v1/responses` is OpenAI's Responses API, translated the same way: `instructions` and `input`
 (a string, or message, `function_call`, `function_call_output` and `reasoning` items) become the
-conversation, `max_output_tokens` and `reasoning.effort` and `text.format` the chat request's
-fields, and every field the Responses API does not define passes through to the chat request as it
-does in llama-server (`chat_template_kwargs`, `top_k`, ...). The answer is a response object, or
-its event stream with every event's `output_index`, `content_index` and `sequence_number`; a reply
-cut at `max_output_tokens` is `incomplete`. Function tools are offered to the model; the built-in
-tools (web search, file search, computer use) and freeform custom tools have no counterpart here
-and are left out, as llama-server leaves them out. Responses are not stored, so
-`previous_response_id` is refused: send the conversation as `input`. What a response object
-cannot carry is refused rather than computed and dropped: `n` other than 1, and logprobs
-(`include` naming `message.output_text.logprobs`, `top_logprobs`, `logprobs`, `n_probs`) --
-`/v1/chat/completions` serves those. A failed generation ends the stream in
-`response.failed`, as one on `/v1/messages` ends in Anthropic's `error` event.
+conversation; `max_output_tokens`, `reasoning.effort` and `text.format` become the chat request's
+fields; and every field the Responses API does not define passes through to the chat request, as in
+llama-server (`chat_template_kwargs`, `top_k`, ...). The answer is a response object, or its event
+stream with every event's `output_index`, `content_index` and `sequence_number`, opening with
+`response.created` and `response.in_progress` at once, as OpenAI's and vLLM's do: they report the
+response object, not output. A reply cut at
+`max_output_tokens` is `incomplete`. Function tools are offered to the model; built-in tools (web
+search, file search, computer use) and freeform custom tools are left out, as in llama-server.
+Responses are not stored, so `previous_response_id` is refused: send the conversation as `input`.
+What a response object cannot carry is refused: `n` other than 1, and logprobs (`include` naming
+`message.output_text.logprobs`, `top_logprobs`, `logprobs`, `n_probs`), which
+`/v1/chat/completions` serves. A failed generation ends the stream in `response.failed`, as one on
+`/v1/messages` ends in Anthropic's `error` event.
 
 `POST /completion` (and `/completions` without `/v1`, as llama-server names it) is llama-server's
-native completion: a prompt string, token ids, or strings and ids mixed as one prompt; the
-request fields of §5.7; and llama-server's answer -- `content`, `stop_type` (`eos`, `limit`,
-`word`), `stopping_word`, `tokens_predicted`, `tokens_evaluated`, `generation_settings`,
-`timings`, and the generated ids with `return_tokens`. A stream is its chunks with the ids that
-made each, then the final result, with no `[DONE]`. `POST /infill` completes between
-`input_prefix` and `input_suffix`, with `input_extra` (files, `{filename, text}`) and `prompt`, in
-the repository-level fill-in-the-middle layout llama-server builds, byte for byte. It needs a model
-with fill-in-the-middle tokens (the Qwen, StarCoder, DeepSeek and CodeLlama spellings are
-recognised) and answers 501 without them; the extra files give way first when the prompt does not
-fit.
-### 5.10 What a response says about its own speed
+native completion: a prompt string, token ids, or strings and ids mixed as one prompt; the request
+fields of §5.7; and llama-server's answer: `content`, `stop_type` (`eos`, `limit`, `word`),
+`stopping_word`, `tokens_predicted`, `tokens_evaluated`, `generation_settings`, `timings`, and the
+generated ids with `return_tokens`. A stream is its chunks with the ids that made each, then the
+final result, with no `[DONE]`. `POST /infill` completes between `input_prefix` and `input_suffix`,
+with `input_extra` (files, `{filename, text}`) and `prompt`, in the repository-level
+fill-in-the-middle layout llama-server builds, byte for byte. It needs a model with fill-in-the-middle
+tokens (the Qwen, StarCoder, DeepSeek and CodeLlama spellings are recognised) and answers 501
+without them; the extra files give way first when the prompt does not fit.
 
-Every chat and completion response carries a top-level `timings` object for the request. It uses
-llama.cpp's field names, so a proxy or dashboard built against llama-server (llama-swap's activity
-view, for one) reads it unchanged:
+### 5.10 Response timings
+
+Every chat and completion response carries a top-level `timings` object with llama.cpp's field
+names, so tools built against llama-server (llama-swap's activity view, for one) read it unchanged:
 
 ```json
 "timings": {
@@ -1716,31 +1743,99 @@ view, for one) reads it unchanged:
 
 | field | meaning |
 |---|---|
-| `prompt_n` | prompt tokens this request computed. Tokens the prefix cache supplied are not in it |
+| `prompt_n` | prompt tokens this request computed; tokens the prefix cache supplied are not in it |
 | `cache_n` | prompt tokens the prefix cache supplied. `prompt_n + cache_n` is the prompt |
-| `prompt_ms` | from the first step the scheduler gave the request to its first token: the prefill. The time it waited for admission is not in it |
-| `prompt_per_second`, `prompt_per_token_ms` | `prompt_n` over `prompt_ms`. A prompt the cache mostly supplied computes few tokens, so this is the speed of the prefill that actually ran, not the prompt length over the time to first token |
+| `prompt_ms` | from the first step the scheduler gave the request to its first token: the prefill. The wait for admission is not in it |
+| `prompt_per_second`, `prompt_per_token_ms` | `prompt_n` over `prompt_ms`: the speed of the prefill that ran, not the prompt length over the time to first token |
 | `predicted_n` | tokens generated, the same as `usage.completion_tokens` |
 | `predicted_ms` | from the first generated token to the last |
-| `predicted_per_second`, `predicted_per_token_ms` | the `predicted_n − 1` tokens after the first, over `predicted_ms`. The first token is the prefill's product. It is the same figure as `/metrics`' time per output token, and with speculative decoding it counts every token a step accepts |
-| `draft_n`, `draft_n_accepted` | speculative tokens proposed for this request and how many were accepted. Present when any were proposed, as llama.cpp does |
-| `ttft_ms` | the server's time to first token: from the moment it had the whole request body to the first generated token. It holds parsing the request, rendering the chat template, tokenising, the wait for admission and the prefill. The time the body took to reach the server is not in it, so a client on a slow link can tell the server's share of the time it measured from the network's. Not a llama.cpp field |
+| `predicted_per_second`, `predicted_per_token_ms` | the `predicted_n − 1` tokens after the first, over `predicted_ms` (the first token is the prefill's product). The same figure as `/metrics`' time per output token; with speculative decoding it counts every token a step accepts |
+| `draft_n`, `draft_n_accepted` | speculative tokens proposed for this request and how many were accepted. Present when any were proposed, as in llama.cpp |
+| `ttft_ms` | the server's time to first token: from having the whole request body to the first generated token, covering parsing, chat template rendering, tokenising, the wait for admission and the prefill. The time the body took to arrive is not in it, so a client on a slow link can separate the server's share from the network's. Not a llama.cpp field |
 | `total_ms` | from the same moment to the last generated token: `ttft_ms + predicted_ms`. Not a llama.cpp field |
 
-Milliseconds are wall-clock milliseconds, and the rates are tokens per second. A rate whose count
-or time is zero is `null`. A request with several choices (`n`, or a batch of prompts) sums the
-counts, and each time runs from the earliest choice's start to the latest choice's end.
+Times are wall-clock milliseconds and rates are tokens per second. A rate whose count or time is
+zero is `null`. A request with several choices (`n`, or a batch of prompts) sums the counts, and each
+time runs from the earliest choice's start to the latest choice's end.
 
-When streaming, each choice's final chunk (the one with `finish_reason`) carries its own
-`timings`, whether or not the request asked for `stream_options.include_usage`. The usage chunk,
-when asked for, carries the request's. `/metrics` stays the aggregate surface (§6.3). It sums
-the same quantities over every request, so it cannot say which request they belong to.
+When streaming, each choice's final chunk (the one with `finish_reason`) carries its own `timings`,
+whether or not the request asked for `stream_options.include_usage`; the usage chunk, when asked
+for, carries the request's. `/metrics` (§6.3) sums the same quantities over all requests.
 
-### 5.11 Logprobs
+### 5.11 Anthropic's Messages API
 
-The numbers are the **raw distribution's** — the logits as the model wrote them, before any
-penalty, temperature, grammar mask or cut — which is what OpenAI and llama-server report. Each
-generated token carries its own logprob and its `top_logprobs` most likely alternatives, at most 20.
+A `/v1/messages` request is translated into the chat request it means and served by the chat
+path, so its template, grammar, sampler and their refusals apply.
+
+```sh
+curl -s http://localhost:8000/v1/messages \
+  -H 'content-type: application/json' \
+  -H 'x-api-key: anything' \
+  -d '{
+    "model": "m",
+    "max_tokens": 200,
+    "messages": [{"role": "user", "content": "Explain merge sort briefly."}]
+  }' | jq '.content[0].text, .stop_reason, .usage'
+```
+
+From Claude Code, name the model as it is served:
+
+```sh
+export ANTHROPIC_BASE_URL=http://127.0.0.1:8000
+export ANTHROPIC_API_KEY=local            # any value, unless the server runs with --api-key
+export ANTHROPIC_MODEL=qwen3.8-flash-next # the --served-model-name
+claude
+```
+
+**The request.** Anthropic's API refuses a field it does not define, and so does this endpoint:
+each field is read, taken without effect, or refused by name.
+
+| field | here |
+|---|---|
+| `system` | a string or text blocks; with the system messages at the head of `messages`, one system message |
+| `messages` | text and image blocks (a base64 image as a `data:` URL; a `url` source is refused, as the server fetches nothing), `tool_use`, `tool_result` (a tool message, ahead of the user's own words), `thinking` (the turn's reasoning); `redacted_thinking` is dropped; `document` blocks and server tool results are refused. A conversation ending in an assistant message is continued |
+| `role: "system"` in `messages` | after the head of the conversation, its text joins a user message at its position, since templates read a system message only at the head: as a text block ahead of the user message right after it, else after the one right before it, else as a user message of its own, so no two user turns follow each other. `clear_at: "next_user_message"` stops rendering it once a later user message (a `tool_result`-only one included) exists. An effort-only message (no text, `output_config: {"effort": ...}`) sets the effort from the next user message on. Blocks other than text (`tool_addition`, ...) are refused |
+| `tools`, `tool_choice` | client tools; server tools (`web_search_…`, `code_execution_…`) are refused. `tool_choice` as an object (`auto`, `any`, `tool`, `none`, `disable_parallel_tool_use`) or a string (`"auto"`, `"none"`, `"any"`); `any` is the chat path's `required` (§5.4) |
+| `max_tokens`, `temperature`, `top_p`, `top_k`, `stop_sequences`, `stream` | as on the chat path; `max_tokens` is optional there too |
+| `thinking` | `enabled` (its `budget_tokens` is the chat request's `thinking_token_budget`), `adaptive`, `disabled`, `between_tools` (off). `display` and `block_binding` are taken: the reasoning comes back whole, with an empty `signature` |
+| `output_config` | `effort` (`low`, `medium`, `high`, `xhigh`, `max`) is the chat request's `reasoning_effort`, which the template reads in its own level names: a level it does not take is refused with the ones it does, and `--reasoning-effort-map` renames them (§4.9). `format` (`{"type": "json_schema", "schema": ...}`, or the older top-level `output_format`) is a `response_format` (§5.5). `task_budget` is taken |
+| `context_management` | validated; the conversation is served as sent, and the answer says so: `"context_management": {"applied_edits": []}`, on `message_delta` in a stream |
+| `thread` | `create` is served as any request; `continue` is refused, since no conversation is stored |
+| `metadata` | `user_id` is the conversation's label on `/sessions` |
+| `service_tier`, `inference_geo`, `speed`, `cache_control`, `diagnostics`, `safeguards`, `fallbacks`, `context_hint` | taken; none can change the answer here. `cache_control` on a block is dropped too |
+| `mcp_servers`, `container` | refused |
+| anything else | refused: `": Extra inputs are not permitted ..."`, Anthropic's own words, which Claude Code matches to retry without a beta field it can drop |
+
+Claude Code's per-request billing stamp at the head of the system prompt is held constant, as
+llama-server does, so each turn can reuse the previous turn's prefix.
+
+**The answer** is an Anthropic message: `content` blocks in the order the reply produced them
+(`thinking`, `text`, `tool_use`), `stop_reason` (`end_turn`, `tool_use`, `max_tokens`,
+`stop_sequence`) and Anthropic's usage split: `input_tokens` without what the prefix cache
+supplied, `cache_read_input_tokens` with it, and `cache_creation_input_tokens` 0, since no cache
+entry is written on a request's behalf. A continued conversation is answered with what follows its
+last message.
+
+**The stream** is Anthropic's events, without `[DONE]`. Nothing is sent while the prompt is read:
+`message_start` (the message with no content; its `input_tokens` is the whole prompt) goes out
+when the first token is generated, so a client that times its first event measures the time to
+the first token, as on `/v1/chat/completions` (§5.3). Then per block `content_block_start`,
+`content_block_delta` and `content_block_stop`, with indices over the whole message (a reply
+that thinks, answers and calls a tool is blocks 0, 1 and 2), then
+`message_delta` (`stop_reason`, `stop_sequence` and the final usage split) and `message_stop`. A
+thinking block opens with an empty `signature` and closes with an empty `signature_delta`; a tool
+block opens with the id and name the server minted, and its input follows as `input_json_delta`.
+A failed generation ends in an `error` event, with no `message_stop`.
+
+**Errors** on `/v1/messages` and the paths below it are in Anthropic's envelope,
+`{"type":"error","error":{"type":"invalid_request_error","message":"..."}}`, the transport's own
+401, 404, 405 and 413 included.
+
+### 5.12 Logprobs
+
+The numbers are the raw distribution's (the logits as the model wrote them, before any penalty,
+temperature, grammar mask or cut), as OpenAI and llama-server report them. Each generated token
+carries its own logprob and its `top_logprobs` most likely alternatives, at most 20.
 
 ```bash
 curl -s localhost:8000/v1/chat/completions -H 'Content-Type: application/json' -d '{
@@ -1756,43 +1851,40 @@ Qwen3.5-0.8B, thinking off:
                  {"id":12675,"token":"Hi","bytes":[72,105],"logprob":-1.3188}]}
 ```
 
-- **Chat** answers in OpenAI's shape, with llama-server's `id` beside each token; a stream carries
-  each token's entry on the chunk that carries its text.
-- **`/v1/completions`** answers OpenAI's legacy arrays (`tokens`, `token_logprobs`, `top_logprobs`
-  as one `{text: logprob}` object a token, `text_offset`) and llama-server's `content` array beside
-  them.
-- **`/completion`** (`n_probs`) answers llama-server's `completion_probabilities`.
+- Chat answers in OpenAI's shape, with llama-server's `id` beside each token; a stream carries each
+  token's entry on the chunk that carries its text.
+- `/v1/completions` answers OpenAI's legacy arrays (`tokens`, `token_logprobs`, `top_logprobs` as one
+  `{text: logprob}` object a token, `text_offset`) and llama-server's `content` array beside them.
+- `/completion` (`n_probs`) answers llama-server's `completion_probabilities`.
 - A token that ends inside a UTF-8 character has the readable part as `token` and every byte in
-  `bytes`, as llama-server does. A stop string's own tokens are not reported, since their text never
+  `bytes`, as in llama-server. A stop string's own tokens are not reported, since their text never
   went out.
 
-Speculation is unaffected — every verified position is scored, and an accepted draft is the token
-the model drew there. The cost is a top-k's worth of work for each row that asks
-(`sample_logprobs`, docs/OPS.md): about 0.12 ms a step on an R9700 at a 248K vocabulary, on the
-card. The chosen token's logprob is exact when it is among the raw top 20; otherwise it is
-recovered from the value it was drawn at by undoing temperature, DRY and the penalties, which
-agrees to float rounding.
+Speculation does not affect logprobs: every verified position is scored, and an accepted draft is the
+token the model drew there. The cost is an on-card top-k for each row that asks (`sample_logprobs`,
+docs/OPS.md), about 0.12 ms a step on an R9700 at a 248K vocabulary. The chosen token's
+logprob is exact when it is among the raw top 20; otherwise it is recovered from the value it was
+drawn at by undoing temperature, DRY and the penalties, which agrees to float rounding.
 
-**Where llama-server differs:** `logprobs: true` without `top_logprobs` returns 20 alternatives
-there and none here, which is OpenAI's default. The values themselves agree with llama-server's to
-bf16 rounding (within 0.1 on Qwen3.5-0.8B, sampled tokens far down the tail included).
+Differences from llama-server: `logprobs: true` without `top_logprobs` returns 20 alternatives there
+and none here, which is OpenAI's default. The values agree with llama-server's to bf16 rounding
+(within 0.1 on Qwen3.5-0.8B, sampled tokens far down the tail included).
 
-### 5.12 Decisions: `/v1/systemone`
+### 5.13 Decisions: `/v1/systemone`
 
-LiquidAI's d1-3B is a decision model on LFM2-VL. It is given a state — text, any JSON value,
-pictures, or a mix — and named questions, and each answer is read off the model's distribution at
-the position after the assistant header: `yes`/`no` for a `noul`, one code an option for a
-`choice`, a digit a level for a `score`. Nothing is generated, so an answer is always in its
-schema. The request and response are d1's own (`api.py` in the model's repository), and the
-prompt it renders is d1's `prompt.py` string for string, since the model was trained on exactly
-those.
+LiquidAI's d1-3B is a decision model on LFM2-VL. Given a state (text, any JSON value, pictures, or a
+mix) and named questions, each answer is read off the model's distribution at the position after the
+assistant header: `yes`/`no` for a `noul`, one code per option for a `choice`, a digit per level for
+a `score`. Nothing is generated, so an answer always fits its schema. The request and response are
+d1's own (`api.py` in the model's repository), and the rendered prompt is d1's `prompt.py` string for
+string, as the model was trained on it.
 
-The endpoint answers only a container that says it is d1, which the checkpoint does not: convert
-it with `--set decision.type=d1`. d1's prompt text, which radiance carries, is Liquid AI's under the
-LFM Open License v1.0, as the model is (NOTICE).
+The endpoint needs a container that declares itself d1; convert the checkpoint with `--set
+decision.type=d1`. d1's prompt text, which radiance carries, is Liquid AI's under the LFM Open
+License v1.0, as the model is (NOTICE).
 
 ```sh
-rad-convert ~/models/LiquidAI/d1-3B -o d1-3b-bf16.rad --set decision.type=d1
+rad-convert /srv/models/LiquidAI/d1-3B -o d1-3b-bf16.rad --set decision.type=d1
 radiance --model d1-3b-bf16.rad --port 8000
 
 curl -s localhost:8000/v1/systemone -H 'Content-Type: application/json' -d '{
@@ -1805,7 +1897,7 @@ curl -s localhost:8000/v1/systemone -H 'Content-Type: application/json' -d '{
                 "criteria": ["Can wait", "Today", "Blocking the customer now"]}}}'
 ```
 
-The answer is an object of the same names, in the same order:
+The answer is an object with the same names, in the same order:
 
 ```
 {"answers": {
@@ -1818,60 +1910,158 @@ The answer is an object of the same names, in the same order:
  "usage": {"input_tokens": N, "output_tokens": 0}}
 ```
 
-- **`state`** is required: a string, any JSON value (rendered as indented JSON, keys in the order
-  sent), or `null` with pictures alone.
-- **`questions`** is an object of named questions, answered in the order sent. A question is
-  `type` (`noul`, `choice` — the default — or `score`), `instructions`, and `criteria`: for a
-  `noul` optionally `{"true": ..., "false": ...}`; for a `choice` the options, name to description;
-  for a `score` 2 to 10 level descriptions, lowest first.
-- **`images`** is an array of `data:` URLs, placed ahead of the state. Each picture is first
-  scaled down to at most 1024 x 1024 pixels' area, as d1's runner does, then cut as LFM2-VL's
-  processor cuts it: whole when it is small, else into 512-pixel tiles plus a thumbnail.
-- **`noul`** is P(yes); a `choice` names its most probable option; a `score` is the expected level.
-  Each answer is a softmax over its options' raw logits, an option scoring its best spelling.
-- **`usage.input_tokens`** counts what the model read as d1 counts it: the shared state once and
-  each question's own tail.
+- `state` is required: a string, any JSON value (rendered as indented JSON, keys in the order sent),
+  or `null` with pictures alone.
+- `questions` is an object of named questions, answered in the order sent. A question is `type`
+  (`noul`, `choice` (the default) or `score`), `instructions`, and `criteria`: for a `noul`
+  optionally `{"true": ..., "false": ...}`; for a `choice` the options, name to description; for a
+  `score` 2 to 10 level descriptions, lowest first.
+- `images` is an array of `data:` URLs, placed ahead of the state. Each picture is first scaled down
+  to at most 1024 x 1024 pixels' area, as d1's runner does, then cut as LFM2-VL's processor cuts it:
+  whole when it is small, else into 512-pixel tiles plus a thumbnail.
+- `noul` is P(yes); a `choice` names its most probable option; a `score` is the expected level. Each
+  answer is a softmax over its options' raw logits, an option scoring its best spelling.
+- `usage.input_tokens` counts what the model read as d1 counts it: the shared state once and each
+  question's own tail.
 
-**Several questions read the state once.** The first runs alone and leaves the state's end in the
-prefix cache — its attention blocks and a checkpoint of LFM2's convolutions there — and the rest
-start from it together, each computing only its own question. A single question is one pass of
-the whole prompt, tokenised as one text, as d1 does.
+Several questions read the state once: the first runs alone and leaves the state in the prefix
+cache (attention blocks and a checkpoint of LFM2's convolutions), and the rest start from it
+together. A single question is one pass of the whole prompt, tokenised as one text, as d1 does.
 
-Against d1's own runner in float32, on eight text cases (one and several questions, JSON and long
-log states): every choice and every `input_tokens` equal, worst probability difference 0.0044.
+Against d1's own runner in float32, on eight text cases (one and several questions, JSON and long log
+states): every choice and every `input_tokens` equal, worst probability difference 0.0044.
 
-## 6. Operate it
+### 5.14 Speech to text
+
+A model whose architecture plugin says how it transcribes -- Qwen3-ASR, served as its checkpoint
+ships -- answers OpenAI's `POST /v1/audio/transcriptions`:
+
+```sh
+radiance --model ~/models/Qwen/Qwen3-ASR-1.7B-hf
+
+curl -s http://localhost:8000/v1/audio/transcriptions \
+  -F file=@meeting.wav -F model=qwen3-asr                    # {"text": "...", "usage": {...}}
+curl -s http://localhost:8000/v1/audio/transcriptions \
+  -F file=@clip.mp3 -F language=en -F response_format=text    # the transcript, as plain text
+curl -sN http://localhost:8000/v1/audio/transcriptions \
+  -F file=@clip.flac -F stream=true                           # transcript.text.delta events
+```
+
+The form is OpenAI's: `file` (wav, mp3, flac, ogg, opus, m4a, aac, webm or aiff), `model`,
+`language`, `prompt`, `response_format` and `stream`.
+
+- **`language`** is an ISO 639-1 code or a name the model knows (`en`, `English`); it forces the
+  language, and without it the model says which it heard -- `verbose_json` reports it. A language
+  the model does not know is a 400 that lists the ones it does.
+- **`prompt`** is context for the recognition -- a name, a domain's words -- read as plain text, so
+  no part of it can be taken for one of the model's control tokens.
+- **`response_format`** is `json` (`text` and token `usage`), `text`, or `verbose_json`, which adds
+  the language, the duration and one segment a clip, each with its start and end in seconds. `srt`
+  and `vtt` are refused, and so are word timestamps.
+- **`stream=true`** sends `transcript.text.delta` events as the transcript is written, then one
+  `transcript.text.done` with the whole text and the usage.
+- **`temperature`** must be 0 or absent: the decode is greedy, as the model's reference is.
+
+**A recording longer than one encoder pass (30 seconds for Qwen3-ASR) is cut into clips,** each
+ending at the quietest 100 ms of the last five seconds before the pass would be full, so the cuts
+land in pauses. The clips run in waves of up to eight (fewer when `--max-queued-requests` admits
+fewer), each wave prepared when it starts, and their transcripts are joined with a space. A
+request holds its wave's admission places from its first wave to its last, so it is refused with a
+429 only before it starts. A request takes up to an hour of audio, in a file within
+`--max-body-mib`.
+
+The same model answers `/v1/chat/completions` with an `input_audio` part through a chat template
+that renders the part's marker where the audio goes (`--override-chat-template`); the checkpoint's
+own template renders audio only for content parts of type `audio`, which this server does not hand
+it.
+
+#### Live: `/v1/realtime`
+
+The same model transcribes speech while it is spoken over a WebSocket at `/v1/realtime`, speaking
+OpenAI's realtime transcription protocol, so a client written for OpenAI's works unchanged. The
+client streams audio in and commits each turn; the server answers with the words as they settle
+and a completed transcript for each turn:
+
+| client sends | server answers |
+|---|---|
+| `session.update` (`session.type: "transcription"`), or the beta's `transcription_session.update` | `session.updated` (`session.created` comes first, unasked) |
+| `input_audio_buffer.append` — base64 of 16-bit little-endian mono PCM; a binary frame of the same bytes also works | `conversation.item.input_audio_transcription.delta` as words settle |
+| `input_audio_buffer.commit` — the turn is over | `input_audio_buffer.committed`, then `...transcription.completed` with the turn's whole transcript and its token usage |
+| `input_audio_buffer.clear` | `input_audio_buffer.cleared` |
+
+The session's settings live under `session.audio.input`:
+
+- **`format`** is `{"type": "audio/pcm", "rate": 24000}` as OpenAI's is; 8, 11.025, 12, 16, 22.05,
+  32, 44.1 and 48 kHz are taken as well, and resampled to the model's 16 kHz.
+- **`transcription`**: `language` (or a one-entry `languages`) forces the language, as `language`
+  does on the upload route; `prompt` and `keywords` are context; `delay` -- `minimal`, `low`,
+  `medium` (the default), `high`, `xhigh` -- trades how soon a word settles for how sure it is.
+- **`turn_detection`** is `null` (the default, as for OpenAI's live models: the client commits
+  each turn) or `{"type": "server_vad", "threshold", "prefix_padding_ms", "silence_duration_ms"}`,
+  which ends a turn at each pause the server hears, with `speech_started` / `speech_stopped`
+  events around it. `semantic_vad` is refused.
+
+**How words settle.** The encoder hears a clip whole, so a turn in progress is heard again from its
+start each time another half second of audio has come in: one short pass, held to the words the
+earlier passes settled and decoding only what follows them. Each pass settles its reply but for the
+last few tokens -- the ones the end of the audio can still change -- and a settled word is never
+taken back: the deltas, joined, are the start of the completed transcript. The words not yet
+settled go out as `radiance.input_audio_transcription.tentative` (`item_id`, `text`), which each
+pass replaces; it is not an OpenAI event, and a client that does not know it ignores it. On
+LibriSpeech streamed at real time, the first word shows half a second into the audio, a word
+settles a median 1.5 s after it first shows (2 s at the 90th percentile), and a turn's completed
+transcript arrives about 0.1 s after its commit -- the same text the upload route gives the same
+audio.
+
+A turn that reaches one encoder pass -- 30 seconds -- is committed at the quietest point of its
+last five seconds, and the rest goes on as the next turn; nothing settles in those five seconds, so
+no word heard after the cut has already gone out as the turn's.
+
+**Limits.** A server holds as many sessions as `--max-num-seqs`. Each runs one pass at a time and
+holds one admission place (`--max-queued-requests`) for its whole life; a session refused either
+way gets an `error` event and a 1013 close. A message is at most 2 MiB; a larger one closes the
+socket unread. A session that falls behind its audio is closed with a `buffer_overflow` error and a
+1008 close: more than 16 MiB of messages it has not taken in, or committed turns waiting for their
+transcript beyond 64 of them or 120 s of audio.
+
+With `--api-key`, a socket carries the key as `Authorization: Bearer`, or -- from a browser, which
+cannot set a header on one -- as the subprotocol `openai-insecure-api-key.` beside `realtime`,
+as OpenAI's browser clients send it. With `--no-cors`, a page from another origin may not open the
+socket.
+
+---
+
+## 6. Operation
 
 ### 6.1 The dashboard
 
-Open `http://:/` in a browser. Three tabs:
+Open `http://:/` in a browser. It has three tabs.
 
-**Dashboard** — the live strip across the top (decode step time, decode and prefill throughput,
+**Dashboard**: the live strip across the top (decode step time, decode and prefill throughput,
 requests in flight, KV cache in VRAM, draft acceptance), then cards for the batch, memory and
 interconnect, and the expert plane.
 
-The **KV cache** meter splits what it is holding into two segments:
+The KV cache meter splits what it holds into two segments:
 
 ```
-KV cache   3.3 GiB / 4.5 GiB · 390.1k tok · 75.5%
+KV cache   3.3 / 4.5 GiB  ·  75.5%
 ▓▓░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
-20.8k tok in flight · 369.3k held for the next turn
+20.8k tok read by running requests  ·  369.3k kept for reuse
 ```
 
-The full-strength segment is live requests; the ghost segment is **prefix cache** — finished turns
-kept so the next turn need not re-prefill. Held is not a second pool: it gives way the moment a
-live request needs it. A high held figure with a high hit rate is the cache doing its job, not a
-leak. Both segments take their warning colour from the *total* fill, since what causes preemption
-is the pool being full.
+The full-strength segment is context running requests are reading; the dim segment is prefix cache,
+finished turns kept for reuse, which gives way the moment a live request needs it. A large kept
+figure with a high hit rate is the cache working, not a leak. Both segments take their warning colour
+from the total fill, since a full pool causes preemption.
 
-**Sessions** — one row per stored conversation: how many tokens, which tier it is in, and whether
-its linear half is still reachable. Sizes **overlap and cannot be added up**: two sessions sharing
-a system prompt share the blocks for it, which is the whole point of a prefix cache.
+**Sessions**: one row per stored conversation: how many tokens, which tier it is in, and whether its
+linear half is still reachable. Sizes overlap and cannot be added: two sessions sharing a system
+prompt share its blocks.
 
-On a hybrid model, a session with blocks but no reachable snapshot reuses **zero** tokens — the
-scheduler clamps reuse to the last linear checkpoint. That verdict is the headline of the tab.
+On a hybrid model, a session with blocks but no reachable snapshot reuses zero tokens, because the
+scheduler clamps reuse to the last linear checkpoint. That verdict is the tab's headline.
 
-**Model** — the resolved graph: every op, which library serves it, and what did not resolve.
+**Model**: the resolved graph: every op, which library serves it, and what did not resolve.
 
 ### 6.2 The JSON behind it
 
@@ -1883,55 +2073,58 @@ curl -s localhost:8000/server_info | jq    # model, cards, KV, draft depth, wire
 curl -s localhost:8000/diagnostics | jq    # the startup report, hardware read again now (§7.1)
 ```
 
-`/server_info` is the operator's first question asked of a process that is already running: which
-model, on how many cards, with how much KV, drafting how deeply, over which wire. All of it is in
-the startup log too — but a startup log is on a machine, in a file, from a process that may have
-been restarted since.
+`/server_info` reports what a running process serves: the model, the cards, the KV cache, the draft
+depth and the wire, as the startup log does.
 
 Its `request_defaults` object says what a request that leaves a field out is served with: every
-sampler field, `max_tokens`, `reasoning_effort`, `reasoning_effort_map`, `chat_template_kwargs` and
-`reasoning_format`, under the request's own spelling of each. `capabilities.reasoning_efforts`
-lists the efforts the chat template takes, or is `null` when it takes any. `server.default_max_tokens` is `null` for `auto`, and
-`server.max_tokens_cap` is `null` when there is none.
+sampler field, `max_tokens`, `reasoning_effort`, `reasoning_effort_map`, `thinking_token_budget`,
+`chat_template_kwargs` and `reasoning_format`, under the request's own spelling of each.
+`capabilities.reasoning_efforts` lists the efforts the chat template takes, or is `null` when it takes
+any. `server.default_max_tokens` is `null` for `auto`, and `server.max_tokens_cap` is `null` when
+there is none.
 
 ### 6.3 Metrics
 
-`GET /metrics` is Prometheus text. Two families:
+`GET /metrics` is Prometheus text, in two families.
 
-**`vllm:` — the compatibility set**, so existing dashboards work: `num_requests_running`,
+**`vllm:`**, the compatibility set, so existing dashboards work: `num_requests_running`,
 `num_requests_waiting`, `num_preemptions_total`, `gpu_cache_usage_perc`, `kv_cache_usage_perc`,
 `gpu_prefix_cache_hit_rate`, `prompt_tokens_total`, `generation_tokens_total`,
 `time_to_first_token_seconds`, `time_per_output_token_seconds`, `inter_token_latency_seconds`,
 `request_prompt_tokens`, `request_generation_tokens`, `request_success_total`, …
 
-**`radiance:` — what this engine actually has**:
+**`radiance:`**, this engine's own:
 
 | | |
 |---|---|
 | `engine_steps_total`, `_decode_total`, `_prefill_total`, `_mixed_total` | step counts by kind |
-| `engine_step_seconds_total`, `_decode_total` | **the honest step time denominator** |
+| `engine_step_seconds_total`, `_decode_total` | step time, the denominator for per-step figures |
 | `decode_tokens_total`, `prefill_tokens_total` | |
 | `decode_tokens_per_second`, `prefill_tokens_per_second` | |
 | `draft_tokens_total`, `draft_accepted_total`, `draft_acceptance_ratio` | |
 | `draft_position_reached_total`, `draft_position_accepted_total`, `draft_position_acceptance_ratio` | acceptance by position: the two counters over any window, the ratio since start |
 | `draft_refills_total`, `draft_refill_tokens_total` | prefix hits ended a drafter window early, and the tokens recomputed (§4.6) |
-| `decode_rows_unspeculated_total` | rows that never drafted at all |
+| `decode_rows_unspeculated_total` | rows that never drafted |
 | `draft_depth_adaptive`, `draft_verify_depth_total{depth}` | the adaptive window's mean over the running sequences, and verifies by the drafts they carried; only with `--draft-window adaptive` (§4.6) |
+| `engine_prefill_chunks_capped_total` | prefill chunks held back to share a step (§4.5) |
+| `engine_steps_held_total` | decode-only steps `--prefill-interleave` ran between chunks (§4.5) |
 | `attn_cached_tokens_total`, `linear_cached_tokens_total` | prefix reuse, both halves |
 | `linear_checkpoints_written_total`, `linear_prefix_cache_hit_rate` | |
 | `prefix_cache_evictions_total`, `prefix_cache_ckpt_evictions_total` | |
-| `prefix_cache_expired_total`, `prefix_cache_ckpt_expired_total` | what `--prefix-cache-ttl` took (§4.8) |
+| `prefix_cache_ckpt_evictions_by_reason_total{reason}`, `prefix_cache_ckpt_refused_total` | snapshots released by `--checkpoint-policy` (`retention`) or as the least recently used of a full store (`store_full`); checkpoints not written for want of a slot |
+| `prefix_hit_cuts_total{reason}`, `prefix_hit_cut_tokens_total` | admissions whose hit reused nothing (`no_snapshot`, `windowed_group`, `adopt_failed`), and the checkpoint shortfall: cached prompt tokens computed again because the hit resumed at a snapshot below it. `/stats` and `/sessions` carry the same counts; `RADIANCE_LOG=debug` logs each eviction and each cut hit |
+| `prefix_cache_expired_total`, `prefix_cache_ckpt_expired_total` | what `--prefix-cache-ttl` removed (§4.8) |
 | `num_requests_preempted` | |
 | `http_queue_depth`, `http_responses_total`, `http_admission_rejected_total` | |
 | `client_disconnect_total`, `stream_overflow_total` | |
 
-Two traps worth naming:
+Two pitfalls:
 
-- **`draft_acceptance_ratio` is conditional on having drafted.** It reads healthy while
-  tokens-per-step collapses. The quantity that separates the two is blocks per step —
-  `draft_tokens_total / depth` over `engine_steps_decode_total`. `scripts/mcdecl.sh` measures it.
-- **Step time is not wall-clock over steps.** Use `engine_step_seconds_decode_total /
-  engine_steps_decode_total`, which charges only decode. Wall-clock charges idle and prefill to it.
+- `draft_acceptance_ratio` is conditional on having drafted, so it can stay high while tokens per
+  step collapse. Blocks per step (`draft_tokens_total / depth` over `engine_steps_decode_total`)
+  separates the two; `scripts/mcdecl.sh` measures it.
+- Step time is not wall-clock over steps. Use `engine_step_seconds_decode_total /
+  engine_steps_decode_total`, which charges only decode; wall-clock also charges idle and prefill.
 
 `deploy/grafana/radiance.json` charts both families over time, on Prometheus or VictoriaMetrics.
 
@@ -1941,15 +2134,15 @@ Two traps worth naming:
 radiance --model m.rad --live
 ```
 
-Cards, throughput, draft acceptance and the expert plane, redrawn in place. **Redirected it prints
-one greppable `key=value` line instead**, so it is usable from a script:
+Cards, throughput, draft acceptance and the expert plane, redrawn in place. Redirected, it prints one
+greppable `key=value` line instead, for scripts:
 
 ```sh
 radiance --model m.rad --live >> serve.log 2>&1
 ```
 
-The step counter is the field that tells a stalled loop from an idle one: throughput decays toward
-zero on its own, but a step count frozen between two draws means the loop itself stopped.
+The `step` field tells a stalled loop from an idle one: throughput decays towards zero on its own,
+but a step count frozen between two draws means the loop stopped.
 
 ### 6.5 Logging
 
@@ -1961,28 +2154,25 @@ radiance --model m.rad -vv                    # same as trace
 
 ### 6.6 Security
 
-**There is no TLS, and without `--api-key` there is no authentication.** CORS is on, so a page on
-any origin can call the API from a browser; `--no-cors` turns it off.
+There is no TLS, and without `--api-key` there is no authentication. CORS is on, so a page on any
+origin can call the API from a browser; `--no-cors` turns it off.
 
 ```sh
 radiance --model m.rad --api-key "$KEY"
 ```
 
 With a key, every request must carry `Authorization: Bearer KEY` (or Anthropic's `X-Api-Key: KEY`)
-or it is answered 401 — `/tokenize` and `/server_info` included, since they hand out the
-vocabulary, the chat template and the configuration. Three paths are exempt: `/health` (and
-`/v1/health`) and `/ping`, because a load balancer cannot carry a bearer token and an
-authenticated probe is a server that reports itself down, and the dashboard page itself (`/`,
-`/dashboard`), which holds no data — on a 401 it shows a key field, keeps the key in the browser's
-storage and sends it on every fetch of data it makes.
+or it is answered 401, `/tokenize` and `/server_info` included. Exempt are `/health`, `/v1/health` and
+`/ping`, because load balancers cannot send a bearer token, and the dashboard page (`/`,
+`/dashboard`), which holds no data: on a 401 it asks for the key, keeps it in the browser's storage
+and sends it on every data fetch.
 
-Without a key, `/diagnostics` answers only a client on the same machine (a loopback address) and
-every other one 403: it describes the host — kernel, boot parameters, PCI layout, memory limits —
-and not just the model. Read it with `curl localhost:8000/diagnostics` on the machine, or start
-the server with `--api-key` to read it from elsewhere.
+Without a key, `/diagnostics` answers only loopback clients (others get 403), because it describes
+the host: kernel, boot parameters, PCI layout, memory limits. Read it on the machine, or start the
+server with `--api-key`.
 
-The key is checked, not encrypted: on any network you do not control, bind to localhost and put a
-TLS-terminating reverse proxy in front:
+The key is not encrypted in transit. On a network you do not control, bind to localhost behind a
+TLS-terminating reverse proxy:
 
 ```sh
 radiance --model m.rad --host 127.0.0.1 --port 8000 --api-key "$KEY"
@@ -1990,46 +2180,40 @@ radiance --model m.rad --host 127.0.0.1 --port 8000 --api-key "$KEY"
 
 ### 6.7 Restarting and stopping
 
-Nothing here is a daemon; run it under systemd, a supervisor or `nohup`. `scripts/fnstop.sh` stops
-a running server and waits for the process to actually go — which matters, because VRAM is not
-released until it does.
+radiance is not a daemon; run it under systemd, a supervisor or `nohup`. `scripts/fnstop.sh` stops a
+running server and waits for the process to exit, which matters because VRAM is not released until
+it does.
 
 ---
 
-## 7. When something goes wrong
+## 7. Troubleshooting
 
-### 7.1 Start with the startup report
+### 7.1 The startup report
 
-The last thing startup prints before `serving on` is one block, `STARTUP REPORT`, in three parts.
-A startup that stops prints it too, after the error, with what it had resolved by then, and ends
-it with an `E` line that repeats the error, so the tail of the log still shows it. It is the part
-of a log to paste into an issue.
+The last block startup prints before `serving on` is `STARTUP REPORT`. A startup that stops prints
+it too, after the error, with what it had resolved, and ends with an `E` line repeating the error. It
+is the part of a log to paste into an issue. Its sections:
 
-- **CONFIGURATION** lists every option the command line takes, from the same table `--help`
-  prints. Each line shows the value in force and where it came from: `default`, `command line`,
-  an environment variable, or `auto`. An `auto` line carries the reason under it: the drafter's
-  depth, where the embedding and the n-gram table went and why, the VRAM split, the placement
-  strategy, and each sampler default with the file it came from, or the built-in default the
-  file left it at. `--api-key` shows only `set` or `not set`.
-- **ENVIRONMENT** names the `RADIANCE_*` variables that are set (§8). It shows only the names,
-  never the values.
+- **CONFIGURATION**: every option `--help` lists, with the value in force and its source
+  (`default`, `command line`, an environment variable, or `auto`). An `auto` line carries the reason
+  under it: the drafter's depth, where the embedding and n-gram table went, the VRAM split, the
+  placement strategy, each sampler default and the file it came from. `--api-key` shows only `set` or
+  `not set`.
+- **ENVIRONMENT** names the `RADIANCE_*` variables that are set (§8), never their values.
 - **DERIVED** shows what startup worked out that no single option states: the VRAM split with the
-  budget report under it, the weights by tier, the KV cache, and the kernel libraries selection
-  used, with the attention rows by name.
-- **HARDWARE** reads the machine from `/proc` and `/sys`, the same files inside the image. It
-  covers the CPU, RAM, swap, kernel, container, cgroup and memlock limits, transparent huge
-  pages, the IOMMU mode from the cards' own groups, TTM's page limit (`ttm.pages_limit`) and
-  `cwsr_enable`. Each display device gets its gfx target, VRAM and BAR, and its PCIe link **at
-  every hop up to the root port**. A card with a switch on it reports its own link at full speed
-  whatever the slot does, so a root port parked at half speed only shows here. The block also
-  shows the card's PCIe power levels, its power cap against its default and its maximum, any
-  voltage offset, and its runtime power management. The cgroup limit is the tightest one from
-  the process's own cgroup up to the root.
-- **FINDINGS** lists warnings first, then notes. Each says what was seen, what it costs, and the
-  fix. Every warning is also printed as a `W` line of its own.
+  budget report under it, the weights by tier, the KV cache, and the kernel libraries selection used,
+  with the attention rows by name.
+- **HARDWARE** reads the machine from `/proc` and `/sys` (the same files inside the image): CPU, RAM,
+  swap, kernel, container, cgroup (the tightest limit up to the root) and memlock limits, transparent
+  huge pages, the IOMMU mode from the cards' groups, `ttm.pages_limit` and `cwsr_enable`. Each display
+  device gets its gfx target, VRAM and BAR; its PCIe link at every hop up to the root port (a card
+  with an on-board switch reports full speed whatever the slot does); its PCIe power levels; its power
+  cap against default and maximum; any voltage offset; and its runtime power management.
+- **FINDINGS** lists warnings, then notes. Each says what was seen, what it costs, and the fix. Every
+  warning is also printed as a `W` line of its own.
 
 ```
-I STARTUP REPORT -- radiance 1.6.0
+I STARTUP REPORT -- radiance 1.7.0
 I CONFIGURATION -- every option, the value in force, and where it came from
 I   --model                            /models/flashnext.rad                       [command line]
 I   --tp                               2                                           [command line]
@@ -2049,12 +2233,12 @@ I        why: every copy between host memory and the card ... cross this link, s
 I        fix: a link stuck one level down after long uptime has been cleared by a reboot; ...
 ```
 
-A PCIe link at rest parks at its lowest speed, so a link below its maximum is only a finding when
-the card was busy as it was read. At startup the cards are mostly idle. `GET /diagnostics` reads
-the hardware again and runs the same checks, so call it during a long prefill to see the links and
-power levels under load. A reading is reused for a second, and the power-management files (DPM
-levels, power caps, busy percentage) are read only for the cards the server runs on: the driver
-answers them from the card's firmware under a lock, and wakes a sleeping card to do it.
+A PCIe link at rest parks at its lowest speed, so a link below its maximum is a finding only when the
+card was busy as it was read; at startup the cards are mostly idle. `GET /diagnostics` reads the
+hardware again and runs the same checks, so call it during a long prefill. A reading is reused for a
+second, and the power-management files (DPM levels, power caps, busy percentage) are read only for
+the cards the server runs on, because the driver answers them from firmware under a lock and wakes a
+sleeping card to do it.
 
 ```sh
 curl -s -H "Authorization: Bearer $KEY" localhost:8000/diagnostics | jq '.findings'
@@ -2062,22 +2246,22 @@ curl -s -H "Authorization: Bearer $KEY" localhost:8000/diagnostics | jq '.findin
 
 ### 7.2 Messages and what they mean
 
-| What you see | What it means | What to do |
+| Message | Meaning | Action |
 |---|---|---|
-| `N declared op(s) resolve to libref` and the engine exits | No kernel library covers those ops on this card. Serving from the reference implementation would be orders of magnitude slow with nothing to say so | Install a library that covers them, or accept the cost with `--debug-accept-reference-kernels`. The named ops are exactly what a new library must implement |
-| `did not fit` at load, naming a weight class or a KV group | The split left one side too little. A routed expert cannot be served from the file tier, so it has nowhere else to go | If **weights** did not fit: add or raise `--host-pool-mib`, or lower `--max-model-len` or `--max-num-seqs`. If a **KV group** did not fit: `--kv-cache-dtype fp8`, or a larger `--host-pool-mib` (RAM permitting), which takes experts off the card. The plan report names which, by class, with the shortfall |
-| `chat is 501` in the startup line | The container carries no chat template | Re-convert with `--tokenizer`, and check that a `chat_template.jinja` sits beside `tokenizer_config.json` in the checkpoint. Meanwhile use `/v1/completions` |
+| `N declared op(s) resolve only to a reference implementation (libref)` and the engine exits | No kernel library covers those ops on this card (§2) | Install a library that covers them, or accept the cost with `--debug-accept-reference-kernels`. The named ops are what a new library must implement |
+| `DID NOT FIT` in the placement plan, naming a weight class, or `KV group '...': ... did not fit the KV pool` | The split left one side too little. A routed expert cannot be served from the file tier, so it has nowhere else to go | If weights did not fit: add or raise `--host-pool-mib`, or lower `--max-model-len` or `--max-num-seqs`. If a KV group did not fit: `--kv-cache-dtype fp8`, or a larger `--host-pool-mib` (RAM permitting), which takes experts off the card. The plan report names which, by class, with the shortfall |
+| `chat is 501` in the `serving on` line | The container carries no chat template | Re-convert with `--tokenizer`, and check that a `chat_template.jinja` sits beside `tokenizer_config.json` in the checkpoint. Meanwhile use `/v1/completions` |
 | `does not read '' encoded ` at startup | No loaded kernel takes that weight's encoding for the op that reads it | Convert with a recipe that writes an encoding a loaded kernel reads, or load the library that reads it |
-| Prefix hit rate 0% and every turn re-prefills | The KV pool cannot hold the live sessions, so the cache evicts what the next turn wanted | The cache already has everything the experts can do without: a larger `--host-pool-mib` (RAM permitting), `--kv-cache-dtype fp8`, or fewer/shorter sessions. See §4.3 |
-| The server dies with no log line, on a request it had been serving fine | A kernel whose code object had never been loaded could not be: the card has no room left. HIP faults inside the launch rather than returning an error, so there is nothing to print | A card left with too little room for a first launch — see §4.3. Set `--gpu-headroom-mib` to the value the startup warning names. `coredumpctl info` names the kernel; `AMD_LOG_LEVEL=1` prints `HSA_STATUS_ERROR_OUT_OF_RESOURCES` just above the fault |
-| KV in VRAM stays high with one session and nothing moves | The idle tiers are **off** — they are sized, and with no size nothing is copied | Pass `--prefix-cache-mib N` |
-| `out of memory` / `the carve reserved N of address space and the card would not back it` | Something else is holding VRAM | Check with `rocm-smi`; stop the other process. The budget is stated before allocation, so the log says what it asked for |
-| `pool allocation refused` with `backing allocation of … refused` on the second card, after the first card's pools succeeded | The VRAM budget is measured before any rank allocates. A card that refuses its weights pool lost that memory to another process in between (the line below the refusal says how much is free now). A refused `host_pool` is pinned memory: **every rank pins its own `--host-pool-mib`**, so `--tp 2` pins it twice, and the amdgpu driver caps what every process together pins at RAM less 1/64 and 1.5 GiB. The pool is locked user memory, which `ttm.pages_limit` does not count | Stop the other process (`rocm-smi --showpids`). For the host pool, keep `--tp` × `--host-pool-mib` under both the cap and the available RAM the refusal names. `amdgpu.no_system_mem_limit=1` lifts the driver's cap, but not the RAM |
-| `host_pool: backing allocation of … refused: rad_dev_alloc(…): locking piece K of N`, and `failed to pin userptr` in `journalctl -k` | The IOMMU would not DMA-map one piece of the pinned host pool. Pinned host memory is locked in pieces of at most 1 GiB because an Intel VT-d host in scalable mode was seen to refuse any single pin above about 2.5 GiB; a piece failing means this machine refuses smaller pins still, or a total its IOMMU will not map | Keep IOMMU translation on: `iommu=pt` lets every pin through but on that host also removed peer access between the cards, which moves every all-reduce onto the slower host-memory path. Report the kernel version, the IOMMU mode and the refusal line |
-| `a synchronisation has waited 5 s` naming a kernel, then `no queue has advanced`, then `HW Exception … GPU Hang` and a reset in `journalctl -k` (`MES failed to respond to msg=REMOVE_QUEUE`, `MODE1 reset`) | The card stopped running the queue. The kernel named is where it stopped, not necessarily why. The driver resets the whole card, VRAM included, and the engine is aborted. The usual cause is compute wave save/restore being off: the driver evicts a process's queues whenever host memory the card maps is moved under memory pressure, and with `cwsr_enable=0` it cannot preempt a running queue, so the eviction waits for a queue a serve never lets drain. A voltage offset or other clock instability is the other cause seen on R9700s. If the stall line says the queues **advanced**, the wait was long rather than stuck, and nothing is wrong | `cat /sys/module/amdgpu/parameters/cwsr_enable` must print `1` (the startup report warns when it is `0`); set `amdgpu.cwsr_enable=1`, rebuild the initramfs and reboot. Remove any `OD_VDDGFX_OFFSET` (`pp_od_clk_voltage`). A reset puts the power cap, fan curve and voltage offset back to firmware defaults, so re-apply them before every start rather than once at boot. Keep the devcoredump under `/sys/class/drm/card*/device/devcoredump/data`; a reboot loses it. `docker inspect` shows exit code 0 for a container Docker has already restarted, which says nothing about how the old process ended |
-| `--draft-model is not implemented` | This engine loads its drafter from the container | `rad-convert --draft-model DIR` at conversion time |
-| `context_length_exceeded` on a request | The **prompt alone** does not fit the context. `max_tokens` is clamped rather than refused, so this fires only when there is no room left to generate at all | Shorten the prompt by the number of tokens the message names, or raise `--max-model-len` if the model allows it |
-| `unknown option '--foo'` and the engine exits | Deliberate. A typo in a budget flag is the difference between the plan you asked for and one the planner invented | Check `radiance --help` |
+| Prefix hit rate 0% and every turn re-prefills | The KV pool cannot hold the live sessions, so the cache evicts what the next turn wanted | The cache already has everything the experts can spare: a larger `--host-pool-mib` (RAM permitting), `--kv-cache-dtype fp8`, or fewer or shorter sessions (§4.3) |
+| The server dies with no log line, on a request it had been serving fine | A kernel's first launch could not load its code object for lack of VRAM; HIP faults inside the launch instead of returning an error | Set `--gpu-headroom-mib` to the value the startup warning names (§4.3). `coredumpctl info` names the kernel; `AMD_LOG_LEVEL=1` prints `HSA_STATUS_ERROR_OUT_OF_RESOURCES` just above the fault |
+| KV in VRAM stays high with one session and nothing moves | The host tier is off: it is sized, and without a size nothing is copied | Pass `--prefix-cache-mib N` |
+| `out of memory` / `the carve reserved N of address space and the card would not back it` | Something else is holding VRAM | Check with `rocm-smi` and stop the other process. The budget is stated before allocation, so the log says what it asked for |
+| `pool allocation refused` with `backing allocation of … refused` on the second card, after the first card's pools succeeded | The VRAM budget is measured before any rank allocates, so a card that refuses its weights pool lost that memory to another process in between (the next line says how much is free now). A refused `host_pool` is pinned memory: every rank pins its own `--host-pool-mib` (twice at `--tp 2`), and the amdgpu driver caps what all processes together pin at RAM less 1/64 and 1.5 GiB. It is locked user memory, which `ttm.pages_limit` does not count | Stop the other process (`rocm-smi --showpids`). For the host pool, keep `--tp` × `--host-pool-mib` under both the cap and the available RAM the refusal names. `amdgpu.no_system_mem_limit=1` lifts the driver's cap, but not the RAM |
+| `host_pool: backing allocation of … refused: rad_dev_alloc(…): locking piece K of N`, and `failed to pin userptr` in `journalctl -k` | The IOMMU would not DMA-map one piece of the pinned host pool. Pinned host memory is locked in pieces of at most 1 GiB because an Intel VT-d host in scalable mode can refuse a single pin above about 2.5 GiB; a failing piece means this machine refuses smaller pins still, or a total its IOMMU will not map | Keep IOMMU translation on: `iommu=pt` lets every pin through, but on such a host it can also remove peer access between the cards, moving every all-reduce onto the slower host-memory path. Report the kernel version, the IOMMU mode and the refusal line |
+| `device: a synchronisation has waited 5 s; the queues:` with the packet each queue is on, then `device: no queue has advanced`, then `HW Exception … GPU Hang` and a reset in `journalctl -k` (`MES failed to respond to msg=REMOVE_QUEUE`, `MODE1 reset`) | The card stopped running the queue; the kernel named is where it stopped, not necessarily why. The driver resets the whole card, VRAM included, and the engine is aborted. The usual cause is compute wave save/restore being off: the driver evicts a process's queues whenever host memory the card maps moves under memory pressure, and with `cwsr_enable=0` it cannot preempt a running queue, so the eviction waits on a queue that never drains. Clock instability (a voltage offset) is the other cause seen on R9700s. If the follow-up line says the queues advanced, the wait was long, not stuck | `cat /sys/module/amdgpu/parameters/cwsr_enable` must print `1` (the startup report warns when it is `0`); set `amdgpu.cwsr_enable=1`, rebuild the initramfs and reboot. Remove any `OD_VDDGFX_OFFSET` (`pp_od_clk_voltage`). A reset restores the power cap, fan curve and voltage offset to firmware defaults; re-apply them before every start. Keep the devcoredump under `/sys/class/drm/card*/device/devcoredump/data`, which a reboot loses. `docker inspect` shows exit code 0 for a container Docker already restarted, whatever ended the old process |
+| `--draft-model is not implemented` | The engine loads its drafter from the container | `rad-convert --draft-model DIR` at conversion time |
+| `context_length_exceeded` on a request | The prompt alone does not fit the context. `max_tokens` is clamped rather than refused, so this fires only when there is no room left to generate | Shorten the prompt by the number of tokens the message names, or raise `--max-model-len` if the model allows it |
+| `unknown option '--foo'` and the engine exits | An unknown flag is an error, so a typo in a budget flag cannot silently change the plan | Check `radiance --help` |
 | Empty `content` and `finish_reason: "length"` on short chat turns | The reasoning spent all of `max_tokens` inside ``; `usage.completion_tokens_details.reasoning_tokens` equals `completion_tokens`. Qwen3.8's default `reasoning_effort` is `xhigh` | `--reasoning-effort medium`, or `"reasoning_effort": "none"` per request; or cap the reasoning with `thinking_token_budget` / `--thinking-token-budget` below `max_tokens` |
 | `401` with `invalid api key` | The server was started with `--api-key` | Send `Authorization: Bearer KEY` (§6.6) |
 
@@ -2086,39 +2270,39 @@ First three things to run when a server will not start:
 ```sh
 rad-info m.rad                            # is the container what you think it is?
 radiance --model m.rad --debug-graph      # does every op resolve?
-rad-kbench --home $RADIANCE_HOME --max-cases 1   # are the kernels correct at all?
+rad-kbench --home $RADIANCE_HOME --max-cases 1   # are the kernels correct?
 ```
 
 ---
 
 ## 8. Environment
 
-**Operator-facing**
+**Operation**
 
 | | |
 |---|---|
-| `RADIANCE_HOME` | where `kernels/`, `architectures/` and `quantizers/` live; a `:`-separated search path, the first home winning. Same as `--radiance-home` |
-| `RADIANCE_KERNELS` | default kernel libraries, comma-separated. Same as `--kernels`, read by the engine *and* every tool, so a plugin validated with `rad-kbench` can be served without editing launchers |
-| `RADIANCE_LOG` | `error` \| `warn` \| `info` \| `debug` \| `trace` |
-| `ROCM_PATH` | where ROCm lives, if not `/opt/rocm` |
-| `HF_TOKEN` | for `scripts/hfget.sh`, and `--model `, on a gated or private repo |
+| `RADIANCE_HOME` | where `kernels/`, `architectures/` and `quantizers/` live; a `:`-separated search path, the first home winning. Same as `--radiance-home`; set but empty is unset |
+| `RADIANCE_KERNELS` | default kernel libraries, separated by `,` or `:`. Same as `--kernels`, read by the engine and every tool by one rule, so a plugin validated with `rad-kbench` serves the same way without editing launchers; set but empty is unset |
+| `RADIANCE_LOG` | `error` \| `warn` \| `info` \| `debug` \| `trace` (default `info`) |
+| `ROCM_PATH` | where ROCm lives, if not `/opt/rocm` (build time) |
+| `HF_TOKEN` | for `scripts/hfget.sh` and `--model ` on a gated or private repo |
 | `XDG_CACHE_HOME` | where `--model ` fetches to without `--download-dir` (`$XDG_CACHE_HOME/radiance/hf`, else `~/.cache/radiance/hf`) |
 
 **Tooling**
 
 | | |
 |---|---|
-| `RADIANCE_TUNE` | pin a kernel's tunable axes instead of reading the tune cache — `op:key=value[,key=value][;op:...]`. For comparing tunings, not for deployment |
+| `RADIANCE_TUNE` | pin a kernel's tunable axes instead of reading the tune cache: `op:key=value[,key=value][;op:...]`. For comparing tunings, not for deployment |
 | `RADIANCE_CALIB_DIR` | where an engine run writes calibration data for a recipe's `gptq calib=DIR` |
 | `RADIANCE_CALIB_TOKENS` | with `RADIANCE_CALIB_DIR`, the tokens the calibration tap accumulates before it writes and switches itself off (default 65536) |
 | `RADIANCE_PROFILE_EVERY` | with `--profile-ops`, dump the per-op table every N steps (default 32) |
 | `RADIANCE_LOG_STEPS` | log one line per step: its phase, sequences, and each one's token count and context (§4.5) |
 
-There is also a family of instruments for engine development — `RADIANCE_DEBUG_*` (residual probes,
-idle scrubs, routing and issue dumps), `RADIANCE_OP_ORACLE*` (named ops checked against `libref` on
-the operands the model issued; `scripts/oracle.sh` drives it) and `RADIANCE_OP_REPEAT` (named ops
-run a second time on the same inputs, to ask whether a kernel is a function of them). They are
-instruments, not features; grep `getenv` if you need one, and read the comment beside it first.
+Engine development has its own instruments: `RADIANCE_DEBUG_*` (residual probes, routing and issue
+dumps), `RADIANCE_OP_ORACLE*` (named ops checked against `libref` on the operands the model issued;
+`scripts/oracle.sh` drives it) and `RADIANCE_OP_REPEAT` (named ops run a second time on the same
+inputs, to check that a kernel is a function of them). They are not features; to use one, find its
+name in the source and read the comment beside it.
 
 ---
 
@@ -2126,11 +2310,11 @@ instruments, not features; grep `getenv` if you need one, and read the comment b
 
 | | |
 |---|---|
-| `spec.md` | the design, and it is binding. Start here for *why* |
+| `spec.md` | the design, and it is binding. Start here for why |
 | [TOOLS.md](TOOLS.md) | every flag of every tool, and the shell harnesses |
 | [PLUGIN.md](PLUGIN.md) | writing a kernel plugin: exports, constraints, hooks, out-of-tree build |
-| [OPS.md](OPS.md) | the conventional op vocabulary. Held to the registries by `ctest -R ops_doc` |
-| [ARCHITECTURES.md](ARCHITECTURES.md) | per-architecture geometry, and the traps that stay plausible when they are wrong |
+| [OPS.md](OPS.md) | the conventional op vocabulary, held to the registries by `ctest -R ops_doc` |
+| [ARCHITECTURES.md](ARCHITECTURES.md) | per-architecture geometry, and the mistakes that stay plausible when they are wrong |
 | [IMPLEMENTATION.md](IMPLEMENTATION.md) | layout, build and conventions for working on the engine |
 | [KERNELS.md](KERNELS.md) | what `rad-kbench` last measured |
 | [QSA.md](QSA.md), [MOE-W4.md](MOE-W4.md) | the sparse-attention indexer; the four-bit expert format |
diff --git a/docs/IMPLEMENTATION.md b/docs/IMPLEMENTATION.md
index 1df30cde..06ad3211 100644
--- a/docs/IMPLEMENTATION.md
+++ b/docs/IMPLEMENTATION.md
@@ -1,22 +1,21 @@
-# Radiance — implementation brief
+# Radiance: implementation brief
 
-Read `spec.md` first; it is the design and it is binding. This file is the mechanical part: who
-owns what, how it builds, and the conventions that keep ten people's code looking like one
-person's.
+`spec.md` is the design and it is binding; read it first. This file covers the mechanical part:
+where things live, how they build, and the conventions every component follows.
 
-## The host backend is the primary target, not a fallback
+## The host backend is a primary target
 
-Everything except the device kernels builds, tests and runs through the **host device backend**:
+Everything except the device kernels builds, tests and runs through the host device backend:
 `cmake` with no ROCm must configure, build, test and run, and `RAD_HIP_FOUND` gates only the HIP
 backend and the device kernels. A machine with no card is a complete development environment for
 the core, the tools, the architecture plugins and `libref`, and the suite runs in full there.
 
-## Layout and ownership
+## Layout
 
 ```
-abi/              THE ABI, and all a plugin compiles against. Frozen — do not edit quietly
+abi/              the ABI, and all a plugin compiles against. Frozen: change it deliberately
 core/rad_internal.h   shared internals: logging, Geometry, constraint matching
-core/util/        logging, error strings, dtype arithmetic, tensor helpers: the bedrock
+core/util/        logging, error strings, dtype arithmetic, tensor helpers
 core/device/      device backends: host, and aql (HSA queues the engine writes; HIP for memory)
 core/plugin/      plugin loader, kernel registry, op schemas, selector, bucket tables
 core/build/       the declare phase: builder, weight manifest, buffer plan, graph dump
@@ -24,33 +23,38 @@ core/runtime/     the run phase: RadCtx, rad_issue, the arena
 core/mem/         pools, slab, KV block manager, prefix cache
 core/sched/       scheduler, RadBatch construction, request lifecycle
 core/place/       placement planner, the mover, the heat engine
-core/sample/      device sampler dispatch + the host reference chain + grammar bitmask
+core/sample/      device sampler dispatch, the host reference chain, grammar bitmask
 core/text/        tokeniser, chat template, tool parsing, detokenisation
 core/mm/          image and video decoding, and the processor that turns frames into patches
+core/gen/         image generation: the request and the pass driver
 core/format/      the .rad reader and writer, safetensors, recipes, the imatrix, the tune cache
 core/server/      HTTP: the OpenAI, Anthropic and llama-server endpoints, /metrics, the dashboard
+core/diag/        the startup report
 core/kld.*        the KL mode: --kld-record / --kld-ref
-core/engine*      the thing that ties them together, and `radiance` the binary
-libref/           every op, naively, correct, host domain: the fallback and the oracle
+core/engine*      the engine that ties them together; core/main.cpp is the `radiance` binary
+libref/           every op, naively and correctly, host domain: the oracle and last resort
 libr4d/           the RDNA4 (gfx12xx) kernel library: kernels, rows, layouts, fusion claims
 libavx/           the same vocabulary in x86 SIMD, host domain: the production host kernels,
-                  built on every x86-64 build because an op placed on the host cannot run on libref
+                  built on every x86-64 build because the engine refuses to serve an op that
+                  resolves only to libref (without --debug-accept-reference-kernels)
 libquant/         the built-in quantisers rad-convert's recipes name: grids, transforms, rtn, gptq
 arch//        one architecture plugin per directory
 tools/            rad-info, rad-kbench, rad-convert, rad-tune, rad-schemas, rad-tokcheck,
                   rad-chatparse, rad-gbnf-check
 cmake/            rad_add_plugin, and the package config an out-of-tree plugin find_package()s
-scripts/          shell harnesses for serving, tracing and profiling a running engine
+scripts/          harnesses for serving, tracing and profiling a running engine
 data/             kernels.rkb and kernels_moe.rkb: recorded references rad-kbench replays with
                   no model. Two, because no one container declares the whole vocabulary.
                   recipes/: the quantisation recipes of the containers this tree serves
 docs/KERNELS.md   what rad-kbench last measured, generated and checked in
-vendor/           llama.cpp lifts, tracked to an upstream commit, patched not edited
+vendor/           llama.cpp lifts tracked to an upstream commit (vendor/UPSTREAM), changed only
+                  through vendor/patches/; nlohmann/json and cpp-httplib
 tests/            ctest
 ```
 
-Each directory has its own `CMakeLists.txt` and each owner writes only inside their own. The
-top-level file already exists; add `add_subdirectory` lines there only if your directory is new.
+Each directory has its own `CMakeLists.txt` and builds only what is inside it. A new top-level
+directory adds its `add_subdirectory` line to the root `CMakeLists.txt`; `arch/CMakeLists.txt`
+adds every architecture directory itself.
 
 ## Build
 
@@ -60,15 +64,16 @@ cmake --build build -j
 ctest --test-dir build --output-on-failure
 ```
 
-Your directory must compile and its tests must pass **before you report done**. A component that
-does not build is not a component.
+A change is done when its directory compiles and its tests pass.
 
 ## Conventions
 
-**No Python in the engine, its tools, its build or its test suite.** This is the project's
-founding constraint — `spec.md` opens with it. Tests are C++ and CTest. The one Python file under
-`tests/`, `mkgolden.py`, is run by hand against transformers to regenerate the reference numbers in
-`tests/mm_golden.h`; nothing in the build or the suite calls it.
+**No Python in the engine, its tools, its build or its test suite.** `spec.md` opens with this
+constraint. Tests are C++ and CTest. The Python files in the tree are run by hand and nothing in
+the build or the suite calls them: `tests/mkgolden.py` and `tests/mklfm2golden.py` regenerate the
+reference numbers in `tests/mm_golden.h` and `tests/lfm2_golden.h` from transformers;
+`tools/pad_tp.py` and `tools/pad_verify.py` pad a checkpoint for a tensor-parallel width and check
+the result; `scripts/cardclock.py` monitors card clocks.
 
 **C ABI at plugin boundaries, C++20 inside.** `abi/` is C and must stay compilable as C.
 Everything under `core/` is C++20 and may use the standard library freely.
@@ -76,32 +81,30 @@ Everything under `core/` is C++20 and may use the standard library freely.
 **Errors are values.** Return `RAD_OK` or a negative `RAD_E_*`. Do not throw across a function
 that a plugin or the run phase can call. `fatal()` is for broken invariants only.
 
-**Nothing unimplemented returns success.** A function you have not written yet returns
-`RAD_E_UNSUPPORTED` and logs once at Warn with its own name. A stub that returns 0 is how a
-project ends with fluent wrong output and no way to bisect it (`spec.md` §17).
+**Nothing unimplemented returns success.** An unwritten function returns `RAD_E_UNSUPPORTED` and
+logs once at Warn with its own name. A stub that returns 0 produces fluent wrong output with no way
+to bisect it (`spec.md` §17).
 
-**No allocation and no synchronisation on the step path.** The arena is sized at declare. If you
-find yourself wanting a `malloc` inside `rad_arch_step` or inside the scheduler's per-step work,
-that is a declare-phase bug.
+**No allocation and no synchronisation on the step path.** The arena is sized at declare. A
+`malloc` needed inside `rad_arch_step` or the scheduler's per-step work is a declare-phase bug.
 
-**`rad_memset_async` refuses `RAD_MEM_HOST` on a card, and the host backend cannot reproduce that.**
+**`rad_memset_async` refuses `RAD_MEM_HOST` on a card; the host backend cannot reproduce that.**
 `RAD_MEM_HOST` is pageable memory the GPU has never been shown, so the device backend returns
-`RAD_E_UNSUPPORTED` naming the rule (`core/device/aql.cpp`). On the host backend every kind of
-memory is the same memory, so a memset added to a path that runs on host memory passes in a no-ROCm
-build and fails on a card. Use `RAD_MEM_HOST_PINNED` or `RAD_MEM_HOST_MAPPED`, or memset on the
-host. `rad_memcpy_async` accepts pageable memory but bounces it through pinned memory and WAITS,
-so a pageable copy on the step path is a host stall; `aql_pageable_bytes()` counts them.
+`RAD_E_UNSUPPORTED` naming the rule (`core/device/aql.cpp`). On the host backend all memory kinds
+are the same memory, so a memset on host memory passes in a no-ROCm build and fails on a card. Use
+`RAD_MEM_HOST_PINNED` or `RAD_MEM_HOST_MAPPED`, or memset on the host. `rad_memcpy_async` accepts
+pageable memory but bounces it through pinned memory and waits, so a pageable copy on the step path
+is a host stall; `aql_pageable_bytes()` counts them.
 
 **Kernel plugins launch with `hipLaunchKernel` and the engine dispatches them.** On a card every
-stream is an HSA queue the engine owns and writes AQL packets into itself (`core/device/aql.cpp`);
-the executable defines `hipLaunchKernel` and HIP's kernel registration hooks, so a plugin built by
-hipcc needs nothing special. What a plugin must NOT do with an engine stream is call any other HIP
-stream API: `hipEventRecord` and `hipStreamWaitEvent` are refused by name, and anything else would
-be handed to HIP as a stream HIP does not own. Use `rad_event_*` and `rad_memcpy_async`.
+stream is an HSA queue the engine owns and writes AQL packets into (`core/device/aql.cpp`). The
+executable defines `hipLaunchKernel` and HIP's kernel registration hooks, so a plugin built by
+hipcc needs nothing special. A plugin must not call any other HIP stream API on an engine stream:
+`hipEventRecord` and `hipStreamWaitEvent` are refused by name, and anything else would hand HIP a
+stream it does not own. Use `rad_event_*` and `rad_memcpy_async`.
 
-**Comments explain the decision, not the syntax.** The spec's voice: say why this and not the
-obvious alternative, and name the cost when there is one. `libr4d/r4d_rows.cpp` is the model.
-Do not write `// increment i`.
+**Comments explain the decision, not the syntax.** Say why this and not the obvious alternative,
+and name the cost when there is one. `libr4d/r4d_rows.cpp` is the model.
 
 **Naming.** `rad_` prefix on everything with external linkage. Files are named for what they
 provide. `snake_case` for functions and variables, `PascalCase` for types.
diff --git a/docs/KERNELS.md b/docs/KERNELS.md
index 302662f4..54f765ab 100644
--- a/docs/KERNELS.md
+++ b/docs/KERNELS.md
@@ -1,1821 +1,4346 @@
 # radiance kernel libraries
 
-Generated by `rad-kbench`. Every kernel every loaded library supplies, run on the same bytes
-and timed in the same pass. Correctness, completeness and speed are three readings of one
-run, because they are not separable: a library that is fastest on the ops it has and absent
-on the rest is slower end to end than one that is uniformly mediocre.
+Generated by `rad-kbench`. Every kernel of every loaded library ran on the same inputs and each
+case that passed was timed in the same run, so correctness, completeness and speed come from one run
+(the Speed section says how the times were taken).
 
-- fixture: `data/kernels.rkb`, 537 case(s) recorded 2026-09-21 from `q38-27b-fp8-df2.rad`
-- libraries: `libr4d@0.5.0 libref@0.1.0`
-- reference: `libref` -- every correctness number is relative to it, so it has none of its own
-- 1067 case(s) checked, 1067 passed, 0 failed, 7 skipped, 0 capped; worst rel_l2 4.270e-03
+- fixture: `data/kernels.rkb`, 741 case(s) recorded 2026-10-15 from `qwen3.8-27b-fp8.rad`
+- libraries: `libavx@0.1.0 libr4d@0.5.0 libref@0.1.0`
+- reference: `libref`; every correctness number is relative to it, so it has none of its own
+- 2202 case(s) checked, 2202 passed, 0 failed, 7 skipped, 0 capped; worst rel_l2 4.270e-03
+- 734 reference result(s) taken from the cache; every comparison ran
 
 ## Libraries
 
-`ops` is how many of the 89-op vocabulary this library has a row for, and `graph` how many of
-the 32 ops THIS container's declared graph asks for. The two differ on purpose: a library can
-be complete for one model and full of holes for the next.
+`ops` is how many of the 147-op vocabulary this library has a row for, and `graph` how many of
+the 43 ops this container's declared graph asks for.
 
 `rows` is how many kernel rows the library declares and `run` how many of them a case in this
-pass actually reached. The gap is the real coverage number: a library can be complete for the
-vocabulary, pass everything it ran, and still have rows nothing has executed since they were
-written -- see **Rows nothing ran** below for which.
+pass reached; the Rows nothing ran section lists the rest.
 
 | library | version | domain | rows | run | ops | graph | cases | pass | fail | worst rel_l2 | median us |
 |---|---|---|---|---|---|---|---|---|---|---|---|
-| `libr4d` | 0.5.0 | device+host | 118 | 36 of 118 | 79 of 89 | 32 of 32 | 537 | 537 | 0 | 4.27e-03 | 12.96 |
-| `libref` (oracle) | 0.1.0 | host | 70 | 31 of 70 | 70 of 89 | 32 of 32 | 530 | 530 | 0 | 0.00e+00 | - |
+| `libavx` | 0.1.0 | host | 100 | 42 of 100 | 100 of 147 | 43 of 43 | 734 | 734 | 0 | 9.01e-04 | 78.91 |
+| `libr4d` | 0.5.0 | device | 287 | 48 of 287 | 142 of 147 | 43 of 43 | 734 | 734 | 0 | 4.27e-03 | 12.78 |
+| `libref` (oracle) | 0.1.0 | host | 123 | 42 of 123 | 123 of 147 | 43 of 43 | 734 | 734 | 0 | 0.00e+00 | - |
 
-Rows declaring an optional hook, which is what separates a library that merely runs from one
-the core can tune, fuse and check against a container:
+Rows declaring an optional hook (tuning, fusion, weight layout):
 
 | library | tunable rows | fusion claims | weight layouts |
 |---|---|---|---|
-| `libr4d` | 33 | 5 | 18 |
+| `libavx` | 0 | 0 | 1 |
+| `libr4d` | 84 | 17 | 35 |
 | `libref` | 0 | 0 | 0 |
 
 ## Rows nothing ran
 
-67 of 188 declared row(s) were reached by a case in this pass.
+132 of 510 declared row(s) were reached by a case in this pass.
 
-`libr4d` -- 82 row(s) not reached:
+`libavx`: 58 row(s) not reached:
 
 | kernel | op |
 |---|---|
+| `avx_act_mul` | `act_mul` |
+| `avx_all_gather` | `all_gather` |
+| `avx_all_reduce` | `all_reduce` |
+| `avx_attn_local_rel` | `attn_local_rel` |
+| `avx_causal_conv1d` | `causal_conv1d` |
+| `avx_clamp` | `clamp` |
+| `avx_conv1d_dw` | `conv1d_dw` |
+| `avx_conv2d` | `conv2d` |
+| `avx_dequant` | `dequant` |
+| `avx_embed_lookup_q` | `embed_lookup_q` |
+| `avx_fill` | `fill` |
+| `avx_gated_had_quant_i8` | `gated_had_quant_i8` |
+| `avx_gdn_conv_prep` | `gdn_conv_prep` |
+| `avx_gdn_conv_recurrent_update` | `gdn_conv_recurrent_update` |
+| `avx_gelu` | `gelu` |
+| `avx_gelu_mul` | `gelu_mul` |
+| `avx_gemm_nt_q_bias` | `gemm_nt_q_bias` |
+| `avx_givens_dense_quant` | `givens_dense_quant` |
+| `avx_givens_rotate` | `givens_rotate` |
+| `avx_gram_accum` | `gram_accum` |
+| `avx_grid_embed_aa` | `grid_embed_aa` |
+| `avx_had_quant_act_fp8` | `had_quant_act_fp8` |
+| `avx_had_quant_act_i8` | `had_quant_act_i8` |
+| `avx_hc_enter` | `hc_enter` |
+| `avx_hc_read` | `hc_read` |
+| `avx_hc_write` | `hc_write` |
+| `avx_logit_rerank` | `logit_rerank` |
+| `avx_logit_softcap` | `logit_softcap` |
+| `avx_moe_gather` | `moe_gather` |
+| `avx_moe_gemm` | `moe_gemm` |
+| `avx_moe_gemm_q` | `moe_gemm_q` |
+| `avx_moe_gemm_q_mod4` | `moe_gemm_q_mod4` |
+| `avx_moe_scatter` | `moe_scatter` |
+| `avx_mtp_enter` | `mtp_enter` |
+| `avx_mul` | `mul` |
+| `avx_mul_weight` | `mul_weight` |
+| `avx_ngram_ids` | `ngram_ids` |
+| `avx_pair_argmax` | `pair_argmax` |
+| `avx_ple_conv` | `ple_conv` |
+| `avx_ple_gate` | `ple_gate` |
+| `avx_pool_rows` | `pool_rows` |
+| `avx_qk_norm_rope` | `qk_norm_rope` |
+| `avx_qsa_block_key` | `qsa_block_key` |
+| `avx_quant_act_i8g` | `quant_act_i8g` |
+| `avx_rel_sinusoid` | `rel_sinusoid` |
+| `avx_relu` | `relu` |
+| `avx_rmsnorm_add` | `rmsnorm_add` |
+| `avx_rmsnorm_had_quant_i8` | `rmsnorm_had_quant_i8` |
+| `avx_rmsnorm_p` | `rmsnorm_p` |
+| `avx_router_topk` | `router_topk` |
+| `avx_row_topk_merge` | `row_topk_merge` |
+| `avx_sample_merge_topk` | `sample_merge_topk` |
+| `avx_scale` | `scale` |
+| `avx_scale_rows` | `scale_rows` |
+| `avx_seg_mean` | `seg_mean` |
+| `avx_sigmoid` | `sigmoid` |
+| `avx_silu` | `silu` |
+| `avx_softmax` | `softmax` |
+
+`libr4d`: 239 row(s) not reached:
+
+| kernel | op |
+|---|---|
+| `act_mul_bf16` | `act_mul` |
 | `ar_gather_2rank` | `all_gather` |
+| `ar_gather_2rank_host` | `all_gather` |
+| `ar_gather_3rank` | `all_gather` |
+| `ar_gather_3rank_host` | `all_gather` |
+| `ar_gather_4rank` | `all_gather` |
+| `ar_gather_4rank_host` | `all_gather` |
+| `ar_gather_8rank` | `all_gather` |
+| `ar_gather_8rank_host` | `all_gather` |
+| `ar_gather_hc_write` | `ar_gather_hc_write` |
+| `ar_gather_hc_write_4rank` | `ar_gather_hc_write` |
+| `ar_gather_hc_write_4rank_host` | `ar_gather_hc_write` |
+| `ar_gather_hc_write_host` | `ar_gather_hc_write` |
+| `ar_hc_write` | `ar_hc_write` |
+| `ar_hc_write_4rank` | `ar_hc_write` |
+| `ar_hc_write_4rank_host` | `ar_hc_write` |
+| `ar_hc_write_host` | `ar_hc_write` |
 | `ar_ln_had_quant_i8` | `ar_ln_had_quant_i8` |
+| `ar_ln_had_quant_i8_host` | `ar_ln_had_quant_i8` |
 | `ar_oneshot_2rank_exact` | `all_reduce` |
+| `ar_oneshot_2rank_exact_host` | `all_reduce` |
+| `ar_oneshot_2rank_exact_lane` | `all_reduce` |
+| `ar_oneshot_2rank_exact_lane_host` | `all_reduce` |
 | `ar_oneshot_2rank_wht6` | `all_reduce` |
+| `ar_oneshot_2rank_wht6_host` | `all_reduce` |
+| `ar_oneshot_2rank_wht6_lane` | `all_reduce` |
+| `ar_oneshot_2rank_wht6_lane_host` | `all_reduce` |
+| `ar_oneshot_3rank_exact` | `all_reduce` |
+| `ar_oneshot_3rank_exact_host` | `all_reduce` |
 | `ar_oneshot_4rank_exact` | `all_reduce` |
+| `ar_oneshot_4rank_exact_host` | `all_reduce` |
 | `ar_oneshot_8rank_exact` | `all_reduce` |
+| `ar_oneshot_8rank_exact_host` | `all_reduce` |
 | `ar_rmsnorm_quant_fp8` | `ar_rmsnorm_quant_fp8` |
+| `ar_rmsnorm_quant_fp8_host` | `ar_rmsnorm_quant_fp8` |
+| `ar_rmsnorm_quant_i8` | `ar_rmsnorm_quant_i8` |
+| `ar_rmsnorm_quant_i8_host` | `ar_rmsnorm_quant_i8` |
+| `ar_twoshot_3rank_exact` | `all_reduce` |
+| `ar_twoshot_3rank_exact_host` | `all_reduce` |
+| `ar_twoshot_3rank_ti8` | `all_reduce` |
+| `ar_twoshot_3rank_ti8_host` | `all_reduce` |
 | `ar_twoshot_4rank_exact` | `all_reduce` |
+| `ar_twoshot_4rank_exact_host` | `all_reduce` |
 | `ar_twoshot_4rank_ti8` | `all_reduce` |
+| `ar_twoshot_4rank_ti8_host` | `all_reduce` |
 | `ar_twoshot_8rank_exact` | `all_reduce` |
-| `attn_decode_h128_gqa4_fp8kv` | `attn_paged` |
+| `ar_twoshot_8rank_exact_host` | `all_reduce` |
+| `attn_decode_gq_h256_gqa12_bf16kv` | `attn_paged_gate_quant` |
+| `attn_decode_gq_h256_gqa12_fp8kv` | `attn_paged_gate_quant` |
+| `attn_decode_gq_h256_gqa6_bs4_bf16kv` | `attn_paged_gate_quant` |
+| `attn_decode_gq_h256_gqa6_bs4_fp8kv` | `attn_paged_gate_quant` |
+| `attn_decode_h128_gqa4_bf16kv` | `attn_paged` |
 | `attn_decode_h128_gqa8_bf16kv` | `attn_paged` |
 | `attn_decode_h128_gqa8_fp8kv` | `attn_paged` |
 | `attn_decode_h256_gqa12_bf16kv` | `attn_paged` |
 | `attn_decode_h256_gqa12_fp8kv` | `attn_paged` |
 | `attn_decode_h256_gqa2_bf16kv` | `attn_paged` |
 | `attn_decode_h256_gqa2_fp8kv` | `attn_paged` |
-| `attn_decode_h256_gqa6_fp8kv` | `attn_paged` |
+| `attn_decode_h256_gqa4_bf16kv` | `attn_paged` |
+| `attn_decode_h256_gqa4_fp8kv` | `attn_paged` |
+| `attn_decode_h256_gqa6_bf16kv` | `attn_paged` |
+| `attn_decode_h256_gqa6_bs4_bf16kv` | `attn_paged` |
+| `attn_decode_h256_gqa6_bs4_fp8kv` | `attn_paged` |
 | `attn_decode_h256_gqa8_bf16kv` | `attn_paged` |
 | `attn_decode_h256_gqa8_fp8kv` | `attn_paged` |
-| `attn_decode_h512_gqa8_bf16kv` | `attn_paged` |
-| `attn_decode_h512_gqa8_fp8kv` | `attn_paged` |
+| `attn_dense_h1152_bf16` | `attn_dense` |
+| `attn_dense_h128_bf16` | `attn_dense` |
+| `attn_dense_h256_gqa2_bf16` | `attn_dense` |
+| `attn_dense_h512_gqa4_bf16` | `attn_dense` |
+| `attn_dense_h64_bf16` | `attn_dense` |
+| `attn_dense_h768_bf16` | `attn_dense` |
+| `attn_local_rel_bf16` | `attn_local_rel` |
 | `attn_prefill_h128_gqa8_bf16kv` | `attn_paged` |
 | `attn_prefill_h128_gqa8_fp8kv` | `attn_paged` |
 | `attn_prefill_h256_gqa12_bf16kv` | `attn_paged` |
 | `attn_prefill_h256_gqa12_fp8kv` | `attn_paged` |
 | `attn_prefill_h256_gqa2_bf16kv` | `attn_paged` |
 | `attn_prefill_h256_gqa2_fp8kv` | `attn_paged` |
-| `attn_prefill_h256_gqa6_fp8kv` | `attn_paged` |
+| `attn_prefill_h256_gqa4_bf16kv` | `attn_paged` |
+| `attn_prefill_h256_gqa4_fp8kv` | `attn_paged` |
+| `attn_prefill_h256_gqa6_bf16kv` | `attn_paged` |
+| `attn_prefill_h256_gqa6_bs4_bf16kv` | `attn_paged` |
+| `attn_prefill_h256_gqa6_bs4_fp8kv` | `attn_paged` |
 | `attn_prefill_h256_gqa8_bf16kv` | `attn_paged` |
 | `attn_prefill_h256_gqa8_fp8kv` | `attn_paged` |
-| `attn_prefill_h512_gqa8_bf16kv` | `attn_paged` |
-| `attn_prefill_h512_gqa8_fp8kv` | `attn_paged` |
-| `attn_vit_h72_bf16` | `attn_dense` |
+| `attn_prefill_h64_gqa4_bf16kv` | `attn_paged` |
+| `attn_prefill_h64_gqa4_fp8kv` | `attn_paged` |
+| `attn_prefix_self_h128_bf16` | `attn_prefix_self` |
+| `attn_qrow_h256_gqa1_bf16kv` | `attn_paged_qrow` |
+| `attn_qrow_h256_gqa1_fp8kv` | `attn_paged_qrow` |
+| `attn_qrow_h256_gqa2_bf16kv` | `attn_paged_qrow` |
+| `attn_qrow_h256_gqa2_fp8kv` | `attn_paged_qrow` |
+| `attn_qrow_h256_gqa4_bf16kv` | `attn_paged_qrow` |
+| `attn_qrow_h256_gqa4_fp8kv` | `attn_paged_qrow` |
+| `attn_qrow_h256_gqa8_bf16kv` | `attn_paged_qrow` |
+| `attn_qrow_h256_gqa8_fp8kv` | `attn_paged_qrow` |
+| `attn_qrow_h512_gqa1_bf16kv` | `attn_paged_qrow` |
+| `attn_qrow_h512_gqa1_fp8kv` | `attn_paged_qrow` |
+| `attn_qrow_h512_gqa2_bf16kv` | `attn_paged_qrow` |
+| `attn_qrow_h512_gqa2_fp8kv` | `attn_paged_qrow` |
+| `attn_qrow_h512_gqa4_bf16kv` | `attn_paged_qrow` |
+| `attn_qrow_h512_gqa4_fp8kv` | `attn_paged_qrow` |
+| `attn_qrow_h512_gqa8_bf16kv` | `attn_paged_qrow` |
+| `attn_qrow_h512_gqa8_fp8kv` | `attn_paged_qrow` |
+| `attn_window_h256_gqa1_bf16kv` | `attn_paged` |
+| `attn_window_h256_gqa1_fp8kv` | `attn_paged` |
+| `attn_window_h256_gqa2_bf16kv` | `attn_paged` |
+| `attn_window_h256_gqa2_fp8kv` | `attn_paged` |
+| `attn_window_h256_gqa4_bf16kv` | `attn_paged` |
+| `attn_window_h256_gqa4_fp8kv` | `attn_paged` |
+| `attn_window_h256_gqa8_bf16kv` | `attn_paged` |
+| `attn_window_h256_gqa8_fp8kv` | `attn_paged` |
+| `attn_window_h512_gqa1_bf16kv` | `attn_paged` |
+| `attn_window_h512_gqa1_fp8kv` | `attn_paged` |
+| `attn_window_h512_gqa2_bf16kv` | `attn_paged` |
+| `attn_window_h512_gqa2_fp8kv` | `attn_paged` |
+| `attn_window_h512_gqa4_bf16kv` | `attn_paged` |
+| `attn_window_h512_gqa4_fp8kv` | `attn_paged` |
+| `attn_window_h512_gqa8_bf16kv` | `attn_paged` |
+| `attn_window_h512_gqa8_fp8kv` | `attn_paged` |
+| `cast_bf16_f32` | `cast` |
+| `causal_conv1d_bf16` | `causal_conv1d` |
+| `chan_affine_bf16` | `chan_affine` |
+| `clamp_bf16` | `clamp` |
+| `conv1d_dw_bf16` | `conv1d_dw` |
+| `conv2d_bf16` | `conv2d` |
+| `conv2d_nhwc_bf16` | `conv2d_nhwc` |
+| `d2s_add_bf16` | `d2s_add` |
 | `dequant_w4_bf16` | `dequant_w4` |
 | `dflash_conv_t2_g16_bf16` | `dflash_conv` |
-| `dflash_select_bf16` | `dflash_select` |
-| `embed_lookup_q_host` | `embed_lookup_q` |
+| `embed_lookup_q_bf16` | `embed_lookup_q` |
+| `expert_scale_bf16` | `expert_scale` |
+| `fill_bf16` | `fill` |
+| `flow_euler_bf16` | `flow_euler` |
+| `gate_add_bf16` | `gate_add` |
 | `gate_quant_fp8` | `gate_quant_fp8` |
 | `gated_had_quant_fp8` | `gated_had_quant_fp8` |
 | `gated_had_quant_i8` | `gated_had_quant_i8` |
-| `gated_quant_fp8` | `gated_quant_fp8` |
+| `gather_rows2_bf16` | `gather_rows2` |
 | `gather_rows_u8` | `gather_rows` |
+| `gdn_conv_prep_w4_h128_bf16` | `gdn_conv_prep` |
+| `gdn_conv_recurrent_update_k128_v128_bf16` | `gdn_conv_recurrent_update` |
 | `gdn_gated_norm_had_quant_i8` | `gdn_gated_norm_had_quant_i8` |
+| `gelu_mul_bf16` | `gelu_mul` |
+| `gelu_mul_quant_i8` | `gelu_mul_quant_i8` |
+| `gelu_tanh_bf16` | `gelu_tanh` |
+| `gemm_bf16_nt_tiled` | `gemm_nt` |
 | `gemm_fp8a16_nt_m1` | `gemm_nt_q` |
-| `gemm_fp8a8_gated_nt_m16` | `gemm_nt_q_gated` |
+| `gemm_i8a8_nt_m16` | `gemm_nt_q` |
+| `gemm_i8a8_tiled` | `gemm_nt_q` |
 | `gemm_mxfp4a8_nt_m64` | `gemm_nt_q` |
 | `gemm_w2a8_nt` | `gemm_nt_q` |
+| `gemm_w4a16_asym_nt_m64` | `gemm_nt_q` |
 | `gemm_w4a16_nt_m64` | `gemm_nt_q` |
 | `gemm_w4a8_nt_m64` | `gemm_nt_q` |
 | `gemm_w4a8_prefill` | `gemm_nt_q` |
 | `gemm_w4a8_tiled` | `gemm_nt_q` |
+| `gemm_w4a8i8_tiled` | `gemm_nt_q` |
+| `gemm_w5a16_nt_m64` | `gemm_nt_q` |
+| `gemm_w5a8i8_tiled` | `gemm_nt_q` |
 | `gemm_w8a16_nt_m64` | `gemm_nt_q` |
 | `gemm_w8a8_nt_m64` | `gemm_nt_q` |
 | `gemm_w8a8_tiled` | `gemm_nt_q` |
+| `givens_dense_quant` | `givens_dense_quant` |
+| `givens_rotate` | `givens_rotate` |
 | `gram_accum` | `gram_accum` |
+| `gram_accum_bf16` | `gram_accum` |
+| `grid_embed_aa_bf16` | `grid_embed_aa` |
 | `had_quant_act_fp8` | `had_quant_act_fp8` |
 | `had_quant_act_i8` | `had_quant_act_i8` |
+| `had_quant_act_i8g` | `had_quant_act_i8g` |
 | `hc_enter_bf16` | `hc_enter` |
 | `hc_read_bf16` | `hc_read` |
+| `hc_read_e4m3` | `hc_read` |
 | `hc_write_bf16` | `hc_write` |
-| `kv_store_fp8` | `kv_store` |
+| `join_add_scale_bf16` | `join_add_scale` |
+| `kv_store_bf16` | `kv_store` |
+| `l2norm_chan_bf16` | `l2norm_chan` |
+| `lane_gather_w32` | `lane_gather` |
+| `lane_store_w32` | `lane_store` |
+| `ln_mod_bf16` | `ln_mod` |
+| `ln_mod_quant_fp8_bf16` | `ln_mod_quant_fp8` |
 | `logit_rerank` | `logit_rerank` |
+| `logit_rerank_i8` | `logit_rerank` |
+| `logit_softcap_bf16` | `logit_softcap` |
+| `logit_softcap_f32` | `logit_softcap` |
 | `logits_gemm_bf16` | `logits_gemm` |
+| `logits_gemm_i8` | `logits_gemm` |
 | `moe_gather_bf16` | `moe_gather` |
+| `moe_gemm_bf16` | `moe_gemm` |
 | `moe_gemm_fp8a8` | `moe_gemm_q` |
+| `moe_gemm_fp8a8_mod4` | `moe_gemm_q_mod4` |
 | `moe_gemm_w4a8` | `moe_gemm_q` |
+| `moe_gemm_w4a8_mod4` | `moe_gemm_q_mod4` |
 | `moe_scatter_i32` | `moe_scatter` |
 | `mtp_enter_bf16` | `mtp_enter` |
+| `mtp_enter_e4m3` | `mtp_enter` |
 | `mul_bf16` | `mul` |
+| `mul_weight_bf16` | `mul_weight` |
 | `ngram_ids_i32` | `ngram_ids` |
+| `norm_add_norm_bf16` | `norm_add_norm` |
+| `norm_add_norm_route_bf16` | `norm_add_norm_route` |
+| `pair_argmax_f32` | `pair_argmax` |
 | `ple_conv_bf16` | `ple_conv` |
 | `ple_gate_bf16` | `ple_gate` |
+| `pool_rows_bf16` | `pool_rows` |
+| `qk_norm_rope_bf16` | `qk_norm_rope` |
 | `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` |
+| `qkv_norm_rope_bf16` | `qkv_norm_rope` |
 | `qsa_block_key_bf16` | `qsa_block_key` |
 | `qsa_score_bf16` | `qsa_score` |
 | `qsa_select_i32` | `qsa_select` |
 | `qsa_tail_store_bf16` | `qsa_tail_store` |
 | `qsa_work_bf16` | `qsa_work` |
-| `quant_act_i8` | `quant_act_i8` |
+| `quant_act_i8g` | `quant_act_i8g` |
+| `randn_lanes_bf16` | `randn_lanes` |
+| `rel_sinusoid_bf16` | `rel_sinusoid` |
+| `relu_bf16` | `relu` |
 | `rmsnorm_had_quant_i8` | `rmsnorm_had_quant_i8` |
-| `rmsnorm_quant_fp8` | `rmsnorm_quant_fp8` |
+| `rmsnorm_p_bf16` | `rmsnorm_p` |
+| `rmsnorm_quant_i8` | `rmsnorm_quant_i8` |
+| `router_gemm_topk_scatter_bf16` | `router_gemm_topk_scatter` |
 | `router_topk_bf16` | `router_topk` |
 | `router_topk_scatter_bf16` | `router_topk_scatter` |
 | `rowtopk_merge` | `row_topk_merge` |
+| `s2d_avg_add_bf16` | `s2d_avg_add` |
 | `sample_chain_f32` | `sample_chain` |
 | `sample_merge_topk_f32` | `sample_merge_topk` |
+| `scale_bf16` | `scale` |
 | `scale_rows_bf16` | `scale_rows` |
+| `scatter_add_rows_bf16` | `scatter_add_rows` |
 | `scatter_rows_u8` | `scatter_rows` |
+| `seg_mean_bf16` | `seg_mean` |
 | `sigmoid_bf16` | `sigmoid` |
+| `silu_bf16` | `silu` |
+| `timestep_embed_bf16` | `timestep_embed` |
+| `to_rgba8_bf16` | `to_rgba8` |
 
-`libref` -- 39 row(s) not reached:
+`libref`: 81 row(s) not reached:
 
 | kernel | op |
 |---|---|
+| `ref_act_mul` | `act_mul` |
 | `ref_all_gather` | `all_gather` |
 | `ref_all_reduce` | `all_reduce` |
-| `ref_attn_dense` | `attn_dense` |
+| `ref_attn_local_rel` | `attn_local_rel` |
+| `ref_attn_prefix_self` | `attn_prefix_self` |
+| `ref_causal_conv1d` | `causal_conv1d` |
+| `ref_chan_affine` | `chan_affine` |
+| `ref_clamp` | `clamp` |
+| `ref_conv1d_dw` | `conv1d_dw` |
+| `ref_conv2d` | `conv2d` |
+| `ref_conv2d_nhwc` | `conv2d_nhwc` |
+| `ref_d2s_add` | `d2s_add` |
 | `ref_dequant` | `dequant` |
+| `ref_dflash_conv` | `dflash_conv` |
 | `ref_embed_lookup_q` | `embed_lookup_q` |
+| `ref_fill` | `fill` |
+| `ref_flow_euler` | `flow_euler` |
+| `ref_gate_add` | `gate_add` |
 | `ref_gated_had_quant_i8` | `gated_had_quant_i8` |
+| `ref_gather_rows2` | `gather_rows2` |
+| `ref_gdn_conv_prep` | `gdn_conv_prep` |
+| `ref_gdn_conv_recurrent_update` | `gdn_conv_recurrent_update` |
 | `ref_gelu` | `gelu` |
-| `ref_gemm_nt_bias` | `gemm_nt_bias` |
+| `ref_gelu_mul` | `gelu_mul` |
+| `ref_gelu_tanh` | `gelu_tanh` |
 | `ref_gemm_nt_q_bias` | `gemm_nt_q_bias` |
+| `ref_givens_dense_quant` | `givens_dense_quant` |
+| `ref_givens_rotate` | `givens_rotate` |
 | `ref_gram_accum` | `gram_accum` |
+| `ref_grid_embed_aa` | `grid_embed_aa` |
 | `ref_had_quant_act_fp8` | `had_quant_act_fp8` |
 | `ref_had_quant_act_i8` | `had_quant_act_i8` |
 | `ref_hc_enter` | `hc_enter` |
 | `ref_hc_read` | `hc_read` |
 | `ref_hc_write` | `hc_write` |
-| `ref_layernorm` | `layernorm` |
+| `ref_l2norm_chan` | `l2norm_chan` |
+| `ref_lane_gather` | `lane_gather` |
+| `ref_lane_store` | `lane_store` |
+| `ref_ln_mod` | `ln_mod` |
+| `ref_ln_mod_quant_fp8` | `ln_mod_quant_fp8` |
 | `ref_logit_rerank` | `logit_rerank` |
-| `ref_logits_gemm` | `logits_gemm` |
+| `ref_logit_softcap` | `logit_softcap` |
 | `ref_moe_gather` | `moe_gather` |
 | `ref_moe_gemm` | `moe_gemm` |
 | `ref_moe_gemm_q` | `moe_gemm_q` |
+| `ref_moe_gemm_q_mod4` | `moe_gemm_q_mod4` |
 | `ref_moe_scatter` | `moe_scatter` |
 | `ref_mtp_enter` | `mtp_enter` |
 | `ref_mul` | `mul` |
+| `ref_mul_weight` | `mul_weight` |
 | `ref_ngram_ids` | `ngram_ids` |
+| `ref_pair_argmax` | `pair_argmax` |
 | `ref_ple_conv` | `ple_conv` |
 | `ref_ple_gate` | `ple_gate` |
+| `ref_pool_rows` | `pool_rows` |
 | `ref_qk_norm_rope` | `qk_norm_rope` |
-| `ref_quant_act_i8` | `quant_act_i8` |
+| `ref_qsa_block_key` | `qsa_block_key` |
+| `ref_qsa_score` | `qsa_score` |
+| `ref_qsa_select` | `qsa_select` |
+| `ref_qsa_tail_store` | `qsa_tail_store` |
+| `ref_qsa_work` | `qsa_work` |
+| `ref_quant_act_i8g` | `quant_act_i8g` |
+| `ref_randn_lanes` | `randn_lanes` |
+| `ref_rel_sinusoid` | `rel_sinusoid` |
+| `ref_relu` | `relu` |
 | `ref_rmsnorm_add` | `rmsnorm_add` |
 | `ref_rmsnorm_had_quant_i8` | `rmsnorm_had_quant_i8` |
+| `ref_rmsnorm_p` | `rmsnorm_p` |
 | `ref_router_topk` | `router_topk` |
 | `ref_row_topk_merge` | `row_topk_merge` |
+| `ref_s2d_avg_add` | `s2d_avg_add` |
 | `ref_sample_merge_topk` | `sample_merge_topk` |
+| `ref_scale` | `scale` |
 | `ref_scale_rows` | `scale_rows` |
-| `ref_scatter_rows` | `scatter_rows` |
+| `ref_scatter_add_rows` | `scatter_add_rows` |
+| `ref_seg_mean` | `seg_mean` |
 | `ref_sigmoid` | `sigmoid` |
 | `ref_silu` | `silu` |
 | `ref_softmax` | `softmax` |
+| `ref_timestep_embed` | `timestep_embed` |
+| `ref_to_rgba8` | `to_rgba8` |
 
 
 ## Completeness
 
-One row per op in the vocabulary. A cell names the DOMAIN the library serves that op in, or `-`
-where it has no row at all. `graph` marks the ops this container's declared program asks for --
-an empty cell on a marked row is a hole a real model falls into, and one on an unmarked row is
-not.
+One row per op in the vocabulary. A cell names the domain the library serves that op in, or `-`
+where it has no row. `graph` marks the ops this container's declared program asks for; a `-`
+on a marked row is a hole this model falls into.
 
-| op | graph | libr4d | libref |
-|---|---|---|---|
-| `add` | yes | device | host |
-| `all_gather` |   | device | host |
-| `all_reduce` |   | device | host |
-| `ar_ln_had_quant_i8` |   | device | - |
-| `ar_rmsnorm_quant_fp8` |   | device | - |
-| `attn_dense` |   | device | host |
-| `attn_paged` | yes | device | host |
-| `cast` | yes | device | host |
-| `dequant` |   | - | host |
-| `dequant_w4` |   | device | - |
-| `dflash_conv` |   | device | - |
-| `dflash_select` |   | device | - |
-| `embed_lookup` | yes | device | host |
-| `embed_lookup_q` |   | host | host |
-| `gate_quant_fp8` |   | device | - |
-| `gated_had_quant_fp8` |   | device | - |
-| `gated_had_quant_i8` |   | device | host |
-| `gated_quant_fp8` |   | device | - |
-| `gather_rows` | yes | device | host |
-| `gdn_chunk_scan` | yes | device | host |
-| `gdn_conv_prep` | yes | device | host |
-| `gdn_conv_update` | yes | device | host |
-| `gdn_gated_norm_had_quant_i8` |   | device | - |
-| `gdn_gated_rmsnorm` | yes | device | host |
-| `gdn_kkt_solve` | yes | device | host |
-| `gdn_recurrent_update` | yes | device | host |
-| `gelu` |   | - | host |
-| `gemm_nt` | yes | device | host |
-| `gemm_nt_bias` |   | - | host |
-| `gemm_nt_q` | yes | device | host |
-| `gemm_nt_q_bias` |   | - | host |
-| `gemm_nt_q_gated` |   | device | - |
-| `gram_accum` |   | device | host |
-| `had_quant_act_fp8` |   | device | host |
-| `had_quant_act_i8` |   | device | host |
-| `hc_enter` |   | device | host |
-| `hc_read` |   | device | host |
-| `hc_write` |   | device | host |
-| `kv_store` | yes | device | host |
-| `layernorm` |   | - | host |
-| `logit_rerank` |   | device | host |
-| `logits_gemm` | yes | device | host |
-| `moe_gather` |   | device | host |
-| `moe_gemm` |   | - | host |
-| `moe_gemm_q` |   | device | host |
-| `moe_scatter` |   | device | host |
-| `mtp_enter` |   | device | host |
-| `mul` |   | device | host |
-| `ngram_ids` |   | device | host |
-| `ple_conv` |   | device | host |
-| `ple_gate` |   | device | host |
-| `qk_norm_rope` |   | - | host |
-| `qk_norm_rope_gate` |   | device | - |
-| `qsa_block_key` |   | device | host |
-| `qsa_score` |   | device | - |
-| `qsa_select` |   | device | - |
-| `qsa_tail_store` |   | device | - |
-| `qsa_work` |   | device | - |
-| `quant_act_fp8` | yes | device | host |
-| `quant_act_i8` |   | device | host |
-| `rmsnorm` | yes | device | host |
-| `rmsnorm_add` |   | - | host |
-| `rmsnorm_had_quant_i8` |   | device | host |
-| `rmsnorm_quant_fp8` |   | device | - |
-| `rope` | yes | device | host |
-| `rope_table` | yes | device | host |
-| `router_topk` |   | device | host |
-| `router_topk_scatter` |   | device | - |
-| `row_topk` | yes | device | host |
-| `row_topk_merge` |   | device | host |
-| `sample_argmax` | yes | device | host |
-| `sample_chain` |   | device | - |
-| `sample_dry` | yes | device | host |
-| `sample_logprobs` |   | device | host |
-| `sample_mask` | yes | device | host |
-| `sample_merge_topk` |   | device | host |
-| `sample_minp` | yes | device | host |
-| `sample_penalties` | yes | device | host |
-| `sample_pick` | yes | device | host |
-| `sample_temp` | yes | device | host |
-| `sample_topk` | yes | device | host |
-| `sample_topp` | yes | device | host |
-| `sample_typical` | yes | device | host |
-| `sample_xtc` | yes | device | host |
-| `scale_rows` |   | device | host |
-| `scatter_rows` |   | device | host |
-| `sigmoid` |   | device | host |
-| `silu` |   | - | host |
-| `silu_mul` | yes | device | host |
-| `softmax` |   | - | host |
+| op | graph | libavx | libr4d | libref |
+|---|---|---|---|---|
+| `act_mul` |   | host | device | host |
+| `add` | yes | host | device | host |
+| `all_gather` |   | host | device | host |
+| `all_reduce` |   | host | device | host |
+| `ar_gather_hc_write` |   | - | device | - |
+| `ar_hc_write` |   | - | device | - |
+| `ar_ln_had_quant_i8` |   | - | device | - |
+| `ar_rmsnorm_quant_fp8` |   | - | device | - |
+| `ar_rmsnorm_quant_i8` |   | - | device | - |
+| `attn_dense` | yes | host | device | host |
+| `attn_local_rel` |   | host | device | host |
+| `attn_paged` | yes | host | device | host |
+| `attn_paged_gate_quant` |   | - | device | - |
+| `attn_paged_qrow` |   | - | device | - |
+| `attn_prefix_self` |   | - | device | host |
+| `cast` | yes | host | device | host |
+| `causal_conv1d` |   | host | device | host |
+| `chan_affine` |   | - | device | host |
+| `clamp` |   | host | device | host |
+| `conv1d_dw` |   | host | device | host |
+| `conv2d` |   | host | device | host |
+| `conv2d_nhwc` |   | - | device | host |
+| `d2s_add` |   | - | device | host |
+| `dequant` |   | host | - | host |
+| `dequant_w4` |   | - | device | - |
+| `dflash_conv` |   | - | device | host |
+| `dflash_select` | yes | host | device | host |
+| `embed_lookup` | yes | host | device | host |
+| `embed_lookup_q` |   | host | device | host |
+| `expert_scale` |   | - | device | - |
+| `fill` |   | host | device | host |
+| `flow_euler` |   | - | device | host |
+| `gate_add` |   | - | device | host |
+| `gate_quant_fp8` |   | - | device | - |
+| `gated_had_quant_fp8` |   | - | device | - |
+| `gated_had_quant_i8` |   | host | device | host |
+| `gated_quant_fp8` | yes | host | device | host |
+| `gather_rows` | yes | host | device | host |
+| `gather_rows2` |   | - | device | host |
+| `gdn_chunk_scan` | yes | host | device | host |
+| `gdn_conv_prep` |   | host | device | host |
+| `gdn_conv_recurrent_update` |   | host | device | host |
+| `gdn_conv_update` | yes | host | device | host |
+| `gdn_gated_norm_had_quant_i8` |   | - | device | - |
+| `gdn_gated_rmsnorm` | yes | host | device | host |
+| `gdn_kkt_solve` | yes | host | device | host |
+| `gdn_recurrent_update` | yes | host | device | host |
+| `gelu` |   | host | - | host |
+| `gelu_mul` |   | host | device | host |
+| `gelu_mul_quant_i8` |   | - | device | - |
+| `gelu_tanh` |   | - | device | host |
+| `gemm_nt` | yes | host | device | host |
+| `gemm_nt_bias` | yes | host | device | host |
+| `gemm_nt_q` | yes | host | device | host |
+| `gemm_nt_q_bias` |   | host | - | host |
+| `gemm_nt_q_gated` | yes | host | device | host |
+| `givens_dense_quant` |   | host | device | host |
+| `givens_rotate` |   | host | device | host |
+| `gram_accum` |   | host | device | host |
+| `grid_embed` | yes | host | device | host |
+| `grid_embed_aa` |   | host | device | host |
+| `had_quant_act_fp8` |   | host | device | host |
+| `had_quant_act_i8` |   | host | device | host |
+| `had_quant_act_i8g` |   | - | device | - |
+| `hc_enter` |   | host | device | host |
+| `hc_read` |   | host | device | host |
+| `hc_write` |   | host | device | host |
+| `join_add_scale` |   | - | device | - |
+| `kv_store` | yes | host | device | host |
+| `l2norm_chan` |   | - | device | host |
+| `lane_gather` |   | - | device | host |
+| `lane_store` |   | - | device | host |
+| `layernorm` | yes | host | device | host |
+| `ln_mod` |   | - | device | host |
+| `ln_mod_quant_fp8` |   | - | device | host |
+| `logit_rerank` | yes | host | device | host |
+| `logit_softcap` |   | host | device | host |
+| `logits_gemm` | yes | host | device | host |
+| `moe_gather` |   | host | device | host |
+| `moe_gemm` |   | host | device | host |
+| `moe_gemm_q` |   | host | device | host |
+| `moe_gemm_q_mod4` |   | host | device | host |
+| `moe_scatter` |   | host | device | host |
+| `mtp_enter` |   | host | device | host |
+| `mul` |   | host | device | host |
+| `mul_weight` |   | host | device | host |
+| `ngram_ids` |   | host | device | host |
+| `norm_add_norm` |   | - | device | - |
+| `norm_add_norm_route` |   | - | device | - |
+| `pair_argmax` |   | host | device | host |
+| `ple_conv` |   | host | device | host |
+| `ple_gate` |   | host | device | host |
+| `pool_rows` |   | host | device | host |
+| `qk_norm_rope` |   | host | device | host |
+| `qk_norm_rope_gate` |   | - | device | - |
+| `qk_norm_rope_gate_kv_store` |   | - | device | - |
+| `qkv_norm_rope` |   | - | device | - |
+| `qsa_block_key` |   | host | device | host |
+| `qsa_score` |   | - | device | host |
+| `qsa_select` |   | - | device | host |
+| `qsa_tail_store` |   | - | device | host |
+| `qsa_work` |   | - | device | host |
+| `quant_act_fp8` | yes | host | device | host |
+| `quant_act_i8` | yes | host | device | host |
+| `quant_act_i8g` |   | host | device | host |
+| `randn_lanes` |   | - | device | host |
+| `rel_sinusoid` |   | host | device | host |
+| `relu` |   | host | device | host |
+| `rmsnorm` | yes | host | device | host |
+| `rmsnorm_add` |   | host | - | host |
+| `rmsnorm_had_quant_i8` |   | host | device | host |
+| `rmsnorm_p` |   | host | device | host |
+| `rmsnorm_quant_fp8` | yes | host | device | host |
+| `rmsnorm_quant_i8` |   | - | device | - |
+| `rope` | yes | host | device | host |
+| `rope_table` | yes | host | device | host |
+| `router_gemm_topk_scatter` |   | - | device | - |
+| `router_topk` |   | host | device | host |
+| `router_topk_scatter` |   | - | device | - |
+| `row_topk` | yes | host | device | host |
+| `row_topk_merge` |   | host | device | host |
+| `s2d_avg_add` |   | - | device | host |
+| `sample_argmax` | yes | host | device | host |
+| `sample_chain` |   | - | device | - |
+| `sample_dry` | yes | host | device | host |
+| `sample_logprobs` | yes | host | device | host |
+| `sample_mask` | yes | host | device | host |
+| `sample_merge_topk` |   | host | device | host |
+| `sample_minp` | yes | host | device | host |
+| `sample_penalties` | yes | host | device | host |
+| `sample_pick` | yes | host | device | host |
+| `sample_temp` | yes | host | device | host |
+| `sample_topk` | yes | host | device | host |
+| `sample_topp` | yes | host | device | host |
+| `sample_typical` | yes | host | device | host |
+| `sample_xtc` | yes | host | device | host |
+| `scale` |   | host | device | host |
+| `scale_rows` |   | host | device | host |
+| `scatter_add_rows` |   | - | device | host |
+| `scatter_rows` | yes | host | device | host |
+| `seg_mean` |   | host | device | host |
+| `sigmoid` |   | host | device | host |
+| `silu` |   | host | device | host |
+| `silu_mul` | yes | host | device | host |
+| `softmax` |   | host | - | host |
+| `timestep_embed` |   | - | device | host |
+| `to_rgba8` |   | - | device | host |
 
 ## Correctness
 
-979 distinct case(s) over 1067 check(s). `n` is how many times the case ran -- one per layer,
-typically -- and `rel_l2` is the WORST of them, because one layer disagreeing is the finding.
-`(synth w)` means this op's weights are not in the container and were drawn instead, so the
-case proves the arithmetic and not the artifact.
+2202 distinct case(s) over 2202 check(s). `n` is how many times the case ran (typically one per
+layer) and `rel_l2` is the worst of them. `(synth w)` means this op's weights are not in the
+container and were drawn instead, so the case checks the arithmetic, not the artifact.
 
 | op | kernel | library | domain | geometry | tuned | n | verdict | rel_l2 | tol |
 |---|---|---|---|---|---|---|---|---|---|
+| `cast` | `avx_cast` | libavx | host | `n=5120 from=bf16 to=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
 | `cast` | `cast_bf16_bf16` | libr4d | device | `n=5120 from=bf16 to=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `cast` | `ref_cast` | libref | host | `n=5120 from=bf16 to=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `cast` | `ref_cast` | libref | host | `n=5120 from=bf16 to=bf16 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `cast` | `avx_cast` | libavx | host | `n=5120 from=bf16 to=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
 | `cast` | `cast_bf16_bf16` | libr4d | device | `n=5120 from=bf16 to=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `cast` | `ref_cast` | libref | host | `n=5120 from=bf16 to=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `cast` | `ref_cast` | libref | host | `n=5120 from=bf16 to=bf16 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `cast` | `avx_cast` | libavx | host | `n=5120 from=bf16 to=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
 | `cast` | `cast_bf16_bf16` | libr4d | device | `n=5120 from=bf16 to=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `cast` | `ref_cast` | libref | host | `n=5120 from=bf16 to=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `cast` | `ref_cast` | libref | host | `n=5120 from=bf16 to=bf16 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `cast` | `avx_cast` | libavx | host | `n=5120 from=bf16 to=bf16 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
 | `cast` | `cast_bf16_bf16` | libr4d | device | `n=5120 from=bf16 to=bf16 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `cast` | `ref_cast` | libref | host | `n=5120 from=bf16 to=bf16 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `cast` | `ref_cast` | libref | host | `n=5120 from=bf16 to=bf16 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `cast` | `avx_cast` | libavx | host | `n=5120 from=bf16 to=bf16 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
 | `cast` | `cast_bf16_bf16` | libr4d | device | `n=5120 from=bf16 to=bf16 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `cast` | `ref_cast` | libref | host | `n=5120 from=bf16 to=bf16 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `cast` | `ref_cast` | libref | host | `n=5120 from=bf16 to=bf16 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `cast` | `avx_cast` | libavx | host | `n=5120 from=bf16 to=bf16 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
 | `cast` | `cast_bf16_bf16` | libr4d | device | `n=5120 from=bf16 to=bf16 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `cast` | `ref_cast` | libref | host | `n=5120 from=bf16 to=bf16 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `cast` | `ref_cast` | libref | host | `n=5120 from=bf16 to=bf16 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `cast` | `avx_cast` | libavx | host | `n=5120 from=bf16 to=bf16 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
 | `cast` | `cast_bf16_bf16` | libr4d | device | `n=5120 from=bf16 to=bf16 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `cast` | `ref_cast` | libref | host | `n=5120 from=bf16 to=bf16 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `cast` | `ref_cast` | libref | host | `n=5120 from=bf16 to=bf16 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `cast` | `avx_cast` | libavx | host | `n=5120 from=bf16 to=bf16 M=128` | - | 1 | ok | 0.00e+00 | 1e-06 |
 | `cast` | `cast_bf16_bf16` | libr4d | device | `n=5120 from=bf16 to=bf16 M=128` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `cast` | `ref_cast` | libref | host | `n=5120 from=bf16 to=bf16 M=128` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `cast` | `ref_cast` | libref | host | `n=5120 from=bf16 to=bf16 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `cast` | `avx_cast` | libavx | host | `n=5120 from=bf16 to=bf16 M=256` | - | 1 | ok | 0.00e+00 | 1e-06 |
 | `cast` | `cast_bf16_bf16` | libr4d | device | `n=5120 from=bf16 to=bf16 M=256` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `cast` | `ref_cast` | libref | host | `n=5120 from=bf16 to=bf16 M=256` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `cast` | `ref_cast` | libref | host | `n=5120 from=bf16 to=bf16 M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `cast` | `avx_cast` | libavx | host | `n=5120 from=bf16 to=bf16 M=512` | - | 1 | ok | 0.00e+00 | 1e-06 |
 | `cast` | `cast_bf16_bf16` | libr4d | device | `n=5120 from=bf16 to=bf16 M=512` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `cast` | `ref_cast` | libref | host | `n=5120 from=bf16 to=bf16 M=512` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `embed_lookup` | `embed_lookup_bf16` | libr4d | device | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=1` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `embed_lookup` | `ref_embed_lookup` | libref | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=1` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `embed_lookup` | `embed_lookup_bf16` | libr4d | device | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=2` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `embed_lookup` | `ref_embed_lookup` | libref | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=2` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `embed_lookup` | `embed_lookup_bf16` | libr4d | device | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=4` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `embed_lookup` | `ref_embed_lookup` | libref | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=4` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `embed_lookup` | `embed_lookup_bf16` | libr4d | device | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=8` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `embed_lookup` | `ref_embed_lookup` | libref | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=8` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `embed_lookup` | `embed_lookup_bf16` | libr4d | device | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=16` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `embed_lookup` | `ref_embed_lookup` | libref | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=16` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `embed_lookup` | `embed_lookup_bf16` | libr4d | device | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=32` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `embed_lookup` | `ref_embed_lookup` | libref | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=32` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `embed_lookup` | `embed_lookup_bf16` | libr4d | device | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=64` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `embed_lookup` | `ref_embed_lookup` | libref | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=64` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `embed_lookup` | `embed_lookup_bf16` | libr4d | device | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=128` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `embed_lookup` | `ref_embed_lookup` | libref | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=128` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `embed_lookup` | `embed_lookup_bf16` | libr4d | device | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=256` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `embed_lookup` | `ref_embed_lookup` | libref | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=256` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `embed_lookup` | `embed_lookup_bf16` | libr4d | device | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=512` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `embed_lookup` | `ref_embed_lookup` | libref | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=512` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `cast` | `ref_cast` | libref | host | `n=5120 from=bf16 to=bf16 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `embed_lookup` | `avx_embed_lookup` | libavx | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `embed_lookup` | `embed_lookup_bf16` | libr4d | device | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `embed_lookup` | `ref_embed_lookup` | libref | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `embed_lookup` | `avx_embed_lookup` | libavx | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `embed_lookup` | `embed_lookup_bf16` | libr4d | device | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `embed_lookup` | `ref_embed_lookup` | libref | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `embed_lookup` | `avx_embed_lookup` | libavx | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `embed_lookup` | `embed_lookup_bf16` | libr4d | device | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `embed_lookup` | `ref_embed_lookup` | libref | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `embed_lookup` | `avx_embed_lookup` | libavx | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `embed_lookup` | `embed_lookup_bf16` | libr4d | device | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `embed_lookup` | `ref_embed_lookup` | libref | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `embed_lookup` | `avx_embed_lookup` | libavx | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `embed_lookup` | `embed_lookup_bf16` | libr4d | device | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `embed_lookup` | `ref_embed_lookup` | libref | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `embed_lookup` | `avx_embed_lookup` | libavx | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `embed_lookup` | `embed_lookup_bf16` | libr4d | device | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `embed_lookup` | `ref_embed_lookup` | libref | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `embed_lookup` | `avx_embed_lookup` | libavx | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `embed_lookup` | `embed_lookup_bf16` | libr4d | device | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `embed_lookup` | `ref_embed_lookup` | libref | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `embed_lookup` | `avx_embed_lookup` | libavx | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `embed_lookup` | `embed_lookup_bf16` | libr4d | device | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `embed_lookup` | `ref_embed_lookup` | libref | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `embed_lookup` | `avx_embed_lookup` | libavx | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `embed_lookup` | `embed_lookup_bf16` | libr4d | device | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `embed_lookup` | `ref_embed_lookup` | libref | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `embed_lookup` | `avx_embed_lookup` | libavx | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `embed_lookup` | `embed_lookup_bf16` | libr4d | device | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `embed_lookup` | `ref_embed_lookup` | libref | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `scatter_rows` | `avx_scatter_rows` | libavx | host | `n=5120 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `scatter_rows` | `scatter_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `scatter_rows` | `ref_scatter_rows` | libref | host | `n=5120 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `scatter_rows` | `avx_scatter_rows` | libavx | host | `n=5120 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `scatter_rows` | `scatter_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `scatter_rows` | `ref_scatter_rows` | libref | host | `n=5120 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `scatter_rows` | `avx_scatter_rows` | libavx | host | `n=5120 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `scatter_rows` | `scatter_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `scatter_rows` | `ref_scatter_rows` | libref | host | `n=5120 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `scatter_rows` | `avx_scatter_rows` | libavx | host | `n=5120 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `scatter_rows` | `scatter_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `scatter_rows` | `ref_scatter_rows` | libref | host | `n=5120 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `scatter_rows` | `avx_scatter_rows` | libavx | host | `n=5120 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `scatter_rows` | `scatter_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `scatter_rows` | `ref_scatter_rows` | libref | host | `n=5120 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `scatter_rows` | `avx_scatter_rows` | libavx | host | `n=5120 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `scatter_rows` | `scatter_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `scatter_rows` | `ref_scatter_rows` | libref | host | `n=5120 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `scatter_rows` | `avx_scatter_rows` | libavx | host | `n=5120 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `scatter_rows` | `scatter_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `scatter_rows` | `ref_scatter_rows` | libref | host | `n=5120 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `scatter_rows` | `avx_scatter_rows` | libavx | host | `n=5120 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `scatter_rows` | `scatter_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `scatter_rows` | `ref_scatter_rows` | libref | host | `n=5120 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `scatter_rows` | `avx_scatter_rows` | libavx | host | `n=5120 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `scatter_rows` | `scatter_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `scatter_rows` | `ref_scatter_rows` | libref | host | `n=5120 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `scatter_rows` | `avx_scatter_rows` | libavx | host | `n=5120 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `scatter_rows` | `scatter_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `scatter_rows` | `ref_scatter_rows` | libref | host | `n=5120 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope_table` | `avx_rope_table` | libavx | host | `rot=64 theta=1e+07 scale=1 dtype=f32 M=1` | - | 1 | ok | 0.00e+00 | 1e-05 |
 | `rope_table` | `rope_table_f32` | libr4d | device | `rot=64 theta=1e+07 scale=1 dtype=f32 M=1` | - | 1 | ok | 0.00e+00 | 1e-05 |
-| `rope_table` | `ref_rope_table` | libref | host | `rot=64 theta=1e+07 scale=1 dtype=f32 M=1` | - | 1 | ok | 0.00e+00 | 1e-05 |
+| `rope_table` | `ref_rope_table` | libref | host | `rot=64 theta=1e+07 scale=1 dtype=f32 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope_table` | `avx_rope_table` | libavx | host | `rot=64 theta=1e+07 scale=1 dtype=f32 M=2` | - | 1 | ok | 0.00e+00 | 1e-05 |
 | `rope_table` | `rope_table_f32` | libr4d | device | `rot=64 theta=1e+07 scale=1 dtype=f32 M=2` | - | 1 | ok | 3.76e-09 | 1e-05 |
-| `rope_table` | `ref_rope_table` | libref | host | `rot=64 theta=1e+07 scale=1 dtype=f32 M=2` | - | 1 | ok | 0.00e+00 | 1e-05 |
-| `rope_table` | `rope_table_f32` | libr4d | device | `rot=64 theta=1e+07 scale=1 dtype=f32 M=4` | - | 1 | ok | 1.27e-08 | 1e-05 |
-| `rope_table` | `ref_rope_table` | libref | host | `rot=64 theta=1e+07 scale=1 dtype=f32 M=4` | - | 1 | ok | 0.00e+00 | 1e-05 |
+| `rope_table` | `ref_rope_table` | libref | host | `rot=64 theta=1e+07 scale=1 dtype=f32 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope_table` | `avx_rope_table` | libavx | host | `rot=64 theta=1e+07 scale=1 dtype=f32 M=4` | - | 1 | ok | 0.00e+00 | 1e-05 |
+| `rope_table` | `rope_table_f32` | libr4d | device | `rot=64 theta=1e+07 scale=1 dtype=f32 M=4` | - | 1 | ok | 1.48e-08 | 1e-05 |
+| `rope_table` | `ref_rope_table` | libref | host | `rot=64 theta=1e+07 scale=1 dtype=f32 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope_table` | `avx_rope_table` | libavx | host | `rot=64 theta=1e+07 scale=1 dtype=f32 M=8` | - | 1 | ok | 0.00e+00 | 1e-05 |
 | `rope_table` | `rope_table_f32` | libr4d | device | `rot=64 theta=1e+07 scale=1 dtype=f32 M=8` | - | 1 | ok | 2.47e-08 | 1e-05 |
-| `rope_table` | `ref_rope_table` | libref | host | `rot=64 theta=1e+07 scale=1 dtype=f32 M=8` | - | 1 | ok | 0.00e+00 | 1e-05 |
-| `rope_table` | `rope_table_f32` | libr4d | device | `rot=64 theta=1e+07 scale=1 dtype=f32 M=16` | - | 1 | ok | 4.99e-08 | 1e-05 |
-| `rope_table` | `ref_rope_table` | libref | host | `rot=64 theta=1e+07 scale=1 dtype=f32 M=16` | - | 1 | ok | 0.00e+00 | 1e-05 |
-| `rope_table` | `rope_table_f32` | libr4d | device | `rot=64 theta=1e+07 scale=1 dtype=f32 M=32` | - | 1 | ok | 7.51e-08 | 1e-05 |
-| `rope_table` | `ref_rope_table` | libref | host | `rot=64 theta=1e+07 scale=1 dtype=f32 M=32` | - | 1 | ok | 0.00e+00 | 1e-05 |
+| `rope_table` | `ref_rope_table` | libref | host | `rot=64 theta=1e+07 scale=1 dtype=f32 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope_table` | `avx_rope_table` | libavx | host | `rot=64 theta=1e+07 scale=1 dtype=f32 M=16` | - | 1 | ok | 0.00e+00 | 1e-05 |
+| `rope_table` | `rope_table_f32` | libr4d | device | `rot=64 theta=1e+07 scale=1 dtype=f32 M=16` | - | 1 | ok | 5.15e-08 | 1e-05 |
+| `rope_table` | `ref_rope_table` | libref | host | `rot=64 theta=1e+07 scale=1 dtype=f32 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope_table` | `avx_rope_table` | libavx | host | `rot=64 theta=1e+07 scale=1 dtype=f32 M=32` | - | 1 | ok | 0.00e+00 | 1e-05 |
+| `rope_table` | `rope_table_f32` | libr4d | device | `rot=64 theta=1e+07 scale=1 dtype=f32 M=32` | - | 1 | ok | 9.56e-08 | 1e-05 |
+| `rope_table` | `ref_rope_table` | libref | host | `rot=64 theta=1e+07 scale=1 dtype=f32 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope_table` | `avx_rope_table` | libavx | host | `rot=64 theta=1e+07 scale=1 dtype=f32 M=64` | - | 1 | ok | 0.00e+00 | 1e-05 |
 | `rope_table` | `rope_table_f32` | libr4d | device | `rot=64 theta=1e+07 scale=1 dtype=f32 M=64` | - | 1 | ok | 1.62e-07 | 1e-05 |
-| `rope_table` | `ref_rope_table` | libref | host | `rot=64 theta=1e+07 scale=1 dtype=f32 M=64` | - | 1 | ok | 0.00e+00 | 1e-05 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 4.61e-09 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 9.84e-09 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 1.08e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 6.91e-05 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 1.24e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 7.57e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 7.95e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 1.10e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=130` | - | 1 | ok | 2.88e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=130` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=260` | - | 1 | ok | 2.65e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=260` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 1.04e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=96 K=5120 dtype=bf16 M=1 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=1 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `rope_table` | `ref_rope_table` | libref | host | `rot=64 theta=1e+07 scale=1 dtype=f32 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm_quant_fp8` | `avx_rmsnorm_quant_fp8` | libavx | host | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=1` | - | 1 | ok | 1.60e-04 | 4e-03 |
+| `rmsnorm_quant_fp8` | `rmsnorm_quant_fp8` | libr4d | device | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=1` | - | 1 | ok | 1.60e-04 | 4e-03 |
+| `rmsnorm_quant_fp8` | `ref_rmsnorm_quant_fp8` | libref | host | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm_quant_fp8` | `avx_rmsnorm_quant_fp8` | libavx | host | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=2` | - | 1 | ok | 1.15e-04 | 4e-03 |
+| `rmsnorm_quant_fp8` | `rmsnorm_quant_fp8` | libr4d | device | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=2` | - | 1 | ok | 1.22e-04 | 4e-03 |
+| `rmsnorm_quant_fp8` | `ref_rmsnorm_quant_fp8` | libref | host | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm_quant_fp8` | `avx_rmsnorm_quant_fp8` | libavx | host | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=4` | - | 1 | ok | 3.25e-04 | 4e-03 |
+| `rmsnorm_quant_fp8` | `rmsnorm_quant_fp8` | libr4d | device | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=4` | - | 1 | ok | 3.25e-04 | 4e-03 |
+| `rmsnorm_quant_fp8` | `ref_rmsnorm_quant_fp8` | libref | host | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm_quant_fp8` | `avx_rmsnorm_quant_fp8` | libavx | host | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=8` | - | 1 | ok | 2.12e-04 | 4e-03 |
+| `rmsnorm_quant_fp8` | `rmsnorm_quant_fp8` | libr4d | device | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=8` | - | 1 | ok | 2.12e-04 | 4e-03 |
+| `rmsnorm_quant_fp8` | `ref_rmsnorm_quant_fp8` | libref | host | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm_quant_fp8` | `avx_rmsnorm_quant_fp8` | libavx | host | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=16` | - | 1 | ok | 3.48e-04 | 4e-03 |
+| `rmsnorm_quant_fp8` | `rmsnorm_quant_fp8` | libr4d | device | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=16` | - | 1 | ok | 3.48e-04 | 4e-03 |
+| `rmsnorm_quant_fp8` | `ref_rmsnorm_quant_fp8` | libref | host | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm_quant_fp8` | `avx_rmsnorm_quant_fp8` | libavx | host | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=32` | - | 1 | ok | 5.75e-04 | 4e-03 |
+| `rmsnorm_quant_fp8` | `rmsnorm_quant_fp8` | libr4d | device | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=32` | - | 1 | ok | 5.75e-04 | 4e-03 |
+| `rmsnorm_quant_fp8` | `ref_rmsnorm_quant_fp8` | libref | host | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm_quant_fp8` | `avx_rmsnorm_quant_fp8` | libavx | host | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=64` | - | 1 | ok | 3.34e-04 | 4e-03 |
+| `rmsnorm_quant_fp8` | `rmsnorm_quant_fp8` | libr4d | device | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=64` | - | 1 | ok | 3.35e-04 | 4e-03 |
+| `rmsnorm_quant_fp8` | `ref_rmsnorm_quant_fp8` | libref | host | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm_quant_fp8` | `avx_rmsnorm_quant_fp8` | libavx | host | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=128` | - | 1 | ok | 7.83e-04 | 4e-03 |
+| `rmsnorm_quant_fp8` | `rmsnorm_quant_fp8` | libr4d | device | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=128` | - | 1 | ok | 7.83e-04 | 4e-03 |
+| `rmsnorm_quant_fp8` | `ref_rmsnorm_quant_fp8` | libref | host | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm_quant_fp8` | `avx_rmsnorm_quant_fp8` | libavx | host | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=256` | - | 1 | ok | 9.01e-04 | 4e-03 |
+| `rmsnorm_quant_fp8` | `rmsnorm_quant_fp8` | libr4d | device | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=256` | - | 1 | ok | 9.01e-04 | 4e-03 |
+| `rmsnorm_quant_fp8` | `ref_rmsnorm_quant_fp8` | libref | host | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm_quant_fp8` | `avx_rmsnorm_quant_fp8` | libavx | host | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=512` | - | 1 | ok | 5.88e-04 | 4e-03 |
+| `rmsnorm_quant_fp8` | `rmsnorm_quant_fp8` | libr4d | device | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=512` | - | 1 | ok | 5.92e-04 | 4e-03 |
+| `rmsnorm_quant_fp8` | `ref_rmsnorm_quant_fp8` | libref | host | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 1.08e-08 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 3.61e-06 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 1.44e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 3.11e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 2.14e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 3.30e-06 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 7.38e-06 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 1.67e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 9.03e-06 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 1.88e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 1.81e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 9.17e-06 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 9.87e-06 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 2.32e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 2.64e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 2.13e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 1.62e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=128` | - | 1 | ok | 2.09e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=128` | - | 1 | ok | 1.42e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=129` | - | 1 | ok | 2.18e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=129` | - | 1 | ok | 2.27e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=129` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=258` | - | 1 | ok | 2.39e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=258` | - | 1 | ok | 1.75e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=258` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 1.84e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 1.71e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt` | `avx_gemm_nt` | libavx | host | `N=96 K=5120 dtype=bf16 M=1 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 6.72e-08 | 8e-03 |
+| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=96 K=5120 dtype=bf16 M=1 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 5.74e-06 | 8e-03 |
+| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=1 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt` | `avx_gemm_nt` | libavx | host | `N=96 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
 | `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=96 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt` | `avx_gemm_nt` | libavx | host | `N=96 K=5120 dtype=bf16 M=4 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 1.71e-04 | 8e-03 |
 | `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=96 K=5120 dtype=bf16 M=4 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=4 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=96 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 6.00e-06 | 8e-03 |
-| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=96 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 1.57e-07 | 8e-03 |
-| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=96 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=96 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 3.35e-14 | 8e-03 |
-| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=96 K=5120 dtype=bf16 M=68 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 2.93e-09 | 8e-03 |
-| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=68 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=96 K=5120 dtype=bf16 M=136 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 5.00e-07 | 8e-03 |
-| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=136 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=96 K=5120 dtype=bf16 M=272 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 6.98e-07 | 8e-03 |
-| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=272 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=96 K=5120 dtype=bf16 M=512 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 3.23e-07 | 8e-03 |
-| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=512 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 chunk=64 conv_width=4 M=1` | - | 1 | ok | 1.91e-07 | 2e-02 |
-| `gdn_conv_prep` | `ref_gdn_conv_prep` | libref | host | `head_k=128 head_v=128 chunk=64 conv_width=4 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 chunk=64 conv_width=4 M=2` | - | 1 | ok | 5.92e-08 | 2e-02 |
-| `gdn_conv_prep` | `ref_gdn_conv_prep` | libref | host | `head_k=128 head_v=128 chunk=64 conv_width=4 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 chunk=64 conv_width=4 M=4` | - | 1 | ok | 3.02e-07 | 2e-02 |
-| `gdn_conv_prep` | `ref_gdn_conv_prep` | libref | host | `head_k=128 head_v=128 chunk=64 conv_width=4 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 chunk=64 conv_width=4 M=8` | - | 1 | ok | 7.31e-08 | 2e-02 |
-| `gdn_conv_prep` | `ref_gdn_conv_prep` | libref | host | `head_k=128 head_v=128 chunk=64 conv_width=4 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 chunk=64 conv_width=4 M=16` | - | 1 | ok | 1.31e-07 | 2e-02 |
-| `gdn_conv_prep` | `ref_gdn_conv_prep` | libref | host | `head_k=128 head_v=128 chunk=64 conv_width=4 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 chunk=64 conv_width=4 M=32` | - | 1 | ok | 8.24e-08 | 2e-02 |
-| `gdn_conv_prep` | `ref_gdn_conv_prep` | libref | host | `head_k=128 head_v=128 chunk=64 conv_width=4 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 chunk=64 conv_width=4 M=64` | - | 1 | ok | 2.81e-07 | 2e-02 |
-| `gdn_conv_prep` | `ref_gdn_conv_prep` | libref | host | `head_k=128 head_v=128 chunk=64 conv_width=4 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 chunk=64 conv_width=4 M=128` | - | 1 | ok | 9.72e-05 | 2e-02 |
-| `gdn_conv_prep` | `ref_gdn_conv_prep` | libref | host | `head_k=128 head_v=128 chunk=64 conv_width=4 M=128` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 chunk=64 conv_width=4 M=256` | - | 1 | ok | 1.14e-07 | 2e-02 |
-| `gdn_conv_prep` | `ref_gdn_conv_prep` | libref | host | `head_k=128 head_v=128 chunk=64 conv_width=4 M=256` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 chunk=64 conv_width=4 M=512` | - | 1 | ok | 1.18e-07 | 2e-02 |
-| `gdn_conv_prep` | `ref_gdn_conv_prep` | libref | host | `head_k=128 head_v=128 chunk=64 conv_width=4 M=512` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | device | `head_k=128 M=1 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_kkt_solve` | `ref_gdn_kkt_solve` | libref | host | `head_k=128 M=1 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | device | `head_k=128 M=2 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_kkt_solve` | `ref_gdn_kkt_solve` | libref | host | `head_k=128 M=2 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | device | `head_k=128 M=4 chunk=64` | - | 1 | ok | 1.63e-05 | 2e-02 |
-| `gdn_kkt_solve` | `ref_gdn_kkt_solve` | libref | host | `head_k=128 M=4 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | device | `head_k=128 M=8 chunk=64` | - | 1 | ok | 2.72e-05 | 2e-02 |
-| `gdn_kkt_solve` | `ref_gdn_kkt_solve` | libref | host | `head_k=128 M=8 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | device | `head_k=128 M=16 chunk=64` | - | 1 | ok | 3.85e-05 | 2e-02 |
-| `gdn_kkt_solve` | `ref_gdn_kkt_solve` | libref | host | `head_k=128 M=16 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | device | `head_k=128 M=32 chunk=64` | - | 1 | ok | 2.54e-05 | 2e-02 |
-| `gdn_kkt_solve` | `ref_gdn_kkt_solve` | libref | host | `head_k=128 M=32 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | device | `head_k=128 M=64 chunk=64` | - | 1 | ok | 7.76e-05 | 2e-02 |
-| `gdn_kkt_solve` | `ref_gdn_kkt_solve` | libref | host | `head_k=128 M=64 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | device | `head_k=128 M=128 chunk=64` | - | 1 | ok | 8.13e-05 | 2e-02 |
-| `gdn_kkt_solve` | `ref_gdn_kkt_solve` | libref | host | `head_k=128 M=128 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | device | `head_k=128 M=256 chunk=64` | - | 1 | ok | 5.42e-05 | 2e-02 |
-| `gdn_kkt_solve` | `ref_gdn_kkt_solve` | libref | host | `head_k=128 M=256 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | device | `head_k=128 M=512 chunk=64` | - | 1 | ok | 1.76e-05 | 2e-02 |
-| `gdn_kkt_solve` | `ref_gdn_kkt_solve` | libref | host | `head_k=128 M=512 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | device | `head_k=128 head_v=128 scale=0.0883883 M=1 chunk=64` | - | 1 | ok | 2.37e-03 | 2e-02 |
-| `gdn_chunk_scan` | `ref_gdn_chunk_scan` | libref | host | `head_k=128 head_v=128 scale=0.0883883 M=1 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
+| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=4 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt` | `avx_gemm_nt` | libavx | host | `N=96 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=96 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt` | `avx_gemm_nt` | libavx | host | `N=96 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 2.16e-08 | 8e-03 |
+| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=96 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 2.16e-08 | 8e-03 |
+| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt` | `avx_gemm_nt` | libavx | host | `N=96 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 2.11e-08 | 8e-03 |
+| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=96 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 2.11e-08 | 8e-03 |
+| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt` | `avx_gemm_nt` | libavx | host | `N=96 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 2.46e-04 | 8e-03 |
+| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=96 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 2.47e-04 | 8e-03 |
+| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt` | `avx_gemm_nt` | libavx | host | `N=96 K=5120 dtype=bf16 M=64 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 9.76e-08 | 8e-03 |
+| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=96 K=5120 dtype=bf16 M=64 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 2.79e-06 | 8e-03 |
+| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=64 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt` | `avx_gemm_nt` | libavx | host | `N=96 K=5120 dtype=bf16 M=65 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 5.06e-05 | 8e-03 |
+| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=96 K=5120 dtype=bf16 M=65 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 4.38e-05 | 8e-03 |
+| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=65 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt` | `avx_gemm_nt` | libavx | host | `N=96 K=5120 dtype=bf16 M=130 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 9.08e-05 | 8e-03 |
+| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=96 K=5120 dtype=bf16 M=130 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 9.03e-05 | 8e-03 |
+| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=130 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt` | `avx_gemm_nt` | libavx | host | `N=96 K=5120 dtype=bf16 M=260 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 1.07e-04 | 8e-03 |
+| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=96 K=5120 dtype=bf16 M=260 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 1.02e-04 | 8e-03 |
+| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=260 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt` | `avx_gemm_nt` | libavx | host | `N=96 K=5120 dtype=bf16 M=512 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 6.05e-05 | 8e-03 |
+| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=96 K=5120 dtype=bf16 M=512 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 1.06e-04 | 8e-03 |
+| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=512 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_kkt_solve` | `avx_gdn_kkt_solve` | libavx | host | `head_k=128 M=1 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | device | `head_k=128 M=1 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `gdn_kkt_solve` | `ref_gdn_kkt_solve` | libref | host | `head_k=128 M=1 chunk=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_kkt_solve` | `avx_gdn_kkt_solve` | libavx | host | `head_k=128 M=2 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | device | `head_k=128 M=2 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `gdn_kkt_solve` | `ref_gdn_kkt_solve` | libref | host | `head_k=128 M=2 chunk=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_kkt_solve` | `avx_gdn_kkt_solve` | libavx | host | `head_k=128 M=4 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | device | `head_k=128 M=4 chunk=64` | - | 1 | ok | 5.28e-05 | 2e-03 |
+| `gdn_kkt_solve` | `ref_gdn_kkt_solve` | libref | host | `head_k=128 M=4 chunk=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_kkt_solve` | `avx_gdn_kkt_solve` | libavx | host | `head_k=128 M=8 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | device | `head_k=128 M=8 chunk=64` | - | 1 | ok | 3.78e-05 | 2e-03 |
+| `gdn_kkt_solve` | `ref_gdn_kkt_solve` | libref | host | `head_k=128 M=8 chunk=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_kkt_solve` | `avx_gdn_kkt_solve` | libavx | host | `head_k=128 M=16 chunk=64` | - | 1 | ok | 1.07e-09 | 2e-03 |
+| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | device | `head_k=128 M=16 chunk=64` | - | 1 | ok | 4.35e-05 | 2e-03 |
+| `gdn_kkt_solve` | `ref_gdn_kkt_solve` | libref | host | `head_k=128 M=16 chunk=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_kkt_solve` | `avx_gdn_kkt_solve` | libavx | host | `head_k=128 M=32 chunk=64` | - | 1 | ok | 3.04e-09 | 2e-03 |
+| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | device | `head_k=128 M=32 chunk=64` | - | 1 | ok | 4.26e-05 | 2e-03 |
+| `gdn_kkt_solve` | `ref_gdn_kkt_solve` | libref | host | `head_k=128 M=32 chunk=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_kkt_solve` | `avx_gdn_kkt_solve` | libavx | host | `head_k=128 M=64 chunk=64` | - | 1 | ok | 6.45e-13 | 2e-03 |
+| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | device | `head_k=128 M=64 chunk=64` | - | 1 | ok | 7.76e-05 | 2e-03 |
+| `gdn_kkt_solve` | `ref_gdn_kkt_solve` | libref | host | `head_k=128 M=64 chunk=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_kkt_solve` | `avx_gdn_kkt_solve` | libavx | host | `head_k=128 M=128 chunk=64` | - | 1 | ok | 1.78e-06 | 2e-03 |
+| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | device | `head_k=128 M=128 chunk=64` | - | 1 | ok | 8.13e-05 | 2e-03 |
+| `gdn_kkt_solve` | `ref_gdn_kkt_solve` | libref | host | `head_k=128 M=128 chunk=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_kkt_solve` | `avx_gdn_kkt_solve` | libavx | host | `head_k=128 M=256 chunk=64` | - | 1 | ok | 3.67e-08 | 2e-03 |
+| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | device | `head_k=128 M=256 chunk=64` | - | 1 | ok | 5.42e-05 | 2e-03 |
+| `gdn_kkt_solve` | `ref_gdn_kkt_solve` | libref | host | `head_k=128 M=256 chunk=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_kkt_solve` | `avx_gdn_kkt_solve` | libavx | host | `head_k=128 M=512 chunk=64` | - | 1 | ok | 3.89e-07 | 2e-03 |
+| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | device | `head_k=128 M=512 chunk=64` | - | 1 | ok | 4.61e-05 | 2e-03 |
+| `gdn_kkt_solve` | `ref_gdn_kkt_solve` | libref | host | `head_k=128 M=512 chunk=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_chunk_scan` | `avx_gdn_chunk_scan` | libavx | host | `head_k=128 head_v=128 scale=0.0883883 M=1 chunk=64` | - | 1 | ok | 4.79e-05 | 2e-02 |
+| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | device | `head_k=128 head_v=128 scale=0.0883883 M=1 chunk=64` | - | 1 | ok | 3.04e-03 | 2e-02 |
+| `gdn_chunk_scan` | `ref_gdn_chunk_scan` | libref | host | `head_k=128 head_v=128 scale=0.0883883 M=1 chunk=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_chunk_scan` | `avx_gdn_chunk_scan` | libavx | host | `head_k=128 head_v=128 scale=0.0883883 M=2 chunk=64` | - | 1 | ok | 2.73e-07 | 2e-02 |
 | `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | device | `head_k=128 head_v=128 scale=0.0883883 M=2 chunk=64` | - | 1 | ok | 2.48e-03 | 2e-02 |
-| `gdn_chunk_scan` | `ref_gdn_chunk_scan` | libref | host | `head_k=128 head_v=128 scale=0.0883883 M=2 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | device | `head_k=128 head_v=128 scale=0.0883883 M=4 chunk=64` | - | 1 | ok | 2.63e-03 | 2e-02 |
-| `gdn_chunk_scan` | `ref_gdn_chunk_scan` | libref | host | `head_k=128 head_v=128 scale=0.0883883 M=4 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | device | `head_k=128 head_v=128 scale=0.0883883 M=8 chunk=64` | - | 1 | ok | 2.48e-03 | 2e-02 |
-| `gdn_chunk_scan` | `ref_gdn_chunk_scan` | libref | host | `head_k=128 head_v=128 scale=0.0883883 M=8 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
+| `gdn_chunk_scan` | `ref_gdn_chunk_scan` | libref | host | `head_k=128 head_v=128 scale=0.0883883 M=2 chunk=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_chunk_scan` | `avx_gdn_chunk_scan` | libavx | host | `head_k=128 head_v=128 scale=0.0883883 M=4 chunk=64` | - | 1 | ok | 6.84e-08 | 2e-02 |
+| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | device | `head_k=128 head_v=128 scale=0.0883883 M=4 chunk=64` | - | 1 | ok | 3.08e-03 | 2e-02 |
+| `gdn_chunk_scan` | `ref_gdn_chunk_scan` | libref | host | `head_k=128 head_v=128 scale=0.0883883 M=4 chunk=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_chunk_scan` | `avx_gdn_chunk_scan` | libavx | host | `head_k=128 head_v=128 scale=0.0883883 M=8 chunk=64` | - | 1 | ok | 5.40e-05 | 2e-02 |
+| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | device | `head_k=128 head_v=128 scale=0.0883883 M=8 chunk=64` | - | 1 | ok | 2.88e-03 | 2e-02 |
+| `gdn_chunk_scan` | `ref_gdn_chunk_scan` | libref | host | `head_k=128 head_v=128 scale=0.0883883 M=8 chunk=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_chunk_scan` | `avx_gdn_chunk_scan` | libavx | host | `head_k=128 head_v=128 scale=0.0883883 M=16 chunk=64` | - | 1 | ok | 5.06e-06 | 2e-02 |
 | `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | device | `head_k=128 head_v=128 scale=0.0883883 M=16 chunk=64` | - | 1 | ok | 2.76e-03 | 2e-02 |
-| `gdn_chunk_scan` | `ref_gdn_chunk_scan` | libref | host | `head_k=128 head_v=128 scale=0.0883883 M=16 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
+| `gdn_chunk_scan` | `ref_gdn_chunk_scan` | libref | host | `head_k=128 head_v=128 scale=0.0883883 M=16 chunk=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_chunk_scan` | `avx_gdn_chunk_scan` | libavx | host | `head_k=128 head_v=128 scale=0.0883883 M=32 chunk=64` | - | 1 | ok | 2.59e-06 | 2e-02 |
 | `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | device | `head_k=128 head_v=128 scale=0.0883883 M=32 chunk=64` | - | 1 | ok | 3.40e-03 | 2e-02 |
-| `gdn_chunk_scan` | `ref_gdn_chunk_scan` | libref | host | `head_k=128 head_v=128 scale=0.0883883 M=32 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | device | `head_k=128 head_v=128 scale=0.0883883 M=64 chunk=64` | - | 1 | ok | 3.33e-03 | 2e-02 |
-| `gdn_chunk_scan` | `ref_gdn_chunk_scan` | libref | host | `head_k=128 head_v=128 scale=0.0883883 M=64 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
+| `gdn_chunk_scan` | `ref_gdn_chunk_scan` | libref | host | `head_k=128 head_v=128 scale=0.0883883 M=32 chunk=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_chunk_scan` | `avx_gdn_chunk_scan` | libavx | host | `head_k=128 head_v=128 scale=0.0883883 M=64 chunk=64` | - | 1 | ok | 4.07e-06 | 2e-02 |
+| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | device | `head_k=128 head_v=128 scale=0.0883883 M=64 chunk=64` | - | 1 | ok | 3.72e-03 | 2e-02 |
+| `gdn_chunk_scan` | `ref_gdn_chunk_scan` | libref | host | `head_k=128 head_v=128 scale=0.0883883 M=64 chunk=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_chunk_scan` | `avx_gdn_chunk_scan` | libavx | host | `head_k=128 head_v=128 scale=0.0883883 M=128 chunk=64` | - | 1 | ok | 3.81e-05 | 2e-02 |
 | `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | device | `head_k=128 head_v=128 scale=0.0883883 M=128 chunk=64` | - | 1 | ok | 4.27e-03 | 2e-02 |
-| `gdn_chunk_scan` | `ref_gdn_chunk_scan` | libref | host | `head_k=128 head_v=128 scale=0.0883883 M=128 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | device | `head_k=128 head_v=128 scale=0.0883883 M=256 chunk=64` | - | 1 | ok | 3.48e-03 | 2e-02 |
-| `gdn_chunk_scan` | `ref_gdn_chunk_scan` | libref | host | `head_k=128 head_v=128 scale=0.0883883 M=256 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
+| `gdn_chunk_scan` | `ref_gdn_chunk_scan` | libref | host | `head_k=128 head_v=128 scale=0.0883883 M=128 chunk=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_chunk_scan` | `avx_gdn_chunk_scan` | libavx | host | `head_k=128 head_v=128 scale=0.0883883 M=256 chunk=64` | - | 1 | ok | 1.92e-05 | 2e-02 |
+| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | device | `head_k=128 head_v=128 scale=0.0883883 M=256 chunk=64` | - | 1 | ok | 3.53e-03 | 2e-02 |
+| `gdn_chunk_scan` | `ref_gdn_chunk_scan` | libref | host | `head_k=128 head_v=128 scale=0.0883883 M=256 chunk=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_chunk_scan` | `avx_gdn_chunk_scan` | libavx | host | `head_k=128 head_v=128 scale=0.0883883 M=512 chunk=64` | - | 1 | ok | 1.92e-05 | 2e-02 |
 | `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | device | `head_k=128 head_v=128 scale=0.0883883 M=512 chunk=64` | - | 1 | ok | 3.64e-03 | 2e-02 |
-| `gdn_chunk_scan` | `ref_gdn_chunk_scan` | libref | host | `head_k=128 head_v=128 scale=0.0883883 M=512 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | device | `channels=128 eps=1e-06 act=silu M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_gated_rmsnorm` | `ref_gdn_gated_rmsnorm` | libref | host | `channels=128 eps=1e-06 act=silu M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | device | `channels=128 eps=1e-06 act=silu M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_gated_rmsnorm` | `ref_gdn_gated_rmsnorm` | libref | host | `channels=128 eps=1e-06 act=silu M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | device | `channels=128 eps=1e-06 act=silu M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_gated_rmsnorm` | `ref_gdn_gated_rmsnorm` | libref | host | `channels=128 eps=1e-06 act=silu M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | device | `channels=128 eps=1e-06 act=silu M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_gated_rmsnorm` | `ref_gdn_gated_rmsnorm` | libref | host | `channels=128 eps=1e-06 act=silu M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | device | `channels=128 eps=1e-06 act=silu M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_gated_rmsnorm` | `ref_gdn_gated_rmsnorm` | libref | host | `channels=128 eps=1e-06 act=silu M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | device | `channels=128 eps=1e-06 act=silu M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_gated_rmsnorm` | `ref_gdn_gated_rmsnorm` | libref | host | `channels=128 eps=1e-06 act=silu M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | device | `channels=128 eps=1e-06 act=silu M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_gated_rmsnorm` | `ref_gdn_gated_rmsnorm` | libref | host | `channels=128 eps=1e-06 act=silu M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | device | `channels=128 eps=1e-06 act=silu M=128` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_gated_rmsnorm` | `ref_gdn_gated_rmsnorm` | libref | host | `channels=128 eps=1e-06 act=silu M=128` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | device | `channels=128 eps=1e-06 act=silu M=256` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_gated_rmsnorm` | `ref_gdn_gated_rmsnorm` | libref | host | `channels=128 eps=1e-06 act=silu M=256` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | device | `channels=128 eps=1e-06 act=silu M=512` | - | 1 | ok | 5.73e-08 | 2e-02 |
-| `gdn_gated_rmsnorm` | `ref_gdn_gated_rmsnorm` | libref | host | `channels=128 eps=1e-06 act=silu M=512` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 conv_width=4 q_len=1` | - | 1 | ok | 4.95e-08 | 2e-02 |
-| `gdn_conv_update` | `ref_gdn_conv_update` | libref | host | `head_k=128 head_v=128 conv_width=4 q_len=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 conv_width=4 q_len=2` | - | 1 | ok | 2.45e-08 | 2e-02 |
-| `gdn_conv_update` | `ref_gdn_conv_update` | libref | host | `head_k=128 head_v=128 conv_width=4 q_len=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 conv_width=4 q_len=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_conv_update` | `ref_gdn_conv_update` | libref | host | `head_k=128 head_v=128 conv_width=4 q_len=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 conv_width=4 q_len=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_conv_update` | `ref_gdn_conv_update` | libref | host | `head_k=128 head_v=128 conv_width=4 q_len=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 conv_width=4 q_len=16` | - | 1 | ok | 2.62e-07 | 2e-02 |
-| `gdn_conv_update` | `ref_gdn_conv_update` | libref | host | `head_k=128 head_v=128 conv_width=4 q_len=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 conv_width=4 q_len=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_conv_update` | `ref_gdn_conv_update` | libref | host | `head_k=128 head_v=128 conv_width=4 q_len=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 conv_width=4 q_len=64` | - | 1 | ok | 1.94e-07 | 2e-02 |
-| `gdn_conv_update` | `ref_gdn_conv_update` | libref | host | `head_k=128 head_v=128 conv_width=4 q_len=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 conv_width=4 q_len=128` | - | 1 | ok | 3.51e-08 | 2e-02 |
-| `gdn_conv_update` | `ref_gdn_conv_update` | libref | host | `head_k=128 head_v=128 conv_width=4 q_len=128` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 conv_width=4 q_len=256` | - | 1 | ok | 7.97e-08 | 2e-02 |
-| `gdn_conv_update` | `ref_gdn_conv_update` | libref | host | `head_k=128 head_v=128 conv_width=4 q_len=256` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 conv_width=4 q_len=512` | - | 1 | ok | 3.09e-08 | 2e-02 |
-| `gdn_conv_update` | `ref_gdn_conv_update` | libref | host | `head_k=128 head_v=128 conv_width=4 q_len=512` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | device | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=1` | - | 1 | ok | 6.79e-08 | 2e-02 |
-| `gdn_recurrent_update` | `ref_gdn_recurrent_update` | libref | host | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | device | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=2` | - | 1 | ok | 7.98e-08 | 2e-02 |
-| `gdn_recurrent_update` | `ref_gdn_recurrent_update` | libref | host | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | device | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=4` | - | 1 | ok | 8.22e-08 | 2e-02 |
-| `gdn_recurrent_update` | `ref_gdn_recurrent_update` | libref | host | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | device | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=8` | - | 1 | ok | 6.98e-08 | 2e-02 |
-| `gdn_recurrent_update` | `ref_gdn_recurrent_update` | libref | host | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | device | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=16` | - | 1 | ok | 8.01e-08 | 2e-02 |
-| `gdn_recurrent_update` | `ref_gdn_recurrent_update` | libref | host | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | device | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=32` | - | 1 | ok | 2.62e-06 | 2e-02 |
-| `gdn_recurrent_update` | `ref_gdn_recurrent_update` | libref | host | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | device | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=64` | - | 1 | ok | 6.90e-08 | 2e-02 |
-| `gdn_recurrent_update` | `ref_gdn_recurrent_update` | libref | host | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | device | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=128` | - | 1 | ok | 9.63e-08 | 2e-02 |
-| `gdn_recurrent_update` | `ref_gdn_recurrent_update` | libref | host | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=128` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | device | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=256` | - | 1 | ok | 3.17e-07 | 2e-02 |
-| `gdn_recurrent_update` | `ref_gdn_recurrent_update` | libref | host | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=256` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | device | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=512` | - | 1 | ok | 1.14e-07 | 2e-02 |
-| `gdn_recurrent_update` | `ref_gdn_recurrent_update` | libref | host | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=512` | - | 1 | ok | 0.00e+00 | 2e-02 |
+| `gdn_chunk_scan` | `ref_gdn_chunk_scan` | libref | host | `head_k=128 head_v=128 scale=0.0883883 M=512 chunk=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_gated_rmsnorm` | `avx_gdn_gated_rmsnorm` | libavx | host | `channels=128 eps=1e-06 act=silu M=1` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | device | `channels=128 eps=1e-06 act=silu M=1` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `gdn_gated_rmsnorm` | `ref_gdn_gated_rmsnorm` | libref | host | `channels=128 eps=1e-06 act=silu M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_gated_rmsnorm` | `avx_gdn_gated_rmsnorm` | libavx | host | `channels=128 eps=1e-06 act=silu M=2` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | device | `channels=128 eps=1e-06 act=silu M=2` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `gdn_gated_rmsnorm` | `ref_gdn_gated_rmsnorm` | libref | host | `channels=128 eps=1e-06 act=silu M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_gated_rmsnorm` | `avx_gdn_gated_rmsnorm` | libavx | host | `channels=128 eps=1e-06 act=silu M=4` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | device | `channels=128 eps=1e-06 act=silu M=4` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `gdn_gated_rmsnorm` | `ref_gdn_gated_rmsnorm` | libref | host | `channels=128 eps=1e-06 act=silu M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_gated_rmsnorm` | `avx_gdn_gated_rmsnorm` | libavx | host | `channels=128 eps=1e-06 act=silu M=8` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | device | `channels=128 eps=1e-06 act=silu M=8` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `gdn_gated_rmsnorm` | `ref_gdn_gated_rmsnorm` | libref | host | `channels=128 eps=1e-06 act=silu M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_gated_rmsnorm` | `avx_gdn_gated_rmsnorm` | libavx | host | `channels=128 eps=1e-06 act=silu M=16` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | device | `channels=128 eps=1e-06 act=silu M=16` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `gdn_gated_rmsnorm` | `ref_gdn_gated_rmsnorm` | libref | host | `channels=128 eps=1e-06 act=silu M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_gated_rmsnorm` | `avx_gdn_gated_rmsnorm` | libavx | host | `channels=128 eps=1e-06 act=silu M=32` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | device | `channels=128 eps=1e-06 act=silu M=32` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `gdn_gated_rmsnorm` | `ref_gdn_gated_rmsnorm` | libref | host | `channels=128 eps=1e-06 act=silu M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_gated_rmsnorm` | `avx_gdn_gated_rmsnorm` | libavx | host | `channels=128 eps=1e-06 act=silu M=64` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | device | `channels=128 eps=1e-06 act=silu M=64` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `gdn_gated_rmsnorm` | `ref_gdn_gated_rmsnorm` | libref | host | `channels=128 eps=1e-06 act=silu M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_gated_rmsnorm` | `avx_gdn_gated_rmsnorm` | libavx | host | `channels=128 eps=1e-06 act=silu M=128` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | device | `channels=128 eps=1e-06 act=silu M=128` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `gdn_gated_rmsnorm` | `ref_gdn_gated_rmsnorm` | libref | host | `channels=128 eps=1e-06 act=silu M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_gated_rmsnorm` | `avx_gdn_gated_rmsnorm` | libavx | host | `channels=128 eps=1e-06 act=silu M=256` | - | 1 | ok | 3.92e-05 | 2e-03 |
+| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | device | `channels=128 eps=1e-06 act=silu M=256` | - | 1 | ok | 3.92e-05 | 2e-03 |
+| `gdn_gated_rmsnorm` | `ref_gdn_gated_rmsnorm` | libref | host | `channels=128 eps=1e-06 act=silu M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_gated_rmsnorm` | `avx_gdn_gated_rmsnorm` | libavx | host | `channels=128 eps=1e-06 act=silu M=512` | - | 1 | ok | 3.48e-06 | 2e-03 |
+| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | device | `channels=128 eps=1e-06 act=silu M=512` | - | 1 | ok | 3.48e-06 | 2e-03 |
+| `gdn_gated_rmsnorm` | `ref_gdn_gated_rmsnorm` | libref | host | `channels=128 eps=1e-06 act=silu M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_conv_update` | `avx_gdn_conv_update` | libavx | host | `head_k=128 head_v=128 conv_width=4 q_len=1` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 conv_width=4 q_len=1` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `gdn_conv_update` | `ref_gdn_conv_update` | libref | host | `head_k=128 head_v=128 conv_width=4 q_len=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_conv_update` | `avx_gdn_conv_update` | libavx | host | `head_k=128 head_v=128 conv_width=4 q_len=2` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 conv_width=4 q_len=2` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `gdn_conv_update` | `ref_gdn_conv_update` | libref | host | `head_k=128 head_v=128 conv_width=4 q_len=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_conv_update` | `avx_gdn_conv_update` | libavx | host | `head_k=128 head_v=128 conv_width=4 q_len=4` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 conv_width=4 q_len=4` | - | 1 | ok | 1.33e-04 | 2e-03 |
+| `gdn_conv_update` | `ref_gdn_conv_update` | libref | host | `head_k=128 head_v=128 conv_width=4 q_len=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_conv_update` | `avx_gdn_conv_update` | libavx | host | `head_k=128 head_v=128 conv_width=4 q_len=8` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 conv_width=4 q_len=8` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `gdn_conv_update` | `ref_gdn_conv_update` | libref | host | `head_k=128 head_v=128 conv_width=4 q_len=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_conv_update` | `avx_gdn_conv_update` | libavx | host | `head_k=128 head_v=128 conv_width=4 q_len=16` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 conv_width=4 q_len=16` | - | 1 | ok | 6.80e-05 | 2e-03 |
+| `gdn_conv_update` | `ref_gdn_conv_update` | libref | host | `head_k=128 head_v=128 conv_width=4 q_len=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_conv_update` | `avx_gdn_conv_update` | libavx | host | `head_k=128 head_v=128 conv_width=4 q_len=32` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 conv_width=4 q_len=32` | - | 1 | ok | 3.62e-06 | 2e-03 |
+| `gdn_conv_update` | `ref_gdn_conv_update` | libref | host | `head_k=128 head_v=128 conv_width=4 q_len=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_conv_update` | `avx_gdn_conv_update` | libavx | host | `head_k=128 head_v=128 conv_width=4 q_len=64` | - | 1 | ok | 9.32e-06 | 2e-03 |
+| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 conv_width=4 q_len=64` | - | 1 | ok | 4.33e-06 | 2e-03 |
+| `gdn_conv_update` | `ref_gdn_conv_update` | libref | host | `head_k=128 head_v=128 conv_width=4 q_len=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_conv_update` | `avx_gdn_conv_update` | libavx | host | `head_k=128 head_v=128 conv_width=4 q_len=128` | - | 1 | ok | 1.14e-05 | 2e-03 |
+| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 conv_width=4 q_len=128` | - | 1 | ok | 2.30e-05 | 2e-03 |
+| `gdn_conv_update` | `ref_gdn_conv_update` | libref | host | `head_k=128 head_v=128 conv_width=4 q_len=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_conv_update` | `avx_gdn_conv_update` | libavx | host | `head_k=128 head_v=128 conv_width=4 q_len=256` | - | 1 | ok | 1.29e-05 | 2e-03 |
+| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 conv_width=4 q_len=256` | - | 1 | ok | 2.40e-05 | 2e-03 |
+| `gdn_conv_update` | `ref_gdn_conv_update` | libref | host | `head_k=128 head_v=128 conv_width=4 q_len=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_conv_update` | `avx_gdn_conv_update` | libavx | host | `head_k=128 head_v=128 conv_width=4 q_len=512` | - | 1 | ok | 7.80e-06 | 2e-03 |
+| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 conv_width=4 q_len=512` | - | 1 | ok | 1.50e-05 | 2e-03 |
+| `gdn_conv_update` | `ref_gdn_conv_update` | libref | host | `head_k=128 head_v=128 conv_width=4 q_len=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_recurrent_update` | `avx_gdn_recurrent_update` | libavx | host | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu state_form=anchor q_len=1` | - | 1 | ok | 1.04e-05 | 2e-02 |
+| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | device | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu state_form=anchor q_len=1` | - | 1 | ok | 6.54e-07 | 2e-02 |
+| `gdn_recurrent_update` | `ref_gdn_recurrent_update` | libref | host | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu state_form=anchor q_len=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_recurrent_update` | `avx_gdn_recurrent_update` | libavx | host | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu state_form=anchor q_len=2` | - | 1 | ok | 6.01e-05 | 2e-02 |
+| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | device | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu state_form=anchor q_len=2` | - | 1 | ok | 6.04e-05 | 2e-02 |
+| `gdn_recurrent_update` | `ref_gdn_recurrent_update` | libref | host | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu state_form=anchor q_len=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_recurrent_update` | `avx_gdn_recurrent_update` | libavx | host | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu state_form=anchor q_len=4` | - | 1 | ok | 2.39e-07 | 2e-02 |
+| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | device | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu state_form=anchor q_len=4` | - | 1 | ok | 4.64e-07 | 2e-02 |
+| `gdn_recurrent_update` | `ref_gdn_recurrent_update` | libref | host | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu state_form=anchor q_len=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_recurrent_update` | `avx_gdn_recurrent_update` | libavx | host | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu state_form=anchor q_len=8` | - | 1 | ok | 3.73e-06 | 2e-02 |
+| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | device | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu state_form=anchor q_len=8` | - | 1 | ok | 9.67e-06 | 2e-02 |
+| `gdn_recurrent_update` | `ref_gdn_recurrent_update` | libref | host | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu state_form=anchor q_len=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gdn_recurrent_update` | `avx_gdn_recurrent_update` | libavx | host | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu state_form=anchor q_len=16` | - | 1 | ok | 9.82e-05 | 2e-02 |
+| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | device | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu state_form=anchor q_len=16` | - | 1 | ok | 4.06e-05 | 2e-02 |
+| `gdn_recurrent_update` | `ref_gdn_recurrent_update` | libref | host | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu state_form=anchor q_len=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=6144 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
 | `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=6144 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=6144 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=6144 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=6144 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
 | `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=6144 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=6144 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=6144 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=6144 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
 | `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=6144 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=6144 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=6144 group=128 dtype=bf16 M=8` | - | 1 | ok | 5.86e-15 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=6144 group=128 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=6144 group=128 dtype=bf16 M=16` | - | 1 | ok | 3.00e-15 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=6144 group=128 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=6144 group=128 dtype=bf16 M=32` | - | 1 | ok | 1.42e-15 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=6144 group=128 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=6144 group=128 dtype=bf16 M=64` | - | 1 | ok | 7.18e-16 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=6144 group=128 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=6144 group=128 dtype=bf16 M=128` | - | 1 | ok | 6.10e-16 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=6144 group=128 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=6144 group=128 dtype=bf16 M=256` | - | 1 | ok | 8.61e-16 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=6144 group=128 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=6144 group=128 dtype=bf16 M=512` | - | 1 | ok | 1.63e-15 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=6144 group=128 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 9.54e-16 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 7.22e-09 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 7.08e-11 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 3.90e-10 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 6.07e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 2.05e-11 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 3.11e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 3.59e-09 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=130` | - | 1 | ok | 1.79e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=130` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=260` | - | 1 | ok | 7.15e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=260` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 1.60e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 7.15e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 2.20e-09 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 2.87e-09 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 1.33e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 2.57e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 3.15e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 9.74e-09 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 2.38e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 9.90e-09 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=130` | - | 1 | ok | 2.27e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=130` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=260` | - | 1 | ok | 1.92e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=260` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 4.64e-09 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 8.01e-05 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 3.56e-13 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 5.04e-11 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 4.56e-09 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 5.84e-12 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 6.06e-10 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 6.89e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 4.32e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 1.29e-07 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=130` | - | 1 | ok | 3.36e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=130` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=260` | - | 1 | ok | 4.29e-09 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=260` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 2.83e-09 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 3.47e-09 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 1.32e-12 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 2.21e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 2.59e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 7.04e-10 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 3.35e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 9.76e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 2.33e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=130` | - | 1 | ok | 4.36e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=130` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=260` | - | 1 | ok | 6.33e-09 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=260` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 2.25e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 1.33e-15 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 1.69e-07 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 9.42e-09 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 3.27e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 5.99e-11 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=130` | - | 1 | ok | 2.53e-07 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=130` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=260` | - | 1 | ok | 2.85e-07 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=260` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 1.22e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=6144 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=6144 group=128 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=6144 group=128 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=6144 group=128 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=6144 group=128 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=6144 group=128 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=6144 group=128 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=6144 group=128 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=6144 group=128 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=6144 group=128 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=6144 group=128 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=6144 group=128 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=6144 group=128 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=6144 group=128 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=6144 group=128 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=6144 group=128 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=6144 group=128 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=6144 group=128 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=6144 group=128 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=6144 group=128 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=6144 group=128 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=6144 group=128 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 2.37e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 7.25e-10 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 1.08e-09 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 8.85e-06 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 9.25e-08 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 5.91e-06 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 5.77e-06 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 5.45e-06 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 1.13e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 8.04e-06 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 1.25e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 3.16e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 1.83e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 1.76e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 2.51e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 6.98e-06 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=128` | - | 1 | ok | 1.54e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=128` | - | 1 | ok | 2.04e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=129` | - | 1 | ok | 2.07e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=129` | - | 1 | ok | 1.82e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=129` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=258` | - | 1 | ok | 1.08e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=258` | - | 1 | ok | 1.36e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=258` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 2.13e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 1.75e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 4.13e-06 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 4.14e-06 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 1.95e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 1.19e-09 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 3.11e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 3.14e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 1.01e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 8.70e-06 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 1.96e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 1.39e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 1.36e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 1.78e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 1.11e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 9.79e-06 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 1.57e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 1.71e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 1.72e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 2.16e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=128` | - | 1 | ok | 1.73e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=128` | - | 1 | ok | 1.37e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=129` | - | 1 | ok | 1.59e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=129` | - | 1 | ok | 1.28e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=129` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=258` | - | 1 | ok | 1.41e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=258` | - | 1 | ok | 1.67e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=258` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 1.91e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 1.37e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gated_quant_fp8` | `avx_gated_quant_fp8` | libavx | host | `n=17408 group=128 dtype=bf16 act=silu M=1` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `gated_quant_fp8` | `gated_quant_fp8` | libr4d | device | `n=17408 group=128 dtype=bf16 act=silu M=1` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `gated_quant_fp8` | `ref_gated_quant_fp8` | libref | host | `n=17408 group=128 dtype=bf16 act=silu M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gated_quant_fp8` | `avx_gated_quant_fp8` | libavx | host | `n=17408 group=128 dtype=bf16 act=silu M=2` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `gated_quant_fp8` | `gated_quant_fp8` | libr4d | device | `n=17408 group=128 dtype=bf16 act=silu M=2` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `gated_quant_fp8` | `ref_gated_quant_fp8` | libref | host | `n=17408 group=128 dtype=bf16 act=silu M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gated_quant_fp8` | `avx_gated_quant_fp8` | libavx | host | `n=17408 group=128 dtype=bf16 act=silu M=4` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `gated_quant_fp8` | `gated_quant_fp8` | libr4d | device | `n=17408 group=128 dtype=bf16 act=silu M=4` | - | 1 | ok | 1.25e-05 | 6e-03 |
+| `gated_quant_fp8` | `ref_gated_quant_fp8` | libref | host | `n=17408 group=128 dtype=bf16 act=silu M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gated_quant_fp8` | `avx_gated_quant_fp8` | libavx | host | `n=17408 group=128 dtype=bf16 act=silu M=8` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `gated_quant_fp8` | `gated_quant_fp8` | libr4d | device | `n=17408 group=128 dtype=bf16 act=silu M=8` | - | 1 | ok | 4.41e-06 | 6e-03 |
+| `gated_quant_fp8` | `ref_gated_quant_fp8` | libref | host | `n=17408 group=128 dtype=bf16 act=silu M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gated_quant_fp8` | `avx_gated_quant_fp8` | libavx | host | `n=17408 group=128 dtype=bf16 act=silu M=16` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `gated_quant_fp8` | `gated_quant_fp8` | libr4d | device | `n=17408 group=128 dtype=bf16 act=silu M=16` | - | 1 | ok | 1.57e-05 | 6e-03 |
+| `gated_quant_fp8` | `ref_gated_quant_fp8` | libref | host | `n=17408 group=128 dtype=bf16 act=silu M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gated_quant_fp8` | `avx_gated_quant_fp8` | libavx | host | `n=17408 group=128 dtype=bf16 act=silu M=32` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `gated_quant_fp8` | `gated_quant_fp8` | libr4d | device | `n=17408 group=128 dtype=bf16 act=silu M=32` | - | 1 | ok | 5.48e-07 | 6e-03 |
+| `gated_quant_fp8` | `ref_gated_quant_fp8` | libref | host | `n=17408 group=128 dtype=bf16 act=silu M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gated_quant_fp8` | `avx_gated_quant_fp8` | libavx | host | `n=17408 group=128 dtype=bf16 act=silu M=64` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `gated_quant_fp8` | `gated_quant_fp8` | libr4d | device | `n=17408 group=128 dtype=bf16 act=silu M=64` | - | 1 | ok | 2.19e-05 | 6e-03 |
+| `gated_quant_fp8` | `ref_gated_quant_fp8` | libref | host | `n=17408 group=128 dtype=bf16 act=silu M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gated_quant_fp8` | `avx_gated_quant_fp8` | libavx | host | `n=17408 group=128 dtype=bf16 act=silu M=128` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `gated_quant_fp8` | `gated_quant_fp8` | libr4d | device | `n=17408 group=128 dtype=bf16 act=silu M=128` | - | 1 | ok | 5.48e-06 | 6e-03 |
+| `gated_quant_fp8` | `ref_gated_quant_fp8` | libref | host | `n=17408 group=128 dtype=bf16 act=silu M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gated_quant_fp8` | `avx_gated_quant_fp8` | libavx | host | `n=17408 group=128 dtype=bf16 act=silu M=256` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `gated_quant_fp8` | `gated_quant_fp8` | libr4d | device | `n=17408 group=128 dtype=bf16 act=silu M=256` | - | 1 | ok | 4.41e-05 | 6e-03 |
+| `gated_quant_fp8` | `ref_gated_quant_fp8` | libref | host | `n=17408 group=128 dtype=bf16 act=silu M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gated_quant_fp8` | `avx_gated_quant_fp8` | libavx | host | `n=17408 group=128 dtype=bf16 act=silu M=512` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `gated_quant_fp8` | `gated_quant_fp8` | libr4d | device | `n=17408 group=128 dtype=bf16 act=silu M=512` | - | 1 | ok | 6.40e-05 | 6e-03 |
+| `gated_quant_fp8` | `ref_gated_quant_fp8` | libref | host | `n=17408 group=128 dtype=bf16 act=silu M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q_gated` | `avx_gemm_nt_q_gated` | libavx | host | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=1` | - | 1 | ok | 1.07e-05 | 3e-02 |
+| `gemm_nt_q_gated` | `gemm_fp8a8_gated_nt_m16` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=1` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q_gated` | `ref_gemm_nt_q_gated` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q_gated` | `avx_gemm_nt_q_gated` | libavx | host | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=2` | - | 1 | ok | 9.06e-06 | 3e-02 |
+| `gemm_nt_q_gated` | `gemm_fp8a8_gated_nt_m16` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=2` | - | 1 | ok | 9.06e-06 | 3e-02 |
+| `gemm_nt_q_gated` | `ref_gemm_nt_q_gated` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q_gated` | `avx_gemm_nt_q_gated` | libavx | host | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=4` | - | 1 | ok | 4.32e-05 | 3e-02 |
+| `gemm_nt_q_gated` | `gemm_fp8a8_gated_nt_m16` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=4` | - | 1 | ok | 4.33e-05 | 3e-02 |
+| `gemm_nt_q_gated` | `ref_gemm_nt_q_gated` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q_gated` | `avx_gemm_nt_q_gated` | libavx | host | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=8` | - | 1 | ok | 4.47e-06 | 3e-02 |
+| `gemm_nt_q_gated` | `gemm_fp8a8_gated_nt_m16` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=8` | - | 1 | ok | 9.43e-06 | 3e-02 |
+| `gemm_nt_q_gated` | `ref_gemm_nt_q_gated` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q_gated` | `avx_gemm_nt_q_gated` | libavx | host | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=16` | - | 1 | ok | 8.53e-05 | 3e-02 |
+| `gemm_nt_q_gated` | `gemm_fp8a8_gated_nt_m16` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=16` | - | 1 | ok | 9.05e-05 | 3e-02 |
+| `gemm_nt_q_gated` | `ref_gemm_nt_q_gated` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q_gated` | `avx_gemm_nt_q_gated` | libavx | host | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=32` | - | 1 | ok | 3.10e-05 | 3e-02 |
+| `gemm_nt_q_gated` | `gemm_fp8a8_gated_nt_m16` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=32` | - | 1 | ok | 2.70e-05 | 3e-02 |
+| `gemm_nt_q_gated` | `ref_gemm_nt_q_gated` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q_gated` | `avx_gemm_nt_q_gated` | libavx | host | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=64` | - | 1 | ok | 1.68e-05 | 3e-02 |
+| `gemm_nt_q_gated` | `gemm_fp8a8_gated_nt_m16` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=64` | - | 1 | ok | 2.16e-05 | 3e-02 |
+| `gemm_nt_q_gated` | `ref_gemm_nt_q_gated` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 5.20e-06 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 5.21e-06 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 4.54e-07 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 6.42e-07 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 2.11e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 2.47e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 8.85e-07 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 8.85e-07 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 1.44e-06 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 2.91e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 8.01e-06 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 4.67e-06 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 1.57e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 2.64e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 3.16e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 3.33e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 2.15e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 1.37e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=128` | - | 1 | ok | 2.10e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=128` | - | 1 | ok | 2.13e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=129` | - | 1 | ok | 2.17e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=129` | - | 1 | ok | 2.66e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=129` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=258` | - | 1 | ok | 2.48e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=258` | - | 1 | ok | 2.45e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=258` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 2.29e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 1.65e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 4.97e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 0.00e+00 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 3.24e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 2.08e-06 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 2.43e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 2.17e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 2.54e-07 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 4.97e-07 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 1.73e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 2.59e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 2.30e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 2.05e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 2.20e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 2.29e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 2.63e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 1.77e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 2.23e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=128` | - | 1 | ok | 3.13e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=128` | - | 1 | ok | 2.09e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=129` | - | 1 | ok | 1.43e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=129` | - | 1 | ok | 1.69e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=129` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=258` | - | 1 | ok | 1.59e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=258` | - | 1 | ok | 1.76e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=258` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 1.56e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 1.87e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 0.00e+00 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 2.84e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 0.00e+00 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 0.00e+00 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 0.00e+00 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 0.00e+00 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 5.48e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 1.70e-06 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 8.06e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 2.01e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 1.43e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 1.39e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 4.14e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 4.14e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 2.03e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 1.91e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=128` | - | 1 | ok | 3.68e-06 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=128` | - | 1 | ok | 3.56e-06 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=129` | - | 1 | ok | 3.61e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=129` | - | 1 | ok | 5.77e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=129` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=258` | - | 1 | ok | 1.05e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=258` | - | 1 | ok | 9.33e-06 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=258` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 2.50e-05 | 5e-03 |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 2.03e-05 | 5e-03 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 4e-03 |
 | `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 4e-03 |
 | `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 4e-03 |
 | `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 4e-03 |
 | `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 4e-03 |
 | `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 4e-03 |
 | `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 4e-03 |
 | `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=128` | - | 1 | ok | 1.20e-07 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=256` | - | 1 | ok | 5.69e-08 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=512` | - | 1 | ok | 2.35e-07 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=32` | - | 1 | ok | 2.29e-13 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=64` | - | 1 | ok | 8.50e-12 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=128` | - | 1 | ok | 7.48e-09 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=128` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=256` | - | 1 | ok | 9.03e-09 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=256` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=512` | - | 1 | ok | 4.07e-10 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=512` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=128` | - | 1 | ok | 7.06e-11 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=128` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=256` | - | 1 | ok | 1.79e-10 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=256` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=512` | - | 1 | ok | 6.95e-09 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=512` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=1 splits=0` | - | 3 | ok | 2.29e-03 | 3e-02 |
-| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=1 splits=0` | - | 3 | ok | 0.00e+00 | 3e-02 |
-| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=2 splits=0` | - | 3 | ok | 2.16e-03 | 3e-02 |
-| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=2 splits=0` | - | 3 | ok | 0.00e+00 | 3e-02 |
-| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=4 splits=0` | - | 3 | ok | 1.83e-03 | 3e-02 |
-| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=4 splits=0` | - | 3 | ok | 0.00e+00 | 3e-02 |
-| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=5 splits=0` | - | 3 | ok | 2.17e-03 | 3e-02 |
-| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=5 splits=0` | - | 3 | ok | 0.00e+00 | 3e-02 |
-| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=6 splits=0` | - | 3 | ok | 2.09e-03 | 3e-02 |
-| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=6 splits=0` | - | 3 | ok | 0.00e+00 | 3e-02 |
-| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=8 splits=0` | - | 3 | ok | 2.07e-03 | 3e-02 |
-| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=8 splits=0` | - | 3 | ok | 0.00e+00 | 3e-02 |
-| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=9 splits=0` | - | 3 | ok | 2.31e-03 | 3e-02 |
-| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=9 splits=0` | - | 3 | ok | 0.00e+00 | 3e-02 |
-| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=10 splits=0` | - | 3 | ok | 1.96e-03 | 3e-02 |
-| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=10 splits=0` | - | 3 | ok | 0.00e+00 | 3e-02 |
-| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=11` | - | 3 | ok | 1.62e-03 | 3e-02 |
-| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=11` | - | 3 | ok | 0.00e+00 | 3e-02 |
-| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=16` | - | 3 | ok | 1.59e-03 | 3e-02 |
-| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=16` | - | 3 | ok | 0.00e+00 | 3e-02 |
-| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=17` | - | 3 | ok | 1.59e-03 | 3e-02 |
-| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=17` | - | 3 | ok | 0.00e+00 | 3e-02 |
-| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=34` | - | 3 | ok | 1.70e-03 | 3e-02 |
-| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=34` | - | 3 | ok | 0.00e+00 | 3e-02 |
-| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=68` | - | 3 | ok | 1.36e-03 | 3e-02 |
-| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=68` | - | 3 | ok | 0.00e+00 | 3e-02 |
-| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=136` | - | 3 | ok | 1.72e-03 | 3e-02 |
-| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=136` | - | 3 | ok | 0.00e+00 | 3e-02 |
-| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=272` | - | 3 | ok | 1.92e-03 | 3e-02 |
-| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=272` | - | 3 | ok | 0.00e+00 | 3e-02 |
-| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=512` | - | 3 | ok | 1.71e-03 | 3e-02 |
-| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=512` | - | 3 | ok | 0.00e+00 | 3e-02 |
-| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `ref_kv_store` | libref | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `ref_kv_store` | libref | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `ref_kv_store` | libref | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `ref_kv_store` | libref | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `ref_kv_store` | libref | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `ref_kv_store` | libref | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `ref_kv_store` | libref | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `ref_kv_store` | libref | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `ref_kv_store` | libref | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `ref_kv_store` | libref | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 2e-02 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 4e-03 |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=256` | - | 1 | ok | 1.47e-06 | 4e-03 |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=256` | - | 1 | ok | 1.47e-06 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=512` | - | 1 | ok | 1.01e-05 | 4e-03 |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=512` | - | 1 | ok | 1.01e-05 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=1` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=1` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=2` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=2` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=4` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=4` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=8` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=8` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=16` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=16` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=32` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=32` | - | 1 | ok | 2.20e-06 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=64` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=64` | - | 1 | ok | 7.75e-09 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=128` | - | 1 | ok | 1.34e-10 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=128` | - | 1 | ok | 7.27e-06 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=256` | - | 1 | ok | 1.92e-08 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=256` | - | 1 | ok | 1.13e-05 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=512` | - | 1 | ok | 1.10e-06 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=512` | - | 1 | ok | 1.43e-05 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=1` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=1` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=2` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=2` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=4` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=4` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=8` | - | 1 | ok | 8.52e-08 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=8` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=16` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=16` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=32` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=32` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=64` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=64` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=128` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=128` | - | 1 | ok | 6.74e-07 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=256` | - | 1 | ok | 4.66e-10 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=256` | - | 1 | ok | 9.89e-07 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=512` | - | 1 | ok | 2.63e-09 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=512` | - | 1 | ok | 2.39e-05 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=1 splits=0` | - | 1 | ok | 0.00e+00 | 2e-02 |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=1 splits=0` | - | 1 | ok | 0.00e+00 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=1 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=1 splits=0` | - | 1 | ok | 1.19e-06 | 2e-02 |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=1 splits=0` | - | 1 | ok | 1.77e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=1 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=1 splits=0` | - | 1 | ok | 8.52e-05 | 2e-02 |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=1 splits=0` | - | 1 | ok | 2.20e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=1 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=2 splits=0` | - | 1 | ok | 0.00e+00 | 2e-02 |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=2 splits=0` | - | 1 | ok | 8.24e-04 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=2 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=2 splits=0` | - | 1 | ok | 4.01e-05 | 2e-02 |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=2 splits=0` | - | 1 | ok | 2.02e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=2 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=2 splits=0` | - | 1 | ok | 1.49e-04 | 2e-02 |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=2 splits=0` | - | 1 | ok | 1.90e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=2 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=4 splits=0` | - | 1 | ok | 7.64e-09 | 2e-02 |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=4 splits=0` | - | 1 | ok | 1.35e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=4 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=4 splits=0` | - | 1 | ok | 1.10e-04 | 2e-02 |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=4 splits=0` | - | 1 | ok | 2.32e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=4 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=4 splits=0` | - | 1 | ok | 1.24e-04 | 2e-02 |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=4 splits=0` | - | 1 | ok | 2.06e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=4 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=5 splits=0` | - | 1 | ok | 0.00e+00 | 2e-02 |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=5 splits=0` | - | 1 | ok | 1.16e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=5 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=5 splits=0` | - | 1 | ok | 3.09e-05 | 2e-02 |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=5 splits=0` | - | 1 | ok | 2.11e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=5 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=5 splits=0` | - | 1 | ok | 1.11e-04 | 2e-02 |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=5 splits=0` | - | 1 | ok | 2.34e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=5 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=6 splits=0` | - | 1 | ok | 1.81e-06 | 2e-02 |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=6 splits=0` | - | 1 | ok | 1.39e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=6 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=6 splits=0` | - | 1 | ok | 4.79e-05 | 2e-02 |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=6 splits=0` | - | 1 | ok | 2.10e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=6 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=6 splits=0` | - | 1 | ok | 8.98e-05 | 2e-02 |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=6 splits=0` | - | 1 | ok | 2.23e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=6 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=8 splits=0` | - | 1 | ok | 1.27e-08 | 2e-02 |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=8 splits=0` | - | 1 | ok | 1.64e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=8 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=8 splits=0` | - | 1 | ok | 6.44e-05 | 2e-02 |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=8 splits=0` | - | 1 | ok | 2.26e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=8 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=8 splits=0` | - | 1 | ok | 1.08e-04 | 2e-02 |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=8 splits=0` | - | 1 | ok | 2.14e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=8 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=9 splits=0` | - | 1 | ok | 5.00e-08 | 2e-02 |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=9 splits=0` | - | 1 | ok | 1.34e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=9 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=9 splits=0` | - | 1 | ok | 3.07e-05 | 2e-02 |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=9 splits=0` | - | 1 | ok | 2.24e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=9 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=9 splits=0` | - | 1 | ok | 6.26e-05 | 2e-02 |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=9 splits=0` | - | 1 | ok | 2.15e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=9 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=10 splits=0` | - | 1 | ok | 4.85e-05 | 2e-02 |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=10 splits=0` | - | 1 | ok | 1.72e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=10 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=10 splits=0` | - | 1 | ok | 6.80e-05 | 2e-02 |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=10 splits=0` | - | 1 | ok | 1.88e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=10 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=10 splits=0` | - | 1 | ok | 5.76e-05 | 2e-02 |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=10 splits=0` | - | 1 | ok | 2.12e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=10 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=11` | - | 1 | ok | 3.71e-10 | 2e-02 |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=11` | - | 1 | ok | 7.52e-04 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=11` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=11` | - | 1 | ok | 3.19e-05 | 2e-02 |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=11` | - | 1 | ok | 1.64e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=11` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=11` | - | 1 | ok | 5.29e-05 | 2e-02 |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=11` | - | 1 | ok | 1.64e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=11` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=16` | - | 1 | ok | 3.49e-07 | 2e-02 |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=16` | - | 1 | ok | 8.67e-04 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=16` | - | 1 | ok | 3.93e-05 | 2e-02 |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=16` | - | 1 | ok | 1.55e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=16` | - | 1 | ok | 1.08e-04 | 2e-02 |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=16` | - | 1 | ok | 1.79e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=17` | - | 1 | ok | 1.15e-05 | 2e-02 |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=17` | - | 1 | ok | 1.04e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=17` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=17` | - | 1 | ok | 3.81e-05 | 2e-02 |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=17` | - | 1 | ok | 1.80e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=17` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=17` | - | 1 | ok | 6.23e-05 | 2e-02 |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=17` | - | 1 | ok | 1.74e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=17` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=32` | - | 1 | ok | 3.43e-06 | 2e-02 |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=32` | - | 1 | ok | 1.00e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=32` | - | 1 | ok | 5.74e-05 | 2e-02 |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=32` | - | 1 | ok | 2.03e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=32` | - | 1 | ok | 1.04e-04 | 2e-02 |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=32` | - | 1 | ok | 1.60e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=33` | - | 1 | ok | 2.49e-05 | 2e-02 |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=33` | - | 1 | ok | 9.41e-04 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=33` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=33` | - | 1 | ok | 3.76e-05 | 2e-02 |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=33` | - | 1 | ok | 1.79e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=33` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=33` | - | 1 | ok | 6.82e-05 | 2e-02 |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=33` | - | 1 | ok | 1.82e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=33` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=66` | - | 1 | ok | 1.31e-05 | 2e-02 |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=66` | - | 1 | ok | 1.22e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=66` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=66` | - | 1 | ok | 5.68e-05 | 2e-02 |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=66` | - | 1 | ok | 1.79e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=66` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=66` | - | 1 | ok | 8.06e-05 | 2e-02 |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=66` | - | 1 | ok | 1.47e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=66` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=132` | - | 1 | ok | 2.16e-05 | 2e-02 |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=132` | - | 1 | ok | 9.77e-04 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=132` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=132` | - | 1 | ok | 4.56e-05 | 2e-02 |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=132` | - | 1 | ok | 1.61e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=132` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=132` | - | 1 | ok | 8.58e-05 | 2e-02 |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=132` | - | 1 | ok | 1.66e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=132` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=264` | - | 1 | ok | 2.02e-05 | 2e-02 |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=264` | - | 1 | ok | 1.68e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=264` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=264` | - | 1 | ok | 3.92e-05 | 2e-02 |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=264` | - | 1 | ok | 1.60e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=264` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=264` | - | 1 | ok | 9.41e-05 | 2e-02 |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=264` | - | 1 | ok | 1.82e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=264` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=512` | - | 1 | ok | 1.66e-05 | 2e-02 |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=512` | - | 1 | ok | 1.31e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=512` | - | 1 | ok | 3.90e-05 | 2e-02 |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=512` | - | 1 | ok | 1.59e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=512` | - | 1 | ok | 8.37e-05 | 2e-02 |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=512` | - | 1 | ok | 1.69e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `avx_kv_store` | libavx | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `kv_store_fp8` | libr4d | device | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `ref_kv_store` | libref | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `avx_kv_store` | libavx | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `kv_store_fp8` | libr4d | device | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `ref_kv_store` | libref | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `avx_kv_store` | libavx | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `kv_store_fp8` | libr4d | device | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `ref_kv_store` | libref | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `avx_kv_store` | libavx | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `kv_store_fp8` | libr4d | device | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `ref_kv_store` | libref | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `avx_kv_store` | libavx | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `kv_store_fp8` | libr4d | device | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `ref_kv_store` | libref | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `avx_kv_store` | libavx | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `kv_store_fp8` | libr4d | device | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `ref_kv_store` | libref | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `avx_kv_store` | libavx | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `kv_store_fp8` | libr4d | device | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `ref_kv_store` | libref | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `avx_kv_store` | libavx | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `kv_store_fp8` | libr4d | device | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `ref_kv_store` | libref | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `avx_kv_store` | libavx | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `kv_store_fp8` | libr4d | device | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `ref_kv_store` | libref | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `avx_kv_store` | libavx | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `kv_store_fp8` | libr4d | device | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `ref_kv_store` | libref | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `add` | `avx_add` | libavx | host | `n=5120 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 6e-03 |
 | `add` | `add_bf16` | libr4d | device | `n=5120 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `add` | `ref_add` | libref | host | `n=5120 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `add` | `ref_add` | libref | host | `n=5120 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `add` | `avx_add` | libavx | host | `n=5120 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 6e-03 |
 | `add` | `add_bf16` | libr4d | device | `n=5120 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `add` | `ref_add` | libref | host | `n=5120 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `add` | `ref_add` | libref | host | `n=5120 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `add` | `avx_add` | libavx | host | `n=5120 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 6e-03 |
 | `add` | `add_bf16` | libr4d | device | `n=5120 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `add` | `ref_add` | libref | host | `n=5120 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `add` | `ref_add` | libref | host | `n=5120 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `add` | `avx_add` | libavx | host | `n=5120 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 6e-03 |
 | `add` | `add_bf16` | libr4d | device | `n=5120 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `add` | `ref_add` | libref | host | `n=5120 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `add` | `ref_add` | libref | host | `n=5120 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `add` | `avx_add` | libavx | host | `n=5120 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 6e-03 |
 | `add` | `add_bf16` | libr4d | device | `n=5120 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `add` | `ref_add` | libref | host | `n=5120 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `add` | `ref_add` | libref | host | `n=5120 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `add` | `avx_add` | libavx | host | `n=5120 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 6e-03 |
 | `add` | `add_bf16` | libr4d | device | `n=5120 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `add` | `ref_add` | libref | host | `n=5120 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `add` | `ref_add` | libref | host | `n=5120 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `add` | `avx_add` | libavx | host | `n=5120 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 6e-03 |
 | `add` | `add_bf16` | libr4d | device | `n=5120 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `add` | `ref_add` | libref | host | `n=5120 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `add` | `ref_add` | libref | host | `n=5120 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `add` | `avx_add` | libavx | host | `n=5120 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 6e-03 |
 | `add` | `add_bf16` | libr4d | device | `n=5120 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `add` | `ref_add` | libref | host | `n=5120 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `add` | `ref_add` | libref | host | `n=5120 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `add` | `avx_add` | libavx | host | `n=5120 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 6e-03 |
 | `add` | `add_bf16` | libr4d | device | `n=5120 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `add` | `ref_add` | libref | host | `n=5120 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `add` | `ref_add` | libref | host | `n=5120 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `add` | `avx_add` | libavx | host | `n=5120 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 6e-03 |
 | `add` | `add_bf16` | libr4d | device | `n=5120 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `add` | `ref_add` | libref | host | `n=5120 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=2` | - | 1 | ok | 4.90e-04 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=4` | - | 1 | ok | 6.58e-07 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=8` | - | 1 | ok | 1.43e-06 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=16` | - | 1 | ok | 2.14e-06 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=32` | - | 1 | ok | 7.14e-05 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=64` | - | 1 | ok | 2.30e-06 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=128` | - | 1 | ok | 2.38e-04 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=256` | - | 1 | ok | 2.78e-04 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=512` | - | 1 | ok | 2.32e-06 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `gather_rows` | `gather_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `gather_rows` | `ref_gather_rows` | libref | host | `n=5120 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `gather_rows` | `gather_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `gather_rows` | `ref_gather_rows` | libref | host | `n=5120 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `gather_rows` | `gather_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `gather_rows` | `ref_gather_rows` | libref | host | `n=5120 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `gather_rows` | `gather_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `gather_rows` | `ref_gather_rows` | libref | host | `n=5120 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `gather_rows` | `gather_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `gather_rows` | `ref_gather_rows` | libref | host | `n=5120 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `gather_rows` | `gather_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `gather_rows` | `ref_gather_rows` | libref | host | `n=5120 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `gather_rows` | `gather_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `gather_rows` | `ref_gather_rows` | libref | host | `n=5120 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `logits_gemm` | `logits_gemm_fp8` | libr4d | device | `n_vocab=248320 n_embd=5120 dtype=bf16 M=1` | - | 1 | ok | 1.62e-03 | 8e-03 |
-| `logits_gemm` | `logits_gemm_fp8` | libr4d | device | `n_vocab=248320 n_embd=5120 dtype=bf16 M=2` | - | 1 | ok | 1.56e-03 | 8e-03 |
-| `logits_gemm` | `logits_gemm_fp8` | libr4d | device | `n_vocab=248320 n_embd=5120 dtype=bf16 M=4` | - | 1 | ok | 1.59e-03 | 8e-03 |
-| `logits_gemm` | `logits_gemm_fp8` | libr4d | device | `n_vocab=248320 n_embd=5120 dtype=bf16 M=8` | - | 1 | ok | 1.63e-03 | 8e-03 |
-| `logits_gemm` | `logits_gemm_fp8` | libr4d | device | `n_vocab=248320 n_embd=5120 dtype=bf16 M=16` | - | 1 | ok | 1.53e-03 | 8e-03 |
-| `logits_gemm` | `logits_gemm_fp8` | libr4d | device | `n_vocab=248320 n_embd=5120 dtype=bf16 M=32` | - | 1 | ok | 1.60e-03 | 8e-03 |
-| `logits_gemm` | `logits_gemm_fp8` | libr4d | device | `n_vocab=248320 n_embd=5120 dtype=bf16 M=64` | - | 1 | ok | 1.64e-03 | 8e-03 |
-| `attn_paged` | `attn_decode_h128_gqa4_bf16kv` | libr4d | device | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=1 splits=0` | - | 3 | ok | 2.24e-03 | 3e-02 |
-| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=1 splits=0` | - | 3 | ok | 0.00e+00 | 3e-02 |
-| `attn_paged` | `attn_decode_h128_gqa4_bf16kv` | libr4d | device | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=2 splits=0` | - | 3 | ok | 1.94e-03 | 3e-02 |
-| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=2 splits=0` | - | 3 | ok | 0.00e+00 | 3e-02 |
-| `attn_paged` | `attn_decode_h128_gqa4_bf16kv` | libr4d | device | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=4 splits=0` | - | 3 | ok | 2.13e-03 | 3e-02 |
-| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=4 splits=0` | - | 3 | ok | 0.00e+00 | 3e-02 |
-| `attn_paged` | `attn_decode_h128_gqa4_bf16kv` | libr4d | device | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=5 splits=0` | - | 3 | ok | 2.16e-03 | 3e-02 |
-| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=5 splits=0` | - | 3 | ok | 0.00e+00 | 3e-02 |
-| `attn_paged` | `attn_decode_h128_gqa4_bf16kv` | libr4d | device | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=6 splits=0` | - | 3 | ok | 2.25e-03 | 3e-02 |
-| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=6 splits=0` | - | 3 | ok | 0.00e+00 | 3e-02 |
-| `attn_paged` | `attn_decode_h128_gqa4_bf16kv` | libr4d | device | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=8 splits=0` | - | 3 | ok | 2.09e-03 | 3e-02 |
-| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=8 splits=0` | - | 3 | ok | 0.00e+00 | 3e-02 |
+| `add` | `ref_add` | libref | host | `n=5120 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=1` | - | 1 | ok | 7.63e-05 | 4e-03 |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=1` | - | 1 | ok | 7.63e-05 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=2` | - | 1 | ok | 6.73e-05 | 4e-03 |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=2` | - | 1 | ok | 6.96e-05 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=4` | - | 1 | ok | 9.17e-05 | 4e-03 |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=4` | - | 1 | ok | 9.17e-05 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=8` | - | 1 | ok | 7.38e-05 | 4e-03 |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=8` | - | 1 | ok | 7.38e-05 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=16` | - | 1 | ok | 1.60e-04 | 4e-03 |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=16` | - | 1 | ok | 1.60e-04 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=32` | - | 1 | ok | 1.21e-04 | 4e-03 |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=32` | - | 1 | ok | 1.22e-04 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=64` | - | 1 | ok | 1.04e-04 | 4e-03 |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=64` | - | 1 | ok | 1.12e-04 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=128` | - | 1 | ok | 1.02e-04 | 4e-03 |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=128` | - | 1 | ok | 1.03e-04 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=256` | - | 1 | ok | 1.22e-04 | 4e-03 |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=256` | - | 1 | ok | 1.19e-04 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=512` | - | 1 | ok | 9.96e-05 | 4e-03 |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=512` | - | 1 | ok | 1.04e-04 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gather_rows` | `avx_gather_rows` | libavx | host | `n=5120 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gather_rows` | `gather_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gather_rows` | `ref_gather_rows` | libref | host | `n=5120 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gather_rows` | `avx_gather_rows` | libavx | host | `n=5120 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gather_rows` | `gather_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gather_rows` | `ref_gather_rows` | libref | host | `n=5120 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gather_rows` | `avx_gather_rows` | libavx | host | `n=5120 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gather_rows` | `gather_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gather_rows` | `ref_gather_rows` | libref | host | `n=5120 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gather_rows` | `avx_gather_rows` | libavx | host | `n=5120 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gather_rows` | `gather_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gather_rows` | `ref_gather_rows` | libref | host | `n=5120 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gather_rows` | `avx_gather_rows` | libavx | host | `n=5120 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gather_rows` | `gather_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gather_rows` | `ref_gather_rows` | libref | host | `n=5120 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gather_rows` | `avx_gather_rows` | libavx | host | `n=5120 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gather_rows` | `gather_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gather_rows` | `ref_gather_rows` | libref | host | `n=5120 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gather_rows` | `avx_gather_rows` | libavx | host | `n=5120 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gather_rows` | `gather_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gather_rows` | `ref_gather_rows` | libref | host | `n=5120 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `logits_gemm` | `avx_logits_gemm` | libavx | host | `n_vocab=248320 n_embd=5120 dtype=bf16 M=1` | - | 1 | ok | 8.22e-07 | 8e-03 |
+| `logits_gemm` | `logits_gemm_fp8` | libr4d | device | `n_vocab=248320 n_embd=5120 dtype=bf16 M=1` | - | 1 | ok | 1.58e-03 | 8e-03 |
+| `logits_gemm` | `ref_logits_gemm` | libref | host | `n_vocab=248320 n_embd=5120 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `logits_gemm` | `avx_logits_gemm` | libavx | host | `n_vocab=248320 n_embd=5120 dtype=bf16 M=2` | - | 1 | ok | 7.62e-07 | 8e-03 |
+| `logits_gemm` | `logits_gemm_fp8` | libr4d | device | `n_vocab=248320 n_embd=5120 dtype=bf16 M=2` | - | 1 | ok | 1.61e-03 | 8e-03 |
+| `logits_gemm` | `ref_logits_gemm` | libref | host | `n_vocab=248320 n_embd=5120 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `logits_gemm` | `avx_logits_gemm` | libavx | host | `n_vocab=248320 n_embd=5120 dtype=bf16 M=4` | - | 1 | ok | 7.71e-07 | 8e-03 |
+| `logits_gemm` | `logits_gemm_fp8` | libr4d | device | `n_vocab=248320 n_embd=5120 dtype=bf16 M=4` | - | 1 | ok | 1.55e-03 | 8e-03 |
+| `logits_gemm` | `ref_logits_gemm` | libref | host | `n_vocab=248320 n_embd=5120 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `logits_gemm` | `avx_logits_gemm` | libavx | host | `n_vocab=248320 n_embd=5120 dtype=bf16 M=8` | - | 1 | ok | 7.54e-07 | 8e-03 |
+| `logits_gemm` | `logits_gemm_fp8` | libr4d | device | `n_vocab=248320 n_embd=5120 dtype=bf16 M=8` | - | 1 | ok | 1.62e-03 | 8e-03 |
+| `logits_gemm` | `ref_logits_gemm` | libref | host | `n_vocab=248320 n_embd=5120 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `logits_gemm` | `avx_logits_gemm` | libavx | host | `n_vocab=248320 n_embd=5120 dtype=bf16 M=16` | - | 1 | ok | 7.35e-07 | 8e-03 |
+| `logits_gemm` | `logits_gemm_fp8` | libr4d | device | `n_vocab=248320 n_embd=5120 dtype=bf16 M=16` | - | 1 | ok | 1.82e-03 | 8e-03 |
+| `logits_gemm` | `ref_logits_gemm` | libref | host | `n_vocab=248320 n_embd=5120 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `logits_gemm` | `avx_logits_gemm` | libavx | host | `n_vocab=248320 n_embd=5120 dtype=bf16 M=32` | - | 1 | ok | 9.10e-07 | 8e-03 |
+| `logits_gemm` | `logits_gemm_fp8` | libr4d | device | `n_vocab=248320 n_embd=5120 dtype=bf16 M=32` | - | 1 | ok | 1.63e-03 | 8e-03 |
+| `logits_gemm` | `ref_logits_gemm` | libref | host | `n_vocab=248320 n_embd=5120 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `logits_gemm` | `avx_logits_gemm` | libavx | host | `n_vocab=248320 n_embd=5120 dtype=bf16 M=64` | - | 1 | ok | 8.28e-07 | 8e-03 |
+| `logits_gemm` | `logits_gemm_fp8` | libr4d | device | `n_vocab=248320 n_embd=5120 dtype=bf16 M=64` | - | 1 | ok | 1.63e-03 | 8e-03 |
+| `logits_gemm` | `ref_logits_gemm` | libref | host | `n_vocab=248320 n_embd=5120 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=1 splits=0` | - | 1 | ok | 0.00e+00 | 2e-02 |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | device | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=1 splits=0` | - | 1 | ok | 0.00e+00 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=1 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=1 splits=0` | - | 1 | ok | 1.85e-08 | 2e-02 |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | device | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=1 splits=0` | - | 1 | ok | 2.16e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=1 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=1 splits=0` | - | 1 | ok | 9.31e-05 | 2e-02 |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | device | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=1 splits=0` | - | 1 | ok | 2.02e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=1 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=2 splits=0` | - | 1 | ok | 0.00e+00 | 2e-02 |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | device | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=2 splits=0` | - | 1 | ok | 1.76e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=2 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=2 splits=0` | - | 1 | ok | 6.59e-05 | 2e-02 |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | device | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=2 splits=0` | - | 1 | ok | 2.34e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=2 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=2 splits=0` | - | 1 | ok | 2.17e-06 | 2e-02 |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | device | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=2 splits=0` | - | 1 | ok | 2.15e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=2 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=4 splits=0` | - | 1 | ok | 6.32e-11 | 2e-02 |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | device | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=4 splits=0` | - | 1 | ok | 1.96e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=4 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=4 splits=0` | - | 1 | ok | 1.52e-04 | 2e-02 |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | device | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=4 splits=0` | - | 1 | ok | 2.33e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=4 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=4 splits=0` | - | 1 | ok | 9.77e-05 | 2e-02 |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | device | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=4 splits=0` | - | 1 | ok | 2.41e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=4 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=5 splits=0` | - | 1 | ok | 0.00e+00 | 2e-02 |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | device | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=5 splits=0` | - | 1 | ok | 1.52e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=5 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=5 splits=0` | - | 1 | ok | 1.87e-05 | 2e-02 |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | device | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=5 splits=0` | - | 1 | ok | 2.09e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=5 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=5 splits=0` | - | 1 | ok | 7.64e-05 | 2e-02 |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | device | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=5 splits=0` | - | 1 | ok | 2.47e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=5 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=6 splits=0` | - | 1 | ok | 0.00e+00 | 2e-02 |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | device | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=6 splits=0` | - | 1 | ok | 1.92e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=6 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=6 splits=0` | - | 1 | ok | 3.30e-05 | 2e-02 |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | device | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=6 splits=0` | - | 1 | ok | 2.13e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=6 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=6 splits=0` | - | 1 | ok | 5.15e-05 | 2e-02 |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | device | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=6 splits=0` | - | 1 | ok | 2.21e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=6 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=8 splits=0` | - | 1 | ok | 2.17e-05 | 2e-02 |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | device | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=8 splits=0` | - | 1 | ok | 1.53e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=8 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=8 splits=0` | - | 1 | ok | 5.19e-05 | 2e-02 |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | device | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=8 splits=0` | - | 1 | ok | 2.01e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=8 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_paged` | `avx_attn_paged` | libavx | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=8 splits=0` | - | 1 | ok | 1.03e-04 | 2e-02 |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | device | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=8 splits=0` | - | 1 | ok | 2.24e-03 | 2e-02 |
+| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=8 splits=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=25600 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
 | `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=25600 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=25600 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=25600 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=25600 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
 | `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=25600 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=25600 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=25600 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=25600 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
 | `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=25600 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=25600 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=25600 group=128 dtype=bf16 M=8` | - | 1 | ok | 1.39e-15 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=25600 group=128 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=25600 group=128 dtype=bf16 M=16` | - | 1 | ok | 2.12e-15 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=25600 group=128 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=25600 group=128 dtype=bf16 M=32` | - | 1 | ok | 2.19e-15 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=25600 group=128 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=25600 group=128 dtype=bf16 M=64` | - | 1 | ok | 7.04e-16 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=25600 group=128 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=25600 group=128 dtype=bf16 M=128` | - | 1 | ok | 1.79e-15 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=25600 group=128 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=25600 group=128 dtype=bf16 M=256` | - | 1 | ok | 1.13e-15 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=25600 group=128 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=25600 group=128 dtype=bf16 M=512` | - | 1 | ok | 1.20e-15 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=25600 group=128 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=25600 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 3.97e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=25600 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 3.11e-09 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=25600 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 1.23e-04 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=25600 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 6.38e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=25600 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 1.22e-11 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=25600 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 3.50e-09 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=25600 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 2.55e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=25600 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 9.19e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=25600 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 9.45e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=25600 group=128 dtype=fp8a8 M=130` | - | 1 | ok | 3.35e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=128 dtype=fp8a8 M=130` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=25600 group=128 dtype=fp8a8 M=260` | - | 1 | ok | 1.37e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=128 dtype=fp8a8 M=260` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=25600 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 1.84e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=2` | - | 1 | ok | 9.52e-05 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=4` | - | 1 | ok | 1.23e-06 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=8` | - | 1 | ok | 9.37e-07 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=16` | - | 1 | ok | 7.01e-05 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=32` | - | 1 | ok | 2.35e-06 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=64` | - | 1 | ok | 2.66e-06 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=128` | - | 1 | ok | 2.29e-06 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=256` | - | 1 | ok | 1.84e-04 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=512` | - | 1 | ok | 1.03e-04 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 4e-03 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=25600 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=25600 group=128 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=25600 group=128 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=25600 group=128 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=25600 group=128 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=25600 group=128 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=25600 group=128 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=25600 group=128 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=25600 group=128 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=25600 group=128 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=25600 group=128 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=25600 group=128 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=25600 group=128 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=25600 group=128 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=25600 group=128 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=25600 group=128 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=25600 group=128 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=25600 group=128 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=25600 group=128 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=25600 group=128 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=25600 group=128 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=25600 group=128 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=1 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=1 ks=0 bk=0 nt=0` | - | 1 | ok | 1.48e-04 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=1 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=2 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=2 ks=0 bk=0 nt=0` | - | 1 | ok | 5.67e-06 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=2 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=4 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=4 ks=0 bk=0 nt=0` | - | 1 | ok | 8.81e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=4 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=8 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=8 ks=0 bk=0 nt=0` | - | 1 | ok | 1.14e-04 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=8 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=9 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=9 ks=0 bk=0 nt=0` | - | 1 | ok | 6.58e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=9 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=18 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=18 ks=0 bk=0 nt=0` | - | 1 | ok | 7.46e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=18 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=36 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=36 ks=0 bk=0 nt=0` | - | 1 | ok | 3.84e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=36 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=64 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=64 ks=0 bk=0 nt=0` | - | 1 | ok | 4.86e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=64 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=65 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=65 ks=0 bk=0 nt=0` | - | 1 | ok | 4.45e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=65 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=128 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=128 ks=0 bk=0 nt=0` | - | 1 | ok | 1.60e-04 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=128 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=129 tn=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_tiled` | libr4d | device | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=129 tn=0` | - | 1 | ok | 5.22e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=129 tn=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=258 tn=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_tiled` | libr4d | device | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=258 tn=0` | - | 1 | ok | 6.80e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=258 tn=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=512 tn=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_tiled` | libr4d | device | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=512 tn=0` | - | 1 | ok | 5.18e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=512 tn=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=1` | - | 1 | ok | 1.35e-04 | 4e-03 |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=1` | - | 1 | ok | 1.35e-04 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=2` | - | 1 | ok | 5.50e-05 | 4e-03 |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=2` | - | 1 | ok | 6.69e-05 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=4` | - | 1 | ok | 2.40e-04 | 4e-03 |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=4` | - | 1 | ok | 2.40e-04 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=8` | - | 1 | ok | 1.17e-04 | 4e-03 |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=8` | - | 1 | ok | 1.17e-04 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=16` | - | 1 | ok | 1.23e-04 | 4e-03 |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=16` | - | 1 | ok | 1.23e-04 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=32` | - | 1 | ok | 8.15e-05 | 4e-03 |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=32` | - | 1 | ok | 8.04e-05 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=64` | - | 1 | ok | 7.83e-05 | 4e-03 |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=64` | - | 1 | ok | 7.83e-05 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=128` | - | 1 | ok | 1.38e-04 | 4e-03 |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=128` | - | 1 | ok | 1.46e-04 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=256` | - | 1 | ok | 9.85e-05 | 4e-03 |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=256` | - | 1 | ok | 9.86e-05 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=512` | - | 1 | ok | 1.06e-04 | 4e-03 |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=512` | - | 1 | ok | 1.06e-04 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=5120 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
 | `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=5120 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=5120 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=5120 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
 | `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=5120 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=5120 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=5120 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
 | `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=5120 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=8` | - | 1 | ok | 6.84e-15 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=5120 group=128 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=16` | - | 1 | ok | 3.60e-15 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=5120 group=128 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=5120 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=5120 group=128 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=5120 group=128 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=5120 group=128 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=5120 group=128 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=5120 group=128 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
 | `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=5120 group=128 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=5120 group=128 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=5120 group=128 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
 | `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=5120 group=128 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=128` | - | 1 | ok | 4.46e-16 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=5120 group=128 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=256` | - | 1 | ok | 1.10e-15 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=5120 group=128 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=512` | - | 1 | ok | 1.45e-15 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=5120 group=128 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=5120 group=128 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=5120 group=128 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=5120 group=128 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=5120 group=128 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=5120 group=128 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=5120 group=128 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=5120 group=128 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=1 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=1 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=1 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=2 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=2 ks=0 bk=0 nt=0` | - | 1 | ok | 1.54e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=2 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=4 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=4 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=4 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=8 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=8 ks=0 bk=0 nt=0` | - | 1 | ok | 9.64e-07 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=8 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=9 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=9 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=9 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=18 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=18 ks=0 bk=0 nt=0` | - | 1 | ok | 3.14e-07 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=18 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=36 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=36 ks=0 bk=0 nt=0` | - | 1 | ok | 1.57e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=36 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=64 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=64 ks=0 bk=0 nt=0` | - | 1 | ok | 2.48e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=64 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=65 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=65 ks=0 bk=0 nt=0` | - | 1 | ok | 9.62e-06 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=65 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=128 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=128 ks=0 bk=0 nt=0` | - | 1 | ok | 2.44e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=128 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=129 tn=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_tiled` | libr4d | device | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=129 tn=0` | - | 1 | ok | 3.30e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=129 tn=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=258 tn=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_tiled` | libr4d | device | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=258 tn=0` | - | 1 | ok | 6.33e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=258 tn=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=512 tn=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_tiled` | libr4d | device | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=512 tn=0` | - | 1 | ok | 2.20e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=512 tn=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 4e-03 |
 | `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 4e-03 |
 | `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 4e-03 |
 | `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 4e-03 |
 | `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 4e-03 |
 | `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 4e-03 |
 | `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 4e-03 |
 | `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=256` | - | 1 | ok | 9.96e-07 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 4e-03 |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=128` | - | 1 | ok | 3.89e-06 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=256` | - | 1 | ok | 5.47e-06 | 4e-03 |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 4e-03 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rmsnorm` | `avx_rmsnorm` | libavx | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 4e-03 |
 | `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 4e-03 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=32` | - | 1 | ok | 1.24e-12 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=64` | - | 1 | ok | 5.15e-08 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=128` | - | 1 | ok | 4.52e-09 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=128` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=256` | - | 1 | ok | 1.25e-07 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=256` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=512` | - | 1 | ok | 1.28e-07 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=512` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `ref_kv_store` | libref | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `ref_kv_store` | libref | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `ref_kv_store` | libref | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `ref_kv_store` | libref | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `ref_kv_store` | libref | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `ref_kv_store` | libref | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `ref_kv_store` | libref | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `ref_kv_store` | libref | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `ref_kv_store` | libref | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `kv_store` | `ref_kv_store` | libref | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 2e-02 |
+| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=1` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=1` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=2` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=2` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=4` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=4` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=8` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=8` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=16` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=16` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=32` | - | 1 | ok | 4.21e-08 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=32` | - | 1 | ok | 8.42e-08 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=64` | - | 1 | ok | 1.19e-07 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=64` | - | 1 | ok | 1.52e-05 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=128` | - | 1 | ok | 3.41e-07 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=128` | - | 1 | ok | 3.99e-06 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=256` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=256` | - | 1 | ok | 4.42e-05 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=512` | - | 1 | ok | 1.35e-06 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=512` | - | 1 | ok | 3.29e-05 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `avx_kv_store` | libavx | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `kv_store_fp8` | libr4d | device | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `ref_kv_store` | libref | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `avx_kv_store` | libavx | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `kv_store_fp8` | libr4d | device | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `ref_kv_store` | libref | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `avx_kv_store` | libavx | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `kv_store_fp8` | libr4d | device | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `ref_kv_store` | libref | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `avx_kv_store` | libavx | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `kv_store_fp8` | libr4d | device | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `ref_kv_store` | libref | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `avx_kv_store` | libavx | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `kv_store_fp8` | libr4d | device | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `ref_kv_store` | libref | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `avx_kv_store` | libavx | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `kv_store_fp8` | libr4d | device | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `ref_kv_store` | libref | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `avx_kv_store` | libavx | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `kv_store_fp8` | libr4d | device | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `ref_kv_store` | libref | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `avx_kv_store` | libavx | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `kv_store_fp8` | libr4d | device | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `ref_kv_store` | libref | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `avx_kv_store` | libavx | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `kv_store_fp8` | libr4d | device | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `ref_kv_store` | libref | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `avx_kv_store` | libavx | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `kv_store_fp8` | libr4d | device | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `kv_store` | `ref_kv_store` | libref | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=4096 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
 | `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=4096 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=4096 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=4096 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=4096 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
 | `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=4096 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=4096 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=4096 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=4096 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
 | `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=4096 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=4096 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=4096 group=128 dtype=bf16 M=8` | - | 1 | ok | 8.74e-15 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=4096 group=128 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=4096 group=128 dtype=bf16 M=16` | - | 1 | ok | 4.38e-15 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=4096 group=128 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=4096 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=4096 group=128 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=4096 group=128 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=4096 group=128 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=4096 group=128 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=4096 group=128 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=4096 group=128 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=4096 group=128 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
 | `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=4096 group=128 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=4096 group=128 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=4096 group=128 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=4096 group=128 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
 | `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=4096 group=128 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=4096 group=128 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=4096 group=128 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=17408 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
 | `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=17408 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=17408 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=17408 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=17408 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
 | `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=17408 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=17408 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=17408 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=17408 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
 | `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=17408 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=17408 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=17408 group=128 dtype=bf16 M=8` | - | 1 | ok | 2.17e-15 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=17408 group=128 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=17408 group=128 dtype=bf16 M=16` | - | 1 | ok | 2.05e-15 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=17408 group=128 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=17408 group=128 dtype=bf16 M=32` | - | 1 | ok | 7.41e-07 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=17408 group=128 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=17408 group=128 dtype=bf16 M=64` | - | 1 | ok | 1.02e-15 | 1e-06 |
-| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=17408 group=128 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=17408 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=17408 group=128 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=17408 group=128 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=17408 group=128 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=17408 group=128 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=17408 group=128 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=17408 group=128 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=17408 group=128 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=17408 group=128 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=17408 group=128 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | host | `n=17408 group=128 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=17408 group=128 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=17408 group=128 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt` | `avx_gemm_nt` | libavx | host | `N=1280 K=5120 dtype=bf16 M=1 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
 | `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=1280 K=5120 dtype=bf16 M=1 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=1280 K=5120 dtype=bf16 M=1 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=1280 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 5.38e-13 | 8e-03 |
-| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=1280 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=1280 K=5120 dtype=bf16 M=4 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 1.22e-06 | 8e-03 |
-| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=1280 K=5120 dtype=bf16 M=4 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=1280 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 1.96e-09 | 8e-03 |
-| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=1280 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=1280 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 3.50e-08 | 8e-03 |
-| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=1280 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=1280 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 3.62e-07 | 8e-03 |
-| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=1280 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=1280 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 1.88e-07 | 8e-03 |
-| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=1280 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=1280 K=5120 dtype=bf16 M=64 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 1.56e-07 | 8e-03 |
-| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=1280 K=5120 dtype=bf16 M=64 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=4096 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=4096 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=4096 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 8.03e-12 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=4096 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=4096 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 3.96e-09 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=4096 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=4096 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 7.55e-09 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=4096 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=4096 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 7.63e-09 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=4096 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=4096 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 5.48e-14 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=4096 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=4096 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 3.41e-09 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=4096 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=4096 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 1.58e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=4096 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=4096 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 2.13e-09 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=4096 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=4096 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 1.71e-07 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=4096 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=4096 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 1.44e-07 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=4096 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=4096 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 1.74e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=4096 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=4096 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=4096 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=4096 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 2.59e-12 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=4096 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=4096 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 4.58e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=4096 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=4096 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 6.74e-08 | 3e-02 |
-| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=4096 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 0.00e+00 | 3e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=8` | - | 1 | ok | 8.88e-11 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=32` | - | 1 | ok | 2.19e-08 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=64` | - | 1 | ok | 2.71e-10 | 2e-02 |
-| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
+| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=1280 K=5120 dtype=bf16 M=1 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt` | `avx_gemm_nt` | libavx | host | `N=1280 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 1.39e-04 | 8e-03 |
+| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=1280 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 1.39e-04 | 8e-03 |
+| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=1280 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt` | `avx_gemm_nt` | libavx | host | `N=1280 K=5120 dtype=bf16 M=4 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=1280 K=5120 dtype=bf16 M=4 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 3.80e-07 | 8e-03 |
+| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=1280 K=5120 dtype=bf16 M=4 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt` | `avx_gemm_nt` | libavx | host | `N=1280 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 5.39e-07 | 8e-03 |
+| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=1280 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 6.31e-07 | 8e-03 |
+| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=1280 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt` | `avx_gemm_nt` | libavx | host | `N=1280 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 6.02e-05 | 8e-03 |
+| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=1280 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 5.49e-05 | 8e-03 |
+| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=1280 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt` | `avx_gemm_nt` | libavx | host | `N=1280 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 2.40e-05 | 8e-03 |
+| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=1280 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 1.04e-04 | 8e-03 |
+| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=1280 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt` | `avx_gemm_nt` | libavx | host | `N=1280 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 2.46e-05 | 8e-03 |
+| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=1280 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 8.34e-06 | 8e-03 |
+| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=1280 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt` | `avx_gemm_nt` | libavx | host | `N=1280 K=5120 dtype=bf16 M=64 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 3.01e-05 | 8e-03 |
+| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=1280 K=5120 dtype=bf16 M=64 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 6.58e-05 | 8e-03 |
+| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=1280 K=5120 dtype=bf16 M=64 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=1 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=1 ks=0 bk=0 nt=0` | - | 1 | ok | 1.45e-06 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=1 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=2 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=2 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=2 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=4 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=4 ks=0 bk=0 nt=0` | - | 1 | ok | 4.55e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=4 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=8 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=8 ks=0 bk=0 nt=0` | - | 1 | ok | 3.10e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=8 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=9 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=9 ks=0 bk=0 nt=0` | - | 1 | ok | 2.29e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=9 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=18 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=18 ks=0 bk=0 nt=0` | - | 1 | ok | 4.50e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=18 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=36 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=36 ks=0 bk=0 nt=0` | - | 1 | ok | 4.19e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=36 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=64 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=64 ks=0 bk=0 nt=0` | - | 1 | ok | 2.12e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=64 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=1 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=1 ks=0 bk=0 nt=0` | - | 1 | ok | 3.63e-07 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=1 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=2 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=2 ks=0 bk=0 nt=0` | - | 1 | ok | 3.65e-06 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=2 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=4 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=4 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=4 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=8 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=8 ks=0 bk=0 nt=0` | - | 1 | ok | 3.04e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=8 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=9 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=9 ks=0 bk=0 nt=0` | - | 1 | ok | 9.10e-06 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=9 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=18 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=18 ks=0 bk=0 nt=0` | - | 1 | ok | 5.36e-06 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=18 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=36 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=36 ks=0 bk=0 nt=0` | - | 1 | ok | 4.19e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=36 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=64 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=64 ks=0 bk=0 nt=0` | - | 1 | ok | 2.92e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=64 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=1 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=1 ks=0 bk=0 nt=0` | - | 1 | ok | 3.15e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=1 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=2 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=2 ks=0 bk=0 nt=0` | - | 1 | ok | 5.94e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=2 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=4 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=4 ks=0 bk=0 nt=0` | - | 1 | ok | 2.42e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=4 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=8 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=8 ks=0 bk=0 nt=0` | - | 1 | ok | 8.96e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=8 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=9 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=9 ks=0 bk=0 nt=0` | - | 1 | ok | 3.57e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=9 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=18 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=18 ks=0 bk=0 nt=0` | - | 1 | ok | 2.45e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=18 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=36 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=36 ks=0 bk=0 nt=0` | - | 1 | ok | 4.77e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=36 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=64 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=64 ks=0 bk=0 nt=0` | - | 1 | ok | 3.54e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=64 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=1 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=1 ks=0 bk=0 nt=0` | - | 1 | ok | 4.28e-08 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=1 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=2 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=2 ks=0 bk=0 nt=0` | - | 1 | ok | 9.41e-07 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=2 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=4 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=4 ks=0 bk=0 nt=0` | - | 1 | ok | 6.56e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=4 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=8 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=8 ks=0 bk=0 nt=0` | - | 1 | ok | 3.81e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=8 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=9 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=9 ks=0 bk=0 nt=0` | - | 1 | ok | 8.90e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=9 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=18 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=18 ks=0 bk=0 nt=0` | - | 1 | ok | 3.97e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=18 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=36 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=36 ks=0 bk=0 nt=0` | - | 1 | ok | 4.71e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=36 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | host | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=64 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 3e-02 |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | device | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=64 ks=0 bk=0 nt=0` | - | 1 | ok | 4.82e-05 | 3e-02 |
+| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=64 ks=0 bk=0 nt=0` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=1` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=1` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=2` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=2` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=4` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=4` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=8` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=8` | - | 1 | ok | 6.77e-07 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=16` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=16` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=32` | - | 1 | ok | 1.05e-08 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=32` | - | 1 | ok | 1.10e-05 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=64` | - | 1 | ok | 3.94e-07 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=64` | - | 1 | ok | 6.38e-06 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `silu_mul` | `avx_silu_mul` | libavx | host | `n=17408 dtype=bf16 M=1` | - | 1 | ok | 2.65e-04 | 6e-03 |
 | `silu_mul` | `silu_mul_bf16` | libr4d | device | `n=17408 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `silu_mul` | `ref_silu_mul` | libref | host | `n=17408 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `silu_mul` | `ref_silu_mul` | libref | host | `n=17408 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `silu_mul` | `avx_silu_mul` | libavx | host | `n=17408 dtype=bf16 M=2` | - | 1 | ok | 2.49e-04 | 6e-03 |
 | `silu_mul` | `silu_mul_bf16` | libr4d | device | `n=17408 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `silu_mul` | `ref_silu_mul` | libref | host | `n=17408 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `silu_mul` | `silu_mul_bf16` | libr4d | device | `n=17408 dtype=bf16 M=4` | - | 1 | ok | 3.60e-08 | 6e-03 |
-| `silu_mul` | `ref_silu_mul` | libref | host | `n=17408 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `silu_mul` | `ref_silu_mul` | libref | host | `n=17408 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `silu_mul` | `avx_silu_mul` | libavx | host | `n=17408 dtype=bf16 M=4` | - | 1 | ok | 3.14e-04 | 6e-03 |
+| `silu_mul` | `silu_mul_bf16` | libr4d | device | `n=17408 dtype=bf16 M=4` | - | 1 | ok | 1.22e-05 | 6e-03 |
+| `silu_mul` | `ref_silu_mul` | libref | host | `n=17408 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `silu_mul` | `avx_silu_mul` | libavx | host | `n=17408 dtype=bf16 M=8` | - | 1 | ok | 5.65e-04 | 6e-03 |
 | `silu_mul` | `silu_mul_bf16` | libr4d | device | `n=17408 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `silu_mul` | `ref_silu_mul` | libref | host | `n=17408 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `silu_mul` | `silu_mul_bf16` | libr4d | device | `n=17408 dtype=bf16 M=16` | - | 1 | ok | 9.74e-09 | 6e-03 |
-| `silu_mul` | `ref_silu_mul` | libref | host | `n=17408 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `silu_mul` | `silu_mul_bf16` | libr4d | device | `n=17408 dtype=bf16 M=32` | - | 1 | ok | 2.45e-08 | 6e-03 |
-| `silu_mul` | `ref_silu_mul` | libref | host | `n=17408 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `silu_mul` | `silu_mul_bf16` | libr4d | device | `n=17408 dtype=bf16 M=64` | - | 1 | ok | 7.13e-09 | 6e-03 |
-| `silu_mul` | `ref_silu_mul` | libref | host | `n=17408 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `gather_rows` | `gather_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=56` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `gather_rows` | `ref_gather_rows` | libref | host | `n=5120 dtype=bf16 M=56` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `row_topk` | `rowtopk_bf16` | libr4d | device | `N=248320 R=16 dtype=bf16 M=1 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `row_topk` | `ref_row_topk` | libref | host | `N=248320 R=16 dtype=bf16 M=1 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `row_topk` | `rowtopk_bf16` | libr4d | device | `N=248320 R=16 dtype=bf16 M=2 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `row_topk` | `ref_row_topk` | libref | host | `N=248320 R=16 dtype=bf16 M=2 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `row_topk` | `rowtopk_bf16` | libr4d | device | `N=248320 R=16 dtype=bf16 M=4 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `row_topk` | `ref_row_topk` | libref | host | `N=248320 R=16 dtype=bf16 M=4 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `row_topk` | `rowtopk_bf16` | libr4d | device | `N=248320 R=16 dtype=bf16 M=8 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `row_topk` | `ref_row_topk` | libref | host | `N=248320 R=16 dtype=bf16 M=8 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `row_topk` | `rowtopk_bf16` | libr4d | device | `N=248320 R=16 dtype=bf16 M=16 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `row_topk` | `ref_row_topk` | libref | host | `N=248320 R=16 dtype=bf16 M=16 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `row_topk` | `rowtopk_bf16` | libr4d | device | `N=248320 R=16 dtype=bf16 M=32 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `row_topk` | `ref_row_topk` | libref | host | `N=248320 R=16 dtype=bf16 M=32 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `row_topk` | `rowtopk_bf16` | libr4d | device | `N=248320 R=16 dtype=bf16 M=56 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 6e-03 |
-| `row_topk` | `ref_row_topk` | libref | host | `N=248320 R=16 dtype=bf16 M=56 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `silu_mul` | `ref_silu_mul` | libref | host | `n=17408 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `silu_mul` | `avx_silu_mul` | libavx | host | `n=17408 dtype=bf16 M=16` | - | 1 | ok | 2.54e-04 | 6e-03 |
+| `silu_mul` | `silu_mul_bf16` | libr4d | device | `n=17408 dtype=bf16 M=16` | - | 1 | ok | 6.46e-06 | 6e-03 |
+| `silu_mul` | `ref_silu_mul` | libref | host | `n=17408 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `silu_mul` | `avx_silu_mul` | libavx | host | `n=17408 dtype=bf16 M=32` | - | 1 | ok | 2.65e-04 | 6e-03 |
+| `silu_mul` | `silu_mul_bf16` | libr4d | device | `n=17408 dtype=bf16 M=32` | - | 1 | ok | 9.34e-06 | 6e-03 |
+| `silu_mul` | `ref_silu_mul` | libref | host | `n=17408 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `silu_mul` | `avx_silu_mul` | libavx | host | `n=17408 dtype=bf16 M=64` | - | 1 | ok | 2.48e-04 | 6e-03 |
+| `silu_mul` | `silu_mul_bf16` | libr4d | device | `n=17408 dtype=bf16 M=64` | - | 1 | ok | 5.43e-06 | 6e-03 |
+| `silu_mul` | `ref_silu_mul` | libref | host | `n=17408 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gather_rows` | `avx_gather_rows` | libavx | host | `n=5120 dtype=bf16 M=56` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gather_rows` | `gather_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=56` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gather_rows` | `ref_gather_rows` | libref | host | `n=5120 dtype=bf16 M=56` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_i8` | `avx_quant_act_i8` | libavx | host | `n=5120 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_i8` | `quant_act_i8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_i8` | `ref_quant_act_i8` | libref | host | `n=5120 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_i8` | `avx_quant_act_i8` | libavx | host | `n=5120 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_i8` | `quant_act_i8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_i8` | `ref_quant_act_i8` | libref | host | `n=5120 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_i8` | `avx_quant_act_i8` | libavx | host | `n=5120 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_i8` | `quant_act_i8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_i8` | `ref_quant_act_i8` | libref | host | `n=5120 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_i8` | `avx_quant_act_i8` | libavx | host | `n=5120 group=128 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_i8` | `quant_act_i8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_i8` | `ref_quant_act_i8` | libref | host | `n=5120 group=128 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_i8` | `avx_quant_act_i8` | libavx | host | `n=5120 group=128 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_i8` | `quant_act_i8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_i8` | `ref_quant_act_i8` | libref | host | `n=5120 group=128 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_i8` | `avx_quant_act_i8` | libavx | host | `n=5120 group=128 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_i8` | `quant_act_i8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_i8` | `ref_quant_act_i8` | libref | host | `n=5120 group=128 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `quant_act_i8` | `avx_quant_act_i8` | libavx | host | `n=5120 group=128 dtype=bf16 M=56` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_i8` | `quant_act_i8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=56` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `quant_act_i8` | `ref_quant_act_i8` | libref | host | `n=5120 group=128 dtype=bf16 M=56` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `row_topk` | `avx_row_topk` | libavx | host | `N=248320 R=32 dtype=bf16 M=1 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `row_topk` | `rowtopk_bf16` | libr4d | device | `N=248320 R=32 dtype=bf16 M=1 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `row_topk` | `ref_row_topk` | libref | host | `N=248320 R=32 dtype=bf16 M=1 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `row_topk` | `avx_row_topk` | libavx | host | `N=248320 R=32 dtype=bf16 M=2 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `row_topk` | `rowtopk_bf16` | libr4d | device | `N=248320 R=32 dtype=bf16 M=2 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `row_topk` | `ref_row_topk` | libref | host | `N=248320 R=32 dtype=bf16 M=2 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `row_topk` | `avx_row_topk` | libavx | host | `N=248320 R=32 dtype=bf16 M=4 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `row_topk` | `rowtopk_bf16` | libr4d | device | `N=248320 R=32 dtype=bf16 M=4 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `row_topk` | `ref_row_topk` | libref | host | `N=248320 R=32 dtype=bf16 M=4 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `row_topk` | `avx_row_topk` | libavx | host | `N=248320 R=32 dtype=bf16 M=8 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `row_topk` | `rowtopk_bf16` | libr4d | device | `N=248320 R=32 dtype=bf16 M=8 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `row_topk` | `ref_row_topk` | libref | host | `N=248320 R=32 dtype=bf16 M=8 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `row_topk` | `avx_row_topk` | libavx | host | `N=248320 R=32 dtype=bf16 M=16 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `row_topk` | `rowtopk_bf16` | libr4d | device | `N=248320 R=32 dtype=bf16 M=16 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `row_topk` | `ref_row_topk` | libref | host | `N=248320 R=32 dtype=bf16 M=16 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `row_topk` | `avx_row_topk` | libavx | host | `N=248320 R=32 dtype=bf16 M=32 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `row_topk` | `rowtopk_bf16` | libr4d | device | `N=248320 R=32 dtype=bf16 M=32 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `row_topk` | `ref_row_topk` | libref | host | `N=248320 R=32 dtype=bf16 M=32 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `row_topk` | `avx_row_topk` | libavx | host | `N=248320 R=32 dtype=bf16 M=56 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `row_topk` | `rowtopk_bf16` | libr4d | device | `N=248320 R=32 dtype=bf16 M=56 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `row_topk` | `ref_row_topk` | libref | host | `N=248320 R=32 dtype=bf16 M=56 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt` | `avx_gemm_nt` | libavx | host | `N=256 K=5120 dtype=bf16 M=1 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
 | `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=256 K=5120 dtype=bf16 M=1 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=256 K=5120 dtype=bf16 M=1 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=256 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 4.58e-08 | 8e-03 |
-| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=256 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=256 K=5120 dtype=bf16 M=1 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt` | `avx_gemm_nt` | libavx | host | `N=256 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=256 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=256 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt` | `avx_gemm_nt` | libavx | host | `N=256 K=5120 dtype=bf16 M=4 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
 | `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=256 K=5120 dtype=bf16 M=4 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=256 K=5120 dtype=bf16 M=4 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=256 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=256 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=256 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 8.65e-05 | 8e-03 |
-| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=256 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=256 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 1.75e-11 | 8e-03 |
-| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=256 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=256 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 4.00e-06 | 8e-03 |
-| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=256 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=256 K=5120 dtype=bf16 M=56 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 3.03e-07 | 8e-03 |
-| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=256 K=5120 dtype=bf16 M=56 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
-| `sample_penalties` | `sample_penalties_f32` | libr4d | device | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_penalties` | `ref_sample_penalties` | libref | host | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_penalties` | `sample_penalties_f32` | libr4d | device | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_penalties` | `ref_sample_penalties` | libref | host | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_penalties` | `sample_penalties_f32` | libr4d | device | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_penalties` | `ref_sample_penalties` | libref | host | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_penalties` | `sample_penalties_f32` | libr4d | device | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_penalties` | `ref_sample_penalties` | libref | host | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_penalties` | `sample_penalties_f32` | libr4d | device | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_penalties` | `ref_sample_penalties` | libref | host | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_penalties` | `sample_penalties_f32` | libr4d | device | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_penalties` | `ref_sample_penalties` | libref | host | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_penalties` | `sample_penalties_f32` | libr4d | device | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_penalties` | `ref_sample_penalties` | libref | host | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_dry` | `sample_dry_f32` | libr4d | device | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_dry` | `ref_sample_dry` | libref | host | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_dry` | `sample_dry_f32` | libr4d | device | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_dry` | `ref_sample_dry` | libref | host | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_dry` | `sample_dry_f32` | libr4d | device | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_dry` | `ref_sample_dry` | libref | host | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_dry` | `sample_dry_f32` | libr4d | device | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_dry` | `ref_sample_dry` | libref | host | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_dry` | `sample_dry_f32` | libr4d | device | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_dry` | `ref_sample_dry` | libref | host | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_dry` | `sample_dry_f32` | libr4d | device | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_dry` | `ref_sample_dry` | libref | host | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_dry` | `sample_dry_f32` | libr4d | device | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_dry` | `ref_sample_dry` | libref | host | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_temp` | `sample_temp_f32` | libr4d | device | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_temp` | `ref_sample_temp` | libref | host | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_temp` | `sample_temp_f32` | libr4d | device | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_temp` | `ref_sample_temp` | libref | host | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_temp` | `sample_temp_f32` | libr4d | device | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_temp` | `ref_sample_temp` | libref | host | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_temp` | `sample_temp_f32` | libr4d | device | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_temp` | `ref_sample_temp` | libref | host | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_temp` | `sample_temp_f32` | libr4d | device | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_temp` | `ref_sample_temp` | libref | host | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_temp` | `sample_temp_f32` | libr4d | device | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_temp` | `ref_sample_temp` | libref | host | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_temp` | `sample_temp_f32` | libr4d | device | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_temp` | `ref_sample_temp` | libref | host | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_mask` | `sample_mask_f32` | libr4d | device | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_mask` | `ref_sample_mask` | libref | host | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_mask` | `sample_mask_f32` | libr4d | device | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_mask` | `ref_sample_mask` | libref | host | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_mask` | `sample_mask_f32` | libr4d | device | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_mask` | `ref_sample_mask` | libref | host | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_mask` | `sample_mask_f32` | libr4d | device | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_mask` | `ref_sample_mask` | libref | host | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_mask` | `sample_mask_f32` | libr4d | device | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_mask` | `ref_sample_mask` | libref | host | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_mask` | `sample_mask_f32` | libr4d | device | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_mask` | `ref_sample_mask` | libref | host | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_mask` | `sample_mask_f32` | libr4d | device | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_mask` | `ref_sample_mask` | libref | host | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_topk` | `sample_topk_f32` | libr4d | device | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_topk` | `ref_sample_topk` | libref | host | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_topk` | `sample_topk_f32` | libr4d | device | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_topk` | `ref_sample_topk` | libref | host | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_topk` | `sample_topk_f32` | libr4d | device | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_topk` | `ref_sample_topk` | libref | host | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_topk` | `sample_topk_f32` | libr4d | device | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_topk` | `ref_sample_topk` | libref | host | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_topk` | `sample_topk_f32` | libr4d | device | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_topk` | `ref_sample_topk` | libref | host | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_topk` | `sample_topk_f32` | libr4d | device | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_topk` | `ref_sample_topk` | libref | host | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_topk` | `sample_topk_f32` | libr4d | device | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_topk` | `ref_sample_topk` | libref | host | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_argmax` | `sample_argmax_f32` | libr4d | device | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_argmax` | `ref_sample_argmax` | libref | host | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_argmax` | `sample_argmax_f32` | libr4d | device | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_argmax` | `ref_sample_argmax` | libref | host | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_argmax` | `sample_argmax_f32` | libr4d | device | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_argmax` | `ref_sample_argmax` | libref | host | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_argmax` | `sample_argmax_f32` | libr4d | device | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_argmax` | `ref_sample_argmax` | libref | host | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_argmax` | `sample_argmax_f32` | libr4d | device | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_argmax` | `ref_sample_argmax` | libref | host | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_argmax` | `sample_argmax_f32` | libr4d | device | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_argmax` | `ref_sample_argmax` | libref | host | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_argmax` | `sample_argmax_f32` | libr4d | device | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_argmax` | `ref_sample_argmax` | libref | host | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_topp` | `sample_topp_f32` | libr4d | device | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_topp` | `ref_sample_topp` | libref | host | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_topp` | `sample_topp_f32` | libr4d | device | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_topp` | `ref_sample_topp` | libref | host | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_topp` | `sample_topp_f32` | libr4d | device | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_topp` | `ref_sample_topp` | libref | host | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_topp` | `sample_topp_f32` | libr4d | device | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_topp` | `ref_sample_topp` | libref | host | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_topp` | `sample_topp_f32` | libr4d | device | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_topp` | `ref_sample_topp` | libref | host | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_topp` | `sample_topp_f32` | libr4d | device | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_topp` | `ref_sample_topp` | libref | host | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_topp` | `sample_topp_f32` | libr4d | device | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_topp` | `ref_sample_topp` | libref | host | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_minp` | `sample_minp_f32` | libr4d | device | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_minp` | `ref_sample_minp` | libref | host | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_minp` | `sample_minp_f32` | libr4d | device | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_minp` | `ref_sample_minp` | libref | host | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_minp` | `sample_minp_f32` | libr4d | device | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_minp` | `ref_sample_minp` | libref | host | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_minp` | `sample_minp_f32` | libr4d | device | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_minp` | `ref_sample_minp` | libref | host | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_minp` | `sample_minp_f32` | libr4d | device | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_minp` | `ref_sample_minp` | libref | host | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_minp` | `sample_minp_f32` | libr4d | device | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_minp` | `ref_sample_minp` | libref | host | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_minp` | `sample_minp_f32` | libr4d | device | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_minp` | `ref_sample_minp` | libref | host | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_typical` | `sample_typical_f32` | libr4d | device | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_typical` | `ref_sample_typical` | libref | host | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_typical` | `sample_typical_f32` | libr4d | device | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_typical` | `ref_sample_typical` | libref | host | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_typical` | `sample_typical_f32` | libr4d | device | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_typical` | `ref_sample_typical` | libref | host | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_typical` | `sample_typical_f32` | libr4d | device | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_typical` | `ref_sample_typical` | libref | host | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_typical` | `sample_typical_f32` | libr4d | device | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_typical` | `ref_sample_typical` | libref | host | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_typical` | `sample_typical_f32` | libr4d | device | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_typical` | `ref_sample_typical` | libref | host | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_typical` | `sample_typical_f32` | libr4d | device | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_typical` | `ref_sample_typical` | libref | host | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_xtc` | `sample_xtc_f32` | libr4d | device | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_xtc` | `ref_sample_xtc` | libref | host | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_xtc` | `sample_xtc_f32` | libr4d | device | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_xtc` | `ref_sample_xtc` | libref | host | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_xtc` | `sample_xtc_f32` | libr4d | device | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_xtc` | `ref_sample_xtc` | libref | host | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_xtc` | `sample_xtc_f32` | libr4d | device | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_xtc` | `ref_sample_xtc` | libref | host | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_xtc` | `sample_xtc_f32` | libr4d | device | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_xtc` | `ref_sample_xtc` | libref | host | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_xtc` | `sample_xtc_f32` | libr4d | device | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_xtc` | `ref_sample_xtc` | libref | host | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_xtc` | `sample_xtc_f32` | libr4d | device | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_xtc` | `ref_sample_xtc` | libref | host | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_pick` | `sample_pick_f32` | libr4d | device | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_pick` | `ref_sample_pick` | libref | host | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_pick` | `sample_pick_f32` | libr4d | device | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_pick` | `ref_sample_pick` | libref | host | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_pick` | `sample_pick_f32` | libr4d | device | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_pick` | `ref_sample_pick` | libref | host | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_pick` | `sample_pick_f32` | libr4d | device | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_pick` | `ref_sample_pick` | libref | host | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_pick` | `sample_pick_f32` | libr4d | device | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_pick` | `ref_sample_pick` | libref | host | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_pick` | `sample_pick_f32` | libr4d | device | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_pick` | `ref_sample_pick` | libref | host | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_pick` | `sample_pick_f32` | libr4d | device | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
-| `sample_pick` | `ref_sample_pick` | libref | host | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
+| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=256 K=5120 dtype=bf16 M=4 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt` | `avx_gemm_nt` | libavx | host | `N=256 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 3.95e-05 | 8e-03 |
+| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=256 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 2.16e-07 | 8e-03 |
+| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=256 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt` | `avx_gemm_nt` | libavx | host | `N=256 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 5.44e-05 | 8e-03 |
+| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=256 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 8.43e-07 | 8e-03 |
+| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=256 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt` | `avx_gemm_nt` | libavx | host | `N=256 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 6.65e-06 | 8e-03 |
+| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=256 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 2.08e-07 | 8e-03 |
+| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=256 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt` | `avx_gemm_nt` | libavx | host | `N=256 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 1.11e-04 | 8e-03 |
+| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=256 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 1.11e-04 | 8e-03 |
+| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=256 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt` | `avx_gemm_nt` | libavx | host | `N=256 K=5120 dtype=bf16 M=56 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 1.24e-04 | 8e-03 |
+| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=256 K=5120 dtype=bf16 M=56 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 1.29e-04 | 8e-03 |
+| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=256 K=5120 dtype=bf16 M=56 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `dflash_select` | `avx_dflash_select` | libavx | host | `steps=7 top_k=16 rank=256 n_vocab=248320 anchor_stride=8 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `dflash_select` | `dflash_select_bf16` | libr4d | device | `steps=7 top_k=16 rank=256 n_vocab=248320 anchor_stride=8 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `dflash_select` | `ref_dflash_select` | libref | host | `steps=7 top_k=16 rank=256 n_vocab=248320 anchor_stride=8 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `dflash_select` | `avx_dflash_select` | libavx | host | `steps=7 top_k=16 rank=256 n_vocab=248320 anchor_stride=8 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `dflash_select` | `dflash_select_bf16` | libr4d | device | `steps=7 top_k=16 rank=256 n_vocab=248320 anchor_stride=8 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `dflash_select` | `ref_dflash_select` | libref | host | `steps=7 top_k=16 rank=256 n_vocab=248320 anchor_stride=8 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `dflash_select` | `avx_dflash_select` | libavx | host | `steps=7 top_k=16 rank=256 n_vocab=248320 anchor_stride=8 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `dflash_select` | `dflash_select_bf16` | libr4d | device | `steps=7 top_k=16 rank=256 n_vocab=248320 anchor_stride=8 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `dflash_select` | `ref_dflash_select` | libref | host | `steps=7 top_k=16 rank=256 n_vocab=248320 anchor_stride=8 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `dflash_select` | `avx_dflash_select` | libavx | host | `steps=7 top_k=16 rank=256 n_vocab=248320 anchor_stride=8 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `dflash_select` | `dflash_select_bf16` | libr4d | device | `steps=7 top_k=16 rank=256 n_vocab=248320 anchor_stride=8 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `dflash_select` | `ref_dflash_select` | libref | host | `steps=7 top_k=16 rank=256 n_vocab=248320 anchor_stride=8 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=1152 K=1536 dtype=bf16 act=none M=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=1152 K=1536 dtype=bf16 act=none M=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=1152 K=1536 dtype=bf16 act=none M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=1152 K=1536 dtype=bf16 act=none M=2` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=1152 K=1536 dtype=bf16 act=none M=2` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=1152 K=1536 dtype=bf16 act=none M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=1152 K=1536 dtype=bf16 act=none M=4` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=1152 K=1536 dtype=bf16 act=none M=4` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=1152 K=1536 dtype=bf16 act=none M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=1152 K=1536 dtype=bf16 act=none M=8` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=1152 K=1536 dtype=bf16 act=none M=8` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=1152 K=1536 dtype=bf16 act=none M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=1152 K=1536 dtype=bf16 act=none M=16` | - | 1 | ok | 2.15e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=1152 K=1536 dtype=bf16 act=none M=16` | - | 1 | ok | 2.17e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=1152 K=1536 dtype=bf16 act=none M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=1152 K=1536 dtype=bf16 act=none M=32` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=1152 K=1536 dtype=bf16 act=none M=32` | - | 1 | ok | 2.21e-06 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=1152 K=1536 dtype=bf16 act=none M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=1152 K=1536 dtype=bf16 act=none M=64` | - | 1 | ok | 1.20e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=1152 K=1536 dtype=bf16 act=none M=64` | - | 1 | ok | 1.74e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=1152 K=1536 dtype=bf16 act=none M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=1152 K=1536 dtype=bf16 act=none M=128` | - | 1 | ok | 1.30e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=1152 K=1536 dtype=bf16 act=none M=128` | - | 1 | ok | 1.55e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=1152 K=1536 dtype=bf16 act=none M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=1152 K=1536 dtype=bf16 act=none M=256` | - | 1 | ok | 2.58e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=1152 K=1536 dtype=bf16 act=none M=256` | - | 1 | ok | 6.45e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=1152 K=1536 dtype=bf16 act=none M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=1152 K=1536 dtype=bf16 act=none M=512` | - | 1 | ok | 3.31e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=1152 K=1536 dtype=bf16 act=none M=512` | - | 1 | ok | 2.86e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=1152 K=1536 dtype=bf16 act=none M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `grid_embed` | `avx_grid_embed` | libavx | host | `n=1152 side=48 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `grid_embed` | `grid_embed_bf16` | libr4d | device | `n=1152 side=48 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `grid_embed` | `ref_grid_embed` | libref | host | `n=1152 side=48 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `grid_embed` | `avx_grid_embed` | libavx | host | `n=1152 side=48 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `grid_embed` | `grid_embed_bf16` | libr4d | device | `n=1152 side=48 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `grid_embed` | `ref_grid_embed` | libref | host | `n=1152 side=48 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `grid_embed` | `avx_grid_embed` | libavx | host | `n=1152 side=48 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `grid_embed` | `grid_embed_bf16` | libr4d | device | `n=1152 side=48 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `grid_embed` | `ref_grid_embed` | libref | host | `n=1152 side=48 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `grid_embed` | `avx_grid_embed` | libavx | host | `n=1152 side=48 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `grid_embed` | `grid_embed_bf16` | libr4d | device | `n=1152 side=48 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `grid_embed` | `ref_grid_embed` | libref | host | `n=1152 side=48 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `grid_embed` | `avx_grid_embed` | libavx | host | `n=1152 side=48 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `grid_embed` | `grid_embed_bf16` | libr4d | device | `n=1152 side=48 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `grid_embed` | `ref_grid_embed` | libref | host | `n=1152 side=48 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `grid_embed` | `avx_grid_embed` | libavx | host | `n=1152 side=48 dtype=bf16 M=32` | - | 1 | ok | 7.83e-05 | 6e-03 |
+| `grid_embed` | `grid_embed_bf16` | libr4d | device | `n=1152 side=48 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `grid_embed` | `ref_grid_embed` | libref | host | `n=1152 side=48 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `grid_embed` | `avx_grid_embed` | libavx | host | `n=1152 side=48 dtype=bf16 M=64` | - | 1 | ok | 4.88e-05 | 6e-03 |
+| `grid_embed` | `grid_embed_bf16` | libr4d | device | `n=1152 side=48 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `grid_embed` | `ref_grid_embed` | libref | host | `n=1152 side=48 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `grid_embed` | `avx_grid_embed` | libavx | host | `n=1152 side=48 dtype=bf16 M=128` | - | 1 | ok | 5.29e-05 | 6e-03 |
+| `grid_embed` | `grid_embed_bf16` | libr4d | device | `n=1152 side=48 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `grid_embed` | `ref_grid_embed` | libref | host | `n=1152 side=48 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `grid_embed` | `avx_grid_embed` | libavx | host | `n=1152 side=48 dtype=bf16 M=256` | - | 1 | ok | 4.16e-05 | 6e-03 |
+| `grid_embed` | `grid_embed_bf16` | libr4d | device | `n=1152 side=48 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `grid_embed` | `ref_grid_embed` | libref | host | `n=1152 side=48 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `grid_embed` | `avx_grid_embed` | libavx | host | `n=1152 side=48 dtype=bf16 M=512` | - | 1 | ok | 5.67e-05 | 6e-03 |
+| `grid_embed` | `grid_embed_bf16` | libr4d | device | `n=1152 side=48 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `grid_embed` | `ref_grid_embed` | libref | host | `n=1152 side=48 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `layernorm` | `avx_layernorm` | libavx | host | `n=1152 eps=1e-06 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `layernorm` | `layernorm_bf16` | libr4d | device | `n=1152 eps=1e-06 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `layernorm` | `ref_layernorm` | libref | host | `n=1152 eps=1e-06 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `layernorm` | `avx_layernorm` | libavx | host | `n=1152 eps=1e-06 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `layernorm` | `layernorm_bf16` | libr4d | device | `n=1152 eps=1e-06 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `layernorm` | `ref_layernorm` | libref | host | `n=1152 eps=1e-06 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `layernorm` | `avx_layernorm` | libavx | host | `n=1152 eps=1e-06 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `layernorm` | `layernorm_bf16` | libr4d | device | `n=1152 eps=1e-06 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 6e-03 |
+| `layernorm` | `ref_layernorm` | libref | host | `n=1152 eps=1e-06 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `layernorm` | `avx_layernorm` | libavx | host | `n=1152 eps=1e-06 dtype=bf16 M=8` | - | 1 | ok | 1.43e-05 | 6e-03 |
+| `layernorm` | `layernorm_bf16` | libr4d | device | `n=1152 eps=1e-06 dtype=bf16 M=8` | - | 1 | ok | 1.43e-05 | 6e-03 |
+| `layernorm` | `ref_layernorm` | libref | host | `n=1152 eps=1e-06 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `layernorm` | `avx_layernorm` | libavx | host | `n=1152 eps=1e-06 dtype=bf16 M=16` | - | 1 | ok | 4.74e-07 | 6e-03 |
+| `layernorm` | `layernorm_bf16` | libr4d | device | `n=1152 eps=1e-06 dtype=bf16 M=16` | - | 1 | ok | 4.74e-07 | 6e-03 |
+| `layernorm` | `ref_layernorm` | libref | host | `n=1152 eps=1e-06 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `layernorm` | `avx_layernorm` | libavx | host | `n=1152 eps=1e-06 dtype=bf16 M=32` | - | 1 | ok | 2.93e-05 | 6e-03 |
+| `layernorm` | `layernorm_bf16` | libr4d | device | `n=1152 eps=1e-06 dtype=bf16 M=32` | - | 1 | ok | 1.46e-05 | 6e-03 |
+| `layernorm` | `ref_layernorm` | libref | host | `n=1152 eps=1e-06 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `layernorm` | `avx_layernorm` | libavx | host | `n=1152 eps=1e-06 dtype=bf16 M=64` | - | 1 | ok | 2.00e-05 | 6e-03 |
+| `layernorm` | `layernorm_bf16` | libr4d | device | `n=1152 eps=1e-06 dtype=bf16 M=64` | - | 1 | ok | 1.25e-06 | 6e-03 |
+| `layernorm` | `ref_layernorm` | libref | host | `n=1152 eps=1e-06 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `layernorm` | `avx_layernorm` | libavx | host | `n=1152 eps=1e-06 dtype=bf16 M=128` | - | 1 | ok | 2.12e-05 | 6e-03 |
+| `layernorm` | `layernorm_bf16` | libr4d | device | `n=1152 eps=1e-06 dtype=bf16 M=128` | - | 1 | ok | 2.14e-05 | 6e-03 |
+| `layernorm` | `ref_layernorm` | libref | host | `n=1152 eps=1e-06 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `layernorm` | `avx_layernorm` | libavx | host | `n=1152 eps=1e-06 dtype=bf16 M=256` | - | 1 | ok | 2.09e-05 | 6e-03 |
+| `layernorm` | `layernorm_bf16` | libr4d | device | `n=1152 eps=1e-06 dtype=bf16 M=256` | - | 1 | ok | 2.11e-05 | 6e-03 |
+| `layernorm` | `ref_layernorm` | libref | host | `n=1152 eps=1e-06 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `layernorm` | `avx_layernorm` | libavx | host | `n=1152 eps=1e-06 dtype=bf16 M=512` | - | 1 | ok | 2.49e-05 | 6e-03 |
+| `layernorm` | `layernorm_bf16` | libr4d | device | `n=1152 eps=1e-06 dtype=bf16 M=512` | - | 1 | ok | 2.34e-05 | 6e-03 |
+| `layernorm` | `ref_layernorm` | libref | host | `n=1152 eps=1e-06 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=3456 K=1152 dtype=bf16 act=none M=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=3456 K=1152 dtype=bf16 act=none M=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=3456 K=1152 dtype=bf16 act=none M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=3456 K=1152 dtype=bf16 act=none M=2` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=3456 K=1152 dtype=bf16 act=none M=2` | - | 1 | ok | 2.17e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=3456 K=1152 dtype=bf16 act=none M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=3456 K=1152 dtype=bf16 act=none M=4` | - | 1 | ok | 3.89e-06 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=3456 K=1152 dtype=bf16 act=none M=4` | - | 1 | ok | 1.56e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=3456 K=1152 dtype=bf16 act=none M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=3456 K=1152 dtype=bf16 act=none M=8` | - | 1 | ok | 3.77e-06 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=3456 K=1152 dtype=bf16 act=none M=8` | - | 1 | ok | 1.13e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=3456 K=1152 dtype=bf16 act=none M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=3456 K=1152 dtype=bf16 act=none M=16` | - | 1 | ok | 1.68e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=3456 K=1152 dtype=bf16 act=none M=16` | - | 1 | ok | 2.28e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=3456 K=1152 dtype=bf16 act=none M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=3456 K=1152 dtype=bf16 act=none M=32` | - | 1 | ok | 3.29e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=3456 K=1152 dtype=bf16 act=none M=32` | - | 1 | ok | 4.24e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=3456 K=1152 dtype=bf16 act=none M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=3456 K=1152 dtype=bf16 act=none M=64` | - | 1 | ok | 4.51e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=3456 K=1152 dtype=bf16 act=none M=64` | - | 1 | ok | 3.05e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=3456 K=1152 dtype=bf16 act=none M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=3456 K=1152 dtype=bf16 act=none M=128` | - | 1 | ok | 3.53e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=3456 K=1152 dtype=bf16 act=none M=128` | - | 1 | ok | 3.43e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=3456 K=1152 dtype=bf16 act=none M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=3456 K=1152 dtype=bf16 act=none M=256` | - | 1 | ok | 2.25e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=3456 K=1152 dtype=bf16 act=none M=256` | - | 1 | ok | 2.89e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=3456 K=1152 dtype=bf16 act=none M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=3456 K=1152 dtype=bf16 act=none M=512` | - | 1 | ok | 3.59e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=3456 K=1152 dtype=bf16 act=none M=512` | - | 1 | ok | 3.11e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=3456 K=1152 dtype=bf16 act=none M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=1` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=1` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=2` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=2` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=4` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=4` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=8` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=8` | - | 1 | ok | 5.91e-06 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=16` | - | 1 | ok | 0.00e+00 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=16` | - | 1 | ok | 5.21e-07 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=32` | - | 1 | ok | 5.72e-09 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=32` | - | 1 | ok | 3.69e-06 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=64` | - | 1 | ok | 4.04e-09 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=64` | - | 1 | ok | 8.28e-06 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=128` | - | 1 | ok | 1.45e-06 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=128` | - | 1 | ok | 1.62e-05 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=256` | - | 1 | ok | 2.57e-06 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=256` | - | 1 | ok | 3.06e-05 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `rope` | `avx_rope` | libavx | host | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=512` | - | 1 | ok | 3.34e-06 | 2e-03 |
+| `rope` | `rope_bf16` | libr4d | device | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=512` | - | 1 | ok | 3.83e-05 | 2e-03 |
+| `rope` | `ref_rope` | libref | host | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_dense` | `avx_attn_dense` | libavx | host | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
+| `attn_dense` | `attn_vit_h72_bf16` | libr4d | device | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 |
+| `attn_dense` | `ref_attn_dense` | libref | host | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_dense` | `avx_attn_dense` | libavx | host | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 |
+| `attn_dense` | `attn_vit_h72_bf16` | libr4d | device | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=2` | - | 1 | ok | 1.36e-03 | 2e-02 |
+| `attn_dense` | `ref_attn_dense` | libref | host | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_dense` | `avx_attn_dense` | libavx | host | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 |
+| `attn_dense` | `attn_vit_h72_bf16` | libr4d | device | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=4` | - | 1 | ok | 8.61e-04 | 2e-02 |
+| `attn_dense` | `ref_attn_dense` | libref | host | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_dense` | `avx_attn_dense` | libavx | host | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 |
+| `attn_dense` | `attn_vit_h72_bf16` | libr4d | device | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=8` | - | 1 | ok | 1.07e-03 | 2e-02 |
+| `attn_dense` | `ref_attn_dense` | libref | host | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_dense` | `avx_attn_dense` | libavx | host | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 |
+| `attn_dense` | `attn_vit_h72_bf16` | libr4d | device | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=16` | - | 1 | ok | 8.42e-04 | 2e-02 |
+| `attn_dense` | `ref_attn_dense` | libref | host | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_dense` | `avx_attn_dense` | libavx | host | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 |
+| `attn_dense` | `attn_vit_h72_bf16` | libr4d | device | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=32` | - | 1 | ok | 1.54e-03 | 2e-02 |
+| `attn_dense` | `ref_attn_dense` | libref | host | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_dense` | `avx_attn_dense` | libavx | host | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 |
+| `attn_dense` | `attn_vit_h72_bf16` | libr4d | device | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=64` | - | 1 | ok | 1.40e-03 | 2e-02 |
+| `attn_dense` | `ref_attn_dense` | libref | host | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_dense` | `avx_attn_dense` | libavx | host | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=128` | - | 1 | ok | 2.17e-06 | 2e-02 |
+| `attn_dense` | `attn_vit_h72_bf16` | libr4d | device | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=128` | - | 1 | ok | 1.61e-03 | 2e-02 |
+| `attn_dense` | `ref_attn_dense` | libref | host | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_dense` | `avx_attn_dense` | libavx | host | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=256` | - | 1 | ok | 4.86e-06 | 2e-02 |
+| `attn_dense` | `attn_vit_h72_bf16` | libr4d | device | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=256` | - | 1 | ok | 1.56e-03 | 2e-02 |
+| `attn_dense` | `ref_attn_dense` | libref | host | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `attn_dense` | `avx_attn_dense` | libavx | host | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=512` | - | 1 | ok | 7.27e-05 | 2e-02 |
+| `attn_dense` | `attn_vit_h72_bf16` | libr4d | device | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=512` | - | 1 | ok | 1.45e-03 | 2e-02 |
+| `attn_dense` | `ref_attn_dense` | libref | host | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=1152 K=1152 dtype=bf16 act=none M=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=1152 K=1152 dtype=bf16 act=none M=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=1152 K=1152 dtype=bf16 act=none M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=1152 K=1152 dtype=bf16 act=none M=2` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=1152 K=1152 dtype=bf16 act=none M=2` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=1152 K=1152 dtype=bf16 act=none M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=1152 K=1152 dtype=bf16 act=none M=4` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=1152 K=1152 dtype=bf16 act=none M=4` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=1152 K=1152 dtype=bf16 act=none M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=1152 K=1152 dtype=bf16 act=none M=8` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=1152 K=1152 dtype=bf16 act=none M=8` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=1152 K=1152 dtype=bf16 act=none M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=1152 K=1152 dtype=bf16 act=none M=16` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=1152 K=1152 dtype=bf16 act=none M=16` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=1152 K=1152 dtype=bf16 act=none M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=1152 K=1152 dtype=bf16 act=none M=32` | - | 1 | ok | 4.96e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=1152 K=1152 dtype=bf16 act=none M=32` | - | 1 | ok | 4.62e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=1152 K=1152 dtype=bf16 act=none M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=1152 K=1152 dtype=bf16 act=none M=64` | - | 1 | ok | 1.40e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=1152 K=1152 dtype=bf16 act=none M=64` | - | 1 | ok | 1.49e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=1152 K=1152 dtype=bf16 act=none M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=1152 K=1152 dtype=bf16 act=none M=128` | - | 1 | ok | 1.84e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=1152 K=1152 dtype=bf16 act=none M=128` | - | 1 | ok | 4.07e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=1152 K=1152 dtype=bf16 act=none M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=1152 K=1152 dtype=bf16 act=none M=256` | - | 1 | ok | 1.83e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=1152 K=1152 dtype=bf16 act=none M=256` | - | 1 | ok | 1.48e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=1152 K=1152 dtype=bf16 act=none M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=1152 K=1152 dtype=bf16 act=none M=512` | - | 1 | ok | 3.03e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=1152 K=1152 dtype=bf16 act=none M=512` | - | 1 | ok | 3.52e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=1152 K=1152 dtype=bf16 act=none M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=1` | - | 1 | ok | 1.71e-04 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=2` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=2` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=4` | - | 1 | ok | 2.46e-06 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=4` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=8` | - | 1 | ok | 4.45e-06 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=8` | - | 1 | ok | 3.49e-06 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=16` | - | 1 | ok | 2.46e-06 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=16` | - | 1 | ok | 1.56e-07 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=32` | - | 1 | ok | 8.50e-06 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=32` | - | 1 | ok | 8.15e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=64` | - | 1 | ok | 4.14e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=64` | - | 1 | ok | 4.34e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=128` | - | 1 | ok | 2.26e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=128` | - | 1 | ok | 2.66e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=256` | - | 1 | ok | 4.17e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=256` | - | 1 | ok | 3.84e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=512` | - | 1 | ok | 3.74e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=512` | - | 1 | ok | 3.75e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=1152 K=4304 dtype=bf16 act=none M=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=1152 K=4304 dtype=bf16 act=none M=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=1152 K=4304 dtype=bf16 act=none M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=1152 K=4304 dtype=bf16 act=none M=2` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=1152 K=4304 dtype=bf16 act=none M=2` | - | 1 | ok | 5.87e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=1152 K=4304 dtype=bf16 act=none M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=1152 K=4304 dtype=bf16 act=none M=4` | - | 1 | ok | 1.27e-04 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=1152 K=4304 dtype=bf16 act=none M=4` | - | 1 | ok | 1.32e-04 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=1152 K=4304 dtype=bf16 act=none M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=1152 K=4304 dtype=bf16 act=none M=8` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=1152 K=4304 dtype=bf16 act=none M=8` | - | 1 | ok | 5.58e-06 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=1152 K=4304 dtype=bf16 act=none M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=1152 K=4304 dtype=bf16 act=none M=16` | - | 1 | ok | 5.71e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=1152 K=4304 dtype=bf16 act=none M=16` | - | 1 | ok | 7.96e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=1152 K=4304 dtype=bf16 act=none M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=1152 K=4304 dtype=bf16 act=none M=32` | - | 1 | ok | 6.39e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=1152 K=4304 dtype=bf16 act=none M=32` | - | 1 | ok | 2.97e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=1152 K=4304 dtype=bf16 act=none M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=1152 K=4304 dtype=bf16 act=none M=64` | - | 1 | ok | 3.79e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=1152 K=4304 dtype=bf16 act=none M=64` | - | 1 | ok | 8.73e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=1152 K=4304 dtype=bf16 act=none M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=1152 K=4304 dtype=bf16 act=none M=128` | - | 1 | ok | 4.64e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=1152 K=4304 dtype=bf16 act=none M=128` | - | 1 | ok | 5.17e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=1152 K=4304 dtype=bf16 act=none M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=1152 K=4304 dtype=bf16 act=none M=256` | - | 1 | ok | 3.50e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=1152 K=4304 dtype=bf16 act=none M=256` | - | 1 | ok | 5.95e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=1152 K=4304 dtype=bf16 act=none M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=1152 K=4304 dtype=bf16 act=none M=512` | - | 1 | ok | 1.25e-04 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=1152 K=4304 dtype=bf16 act=none M=512` | - | 1 | ok | 5.45e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=1152 K=4304 dtype=bf16 act=none M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=4608 K=4608 dtype=bf16 act=gelu M=1` | - | 1 | ok | 0.00e+00 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=4608 K=4608 dtype=bf16 act=gelu M=1` | - | 1 | ok | 1.19e-06 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=4608 K=4608 dtype=bf16 act=gelu M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=4608 K=4608 dtype=bf16 act=gelu M=2` | - | 1 | ok | 1.72e-04 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=4608 K=4608 dtype=bf16 act=gelu M=2` | - | 1 | ok | 5.46e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=4608 K=4608 dtype=bf16 act=gelu M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=4608 K=4608 dtype=bf16 act=gelu M=4` | - | 1 | ok | 4.74e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=4608 K=4608 dtype=bf16 act=gelu M=4` | - | 1 | ok | 5.44e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=4608 K=4608 dtype=bf16 act=gelu M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=4608 K=4608 dtype=bf16 act=gelu M=8` | - | 1 | ok | 3.99e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=4608 K=4608 dtype=bf16 act=gelu M=8` | - | 1 | ok | 5.42e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=4608 K=4608 dtype=bf16 act=gelu M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=4608 K=4608 dtype=bf16 act=gelu M=16` | - | 1 | ok | 4.94e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=4608 K=4608 dtype=bf16 act=gelu M=16` | - | 1 | ok | 4.78e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=4608 K=4608 dtype=bf16 act=gelu M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=4608 K=4608 dtype=bf16 act=gelu M=32` | - | 1 | ok | 7.35e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=4608 K=4608 dtype=bf16 act=gelu M=32` | - | 1 | ok | 5.98e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=4608 K=4608 dtype=bf16 act=gelu M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=4608 K=4608 dtype=bf16 act=gelu M=64` | - | 1 | ok | 4.99e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=4608 K=4608 dtype=bf16 act=gelu M=64` | - | 1 | ok | 4.52e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=4608 K=4608 dtype=bf16 act=gelu M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=4608 K=4608 dtype=bf16 act=gelu M=128` | - | 1 | ok | 6.17e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=4608 K=4608 dtype=bf16 act=gelu M=128` | - | 1 | ok | 5.56e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=4608 K=4608 dtype=bf16 act=gelu M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=4608 K=4608 dtype=bf16 act=gelu M=256` | - | 1 | ok | 6.50e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=4608 K=4608 dtype=bf16 act=gelu M=256` | - | 1 | ok | 4.42e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=4608 K=4608 dtype=bf16 act=gelu M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=4608 K=4608 dtype=bf16 act=gelu M=512` | - | 1 | ok | 7.39e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=4608 K=4608 dtype=bf16 act=gelu M=512` | - | 1 | ok | 5.50e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=4608 K=4608 dtype=bf16 act=gelu M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=5120 K=4608 dtype=bf16 act=none M=1` | - | 1 | ok | 3.29e-06 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=5120 K=4608 dtype=bf16 act=none M=1` | - | 1 | ok | 3.31e-06 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=5120 K=4608 dtype=bf16 act=none M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=5120 K=4608 dtype=bf16 act=none M=2` | - | 1 | ok | 8.96e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=5120 K=4608 dtype=bf16 act=none M=2` | - | 1 | ok | 8.96e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=5120 K=4608 dtype=bf16 act=none M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=5120 K=4608 dtype=bf16 act=none M=4` | - | 1 | ok | 6.08e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=5120 K=4608 dtype=bf16 act=none M=4` | - | 1 | ok | 4.02e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=5120 K=4608 dtype=bf16 act=none M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=5120 K=4608 dtype=bf16 act=none M=8` | - | 1 | ok | 1.61e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=5120 K=4608 dtype=bf16 act=none M=8` | - | 1 | ok | 1.91e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=5120 K=4608 dtype=bf16 act=none M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=5120 K=4608 dtype=bf16 act=none M=16` | - | 1 | ok | 5.75e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=5120 K=4608 dtype=bf16 act=none M=16` | - | 1 | ok | 5.42e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=5120 K=4608 dtype=bf16 act=none M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=5120 K=4608 dtype=bf16 act=none M=32` | - | 1 | ok | 8.34e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=5120 K=4608 dtype=bf16 act=none M=32` | - | 1 | ok | 8.01e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=5120 K=4608 dtype=bf16 act=none M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=5120 K=4608 dtype=bf16 act=none M=64` | - | 1 | ok | 5.04e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=5120 K=4608 dtype=bf16 act=none M=64` | - | 1 | ok | 6.18e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=5120 K=4608 dtype=bf16 act=none M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=5120 K=4608 dtype=bf16 act=none M=128` | - | 1 | ok | 4.18e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=5120 K=4608 dtype=bf16 act=none M=128` | - | 1 | ok | 6.17e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=5120 K=4608 dtype=bf16 act=none M=128` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=5120 K=4608 dtype=bf16 act=none M=256` | - | 1 | ok | 5.00e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=5120 K=4608 dtype=bf16 act=none M=256` | - | 1 | ok | 5.00e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=5120 K=4608 dtype=bf16 act=none M=256` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | host | `N=5120 K=4608 dtype=bf16 act=none M=512` | - | 1 | ok | 5.78e-05 | 8e-03 |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | device | `N=5120 K=4608 dtype=bf16 act=none M=512` | - | 1 | ok | 6.37e-05 | 8e-03 |
+| `gemm_nt_bias` | `ref_gemm_nt_bias` | libref | host | `N=5120 K=4608 dtype=bf16 act=none M=512` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_penalties` | `avx_sample_penalties` | libavx | host | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_penalties` | `sample_penalties_f32` | libr4d | device | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_penalties` | `ref_sample_penalties` | libref | host | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_penalties` | `avx_sample_penalties` | libavx | host | `n_vocab=248320 M=2` | - | 1 | ok | 7.03e-10 | 1e-06 |
+| `sample_penalties` | `sample_penalties_f32` | libr4d | device | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_penalties` | `ref_sample_penalties` | libref | host | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_penalties` | `avx_sample_penalties` | libavx | host | `n_vocab=248320 M=4` | - | 1 | ok | 5.76e-10 | 1e-06 |
+| `sample_penalties` | `sample_penalties_f32` | libr4d | device | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_penalties` | `ref_sample_penalties` | libref | host | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_penalties` | `avx_sample_penalties` | libavx | host | `n_vocab=248320 M=8` | - | 1 | ok | 5.46e-10 | 1e-06 |
+| `sample_penalties` | `sample_penalties_f32` | libr4d | device | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_penalties` | `ref_sample_penalties` | libref | host | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_penalties` | `avx_sample_penalties` | libavx | host | `n_vocab=248320 M=16` | - | 1 | ok | 6.50e-10 | 1e-06 |
+| `sample_penalties` | `sample_penalties_f32` | libr4d | device | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_penalties` | `ref_sample_penalties` | libref | host | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_penalties` | `avx_sample_penalties` | libavx | host | `n_vocab=248320 M=32` | - | 1 | ok | 3.79e-10 | 1e-06 |
+| `sample_penalties` | `sample_penalties_f32` | libr4d | device | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_penalties` | `ref_sample_penalties` | libref | host | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_penalties` | `avx_sample_penalties` | libavx | host | `n_vocab=248320 M=64` | - | 1 | ok | 4.36e-10 | 1e-06 |
+| `sample_penalties` | `sample_penalties_f32` | libr4d | device | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_penalties` | `ref_sample_penalties` | libref | host | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_dry` | `avx_sample_dry` | libavx | host | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_dry` | `sample_dry_f32` | libr4d | device | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_dry` | `ref_sample_dry` | libref | host | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_dry` | `avx_sample_dry` | libavx | host | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_dry` | `sample_dry_f32` | libr4d | device | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_dry` | `ref_sample_dry` | libref | host | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_dry` | `avx_sample_dry` | libavx | host | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_dry` | `sample_dry_f32` | libr4d | device | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_dry` | `ref_sample_dry` | libref | host | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_dry` | `avx_sample_dry` | libavx | host | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_dry` | `sample_dry_f32` | libr4d | device | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_dry` | `ref_sample_dry` | libref | host | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_dry` | `avx_sample_dry` | libavx | host | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_dry` | `sample_dry_f32` | libr4d | device | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_dry` | `ref_sample_dry` | libref | host | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_dry` | `avx_sample_dry` | libavx | host | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_dry` | `sample_dry_f32` | libr4d | device | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_dry` | `ref_sample_dry` | libref | host | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_dry` | `avx_sample_dry` | libavx | host | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_dry` | `sample_dry_f32` | libr4d | device | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_dry` | `ref_sample_dry` | libref | host | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_temp` | `avx_sample_temp` | libavx | host | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_temp` | `sample_temp_f32` | libr4d | device | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_temp` | `ref_sample_temp` | libref | host | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_temp` | `avx_sample_temp` | libavx | host | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_temp` | `sample_temp_f32` | libr4d | device | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_temp` | `ref_sample_temp` | libref | host | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_temp` | `avx_sample_temp` | libavx | host | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_temp` | `sample_temp_f32` | libr4d | device | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_temp` | `ref_sample_temp` | libref | host | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_temp` | `avx_sample_temp` | libavx | host | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_temp` | `sample_temp_f32` | libr4d | device | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_temp` | `ref_sample_temp` | libref | host | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_temp` | `avx_sample_temp` | libavx | host | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_temp` | `sample_temp_f32` | libr4d | device | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_temp` | `ref_sample_temp` | libref | host | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_temp` | `avx_sample_temp` | libavx | host | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_temp` | `sample_temp_f32` | libr4d | device | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_temp` | `ref_sample_temp` | libref | host | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_temp` | `avx_sample_temp` | libavx | host | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_temp` | `sample_temp_f32` | libr4d | device | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_temp` | `ref_sample_temp` | libref | host | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_mask` | `avx_sample_mask` | libavx | host | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_mask` | `sample_mask_f32` | libr4d | device | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_mask` | `ref_sample_mask` | libref | host | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_mask` | `avx_sample_mask` | libavx | host | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_mask` | `sample_mask_f32` | libr4d | device | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_mask` | `ref_sample_mask` | libref | host | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_mask` | `avx_sample_mask` | libavx | host | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_mask` | `sample_mask_f32` | libr4d | device | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_mask` | `ref_sample_mask` | libref | host | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_mask` | `avx_sample_mask` | libavx | host | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_mask` | `sample_mask_f32` | libr4d | device | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_mask` | `ref_sample_mask` | libref | host | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_mask` | `avx_sample_mask` | libavx | host | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_mask` | `sample_mask_f32` | libr4d | device | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_mask` | `ref_sample_mask` | libref | host | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_mask` | `avx_sample_mask` | libavx | host | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_mask` | `sample_mask_f32` | libr4d | device | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_mask` | `ref_sample_mask` | libref | host | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_mask` | `avx_sample_mask` | libavx | host | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_mask` | `sample_mask_f32` | libr4d | device | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_mask` | `ref_sample_mask` | libref | host | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_topk` | `avx_sample_topk` | libavx | host | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topk` | `sample_topk_f32` | libr4d | device | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topk` | `ref_sample_topk` | libref | host | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topk` | `avx_sample_topk` | libavx | host | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topk` | `sample_topk_f32` | libr4d | device | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topk` | `ref_sample_topk` | libref | host | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topk` | `avx_sample_topk` | libavx | host | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topk` | `sample_topk_f32` | libr4d | device | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topk` | `ref_sample_topk` | libref | host | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topk` | `avx_sample_topk` | libavx | host | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topk` | `sample_topk_f32` | libr4d | device | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topk` | `ref_sample_topk` | libref | host | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topk` | `avx_sample_topk` | libavx | host | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topk` | `sample_topk_f32` | libr4d | device | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topk` | `ref_sample_topk` | libref | host | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topk` | `avx_sample_topk` | libavx | host | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topk` | `sample_topk_f32` | libr4d | device | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topk` | `ref_sample_topk` | libref | host | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topk` | `avx_sample_topk` | libavx | host | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topk` | `sample_topk_f32` | libr4d | device | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topk` | `ref_sample_topk` | libref | host | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_argmax` | `avx_sample_argmax` | libavx | host | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_argmax` | `sample_argmax_f32` | libr4d | device | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_argmax` | `ref_sample_argmax` | libref | host | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_argmax` | `avx_sample_argmax` | libavx | host | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_argmax` | `sample_argmax_f32` | libr4d | device | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_argmax` | `ref_sample_argmax` | libref | host | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_argmax` | `avx_sample_argmax` | libavx | host | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_argmax` | `sample_argmax_f32` | libr4d | device | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_argmax` | `ref_sample_argmax` | libref | host | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_argmax` | `avx_sample_argmax` | libavx | host | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_argmax` | `sample_argmax_f32` | libr4d | device | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_argmax` | `ref_sample_argmax` | libref | host | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_argmax` | `avx_sample_argmax` | libavx | host | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_argmax` | `sample_argmax_f32` | libr4d | device | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_argmax` | `ref_sample_argmax` | libref | host | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_argmax` | `avx_sample_argmax` | libavx | host | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_argmax` | `sample_argmax_f32` | libr4d | device | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_argmax` | `ref_sample_argmax` | libref | host | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_argmax` | `avx_sample_argmax` | libavx | host | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_argmax` | `sample_argmax_f32` | libr4d | device | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_argmax` | `ref_sample_argmax` | libref | host | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topp` | `avx_sample_topp` | libavx | host | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topp` | `sample_topp_f32` | libr4d | device | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topp` | `ref_sample_topp` | libref | host | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topp` | `avx_sample_topp` | libavx | host | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topp` | `sample_topp_f32` | libr4d | device | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topp` | `ref_sample_topp` | libref | host | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topp` | `avx_sample_topp` | libavx | host | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topp` | `sample_topp_f32` | libr4d | device | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topp` | `ref_sample_topp` | libref | host | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topp` | `avx_sample_topp` | libavx | host | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topp` | `sample_topp_f32` | libr4d | device | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topp` | `ref_sample_topp` | libref | host | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topp` | `avx_sample_topp` | libavx | host | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topp` | `sample_topp_f32` | libr4d | device | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topp` | `ref_sample_topp` | libref | host | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topp` | `avx_sample_topp` | libavx | host | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topp` | `sample_topp_f32` | libr4d | device | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topp` | `ref_sample_topp` | libref | host | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topp` | `avx_sample_topp` | libavx | host | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topp` | `sample_topp_f32` | libr4d | device | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_topp` | `ref_sample_topp` | libref | host | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_minp` | `avx_sample_minp` | libavx | host | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_minp` | `sample_minp_f32` | libr4d | device | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_minp` | `ref_sample_minp` | libref | host | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_minp` | `avx_sample_minp` | libavx | host | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_minp` | `sample_minp_f32` | libr4d | device | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_minp` | `ref_sample_minp` | libref | host | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_minp` | `avx_sample_minp` | libavx | host | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_minp` | `sample_minp_f32` | libr4d | device | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_minp` | `ref_sample_minp` | libref | host | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_minp` | `avx_sample_minp` | libavx | host | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_minp` | `sample_minp_f32` | libr4d | device | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_minp` | `ref_sample_minp` | libref | host | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_minp` | `avx_sample_minp` | libavx | host | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_minp` | `sample_minp_f32` | libr4d | device | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_minp` | `ref_sample_minp` | libref | host | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_minp` | `avx_sample_minp` | libavx | host | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_minp` | `sample_minp_f32` | libr4d | device | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_minp` | `ref_sample_minp` | libref | host | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_minp` | `avx_sample_minp` | libavx | host | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_minp` | `sample_minp_f32` | libr4d | device | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_minp` | `ref_sample_minp` | libref | host | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_typical` | `avx_sample_typical` | libavx | host | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_typical` | `sample_typical_f32` | libr4d | device | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_typical` | `ref_sample_typical` | libref | host | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_typical` | `avx_sample_typical` | libavx | host | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_typical` | `sample_typical_f32` | libr4d | device | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_typical` | `ref_sample_typical` | libref | host | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_typical` | `avx_sample_typical` | libavx | host | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_typical` | `sample_typical_f32` | libr4d | device | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_typical` | `ref_sample_typical` | libref | host | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_typical` | `avx_sample_typical` | libavx | host | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_typical` | `sample_typical_f32` | libr4d | device | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_typical` | `ref_sample_typical` | libref | host | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_typical` | `avx_sample_typical` | libavx | host | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_typical` | `sample_typical_f32` | libr4d | device | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_typical` | `ref_sample_typical` | libref | host | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_typical` | `avx_sample_typical` | libavx | host | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_typical` | `sample_typical_f32` | libr4d | device | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_typical` | `ref_sample_typical` | libref | host | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_typical` | `avx_sample_typical` | libavx | host | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_typical` | `sample_typical_f32` | libr4d | device | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_typical` | `ref_sample_typical` | libref | host | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_xtc` | `avx_sample_xtc` | libavx | host | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_xtc` | `sample_xtc_f32` | libr4d | device | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_xtc` | `ref_sample_xtc` | libref | host | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_xtc` | `avx_sample_xtc` | libavx | host | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_xtc` | `sample_xtc_f32` | libr4d | device | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_xtc` | `ref_sample_xtc` | libref | host | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_xtc` | `avx_sample_xtc` | libavx | host | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_xtc` | `sample_xtc_f32` | libr4d | device | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_xtc` | `ref_sample_xtc` | libref | host | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_xtc` | `avx_sample_xtc` | libavx | host | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_xtc` | `sample_xtc_f32` | libr4d | device | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_xtc` | `ref_sample_xtc` | libref | host | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_xtc` | `avx_sample_xtc` | libavx | host | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_xtc` | `sample_xtc_f32` | libr4d | device | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_xtc` | `ref_sample_xtc` | libref | host | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_xtc` | `avx_sample_xtc` | libavx | host | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_xtc` | `sample_xtc_f32` | libr4d | device | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_xtc` | `ref_sample_xtc` | libref | host | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_xtc` | `avx_sample_xtc` | libavx | host | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_xtc` | `sample_xtc_f32` | libr4d | device | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_xtc` | `ref_sample_xtc` | libref | host | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_pick` | `avx_sample_pick` | libavx | host | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_pick` | `sample_pick_f32` | libr4d | device | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_pick` | `ref_sample_pick` | libref | host | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_pick` | `avx_sample_pick` | libavx | host | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_pick` | `sample_pick_f32` | libr4d | device | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_pick` | `ref_sample_pick` | libref | host | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_pick` | `avx_sample_pick` | libavx | host | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_pick` | `sample_pick_f32` | libr4d | device | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_pick` | `ref_sample_pick` | libref | host | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_pick` | `avx_sample_pick` | libavx | host | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_pick` | `sample_pick_f32` | libr4d | device | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_pick` | `ref_sample_pick` | libref | host | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_pick` | `avx_sample_pick` | libavx | host | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_pick` | `sample_pick_f32` | libr4d | device | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_pick` | `ref_sample_pick` | libref | host | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_pick` | `avx_sample_pick` | libavx | host | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_pick` | `sample_pick_f32` | libr4d | device | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_pick` | `ref_sample_pick` | libref | host | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_pick` | `avx_sample_pick` | libavx | host | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_pick` | `sample_pick_f32` | libr4d | device | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_pick` | `ref_sample_pick` | libref | host | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_temp` | `avx_sample_temp` | libavx | host | `n_vocab=1024 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_temp` | `sample_temp_f32` | libr4d | device | `n_vocab=1024 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_temp` | `ref_sample_temp` | libref | host | `n_vocab=1024 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_temp` | `avx_sample_temp` | libavx | host | `n_vocab=1024 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_temp` | `sample_temp_f32` | libr4d | device | `n_vocab=1024 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_temp` | `ref_sample_temp` | libref | host | `n_vocab=1024 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_temp` | `avx_sample_temp` | libavx | host | `n_vocab=1024 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_temp` | `sample_temp_f32` | libr4d | device | `n_vocab=1024 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_temp` | `ref_sample_temp` | libref | host | `n_vocab=1024 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_temp` | `avx_sample_temp` | libavx | host | `n_vocab=1024 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_temp` | `sample_temp_f32` | libr4d | device | `n_vocab=1024 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_temp` | `ref_sample_temp` | libref | host | `n_vocab=1024 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_temp` | `avx_sample_temp` | libavx | host | `n_vocab=1024 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_temp` | `sample_temp_f32` | libr4d | device | `n_vocab=1024 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_temp` | `ref_sample_temp` | libref | host | `n_vocab=1024 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_temp` | `avx_sample_temp` | libavx | host | `n_vocab=1024 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_temp` | `sample_temp_f32` | libr4d | device | `n_vocab=1024 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_temp` | `ref_sample_temp` | libref | host | `n_vocab=1024 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_temp` | `avx_sample_temp` | libavx | host | `n_vocab=1024 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_temp` | `sample_temp_f32` | libr4d | device | `n_vocab=1024 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 |
+| `sample_temp` | `ref_sample_temp` | libref | host | `n_vocab=1024 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_logprobs` | `avx_sample_logprobs` | libavx | host | `n_vocab=248320 k=21 M=1` | - | 1 | ok | 0.00e+00 | 1e-05 |
+| `sample_logprobs` | `sample_logprobs_f32` | libr4d | device | `n_vocab=248320 k=21 M=1` | - | 1 | ok | 0.00e+00 | 1e-05 |
+| `sample_logprobs` | `ref_sample_logprobs` | libref | host | `n_vocab=248320 k=21 M=1` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_logprobs` | `avx_sample_logprobs` | libavx | host | `n_vocab=248320 k=21 M=2` | - | 1 | ok | 8.62e-10 | 1e-05 |
+| `sample_logprobs` | `sample_logprobs_f32` | libr4d | device | `n_vocab=248320 k=21 M=2` | - | 1 | ok | 1.09e-09 | 1e-05 |
+| `sample_logprobs` | `ref_sample_logprobs` | libref | host | `n_vocab=248320 k=21 M=2` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_logprobs` | `avx_sample_logprobs` | libavx | host | `n_vocab=248320 k=21 M=4` | - | 1 | ok | 6.30e-10 | 1e-05 |
+| `sample_logprobs` | `sample_logprobs_f32` | libr4d | device | `n_vocab=248320 k=21 M=4` | - | 1 | ok | 2.72e-10 | 1e-05 |
+| `sample_logprobs` | `ref_sample_logprobs` | libref | host | `n_vocab=248320 k=21 M=4` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_logprobs` | `avx_sample_logprobs` | libavx | host | `n_vocab=248320 k=21 M=8` | - | 1 | ok | 9.99e-10 | 1e-05 |
+| `sample_logprobs` | `sample_logprobs_f32` | libr4d | device | `n_vocab=248320 k=21 M=8` | - | 1 | ok | 5.27e-10 | 1e-05 |
+| `sample_logprobs` | `ref_sample_logprobs` | libref | host | `n_vocab=248320 k=21 M=8` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_logprobs` | `avx_sample_logprobs` | libavx | host | `n_vocab=248320 k=21 M=16` | - | 1 | ok | 6.26e-10 | 1e-05 |
+| `sample_logprobs` | `sample_logprobs_f32` | libr4d | device | `n_vocab=248320 k=21 M=16` | - | 1 | ok | 5.67e-10 | 1e-05 |
+| `sample_logprobs` | `ref_sample_logprobs` | libref | host | `n_vocab=248320 k=21 M=16` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_logprobs` | `avx_sample_logprobs` | libavx | host | `n_vocab=248320 k=21 M=32` | - | 1 | ok | 1.06e-09 | 1e-05 |
+| `sample_logprobs` | `sample_logprobs_f32` | libr4d | device | `n_vocab=248320 k=21 M=32` | - | 1 | ok | 6.50e-10 | 1e-05 |
+| `sample_logprobs` | `ref_sample_logprobs` | libref | host | `n_vocab=248320 k=21 M=32` | - | 1 | ok | 0.00e+00 | 0e+00 |
+| `sample_logprobs` | `avx_sample_logprobs` | libavx | host | `n_vocab=248320 k=21 M=64` | - | 1 | ok | 1.21e-09 | 1e-05 |
+| `sample_logprobs` | `sample_logprobs_f32` | libr4d | device | `n_vocab=248320 k=21 M=64` | - | 1 | ok | 7.06e-10 | 1e-05 |
+| `sample_logprobs` | `ref_sample_logprobs` | libref | host | `n_vocab=248320 k=21 M=64` | - | 1 | ok | 0.00e+00 | 0e+00 |
 
 ## Speed
 
-> **These times rank kernels; they do not size a roofline.** Every launch in a timed
-> run reuses one set of operands, so a weight that fits in the last-level cache is
-> read from cache after the first launch, and a bandwidth-bound kernel can read
-> several times its true rate. Ranking two kernels at one shape is what these times are
-> for; a roofline is not.
->
-> `operands` is the total the case ALLOCATED, not what the kernel read: a gather
-> touches M rows of a table, not the table. Dividing the two columns produces a
-> bandwidth figure this tool cannot stand behind, which is why it does not print one.
->
-> The `libref` column is ONE untimed-warmup call, not a median of reps: it is there to
-> show the order of magnitude a reference implementation costs, which is the reason the
-> device kernels exist. It is not a measurement of a library anyone tunes.
->
-> `spread` is how far the fastest and slowest timed rep were apart, as a percent of
-> the median. Each case is warmed with untimed launches first, because these cards sit in
-> a low-power state whenever nothing is running and the ramp back up is longer than a
-> short timed window -- but a warm-up is not a guarantee, and a wide spread is what marks
-> a number the card was still ramping through. Read a row with a large one as an order of
-> magnitude, not a measurement.
+How the times were taken (`--bench`, tools/kbench_timer.h):
 
-| op | kernel | library | geometry | us | spread | libref us | x | operands |
-|---|---|---|---|---|---|---|---|---|
-| `logits_gemm` | `logits_gemm_fp8` | libr4d | `n_vocab=248320 n_embd=5120 dtype=bf16 M=64` | 3712.35 | 0% | - | - | 2.43 GiB |
-| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=512` | 2804.57 | 0% | - | - | 1.52 GiB |
-| `logits_gemm` | `logits_gemm_fp8` | libr4d | `n_vocab=248320 n_embd=5120 dtype=bf16 M=32` | 2475.88 | 0% | - | - | 2.40 GiB |
-| `logits_gemm` | `logits_gemm_fp8` | libr4d | `n_vocab=248320 n_embd=5120 dtype=bf16 M=16` | 2142.16 | 0% | - | - | 2.38 GiB |
-| `logits_gemm` | `logits_gemm_fp8` | libr4d | `n_vocab=248320 n_embd=5120 dtype=bf16 M=8` | 2114.68 | 0% | - | - | 2.38 GiB |
-| `logits_gemm` | `logits_gemm_fp8` | libr4d | `n_vocab=248320 n_embd=5120 dtype=bf16 M=4` | 2092.86 | 0% | - | - | 2.37 GiB |
-| `logits_gemm` | `logits_gemm_fp8` | libr4d | `n_vocab=248320 n_embd=5120 dtype=bf16 M=2` | 2075.97 | 0% | - | - | 2.37 GiB |
-| `logits_gemm` | `logits_gemm_fp8` | libr4d | `n_vocab=248320 n_embd=5120 dtype=bf16 M=1` | 2038.46 | 0% | - | - | 2.37 GiB |
-| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=256` | 1406.26 | 0% | - | - | 779.05 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=512` | 1358.00 | 1% | - | - | 206.60 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=260` | 1031.50 | 0% | - | - | 188.60 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=25600 group=128 dtype=fp8a8 M=512` | 1002.50 | 1% | - | - | 142.91 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=25600 group=128 dtype=fp8a8 M=260` | 887.98 | 3% | - | - | 134.10 MiB |
-| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=128` | 706.45 | 0% | - | - | 389.52 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=512` | 679.02 | 0% | - | - | 98.78 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=130` | 675.48 | 1% | - | - | 179.31 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=512` | 643.75 | 0% | - | - | 98.59 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=260` | 602.97 | 0% | - | - | 92.00 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=25600 group=128 dtype=fp8a8 M=130` | 587.22 | 1% | - | - | 129.56 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=260` | 507.22 | 1% | - | - | 89.44 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=512` | 473.86 | 0% | - | - | 74.59 MiB |
-| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 conv_width=4 q_len=512` | 456.53 | 0% | - | - | 30.12 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=25600 group=128 dtype=fp8a8 M=65` | 416.22 | 0% | - | - | 127.29 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=130` | 391.21 | 3% | - | - | 88.51 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=65` | 386.91 | 1% | - | - | 174.66 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=260` | 361.39 | 0% | - | - | 67.41 MiB |
-| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=64` | 353.11 | 0% | - | - | 194.76 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=130` | 334.85 | 1% | - | - | 84.73 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=64` | 322.94 | 2% | - | - | 174.59 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=36` | 319.42 | 0% | - | - | 172.59 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=18` | 304.22 | 0% | - | - | 171.31 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=9` | 303.48 | 0% | - | - | 170.66 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=8` | 302.87 | 0% | - | - | 170.59 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=4` | 299.38 | 0% | - | - | 170.31 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=2` | 297.78 | 0% | - | - | 170.16 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=1` | 296.97 | 0% | - | - | 170.09 MiB |
-| `sample_topk` | `sample_topk_f32` | libr4d | `n_vocab=248320 M=64` | 296.07 | 0% | - | - | 60.69 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=65` | 281.73 | 0% | - | - | 86.76 MiB |
-| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=512` | 265.83 | 2% | - | - | 14.00 MiB |
-| `sample_topk` | `sample_topk_f32` | libr4d | `n_vocab=248320 M=32` | 253.05 | 0% | - | - | 30.35 MiB |
-| `sample_topk` | `sample_topk_f32` | libr4d | `n_vocab=248320 M=16` | 252.63 | 0% | - | - | 15.17 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=25600 group=128 dtype=fp8a8 M=64` | 240.22 | 0% | - | - | 127.25 MiB |
-| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=272` | 236.02 | 0% | - | - | 7.44 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=130` | 229.21 | 2% | - | - | 63.71 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=512` | 221.47 | 0% | - | - | 38.10 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=25600 group=128 dtype=fp8a8 M=36` | 219.95 | 0% | - | - | 126.27 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=25600 group=128 dtype=fp8a8 M=18` | 219.81 | 0% | - | - | 125.64 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=25600 group=128 dtype=fp8a8 M=9` | 213.95 | 0% | - | - | 125.33 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=25600 group=128 dtype=fp8a8 M=8` | 213.66 | 0% | - | - | 125.29 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=25600 group=128 dtype=fp8a8 M=4` | 213.24 | 0% | - | - | 125.16 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=25600 group=128 dtype=fp8a8 M=2` | 212.55 | 0% | - | - | 125.09 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=25600 group=128 dtype=fp8a8 M=1` | 212.21 | 0% | - | - | 125.05 MiB |
-| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=136` | 211.11 | 1% | - | - | 3.75 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=65` | 209.33 | 0% | - | - | 82.37 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=260` | 206.42 | 1% | - | - | 34.11 MiB |
-| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=68` | 195.89 | 8% | - | - | 1.91 MiB |
-| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=34` | 195.70 | 2% | - | - | 1008.02 KiB |
-| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=11` | 195.68 | 1% | - | - | 328.01 KiB |
-| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=16` | 195.59 | 4% | - | - | 448.01 KiB |
-| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=17` | 195.42 | 4% | - | - | 536.01 KiB |
-| `sample_topk` | `sample_topk_f32` | libr4d | `n_vocab=248320 M=1` | 189.89 | 0% | - | - | 971.09 KiB |
-| `sample_topk` | `sample_topk_f32` | libr4d | `n_vocab=248320 M=8` | 189.73 | 0% | - | - | 7.59 MiB |
-| `sample_topk` | `sample_topk_f32` | libr4d | `n_vocab=248320 M=4` | 187.49 | 0% | - | - | 3.79 MiB |
-| `sample_topk` | `sample_topk_f32` | libr4d | `n_vocab=248320 M=2` | 186.34 | 0% | - | - | 1.90 MiB |
-| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 conv_width=4 q_len=256` | 176.56 | 0% | - | - | 15.12 MiB |
-| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=32` | 175.39 | 0% | - | - | 97.38 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=64` | 169.57 | 0% | - | - | 86.73 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=36` | 151.93 | 0% | - | - | 85.98 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=64` | 150.40 | 1% | - | - | 82.33 MiB |
-| `row_topk` | `rowtopk_bf16` | libr4d | `N=248320 R=16 dtype=bf16 M=56 nch=0 pt1=8` | 148.94 | 1% | - | - | 26.54 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=18` | 148.54 | 0% | - | - | 85.49 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=9` | 145.17 | 0% | - | - | 85.25 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=8` | 145.02 | 0% | - | - | 85.23 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=36` | 142.37 | 0% | - | - | 81.32 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=4` | 142.36 | 0% | - | - | 85.12 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=2` | 139.57 | 0% | - | - | 85.06 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=1` | 139.26 | 0% | - | - | 85.04 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=18` | 134.58 | 1% | - | - | 80.66 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=130` | 134.57 | 4% | - | - | 32.06 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=9` | 132.75 | 0% | - | - | 80.34 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=8` | 132.71 | 1% | - | - | 80.30 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=4` | 130.76 | 0% | - | - | 80.15 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=2` | 130.05 | 0% | - | - | 80.08 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=1` | 129.22 | 1% | - | - | 80.05 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=65` | 118.06 | 0% | - | - | 61.86 MiB |
-| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | `head_k=128 head_v=128 scale=0.0883883 M=512 chunk=64` | 105.41 | 0% | - | - | 25.19 MiB |
-| `sample_pick` | `sample_pick_f32` | libr4d | `n_cand=1024 M=64` | 102.31 | 0% | - | - | 518.25 KiB |
-| `sample_pick` | `sample_pick_f32` | libr4d | `n_cand=1024 M=16` | 101.77 | 0% | - | - | 129.56 KiB |
-| `row_topk` | `rowtopk_bf16` | libr4d | `N=248320 R=16 dtype=bf16 M=32 nch=0 pt1=8` | 101.14 | 0% | - | - | 15.16 MiB |
-| `sample_pick` | `sample_pick_f32` | libr4d | `n_cand=1024 M=8` | 101.04 | 0% | - | - | 64.78 KiB |
-| `sample_pick` | `sample_pick_f32` | libr4d | `n_cand=1024 M=1` | 98.74 | 0% | - | - | 8.10 KiB |
-| `sample_pick` | `sample_pick_f32` | libr4d | `n_cand=1024 M=32` | 96.05 | 0% | - | - | 259.12 KiB |
-| `sample_pick` | `sample_pick_f32` | libr4d | `n_cand=1024 M=4` | 95.44 | 0% | - | - | 32.39 KiB |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=65` | 94.74 | 0% | - | - | 31.03 MiB |
-| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 conv_width=4 q_len=128` | 86.13 | 0% | - | - | 7.62 MiB |
-| `sample_typical` | `sample_typical_f32` | libr4d | `n_cand=1024 M=32` | 77.72 | 0% | - | - | 259.00 KiB |
-| `sample_typical` | `sample_typical_f32` | libr4d | `n_cand=1024 M=2` | 74.34 | 0% | - | - | 16.19 KiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=64` | 70.24 | 2% | - | - | 61.83 MiB |
-| `row_topk` | `rowtopk_bf16` | libr4d | `N=248320 R=16 dtype=bf16 M=16 nch=0 pt1=8` | 69.07 | 20% | - | - | 7.58 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=260` | 68.43 | 1% | - | - | 6.82 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=130` | 65.02 | 0% | - | - | 5.91 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=65` | 62.33 | 0% | - | - | 5.45 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=36` | 61.12 | 2% | - | - | 61.03 MiB |
-| `sample_pick` | `sample_pick_f32` | libr4d | `n_cand=1024 M=2` | 60.10 | 0% | - | - | 16.20 KiB |
-| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=16` | 59.40 | 1% | - | - | 48.69 MiB |
-| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | `head_k=128 head_v=128 scale=0.0883883 M=256 chunk=64` | 57.93 | 1% | - | - | 15.59 MiB |
-| `row_topk` | `rowtopk_bf16` | libr4d | `N=248320 R=16 dtype=bf16 M=8 nch=0 pt1=8` | 54.04 | 0% | - | - | 3.79 MiB |
-| `sample_typical` | `sample_typical_f32` | libr4d | `n_cand=1024 M=64` | 53.11 | 0% | - | - | 518.00 KiB |
-| `sample_typical` | `sample_typical_f32` | libr4d | `n_cand=1024 M=16` | 50.60 | 0% | - | - | 129.50 KiB |
-| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=512` | 49.01 | 0% | - | - | 8.58 MiB |
-| `sample_topp` | `sample_topp_f32` | libr4d | `n_cand=1024 M=32` | 47.65 | 0% | - | - | 259.00 KiB |
-| `row_topk` | `rowtopk_bf16` | libr4d | `N=248320 R=16 dtype=bf16 M=4 nch=0 pt1=8` | 46.87 | 0% | - | - | 1.90 MiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=25600 group=128 dtype=bf16 M=512` | 46.44 | 2% | - | - | 37.89 MiB |
-| `row_topk` | `rowtopk_bf16` | libr4d | `N=248320 R=16 dtype=bf16 M=1 nch=0 pt1=8` | 46.33 | 0% | - | - | 485.25 KiB |
-| `sample_argmax` | `sample_argmax_f32` | libr4d | `n_vocab=248320 M=64` | 46.00 | 1% | - | - | 60.63 MiB |
-| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 conv_width=4 q_len=64` | 45.64 | 0% | - | - | 3.87 MiB |
-| `row_topk` | `rowtopk_bf16` | libr4d | `N=248320 R=16 dtype=bf16 M=2 nch=0 pt1=8` | 45.49 | 0% | - | - | 970.50 KiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=64` | 44.85 | 1% | - | - | 31.02 MiB |
-| `sample_topp` | `sample_topp_f32` | libr4d | `n_cand=1024 M=1` | 44.54 | 0% | - | - | 8.09 KiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=18` | 44.18 | 0% | - | - | 60.52 MiB |
-| `sample_topp` | `sample_topp_f32` | libr4d | `n_cand=1024 M=64` | 43.76 | 0% | - | - | 518.00 KiB |
-| `sample_topp` | `sample_topp_f32` | libr4d | `n_cand=1024 M=4` | 43.46 | 0% | - | - | 32.38 KiB |
-| `sample_topp` | `sample_topp_f32` | libr4d | `n_cand=1024 M=8` | 42.74 | 0% | - | - | 64.75 KiB |
-| `sample_topp` | `sample_topp_f32` | libr4d | `n_cand=1024 M=16` | 42.67 | 0% | - | - | 129.50 KiB |
-| `sample_temp` | `sample_temp_f32` | libr4d | `n_vocab=248320 M=64` | 42.62 | 0% | - | - | 60.63 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=8` | 41.39 | 0% | - | - | 60.24 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=9` | 41.36 | 1% | - | - | 60.26 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=4` | 40.72 | 1% | - | - | 60.12 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=2` | 40.67 | 1% | - | - | 60.06 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=1` | 40.47 | 1% | - | - | 60.04 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=36` | 39.60 | 1% | - | - | 30.57 MiB |
-| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 chunk=64 conv_width=4 M=512` | 36.38 | 1% | - | - | 20.42 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=4096 K=5120 group=128 dtype=fp8a8 M=64` | 36.37 | 1% | - | - | 20.82 MiB |
-| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | `head_k=128 head_v=128 scale=0.0883883 M=128 chunk=64` | 33.63 | 0% | - | - | 10.80 MiB |
-| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=8` | 33.08 | 0% | - | - | 24.35 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=4096 group=128 dtype=fp8a8 M=64` | 32.38 | 0% | - | - | 20.89 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=4096 K=5120 group=128 dtype=fp8a8 M=36` | 32.33 | 0% | - | - | 20.46 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=18` | 31.25 | 1% | - | - | 30.29 MiB |
-| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 chunk=64 conv_width=4 M=256` | 30.91 | 0% | - | - | 10.28 MiB |
-| `sample_typical` | `sample_typical_f32` | libr4d | `n_cand=1024 M=8` | 30.55 | 0% | - | - | 64.75 KiB |
-| `sample_typical` | `sample_typical_f32` | libr4d | `n_cand=1024 M=4` | 30.19 | 0% | - | - | 32.38 KiB |
-| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 chunk=64 conv_width=4 M=64` | 29.90 | 0% | - | - | 2.67 MiB |
-| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 chunk=64 conv_width=4 M=128` | 29.84 | 0% | - | - | 5.21 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=9` | 28.58 | 0% | - | - | 30.15 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=8` | 28.40 | 2% | - | - | 30.13 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=4096 group=128 dtype=fp8a8 M=36` | 28.35 | 0% | - | - | 20.50 MiB |
-| `sample_temp` | `sample_temp_f32` | libr4d | `n_vocab=248320 M=32` | 28.20 | 1% | - | - | 30.32 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=4` | 28.06 | 1% | - | - | 30.07 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=1` | 27.86 | 1% | - | - | 30.02 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=2` | 27.73 | 1% | - | - | 30.04 MiB |
-| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=96 K=5120 dtype=bf16 M=512 wv=1 sk=0 mb=0 npw=1 nt=1` | 26.76 | 1% | - | - | 6.03 MiB |
-| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=1280 K=5120 dtype=bf16 M=64 wv=1 sk=0 mb=0 npw=1 nt=1` | 25.80 | 0% | - | - | 13.28 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=4096 K=5120 group=128 dtype=fp8a8 M=18` | 25.64 | 1% | - | - | 20.23 MiB |
-| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 conv_width=4 q_len=32` | 25.56 | 3% | - | - | 1.99 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=64` | 25.28 | 0% | - | - | 5.45 MiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=25600 group=128 dtype=bf16 M=256` | 25.08 | 0% | - | - | 18.95 MiB |
-| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=4` | 24.56 | 2% | - | - | 12.17 MiB |
-| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=10 splits=0` | 24.10 | 5% | - | - | 304.01 KiB |
-| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=9 splits=0` | 23.29 | 2% | - | - | 280.01 KiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=4096 K=5120 group=128 dtype=fp8a8 M=8` | 23.22 | 1% | - | - | 20.11 MiB |
-| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=8 splits=0` | 23.15 | 2% | - | - | 256.01 KiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=4096 K=5120 group=128 dtype=fp8a8 M=9` | 23.10 | 1% | - | - | 20.12 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=4096 K=5120 group=128 dtype=fp8a8 M=4` | 23.03 | 0% | - | - | 20.05 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=4096 K=5120 group=128 dtype=fp8a8 M=2` | 22.86 | 1% | - | - | 20.03 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=4096 K=5120 group=128 dtype=fp8a8 M=1` | 22.82 | 1% | - | - | 20.02 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=4096 group=128 dtype=fp8a8 M=18` | 22.59 | 0% | - | - | 20.25 MiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=512` | 22.47 | 0% | - | - | 10.01 MiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=512` | 22.45 | 1% | - | - | 10.01 MiB |
-| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | `head_k=128 head_v=128 scale=0.0883883 M=64 chunk=64` | 21.74 | 0% | - | - | 8.40 MiB |
-| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=6 splits=0` | 21.38 | 5% | - | - | 208.01 KiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=36` | 21.02 | 0% | - | - | 5.25 MiB |
-| `sample_argmax` | `sample_argmax_f32` | libr4d | `n_vocab=248320 M=32` | 20.89 | 0% | - | - | 30.32 MiB |
-| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=2 splits=0` | 20.84 | 3% | - | - | 112.01 KiB |
-| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=1 splits=0` | 20.64 | 2% | - | - | 88.01 KiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=4096 group=128 dtype=fp8a8 M=8` | 20.18 | 0% | - | - | 20.11 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=4096 group=128 dtype=fp8a8 M=9` | 20.17 | 0% | - | - | 20.13 MiB |
-| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 chunk=64 conv_width=4 M=32` | 19.78 | 0% | - | - | 1.40 MiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=6144 group=128 dtype=bf16 M=512` | 19.67 | 1% | - | - | 9.09 MiB |
-| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | `head_k=128 head_v=128 scale=0.0883883 M=32 chunk=64` | 19.63 | 1% | - | - | 7.20 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=4096 group=128 dtype=fp8a8 M=1` | 19.41 | 1% | - | - | 20.02 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=4096 group=128 dtype=fp8a8 M=2` | 19.38 | 1% | - | - | 20.03 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=4096 group=128 dtype=fp8a8 M=4` | 19.35 | 0% | - | - | 20.06 MiB |
-| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=1280 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | 19.20 | 83% | - | - | 12.92 MiB |
-| `add` | `add_bf16` | libr4d | `n=5120 dtype=bf16 M=512` | 19.17 | 0% | - | - | 15.00 MiB |
-| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=5 splits=0` | 18.91 | 3% | - | - | 184.01 KiB |
-| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=4 splits=0` | 18.52 | 4% | - | - | 160.01 KiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=5120 group=128 dtype=bf16 M=512` | 18.37 | 1% | - | - | 7.58 MiB |
-| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | `head_k=128 head_v=128 scale=0.0883883 M=16 chunk=64` | 18.30 | 0% | - | - | 6.60 MiB |
-| `embed_lookup` | `embed_lookup_bf16` | libr4d | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=512` | 18.28 | 0% | - | - | 2.37 GiB |
-| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | `head_k=128 head_v=128 scale=0.0883883 M=8 chunk=64` | 17.94 | 1% | - | - | 6.30 MiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=25600 group=128 dtype=bf16 M=128` | 17.80 | 0% | - | - | 9.47 MiB |
-| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | `head_k=128 head_v=128 scale=0.0883883 M=4 chunk=64` | 17.70 | 0% | - | - | 6.15 MiB |
-| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | `head_k=128 head_v=128 scale=0.0883883 M=1 chunk=64` | 17.70 | 0% | - | - | 6.04 MiB |
-| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | `head_k=128 head_v=128 scale=0.0883883 M=2 chunk=64` | 17.65 | 1% | - | - | 6.07 MiB |
-| `sample_argmax` | `sample_argmax_f32` | libr4d | `n_vocab=248320 M=16` | 16.60 | 1% | - | - | 15.16 MiB |
-| `sample_argmax` | `sample_argmax_f32` | libr4d | `n_vocab=248320 M=8` | 16.49 | 1% | - | - | 7.58 MiB |
-| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=96 K=5120 dtype=bf16 M=272 wv=1 sk=0 mb=0 npw=1 nt=1` | 16.38 | 1% | - | - | 3.64 MiB |
-| `sample_argmax` | `sample_argmax_f32` | libr4d | `n_vocab=248320 M=4` | 16.33 | 1% | - | - | 3.79 MiB |
-| `sample_argmax` | `sample_argmax_f32` | libr4d | `n_vocab=248320 M=1` | 16.29 | 0% | - | - | 970.10 KiB |
-| `sample_argmax` | `sample_argmax_f32` | libr4d | `n_vocab=248320 M=2` | 16.24 | 0% | - | - | 1.89 MiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=512` | 16.17 | 1% | - | - | 6.00 MiB |
-| `sample_temp` | `sample_temp_f32` | libr4d | `n_vocab=248320 M=2` | 15.54 | 7% | - | - | 1.89 MiB |
-| `attn_paged` | `attn_decode_h128_gqa4_bf16kv` | libr4d | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=8 splits=0` | 15.44 | 6% | - | - | 192.01 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=512` | 15.31 | 0% | - | - | 512.50 KiB |
-| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=2` | 15.19 | 0% | - | - | 6.09 MiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=25600 group=128 dtype=bf16 M=1` | 15.02 | 1% | - | - | 75.78 KiB |
-| `attn_paged` | `attn_decode_h128_gqa4_bf16kv` | libr4d | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=6 splits=0` | 14.99 | 4% | - | - | 160.01 KiB |
-| `attn_paged` | `attn_decode_h128_gqa4_bf16kv` | libr4d | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=5 splits=0` | 14.97 | 2% | - | - | 144.01 KiB |
-| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | `head_k=128 M=512 chunk=64` | 14.96 | 0% | - | - | 5.19 MiB |
-| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 conv_width=4 q_len=16` | 14.90 | 0% | - | - | 1.05 MiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=25600 group=128 dtype=bf16 M=2` | 14.85 | 1% | - | - | 151.56 KiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=25600 group=128 dtype=bf16 M=64` | 14.79 | 0% | - | - | 4.74 MiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=25600 group=128 dtype=bf16 M=4` | 14.67 | 1% | - | - | 303.12 KiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=25600 group=128 dtype=bf16 M=8` | 14.61 | 1% | - | - | 606.25 KiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=25600 group=128 dtype=bf16 M=16` | 14.56 | 0% | - | - | 1.18 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=18` | 14.55 | 0% | - | - | 5.13 MiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=25600 group=128 dtype=bf16 M=32` | 14.52 | 0% | - | - | 2.37 MiB |
-| `sample_temp` | `sample_temp_f32` | libr4d | `n_vocab=248320 M=16` | 14.39 | 0% | - | - | 15.16 MiB |
-| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 chunk=64 conv_width=4 M=16` | 14.35 | 1% | - | - | 789.39 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=256` | 13.95 | 2% | - | - | 5.01 MiB |
-| `sample_temp` | `sample_temp_f32` | libr4d | `n_vocab=248320 M=1` | 13.90 | 0% | - | - | 970.09 KiB |
-| `sample_mask` | `sample_mask_f32` | libr4d | `n_vocab=248320 M=1` | 13.89 | 0% | - | - | 1000.41 KiB |
-| `embed_lookup` | `embed_lookup_bf16` | libr4d | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=256` | 13.89 | 1% | - | - | 2.37 GiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=256` | 13.89 | 0% | - | - | 5.01 MiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=256` | 13.88 | 2% | - | - | 256.50 KiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=6144 group=128 dtype=bf16 M=256` | 13.87 | 1% | - | - | 4.55 MiB |
-| `attn_paged` | `attn_decode_h128_gqa4_bf16kv` | libr4d | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=4 splits=0` | 13.87 | 3% | - | - | 128.01 KiB |
-| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=256` | 13.83 | 0% | - | - | 2.13 MiB |
-| `add` | `add_bf16` | libr4d | `n=5120 dtype=bf16 M=256` | 13.83 | 0% | - | - | 7.50 MiB |
-| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=256` | 13.82 | 0% | - | - | 2.13 MiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=256` | 13.82 | 0% | - | - | 513.00 KiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=32` | 13.82 | 1% | - | - | 256.12 KiB |
-| `attn_paged` | `attn_decode_h128_gqa4_bf16kv` | libr4d | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=2 splits=0` | 13.79 | 8% | - | - | 96.01 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=256` | 13.78 | 0% | - | - | 128.25 KiB |
-| `attn_paged` | `attn_decode_h128_gqa4_bf16kv` | libr4d | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=1 splits=0` | 13.77 | 2% | - | - | 80.01 KiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=128` | 13.77 | 0% | - | - | 256.50 KiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=5120 group=128 dtype=bf16 M=256` | 13.75 | 0% | - | - | 3.79 MiB |
-| `sample_mask` | `sample_mask_f32` | libr4d | `n_vocab=248320 M=64` | 13.56 | 1% | - | - | 62.53 MiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=256` | 13.32 | 6% | - | - | 513.00 KiB |
-| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=1280 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | 13.24 | 1% | - | - | 12.71 MiB |
-| `silu_mul` | `silu_mul_bf16` | libr4d | `n=17408 dtype=bf16 M=64` | 13.20 | 0% | - | - | 6.38 MiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=512` | 13.01 | 11% | - | - | 1.00 MiB |
-| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=1280 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | 12.64 | 1% | - | - | 12.70 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=9` | 12.60 | 0% | - | - | 5.06 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=8` | 12.54 | 1% | - | - | 5.06 MiB |
-| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | `head_k=128 M=256 chunk=64` | 12.52 | 0% | - | - | 2.59 MiB |
-| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=1` | 12.23 | 1% | - | - | 3.04 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=1` | 12.14 | 1% | - | - | 5.01 MiB |
-| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=96 K=5120 dtype=bf16 M=136 wv=1 sk=0 mb=0 npw=1 nt=1` | 12.12 | 2% | - | - | 2.29 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=4` | 12.10 | 0% | - | - | 5.03 MiB |
-| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=2` | 12.01 | 1% | - | - | 5.01 MiB |
-| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=1280 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | 11.95 | 1% | - | - | 12.60 MiB |
-| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=1280 K=5120 dtype=bf16 M=4 wv=1 sk=0 mb=0 npw=1 nt=1` | 11.77 | 0% | - | - | 12.55 MiB |
-| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=1280 K=5120 dtype=bf16 M=1 wv=1 sk=0 mb=0 npw=1 nt=1` | 11.76 | 1% | - | - | 12.51 MiB |
-| `silu_mul` | `silu_mul_bf16` | libr4d | `n=17408 dtype=bf16 M=4` | 11.73 | 1% | - | - | 408.00 KiB |
-| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=1280 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | 11.72 | 0% | - | - | 12.52 MiB |
-| `silu_mul` | `silu_mul_bf16` | libr4d | `n=17408 dtype=bf16 M=32` | 11.68 | 1% | - | - | 3.19 MiB |
-| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | `head_k=128 M=128 chunk=64` | 11.68 | 0% | - | - | 1.30 MiB |
-| `silu_mul` | `silu_mul_bf16` | libr4d | `n=17408 dtype=bf16 M=2` | 11.66 | 1% | - | - | 204.00 KiB |
-| `silu_mul` | `silu_mul_bf16` | libr4d | `n=17408 dtype=bf16 M=8` | 11.62 | 0% | - | - | 816.00 KiB |
-| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 chunk=64 conv_width=4 M=8` | 11.62 | 1% | - | - | 464.89 KiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=64` | 11.62 | 6% | - | - | 512.25 KiB |
-| `silu_mul` | `silu_mul_bf16` | libr4d | `n=17408 dtype=bf16 M=1` | 11.62 | 1% | - | - | 102.00 KiB |
-| `silu_mul` | `silu_mul_bf16` | libr4d | `n=17408 dtype=bf16 M=16` | 11.60 | 1% | - | - | 1.59 MiB |
-| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | `head_k=128 M=64 chunk=64` | 11.30 | 1% | - | - | 664.01 KiB |
-| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=512` | 11.22 | 12% | - | - | 4.13 MiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=17408 group=128 dtype=bf16 M=64` | 11.18 | 1% | - | - | 3.22 MiB |
-| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=512` | 11.18 | 15% | - | - | 4.13 MiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=17408 group=128 dtype=bf16 M=32` | 10.97 | 2% | - | - | 1.61 MiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=17408 group=128 dtype=bf16 M=1` | 10.96 | 2% | - | - | 51.53 KiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=17408 group=128 dtype=bf16 M=8` | 10.95 | 1% | - | - | 412.25 KiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=17408 group=128 dtype=bf16 M=4` | 10.88 | 1% | - | - | 206.12 KiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=17408 group=128 dtype=bf16 M=2` | 10.88 | 2% | - | - | 103.06 KiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=256` | 10.85 | 115% | - | - | 3.00 MiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=17408 group=128 dtype=bf16 M=16` | 10.83 | 1% | - | - | 824.50 KiB |
-| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | `head_k=128 M=32 chunk=64` | 10.66 | 1% | - | - | 332.01 KiB |
-| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 chunk=64 conv_width=4 M=4` | 10.49 | 4% | - | - | 302.64 KiB |
-| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | `head_k=128 M=1 chunk=64` | 10.43 | 2% | - | - | 10.38 KiB |
-| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | `head_k=128 M=4 chunk=64` | 10.43 | 1% | - | - | 41.51 KiB |
-| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | `head_k=128 M=2 chunk=64` | 10.34 | 1% | - | - | 20.76 KiB |
-| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | `head_k=128 M=8 chunk=64` | 10.26 | 3% | - | - | 83.01 KiB |
-| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | `head_k=128 M=16 chunk=64` | 10.14 | 2% | - | - | 166.01 KiB |
-| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=96 K=5120 dtype=bf16 M=68 wv=1 sk=0 mb=0 npw=1 nt=1` | 10.14 | 1% | - | - | 1.61 MiB |
-| `sample_temp` | `sample_temp_f32` | libr4d | `n_vocab=248320 M=8` | 10.00 | 1% | - | - | 7.58 MiB |
-| `sample_dry` | `sample_dry_f32` | libr4d | `n_vocab=248320 M=32` | 9.54 | 3% | - | - | 30.32 MiB |
-| `sample_dry` | `sample_dry_f32` | libr4d | `n_vocab=248320 M=64` | 9.45 | 0% | - | - | 60.65 MiB |
-| `cast` | `cast_bf16_bf16` | libr4d | `n=5120 from=bf16 to=bf16 M=512` | 9.33 | 4% | - | - | 10.00 MiB |
-| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 chunk=64 conv_width=4 M=2` | 9.28 | 2% | - | - | 221.52 KiB |
-| `sample_mask` | `sample_mask_f32` | libr4d | `n_vocab=248320 M=32` | 8.97 | 4% | - | - | 31.26 MiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=128` | 8.78 | 1% | - | - | 2.51 MiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=128` | 8.77 | 4% | - | - | 2.51 MiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=128` | 8.09 | 12% | - | - | 1.50 MiB |
-| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 chunk=64 conv_width=4 M=1` | 7.57 | 0% | - | - | 180.95 KiB |
-| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=256 K=5120 dtype=bf16 M=56 wv=1 sk=0 mb=0 npw=1 nt=1` | 7.47 | 1% | - | - | 3.07 MiB |
-| `sample_penalties` | `sample_penalties_f32` | libr4d | `n_vocab=248320 M=64` | 7.10 | 2% | - | - | 60.65 MiB |
-| `sample_penalties` | `sample_penalties_f32` | libr4d | `n_vocab=248320 M=32` | 7.08 | 1% | - | - | 30.32 MiB |
-| `sample_penalties` | `sample_penalties_f32` | libr4d | `n_vocab=248320 M=16` | 7.06 | 0% | - | - | 15.16 MiB |
-| `sample_penalties` | `sample_penalties_f32` | libr4d | `n_vocab=248320 M=4` | 7.01 | 0% | - | - | 3.79 MiB |
-| `gather_rows` | `gather_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=1` | 6.92 | 1% | - | - | 50.00 KiB |
-| `sample_xtc` | `sample_xtc_f32` | libr4d | `n_cand=1024 M=8` | 6.91 | 2% | - | - | 64.75 KiB |
-| `embed_lookup` | `embed_lookup_bf16` | libr4d | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=2` | 6.81 | 3% | - | - | 2.37 GiB |
-| `sample_xtc` | `sample_xtc_f32` | libr4d | `n_cand=1024 M=32` | 6.73 | 6% | - | - | 259.00 KiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=6144 group=128 dtype=bf16 M=128` | 6.72 | 3% | - | - | 2.27 MiB |
-| `embed_lookup` | `embed_lookup_bf16` | libr4d | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=128` | 6.71 | 1% | - | - | 2.37 GiB |
-| `embed_lookup` | `embed_lookup_bf16` | libr4d | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=4` | 6.67 | 1% | - | - | 2.37 GiB |
-| `embed_lookup` | `embed_lookup_bf16` | libr4d | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=16` | 6.67 | 3% | - | - | 2.37 GiB |
-| `embed_lookup` | `embed_lookup_bf16` | libr4d | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=64` | 6.67 | 0% | - | - | 2.37 GiB |
-| `embed_lookup` | `embed_lookup_bf16` | libr4d | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=8` | 6.67 | 3% | - | - | 2.37 GiB |
-| `embed_lookup` | `embed_lookup_bf16` | libr4d | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=1` | 6.65 | 1% | - | - | 2.37 GiB |
-| `embed_lookup` | `embed_lookup_bf16` | libr4d | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=32` | 6.65 | 1% | - | - | 2.37 GiB |
-| `sample_xtc` | `sample_xtc_f32` | libr4d | `n_cand=1024 M=64` | 6.65 | 1% | - | - | 518.00 KiB |
-| `sample_xtc` | `sample_xtc_f32` | libr4d | `n_cand=1024 M=16` | 6.62 | 0% | - | - | 129.50 KiB |
-| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 conv_width=4 q_len=8` | 6.61 | 5% | - | - | 600.04 KiB |
-| `gather_rows` | `gather_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=2` | 6.59 | 2% | - | - | 100.01 KiB |
-| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=256 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | 6.58 | 1% | - | - | 2.85 MiB |
-| `gather_rows` | `gather_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=56` | 6.52 | 2% | - | - | 2.73 MiB |
-| `gather_rows` | `gather_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=4` | 6.50 | 0% | - | - | 200.02 KiB |
-| `gather_rows` | `gather_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=8` | 6.44 | 0% | - | - | 400.03 KiB |
-| `gather_rows` | `gather_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=16` | 6.41 | 3% | - | - | 800.06 KiB |
-| `sample_temp` | `sample_temp_f32` | libr4d | `n_vocab=248320 M=4` | 6.41 | 2% | - | - | 3.79 MiB |
-| `gather_rows` | `gather_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=64` | 6.39 | 1% | - | - | 3.13 MiB |
-| `gather_rows` | `gather_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=32` | 6.37 | 0% | - | - | 1.56 MiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=6144 group=128 dtype=bf16 M=2` | 6.30 | 2% | - | - | 36.38 KiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=6144 group=128 dtype=bf16 M=1` | 6.23 | 5% | - | - | 18.19 KiB |
-| `sample_mask` | `sample_mask_f32` | libr4d | `n_vocab=248320 M=16` | 6.23 | 7% | - | - | 15.63 MiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=6144 group=128 dtype=bf16 M=4` | 6.12 | 7% | - | - | 72.75 KiB |
-| `sample_topp` | `sample_topp_f32` | libr4d | `n_cand=1024 M=2` | 6.11 | 5% | - | - | 16.19 KiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=6144 group=128 dtype=bf16 M=64` | 6.09 | 5% | - | - | 1.14 MiB |
-| `sample_xtc` | `sample_xtc_f32` | libr4d | `n_cand=1024 M=4` | 6.06 | 5% | - | - | 32.38 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=64` | 6.03 | 4% | - | - | 1.26 MiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=6144 group=128 dtype=bf16 M=16` | 6.01 | 5% | - | - | 291.00 KiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=5120 group=128 dtype=bf16 M=128` | 5.98 | 5% | - | - | 1.89 MiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=6144 group=128 dtype=bf16 M=32` | 5.96 | 5% | - | - | 582.00 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=64` | 5.95 | 9% | - | - | 1.26 MiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=6144 group=128 dtype=bf16 M=8` | 5.93 | 2% | - | - | 145.50 KiB |
-| `sample_minp` | `sample_minp_f32` | libr4d | `n_cand=1024 M=32` | 5.82 | 0% | - | - | 259.00 KiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=5120 group=128 dtype=bf16 M=8` | 5.77 | 5% | - | - | 121.25 KiB |
-| `sample_minp` | `sample_minp_f32` | libr4d | `n_cand=1024 M=64` | 5.75 | 4% | - | - | 518.00 KiB |
-| `sample_xtc` | `sample_xtc_f32` | libr4d | `n_cand=1024 M=1` | 5.74 | 2% | - | - | 8.09 KiB |
-| `sample_xtc` | `sample_xtc_f32` | libr4d | `n_cand=1024 M=2` | 5.74 | 2% | - | - | 16.19 KiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=5120 group=128 dtype=bf16 M=32` | 5.73 | 5% | - | - | 485.00 KiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=5120 group=128 dtype=bf16 M=64` | 5.72 | 6% | - | - | 970.00 KiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=64` | 5.70 | 7% | - | - | 768.25 KiB |
-| `sample_typical` | `sample_typical_f32` | libr4d | `n_cand=1024 M=1` | 5.67 | 1% | - | - | 8.09 KiB |
-| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 conv_width=4 q_len=4` | 5.65 | 6% | - | - | 360.03 KiB |
-| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=256 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | 5.65 | 7% | - | - | 2.66 MiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=512` | 5.65 | 2% | - | - | 1.00 MiB |
-| `add` | `add_bf16` | libr4d | `n=5120 dtype=bf16 M=64` | 5.65 | 5% | - | - | 1.88 MiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=5120 group=128 dtype=bf16 M=2` | 5.64 | 7% | - | - | 30.31 KiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=5120 group=128 dtype=bf16 M=1` | 5.62 | 5% | - | - | 15.16 KiB |
-| `add` | `add_bf16` | libr4d | `n=5120 dtype=bf16 M=128` | 5.61 | 6% | - | - | 3.75 MiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=5120 group=128 dtype=bf16 M=4` | 5.58 | 6% | - | - | 60.62 KiB |
-| `sample_minp` | `sample_minp_f32` | libr4d | `n_cand=1024 M=2` | 5.57 | 5% | - | - | 16.19 KiB |
-| `sample_minp` | `sample_minp_f32` | libr4d | `n_cand=1024 M=8` | 5.55 | 7% | - | - | 64.75 KiB |
-| `add` | `add_bf16` | libr4d | `n=5120 dtype=bf16 M=32` | 5.54 | 4% | - | - | 960.00 KiB |
-| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=256 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | 5.53 | 5% | - | - | 2.67 MiB |
-| `cast` | `cast_bf16_bf16` | libr4d | `n=5120 from=bf16 to=bf16 M=256` | 5.51 | 5% | - | - | 5.00 MiB |
-| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=256 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | 5.47 | 11% | - | - | 2.52 MiB |
-| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=256 K=5120 dtype=bf16 M=1 wv=1 sk=0 mb=0 npw=1 nt=1` | 5.47 | 6% | - | - | 2.51 MiB |
-| `sample_minp` | `sample_minp_f32` | libr4d | `n_cand=1024 M=16` | 5.46 | 2% | - | - | 129.50 KiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=5120 group=128 dtype=bf16 M=16` | 5.45 | 7% | - | - | 242.50 KiB |
-| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=96 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | 5.41 | 10% | - | - | 1.10 MiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=16` | 5.40 | 11% | - | - | 330.00 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=2` | 5.40 | 8% | - | - | 50.00 KiB |
-| `sample_minp` | `sample_minp_f32` | libr4d | `n_cand=1024 M=4` | 5.39 | 6% | - | - | 32.38 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=2` | 5.39 | 10% | - | - | 50.00 KiB |
-| `add` | `add_bf16` | libr4d | `n=5120 dtype=bf16 M=8` | 5.38 | 11% | - | - | 240.00 KiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=4096 group=128 dtype=bf16 M=32` | 5.36 | 4% | - | - | 388.00 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=32` | 5.34 | 8% | - | - | 650.00 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=8` | 5.33 | 10% | - | - | 170.00 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=16` | 5.32 | 0% | - | - | 330.00 KiB |
-| `add` | `add_bf16` | libr4d | `n=5120 dtype=bf16 M=4` | 5.32 | 6% | - | - | 120.00 KiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=4096 group=128 dtype=bf16 M=2` | 5.30 | 8% | - | - | 24.25 KiB |
-| `add` | `add_bf16` | libr4d | `n=5120 dtype=bf16 M=16` | 5.30 | 7% | - | - | 480.00 KiB |
-| `add` | `add_bf16` | libr4d | `n=5120 dtype=bf16 M=1` | 5.30 | 6% | - | - | 30.00 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=1` | 5.27 | 7% | - | - | 30.00 KiB |
-| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=256 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | 5.24 | 6% | - | - | 2.58 MiB |
-| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=256 K=5120 dtype=bf16 M=4 wv=1 sk=0 mb=0 npw=1 nt=1` | 5.24 | 8% | - | - | 2.54 MiB |
-| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 conv_width=4 q_len=1` | 5.22 | 2% | - | - | 180.02 KiB |
-| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=96 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | 5.22 | 7% | - | - | 1.11 MiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=1` | 5.21 | 10% | - | - | 30.00 KiB |
-| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=96 K=5120 dtype=bf16 M=4 wv=1 sk=0 mb=0 npw=1 nt=1` | 5.20 | 4% | - | - | 1000.75 KiB |
-| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=96 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | 5.19 | 7% | - | - | 1.28 MiB |
-| `add` | `add_bf16` | libr4d | `n=5120 dtype=bf16 M=2` | 5.19 | 7% | - | - | 60.00 KiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=4096 group=128 dtype=bf16 M=64` | 5.15 | 8% | - | - | 776.00 KiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=4096 group=128 dtype=bf16 M=16` | 5.14 | 7% | - | - | 194.00 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=4` | 5.14 | 7% | - | - | 90.00 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=8` | 5.13 | 7% | - | - | 170.00 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=32` | 5.12 | 5% | - | - | 650.00 KiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=4096 group=128 dtype=bf16 M=4` | 5.10 | 7% | - | - | 48.50 KiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=4096 group=128 dtype=bf16 M=8` | 5.09 | 4% | - | - | 97.00 KiB |
-| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 conv_width=4 q_len=2` | 5.09 | 8% | - | - | 240.02 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=4` | 5.06 | 3% | - | - | 90.00 KiB |
-| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=4096 group=128 dtype=bf16 M=1` | 4.97 | 3% | - | - | 12.12 KiB |
-| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=96 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | 4.95 | 2% | - | - | 1.02 MiB |
-| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=96 K=5120 dtype=bf16 M=1 wv=1 sk=0 mb=0 npw=1 nt=1` | 4.81 | 4% | - | - | 970.19 KiB |
-| `sample_mask` | `sample_mask_f32` | libr4d | `n_vocab=248320 M=8` | 4.72 | 3% | - | - | 7.82 MiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=16` | 4.67 | 1% | - | - | 128.06 KiB |
-| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=96 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | 4.67 | 0% | - | - | 980.38 KiB |
-| `sample_minp` | `sample_minp_f32` | libr4d | `n_cand=1024 M=1` | 4.67 | 1% | - | - | 8.09 KiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=64` | 4.53 | 2% | - | - | 128.25 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=512` | 4.46 | 2% | - | - | 256.25 KiB |
-| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=128` | 4.30 | 2% | - | - | 1.13 MiB |
-| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=128` | 4.29 | 1% | - | - | 1.13 MiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=32` | 4.29 | 0% | - | - | 384.12 KiB |
-| `cast` | `cast_bf16_bf16` | libr4d | `n=5120 from=bf16 to=bf16 M=128` | 4.27 | 1% | - | - | 2.50 MiB |
-| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=64` | 4.17 | 1% | - | - | 640.25 KiB |
-| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=1` | 4.16 | 2% | - | - | 196.00 KiB |
-| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=1` | 4.15 | 1% | - | - | 196.00 KiB |
-| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=32` | 4.14 | 3% | - | - | 384.12 KiB |
-| `sample_mask` | `sample_mask_f32` | libr4d | `n_vocab=248320 M=4` | 4.12 | 1% | - | - | 3.91 MiB |
-| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=2` | 4.12 | 1% | - | - | 200.01 KiB |
-| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=64` | 4.11 | 4% | - | - | 640.25 KiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=8` | 4.08 | 1% | - | - | 64.03 KiB |
-| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=4` | 4.08 | 2% | - | - | 208.02 KiB |
-| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=2` | 4.06 | 3% | - | - | 200.01 KiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=32` | 4.06 | 1% | - | - | 64.12 KiB |
-| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=32` | 4.06 | 2% | - | - | 384.12 KiB |
-| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=4` | 4.05 | 2% | - | - | 208.02 KiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=128` | 4.05 | 0% | - | - | 256.50 KiB |
-| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=16` | 4.05 | 4% | - | - | 256.06 KiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=16` | 4.03 | 1% | - | - | 192.06 KiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=2` | 4.03 | 4% | - | - | 16.01 KiB |
-| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=8` | 4.03 | 1% | - | - | 224.03 KiB |
-| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=16` | 4.01 | 0% | - | - | 256.06 KiB |
-| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=8` | 4.00 | 4% | - | - | 224.03 KiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=1` | 3.99 | 1% | - | - | 8.00 KiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=4` | 3.98 | 3% | - | - | 32.02 KiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=1` | 3.94 | 0% | - | - | 2.00 KiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=2` | 3.93 | 1% | - | - | 4.01 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=1` | 3.93 | 2% | - | - | 1.50 KiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=4` | 3.93 | 3% | - | - | 8.02 KiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=1` | 3.93 | 1% | - | - | 2.00 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=2` | 3.92 | 6% | - | - | 2.50 KiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=2` | 3.89 | 1% | - | - | 4.01 KiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=8` | 3.89 | 0% | - | - | 96.03 KiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=4` | 3.89 | 1% | - | - | 48.02 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=4` | 3.88 | 6% | - | - | 4.50 KiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=16` | 3.88 | 1% | - | - | 32.06 KiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=64` | 3.88 | 1% | - | - | 128.25 KiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=2` | 3.87 | 1% | - | - | 24.01 KiB |
-| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | `channels=128 eps=1e-06 act=silu M=1` | 3.87 | 1% | - | - | 1.25 KiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=8` | 3.87 | 1% | - | - | 16.03 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=1` | 3.87 | 3% | - | - | 768 B |
-| `cast` | `cast_bf16_bf16` | libr4d | `n=5120 from=bf16 to=bf16 M=64` | 3.86 | 1% | - | - | 1.25 MiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=4` | 3.86 | 1% | - | - | 8.02 KiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=1` | 3.86 | 6% | - | - | 12.00 KiB |
-| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | `channels=128 eps=1e-06 act=silu M=512` | 3.85 | 2% | - | - | 384.50 KiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=16` | 3.85 | 1% | - | - | 32.06 KiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=32` | 3.84 | 0% | - | - | 64.12 KiB |
-| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | `channels=128 eps=1e-06 act=silu M=2` | 3.84 | 1% | - | - | 2.00 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=8` | 3.83 | 2% | - | - | 8.50 KiB |
-| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=8` | 3.82 | 0% | - | - | 16.03 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=2` | 3.82 | 2% | - | - | 1.25 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=16` | 3.81 | 7% | - | - | 8.25 KiB |
-| `rope_table` | `rope_table_f32` | libr4d | `rot=64 theta=1e+07 scale=1 dtype=f32 M=8` | 3.81 | 3% | - | - | 2.03 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=16` | 3.81 | 1% | - | - | 16.50 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=32` | 3.81 | 1% | - | - | 32.50 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=8` | 3.80 | 4% | - | - | 4.25 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=4` | 3.79 | 1% | - | - | 2.25 KiB |
-| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | `channels=128 eps=1e-06 act=silu M=4` | 3.79 | 1% | - | - | 3.50 KiB |
-| `rope_table` | `rope_table_f32` | libr4d | `rot=64 theta=1e+07 scale=1 dtype=f32 M=1` | 3.79 | 1% | - | - | 260 B |
-| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | `channels=128 eps=1e-06 act=silu M=256` | 3.78 | 6% | - | - | 192.50 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=128` | 3.78 | 3% | - | - | 128.50 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=32` | 3.78 | 1% | - | - | 16.25 KiB |
-| `sample_mask` | `sample_mask_f32` | libr4d | `n_vocab=248320 M=2` | 3.77 | 0% | - | - | 1.95 MiB |
-| `rope_table` | `rope_table_f32` | libr4d | `rot=64 theta=1e+07 scale=1 dtype=f32 M=16` | 3.76 | 2% | - | - | 4.06 KiB |
-| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | `channels=128 eps=1e-06 act=silu M=8` | 3.76 | 5% | - | - | 6.50 KiB |
-| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | `channels=128 eps=1e-06 act=silu M=64` | 3.76 | 4% | - | - | 48.50 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=64` | 3.75 | 2% | - | - | 64.50 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=64` | 3.75 | 1% | - | - | 32.25 KiB |
-| `rope_table` | `rope_table_f32` | libr4d | `rot=64 theta=1e+07 scale=1 dtype=f32 M=64` | 3.75 | 4% | - | - | 16.25 KiB |
-| `rope_table` | `rope_table_f32` | libr4d | `rot=64 theta=1e+07 scale=1 dtype=f32 M=2` | 3.75 | 4% | - | - | 520 B |
-| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | `channels=128 eps=1e-06 act=silu M=128` | 3.74 | 1% | - | - | 96.50 KiB |
-| `rope_table` | `rope_table_f32` | libr4d | `rot=64 theta=1e+07 scale=1 dtype=f32 M=4` | 3.73 | 1% | - | - | 1.02 KiB |
-| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | `channels=128 eps=1e-06 act=silu M=16` | 3.72 | 1% | - | - | 12.50 KiB |
-| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | `channels=128 eps=1e-06 act=silu M=32` | 3.70 | 3% | - | - | 24.50 KiB |
-| `cast` | `cast_bf16_bf16` | libr4d | `n=5120 from=bf16 to=bf16 M=2` | 3.70 | 5% | - | - | 40.00 KiB |
-| `cast` | `cast_bf16_bf16` | libr4d | `n=5120 from=bf16 to=bf16 M=32` | 3.70 | 4% | - | - | 640.00 KiB |
-| `rope_table` | `rope_table_f32` | libr4d | `rot=64 theta=1e+07 scale=1 dtype=f32 M=32` | 3.70 | 0% | - | - | 8.12 KiB |
-| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=128` | 3.70 | 5% | - | - | 64.25 KiB |
-| `cast` | `cast_bf16_bf16` | libr4d | `n=5120 from=bf16 to=bf16 M=16` | 3.59 | 0% | - | - | 320.00 KiB |
-| `cast` | `cast_bf16_bf16` | libr4d | `n=5120 from=bf16 to=bf16 M=4` | 3.56 | 3% | - | - | 80.00 KiB |
-| `cast` | `cast_bf16_bf16` | libr4d | `n=5120 from=bf16 to=bf16 M=8` | 3.56 | 1% | - | - | 160.00 KiB |
-| `cast` | `cast_bf16_bf16` | libr4d | `n=5120 from=bf16 to=bf16 M=1` | 3.50 | 2% | - | - | 20.00 KiB |
-| `sample_penalties` | `sample_penalties_f32` | libr4d | `n_vocab=248320 M=2` | 3.40 | 9% | - | - | 1.90 MiB |
-| `sample_dry` | `sample_dry_f32` | libr4d | `n_vocab=248320 M=16` | 3.39 | 0% | - | - | 15.16 MiB |
-| `sample_penalties` | `sample_penalties_f32` | libr4d | `n_vocab=248320 M=8` | 3.39 | 2% | - | - | 7.58 MiB |
-| `sample_dry` | `sample_dry_f32` | libr4d | `n_vocab=248320 M=8` | 3.39 | 1% | - | - | 7.58 MiB |
-| `sample_dry` | `sample_dry_f32` | libr4d | `n_vocab=248320 M=4` | 3.38 | 2% | - | - | 3.79 MiB |
-| `sample_dry` | `sample_dry_f32` | libr4d | `n_vocab=248320 M=1` | 3.37 | 0% | - | - | 970.34 KiB |
-| `sample_penalties` | `sample_penalties_f32` | libr4d | `n_vocab=248320 M=1` | 3.37 | 5% | - | - | 970.34 KiB |
-| `sample_dry` | `sample_dry_f32` | libr4d | `n_vocab=248320 M=2` | 3.37 | 0% | - | - | 1.90 MiB |
+- **Device rows** are device timestamps around a batch of back-to-back launches, divided by the
+  launch count. The batch is queued behind a gate the host opens once all of it is queued,
+  so neither the host's submission rate nor its synchronisation is in the interval, and a
+  keep-alive copy runs ahead of the gate so the card does not idle (and drop its clock) while
+  the host submits. Correctness ran first; the passing cases were then timed back to back after
+  one sustained warm-up, two untimed launches ahead of every batch. A batch lasts at least a
+  millisecond and fifty launch floors.
+- A time **includes the launch floor** below, the gap between two dependent dispatches, which
+  the engine pays too; a kernel near the floor is launch-bound, not slow.
+- In-place operands are restored from a pristine copy before every launch, so mutation does not
+  drift. The restores are timed in a batch of their own, each followed by a floor launch in the
+  kernel's place, and subtracted, the floor added back (`restore` in the notes is their share
+  of the batch). A large share leaves the kernel a small difference of two large
+  times, which the interval shows as noise but not as bias (the restores leave the operand in
+  the cache): a share of 75% or more, or a time under the launch floor, is noted as an order
+  of magnitude.
+- The timing pass draws its own **routing and block tables**: expert offsets and ids skewed as
+  real routing is (Zipf, exponent 0.5) and block tables as permutations. The checked launch
+  keeps the recorded draw.
+- `±%` is the half-width of a distribution-free 95% interval for the median, as a percent of
+  it (below six batches the range, which covers less); a case is timed until it is 1% or
+  the rep cap (`--bench-reps`) is reached, so a wide one marks a noisy case. `n` counts the
+  timed batches. `MHz` is the firmware's averaged graphics
+  clock read after each batch; a batch during which a throttler came on that was off at idle and
+  after the warm-up is discarded and repeated.
+- **Host rows** (their own column) are steady_clock times on the calling thread, after an untimed
+  launch, with in-place operands restored outside the timed region; weights, weight tables and
+  inputs of 8.00 MiB or more are rotated over copies spanning 256.00 MiB (twice the CPU's last-level
+  cache, at least 256 MiB), so read from memory. The notes name the OpenMP threads.
+- `operands` is the total the case allocated, not what the kernel read (a gather touches M rows
+  of a table, not the table), so dividing the two gives no bandwidth figure.
+
+Device timing and its calibration:
+
+> device: AMD Radeon AI PRO R9700 (gfx1201), the aql backend
+>
+> cold: each launch reads its weights, weight tables and inputs of 8.00 MiB or more from one of a set of copies spanning 256.00 MiB, so from memory; smaller inputs stay warm, as the previous op leaves them; in-place operands are restored before every launch and the restores' own time subtracted
+>
+> launch floor: 2.14 us a launch back to back in a batch, 4.84 us alone between two events (the backend's own 4-byte fill, the cheapest kernel a tool can launch); a batch lasts at least 1000 us
+>
+> read bandwidth (ranged copies into a 1 MiB ring, so the writes stay in the cache), warm / cold: 4.00 MiB 320 / 324 GB/s; 16.00 MiB 1417 / 480 GB/s; 64.00 MiB 1764 / 602 GB/s; 256.00 MiB 629 / 629 GB/s
+>
+> clock: 3245 MHz averaged graphics clock after a 2000 ms warm-up (gpu_metrics); on at idle, not counted: TEMP_HOTSPOT; on under the warm-up's load, binding throughout and not counted: PPT0; a batch during which another throttler came on is repeated
+
+| op | kernel | library | geometry | device us | host us | min | p90 | n | ±% | MHz | operands | notes |
+|---|---|---|---|---|---|---|---|---|---|---|---|---|
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=512` | - | 6279838.66 | 6279838.66 | 6279838.66 | 1 | - | - | 44.00 MiB | 32 thread(s); 1 timed launch(es) within the 2 s host budget |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=512 tn=0` | - | 4155022.72 | 4155022.72 | 4155022.72 | 1 | - | - | 88.20 MiB | 32 thread(s); 1 timed launch(es) within the 2 s host budget |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=264` | - | 2888453.88 | 2888453.88 | 2888453.88 | 1 | - | - | 38.19 MiB | 32 thread(s); 1 timed launch(es) within the 2 s host budget |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=258 tn=0` | - | 2106871.18 | 2106871.18 | 2106871.18 | 1 | - | - | 79.33 MiB | 32 thread(s); 1 timed launch(es) within the 2 s host budget |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=132` | - | 1732679.63 | 1705393.49 | 1759965.77 | 2 | 1.6 | - | 35.10 MiB | 32 thread(s); 2 timed launch(es) within the 2 s host budget |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=129 tn=0` | - | 1082439.92 | 1068723.95 | 1096155.89 | 2 | 1.3 | - | 74.82 MiB | 32 thread(s); 2 timed launch(es) within the 2 s host budget |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=128 ks=0 bk=0 nt=0` | - | 1039280.58 | 1038198.86 | 1040362.29 | 2 | 0.1 | - | 74.79 MiB | 32 thread(s); 2 timed launch(es) within the 2 s host budget |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=66` | - | 888574.31 | 859059.82 | 889376.71 | 3 | 1.7 | - | 33.55 MiB | 32 thread(s); 3 timed launch(es) within the 2 s host budget |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=65 ks=0 bk=0 nt=0` | - | 549367.37 | 549256.47 | 549603.38 | 4 | 0.0 | - | 72.58 MiB | 32 thread(s); 4 timed launch(es) within the 2 s host budget |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=64 ks=0 bk=0 nt=0` | - | 518622.97 | 518516.85 | 519228.34 | 4 | 0.1 | - | 72.55 MiB | 32 thread(s); 4 timed launch(es) within the 2 s host budget |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=33` | - | 442653.59 | 442568.03 | 443207.98 | 5 | 0.1 | - | 32.78 MiB | 32 thread(s); 5 timed launch(es) within the 2 s host budget |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=32` | - | 429693.71 | 429168.88 | 430590.52 | 5 | 0.2 | - | 32.75 MiB | 32 thread(s); 5 timed launch(es) within the 2 s host budget |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=64 ks=0 bk=0 nt=0` | - | 351854.86 | 351417.26 | 351939.64 | 6 | 0.1 | - | 49.53 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=34816 K=5120 group=128 dtype=fp8a8 M=512` | - | 328291.96 | 327900.26 | 328705.11 | 6 | 0.1 | - | 206.60 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=64 ks=0 bk=0 nt=0` | - | 327875.47 | 326741.53 | 377330.25 | 6 | 7.7 | - | 100.20 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=36 ks=0 bk=0 nt=0` | - | 291904.77 | 291713.86 | 292211.07 | 6 | 0.1 | - | 71.57 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=17408 group=128 dtype=fp8a8 M=512` | - | 215410.27 | 215100.46 | 215614.23 | 6 | 0.1 | - | 98.78 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=36 ks=0 bk=0 nt=0` | - | 198358.57 | 198117.88 | 198474.15 | 6 | 0.1 | - | 48.78 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=36 ks=0 bk=0 nt=0` | - | 178054.62 | 169525.51 | 200811.86 | 11 | 8.8 | - | 98.20 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=34816 K=5120 group=128 dtype=fp8a8 M=258` | - | 170942.02 | 170415.47 | 172283.14 | 6 | 0.5 | - | 188.45 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=18 ks=0 bk=0 nt=0` | - | 160638.71 | 160502.32 | 160722.14 | 6 | 0.1 | - | 70.94 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=16384 K=5120 group=128 dtype=fp8a8 M=512` | - | 154888.66 | 154819.00 | 155233.69 | 6 | 0.1 | - | 98.59 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=12288 K=5120 group=128 dtype=fp8a8 M=512` | - | 119795.34 | 119665.60 | 119843.12 | 6 | 0.1 | - | 74.59 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=18 ks=0 bk=0 nt=0` | - | 109097.75 | 109007.77 | 109131.72 | 6 | 0.1 | - | 48.30 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=17408 group=128 dtype=fp8a8 M=258` | - | 108465.62 | 107933.77 | 108620.79 | 6 | 0.3 | - | 91.95 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=18 ks=0 bk=0 nt=0` | - | 104865.56 | 104748.85 | 105065.96 | 6 | 0.2 | - | 96.91 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=9 ks=0 bk=0 nt=0` | - | 94401.70 | 94360.47 | 94535.94 | 6 | 0.1 | - | 70.63 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=34816 K=5120 group=128 dtype=fp8a8 M=129` | - | 82474.04 | 82426.54 | 82594.74 | 6 | 0.1 | - | 179.24 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=34816 K=5120 group=128 dtype=fp8a8 M=128` | - | 82209.80 | 81840.95 | 82507.37 | 6 | 0.4 | - | 179.17 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=16384 K=5120 group=128 dtype=fp8a8 M=258` | - | 78245.42 | 78231.86 | 78562.90 | 6 | 0.2 | - | 89.37 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=512 tn=0` | - | 75485.50 | 75424.78 | 75515.79 | 6 | 0.1 | - | 6.39 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=8 ks=0 bk=0 nt=0` | - | 64705.77 | 64677.23 | 64772.02 | 6 | 0.1 | - | 70.59 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=6144 group=128 dtype=fp8a8 M=512` | - | 64570.37 | 64551.29 | 64699.21 | 6 | 0.1 | - | 38.10 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=9 ks=0 bk=0 nt=0` | - | 64192.15 | 64101.63 | 64229.47 | 6 | 0.1 | - | 48.05 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=12288 K=5120 group=128 dtype=fp8a8 M=258` | - | 60304.27 | 60109.47 | 60370.85 | 6 | 0.2 | - | 67.35 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=17408 group=128 dtype=fp8a8 M=129` | - | 54814.38 | 54703.52 | 54986.91 | 6 | 0.3 | - | 88.48 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=17408 group=128 dtype=fp8a8 M=128` | - | 54258.37 | 54002.21 | 55001.78 | 6 | 0.9 | - | 88.45 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=9 ks=0 bk=0 nt=0` | - | 53011.12 | 52816.02 | 53078.79 | 6 | 0.2 | - | 96.27 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=8 ks=0 bk=0 nt=0` | - | 50106.70 | 50017.83 | 53553.75 | 20 | 1.6 | - | 96.20 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=264` | - | 49994.63 | 42676.96 | 56218.13 | 20 | 8.9 | - | 10.19 MiB | 32 thread(s) |
+| `logits_gemm` | `avx_logits_gemm` | libavx | `n_vocab=248320 n_embd=5120 dtype=bf16 M=64` | - | 49238.59 | 49041.81 | 49319.85 | 6 | 0.3 | - | 2.43 GiB | 32 thread(s) |
+| `logits_gemm` | `avx_logits_gemm` | libavx | `n_vocab=248320 n_embd=5120 dtype=bf16 M=16` | - | 46504.59 | 46468.01 | 46542.55 | 6 | 0.1 | - | 2.38 GiB | 32 thread(s) |
+| `logits_gemm` | `avx_logits_gemm` | libavx | `n_vocab=248320 n_embd=5120 dtype=bf16 M=32` | - | 46168.73 | 46123.00 | 46268.50 | 6 | 0.2 | - | 2.40 GiB | 32 thread(s) |
+| `logits_gemm` | `avx_logits_gemm` | libavx | `n_vocab=248320 n_embd=5120 dtype=bf16 M=8` | - | 44313.69 | 44193.56 | 44508.82 | 6 | 0.4 | - | 2.38 GiB | 32 thread(s) |
+| `logits_gemm` | `avx_logits_gemm` | libavx | `n_vocab=248320 n_embd=5120 dtype=bf16 M=4` | - | 44126.68 | 44041.87 | 44172.62 | 6 | 0.1 | - | 2.37 GiB | 32 thread(s) |
+| `logits_gemm` | `avx_logits_gemm` | libavx | `n_vocab=248320 n_embd=5120 dtype=bf16 M=1` | - | 44092.88 | 43813.02 | 44306.72 | 6 | 0.6 | - | 2.37 GiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=8 ks=0 bk=0 nt=0` | - | 44010.38 | 43943.00 | 44063.86 | 6 | 0.1 | - | 48.03 MiB | 32 thread(s) |
+| `logits_gemm` | `avx_logits_gemm` | libavx | `n_vocab=248320 n_embd=5120 dtype=bf16 M=2` | - | 43586.54 | 43540.05 | 43723.01 | 6 | 0.2 | - | 2.37 GiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=4 ks=0 bk=0 nt=0` | - | 43359.08 | 43290.80 | 43404.92 | 6 | 0.1 | - | 95.91 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=34816 K=5120 group=128 dtype=fp8a8 M=65` | - | 42289.78 | 42102.32 | 42349.13 | 6 | 0.3 | - | 174.66 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=512` | - | 42099.14 | 40270.51 | 57081.93 | 20 | 8.7 | - | 16.00 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=34816 K=5120 group=128 dtype=fp8a8 M=64` | - | 41666.52 | 41307.89 | 41709.87 | 6 | 0.5 | - | 174.59 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=2 ks=0 bk=0 nt=0` | - | 41301.72 | 41267.07 | 41457.89 | 6 | 0.2 | - | 95.77 MiB | 32 thread(s) |
+| `gemm_nt_q_gated` | `avx_gemm_nt_q_gated` | libavx | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=64` | - | 40465.42 | 40417.82 | 40639.25 | 6 | 0.3 | - | 173.56 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=1 ks=0 bk=0 nt=0` | - | 39693.70 | 39567.76 | 39866.84 | 6 | 0.4 | - | 95.70 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=16384 K=5120 group=128 dtype=fp8a8 M=129` | - | 39133.14 | 39011.23 | 39318.62 | 6 | 0.4 | - | 84.69 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=64 ks=0 bk=0 nt=0` | - | 38875.41 | 38814.38 | 38887.78 | 6 | 0.1 | - | 12.07 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=16384 K=5120 group=128 dtype=fp8a8 M=128` | - | 38793.61 | 38641.71 | 38878.47 | 6 | 0.3 | - | 84.65 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=258 tn=0` | - | 38307.60 | 38250.19 | 38725.86 | 6 | 0.6 | - | 4.62 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=4 ks=0 bk=0 nt=0` | - | 32365.44 | 32309.80 | 32420.97 | 6 | 0.2 | - | 70.45 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=6144 group=128 dtype=fp8a8 M=258` | - | 32340.91 | 31474.55 | 32398.43 | 11 | 0.9 | - | 34.08 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=2 ks=0 bk=0 nt=0` | - | 30911.62 | 30833.33 | 34301.53 | 20 | 2.6 | - | 70.38 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=64 ks=0 bk=0 nt=0` | - | 30275.42 | 30149.27 | 30305.58 | 6 | 0.3 | - | 12.13 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=12288 K=5120 group=128 dtype=fp8a8 M=129` | - | 30269.63 | 30189.27 | 30350.88 | 6 | 0.3 | - | 63.68 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=12288 K=5120 group=128 dtype=fp8a8 M=128` | - | 30014.27 | 29863.73 | 30037.22 | 6 | 0.3 | - | 63.65 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=1 ks=0 bk=0 nt=0` | - | 29511.96 | 29469.99 | 29537.88 | 6 | 0.1 | - | 70.35 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=17408 group=128 dtype=fp8a8 M=65` | - | 27787.97 | 27758.75 | 28041.79 | 6 | 0.5 | - | 86.76 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=17408 group=128 dtype=fp8a8 M=64` | - | 27055.37 | 27019.58 | 27122.99 | 6 | 0.2 | - | 86.73 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=132` | - | 25094.49 | 19795.50 | 28553.08 | 20 | 10.3 | - | 7.09 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=34816 K=5120 group=128 dtype=fp8a8 M=36` | - | 22831.94 | 22695.01 | 22961.41 | 6 | 0.6 | - | 172.59 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=4 ks=0 bk=0 nt=0` | - | 22034.31 | 21977.85 | 25298.99 | 19 | 0.1 | - | 47.92 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=2 ks=0 bk=0 nt=0` | - | 21021.28 | 20949.69 | 22645.57 | 14 | 0.6 | - | 47.87 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=16384 K=5120 group=128 dtype=fp8a8 M=65` | - | 20622.69 | 19848.82 | 20708.32 | 19 | 0.2 | - | 82.37 MiB | 32 thread(s) |
+| `gemm_nt_q_gated` | `avx_gemm_nt_q_gated` | libavx | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=32` | - | 20370.77 | 20300.95 | 20489.65 | 6 | 0.5 | - | 171.79 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=36 ks=0 bk=0 nt=0` | - | 20318.18 | 20176.38 | 25330.90 | 20 | 12.1 | - | 11.75 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=36 ks=0 bk=0 nt=0` | - | 20222.66 | 20178.15 | 22059.20 | 14 | 0.1 | - | 11.71 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=1 ks=0 bk=0 nt=0` | - | 20094.03 | 20039.49 | 20149.54 | 11 | 0.3 | - | 47.84 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=16384 K=5120 group=128 dtype=fp8a8 M=64` | - | 19613.62 | 19479.94 | 19646.86 | 11 | 0.1 | - | 82.33 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=129 tn=0` | - | 19186.80 | 19104.93 | 19266.86 | 6 | 0.4 | - | 3.71 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=128 ks=0 bk=0 nt=0` | - | 19065.87 | 19037.33 | 19244.74 | 6 | 0.5 | - | 3.71 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=66` | - | 17701.40 | 17504.04 | 18368.57 | 16 | 0.7 | - | 5.55 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=6144 group=128 dtype=fp8a8 M=129` | - | 16218.91 | 16147.07 | 16284.71 | 11 | 0.4 | - | 32.04 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=6144 group=128 dtype=fp8a8 M=128` | - | 15809.08 | 15638.36 | 15878.55 | 6 | 0.8 | - | 32.03 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=17408 group=128 dtype=fp8a8 M=36` | - | 15305.98 | 15253.77 | 23834.21 | 14 | 0.6 | - | 85.98 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=12288 K=5120 group=128 dtype=fp8a8 M=65` | - | 14972.51 | 14869.96 | 19458.31 | 14 | 0.3 | - | 61.86 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=12288 K=5120 group=128 dtype=fp8a8 M=64` | - | 14614.20 | 14551.34 | 14631.23 | 6 | 0.3 | - | 61.83 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=17` | - | 14053.32 | 14003.33 | 18429.84 | 16 | 0.3 | - | 32.40 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=16` | - | 12849.68 | 12448.54 | 12924.99 | 14 | 0.8 | - | 32.38 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=18 ks=0 bk=0 nt=0` | - | 12514.79 | 12420.19 | 12540.15 | 6 | 0.5 | - | 11.50 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=18 ks=0 bk=0 nt=0` | - | 12461.48 | 12406.13 | 12537.80 | 6 | 0.5 | - | 11.48 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=34816 K=5120 group=128 dtype=fp8a8 M=18` | - | 12094.05 | 12078.00 | 12191.45 | 6 | 0.5 | - | 171.31 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=9 splits=0` | - | 12002.43 | 8467.67 | 12283.43 | 20 | 15.5 | - | 32.21 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=1024 K=5120 group=128 dtype=fp8a8 M=512` | - | 11417.08 | 11311.06 | 16866.86 | 19 | 0.5 | - | 8.58 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=16384 K=5120 group=128 dtype=fp8a8 M=36` | - | 11159.90 | 11060.76 | 16880.61 | 19 | 0.2 | - | 81.32 MiB | 32 thread(s) |
+| `gemm_nt_q_gated` | `avx_gemm_nt_q_gated` | libavx | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=16` | - | 10760.19 | 10733.02 | 16663.62 | 16 | 0.4 | - | 170.91 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=65 ks=0 bk=0 nt=0` | - | 10206.59 | 10125.99 | 10275.97 | 11 | 0.5 | - | 3.27 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=64 ks=0 bk=0 nt=0` | - | 10160.29 | 10035.26 | 10187.16 | 11 | 0.3 | - | 3.26 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=33` | - | 9144.90 | 8980.83 | 9261.28 | 20 | 1.0 | - | 4.77 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=32` | - | 9071.00 | 8982.39 | 9175.31 | 11 | 1.0 | - | 4.75 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=8 splits=0` | - | 9065.15 | 8959.90 | 9110.98 | 6 | 0.8 | - | 32.19 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=5120 K=4608 dtype=bf16 act=none M=512` | - | 8779.54 | 8579.50 | 8997.17 | 19 | 0.9 | - | 59.51 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=11` | - | 8667.47 | 8622.13 | 13714.88 | 20 | 23.9 | - | 32.26 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=10 splits=0` | - | 8656.79 | 8475.00 | 8722.50 | 11 | 0.9 | - | 32.24 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=4608 K=4608 dtype=bf16 act=gelu M=512` | - | 8535.17 | 8008.35 | 10277.93 | 20 | 8.4 | - | 54.01 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=6144 group=128 dtype=fp8a8 M=65` | - | 8241.16 | 8064.95 | 8260.28 | 11 | 0.8 | - | 31.03 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=6144 group=128 dtype=fp8a8 M=64` | - | 8098.22 | 7866.78 | 8140.62 | 19 | 0.3 | - | 31.02 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=12288 K=5120 group=128 dtype=fp8a8 M=36` | - | 8092.43 | 8022.27 | 8110.35 | 11 | 0.5 | - | 61.03 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=17408 group=128 dtype=fp8a8 M=18` | - | 8074.35 | 8016.94 | 8096.97 | 11 | 0.4 | - | 85.49 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=512` | - | 8065.13 | 8032.14 | 10007.14 | 20 | 10.8 | - | 13.00 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=5 splits=0` | - | 7298.69 | 7280.22 | 7311.46 | 6 | 0.2 | - | 32.12 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=36 ks=0 bk=0 nt=0` | - | 6480.71 | 6454.71 | 6508.01 | 6 | 0.4 | - | 3.06 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=8 ks=0 bk=0 nt=0` | - | 6451.49 | 5936.40 | 7248.79 | 20 | 9.8 | - | 11.36 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=9 ks=0 bk=0 nt=0` | - | 6320.68 | 6253.17 | 7608.16 | 14 | 0.6 | - | 11.37 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=9 ks=0 bk=0 nt=0` | - | 6309.34 | 6205.30 | 6340.68 | 11 | 0.9 | - | 11.37 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=34816 K=5120 group=128 dtype=fp8a8 M=9` | - | 6297.13 | 6232.45 | 8842.41 | 14 | 0.4 | - | 170.66 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=4608 K=4608 dtype=bf16 act=gelu M=256` | - | 6269.07 | 5759.48 | 6832.21 | 20 | 4.0 | - | 47.26 MiB | 32 thread(s) |
+| `attn_dense` | `avx_attn_dense` | libavx | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=512` | - | 6019.46 | 5989.82 | 6044.60 | 6 | 0.5 | - | 288.01 KiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=8 ks=0 bk=0 nt=0` | - | 5932.29 | 5918.34 | 5958.64 | 6 | 0.3 | - | 11.35 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=1024 K=5120 group=128 dtype=fp8a8 M=258` | - | 5798.89 | 5743.29 | 8184.74 | 20 | 20.0 | - | 6.80 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=16384 K=5120 group=128 dtype=fp8a8 M=18` | - | 5773.27 | 5740.70 | 8951.51 | 20 | 17.5 | - | 80.66 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=6 splits=0` | - | 5758.83 | 5659.24 | 5848.11 | 16 | 0.6 | - | 32.14 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=5120 K=4608 dtype=bf16 act=none M=256` | - | 5680.98 | 5463.24 | 6871.94 | 20 | 7.4 | - | 52.26 MiB | 32 thread(s) |
+| `gemm_nt_q_gated` | `avx_gemm_nt_q_gated` | libavx | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=8` | - | 5454.27 | 5410.62 | 5484.79 | 11 | 0.6 | - | 170.46 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=34816 K=5120 group=128 dtype=fp8a8 M=8` | - | 5410.44 | 5369.15 | 5437.19 | 11 | 0.6 | - | 170.59 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=4 ks=0 bk=0 nt=0` | - | 5168.15 | 5152.80 | 5899.83 | 20 | 4.8 | - | 11.31 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=4 ks=0 bk=0 nt=0` | - | 5142.00 | 5129.44 | 5147.51 | 6 | 0.2 | - | 11.30 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=1 ks=0 bk=0 nt=0` | - | 5122.39 | 5110.83 | 5158.52 | 6 | 0.5 | - | 11.26 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=2 ks=0 bk=0 nt=0` | - | 4935.73 | 4905.02 | 4937.38 | 6 | 0.3 | - | 11.28 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=2 ks=0 bk=0 nt=0` | - | 4907.77 | 4886.83 | 5459.09 | 19 | 0.3 | - | 11.28 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=1 ks=0 bk=0 nt=0` | - | 4734.36 | 4716.24 | 5192.35 | 20 | 4.7 | - | 11.26 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=12288 K=5120 group=128 dtype=fp8a8 M=18` | - | 4652.41 | 4603.64 | 6709.87 | 19 | 0.2 | - | 60.52 MiB | 32 thread(s) |
+| `gdn_chunk_scan` | `avx_gdn_chunk_scan` | libavx | `head_k=128 head_v=128 scale=0.0883883 M=512 chunk=64` | - | 4599.36 | 3786.59 | 5140.46 | 20 | 12.0 | - | 25.19 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=6144 group=128 dtype=fp8a8 M=36` | - | 4491.21 | 4469.66 | 4589.56 | 14 | 1.0 | - | 30.57 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=17408 group=128 dtype=fp8a8 M=9` | - | 4455.98 | 4405.58 | 4466.12 | 11 | 0.5 | - | 85.25 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=4 splits=0` | - | 4423.60 | 4386.39 | 4457.66 | 6 | 0.8 | - | 32.10 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=512` | - | 3984.69 | 3945.42 | 4010.66 | 6 | 0.8 | - | 19.00 MiB | 32 thread(s) |
+| `sample_topk` | `avx_sample_topk` | libavx | `n_vocab=248320 M=64` | - | 3903.93 | 3792.34 | 4132.83 | 20 | 2.2 | - | 60.69 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=18 ks=0 bk=0 nt=0` | - | 3877.06 | 3869.06 | 3906.11 | 6 | 0.5 | - | 2.94 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=5120 K=4608 dtype=bf16 act=none M=128` | - | 3850.22 | 3612.64 | 4230.71 | 20 | 3.5 | - | 48.63 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=17408 group=128 dtype=fp8a8 M=8` | - | 3505.89 | 3471.76 | 3524.58 | 6 | 0.8 | - | 85.23 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=34816 K=5120 group=128 dtype=fp8a8 M=1` | - | 3421.69 | 2466.94 | 3768.87 | 20 | 9.9 | - | 170.09 MiB | 32 thread(s) |
+| `gemm_nt_q_gated` | `avx_gemm_nt_q_gated` | libavx | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=1` | - | 3320.49 | 3216.01 | 3621.38 | 20 | 4.1 | - | 170.08 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=4608 K=4608 dtype=bf16 act=gelu M=128` | - | 3311.52 | 3132.93 | 3904.94 | 20 | 6.0 | - | 43.88 MiB | 32 thread(s) |
+| `gemm_nt_q_gated` | `avx_gemm_nt_q_gated` | libavx | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=4` | - | 3267.49 | 3235.43 | 3546.49 | 19 | 0.6 | - | 170.24 MiB | 32 thread(s) |
+| `row_topk` | `avx_row_topk` | libavx | `N=248320 R=32 dtype=bf16 M=56 nch=0 pt1=8` | - | 3252.70 | 3206.28 | 3267.77 | 6 | 0.9 | - | 26.55 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=34816 K=5120 group=128 dtype=fp8a8 M=4` | - | 3249.03 | 3211.30 | 3312.43 | 16 | 0.8 | - | 170.31 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=264` | - | 3096.83 | 3038.86 | 3111.84 | 16 | 0.8 | - | 6.72 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=1 splits=0` | - | 3073.27 | 2967.23 | 3165.46 | 20 | 2.1 | - | 32.03 MiB | 32 thread(s) |
+| `gemm_nt_q_gated` | `avx_gemm_nt_q_gated` | libavx | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=2` | - | 3070.49 | 2913.10 | 4067.99 | 14 | 0.8 | - | 170.13 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=2 splits=0` | - | 2955.39 | 2905.45 | 3084.64 | 20 | 1.4 | - | 32.05 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=12288 K=5120 group=128 dtype=fp8a8 M=9` | - | 2949.23 | 2229.80 | 3495.48 | 20 | 21.1 | - | 60.26 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=17408 group=128 dtype=fp8a8 M=4` | - | 2947.67 | 1761.59 | 3328.71 | 20 | 3.8 | - | 85.12 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=16384 K=5120 group=128 dtype=fp8a8 M=9` | - | 2946.56 | 2928.74 | 3027.75 | 16 | 0.7 | - | 80.34 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=1024 K=5120 group=128 dtype=fp8a8 M=129` | - | 2893.57 | 2880.69 | 2909.50 | 11 | 0.4 | - | 5.90 MiB | 32 thread(s) |
+| `logits_gemm` | `logits_gemm_fp8` | libr4d | `n_vocab=248320 n_embd=5120 dtype=bf16 M=64` | 2886.61 | - | 2771.39 | 2900.39 | 14 | 0.9 | 2148 | 2.43 GiB |  |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=1024 K=5120 group=128 dtype=fp8a8 M=128` | - | 2876.31 | 2830.52 | 4261.58 | 20 | 23.0 | - | 5.90 MiB | 32 thread(s) |
+| `gdn_conv_update` | `avx_gdn_conv_update` | libavx | `head_k=128 head_v=128 conv_width=4 q_len=512` | - | 2701.45 | 2605.74 | 2778.01 | 20 | 1.8 | - | 30.12 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=3456 K=1152 dtype=bf16 act=none M=512` | - | 2701.14 | 2686.26 | 2723.97 | 6 | 0.7 | - | 15.48 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=34816 K=5120 group=128 dtype=fp8a8 M=2` | - | 2598.22 | 2412.55 | 2976.88 | 20 | 5.8 | - | 170.16 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=16384 K=5120 group=128 dtype=fp8a8 M=8` | - | 2581.41 | 2538.67 | 2771.88 | 20 | 1.7 | - | 80.30 MiB | 32 thread(s) |
+| `sample_typical` | `avx_sample_typical` | libavx | `n_cand=1024 M=64` | - | 2493.07 | 2489.33 | 2547.49 | 14 | 0.5 | - | 518.00 KiB | 32 thread(s) |
+| `gdn_chunk_scan` | `avx_gdn_chunk_scan` | libavx | `head_k=128 head_v=128 scale=0.0883883 M=256 chunk=64` | - | 2484.39 | 2468.43 | 2517.70 | 6 | 1.0 | - | 15.59 MiB | 32 thread(s) |
+| `sample_topk` | `avx_sample_topk` | libavx | `n_vocab=248320 M=32` | - | 2467.16 | 2119.59 | 2659.33 | 20 | 7.0 | - | 30.35 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=6144 group=128 dtype=fp8a8 M=18` | - | 2396.19 | 2226.42 | 2563.14 | 20 | 5.8 | - | 30.29 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=256` | - | 2280.76 | 2141.07 | 2369.27 | 20 | 1.9 | - | 14.23 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=17408 group=128 dtype=fp8a8 M=2` | - | 2270.51 | 2219.32 | 2299.08 | 20 | 1.1 | - | 85.06 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=16384 K=5120 group=128 dtype=fp8a8 M=4` | - | 2242.88 | 2184.64 | 2272.52 | 20 | 1.3 | - | 80.15 MiB | 32 thread(s) |
+| `logits_gemm` | `logits_gemm_fp8` | libr4d | `n_vocab=248320 n_embd=5120 dtype=bf16 M=32` | 2196.66 | - | 2185.06 | 2202.58 | 6 | 0.4 | 2592 | 2.40 GiB |  |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=1152 K=4304 dtype=bf16 act=none M=512` | - | 2167.96 | 1941.83 | 2364.31 | 20 | 8.0 | - | 15.91 MiB | 32 thread(s) |
+| `logits_gemm` | `logits_gemm_fp8` | libr4d | `n_vocab=248320 n_embd=5120 dtype=bf16 M=16` | 2124.50 | - | 2123.10 | 2126.18 | 6 | 0.1 | 2938 | 2.38 GiB |  |
+| `logits_gemm` | `logits_gemm_fp8` | libr4d | `n_vocab=248320 n_embd=5120 dtype=bf16 M=8` | 2097.06 | - | 2095.94 | 2098.54 | 6 | 0.1 | 3071 | 2.38 GiB |  |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=1024 K=5120 group=128 dtype=fp8a8 M=64` | - | 2096.43 | 2083.71 | 2111.25 | 6 | 0.7 | - | 5.45 MiB | 32 thread(s) |
+| `logits_gemm` | `logits_gemm_fp8` | libr4d | `n_vocab=248320 n_embd=5120 dtype=bf16 M=4` | 2079.53 | - | 2078.98 | 2082.18 | 6 | 0.1 | 3076 | 2.37 GiB |  |
+| `logits_gemm` | `logits_gemm_fp8` | libr4d | `n_vocab=248320 n_embd=5120 dtype=bf16 M=2` | 2054.41 | - | 2053.14 | 2059.18 | 6 | 0.1 | 3109 | 2.37 GiB |  |
+| `logits_gemm` | `logits_gemm_fp8` | libr4d | `n_vocab=248320 n_embd=5120 dtype=bf16 M=1` | 2036.80 | - | 2036.14 | 2039.02 | 6 | 0.1 | 3397 | 2.37 GiB |  |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=9 ks=0 bk=0 nt=0` | - | 1956.10 | 1952.36 | 1964.78 | 6 | 0.3 | - | 2.88 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=12288 K=5120 group=128 dtype=fp8a8 M=8` | - | 1927.15 | 1912.54 | 1982.61 | 19 | 1.0 | - | 60.24 MiB | 32 thread(s) |
+| `sample_topk` | `avx_sample_topk` | libavx | `n_vocab=248320 M=16` | - | 1913.64 | 1869.29 | 1966.23 | 19 | 0.8 | - | 15.17 MiB | 32 thread(s) |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=512` | 1880.68 | - | 1823.26 | 1886.34 | 14 | 0.8 | 2598 | 44.00 MiB |  |
+| `row_topk` | `avx_row_topk` | libavx | `N=248320 R=32 dtype=bf16 M=32 nch=0 pt1=8` | - | 1862.83 | 1850.13 | 1872.43 | 11 | 0.5 | - | 15.17 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=8 ks=0 bk=0 nt=0` | - | 1834.20 | 1829.04 | 1838.16 | 6 | 0.2 | - | 2.87 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=17` | - | 1717.62 | 1706.37 | 1735.08 | 11 | 0.8 | - | 4.40 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=16384 K=5120 group=128 dtype=fp8a8 M=1` | - | 1710.19 | 1528.03 | 1840.42 | 20 | 6.7 | - | 80.05 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=6144 group=128 dtype=fp8a8 M=9` | - | 1654.02 | 1247.10 | 1717.10 | 20 | 13.2 | - | 30.15 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=5120 K=4608 dtype=bf16 act=none M=64` | - | 1638.63 | 1635.05 | 1663.44 | 6 | 0.9 | - | 46.82 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=4 ks=0 bk=0 nt=0` | - | 1626.47 | 1618.94 | 1645.46 | 6 | 0.8 | - | 2.84 MiB | 32 thread(s) |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=264` | 1618.38 | - | 1569.74 | 1630.34 | 11 | 1.0 | 3022 | 38.19 MiB |  |
+| `sample_temp` | `avx_sample_temp` | libavx | `n_vocab=248320 M=64` | - | 1606.84 | 1397.36 | 2993.10 | 20 | 15.5 | - | 60.63 MiB | 32 thread(s) |
+| `gdn_chunk_scan` | `avx_gdn_chunk_scan` | libavx | `head_k=128 head_v=128 scale=0.0883883 M=128 chunk=64` | - | 1583.66 | 1578.56 | 1585.93 | 6 | 0.2 | - | 10.80 MiB | 32 thread(s) |
+| `gdn_conv_update` | `avx_gdn_conv_update` | libavx | `head_k=128 head_v=128 conv_width=4 q_len=256` | - | 1569.99 | 1564.06 | 1590.86 | 11 | 0.8 | - | 15.12 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=16` | - | 1565.26 | 1515.29 | 2272.71 | 19 | 0.8 | - | 4.38 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=2 ks=0 bk=0 nt=0` | - | 1530.14 | 1506.48 | 1552.12 | 16 | 1.0 | - | 2.83 MiB | 32 thread(s) |
+| `attn_dense` | `avx_attn_dense` | libavx | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=256` | - | 1522.34 | 1520.16 | 1527.69 | 6 | 0.2 | - | 144.01 KiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=1024 K=5120 group=128 dtype=fp8a8 M=65` | - | 1503.88 | 1460.18 | 2121.86 | 20 | 2.0 | - | 5.45 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=3456 K=1152 dtype=bf16 act=none M=256` | - | 1472.64 | 1437.33 | 1502.34 | 16 | 0.8 | - | 11.54 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=16384 K=5120 group=128 dtype=fp8a8 M=2` | - | 1452.79 | 1401.28 | 1504.62 | 20 | 1.3 | - | 80.08 MiB | 32 thread(s) |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=132` | 1436.34 | - | 1409.62 | 1481.01 | 20 | 1.7 | 3364 | 35.10 MiB |  |
+| `sample_topk` | `avx_sample_topk` | libavx | `n_vocab=248320 M=8` | - | 1432.52 | 1427.50 | 1440.95 | 6 | 0.5 | - | 7.59 MiB | 32 thread(s) |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=33` | 1429.38 | - | 1406.10 | 1451.14 | 16 | 0.9 | 3417 | 32.78 MiB |  |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=66` | 1425.73 | - | 1411.26 | 1461.90 | 19 | 0.6 | 3414 | 33.55 MiB |  |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=16` | 1425.70 | - | 1410.25 | 1444.42 | 14 | 0.9 | 3415 | 32.38 MiB |  |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=11` | 1424.41 | - | 1409.65 | 1450.73 | 14 | 1.0 | 3412 | 32.26 MiB |  |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=32` | 1421.23 | - | 1410.22 | 1441.14 | 16 | 0.9 | 3414 | 32.75 MiB |  |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=17` | 1419.70 | - | 1408.41 | 1434.98 | 11 | 0.9 | 3421 | 32.40 MiB |  |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=1152 K=4304 dtype=bf16 act=none M=256` | - | 1416.00 | 1302.42 | 1445.35 | 20 | 2.7 | - | 12.69 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=17408 group=128 dtype=fp8a8 M=1` | - | 1411.49 | 1168.28 | 2061.53 | 20 | 27.7 | - | 85.04 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=132` | - | 1344.09 | 1338.34 | 1351.23 | 6 | 0.5 | - | 3.38 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=4608 K=4608 dtype=bf16 act=gelu M=64` | - | 1341.51 | 1083.19 | 1404.01 | 20 | 4.6 | - | 42.20 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=1 ks=0 bk=0 nt=0` | - | 1334.01 | 1326.22 | 1344.36 | 6 | 0.7 | - | 2.82 MiB | 32 thread(s) |
+| `sample_typical` | `avx_sample_typical` | libavx | `n_cand=1024 M=32` | - | 1318.26 | 1305.74 | 1393.23 | 20 | 1.9 | - | 259.00 KiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=12288 K=5120 group=128 dtype=fp8a8 M=1` | - | 1292.81 | 1142.66 | 1451.08 | 20 | 7.8 | - | 60.04 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=128` | - | 1284.87 | 1229.99 | 1326.86 | 19 | 0.7 | - | 11.85 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=512` | 1218.55 | - | 1118.05 | 1258.93 | 20 | 2.7 | 2187 | 206.60 MiB |  |
+| `gated_quant_fp8` | `avx_gated_quant_fp8` | libavx | `n=17408 group=128 dtype=bf16 act=silu M=512` | - | 1206.69 | 1077.54 | 1443.07 | 20 | 9.8 | - | 59.77 MiB | 32 thread(s) |
+| `sample_topk` | `avx_sample_topk` | libavx | `n_vocab=248320 M=4` | - | 1191.73 | 1109.75 | 1608.78 | 20 | 20.0 | - | 3.79 MiB | 32 thread(s) |
+| `sample_argmax` | `avx_sample_argmax` | libavx | `n_vocab=248320 M=64` | - | 1190.62 | 1012.77 | 1276.07 | 20 | 4.6 | - | 60.63 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=12288 K=5120 group=128 dtype=fp8a8 M=4` | - | 1189.13 | 1168.15 | 1294.34 | 20 | 1.4 | - | 60.12 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=1024 K=5120 group=128 dtype=fp8a8 M=36` | - | 1182.61 | 1161.44 | 1193.84 | 11 | 0.7 | - | 5.25 MiB | 32 thread(s) |
+| `sample_logprobs` | `avx_sample_logprobs` | libavx | `n_vocab=248320 k=21 M=64` | - | 1155.71 | 1044.77 | 1241.17 | 20 | 5.5 | - | 60.64 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=8 splits=0` | - | 1145.12 | 1141.44 | 1149.21 | 6 | 0.3 | - | 4.19 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=6144 group=128 dtype=fp8a8 M=8` | - | 1115.04 | 1034.01 | 1473.45 | 20 | 17.6 | - | 30.13 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=5120 K=4608 dtype=bf16 act=none M=32` | - | 1100.34 | 1092.13 | 1117.30 | 11 | 0.9 | - | 45.92 MiB | 32 thread(s) |
+| `gdn_conv_update` | `avx_gdn_conv_update` | libavx | `head_k=128 head_v=128 conv_width=4 q_len=128` | - | 1085.04 | 1075.82 | 1097.42 | 6 | 1.0 | - | 7.62 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=10 splits=0` | - | 1076.61 | 1048.46 | 1503.27 | 20 | 20.4 | - | 4.23 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=12288 K=5120 group=128 dtype=fp8a8 M=2` | - | 1072.08 | 902.90 | 1440.56 | 20 | 22.1 | - | 60.06 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=11` | - | 1070.45 | 1061.12 | 1993.24 | 20 | 21.2 | - | 4.26 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=1152 K=1536 dtype=bf16 act=none M=512` | - | 1057.68 | 874.98 | 1079.46 | 20 | 3.6 | - | 7.13 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=8 splits=0` | - | 1039.64 | 1033.22 | 1054.65 | 11 | 0.9 | - | 32.13 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=9 splits=0` | - | 1018.72 | 1004.31 | 1466.04 | 20 | 11.6 | - | 4.21 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=5120 K=4608 dtype=bf16 act=none M=16` | - | 1007.68 | 1003.19 | 1011.94 | 11 | 0.4 | - | 45.46 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=8 splits=0` | - | 1001.25 | 996.75 | 1012.24 | 6 | 0.8 | - | 4.13 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=5120 K=4608 dtype=bf16 act=none M=8` | - | 990.01 | 973.70 | 992.36 | 6 | 0.9 | - | 45.24 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=5120 K=4608 dtype=bf16 act=none M=2` | - | 955.37 | 749.33 | 1037.97 | 20 | 12.1 | - | 45.07 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=5120 K=4608 dtype=bf16 act=none M=1` | - | 946.51 | 626.55 | 992.29 | 20 | 6.4 | - | 45.04 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=4608 K=4608 dtype=bf16 act=gelu M=32` | - | 917.18 | 692.16 | 955.31 | 20 | 5.6 | - | 41.35 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=1152 K=1152 dtype=bf16 act=none M=512` | - | 902.15 | 877.33 | 921.06 | 20 | 1.1 | - | 5.91 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=6144 group=128 dtype=fp8a8 M=4` | - | 901.89 | 866.34 | 915.78 | 20 | 1.7 | - | 30.07 MiB | 32 thread(s) |
+| `grid_embed` | `avx_grid_embed` | libavx | `n=1152 side=48 dtype=bf16 M=512` | - | 891.89 | 885.05 | 894.99 | 6 | 0.6 | - | 6.20 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=1152 K=4304 dtype=bf16 act=none M=128` | - | 891.54 | 791.58 | 919.57 | 20 | 3.1 | - | 11.07 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=258` | 888.80 | - | 863.45 | 916.69 | 20 | 1.5 | 2426 | 188.45 MiB |  |
+| `row_topk` | `avx_row_topk` | libavx | `N=248320 R=32 dtype=bf16 M=16 nch=0 pt1=8` | - | 865.99 | 864.02 | 868.56 | 6 | 0.3 | - | 7.59 MiB | 32 thread(s) |
+| `sample_topk` | `avx_sample_topk` | libavx | `n_vocab=248320 M=1` | - | 857.82 | 857.56 | 865.80 | 6 | 0.5 | - | 971.09 KiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=3456 K=1152 dtype=bf16 act=none M=128` | - | 848.89 | 794.80 | 949.37 | 20 | 8.1 | - | 9.57 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=4608 K=4608 dtype=bf16 act=gelu M=4` | - | 847.92 | 751.79 | 917.75 | 20 | 6.0 | - | 40.61 MiB | 32 thread(s) |
+| `sample_mask` | `avx_sample_mask` | libavx | `n_vocab=248320 M=64` | - | 845.77 | 732.77 | 1019.57 | 20 | 11.2 | - | 62.53 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=4608 K=4608 dtype=bf16 act=gelu M=8` | - | 832.41 | 732.38 | 965.71 | 20 | 8.7 | - | 40.72 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=4608 K=4608 dtype=bf16 act=gelu M=2` | - | 830.12 | 798.85 | 917.49 | 20 | 5.9 | - | 40.56 MiB | 32 thread(s) |
+| `sample_temp` | `avx_sample_temp` | libavx | `n_vocab=248320 M=16` | - | 827.35 | 489.44 | 908.55 | 20 | 21.8 | - | 15.16 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=6 splits=0` | - | 819.64 | 661.18 | 850.18 | 20 | 8.9 | - | 32.10 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=4608 K=4608 dtype=bf16 act=gelu M=16` | - | 816.93 | 669.62 | 1032.24 | 20 | 15.2 | - | 40.93 MiB | 32 thread(s) |
+| `gdn_kkt_solve` | `avx_gdn_kkt_solve` | libavx | `head_k=128 M=512 chunk=64` | - | 814.16 | 804.16 | 819.71 | 6 | 1.0 | - | 5.19 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=5120 K=4608 dtype=bf16 act=none M=4` | - | 808.42 | 681.63 | 1042.61 | 20 | 9.2 | - | 45.12 MiB | 32 thread(s) |
+| `gdn_chunk_scan` | `avx_gdn_chunk_scan` | libavx | `head_k=128 head_v=128 scale=0.0883883 M=64 chunk=64` | - | 799.88 | 795.52 | 802.19 | 6 | 0.4 | - | 8.40 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=5 splits=0` | - | 799.86 | 786.45 | 839.71 | 20 | 2.5 | - | 32.08 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=4608 K=4608 dtype=bf16 act=gelu M=1` | - | 797.95 | 762.01 | 880.74 | 20 | 6.1 | - | 40.54 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_mxfp4a8_tiled` | libr4d | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=512 tn=0` | 767.05 | - | 730.47 | 788.49 | 20 | 1.7 | 2463 | 88.20 MiB |  |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=6144 group=128 dtype=fp8a8 M=2` | - | 757.47 | 704.61 | 818.05 | 20 | 3.6 | - | 30.04 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=6 splits=0` | - | 737.00 | 732.43 | 745.99 | 6 | 0.9 | - | 4.09 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=6 splits=0` | - | 724.53 | 703.47 | 739.64 | 19 | 0.9 | - | 4.14 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_mxfp4a8_tiled` | libr4d | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=258 tn=0` | 697.31 | - | 665.05 | 703.47 | 16 | 1.0 | 2593 | 79.33 MiB |  |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=5 splits=0` | - | 660.06 | 653.52 | 663.85 | 11 | 0.6 | - | 4.12 MiB | 32 thread(s) |
+| `sample_typical` | `avx_sample_typical` | libavx | `n_cand=1024 M=16` | - | 653.58 | 650.90 | 662.96 | 6 | 0.9 | - | 129.50 KiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=5120 K=6144 group=128 dtype=fp8a8 M=1` | - | 651.44 | 596.90 | 709.93 | 20 | 4.5 | - | 30.02 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=1024 K=5120 group=128 dtype=fp8a8 M=18` | - | 637.02 | 611.41 | 882.38 | 20 | 5.6 | - | 5.13 MiB | 32 thread(s) |
+| `sample_logprobs` | `avx_sample_logprobs` | libavx | `n_vocab=248320 k=21 M=32` | - | 631.42 | 574.95 | 690.77 | 20 | 5.6 | - | 30.32 MiB | 32 thread(s) |
+| `sample_typical` | `avx_sample_typical` | libavx | `n_cand=1024 M=8` | - | 625.11 | 622.69 | 628.30 | 6 | 0.4 | - | 64.75 KiB | 32 thread(s) |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=25600 group=128 dtype=bf16 M=512` | - | 623.72 | 570.42 | 680.63 | 20 | 4.9 | - | 37.89 MiB | 32 thread(s) |
+| `sample_typical` | `avx_sample_typical` | libavx | `n_cand=1024 M=2` | - | 623.49 | 621.47 | 626.71 | 6 | 0.4 | - | 16.19 KiB | 32 thread(s) |
+| `sample_typical` | `avx_sample_typical` | libavx | `n_cand=1024 M=4` | - | 618.09 | 613.69 | 623.02 | 6 | 0.8 | - | 32.38 KiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=1152 K=1536 dtype=bf16 act=none M=256` | - | 598.53 | 516.18 | 626.00 | 20 | 4.3 | - | 5.25 MiB | 32 thread(s) |
+| `sample_typical` | `avx_sample_typical` | libavx | `n_cand=1024 M=1` | - | 598.31 | 597.61 | 606.63 | 6 | 0.8 | - | 8.09 KiB | 32 thread(s) |
+| `sample_mask` | `avx_sample_mask` | libavx | `n_vocab=248320 M=16` | - | 594.04 | 490.01 | 599.62 | 19 | 0.4 | - | 15.63 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=64` | - | 593.87 | 580.54 | 601.48 | 14 | 0.7 | - | 10.66 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=1152 K=1152 dtype=bf16 act=none M=256` | - | 590.65 | 545.29 | 622.18 | 20 | 3.7 | - | 4.22 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=512` | 589.59 | - | 555.31 | 620.45 | 20 | 3.8 | 2348 | 98.78 MiB |  |
+| `row_topk` | `avx_row_topk` | libavx | `N=248320 R=32 dtype=bf16 M=4 nch=0 pt1=8` | - | 580.62 | 558.35 | 596.92 | 20 | 2.5 | - | 1.90 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=5 splits=0` | - | 579.14 | 570.91 | 655.82 | 20 | 1.3 | - | 4.08 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=129` | 573.27 | - | 555.57 | 582.95 | 16 | 0.9 | 2487 | 179.24 MiB |  |
+| `row_topk` | `avx_row_topk` | libavx | `N=248320 R=32 dtype=bf16 M=8 nch=0 pt1=8` | - | 569.50 | 551.27 | 590.38 | 20 | 2.6 | - | 3.79 MiB | 32 thread(s) |
+| `row_topk` | `avx_row_topk` | libavx | `N=248320 R=32 dtype=bf16 M=2 nch=0 pt1=8` | - | 560.72 | 526.16 | 586.97 | 20 | 1.1 | - | 971.00 KiB | 32 thread(s) |
+| `sample_argmax` | `avx_sample_argmax` | libavx | `n_vocab=248320 M=32` | - | 558.73 | 479.85 | 624.92 | 20 | 8.6 | - | 30.32 MiB | 32 thread(s) |
+| `gated_quant_fp8` | `avx_gated_quant_fp8` | libavx | `n=17408 group=128 dtype=bf16 act=silu M=256` | - | 551.03 | 516.13 | 652.89 | 20 | 8.7 | - | 29.88 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=1 splits=0` | - | 543.28 | 541.66 | 546.19 | 6 | 0.4 | - | 4.02 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=4 splits=0` | - | 529.08 | 521.02 | 542.94 | 19 | 0.9 | - | 32.07 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=512` | 528.85 | - | 511.33 | 545.65 | 20 | 1.3 | 2384 | 98.59 MiB |  |
+| `gdn_conv_update` | `avx_gdn_conv_update` | libavx | `head_k=128 head_v=128 conv_width=4 q_len=64` | - | 524.95 | 520.77 | 534.34 | 14 | 0.7 | - | 3.87 MiB | 32 thread(s) |
+| `sample_typical` | `sample_typical_f32` | libr4d | `n_cand=1024 M=64` | 522.64 | - | 521.82 | 525.72 | 6 | 0.4 | 3580 | 518.00 KiB | restore 1% |
+| `sample_typical` | `sample_typical_f32` | libr4d | `n_cand=1024 M=16` | 502.86 | - | 501.94 | 504.62 | 6 | 0.3 | 3583 | 129.50 KiB | restore 1% |
+| `sample_typical` | `sample_typical_f32` | libr4d | `n_cand=1024 M=32` | 502.18 | - | 492.84 | 505.66 | 11 | 0.5 | 3581 | 259.00 KiB | restore 1% |
+| `sample_typical` | `sample_typical_f32` | libr4d | `n_cand=1024 M=8` | 502.06 | - | 500.54 | 503.78 | 6 | 0.3 | 3583 | 64.75 KiB | restore 1% |
+| `sample_typical` | `sample_typical_f32` | libr4d | `n_cand=1024 M=4` | 501.24 | - | 489.70 | 502.08 | 11 | 0.2 | 3584 | 32.38 KiB | restore 1% |
+| `sample_typical` | `sample_typical_f32` | libr4d | `n_cand=1024 M=1` | 500.94 | - | 500.32 | 503.40 | 6 | 0.3 | 3580 | 8.09 KiB | restore 1% |
+| `sample_typical` | `sample_typical_f32` | libr4d | `n_cand=1024 M=2` | 500.94 | - | 500.70 | 502.52 | 6 | 0.2 | 3582 | 16.19 KiB | restore 1% |
+| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 conv_width=4 q_len=512` | 500.42 | - | 497.10 | 503.50 | 6 | 0.6 | 3408 | 30.12 MiB | restore 4% |
+| `row_topk` | `avx_row_topk` | libavx | `N=248320 R=32 dtype=bf16 M=1 nch=0 pt1=8` | - | 485.84 | 482.85 | 487.57 | 6 | 0.5 | - | 485.50 KiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=4 splits=0` | - | 485.81 | 483.11 | 487.92 | 6 | 0.5 | - | 4.06 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=258` | 468.49 | - | 447.66 | 480.90 | 20 | 1.6 | 2598 | 91.95 MiB |  |
+| `rmsnorm_quant_fp8` | `avx_rmsnorm_quant_fp8` | libavx | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=512` | - | 452.10 | 431.35 | 505.51 | 16 | 0.9 | - | 17.59 MiB | 32 thread(s) |
+| `grid_embed` | `avx_grid_embed` | libavx | `n=1152 side=48 dtype=bf16 M=256` | - | 436.06 | 431.19 | 440.43 | 11 | 1.0 | - | 5.63 MiB | 32 thread(s) |
+| `gemm_nt` | `avx_gemm_nt` | libavx | `N=1280 K=5120 dtype=bf16 M=64 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 416.08 | 403.73 | 431.95 | 20 | 2.1 | - | 13.28 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=258` | 406.86 | - | 392.14 | 415.62 | 20 | 1.8 | 2506 | 89.37 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=512` | 402.12 | - | 376.64 | 417.84 | 20 | 2.5 | 2390 | 74.59 MiB |  |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=4 splits=0` | - | 385.75 | 376.81 | 393.33 | 20 | 1.5 | - | 4.09 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_mxfp4a8_tiled` | libr4d | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=129 tn=0` | 385.10 | - | 383.40 | 391.10 | 6 | 1.0 | 2907 | 74.82 MiB |  |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=2 splits=0` | - | 384.39 | 353.17 | 781.10 | 20 | 51.5 | - | 4.05 MiB | 32 thread(s) |
+| `attn_dense` | `avx_attn_dense` | libavx | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=128` | - | 383.94 | 383.24 | 387.50 | 6 | 0.6 | - | 72.01 KiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=3456 K=1152 dtype=bf16 act=none M=64` | - | 382.23 | 319.13 | 398.44 | 20 | 8.6 | - | 8.58 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=1152 K=1536 dtype=bf16 act=none M=128` | - | 374.76 | 358.45 | 389.57 | 20 | 1.8 | - | 4.31 MiB | 32 thread(s) |
+| `sample_logprobs` | `avx_sample_logprobs` | libavx | `n_vocab=248320 k=21 M=16` | - | 374.13 | 300.09 | 413.46 | 20 | 6.2 | - | 15.16 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=66` | - | 365.60 | 328.89 | 407.69 | 20 | 5.3 | - | 1.70 MiB | 32 thread(s) |
+| `gdn_chunk_scan` | `avx_gdn_chunk_scan` | libavx | `head_k=128 head_v=128 scale=0.0883883 M=32 chunk=64` | - | 364.51 | 360.56 | 367.35 | 6 | 0.9 | - | 7.20 MiB | 32 thread(s) |
+| `sample_mask` | `avx_sample_mask` | libavx | `n_vocab=248320 M=8` | - | 351.65 | 269.01 | 357.10 | 20 | 2.4 | - | 7.82 MiB | 32 thread(s) |
+| `sample_argmax` | `avx_sample_argmax` | libavx | `n_vocab=248320 M=16` | - | 351.24 | 221.39 | 400.37 | 20 | 3.3 | - | 15.16 MiB | 32 thread(s) |
+| `gemm_nt` | `avx_gemm_nt` | libavx | `N=1280 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 350.71 | 317.72 | 362.51 | 20 | 3.4 | - | 12.92 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=32` | - | 348.43 | 339.95 | 367.25 | 20 | 2.6 | - | 10.06 MiB | 32 thread(s) |
+| `gdn_recurrent_update` | `avx_gdn_recurrent_update` | libavx | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu state_form=anchor q_len=16` | - | 345.14 | 315.03 | 358.19 | 20 | 4.6 | - | 48.69 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=128` | 340.66 | - | 337.48 | 346.38 | 14 | 0.7 | 2516 | 179.17 MiB |  |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=1024 K=5120 group=128 dtype=fp8a8 M=9` | - | 335.64 | 322.70 | 348.13 | 20 | 3.1 | - | 5.06 MiB | 32 thread(s) |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=25600 group=128 dtype=bf16 M=256` | - | 332.99 | 315.39 | 342.81 | 20 | 1.8 | - | 18.95 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=65` | 330.58 | - | 320.38 | 333.82 | 20 | 1.4 | 2669 | 174.66 MiB |  |
+| `gdn_kkt_solve` | `avx_gdn_kkt_solve` | libavx | `head_k=128 M=256 chunk=64` | - | 329.40 | 313.19 | 348.31 | 20 | 3.7 | - | 2.59 MiB | 32 thread(s) |
+| `gemm_nt` | `avx_gemm_nt` | libavx | `N=96 K=5120 dtype=bf16 M=512 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 328.93 | 323.71 | 334.13 | 14 | 0.9 | - | 6.03 MiB | 32 thread(s) |
+| `sample_topk` | `avx_sample_topk` | libavx | `n_vocab=248320 M=2` | - | 328.91 | 328.49 | 333.12 | 6 | 0.7 | - | 1.90 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=1 splits=0` | - | 327.66 | 282.50 | 369.93 | 20 | 8.8 | - | 32.02 MiB | 32 thread(s) |
+| `gemm_nt` | `avx_gemm_nt` | libavx | `N=96 K=5120 dtype=bf16 M=260 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 326.63 | 292.10 | 365.35 | 20 | 5.2 | - | 3.52 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=2 splits=0` | - | 323.67 | 303.34 | 345.53 | 20 | 4.6 | - | 32.04 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=1152 K=1152 dtype=bf16 act=none M=128` | - | 321.10 | 300.06 | 329.31 | 20 | 2.4 | - | 3.38 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=129` | 319.97 | - | 317.26 | 322.72 | 6 | 0.9 | 2809 | 88.48 MiB |  |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=1 splits=0` | - | 314.54 | 250.20 | 348.70 | 20 | 5.6 | - | 4.02 MiB | 32 thread(s) |
+| `gemm_nt_q_gated` | `gemm_fp8a8_gated_nt_m16` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=64` | 313.03 | - | 309.97 | 320.22 | 14 | 0.5 | 3163 | 173.56 MiB |  |
+| `sample_temp` | `avx_sample_temp` | libavx | `n_vocab=248320 M=32` | - | 312.91 | 280.06 | 322.87 | 20 | 2.4 | - | 30.32 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=64` | 312.22 | - | 310.01 | 313.55 | 11 | 0.4 | 3046 | 174.59 MiB |  |
+| `gemm_nt` | `avx_gemm_nt` | libavx | `N=1280 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 307.86 | 244.44 | 320.46 | 20 | 2.3 | - | 12.60 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=16` | - | 306.30 | 265.03 | 316.86 | 20 | 5.1 | - | 9.76 MiB | 32 thread(s) |
+| `sample_temp` | `avx_sample_temp` | libavx | `n_vocab=248320 M=8` | - | 305.64 | 108.86 | 309.26 | 20 | 16.9 | - | 7.58 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=1152 K=4304 dtype=bf16 act=none M=8` | - | 305.32 | 279.09 | 334.97 | 20 | 5.3 | - | 9.56 MiB | 32 thread(s) |
+| `gemm_nt` | `avx_gemm_nt` | libavx | `N=1280 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 304.88 | 224.81 | 314.90 | 20 | 3.1 | - | 12.52 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=36` | 303.91 | - | 300.66 | 308.30 | 14 | 0.9 | 3240 | 172.59 MiB |  |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=1152 K=4304 dtype=bf16 act=none M=64` | - | 301.92 | 282.77 | 324.81 | 20 | 2.4 | - | 10.27 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=258` | 301.59 | - | 291.93 | 305.78 | 20 | 1.5 | 2584 | 67.35 MiB |  |
+| `gemm_nt_q_gated` | `gemm_fp8a8_gated_nt_m16` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=16` | 297.02 | - | 294.41 | 305.04 | 14 | 0.8 | 3364 | 170.91 MiB |  |
+| `gemm_nt_q_gated` | `gemm_fp8a8_gated_nt_m16` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=32` | 296.37 | - | 295.43 | 309.43 | 14 | 0.5 | 3362 | 171.79 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=18` | 295.75 | - | 294.70 | 300.05 | 11 | 0.8 | 3403 | 171.31 MiB |  |
+| `gemm_nt` | `avx_gemm_nt` | libavx | `N=96 K=5120 dtype=bf16 M=130 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 293.94 | 172.93 | 303.00 | 20 | 13.4 | - | 2.23 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=9` | 293.65 | - | 292.95 | 294.46 | 11 | 0.2 | 3423 | 170.66 MiB |  |
+| `gemm_nt_q_gated` | `gemm_fp8a8_gated_nt_m16` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=8` | 293.65 | - | 290.72 | 306.20 | 14 | 0.8 | 3362 | 170.46 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=8` | 293.38 | - | 292.30 | 294.28 | 11 | 0.3 | 3426 | 170.59 MiB |  |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=128 ks=0 bk=0 nt=0` | 293.28 | - | 291.12 | 294.83 | 6 | 0.6 | 2900 | 74.79 MiB |  |
+| `gemm_nt_q_gated` | `gemm_fp8a8_gated_nt_m16` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=4` | 292.43 | - | 290.22 | 294.61 | 11 | 0.6 | 3358 | 170.24 MiB |  |
+| `gemm_nt_q_gated` | `gemm_fp8a8_gated_nt_m16` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=2` | 291.85 | - | 289.88 | 294.60 | 11 | 0.8 | 3368 | 170.13 MiB |  |
+| `gemm_nt_q_gated` | `gemm_fp8a8_gated_nt_m16` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 act=silu M=1` | 291.25 | - | 289.78 | 293.63 | 11 | 0.6 | 3366 | 170.08 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=4` | 290.72 | - | 289.60 | 294.97 | 11 | 0.8 | 3436 | 170.31 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=2` | 289.21 | - | 288.26 | 298.21 | 14 | 0.2 | 3374 | 170.16 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=4608 K=4608 dtype=bf16 act=gelu M=512` | 289.13 | - | 277.97 | 292.14 | 20 | 1.1 | 2952 | 54.01 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=1` | 288.76 | - | 288.34 | 289.82 | 6 | 0.3 | 2787 | 170.09 MiB |  |
+| `gemm_nt` | `avx_gemm_nt` | libavx | `N=1280 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 287.15 | 183.92 | 308.89 | 20 | 13.1 | - | 12.70 MiB | 32 thread(s) |
+| `gated_quant_fp8` | `avx_gated_quant_fp8` | libavx | `n=17408 group=128 dtype=bf16 act=silu M=128` | - | 286.78 | 270.00 | 303.39 | 20 | 3.4 | - | 14.94 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=1024 K=5120 group=128 dtype=fp8a8 M=8` | - | 286.36 | 276.96 | 306.16 | 20 | 2.3 | - | 5.06 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=5120 K=4608 dtype=bf16 act=none M=512` | 285.93 | - | 271.91 | 289.51 | 20 | 1.2 | 2873 | 59.51 MiB |  |
+| `gemm_nt` | `avx_gemm_nt` | libavx | `N=1280 K=5120 dtype=bf16 M=1 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 284.28 | 213.54 | 297.19 | 20 | 4.1 | - | 12.51 MiB | 32 thread(s) |
+| `gemm_nt` | `avx_gemm_nt` | libavx | `N=1280 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 284.07 | 254.48 | 289.54 | 20 | 1.4 | - | 12.71 MiB | 32 thread(s) |
+| `gemm_nt` | `avx_gemm_nt` | libavx | `N=1280 K=5120 dtype=bf16 M=4 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 281.48 | 231.13 | 352.26 | 20 | 4.9 | - | 12.55 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=1` | - | 272.05 | 179.04 | 286.27 | 20 | 3.4 | - | 9.48 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=2` | - | 268.33 | 265.19 | 273.31 | 16 | 0.6 | - | 9.50 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=8` | - | 267.23 | 213.51 | 275.29 | 20 | 1.6 | - | 9.61 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=129` | 264.96 | - | 258.92 | 270.47 | 14 | 1.0 | 2666 | 84.69 MiB |  |
+| `scatter_rows` | `avx_scatter_rows` | libavx | `n=5120 dtype=bf16 M=512` | - | 264.70 | 263.81 | 265.19 | 6 | 0.3 | - | 25.00 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=2 splits=0` | - | 249.37 | 217.85 | 256.04 | 19 | 1.0 | - | 4.03 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=4` | - | 247.15 | 243.26 | 252.95 | 20 | 1.3 | - | 9.54 MiB | 32 thread(s) |
+| `rmsnorm_quant_fp8` | `avx_rmsnorm_quant_fp8` | libavx | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=256` | - | 245.09 | 229.45 | 280.11 | 20 | 7.2 | - | 8.80 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=3456 K=1152 dtype=bf16 act=none M=32` | - | 238.51 | 214.15 | 269.05 | 20 | 5.3 | - | 8.09 MiB | 32 thread(s) |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=1024 K=5120 group=128 dtype=fp8a8 M=4` | - | 236.90 | 221.83 | 241.33 | 20 | 3.1 | - | 5.03 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=3456 K=1152 dtype=bf16 act=none M=4` | - | 236.68 | 226.32 | 248.01 | 20 | 1.8 | - | 7.66 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=1152 K=4304 dtype=bf16 act=none M=4` | - | 235.41 | 209.56 | 239.77 | 19 | 0.8 | - | 9.51 MiB | 32 thread(s) |
+| `gdn_conv_update` | `avx_gdn_conv_update` | libavx | `head_k=128 head_v=128 conv_width=4 q_len=32` | - | 235.14 | 229.97 | 288.84 | 20 | 2.8 | - | 1.99 MiB | 32 thread(s) |
+| `sample_logprobs` | `sample_logprobs_f32` | libr4d | `n_vocab=248320 k=21 M=64` | 232.14 | - | 231.89 | 232.43 | 6 | 0.1 | 3547 | 60.64 MiB |  |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=1152 K=4304 dtype=bf16 act=none M=32` | - | 225.35 | 198.83 | 230.88 | 20 | 1.3 | - | 9.86 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=1152 K=4304 dtype=bf16 act=none M=2` | - | 223.68 | 210.22 | 228.12 | 20 | 2.0 | - | 9.48 MiB | 32 thread(s) |
+| `grid_embed` | `avx_grid_embed` | libavx | `n=1152 side=48 dtype=bf16 M=128` | - | 223.12 | 216.82 | 230.79 | 20 | 1.1 | - | 5.35 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=128` | 220.63 | - | 211.89 | 224.07 | 20 | 1.5 | 2883 | 88.45 MiB |  |
+| `sample_topk` | `sample_topk_f32` | libr4d | `n_vocab=248320 M=64` | 220.09 | - | 218.23 | 220.64 | 6 | 0.5 | 3518 | 60.69 MiB |  |
+| `sample_mask` | `avx_sample_mask` | libavx | `n_vocab=248320 M=32` | - | 219.13 | 154.97 | 224.23 | 20 | 2.8 | - | 31.26 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=1152 K=4304 dtype=bf16 act=none M=1` | - | 217.43 | 175.19 | 219.52 | 16 | 0.8 | - | 9.47 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=3456 K=1152 dtype=bf16 act=none M=2` | - | 215.46 | 166.75 | 254.30 | 20 | 7.0 | - | 7.63 MiB | 32 thread(s) |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=512` | 214.56 | - | 198.20 | 219.09 | 20 | 1.6 | 3024 | 16.00 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=65` | 214.19 | - | 208.50 | 217.51 | 16 | 0.8 | 3072 | 86.76 MiB |  |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=64 ks=0 bk=0 nt=0` | 205.57 | - | 203.58 | 207.19 | 6 | 0.9 | 2899 | 100.20 MiB |  |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=1152 K=4304 dtype=bf16 act=none M=16` | - | 204.35 | 185.19 | 212.78 | 20 | 3.1 | - | 9.66 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=129` | 202.10 | - | 195.49 | 207.26 | 20 | 1.3 | 2650 | 63.68 MiB |  |
+| `gdn_recurrent_update` | `avx_gdn_recurrent_update` | libavx | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu state_form=anchor q_len=8` | - | 201.08 | 196.28 | 213.17 | 20 | 1.7 | - | 24.35 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=3456 K=1152 dtype=bf16 act=none M=8` | - | 199.95 | 191.73 | 214.36 | 20 | 3.5 | - | 7.72 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=3456 K=1152 dtype=bf16 act=none M=1` | - | 199.76 | 112.72 | 211.82 | 20 | 4.2 | - | 7.62 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=512` | 199.36 | - | 190.60 | 203.19 | 20 | 1.5 | 2486 | 38.10 MiB |  |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=1152 K=1536 dtype=bf16 act=none M=64` | - | 199.03 | 183.59 | 205.69 | 20 | 3.4 | - | 3.85 MiB | 32 thread(s) |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=33` | 197.51 | - | 196.73 | 198.72 | 6 | 0.5 | 3438 | 4.77 MiB |  |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=11` | 197.34 | - | 195.04 | 198.44 | 11 | 0.5 | 3438 | 4.26 MiB |  |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=32` | 197.14 | - | 193.12 | 198.01 | 14 | 1.0 | 3439 | 4.75 MiB |  |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=17` | 197.07 | - | 192.48 | 197.99 | 14 | 0.9 | 3437 | 4.40 MiB |  |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=16` | 197.01 | - | 196.40 | 198.24 | 6 | 0.5 | 3440 | 4.38 MiB |  |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=3456 K=1152 dtype=bf16 act=none M=16` | - | 193.66 | 181.85 | 205.37 | 20 | 4.5 | - | 7.85 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=65 ks=0 bk=0 nt=0` | 187.40 | - | 182.42 | 190.80 | 20 | 1.0 | 2900 | 72.58 MiB |  |
+| `row_topk` | `rowtopk_bf16` | libr4d | `N=248320 R=32 dtype=bf16 M=56 nch=0 pt1=8` | 187.00 | - | 185.74 | 188.32 | 6 | 0.7 | 3443 | 26.55 MiB |  |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=264` | 184.08 | - | 182.78 | 185.81 | 6 | 0.8 | 3408 | 10.19 MiB |  |
+| `gdn_chunk_scan` | `avx_gdn_chunk_scan` | libavx | `head_k=128 head_v=128 scale=0.0883883 M=16 chunk=64` | - | 181.36 | 177.14 | 258.81 | 19 | 1.0 | - | 6.60 MiB | 32 thread(s) |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=132` | 177.57 | - | 176.25 | 178.62 | 6 | 0.7 | 3421 | 7.09 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=65` | 177.26 | - | 173.21 | 179.56 | 16 | 0.6 | 2937 | 82.37 MiB |  |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=66` | 175.95 | - | 175.57 | 177.34 | 6 | 0.5 | 3432 | 5.55 MiB |  |
+| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 conv_width=4 q_len=256` | 174.84 | - | 174.04 | 176.19 | 6 | 0.6 | 3408 | 15.12 MiB | restore 5% |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=128` | 173.86 | - | 166.74 | 177.28 | 20 | 1.4 | 2761 | 84.65 MiB |  |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=36 ks=0 bk=0 nt=0` | 171.34 | - | 170.32 | 173.08 | 6 | 0.8 | 3063 | 98.20 MiB |  |
+| `gdn_kkt_solve` | `avx_gdn_kkt_solve` | libavx | `head_k=128 M=128 chunk=64` | - | 169.43 | 156.29 | 201.98 | 20 | 12.5 | - | 1.30 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=4608 K=4608 dtype=bf16 act=gelu M=256` | 165.32 | - | 160.21 | 167.54 | 14 | 0.9 | 3144 | 47.26 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=5120 K=4608 dtype=bf16 act=none M=256` | 164.64 | - | 153.33 | 168.04 | 19 | 0.8 | 3078 | 52.26 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=258` | 163.99 | - | 158.78 | 166.89 | 19 | 1.0 | 2789 | 34.08 MiB |  |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=18 ks=0 bk=0 nt=0` | 161.82 | - | 161.66 | 162.08 | 6 | 0.1 | 3273 | 96.91 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=64` | 159.92 | - | 159.44 | 160.28 | 11 | 0.2 | 3235 | 86.73 MiB |  |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=64 ks=0 bk=0 nt=0` | 158.50 | - | 157.61 | 160.32 | 6 | 0.9 | 3116 | 72.55 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=36` | 156.37 | - | 155.63 | 159.46 | 14 | 0.3 | 3359 | 85.98 MiB |  |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=1152 K=1152 dtype=bf16 act=none M=64` | - | 155.73 | 149.29 | 162.33 | 20 | 3.1 | - | 2.96 MiB | 32 thread(s) |
+| `gdn_conv_update` | `avx_gdn_conv_update` | libavx | `head_k=128 head_v=128 conv_width=4 q_len=16` | - | 153.99 | 150.45 | 162.61 | 20 | 1.4 | - | 1.05 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=9 ks=0 bk=0 nt=0` | 153.17 | - | 153.06 | 153.45 | 11 | 0.1 | 3321 | 96.27 MiB |  |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=8 ks=0 bk=0 nt=0` | 152.90 | - | 152.77 | 153.79 | 6 | 0.3 | 3314 | 96.20 MiB |  |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=4 ks=0 bk=0 nt=0` | 150.47 | - | 150.16 | 150.88 | 11 | 0.2 | 3327 | 95.91 MiB |  |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=1024 K=5120 group=128 dtype=fp8a8 M=2` | - | 150.36 | 143.13 | 151.94 | 20 | 1.1 | - | 5.01 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=18` | 149.38 | - | 148.74 | 158.51 | 14 | 0.4 | 3361 | 85.49 MiB |  |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=2 ks=0 bk=0 nt=0` | 149.31 | - | 149.18 | 149.80 | 6 | 0.2 | 3315 | 95.77 MiB |  |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=34816 K=5120 group=32 dtype=mxfp4a8 M=1 ks=0 bk=0 nt=0` | 148.63 | - | 148.49 | 149.00 | 6 | 0.2 | 3401 | 95.70 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=64` | 147.06 | - | 146.64 | 147.38 | 11 | 0.2 | 3304 | 82.33 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=8` | 146.70 | - | 146.38 | 153.31 | 14 | 0.2 | 3364 | 85.23 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=9` | 146.66 | - | 146.12 | 158.57 | 14 | 0.3 | 3367 | 85.25 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=4` | 146.09 | - | 145.46 | 153.90 | 14 | 0.3 | 3362 | 85.12 MiB |  |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=5120 group=128 dtype=bf16 M=512` | - | 145.91 | 142.74 | 146.67 | 11 | 0.7 | - | 7.58 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=1` | 145.45 | - | 145.14 | 165.28 | 14 | 0.4 | 3223 | 85.04 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=2` | 145.37 | - | 145.00 | 151.06 | 14 | 0.1 | 3366 | 85.06 MiB |  |
+| `gdn_recurrent_update` | `avx_gdn_recurrent_update` | libavx | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu state_form=anchor q_len=4` | - | 144.34 | 138.17 | 167.26 | 20 | 4.9 | - | 18.17 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=36` | 143.76 | - | 143.37 | 144.38 | 11 | 0.3 | 3416 | 81.32 MiB |  |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=36 ks=0 bk=0 nt=0` | 140.39 | - | 139.45 | 141.91 | 6 | 0.9 | 3336 | 71.57 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=18` | 140.13 | - | 139.95 | 141.42 | 11 | 0.5 | 3418 | 80.66 MiB |  |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=1152 K=1536 dtype=bf16 act=none M=8` | - | 140.12 | 126.97 | 150.30 | 20 | 5.9 | - | 3.44 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=9` | 138.83 | - | 138.55 | 144.07 | 14 | 0.1 | 3406 | 80.34 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=8` | 138.44 | - | 138.28 | 141.92 | 14 | 0.3 | 3416 | 80.30 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=4` | 137.75 | - | 137.48 | 143.69 | 14 | 0.1 | 3404 | 80.15 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=2` | 137.11 | - | 136.92 | 139.34 | 11 | 0.9 | 3410 | 80.08 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=1` | 137.03 | - | 136.87 | 137.27 | 11 | 0.1 | 3407 | 80.05 MiB |  |
+| `grid_embed` | `avx_grid_embed` | libavx | `n=1152 side=48 dtype=bf16 M=64` | - | 137.01 | 123.27 | 159.01 | 20 | 4.1 | - | 5.20 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=18 ks=0 bk=0 nt=0` | 136.78 | - | 136.48 | 136.91 | 6 | 0.2 | 3334 | 70.94 MiB |  |
+| `gdn_recurrent_update` | `avx_gdn_recurrent_update` | libavx | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu state_form=anchor q_len=2` | - | 136.42 | 98.48 | 174.31 | 20 | 8.6 | - | 18.09 MiB | 32 thread(s) |
+| `row_topk` | `rowtopk_bf16` | libr4d | `N=248320 R=32 dtype=bf16 M=32 nch=0 pt1=8` | 134.50 | - | 133.62 | 136.28 | 6 | 1.0 | 3447 | 15.17 MiB |  |
+| `sample_logprobs` | `sample_logprobs_f32` | libr4d | `n_vocab=248320 k=21 M=8` | 133.29 | - | 128.50 | 133.70 | 16 | 1.0 | 3582 | 7.58 MiB |  |
+| `sample_logprobs` | `sample_logprobs_f32` | libr4d | `n_vocab=248320 k=21 M=4` | 133.20 | - | 130.59 | 133.79 | 16 | 0.3 | 3583 | 3.79 MiB |  |
+| `sample_logprobs` | `sample_logprobs_f32` | libr4d | `n_vocab=248320 k=21 M=2` | 132.84 | - | 132.68 | 133.22 | 6 | 0.2 | 3588 | 1.90 MiB |  |
+| `sample_logprobs` | `sample_logprobs_f32` | libr4d | `n_vocab=248320 k=21 M=1` | 132.67 | - | 131.02 | 133.08 | 6 | 0.8 | 3584 | 970.27 KiB |  |
+| `sample_logprobs` | `sample_logprobs_f32` | libr4d | `n_vocab=248320 k=21 M=32` | 132.61 | - | 132.13 | 133.56 | 6 | 0.5 | 3564 | 30.32 MiB |  |
+| `gemm_nt_q` | `avx_gemm_nt_q` | libavx | `N=1024 K=5120 group=128 dtype=fp8a8 M=1` | - | 129.89 | 109.93 | 132.42 | 20 | 1.7 | - | 5.01 MiB | 32 thread(s) |
+| `sample_logprobs` | `sample_logprobs_f32` | libr4d | `n_vocab=248320 k=21 M=16` | 127.96 | - | 127.52 | 128.81 | 6 | 0.5 | 3576 | 15.16 MiB |  |
+| `sample_topp` | `sample_topp_f32` | libr4d | `n_cand=1024 M=64` | 127.45 | - | 126.42 | 127.97 | 6 | 0.6 | 3564 | 518.00 KiB | restore 4% |
+| `sample_topp` | `sample_topp_f32` | libr4d | `n_cand=1024 M=16` | 127.32 | - | 127.22 | 127.40 | 6 | 0.1 | 3562 | 129.50 KiB | restore 4% |
+| `sample_topp` | `sample_topp_f32` | libr4d | `n_cand=1024 M=32` | 126.63 | - | 123.88 | 127.56 | 14 | 0.9 | 3560 | 259.00 KiB | restore 4% |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=25600 group=128 dtype=bf16 M=128` | - | 126.52 | 124.06 | 140.36 | 19 | 1.0 | - | 9.47 MiB | 32 thread(s) |
+| `sample_topp` | `sample_topp_f32` | libr4d | `n_cand=1024 M=1` | 125.50 | - | 115.49 | 126.06 | 16 | 1.0 | 3540 | 8.09 KiB | restore 4% |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=9 ks=0 bk=0 nt=0` | 123.92 | - | 123.82 | 124.18 | 6 | 0.1 | 3364 | 70.63 MiB |  |
+| `sample_topp` | `sample_topp_f32` | libr4d | `n_cand=1024 M=8` | 123.82 | - | 120.90 | 124.05 | 11 | 1.0 | 3560 | 64.75 KiB | restore 4% |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=4608 K=4608 dtype=bf16 act=gelu M=128` | 123.73 | - | 118.46 | 127.55 | 20 | 2.3 | 3376 | 43.88 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=128` | 123.66 | - | 122.33 | 124.57 | 11 | 0.9 | 2806 | 63.65 MiB |  |
+| `sample_topk` | `sample_topk_f32` | libr4d | `n_vocab=248320 M=8` | 123.43 | - | 121.22 | 123.57 | 6 | 1.0 | 3520 | 7.59 MiB |  |
+| `sample_topk` | `sample_topk_f32` | libr4d | `n_vocab=248320 M=4` | 123.20 | - | 118.37 | 123.63 | 19 | 0.4 | 3521 | 3.79 MiB |  |
+| `sample_topp` | `sample_topp_f32` | libr4d | `n_cand=1024 M=4` | 122.93 | - | 120.15 | 123.36 | 16 | 0.8 | 3551 | 32.38 KiB | restore 4% |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=8 ks=0 bk=0 nt=0` | 122.72 | - | 122.55 | 122.84 | 6 | 0.1 | 3358 | 70.59 MiB |  |
+| `sample_topk` | `sample_topk_f32` | libr4d | `n_vocab=248320 M=1` | 122.61 | - | 118.45 | 123.07 | 11 | 0.4 | 3513 | 971.09 KiB |  |
+| `sample_topk` | `sample_topk_f32` | libr4d | `n_vocab=248320 M=2` | 121.91 | - | 119.71 | 122.61 | 14 | 0.8 | 3518 | 1.90 MiB |  |
+| `sample_topk` | `sample_topk_f32` | libr4d | `n_vocab=248320 M=32` | 120.70 | - | 120.48 | 121.41 | 6 | 0.4 | 3522 | 30.35 MiB |  |
+| `gdn_recurrent_update` | `avx_gdn_recurrent_update` | libavx | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu state_form=anchor q_len=1` | - | 120.64 | 106.87 | 169.65 | 20 | 14.4 | - | 18.04 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=65` | 120.37 | - | 119.11 | 121.05 | 11 | 0.5 | 3153 | 61.86 MiB |  |
+| `sample_pick` | `sample_pick_f32` | libr4d | `n_cand=1024 M=64` | 120.27 | - | 115.65 | 120.72 | 19 | 0.9 | 3584 | 518.25 KiB |  |
+| `gated_quant_fp8` | `avx_gated_quant_fp8` | libavx | `n=17408 group=128 dtype=bf16 act=silu M=64` | - | 119.66 | 118.73 | 121.44 | 11 | 1.0 | - | 7.47 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=1152 K=1152 dtype=bf16 act=none M=8` | - | 119.66 | 113.80 | 125.93 | 20 | 3.1 | - | 2.59 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=5120 K=4608 dtype=bf16 act=none M=128` | 119.61 | - | 115.50 | 125.05 | 20 | 1.9 | 3296 | 48.63 MiB |  |
+| `sample_pick` | `sample_pick_f32` | libr4d | `n_cand=1024 M=8` | 118.81 | - | 116.32 | 118.90 | 11 | 0.2 | 3586 | 64.78 KiB |  |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=6144 group=128 dtype=bf16 M=512` | - | 118.79 | 116.01 | 171.77 | 20 | 1.1 | - | 9.09 MiB | 32 thread(s) |
+| `sample_pick` | `sample_pick_f32` | libr4d | `n_cand=1024 M=32` | 118.67 | - | 118.44 | 119.01 | 11 | 0.2 | 3585 | 259.12 KiB |  |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=33` | - | 118.06 | 110.02 | 139.06 | 20 | 4.3 | - | 888.02 KiB | 32 thread(s) |
+| `row_topk` | `rowtopk_bf16` | libr4d | `N=248320 R=32 dtype=bf16 M=8 nch=0 pt1=8` | 117.53 | - | 114.66 | 118.00 | 16 | 0.5 | 3457 | 3.79 MiB |  |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=64 ks=0 bk=0 nt=0` | 116.87 | - | 114.81 | 117.66 | 14 | 0.9 | 3005 | 49.53 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=4608 K=4608 dtype=bf16 act=gelu M=64` | 116.79 | - | 115.42 | 119.12 | 14 | 0.7 | 3453 | 42.20 MiB |  |
+| `sample_pick` | `sample_pick_f32` | libr4d | `n_cand=1024 M=16` | 116.77 | - | 111.51 | 117.17 | 19 | 0.2 | 3586 | 129.56 KiB |  |
+| `sample_topk` | `sample_topk_f32` | libr4d | `n_vocab=248320 M=16` | 116.62 | - | 116.38 | 117.09 | 6 | 0.3 | 3522 | 15.17 MiB |  |
+| `sample_mask` | `sample_mask_f32` | libr4d | `n_vocab=248320 M=64` | 116.22 | - | 115.26 | 118.68 | 14 | 0.9 | 3505 | 62.53 MiB | restore 65% |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=129` | 116.20 | - | 114.09 | 116.60 | 11 | 0.9 | 2900 | 32.04 MiB |  |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=4 ks=0 bk=0 nt=0` | 115.88 | - | 115.49 | 116.99 | 6 | 0.6 | 3362 | 70.45 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=5120 K=4608 dtype=bf16 act=none M=64` | 115.51 | - | 114.51 | 116.29 | 6 | 0.8 | 3416 | 46.82 MiB |  |
+| `row_topk` | `rowtopk_bf16` | libr4d | `N=248320 R=32 dtype=bf16 M=16 nch=0 pt1=8` | 112.60 | - | 109.02 | 113.12 | 14 | 0.8 | 3452 | 7.59 MiB |  |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=2 ks=0 bk=0 nt=0` | 112.53 | - | 112.21 | 113.33 | 6 | 0.5 | 3352 | 70.38 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=64` | 111.61 | - | 110.74 | 112.22 | 11 | 0.5 | 3348 | 61.83 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=4608 K=4608 dtype=bf16 act=gelu M=32` | 111.53 | - | 108.85 | 113.70 | 19 | 0.9 | 3430 | 41.35 MiB |  |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=1152 K=1536 dtype=bf16 act=none M=4` | - | 111.37 | 90.31 | 116.63 | 20 | 4.2 | - | 3.41 MiB | 32 thread(s) |
+| `sample_topp` | `sample_topp_f32` | libr4d | `n_cand=1024 M=2` | 111.37 | - | 108.92 | 111.72 | 20 | 1.1 | 3552 | 16.19 KiB | restore 4% |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=5120 K=25600 group=32 dtype=mxfp4a8 M=1 ks=0 bk=0 nt=0` | 110.87 | - | 110.68 | 111.03 | 11 | 0.1 | 3344 | 70.35 MiB |  |
+| `add` | `avx_add` | libavx | `n=5120 dtype=bf16 M=512` | - | 110.76 | 107.78 | 112.33 | 16 | 0.9 | - | 15.00 MiB | 32 thread(s) |
+| `row_topk` | `rowtopk_bf16` | libr4d | `N=248320 R=32 dtype=bf16 M=4 nch=0 pt1=8` | 110.60 | - | 110.37 | 110.83 | 6 | 0.2 | 3456 | 1.90 MiB |  |
+| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 conv_width=4 q_len=128` | 109.87 | - | 104.83 | 110.25 | 19 | 0.7 | 3396 | 7.62 MiB | restore 3% |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=5120 K=4608 dtype=bf16 act=none M=32` | 109.50 | - | 108.71 | 110.89 | 6 | 1.0 | 3467 | 45.92 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=36` | 109.34 | - | 109.06 | 109.85 | 11 | 0.4 | 3353 | 61.03 MiB |  |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=1152 K=1536 dtype=bf16 act=none M=32` | - | 107.27 | 92.40 | 121.14 | 20 | 4.0 | - | 3.61 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=5120 K=4608 dtype=bf16 act=none M=8` | 106.85 | - | 105.48 | 107.33 | 6 | 0.9 | 3452 | 45.24 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=5120 K=4608 dtype=bf16 act=none M=1` | 106.57 | - | 103.19 | 111.33 | 20 | 3.1 | 3263 | 45.04 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=5120 K=4608 dtype=bf16 act=none M=16` | 106.35 | - | 105.93 | 107.57 | 6 | 0.8 | 3458 | 45.46 MiB |  |
+| `sample_argmax` | `sample_argmax_f32` | libr4d | `n_vocab=248320 M=64` | 106.35 | - | 106.17 | 106.64 | 6 | 0.2 | 3534 | 60.63 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=4608 K=4608 dtype=bf16 act=gelu M=16` | 106.09 | - | 105.37 | 106.58 | 6 | 0.6 | 3502 | 40.93 MiB |  |
+| `grid_embed` | `avx_grid_embed` | libavx | `n=1152 side=48 dtype=bf16 M=8` | - | 105.61 | 105.04 | 108.09 | 14 | 0.4 | - | 5.08 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=18` | 105.59 | - | 105.43 | 105.65 | 11 | 0.1 | 3352 | 60.52 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=4608 K=4608 dtype=bf16 act=gelu M=8` | 105.28 | - | 104.89 | 106.23 | 6 | 0.6 | 3484 | 40.72 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=5120 K=4608 dtype=bf16 act=none M=4` | 105.18 | - | 104.62 | 106.62 | 11 | 0.8 | 3422 | 45.12 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=5120 K=4608 dtype=bf16 act=none M=2` | 104.52 | - | 103.66 | 105.28 | 6 | 0.8 | 3443 | 45.07 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=9` | 104.32 | - | 104.25 | 104.91 | 11 | 0.3 | 3357 | 60.26 MiB |  |
+| `gated_quant_fp8` | `gated_quant_fp8` | libr4d | `n=17408 group=128 dtype=bf16 act=silu M=512` | 104.25 | - | 103.95 | 104.38 | 11 | 0.2 | 3341 | 59.77 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=8` | 104.16 | - | 104.04 | 104.32 | 11 | 0.1 | 3359 | 60.24 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=4608 K=4608 dtype=bf16 act=gelu M=1` | 104.04 | - | 103.03 | 104.43 | 6 | 0.7 | 3412 | 40.54 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=4608 K=4608 dtype=bf16 act=gelu M=4` | 103.99 | - | 103.72 | 104.41 | 6 | 0.3 | 3464 | 40.61 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=4608 K=4608 dtype=bf16 act=gelu M=2` | 103.96 | - | 103.09 | 104.72 | 6 | 0.8 | 3454 | 40.56 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=4` | 103.63 | - | 103.51 | 105.57 | 11 | 1.0 | 3361 | 60.12 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=1` | 103.53 | - | 102.99 | 117.00 | 14 | 0.2 | 2831 | 60.04 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=2` | 103.52 | - | 103.33 | 105.95 | 14 | 0.1 | 3361 | 60.06 MiB |  |
+| `gdn_kkt_solve` | `avx_gdn_kkt_solve` | libavx | `head_k=128 M=64 chunk=64` | - | 103.19 | 101.52 | 104.45 | 20 | 1.1 | - | 664.01 KiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=36 ks=0 bk=0 nt=0` | 101.73 | - | 101.22 | 102.59 | 11 | 0.7 | 3208 | 48.78 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=1152 K=4304 dtype=bf16 act=none M=512` | 100.40 | - | 98.95 | 102.68 | 19 | 0.8 | 3357 | 15.91 MiB |  |
+| `attn_dense` | `avx_attn_dense` | libavx | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=64` | - | 99.78 | 99.00 | 101.88 | 20 | 1.0 | - | 36.01 KiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=1152 K=1152 dtype=bf16 act=none M=4` | - | 99.70 | 62.23 | 112.18 | 20 | 10.4 | - | 2.56 MiB | 32 thread(s) |
+| `kv_store` | `avx_kv_store` | libavx | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=512` | - | 97.97 | 96.94 | 99.15 | 14 | 0.7 | - | 3.06 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=1152 K=1536 dtype=bf16 act=none M=2` | - | 97.23 | 78.85 | 101.07 | 20 | 5.4 | - | 3.39 MiB | 32 thread(s) |
+| `gdn_chunk_scan` | `avx_gdn_chunk_scan` | libavx | `head_k=128 head_v=128 scale=0.0883883 M=8 chunk=64` | - | 95.58 | 94.40 | 140.24 | 19 | 0.9 | - | 6.30 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=1152 K=1536 dtype=bf16 act=none M=1` | - | 95.31 | 59.44 | 144.63 | 20 | 7.0 | - | 3.38 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=32` | - | 94.71 | 93.30 | 98.07 | 20 | 1.5 | - | 832.01 KiB | 32 thread(s) |
+| `gemm_nt` | `avx_gemm_nt` | libavx | `N=256 K=5120 dtype=bf16 M=56 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 94.00 | 83.82 | 97.73 | 20 | 4.2 | - | 3.07 MiB | 32 thread(s) |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=2 splits=0` | 92.67 | - | 92.40 | 93.22 | 6 | 0.4 | 3394 | 32.05 MiB |  |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=1 splits=0` | 92.04 | - | 91.73 | 92.32 | 6 | 0.3 | 3400 | 32.03 MiB |  |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=1152 K=1536 dtype=bf16 act=none M=16` | - | 90.73 | 73.67 | 96.50 | 20 | 2.9 | - | 3.49 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=18 ks=0 bk=0 nt=0` | 90.39 | - | 90.30 | 90.92 | 6 | 0.3 | 3313 | 48.30 MiB |  |
+| `gdn_conv_update` | `avx_gdn_conv_update` | libavx | `head_k=128 head_v=128 conv_width=4 q_len=8` | - | 89.54 | 88.61 | 131.41 | 20 | 2.6 | - | 600.04 KiB | 32 thread(s) |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=512` | 87.87 | - | 85.61 | 88.48 | 14 | 0.9 | 3174 | 19.00 MiB |  |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=25600 group=128 dtype=bf16 M=64` | - | 87.60 | 81.51 | 92.30 | 20 | 3.6 | - | 4.74 MiB | 32 thread(s) |
+| `rmsnorm_quant_fp8` | `avx_rmsnorm_quant_fp8` | libavx | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=128` | - | 86.23 | 84.21 | 96.04 | 20 | 2.1 | - | 4.40 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=1152 K=1152 dtype=bf16 act=none M=32` | - | 85.76 | 77.23 | 89.78 | 20 | 5.4 | - | 2.74 MiB | 32 thread(s) |
+| `sample_pick` | `sample_pick_f32` | libr4d | `n_cand=1024 M=1` | 84.25 | - | 82.99 | 84.66 | 11 | 0.9 | 3586 | 8.10 KiB |  |
+| `sample_temp` | `sample_temp_f32` | libr4d | `n_vocab=248320 M=64` | 84.23 | - | 83.97 | 84.32 | 6 | 0.2 | 3485 | 60.63 MiB | restore 72% |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=9 ks=0 bk=0 nt=0` | 81.69 | - | 81.54 | 81.94 | 11 | 0.2 | 3360 | 48.05 MiB |  |
+| `row_topk` | `rowtopk_bf16` | libr4d | `N=248320 R=32 dtype=bf16 M=1 nch=0 pt1=8` | 81.56 | - | 79.64 | 81.83 | 16 | 1.0 | 3457 | 485.50 KiB |  |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=8 ks=0 bk=0 nt=0` | 81.30 | - | 81.06 | 81.69 | 11 | 0.3 | 3317 | 48.03 MiB |  |
+| `scatter_rows` | `avx_scatter_rows` | libavx | `n=5120 dtype=bf16 M=256` | - | 80.86 | 79.16 | 82.72 | 14 | 0.7 | - | 12.50 MiB | 32 thread(s) |
+| `row_topk` | `rowtopk_bf16` | libr4d | `N=248320 R=32 dtype=bf16 M=2 nch=0 pt1=8` | 80.76 | - | 79.81 | 81.35 | 6 | 1.0 | 3455 | 971.00 KiB |  |
+| `rope` | `avx_rope` | libavx | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=512` | - | 79.98 | 78.81 | 97.84 | 20 | 2.3 | - | 6.01 MiB | 32 thread(s) |
+| `grid_embed` | `avx_grid_embed` | libavx | `n=1152 side=48 dtype=bf16 M=32` | - | 78.91 | 78.48 | 79.29 | 6 | 0.5 | - | 5.13 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=65` | 78.78 | - | 75.69 | 80.27 | 20 | 1.7 | 3217 | 31.03 MiB |  |
+| `rope` | `avx_rope` | libavx | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=512` | - | 78.72 | 78.03 | 87.74 | 16 | 0.6 | - | 3.38 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=4 ks=0 bk=0 nt=0` | 78.50 | - | 78.29 | 78.67 | 11 | 0.2 | 3352 | 47.92 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=128` | 78.44 | - | 76.86 | 79.71 | 14 | 1.0 | 3056 | 32.03 MiB |  |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=1 ks=0 bk=0 nt=0` | 77.43 | - | 77.13 | 77.97 | 11 | 0.4 | 2989 | 47.84 MiB |  |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=5120 K=17408 group=32 dtype=mxfp4a8 M=2 ks=0 bk=0 nt=0` | 77.36 | - | 77.17 | 78.07 | 6 | 0.6 | 3289 | 47.87 MiB |  |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=25600 group=128 dtype=bf16 M=512` | 74.80 | - | 74.62 | 75.18 | 6 | 0.4 | 3351 | 37.89 MiB |  |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=10 splits=0` | 74.79 | - | 74.70 | 75.30 | 6 | 0.4 | 3397 | 32.24 MiB |  |
+| `gemm_nt` | `avx_gemm_nt` | libavx | `N=256 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 74.73 | 62.57 | 81.19 | 20 | 1.9 | - | 2.58 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=1152 K=1152 dtype=bf16 act=none M=2` | - | 74.68 | 65.20 | 93.48 | 20 | 10.3 | - | 2.55 MiB | 32 thread(s) |
+| `sample_pick` | `sample_pick_f32` | libr4d | `n_cand=1024 M=4` | 74.64 | - | 72.92 | 74.85 | 14 | 0.4 | 3587 | 32.39 KiB |  |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=5 splits=0` | 74.35 | - | 74.04 | 74.72 | 6 | 0.5 | 3392 | 32.12 MiB |  |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=9 splits=0` | 74.04 | - | 73.94 | 74.26 | 6 | 0.2 | 3382 | 32.21 MiB |  |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=4 splits=0` | 73.51 | - | 73.41 | 74.10 | 6 | 0.5 | 3393 | 32.10 MiB |  |
+| `sample_logprobs` | `avx_sample_logprobs` | libavx | `n_vocab=248320 k=21 M=2` | - | 73.46 | 72.96 | 75.14 | 20 | 1.3 | - | 1.90 MiB | 32 thread(s) |
+| `sample_logprobs` | `avx_sample_logprobs` | libavx | `n_vocab=248320 k=21 M=8` | - | 73.31 | 71.15 | 74.67 | 20 | 1.8 | - | 7.58 MiB | 32 thread(s) |
+| `sample_logprobs` | `avx_sample_logprobs` | libavx | `n_vocab=248320 k=21 M=1` | - | 73.16 | 70.61 | 77.23 | 20 | 3.7 | - | 970.27 KiB | 32 thread(s) |
+| `gemm_nt` | `avx_gemm_nt` | libavx | `N=256 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 72.23 | 61.44 | 82.41 | 20 | 11.4 | - | 2.85 MiB | 32 thread(s) |
+| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | `head_k=128 head_v=128 scale=0.0883883 M=512 chunk=64` | 71.61 | - | 71.37 | 72.22 | 6 | 0.6 | 3351 | 25.19 MiB |  |
+| `sample_logprobs` | `avx_sample_logprobs` | libavx | `n_vocab=248320 k=21 M=4` | - | 71.41 | 70.01 | 73.55 | 19 | 1.0 | - | 3.79 MiB | 32 thread(s) |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=8 splits=0` | 71.22 | - | 70.95 | 71.68 | 6 | 0.5 | 3389 | 32.19 MiB |  |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=1152 K=1152 dtype=bf16 act=none M=16` | - | 71.09 | 60.11 | 76.68 | 20 | 6.6 | - | 2.64 MiB | 32 thread(s) |
+| `gemm_nt` | `avx_gemm_nt` | libavx | `N=256 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 70.69 | 62.62 | 93.68 | 20 | 13.7 | - | 2.52 MiB | 32 thread(s) |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=6 splits=0` | 68.97 | - | 68.86 | 69.34 | 6 | 0.3 | 3387 | 32.14 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=3456 K=1152 dtype=bf16 act=none M=512` | 67.30 | - | 64.15 | 67.97 | 20 | 1.7 | 3268 | 15.48 MiB |  |
+| `gemm_nt` | `avx_gemm_nt` | libavx | `N=256 K=5120 dtype=bf16 M=4 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 64.18 | 42.30 | 65.19 | 20 | 1.1 | - | 2.54 MiB | 32 thread(s) |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=512` | - | 64.11 | 61.95 | 91.79 | 20 | 1.7 | - | 10.01 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=1152 K=4304 dtype=bf16 act=none M=256` | 63.93 | - | 60.99 | 65.21 | 20 | 1.8 | 3412 | 12.69 MiB |  |
+| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 conv_width=4 q_len=64` | 63.40 | - | 52.96 | 63.59 | 11 | 0.3 | 3396 | 3.87 MiB | restore 4% |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=512` | - | 62.95 | 61.45 | 88.42 | 20 | 5.4 | - | 10.01 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `avx_gemm_nt_bias` | libavx | `N=1152 K=1152 dtype=bf16 act=none M=1` | - | 62.80 | 49.52 | 65.88 | 16 | 0.6 | - | 2.54 MiB | 32 thread(s) |
+| `gemm_nt` | `avx_gemm_nt` | libavx | `N=256 K=5120 dtype=bf16 M=1 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 61.75 | 36.84 | 93.16 | 20 | 9.3 | - | 2.51 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=128 ks=0 bk=0 nt=0` | 61.45 | - | 60.37 | 61.48 | 11 | 0.1 | 3374 | 3.71 MiB |  |
+| `gdn_conv_update` | `avx_gdn_conv_update` | libavx | `head_k=128 head_v=128 conv_width=4 q_len=2` | - | 61.35 | 60.93 | 61.79 | 6 | 0.7 | - | 240.02 KiB | 32 thread(s) |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=17408 group=128 dtype=bf16 M=64` | - | 60.70 | 55.25 | 63.15 | 20 | 4.1 | - | 3.22 MiB | 32 thread(s) |
+| `gated_quant_fp8` | `avx_gated_quant_fp8` | libavx | `n=17408 group=128 dtype=bf16 act=silu M=32` | - | 59.97 | 59.13 | 62.03 | 20 | 1.4 | - | 3.74 MiB | 32 thread(s) |
+| `rope` | `avx_rope` | libavx | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=256` | - | 59.74 | 59.38 | 60.68 | 11 | 1.0 | - | 3.00 MiB | 32 thread(s) |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=6144 group=128 dtype=bf16 M=256` | - | 59.60 | 58.21 | 60.53 | 20 | 1.3 | - | 4.55 MiB | 32 thread(s) |
+| `kv_store` | `avx_kv_store` | libavx | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=512` | - | 59.13 | 57.82 | 61.26 | 16 | 1.0 | - | 3.06 MiB | 32 thread(s) |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=512` | 58.81 | - | 58.55 | 61.55 | 16 | 0.7 | 3273 | 13.00 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=64` | 57.76 | - | 57.58 | 57.99 | 11 | 0.3 | 3439 | 31.02 MiB |  |
+| `gdn_conv_update` | `avx_gdn_conv_update` | libavx | `head_k=128 head_v=128 conv_width=4 q_len=4` | - | 56.95 | 55.96 | 82.40 | 20 | 1.1 | - | 360.03 KiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=36` | 56.47 | - | 56.37 | 56.52 | 11 | 0.1 | 3445 | 30.57 MiB |  |
+| `add` | `avx_add` | libavx | `n=5120 dtype=bf16 M=256` | - | 56.31 | 56.19 | 57.29 | 6 | 1.0 | - | 7.50 MiB | 32 thread(s) |
+| `gemm_nt` | `avx_gemm_nt` | libavx | `N=256 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 56.24 | 54.66 | 58.73 | 20 | 2.0 | - | 2.67 MiB | 32 thread(s) |
+| `gemm_nt` | `avx_gemm_nt` | libavx | `N=256 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 55.63 | 39.38 | 57.42 | 20 | 2.1 | - | 2.66 MiB | 32 thread(s) |
+| `gdn_chunk_scan` | `avx_gdn_chunk_scan` | libavx | `head_k=128 head_v=128 scale=0.0883883 M=4 chunk=64` | - | 55.40 | 54.66 | 79.23 | 20 | 1.4 | - | 6.15 MiB | 32 thread(s) |
+| `gemm_nt` | `avx_gemm_nt` | libavx | `N=96 K=5120 dtype=bf16 M=65 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 55.28 | 42.96 | 89.90 | 20 | 35.0 | - | 1.58 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=18` | 54.95 | - | 54.82 | 55.17 | 11 | 0.3 | 3442 | 30.29 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=8` | 54.07 | - | 54.04 | 54.12 | 11 | 0.1 | 3444 | 30.13 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=9` | 53.99 | - | 53.90 | 54.03 | 11 | 0.1 | 3447 | 30.15 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=2` | 53.79 | - | 53.71 | 53.84 | 11 | 0.1 | 3443 | 30.04 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=4` | 53.66 | - | 53.62 | 53.69 | 11 | 0.1 | 3435 | 30.07 MiB |  |
+| `grid_embed` | `avx_grid_embed` | libavx | `n=1152 side=48 dtype=bf16 M=4` | - | 53.63 | 53.13 | 54.39 | 11 | 0.9 | - | 5.07 MiB | 32 thread(s) |
+| `gated_quant_fp8` | `gated_quant_fp8` | libr4d | `n=17408 group=128 dtype=bf16 act=silu M=256` | 53.56 | - | 53.45 | 54.01 | 11 | 0.5 | 3347 | 29.88 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=1` | 53.52 | - | 53.50 | 53.54 | 6 | 0.0 | 3417 | 30.02 MiB |  |
+| `sample_argmax` | `sample_argmax_f32` | libr4d | `n_vocab=248320 M=32` | 53.01 | - | 53.00 | 53.05 | 6 | 0.0 | 3534 | 30.32 MiB |  |
+| `rmsnorm_quant_fp8` | `avx_rmsnorm_quant_fp8` | libavx | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=64` | - | 51.29 | 48.91 | 56.79 | 20 | 6.3 | - | 2.21 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=256` | 51.07 | - | 48.92 | 51.81 | 20 | 1.5 | 3316 | 14.23 MiB |  |
+| `sample_minp` | `avx_sample_minp` | libavx | `n_cand=1024 M=64` | - | 50.86 | 46.53 | 52.77 | 20 | 1.5 | - | 518.00 KiB | 32 thread(s) |
+| `sample_temp` | `avx_sample_temp` | libavx | `n_vocab=248320 M=2` | - | 48.05 | 47.97 | 48.25 | 6 | 0.3 | - | 1.89 MiB | 32 thread(s) |
+| `gemm_nt` | `avx_gemm_nt` | libavx | `N=96 K=5120 dtype=bf16 M=64 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 47.16 | 44.92 | 54.34 | 20 | 7.9 | - | 1.57 MiB | 32 thread(s) |
+| `rope` | `rope_bf16` | libr4d | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=512` | 47.08 | - | 44.74 | 47.30 | 11 | 0.8 | 3464 | 3.38 MiB | restore 8% |
+| `rope` | `avx_rope` | libavx | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=256` | - | 45.88 | 44.69 | 52.17 | 14 | 0.9 | - | 1.69 MiB | 32 thread(s) |
+| `silu_mul` | `avx_silu_mul` | libavx | `n=17408 dtype=bf16 M=64` | - | 44.85 | 44.29 | 65.37 | 16 | 0.9 | - | 6.38 MiB | 32 thread(s) |
+| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu state_form=anchor q_len=16` | 44.70 | - | 29.12 | 45.16 | 11 | 0.9 | 3428 | 48.69 MiB | restore 79%; restore-dominated (79% of the batch): an order of magnitude |
+| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 conv_width=4 q_len=32` | 44.61 | - | 39.25 | 44.67 | 14 | 0.2 | 3397 | 1.99 MiB | restore 6% |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=258` | 44.04 | - | 43.57 | 44.38 | 6 | 0.9 | 3345 | 6.80 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=129` | 43.62 | - | 43.29 | 44.04 | 6 | 0.9 | 3354 | 5.90 MiB |  |
+| `sample_xtc` | `avx_sample_xtc` | libavx | `n_cand=1024 M=64` | - | 43.57 | 43.15 | 59.89 | 16 | 0.3 | - | 518.00 KiB | 32 thread(s) |
+| `gdn_conv_update` | `avx_gdn_conv_update` | libavx | `head_k=128 head_v=128 conv_width=4 q_len=1` | - | 43.50 | 30.54 | 44.98 | 20 | 1.9 | - | 180.02 KiB | 32 thread(s) |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=256` | - | 43.27 | 33.61 | 47.77 | 20 | 14.7 | - | 5.01 MiB | 32 thread(s) |
+| `gemm_nt` | `avx_gemm_nt` | libavx | `N=96 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 42.75 | 40.39 | 47.04 | 20 | 5.2 | - | 1.02 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=1152 K=4304 dtype=bf16 act=none M=128` | 42.58 | - | 42.40 | 43.00 | 6 | 0.7 | 3535 | 11.07 MiB |  |
+| `gemm_nt_q` | `gemm_mxfp4a8_tiled` | libr4d | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=512 tn=0` | 42.54 | - | 42.19 | 42.96 | 6 | 0.9 | 3352 | 6.39 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=65` | 42.05 | - | 41.91 | 42.16 | 11 | 0.2 | 3366 | 5.45 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=512` | 41.91 | - | 39.91 | 43.64 | 20 | 2.3 | 3255 | 8.58 MiB |  |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=132` | 40.89 | - | 23.37 | 41.02 | 20 | 1.2 | 3435 | 3.38 MiB |  |
+| `gated_quant_fp8` | `avx_gated_quant_fp8` | libavx | `n=17408 group=128 dtype=bf16 act=silu M=8` | - | 40.82 | 39.09 | 47.22 | 20 | 5.6 | - | 956.25 KiB | 32 thread(s) |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=1152 K=1536 dtype=bf16 act=none M=512` | 40.80 | - | 40.59 | 41.14 | 11 | 0.6 | 3479 | 7.13 MiB |  |
+| `scatter_rows` | `avx_scatter_rows` | libavx | `n=5120 dtype=bf16 M=128` | - | 40.53 | 37.87 | 40.83 | 16 | 0.8 | - | 6.25 MiB | 32 thread(s) |
+| `grid_embed` | `avx_grid_embed` | libavx | `n=1152 side=48 dtype=bf16 M=16` | - | 40.51 | 40.27 | 40.86 | 6 | 0.7 | - | 5.10 MiB | 32 thread(s) |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=25600 group=128 dtype=bf16 M=256` | 39.82 | - | 39.35 | 40.32 | 11 | 0.9 | 3355 | 18.95 MiB |  |
+| `sample_topp` | `avx_sample_topp` | libavx | `n_cand=1024 M=64` | - | 39.81 | 39.43 | 56.07 | 20 | 20.1 | - | 518.00 KiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_mxfp4a8_tiled` | libr4d | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=258 tn=0` | 39.75 | - | 39.62 | 40.31 | 6 | 0.9 | 3368 | 4.62 MiB |  |
+| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | `head_k=128 head_v=128 scale=0.0883883 M=256 chunk=64` | 39.68 | - | 39.46 | 39.80 | 6 | 0.4 | 3346 | 15.59 MiB |  |
+| `cast` | `avx_cast` | libavx | `n=5120 from=bf16 to=bf16 M=512` | - | 39.16 | 37.66 | 40.04 | 20 | 2.1 | - | 10.00 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_mxfp4a8_tiled` | libr4d | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=129 tn=0` | 38.77 | - | 38.53 | 38.84 | 6 | 0.4 | 3368 | 3.71 MiB |  |
+| `sample_mask` | `sample_mask_f32` | libr4d | `n_vocab=248320 M=32` | 38.72 | - | 38.40 | 39.11 | 11 | 0.7 | 3490 | 31.26 MiB | restore 51% |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=128` | 38.58 | - | 38.45 | 38.69 | 6 | 0.3 | 3557 | 11.85 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=128` | 37.71 | - | 37.61 | 37.97 | 11 | 0.4 | 3368 | 5.90 MiB |  |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=64 ks=0 bk=0 nt=0` | 37.60 | - | 37.32 | 37.67 | 6 | 0.5 | 3410 | 12.13 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=3456 K=1152 dtype=bf16 act=none M=256` | 37.25 | - | 36.73 | 37.50 | 11 | 0.8 | 3435 | 11.54 MiB |  |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=5120 group=128 dtype=bf16 M=128` | - | 37.22 | 36.93 | 37.51 | 6 | 0.8 | - | 1.89 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=64` | 36.87 | - | 36.61 | 37.06 | 6 | 0.6 | 3550 | 10.66 MiB |  |
+| `gemm_nt` | `avx_gemm_nt` | libavx | `N=96 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 36.80 | 35.06 | 39.50 | 20 | 4.5 | - | 1.28 MiB | 32 thread(s) |
+| `gdn_chunk_scan` | `avx_gdn_chunk_scan` | libavx | `head_k=128 head_v=128 scale=0.0883883 M=2 chunk=64` | - | 36.27 | 35.21 | 51.68 | 20 | 13.3 | - | 6.07 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=64 ks=0 bk=0 nt=0` | 36.11 | - | 35.87 | 36.32 | 6 | 0.6 | 3454 | 12.07 MiB |  |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=5120 group=128 dtype=bf16 M=256` | - | 35.73 | 33.84 | 47.27 | 20 | 3.7 | - | 3.79 MiB | 32 thread(s) |
+| `kv_store` | `avx_kv_store` | libavx | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=256` | - | 35.57 | 35.44 | 36.40 | 14 | 0.6 | - | 1.56 MiB | 32 thread(s) |
+| `sample_pick` | `avx_sample_pick` | libavx | `n_cand=1024 M=64` | - | 35.03 | 34.76 | 35.37 | 6 | 0.9 | - | 518.25 KiB | 32 thread(s) |
+| `sample_temp` | `avx_sample_temp` | libavx | `n_vocab=248320 M=4` | - | 34.90 | 34.84 | 35.46 | 6 | 0.9 | - | 3.79 MiB | 32 thread(s) |
+| `sample_xtc` | `avx_sample_xtc` | libavx | `n_cand=1024 M=32` | - | 34.65 | 34.48 | 34.76 | 11 | 0.4 | - | 259.00 KiB | 32 thread(s) |
+| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=1280 K=5120 dtype=bf16 M=64 wv=1 sk=0 mb=0 npw=1 nt=1` | 34.62 | - | 34.55 | 34.72 | 6 | 0.2 | 3458 | 13.28 MiB |  |
+| `gated_quant_fp8` | `avx_gated_quant_fp8` | libavx | `n=17408 group=128 dtype=bf16 act=silu M=16` | - | 33.59 | 32.40 | 50.42 | 20 | 24.1 | - | 1.87 MiB | 32 thread(s) |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=256` | - | 33.57 | 32.84 | 47.92 | 20 | 13.2 | - | 5.01 MiB | 32 thread(s) |
+| `sample_temp` | `avx_sample_temp` | libavx | `n_vocab=248320 M=1` | - | 33.12 | 33.03 | 33.57 | 6 | 0.8 | - | 970.09 KiB | 32 thread(s) |
+| `gated_quant_fp8` | `gated_quant_fp8` | libr4d | `n=17408 group=128 dtype=bf16 act=silu M=128` | 32.99 | - | 32.37 | 33.63 | 16 | 0.8 | 3352 | 14.94 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=1152 K=1152 dtype=bf16 act=none M=512` | 32.64 | - | 32.34 | 33.20 | 14 | 0.9 | 3519 | 5.91 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=32` | 32.58 | - | 32.47 | 32.73 | 6 | 0.4 | 3550 | 10.06 MiB |  |
+| `gemm_nt` | `avx_gemm_nt` | libavx | `N=96 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 32.25 | 29.17 | 35.07 | 20 | 6.9 | - | 980.38 KiB | 32 thread(s) |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=25600 group=128 dtype=bf16 M=32` | - | 32.06 | 31.92 | 32.64 | 14 | 0.9 | - | 2.37 MiB | 32 thread(s) |
+| `gemm_nt` | `avx_gemm_nt` | libavx | `N=96 K=5120 dtype=bf16 M=4 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 31.70 | 17.66 | 35.43 | 20 | 7.8 | - | 1000.75 KiB | 32 thread(s) |
+| `rmsnorm_quant_fp8` | `avx_rmsnorm_quant_fp8` | libavx | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=32` | - | 30.55 | 29.80 | 31.67 | 20 | 1.7 | - | 1.11 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=36 ks=0 bk=0 nt=0` | 30.54 | - | 30.40 | 30.78 | 6 | 0.6 | 3476 | 11.75 MiB |  |
+| `kv_store` | `avx_kv_store` | libavx | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=256` | - | 30.52 | 29.44 | 31.49 | 20 | 1.9 | - | 1.56 MiB | 32 thread(s) |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=6144 group=128 dtype=bf16 M=128` | - | 30.51 | 30.10 | 44.83 | 20 | 21.3 | - | 2.27 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=36 ks=0 bk=0 nt=0` | 30.47 | - | 30.29 | 30.63 | 6 | 0.6 | 3457 | 11.71 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=8` | 30.43 | - | 30.28 | 30.70 | 6 | 0.7 | 3542 | 9.61 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=16` | 30.43 | - | 30.27 | 30.69 | 6 | 0.7 | 3546 | 9.76 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=1152 K=4304 dtype=bf16 act=none M=64` | 30.37 | - | 30.32 | 30.52 | 6 | 0.3 | 3554 | 10.27 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=1152 K=4304 dtype=bf16 act=none M=32` | 30.13 | - | 30.09 | 30.22 | 6 | 0.2 | 3558 | 9.86 MiB |  |
+| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=1280 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | 29.60 | - | 29.54 | 29.68 | 6 | 0.2 | 3464 | 12.92 MiB |  |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=264` | 29.58 | - | 29.40 | 29.74 | 6 | 0.6 | 3407 | 6.72 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=4` | 29.28 | - | 29.19 | 29.46 | 6 | 0.5 | 3549 | 9.54 MiB |  |
+| `add` | `avx_add` | libavx | `n=5120 dtype=bf16 M=128` | - | 29.08 | 28.61 | 38.64 | 20 | 4.1 | - | 3.75 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=2` | 28.96 | - | 28.72 | 29.10 | 6 | 0.7 | 3558 | 9.50 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=4304 K=1152 dtype=bf16 act=gelu_tanh M=1` | 28.86 | - | 28.68 | 28.95 | 6 | 0.5 | 3548 | 9.48 MiB |  |
+| `rope` | `avx_rope` | libavx | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=256` | - | 28.77 | 28.02 | 34.42 | 20 | 9.7 | - | 513.00 KiB | 32 thread(s) |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=1152 K=4304 dtype=bf16 act=none M=16` | 28.67 | - | 28.57 | 28.72 | 6 | 0.3 | 3556 | 9.66 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=1152 K=4304 dtype=bf16 act=none M=8` | 28.48 | - | 28.44 | 28.62 | 6 | 0.3 | 3554 | 9.56 MiB |  |
+| `gemm_nt` | `avx_gemm_nt` | libavx | `N=96 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 28.47 | 23.05 | 32.90 | 20 | 6.5 | - | 1.10 MiB | 32 thread(s) |
+| `sample_argmax` | `sample_argmax_f32` | libr4d | `n_vocab=248320 M=16` | 28.45 | - | 28.43 | 28.62 | 6 | 0.3 | 3540 | 15.16 MiB |  |
+| `sample_temp` | `sample_temp_f32` | libr4d | `n_vocab=248320 M=32` | 28.04 | - | 27.86 | 28.17 | 6 | 0.6 | 3474 | 30.32 MiB | restore 59% |
+| `rope` | `avx_rope` | libavx | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=512` | - | 28.02 | 25.42 | 30.63 | 20 | 8.3 | - | 1.00 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=1152 K=4304 dtype=bf16 act=none M=4` | 27.85 | - | 27.75 | 27.96 | 6 | 0.4 | 3558 | 9.51 MiB |  |
+| `gemm_nt` | `avx_gemm_nt` | libavx | `N=96 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 27.61 | 20.91 | 33.04 | 20 | 10.2 | - | 1.11 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=1152 K=4304 dtype=bf16 act=none M=2` | 27.51 | - | 27.42 | 27.57 | 6 | 0.3 | 3556 | 9.48 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=1152 K=4304 dtype=bf16 act=none M=1` | 27.42 | - | 27.27 | 27.94 | 14 | 0.6 | 3516 | 9.47 MiB |  |
+| `grid_embed` | `avx_grid_embed` | libavx | `n=1152 side=48 dtype=bf16 M=2` | - | 27.34 | 27.02 | 28.13 | 16 | 0.8 | - | 5.07 MiB | 32 thread(s) |
+| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=1280 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | 26.97 | - | 26.93 | 27.08 | 6 | 0.3 | 3468 | 12.70 MiB |  |
+| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=1280 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | 26.63 | - | 26.60 | 26.66 | 6 | 0.1 | 3467 | 12.71 MiB |  |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=18 ks=0 bk=0 nt=0` | 26.38 | - | 26.29 | 26.51 | 6 | 0.4 | 3492 | 11.50 MiB |  |
+| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=1280 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | 26.37 | - | 26.34 | 26.53 | 6 | 0.4 | 3472 | 12.60 MiB |  |
+| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=1280 K=5120 dtype=bf16 M=4 wv=1 sk=0 mb=0 npw=1 nt=1` | 26.15 | - | 26.12 | 26.17 | 6 | 0.1 | 3470 | 12.55 MiB |  |
+| `gdn_chunk_scan` | `avx_gdn_chunk_scan` | libavx | `head_k=128 head_v=128 scale=0.0883883 M=1 chunk=64` | - | 26.14 | 25.72 | 26.58 | 20 | 1.0 | - | 6.04 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=3456 K=1152 dtype=bf16 act=none M=128` | 26.06 | - | 25.71 | 26.26 | 11 | 1.0 | 3467 | 9.57 MiB |  |
+| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=1280 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | 26.06 | - | 26.05 | 26.28 | 6 | 0.4 | 3464 | 12.52 MiB |  |
+| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=1280 K=5120 dtype=bf16 M=1 wv=1 sk=0 mb=0 npw=1 nt=1` | 26.05 | - | 26.04 | 26.10 | 6 | 0.1 | 3461 | 12.51 MiB |  |
+| `sample_topp` | `avx_sample_topp` | libavx | `n_cand=1024 M=32` | - | 25.92 | 25.48 | 26.83 | 16 | 0.7 | - | 259.00 KiB | 32 thread(s) |
+| `gemm_nt` | `avx_gemm_nt` | libavx | `N=96 K=5120 dtype=bf16 M=1 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 25.35 | 21.21 | 29.32 | 20 | 10.4 | - | 970.19 KiB | 32 thread(s) |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=1152 K=1536 dtype=bf16 act=none M=256` | 25.06 | - | 24.78 | 25.33 | 14 | 0.8 | 3482 | 5.25 MiB |  |
+| `gated_quant_fp8` | `avx_gated_quant_fp8` | libavx | `n=17408 group=128 dtype=bf16 act=silu M=4` | - | 25.05 | 24.47 | 33.32 | 20 | 11.4 | - | 478.12 KiB | 32 thread(s) |
+| `attn_dense` | `avx_attn_dense` | libavx | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=32` | - | 24.58 | 24.53 | 25.14 | 16 | 1.0 | - | 18.01 KiB | 32 thread(s) |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=512` | 24.49 | - | 24.37 | 24.57 | 6 | 0.4 | 3356 | 10.01 MiB |  |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=18 ks=0 bk=0 nt=0` | 24.47 | - | 24.37 | 24.80 | 6 | 0.9 | 3460 | 11.48 MiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=512` | 24.46 | - | 24.38 | 24.60 | 6 | 0.5 | 3377 | 10.01 MiB |  |
+| `rope` | `avx_rope` | libavx | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=128` | - | 24.33 | 23.66 | 26.24 | 20 | 4.4 | - | 1.50 MiB | 32 thread(s) |
+| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu state_form=anchor q_len=8` | 24.27 | - | 23.10 | 24.33 | 11 | 0.3 | 3399 | 24.35 MiB | restore 58% |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=9 ks=0 bk=0 nt=0` | 24.24 | - | 24.21 | 24.47 | 6 | 0.5 | 3492 | 11.37 MiB |  |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=8 ks=0 bk=0 nt=0` | 24.10 | - | 24.07 | 24.19 | 6 | 0.2 | 3484 | 11.36 MiB |  |
+| `sample_minp` | `avx_sample_minp` | libavx | `n_cand=1024 M=32` | - | 24.09 | 22.27 | 26.18 | 20 | 6.7 | - | 259.00 KiB | 32 thread(s) |
+| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | `head_k=128 head_v=128 scale=0.0883883 M=128 chunk=64` | 23.87 | - | 23.77 | 24.03 | 6 | 0.5 | 3346 | 10.80 MiB |  |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=4 ks=0 bk=0 nt=0` | 23.65 | - | 23.64 | 23.80 | 6 | 0.3 | 3486 | 11.31 MiB |  |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=65 ks=0 bk=0 nt=0` | 23.63 | - | 23.49 | 23.76 | 6 | 0.6 | 3368 | 3.27 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=64` | 23.58 | - | 23.51 | 23.70 | 11 | 0.4 | 3361 | 5.45 MiB |  |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=2 ks=0 bk=0 nt=0` | 23.42 | - | 23.39 | 23.57 | 6 | 0.4 | 3484 | 11.28 MiB |  |
+| `silu_mul` | `avx_silu_mul` | libavx | `n=17408 dtype=bf16 M=32` | - | 23.36 | 22.87 | 32.83 | 20 | 2.7 | - | 3.19 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=5120 K=4096 group=32 dtype=mxfp4a8 M=1 ks=0 bk=0 nt=0` | 23.28 | - | 23.24 | 23.40 | 6 | 0.3 | 3458 | 11.26 MiB |  |
+| `rmsnorm_quant_fp8` | `rmsnorm_quant_fp8` | libr4d | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=512` | 22.96 | - | 22.82 | 23.15 | 6 | 0.7 | 3315 | 17.59 MiB | restore 28% |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=17408 group=128 dtype=bf16 M=32` | - | 22.83 | 22.48 | 23.56 | 20 | 1.3 | - | 1.61 MiB | 32 thread(s) |
+| `rope` | `avx_rope` | libavx | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=128` | - | 22.62 | 21.73 | 25.16 | 20 | 6.1 | - | 865.00 KiB | 32 thread(s) |
+| `rope` | `avx_rope` | libavx | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=64` | - | 22.62 | 22.47 | 22.81 | 6 | 0.7 | - | 512.25 KiB | 32 thread(s) |
+| `gated_quant_fp8` | `avx_gated_quant_fp8` | libavx | `n=17408 group=128 dtype=bf16 act=silu M=2` | - | 22.36 | 22.25 | 22.90 | 20 | 1.0 | - | 239.06 KiB | 32 thread(s) |
+| `gated_quant_fp8` | `avx_gated_quant_fp8` | libavx | `n=17408 group=128 dtype=bf16 act=silu M=1` | - | 22.23 | 22.10 | 22.62 | 16 | 0.4 | - | 119.53 KiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=9 ks=0 bk=0 nt=0` | 22.12 | - | 22.09 | 22.17 | 6 | 0.2 | 3472 | 11.37 MiB |  |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=8 ks=0 bk=0 nt=0` | 22.00 | - | 21.97 | 22.23 | 6 | 0.6 | 3470 | 11.35 MiB |  |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=64 ks=0 bk=0 nt=0` | 21.69 | - | 20.97 | 22.30 | 20 | 2.6 | 3360 | 3.26 MiB |  |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=4 ks=0 bk=0 nt=0` | 21.49 | - | 21.46 | 21.77 | 6 | 0.7 | 3472 | 11.30 MiB |  |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=2 ks=0 bk=0 nt=0` | 21.25 | - | 21.23 | 21.30 | 6 | 0.2 | 3474 | 11.28 MiB |  |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=4096 K=5120 group=32 dtype=mxfp4a8 M=1 ks=0 bk=0 nt=0` | 21.13 | - | 21.10 | 21.37 | 6 | 0.6 | 3467 | 11.26 MiB |  |
+| `rmsnorm_quant_fp8` | `avx_rmsnorm_quant_fp8` | libavx | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=8` | - | 20.99 | 20.53 | 21.36 | 16 | 0.8 | - | 291.25 KiB | 32 thread(s) |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=128` | - | 20.73 | 19.45 | 27.25 | 20 | 17.3 | - | 2.51 MiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=17` | - | 20.65 | 20.50 | 21.27 | 20 | 1.2 | - | 472.01 KiB | 32 thread(s) |
+| `gdn_kkt_solve` | `avx_gdn_kkt_solve` | libavx | `head_k=128 M=32 chunk=64` | - | 20.49 | 19.42 | 21.69 | 20 | 3.5 | - | 332.01 KiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=36` | 20.46 | - | 20.34 | 20.54 | 11 | 0.5 | 3364 | 5.25 MiB |  |
+| `sample_minp` | `avx_sample_minp` | libavx | `n_cand=1024 M=16` | - | 20.20 | 13.39 | 21.22 | 20 | 8.0 | - | 129.50 KiB | 32 thread(s) |
+| `cast` | `avx_cast` | libavx | `n=5120 from=bf16 to=bf16 M=256` | - | 20.04 | 19.94 | 20.15 | 6 | 0.5 | - | 5.00 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=3456 K=1152 dtype=bf16 act=none M=64` | 20.02 | - | 20.01 | 20.12 | 6 | 0.3 | 3537 | 8.58 MiB |  |
+| `rope` | `avx_rope` | libavx | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=512` | - | 19.73 | 19.19 | 20.20 | 20 | 1.1 | - | 1.01 MiB | 32 thread(s) |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=128` | - | 19.58 | 18.90 | 27.06 | 20 | 11.0 | - | 2.51 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=1152 K=1152 dtype=bf16 act=none M=256` | 19.54 | - | 19.24 | 19.88 | 14 | 0.7 | 3512 | 4.22 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=3456 K=1152 dtype=bf16 act=none M=32` | 19.28 | - | 19.23 | 19.28 | 6 | 0.1 | 3539 | 8.09 MiB |  |
+| `rmsnorm_quant_fp8` | `avx_rmsnorm_quant_fp8` | libavx | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=16` | - | 18.87 | 18.30 | 19.23 | 20 | 1.4 | - | 572.50 KiB | 32 thread(s) |
+| `sample_pick` | `avx_sample_pick` | libavx | `n_cand=1024 M=32` | - | 18.75 | 18.36 | 19.11 | 20 | 1.5 | - | 259.12 KiB | 32 thread(s) |
+| `kv_store` | `avx_kv_store` | libavx | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=128` | - | 18.70 | 18.02 | 19.53 | 20 | 1.7 | - | 832.50 KiB | 32 thread(s) |
+| `sample_mask` | `avx_sample_mask` | libavx | `n_vocab=248320 M=4` | - | 18.66 | 18.55 | 18.73 | 6 | 0.5 | - | 3.91 MiB | 32 thread(s) |
+| `kv_store` | `avx_kv_store` | libavx | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=128` | - | 18.64 | 15.28 | 19.19 | 20 | 7.6 | - | 832.50 KiB | 32 thread(s) |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=1152 K=1536 dtype=bf16 act=none M=128` | 18.55 | - | 18.46 | 18.59 | 6 | 0.3 | 3494 | 4.31 MiB |  |
+| `sample_argmax` | `avx_sample_argmax` | libavx | `n_vocab=248320 M=2` | - | 18.51 | 18.47 | 19.01 | 16 | 0.4 | - | 1.89 MiB | 32 thread(s) |
+| `add` | `add_bf16` | libr4d | `n=5120 dtype=bf16 M=512` | 18.30 | - | 18.27 | 18.46 | 6 | 0.5 | 3326 | 15.00 MiB |  |
+| `sample_temp` | `sample_temp_f32` | libr4d | `n_vocab=248320 M=16` | 18.27 | - | 18.15 | 18.32 | 6 | 0.5 | 3473 | 15.16 MiB | restore 53% |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=6144 group=128 dtype=bf16 M=512` | 18.06 | - | 17.96 | 18.18 | 6 | 0.6 | 3388 | 9.09 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=3456 K=1152 dtype=bf16 act=none M=16` | 17.91 | - | 17.84 | 17.95 | 6 | 0.3 | 3544 | 7.85 MiB |  |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=25600 group=128 dtype=bf16 M=16` | - | 17.83 | 17.26 | 30.60 | 20 | 25.4 | - | 1.18 MiB | 32 thread(s) |
+| `scatter_rows` | `avx_scatter_rows` | libavx | `n=5120 dtype=bf16 M=64` | - | 17.80 | 16.69 | 18.24 | 20 | 2.4 | - | 3.13 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=3456 K=1152 dtype=bf16 act=none M=8` | 17.67 | - | 17.64 | 17.79 | 6 | 0.4 | 3536 | 7.72 MiB |  |
+| `rope` | `avx_rope` | libavx | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=64` | - | 17.51 | 15.58 | 19.08 | 20 | 4.6 | - | 432.50 KiB | 32 thread(s) |
+| `embed_lookup` | `embed_lookup_bf16` | libr4d | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=512` | 17.50 | - | 17.43 | 17.57 | 6 | 0.4 | 3192 | 2.37 GiB |  |
+| `sample_minp` | `avx_sample_minp` | libavx | `n_cand=1024 M=8` | - | 17.43 | 13.61 | 19.58 | 20 | 13.5 | - | 64.75 KiB | 32 thread(s) |
+| `sample_argmax` | `avx_sample_argmax` | libavx | `n_vocab=248320 M=8` | - | 17.36 | 16.81 | 17.90 | 20 | 2.2 | - | 7.58 MiB | 32 thread(s) |
+| `sample_xtc` | `avx_sample_xtc` | libavx | `n_cand=1024 M=16` | - | 17.27 | 16.74 | 17.94 | 20 | 2.4 | - | 129.50 KiB | 32 thread(s) |
+| `layernorm` | `layernorm_bf16` | libr4d | `n=1152 eps=1e-06 dtype=bf16 M=512` | 17.16 | - | 17.14 | 17.17 | 6 | 0.1 | 3538 | 2.25 MiB |  |
+| `rmsnorm_quant_fp8` | `avx_rmsnorm_quant_fp8` | libavx | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=4` | - | 17.14 | 16.83 | 17.89 | 16 | 1.0 | - | 150.62 KiB | 32 thread(s) |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=3456 K=1152 dtype=bf16 act=none M=4` | 17.11 | - | 17.07 | 17.17 | 6 | 0.3 | 3534 | 7.66 MiB |  |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=5120 group=128 dtype=bf16 M=512` | 17.02 | - | 16.97 | 17.10 | 6 | 0.4 | 3343 | 7.58 MiB |  |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=6144 group=128 dtype=bf16 M=64` | - | 16.87 | 16.61 | 23.55 | 20 | 19.4 | - | 1.14 MiB | 32 thread(s) |
+| `layernorm` | `avx_layernorm` | libavx | `n=1152 eps=1e-06 dtype=bf16 M=512` | - | 16.78 | 16.46 | 22.91 | 20 | 3.0 | - | 2.25 MiB | 32 thread(s) |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=3456 K=1152 dtype=bf16 act=none M=2` | 16.75 | - | 16.71 | 16.82 | 6 | 0.3 | 3532 | 7.63 MiB |  |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=10 splits=0` | 16.61 | - | 16.50 | 16.73 | 6 | 0.7 | 3404 | 4.23 MiB |  |
+| `sample_argmax` | `avx_sample_argmax` | libavx | `n_vocab=248320 M=1` | - | 16.61 | 16.53 | 16.99 | 20 | 1.3 | - | 970.10 KiB | 32 thread(s) |
+| `sample_dry` | `sample_dry_f32` | libr4d | `n_vocab=248320 M=64` | 16.57 | - | 15.53 | 17.06 | 20 | 2.0 | 3471 | 60.65 MiB | restore 93%; restore-dominated (93% of the batch): an order of magnitude |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=3456 K=1152 dtype=bf16 act=none M=1` | 16.52 | - | 16.49 | 16.60 | 6 | 0.3 | 3525 | 7.62 MiB |  |
+| `sample_argmax` | `avx_sample_argmax` | libavx | `n_vocab=248320 M=4` | - | 16.42 | 15.91 | 17.12 | 20 | 1.7 | - | 3.79 MiB | 32 thread(s) |
+| `add` | `avx_add` | libavx | `n=5120 dtype=bf16 M=64` | - | 16.27 | 13.54 | 22.19 | 20 | 17.1 | - | 1.88 MiB | 32 thread(s) |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=9 splits=0` | 16.23 | - | 16.18 | 16.36 | 6 | 0.6 | 3414 | 4.21 MiB |  |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=64` | - | 16.06 | 14.99 | 17.21 | 20 | 5.1 | - | 1.26 MiB | 32 thread(s) |
+| `sample_topp` | `avx_sample_topp` | libavx | `n_cand=1024 M=16` | - | 16.05 | 15.47 | 16.40 | 20 | 1.7 | - | 129.50 KiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=36 ks=0 bk=0 nt=0` | 15.69 | - | 15.64 | 15.80 | 6 | 0.5 | 3356 | 3.06 MiB |  |
+| `sample_xtc` | `avx_sample_xtc` | libavx | `n_cand=1024 M=4` | - | 15.66 | 15.26 | 19.50 | 20 | 7.5 | - | 32.38 KiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=18` | 15.62 | - | 15.58 | 15.67 | 11 | 0.2 | 3364 | 5.13 MiB |  |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=1 splits=0` | 15.61 | - | 15.57 | 15.64 | 6 | 0.2 | 3400 | 4.02 MiB |  |
+| `rmsnorm_quant_fp8` | `rmsnorm_quant_fp8` | libr4d | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=256` | 15.59 | - | 15.54 | 15.62 | 6 | 0.3 | 3343 | 8.80 MiB | restore 16% |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=2 splits=0` | 15.58 | - | 15.54 | 15.62 | 6 | 0.3 | 3400 | 4.05 MiB |  |
+| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu state_form=anchor q_len=4` | 15.55 | - | 15.07 | 15.69 | 11 | 0.7 | 3406 | 18.17 MiB | restore 61% |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=1152 K=1536 dtype=bf16 act=none M=64` | 15.24 | - | 15.21 | 15.28 | 6 | 0.2 | 3505 | 3.85 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=1152 K=1536 dtype=bf16 act=none M=32` | 15.24 | - | 15.17 | 15.28 | 6 | 0.4 | 3502 | 3.61 MiB |  |
+| `scatter_rows` | `scatter_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=512` | 15.07 | - | 14.97 | 15.13 | 6 | 0.5 | 3367 | 25.00 MiB | restore 64% |
+| `sample_penalties` | `sample_penalties_f32` | libr4d | `n_vocab=248320 M=64` | 15.00 | - | 13.06 | 15.12 | 20 | 1.6 | 3457 | 60.65 MiB | restore 94%; restore-dominated (94% of the batch): an order of magnitude |
+| `sample_mask` | `avx_sample_mask` | libavx | `n_vocab=248320 M=1` | - | 14.73 | 14.32 | 15.20 | 20 | 1.6 | - | 1000.41 KiB | 32 thread(s) |
+| `sample_xtc` | `avx_sample_xtc` | libavx | `n_cand=1024 M=8` | - | 14.61 | 14.32 | 15.47 | 20 | 3.0 | - | 64.75 KiB | 32 thread(s) |
+| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | `head_k=128 head_v=128 scale=0.0883883 M=64 chunk=64` | 14.58 | - | 14.56 | 14.66 | 6 | 0.3 | 3347 | 8.40 MiB |  |
+| `sample_mask` | `sample_mask_f32` | libr4d | `n_vocab=248320 M=16` | 14.55 | - | 14.50 | 14.66 | 6 | 0.5 | 3487 | 15.63 MiB | restore 58% |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=1152 K=1152 dtype=bf16 act=none M=128` | 14.55 | - | 14.43 | 14.70 | 6 | 0.9 | 3556 | 3.38 MiB |  |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=16` | - | 14.40 | 14.03 | 21.25 | 20 | 23.8 | - | 416.01 KiB | 32 thread(s) |
+| `rope` | `rope_bf16` | libr4d | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=256` | 14.39 | - | 14.35 | 14.59 | 6 | 0.8 | 3514 | 1.69 MiB | restore 16% |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=1152 K=1536 dtype=bf16 act=none M=16` | 14.32 | - | 14.28 | 14.35 | 6 | 0.3 | 3502 | 3.49 MiB |  |
+| `rope` | `rope_bf16` | libr4d | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=64` | 14.32 | - | 13.91 | 14.43 | 11 | 0.7 | 3537 | 432.50 KiB | restore 13% |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=1152 K=1536 dtype=bf16 act=none M=8` | 14.31 | - | 14.29 | 14.37 | 6 | 0.3 | 3502 | 3.44 MiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=512` | 14.30 | - | 13.81 | 14.31 | 11 | 0.2 | 3366 | 512.50 KiB |  |
+| `rope` | `avx_rope` | libavx | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=64` | - | 14.24 | 13.83 | 14.56 | 20 | 1.3 | - | 768.75 KiB | 32 thread(s) |
+| `grid_embed` | `avx_grid_embed` | libavx | `n=1152 side=48 dtype=bf16 M=1` | - | 14.10 | 13.88 | 14.44 | 19 | 0.9 | - | 5.06 MiB | 32 thread(s) |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=8 splits=0` | 14.06 | - | 13.96 | 14.12 | 6 | 0.6 | 3397 | 4.19 MiB |  |
+| `sample_mask` | `sample_mask_f32` | libr4d | `n_vocab=248320 M=2` | 14.06 | - | 14.00 | 14.16 | 6 | 0.6 | 3481 | 1.95 MiB | restore 17% |
+| `sample_temp` | `sample_temp_f32` | libr4d | `n_vocab=248320 M=2` | 13.95 | - | 13.92 | 13.98 | 6 | 0.2 | 3472 | 1.89 MiB | restore 17% |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=5120 group=128 dtype=bf16 M=64` | - | 13.90 | 13.71 | 19.73 | 20 | 1.2 | - | 970.00 KiB | 32 thread(s) |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=1152 K=1536 dtype=bf16 act=none M=4` | 13.90 | - | 13.84 | 13.94 | 6 | 0.4 | 3500 | 3.41 MiB |  |
+| `embed_lookup` | `avx_embed_lookup` | libavx | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=512` | - | 13.85 | 13.72 | 14.66 | 16 | 1.0 | - | 2.37 GiB | 32 thread(s) |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=1152 K=1536 dtype=bf16 act=none M=2` | 13.72 | - | 13.68 | 13.74 | 6 | 0.2 | 3496 | 3.39 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=1152 K=1536 dtype=bf16 act=none M=1` | 13.66 | - | 13.62 | 14.53 | 14 | 0.4 | 3491 | 3.38 MiB |  |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=6 splits=0` | 13.64 | - | 13.57 | 13.70 | 6 | 0.4 | 3408 | 4.14 MiB |  |
+| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | `head_k=128 M=512 chunk=64` | 13.57 | - | 13.54 | 13.59 | 6 | 0.2 | 3253 | 5.19 MiB |  |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=66` | 13.44 | - | 13.26 | 13.50 | 6 | 0.9 | 3425 | 1.70 MiB |  |
+| `embed_lookup` | `embed_lookup_bf16` | libr4d | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=256` | 13.36 | - | 13.33 | 13.37 | 6 | 0.1 | 3281 | 2.37 GiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=9` | 13.34 | - | 13.29 | 13.39 | 11 | 0.2 | 3367 | 5.06 MiB |  |
+| `attn_dense` | `attn_vit_h72_bf16` | libr4d | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=512` | 13.32 | - | 13.30 | 13.39 | 11 | 0.3 | 3559 | 288.01 KiB |  |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=25600 group=128 dtype=bf16 M=128` | 13.31 | - | 13.19 | 13.38 | 6 | 0.7 | 3346 | 9.47 MiB |  |
+| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=96 K=5120 dtype=bf16 M=512 wv=1 sk=0 mb=0 npw=1 nt=1` | 13.31 | - | 12.97 | 13.76 | 20 | 2.0 | 3288 | 6.03 MiB |  |
+| `add` | `add_bf16` | libr4d | `n=5120 dtype=bf16 M=256` | 13.31 | - | 13.30 | 13.33 | 6 | 0.1 | 3296 | 7.50 MiB |  |
+| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=128` | 13.28 | - | 13.25 | 13.35 | 6 | 0.4 | 3412 | 256.50 KiB | restore 15% |
+| `kv_store` | `kv_store_fp8` | libr4d | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=256` | 13.26 | - | 13.23 | 13.27 | 6 | 0.1 | 3399 | 1.56 MiB | restore 15% |
+| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=256` | 13.26 | - | 13.24 | 13.28 | 6 | 0.1 | 3388 | 515.00 KiB | restore 15% |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=5 splits=0` | 13.24 | - | 13.20 | 13.30 | 6 | 0.4 | 3405 | 4.12 MiB |  |
+| `kv_store` | `kv_store_fp8` | libr4d | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=256` | 13.21 | - | 13.13 | 13.24 | 6 | 0.4 | 3440 | 1.56 MiB | restore 15% |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=4 splits=0` | 13.20 | - | 13.15 | 13.23 | 6 | 0.3 | 3363 | 32.07 MiB |  |
+| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=32` | 13.19 | - | 13.15 | 13.30 | 6 | 0.6 | 3447 | 256.12 KiB | restore 15% |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=8` | 13.17 | - | 13.14 | 13.22 | 11 | 0.3 | 3368 | 5.06 MiB |  |
+| `sample_temp` | `sample_temp_f32` | libr4d | `n_vocab=248320 M=1` | 13.16 | - | 13.09 | 13.18 | 6 | 0.3 | 3478 | 970.09 KiB | restore 16% |
+| `grid_embed` | `grid_embed_bf16` | libr4d | `n=1152 side=48 dtype=bf16 M=256` | 13.14 | - | 13.03 | 13.23 | 6 | 0.8 | 3468 | 5.63 MiB | restore 15% |
+| `sample_mask` | `sample_mask_f32` | libr4d | `n_vocab=248320 M=1` | 13.13 | - | 13.09 | 13.20 | 6 | 0.4 | 3493 | 1000.41 KiB | restore 16% |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=5120 group=128 dtype=bf16 M=256` | 13.13 | - | 13.11 | 13.16 | 6 | 0.2 | 3353 | 3.79 MiB |  |
+| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | `head_k=128 head_v=128 scale=0.0883883 M=32 chunk=64` | 13.11 | - | 13.07 | 13.16 | 6 | 0.4 | 3347 | 7.20 MiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=256` | 13.10 | - | 12.77 | 13.12 | 11 | 0.2 | 3365 | 256.50 KiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=256` | 13.06 | - | 13.03 | 13.06 | 6 | 0.1 | 3362 | 5.01 MiB |  |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=6144 group=128 dtype=bf16 M=256` | 13.05 | - | 13.04 | 13.12 | 6 | 0.3 | 3411 | 4.55 MiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=256` | 13.04 | - | 13.03 | 13.08 | 6 | 0.2 | 3403 | 128.25 KiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=256` | 13.03 | - | 13.01 | 13.17 | 6 | 0.6 | 3381 | 5.01 MiB |  |
+| `scatter_rows` | `scatter_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=256` | 12.97 | - | 12.91 | 13.02 | 6 | 0.4 | 3365 | 12.50 MiB | restore 52% |
+| `sample_temp` | `sample_temp_f32` | libr4d | `n_vocab=1024 M=64` | 12.96 | - | 12.92 | 12.98 | 6 | 0.3 | 3585 | 262.00 KiB | restore 14% |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=2 splits=0` | 12.94 | - | 12.94 | 13.00 | 6 | 0.2 | 3364 | 32.04 MiB |  |
+| `sample_topp` | `avx_sample_topp` | libavx | `n_cand=1024 M=4` | - | 12.94 | 12.19 | 13.79 | 20 | 5.4 | - | 32.38 KiB | 32 thread(s) |
+| `layernorm` | `layernorm_bf16` | libr4d | `n=1152 eps=1e-06 dtype=bf16 M=256` | 12.92 | - | 12.89 | 12.98 | 6 | 0.3 | 3541 | 1.13 MiB |  |
+| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | `head_k=128 head_v=128 scale=0.0883883 M=16 chunk=64` | 12.86 | - | 12.80 | 12.93 | 6 | 0.5 | 3348 | 6.60 MiB |  |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=4 splits=0` | 12.86 | - | 12.81 | 12.90 | 6 | 0.3 | 3411 | 4.09 MiB |  |
+| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | `head_k=128 head_v=128 scale=0.0883883 M=8 chunk=64` | 12.86 | - | 12.81 | 12.91 | 6 | 0.4 | 3355 | 6.30 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=4` | 12.81 | - | 12.78 | 12.83 | 11 | 0.2 | 3370 | 5.03 MiB |  |
+| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | `head_k=128 head_v=128 scale=0.0883883 M=4 chunk=64` | 12.80 | - | 12.73 | 12.88 | 6 | 0.6 | 3353 | 6.15 MiB |  |
+| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | `head_k=128 head_v=128 scale=0.0883883 M=2 chunk=64` | 12.80 | - | 12.75 | 12.87 | 6 | 0.5 | 3350 | 6.07 MiB |  |
+| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | `head_k=128 head_v=128 scale=0.0883883 M=1 chunk=64` | 12.78 | - | 12.71 | 12.85 | 6 | 0.5 | 3196 | 6.04 MiB |  |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=8 splits=0` | 12.74 | - | 12.67 | 12.77 | 6 | 0.4 | 3352 | 32.13 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=1` | 12.72 | - | 12.63 | 14.33 | 20 | 4.1 | 2889 | 5.01 MiB |  |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=6 splits=0` | 12.62 | - | 12.57 | 12.75 | 6 | 0.7 | 3352 | 32.10 MiB |  |
+| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=2` | 12.60 | - | 12.55 | 12.65 | 11 | 0.3 | 3362 | 5.01 MiB |  |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=17408 group=128 dtype=bf16 M=16` | - | 12.57 | 12.34 | 17.26 | 20 | 2.5 | - | 824.50 KiB | 32 thread(s) |
+| `sample_topp` | `avx_sample_topp` | libavx | `n_cand=1024 M=8` | - | 12.57 | 12.15 | 13.02 | 19 | 0.8 | - | 64.75 KiB | 32 thread(s) |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=5 splits=0` | 12.45 | - | 12.41 | 12.56 | 6 | 0.6 | 3352 | 32.08 MiB |  |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=25600 group=128 dtype=bf16 M=8` | - | 12.45 | 12.24 | 15.41 | 20 | 6.6 | - | 606.25 KiB | 32 thread(s) |
+| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 conv_width=4 q_len=16` | 12.39 | - | 12.32 | 12.43 | 6 | 0.4 | 3399 | 1.05 MiB | restore 16% |
+| `silu_mul` | `avx_silu_mul` | libavx | `n=17408 dtype=bf16 M=16` | - | 12.38 | 12.22 | 16.99 | 20 | 18.7 | - | 1.59 MiB | 32 thread(s) |
+| `sample_topp` | `avx_sample_topp` | libavx | `n_cand=1024 M=2` | - | 12.35 | 12.13 | 12.70 | 19 | 0.9 | - | 16.19 KiB | 32 thread(s) |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=64` | - | 12.31 | 11.87 | 12.77 | 20 | 1.5 | - | 1.26 MiB | 32 thread(s) |
+| `quant_act_i8` | `avx_quant_act_i8` | libavx | `n=5120 group=128 dtype=bf16 M=56` | - | 12.30 | 11.90 | 12.82 | 20 | 2.4 | - | 850.22 KiB | 32 thread(s) |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=25600 group=128 dtype=bf16 M=4` | - | 12.27 | 12.00 | 14.64 | 20 | 9.5 | - | 303.12 KiB | 32 thread(s) |
+| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=512` | 12.18 | - | 12.12 | 12.26 | 6 | 0.6 | 3331 | 6.01 MiB | restore 43% |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=1 splits=0` | 12.09 | - | 12.06 | 12.19 | 6 | 0.5 | 3364 | 32.02 MiB |  |
+| `rope` | `avx_rope` | libavx | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=128` | - | 12.04 | 11.70 | 12.61 | 20 | 2.6 | - | 256.50 KiB | 32 thread(s) |
+| `rope` | `avx_rope` | libavx | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=32` | - | 12.02 | 8.93 | 12.51 | 20 | 5.9 | - | 216.25 KiB | 32 thread(s) |
+| `rope` | `avx_rope` | libavx | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=256` | - | 11.98 | 10.96 | 12.15 | 20 | 2.0 | - | 515.00 KiB | 32 thread(s) |
+| `sample_xtc` | `avx_sample_xtc` | libavx | `n_cand=1024 M=2` | - | 11.95 | 11.46 | 15.21 | 20 | 8.2 | - | 16.19 KiB | 32 thread(s) |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=17408 group=128 dtype=bf16 M=8` | - | 11.80 | 11.69 | 16.86 | 20 | 16.6 | - | 412.25 KiB | 32 thread(s) |
+| `sample_minp` | `avx_sample_minp` | libavx | `n_cand=1024 M=4` | - | 11.72 | 11.53 | 11.93 | 19 | 1.0 | - | 32.38 KiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=18 ks=0 bk=0 nt=0` | 11.70 | - | 11.67 | 11.73 | 6 | 0.3 | 3356 | 2.94 MiB |  |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=4 splits=0` | 11.62 | - | 11.59 | 11.66 | 6 | 0.3 | 3366 | 4.06 MiB |  |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=8 splits=0` | 11.58 | - | 11.54 | 11.60 | 6 | 0.3 | 3356 | 4.13 MiB |  |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=25600 group=128 dtype=bf16 M=2` | - | 11.55 | 11.33 | 11.78 | 20 | 1.1 | - | 151.56 KiB | 32 thread(s) |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=2 splits=0` | 11.48 | - | 11.43 | 11.54 | 6 | 0.5 | 3360 | 4.03 MiB |  |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=1 splits=0` | 11.44 | - | 11.39 | 11.47 | 6 | 0.4 | 3362 | 4.02 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=1152 K=1152 dtype=bf16 act=none M=64` | 11.40 | - | 11.38 | 11.43 | 6 | 0.2 | 3572 | 2.96 MiB |  |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=6 splits=0` | 11.40 | - | 11.37 | 11.42 | 6 | 0.2 | 3356 | 4.09 MiB |  |
+| `sample_argmax` | `sample_argmax_f32` | libr4d | `n_vocab=248320 M=8` | 11.37 | - | 11.33 | 11.46 | 6 | 0.6 | 3534 | 7.58 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=1152 K=1152 dtype=bf16 act=none M=32` | 11.35 | - | 11.34 | 11.38 | 6 | 0.2 | 3566 | 2.74 MiB |  |
+| `sample_argmax` | `sample_argmax_f32` | libr4d | `n_vocab=248320 M=4` | 11.33 | - | 11.31 | 11.39 | 6 | 0.4 | 3531 | 3.79 MiB |  |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=5 splits=0` | 11.29 | - | 11.25 | 11.34 | 6 | 0.4 | 3358 | 4.08 MiB |  |
+| `sample_argmax` | `sample_argmax_f32` | libr4d | `n_vocab=248320 M=2` | 11.27 | - | 11.24 | 11.33 | 6 | 0.4 | 3534 | 1.89 MiB |  |
+| `sample_argmax` | `sample_argmax_f32` | libr4d | `n_vocab=248320 M=1` | 11.26 | - | 11.22 | 11.32 | 6 | 0.4 | 3525 | 970.10 KiB |  |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=25600 group=128 dtype=bf16 M=1` | - | 11.21 | 11.10 | 11.43 | 16 | 0.9 | - | 75.78 KiB | 32 thread(s) |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=128` | 11.17 | - | 11.16 | 11.20 | 6 | 0.2 | 3364 | 2.51 MiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=128` | 11.13 | - | 11.10 | 11.14 | 6 | 0.2 | 3385 | 2.51 MiB |  |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=25600 group=128 dtype=bf16 M=64` | 11.05 | - | 10.98 | 11.08 | 6 | 0.5 | 3364 | 4.74 MiB |  |
+| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu state_form=anchor q_len=2` | 10.82 | - | 10.54 | 10.96 | 14 | 0.8 | 3402 | 18.09 MiB | restore 70% |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=10 splits=0` | 10.80 | - | 10.76 | 10.84 | 6 | 0.4 | 3415 | 272.01 KiB |  |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=25600 group=128 dtype=bf16 M=32` | 10.66 | - | 10.61 | 10.71 | 6 | 0.5 | 3368 | 2.37 MiB |  |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=25600 group=128 dtype=bf16 M=16` | 10.64 | - | 10.60 | 10.66 | 6 | 0.3 | 3369 | 1.18 MiB |  |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=25600 group=128 dtype=bf16 M=8` | 10.62 | - | 10.58 | 10.65 | 6 | 0.3 | 3372 | 606.25 KiB |  |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=9 splits=0` | 10.59 | - | 10.56 | 10.60 | 6 | 0.2 | 3417 | 248.01 KiB |  |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=25600 group=128 dtype=bf16 M=4` | 10.58 | - | 10.56 | 10.61 | 6 | 0.2 | 3371 | 303.12 KiB |  |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=25600 group=128 dtype=bf16 M=2` | 10.55 | - | 10.54 | 10.57 | 6 | 0.2 | 3371 | 151.56 KiB |  |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=25600 group=128 dtype=bf16 M=1` | 10.51 | - | 10.49 | 10.64 | 6 | 0.8 | 3358 | 75.78 KiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=1152 K=1152 dtype=bf16 act=none M=8` | 10.49 | - | 10.46 | 10.51 | 6 | 0.2 | 3564 | 2.59 MiB |  |
+| `sample_temp` | `avx_sample_temp` | libavx | `n_vocab=1024 M=64` | - | 10.49 | 10.04 | 11.13 | 20 | 1.8 | - | 262.00 KiB | 32 thread(s) |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=1152 K=1152 dtype=bf16 act=none M=16` | 10.48 | - | 10.44 | 10.52 | 6 | 0.4 | 3562 | 2.64 MiB |  |
+| `sample_pick` | `avx_sample_pick` | libavx | `n_cand=1024 M=16` | - | 10.44 | 10.13 | 10.75 | 20 | 1.7 | - | 129.56 KiB | 32 thread(s) |
+| `sample_minp` | `avx_sample_minp` | libavx | `n_cand=1024 M=2` | - | 10.36 | 9.99 | 14.48 | 20 | 19.5 | - | 16.19 KiB | 32 thread(s) |
+| `sample_pick` | `avx_sample_pick` | libavx | `n_cand=1024 M=8` | - | 10.31 | 10.25 | 10.76 | 19 | 0.8 | - | 64.78 KiB | 32 thread(s) |
+| `sample_mask` | `avx_sample_mask` | libavx | `n_vocab=248320 M=2` | - | 10.26 | 9.95 | 10.58 | 20 | 2.4 | - | 1.95 MiB | 32 thread(s) |
+| `gdn_kkt_solve` | `avx_gdn_kkt_solve` | libavx | `head_k=128 M=16 chunk=64` | - | 10.25 | 10.12 | 10.46 | 20 | 1.1 | - | 166.01 KiB | 32 thread(s) |
+| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | `head_k=128 M=256 chunk=64` | 10.24 | - | 10.21 | 10.29 | 6 | 0.4 | 3364 | 2.59 MiB |  |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=32` | - | 10.17 | 9.76 | 10.67 | 20 | 2.7 | - | 650.00 KiB | 32 thread(s) |
+| `kv_store` | `avx_kv_store` | libavx | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=64` | - | 10.15 | 9.81 | 10.68 | 20 | 2.7 | - | 448.25 KiB | 32 thread(s) |
+| `gated_quant_fp8` | `gated_quant_fp8` | libr4d | `n=17408 group=128 dtype=bf16 act=silu M=64` | 10.11 | - | 10.07 | 10.13 | 6 | 0.3 | 3304 | 7.47 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=1152 K=1152 dtype=bf16 act=none M=4` | 10.05 | - | 10.04 | 10.11 | 6 | 0.3 | 3565 | 2.56 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=1152 K=1152 dtype=bf16 act=none M=2` | 9.90 | - | 9.86 | 9.92 | 6 | 0.3 | 3564 | 2.55 MiB |  |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=9 ks=0 bk=0 nt=0` | 9.80 | - | 9.80 | 9.88 | 6 | 0.4 | 3360 | 2.88 MiB |  |
+| `gemm_nt_bias` | `gemm_bf16_nt_bias_tiled` | libr4d | `N=1152 K=1152 dtype=bf16 act=none M=1` | 9.79 | - | 9.76 | 9.81 | 6 | 0.2 | 3560 | 2.54 MiB |  |
+| `layernorm` | `avx_layernorm` | libavx | `n=1152 eps=1e-06 dtype=bf16 M=256` | - | 9.74 | 9.54 | 10.59 | 20 | 2.8 | - | 1.13 MiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=8 ks=0 bk=0 nt=0` | 9.64 | - | 9.62 | 9.69 | 6 | 0.3 | 3360 | 2.87 MiB |  |
+| `sample_xtc` | `avx_sample_xtc` | libavx | `n_cand=1024 M=1` | - | 9.61 | 9.53 | 9.79 | 14 | 0.5 | - | 8.09 KiB | 32 thread(s) |
+| `sample_temp` | `sample_temp_f32` | libr4d | `n_vocab=248320 M=8` | 9.58 | - | 9.56 | 9.61 | 6 | 0.3 | 3462 | 7.58 MiB | restore 53% |
+| `rmsnorm_quant_fp8` | `avx_rmsnorm_quant_fp8` | libavx | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=2` | - | 9.52 | 9.20 | 9.99 | 20 | 2.1 | - | 80.31 KiB | 32 thread(s) |
+| `sample_mask` | `sample_mask_f32` | libr4d | `n_vocab=248320 M=8` | 9.42 | - | 9.38 | 9.49 | 6 | 0.6 | 3424 | 7.82 MiB | restore 54% |
+| `dflash_select` | `dflash_select_bf16` | libr4d | `steps=7 top_k=16 rank=256 n_vocab=248320 anchor_stride=8 dtype=bf16 M=8` | 9.26 | - | 9.24 | 9.30 | 11 | 0.3 | 3495 | 242.53 MiB |  |
+| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | `head_k=128 M=128 chunk=64` | 9.26 | - | 9.25 | 9.28 | 6 | 0.2 | 3369 | 1.30 MiB |  |
+| `dflash_select` | `dflash_select_bf16` | libr4d | `steps=7 top_k=16 rank=256 n_vocab=248320 anchor_stride=8 dtype=bf16 M=4` | 9.23 | - | 9.21 | 9.35 | 6 | 0.8 | 3497 | 242.52 MiB |  |
+| `silu_mul` | `avx_silu_mul` | libavx | `n=17408 dtype=bf16 M=2` | - | 9.17 | 8.78 | 9.44 | 20 | 2.2 | - | 204.00 KiB | 32 thread(s) |
+| `dflash_select` | `dflash_select_bf16` | libr4d | `steps=7 top_k=16 rank=256 n_vocab=248320 anchor_stride=8 dtype=bf16 M=2` | 9.17 | - | 9.15 | 9.23 | 11 | 0.4 | 3489 | 242.51 MiB |  |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=8 splits=0` | 9.14 | - | 9.12 | 9.15 | 6 | 0.2 | 3417 | 224.01 KiB |  |
+| `dflash_select` | `dflash_select_bf16` | libr4d | `steps=7 top_k=16 rank=256 n_vocab=248320 anchor_stride=8 dtype=bf16 M=1` | 9.13 | - | 9.12 | 9.18 | 6 | 0.4 | 3485 | 242.50 MiB |  |
+| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu state_form=anchor q_len=1` | 9.11 | - | 8.94 | 9.24 | 14 | 0.8 | 3397 | 18.04 MiB | restore 73% |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=6144 group=128 dtype=bf16 M=32` | - | 9.10 | 8.94 | 10.73 | 20 | 2.8 | - | 582.00 KiB | 32 thread(s) |
+| `silu_mul` | `avx_silu_mul` | libavx | `n=17408 dtype=bf16 M=8` | - | 9.09 | 8.79 | 9.98 | 20 | 3.8 | - | 816.00 KiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=4 ks=0 bk=0 nt=0` | 9.01 | - | 9.00 | 9.06 | 6 | 0.3 | 3360 | 2.84 MiB |  |
+| `rope` | `avx_rope` | libavx | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=32` | - | 8.94 | 8.56 | 9.11 | 20 | 2.5 | - | 384.38 KiB | 32 thread(s) |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=4096 group=128 dtype=bf16 M=64` | - | 8.91 | 8.67 | 10.05 | 20 | 1.1 | - | 776.00 KiB | 32 thread(s) |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=6 splits=0` | 8.86 | - | 8.84 | 8.87 | 6 | 0.2 | 3415 | 176.01 KiB |  |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=17408 group=128 dtype=bf16 M=4` | - | 8.86 | 8.61 | 10.24 | 20 | 8.5 | - | 206.12 KiB | 32 thread(s) |
+| `add` | `avx_add` | libavx | `n=5120 dtype=bf16 M=32` | - | 8.84 | 8.61 | 10.23 | 20 | 8.2 | - | 960.00 KiB | 32 thread(s) |
+| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=96 K=5120 dtype=bf16 M=260 wv=1 sk=0 mb=0 npw=1 nt=1` | 8.82 | - | 8.77 | 8.89 | 11 | 0.6 | 3336 | 3.52 MiB |  |
+| `rope` | `avx_rope` | libavx | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=64` | - | 8.81 | 8.19 | 9.04 | 20 | 3.1 | - | 128.25 KiB | 32 thread(s) |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=17408 group=128 dtype=bf16 M=1` | - | 8.77 | 8.34 | 8.99 | 20 | 2.2 | - | 51.53 KiB | 32 thread(s) |
+| `silu_mul` | `avx_silu_mul` | libavx | `n=17408 dtype=bf16 M=4` | - | 8.74 | 8.63 | 9.48 | 20 | 2.2 | - | 408.00 KiB | 32 thread(s) |
+| `sample_pick` | `avx_sample_pick` | libavx | `n_cand=1024 M=4` | - | 8.74 | 8.56 | 8.94 | 20 | 1.6 | - | 32.39 KiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=2 ks=0 bk=0 nt=0` | 8.71 | - | 8.70 | 8.75 | 6 | 0.3 | 3356 | 2.83 MiB |  |
+| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=512` | 8.64 | - | 8.57 | 8.68 | 6 | 0.6 | 3387 | 1.00 MiB | restore 22% |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=1 splits=0` | 8.59 | - | 8.55 | 8.60 | 6 | 0.2 | 3396 | 56.01 KiB |  |
+| `gdn_gated_rmsnorm` | `avx_gdn_gated_rmsnorm` | libavx | `channels=128 eps=1e-06 act=silu M=512` | - | 8.56 | 7.54 | 10.30 | 20 | 15.3 | - | 384.50 KiB | 32 thread(s) |
+| `gemm_nt_q` | `gemm_mxfp4a8_decode` | libr4d | `N=1024 K=5120 group=32 dtype=mxfp4a8 M=1 ks=0 bk=0 nt=0` | 8.56 | - | 8.55 | 8.57 | 6 | 0.2 | 3357 | 2.82 MiB |  |
+| `kv_store` | `avx_kv_store` | libavx | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=64` | - | 8.52 | 8.01 | 9.36 | 20 | 3.9 | - | 448.25 KiB | 32 thread(s) |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=33` | 8.47 | - | 8.44 | 8.53 | 6 | 0.5 | 3438 | 888.02 KiB |  |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=2 splits=0` | 8.46 | - | 8.45 | 8.49 | 6 | 0.2 | 3408 | 80.01 KiB |  |
+| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | `head_k=128 M=64 chunk=64` | 8.44 | - | 8.42 | 8.46 | 6 | 0.2 | 3368 | 664.01 KiB |  |
+| `rope` | `rope_bf16` | libr4d | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=128` | 8.44 | - | 8.40 | 8.57 | 11 | 1.0 | 3507 | 865.00 KiB | restore 21% |
+| `sample_topp` | `avx_sample_topp` | libavx | `n_cand=1024 M=1` | - | 8.41 | 8.39 | 8.47 | 11 | 0.5 | - | 8.09 KiB | 32 thread(s) |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=32` | 8.35 | - | 8.33 | 8.40 | 6 | 0.4 | 3438 | 832.01 KiB |  |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=5 splits=0` | 8.35 | - | 8.34 | 8.38 | 6 | 0.2 | 3415 | 152.01 KiB |  |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=11` | - | 8.35 | 8.22 | 11.32 | 20 | 16.9 | - | 296.01 KiB | 32 thread(s) |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=17408 group=128 dtype=bf16 M=2` | - | 8.31 | 8.22 | 8.43 | 14 | 0.9 | - | 103.06 KiB | 32 thread(s) |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=5120 group=128 dtype=bf16 M=32` | - | 8.20 | 7.93 | 10.62 | 20 | 7.9 | - | 485.00 KiB | 32 thread(s) |
+| `quant_act_i8` | `quant_act_i8` | libr4d | `n=5120 group=128 dtype=bf16 M=56` | 8.17 | - | 8.14 | 8.19 | 6 | 0.3 | 3446 | 850.22 KiB |  |
+| `attn_paged` | `attn_decode_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=4 splits=0` | 8.15 | - | 8.15 | 8.17 | 6 | 0.2 | 3414 | 128.01 KiB |  |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=16` | 8.11 | - | 8.10 | 8.19 | 6 | 0.6 | 3428 | 416.01 KiB |  |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=11` | 8.09 | - | 8.05 | 8.15 | 6 | 0.6 | 3414 | 296.01 KiB |  |
+| `attn_paged` | `attn_prefill_h256_gqa6_fp8kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=17` | 8.08 | - | 8.06 | 8.15 | 6 | 0.5 | 3423 | 472.01 KiB |  |
+| `scatter_rows` | `avx_scatter_rows` | libavx | `n=5120 dtype=bf16 M=32` | - | 8.07 | 7.20 | 9.07 | 20 | 4.7 | - | 1.56 MiB | 32 thread(s) |
+| `sample_pick` | `avx_sample_pick` | libavx | `n_cand=1024 M=1` | - | 8.06 | 7.82 | 8.25 | 19 | 0.7 | - | 8.10 KiB | 32 thread(s) |
+| `sample_penalties` | `avx_sample_penalties` | libavx | `n_vocab=248320 M=64` | - | 8.03 | 6.82 | 9.05 | 20 | 4.5 | - | 60.65 MiB | 32 thread(s) |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=17408 group=128 dtype=bf16 M=64` | 8.02 | - | 7.97 | 8.06 | 6 | 0.5 | 3454 | 3.22 MiB |  |
+| `attn_dense` | `attn_vit_h72_bf16` | libr4d | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=256` | 7.96 | - | 7.94 | 7.98 | 6 | 0.2 | 3564 | 144.01 KiB |  |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=32` | - | 7.87 | 7.77 | 8.32 | 20 | 1.5 | - | 650.00 KiB | 32 thread(s) |
+| `sample_xtc` | `sample_xtc_f32` | libr4d | `n_cand=1024 M=64` | 7.85 | - | 7.76 | 7.91 | 11 | 0.7 | 3584 | 518.00 KiB | restore 36% |
+| `quant_act_i8` | `avx_quant_act_i8` | libavx | `n=5120 group=128 dtype=bf16 M=32` | - | 7.85 | 7.64 | 8.64 | 20 | 3.8 | - | 485.12 KiB | 32 thread(s) |
+| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | `head_k=128 M=32 chunk=64` | 7.77 | - | 7.75 | 7.78 | 6 | 0.2 | 3375 | 332.01 KiB |  |
+| `sample_dry` | `sample_dry_f32` | libr4d | `n_vocab=248320 M=4` | 7.76 | - | 7.69 | 7.82 | 6 | 0.8 | 3388 | 3.79 MiB | restore 35% |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=17408 group=128 dtype=bf16 M=32` | 7.76 | - | 7.71 | 7.77 | 6 | 0.4 | 3459 | 1.61 MiB |  |
+| `sample_xtc` | `sample_xtc_f32` | libr4d | `n_cand=1024 M=4` | 7.74 | - | 7.73 | 7.76 | 6 | 0.2 | 3586 | 32.38 KiB | restore 35% |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=17408 group=128 dtype=bf16 M=16` | 7.72 | - | 7.70 | 7.76 | 6 | 0.4 | 3460 | 824.50 KiB |  |
+| `sample_xtc` | `sample_xtc_f32` | libr4d | `n_cand=1024 M=32` | 7.71 | - | 7.66 | 7.76 | 6 | 0.6 | 3587 | 259.00 KiB | restore 36% |
+| `cast` | `cast_bf16_bf16` | libr4d | `n=5120 from=bf16 to=bf16 M=512` | 7.70 | - | 7.68 | 7.75 | 6 | 0.5 | 3342 | 10.00 MiB |  |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=17408 group=128 dtype=bf16 M=8` | 7.70 | - | 7.68 | 7.71 | 6 | 0.2 | 3464 | 412.25 KiB |  |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=17408 group=128 dtype=bf16 M=2` | 7.67 | - | 7.66 | 7.68 | 6 | 0.2 | 3456 | 103.06 KiB |  |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=17408 group=128 dtype=bf16 M=4` | 7.66 | - | 7.63 | 7.67 | 6 | 0.2 | 3463 | 206.12 KiB |  |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=17408 group=128 dtype=bf16 M=1` | 7.64 | - | 7.62 | 7.66 | 6 | 0.3 | 3451 | 51.53 KiB |  |
+| `sample_xtc` | `sample_xtc_f32` | libr4d | `n_cand=1024 M=2` | 7.60 | - | 7.51 | 7.64 | 6 | 0.9 | 3586 | 16.19 KiB | restore 36% |
+| `sample_dry` | `sample_dry_f32` | libr4d | `n_vocab=248320 M=2` | 7.57 | - | 7.56 | 7.59 | 6 | 0.2 | 3441 | 1.90 MiB | restore 27% |
+| `rope` | `avx_rope` | libavx | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=32` | - | 7.56 | 7.26 | 8.47 | 20 | 3.2 | - | 256.12 KiB | 32 thread(s) |
+| `sample_dry` | `sample_dry_f32` | libr4d | `n_vocab=248320 M=1` | 7.53 | - | 7.51 | 7.55 | 6 | 0.2 | 3458 | 970.41 KiB | restore 24% |
+| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=256` | 7.43 | - | 7.43 | 7.45 | 6 | 0.2 | 3337 | 3.00 MiB | restore 30% |
+| `sample_xtc` | `sample_xtc_f32` | libr4d | `n_cand=1024 M=16` | 7.43 | - | 7.37 | 7.49 | 6 | 0.8 | 3586 | 129.50 KiB | restore 37% |
+| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=256 K=5120 dtype=bf16 M=56 wv=1 sk=0 mb=0 npw=1 nt=1` | 7.42 | - | 7.41 | 7.45 | 6 | 0.3 | 3474 | 3.07 MiB |  |
+| `sample_xtc` | `sample_xtc_f32` | libr4d | `n_cand=1024 M=8` | 7.41 | - | 7.39 | 7.43 | 6 | 0.3 | 3585 | 64.75 KiB | restore 37% |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=9 splits=0` | - | 7.38 | 7.31 | 7.58 | 20 | 1.1 | - | 248.01 KiB | 32 thread(s) |
+| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | `head_k=128 M=16 chunk=64` | 7.38 | - | 7.37 | 7.39 | 6 | 0.1 | 3373 | 166.01 KiB |  |
+| `sample_dry` | `sample_dry_f32` | libr4d | `n_vocab=248320 M=8` | 7.38 | - | 7.31 | 7.41 | 6 | 0.7 | 3444 | 7.58 MiB | restore 60% |
+| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | `head_k=128 M=8 chunk=64` | 7.33 | - | 7.31 | 7.34 | 6 | 0.2 | 3380 | 83.01 KiB |  |
+| `silu_mul` | `avx_silu_mul` | libavx | `n=17408 dtype=bf16 M=1` | - | 7.32 | 7.28 | 7.42 | 6 | 1.0 | - | 102.00 KiB | 32 thread(s) |
+| `layernorm` | `avx_layernorm` | libavx | `n=1152 eps=1e-06 dtype=bf16 M=128` | - | 7.30 | 7.17 | 8.47 | 20 | 7.5 | - | 580.50 KiB | 32 thread(s) |
+| `cast` | `avx_cast` | libavx | `n=5120 from=bf16 to=bf16 M=128` | - | 7.20 | 6.96 | 9.53 | 20 | 15.5 | - | 2.50 MiB | 32 thread(s) |
+| `rope` | `avx_rope` | libavx | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=128` | - | 7.20 | 6.92 | 7.38 | 20 | 1.9 | - | 257.50 KiB | 32 thread(s) |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=4096 group=128 dtype=bf16 M=32` | - | 7.19 | 7.12 | 8.44 | 20 | 2.0 | - | 388.00 KiB | 32 thread(s) |
+| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | `head_k=128 M=4 chunk=64` | 7.18 | - | 7.17 | 7.19 | 6 | 0.1 | 3382 | 41.51 KiB |  |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=6 splits=0` | 7.16 | - | 7.14 | 7.17 | 6 | 0.2 | 3368 | 128.01 KiB |  |
+| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=256 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | 7.14 | - | 7.13 | 7.15 | 6 | 0.1 | 3472 | 2.85 MiB |  |
+| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | `head_k=128 M=1 chunk=64` | 7.14 | - | 7.11 | 7.32 | 14 | 0.1 | 3372 | 10.38 KiB |  |
+| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | `head_k=128 M=2 chunk=64` | 7.14 | - | 7.13 | 7.15 | 6 | 0.1 | 3381 | 20.76 KiB |  |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=5 splits=0` | 7.03 | - | 7.01 | 7.05 | 6 | 0.3 | 3369 | 112.01 KiB |  |
+| `embed_lookup` | `avx_embed_lookup` | libavx | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=256` | - | 7.01 | 6.94 | 7.45 | 19 | 0.7 | - | 2.37 GiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=10 splits=0` | - | 6.98 | 6.75 | 7.80 | 20 | 5.0 | - | 272.01 KiB | 32 thread(s) |
+| `sample_xtc` | `sample_xtc_f32` | libr4d | `n_cand=1024 M=1` | 6.98 | - | 6.94 | 6.99 | 6 | 0.3 | 3588 | 8.09 KiB | restore 37% |
+| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=256 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | 6.93 | - | 6.92 | 6.96 | 6 | 0.3 | 3486 | 2.66 MiB |  |
+| `rope` | `avx_rope` | libavx | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=8` | - | 6.90 | 6.54 | 7.19 | 20 | 3.4 | - | 54.06 KiB | 32 thread(s) |
+| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=256 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | 6.88 | - | 6.88 | 6.89 | 6 | 0.1 | 3470 | 2.58 MiB |  |
+| `rope` | `avx_rope` | libavx | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=16` | - | 6.88 | 5.52 | 7.06 | 20 | 2.6 | - | 108.12 KiB | 32 thread(s) |
+| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=256 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | 6.88 | - | 6.87 | 6.92 | 6 | 0.4 | 3480 | 2.67 MiB |  |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=4 splits=0` | 6.88 | - | 6.86 | 6.89 | 6 | 0.2 | 3368 | 96.01 KiB |  |
+| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=256 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | 6.86 | - | 6.86 | 6.91 | 6 | 0.4 | 3470 | 2.52 MiB |  |
+| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=256 K=5120 dtype=bf16 M=1 wv=1 sk=0 mb=0 npw=1 nt=1` | 6.86 | - | 6.85 | 6.89 | 11 | 0.3 | 3469 | 2.51 MiB |  |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=1 splits=0` | 6.86 | - | 6.83 | 7.98 | 20 | 3.9 | 3280 | 48.01 KiB |  |
+| `sample_pick` | `avx_sample_pick` | libavx | `n_cand=1024 M=2` | - | 6.86 | 6.77 | 6.99 | 14 | 0.8 | - | 16.20 KiB | 32 thread(s) |
+| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=256 K=5120 dtype=bf16 M=4 wv=1 sk=0 mb=0 npw=1 nt=1` | 6.86 | - | 6.85 | 6.90 | 6 | 0.4 | 3472 | 2.54 MiB |  |
+| `attn_dense` | `avx_attn_dense` | libavx | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=16` | - | 6.80 | 6.74 | 7.03 | 20 | 1.3 | - | 9.01 KiB | 32 thread(s) |
+| `rope` | `avx_rope` | libavx | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=16` | - | 6.80 | 6.16 | 7.15 | 20 | 5.0 | - | 128.06 KiB | 32 thread(s) |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=2 splits=0` | 6.79 | - | 6.78 | 6.80 | 6 | 0.1 | 3369 | 64.01 KiB |  |
+| `sample_pick` | `sample_pick_f32` | libr4d | `n_cand=1024 M=2` | 6.77 | - | 6.75 | 6.80 | 6 | 0.3 | 3584 | 16.20 KiB |  |
+| `sample_temp` | `avx_sample_temp` | libavx | `n_vocab=1024 M=32` | - | 6.72 | 6.44 | 6.91 | 20 | 2.3 | - | 131.00 KiB | 32 thread(s) |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=16` | - | 6.71 | 6.55 | 7.17 | 20 | 3.1 | - | 330.00 KiB | 32 thread(s) |
+| `sample_dry` | `sample_dry_f32` | libr4d | `n_vocab=248320 M=16` | 6.67 | - | 6.55 | 6.71 | 14 | 0.7 | 3448 | 15.16 MiB | restore 75% |
+| `sample_minp` | `avx_sample_minp` | libavx | `n_cand=1024 M=1` | - | 6.66 | 6.57 | 7.03 | 16 | 1.0 | - | 8.09 KiB | 32 thread(s) |
+| `rope` | `avx_rope` | libavx | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=16` | - | 6.64 | 6.19 | 7.25 | 20 | 4.5 | - | 192.19 KiB | 32 thread(s) |
+| `attn_paged` | `attn_decode_h128_gqa4_fp8kv` | libr4d | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=8 splits=0` | 6.62 | - | 6.58 | 6.66 | 6 | 0.6 | 3362 | 160.01 KiB |  |
+| `grid_embed` | `grid_embed_bf16` | libr4d | `n=1152 side=48 dtype=bf16 M=512` | 6.62 | - | 6.60 | 6.64 | 6 | 0.3 | 3415 | 6.20 MiB | restore 27% |
+| `silu_mul` | `silu_mul_bf16` | libr4d | `n=17408 dtype=bf16 M=64` | 6.62 | - | 6.58 | 6.64 | 6 | 0.4 | 3379 | 6.38 MiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=64` | 6.60 | - | 6.58 | 6.61 | 6 | 0.2 | 3365 | 1.26 MiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=64` | 6.58 | - | 6.56 | 6.59 | 6 | 0.2 | 3385 | 1.26 MiB |  |
+| `layernorm` | `avx_layernorm` | libavx | `n=1152 eps=1e-06 dtype=bf16 M=64` | - | 6.49 | 6.11 | 7.06 | 20 | 3.4 | - | 292.50 KiB | 32 thread(s) |
+| `rmsnorm_quant_fp8` | `rmsnorm_quant_fp8` | libr4d | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=128` | 6.44 | - | 6.40 | 6.52 | 6 | 0.9 | 3365 | 4.40 MiB | restore 28% |
+| `kv_store` | `avx_kv_store` | libavx | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=32` | - | 6.38 | 5.79 | 6.67 | 20 | 4.0 | - | 256.12 KiB | 32 thread(s) |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=8` | - | 6.27 | 5.83 | 6.82 | 20 | 4.0 | - | 170.00 KiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=8 splits=0` | - | 6.23 | 6.05 | 6.50 | 16 | 1.0 | - | 224.01 KiB | 32 thread(s) |
+| `quant_act_i8` | `avx_quant_act_i8` | libavx | `n=5120 group=128 dtype=bf16 M=16` | - | 6.12 | 5.71 | 6.38 | 20 | 2.5 | - | 242.56 KiB | 32 thread(s) |
+| `dflash_select` | `avx_dflash_select` | libavx | `steps=7 top_k=16 rank=256 n_vocab=248320 anchor_stride=8 dtype=bf16 M=2` | - | 6.03 | 5.41 | 6.51 | 20 | 6.9 | - | 242.51 MiB | 32 thread(s) |
+| `dflash_select` | `avx_dflash_select` | libavx | `steps=7 top_k=16 rank=256 n_vocab=248320 anchor_stride=8 dtype=bf16 M=8` | - | 6.03 | 5.82 | 6.70 | 20 | 6.0 | - | 242.53 MiB | 32 thread(s) |
+| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=96 K=5120 dtype=bf16 M=130 wv=1 sk=0 mb=0 npw=1 nt=1` | 6.00 | - | 5.97 | 6.02 | 11 | 0.3 | 3339 | 2.23 MiB |  |
+| `quant_act_i8` | `quant_act_i8` | libr4d | `n=5120 group=128 dtype=bf16 M=32` | 5.98 | - | 5.95 | 5.99 | 6 | 0.3 | 3453 | 485.12 KiB |  |
+| `quant_act_i8` | `quant_act_i8` | libr4d | `n=5120 group=128 dtype=bf16 M=16` | 5.96 | - | 5.94 | 6.00 | 6 | 0.6 | 3441 | 242.56 KiB |  |
+| `sample_penalties` | `sample_penalties_f32` | libr4d | `n_vocab=248320 M=4` | 5.96 | - | 5.93 | 6.01 | 6 | 0.6 | 3327 | 3.79 MiB | restore 42% |
+| `quant_act_i8` | `quant_act_i8` | libr4d | `n=5120 group=128 dtype=bf16 M=8` | 5.95 | - | 5.93 | 5.97 | 6 | 0.3 | 3441 | 122.53 KiB |  |
+| `quant_act_i8` | `quant_act_i8` | libr4d | `n=5120 group=128 dtype=bf16 M=4` | 5.93 | - | 5.92 | 5.94 | 6 | 0.1 | 3443 | 62.52 KiB |  |
+| `quant_act_i8` | `quant_act_i8` | libr4d | `n=5120 group=128 dtype=bf16 M=2` | 5.88 | - | 5.87 | 5.88 | 6 | 0.1 | 3443 | 32.51 KiB |  |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=8 splits=0` | - | 5.85 | 5.70 | 6.00 | 20 | 1.4 | - | 160.01 KiB | 32 thread(s) |
+| `rope` | `avx_rope` | libavx | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=32` | - | 5.84 | 5.51 | 6.01 | 20 | 2.4 | - | 64.12 KiB | 32 thread(s) |
+| `sample_dry` | `sample_dry_f32` | libr4d | `n_vocab=248320 M=32` | 5.81 | - | 5.35 | 5.89 | 20 | 1.0 | 3448 | 30.33 MiB | restore 87%; restore-dominated (87% of the batch): an order of magnitude |
+| `quant_act_i8` | `quant_act_i8` | libr4d | `n=5120 group=128 dtype=bf16 M=1` | 5.80 | - | 5.79 | 5.87 | 6 | 0.6 | 3438 | 17.50 KiB |  |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=4` | - | 5.75 | 5.20 | 6.40 | 20 | 7.0 | - | 90.00 KiB | 32 thread(s) |
+| `gated_quant_fp8` | `gated_quant_fp8` | libr4d | `n=17408 group=128 dtype=bf16 act=silu M=32` | 5.74 | - | 5.73 | 5.76 | 6 | 0.3 | 3340 | 3.74 MiB |  |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=16` | - | 5.69 | 5.52 | 7.08 | 20 | 11.5 | - | 330.00 KiB | 32 thread(s) |
+| `layernorm` | `layernorm_bf16` | libr4d | `n=1152 eps=1e-06 dtype=bf16 M=128` | 5.69 | - | 5.68 | 5.72 | 6 | 0.3 | 3548 | 580.50 KiB |  |
+| `layernorm` | `layernorm_bf16` | libr4d | `n=1152 eps=1e-06 dtype=bf16 M=1` | 5.68 | - | 5.67 | 5.72 | 6 | 0.4 | 3468 | 9.00 KiB |  |
+| `layernorm` | `layernorm_bf16` | libr4d | `n=1152 eps=1e-06 dtype=bf16 M=2` | 5.66 | - | 5.65 | 5.70 | 6 | 0.4 | 3542 | 13.50 KiB |  |
+| `layernorm` | `layernorm_bf16` | libr4d | `n=1152 eps=1e-06 dtype=bf16 M=64` | 5.65 | - | 5.64 | 5.67 | 6 | 0.2 | 3550 | 292.50 KiB |  |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=6144 group=128 dtype=bf16 M=16` | - | 5.65 | 5.57 | 7.03 | 20 | 2.6 | - | 291.00 KiB | 32 thread(s) |
+| `sample_penalties` | `sample_penalties_f32` | libr4d | `n_vocab=248320 M=2` | 5.64 | - | 5.58 | 5.68 | 11 | 0.7 | 3452 | 1.90 MiB | restore 33% |
+| `layernorm` | `layernorm_bf16` | libr4d | `n=1152 eps=1e-06 dtype=bf16 M=4` | 5.64 | - | 5.63 | 5.66 | 6 | 0.3 | 3543 | 22.50 KiB |  |
+| `layernorm` | `layernorm_bf16` | libr4d | `n=1152 eps=1e-06 dtype=bf16 M=32` | 5.63 | - | 5.61 | 5.66 | 6 | 0.4 | 3540 | 148.50 KiB |  |
+| `sample_penalties` | `sample_penalties_f32` | libr4d | `n_vocab=248320 M=1` | 5.63 | - | 5.61 | 5.88 | 16 | 0.1 | 3478 | 970.34 KiB | restore 30% |
+| `layernorm` | `layernorm_bf16` | libr4d | `n=1152 eps=1e-06 dtype=bf16 M=8` | 5.62 | - | 5.62 | 5.64 | 6 | 0.2 | 3541 | 40.50 KiB |  |
+| `layernorm` | `layernorm_bf16` | libr4d | `n=1152 eps=1e-06 dtype=bf16 M=16` | 5.62 | - | 5.61 | 5.65 | 6 | 0.3 | 3541 | 76.50 KiB |  |
+| `dflash_select` | `avx_dflash_select` | libavx | `steps=7 top_k=16 rank=256 n_vocab=248320 anchor_stride=8 dtype=bf16 M=4` | - | 5.60 | 5.53 | 5.90 | 20 | 2.4 | - | 242.52 MiB | 32 thread(s) |
+| `gated_quant_fp8` | `gated_quant_fp8` | libr4d | `n=17408 group=128 dtype=bf16 act=silu M=1` | 5.60 | - | 5.46 | 7.20 | 20 | 11.4 | 2815 | 119.53 KiB |  |
+| `gated_quant_fp8` | `gated_quant_fp8` | libr4d | `n=17408 group=128 dtype=bf16 act=silu M=16` | 5.58 | - | 5.54 | 5.60 | 6 | 0.5 | 3376 | 1.87 MiB |  |
+| `sample_penalties` | `sample_penalties_f32` | libr4d | `n_vocab=248320 M=8` | 5.55 | - | 5.49 | 5.57 | 6 | 0.7 | 3446 | 7.58 MiB | restore 66% |
+| `dflash_select` | `avx_dflash_select` | libavx | `steps=7 top_k=16 rank=256 n_vocab=248320 anchor_stride=8 dtype=bf16 M=1` | - | 5.54 | 5.39 | 6.33 | 20 | 5.4 | - | 242.50 MiB | 32 thread(s) |
+| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=256` | 5.54 | - | 5.53 | 5.56 | 6 | 0.3 | 3402 | 513.00 KiB | restore 29% |
+| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=64` | 5.52 | - | 5.47 | 5.54 | 6 | 0.6 | 3429 | 512.25 KiB | restore 29% |
+| `gated_quant_fp8` | `gated_quant_fp8` | libr4d | `n=17408 group=128 dtype=bf16 act=silu M=8` | 5.51 | - | 5.50 | 5.54 | 6 | 0.4 | 3372 | 956.25 KiB |  |
+| `gated_quant_fp8` | `gated_quant_fp8` | libr4d | `n=17408 group=128 dtype=bf16 act=silu M=4` | 5.50 | - | 5.48 | 5.52 | 6 | 0.3 | 3383 | 478.12 KiB |  |
+| `gated_quant_fp8` | `gated_quant_fp8` | libr4d | `n=17408 group=128 dtype=bf16 act=silu M=2` | 5.48 | - | 5.47 | 5.49 | 6 | 0.2 | 3380 | 239.06 KiB |  |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=512` | - | 5.47 | 5.37 | 6.06 | 20 | 5.6 | - | 512.50 KiB | 32 thread(s) |
+| `attn_dense` | `attn_vit_h72_bf16` | libr4d | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=32` | 5.45 | - | 5.42 | 5.47 | 6 | 0.4 | 3560 | 18.01 KiB |  |
+| `attn_dense` | `attn_vit_h72_bf16` | libr4d | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=16` | 5.44 | - | 5.43 | 5.46 | 6 | 0.3 | 3559 | 9.01 KiB |  |
+| `attn_dense` | `attn_vit_h72_bf16` | libr4d | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=64` | 5.44 | - | 5.43 | 5.45 | 6 | 0.2 | 3562 | 36.01 KiB |  |
+| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 conv_width=4 q_len=8` | 5.44 | - | 5.36 | 5.45 | 6 | 0.8 | 3400 | 600.04 KiB | restore 30% |
+| `attn_dense` | `attn_vit_h72_bf16` | libr4d | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=4` | 5.42 | - | 5.40 | 5.43 | 6 | 0.2 | 3551 | 2.26 KiB |  |
+| `scatter_rows` | `avx_scatter_rows` | libavx | `n=5120 dtype=bf16 M=16` | - | 5.42 | 4.69 | 7.25 | 20 | 17.5 | - | 800.06 KiB | 32 thread(s) |
+| `attn_dense` | `attn_vit_h72_bf16` | libr4d | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=8` | 5.39 | - | 5.38 | 5.40 | 6 | 0.1 | 3551 | 4.51 KiB |  |
+| `attn_dense` | `attn_vit_h72_bf16` | libr4d | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=1` | 5.39 | - | 5.38 | 5.41 | 6 | 0.3 | 3500 | 584 B |  |
+| `attn_dense` | `attn_vit_h72_bf16` | libr4d | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=2` | 5.39 | - | 5.38 | 5.40 | 6 | 0.2 | 3551 | 1.13 KiB |  |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=8` | - | 5.38 | 5.28 | 6.63 | 20 | 2.5 | - | 170.00 KiB | 32 thread(s) |
+| `rmsnorm_quant_fp8` | `avx_rmsnorm_quant_fp8` | libavx | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=1` | - | 5.37 | 5.20 | 5.73 | 20 | 2.6 | - | 45.16 KiB | 32 thread(s) |
+| `rope` | `avx_rope` | libavx | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=8` | - | 5.36 | 4.66 | 6.40 | 20 | 10.8 | - | 64.03 KiB | 32 thread(s) |
+| `add` | `avx_add` | libavx | `n=5120 dtype=bf16 M=2` | - | 5.35 | 5.29 | 5.45 | 16 | 1.0 | - | 60.00 KiB | 32 thread(s) |
+| `sample_penalties` | `avx_sample_penalties` | libavx | `n_vocab=248320 M=32` | - | 5.32 | 4.96 | 6.62 | 20 | 5.2 | - | 30.32 MiB | 32 thread(s) |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=4` | - | 5.30 | 5.18 | 5.77 | 20 | 2.8 | - | 90.00 KiB | 32 thread(s) |
+| `kv_store` | `avx_kv_store` | libavx | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=32` | - | 5.29 | 4.96 | 6.21 | 20 | 4.8 | - | 256.12 KiB | 32 thread(s) |
+| `add` | `avx_add` | libavx | `n=5120 dtype=bf16 M=16` | - | 5.26 | 5.14 | 6.52 | 20 | 12.5 | - | 480.00 KiB | 32 thread(s) |
+| `attn_dense` | `attn_vit_h72_bf16` | libr4d | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=128` | 5.20 | - | 5.19 | 5.22 | 6 | 0.3 | 3559 | 72.01 KiB |  |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=6 splits=0` | - | 5.10 | 5.06 | 5.17 | 11 | 0.8 | - | 128.01 KiB | 32 thread(s) |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=512` | - | 5.08 | 4.86 | 5.21 | 20 | 2.8 | - | 256.25 KiB | 32 thread(s) |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=6144 group=128 dtype=bf16 M=2` | - | 5.06 | 4.99 | 5.35 | 20 | 3.1 | - | 36.38 KiB | 32 thread(s) |
+| `add` | `avx_add` | libavx | `n=5120 dtype=bf16 M=8` | - | 5.05 | 4.80 | 5.21 | 20 | 2.3 | - | 240.00 KiB | 32 thread(s) |
+| `rope` | `avx_rope` | libavx | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=4` | - | 5.04 | 4.95 | 5.06 | 11 | 0.8 | - | 27.03 KiB | 32 thread(s) |
+| `rope` | `avx_rope` | libavx | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=64` | - | 5.02 | 4.63 | 5.34 | 20 | 4.0 | - | 128.75 KiB | 32 thread(s) |
+| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=128` | 5.02 | - | 4.98 | 5.03 | 6 | 0.4 | 3349 | 1.50 MiB | restore 34% |
+| `sample_penalties` | `sample_penalties_f32` | libr4d | `n_vocab=248320 M=16` | 5.01 | - | 4.89 | 5.06 | 11 | 0.7 | 3458 | 15.16 MiB | restore 80%; restore-dominated (80% of the batch): an order of magnitude |
+| `cast` | `avx_cast` | libavx | `n=5120 from=bf16 to=bf16 M=64` | - | 5.01 | 4.90 | 6.29 | 20 | 4.6 | - | 1.25 MiB | 32 thread(s) |
+| `sample_dry` | `avx_sample_dry` | libavx | `n_vocab=248320 M=64` | - | 5.00 | 4.00 | 5.72 | 20 | 10.9 | - | 60.65 MiB | 32 thread(s) |
+| `rope_table` | `avx_rope_table` | libavx | `rot=64 theta=1e+07 scale=1 dtype=f32 M=64` | - | 4.93 | 4.92 | 5.12 | 16 | 0.4 | - | 16.25 KiB | 32 thread(s) |
+| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=96 K=5120 dtype=bf16 M=65 wv=1 sk=0 mb=0 npw=1 nt=1` | 4.91 | - | 4.89 | 4.93 | 11 | 0.3 | 3375 | 1.58 MiB |  |
+| `gdn_gated_rmsnorm` | `avx_gdn_gated_rmsnorm` | libavx | `channels=128 eps=1e-06 act=silu M=64` | - | 4.81 | 4.78 | 4.91 | 20 | 1.0 | - | 48.50 KiB | 32 thread(s) |
+| `sample_temp` | `avx_sample_temp` | libavx | `n_vocab=1024 M=16` | - | 4.80 | 4.63 | 5.15 | 20 | 2.6 | - | 65.50 KiB | 32 thread(s) |
+| `gdn_gated_rmsnorm` | `avx_gdn_gated_rmsnorm` | libavx | `channels=128 eps=1e-06 act=silu M=256` | - | 4.80 | 4.68 | 5.84 | 20 | 3.1 | - | 192.50 KiB | 32 thread(s) |
+| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=96 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | 4.78 | - | 4.75 | 4.80 | 11 | 0.3 | 3383 | 1.28 MiB |  |
+| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=96 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | 4.76 | - | 4.73 | 4.77 | 11 | 0.3 | 3399 | 1.11 MiB |  |
+| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=96 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | 4.74 | - | 4.73 | 4.76 | 11 | 0.3 | 3400 | 1.10 MiB |  |
+| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=96 K=5120 dtype=bf16 M=64 wv=1 sk=0 mb=0 npw=1 nt=1` | 4.72 | - | 4.71 | 4.74 | 11 | 0.3 | 3376 | 1.57 MiB |  |
+| `rope` | `avx_rope` | libavx | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=32` | - | 4.68 | 4.62 | 4.83 | 20 | 1.6 | - | 64.38 KiB | 32 thread(s) |
+| `kv_store` | `avx_kv_store` | libavx | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=8` | - | 4.67 | 4.62 | 4.73 | 14 | 1.0 | - | 128.03 KiB | 32 thread(s) |
+| `layernorm` | `avx_layernorm` | libavx | `n=1152 eps=1e-06 dtype=bf16 M=32` | - | 4.66 | 4.47 | 4.93 | 20 | 2.1 | - | 148.50 KiB | 32 thread(s) |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=1` | 4.66 | - | 4.64 | 5.10 | 20 | 1.9 | 3334 | 30.00 KiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=32` | 4.65 | - | 4.65 | 4.66 | 6 | 0.1 | 3368 | 650.00 KiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=1` | 4.65 | - | 4.63 | 4.65 | 6 | 0.2 | 3363 | 30.00 KiB |  |
+| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=96 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | 4.64 | - | 4.61 | 4.66 | 11 | 0.3 | 3402 | 1.02 MiB |  |
+| `gdn_kkt_solve` | `avx_gdn_kkt_solve` | libavx | `head_k=128 M=8 chunk=64` | - | 4.64 | 4.31 | 4.79 | 20 | 4.0 | - | 83.01 KiB | 32 thread(s) |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=32` | 4.64 | - | 4.63 | 4.67 | 6 | 0.4 | 3389 | 650.00 KiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=2` | 4.63 | - | 4.63 | 4.65 | 6 | 0.3 | 3372 | 50.00 KiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=16` | 4.63 | - | 4.62 | 4.65 | 6 | 0.3 | 3371 | 330.00 KiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=4` | 4.63 | - | 4.62 | 4.65 | 6 | 0.3 | 3369 | 90.00 KiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=8` | 4.62 | - | 4.62 | 4.64 | 6 | 0.2 | 3372 | 170.00 KiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=2` | 4.62 | - | 4.62 | 4.65 | 6 | 0.3 | 3378 | 50.00 KiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=8` | 4.62 | - | 4.61 | 4.65 | 6 | 0.5 | 3382 | 170.00 KiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=4` | 4.62 | - | 4.61 | 4.63 | 6 | 0.2 | 3384 | 90.00 KiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=16` | 4.60 | - | 4.59 | 4.61 | 6 | 0.2 | 3390 | 330.00 KiB |  |
+| `rmsnorm_quant_fp8` | `rmsnorm_quant_fp8` | libr4d | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=64` | 4.59 | - | 4.57 | 4.61 | 6 | 0.5 | 3385 | 2.21 MiB | restore 34% |
+| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=96 K=5120 dtype=bf16 M=4 wv=1 sk=0 mb=0 npw=1 nt=1` | 4.55 | - | 4.53 | 4.56 | 11 | 0.3 | 3399 | 1000.75 KiB |  |
+| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=96 K=5120 dtype=bf16 M=1 wv=1 sk=0 mb=0 npw=1 nt=1` | 4.53 | - | 4.49 | 5.19 | 20 | 3.6 | 3052 | 970.19 KiB |  |
+| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=96 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | 4.52 | - | 4.50 | 4.54 | 11 | 0.4 | 3402 | 980.38 KiB |  |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=4096 group=128 dtype=bf16 M=16` | - | 4.50 | 4.09 | 4.62 | 20 | 2.1 | - | 194.00 KiB | 32 thread(s) |
+| `quant_act_i8` | `avx_quant_act_i8` | libavx | `n=5120 group=128 dtype=bf16 M=8` | - | 4.49 | 4.24 | 4.85 | 20 | 3.2 | - | 122.53 KiB | 32 thread(s) |
+| `kv_store` | `avx_kv_store` | libavx | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=8` | - | 4.49 | 4.42 | 4.80 | 16 | 0.8 | - | 128.03 KiB | 32 thread(s) |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=5120 group=128 dtype=bf16 M=16` | - | 4.48 | 4.41 | 5.78 | 20 | 3.3 | - | 242.50 KiB | 32 thread(s) |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=6144 group=128 dtype=bf16 M=128` | 4.47 | - | 4.45 | 4.47 | 6 | 0.2 | 3420 | 2.27 MiB |  |
+| `sample_penalties` | `avx_sample_penalties` | libavx | `n_vocab=248320 M=8` | - | 4.46 | 4.23 | 5.10 | 20 | 4.5 | - | 7.58 MiB | 32 thread(s) |
+| `rope` | `avx_rope` | libavx | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=16` | - | 4.42 | 4.18 | 4.67 | 20 | 2.7 | - | 32.06 KiB | 32 thread(s) |
+| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 conv_width=4 q_len=4` | 4.42 | - | 4.41 | 4.43 | 6 | 0.2 | 3392 | 360.03 KiB | restore 34% |
+| `add` | `avx_add` | libavx | `n=5120 dtype=bf16 M=4` | - | 4.40 | 4.25 | 4.55 | 20 | 1.3 | - | 120.00 KiB | 32 thread(s) |
+| `layernorm` | `avx_layernorm` | libavx | `n=1152 eps=1e-06 dtype=bf16 M=16` | - | 4.40 | 4.21 | 4.73 | 20 | 2.7 | - | 76.50 KiB | 32 thread(s) |
+| `silu_mul` | `silu_mul_bf16` | libr4d | `n=17408 dtype=bf16 M=32` | 4.40 | - | 4.38 | 4.41 | 6 | 0.3 | 3414 | 3.19 MiB |  |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=6144 group=128 dtype=bf16 M=4` | - | 4.29 | 4.17 | 4.39 | 20 | 1.1 | - | 72.75 KiB | 32 thread(s) |
+| `cast` | `avx_cast` | libavx | `n=5120 from=bf16 to=bf16 M=32` | - | 4.25 | 4.17 | 5.63 | 20 | 10.3 | - | 640.00 KiB | 32 thread(s) |
+| `embed_lookup` | `avx_embed_lookup` | libavx | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=128` | - | 4.25 | 4.18 | 4.89 | 20 | 2.1 | - | 2.37 GiB | 32 thread(s) |
+| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=512` | 4.22 | - | 4.21 | 4.23 | 6 | 0.2 | 3388 | 1.01 MiB | restore 36% |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=6144 group=128 dtype=bf16 M=64` | 4.22 | - | 4.21 | 4.22 | 6 | 0.2 | 3436 | 1.14 MiB |  |
+| `quant_act_i8` | `avx_quant_act_i8` | libavx | `n=5120 group=128 dtype=bf16 M=4` | - | 4.17 | 3.98 | 4.38 | 20 | 2.8 | - | 62.52 KiB | 32 thread(s) |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=5120 group=128 dtype=bf16 M=128` | 4.15 | - | 4.14 | 4.16 | 6 | 0.2 | 3357 | 1.89 MiB |  |
+| `sample_mask` | `sample_mask_f32` | libr4d | `n_vocab=248320 M=4` | 4.13 | - | 4.12 | 4.15 | 6 | 0.4 | 3274 | 3.91 MiB | restore 52% |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=6144 group=128 dtype=bf16 M=8` | - | 4.11 | 4.03 | 4.21 | 20 | 1.1 | - | 145.50 KiB | 32 thread(s) |
+| `rope` | `avx_rope` | libavx | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=8` | - | 4.11 | 4.08 | 4.22 | 19 | 0.9 | - | 16.03 KiB | 32 thread(s) |
+| `rope` | `avx_rope` | libavx | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=4` | - | 4.11 | 3.94 | 4.70 | 20 | 4.4 | - | 32.02 KiB | 32 thread(s) |
+| `kv_store` | `avx_kv_store` | libavx | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=16` | - | 4.09 | 3.70 | 4.64 | 20 | 5.5 | - | 160.06 KiB | 32 thread(s) |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=6144 group=128 dtype=bf16 M=32` | 4.09 | - | 4.08 | 4.11 | 6 | 0.4 | 3431 | 582.00 KiB |  |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=6144 group=128 dtype=bf16 M=16` | 4.09 | - | 4.08 | 4.09 | 6 | 0.1 | 3432 | 291.00 KiB |  |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=6 splits=0` | - | 4.09 | 3.90 | 4.25 | 20 | 1.7 | - | 176.01 KiB | 32 thread(s) |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=6144 group=128 dtype=bf16 M=8` | 4.08 | - | 4.07 | 4.09 | 6 | 0.3 | 3434 | 145.50 KiB |  |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=6144 group=128 dtype=bf16 M=4` | 4.07 | - | 4.06 | 4.08 | 6 | 0.3 | 3432 | 72.75 KiB |  |
+| `sample_penalties` | `avx_sample_penalties` | libavx | `n_vocab=248320 M=16` | - | 4.06 | 3.69 | 4.35 | 20 | 3.8 | - | 15.16 MiB | 32 thread(s) |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=6144 group=128 dtype=bf16 M=1` | 4.06 | - | 4.05 | 4.08 | 6 | 0.4 | 3430 | 18.19 KiB |  |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=6144 group=128 dtype=bf16 M=2` | 4.06 | - | 4.06 | 4.09 | 6 | 0.4 | 3432 | 36.38 KiB |  |
+| `sample_penalties` | `sample_penalties_f32` | libr4d | `n_vocab=248320 M=32` | 3.99 | - | 3.59 | 4.05 | 16 | 1.0 | 3448 | 30.32 MiB | restore 91%; restore-dominated (91% of the batch): an order of magnitude |
+| `add` | `add_bf16` | libr4d | `n=5120 dtype=bf16 M=128` | 3.98 | - | 3.98 | 4.00 | 6 | 0.3 | 3372 | 3.75 MiB |  |
+| `rope` | `rope_bf16` | libr4d | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=32` | 3.97 | - | 3.96 | 3.99 | 6 | 0.4 | 3549 | 216.25 KiB | restore 36% |
+| `sample_minp` | `sample_minp_f32` | libr4d | `n_cand=1024 M=64` | 3.97 | - | 3.94 | 3.98 | 6 | 0.6 | 3581 | 518.00 KiB | restore 52% |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=5120 group=128 dtype=bf16 M=8` | - | 3.94 | 3.88 | 4.03 | 16 | 1.0 | - | 121.25 KiB | 32 thread(s) |
+| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 conv_width=4 q_len=2` | 3.94 | - | 3.92 | 4.00 | 6 | 1.0 | 3390 | 240.02 KiB | restore 36% |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=5120 group=128 dtype=bf16 M=64` | 3.92 | - | 3.91 | 3.93 | 6 | 0.2 | 3365 | 970.00 KiB |  |
+| `sample_minp` | `sample_minp_f32` | libr4d | `n_cand=1024 M=16` | 3.91 | - | 3.90 | 3.92 | 6 | 0.3 | 3576 | 129.50 KiB | restore 52% |
+| `rope` | `avx_rope` | libavx | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=8` | - | 3.91 | 3.87 | 3.93 | 11 | 0.6 | - | 96.09 KiB | 32 thread(s) |
+| `sample_minp` | `sample_minp_f32` | libr4d | `n_cand=1024 M=32` | 3.91 | - | 3.87 | 3.91 | 6 | 0.5 | 3582 | 259.00 KiB | restore 52% |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=5120 group=128 dtype=bf16 M=4` | - | 3.89 | 3.88 | 4.44 | 20 | 2.1 | - | 60.62 KiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=5 splits=0` | - | 3.89 | 3.89 | 4.04 | 14 | 1.0 | - | 112.01 KiB | 32 thread(s) |
+| `sample_minp` | `sample_minp_f32` | libr4d | `n_cand=1024 M=8` | 3.89 | - | 3.87 | 3.90 | 6 | 0.4 | 3574 | 64.75 KiB | restore 52% |
+| `sample_minp` | `sample_minp_f32` | libr4d | `n_cand=1024 M=2` | 3.87 | - | 3.86 | 3.87 | 6 | 0.2 | 3572 | 16.19 KiB | restore 52% |
+| `sample_minp` | `sample_minp_f32` | libr4d | `n_cand=1024 M=4` | 3.87 | - | 3.85 | 3.88 | 6 | 0.4 | 3572 | 32.38 KiB | restore 52% |
+| `sample_minp` | `sample_minp_f32` | libr4d | `n_cand=1024 M=1` | 3.84 | - | 3.83 | 3.85 | 6 | 0.2 | 3572 | 8.09 KiB | restore 52% |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=4 splits=0` | - | 3.81 | 3.68 | 3.89 | 20 | 1.8 | - | 96.01 KiB | 32 thread(s) |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=5120 group=128 dtype=bf16 M=32` | 3.81 | - | 3.81 | 3.83 | 6 | 0.2 | 3370 | 485.00 KiB |  |
+| `sample_dry` | `avx_sample_dry` | libavx | `n_vocab=248320 M=32` | - | 3.80 | 3.41 | 4.34 | 20 | 8.9 | - | 30.33 MiB | 32 thread(s) |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=5120 group=128 dtype=bf16 M=16` | 3.80 | - | 3.80 | 3.81 | 6 | 0.2 | 3371 | 242.50 KiB |  |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=5120 group=128 dtype=bf16 M=8` | 3.80 | - | 3.79 | 3.80 | 6 | 0.1 | 3371 | 121.25 KiB |  |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=5120 group=128 dtype=bf16 M=2` | 3.79 | - | 3.77 | 3.79 | 6 | 0.3 | 3370 | 30.31 KiB |  |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=5120 group=128 dtype=bf16 M=4` | 3.78 | - | 3.77 | 3.80 | 6 | 0.4 | 3373 | 60.62 KiB |  |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=5120 group=128 dtype=bf16 M=1` | 3.78 | - | 3.77 | 3.82 | 6 | 0.7 | 3371 | 15.16 KiB |  |
+| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=64` | 3.77 | - | 3.76 | 3.79 | 6 | 0.4 | 3361 | 768.75 KiB | restore 39% |
+| `rmsnorm_quant_fp8` | `rmsnorm_quant_fp8` | libr4d | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=32` | 3.77 | - | 3.73 | 3.78 | 6 | 0.6 | 3394 | 1.11 MiB | restore 37% |
+| `sample_dry` | `avx_sample_dry` | libavx | `n_vocab=248320 M=2` | - | 3.76 | 2.81 | 4.18 | 20 | 14.2 | - | 1.90 MiB | 32 thread(s) |
+| `gdn_gated_rmsnorm` | `avx_gdn_gated_rmsnorm` | libavx | `channels=128 eps=1e-06 act=silu M=128` | - | 3.73 | 3.58 | 4.14 | 20 | 5.8 | - | 96.50 KiB | 32 thread(s) |
+| `rmsnorm_quant_fp8` | `rmsnorm_quant_fp8` | libr4d | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=16` | 3.73 | - | 3.72 | 3.75 | 6 | 0.4 | 3401 | 572.50 KiB | restore 37% |
+| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 conv_width=4 q_len=1` | 3.71 | - | 3.68 | 3.72 | 6 | 0.5 | 3391 | 180.02 KiB | restore 38% |
+| `rmsnorm_quant_fp8` | `rmsnorm_quant_fp8` | libr4d | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=8` | 3.71 | - | 3.69 | 3.71 | 6 | 0.4 | 3402 | 291.25 KiB | restore 37% |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=4 splits=0` | - | 3.71 | 3.58 | 3.83 | 20 | 1.9 | - | 128.01 KiB | 32 thread(s) |
+| `rmsnorm_quant_fp8` | `rmsnorm_quant_fp8` | libr4d | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=2` | 3.71 | - | 3.68 | 3.72 | 6 | 0.5 | 3393 | 80.31 KiB | restore 38% |
+| `rmsnorm_quant_fp8` | `rmsnorm_quant_fp8` | libr4d | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=4` | 3.70 | - | 3.68 | 3.71 | 6 | 0.4 | 3401 | 150.62 KiB | restore 38% |
+| `rmsnorm_quant_fp8` | `rmsnorm_quant_fp8` | libr4d | `n=5120 eps=1e-06 group=128 dtype=bf16 wadd=1 M=1` | 3.70 | - | 3.68 | 3.71 | 6 | 0.4 | 3392 | 45.16 KiB | restore 38% |
+| `sample_penalties` | `avx_sample_penalties` | libavx | `n_vocab=248320 M=2` | - | 3.69 | 3.39 | 4.03 | 20 | 5.2 | - | 1.90 MiB | 32 thread(s) |
+| `kv_store` | `kv_store_fp8` | libr4d | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=512` | 3.63 | - | 3.63 | 3.65 | 6 | 0.3 | 3384 | 3.06 MiB | restore 40% |
+| `kv_store` | `kv_store_fp8` | libr4d | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=512` | 3.61 | - | 3.59 | 3.62 | 6 | 0.5 | 3419 | 3.06 MiB | restore 40% |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=5120 group=128 dtype=bf16 M=2` | - | 3.60 | 3.59 | 3.70 | 16 | 0.2 | - | 30.31 KiB | 32 thread(s) |
+| `add` | `add_bf16` | libr4d | `n=5120 dtype=bf16 M=64` | 3.60 | - | 3.59 | 3.60 | 6 | 0.1 | 3384 | 1.88 MiB |  |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=4096 group=128 dtype=bf16 M=2` | - | 3.51 | 3.37 | 3.63 | 20 | 2.5 | - | 24.25 KiB | 32 thread(s) |
+| `sample_temp` | `sample_temp_f32` | libr4d | `n_vocab=248320 M=4` | 3.49 | - | 3.41 | 3.55 | 19 | 1.0 | 3346 | 3.79 MiB | restore 55% |
+| `add` | `add_bf16` | libr4d | `n=5120 dtype=bf16 M=32` | 3.49 | - | 3.49 | 3.51 | 6 | 0.3 | 3388 | 960.00 KiB |  |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=4096 group=128 dtype=bf16 M=64` | 3.49 | - | 3.49 | 3.49 | 6 | 0.1 | 3452 | 776.00 KiB |  |
+| `grid_embed` | `grid_embed_bf16` | libr4d | `n=1152 side=48 dtype=bf16 M=128` | 3.47 | - | 3.43 | 3.66 | 16 | 0.8 | 3499 | 5.35 MiB | restore 38% |
+| `add` | `add_bf16` | libr4d | `n=5120 dtype=bf16 M=16` | 3.47 | - | 3.47 | 3.48 | 6 | 0.2 | 3390 | 480.00 KiB |  |
+| `add` | `add_bf16` | libr4d | `n=5120 dtype=bf16 M=8` | 3.46 | - | 3.45 | 3.46 | 6 | 0.2 | 3390 | 240.00 KiB |  |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=256` | - | 3.45 | 3.38 | 4.21 | 20 | 6.5 | - | 256.50 KiB | 32 thread(s) |
+| `add` | `add_bf16` | libr4d | `n=5120 dtype=bf16 M=4` | 3.45 | - | 3.44 | 3.45 | 6 | 0.1 | 3392 | 120.00 KiB |  |
+| `add` | `add_bf16` | libr4d | `n=5120 dtype=bf16 M=2` | 3.44 | - | 3.43 | 3.45 | 6 | 0.2 | 3392 | 60.00 KiB |  |
+| `add` | `add_bf16` | libr4d | `n=5120 dtype=bf16 M=1` | 3.43 | - | 3.42 | 3.44 | 6 | 0.2 | 3384 | 30.00 KiB |  |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=4096 group=128 dtype=bf16 M=8` | - | 3.42 | 3.35 | 3.44 | 11 | 0.8 | - | 97.00 KiB | 32 thread(s) |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=4096 group=128 dtype=bf16 M=32` | 3.41 | - | 3.39 | 3.41 | 6 | 0.2 | 3456 | 388.00 KiB |  |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=4096 group=128 dtype=bf16 M=16` | 3.40 | - | 3.39 | 3.41 | 6 | 0.2 | 3456 | 194.00 KiB |  |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=4096 group=128 dtype=bf16 M=8` | 3.39 | - | 3.38 | 3.41 | 6 | 0.4 | 3452 | 97.00 KiB |  |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=4096 group=128 dtype=bf16 M=2` | 3.39 | - | 3.39 | 3.41 | 6 | 0.3 | 3444 | 24.25 KiB |  |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=4096 group=128 dtype=bf16 M=4` | 3.39 | - | 3.38 | 3.40 | 6 | 0.2 | 3452 | 48.50 KiB |  |
+| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=4096 group=128 dtype=bf16 M=1` | 3.38 | - | 3.38 | 3.40 | 6 | 0.4 | 3430 | 12.12 KiB |  |
+| `silu_mul` | `silu_mul_bf16` | libr4d | `n=17408 dtype=bf16 M=16` | 3.35 | - | 3.35 | 3.37 | 6 | 0.3 | 3426 | 1.59 MiB |  |
+| `sample_penalties` | `avx_sample_penalties` | libavx | `n_vocab=248320 M=4` | - | 3.31 | 2.96 | 3.66 | 20 | 6.4 | - | 3.79 MiB | 32 thread(s) |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=512` | 3.29 | - | 3.28 | 3.30 | 6 | 0.3 | 3402 | 256.25 KiB |  |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=5 splits=0` | - | 3.28 | 3.22 | 3.40 | 20 | 1.7 | - | 152.01 KiB | 32 thread(s) |
+| `rope` | `rope_bf16` | libr4d | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=16` | 3.27 | - | 3.27 | 3.27 | 6 | 0.1 | 3553 | 108.12 KiB | restore 40% |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=4096 group=128 dtype=bf16 M=4` | - | 3.24 | 3.12 | 3.31 | 20 | 1.6 | - | 48.50 KiB | 32 thread(s) |
+| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=64` | 3.20 | - | 3.19 | 3.20 | 6 | 0.2 | 3414 | 128.25 KiB | restore 41% |
+| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=16` | 3.19 | - | 3.17 | 3.19 | 6 | 0.3 | 3447 | 128.06 KiB | restore 40% |
+| `kv_store` | `avx_kv_store` | libavx | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=16` | - | 3.19 | 2.84 | 3.45 | 20 | 7.1 | - | 160.06 KiB | 32 thread(s) |
+| `scatter_rows` | `scatter_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=128` | 3.17 | - | 3.13 | 3.19 | 6 | 0.9 | 3359 | 6.25 MiB | restore 73% |
+| `cast` | `avx_cast` | libavx | `n=5120 from=bf16 to=bf16 M=16` | - | 3.14 | 3.07 | 4.03 | 20 | 13.7 | - | 320.00 KiB | 32 thread(s) |
+| `cast` | `cast_bf16_bf16` | libr4d | `n=5120 from=bf16 to=bf16 M=256` | 3.14 | - | 3.13 | 3.15 | 6 | 0.3 | 3354 | 5.00 MiB |  |
+| `scatter_rows` | `scatter_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=64` | 3.11 | - | 3.09 | 3.13 | 6 | 0.6 | 3350 | 3.13 MiB | restore 48% |
+| `grid_embed` | `grid_embed_bf16` | libr4d | `n=1152 side=48 dtype=bf16 M=64` | 3.10 | - | 3.10 | 3.12 | 6 | 0.4 | 3526 | 5.20 MiB | restore 41% |
+| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=32` | 3.10 | - | 3.09 | 3.10 | 6 | 0.2 | 3368 | 384.38 KiB | restore 42% |
+| `scatter_rows` | `avx_scatter_rows` | libavx | `n=5120 dtype=bf16 M=4` | - | 3.09 | 2.60 | 3.66 | 20 | 13.1 | - | 200.02 KiB | 32 thread(s) |
+| `scatter_rows` | `scatter_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=32` | 3.09 | - | 3.06 | 3.10 | 6 | 0.7 | 3374 | 1.56 MiB | restore 45% |
+| `scatter_rows` | `scatter_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=8` | 3.08 | - | 3.07 | 3.09 | 6 | 0.2 | 3374 | 400.03 KiB | restore 42% |
+| `scatter_rows` | `scatter_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=4` | 3.08 | - | 3.07 | 3.09 | 6 | 0.3 | 3373 | 200.02 KiB | restore 42% |
+| `scatter_rows` | `scatter_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=16` | 3.08 | - | 3.07 | 3.08 | 6 | 0.2 | 3373 | 800.06 KiB | restore 43% |
+| `gdn_kkt_solve` | `avx_gdn_kkt_solve` | libavx | `head_k=128 M=4 chunk=64` | - | 3.08 | 2.68 | 3.12 | 20 | 1.3 | - | 41.51 KiB | 32 thread(s) |
+| `scatter_rows` | `scatter_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=2` | 3.07 | - | 3.05 | 3.08 | 6 | 0.5 | 3370 | 100.01 KiB | restore 42% |
+| `scatter_rows` | `scatter_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=1` | 3.05 | - | 3.03 | 3.05 | 6 | 0.4 | 3364 | 50.00 KiB | restore 43% |
+| `grid_embed` | `grid_embed_bf16` | libr4d | `n=1152 side=48 dtype=bf16 M=32` | 3.04 | - | 3.02 | 3.07 | 6 | 0.7 | 3523 | 5.13 MiB | restore 42% |
+| `embed_lookup` | `embed_lookup_bf16` | libr4d | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=128` | 3.02 | - | 3.01 | 3.04 | 6 | 0.4 | 3353 | 2.37 GiB |  |
+| `rope` | `rope_bf16` | libr4d | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=8` | 3.00 | - | 2.99 | 3.01 | 6 | 0.3 | 3559 | 54.06 KiB | restore 42% |
+| `sample_dry` | `avx_sample_dry` | libavx | `n_vocab=248320 M=4` | - | 2.96 | 2.74 | 3.17 | 20 | 3.9 | - | 3.79 MiB | 32 thread(s) |
+| `grid_embed` | `grid_embed_bf16` | libr4d | `n=1152 side=48 dtype=bf16 M=16` | 2.93 | - | 2.92 | 2.96 | 6 | 0.7 | 3523 | 5.10 MiB | restore 43% |
+| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=128` | 2.93 | - | 2.92 | 2.94 | 6 | 0.4 | 3388 | 257.50 KiB | restore 43% |
+| `rope` | `rope_bf16` | libr4d | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=4` | 2.91 | - | 2.88 | 2.91 | 6 | 0.5 | 3560 | 27.03 KiB | restore 43% |
+| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=16` | 2.90 | - | 2.88 | 2.90 | 6 | 0.4 | 3370 | 192.19 KiB | restore 44% |
+| `rope` | `rope_bf16` | libr4d | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=2` | 2.89 | - | 2.88 | 2.90 | 6 | 0.4 | 3562 | 13.52 KiB | restore 43% |
+| `cast` | `avx_cast` | libavx | `n=5120 from=bf16 to=bf16 M=4` | - | 2.89 | 2.85 | 2.99 | 16 | 0.8 | - | 80.00 KiB | 32 thread(s) |
+| `rope` | `rope_bf16` | libr4d | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=1` | 2.89 | - | 2.88 | 2.90 | 6 | 0.3 | 3376 | 6.76 KiB | restore 42% |
+| `grid_embed` | `grid_embed_bf16` | libr4d | `n=1152 side=48 dtype=bf16 M=8` | 2.87 | - | 2.86 | 2.89 | 6 | 0.6 | 3522 | 5.08 MiB | restore 43% |
+| `grid_embed` | `grid_embed_bf16` | libr4d | `n=1152 side=48 dtype=bf16 M=4` | 2.87 | - | 2.85 | 2.90 | 6 | 0.9 | 3523 | 5.07 MiB | restore 43% |
+| `grid_embed` | `grid_embed_bf16` | libr4d | `n=1152 side=48 dtype=bf16 M=2` | 2.87 | - | 2.86 | 2.91 | 6 | 0.9 | 3517 | 5.07 MiB | restore 42% |
+| `grid_embed` | `grid_embed_bf16` | libr4d | `n=1152 side=48 dtype=bf16 M=1` | 2.86 | - | 2.84 | 2.87 | 11 | 0.3 | 3517 | 5.06 MiB | restore 41% |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=6144 group=128 dtype=bf16 M=1` | - | 2.86 | 2.74 | 3.06 | 20 | 4.6 | - | 18.19 KiB | 32 thread(s) |
+| `gather_rows` | `avx_gather_rows` | libavx | `n=5120 dtype=bf16 M=64` | - | 2.85 | 2.72 | 3.17 | 20 | 2.8 | - | 3.13 MiB | 32 thread(s) |
+| `add` | `avx_add` | libavx | `n=5120 dtype=bf16 M=1` | - | 2.83 | 2.81 | 2.91 | 20 | 1.5 | - | 30.00 KiB | 32 thread(s) |
+| `silu_mul` | `silu_mul_bf16` | libr4d | `n=17408 dtype=bf16 M=8` | 2.83 | - | 2.82 | 2.84 | 6 | 0.3 | 3438 | 816.00 KiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=32` | 2.82 | - | 2.80 | 2.83 | 6 | 0.5 | 3373 | 32.50 KiB |  |
+| `embed_lookup` | `embed_lookup_bf16` | libr4d | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=64` | 2.81 | - | 2.81 | 2.82 | 6 | 0.2 | 3369 | 2.37 GiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=16` | 2.81 | - | 2.79 | 2.82 | 6 | 0.5 | 3367 | 16.50 KiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=8` | 2.80 | - | 2.78 | 2.81 | 6 | 0.5 | 3371 | 8.50 KiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=1` | 2.80 | - | 2.79 | 2.92 | 16 | 0.4 | 3357 | 1.50 KiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=2` | 2.80 | - | 2.79 | 2.81 | 6 | 0.3 | 3370 | 2.50 KiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=4` | 2.80 | - | 2.78 | 2.80 | 6 | 0.4 | 3372 | 4.50 KiB |  |
+| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=32` | 2.79 | - | 2.78 | 2.80 | 6 | 0.3 | 3416 | 64.12 KiB | restore 44% |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=2` | - | 2.79 | 2.78 | 2.85 | 16 | 0.9 | - | 50.00 KiB | 32 thread(s) |
+| `rope` | `avx_rope` | libavx | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=2` | - | 2.79 | 2.76 | 2.91 | 16 | 0.5 | - | 13.52 KiB | 32 thread(s) |
+| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=8` | 2.78 | - | 2.77 | 2.78 | 6 | 0.3 | 3459 | 64.03 KiB | restore 43% |
+| `gather_rows` | `gather_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=64` | 2.78 | - | 2.77 | 2.79 | 6 | 0.3 | 3396 | 3.13 MiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=32` | 2.78 | - | 2.77 | 2.79 | 6 | 0.3 | 3404 | 16.25 KiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=64` | 2.77 | - | 2.77 | 2.79 | 6 | 0.3 | 3368 | 64.50 KiB |  |
+| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=64` | 2.77 | - | 2.77 | 2.79 | 6 | 0.3 | 3392 | 128.75 KiB | restore 44% |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=128` | 2.77 | - | 2.75 | 2.77 | 6 | 0.4 | 3366 | 128.50 KiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=4` | 2.77 | - | 2.76 | 2.78 | 6 | 0.3 | 3392 | 2.25 KiB |  |
+| `embed_lookup` | `embed_lookup_bf16` | libr4d | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=32` | 2.77 | - | 2.76 | 2.78 | 6 | 0.2 | 3372 | 2.37 GiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=16` | 2.77 | - | 2.76 | 2.78 | 6 | 0.4 | 3402 | 8.25 KiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=8` | 2.76 | - | 2.76 | 2.77 | 6 | 0.2 | 3396 | 4.25 KiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=2` | 2.76 | - | 2.76 | 2.78 | 6 | 0.4 | 3392 | 1.25 KiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=1` | 2.76 | - | 2.75 | 2.78 | 6 | 0.5 | 3400 | 768 B |  |
+| `gather_rows` | `gather_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=56` | 2.75 | - | 2.75 | 2.76 | 6 | 0.2 | 3424 | 2.73 MiB |  |
+| `embed_lookup` | `embed_lookup_bf16` | libr4d | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=16` | 2.75 | - | 2.75 | 2.76 | 6 | 0.2 | 3370 | 2.37 GiB |  |
+| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=8` | 2.75 | - | 2.74 | 2.78 | 6 | 0.8 | 3373 | 96.09 KiB | restore 45% |
+| `embed_lookup` | `embed_lookup_bf16` | libr4d | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=8` | 2.74 | - | 2.74 | 2.75 | 6 | 0.3 | 3372 | 2.37 GiB |  |
+| `embed_lookup` | `embed_lookup_bf16` | libr4d | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=4` | 2.74 | - | 2.74 | 2.75 | 6 | 0.3 | 3372 | 2.37 GiB |  |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=256` | - | 2.74 | 2.63 | 3.15 | 20 | 2.5 | - | 128.25 KiB | 32 thread(s) |
+| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=16` | 2.74 | - | 2.73 | 2.74 | 6 | 0.2 | 3392 | 32.19 KiB | restore 44% |
+| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=32` | 2.74 | - | 2.70 | 2.74 | 6 | 0.7 | 3394 | 64.38 KiB | restore 44% |
+| `gather_rows` | `gather_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=32` | 2.73 | - | 2.73 | 2.74 | 6 | 0.2 | 3404 | 1.56 MiB |  |
+| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=4` | 2.73 | - | 2.72 | 2.74 | 6 | 0.3 | 3372 | 48.05 KiB | restore 45% |
+| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=2` | 2.73 | - | 2.70 | 2.73 | 6 | 0.6 | 3372 | 24.02 KiB | restore 46% |
+| `embed_lookup` | `avx_embed_lookup` | libavx | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=64` | - | 2.73 | 2.61 | 2.86 | 20 | 3.3 | - | 2.37 GiB | 32 thread(s) |
+| `embed_lookup` | `embed_lookup_bf16` | libr4d | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=2` | 2.73 | - | 2.72 | 2.75 | 6 | 0.5 | 3370 | 2.37 GiB |  |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=64` | 2.73 | - | 2.72 | 2.75 | 6 | 0.4 | 3403 | 32.25 KiB |  |
+| `rope` | `avx_rope` | libavx | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=16` | - | 2.73 | 2.69 | 2.82 | 14 | 0.9 | - | 32.19 KiB | 32 thread(s) |
+| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=1` | 2.72 | - | 2.71 | 2.75 | 6 | 0.7 | 3366 | 12.01 KiB | restore 46% |
+| `embed_lookup` | `embed_lookup_bf16` | libr4d | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=1` | 2.72 | - | 2.71 | 2.73 | 6 | 0.3 | 3356 | 2.37 GiB |  |
+| `rope_table` | `avx_rope_table` | libavx | `rot=64 theta=1e+07 scale=1 dtype=f32 M=32` | - | 2.72 | 2.69 | 2.79 | 14 | 0.7 | - | 8.12 KiB | 32 thread(s) |
+| `gather_rows` | `gather_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=16` | 2.72 | - | 2.71 | 2.73 | 6 | 0.3 | 3404 | 800.06 KiB |  |
+| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=8` | 2.72 | - | 2.68 | 2.73 | 6 | 0.9 | 3379 | 16.09 KiB | restore 45% |
+| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=2` | 2.72 | - | 2.69 | 2.72 | 6 | 0.6 | 3380 | 4.02 KiB | restore 44% |
+| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=4` | 2.71 | - | 2.71 | 2.72 | 6 | 0.3 | 3379 | 8.05 KiB | restore 45% |
+| `gather_rows` | `gather_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=8` | 2.71 | - | 2.70 | 2.72 | 6 | 0.2 | 3405 | 400.03 KiB |  |
+| `sample_dry` | `avx_sample_dry` | libavx | `n_vocab=248320 M=16` | - | 2.71 | 2.40 | 2.93 | 20 | 6.1 | - | 15.16 MiB | 32 thread(s) |
+| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=128` | 2.70 | - | 2.70 | 2.71 | 6 | 0.3 | 3400 | 64.25 KiB |  |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=128` | - | 2.70 | 2.61 | 3.07 | 20 | 4.0 | - | 128.50 KiB | 32 thread(s) |
+| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=1` | 2.70 | - | 2.68 | 2.71 | 6 | 0.6 | 3367 | 2.01 KiB | restore 44% |
+| `gather_rows` | `gather_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=4` | 2.70 | - | 2.69 | 2.71 | 6 | 0.3 | 3404 | 200.02 KiB |  |
+| `gather_rows` | `gather_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=2` | 2.70 | - | 2.69 | 2.71 | 6 | 0.3 | 3403 | 100.01 KiB |  |
+| `gather_rows` | `gather_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=1` | 2.69 | - | 2.69 | 2.73 | 6 | 0.7 | 3397 | 50.00 KiB |  |
+| `kv_store` | `kv_store_fp8` | libr4d | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=128` | 2.67 | - | 2.65 | 2.68 | 6 | 0.5 | 3401 | 832.50 KiB | restore 46% |
+| `kv_store` | `kv_store_fp8` | libr4d | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=128` | 2.66 | - | 2.65 | 2.67 | 6 | 0.2 | 3440 | 832.50 KiB | restore 45% |
+| `cast` | `avx_cast` | libavx | `n=5120 from=bf16 to=bf16 M=8` | - | 2.66 | 2.60 | 3.95 | 19 | 0.9 | - | 160.00 KiB | 32 thread(s) |
+| `cast` | `cast_bf16_bf16` | libr4d | `n=5120 from=bf16 to=bf16 M=128` | 2.65 | - | 2.65 | 2.66 | 6 | 0.2 | 3364 | 2.50 MiB |  |
+| `scatter_rows` | `avx_scatter_rows` | libavx | `n=5120 dtype=bf16 M=8` | - | 2.65 | 2.23 | 3.20 | 20 | 5.7 | - | 400.03 KiB | 32 thread(s) |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=2` | - | 2.62 | 2.60 | 2.67 | 19 | 0.8 | - | 50.00 KiB | 32 thread(s) |
+| `gdn_gated_rmsnorm` | `avx_gdn_gated_rmsnorm` | libavx | `channels=128 eps=1e-06 act=silu M=32` | - | 2.61 | 2.59 | 2.66 | 16 | 0.9 | - | 24.50 KiB | 32 thread(s) |
+| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=16` | 2.60 | - | 2.60 | 2.61 | 6 | 0.2 | 3414 | 32.06 KiB | restore 45% |
+| `silu_mul` | `silu_mul_bf16` | libr4d | `n=17408 dtype=bf16 M=4` | 2.60 | - | 2.60 | 2.61 | 6 | 0.3 | 3452 | 408.00 KiB |  |
+| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=4` | 2.60 | - | 2.59 | 2.61 | 6 | 0.3 | 3464 | 32.02 KiB | restore 45% |
+| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=1` | 2.60 | - | 2.59 | 2.61 | 6 | 0.4 | 3408 | 2.00 KiB | restore 45% |
+| `kv_store` | `avx_kv_store` | libavx | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=4` | - | 2.59 | 2.53 | 2.71 | 20 | 1.7 | - | 112.02 KiB | 32 thread(s) |
+| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=2` | 2.59 | - | 2.59 | 2.61 | 6 | 0.4 | 3418 | 4.01 KiB | restore 44% |
+| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=4` | 2.59 | - | 2.58 | 2.61 | 6 | 0.5 | 3416 | 8.02 KiB | restore 46% |
+| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=8` | 2.59 | - | 2.59 | 2.60 | 6 | 0.2 | 3416 | 16.03 KiB | restore 46% |
+| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=1` | 2.59 | - | 2.54 | 2.59 | 11 | 0.4 | 3462 | 8.00 KiB | restore 45% |
+| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=2` | 2.58 | - | 2.58 | 2.59 | 6 | 0.2 | 3463 | 16.01 KiB | restore 45% |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=2 splits=0` | - | 2.57 | 2.52 | 2.68 | 20 | 1.4 | - | 80.01 KiB | 32 thread(s) |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=1 splits=0` | - | 2.56 | 2.52 | 2.78 | 20 | 1.4 | - | 56.01 KiB | 32 thread(s) |
+| `quant_act_i8` | `avx_quant_act_i8` | libavx | `n=5120 group=128 dtype=bf16 M=2` | - | 2.55 | 2.54 | 2.61 | 14 | 0.3 | - | 32.51 KiB | 32 thread(s) |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=64` | - | 2.53 | 2.52 | 2.58 | 16 | 1.0 | - | 32.25 KiB | 32 thread(s) |
+| `sample_dry` | `avx_sample_dry` | libavx | `n_vocab=248320 M=8` | - | 2.53 | 2.22 | 3.03 | 20 | 9.1 | - | 7.58 MiB | 32 thread(s) |
+| `rope_table` | `rope_table_f32` | libr4d | `rot=64 theta=1e+07 scale=1 dtype=f32 M=64` | 2.52 | - | 2.51 | 2.53 | 6 | 0.4 | 3394 | 16.25 KiB |  |
+| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | `channels=128 eps=1e-06 act=silu M=512` | 2.51 | - | 2.50 | 2.53 | 6 | 0.5 | 3388 | 384.50 KiB |  |
+| `rope_table` | `rope_table_f32` | libr4d | `rot=64 theta=1e+07 scale=1 dtype=f32 M=32` | 2.51 | - | 2.50 | 2.52 | 6 | 0.3 | 3393 | 8.12 KiB |  |
+| `rope_table` | `rope_table_f32` | libr4d | `rot=64 theta=1e+07 scale=1 dtype=f32 M=16` | 2.51 | - | 2.50 | 2.51 | 6 | 0.3 | 3392 | 4.06 KiB |  |
+| `rope_table` | `rope_table_f32` | libr4d | `rot=64 theta=1e+07 scale=1 dtype=f32 M=8` | 2.50 | - | 2.50 | 2.50 | 6 | 0.2 | 3395 | 2.03 KiB |  |
+| `rope_table` | `rope_table_f32` | libr4d | `rot=64 theta=1e+07 scale=1 dtype=f32 M=2` | 2.50 | - | 2.49 | 2.50 | 6 | 0.3 | 3386 | 520 B |  |
+| `kv_store` | `kv_store_fp8` | libr4d | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=64` | 2.50 | - | 2.49 | 2.50 | 6 | 0.2 | 3439 | 448.25 KiB | restore 47% |
+| `rope_table` | `rope_table_f32` | libr4d | `rot=64 theta=1e+07 scale=1 dtype=f32 M=4` | 2.50 | - | 2.49 | 2.51 | 6 | 0.3 | 3391 | 1.02 KiB |  |
+| `rope_table` | `rope_table_f32` | libr4d | `rot=64 theta=1e+07 scale=1 dtype=f32 M=1` | 2.49 | - | 2.49 | 2.51 | 6 | 0.6 | 3365 | 260 B |  |
+| `kv_store` | `kv_store_fp8` | libr4d | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=64` | 2.49 | - | 2.49 | 2.52 | 6 | 0.7 | 3403 | 448.25 KiB | restore 47% |
+| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | `channels=128 eps=1e-06 act=silu M=256` | 2.49 | - | 2.48 | 2.49 | 6 | 0.2 | 3391 | 192.50 KiB |  |
+| `silu_mul` | `silu_mul_bf16` | libr4d | `n=17408 dtype=bf16 M=2` | 2.49 | - | 2.48 | 2.52 | 6 | 0.7 | 3454 | 204.00 KiB |  |
+| `gdn_kkt_solve` | `avx_gdn_kkt_solve` | libavx | `head_k=128 M=2 chunk=64` | - | 2.48 | 2.44 | 2.55 | 20 | 1.7 | - | 20.76 KiB | 32 thread(s) |
+| `kv_store` | `avx_kv_store` | libavx | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=4` | - | 2.48 | 2.43 | 2.56 | 20 | 1.8 | - | 112.02 KiB | 32 thread(s) |
+| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | `channels=128 eps=1e-06 act=silu M=128` | 2.47 | - | 2.46 | 2.48 | 6 | 0.4 | 3389 | 96.50 KiB |  |
+| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | `channels=128 eps=1e-06 act=silu M=16` | 2.46 | - | 2.46 | 2.47 | 6 | 0.1 | 3379 | 12.50 KiB |  |
+| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | `channels=128 eps=1e-06 act=silu M=64` | 2.46 | - | 2.45 | 2.47 | 6 | 0.3 | 3394 | 48.50 KiB |  |
+| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | `channels=128 eps=1e-06 act=silu M=8` | 2.46 | - | 2.46 | 2.47 | 6 | 0.3 | 3382 | 6.50 KiB |  |
+| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | `channels=128 eps=1e-06 act=silu M=32` | 2.46 | - | 2.45 | 2.47 | 6 | 0.4 | 3392 | 24.50 KiB |  |
+| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | `channels=128 eps=1e-06 act=silu M=4` | 2.46 | - | 2.45 | 2.47 | 6 | 0.4 | 3382 | 3.50 KiB |  |
+| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | `channels=128 eps=1e-06 act=silu M=2` | 2.45 | - | 2.45 | 2.47 | 6 | 0.4 | 3380 | 2.00 KiB |  |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=128` | - | 2.45 | 2.35 | 2.72 | 20 | 7.0 | - | 64.25 KiB | 32 thread(s) |
+| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | `channels=128 eps=1e-06 act=silu M=1` | 2.45 | - | 2.45 | 2.46 | 6 | 0.2 | 3372 | 1.25 KiB |  |
+| `silu_mul` | `silu_mul_bf16` | libr4d | `n=17408 dtype=bf16 M=1` | 2.44 | - | 2.44 | 2.45 | 6 | 0.2 | 3441 | 102.00 KiB |  |
+| `kv_store` | `kv_store_fp8` | libr4d | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=32` | 2.44 | - | 2.43 | 2.46 | 6 | 0.6 | 3432 | 256.12 KiB | restore 47% |
+| `kv_store` | `kv_store_fp8` | libr4d | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=32` | 2.43 | - | 2.43 | 2.45 | 6 | 0.5 | 3404 | 256.12 KiB | restore 47% |
+| `kv_store` | `kv_store_fp8` | libr4d | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=16` | 2.43 | - | 2.43 | 2.45 | 6 | 0.4 | 3416 | 160.06 KiB | restore 47% |
+| `layernorm` | `avx_layernorm` | libavx | `n=1152 eps=1e-06 dtype=bf16 M=8` | - | 2.43 | 2.43 | 2.50 | 16 | 0.6 | - | 40.50 KiB | 32 thread(s) |
+| `kv_store` | `kv_store_fp8` | libr4d | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=16` | 2.43 | - | 2.42 | 2.44 | 6 | 0.3 | 3434 | 160.06 KiB | restore 47% |
+| `kv_store` | `kv_store_fp8` | libr4d | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=8` | 2.43 | - | 2.41 | 2.44 | 6 | 0.6 | 3414 | 128.03 KiB | restore 47% |
+| `kv_store` | `kv_store_fp8` | libr4d | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=8` | 2.43 | - | 2.42 | 2.43 | 6 | 0.3 | 3435 | 128.03 KiB | restore 47% |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=64` | - | 2.42 | 2.36 | 2.63 | 20 | 4.0 | - | 64.50 KiB | 32 thread(s) |
+| `kv_store` | `kv_store_fp8` | libr4d | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=4` | 2.42 | - | 2.42 | 2.43 | 6 | 0.2 | 3415 | 112.02 KiB | restore 47% |
+| `kv_store` | `kv_store_fp8` | libr4d | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=1` | 2.42 | - | 2.39 | 2.43 | 11 | 0.7 | 3404 | 100.00 KiB | restore 47% |
+| `kv_store` | `kv_store_fp8` | libr4d | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=4` | 2.42 | - | 2.41 | 2.42 | 6 | 0.2 | 3434 | 112.02 KiB | restore 47% |
+| `kv_store` | `kv_store_fp8` | libr4d | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=2` | 2.42 | - | 2.41 | 2.44 | 6 | 0.5 | 3415 | 104.01 KiB | restore 47% |
+| `kv_store` | `kv_store_fp8` | libr4d | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=1` | 2.41 | - | 2.41 | 2.42 | 6 | 0.3 | 3416 | 100.00 KiB | restore 47% |
+| `kv_store` | `kv_store_fp8` | libr4d | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=2` | 2.41 | - | 2.41 | 2.42 | 6 | 0.2 | 3432 | 104.01 KiB | restore 47% |
+| `cast` | `cast_bf16_bf16` | libr4d | `n=5120 from=bf16 to=bf16 M=64` | 2.39 | - | 2.38 | 2.39 | 6 | 0.2 | 3370 | 1.25 MiB |  |
+| `gather_rows` | `avx_gather_rows` | libavx | `n=5120 dtype=bf16 M=56` | - | 2.37 | 2.34 | 2.44 | 20 | 1.5 | - | 2.73 MiB | 32 thread(s) |
+| `gather_rows` | `avx_gather_rows` | libavx | `n=5120 dtype=bf16 M=8` | - | 2.32 | 2.24 | 2.34 | 14 | 1.0 | - | 400.03 KiB | 32 thread(s) |
+| `rope` | `avx_rope` | libavx | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=4` | - | 2.32 | 2.29 | 2.40 | 16 | 0.9 | - | 8.02 KiB | 32 thread(s) |
+| `sample_temp` | `sample_temp_f32` | libr4d | `n_vocab=1024 M=32` | 2.32 | - | 2.31 | 2.33 | 6 | 0.4 | 3587 | 131.00 KiB | restore 47% |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=2 splits=0` | - | 2.31 | 2.29 | 2.40 | 19 | 0.4 | - | 64.01 KiB | 32 thread(s) |
+| `sample_temp` | `sample_temp_f32` | libr4d | `n_vocab=1024 M=16` | 2.29 | - | 2.29 | 2.30 | 6 | 0.3 | 3585 | 65.50 KiB | restore 47% |
+| `embed_lookup` | `avx_embed_lookup` | libavx | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=4` | - | 2.29 | 2.13 | 2.35 | 16 | 0.7 | - | 2.37 GiB | 32 thread(s) |
+| `rope` | `avx_rope` | libavx | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=4` | - | 2.29 | 2.24 | 2.35 | 20 | 1.1 | - | 48.05 KiB | 32 thread(s) |
+| `sample_temp` | `sample_temp_f32` | libr4d | `n_vocab=1024 M=8` | 2.27 | - | 2.27 | 2.28 | 6 | 0.3 | 3586 | 32.75 KiB | restore 48% |
+| `embed_lookup` | `avx_embed_lookup` | libavx | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=32` | - | 2.27 | 2.23 | 2.43 | 20 | 3.9 | - | 2.37 GiB | 32 thread(s) |
+| `sample_temp` | `sample_temp_f32` | libr4d | `n_vocab=1024 M=4` | 2.27 | - | 2.26 | 2.28 | 6 | 0.3 | 3585 | 16.38 KiB | restore 48% |
+| `sample_temp` | `sample_temp_f32` | libr4d | `n_vocab=1024 M=2` | 2.27 | - | 2.26 | 2.28 | 6 | 0.3 | 3587 | 8.19 KiB | restore 48% |
+| `sample_temp` | `sample_temp_f32` | libr4d | `n_vocab=1024 M=1` | 2.27 | - | 2.23 | 2.28 | 11 | 0.5 | 3584 | 4.09 KiB | restore 47% |
+| `cast` | `cast_bf16_bf16` | libr4d | `n=5120 from=bf16 to=bf16 M=32` | 2.26 | - | 2.26 | 2.27 | 6 | 0.2 | 3366 | 640.00 KiB |  |
+| `cast` | `cast_bf16_bf16` | libr4d | `n=5120 from=bf16 to=bf16 M=16` | 2.23 | - | 2.23 | 2.24 | 6 | 0.3 | 3372 | 320.00 KiB |  |
+| `rope` | `avx_rope` | libavx | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=2` | - | 2.23 | 2.15 | 2.58 | 20 | 4.5 | - | 16.01 KiB | 32 thread(s) |
+| `attn_dense` | `avx_attn_dense` | libavx | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=8` | - | 2.22 | 2.21 | 2.28 | 20 | 1.0 | - | 4.51 KiB | 32 thread(s) |
+| `cast` | `cast_bf16_bf16` | libr4d | `n=5120 from=bf16 to=bf16 M=8` | 2.20 | - | 2.20 | 2.21 | 6 | 0.3 | 3371 | 160.00 KiB |  |
+| `gather_rows` | `avx_gather_rows` | libavx | `n=5120 dtype=bf16 M=4` | - | 2.19 | 1.93 | 2.35 | 20 | 5.4 | - | 200.02 KiB | 32 thread(s) |
+| `cast` | `cast_bf16_bf16` | libr4d | `n=5120 from=bf16 to=bf16 M=4` | 2.19 | - | 2.19 | 2.21 | 6 | 0.4 | 3375 | 80.00 KiB |  |
+| `cast` | `cast_bf16_bf16` | libr4d | `n=5120 from=bf16 to=bf16 M=2` | 2.19 | - | 2.18 | 2.20 | 6 | 0.3 | 3356 | 40.00 KiB |  |
+| `cast` | `cast_bf16_bf16` | libr4d | `n=5120 from=bf16 to=bf16 M=1` | 2.18 | - | 2.18 | 2.20 | 6 | 0.6 | 3310 | 20.00 KiB |  |
+| `attn_paged` | `avx_attn_paged` | libavx | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=fp8_e4m3 q_len=1 splits=0` | - | 2.14 | 2.10 | 2.23 | 20 | 2.6 | - | 48.01 KiB | 32 thread(s) |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=4096 group=128 dtype=bf16 M=1` | - | 2.00 | 1.89 | 2.06 | 20 | 1.6 | - | 12.12 KiB | 32 thread(s) |
+| `quant_act_fp8` | `avx_quant_act_fp8` | libavx | `n=5120 group=128 dtype=bf16 M=1` | - | 1.99 | 1.97 | 2.05 | 20 | 1.3 | - | 15.16 KiB | 32 thread(s) |
+| `gather_rows` | `avx_gather_rows` | libavx | `n=5120 dtype=bf16 M=16` | - | 1.98 | 1.95 | 2.09 | 20 | 1.9 | - | 800.06 KiB | 32 thread(s) |
+| `embed_lookup` | `avx_embed_lookup` | libavx | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=16` | - | 1.96 | 1.94 | 2.02 | 19 | 0.9 | - | 2.37 GiB | 32 thread(s) |
+| `gather_rows` | `avx_gather_rows` | libavx | `n=5120 dtype=bf16 M=32` | - | 1.95 | 1.94 | 2.04 | 20 | 1.5 | - | 1.56 MiB | 32 thread(s) |
+| `gdn_kkt_solve` | `avx_gdn_kkt_solve` | libavx | `head_k=128 M=1 chunk=64` | - | 1.95 | 1.94 | 2.01 | 16 | 0.6 | - | 10.38 KiB | 32 thread(s) |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=1` | - | 1.94 | 1.86 | 1.98 | 20 | 1.9 | - | 30.00 KiB | 32 thread(s) |
+| `embed_lookup` | `avx_embed_lookup` | libavx | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=8` | - | 1.91 | 1.88 | 2.00 | 14 | 0.9 | - | 2.37 GiB | 32 thread(s) |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=32` | - | 1.90 | 1.89 | 1.94 | 14 | 0.8 | - | 32.50 KiB | 32 thread(s) |
+| `rope` | `avx_rope` | libavx | `head_dim=72 n_head=16 n_head_kv=16 theta=10000 scale=1 mode=axial rotary_dim=72 sections=18 18 M=1` | - | 1.85 | 1.77 | 1.88 | 20 | 2.2 | - | 6.76 KiB | 32 thread(s) |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=1` | - | 1.76 | 1.74 | 1.80 | 20 | 1.1 | - | 30.00 KiB | 32 thread(s) |
+| `rope` | `avx_rope` | libavx | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=2` | - | 1.73 | 1.68 | 1.85 | 20 | 3.8 | - | 4.01 KiB | 32 thread(s) |
+| `rope` | `avx_rope` | libavx | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=8` | - | 1.72 | 1.65 | 1.80 | 20 | 2.6 | - | 16.09 KiB | 32 thread(s) |
+| `rope_table` | `avx_rope_table` | libavx | `rot=64 theta=1e+07 scale=1 dtype=f32 M=16` | - | 1.61 | 1.61 | 1.66 | 14 | 0.9 | - | 4.06 KiB | 32 thread(s) |
+| `kv_store` | `avx_kv_store` | libavx | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=2` | - | 1.56 | 1.53 | 1.67 | 20 | 2.9 | - | 104.01 KiB | 32 thread(s) |
+| `cast` | `avx_cast` | libavx | `n=5120 from=bf16 to=bf16 M=2` | - | 1.54 | 1.53 | 1.57 | 16 | 0.2 | - | 40.00 KiB | 32 thread(s) |
+| `kv_store` | `avx_kv_store` | libavx | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=2` | - | 1.52 | 1.50 | 1.68 | 16 | 0.7 | - | 104.01 KiB | 32 thread(s) |
+| `gdn_gated_rmsnorm` | `avx_gdn_gated_rmsnorm` | libavx | `channels=128 eps=1e-06 act=silu M=16` | - | 1.51 | 1.50 | 1.54 | 11 | 0.9 | - | 12.50 KiB | 32 thread(s) |
+| `layernorm` | `avx_layernorm` | libavx | `n=1152 eps=1e-06 dtype=bf16 M=4` | - | 1.50 | 1.49 | 1.53 | 14 | 0.5 | - | 22.50 KiB | 32 thread(s) |
+| `rope` | `avx_rope` | libavx | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=1` | - | 1.49 | 1.43 | 2.31 | 20 | 7.7 | - | 8.00 KiB | 32 thread(s) |
+| `quant_act_i8` | `avx_quant_act_i8` | libavx | `n=5120 group=128 dtype=bf16 M=1` | - | 1.48 | 1.48 | 1.51 | 6 | 1.0 | - | 17.50 KiB | 32 thread(s) |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=32` | - | 1.46 | 1.45 | 1.50 | 16 | 0.7 | - | 16.25 KiB | 32 thread(s) |
+| `rope` | `avx_rope` | libavx | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=2` | - | 1.45 | 1.43 | 1.49 | 20 | 1.0 | - | 24.02 KiB | 32 thread(s) |
+| `kv_store` | `avx_kv_store` | libavx | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=fp8_e4m3 M=1` | - | 1.28 | 1.19 | 1.38 | 20 | 5.1 | - | 100.00 KiB | 32 thread(s) |
+| `sample_penalties` | `avx_sample_penalties` | libavx | `n_vocab=248320 M=1` | - | 1.22 | 1.18 | 1.48 | 19 | 0.8 | - | 970.34 KiB | 32 thread(s) |
+| `rope` | `avx_rope` | libavx | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=4` | - | 1.21 | 1.17 | 1.27 | 20 | 3.7 | - | 8.05 KiB | 32 thread(s) |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=16` | - | 1.17 | 1.16 | 1.20 | 14 | 0.9 | - | 16.50 KiB | 32 thread(s) |
+| `sample_temp` | `avx_sample_temp` | libavx | `n_vocab=1024 M=8` | - | 1.16 | 1.14 | 1.19 | 20 | 1.3 | - | 32.75 KiB | 32 thread(s) |
+| `rope` | `avx_rope` | libavx | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=1` | - | 1.12 | 1.09 | 1.18 | 20 | 2.7 | - | 12.01 KiB | 32 thread(s) |
+| `rope` | `avx_rope` | libavx | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=1` | - | 1.12 | 1.09 | 1.24 | 20 | 2.2 | - | 2.00 KiB | 32 thread(s) |
+| `rope_table` | `avx_rope_table` | libavx | `rot=64 theta=1e+07 scale=1 dtype=f32 M=8` | - | 1.07 | 1.06 | 1.13 | 16 | 0.5 | - | 2.03 KiB | 32 thread(s) |
+| `sample_dry` | `avx_sample_dry` | libavx | `n_vocab=248320 M=1` | - | 1.03 | 0.99 | 1.15 | 16 | 1.0 | - | 970.41 KiB | 32 thread(s) |
+| `layernorm` | `avx_layernorm` | libavx | `n=1152 eps=1e-06 dtype=bf16 M=2` | - | 1.01 | 0.99 | 1.04 | 20 | 1.3 | - | 13.50 KiB | 32 thread(s) |
+| `kv_store` | `avx_kv_store` | libavx | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=fp8_e4m3 M=1` | - | 0.97 | 0.95 | 1.01 | 20 | 1.5 | - | 100.00 KiB | 32 thread(s) |
+| `attn_dense` | `avx_attn_dense` | libavx | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=4` | - | 0.97 | 0.96 | 1.02 | 16 | 0.8 | - | 2.26 KiB | 32 thread(s) |
+| `cast` | `avx_cast` | libavx | `n=5120 from=bf16 to=bf16 M=1` | - | 0.96 | 0.96 | 0.99 | 16 | 0.3 | - | 20.00 KiB | 32 thread(s) |
+| `gdn_gated_rmsnorm` | `avx_gdn_gated_rmsnorm` | libavx | `channels=128 eps=1e-06 act=silu M=8` | - | 0.96 | 0.96 | 0.98 | 14 | 0.9 | - | 6.50 KiB | 32 thread(s) |
+| `rope` | `avx_rope` | libavx | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=2` | - | 0.96 | 0.94 | 1.04 | 20 | 3.6 | - | 4.02 KiB | 32 thread(s) |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=16` | - | 0.92 | 0.91 | 0.94 | 20 | 1.1 | - | 8.25 KiB | 32 thread(s) |
+| `layernorm` | `avx_layernorm` | libavx | `n=1152 eps=1e-06 dtype=bf16 M=1` | - | 0.86 | 0.84 | 0.89 | 16 | 0.8 | - | 9.00 KiB | 32 thread(s) |
+| `rope_table` | `avx_rope_table` | libavx | `rot=64 theta=1e+07 scale=1 dtype=f32 M=4` | - | 0.85 | 0.85 | 0.87 | 16 | 0.9 | - | 1.02 KiB | 32 thread(s) |
+| `rope` | `avx_rope` | libavx | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=imrope rotary_dim=64 sections=11 11 10 M=1` | - | 0.83 | 0.79 | 0.88 | 20 | 3.6 | - | 2.01 KiB | 32 thread(s) |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=8` | - | 0.80 | 0.79 | 0.83 | 20 | 1.8 | - | 8.50 KiB | 32 thread(s) |
+| `embed_lookup` | `avx_embed_lookup` | libavx | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=2` | - | 0.72 | 0.69 | 0.74 | 20 | 1.9 | - | 2.37 GiB | 32 thread(s) |
+| `gdn_gated_rmsnorm` | `avx_gdn_gated_rmsnorm` | libavx | `channels=128 eps=1e-06 act=silu M=4` | - | 0.69 | 0.68 | 0.70 | 14 | 0.8 | - | 3.50 KiB | 32 thread(s) |
+| `scatter_rows` | `avx_scatter_rows` | libavx | `n=5120 dtype=bf16 M=2` | - | 0.69 | 0.66 | 0.75 | 20 | 5.1 | - | 100.01 KiB | 32 thread(s) |
+| `sample_temp` | `avx_sample_temp` | libavx | `n_vocab=1024 M=4` | - | 0.68 | 0.64 | 0.73 | 20 | 3.7 | - | 16.38 KiB | 32 thread(s) |
+| `rope_table` | `avx_rope_table` | libavx | `rot=64 theta=1e+07 scale=1 dtype=f32 M=2` | - | 0.68 | 0.66 | 0.71 | 16 | 0.7 | - | 520 B | 32 thread(s) |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=8` | - | 0.67 | 0.66 | 0.68 | 20 | 1.6 | - | 4.25 KiB | 32 thread(s) |
+| `gather_rows` | `avx_gather_rows` | libavx | `n=5120 dtype=bf16 M=2` | - | 0.63 | 0.62 | 0.65 | 20 | 1.3 | - | 100.01 KiB | 32 thread(s) |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=4` | - | 0.61 | 0.60 | 0.63 | 19 | 0.7 | - | 4.50 KiB | 32 thread(s) |
+| `attn_dense` | `avx_attn_dense` | libavx | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=2` | - | 0.61 | 0.60 | 0.62 | 19 | 0.6 | - | 1.13 KiB | 32 thread(s) |
+| `attn_dense` | `avx_attn_dense` | libavx | `head_dim=72 gqa=1 causal=0 dtype=bf16 scale=0.117851 max_seqlen=2048 M=1` | - | 0.61 | 0.49 | 0.74 | 20 | 20.1 | - | 584 B | 32 thread(s) |
+| `rope_table` | `avx_rope_table` | libavx | `rot=64 theta=1e+07 scale=1 dtype=f32 M=1` | - | 0.58 | 0.58 | 0.60 | 14 | 0.5 | - | 260 B | 32 thread(s) |
+| `scatter_rows` | `avx_scatter_rows` | libavx | `n=5120 dtype=bf16 M=1` | - | 0.57 | 0.52 | 0.63 | 20 | 7.0 | - | 50.00 KiB | 32 thread(s) |
+| `embed_lookup` | `avx_embed_lookup` | libavx | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=1` | - | 0.56 | 0.56 | 0.68 | 20 | 2.7 | - | 2.37 GiB | 32 thread(s) |
+| `sample_temp` | `avx_sample_temp` | libavx | `n_vocab=1024 M=2` | - | 0.56 | 0.53 | 0.57 | 20 | 1.8 | - | 8.19 KiB | 32 thread(s) |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=4` | - | 0.55 | 0.54 | 0.56 | 20 | 1.1 | - | 2.25 KiB | 32 thread(s) |
+| `gdn_gated_rmsnorm` | `avx_gdn_gated_rmsnorm` | libavx | `channels=128 eps=1e-06 act=silu M=2` | - | 0.55 | 0.54 | 0.56 | 19 | 0.5 | - | 2.00 KiB | 32 thread(s) |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=2` | - | 0.51 | 0.51 | 0.53 | 20 | 1.1 | - | 2.50 KiB | 32 thread(s) |
+| `gather_rows` | `avx_gather_rows` | libavx | `n=5120 dtype=bf16 M=1` | - | 0.51 | 0.50 | 0.52 | 20 | 1.2 | - | 50.00 KiB | 32 thread(s) |
+| `sample_temp` | `avx_sample_temp` | libavx | `n_vocab=1024 M=1` | - | 0.50 | 0.48 | 0.55 | 20 | 5.0 | - | 4.09 KiB | 32 thread(s) |
+| `gdn_gated_rmsnorm` | `avx_gdn_gated_rmsnorm` | libavx | `channels=128 eps=1e-06 act=silu M=1` | - | 0.49 | 0.49 | 0.51 | 20 | 1.4 | - | 1.25 KiB | 32 thread(s) |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=2` | - | 0.48 | 0.48 | 0.49 | 14 | 0.4 | - | 1.25 KiB | 32 thread(s) |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=1` | - | 0.47 | 0.47 | 0.48 | 20 | 1.2 | - | 1.50 KiB | 32 thread(s) |
+| `rmsnorm` | `avx_rmsnorm` | libavx | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=1` | - | 0.46 | 0.45 | 0.47 | 20 | 1.3 | - | 768 B | 32 thread(s) |
 
 ## Memory safety
 
-Every device allocation in this run -- every operand and every kernel's own scratch -- was
-made with a poisoned 256-byte margin on both sides, the kernel was handed the middle, and the
-margins were read back and verified after the checked launch. It catches an out-of-bounds
-WRITE, which is the one that corrupts a neighbouring tensor and surfaces as wrong output three
-ops later in a kernel that is correct. An out-of-bounds READ it cannot see.
+Every device allocation in this run (operands and kernel scratch) had a poisoned 256-byte margin
+on both sides, verified after the checked launch. This catches out-of-bounds writes, which
+corrupt a neighbouring tensor; out-of-bounds reads go unseen.
 
-AMD's amdgcn AddressSanitizer (`/opt/rocm/amdgcn/bitcode/asanrtl.bc`) is not an option on every
-card: its shadow is page-fault based and needs `xnack+`, which RDNA does not implement --
-`rocminfo` reports `XNACK enabled: NO` there. The margins are what replaces it.
+AMD's amdgcn AddressSanitizer (`/opt/rocm/amdgcn/bitcode/asanrtl.bc`) needs `xnack+` for its
+page-fault-based shadow, which RDNA does not implement (`rocminfo` reports `XNACK enabled: NO`),
+so the margins stand in for it.
 
-- 537 case(s) ran inside guarded allocations
+- 734 case(s) ran inside guarded allocations
 - 0 wrote outside one
 
 ## Not covered
 
-A skip is a real answer: the tool declined rather than invent an extent, a dtype or an
-oracle it does not have. Each line below is a gap in COVERAGE, not a failing kernel.
+A skip means the tool declined a case rather than invent an extent, a dtype or an oracle it
+does not have. Each line below is a gap in coverage, not a failing kernel.
 
-**Collective ops are not checked here and cannot be.** `all_reduce`, `all_gather` and the
-fused all-reduce forms establish one instance across ranks through a rendezvous over peer
-memory: a single process has nobody to reduce with, and a kernel waiting for a peer that
-never arrives hangs rather than failing. They appear in the completeness matrix because the
-rows exist; they carry no correctness or speed number because producing one needs a second
-rank, and that is a different harness.
+**Collective ops are not checked.** `all_reduce`, `all_gather` and the fused all-reduce forms
+rendezvous with peer ranks over peer memory; in a single process a kernel waiting for a peer
+hangs. They appear in the completeness matrix but carry no correctness or speed number.
 
 | what | cases |
 |---|---|
-| logits_gemm  (reference was recorded through logits_gemm_fp8's weight layout, which ref_logits_gemm does not implement; only that row can reproduce it) | 7 |
+| logit_rerank  (one case needs 14.21 GiB, over the 8.00 GiB budget -- raise --max-bytes to check it) | 7 |
 
 ## Static and dynamic analysis
 
@@ -1828,28 +4353,35 @@ Advisory, and generated separately from the measurements above:
 (`libref/`, `core/`, `tools/`). HIP units are excluded: clang-tidy cannot replay the
 offload flags and reports `__device__` as an error rather than analysing the body.
 
-- 195 warning(s)
+- 358 distinct warning(s)
 
 | check | count |
 |---|---|
-| `[bugprone-unchecked-string-to-number-conversion]` | 49 |
-| `[bugprone-assignment-in-if-condition]` | 41 |
-| `[performance-enum-size]` | 18 |
-| `[performance-inefficient-vector-operation]` | 10 |
-| `[bugprone-multi-level-implicit-pointer-conversion]` | 10 |
-| `[bugprone-misplaced-widening-cast]` | 9 |
-| `[bugprone-implicit-widening-of-multiplication-result]` | 9 |
-| `[bugprone-suspicious-string-compare]` | 8 |
-| `[bugprone-branch-clone]` | 6 |
-| `[performance-inefficient-string-concatenation]` | 5 |
-| `[performance-unnecessary-value-param]` | 3 |
-| `[bugprone-throwing-static-initialization]` | 3 |
-| `[bugprone-signed-char-misuse]` | 2 |
-| `[bugprone-incorrect-roundings]` | 2 |
-| `[performance-no-int-to-ptr]` | 1 |
-| `[bugprone-integer-division]` | 1 |
-| `[bugprone-exception-escape]` | 1 |
-| `[bugprone-empty-catch]` | 1 |
+| `[bugprone-unchecked-string-to-number-conversion]` | 60 |
+| `[bugprone-assignment-in-if-condition]` | 56 |
+| `[bugprone-implicit-widening-of-multiplication-result]` | 34 |
+| `[performance-inefficient-string-concatenation]` | 31 |
+| `[bugprone-suspicious-string-compare]` | 16 |
+| `[performance-no-int-to-ptr]` | 15 |
+| `[performance-inefficient-vector-operation]` | 14 |
+| `[bugprone-misplaced-widening-cast]` | 13 |
+| `[bugprone-incorrect-roundings]` | 11 |
+| `[bugprone-signed-char-misuse]` | 9 |
+| `[bugprone-multi-level-implicit-pointer-conversion]` | 9 |
+| `[bugprone-branch-clone]` | 8 |
+| `[performance-unnecessary-value-param]` | 6 |
+| `[bugprone-switch-missing-default-case]` | 6 |
+| `[bugprone-throwing-static-initialization]` | 5 |
+| `[bugprone-reserved-identifier]` | 3 |
+| `[performance-unnecessary-copy-initialization]` | 2 |
+| `[bugprone-return-const-ref-from-parameter]` | 2 |
+| `[bugprone-integer-division]` | 2 |
+| `[bugprone-exception-escape]` | 2 |
+| `[bugprone-empty-catch]` | 2 |
+| `[performance-no-automatic-move]` | 1 |
+| `[bugprone-random-generator-seed]` | 1 |
+| `[bugprone-not-null-terminated-result]` | 1 |
+| `[bugprone-forward-declaration-namespace]` | 1 |
 
 ### AddressSanitizer + UndefinedBehaviorSanitizer
 
diff --git a/docs/MOE-W4.md b/docs/MOE-W4.md
index 78bc3757..59fd8aad 100644
--- a/docs/MOE-W4.md
+++ b/docs/MOE-W4.md
@@ -1,25 +1,27 @@
 # The four-bit MoE expert format
 
-Qwen3.8-Flash-Next has 512 experts of 640 over 48 layers. At E4M3 that is **112.8 GiB of expert
-weight** against two 32 GB cards. Splitting the experts over the two ranks halves the per-rank
-share and the placement planner still refuses 26 GiB. A routed weight can be served from the file
-tier (`--weights-disk-tier`), but it is then read a layer at a time and a step is paced by the
-drive. Pinned host memory does not close it either on a host with 64 GB of RAM (2 x 34.78 GiB).
-
-So four bits is not an optimisation here. It is what lets the model run from VRAM and host memory:
-an expert unit is 2.42 MiB instead of 4.69, the per-rank share is ~29 GiB, and that fits VRAM plus
-a few GiB of pinned host.
+Qwen3.8-Flash-Next has 512 experts of 640 over 48 layers: 112.5 GiB of expert weight at E4M3,
+against two 32 GB cards. Split over both ranks, the placement planner still comes up 26 GiB short.
+The file tier (`--weights-disk-tier`) can serve routed weights, but it reads them a layer at a time
+and a step is then paced by the drive; pinned host memory does not close the gap on a 64 GB host.
+At four bits an expert unit is 2.42 MiB instead of 4.69, the per-rank share is ~29 GiB, and that
+fits VRAM plus a few GiB of pinned host.
 
 ## What is served
 
 Qwen3.8-Flash-Next is served as `w4nl64-i8lm.rad`, built by
-`data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe` with `CALIB=` naming the calibration Grams
-(below, "Calibration"): the routed experts at `w4nl64a8h` (the w4nl codebook below, an E4M3 scale
-a row and group of 64, GPTQ and three sweeps of coordinate descent), ten protected experts bf16,
-and the trunk's block linears and the lm_head **int8, served W8A8** -- `gemm_i8a8_nt_m16` /
-`gemm_i8a8_tiled` and `logits_gemm_i8` (docs/OPS.md), every quantising producer writing the int8
-codes its consumer reads, so an int8 trunk adds no quantiser launch. How each step moved the model, by the engine's KL mode against the
-bf16 model over the same 83K positions (docs/TOOLS.md, "The KL mode"):
+`data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe` with `CALIB=` naming the calibration Grams (see
+"Calibration"):
+
+- routed experts at `w4nl64a8h`: the w4nl codebook, an E4M3 scale per row and group of 64, GPTQ
+  and three sweeps of coordinate descent;
+- ten protected experts bf16;
+- the trunk's block linears and the lm_head int8, served W8A8 (`gemm_i8a8_nt_m16` /
+  `gemm_i8a8_tiled` and `logits_gemm_i8`, `docs/OPS.md`). Every quantising producer writes the int8
+  codes its consumer reads, so an int8 trunk adds no quantiser launch.
+
+Each row below adds one change to the row above, measured with the engine's KL mode against the
+bf16 model over the same 83K positions ([TOOLS.md](TOOLS.md#the-kl-mode)):
 
 | | all: mean KL | all: top-1 | text + assistant: mean KL | text + assistant: top-1 |
 |---|---|---|---|---|
@@ -27,23 +29,22 @@ bf16 model over the same 83K positions (docs/TOOLS.md, "The KL mode"):
 | `w4nla8h` experts, GPTQ | 0.1098 | 91.36% | 0.0363 | 93.30% |
 | + int8 W8A8 trunk | 0.0841 | 92.46% | 0.0277 | 94.07% |
 | + int8 lm_head | 0.0830 | 92.84% | 0.0265 | 94.54% |
-| **+ E4M3 scales a 64, coordinate descent (`w4nl64a8h`) -- served** | **0.0789** | **92.85%** | **0.0239** | **94.57%** |
-| + every down projection at five bits (`w5nl64a8h`) -- not served | 0.0717 | 93.34% | 0.0204 | 95.10% |
+| **+ E4M3 scales per 64, coordinate descent (`w4nl64a8h`): served** | **0.0789** | **92.85%** | **0.0239** | **94.57%** |
+| + every down projection at five bits (`w5nl64a8h`): not served | 0.0717 | 93.34% | 0.0204 | 95.10% |
 | a second bf16 implementation (the floor) | 0.0399 | 95.13% | 0.0111 | 96.44% |
 
 The served container's tail: median 0.0037, p99 1.65, p99.9 5.33. **The floor is not zero and is
-most of the overall mean**: the tool-documentation system prompts in the corpus are numerically
-chaotic, and two bf16 implementations already disagree there at KL 0.142 -- so text and assistant
-turns are the slice comparable with other quantisers' published numbers, and the overall mean of
-~0.04 is the floor itself rather than a target a quantised model can reach.
+most of the overall mean**: the corpus's tool-documentation system prompts are numerically chaotic,
+and two bf16 implementations already disagree there at KL 0.142. Text and assistant turns are
+therefore the slice comparable with other quantisers' published numbers.
 
-What it costs, two cards, production flags, against `w4nla8h` with the same trunk: decode
-15.28 -> 15.32 ms a step (+0.3%), a 26K-token prefill 6539 -> 6442 tokens a second (-1.5%). The
-five-bit down projections cost decode +4% and prefill **-19%**: the experts are 8% larger, fewer of
-them fit beside the KV cache (137.5 resident a layer against 149), and a prefill streams the rest.
+Cost on two cards with production flags, against `w4nla8h` with the same trunk: decode 15.28 ->
+15.32 ms per step (+0.3%), a 26K-token prefill 6539 -> 6442 tokens per second (-1.5%). Five-bit
+down projections cost decode +4% and prefill -19%: the experts are 8% larger, fewer fit beside the
+KV cache (137.5 resident per layer against 149), and a prefill streams the rest.
 
-**Where the rest of the loss is.** Emulated with the experts of some layers left bf16 and the rest
-as served (an HF reference with the container's quantisers, which matches the engine to 0.001):
+**Where the remaining loss is.** Emulated with some layers' experts left bf16 and the rest as
+served (an HF reference with the container's quantisers, matching the engine to 0.001):
 
 | | all: mean KL | all: top-1 | text + assistant | system / user |
 |---|---|---|---|---|
@@ -51,31 +52,35 @@ as served (an HF reference with the container's quantisers, which matches the en
 | every down projection bf16 | 0.0700 | 93.61% | 0.0203 | 0.2456 |
 | layers 16-31 bf16 | 0.0631 | 93.51% | 0.0226 | 0.2064 |
 
-Both are a third of the experts' bytes. Five-bit down projections already take ~80% of what bf16
-down projections would; layers 16-31 hold more of the overall mean -- almost all of it on the
-chaotic system and user turns -- and text and assistant turns are most sensitive in layers 24-39.
-Round-to-nearest experts in one group of eight layers at a time, the rest bf16, put the excess
-over the floor at .012, .017, .031, .026, .020 and .009 for layers 0-7 through 40-47.
+Both are a third of the experts' bytes. Five-bit down projections already recover ~80% of what bf16
+down projections would. Layers 16-31 hold more of the overall mean, almost all of it on the chaotic
+system and user turns; text and assistant turns are most sensitive in layers 24-39. With
+round-to-nearest experts in one group of eight layers at a time and the rest bf16, the excess over
+the floor is .012, .017, .031, .026, .020 and .009 for layers 0-7 through 40-47.
 
-**What did not pay**, measured: GPTQ's act order (no change once the
-weight is rotated), its dampening at 0.003 and 0.03 (within 0.4%), a codebook of the layer's own
-(Lloyd's fit is the same in every layer) or one refitted at groups of 64 or for the E4M3 grid
-(worse), a power-of-two sub-scale a 32 under the 64-wide scale (0.0679 -> 0.0675),
-a 256-word two-dimensional codebook a pair of weights (10% less error than the scalar table, for an
-LDS lookup a byte), more protected bf16 experts (+4% bytes for 7% less error), and E4M3 scales a 32
-(13% less error energy for +13-18% on the expert GEMMs).
+Tried without benefit:
 
-**Further quality levers**, in order: five bits on both projections of layers
-16-31 (the same +8% as the down projections, ~0.066 expected), and fewer layers at five bits for a
-smaller prefill cost. The formats, the kernel and a layer's own choice of form are all in the tree.
+- GPTQ's act order (no change once the weight is rotated); its dampening at 0.003 and 0.03 (within
+  0.4%);
+- a codebook per layer (Lloyd's fit is the same in every layer), or one refitted at groups of 64 or
+  for the E4M3 grid (worse);
+- a power-of-two sub-scale per 32 under the 64-wide scale (0.0679 -> 0.0675);
+- a 256-word two-dimensional codebook per pair of weights (10% less error than the scalar table,
+  for an LDS lookup per byte);
+- more protected bf16 experts (+4% bytes for 7% less error);
+- E4M3 scales per 32 (13% less error energy for +13-18% on the expert GEMMs).
+
+Remaining levers: five bits on both projections of layers 16-31 (+8% bytes, like the down
+projections, ~0.066 expected), or fewer layers at five bits for a smaller prefill cost. The
+formats, the kernel and per-layer form selection are all implemented.
 
 ## The stored plane
 
 Row-major packed nibbles, two's complement `-8..7`, with a **bf16 scale per (row, group of 128
-along K)** -- not the fp8 path's 128x128 tile scale, which would spend all sixteen levels on the
-largest row in a block. The kernel is `moe_gemm_w4a8` (libr4d), which is the fp8 kernel with the
-LDS staging and the scale fold changed: the integers `-8..7` are exact in E4M3, so a code expands
-losslessly and the existing fp8 WMMA loop is untouched.
+along K)**, not the fp8 path's 128x128 tile scale, which would spend all sixteen levels on the
+largest row in a block. The kernel is libr4d's `moe_gemm_w4a8`: the fp8 kernel with the LDS staging
+and the scale fold changed. The integers `-8..7` are exact in E4M3, so a code expands losslessly
+and the fp8 WMMA loop is unchanged.
 
 The encodings are **not interchangeable**:
 
@@ -84,55 +89,48 @@ The encodings are **not interchangeable**:
 | `i4*bf16[1x128]` | `w4a8` | int4 codes, a bf16 scale per row and group of 128 along K |
 | `i4*bf16[1x128]/fwht128` | `w4a8h` | the same, with a 128-wide Walsh-Hadamard along K applied before quantising |
 | `affine:codes=u4[1x1],scale=bf16[1x128],table=f32{1x16}/fwht128` | `w4nla8h` | the rotated plane with the codes indexing the `w4nl` codebook (below) |
-| `affine:codes=u4[1x1],scale=fp8_e4m3[1x64],scale.1=f32[*x*],table=f32{1x16}/fwht128` | `w4nl64a8h` | the codebook with an E4M3 scale a row and group of **64**, under one fixed f32 (below) -- the same bytes |
-| `affine:codes=u4[1x1],scale=fp8_e4m3[1x32],scale.1=f32[*x*],table=f32{1x16}/fwht128` | `w4nl32a8h` | the same at a group of **32**, +0.125 bits a weight |
-| `affine:codes=u5[1x1],scale=fp8_e4m3[1x64],scale.1=f32[*x*],table=f32{1x32}/fwht128` | `w5nl64a8h` | `w4nl64a8h` with **five-bit** codes into the 32-level `w5nl` codebook (below), +1 bit a weight |
+| `affine:codes=u4[1x1],scale=fp8_e4m3[1x64],scale.1=f32[*x*],table=f32{1x16}/fwht128` | `w4nl64a8h` | the codebook with an E4M3 scale per row and group of **64**, under one fixed f32 (below); the same bytes |
+| `affine:codes=u4[1x1],scale=fp8_e4m3[1x32],scale.1=f32[*x*],table=f32{1x16}/fwht128` | `w4nl32a8h` | the same at a group of **32**, +0.125 bits per weight |
+| `affine:codes=u5[1x1],scale=fp8_e4m3[1x64],scale.1=f32[*x*],table=f32{1x32}/fwht128` | `w5nl64a8h` | `w4nl64a8h` with **five-bit** codes into the 32-level `w5nl` codebook (below), +1 bit per weight |
 
-The first two have the same planes, extents and byte count and differ only in the transform; the
-container says which encoding each expert has. The architecture plugin asks for the first expert's encoding (`rad_weight_encoding`) and
-declares the matching kernels, and a kernel that does not read an encoding is not a candidate for
-it -- a rotated container cannot be served unrotated. libr4d reorders each row's nibbles into the
-order its unpack reads when the experts load; the container holds them in the canonical order. The
-activation side is `had_quant_act_fp8` / `gated_had_quant_fp8`, which are the ordinary fp8
-quantisers with `r4d_fwht_wave<128>` between the load and the absmax -- free, because that
-kernel's mapping (one wave a 128-column group, four consecutive columns a lane) is already the
-transform's.
+The first two differ only in the transform. The plugin reads the first expert's encoding
+(`rad_weight_encoding`) and declares the matching kernels; a kernel that does not read an encoding
+is not a candidate for it, so a rotated container cannot be served unrotated. The container holds
+nibbles in canonical order, and libr4d reorders each row into its unpack order at load. The
+activation side is `had_quant_act_fp8` / `gated_had_quant_fp8`: the ordinary fp8 quantisers with
+`r4d_fwht_wave<128>` between the load and the absmax, at no cost, since the kernel's mapping (one
+wave per 128-column group, four consecutive columns per lane) is already the transform's.
 
-**The residual factor is not split.** `H` is symmetric, so ` = 128 `, and the whole
-factor of 128 is folded into the **stored weight scale** by the quantiser (`bf16(amax/7) / 128`). The
-int8 rotated ops fold `1/sqrt(group)` into each side; these fold nothing at runtime. That the fold
-goes entirely into the stored scale rather than being split is normative in `docs/OPS.md`
-(*Quantisation and rotation*, the `group` parameter under the `had_*` FP8 forms), which is also
-where the cost of splitting it is stated.
+**The residual factor is not split.** `H` is symmetric, so ` = 128 `, and the
+quantiser folds the whole factor of 128 into the **stored weight scale** (`bf16(amax/7) / 128`).
+The int8 rotated ops fold `1/sqrt(group)` into each side; these fold nothing at runtime. This is
+normative in `docs/OPS.md` (*Quantisation and rotation*, the `group` parameter under the `had_*`
+FP8 forms), which also states the cost of splitting it.
 
 ## The w4nl codebook
 
-A Hadamard-rotated expert weight is close to normal, and sixteen evenly spaced levels are not the
-best sixteen for a normal value: the outer levels are rarely used and the inner ones are too far
-apart. `w4nla8h` keeps everything about the rotated plane -- the bytes a code, the bf16 scale a row
-and group of 128, the rotation, the activation quantiser, the GEMM -- and changes only what a code
-stands for:
+A Hadamard-rotated expert weight is close to normal, for which evenly spaced levels are a poor
+choice: the outer ones are rarely used and the inner ones too far apart. `w4nla8h` keeps everything
+about the rotated plane (bytes per code, scale grid, rotation, activation quantiser, GEMM) and
+changes only what a code stands for:
 
     codes 0..7    1.125  3.25  5.5  8  11  14  18  22
     codes 8..15   the same, negated
 
-Lloyd's quantiser fitted to the rotated, amax-normalised experts of Qwen3.8-Flash-Next gives the
-same levels in every layer and both projections once each is rounded to E4M3, and every one is
-exact in E4M3 -- so the kernel expands a code to the byte the fp8 WMMA reads with no rounding, as
-it does `-8..7`. The decode is the same three byte permutes with another four dwords in them: the
-table is a kernel argument (`r4d_args.h`, `kW4IntPerm` / `kW4nlPerm`), so both formats are one
-code path and the same fifteen VALU per eight weights.
+Lloyd's quantiser on the rotated, amax-normalised experts of Qwen3.8-Flash-Next gives these levels
+in every layer and both projections once rounded to E4M3, and each is exact in E4M3, so a code
+expands to the fp8 WMMA's byte without rounding. The table is a kernel argument (`r4d_args.h`,
+`kW4IntPerm` / `kW4nlPerm`), so both formats share one code path: three byte permutes, fifteen VALU
+per eight weights.
 
 In libquant it is the named codebook `table=w4nl`, which a recipe pairs with `rule=search` (each
-group's scale searched for least error, from 0.70 to 1.10 of amax / 22 and each candidate's
-least-squares refit) and `gptq`. **An encoding cannot say what its table holds**, so the codes view
-selects the `table` plane beside the codes, and the relayout compares it with the kernel's value
-for value before it serves a byte: a container quantised against any other table of the same shape
-is refused at load.
+group's scale searched over 0.70 to 1.10 of amax / 22, plus each candidate's least-squares refit)
+and `gptq`. **An encoding cannot say what its table holds**, so the codes view selects the `table`
+plane beside the codes, and the relayout compares it value for value with the kernel's: a container
+quantised against any other table of the same shape is refused at load.
 
-Measured as held-out output error (`sqrt(tr(dW H dW^T) / tr(W H W^T))`, the layer's pooled gate_up
-Gram and each expert's own down Gram, 6 experts in each of 7 layers), at the same 4.125 bits a
-weight:
+Held-out output error (`sqrt(tr(dW H dW^T) / tr(W H W^T))`, the layer's pooled gate_up Gram and
+each expert's own down Gram, 6 experts in each of 7 layers), at 4.125 bits per weight:
 
 | | gate_up | down |
 |---|---|---|
@@ -142,121 +140,112 @@ weight:
 | `-8..7` + GPTQ | 0.0629 | 0.0832 |
 | `w4nl` + GPTQ | **0.0547** | **0.0720** |
 
-`-8..7` at amax/7, what `w4a8h` containers were converted with, is a further ~10% worse than the
-first row. Halving the group to 64 at bf16 scales (+3% of the expert bytes) does less than the
-codebook does for nothing -- and at E4M3 scales it costs nothing at all (below).
+`-8..7` at amax/7, the scale `w4a8h` containers use, is ~10% worse than the first row. Halving the
+group to 64 at bf16 scales (+3% of the expert bytes) does less than the codebook does for free, and
+at E4M3 scales it costs no bytes (below).
 
-## Finer groups at the same bytes: E4M3 scales under a fixed 2^-13
+## E4M3 scales under a fixed 2^-13
 
-A bf16 scale a 128 is sixteen bits a 128; an E4M3 scale a 64 is the same sixteen. What an E4M3
-scale lacks is range, and the experts do not need it: with the rotation's 1/128 folded in, the
-scales of Qwen3.8-Flash-Next's routed experts at a 64 sit between 2^-15 and 2^-10.6 (every 37th
-expert of eight layers), so under one fixed factor of **2^-13** each is a normal E4M3 value with
-four binades to spare either side -- and E4M3's three mantissa bits are the same in every binade,
-so a per-row second level would buy range nobody uses and no precision. The factor is libr4d's
-`kW4G64Scale`; a container states it as libquant's fixed second level (`scale2=f32 block2=*x*
-scale2_value=0.0001220703125`), and the scale view's relayout compares it with the kernel's before
-it serves a byte, as the codes view does the table. libquant searches each group's scale **as
-stored**: once the second level is known the first is searched again over the E4M3 values it can
-take, or the rounding gives back most of what the search won.
+A bf16 scale per 128 and an E4M3 scale per 64 both cost sixteen bits per 128 weights. E4M3 lacks
+range, which the experts do not need: with the rotation's 1/128 folded in, the per-64 scales of
+Qwen3.8-Flash-Next's routed experts sit between 2^-15 and 2^-10.6 (every 37th expert of eight
+layers), so under one fixed factor of **2^-13** each is a normal E4M3 value with four binades to
+spare either side. E4M3 has three mantissa bits in every binade, so a per-row second level would
+add only unused range. The factor is libr4d's `kW4G64Scale`; a container states it as libquant's
+fixed second level (`scale2=f32 block2=*x* scale2_value=0.0001220703125`), and the scale view's
+relayout checks it against the kernel's. libquant searches each group's scale **as stored**: once
+the second level is known, the first is searched again over its E4M3 values, or rounding gives back
+most of what the search won.
 
-The kernel stages a 128-wide tile's E4M3 scales as one 16- or 32-bit load, sums each scale group's
-WMMA in its own accumulator -- folding a group as it ends would make the next group's WMMA wait on
-its results -- and folds them together at the end of the tile. Held-out output error, GPTQ + `w4nl`
-(layer 20 and 28's experts):
+The kernel loads a 128-wide tile's E4M3 scales in one 16- or 32-bit load and sums each scale
+group's WMMA in its own accumulator, folding them at the end of the tile (folding a group as it
+ends would stall the next group's WMMA). Held-out output error, GPTQ + `w4nl` (layers 20 and 28):
 
-| | gate_up | down | bits a weight |
+| | gate_up | down | bits per weight |
 |---|---|---|---|
-| bf16 a 128 (`w4nla8h`) | 0.0683 / 0.0708 | 0.0842 / 0.0957 | 4.125 |
-| E4M3 a 64 under 2^-13 (`w4nl64a8h`) | 0.0655 / 0.0679 | 0.0807 / 0.0917 | 4.125 |
-| E4M3 a 32 under 2^-13 (`w4nl32a8h`) | -- / 0.0632 | -- / 0.0850 | 4.25 |
+| bf16 per 128 (`w4nla8h`) | 0.0683 / 0.0708 | 0.0842 / 0.0957 | 4.125 |
+| E4M3 per 64 under 2^-13 (`w4nl64a8h`) | 0.0655 / 0.0679 | 0.0807 / 0.0917 | 4.125 |
+| E4M3 per 32 under 2^-13 (`w4nl32a8h`) | -- / 0.0632 | -- / 0.0850 | 4.25 |
 
-and three sweeps of coordinate descent after GPTQ (libquant `cd=3`) take another ~2% off either.
-What the finer groups cost in the GEMM, against `w4nla8h` at a decode step's 4 tokens and a
-2048-token chunk: `w4nl64a8h` +4% / +2% and +7% / +4% (gate_up / down); `w4nl32a8h` +13% / +15%
-and +18% / +11% -- the 32-wide form is for the layers that need it, not the model.
+Three sweeps of coordinate descent after GPTQ (libquant `cd=3`) take another ~2% off either. GEMM
+cost against `w4nla8h`, at a decode step's 4 tokens and a 2048-token chunk (gate_up / down):
+`w4nl64a8h` +4% / +2% and +7% / +4%; `w4nl32a8h` +13% / +15% and +18% / +11%. The 32-wide form is
+for the layers that need it, not the whole model.
 
-## Five bits where the error is: w5nl64a8h
+## Five-bit codes: w5nl64a8h
 
-The 64-wide form at one more bit a weight. libquant's `table=w5nl` is Lloyd's quantiser with
-sixteen magnitudes, fitted to the rotated experts at groups of 64 as `w4nl` was -- the same to
-three places in every layer and both projections -- and rounded to E4M3 at the top level (30) that
-leaves the sixteen distinct and moves them least: 0.8125, 2.5, 4, 5.5, 7.5, 9, 11, 12, 14, 16, 18,
-20, 22, 24, 26, 30, then their negatives. The order makes a code's high bit its sign, so the
-kernel expands the low four bits exactly as a `w4nl` code -- out of the sixteen magnitudes -- and
-sets each byte's sign from a bit plane stored after the row's nibbles. That plane is a dword a 32
-elements, transposed so that a shift by m puts the signs of the expansion's output dword m on
-E4M3's sign bits at once: two VALU per four weights.
+The 64-wide form at one more bit per weight. libquant's `table=w5nl` is Lloyd's quantiser with
+sixteen magnitudes, fitted to the rotated experts at groups of 64 as `w4nl` was (the same to three
+places in every layer and both projections), and rounded to E4M3 at the top level (30) that keeps
+the sixteen distinct and moves them least: 0.8125, 2.5, 4, 5.5, 7.5, 9, 11, 12, 14, 16, 18, 20, 22,
+24, 26, 30, then their negatives. A code's high bit is its sign, so the kernel expands the low four
+bits exactly as a `w4nl` code (from the sixteen magnitudes) and sets each byte's sign from a bit
+plane stored after the row's nibbles. That plane is a dword per 32 elements, transposed so that a
+shift by m puts the signs of the expansion's output dword m on E4M3's sign bits at once: two VALU
+per four weights.
 
-Held-out output error under the production quantiser (GPTQ, an E4M3 scale a 64 under 2^-13, three
-sweeps of coordinate descent), layers 20 and 28:
+Held-out output error under the production quantiser (GPTQ, an E4M3 scale per 64 under 2^-13,
+three sweeps of coordinate descent), layers 20 and 28:
 
 | | gate_up | down |
 |---|---|---|
 | `w4nl64a8h` | 0.0638 | 0.0943 |
 | `w5nl64a8h` | 0.0335 | 0.0501 |
 
--- 72% less error energy for 25% more expert bytes on whatever it is applied to. In the GEMM
-against `w4nl64a8h`, at a 2048-token chunk: +19% gate_up, +8% down, most of it the extra bytes
-streamed. At a decode step the projection reads 25% more from DRAM. (`r4d_selftest --perfmoe` at a
-decode step's 4 tokens times one routing again and again, so its experts sit in the 64 MB last-level
-cache: there the five-bit gate_up falls out of it and reads 3x slower, which a served decode step,
-reading ~3 GB of experts, never sees.)
+That is 72% less error energy for 25% more expert bytes wherever it is applied. In the GEMM
+against `w4nl64a8h` at a 2048-token chunk: +19% gate_up, +8% down, mostly the extra bytes. At a
+decode step the projection reads 25% more from DRAM. (`r4d_selftest --perfmoe` at a decode step's
+4 tokens repeats one routing, so its experts sit in the 64 MB last-level cache; there the five-bit
+gate_up falls out of it and reads 3x slower, which a served decode step, reading ~3 GB of experts,
+never sees.)
 
-Every down projection at five bits (`data/recipes/qwen4exp-w5dn64-i8-hc8m.recipe`) is measured in
-"What is served" above: 0.0717 / 93.34% against 0.0789 / 92.85%, for -19% prefill.
+Every down projection at five bits (`data/recipes/qwen4exp-w5dn64-i8-hc8m.recipe`) is in the table
+under "What is served": 0.0717 / 93.34% against 0.0789 / 92.85%, for -19% prefill.
 
-**WHERE IT GOES IS A PER-PROJECTION, PER-LAYER CHOICE.** The codebook forms at E4M3 scales --
-`w4nl64a8h`, `w4nl32a8h`, `w5nl64a8h` -- share the rotated input, the scale views and the
+**The form is chosen per projection and per layer.** The codebook forms at E4M3 scales
+(`w4nl64a8h`, `w4nl32a8h`, `w5nl64a8h`) share the rotated input, the scale views and the
 accumulators and differ only in the GEMM's dtype, so a recipe may put any projection of any layer
-in any of them, and the MoE block takes each layer's two from that layer's own experts.
+in any of them, and the MoE block reads each layer's two forms from that layer's experts.
 
-## Rotation alone is expected to be worse
+## Rotation without GPTQ
 
-A rotation fixes **range**, and a group-128 absmax already handles range. Measured on the 27B,
-Hadamard was **2x worse** for RTN int4, and e4m3 activations went 0.02024 -> 0.02254 KL under one.
-The rotation is here because it is the substrate an error-feedback packer needs underneath it --
-the pair is what gets measured, not this half: a recipe asks for `transform=fwht128` together with
-`gptq`, not on its own.
+A rotation fixes range, and a group-128 absmax already handles range. On the 27B, Hadamard was 2x
+worse for RTN int4, and e4m3 activations went 0.02024 -> 0.02254 KL under one. The rotation is here
+as the basis an error-feedback packer quantises in, so a recipe asks for `transform=fwht128`
+together with `gptq`, not on its own.
 
-## Calibration, and why it is a separate run
+## Calibration
 
-GPTQ needs `H = sum over tokens of x x^T` for the layer's real input. That needs the model
-**running**, and a container has to be written before it can be served. So the order is a
-bootstrap:
+GPTQ needs `H = sum over tokens of x x^T` for the layer's real input, which needs the model
+running, and a container must exist before it can be served. One route is a bootstrap:
 
-1. **convert with plain absmax** -- the experts quantised by `rtn`
-2. **serve that** with `RADIANCE_CALIB_DIR` set, and push a corpus through prefill
-3. **convert again**, the experts quantised by `gptq calib=`
+1. **convert with plain absmax**: the experts quantised by `rtn`;
+2. **serve that** with `RADIANCE_CALIB_DIR` set, and push a corpus through prefill;
+3. **convert again**, the experts quantised by `gptq calib=`.
 
-The production recipe takes the second route below instead: its Grams are recorded from the bf16
-checkpoint.
+A second moment is robust to the small perturbation the first container's error puts on the
+activation, which is what makes step 2 valid.
 
-A second moment is robust to the small perturbation the first container's own error puts on the
-activation, which is what makes step 2 legitimate.
+**The production recipe calibrates the checkpoint as it ships instead.** Converted without a
+recipe, Flash-Next is a 335 GiB bf16 container, which `--weights-disk-tier` serves on two cards by
+reading each routed layer's non-resident experts from the container per pass (GUIDE.md §4.3). Its
+tap reads the bf16 activation with no upstream layer quantised and writes Hessians in the model's
+own domain, which a rotated recipe's GPTQ rotates into its own; experts are whole per rank. A step
+reads about 100 GiB per rank from the drive and grows slowly with what it carries (50 s at ~32K
+tokens, 59 s at ~55K), so use large prefill steps: `--max-num-batched-tokens 65536
+--max-num-seqs 64`, about 96 requests in flight, and a KV pool that holds 64 sequences' recurrent
+state. That records ~930 tokens per second, ten million tokens in three hours.
 
-**Or calibrate the checkpoint as it ships, with no bootstrap at all.** Converted without a recipe,
-Flash-Next is a 335 GiB bf16 container, and `--weights-disk-tier` serves it at two cards by reading
-each routed layer's non-resident experts from the container a pass at a time (GUIDE.md §4.3). Its
-tap reads the bf16 activation the bf16 experts multiply -- no upstream layer quantised -- and writes
-its Hessians in the model's own domain; a rotated recipe's GPTQ reads them rotated into its own.
-Whole experts per rank, which a calibration run wants anyway. A step reads about 100 GiB a rank from
-the drive and grows only slowly with what it carries -- 50 s at ~32K tokens, 59 s at ~55K -- so
-drive it with large prefill steps: `--max-num-batched-tokens 65536 --max-num-seqs 64`, about 96
-requests in flight, with a KV pool that holds 64 sequences' recurrent state. That records ~930 tokens a second, ten million tokens in three hours.
+**The corpus must look like the traffic.** A few thousand tokens of one repeated sentence gives a
+Gram with its energy in a handful of directions, and GPTQ hides its error in the directions the
+corpus never excites. Score on Hessians from a held-out slice of the corpus, never on the ones the
+weight was fitted to.
 
-**The corpus is what the Hessian is of, so it has to look like the traffic.** A few thousand
-tokens of one repeated sentence gives a Gram whose energy sits in a handful of directions, and GPTQ
-then hides its error in the directions the corpus never excites -- an in-sample number that says
-nothing. Score on Hessians from a held-out slice of the corpus, never on the ones the weight was
-fitted to.
-
-**A million tokens is enough for the tap's Hessians; the held-out slice wants more.** The tap pools
-a layer's Gram over every expert, and on Flash-Next one recorded from 10M tokens beat one from 1M by
-under 1% on 1.8M held-out tokens (GPTQ on gate_up, layers 0-47), with no change on down or under
-AutoRound. What the larger corpus does fix is the scoring: the gap between in-sample and held-out
-error drops from up to 3% to under 1% on gate_up, and a 113K-token held-out slice put layer 47's
-down GPTQ at 0.49x RTN where 1.8M tokens say 0.60x.
+**A million tokens is enough for the tap's Hessians; scoring wants more.** On Flash-Next a pooled
+Gram from 10M tokens beat one from 1M by under 1% on 1.8M held-out tokens (GPTQ on gate_up, layers
+0-47), with no change on down or under AutoRound. The larger held-out slice matters for scoring:
+the in-sample/held-out gap drops from up to 3% to under 1% on gate_up, and a 113K-token slice put
+layer 47's down GPTQ at 0.49x RTN where 1.8M tokens say 0.60x.
 
 ```sh
 # 1. the uncalibrated container: the recipe's expert rule is rtn, int4 g128 rotated
@@ -276,124 +265,122 @@ CALIB= rad-convert  -o model-gptq.rad \
     --quant 'blk.*.ffn_*_exps.*.weight=gptq:codes=i4,group=128,scale=bf16,transform=fwht128,calib=$CALIB'
 ```
 
-`--reuse` in step 3 copies every weight whose encoding, quantiser and options did not change -- all
-but the experts -- from the first container. **The format is a property of the container**: each
+`--reuse` in step 3 copies every weight whose encoding, quantiser and options did not change (all
+but the experts) from the first container. **The format is a property of the container**: each
 expert's encoding is in its entry, the plugin reads it from there, and the recipe that made it is
-in the header (`rad-info --recipe`), `calib=` included, so a reader can tell an error-feedback
-plane from a plain absmax one.
+in the header (`rad-info --recipe`), `calib=` included, so an error-feedback plane can be told from
+a plain absmax one.
 
-The files are `gram.r..bin`: a 32-byte `RADGRAM2` header (`k`, `rank`, `rows`, `domain`)
-then `k*k` f32. `domain` is what the tap summed: 0 for the model's own activation, 128 for the
-rotated one a `w4a8h` container's kernel multiplies; libquant brings every file into the domain the
-recipe's grid quantises in before summing them, so a bf16 model's Hessians serve a rotated recipe.
-**Named after the weight they will pack, minus the expert index**, because that is
-the whole protocol between the engine and the quantiser -- `gptq` is given a directory and a weight
-name, and strips `..weight` to find its file. A name of the tap's own
-would have made the quantiser carry a per-architecture table.
+The files are `gram.r..bin`: a 32-byte `RADGRAM2` header (`k`, `rank`, `rows`,
+`domain`), then `k*k` f32. `domain` is what the tap summed: 0 for the model's own activation, 128
+for the rotated one a `w4a8h` container's kernel multiplies. libquant brings every file into the
+domain the recipe's grid quantises in before summing, so a bf16 model's Hessians serve a rotated
+recipe. **Files are named after the weight they will pack, minus the expert index**: that is the
+whole protocol between the engine and the quantiser. `gptq` is given a directory and a weight name
+and strips `..weight` to find its file, so it needs no per-architecture table.
 
-**`down` gets a Hessian an expert.** A routed expert's `down` input is its own intermediate units,
-so channel `i` of one expert has nothing to do with channel `i` of another, and a Gram pooled over a
-layer's experts describes none of them: on Flash-Next a typical expert's own profile has a median
-cosine of 0.15-0.87 with the pool, and in the last layers the pool *is* one expert. The tap also
-sums each local expert's rows into its own Gram -- the same `gram_accum` once an expert over its run
-of the sorted rows, into a layer-sized scratch that comes back to the host every pass (640^2 f32 for
-256 experts a rank is 10 GB a rank as packed triangles) -- and writes
-`gram.r.blk.L.ffn_down_exps..bin` beside the pooled file. libquant reads an expert's own
-file when it holds at least 4K rows and the layer's otherwise. Fitted to its own Gram, a Flash-Next
-expert's down projection comes out 20-55% below round-to-nearest on its own held-out Gram, where the
-pooled Gram bought 0-10%; the super experts gain most (layer 47's expert 399: 0.204 rounded, 0.137
-pooled, 0.065 own). Under ~2K rows the own fit fits its rows and can lose to rounding, which is why
-the threshold: below it sit 0.6% of the routed rows. The per-layer sync it costs roughly
-halves a disk-tier recording's throughput, which is why the per-expert sets are recorded from a
-million tokens.
+**`down` gets a Hessian per expert.** A routed expert's `down` input is its own intermediate units,
+so channel `i` means something different in each expert and a Gram pooled over the layer describes
+none of them: on Flash-Next a typical expert's own profile has a median cosine of 0.15-0.87 with
+the pool, and in the last layers the pool is one expert. The tap also sums each local expert's rows
+into its own Gram (`gram_accum` once per expert over its run of the sorted rows, into a
+layer-sized scratch copied to the host every pass; 640^2 f32 for 256 experts per rank is 10 GB per
+rank over 48 layers as packed triangles) and writes `gram.r.blk.L.ffn_down_exps..bin`
+beside the pooled file. libquant reads an expert's own file when the ranks' files together hold at
+least 4 x K rows (2560 for a 640-wide `down`), and the layer's otherwise, saying so on stderr.
+Fitted to its own Gram, a Flash-Next expert's down projection comes out 20-55% below
+round-to-nearest on its own held-out Gram, where the pooled Gram bought 0-10%; super experts gain
+most (layer 47's expert 399: 0.204 rounded, 0.137 pooled, 0.065 own). Under ~2K rows the own fit
+overfits and can lose to rounding, hence the threshold; 0.6% of the routed rows fall below it. The
+per-layer sync roughly halves a disk-tier recording's throughput, so the per-expert sets are
+recorded from a million tokens.
 
-Three things about the tap worth knowing before reading its numbers:
+About the tap's numbers:
 
-- **The gate_up tap is the unsorted activation and loses nothing.** Every token is routed to
-  exactly `top_k` experts, so the gathered distribution IS the token distribution times `top_k`,
-  and GPTQ is invariant to a positive scale on H. `top_k` times cheaper for the same matrix.
-- **It taps the quantiser's output, not the bf16 before it.** The Hessian wanted is of the operand
-  the expert GEMM actually contracts -- and under `w4a8h` that is the only form the activation has.
-- **Per rank, and the quantiser sums.** Under expert parallelism a rank's `down` input is only the
-  tokens routed to its own experts. Its gate_up input is the whole token set on every rank, so
-  summing those double-counts by `world` -- a positive scale, harmless. One rule beats two.
+- **The gate_up tap is the unsorted activation and loses nothing.** Every token is routed to exactly
+  `top_k` experts, so the gathered distribution is the token distribution times `top_k`, and GPTQ is
+  invariant to a positive scale on H. It is `top_k` times cheaper for the same matrix.
+- **It taps the quantiser's output, not the bf16 before it**, because the Hessian wanted is of the
+  operand the expert GEMM contracts; under `w4a8h` that is the only form the activation has.
+- **Files are per rank, and the quantiser sums them.** Under expert parallelism a rank's `down`
+  input is only the tokens routed to its own experts. Its gate_up input is the whole token set on
+  every rank, so summing double-counts by `world`, a positive scale that does not matter.
 
 ## Protected experts
 
 **A few experts carry a large share of a layer's output, and those are kept plain bf16.** In
 Flash-Next's last layers one expert's `down` input holds a sixth of the layer's energy from a third
 of a percent of its routing, nearly all of it in one channel (layer 47, expert 445). Four bits cost
-it the same *relative* error as any expert -- about 12% of its output under its own profile -- but its
+it the same relative error as any expert (about 12% of its output under its own profile), but its
 output is that much larger, so the absolute error is too. unsloth's GGUFs upcast the whole layer's
 `down` for this (a GGUF type is per tensor, and a tensor is all 512 experts); a container keeps an
-expert's encoding per expert, so here only those experts are kept, at ~7 MB each.
+encoding per expert, so here only those experts are kept, at about 7 MB each over their four-bit
+size.
 
-A recipe names them with a rule ahead of the expert rule, `blk.47.ffn_*_exps.445.weight cast
-dtype=bf16`, and the layer serves them apart: the sort places them last (`moe_scatter`'s `protect`),
-the four-bit GEMMs serve the other experts, and a bf16 `moe_gemm` pair serves the trailing run of the
-offsets, writing the routed rows the four-bit `down` GEMM left zero. Their weights are the layer's
-static weights, not expert slots -- a container's experts in a layer are one fixed-size unit each --
-so they are always resident and the file tier never reads them. Where every rank holds a slice of
-every expert, it holds an even slice of these too -- 320 of the 640 intermediate units at two ranks,
-since a bf16 expert has no scale blocks to respect -- and the block's all-reduce sums the partials.
-The count must keep the rest even, because the four-bit GEMM takes them as two equal tables by parity.
+A recipe names them with a rule ahead of the expert rule,
+`blk.47.ffn_*_exps.445.weight cast dtype=bf16`, and the layer serves them apart: the sort places
+them last (`moe_scatter`'s `protect`), the four-bit GEMMs serve the other experts, and a bf16
+`moe_gemm` pair serves the trailing run of the offsets, writing the routed rows the four-bit `down`
+GEMM left zero. Their weights are the layer's static weights, not expert slots (a container's
+experts in a layer are one fixed-size unit each), so they are always resident and the file tier
+never reads them. Where every rank holds a slice of every expert it holds an even slice of these
+too (320 of the 640 intermediate units at two ranks; a bf16 expert has no scale blocks to respect),
+and the block's all-reduce sums the partials. The count must leave the rest even, because the
+four-bit GEMM takes them as two equal tables by parity.
 
 ## The quantiser
 
-`gptq` in libquant (`libquant/lq_gptq.{h,cpp}`), over any grid `rtn` takes. H is damped by 1% of its mean diagonal, inverted, and re-factorised
-into the upper triangle `U` with `U^T U = H^-1`; then columns are quantised left to right and each
-column's rounding error is pushed into the columns to its right, weighted by `U`. Blocked 128
-columns at a time so `U` is streamed once rather than once per row, and parallel over rows because
-the recursion is independent in the row index.
+`gptq` in libquant (`libquant/lq_gptq.{h,cpp}`), over any grid `rtn` takes. H is damped by 1% of its
+mean diagonal, inverted, and re-factorised into the upper triangle `U` with `U^T U = H^-1`; columns
+are then quantised left to right and each column's rounding error is pushed into the columns to
+its right, weighted by `U`. It works in blocks of 128 columns so `U` is streamed once rather than
+once per row, and in parallel over rows, since the recursion is independent in the row index.
 
-**The scale grid is fixed from the weight before any code is chosen** -- the "static groups"
-variant. The scales are then exactly the ones `rtn` writes for the same weight, which
-`tests/relayout_parity_test.cpp` checks, and the grid does not depend on the order the columns are
-visited in.
+**The scale grid is fixed from the weight before any code is chosen** (the "static groups"
+variant). The scales are then exactly the ones `rtn` writes for the same weight, which
+`tests/relayout_parity_test.cpp` checks, and the grid does not depend on column order.
 
 **Cost.** Budget tens of minutes of extra convert time for a 48-layer container, and ~1.3 GB of
-factor cache held for its duration. The quantiser is OpenMP-parallel over rows, so the wall time
-falls with core count; the cache is a property of the model, not of the machine. The factorisation
-is per layer and projection, not per expert: 512 experts share one factor.
+factor cache for its duration. The quantiser is OpenMP-parallel over rows, so wall time falls with
+core count. A layer's pooled factor is shared by all 512 experts of that projection; a `down`
+projection fitted to its own Gram factors per expert, in parallel and uncached.
 
-**A weight with no calibration file is packed the uncalibrated way and says so on stderr** -- so a
-typo'd directory is a message, not a silent quality regression.
+**A weight with no calibration file is packed the uncalibrated way and says so on stderr**, so a
+mistyped directory is a message, not a silent quality loss.
 
-## What is measured
+## Tests
 
-- `r4d_selftest --case moe_gemm_w4a8` -- the kernel against an independent host decode of the same
+- `r4d_selftest --case moe_gemm_w4a8`: the kernel against an independent host decode of the same
   planes, both M bands, through the relayout the loader runs.
-- `r4d_selftest --case moe_gemm_w4a8_mod4` -- the four-class op against the two-class one byte for
+- `r4d_selftest --case moe_gemm_w4a8_mod4`: the four-class op against the two-class one byte for
   byte, and against a host decode with every class at its own geometry and one of classes 1 to 3
   the only wide one, as ranks 1 to 3 of four hold them; `--case moe_gemm_fp8a8_mod4` is the same
   host decode at block fp8.
-- `quant_test` -- **GPTQ against the objective it minimises**. The metric is
-  `||X (W - W')^T||^2 = sum over rows of e H e^T` and *not* rel_l2 on the weight: error feedback
-  makes the weight worse in the plain sense, deliberately. The control is no Hessian at all, under
-  which `gptq` must produce `rtn`'s planes **byte for byte**.
-- `r4d_selftest --case had_quant_act_fp8` -- every format against the exact f32 dot product,
-  which is the only way to see whether the quantiser's `fwht_inplace` and the device's
-  `r4d_fwht_wave` are the same transform, and whether the kernel decodes the `w4nl` codes as their
-  table entries. 0.2015 (`w4a8`), 0.1307 (`w4a8h`), 0.0991 (`w4nla8h`, round to nearest at
-  amax / 22), 0.0761 (`w4nl64a8h`), 0.0625 (`w4nl32a8h`) and 0.0469 (`w5nl64a8h`) on a source
-  with outlier channels; the negative control (rotate the activation, not the weight) measures
-  5.32.
-- `relayout_parity_test` -- the `w4nla8h` plane's stored bytes pinned, its inverse giving back the
+- `quant_test`: **GPTQ against the objective it minimises**, `||X (W - W')^T||^2 = sum over rows of
+  e H e^T`, not rel_l2 on the weight (error feedback deliberately makes the weight worse in the
+  plain sense). The control is no Hessian at all, under which `gptq` must produce `rtn`'s planes
+  byte for byte.
+- `r4d_selftest --case had_quant_act_fp8`: every format against the exact f32 dot product, the only
+  way to see whether the quantiser's `fwht_inplace` and the device's `r4d_fwht_wave` are the same
+  transform, and whether the kernel decodes `w4nl` codes as their table entries. On a source with
+  outlier channels: 0.2015 (`w4a8`), 0.1307 (`w4a8h`), 0.0991 (`w4nla8h`, round to nearest at
+  amax / 22), 0.0761 (`w4nl64a8h`), 0.0625 (`w4nl32a8h`) and 0.0469 (`w5nl64a8h`); the negative
+  control (rotate the activation, not the weight) measures 5.32.
+- `relayout_parity_test`: the `w4nla8h` plane's stored bytes pinned, its inverse giving back the
   codes and the table, and a container quantised against another sixteen-entry table refused at
   relayout; the same for `w4nl64a8h`, `w4nl32a8h` and `w5nl64a8h`, with a second level other than
   2^-13 refused, a 32-entry table other than `w5nl` refused, and each refusing the others'
-  encodings. `r4d_selftest --case moe_gemm_w4a8` also checks `w5nl64a8h`'s arranged row bit for
-  bit against the statement in r4d_layout.cpp, and its inverse. `moe_gemm_q_mod4`'s four classes
-  are held to `moe_gemm_q`'s stored bytes in every format, and for both ops what the op oracle
-  reads through the inverse -- codes as their levels, an E4M3 scale times its second level -- is
-  held to the quantiser's planes.
-- `r4d_selftest --case gram_accum` -- the accumulator against an f64 host Gram, **launched twice
-  over a seeded buffer**, because a kernel that stored instead of adding would agree with any
+  encodings. `r4d_selftest --case moe_gemm_w4a8` also checks `w5nl64a8h`'s arranged row bit for bit
+  against the statement in `r4d_layout.cpp`, and its inverse. `moe_gemm_q_mod4`'s four classes are
+  held to `moe_gemm_q`'s stored bytes in every format, and for both ops what the op oracle reads
+  through the inverse (codes as their levels, an E4M3 scale times its second level) is held to the
+  quantiser's planes.
+- `r4d_selftest --case gram_accum`: the accumulator against an f64 host Gram, **launched twice over
+  a seeded buffer**, because a kernel that stored instead of adding would agree with any
   single-call oracle.
 
-**The end-to-end quality of a container against the bf16 model** is the engine's KL mode
-([TOOLS.md](TOOLS.md#the-kl-mode)): the full-vocabulary KL at every position of a fixed corpus,
-its mean and its tail percentiles, and the top-1 agreement. It needs the **full 48-layer
-container**: the 4-layer bring-up slice cannot resolve a difference this small -- its residual
-probe reads the same to within 1% for fp8, `w4a8`, `w4a8h` and GPTQ alike, which says only that
-all four compute the same function.
+**End-to-end quality against the bf16 model** is the engine's KL mode
+([TOOLS.md](TOOLS.md#the-kl-mode)): the full-vocabulary KL at every position of a fixed corpus, its
+mean and tail percentiles, and the top-1 agreement. It needs the **full 48-layer container**: the
+4-layer bring-up slice cannot resolve a difference this small (its residual probe reads the same to
+within 1% for fp8, `w4a8`, `w4a8h` and GPTQ alike).
diff --git a/docs/OPS.md b/docs/OPS.md
index a8f2829f..0a53e0c0 100644
--- a/docs/OPS.md
+++ b/docs/OPS.md
@@ -1,159 +1,182 @@
 # The conventional op vocabulary
 
-Op names are free strings (`spec.md` §2.3) and the core never learns one. But `libref`
-cannot implement an op it has never heard of, so **ref's op list is the conventional vocabulary**:
-an architecture plugin that stays inside it is guaranteed to run somewhere, and one that invents
-an op has no fallback for it (`spec.md` §17).
+Op names are free strings (`spec.md` §2.3) and the core never interprets one. `libref` can only
+implement ops it knows, so its op list is the conventional vocabulary: an architecture plugin that
+stays inside it can run somewhere, and an op outside it has no fallback (`spec.md` §17).
 
-This file is that list. `libref/` holds the authoritative `RadOpSchema` rows; this is what
-they say, in a form an architecture plugin author reads first.
+This file describes that vocabulary for architecture and kernel plugin authors. The schemas
+themselves are the `RadOpSchema` rows the kernel plugins declare (`libref/` for every op it
+implements, `libr4d/r4d_rows.cpp` for the rest).
 
-**AND IT IS CHECKED.** `tests/CMakeLists.txt` registers `ops_doc`, which dumps every plugin's
-schemas with `rad-schemas` and holds every table row below to them — op for op, parameter for
-parameter, operand for operand, including the optional markers and the `w` that makes an operand a
-weight. Run it by hand as:
+The tables are machine-checked. `tests/CMakeLists.txt` registers `ops_doc`, which dumps every
+plugin's schemas with `rad-schemas` and compares each table row with them: op, parameters,
+operands, optional markers and weight markers. By hand:
 
     tools/ops_doc_check.sh docs/OPS.md build/bin/rad-schemas build/radiance_home/kernels/*.so
 
-A row that is a PROPOSAL rather than a description carries a FOURTH COLUMN saying so and is exempt
-from the check. That is how an op the vocabulary has agreed on but no plugin declares yet stays in
-this document without being a lie, and it is the only way one may.
+A row with a fourth column is a proposal, not a description, and is exempt from the check. This is
+the only way an op no plugin declares yet may appear here.
 
-An op that a kernel library serves and this document omits gets written against a GUESS at its
-schema, and no fallback absorbs a wrong guess — `qk_norm_rope_gate` and `qk_norm_rope` differ in
-exactly the way a guess gets wrong, one taking a `theta` and the other a precomputed cos/sin table.
-**A document that is WRONG is worse than one that is missing**, because it is read instead of the
-source.
+Write against this document, not a guess: `qk_norm_rope_gate` and `qk_norm_rope` differ
+where a guess goes wrong (one takes a precomputed cos/sin table, the other `theta`).
 
-**A ROW HERE DOES NOT MEAN THERE IS A HOST KERNEL.** A table marked **device-only** is declared by
-libr4d and by nothing else, so its ops have no oracle for `rad-kbench` and no host fallback: an
-architecture that reaches for one is choosing to run on this library or not at all. That is a
-legitimate choice — every fusion in this document is one — but it is a choice, and it should be
-made knowingly.
+A table or op marked **device-only** is declared by libr4d alone. It has no host fallback and no
+oracle for `rad-kbench`, so an architecture that uses it runs on libr4d or not at all. Every fusion
+here is such a choice.
 
 ## Conventions
 
-- Operands are **positional**, in the order given. `w` marks a weight operand, `→` the outputs.
-- A tensor's leading dimension is tokens unless stated. Everything is contiguous unless an op
-  says otherwise; strides are the kernel's business, not the schema's.
-- `dtype` is always present and always a string. It names the **operand combination**, which is
-  why a weight format and an activation format share one key: `bf16`, `f16`/`fp16`, `f32`/`fp32`,
-  `fp8_e4m3`, `fp8a8`, `fp8a16`, `w4`, `w4a8`, `w4a8_asym`, `w4a8h`, `w8a8`, `w4a16`, `w8a16`,
-  `w2a8`, `mxfp4a8`, `w5a16`, `w4a16_asym`, `w5a8i8`, `w4a8i8_asym`. `w4a8h` is `w4a8` with a
-  `group`-wide Walsh–Hadamard along K baked into the stored weight (`docs/MOE-W4.md`), `w4a8_asym`
-  the unsigned-nibble-minus-zero-point grid rather than the symmetric one, and `fp8a8`/`fp8a16` say
-  whether a block-scaled E4M3 weight is met by an fp8 activation or a bf16 one. `w5a16` and
-  `w4a16_asym` are ParoQuant's int5 and z-lab's int4 (u5 / u4 codes, an f16 scale and a u8 zero
-  point a 128 of K) against an f16 activation, and `w5a8i8` / `w4a8i8_asym` the same weights
-  against an int8 one with an f32 scale per (row, 128 of K). `q_dtype` and `kv_dtype` are the same key split in two where
-  attention reads two formats at once.
-- `M` is the ranged parameter wherever a token count appears. **At most one ranged parameter per
-  op** — that is what keeps `rad_issue` a single integer on the hot path.
-- Every op below returns `RAD_OK` or a negative `RAD_E_*`. There is no partial success.
-- In a row, `?` marks an optional operand, `/opt` an optional parameter and `/der` a derived one,
-  and none of the three is decoration: `/der` says the KERNEL supplies the value rather than the
-  caller, an omitted optional parameter is one a kernel will ignore when a caller passes it, and a
-  constraint on an `:f64` key never matches, because a tolerance is not a predicate.
+- Operands are positional, in the order given. `→` separates inputs from outputs.
+- `w` marks a weight operand and `wt` a weight table (see
+  [Weight operands and weight tables](#weight-operands-and-weight-tables));
+  `:inout` an operand that is read and written; `?` an optional operand.
+- `/opt` marks an optional parameter (a kernel that does not read it ignores it), `/der` a derived
+  one ([Parameters the kernel supplies](#parameters-the-kernel-supplies)), `:f64` a float
+  parameter and `:str` a string one where the name does not make it obvious.
+- `(range)` marks the parameter callers declare as a range (`RAD_RANGE`); it is `M` wherever a token
+  count appears. At most one parameter per op is ranged, which keeps `rad_issue` to a single
+  integer on the hot path.
+- A tensor's leading dimension is tokens unless stated. Everything is contiguous unless an op says
+  otherwise; strides are the kernel's business, not the schema's.
+- Where an op takes `dtype`, it is a string naming the operand combination, so a weight format and
+  an activation format share one key: `bf16`, `f16`/`fp16`, `f32`/`fp32`, `u8`, `fp8_e4m3`,
+  `fp8a8`, `fp8a16`, `i8a8`, `w4`, `w4a8`, `w4a8_asym`, `w4a8h`, `w8a8`, `w4a16`, `w8a16`, `w2a8`,
+  `mxfp4a8`, `w5a16`, `w4a16_asym`, `w5a8i8`, `w4a8i8_asym`, and the codebook expert forms
+  `w4nla8h`, `w4nl64a8h`, `w4nl32a8h`, `w5nl64a8h` (`docs/MOE-W4.md`).
+  - `w4a8h` is `w4a8` with a `group`-wide Walsh–Hadamard along K baked into the stored weight
+    (`docs/MOE-W4.md`).
+  - `w4a8_asym` is the unsigned-nibble-minus-zero-point grid instead of the symmetric one.
+  - `fp8a8` and `fp8a16` say whether a block-scaled E4M3 weight meets an fp8 or a bf16 activation.
+  - `w5a16` and `w4a16_asym` are ParoQuant's int5 and z-lab's int4 (u5 / u4 codes, an f16 scale and
+    a u8 zero point per 128 of K) against an f16 activation; `w5a8i8` and `w4a8i8_asym` are the same
+    weights against an int8 activation with an f32 scale per (row, 128 of K).
+  - `q_dtype` and `kv_dtype` are the same key split in two where attention reads two formats.
+- Every op returns `RAD_OK` or a negative `RAD_E_*`. There is no partial success.
+- **Zero rows is not a call.** An op issued over zero rows (zero along its ranged extent, or a
+  `cu_seqlens` whose sequences are all empty) returns `RAD_E_SHAPE` and writes nothing. A caller
+  with nothing to compute skips the issue, as the architectures' decode and prefill halves do.
+  libref holds every op to this, so a host run names an unguarded issue.
+- An implementation refuses what it cannot compute: an operand dtype it does not read
+  (`RAD_E_DTYPE`) or an optional operand it does not implement (`RAD_E_UNSUPPORTED`). Returning
+  `RAD_OK` with the answer to a different function is the one wrong response.
+- libref accumulates in f32 (`libref/ref_common.h`). Its double-precision sums are part of the
+  op's reference: `seg_mean`, `gram_accum`, `logit_rerank`, the normaliser of `sample_logprobs`,
+  `givens_dense_quant`'s rotation, `ple_gate`'s dot, and the sums of squares of the norms in
+  `hc_read`, `mtp_enter`, `ple_gate` and `qsa_block_key`.
 
 ## How a schema is written
 
-`libref` and `libr4d` implement the same ops from opposite ends, and a schema they do not agree on
-cannot be loaded at all — the loader refuses the whole plugin on any one conflict, which makes
-every other row of it unreachable and `rad-kbench` unrunnable. Four rules settle every case, and
-they are why `gdn_conv_prep` and `gdn_recurrent_update` carry the long operand lists they do.
+`libref` and `libr4d` implement the same ops, and a schema they disagree on cannot be loaded: the
+loader refuses the whole plugin on any one conflict, which makes all its other rows unreachable
+and `rad-kbench` unrunnable. Four rules settle every case; they are why `gdn_conv_prep` and
+`gdn_recurrent_update` carry long operand lists.
 
-### The four rules that resolve every case
+### The four rules
 
-1. **Operands are the UNION, and anything only one implementation needs is `optional`.** A schema
-   that lacks an operand cannot express the call at all, so the narrower reading always loses. An
-   implementation ignores an optional operand it does not use; it cannot invent one it needs.
-2. **Parameters are the UNION, and anything only one implementation needs is `optional`.** Same
-   argument. A constraint on an absent key simply does not hold, which is the correct answer: a
-   row that needs a parameter the caller did not state is not a match.
-3. **A float-valued parameter is `RAD_P_F64`.** `eps`, `scale`, `theta`, `softplus_thr`, `l2_eps`,
-   `wadd`. A `"%.9g"` string round-trips an IEEE single exactly and is unreadable in a graph dump,
-   which is the whole of the argument against spelling them as strings. **Constraints never match
-   on a float** — a tolerance is not a predicate, and a kernel that cares about `eps` to that
-   precision has a bug.
+1. **Operands are the union**, and an operand only one implementation needs is optional. A schema
+   that lacks an operand cannot express the call at all. An implementation ignores an optional
+   operand it does not use; it cannot invent one it needs.
+2. **Parameters are the union**, and a parameter only one implementation needs is optional. A
+   constraint on an absent key does not hold, so a row that needs a parameter the caller did not
+   state does not match.
+3. **A float-valued parameter is `RAD_P_F64`**: `eps`, `scale`, `theta`, `softplus_thr`, `l2_eps`,
+   `wadd`. A `"%.9g"` string would round-trip an IEEE single but is unreadable in a graph dump.
+   Constraints never match on a float: a tolerance is not a predicate, and a kernel that depends on
+   `eps` to that precision has a bug.
 4. **An enumerated parameter is `RAD_P_STR` with named values.** `act` is `"silu"` or `"sigmoid"`,
-   not `0` or `1`. A graph dump reading `act=1` is precisely the "unclear what actually runs"
-   complaint this engine exists to answer; a plugin's launch adapter maps the name to whatever
-   integer its kernel wants.
+   not `0` or `1`, so a graph dump says what runs. A plugin's launch adapter maps the name to
+   whatever integer its kernel wants.
 
-The union rule has exactly two deliberate exceptions, both on the gated delta net and both argued
-where those ops are described: `cu` and `num_accepted` are REQUIRED, because an op that lets the
-caller omit either is an op whose contract is optional.
+The union rule has two deliberate exceptions, both on the gated delta net: `cu` and `num_accepted`
+are required ([Linear attention](#linear-attention-gated-delta-net)).
 
 ### Parameters the kernel supplies
 
 `attn_paged.block_size`, `gdn_chunk_scan.chunk`, `gdn_kkt_solve.chunk` and `gdn_conv_prep.chunk`
-are supplied by the **kernel**, not the caller (`spec.md` §7.2, and `RAD_DERIVED` in `rad_abi.h`).
-Constraints on them are skipped during matching and the winning kernel's `RAD_C_EQ` value is
-written into the resolved geometry afterwards. Declaring them `RAD_REQUIRED` makes them
-unselectable: a constraint whose key the geometry lacks does not hold, so a kernel compiled for
-`block_size == 16` could never be reached by the query whose answer was to be read off it.
+(and the `block_size` of `attn_paged_qrow` and `attn_prefix_self`) are supplied by the kernel, not
+the caller (`spec.md` §7.2, `RAD_DERIVED` in `rad_abi.h`). Constraints on them are skipped during
+matching, and the winning kernel's `RAD_C_EQ` value is written into the resolved geometry
+afterwards. Declared `RAD_REQUIRED` they would be unselectable: a kernel compiled for
+`block_size == 16` could never match the query whose answer is to be read off it.
 
-`gdn_conv_prep.chunk` has a cost the other three do not: nothing in conv_prep's operands carries
-the chunk length, so `libref`, which declares no `RAD_C_EQ` to answer with, returns `RAD_E_SHAPE`
-by name when a caller omits it rather than quietly treating the whole sequence as one chunk.
-libr4d supplies 64.
+Nothing in `gdn_conv_prep`'s operands carries the chunk length, so `libref`, which has no
+`RAD_C_EQ` to supply it, returns `RAD_E_SHAPE` when a caller omits `chunk` rather than treating the
+whole sequence as one chunk. libr4d supplies 64.
 
-`all_reduce.hops` is `RAD_OPTIONAL` — a one-shot/two-shot distinction the caller may state and
-usually should not. `all_reduce.exact` stays `RAD_REQUIRED`: a caller that does not say it will
-accept a lossy wire gets no kernel rather than the quantised one.
+`all_reduce.hops` is optional: a one-shot/two-shot preference the caller may state and usually
+should not. `all_reduce.exact` is required: a caller that does not accept a lossy wire must get no
+kernel rather than the quantised one.
 
-### Weight operands, and the weight TABLE
+### Weight operands and weight tables
 
-- **`RAD_OPD_WEIGHT`** — the issue names one weight handle, and the kernel receives that weight's
-  bytes, its dtype and its declared shape.
-- **`RAD_OPD_WTAB`** — the issue names the FIRST handle of a run and the run's length, and the
-  kernel receives a device array of `n` pointers, one per entry.
+- **`RAD_OPD_WEIGHT`** (`w`): the issue names one weight handle, and the kernel receives that
+  weight's bytes, dtype and declared shape.
+- **`RAD_OPD_WTAB`** (`wt`): the issue names the first handle of a run and the run's length, and
+  the kernel receives a device array of pointers, one per entry. `RAD_WTAB(h, n)` in
+  `abi/rad_runtime.h` is the issue-side spelling; `rad_decl_weight` hands out consecutive indices,
+  so a declaration loop over experts produces such a run.
 
-`RAD_WTAB(h, n)` in `abi/rad_runtime.h` is the issue-side spelling, and `rad_decl_weight` handing
-out consecutive indices is what makes a declaration loop over experts produce such a run.
+A table, not a base plus a stride, because a layer's experts are separate movement units
+(`spec.md` §4.2): after placement one may be in VRAM, the next streamed over the link and the third
+still on disk. `base + e * stride` describes only the case where nothing was offloaded. The core
+resolves every handle of the run like any weight (residency table, mover event, use note) and
+uploads a pointer array, patching it only when a pointer moves.
 
-**Why it is a table and not a base plus a stride.** A layer's experts are separate movement units
-(`spec.md` §4.1): after placement one is in VRAM, the next is streamed over the link and the third
-is still on disk. `base + e * stride` describes exactly one of those cases — the one where nothing
-was offloaded — and expert offload is the reason the placement engine exists. So the core resolves
-every handle in the run the way it resolves any weight (residency table, mover event, use note) and
-uploads a pointer array, rebuilding it only when a pointer actually moved.
+What the kernel sees: `RadTensor::data` points at the pointer array, `shape[0]` is the entry count
+and `stride[0]` is 0, which marks a table. `dtype` and the trailing extents and strides are one
+entry's, and every entry of a run must agree on them; the core refuses the issue by name if they
+do not. A kernel may also accept the stacked form (an ordinary rank-3 tensor with a real leading
+stride): `rad-kbench` replaying a fixture has nowhere to put a pointer array, and libref and libr4d
+both read either form.
 
-**What the kernel sees.** `RadTensor::data` points at the pointer array; `shape[0]` is the entry
-count and **`stride[0]` is 0**, which is the marker. `dtype` and the trailing extents and strides
-are ONE entry's, and every entry of a run must agree about them — the core refuses the issue by
-name if they do not, because a table whose entries have different shapes is a table the kernel
-cannot walk. A kernel may also accept the STACKED form (an ordinary rank-3 tensor with a real
-leading stride): `rad-kbench` replaying a fixture has nowhere to put a pointer array, and both
-libref and libr4d read either, so a described case runs against the same bytes the engine would
-hand it.
+How the declared weights are divided: after each fixed weight position takes one weight, the rest
+is split evenly across the table positions in declaration order, and where it does not divide the
+first positions take one more each. So `moe_gemm_q_mod4`'s first `n_expert % 4` classes hold one
+expert more than the rest, and their codes and scales are its first table positions. A list too
+short to give every table an entry is refused at declare; a table whose declared run is not
+contiguous is refused when the tables are bound, before the first step; entries that disagree on
+shape, or an issue naming a run other than the declared one, are refused at issue.
 
-**How the declaration divides.** An op may carry several table operands — `moe_gemm_q` has four,
-the codes and the scale planes of its even experts and of its odd ones. Whatever is left after the fixed weight positions have taken one each
-is split EVENLY across the table positions, in declaration order, and where it does not come out
-whole the first positions take one more each: `moe_gemm_q_mod4`'s first `n_expert % 4` classes hold
-one expert more than the rest, and their codes and scales are its first table positions. A list too
-short to give every table an entry is refused at declare. A table whose declared run is not
-contiguous is refused when the tables are bound, before the first step; one whose entries disagree
-about their shape, or an issue naming a run other than the declared one, is refused at issue. That
-is exactly right for the case tables exist for: every table of one MoE op takes one weight per
-expert of its class.
+### Weights of several planes
 
-## What the loader enforces
+A weight may be declared over several planes of one stored tensor (`RadWeightDecl::planes`,
+`spec.md` §4.3) and still be one operand: an fp8 or int8 lm head (codes and scale), Flash-Next's
+E4M3 mixing and fc rows (codes and f32 group scales), a zero-point grid's `b_scale` (scale and
+zero). A device kernel arranges such a weight in its layout hook. A host kernel reads the joined
+form `abi/rad_planes.h` defines: a header naming each plane by role, then the planes as the
+container holds them. libref and libavx join the same selections on the same operands and refuse
+the others with `RAD_E_DTYPE`, so either may serve any band:
 
-**A kernel plugin must declare a `RadOpSchema` for every op it has a `RadKernelInfo` row for.**
-The loader checks this after the whole hierarchy is open — deferred to the end because an override
-plugin may legitimately rely on the schema of the plugin below it — and refuses the load naming the
-plugin and the op. Without the rule, a typo and an unimplemented op are the same diagnostic.
+| op | operand | joined planes |
+|---|---|---|
+| logits_gemm, logit_rerank | `lm_head` / `head` | codes (E4M3 or i8, one a value) and one scale plane (bf16, f16 or f32, any block) |
+| hc_read | `mix_down`, `mix_up` | the same (`mix` e4m3) |
+| mtp_enter | `fc_h`, `fc_e` | the same (`fc` e4m3) |
+| gemm_nt_q | `b_scale` | `scale` (f16) and `zero` (u8, u4 or u5), one each per (row, `group` of K), at the zero-point grids below |
 
-The first plugin in hierarchy order to declare an op **fixes its schema**. A later plugin declaring
-the same op name with a *different* schema is refused at load with both plugins named; declaring it
-identically is fine and is what every plugin implementing a shared op does. Since arguments are
-positional, two disagreeing schemas would make the same call mean different things depending on
-which plugin won selection — silent numerical garbage rather than a diagnosable failure.
+The kernel finds the joined form by its header and its extents from the planes' entries, not the
+operand's declared shape. A joined head or matrix is read element by element as the core's affine
+decoder gives it (`core/format/encoding.h`): the code times the scale covering it, one f32
+rounding, so libref's product over a joined head is bit-identical to its product over that
+decoder's f32 head. A single plane is never joined, and the plain forms (a bf16 head, the logical
+f32 head a tool describes) reach the same ops unchanged. Where a joined `hc_read` or `mtp_enter`
+matrix rounds a gate, it rounds to `h`'s dtype, as a plain matrix rounds to its own.
 
-`build/bin/rad-schemas a.so b.so` prints and diffs what plugins actually declare. Run it before
-adding a kernel plugin; "refused at load" names one op and leaves you to find the rest.
+## Loader checks
+
+Every op a kernel row implements must have a schema declared by some loaded plugin. The check runs
+once the whole hierarchy is open, because an override plugin may rely on the schema of a plugin
+below it, and the refusal names the kernel, the plugin and the op. Without it a typo and an
+unimplemented op give the same diagnostic.
+
+The first plugin in hierarchy order to declare an op fixes its schema. A later plugin declaring the
+same op with a different schema (parameter keys, types and requiredness; operand count, roles and
+optionality) is refused at load with both plugins named; an identical declaration is expected.
+Since arguments are positional, two disagreeing schemas would give one call two meanings depending
+on which plugin won selection.
+
+`build/bin/rad-schemas a.so b.so` prints what plugins declare and every disagreement between them
+at once. Run it before adding a kernel plugin; the loader names only the first conflict.
 
 ---
 
@@ -179,10 +202,12 @@ adding a kernel plugin; "refused at load" names one op and leaves you to find th
 | `pool_rows` | `M`(range) `n` `k` `mult`:f64/opt `dtype` | `x` → `y` (one mean row a window of k rows) |
 | `relu` | `M`(range) `n` `dtype` | `x` → `y` |
 | `clamp` | `M`(range) `n` `dtype` | `x`, `lo`w, `hi`w → `y` |
-| `conv2d` | `M`(range) `width` `cin` `cout` `kh` `kw` `stride` `pad` `cu_div`/opt `valid_stride`/opt `dtype` | `x`, `w`w, `cu_seqlens`, `valid`? → `y` |
+| `conv2d` | `M`(range) `width` `cin` `cout` `kh` `kw` `stride` `pad` `cu_div`/opt `valid_stride`/opt `dtype` `t_last`/opt `act`/opt | `x`, `w`w, `cu_seqlens`, `valid`? → `y`; `b`w? |
+| `conv2d_unfold` | `M`(range) `width` `cin` `kh` `kw` `stride` `pad` `cu_div`/opt `valid_stride`/opt `t_last`/opt `dtype` | `x`, `cu_seqlens`, `valid`? → `y` |
 | `conv1d_dw` | `M`(range) `n` `k` `cu_div`/opt `dtype` | `x`, `w`w, `cu_seqlens` → `y` |
 | `rel_sinusoid` | `M`(range) `n` `max_timescale`:f64/opt `dtype` | → `y` |
 | `gelu_mul` | `M`(range) `n` `dtype` | `gate_up` → `y` (splits `[M,2n]` into gelu·up, tanh approx) |
+| `seg_sinusoid` | `M`(range) `n` `period` `max_timescale`:f64/opt `cu_div`/opt `dtype` | `cu_seqlens` → `y` |
 | `gelu` / `silu` | `M`(range) `n` `dtype` | `x` → `y` |
 | `cast` | `M`(range) `n` `from` `to` | `x` → `y` |
 | `softmax` | `M`(range) `n` `dtype` | `x` → `y` |
@@ -192,24 +217,73 @@ adding a kernel plugin; "refused at load" names one op and leaves you to find th
 | `silu` | `M` `n` `dtype` | `x` → `y` |
 | `fill` | `M`(range) `n` `dtype` `value`:f64/opt | → `y` |
 
-`gelu` and `silu` are two ops with one schema, and `silu` carries a row of its own because a row
-names one op.
+`gelu` (exact erf) and `silu` share one schema; `silu` has a row of its own because a row names one
+op.
 
-`rmsnorm_add` exists because the residual add and the next norm are one pass in every real
-implementation. A plugin asks for it first and falls back to `add` + `rmsnorm` (`spec.md` §2.3).
+**`rmsnorm`** is `y = x * rsqrt(mean(x^2) + eps) * (w + wadd)`; `wadd` is GemmaRMSNorm's `1 +`,
+added in f32. `mult` scales the normed row before its one rounding, for a residual branch weighted
+by a constant (Gemma 4's audio feed-forward adds half its output). For a power of two this equals
+norm-then-scale exactly, since scaling by a power of two commutes with rounding.
 
-`rmsnorm_p` is `rmsnorm` with the gain removed: `x * rsqrt(mean(x^2) + eps)` and no `w` at all.
-Gemma's attention normalises the value with a bare RMS (a weightless norm) while normalising the
-key with the `k_norm` gain in the same layer, and there is no checkpoint plane to feed the value
-through a gain -- `rmsnorm` would need a phantom all-zero weight to say the same thing.
+**`rmsnorm_p`** is `rmsnorm` with no gain: `y = x * rsqrt(mean(x^2) + eps)`. Gemma's attention
+normalises the value with a bare RMS while the key takes the `k_norm` gain, and the checkpoint has
+no plane to feed `rmsnorm` as a gain.
 
-`gelu_mul` is `silu_mul` with the tanh GELU instead of silu -- Gemma's gated FFN is trained with
-`gelu_pytorch_tanh`, and gated feed-forwards ask for the tanh form rather than the unary `gelu`'s
-exact erf one. Both split the fused `gate_up` with the gate in the FIRST half.
+**`rmsnorm_add`** is the residual add and the next norm in one pass, as every real implementation
+does it. A plugin asks for it first and falls back to `add` + `rmsnorm` (`spec.md` §2.3).
 
-`hc_read` / `hc_write` are the GATED RESIDUAL pair, which is what a hyper-connection model has
-instead of a pre-norm and a residual add. The stream is `hc` times the model width and every block
-reads a mix of the `hc` sub-streams and writes back into all of them, both gated by data:
+**`gelu_mul`** is `silu_mul` with the tanh GELU: Gemma's gated FFN is trained with
+`gelu_pytorch_tanh`, while the unary `gelu` is the exact erf form. Both split the fused `gate_up`
+with the gate in the first half.
+
+**`add` and `mul`** broadcast a `b` of exactly `n` elements along the rows of a taller output (a
+bias add). Nothing else broadcasts, in these or any other elementwise op.
+
+**`sigmoid`**, with `mul`, gates a shared expert (`ffn_gate_inp_shexp`). Without it the shared
+expert runs ungated, which is a different model.
+
+**`mul_weight`** is a learned gain on an activation: `w` is a weight of one element (a scalar for
+the whole output, Gemma 4's per-layer `layer_scalar`) or one row broadcast down the rows (a
+per-channel layer scale). It is its own op because the schema fixes whether an operand is a weight
+or an activation, and `mul`'s `b` is an activation. Kernels read the form off the operand;
+`scalar` 1 states the one-element form so a shape description (`rad-kbench`'s) builds the right
+weight.
+
+**`act_mul`** is `silu_mul` with its halves in two operands, so the multiplier can be any tensor:
+two column slices of a fused `gate_up`, or a gate and a separate per-layer input (EmbeddingGemma 2's
+per-layer-embedding block multiplies `gelu_tanh(gate(x))` by one). `act` is `silu`, `gelu` (exact
+erf), `gelu_tanh` or `sigmoid` (a GLU: `a` the gate half, `b` the value half). The activation is
+rounded to `y`'s dtype before the product, as the unfused pair stores it.
+
+**`seg_mean`** is mean pooling over a ragged batch: row `s` of `y` is the mean of `x`'s rows
+`[cu[s], cu[s+1])`, summed in double and rounded once. `M` is the step's token count and bands the
+op; the segment count is `cu_seqlens`' length less one. An empty segment is a zero row.
+
+**`pool_rows`** is a vision pooler over windows laid out consecutively: row `r` of `y` is the mean
+of `x`'s rows `[r*k, r*k + k)`, summed in f32 and rounded to `y`'s dtype, then times `mult` and
+rounded again (the unfused pair stores the mean). `M` is the input row count, a multiple of `k`.
+
+**`fill`** writes `y = value` over the extent (`value` 0 when absent). A rank issues it where it
+computes nothing but a downstream reader still expects a defined buffer: an attention-zero rank's
+block (`docs/TP3.md`) is one `fill` of its output wire before the all-reduce. A wire shared across
+layers cannot be zeroed once a step, and a memset knows neither the row pitch nor the dtype.
+
+**`grid_embed`** adds a learned `side x side` position table resampled to each row's grid. `coord`
+is `[4, M]` (row, column, grid height, grid width); sampling is bilinear with the grid's corners on
+the table's (align_corners), edge taps clamped, the four taps summed in f32 and rounded to `x`'s
+dtype before the add.
+
+**`grid_embed_aa`** is the same addition with SigLIP2's resample, torch's
+`F.interpolate(mode="bilinear", align_corners=False, antialias=True)`: per axis a triangle filter on
+half-pixel centres, widened by the scale when the grid is smaller than the table, its in-table taps
+normalised to sum to one; separable, f32, rounded once. A different function from `grid_embed`'s,
+so a different op rather than a mode a library could ignore.
+
+### Hyper-connections
+
+`hc_read` and `hc_write` are the gated residual pair a hyper-connection model has instead of a
+pre-norm and a residual add. The stream is `hc` times the model width; every block reads a mix of
+the `hc` sub-streams and writes back into all of them, both gated by data:
 
     hc_read     N      = grouped_rmsnorm(h)          one rsqrt per n-wide stream, one hc*n gain
                 g      = sigmoid(mix_up @ silu(mix_down @ N / hc))
@@ -217,88 +291,49 @@ reads a mix of the `hc` sub-streams and writes back into all of them, both gated
                 inj[s] = 2 * sigmoid(inject_w[s] . N / hc)
     hc_write    h[s]  += inj[s] * y
 
-Three facts that are not derivable from the others and that a second implementation has to match:
-the mix is a MEAN over the streams and not a sum; there is a separate `/ hc` inside each of the two
-gate arguments; and **`hc_write` adds into the UNNORMED `h`** -- the normalisation is consumed by
-the block input and the gates and never enters the residual. Writing into `N` instead re-normalises
-the stream 96 times over and still produces fluent text.
+Three facts a second implementation must match: the mix is a mean over the streams, not a sum;
+each of the two gate arguments has its own `/ hc`; and `hc_write` adds into the unnormed `h`. The
+normalisation feeds the block input and the gates and never enters the residual. Writing into `N`
+instead re-normalises the stream at every connection and still produces fluent text, so the error
+is easy to miss.
 
-`inject_w` absent is the final mixer, which collapses the wide stream to one and has nothing to
-write back; `group` absent is a read whose consumer wants bf16. Otherwise the fp8 form of `x` comes
-out of the same pass, because a model with 96 connections cannot afford a separate quantise launch
-at each of them -- and it is quantised from the NARROWED `x`, not from the accumulator, so a fused
-kernel and the reference agree bit for bit. `rotate` adds `rq`/`rscale`: `had_quant_act_fp8` of the
-same stored `x`, each group rotated by an unnormalised Hadamard before its absmax, for a consumer
-whose weight plane carries the rotation (the w4a8h experts) -- which then needs no quantise launch
-of its own either.
+- `inject_w` absent is the final mixer, which collapses the wide stream to one and writes nothing
+  back.
+- `group` absent is a read whose consumer wants bf16. Otherwise the fp8 form of `x` (`q`, `scale`)
+  comes out of the same pass, quantised from the narrowed `x` rather than the accumulator, so a
+  fused kernel and the reference agree bit for bit.
+- `rotate` adds `rq`/`rscale`: `had_quant_act_fp8` of the same stored `x`, each group rotated by an
+  unnormalised Hadamard before its absmax, for a consumer whose weight carries the rotation (the
+  `w4a8h` experts).
+- `mix` is the mixing matrices' stored format: `bf16`, or `e4m3` (rows of E4M3 codes with f32
+  scales in each row's own tail, one per 128 columns for `mix_down` and one per quarter row for
+  `mix_up`). It changes the bytes read, not the arithmetic. The matrices are replicated on every
+  rank and read once per connection; on Qwen3.8-Flash-Next (96 connections) `e4m3` halves their
+  1.26 GB a step. The scales in the row's tail are libr4d's arrangement; the container holds codes
+  and an f32 scale plane (a group of 128 for `mix_down`, a quarter row for `mix_up`), which a host
+  kernel reads joined (Weights of several planes).
 
-`mix` is the mixing matrices' STORED format: `bf16`, or `e4m3` -- rows of E4M3 codes with f32
-scales in each row's own tail, a 128-column group for `mix_down` and a quarter row for `mix_up`.
-It changes the bytes a step reads, not the arithmetic above; the two matrices are replicated on
-every rank and read once a connection, so at 96 connections the format is worth half of 1.26 GB a
-step on Qwen3.8-Flash-Next.
-
-`mul`'s `b` operand may have extent 1 on any dimension where `a` does not, and is broadcast along
-it. Every other elementwise op keeps the strict same-shape rule.
-
-`sigmoid`, with a broadcast-capable `mul`, is what a gated shared expert needs
-(`ffn_gate_inp_shexp`). Without it the shared expert runs ungated, which is a different model.
-
-`fill` has no input: `y = value` over the extent, `value` 0 when absent. It is the op a rank issues
-where it computes nothing and a reader downstream still expects a defined buffer -- an
-attention-zero rank's block (`docs/TP3.md`) is one `fill` of its output wire before the all-reduce.
-A wire shared across layers cannot be zeroed once a step, and a memset knows neither the row pitch
-nor the dtype; this does.
-
-**`mul_weight`** is a learned gain on an activation: `w` is a WEIGHT of one element, a scalar for
-the whole output -- Gemma 4's per-layer `layer_scalar` on the residual stream -- or of one row,
-broadcast down the rows (a per-channel layer scale). Its own op rather than a form of `mul`
-because an operand is a weight or an activation by its schema, and `mul`'s `b` is an activation.
-`scalar` 1 states the one-element form; kernels read the form off the operand, and the parameter
-is what lets a shape description (rad-kbench's) build the right weight.
-
-**`act_mul`** is `silu_mul` with its two halves in two operands, so the multiplier can be any
-tensor -- the two column slices of a fused `gate_up`, or a gate and a separate per-layer input
-(EmbeddingGemma 2's per-layer-embedding block multiplies `gelu_tanh(gate(x))` by one). `act` is
-`silu`, `gelu` (exact erf), `gelu_tanh` or `sigmoid` (a GLU's gate: `a` the gate half, `b` the
-value half); the activation is rounded to `y`'s dtype before the product, which is what the
-unfused pair stores.
-
-**`seg_mean`** is a sentence embedding's mean pooling over a ragged batch: row `s` of `y` is the
-mean of `x`'s rows `[cu[s], cu[s+1])`, summed in double and rounded once. `M` is the step's token
-count and bands the op; the segment count is `cu_seqlens`' length less one. An empty segment is a
-zero row.
-
-**`pool_rows`** is a vision pooler over windows its processor laid out consecutively: row `r` of `y`
-is the mean of `x`'s rows `[r*k, r*k + k)`, summed in f32 and rounded to `y`'s dtype, then times
-`mult` and rounded again (the unfused pair stores the mean). `M` is the input row count and a
-multiple of `k`.
-
-**`rmsnorm`'s `mult`** scales the normed row before its one rounding: a residual branch weighted by
-a constant -- Gemma 4's audio feed-forward adds half of its output -- with no second pass. For a
-power of two it is exactly the reference's norm-then-scale, since scaling by one commutes with the
-rounding.
-
-**The audio tower's operators** (Gemma 4's USM conformer):
+### Gemma 4's audio tower
 
 - **`relu`** is `max(x, 0)` at each operand's own row pitch.
-- **`clamp`** is `min(max(x, lo), hi)` with `lo` and `hi` WEIGHTS of one element each -- a clipped
-  linear's input or output range, which the checkpoint states per projection.
+- **`clamp`** is `min(max(x, lo), hi)` with `lo` and `hi` weights of one element each: a clipped
+  linear's input or output range, stated per projection in the checkpoint.
 - **`conv2d`** convolves over (time, width) with channels innermost: element `(t, w, c)` of `x` is
   at row `t`, column `w * cin + c`, and `w` is PyTorch's `[cout, cin, kh, kw]`. Each `cu_seqlens`
-  segment -- rows `[cu[s] / cu_div, cu[s+1] / cu_div)` -- is convolved on its own with zero padding
+  segment (rows `[cu[s] / cu_div, cu[s+1] / cu_div)`) is convolved on its own with zero padding
   `pad` at its edges on both axes, so two clips in one pass never see each other, and its output
   rows start at `cu[s] / (cu_div * stride)` (a segment whose start does not divide is refused).
-  With the optional `valid`, input row `t` reads as zeros unless `valid[t * valid_stride] != 0`:
-  the frame mask the subsampler multiplies in before each convolution. f32 sum, one rounding.
-- **`conv1d_dw`** is a causal depthwise convolution over time, `y[t, c] = sum_j w[c, 0, j] *
-  x[t - (k - 1) + j, c]`, with the rows before the segment's start reading as zeros.
+  With `valid`, input row `t` reads as zeros unless `valid[t * valid_stride] != 0`: the frame mask
+  the subsampler applies before each convolution. f32 sum, one rounding.
+- **`conv1d_dw`** is a causal depthwise convolution over time,
+  `y[t, c] = sum_j w[c, 0, j] * x[t - (k - 1) + j, c]`, with rows before the segment's start
+  reading as zeros.
 - **`rel_sinusoid`** writes the sinusoidal relative-position table, row `d` for distance `d`:
-  `sin(d * inv[i])` over the first half and `cos(d * inv[i])` over the second, `inv[i] = exp(i *
-  -log(max_timescale) / max(n/2 - 1, 1))`, each step in f32 as the reference's torch expressions
-  are, then rounded.
+  `sin(d * inv[i])` over the first half and `cos(d * inv[i])` over the second,
+  `inv[i] = exp(i * -log(max_timescale) / max(n/2 - 1, 1))`, each step in f32 as the reference's
+  torch expressions are, then rounded.
 
-### Gemma 4's fusions: the sandwich-norm joins, `expert_scale`, `attn_paged_qrow` — no reference row
+### Gemma 4 fusions (device-only)
 
 | op | params | operands |
 |---|---|---|
@@ -308,124 +343,142 @@ rounding.
 | `expert_scale` | `M`(range) `n_expert` `top_k` `dtype` | `ids`, `w_e`w, `ew`:inout |
 | `attn_paged_qrow` | `q_len`(range) `head_dim` `gqa` `block_size`/der `causal` `window` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt | `q`, `kv_cache`, `block_table`, `seqused`, `k_descale`?, `v_descale`?, `cu_seqlens`? → `out` |
 
-Gemma's sandwich norms, each one kernel in place of a chain of `rmsnorm`, `add` and `mul_weight`.
-`norm_add_norm` is `t = rmsnorm(a) * w_a; x += t; y = rmsnorm(x) * w_y` -- a post-norm, the
-residual add, the next pre-norm. `join_add_scale` is `x = (x + rmsnorm(rmsnorm(d) * w_d +
-rmsnorm(r) * w_r) * w_j) * s` -- two arms' post-norms, their sum, its norm, the residual add and a
-one-element layer scalar (Gemma 4's MoE feed-forward) -- and, given `w_n` and `y` (both or
-neither), `y = rmsnorm(x) * w_n` over the `x` it writes: the next layer's input norm, or the final
-norm after the last layer, which would otherwise be a launch of its own reading that `x` back.
-Every value the chain stores is rounded to the activation dtype at the same point, so the two
-differ from the chain only in the order a sum of squares is added in: with the same order they are
-bit-identical to it, and against a chain summed in another block width a norm factor can differ in
-its last bit.
+Gemma's sandwich norms, each one kernel in place of a chain of `rmsnorm`, `add` and `mul_weight`:
 
-`norm_add_norm_route` is `norm_add_norm` and, from the same norm of the `x` it writes, a MoE
-layer's two routed inputs: `r = rmsnorm(x) * w_r * mult` -- `rmsnorm`'s expression with `mult` --
-and `q`, `qs` = `rmsnorm_quant_fp8` of `x` under `w_e`: E4M3 codes of the bf16-rounded norm, an
-f32 scale per (row, `group` columns) of `amax / 448` (1 for an all-zero group), the value over it
-clamped to +-448. `n` is whole groups and `group` 128. In Gemma 4 it replaces the router's
-`rmsnorm` and the experts' `rmsnorm_quant_fp8`, two launches a layer that read back the `x` the
-join had just written.
+- `norm_add_norm` is `t = rmsnorm(a) * w_a; x += t; y = rmsnorm(x) * w_y`: a post-norm, the
+  residual add and the next pre-norm.
+- `join_add_scale` is `x = (x + rmsnorm(rmsnorm(d) * w_d + rmsnorm(r) * w_r) * w_j) * s`: two arms'
+  post-norms, their sum, its norm, the residual add and a one-element layer scalar (Gemma 4's MoE
+  feed-forward). Given `w_n` and `y` (both or neither) it also writes `y = rmsnorm(x) * w_n` over
+  the new `x`: the next layer's input norm, or the final norm after the last layer.
+- `norm_add_norm_route` is `norm_add_norm` plus, from the same norm of the new `x`, a MoE layer's
+  two routed inputs: `r = rmsnorm(x) * w_r * mult` (`rmsnorm`'s expression with `mult`), and `q`,
+  `qs` = `rmsnorm_quant_fp8` of `x` under `w_e` (E4M3 codes of the bf16-rounded norm, an f32 scale
+  per (row, `group` columns) of `amax / 448`, 1 for an all-zero group, the value over it clamped to
+  ±448). `n` is whole groups and `group` is 128. In Gemma 4 it replaces the router's `rmsnorm` and
+  the experts' `rmsnorm_quant_fp8`.
+
+Every value the chain stores is rounded to the activation dtype at the same point, so the fusions
+differ from the chain only in the order a sum of squares is added: with the same order they are
+bit-identical, and against a chain summed in another block width a norm factor can differ in its
+last bit.
 
 `expert_scale` is `ew[t, k] = ew[t, k] * w_e[ids[t, k]]` over `[M, top_k]`, `w_e` an `[n_expert]`
-table and an id outside it reading 0: Gemma 4's per_expert_scale on the renormalised routing
-weights, in place of an `embed_lookup` of the table by the ids and a `mul` into the weights. One
-product rounded once, so the pair's value bit for bit.
+table and an id outside it reading 0: Gemma 4's `per_expert_scale` on the renormalised routing
+weights, in place of an `embed_lookup` and a `mul`. One product rounded once, so the pair's value
+bit for bit.
 
-`attn_paged_qrow` is `attn_paged` -- the same parameters, operands and values -- with `q` read at
-its own row pitch: a column slice of a wider row, the q part of a fused `[q|k|v]` projection, read
-where it lies instead of lifted into a dense block by a `cast` first. It is a name of its own
-because an `attn_paged` kernel may refuse a pitched `q` (libr4d's other attention kernels do, with
-`RAD_E_STRIDE`, at the first step), and under `attn_paged` whichever library is first in `--kernels` wins the op: an
-architecture handing it the slice would depend on an order it cannot see. Asked for by name, the op
-resolves to a library that reads the pitch or to nothing, and the architecture lifts `q` for
-`attn_paged` where it is nothing.
+`attn_paged_qrow` is `attn_paged` (same parameters, operands and values) with `q` read at its own
+row pitch: the q part of a fused `[q|k|v]` projection, read where it lies instead of copied into a
+dense block by a `cast`. It has its own name because other `attn_paged` kernels refuse a pitched `q`
+(libr4d's with `RAD_E_STRIDE`, at the first step), and under `attn_paged` the first library in
+`--kernels` wins the op, an order the architecture cannot see. Asked for by name, the op resolves to
+a library that reads the pitch or to nothing, and the architecture copies `q` for `attn_paged` in
+the second case.
 
-**libref has no row for any of them, on purpose.** An architecture asks for a join and declares the
-chain where it does not resolve (`rad_op_resolved`), and a reference row would resolve it
-everywhere -- so a model loaded without the library that serves the join would resolve it to the
-reference and be refused at serve, instead of running the chain on libr4d or libavx. libr4d
-declares them, with device rows only, so the host backend runs the chains too. With no oracle, its
-kernels are held to a chain summed in their own block order, bit for bit, by `tests/r4d_emu`. No row
-declares `replaces`: rad-kbench's fusion oracle runs the replaced chain out of the fusing library's
-own rows and compares bytes, and libr4d's `rmsnorm` adds its sums of squares in another block
-order, which can move a norm factor's last bit.
+libref has no row for any of them, deliberately. An architecture asks for a fusion and declares
+the chain where it does not resolve (`rad_op_resolved`); a reference row would make it resolve
+everywhere, so a model loaded without the serving library would resolve to the reference and be
+refused at serve, instead of running the chain on libr4d or libavx. libr4d declares them with
+device rows only, so the host backend runs the chains. With no oracle, its kernels are held bit
+for bit to a chain summed in their own block order by `tests/r4d_emu`. No row declares `replaces`:
+`rad-kbench`'s fusion oracle runs the replaced chain on the fusing library's own rows and compares
+bytes, and libr4d's `rmsnorm` adds its sums of squares in another block order.
+
+**The Whisper-style audio encoder's** (Qwen3-ASR's, `arch/qwen3asr_bf16`), which convolves each
+second of a clip apart and attends in windows of eight seconds:
+
+- **`conv2d`'s `t_last`, `b` and `act`.** `t_last` 1 reads the weight as PyTorch's `[cout, cin, kw,
+  kh]`, time last: the kernel of a model that convolves a `[mel, time]` spectrogram, whose first
+  spatial axis is the one this op calls width. `b`, after `y` so a call without it keeps its five
+  operands, is a bias per output channel added to the f32 sum before the one rounding; `act`
+  (`none`, `gelu` exact) is then applied to the rounded value and rounded again, as
+  `gemm_nt_bias`'s epilogue does. A linear over a `(width, channel)` row whose weight is stored
+  channel-major is a `1 x width` convolution with `kh` 1: its `[N, cin * width]` weight is
+  PyTorch's `[N, cin, 1, width]`.
+- **`conv2d_unfold`** is `conv2d`'s receptive fields as rows, so a convolution with many channels
+  is a GEMM. Row `(to, wo)` (output time row `to` in conv2d's numbering, output column `wo`)
+  holds, for every input channel and kernel tap, the value conv2d multiplies that tap's weight by,
+  and zero where the tap falls in the padding or on a row `valid` masks. Its columns are in the
+  weight's order, `(ci, i, j)` for `[cout, cin, kh, kw]` and `(ci, j, i)` with `t_last`, so `y`
+  times the weight read as `[cout, cin * kh * kw]` is conv2d's output (`[rows * Wo, cout]` is the
+  same bytes as conv2d's `[rows, Wo * cout]`). Segments, `cu_div` and `valid` are conv2d's; `M`
+  counts input time rows.
+- **`seg_sinusoid`** is `rel_sinusoid`'s table at absolute positions that restart: row `r` of
+  segment `s` (rows `[cu[s] / cu_div, cu[s+1] / cu_div)`) takes position `(r - cu[s] / cu_div) mod
+  period`. Qwen3-ASR adds it to each second's rows, which start again at position 0. A row no
+  segment covers is left untouched.
+- **`attn_dense`'s `block` and `cu_div`.** `block` cuts a segment into blocks of that many rows from
+  its start, the last one short, each attending only within itself: a chunked encoder's window
+  (Qwen3-ASR's 104 rows, eight seconds). `cu_div` reads `cu_seqlens` in units that many rows
+  apart, as the other encoder ops do, so a tower can bound its rows by the pass's frame
+  boundaries. A kernel that reads neither refuses a call that sets them.
 
 ## Quantisation and rotation
 
 | op | params | operands |
 |---|---|---|
 | `quant_act_i8` | `M`(range) `n` `group` `dtype` | `x` → `q`, `scale`, `asum`? |
+| `quant_act_i8g` | `M`(range) `n` `group` `dtype` | `x` → `q`, `scale` |
 | `had_quant_act_i8` | `M`(range) `n` `group` `dtype` | `x` → `q`, `scale` |
 | `rmsnorm_had_quant_i8` | `M`(range) `n` `eps`:f64 `group` `dtype` `wadd`:f64/opt | `x`, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? |
 | `gated_had_quant_i8` | `M`(range) `n` `group` `dtype` `act`:str/opt `mode`/opt | `a`, `b`? → `q`, `scale` |
 | `dequant` | `M`(range) `n` `group` `dtype` | `q`, `scale` → `y` |
 | `gram_accum` | `M`(range) `n` `group` `dtype` | `a`, `a_scale`?, `h`:inout |
 
-`gram_accum` is the odd one here and belongs in this table anyway, because it characterises a
-quantiser's output: `h[k1][k2] += sum over rows of dequant(a)[m][k1] * dequant(a)[m][k2]`, in f32.
-That is the Hessian a GPTQ packer needs, over exactly the operand the consuming GEMM contracts.
-**`h` is `[n, n]` and INOUT** -- a caller zeroes it once and drives a whole calibration corpus
-through the graph, so each launch adds its own block; an implementation that stored instead of
-added would agree on one call and disagree on a corpus. It is **not** `gemm_nt` with a transposed
-operand: that op contracts the LAST axis of both sides and this one contracts the FIRST, so
-expressing it as a GEMM would need `x` materialised transposed. It is also the one op in this
-document that **no forward pass issues** -- it runs under a calibration flag and its result is
-read at convert time, in another process, through a file.
+**`gram_accum`** characterises a quantiser's output:
+`h[k1][k2] += sum over rows of dequant(a)[m][k1] * dequant(a)[m][k2]`, the Hessian a GPTQ packer
+needs over the operand the consuming GEMM contracts. `h` is f32 `[n, n]` and inout: a caller
+zeroes it once and drives a whole calibration corpus through the graph, each launch adding its
+block. It is not `gemm_nt` with a transposed operand: that op contracts the last axis of both sides
+and this one the first. It is the one op here that no forward pass issues; it runs under a
+calibration flag and its result is read at convert time, in another process, through a file.
+`dtype` says how `a` is read: `fp8a8` is E4M3 codes with an f32 dequant scale per (row, `group`
+columns) in `a_scale`; `bf16` is a plain activation with no `a_scale` and no grouping.
 
-**`a_scale` is optional, and `dtype` says which reading `a` takes.** `fp8a8` is E4M3 codes with
-an f32 dequant scale per (row, `group` columns): the tap of a model whose expert GEMM contracts a
-quantised activation. `bf16` is a plain activation read as it stands, with no `a_scale` and no
-grouping: the tap of a model served at bf16, whose expert GEMM contracts exactly that.
+**Activation widths.** Which width a linear's activation takes follows from the weight. Where the
+checkpoint ships E4M3 weights and a block scale plane, every linear is `fp8a8`
+(`arch/common/rad_fp8.h`). libr4d's `fp8a16` matvec (`M <= 8`) reads bf16 directly, but it assumes
+a weight layout the stored WMMA fragment order does not provide, so it is not used. Where the engine
+quantises the activation for an integer weight it is int8: `quant_act_i8` for `w4a8`, `w8a8` and
+`w2a8`, `quant_act_i8g` for `i8a8`.
 
-**Two activation widths are in use, and which one a linear takes is the WEIGHT's question rather
-than a preference.** Where the checkpoint already ships E4M3 weights and a block scale plane, the
-activation follows the weight: `fp8a8` is the shipped path (`arch/common/rad_fp8.h`), because the
-`fp8a16` form that would read a bf16 activation directly and skip the quantise launch has a kernel
-only at `M <= 1` — a single-sequence decode and nothing else. Where the engine quantises the
-activation itself, it is **rotated int8**: the rotation is a per-group Walsh–Hadamard, and it is
-what makes a single scale per row viable at all, which is what an int8 row buys over a row of
-floats each carrying its own exponent.
+**`group` has different meanings in this table.** A kernel that reads it the other way is wrong,
+not slow. `libref/ref_quant.cpp` is the definition.
 
-**`group` MEANS TWO DIFFERENT THINGS IN THIS TABLE**, and a kernel that reads it the other way is
-wrong rather than slow. `libref/ref_quant.cpp` is the definition; this is what it says.
-
-- **`quant_act_i8`, `dequant`** — `group` is the number of **contiguous elements sharing one f32
-  scale**, so `scale` is `[M, ceil(n/group)]`. `group <= 0` or `group >= n` means one scale per
-  ROW. For `dequant` the same reading, inverted: the scale stream's extent says how many groups
-  there are and `group` says how wide each one is.
-- **every `had_*` INT8 form** — `group` is the **Walsh–Hadamard rotation width** (libr4d spells it
-  `had`), and the int8 scale is per **ROW**, carrying the `1/sqrt(group)` normalisation. That is
-  the reading the prose above forces: a per-group rotation is what makes a single scale per row
-  viable, so the rotation width and the scale granularity cannot be the same number.
-- **the `had_*` FP8 forms** (`had_quant_act_fp8`, `gated_had_quant_fp8`) — `group` is **both**, and
-  that is not an inconsistency but a different bargain. They exist for a four-bit MoE expert whose
-  scale grid is already one bf16 per (row, 128 of K); making the rotation the same 128 lines the
-  two up, so the scale is per group here and shaped `[M, n/group]` exactly as `quant_act_fp8`'s is.
-  They also do **no normalisation at all**: ` = group * `, and the whole residual
-  factor is folded into the **stored weight scale** at convert, where dividing a bf16 by a power of
-  two is exact. Splitting it as the int8 forms do would round `amax/7/sqrt(group)` into bf16 and
-  land a ~0.2% multiplicative error on every group. `n` must be a multiple of `group`: a rotation
-  block cannot straddle the end of a row.
-- **`quant_act_i8g`, `had_quant_act_i8g`** — `quant_act_fp8`'s grouping and scale shape at INT8
-  codes: one f32 scale per `group` of a row, `amax / 127` (1 for a zero group), each code the value
-  over it rounded to nearest even and clamped to +-127. They are the activation side of the int8
-  W8A8 trunk (`gemm_nt_q` at `dtype=i8a8`), which is why they are not `quant_act_i8`: that op's scale
-  is per row unless asked otherwise, and an int8 GEMM folding a scale per K block needs the block.
-  The `had_` form rotates first, as `had_quant_act_fp8` does.
+- **`quant_act_i8`**: one f32 scale per row, `max(amax, 1e-8) / 127`, and codes `x * (1 / scale)`
+  rounded to nearest even, stored in the step order the int8 WMMA reads an A fragment in: the
+  middle two dwords of every 16-byte step exchanged (column `c` at byte `c` with bits 2 and 3
+  swapped), so `n` is a multiple of 16. `group` sizes `asum`, each row's code sums per `group`
+  columns, group-major `[n/group][ceil(M/16)*16]`, which an asymmetric weight grid needs to remove
+  its zero point. Rows past `M` are not written.
+- **The `had_*` int8 forms**: `group` is the Walsh–Hadamard rotation width (libr4d's `had`), and
+  the int8 scale is per row, carrying the `1/sqrt(group)` normalisation. The rotation is what makes
+  one scale per row viable, so its width and the scale granularity cannot be the same number.
+- **The `had_*` fp8 forms** (`had_quant_act_fp8`, `gated_had_quant_fp8`): `group` is both. They
+  serve a four-bit MoE expert whose scale grid is already one bf16 per (row, 128 of K); a rotation
+  of the same 128 lines the two up, so the scale is per group, `[M, n/group]` as for
+  `quant_act_fp8`. They apply no normalisation: ` = group * `, and the whole factor is
+  folded into the stored weight scale at convert, where dividing a bf16 by a power of two is exact.
+  Splitting it as the int8 forms do would round `amax/7/sqrt(group)` into bf16, a ~0.2% error per
+  group. `n` must be a multiple of `group`.
+- **`quant_act_i8g`, `had_quant_act_i8g`, `dequant`**: `quant_act_fp8`'s grouping at int8 codes:
+  one f32 scale per `group` contiguous elements of a row, so `scale` is `[M, ceil(n/group)]`
+  (`group <= 0` or `group >= n` is one per row). The scale is `amax / 127` (1 for a zero group) and
+  each code the value over it rounded to nearest even and clamped to ±127, row-major. They feed the
+  int8 trunk GEMM (`gemm_nt_q` at `dtype=i8a8`), which folds a scale per K block. The `had_` form
+  rotates first. `dequant` inverts `quant_act_i8g`: the scale stream's extent gives the group count
+  and `group` each group's width.
 
 The rotation is unnormalised butterflies at ascending strides `1, 2, 4, ... group/2`, pairing `i`
 with `i + h` where `(i & h) == 0`. The `1/sqrt(group)` is folded into the scale rather than applied
-to the values -- dividing every element by a constant cannot change which int8 code it rounds to,
-and folding it costs nothing. A rotation block may not cross a tensor-parallel shard boundary, so
-the width has to divide the PER-RANK `n`.
+to the values; dividing every element by a constant cannot change which int8 code it rounds to. A
+rotation block may not cross a tensor-parallel shard boundary, so the width must divide the
+per-rank `n`.
 
-`gated_had_quant_i8` serves two readings of its input: the gate and up as two operands, which is
-libr4d's, and one fused `gate_up` `[M, 2n]` with the gate first, which is what a fused gate_up
-projection produces. Two operands with the second optional expresses both — a caller with a fused
-buffer passes it as `a` and omits `b` — and `mode` is optional because it is libr4d's integer
-spelling of `act`, not the vocabulary's.
+`gated_had_quant_i8` takes the gate and up as two operands (libr4d's form), or one fused `gate_up`
+`[M, 2n]` with the gate first as `a` and `b` absent. `mode` is libr4d's integer spelling of `act`
+and is optional.
 
 ### The fp8 fusions
 
@@ -439,82 +492,80 @@ spelling of `act`, not the vocabulary's.
 | `gated_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `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`? |
 
-### `givens_dense_quant`: ParoQuant's rotated activation
+`gemm_nt_q_gated` is `gemm_nt_q` over a `[N, K]` gate_up plane (`N` is the weight's rows, twice the
+fused width, gate half first) with `gated_quant_fp8`'s pass in the epilogue, so the `[M, N]` bf16
+tensor between them is never written. It is a separate schema, not a flag on `gemm_nt_q`, because
+it does not produce that op's `y`. `act` is required here, unlike on the quantiser: an
+implementation may compile one gate only, and an optional parameter would let it resolve for
+another.
 
-A weight stored with the `givens` transform (`abi/rad_encoding.h`) is `v = w . D . G_1 ... G_S`: the
-channel scale `D` and `S` stages of disjoint pairwise rotations were applied to each row BEFORE it
-was quantised (ParoQuant, z-lab), so the product the GEMM contracts is `` with
-`x' = x . D^-1 . G_1 ... G_S` -- the activation takes the same rotation, forward, once a token.
-`givens_dense_quant` is that: `x / rscale`, then the rotation, then a block-scaled quantiser (`out`
-names it: `fp8` is `quant_act_fp8`'s, scale `amax / 448`; `i8` is `quant_act_i8g`'s, scale
-`amax / 127`, round to nearest) per `group` columns. The rotation is applied as ONE dense 128 x 128
-f16 matrix a (part, group) -- `tdense`, `[parts * n, 128]` -- the composition of the group's `stages`
-rounds `a' = a cos t + b sin t, b' = b cos t - a sin t` over its pairs. A weight's `pairs` and `angle`
-tables are column indices and angles of the row and each pair lies inside ONE scale group (ParoQuant's
-are within groups of 128), so the matrices are the weight's own: rad-convert composes them once, in f64,
-and stores them as the weight's `t.dense` table, which the layout hook (`r4d_rad_layout_gdense`) only
-moves. The consumers are `gemm_nt_q` at `mxfp4a8`
-(`out` fp8) and at `w4a8i8_asym` / `w5a8i8` (`out` i8); nothing in the weight's codes or exponents
-changed.
+`out_bf16` is part of the function, not an optimisation: the unfused pair leaves a bf16 tensor
+behind and takes the codes over it, so a layer with a bf16 consumer of the post-norm value must ask
+for it. `residual` present is the `fused_add_rms_norm` form.
 
-A fused projection (gate|up, qkv|z) was rotated PER CHECKPOINT TENSOR, so it has `parts` rotated
-copies of the activation, written side by side -- `q` is `[M, parts * n]`, `scale`
-`[M, parts * n / group]` -- and `pairs` and `angle` stack the parts' `stages` rows each, `rscale`
-one row a part. `gemm_nt_q` then takes `pb1` and `pb2`, the row bounds of the weight's parts: its
-rows `[0, pb1)`, `[pb1, pb2)` and `[pb2, N)` meet copy 0, 1 and 2, and `a`/`a_scale` are the wide
-planes. `givens_rotate` is the same rotation done stage by stage, with no quantiser, `y` in its own dtype (f16), for the 16-bit-activation weights `w5a16` and `w4a16_asym`; their GEMM serves any `M` (rows past 64 run as chunks of 64). The int8 activation of `w5a8i8` / `w4a8i8_asym` is `givens_dense_quant`'s at `out` `i8`. `pb1` absent is one part; `pb2` absent ends the second part at `N`. The `mxfp4a8` rows and the
-asymmetric 4- and 5-bit rows (`w5a16`, `w4a16_asym`, `w5a8i8`, `w4a8i8_asym`) read them, and the
-host rows that do not (`libavx`) refuse a call that names one rather than contract against the
-wrong copy.
+### ParoQuant rotations
 
-### The int8 and gated fp8 fusions — device-only
+A weight stored with the `givens` transform (`abi/rad_encoding.h`) is `v = w . D . G_1 ... G_S`: a
+channel scale `D` and `S` stages of disjoint pairwise rotations applied to each row before
+quantisation (ParoQuant, z-lab). The GEMM contracts `` with `x' = x . D^-1 . G_1 ... G_S`,
+so the activation takes the same rotation once a token.
+
+- **`givens_dense_quant`** computes `x / rscale`, the rotation, then a block-scaled quantiser per
+  `group` columns that `out` names: `fp8` is `quant_act_fp8`'s (scale `amax / 448`), `i8` is
+  `quant_act_i8g`'s (scale `amax / 127`, round to nearest). The rotation is one dense 128 x 128 f16
+  matrix per (part, group), `tdense` `[parts * n, 128]`, composed from that group's `stages` rounds
+  of `a' = a cos t + b sin t, b' = b cos t - a sin t`. Each pair lies inside one scale group, so the
+  matrices belong to the weight: rad-convert composes them once in f64 and stores them as the
+  weight's `t.dense` table, which the layout hook (`r4d_rad_layout_gdense`) only moves. Consumers
+  are `gemm_nt_q` at `mxfp4a8` (`out` fp8) and at `w4a8i8_asym` / `w5a8i8` (`out` i8).
+- **`givens_rotate`** is the same rotation stage by stage with no quantiser, `y` in its own dtype
+  (f16), for the 16-bit-activation weights `w5a16` and `w4a16_asym`, whose GEMM serves any `M`
+  (rows past 64 run as chunks of 64).
+
+A fused projection (gate|up, qkv|z) was rotated per checkpoint tensor, so the activation has
+`parts` rotated copies side by side: `q` is `[M, parts * n]` and `scale` `[M, parts * n / group]`;
+`pairs` and `angle` stack each part's `stages` rows and `rscale` has one row per part. `gemm_nt_q`'s
+`pb1` and `pb2` are the row bounds of the weight's parts: rows `[0, pb1)`, `[pb1, pb2)` and
+`[pb2, N)` meet copies 0, 1 and 2 of the wide `a`/`a_scale`. `pb1` absent is one part; `pb2` absent
+ends the second part at `N`. The `mxfp4a8` rows and the asymmetric 4- and 5-bit rows read them;
+host rows that do not (libavx) refuse a call that names one rather than contract against the wrong
+copy.
+
+### Int8 and gated fp8 fusions (device-only)
 
 | op | params | operands |
 |---|---|---|
-| `quant_act_i8g` | `M` `n` `group` `dtype` | `x` → `q`, `scale` |
 | `had_quant_act_i8g` | `M` `n` `group` `dtype` | `x` → `q`, `scale` |
 | `gated_had_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate_up` → `q`, `scale`, `out_bf16`? |
 | `gate_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate`, `x` → `q`, `scale`, `out_bf16`? |
 | `rmsnorm_quant_i8` | `M` `n` `eps`:f64 `dtype` `wadd`:f64/opt | `x`, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`?; `w_post`w?, `scalar`w? |
 | `gelu_mul_quant_i8` | `M` `n` `dtype` | `gate_up` → `q`, `scale`, `out_bf16`? |
 
-`gelu_mul_quant_i8` is `gelu_mul` with the same quantiser on its pass, byte-identical to the pair.
+`gelu_mul_quant_i8` is `gelu_mul` with `rmsnorm_quant_i8`'s quantiser on its pass, byte-identical
+to the pair.
 
-`rmsnorm_quant_i8` is `rmsnorm` with `quant_act_i8`'s quantiser on its pass — fragment-order int8
-codes and one f32 scale per row, the grid `gemm_nt_q` reads at `dtype=w4a8`. With `residual` the
+`rmsnorm_quant_i8` is `rmsnorm` with `quant_act_i8`'s quantiser on its pass: step-order int8 codes
+and one f32 scale per row, what `gemm_nt_q` reads at `dtype=w4a8` and `w8a8`. With `residual` the
 norm is of `residual + x`, stored back; `w_post` normalises `x` before that add and `scalar` (`[1]`)
-multiplies the sum after it, which together are a sandwich-norm model's residual junction
-(`rmsnorm` → `add` → `scale` → `rmsnorm` → `quant_act_i8`). Byte-identical to that chain: every
-intermediate the chain stores is rounded to bf16, and both sums of squares take `rmsnorm`'s partition.
+multiplies the sum after it, together a sandwich-norm model's residual junction (`rmsnorm` → `add`
+→ `scale` → `rmsnorm` → `quant_act_i8`). Byte-identical to that chain: every intermediate the chain
+stores is rounded to bf16, and both sums of squares take `rmsnorm`'s partition.
 
-`gemm_nt_q_gated` is the row above pulled into the projection that feeds it: `gemm_nt_q` over a
-`[N, K]` gate_up plane — `N` is the WEIGHT's rows, twice the fused width, gate half first — with
-`gated_quant_fp8`'s pass in the epilogue, so the `[M, N]` bf16 tensor between them is never
-written. It is a separate schema and not a flag on `gemm_nt_q` because it does not produce that
-op's `y`, and an architecture that resolved it into `gemm_nt_q`'s operand list would hand the GEMM
-a buffer of half the width it expects. `act` is REQUIRED here, unlike the quantiser's: an
-implementation is free to compile one gate and an optional parameter would let it resolve for
-another.
-
-`out_bf16` is not an optimisation: the unfused pair leaves a bf16 tensor behind and the codes are
-taken over *that*, so a layer with a bf16 consumer of the post-norm value must ask for it or the
-fusion is a different function. `residual` present is the `fused_add_rms_norm` form.
-
-### `dequant_w4` — device-only
-
-`libref` declares `dequant` and nothing else declares `dequant_w4`, so this op is not negotiated
-between plugins the way the shared ones are: it is libr4d's own, spelled libr4d's way.
+### `dequant_w4` (device-only)
 
 | op | params | operands |
 |---|---|---|
 | `dequant_w4` | `N` `K` `group` `dtype` `twos` | `wq`w, `ws`w → `y` |
 
-`twos` selects the symmetric two's-complement nibble over the asymmetric unsigned-nibble-minus-
-zero-point grid. The two differ by bit 3, so the wrong one is not a refusal, it is wrong output.
+libr4d's own op: a packed 4-bit fragment-ordered weight back to row-major bf16. libref declares
+`dequant`, which is activation-shaped, and nothing else declares `dequant_w4`.
 
-**`wq` and `ws` are WEIGHT operands**, and the `w` marker is the load-bearing part of that. Spelt
-as plain inputs they name the same bytes, and the core stops resolving their handles and stops
-waiting on the mover's event — a read of weight bytes that may not have arrived yet.
+`twos` selects the symmetric two's-complement nibble over the asymmetric unsigned-nibble-minus-
+zero-point grid. The two differ in bit 3, so the wrong one is wrong output, not a refusal.
+
+`wq` and `ws` must be weight operands. As plain inputs they would name the same bytes, but the core
+would stop resolving their handles and stop waiting on the mover's event, reading weight bytes that
+may not have arrived.
 
 ## GEMM
 
@@ -525,20 +576,57 @@ waiting on the mover's event — a read of weight bytes that may not have arrive
 | `gemm_nt_q` | `M`(range) `N` `K` `group` `dtype` `pb1`/opt `pb2`/opt | `a`, `a_scale`?, `b`w, `b_scale`w → `y`; `a_sum`?, `b_ref`w? |
 | `gemm_nt_q_bias` | `M`(range) `N` `K` `group` `dtype` | `a`, `a_scale`, `b`w, `b_scale`w, `bias`w → `y` |
 
-`nt` is A row-major `[M,K]` times B **transposed** `[N,K]`, giving `[M,N]` — the layout every
-weight in a transformer already has. `dtype` distinguishes `bf16` from `w4a8`, so one op name
-covers the family and the selector picks by the quant string. That is deliberate: an architecture
-plugin that switches quant changes one string, not its op names.
+`nt` is A row-major `[M,K]` times B transposed `[N,K]`, giving `[M,N]`: the layout every weight in
+a transformer already has. `gemm_nt_q`'s `dtype` names the operand combination, so one op covers
+every quantised format and an architecture plugin that changes quantisation changes one string, not
+its op names.
 
-`gemm_nt_q` takes activation scales as an operand because the quantiser produced them; a kernel
-that folds dequantisation into its epilogue still receives them.
+`gemm_nt_q` takes the activation scales as an operand because the quantiser produced them; a kernel
+that folds dequantisation into its epilogue still receives them. Being a quantiser's amax over its
+range, an `a_scale` entry is never negative, and a kernel may treat a block whose scale is zero as
+contributing nothing (libr4d's MXFP4 GEMMs carry their accumulators in the last positive scale).
+`a_scale` is absent for the f16-activation grids. At `w4a8`, `w4a8_asym`, `w8a8` and `w2a8`, `a` and `a_scale` are
+`quant_act_i8`'s codes, in its step order, and per-row scale, and `a_sum` is its `asum`.
+At `i8a8` they are `quant_act_i8g`'s row-major codes and per-(row, 128 of K) scales against an int8
+weight with a bf16 scale per (row, 128 of K); at `mxfp4a8`, `quant_act_fp8`'s pair against e2m1
+codes with an E8M0 exponent per (row, 32 of K).
+
+`a_sum` removes an asymmetric grid's zero point and `b_ref` is the per-row reference exponent an
+MXFP4 kernel folds its block exponents against. `b_ref` is derived from `b_scale` and does not
+change the product. Both host libraries accept `b_ref` beside an e2m1 weight and ignore it, and
+refuse `a_sum` (`RAD_E_UNSUPPORTED`) except at the grids that remove their zero through it.
+
+The zero-point grids read unsigned codes as `b` and their scale and zero joined as `b_scale` (above):
+weight element (n, k) is `(code - zero) * scale`, one f16 scale and one integer zero per (row,
+`group` of K). libref's reference forms each group's sub-sum on the integer grid and scales it once:
+
+| dtype | codes | `a`, `a_scale` | group sub-sum `sub` | accumulated |
+|---|---|---|---|---|
+| w2a8, w4a8_asym | u2, u4 | `quant_act_i8`'s step-order codes, per-row scale; `a_sum` required | `sum(a * code) - zero * a_sum[g][m]`, exact | `(sub * a_scale[m]) * scale` |
+| w4a8i8_asym, w5a8i8 | u4, u5 | row-major int8, f32 scale per (row, 128 of K) (`givens_dense_quant`) | `sum(a * (code - zero))`, exact | `(sub * a_scale[m][g]) * scale` |
+| w4a16_asym, w5a16 | u4, u5 | a 16-bit activation (`givens_rotate`), no `a_scale` | `sum(a * (code - zero))` in f32, ascending k | `sub * scale` |
+
+`a_sum` is `quant_act_i8`'s `asum`, group-major `[K/group][Mpad]` with `Mpad = ceil(M/16)*16`. The
+ParoQuant grids (the four 4- and 5-bit ones) take parts (`pb1`, `pb2`); `w2a8` and `w4a8_asym` do
+not, and none has a bias form. libr4d's kernels compute the same products in another order (split-K
+partials, the activation scale applied at the store); libavx folds the scales into its decoded rows,
+each product rounding once where libref rounds each group's sub-sum. A `b_scale` that is not joined
+at these grids has no zero to read and is refused (`RAD_E_DTYPE`). libref describes none of them
+(`opd_shape` declines: no single tensor states a scale and a zero), so rad-kbench and the op oracle
+leave them out and rad-avx-check builds them by hand.
+
+`gemm_nt_bias`'s epilogue is a linear layer's: the biased product rounded to `y`'s dtype, then
+`act` of it (`none`, `gelu` exact, `gelu_tanh`) rounded, then `res` added and rounded. Each step is
+what a separate tensor would hold, so the fused form equals the unfused chain bit for bit. `res`
+may be `y` itself, the residual stream updated in place (the encoder towers' layers do this), so an
+implementation reads `res` before it stores the product over it.
 
 ## Attention
 
 | op | params | operands |
 |---|---|---|
 | `attn_paged` | `q_len`(range) `head_dim` `gqa` `block_size`/der `causal` `window` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt | `q`, `kv_cache`, `block_table`, `seqused`, `k_descale`?, `v_descale`?, `cu_seqlens`? → `out` |
-| `attn_dense` | `M`(range) `head_dim` `gqa` `causal` `dtype` `scale`:f64/opt `max_seqlen`/opt `window`/opt | `q`, `k`, `v`, `cu_seqlens` → `out` |
+| `attn_dense` | `M`(range) `head_dim` `gqa` `causal` `dtype` `scale`:f64/opt `max_seqlen`/opt `window`/opt `cu_div`/opt `block`/opt | `q`, `k`, `v`, `cu_seqlens` → `out` |
 | `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` |
 | `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 |
 | `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 | `qkv`:inout, `positions` |
@@ -546,162 +634,148 @@ that folds dequantisation into its epilogue still receives them.
 | `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 |
 | `qkv_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `ladder`/opt `wadd`:f64/opt `v_from_k`/opt `dtype` | `q`:inout, `k`:inout, `v`:inout, `positions`, `q_w`w, `k_w`w |
 
-**`attn_local_rel`** is Gemma 4's audio attention: local, with a relative-position term and a
-softcap. Query row `i` of a segment sees the key rows `j` of the same segment with `0 <= i - j <=
-left` (`right` must be 0). Per head, `qf = q * (head_dim^-0.5 / ln 2) * softplus(pds)` -- softplus
-rounded to `pds`'s dtype, as the reference evaluates it on the parameter -- and `logit = qf . k *
-(ln(1 + e) / ln 2) + qf . relk[i - j]`, then `softcap * tanh(logit / softcap)`, a softmax over the
-visible keys and the weighted sum of `v`, all in f32 and rounded once. `relk` is `[left + 1,
-n_head * head_dim]`, row `d` the projected position for distance `d`. The reference computes this
-in 12-query blocks over 24-key windows with a Transformer-XL shift; every key outside the window
-carries a `-1e9` logit there, so the sliding form is the same function.
+**`attn_paged`**'s band is `q_len`, not `M`: one query row at decode, `1 + n_spec` at a speculative
+verify, thousands in a prefill chunk, and libr4d has a different kernel for each band.
+`block_size` is read off the resolved kernel, not chosen: declare the group, declare the op, then
+ask `rad_kv_block_size()` (`spec.md` §7.2).
 
-`attn_paged` is the ranged op whose band is `q_len`, not `M`: one query row at decode, up to 64 at
-a speculative verify, thousands in a prefill chunk, and libr4d has a different kernel for each
-band. `block_size` is **read off the resolved kernel**, not chosen — declare the group, declare
-the op, then ask `rad_kv_block_size()` (`spec.md` §7.2).
+`cu_seqlens` is optional and makes the batch ragged: `[n_seq+1]` i32, sequence `s` owning query rows
+`[cu[s], cu[s+1])` of the dense `q` and `out` blocks. Absent, every sequence has the same query
+length and the total query rows must be a multiple of `n_seq`. Pass it: the scheduler builds mixed
+steps (one sequence's prefill chunk beside other sequences' decode rows, each with its own verify
+window) whenever prefill and decode coexist, and those are not uniform. `q_len` is then the batch
+maximum, which selects the band; the per-sequence lengths come from `cu_seqlens` alone.
 
-`cu_seqlens` is optional and makes the batch **ragged**: `[n_seq+1]` i32, sequence `s` owning query
-rows `[cu[s], cu[s+1])` of the dense `q` and `out` blocks. Absent, every sequence must present the
-same query length and `total_q` must divide `n_seq`. Pass it: a mixed step — one sequence's prefill
-chunk beside other sequences' decode rows, which carry their own verify windows and so are not one
-row each — is what the scheduler builds whenever prefill and decode coexist, and it does not
-satisfy the uniform form. `q_len` is then the batch MAXIMUM, which is what selects the band; the
-per-sequence lengths come from `cu_seqlens` alone.
-
-`attn_dense` is the vision tower's and an encoder's: nothing paged, `cu_seqlens` bounding one
-image or one input per entry so a whole batch is one launch. `window` is `attn_paged`'s rule over a
-segment's own positions -- causal, key `j` is visible to query `i` when `i - j < window`;
-non-causal, when `|i - j| < window` -- and 0 is no window. A bidirectional encoder's sliding layer
-of radius `r` (`|i - j| <= r`) is `window = r + 1`. `q`, `k` and `v` may each be `[tokens, heads, head_dim]` or
+**`attn_dense`** serves vision towers and encoders: nothing paged, `cu_seqlens` bounding one image
+or one input per entry so a whole batch is one launch. `window` is `attn_paged`'s rule over a
+segment's own positions (causal: key `j` is visible to query `i` when `i - j < window`; non-causal:
+when `|i - j| < window`), and 0 is no window. A bidirectional encoder's sliding layer of radius `r`
+(`|i - j| <= r`) is `window = r + 1`. `q`, `k` and `v` may each be `[tokens, heads, head_dim]` or
 `[tokens, heads * head_dim]`, and the second form may be a column slice of a fused projection read
-at that projection's row pitch -- which is how a tower's `[q|k|v]` row reaches it without a copy.
+at its row pitch, so a tower's `[q|k|v]` row needs no copy.
 
-**`qkv_norm_rope`** is the same prologue over SEPARATE `q`, `k` and `v` projections (Gemma 4's text
-attention, three GEMMs): the q and k norms, the unit-gain value norm and the rotary in one dispatch.
-`v_from_k` 1 takes v from the RAW k before the k norm (the k == v global class). The rotary parameters
-are `rope`'s, `ladder` included; byte-identical to `rmsnorm_p` + `rmsnorm` x2 + `rope` x2.
-
-**`qk_norm_rope`'s `v_norm`** set to 1 also RMS-norms every v head of the fused row with a UNIT
-gain and does not rotate it: Gemma 4's value norm, which has no weight to name.
-
-**`qk_norm_rope`'s `blocks` mode** rotates each section as its own block of channels: section `c`
-is `sections[c]` pairs over the next `2 * sections[c]` channels, paired `(start + j, start +
-sections[c] + j)` -- NeoX inside the block -- and turned by position component `comps[c]` (default
-`c`) at `theta^(-j / sections[c])`. The sections fill `rotary_dim` exactly and `positions` is
-`[C, M]`. It is Gemma 4's vision rotary: x over the first half of each head and y over the second,
-each half a complete rotary of its own; `mode` `axial` of `rope` pairs across the halves instead.
+**`attn_local_rel`** is Gemma 4's audio attention: local, with a relative-position term and a
+softcap. Query row `i` of a segment sees key rows `j` of the same segment with
+`0 <= i - j <= left` (`right` must be 0). Per head, `qf = q * (head_dim^-0.5 / ln 2) * softplus(pds)`
+(softplus rounded to `pds`'s dtype, as the reference evaluates it on the parameter) and
+`logit = qf . k * (ln(1 + e) / ln 2) + qf . relk[i - j]`, then `softcap * tanh(logit / softcap)`, a
+softmax over the visible keys and the weighted sum of `v`, all in f32 and rounded once. `relk` is
+`[left + 1, n_head * head_dim]`, row `d` the projected position for distance `d`. The upstream
+reference computes this in 12-query blocks over 24-key windows with a Transformer-XL shift, giving
+every key outside the window a `-1e9` logit, so the sliding form is the same function.
 
 **`rope`'s multi-component modes.** `mrope`, `imrope` and `axial` rotate with NeoX pairing and let
 several position components drive different frequencies. `positions` is then `[C, M]`,
 component-major, and `sections` names how many of the `rotary_dim / 2` frequencies each component
-owns: `mrope` gives contiguous runs of them to components 0, 1, ... (Qwen2-VL); `imrope` interleaves
--- component 1 takes frequency `i` where `i % 3 == 1` and `i < 3 * s1`, component 2 where
-`i % 3 == 2` and `i < 3 * s2`, component 0 the rest (Qwen3-VL); `axial` gives contiguous runs AND
-restarts the frequency ladder in each, `theta^(-2j / (2 s_c))` for the run's `j`-th frequency (a
-vision tower's 2-D rotary over row and column). With `[M]` positions every component is that one
-position, so `mrope` and `imrope` over a text batch are `neox` exactly.
+owns:
 
-**`ladder` names the width the base frequency ladder is measured in.** Absent, or `rotary`, the
-exponent divides by `rotary_dim`: a partial rotary is a complete rotation of its own width, and
-every existing model is bit-for-bit unchanged. `head` divides by `head_dim` instead -- the
-**proportional** variant, where the `rotary_dim / 2` frequencies are a prefix of the full-width
-table rather than a table rescaled to the rotated width: at `head_dim 512, rotary_dim 128`,
-frequency `i = 1` wants `theta^(-1 / 256)`, not `theta^(-1 / 64)`. Only the base ladder moves
-(`axial` keeps its per-section ladders), and the tail of the head past `rotary_dim` is untouched
-either way. `rope_table` carries a `head_dim` param for the same reason: its angles must stay
-`rope`'s to the last operation.
+- `mrope` gives contiguous runs of them to components 0, 1, ... (Qwen2-VL);
+- `imrope` interleaves: component 1 takes frequency `i` where `i % 3 == 1` and `i < 3 * s1`,
+  component 2 where `i % 3 == 2` and `i < 3 * s2`, component 0 the rest (Qwen3-VL);
+- `axial` gives contiguous runs and restarts the frequency ladder in each, `theta^(-2j / (2 s_c))`
+  for the run's `j`-th frequency (a vision tower's 2-D rotary over row and column).
 
-**`gemm_nt_bias`'s epilogue** is a linear layer's: the biased product rounded to `y`'s dtype, then
-`act` of it (`none`, `gelu` exact, `gelu_tanh`) rounded, then `res` added and rounded -- each step
-what a separate tensor would hold, so the fused form is the unfused chain to the bit.
+With `[M]` positions every component is that one position, so `mrope` and `imrope` over a text batch
+are exactly `neox`.
 
-**`grid_embed`** adds a learned `side x side` position table resampled to each row's grid: `coord`
-is `[4, M]` (row, column, grid height, grid width), sampled bilinearly with the grid's corners on the
-table's (align_corners), edge taps clamped, the four taps summed in f32 and rounded to `x`'s dtype
-before the add.
+**`ladder`** names the width the base frequency ladder is measured in. Absent or `rotary`, the
+exponent divides by `rotary_dim`: a partial rotary is a complete rotation of its own width. `head`
+divides by `head_dim` instead (the proportional variant), so the `rotary_dim / 2` frequencies are a
+prefix of the full-width table: at `head_dim 512, rotary_dim 128`, frequency `i = 1` is
+`theta^(-1 / 256)`, not `theta^(-1 / 64)`. Only the base ladder moves (`axial` keeps its per-section
+ladders), and the head past `rotary_dim` is untouched either way. `rope_table` takes `head_dim` for
+the same reason: its angles must stay `rope`'s exactly.
 
-**`grid_embed_aa`** is the same addition with SigLIP2's resample: torch's
-`F.interpolate(mode="bilinear", align_corners=False, antialias=True)`. Per axis a triangle filter on
-half-pixel centres, widened by the scale when the grid is smaller than the table, its taps inside the
-table normalised to sum to one; separable, f32, rounded once. A different function from
-`grid_embed`'s, and so a different op rather than a mode a library could ignore.
+**`qk_norm_rope`** RMS-norms each q and k head of a fused `[q | k | v]` row against its gain (plus
+`wadd`), rounds, and rotates in place.
+
+- `v_norm` 1 also RMS-norms every v head with a unit gain and does not rotate it: Gemma 4's value
+  norm, which has no weight.
+- `mode` `blocks` rotates each section as its own block of channels: section `c` is `sections[c]`
+  pairs over the next `2 * sections[c]` channels, paired `(start + j, start + sections[c] + j)`
+  (NeoX inside the block), turned by position component `comps[c]` (default `c`) at
+  `theta^(-j / sections[c])`. The sections fill `rotary_dim` exactly and `positions` is `[C, M]`.
+  This is Gemma 4's vision rotary: x over the first half of each head and y over the second, each a
+  complete rotary; `rope`'s `axial` pairs across the halves instead.
+- `mode` `gptj_blocks` is `blocks` with each section's pairs adjacent, `(start + 2j, start + 2j + 1)`:
+  a 3-axis image rotary's complex form.
+- `mode` `imrope` is `rope`'s `imrope` over NeoX pairs, reading three position planes (Qwen3-VL's
+  text attention).
+
+**`qkv_norm_rope`** (device-only) is the same prologue over separate `q`, `k` and `v` projections
+(Gemma 4's text attention, three GEMMs): the q and k norms, the unit-gain value norm and the rotary
+in one dispatch. `v_from_k` 1 takes v from the raw k before the k norm (the k == v global class).
+The rotary parameters are `rope`'s, `ladder` included. Byte-identical to `rmsnorm_p`, two
+`rmsnorm`s and two `rope`s.
 
 | op | params | operands |
 |---|---|---|
 | `attn_paged_gate_quant` | `q_len`(range) `head_dim` `gqa` `block_size` `causal` `window` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt:capacity `group` `act` | `q`, `kv_cache`, `block_table`, `seqused`, `k_descale`?, `v_descale`?, `cu_seqlens`? → `out`; `gate` → `q8`, `q8_scale` |
 
-**`attn_paged_gate_quant` is `attn_paged` followed by `gate_quant_fp8` over its output**, the
-second op finished inside the first's split-KV merge. A merge row is one (token, head) pair of
-`head_dim` columns, which is exactly a `gate_quant_fp8` row, so the merged values are gated
-(`bf16(sigmoid(gate))`, rounded before the multiply), rounded, written to `out` and quantised to
-E4M3 with one scale per 128 columns while they are still in registers. It is byte-for-byte the
-pair, checked by `r4d_selftest` at both merge forms and over a bf16 and an E4M3 cache. `block_size` is required rather than derived
-because the cache's page size is `attn_paged`'s to answer; the caller passes the value it read. The
-gated attention block takes it on the QSA sparse path, where every launch is one query row a
-sequence and the decode kernel serves every chunk -- the whole step in one launch, which is why
-`max_seqs` is a capacity: the block declares it at the step size, and the activation arena's
-smaller declares bound it lower.
+**`attn_paged_gate_quant`** (device-only) is `attn_paged` followed by `gate_quant_fp8` over its
+output, finished inside the split-KV merge. A merge row is one (token, head) pair of `head_dim`
+columns, which is a `gate_quant_fp8` row, so the merged values are gated (`bf16(sigmoid(gate))`,
+rounded before the multiply), rounded, written to `out` and quantised to E4M3 with one scale per 128
+columns while still in registers. `r4d_selftest` checks it byte for byte against the pair at both
+merge forms and over a bf16 and an E4M3 cache. `block_size` is required rather than derived because
+the cache's page size is `attn_paged`'s to answer; the caller passes the value it read. The gated
+attention block uses it on the QSA sparse path, where every launch is one query row per sequence
+and the decode kernel serves the whole step in one launch. `max_seqs` is a capacity
+(`RAD_PROLE_CAPACITY`): the block declares it at the step size, and the activation arena's smaller
+declares bound it lower.
 
-### The KV cache is an operand
+### The KV cache operand
 
 `attn_paged` and `kv_store` take the group's cache as operand 1, passed as `RAD_KV(group, layer)`.
 `RadKVGroupBatch` carries the slot mapping, the block table and the sequence lengths, but the pool
-base belongs to the block manager and not to the batch.
+base belongs to the block manager, not the batch.
 
-### `qk_norm_rope_gate` — device-only
+### `qk_norm_rope_gate` (device-only)
 
 | op | params | operands |
 |---|---|---|
 | `qk_norm_rope_gate` | `M` `head_dim` `n_head` `n_head_kv` `rot` `q_dtype` `eps`:f64/opt `wadd`:f64/opt `cs_f32`/opt `pos_i64`/opt | `q_gate`?, `k`, `cos_sin`, `positions`, `q_w`w?, `k_w`w → `q_out`?, `k_out`, `gate_out`? |
 
-It splits an interleaved `[q|gate]` projection per head, RMS-norms q and k over the
-head, applies partial NeoX rope and copies the gate — four launches a layer in one. **It is NOT
-`qk_norm_rope`** in the attention table above, which takes `theta`: this one takes a
-PRECOMPUTED `cos_sin` table (`rope_table` builds it) and a different operand list, which is why it
-carries its own name. `rot` is the rotary width, `cs_f32` and `pos_i64` state the widths of the
-table and the position vector, and `gate_out` is optional — a caller that already reads the gate at
-its column offset inside the projection passes none.
+It splits an interleaved `[q|gate]` projection per head, RMS-norms q and k over the head, applies
+partial NeoX rope and copies the gate: four launches a layer in one. It is not `qk_norm_rope`, which
+takes `theta`: this op takes a precomputed `cos_sin` table (`rope_table` builds it) and a different
+operand list. `rot` is the rotary width, `cs_f32` and `pos_i64` state the widths of the table and
+the position vector, and `gate_out` is optional for a caller that reads the gate at its column
+offset inside the projection.
 
-**`n_head` 0 IS THE K-ONLY FORM**, and it is the half of this op that has nothing to do with
-gating. The `k` side is the plain reader — one head per `head_dim` columns, taken at the
-OPERAND's own row pitch, written contiguously to `k_out` — and the only thing the q side adds is
-the `[q|gate]` split. So an input that is already plain asks for `n_head` 0 and passes no
-`q_gate`, no `q_w` and no `q_out`. The QSA indexer's query heads are that shape: `heads` of them
-inside a `heads + 1` projection, which is a stride no rank-2 view can express and would otherwise
-be `heads` separate `rmsnorm` launches plus a `rope`. At 4 heads over 12 trunk layers and 4 MTP
-passes that is 80 launches a step for ~7 µs of work each; as one op it is 16.
+**`n_head` 0 is the K-only form.** The `k` side reads one head per `head_dim` columns at the
+operand's own row pitch and writes contiguously to `k_out`; only the q side adds the `[q|gate]`
+split. A plain input asks for `n_head` 0 and passes no `q_gate`, `q_w` or `q_out`. The QSA
+indexer's query heads have that shape: `heads` of them inside a `heads + 1` projection, a stride no
+rank-2 view can express, which would otherwise take `heads` `rmsnorm` launches plus a `rope`.
 
 | 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` is the prologue followed by `kv_store`**, in one launch. A k head's
-block already holds its token's rotated k one element a lane, so it writes that element and the
-head's v element into the cache at the token's slot as well. The `k` the store reads is `k_out`
-and is not an operand of its own, which is why the tail adds only `v`, `slot_mapping` and
-`kv_cache`; every parameter is one of the two ops' own. It is byte-for-byte the pair at either
-cache width: the store converts the rotated k exactly as `k_out` stores it, a bf16 cache takes the
-two values as they are, and the E4M3 conversion rounds each element on its own.
+**`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
+the head's v element into the cache at the token's slot. The store reads `k_out`, so the tail adds
+only `v`, `slot_mapping` and `kv_cache`; every parameter is one of the two ops' own. It is
+byte-identical to the pair at either cache width: the store converts the rotated k exactly as
+`k_out` stores it, a bf16 cache takes the values as they are, and the E4M3 conversion rounds each
+element on its own.
 
-**It IS byte-identical to the kernels it replaces**, and the check is in `r4d_selftest` rather than
-in an argument — two rows, one for the `[q|gate]` form and one for the K-only form on a strided
-projection. Byte equality and not a tolerance, and the difference between the two is the whole
-reason: fold the sum of squares over eight consecutive elements a lane where `rmsnorm` folds it
-over one and the two agree to a ULP, which a RELATIVE bound calls ok — but a ULP in the mean square
-is a ULP in the normed value, and a rotated element is a difference of two products, so where those
-nearly cancel the ULP comes out as a few percent and the transcript moves after a few dozen steps.
-The kernel reproduces the reference's fold exactly: the widths above the head dim contribute zeros
-and adding 0.0f is exact, so a block sum over 8 wave partials and over 32 are the same number.
+Both ops are byte-identical to the kernels they replace, checked in `r4d_selftest` for the
+`[q|gate]` form and the K-only form on a strided projection. The check is byte equality, not a
+tolerance: a sum of squares folded in another order differs by an ULP, which a relative bound
+accepts, but a rotated element is a difference of two products, so where those nearly cancel the
+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.
 
 ## Image generation
 
-The ops a diffusion image generator declares (`rad_declare_generator`, abi/rad_builder.h): a
-single-stream diffusion transformer's adaptive norm and gated residual, the timestep embedding, the
-per-image latent LANES and the flow-matching sampler over them, attention over a cached
+The ops a diffusion image generator declares (`rad_declare_generator`, `abi/rad_builder.h`): a
+single-stream diffusion transformer's adaptive norm and gated residual, the timestep embedding,
+per-image latent lanes and the flow-matching sampler over them, attention over a cached
 conditioning prefix, and an image decoder's convolution, channel norm, resampling shortcuts and
-pixel output. Each rounds where the reference model materialises a bf16 tensor; the libref
-function says which (libref/ref_gen.cpp).
+pixel output. Each rounds where the reference model materialises a bf16 tensor; the libref function
+says which (`libref/ref_gen.cpp`).
 
 | op | params | operands |
 |---|---|---|
@@ -726,24 +800,24 @@ function says which (libref/ref_gen.cpp).
 
 **Sequences and lanes.** `cu_seqlens` partitions the rows into entries (`[n_seq+1]` i32, entry `e`
 owning `[cu[e], cu[e+1])`; it need not start at 0). `ln_mod` and `gate_add` take each row's
-modulation row from `s`/`g`, `[n_seq, >= n]` at its own row pitch -- a column slice of one shared
-modulation projection. A LANE is one image's latent in a per-image state buffer, `stride` rows
-apart: `lane_gather` copies entry `e`'s rows out of lane `lane[e]`, `lane_store` copies one
+modulation row from `s`/`g`, `[n_seq, >= n]` at its own row pitch (a column slice of one shared
+modulation projection). A lane is one image's latent in a per-image state buffer, `stride` rows
+apart: `lane_gather` copies entry `e`'s rows out of lane `lane[e]`, and `lane_store` copies one
 source into every listed lane (a repainted picture's latent into each of its images).
 
 - `ln_mod`: `y = bf16(bf16(LN(x)) * bf16(1 + s[seq]))`, a layer norm with no gain and no bias.
 - `gate_add`: `x = bf16(x + bf16(bf16(tanh(g[seq])) * y))`.
 - `ln_mod_quant_fp8`: with `gated` 1, `gate_add` first; then `z = ln_mod(x)` and
-  `(q, scale) = quant_act_fp8(z, group)`, `z` written when bound -- the three in one pass, each
-  rounded as its own store would round it, so the bytes are the three ops'.
+  `(q, scale) = quant_act_fp8(z, group)`, `z` written when bound. Each value is rounded as its own
+  store would round it, so the bytes are the three ops'.
 - `timestep_embed`: `[cos | sin]` of `t' * f_i`, `f_i = exp(-ln(max_period) * i / (n/2))` in f32,
-  `t' = scale * t`; with `round` 1, `t' = scale * bf16(bf16(t * scale) / scale)` -- the value
+  `t' = scale * t`; with `round` 1, `t' = scale * bf16(bf16(t * scale) / scale)`, the value
   diffusers' pipeline hands its transformer. `t` is f32 `[M]`.
 - `gather_rows2`: `y[i] = idx[i] >= 0 ? a[idx[i]] : b[-1 - idx[i]]`, zeros past either source.
 - `randn_lanes`: for entries whose `flags` carry 1, the lane's rows become the entry's seed's
-  standard-normal stream (abi/rad_philox.h), element `(k, c)` the stream's `k * n + c`. `seed` is
+  standard-normal stream (`abi/rad_philox.h`), element `(k, c)` the stream's `k * n + c`. `seed` is
   `[n_seq, 2]` u32, low word first.
-- `flow_euler`: for every entry with `pair != -2` (an entry that IS a negative conditioning moves
+- `flow_euler`: for every entry with `pair != -2` (an entry that is a negative conditioning moves
   no lane), `v' = pair >= 0 ? bf16(neg + bf16(cfg * bf16(v - neg))) : v`, `neg` the paired entry's
   rows; flag 4 writes `bf16(x - sigma * v')` to the lane's `preview`; then
   `x' = bf16(x + bf16(bf16(sigma_next - sigma) * v'))`; flag 2 restores the kept region,
@@ -751,18 +825,18 @@ source into every listed lane (a repainted picture's latent into each of its ima
   `inp_mask` row, `src` its `inp_lat` row and `noise` the seed's stream.
 
 **Images** are `[height, width * channels]`, dense, and the ops read both sizes off the operand
-shapes: an image's size is a request's, and a parameter is fixed at declare.
+shapes: an image's size belongs to a request, and a parameter is fixed at declare.
 
 - `conv2d_nhwc`: `w` is PyTorch's `[cout, cin, k, k]` (a kernel may store it permuted through its
   layout hook), `b` `[cout]`; `up` 2 reads the input upsampled 2x nearest-neighbour; `pad` `same`
-  is `k/2` zeros a side, `down` is none above and left and one below and right (`ZeroPad2d((0,1,0,1))`
-  before a stride-2 conv). f32 accumulation, the bias added, one rounding.
-- `l2norm_chan`: each pixel's channels to unit L2 (eps 1e-12), times `sqrt(n)`, times `gamma` --
-  three roundings -- then `act` `none` or `silu`.
+  is `k/2` zeros a side, `down` is none above and left and one below and right
+  (`ZeroPad2d((0,1,0,1))` before a stride-2 conv). f32 accumulation, the bias added, one rounding.
+- `l2norm_chan`: each pixel's channels to unit L2 (eps 1e-12), times `sqrt(n)`, times `gamma`
+  (three roundings), then `act` `none` or `silu`.
 - `chan_affine`: `mul` and `add` are space-separated lists of `n` values, each rounded to bf16;
   `fma` is `bf16(bf16(x * mul) + add)`, `inv` is `bf16(bf16(x - add) / mul)`.
-- `d2s_add` (Wan's DupUp3D on one frame): `y[2r+i, 2c+j, o] += x[r, c, (o F + off + 2i + j) /
-  rep]`, `F = 4 ft`, `off = 4` when `ft` is 2, `rep = cout F / cin`.
+- `d2s_add` (Wan's DupUp3D on one frame): `y[2r+i, 2c+j, o] += x[r, c, (o F + off + 2i + j) / rep]`,
+  `F = 4 ft`, `off = 4` when `ft` is 2, `rep = cout F / cin`.
 - `s2d_avg_add` (AvgDown3D on one frame): `y` gains the mean of each output channel's group of
   `cin F / cout` dealt values, a dealt channel being `(c, t, i, j)` at `c F + 4t + 2i + j`; with
   `ft` 2 the frame `t = 0` is the zero frame the reference pads in, which the mean still counts.
@@ -770,18 +844,13 @@ shapes: an image's size is a request's, and a parameter is fixed at declare.
 
 **`attn_prefix_self`** attends over two key sources: entry `s`'s first `seqused[s]` keys in the
 paged cache, all visible, and the pass's own rows `k`/`v` beside `q` (dense, at their own pitch,
-rows indexed as `q`'s), of which row `i` sees `j <= i` with `causal` and all of them without. It
-is an image's latent rows against its conditioning, and one segment of a conditioning against the
-segments before it. `qk` `"i8"` is the int8 score form and takes `k_i8` [tokens, kv_heads *
-head_dim] and `k_scale` [tokens, kv_heads] f32, the own keys as `quant_act_i8g` writes them at
-group `head_dim`; the query and every prefix key are quantised inside the op by the same rule
-(scale `amax/127`, 1 for an all-zero row; code `rint(clamp(x * (1/scale), +-127))`) and a score is
-the exact integer dot product times both scales. `k` is then not read for the own rows.
-
-`qk_norm_rope` takes two more `mode`s for these models: `gptj_blocks` is `blocks` with each
-section's pairs ADJACENT, `(start + 2j, start + 2j + 1)` -- a 3-axis image rotary's complex form
--- and `imrope` is the interleaved M-RoPE of Qwen3-VL's text attention over NeoX pairs (`rope`'s
-`imrope`), reading three position planes.
+indexed as `q`'s rows), of which row `i` sees `j <= i` with `causal` and all of them without. It is
+an image's latent rows against its conditioning, or one segment of a conditioning against the
+segments before it. `qk` `"i8"` is the int8 score form and takes `k_i8` `[tokens, kv_heads *
+head_dim]` and `k_scale` `[tokens, kv_heads]` f32, the own keys as `quant_act_i8g` writes them at
+group `head_dim`. The query and every prefix key are quantised inside the op by the same rule
+(scale `amax/127`, 1 for an all-zero row; code `rint(clamp(x * (1/scale), ±127))`), a score is the
+exact integer dot product times both scales, and `k` is not read for the own rows.
 
 ## Mixture of experts
 
@@ -798,102 +867,92 @@ section's pairs ADJACENT, `(start + 2j, start + 2j + 1)` -- a 3-axis image rotar
 | `pair_argmax` | `M`(range) `n` `dtype` | `pairs` → `idx`, `val`? |
 | `logit_rerank` | `M`(range) `R` `n_vocab` `n_embd` `vocab_off`/opt `dtype` | `x`, `head`w, `idx_in` → `idx`, `val`, `pairs`? |
 
-`row_topk` and `row_topk_merge` are a pair, and the second only means anything with the first's
-optional half. A vocab-sharded head produces logits for its own slice and nothing else, so its
-top-R is over that slice: `vocab_off` shifts the columns reported into GLOBAL ids, and `pairs`
-writes the same R entries as `[M, R, 2]` (an int32 id in the first float slot, its value in the
-second) -- the plane `core/sample/sampler.h` holds as `buf_pairs_`, and the one the
-sampler's own vocab-parallel path gathers. An `all_gather` with `row = R*2` concatenates those
-into `[M, world_size * R, 2]`, rank r's at `[r*R, (r+1)*R)`, and `row_topk_merge` reduces it to
-the global top-R. **The merge is exact, not approximate**: a candidate in the global top-R is in
-its own shard's top-R, and both stages break ties on the lower id, so the result equals a top-R
-over the unsharded plane element for element. A slot a shard could not fill carries id -1 in
-`pairs` and is dropped -- a sentinel rather than a -inf value, because a masked logit takes that
-value legitimately.
+**`row_topk` and `row_topk_merge`** are a pair for a vocab-sharded head, whose logits cover only its
+own slice. `vocab_off` shifts the reported columns into global ids, and `pairs` writes the same R
+entries as `[M, R, 2]` (an int32 id in the first float slot, its value in the second): the plane
+`core/sample/sampler.h` holds as `buf_pairs_` and the sampler's vocab-parallel path gathers. An
+`all_gather` with `row = R*2` concatenates them into `[M, world_size * R, 2]`, rank r's at
+`[r*R, (r+1)*R)`, and `row_topk_merge` reduces that to the global top-R. The merge is exact: a
+candidate in the global top-R is in its own shard's top-R, and both stages break ties on the lower
+id, so the result equals a top-R over the unsharded plane. A slot a shard could not fill carries id
+-1 in `pairs` and is dropped; a sentinel id rather than a -inf value, because a masked logit can be
+-inf legitimately.
 
-`pair_argmax` is the merge at R = 1, for a vocab-sharded draft head that wants each position's
-winner as a proposal: `idx` gets the id of the largest value among a row's `n` gathered pairs,
-ties to the lower id, a negative id skipped, -1 (and -inf in `val`) when nothing is valid --
-written one element a row at the output's own pitch, which is what a block drafter's contiguous
-proposal needs. It is not `row_topk_merge` with R = 1 because a rank still sends R >= 2 pairs: a
-row-interleaved `all_gather` moves whole 16-byte words and one pair is 8 bytes, so `n` is
-`world_size * R` and the op takes the top-1 of all of them.
+**`pair_argmax`** is the merge at R = 1, for a vocab-sharded draft head that wants each position's
+winner: `idx` gets the id of the largest value among a row's `n` gathered pairs, ties to the lower
+id, negative ids skipped, -1 (and -inf in `val`) when nothing is valid, written one element a row at
+the output's own pitch (a block drafter's contiguous proposal). It is not `row_topk_merge` at R = 1
+because a rank still sends R >= 2 pairs: a row-interleaved `all_gather` moves whole 16-byte words
+and a pair is 8 bytes, so `n` is `world_size * R`.
 
-`logit_rerank` is the second half of a COARSE top-R. A speculative step can afford a cheap draft
-head -- the target verifies every proposal, so a worse draft costs acceptance and never a token --
-but a head quantised hard enough to be cheap also picks a different top-1 often enough to matter.
-So the coarse head proposes R and this op scores those R, and only those R, against the
-full-precision head the trunk already carries: a few hundred KB a row against a few hundred MB, for
-an answer that agrees with the exact argmax on almost every row. `idx_in` carries GLOBAL ids as
-`row_topk` reports them and `vocab_off` is this rank's first column, so under vocab-parallel
-drafting each rank rescores the candidates it owns and the existing `all_gather` + `row_topk_merge`
-still finds the global winner -- it needs no collective of its own. Ties break on the LOWER id, the
-rule the other two use, so a tie inside a shard and a tie between shards resolve alike.
+**`logit_rerank`** is the second half of a coarse top-R. A cheap, coarsely quantised draft head
+proposes R candidates, and this op rescores those R against the full-precision head the trunk
+already carries: a few hundred KB a row instead of a few hundred MB, and an answer that agrees with
+the exact argmax on almost every row. A worse draft costs acceptance, never a token, since the
+target verifies every proposal. `idx_in` carries global ids as `row_topk` reports them and
+`vocab_off` is this rank's first column, so under vocab-parallel drafting each rank rescores the
+candidates it owns and the existing `all_gather` + `row_topk_merge` finds the global winner. Ties
+break on the lower id, as in the other two.
 
-**`router_topk_scatter` is those two in one launch**, and it exists because neither of them is
-work. At a decode shape each is a SINGLE 256-thread workgroup ranking about a kilobyte — the
-selection is a wave a row and four rows is one workgroup; the sort is one workgroup by
-construction — so each costs the one-workgroup dispatch floor and almost nothing else. At 52 of
-each per step that is ~1.0 ms, 3.6% of the decode step, for two dispatches. The chain is closed:
-the sort reads `expert_ids` and nothing else, and `expert_ids` is exactly what the selection
-writes, so a launch between them buys only a barrier and `__syncthreads()` is that barrier.
+**`router_topk_scatter`** (device-only) is `router_topk` and `moe_scatter` in one launch. At a
+decode shape each is a single 256-thread workgroup ranking about a kilobyte, so each costs the
+one-workgroup dispatch floor and almost nothing else. The chain is closed (the sort reads only
+`expert_ids`, which the selection writes), so a launch between them buys only a barrier.
 
-**Two expert counts, and they are not the same number.** `n_expert` is the ROUTER's — it is
-replicated and every rank picks from every expert — while `n_local` is THIS RANK's slice, which is
-what the sort runs over and what sizes `expert_offset` and `expert_count` — half of the router's
-on Qwen3.8-Flash-Next when its experts are divided between two ranks, as a calibration run divides
-them. `n_local` absent means the slice is the router, which is every deployment that gives each
-rank a slice of every expert instead.
+- **Two expert counts.** `n_expert` is the router's: it is replicated and every rank picks from
+  every expert. `n_local` is this rank's slice, which the sort runs over and which sizes
+  `expert_offset` and `expert_count`, as when a calibration run divides Qwen3.8-Flash-Next's experts
+  between two ranks. `n_local` absent means the slice is the whole router, as in every deployment
+  that gives each rank a slice of every expert.
+- **Bounded, with no fallback.** Only `moe_scatter`'s single-workgroup form is fusible
+  (`M * top_k <= 1024`); above that the sort is three launches, which keep it stable without an
+  atomic deciding the order. That bound covers the decode band (eight sequences at depth 3 and
+  top_k 10 is 320 slots). A prefill chunk is past it, where the pair is amortised over real work.
+  A caller past the bound gets a refusal, not a silent change of cost.
 
-**Bounded, and it refuses rather than falling back.** Only `moe_scatter`'s single-workgroup form is
-fusible (`M * top_k <= 1024`); above it the sort is three launches, which exist to keep it stable
-without an atomic deciding the order. That bound is the decode band by construction — eight
-sequences at depth 3 and top_k 10 is 320 slots — and a prefill chunk is past it, which is also
-where the pair is amortised over real work and a fusion would buy nothing. A caller past the bound
-gets a refusal, not a silent change of cost.
+**`router_gemm_topk_scatter`** (device-only) adds the router's GEMM in front, in the same launch:
+`gemm_nt` of `a` `[M, K]` against the router `b` `[n_expert, K]` into `logits`, then
+`router_topk_scatter` over those logits. With `gate_b` `[1, K]` and `gate` `[M, 1]` (both or
+neither) it is also the shared expert's one-column `gemm_nt` over the same `a`. The selection needs
+every logit of a row, so it runs in the workgroup that finishes the GEMM last (a self-resetting
+arrival counter per op instance, which libr4d takes in the row's `init`, so it is in the VRAM
+budget; a launch without one is refused). It is byte-identical to the launches it replaces: an
+element of the skinny bf16 GEMM depends only on its split-K count, which this op takes from the same
+law at the same N, and the selection and sort are the same code. Decode only (`M <= 64`, past which
+the router is the tiled GEMM), and bounded like the pair. The logits stay an output.
 
-**`router_gemm_topk_scatter` puts the router's GEMM in front of that pair**, in the same launch:
-`gemm_nt` of `a` [M, K] against the router `b` [n_expert, K] into `logits`, then exactly
-`router_topk_scatter` over those logits. With `gate_b` [1, K] and `gate` [M, 1] present it is
-also the shared expert's one-column `gemm_nt` over the same `a`; the two come together or not at
-all. The selection needs every logit of a row, so it runs in the workgroup that finishes the GEMM
-last (an arrival counter, self-resetting, one an op instance: libr4d takes it in the row's `init`,
-so it is in the VRAM budget, and refuses a launch without one). It is byte-identical to the
-launches it stands in for: an element of the skinny bf16 GEMM depends only on its split-K count,
-which this op takes from the same law at the same N, and the selection and sort are the same code.
-Decode only, `M <= 64` -- past that the router is the tiled GEMM -- and bounded like the pair. The
-logits stay an output.
+The router GEMM inside it always takes the split the untuned law picks, so a tune-cache entry for
+the unfused router's `gemm_nt` does not reach it, and on a tuned install the two forms may differ in
+the last bit; no shipped configuration tunes these GEMMs. An architecture asks for this op wherever
+it declares the pair, and issues the router and the pair itself where it does not resolve or a pass
+is past its rows.
 
-**The router GEMM inside it is NOTUNE.** It always takes the split the untuned law picks, which is
-what makes it byte-identical to the unfused GEMM as an untuned install runs it. A tune-cache entry
-for the unfused router's `gemm_nt` does not reach this op, so on a tuned install the two forms may
-differ in the last bit; no shipped configuration tunes these GEMMs. An architecture asks for this op
-wherever it declares the pair and issues the router and the pair itself where it does not resolve
-or a pass is past its rows.
-
-`moe_scatter`'s output is what `rad_route_report` hands the heat engine. The histogram is read
-back asynchronously and consumed on the next step; nothing here blocks the compute stream
+**`moe_scatter`** is a stable counting sort of the (token, slot) pairs by expert. `sorted_tok` holds
+the flattened index `token * top_k + slot`. A slot whose expert is outside
+`[expert_base, expert_base + n_expert)` is dropped and the tail filled with -1, which is how expert
+parallelism is expressed. Its output is what `rad_route_report` hands the heat engine; the histogram
+is read back asynchronously and consumed on the next step, so nothing blocks the compute stream
 (`spec.md` §5.5).
 
-**`protect` sorts a few experts last.** A layer that keeps some experts at a higher precision than
-the rest serves them with a second grouped GEMM, and a grouped GEMM takes one contiguous run of the
-offsets. So `protect` lists local experts (ascending, at most eight) that the sort places after
-every other expert, in the order listed, with the rest closed up: `expert_offset` and
-`expert_count` are then in that order, the regular experts are `[0, n - p)` of the offsets and the
-protected ones `[n - p, n)`. A `moe_gemm` handed the trailing run (offsets that begin above zero)
-serves those rows and leaves the ones below untouched.
+**`protect`** sorts a few experts last. A layer that keeps some experts at a higher precision serves
+them with a second grouped GEMM, and a grouped GEMM takes one contiguous run of the offsets. So
+`protect` lists local experts (ascending, at most eight) that the sort places after every other
+expert, in the order listed, with the rest closed up: `expert_offset` and `expert_count` are in that
+order, the regular experts are `[0, n - p)` of the offsets and the protected ones `[n - p, n)`. A
+`moe_gemm` handed the trailing run (offsets that begin above zero) serves those rows and leaves the
+ones below untouched.
 
-**`moe_gather` folds the shared expert in when `shared` and `shared_gate` are given**, computing
-`y = bf16(shared * act(shared_gate)) + bf16(gathered)` in one pass -- which is `scale_rows`' own
-fused gate-and-add form, taken one op further back so the bf16 plane between the two never
-exists. BOTH NARROWS ARE PART OF THE CONTRACT: the unfused pair writes the gather to a bf16
-buffer and narrows the product before the sum, so an implementation that carried either in f32
-would move the last bit of every channel. `act` is "sigmoid" or "none" and applies to the
-SCALAR, the same spelling `scale_rows` uses. It is worth a pair of operands because a shared arm
-that cannot be width-sharded runs on ONE RANK, so the op it replaces is a dispatch a layer that
-every other rank waits out inside the block's all-reduce.
+**`moe_gather`** scatters the sorted expert output back to token order and weights it, summing a
+token's slots in ascending slot order. With `shared` and `shared_gate` it also folds the shared
+expert in: `y = bf16(shared * act(shared_gate)) + bf16(gathered)`, `scale_rows`' fused
+gate-and-add form one op further back, so the bf16 plane between them never exists. Both narrowings
+are part of the contract: the unfused pair writes the gather to a bf16 buffer and narrows the
+product before the sum, so carrying either in f32 moves the last bit. `act` is `"sigmoid"` or
+`"none"` and applies to the scalar, as in `scale_rows`. A shared arm that cannot be width-sharded
+runs on one rank, so the op this replaces is a dispatch every other rank waits out inside the
+block's all-reduce.
 
-### The quantised and gated arms
+### Quantised experts and the row gate
 
 | op | params | operands |
 |---|---|---|
@@ -901,77 +960,84 @@ every other rank waits out inside the block's all-reduce.
 | `moe_gemm_q_mod4` | `M`(range) `N` `K` `n_expert` `top_k` `group` `a_order` `dtype` `N_1`/opt `K_1`/opt `N_2`/opt `K_2`/opt `N_3`/opt `K_3`/opt `parts`/opt | `a`, `a_scale`?, `w`wt, `w_scale`wt, `sorted_tok`, `expert_offset`, `w_1`wt, `w_1_scale`wt, `w_2`wt, `w_2_scale`wt, `w_3`wt, `w_3_scale`wt → `y` |
 | `scale_rows` | `M`(range) `n` `act` `dtype` | `x`, `s`, `add`? → `y` |
 
-The `wt` suffix is the table form and `w` alone is an ordinary weight operand; `moe_gemm`'s row
-further up carries the same suffix, because its weight list is a per-expert pointer table. The
-arithmetic is unchanged by that — a kernel may also be handed the stacked reading, an ordinary
-rank-3 tensor with a real leading stride, and computes the same function from it.
+The arithmetic is the same whether a kernel is handed the tables or the stacked form
+([Weight operands and weight tables](#weight-operands-and-weight-tables)).
 
-**`moe_gemm_q`'s experts are two tables by parity.** `w`/`w_scale` hold the even-numbered experts
-at `[N, K]` and `w_odd`/`w_odd_scale` the odd ones at `[N_odd, K_odd]` (defaulting to `N`, `K`);
-expert `e` is entry `e / 2` of its class. Every entry of one table shares a geometry, and a rank
-that holds an uneven slice of every expert's width — three 128-column blocks of one parity's
-experts and two of the other's, which is how a five-block expert splits across two ranks evenly on
-average — has two. `parts` stacked parts run along both the weight rows and the output columns (two
-for a fused gate/up); the output is `max(N, N_odd)` wide, and a narrower class fills the leading
-columns of each output part and writes zeros after them, so the gated quantiser behind it reads
-one layout for every row. Under the equal-division rule above the op's weight list is the even
-class's codes, its scales, then the odd class's codes and scales.
+**`moe_gemm_q`'s experts are two tables by parity.** `w`/`w_scale` hold the even-numbered experts at
+`[N, K]` and `w_odd`/`w_odd_scale` the odd ones at `[N_odd, K_odd]` (defaulting to `N`, `K`); expert
+`e` is entry `e / 2` of its class. Every entry of one table shares a geometry, and a rank that holds
+an uneven slice of every expert's width (three 128-column blocks of one parity's experts and two of
+the other's, which is how a five-block expert splits evenly across two ranks on average) has two.
+`parts` stacked parts run along both the weight rows and the output columns (two for a fused
+gate/up); the output is `max(N, N_odd)` wide, and a narrower class fills the leading columns of each
+output part and writes zeros after them, so the gated quantiser behind it reads one layout for every
+row. The weight list is the even class's codes, its scales, then the odd class's codes and scales.
 
-**`moe_gemm_q_mod4` is the same GEMM over four classes, by the expert's number mod 4.**
-`w`/`w_scale` hold class 0 at `[N, K]` and `w_q`/`w_q_scale` class `q` at `[N_q, K_q]` (defaulting
-to `N`, `K`); expert `e` is entry `e / 4` of class `e % 4`, so class `q` holds `ceil((n_expert - q) /
-4)` of them. Four ranks splitting a five-block expert cannot share the extra block evenly over two
-classes -- whichever two ranks take it carry three blocks of every even/odd pair against the other
-two's two -- and over four they can: rank `r` takes two blocks of class `r` and one of each other,
-five of every four experts on every rank. It is a separate op and not a parameter on `moe_gemm_q`
-because the declaration divides a table op's weights over its table operands by count alone: the
-operand list is the class count. Everything else -- `parts`, the zero fill of a narrower class, `a_order`
--- is `moe_gemm_q`'s, and the weight list is class 0's codes and scales, then class 1's, 2's and
-3's.
+**`moe_gemm_q_mod4`** is the same GEMM over four classes by the expert's number mod 4. `w`/`w_scale`
+hold class 0 at `[N, K]` and `w_q`/`w_q_scale` class `q` at `[N_q, K_q]` (defaulting to `N`, `K`);
+expert `e` is entry `e / 4` of class `e % 4`, so class `q` holds `ceil((n_expert - q) / 4)` of them.
+Four ranks splitting a five-block expert cannot share the extra block evenly over two classes, but
+over four they can: rank `r` takes two blocks of class `r` and one of each other, five of every four
+experts on every rank. It is a separate op, not a parameter on `moe_gemm_q`, because the declaration
+divides a table op's weights over its table operands by count alone, so the operand list is the
+class count. Everything else (`parts`, the zero fill, `a_order`) is `moe_gemm_q`'s, and the weight
+list is class 0's codes and scales, then class 1's, 2's and 3's.
 
-### `a_order`: which rows a grouped GEMM's activation has
+**The codebook forms** (`w4nla8h`, `w4nl64a8h`, `w4nl32a8h`, `w5nl64a8h`; `docs/MOE-W4.md`) hold
+u4 or u5 codes into an f32 table of 16 or 32 levels, declared as one view over the planes
+`codes,table`, and a scale per (row, group of K): bf16 per 128, or E4M3 per 64 or 32 declared with
+its fixed f32 level as `scale,scale.1`. Element (n, k) of an expert is `table[code] * scale`, times
+`scale.1` where there is one. The encoding's `fwht128` is in the stored weight and in the
+activation `had_quant_act_fp8` writes, so the GEMM applies none. On the host, a view of several
+planes is stored in the joined form of `abi/rad_planes.h`; libref's and libavx's hooks accept
+exactly the planes `dtype` names (code width and table length, scale dtype and group, `fwht128`)
+and refuse any other selection at declare with `RAD_E_DTYPE`. libref computes the form as
+`gemm_nt_q` does: per weight group the sub-sum of table values times activation codes, then
+`(sub * sa) * sb` with `sb` the scale times its level. The logical form the oracle and rad-kbench
+pass (table entries for codes, scale products for scales) goes through the same chain, bit for
+bit. libr4d sums each 64- or 32-wide group under its scale before the activation's scale per 128,
+and libavx folds both scales into the operands before one sum over K; both differ from libref in
+the last bits only.
 
-A routed block runs two `moe_gemm_q` ops and **they disagree about what a row of `a` is**, which is
-why this is a parameter and not a convention.
+**`moe_gemm_q` is a separate op, not a `dtype` on `moe_gemm`**, for the reason `gemm_nt_q` is
+separate from `gemm_nt`: the operand list differs and operands are positional. The group sub-sum is
+accumulated from the raw codes and scaled once per group, as `gemm_nt_q` does; the two
+references must agree in the last bits or `rad-kbench` blames a kernel for a choice made in
+`libref`.
 
-- The **gate_up** projection reads the block's normed input: one row per **token**. A sorted row
-  `i` belongs to the pair `sorted_tok[i] = token * top_k + slot`, so it must gather
-  `a[sorted_tok[i] / top_k]`. That is `a_order = "token"`, the default.
-- The **down** projection reads gate_up's output through the gated quantiser, which is already one
-  row per **(token, slot)** in the scatter's own order. Row `i` is row `i`. That is
-  `a_order = "sorted"`.
+**`moe_gemm`** is what a model served at bf16 runs, and libr4d serves it at `dtype` bf16: one weight
+table of the checkpoint's own row-major `[N, K]` planes, read with no layout hook, so a container
+stores an expert as the safetensors file holds it. It has no parity classes and no `parts` (those
+exist because a quantised expert's width must fall on its scale blocks), and its rows go through
+the same run grouping and the same three forms as `moe_gemm_q`'s kernels, byte-identical to each
+other.
+
+**`scale_rows`** is the per-token scalar gate: `y[m, i] = x[m, i] * act(s[m])`, one scalar per row
+broadcast across it. `mul` broadcasts one row down the rows, and one op with both rules would be
+ambiguous when `rows == n`. `act` is `"sigmoid"` or `"none"` and applies to the scalar. Qwen3.5-MoE's
+`shared_expert_gate` is a `[1, n_embd]` projection whose one output per token gates the shared
+expert's contribution, and this is that multiply. With `add` present it is
+`y = bf16(x * act(s)) + add`, the product narrowed before the sum as the unfused pair stores it.
+
+### `a_order`
+
+A routed block runs two `moe_gemm_q` ops, and they disagree about what a row of `a` is, so this is
+a parameter, not a convention.
+
+- The **gate_up** projection reads the block's normed input, one row per token. Sorted row `i`
+  belongs to the pair `sorted_tok[i] = token * top_k + slot`, so it gathers `a[sorted_tok[i] / top_k]`:
+  `a_order = "token"`, the default.
+- The **down** projection reads gate_up's output through the gated quantiser, already one row per
+  (token, slot) in the scatter's order, so row `i` is row `i`: `a_order = "sorted"`.
 
 `a_scale` has a row for every row `a` has, either way.
 
-**Why it is said and not derived.** The row count gives it away — `M` against `M * top_k` — and
-deriving it is the tempting shortcut. It is also the shortcut no harness catches: a kernel and a
-reference that *both* gather agree to 1e-4 on every case, and `rad-kbench` builds each operand from
-the op's own shape hook, so a hook describing `a` at the extent the gather wants builds a case that
-is self-consistent and wrong. Served, the down projection hands every slot of a token the *first*
-slot's intermediate — at decode, where a step carries one token, all `top_k` experts read slot 0 —
-and the model runs, and answers fluently, and gets facts wrong. An operand whose meaning changes
-with its extent cannot be checked by a harness that sizes the operand from the same reading.
-
-**`moe_gemm_q` is a separate op and not a `dtype` on `moe_gemm`**, for the same reason `gemm_nt_q`
-is separate from `gemm_nt`: the operand LIST differs, operands are positional, and an op whose
-count depends on a string means different things to different kernels. The group sub-sum is
-accumulated from the raw codes and scaled once per group, exactly as `gemm_nt_q` does — the two
-references have to agree in the last bits or `rad-kbench` blames a kernel for a choice made in
-`libref`.
-
-**`moe_gemm` itself is what a model served at bf16 runs**, and libr4d serves it at `dtype` bf16:
-one weight table of the checkpoint's own row-major `[N, K]` planes, read with no layout hook, so a
-container stores an expert as the safetensors file holds it. It has no parity classes and no
-`parts` — those exist because a quantised expert's width must fall on its scale blocks, and an
-unscaled plane has none — and its rows go through the same run grouping and the same three forms
-as `moe_gemm_q`'s kernels, byte-identical to each other.
-
-**`scale_rows` is the per-token scalar gate**, and it exists because `mul`'s broadcast is the wrong
-one. `mul` lets `b` carry a single ROW broadcast down the rows; a shared-expert gate is a single
-COLUMN broadcast across them — `y[m, i] = x[m, i] * act(s[m])` — and adding a second broadcast rule
-to `mul` would make the two ambiguous exactly when `rows == n`. `act` is `"sigmoid"` or `"none"`.
-Qwen3.5-MoE's `shared_expert_gate` is a `[1, n_embd]` projection whose one output per token gates
-the shared expert's contribution, and this is that multiply.
+It is stated, not derived from the row count (`M` against `M * top_k`), because no harness would
+catch a wrong derivation: a kernel and a reference that both gather agree on every case, and
+`rad-kbench` sizes each operand from the op's own shape hook, so a hook describing `a` at the extent
+the gather wants builds a self-consistent, wrong case. Served, the down projection would hand every
+slot of a token the first slot's intermediate, and the model would answer fluently and get facts
+wrong.
 
 ## Linear attention (gated delta net)
 
@@ -985,82 +1051,74 @@ the shared expert's contribution, and this is that multiply.
 | `gdn_conv_recurrent_update` | `q_len`(range) `head_k` `head_v` `conv_width` `n_head_v`/opt `scale`:f64/opt `eps`:f64/opt `l2_eps`:f64/opt `softplus_thr`:f64/opt `act`:str/opt `state_fp16`/opt `state_form`:str/opt | `x`, `conv_w`w, `conv_b`w?, `conv_state`:inout, `conv_idx`, `a`,`b`,`A_log`w,`dt_bias`w,`state`:inout,`state_idx`,`num_accepted`,`cu`,`z`,`norm_w`w → `o`,`o_q`?,`o_scale`? |
 | `gdn_gated_rmsnorm` | `M`(range) `channels` `eps`:f64 `act`:str | `x`, `z`, `w`w → `o` |
 
-**A linear-attention kernel pair must support speculative rollback.** The recurrent state and the
-conv window have already absorbed rejected tokens, so `num_accepted` is a required operand and the
-state cache is a rolling window of `conv_width-1 + n_spec` entries read at the slot the last
-accepted token left. A rejection is a change of read offset, not a recompute. This is part of the
-schema, not an assumption (`spec.md` §10).
+**Speculative rollback is part of the schema** (`spec.md` §10). The recurrent state and the conv
+window have already absorbed rejected tokens, so the state cache is a rolling window of
+`conv_width-1 + n_spec` entries read at the slot the last accepted token left, and a rejection is a
+change of read offset, not a recompute.
 
-**`num_accepted` is ONE-BASED.** It counts the tokens the previous step committed: the one it was
-given, plus however many of its drafts survived. So 1 is an ordinary decode step that drafted
-nothing, which is exactly what these kernels assume when the operand is absent, and 0 is not a
-value either of them can read -- `gdn_conv_update` reads its window at `num_accepted - 1`.
+**`num_accepted` is required and one-based.** It counts the tokens the previous step committed: the
+one it was given plus however many of its drafts survived. 1 is an ordinary decode step that drafted
+nothing, and 0 is not a value either kernel can read (`gdn_conv_update` reads its window at
+`num_accepted - 1`). A non-speculative decode passes all ones. It is one of the two exceptions to
+the union rule: an op that lets the caller omit `num_accepted` has an optional rollback contract.
 
-**`state_form` says what the state cache MEANS, and there are two answers.** `per_candidate` --
-the default, and what this table's operand description above says -- writes one full state per
-candidate token and needs `1 + n_spec` distinct slots in `state_idx`. `anchor` keeps ONE committed
-state a sequence and replays the accepted prefix onto it out of a scratch slot, which is two slots
-whatever the draft depth. The two produce the SAME `o` from a COMPLETELY DIFFERENT `state`, so an
-implementation that serves one and is handed the other computes a correct answer to the other
-question and disagrees with a checker on every element of the cache while agreeing on every
-element of the output. That is why it is declared and not inferred: the index row's width does not
-say which, and neither does anything else a kernel can see.
+**`cu` is required by every gdn kernel, decode included**, the other exception. `gdn_conv_update`
+and `gdn_recurrent_update` read `cu[n]` and `cu[n+1]` before any null test, and the sequence count
+is `cu`'s length minus one; nothing else in the argument list carries it. A caller working from a
+schema that made `cu` optional would pass a null and fault rather than be refused.
 
-A caller declares it; an implementation that serves only one form REFUSES the other by name.
-libref serves `per_candidate`. The engine picks the form from whether the deployment speculates,
-which is the same condition that sizes the state pool.
+**`state_idx` is `[n_seq, W]`, and W is the group's, not the op's.** Column 0 is the sequence's
+state. A kernel that needs somewhere to put what it cannot commit yet may ask for more columns, and
+those are its scratch: the caller stages the row, zeroes every slot it names when the sequence is
+admitted, zeroes the scratch again after any step that ran a different path over the sequence (a
+chunked prefill commits the state directly and writes no scratch), and otherwise does not look
+inside. `gdn_chunk_scan` takes the same row and reads column 0.
 
-It is also REQUIRED rather than optional, which is one of the two places the union rule is
-deliberately not applied: an op that lets the caller omit `num_accepted` is an op whose rollback
-contract is optional. A non-speculative decode passes all ones.
+**`state_form` says what the state cache means.** `per_candidate`, the default, writes one full
+state per candidate token and needs `1 + n_spec` distinct slots in `state_idx`. `anchor` keeps one
+committed state per sequence and, beside it, the few hundred floats per head each token's rank-1
+update needs; the next step replays the accepted prefix onto the state out of that scratch slot. That
+is two slots whatever the draft depth, against `1 + n_spec` full states (1.3 GiB a sequence on
+Qwen3.8-27B), and less write traffic. A zeroed scratch block replays as the identity, so "zero it
+and pass `num_accepted` 1" is the correct handover out of a prefill.
 
-**`state_idx` is `[n_seq, W]`, and W is the group's, not the op's.** One column is the sequence's
-state. A kernel that needs somewhere to put what it cannot commit yet may ask for more, and the
-columns after the first are ITS scratch: the caller stages the row, zeroes every slot it names when
-the sequence is admitted, zeroes the scratch again after any step that ran a different path over
-the same sequence (a chunked prefill commits the state directly and writes no scratch), and
-otherwise does not look inside. `gdn_chunk_scan` takes the same row and reads column 0.
+The two forms produce the same `o` from a different `state`, so an implementation handed the other
+form computes a correct output and disagrees with a checker on every element of the cache. The index
+row's width does not say which form is meant, so it is declared, not inferred: the engine passes
+`anchor` when the deployment speculates and `per_candidate` otherwise (the condition that sizes the
+state pool), and an implementation that serves one form refuses the other.
 
-The point of that freedom is what libr4d does with it. One state per candidate token is the plain
-reading of "the next step reads the slot the last accepted token left", and on Qwen3.8-27B it is
-1.3 GiB a sequence. Instead libr4d keeps ONE committed state and, beside it, the few hundred floats
-a head that each token's rank-1 update needs; the next step replays the accepted prefix onto the
-state out of that block and starts from a state carrying exactly the tokens that survived. Two
-slots a sequence instead of `1 + n_spec`, and less write traffic than the per-candidate form.
+libref serves both, the anchor form in libr4d's cache layout (`libref/ref_gdn.cpp`,
+`AnchorLayout`): `state_idx` has six columns, the anchor in 0-2 and the factor block in 3-5. A paged
+caller's window may shift by -1, 0 or +1 pages a step, so the advanced anchor is published at column
+2 and each factor copy is stamped with its column; the next step reads the stamp at column 4 and the
+anchor at the column it implies. The factors are each token's normalised k and its decay exponent
+and beta (once per 32-row group of `head_v`, each group's rows replaying from their own copy, as
+libr4d reads them), and v, at most 16 tokens a step, with the stamp just past them. A
+head whose `[head_v, head_k]` block cannot hold 16 tokens' factors (under 64 x 64) holds as many as
+fit, so a 16 x 16 head speculates at most 6 tokens deep. With an f32 state the replayed state is bit
+for bit the per-candidate one, so `o` matches the per-candidate form exactly. libavx serves both
+forms in the same layout, its replay bit for bit its own per-candidate state (rad-avx-check runs the
+two over a four-step schedule). The end-to-end check is that greedy speculation emits the same bytes
+as greedy without it.
 
-Two consequences worth naming. A zeroed scratch block replays as the identity, which is what makes
-"zero it and pass `num_accepted` 1" the correct handover out of a prefill. And **libref is
-not a meaningful oracle for `gdn_recurrent_update` while that layout is in use** -- ref implements
-the per-candidate reading, so it would decode another plugin's scratch as its own. The end-to-end
-check that does hold is stronger anyway: greedy speculation must emit the same bytes as greedy
-without it.
+**`gdn_conv_recurrent_update`** (`gdn_conv_update` then `gdn_recurrent_update`, in one launch)
+computes the convolution where the recurrence reads it, so `q`, `k` and `v` are never written. The
+operands are the convolution's inputs (`conv_idx` is its `state_idx`) followed by the recurrence's
+without those three; the parameters are the union of the two ops' under their own names, and both
+ops' rollback and state contracts hold unchanged. `z` and `norm_w` are required, because the fusion
+serves the decode shape, where the fused row norm already puts one workgroup on each (sequence,
+value head). It is byte-identical to the pair. libr4d rewrites a key head's conv state once every
+value head reading it has read it, by an arrival count, so no workgroup waits on another.
 
-**Every gdn kernel takes `cu`, decode included, and that is the other place the union rule is not
-applied.** `gdn_conv_update` and `gdn_recurrent_update` run off the one cumulative-lengths tensor
-on the one step, and both open by reading `cu[n]` and `cu[n+1]` before any null test — the number
-of sequences is `cu`'s length minus one and nothing else in the argument list carries it. A caller
-working from a schema that made `cu` optional passes a null and faults on the dereference rather
-than being refused.
-
-**`gdn_conv_recurrent_update` is the decode pair as one launch**: `gdn_conv_update` followed by
-`gdn_recurrent_update`, with the convolution computed where the recurrence reads it, so `q`, `k`
-and `v` are never written. The operands are the convolution's inputs -- `conv_idx` is its
-`state_idx` -- and then the recurrence's without those three; the parameters are the union of the
-two ops' under their own names, and both ops' rollback and state contracts hold unchanged. `z` and
-`norm_w` are required, because the fold serves the decode shape, where the fused row norm already
-puts one workgroup on each (sequence, value head). It is byte-identical to the pair. libr4d
-rewrites a key head's conv state once all the value heads reading it have read it, by an arrival
-count, so nothing waits on another workgroup.
-
-**The output gate `z` may be a COLUMN SLICE, on both `gdn_recurrent_update` and
-`gdn_gated_rmsnorm`.** The fp8 delta-net block projects `[q|k|v|z]` in one GEMM
+**The output gate `z` may be a column slice**, on both `gdn_recurrent_update` and
+`gdn_gated_rmsnorm`. The fp8 delta-net block projects `[q|k|v|z]` in one GEMM
 (`arch/common/rad_block_gdn_fp8.h`), so the gate is the right-hand `n_head_v * head_v` columns of a
-wider row and its `(token, head)` rows are NOT evenly spaced: heads are `head_v` apart inside a
+wider row and its `(token, head)` rows are not evenly spaced: heads are `head_v` apart inside a
 token and the next token is the slice's own stride away. An implementation that reads one pitch off
-`z` walks into the next token after `n_head_v` rows and is wrong without being out of bounds. The
-three spellings a caller may hand over are `[tokens, heads, head_v]`, a flat
-`[tokens, heads*head_v]` buffer of its own, and that slice; the first two are the same arithmetic
-and the third is what needs the token stride carried separately.
+`z` walks into the next token after `n_head_v` rows and is wrong without going out of bounds. A
+caller may hand over `[tokens, heads, head_v]`, a flat `[tokens, heads*head_v]` buffer of its own,
+or that slice; only the slice needs the token stride carried separately.
 
 ## Collectives
 
@@ -1069,44 +1127,44 @@ and the third is what needs the token stride carried separately.
 | `all_reduce` | `world_size` `numel`(range) `dtype` `exact` `min_bytes`/opt `hops`/opt `overlap`/opt | `x`:inout, `y`:out? |
 | `all_gather` | `world_size` `numel` `dtype` `row`/opt | `x` → `y` |
 
-`exact` separates the exact sum from the quantised wire, and a caller has to say which it wants: a
-request that does not declare it will accept a lossy wire gets no kernel rather than the quantised
-one. That is libr4d's rule and it is right.
+`exact` separates the exact sum from a lossy wire, and a caller must state it: a request that does
+not accept a lossy wire gets no kernel rather than the quantised one.
 
-libr4d separates one-shot from two-shot, at a width that has both, by message size: its two-shot
-rows start above 524288 elements, which makes that a band edge of the ranged `numel`, so a caller
-states nothing for it. `hops` is a caller's request for one or the other (1 or 2); libref accepts
-and ignores it, and no libr4d row reads it. Every all-reduce kernel serves `y` absent, in place.
-`overlap` 1 says the caller issues the collective on its second lane, beside compute: libr4d then
-serves it with rows whose launch is narrow (8 blocks of 256 threads at two ranks), which compute
-the same bits and leave the CUs to the kernels running beside them; libref ignores it.
+`hops` (1 or 2) is a caller's request for one-shot or two-shot; libref accepts and ignores it, and
+no libr4d row reads it. libr4d chooses by message size where a width has both: its two-shot rows
+start above 524288 elements, a band edge of the ranged `numel`. Every all-reduce kernel serves `y`
+absent, in place. `overlap` 1 says the caller issues the collective on its second lane, beside
+compute; libr4d then picks rows with a narrow launch (8 blocks of 256 threads at two ranks, 4 of
+1024 for the four-rank two-shots, exact and tiered-int8) that compute the same bits and leave the
+CUs to the kernels running beside them. libref ignores it.
 
-libr4d serves these at **2, 3, 4 and 8 ranks**. Two ranks have their own kernels (one flag word a
-block, the rotated 6-bit wire, the fused norm-and-reduce forms). The wide family is one template on
-the world size; 4 and 8 have both hops, 3 has the one-shot only -- the two-shot shards the message
-`world` ways and a residual width such as 2560 does not divide by 3 -- and `all_gather` at width
-rides the same instance as the wide `all_reduce` (`ar_gather_3rank`, `_4rank`, `_8rank`). The
-fused forms are declared only at two ranks by the arch blocks, which fall back to the plain pair at
-any other width.
+libr4d serves these at 2, 3, 4 and 8 ranks:
 
-`min_bytes` is the byte floor under which a LOSSY row must serve the message exactly anyway, and it
-is a parameter rather than a constant in the library because it is a property of the link and not
-of the kernel. Compression only pays once the transfer is bandwidth-bound: a decode step
-all-reduces a handful of residual rows and the exact kernel already moves that at most of what the
-interconnect delivers, so the rotate, the pack and the unpack cost more than the bytes they remove.
-A row selected for `exact=0` therefore decides the ROW once, at declare, and the WIRE per launch.
-Absent, the plugin uses its own measured default.
+- Two ranks have their own kernels (one flag word a block), the rotated 6-bit lossy wire and the
+  fused norm-and-reduce forms below.
+- The wider widths share one template on the world size. 3, 4 and 8 have both one-shot and
+  two-shot (the three-rank two-shot shards unevenly), and 3 and 4 have a tiered int8 lossy two-shot.
+  8 has no lossy wire.
+- `all_gather` at those widths rides the same instance as the wide `all_reduce` (`ar_gather_3rank`,
+  `_4rank`, `_8rank`).
+
+`min_bytes` is the byte floor under which a lossy row serves the message exactly. It is a parameter,
+not a library constant, because it is a property of the link: compression pays only once the
+transfer is bandwidth-bound, and for a decode step's few residual rows the rotate, pack and unpack
+cost more than the bytes they remove. A row selected for `exact=0` therefore decides the row once,
+at declare, and the wire per launch. Absent, the plugin uses its own default.
 
 `all_gather.row` is one row of a rank's contribution, in elements. Absent or `0`, `y` is the plain
-concatenation — rank `r`'s slice at `r * numel`. Present, the placement is row-interleaved: `x` is
-`[rows][row]` and `y` is `[rows][world_size][row]`, which is what a vocab-parallel candidate merge
-reads, because it takes one row of gathered candidates per sampled position at a single row stride.
+concatenation, rank `r`'s slice at `r * numel`. Present, the placement is row-interleaved: `x` is
+`[rows][row]` and `y` is `[rows][world_size][row]`, so a vocab-parallel candidate merge reads one
+row of gathered candidates per sampled position at a single row stride.
 
 **`-ffp-contract=off` is mandatory for any quantised cross-rank op.** Two ranks see the two
-dequantised products in the opposite order, and contracting either into an FMA makes them disagree
-by ~1 ULP, which breaks the replicated-state invariant. The build sets it globally for device code.
+dequantised products in opposite order, and contracting either into an FMA makes them disagree by
+~1 ULP, which breaks the replicated-state invariant. `cmake/RadAddPlugin.cmake` sets it for all
+device code.
 
-### The collectives that carry a norm — device-only
+### Collectives with a norm (device-only)
 
 | op | params | operands |
 |---|---|---|
@@ -1118,23 +1176,23 @@ by ~1 ULP, which breaks the replicated-state invariant. The build sets it global
 | `gdn_gated_norm_had_quant_i8` | `M` `n` `head_dim` `group` `eps`:f64 `dtype` `zgrp`/opt `zblk`/opt | `x`, `z`, `w`w → `q`, `scale` |
 
 `wire` is the payload width on the link: 0 is exact bf16, 6 the rotated six-bit form. It is a
-property of the LINK and not of the kernel, which is why it is a parameter — see `all_reduce`'s
-`min_bytes` for the same argument. `x` is INOUT on `ar_rmsnorm_quant_fp8`: it is both the message
-and the input, and the reduced sum lands in it.
+parameter for the same reason as `min_bytes`. `x` is inout on `ar_rmsnorm_quant_fp8`: it is both
+the message and the input, and the reduced sum lands in it.
+
+The norm-carrying forms are two-rank only. `ar_hc_write` and `ar_gather_hc_write` also have an
+exact-wire four-rank form. At other widths the arch blocks issue the plain ops.
 
 `ar_hc_write` is `all_reduce` of `y` followed by `hc_write` of the reduced `y`, for a block whose
-output feeds a gated residual rather than a norm. `y` is INOUT for the same reason `x` is above.
-It serves both wires, one op a wire: a caller declares the rotated form beside the exact one and
-issues whichever the step's message goes out on, and a `wire` of 6 is 6 at every size. At four
-ranks only the exact form exists. A caller states `wire` 0 on the exact form rather than leaving it
-out: a row that serves one wire only says so with a constraint on `wire`, and a constraint on an
-absent key does not hold.
+output feeds a gated residual rather than a norm; `y` is inout as `x` is above. It serves both
+wires, one op per wire: a caller declares the rotated form beside the exact one and issues whichever
+the step's message goes out on, and `wire` 6 is 6 at every size. A caller states `wire` 0 on the
+exact form rather than omitting it: a row that serves one wire says so with a constraint on `wire`,
+and a constraint on an absent key does not hold.
 
-`ar_gather_hc_write` is `moe_gather` followed by `ar_hc_write`: the gather's output IS the
-message, so `y` is written by the gather half before it is reduced in place, and the five gather
-operands and `act` mean exactly what they mean on `moe_gather`. `wire` is `ar_hc_write`'s. On
-either wire, byte-identical to the three kernels it stands in for. At four ranks only the exact
-form exists, as for `ar_hc_write`.
+`ar_gather_hc_write` is `moe_gather` followed by `ar_hc_write`: the gather's output is the message,
+so the gather half writes `y` before it is reduced in place, and the five gather operands and `act`
+mean what they mean on `moe_gather`. `wire` is `ar_hc_write`'s. On either wire it is byte-identical
+to the three kernels it replaces.
 
 ## Vocabulary edges
 
@@ -1148,9 +1206,11 @@ form exists, as for `ar_hc_write`.
 | `ple_conv` | `M`(range) `n` `width` `dilation` `dtype` | `x`, `w`w, `conv_state`:inout, `cu`, `resid`?, `cache_idx`?, `has_init`?, `num_accepted`? → `y` |
 | `causal_conv1d` | `M`(range) `n` `width` `dtype` | `x`, `w`w, `conv_state`:inout, `cu`, `cache_idx`?, `has_init`?, `num_accepted`? → `y` |
 
-Separate from `gemm_nt` because `lm_head` is its own access class (`RAD_ACCESS_VOCAB`) and because
-the sampler wants to fuse against it: at a 151K vocab and batch 256 the logits are ~77 MiB a step,
-and the distributed top-k means a rank never materialises a full row (`spec.md` §9, §13).
+`logits_gemm` is separate from `gemm_nt` because `lm_head` is its own access class
+(`RAD_ACCESS_VOCAB`) and because the sampler fuses against it: under the distributed top-k a rank
+never materialises a full logits row (`spec.md` §9, §13). `M` is one row per sampled position,
+`gather_rows` having run first. A quantised head (block fp8, int8 per row and 128 of K) reaches a
+host kernel joined (Weights of several planes, above).
 
 ### `gather_rows`
 
@@ -1158,11 +1218,9 @@ and the distributed top-k means a rank never materialises a full row (`spec.md`
 |---|---|---|
 | `gather_rows` | `M`(range) `n` `dtype` | `x`, `idx` → `y` |
 
-`gather_rows` is not a convenience. Without it a plugin computes logits for **every** token in a
-prefill chunk instead of the last one per sequence — `n_tok / n_seq` times too much work, and at
-`max_tok` 8192 against a 248K vocab the logits buffer alone is 8 GiB. It is the op that turns
-"correct" into "affordable".
-
+`y[i, :] = x[idx[i], :]`; a negative index writes a zero row. Without it a plugin computes logits for
+every token of a prefill chunk instead of the last one per sequence: `n_tok / n_seq` times the work,
+and at `max_tok` 8192 against a 248K vocab the logits buffer alone is 8 GiB.
 
 ### `scatter_rows`
 
@@ -1170,106 +1228,77 @@ prefill chunk instead of the last one per sequence — `n_tok / n_seq` times too
 |---|---|---|
 | `scatter_rows` | `M`(range) `n` `dtype` | `v`, `idx`, `x`:inout |
 
-`x[idx[i], :] = v[i, :]`, the mirror of `gather_rows`, and `x` is **inout** because the write is
-partial: rows no index names keep what they held. That is what makes it usable against a pool other
-sequences are also in — an op that returned a fresh `x` would have to copy everything it was not
-asked to change.
+`x[idx[i], :] = v[i, :]`, the mirror of `gather_rows`. `x` is inout because the write is partial:
+rows no index names keep what they held, so it can target a pool other sequences also use. Two
+rules differ from the gather, because the destination is live memory:
 
-Two rules differ from the gather, and both follow from the destination being live memory rather
-than a fresh buffer:
+- **A negative index writes nothing.** `gather_rows` reads a zero row for one (the padding a short
+  prefill chunk leaves); here a zero fill would be data loss.
+- **Indices must be distinct**, declared with `RAD_OPD_F_IDX_UNIQUE`. Two rows landing on one
+  destination have no defined winner on a parallel machine, so the reference and a kernel could
+  legitimately disagree.
 
-- **A negative index writes nothing.** `gather_rows` reads a zero row for one, which is the padding
-  convention a short prefill chunk leaves behind. On this side a zero fill would be data loss.
-- **Indices must be distinct**, declared with `RAD_OPD_F_IDX_UNIQUE` rather than left to prose. Two
-  rows landing on one destination has no defined winner on a parallel machine, so permitting it
-  would make this an op whose reference implementation and whose real kernel are allowed to
-  disagree — which is exactly what the oracle exists to rule out.
+The caller is the KV tier traffic (`core/mem/kvtier.h`), where a row is a few hundred bytes and `M`
+separate transfers would be all dispatch cost. A paged pool is layer-major, so within one layer a
+group's blocks are dense rows of `layer_bytes_per_block()`: packing any set of them is a gather and
+restoring them a scatter, one launch per (group, layer) however many blocks move.
 
-It exists for the same reason `gather_rows` does: the alternative is `M` separate transfers, and
-where this op is used a row is a few hundred bytes, so that is dispatch cost with the data as a
-rounding error. The caller is the KV tier traffic (`core/mem/kvtier.h`). A paged pool is
-**layer-major**, so within one layer a group's blocks are dense rows of `layer_bytes_per_block()`
-— which makes packing an arbitrary set of them exactly a gather and restoring them exactly a
-scatter, one launch per (group, layer) however many blocks are moving.
-
-**At `dtype` u8 the rows are opaque bytes**, and libr4d supplies that width as its own kernel pair
-rather than widening the bf16 one. What moves is whatever the attention kernel wrote; calling it
-bf16 would matter, because `libref` is the oracle for every op here and its bf16 path loads through
-float, which is not guaranteed to return a NaN payload unchanged. At u8 every value is 0..255,
-float carries it exactly, and oracle and kernel agree bit for bit on any payload at all.
+At `dtype` u8 the rows are opaque bytes, and libr4d supplies that width as its own kernel pair
+rather than widening the bf16 one. What moves is whatever the attention kernel wrote. Calling it
+bf16 would matter: `libref` is the oracle for every op here and its bf16 path loads through float,
+which need not return a NaN payload unchanged. At u8 every value is 0..255, which float carries
+exactly, so oracle and kernel agree bit for bit on any payload.
 
 ### `embed_lookup`'s `mult`
 
-Every gathered row multiplied by `mult` and rounded once to `x`'s dtype; absent, the gather is a
-plain copy. Gemma scales its embedding by `sqrt(hidden)` held in a bf16 buffer, so the plugin
-passes that value rounded to bf16 (22.625 at a hidden of 512, not 22.6274) and the product is the
-reference's to the bit. `wscale` is not this: it is the scale `embed_lookup_q`'s layout quantises
-with, and `embed_lookup` reads none.
+`mult` (optional, default 1) multiplies the rows that are found, `x[m] = wte[id] * mult`, rounded
+once to `x`'s dtype; a missed row (negative padding or another rank's token) writes zero. Gemma
+scales its embedding by `sqrt(hidden)` held in a bf16 buffer, so the plugin passes that value
+rounded to bf16 (22.625 at a hidden of 512, not 22.6274) and the product is the reference's bit for
+bit. Scaling at the lookup leaves the table plain and tied to the head, as the checkpoint stores
+it.
+
+`wscale` is a different thing: the scale `embed_lookup_q`'s layout quantises the stored table with,
+read back as the dequant. `embed_lookup` reads none, and `embed_lookup_q` takes no `mult`.
 
 ### `embed_lookup`'s `vocab_offset`
 
-`vocab_offset` (optional, default 0) is the first vocabulary row this rank holds. With it,
-`n_vocab` is THIS RANK'S row count -- the meaning it already carries for `logits_gemm` -- and the
-table covers global ids `[vocab_offset, vocab_offset + n_vocab)`. **Token ids stay GLOBAL**: a rank
-subtracts the offset and writes a zero row for an id belonging to another rank, exactly as it does
-for the negative padding id, so summing the ranks reconstructs `x`. Every token lands on exactly
-one rank, which is why the `all_reduce` that follows is declared `exact` rather than taking the
-model's wire setting: it sums disjoint rows, so a lossy wire would be loss on a value that is
-already the answer.
+`vocab_offset` (optional, default 0) is the first vocabulary row this rank holds. With it, `n_vocab`
+is this rank's row count (as it is for `logits_gemm`) and the table covers global ids
+`[vocab_offset, vocab_offset + n_vocab)`. Token ids stay global: a rank subtracts the offset and
+writes a zero row for an id that belongs to another rank, as it does for the negative padding id, so
+summing the ranks reconstructs `x`. Every token lands on exactly one rank, so the `all_reduce` that
+follows is declared `exact` rather than taking the model's wire setting: it sums disjoint rows, and
+a lossy wire would lose precision on values that are already final.
 
-Without it the embedding must be REPLICATED while `lm_head` is row-sharded, and asymmetric sharding
-of the two ends of the same vocabulary is not a design, it is an omission. The table is bf16 even
-in the fp8 checkpoint, so replicating it costs 248320 x 5120 x 2 = 2.43 GiB on every card --
-memory the split hands to the KV cache instead.
+Without it the embedding would be replicated while `lm_head` is row-sharded. The table is bf16
+even in an fp8 checkpoint, so replicating a 248320 x 5120 table costs 2.37 GiB on every card that
+the split gives to the KV cache instead.
 
-One thing is given up and it is worth naming: under a split this kernel can no longer tell a
-garbage id from another rank's token, so the "an id at or above `n_vocab` fails the launch" check
-holds only where the rank holds the WHOLE vocabulary -- `world_size` 1, not merely `vocab_offset`
-0. **Rank 0 of a vocab-parallel split has offset 0** and legitimately sees ids past its own slice
-on most steps, so a check keyed on the offset alone refuses correct calls. Bounding ids is the
-caller's, and the tokeniser and the sampler both already are.
-
-### `embed_lookup`'s runtime `mult`
-
-`mult` (optional f64, default 1) multiplies the rows that are FOUND: `x[m] = wte[id] * mult`.
-A missed row — negative padding or another rank's token — writes zero, not zero times the scale.
-Absent it is the plain gather the op has always been, which is what keeps every other caller in
-the tree bit-identical.
-
-**Not `wscale`.** `wscale` is the scale `embed_lookup_q`'s LAYOUT quantises with — a property of
-the stored table, read back as the dequant. `mult` is applied AFTER the gather, to the rows that
-come out of it; `embed_lookup_q` takes no `mult` at all, because its rows arrive already scaled by
-the table's own dequant.
-
-**Why it exists**: Gemma 4 scales its embedding by `sqrt(n_embd)` at the lookup — the reference's
-`build_inp_embd` and HF's `Gemma4TextScaledWordEmbedding` both do it there, and the checkpoint's
-table is plain. Baking it into the table instead would untie it from the head, which the model
-ties and which the checkpoint stores twice; scaling the lookup leaves the table and the head the
-same tensor the weights loader already maps.
+Under a split the kernel cannot tell a garbage id from another rank's token, so "an id at or above
+`n_vocab` fails the launch" holds only where the rank holds the whole vocabulary (world size 1, not
+merely `vocab_offset` 0: rank 0 of a split has offset 0 and sees ids past its slice on most steps).
+Bounding ids is the caller's job, and the tokeniser and sampler are already bounded.
 
 ### `embed_lookup_q`, the n-gram gather
 
-**A gather from a table quantised with ONE scale for all of it**: `x[m] = wte[id] * scale[0]`.
-Padding and bounds behave exactly as `embed_lookup`'s — a negative id writes a zero row, an id past
-the table fails the launch in the host kernels and writes a zero row in the device one, which
-cannot read its ids before it runs (libr4d's divergence note).
+A gather from a table quantised with one scale for all of it: `x[m] = wte[id] * scale[0]`, an absent
+`scale` being 1. Padding and bounds behave as `embed_lookup`'s, except that an id past the table
+fails the launch in the host kernels and writes a zero row in the device one, which cannot read its
+ids before it runs.
 
-**Why one scale is enough**, measured on the bf16 original: E4M3 carries its own exponent, a row's
-dynamic range in this table is only 2.3×, and the scale sits on a **three-octave plateau** where
-2⁻¹³ through 2⁻¹⁰ all give rel_l2 0.02662 to five digits. A per-row scale buys 2.9%.
-Qwen3.8-Flash-Next-FP8 ships exactly this: 128 E4M3 shards and a single bf16 `weight_scale` of
-1.9932e-4.
+One scale suffices because E4M3 carries its own exponent: on Qwen3.8-Flash-Next's table a row's
+dynamic range is 2.3x and a per-row scale would improve the error by only 2.9%. The FP8 checkpoint
+ships it this way, E4M3 rows with a single bf16 `weight_scale`.
 
-**A separate op and not a `dtype` on `embed_lookup`.** The operand list differs — there is a scale
-— and operands are positional, so an op whose count depends on a string means different things to
-different kernels. It is `gemm_nt_q`'s argument against being a `dtype` on `gemm_nt`. Adding the
-scale to `embed_lookup` as an optional operand would also have moved `x` from slot 2 to slot 3 for
-every caller in the tree.
+It is a separate op, not a `dtype` on `embed_lookup`, because the operand list differs and
+operands are positional; an optional scale operand on `embed_lookup` would also move `x` from slot
+2 to slot 3 for every caller.
 
-**Where it runs is where `--ngram-placement` puts the table**, because the planner runs an op on
-the host when **every weight operand of it** is `Site::Host` and takes that from the table's
-placement. The table is 51.2 GB and is never staged a unit at a time — moving a whole unit to use
-5 KB is the wrong shape — so it is read where it lies:
+Where it runs is where `--ngram-placement` puts the table: the planner runs an op on the host when
+every weight operand of it is `Site::Host`, and takes that from the table's placement. The table is
+51.2 GB and is never staged a unit at a time (moving a whole unit to use 5 KB is the wrong shape),
+so it is read where it lies:
 
 | placement | the table | the gather |
 |---|---|---|
@@ -1278,177 +1307,155 @@ placement. The table is 51.2 GB and is never staged a unit at a time — moving
 | `ram`, no device kernel | a locked copy (`core/format/table_copy.h`) | libavx's host kernel |
 | `vram` | the card, every rank holding all of it | libr4d's device kernel |
 
-`hipHostRegister` on the container's mapping is not one of them: it would force all of the file
+`hipHostRegister` on the container's mapping is not an option: it would force the whole file
 resident.
 
-**The host gather keeps its own row cache.** The container is mmapped, so the table is at a host
-address on open. libavx keeps the rows a gather has touched in a row cache of its own and reads a
-miss straight from the file with O_DIRECT (`libavx/avx_ngram.cpp`): the page cache would map a
-4 KiB page per 160-byte row. The reads keep the alignment the filesystem reports for direct I/O, or
-its block size where it reports none, as btrfs does; one read of the table proves it before the
-first row is served. A filesystem with no direct I/O at all cannot hold a container with this table
-on `disk`.
+**Host gather.** libavx keeps the rows a gather has touched in a row cache of its own and reads a
+miss from the file with `O_DIRECT` (`libavx/avx_ngram.cpp`); the page cache would map a 4 KiB page
+per 160-byte row. Reads keep the alignment the filesystem reports for direct I/O, or its block size
+where it reports none (as btrfs does); one read of the table proves it before the first row is
+served. A filesystem without direct I/O cannot hold a container with this table on `disk`.
 
-**The device gather is libr4d's `embed_lookup_q_bf16`**: four entries a thread, each E4M3 code
-decoded exactly, multiplied by the scale in f32 and rounded to nearest even — the value libavx's
-lookup table holds, to the bit. It reads the ids and writes `e` in the host arena, where the
-architecture declares them for the host gather, so the step has no host op left in it.
+**Device gather.** libr4d's `embed_lookup_q_bf16` handles four entries a thread, decodes each E4M3
+code exactly, multiplies by the scale in f32 and rounds to nearest even: the value libavx's lookup
+table holds, bit for bit. It reads the ids and writes `x` in the host arena, where the architecture
+declares them for the host gather, so the step has no host op left in it.
 
-The table has to be a weight operand at all for the host site to be reachable: `gather_rows` takes
-a plain `IN` operand and would never be placed there. And the host kernel has to live in a
-production plugin — libavx, the host kernel library — because `rad_gate_reference_kernels`
-refuses to serve on libref by design.
+The table must be a weight operand for the host site to be reachable at all: `gather_rows` takes a
+plain input and would never be placed there. The host kernel lives in a production plugin (libavx)
+because `rad_gate_reference_kernels` refuses to serve on libref.
 
-### `ngram_ids`, and the gather that is not an op
+### `ngram_ids`
 
-**Qwen4-Exp's Per-Layer Embedding gives one layer a second embedding table addressed by a HASH of
-the last `ngram` tokens.** Qwen3.8-Flash-Next's is 320,001,536 rows of 160 — 102 GB, 51 of the
-model's 180 billion parameters — read sixteen rows a token. `ngram_ids` computes those row ids:
+Qwen4-Exp's Per-Layer Embedding gives one layer a second embedding table addressed by a hash of the
+last `ngram` tokens. Qwen3.8-Flash-Next's has 320,001,536 rows of 160 (102 GB at bf16, 51 of the
+model's 180 billion parameters), read sixteen rows a token. `ngram_ids` computes those row ids:
 
     mixed(k) = t0*mult[0] ^ t1*mult[1] ^ ... ^ tk*mult[k]
     ids[h]   = remainder(mixed(b+1), vocab_sizes[h]) + offsets[h]
 
-where `heads` is `ngram - 1` equal blocks and block `b` uses the `(b+2)`-gram. `t_s` is the token
-`s` positions back, **or the EOS token if the shift would cross one** — and once a shift falls back
-to EOS every deeper shift does too. `mult`, `vocab_sizes` and `offsets` are weights because the
-checkpoint carries them; the reference builds them from a seed and a prime search at construction
-time, and re-deriving sixteen numbers the container already holds would be a second source for them.
+where the `heads` are `ngram - 1` equal blocks and block `b` uses the `(b+2)`-gram. `t_s` is the
+token `s` positions back, or the EOS token if the shift would cross one, and once a shift falls
+back to EOS every deeper shift does too. `mult`, `vocab_sizes` and `offsets` are weights because the
+checkpoint carries them; re-deriving them from the reference's seed and prime search would be a
+second source.
 
-**`state` is a rolling window of committed ids**, `ngram - 1 + n_spec` deep, read at
-`num_accepted - 1` and rewritten in the layout `ple_conv` describes below — operand for operand,
-including the two layouts `num_accepted`'s presence chooses between. **A cold window is EOS and not
-zero**, which is the one place it differs from a convolution window: zero is a real token id.
+**`state` is a rolling window of committed token ids**, `ngram - 1 + n_spec` deep, read at
+`num_accepted - 1` and rewritten in `ple_conv`'s layouts (below), including the two that
+`num_accepted`'s presence chooses between. A cold window is EOS, not zero, since zero is a real
+token id. It is a state rather than a plain input because the contract is already paid for: the
+dilated convolution downstream carries a window with this rollback contract, so PLE needs
+`num_accepted`, `cache_idx` and `has_init` regardless, while nothing in the engine derives "the ids
+before this step" (`DeriveInput` carries positions and cu_seqlens and no token ids, and an input
+would need a new core derivation and a wider `DeriveFn`). `RAD_KV_CONV` is already "per-sequence, a
+rolling window of width-1 + num_spec entries", and `conv_state_index` already derives its read
+cursor.
 
-**The ids are a STATE and not a plain input**, and the reason is that the contract is already paid
-for. A state needs a rollback contract and an input does not, which reads like an argument for the
-input — but the dilated convolution downstream carries a 9-timestep window with exactly this
-contract, so PLE pays for `num_accepted`, `cache_idx` and `has_init` regardless, and against that a
-plain input costs *more*. Nothing in the engine derives "the ids before this step": `DeriveInput`
-carries positions and cu_seqlens and no token ids at all, so an input would mean a new core
-derivation and a widened `DeriveFn` signature to serve one op. `RAD_KV_CONV` is already
-"per-sequence, a rolling window of width-1 + num_spec entries", and `conv_state_index` already
-derives the read cursor for it.
+The gather is `embed_lookup_q`, not `gather_rows`, because the table must be a weight operand for
+`Site::Host` to be reachable.
 
-**The gather is `embed_lookup_q`, not `gather_rows`.** The table has to be a WEIGHT operand or
-`Site::Host` is unreachable, because the planner puts an op on the host only when every weight
-operand of it is `Site::Host`, and `gather_rows` takes a plain `IN` operand.
+**`ahead_ids` and `ahead` fetch the next chunk's rows a step early.** A prefill chunk gathers `heads`
+rows a token, and with the table on `disk` and text the row cache has not seen, most are random
+reads of the container file while the card idles behind the host-site op. The next chunk of the
+prompt is already known (`RadBatch::n_ahead`, stored in `token_ids` after the step's own tokens), so:
 
-**`ahead_ids` and `ahead`: the next chunk's rows, a step early.** A prefill chunk gathers `heads`
-rows a token and, with the table on `disk` and text the row cache has not seen, most of them are
-random reads of the container file — ~30 ms a 2048-token chunk on an NVMe, with the card idle behind
-the host-site op.
-The next chunk of the prompt is already known (`RadBatch::n_ahead`, which stores it in `token_ids`
-after the step's own tokens), so:
+- `ngram_ids` with `ahead_ids` present reads that many tokens past the step's in `tok`, as a
+  continuation of the last sequence, and writes their ids there: the same ids the step that runs
+  those tokens will compute. The window it writes back is the step's own.
+- `embed_lookup_q` with `ahead` present may start reading those rows once its own are gathered. No
+  output depends on it, so a kernel may ignore it; libavx's row hands them to a reader thread that
+  fills its row cache while the step runs.
 
-- `ngram_ids` with `ahead_ids` present reads `tok` that many tokens past the step's, as a
-  continuation of the LAST sequence, and writes their ids there — exactly the ids the step that
-  runs those tokens will compute, since it hashes the same history. The window it writes back is
-  the step's own and never sees them.
-- `embed_lookup_q` with `ahead` present may start reading those rows once its own are gathered.
-  No output depends on it, so a kernel may ignore it; libavx's row hands them to a reader thread
-  that fills its row cache while the step runs, and the next call finds them there.
+### `ple_gate`
 
-### `ple_gate`, and what the convolution branch does not see
-
-PLE's mixing coefficient is a **dot product between the n-gram embedding and the residual stream** —
-one scalar per hyper-connection stream, per token:
+PLE's mixing coefficient is a dot product between the n-gram embedding and the residual stream, one
+scalar per hyper-connection stream per token:
 
     K[c] = grouped_rmsnorm(k)[c] * (w_key + wadd)      k is key_proj(embedding)
-    Q[c] = grouped_rmsnorm(q)[c] * (w_query + wadd)    q is the INCOMING hc stream
+    Q[c] = grouped_rmsnorm(q)[c] * (w_query + wadd)    q is the incoming hc stream
     s[c] = sum_d K[c][d] * Q[c][d] / sqrt(n)
     s[c] = sign(s[c]) * sqrt(max(|s[c]|, gate_eps))
-    gv[c] = sigmoid(s[c]) * v                          v is value_proj(embedding), ONE row
+    gv[c] = sigmoid(s[c]) * v                          v is value_proj(embedding), one row
     gvn   = grouped_rmsnorm(gv) * (w_conv + wadd)
 
-**The signed square root keeps the sign**, so a stream whose embedding opposes the residual gets a
-gate below a half rather than a gate of zero. The clamp is on the **magnitude** and the sign comes
-from the **original**, which matters at exactly one value: torch's `sign(0)` is 0, so a dot product
-of exactly zero comes out as zero and not as `sqrt(gate_eps)`. Clamping first and re-signing the
-clamped value would give 1e-3 there.
+- The signed square root keeps the sign, so a stream whose embedding opposes the residual gets a
+  gate below one half rather than zero. The clamp is on the magnitude and the sign comes from the
+  original, which matters at one value: torch's `sign(0)` is 0, so a dot product of exactly zero
+  stays zero rather than becoming `sqrt(gate_eps)`.
+- Both outputs leave the op: the dilated convolution reads the normed copy and the residual add the
+  un-normed one, and recomputing either outside would be a second definition of the norm.
+- The convolution branch does not see the gate. `gv[c]` is a scalar times one shared `v` row and the
+  norm's rms is per `n`-wide stream, so the gate divides back out: `gvn[c][d]` is `v[d]/rms(v)`
+  times its gain whatever the gate did. A fused kernel whose `gvn` varies with the gate is wrong. It
+  is not a shortcut, though: `gv` is narrowed to its dtype before the third norm reads it, so
+  computing `gvn` from `v` directly differs in the last bits.
 
-**Both outputs leave the op.** The dilated convolution that follows reads the *normed* copy and the
-residual add reads the *un-normed* one — two different tensors, and recomputing either outside
-would be a second definition of the norm.
+It is one op rather than six (three grouped norms, a reduction, a scalar nonlinearity and a broadcast
+multiply, all over `[M, hc*n]`, 10240 wide on Qwen3.8-Flash-Next), because six memory-bound launches
+would each pay the per-kernel floor; `hc_read` is the same argument at the same width.
 
-**AND THE CONVOLUTION BRANCH DOES NOT SEE THE GATE.** `gv[c]` is a scalar times one shared `v` row,
-and `norm_conv`'s rms is taken per `n`-wide stream — so the gate appears in both the numerator and
-the rms and divides straight back out. `gvn[c][d]` is `v[d]/rms(v)` times its gain, whatever the
-gate did. This is a sharp invariant to check a kernel against: a fused implementation whose `gvn`
-varies with the gate has folded something it should not have. It is *not* a shortcut to take —
-`gv` is narrowed to its dtype before the third norm reads it, so computing `gvn` from `v` directly
-would differ in the last bits.
-
-**One op and not six.** Three grouped norms, a reduction, a scalar nonlinearity and a broadcast
-multiply over tensors that are all `[M, hc*n]` — 10240 wide here — would be six launches against a
-~4.5 µs per-kernel floor, every one of them memory-bound. `hc_read` is the same argument at the
-same width.
-
-### `ple_conv`: a dilated convolution cache is not a conv cache
+### `ple_conv`
 
     y[t] = resid[t] + silu( sum_j w[c][j] * x[t - (width-1-j)*dilation] )
 
-**The dilation changes how deep the history is, and that is the whole trap.** At Qwen4-Exp's width
-4 and dilation 3 the taps are **9, 6, 3 and 0** timesteps back, so a sequence carries
-`(width-1)*dilation = 9` timesteps — not `width-1 = 3`. A cache sized for the undilated width keeps
-only the three most recent values and reads zeros where the deepest tap belongs, which is a model
-that generates fluently from a slightly wrong context.
+The dilation sets the history depth. At Qwen4-Exp's width 4 and dilation 3 the taps are 9, 6, 3 and
+0 timesteps back, so a sequence carries `(width-1)*dilation = 9` timesteps, not `width-1 = 3`. A
+cache sized for the undilated width reads zeros where the deepest tap belongs, and the model still
+generates fluently from a slightly wrong context.
 
-The state is `[n_slots, n, state_len]` with slot `i` holding the value at relative position
-`i - (width-1)*dilation`, which is `gdn_conv_prep`'s convention with the dilation folded in.
-`has_init` 0 means that window is **zeros** rather than whatever the slot last held — without it a
-fresh sequence landing on a recycled slot convolves the previous sequence's tail into its first
-nine tokens.
+The state is `[n_slots, n, state_len]`, slot `i` holding the value at relative position
+`i - (width-1)*dilation` (`gdn_conv_prep`'s convention with the dilation folded in). `has_init` 0
+means that window is zeros rather than whatever the slot last held; without it a fresh sequence on a
+recycled slot convolves the previous sequence's tail into its first nine tokens.
 
-**`num_accepted` shifts the READ offset, and its presence picks what the step leaves behind.** The
+`num_accepted` shifts the read offset, and its presence picks what the step leaves behind. The
 manager sizes the state `(width-1)*dilation + n_spec` deep so a speculative step can read at an
-offset inside it. What the next step's offset must find is the history ending at the last token
-this step *committed*, and which token that is depends on the kind of step:
+offset inside it. The next step's offset must find the history ending at the last token this step
+committed:
 
-- **Present — a decode step**, any of whose drafts a verify may reject. The window is rewritten the
-  way `gdn_conv_update` rewrites its own: the history read, shifted down by one, then every input of
+- **Present: a decode step**, whose drafts a verify may reject. The window is rewritten as
+  `gdn_conv_update` rewrites its own: the history read, shifted down by one, then every input of
   the step, so slot `i` holds position `i + 1` of (window read ++ step). A next step that kept `k`
   of these tokens reads at `k - 1` and finds the history ending at the `k`-th. It needs
   `(width-1)*dilation - 1` slots plus one a token, which a step of `1 + n_spec` tokens gets.
-- **Absent — every token commits**, which is the prefill chunk. The read is at offset zero and the
-  last `(width-1)*dilation` inputs land at offset zero, where the next step's `num_accepted` of 1
-  reads them.
+- **Absent: every token commits**, as in a prefill chunk. The read is at offset zero and the last
+  `(width-1)*dilation` inputs land at offset zero, where the next step's `num_accepted` of 1 reads
+  them.
 
-The two agree when the step has one token, and no single layout can serve both at several: at
-offset zero one must hold the history ending at the step's first token and the other the history
-ending at its last. An architecture therefore issues the op once over its decode rows and once over
-its prefill rows, as it already does the two `gdn` convolutions.
+The two agree for a one-token step, and no single layout serves both at several tokens: at offset
+zero one needs the history ending at the step's first token and the other at its last. An
+architecture therefore issues the op once over its decode rows and once over its prefill rows, as it
+does the two `gdn` convolutions.
 
-**One op where the gated delta net has two.** `gdn_conv_prep` and `gdn_conv_update` are separate
-because the work *around* their convolutions differs — one splits a fused projection and takes an
-l2 norm, the other does not. PLE's convolution is the same arithmetic at prefill and at decode, so
-it takes the union of the two contracts instead: `has_init` is prefill's question and
-`num_accepted` is decode's.
+`gdn_conv_prep` and `gdn_conv_update` are separate because the work around their convolutions
+differs (one splits a fused projection and takes an l2 norm). PLE's convolution is the same
+arithmetic at prefill and decode, so one op takes the union of both contracts: `has_init` is
+prefill's question and `num_accepted` decode's.
 
-The residual add is folded in because the reference is `gv + silu(conv(gvn))` and the two tensors
-are both `[M, hc*n]` — 10240 wide here. `resid` absent leaves the plain convolution.
+The residual add is folded in because the reference is `gv + silu(conv(gvn))` and both tensors are
+`[M, hc*n]`. `resid` absent leaves the plain convolution.
 
-### `causal_conv1d`: `ple_conv` without the PLE
+### `causal_conv1d`
 
     y[t] = sum_j w[c][j] * x[t - (width-1-j)]
 
-LFM2's short convolution: depthwise, causal, undilated, with no activation and no residual — the
-gates around it are separate `mul`s in the architecture. The window and its three optional operands
+LFM2's short convolution: depthwise, causal, undilated, with no activation and no residual (the
+gates around it are separate `mul`s in the architecture). The window and its three optional operands
 are `ple_conv`'s at dilation one, so an architecture issues it the same way, once over its decode
 rows with `num_accepted` and once over its prefill rows without. libr4d, libref and libavx each
 serve both ops from one implementation.
 
 ## Sampling
 
-Every sampler is a kernel, not a host lift. `llama.cpp`'s chain is kept as a **host reference**
-that `rad-kbench` compares the device samplers against (`spec.md` §13).
+Every sampler is a kernel, not a host lift. `rad-kbench` checks the device samplers against a host
+reference that follows llama.cpp's chain (`spec.md` §13).
 
-**EVERY PER-REQUEST SCALAR IS AN OPERAND, NOT A PARAMETER.** `params` is `[M]` rows of
-`RadSampleParams` (`abi/rad_sample.h`), uploaded once a step, and it carries `temp`,
-`top_k`, `top_p`, `min_p`, `typical_p`, the three penalties, the DRY and XTC settings, the seed and
-position, the history window and the grammar's `mask_row`. Not one of them is in a params cell
-below, and the reason is that a parameter is GEOMETRY: the selector matches on it and freezes it at
-declare (`spec.md` §2.2), so two requests in one batch with different `top_p` would be two
-resolutions of one op — which is not something a batch can contain.
+**Per-request settings are operands, not parameters.** `params` is `[M]` rows of `RadSampleParams`
+(`abi/rad_sample.h`), uploaded once a step, carrying `temp`, `top_k`, `top_p`, `min_p`,
+`typical_p`, the three penalties, the DRY and XTC settings, the seed and position, the history
+window and the grammar's `mask_row`. A parameter is geometry: the selector matches on it and freezes
+it at declare (`spec.md` §2.2), so two requests in one batch with different `top_p` would need two
+resolutions of one op. The one exception is `sample_chain` (below).
 
 | op | params | operands |
 |---|---|---|
@@ -1463,21 +1470,27 @@ resolutions of one op — which is not something a batch can contain.
 | `sample_merge_topk` | `M`(range) `n_cand` | `gathered`, `params` → `cand_idx`, `cand_val` |
 | `sample_logprobs` | `M`(range) `n_vocab` `k` `vocab_off`/opt | `logits`, `params` → `stats` |
 
-`sample_mask` is where a GBNF grammar lands: the state machine stays on host and what crosses is a
-token bitmask per sequence, 19 KiB at a 151K vocab, cheap enough to upload every step.
+`sample_mask` is where a GBNF grammar lands: the state machine stays on the host, and what crosses
+is a token bitmask per sequence (~19 KB at a 151K vocab), cheap enough to upload every step. A set
+bit means allowed.
 
-`sample_logprobs` is what an OpenAI `logprobs` field or llama-server's `n_probs` reads. It runs on
-the RAW logits, before any stage has touched them, and only for a row whose flags carry
-`RAD_SP_LOGPROBS`; other rows are not written. `stats` is `[M, 2 + 2k]` f32: the row's maximum, the
-sum of `exp(l - max)` over it, and its `k` largest as (id, logit) pairs, descending, ties to the
-lower id, the id written as a float (exact below 2^24) and GLOBAL under a split vocabulary
-(`vocab_off` added). A slot past the vocabulary is id -1, logit -infinity. `k` is geometry: the one
-width every request's `top_logprobs` fits in. The engine declares 21 -- OpenAI's bound of 20, plus
-one so that a row is 44 floats, whole 16-byte words, which the vocab-parallel `all_gather` moves. A
-token's logprob is `l - max - log(sum)`; under a split vocabulary the host merges the ranks' rows
-(the maxima and sums by the usual rescale, the pairs by value).
+`sample_penalties` and `sample_dry` read global token ids from `history` and write this rank's
+logits, so under a split vocabulary they take `vocab_off`, as `sample_topk` does, and a token outside
+the shard is another rank's to penalise. Their `penalty_last_n` / `dry_penalty_last_n` window is
+llama.cpp's: 0 turns the stage off for the row, and a negative value takes the whole history.
 
-### Stages the decomposed chain does not carry
+`sample_logprobs` serves an OpenAI `logprobs` field or llama-server's `n_probs`. It runs on the raw
+logits, before any stage has touched them, and only for a row whose flags carry `RAD_SP_LOGPROBS`;
+other rows are not written. `stats` is `[M, 2 + 2k]` f32: the row's maximum, the sum of
+`exp(l - max)` over it, and its `k` largest as (id, logit) pairs, descending, ties to the lower id,
+the id written as a float (exact below 2^24) and global under a split vocabulary (`vocab_off`
+added). A slot past the vocabulary is id -1, logit -infinity. `k` is geometry, the one width every
+request's `top_logprobs` fits in: the engine declares 21, OpenAI's limit of 20 plus one so a row is
+44 floats, whole 16-byte words, which the vocab-parallel `all_gather` requires. A token's logprob is
+`l - max - log(sum)`; under a split vocabulary the host merges the ranks' rows (maxima and sums by
+the usual rescale, pairs by value).
+
+### Further sampling stages
 
 | op | params | operands |
 |---|---|---|
@@ -1486,46 +1499,42 @@ token's logprob is `l - max - log(sum)`; under a split vocabulary the host merge
 | `sample_xtc` | `M` `n_cand` | `cand_idx`:inout, `cand_val`:inout, `params` |
 | `sample_chain` | `M` `n_vocab` `temp`:f64/opt `p`:f64/opt `min_p`:f64/opt `k`/opt | `logits`, `query`?, `u` → `draw` |
 
-`sample_dry` penalises each token that would extend a repeated suffix of the history ONCE, by its
-longest such repeat — llama.cpp's DRY. The sequence breakers are strings, so they are resolved
+`sample_dry` is llama.cpp's DRY: it penalises, once, each token that would extend a repeated suffix
+of the history, by its longest such repeat. Sequence breakers are strings, so they are resolved
 against the vocabulary on the host: the row's `dry_rep_limit` carries the repeat limit the most
-recent breaker imposes, and the optional `breakers` plane, one byte beside every history token,
-marks the tokens that are whole breakers and are never penalised. Absent, no token is exempt.
+recent breaker imposes, and the optional `breakers` plane (one byte beside every history token) marks
+tokens that are whole breakers and are never penalised. Absent, no token is exempt.
 
-`sample_penalties` and `sample_dry` read GLOBAL token ids from `history` and write this rank's
-logits, so under a split vocabulary they take `vocab_off`, as `sample_topk` does, and a token
-outside the shard is another rank's to penalise. Their `penalty_last_n` / `dry_penalty_last_n`
-window is llama.cpp's: 0 turns the stage off for the row, and a negative value takes the whole
-history.
+`sample_typical` is locally typical sampling. It is not a prefix of the descending candidate order
+(that order and the typicality order disagree), so it narrows in place rather than truncating.
 
-`sample_typical` is locally-typical sampling and is NOT a prefix of the descending candidate order —
-that order and the probability order disagree, which is why it narrows in place rather than
-truncating. `sample_chain` is the whole chain in one kernel for the speculative verify: `query` is
-the drafted token per position (absent at the last one), `u` is TWO uniforms a position, and `draw`
-is `{u32 tok, u32 tok_excl, f32 p_query}` — the rejection test's three values. It stands beside the
-decomposed stages rather than replacing them; both are declared and the band decides.
+`sample_chain` (device-only) is the whole chain in one kernel for a speculative verify: temperature,
+softmax, top-k, top-p, min-p, renormalise and draw over an L2-resident row. `query` is the drafted
+token per position (absent at the last), `u` is two uniforms per position, and `draw` is
+`{u32 tok, u32 tok_excl, f32 p_query}`: a draw, a draw with `query` excluded, and `query`'s filtered
+probability, the three values a rejection-sampling verify needs. Its settings are launch-time
+parameters, never constraints. libr4d serves it; the engine's sampler issues the decomposed stages
+and does not declare it.
 
-### The vocabulary-parallel chain
+### Vocabulary-parallel sampling
 
-When `lm_head` is row-sharded, a rank's logits row covers only its own slice of the vocabulary, and
-two things follow. `sample_argmax` becomes unusable — its answer is a LOCAL column index, which is
-a different token — so a greedy request is staged at `top_k = 1` and takes the chain instead. And
-`sample_topk` writes an optional third output, `pairs`: its candidates as (u32 GLOBAL id, f32
-logit), with the rank's `vocab_off` already added, which is what `all_gather` moves and
-`sample_merge_topk` reads.
+When `lm_head` is row-sharded, a rank's logits row covers only its slice of the vocabulary.
+`sample_argmax` is then unusable (its answer is a local column index, a different token), so a greedy
+request is staged at `top_k = 1` and takes the chain. `sample_topk` writes the optional `pairs`
+output: its candidates as (u32 global id, f32 logit), with the rank's `vocab_off` added, which is
+what `all_gather` moves and `sample_merge_topk` reads.
 
-`sample_merge_topk` **re-applies the row's `top_k`**, and that is why it takes `params`. Every rank
-ran its own top-k before the gather, so the merged set holds up to `world_size * k` candidates
-where the request asked for `k`, and no stage after it narrows again. At `k = 1` the difference is
-not a slightly wider support: `sample_pick` is a DRAW, so a greedy row with two live candidates
-returns whichever one the request's seed happens to select.
+`sample_merge_topk` re-applies the row's `top_k`, which is why it takes `params`. Every rank ran its
+own top-k before the gather, so the merged set holds up to `world_size * k` candidates and no later
+stage narrows again. At `k = 1` that matters: `sample_pick` is a draw, so a greedy row with two live
+candidates would return whichever one the seed selects.
 
-**`gathered` is `world_size` SORTED RUNS, and the merge relies on it.** Each rank's `sample_topk`
-writes its `n_cand` pairs in descending (logit, lower id first) order with its holes at the tail,
-and the all-gather lays a row's runs side by side. libr4d's merge therefore runs only the merge
-stages of its sorting network when the runs are a power of two long and fill the row -- 11 passes
-over two runs of 1024 where a full sort is 66 -- and the whole network otherwise. A producer that
-hands it unsorted runs gets a wrong order, not a slow one.
+`gathered` is `world_size` sorted runs, and the merge relies on it. Each rank's `sample_topk` writes
+its `n_cand` pairs in descending (logit, lower id first) order with its holes at the tail, and the
+all-gather lays a row's runs side by side. libr4d's merge therefore runs only the merge stages of
+its sorting network when the runs are a power of two long and fill the row (11 passes over two runs
+of 1024, where a full sort is 66), and the whole network otherwise. Unsorted runs give a wrong
+order, not a slow one.
 
 ## Sparse attention (QSA)
 
@@ -1537,248 +1546,191 @@ hands it unsorted runs gets a wrong order, not a slow one.
 | `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 thing: an indexer that scores blocks of key history against the query and
-hands `attn_paged` a shorter block table. `docs/QSA.md` is that decomposition; these are the
-schemas, and `arch/common/rad_qsa.h` issues all five. **`qsa_block_key` has a host kernel in libref
-and libavx** -- the oracle for libr4d's, YaRN included -- and the other four are **device-only**.
+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.
 
-`qsa_block_key` builds the **compressed key**: one vector per `ratio` tokens of key history, which
-is what the indexer's block scores are taken against.
+### `qsa_block_key`
+
+The compressed key: one vector per `ratio` tokens of key history, against which the indexer's block
+scores are taken.
 
 ```
 out[b] = rope( rmsnorm( mean over j= j of
+                (base[j][h] + delta[t][j][h / group_size]) * x[t - j][h]
+
+Blocks are `block_size` rows starting at row 0, so a tap never reaches into the previous block.
+`delta` is `[T, taps, NG]` read at its own row pitch: the architecture passes a slice of the
+`[T, 2, taps, NG]` coefficient projection. `out` must not alias `x`. libr4d's kernel serves
+`taps` 2, `group_size` 16 and a power-of-two `block_size`; libref and libavx any.
+
 `dflash_select` is the greedy walk over the candidate lattice: `cand`/`unary` are `row_topk`'s two
 output planes at one row per draft position, `hp` the selector's rank-256 query, and `anchor` the
-step's own token ids — `anchor_stride` is the block width, because a draft pass carries `block` ids
-a sequence and the anchor is the first of them. `tokens` is THE DRAFT, and the engine reads it by
-name rather than through the sampler.
+step's own token ids (`anchor_stride` is the block width, because a draft pass carries `block` ids a
+sequence and the anchor is the first). `tokens` is the draft, which the engine reads by name rather
+than through the sampler. Only the K edges leaving the previous pick are scored, because the walk is
+serial.
 
-**`hp` IS OPTIONAL, AND ABSENT IT IS A PLANE OF ONES** — which turns the edge score
-`unary + Σ_r pred[prev][r]·hp[l][r]·succ[cand][r]` into the plain low-rank BIGRAM
-`⟨pred[prev], succ[cand]⟩`. That is exactly DSpark's Markov head: a rank-256 learned bigram bias
-added to the draft logits, decoded greedily, with the predecessor read after the previous step's
-argmax inside one workgroup. Written literally it is `steps` full-vocabulary [rank, n_vocab]
-matrix products — 466 MiB a step to use seven rows — and through this operand it is 8 KiB of
-codebook gather. The only approximation is the top-K candidate set, which can cost acceptance and
-nothing else.
+`hp` absent is a plane of ones, which turns the edge score
+`unary + Σ_r pred[prev][r]·hp[l][r]·succ[cand][r]` into the plain low-rank bigram
+`⟨pred[prev], succ[cand]⟩`. That is DSpark's Markov head: a rank-256 learned bigram bias added to
+the draft logits, decoded greedily, with the predecessor read after the previous step's argmax
+inside one workgroup. Written literally it is `steps` full-vocabulary `[rank, n_vocab]` matrix
+products; through this operand it is a codebook gather. The only approximation is the top-K
+candidate set, which can cost acceptance and nothing else.
 
-### `mtp_enter`: the MTP head's entry, when the residual stream is wide
+### `mtp_enter`
 
 | op | params | operands |
 |---|---|---|
@@ -1819,42 +1779,40 @@ nothing else.
     nh[k][j] = h[k*n+j] * rs[k] * (w_h[k*n+j] + wadd)
     x[k*n+i] = fc_h[i] . nh[k] + fe[i]                         for each of the hc sub-streams
 
-A pre-norm MTP head (Qwen3.5, Qwen3-Next, DeepSeek-V3) joins the trunk's hidden state and the next
-token's embedding with **one** `fc` over their concatenation, and `arch/common/rad_block_mtp_fp8.h`
-runs that as two `rmsnorm`s into the two halves of one buffer and a single `gemm_nt`. Qwen4-Exp's
-head cannot: its hidden state is the **wide** stream and its checkpoint carries `mtp.fc_hidden` and
-`mtp.fc_embedding` as two **square** `[n, n]` matrices beside a `[hc*n]` gain and an `[n]` one. So
-the hidden half is the same matrix applied to **each** sub-stream — the reference's own
-`.unflatten(-1, (hc_count, hidden_size))` idiom, which is how every other 10240-wide tensor in that
-architecture is handled — and the embedding half is one `n`-wide product added into all `hc` of
-them, the same broadcast the trunk enters the stream with (`hidden_states.repeat(1, 1, hc_count)`).
+The MTP head's entry when the residual stream is wide. A pre-norm MTP head (Qwen3.5, Qwen3-Next,
+DeepSeek-V3) joins the trunk's hidden state and the next token's embedding with one `fc` over their
+concatenation, and `arch/common/rad_block_mtp_fp8.h` runs that as two `rmsnorm`s into the two
+halves of one buffer and one `gemm_nt`. Qwen4-Exp's head cannot: its hidden state is the wide
+stream, and its checkpoint carries `mtp.fc_hidden` and `mtp.fc_embedding` as two square `[n, n]`
+matrices beside a `[hc*n]` gain and an `[n]` one. So the hidden half applies the same matrix to each
+sub-stream (the reference's `.unflatten(-1, (hc_count, hidden_size))`), and the embedding half is
+one `n`-wide product added into all `hc` of them, the broadcast the trunk enters the stream with
+(`hidden_states.repeat(1, 1, hc_count)`).
 
-**One op and not six, and here that is a statement about the ABI rather than about launch count.**
-Every intermediate above is a different *view* of the same bytes: `nh` is `[M*hc, n]` to the GEMM
-and `[M, hc*n]` to the norm. `core/runtime/issue.cpp` narrows **dim 0 or the last dimension with
-every stride left alone**, which is the right rule and makes a row-pitch change inexpressible — so
-the unfused spelling cannot be written at all, not merely at a cost. It is also six launches off a
-draft round, and a draft round is the latency the head exists to hide.
+It is one op because the unfused form cannot be written: every intermediate is a different view of
+the same bytes (`nh` is `[M*hc, n]` to the GEMM and `[M, hc*n]` to the norm), and
+`core/runtime/issue.cpp` narrows only dim 0 or the last dimension with every stride left alone, so a
+row-pitch change is inexpressible. It also saves launches in a draft round, whose latency the head
+exists to hide.
 
-**`fc` is the two square matrices' STORED format**: `bf16`, or `e4m3` rows with f32 128-column
-group scales in each row's own tail, the geometry `hc_read`'s `mix_down` uses. Only the drafts see
-it -- the head proposes and the trunk verifies -- so it can cost acceptance and never a token.
+`fc` is the two square matrices' stored format: `bf16`, or `e4m3` rows with f32 128-column group
+scales in each row's own tail (the geometry of `hc_read`'s `mix_down`). Only the drafts see it (the
+head proposes and the trunk verifies), so it can cost acceptance, never a token. A host kernel
+reads the codes and f32 scale planes joined (Weights of several planes).
 
-**`ngroup` is the one thing the checkpoint does not say.** A `[hc*n]` gain fits both a grouped norm
-(`hc` rsqrts, one per sub-stream — what `Qwen4ExpTextGatedResidual` does at every one of its 97
-connections) and a flat one (a single rsqrt over the whole wide row). Both readings are
-self-consistent, libref shares whichever the graph picks, and **no per-op oracle can reach it** —
-exactly the shape of question `rad_block_mtp_fp8.h`'s concat order is. It has the same cheap
-empirical answer: a head wired the right way round accepts most of what it proposes, and one wired
-the wrong way round proposes noise while the model's own output stays perfectly correct. The head
-declares the grouped reading (`ngroup = hc`), and `ngroup` carries it as a parameter so a flat
-reading (`ngroup = 1`) is one declaration away rather than a different kernel.
+`ngroup` is the one thing the checkpoint does not say. A `[hc*n]` gain fits both a grouped norm
+(`hc` rsqrts, one per sub-stream, as `Qwen4ExpTextGatedResidual` does at every connection) and a
+flat one (one rsqrt over the whole wide row). Both readings are self-consistent, libref shares
+whichever the graph picks, and no per-op oracle can tell them apart. The empirical answer is cheap:
+a head wired correctly accepts most of what it proposes, and one wired wrongly proposes noise while
+the model's own output stays correct. The head declares the grouped reading (`ngroup = hc`), and the
+parameter makes a flat reading (`ngroup = 1`) one declaration away rather than a different kernel.
 
 ---
 
 ## Adding an op
 
-Add the schema row to `libref/`, write the naive host implementation beside it, and it exists.
-No core file changes. If you add an op **without** a ref implementation, say so in your commit: you
-have just created something with no fallback and no oracle, and that is a decision, not an
-oversight.
+Add the schema row to `libref/`, write the naive host implementation beside it, and add a row to
+this document (`ops_doc` fails on an op a plugin declares that no table lists). No core file
+changes. An op added without a ref implementation has no fallback and no oracle; say so in the
+commit, because that is a decision, not an oversight.
diff --git a/docs/PLUGIN.md b/docs/PLUGIN.md
index 1dd0edbe..2c11410e 100644
--- a/docs/PLUGIN.md
+++ b/docs/PLUGIN.md
@@ -1,28 +1,25 @@
 # Writing a plugin
 
-Three kinds of plugin extend the engine, each a shared object that exports a handful of C symbols
-and links **nothing** of radiance's:
+Three kinds of plugin extend the engine, each a shared object that exports a few C symbols and
+links nothing of radiance's:
 
-- a **kernel library** implements ops for some hardware — a card, a family of cards, the CPU;
-- an **architecture** declares a model: its weights, its buffers, the ops it issues and in what
-  order;
+- a **kernel library** implements ops for some hardware (a card, a family of cards, the CPU);
+- an **architecture** declares a model: its weights, its buffers, and the ops it issues in order;
 - a **quantiser** turns a checkpoint's weights into the planes of an encoding, for `rad-convert`.
 
-The engine `dlopen`s them, asks what they can do, and calls them. That boundary is the whole design:
-a plugin is compiled against the installed `abi/` headers and nothing else, so a third party can
-ship one without building the engine. **The plugins radiance ships go through exactly this door.**
-libr4d, libref, libavx, libquant and every architecture are built with the same `rad_add_plugin`, can
-each be built on their own against an installed radiance, and are found and ranked by what they
-declare, never by their names; `ctest -L oot` rebuilds all of them out of tree against an installed
-prefix and requires the same result (`tests/oot_plugins.sh`).
+A plugin is compiled against the installed `abi/` headers alone, so a third party can ship one
+without building the engine. The in-tree plugins (libr4d, libref, libavx, libquant and every
+architecture) use the same interface: each is built with `rad_add_plugin`, builds on its own
+against an installed radiance, and is found and ranked by what it declares, never by its name.
+`ctest -L oot` (`tests/oot_plugins.sh`) rebuilds them out of tree against an installed prefix
+(libr4d only when given a HIP compiler) and requires the same result.
 
-Sections 1–9 are the kernel side; §10 is what a library for a card radiance has never seen needs;
-§11 and §12 are architectures and quantisers; §13 is building, installing and the search path all
-three share.
+§1-§9 cover kernel libraries, §10 a library for a new card, §11 and §12 architectures and
+quantisers, and §13 building, installing and the search path.
 
 ---
 
-## 1. The shape of it
+## 1. Kernel library exports
 
 ```c
 #include "rad_abi.h"          /* required */
@@ -37,34 +34,33 @@ const RadPluginInfo* rad_plugin_info(void) {
     return &i;
 }
 
-int                rad_kernel_schema_count(void);   /* the ops you DEFINE, if any */
+int                rad_kernel_schema_count(void);   /* the ops you define, if any */
 const RadOpSchema* rad_kernel_schema_at(int i);
-int                rad_kernel_count(void);          /* the kernels you IMPLEMENT */
+int                rad_kernel_count(void);          /* the kernels you implement */
 const RadKernelInfo* rad_kernel_at(int i);
 ```
 
-`rad_plugin_abi_version` is checked at load and a mismatch is refused **by name, with both numbers
-printed**. Do not hardcode the integer — return the macro, and rebuild when it moves. It moves for
-any shape change in a header a plugin compiles against (`rad_abi.h` says which).
+A plugin whose `rad_plugin_abi_version` differs from the engine's is refused at load, by name, with
+both numbers printed. Return the macro, not the integer, and rebuild when it changes; it changes
+with any shape change in a header a plugin compiles against (`rad_abi.h` lists them).
 
-`build_target` is prose for a human: the targets you were compiled for (`"gfx1100"`,
-`"gfx11-generic"`, several separated by spaces or commas), `"host"` for CPU kernels — which is what
-both in-tree host libraries say — or `""` for a plugin that really is portable. It is printed, not
-trusted: what the engine checks is the code objects your library actually carries (§10).
+`build_target` is printed, not trusted: the targets the library was built for (`"gfx1100"`,
+`"gfx11-generic"`, several separated by spaces or commas), `"host"` for CPU kernels, or `""` for a
+portable plugin. The engine checks the code objects the library carries instead (§10).
 
 Five more exports are optional, each looked up by exactly this name:
 
-| symbol | says |
+| symbol | meaning |
 |---|---|
-| `int rad_plugin_open(void)` | called once after load. `RAD_E_UNSUPPORTED` **declines this machine** — the library is unloaded and the rest of the installation carries on; any other negative status refuses it as an error |
+| `int rad_plugin_open(void)` | called once after load. `RAD_E_UNSUPPORTED` declines this machine: the library is unloaded and the rest of the installation carries on. Any other negative status is an error |
 | `void rad_plugin_close(void)` | called once at shutdown |
 | `int rad_kernel_concurrent(int i)` | nonzero: kernel `i` touches nothing but its operands and scratch, so independent launches may overlap |
-| `int rad_kernel_collective(int i)` | nonzero: kernel `i` exchanges data with the other ranks' cards, so the engine keeps its own bulk link traffic out of the way while it runs. 2: each launch ends that itself once the other ranks' bytes have landed, through the `link_gate` parameter (rad_abi.h). Without it only the `all_reduce` op counts as one |
-| `int rad_plugin_reference(void)` | nonzero: this library is a **reference implementation** — ranked below every unnamed library, refused for serving unless `--debug-accept-reference-kernels`, and what `rad-kbench` checks the others against. libref says so through this, as any library would |
+| `int rad_kernel_collective(int i)` | nonzero: kernel `i` exchanges data with the other ranks' cards, so the engine keeps its own bulk link traffic away while it runs. 2: each launch ends that hold itself once the other ranks' bytes have landed, through the `link_gate` parameter (`rad_abi.h`). Without this export only the `all_reduce` op is a collective |
+| `int rad_plugin_reference(void)` | nonzero: a **reference implementation**, ranked below every unnamed library, refused for serving unless `--debug-accept-reference-kernels`, and what `rad-kbench` checks the others against. libref declares itself this way |
 
 ---
 
-## 2. A kernel says what it can serve, not what it is
+## 2. Kernel constraints
 
 ```c
 static const RadConstraint c_gemm[] = {
@@ -85,284 +81,243 @@ static const RadKernelInfo k[] = {{
 }};
 ```
 
-The five operators are `RAD_CEQ`, `RAD_CLE`, `RAD_CGE`, `RAD_CDIV`, `RAD_CIN`. **The engine picks
-bucket boundaries out of your `LE`/`GE`/`EQ` values** and resolves once per bucket, because a GEMM
-sees one row at decode and thousands in a prefill chunk and they do not want the same kernel
-(`spec.md` §2.2). `DIV` and `IN` cut nothing — a divisibility holds at every value in a range, and
-set membership is not an interval — so neither can be a band edge.
+A kernel declares what it can serve. The operators are `RAD_CEQ`, `RAD_CLE`, `RAD_CGE`, `RAD_CDIV`
+and `RAD_CIN`. The engine takes bucket boundaries from the `LE`/`GE`/`EQ` values and resolves once
+per bucket, since a GEMM sees one row at decode and thousands in a prefill chunk (`spec.md` §2.2).
+`DIV` and `IN` are not intervals, so neither is a band edge.
 
-Two consequences worth internalising:
+Declare only the band you serve: the engine believes the claim, and a kernel that claims
+`M <= 2048` but is correct only to 64 is wrong. A wrong band shows only at concurrency, where M is
+larger, so test the whole concurrency ladder, not C=1 alone.
 
-- **Declare the band you actually serve.** A kernel that claims `M <= 2048` and is correct only to
-  64 is not slow, it is wrong, and the engine believes you.
-- **A band you claim and cannot serve is invisible to a single-sequence bench.** It only shows at
-  concurrency, where M is larger. Run the whole ladder, not just C=1.
+**Machine constraints.** A key starting with `device.` is matched against what the engine measured
+about the ranks' cards at launch, not against the op's parameters. `RAD_CEQ(RAD_FACT_P2P, 1)`
+(`device.p2p`) says a kernel accesses another card's memory. Where some pair of the ranks' cards
+cannot reach each other, the kernel is not selected and the next matching row takes the op; with
+none, startup stops and the selection table names the fact (`device.p2p == 1, have 0 -- this
+machine, measured at launch`). Every libr4d collective carries it and has a `_host` twin requiring
+`device.p2p == 0` that exchanges through pinned host memory, so exactly one of the pair matches any
+machine. A machine fact changes no tuning key. A tool selecting without an engine has measured
+nothing, so such a kernel is not selected there.
 
-**A constraint can be on the machine instead of the geometry.** A key that starts with `device.`
-is matched against what the engine measured about the ranks' cards at launch, not against the
-op's parameters. `RAD_CEQ(RAD_FACT_P2P, 1)` (`device.p2p`) is how a kernel says it reads or writes
-another card's memory. On a machine where some pair of the ranks' cards cannot reach each other,
-such a kernel is not selected. The next row that does not need it takes the op. With no such row,
-startup stops and the selection table names the fact (`device.p2p == 1, have 0 -- this machine,
-measured at launch`). Every collective in libr4d carries it, and each has a `_host` twin that
-requires `device.p2p == 0` and exchanges through pinned host memory, so exactly one of the pair
-matches any machine. A machine fact is in no geometry, so
-it changes no tuning key. A tool that selects without an engine has measured nothing, and such a
-kernel is not selected there either.
-
-`priority` breaks ties **within your plugin**, highest first, a tie going to declaration order.
-Between plugins there is no contest: **the hierarchy is absolute.** The first plugin in `--kernels`
-order with any matching kernel supplies it, and a later plugin never outbids it however
-specialised its kernel — which is exactly what makes a user override an override rather than a
-competitor.
+**Priority.** `priority` breaks ties within one plugin, highest first, then declaration order.
+Between plugins the hierarchy is absolute: the first plugin in `--kernels` order with any matching
+kernel supplies it, however specialised a later plugin's kernel is. That makes a user's library an
+override rather than a competitor.
 
 ---
 
-## 3. Operand extents are a request, not a bound
+## 3. Operand extents
 
-`RadArgs.t` is positional, in the op schema's order. Each `RadTensor` carries the extent the
-**caller narrowed it to**, which is generally smaller than the buffer.
+`RadArgs.t` is positional, in the op schema's order. Each `RadTensor` carries the extent the caller
+narrowed it to, generally smaller than the buffer. Size loops and grids from those extents, never
+from a declared maximum: otherwise a single-row decode runs over every row of an arena buffer,
+reading uninitialised memory and overwriting the next op's input.
 
-> An operand handed over at its declared extent means a single-row decode computed over all 8192
-> rows of an arena buffer — reading uninitialised memory and writing over the next op's input.
+Where an op takes `cu_seqlens`, derive the sequence count from its own length (`n = len - 1`), not
+from a sibling array, and each sequence's rows from `cu[n]` and `cu[n+1]`, which are absolute
+offsets into the token operands. This lets the engine pass a sub-range of the step (§8).
 
-Size your loops and your grid from the operands you were given, never from a declared maximum.
-Where an op takes `cu_seqlens`, derive the sequence count from **its own length** (`n = len - 1`)
-rather than from a sibling array, and derive each sequence's rows from `cu[n]` and `cu[n+1]`, which
-are absolute offsets into the token operands. Doing it that way is also what lets the engine hand
-you a *sub-range* of the step — see §8.
-
-An **absent optional operand is a null `RadTensor.data`, not a short operand count.** Read the
-operand after it and every weight in the model shifts by one. `rad_arg_in()` in `rad_plugin.h` is the
-one correct fetch.
+An absent optional operand is a null `RadTensor.data`, not a shorter operand count; reading it as
+a shorter array shifts every later operand by one. `rad_arg_in()` in `rad_plugin.h` fetches an
+operand correctly.
 
 ---
 
-## 4. The optional hooks, and what each one buys
+## 4. Optional kernel hooks
 
-None are required. Each one is a claim, and the engine will use it.
+None are required. Each is a claim the engine acts on.
 
-| hook | says |
+| hook | meaning |
 |---|---|
 | `init` / `fini` | per-resolved-instance state; `RadArgs.instance` hands it back |
-| `scratch` | how many bytes you need; the engine provides at least that |
-| `layout` | this weight is held in my order, not as the container stores it |
-| `relayout` | how to produce that order from the container's planes, run by the loader at load |
+| `scratch` | bytes of scratch a launch needs; the engine provides at least that |
+| `layout` | the kernel holds this weight in its own order, not as the container stores it |
+| `relayout` | produces that order from the container's planes, run by the loader |
 | `unrelayout` | the inverse, so a tool holding the stored bytes can read the planes back |
-| `opd_shape` | how to size and fill every operand, so a tool can call you cold |
-| `replaces` | the chain of conventional ops I compute in one launch |
-| `tunables` / `tune_valid` | the axes of my instantiation space, and which combinations are legal at a geometry |
-| `describe` | this dispatch, described rather than performed, so a repeated sequence can be replayed as a graph |
+| `opd_shape` | how to size and fill every operand, so a tool can call the kernel cold |
+| `replaces` | the chain of conventional ops the kernel computes in one launch |
+| `tunables` / `tune_valid` | the axes of the instantiation space, and which combinations are legal at a geometry |
 
-`opd_shape` and `unrelayout` are what make your kernel **checkable**. Without them, tools that would
-otherwise test you against the reference skip you *by name* rather than guessing — which is the
-right outcome, and a quiet one.
+`opd_shape` and `unrelayout` make a kernel checkable; without them, tools skip it by name instead
+of guessing.
 
-`replaces` is a strong claim and the ABI demands exactness: it means "I stand in for this chain,
-and you may check me against it." **A kernel that is merely close to the sequence it names should
-publish no hook at all.** In exchange, the engine can recognise that your fused kernel and the
-spelled-out chain are alternatives — which is how the Model view draws them as one branch instead
-of four sequential nodes.
+`replaces` must be exact ("this kernel stands in for this chain; check it against it"). A kernel
+that is only close publishes no hook. The claim lets the engine treat the fused kernel and the
+chain as alternatives, which the Model view draws as one branch.
 
-`tunables` is what makes your kernel tunable at all; without it, it is one fixed implementation
-forever. **You declare the axes and their legal values, not a list of pre-named variants**
-(`RadTunable` in `rad_abi.h`): the core takes the cross product, so a ladder cannot end up with a
-hole in it that quietly runs the next tile up. `tune_valid` rejects the combinations a product of
-independent lists cannot express — a block bound that couples two axes, a `K % (sk * unit)` rule —
-and a rejected candidate is reported as skipped, not as a failure. `rad-tune` measures the
-survivors at the shapes this model actually issues and writes the cache the selector consults at
-declare. The chosen point then arrives as **ordinary parameters**: you read `sk` with the same
-`rad_args_geti()` you read `M` with, so there is no variant index and no picker in your launch
-adapter. `deflt` is what runs where this machine has no measurement for an instantiation, so it has
-to be launchable — the loader checks it appears in `values` and refuses your plugin by name if it
-does not.
-
-`describe` buys nothing but speed: null means every issue of your kernel is submitted
-individually, which is correct and merely slower, and non-null lets a repeatedly issued sequence
-be replayed as a graph instead. It must not allocate, must not synchronise and must not touch the
-device: it is called while a run is being RECORDED -- not on every step, and not instead of the
-launch, which happens anyway on that pass. It takes the stream, because a launch whose arguments
-depend on which stream it goes onto would otherwise be described as something it is not. An op
-whose work is a memory copy rather than a launch has nothing to put in a `RadLaunchDesc` and should
-leave `describe` null.
+`tunables` declares the axes and their legal values (`RadTunable` in `rad_abi.h`), not a list of
+named variants. The core takes the cross product, so a ladder has no hole that silently runs the
+next tile up. `tune_valid` rejects combinations independent lists cannot express (a bound coupling
+two axes, a `K % (sk * unit)` rule); a rejected candidate is reported as skipped, not failed.
+`rad-tune` measures the survivors at the shapes the model issues and writes the cache the selector
+reads at declare. The chosen point arrives as ordinary parameters, read with `rad_args_geti()` like
+`M`, so the launch needs no variant index. `deflt` runs where this machine has no measurement and
+must be launchable; the loader refuses the plugin by name if `deflt` is not in `values`.
 
 ---
 
 ## 5. What a launch may do
 
-On a card the `RadStream` a kernel is handed is a queue the engine writes packets into itself
-(`core/device/aql.cpp`), not a `hipStream_t`. The engine binary defines the HIP entry points a
-kernel library uses and answers them on its own queues:
+On a card the `RadStream` a kernel receives is a queue the engine writes packets into itself
+(`core/device/aql.cpp`), not a `hipStream_t`. The engine binary defines these HIP entry points and
+serves them on its own queues:
 
 - `hipLaunchKernel`, and therefore `<<<>>>` and `hipLaunchKernelGGL`;
 - `hipMemcpyAsync`, `hipMemcpy2DAsync`, `hipMemsetAsync`;
-- `hipGetLastError` / `hipPeekAtLastError`, with HIP's own semantics.
+- `hipStreamSynchronize` (not from a launch, which must not synchronise);
+- `hipMemset`, which runs on the engine's queue for the current device and waits;
+- `hipGetLastError` / `hipPeekAtLastError`, with HIP's semantics.
 
 **Nothing else in HIP takes an engine stream.** `hipModuleLaunchKernel`, `hipExtLaunchKernel`,
-cooperative launches, `hipLaunchHostFunc`, and any library that launches through them — rocBLAS,
-hipBLASLt, MIOpen, a hipRTC module — would hand HIP a queue it has never heard of. Header-only
-device code (Composable Kernel's device templates, rocPRIM's block primitives) compiled into your
-own `.hip` launches through `hipLaunchKernel` and is fine. `hipEventRecord` and `hipStreamWaitEvent`
-on an engine stream are refused by name; ordering between streams is the engine's.
+cooperative launches, `hipLaunchHostFunc`, and libraries that launch through them (rocBLAS,
+hipBLASLt, MIOpen, hipRTC modules) would hand HIP a queue it does not know. Header-only device code
+(Composable Kernel's device templates, rocPRIM's block primitives) compiled into your own `.hip`
+launches through `hipLaunchKernel` and works. `hipEventRecord` and `hipStreamWaitEvent` on an engine
+stream are refused by name; ordering between streams is the engine's.
 
-The code object is read by the engine too, which puts limits on what a kernel may be:
+The engine reads the code object too, which limits a kernel to:
 
-- **no hostcall**: `printf` and `assert` in device code need a buffer the queues do not provide, and
-  a kernel that takes one is refused at its first launch, by name. `rad_add_plugin` compiles device
-  code with `-DNDEBUG` outside Debug for this reason;
-- **no dynamic stack** — recursion, a variable-length array — since nothing sizes its scratch;
+- **no hostcall**: `printf` and `assert` in device code need a buffer the queues do not provide,
+  and the kernel is refused by name at its first launch. `rad_add_plugin` compiles device code with
+  `-DNDEBUG` outside Debug for this reason;
+- **no dynamic stack** (recursion, a variable-length array), since nothing sizes its scratch;
 - **kernel arguments up to 768 bytes**, and static plus dynamic LDS up to 64 KiB a dispatch;
-- **an uncompressed fat binary**. `rad_add_plugin` passes `--no-offload-compress`; a toolchain that
-  compresses anyway is refused at the first launch.
+- **an uncompressed fat binary**. `rad_add_plugin` passes `--no-offload-compress`; a compressed one
+  is refused at the first launch.
 
-A device allocation a kernel needs for itself comes from the `scratch` hook (§4), not `hipMalloc`:
-the engine's allocator is the one that knows what the card has left.
+Device memory a kernel needs for itself comes from the `scratch` hook (§4), not `hipMalloc`, since
+the engine's allocator knows what the card has left.
 
 ---
 
-## 6. `rad_plugin.h` is optional, and one part of it is not merely convenience
+## 6. `rad_plugin.h`
 
-A plugin that includes only `rad_abi.h` is complete and correct. The helper header is shared
-definitions of the dozen things every plugin needs — optional-operand fetch, parameter-with-default,
-contiguity, row pitch, narrowing conversions.
+A plugin that includes only `rad_abi.h` is complete. The helper header holds what every plugin
+needs: the optional-operand fetch, parameters with defaults, row pitch, pointer alignment and the
+narrowing conversions.
 
-Use its conversions. **The narrowing conversions define what a result IS**: the reference contract
-is f32 accumulation, IEEE round-to-nearest-even, no FMA and no reassociation, and a plugin whose
-bf16 rounding truncates instead of rounding to even does not reproduce the reference and therefore
-cannot be checked against it.
+Use its conversions: they define what a result is. The reference contract is f32 accumulation,
+IEEE round-to-nearest-even, no FMA and no reassociation, and a plugin whose bf16 narrowing
+truncates cannot be checked against the reference.
 
 ---
 
 ## 7. Defining a new op
 
-Only if the conventional vocabulary in `docs/OPS.md` genuinely has no name for it. That document
-is the op vocabulary and the rules that come with adding to it: what a schema must declare, that
-the first plugin in hierarchy order to declare an op **fixes its schema** and a later plugin
-declaring it differently is refused at load with both plugins named, and why the refusal is worth
-having. It is also mechanically checked against the registries by `ctest -R ops_doc`, which is the
-reason the statement lives there and not in a second copy here that can drift away from it.
+Only when `docs/OPS.md` has no name for it. That document is the op vocabulary and its rules: what
+a schema must declare, and that the first plugin in hierarchy order to declare an op fixes its
+schema (a later plugin declaring it differently is refused at load, both named). `ctest -R ops_doc`
+checks it against the registries, so the rules live there only.
 
-An op that stays inside `docs/OPS.md` is describable by the reference, and therefore checkable,
-even when your kernel cannot describe itself.
+An op in `docs/OPS.md` is describable by the reference, and so checkable, even when your kernel
+cannot describe itself.
 
 ---
 
-## 8. The one contract an architecture plugin gets silently wrong
+## 8. Mixed steps in an architecture plugin
 
-If you write an **architecture** plugin with a linear/recurrent block, read `spec.md` §10 before
-you write its `step()`.
+An **architecture** plugin with a linear or recurrent block must follow `spec.md` §10 in its
+`step()`.
 
-A step that carries a prefill chunk beside decode rows is what continuous batching produces
-constantly — on an agentic load about a third of all steps, and *none of them prefill-only*,
-because every chunk rides with decode rows. The obvious block issues one path for the whole step.
-Its decode rows then land on the chunked path, which commits the recurrent state directly and takes
-no `num_accepted`: a draft verified there cannot be rolled back, the rejected tokens stay folded
-into the state, and the model is conditioned on text it never emitted. **The answer stays fluent
-and drifts**, which is why it shows up as concurrent requests disagreeing with the same requests
-run alone rather than as anything failing.
+Continuous batching produces many steps that carry a prefill chunk beside decode rows. A block that
+issues one path for the whole step sends its decode rows down the chunked path, which commits the
+recurrent state directly and takes no `num_accepted`. A draft verified there cannot be rolled back:
+the rejected tokens stay in the state and the model is conditioned on text it never emitted. The
+output stays fluent and drifts, so the symptom is concurrent requests disagreeing with the same
+requests run alone.
 
-Issue the recurrent path over `RadBatch::n_seq_decode` sequences and the chunked path over the
-rest. The core orders every step decode-first so each half is a contiguous run. It costs no kernel
-change, for the reason in §3: `cu_seqlens` holds absolute offsets, so the prefill half is addressed
-by passing `cu + n_seq_decode` with the token operands left at their base.
+Issue the recurrent path over the first `RadBatch::n_seq_decode` sequences and the chunked path
+over the rest; the core orders every step decode-first, so each half is contiguous. No kernel
+change is needed (§3): `cu_seqlens` holds absolute offsets, so the prefill half is addressed by
+passing `cu + n_seq_decode` with the token operands left at their base.
 
 ---
 
 ## 9. Checking your work
 
-`rad-kbench` is the answer to "is my library correct, complete and fast", and it needs no model:
+`rad-kbench` checks a library for correctness, completeness and speed without a model:
 
 ```sh
 rad-kbench --kernels mylib,libr4d,libref --report mylib.md --bench
 ```
 
-It replays a recorded fixture — `kernels.rkb` unless `--fixture` names another, and `data/` holds
-a dense one and a routed-MoE one — a recording of libref's answers over a few hundred real model
-geometries, and runs every kernel **your** library supplies against it. Your rows are found the
-same way the engine finds them — your constraints, your priorities — but they are not *selected*:
-every library that has a row for a case is run, so yours appears beside libr4d's rather than
-instead of it. The report carries the three columns that matter separately:
+It replays a recorded fixture of libref's answers over a few hundred real model geometries
+(`kernels.rkb` unless `--fixture` names another; `data/` holds a dense one and a routed-MoE one).
+Rows are found as the engine finds them, but every library with a row for a case is run, so yours
+appear beside libr4d's. The report covers:
 
-- **correctness**, relative to the recorded reference. The recording keeps the full norm of every
-  output plus 1024 sampled values, so a kernel that gets the sampled positions right and the total
-  energy wrong still fails.
-- **completeness**, the op-by-library matrix, read off the registries rather than off the run —
-  so an op your library does not implement is a gap whether or not this fixture exercises it.
+- **correctness** against the recording, which keeps every output's full norm plus 1024 sampled
+  values, so a kernel right at the samples but wrong in total energy fails;
+- **completeness**, the op-by-library matrix, read from the registries, so a missing op is a gap
+  whether or not the fixture exercises it;
 - **speed**, timed on the same bytes in the same pass.
 
-Three things it does for you that are easy to get wrong on your own:
+It also checks:
 
-- **Red zones.** Every device allocation it hands you has a poisoned 256-byte margin either side,
-  verified after the launch. An out-of-bounds write is the one fault that otherwise reports as a
-  pass, because in a harness the bytes past your operand belong to nobody. AMD's device
-  AddressSanitizer needs `xnack+` and RDNA has none, so this is what there is.
-- **Fusion.** A row with `replaces` is run against the chain it names, out of *your* library, and
-  the outputs compared byte for byte. That is a stronger claim than a tolerance against the
-  oracle, and it is the claim a fusion actually makes.
-- **Divergence.** If your `opd_shape` describes an output differently from libref's, you are told
-  so by name with both descriptions printed, and the case is counted apart from the failures. Two
-  libraries can mean different things by one op name; that is a conversation, not a bug in your
-  arithmetic.
+- **red zones**: every device allocation has a poisoned 256-byte margin on each side, verified
+  after the launch, since in a harness an out-of-bounds write otherwise passes. AMD's device
+  AddressSanitizer needs `xnack+`, which RDNA lacks;
+- **fusion**: a row with `replaces` is run against the chain it names, out of your own library,
+  and the outputs compared byte for byte;
+- **divergence**: an output your `opd_shape` describes differently from libref's is reported by
+  name with both descriptions and counted apart from the failures.
 
-If your kernel is skipped rather than checked, the report names why. The usual cause is a missing
-`opd_shape` (§4) — without it the tool will not invent an extent for you.
+A skipped kernel is reported with the reason, usually a missing `opd_shape` (§4). Other
+diagnostics:
 
 - `--debug-selection` prints the selection table: which kernel took each band, and the constraint
-  that refused every other candidate.
-- `/graph` on a running server carries the declared graph *and* which declarations the run phase
-  has actually issued — the way to find a band you resolved for nothing.
-- `--debug-accept-reference-kernels` is required to run with a reference fallback in place. Without
-  it, falling back is a fatal error, on purpose: a reference kernel in production is a correctness
-  result reported as a performance one.
-- `rad-info --plugins` prints every plugin the search path offers, as the engine loads it: kind,
-  version, what it declares, whether it is a reference, whether its device code runs on this card,
-  and the file it came from.
+  that refused each other candidate;
+- `/graph` on a running server returns the declared graph and which declarations the run phase has
+  issued, which finds a band resolved for nothing;
+- `--debug-accept-reference-kernels` is required to serve with a reference fallback; without it a
+  fallback is fatal, because a reference kernel in production would look like a performance
+  problem;
+- `rad-info --plugins` prints every plugin on the search path as the engine loads it: kind, version,
+  declarations, whether it is a reference, whether its device code runs on this card, and its file.
 
 ---
 
-## 10. A library for a card radiance has never seen
+## 10. A library for a new card
 
-The engine holds no opinion about cards. Its own device code — the copies and fills every transfer
-runs, the step's bookkeeping, the weight-table patches — is compiled for every AMD GPU family's
-generic target (`gfx9-generic`, `gfx9-4-generic`, `gfx10-1-generic`, `gfx10-3-generic`,
-`gfx11-generic`, `gfx12-generic`) beside whatever the build targeted, so one engine binary starts on
-any of them. What it computes there is whatever kernel library you install.
+The engine's own device code (the copies and fills every transfer runs, the step's bookkeeping,
+the weight-table patches) is compiled for every AMD GPU family's generic target (`gfx9-generic`,
+`gfx9-4-generic`, `gfx10-1-generic`, `gfx10-3-generic`, `gfx11-generic`, `gfx12-generic`) beside
+the build's own targets, so one engine binary starts on any of them. What it computes there depends
+on the kernel library installed.
 
-**Build for the card, or for its family.** `-DRAD_GPU_TARGETS=gfx942` or `=gfx11-generic` when you
-configure; the default is the targets the installed radiance was built for. When a code object is
-needed the engine asks the runtime which targets the card accepts, in order — the chip itself, then
-its family (`gfx1036`, then `gfx10-3-generic`) — each with the modes the card runs in
-(`gfx942:sramecc+:xnack-`), and takes the best fit your fat binary holds: the exact chip over the
-family, a code object built for the card's mode over one built for either.
+**Targets.** Configure with `-DRAD_GPU_TARGETS=gfx942` or `=gfx11-generic`; the default is the
+installed radiance's targets. For each code object the engine asks the runtime which targets the
+card accepts, in order (the chip, then its family: `gfx1036`, then `gfx10-3-generic`), each with
+the card's modes (`gfx942:sramecc+:xnack-`), and takes the best fit in the fat binary: the chip
+over the family, a code object for the card's mode over one for either.
 
-**A library with nothing for this card is left out, not failed.** When a kernel library loads, the
-fat binaries its `dlopen` registered are checked against the card the ranks will run on, the same
-check its first launch would make. If none fits, its device rows are left out of selection and the
-log says what it carries and what the card runs; its host rows stay. So one installation can carry
-a library per card. A library that knows at `rad_plugin_open` that it does not serve the machine
-can also decline it with `RAD_E_UNSUPPORTED`.
+**A library with nothing for this card is left out, not failed.** At load, the fat binaries a
+kernel library registered are checked against the ranks' card. If none fits, its device rows are
+left out of selection, the log says what it carries and what the card runs, and its host rows stay.
+One installation can therefore carry a library per card. A library can also decline from
+`rad_plugin_open` with `RAD_E_UNSUPPORTED`.
 
-**Which devices.** Discrete cards are used when there are any, and of those the ones sharing the
-first one's architecture; integrated graphics only when it is all there is. `ROCR_VISIBLE_DEVICES`
-chooses explicitly. On integrated graphics the device memory is the host's: the budget is bounded by
-what the host has available and leaves an eighth of the host's memory to it.
+**Devices.** The engine uses the discrete cards if there are any (those with the first one's
+architecture), and integrated graphics only when there is nothing else. `ROCR_VISIBLE_DEVICES`
+chooses explicitly. On integrated graphics device memory is host memory: the budget is bounded by
+what the host has available and leaves an eighth of host memory to the host.
 
-**What the core assumes of a card: nothing about its wave size**, its LDS, its fp8 hardware or its
-links — those are your kernels' business. Three things are worth knowing before you start:
+The core assumes nothing about a card's wave size, LDS, fp8 hardware or links. Three points matter:
 
 - **The vocabulary is what you implement.** A model runs on your library when every op its
-  architecture issues has a row in it (`docs/OPS.md`; `--debug-graph` lists them). A bf16 model
-  in the tree issues only ops libref also implements — MiniCPM5-2B is 13 model ops and 11 sampler
-  ops — so libref's host code is the specification and `rad-kbench` the check. Ops `docs/OPS.md`
-  marks **device-only** are libr4d's own and have no reference yet: the fp8 models, and a drafter
-  with a 2-bit head, issue some, and run on a library that implements them.
-- **fp8 bytes are OCP E4M3** (`e4m3fn`, bias 7, max 448) everywhere the engine reads them: weights in
-  a container, the KV cache at `--kv-cache-dtype fp8`, activations between ops. A card whose fp8
-  is `e4m3fnuz` (gfx942) converts weights in its `relayout` hook — the codes are the same bits but
-  0x80, the value half, so the scale doubles — and keeps activations and KV in OCP bytes, or
-  converts at its own boundaries.
+  architecture issues has a row there (`docs/OPS.md`; `--debug-graph` lists them). The bf16 models
+  in the tree issue only ops libref implements (MiniCPM5-2B: 13 model ops and 11 sampler ops), so
+  libref's host code is the specification and `rad-kbench` the check. Ops `docs/OPS.md` marks
+  **device-only** are libr4d's and have no reference; the fp8 models and a drafter with a 2-bit
+  head issue some.
+- **fp8 bytes are OCP E4M3** (`e4m3fn`, bias 7, max 448) wherever the engine reads them: container
+  weights, the KV cache at `--kv-cache-dtype fp8`, activations between ops. A card whose fp8 is
+  `e4m3fnuz` (gfx942) converts weights in its `relayout` hook (the codes keep their bits except
+  0x80 and decode to half the value, so the scale doubles) and keeps activations and KV in OCP
+  bytes, or converts at its own boundaries.
 - **Tensor parallelism is ops you supply.** `all_reduce`, `all_gather` and the fused collectives
-  are rows in a kernel library like any other; the engine inserts none and assumes no link.
+  are kernel-library rows like any other; the engine inserts none and assumes no link.
 
 ---
 
@@ -370,10 +325,10 @@ links — those are your kernels' business. Three things are worth knowing befor
 
 An architecture plugin declares a model in two phases (`spec.md` §3): `rad_arch_declare` names
 every weight, buffer and op once, against the model's metadata, and `rad_arch_step` issues the ops
-for one step. The contract is `abi/rad_builder.h` and `abi/rad_runtime.h`; the helpers every
-in-tree architecture is built from — weight declarations, the gated-attention and MoE blocks, the
-MTP and DFlash2 drafters — are installed as `` and its siblings, and the in-tree
-plugins include them by exactly that spelling.
+for one step. The contract is `abi/rad_builder.h` and `abi/rad_runtime.h`. The helpers the in-tree
+architectures use (weight declarations, the gated-attention and MoE blocks, the MTP and DFlash2
+drafters) are installed as `` and its siblings, and the in-tree plugins include
+them by that spelling.
 
 ```c
 const char* rad_arch_id(void);          /* "llama" -- what a container's header names */
@@ -385,43 +340,48 @@ const RadChatFormat* rad_arch_chat_format(const RadModelMeta* meta);
 ```
 
 `rad_plugin_info` reports `RAD_PLUGIN_ARCH`. The engine picks the plugin whose
-`(rad_arch_id, rad_arch_quant)` pair equals the container's — exactly, with no fallback — so one
-model family at two weight formats is two plugins. A checkpoint's id is its `config.json`
-`model_type` with the underscores removed; `rad-convert --arch ID` overrides it. Every key of the
-checkpoint's configuration reaches the plugin in `RadModelMeta`, and the plugin's name map says
-which checkpoint tensor each declared weight comes from, so `rad-convert` needs no knowledge of the
-model.
+`(rad_arch_id, rad_arch_quant)` pair equals the container's, with no fallback, so one model family
+at two weight formats is two plugins. A checkpoint's id is its `config.json` `model_type` without
+underscores; `rad-convert --arch ID` overrides it. Every configuration key reaches the plugin in
+`RadModelMeta`, and the plugin's name map says which checkpoint tensor each declared weight comes
+from, so `rad-convert` needs no knowledge of the model.
 
-What to know first:
-
-- **Stay inside `docs/OPS.md` and the model runs anywhere.** An op libref implements has a host
-  fallback, an oracle and a specification every kernel library can be checked against. An op you
-  invent runs only on a library that implements it.
-- **A fusion is an op name.** The engine does not rewrite your graph; a kernel library's
-  `replaces` declares an equivalence for checking, not a substitution. Ask for a fused op where one
-  exists and fall back to its parts where it does not resolve — an op no library serves is
-  declared as `RAD_NULL_HANDLE` (`rad_op_resolved`), which is an error only if it is issued — the
-  way the in-tree blocks do for `qk_norm_rope_gate`.
+- **Ops from `docs/OPS.md` run on any library.** An op libref implements has a host fallback, an
+  oracle and a specification to check kernel libraries against. An op you invent runs only on a
+  library that implements it.
+- **A fusion is an op name.** The engine does not rewrite your graph, and `replaces` declares an
+  equivalence for checking, not a substitution. Ask for the fused op and fall back to its parts
+  where it does not resolve: an op no library serves is declared as `RAD_NULL_HANDLE`
+  (`rad_op_resolved`) and is an error only if issued. The in-tree blocks do this for
+  `qk_norm_rope_gate`.
 - **Read §8** if the model has a linear or recurrent block.
-- **Images go through the Qwen-VL processor** (`core/mm`): patching, the pad-token expansion and
-  three-part rotary positions are the core's. A vision model with another image pipeline needs a
-  core change today.
+- **Media preprocessing is the core's** (`core/mm`): resizing, patching, placeholder-token
+  expansion and positions, in three processor families (Qwen-VL, Gemma 4, LFM2-VL) chosen by the
+  container's `vision_config.model_type`. A vision model with another pipeline needs a core change.
+  Audio goes through one of two feature extractors, Gemma 4's and Qwen3-ASR's (Whisper's), chosen
+  by `audio_config.model_type`.
+- **A speech model says how it hears**, through the optional
+  `const RadAudioFormat* rad_arch_audio_format(const RadModelMeta*)` (`RAD_ARCH_AUDIO_FORMAT`): the
+  tokens around a clip when its config names none, the turn a transcription is asked in, how a
+  language is forced and named, and where the transcript starts in the reply. That is all
+  `/v1/audio/transcriptions` knows about a model, so a new speech model is a plugin, not a server
+  change. Like `rad_arch_chat_format`, the struct grows only at its end, behind its `struct_size`.
 
 ---
 
 ## 12. Quantiser plugins
 
 A quantiser turns a weight, handed to it in f32, into the planes of an **encoding**
-(`abi/rad_encoding.h`) — the numbers, in one canonical row-major arrangement any kernel library can
-lay out its own way at load. The contract is `abi/rad_quant.h`:
+(`abi/rad_encoding.h`): the numbers in one canonical row-major arrangement, which a kernel library
+lays out its own way at load. The contract is `abi/rad_quant.h`:
 
 ```c
 int                     rad_quant_count(void);
-const RadQuantizerInfo* rad_quant_at(int i);   /* name, options, encoding, row_block, quantize, decode */
+const RadQuantizerInfo* rad_quant_at(int i);   /* name, doc, options, encoding, row_block, quantize, decode */
 ```
 
-`rad_plugin_info` reports `RAD_PLUGIN_QUANT`. `rad-convert` drives quantisers through a **recipe**,
-ordered rules from a weight's logical name to a quantiser and its options:
+`rad_plugin_info` reports `RAD_PLUGIN_QUANT`. `rad-convert` drives quantisers through a
+**recipe**: ordered rules from a weight's logical name to a quantiser and its options.
 
 ```
 # PATTERN                    QUANTISER  OPTIONS
@@ -429,21 +389,20 @@ blk.*.ffn_*_exps.*.weight    myquant    bits=3 group=64
 *                            rtn        codes=fp8_e4m3 block=128x128 scale=bf16
 ```
 
-`rad-convert --list-quantizers` prints every quantiser loaded and the options each takes; an option
-a recipe gives that the quantiser does not declare is refused before anything is quantised. Two
-plugins naming the same quantiser are refused, both named.
+`rad-convert --list-quantizers` prints every loaded quantiser and its options. A recipe option the
+quantiser does not declare is refused before anything is quantised. Two plugins naming the same
+quantiser are refused, both named.
 
-An encoding whose scheme is `plain` or `affine` is decoded by the core. A scheme of your own is
-decoded by your `decode` hook, which the oracle, `rad-kbench` and `rad-convert`'s error report all
-read through; answer `RAD_E_UNSUPPORTED` for a scheme you did not write. A container in a new
-encoding then needs two more things to SERVE: a kernel library whose `layout` hook accepts it, and an
-architecture that declares the weight at it. The in-tree architectures' linear and expert
-declarations take the encodings their blocks were written for, so a format that is not one of
-those is served by a kernel library and an architecture plugin of its own.
+The core decodes the `plain` and `affine` schemes. Your own scheme is decoded by your `decode`
+hook, which the oracle, `rad-kbench` and `rad-convert`'s error report use; return
+`RAD_E_UNSUPPORTED` for a scheme you did not write. Serving a new encoding also needs a kernel
+library whose `layout` hook accepts it and an architecture that declares the weight at it. The
+in-tree architectures declare only the encodings their blocks were written for, so another format
+needs its own kernel library and architecture plugin.
 
 ---
 
-## 13. Building, installing, and the search path
+## 13. Building, installing and the search path
 
 ```cmake
 cmake_minimum_required(VERSION 3.21)
@@ -453,37 +412,35 @@ rad_plugin_defaults()                  # C++20, an optimising build type unless
 rad_add_plugin(mykernels kernels SOURCES rows.cpp HIP_SOURCES kernels.hip)
 ```
 
-The kind is `kernels`, `architectures` or `quantizers` — the directory the engine loads it from.
-`HIP_SOURCES`, not `SOURCES`, for device code: only those are compiled as HIP, for
-`RAD_GPU_TARGETS` (§10) or a list you pass as `GPU_TARGETS`, at `-O3 -DNDEBUG` outside Debug,
-uncompressed, against the HIP runtime the installed radiance found. `rad_add_plugin` is the same
-function radiance builds its own plugins with, deliberately not a copy, and every plugin directory
-in radiance's tree opens with these lines guarded by `if(NOT COMMAND rad_add_plugin)`, which is
-what lets each be built inside the tree or on its own.
+The kind is `kernels`, `architectures` or `quantizers`, the directory the engine loads it from.
+Only `HIP_SOURCES` are compiled as HIP: for `RAD_GPU_TARGETS` (§10) or a `GPU_TARGETS` list,
+optimised with `-DNDEBUG` outside Debug, uncompressed, against the HIP runtime the installed
+radiance found. radiance builds its own plugins with the same `rad_add_plugin`, and every plugin
+directory in the tree opens with these lines guarded by `if(NOT COMMAND rad_add_plugin)`, so each
+builds inside the tree or on its own.
 
-`find_package` also gives you `RADIANCE_ABI_VERSION`, so you can refuse at configure time rather
-than at `dlopen`, and `RADIANCE_HOME`, `RADIANCE_KERNELS_DIR`, `RADIANCE_ARCHITECTURES_DIR` and
+`find_package` also sets `RADIANCE_ABI_VERSION` (to refuse at configure time rather than at
+`dlopen`), `RADIANCE_HOME`, `RADIANCE_KERNELS_DIR`, `RADIANCE_ARCHITECTURES_DIR` and
 `RADIANCE_QUANTIZERS_DIR`. `cmake --install` puts the plugin under the home of the radiance you
-built against; set `RAD_PLUGIN_INSTALL_HOME` to install somewhere else. Before installing, the
-build tree's own `radiance_home/` is a working home for the plugin alone.
+built against; `RAD_PLUGIN_INSTALL_HOME` overrides that. Before installing, the build tree's
+`radiance_home/` is a working home for the plugin alone.
 
-**`$RADIANCE_HOME` is a search path**: homes separated by `:`, the first winning. Each may hold any
-of `kernels/`, `architectures/` and `quantizers/`; a plugin file an earlier home holds shadows one
-of the same name later on. So your own plugins go ahead of an installation without copying it:
+**`$RADIANCE_HOME` is a search path**: homes separated by `:`, the first winning. Each may hold
+`kernels/`, `architectures/` and `quantizers/`, and a plugin file in an earlier home shadows one of
+the same name later. Your plugins go ahead of an installation without copying it:
 
 ```sh
 RADIANCE_HOME=$HOME/radiance-plugins:/opt/radiance/share/radiance radiance --model ...
 ```
 
-and the container image takes one the same way, mounted:
+The container image takes one the same way, mounted:
 `-v /my/plugins:/plugins -e RADIANCE_HOME=/plugins:/opt/radiance/share/radiance`.
 
 **The kernel hierarchy** is `--kernels` (or `$RADIANCE_KERNELS`), an ordered list of the kernel
-libraries to use: `--kernels mykernels,libr4d` puts you in front of libr4d. An entry matches a
-plugin's name or its file (`libr4d`, `r4d`, `libr4d.so` and a path to it are one library), and an
-entry that matches nothing is warned about by name. **The list is comma-separated** — the tools
-also accept colons, the engine's `--kernels` and `$RADIANCE_KERNELS` do not, so write commas
-everywhere. A kernel
-library on the search path that the list does not name is not loaded, so name every library you
-want, the host library (`libavx`) and the reference (`libref`) included. With no list every library
-found loads, a reference library (§1) last.
+libraries to use: `--kernels mykernels,libr4d` puts yours before libr4d. An entry matches a
+plugin's name or its file (`libr4d`, `r4d`, `libr4d.so` and a path to it are one library); an entry
+matching nothing is warned about by name. Separate entries with commas or colons
+(`mykernels:libr4d` is the same list); the engine and every tool read `--kernels` and
+`$RADIANCE_KERNELS` by this one rule, and an empty `$RADIANCE_KERNELS` counts as unset. A kernel library the list does not
+name is not loaded, so name every library you want, including the host library (`libavx`) and the
+reference (`libref`). With no list every library found loads, a reference library (§1) last.
diff --git a/docs/QSA.md b/docs/QSA.md
index c1ab8743..07552a48 100644
--- a/docs/QSA.md
+++ b/docs/QSA.md
@@ -1,23 +1,20 @@
-# QSA — Qwen4-Exp's sparse attention
+# QSA: Qwen4-Exp's sparse attention
 
-The full-attention layers of Qwen4-Exp (every fourth: 3, 7, … 47) do not attend to everything. A
-small **indexer** scores 4-token blocks of the key history and the attention reads only the best
-512 of them, plus the incomplete tail. Attention cost is therefore **constant past 2051 tokens**
-instead of linear, which is the whole reason the model is usable at 262144.
+The full-attention layers of Qwen4-Exp (every fourth: 3, 7, … 47) do not attend to the whole
+history. A small **indexer** scores 4-token blocks of the key history, and the attention reads the
+best 512 of them plus the incomplete tail, so attention cost is constant past 2051 tokens.
 
-This file is the decomposition and the argument for its shape. The declaration side is
-`arch/common/rad_qsa.h`; the arithmetic is libr4d's `qsa_block_key`, `qsa_score`, `qsa_select`,
-`qsa_work` and `qsa_tail_store`; the sparse attention is the *ordinary* `attn_paged`. **Schemas and
-per-operand contracts live in `docs/OPS.md`**, which is the mechanically checked document, and are
-not repeated here.
+The declaration side is `arch/common/rad_qsa.h`. The kernels are libr4d's `qsa_block_key`,
+`qsa_score`, `qsa_select`, `qsa_work` and `qsa_tail_store`; the sparse attention is the ordinary
+`attn_paged`. Schemas and operand contracts are in `docs/OPS.md`.
 
-## The shape
+## Shape
 
 From the checkpoint: `indexer_n_heads` 4, `indexer_kv_heads` 1, `indexer_head_dim` 128,
-`indexer_budget` 2048, `indexer_compress_ratio` 4. So `block_topk = 2048 / 4 = 512` blocks.
-`rotary_dim` is the main attention's — `head_dim 256 * partial_rotary_factor 0.25 = 64` — applied
-to the first 64 of the indexer's 128 dims, from the same cos/sin table the layer's attention uses.
-The plugin refuses a checkpoint where that would not fit. Three weights a QSA layer:
+`indexer_budget` 2048, `indexer_compress_ratio` 4, so `block_topk = 2048 / 4 = 512` blocks.
+`rotary_dim` is the main attention's (`head_dim 256 * partial_rotary_factor 0.25 = 64`), applied to
+the first 64 of the indexer's 128 dims from the layer's cos/sin table; the plugin refuses a
+checkpoint where it does not fit. Weights per QSA layer:
 
 ```
 model.language_model.layers..self_attn.indexer.index_qk_proj.weight   [640, 2560]
@@ -27,219 +24,182 @@ model.language_model.layers..self_attn.indexer.k_layernorm.weight     [128]
 
 640 = (4 query heads + 1 key head) x 128.
 
-## What it computes
+## Computation
 
 ```
 qk        = index_qk_proj(hidden)             [T, 640]
 q, raw_k  = split(qk, [512, 128])             q -> [T, 4, 128], raw_k -> [T, 128]
-q         = rope(q_layernorm(q), pos)         per query, at the query's OWN position
+q         = rope(q_layernorm(q), pos)         per query, at the query's own position
 
 per complete block b of 4 consecutive key tokens:
-  pooled  = mean over the 4 raw_k, IN f32, cast back to bf16
-  blk_k_b = rope(k_layernorm(pooled), pos of the block's FIRST token)
+  pooled  = mean over the 4 raw_k, in f32, cast back to bf16
+  blk_k_b = rope(k_layernorm(pooled), pos of the block's first token)
 
 per query:
   score_b = sum over the 4 heads of relu(q_h . blk_k_b) / sqrt(128)
   keep    = indices of the top min(512, n_blocks) scores
-  visible = the 4 tokens of every kept block, PLUS the tail
+  visible = the 4 tokens of every kept block, plus the tail
             (the (pos+1) % 4 tokens after the last complete block, attended unconditionally)
 ```
 
-The q side needs no kernel of its own: the norm and the partial rotation over the query half are
-`qk_norm_rope_gate`'s **k side** at `n_head` 0, because that kernel already reads a
-`[tokens, heads, head_dim]` input at the operand's own row pitch — exactly this projection's query
-half inside its `heads + 1` width. It needs the model's cos/sin table, and is bounded by the same
-row count the attention block's fusion is, because above that the rows it would read were never
-written this step; with no table it falls back to `rmsnorm` + `rope` over a column slice.
+The query side is `qk_norm_rope_gate`'s k side at `n_head` 0, which reads `[tokens, heads,
+head_dim]` at the operand's row pitch (the query half of the `heads + 1` projection). It needs the
+model's cos/sin table and is bounded by the attention block's fusion row count, above which the
+table is not filled; otherwise `rmsnorm` and `rope` run over column slices.
 
-## The one thing the reference hides
+## Block keys
 
-**A block key is query-independent and, once its four tokens exist, permanent.** The reference
-implementation recomputes every block key inside the per-query loop because it is written for
-clarity. An engine must not: a block key is computed ONCE, when token `t` with `t % 4 == 3`
-arrives, and cached. That turns "a second KV cache" into something much smaller — **block keys**,
-`[n_blocks, 128]` bf16, 64 bytes per *token* per QSA layer, plus **a rolling tail** of at most 3 raw
-keys to complete the next block.
+A block key is independent of the query and, once its four tokens exist, permanent. The reference
+recomputes block keys inside the per-query loop; the engine computes each once, when the token with
+`t % 4 == 3` arrives, and caches it. The indexer's cache is **block keys**, `[n_blocks, 128]` bf16
+(64 bytes per token per QSA layer), plus **a tail** of at most 3 raw keys for the next block.
 
-12 QSA layers x 64 B = **768 B a token**, against the main KV cache's 2 heads x 256 x 2 (K and V)
-x 2 bytes x 12 = 24 KiB a token. **The indexer's cache is 3% of the KV cache.** At 262144 tokens
-it is 192 MiB a sequence; at 32768, 24 MiB.
+12 QSA layers x 64 B = 768 B per token, about 3% of the main KV cache's 24 KiB per token
+(2 heads x 256 x 2 (K and V) x 2 bytes x 12 at bf16): 192 MiB per sequence at 262144 tokens,
+24 MiB at 32768.
 
-## The exactness bound
+## Exactness bound
 
-With `pos + 1 <= budget + ratio - 1 = 2051` visible tokens there are at most `2051/4 = 512`
-complete blocks, the top-k keeps all of them, and the tail is attended unconditionally — so the
-selected set is every visible token and **QSA is dense causal attention bit for bit**. It is not an
-approximation below the bound; it is the same function. Two things follow. A step that carries more
-than one query a sequence — a prefill chunk, or a mixed step — issues the *dense* attention below
-the bound, because a dense kernel reads each key once a query *tile* where the sparse path reads a
-table a query; at decode there is no tile to amortise over, the two cost the same, and the sparse
-path runs at every context. And the bound is the property every change to this subsystem is argued
-against — see "Checking it".
+With `pos + 1 <= budget + ratio - 1 = 2051` visible tokens there are at most 512 complete blocks,
+the top-k keeps all of them and the tail is always attended, so QSA equals dense causal attention
+bit for bit. Below the bound, a step with more than one query per sequence (prefill, mixed or
+speculative) issues dense attention, which reads each key once per query tile where the sparse
+path reads a table per query. Plain decode (one query per sequence) takes the sparse path at every
+context: there is no tile to amortise, and the sparse path stays exercised. The bound is the test
+for every change here (see "Checking").
 
-## How the attention reads a selected set
+## Attention over a selected set
 
-The selected tokens are 4-aligned and scattered, and **page size 4 makes the selection a block
-table**. If the full-attention KV group is paged at 4, a compress block IS a page and the selected
-set IS a paged block table — so sparse attention is "write a 512-entry block table" and call the
-existing attention, with no new kernel at all.
+With the full-attention KV group paged at 4, a compress block is a page and the selected set is a
+paged block table, so sparse attention is the existing `attn_paged` with a 512-entry table.
 
-Nothing structural pins 16: in `r4d_attn_paged_h256_gqa12.hip` the block size is a template
-parameter and every use of it is generic, so `C_EQ("block_size", 16)` on an attention row is a
-declaration and not a limit. And the way an architecture ASKS for four needs no new mechanism —
-`RadKVGroupDecl` deliberately does not carry a block size, because a core that picked its own would
-be a core that has to be edited when a kernel changes; it is taken off the resolved kernel's
-constraints at declare. **The rows and the `#define` have to agree**: a row that claims 16 against a
-kernel compiled at 4 resolves at *declare* and refuses at *issue*, which is a much worse place to
-find out.
+The page size is a kernel constant. The QSA attention units (`r4d_attn_paged_h256_gqa12.hip`,
+`r4d_attn_paged_h256_gqa6_bs4.hip`) build `r4d_attn_paged_gqa8.hip` with `G8_BLOCK_SIZE 4`, and
+their rows declare `C_EQ("block_size", 4)`. `RadKVGroupDecl` carries no block size: the core takes
+it from the resolved attention kernel, and the plugin asks for 4 through the attention op's
+`block_size` parameter. **The rows and the `#define` must agree**: a row claiming 16 against a
+kernel compiled at 4 resolves at declare and fails at issue.
 
-**There is no engine change either.** `attn_paged` takes the block table and `seqused_k` as ORDINARY
-OPERANDS — `arch/common/rad_block_attn_gated_fp8.h` reads them off the KV group batch — so the
-sparse attention is the same op and the same kernel, issued with `sel` in place of the sequence's
-table and `qsa_select`'s `seqused` in place of its length. Nothing in `core/` learns what QSA is.
-The *declaration* order is the reverse of the issue order and is load-bearing: `attn_paged` declares
-`sel` and `seqused` as reads, which is what the buffer plan is computed from, so the arch sets them
-on the attention block before `attn.declare()` and declares the indexer after it.
+`attn_paged` takes the block table and `seqused_k` as ordinary operands
+(`arch/common/rad_block_attn_gated_fp8.h`), so the sparse attention is issued with `sel` in place
+of the sequence's table and `qsa_select`'s `seqused` in place of its length. Nothing in `core/`
+knows about QSA.
 
-## Where the block keys live, and why it decides everything downstream
+Declaration order is the reverse of issue order. `attn_paged` declares `sel` and `seqused` as
+reads, and the buffer plan comes from declared reads, so the architecture sets them on the
+attention block before `attn.declare()` and declares the indexer after it.
 
-**In a KV group, at one page per compress block, indexed by PAGE ID.** The argument is not storage —
-it is that **the selected set then needs no translation at all.** The scorer reads `bk[page_id]`
-through a table the manager already maintains, and the top-512 output is a list of page ids, which
-is the block table the attention reads.
+## Block-key storage
 
-**TWO GROUPS, TWO TABLES, AND EACH OP TAKES THE ONE IT BELONGS TO.** The block keys cannot live in
-the attention group's pages — there is no room — so they are their own `RAD_KV_FULL` group, and a
-sequence's pages there are *different pages* from its attention pages. What makes that harmless is
-that both groups are paged at `ratio`, so **block index `b` means the same thing in both**: the b-th
-4-token block of the sequence.
+Block keys live **in their own `RAD_KV_FULL` group, one page per compress block, indexed by page
+id**. The scorer reads `bk[page_id]` through a table the KV manager already maintains, and the
+top-512 output is a list of attention page ids, which is the block table the attention reads.
+
+A sequence's block-key pages differ from its attention pages, but both groups are paged at
+`ratio`, so **block index `b` means the same in both**. Each op takes the table of the group it
+serves:
 
 | op | table it takes |
 |---|---|
-| `qsa_score` | the **block-key** group's, because it is gathering block keys |
-| `qsa_select` | the **attention** group's, because its output is what the attention reads |
+| `qsa_score` | the block-key group's, because it gathers block keys |
+| `qsa_select` | the attention group's, because its output is what the attention reads |
 
-Nothing is remapped — the index `b` is the join, and it is the same number on both sides. Getting it
-backwards scores one sequence's keys through another's pages. A `RAD_BUF_PERSIST` array indexed by
-`(slot, block within the sequence)` would work, be simpler to declare, and put that translation back
-in three places.
+Swapping them scores one sequence's keys through another's pages. A `RAD_BUF_PERSIST` array
+indexed by `(slot, block)` would be simpler to declare but needs a translation in three places.
 
-**The geometry is a container, not an attention shape.** A `RAD_KV_FULL` group stores
-`[pages, kv_heads, block_size, 2*head_dim]`, so with `kv_heads = 1`, `block_size = ratio` and
-`head_dim = n / (2*ratio)` a page holds exactly `n` contiguous values — one block key — and the
-manager allocates exactly one page per `ratio` tokens. Here `head_dim` is `128 / 8 = 16`, and
-`2 * head_dim * ratio == n` is the assertion that keeps the fiction honest. No waste. **The group's
-page size comes from the first op declared after it that carries a `block_size`**
-(`Builder::find_kv_consumer`) — *any* op, not only an attention one — so `qsa_block_key` declaring
-`block_size` is what sizes this group, exactly as `attn_paged` sizes the attention group.
+A `RAD_KV_FULL` group stores `[pages, kv_heads, block_size, 2*head_dim]`. With `kv_heads = 1`,
+`block_size = ratio` and `head_dim = n / (2*ratio)` (here `128 / 8 = 16`), a page holds exactly
+one block key of `n` values (`2 * head_dim * ratio == n` is asserted). A group's page size comes
+from the first later-declared op with a `block_size` (`Builder::find_kv_consumer`), so the group is
+declared immediately before `qsa_block_key`, whose `block_size` sizes it.
 
-## The tail is state, and storing it as scratch fails three ways
+## The tail
 
-A block key needs `ratio` consecutive raw keys, and at decode three of them are from earlier steps.
-The tail is a `RAD_KV_LINEAR` group with `state_dim` `{ratio + n_spec, head_dim}` bound to every QSA
-layer including the MTP head's — and the reason is worth stating as failures, because each
-alternative is plausible and produces fluent wrong text.
+A block key needs `ratio` consecutive raw keys; at decode three come from earlier steps. The tail
+is a `RAD_KV_LINEAR` group with `state_dim` `{ratio + max_spec, head_dim}`, bound to every QSA
+layer including the MTP head's. The alternatives all produce fluent wrong text:
 
-| a tail stored as… | what it does | fires when |
+| a tail stored as… | what goes wrong | when |
 |---|---|---|
-| ONE buffer for the whole model | layer L pools layer L-1's raw keys, because `index_qk_proj` is per layer | every decode step, always — three of every four keys in a completing block |
-| a plane indexed by the BATCH ROW | a request that outlives an earlier one inherits its keys, because the scheduler orders a step by priority and stable-sorts decode first | any step after a concurrent request retires |
-| `ratio` rows indexed `pos % ratio` | a rejected draft restarts the next step at a position this one has already overwritten, so a completed block is REBUILT from a future token's key | any speculative step that straddles a block boundary and does not accept everything |
+| one buffer for the whole model | layer L pools layer L-1's raw keys, because `index_qk_proj` is per layer | every decode step: three of every four keys in a completing block |
+| a plane indexed by the batch row | a request that outlives an earlier one inherits its keys, because the scheduler orders a step by priority and stable-sorts decode first | any step after a concurrent request retires |
+| `ratio` rows indexed `pos % ratio` | a rejected draft restarts the next step at a position this one already overwrote, so a completed block is rebuilt from a future token's key | any speculative step that straddles a block boundary and does not accept everything |
 
-All three are one shape: **the tail is state, and it was stored as scratch.** It is read on a later
-step than the one that wrote it, and it is keyed by layer, by sequence and by position — none of
-which a shared plane indexed by a step-local row can carry. `cu_seqlens` answers *which sequence a
-token belongs to in this step*; it says nothing about where that sequence's keys may live. A KV
-group answers all three, and two more things fall out for nothing: the engine ZEROES a slot when it
-hands one out, and it checkpoints the state with the rest of the linear state, so a resume onto a
-half-built block reads the keys that block was built from and not whatever the last tenant left.
-A `RAD_KV_WINDOW` of width `ratio` is the near miss — it holds the last four tokens of the STEP,
-which at decode is exactly the block completing, but within a prefill chunk many blocks complete and
-their keys are long gone, so the window would have to be as wide as the chunk and is then not a tail.
+The tail is read on a later step than the one that wrote it and is keyed by layer, sequence and
+position; `cu_seqlens` gives only a token's sequence within the step. A KV group slot is zeroed on
+hand-out and checkpointed with the linear state, so a resume onto a half-built block reads the keys
+it was built from. A `RAD_KV_WINDOW` of width `ratio` holds only the step's last four tokens, which
+is the completing block at decode but not within a prefill chunk.
 
-**Two small ops carry it, and their order is load-bearing rather than tidy.** `qsa_work` gathers the
-blocks completing this step into the flat list `qsa_block_key` reads; `qsa_tail_store` writes this
-step's keys into the state. **`qsa_work` is issued BEFORE `qsa_tail_store`**, because the gather
-reads raw keys that are in the tail from earlier steps and the store is about to overwrite them. A
-token at position `p` lands at row `p % ring`, so a completing block's rows are already in order,
-and a sequence that completes nothing gets `page = -1` and is skipped — one launch a layer a step,
-whatever the batch is doing.
+`qsa_work` gathers the blocks completing this step into the flat list `qsa_block_key` reads, and
+`qsa_tail_store` writes this step's raw keys into the state. **`qsa_work` is issued before
+`qsa_tail_store`**, because the gather reads tail keys the store overwrites. Position `p` lands at
+row `p % ring`. The work list has `ceil(T / ratio) + n_seq` items; items past the real count get
+`page = -1` and are skipped, so it is one launch per layer per step.
 
-## Selecting per query, which is what prefill needs
+## Per-query selection (prefill)
 
-At decode there is one query a sequence, so a per-sequence selection is the right granularity by
-accident; at prefill every query in a chunk selects its own set out of one shared history. Both
-scoring ops take `cu_seqlens`, so `m` is a QUERY row while the block table stays the sequence's —
-`cu_seqlens` is the only operand in a batch that says which sequence a token belongs to. Each query
-is then bounded by its own position, `n = min(nc[seq], (pos + 1) / ratio)`, which at decode is
-`nc[seq]` itself.
+At prefill every query in a chunk selects its own set from one shared history. Both scoring ops
+take `cu_seqlens`, so `m` is a query row while the block table stays the sequence's. Each query is
+bounded by its own position, `n = min(nc[seq], (pos + 1) / ratio)` (at decode, `nc[seq]`).
 
-**And the attention is issued one row a query.** `attn_paged` indexes its block table and its length
-by the ROW, and nothing ever said a row had to be a sequence: a chunk of `T` queries issued as `T`
-rows of `q_len` 1, each with its own `sel` and `seqused`, *is* per-query sparse attention. Same op,
-same kernel, for the second time. It is chunked at `max_seqs` rows because the decode kernel's
-split-KV scratch is sized at declare from `max_seqs * q_len_max`.
+The attention is issued **one row per query**: `attn_paged` indexes its block table and length by
+row, so `T` queries issued as `T` rows of `q_len` 1, each with its own `sel` and `seqused`, is
+per-query sparse attention. Launches are chunked at `max(max_seqs, 256)` rows (the gated form takes
+the whole step), because the decode kernel's split-KV scratch is sized at declare from `max_seqs`
+and `q_len`.
 
-**The partial page is a position test, and that is a causality rule.** `bt[n] >= 0` would be right
-for every case decode can present — a decode query on a block boundary has `bt[nc] == -1`, because the KV
-manager has not allocated past the sequence. Mid-chunk the same query has *later tokens of the same
-chunk* in `bt[n]`: a live page entirely in its future, which `seqused` would then cover in full. The
-rule is the query's position, `(pos + 1) % ratio != 0`.
+**The partial page is decided by position.** At decode `bt[nc] == -1` on a block boundary, since
+nothing is allocated past the sequence, so `bt[n] >= 0` would work there. Mid-chunk, the same
+query finds a later token's live page in `bt[n]`, which `seqused` would then cover. The partial
+page is appended only when `(pos + 1) % ratio != 0`.
 
-## What the indexer costs
+## Cost
 
-**The indexer is the only part of a decode step that grows with context.** `qsa_score` and
-`qsa_select` both scale with the number of compressed blocks in the history and both run once a
-layer, so between them they account for the whole of the step-time-against-context curve; every
-other op in a hybrid of linear layers and a constant-cost attention is flat to within noise. So the
-pair is timed AT LENGTH rather than at a convenient context, and `r4d_selftest --perfqsa` does it
-with no model — passing the declared width and the live context separately, because the launch
-geometry comes from the declaration and the work from `nc`. Both kernels are shaped by that:
-`qsa_score` reads the key history once a query TILE and not once a query row, the tile landing on a
-sequence boundary because a sequence contributes exactly `1 + n_spec` rows and `cu` is their
-cumulative count; `qsa_select` splits the block list into chunks that each find a local top-k, which
-is exact because a chunk's local top-k contains every global top-k member of that chunk — that
-argument and its tie rule live in `libr4d/r4d_qsa_select_bf16.hip`, beside the code depending on
-them.
+The indexer is the only part of a decode step that grows with context: `qsa_score` and
+`qsa_select` scale with the number of compressed blocks, once per layer. `r4d_selftest --perfqsa
+CTX [M] [iters]` times them at a real context length with no model, passing the declared width and
+the live context separately (launch geometry comes from the declaration, work from `nc`).
 
-**The reduction is on the VALU and not the LDS crossbar**, which is a property of the architecture
-rather than a measurement: `__shfl_xor` lowers to `ds_bpermute_b32` at any offset, so a shuffle
-butterfly queues on the LDS pipe, while DPP performs the exchange as a *modifier on the add* —
-`row_xmask` covers XOR offsets 8, 4, 2 and 1 within each row of sixteen and `v_permlanex16_b32`
-covers the one that crosses rows. The lanes exchanged and the order of the adds are identical, so it
-is bit-identical and not merely equivalent. That reasoning belongs beside the instructions and lives
-there: `libr4d/r4d_common.h`'s `r4d_wave_sum`.
+- `qsa_score` reads the key history once per 4-row query tile, matching a decode sequence's
+  `1 + n_spec` rows at depth 3; a tile straddling two sequences is processed per part.
+- `qsa_select` splits the block list into chunks that each find a local top-k, exact because a
+  chunk's local top-k contains every global top-k member in it. The proof and the tie rule are in
+  `libr4d/r4d_qsa_select_bf16.hip`.
+- Wave reductions use DPP (`row_xmask` for XOR offsets 8..1, `v_permlanex16_b32` across rows), not
+  `__shfl_xor`, which lowers to `ds_bpermute_b32` and queues on the LDS pipe. Same lanes and add
+  order, so bit-identical (`libr4d/r4d_common.h`, `r4d_wave_sum`).
 
-**Any two forms of the selection kernel must produce the same BYTES**, not the same set. A selected set has
-no order, so a kernel is free to put entries above the threshold at the front of the table and the
-ties at the back — but the attention accumulates a softmax over the pages *in table order*, and
-float addition is not associative. A second implementation reproduces the first's layout slot for
-slot or it changes the model's output.
+**Any two forms of the selection kernel must produce the same bytes**, not only the same set: the
+attention sums its softmax over pages in table order, and float addition is not associative.
 
-**And the caller says how much history there is.** Both ops size their grid from the *declared*
-width, because the live count is device data and a grid is a host-side number — so without help a
-short prompt launches for the whole `--max-model-len`. The architecture narrows the score operand's column
-count to a host-side ceiling the batch already carries, leaving the pitch at the declaration's.
-**Every term of that ceiling is slack on purpose**, because an under-estimate drops blocks from the
-selection and nothing would say so.
+**The score plane is the one buffer whose size is a product of the deployment's bounds** — a row
+of `max_ctx / ratio` floats a query, 512 MiB at a 2048-row step and 256K of context. Under
+`--prefill-span`, where every step that mixes sequences fits in a MoE pass
+(`RadBuildCtx::max_mixed_tok`), it is declared a pass tall instead of `--max-num-batched-tokens`
+rows: a wider step is one sequence, scored and selected in windows of the plane's rows, each handed
+as a sequence of its own rows. Every operand a query row reads is its own (query, position,
+selection), so a row is scored and selected exactly as in one pass, and a row two windows share is
+written twice with the same bytes.
 
-## Checking it
+**The caller bounds the history.** Both ops size their grid from the declared width (the live count
+is device data), so a short prompt would otherwise launch for the whole `--max-model-len`. The
+architecture narrows the score operand's column count to a host-side ceiling from the batch, with
+the pitch unchanged. **Every term of the ceiling is generous**, because an underestimate silently
+drops blocks.
 
-There is no switch that runs sparse and dense attention over the same tokens, deliberately: above
-the bound, dense attention is *not* the attention the checkpoint was trained with, so a knob for it
-is a way to make a server quietly serve a different model. `libref`
-implements none of the QSA ops either, so there is no reference-plugin comparison for the subsystem
-as a whole. What exists instead is what a change here is checked against:
+## Checking
 
-- **per-kernel oracles in `r4d_selftest`** — `qsa_block_key` and `qsa_score` against an f64
-  evaluation of the same formula, `qsa_work` and `qsa_tail_store` against a host walk of the same
-  batch, `qsa_select` against a host sort, a prefill case for the per-query join, and a
-  split-vs-unsplit case asserting BIT identity on a fixture whose scores are mostly ties, so the tie
-  rule rather than the radix decides the answer;
-- **`RADIANCE_DEBUG_QSA`**, the only window into a selection: `nc`, `nsel`, `seqused` and the head of
-  the table, for the first few steps. `nc` above `topk` is blocks being dropped on purpose, which is
-  what tells QSA doing its job apart from a divergence. It synchronises the stream, so it is an
-  environment variable and it is off.
+There is deliberately no switch that forces dense attention above the bound, where it is not the
+model the checkpoint was trained as. libref implements only `qsa_block_key` of the QSA ops, so
+there is no whole-subsystem reference comparison. Changes are checked with:
 
-**Count the reach, not the prompt.** The bound is on the context each query sees, so a prompt a few
-tokens under it crosses it partway through the decode and is *supposed* to start differing there.
+- **`r4d_selftest` oracles**: `qsa_block_key` and `qsa_score` against f64 evaluations,
+  `qsa_work` and `qsa_tail_store` against a host walk of the batch, `qsa_select` against a host
+  sort, a prefill case for the per-query join, the wide-launch form against the single-workgroup
+  form, and split against unsplit at bit identity on mostly-tied scores, so the tie rule decides;
+- **`RADIANCE_DEBUG_QSA`**: prints `nc`, `nsel`, `seqused` and the head of the table for the first
+  few steps. `nc` above `topk` is intended dropping, not a divergence. It synchronises the stream.
+
+**Count the reach, not the prompt.** The bound is on the context each query sees, so a prompt a
+few tokens under it crosses the bound during decode and is expected to start differing there.
diff --git a/docs/TOOLS.md b/docs/TOOLS.md
index 7f1478e9..c11c1551 100644
--- a/docs/TOOLS.md
+++ b/docs/TOOLS.md
@@ -1,26 +1,32 @@
-# Radiance — tools reference
+# radiance tools reference
 
-Every flag of every tool, with examples. For getting started, read [GUIDE.md](GUIDE.md) first.
+Every flag of every tool, with examples. Start with [GUIDE.md](GUIDE.md).
 
-Six binaries are installed beside `radiance`, plus the shell harnesses in `scripts/`:
+Six binaries and the `rad-export` script are installed beside `radiance`; the shell harnesses
+live in `scripts/`:
 
 | | |
 |---|---|
 | [`rad-info`](#rad-info) | print what a `.rad` container holds. Loads no plugins |
 | [`rad-convert`](#rad-convert) | safetensors or GGUF in, `.rad` out, quantised by a recipe |
+| [`rad-export`](#rad-export) | a finetune (merged checkpoint or LoRA adapter) to a `.rad`, with the base model's own recipe |
 | [`rad-kbench`](#rad-kbench) | correctness, completeness and speed of every kernel library |
 | [`rad-tune`](#rad-tune) | benchmark each kernel's tunable space at this model's shapes, on this machine |
 | [`rad-schemas`](#rad-schemas) | print and diff the op schemas plugins declare |
-| [`rad-tokcheck`](#rad-tokcheck) | hold the tokeniser to its reference encoder and to HuggingFace's ids over real text, and time it |
+| [`rad-tokcheck`](#rad-tokcheck) | compare the tokeniser with its reference encoder and with HuggingFace's ids over real text, and time it |
 | [`radiance --kld-*`](#the-kl-mode) | KL divergence of a quantised model against the bf16 one, at every position of a corpus |
 | [`scripts/`](#the-shell-harnesses) | bring a model up, measure it, assert on what comes back |
 
-Three of them — `rad-convert`, `rad-kbench`, `rad-tune` — **are the engine's startup with a
-different last step**. They load the same plugins in the same hierarchy and run the same declare
-phase. A tool that resolved kernels differently from the engine would be a tool whose answers are
-about a different program.
+[`rad-avx-check`](#rad-avx-check), which checks a host kernel library against libref without a GPU,
+is built beside libavx rather than installed.
 
-Every tool that loads plugins honours `RADIANCE_HOME` and `RADIANCE_KERNELS`.
+`rad-convert`, `rad-kbench` and `rad-tune` run the engine's startup with a different last step:
+the same plugins, in the same hierarchy, through the same declare phase, so they resolve kernels
+as the engine does.
+
+Every tool that loads plugins honours `RADIANCE_HOME` and `RADIANCE_KERNELS`, and reads them, and
+`--kernels`, as the engine does. A numeric option takes a whole number, as the engine's do: `12k`,
+`auto` (where the option does not name it) or an empty value is refused with exit status 2.
 
 ---
 
@@ -28,18 +34,21 @@ Every tool that loads plugins honours `RADIANCE_HOME` and `RADIANCE_KERNELS`.
 
 ```
 rad-info [options] 
+rad-info --plugins [--home DIRS]
 
   -v, --verbose      list every tensor, not just the per-unit summary
       --meta         print the metadata table and stop
       --vocab        print the vocab summary and its normaliser chain, and stop
       --profile N    print the top N entries of the expert profile (default 20, 0 = all)
       --recipe       print the recipe the container was converted with, and stop
+      --plugins      print every plugin the $RADIANCE_HOME search path offers, as the
+                     engine loads it, and stop
+      --home DIRS    the search path for --plugins (default $RADIANCE_HOME)
 ```
 
-This is the tool you reach for when something is wrong, so it is written for reading: aligned
-columns, byte counts in human units, and every number that could mislead labelled with what it
-actually counts. **It opens the container read-only and loads no plugins** — a container names no
-kernel library, so there is nothing to load.
+It opens the container read-only and, except for `--plugins`, loads no plugins: a container names
+no kernel library. Output is aligned, byte counts are in binary units, and each count says what it
+counts.
 
 ```sh
 rad-info flashnext-w4.rad
@@ -47,7 +56,7 @@ rad-info flashnext-w4.rad
 
 ```
 flashnext-w4.rad
-  format        RAD2, 166.4 GiB, little-endian
+  format        RAD2, ... GiB, little-endian
   architecture  qwen4exp
   model         Qwen3.8-Flash-Next
   source quant  (none)
@@ -55,17 +64,21 @@ flashnext-w4.rad
   created by    rad-convert ...
 
   section          offset        bytes    count
-  strings             256      1.2 MiB        -
-  metadata        1258752      8.4 KiB      214
-  directory       ...
-  planes          ...
-  encodings       ...
-  data              ...        166.1 GiB    ...
+  strings          ...
+  metadata         ...
+  directory        ...
+  planes           ...
+  encodings        ...
+  vocab            ...
+  profile          ...
+  data             ...
 ```
 
-Every weight is listed with its **encoding** — `fp8_e4m3*bf16[128x128]`, `i4*bf16[1x128]/fwht128`,
-`bf16` — its logical shape, and what made it: the checkpoint as it stood, or the quantiser and
-options of the recipe rule that matched. The totals are by encoding and by quantiser.
+The metadata table, the weight directory (grouped by layer and movement unit), the vocab and the
+expert profile follow. With `-v`, every weight is listed with its encoding
+(`fp8_e4m3*bf16[128x128]`, `i4*bf16[1x128]/fwht128`, `bf16`), its logical shape and what made it:
+the checkpoint as it stood, or the quantiser and options of the recipe rule that matched. Totals
+are given by encoding and by what made the weight.
 
 ```sh
 rad-info --meta m.rad                         # the metadata table alone
@@ -73,6 +86,7 @@ rad-info --vocab m.rad                        # vocab + normaliser chain
 rad-info --recipe m.rad                       # the recipe, expanded, one rule a line
 rad-info -v m.rad | head -40                  # every tensor, its encoding, shape and planes
 rad-info --profile 0 m.rad                    # the whole expert-popularity profile
+rad-info --plugins                            # every plugin on the search path
 ```
 
 ---
@@ -94,47 +108,50 @@ rad-convert [options]  -o 
       --tokenizer F    tokenizer.json; its declared chain is baked instead of being
                        reconstructed from a pre-tokenizer name
       --imatrix F      llama.cpp imatrix: expert profile, column importances, error weighting
-      --set K=V        a metadata key, seen by declare AND written into the container. Repeatable
+      --set K=V        a metadata key, seen by declare and written into the container. Repeatable
       --max-tok N      the max_tok declare is run at (default 8192)
       --max-ctx N      the context bound declare is run at. Default: the checkpoint's
                        training context
-      --draft-model DIR  a SECOND checkpoint: a drafter that ships as its own repository
+      --draft-model DIR  a drafter that ships as its own repository, merged under `draft.`
       --kv-cache-dtype T  bf16 | fp8, the cache width declare is run at. Default: the first
                        at which every op resolves; the container is the same at either
       --max-spec N     the max_spec declare is run at (default 4, or the block a drafter
-                       states). 0 leaves the draft head out
+                       states; a number given here is used as given). 0 leaves the draft
+                       head out
       --reuse FILE     copy every weight an earlier container holds identically
+      --changed FILE   with --reuse: checkpoint tensors (one name a line) that differ from
+                       the --reuse container's source; every weight that reads one is converted
       --in-place       with --reuse: extend that container instead of writing a new one
-      --plan-only      declare, plan every weight's encoding, print the plan, then STOP
+      --plan-only      declare, plan every weight's encoding, print the plan, and stop
       --report N       the worst N quantisation errors to print (default 20)
   -v, --verbose
 ```
 
 ### What it does
 
-A container holds each weight as the **canonical planes of its encoding** — codes, scales, zero
-points, a codebook — row-major, and no kernel library is named anywhere in it. The kernels
-rearrange those planes into their own layouts when the model loads, so a kernel library can change
-any layout it has without a reconvert. What rad-convert decides is the *numbers*:
+A container holds each weight as the canonical planes of its encoding (codes, scales, zero points,
+a codebook), row-major, and names no kernel library. Kernels rearrange the planes into their own
+layouts at load, so a kernel library can change its layouts without a reconvert. rad-convert
+decides the numbers:
 
 1. Reads the checkpoint's `config.json` (or GGUF metadata).
-2. Loads the architecture, kernel and quantiser plugins and runs **declare** — the same phase the
-   engine runs. The architecture plugin's name map says which checkpoint tensors make each declared
-   weight; `rad_weight_encoding` answers each one with the encoding the **recipe** gives it.
-3. Every op resolves, and every resolved kernel's `layout` hook is asked about the planned encoding.
-   A recipe nothing can serve is refused here, before a byte is written.
-4. Writes each logical weight once: the checkpoint's own bytes where no rule matches, or the planes
-   the matching rule's quantiser writes, a block of rows at a time.
+2. Loads the architecture, kernel and quantiser plugins and runs declare, as the engine does. The
+   architecture plugin's name map says which checkpoint tensors make each declared weight, and
+   `rad_weight_encoding` answers each one with the encoding the recipe gives it.
+3. Resolves every op and asks each resolved kernel's `layout` hook about the planned encoding. A
+   recipe no kernel can serve is refused here, before a byte is written.
+4. Writes each logical weight once: the checkpoint's own bytes where no rule matches, otherwise the
+   planes the matching rule's quantiser writes, a block of rows at a time.
 5. Measures every quantised weight against its source through the core's decoder and prints the
    worst, imatrix-weighted when `--imatrix` is given.
 6. Bakes in the tokeniser, the chat template, the metadata, the recipe and any draft head.
 
 ### Recipes
 
-Ordered rules from a logical weight name to a quantiser and its options. **The first rule whose
-pattern matches decides**; a weight no rule matches keeps the checkpoint's encoding, which has to be
-one the engine serves as it is — bf16, f16, f32, or block-scaled FP8 (`X.weight` with
-`X.weight_scale_inv`). Anything else is named and refused.
+A recipe is an ordered list of rules from a logical weight name to a quantiser and its options.
+The first rule whose pattern matches decides. A weight no rule matches keeps the checkpoint's
+encoding, which must be one the engine serves as it is: bf16, f16, f32, or block-scaled FP8
+(`X.weight` with `X.weight_scale_inv`). Anything else is named and refused.
 
 ```
 # PATTERN                      QUANTISER  OPTIONS
@@ -144,11 +161,12 @@ output.weight                  rtn        codes=fp8_e4m3 block=128x128 scale=bf1
 blk.*.weight                   rtn        codes=fp8_e4m3 block=128x128 scale=bf16
 ```
 
-A pattern is a glob over the whole name (`*` crosses dots, `?` is one character). `$NAME` in an
-option is the environment's, and an unset one is refused. `--quant` adds rules on the command line,
-ahead of the file's: `--quant 'output.weight=rtn:codes=fp8_e4m3,block=128x128,scale=bf16'`.
-A quantiser that declines a weight — `rtn` declines a rank-1 tensor, so a pattern that happens to
-match a norm keeps the norm as it is — leaves it to the checkpoint's encoding.
+A pattern is a glob over the whole name: `*` crosses dots, `?` is one character. `$NAME` (or
+`${NAME}`) in an option is taken from the environment; an unset variable is refused. `--quant`
+adds rules ahead of the file's:
+`--quant 'output.weight=rtn:codes=fp8_e4m3,block=128x128,scale=bf16'`. A quantiser that declines a
+weight leaves it in the checkpoint's encoding; `rtn` declines a rank-1 tensor, so a pattern that
+also matches a norm leaves the norm as it is.
 
 `rad-convert --list-quantizers` prints every quantiser and its options. The built-in set is
 `libquant`:
@@ -158,12 +176,12 @@ match a norm keeps the norm as it is — leaves it to the checkpoint's encoding.
 | `rtn` | round to nearest on a grid; the scale of each block chosen by `rule` |
 | `gptq` | error feedback against the layer's input Hessian (`calib=DIR`, damped by `damp`, default 0.01 of its mean diagonal), scales fixed from the weight first; `act_order=1` quantises the columns by descending input energy and stores the permutation as the encoding's `perm` transform; `cd=N` adds N sweeps of coordinate descent after the loop, every code re-chosen at its conditional optimum against the same Hessian |
 | `awq` | each input column scaled by its activation magnitude to a searched power, then a per-block clip search, both against the Hessian; the column scales are the encoding's last scale level |
-| `autoround` | sign-gradient descent on a rounding offset a value and a range factor a block, against the Hessian; `iters` steps of N·K² multiply-adds each |
+| `autoround` | sign-gradient descent on a rounding offset per value and a range factor per block, against the Hessian; `iters` steps of N·K² multiply-adds each |
 | `paroquant` | a channel scaling and `stages` rounds of Givens pair rotations, learned against the Hessian, then AutoRound on the rotated weight; the encoding's `givens` transform |
-| `ggml` | `type=` one of llama.cpp's formats -- q4_0, q4_1, q5_0, q5_1, q8_0, q2_K..q6_K, iq4_nl, iq4_xs, iq2_xxs, iq2_xs, iq2_s, iq3_xxs, iq3_s, iq1_s, iq1_m -- by llama.cpp's own search, imatrix-weighted, the codes byte for byte llama.cpp's, stored as each type's affine planes; iq2_xxs, iq2_xs and iq1_s need `--imatrix` |
+| `ggml` | `type=` one of llama.cpp's formats (q4_0, q4_1, q5_0, q5_1, q8_0, q2_K..q6_K, iq4_nl, iq4_xs, iq2_xxs, iq2_xs, iq2_s, iq3_xxs, iq3_s, iq1_s, iq1_m), chosen by llama.cpp's own search, imatrix-weighted; the codes are byte for byte llama.cpp's, stored as each type's affine planes. iq2_xxs, iq2_xs and iq1_s need `--imatrix` |
 | `cast` | a float weight in another float dtype (`dtype=` f32, bf16, f16, fp8_e4m3, fp8_e5m2), no scale |
 
-and the grid options every quantiser but `ggml` and `cast` takes:
+Every quantiser except `ggml` and `cast` takes the grid options:
 
 | option | |
 |---|---|
@@ -173,45 +191,45 @@ and the grid options every quantiser but `ggml` and `cast` takes:
 | `scale` | f32, bf16, f16, fp8_e4m3, e8m0; under `scale2` also an integer sub-scale, u4..u8, i6, i8 |
 | `scale2`, `group2` / `block2` | a second scale level the first is relative to (default the whole tensor) |
 | `scale2_value` | the second level fixed at this value, exact in `scale2`'s dtype, for every block of it |
-| `zero` | an integer zero point a block, making the grid asymmetric |
+| `zero` | an integer zero point per block, making the grid asymmetric |
 | `transform=fwhtN` | rotate each row by the Hadamard first |
 | `rule` | `absmax`, `mx` (the OCP shared exponent), `fixed` (`scale_value=`), `search` (least squared error over candidates and their refits, imatrix-weighted) |
 | `clamp` | a signed code's range, `full` or `sym` |
 
-So MXFP4 is `codes=fp4_e2m1 group=32 scale=e8m0`, NVFP4 `codes=fp4_e2m1 group=16 scale=fp8_e4m3
-scale2=f32`, NF4 `table=nf4 group=64`, a K-quant-like grid `codes=i4 group=32 scale=u6 scale2=f16
-group2=256`, and a ternary BitNet weight `table=ternary`.
+Examples: MXFP4 is `codes=fp4_e2m1 group=32 scale=e8m0`; NVFP4 is `codes=fp4_e2m1 group=16
+scale=fp8_e4m3 scale2=f32`; NF4 is `table=nf4 group=64`; a K-quant-like grid is `codes=i4
+group=32 scale=u6 scale2=f16 group2=256`; a ternary BitNet weight is `table=ternary`.
 
-**A container can hold only what some kernel reads.** The converter checks every planned encoding
-against the layout hooks of the kernels declare resolved and refuses one nothing accepts, so a
-grid libquant can write is a container's only once a kernel library takes it. libr4d reads the
-plain floats; block-scaled fp8 and fp8 rows; int8 block rows (the W8A8 trunk and lm_head); the
-routed experts as fp8, int4 (`i4*bf16[1x128]/fwht128`) or the `w4nl`/`w5nl` codebooks under E4M3
-scales ([MOE-W4.md](MOE-W4.md)); the dense w4, w8 and mxfp4 GEMM rows; and the 2-bit draft head.
-Every encoding decodes through the core all the same, which is what the converter's error report,
-the oracle and these quantisers' tests read it with.
+A container can hold only what some kernel reads. The converter checks every planned encoding
+against the layout hooks of the kernels declare resolved and refuses one that no kernel accepts,
+so a grid libquant can write is usable only once a kernel library takes it. libr4d reads the plain
+floats; block-scaled fp8 and fp8 rows; int8 block rows (the W8A8 trunk and lm_head); the routed
+experts as fp8, int4 (`i4*bf16[1x128]/fwht128`) or the `w4nl`/`w5nl` codebooks under E4M3 scales
+([MOE-W4.md](MOE-W4.md)); the dense w4, w8 and mxfp4 GEMM rows; and the 2-bit draft head. Every
+encoding also decodes through the core, which the converter's error report, the oracle and the
+quantisers' tests use.
 
-The recipes for the containers this tree serves are in `data/recipes/`, and the conversions of
-record in `scripts/convfn.sh` and `scripts/convdspark.sh` use them.
+The recipes for the containers this tree serves are in `data/recipes/`. `scripts/convfn.sh` and
+`scripts/convdspark.sh` are the reference conversions.
 
 ### Examples
 
 ```sh
-# Flash-Next as it is served (w4nl64-i8lm.rad): codebook experts by GPTQ against the calibration
+# Flash-Next as served (w4nl64-i8lm.rad): codebook experts by GPTQ against the calibration
 # Grams in $CALIB, an int8 trunk (docs/MOE-W4.md, "What is served"). The recipe's expert rule
-# reads calib=$CALIB, and an unset variable is refused
+# reads calib=$CALIB, so CALIB must be set
 CALIB= rad-convert  \
     -o w4nl64-i8lm.rad --recipe data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe \
     --home $RADIANCE_HOME -v
 
-# A rule given on the command line goes ahead of the recipe's: here the experts at plain int4 by
-# GPTQ, under a recipe whose own expert rule rounds to nearest
+# A --quant rule goes ahead of the recipe's: the experts as plain int4 by GPTQ, under a recipe
+# whose own expert rule rounds to nearest
 CALIB= rad-convert  -o flashnext-w4.rad \
     --quant 'blk.*.ffn_*_exps.*.weight=gptq:codes=i4,group=128,scale=bf16,transform=fwht128,calib=$CALIB' \
     --recipe data/recipes/qwen4exp-w4-hc8m.recipe --home $RADIANCE_HOME -v
 
 # A block-fp8 checkpoint needs no recipe: every weight is kept as it is. It needs no container
-# either -- `radiance --model` serves the checkpoint directly -- unless a tier only a container
+# either (`radiance --model` serves the checkpoint directly) unless a tier only a container
 # has is wanted (GUIDE §3.4)
 rad-convert  -o q38-27b-fp8.rad
 
@@ -222,7 +240,7 @@ rad-convert  -o q38-27b-fp8.rad --recipe data/recipes
     --set quantization_config.fmt=e4m3 --set "quantization_config.weight_block_size=128 128" \
     --set quantization_config.activation_scheme=dynamic
 
-# Check the plan without writing 166 GiB
+# Check the plan without writing anything
 rad-convert $SRC -o /dev/null --recipe r.recipe --plan-only -v
 
 # Merge a drafter that ships as its own repository
@@ -233,164 +251,349 @@ rad-convert  -o minicpm5-2b-dspark.rad \
 rad-convert $SRC -o new.rad --recipe new.recipe --reuse old.rad
 ```
 
-### The flags that catch people
+### Flag notes
 
-**`--tokenizer`.** Pass it for a GGUF. Without it the tokeniser chain is reconstructed from a
-pre-tokeniser *name*, which is a guess; a safetensors checkpoint's `tokenizer.json` is found beside
-it. Also make sure a `chat_template.jinja` sits beside `tokenizer_config.json` in the checkpoint —
-newer repos moved the template out of the JSON, and the symptom of missing it is `chat is 501`.
+- `--tokenizer`: pass it for a GGUF. Without it the tokeniser chain is reconstructed from a
+  pre-tokeniser name, which is a guess. A safetensors checkpoint's `tokenizer.json` is found beside
+  it. A checkpoint that keeps its chat template in `chat_template.jinja` needs that file beside
+  `tokenizer_config.json`; without a template, `/v1/chat/completions` answers 501.
+- `--set K=V` states a convert-time choice that must also hold at serve time: the key is handed to
+  declare and written into the container. A weight's storage format is not such a choice (the
+  encoding is in the container and the plugin reads it there), but the serving plugin is: a
+  `quantization_config.*` key re-derives the descriptor the plugin is chosen by. A bf16 checkpoint
+  whose recipe writes Qwen's block fp8 is therefore declared as that format and converted for the
+  fp8 plugin (`data/recipes/q38-27b-fp8block-df2.recipe` has the keys).
+- `--max-ctx`: some graphs depend on the context bound. Qwen4-Exp sizes its QSA buffers by it and
+  refuses a `--max-tok` and context pair whose score plane would pass 2 GiB.
+- `--max-spec`: a container carries what the model can serve, so a draft head is written even when
+  this run would not draft. `0` leaves it out.
+- `--draft-model` merges a drafter here; the engine refuses the flag. The drafter's tensors go in
+  under a `draft.` prefix and its config under `draft.` keys. It has no embedding and no `lm_head`
+  of its own; it uses the target's.
+- `--imatrix` supplies the expert-popularity profile the placement planner ranks units by, hands
+  each quantiser its weight's column importances, and weights the error report.
+- `calib=DIR` (`gptq`, `awq`, `autoround`, `paroquant`) is a directory an engine run wrote with
+  `RADIANCE_CALIB_DIR`: each layer's Gram matrices of the input, in the domain the kernel multiplies
+  it in. A container that stores a weight rotated records the rotated input, and a recipe that
+  rotates the same weight reads it as it is. A weight with no file there is quantised uncalibrated,
+  and the converter says so; `awq`, `autoround` and `paroquant` use the imatrix's diagonal instead
+  when `--imatrix` gives one. The three-step calibrated conversion is in [MOE-W4.md](MOE-W4.md).
+- `autoround` and `paroquant` are slow. AutoRound's 200 default steps each cost N·K² multiply-adds;
+  on a 16-core Zen 5 at about 2.5 TFLOP/s that is minutes for a 17408-wide down projection and
+  most of a working day for a 27B dense model. `iters=50` takes a quarter of the time.
+- `--reuse` / `--in-place` match a weight on its encoding, quantiser, options and shape, not on its
+  source bytes, and carry whatever calibration made the old planes. Use `--reuse` only when the
+  source and the calibration are the same, or name the changed source tensors with `--changed`.
+  `--in-place` writes new weights past the container's end and the header last; it refuses to
+  change a weight the container holds or to add an expert, and keeps the old header and length in
+  `.pre-append`.
 
-**`--set K=V` is how a convert-time choice that must also hold at serve time is stated once.** The
-key is handed to declare *and* written into the container. What a weight is stored as is not such a
-choice: the encoding is in the container, and the plugin reads it from there. Which plugin serves
-the container is: a `quantization_config.*` key re-derives the descriptor the plugin is chosen by,
-so a bf16 checkpoint whose recipe writes Qwen's block fp8 is stated as that format and converted for
-the fp8 plugin (`data/recipes/q38-27b-fp8block-df2.recipe` has the keys).
+---
 
-**`--max-ctx`.** Some architectures' graphs depend on the context bound: Qwen4-Exp sizes its QSA
-buffers by it, and refuses a `--max-tok` and context pair whose score plane would pass 2 GiB.
-Default is the checkpoint's training context.
+## rad-export
 
-**`--max-spec`.** A *container* carries what the model can serve, so a draft head is written even
-when this run would not have drafted. `0` leaves it out.
+```
+rad-export SRC [-o OUT.rad] [--recipe NAME|FILE|auto] [--base DIR] [--draft DIR|ORG/NAME]
+           [--set K=V ...] [--image IMAGE | --rad-convert PATH] [--memory 24g] [--dry-run]
+           [-- rad-convert options]
+rad-export --list-recipes [--json]
 
-**`--draft-model` here is real** — unlike on the engine, where it is refused. This is where a
-drafter gets merged: its tensors go in under a `draft.` prefix and its config under `draft.` keys.
-It has no embedding and no `lm_head` of its own because it uses the target's.
+  SRC                a merged 16-bit checkpoint (config.json + *.safetensors) or a PEFT LoRA
+                     adapter (adapter_config.json + adapter_model.safetensors)
+  -o, --out FILE     the container (default: SRC's folder name + .rad, beside SRC or in out_dir)
+      --recipe R     a recipe name, a recipe file, or auto (default): the one recipe whose header
+                     names the base model, takes a bf16 checkpoint and needs no calibration data
+      --base DIR     the base checkpoint a LoRA adapter merges into. Default: the adapter's
+                     base_model_name_or_path, from disk or the Hugging Face cache, else downloaded
+      --draft D      the drafter, when the recipe merges one. Default: the config, else the Hub
+                     repository the recipe's usage line names (``); a usage line with
+                     a placeholder instead asks for --draft
+      --image IMAGE  run rad-convert in this Radiance image (docker, CPU only, no network, not
+                     pulled). Default $RADIANCE_IMAGE, then the config's image, then
+                     stilldeadcode/radiance
+      --rad-convert P  run this rad-convert instead of docker; recipes from its share/radiance
+      --memory M     docker memory limit for the convert
+      --dry-run      resolve recipe, drafter and paths, print the rad-convert line, write nothing
+      --keep-merged  keep the merged checkpoint of an adapter beside OUT
+```
 
-**`--imatrix`** supplies the expert-popularity profile, which the placement planner ranks units by,
-hands each quantiser its weight's column importances, and weights the error report.
+A trainer -- Unsloth, PEFT/TRL, Axolotl, a plain torch loop -- leaves a merged 16-bit checkpoint or
+a LoRA adapter. The container a finetune ships in should be encoded exactly like the stock model's,
+so rad-export converts it with the **stock model's recipe**, its `--set` keys and its drafter; the
+tuned `.rad` loads with the same serve line as the stock one.
 
-**`calib=DIR`** (`gptq`, `awq`, `autoround`, `paroquant`) is a directory an engine run wrote with
-`RADIANCE_CALIB_DIR` — each layer's Gram matrices, of the input in the domain the kernel multiplies
-it in: a container that stores a weight rotated records the rotated input, and a recipe that rotates
-the same weight reads it as it stands. A weight with nothing there is quantised the uncalibrated
-way and says so; `awq`, `autoround` and `paroquant` take the imatrix's diagonal instead when
-`--imatrix` gives one. The three-step calibrated recipe is in [MOE-W4.md](MOE-W4.md).
+1. **An adapter is merged first**, `W + scale · B·A` per weight as PEFT's `merge_and_unload`
+   computes it on the CPU (`scale` = alpha/r, alpha/√r with rsLoRA; `rank_pattern` and
+   `alpha_pattern` matched as PEFT matches them; the delta in fp32, rounded to the adapter's dtype
+   when that is bf16 or fp16), so the merged weights equal PEFT's bit for bit. It streams tensor by
+   tensor into 1 GiB shards beside OUT, so a 27B merge needs a few GiB of RAM, not the model twice,
+   and the bf16 model's size free on OUT's disk until the convert ends. Plain linear LoRA only:
+   embedding LoRA, trained biases, DoRA, saved modules, a convolution's LoRA, a rank other than the
+   adapter config's, and a target the base lacks are refused before anything is written -- merge
+   those with PEFT's `merge_and_unload` and pass the merged folder. The adapter's tokenizer and
+   chat template, where it ships them, replace the base's; one with more tokens than the base's
+   embedding has rows is refused.
+2. **The recipe** comes from the image (`/opt/radiance/share/radiance/recipes`, copied out once
+   per image) or from the installed `rad-convert`'s `share/radiance/recipes`. `auto` matches the
+   base model's name against each recipe's header; when several fit (a bf16 and an fp8 recipe of
+   the same model), it names them and asks. The recipe's own usage line supplies the `--set` keys
+   and says whether a drafter is merged.
+3. **rad-convert runs on the CPU.** It opens no GPU, so it is safe beside a running serve. Under
+   docker it runs as the caller, with no network, and sees only the checkpoint, the drafter, the
+   recipe and OUT's folder. Its output goes to `OUT.log`.
 
-**`autoround` and `paroquant` are slow by construction.** AutoRound's 200 default steps each cost
-N·K² multiply-adds — on a 16-core Zen 5 at ~2.5 TFLOP/s that is minutes for a 17408-wide down
-projection and most of a working day for a 27B dense model. `iters=50` is a quarter of it.
+```bash
+rad-export ~/outputs/my-run/checkpoint-400 --dry-run            # what it would run
+rad-export ~/outputs/my-run/checkpoint-400                      # adapter -> my-run-checkpoint-400.rad
+rad-export ~/exports/merged -o ~/models/mine.rad --recipe q38-27b-fp8block-df2 --draft ~/Qwen3.8-27B-DFlash2
+```
 
-**`--reuse` / `--in-place`** match a weight on its encoding, quantiser, options and shape. Whatever
-calibration made the old planes is carried with them: pass `--reuse` only when the source and the
-calibration are the same.
+`~/.config/rad-export/config.json` (or `--config`) pins what auto cannot know -- every key optional:
+
+```json
+{"image": "stilldeadcode/radiance", "out_dir": "~/models/rad",
+ "recipes": {"Qwen3.8-27B": "q38-27b-fp8block-df2"},
+ "drafts":  {"q38-27b-fp8block-df2": "~/models/Qwen3.8-27B-DFlash2"},
+ "bases":   {"Qwen/Qwen3.8-27B": "~/models/Qwen3.8-27B"}}
+```
+
+A recipe that needs calibration data (`calib=`, `--imatrix`) is listed but never picked by auto:
+a finetune's Hessians are not the stock model's, so those recipes need their calibration rerun on
+the tuned checkpoint first. rad-export itself is Python 3 with no dependencies; merging an adapter
+needs `torch` and `safetensors`, which every trainer's environment already has, and fetching a base
+or drafter that is not in the Hub cache needs `huggingface_hub` (only the files a conversion reads:
+`*.json`, `*.safetensors` and the tokenizer's). The image carries no Python; take the script out of
+it with
+`docker run --rm --entrypoint busybox stilldeadcode/radiance cat /opt/radiance/bin/rad-export > ~/.local/bin/rad-export`.
+
+When it runs as a post-export command (`UNSLOTH_POST_EXPORT` set in its environment), its last line
+is `UNSLOTH_HOOK_OUTPUT=`, which a trainer UI can list with the export.
 
 ---
 
 ## rad-kbench
 
-It checks every kernel every loaded library supplies against `libref`'s answers, benchmarks them,
-and writes a report. It is meant for out-of-tree authors as much as for this repo.
+Checks every kernel every loaded library supplies against the reference library's answers,
+benchmarks them, and writes a report. It is meant for out-of-tree library authors as well as this
+repository.
 
 ```
-rad-kbench [options]                     replay the recorded fixture (no model)
-rad-kbench -m  [options]      check against a real container
-rad-kbench -m  --record FILE  record a new fixture
+rad-kbench [options]                       replay the recorded fixture (no model)
+rad-kbench -m  [options]        check against a real container
+rad-kbench -m  --record FILE    record a new fixture
+rad-kbench -m  --skeleton FILE  write a metadata-only copy to record from
 ```
 
-### The three modes
+### Modes
 
-**Replay (no `-m`)** — seconds, on any machine, with no model and no weights present. The
-geometries, the seeds the inputs are drawn from, and `libref`'s answers reduced to a norm and a
-sample are checked in as `data/kernels.rkb`. This is what `ctest` runs.
+Replay (no `-m`) needs no model, no weights and no card. The geometries, the seeds the inputs are
+drawn from, and `libref`'s answers reduced to a norm, a sample and a projection sketch are checked
+in as `data/kernels.rkb` and `data/kernels_moe.rkb`. `ctest` runs three replays: the other
+libraries against each recording, and `libref` against both of its own at tolerance zero.
 
 ```sh
-rad-kbench --home $RADIANCE_HOME --max-cases 1
-rad-kbench --home $RADIANCE_HOME --max-cases 1 --fixture $RADIANCE_HOME/kernels_moe.rkb
+rad-kbench --home $RADIANCE_HOME --max-cases 1 --no-ref --strict           # kbench
+rad-kbench --home $RADIANCE_HOME --max-cases 1 --no-ref --strict \
+           --fixture $RADIANCE_HOME/kernels_moe.rkb                         # kbench_moe
+rad-kbench --home $RADIANCE_HOME --kernels libref --max-cases 1 --strict \
+           --fixture $RADIANCE_HOME/kernels.rkb \
+           --fixture $RADIANCE_HOME/kernels_moe.rkb                         # kbench_ref
 ```
 
-There are **two** fixtures because a recording is of *one* container and no container declares the
-whole op vocabulary: `kernels.rkb` is a dense model with a block drafter and gqa 6; `kernels_moe.rkb`
-is a routed MoE with an MTP head and gqa 8.
+(The ctests also pass `--coverage data/kbench_rows`, below.) There are two fixtures because a
+recording covers one container and no container declares the whole op vocabulary: `kernels.rkb`
+is a dense model with a block drafter and gqa 6; `kernels_moe.rkb` is a routed MoE with an MTP
+head and gqa 8. `--fixture` is repeatable, and the report then covers the union.
 
-Note that the replay also regression-tests `libref` itself — which a live oracle never can, since a
-live comparison moves both sides together and reports agreement.
+Each library is asked for its row as the engine would ask it with that library alone: the same
+constraints, derived parameters and weight-encoding filter, so a row the engine would pass over
+for a weight's encoding does not run here either (`--all-rows` runs every row whose constraints
+hold).
 
-**Against a container (`-m`)** — weight operands are read *from it*: each weight's canonical
-planes, which the kernel under test gets through its own `layout`/`relayout` hooks and the oracle
-gets decoded. That is a test of the artifact and of the layout hooks, and it is the only way to get
-one.
+The replay of `libref` is its regression test, which a live comparison cannot be: there both
+sides move together and agree. `libref` is deterministic and machine-independent by construction,
+so it is judged exactly. Its reduced answers are cached under `$RADIANCE_HOME/cache/kbench`, keyed
+by the build-ids of `libref` and every object it links, the CPU, a hash of every input byte and
+the case itself: an unchanged `libref` replays in seconds, a rebuilt one in full, and the
+comparison with the recording runs either way. `--no-cache` runs it regardless.
+
+Against a container (`-m`), weight operands are read from it: each weight's canonical planes,
+which the kernel under test gets through its own `layout`/`relayout` hooks and the oracle gets
+decoded, and every expert of a weight table. This is the only test of the artifact and of the
+layout hooks.
 
 ```sh
 rad-kbench -m flashnext-w4.rad --home $RADIANCE_HOME --bench --report kbench.md
 ```
 
-**Recording (`--record`)** — runs the oracle once and checks in what it produced. Weights are
-**drawn from a seed, not read from the container**, because a reference nothing can reproduce is
-not one. The recording carries each weight's encoding and the planes the operand takes, so a replay
-draws the same planes, every library lays them out its own way, and the reference reads what they
-decode to.
+Recording (`--record`) takes the reference's answer once at every point of every declared op the
+reference serves, whichever library resolved it. Weights are drawn from a seed, not read from the
+container, so any machine can reproduce the reference and no card is needed: a host with only
+`libref` records the same fixture. The recording carries each weight's encoding (a weight table's
+from its first expert) and the planes the operand takes, so a replay draws the same planes, each
+library lays them out its own way, and the reference reads what they decode to. Only the
+container's tables are read, so a skeleton of it (`--skeleton`: the tables, the data region a
+hole) records the same fixture in a few megabytes.
 
 ```sh
-rad-kbench -m model.rad --max-cases 1 --record data/kernels.rkb
-rad-kbench -m moe.rad   --max-cases 1 --record data/kernels_moe.rkb
+rad-kbench -m model.rad --skeleton model.skel.rad
+rad-kbench -m model.skel.rad --max-cases 1 --record data/kernels.rkb
+rad-kbench -m moe.rad        --max-cases 1 --record data/kernels_moe.rkb
 ```
 
+Inputs are drawn by the law the reference's description states for each operand (a sigmoid gate,
+a monotone log-decay, a routing histogram, a sampler's parameter rows as requests over a token
+history that repeats itself), and the recording keeps the law, so a replay draws what was
+recorded. The sampler's two laws need format version 6: a sampler case in an older recording
+draws its rows as numbers, on which the mask, DRY and XTC stages do nothing and the penalties act
+on an eighth of the rows.
+
+`--rerecord FILE` writes the replayed fixtures' cases again with the reference's current answers
+in the current format, each case keeping the laws it was recorded with. `--record-rows FILE`
+moves the fixtures' cases into the constraints of every row of the libraries under test (another
+band, tuned point or dtype) and records the reference there, described afresh: a fixture that
+reaches rows no container selects, to replay with `--all-rows`. A row whose geometry would change
+a weight's shape needs a container, and is listed.
+
+### Verdicts
+
+- An output is compared on its sampled positions, its full-tensor norm (a correct first tile
+  followed by zeros) and, from format version 5, 32 seeded random-sign projections whose
+  difference estimates the full rel_l2 to about 25% (a permuted or sign-flipped tile no sample
+  lands in). The largest of the three is the error.
+- Tolerances are per op and activation dtype (`dtype`, else `q_dtype`, else `kv_dtype`). Copies,
+  gathers, scatters and cache stores are exact. Every op in the fixtures has a row of its own
+  (`tests/kbench_test.cpp` checks).
+- Ids (token, expert and top-k indices) are compared exactly. Where an op's contract leaves a tie
+  open (`sample_argmax`, `router_topk`, `sample_topk`), an id that indexes a value equal to the
+  reference id's is accepted.
+- A case whose reference and output are both identically zero checked nothing: it is counted as
+  vacuous, not passed.
+- A failure, a red-zone overrun, a fusion that differs from its chain, and a host kernel that
+  wrote into an input it was handed all exit 1. Under `--strict` so does a stale fixture: an
+  operand count or schema that moved, or a case the reference no longer serves or now describes
+  differently. A case no library under test serves is named, never a failure.
+- `--coverage DIR` keeps one file per fixture and library of the rows a replay reaches
+  (`data/kbench_rows/`). A row listed and not reached fails the run, unless a memory skip kept
+  every case that would reach it from running. `--coverage-write` writes the files from a run.
+- Every pass ends with a line saying where its time went: draw, hashing, layout, upload, launch
+  per library, read-back, comparison, cache, timing.
+
+### Timing
+
+`--bench` times every case that passes, on the bytes it was checked on, and the report's speed
+section says how with the calibration it was checked against (`tools/kbench_timer.h`):
+
+- **Device cases are timed after the checks**, operands still on the device, back to back after
+  one sustained warm-up (`--bench-warm-ms`, again after correctness work long enough to drop the
+  clock). Cases are held until the `--max-bytes` budget fills, then timed.
+- **A time is device timestamps around a batch** of back-to-back launches, divided by the launch
+  count. The batch is queued behind a gate (`rad_stream_gate`, `core/device/device.h`) the host
+  opens once the whole batch is queued, so neither the host's submission rate nor a host sync is
+  in the interval; a keep-alive copy runs ahead of the gate so the card does not idle and drop its
+  clock while the host submits. Two untimed launches precede every batch. A batch lasts a
+  millisecond and fifty launch floors; a case takes batches until its median's 95% interval is
+  within 1% or `--bench-reps` is reached. The report gives median, minimum, p90, batch count and
+  the interval. A launch that waits on its own stream cannot run behind a gate; it is timed
+  without one and marked `ungated`.
+- **Cold by rotation.** Weights, weight tables and inputs of 1/32 of the footprint or more are
+  read from one of a set of copies spanning the footprint (`--bench-flush`, default 256 MiB, at
+  least twice an R9700's 8 MiB L2 plus 64 MiB last-level cache), so every launch reads them from
+  memory as the engine's streamed weights are; smaller inputs stay warm, as the previous op
+  leaves them. A weight table is read through pointer tables that send each launch's routed
+  experts to different slots, so the experts a launch reads are cold although it reads only a
+  few. Nothing is flushed, so no dirty lines are left for the timed kernel to write back.
+- **In-place operands are restored** from a pristine copy before every launch. The restores are
+  timed alone in the same window and subtracted; their share is in the notes.
+- **Realistic inputs where the time depends on them**: the timing pass draws expert offsets and
+  routing ids skewed (Zipf, exponent 0.5) and block tables as permutations. The checked launch
+  keeps the recorded draw, so fixtures replay byte for byte.
+- **Calibration**, printed above the table: the launch floor (the backend's own 4-byte fill, back
+  to back and between two events), and streaming-read bandwidth (ranged copies whose writes all
+  land in one cache-resident ring) warm and rotated-cold at four sizes up to
+  the footprint. If a smaller cold probe runs more than 1.5x the largest's rate the rotation was
+  served from a cache, and device times are withheld. The clock is read from the card's
+  `gpu_metrics` after every batch (v1.3 tables: RDNA3 and RDNA4 discrete cards); a batch during
+  which a throttler came on that was off at idle and after the warm-up is repeated, up to three
+  times. A throttler on under the warm-up's load binds throughout and is named in the header
+  instead.
+- **Host cases are timed where they are checked**, in their own column: steady_clock on the
+  calling thread after an untimed launch, in-place operands restored outside the timed region,
+  weights rotated over twice the CPU's last-level cache (at least 256 MiB, or `--bench-flush`),
+  on the OpenMP threads the notes name, for at most two seconds a case. A reference answer the
+  cache served launched nothing to time; `--no-cache` times it too.
+
 ### Flags
 
 | | |
 |---|---|
-| `--fixture FILE` | the recording to replay (default `$RADIANCE_HOME/kernels.rkb`) |
+| `--fixture FILE` | the recording to replay (default `$RADIANCE_HOME/kernels.rkb`); repeatable |
 | `--record FILE` | with `-m`: write a fixture |
+| `--skeleton FILE` | with `-m`: write a sparse copy of the container, its tables intact and its data a hole |
+| `--rerecord FILE` | replay: write the fixtures' cases again with the reference's answers |
+| `--record-rows FILE` | replay: record a row-driven fixture from the fixtures' cases |
 | `-m, --model FILE` | the `.rad` to read weight operands from |
 | `--home DIR`, `--kernels A:B` | plugin home, and the kernel libraries to load (default every one found) |
 | `--op NAME` | check only this op (repeatable prefix match) |
-| `--ref NAME` | the oracle plugin's name (default `libref`) |
+| `--ref NAME` | the oracle plugin's name (default: the loaded library that declares itself a reference implementation, `libref` in this tree) |
+| `--no-ref` | replay: leave the reference out of the libraries under test |
+| `--strict` | replay: a stale fixture fails the run |
+| `--all-rows` | replay: run every row whose constraints hold, not only the selected one |
+| `--coverage DIR`, `--coverage-write` | replay: the row coverage ratchet, and writing its files |
+| `--no-cache`, `--cache-dir DIR` | replay: run the reference instead of reusing its cached answers; where the cache lives |
 | `--seed N` | base seed; every case derives its own, so changing a filter does not change any other case's inputs |
-| `--tol X` | override every tolerance (for bisecting, **not** for passing) |
+| `--tol X` | override every tolerance (for bisecting, not for passing) |
 | `--max-ctx N` | the deepest context considered: declare runs at it and the attention sweep builds to it (default: the checkpoint's training context for declare, 16384 for the sweep). Attention is swept over depth as well as query length |
 | `--max-tok N` | the `max_tok` declare runs at (default 512, small on purpose) |
+| `--mm-max-patches N` | the encoder pass declare runs at, so a media tower's kernels are in the graph (default 2048, rounded to whole output rows, when the container carries an encoder; 0 leaves it out) |
 | `--kv-cache-dtype T` | `bf16` or `fp8`, the cache width declare runs at, as on the engine (default bf16) |
-| `--max-cases N` | runs per distinct (op, kernel, geometry, tuned point); 0 means every one (default 4) |
-| `--max-bytes MIB` | **skip a case whose operands would need more than this**, by name (default: half the memory free at start, at most 8192 and at least 512) |
+| `--num-speculative-tokens N` | draft depth to declare at (default: the container's own); puts the drafter's kernels in the checked graph |
+| `--max-cases N` | runs per distinct (op, kernel, library, domain, geometry, operand shapes); 0 means every one (default 4) |
+| `--max-bytes MIB` | skip a case whose operands would need more than this, by name (default: half the memory available at start, at most 8192 and at least 512) |
 | `--no-fusion` | skip the fusion oracle |
-| `--bench` | time each case that passes, on the same bytes |
-| `--bench-iters N`, `--bench-reps N` | launches per rep (20), timed reps (3) |
-| `--bench-warm-ms N` | untimed launches before each timed window (default 500) |
-| `--bench-flush MIB` | time cold: read MIB through the caches before every timed launch (256 empties an R9700's 8 MiB L2 and 64 MiB last level) and time each launch alone between two device events. Implies `--bench` |
+| `--bench` | time each case that passes, on the same bytes (Timing, above) |
+| `--bench-iters N` | launches in every timed batch; 0 (default) sizes each batch to a millisecond and fifty launch floors |
+| `--bench-reps N` | the most batches a case takes (default 20); fewer once the median's 95% interval is within 1% after six |
+| `--bench-warm-ms N` | sustained load before each timing pass, in ms (default 2000; 0 for none) |
+| `--bench-flush MIB` | the rotation footprint: weights and inputs of MIB/32 or more are read from copies spanning MIB, so from memory (default 256 on a card; twice the last-level cache and at least 256 for host rows); 0 times warm, every launch rereading one set of operands. Implies `--bench` |
 | `--timing-only` | time every device kernel and check nothing: no reference run, read-back, margins or fusion chain, host rows skipped. For comparing builds a checked run has already passed; refuses `--record`. Implies `--bench` |
 | `--report FILE` | write the markdown report |
 | `--analysis FILE` | splice in a fragment from `tools/kbench-analysis.sh` |
-| `--num-speculative-tokens N` | draft depth to declare at |
 | `-v` | print every case, not only failures |
 
-### Things that will bite you
+### Notes
 
-**`--max-bytes` matters on a loaded machine.** One case holds every operand as host floats, again
-as the kernel's dtype, and again per library on the device. Without the cap a small machine is
-killed by the OOM killer with no indication which op it died on. The default is taken from the
-memory free when the run starts, which a server started later does not respect; if a server is
-running on the same box, pass something small explicitly:
+- A replay costs the input draw (threaded, and nothing for a case every library caps or skips)
+  plus the libraries under test. Without `libref` a host replay takes seconds to a minute;
+  `kbench_ref` takes minutes after a `libref` rebuild and seconds otherwise.
+- `--max-bytes` matters on a loaded machine. One case holds every operand as drawn, again as a
+  kernel's copy of what it writes, and again on the device. Without the cap a small machine is
+  killed by the OOM killer with no indication of the op. The default is taken from the memory
+  available when the run starts, which a server started later does not respect; with a server on
+  the same machine, pass a small value:
 
-```sh
-rad-kbench --home $RADIANCE_HOME --max-cases 1 --max-bytes 1024
-```
+  ```sh
+  rad-kbench --home $RADIANCE_HOME --max-cases 1 --max-bytes 1024
+  ```
 
-**`--bench` is cache-warm.** Every launch of a timed window reuses one set of operands, so a weight
-that fits in the last-level cache is read from it after the first launch: a 52 MB bf16 decode weight
-times at 1.45 TB/s warm and at 565 GB/s, the card's DRAM rate, cold. The engine streams its weights
-cold every step. `--bench-flush 256` measures that; use it whenever the comparison is about how a
-kernel waits on memory. Its numbers are device time per launch and are not comparable with a warm
-run's, which divide a window's wall time by its launches.
-
-**`--timing-only` runs the card hotter.** With no host-side check between cases the card is busy
-almost all of the run, and on the same binary its times come out 0.3-0.8% above a checked run's in
-total, compute-bound kernels 1-2%. Compare builds within one mode, interleaved; the ratio between
-two builds matched the checked mode's to within half a percent.
-
-**`--max-cases`.** A 62-layer model presents the same kernel at the same shape sixty times and only
-the weights differ. The default of 4 is not a sample of anything interesting; `--max-cases 1` is
-what the fixtures are recorded at.
-
-**Fusion claims are checked byte for byte.** A kernel that declares the chain it replaces is run
-against that chain, out of its own plugin, and the outputs compared with `memcmp`. That claim is
-what makes a fused kernel *substitutable* rather than a second numerical path.
-
-**A kernel that does not read a weight's encoding is a skip, not a failure.** Its layout hook
-answers `RAD_E_DTYPE` for an encoding it does not take, and the report names the kernel, the
-operand and the encoding. A fixture in another format version does not load at all — record it
-again.
+- `--bench` times cold, the way the engine reads its weights. On an R9700 a 52 MB bf16 decode
+  weight read warm (`--bench-flush 0`) comes from the last-level cache at 1.45 TB/s against the
+  card's 565 GB/s from memory, so warm times rank kernels at a shape but do not size a roofline.
+  Warm and cold are both device time per launch, so the two are comparable.
+- A time includes the launch floor the header prints, the gap between two dependent dispatches,
+  which the engine pays too; a kernel close to the floor is launch-bound.
+- `--timing-only` times the same way a checked run does, after the same warm-up, without the
+  checks in between. Compare builds within one mode, interleaved.
+- `--max-cases`: a 62-layer model presents the same kernel at the same shape sixty times with only
+  the weights differing. The fixtures are recorded at `--max-cases 1`.
+- Fusion claims are checked byte for byte. A kernel that declares the chain it replaces is run
+  against that chain, out of its own plugin, and the outputs compared with `memcmp`. That is what
+  makes a fused kernel substitutable instead of a second numerical path.
+- A kernel that cannot lay out a weight's encoding is a skip, not a failure: its layout hook
+  answers `RAD_E_DTYPE`, and the report names the kernel, the operand and the encoding. A fixture
+  in a format version this tree cannot read does not load; record it again. Version 4 still loads:
+  it has no sketch, and its weight tables were recorded undrawn, so its grouped-GEMM cases are
+  vacuous until it is recorded again.
 
 ---
 
@@ -403,19 +606,20 @@ rad-tune -m  [options]
       --home DIR     $RADIANCE_HOME; the cache is written to /tune/.tune
       --kernels A:B  the kernel libraries to load, first wins; default every library found
       --op NAME      tune only ops whose name starts with NAME
-      --machine KEY  override the machine key (for writing a cache for another box)
+      --machine KEY  override the machine key (for writing a cache for another machine)
       --reps N       timing reps, median reported (default 5)
       --iters N      launches per rep (default 32)
       --max-tok N    the max_tok declare is run at (default 8192)
       --tp N         tensor-parallel width to declare at (default 1)
-      --num-speculative-tokens N
+      --num-speculative-tokens N|auto
+                     draft depth to declare at (default auto: the container's own)
       --dry-run      list what would be measured and stop
   -v, --verbose      print every candidate, not just the winner
 ```
 
-Kernels declare **tunable axes** rather than named variants. `rad-tune` walks that space at this
-model's actual shapes on this actual machine, and writes the winner per (op, geometry) to
-`$RADIANCE_HOME/tune/.tune`. The engine's selector reads that cache at startup.
+Kernels declare tunable axes, not named variants. `rad-tune` walks that space at this model's
+shapes on this machine and writes the winner per (op, geometry) to
+`$RADIANCE_HOME/tune/.tune`, which the engine's selector reads at startup.
 
 ```sh
 rad-tune -m model.rad --home $RADIANCE_HOME --tp 2
@@ -423,20 +627,18 @@ rad-tune -m model.rad --op gemm --dry-run        # what would be measured
 rad-tune -m model.rad --op attn_paged -v         # every candidate
 ```
 
-**Declare at the shapes you serve.** Two things decide that and both are flags here:
+Declare at the shapes you serve:
 
-- **`--tp N`** — a sharded deployment halves every sharded N. A declare at world size 1 measures a
-  program no `--tp 2` serve ever runs.
-- **`--num-speculative-tokens N`** — this is what puts the *drafter's* kernels in the measured graph
-  at all. The default is the container's own depth. The drafter's shapes appear in no other model's
-  tuning table, so nothing else covers them.
+- `--tp N`: a sharded deployment divides every sharded N by the world size. A declare at world size
+  1 measures a program no `--tp 2` serve runs.
+- `--num-speculative-tokens N` puts the drafter's kernels in the measured graph. The drafter's
+  shapes appear in no other model's tuning table.
 
-At `--tp > 1` every rank declares at once, on its own thread and its own device, exactly as the
-engine does: a collective's `init` is a rendezvous, so declaring rank 0 alone at world size 2 does
-not fail — it *hangs*.
+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.
 
-**Prove the variants beat the default before trusting a cache.** `RADIANCE_TUNE` pins a kernel's
-axes for a comparison; it is an instrument, not a deployment setting.
+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.
 
 ---
 
@@ -447,18 +649,17 @@ rad-schemas libref.so                 print one plugin's vocabulary
 rad-schemas libr4d.so libref.so       diff them, in hierarchy order
 ```
 
-The first plugin in hierarchy order to declare an op **fixes its schema**, and a later plugin
-declaring the same op differently is refused at load with both plugins named. That rule is right:
-arguments are positional, so two disagreeing schemas make the same call mean different things
-depending on which plugin won selection — silent numerical garbage rather than a diagnosable
-failure.
+The first plugin in hierarchy order to declare an op fixes its schema, and a later plugin that
+declares the same op differently is refused at load, with both plugins named. Arguments are
+positional, so two disagreeing schemas would make the same call mean different things depending on
+which plugin won selection.
 
-But "refused at load" is a poor place to find out, because the message names one op and you have to
-guess the rest. This prints all of them at once, so a new plugin can be conformed to the vocabulary
-before it is ever loaded beside another.
+The loader names one op at a time. `rad-schemas` prints every disagreement at once, so a new
+plugin can be conformed to the vocabulary before it is loaded beside another. It exits 1 when any
+schema disagrees.
 
-**It links no core at all**, deliberately: it `dlopen`s plugins and reads their static schema
-tables, so it works on a plugin the engine cannot even load — which is exactly when you need it.
+It links no core: it `dlopen`s plugins and reads their static schema tables, so it works on a
+plugin the engine cannot load. It takes no options; run it with no arguments for its usage.
 
 ```sh
 rad-schemas $RADIANCE_HOME/kernels/libr4d.so $RADIANCE_HOME/kernels/libref.so
@@ -466,6 +667,49 @@ rad-schemas $RADIANCE_HOME/kernels/libr4d.so $RADIANCE_HOME/kernels/libref.so
 
 ---
 
+## rad-avx-check
+
+```
+rad-avx-check --ref libref.so --avx LIB.so [options]
+
+  --ref PATH     the oracle plugin      (default libref.so)
+  --avx PATH     the plugin under test  (default libavx.so); any host library
+  --op NAME      only this op
+  --level N      only this ISA level (0 scalar 1 avx 2 avx2 3 avx512)
+  --threads N    rerun every case with each parallel region on N threads and
+                 require the same bytes (default 4, 0 to skip; libavx only)
+  --tol X        override every tolerance (for bisecting, not for passing)
+  -v             print every case, not only the failures
+```
+
+Checks a host kernel library op by op against libref, on the CPU, with neither the engine nor a
+card: two `dlopen` calls, a geometry table (`libavx/avx_cases.cpp`), libref's operand descriptions
+and hand-built cases for the operand shapes and formats a description cannot draw. It is built
+into the build's `radiance_home/kernels/` with libavx (and by a standalone libavx build against an
+installed radiance), and ctest runs it as `avx_check`.
+
+For every case: schemas as the loader compares them, the outputs within rad-kbench's tolerances
+(ids exactly), guard bytes around every buffer, inputs unchanged, and an oracle output that is not
+just the draw. libavx is also checked at every ISA level the CPU executes and with every parallel
+region forced onto several threads, and must cover every libref op but those `avx_check.cpp` lists
+as not implemented yet.
+
+A new host library is checked with the same command, pointing `--avx` at it:
+
+```sh
+K=/radiance_home/kernels
+$K/rad-avx-check --ref $K/libref.so --avx ./build/mylib.so -v
+```
+
+A library not named `libavx` is checked as a host library: the libref ops it has no host row for
+are listed rather than failed, each case runs on the row the selector would choose for its
+geometry (constraints, then priority), and the ISA sweep and threaded rerun run only if it exports
+`avx_isa_force` and `avx_par_force`. A row that returns `RAD_E_UNSUPPORTED` for a geometry libref
+serves fails in either case: the selector would resolve to it and the step would fail at issue.
+`libavx/README.md` has the details. Device libraries are checked by `rad-kbench`.
+
+---
+
 ## rad-tokcheck
 
 ```
@@ -480,50 +724,60 @@ rad-tokcheck [options]  ...
   --context N     ids shown either side of a difference (default 6)
 ```
 
-Three questions, per corpus file: does the encoder produce the ids the reference encoder in
-`tools/tokref` produces (llama.cpp's splitters and `std::regex`, a string-keyed merge); does it
-produce the ids HuggingFace `tokenizers` produces, read from files made elsewhere so that nothing
-here needs Python; and how fast is it -- MB/s for both encoders, and what re-tokenising a growing
-conversation costs with the segment cache and without it. Any difference is printed with the ids
-and the text around it, and makes the exit status non-zero, so it can gate a change.
+Per corpus file it checks three things:
+
+1. The ids match those of the reference encoder in `tools/tokref` (llama.cpp's splitters and
+   `std::regex`, a string-keyed merge).
+2. The ids match HuggingFace `tokenizers`, read from files made elsewhere so that no Python is
+   needed here.
+3. Speed: MB/s for both encoders, and the cost of re-tokenising a growing conversation with and
+   without the segment cache.
+
+Any difference is printed with the ids and the text around it and makes the exit status non-zero,
+so the tool can gate a change.
 
 ---
 
 ## The KL mode
 
 ```
-radiance --model BF16.rad ... --kld-record DIR --kld-corpus CORPUS.jsonl    the yardstick, once
+radiance --model BF16.rad ... --kld-record DIR --kld-corpus CORPUS.jsonl    the reference, once
 radiance --model QUANT.rad ... --kld-ref DIR [--kld-out REPORT.json]        each candidate
 ```
 
-How far a quantised model is from the one it was quantised from, as the distribution of the
-per-position **KL(P_bf16 || Q_quant)** over the whole vocabulary: mean, median, 99th, 99.9th and
-99.99th percentiles and maximum, the top-1 agreement (the candidate's argmax is the reference's),
-and both models' perplexity on the corpus's own next tokens -- overall and per source. A mode of
-the engine rather than a tool, like `--debug-graph`: it starts exactly as a serve would, with the
-same placement and kernels, then runs the corpus through prefill instead of listening, and exits.
+Measures how far a quantised model is from the one it was quantised from, as the distribution of
+the per-position KL(P_bf16 || Q_quant) over the whole vocabulary: mean, median, 99th, 99.9th and
+99.99th percentiles and maximum, top-1 agreement (the candidate's argmax is the reference's), and
+both models' perplexity on the corpus's own next tokens, overall and per source. It is a mode of
+the engine, like `--debug-graph`: it starts as a serve would, with the same placement and kernels,
+runs the corpus through prefill instead of listening, and exits.
 
-**The reference is computed once.** `--kld-record` writes the bf16 model's log-probabilities at
-every scored position to DIR -- f16 over the whole vocabulary, the 16 most likely tokens exactly,
-and the tokens themselves -- and `--kld-ref` runs a candidate over those stored tokens, scoring its
-own f32 logits against the stored row. A candidate costs one prefill of the corpus. DIR is never
-written over, and is read only once its `kld.json` exists, which the recording writes last.
+The reference is computed once. `--kld-record` writes the bf16 model's log-probabilities at every
+scored position to DIR (f16 over the whole vocabulary, the 16 most likely tokens exactly, and the
+tokens themselves). `--kld-ref` runs a candidate over those stored tokens and scores its own f32
+logits against the stored rows, so a candidate costs one prefill of the corpus. DIR is never
+overwritten, and is read only once its `kld.json` exists, which the recording writes last.
 
-**The corpus** is JSONL, one `{"prompt", "score_from", "source"}` a line: `prompt` is tokenised
-with control tokens recognised, as a rendered chat template is; positions `[score_from, n - 1)`
-are scored; `source` is the report's grouping. The corpus the Flash-Next numbers in
-[MOE-W4.md](MOE-W4.md) were measured on is disjoint from the calibration corpus, so a calibrated
-quantiser is not scored on the text it was fitted to. Positions are what the tail needs: the
-99.99th percentile of 83K positions rests on eight of them.
+The corpus is JSONL, one `{"prompt", "score_from", "source"}` object a line; only `prompt` is
+required. `prompt` is tokenised with control tokens recognised, as a rendered chat template is.
+Positions `[score_from, n - 1)` are scored (`score_from` defaults to 0), and `source` groups the
+report. The corpus behind the Flash-Next numbers in [MOE-W4.md](MOE-W4.md) is disjoint from the
+calibration corpus, so a calibrated quantiser is not scored on the text it was fitted to. The tail
+needs many positions: the 99.99th percentile of 83K positions rests on eight of them.
 
-**What the mode changes for itself.** Speculation and the prefix cache are off (a drafter writes
-no scored row; a prefix hit would skip positions the reference holds), the step pipeline is off
-(the scored rows are copied off the cards after the step), and the logits buffer holds a row for
-every token of a step (`RadBuildCtx::max_out_rows`) -- `--max-num-batched-tokens 4096` is 2 GiB
-of it a rank, plus the same in pinned host memory. Everything else is the command line's: run
-every candidate with the same flags, and the reference with an exact wire and a bf16 KV cache.
+The mode changes these settings itself:
 
-`--kld-out FILE` writes the report as JSON and every position's KL, both NLLs and the argmax
+- Speculation and the prefix cache are off: a drafter writes no scored row, and a prefix hit would
+  skip positions the reference holds. An explicit `--num-speculative-tokens` above 0 is refused.
+- The step pipeline is off, since the scored rows are copied off the cards after the step.
+- The logits buffer holds a row for every token of a step (`RadBuildCtx::max_out_rows`). At
+  `--max-num-batched-tokens 4096` with a 248320-token vocabulary over two ranks that is about
+  2 GiB per rank, plus the same in pinned host memory.
+
+Everything else comes from the command line: run every candidate with the same flags, and the
+reference with the exact wire and a bf16 KV cache.
+
+`--kld-out FILE` writes the report as JSON, and every position's KL, both NLLs and the argmax
 agreement to `FILE.rows` (`[positions, 4]` f32, reference row order), so two candidates can be
 compared position by position.
 
@@ -531,34 +785,35 @@ compared position by position.
 
 ## The shell harnesses
 
-`scripts/` drives a **running** engine: bring a model up, measure it, and assert on what comes back
-over the wire. They are versioned with the engine because a measurement is only reproducible if the
-thing that took it is — and because what each one encodes is an argument (why a window is sampled
-the way it is, which counter is the honest one) that is expensive to reconstruct from the number.
-[scripts/README.md](../scripts/README.md) has a line on each.
+`scripts/` drives a running engine: bring a model up, measure it, and assert on what comes back
+over the wire. The scripts are versioned with the engine so that a measurement can be reproduced,
+and each one's header records why it measures the way it does (how a window is sampled, which
+counter to trust). [scripts/README.md](../scripts/README.md) has a line on each.
 
-The scripts that start a server or a conversion expect the build at
-`$HOME/workspace/radiance/build` and the containers under `$HOME/models/rad/`; every default is an
-environment override, listed in each script's header. The ones that only attach to a live server
-need nothing but `curl` and `jq`. Scripts resolve each other by `$(dirname "$0")`.
+The scripts that start a server or a conversion expect the source tree and its `build/` directory
+at a fixed path under `$HOME`, set at the top of each script, and the containers under
+`$HOME/models/rad/`. Most other defaults (port, container, sizes) take an environment override,
+listed in each script's header. The scripts that only attach to a live server need nothing but
+`curl` and `jq`. Scripts find each other through `$(dirname "$0")`.
 
-**Which ones restart the server.** `fnserve.sh`, `mcserve.sh`, `fnstop.sh`, `fntrace.sh`,
-`dprofd.sh`, `mctrace.sh`, `mcagent.sh` and `mcdecl.sh` all `pkill` a running engine, whatever port
-it is on. `oracle.sh` starts its own server and stops whatever listens on its port (`P`, default
-8302). Everything else — `cstep2.sh`, `ident.sh`, `tierident.sh`, `tiercross.sh`, `mctools.sh`,
-`mcstream.sh`, `hfget.sh`, `convfn.sh`, `convdspark.sh`, `fnpf.sh`, `fnconc.sh`, `fndrop.sh`,
-`apikeys.sh`, `cardclock.py` — leaves a live serve alone.
-`fndrop.sh` is the one to read the description of first: it leaves the PROCESS alone and
-deliberately disconnects clients from it, which is not the same promise.
+Which ones stop a running server:
+
+- `fnserve.sh`, `mcserve.sh`, `fnstop.sh`, `fntrace.sh`, `dprofd.sh`, `mctrace.sh`, `mcagent.sh`
+  and `mcdecl.sh` `pkill` any running engine, whatever port it is on.
+- `oracle.sh` starts its own server and stops whatever listens on its port (`P`, default 8302).
+- `cstep2.sh`, `ident.sh`, `tierident.sh`, `tiercross.sh`, `mctools.sh`, `mcstream.sh`, `hfget.sh`,
+  `convfn.sh`, `convdspark.sh`, `fnpf.sh`, `fnconc.sh`, `fndrop.sh` and `cardclock.py` leave a
+  running server alone. `fndrop.sh` leaves the process alone but disconnects clients from it on
+  purpose.
 
 ### Bringing a model up
 
 | | knobs |
 |---|---|
 | `mcserve.sh` | MiniCPM5-2B + DSpark drafter (`minicpm5-2b-dspark.v2.rad`), left running. `P` `TP` `MLEN` `SEQS` `M` `KVD` `HR` `MNBT` `EXTRA` `EXTRA_ENV` |
-| `fnserve.sh` | Qwen3.8-Flash-Next, the production container `w4nl64-i8lm.rad`, same contract. `P` `TP` `MLEN` `SEQS` `M` `NS` `HOSTPOOL` `KVD` `HR` `MNBT` `WIRE` `KVHOST` `KVDIR` `KVDISK` `EXTRA` `EXTRA_ENV` |
-| `fnstop.sh` | stops whichever is running and **waits for the process to go** |
-| `convdspark.sh`, `convfn.sh` | rebuild the containers those two serve. The conversions of record. `convfn.sh` needs `CALIB=`: the production recipe's expert rule runs GPTQ against the calibration Grams there |
+| `fnserve.sh` | Qwen3.8-Flash-Next, the production container `w4nl64-i8lm.rad`, left running. `P` `TP` `MLEN` `SEQS` `M` `NS` `HOSTPOOL` `KVD` `HR` `MNBT` `WIRE` `KVHOST` `EXTRA` `EXTRA_ENV` |
+| `fnstop.sh` | stops whichever is running and waits for the process to exit |
+| `convdspark.sh`, `convfn.sh` | rebuild the containers those two serve; the reference conversions. `convfn.sh` needs `CALIB=`: the production recipe's expert rule runs GPTQ against the calibration Grams there |
 | `hfget.sh` | fetch a checkpoint from Hugging Face with `curl` and `jq`. Resumable; a file changed at the same size is fetched again (`.hfget-manifest`). `radiance --model ` runs it too |
 
 ```sh
@@ -567,32 +822,31 @@ P=8100 MLEN=131072 SEQS=4 scripts/fnserve.sh   # override
 scripts/fnstop.sh
 ```
 
-Both print the endpoints and exit with the server still up. Read their headers — `fnserve.sh` in
-particular records why each production flag is what it is.
+Both serve scripts print the endpoints and exit with the server still up. `fnserve.sh`'s header
+gives the reason for each production flag.
 
 ### Measuring a server that is already up
 
-These attach to a running server and never restart one, so they can be pointed at a live
+These attach to a running server and never restart it, so they can be pointed at a live
 deployment. `P` selects the port.
 
-| | what it answers | knobs |
+| | what it measures | knobs |
 |---|---|---|
-| `fnpf.sh` | prefill throughput, with a fresh nonce per rep so the prefix cache cannot answer for work that was never done | `P` `N` `REPS` `BPT` |
-| `fnconc.sh` | what a long prefill costs the requests already running beside it — both halves on one clock, alone then contended, with the warm pass discarded | `P` `C` `DEC` `PROMPT` |
-| `fndrop.sh` | whether a client going away mid-request takes anything with it. Drop points are derived from one timed request, and every answer is checked against a reference | `P` `LONG` `GEN` |
-| `apikeys.sh` | whether the server does what oai.cpp says about request keys: every rejected one refused by name, every inert one accepted, every accepted one honoured | `P` |
-| `cstep2.sh` | steady-state decode ms/step at concurrency | `P` `LEVELS` `MT` `WIN` |
+| `fnpf.sh` | prefill throughput, with a fresh nonce per rep so the prefix cache cannot serve it | `P` `N` `REPS` `BPT` |
+| `fnconc.sh` | what a long prefill costs the requests running beside it: both on one clock, alone and then contended, with the warm-up pass discarded | `P` `C` `DEC` `PROMPT` |
+| `fndrop.sh` | whether a client disconnecting mid-request breaks anything. Drop points are derived from one timed request, and every answer is checked against a reference | `P` `LONG` `GEN` |
+| `cstep2.sh` | steady-state decode ms/step at each concurrency | `P` `LEVELS` `MT` `WIN` |
 | `ident.sh` | run-to-run reproducibility at a fixed configuration: one hash per (temperature, question) | `P` |
-| `cardclock.py` | what holds each card's clock under a sustained load (power limit, temperature or current limit, or the top of the voltage/frequency curve) and which card the tensor-parallel step waits for, with the engine's step counters per window beside it. Drives its own greedy load; `--watch` only samples while real traffic drives the server. Never writes to a card | `--port` `--conc` `--gen` `--seconds` `--window` `--seed` `--watch` `--json` `--compare` |
+| `cardclock.py` | what holds each card's clock under sustained load (power limit, temperature or current limit, or the top of the voltage/frequency curve) and which card the tensor-parallel step waits for, with the engine's step counters per window. Drives its own greedy load; `--watch` only samples while other traffic drives the server. Never writes to a card | `--port` `--conc` `--gen` `--seconds` `--window` `--seed` `--watch` `--json` `--compare` |
 
-`fndrop.sh` exists because a disconnect reaps a request at an arbitrary point in the step loop, and
-every other harness here waits for its requests, so none of them can see what holds a reference
-across that point. Surviving is not the whole test: a server that stays up and then answers
-differently has a freed slot feeding a live sequence. Note its own caveat — one diverged hash is not
-a finding, it is an instruction to run it again.
+`fndrop.sh`: a disconnect reaps a request at an arbitrary point in the step loop, and every other
+harness waits for its requests, so none of them sees what holds a reference across that point.
+Staying up is not enough; a server that stays up but answers differently has a freed slot feeding
+a live sequence. One diverged hash can be a tie flipped by a different batch; rerun before
+treating it as a defect.
 
 `ident.sh` does not expect a speculative run to match a non-speculative one byte for byte: the
-split-K count is chosen from M, so the two take different reduction orders and a long answer can
+split-K count is chosen from M, so the two use different reduction orders and a long answer can
 flip a near-tie. A divergence within the first sentence or two is a defect.
 
 ```sh
@@ -601,21 +855,20 @@ P=8100 LEVELS="1 2 4 8" scripts/cstep2.sh
 
 ```
 C        steps       tok   tok/step    ms/step   accept%
-1          812       900      1.108     29.820      74.2
-2         ...
+1          ...
 ```
 
-`cstep2.sh` waits until exactly C sequences are running before sampling and re-checks at the end: a
-window whose edges carry fewer than C describes no concurrency at all.
+`cstep2.sh` waits until exactly C sequences are running before sampling and re-checks the count at
+the end: a window with fewer than C at either edge measures no single concurrency.
 
-`cardclock.py` exists because the same image reads several percent apart from one boot to the next
-on workstation cards. A tensor-parallel step runs at its slowest card's clock, and under a sustained
-load the firmware picks each card's clock. A throttler bit counts only when the card's clock is
-lower while it is set: some firmware keeps a bit on at idle (on Radeon AI PRO R9700,
-`TEMP_HOTSPOT`), so a bit the idle baseline also shows is listed and ignored. When it names a
-setting (power cap, fan target, voltage offset) it prints the command and changes nothing. That
-write is for a moment when no process holds `/dev/kfd`. Under load, an SMU write on gfx1201 has
-reset the machine.
+`cardclock.py`: on workstation cards the same image can measure several percent apart from one
+boot to the next. A tensor-parallel step runs at its slowest card's clock, and under sustained load
+the firmware picks each card's clock. A throttler bit counts only when the card's clock is lower
+while it is set. Some firmware keeps a bit on at idle (`TEMP_HOTSPOT` on the Radeon AI PRO R9700),
+so a bit the idle baseline also shows is listed and ignored. When the script names a setting
+(power cap, fan target, voltage offset) it prints the command and changes nothing. Apply such a
+setting only while no process holds `/dev/kfd`: on gfx1201 an SMU write under load can reset the
+machine.
 
 ```sh
 scripts/cardclock.py --port 8100 --conc 8 --seconds 180 --seed 7 --json before.json
@@ -626,37 +879,37 @@ scripts/cardclock.py --compare before.json after.json
 
 | | |
 |---|---|
-| `dprofd.sh` | per-op device timing at depth and concurrency, on the 27B dense model with its DFlash2 drafter. **Difference two dumps**, both taken after prefill ended |
+| `dprofd.sh` | per-op device timing at depth and concurrency, on the 27B dense model with its DFlash2 drafter. Take the difference of two dumps, both after prefill ended |
 | `fntrace.sh` | a Flash-Next prefill under `rocprofv3`, with the link counters from `/stats` across the same request |
 | `mctrace.sh` | a MiniCPM5-2B decode trace under `rocprofv3`, formatted for `libr4d/isa/tsum.sh` |
-| `oracle.sh` | every op compared against libref on the operands the model actually issued; reads for a MISMATCH and for the NOT CHECKED lines that name what cannot be compared. `OPS` `MAXN` `FROM`/`TO` `TOL` `M` |
+| `oracle.sh` | every op compared against libref on the operands the model issued. Read it for MISMATCH lines and for the NOT CHECKED lines that name what cannot be compared. `OPS` `MAXN` `FROM`/`TO` `TOL` `M` |
 
 ### Regression checks against a live server
 
-These cover what `tests/chat_test.cpp` structurally cannot: the server, the wire format, and a real
-model's output.
+These cover what `tests/chat_test.cpp` cannot: the server, the wire format and a real model's
+output.
 
 | | |
 |---|---|
-| `tierident.sh` | does a session that left VRAM come back byte for byte, both halves, after a full host tier, and (with `TTL`) after it expired? `P` `H` `N` `TO_HOST` `FILL` `TTL` |
-| `tiercross.sh` | the same with **two** sessions in flight — the only way to see one being served the other's context |
-| `mctools.sh` | the tool-call shapes hardest to parse — an array argument, two calls in one reply, prose before a call, plain chat with tools available. Asserts `finish_reason` and that no ` **They are not all read-only.** `tierident.sh`, `tiercross.sh`, `mctools.sh` and `mcstream.sh`
-> talk to a server already running (port 8100 unless `P` says otherwise) and leave it alone.
-> `mcagent.sh` and `mcdecl.sh` **start and stop servers of their own** — and `mcserve.sh`, which
-> they call, begins with `pkill -f "bin/radianc[e]"`, so they will take down any radiance you have
-> running. Check before you run one on a box that is serving.
+> **Not all of them leave a server alone.** `tierident.sh`, `tiercross.sh`, `mctools.sh` and
+> `mcstream.sh` talk to a server already running (port 8100 unless `P` says otherwise) and leave
+> it running. `mcagent.sh` and `mcdecl.sh` start and stop servers of their own through
+> `mcserve.sh`, which begins with `pkill -f "bin/radianc[e]"`, so they stop any radiance running
+> on the machine.
 
 ```sh
 scripts/mctools.sh && scripts/mcstream.sh
 ```
 
-### One more, in `tools/`
+### In `tools/`
 
-`tools/kbench-analysis.sh` produces the static-and-dynamic-analysis fragment that
-`rad-kbench --analysis` splices into its report. `tools/ops_doc_check.sh` is the `ops_doc` test:
-it holds `docs/OPS.md` to what the registries actually declare.
+`tools/kbench-analysis.sh` produces the static- and dynamic-analysis fragment that
+`rad-kbench --analysis` splices into its report. `tools/ops_doc_check.sh` is the `ops_doc` test: it
+checks `docs/OPS.md` against the schemas the plugins declare.
diff --git a/docs/TP3.md b/docs/TP3.md
index 4305b212..c67cf822 100644
--- a/docs/TP3.md
+++ b/docs/TP3.md
@@ -1,121 +1,124 @@
-# Any world size: the attention world, uneven delta-net heads, and nothing padded
+# Tensor parallelism at any world size
 
-Radiance shards by dividing: `n_head`, `n_head_kv`, the delta-net head counts and the vocabulary
-each split across the world, and a count that does not divide is **refused at declare, by name**
-(`share.cpp`, `rad_arch.h`). Four ranks get through for Qwen3.8-Flash-Next by replicating the two
-KV heads in rank pairs; three did not: 24 query heads, 2 KV heads, 16 GDN K heads and 48 GDN V
-heads have no even share in 3, and replication needs a world that is a multiple of the head count.
-Padding the checkpoint offline (`tools/pad_tp.py`: zero heads appended so that 36 / 3 / 18 / 54
-divide) served three ranks exactly, at the cost of a second 115 GiB container for every model and
-a third of the attention and 2 of 18 delta-net heads computing zeros.
+radiance shards by dividing: `n_head`, `n_head_kv` and the delta-net head counts split across the
+world, and a count that does not divide is refused at declare, by name (`rad_arch.h`,
+`core/format/share.cpp`). Qwen3.8-Flash-Next has 24 query heads, 2 KV heads, 16 GDN K heads and 48
+GDN V heads. Four ranks work by replicating each KV head on a pair of ranks; three do not, since
+none of the counts divides by 3 and replication needs a world that is a multiple of the KV head
+count.
 
-This document describes what replaced it: **the shipped container serves at any world size**, with
-no tool and no second file. Two rules, both built from machinery the engine already had.
+Two rules let the shipped container serve at any world size, with no second container and no
+padded heads: a smaller attention world (§1) and uneven delta-net heads (§2).
 
 ## 1. The attention world
 
-`rad_arch.h` `geom_from` handles a world *above* the KV head count by replication, when the world
-is a multiple of the count. For a plugin that asks for it (`attn_world_ok`; qwen4exp does) it also
-handles a world that is **neither a divisor nor a multiple** of it:
+`rad_arch.h` `geom_from` handles a world above the KV head count by replication when the world is
+a multiple of the count. For a plugin that passes `attn_world_ok` (qwen4exp does), it also handles
+a world that is neither a divisor nor a multiple of the count: attention is served on the largest
+multiple of the KV head count below the world (the **attention world**), and the ranks past it are
+**attention-zero**.
 
-> attention is served on the largest multiple of the KV head count under the world -- the
-> **attention world** -- and the ranks past it are **attention-zero**.
+Three ranks over two KV heads give an attention world of 2. Ranks 0 and 1 split the heads as a
+two-rank serve does (12 query heads, one KV head, gqa 12, the same kernels). Rank 2 computes no
+attention: `rad_block_attn_gated_fp8.h` declares no projections, no attention and no cache store on
+it, and zeroes the block's output wire with one `fill` ([OPS.md](OPS.md)). The all-reduce and the
+residual after it run as usual, and the zero adds nothing to the reduce. Five ranks over two KV
+heads give an attention world of 4 (two replicated pairs) with rank 4 attention-zero; six give
+three pairs and no zero rank. A plugin that does not pass `attn_world_ok` is refused at such a
+world, by name.
 
-Three ranks over two KV heads: the attention world is 2. Ranks 0 and 1 split the heads exactly as
-the two-rank serve does -- 12 query heads, one KV head, gqa 12, the same kernels -- and rank 2
-**computes no attention**: `rad_block_attn_gated_fp8.h` declares no projections, no attention and
-no cache store on it, and writes the block's output wire to zero with one `fill` (`docs/OPS.md`).
-The all-reduce and the residual after it see what they always saw, and the zero adds exactly
-nothing to the reduce. Five ranks over two: attention world 4 (two replicated pairs), rank 4
-attention-zero. Six: three pairs, no zero rank. A plugin that does not ask is refused at a world
-like these, by name, as before.
-
-**The KV groups stay in the same order on every rank.** The scheduler sees one program
+KV groups stay in the same order on every rank. The scheduler sees one program
 (`core/sched/batch.cpp` indexes `kv_groups[i]` by position) and one block table serves every rank,
 so an attention-zero rank declares its attention group like its peers and marks it
-`rad_kv_group_zero`: it carves nothing for it, holds the shared table's block count, lends none of
-it, and the tiers skip it when they move an entry. Every rank carves the same block count -- each
-is planned, asked what it could page (`KVManager::paged_tokens`; a rank whose only paged groups are
-zero limits nobody) and capped at the least before any carves.
+`rad_kv_group_zero`: it carves nothing for the group, holds the shared table's block count, lends
+none of it, and the tiers skip the group when they move an entry. Every rank carves the same block
+count: each is planned, asked what it could page (`KVManager::paged_tokens`; a rank whose only
+paged groups are zero limits nobody), and capped at the least before any rank carves.
 
-**The attention-zero rank's pools are its own.** The budget resolver derives one split for every
-card, the dearest rank's -- and an attention-zero rank's cache costs a fraction of its peers' per
-token (at TP3 on Flash-Next it keeps only the QSA block keys: 2.3 GiB at the worst case where an
-attention rank's costs 15.2). Under `expert_tiered` with both pools derived, `Engine::plan` gives
-such a rank a KV pool that pages exactly the common token count (`KVManager::pool_mib_for_tokens`,
-the inverse of `paged_tokens`: the least whole MiB whose paged split reaches the count, exact
-because the split is monotone in the budget and its alignment is among the fixed costs) and moves the
-difference into its weights pool, no further than every one of its weights resident. Both readers
-of the resolved sizes take the rank's own split -- `Pools::configure` and the planner -- so the
-grown pool is planned into, and startup refuses a rank whose plan and weights pool disagree, or
-whose re-sized KV pool pages fewer tokens than it was sized for. The token count, the carve, the
-loan and the attention ranks' pools are unchanged, and `auto` keeps the common split (a fully
-resident rank would choose all_vram while its peers spill). `--deterministic` and a device without virtual memory
-management re-split like any other: the cache does not lend there, and the bytes the rank never
-pages are as much its experts' as they are under a lending cache. The condition is the cost, not
-the world: a rank is re-split only where its cache costs less per token than the dearest rank's,
-which at TP2/TP4 no rank does. A rank that qualifies and keeps the common split names the reason on
-its `kv: rank N's cache costs ...` line. The pinned host pool is not re-split: every rank allocates
-its whole `--host-pool-mib`, and a re-split rank whose weights all fit on the card says so
-(`its pinned host pool holds no weights`). The log line, and the mover on the third rank:
+An attention-zero rank gets pools of its own. The budget resolver derives one split for every card
+from the most expensive rank, and an attention-zero rank's cache costs a fraction of its peers' per
+token (at TP3 on Flash-Next it keeps only the QSA block keys: 2.3 GiB at the worst case, where an
+attention rank's costs 15.2 GiB). Under `expert_tiered`, `Engine::plan` gives such a rank a KV pool
+that pages exactly the common token count (`KVManager::pool_mib_for_tokens`, the inverse of
+`paged_tokens`: the least whole MiB whose paged split reaches the count; exact because the split is
+monotone in the budget and its alignment is among the fixed costs), and moves the difference into
+its weights pool, up to all of its weights resident.
+
+- Both readers of the resolved sizes, `Pools::configure` and the planner, take the rank's own
+  split, so the grown pool is planned into. Startup refuses a rank whose plan and weights pool
+  disagree, or whose re-sized KV pool pages fewer tokens than it was sized for.
+- The token count, the carve, the loan and the attention ranks' pools are unchanged.
+- Other placements keep the common split (under `auto` a fully resident rank would choose
+  all_vram while its peers spill).
+- `--deterministic` and a device without virtual memory management re-split like any other: the
+  cache does not lend there, and the bytes the rank never pages are as much its experts' as under a
+  lending cache.
+- The condition is the cost, not the world: a rank is re-split only when its cache costs less per
+  token than the most expensive rank's, which at TP2 and TP4 no rank does. A rank that qualifies
+  but keeps the common split gives the reason on its `kv: rank N's cache costs ...` line.
+- The pinned host pool is not re-split: every rank allocates its whole `--host-pool-mib`, and a
+  re-split rank whose weights all fit on the card logs that its pinned host pool holds no weights.
+
+The log line on the third rank:
 
 ```
 kv: rank 2's cache costs 2.27 GiB at the worst case where its dearest peer's costs 15.16 GiB, so its KV pool pages the common 1446302 tokens in 1811 MiB instead of 10881; its weights pool grows 19747 -> 21692 MiB (every weight resident wants 21.18 GiB), and 7125 MiB stay unclaimed
-I[2] mover: 25142 slab slots (64 shadow), 0 pinned pool slots
 ```
 
-The settle check's INFO line on that card names the unclaimed MiB and points at this line rather
-than at the budget's `unusable` line alone.
+That rank's `mover:` line then reports 0 pinned pool slots. The settle check's INFO line on that
+card names the unclaimed MiB and points at the `kv: rank 2 ...` line, not only at the budget's
+`unusable` line.
 
-Under a smaller attention world the plain even shard over `world` is the wrong cut for every
-attention projection, so the attention ranks declare **spans** (`rad_weight_shard_span`, the same
-call the KV replication uses for k/v): q|gate rows and output columns `[attn_rank * n_head,
-+n_head)` heads, k/v rows at `kv_off`. When the attention world is the world -- every TP2 and TP4
-deployment -- no span is declared and the block declares as it always did.
+Under a smaller attention world, the even shard over `world` is the wrong cut for every attention
+projection, so the attention ranks declare spans (`rad_weight_shard_span`, the call KV replication
+uses for k/v): q|gate rows and output columns over heads `[attn_rank * n_head, +n_head)`, k/v rows
+at `kv_off`. When the attention world is the world (every TP2 and TP4 deployment), no span is
+declared.
 
 ## 2. Uneven delta-net heads
 
-The delta net has no KV-head constraint: its kernels are bound on head *widths* (`head_k`,
-`head_v`, the chunk) and take any head count. So 16 K heads over three ranks are **5, 5 and 6**,
-each rank's V heads the same multiple of its K heads (48 / 16 = 3: 15, 15, 18), every rank real
-heads, nothing padded. The extra head goes to the rank without attention (`remainder_place` in
-`rad_arch.h`): it has the time, and the rank that would otherwise hold the extra head AND attention
-is the step's slowest. The experts' extra block stays on the parity rotation (`qwen4exp_fp8.cpp`
-says why). `qwen4exp` computes the split and `rad_block_gdn_fp8.h` declares it as spans of the
-container's rows. Each rank's recurrent state is its own size, so a fresh slot is cleared, a
-snapshot taken and a tier entry laid out by each rank's own plan: a slot of the snapshot store or
-the tiers is the sum of the ranks' shares, each rank's where the ones before it end.
+The delta net has no KV-head constraint: its kernels are bound by head widths (`head_k`, `head_v`,
+the chunk) and take any head count. 16 K heads over three ranks are therefore 5, 5 and 6, and each
+rank's V heads are the same multiple of its K heads (48 / 16 = 3: 15, 15 and 18). Every rank holds
+real heads and nothing is padded.
 
-That needed one thing the span call could not say. `in_proj_qkv|z` is four projections stacked
-along dim 0 -- q 2048, k 2048, v 6144, z 6144 rows -- and `rad_weight_shard_span` takes one
-`[lo, hi)` applied to every stacked part, which assumes the parts are equal.
-**`rad_weight_shard_span_parts`** (an additive export) takes a span per part together with each
-part's whole extent in the container; `share.cpp` cuts every part by its own rows. The conv
-channels `[q|k|v]`, the `[a|b]` projections, `A_log`, `dt_bias` and the output projection's
-columns take the same rank's heads. The even split, when the counts divide, is untouched.
+The extra head goes to the rank without attention (`remainder_place` in `rad_arch.h`), which has
+the time; a rank holding both the extra head and attention would be the step's slowest. The
+experts' extra block stays on the parity rotation (`qwen4exp_fp8.cpp` gives the reason).
+`qwen4exp` computes the split and `rad_block_gdn_fp8.h` declares it as spans of the container's
+rows. Each rank's recurrent state has its own size, so each rank's own plan clears a fresh slot,
+takes a snapshot and lays out a tier entry: a slot of the snapshot store or of the tiers is the sum
+of the ranks' shares, each rank's share starting where the previous one ends.
 
-## 3. What this is built from
+`in_proj_qkv|z` stacks four projections along dim 0 (q 2048, k 2048, v 6144 and z 6144 rows), and
+`rad_weight_shard_span` applies one `[lo, hi)` to every stacked part, which assumes equal parts.
+`rad_weight_shard_span_parts` takes a span per part together with each part's whole extent in the
+container, and `share.cpp` cuts every part by its own rows. The conv channels `[q|k|v]`, the `[a|b]`
+projections, `A_log`, `dt_bias` and the output projection's columns take the same rank's heads.
+When the counts divide, the even split is used.
 
-- `rad_weight_shard_span_parts(b, w, lo, hi, total, n)` -- a span per stacked part.
-- `rad_kv_group_zero(b, g)` -- this rank keeps no cache for a paged group.
-- the `fill` op -- libr4d's `fill_bf16`, libref's `ref_fill`.
+## 3. Interfaces
+
+- `rad_weight_shard_span_parts(b, w, lo, hi, total, n)`: a span per stacked part.
+- `rad_kv_group_zero(b, g)`: this rank keeps no cache for a paged group.
+- The `fill` op: libr4d's `fill_bf16`, libref's `ref_fill`.
 - `Geom::attn_world / attn_rank / attn_zero`, set by `geom_from` under `attn_world_ok`;
   `GdnFP8::Config::k_first / v_first`, set by the plugin.
-- The exports are additive: `RAD_ABI_VERSION` does not move, and a plugin that does not call them
-  declares as before. `tests/share_test.cpp` holds the per-part cut, `tests/arch_test.cpp` the
-  three-rank declaration, `tests/mem_test.cpp` the capped carve, the zero group and a tier entry
-  moved across ranks with unequal shares.
+- Both exports are additive: `RAD_ABI_VERSION` is unchanged by them, and a plugin that does not
+  call them is unaffected.
+- Tests: `tests/share_test.cpp` covers the per-part cut, `tests/arch_test.cpp` the three-rank
+  declaration, and `tests/mem_test.cpp` the capped carve, the zero group and a tier entry moved
+  across ranks with unequal shares.
 
-**A load check that came with it.** The relayout pool refuses to finish when any staged weight was
-never delivered: a slot nothing wrote holds whatever the card had there -- zeros on a card whose
-freed memory the driver wipes, garbage after a reset ("VRAM is lost"). The instrument that shows
-such a read on any card:
+Load check: the relayout pool refuses to finish when any staged weight was never delivered. A slot
+nothing wrote holds whatever the card had there: zeros on a card whose driver wipes freed memory,
+garbage after a reset ("VRAM is lost"). To expose such a read on any card:
 
     RADIANCE_DEBUG_POISON_ALLOC=255 radiance --model stock.rad --tp 3 ...
 
-fills every fresh device allocation with 0xFF (NaN in every float width) before it is handed out;
-the serve must answer exactly as without it. `RADIANCE_DEBUG_POISON_RANGE=lo:hi` narrows the fill
-to a thread's allocation ordinals for a bisect (`core/device/dispatch.cpp`).
+This fills every fresh device allocation with 0xFF (NaN in every float width) before it is handed
+out; the serve must answer exactly as without it. `RADIANCE_DEBUG_POISON_RANGE=lo:hi` narrows the
+fill to a range of a thread's allocation ordinals, for bisecting (`core/device/dispatch.cpp`).
 
 ## 4. Serving
 
@@ -126,28 +129,34 @@ radiance --model qwen3.8-next-flash-fp8-iq4r-moe.rad --tp 3 --tp-wire exact --ma
     --num-speculative-tokens 3 --max-num-batched-tokens 2048
 ```
 
-The exact all-reduce at three ranks is the wide family's one-shot up to 1 MiB a message (every
-decode step) and its two-shot above it (every prefill chunk): reduce-scatter + all-gather, which
-sends 4/3 of the message per rank instead of twice it. A message rarely divides into thirds -- a
-2048-wide bf16 row is 256 16-byte words -- so the first `words % 3` shards take one word more.
-Both rows fold in fp32 in ascending rank order, so the band edge between them changes no bits.
-`--tp-wire wht6` at three ranks is the four-rank tiered-int8 wire over the same uneven two-shot,
-above `--tp-wire-min-kb`; under it, the exact one-shot.
+At three ranks the exact all-reduce is the one-shot up to 1 MiB per message (every decode step) and
+the two-shot above it (every prefill chunk). The two-shot is reduce-scatter + all-gather and sends
+4/3 of the message per rank instead of twice it. A message rarely divides into thirds (a
+2048-wide bf16 row is 256 16-byte words), so the first `words % 3` shards take one word more. Both
+fold in fp32 in ascending rank order, so the switch between them changes no bits. `--tp-wire wht6`
+at three ranks is the tiered-int8 wire over the same uneven two-shot for messages from
+`--tp-wire-min-kb` up, and the exact one-shot below.
 
-The log says what the geometry did:
+Startup logs the geometry:
 
 ```
 radiance: world_size = 3 over n_head_kv = 2: attention on 2 rank(s), rank(s) 2..2 carry no attention and take the delta net's remainder first
-radiance: qwen4exp: rank 0 takes delta-net K heads [6, 11) of 16 and V heads [18, 33) of 48
-radiance: qwen4exp: rank 1 takes delta-net K heads [11, 16) of 16 and V heads [33, 48) of 48
-radiance: qwen4exp: rank 2 takes delta-net K heads [0, 6) of 16 and V heads [0, 18) of 48
 ```
 
-Measured by the contributor on three Radeon AI PRO R9700 (gfx1201, PCIe Gen5 x16) at an earlier
-state of this design -- the attention-zero rank then ran its projections on zero weights, and the
-extra delta-net head sat on rank 0 -- with the uncensored Flash-Next fine-tune. Hot = 1 / 4 / 8
-streams, 8 K prompt, 1 K generated, aggregate tok/s; crowd = 4 streams at 100 K context, per
-stream; HumanEval 164 and a 200-question GSM8K subset at temperature 0:
+Each rank's delta-net share is a note in its declared graph; `--debug-graph` and the dashboard's
+graph view show rank 0's:
+
+```
+rank 0 takes delta-net K heads [6, 11) of 16 and V heads [18, 33) of 48
+```
+
+Ranks 1 and 2 take K heads [11, 16) and [0, 6), and V heads [33, 48) and [0, 18).
+
+The following was measured by a contributor on three Radeon AI PRO R9700 (gfx1201, PCIe Gen5 x16)
+with the uncensored Flash-Next fine-tune, on an earlier revision of this design: the
+attention-zero rank still ran its projections on zero weights, and the extra delta-net head sat on
+rank 0. Hot = 1 / 4 / 8 streams, 8K prompt, 1K generated, aggregate tok/s; crowd = 4 streams at
+100K context, per stream; HumanEval 164 and a 200-question GSM8K subset at temperature 0:
 
 | container | `--tp` | hot c1 / c4 / c8 | crowd | HE | GSM8K |
 |---|---|---|---|---|---|
@@ -155,11 +164,12 @@ stream; HumanEval 164 and a 200-question GSM8K subset at temperature 0:
 | unpadded, the same file | 2 | 177 / 308 / 377 | 33.8 | 0.884 | 0.915 |
 | padded offline | 3 | 182 / 288 / 395 | 43.5 | 0.848 | 0.935 |
 
-Three ranks buy the single stream and the long-context crowd, not the eight-stream aggregate. The
-quality rows are within a rerun of each other (HumanEval moves by about 3 of 164 between runs of one
-container); unpadded and padded at three ranks gave the same answers on 40 prompts at temperature
-0, bit-identical on one -- the head regroup changes the order the all-reduce sums in, and near-ties
-flip.
+At these settings three ranks were faster than two for a single stream and for the long-context
+crowd, but not for the eight-stream aggregate. The quality columns are within run-to-run variation
+(HumanEval moves by about 3 of 164 between runs of one container). Unpadded and padded at three
+ranks gave the same answers on 40 prompts at temperature 0, bit-identical on one: the head regroup
+changes the order the all-reduce sums in, and near-ties flip.
 
-`tools/pad_tp.py` and `tools/pad_verify.py` remain in the tree: they are how a checkpoint is padded
-for an engine that has no attention world, and how a pad is verified, and nothing here needs them.
+`tools/pad_tp.py` pads a checkpoint for an engine without an attention world (zero heads appended
+so that 36 / 3 / 18 / 54 divide, at the cost of a second container and of computing zeros), and
+`tools/pad_verify.py` verifies a pad; radiance needs neither.
diff --git a/docs/TP4.md b/docs/TP4.md
new file mode 100644
index 00000000..dcbb4375
--- /dev/null
+++ b/docs/TP4.md
@@ -0,0 +1,189 @@
+# Four ranks on a PCIe fabric: what pays, what doesn't, and how to tell
+
+A measured map of every TP4 lever tried on 4×R9700 (PCIe P2P, no NVLink),
+with the receipt that decided each one — for anyone attacking the same
+terrain on a different card or fabric. The shipped combination here is
+span (#78) + the link-hold release (#94) + the four-rank harness (#93);
+everything else in the table is either reverted or still open.
+All numbers: paired within-session windows, bar ≥0.5% + sign test, geometry
+`--prefill-span 2 --tp-wire wht6 --placement all_vram` iq4r MoE unless stated.
+Every "dead" row is a *measured* dead — the mechanism, not a guess.
+
+## The table
+
+| # | Element | What we tried | Result (measured) | Status / PR |
+|---|---------|--------------|-------------------|-------------|
+| 1 | `--prefill-span 2` (upstream **#78**) | overlap the two half-chunk all-reduces with compute via ti8 lane rows; needed `I=2048` + `all_vram` (placement flips its sign!) | +5…11% pp span-on under `all_vram`; repro of upstream's numbers | **SHIPPED**; receipts posted on #78 |
+| 2 | **R2** = `ar_*_4rank` link-hold release (kernel gate `link_gate/early/gate_ctr`) | 4-rank rows answered "keep holding" → all yielding DMA (stager copies, expert prefetch) idled behind every collective; wire the self-release like the 2-rank rows do | **−3.66% c8 when removed** (W16, 2 rounds, per-req agrees) — the whole R-suite carrier | **SHIPPED**, PR **#94** with the number |
+| 3 | **R6** 4-rank selftest harness | shipped TP4 width had zero test coverage; wide-collective + fused-write cases at world 4 (+fixed gather oracle indexing) | test-only; it's what lets anything else be proven at TP4 | **SHIPPED**, PR **#93** |
+| 4 | **R1** MoE FK four-class band (20→80) | widen expert-GEMM fast band for mixed-class tiles | **inert for W4=4 (iq4r)** — cap only bites 3-bit formats; TP2: provable no-op | REVERTED; PR **#95 closed** in favor of upstream #79 |
+| 5 | **R3** fused AR+hc_write prefill rows (`wire==1` band) | fuse residual write into exact-wire AR epilogue | **0 selections** in 121k-line debug-graph boot (wht6 → lossy band; fused row is exact-only); removing whole suite = noise | REVERTED; PR **#96 closed** w/ receipts — *never isolated: measured only inside the exact-wire bundle (row 9), its own territory un-timed* |
+| 6 | **W15** MoE per-class grid split | give lossy/exact class tiles their own launch grids | **non-constructible**: "a run's class is not a property of `blockIdx.y`" — all y-siblings of a (tile,run) serve one run | DEAD; its selftest arm (`R4D_PERFMOE4`) and mixed-class cases are on the author's fork, not in this tree |
+| 7 | **W17/#100** ti8 fused two-shot + hc_write (`ar_twoshot_hc_write_4rank_ti8`) | delete the standalone hc_write launches from the lossy decode/verify band (new `ti8 1` key, M=26..max_tok) | byte-for-bit ✅ on GPU; row selected ✅; **c8 −0.43%, c16 sign-split — no win**. Launches are cheap here (~4µs floor); epilogue serializes behind AR spin | PR **#100** (closed, branch + byte-for-bit harness kept on the fork), honest-null description; MTP-head declare finding inside |
+| 8 | **W18** AR grid 16→32→64 blocks (`R4D_AR_NB_DESIGN`) | hypothesis: 16-block design starves the P2P link | **GB/s FALLS with blocks**: M=2048 34.5→33.7→31.4; M=128 18.4→12.4→7.4. Handshake-bound, not launch-starved | DEAD rungs (images kept); microbench killed it in 3 min |
+| 9 | exact wire (`--tp-wire exact`) vs wht6 | exact AR everywhere incl. fused rows | loses −7.6…−8.3% at span-off to wht6; 128 KiB wire floor proven; exact only lives at T≤25 decode | rejected; upstream informed |
+| 10 | F1 rank-load balancer | rebalance shard columns to equalize rank work | ~+1.3% at 64K only; **bit-changing output** | not shipped (bit-identity beats 1.3%) |
+| 11 | step-graph capture (launch overhead) | replay decode passes as HIP graphs (`libr4d/isa/graphrate.hip` arms) | trunk submit = **backpressure** (device-bound; host hidden) → capture irrelevant for trunk; draft-pass gap real but hidden by other requests at c8+ | closed for trunk; draft-loop variant unmeasured (pays only at c1/c2) |
+| 12 | **W19** clean lane | revert R1+R3, keep R2+R6, re-gate | **parity** (c8 +0.45%, c16 −0.08%, noise band) → deletions cost nothing | **SHIPPED = prod** |
+| 13 | ti8 gather row (a hypothetical `ar_gather_hc_write_4rank_ti8`; the fused gather row that exists, `ar_gather_hc_write_4rank`, is exact-wire only) | hypothesis: the MoE gather is the last exact-wire (2 B/elem) collective; move it to ti8 like the AR rows | **premise collapsed by code reading**: on the lossy band the MoE boundary runs the unfused triple `moe_gather + ar_twoshot_4rank_ti8 + hc_write` — the gather's all-reduce already rides ti8. The `wire==0` fused row serves exact territory only; what a ti8 gather row would buy there is launch fusion, measured null (row 7) | demoted: companion of the (closed) fused-epilogue line, exact-wire configs only |
+| 14 | codec inner-loop (the "22%") | decomposed the ti8 two-shot with `--perfarx` probe kernels: encode-only / encode+push / fold-only, vs the full row, M=2048/4096 | **dead, and the reframe is the prize**: encode = 4% of the row (36 µs of ~900); the P2P push runs at ~60 GB/s = **PCIe Gen5 x16 line rate** — the fabric is saturated, ti8 is already optimal per byte; fold ~200 µs is local-memory work pp doesn't wait on (row 12/13 showed pp isn't link-bound) | CLOSED — no codec win exists; “22% tax” was line-rate physics |
+
+## Kill levels — which dead ends are actually closed
+
+A dead end is only closed if the code ran where it was meant to run, did the right
+thing, and still lost. Rows below say which level killed them; **L0/L1 kills are
+implementation gaps, not physics** — a differently-coded version of those is still
+fair game, and this is the list to re-attack from.
+
+| level | meaning | rows |
+|---|---|---|
+| **L3 mechanism dead** | ran, correct, lost to a measured mechanism | W18 grid (GB/s falls with blocks — handshake-bound), W17 fusion (ran + byte-exact + net-flat; the saved launches are at the 4 µs floor), step-graph capture (trunk submit = backpressure — *but this one is synthetic-evidence only, see below*) |
+| **L2 territory dead** | the config that would use it loses as a bundle | exact wire −7.6…−8.3% (row 9) — but it bundles rows 5/13, see L1 |
+| **L1 never activated** | declared, never observed serving; never benchmarked in its own territory | **R3 fused rows (row 5): 0 selections on the lossy lane; its exact-wire territory was only ever measured inside W11's bundle, never isolated** · **fused gather row: same story — on the lossy lane `gather_taken()` skips it by design; nobody has booted an exact-wire config and timed it** (`ar_gather_hc_write_4rank`) |
+| **L0 never implemented** | the idea died before code | W15 per-class grid (single-launch version non-constructible: "class is not a property of `blockIdx.y`" — a **two-launch split version was never tried**; it only matters for mixed-class formats, not W4) · ti8 one-shot band for 128 KiB–512 KiB (flagged upstream, nobody built it) · draft-pass graph capture (real host gap, unmeasured, pays only at c1/c2) |
+
+Two caveats on the L3 list, since L3 is the only level that forbids re-trying:
+step-graph closure rests on the `graphrate` synthetic ring, not an engine capture —
+the engine has no capture path to test, so treat it as strong-suspect, not closed.
+And W17's net-flat is solid *at the geometry it ran*; it does not falsify fused
+epilogues for configs that sit host-bound (very low concurrency + slow host).
+
+## Instruments (not lanes, but they decide lanes)
+
+`--debug-graph` boot (2 min): which row the config *actually selects* —
+killed R3 and W15 premises, and pinned R2's sites — note it lists declared bands, so a row can match on paper while a different row serves the step; confirm against the running step. `--perfar/--perfarx`:
+cross-rank row us/launch + GB/s, arms interleaved one loop (drift rule); these two
+`r4d_selftest` modes are on the author's fork, not in this tree (which has `--perfops`, `--perfhc`
+and the GEMM/MoE ones).
+`rad-kbench`: kernel-vs-reference replay. BetterBench (one fixed standard profile):
+promotion truth; quick concurrency ladders within windows.
+
+## Open levers, ranked
+
+1. **Decode-side config**: big steps (interval 4096 / budget 8192) measured
+   +2…3% c8 and −2…4% pp — a two-flag promotion if the serving mix is
+   decode-heavy. No new code; already paired twice (rows 12 + W22).
+2. exact-wire configs only: the fused gather/write rows (row 13) still have
+   territory there — on a lossy wire they are launch-fusion rows, not wins.
+3. **span_min sweep** — the floor of eight checkpoint intervals (16384 tokens at
+   I=2048) applies only where routed experts are read from host memory, and was
+   priced on Flash-Next at TP2; under `all_vram` there is none and every lone
+   prefill spans. At TP4 with tiered experts the floor is unmeasured. One
+   boot-flag arm + window.
+4. ti8 **one-shot band** for 128 KiB–512 KiB lossy messages (currently every
+   such message pays two-shot 1.5N + 2 syncs) — flagged upstream on #78.
+5. Draft-pass graph capture — only if low-concurrency latency ever matters.
+
+## Interaction diagram
+
+Where each element lives in one decode/prefill step (per layer, TP4):
+
+```
+                     ENGINE LAYER (per step)
+   span (PR78): prefill step = 2 chunks; chunk A's AR on lane-2
+   beside chunk B's compute.  stager DMA + expert prefetch run
+   CONCURRENTLY with kernels — unless the link gate is held:
+   ┌────────────────────────────────────────────────────────────┐
+   │ link gate (R2/#94): collective must release it itself,     │
+   │ else every yielding DMA waits out the whole collective.    │
+   │ any NEW collective row MUST honor it or re-lose the 3.7%        │
+   └────────────────────────────────────────────────────────────┘
+                     KERNEL LAYER (per layer ×8 + MTP head ×2)
+  attn out ──► AR ──► hc_write ──► router ──► MoE gather ──► hc_write
+              │          │                       │
+              │          │                       └─ MoE boundary: on the lossy wire
+              │          │                          this is the UNFUSED triple (gather +
+              │          │                          ar_twoshot_4rank_ti8 + hc_write) — the
+              │          │                          gather's AR already rides ti8. The fused
+              │          │                          exact rows (R3: 0 selects; ti8 gather:
+              │          │                          launch fusion = row 7 null) serve exact
+              │          │                          W17 fused ti8+write, no win
+              │          └─ tiny op, 4µs launch floor (perfops) — not attackable
+              │
+              ├─ ar_twoshot_4rank_ti8        (T≥26 & ≥128KiB: the shipped row)
+              │    └─ codec (r4d_ar_ti8.h): 4-lane groups, 38B records,
+              │       own-shard exact + int8 peers.  the "22%" is the push at
+              │       PCIe line rate (row 14, appendix E): no codec lever
+              │    └─ grid: nb_for rule, design=16 — W18: raising it LOWERS GB/s
+              ├─ exact rows (T≤25 / <128KiB): 1-sync oneshot — already cheapest
+              └─ one-shot gap: 128KiB–512KiB lossy has no 1-sync form (upstream)
+                     HOST LAYER
+  no step graph; trunk submit = backpressure (graphrate) → launch-count
+  fusion structurally unimportant (why W17 measured flat); draft passes
+  have real host gaps, invisible at c8+ concurrency.
+```
+
+Value stack, multiplicative where marked: PR78 overlaps the ARs · R2 unblocks
+DMA around them · on the lossy wire the AR and the gather already share the one
+codec. The bytes lever is spent, and the codec's push runs at line rate (row 14).
+
+## Appendix A — cross-rank row microbench (`--perfar` on the author's fork, idle cards, 300 iters, arms interleaved one loop)
+
+```
+ti8 M=16   nb=rule   33.1 us  14.8 GB/s   (under the 131072 B floor: exact one-shot folds it)
+ti8 M=128  nb=16     63.4 us  18.4 GB/s
+ti8 M=128  nb=32     94.5 us  12.4 GB/s
+ti8 M=128  nb=64    156.9 us   7.4 GB/s   (64 = R4D_AR_WIDE_MAX_BLOCKS)
+ti8 M=2048 nb=16    540.8 us  34.5 GB/s   (shipped)
+ti8 M=2048 nb=32    554.7 us  33.7 GB/s
+ti8 M=2048 nb=64    594.9 us  31.4 GB/s
+exact M=2048 rule   830.4 us  37.9 GB/s   (control: 2x the bytes, 1.53x the time)
+```
+
+Reads: more blocks LOSE (handshake-bound, not launch-starved); the ti8 wire
+buys 2x bytes for ~1.53x time — the ~22% fold/push tax lives inside the codec
+(appendix E decomposes it).
+
+## Appendix B — host submit cost (`libr4d/isa/graphrate.hip`, 45-dispatch pass)
+
+```
+individual      62.4 us   (1.39 us a dispatch, +GetLastError churn)
+graph            3.6 us   (0.08 a dispatch — the floor, unreachable: passes aren't static)
+graph+set       21.1 us   (~10 moved operand pointers/step)
+recap+update    89.5 us   (capture 0.48/node + ExecUpdate 63.7 — LOSES vs plain)
+full ring       52.9 us   == idle ring => trunk submit is BACKPRESSURE, host is hidden
+```
+
+Reads: step-graph capture is irrelevant for a trunk that runs ahead of the
+device; it can only matter where the host sits on the critical path (MTP
+draft passes), and there other requests hide the gap at ≥8 concurrency.
+
+## Appendix C — small-op launch floor (`r4d_selftest --perfops 16 2560`, 500 launches, one sync per stretch)
+
+```
+rmsnorm_quant_fp8  4.43 us | rmsnorm_quant_fp8(res) 4.19 | gated_quant_fp8 3.70
+quant_act_fp8      4.64 us | rmsnorm_bf16 4.64       | add_bf16 4.03
+```
+
+Every elementwise op costs the same ~4-4.6 us regardless of payload: pure
+launch/teardown floor at 26-88 GB/s. Fusing two such ops saves the launch,
+and a launch saved here demonstrably moves nothing end-to-end (see W17).
+
+## Appendix D — the config surface (`chunk = checkpoint_interval x span`, clamped BEFORE the budget)
+
+The step budget is not the chunk: a prefill chunk is `min(budget, interval x span)` (the engine
+prints the effective chunk at boot — read that line before sweeping anything). Measured, paired,
+lossy wire, chunk-4096 baseline = shipped:
+
+| arm | pp16K | pp64K | pp128K | c8 | c16 |
+|---|---|---|---|---|---|
+| chunk 8192 (`I 4096 x span 2`, budget 8192) | -1.7% | -3.7% | -3.0% | +2.0% | +1.0% |
+| step 8192 (budget up, chunk clamped unchanged) | -4.1% | -1.3% | -1.3% | +3.1% | +1.0% |
+
+Both directions agree: **bigger steps/chunks trade pp for decode** — on this box pp time hides
+behind compute, decode time hides behind stalls, so nothing on the link side moves pp. The step
+band is sized by the AR mailbox (`numel` instance bound = budget x width), so raising the budget
+extends the device band — but the arch sizes a QSA score plane `budget x max_ctx / 4` and refuses
+when it grows past its cap; the flags are coupled, the refusal is named and loud.
+
+## Appendix E — the ti8 codec decomposed (`--perfarx` probe kernels on the author's fork, M=2048 nb=16)
+
+One launch of the shipped row = 909 us. Phase probes: encode into local mailbox **36 us (4%)**;
+encode+P2P-push+flag 210 us — the push alone runs ~60 GB/s = **PCIe Gen5 x16 line rate**; fold
+(reduce + region-B + out + assemble) 196 us of local-memory work. At the band top (M=4096)
+nb=32 beats the rule's nb=16 by 2.3% — inside the don't-bother band.
+
+Reads: the "22% link-efficiency tax" of the lossy wire vs exact is **line-rate physics, not an
+implementation defect** — the wire is saturated and per-byte optimal. Encode is irrelevant; the
+fold is real but off the critical path (see D: pp isn't link-bound). There is no codec patch to
+write; proposals for codec-kernel link wins should be pointed at the push-rate line.
diff --git a/docs/YARN.md b/docs/YARN.md
index a88f7e78..fc453ef8 100644
--- a/docs/YARN.md
+++ b/docs/YARN.md
@@ -1,26 +1,25 @@
 # Static YaRN
 
-Increasing `--max-model-len` reserves a larger serving window; it does not change
-the model's rotary embeddings. A checkpoint trained at 262144 positions can
-explicitly request static YaRN for a 524288-token deployment. Whether that extension
-preserves useful accuracy must be measured on the model and workload.
+A larger `--max-model-len` reserves a larger serving window; it does not change the model's rotary
+embedding. A checkpoint trained at 262144 positions can request static YaRN explicitly for a
+524288-token deployment. Whether the extension keeps useful accuracy must be measured on the model
+and workload.
 
-One reader takes every architecture's rotary scaling (`yarn_from`,
-`arch/common/rad_arch.h`). For the target it reads `text_config.rope_parameters`,
-then `rope_parameters`, then the legacy `text_config.rope_scaling` and `rope_scaling`,
-in that order; the first object with `rope_type` (or legacy `type`) is authoritative.
-A drafter (DFlash2, DSpark) reads its own `draft.rope_parameters` /
-`draft.rope_scaling`; it does not inherit the target's scaling. The vision tower keeps
-its original axial rotations. A GGUF's `rope.scaling.*` keys are carried in as the
-same `rope_scaling` keys when it is read.
+Every architecture reads its rotary scaling through one function (`yarn_from`,
+`arch/common/rad_arch.h`). For the target it reads `text_config.rope_parameters`, then
+`rope_parameters`, then the legacy `text_config.rope_scaling` and `rope_scaling`; the first object
+with a `rope_type` (or legacy `type`) key is authoritative. A drafter (DFlash2, DSpark) reads its
+own `draft.rope_parameters` / `draft.rope_scaling` and does not inherit the target's scaling. The
+vision tower keeps its axial rotary. A GGUF's `rope.scaling.*` keys are read in as the same
+`rope_scaling` keys.
 
-**The factor convention is the config's**, as vLLM and transformers read it:
-`factor` 2 over `original_max_position_embeddings` 262144 reaches 524288 positions.
+The factor convention is the config's, as vLLM and transformers read it: `factor` 2 over
+`original_max_position_embeddings` 262144 reaches 524288 positions.
 
-Validated so far: the Qwen3.8 27B and 35B-A3B containers and both Flash-Next
-variants at factor 2, with retrieval at ~500K tokens, and TP3 perplexity with
-`--rope-scaling` within roughly ±1% of stock at factor 2. The LLaMA plugins read the
-same keys and declare the same ops; YaRN there has had no model run.
+Validated: the Qwen3.8-27B and Qwen3.6-35B-A3B containers and both Flash-Next variants at factor 2,
+with retrieval at about 500K tokens, and TP3 perplexity with `--rope-scaling` within about ±1% of
+the unscaled model at factor 2. The LLaMA plugins read the same keys and declare the same ops, but
+YaRN has not been run on a LLaMA model.
 
 ## Metadata
 
@@ -28,22 +27,21 @@ same keys and declare the same ops; YaRN there has had no model run.
 | --- | --- |
 | `rope_type` | `yarn`; `default`, absent or legacy `mrope` is no scaling; `linear` divides positions by `factor` |
 | `factor` | finite number >= 1, required for YaRN |
-| `original_max_position_embeddings` | positive integer, required; the **training** length, not the enlarged deployment/table length |
+| `original_max_position_embeddings` | positive integer, required; the training length, not the enlarged deployment or table length |
 | `beta_fast`, `beta_slow` | defaults 32 and 1; finite, fast >= slow > 0 |
 | `attention_factor` | positive finite cos/sin multiplier; default 1 + 0.1 ln(factor) for factor > 1, otherwise 1 |
-| `truncate` | true/1 (default): floor/ceil correction bounds; false/0: retain fractional bounds |
+| `truncate` | true/1 (default): floor/ceil correction bounds; false/0: keep fractional bounds |
 
-Every other type -- `llama3`, `longrope`, `dynamic` -- is refused by name at load,
-as are the `mscale` and `mscale_all_dim` variants (specify `attention_factor`). A
-GGUF that sets llama.cpp's YaRN `attn_factor`, `ext_factor` or log multiplier to
-anything but its neutral value is refused when read. Rotary width (including
-partial rotary), theta and M-RoPE section selection are unchanged.
+Every other type (`llama3`, `longrope`, `dynamic`) is refused by name at load, as are the `mscale`
+and `mscale_all_dim` keys (use `attention_factor`). A GGUF that sets llama.cpp's YaRN
+`attn_factor`, `ext_factor` or log multiplier to anything but its neutral value is refused when
+read. Rotary width (including partial rotary), theta and the M-RoPE sections are unchanged.
 
-## Convert a separate container
+## Converting a separate container
 
-Use the original target and drafter checkpoints, the same quantization recipe,
-and a **new output path**. `--reuse` is valid only for the same source weights and
-recipe; it is not a way to mix weights from different model revisions.
+Use the original target and drafter checkpoints, the same recipe, and a new output path. `--reuse`
+is valid only for the same source weights and recipe; it cannot mix weights from different model
+revisions.
 
 ```sh
 rad-convert /checkpoints/Qwen3.8-27B-FP8 \
@@ -60,10 +58,9 @@ rad-convert /checkpoints/Qwen3.8-27B-FP8 \
   -o /models/qwen3.8-27b-fp8-yarn2.rad
 ```
 
-Run with `--plan-only` first. `--max-ctx` is the converter's graph bound, not a
-replacement for the explicit YaRN metadata or the server's `--max-model-len`.
-The bundled `.rad` by itself is not a converter input; keep the source checkpoints.
-Check both target and draft settings with `rad-info --meta` after conversion.
+Run it with `--plan-only` first. `--max-ctx` is the converter's graph bound; it replaces neither
+the YaRN metadata nor the server's `--max-model-len`. A `.rad` is not a converter input, so keep
+the source checkpoints. After conversion, check the target and draft keys with `rad-info --meta`.
 
 Serve on enough memory for the requested window:
 
@@ -72,53 +69,57 @@ radiance --model /models/qwen3.8-27b-fp8-yarn2.rad \
   --tp 4 --max-model-len 524288 --max-num-seqs 32 --kv-cache-dtype bf16
 ```
 
-That cache flag controls **both** target and drafter KV. Startup capacity and
-successful actual long requests must be checked; the command is not a promise
-of concurrency or accuracy. Keep the unmodified model and serving setup until
-long-context quality and speed meet the deployment's requirements.
+`--kv-cache-dtype` sets both the target's and the drafter's KV cache. Check the startup capacity
+and real long requests; the command guarantees neither concurrency nor accuracy. Keep the
+unmodified model and serving setup until long-context quality and speed meet the deployment's
+requirements.
 
-## Serve an existing container: `--rope-scaling`
+## Serving an existing container: `--rope-scaling`
 
-The same metadata can be written when the container is loaded instead of converted in:
+The same metadata can be applied when the container is loaded instead of at conversion:
 
 ```sh
 radiance --model /models/qwen3.8-next-flash-fp8.rad \
   --rope-scaling yarn:2 --max-model-len 409600
 ```
 
-`yarn:FACTOR[:ORIG]` sets `rope_type = yarn`, `factor` and `original_max_position_embeddings`
-(`ORIG`, default the container's own trained length) in the rotary object the reader above
-takes first -- for a Qwen3.8 container that is `text_config.rope_parameters`, which already says
-`default`; YaRN written under plain `rope_parameters` would sit behind it and never be read. A
-drafter gets the same factor over its own trained length. Over a checkpoint's own YaRN
-the factor is replaced, its trained length kept unless `ORIG` is given, and an explicit
-`attention_factor` (or `mscale` variant) dropped so the magnitude is derived for the new factor.
-`none` takes a checkpoint's YaRN off. A linear or other explicit rotary type is refused rather
-than stacked over. The result is resolved and checked exactly as a converted container's is
-(`core/format/rope_override.h`, held to `yarn_from` in `tests/yarn_test.cpp`).
+`yarn:FACTOR[:ORIG]` (FACTOR above 1) sets `rope_type = yarn`, `factor` and
+`original_max_position_embeddings` (`ORIG`, default the container's own trained length) in the
+object the reader takes first. For a Qwen3.8 container that is `text_config.rope_parameters`,
+which already says `default`; YaRN written under plain `rope_parameters` would never be read. A
+drafter gets the same factor over its own trained length.
 
-Startup says what the rotary is (`rope: YaRN factor 2 over 262144 trained positions -- the rotary
-reaches 524288`) and warns when `--max-model-len` is past what it covers -- also with no scaling
-at all, past the trained length.
+Over a checkpoint's own YaRN, the factor is replaced, the trained length is kept unless `ORIG` is
+given, and an explicit `attention_factor` (or `mscale` key) is dropped so the magnitude is derived
+for the new factor. `none` turns a checkpoint's YaRN off. A `linear` or other explicit rotary type
+is refused, not stacked over. The result is resolved and checked as a converted container's is
+(`core/format/rope_override.h`, held to `yarn_from` by `tests/yarn_test.cpp`).
 
-The flag is for trying a factor, or serving a container whose source checkpoints are not at hand;
-a deployment that settles on one can convert it in as above and drop the flag.
+Startup logs the rotary:
+
+```
+rope: YaRN factor 2 over 262144 trained positions -- the rotary reaches 524288; --max-model-len 409600 (--rope-scaling)
+```
+
+It warns when `--max-model-len` is past what the rotary covers, and, with no scaling, past the
+trained length.
+
+Use the flag to try a factor, or to serve a container whose source checkpoints are not at hand. A
+deployment that settles on a factor can convert it in as above and drop the flag.
 
 ## Kernel and test contract
 
-`rope`, `rope_table` and `qsa_block_key` take optional resolved coefficients
-`yarn_factor`, `yarn_low`, `yarn_high`, `yarn_magnitude` (docs/OPS.md). Absent factor
-is the original path, with the original op identities. With YaRN, `scale` must be 1:
-inverse frequencies are blended rather than all positions being divided. Axial
-rotary with YaRN is refused. Rebuild the bundled plugins together because their
-shared op schemas must match.
+`rope`, `rope_table` and `qsa_block_key` take the optional resolved coefficients `yarn_factor`,
+`yarn_low`, `yarn_high` and `yarn_magnitude` ([OPS.md](OPS.md)). Without them an op is declared
+as for an unscaled rotary, so op identities and tune keys do not change. With YaRN, `scale` must be 1, since YaRN
+blends inverse frequencies instead of dividing positions. Axial rotary with YaRN is refused.
+Rebuild the bundled plugins together, because their shared op schemas must match.
 
 The math follows the static YaRN formulation (Peng et al.) as vLLM's
-`YaRNScalingRotaryEmbedding` implements it. `tests/yarn_test.cpp` pins the
-correction bounds to vLLM's integers (14/22, 28/43, 56/85 for rotary widths 64, 128,
-256 at factor 2, theta 1e7, 262144 trained positions); `tests/ref_test.cpp` and
-`r4d_selftest` compare libref and libr4d against a double-precision evaluation of the
-same formula at positions through 524287, within 8 ulp of each angle -- tight where
-the ramp sits, loose only in the fastest pairs at long positions, which no f32 rotary
-places better than its angle's own ulp. libavx is held to libref by `avx_check`, and
-fused versus unfused HIP rotation is checked byte-for-byte separately.
+`YaRNScalingRotaryEmbedding` implements it. `tests/yarn_test.cpp` pins the correction bounds to
+vLLM's integers (14/22, 28/43, 56/85 for rotary widths 64, 128, 256 at factor 2, theta 1e7, 262144
+trained positions). `tests/ref_test.cpp` and `r4d_selftest` compare libref and libr4d against a
+double-precision evaluation of the same formula at positions up to 524287, within 8 ulp of each
+angle. That bound is tight where the ramp sits and loose only in the fastest pairs at long
+positions, where no f32 rotary can do better than the angle's own ulp. `avx_check` holds libavx
+to libref, and fused against unfused HIP rotation is checked byte for byte.
diff --git a/docs/qwen3-8-flash-next-gguf-quant-recipes.md b/docs/qwen3-8-flash-next-gguf-quant-recipes.md
index 69405ea4..1e099a59 100644
--- a/docs/qwen3-8-flash-next-gguf-quant-recipes.md
+++ b/docs/qwen3-8-flash-next-gguf-quant-recipes.md
@@ -1,21 +1,9 @@
-# Research note: measured quant recipes of `unsloth/Qwen3.8-Flash-Next-GGUF`
+# Research note: quant recipes of `unsloth/Qwen3.8-Flash-Next-GGUF`
 
-Method: GGUF header reads only (HTTP `Range`), no weight downloads · Verified against published file sizes to 4 significant figures
+Method: GGUF header reads only (HTTP `Range`), no weight downloads; sizes verified against the
+published file sizes to 4 significant figures.
 
-## TL;DR
-
-- Qwen3.8 Flash Next is **176.94 B total / ~6.04 B active** parameters: 125.74 B "normal"
-  weights (48 layers, 512-expert MoE, Gated DeltaNet + 12 layers of QSA sparse attention)
-  plus a **51.20 B n-gram/PLE look-up table** (29 % of all params, 0 FLOPs).
-- Unsloth's quants only really compress **two things**: the routed-expert `gate`/`up`
-  matrices and the n-gram table. Everything else stays at Q8_0/Q6_K/F32 in every build.
-- Consequence: **file size has a floor (~72 GB) and per-token traffic has a floor (~3.5 GB)**
-  that are invisible in the quant name. Q2_K_XL → IQ1_S buys 3 % of per-token bandwidth and
-  costs 0.6 bpw of expert precision — a bad trade.
-- MTP speculative decoding trades **+17 % compute for −38 % weight traffic** per token at
-  batch 1, and is a net loss at ≥8 concurrent streams.
-
-## Model facts (read from the GGUF KV metadata)
+## Model facts (from the GGUF KV metadata)
 
 | | |
 |---|---|
@@ -28,35 +16,37 @@ Method: GGUF header reads only (HTTP `Range`), no weight downloads · Verified a
 | draft | 1 MTP layer (`blk.48`, `nextn.*`), 3.88 B params self-contained / 2.61 B shared |
 | quantisation | imatrix-driven: `quantize.imatrix.file = imatrix_unsloth.gguf`, 926 entries of 1224 tensors, 45 calibration chunks (absent only in the BF16 build) |
 
-Per-token tensor census: 1224 tensors; `blk.N` names appear 48× (layers), attn_q/k/v/o and
-`indexer.*` 12× (QSA layers), `attn_qkv`/`attn_gate`/`ssm_*` 36× (DeltaNet layers),
-`ffn_gate_exps/up_exps/down_exps` 48× as `[2560, 640, 512]`-stacked 3-D tensors (838.86 M
-params each).
+176.94 B parameters in total: 125.74 B of model weights and a 51.20 B n-gram/PLE look-up table
+(29%, no FLOPs). About 6.04 B are active per token (see "Active parameters").
 
-## Method — how to read a quant recipe without downloading anything
+Tensor census: 1224 tensors; `blk.N` names appear 48× (layers), attn_q/k/v/o and `indexer.*` 12×
+(QSA layers), `attn_qkv`/`attn_gate`/`ssm_*` 36× (DeltaNet layers), and
+`ffn_gate_exps/up_exps/down_exps` 48× as `[2560, 640, 512]`-stacked 3-D tensors (838.86 M params
+each).
 
-`GET` the first ~1 MB of each `.gguf` with a `Range` header and parse the header:
-magic `GGUF`, version, `n_tensors` (u64), `n_kv` (u64), KV pairs, then per tensor
-`name`, `n_dims`, `dims[]`, `ggml_type` (u32), `offset` (u64). Name + dims + type *is* the
-recipe; the tensor data blobs are never touched.
+## Reading a recipe without downloading
 
-Four things that bite:
+`GET` the first ~1 MB of each `.gguf` with a `Range` header and parse the header: magic `GGUF`,
+version, `n_tensors` (u64), `n_kv` (u64), the KV pairs, then per tensor `name`, `n_dims`, `dims[]`,
+`ggml_type` (u32), `offset` (u64). Name, dims and type are the recipe; the tensor data is never
+read.
 
-1. **Split repos.** In a `gguf-split` "magic" layout the **first shard has
-   `n_tensors = 0`** and carries only metadata (≈ 11 MB, mostly tokenizer arrays); every
-   *data* shard repeats 3 KV pairs plus the tensor-info table for the tensors it holds. So
-   tensor info must be merged from shards 2…N, and KV (`general.file_type`,
-   `quantize.imatrix.*`) read from shard 1. A scanner that only reads shard 1 reports zero
-   tensors.
-2. **Don't guess the type enum.** Use the real `GGMLQuantizationType` values (F32 0, F16 1,
-   Q4_0 2, Q8_0 8, Q2_K 10, Q4_K 12, Q5_K 13, Q6_K 14, IQ2_XXS 16, IQ3_XXS 18, IQ1_S 19,
-   IQ4_NL 20, IQ3_S 21, IQ2_S 22, IQ4_XS 23, IQ1_M 29, BF16 30) and
-   `GGML_QUANT_SIZES` for block sizes. A wrong enum silently mislabels the whole table.
-3. **Validate.** Compute `Σ ⌈n/block⌉ · type_size` over all tensors and compare with the
-   published shard sizes. Agreement to 4 significant figures across all 11 builds
-   (e.g. 354.02 GB computed vs 354.03 GB published) is what makes the dtype IDs trustworthy.
-4. Parse with an offset pointer into the buffer, not `buf = buf[n:]` per field — that is
-   quadratic on an 11 MB header and looks exactly like a network hang.
+Pitfalls:
+
+1. **Split repos.** In a `gguf-split` layout the **first shard has `n_tensors = 0`** and carries
+   only metadata (≈ 11 MB, mostly tokenizer arrays); every data shard repeats 3 KV pairs plus the
+   tensor-info table for its own tensors. Merge tensor info from shards 2…N, and read KV
+   (`general.file_type`, `quantize.imatrix.*`) from shard 1. A scanner that reads only shard 1
+   reports zero tensors.
+2. **Use the real type enum.** `GGMLQuantizationType` values: F32 0, F16 1, Q4_0 2, Q8_0 8, Q2_K 10,
+   Q4_K 12, Q5_K 13, Q6_K 14, IQ2_XXS 16, IQ3_XXS 18, IQ1_S 19, IQ4_NL 20, IQ3_S 21, IQ2_S 22,
+   IQ4_XS 23, IQ1_M 29, BF16 30; block sizes from `GGML_QUANT_SIZES`. A wrong enum silently
+   mislabels the whole table.
+3. **Validate.** Compute `Σ ⌈n/block⌉ · type_size` over all tensors and compare with the published
+   shard sizes. Agreement to 4 significant figures across all 11 builds (e.g. 354.02 GB computed vs
+   354.03 GB published) confirms the type IDs.
+4. Parse with an offset into the buffer, not `buf = buf[n:]` per field, which is quadratic on an
+   11 MB header and looks like a network hang.
 
 ## File sizes
 
@@ -74,9 +64,9 @@ Four things that bite:
 | UD-IQ1_M | 176.94 B | 74.54 GB | 3.37 |
 | UD-IQ1_S | 176.94 B | 72.55 GB | 3.28 |
 
-`L2`/`L46-47` below = layers given one notch more precision (dynamic "UD/XL" selection).
+## Recipe matrix
 
-## The recipe matrix
+`L2`/`L46-47` = layers given one notch more precision (the dynamic "UD/XL" selection).
 
 | weight group (count, params) | BF16 | Q8_0 | Q6_K_XL | Q5_K_XL | Q4_K_XL | Q3_K_XL | IQ4_XS | Q2_K_XL | IQ3_XXS | IQ1_M | IQ1_S |
 |---|---|---|---|---|---|---|---|---|---|---|---|
@@ -104,15 +94,14 @@ Four things that bite:
 the other 24. IQ1_S: IQ2_XXS at L1-2, 4, 14, 16, 25, 30, 32, 37, 39, 42, 45-47 (14 tensors),
 IQ1_S on the other 34.
 
-Type bpw for reference: Q4_K 4.50, Q5_K 5.50, Q5_1 6.00, Q6_K 6.56, Q8_0 8.50, IQ1_S 1.56,
-IQ1_M 1.75, IQ2_XXS 2.06, IQ2_XS 2.31, IQ2_S 2.56, IQ3_XXS 3.06, IQ3_S 3.44, IQ4_NL 4.50,
-IQ4_XS 4.25.
+Type bpw: Q4_K 4.50, Q5_K 5.50, Q5_1 6.00, Q6_K 6.56, Q8_0 8.50, IQ1_S 1.56, IQ1_M 1.75,
+IQ2_XXS 2.06, IQ2_XS 2.31, IQ2_S 2.56, IQ3_XXS 3.06, IQ3_S 3.44, IQ4_NL 4.50, IQ4_XS 4.25.
 
-MTP drafts are separate recipes: `mtp-*Q8_0` is Q8_0 throughout (indexer BF16, norms F32);
+MTP drafts have their own recipes: `mtp-*Q8_0` is Q8_0 throughout (indexer BF16, norms F32);
 `mtp-*Q4_K_M` is stock llama.cpp Q4_K_M (Q4_K base, `output`/`attn_v`/`ffn_down*`/`hc_ffn_down`
-upcast to Q6_K/Q8_0, and the `[320, 10240]` up-projections fall to **Q5_0** because 320 is not
-a multiple of the 256-element K-quant block). `mmproj-*` is a 0.449 B `clip` vision tower,
-BF16 or F16 only, with biases/pos-embed in F32.
+upcast to Q6_K/Q8_0, and the `[320, 10240]` up-projections fall to **Q5_0** because 320 is not a
+multiple of the 256-element K-quant block). `mmproj-*` is a 0.449 B `clip` vision tower, BF16 or
+F16 only, with biases and position embeddings in F32.
 
 ## Where the bytes go
 
@@ -124,11 +113,11 @@ BF16 or F16 only, with biases/pos-embed in F32.
 | everything else (5 B, 2 %) | 8.96 / 4.1 | 9.04 / 4.2 | 9.04 / 4.2 | 6.92 / 3.2 | 6.91 / 3.2 |
 | share of file that is n-gram + expert down | 51 % | 54 % | 57 % | 65 % | 71 % |
 
-## Sizes with the n-gram table removed
+## Sizes without the n-gram table
 
-`per_layer_token_embd.weight` is a single 160 × 320 001 536 tensor — 51.20 B params, i.e. 41 %
-as many params as the rest of the model combined. It takes only three settings across the whole
-repo: BF16 (102.4 GB), Q8_0 (54.4 GB) and IQ4_NL (28.8 GB).
+`per_layer_token_embd.weight` is a single 160 × 320 001 536 tensor: 51.20 B params, 41 % as many
+as the rest of the model combined. It takes only three settings across the repository: BF16
+(102.4 GB), Q8_0 (54.4 GB) and IQ4_NL (28.8 GB).
 
 | build | file | n-gram table | rest of model | rest bpw (÷ 125.74 B) | n-gram share |
 |---|---|---|---|---|---|
@@ -144,13 +133,12 @@ repo: BF16 (102.4 GB), Q8_0 (54.4 GB) and IQ4_NL (28.8 GB).
 | UD-IQ1_M | 74.53 | 28.80 | **45.73 GB** | 2.91 | 38.6 % |
 | UD-IQ1_S | 72.54 | 28.80 | **43.74 GB** | 2.78 | 39.7 % |
 
-Strip the table and the ladder is a genuine 2.8-8.5 bpw spread instead of the flat 3.3-8.5 the
-file sizes suggest.
+Without the table the builds span 2.8-8.5 bpw, not the 3.3-8.5 the file sizes suggest.
 
 ## Active parameters
 
-Per forward, counting only tensors actually touched (routed experts at 10/512, embedding and
-n-gram tables as look-ups):
+Per forward, counting only tensors touched (routed experts at 10/512, embedding and n-gram tables
+as look-ups):
 
 | component | active/token | in file | fraction used |
 |---|---|---|---|
@@ -167,14 +155,14 @@ n-gram tables as look-ups):
 | token embedding | ≈ 0 (1 row) | 0.64 B | 2e-4 % |
 | **total** | **6.671 B** incl. lm_head / **6.036 B** excl. | 176.94 B | **3.77 %** |
 
-6.036 B reproduces Qwen's advertised "6B activated"; 125.74 B reproduces "125B". Two thirds of
-the active mass is dense (DeltaNet + gated residual + attention), not expert — so this behaves
-like a bandwidth-bound 6 B dense model wearing a 177 B memory footprint, not like a normal MoE.
+6.036 B matches Qwen's advertised "6B activated" and 125.74 B its "125B". Two thirds of the active
+parameters are dense (DeltaNet, gated residual, attention), not experts, so per-token cost is that
+of a bandwidth-bound 6 B dense model with a 177 B memory footprint.
 
-Per draft step, the MTP head adds 139.7 M of real work (`attn` 49.8 M, 10 experts 49.2 M,
-`eh_proj` 13.1 M, gated residual 13.1 M, `hc_head` 6.6 M, shared expert 4.9 M, router/indexer
-3.3 M) plus the 636 M output projection → **0.776 B active and 0.83 GB read per draft token**,
-of which 82 % is the output projection.
+Per draft step the MTP head adds 139.7 M of compute (`attn` 49.8 M, 10 experts 49.2 M, `eh_proj`
+13.1 M, gated residual 13.1 M, `hc_head` 6.6 M, shared expert 4.9 M, router/indexer 3.3 M) plus the
+636 M output projection: **0.776 B active and 0.83 GB read per draft token**, 82 % of it the output
+projection.
 
 | | active params | weight bytes read (Q4_K_XL) |
 |---|---|---|
@@ -186,8 +174,8 @@ of which 82 % is the output projection.
 ## Weight traffic per token (batch 1)
 
 `step(P) = experts_touched(P) + dense + lm_head`, with `experts_touched(P) = 512·(1 − (1 −
-10/512)^P)` (P=1 → 10.0, P=2 → 19.8, P=3 → 29.4 experts per layer). MTP row uses
-`shared-Q8_0` draft, llama.cpp's `--spec-draft-n-max 2`, mean accepted length 2.76.
+10/512)^P)` (P=1 → 10.0, P=2 → 19.8, P=3 → 29.4 experts per layer). The MTP columns use the
+`shared-Q8_0` draft, llama.cpp's `--spec-draft-n-max 2`, and mean accepted length 2.76.
 
 | build | no MTP | MTP cycle | MTP per token | traffic ratio | measured speedup |
 |---|---|---|---|---|---|
@@ -205,53 +193,51 @@ of which 82 % is the output projection.
 
 ## Analysis
 
-1. **Quantisation here is applied to the expert FFNs and the n-gram table; nothing else
-   matters.** The other 3.6 B params sit at 7-32 bpw in every build and cost 3-4 GB total.
-2. **`down_proj` is protected, `gate`/`up` is the sacrifice.** Down never drops below 4.5 bpw
-   and is still full Q8_0 at Q6_K_XL/Q5_K_XL; at IQ1_S the down tables cost *more* bytes
-   (22.6 GB) than the gate+up tables (17.2 GB). Sensible — down-projection error is applied
-   after the nonlinearity and summed across the 10 active experts.
-3. **Router is never quantised** (F32 everywhere), nor is the QSA indexer (BF16 everywhere,
-   20 M params). Both are small and both fail catastrophically when wrong.
-4. **Layer 2 is special in every build** (one notch up, plus attention/shared-expert upcasts
-   at the aggressive levels) — it is adjacent to layer 1, where the n-gram/PLE signal is
-   injected. Layers 2, 4, 30, 46, 47 form an identical "important down-expert" set across
-   Q4_K_XL, Q3_K_XL and IQ4_XS, so the ranking comes from the calibration run, not from a
-   per-target heuristic.
-5. **The names understate size at the bottom.** UD-Q3_K_XL (90.0 GB) is *smaller* than
-   UD-IQ4_XS (93.7 GB), and UD-Q2_K_XL (78.9 GB) smaller than UD-IQ3_XXS (82.0 GB). Each pair
-   is one tier offered with two codebooks; the IQ variant buys accuracy with size
-   (IQ3_S 3.44 vs IQ3_XXS 3.06, IQ2_S 2.56 vs IQ2_XS 2.31 bpw).
-6. **The n-gram table is the real constraint.** 51.2 B params at a 4.5 bpw floor = 28.8 GB that
-   never shrinks, 71 % of the IQ1_S file when combined with the down tables. Nothing in this
-   repo goes under ~72 GB. It is a pure random look-up (≈ 1.4 KB/token, 2 560 values), so it is
-   a VRAM cost, not a bandwidth cost — the one component that is genuinely free to park in CPU
-   RAM or on disk.
-7. **MTP is a bandwidth-only trade.** +17 % compute (7.81 vs 6.67 B active params per token)
-   for −38 % weight traffic. Its hidden cost is that a 3-position verify pass touches ~29 of
-   512 experts per layer instead of 10, so MTP stops paying the moment concurrency saturates
-   the experts: unsloth measures Q4_K_XL at 83 → 139 tok/s with 1 user but 216 → 192 tok/s
-   *worse* with 8 users.
-8. **Value points.** Q4_K_XL (5.03 bpw, 111 GB) is the best engineering point. Below it,
-   each step buys surprisingly little traffic: Q2_K_XL → IQ1_S is 3 % of per-token bandwidth
-   for 0.6 bpw of expert precision, and IQ1_S additionally under-delivers in practice (1.34×
-   vs 1.74× modelled) because 1.5 bpw IQ1_S is dequant-bound. Take IQ1_M over IQ1_S if 74.5 GB
-   fits — 2 GB more for +0.2 bpw. For MTP, use a `shared-*` draft: identical runtime cost,
-   ~1.3 GB less resident weight, and the draft's output projection is then read at the *main*
-   model's precision.
+1. **Only the expert FFNs and the n-gram table are compressed hard.** Everything else stays at
+   Q4_K or better, mostly Q8_0/Q6_K/F32: the other 3.6 B params sit at 7-32 bpw and cost 3-4 GB in
+   every build, a floor on both file size and per-token traffic that the quant name does not show.
+2. **`down_proj` is protected, `gate`/`up` gives way.** Down never drops below 4.5 bpw and stays
+   Q8_0 at Q6_K_XL/Q5_K_XL; at IQ1_S the down tables cost more bytes (22.6 GB) than gate+up
+   (17.2 GB). Down-projection error is applied after the nonlinearity and summed across the 10
+   active experts.
+3. **The router is never quantised** (F32 everywhere), nor is the QSA indexer (BF16 everywhere,
+   20 M params). Both are small and both fail badly when wrong.
+4. **Layer 2 is upgraded in every build** (one notch up, plus attention/shared-expert upcasts at the
+   aggressive levels); it is adjacent to layer 1, where the n-gram/PLE signal is injected. Layers 2,
+   4, 30, 46, 47 form the same "important down-expert" set across Q4_K_XL, Q3_K_XL and IQ4_XS, so
+   the ranking comes from the calibration run, not a per-target heuristic.
+5. **Names understate size at the bottom.** UD-Q3_K_XL (90.0 GB) is smaller than UD-IQ4_XS
+   (93.7 GB), and UD-Q2_K_XL (78.9 GB) smaller than UD-IQ3_XXS (82.0 GB). Each pair is one tier with
+   two codebooks; the IQ variant buys accuracy with size (IQ3_S 3.44 vs IQ3_XXS 3.06, IQ2_S 2.56 vs
+   IQ2_XS 2.31 bpw).
+6. **The n-gram table is the binding constraint on size.** 51.2 B params at a 4.5 bpw floor is
+   28.8 GB in every build below Q5_K_XL, 71 % of the IQ1_S file together with the down tables;
+   nothing in the repository is under ~72 GB. It is a random look-up (≈ 1.4 KB per token,
+   2 560 values), so it costs memory, not bandwidth, and is the one component that can live in CPU
+   RAM or on disk at no speed cost.
+7. **MTP trades compute for bandwidth.** +17 % compute (7.81 vs 6.67 B active params per token) for
+   −38 % weight traffic at batch 1. A 3-position verify pass touches ~29 of 512 experts per layer
+   instead of 10, so MTP stops paying once concurrency saturates the experts: unsloth measures
+   Q4_K_XL at 83 → 139 tok/s with 1 user but 216 → 192 tok/s with 8.
+8. **Value points.** Q4_K_XL (5.03 bpw, 111 GB) is the best balance. Below it each step saves little
+   traffic: Q2_K_XL → IQ1_S saves 3 % of per-token bandwidth for 0.6 bpw of expert precision, and
+   IQ1_S also under-delivers in practice (1.34× vs 1.74× modelled) because 1.5 bpw IQ1_S is
+   dequant-bound. Prefer IQ1_M over IQ1_S if 74.5 GB fits (2 GB more for +0.2 bpw). For MTP, use a
+   `shared-*` draft: the same runtime cost, ~1.3 GB less resident weight, and the draft's output
+   projection read at the main model's precision.
 
-## What the imatrix says
+## The imatrix
 
-`imatrix_unsloth.gguf` (580 MB, in the repo as `imatrix_unsloth.gguf_file`) is llama.cpp's GGUF
-imatrix: per weight, `in_sum2` (the sum of the input's squares, per input channel) and `counts`
+`imatrix_unsloth.gguf` (580 MB, in the repository as `imatrix_unsloth.gguf_file`) is llama.cpp's
+GGUF imatrix: per weight, `in_sum2` (the sum of the input's squares, per input channel) and `counts`
 (tokens seen). 45 chunks of 18 432 tokens = **829 440 tokens** from one file,
 `unsloth_calibration_Qwen3.8-Flash-Next.txt`. The routed experts are recorded **per expert**
 (`in_sum2` is `[K, 512]`, `counts` `[512]`); `ffn_gate_exps` and `ffn_up_exps` are byte-identical,
-being the same input. There is nothing for `blk.48`, `output`, `token_embd` or the n-gram table.
+having the same input. There is nothing for `blk.48`, `output`, `token_embd` or the n-gram table.
 
-**The Q8_0 down layers are the layers that host a super expert.** One expert in each of a few
-layers carries a large share of the layer's `down` input energy from a sliver of its tokens, all
-of it in one or two channels -- up to 208 000x that expert's median channel:
+**The Q8_0 down layers are the layers that host a super expert.** One expert in each of a few layers
+carries a large share of the layer's `down` input energy from a sliver of its tokens, all of it in
+one or two channels, up to 208 000x that expert's median channel:
 
 | layer | expert | share of the layer's down-input energy | share of its routing |
 |---|---|---|---|
@@ -261,40 +247,38 @@ of it in one or two channels -- up to 208 000x that expert's median channel:
 | 46 | 290 | 6.9 % | 0.84 % |
 | 30 | 169 | 3.9 % | 0.12 % |
 
-Those are exactly the five layers given Q8_0 down. The next layers by energy share (28, 37, 26:
-~4 %) are heavily *routed* experts, energy share equal to routing share, and are not protected. A
-super expert is **not harder to quantise relative to its own output** -- scored against its own
-imatrix profile, int4 g128 costs it the same ~12 % relative output error as an ordinary expert and
-E4M3 the same 2.6 % -- its output is simply that much larger, so the same relative error is a large
-absolute one. A GGUF type is per tensor and a tensor is all 512 experts of a layer, so protecting
-one expert costs the whole layer's `down`.
+These are the five layers given Q8_0 down. The next layers by energy share (28, 37, 26: ~4 %) are
+heavily routed experts whose energy share equals their routing share, and are not protected. A
+super expert is not harder to quantise relative to its own output: against its own imatrix
+profile, int4 g128 costs it the same ~12 % relative output error as an ordinary expert and E4M3 the
+same 2.6 %. Its output is larger, so the same relative error is a large absolute one. A GGUF type is
+per tensor and a tensor holds all 512 experts of a layer, so protecting one expert costs the whole
+layer's `down`.
 
 **A pooled down profile describes no expert.** A typical expert's own `down` input profile has a
-median cosine of 0.15-0.87 with the layer's pooled one (0.15 at layer 4, 0.20 at 47: the pool *is*
-the super expert there); `gate_up` 0.91-0.98. `down`'s input channels are each expert's own
+median cosine of 0.15-0.87 with the layer's pooled one (0.15 at layer 4, 0.20 at 47, where the pool
+is the super expert); `gate_up` 0.91-0.98. `down`'s input channels are each expert's own
 intermediate units, so channel `i` of one expert has nothing to do with channel `i` of another.
 
-**Against radiance's 10M-token Grams** (recorded from the bf16 model over ten million tokens of its
-calibration corpus, pooled per layer; [MOE-W4.md](MOE-W4.md), "Calibration"): the `gate_up`
-diagonals agree at every layer (cosine 0.98-0.99, the same top channels at the same shares), and so
-do the `down` spikes at layers 46 and 47 (channels 218 and 635). At layers 2, 4, 9, 14, 16, 25, 30
-and 32 the spike channels sit at a flat channel's share in radiance's Grams -- the super experts
-there never fired on its corpus. Open: either the imatrix harness (raw 18K-token chunks, each from
+**Compared with radiance's 10M-token Grams** (recorded from the bf16 model over ten million tokens
+of its calibration corpus, pooled per layer; [MOE-W4.md](MOE-W4.md), "Calibration"): the `gate_up`
+diagonals agree at every layer (cosine 0.98-0.99, the same top channels at the same shares), as do
+the `down` spikes at layers 46 and 47 (channels 218 and 635). At layers 2, 4, 9, 14, 16, 25, 30 and
+32 the spike channels sit at a flat channel's share in radiance's Grams: those super experts never
+fired on its corpus. Open question: either the imatrix harness (raw 18K-token chunks, each from
 position 0, special tokens as plain text) triggers what chat-templated traffic does not, or the two
 implementations compute those experts differently.
 
 **The expert stack repeats every 16 layers in the middle of the model.** Per-expert routing counts
 correlate 0.76-0.93 between layer L and L+16 for L in 8..23, and ~0 between neighbours; the same
-(expert, channel) spikes at 9/25 (e368 c191), 14/30 (e169 c72) and 16/32 (e391 c139).
+(expert, channel) spikes appear at 9/25 (e368 c191), 14/30 (e169 c72) and 16/32 (e391 c139).
 
 ## Caveats
 
-- These are the recipes of the shipped files as published when read (2026-09-30); later uploads
-  to the repository may differ. They say nothing about the *quality* of each level, which needs a
-  downstream eval.
-- Percentages inside a cell are byte shares of that tensor group.
+- These are the recipes of the files as published on 2026-09-30; later uploads may differ. They say
+  nothing about the quality of each level, which needs a downstream evaluation.
 - Traffic numbers assume batch 1 and independent routing across positions; real expert usage is
-  skewed, so distinct-expert counts (and hence MTP cost) are slightly over-estimated.
-- Mean accepted length 2.76 and 66 % acceptance are from a single unsloth log line
-  (`shared-Q8_0` draft + `Q4_K_XL`, 4× A100, 8 K input, llama.cpp's `--spec-draft-n-max 2`),
-  applied to every build here.
+  skewed, so distinct-expert counts (and hence MTP cost) are slightly overestimated.
+- Mean accepted length 2.76 and 66 % acceptance come from a single unsloth log line (`shared-Q8_0`
+  draft + `Q4_K_XL`, 4× A100, 8K input, llama.cpp's `--spec-draft-n-max 2`) and are applied to
+  every build here.
diff --git a/libavx/CMakeLists.txt b/libavx/CMakeLists.txt
index 5f5ba541..c55bc82b 100644
--- a/libavx/CMakeLists.txt
+++ b/libavx/CMakeLists.txt
@@ -1,39 +1,24 @@
 # libavx -- the conventional op vocabulary in hand-written x86 SIMD, dispatched by CPU feature.
 #
-# ============================ THE BUILD IS THE DISPATCH ============================
+# This build is what makes runtime dispatch safe:
 #
-# This file is not a list of sources. It is the mechanism that makes runtime dispatch SAFE, and
-# every decision in it is load-bearing:
+#   The kernels are compiled four times, once per ISA level, into OBJECT libraries with different
+#   -m flags and AVX_LEVEL=0..3. avx_vec.h wraps each level in its own inline namespace; without
+#   that the linker would keep one definition (e.g. of avx::row_to_f32) for all four tables, and
+#   the scalar path could execute AVX-512 and fault.
 #
-#   THE KERNELS ARE COMPILED FOUR TIMES, once per ISA level, into four OBJECT libraries with
-#   different -m flags and AVX_LEVEL defined to 0/1/2/3. Same sources, four instruction streams.
-#   avx_vec.h wraps each level in its own inline namespace so the four sets of symbols do not
-#   collide -- which is not a nicety: without it the linker would pick one definition of
-#   avx::row_to_f32 for all four tables, and on a machine without AVX-512 the SCALAR path would
-#   execute AVX-512 and fault.
+#   The dispatcher and registry are compiled at baseline with no -m flags, because they decide
+#   which levels may run. This depends on the flags, not the source: with -mavx512f the compiler
+#   may auto-vectorise code that has no intrinsics.
 #
-#   THE DISPATCHER AND THE REGISTRY ARE COMPILED BASELINE, with no -m flags at all. They are what
-#   decides whether the other levels may run, so an instruction above the baseline in either of
-#   them faults before the decision is made. Note that this is a property of the FLAGS and not of
-#   the source: a compiler given -mavx512f may auto-vectorise anything, so "contains no intrinsics"
-#   is not the same claim.
+#   No -march=native: the .so is copied to other machines and dlopened by an engine that does not
+#   know its target, so it would SIGILL on older CPUs before main.
 #
-#   -march=native APPEARS NOWHERE. It is the obvious thing and it is wrong for a plugin: the .so is
-#   built on one machine, copied to others, and dlopened by an engine that has no idea what it was
-#   compiled for. A binary built with -march=native on a Zen 5 host SIGILLs on the first
-#   AVX-512 instruction anywhere older, before main, with no diagnostic.
-#
-# ============================ IN THE TREE, AND ALONE ============================
-#
-# The root CMakeLists adds this directory on every x86-64 build: these are the production host
-# kernels, and a model whose placement puts an op on the host -- the n-gram embedding's gather,
-# every step -- has no other kernel for it that the engine will serve on.
-#
-# It also builds ON ITS OWN, as any third party's plugin does: against an installed radiance,
-# through find_package and the same rad_add_plugin -- `cmake -S libavx -B build-avx
-# -DCMAKE_PREFIX_PATH=`. A box with no ROCm builds and checks it that way without
-# the HIP probe and the whole core; the oracle the checker compares against is the installed
-# reference library.
+# The root CMakeLists adds this directory on every x86-64 build; these are the production host
+# kernels (e.g. the n-gram embedding gather when placed on the host). It also builds standalone
+# against an installed radiance, like any third-party plugin:
+# `cmake -S libavx -B build-avx -DCMAKE_PREFIX_PATH=`. That needs no ROCm, and
+# the checker's oracle is then the installed reference library.
 if(NOT COMMAND rad_add_plugin)
   cmake_minimum_required(VERSION 3.21)
   project(libavx LANGUAGES CXX)
@@ -41,13 +26,11 @@ if(NOT COMMAND rad_add_plugin)
   rad_plugin_defaults()
 endif()
 
-# The harnesses land beside the plugin, in the build's $RADIANCE_HOME, where the loader ignores
-# anything that is not a .so.
+# The harnesses go beside the plugin in the build's $RADIANCE_HOME; the loader ignores non-.so files.
 set(AVX_OUT_DIR ${RAD_PLUGIN_OUT}/kernels)
 
 # ============================ the four ISA levels ============================
-# Every kernel translation unit. avx_dispatch.cpp and avx_registry.cpp are NOT here -- they are
-# baseline and belong to the plugin target itself.
+# Every kernel translation unit. The baseline sources belong to the plugin target below.
 set(AVX_KERNEL_SRC
   avx_support.cpp
   avx_table.cpp
@@ -56,26 +39,27 @@ set(AVX_KERNEL_SRC
   avx_hc.cpp
   avx_quant.cpp
   avx_gemm.cpp
+  avx_gemm_tile.cpp
+  avx_planes.cpp
   avx_attn.cpp
+  avx_qsa.cpp
   avx_moe.cpp
   avx_gdn.cpp
   avx_sample.cpp
   avx_misc.cpp
+  avx_gen.cpp
+  avx_gen_attn.cpp
 )
 
-# The flag sets, one per level. Written out rather than derived, because each one is a claim about
-# what instructions the object may contain and a derived list hides that claim.
+# The flag sets, written out because each states which instructions the object may contain.
 #
-#   0 scalar  nothing. x86-64 baseline, which is SSE2 -- the compiler will use it for scalar float
-#             and that is fine: SSE2 is in the base ISA and exists on every x86-64 that boots.
-#   1 avx     -mavx alone. NOT -mf16c and NOT -mfma: both are separate CPUID bits that arrived
-#             after AVX (Ivy Bridge and Haswell), and a level called `avx` that required them would
-#             fault on exactly the Sandy Bridge machines it exists for.
-#   2 avx2    -mavx2 -mfma -mf16c. These three ship together on every part that has any of them.
-#   3 avx512  F + BW + DQ + VL, which is what avx_dispatch.cpp checks for as a conjunction, plus
-#             the AVX2 set beneath it. Deliberately NOT avx512bf16 / avx512vnni: many AVX-512
-#             parts have neither, and neither is used (see avx_vec.h on why the bf16 convert is
-#             done with integer ops rather than vcvtneps2bf16).
+#   0 scalar  x86-64 baseline (SSE2).
+#   1 avx     -mavx only. F16C and FMA are separate CPUID bits (Ivy Bridge, Haswell); requiring them
+#             would fault on the Sandy Bridge parts this level exists for.
+#   2 avx2    -mavx2 -mfma -mf16c, which ship together.
+#   3 avx512  F + BW + DQ + VL (the conjunction avx_dispatch.cpp checks) plus the AVX2 set. No
+#             avx512bf16 / avx512vnni: many AVX-512 parts lack them (avx_vec.h converts bf16 with
+#             integer ops instead of vcvtneps2bf16).
 set(AVX_FLAGS_0 "")
 set(AVX_FLAGS_1 -mavx)
 set(AVX_FLAGS_2 -mavx2 -mfma -mf16c)
@@ -89,18 +73,12 @@ foreach(lvl RANGE 0 3)
   target_link_libraries(avx_lvl${lvl} PRIVATE radiance::abi)
   target_include_directories(avx_lvl${lvl} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
   target_compile_options(avx_lvl${lvl} PRIVATE ${AVX_FLAGS_${lvl}}
-    # CONTRACTION IS ALLOWED HERE AND THAT IS THE OPPOSITE OF libref'S RULE, stated so the
-    # difference is deliberate rather than inherited. libref passes -ffp-contract=off because it is
-    # the ORACLE: a reference that contracts disagrees with itself between compilers. libavx is a
-    # fast kernel checked against that oracle to a tolerance, and refusing FMA would throw away
-    # half the machine's floating-point throughput to chase a bit-exactness it already gives up by
-    # vectorising the reduction at all.
+    # Contraction is allowed, unlike libref (the oracle, which must not contract). libavx is checked
+    # against it to a tolerance, and vectorised reductions are not bit-exact anyway, so FMA is kept.
     -ffp-contract=fast
-    # NO -ffast-math, and it is worth saying why given the above. Contraction changes the last ulp;
-    # -ffast-math changes what the code MEANS -- it lets the compiler assume no NaN and no signed
-    # zero, and this vocabulary is full of both (a masked logit is -inf, an attention row with no
-    # valid keys is a NaN the online softmax has to carry). The checker compares the finiteness
-    # pattern before it compares any number, exactly so that this cannot be smuggled in.
+    # No -ffast-math: it assumes no NaN/Inf and no signed zero, and these ops rely on them (a masked
+    # logit is -inf; an attention row with no valid keys carries a NaN through the online softmax).
+    # The checker compares the finiteness pattern before any value.
     -fno-math-errno)
   set_property(TARGET avx_lvl${lvl} PROPERTY POSITION_INDEPENDENT_CODE ON)
   if(OpenMP_CXX_FOUND)
@@ -109,9 +87,8 @@ foreach(lvl RANGE 0 3)
 endforeach()
 
 # ============================ the plugin ============================
-# avx_ngram.cpp is baseline for the same reason as the other two, and for one more: it holds the
-# embedding gather's row cache and its reader thread, and there must be ONE of each in the process
-# whatever level runs -- compiled per level, each level would keep its own.
+# Baseline sources. avx_ngram.cpp is also here because it holds the embedding gather's row cache
+# and reader thread, which must exist once per process, not once per level.
 set(AVX_BASELINE_SRC avx_dispatch.cpp avx_registry.cpp avx_ngram.cpp)
 
 rad_add_plugin(libavx kernels SOURCES ${AVX_BASELINE_SRC} INCLUDES ${CMAKE_CURRENT_SOURCE_DIR})
@@ -128,13 +105,18 @@ else()
 endif()
 
 # ============================ the harnesses ============================
-# They dlopen both plugins by path and link NEITHER. That is deliberate and it is what makes them
-# usable in both builds and against a plugin built somewhere else entirely: the checker's whole
-# claim is that it exercises the .so the engine would load, and a checker that statically linked
-# the kernels would be exercising a different binary.
-add_executable(rad-avx-check avx_check.cpp avx_check_rows.cpp avx_cases.cpp)
+# The harnesses dlopen both plugins by path and link neither, so they exercise the exact .so the
+# engine would load, in either build or against a plugin built elsewhere.
+add_executable(rad-avx-check avx_check.cpp avx_check_hand.cpp avx_check_rows.cpp avx_cases.cpp)
 target_include_directories(rad-avx-check PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
 target_link_libraries(rad-avx-check PRIVATE radiance::abi ${CMAKE_DL_LIBS} Threads::Threads)
+# In the source tree the checker also decodes weights with the core's own decoder, an oracle
+# independent of both plugins (avx_check_hand.cpp). One source file, not the core library.
+if(TARGET rad_core)
+  target_sources(rad-avx-check PRIVATE ${CMAKE_SOURCE_DIR}/core/format/encoding.cpp)
+  target_include_directories(rad-avx-check PRIVATE ${CMAKE_SOURCE_DIR}/core)
+  target_compile_definitions(rad-avx-check PRIVATE AVX_CHECK_CORE_DECODER=1)
+endif()
 set_target_properties(rad-avx-check PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${AVX_OUT_DIR})
 
 add_executable(rad-avx-bench avx_bench.cpp avx_cases.cpp)
diff --git a/libavx/README.md b/libavx/README.md
index fc3b5562..b4247bec 100644
--- a/libavx/README.md
+++ b/libavx/README.md
@@ -1,130 +1,274 @@
 # libavx
 
-The conventional op vocabulary in hand-written x86 SIMD, runtime-dispatched by CPU feature.
+The conventional op vocabulary in hand-written x86 SIMD, dispatched at run time by CPU feature.
 
-A third kernel plugin beside `libref` and `libr4d`, for a domain whose only other implementation is
-the reference one, which says in its own header that it is slow. Same seventy-five ops as libref,
-same schemas, same answers to a tolerance — the difference is the instruction stream underneath.
+libavx is a kernel plugin beside `libref` and `libr4d`. libref is the only other host
+implementation, and it is a slow reference. libavx implements all 123 of libref's ops with the
+same schemas and the same answers to a tolerance, the image generator's included (below).
 
     cmake -S libavx -B build-avx -DCMAKE_PREFIX_PATH= && cmake --build build-avx -j4
     K=build-avx/radiance_home/kernels; R=/share/radiance/kernels
     $K/rad-avx-check --ref $R/libref.so --avx $K/libavx.so
     $K/rad-avx-bench --ref $R/libref.so --avx $K/libavx.so --all
 
-It builds on its own exactly as a third party's plugin does -- `find_package(radiance)` and the
-same `rad_add_plugin` -- against an installed radiance, with no ROCm and no core build. A
-full-tree build on x86-64 always builds it: it is where the engine's HOST kernels come from. libref is the
-oracle and the engine refuses to serve on it, so an op the placement runs on the host — the n-gram
-embedding's gather, every step — needs this plugin.
+It builds on its own as a third party's plugin does (`find_package(radiance)` and the same
+`rad_add_plugin`) against an installed radiance, with no ROCm and no core build. A full-tree build
+on x86-64 always builds it, because it supplies the engine's host kernels: libref is the oracle and
+the engine refuses to serve on it, so an op placed on the host (the n-gram embedding's gather,
+every step) needs this plugin.
 
 ## The embedding gather
 
 `embed_lookup_q` over an E4M3 table into bf16 is the one host op a GPU deployment runs, wherever
-`--ngram-placement` leaves the n-gram table for the host gather: in the container's mapping
-(`disk`), or in a locked copy in RAM when no device kernel for the op is loaded (`ram`). Where
-libr4d is loaded, `ram` is a pinned copy its kernel reads over the link and this one does not run.
-Its rows come through `avx_ngram.cpp`, compiled baseline so the process has one of each: a row
-cache shared by every thread (2^19 rows, eight ways, CLOCK), an O_DIRECT read through io_uring for
-each miss, the ranks dividing a call's misses rather than duplicating them, and a reader thread
-that fetches the next prefill chunk's rows while the current one runs. The level's kernel decodes
-the rows: at AVX-512 the call's 256-entry bf16 table sits in eight registers and four `vpermt2w`
-look up 32 codes; below it, one code at a time. The row's layout hook only checks the table's
-encoding — E4M3 with one bf16 scale, or the checkpoint's plain bf16 — and asks for no re-layout,
-because the gather reads the rows from the container file in the layout they are stored in.
+`--ngram-placement` leaves the n-gram table for the host gather: read from the container file
+(`disk`), or a locked copy in RAM when no device kernel for the op is loaded (`ram`). Where libr4d
+is loaded, `ram` is a pinned copy its kernel reads over the link, and this one does not run.
 
-`rad-avx-check` runs the op over a file-backed table with two ranks and the reader racing, at
-every level, and compares every row with the file's bytes.
+The rows come through `avx_ngram.cpp`, compiled baseline so the process has one of each:
 
-## The build is the dispatch
+- a row cache shared by every thread (2^19 rows, eight ways, CLOCK replacement);
+- an O_DIRECT read through io_uring for each miss, with the ranks dividing a call's misses rather
+  than duplicating them;
+- a reader thread that fetches the next prefill chunk's rows while the current one runs.
 
-Every kernel source is compiled **four times** into four object libraries — scalar / AVX /
-AVX2+FMA / AVX-512 — with `AVX_LEVEL` defined and the matching `-m` flags. `avx_vec.h` wraps each
-level in its own inline namespace so the four symbol sets cannot collide; without that the linker
-picks one definition of `avx::row_to_f32` for all four tables and the *scalar* path executes
-AVX-512, which is a SIGILL from the fallback that exists to prevent SIGILLs.
+The level's kernel decodes the rows: at AVX-512 the call's 256-entry bf16 table sits in eight
+registers and four `vpermt2w` look up 32 codes; below it, one code at a time. The row's layout hook
+only checks the table's encoding (E4M3 with one bf16 scale, or the checkpoint's plain bf16) and asks
+for no re-layout, because the gather reads rows from the container file as stored.
 
-`avx_dispatch.cpp` and `avx_registry.cpp` are compiled **baseline, with no `-m` flags**, because
-they are what decides whether the others may run. That is a property of the flags and not of the
-source: a compiler given `-mavx512f` may auto-vectorise anything, so "contains no intrinsics" is
-not the same claim. `-march=native` appears nowhere.
+`rad-avx-check` runs the op over a file-backed table with two ranks and the reader racing, and
+compares every row with the file's bytes: 1000 calls at the highest level the CPU executes and 50 at
+each other level. The reads, the cache and the reader thread are compiled once, at the baseline, so
+the other levels differ only in the decode. Each table is written once per run under a name of its
+own.
 
-Detection is `__builtin_cpu_supports`, not raw CPUID, because the OS has a say — a CPU may
-enumerate AVX-512 while the kernel has left the ZMM state disabled, and using it then faults.
-AVX-512 is checked as the conjunction F + BW + DQ + VL, all four of which the kernels use.
+## Dispatch
+
+Every kernel source is compiled four times into four object libraries (scalar, AVX, AVX2+FMA,
+AVX-512) with `AVX_LEVEL` defined and the matching `-m` flags. `avx_vec.h` puts each level in its
+own inline namespace so the four symbol sets cannot collide; otherwise the linker picks one
+definition of `avx::row_to_f32` for all four tables and the scalar path executes AVX-512.
+
+`avx_dispatch.cpp` and `avx_registry.cpp` decide whether the others may run, so they are compiled
+baseline, with no `-m` flags. That is a property of the flags, not the source: a compiler given
+`-mavx512f` may auto-vectorise anything. `-march=native` appears nowhere.
+
+Detection uses `__builtin_cpu_supports`, not raw CPUID, because the OS must also enable the state:
+a CPU may enumerate AVX-512 while the kernel leaves the ZMM state disabled, and using it then
+faults. AVX-512 requires F + BW + DQ + VL, all of which the kernels use.
 
 `avx_isa_force()` is an exported symbol, not an environment variable, so the checker can sweep all
-four levels and the engine can never reach it.
+four levels and the engine never reaches it.
 
 ## Coverage
 
-75 of 75 ops. Every op `libref` implements, `libavx` implements; `rad-avx-check` fails if that
-stops being true, and reports a row that returns `RAD_E_UNSUPPORTED` separately from one that is
-absent — a row that declines is worse than no row, because the selector resolves to it and the step
-fails at issue rather than at declare.
+Every op `libref` implements, `libavx` implements, so the selector resolves no op of a CPU-only
+deployment to libref: Flash-Next's QSA indexer, the DFlash2 drafters' convolution and the image
+generator included. `rad-avx-check` fails on any missing op, and reports a row that returns
+`RAD_E_UNSUPPORTED` separately from one that is absent: a declining row is worse than none, because
+the selector resolves to it and the step fails at issue rather than at declare.
+
+Every `RAD_E_UNSUPPORTED` a libavx kernel returns, beside libref's answer to the same geometry:
+
+| where | libavx refuses | libref |
+|---|---|---|
+| `attn_paged`, `attn_dense` | head_dim over 2048 | the same (`REF_HD_MAX`) |
+| `attn_local_rel` | a right context; head_dim or left context + 1 over 2048 | the same |
+| `rope`, `qk_norm_rope`, `qsa_block_key` | an unknown `mode`; for `rope`, an unknown `ladder` | the same |
+| `rope` | YaRN with `axial` or a position scale | the same |
+| `rope` | a rotary half-width over 1024 | the same |
+| `had_quant_act_i8`, `had_quant_act_fp8`, `rmsnorm_had_quant_i8`, `gated_had_quant_i8`, `hc_read` | a Hadamard group over 4096 | the same (`REF_HAD_MAX`) |
+| `gdn_conv_prep`, `gdn_conv_update` | a convolution history over 16 | the same |
+| `gdn_recurrent_update` | a `state_form` other than `per_candidate` or `anchor` | the same |
+| `ple_conv`, `causal_conv1d` | a history over 64 | the same |
+| `ngram_ids` | `ngram` over 8 | the same |
+| `moe_gemm`, `moe_gemm_q`, `moe_gemm_q_mod4` | an `a_order` other than `token` or `sorted` | the same |
+| `gemm_nt_q` | parts (`pb1`/`pb2`) over a weight other than MXFP4 and the ParoQuant grids, or on the bias form | the same |
+| `gemm_nt_q` | parts at `w2a8` / `w4a8_asym`; a zero-point grid's bias form; `a_sum` at any other grid; `b_ref` beside a weight other than e2m1 | the same |
+| `attn_prefix_self` | head_dim over 1024; the int8 score form with descales | the same |
+| `all_reduce`, `all_gather` | world size over 1 | serves up to 8 ranks; deliberate, below |
+| `embed_lookup_q` | a file without direct I/O; a bf16 gather in a process without io_uring | reads the table as memory; deliberate, see the gather above |
+
+Everything but the last two rows refuses exactly where libref does, so the selector never
+resolves a geometry to libavx that libref would have served. The per-entry image ops
+(`lane_gather`, `lane_store`, `randn_lanes`, `flow_euler`) check every entry before writing any,
+where libref writes the entries before a bad one; they return libref's code, and refuse (with
+`RAD_E_SHAPE`) the entries libref would read or write past an operand for.
+
+`moe_gemm_q` and `moe_gemm_q_mod4` carry layout hooks for Qwen3.8-Flash-Next's codebook experts
+(`w4nla8h`, `w4nl64a8h`, `w4nl32a8h`, `w5nl64a8h`; `docs/MOE-W4.md`): a view of several planes
+(`codes,table`, `scale,scale.1`) is stored in the joined form of `abi/rad_planes.h`, the bytes
+libref's hooks store, and a selection the `dtype` does not name is refused at declare with
+`RAD_E_DTYPE`, as libref refuses it. At launch both libraries refuse with `RAD_E_DTYPE` a joined
+form of other planes, plain and codebook experts in one call, and a joined scale beside plain codes.
 
 Two things are deliberately narrower than libref and say so at the call site:
 
 - **`all_reduce` / `all_gather` serve world size 1** and refuse anything wider by name. libref's
-  real implementation is a rendezvous over shared mutable state with a barrier and a generation
-  counter, and there is exactly one of it per process; two kernel plugins each carrying their own
-  would be two rendezvous groups for one world, and which one a rank joined would depend on which
-  plugin won selection. libref sits below this plugin in the hierarchy, so a tensor-parallel host
-  deployment resolves the collectives there and everything else here.
-- **The rows carry no `opd_shape`.** libref publishes one for the whole conventional vocabulary and
-  the ABI says an op inside `docs/OPS.md` is describable even when the kernel under test is not.
-  A second copy would be a second set of judgement calls about the same ops.
+  implementation is a rendezvous over shared state with a barrier and a generation counter, one per
+  process; two plugins each carrying one would make two rendezvous groups for one world, and which
+  one a rank joined would depend on selection. libref sits below this plugin in the hierarchy, so a
+  tensor-parallel host deployment resolves the collectives there and everything else here.
+- **The rows carry no `opd_shape`.** libref publishes one for the whole conventional vocabulary,
+  and the ABI makes an op in `docs/OPS.md` describable even when the kernel under test is not. A
+  second copy would be a second set of judgement calls about the same ops.
 
 ## Correctness
 
-`rad-avx-check` opens both plugins with `dlopen` and links neither — the claim is about the `.so`
-the engine would load. It checks four things in order: schema agreement (the loader's own
-`schema_same`, run before any arithmetic, because the loader refuses the *whole* plugin on one
-disagreement), coverage, the numbers, and every ISA level.
+`rad-avx-check` opens both plugins with `dlopen` and links neither, so it checks the `.so` the
+engine would load. It checks, in order: schema agreement (a copy of the loader's `schema_same`, run
+before any arithmetic, because the loader refuses the whole plugin on one disagreement), coverage,
+the numbers, and every ISA level. Each level prints:
 
-    233 checked, 233 passed, 0 failed, 0 declined, 4 skipped, 0 missing.
-    worst rel_l2 = 3.556e-04   [rmsnorm M=3 n=645 bf16 wadd=1]
-    hand-built: 22 checked, 0 failed
+    522 checked, 522 passed, 0 failed, 0 declined, 0 skipped, 0 missing.  worst rel_l2 = 3.556e-04
+    worst case: rmsnorm M=3 n=645 eps=1e-05 dtype=bf16 wadd=1
+    522 rerun on 4 threads, byte for byte
+    hand-built: 198 checked, 0 failed
+    zero rows: 116 ops checked, 0 failed
 
-at every level, against `rad-kbench`'s tolerance table (the worst case at AVX2 is silu_mul's
-4.038e-04 rather than rmsnorm's). Every conversion is
-additionally proven **exhaustively** — all 256 or 65536 bit patterns of each narrow format, in both
-directions, bit-identical to libref including NaN, subnormals and negative zero. That sweep is not
-redundant with the geometry table: a draw of normals reaches none of those patterns, so a
-conversion can be wrong by octaves at the bottom of its range while every geometry still passes.
+against `rad-kbench`'s tolerance table, ids (i32, u32, i64 outputs) exactly; the worst case differs
+per level. Every conversion is also checked exhaustively: all 256 or 65536 bit patterns of each
+narrow format, in both directions, bit-identical to libref including NaN, subnormals and negative
+zero. Normal draws reach none of those patterns, so a conversion can be wrong by octaves at the
+bottom of its range while every geometry passes.
 
-**The four skipped cases are limits of libref's descriptions, not of libavx.**
-`sample_merge_topk`'s shape hook returns `RAD_E_UNSUPPORTED` unconditionally, so it publishes no
-description at all. `gemm_nt_q_bias` at `fp8a16` is declined by name (the bias form takes `a_scale`
-as required and fp8a16 has none). `ngram_ids` describes `vocab_sizes` as normal-filled i64, which
-its own launch then refuses because a vocabulary size must be positive — so that op cannot be
-checked cold until libref's hook describes it as an index fill with a positive range.
+Each case also checks what a value comparison cannot see:
 
-A cold description cannot reach every form of every op, and the **hand-built cases** are the rest:
+- **Guard bytes.** Every operand and scratch buffer carries 64 bytes of a known pattern on each
+  side, checked after the launch, for both plugins. A write past a row's end is otherwise invisible
+  until it lands on something the engine reads.
+- **Inputs unchanged.** Every input and weight must hold its drawn bytes after the launch; a kernel
+  writing into one would corrupt a weight or a shared buffer in the engine.
+- **Something was computed.** A case whose libref output equals what was drawn (all-zero weights,
+  a sampler stage its parameters switch off) fails as vacuous.
+- **Threads.** Every check geometry is below the kernels' OpenMP thresholds, so each case runs a
+  second time with every parallel region forced onto four threads through `avx_par_force` (an
+  exported symbol, like `avx_isa_force`) and must reproduce the serial run byte for byte, as the
+  threading rule in `avx_common.h` promises. `--threads N` changes the team, 0 skips the rerun.
+- **Zero rows.** Each op's first case is described at its row count and at twice it; the extents
+  that change are set to zero and the op launched with its row parameter at 0. It must return
+  `RAD_E_SHAPE` and write nothing, as docs/OPS.md requires and libref does.
+
+A case libref cannot describe or run fails rather than being skipped, because the table is then
+wrong. Two forms libref cannot describe have no table case for that reason: `sample_merge_topk`'s
+packed (id, logit) words and the bias form of `gemm_nt_q` at `fp8a16` (it requires `a_scale`); the
+first is a hand-built case.
+
+The harness draws what libref's descriptions cannot state: integer and 4-bit codes across their
+grid (a weight-scale draw truncates them to zero), weight tables (a MoE layer's experts) like any
+weight, an operand flagged `RAD_OPD_F_IDX_PREFIX` (a routing histogram's offsets) as a
+non-decreasing prefix array, and an E8M0 exponent plane as the power of two nearest each draw.
+Sampler rows are its own too: libref describes them as random requests (`RAD_FILL_SAMPLE_PARAMS`,
+over a `RAD_OPD_F_IDX_HISTORY` history), which rad-kbench draws; the harness writes each row as a
+request with every stage switched on, over a history that repeats itself.
+
+A cold description cannot reach every form of every op, and the hand-built cases cover the rest:
 operand views and index patterns a description does not draw, and the forms an optional operand
-selects. `dflash_select`'s are the sharpest example: a description draws its codebooks as weights,
-at 0.02, where the pairwise term is a thousandth of the unary score and never decides a pick — so
-the walk is checked cold and the form it computes is checked by hand, with unit-scale codebooks, once
-with `hp` and once without.
+selects. For example, a description draws `dflash_select`'s codebooks as weights at 0.02, where the
+pairwise term is a thousandth of the unary score and never decides a pick; so the walk is checked
+cold and the form it computes is checked by hand, with unit-scale codebooks, once with `hp` and
+once without. Others cover formats libref does not describe: MXFP4 weights with e8m0 exponents
+(one of them 0xFF, NaN), ParoQuant's multi-part GEMM, an fp8 KV cache read with per-head descales,
+4-bit experts, activation scale grids finer than the weight's, packed-code stores, and
+`gdn_recurrent_update`'s anchor state form, both against libref and against itself: over four steps
+the anchor replay must give the per-candidate form's `o` bit for bit, which is what lets greedy
+speculation emit the same text as greedy decode.
 
-## The measurement platform
+The codebook experts reach both libraries in the joined form, which no description draws. Their
+cases draw canonical planes (codes over the whole code range, the shipped w4nl and w5nl tables,
+E4M3 or bf16 scales, the fixed 2^-13 level), store them through each library's own layout hooks,
+and run each library on its own stored bytes, every form at four geometries that reach each decode
+at each level: AVX-512's lines, the chunk decode, the generic one; the fused and the panel forms;
+narrower classes, a dropped slot, a partial row block and odd widths. Besides the checks above,
+both libraries must store the same bytes and each unrelayout give the planes back; libref over the
+stored form must equal libref over the logical form rad-kbench and the oracle pass, bit for bit;
+and both must agree with the core's own decoder (`core/format/encoding.h`, compiled into the
+checker in the source tree): the weight decoded with its Hadamard undone against the activation
+rotated back, summed in double. The hooks of both libraries must refuse the same mismatched
+selections with the same code.
 
-The numbers below are one thread on a **Ryzen 9 9950X3D** (Zen 5, 16 cores, 128 MiB L3), taken with
-`rad-avx-bench --peak` rather than quoted from a data sheet. All four ISA levels execute natively on
-that part, so all four are measured and none is inferred. Re-run the commands above to get the
-figures for another one; the ratios are what the rest of this document reasons about.
+The QSA indexer's hand-built cases are batches a description cannot draw: `cu` not starting at 0
+and rows no sequence holds, -1 pages and a sequence whose blocks are all dead, the score plane as a
+column slice of its declared width, block keys in the KV cache's rank, ring wrap in the tail store
+and the work list, and libr4d's eight few-live selection rows, held to the selection rule itself as
+well as to libref. Their outputs start as a sentinel, so an element only one side writes shows.
+
+### Weights of several planes
+
+A weight joined over several planes (docs/OPS.md, Weights of several planes; abi/rad_planes.h) has
+no description, so its cases are hand-built: canonical planes with codes across their range, real
+scales, zeros at both ends of the code range; both libraries' layout hooks must join them into the
+same bytes and invert them back; both launch over the joined form. Each GEMM case is also held to
+an answer neither library computes: in radiance's own tree the checker compiles in the core's
+affine decoder (core/format/encoding.cpp), dequantises the planes and the activation, and takes a
+double product. The cases:
+
+- `logits_gemm` over `fp8_e4m3*bf16[128x128]` (N = 200, K = 320: a partial block row and column)
+  and `i8*bf16[1x128]` heads, M 1, 5 and 9, bf16 and f32 activations; `logit_rerank` over both,
+  candidates across the shard and both block rows.
+- `hc_read` (inject and the final mixer) and `mtp_enter` over E4M3 rows with f32 scales per 128
+  columns and per quarter row, bf16 and f32.
+- `gemm_nt_q` at `w2a8`, `w4a8_asym`, `w4a16_asym`, `w5a16`, `w4a8i8_asym` and `w5a8i8`, M 1,
+  13 and 17 (the small-M paths' blocks and the decoded driver), N not a multiple of 6 or 16, the
+  ParoQuant grids in two and three parts; a plain `b_scale` at a grid is refused by both.
+- The hooks' refusals, pinned for both libraries: a u4 head, a transformed head, a grid's scale
+  and zero over the wrong codes, at the wrong group, out of order, or at a grid without a zero.
+
+At every level the heads' f32 logits agree with libref to 4e-7 and the grids' bf16 outputs to 5e-9
+(most of them byte for byte); against the core decoder the logits are within 4e-7 and the
+grids within 2e-3, their bf16 rounding.
+
+## Checking another host library
+
+`rad-avx-check` checks any host kernel library against libref, without a GPU and without the
+engine:
+
+    rad-avx-check --ref /share/radiance/kernels/libref.so --avx path/to/mylib.so
+
+A library not named `libavx` is checked as a host library rather than held to libavx's contract:
+
+- Schemas must agree with libref's wherever both declare an op, since the loader refuses the
+  plugin otherwise. Ops libref does not declare have no oracle and are not checked.
+- Coverage is reported: the libref ops the library has no host row for are listed, and every table
+  and hand-built case for them is left out. A row that returns `RAD_E_UNSUPPORTED` still fails, for
+  the reason above.
+- Each case runs on the row the selector would choose: the host row whose constraints the
+  geometry meets, highest priority first. A case no row admits is counted, not failed. Device rows
+  are never launched; the checker passes host pointers.
+- The ISA sweep needs `avx_isa_force`, and the threaded rerun `avx_par_force`. Without them the
+  library is checked once, at the level it picks for itself, on the thread count it picks.
+- The file-backed gather and its init are libavx's own and do not run.
+
+Everything else applies unchanged: the tolerances, guard bytes, unchanged inputs, exact ids, the
+vacuity check and the exhaustive conversions (when the library has `cast`).
+
+## Measurement platform
+
+The numbers below are one thread on a Ryzen 9 9950X3D (Zen 5, 16 cores, 128 MiB L3), measured with
+`rad-avx-bench --peak`. All four ISA levels execute natively on that part. Re-run the commands above
+for another CPU; the ratios are what the rest of this document reasons about.
 
     FMA scalar     29.3 GFLOP/s      triad L1     129 GB/s   (48 KiB)
     FMA avx       135.0 GFLOP/s      triad L2     157 GB/s   (1.5 MiB)
     FMA avx2      175.0 GFLOP/s      triad DRAM    42 GB/s   (768 MiB)
     FMA avx512    351.4 GFLOP/s
 
-The avx2 and avx512 figures are exactly 2 FMA/cycle at 8 and 16 lanes; avx (no FMA) reaches 4
-vector FP ops/cycle on Zen 5's four FP pipes. The triad counts three arrays — two read, one
-written — and does not count a read-for-ownership the compiler may have elided.
+The avx2 and avx512 figures are 2 FMA/cycle at 8 and 16 lanes; avx (no FMA) reaches 4 vector FP
+ops/cycle on Zen 5's four FP pipes. The triad counts three arrays (two read, one written) and not a
+read-for-ownership the compiler may have elided.
+
+`--peak --threads N` measures the memory ceilings on N threads, and adds a read-only stream, the
+ceiling of an op that only reads (the QSA indexer's keys). Each eight-core complex of this part
+reaches memory through its own link, narrower for writes than for reads, so the triad hardly moves
+with threads while the read stream does:
+
+    read DRAM     39 GB/s  1 thread     53-57 GB/s  8 threads (cores 0-7)     64-66 GB/s  16 threads
+
+The ranges are run-to-run spread on a machine shared with other work.
 
 ## Conversion, MB/s of source bytes
 
-`rad-avx-bench --cvt`, through the plugin's own `cast`.
+`rad-avx-bench --cvt`, through the plugin's own `cast`, same platform.
 
 | pair | scalar | avx | avx2 | avx512 | libref |
 |---|---|---|---|---|---|
@@ -137,14 +281,14 @@ written — and does not count a read-for-ownership the compiler may have elided
 | f32 → i8 | 4247 | 10699 | 99319 | 164889 | 1071 |
 | i8 → f32 | 12088 | 11182 | 17324 | 20526 | 384 |
 
-f16 is software below AVX2 because F16C is its own CPUID bit that arrived one generation after
-AVX — a level called `avx` that required it would fault on the machines it exists for.
+f16 is software below AVX2 because F16C is a separate CPUID bit that arrived a generation after
+AVX; a level called `avx` that required it would fault on the machines it exists for.
 
 ## Per op, at model shapes
 
-`rad-avx-bench`, microseconds per launch, median of 7 reps, **one thread**, cache-warm. Geometry is
-a ~1.5B dense model: n_embd 2048, n_ff 5632, n_vocab 32000, 16 heads of 128. M = 1 is decode, 64 a
-speculative verify window, 512 a prefill chunk.
+`rad-avx-bench`, microseconds per launch, median of 7 reps, one thread, cache-warm, same platform.
+The geometry is a ~1.5B dense model: n_embd 2048, n_ff 5632, n_vocab 32000, 16 heads of 128. M = 1
+is decode, 64 a speculative verify window, 512 a prefill chunk.
 
 | op | geometry | libref | scalar | avx | avx2 | avx512 | rate (avx512) |
 |---|---|---|---|---|---|---|---|
@@ -162,75 +306,310 @@ speculative verify window, 512 a prefill chunk.
 | sample_topk | M=1 n_vocab=32000 | 2287 | 1067 | 174 | 139 | **77** | |
 | attn_paged | q_len=1 hd=128 gqa=4 ctx=2048 | 6.73 | 1.53 | 1.18 | 1.11 | **0.93** | |
 
-**How to read this.** The libref column is a statement about libref, which is a scalar loop with a
-per-element dtype switch and says so in its own header; the ratio is what says an op is wired at
-all. The rate column against the ceilings above is the statement about libavx:
+The libref column is about libref, a scalar loop with a per-element dtype switch; the ratio only
+shows an op is wired. The rate column against the ceilings above is what describes libavx:
 
-- `gemm_nt` at prefill reaches **188 GFLOP/s against a 351 GFLOP/s ceiling — 54%**.
-- `sample_argmax` reaches **111 GB/s against a 129 GB/s L1 ceiling — 86%**; it is a single pass
-  over the logits and is essentially at the memory system.
-- `softmax` at 41 GB/s and `logits_gemm` at 24 GB/s are **DRAM-bound, not flop-bound** —
-  `logits_gemm`'s weight is 128 MiB in bf16 and fits in no cache, so whatever the flop count says
-  it is a memory benchmark wearing a GEMM's name, and 24 against a 42 GB/s single-thread triad is
-  the honest way to read it.
-- `silu_mul` at 23 GB/s and `rmsnorm` at 48 GB/s are the two that have room left.
+- `gemm_nt` at prefill reaches 188 GFLOP/s of a 351 GFLOP/s ceiling (54%).
+- `sample_argmax` reaches 111 GB/s of a 129 GB/s L1 ceiling (86%): a single pass over the logits,
+  close to the memory system's limit.
+- `softmax` at 41 GB/s and `logits_gemm` at 24 GB/s are DRAM-bound. `logits_gemm`'s weight is
+  128 MiB in bf16 and fits no cache, so it is a memory benchmark, and 24 against a 42 GB/s
+  single-thread triad is the comparison that applies.
+- `silu_mul` at 23 GB/s and `rmsnorm` at 48 GB/s have room left.
 
-These are **single-thread** numbers throughout. The plugin parallelises over the outer dimension
-with OpenMP above a work threshold; the bench pins one thread because that is what ranks a kernel
-change, and a 32-thread number would be measuring the memory controller.
+All numbers are single-thread. The plugin parallelises over the outer dimension with OpenMP above a
+work threshold; the bench pins one thread because that ranks a kernel change, while a 32-thread
+number measures the memory controller.
 
-## Why the code is shaped the way it is
+### The codebook experts
 
-Each choice below is measured rather than reasoned about, and the ones that did not pay are recorded
-beside the code, because a null result is worth as much as a win.
+`rad-avx-bench --moe [--moe-dtype LIST] [--threads N]` runs `moe_gemm_q` over Qwen3.8-Flash-Next's
+experts at the model's geometry on one rank: 512 experts in two parity tables at top-k 10, gate_up
+`[1280, 2560]` and down `[2560, 640]`, 1.3 GB stored through libavx's own layout hooks. Each call
+draws a new routing, so a decode step reads its experts from DRAM as a served one does. GB/s counts
+the codes and scales of the experts a call routes to; GFLOP/s is `2 M top_k N K`. One thread on a
+core that measured 347 GFLOP/s (FMA, avx512) and a 39.6 GB/s DRAM triad in the same session;
+microseconds per call:
 
-**The register block is swept, not reasoned about** (`gemm_nt` bf16, M=512 N=2048 K=2048):
+| dtype | M | proj | libref | scalar | avx | avx2 | avx512 | rate (avx512) |
+|---|---|---|---|---|---|---|---|---|
+| w4nl64a8h | 1 | gate_up | 52215 | 17166 | 14371 | 1706 | **591** | 28.6 GB/s |
+| w4nl64a8h | 1 | down | 25558 | 8655 | 7351 | 869 | **392** | 21.5 GB/s |
+| w4nl64a8h | 4 | gate_up | 209824 | 67939 | 56762 | 6738 | **2427** | 27.1 GB/s |
+| w4nl64a8h | 4 | down | 100874 | 33854 | 28751 | 3426 | **1523** | 21.6 GB/s |
+| w4nl64a8h | 64 | gate_up | | | | 73779 | **32050** | 19.4 GB/s |
+| w4nl64a8h | 64 | down | | | | 37662 | **18215** | 17.0 GB/s |
+| w4nl64a8h | 2048 | gate_up | | | | 1109980 | **665963** | 201.5 GFLOP/s |
+| w4nl64a8h | 2048 | down | | | | 557618 | **293857** | 228.4 GFLOP/s |
+| w4nla8h | 1 | gate_up | 49967 | 18048 | 15348 | 1629 | **538** | 31.4 GB/s |
+| w4nla8h | 2048 | gate_up | | | | 1100388 | **662523** | 202.6 GFLOP/s |
+| w4nl32a8h | 1 | gate_up | 54194 | 17841 | 15042 | 1840 | **696** | 25.0 GB/s |
+| w4nl32a8h | 2048 | gate_up | | | | 1196490 | **668847** | 200.7 GFLOP/s |
+| w5nl64a8h | 1 | gate_up | 51501 | 18977 | 16711 | 3895 | **1202** | 17.5 GB/s |
+| w5nl64a8h | 2048 | gate_up | | | | 1149541 | **694854** | 193.2 GFLOP/s |
+
+On eight threads (eight cores, an 8-thread DRAM triad of 45.8 GB/s) the served form reads 54.4 /
+53.6 GB/s at M = 1 (gate_up / down) and 55.1 / 53.4 at M = 64, and computes 1529 / 1607 GFLOP/s at
+M = 2048, 55-58% of eight cores' FMA peak. Decode is then at the memory system's limit: the triad
+also writes, and the read stream is faster than it.
+
+- **Decode on one thread** reaches 72% of the triad on gate_up, and the decode is what limits it
+  (eight vpermps and seven shifts per 128 codes): cache-warm, the same call reads about 30 GB/s.
+  down's rows are 320 bytes, so the per-row work (scales, horizontal sums, stores) weighs more. At
+  M = 64 most experts take one or two rows, and each 64-row item is mostly overhead around a short
+  decode.
+- **u5 decodes at half u4's rate**: a code straddles bytes, so each sixteen take a broadcast, a
+  vpshufb, a variable shift and a two-table vpermt2ps. w5nl64a8h is not the served form.
+- **AVX2** decodes through two 8-entry vpermps and a blend per eight codes; it is 2-3x the AVX-512
+  time on one thread and the same on eight, where both wait on DRAM.
+- **Prefill** reaches 58-66% of the FMA peak, gemm_nt's share: the 3 x 8 register block over an
+  L2-resident panel decoded once per 64 rows, one horizontal sum per output.
+- The scalar and AVX levels decode a row through the table and take the generic dot; they are the
+  correctness baselines.
+
+### The QSA indexer and DFlash2's convolution
+
+Qwen3.8-Flash-Next's indexer (`arch/qwen4exp_fp8`: 4 heads of 128, ratio 4, topk 512, a 7-row
+ring) over 8K, 64K and 200K tokens of context, with every block complete and every query past
+them; and the 27B DFlash2 drafter's convolution (`arch/common/rad_block_dflash2.h`: n_embd 5120,
+2 taps, groups of 16, a 16-row block). One thread, cache-warm, as above; `blocks` is context / 4.
+
+| op | geometry | libref | scalar | avx | avx2 | avx512 | rate (avx512) |
+|---|---|---|---|---|---|---|---|
+| qsa_score | M=1, 8K (2048 blocks) | 896 | 269 | 41.6 | 34.0 | **31.4** | 17.2 GB/s |
+| qsa_score | M=1, 64K | 7938 | 2159 | 341 | 296 | **225** | 19.2 GB/s |
+| qsa_score | M=1, 200K | 24222 | 6662 | 1061 | 944 | **724** | 18.2 GB/s |
+| qsa_score | M=4, 200K | 88009 | 23875 | 2277 | 2100 | **1400** | 146 GFLOP/s |
+| qsa_score | M=2048, 64K | 14.9 s | 3.92 s | 313 ms | 322 ms | **184 ms** | 187 GFLOP/s |
+| qsa_select | M=1, 8K | 6.19 | 6.33 | 5.99 | 1.69 | **1.64** | 10.0 GB/s |
+| qsa_select | M=1, 200K | 339 | 135 | 135 | 23.0 | **21.0** | 19.1 GB/s |
+| qsa_select | M=2048, 64K | 241 ms | 130 ms | 111 ms | 36.4 ms | **29.9 ms** | 9.0 GB/s |
+| qsa_tail_store | 4 sequences, decode | 1.03 | 0.21 | 0.15 | 0.12 | **0.10** | 20.0 GB/s |
+| qsa_work | 4 sequences, decode | 4.05 | 0.83 | 0.62 | 0.49 | **0.41** | 20.1 GB/s |
+| qsa_work | 2048 rows, 512 blocks | 467 | 93.0 | 67.5 | 51.8 | **40.8** | 25.7 GB/s |
+| dflash_conv | T=16 | 538 | 41.6 | 27.1 | 13.4 | **8.28** | 44.5 GB/s |
+| dflash_conv | T=64 | 2156 | 166 | 109 | 55.0 | **37.0** | 38.2 GB/s |
+
+The indexer is the only decode op that grows with context, and at decode its keys (256 bytes a
+block, 12.8 MB at 200K) fit this part's L3 though no real step leaves them there. So decode is also
+measured the way it runs: on a team (`--threads`), with the operands flushed from every cache
+before each launch (`--cold`), against the read-only ceiling of the same team. Eight threads on
+cores 0-7:
+
+| op | geometry | avx512 | rate | ceiling |
+|---|---|---|---|---|
+| qsa_score | M=1, 8K | 14.0 | 38.5 GB/s | 53-57 GB/s read |
+| qsa_score | M=1, 64K | 84.7 | 51.1 GB/s | 53-57 GB/s read |
+| qsa_score | M=1, 200K | 213 | 62.0 GB/s | 53-57 GB/s read |
+| qsa_score | M=4, 200K | 278 | 49.7 GB/s | 53-57 GB/s read |
+| qsa_score | M=2048, 64K | 25.3 ms | 1360 GFLOP/s | 2680 GFLOP/s FMA |
+| qsa_select | M=4, 200K | 47.8 | 33.5 GB/s | |
+| qsa_select | M=2048, 64K | 4.94 ms | 54.4 GB/s | |
+
+On all 16 cores (0-15), with another job on the machine, decode over 200K tokens takes 219 us at
+M=1 (60 GB/s of a 64-69 GB/s read ceiling) and 277 us at M=4, no faster than on one complex: the
+stream is at the memory's limit either way. The prefill chunk takes 13.7 ms (2.5 TFLOP/s).
+
+- `qsa_score` at decode streams the keys at or near the read ceiling from 64K up, with the software
+  prefetch 32 blocks ahead (a block table need not be in page order, so the hardware prefetcher
+  cannot follow it). At M=4 a block's 16 dot rows are compute the stream does not fully hide. At 8K
+  a launch moves 0.5 MB, too little for the stream to reach its rate. One thread reaches 44% of the
+  FMA ceiling at M=4 and 56% at prefill: each (row, block group) adds a 45-instruction lane
+  reduction and the accumulators' setup to its 128 FMAs.
+- `qsa_select` is linear in the blocks, under 1 ns a block on one core, a row a thread; at decode a
+  row is one thread's work, a tenth of the scoring before it.
+- `qsa_tail_store` and `qsa_work` copy at most a few hundred key rows a step through f32, as libref
+  does, so a key lands with the bits libref's would.
+- `dflash_conv` is bound by instructions, not by L2 (152 GB/s): the bf16 store rounds in software,
+  RTNE with the ABI's NaN rule, about a third of each vector's instructions.
+
+### Weights of several planes, at model size
+
+The decode step's largest reads are an lm head and, in the 2-bit draft heads and ParoQuant's int4
+and int5 linears, zero-point grids, all stored joined (docs/OPS.md). At M = 1 to 8 they are memory
+benchmarks, so `rad-avx-bench --joined --threads 16` times them on every core (pinned to cores
+0-15), each weight over a working set past the 128 MiB L3 (copies of a weight under 1 GiB), beside
+a read-only stream of 1 GiB on the same threads, measured before and after the kernels and the
+better reading kept: 70.5 GB/s in the run below (the triad: 50). Best of 7, milliseconds, from the
+quietest of several runs on a machine shared with other work.
+
+| op | geometry | M = 1 | M = 4 | M = 8 | M = 64 |
+|---|---|---|---|---|---|
+| logits_gemm | fp8_e4m3*bf16[128x128] 248320x5120 (1.27 GB) | 19.2 (66 GB/s) | 21.2 | | 70 (2.3 TFLOP/s) |
+| logits_gemm | i8*bf16[1x128] 248320x5120 (1.29 GB) | 17.9 (72 GB/s) | 19.0 | | 83 (2.0 TFLOP/s) |
+| logits_gemm | i8*bf16[1x128] 248320x2560 (0.65 GB) | 10.2 (63 GB/s) | 9.7 | | 34 (2.4 TFLOP/s) |
+| gemm_nt_q | w2a8 248320x5120 (0.35 GB) | 5.2 (68 GB/s) | 5.7 | 6.1 | |
+| gemm_nt_q | w4a16_asym 34816x5120, 2 parts (93 MB) | 1.8 (51 GB/s) | 1.5 | 2.7 | |
+| gemm_nt_q | w4a16_asym 5120x17408 (47 MB) | 1.0 (46 GB/s) | 1.3 | 1.4 | |
+| gemm_nt_q | w5a16 34816x5120, 2 parts (115 MB) | 2.6 (44 GB/s) | 4.6 | 5.5 | |
+| gemm_nt_q | w5a16 5120x17408 (58 MB) | 1.3 (45 GB/s) | 1.5 | 2.6 | |
+| gemm_nt_q | w4a8i8_asym / w5a8i8 34816x5120, 2 parts, M = 256 | | | | 53 / 47 (1.7 / 1.9 TFLOP/s) |
+
+Against the read-only ceiling:
+
+- **The lm heads run at 85-102% of it at M = 1 and 4.** A joined head goes through the GEMM's
+  register-blocked driver with a row decoder in its packing step (E4M3 by avx_vec.h's bit
+  reconstruction, int8 by widening, then one multiply by the covering scale), so the codes are
+  widened six rows at a time into L2 and never in memory. At M = 64 it is compute-bound at 2.0-2.4
+  TFLOP/s, 36-43% of the 5.6 TFLOP/s 16-core FMA peak: a decoded weight's M block is the whole of
+  M, so the head is decoded once, and the 1.3 MiB activation panel is read again for every six head
+  rows.
+- **The 2-bit head runs at 96% of it at M = 1 and 81% at M = 8** on the integer path: code planes
+  in registers against the activation in plane order, one vpdpbusd a plane where AVX512-VNNI is
+  present (vpmaddubsw, vpmaddwd and an add where it is not).
+- **ParoQuant int4 and int5 run at 62-72% of it at M = 1** (int4 reached 92-99% in a quieter run),
+  and fall to 30-50% by M = 8: every 16 codes decode in registers (int5 by pdep) and meet M
+  activation rows with one load and one FMA each, two weight rows sharing each load at AVX-512, so
+  from M = 4 the activation loads outnumber the rest of the loop.
+- **The prefill grids are compute-bound** at 1.7-1.9 TFLOP/s on the decoded driver, a third of the
+  FMA peak: the codes are widened to f32 rather than multiplied as int8.
+
+On a busy machine each figure moves by up to 2x between runs; repeat before comparing two.
+
+## Image generation
+
+Qwen-Image 2.1 (`arch/qwenimage21`) generates on the host backend with `--kernels libavx` alone,
+no reference library loaded: engine_e2e_test's `qwen_image_generates_on_libavx_alone_as_on_libref`
+serves a tiny synthetic pipeline converted to a bf16 and a block-fp8 container, with and without
+guidance. A seed repeats its PNG byte for byte, and the picture agrees with libref's at 51-53 dB
+PSNR (another seed: 15 dB). The core needed no change for it.
+
+The generator's 18 ops (`avx_gen.cpp`, `avx_gen_attn.cpp`) round where libref rounds, which is
+where the upstream bf16 model stores a tensor. The sampler (`randn_lanes`, `flow_euler`), the gated
+residual, the lane copies, the shortcuts, `chan_affine`, `timestep_embed` and `to_rgba8` are libref's
+bit for bit, held to zero error by the hand-built cases: a seed's noise and every later sampler
+state are the same on both host libraries. `flow_euler` keeps libref's two roundings where it
+multiplies and adds (`keep`: this plugin is built with `-ffp-contract=fast`). The norms, the
+convolution and the attention reduce in other orders and are held to the tolerance table.
+
+- **`conv2d_nhwc`** is GEMMs over bands of patch rows. The weight is re-laid once a launch as
+  `[cout][kh][kw][cin]`, so a pixel's patch row is k * k channel runs copied back to back; a band
+  of output rows (at least 8 Mi patch elements and eight times the weight) is one `gemm_nt_into`
+  call, the bf16 outer-product path where the CPU has AVX512_BF16. A 1 x 1 layer reads x in place;
+  a layer narrower than one 48-column panel (the decoder's last, 4 channels) computes y^T so the
+  threads split the pixels.
+- **`attn_prefix_self`** is flash attention over each (entry, kv head)'s keys, packed once a launch
+  into 64-key tiles (the prefix from the paged cache, then the own rows), for kv heads in groups of
+  at most 64 MiB of tiles. A task is 32 query positions of one kv head; S = Q K^T and O += P V are
+  `vdpbf16ps` broadcasts against the tile (P rounded to bf16, as attn_dense's bf16 form and
+  PyTorch's CPU flash attention do) on AVX512_BF16 parts and f32 FMAs elsewhere. The int8 score
+  form computes libref's exact integer dot products (codes of at most 127 are exact in bf16).
+- `qk_norm_rope` gained libref's `gptj_blocks` (the DiT's adjacent pairs, in whole vectors) and
+  `imrope` (the text encoder's) modes, which Qwen-Image needs.
+
+One thread, microseconds per launch, the model's widths (`rad-avx-bench --op `; libref is not
+timed past 2e10 FLOP). The bf16 dot-product ceiling is twice the f32 FMA one, about 700 GFLOP/s a
+core at AVX-512:
+
+| op | geometry | libref | scalar | avx | avx2 | avx512 | rate (avx512) |
+|---|---|---|---|---|---|---|---|
+| conv2d_nhwc | 3x3 1152->1152, 1024 px | - | 1530639 | 401811 | 242491 | **48957** | 500 GFLOP/s |
+| conv2d_nhwc | 3x3 576->576, 4096 px | - | 1470642 | 350498 | 205767 | **39526** | 619 GFLOP/s |
+| conv2d_nhwc | 3x3 up 2 288->288, 16384 px | - | 1465933 | 343962 | 201592 | **40163** | 609 GFLOP/s |
+| conv2d_nhwc | 3x3 144->144, 65536 px | - | 1506985 | 349133 | 194474 | **41631** | 588 GFLOP/s |
+| conv2d_nhwc | 3x3 144->4, 262144 px | 1066406 | 192806 | 68558 | 45259 | **35668** | 76 GFLOP/s |
+| conv2d_nhwc | 1x1 1152->3456, 1024 px | 3259307 | 497989 | 113977 | 63326 | **13314** | 612 GFLOP/s |
+| attn_prefix_self | 1024 rows + 256 prefix, 32 x 128, bf16 | - | 736629 | 171322 | 169915 | **48335** | 444 GFLOP/s |
+| attn_prefix_self | the same, int8 scores | - | 1024020 | 224256 | 198774 | **66715** | 322 GFLOP/s |
+| attn_prefix_self | 4096 rows + 256, 4 x 128, bf16 | - | 1243625 | 287250 | 282482 | **80237** | 455 GFLOP/s |
+| ln_mod | 1024 x 4096 | 53696 | 3490 | 1909 | 1347 | **879** | 19.1 GB/s |
+| gate_add | 1024 x 4096 | 48096 | 2974 | 2105 | 1444 | **991** | 25.4 GB/s |
+| ln_mod_quant_fp8 | 1024 x 4096, gated | 120492 | 28441 | 23452 | 5227 | **3267** | 9.0 GB/s |
+| qk_norm_rope | gptj_blocks, 1024 x 64 heads of 128 | 83241 | 9851 | 4963 | 3851 | **3078** | 10.9 GB/s |
+| l2norm_chan | 262144 px x 144, silu | 534042 | 100513 | 50344 | 34219 | **23405** | 6.5 GB/s |
+| d2s_add | 576 -> 288, 512 x 512 out | 174944 | 47387 | 42418 | 34430 | **29654** | 12.7 GB/s |
+
+- The convolutions reach 70-88% of the bf16 dot-product ceiling at AVX-512 and 58-70% of the f32
+  FMA one at AVX2. The 4-channel output layer is f32 dot products over 1296-long patch rows (24% of
+  the FMA ceiling); it is 0.06% of the decoder's FLOPs.
+- The attention reaches 64% of the bf16 ceiling: the softmax between the two products costs about
+  a fifth of a tile at head width 128. The int8 rows above draw their key scales as unit normals,
+  so the running maximum moves in most tiles; a model's moves rarely.
+- The row ops are not bandwidth-bound: each rounds its row through bf16 two or three times in L1
+  (the stores libref models), and l2norm_chan divides and takes an exponential per element.
+
+16 threads (`--threads 16`, the 16 cores pinned; other work was running on the machine,
+so these vary by about 15%):
+
+| op | geometry | avx512 | avx2 |
+|---|---|---|---|
+| conv2d_nhwc | 3x3 at 576, 1152, 288 (up 2) | 3.7-4.1 TFLOP/s | 0.48-0.55 TFLOP/s |
+| conv2d_nhwc | 3x3 144->144 at the picture's resolution | 3.1-3.9 TFLOP/s | 0.39 TFLOP/s |
+| conv2d_nhwc | 1x1 1152->3456 | 6.3 TFLOP/s | 0.71 TFLOP/s |
+| attn_prefix_self | bf16 scores, 1024 and 4096 rows | 4.4-5.9 TFLOP/s | 1.5-1.8 TFLOP/s |
+| attn_prefix_self | int8 scores | 3.7-4.4 TFLOP/s | 1.4-1.5 TFLOP/s |
+| gemm_nt | the DiT's gate_up, bf16, M 1024 | 5.2 TFLOP/s | 0.64 TFLOP/s |
+| gemm_nt_q | the same, fp8a8 (block fp8) | 0.31-0.42 TFLOP/s | 0.26 TFLOP/s |
+| ln_mod, gate_add | 1024 x 4096 | 92-101 GB/s | |
+| ln_mod_quant_fp8, qk_norm_rope | 1024 x 4096 | 33-35 GB/s | |
+
+At AVX2 the convolution and the bf16 GEMM run on the generic driver, which at large M forks one
+parallel region per 6- to 16-row block of A: it is a decode-shaped loop, and why their 16-thread
+rate there is a fraction of one thread's times sixteen.
+
+**Seconds per denoising step and per image, this machine.** A DiT step is 32 blocks of linears
+(13.96 GFLOP a latent row), the attention over the conditioning and the image's rows, and the row
+ops (about 2.5 ms a block at 1024 rows). The decoder is about 4.3 TFLOP at 512 x 512 and 17 TFLOP
+at 1024 x 1024, plus a few GB of row passes. Estimated from the 16-thread rates above with a 256-key
+conditioning and no guidance (guidance doubles the steps' cost):
+
+| picture | container | linears | attention | step | 40 steps + condition + decode |
+|---|---|---|---|---|---|
+| 512 x 512 (1024 rows) | bf16 | 14.3 TFLOP, 2.8 s | 0.7 TFLOP, 0.15 s | **3.0 s** | **about 2 minutes** |
+| 1024 x 1024 (4096 rows) | bf16 | 57 TFLOP, 11 s | 9.3 TFLOP, 1.9 s | **13 s** | **about 9 minutes** |
+| 512 x 512 | block fp8 | 14.3 TFLOP, 40 s | 0.2 s | **40 s** | 27 minutes; Turbo's 8 steps 5.5 |
+| 1024 x 1024 | block fp8 | 57 TFLOP, 160 s | 2.3 s | **162 s** | 1.8 hours; Turbo's 8 steps 22 |
+
+The fp8 rows are `gemm_nt_q`'s fp8a8 rate, a twelfth to a seventeenth of the bf16 GEMM's here:
+its generic driver widens each fp8 weight row to f32 again for every 16-row block of the
+activation. With a bf16-pair path for block fp8 the fp8 container would cost about what the bf16
+one does. The decoder takes about 1.3 s at 512 x 512 and 5 s at 1024 x 1024, the condition (the
+8B text encoder and the DiT over about 100 prompt tokens) about 0.6 s in bf16 and 8 s in fp8.
+
+## Design choices
+
+Each choice below was measured on the platform above. The variants that did not pay are recorded
+beside the code.
+
+**Register block** (`gemm_nt` bf16, M=512 N=2048 K=2048; `avx_gemm.cpp`):
 
     AVX-512, 32 ZMM   4x4 23.2 ms   4x6 22.1 (chosen)   6x4 24.2   8x4 23.8   8x2 35.2   12x2 34.1
     AVX2/AVX, 16 YMM  3x3 34.4 ms   2x6 30.7 (chosen)   2x5 31.9   2x4 34.8   3x4 58.4   4x3 58.1
 
-Two things in that table matter more than the choice. The **cliff**: 3×4 and 4×3 at AVX2 are 58 ms
-against 31–34 around them, because 12 accumulators plus 3–4 A vectors plus one B is 16–17 live in a
-16-register file, and the spill lands *inside* the k loop. And **wider in N beat wider in M at equal
-arithmetic intensity** — 2×6 and 3×3 both load 8 vectors, for 12 and 9 FMAs, intensity 1.5 either
-way, and 2×6 is 11% faster. Nothing about the flop count predicts that.
+3×4 and 4×3 at AVX2 fall to 58 ms against 31-34 around them: 12 accumulators plus 3-4 A vectors
+plus one B is 16-17 live registers in a 16-register file, and the spill lands inside the k loop.
+Wider in N beats wider in M at equal arithmetic intensity: 2×6 and 3×3 both load 8 vectors, for 12
+and 9 FMAs (intensity 1.5 either way), and 2×6 is 11% faster.
 
-**NULL RESULT — cache-blocking the A panel is worth 6% on this part**, not the several-fold the
-traffic argument predicts. Swept: 128 KiB 26.0 ms, 256 KiB 23.4, 1 MiB 24.0, 4 MiB 25.4, 16 MiB
-25.4, unblocked 25.0; and at M=64 blocking is *worse* (2.91 against 2.85). The reason is the part:
-128 MiB of L3, so the traffic the blocking removes is served at L3 speed and not DRAM's. Kept,
-because it is never much worse and is the real fix on a part with 8 MiB of L3 — but it is worth six
-percent where there is this much cache, not the several-fold the traffic argument suggests.
+**Cache-blocking the A panel gains about 6% on this part**, not the several-fold the traffic
+argument predicts, and at M=64 it is slightly worse (2.91 ms against 2.85). The 128 MiB L3 serves
+the traffic blocking removes. It is kept because it is never much worse and is the real fix on a
+part with 8 MiB of L3.
 
-**NULL RESULT — the fp8 decode table gather loses to scalar.** Every fp8 byte is one of 256 floats,
-so a lookup is exact and obvious; `vpgatherdd` measured 3268 MB/s at AVX2 and 3815 at AVX-512
-against **4512 scalar**. A gather issues one cache line per lane however small the table is.
-The decode is a branchless exponent reconstruction instead: 8294 and 12545 MB/s, 2.5× and 3.3×.
+**fp8 decode is branchless exponent reconstruction, not a table gather.** Every fp8 byte is one of
+256 floats, but `vpgatherdd` measured 3268 MB/s at AVX2 and 3815 at AVX-512 against 4512 scalar,
+because a gather issues one cache line per lane however small the table. The reconstruction
+reaches 8294 and 12545 MB/s.
 
-**A "fast path" whose epilogue is a per-element branch is not a fast path.** Computing sixteen lanes
-of an fp8 encode with vector integer arithmetic and then spilling them to a stack array to run a
-scalar loop testing one mask bit each costs roughly twice what the vector form does: on a normalised
-activation the mask is all-ones every time, so that loop runs on exactly the path it was written to
-avoid. The encode finishes in vector registers.
+**The fp8 encode finishes in vector registers.** Computing sixteen lanes with vector integer
+arithmetic and then spilling them to a stack array for a scalar loop that tests one mask bit each
+costs about twice the vector form: on a normalised activation the mask is all ones every time, so
+that loop always runs.
 
-**An unvectorised level is not a half-speed level.** A level that falls through to the ABI's scalar
-converter for a conversion costs an order of magnitude more than the vector form, not the 2× its
-width would suggest — so every conversion is written at AVX2 as well as at AVX-512, and AVX2 is the
-level most machines in the world run.
+**Every conversion is vectorised at AVX2 as well as AVX-512.** A level that falls back to the ABI's
+scalar converter costs an order of magnitude more than the vector form, not the 2× its width
+suggests, and AVX2 is the level most machines run.
 
-**A fallback that loses to the thing it falls back from is not a fallback.** The top-R selection's
-two-pass form (vector max, then find the index) pays only because the first pass is vector work; at
-the scalar level it is strictly two passes where a single-pass loop does one, and it measures slower
-than libref's. The scalar level therefore uses the single-pass loop. The confirmation pass is
-vectorised at every level for the same reason: scalar, it reads n/2 elements on average and is most
-of what `sample_argmax` costs.
+**The scalar top-R selection is single-pass.** The two-pass form (vector max, then find the index)
+pays only when the first pass is vector work; at the scalar level it is two passes where one would
+do and is slower than libref's. The confirmation pass is vectorised at every level for the same
+reason: scalar, it reads n/2 elements on average and is most of what `sample_argmax` costs.
 
-**A ceiling has to be compiled at the level it describes.** A peak loop compiled baseline measures
-SSE2 whatever level it is nominally for, and every kernel looks excellent against a ceiling an order
-of magnitude too low — so the peak kernels live in the plugin and are compiled per level like every
-other kernel here. The accumulator count matters as much as the flags: sixteen accumulators plus two
-constants is eighteen live vectors and spills a 16-register file, which costs more than the FMA
-saves, so the AVX and AVX2 peaks use ten.
+**Peak kernels are compiled per level.** A peak loop compiled baseline measures SSE2 whatever level
+it is nominally for, and every kernel then looks excellent against a ceiling an order of magnitude
+too low. So the peak kernels live in the plugin, compiled per level like every other kernel. The
+accumulator count matters as much: sixteen accumulators plus two constants is eighteen live vectors
+and spills a 16-register file, costing more than the FMA saves, so the AVX and AVX2 peaks use ten.
 
 ## Layout
 
@@ -239,13 +618,21 @@ saves, so the AVX and AVX2 peaks use ten.
     avx_common.h       libref's addressing contract, the scratch arena, the threading rule
     avx_dispatch.cpp   BASELINE: CPUID, the level tables, the thunks, the fp8 table
     avx_registry.cpp   BASELINE: the schemas (libref's, slot for slot) and the kernel rows
+    avx_planes.h       weights joined over several planes: the hooks (libref's rules) and readers
     avx_ngram.cpp      BASELINE: the embedding gather's row cache, direct reads and reader
     avx_rows.h         the gather's two halves: the row source and the per-level decode
+    avx_table.cpp      one level's table of entry points, expanded from AVX_OP_LIST; compiled 4x
     avx_support.cpp    the generic row, the reductions, the top-R step; compiled 4x
+    avx_planes.cpp     a joined row's decode: scaled E4M3 / int8, zero-point u2 / u4 / u5; compiled 4x
     avx_had.h          the Hadamard rotation, the fp8 group, the fp8 fusions' shared epilogue
-    avx_{elementwise,norm,hc,quant,gemm,attn,moe,gdn,sample,misc}.cpp   the kernels; compiled 4x
-    avx_harness.h      plugin loading, the operand draw, the geometry table -- shared by both tools
+    avx_{elementwise,norm,hc,quant,gemm,attn,qsa,moe,gdn,sample,misc}.cpp   the kernels; compiled 4x
+    avx_gen.cpp        the image generator's norms, sampler, lanes and decoder ops; compiled 4x
+    avx_gen_attn.cpp   attn_prefix_self, the generator's attention; compiled 4x
+    avx_harness.h      plugin loading, row selection, the operand draw, guarded buffers, the
+                       geometry table -- shared by both tools
     avx_cases.cpp      the geometries; one table so the check and the bench cannot disagree
-    avx_check.cpp      rad-avx-check
+    avx_check.h        what the checker's files share: the comparison, the threaded rerun
+    avx_check.cpp      rad-avx-check: schemas, coverage, the table, the conversions, the levels
+    avx_check_hand.cpp rad-avx-check's hand-built cases
     avx_check_rows.cpp rad-avx-check's file-backed embed_lookup_q case
     avx_bench.cpp      rad-avx-bench
diff --git a/libavx/avx_attn.cpp b/libavx/avx_attn.cpp
index 40cfbf81..66aa69a6 100644
--- a/libavx/avx_attn.cpp
+++ b/libavx/avx_attn.cpp
@@ -1,56 +1,33 @@
-/* avx_attn.cpp -- paged attention, dense attention, the KV write, and the two rotary forms.
+/* avx_attn.cpp -- paged attention, dense attention, the KV write, and the rotary forms.
  *
- * ============================== THE PAGED LAYOUT ==============================
+ * Paged layout (libr4d's, stated in libref/ref_ops.h):
  *
  *     kv_cache[num_blocks, kv_heads, block_size, 2 * head_dim]      K then V inside a slot
  *
- * libr4d's, stated once for the whole project in libref/ref_ops.h, obeyed here. A flat slot index
- * s decomposes as block = s / block_size, offset = s % block_size; `block_table[seq, i]` holds the
- * block id of the sequence's i-th block and `slot_mapping[token]` the flat slot a token writes to.
+ * A flat slot s is block s / block_size, offset s % block_size. `block_table[seq, i]` holds the
+ * block id of the sequence's i-th block; `slot_mapping[token]` is the flat slot a token writes.
  *
- * ============================== THE MASK ==============================
- *
- * `seqused[s]` is the sequence's TOTAL key count INCLUDING this step's query tokens, so query row
- * i of a q_len-row step sits at absolute position seqused[s] - q_len + i. That is what makes one
- * kernel serve a decode (q_len 1), a speculative verify (q_len <= 64) and a prefill chunk (q_len
- * in the thousands) with no second length parameter.
+ * Mask. `seqused[s]` is the sequence's total key count including this step's queries, so query row
+ * i of a q_len-row step is at position seqused[s] - q_len + i. One kernel thus serves decode
+ * (q_len 1), speculative verify (q_len <= 64) and prefill chunks.
  *
  *   causal = 1   key j is visible when j <= pos
  *   causal = 0   key j is visible when j <  seqused[s]
- *   window > 0   causal: additionally pos - j < window; non-causal: |pos - j| < window, the
- *                two-sided reading libr4d's h128 kernel documents.
+ *   window > 0   causal: additionally pos - j < window; non-causal: |pos - j| < window (the
+ *                two-sided reading documented by libr4d's h128 kernel).
  *
- * ============================== ONE PASS OVER THE CACHE, NOT TWO ==============================
+ * One pass over the cache. libref makes two passes (max, then exp-and-accumulate, recomputing every
+ * dot) to avoid a context-sized buffer. Here the softmax is online and tiled (flash-attention
+ * style): each tile's scores are computed once, the running maximum moves at tile boundaries, and
+ * the accumulator is rescaled by exp(m_old - m_new). The final weights are mathematically the same
+ * but the rescales add roundings, so results are not bit-exact with libref: ~1e-7 relative against
+ * tolerances of 1e-4 (f32) / 2e-2 (bf16). The other choices match libref exactly:
  *
- * This is the one place where this plugin deliberately computes the softmax in a DIFFERENT ORDER
- * from the oracle, and it is worth being explicit about the trade.
+ *   Descales are applied per element: libref computes `dot += q[d] * (k[d] * kds)`, which differs
+ *   from `dot(q, k) * kds`, so K rows are scaled by `kds` as they are widened (V by `vds`).
  *
- * libref makes two passes over the whole context: one to find the maximum score, one to
- * exponentiate and accumulate -- and it RECOMPUTES every dot product in the second pass, because
- * keeping them would need a buffer the size of the context and "the reference has time it does not
- * have memory". At a 128K context that is two full sweeps of the KV cache and twice the dot
- * products, and the KV cache is the largest thing a decode step touches.
- *
- * Here the softmax is ONLINE and tiled, the flash-attention arrangement: keys are taken in tiles,
- * a tile's scores are computed once, the running maximum is updated at the tile boundary and the
- * accumulator rescaled by exp(m_old - m_new) when it moves. One pass, one dot product per key, and
- * the memory is one tile of scores rather than one context of them.
- *
- * WHAT IT COSTS: the rescalings round. The result is mathematically identical -- the final running
- * maximum IS the global maximum, and every weight ends up as exp(s_j - m_final) -- but the
- * intermediate multiplications are extra roundings that libref does not perform, so this cannot be
- * bit-exact against it and does not claim to be. It lands at ~1e-7 relative against a tolerance of
- * 1e-4 (f32) / 2e-2 (bf16). Every other numerical choice in this file is exact by construction:
- *
- *   THE DESCALES ARE APPLIED PER ELEMENT, NOT TO THE DOT. libref computes
- *   `dot += q[d] * (k[d] * kds)`, which is not the same f32 number as `dot(q, k) * kds`. The K row
- *   is therefore scaled by `kds` as it is widened, which reproduces the reference's arithmetic
- *   exactly rather than to a tolerance. Same for V and `vds`.
- *
- *   AN EMPTY WINDOW IS A ZERO ROW, NOT A NaN. A softmax over no visible key has no defined answer
- *   and zero is what every kernel in this project produces. The checker compares the finiteness
- *   pattern before any norm, so getting this wrong is a hard failure rather than a tolerance
- *   question -- which is the right treatment.
+ *   A row with no visible key is a zero row, not NaN, as in every kernel here. The checker
+ *   compares the finiteness pattern first, so a mismatch is a hard failure.
  */
 #include "avx_vec.h"
 #include "avx_common.h"
@@ -61,17 +38,13 @@
 
 using namespace avx;
 
-/* The widest head this accumulates in one frame. The widest in circulation is an image VAE's
- * single-head mid-block attention at 1152 (Qwen-Image 2.1), so 2048 is headroom; above it the op
- * says RAD_E_UNSUPPORTED by name instead of overflowing. Same number as libref's, so the two
- * refuse the same calls. */
+/* Widest supported head. The widest in use is an image VAE's single-head mid-block attention at
+ * 1152 (Qwen-Image 2.1); wider heads return RAD_E_UNSUPPORTED. Same bound as libref. */
 enum { AVX_HD_MAX = 2048 };
 
-/* Keys per online-softmax tile. Sized so a tile of scores and the key rows behind it stay in L1
- * beside the query head and the accumulator: at head_dim 128 that is 64 keys x 128 floats = 32 KiB
- * of K plus the same of V, which is the working set a Zen-class L1 holds. It is a constant rather
- * than a tunable because the cost curve is flat between 32 and 128 -- what matters is that it is
- * not 1 (a rescale per key) and not the whole context (libref's memory problem). */
+/* Keys per online-softmax tile, sized so a tile's scores and key rows stay in L1 with the query
+ * and accumulator (at head_dim 128: 32 KiB of K plus the same of V). The cost curve is flat from
+ * 32 to 128, so it is a constant, not a tunable. */
 enum { AVX_KV_TILE = 64 };
 
 struct KVView {
@@ -95,8 +68,8 @@ static KVView kv_view(const RadTensor* c, int64_t head_dim, int64_t block_size,
     return v;
 }
 
-/* A head of an operand, widened into f32 and optionally scaled as it goes -- which is what makes
- * the descale exact against libref rather than close (see the header). */
+/* One head of an operand widened to f32 and scaled by `mul` per element, which makes the descale
+ * match libref exactly (see the header). */
 static inline const float* head_f32(const RadTensor* t, int64_t base, int64_t ds, int64_t n,
                                     float mul, float* scr) {
     if (ds == 1) {
@@ -114,24 +87,6 @@ static inline const float* head_f32(const RadTensor* t, int64_t base, int64_t ds
     return scr;
 }
 
-/* A dot product with four accumulators, which is what covers the FMA latency. Shared by both
- * attention forms and by nothing else, so it lives here rather than in the header. */
-static inline float dotf(const float* a, const float* b, int64_t n) {
-    vf a0 = vf_zero(), a1 = vf_zero(), a2 = vf_zero(), a3 = vf_zero();
-    int64_t i = 0;
-    for (; i + 4 * VF_N <= n; i += 4 * VF_N) {
-        a0 = vf_fma(vf_loadu(a + i), vf_loadu(b + i), a0);
-        a1 = vf_fma(vf_loadu(a + i + VF_N), vf_loadu(b + i + VF_N), a1);
-        a2 = vf_fma(vf_loadu(a + i + 2 * VF_N), vf_loadu(b + i + 2 * VF_N), a2);
-        a3 = vf_fma(vf_loadu(a + i + 3 * VF_N), vf_loadu(b + i + 3 * VF_N), a3);
-    }
-    for (; i + VF_N <= n; i += VF_N) a0 = vf_fma(vf_loadu(a + i), vf_loadu(b + i), a0);
-    float s = vf_hsum(vf_add(vf_add(a0, a1), vf_add(a2, a3)));
-    for (; i < n; ++i) s += a[i] * b[i];
-    return s;
-}
-
-/* acc += w * v, vectorised. */
 static inline void axpy(float* acc, const float* v, float w, int64_t n) {
     const vf vw = vf_set1(w);
     int64_t i = 0;
@@ -141,14 +96,11 @@ static inline void axpy(float* acc, const float* v, float w, int64_t n) {
 }
 
 /* ------------------------------------------------------------------ attn_paged */
-/* Prefill form, taken when the queries are uniform (!cus) and long (q_len >= 32): the
- * whole context is shared across q_len rows, so widening K/V per q-row (the decode form in
- * AVX_KERNEL below) re-converts the context q_len times -- 512x over at the bench shape.
- * Each (seq, kv-head, q-block) unit widens the context ONCE into panels and runs its rows
- * off them. The per-row math is unchanged -- dots ascending, the online softmax with the
- * same rescale points, the same scalar exps -- so rows match the decode form bit for bit;
- * only the loads move. q-blocks of 64 keep the units many for the engine's thread pool.
- * Ragged (cus) inputs stay on the decode form, whatever their lengths. */
+/* Prefill form, used for uniform (no cus) long queries (q_len >= 32). The decode form below widens
+ * K/V per query row, re-converting the shared context q_len times. Here each (seq, kv-head,
+ * q-block) unit widens the context once into panels and runs its rows from them. Per-row math
+ * (ascending dots, the same rescale points) is the decode form's; the loads differ. q-blocks of 64
+ * keep enough units for the thread pool. Ragged (cus) inputs always take the decode form. */
 static int attn_paged_prefill(const RadArgs* a, [[maybe_unused]] RadStream stream) {
     const RadTensor *q = &a->t[0], *kv = &a->t[1], *bt = &a->t[2], *su = &a->t[3], *o = &a->t[7];
     const RadTensor* kdes = rad_arg_in(a, 4);
@@ -164,9 +116,8 @@ static int attn_paged_prefill(const RadArgs* a, [[maybe_unused]] RadStream strea
     if (kv_heads <= 0) return RAD_E_SHAPE;
     const int64_t q_heads = gqa * kv_heads;
     const int64_t n_seq = numel(su);
-    /* THE QUERY LENGTH IS PER SEQUENCE. The operand holds every sequence's rows back to back, so
-     * its row count is n_seq * q_len; taking the whole of it as one sequence's length puts
-     * sequence s at rows s * rows and writes every sequence after the first past `out`. */
+    /* q_len is per sequence: the operand holds every sequence's rows back to back
+     * (n_seq * q_len rows). */
     const int64_t rows = numel(q) / (q_heads * head_dim);
     if (n_seq <= 0 || rows <= 0 || rows % n_seq != 0) return RAD_E_SHAPE;
     const int64_t q_len = rows / n_seq;
@@ -174,8 +125,8 @@ static int attn_paged_prefill(const RadArgs* a, [[maybe_unused]] RadStream strea
     const int64_t bt_rs = bt->rank >= 2 ? bt->stride[bt->rank - 2] : max_blocks;
     const int64_t bt_cs = bt->rank >= 2 ? bt->stride[bt->rank - 1] : 1;
     const KVView kvv = kv_view(kv, head_dim, block_size, kv_heads);
-    /* Read as [rows, q_heads, head_dim] at whatever rank they arrived, libref's reading: a rank-2
-     * q is a column slice whose row stride is its own (avx_common.h: row_stride). */
+    /* q and out read as [rows, q_heads, head_dim] at any rank, as libref does; a rank-2 operand
+     * is a column slice with its own row stride (avx_common.h: row_stride). */
     const int64_t q_ds = q->rank >= 2 ? q->stride[q->rank - 1] : 1;
     const int64_t q_hs = q->rank >= 3 ? q->stride[q->rank - 2] : head_dim * q_ds;
     const int64_t q_rs = row_stride(q, q_heads * head_dim);
@@ -193,7 +144,7 @@ static int attn_paged_prefill(const RadArgs* a, [[maybe_unused]] RadStream strea
         if (ctx <= 0) continue;
         const float kds = kdes ? ldt(kdes, s * kv_heads + kh) : 1.0f;
         const float vds = vdes ? ldt(vdes, s * kv_heads + kh) : 1.0f;
-        /* Panels plus one row frame: a single arena call, partitioned by hand. */
+        /* K/V panels plus one row frame, from a single scratch call. */
         float* mem = scratch_f32((size_t)2 * (size_t)ctx * (size_t)head_dim +
                                  (size_t)(3 * head_dim + AVX_KV_TILE) + 16);
         float* Kp = mem;
@@ -204,8 +155,8 @@ static int attn_paged_prefill(const RadArgs* a, [[maybe_unused]] RadStream strea
         float* acc = frame + 2 * head_dim;
         float* sbuf = frame + 3 * head_dim;
         int64_t* kbv = (int64_t*)scratch_raw((size_t)ctx * sizeof(int64_t) + 64);
-        /* Widen the context once. Rows past max_blocks stay invalid, exactly as the
-         * per-row loop's break would leave them. */
+        /* Widen the context once. Keys past max_blocks are excluded, as the decode form's
+         * break does. */
         int64_t nkeys = 0;
         for (int64_t j = 0; j < ctx; ++j) {
             if (j / block_size >= max_blocks) break;
@@ -223,10 +174,8 @@ static int attn_paged_prefill(const RadArgs* a, [[maybe_unused]] RadStream strea
             nkeys = j + 1;
         }
         const int64_t i0 = qb * QB, i1 = (i0 + QB < q_len) ? i0 + QB : q_len;
-        /* One gqa row at a time. A joint-rows form -- each key row loaded once for all gqa
-         * dots -- measures identical on a long-query shape: the nest is compute-saturated
-         * (dots, axpy, scalar exps) rather than bound by panel traffic, so sharing the loads
-         * frees nothing. Do not switch to it without measuring. */
+        /* One gqa row at a time. Loading each key row once for all gqa dots measured no faster
+         * on long queries: the nest is compute-bound, not bound by panel traffic. */
         for (int64_t g = 0; g < gqa; ++g) {
             const int64_t h = kh * gqa + g;
             for (int64_t i = i0; i < i1; ++i) {
@@ -244,7 +193,7 @@ static int attn_paged_prefill(const RadArgs* a, [[maybe_unused]] RadStream strea
                     float tmax = sbuf[0];
                     for (int t = 1; t < ntile; ++t) if (sbuf[t] > tmax) tmax = sbuf[t];
                     if (tmax > m) {
-                        const float r = (m == -INFINITY) ? 0.0f : std::exp(m - tmax);
+                        const float r = (m == -INFINITY) ? 0.0f : sc_exp(m - tmax);
                         if (r != 1.0f) {
                             const vf vr = vf_set1(r);
                             int64_t d = 0;
@@ -255,12 +204,10 @@ static int attn_paged_prefill(const RadArgs* a, [[maybe_unused]] RadStream strea
                         }
                         m = tmax;
                     }
-                    /* Scalar exps here, deliberately: the tile-vectorised form
-                     * (vf_exp, as in the decode flush) measures neutral-to-slower on a
-                     * long-query shape, because the nest is bound elsewhere. The values
-                     * are the same either way. */
+                    /* Scalar exps: vf_exp (as in the decode flush) measured neutral to slower
+                     * here. */
                     for (int t = 0; t < ntile; ++t) {
-                        const float w = std::exp(sbuf[t] - m);
+                        const float w = sc_exp(sbuf[t] - m);
                         l += w;
                         axpy(acc, Vp + (size_t)kbase[t] * head_dim, w, head_dim);
                     }
@@ -309,9 +256,8 @@ AVX_KERNEL(attn_paged) {
 
     const int64_t head_dim = p_int(a, "head_dim", q->rank >= 3 ? q->shape[q->rank - 1] : 0);
     const int64_t gqa = p_int(a, "gqa", 1);
-    /* `block_size` is RAD_DERIVED (docs/OPS.md), so a caller who did not pin it and resolved to a
-     * kernel that declares no RAD_C_EQ for it arrives here without the key. The cache tensor says
-     * what the block size is; reading it off the operand is this plugin's rule anyway. */
+    /* `block_size` is RAD_DERIVED (docs/OPS.md) and may be absent; the cache tensor's shape gives
+     * it. */
     const int64_t block_size = p_int(a, "block_size", kv->rank == 4 ? kv->shape[2] : 0);
     const int causal = (int)p_int(a, "causal", 1);
     const int64_t window = p_int(a, "window", 0);
@@ -337,8 +283,8 @@ AVX_KERNEL(attn_paged) {
     const int64_t bt_cs = bt->rank >= 2 ? bt->stride[bt->rank - 1] : 1;
     const KVView kvv = kv_view(kv, head_dim, block_size, kv_heads);
 
-    /* Row strides of q and out read as [rows, q_heads, head_dim], at whatever rank they arrived --
-     * libref's reading. A rank-2 operand is a column slice whose row stride is its own. */
+    /* q and out read as [rows, q_heads, head_dim] at any rank, as libref does; a rank-2 operand
+     * is a column slice with its own row stride. */
     const int64_t q_ds = q->rank >= 2 ? q->stride[q->rank - 1] : 1;
     const int64_t q_hs = q->rank >= 3 ? q->stride[q->rank - 2] : head_dim * q_ds;
     const int64_t q_rs = row_stride(q, q_heads * head_dim);
@@ -347,20 +293,17 @@ AVX_KERNEL(attn_paged) {
     const int64_t o_rs = row_stride(o, q_heads * head_dim);
 
     const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim));
-    /* Uniform long queries share one context: the panel form widens it once instead of once
-     * per row. Ragged (cus) inputs stay below whatever their lengths. */
+    /* Uniform long queries take the panel form; ragged (cus) inputs stay here. */
     if (!cus && q_len >= 32) return attn_paged_prefill(a, stream);
-    /* Rows run as (token, kv-head) groups: the gqa query rows of a group share the key
-     * and value rows behind every key, so each is widened once for gqa dots/axpys rather
-     * than once per row. Per-row arithmetic is untouched -- rows match bit for bit. */
+    /* Work units are (token, kv-head) groups: the gqa query rows of a group share every key and
+     * value row, so each is widened once for gqa dots/axpys. Per-row arithmetic is unchanged. */
     const int64_t total = rows * kv_heads;
 
     AVX_PARALLEL_FOR_IF(total >= 2)
     for (int64_t tidx = 0; tidx < total; ++tidx) {
         const int64_t kh = tidx % kv_heads;
         const int64_t tok = tidx / kv_heads;
-        /* Which sequence owns this token and where inside its query it sits. Linear rather
-         * than a binary search: n_seq is a handful. Once per group, not once per row. */
+        /* Owning sequence and position within its query; linear search, n_seq is small. */
         int64_t s = 0, qlen = q_len, i = 0;
         if (cus) {
             while (s + 1 < n_seq && ldi(cus, offlin(cus, s + 1)) <= tok) ++s;
@@ -377,8 +320,7 @@ AVX_KERNEL(attn_paged) {
         const float kds = kdes ? ldt(kdes, s * kv_heads + kh) : 1.0f;
         const float vds = vdes ? ldt(vdes, s * kv_heads + kh) : 1.0f;
 
-        /* One arena call carves the whole frame, because a second one may reallocate and
-         * invalidate the first pointer (avx_common.h). */
+        /* The whole frame from one scratch call; a second may reallocate the first. */
         float* frame = (float*)scratch_f32((size_t)gqa * (size_t)(2 * head_dim + AVX_KV_TILE + 2) +
                                            (size_t)(2 * head_dim) + 16);
         float* qpan = frame;                                 /* [gqa, head_dim] queries */
@@ -402,9 +344,9 @@ AVX_KERNEL(attn_paged) {
         }
         int ntile = 0;
 
-        /* Flush a tile: per row, update the running maximum, rescale what is already
-         * accumulated, then add this tile's weighted values in ascending key order. The
-         * value row is widened once per key and shared across the group's axpys. */
+        /* Flush a tile: per row, update the running maximum and rescale the accumulator, then
+         * add the tile's weighted values in ascending key order, widening each value row once
+         * for the whole group. */
         auto flush = [&]() {
             if (ntile == 0) return;
             for (int64_t g = 0; g < gqa; ++g) {
@@ -414,7 +356,7 @@ AVX_KERNEL(attn_paged) {
                 float tmax = sb[0];
                 for (int t = 1; t < ntile; ++t) if (sb[t] > tmax) tmax = sb[t];
                 if (tmax > m) {
-                    const float r = (m == -INFINITY) ? 0.0f : std::exp(m - tmax);
+                    const float r = (m == -INFINITY) ? 0.0f : sc_exp(m - tmax);
                     if (r != 1.0f) {
                         const vf vr = vf_set1(r);
                         int64_t d = 0;
@@ -425,19 +367,19 @@ AVX_KERNEL(attn_paged) {
                     }
                     m = tmax;
                 }
-                /* The tile's exps, vectorised: the accumulation keeps its order. */
+                /* Vectorised exps; the accumulation order is unchanged. */
                 {
                     const vf vm = vf_set1(m);
                     int t = 0;
                     for (; t + VF_N <= ntile; t += VF_N)
                         vf_storeu(sb + t, vf_exp(vf_sub(vf_loadu(sb + t), vm)));
-                    for (; t < ntile; ++t) sb[t] = std::exp(sb[t] - m);
+                    for (; t < ntile; ++t) sb[t] = sc_exp(sb[t] - m);
                 }
                 mm[g] = m;
                 ll[g] = l;
             }
             for (int t = 0; t < ntile; ++t) {
-                /* One widening per key for the whole group, then gqa axpys. */
+                /* One widening per key, then gqa axpys. */
                 const float* vv = head_f32(kv, kbase[t] + head_dim * kvv.sd, kvv.sd, head_dim,
                                            vds, vrow);
                 for (int64_t g = 0; g < gqa; ++g) {
@@ -455,11 +397,11 @@ AVX_KERNEL(attn_paged) {
                 const int64_t d = pos - j;
                 if (causal ? (d >= window) : (d >= window || d <= -window)) continue;
             }
-            if (j / block_size >= max_blocks) break;   /* the table is only this wide */
+            if (j / block_size >= max_blocks) break;   /* past the block table's width */
             const int64_t blk = ldi(bt, s * bt_rs + (j / block_size) * bt_cs);
             if (blk < 0) continue;
             const int64_t kb = blk * kvv.sb + kh * kvv.sh + (j % block_size) * kvv.so;
-            /* One widening per key for the whole group, then gqa dots. */
+            /* One widening per key, then gqa dots. */
             const float* kvrow = head_f32(kv, kb, kvv.sd, head_dim, kds, krow);
             for (int64_t g = 0; g < gqa; ++g)
                 sbufs[g * AVX_KV_TILE + ntile] =
@@ -494,14 +436,13 @@ AVX_KERNEL(attn_paged) {
 }
 
 /* ------------------------------------------------------------------ attn_dense, bf16 blocks */
-/* AN ENCODER'S ATTENTION IS ALL PREFILL, and the per-query loop below is built for a decode row:
- * it parallelises over (segment, head) -- eight units for one long input on a sixteen-core part --
- * and widens every key row to f32 again for every query that reads it, so a 2000-token segment
- * pays four million row conversions a head. Measured at 130 GFLOPS on the sliding layers.
+/* Encoder attention is all prefill. The per-query loop in attn_dense parallelises over
+ * (segment, head) only and re-widens every key row for every query (four million row conversions
+ * per head for a 2000-token segment); it reached 130 GFLOPS on the sliding layers.
  *
- * Where q, k and v are bf16 with unit element stride and the CPU has AVX512_BF16, this blocked
- * form runs instead. A task is (segment, KV head, 32 query positions) and holds the rows of every
- * query head that reads that KV head, so one key tile serves gqa x 32 rows. Per tile of 64 keys:
+ * When q, k and v are bf16 with unit element stride and the CPU has AVX512_BF16, this blocked form
+ * runs instead. A task is (segment, KV head, 32 query positions) with the rows of every query head
+ * sharing that KV head, so one key tile serves gqa x 32 rows. Per tile of 64 keys:
  *
  *   S = Q K^T     vdpbf16ps against the tile packed once as key-interleaved bf16 pairs, each
  *                 query pair broadcast into 16-key vectors: no score is horizontally reduced
@@ -518,10 +459,10 @@ AVX_KERNEL(attn_paged) {
 #if AVX_LEVEL == 3
 #define AVX_BF16_TARGET __attribute__((target("avx512f,avx512bw,avx512vl,avx512bf16")))
 
-/* S[r][0..63] for MB_ query rows against a key tile packed as bf16 PAIRS INTERLEAVED BY KEY:
- * kp[d2 * 64 + j] holds key j's dims 2*d2 and 2*d2+1. Each step broadcasts one row's pair and
- * multiplies it into four 16-key vectors, so a score is never horizontally reduced -- with a
- * 64-wide head a reduction per score cost more than the two products it closed. */
+/* S[r][0..63] for MB_ query rows against a key tile packed as bf16 pairs interleaved by key:
+ * kp[d2 * 64 + j] holds key j's dims 2*d2 and 2*d2+1. Each step broadcasts one row's pair into
+ * four 16-key vectors, so no score needs a horizontal reduction (which at head_dim 64 cost more
+ * than the products). */
 template 
 AVX_BF16_TARGET static inline void qk_rows(const uint16_t* const* qr, const uint32_t* kp,
                                            int64_t D2, float scale, float* S, int64_t ldS) {
@@ -555,9 +496,9 @@ AVX_BF16_TARGET static inline void qk_rows(const uint16_t* const* qr, const uint
 }
 
 /* acc[r][c0 .. c0+63] += P[r] . V for MB_ rows, in bf16 pairs: pp[r * 32 + k2] holds row r's
- * probabilities for keys 2*k2 and 2*k2+1, vp[k2 * D + d] holds those two keys' values at column
- * d. PyTorch's CPU flash attention -- the reference's -- rounds P to bf16 for this product as
- * well; the softmax's sum is kept in f32 from the unrounded P. */
+ * probabilities for keys 2*k2 and 2*k2+1, vp[k2 * D + d] those two keys' values at column d. P is
+ * rounded to bf16 here, as in PyTorch's CPU flash attention (the reference); the softmax sum uses
+ * the unrounded P in f32. */
 template 
 AVX_BF16_TARGET static inline void pv_rows(float* acc, int64_t D, const uint32_t* pp,
                                            const uint32_t* vp, int64_t K2, int64_t c0) {
@@ -591,7 +532,7 @@ AVX_BF16_TARGET static bool attn_dense_bf16(const RadTensor* q, const RadTensor*
                                             const RadTensor* v, const RadTensor* cu,
                                             const RadTensor* o, int64_t D, int64_t gqa,
                                             int64_t kv_heads, int causal, int64_t window,
-                                            float scale, int64_t q_rs, int64_t q_hs, int64_t q_ds,
+                                            int64_t block, int64_t cdiv, float scale, int64_t q_rs, int64_t q_hs, int64_t q_ds,
                                             int64_t k_rs, int64_t k_hs, int64_t k_ds, int64_t v_rs,
                                             int64_t v_hs, int64_t v_ds, int64_t o_rs, int64_t o_hs,
                                             int64_t o_ds) {
@@ -602,10 +543,10 @@ AVX_BF16_TARGET static bool attn_dense_bf16(const RadTensor* q, const RadTensor*
 
     constexpr int64_t QB = 32, KT = 64;
     const int64_t n_seq = numel(cu) - 1;
-    /* The task list: (segment, kv head, query block), flattened through a prefix over segments. */
+    /* Tasks are (segment, kv head, query block), flattened with a prefix sum over segments. */
     std::vector first((size_t)n_seq + 1, 0);
     for (int64_t s = 0; s < n_seq; ++s) {
-        const int64_t len = ldi(cu, offlin(cu, s + 1)) - ldi(cu, offlin(cu, s));
+        const int64_t len = ldi(cu, offlin(cu, s + 1)) / cdiv - ldi(cu, offlin(cu, s)) / cdiv;
         first[(size_t)s + 1] = first[(size_t)s] + kv_heads * ((len + QB - 1) / QB);
     }
     const int64_t n_task = first[(size_t)n_seq];
@@ -619,7 +560,8 @@ AVX_BF16_TARGET static bool attn_dense_bf16(const RadTensor* q, const RadTensor*
 #endif
     for (int64_t t = 0; t < n_task; ++t) {
         int64_t s = (int64_t)(std::upper_bound(first.begin(), first.end(), t) - first.begin()) - 1;
-        const int64_t b0 = ldi(cu, offlin(cu, s)), len = ldi(cu, offlin(cu, s + 1)) - b0;
+        const int64_t b0 = ldi(cu, offlin(cu, s)) / cdiv;
+        const int64_t len = ldi(cu, offlin(cu, s + 1)) / cdiv - b0;
         const int64_t local = t - first[(size_t)s];
         const int64_t nqb = (len + QB - 1) / QB;
         const int64_t kh = local / nqb, q0 = (local % nqb) * QB;
@@ -649,10 +591,14 @@ AVX_BF16_TARGET static bool attn_dense_bf16(const RadTensor* q, const RadTensor*
             jbeg = std::max(0, q0 - window + 1);
             if (!causal) jend = std::min(len, q1 - 1 + window);
         }
+        if (block > 0) {
+            jbeg = std::max(jbeg, q0 / block * block);
+            jend = std::min(jend, ((q1 - 1) / block + 1) * block);
+        }
         for (int64_t j0 = jbeg; j0 < jend; j0 += KT) {
             const int64_t kt = std::min(KT, jend - j0);
-            /* The key tile packed once for every row of the task: pairs interleaved by key, the
-             * keys past the tile's end zero (their scores are never read). */
+            /* Pack the key tile once for the task: pairs interleaved by key, keys past the tile's
+             * end zero (their scores are never read). */
             for (int64_t d2 = 0; d2 < D2; ++d2) {
                 uint32_t* dst = kpack + d2 * KT;
                 for (int64_t j = 0; j < kt; ++j)
@@ -660,24 +606,25 @@ AVX_BF16_TARGET static bool attn_dense_bf16(const RadTensor* q, const RadTensor*
                 for (int64_t j = kt; j < KT; ++j) dst[j] = 0;
             }
 
-            /* S, six rows a block against the whole packed tile. */
+            /* S, six rows per block against the packed tile. */
             int64_t r = 0;
             for (; r + 6 <= R; r += 6) qk_rows<6>(qrow + r, kpack, D2, scale, S + r * KT, KT);
             for (; r < R; ++r) qk_rows<1>(qrow + r, kpack, D2, scale, S + r * KT, KT);
-            /* The mask, by position inside the segment. */
-            if (causal || window > 0) {
+            /* Mask by position within the segment. */
+            if (causal || window > 0 || block > 0) {
                 for (int64_t r = 0; r < R; ++r) {
                     const int64_t i = q0 + r / gqa;
                     for (int64_t j = 0; j < kt; ++j) {
                         const int64_t d = i - (j0 + j);
                         bool ok = !causal || d >= 0;
                         if (window > 0) ok = ok && (causal ? d < window : (d < window && -d < window));
+                        if (block > 0) ok = ok && i / block == (j0 + j) / block;
                         if (!ok) S[r * KT + j] = -INFINITY;
                     }
                 }
             }
-            /* The online softmax, row by row, four vectors a row; S becomes P in place. The keys
-             * past a short tile's end score -inf, so P is zero there and every row is full width. */
+            /* Online softmax per row, four vectors per row; S becomes P in place. Keys past a short
+             * tile's end score -inf, so P is zero there and rows are always full width. */
             if (kt < KT)
                 for (int64_t r = 0; r < R; ++r)
                     for (int64_t j = kt; j < KT; ++j) S[r * KT + j] = -INFINITY;
@@ -691,7 +638,7 @@ AVX_BF16_TARGET static bool attn_dense_bf16(const RadTensor* q, const RadTensor*
                     continue;
                 }
                 if (tmax > m[r]) {
-                    const float alpha = m[r] == -INFINITY ? 0.0f : std::exp(m[r] - tmax);
+                    const float alpha = m[r] == -INFINITY ? 0.0f : sc_exp(m[r] - tmax);
                     if (alpha != 1.0f) {
                         float* ar = acc + r * D;
                         const __m512 va = _mm512_set1_ps(alpha);
@@ -704,20 +651,19 @@ AVX_BF16_TARGET static bool attn_dense_bf16(const RadTensor* q, const RadTensor*
                 const vf vm = vf_set1(m[r]);
                 __m512 sum = _mm512_setzero_ps();
                 for (int64_t j = 0; j < KT; j += 16) {
-                    /* exp of -inf is the clamp's floor, ~1e-38: zero to every sum it joins. */
+                    /* vf_exp(-inf) is set to zero (see vf_exp). */
                     const vf e = vf_exp(vf_sub(vf_loadu(sr + j), vm));
                     vf_storeu(sr + j, e);
                     sum = _mm512_add_ps(sum, e);
                 }
                 l[r] += _mm512_reduce_add_ps(sum);
             }
-            /* V's tile packed once for every row of the task, consecutive keys interleaved in
-             * pairs (a key past the tile's end is zero), and each row's P rounded to bf16 pairs
-             * along the keys. */
+            /* Pack V's tile once for the task, consecutive keys interleaved in pairs (a key past
+             * the tile's end is zero), then round each row's P to bf16 pairs along the keys. */
             const int64_t K2 = (kt + 1) / 2;
             {
-                /* Two key rows' words interleaved, 32 columns a step: lanes 0..15 of the first
-                 * output are (k0[d], k1[d]) for d = 0..15, the second's for d = 16..31. */
+                /* Interleave two key rows, 32 columns per step: the first output holds
+                 * (k0[d], k1[d]) for d = 0..15, the second for d = 16..31. */
                 const __m512i ilo = _mm512_set_epi16(47, 15, 46, 14, 45, 13, 44, 12, 43, 11, 42, 10,
                                                      41, 9, 40, 8, 39, 7, 38, 6, 37, 5, 36, 4, 35, 3,
                                                      34, 2, 33, 1, 32, 0);
@@ -738,7 +684,7 @@ AVX_BF16_TARGET static bool attn_dense_bf16(const RadTensor* q, const RadTensor*
                     }
                 }
             }
-            /* P to bf16, round to nearest even: a row's 64 values are its 32 key pairs in order. */
+            /* P to bf16, round to nearest even: a row's 64 values become its 32 key pairs. */
             for (int64_t r = 0; r < R; ++r) {
                 const float* sr = S + r * KT;
                 uint32_t* pr = ppack + r * 32;
@@ -770,13 +716,12 @@ AVX_BF16_TARGET static bool attn_dense_bf16(const RadTensor* q, const RadTensor*
 #endif
 
 /* ------------------------------------------------------------------ attn_dense */
-/* The vision tower's: nothing paged, nothing quantised, `cu_seqlens` bounding one image (or one
- * attention window) per entry so a whole batch is ONE launch rather than a per-segment loop and a
- * concatenate. Causal is a parameter because a dense decoder-only prefill wants the same kernel.
+/* Unpaged, unquantised attention (vision towers): `cu_seqlens` bounds one image or attention
+ * window per entry, so a whole batch is one launch. `causal` is a parameter so a dense
+ * decoder-only prefill can use it too.
  *
- * Same online softmax as the paged form, and the tile is over the segment rather than the page
- * table -- so the K and V rows are consecutive in memory and the hardware prefetcher sees a single
- * stream, which is the one thing the dense form has that the paged one cannot. */
+ * Same online softmax as the paged form; K and V rows are consecutive in memory, so the prefetcher
+ * sees one stream. */
 AVX_KERNEL(attn_dense) {
     if (!rad_args_have(a, 5)) return RAD_E_INVAL;
     const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *cu = &a->t[3], *o = &a->t[4];
@@ -784,13 +729,15 @@ AVX_KERNEL(attn_dense) {
     const int64_t head_dim = p_int(a, "head_dim", q->rank >= 3 ? q->shape[q->rank - 1] : 0);
     const int64_t gqa = p_int(a, "gqa", 1);
     const int causal = (int)p_int(a, "causal", 0);
-    /* libref's window: causal, i - j < window; non-causal, |i - j| < window; 0 none. */
+    /* As libref: causal, i - j < window; non-causal, |i - j| < window; 0 means none. A `block`
+     * cuts a segment into blocks attending within themselves; `cu_div` reads cu_seqlens in units
+     * that many rows apart. */
     const int64_t window = p_int(a, "window", 0);
-    if (head_dim <= 0 || gqa <= 0 || window < 0) return RAD_E_SHAPE;
+    const int64_t block = p_int(a, "block", 0), cdiv = p_int(a, "cu_div", 1);
+    if (head_dim <= 0 || gqa <= 0 || window < 0 || block < 0 || cdiv <= 0) return RAD_E_SHAPE;
     if (head_dim > AVX_HD_MAX) return RAD_E_UNSUPPORTED;
 
-    /* A rank-2 operand is [tokens, heads * head_dim], so its head count is its width over the
-     * head; reading it as one head would take every head of a multi-head slice for one long one. */
+    /* A rank-2 operand is [tokens, heads * head_dim]: its head count is width / head_dim. */
     const int64_t q_heads = q->rank >= 3 ? q->shape[q->rank - 2]
                           : (q->rank == 2 ? q->shape[1] / head_dim : 1);
     const int64_t kv_heads = q_heads / gqa;
@@ -798,12 +745,14 @@ AVX_KERNEL(attn_dense) {
     const int64_t n_seq = numel(cu) - 1;
     if (n_seq <= 0) return RAD_E_SHAPE;
     const int64_t total_q = numel(q) / (q_heads * head_dim);
+    if (total_q <= 0 || ldi(cu, offlin(cu, n_seq)) <= ldi(cu, offlin(cu, 0)))
+        return RAD_E_SHAPE;                         /* zero rows is not a call (docs/OPS.md) */
     if (numel(o) < total_q * q_heads * head_dim) return RAD_E_SHAPE;
     if (numel(k) < total_q * kv_heads * head_dim) return RAD_E_SHAPE;
     if (numel(v) < total_q * kv_heads * head_dim) return RAD_E_SHAPE;
 
-    /* libref's reading of all four, at whatever rank they arrived: a rank-2 operand is a column
-     * slice whose row stride is its own (avx_common.h: row_stride). */
+    /* All four read as libref does at any rank; a rank-2 operand is a column slice with its own
+     * row stride (avx_common.h: row_stride). */
     const int64_t q_ds = q->rank >= 2 ? q->stride[q->rank - 1] : 1;
     const int64_t q_hs = q->rank >= 3 ? q->stride[q->rank - 2] : head_dim * q_ds;
     const int64_t q_rs = row_stride(q, q_heads * head_dim);
@@ -819,7 +768,8 @@ AVX_KERNEL(attn_dense) {
 
     const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim));
 #if AVX_LEVEL == 3
-    if (attn_dense_bf16(q, k, v, cu, o, head_dim, gqa, kv_heads, causal, window, scale, q_rs,
+    if (attn_dense_bf16(q, k, v, cu, o, head_dim, gqa, kv_heads, causal, window, block, cdiv,
+                        scale, q_rs,
                         q_hs, q_ds, k_rs, k_hs, k_ds, v_rs, v_hs, v_ds, o_rs, o_hs, o_ds))
         return RAD_OK;
 #endif
@@ -827,8 +777,8 @@ AVX_KERNEL(attn_dense) {
     AVX_PARALLEL_FOR_IF(n_seq * q_heads >= 2)
     for (int64_t sh = 0; sh < n_seq * q_heads; ++sh) {
         const int64_t s = sh / q_heads, h = sh % q_heads, kh = h / gqa;
-        const int64_t b0 = ldi(cu, offlin(cu, s));
-        const int64_t b1 = ldi(cu, offlin(cu, s + 1));
+        const int64_t b0 = ldi(cu, offlin(cu, s)) / cdiv;
+        const int64_t b1 = ldi(cu, offlin(cu, s + 1)) / cdiv;
         float* frame = (float*)scratch_f32((size_t)(4 * head_dim + AVX_KV_TILE) + 16);
         float* qbuf = frame;
         float* kbuf = frame + head_dim;
@@ -844,6 +794,11 @@ AVX_KERNEL(attn_dense) {
                 jbeg = std::max(b0, i - window + 1);
                 if (!causal) jend = std::min(b1, i + window);
             }
+            if (block > 0) {
+                const int64_t blk = b0 + (i - b0) / block * block;
+                jbeg = std::max(jbeg, blk);
+                jend = std::min(jend, blk + block);
+            }
             const float* qv = head_f32(q, qb, q_ds, head_dim, 1.0f, qbuf);
             for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f;
             float m = -INFINITY, l = 0.0f;
@@ -854,7 +809,7 @@ AVX_KERNEL(attn_dense) {
                 float tmax = sbuf[0];
                 for (int t = 1; t < ntile; ++t) if (sbuf[t] > tmax) tmax = sbuf[t];
                 if (tmax > m) {
-                    const float r = (m == -INFINITY) ? 0.0f : std::exp(m - tmax);
+                    const float r = (m == -INFINITY) ? 0.0f : sc_exp(m - tmax);
                     if (r != 1.0f) {
                         const vf vr = vf_set1(r);
                         int64_t d = 0;
@@ -865,14 +820,13 @@ AVX_KERNEL(attn_dense) {
                     }
                     m = tmax;
                 }
-                /* The tile's exps, vectorised (see the prefill flush above): the
-                 * accumulation keeps its order. */
+                /* Vectorised exps; the accumulation order is unchanged. */
                 {
                     const vf vm = vf_set1(m);
                     int t = 0;
                     for (; t + VF_N <= ntile; t += VF_N)
                         vf_storeu(sbuf + t, vf_exp(vf_sub(vf_loadu(sbuf + t), vm)));
-                    for (; t < ntile; ++t) sbuf[t] = std::exp(sbuf[t] - m);
+                    for (; t < ntile; ++t) sbuf[t] = sc_exp(sbuf[t] - m);
                 }
                 for (int t = 0; t < ntile; ++t) {
                     const float w = sbuf[t];
@@ -912,8 +866,8 @@ AVX_KERNEL(attn_dense) {
 
 /* ------------------------------------------------------------------ attn_local_rel */
 /* libref's local attention with a relative-position term (Gemma 4's audio). A query sees at most
- * left + 1 keys -- thirteen at the checkpoint's geometry -- so the work is a few dot products a
- * (row, head) and the loop is libref's, vectorised along the head and parallel over (row, head). */
+ * left + 1 keys (13 for that checkpoint), so this is libref's loop, vectorised along the head and
+ * parallel over (row, head). */
 AVX_KERNEL(attn_local_rel) {
     if (!rad_args_have(a, 7)) return RAD_E_INVAL;
     const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *rk = &a->t[3];
@@ -930,6 +884,8 @@ AVX_KERNEL(attn_local_rel) {
     const int64_t S = numel(cu) - 1;
     if (S <= 0) return RAD_E_SHAPE;
     const int64_t Mq = numel(q) / Wd, Mk = numel(k) / Wd, Mv = numel(v) / Wd, Mo = numel(o) / Wd;
+    if (Mq <= 0 || Mo <= 0 || ldi(cu, offlin(cu, S)) <= ldi(cu, offlin(cu, 0)))
+        return RAD_E_SHAPE;                         /* zero rows is not a call (docs/OPS.md) */
     const int64_t q_rs = row_stride(q, Wd), k_rs = row_stride(k, Wd), v_rs = row_stride(v, Wd);
     const int64_t r_rs = row_stride(rk, Wd), o_rs = row_stride(o, Wd);
     const int64_t q_ds = laststride(q), k_ds = laststride(k), v_ds = laststride(v);
@@ -938,12 +894,12 @@ AVX_KERNEL(attn_local_rel) {
     const float qs = (float)(1.0 / std::sqrt((double)D) / std::log(2.0));
     const float ks = (float)(std::log(1.0 + std::exp(1.0)) / std::log(2.0));
     /* softplus(pds), rounded to the weight's dtype as the reference evaluates it on the bf16
-     * parameter (libref's reading), and the query's whole scale folded into one vector. */
+     * parameter (as libref does); the query's whole scale is folded into one vector. */
     float* spd = (float*)scratch_raw((size_t)D * sizeof(float) + 64);
     for (int64_t d = 0; d < D; ++d) {
         const float x = ldt(pds, d * laststride(pds));
-        const float sp = x > 20.0f ? x : (x > 0.0f ? x + std::log1p(std::exp(-x))
-                                                   : std::log1p(std::exp(x)));
+        const float sp = x > 20.0f ? x : (x > 0.0f ? x + sc_log1p(sc_exp(-x))
+                                                   : sc_log1p(sc_exp(x)));
         float r = sp;
         if (pds->dtype == RAD_BF16) r = rad_bf16_to_f32(rad_f32_to_bf16(sp));
         else if (pds->dtype == RAD_F16) r = rad_f16_to_f32(rad_f32_to_f16(sp));
@@ -975,13 +931,13 @@ AVX_KERNEL(attn_local_rel) {
                 float ac = dotf(qf, kb, D);
                 const float* rv = head_f32(rk, (i - j) * r_rs + h * D * r_ds, r_ds, D, 1.0f, tmp);
                 ac += dotf(qf, rv, D);
-                const float x = cap * std::tanh(ac / cap);
+                const float x = cap * sc_tanh(ac / cap);
                 lg[j - j0] = x;
                 mx = x > mx ? x : mx;
             }
             float sum = 0.0f;
             for (int64_t j = j0; j <= i; ++j) {
-                lg[j - j0] = std::exp(lg[j - j0] - mx);
+                lg[j - j0] = sc_exp(lg[j - j0] - mx);
                 sum += lg[j - j0];
             }
             for (int64_t d = 0; d < D; ++d) acc[d] = 0.0f;
@@ -997,14 +953,57 @@ AVX_KERNEL(attn_local_rel) {
 }
 
 /* ------------------------------------------------------------------ kv_store */
-/* The cache operand is INOUT and not OUT: this op touches only the mapped slots and every other
- * slot in the pool must survive it, which is a liveness fact the buffer planner has to know.
+/* The cache operand is INOUT, not OUT: only the mapped slots are written and every other slot
+ * must survive (the buffer planner relies on this).
  *
- * A NEGATIVE slot is SKIPPED, and that is a documented value rather than an accident: it is how a
- * padded batch row says "this token has no cache slot". libr4d treats slot <= 0 as null because
- * vLLM reserves block 0; a generic implementation must not steal a valid slot, so only the
- * strictly negative is skipped -- libref's rule, and the two have to agree or a padded step writes
- * different bytes under the two plugins. */
+ * A negative slot is skipped; that is how a padded batch row says it has no cache slot. libr4d
+ * treats slot <= 0 as null because vLLM reserves block 0, but slot 0 is valid in general, so only
+ * negative slots are skipped (libref's rule). */
+/* The scatter: token t's k and v rows into its slot of every KV head. SCALED multiplies them by
+ * the fp8 cache's inverse descales `ks` and `vs`; the unscaled form is a separate instantiation so
+ * the common path carries no scale. */
+template 
+static void kv_scatter(const RadTensor* k, const RadTensor* v, const RadTensor* sm,
+                       const RadTensor* kv, const KVView& kvv, int64_t M, int64_t kv_heads,
+                       int64_t head_dim, int64_t block_size, int64_t k_rs, int64_t k_hs,
+                       int64_t k_ds, int64_t v_rs, int64_t v_hs, int64_t v_ds, float ks,
+                       float vs) {
+    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;
+        float* buf = scratch_f32((size_t)head_dim);
+        for (int64_t h = 0; h < kv_heads; ++h) {
+            const int64_t cb = blk * kvv.sb + h * kvv.sh + off * kvv.so;
+            /* A whole head at a time through the row converter; strided operands go per
+             * element. */
+            if (k_ds == 1 && kvv.sd == 1) {
+                row_to_f32(k->dtype, byte_at(k->data, k->dtype, t * k_rs + h * k_hs), buf, head_dim);
+                if constexpr (SCALED)
+                    for (int64_t d = 0; d < head_dim; ++d) buf[d] *= ks;
+                out_row(kv, cb, head_dim, buf);
+            } else {
+                for (int64_t d = 0; d < head_dim; ++d) {
+                    const float x = ldt(k, t * k_rs + h * k_hs + d * k_ds);
+                    stt(kv, cb + d * kvv.sd, SCALED ? x * ks : x);
+                }
+            }
+            if (v_ds == 1 && kvv.sd == 1) {
+                row_to_f32(v->dtype, byte_at(v->data, v->dtype, t * v_rs + h * v_hs), buf, head_dim);
+                if constexpr (SCALED)
+                    for (int64_t d = 0; d < head_dim; ++d) buf[d] *= vs;
+                out_row(kv, cb + head_dim, head_dim, buf);
+            } else {
+                for (int64_t d = 0; d < head_dim; ++d) {
+                    const float x = ldt(v, t * v_rs + h * v_hs + d * v_ds);
+                    stt(kv, cb + (head_dim + d) * kvv.sd, SCALED ? x * vs : x);
+                }
+            }
+        }
+    }
+}
+
 AVX_KERNEL(kv_store) {
     if (!rad_args_have(a, 4)) return RAD_E_INVAL;
     const RadTensor *k = &a->t[0], *v = &a->t[1], *sm = &a->t[2], *kv = &a->t[3];
@@ -1020,10 +1019,9 @@ AVX_KERNEL(kv_store) {
     if (M <= 0 || numel(k) < M * kv_heads * head_dim) return RAD_E_SHAPE;
     const int64_t n_blocks = kv->rank == 4 ? kv->shape[0] : 0;
 
-    /* `k` AND `v` ARRIVE RANK 2 FROM AN ARCHITECTURE THAT DOES NOT DE-INTERLEAVE ITS PROJECTION --
-     * a column slice of the fused QKV plane, whose row stride is the whole projection's width.
-     * Deriving the stride from the shape puts token 0 in the right slot and fills every later
-     * token's slot out of the previous token's query rows. libref's reading, through row_stride. */
+    /* `k` and `v` may arrive rank 2 as column slices of the fused QKV plane, whose row stride is
+     * the whole projection's width, so the stride comes from row_stride, not the shape (as in
+     * libref). */
     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);
@@ -1031,95 +1029,70 @@ AVX_KERNEL(kv_store) {
     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 KVView kvv = kv_view(kv, head_dim, block_size, kv_heads);
+    /* An fp8 cache stores k / k_scale and v / v_scale, the scales being the reader's descales
+     * (default 1.0), as libref and libr4d store it. A wider cache stores the value itself. */
+    const bool  fp8 = kv->dtype == RAD_F8E4M3 || kv->dtype == RAD_F8E5M2;
+    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;
 
-    /* Validated before the loop, because an OpenMP body cannot return. */
+    /* Validated before the loop; an OpenMP body cannot return. */
     for (int64_t t = 0; t < M; ++t) {
         const int64_t slot = ldi(sm, offlin(sm, t));
         if (slot >= 0 && n_blocks > 0 && slot / block_size >= n_blocks) return RAD_E_SHAPE;
     }
 
-    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;
-        float* buf = scratch_f32((size_t)head_dim);
-        for (int64_t h = 0; h < kv_heads; ++h) {
-            const int64_t cb = blk * kvv.sb + h * kvv.sh + off * kvv.so;
-            /* The head at a time, through the row converter, so a bf16 cache fed a bf16 activation
-             * is a widen and a narrow of a whole head rather than 2*head_dim dtype switches. The
-             * strided case falls back per element, which is what a non-unit cache stride means. */
-            if (k_ds == 1 && kvv.sd == 1) {
-                row_to_f32(k->dtype, byte_at(k->data, k->dtype, t * k_rs + h * k_hs), buf, head_dim);
-                out_row(kv, cb, head_dim, buf);
-            } else {
-                for (int64_t d = 0; d < head_dim; ++d)
-                    stt(kv, cb + d * kvv.sd, ldt(k, t * k_rs + h * k_hs + d * k_ds));
-            }
-            if (v_ds == 1 && kvv.sd == 1) {
-                row_to_f32(v->dtype, byte_at(v->data, v->dtype, t * v_rs + h * v_hs), buf, head_dim);
-                out_row(kv, cb + head_dim, head_dim, buf);
-            } else {
-                for (int64_t d = 0; d < head_dim; ++d)
-                    stt(kv, cb + (head_dim + d) * kvv.sd, ldt(v, t * v_rs + h * v_hs + d * v_ds));
-            }
-        }
-    }
+    if (ks != 1.0f || vs != 1.0f)
+        kv_scatter(k, v, sm, kv, kvv, M, kv_heads, head_dim, block_size, k_rs, k_hs, k_ds,
+                         v_rs, v_hs, v_ds, ks, vs);
+    else
+        kv_scatter(k, v, sm, kv, kvv, M, kv_heads, head_dim, block_size, k_rs, k_hs, k_ds,
+                          v_rs, v_hs, v_ds, ks, vs);
     return RAD_OK;
 }
 
 /* ================================================================== rotary
  *
- * NeoX pairs element i with i + rotary_dim/2; GPT-J (the "interleaved" style) pairs 2i with 2i+1.
- * Which one a checkpoint wants is a property of the checkpoint, so it is a parameter and not a
- * guess -- and getting it wrong produces fluent text with a broken sense of position, which is the
- * hardest kind of wrong to notice.
+ * NeoX pairs element i with i + rotary_dim/2; GPT-J ("interleaved") pairs 2i with 2i+1. The style
+ * is a checkpoint property and therefore a parameter; the wrong one still produces fluent text
+ * with broken positions.
  *
- * THE ANGLE TABLE IS THE WHOLE OPTIMISATION HERE. libref computes
- * `1/pow(theta, 2i/rot)` and then a cos and a sin FOR EVERY (token, head, i) -- three libm calls
- * per element, on an op that otherwise does two multiplies and an add. But the angle depends only
- * on (position, i): every head of a token wants the same cos/sin. Building the row's table once
- * and reusing it across all n_head + n_head_kv heads removes (heads - 1)/heads of the transcendental
- * work, which at 32 heads is 97% of it, and the values are identical because they are the same
- * computation performed once instead of many times -- so this is bit-identical, not merely close.
+ * libref computes 1/pow(theta, 2i/rot) and a cos and sin for every (token, head, i). The angle
+ * depends only on (position, i), so here each token's cos/sin table is built once and reused for
+ * all n_head + n_head_kv heads, and the inverse frequencies once per launch. Same computations,
+ * so bit-identical.
  *
- * The inverse frequencies depend only on `i` and are built ONCE PER LAUNCH for the same reason.
- *
- * What is NOT vectorised is the cos/sin themselves: a vector sincos is a polynomial with its own
- * accuracy, and `rope` feeds a position signal where a fraction of a ULP is exactly the error that
- * produces fluent text with wrong positions. The table makes them rare enough not to matter. */
-/* The multi-component modes (docs/OPS.md, `rope`): which position component drives each of the
- * rot/2 frequencies, and for `axial` a ladder per section. libref's rope_freqs states the same
- * rule; the two are checked against each other by avx_check. */
+ * cos/sin stay libm calls: a vector sincos would be a polynomial with its own accuracy, and
+ * positions are sensitive to fractions of an ulp. */
+/* Multi-component modes (docs/OPS.md, `rope`): which position component drives each of the rot/2
+ * frequencies, and for `axial` a frequency ladder per section. Same rule as libref's rope_freqs. */
 enum { ROPE_NEOX = 0, ROPE_GPTJ = 1, ROPE_MROPE = 2, ROPE_IMROPE = 3, ROPE_AXIAL = 4 };
 
-/* cos in [0, half), sin in [half, rot). Same layout `rope_table` writes, deliberately.
+/* cos in [0, half), sin in [half, rot): the layout `rope_table` writes.
  *
- * NOT sincosf: it is bit-identical to the two separate calls over a sweep of millions of angles,
- * but measures SLOWER than them, because glibc's joint wrapper costs more than two fast-path
- * calls. */
+ * Not sincosf: it gives the same bits but glibc's joint wrapper is slower than two separate
+ * fast-path calls. */
 static void angles(float* cs, const float* invf, int64_t half, float pos) {
     for (int64_t i = 0; i < half; ++i) {
         const float ang = pos * invf[i];
-        cs[i] = std::cos(ang);
-        cs[half + i] = std::sin(ang);
+        cs[i] = sc_cos(ang);
+        cs[half + i] = sc_sin(ang);
     }
 }
 
-/* ...and with a position per component, `comp[i]` naming the one frequency i reads. */
+/* As `angles`, with a position per component; frequency i reads component comp[i]. */
 static void angles_multi(float* cs, const float* invf, const int* comp, int64_t half,
                          const float* pos) {
     for (int64_t i = 0; i < half; ++i) {
         const float ang = pos[comp[i]] * invf[i];
-        cs[i] = std::cos(ang);
-        cs[half + i] = std::sin(ang);
+        cs[i] = sc_cos(ang);
+        cs[half + i] = sc_sin(ang);
     }
 }
 
 static void rope_head(const RadTensor* t, int64_t base, int64_t ds, int64_t rot, int mode,
                       const float* cs, int64_t half, float* buf) {
     if (mode == ROPE_NEOX && ds == 1) {
-        /* x0 and x1 are two contiguous runs of `half`, so the whole rotation is vector work. */
+        /* x0 and x1 are contiguous runs of `half`, so the rotation is all vector work. */
         row_to_f32(t->dtype, byte_at(t->data, t->dtype, base), buf, rot);
         int64_t i = 0;
         for (; i + VF_N <= half; i += VF_N) {
@@ -1136,9 +1109,8 @@ static void rope_head(const RadTensor* t, int64_t base, int64_t ds, int64_t rot,
         out_row(t, base, rot, buf);
         return;
     }
-    /* GPT-J's interleave, and every strided case. The pairs are adjacent, so a vector form needs a
-     * de-interleave and a re-interleave for two multiplies -- not worth the code on a layout only
-     * older checkpoints use. */
+    /* GPT-J's interleave and every strided case, scalar: adjacent pairs would need a
+     * de-interleave and re-interleave, not worth it for a layout only older checkpoints use. */
     for (int64_t i = 0; i < half; ++i) {
         const int64_t i0 = (mode == ROPE_GPTJ) ? 2 * i : i;
         const int64_t i1 = (mode == ROPE_GPTJ) ? 2 * i + 1 : i + half;
@@ -1149,19 +1121,18 @@ static void rope_head(const RadTensor* t, int64_t base, int64_t ds, int64_t rot,
     }
 }
 
-/* `den` is the width the base ladder is measured in: `rot` for a `rotary` ladder (a partial rotary
- * is a complete rotation of its own width) and `head_dim` for `head`, the proportional variant.
- * Shared by `rope` and `rope_table` because the two must compute the same angles. */
+/* Inverse frequencies. `den` is the width the frequency ladder is measured in: `rot` for a `rotary`
+ * ladder (a partial rotary is a full rotation of its own width), `head_dim` for `head` (the
+ * proportional variant). Shared by `rope` and `rope_table` so both compute the same angles. */
 static float* inv_freqs(int64_t half, int64_t den, float theta) {
     float* f = (float*)scratch_raw((size_t)half * sizeof(float));
     for (int64_t i = 0; i < half; ++i)
-        f[i] = 1.0f / std::pow(theta, (float)(2 * i) / (float)den);
+        f[i] = 1.0f / sc_pow(theta, (float)(2 * i) / (float)den);
     return f;
 }
 
-/* `ladder` names the width the base frequency ladder is measured in -- see inv_freqs. Absent and
- * `rotary` divide by `rot` (every existing model); `head` divides by `head_dim`, which it needs. An
- * unknown value is a schema error, not a silent default. */
+/* Resolves the `ladder` parameter (see inv_freqs): absent or `rotary` gives `rot`, `head` gives
+ * `head_dim`. Unknown values are refused. */
 static int rope_ladder(const RadArgs* a, int64_t rot, int64_t head_dim, int64_t* den) {
     const char* lad = p_str(a, "ladder", nullptr);
     if (!lad) { *den = rot; return RAD_OK; }
@@ -1192,7 +1163,7 @@ AVX_KERNEL(rope) {
     const int lrc = rope_ladder(a, rot, head_dim, &den);
     if (lrc != RAD_OK) return lrc;
 
-    /* [M] one component a token, or [C, M] component-major with `sections`. */
+    /* Positions: [M], one component per token, or [C, M] component-major with `sections`. */
     int64_t sec[8] = {};
     int n_sec = 0;
     for (const char* v = p_str(a, "sections", nullptr); v && *v && n_sec < 8;) {
@@ -1214,14 +1185,14 @@ AVX_KERNEL(rope) {
     if (M <= 0 || numel(qkv) < M * stride_row) return RAD_E_SHAPE;
     const int64_t rs = qkv->rank >= 2 ? qkv->stride[qkv->rank - 2] : stride_row;
     const int64_t ds = laststride(qkv);
-    /* THE PROPORTIONAL LADDER (`head`) is HF's: the rotation spans the whole head -- pair i is
-     * (i, i + head_dim/2) -- and every frequency past rotary_dim/2 is zero (libref, ref_rope). */
+    /* The proportional ladder (`head`) is HF's: the rotation spans the whole head (pair i is
+     * (i, i + head_dim/2)) and every frequency past rotary_dim/2 is zero (libref: ref_rope). */
     const int64_t nfreq = rot / 2;
     if (den == head_dim && rot < head_dim && !multi && mode == ROPE_NEOX) rot = head_dim;
     const int64_t half = rot / 2;
+    if (half > AVX_HD_MAX / 2) return RAD_E_UNSUPPORTED;
     float* invf = inv_freqs(half, den, theta);
-    int comp[512] = {};
-    if (half > 512) return RAD_E_UNSUPPORTED;
+    int comp[AVX_HD_MAX / 2];          /* filled and read only for multi-component positions */
     if (multi) {
         int64_t start[8] = {}, total = 0;
         for (int c = 0; c < n_sec; ++c) { start[c] = total; total += sec[c]; }
@@ -1231,7 +1202,7 @@ AVX_KERNEL(rope) {
             if (mode == ROPE_MROPE || mode == ROPE_AXIAL) {
                 while (c + 1 < n_sec && i >= start[c + 1]) ++c;
                 if (mode == ROPE_AXIAL)
-                    invf[i] = 1.0f / std::pow(theta, (float)(2 * (i - start[c])) /
+                    invf[i] = 1.0f / sc_pow(theta, (float)(2 * (i - start[c])) /
                                                      (float)(2 * sec[c]));
             } else if (mode == ROPE_IMROPE) {
                 if (i % 3 == 1 && i < 3 * sec[1]) c = 1;
@@ -1265,8 +1236,7 @@ AVX_KERNEL(rope) {
         }
         if (yarn.factor != 0.0f)
             for (int64_t i = 0; i < rot; ++i) cs[i] *= yarn.magnitude;
-        /* Q heads then K heads. The V heads that follow are left alone, which is the whole reason
-         * this op takes the fused qkv rather than two tensors. */
+        /* Q heads, then K heads; the V heads that follow in the fused qkv are left alone. */
         for (int64_t h = 0; h < n_head + n_head_kv; ++h)
             rope_head(qkv, row + h * head_dim * ds, ds, rot, pair_mode, cs, half, buf);
     }
@@ -1274,14 +1244,11 @@ AVX_KERNEL(rope) {
 }
 
 /* ------------------------------------------------------------------ qk_norm_rope */
-/* An RMS norm over each head against its own gain, then RoPE.
+/* Per-head RMS norm with its own gain, then RoPE.
  *
- * THE NORM OUTPUT IS ROUNDED TO THE TENSOR'S DTYPE BEFORE THE ROTATION. That is not an accident of
- * writing it back in place -- it is what the unfused pair does, because the norm stores a tensor
- * and the rotation reads it, and libr4d's r4d_qk_norm_rope_gate matches the unfused reference for
- * exactly this reason. A fused kernel that kept f32 across the seam would be half an ulp better
- * and would fail a comparison against this. So the norm is written with out_row and the rotation
- * re-reads it, rather than being carried in registers. */
+ * The norm output is rounded to the tensor's dtype before the rotation, as the unfused pair does
+ * (and libr4d's r4d_qk_norm_rope_gate matches): it is stored with out_row and re-read by the
+ * rotation rather than kept in f32. */
 AVX_KERNEL(qk_norm_rope) {
     if (!rad_args_have(a, 4)) return RAD_E_INVAL;
     const RadTensor *qkv = &a->t[0], *pos = &a->t[1], *qw = &a->t[2], *kw = &a->t[3];
@@ -1294,18 +1261,34 @@ AVX_KERNEL(qk_norm_rope) {
     const float rscale = p_f32(a, "scale", 1.0f);
     const float wadd = p_f32(a, "wadd", 0.0f);
     const int v_norm = (int)p_int(a, "v_norm", 0);
-    static const char* kModes[] = { "neox", "gptj", "blocks" };
-    const int mode = p_enum(a, "mode", kModes, 3, ROPE_NEOX);
+    /* libref's modes: `gptj_blocks` is `blocks` with each section's pairs adjacent, (start + 2j,
+     * start + 2j + 1), Qwen-Image's 3-axis rotary; `imrope` is `rope`'s interleaved M-RoPE over
+     * NeoX pairs (Qwen3-VL's text attention). */
+    static const char* kModes[] = { "neox", "gptj", "blocks", "gptj_blocks", "imrope" };
+    const int mode = p_enum(a, "mode", kModes, 5, ROPE_NEOX);
     if (mode < 0) return RAD_E_UNSUPPORTED;
-    const bool blocks = mode == 2;
+    const bool blocks = mode == 2 || mode == 3;
+    const bool adjacent = mode == 3;
+    const bool im = mode == 4;
     const int64_t rot = p_int(a, "rotary_dim", head_dim);
     if (head_dim <= 0 || n_head <= 0 || rot <= 0 || rot > head_dim || (rot & 1)) return RAD_E_SHAPE;
     if (numel(qw) < head_dim || numel(kw) < head_dim) return RAD_E_SHAPE;
 
-    /* BLOCKS (libref): section c is sec[c] pairs over its own 2 * sec[c] channels, paired
-     * (start + j, start + sec[c] + j), turned by position component comps[c]. */
+    /* `blocks` mode (libref): section c is sec[c] pairs over its own 2 * sec[c] channels, paired
+     * (start + j, start + sec[c] + j), rotated by position component comps[c]. */
     int64_t sec[8] = {}, comp[8] = {};
     int n_sec = 0;
+    if (im) {
+        for (const char* v = p_str(a, "sections", nullptr); v && *v && n_sec < 8; ) {
+            char* end = nullptr;
+            const long long x = std::strtoll(v, &end, 10);
+            if (end == v) break;
+            if (x <= 0) return RAD_E_SHAPE;
+            sec[n_sec++] = x;
+            v = end;
+        }
+        if (n_sec < 3) return RAD_E_SHAPE;
+    }
     if (blocks) {
         for (const char* v = p_str(a, "sections", nullptr); v && *v && n_sec < 8; ) {
             char* end = nullptr;
@@ -1333,8 +1316,9 @@ AVX_KERNEL(qk_norm_rope) {
     }
     const bool multi = pos->rank >= 2;
     const int64_t n_comp = multi ? pos->shape[0] : 1;
-    if (multi && !blocks) return RAD_E_SHAPE;
-    for (int c = 0; c < n_sec; ++c)
+    if (multi && !blocks && !im) return RAD_E_SHAPE;
+    if (multi && im && n_comp < 3) return RAD_E_SHAPE;
+    for (int c = 0; blocks && c < n_sec; ++c)
         if (comp[c] < 0 || comp[c] >= n_comp || n_comp > 8) return RAD_E_SHAPE;
     const int64_t pcs = multi ? pos->stride[0] : 0, pms = multi ? pos->stride[1] : 0;
 
@@ -1345,22 +1329,28 @@ AVX_KERNEL(qk_norm_rope) {
     const int64_t ds = laststride(qkv);
     const int64_t half = rot / 2;
 
-    /* One arena call for the launch-invariant tables: the inverse frequencies (and, for blocks,
-     * each pair's component) and both widened gains. A second scratch_raw would reallocate under
-     * the parallel region. */
+    /* One scratch_raw call for the launch-invariant tables (inverse frequencies, each pair's
+     * component for blocks, both gains); a second could reallocate under the parallel region. */
     float* tab = (float*)scratch_raw((size_t)(2 * half + 2 * head_dim) * sizeof(float) + 64);
     float* invf = tab;
     float* pcomp = tab + half;
     float* gq = tab + 2 * half;
     float* gk = tab + 2 * half + head_dim;
+    /* imrope's component per frequency, as libref's rope_freqs: 1 where i % 3 == 1 and
+     * i < 3 * sec[1], 2 where i % 3 == 2 and i < 3 * sec[2], 0 elsewhere. */
+    const bool by_comp = blocks || (im && multi);
     if (!blocks) {
-        for (int64_t i = 0; i < half; ++i)
-            invf[i] = 1.0f / std::pow(theta, (float)(2 * i) / (float)rot);
+        for (int64_t i = 0; i < half; ++i) {
+            invf[i] = 1.0f / sc_pow(theta, (float)(2 * i) / (float)rot);
+            pcomp[i] = !im ? 0.0f
+                     : (i % 3 == 1 && i < 3 * sec[1]) ? 1.0f
+                     : (i % 3 == 2 && i < 3 * sec[2]) ? 2.0f : 0.0f;
+        }
     } else {
         int64_t i = 0;
         for (int c = 0; c < n_sec; ++c)
             for (int64_t j = 0; j < sec[c]; ++j, ++i) {
-                invf[i] = 1.0f / std::pow(theta, (float)j / (float)sec[c]);
+                invf[i] = 1.0f / sc_pow(theta, (float)j / (float)sec[c]);
                 pcomp[i] = (float)comp[c];
             }
     }
@@ -1374,19 +1364,32 @@ AVX_KERNEL(qk_norm_rope) {
         const float div = rscale != 0.0f ? rscale : 1.0f;
         float pc[8];
         if (multi)
-            for (int64_t c = 0; c < n_comp; ++c) pc[c] = (float)ldi(pos, c * pcs + m * pms) / div;
+            for (int64_t c = 0; c < n_comp && c < 8; ++c)
+                pc[c] = (float)ldi(pos, c * pcs + m * pms) / div;
         else
             pc[0] = (float)ldi(pos, offlin(pos, m)) / div;
         const int64_t row = m * rs;
-        float* cs = scratch_f32((size_t)rot);
+        /* cos and sin, then for adjacent pairs the same per rotated channel: cc[2i] = cc[2i+1]
+         * = cos_i, ss[2i] = -sin_i, ss[2i+1] = sin_i, so channel d becomes
+         * x[d] * cc[d] + x[d ^ 1] * ss[d] (x0 c - x1 s, x0 s + x1 c) in whole vectors. */
+        float* cs = scratch_f32((size_t)(3 * rot));
+        float* cc = cs + rot;
+        float* ss = cs + 2 * rot;
         float* buf = scratch_f32_b((size_t)head_dim);
         float* rbuf = scratch_f32_c((size_t)head_dim);
-        if (!blocks) angles(cs, invf, half, pc[0]);
+        if (!by_comp) angles(cs, invf, half, pc[0]);
         else
             for (int64_t i = 0; i < half; ++i) {
                 const float ang = pc[(int)pcomp[i]] * invf[i];
-                cs[i] = std::cos(ang);
-                cs[half + i] = std::sin(ang);
+                cs[i] = sc_cos(ang);
+                cs[half + i] = sc_sin(ang);
+            }
+        const bool pairs_vec = adjacent && ds == 1;
+        if (pairs_vec)
+            for (int64_t i = 0; i < half; ++i) {
+                cc[2 * i] = cc[2 * i + 1] = cs[i];
+                ss[2 * i] = -cs[half + i];
+                ss[2 * i + 1] = cs[half + i];
             }
         for (int64_t h = 0; h < n_head + n_head_kv; ++h) {
             const float* g = h < n_head ? gq : gk;
@@ -1398,18 +1401,40 @@ AVX_KERNEL(qk_norm_rope) {
             for (; d + VF_N <= head_dim; d += VF_N)
                 vf_storeu(rbuf + d, vf_mul(vf_mul(vf_loadu(xv + d), vs), vf_loadu(g + d)));
             for (; d < head_dim; ++d) rbuf[d] = xv[d] * sc * g[d];
-            /* Written back through the operand's dtype, then re-read by the rotation -- the
-             * rounding across the seam is the contract. */
+            /* Store through the operand's dtype; the rotation re-reads it (see above). */
             if (ds == 1) out_row(qkv, base, head_dim, rbuf);
             else for (int64_t i = 0; i < head_dim; ++i) stt(qkv, base + i * ds, rbuf[i]);
             if (!blocks) {
-                rope_head(qkv, base, ds, rot, mode, cs, half, rbuf);
+                rope_head(qkv, base, ds, rot, im ? (int)ROPE_NEOX : mode, cs, half, rbuf);
+                continue;
+            }
+            if (pairs_vec) {
+                /* The stored (rounded) row, rotated a vector at a time; channels past `rot`
+                 * are rewritten unchanged. */
+                row_to_f32(qkv->dtype, byte_at(qkv->data, qkv->dtype, base), buf, head_dim);
+                int64_t d = 0;
+#if AVX_LEVEL >= 1
+                for (; d + VF_N <= rot; d += VF_N) {
+                    const vf x = vf_loadu(buf + d);
+#if AVX_LEVEL == 3
+                    const vf xs = _mm512_permute_ps(x, 0xB1);
+#else
+                    const vf xs = _mm256_permute_ps(x, 0xB1);
+#endif
+                    vf_storeu(rbuf + d, vf_add(vf_mul(x, vf_loadu(cc + d)),
+                                               vf_mul(xs, vf_loadu(ss + d))));
+                }
+#endif
+                for (; d < rot; ++d) rbuf[d] = buf[d] * cc[d] + buf[d ^ 1] * ss[d];
+                for (; d < head_dim; ++d) rbuf[d] = buf[d];
+                out_row(qkv, base, head_dim, rbuf);
                 continue;
             }
             int64_t i = 0, start = 0;
             for (int c = 0; c < n_sec; ++c) {
                 for (int64_t j = 0; j < sec[c]; ++j, ++i) {
-                    const int64_t i0 = start + j, i1 = start + sec[c] + j;
+                    const int64_t i0 = adjacent ? start + 2 * j : start + j;
+                    const int64_t i1 = adjacent ? start + 2 * j + 1 : start + sec[c] + j;
                     const float x0 = ldt(qkv, base + i0 * ds), x1 = ldt(qkv, base + i1 * ds);
                     stt(qkv, base + i0 * ds, x0 * cs[i] - x1 * cs[half + i]);
                     stt(qkv, base + i1 * ds, x0 * cs[half + i] + x1 * cs[i]);
@@ -1417,7 +1442,7 @@ AVX_KERNEL(qk_norm_rope) {
                 start += 2 * sec[c];
             }
         }
-        /* v_norm: the v heads RMS-normed with a unit gain and not rotated (libref). */
+        /* v_norm: V heads RMS-normed with unit gain, not rotated (libref). */
         for (int64_t h = 0; v_norm && h < n_head_kv; ++h) {
             const int64_t base = row + (n_head + n_head_kv + h) * head_dim * ds;
             const float* xv = head_f32(qkv, base, ds, head_dim, 1.0f, buf);
@@ -1431,14 +1456,11 @@ AVX_KERNEL(qk_norm_rope) {
 }
 
 /* ------------------------------------------------------------------ rope_table */
-/* The cos/sin plane a fused prologue reads instead of theta, written at each position's OWN row of
- * a [max_ctx, rot] table: `rot` values a row, cos for the first rot/2 and sin for the second.
+/* The cos/sin plane a fused prologue reads instead of theta: row `pos` of a [max_ctx, rot] table,
+ * cos in the first rot/2 values and sin in the second.
  *
- * THE ANGLES ARE `rope`'s, TO THE LAST OPERATION, and that is the whole contract: a fused rotation
- * reading a table built any other way would be a different model by a fraction of a ULP per
- * element -- fluent text, subtly wrong positions. So the two share `inv_freqs` and `angles` rather
- * than each computing the angle their own way. Only the rows `positions` names are written; a
- * negative position is a padded row and writes nothing. */
+ * The angles must equal `rope`'s exactly, so both use `inv_freqs` and `angles`. Only rows named by
+ * `positions` are written; a negative position (padding) writes nothing. */
 AVX_KERNEL(rope_table) {
     if (!rad_args_have(a, 2)) return RAD_E_INVAL;
     const RadTensor *pos = &a->t[0], *cs = &a->t[1];
@@ -1470,8 +1492,7 @@ AVX_KERNEL(rope_table) {
         angles(buf, invf, half, p);
         if (yarn.factor != 0.0f)
             for (int64_t i = 0; i < rot; ++i) buf[i] *= yarn.magnitude;
-        /* `cs` may be strided, and offlin has to be evaluated per element there -- which is what
-         * libref does unconditionally. The dense case is one row store. */
+        /* Dense: one row store. Strided: offlin per element, as libref always does. */
         if (rad_tensor_is_contiguous(cs)) {
             out_row(cs, pp * rot, rot, buf);
         } else {
@@ -1484,8 +1505,8 @@ AVX_KERNEL(rope_table) {
 /* ------------------------------------------------------------------ qsa_block_key */
 /* QSA's compressed key (docs/OPS.md): a block's `ratio` rows of k averaged in f32 and rounded to
  * k's dtype, RMS-normed with gain (wadd + w), then NeoX-rotated over `rotary_dim` at the block's
- * position, YaRN included. libref's arithmetic in libref's order; what differs is that the angles
- * of a block come from one `angles` table, and the inverse frequencies are built once a launch. */
+ * position, YaRN included. libref's arithmetic and order; the block's angles come from one
+ * `angles` table and the inverse frequencies are built once per launch. */
 AVX_KERNEL(qsa_block_key) {
     const RadTensor* k = rad_arg_in(a, 0);
     const RadTensor* w = rad_arg_in(a, 1);
@@ -1496,7 +1517,7 @@ AVX_KERNEL(qsa_block_key) {
     const int64_t n = p_int(a, "n", 0), ratio = p_int(a, "ratio", 0);
     const int64_t rot = p_int(a, "rotary_dim", 0), pos0 = p_int(a, "pos0", -1);
     if (n <= 0 || ratio <= 0 || (pos0 < 0 && !pos)) return RAD_E_INVAL;
-    if (rot < 0 || rot > n || (rot & 1) || rot / 2 > 512) return RAD_E_SHAPE;
+    if (rot < 0 || rot > n || (rot & 1) || rot / 2 > AVX_HD_MAX / 2) return RAD_E_SHAPE;
     if (p_int(a, "block_size", ratio) != ratio) return RAD_E_SHAPE;
     if (k->rank != 2 || out->rank < 2 || out->shape[0] < 1) return RAD_E_SHAPE;
     const int64_t M = page ? numel(page) : out->shape[0];
@@ -1520,14 +1541,14 @@ AVX_KERNEL(qsa_block_key) {
         sec[n_sec++] = x;
         v = e;
     }
-    /* Several components only with a mode, its sections and three columns of `pos`. */
+    /* Multi-component positions need a mode, its sections and three columns of `pos`. */
     const bool mc = mi != 0 && n_sec > 0 && pos2 && pos->shape[1] >= 3;
     const RadYarn yarn = rad_yarn_args(a);
     if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && (rot <= 0 || rscale != 1.0f)))
         return RAD_E_INVAL;
     const int64_t half = rot / 2;
     float* invf = inv_freqs(half, rot, theta);
-    int comp[512] = {};
+    int comp[AVX_HD_MAX / 2];          /* filled and read only when `mc` */
     if (mc) {
         int64_t total = 0;
         for (int c = 0; c < n_sec; ++c) total += sec[c];
diff --git a/libavx/avx_bench.cpp b/libavx/avx_bench.cpp
index 63ae3582..07922aa4 100644
--- a/libavx/avx_bench.cpp
+++ b/libavx/avx_bench.cpp
@@ -1,46 +1,33 @@
-/* avx_bench.cpp -- rad-avx-bench: what this machine can do, and what libavx gets of it.
+/* avx_bench.cpp -- rad-avx-bench: this machine's measured ceilings, and what libavx reaches.
  *
- * ============================== A SPEEDUP AGAINST libref IS NOT A RESULT ==============================
+ * A speedup over libref (a scalar loop nest with a per-element dtype switch) says more about
+ * libref than about libavx. So each op is also reported as a rate to compare against this
+ * machine's ceilings, measured by --peak rather than taken from a spec sheet (memory population,
+ * thermal limits and firmware settings only show up when measured). The libref ratio stays: it
+ * shows an op is wired at all, and a kernel slower than the reference is a defect.
  *
- * libref is a nest of scalar loops with a per-element dtype switch and it says so in its own
- * header. "libavx is 14x libref" is therefore a statement about libref, and this tool refuses to
- * print it as though it were a statement about libavx. What it prints beside every op is the
- * fraction of THIS MACHINE'S measured ceiling the kernel reaches -- and the ceiling is measured
- * here, by --peak, rather than quoted off a spec sheet, because a spec sheet describes a part and
- * not the machine it is in: a memory channel population, a thermal cap or a firmware setting that
- * parks a link costs real throughput and shows up only under measurement.
- *
- * The libref column stays, because the ratio is what says an op is WIRED AT ALL, and because a
- * kernel that is slower than the reference is a real and findable defect. It is reported as what
- * it is.
- *
- * ============================== THE THINGS THAT MAKE A HOST BENCH LIE ==============================
- *
- * Each of these is a way a host benchmark quietly measures something other than the kernel:
- *
- *   AN INOUT OPERAND ACCUMULATES ACROSS ITERATIONS. A twenty-iteration loop over `rope` leaves the
- *   tensor rotated twenty-one times, and a harness that does not reset between iterations reports
- *   a large error for a correct kernel. Timing is not immune -- an op whose cost depends on its input
- *   (every sampler that narrows in place) measures something different each time round. h_reset
- *   restores the drawn bytes between iterations and its cost is excluded from the timing.
- *
- *   A CACHE-WARM LOOP CANNOT RANK A BANDWIDTH-BOUND KERNEL. Running the same 40 KB row a thousand
- *   times measures L1, so a warm loop ranks kernels by how they behave in cache and not by the
- *   bandwidth they need. --cold walks a working set larger than L3 between iterations; the default
- *   is warm and the column says which it is.
- *
- *   THE FIRST CALL IS NOT THE STEADY STATE. The thread_local scratch arenas allocate on their
- *   first use at a size, so iteration one includes a malloc per thread. Warm-up iterations run
- *   before the clock starts.
- *
- *   A MEDIAN, NOT A MEAN. One preempted iteration moves a mean and does not move a median, and on
- *   any machine that is also doing something else there is always one.
+ * Measurement hygiene:
+ *   - INOUT operands are reset to the drawn bytes between iterations (h_reset), outside the
+ *     clock; otherwise each iteration computes something different (rope rotates again, samplers
+ *     narrow an already narrowed set).
+ *   - Loops are cache-warm, so bandwidth-bound kernels are ranked by in-cache behaviour; the
+ *     output says so.
+ *   - Warm-up iterations run first, since the thread-local scratch arenas allocate on first use.
+ *   - Per-op times are medians, robust to a preempted iteration.
+ *   - --cold flushes the case's operands from every cache before each timed launch, for an op
+ *     whose working set fits this part's L3 at model shape but not beside the rest of a model's
+ *     step (the QSA indexer's block keys); the flush is outside the clock.
  */
 #include "avx_harness.h"
 #include "avx_isa.h"
+#include "avx_planes.h"
 
 #include 
 #include 
+#include 
+#include 
+
+#include    /* _mm_clflush, _mm_mfence: SSE2, the x86-64 baseline */
 
 #ifdef _OPENMP
 #include 
@@ -60,31 +47,24 @@ static double median(std::vector& v) {
 
 /* ================================================================== the machine's ceilings
  *
- * MEASURED, NOT QUOTED. Three numbers, and each is the ceiling for a different class of op here:
+ * Measured ceilings, one per class of op:
  *
- *   FMA THROUGHPUT bounds the GEMMs. A dependency-free chain of FMAs on enough accumulators to
- *   cover the latency, all in registers, nothing touching memory. What comes out is what the
- *   machine can retire, including whatever clock it actually holds under a vector load -- which on
- *   a part with an AVX-512 offset is not the advertised boost.
+ *   FMA throughput bounds the GEMMs: independent in-register FMA chains, at the clock the core
+ *   holds under vector load (below advertised boost on parts with an AVX-512 offset).
  *
- *   L1 BANDWIDTH bounds every elementwise op at a shape that fits, which is most of a decode step.
+ *   L1 bandwidth bounds elementwise ops at shapes that fit, most of a decode step.
  *
- *   DRAM BANDWIDTH bounds everything at prefill shapes and bounds `logits_gemm` always: a 248K
- *   vocabulary weight does not fit in any cache, so that op is a memory benchmark wearing a GEMM's
- *   name whatever the flops say.
+ *   DRAM bandwidth bounds prefill shapes, and always bounds `logits_gemm` (a 248K-vocabulary
+ *   weight fits no cache).
  *
- * All three are single-threaded by default and scale with --threads, because a per-core ceiling is
- * what an op that runs one row per thread is actually up against.
+ * The memory triads use --threads (default 1); the FMA probe is single-threaded.
  */
 static void bench_peak(Lib& avx, int threads) {
     std::printf("\n== machine ceilings (measured here, not quoted) ==\n");
 
-    /* ---- FMA, PER ISA LEVEL, measured inside the plugin. It has to be: this file is
-     * baseline-compiled like the dispatcher (see avx_dispatch.cpp) and can only emit SSE2, so a
-     * ceiling computed here would be ten times below what an AVX-512 GEMM is actually up against
-     * and every kernel would look like it was doing well. `avx_peak_fma` runs the probe compiled
-     * with the level's own flags and hands back the FLOPS PERFORMED; the clock stays here, because
-     * it is here that the median over repetitions is taken. */
+    /* ---- FMA per ISA level, measured inside the plugin: this file is baseline-compiled and
+     * could only measure SSE2. `avx_peak_fma` runs the level's probe and returns the flops
+     * performed; timing happens here. */
     auto peak = (double (*)(int, int64_t))dlsym(avx.h, "avx_peak_fma");
     if (peak) {
         for (int lvl = 0; lvl < AVX_N_LEVELS; ++lvl) {
@@ -101,18 +81,16 @@ static void bench_peak(Lib& avx, int threads) {
                 const double dt = now_s() - t0;
                 rates.push_back(fl / dt);
             }
-            /* The BEST of five, not the median: this is a CEILING, and a repetition that was
-             * preempted or ran at a lower clock is not evidence the machine cannot do better. The
-             * per-op numbers below take the median instead, for the opposite reason -- there the
-             * question is what a kernel does in practice. */
+            /* Best of five, since this is a ceiling (a preempted or down-clocked repetition says
+             * nothing about the limit). Per-op timings use the median. */
             std::sort(rates.begin(), rates.end());
             std::printf("  FMA %-18s %8.2f GFLOP/s  (1 thread, in-register, no memory traffic)\n",
                         avx.isa_name(lvl), rates.back() / 1e9);
         }
     }
 
-    /* ---- memory, at three working-set sizes. A read-modify-write triad (a[i] = b[i] + s*c[i])
-     * because that is the traffic shape every elementwise op here has: two streams in, one out. */
+    /* ---- memory at three working-set sizes. A triad (a[i] = b[i] + s*c[i]): two streams in,
+     * one out, the traffic shape of the elementwise ops. */
     auto triad = [&](size_t bytes_per_array, const char* label) {
         const size_t n = bytes_per_array / sizeof(float);
         std::vector A(n), B(n), C(n);
@@ -127,9 +105,8 @@ static void bench_peak(Lib& avx, int threads) {
             ts.push_back(now_s() - t0);
         }
         const double dt = median(ts);
-        /* Three arrays touched: two read, one written. The write also reads the line unless the
-         * store is non-temporal, which this is not -- so 3x is the honest count and 4x would be
-         * counting a read-for-ownership the compiler may or may not have elided. */
+        /* Counts three arrays (two read, one written); the store's read-for-ownership, which the
+         * compiler may or may not elide, is not counted. */
         std::printf("  triad %-15s %8.2f GB/s     (%zu threads, %.0f KiB working set)\n", label,
                     3.0 * (double)n * sizeof(float) / dt / 1e9, (size_t)threads,
                     3.0 * (double)bytes_per_array / 1024.0);
@@ -137,12 +114,36 @@ static void bench_peak(Lib& avx, int threads) {
     triad(16 * 1024, "L1");
     triad(512 * 1024, "L2");
     triad(256u * 1024 * 1024, "DRAM");
+
+    /* ---- a read-only stream over 768 MiB: the ceiling of an op that only reads, as the QSA
+     * indexer does its block keys. On parts whose core complexes reach memory through links
+     * narrower for writes than for reads, it exceeds the triad. */
+    {
+        /* An integer sum: this file is baseline-compiled, and a float sum may not be reassociated,
+         * so it would measure one add's latency instead of the memory. */
+        const size_t n = (768u << 20) / sizeof(uint64_t);
+        std::vector A(n, 1);
+        std::vector ts;
+        uint64_t sink = 0;
+        for (int rep = 0; rep < 7; ++rep) {
+            const double t0 = now_s();
+            uint64_t acc = 0;
+#ifdef _OPENMP
+#pragma omp parallel for schedule(static) num_threads(threads) reduction(+ : acc)
+#endif
+            for (int64_t i = 0; i < (int64_t)n; ++i) acc += A[(size_t)i];
+            ts.push_back(now_s() - t0);
+            sink += acc;
+        }
+        std::printf("  read  %-15s %8.2f GB/s     (%zu threads, %.0f KiB, sum %llu)\n", "DRAM",
+                    (double)n * sizeof(uint64_t) / median(ts) / 1e9, (size_t)threads,
+                    (double)n * sizeof(uint64_t) / 1024.0, (unsigned long long)sink);
+    }
 }
 
 /* ================================================================== conversion rates
- * The claim avx_support.cpp's header makes and does not carry the numbers for. Timed through the
- * PLUGIN's own `cast` op at each ISA level, which is the only way to time the conversion the
- * kernels actually use rather than a copy of it compiled here with different flags. */
+ * Timed through the plugin's own `cast` op at each ISA level, so the conversions measured are the
+ * ones the kernels use (avx_support.cpp). */
 static void bench_cvt(Lib& avx, Lib& ref) {
     std::printf("\n== dtype conversion, through `cast` (MB/s of SOURCE bytes) ==\n");
     const char* dts[] = { "bf16", "f16", "fp8_e4m3", "i8" };
@@ -194,6 +195,768 @@ static void bench_cvt(Lib& avx, Lib& ref) {
     if (avx.isa_force) avx.isa_force(AVX_N_LEVELS - 1);
 }
 
+/* ================================================================== the codebook experts
+ *
+ * moe_gemm_q over Qwen3.8-Flash-Next's served experts at the model's geometry on one rank: 512
+ * experts in two parity tables, top_k 10, gate_up [1280, 2560] and down [2560, 640], stored through
+ * libavx's own layout hooks. Every expert of a layer is resident (1.3 GB at w4nl64a8h) and each
+ * timed call draws a new routing, so a decode step reads its experts from DRAM as a served step
+ * does, not from the cache a repeated call would leave them in. Reported: the expert bytes a call
+ * reads (codes and scales of the experts it routes to) per second, against the DRAM triad, and
+ * FLOP/s against the FMA peak (--peak measures both). */
+namespace moebench {
+
+struct Form { const char* dtype; int bits; int64_t group; uint32_t sdt; bool level; };
+const Form kForms[] = {
+    { "w4nla8h",   4, 128, RAD_BF16,   false },
+    { "w4nl64a8h", 4, 64,  RAD_F8E4M3, true },
+    { "w4nl32a8h", 4, 32,  RAD_F8E4M3, true },
+    { "w5nl64a8h", 5, 64,  RAD_F8E4M3, true },
+};
+const float kW4nl[16] = { 1.125f, 3.25f, 5.5f, 8.0f, 11.0f, 14.0f, 18.0f, 22.0f,
+                          -1.125f, -3.25f, -5.5f, -8.0f, -11.0f, -14.0f, -18.0f, -22.0f };
+const float kW5nl[32] = { 0.8125f, 2.5f, 4.0f, 5.5f, 7.5f, 9.0f, 11.0f, 12.0f,
+                          14.0f, 16.0f, 18.0f, 20.0f, 22.0f, 24.0f, 26.0f, 30.0f,
+                          -0.8125f, -2.5f, -4.0f, -5.5f, -7.5f, -9.0f, -11.0f, -12.0f,
+                          -14.0f, -16.0f, -18.0f, -20.0f, -22.0f, -24.0f, -26.0f, -30.0f };
+
+constexpr int64_t kEmbd = 2560, kFF = 640, kExperts = 512, kTopK = 10;
+
+struct Buf {
+    uint8_t* p = nullptr;
+    int64_t  n = 0;
+    explicit Buf(int64_t bytes) : n(bytes) {
+        p = (uint8_t*)std::aligned_alloc(64, (size_t)((bytes + 63) / 64 * 64));
+    }
+    ~Buf() { std::free(p); }
+    Buf(const Buf&) = delete;
+    Buf& operator=(const Buf&) = delete;
+};
+
+/* One projection's experts, each view stored as libavx's row stores it. */
+struct Proj {
+    int64_t N = 0, K = 0;
+    std::vector> codes, scales;
+    uint32_t cdt = 0, sdt = 0;
+    int64_t  bytes_per_expert = 0;
+};
+
+/* The experts of one projection, every view through the row's layout hooks. False on a refusal. */
+bool build(const RadKernelInfo* k, const Form& f, int64_t N, int64_t K, const char* order,
+           Proj* out) {
+    out->N = N;
+    out->K = K;
+    RadEncoding e;
+    rad_enc_clear(&e);
+    rad_enc_copy_str(e.scheme, "affine");
+    rad_enc_copy_str(e.transform, "fwht128");
+    const uint32_t cdt = f.bits == 5 ? RAD_U5 : RAD_U4;
+    const int ic = rad_enc_add_plane(&e, "codes", cdt, 1, 1);
+    const int is = rad_enc_add_plane(&e, "scale", f.sdt, 1, f.group);
+    const int il = f.level ? rad_enc_add_plane(&e, "scale.1", RAD_F32, 0, 0) : -1;
+    const int it = rad_enc_add_table(&e, "table", RAD_F32, 1, (int64_t)1 << f.bits);
+    const int64_t SC = (K + f.group - 1) / f.group;
+    const int64_t rbc = rad_dtype_bytes(cdt, K), rbs = rad_dtype_bytes(f.sdt, SC);
+    std::vector pc((size_t)(N * rbc)), ps((size_t)(N * rbs)), pl(4), pt(4u << f.bits);
+    const float lv = 0x1p-13f;
+    std::memcpy(pl.data(), &lv, 4);
+    std::memcpy(pt.data(), f.bits == 5 ? kW5nl : kW4nl, pt.size());
+    const RadParam p[] = { RadParam{ "dtype", RAD_P_STR, 0, 0, f.dtype, 0 },
+                           RadParam{ "a_order", RAD_P_STR, 0, 0, order, 0 } };
+    auto plane = [](void* d, uint32_t dt, int64_t r, int64_t c) {
+        RadTensor t{};
+        t.data = d; t.dtype = dt; t.rank = 2; t.shape[0] = r; t.shape[1] = c;
+        t.stride[0] = c; t.stride[1] = 1;
+        return t;
+    };
+    uint64_t s = 0x1234567ull + (uint64_t)N;
+    for (int64_t ex = 0; ex < kExperts; ++ex) {
+        /* Any bit pattern is a valid code, and the scales span four binades as the model's do. */
+        for (size_t i = 0; i < pc.size(); i += 8) {
+            const uint64_t r = hsplitmix(s);
+            std::memcpy(pc.data() + i, &r, std::min(8, pc.size() - i));
+        }
+        for (int64_t i = 0; i < N * SC; ++i)
+            rad_store_f32(ps.data(), f.sdt, i,
+                          f.sdt == RAD_F8E4M3 ? std::ldexp(1.0f + (float)(i % 7) / 8.0f,
+                                                           (int)(hsplitmix(s) % 4) - 2)
+                                              : 0.0005f + 0.0001f * (float)(i % 13));
+        const int opd = ex % 2 ? 6 : 2;
+        for (int v = 0; v < 2; ++v) {
+            int sel[2];
+            RadTensor t[2];
+            int n = 0;
+            if (v == 0) {
+                sel[0] = ic; sel[1] = it; n = 2;
+                t[0] = plane(pc.data(), cdt, N, K);
+                t[1] = plane(pt.data(), RAD_F32, 1, (int64_t)1 << f.bits);
+            } else {
+                sel[0] = is; t[0] = plane(ps.data(), f.sdt, N, SC); n = 1;
+                if (f.level) { sel[1] = il; t[1] = plane(pl.data(), RAD_F32, 1, 1); n = 2; }
+            }
+            RadLayout L{};
+            const int rc = k->layout ? k->layout(p, 2, opd + v, &e, sel, t, n, &L)
+                                     : RAD_E_UNSUPPORTED;
+            std::unique_ptr b;
+            if (rc == RAD_E_UNSUPPORTED && n == 1) {
+                b.reset(new Buf((int64_t)ps.size()));
+                std::memcpy(b->p, ps.data(), ps.size());
+                if (ex == 0) out->sdt = f.sdt;
+            } else if (rc == RAD_OK && k->relayout) {
+                b.reset(new Buf(L.bytes));
+                if (k->relayout(p, 2, opd + v, &e, sel, t, n, b->p, L.bytes) != RAD_OK) return false;
+                if (ex == 0) (v ? out->sdt : out->cdt) = L.dtype;
+            } else {
+                std::fprintf(stderr, "  %s: %s's layout refused %s (%d)\n", f.dtype, k->name,
+                             v ? "the scales" : "the codes", rc);
+                return false;
+            }
+            (v ? out->scales : out->codes).push_back(std::move(b));
+        }
+    }
+    out->bytes_per_expert = N * rbc + N * rbs;
+    return true;
+}
+
+/* A routing of M tokens to kTopK distinct experts each, drawn from `seed`, as moe_scatter leaves
+ * it: the flattened slots grouped by expert, and the offsets. Returns the experts it touches. */
+int64_t route(int64_t M, uint64_t seed, std::vector* sorted, std::vector* off) {
+    const int64_t T = M * kTopK;
+    std::vector eid((size_t)T);
+    uint64_t s = seed;
+    for (int64_t t = 0; t < M; ++t)
+        for (int64_t j = 0; j < kTopK; ++j) {
+            int32_t e;
+            bool dup;
+            do {
+                e = (int32_t)(hsplitmix(s) % (uint64_t)kExperts);
+                dup = false;
+                for (int64_t i = 0; i < j; ++i) dup = dup || eid[(size_t)(t * kTopK + i)] == e;
+            } while (dup);
+            eid[(size_t)(t * kTopK + j)] = e;
+        }
+    sorted->assign((size_t)T, -1);
+    off->assign((size_t)kExperts + 1, 0);
+    std::vector cnt((size_t)kExperts, 0);
+    for (int32_t e : eid) ++cnt[(size_t)e];
+    int64_t touched = 0;
+    for (int64_t e = 0; e < kExperts; ++e) {
+        (*off)[(size_t)e + 1] = (*off)[(size_t)e] + (int32_t)cnt[(size_t)e];
+        touched += cnt[(size_t)e] > 0;
+    }
+    std::vector cur(off->begin(), off->end() - 1);
+    for (int64_t i = 0; i < T; ++i) (*sorted)[(size_t)cur[(size_t)eid[(size_t)i]]++] = (int32_t)i;
+    return touched;
+}
+
+/* Seconds per call, median of `reps` calls, each on a fresh routing; the touched experts' bytes
+ * averaged over the calls. */
+double time_proj(const RadKernelInfo* k, const Form& f, const Proj& pj, bool gate_up, int64_t M,
+                 int reps, double* bytes, int* status) {
+    const int64_t T = M * kTopK, AR = gate_up ? M : T, N = pj.N, K = pj.K, SG = (K + 127) / 128;
+    std::vector aq((size_t)(AR * K)), y((size_t)(T * N * 2));
+    std::vector as((size_t)(AR * SG));
+    uint64_t s = 99;
+    for (auto& b : aq) {
+        b = (uint8_t)(hsplitmix(s) & 0xff);
+        if ((b & 0x7f) == 0x7f) b = 0x38;       /* not the format's one NaN */
+    }
+    for (size_t i = 0; i < as.size(); ++i) as[i] = 0.01f + 0.001f * (float)(i % 11);
+    std::vector tab[4];
+    for (int64_t e = 0; e < kExperts; ++e) {
+        tab[(e % 2) * 2].push_back(pj.codes[(size_t)e]->p);
+        tab[(e % 2) * 2 + 1].push_back(pj.scales[(size_t)e]->p);
+    }
+    const int64_t scols = f.level ? K : SG;
+    auto table = [&](int i) {
+        RadTensor t{};
+        t.data = tab[i].data();
+        t.dtype = i % 2 ? pj.sdt : pj.cdt;
+        t.rank = 3;
+        t.shape[0] = kExperts / 2; t.shape[1] = N; t.shape[2] = i % 2 ? scols : K;
+        t.stride[0] = 0; t.stride[1] = t.shape[2]; t.stride[2] = 1;
+        return t;
+    };
+    auto dense = [](void* d, uint32_t dt, std::initializer_list sh) {
+        RadTensor t{};
+        t.data = d; t.dtype = dt; t.rank = (uint32_t)sh.size();
+        int i = 0;
+        for (int64_t x : sh) t.shape[i++] = x;
+        rad_tensor_pack(&t);
+        return t;
+    };
+    std::vector sorted, off;
+    const RadParam p[] = {
+        RadParam{ "M", RAD_P_INT, M, 0, nullptr, 0 }, RadParam{ "N", RAD_P_INT, N, 0, nullptr, 0 },
+        RadParam{ "K", RAD_P_INT, K, 0, nullptr, 0 },
+        RadParam{ "n_expert", RAD_P_INT, kExperts, 0, nullptr, 0 },
+        RadParam{ "top_k", RAD_P_INT, kTopK, 0, nullptr, 0 },
+        RadParam{ "group", RAD_P_INT, 128, 0, nullptr, 0 },
+        RadParam{ "a_order", RAD_P_STR, 0, 0, gate_up ? "token" : "sorted", 0 },
+        RadParam{ "dtype", RAD_P_STR, 0, 0, f.dtype, 0 },
+        RadParam{ "N_odd", RAD_P_INT, N, 0, nullptr, 0 },
+        RadParam{ "K_odd", RAD_P_INT, K, 0, nullptr, 0 },
+        RadParam{ "parts", RAD_P_INT, gate_up ? 2 : 1, 0, nullptr, 0 } };
+    std::vector ts;
+    double total = 0;
+    *status = RAD_OK;
+    for (int r = -1; r < reps; ++r) {
+        const int64_t touched = route(M, 1000 + (uint64_t)r, &sorted, &off);
+        RadTensor t[9] = { dense(aq.data(), RAD_F8E4M3, { AR, K }),
+                           dense(as.data(), RAD_F32, { AR, SG }), table(0), table(1),
+                           dense(sorted.data(), RAD_I32, { T }),
+                           dense(off.data(), RAD_I32, { kExperts + 1 }), table(2), table(3),
+                           dense(y.data(), RAD_BF16, { T, N }) };
+        RadArgs a{};
+        a.t = t; a.n_t = 9; a.p = p; a.n_p = (int)(sizeof p / sizeof p[0]); a.world_size = 1;
+        const double t0 = now_s();
+        const int rc = k->launch(&a, nullptr);
+        const double dt = now_s() - t0;
+        if (rc < 0) { *status = rc; return 0; }
+        if (r < 0) continue;                      /* the warm-up: scratch arenas grow */
+        ts.push_back(dt);
+        total += (double)touched * (double)pj.bytes_per_expert;
+    }
+    *bytes = total / reps;
+    return median(ts);
+}
+
+}  /* namespace moebench */
+
+static void bench_moe(Lib& avx, Lib& ref, const std::string& dtypes, int threads) {
+    using namespace moebench;
+#ifdef _OPENMP
+    omp_set_num_threads(threads);
+#endif
+    const RadKernelInfo* ka = avx.row("moe_gemm_q");
+    const RadKernelInfo* kr = ref.row("moe_gemm_q");
+    if (!ka || !kr) return;
+    std::printf("\n== moe_gemm_q, Qwen3.8-Flash-Next's experts on one rank: %lld experts, top_k "
+                "%lld, gate_up [%lld, %lld], down [%lld, %lld]; %d thread(s), each call a fresh "
+                "routing ==\n", (long long)kExperts, (long long)kTopK, (long long)(2 * kFF),
+                (long long)kEmbd, (long long)kEmbd, (long long)kFF, threads);
+    std::printf("  %-10s %5s %-8s %11s %11s %11s %11s %11s %10s %11s\n", "dtype", "M", "proj",
+                "libref us", "scalar us", "avx us", "avx2 us", "avx512 us", "GB/s", "GFLOP/s");
+    for (const Form& f : kForms) {
+        if (("," + dtypes + ",").find("," + std::string(f.dtype) + ",") == std::string::npos)
+            continue;
+        Proj gu, dn;
+        if (!build(ka, f, 2 * kFF, kEmbd, "token", &gu) || !build(ka, f, kEmbd, kFF, "sorted", &dn))
+            continue;
+        for (int64_t M : { 1, 4, 64, 2048 })
+            for (int pj = 0; pj < 2; ++pj) {
+                const Proj& P = pj ? dn : gu;
+                const int reps = M >= 2048 ? 3 : M >= 64 ? 7 : 21;
+                double t[AVX_N_LEVELS + 1] = {}, bytes = 0;
+                int st = RAD_OK;
+                /* libref decodes per element through its table: decode sizes only. */
+                if (M <= 4) t[0] = time_proj(kr, f, P, !pj, M, 3, &bytes, &st);
+                for (int lvl = 0; lvl < AVX_N_LEVELS && st == RAD_OK; ++lvl) {
+                    if (avx.isa_force && avx.isa_force(lvl) != lvl) continue;
+                    if (lvl < 2 && M >= 64) continue;
+                    t[lvl + 1] = time_proj(ka, f, P, !pj, M, reps, &bytes, &st);
+                }
+                if (avx.isa_force) avx.isa_force(AVX_N_LEVELS - 1);
+                if (st != RAD_OK) {
+                    std::printf("  %-10s %5lld %-8s refused: %d\n", f.dtype, (long long)M,
+                                pj ? "down" : "gate_up", st);
+                    continue;
+                }
+                const double best = t[AVX_N_LEVELS];
+                const double flops = 2.0 * (double)(M * kTopK) * (double)P.N * (double)P.K;
+                char line[256];
+                int o = std::snprintf(line, sizeof line, "  %-10s %5lld %-8s", f.dtype,
+                                      (long long)M, pj ? "down" : "gate_up");
+                for (int i = 0; i <= AVX_N_LEVELS; ++i)
+                    o += t[i] > 0 ? std::snprintf(line + o, sizeof line - o, " %11.0f", t[i] * 1e6)
+                                  : std::snprintf(line + o, sizeof line - o, " %11s", "-");
+                std::snprintf(line + o, sizeof line - o, " %10.1f %11.1f", bytes / best / 1e9,
+                              flops / best / 1e9);
+                std::printf("%s\n", line);
+            }
+    }
+#ifdef _OPENMP
+    omp_set_num_threads(1);
+#endif
+}
+
+/* ================================================================== weights of several planes
+ *
+ * The lm head and the zero-point grids at model size, the weight stored joined (abi/rad_planes.h)
+ * through libavx's own hooks, on every team thread: these are the decode step's largest reads, a
+ * memory benchmark at small M, so each rate is beside the DRAM triad on the same threads. The case
+ * table cannot describe them (libref describes logical forms), so they are built here. */
+
+/* A weight's canonical planes over [rows, cols]: codes and the planes after them, each dense. */
+struct BenchPlanes {
+    RadEncoding enc{};
+    int64_t rows = 0, cols = 0;
+    std::vector> data;
+    std::vector pr, pc;
+    BenchPlanes(const RadEncoding& e, int64_t r, int64_t c) : enc(e), rows(r), cols(c) {
+        for (int i = 0; i < e.n_planes; ++i) {
+            int64_t a = 0, b = 0;
+            rad_enc_plane_dims(&e.plane[i], r, c, &a, &b);
+            pr.push_back(a);
+            pc.push_back(b);
+            data.emplace_back((size_t)(a * rad_enc_row_bytes(e.plane[i].dtype, b)), 0);
+        }
+    }
+    /* Plane i filled with element values v(r, c): floats in their dtype, codes as integers. */
+    template  void fill(int i, F v) {
+        const uint32_t dt = enc.plane[i].dtype;
+        const int64_t rb = rad_enc_row_bytes(dt, pc[(size_t)i]);
+        for (int64_t r = 0; r < pr[(size_t)i]; ++r) {
+            uint8_t* row = data[(size_t)i].data() + r * rb;
+            for (int64_t c = 0; c < pc[(size_t)i]; ++c) {
+                const float x = v(r, c);
+                if (dt == RAD_F32 || dt == RAD_F16 || dt == RAD_BF16) rad_store_f32(row, dt, c, x);
+                else rad_store_code(row, dt, c, (int)x);
+            }
+        }
+    }
+    /* The joined bytes of planes `sel` for operand `opd`, through `k`'s hooks. */
+    bool join(const RadKernelInfo* k, const std::vector& p, int opd,
+              const std::vector& sel, std::vector* out, uint32_t* dt) {
+        std::vector t;
+        for (int i : sel) {
+            RadTensor x{};
+            x.dtype = enc.plane[i].dtype;
+            x.rank = 2;
+            x.shape[0] = pr[(size_t)i];
+            x.shape[1] = pc[(size_t)i];
+            x.stride[0] = x.shape[1];
+            x.stride[1] = 1;
+            x.data = data[(size_t)i].data();
+            t.push_back(x);
+        }
+        RadLayout L{};
+        if (!k->layout || k->layout(p.data(), (int)p.size(), opd, &enc, sel.data(), t.data(),
+                                    (int)t.size(), &L) != RAD_OK)
+            return false;
+        out->assign((size_t)L.bytes, 0);
+        *dt = L.dtype;
+        return k->relayout(p.data(), (int)p.size(), opd, &enc, sel.data(), t.data(),
+                           (int)t.size(), out->data(), L.bytes) == RAD_OK;
+    }
+};
+
+static uint64_t bench_mix(uint64_t s, int64_t i) {
+    uint64_t x = s * 0x9E3779B97F4A7C15ull + (uint64_t)i;
+    x ^= x >> 31; x *= 0xBF58476D1CE4E5B9ull; x ^= x >> 29;
+    return x;
+}
+
+static RadTensor bench_tensor(void* data, uint32_t dt, std::initializer_list shape) {
+    RadTensor t{};
+    t.data = data;
+    t.dtype = dt;
+    t.rank = (uint32_t)shape.size();
+    int i = 0;
+    for (int64_t s : shape) t.shape[i++] = s;
+    rad_tensor_pack(&t);
+    return t;
+}
+
+/* Seconds of `reps` launches after `warm`, launch i over copy i of the weight: a working set past
+ * the last-level cache (128 MiB here), so a weight smaller than it is not timed from it
+ * (libr4d/r4d_gemm_w4a16_nt_m64.hip makes the same point). The best of them, and the median in
+ * `med`: on a machine with other load the best is the kernel's, the median the machine's. */
+static double bench_time(const RadKernelInfo* k, const std::vector& a, int warm,
+                         int reps, double* med = nullptr) {
+    for (int w = 0; w < warm; ++w) k->launch(&a[(size_t)w % a.size()], nullptr);
+    std::vector ts;
+    for (int r = 0; r < reps; ++r) {
+        const double t0 = now_s();
+        const int rc = k->launch(&a[(size_t)(warm + r) % a.size()], nullptr);
+        ts.push_back(now_s() - t0);
+        if (rc < 0) { std::printf("    launch returned %d\n", rc); return -1; }
+    }
+    if (med) *med = median(ts);
+    return *std::min_element(ts.begin(), ts.end());
+}
+
+/* Copies of a weight of `bytes` that make a working set of at least 1 GiB. */
+static int bench_copies(double bytes) {
+    const double want = (double)(1u << 30);
+    return bytes >= want ? 1 : (int)std::ceil(want / bytes);
+}
+
+static double dram_triad(int threads) {
+    const size_t n = (size_t)256 * 1024 * 1024 / sizeof(float);
+    std::vector A(n), B(n, 1.0f), C(n, 2.0f);
+    std::vector ts;
+    for (int rep = 0; rep < 5; ++rep) {
+        const double t0 = now_s();
+#ifdef _OPENMP
+#pragma omp parallel for schedule(static) num_threads(threads)
+#endif
+        for (int64_t i = 0; i < (int64_t)n; ++i) A[(size_t)i] = B[(size_t)i] + 0.5f * C[(size_t)i];
+        ts.push_back(now_s() - t0);
+    }
+    return 3.0 * (double)n * sizeof(float) / median(ts) / 1e9;
+}
+
+/* A read-only stream, the traffic shape of a GEMM's weight at small M: 1 GiB summed as integers
+ * (an integer sum vectorises without reassociating floats). The best of five: it is a ceiling. */
+static double dram_read(int threads) {
+    const size_t n = ((size_t)1 << 30) / sizeof(uint64_t);
+    std::vector A(n, 1);
+    std::vector ts;
+    uint64_t sink = 0;
+    for (int rep = 0; rep < 5; ++rep) {
+        uint64_t sum = 0;
+        const double t0 = now_s();
+#ifdef _OPENMP
+#pragma omp parallel for schedule(static) num_threads(threads) reduction(+ : sum)
+#endif
+        for (int64_t i = 0; i < (int64_t)n; ++i) sum += A[(size_t)i];
+        ts.push_back(now_s() - t0);
+        sink += sum;
+    }
+    if (sink == 0) std::printf("(empty read)\n");
+    return (double)n * sizeof(uint64_t) / *std::min_element(ts.begin(), ts.end()) / 1e9;
+}
+
+static void bench_joined(Lib& avx, Lib& ref, int threads, int reps, bool with_ref,
+                         const std::string& only_op, int level) {
+#ifdef _OPENMP
+    omp_set_num_threads(threads);
+#endif
+    const int lvl = level >= 0 ? level : AVX_N_LEVELS - 1;
+    if (avx.isa_force && avx.isa_force(lvl) != lvl) {
+        std::printf("  level %d does not execute on this CPU\n", lvl);
+        return;
+    }
+    /* Other load on the machine lowers a ceiling measured once; it is taken again after the
+     * kernels, and the higher reading kept. */
+    const double triad = dram_triad(threads);
+    double rd = dram_read(threads);
+    std::printf("\n== weights of several planes at model size, %s, %d thread(s), best of %d ==\n",
+                avx.isa_name(lvl), threads, reps);
+    std::printf("  DRAM on these threads: triad %.1f GB/s, read-only %.1f GB/s (measured again at "
+                "the end)\n\n", triad, rd);
+    /* The weight's stored bytes over the time, against the read; libref once, at M = 1. */
+    struct Line { std::string op, geom; double t, med, tr, wbytes, flops; };
+    std::vector lines;
+    auto row = [&](const char* op, const char* geom, const RadKernelInfo* ka,
+                   const RadKernelInfo* kr, const std::vector& a, double wbytes,
+                   double flops) {
+        double med = 0;
+        const double t = bench_time(ka, a, 2, reps, &med);
+        const double tr = with_ref && kr ? bench_time(kr, a, 0, 1) : 0;
+        if (t > 0) lines.push_back({ op, geom, t, med, tr, wbytes, flops });
+    };
+
+    /* ---- the lm head: the 27B's fp8 (block 128 x 128, bf16 scales) and Flash-Next's int8
+     * (bf16 scale per row and 128 of K), against a bf16 activation into f32 logits. */
+    struct Head { const char* name; uint32_t codes; int64_t br, N, K; };
+    static const Head kHeads[] = {
+        { "fp8_e4m3*bf16[128x128]", RAD_F8E4M3, 128, 248320, 5120 },
+        { "i8*bf16[1x128]", RAD_I8, 1, 248320, 5120 },
+        { "i8*bf16[1x128]", RAD_I8, 1, 248320, 2560 },
+    };
+    const RadKernelInfo* ka = avx.row("logits_gemm");
+    const RadKernelInfo* kr = ref.row("logits_gemm");
+    for (const Head& hd : kHeads) {
+        if (!only_op.empty() && only_op != "logits_gemm") break;
+        BenchPlanes w(rad_enc_affine(hd.codes, RAD_BF16, hd.br, 128), hd.N, hd.K);
+        w.fill(0, [&](int64_t r, int64_t c) {
+            const int v = (int)(bench_mix(7, r * hd.K + c) & 0xffu);
+            return hd.codes == RAD_I8 ? (float)(int8_t)v : (float)(v == 0x7f || v == 0xff ? 0 : v);
+        });
+        w.fill(1, [](int64_t r, int64_t c) { return 0.001f * (float)(1 + (r + c) % 13); });
+        for (int64_t M : { 1, 4, 64 }) {
+            std::vector p = {
+                RadParam{ "M", RAD_P_INT, M, 0, nullptr, 0 },
+                RadParam{ "n_vocab", RAD_P_INT, hd.N, 0, nullptr, 0 },
+                RadParam{ "n_embd", RAD_P_INT, hd.K, 0, nullptr, 0 },
+                RadParam{ "dtype", RAD_P_STR, 0, 0, "bf16", 0 } };
+            std::vector j;
+            uint32_t jdt = 0;
+            if (!w.join(ka, p, 1, { 0, 1 }, &j, &jdt)) { std::printf("  join failed\n"); return; }
+            std::vector> pool((size_t)bench_copies((double)j.size()) - 1, j);
+            std::vector x((size_t)(M * hd.K));
+            for (size_t i = 0; i < x.size(); ++i)
+                x[i] = rad_f32_to_bf16(
+                    (float)((int64_t)(bench_mix(9, (int64_t)i) % 2001) - 1000) * 1e-3f);
+            std::vector y((size_t)(M * hd.N));
+            std::vector> ts;
+            std::vector a;
+            for (size_t c = 0; c <= pool.size(); ++c) {
+                void* wd = c ? pool[c - 1].data() : j.data();
+                ts.push_back({ bench_tensor(x.data(), RAD_BF16, { M, hd.K }),
+                               bench_tensor(wd, jdt, { hd.N, hd.K }),
+                               bench_tensor(y.data(), RAD_F32, { M, hd.N }) });
+            }
+            for (auto& t : ts) {
+                RadArgs x1{};
+                x1.t = t.data(); x1.n_t = 3; x1.p = p.data(); x1.n_p = (int)p.size();
+                x1.world_size = 1;
+                a.push_back(x1);
+            }
+            char g[96];
+            std::snprintf(g, sizeof g, "%s %lldx%lld M=%lld", hd.name, (long long)hd.N,
+                          (long long)hd.K, (long long)M);
+            row("logits_gemm", g, ka, M == 1 ? kr : nullptr, a, (double)j.size(),
+                2.0 * (double)M * (double)hd.N * (double)hd.K);
+        }
+    }
+
+    /* ---- gemm_nt_q's zero-point grids: the 2-bit draft head over the 27B's vocabulary, and
+     * the 27B ParoQuant int4 / int5 MLP (gate|up in two rotated parts, then down). */
+    struct Zp { const char* dtype; uint32_t codes; int64_t N, K, parts; std::vector Ms; };
+    const Zp kZp[] = {
+        { "w2a8", RAD_U2, 248320, 5120, 1, { 1, 4, 8 } },
+        { "w4a16_asym", RAD_U4, 34816, 5120, 2, { 1, 4, 8 } },
+        { "w4a16_asym", RAD_U4, 5120, 17408, 1, { 1, 4, 8 } },
+        { "w5a16", RAD_U5, 34816, 5120, 2, { 1, 4, 8 } },
+        { "w5a16", RAD_U5, 5120, 17408, 1, { 1, 4, 8 } },
+        { "w4a8i8_asym", RAD_U4, 34816, 5120, 2, { 256 } },
+        { "w5a8i8", RAD_U5, 34816, 5120, 2, { 256 } },
+    };
+    const RadKernelInfo* qa = avx.row("gemm_nt_q");
+    const RadKernelInfo* qr = ref.row("gemm_nt_q");
+    for (const Zp& z : kZp) {
+        if (!only_op.empty() && only_op != "gemm_nt_q" && only_op != z.dtype) continue;
+        const int64_t GS = 128, G = z.K / GS, P = z.parts;
+        const int64_t top = (1 << rad_dtype_bits(z.codes)) - 1;
+        RadEncoding e = rad_enc_affine(z.codes, RAD_F16, 1, GS);
+        rad_enc_add_plane(&e, "zero", RAD_U8, 1, GS);
+        BenchPlanes w(e, z.N, z.K);
+        w.fill(0, [&](int64_t r, int64_t c) {
+            return (float)(bench_mix(11, r * z.K + c) % (uint64_t)(top + 1));
+        });
+        w.fill(1, [](int64_t r, int64_t c) { return 0.01f * (float)(1 + (r + c) % 7); });
+        w.fill(2, [&](int64_t r, int64_t c) { return (float)((r + c) % (top + 1)); });
+        for (int64_t M : z.Ms) {
+            std::vector p;
+            p.reserve(6);
+            p.push_back(RadParam{ "M", RAD_P_INT, M, 0, nullptr, 0 });
+            p.push_back(RadParam{ "N", RAD_P_INT, z.N, 0, nullptr, 0 });
+            p.push_back(RadParam{ "K", RAD_P_INT, z.K, 0, nullptr, 0 });
+            p.push_back(RadParam{ "group", RAD_P_INT, GS, 0, nullptr, 0 });
+            p.push_back(RadParam{ "dtype", RAD_P_STR, 0, 0, z.dtype, 0 });
+            if (P > 1) p.push_back(RadParam{ "pb1", RAD_P_INT, z.N / 2, 0, nullptr, 0 });
+            std::vector j;
+            uint32_t jdt = 0;
+            if (!w.join(qa, p, 3, { 1, 2 }, &j, &jdt)) { std::printf("  join failed\n"); return; }
+            const avxp::ZpGrid* zg = avxp::zp_grid(z.dtype);
+            const int64_t AC = P * z.K, mpad = (M + 15) / 16 * 16;
+            std::vector a8((size_t)(M * AC));
+            std::vector a16((size_t)(M * AC));
+            for (int64_t i = 0; i < M * AC; ++i) {
+                a8[(size_t)i] = (uint8_t)(bench_mix(13, i) % 255 + 129);
+                a16[(size_t)i] =
+                    rad_f32_to_f16((float)((int64_t)(bench_mix(13, i) % 2001) - 1000) * 1e-3f);
+            }
+            std::vector as((size_t)(M * P * G), 0.004f), asum((size_t)(G * mpad), 3.0f);
+            std::vector y((size_t)(M * z.N));
+            const double wb = (double)(w.data[0].size() + j.size());
+            const size_t ncopy = (size_t)bench_copies(wb);
+            std::vector> cpool(ncopy - 1, w.data[0]), jpool(ncopy - 1, j);
+            std::vector> ts;
+            for (size_t c = 0; c < ncopy; ++c) {
+                std::vector t(7);
+                if (zg->act == avxp::ZP_F16) t[0] = bench_tensor(a16.data(), RAD_F16, { M, AC });
+                else                         t[0] = bench_tensor(a8.data(), RAD_I8, { M, AC });
+                if (zg->act == avxp::ZP_I8_ROW) t[1] = bench_tensor(as.data(), RAD_F32, { M, 1 });
+                if (zg->act == avxp::ZP_I8_GROUP)
+                    t[1] = bench_tensor(as.data(), RAD_F32, { M, P * G });
+                t[2] = bench_tensor(c ? cpool[c - 1].data() : w.data[0].data(), z.codes,
+                                    { z.N, z.K });
+                t[3] = bench_tensor(c ? jpool[c - 1].data() : j.data(), jdt, { z.N, z.K });
+                t[4] = bench_tensor(y.data(), RAD_BF16, { M, z.N });
+                if (zg->act == avxp::ZP_I8_ROW)
+                    t[5] = bench_tensor(asum.data(), RAD_F32, { G, mpad });
+                ts.push_back(std::move(t));
+            }
+            std::vector a;
+            for (auto& t : ts) {
+                RadArgs x1{};
+                x1.t = t.data(); x1.n_t = 7; x1.p = p.data(); x1.n_p = (int)p.size();
+                x1.world_size = 1;
+                a.push_back(x1);
+            }
+            char g[96];
+            std::snprintf(g, sizeof g, "%s %lldx%lld%s M=%lld", z.dtype, (long long)z.N,
+                          (long long)z.K, P > 1 ? " 2 parts" : "", (long long)M);
+            row("gemm_nt_q", g, qa, M == 1 ? qr : nullptr, a, wb,
+                2.0 * (double)M * (double)z.N * (double)z.K);
+        }
+    }
+    rd = std::max(rd, dram_read(threads));
+    std::printf("  read-only stream, the better of the two readings: %.1f GB/s\n\n", rd);
+    std::printf("  %-12s %-44s %9s %9s %9s %8s %10s %10s\n", "op", "geometry", "ms", "median",
+                "GB/s", "of read", "GFLOP/s", "libref ms");
+    for (const Line& l : lines)
+        std::printf("  %-12s %-44s %9.3f %9.3f %9.1f %7.0f%% %10.1f %10.1f\n", l.op.c_str(),
+                    l.geom.c_str(), l.t * 1e3, l.med * 1e3, l.wbytes / l.t / 1e9,
+                    100.0 * l.wbytes / l.t / 1e9 / rd, l.flops / l.t / 1e9, l.tr * 1e3);
+    if (avx.isa_force) avx.isa_force(AVX_N_LEVELS - 1);
+#ifdef _OPENMP
+    omp_set_num_threads(1);
+#endif
+}
+
+/* ================================================================== dense GEMM forms at model size
+ *
+ * gemm_nt and every plain gemm_nt_q form a shipped model's linears use, at the linears' own shapes,
+ * on --threads threads at one ISA level. A small M (decode, a verify window) reads each weight once
+ * per launch, so it is timed over copies of the weight past the last-level cache and reported
+ * against the read-only stream; a prefill M is compute-bound and is reported in GFLOP/s, beside the
+ * level's FMA probe times the team (the bf16 dot product's ceiling is twice that). */
+struct DenseForm {
+    const char* name;      /* gemm_nt_q's dtype, or "bf16" for gemm_nt */
+    uint32_t adt;          /* activation codes */
+    int      a_scale;      /* 0 none, 1 one per row, 2 one per (row, 128 of K) */
+    uint32_t bdt;          /* weight codes */
+    uint32_t sdt;          /* weight scale dtype (0: none) */
+    int64_t  sbr, sbc;     /* weight rows x columns one scale covers */
+    int64_t  group;
+};
+static const DenseForm kDenseForms[] = {
+    { "bf16",    RAD_BF16,   0, RAD_BF16,    0,        0,   0,   0 },
+    { "fp8a8",   RAD_F8E4M3, 2, RAD_F8E4M3,  RAD_BF16, 128, 128, 128 },
+    { "fp8a16",  RAD_BF16,   0, RAD_F8E4M3,  RAD_BF16, 128, 128, 128 },
+    { "i8a8",    RAD_I8,     2, RAD_I8,      RAD_BF16, 1,   128, 128 },
+    { "mxfp4a8", RAD_F8E4M3, 2, RAD_FP4E2M1, RAD_E8M0, 1,   32,  32 },
+    { "w4a8",    RAD_I8,     1, RAD_I4,      RAD_F16,  1,   128, 128 },
+    { "w8a8",    RAD_I8,     1, RAD_I8,      RAD_F16,  1,   128, 128 },
+};
+
+/* The linears each form serves, [N, K] (docs/ARCHITECTURES.md): the 27B's gate|up, down and
+ * q|gate for bf16, block fp8 and MXFP4; Flash-Next's q|gate and o for its int8 trunk; Gemma 4
+ * 31B's MLP for the int4 and int8 weights. */
+static std::vector> dense_shapes(const DenseForm& f) {
+    if (!std::strcmp(f.name, "i8a8")) return { { 12288, 2560 }, { 2560, 6144 } };
+    if (!std::strcmp(f.name, "w4a8") || !std::strcmp(f.name, "w8a8"))
+        return { { 21504, 5376 }, { 5376, 21504 } };
+    return { { 34816, 5120 }, { 5120, 17408 }, { 12288, 5120 } };
+}
+
+static void bench_dense(Lib& avx, int threads, int level, const std::string& only,
+                        const std::vector& Ms, int64_t shape_n, int64_t shape_k,
+                        int reps) {
+#ifdef _OPENMP
+    omp_set_num_threads(threads);
+#endif
+    const int lvl = level >= 0 ? level : AVX_N_LEVELS - 1;
+    if (avx.isa_force && avx.isa_force(lvl) != lvl) {
+        std::printf("  level %d does not execute on this CPU\n", lvl);
+        return;
+    }
+    double fma = 0;
+    if (auto peak = (double (*)(int, int64_t))dlsym(avx.h, "avx_peak_fma")) {
+        for (int r = 0; r < 3; ++r) {
+            const double t0 = now_s();
+            const double fl = peak(lvl, 1000000);
+            fma = std::max(fma, fl / (now_s() - t0));
+        }
+    }
+    double rd = dram_read(threads);
+    std::printf("\n== dense GEMM forms at model size, %s, %d thread(s), best of %d ==\n",
+                avx.isa_name(lvl), threads, reps);
+    std::printf("  ceilings: FMA %.0f GFLOP/s x %d threads = %.0f; read-only DRAM %.1f GB/s\n\n",
+                fma / 1e9, threads, fma * threads / 1e9, rd);
+    std::printf("  %-8s %-14s %6s %10s %10s %10s %9s %8s\n", "form", "N x K", "M", "ms", "median",
+                "GFLOP/s", "GB/s", "of read");
+    for (const DenseForm& f : kDenseForms) {
+        if (!only.empty() && only != f.name) continue;
+        const bool plain = !std::strcmp(f.name, "bf16");
+        const RadKernelInfo* k = avx.row(plain ? "gemm_nt" : "gemm_nt_q");
+        if (!k) continue;
+        auto shapes = dense_shapes(f);
+        if (shape_n > 0 && shape_k > 0) shapes = { { shape_n, shape_k } };
+        for (const auto& sh : shapes) {
+            const int64_t N = sh.first, K = sh.second;
+            const int64_t wbytes = rad_dtype_bytes(f.bdt, N * K);
+            const int64_t sr = f.sdt ? (N + f.sbr - 1) / f.sbr : 0;
+            const int64_t sc = f.sdt ? (K + f.sbc - 1) / f.sbc : 0;
+            const int64_t sbytes = f.sdt ? rad_dtype_bytes(f.sdt, sr * sc) : 0;
+            /* One weight, its copies made on demand for the small M that read it from DRAM. */
+            std::vector w0((size_t)wbytes), s0((size_t)sbytes);
+            for (int64_t i = 0; i < wbytes; i += 8) {
+                uint64_t r = bench_mix(17, i);
+                if (f.bdt == RAD_F8E4M3)        /* no NaN codes: 0x7f and 0xff become 0x7e, 0xfe */
+                    for (int b = 0; b < 8; ++b)
+                        if (((r >> (8 * b)) & 0x7f) == 0x7f) r ^= (uint64_t)1 << (8 * b);
+                if (f.bdt == RAD_BF16)          /* normal and finite: |w| in [2^-7, 2) */
+                    r = (r & 0x80ff80ff80ff80ffull) | 0x3c003c003c003c00ull;
+                std::memcpy(w0.data() + i, &r, (size_t)std::min(8, wbytes - i));
+            }
+            for (int64_t i = 0; i < sr * sc; ++i) {
+                if (f.sdt == RAD_E8M0) s0[(size_t)i] = (uint8_t)(120 + bench_mix(19, i) % 8);
+                else rad_store_f32(s0.data(), f.sdt, i, 0.001f * (float)(1 + i % 13));
+            }
+            for (int64_t M : Ms) {
+                const size_t ncopy = M < 256 ? (size_t)bench_copies((double)(wbytes + sbytes)) : 1;
+                std::vector> wc(ncopy - 1, w0), scp(ncopy - 1, s0);
+                std::vector a((size_t)rad_dtype_bytes(f.adt, M * K));
+                for (int64_t i = 0; i < (int64_t)a.size(); ++i) {
+                    uint8_t v = (uint8_t)bench_mix(23, i);
+                    if (f.adt == RAD_F8E4M3 && (v & 0x7f) == 0x7f) v ^= 1;
+                    if (f.adt == RAD_BF16 && (i & 1)) v = (uint8_t)(0x3c + (v & 3));  /* finite */
+                    a[(size_t)i] = v;
+                }
+                const int64_t asc = f.a_scale == 2 ? (K + 127) / 128 : 1;
+                std::vector as((size_t)(M * asc), 0.01f);
+                std::vector y((size_t)(M * N));
+                std::vector> ts;
+                for (size_t c = 0; c < ncopy; ++c) {
+                    void* wd = c ? wc[c - 1].data() : w0.data();
+                    void* sd = c ? scp[c - 1].data() : s0.data();
+                    if (plain) {
+                        ts.push_back({ bench_tensor(a.data(), f.adt, { M, K }),
+                                       bench_tensor(wd, f.bdt, { N, K }),
+                                       bench_tensor(y.data(), RAD_BF16, { M, N }) });
+                        continue;
+                    }
+                    std::vector t(7);
+                    t[0] = bench_tensor(a.data(), f.adt, { M, K });
+                    if (f.a_scale) t[1] = bench_tensor(as.data(), RAD_F32, { M, asc });
+                    t[2] = bench_tensor(wd, f.bdt, { N, K });
+                    t[3] = bench_tensor(sd, f.sdt, { sr, sc });
+                    t[4] = bench_tensor(y.data(), RAD_BF16, { M, N });
+                    ts.push_back(std::move(t));
+                }
+                std::vector p = {
+                    RadParam{ "M", RAD_P_INT, M, 0, nullptr, 0 },
+                    RadParam{ "N", RAD_P_INT, N, 0, nullptr, 0 },
+                    RadParam{ "K", RAD_P_INT, K, 0, nullptr, 0 },
+                    RadParam{ "dtype", RAD_P_STR, 0, 0, f.name, 0 },
+                    RadParam{ "group", RAD_P_INT, f.group, 0, nullptr, 0 } };
+                std::vector args;
+                for (auto& t : ts) {
+                    RadArgs x{};
+                    x.t = t.data(); x.n_t = (int)t.size(); x.p = p.data();
+                    x.n_p = plain ? 4 : 5;
+                    x.world_size = 1;
+                    args.push_back(x);
+                }
+                const double flops = 2.0 * (double)M * (double)N * (double)K;
+                /* At least a second of launches, at most `reps`. */
+                double med = 0;
+                const double t1 = bench_time(k, args, 1, 1);
+                const int r = t1 <= 0 ? 0 : std::max(3, std::min(reps, (int)(1.0 / t1)));
+                const double t = r ? bench_time(k, args, 1, r, &med) : -1;
+                if (t <= 0) continue;
+                char g[32];
+                std::snprintf(g, sizeof g, "%lldx%lld", (long long)N, (long long)K);
+                std::printf("  %-8s %-14s %6lld %10.3f %10.3f %10.1f %9.1f %7.0f%%\n", f.name, g,
+                            (long long)M, t * 1e3, med * 1e3, flops / t / 1e9,
+                            (double)(wbytes + sbytes) / t / 1e9,
+                            100.0 * (double)(wbytes + sbytes) / t / 1e9 / rd);
+                std::fflush(stdout);
+            }
+        }
+    }
+    if (avx.isa_force) avx.isa_force(AVX_N_LEVELS - 1);
+#ifdef _OPENMP
+    omp_set_num_threads(1);
+#endif
+}
+
 /* ================================================================== per-op timing */
 struct Row {
     std::string op, geom;
@@ -202,30 +965,75 @@ struct Row {
     double bytes = 0, flops = 0;
 };
 
-static double time_launch(const RadKernelInfo* k, RadArgs* args, Prepared& pr, bool is_ref,
-                          int warm, int iters, int reps) {
+/* Flushes every line of the operands one side of the case launches with, from every cache level,
+ * so the launch reads its inputs from DRAM and writes its outputs into lines it does not hold.
+ * Flushing the operands themselves is exact; sweeping a large buffer instead leaves some of them
+ * behind on a part whose L3 favours reused lines over streamed ones. */
+static void evict_operands(Prepared& pr, bool side_a) {
+    for (Opd& o : pr.opd) {
+        if (o.absent || o.n <= 0) continue;
+        GBuf& g = side_a ? o.a : o.b;
+        const uint8_t* p = g.data();
+        for (size_t off = 0; off < g.size(); off += 64) _mm_clflush(p + off);
+        if (g.size()) _mm_clflush(p + g.size() - 1);
+    }
+    GBuf& s = side_a ? pr.sa : pr.sb;
+    for (size_t off = 0; off < s.size(); off += 64) _mm_clflush(s.data() + off);
+    _mm_mfence();
+}
+
+static double time_launch(const RadKernelInfo* k, RadArgs* args, Prepared& pr, int warm,
+                          int iters, int reps, bool cold) {
     for (int w = 0; w < warm; ++w) { k->launch(args, nullptr); h_reset(pr); }
     std::vector ts;
     for (int r = 0; r < reps; ++r) {
         double acc = 0;
         for (int it = 0; it < iters; ++it) {
+            if (cold) evict_operands(pr, args == &pr.aa);
             const double t0 = now_s();
             k->launch(args, nullptr);
             acc += now_s() - t0;
-            /* Outside the clock: an INOUT op must start from the drawn bytes every time or it is
-             * timing a different computation each round. */
+            /* Outside the clock: INOUT operands must start from the drawn bytes each time. */
             h_reset(pr);
         }
         ts.push_back(acc / iters);
     }
-    (void)is_ref;
     return median(ts);
 }
 
+/* The indexer's descriptions draw each sequence's complete-block count and each query's position
+ * at random (libref/ref_shapes.cpp), so a timing would cover a random share of the context. At
+ * model shape every block is complete and every query sees all of them. */
+static void model_shape(const Case& c, Prepared& pr) {
+    auto param = [&](const char* k) {
+        for (const P& p : c.p)
+            if (!std::strcmp(p.k, k)) return (int64_t)p.i;
+        return (int64_t)0;
+    };
+    auto set_all = [&](size_t k, int64_t v) {
+        Opd& o = pr.opd[k];
+        if (o.absent || o.d.dtype != RAD_I32) return;
+        int32_t* w = (int32_t*)o.master.data();
+        for (int64_t i = 0; i < o.n; ++i) w[i] = (int32_t)v;
+        std::memcpy(o.a.data(), o.master.data(), o.master.size());
+        std::memcpy(o.b.data(), o.master.data(), o.master.size());
+    };
+    if (!std::strcmp(c.op, "qsa_score")) {
+        set_all(4, param("blocks"));                                   /* nc */
+    } else if (!std::strcmp(c.op, "qsa_select")) {
+        set_all(2, param("blocks"));                                   /* nc */
+        set_all(3, param("blocks") * param("ratio") - 1);              /* pos */
+    }
+}
+
 int main(int argc, char** argv) {
     std::string ref_path = "libref.so", avx_path = "libavx.so", only_op;
-    bool do_peak = false, do_cvt = false, do_ops = true;
-    int threads = 1;
+    bool do_peak = false, do_cvt = false, do_ops = true, do_moe = false, no_ref = false;
+    bool cold = false, do_joined = false, joined_ref = false, do_dense = false;
+    std::vector dense_m = { 1, 4, 8, 512 };
+    int64_t shape_n = 0, shape_k = 0;
+    std::string moe_dtypes = "w4nl64a8h";
+    int threads = 1, only_level = -1;
     int iters = 20, reps = 7;
 
     for (int i = 1; i < argc; ++i) {
@@ -236,8 +1044,30 @@ int main(int argc, char** argv) {
         else if (s == "--op")   only_op = next();
         else if (s == "--peak") { do_peak = true; do_ops = false; }
         else if (s == "--cvt")  { do_cvt = true; do_ops = false; }
+        else if (s == "--moe")  { do_moe = true; do_ops = false; }
+        else if (s == "--moe-dtype") moe_dtypes = next();
         else if (s == "--all")  { do_peak = do_cvt = do_ops = true; }
+        else if (s == "--joined") { do_joined = true; do_ops = false; }
+        else if (s == "--joined-ref") { do_joined = joined_ref = true; do_ops = false; }
+        else if (s == "--dense") { do_dense = true; do_ops = false; }
+        else if (s == "--m") {
+            dense_m.clear();
+            for (const char* q = next(); *q;) {
+                dense_m.push_back(std::strtoll(q, nullptr, 10));
+                while (*q && *q != ',') ++q;
+                if (*q == ',') ++q;
+            }
+        }
+        else if (s == "--shape") {
+            const char* q = next();
+            shape_n = std::strtoll(q, nullptr, 10);
+            const char* x = std::strchr(q, 'x');
+            shape_k = x ? std::strtoll(x + 1, nullptr, 10) : 0;
+        }
         else if (s == "--threads") threads = std::atoi(next());
+        else if (s == "--level") only_level = std::atoi(next());
+        else if (s == "--no-ref") no_ref = true;
+        else if (s == "--cold") cold = true;
         else if (s == "--iters") iters = std::atoi(next());
         else if (s == "-h" || s == "--help") {
             std::printf(
@@ -247,19 +1077,36 @@ int main(int argc, char** argv) {
                 "  --peak          measure this machine's FMA and memory ceilings and stop\n"
                 "  --cvt           measure the dtype conversions per ISA level and stop\n"
                 "  --all           ceilings, conversions and every op\n"
+                "  --joined        the lm head and the zero-point grids at model size, stored\n"
+                "                  joined, on --threads threads (--joined-ref also times libref;\n"
+                "                  --op narrows it to logits_gemm, gemm_nt_q or one grid;\n"
+                "                  --level picks the ISA level, default the highest)\n"
+                "  --dense         gemm_nt and the plain gemm_nt_q forms at their models' linear\n"
+                "                  shapes, on --threads threads at --level (default the highest);\n"
+                "                  --op narrows it to one form (bf16, fp8a8, fp8a16, i8a8,\n"
+                "                  mxfp4a8, w4a8, w8a8)\n"
+                "  --m LIST        --dense's row counts, comma-separated (default 1,4,8,512)\n"
+                "  --shape NxK     --dense at this one weight shape\n"
                 "  --op NAME       only this op\n"
-                "  --threads N     OpenMP threads for the ceiling measurement (default 1)\n"
+                "  --moe           moe_gemm_q over Qwen3.8-Flash-Next's codebook experts at the\n"
+                "                  model's geometry (1.3 GB of experts), and stop\n"
+                "  --moe-dtype L   the codebook forms --moe runs, comma-separated (default\n"
+                "                  w4nl64a8h; also w4nla8h, w4nl32a8h, w5nl64a8h)\n"
+                "  --threads N     OpenMP threads for the ceilings, the kernels, --moe and --joined\n"
+                "                  (default 1)\n"
+                "  --level L       time only ISA level L (0 scalar .. 3 avx512)\n"
+                "  --no-ref        do not time libref (it is not timed past 2e10 FLOP anyway)\n"
+                "  --cold          flush the operands from every cache before each timed launch\n"
                 "  --iters N       timed iterations per rep (default 20)\n");
             return 0;
         }
     }
 
 #ifdef _OPENMP
-    /* ONE THREAD BY DEFAULT, and that is a measurement decision rather than a timid one. Every
-     * geometry in the case table is small -- deliberately, so the checker is fast -- and a
-     * 32-thread fork/join over a 640-element row measures the barrier. The per-core number is what
-     * ranks a kernel change; --threads is there for the ceiling, where the aggregate is the point. */
-    omp_set_num_threads(1);
+    /* One thread by default: most case geometries are small (to keep the checker fast), and a wide
+     * fork/join on them would measure the barrier. --threads sets the team for a scaling
+     * measurement, of the kernels, the ceilings and --moe alike. */
+    omp_set_num_threads(threads > 0 ? threads : 1);
 #endif
 
     Lib ref, avx;
@@ -271,6 +1118,9 @@ int main(int argc, char** argv) {
 
     if (do_peak) bench_peak(avx, threads);
     if (do_cvt)  bench_cvt(avx, ref);
+    if (do_moe)  bench_moe(avx, ref, moe_dtypes, threads);
+    if (do_joined) bench_joined(avx, ref, threads, 7, joined_ref, only_op, only_level);
+    if (do_dense) bench_dense(avx, threads, only_level, only_op, dense_m, shape_n, shape_k, 7);
     if (!do_ops) return 0;
 
     const std::vector cases = build_cases();
@@ -283,6 +1133,7 @@ int main(int argc, char** argv) {
         if (!kr || !ka) continue;
         Prepared pr = h_prepare(ref, kr, c, kr, ka);
         if (!pr.ok) continue;
+        model_shape(c, pr);
         if (ka->launch(&pr.ab, nullptr) == RAD_E_UNSUPPORTED) continue;
         h_reset(pr);
 
@@ -291,36 +1142,44 @@ int main(int argc, char** argv) {
         r.geom = case_str(c);
         r.bytes = c.bytes;
         r.flops = c.flops;
-        /* libref gets fewer iterations: it is one to two orders slower and the whole run would be
-         * spent in the oracle. Its median over three is stable enough for a ratio. */
-        r.t_ref = time_launch(kr, &pr.aa, pr, true, 2, 3, 3);
+        /* Fewer iterations for libref, which is one to two orders of magnitude slower, and none
+         * for a case whose one launch would take it minutes. */
+        if (!no_ref && c.flops <= 2e10) r.t_ref = time_launch(kr, &pr.aa, pr, 2, 3, 3, cold);
+        /* A case of a second or more is timed fewer times. */
+        const bool big = c.flops > 2e10;
         for (int lvl = 0; lvl < AVX_N_LEVELS; ++lvl) {
+            if (only_level >= 0 && lvl != only_level) { r.t[lvl] = 0; continue; }
             if (avx.isa_force && avx.isa_force(lvl) != lvl) { r.t[lvl] = 0; continue; }
-            r.t[lvl] = time_launch(ka, &pr.ab, pr, false, 5, iters, reps);
+            r.t[lvl] = big ? time_launch(ka, &pr.ab, pr, 1, 2, 3, cold)
+                           : time_launch(ka, &pr.ab, pr, 5, iters, reps, cold);
         }
         rows.push_back(r);
     }
 
-    std::printf("\n== per op, microseconds per launch (median of %d reps x %d iters, 1 thread, "
-                "cache-warm) ==\n", reps, iters);
+    std::printf("\n== per op, microseconds per launch (median of %d reps x %d iters, %d thread%s, "
+                "%s) ==\n", reps, iters, std::max(threads, 1), threads > 1 ? "s" : "",
+                cold ? "operands flushed before each launch" : "cache-warm");
     std::printf("%-22s %9s %9s %9s %9s %9s %8s  %s\n", "op", "libref", "scalar", "avx", "avx2",
                 "avx512", "x(ref)", "rate");
     for (const Row& r : rows) {
         char rate[64] = "";
-        const double best = r.t[AVX_N_LEVELS - 1] > 0 ? r.t[AVX_N_LEVELS - 1] : r.t[0];
+        /* The highest level timed. */
+        double best = 0;
+        for (int lvl = 0; lvl < AVX_N_LEVELS; ++lvl)
+            if (r.t[lvl] > 0) best = r.t[lvl];
         if (best > 0 && r.flops > 0)
             std::snprintf(rate, sizeof rate, "%.1f GFLOP/s", r.flops / best / 1e9);
         else if (best > 0 && r.bytes > 0)
             std::snprintf(rate, sizeof rate, "%.1f GB/s", r.bytes / best / 1e9);
-        std::printf("%-22s %9.2f", r.op.c_str(), r.t_ref * 1e6);
+        if (r.t_ref > 0) std::printf("%-22s %9.2f", r.op.c_str(), r.t_ref * 1e6);
+        else             std::printf("%-22s %9s", r.op.c_str(), "n/a");
         for (int lvl = 0; lvl < AVX_N_LEVELS; ++lvl) {
             if (r.t[lvl] > 0) std::printf(" %9.2f", r.t[lvl] * 1e6);
             else              std::printf(" %9s", "n/a");
         }
         std::printf(" %8.1f  %-14s  %s\n", best > 0 ? r.t_ref / best : 0.0, rate, r.geom.c_str());
     }
-    std::printf("\nThe x(ref) column is a statement about libref, which is a scalar loop with a\n"
-                "per-element dtype switch and says so. The rate column against the ceilings from\n"
-                "--peak is the statement about libavx.\n");
+    std::printf("\nx(ref) is the speedup over libref's scalar loop; judge libavx by the rate column\n"
+                "against the --peak ceilings.\n");
     return 0;
 }
diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp
index 07bf9014..608615cd 100644
--- a/libavx/avx_cases.cpp
+++ b/libavx/avx_cases.cpp
@@ -1,32 +1,22 @@
-/* avx_cases.cpp -- the geometry table both harnesses run.
+/* avx_cases.cpp -- the geometry table both harnesses run (one table, so the bench and the checker
+ * cannot drift apart; tools/opshapes.h does the same for rad-kbench and rad-tune).
  *
- * ONE TABLE, TWO BINARIES. A benchmark taken at a different extent from the correctness check is a
- * measurement of something else, and the two tables would drift the first time one of them gained
- * a case. tools/opshapes.h makes this argument for rad-kbench and rad-tune; it holds one level
- * down too.
+ * Values are chosen to break hand-vectorised kernels, not for realism (a real n_embd would make the
+ * checker take minutes and find nothing a 640-wide row does not):
  *
- * WHAT THE VALUES ARE CHOSEN FOR. Not realism -- a real n_embd would make the checker take minutes
- * and would not find anything a 640-wide row does not. They are chosen to break a hand-vectorised
- * kernel:
+ *   Rows wider than any vector (16 floats at AVX-512), so the main body runs at every level.
+ *   Rows that are not a multiple of it, where tails, masked stores and scalar loops can disagree:
+ *     645 % 16 == 5, 645 % 8 == 5, 259 % 16 == 3.
+ *   More than one row, to catch a kernel that computes row 0 and broadcasts it.
+ *   M = 1, 7 and 65 on the GEMMs: decode, a speculative verify window, and one row past any
+ *     register-block edge.
+ *   Both sides of every option: `causal`, bounded and unbounded `window`, `norm`, both `a_order`
+ *     spellings, both rope `mode`s.
  *
- *   A ROW WIDER THAN ANY VECTOR, so the main body runs at every level (16 floats at AVX-512).
- *   A ROW THAT DOES NOT DIVIDE IT, because the tail loop is where a hand-vectorised kernel is
- *     wrong and where a level-3 masked store and a level-0 scalar loop can disagree. 645 and 259
- *     are chosen for exactly this: 645 % 16 == 5, % 8 == 5, and 259 % 16 == 3.
- *   MORE THAN ONE ROW, so a kernel that computed row 0 and broadcast it is caught.
- *   M = 1, 7 and 65 ON EVERY GEMM, which is decode, a speculative verify window, and one row past
- *     any register-block edge a microkernel can have.
- *   BOTH SIDES OF EVERY BANDED OPTION -- `causal` on and off, `window` bounded and unbounded,
- *     `norm` on and off, both `a_order` spellings, both rope `mode`s. A parameter exists because
- *     two implementations can disagree about it; a check that ran one value could never see that.
+ * Ops run in f32 (tight tolerance: only summation order may differ) and in bf16 (narrowing).
  *
- * Every op appears in f32, where the tolerance is tight enough that only the summation order may
- * differ, and in bf16, where the narrowing is exercised.
- *
- * `bytes` and `flops` are for the bench's rate columns and are left 0 wherever the cost is not a
- * simple function of the geometry -- a sampler that narrows a candidate set in place, a scatter
- * whose work depends on the draw. An invented denominator is worse than no rate at all: it
- * produces a number that looks comparable and is not.
+ * `bytes` and `flops` feed the bench's rate columns and stay 0 where the cost is not a simple
+ * function of the geometry (in-place samplers, draw-dependent scatters).
  */
 #include "avx_harness.h"
 
@@ -35,7 +25,7 @@ std::vector build_cases() {
     auto add = [&](const char* op, std::vector

p, double bytes = 0, double flops = 0) { c.push_back(Case{ op, std::move(p), bytes, flops }); }; - /* Bytes an elementwise op of `rows` x `n` moves at `w` bytes an element and `k` streams. */ + /* Bytes moved by an elementwise op over `rows` x `n`, `w` bytes per element, `k` streams. */ auto EB = [](double rows, double n, double w, double k) { return rows * n * w * k; }; for (const char* dt : { "f32", "bf16", "f16" }) { @@ -77,13 +67,28 @@ std::vector build_cases() { add("clamp", { HI("M", 7), HI("n", 645), HS("dtype", dt) }, EB(7, 645, w, 2)); add("rmsnorm", { HI("M", 5), HI("n", 645), HF("eps", 1e-6), HS("dtype", dt), HF("wadd", 0), HF("mult", 0.5) }, EB(5, 645, w, 2)); - /* The audio subsampler's two geometries, scaled down in time, with and without the - * frame mask, and a segment boundary (cu_div 2: the cu counts finer than the rows). */ + /* The audio subsampler's two geometries, scaled down in time: without and with the + * frame mask and a segment boundary (cu_div 2: cu counts in units finer than rows). */ add("conv2d", { HI("M", 24), HI("width", 16), HI("cin", 1), HI("cout", 24), HI("kh", 3), HI("kw", 3), HI("stride", 2), HI("pad", 1), HS("dtype", dt) }); add("conv2d", { HI("M", 24), HI("width", 8), HI("cin", 20), HI("cout", 12), HI("kh", 3), HI("kw", 3), HI("stride", 2), HI("pad", 1), HI("cu_div", 2), HI("valid_stride", 2), HS("dtype", dt) }); + /* Qwen3-ASR's: a [mel, time] kernel (time last), a bias and gelu after it; and its + * output projection as a 1 x 16 convolution over the frequency axis. */ + add("conv2d", { HI("M", 24), HI("width", 16), HI("cin", 6), HI("cout", 10), HI("kh", 3), + HI("kw", 3), HI("stride", 2), HI("pad", 1), HS("dtype", dt), + HI("t_last", 1), HS("act", "gelu") }); + add("conv2d", { HI("M", 8), HI("width", 16), HI("cin", 6), HI("cout", 20), HI("kh", 1), + HI("kw", 16), HI("stride", 1), HI("pad", 0), HS("dtype", dt) }); + /* A kernel taller than sixteen rows. */ + add("conv2d_unfold", { HI("M", 40), HI("width", 4), HI("cin", 2), HI("kh", 17), + HI("kw", 1), HI("stride", 1), HI("pad", 8), HS("dtype", dt) }); + for (int tl : { 0, 1 }) + add("conv2d_unfold", { HI("M", 24), HI("width", 16), HI("cin", 6), HI("kh", 3), + HI("kw", 3), HI("stride", 2), HI("pad", 1), + HI("cu_div", 2), HI("valid_stride", 2), HI("t_last", tl), + HS("dtype", dt) }); add("conv1d_dw", { HI("M", 26), HI("n", 645), HI("k", 5), HS("dtype", dt) }); add("conv1d_dw", { HI("M", 24), HI("n", 64), HI("k", 5), HI("cu_div", 4), HS("dtype", dt) }); add("rel_sinusoid", { HI("M", 13), HI("n", 1024), HF("max_timescale", 10000.0), @@ -96,16 +101,14 @@ std::vector build_cases() { add("scale_rows", { HI("M", 6), HI("n", 640), HS("act", "none"), HS("dtype", dt) }, EB(6, 640, w, 2)); } - /* Every dtype pair, because `cast` is where the narrowing conventions live and the tolerance - * for it is 1e-6 -- which is to say exact. A cast that rounded differently from the ABI's RTNE - * would make every operand of every other op disagree by up to an ulp. */ + /* Every dtype pair: `cast` carries the narrowing conventions and is checked at 1e-6, i.e. + * exactly. */ for (const char* from : { "f32", "bf16", "f16", "fp8_e4m3", "fp8_e5m2", "i8" }) for (const char* to : { "f32", "bf16", "f16", "fp8_e4m3", "fp8_e5m2", "i8" }) add("cast", { HI("M", 5), HI("n", 259), HS("from", from), HS("to", to) }); - /* The wide residual stream. hc = 4 and lowrank = 8 is Qwen4-Exp's gated residual, scaled down. - * `inject` on is the trunk case and off is the final mixer, and the two differ in the operand - * LIST -- which is what makes running both worth it rather than a duplicate. */ + /* The wide residual stream: Qwen4-Exp's gated residual scaled down (hc 4, lowrank 8). `inject` + * on is the trunk case, off the final mixer; they differ in the operand list. */ for (const char* dt : { "f32", "bf16" }) { add("hc_enter", { HI("M", 5), HI("n", 128), HI("hc", 4), HS("dtype", dt) }); add("hc_write", { HI("M", 5), HI("n", 128), HI("hc", 4), HS("dtype", dt) }); @@ -115,7 +118,7 @@ std::vector build_cases() { add("hc_read", { HI("M", 5), HI("n", 128), HI("hc", 4), HI("lowrank", 8), HF("eps", 1e-6), HS("dtype", dt), HF("wadd", 0), HI("inject", 0), HI("group", 0) }); - /* The fp8 form and its Hadamard-rotated twin, 32-wide groups: four of them a stream. */ + /* The fp8 form and its Hadamard-rotated variant, 32-wide groups (four per stream). */ add("hc_read", { HI("M", 5), HI("n", 128), HI("hc", 4), HI("lowrank", 8), HF("eps", 1e-6), HS("dtype", dt), HF("wadd", 1), HI("inject", 1), HI("group", 32), HI("rotate", 1) }); @@ -129,14 +132,17 @@ std::vector build_cases() { } add("ngram_ids", { HI("M", 9), HI("heads", 3), HI("ngram", 4), HI("eos", 2) }); - /* Quantisation. 128 is every real grid; 64 proves a second block edge works. n = 256 keeps - * both dividing, which the had_* forms require by contract (a rotation block may not straddle - * the end of a row). */ + /* Quantisation. 128 is the real grid; 64 tests a second block edge. n = 256 is divisible by + * both, which the had_* forms require (a rotation block may not straddle the row end). */ for (int group : { 64, 128 }) { add("quant_act_i8", { HI("M", 5), HI("n", 256), HI("group", group), HS("dtype", "bf16") }, EB(5, 256, 2, 1.5)); add("quant_act_i8", { HI("M", 5), HI("n", 256), HI("group", group), HS("dtype", "f32") }, EB(5, 256, 4, 1.25)); + add("quant_act_i8g", { HI("M", 5), HI("n", 256), HI("group", group), + HS("dtype", "bf16") }, EB(5, 256, 2, 1.5)); + add("quant_act_i8g", { HI("M", 5), HI("n", 256), HI("group", group), + HS("dtype", "f32") }, EB(5, 256, 4, 1.25)); add("quant_act_fp8", { HI("M", 5), HI("n", 256), HI("group", group), HS("dtype", "bf16") }, EB(5, 256, 2, 1.5)); add("had_quant_act_fp8", { HI("M", 5), HI("n", 256), HI("group", group), @@ -155,33 +161,39 @@ std::vector build_cases() { HS("dtype", "bf16"), HS("act", "silu") }); } /* The fp8 fusions off the grid: a row the group does not divide (260 = 4 x 64 + 4, so the last - * scale covers four values), f32 activations -- which are narrowed to bf16 all the same -- and - * the other gate and gain. */ + * scale covers four values), f32 activations (still narrowed to bf16), and the other gate and + * gain. */ add("rmsnorm_quant_fp8", { HI("M", 5), HI("n", 260), HF("eps", 1e-6), HI("group", 64), HS("dtype", "f32"), HF("wadd", 1) }); add("gated_quant_fp8", { HI("M", 5), HI("n", 260), HI("group", 64), HS("dtype", "f32"), HS("act", "sigmoid") }); add("gram_accum", { HI("M", 5), HI("n", 128), HI("group", 128), HS("dtype", "fp8_e4m3") }, 0, 2.0 * 5 * 128 * 128); - /* ...and the plain bf16 activation, which passes no scale. */ + /* The plain bf16 activation, with no scale. */ add("gram_accum", { HI("M", 5), HI("n", 260), HI("group", 128), HS("dtype", "bf16") }, 0, 2.0 * 5 * 260 * 260); - /* GEMM. K = 259 is deliberately not a multiple of anything. */ + /* GEMM. K = 259 is not a multiple of any vector or block width. + * + * gemm_nt_bias's activations run at M = 7 only. The product is computed the same way whatever + * `act` names, and the activation and residual are applied afterwards, element by element, by + * an epilogue with no M blocking (avx_gemm.cpp: gemm_epilogue), so M = 1 and 65 add nothing + * for them; those two keep the plain bias form for the product's own M edges. */ for (const char* dt : { "f32", "bf16", "f16" }) for (int M : { 1, 7, 65 }) { const double fl = 2.0 * M * 96 * 259; add("gemm_nt", { HI("M", M), HI("N", 96), HI("K", 259), HS("dtype", dt) }, 0, fl); add("gemm_nt_bias", { HI("M", M), HI("N", 96), HI("K", 259), HS("dtype", dt) }, 0, fl); - for (const char* act : { "none", "gelu", "gelu_tanh" }) - add("gemm_nt_bias", { HI("M", M), HI("N", 96), HI("K", 259), HS("dtype", dt), - HS("act", act) }, 0, fl); + if (M == 7) + for (const char* act : { "none", "gelu", "gelu_tanh" }) + add("gemm_nt_bias", { HI("M", M), HI("N", 96), HI("K", 259), HS("dtype", dt), + HS("act", act) }, 0, fl); add("logits_gemm", { HI("M", M), HI("n_vocab", 96), HI("n_embd", 259), HS("dtype", dt) }, 0, fl); } - /* Encoder-sized M at a width that is not a whole number of 48-column panels, with K odd and - * even: 37 rows take the bf16 dot-product path, 133 the outer-product one -- its column edge, - * its zero-paired last k and its five-row tail. */ + /* Encoder-sized M with N not a multiple of the 48-column panel, K odd and even: 37 rows take + * the bf16 dot-product path, 133 the outer-product one (column edge, zero-paired last k, + * five-row tail). */ for (const char* dt : { "f32", "bf16" }) for (int M : { 37, 133 }) for (int K : { 259, 64 }) { @@ -191,23 +203,50 @@ std::vector build_cases() { add("gemm_nt_bias", { HI("M", M), HI("N", 100), HI("K", K), HS("dtype", dt), HS("act", "gelu_tanh") }, 0, fl); } - /* fp8a8 and fp8a16 ARE THE ONLY TWO libref CAN DESCRIBE, and that is a real limit rather than - * a gap in this table: `gemm_nt_q` is one op over six weight formats and the SCALE GRID is - * what differs between them -- per row, per row-group, per output-row-block, an e8m0 exponent - * byte, with or without a zero point. Every one of those is a property of the kernel that - * reads it, so libref declines to guess (ref_shapes.cpp says so at length) and a case at - * "w4a8" would be SKIPPED, not checked. The packed-nibble path is still exercised -- through - * `dequant`, whose grid the schema does state. */ - for (const char* dt : { "fp8a8", "fp8a16" }) + /* The formats libref describes (ref_shapes.cpp): block fp8, and the int4 and int8 weights + * against quant_act_i8's step-ordered codes. The bias form needs `a_scale`, which fp8a16 (a + * bf16 activation) does not have, so libref declines it there. */ + for (const char* dt : { "fp8a8", "fp8a16", "w4a8", "w8a8" }) for (int M : { 1, 65 }) { const double fl = 2.0 * M * 96 * 256; add("gemm_nt_q", { HI("M", M), HI("N", 96), HI("K", 256), HI("group", 128), HS("dtype", dt) }, 0, fl); - add("gemm_nt_q_bias", { HI("M", M), HI("N", 96), HI("K", 256), HI("group", 128), - HS("dtype", dt) }, 0, fl); + if (std::strcmp(dt, "fp8a16") != 0) + add("gemm_nt_q_bias", { HI("M", M), HI("N", 96), HI("K", 256), HI("group", 128), + HS("dtype", dt) }, 0, fl); } - /* The gated form, which libref describes at fp8a8 only. N is the WEIGHT's rows, so the output - * is N/2 wide: 96 is one scale group a row at group 128 and 256 is two. */ + /* The int8 trunk (row-major codes, a scale per row per 128 of K on both sides) and OCP-MXFP4 + * (e2m1 codes with an E8M0 exponent per 32 of K against the E4M3 activation). */ + for (int M : { 1, 65 }) { + add("gemm_nt_q", { HI("M", M), HI("N", 96), HI("K", 256), HI("group", 128), + HS("dtype", "i8a8") }, 0, 2.0 * M * 96 * 256); + add("gemm_nt_q", { HI("M", M), HI("N", 96), HI("K", 256), HI("group", 32), + HS("dtype", "mxfp4a8") }, 0, 2.0 * M * 96 * 256); + } + /* Block fp8 off the 128 grid: N = 200 gives the weight's scale plane a second, partial block + * row (rows 128..199) and K = 320 a partial last group (256..319). */ + for (const char* dt : { "fp8a8", "fp8a16" }) + for (int M : { 1, 65 }) + add("gemm_nt_q", { HI("M", M), HI("N", 200), HI("K", 320), HI("group", 128), + HS("dtype", dt) }, 0, 2.0 * M * 200 * 320); + add("gemm_nt_q_bias", { HI("M", 7), HI("N", 200), HI("K", 320), HI("group", 128), + HS("dtype", "fp8a8") }, 0, 2.0 * 7 * 200 * 320); + /* The tile drivers' edges (avx_gemm_tile.cpp): K = 1104 is two of the bf16 driver's K chunks + * and three of the f32 one's, the last with a partial group; K = 17408 (the 27B's down) puts + * 490 rows in two or three super-blocks, the last one short. */ + for (const char* dt : { "fp8a8", "fp8a16", "i8a8", "mxfp4a8", "w4a8" }) + add("gemm_nt_q", { HI("M", 40), HI("N", 100), HI("K", 1104), + HI("group", std::strcmp(dt, "mxfp4a8") ? 128 : 32), HS("dtype", dt) }, + 0, 2.0 * 40 * 100 * 1104); + add("gemm_nt_q", { HI("M", 490), HI("N", 20), HI("K", 17408), HI("group", 128), + HS("dtype", "fp8a8") }, 0, 2.0 * 490 * 20 * 17408); + for (const char* dt : { "f32", "bf16" }) + add("gemm_nt", { HI("M", 40), HI("N", 100), HI("K", 1104), HS("dtype", dt) }, 0, + 2.0 * 40 * 100 * 1104); + add("gemm_nt", { HI("M", 250), HI("N", 20), HI("K", 17408), HS("dtype", "bf16") }, 0, + 2.0 * 250 * 20 * 17408); + /* The gated form, which libref describes at fp8a8 only. N is the weight's rows, so the output + * is N/2 = 96 wide. */ for (int M : { 1, 65 }) for (const char* act : { "silu", "sigmoid" }) add("gemm_nt_q_gated", { HI("M", M), HI("N", 192), HI("K", 256), HI("group", 128), @@ -224,9 +263,8 @@ std::vector build_cases() { HI("vocab_offset", 0), HF("wscale", 0.01) }); } - /* Attention. q_len 1 is decode, 17 a ragged verify window. `window` 0 is unbounded and 8 the - * sliding form, which is a different loop bound and where an off-by-one lives. 64 takes - * the prefill panel form (q_len >= 32, uniform), so the second kernel has coverage too. */ + /* Attention. q_len 1 is decode, 17 a ragged verify window, 64 the prefill panel form + * (q_len >= 32, uniform). `window` 0 is unbounded, 8 sliding (a different loop bound). */ for (const char* dt : { "f32", "bf16" }) for (int qlen : { 1, 17, 64 }) for (int window : { 0, 8 }) @@ -239,23 +277,45 @@ std::vector build_cases() { add("attn_dense", { HI("M", 24), HI("head_dim", 64), HI("gqa", 2), HI("causal", causal), HS("dtype", dt), HF("scale", 0.125), HI("max_seqlen", 24), HI("window", 0) }); - /* The sliding window both ways: bidirectional |i - j| < 5 and causal i - j < 5, over - * segments longer than the window so both bounds bite. */ + /* The sliding window both ways (bidirectional |i - j| < 5, causal i - j < 5), over segments + * longer than the window. */ for (const char* dt : { "f32", "bf16" }) for (int causal : { 0, 1 }) add("attn_dense", { HI("M", 24), HI("head_dim", 64), HI("gqa", 2), HI("causal", causal), HS("dtype", dt), HF("scale", 0.125), HI("max_seqlen", 24), HI("window", 5) }); - /* Gemma 4's audio attention: left 12 over segments longer than the window. */ + /* Blocks: each segment cut into blocks of 7 rows that attend within themselves (a chunked + * encoder's windows), the last block of a segment short. */ + for (const char* dt : { "f32", "bf16" }) + add("attn_dense", { HI("M", 24), HI("head_dim", 64), HI("gqa", 1), HI("causal", 0), + HS("dtype", dt), HF("scale", 0.125), HI("max_seqlen", 24), + HI("block", 7) }); + for (const char* dt : { "f32", "bf16" }) + add("seg_sinusoid", { HI("M", 30), HI("n", 64), HI("period", 13), HS("dtype", dt) }); + /* Gemma 4's audio attention: left 12, over segments longer than the window. */ for (const char* dt : { "f32", "bf16" }) for (int cd : { 1, 4 }) add("attn_local_rel", { HI("M", 40), HI("head_dim", 32), HI("n_head", 3), HI("left", 12), HI("right", 0), HF("softcap", 50.0), HI("cu_div", cd), HS("dtype", dt) }); + /* An fp8 cache under bf16 queries, as --kv-cache-dtype fp8 serves: decode and a ragged verify + * window, unbounded and sliding. */ + for (int qlen : { 1, 17 }) + for (int window : { 0, 8 }) + add("attn_paged", { HI("q_len", qlen), HI("head_dim", 64), HI("gqa", 4), + HI("block_size", 16), HI("causal", 1), HI("window", window), + HS("q_dtype", "bf16"), HS("kv_dtype", "fp8_e4m3"), + HF("scale", 0.125), HI("max_ctx", 128), HI("n_head", 8), + HI("max_seqs", 2) }); for (const char* dt : { "f32", "bf16" }) add("kv_store", { HI("M", 12), HI("head_dim", 64), HI("n_head_kv", 2), HI("block_size", 16), HS("kv_dtype", dt), HF("k_scale", 1.0), HF("v_scale", 1.0) }); + /* The fp8 store divides by the reader's descales; one below 1 and one above. */ + for (double ks : { 0.5, 2.0 }) + 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) }); 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), @@ -268,13 +328,22 @@ std::vector build_cases() { HS("mode", mode), HI("rotary_dim", 64), HF("wadd", 0), HI("v_norm", 1) }); } - /* `blocks`, the two-component vision form: x over the first half, y over the second, the - * components named in the other order from the planes. */ + /* `blocks`, the two-component vision form: x over the first half, y over the second, with the + * components listed in the opposite order to the position planes. */ for (const char* dt : { "f32", "bf16" }) { add("qk_norm_rope", { HI("M", 12), HI("head_dim", 64), HI("n_head", 4), HI("n_head_kv", 4), HF("theta", 100.0), HF("eps", 1e-6), HS("mode", "blocks"), HS("sections", "16 16"), HS("comps", "1 0"), HI("v_norm", 1), HS("dtype", dt) }); + /* Qwen-Image's two forms over one position component (libref describes no other): + * the DiT's adjacent pairs in one section, and Qwen3-VL's interleaved M-RoPE, which then + * reduces to NeoX pairs. Three components are avx_check_hand.cpp's. */ + add("qk_norm_rope", { HI("M", 12), HI("head_dim", 64), HI("n_head", 4), HI("n_head_kv", 4), + HF("theta", 10000.0), HF("eps", 1e-6), HS("mode", "gptj_blocks"), + HS("sections", "32"), HS("dtype", dt) }); + add("qk_norm_rope", { HI("M", 12), HI("head_dim", 64), HI("n_head", 4), HI("n_head_kv", 2), + HF("theta", 5e6), HF("eps", 1e-6), HS("mode", "imrope"), + HI("rotary_dim", 64), HS("sections", "12 10 10"), HS("dtype", dt) }); } add("rope_table", { HI("M", 12), HI("rot", 64), HF("theta", 10000.0), HF("scale", 1.0), HS("dtype", "f32") }); @@ -297,8 +366,8 @@ std::vector build_cases() { add("rope_table", { HI("M", 12), HI("rot", 64), HF("theta", 1e7), HF("scale", 1), HS("dtype", "f32"), HF("yarn_factor", 0), HF("yarn_magnitude", magnitude) }); } - /* QSA's compressed key at Flash-Next's geometry (n 128, ratio 4, a 64-wide rotary), stock and - * with YaRN, positions drawn up to the block count times the ratio. */ + /* QSA's compressed key at Flash-Next's geometry (n 128, ratio 4, 64-wide rotary), plain and + * with YaRN; positions are drawn up to block count times ratio. */ for (const char* dt : { "f32", "bf16" }) { add("qsa_block_key", { HI("M", 12), HI("n", 128), HI("ratio", 4), HI("rotary_dim", 64), HF("eps", 1e-6), HF("theta", 1e7), HF("scale", 1), HF("wadd", 1), @@ -308,8 +377,42 @@ std::vector build_cases() { HS("dtype", dt), HF("yarn_factor", 2), HF("yarn_low", 14), HF("yarn_high", 22), HF("yarn_magnitude", 1.069314718) }); } + /* The rest of the indexer at Flash-Next's geometry (4 heads of 128, ratio 4, a 7-row ring for + * depth 3) with the block count cut to the checker's budget, then the edges: block counts that + * are no multiple of any vector width, one block, several sequences, more rows than a score + * tile, a head width that pads, and a topk that keeps every live block or splits the zeros. + * libref's descriptions draw page ids >= 0, cu from 0 and nc in [0, blocks]; the hand-built + * cases (avx_check_hand.cpp) cover the rest. */ + for (const char* dt : { "bf16", "f32" }) { + add("qsa_score", { HI("M", 4), HI("n", 128), HI("heads", 4), HI("blocks", 300), + HI("seqs", 1), HS("dtype", dt) }); + add("qsa_tail_store", { HI("M", 5), HI("n", 128), HI("ratio", 4), HI("ring", 7), + HI("seqs", 5), HS("dtype", dt) }); + add("qsa_work", { HI("M", 8), HI("n", 128), HI("ratio", 4), HI("ring", 7), HI("seqs", 4), + HI("work", 6), HS("dtype", dt) }); + } + add("qsa_score", { HI("M", 7), HI("n", 128), HI("heads", 4), HI("blocks", 37), HI("seqs", 3), + HS("dtype", "bf16") }); + add("qsa_score", { HI("M", 19), HI("n", 72), HI("heads", 3), HI("blocks", 41), HI("seqs", 2), + HS("dtype", "f32") }); + add("qsa_score", { HI("M", 1), HI("n", 128), HI("heads", 4), HI("blocks", 1), HI("seqs", 1), + HS("dtype", "bf16") }); + add("qsa_select", { HI("M", 4), HI("blocks", 300), HI("topk", 32), HI("ratio", 4), + HI("seqs", 1) }); + add("qsa_select", { HI("M", 4), HI("blocks", 300), HI("topk", 200), HI("ratio", 4), + HI("seqs", 1) }); + add("qsa_select", { HI("M", 3), HI("blocks", 300), HI("topk", 512), HI("ratio", 4), + HI("seqs", 1) }); + add("qsa_select", { HI("M", 7), HI("blocks", 129), HI("topk", 16), HI("ratio", 4), + HI("seqs", 3) }); + add("qsa_select", { HI("M", 2), HI("blocks", 1), HI("topk", 1), HI("ratio", 3), + HI("seqs", 1) }); + add("qsa_tail_store", { HI("M", 3), HI("n", 37), HI("ratio", 2), HI("ring", 2), HI("seqs", 3), + 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 proportional ladder: a partial rotary (rotary_dim < head_dim) with `ladder` head, so the - * denominator is head_dim and libavx's answer must agree with libref's on it. */ + * frequency denominator is head_dim. */ 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), @@ -317,6 +420,17 @@ std::vector build_cases() { } add("rope_table", { HI("M", 12), HI("rot", 32), HF("theta", 10000.0), HF("scale", 1.0), HS("dtype", "f32"), HI("head_dim", 64), HS("ladder", "head") }); + /* A rotary wider than 1024 (libref takes up to 2048, i.e. 1024 frequencies), plain and with + * contiguous sections, and QSA's key at the same width. */ + add("rope", { HI("M", 3), HI("head_dim", 1280), HI("n_head", 1), HI("n_head_kv", 1), + HF("theta", 10000.0), HF("scale", 1.0), HS("mode", "neox"), + HI("rotary_dim", 1280), HS("dtype", "f32") }); + add("rope", { HI("M", 3), HI("head_dim", 1280), HI("n_head", 1), HI("n_head_kv", 1), + HF("theta", 10000.0), HF("scale", 1.0), HS("mode", "mrope"), + HI("rotary_dim", 1280), HS("sections", "214 213 213"), HS("dtype", "f32") }); + add("qsa_block_key", { HI("M", 3), HI("n", 1280), HI("ratio", 2), HI("rotary_dim", 1280), + HF("eps", 1e-6), HF("theta", 10000.0), HF("scale", 1), HF("wadd", 1), + HS("dtype", "f32") }); /* The multi-component forms: Qwen3-VL's interleaved M-RoPE over a partial rotary, and a vision * tower's 2-D axial rotary over a whole 72-wide head. */ for (const char* dt : { "f32", "bf16" }) { @@ -327,41 +441,39 @@ std::vector build_cases() { HF("theta", 10000.0), HF("scale", 1.0), HS("mode", "axial"), HI("rotary_dim", 72), HS("sections", "18 18"), HS("dtype", dt) }); add("grid_embed", { HI("M", 20), HI("n", 72), HI("side", 6), HS("dtype", dt) }); - /* Two table sides. A drawn grid is never larger than the table, so enlarging is + /* Two table sides. A drawn grid never exceeds the table, so upscaling is covered by * avx_check's hand-built case. */ add("grid_embed_aa", { HI("M", 20), HI("n", 72), HI("side", 16), HS("dtype", dt) }); add("grid_embed_aa", { HI("M", 40), HI("n", 72), HI("side", 4), HS("dtype", dt) }); } - /* MoE. `a_order` exists because the two grouped GEMMs of one routed block disagree about it, - * and a check that ran one spelling could never have seen the defect it was added for. */ + /* MoE. Both `a_order` spellings, since the two grouped GEMMs of a routed block use + * different ones. */ for (const char* dt : { "f32", "bf16" }) { add("router_topk", { HI("M", 9), HI("n_expert", 8), HI("top_k", 2), HI("norm", 1), HS("dtype", dt) }); add("router_topk", { HI("M", 9), HI("n_expert", 8), HI("top_k", 2), HI("norm", 0), HS("dtype", dt) }); add("moe_gather", { HI("M", 9), HI("n", 128), HI("top_k", 2), HS("dtype", dt) }); - /* The shared-expert fold: `shared`/`shared_gate` are always described, so the - * harness always presents them -- this case names the sigmoid spelling, the plain one - * above covers "none". */ + /* The shared-expert fold: `shared`/`shared_gate` are always described, so always + * present; this case uses sigmoid, the one above "none". */ add("moe_gather", { HI("M", 9), HI("n", 128), HI("top_k", 2), HS("dtype", dt), HS("act", "sigmoid") }); add("row_topk", { HI("M", 5), HI("N", 97), HI("R", 4), HI("vocab_off", 0), HS("dtype", dt) }); add("row_topk_merge", { HI("M", 5), HI("R", 4), HI("world_size", 2), HS("dtype", dt) }); add("pair_argmax", { HI("M", 5), HI("n", 8), HS("dtype", dt) }); - /* "sorted" and not "slot": libref refuses any other spelling with RAD_E_UNSUPPORTED, and a - case at a spelling both plugins decline is a case that proves nothing. */ + /* "sorted", not "slot": libref refuses other spellings with RAD_E_UNSUPPORTED. */ for (const char* order : { "token", "sorted" }) { add("moe_gemm", { HI("M", 9), HI("N", 64), HI("K", 128), HI("n_expert", 8), HI("top_k", 2), HS("a_order", order), HS("dtype", dt) }); - /* `fp8a8`, the block-fp8 grid: libref describes a grouped GEMM's weight scale plane - * only at a dtype that names its grid. */ + /* `fp8a8` (block fp8): libref describes a grouped GEMM's scale plane only for a + * dtype that names its grid. */ add("moe_gemm_q", { HI("M", 9), HI("N", 64), HI("K", 128), HI("n_expert", 8), HI("top_k", 2), HI("group", 128), HS("a_order", order), HS("dtype", "fp8a8") }); } - /* The two classes at different widths: a gate/up pair whose odd experts are half as wide + /* Two classes at different widths: a gate/up pair whose odd experts are half as wide * (the output's second part begins past the odd class's zeros), and a down projection * whose odd experts are half as long. */ add("moe_gemm_q", { HI("M", 9), HI("N", 256), HI("K", 128), HI("N_odd", 128), @@ -370,9 +482,9 @@ std::vector build_cases() { add("moe_gemm_q", { HI("M", 9), HI("N", 64), HI("K", 256), HI("K_odd", 128), HI("n_expert", 8), HI("top_k", 2), HI("group", 128), HS("a_order", "sorted"), HS("dtype", "fp8a8") }); - /* Four classes at three widths -- a four-rank slice of a five-block expert is two blocks - * of one class and one of each other -- over ten experts, so classes 2 and 3 hold one - * fewer than 0 and 1: the gate/up pair and the down projection. */ + /* Four classes at three widths (a four-rank slice of a five-block expert is two blocks of + * one class and one of each other), over ten experts, so classes 2 and 3 hold one fewer + * than 0 and 1; for the gate/up pair and the down projection. */ add("moe_gemm_q_mod4", { HI("M", 9), HI("N", 128), HI("K", 128), HI("N_1", 256), HI("N_2", 128), HI("N_3", 128), HI("parts", 2), HI("n_expert", 10), HI("top_k", 2), HI("group", 128), @@ -383,21 +495,23 @@ std::vector build_cases() { HS("dtype", "fp8a8") }); } add("moe_scatter", { HI("M", 9), HI("n_expert", 8), HI("top_k", 2), HI("expert_base", 0) }); + /* The draft head's rerank: f32 and bf16 activations over an f32 head, the whole vocabulary on + * this rank and a shard of it (candidates below vocab_off become pads). */ + for (const char* dt : { "f32", "bf16" }) + add("logit_rerank", { HI("M", 5), HI("R", 8), HI("n_vocab", 300), HI("n_embd", 259), + HI("vocab_off", 0), HS("dtype", dt) }); + add("logit_rerank", { HI("M", 3), HI("R", 16), HI("n_vocab", 64), HI("n_embd", 128), + HI("vocab_off", 100), HS("dtype", "f32") }); - /* Gated delta net. head_k = head_v = 32 and chunk 8 keeps the state matrices small enough to - * read in a dump while still running every loop the full 128/128 shape does. + /* Gated delta net. head_k = head_v = 32 and chunk 8 keep the states small enough to inspect + * while running every loop the 128/128 shape does. * - * `n_head_k`, `n_head_v` and `n_seq` ARE NOT PARAMETERS OF THESE OPS and are passed anyway. - * The gdn family reads its head counts off the OPERANDS, so no op names them and no geometry - * carries them -- which means a tool sizing the operands cold has nothing to size them FROM, - * and libref's shape hook declines (RAD_E_UNSUPPORTED) rather than inventing a head ratio and - * calling the result correctness. tools/opshapes.h calls the same three a `ShapeCtx` and takes - * them from the container's metadata. Here they are stated in the case, which is the same - * decision made by the same person for the same reason; without them every gdn case is SKIPPED - * AND COUNTED and the family is never checked at all. + * `n_head_k`, `n_head_v` and `n_seq` are not op parameters: the gdn ops read head counts from + * their operands, so libref's shape hook cannot size them cold and declines without these + * hints (tools/opshapes.h takes the same three, as `ShapeCtx`, from container metadata). + * Without them every gdn case would be skipped. * - * `n_seq` 2 rather than 1 deliberately: every gdn op opens by reading `cu`, and a single - * sequence makes a wrong `cu` walk indistinguishable from a right one. */ + * `n_seq` is 2 so that a wrong `cu` walk differs from a right one. */ add("gdn_conv_prep", { HI("M", 16), HI("head_k", 32), HI("head_v", 32), HI("chunk", 8), HI("conv_width", 4), HF("l2_eps", 1e-6), HF("softplus_thr", 20.0), HI("n_head_k", 2), HI("n_head_v", 2), HI("n_seq", 2) }); @@ -422,50 +536,135 @@ std::vector build_cases() { add("gdn_gated_rmsnorm", { HI("M", 12), HI("channels", 128), HF("eps", 1e-6), HS("act", act) }); - /* Collectives at world_size 1, which is the only width libavx serves and says so in its row. */ + /* Collectives at world_size 1, the only width libavx serves. */ add("all_reduce", { HI("world_size", 1), HI("numel", 645), HS("dtype", "f32"), HI("exact", 1), HI("min_bytes", 0), HI("hops", 1) }); add("all_gather", { HI("world_size", 1), HI("numel", 645), HS("dtype", "f32"), HI("row", 0) }); - /* Sampling. n_vocab 517 is above every vector width and divides nothing; n_cand 12 is a real - * candidate set after a top-k. */ + /* Sampling. n_vocab 517 exceeds every vector width and is not a multiple of any; n_cand 12 is + * a realistic candidate set after top-k. */ for (const char* op : { "sample_penalties", "sample_dry", "sample_temp", "sample_mask", "sample_argmax" }) add(op, { HI("M", 5), HI("n_vocab", 517) }); add("sample_topk", { HI("M", 5), HI("n_vocab", 517), HI("vocab_off", 0) }); - /* k 7 and 20 (OpenAI's top_logprobs bound) against 517: the one-pass set starts full after - * seven columns, and an offset shard reports global ids. */ + /* k 7 and 20 (OpenAI's top_logprobs bound) against 517 columns; the offset case checks that + * a shard reports global ids. */ for (int64_t k : { 7, 20 }) add("sample_logprobs", { HI("M", 5), HI("n_vocab", 517), HI("k", k), HI("vocab_off", 0) }); add("sample_logprobs", { HI("M", 3), HI("n_vocab", 517), HI("k", 5), HI("vocab_off", 1000) }); + /* sample_merge_topk has no table case: libref cannot describe its packed (id, logit) words + * (ref_shapes.cpp), so avx_check_hand.cpp builds them. */ for (const char* op : { "sample_topp", "sample_minp", "sample_typical", "sample_xtc", - "sample_pick", "sample_merge_topk" }) + "sample_pick" }) add(op, { HI("M", 5), HI("n_cand", 12) }); - /* The drafter's walk: four steps over eight candidates, so every step after the first reads its - * predecessor off the walk. Rank 64 is whole vectors at every level and 37 is not; a stride of - * 2 reads every other anchor. */ + /* The drafter's walk: every step after the first reads its predecessor from the walk. Rank 64 + * is whole vectors at every level, 37 is not; anchor stride 2 reads every other anchor. */ add("dflash_select", { HI("M", 3), HI("steps", 4), HI("top_k", 8), HI("rank", 64), HI("n_vocab", 300), HI("anchor_stride", 1), HS("dtype", "bf16") }); add("dflash_select", { HI("M", 5), HI("steps", 3), HI("top_k", 12), HI("rank", 37), HI("n_vocab", 97), HI("anchor_stride", 2), HS("dtype", "bf16") }); + /* DFlash2's convolution: the 27B drafter's form (2 taps, groups of 16) over a narrower row, + * then groups that are no multiple of a vector, three taps and a one-row block. f16 rows take + * the path through f32 copies, bf16 and f32 the fused one. */ + for (const char* dt : { "bf16", "f32" }) + add("dflash_conv", { HI("T", 16), HI("hidden_size", 640), HI("taps", 2), + HI("group_size", 16), HI("NG", 40), HI("block_size", 4), + HS("dtype", dt) }); + add("dflash_conv", { HI("T", 11), HI("hidden_size", 36), HI("taps", 3), HI("group_size", 4), + HI("NG", 9), HI("block_size", 5), HS("dtype", "f32") }); + add("dflash_conv", { HI("T", 6), HI("hidden_size", 48), HI("taps", 2), HI("group_size", 48), + HI("NG", 1), HI("block_size", 1), HS("dtype", "bf16") }); + add("dflash_conv", { HI("T", 11), HI("hidden_size", 36), HI("taps", 3), HI("group_size", 4), + HI("NG", 9), HI("block_size", 5), HS("dtype", "f16") }); + + /* Image generation (Qwen-Image 2.1, arch/qwenimage21), scaled down: the DiT's norms over rows + * that are not a multiple of any vector, the latent's 64 channels in lanes of 16 rows over two + * entries, the decoder's convolutions and shortcuts on the eight-column pictures libref picks + * (a channel count below and above the convolution's 48-column panel, every padding and + * resampling form, and 256 pixels for the bf16 outer-product path), and the DiT's attention: + * 40 rows (one query block and part of a second) against a 37-key prefix (two whole blocks + * and part of a third), both score forms. Several entries, missing blocks and column slices + * are avx_check_hand.cpp's. */ + static const std::string kMul = [] { + std::string s; + for (int i = 0; i < 67; ++i) s += (i ? " " : "") + std::to_string(0.9 + 0.013 * i); + return s; + }(); + static const std::string kAdd = [] { + std::string s; + for (int i = 0; i < 67; ++i) s += (i ? " " : "") + std::to_string(0.017 * i - 0.5); + return s; + }(); + for (const char* dt : { "f32", "bf16" }) { + add("ln_mod", { HI("M", 7), HI("n", 645), HF("eps", 1e-6), HS("dtype", dt) }, + EB(7, 645, dt[0] == 'f' ? 4 : 2, 2)); + add("gate_add", { HI("M", 7), HI("n", 645), HS("dtype", dt) }, + EB(7, 645, dt[0] == 'f' ? 4 : 2, 3)); + for (int gated : { 1, 0 }) + add("ln_mod_quant_fp8", { HI("M", 5), HI("n", 256), HF("eps", 1e-6), HI("group", 128), + HI("gated", gated), HS("dtype", dt) }); + for (int round : { 1, 0 }) + add("timestep_embed", { HI("M", 3), HI("n", 256), HF("scale", 1000.0), + HF("max_period", 10000.0), HI("round", round), + HS("dtype", dt) }); + add("lane_gather", { HI("M", 24), HI("n", 64), HI("stride", 16), HI("n_seq", 2), + HS("dtype", dt) }); + add("lane_store", { HI("M", 12), HI("n", 64), HI("stride", 16), HS("dtype", dt) }); + add("randn_lanes", { HI("M", 24), HI("n", 64), HI("stride", 16), HI("n_seq", 2), + HS("dtype", dt) }); + add("flow_euler", { HI("M", 24), HI("n", 64), HI("stride", 16), HS("dtype", dt) }); + for (const char* mode : { "fma", "inv" }) + add("chan_affine", { HI("M", 9), HI("n", 67), HS("mul", kMul.c_str()), + HS("add", kAdd.c_str()), HS("mode", mode), HS("dtype", dt) }); + for (const char* act : { "silu", "none" }) + add("l2norm_chan", { HI("M", 9), HI("n", 645), HS("act", act), HS("dtype", dt) }); + add("to_rgba8", { HI("M", 9), HI("n", 4), HS("dtype", dt) }); + add("gelu_tanh", { HI("M", 6), HI("n", 645), HS("dtype", dt) }); + add("scatter_add_rows", { HI("M", 6), HI("n", 645), HS("dtype", dt) }); + struct Conv { int M, cin, cout, k, stride, up; const char* pad; }; + static const Conv kConv[] = { + { 64, 20, 24, 3, 1, 1, "same" }, { 64, 20, 52, 3, 1, 1, "same" }, + { 64, 4, 52, 3, 1, 1, "same" }, { 64, 20, 52, 1, 1, 1, "same" }, + { 64, 20, 12, 1, 1, 1, "same" }, { 64, 20, 52, 3, 2, 1, "down" }, + { 64, 20, 52, 3, 1, 2, "same" }, { 64, 20, 4, 3, 1, 1, "same" }, + { 256, 20, 52, 3, 1, 1, "same" }, + }; + for (const Conv& v : kConv) + add("conv2d_nhwc", { HI("M", v.M), HI("cin", v.cin), HI("cout", v.cout), HI("k", v.k), + HI("stride", v.stride), HS("pad", v.pad), HI("up", v.up), + HS("dtype", dt) }, + 0, 2.0 * v.M * v.cout * v.cin * v.k * v.k); + for (int ft : { 1, 2 }) { + add("d2s_add", { HI("M", 64), HI("cin", 24), HI("cout", 24), HI("ft", ft), + HS("dtype", dt) }); + add("d2s_add", { HI("M", 64), HI("cin", 48), HI("cout", 24), HI("ft", ft), + HS("dtype", dt) }); + add("s2d_avg_add", { HI("M", 64), HI("cin", 24), HI("cout", 24), HI("ft", ft), + HS("dtype", dt) }); + add("s2d_avg_add", { HI("M", 64), HI("cin", 12), HI("cout", 24), HI("ft", ft), + HS("dtype", dt) }); + } + for (const char* qk : { "bf16", "i8" }) + for (int causal : { 0, 1 }) + for (int hd : { 64, 72 }) + add("attn_prefix_self", { HI("q_len", 40), HI("head_dim", hd), HI("gqa", 2), + HI("block_size", 16), HI("causal", causal), + HS("q_dtype", dt), HS("kv_dtype", dt), + HF("scale", 1.0 / std::sqrt((double)hd)), + HI("n_head", 4), HS("qk", qk) }); + } /* ================================================================== speed-only, at model size * - * WHY THESE EXIST SEPARATELY. Everything above is sized to break a kernel, not to represent - * one -- a 640-wide row exercises every code path a 2048-wide row does and the checker would - * spend minutes inside libref to learn nothing more. But SPEED is decided by the cache - * hierarchy, and a shape that fits in L1 answers a different question from the one a - * deployment asks. rad-avx-check skips every case below; rad-avx-bench runs them. + * Timed by rad-avx-bench, skipped by rad-avx-check. The cases above are sized to break kernels; + * speed depends on the cache hierarchy and needs real shapes. * - * The geometry is a ~1.5B dense model -- n_embd 2048, n_ff 5632, n_vocab 32000, 16 heads of - * 128 -- which is the size a CPU plugin plausibly serves. M = 1 is decode, 64 a speculative - * verify window, 512 a prefill chunk. + * Geometry of a ~1.5B dense model (n_embd 2048, n_ff 5632, n_vocab 32000, 16 heads of 128). + * M = 1 is decode, 64 a speculative verify window, 512 a prefill chunk. * - * `logits_gemm` AT 32000 x 2048 IS THE ONE THAT IS NOT A GEMM. Its weight is 128 MiB in bf16, - * which fits in no cache on any part this runs on, so whatever the flop count says it is a memory - * benchmark -- and reading it against the DRAM triad rather than the FMA ceiling is the only - * honest way to read it. It is in this list precisely because no other case can show that. */ + * `logits_gemm` at 32000 x 2048 is memory-bound: its 128 MiB bf16 weight fits no cache, so + * compare it with the DRAM triad, not the FMA ceiling. */ auto speed = [&](const char* op, std::vector

p, double bytes, double flops) { c.push_back(Case{ op, std::move(p), bytes, flops, true }); }; @@ -475,7 +674,7 @@ std::vector build_cases() { speed("gemm_nt", { HI("M", M), HI("N", 5632), HI("K", 2048), HS("dtype", "bf16") }, 0, 2.0 * M * 5632 * 2048); } - /* An encoder step: every token of the batch at once, at EmbeddingGemma 2's two FFN shapes. */ + /* An encoder step (all tokens at once) at EmbeddingGemma 2's two FFN shapes. */ for (int M : { 2048 }) { speed("gemm_nt", { HI("M", M), HI("N", 4096), HI("K", 512), HS("dtype", "bf16") }, 0, 2.0 * M * 4096 * 512); @@ -493,13 +692,14 @@ std::vector build_cases() { HS("dtype", "bf16") }, (double)M * 2048 * 3, 0); speed("quant_act_i8", { HI("M", M), HI("n", 2048), HI("group", 128), HS("dtype", "bf16") }, (double)M * 2048 * 3, 0); + speed("quant_act_i8g", { HI("M", M), HI("n", 2048), HI("group", 128), + HS("dtype", "bf16") }, (double)M * 2048 * 3, 0); speed("had_quant_act_i8", { HI("M", M), HI("n", 2048), HI("group", 128), HS("dtype", "bf16") }, (double)M * 2048 * 3, 0); } - /* GDN at qwen35 model shape (k128/v128, chunk 64, 16 key heads, 48 value heads): the - * prefill heart (chunk_scan over a 512 chunk) and the decode heart (recurrent_update at - * q_len 1). NO RATE: the traffic denominator depends on the state layout, so a time and no - * rate is the honest column. libref runs these scalar -- keep --iters low. */ + /* GDN at qwen35 model shape (k128/v128, chunk 64, 16 key heads, 48 value heads): chunk_scan + * over a 512 chunk (prefill) and recurrent_update at q_len 1 (decode). No rate: the traffic + * depends on the state layout. libref runs these scalar, so keep --iters low. */ speed("gdn_chunk_scan", { HI("M", 512), HI("head_k", 128), HI("head_v", 128), HI("chunk", 64), HF("scale", 0.176), HI("state_fp16", 0), HI("n_head_k", 16), HI("n_head_v", 48), HI("n_seq", 2) }, 0, 0); @@ -516,7 +716,7 @@ std::vector build_cases() { speed("gdn_conv_prep", { HI("M", 512), HI("head_k", 128), HI("head_v", 128), HI("chunk", 64), HI("conv_width", 4), HF("l2_eps", 1e-6), HF("softplus_thr", 20.0), HI("n_head_k", 16), HI("n_head_v", 48), HI("n_seq", 2) }, 0, 0); - /* Conv update at decode shape: one new token a sequence, same widths. */ + /* Conv update at decode shape: one new token per sequence, same widths. */ speed("gdn_conv_update", { HI("q_len", 1), HI("head_k", 128), HI("head_v", 128), HI("conv_width", 4), HI("max_query_len", 1), HI("n_head_k", 16), HI("n_head_v", 48), HI("n_seq", 2) }, 0, 0); @@ -525,15 +725,13 @@ std::vector build_cases() { speed("sample_argmax", { HI("M", 1), HI("n_vocab", 32000) }, (double)32000 * 4, 0); speed("sample_logprobs", { HI("M", 1), HI("n_vocab", 32000), HI("k", 20) }, (double)32000 * 4, 0); speed("sample_topk", { HI("M", 1), HI("n_vocab", 32000), HI("vocab_off", 0) }, 0, 0); - /* Decode attention over a real context: 16 query heads in groups of 4, 2048 keys already in - * the cache. This is the shape a decode step spends its time in. */ + /* Decode attention over a real context: 16 query heads in groups of 4, 2048 cached keys. */ speed("attn_paged", { HI("q_len", 1), HI("head_dim", 128), HI("gqa", 4), HI("block_size", 16), HI("causal", 1), HI("window", 0), HS("q_dtype", "bf16"), HS("kv_dtype", "bf16"), HF("scale", 0.088), HI("max_ctx", 2048), HI("n_head", 16), HI("max_seqs", 1) }, - /* NO RATE. The KV bytes an attention row reads depend on the CONTEXT LENGTH the - draw put in `seqused`, which this table does not set and cannot see, so any - denominator here would be invented. A time and no rate is the honest column. */ + /* No rate: the KV bytes read depend on the context length drawn into `seqused`, + which this table does not control. */ 0, 0); /* Prefill attention: 512 queries over 512 cached keys, same heads. */ speed("attn_paged", { HI("q_len", 512), HI("head_dim", 128), HI("gqa", 4), @@ -541,6 +739,43 @@ std::vector build_cases() { HS("q_dtype", "bf16"), HS("kv_dtype", "bf16"), HF("scale", 0.088), HI("max_ctx", 512), HI("n_head", 16), HI("max_seqs", 1) }, 0, 0); + /* Qwen3.8-Flash-Next's indexer (arch/qwen4exp_fp8: 4 heads of 128, ratio 4, topk 512, a + * 7-row ring at depth 3) over 8K, 64K and 200K tokens of context: decode at one query and at + * one sequence's four verify rows, and a 2048-token prefill chunk at 64K. Decode streams the + * bf16 block keys (256 bytes a block), so it is rated in GB/s; the prefill chunk is FMA work. + * The bench sets every block complete and every query past all of them (avx_bench.cpp: + * model_shape). Page ids are drawn at random, which a block table need not be in practice. */ + for (const int64_t blocks : { 2048, 16384, 50000 }) + for (const int64_t M : { 1, 4 }) + speed("qsa_score", { HI("M", M), HI("n", 128), HI("heads", 4), HI("blocks", blocks), + HI("seqs", 1), HS("dtype", "bf16") }, + (double)blocks * (128 * 2 + 4) + (double)M * blocks * 4, 0); + speed("qsa_score", { HI("M", 2048), HI("n", 128), HI("heads", 4), HI("blocks", 16384), + HI("seqs", 1), HS("dtype", "bf16") }, + 0, 2.0 * 2048 * 4 * 128 * 16384); + for (const int64_t blocks : { 2048, 16384, 50000 }) + for (const int64_t M : { 1, 4 }) + speed("qsa_select", { HI("M", M), HI("blocks", blocks), HI("topk", 512), + HI("ratio", 4), HI("seqs", 1) }, + (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 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), + HI("seqs", 4), HS("dtype", "bf16") }, 4.0 * 128 * 2 * 2, 0); + speed("qsa_work", { HI("M", 4), HI("n", 128), HI("ratio", 4), HI("ring", 7), HI("seqs", 4), + HI("work", 5), HS("dtype", "bf16") }, 4.0 * 4 * 128 * 2 * 2, 0); + speed("qsa_work", { HI("M", 2048), HI("n", 128), HI("ratio", 4), HI("ring", 7), + HI("seqs", 512), HI("work", 513), HS("dtype", "bf16") }, + 2048.0 * 128 * 2 * 2, 0); + /* The 27B DFlash2 drafter's convolution (arch/common/rad_block_dflash2.h: n_embd 5120, 2 + * taps, groups of 16, a 16-row query block): one sequence's block and four. */ + for (const int64_t T : { 16, 64 }) + speed("dflash_conv", { HI("T", T), HI("hidden_size", 5120), HI("taps", 2), + HI("group_size", 16), HI("NG", 320), HI("block_size", 16), + HS("dtype", "bf16") }, + (double)T * 5120 * 2 * 2 + (double)T * 2 * 320 * 2 + 2.0 * 5120 * 2, 0); /* Rope at model shape: 512 tokens, 16+4 heads of 128. Time-only (libref scalar). */ speed("rope", { HI("M", 512), HI("head_dim", 128), HI("n_head", 16), HI("n_head_kv", 4), HF("theta", 10000.0), HF("scale", 1.0), HS("mode", "neox"), @@ -550,5 +785,85 @@ std::vector build_cases() { HF("scale", 1.0), HS("mode", "neox"), HI("rotary_dim", 128), HF("wadd", 0) }, 0, 0); + /* Qwen-Image 2.1 (docs/ARCHITECTURES.md): the VAE decoder's widths 1152..144 and the DiT's + * 32 heads of 128 over 4096 rows. Each case is about 25 GFLOP so a one-thread run stays + * practical; libref is not timed past 2e10 (rad-avx-bench). A 512 x 512 picture's decoder + * runs its 1152-wide convolutions at 32 x 32 pixels, its 576-wide ones at 128 x 128 and its + * 144-wide ones at 512 x 512; the cases cut the pixels to keep the width (libref describes an + * eight-column picture, the same work per pixel). */ + struct ConvSpeed { int64_t M, cin, cout, k, up; }; + static const ConvSpeed kConvSpeed[] = { + { 1024, 1152, 1152, 3, 1 }, /* mid block and up block 0, at 32 x 32 */ + { 4096, 576, 576, 3, 1 }, /* up block 2 */ + { 16384, 288, 288, 3, 2 }, /* up block 3's upsampler, nearest 2x then 3 x 3 */ + { 65536, 144, 144, 3, 1 }, /* up block 4, at the picture's resolution */ + { 262144, 144, 4, 3, 1 }, /* conv_out at 512 x 512: four output channels */ + { 1024, 1152, 3456, 1, 1 }, /* the middle attention's qkv, 1 x 1 */ + }; + for (const ConvSpeed& v : kConvSpeed) + speed("conv2d_nhwc", { HI("M", v.M), HI("cin", v.cin), HI("cout", v.cout), HI("k", v.k), + HI("stride", 1), HS("pad", "same"), HI("up", v.up), + HS("dtype", "bf16") }, + 0, 2.0 * (double)v.M * v.cout * v.cin * v.k * v.k); + /* The denoising attention: an image's 1024 latent rows (512 x 512) against a 256-key + * conditioning, all 32 heads; 4096 rows (1024 x 1024) over four heads (the cost is per head, + * and four heads of 128 query blocks fill the threads). Both score forms. */ + for (const char* qk : { "bf16", "i8" }) { + speed("attn_prefix_self", { HI("q_len", 1024), HI("head_dim", 128), HI("gqa", 1), + HI("block_size", 16), HI("causal", 0), HS("q_dtype", "bf16"), + HS("kv_dtype", "bf16"), HF("scale", 0.08838834764831845), + HI("n_head", 32), HI("ctx", 256), HS("qk", qk) }, + 0, 4.0 * 1024 * (1024 + 256) * 128 * 32); + speed("attn_prefix_self", { HI("q_len", 4096), HI("head_dim", 128), HI("gqa", 1), + HI("block_size", 16), HI("causal", 0), HS("q_dtype", "bf16"), + HS("kv_dtype", "bf16"), HF("scale", 0.08838834764831845), + HI("n_head", 4), HI("ctx", 256), HS("qk", qk) }, + 0, 4.0 * 4096 * (4096 + 256) * 128 * 4); + } + /* The DiT's row ops over a 512 x 512 picture's 1024 rows of 4096, and the decoder's at its + * last level (512 x 512 pixels): bytes are the operands' reads and writes. */ + speed("ln_mod", { HI("M", 1024), HI("n", 4096), HF("eps", 1e-6), HS("dtype", "bf16") }, + 1024.0 * 4096 * 2 * 2, 0); + speed("gate_add", { HI("M", 1024), HI("n", 4096), HS("dtype", "bf16") }, + 1024.0 * 4096 * 2 * 3, 0); + speed("ln_mod_quant_fp8", { HI("M", 1024), HI("n", 4096), HF("eps", 1e-6), HI("group", 128), + HI("gated", 1), HS("dtype", "bf16") }, + 1024.0 * 4096 * (2 * 3 + 1), 0); + speed("qk_norm_rope", { HI("M", 1024), HI("head_dim", 128), HI("n_head", 32), + HI("n_head_kv", 32), HF("theta", 10000.0), HF("eps", 1e-6), + HS("mode", "gptj_blocks"), HS("sections", "64"), + HS("dtype", "bf16") }, 1024.0 * 64 * 128 * 2 * 2, 0); + speed("l2norm_chan", { HI("M", 262144), HI("n", 144), HS("act", "silu"), HS("dtype", "bf16") }, + 262144.0 * 144 * 2 * 2, 0); + speed("d2s_add", { HI("M", 262144), HI("cin", 576), HI("cout", 288), HI("ft", 1), + HS("dtype", "bf16") }, 262144.0 * 288 * 2 * 2 + 65536.0 * 576 * 2, 0); + /* Qwen3.6-35B-A3B's routed experts in block fp8 (256 experts of 512 at top 8 over n_embd + * 2048): gate|up in two parts with the token-order activation, down with the sorted one. The + * bytes are the experts a call routes to at most, top_k * M of them. */ + for (int M : { 1, 8, 512 }) { + const double ex = std::min(256.0, 8.0 * M); + speed("moe_gemm_q", { HI("M", M), HI("N", 1024), HI("K", 2048), HI("parts", 2), + HI("n_expert", 256), HI("top_k", 8), HI("group", 128), + HS("a_order", "token"), HS("dtype", "fp8a8") }, + ex * 1024 * 2048, 2.0 * M * 8 * 1024 * 2048); + speed("moe_gemm_q", { HI("M", M), HI("N", 2048), HI("K", 512), HI("n_expert", 256), + HI("top_k", 8), HI("group", 128), HS("a_order", "sorted"), + HS("dtype", "fp8a8") }, + ex * 2048 * 512, 2.0 * M * 8 * 2048 * 512); + } + /* Flash-Next's gated residual read (n 2560, hc 4, lowrank 320) at decode, a verify window and + * a prefill chunk; the bytes are the two mixing matrices in bf16, read once per launch. */ + for (int M : { 1, 4, 512 }) + speed("hc_read", { HI("M", M), HI("n", 2560), HI("hc", 4), HI("lowrank", 320), + HF("eps", 1e-6), HS("dtype", "bf16"), HF("wadd", 1), HI("inject", 1), + HI("group", 128), HI("rotate", 0) }, + 2.0 * 2 * 320 * 10240, 2.0 * 2 * M * 320 * 10240); + /* The DiT's feed-forward gate_up over 1024 rows, as the bf16 and the block-fp8 containers + * hold it: 61% of a block's FLOPs are in its three feed-forward products. */ + speed("gemm_nt", { HI("M", 1024), HI("N", 12288), HI("K", 4096), HS("dtype", "bf16") }, 0, + 2.0 * 1024 * 12288 * 4096); + speed("gemm_nt_q", { HI("M", 1024), HI("N", 12288), HI("K", 4096), HI("group", 128), + HS("dtype", "fp8a8") }, 0, 2.0 * 1024 * 12288 * 4096); + return c; } diff --git a/libavx/avx_check.cpp b/libavx/avx_check.cpp index f0ca0c10..5bb515e2 100644 --- a/libavx/avx_check.cpp +++ b/libavx/avx_check.cpp @@ -1,64 +1,47 @@ -/* avx_check.cpp -- rad-avx-check: libavx against libref, every op, every ISA level, no engine. +/* avx_check.cpp -- rad-avx-check: a host kernel library against libref, every op, every ISA level, + * no engine. * - * ============================== WHAT THIS IS AND WHY IT IS NOT rad-kbench ============================== + * rad-kbench needs rad_core, a Geometry, the plugin loader and sometimes a recorded fixture, i.e. + * building the engine. This is the same comparison with only two dlopen calls, a geometry table and + * libref's operand descriptions. Neither plugin is linked, so the .so under test is the one the + * engine would load. * - * rad-kbench is the tree's kernel checker and it is the right tool for a DEVICE plugin: it needs - * rad_core, a Geometry, a plugin loader and (for the fixture path) a recorded artifact. Building - * it means building the engine, which on a machine with no device toolchain means building the - * engine's host half to test a host plugin. This is the same comparison with nothing under it: two dlopen calls, a - * table of geometries, and libref's own operand descriptions to size the buffers. + * Checks, in order: * - * It links NEITHER plugin. That is not laziness -- the claim being made is about the .so the - * engine would load, and a checker that statically linked the kernels would be exercising a - * different binary with different inlining and different flags. + * 1. Schema agreement. The loader refuses a whole plugin on any schema disagreement, which would + * make every row unreachable. libavx's schema table is a hand-kept copy of libref's + * (avx_registry.cpp), checked here with the loader's rule: parameter key/type/requiredness + * and operand role/optionality, by position; names are not compared. * - * ============================== THE FOUR THINGS IT CHECKS, IN ORDER ============================== + * 2. Coverage. libavx must implement every op libref implements. An absent row and a row that + * returns RAD_E_UNSUPPORTED are reported separately and neither passes; this catches kernels + * built but never wired. * - * 1. SCHEMA AGREEMENT, before any arithmetic. The loader refuses two plugins whose schemas for - * one op disagree, and it refuses the WHOLE plugin -- so a single drifted parameter makes - * every row libavx carries unreachable, and the message an operator sees names one op and - * leaves them to find the rest. libavx's schema table is a hand-kept copy of libref's - * (avx_registry.cpp says so at length); this is what keeps the copy honest, running the - * loader's own rule: parameter key/type/requiredness positionally, operand role/optionality - * positionally, names deliberately NOT compared. + * 3. The numbers. Both plugins get byte-identical inputs and every OUT and INOUT operand is + * compared. The finiteness pattern is compared first (a NaN on one side only is a failure; + * `rel > tol` is false for NaN), and ids exactly. Every buffer carries guard bytes on both + * sides, and every input must be unchanged after the launch. A case libref cannot describe + * or run fails: the table is then wrong. Hand-built cases cover operand shapes a description + * cannot draw (avx_check_hand.cpp). * - * 2. COVERAGE. Every op libref implements, libavx must implement. A row that is ABSENT and a row - * that RETURNS RAD_E_UNSUPPORTED are reported differently and neither is reported as a pass. - * This is the check that catches a kernel that was built and never wired, because a kernel - * that declines is indistinguishable from a kernel that works to anything that only looks for - * the return codes it expects. + * 4. Threads. No check geometry reaches the kernels' parallel thresholds, so every case runs a + * second time with each parallel region forced to several threads (avx_par_force) and must + * reproduce the serial run byte for byte. * - * 3. THE NUMBERS. Both plugins are handed BYTE-IDENTICAL inputs and every OUT and INOUT operand - * is compared. The FINITENESS PATTERN is compared first and separately: a NaN on one side and - * a number on the other is a failure, not a tolerance question, and the obvious spelling - * (`rel > tol || rel < 0`) is FALSE for NaN -- which is how a NaN passes a comparison - * silently. After the geometry table, a set of HAND-BUILT cases covers the operand shapes a - * description cannot draw -- strided column slices, several sequences, rolling windows read - * past offset zero, a band above the operand's rows (see hand_cases below). + * 5. Every ISA level, each forced in turn through avx_isa_force (an exported symbol, not an env + * variable). A level the CPU cannot execute is reported as not executable and not counted. * - * 4. EVERY ISA LEVEL. The scalar, AVX, AVX2 and AVX-512 paths are four instruction streams - * compiled from one source, and only the level the machine under it happens to execute gets - * exercised by accident. Each is forced in turn through avx_isa_force -- an exported - * symbol rather than an environment variable, because an env switch that changes what a - * kernel computes is exactly what this project refuses to have. A level the CPU cannot - * execute is reported as NOT EXECUTABLE and counted nowhere: claiming a pass for a path that - * never ran is the one result worse than a failure. + * Another host library is checked the same way at the one level it selects for itself, with the + * row the selector would resolve each geometry to; the ops it does not implement are listed rather + * than failed (libavx/README.md, "Checking another host library"). */ -#include "avx_harness.h" +#include "avx_check.h" #include "avx_isa.h" -#include -#include +#include -/* ================================================================== error metric - * rad-kbench's, including the thing its header says it got wrong once: the finiteness pattern is - * compared BEFORE any norm. */ -struct Err { - double max_abs = 0, max_rel = 0, rel_l2 = 0; - int64_t nonfinite_gap = 0, n = 0; -}; - -static Err compare(const float* got, const float* ref, int64_t n) { +/* ================================================================== comparison */ +Err compare(const float* got, const float* ref, int64_t n) { Err e; e.n = n; double num = 0, den = 0; @@ -77,10 +60,67 @@ static Err compare(const float* got, const float* ref, int64_t n) { return e; } -/* rad-kbench's tolerance table, and it means the same thing here: what a DIFFERENT SUMMATION ORDER - * of the same arithmetic costs, not what a wrong kernel costs. A vectorised reduction IS that - * different order, so these are the right numbers for this comparison rather than a loosened - * version of them. A kernel with a transposed operand lands nowhere near any of these. */ +bool same_values(uint32_t dt, const void* ref, const void* got, int64_t n, double tol, + double* rel, std::string* why) { + char buf[256]; + if (dt == RAD_I32 || dt == RAD_U32 || dt == RAD_I64) { + int64_t bad = 0, first = -1; + for (int64_t i = 0; i < n; ++i) + if (avx::ld_int_dt(dt, ref, i) != avx::ld_int_dt(dt, got, i)) { + if (first < 0) first = i; + ++bad; + } + *rel = bad ? 1.0 : 0.0; + if (!bad) return true; + std::snprintf(buf, sizeof buf, "%lld of %lld ids differ, first at %lld: %lld where libref " + "has %lld", (long long)bad, (long long)n, (long long)first, + (long long)avx::ld_int_dt(dt, got, first), + (long long)avx::ld_int_dt(dt, ref, first)); + *why = buf; + return false; + } + std::vector fr((size_t)n), fa((size_t)n); + h_widen(ref, dt, n, fr.data()); + h_widen(got, dt, n, fa.data()); + const Err e = compare(fa.data(), fr.data(), n); + *rel = e.rel_l2; + if (e.nonfinite_gap == 0 && e.rel_l2 <= tol) return true; + std::snprintf(buf, sizeof buf, "rel_l2=%.3e max_abs=%.3e nonfinite_gap=%lld tol=%.1e", + e.rel_l2, e.max_abs, (long long)e.nonfinite_gap, tol); + *why = buf; + return false; +} + +bool parallel_rerun(const Lib& lib, int threads, const std::vector& outs, + const std::vector& bytes, const std::function& reset, + const std::function& launch, std::string* why) { + std::vector> serial(outs.size()); + for (size_t i = 0; i < outs.size(); ++i) serial[i].assign(outs[i], outs[i] + bytes[i]); + reset(); + lib.par_force(threads); + const int rc = launch(); + lib.par_force(0); + char buf[160]; + if (rc < 0) { + std::snprintf(buf, sizeof buf, "on %d threads it returned %d", threads, rc); + *why = buf; + return false; + } + for (size_t i = 0; i < outs.size(); ++i) { + if (std::memcmp(outs[i], serial[i].data(), bytes[i]) == 0) continue; + size_t at = 0; + while (at < bytes[i] && outs[i][at] == serial[i][at]) ++at; + std::snprintf(buf, sizeof buf, "on %d threads output buffer %zu differs from the serial " + "run from byte %zu of %zu", threads, i, at, bytes[i]); + *why = buf; + return false; + } + return true; +} + +/* rad-kbench's tolerance table: rel_l2 bounds for the same arithmetic in a different summation + * order, which is what a vectorised reduction is. A wrong kernel (e.g. a transposed operand) lands + * far outside these. First match wins. */ struct Tol { const char* op; const char* dtype; double rel_l2; }; static const Tol kTol[] = { { "gemm_nt", "bf16", 8e-3 }, @@ -89,6 +129,9 @@ static const Tol kTol[] = { { "gemm_nt", "*", 3e-2 }, { "logits_gemm", "bf16", 8e-3 }, { "logits_gemm", "f32", 2e-5 }, + /* The plain grouped GEMM is gemm_nt's arithmetic per expert, held to its bounds. */ + { "moe_gemm", "f32", 2e-5 }, + { "moe_gemm", "bf16", 8e-3 }, { "moe_gemm", "*", 3e-2 }, { "attn_", "bf16", 2e-2 }, { "attn_", "f32", 1e-4 }, @@ -100,6 +143,8 @@ static const Tol kTol[] = { { "quant_act", "*", 1e-6 }, { "dequant", "*", 1e-6 }, { "cast", "*", 1e-6 }, + /* An fp8 cache stores x / scale narrowed once; both libraries narrow the same quotient. */ + { "kv_store", "fp8_e4m3", 1e-6 }, { "all_reduce", "f32", 1e-6 }, { "all_reduce", "*", 4e-3 }, { "all_gather", "*", 0.0 }, @@ -121,119 +166,348 @@ static double tolerance_for(const std::string& op, const char* dtype) { struct Stats { int checked = 0, passed = 0, failed = 0, skipped = 0, declined = 0, missing = 0; + int unselected = 0, rerun = 0; double worst = 0; std::string worst_where; }; -static void run_case(const Lib& ref, const Lib& avx, const Case& c, bool verbose, - double tol_override, Stats* st) { - const RadKernelInfo* kr = ref.row(c.op); - const RadKernelInfo* ka = avx.row(c.op); - if (!kr) { ++st->skipped; return; } - if (!ka) { ++st->missing; return; } +/* After a launch on one side: both guards of every operand and of the scratch intact, and every + * input operand as drawn. Prints each violation and returns false. */ +static bool intact(const Prepared& pr, bool side_a, const char* who, const Case& c) { + bool ok = true; + auto name = [&](size_t i) { + return pr.schema->operands[i].name ? pr.schema->operands[i].name : "?"; + }; + for (size_t i = 0; i < pr.opd.size(); ++i) { + const Opd& o = pr.opd[i]; + if (o.absent) continue; + const GBuf& g = side_a ? o.a : o.b; + if (const int hit = g.guard_hit()) { + std::printf(" FAIL %-20s %s\n %s wrote %s operand %d (%s)\n", c.op, + case_str(c).c_str(), who, hit < 0 ? "before the start of" : "past the end of", + (int)i, name(i)); + ok = false; + } + const bool input = o.role == RAD_OPD_IN || o.role == RAD_OPD_WEIGHT || + o.role == RAD_OPD_WTAB; + if (input && g.size() && std::memcmp(g.data(), o.master.data(), g.size()) != 0) { + std::printf(" FAIL %-20s %s\n %s changed its input operand %d (%s)\n", c.op, + case_str(c).c_str(), who, (int)i, name(i)); + ok = false; + } + } + if ((side_a ? pr.sa : pr.sb).guard_hit()) { + std::printf(" FAIL %-20s %s\n %s wrote outside its scratch\n", c.op, + case_str(c).c_str(), who); + ok = false; + } + return ok; +} - /* Side A is libref, side B is libavx. The description comes from the ORACLE: the two have to - * be handed the same bytes for the comparison to mean anything, and where they could disagree - * about an extent the reference semantics are the ones that define the op. */ - /* A SKIP IS REPORTED WITH ITS REASON, and that is not a nicety. A silent skip is how a checker - * reports coverage it does not have, and the two reasons here mean completely - * different things. "the oracle cannot describe this geometry" is a limit of libref's shape - * hook and the case should be rewritten or dropped; "the oracle declined the launch" means the - * case is asking for something the op does not define. Either way it is the CASE TABLE that is - * wrong, and a count with no name does not say which line. */ - Prepared pr = h_prepare(ref, kr, c, kr, ka); - if (pr.skipped || !pr.ok) { +static void run_case(const Check& ck, const Case& c, Stats* st) { + const Lib& ref = *ck.ref; + const Lib& lib = *ck.lib; + const char* who = lib.info->name; + auto skip = [&](const char* why) { ++st->skipped; - if (verbose) - std::printf(" %-22s %-46s SKIP: libref's opd_shape declines this geometry\n", - c.op, case_str(c).c_str()); + std::printf(" SKIP %-20s %s\n %s\n", c.op, case_str(c).c_str(), why); + }; + const RadKernelInfo* kr = ref.row(c.op); + if (!kr) { skip("libref has no row for the op"); return; } + std::vector params; + for (const P& p : c.p) params.push_back(h_mk(p)); + const RadKernelInfo* ka = lib.select(c.op, params.data(), (int)params.size()); + if (!ka) { + if (lib.host_row(c.op)) { + ++st->unselected; + if (ck.verbose) + std::printf(" %-22s %-46s no row's constraints admit it\n", c.op, + case_str(c).c_str()); + } else { + ++st->missing; + } return; } + /* Side A is libref, side B the library under test; operands are sized by the oracle's + * description. A case libref cannot describe or run fails as a skip: the table is wrong. */ + Prepared pr = h_prepare(ref, kr, c, kr, ka); + if (pr.skipped || !pr.ok) { skip("libref's opd_shape declines this geometry"); return; } + const int rr = kr->launch(&pr.aa, nullptr); const int ra = ka->launch(&pr.ab, nullptr); - /* THE ORACLE IS ASKED FIRST, and getting this order wrong cost a false report. If libref - * declines the geometry there is nothing to compare against, so the case is SKIPPED -- even - * when libavx declined it too, which is the correct and identical behaviour rather than a gap. - * Reporting libavx's decline before looking at the oracle's blamed the plugin for a case the - * op does not define (it was a case table asking for an `a_order` spelling neither - * implementation accepts). A DECLINE only means something when the oracle produced an answer. */ + /* Check the oracle first: if libref declines, there is nothing to compare, even if the library + * declined too. A decline only counts when libref answered. */ if (rr < 0) { - ++st->skipped; - if (verbose) - std::printf(" %-22s %-46s SKIP: libref's launch returned %d\n", c.op, - case_str(c).c_str(), rr); + char why[64]; + std::snprintf(why, sizeof why, "libref's launch returned %d", rr); + skip(why); return; } if (ra == RAD_E_UNSUPPORTED) { ++st->declined; - if (verbose) std::printf(" %-22s %-46s DECLINED\n", c.op, case_str(c).c_str()); + std::printf(" %-22s %-46s DECLINED\n", c.op, case_str(c).c_str()); return; } + ++st->checked; if (ra < 0) { - std::printf(" FAIL %-20s %s\n libavx returned %d where libref returned %d\n", - c.op, case_str(c).c_str(), ra, rr); + std::printf(" FAIL %-20s %s\n %s returned %d where libref returned %d\n", c.op, + case_str(c).c_str(), who, ra, rr); ++st->failed; - ++st->checked; return; } - bool ok = true; + bool ok = intact(pr, true, "libref", c); + ok = intact(pr, false, who, c) && ok; double worst = 0; - const double tol = tol_override >= 0 ? tol_override : tolerance_for(c.op, case_dtype(c)); + const double tol = ck.tol_override >= 0 ? ck.tol_override : tolerance_for(c.op, case_dtype(c)); for (size_t i = 0; i < pr.opd.size(); ++i) { const Opd& o = pr.opd[i]; if (o.absent || o.n <= 0) continue; if (o.role != RAD_OPD_OUT && o.role != RAD_OPD_INOUT) continue; - std::vector fr((size_t)o.n), fa((size_t)o.n); - h_widen(o.a.data(), o.d.dtype, o.n, fr.data()); - h_widen(o.b.data(), o.d.dtype, o.n, fa.data()); - const Err e = compare(fa.data(), fr.data(), o.n); - worst = std::max(worst, e.rel_l2); - if (e.nonfinite_gap != 0 || !(e.rel_l2 <= tol)) { + double rel = 0; + std::string why; + if (!same_values(o.d.dtype, o.a.data(), o.b.data(), o.n, tol, &rel, &why)) { ok = false; - std::printf(" FAIL %-20s %s\n operand %d (%s) rel_l2=%.3e max_abs=%.3e " - "nonfinite_gap=%lld tol=%.1e\n", - c.op, case_str(c).c_str(), (int)i, - pr.schema->operands[i].name ? pr.schema->operands[i].name : "?", - e.rel_l2, e.max_abs, (long long)e.nonfinite_gap, tol); + std::printf(" FAIL %-20s %s\n operand %d (%s): %s\n", c.op, case_str(c).c_str(), + (int)i, pr.schema->operands[i].name ? pr.schema->operands[i].name : "?", + why.c_str()); } + worst = std::max(worst, rel); } - ++st->checked; + /* A launch that left every output's values as drawn compares the draw with itself: the case + * proves nothing about the arithmetic (all-zero weights, or a stage its parameters switch + * off). -0 counts as 0, so a product of zeros does not pass for work. */ + bool wrote = false; + for (const Opd& o : pr.opd) { + if (o.absent || o.n <= 0 || (o.role != RAD_OPD_OUT && o.role != RAD_OPD_INOUT)) continue; + std::vector now((size_t)o.n), was((size_t)o.n); + h_widen(o.a.data(), o.d.dtype, o.n, now.data()); + h_widen(o.master.data(), o.d.dtype, o.n, was.data()); + for (int64_t i = 0; i < o.n && !wrote; ++i) + wrote = !(now[(size_t)i] == was[(size_t)i]); + } + if (!wrote) { + ok = false; + std::printf(" FAIL %-20s %s\n libref's launch changed no output byte, so the " + "comparison is vacuous\n", c.op, case_str(c).c_str()); + } + + /* The same launch with every parallel region on several threads, against the serial bytes. */ + if (ok && ck.threads > 0 && lib.par_force) { + std::vector outs; + std::vector bytes; + for (Opd& o : pr.opd) + if (!o.absent && o.n > 0 && (o.role == RAD_OPD_OUT || o.role == RAD_OPD_INOUT)) { + outs.push_back(o.b.data()); + bytes.push_back(o.b.size()); + } + auto reset = [&] { + for (Opd& o : pr.opd) + if (!o.absent && o.n > 0 && (o.role == RAD_OPD_OUT || o.role == RAD_OPD_INOUT)) + std::memcpy(o.b.data(), o.master.data(), o.master.size()); + if (!pr.sb.empty()) std::memset(pr.sb.data(), 0, pr.sb.size()); + }; + std::string why; + if (!parallel_rerun(lib, ck.threads, outs, bytes, reset, + [&] { return ka->launch(&pr.ab, nullptr); }, &why)) { + ok = false; + std::printf(" FAIL %-20s %s\n %s\n", c.op, case_str(c).c_str(), why.c_str()); + } + ok = intact(pr, false, who, c) && ok; + ++st->rerun; + } + if (ok) ++st->passed; else ++st->failed; if (worst > st->worst) { st->worst = worst; st->worst_where = std::string(c.op) + " " + case_str(c); } - if (verbose) + if (ck.verbose) std::printf(" %-22s %-46s rel_l2=%.3e tol=%.1e %s\n", c.op, case_str(c).c_str(), worst, tol, ok ? "ok" : "FAIL"); } +/* ================================================================== zero rows + * + * docs/OPS.md: an op issued over zero rows returns RAD_E_SHAPE and writes nothing. Each op's first + * case is described at its row count and at twice it; every extent that changes is a row extent + * and is set to zero, and both plugins are launched with the row parameter at 0 (a cumulative + * length draws as all zeros, every sequence empty). libref answering anything else means the + * construction does not fit the op, which is reported and not counted. */ +static bool zero_row_cases(const Check& ck, const std::vector& cases) { + const Lib& ref = *ck.ref; + const Lib& lib = *ck.lib; + std::vector seen; + int checked = 0, failed = 0, unfit = 0; + for (const Case& c : cases) { + if (c.speed_only || (!ck.only_op.empty() && ck.only_op != c.op)) continue; + if (std::find(seen.begin(), seen.end(), c.op) != seen.end()) continue; + seen.push_back(c.op); + const char* key = nullptr; + for (const char* k : { "M", "q_len", "numel" }) + for (const P& p : c.p) + if (!key && p.kind == RAD_P_INT && !std::strcmp(p.k, k)) key = k; + const RadKernelInfo* kr = ref.row(c.op); + if (!key || !kr || !kr->opd_shape) continue; + auto with = [&](long long r) { + std::vector v; + for (const P& p : c.p) { + v.push_back(h_mk(p)); + if (!std::strcmp(p.k, key)) v.back().ival = r == 2 ? 2 * p.i : 0; + } + return v; + }; + long long r1 = 0; + for (const P& p : c.p) if (!std::strcmp(p.k, key)) r1 = p.i; + std::vector p1, p2 = with(2), p0 = with(0); + for (const P& p : c.p) p1.push_back(h_mk(p)); + const RadKernelInfo* ka = lib.select(c.op, p0.data(), (int)p0.size()); + const RadOpSchema* sch = ref.schema(c.op); + if (!ka || !sch || r1 <= 0) continue; + + Prepared pr; + pr.schema = sch; + pr.opd.assign((size_t)sch->n_operands, Opd{}); + bool described = true; + for (int i = 0; i < sch->n_operands && described; ++i) { + RadOpdDesc d1{}, d2{}; + d1.idx_const = d2.idx_const = -1; + described = kr->opd_shape(p1.data(), (int)p1.size(), i, &d1) >= 0 && + kr->opd_shape(p2.data(), (int)p2.size(), i, &d2) >= 0; + Opd& o = pr.opd[(size_t)i]; + o.d = d1; + for (uint32_t k = 0; k < d1.rank; ++k) + if (d1.shape[k] != d2.shape[k]) o.d.shape[k] = 0; + o.absent = (d1.flags & RAD_OPD_F_ABSENT) != 0; + o.role = sch->operands[i].role; + o.n = o.absent ? 0 : desc_numel(o.d); + } + if (!described) continue; + for (size_t k = 0; k < pr.opd.size(); ++k) h_draw(pr.opd, k, 0, 0x2e70u + k); + for (Opd& o : pr.opd) { + o.a.assign(o.master); + o.b.assign(o.master); + } + pr.params = p0; + h_build_tensors(pr.opd, true, &pr.ta); + h_build_tensors(pr.opd, false, &pr.tb); + pr.aa.t = pr.ta.data(); pr.aa.n_t = (int)pr.ta.size(); + pr.aa.p = pr.params.data(); pr.aa.n_p = (int)pr.params.size(); + pr.aa.world_size = 1; + pr.ab = pr.aa; + pr.ab.t = pr.tb.data(); + + const int rr = kr->launch(&pr.aa, nullptr); + if (rr != RAD_E_SHAPE) { + ++unfit; + if (ck.verbose) + std::printf(" %-22s zero rows: libref returned %d; not counted\n", c.op, rr); + continue; + } + const int ra = ka->launch(&pr.ab, nullptr); + bool untouched = true; + for (const Opd& o : pr.opd) + untouched = untouched && o.b.guard_hit() == 0 && + std::memcmp(o.b.data(), o.master.data(), o.master.size()) == 0; + ++checked; + if (ra != RAD_E_SHAPE || !untouched) { + ++failed; + std::printf(" FAIL %-20s zero rows (%s = 0)\n %s returned %d%s; libref " + "refuses with RAD_E_SHAPE and writes nothing\n", c.op, key, + lib.info->name, ra, untouched ? "" : " and wrote"); + } else if (ck.verbose) { + std::printf(" %-22s zero rows refused, nothing written\n", c.op); + } + } + if (checked || unfit) + std::printf(" zero rows: %d ops checked, %d failed%s\n", checked, failed, + unfit ? (", " + std::to_string(unfit) + " not reducible to zero rows").c_str() + : ""); + return failed == 0; +} + /* ================================================================== exhaustive conversion * - * THE ONE CHECK A DRAW CANNOT MAKE. Every geometry in the case table fills its operands with - * standard normals, which is the right domain for an activation and reaches almost none of the - * interesting bit patterns of a narrow float: no NaN, no infinity, no subnormal, no negative zero. - * A conversion is exactly where those live -- `cvt_fp8e4m3_to_f32` has a separate branch for the - * subnormal range and another for the format's single NaN encoding, and a draw of normals exercises - * neither. - * - * So the 8-bit and 16-bit formats are checked EXHAUSTIVELY: every one of the 256 or 65536 bit - * patterns, through the plugin's own `cast`, against libref's. For an 8-bit source that is the - * complete input space and the result is a proof rather than evidence; for a 16-bit one it is the - * complete space too. The narrowing direction (f32 -> narrow) cannot be exhaustive over 2^32, so it - * is fed the widened patterns back plus the boundary values of each format -- which is where a - * narrowing rounds differently if it is going to. - * - * It is worth the forty lines because this is the class of bug that survives everything else: the - * fp8 encode's lower bound was wrong by seven octaves and every geometry in the table still passed - * until `cast` was run at a tolerance of 1e-6. */ -static bool exhaustive_cast(const Lib& ref, const Lib& avx, bool verbose) { + * Drawn normals reach almost none of a narrow float's special patterns (NaN, infinity, + * subnormals, negative zero), yet conversions branch on exactly those (e.g. cvt_fp8e4m3_to_f32's + * subnormal and NaN handling). So every bit pattern of each 8- and 16-bit format is widened to f32 + * through both plugins' `cast` and compared bit for bit, NaNs as NaNs. The narrowing direction + * cannot cover 2^32 inputs. It is fed every representable value (the widened patterns), then + * every midpoint between two adjacent values with 1 and 2 f32 ulps to either side, where + * round-to-nearest-even decides and a rounding error lands, then the overflow edges and every + * class of NaN. */ +static bool exhaustive_cast(const Check& ck) { + const Lib& ref = *ck.ref; + const Lib& lib = *ck.lib; const RadKernelInfo* kr = ref.row("cast"); - const RadKernelInfo* ka = avx.row("cast"); - if (!kr || !ka) return true; + if (!kr || !lib.host_row("cast")) { + std::printf("EXACT cast: no row in %s\n", kr ? lib.info->name : "libref"); + return kr && !ck.own; + } + + /* One cast of `n` elements through both plugins; the outputs compared byte for byte, element + * by element. Returns false having printed the first difference. */ + auto both = [&](const char* label, uint32_t from, const char* fname, uint32_t to, + const char* tname, const void* src, int64_t n, std::vector* out_a) { + const size_t ob = dt_bytes(to, n), eb = (size_t)rad_dtype_bits(to) / 8; + std::vector ya(ob, 0), yb(ob, 0); + RadParam p[4]; + p[0] = RadParam{ "M", RAD_P_INT, 1, 0, nullptr, 0 }; + p[1] = RadParam{ "n", RAD_P_INT, (long long)n, 0, nullptr, 0 }; + p[2] = RadParam{ "from", RAD_P_STR, 0, 0, fname, 0 }; + p[3] = RadParam{ "to", RAD_P_STR, 0, 0, tname, 0 }; + const RadKernelInfo* kb = lib.select("cast", p, 4); + if (!kb) { + std::printf("EXACT cast %-16s %-10s no row of %s admits it\n", label, fname, + lib.info->name); + return !ck.own; + } + auto mk_t = [&](const void* data, uint32_t dt) { + RadTensor t{}; + t.data = const_cast(data); t.dtype = dt; t.rank = 2; + t.shape[0] = 1; t.shape[1] = n; + t.stride[0] = n; t.stride[1] = 1; + return t; + }; + RadTensor ta[2] = { mk_t(src, from), mk_t(ya.data(), to) }; + RadTensor tb[2] = { mk_t(src, from), mk_t(yb.data(), to) }; + RadArgs aa{}, ab{}; + aa.t = ta; aa.n_t = 2; aa.p = p; aa.n_p = 4; aa.world_size = 1; + ab = aa; ab.t = tb; + const int rr = kr->launch(&aa, nullptr), ra = kb->launch(&ab, nullptr); + if (rr < 0 || ra < 0) { + std::printf("EXACT cast %-16s refused: libref %d, %s %d\n", label, rr, + lib.info->name, ra); + return false; + } + /* Widened NaNs need only be NaNs: F16C quiets a signalling one, libref keeps it. */ + int64_t bad = 0, first = -1; + for (int64_t i = 0; i < n; ++i) { + if (std::memcmp(ya.data() + i * eb, yb.data() + i * eb, eb) == 0) continue; + if (to == RAD_F32 && std::isnan(((const float*)ya.data())[i]) && + std::isnan(((const float*)yb.data())[i])) + continue; + if (first < 0) first = i; + ++bad; + } + if (out_a) *out_a = ya; + if (!bad) { + if (ck.verbose) + std::printf(" cast %-16s all %lld inputs identical\n", label, (long long)n); + return true; + } + uint32_t in_bits = 0, got = 0, want = 0; + std::memcpy(&in_bits, (const uint8_t*)src + first * (rad_dtype_bits(from) / 8), + (size_t)rad_dtype_bits(from) / 8); + std::memcpy(&want, ya.data() + first * eb, eb); + std::memcpy(&got, yb.data() + first * eb, eb); + std::printf("EXACT cast %-16s %lld of %lld inputs differ, first input 0x%x: libref " + "0x%x, %s 0x%x\n", label, (long long)bad, (long long)n, in_bits, want, + lib.info->name, got); + return false; + }; struct Fmt { const char* name; uint32_t dt; int bits; }; static const Fmt kFmt[] = { @@ -247,592 +521,59 @@ static bool exhaustive_cast(const Lib& ref, const Lib& avx, bool verbose) { std::vector src((size_t)((n * f.bits) / 8)); if (f.bits == 8) for (int64_t i = 0; i < n; ++i) src[(size_t)i] = (uint8_t)i; else for (int64_t i = 0; i < n; ++i) ((uint16_t*)src.data())[i] = (uint16_t)i; + const std::string wide = std::string(f.name) + " -> f32"; + const std::string narrow = std::string("f32 -> ") + f.name; - /* ---- widening: every pattern of the narrow format into f32. */ - std::vector ya((size_t)n, 0), yb((size_t)n, 0); - for (int pass = 0; pass < 2; ++pass) { - const bool narrowing = pass == 1; - /* ---- narrowing: the widened values back down, which covers every value the format can - * represent plus, through the round trip, the ties at each of its steps. */ - std::vector na((size_t)((n * f.bits) / 8), 0); - std::vector nb((size_t)((n * f.bits) / 8), 0); + /* Every pattern widened; then every value narrowed back. */ + std::vector wbytes; + if (!both(wide.c_str(), f.dt, f.name, RAD_F32, "f32", src.data(), n, &wbytes)) { + ok = false; + continue; + } + std::vector vals((size_t)n); + std::memcpy(vals.data(), wbytes.data(), (size_t)n * sizeof(float)); + if (!both(narrow.c_str(), RAD_F32, "f32", f.dt, f.name, vals.data(), n, nullptr)) + ok = false; - RadParam p[4]; - p[0] = RadParam{ "M", RAD_P_INT, 1, 0, nullptr, 0 }; - p[1] = RadParam{ "n", RAD_P_INT, (long long)n, 0, nullptr, 0 }; - p[2] = RadParam{ "from", RAD_P_STR, 0, 0, narrowing ? "f32" : f.name, 0 }; - p[3] = RadParam{ "to", RAD_P_STR, 0, 0, narrowing ? f.name : "f32", 0 }; - - auto mk_t = [&](void* data, uint32_t dt) { - RadTensor t{}; - t.data = data; t.dtype = dt; t.rank = 2; - t.shape[0] = 1; t.shape[1] = n; - t.stride[0] = n; t.stride[1] = 1; - return t; - }; - RadTensor ta[2], tb[2]; - if (!narrowing) { - ta[0] = mk_t(src.data(), f.dt); ta[1] = mk_t(ya.data(), RAD_F32); - tb[0] = mk_t(src.data(), f.dt); tb[1] = mk_t(yb.data(), RAD_F32); - } else { - ta[0] = mk_t(ya.data(), RAD_F32); ta[1] = mk_t(na.data(), f.dt); - tb[0] = mk_t(ya.data(), RAD_F32); tb[1] = mk_t(nb.data(), f.dt); - } - RadArgs aa{}, ab{}; - aa.t = ta; aa.n_t = 2; aa.p = p; aa.n_p = 4; aa.world_size = 1; - ab = aa; ab.t = tb; - if (kr->launch(&aa, nullptr) < 0 || ka->launch(&ab, nullptr) < 0) continue; - - int64_t bad = 0; - int64_t first = -1; - if (!narrowing) { - for (int64_t i = 0; i < n; ++i) { - const bool na_ = std::isnan(ya[(size_t)i]), nb_ = std::isnan(yb[(size_t)i]); - if (na_ != nb_ || (!na_ && ya[(size_t)i] != yb[(size_t)i])) { - if (first < 0) first = i; - ++bad; - } - } - } else { - for (size_t i = 0; i < na.size(); ++i) - if (na[i] != nb[i]) { if (first < 0) first = (int64_t)i; ++bad; } - } - if (bad) { - ok = false; - std::printf("EXACT cast %-10s %-10s %lld of %lld patterns differ, first at %lld\n", - narrowing ? "f32 ->" : "-> f32", f.name, (long long)bad, - (long long)n, (long long)first); - } else if (verbose) { - std::printf(" cast %-6s %-9s all %lld bit patterns identical\n", - narrowing ? "f32 ->" : "-> f32", f.name, (long long)n); + /* The midpoints, their neighbours, the overflow edges and the NaNs. */ + std::vector fin; + for (float v : vals) if (std::isfinite(v)) fin.push_back(v); + std::sort(fin.begin(), fin.end()); + fin.erase(std::unique(fin.begin(), fin.end()), fin.end()); + std::vector in; + for (size_t i = 0; i + 1 < fin.size(); ++i) { + const float m = (float)(((double)fin[i] + (double)fin[i + 1]) / 2.0); + float lo = m, hi = m; + in.push_back(m); + for (int u = 0; u < 2; ++u) { + lo = std::nextafter(lo, -INFINITY); + hi = std::nextafter(hi, INFINITY); + in.push_back(lo); + in.push_back(hi); } } - } - return ok; -} - -/* ================================================================== operands no description draws - * - * libref's opd_shape describes every op the one way a cold harness can use it: one sequence where - * the op allows it, every operand dense at its declared rank, integer operands at their plainest - * value. The engine hands kernels more than that, and each case below is one of those shapes, with - * its operands built by hand: - * - * several sequences through a path chosen for uniform queries; - * a rank-2 COLUMN SLICE of a fused projection, whose row stride is the projection's width; - * a speculative step whose `num_accepted` reads a rolling window past offset zero; - * a ranged parameter at its band's upper bound over an operand of fewer rows; - * head widths that do not divide a kernel's channel panel; - * packed weight codes at odd element offsets, which fall off the row converter; - * integer stores of values past the target's range, and exponents of -inf and NaN. - * - * Both plugins get byte-identical copies, and every OUT or INOUT buffer is compared WHOLE -- not - * just the view the op was handed -- so a write outside the view is a difference too. */ -struct Hand { - struct Buf { - uint32_t dt = RAD_F32; - int64_t elems = 0; - std::vector a, b; - bool out = false; - }; - std::string name, op; - std::deque bufs; - std::vector buf_of; /* per operand, the backing buffer or -1 */ - std::vector ta, tb; - std::vector p; - std::deque strs; - double tol = 1e-5; - - Hand(const char* n, const char* o, double t) : name(n), op(o), tol(t) {} - - /* An operand over a fresh buffer of `span` elements, viewed with `shape` and `stride`. The - * whole buffer is filled -- the bytes outside the view are another projection's columns, and - * a kernel that reads them must read the same thing on both sides. */ - Hand& view(uint32_t dt, std::vector shape, std::vector stride, int64_t span, - const std::function& fill, bool out = false) { - Buf bf; - bf.dt = dt; bf.elems = span; bf.out = out; - std::vector v((size_t)span); - for (int64_t i = 0; i < span; ++i) v[(size_t)i] = fill(i); - bf.a.assign(dt_bytes(dt, span) + 8, 0); - h_narrow(v.data(), dt, span, bf.a.data()); - bf.b = bf.a; - bufs.push_back(std::move(bf)); - RadTensor t{}; - t.dtype = dt; - t.rank = (uint32_t)shape.size(); - for (size_t i = 0; i < shape.size(); ++i) { - t.shape[i] = shape[i]; - t.stride[i] = stride[i]; + static const float kEdges[] = { 127.5f, 128.0f, 300.0f, 448.0f, 464.0f, 480.0f, 57344.0f, + 61440.0f, 65504.0f, 65520.0f, 1e10f, 3.4028235e38f, + INFINITY }; + for (float e : kEdges) { in.push_back(e); in.push_back(-e); } + static const uint32_t kNaN[] = { 0x7fc00000u, 0xffc00000u, 0x7fffffffu, 0xffffffffu, + 0x7ff00000u, 0x7f800001u, 0xff800001u, 0x7fc00001u }; + for (uint32_t b : kNaN) { + float v; + std::memcpy(&v, &b, 4); + in.push_back(v); } - ta.push_back(t); tb.push_back(t); - buf_of.push_back((int)bufs.size() - 1); - return *this; + const std::string mid = narrow + " mid"; + if (!both(mid.c_str(), RAD_F32, "f32", f.dt, f.name, in.data(), (int64_t)in.size(), + nullptr)) + ok = false; } - /* A dense operand of `shape`. */ - Hand& dense(uint32_t dt, std::vector shape, const std::function& fill, - bool out = false) { - std::vector st(shape.size()); - int64_t acc = 1; - for (int i = (int)shape.size() - 1; i >= 0; --i) { - st[(size_t)i] = acc; - acc *= shape[(size_t)i]; - } - return view(dt, shape, st, acc, fill, out); - } - Hand& idx(std::vector v, bool out = false) { - return dense(RAD_I32, { (int64_t)v.size() }, [v](int64_t i) { return (float)v[(size_t)i]; }, - out); - } - Hand& none() { - ta.push_back(RadTensor{}); - tb.push_back(RadTensor{}); - buf_of.push_back(-1); - return *this; - } - Hand& pi(const char* k, long long v) { - p.push_back(RadParam{ k, RAD_P_INT, v, 0, nullptr, 0 }); - return *this; - } - Hand& pf(const char* k, double v) { - p.push_back(RadParam{ k, RAD_P_F64, 0, 0, nullptr, v }); - return *this; - } - Hand& ps(const char* k, const char* v) { - strs.emplace_back(v); - p.push_back(RadParam{ k, RAD_P_STR, 0, 0, strs.back().c_str(), 0 }); - return *this; - } - - /* Returns false on a failure, having printed it. */ - bool run(const Lib& ref, const Lib& avx, bool verbose) { - const RadKernelInfo* kr = ref.row(op.c_str()); - const RadKernelInfo* ka = avx.row(op.c_str()); - if (!kr || !ka) { - std::printf(" FAIL %-20s %s\n no row for the op in %s\n", op.c_str(), - name.c_str(), kr ? "libavx" : "libref"); - return false; - } - for (size_t i = 0; i < ta.size(); ++i) { - if (buf_of[i] < 0) continue; - ta[i].data = bufs[(size_t)buf_of[i]].a.data(); - tb[i].data = bufs[(size_t)buf_of[i]].b.data(); - } - RadArgs aa{}, ab{}; - aa.t = ta.data(); aa.n_t = (int)ta.size(); - aa.p = p.data(); aa.n_p = (int)p.size(); - aa.world_size = 1; - ab = aa; ab.t = tb.data(); - const int rr = kr->launch(&aa, nullptr); - const int ra = ka->launch(&ab, nullptr); - if (rr < 0) { - std::printf(" FAIL %-20s %s\n libref refused the case (%d); the case is wrong\n", - op.c_str(), name.c_str(), rr); - return false; - } - if (ra < 0) { - std::printf(" FAIL %-20s %s\n libavx returned %d where libref returned %d\n", - op.c_str(), name.c_str(), ra, rr); - return false; - } - bool ok = true; - double worst = 0; - for (const Buf& bf : bufs) { - if (!bf.out) continue; - std::vector fr((size_t)bf.elems), fa((size_t)bf.elems); - h_widen(bf.a.data(), bf.dt, bf.elems, fr.data()); - h_widen(bf.b.data(), bf.dt, bf.elems, fa.data()); - const Err e = compare(fa.data(), fr.data(), bf.elems); - worst = std::max(worst, e.rel_l2); - if (e.nonfinite_gap != 0 || !(e.rel_l2 <= tol)) { - ok = false; - std::printf(" FAIL %-20s %s\n rel_l2=%.3e max_abs=%.3e nonfinite_gap=%lld " - "tol=%.1e\n", op.c_str(), name.c_str(), e.rel_l2, e.max_abs, - (long long)e.nonfinite_gap, tol); - } - } - if (verbose) - std::printf(" %-22s %-46s rel_l2=%.3e tol=%.1e %s\n", op.c_str(), name.c_str(), worst, - tol, ok ? "ok" : "FAIL"); - return ok; - } -}; - -/* A deterministic fill that is not a constant: the value of element i under seed s. */ -static std::function hfill(uint64_t s, float sigma = 1.0f) { - return [s, sigma](int64_t i) { - uint64_t x = s * 0x9E3779B97F4A7C15ull + (uint64_t)i; - x ^= x >> 31; x *= 0xBF58476D1CE4E5B9ull; x ^= x >> 29; - return ((float)(x % 2001) / 1000.0f - 1.0f) * sigma; - }; -} - -static bool hand_cases(const Lib& ref, const Lib& avx, bool verbose, int* n_checked) { - std::vector hs; - - /* ---- attention: two sequences through the uniform long-query form, no cu_seqlens ------- */ - { - const int64_t S = 2, QL = 32, KVH = 1, G = 2, HD = 16, BS = 16, NB = 6; - Hand h("n_seq=2 q_len=32 no cu_seqlens", "attn_paged", 1e-4); - h.dense(RAD_F32, { S * QL, KVH * G, HD }, hfill(1)) - .dense(RAD_F32, { NB, KVH, BS, 2 * HD }, hfill(2)) - .dense(RAD_I32, { S, 3 }, [](int64_t i) { return (float)((i * 5) % 6); }) - .idx({ 40, 36 }) - .none().none().none() - .dense(RAD_F32, { S * QL, KVH * G, HD }, hfill(3), true) - .pi("q_len", QL).pi("head_dim", HD).pi("gqa", G).pi("block_size", BS).pi("causal", 1) - .pi("window", 0).ps("q_dtype", "f32").ps("kv_dtype", "f32"); - hs.push_back(std::move(h)); - } - /* ---- attention and the KV write over column slices of a fused [q|k|v] projection ------- */ - { - const int64_t T = 5, NH = 2, KVH = 1, HD = 16, W = (NH + 2 * KVH) * HD, BS = 4, NB = 4; - Hand h("k, v are rank-2 column slices, row stride 64", "kv_store", 1e-6); - h.view(RAD_F32, { T, KVH * HD }, { W, 1 }, T * W, hfill(4)) /* k at column 0 */ - .view(RAD_F32, { T, KVH * HD }, { W, 1 }, T * W, hfill(5)) - .idx({ 3, 0, 9, 14, 6 }) - .dense(RAD_F32, { NB, KVH, BS, 2 * HD }, hfill(6), true) - .pi("M", T).pi("head_dim", HD).pi("n_head_kv", KVH).pi("block_size", BS) - .ps("kv_dtype", "f32"); - hs.push_back(std::move(h)); - - Hand g("q and out are rank-2 column slices", "attn_paged", 1e-4); - g.view(RAD_F32, { T, NH * HD }, { W, 1 }, T * W, hfill(7)) - .dense(RAD_F32, { NB, KVH, BS, 2 * HD }, hfill(8)) - .dense(RAD_I32, { T, 2 }, [](int64_t i) { return (float)(i % NB); }) - .idx({ 3, 5, 7, 2, 8 }) - .none().none().none() - .view(RAD_F32, { T, NH * HD }, { W, 1 }, T * W, hfill(9), true) - .pi("q_len", 1).pi("head_dim", HD).pi("gqa", NH / KVH).pi("block_size", BS) - .pi("causal", 1).pi("window", 0).ps("q_dtype", "f32").ps("kv_dtype", "f32"); - hs.push_back(std::move(g)); - - Hand d("q, k, v, out are rank-2 column slices", "attn_dense", 1e-4); - d.view(RAD_F32, { T, HD }, { W, 1 }, T * W, hfill(10)) - .view(RAD_F32, { T, HD }, { W, 1 }, T * W, hfill(11)) - .view(RAD_F32, { T, HD }, { W, 1 }, T * W, hfill(12)) - .idx({ 0, 2, 5 }) - .view(RAD_F32, { T, HD }, { W, 1 }, T * W, hfill(13), true) - .pi("M", T).pi("head_dim", HD).pi("gqa", 1).pi("causal", 1).ps("dtype", "f32"); - hs.push_back(std::move(d)); - } - /* ---- the GDN decode convolution read past offset zero ---------------------------------- */ - { - const int64_t S = 2, QL = 3, HG = 2, H = 2, K = 16, V = 16, WID = 4; - const int64_t CD = 2 * HG * K + H * V, SL = WID - 2 + QL; - Hand h("num_accepted 2 and 3", "gdn_conv_update", 2e-5); - h.dense(RAD_F32, { S * QL, CD }, hfill(14)) - .dense(RAD_F32, { CD, WID }, hfill(15, 0.5f)) - .none() - .dense(RAD_F32, { 3, CD, SL }, hfill(16), true) - .idx({ 2, 0 }) - .idx({ 2, 3 }) - .idx({ 0, QL, 2 * QL }) - .dense(RAD_F32, { S * QL, HG, K }, hfill(17), true) - .dense(RAD_F32, { S * QL, HG, K }, hfill(18), true) - .dense(RAD_F32, { S * QL, H, V }, hfill(19), true) - .pi("q_len", QL).pi("head_k", K).pi("head_v", V).pi("conv_width", WID) - .pi("max_query_len", QL); - hs.push_back(std::move(h)); - - /* The same step over a CHANNEL-CONTIGUOUS state, [slot][t][c] viewed as [slot][c][t]: - * the layout that takes libavx's row-move path rather than its element loop. */ - Hand m("num_accepted 2 and 3, channel-contiguous state", "gdn_conv_update", 2e-5); - m.dense(RAD_F32, { S * QL, CD }, hfill(14)) - .dense(RAD_F32, { CD, WID }, hfill(15, 0.5f)) - .none() - .view(RAD_F32, { 3, CD, SL }, { SL * CD, 1, CD }, 3 * SL * CD, hfill(16), true) - .idx({ 2, 0 }) - .idx({ 2, 3 }) - .idx({ 0, QL, 2 * QL }) - .dense(RAD_F32, { S * QL, HG, K }, hfill(17), true) - .dense(RAD_F32, { S * QL, HG, K }, hfill(18), true) - .dense(RAD_F32, { S * QL, H, V }, hfill(19), true) - .pi("q_len", QL).pi("head_k", K).pi("head_v", V).pi("conv_width", WID) - .pi("max_query_len", QL); - hs.push_back(std::move(m)); - } - /* ---- head widths that do not divide the 1024-channel panel ------------------------------- */ - { - const int64_t S = 2, QL = 2, HG = 4, H = 8, K = 96, V = 96, WID = 4; - const int64_t CD = 2 * HG * K + H * V, SL = WID - 2 + QL; - Hand h("head_k = head_v = 96, conv_dim 1536", "gdn_conv_update", 2e-5); - h.dense(RAD_F32, { S * QL, CD }, hfill(20)) - .dense(RAD_F32, { CD, WID }, hfill(21, 0.5f)) - .none() - .dense(RAD_F32, { 2, CD, SL }, hfill(22), true) - .idx({ 1, 0 }) - .idx({ 1, 2 }) - .idx({ 0, QL, 2 * QL }) - .dense(RAD_F32, { S * QL, HG, K }, hfill(23), true) - .dense(RAD_F32, { S * QL, HG, K }, hfill(24), true) - .dense(RAD_F32, { S * QL, H, V }, hfill(25), true) - .pi("q_len", QL).pi("head_k", K).pi("head_v", V).pi("conv_width", WID) - .pi("max_query_len", QL); - hs.push_back(std::move(h)); - - const int64_t M = 6; - Hand p("head_k = head_v = 96, conv_dim 1536", "gdn_conv_prep", 2e-5); - p.dense(RAD_F32, { M, CD + 2 * H }, hfill(26)) - .dense(RAD_F32, { CD, WID }, hfill(27, 0.5f)) - .none() - .dense(RAD_F32, { H }, hfill(28, 0.5f)) - .dense(RAD_F32, { H }, hfill(29, 0.5f)) - .dense(RAD_F32, { 2, CD, WID - 1 }, hfill(30), true) - .idx({ 0, 4, M }) - .none().none() - .idx({ 1, 0 }) - .idx({ 1, 0 }) - .dense(RAD_F32, { M, HG, K }, hfill(31), true) - .dense(RAD_F32, { M, HG, K }, hfill(32), true) - .dense(RAD_F32, { M, H, V }, hfill(33), true) - .dense(RAD_F32, { M, H }, hfill(34), true) - .dense(RAD_F32, { M, H }, hfill(35), true) - .pi("M", M).pi("head_k", K).pi("head_v", V).pi("chunk", 4).pi("conv_width", WID) - .pf("l2_eps", 1e-6).pf("softplus_thr", 20.0); - hs.push_back(std::move(p)); - } - /* ---- the PLE ops at their band's upper bound, and a verify over two sequences ------------ */ - { - const int64_t T = 5, N = 32, HC = 2, BAND = 64; - Hand g("M = 64 over 5 rows", "ple_gate", 1e-5); - g.dense(RAD_F32, { T, HC * N }, hfill(36)) - .dense(RAD_F32, { T, HC * N }, hfill(37)) - .dense(RAD_F32, { T, N }, hfill(38)) - .dense(RAD_F32, { HC * N }, hfill(39, 0.2f)) - .dense(RAD_F32, { HC * N }, hfill(40, 0.2f)) - .dense(RAD_F32, { HC * N }, hfill(41, 0.2f)) - .dense(RAD_F32, { T, HC * N }, hfill(42), true) - .dense(RAD_F32, { T, HC * N }, hfill(43), true) - .pi("M", BAND).pi("n", N).pi("hc", HC).pf("eps", 1e-6).ps("dtype", "f32") - .pf("wadd", 1.0); - hs.push_back(std::move(g)); - - /* Two sequences, a verify of 3 and one of 2, reading at offsets 1 and 2 of a window deep - * enough for both: hist 6 at width 4 and dilation 2, plus a verify's n - 1. */ - const int64_t WIDTH = 4, DIL = 2, HIST = (WIDTH - 1) * DIL, SL = HIST + 2; - Hand c("M = 64 over 5 rows, verifies of 3 and 2", "ple_conv", 1e-5); - c.dense(RAD_F32, { T, N }, hfill(44)) - .dense(RAD_F32, { N, WIDTH }, hfill(45, 0.5f)) - .dense(RAD_F32, { 2, N, SL }, hfill(46), true) - .idx({ 0, 3, 5 }) - .dense(RAD_F32, { T, N }, hfill(47)) - .idx({ 1, 0 }) - .idx({ 7, 9 }) - .idx({ 2, 3 }) - .dense(RAD_F32, { T, N }, hfill(48), true) - .pi("M", BAND).pi("n", N).pi("width", WIDTH).pi("dilation", DIL).ps("dtype", "f32"); - hs.push_back(std::move(c)); - - /* LFM2's form of the same window: width 3, undilated, no residual and no activation. */ - const int64_t CW = 3, CHIST = CW - 1, CSL = CHIST + 2; - Hand k("M = 64 over 5 rows, verifies of 3 and 2", "causal_conv1d", 1e-5); - k.dense(RAD_F32, { T, N }, hfill(55)) - .dense(RAD_F32, { N, CW }, hfill(56, 0.5f)) - .dense(RAD_F32, { 2, N, CSL }, hfill(57), true) - .idx({ 0, 3, 5 }) - .idx({ 1, 0 }) - .idx({ 7, 9 }) - .idx({ 2, 3 }) - .dense(RAD_F32, { T, N }, hfill(58), true) - .pi("M", BAND).pi("n", N).pi("width", CW).ps("dtype", "f32"); - hs.push_back(std::move(k)); - - /* The antialiased resample ENLARGING a 4 x 4 table (a drawn case's grid is never larger - * than the table), one row shrinking it, and a 1 x 1 grid. */ - static const int32_t kAaCrd[4][6] = { { 0, 6, 3, 1, 0, 5 }, { 0, 8, 4, 2, 0, 1 }, - { 7, 7, 7, 2, 1, 7 }, { 9, 9, 9, 3, 1, 9 } }; - Hand ga("a 4 x 4 table onto 7 x 9, 2 x 3 and 1 x 1 grids", "grid_embed_aa", 1e-6); - ga.dense(RAD_F32, { 6, N }, hfill(59), true) - .dense(RAD_F32, { 16, N }, hfill(60)) - .dense(RAD_I32, { 4, 6 }, [](int64_t i) { return (float)kAaCrd[i / 6][i % 6]; }) - .pi("M", 6).pi("n", N).pi("side", 4).ps("dtype", "f32"); - hs.push_back(std::move(ga)); - - Hand n("M = 64 over 5 rows, verifies of 3 and 2", "ngram_ids", 0.0); - n.idx({ 11, 12, 13, 21, 22 }) - .dense(RAD_I32, { 2, 2 + 2 }, [](int64_t i) { return (float)(100 + i); }, true) - .idx({ 0, 3, 5 }) - .dense(RAD_I64, { 3 }, [](int64_t i) { return (float)(1000003 + 7919 * i); }) - .dense(RAD_I64, { 4 }, [](int64_t i) { return (float)(97 + 2 * i); }) - .dense(RAD_I64, { 4 }, [](int64_t i) { return (float)(1000 * i); }) - .idx({ 1, 0 }) - .idx({ 7, 9 }) - .idx({ 2, 3 }) - .dense(RAD_I32, { T, 4 }, [](int64_t) { return -1.0f; }, true) - .pi("M", BAND).pi("heads", 4).pi("ngram", 3).pi("eos", 5); - hs.push_back(std::move(n)); - } - /* ---- packed weight codes at odd element offsets ------------------------------------------ */ - { - const int64_t M = 2, N = 4, K = 33; - Hand h("W4 weight, K = 33: odd rows start mid-byte", "gemm_nt_q", 1e-5); - h.dense(RAD_F32, { M, K }, hfill(49)) - .none() - .dense(RAD_I4, { N, K }, hfill(50, 2.0f)) - .dense(RAD_F32, { N, 1 }, [](int64_t i) { return 0.5f + 0.25f * (float)i; }) - .dense(RAD_F32, { M, N }, hfill(51), true) - .pi("M", M).pi("N", N).pi("K", K).ps("dtype", "w4a16"); - hs.push_back(std::move(h)); - - Hand w("W2 weight, K = 33", "gemm_nt_q", 1e-5); - w.dense(RAD_F32, { M, K }, hfill(52)) - .none() - .dense(RAD_I2, { N, K }, hfill(53, 2.0f)) - .dense(RAD_F32, { N, 1 }, [](int64_t i) { return 1.0f + (float)i; }) - .dense(RAD_F32, { M, N }, hfill(54), true) - .pi("M", M).pi("N", N).pi("K", K).ps("dtype", "w2a16"); - hs.push_back(std::move(w)); - } - /* ---- integer stores past the range, and exponents of -inf and NaN ------------------------ */ - { - const float big[] = { 1e10f, -1e10f, INFINITY, -INFINITY, 2.5f, -2.5f, 3.5f, 127.5f, - -128.5f, 300.0f, -300.0f, 0.49f }; - const int64_t n = (int64_t)(sizeof big / sizeof big[0]); - for (const char* to : { "i8", "u8", "i16" }) { - /* 51 elements: the vector body runs at every level and so does the scalar tail. */ - const int64_t len = 4 * n + 3; - Hand h((std::string("f32 -> ") + to + " past the range").c_str(), "cast", 0.0); - const uint32_t dt = rad_dtype_parse(to); - h.dense(RAD_F32, { 1, len }, [&big, n](int64_t i) { return big[i % n]; }) - .dense(dt, { 1, len }, [](int64_t) { return 0.0f; }, true) - .pi("M", 1).pi("n", len).ps("from", "f32").ps("to", to); - hs.push_back(std::move(h)); - } - /* 48 wide, a whole number of vectors at every level: a scalar tail's own exp would turn - * the row's sum into a NaN by itself and hide what the vector exp did with one. */ - Hand s("rows of -inf: one fully masked, one partly", "softmax", 1e-6); - const int64_t w = 48; - s.dense(RAD_F32, { 3, w }, [w](int64_t i) { - const int64_t r = i / w, c = i % w; - if (r == 0) return -INFINITY; - if (r == 1 && c % 3 == 0) return -INFINITY; - return (float)(c % 7) * 0.5f - 1.0f; - }) - .dense(RAD_F32, { 3, w }, [](int64_t) { return 0.0f; }, true) - .pi("M", 3).pi("n", w).ps("dtype", "f32"); - hs.push_back(std::move(s)); - } - - /* ---- the drafter's walk with the pairwise term in charge -------------------------------- * - * A cold description draws `pred` and `succ` as weights, at 0.02, where the pairwise term is a - * thousandth of `unary` and never moves a pick: the walk is checked and the form is not. Here - * the codebooks are unit-scale and `unary` half that, so every pick is the form's. Some - * candidates are outside the vocabulary (-1 and past it) and so is the second sequence's - * anchor, which is the "contributes nothing" branch. Once with `hp` and once without. */ - for (int with_hp : { 1, 0 }) { - const int64_t M = 3, L = 4, K = 8, R = 40, NV = 50; - Hand h(with_hp ? "unit codebooks, hp present, ids outside the vocab" - : "unit codebooks, hp absent (a plane of ones)", "dflash_select", 0.0); - h.dense(RAD_I32, { M * L, K }, [](int64_t i) { return (float)((i * 7 + 3) % 53 - 1); }) - .dense(RAD_F32, { M * L, K }, hfill(31, 0.5f)); - if (with_hp) h.dense(RAD_BF16, { M * L, R }, hfill(32)); - else h.none(); - h.idx({ 5, 60, 17 }) - .dense(RAD_BF16, { NV, R }, hfill(33)) - .dense(RAD_BF16, { NV, R }, hfill(34)) - .dense(RAD_I32, { M, L }, [](int64_t) { return 0.0f; }, true) - .pi("M", M).pi("steps", L).pi("top_k", K).pi("rank", R).pi("n_vocab", NV) - .pi("anchor_stride", 1).ps("dtype", "bf16"); - hs.push_back(std::move(h)); - } - - /* ---- the fp8 fusions without their optional operands ------------------------------------ * - * The cold descriptions always carry `residual` and `out_bf16`; the plain norm and a caller - * that wants only the codes are the other forms. `mode` 1 is sigmoid in libr4d's spelling. */ - { - const int64_t M = 4, n = 200; - Hand r("no residual, no out_bf16, ragged group", "rmsnorm_quant_fp8", 4e-3); - r.dense(RAD_BF16, { M, n }, hfill(41)) - .none() - .dense(RAD_BF16, { n }, hfill(42, 0.1f)) - .dense(RAD_F8E4M3, { M, n }, [](int64_t) { return 0.0f; }, true) - .dense(RAD_F32, { M, 4 }, [](int64_t) { return 0.0f; }, true) - .pi("M", M).pi("n", n).pf("eps", 1e-6).pi("group", 64).ps("dtype", "bf16") - .pf("wadd", 1.0); - hs.push_back(std::move(r)); - - Hand g("mode 1, no out_bf16", "gated_quant_fp8", 6e-3); - g.dense(RAD_BF16, { M, 2 * n }, hfill(43)) - .dense(RAD_F8E4M3, { M, n }, [](int64_t) { return 0.0f; }, true) - .dense(RAD_F32, { M, 4 }, [](int64_t) { return 0.0f; }, true) - .pi("M", M).pi("n", n).pi("group", 64).ps("dtype", "bf16").pi("mode", 1); - hs.push_back(std::move(g)); - } - - /* ---- scatter_rows: a negative index writes nothing, and the rows nobody names stay ------- */ - { - const int64_t n = 70; - Hand s("idx with -1 over a 12-row pool", "scatter_rows", 0.0); - s.dense(RAD_F32, { 4, n }, hfill(51)) - .idx({ 5, -1, 0, 9 }) - .dense(RAD_F32, { 12, n }, hfill(52), true) - .pi("M", 4).pi("n", n).ps("dtype", "f32"); - hs.push_back(std::move(s)); - } - - /* ---- ParoQuant's rotation over real pairings: every stage of every group a permutation of - * its 128 columns read as pairs, two parts of three stages. The dense form over a drawn matrix - * a (part, group) -- the op takes whatever matrices the weight stores. --------------------- */ - { - const int64_t M = 5, K = 256, S = 3, P = 2, G = 128; - std::vector pr((size_t)(P * S * K)); - for (int64_t ps = 0; ps < P * S; ++ps) - for (int64_t g = 0; g < K / G; ++g) { - std::vector perm((size_t)G); - for (int64_t i = 0; i < G; ++i) perm[(size_t)i] = (int32_t)i; - uint64_t x = 0x9E3779B97F4A7C15ull * (uint64_t)(ps * 31 + g + 1); - for (int64_t i = G - 1; i > 0; --i) { - x ^= x >> 31; x *= 0xBF58476D1CE4E5B9ull; x ^= x >> 29; - std::swap(perm[(size_t)i], perm[(size_t)(x % (uint64_t)(i + 1))]); - } - for (int64_t i = 0; i < G; ++i) - pr[(size_t)(ps * K + g * G + i)] = (int32_t)(g * G + perm[(size_t)i]); - } - const auto h63 = hfill(63); - const auto scl = [h63](int64_t i) { return 1.25f + 0.75f * h63(i); }; /* (0.5, 2) */ - const auto zero = [](int64_t) { return 0.0f; }; - for (uint32_t ydt : { (uint32_t)RAD_F16, (uint32_t)RAD_F32 }) { - Hand h(ydt == RAD_F16 ? "two parts of three stages, y f16" : "two parts of three stages, y f32", - "givens_rotate", 1e-5); - h.dense(RAD_BF16, { M, K }, hfill(61)) - .dense(RAD_I32, { P * S, K }, [pr](int64_t i) { return (float)pr[(size_t)i]; }) - .dense(RAD_F32, { P * S, K / 2 }, hfill(62, 3.0f)) - .dense(RAD_F32, { P, K }, scl) - .dense(ydt, { M, P * K }, zero, true) - .pi("M", M).pi("n", K).pi("group", G).ps("dtype", "bf16").pi("stages", S) - .pi("parts", P); - hs.push_back(std::move(h)); - } - /* A code may sit on a rounding edge that libref's f64 sum and libavx's f32 sum land on - * either side of, one step of the grid: the tolerance is a few such codes in 2560. */ - for (const char* outq : { "fp8", "i8" }) { - const bool i8 = outq[0] == 'i'; - Hand h(i8 ? "two parts, i8" : "two parts, fp8", "givens_dense_quant", 5e-3); - h.dense(RAD_BF16, { M, K }, hfill(64)) - .dense(RAD_F16, { P * K, G }, hfill(65, 0.1f)) - .dense(RAD_F32, { P, K }, scl) - .dense(i8 ? RAD_I8 : RAD_F8E4M3, { M, P * K }, zero, true) - .dense(RAD_F32, { M, P * K / G }, zero, true) - .pi("M", M).pi("n", K).pi("group", G).ps("dtype", "bf16").pi("parts", P) - .ps("out", outq); - hs.push_back(std::move(h)); - } - } - - bool ok = true; - int fails = 0; - for (Hand& h : hs) { - ++*n_checked; - if (!h.run(ref, avx, verbose)) { ok = false; ++fails; } - } - std::printf(" hand-built: %d checked, %d failed\n", (int)hs.size(), fails); return ok; } /* ================================================================== schema agreement - * core/plugin/loader.cpp:schema_same, reproduced so a drift is caught here rather than at an - * engine start on a machine that has a model on it. */ + * A copy of core/plugin/loader.cpp: schema_same, so drift is caught here rather than at engine + * start. */ static bool schema_same(const RadOpSchema& a, const RadOpSchema& b, std::string* why) { char buf[256]; if (a.n_params != b.n_params) { @@ -873,54 +614,75 @@ static bool schema_same(const RadOpSchema& a, const RadOpSchema& b, std::string* return true; } -/* embed_lookup_q over a file-backed table, two ranks and the reader racing (avx_check_rows.cpp). */ -bool row_gather_case(const Lib& avx, const std::string& dir, int64_t calls, bool verbose, - bool bf16); -/* embed_lookup_q's init, where io_uring is refused and here (avx_check_rows.cpp). */ -bool ngram_init_case(const Lib& avx); +/* The directory holding this binary, on the build's filesystem (which reports its direct-I/O + * alignment on ext4 or XFS). */ +static std::string self_dir(const char* argv0) { + const std::string self = argv0; + const size_t sl = self.rfind('/'); + return sl == std::string::npos ? "." : self.substr(0, sl); +} int main(int argc, char** argv) { - std::string ref_path = "libref.so", avx_path = "libavx.so", only_op; + std::string ref_path = "libref.so", avx_path = "libavx.so"; int only_level = -1; - bool verbose = false; - double tol_override = -1; + Check ck; + ck.threads = 4; for (int i = 1; i < argc; ++i) { const std::string s = argv[i]; auto next = [&]() -> const char* { return i + 1 < argc ? argv[++i] : ""; }; - if (s == "--ref") ref_path = next(); - else if (s == "--avx") avx_path = next(); - else if (s == "--op") only_op = next(); - else if (s == "--level") only_level = std::atoi(next()); - else if (s == "--tol") tol_override = std::atof(next()); - else if (s == "-v" || s == "--verbose") verbose = true; + if (s == "--ref") ref_path = next(); + else if (s == "--avx") avx_path = next(); + else if (s == "--op") ck.only_op = next(); + else if (s == "--level") only_level = std::atoi(next()); + else if (s == "--tol") ck.tol_override = std::atof(next()); + else if (s == "--threads") ck.threads = std::atoi(next()); + else if (s == "-v" || s == "--verbose") ck.verbose = true; else if (s == "-h" || s == "--help") { std::printf( - "rad-avx-check -- libavx against libref, every op, every ISA level.\n\n" + "rad-avx-check -- a host kernel library against libref, every op, every ISA " + "level.\n\n" " --ref PATH the oracle plugin (default libref.so)\n" - " --avx PATH the plugin under test (default libavx.so)\n" + " --avx PATH the plugin under test (default libavx.so); any host library\n" " --op NAME only this op\n" " --level N only this ISA level (0 scalar 1 avx 2 avx2 3 avx512)\n" + " --threads N rerun every case with each parallel region on N threads and\n" + " require the same bytes (default 4, 0 to skip; libavx only)\n" " --tol X override every tolerance (for bisecting, not for passing)\n" - " -v print every case, not only the failures\n"); + " -v print every case, not only the failures\n\n" + "A library not named libavx is checked as a host library: the libref ops it\n" + "does not serve are listed rather than failed (libavx/README.md).\n"); return 0; } } - Lib ref, avx; - if (!ref.open(ref_path.c_str()) || !avx.open(avx_path.c_str())) return 2; + Lib ref, lib; + if (!ref.open(ref_path.c_str()) || !lib.open(avx_path.c_str())) return 2; + ck.ref = &ref; + ck.lib = &lib; + ck.own = std::strcmp(lib.info->name, "libavx") == 0; + const char* who = lib.info->name; std::printf("oracle : %s %s (%s)\n", ref.info->name, ref.info->version, ref_path.c_str()); - std::printf("under : %s %s (%s)\n", avx.info->name, avx.info->version, avx_path.c_str()); + std::printf("under : %s %s (%s)\n", who, lib.info->version, avx_path.c_str()); + if (!ck.own) + std::printf(" checked as a host library: the ops it lacks are listed, not " + "failed\n"); /* ---- 1. schema agreement */ - int sch_bad = 0; - for (int i = 0, n = avx.schema_count(); i < n; ++i) { - const RadOpSchema* sa = avx.schema_at(i); + int sch_bad = 0, sch_extra = 0; + for (int i = 0, n = lib.schema_count(); i < n; ++i) { + const RadOpSchema* sa = lib.schema_at(i); if (!sa || !sa->op) continue; const RadOpSchema* sr = ref.schema(sa->op); if (!sr) { - std::printf("SCHEMA %-24s declared by libavx and not by libref\n", sa->op); - ++sch_bad; + if (ck.own) { + std::printf("SCHEMA %-24s declared by %s and not by libref\n", sa->op, who); + ++sch_bad; + } else { + if (ck.verbose) + std::printf("SCHEMA %-24s not in libref: no oracle, not checked\n", sa->op); + ++sch_extra; + } continue; } std::string why; @@ -929,131 +691,143 @@ int main(int argc, char** argv) { ++sch_bad; } } - std::printf("schemas: %d declared, %d disagree with libref\n", avx.schema_count(), sch_bad); + std::printf("schemas: %d declared, %d disagree with libref", lib.schema_count(), sch_bad); + if (sch_extra) std::printf(", %d not in libref (no oracle)", sch_extra); + std::printf("\n"); if (sch_bad) { - std::printf("\nThe loader refuses a plugin on ANY schema disagreement, so this would make " - "every row\nlibavx carries unreachable. Nothing below is worth reading until " - "that is fixed.\n"); + std::printf("\nThe loader refuses a plugin on any schema disagreement, so every row of %s " + "would be\nunreachable. Fix the schemas first.\n", who); return 1; } /* ---- 2. coverage * - * OPS WITH NO CPU PATH BY DECISION, named one by one: the image generator's (arch/qwenimage21). - * A DiT step at 2048^2 is about 4e14 FLOP, minutes on a CPU, so the generator is a GPU program - * and libavx serves none of its ops. The list is what keeps the rule a rule -- an op missing - * from libavx and not named here is still a kernel built and never wired. */ - static const char* const kNoCpuPath[] = { - "ln_mod", "gate_add", "timestep_embed", "gather_rows2", "lane_gather", "lane_store", - "randn_lanes", "flow_euler", "chan_affine", "conv2d_nhwc", "l2norm_chan", "d2s_add", - "s2d_avg_add", "to_rgba8", "gelu_tanh", "scatter_add_rows", "attn_prefix_self", - "ln_mod_quant_fp8", - }; - auto no_cpu_path = [](const char* op) { - for (const char* o : kNoCpuPath) - if (!std::strcmp(o, op)) return true; - return false; - }; - int missing = 0, exempt = 0; + * Any op libref implements and libavx lacks is a failure. For another library every gap is + * listed. */ + int missing = 0, device_only = 0; + std::vector gaps; for (int i = 0, n = ref.kernel_count(); i < n; ++i) { const RadKernelInfo* kr = ref.kernel_at(i); if (!kr || !kr->op) continue; - if (!avx.row(kr->op) && no_cpu_path(kr->op)) { - ++exempt; - continue; - } - if (!avx.row(kr->op)) { - std::printf("COVER %-24s libref implements it, libavx does not\n", kr->op); - ++missing; - } + if (lib.host_row(kr->op)) continue; + if (lib.row(kr->op)) ++device_only; + if (ck.own) std::printf("COVER %-24s libref implements it, %s does not\n", kr->op, who); + ++missing; + gaps.push_back(kr->op); } - std::printf("coverage: libref %d rows, libavx %d rows, %d op(s) missing, %d with no CPU path " - "(the image generator's)\n", ref.kernel_count(), avx.kernel_count(), missing, exempt); - - /* ---- 3/4. the numbers, per ISA level */ - const std::vector cases = build_cases(); - if (!avx.isa_force) { - std::printf("\nNOTE: %s exports no avx_isa_force, so only the path it selects for itself " - "is\nexercised. That is honest but it is not the four-level sweep.\n", - avx_path.c_str()); + if (ck.own) { + std::printf("coverage: libref %d rows, %s %d rows, %d op(s) missing\n", + ref.kernel_count(), who, lib.kernel_count(), missing); } else { - std::printf("cpu : highest executable level is %s\n", avx.isa_name(avx.isa_detect())); + std::printf("coverage: libref %d rows, %s %d rows; %d of libref's ops have no host row " + "here (%d a device row only)", ref.kernel_count(), who, lib.kernel_count(), + missing, device_only); + if (!gaps.empty()) { + std::printf(", not checked:\n "); + for (const std::string& g : gaps) std::printf(" %s", g.c_str()); + } + std::printf("\n"); } - int rc = missing ? 1 : 0; - /* Before anything runs a gather: the case forks, and a child is cleanest taken from a process - * that has started none of the gather's threads. */ - if (only_op.empty() || only_op == "embed_lookup_q") { + /* ---- 3/4/5. the numbers, per ISA level */ + const std::vector cases = build_cases(); + int lo = 0, hi = 0, top = 0; + if (!lib.isa_force) { + std::printf("\nNote: %s exports no avx_isa_force, so only the level it selects for itself " + "is checked.\n", avx_path.c_str()); + } else { + std::printf("cpu : highest executable level is %s\n", lib.isa_name(lib.isa_detect())); + lo = only_level >= 0 ? only_level : 0; + hi = only_level >= 0 ? only_level : AVX_N_LEVELS - 1; + top = std::min(hi, lib.isa_detect()); + } + if (ck.threads > 0 && !lib.par_force) { + std::printf("Note: %s exports no avx_par_force, so its parallel regions are not forced.\n", + avx_path.c_str()); + ck.threads = 0; + } else if (ck.threads > 0) { + const int forced = lib.par_force(ck.threads); + lib.par_force(0); + if (!forced) { + std::printf("Note: %s was built without OpenMP: no parallel region to force.\n", + avx_path.c_str()); + ck.threads = 0; + } + } + + int rc = ck.own && missing ? 1 : 0; + const bool gather = ck.own && (ck.only_op.empty() || ck.only_op == "embed_lookup_q"); + /* Run before any gather: the case forks, best done before the gather's threads exist. */ + if (gather) { std::printf("\n"); - if (!ngram_init_case(avx)) rc = 1; + if (!ngram_init_case(lib)) rc = 1; } - const int lo = only_level >= 0 ? only_level : 0; - const int hi = only_level >= 0 ? only_level : AVX_N_LEVELS - 1; std::vector declined_ops; for (int lvl = lo; lvl <= hi; ++lvl) { - int actual = lvl; - if (avx.isa_force) actual = avx.isa_force(lvl); - if (actual != lvl) { - /* CLAMPED, AND SAID SO. Reporting a pass for a level the machine cannot execute would - * be reporting that a path works on a machine that never ran it. */ - std::printf("\n== level %d (%s): NOT EXECUTABLE on this CPU -- avx_isa_force clamped to" - " %s.\n This row proves nothing about level %d and is not counted.\n", - lvl, avx.isa_name ? avx.isa_name(lvl) : "?", - avx.isa_name ? avx.isa_name(actual) : "?", lvl); - continue; + if (lib.isa_force) { + const int actual = lib.isa_force(lvl); + if (actual != lvl) { + /* Clamped: the level cannot run here, so report it and count nothing. */ + std::printf("\n== level %d (%s): not executable on this CPU (clamped to %s), not " + "counted\n", lvl, lib.isa_name(lvl), lib.isa_name(actual)); + continue; + } + std::printf("\n== level %d (%s) ==\n", lvl, lib.isa_name(lvl)); + } else { + std::printf("\n== %s ==\n", who); } - std::printf("\n== level %d (%s) ==\n", lvl, avx.isa_name ? avx.isa_name(lvl) : "?"); - /* Before the tolerances: the conversions have to be EXACT, and they are checked over their - * whole input space rather than over a draw. Run per level, because the vectorised bodies - * differ per level and a draw of normals reaches none of the patterns that separate them. */ - if (!exhaustive_cast(ref, avx, verbose)) rc = 1; + /* Exhaustive conversion check first, per level (the vector bodies differ per level). */ + if (ck.only_op.empty() || ck.only_op == "cast") + if (!exhaustive_cast(ck)) rc = 1; Stats st; for (const Case& c : cases) { - if (!only_op.empty() && only_op != c.op) continue; - /* A speed-only case has no correctness question to ask -- see avx_harness.h. */ + if (!ck.only_op.empty() && ck.only_op != c.op) continue; + /* Speed-only cases are not checked (avx_harness.h). */ if (c.speed_only) continue; - const size_t before = (size_t)st.declined; - run_case(ref, avx, c, verbose, tol_override, &st); - if ((size_t)st.declined != before && lvl == lo) { - bool seen = false; - for (const std::string& s : declined_ops) if (s == c.op) { seen = true; break; } - if (!seen) declined_ops.push_back(c.op); - } + const int before = st.declined; + run_case(ck, c, &st); + if (st.declined != before && + std::find(declined_ops.begin(), declined_ops.end(), c.op) == declined_ops.end()) + declined_ops.push_back(c.op); } - std::printf(" %d checked, %d passed, %d failed, %d declined, %d skipped, %d missing." - " worst rel_l2 = %.3e", - st.checked, st.passed, st.failed, st.declined, st.skipped, st.missing, - st.worst); + std::printf(" %d checked, %d passed, %d failed, %d declined, %d skipped, %d missing.", + st.checked, st.passed, st.failed, st.declined, st.skipped, st.missing); + if (st.unselected) std::printf(" %d admitted by no row's constraints.", st.unselected); + std::printf(" worst rel_l2 = %.3e", st.worst); if (!st.worst_where.empty()) std::printf("\n worst case: %s", st.worst_where.c_str()); + if (st.rerun) std::printf("\n %d rerun on %d threads, byte for byte", st.rerun, ck.threads); std::printf("\n"); - if (st.failed || st.declined || st.missing) rc = 1; - if (only_op.empty()) { - int hand_checked = 0; - if (!hand_cases(ref, avx, verbose, &hand_checked)) rc = 1; - } - if (only_op.empty() || only_op == "embed_lookup_q") { - /* Beside the binary, on the build's filesystem, which reports its direct-I/O - * alignment wherever the build is on ext4 or XFS. */ - const std::string self = argv[0]; - const size_t sl = self.rfind('/'); - const std::string at = sl == std::string::npos ? "." : self.substr(0, sl); - /* The E4M3 table the quantised containers carry, and the plain bf16 one a checkpoint - * served as it ships carries: one path, two row sizes. */ - if (!row_gather_case(avx, at, 1000, verbose, false)) rc = 1; - if (!row_gather_case(avx, at, 1000, verbose, true)) rc = 1; - /* And in TMPDIR, which is a tmpfs on most machines: since Linux 6.6 a tmpfs does - * direct reads and reports no alignment for them, as btrfs does, so the gather finds - * its granule from the block size there. */ - const char* tmp = std::getenv("TMPDIR"); - if (!row_gather_case(avx, tmp && *tmp ? tmp : "/tmp", 1000, verbose, false)) rc = 1; + if (st.failed || st.declined || st.skipped || (ck.own && st.missing)) rc = 1; + if (!hand_cases(ck)) rc = 1; + if (!zero_row_cases(ck, cases)) rc = 1; + if (gather) { + /* The E4M3 table of quantised containers and the plain bf16 one of an unconverted + * checkpoint: one path, two row sizes. The reads, the cache and the reader thread are + * compiled once, at the baseline, so the two ranks race through 1000 calls only at the + * highest level; the others run 50, enough to check their decode. Ids differ per level, + * so each level also misses the cache. */ + const std::string at = self_dir(argv[0]); + const int64_t calls = lvl == top ? 1000 : 50; + const uint64_t seed = 0x9e3779b97f4a7c15ull + (uint64_t)lvl; + if (!row_gather_case(lib, at, calls, seed, ck.verbose, false)) rc = 1; + if (!row_gather_case(lib, at, calls, seed, ck.verbose, true)) rc = 1; + /* And in TMPDIR, usually tmpfs: since Linux 6.6 tmpfs does direct reads but reports + * no alignment (like btrfs), so the gather uses the block size. Only the read differs + * there, so it runs once. */ + if (lvl == top) { + const char* tmp = std::getenv("TMPDIR"); + if (!row_gather_case(lib, tmp && *tmp ? tmp : "/tmp", calls, seed, ck.verbose, + false)) + rc = 1; + } } } if (!declined_ops.empty()) { - std::printf("\nDECLINED (RAD_E_UNSUPPORTED from a row that claims the op) -- %d op(s):\n ", + std::printf("\nDeclined (RAD_E_UNSUPPORTED from a row that claims the op), %d op(s):\n ", (int)declined_ops.size()); for (const std::string& s : declined_ops) std::printf(" %s", s.c_str()); - std::printf("\nA row that declines is worse than no row: the selector resolves to it and " - "the step\nfails at issue rather than at declare.\n"); + std::printf("\nThe selector resolves to such a row, so the step fails at issue, not at " + "declare.\n"); } std::printf("\n%s\n", rc == 0 ? "PASS" : "FAIL"); return rc; diff --git a/libavx/avx_check.h b/libavx/avx_check.h new file mode 100644 index 00000000..9de2c94c --- /dev/null +++ b/libavx/avx_check.h @@ -0,0 +1,64 @@ +/* avx_check.h -- what rad-avx-check's translation units share: the run's settings, the value + * comparison and the parallel rerun. */ +#ifndef RAD_AVX_CHECK_H +#define RAD_AVX_CHECK_H + +#include "avx_harness.h" + +#include +#include +#include +#include + +/* One run: the oracle, the library under test, and what it is held to. */ +struct Check { + const Lib* ref = nullptr; + const Lib* lib = nullptr; + /* The library under test is libavx and is held to libavx's contract: every op libref + * implements (avx_check.cpp lists those not yet implemented), and the file-backed gather of + * embed_lookup_q with its init. Any other host library is checked op for op against libref, and what it does not + * implement is reported rather than failed. */ + bool own = false; + /* Team size of the parallel rerun (avx_par_force), or 0 for none. */ + int threads = 0; + bool verbose = false; + double tol_override = -1; + /* Only this op, or every op when empty. */ + std::string only_op; +}; + +/* rad-kbench's error metric: the finiteness pattern is compared before any norm. */ +struct Err { + double max_abs = 0, max_rel = 0, rel_l2 = 0; + int64_t nonfinite_gap = 0, n = 0; +}; +Err compare(const float* got, const float* ref, int64_t n); + +/* One output buffer of `n` elements of `dt`, the library's against the oracle's. Token and row ids + * (i32, u32, i64) must match exactly: widened to f32, two ids above 2^24 can compare equal and an + * off-by-one under the relative tolerance passes. Everything else is held to `tol` in rel_l2 with + * the finiteness pattern first. Returns false with the reason in `why`; `rel` gets the error. */ +bool same_values(uint32_t dt, const void* ref, const void* got, int64_t n, double tol, + double* rel, std::string* why); + +/* The serial run's outputs against a rerun with every parallel region forced to `threads` team + * threads (avx_par_force). libavx partitions only outer loops and never reduces across threads + * (avx_common.h), so the rerun must reproduce every byte. `outs` are the output buffers and + * `bytes` their sizes; `reset` restores every output and in-out buffer to its pre-launch bytes and + * `launch` runs the library's kernel once. Returns false with the reason in `why`. */ +bool parallel_rerun(const Lib& lib, int threads, const std::vector& outs, + const std::vector& bytes, const std::function& reset, + const std::function& launch, std::string* why); + +/* The hand-built cases (avx_check_hand.cpp). Returns false on any failure, having printed it. */ +bool hand_cases(const Check& ck); + +/* embed_lookup_q over a file-backed table in `dir`, with two ranks and the reader racing, for + * `calls` calls whose ids are drawn from `seed` (avx_check_rows.cpp). Each table is written once + * per process and kept mapped, so later calls reuse it. */ +bool row_gather_case(const Lib& lib, const std::string& dir, int64_t calls, uint64_t seed, + bool verbose, bool bf16); +/* embed_lookup_q's init with io_uring refused, and in this process (avx_check_rows.cpp). */ +bool ngram_init_case(const Lib& lib); + +#endif /* RAD_AVX_CHECK_H */ diff --git a/libavx/avx_check_hand.cpp b/libavx/avx_check_hand.cpp new file mode 100644 index 00000000..e0de7805 --- /dev/null +++ b/libavx/avx_check_hand.cpp @@ -0,0 +1,3075 @@ +/* avx_check_hand.cpp -- rad-avx-check's hand-built cases: operands no description draws. + * + * libref's opd_shape describes each op one way: one sequence where allowed, dense operands at the + * declared rank, plain integer operands. The engine passes more, and each hand-built case below is + * one such shape: + * + * several sequences through a path chosen for uniform queries; + * a rank-2 column slice of a fused projection, with the projection's width as row stride; + * a speculative step whose `num_accepted` reads a rolling window past offset zero; + * a ranged parameter at its band's upper bound over an operand with fewer rows; + * head widths that do not divide a kernel's channel panel; + * packed weight codes at odd element offsets; + * integer stores past the target's range, and exps of -inf and NaN; + * bit patterns a float draw cannot make: packed (id, logit) words, sampler rows, e8m0 exponents; + * weight formats and scale grids libref does not describe. + * + * Both plugins get byte-identical copies, and each OUT/INOUT buffer is compared whole, not just the + * view, so writes outside the view are caught. Every buffer carries guard bytes, every input must + * be unchanged, and the parallel rerun applies as for the table (avx_check.cpp). */ +#include "avx_check.h" +#include "rad_planes.h" +#include "rad_sample.h" +#ifdef AVX_CHECK_CORE_DECODER +#include "format/encoding.h" +#endif + +#include + +namespace { + +struct Hand { + struct Buf { + uint32_t dt = RAD_F32; + int64_t elems = 0; + std::vector orig; /* the bytes both sides start from */ + GBuf a, b; + bool out = false; + }; + std::string name, op; + std::deque bufs; + std::vector buf_of; /* per operand: backing buffer index, or -1 */ + std::vector ta, tb; + std::vector p; + /* String parameters' values with their index in `p`. `p` points into them only at launch: + * a Hand is copied when the case vector grows, which would leave earlier pointers dangling. */ + std::vector> strs; + double tol = 1e-5; + /* Ids both sides must produce, independent of either: (operand, values). */ + int want_opd = -1; + std::vector want; + /* The return both sides must give, RAD_OK unless the case pins a refusal; a refusal must + * leave every buffer as it was. */ + int want_rc = RAD_OK; + /* An answer computed by neither library for output operand `oracle_opd`, both sides held to + * it within `oracle_tol` (rel_l2). Empty when this build cannot compute one. */ + int oracle_opd = -1; + std::vector oracle; + double oracle_tol = 0; + + Hand(const char* n, const char* o, double t) : name(n), op(o), tol(t) {} + + /* An operand over a fresh buffer of `span` elements holding `bytes`, viewed with `shape` and + * `stride`. */ + Hand& bytes(uint32_t dt, std::vector shape, std::vector stride, int64_t span, + std::vector b, bool out) { + Buf bf; + bf.dt = dt; bf.elems = span; bf.out = out; + bf.orig = std::move(b); + bf.orig.resize(dt_bytes(dt, span), 0); + bf.a.assign(bf.orig); + bf.b.assign(bf.orig); + bufs.push_back(std::move(bf)); + RadTensor t{}; + t.dtype = dt; + t.rank = (uint32_t)shape.size(); + for (size_t i = 0; i < shape.size(); ++i) { + t.shape[i] = shape[i]; + t.stride[i] = stride[i]; + } + ta.push_back(t); tb.push_back(t); + buf_of.push_back((int)bufs.size() - 1); + return *this; + } + /* The whole buffer is filled, since bytes outside the view stand for other columns. */ + Hand& view(uint32_t dt, std::vector shape, std::vector stride, int64_t span, + const std::function& fill, bool out = false) { + std::vector v((size_t)span); + for (int64_t i = 0; i < span; ++i) v[(size_t)i] = fill(i); + std::vector b(dt_bytes(dt, span)); + h_narrow(v.data(), dt, span, b.data()); + return bytes(dt, std::move(shape), std::move(stride), span, std::move(b), out); + } + static std::vector dense_strides(const std::vector& shape, int64_t* elems) { + std::vector st(shape.size()); + int64_t acc = 1; + for (int i = (int)shape.size() - 1; i >= 0; --i) { + st[(size_t)i] = acc; + acc *= shape[(size_t)i]; + } + *elems = acc; + return st; + } + /* A dense operand of `shape`. */ + Hand& dense(uint32_t dt, std::vector shape, const std::function& fill, + bool out = false) { + int64_t n = 0; + std::vector st = dense_strides(shape, &n); + return view(dt, std::move(shape), std::move(st), n, fill, out); + } + /* A dense operand holding `src`'s bytes verbatim. */ + Hand& raw(uint32_t dt, std::vector shape, const void* src, bool out = false) { + int64_t n = 0; + std::vector st = dense_strides(shape, &n); + const uint8_t* s = (const uint8_t*)src; + return bytes(dt, std::move(shape), std::move(st), n, + std::vector(s, s + dt_bytes(dt, n)), out); + } + Hand& idx(std::vector v, bool out = false) { + return dense(RAD_I32, { (int64_t)v.size() }, [v](int64_t i) { return (float)v[(size_t)i]; }, + out); + } + /* Another operand over operand `opd`'s buffer and view, which the launch then writes: an + * input that is also the output (an in-place residual). */ + Hand& alias(int opd) { + ta.push_back(ta[(size_t)opd]); + tb.push_back(tb[(size_t)opd]); + buf_of.push_back(buf_of[(size_t)opd]); + bufs[(size_t)buf_of[(size_t)opd]].out = true; + return *this; + } + Hand& none() { + ta.push_back(RadTensor{}); + tb.push_back(RadTensor{}); + buf_of.push_back(-1); + return *this; + } + Hand& pi(const char* k, long long v) { + p.push_back(RadParam{ k, RAD_P_INT, v, 0, nullptr, 0 }); + return *this; + } + Hand& pf(const char* k, double v) { + p.push_back(RadParam{ k, RAD_P_F64, 0, 0, nullptr, v }); + return *this; + } + Hand& ps(const char* k, const char* v) { + strs.emplace_back(p.size(), v); + p.push_back(RadParam{ k, RAD_P_STR, 0, 0, nullptr, 0 }); + return *this; + } + Hand& refuses(int rc) { + want_rc = rc; + return *this; + } + /* Operand `opd` (an i32 output) must hold `v` on both sides. */ + Hand& expect(int opd, std::vector v) { + want_opd = opd; + want = std::move(v); + return *this; + } + + enum Result { PASS, FAIL, ABSENT }; + + Result fail(const std::string& why) { + std::printf(" FAIL %-20s %s\n %s\n", op.c_str(), name.c_str(), why.c_str()); + return FAIL; + } + + /* After a launch on one side: guards intact and inputs unchanged. */ + bool intact(bool side_a, const char* who) { + bool ok = true; + for (size_t i = 0; i < buf_of.size(); ++i) { + if (buf_of[i] < 0) continue; + const Buf& bf = bufs[(size_t)buf_of[i]]; + const GBuf& g = side_a ? bf.a : bf.b; + if (const int hit = g.guard_hit()) { + fail(std::string(who) + (hit < 0 ? " wrote before the start of operand " + : " wrote past the end of operand ") + + std::to_string(i)); + ok = false; + } + if (!bf.out && std::memcmp(g.data(), bf.orig.data(), bf.orig.size()) != 0) { + fail(std::string(who) + " changed its input operand " + std::to_string(i)); + ok = false; + } + } + return ok; + } + + Result run(const Check& ck) { + const Lib& ref = *ck.ref; + const Lib& lib = *ck.lib; + const char* who = lib.info->name; + for (const auto& [i, v] : strs) p[i].sval = v.c_str(); + const RadKernelInfo* kr = ref.row(op.c_str()); + const RadKernelInfo* ka = lib.select(op.c_str(), p.data(), (int)p.size()); + if (!kr) return fail("no row for the op in libref"); + if (!ka) { + if (ck.own) return fail(std::string("no row of ") + who + " admits the case"); + if (ck.verbose) + std::printf(" %-22s %-46s not served by %s\n", op.c_str(), name.c_str(), who); + return ABSENT; + } + for (size_t i = 0; i < ta.size(); ++i) { + if (buf_of[i] < 0) continue; + ta[i].data = bufs[(size_t)buf_of[i]].a.data(); + tb[i].data = bufs[(size_t)buf_of[i]].b.data(); + } + RadArgs aa{}, ab{}; + aa.t = ta.data(); aa.n_t = (int)ta.size(); + aa.p = p.data(); aa.n_p = (int)p.size(); + aa.world_size = 1; + ab = aa; ab.t = tb.data(); + const int rr = kr->launch(&aa, nullptr); + const int ra = ka->launch(&ab, nullptr); + if (want_rc != RAD_OK) { + bool same = true; + for (const Buf& bf : bufs) + same = same && bf.a.guard_hit() == 0 && bf.b.guard_hit() == 0 && + std::memcmp(bf.a.data(), bf.orig.data(), bf.orig.size()) == 0 && + std::memcmp(bf.b.data(), bf.orig.data(), bf.orig.size()) == 0; + if (rr != want_rc || ra != want_rc || !same) + return fail("expected both to refuse with " + std::to_string(want_rc) + + " and write nothing: libref " + std::to_string(rr) + ", " + who + + " " + std::to_string(ra) + (same ? "" : ", and a buffer changed")); + if (ck.verbose) + std::printf(" %-22s %-46s refused, nothing written\n", op.c_str(), + name.c_str()); + return PASS; + } + if (rr < 0) + return fail("libref refused the case (" + std::to_string(rr) + "); the case is wrong"); + if (ra < 0) + return fail(std::string(who) + " returned " + std::to_string(ra) + + " where libref returned " + std::to_string(rr)); + bool ok = intact(true, "libref"); + ok = intact(false, who) && ok; + double worst = 0; + for (const Buf& bf : bufs) { + if (!bf.out) continue; + double rel = 0; + std::string why; + if (!same_values(bf.dt, bf.a.data(), bf.b.data(), bf.elems, tol, &rel, &why)) { + ok = false; + std::printf(" FAIL %-20s %s\n %s\n", op.c_str(), name.c_str(), why.c_str()); + } + worst = std::max(worst, rel); + } + /* As for the table: some output must hold a value libref wrote, or the case is vacuous. */ + bool wrote = false; + for (const Buf& bf : bufs) { + if (!bf.out || wrote) continue; + std::vector now((size_t)bf.elems), was((size_t)bf.elems); + h_widen(bf.a.data(), bf.dt, bf.elems, now.data()); + h_widen(bf.orig.data(), bf.dt, bf.elems, was.data()); + for (int64_t i = 0; i < bf.elems && !wrote; ++i) + wrote = !(now[(size_t)i] == was[(size_t)i]); + } + if (!wrote) { + fail("libref's launch changed no output value, so the comparison is vacuous"); + ok = false; + } + if (want_opd >= 0) { + const Buf& bf = bufs[(size_t)buf_of[(size_t)want_opd]]; + for (int side = 0; side < 2; ++side) { + const uint8_t* d = side ? bf.b.data() : bf.a.data(); + for (size_t i = 0; i < want.size(); ++i) + if (avx::ld_int_dt(bf.dt, d, (int64_t)i) != want[i]) { + std::printf(" FAIL %-20s %s\n %s wrote %lld at %zu, expected %lld\n", + op.c_str(), name.c_str(), side ? who : "libref", + (long long)avx::ld_int_dt(bf.dt, d, (int64_t)i), i, + (long long)want[i]); + ok = false; + break; + } + } + } + double core_rel = -1; + if (oracle_opd >= 0 && !oracle.empty()) { + const Buf& bf = bufs[(size_t)buf_of[(size_t)oracle_opd]]; + for (int side = 0; side < 2; ++side) { + std::vector got((size_t)bf.elems); + h_widen(side ? bf.b.data() : bf.a.data(), bf.dt, bf.elems, got.data()); + const Err e = compare(got.data(), oracle.data(), bf.elems); + core_rel = std::max(core_rel, e.rel_l2); + if (e.nonfinite_gap || !(e.rel_l2 <= oracle_tol)) { + std::printf(" FAIL %-20s %s\n %s is %.3e from the core decoder's answer " + "(tolerance %.1e)\n", op.c_str(), name.c_str(), + side ? who : "libref", e.rel_l2, oracle_tol); + ok = false; + } + } + } + if (ok && ck.threads > 0 && lib.par_force) { + std::vector outs; + std::vector sizes; + for (Buf& bf : bufs) + if (bf.out) { + outs.push_back(bf.b.data()); + sizes.push_back(bf.b.size()); + } + auto reset = [&] { + for (Buf& bf : bufs) + if (bf.out) std::memcpy(bf.b.data(), bf.orig.data(), bf.orig.size()); + }; + std::string why; + if (!parallel_rerun(lib, ck.threads, outs, sizes, reset, + [&] { return ka->launch(&ab, nullptr); }, &why)) { + ok = false; + std::printf(" FAIL %-20s %s\n %s\n", op.c_str(), name.c_str(), why.c_str()); + } + ok = intact(false, who) && ok; + } + if (ck.verbose && core_rel >= 0) + std::printf(" %-22s %-46s rel_l2=%.3e tol=%.1e, core decoder %.3e %s\n", op.c_str(), + name.c_str(), worst, tol, core_rel, ok ? "ok" : "FAIL"); + else if (ck.verbose) + std::printf(" %-22s %-46s rel_l2=%.3e tol=%.1e %s\n", op.c_str(), name.c_str(), worst, + tol, ok ? "ok" : "FAIL"); + return ok ? PASS : FAIL; + } +}; + +/* Deterministic pseudo-random fill in [-sigma, sigma]: element i under seed s. */ +std::function hfill(uint64_t s, float sigma = 1.0f) { + return [s, sigma](int64_t i) { + uint64_t x = s * 0x9E3779B97F4A7C15ull + (uint64_t)i; + x ^= x >> 31; x *= 0xBF58476D1CE4E5B9ull; x ^= x >> 29; + return ((float)(x % 2001) / 1000.0f - 1.0f) * sigma; + }; +} + +/* ================================================================== operand shapes */ +void shape_cases(std::vector& hs) { + + /* ---- attention: two sequences through the uniform long-query form, no cu_seqlens ------- */ + { + const int64_t S = 2, QL = 32, KVH = 1, G = 2, HD = 16, BS = 16, NB = 6; + Hand h("n_seq=2 q_len=32 no cu_seqlens", "attn_paged", 1e-4); + h.dense(RAD_F32, { S * QL, KVH * G, HD }, hfill(1)) + .dense(RAD_F32, { NB, KVH, BS, 2 * HD }, hfill(2)) + .dense(RAD_I32, { S, 3 }, [](int64_t i) { return (float)((i * 5) % 6); }) + .idx({ 40, 36 }) + .none().none().none() + .dense(RAD_F32, { S * QL, KVH * G, HD }, hfill(3), true) + .pi("q_len", QL).pi("head_dim", HD).pi("gqa", G).pi("block_size", BS).pi("causal", 1) + .pi("window", 0).ps("q_dtype", "f32").ps("kv_dtype", "f32"); + hs.push_back(std::move(h)); + } + /* ---- attention and the KV write over column slices of a fused [q|k|v] projection ------- */ + { + const int64_t T = 5, NH = 2, KVH = 1, HD = 16, W = (NH + 2 * KVH) * HD, BS = 4, NB = 4; + Hand h("k, v are rank-2 column slices, row stride 64", "kv_store", 1e-6); + h.view(RAD_F32, { T, KVH * HD }, { W, 1 }, T * W, hfill(4)) /* k at column 0 */ + .view(RAD_F32, { T, KVH * HD }, { W, 1 }, T * W, hfill(5)) + .idx({ 3, 0, 9, 14, 6 }) + .dense(RAD_F32, { NB, KVH, BS, 2 * HD }, hfill(6), true) + .pi("M", T).pi("head_dim", HD).pi("n_head_kv", KVH).pi("block_size", BS) + .ps("kv_dtype", "f32"); + hs.push_back(std::move(h)); + + Hand g("q and out are rank-2 column slices", "attn_paged", 1e-4); + g.view(RAD_F32, { T, NH * HD }, { W, 1 }, T * W, hfill(7)) + .dense(RAD_F32, { NB, KVH, BS, 2 * HD }, hfill(8)) + .dense(RAD_I32, { T, 2 }, [](int64_t i) { return (float)(i % NB); }) + .idx({ 3, 5, 7, 2, 8 }) + .none().none().none() + .view(RAD_F32, { T, NH * HD }, { W, 1 }, T * W, hfill(9), true) + .pi("q_len", 1).pi("head_dim", HD).pi("gqa", NH / KVH).pi("block_size", BS) + .pi("causal", 1).pi("window", 0).ps("q_dtype", "f32").ps("kv_dtype", "f32"); + hs.push_back(std::move(g)); + + Hand d("q, k, v, out are rank-2 column slices", "attn_dense", 1e-4); + d.view(RAD_F32, { T, HD }, { W, 1 }, T * W, hfill(10)) + .view(RAD_F32, { T, HD }, { W, 1 }, T * W, hfill(11)) + .view(RAD_F32, { T, HD }, { W, 1 }, T * W, hfill(12)) + .idx({ 0, 2, 5 }) + .view(RAD_F32, { T, HD }, { W, 1 }, T * W, hfill(13), true) + .pi("M", T).pi("head_dim", HD).pi("gqa", 1).pi("causal", 1).ps("dtype", "f32"); + hs.push_back(std::move(d)); + } + /* ---- the GDN decode convolution read past offset zero ---------------------------------- */ + { + const int64_t S = 2, QL = 3, HG = 2, H = 2, K = 16, V = 16, WID = 4; + const int64_t CD = 2 * HG * K + H * V, SL = WID - 2 + QL; + Hand h("num_accepted 2 and 3", "gdn_conv_update", 2e-5); + h.dense(RAD_F32, { S * QL, CD }, hfill(14)) + .dense(RAD_F32, { CD, WID }, hfill(15, 0.5f)) + .none() + .dense(RAD_F32, { 3, CD, SL }, hfill(16), true) + .idx({ 2, 0 }) + .idx({ 2, 3 }) + .idx({ 0, QL, 2 * QL }) + .dense(RAD_F32, { S * QL, HG, K }, hfill(17), true) + .dense(RAD_F32, { S * QL, HG, K }, hfill(18), true) + .dense(RAD_F32, { S * QL, H, V }, hfill(19), true) + .pi("q_len", QL).pi("head_k", K).pi("head_v", V).pi("conv_width", WID) + .pi("max_query_len", QL); + hs.push_back(std::move(h)); + + /* The same step over a channel-contiguous state, [slot][t][c] viewed as [slot][c][t], + * which takes libavx's row-move path instead of the element loop. */ + Hand m("num_accepted 2 and 3, channel-contiguous state", "gdn_conv_update", 2e-5); + m.dense(RAD_F32, { S * QL, CD }, hfill(14)) + .dense(RAD_F32, { CD, WID }, hfill(15, 0.5f)) + .none() + .view(RAD_F32, { 3, CD, SL }, { SL * CD, 1, CD }, 3 * SL * CD, hfill(16), true) + .idx({ 2, 0 }) + .idx({ 2, 3 }) + .idx({ 0, QL, 2 * QL }) + .dense(RAD_F32, { S * QL, HG, K }, hfill(17), true) + .dense(RAD_F32, { S * QL, HG, K }, hfill(18), true) + .dense(RAD_F32, { S * QL, H, V }, hfill(19), true) + .pi("q_len", QL).pi("head_k", K).pi("head_v", V).pi("conv_width", WID) + .pi("max_query_len", QL); + hs.push_back(std::move(m)); + } + /* ---- head widths that do not divide the 1024-channel panel ------------------------------- */ + { + const int64_t S = 2, QL = 2, HG = 4, H = 8, K = 96, V = 96, WID = 4; + const int64_t CD = 2 * HG * K + H * V, SL = WID - 2 + QL; + Hand h("head_k = head_v = 96, conv_dim 1536", "gdn_conv_update", 2e-5); + h.dense(RAD_F32, { S * QL, CD }, hfill(20)) + .dense(RAD_F32, { CD, WID }, hfill(21, 0.5f)) + .none() + .dense(RAD_F32, { 2, CD, SL }, hfill(22), true) + .idx({ 1, 0 }) + .idx({ 1, 2 }) + .idx({ 0, QL, 2 * QL }) + .dense(RAD_F32, { S * QL, HG, K }, hfill(23), true) + .dense(RAD_F32, { S * QL, HG, K }, hfill(24), true) + .dense(RAD_F32, { S * QL, H, V }, hfill(25), true) + .pi("q_len", QL).pi("head_k", K).pi("head_v", V).pi("conv_width", WID) + .pi("max_query_len", QL); + hs.push_back(std::move(h)); + + const int64_t M = 6; + Hand p("head_k = head_v = 96, conv_dim 1536", "gdn_conv_prep", 2e-5); + p.dense(RAD_F32, { M, CD + 2 * H }, hfill(26)) + .dense(RAD_F32, { CD, WID }, hfill(27, 0.5f)) + .none() + .dense(RAD_F32, { H }, hfill(28, 0.5f)) + .dense(RAD_F32, { H }, hfill(29, 0.5f)) + .dense(RAD_F32, { 2, CD, WID - 1 }, hfill(30), true) + .idx({ 0, 4, M }) + .none().none() + .idx({ 1, 0 }) + .idx({ 1, 0 }) + .dense(RAD_F32, { M, HG, K }, hfill(31), true) + .dense(RAD_F32, { M, HG, K }, hfill(32), true) + .dense(RAD_F32, { M, H, V }, hfill(33), true) + .dense(RAD_F32, { M, H }, hfill(34), true) + .dense(RAD_F32, { M, H }, hfill(35), true) + .pi("M", M).pi("head_k", K).pi("head_v", V).pi("chunk", 4).pi("conv_width", WID) + .pf("l2_eps", 1e-6).pf("softplus_thr", 20.0); + hs.push_back(std::move(p)); + } + /* ---- the PLE ops at their band's upper bound, and a verify over two sequences ------------ */ + { + const int64_t T = 5, N = 32, HC = 2, BAND = 64; + Hand g("M = 64 over 5 rows", "ple_gate", 1e-5); + g.dense(RAD_F32, { T, HC * N }, hfill(36)) + .dense(RAD_F32, { T, HC * N }, hfill(37)) + .dense(RAD_F32, { T, N }, hfill(38)) + .dense(RAD_F32, { HC * N }, hfill(39, 0.2f)) + .dense(RAD_F32, { HC * N }, hfill(40, 0.2f)) + .dense(RAD_F32, { HC * N }, hfill(41, 0.2f)) + .dense(RAD_F32, { T, HC * N }, hfill(42), true) + .dense(RAD_F32, { T, HC * N }, hfill(43), true) + .pi("M", BAND).pi("n", N).pi("hc", HC).pf("eps", 1e-6).ps("dtype", "f32") + .pf("wadd", 1.0); + hs.push_back(std::move(g)); + + /* Two sequences, verifies of 3 and 2, reading at offsets 1 and 2 of a window deep enough + * for both: hist 6 (width 4, dilation 2) plus a verify's n - 1. */ + const int64_t WIDTH = 4, DIL = 2, HIST = (WIDTH - 1) * DIL, SL = HIST + 2; + Hand c("M = 64 over 5 rows, verifies of 3 and 2", "ple_conv", 1e-5); + c.dense(RAD_F32, { T, N }, hfill(44)) + .dense(RAD_F32, { N, WIDTH }, hfill(45, 0.5f)) + .dense(RAD_F32, { 2, N, SL }, hfill(46), true) + .idx({ 0, 3, 5 }) + .dense(RAD_F32, { T, N }, hfill(47)) + .idx({ 1, 0 }) + .idx({ 7, 9 }) + .idx({ 2, 3 }) + .dense(RAD_F32, { T, N }, hfill(48), true) + .pi("M", BAND).pi("n", N).pi("width", WIDTH).pi("dilation", DIL).ps("dtype", "f32"); + hs.push_back(std::move(c)); + + /* LFM2's form of the same window: width 3, undilated, no residual, no activation. */ + const int64_t CW = 3, CHIST = CW - 1, CSL = CHIST + 2; + Hand k("M = 64 over 5 rows, verifies of 3 and 2", "causal_conv1d", 1e-5); + k.dense(RAD_F32, { T, N }, hfill(55)) + .dense(RAD_F32, { N, CW }, hfill(56, 0.5f)) + .dense(RAD_F32, { 2, N, CSL }, hfill(57), true) + .idx({ 0, 3, 5 }) + .idx({ 1, 0 }) + .idx({ 7, 9 }) + .idx({ 2, 3 }) + .dense(RAD_F32, { T, N }, hfill(58), true) + .pi("M", BAND).pi("n", N).pi("width", CW).ps("dtype", "f32"); + hs.push_back(std::move(k)); + + /* The antialiased resample upscaling a 4 x 4 table (drawn grids never exceed the table), + * one row downscaling it, and a 1 x 1 grid. */ + static const int32_t kAaCrd[4][6] = { { 0, 6, 3, 1, 0, 5 }, { 0, 8, 4, 2, 0, 1 }, + { 7, 7, 7, 2, 1, 7 }, { 9, 9, 9, 3, 1, 9 } }; + Hand ga("a 4 x 4 table onto 7 x 9, 2 x 3 and 1 x 1 grids", "grid_embed_aa", 1e-6); + ga.dense(RAD_F32, { 6, N }, hfill(59), true) + .dense(RAD_F32, { 16, N }, hfill(60)) + .dense(RAD_I32, { 4, 6 }, [](int64_t i) { return (float)kAaCrd[i / 6][i % 6]; }) + .pi("M", 6).pi("n", N).pi("side", 4).ps("dtype", "f32"); + hs.push_back(std::move(ga)); + + Hand n("M = 64 over 5 rows, verifies of 3 and 2", "ngram_ids", 0.0); + n.idx({ 11, 12, 13, 21, 22 }) + .dense(RAD_I32, { 2, 2 + 2 }, [](int64_t i) { return (float)(100 + i); }, true) + .idx({ 0, 3, 5 }) + .dense(RAD_I64, { 3 }, [](int64_t i) { return (float)(1000003 + 7919 * i); }) + .dense(RAD_I64, { 4 }, [](int64_t i) { return (float)(97 + 2 * i); }) + .dense(RAD_I64, { 4 }, [](int64_t i) { return (float)(1000 * i); }) + .idx({ 1, 0 }) + .idx({ 7, 9 }) + .idx({ 2, 3 }) + .dense(RAD_I32, { T, 4 }, [](int64_t) { return -1.0f; }, true) + .pi("M", BAND).pi("heads", 4).pi("ngram", 3).pi("eos", 5); + hs.push_back(std::move(n)); + } + /* ---- packed weight codes at odd element offsets ------------------------------------------ */ + { + const int64_t M = 2, N = 4, K = 33; + Hand h("W4 weight, K = 33: odd rows start mid-byte", "gemm_nt_q", 1e-5); + h.dense(RAD_F32, { M, K }, hfill(49)) + .none() + .dense(RAD_I4, { N, K }, hfill(50, 2.0f)) + .dense(RAD_F32, { N, 1 }, [](int64_t i) { return 0.5f + 0.25f * (float)i; }) + .dense(RAD_F32, { M, N }, hfill(51), true) + .pi("M", M).pi("N", N).pi("K", K).ps("dtype", "w4a16"); + hs.push_back(std::move(h)); + + Hand w("W2 weight, K = 33", "gemm_nt_q", 1e-5); + w.dense(RAD_F32, { M, K }, hfill(52)) + .none() + .dense(RAD_I2, { N, K }, hfill(53, 2.0f)) + .dense(RAD_F32, { N, 1 }, [](int64_t i) { return 1.0f + (float)i; }) + .dense(RAD_F32, { M, N }, hfill(54), true) + .pi("M", M).pi("N", N).pi("K", K).ps("dtype", "w2a16"); + hs.push_back(std::move(w)); + } + /* ---- integer stores past the range, and exponents of -inf and NaN ------------------------ */ + { + const float big[] = { 1e10f, -1e10f, INFINITY, -INFINITY, 2.5f, -2.5f, 3.5f, 127.5f, + -128.5f, 300.0f, -300.0f, 0.49f }; + const int64_t n = (int64_t)(sizeof big / sizeof big[0]); + for (const char* to : { "i8", "u8", "i16" }) { + /* 51 elements: both the vector body and the scalar tail run at every level. */ + const int64_t len = 4 * n + 3; + Hand h((std::string("f32 -> ") + to + " past the range").c_str(), "cast", 0.0); + const uint32_t dt = rad_dtype_parse(to); + h.dense(RAD_F32, { 1, len }, [&big, n](int64_t i) { return big[i % n]; }) + .dense(dt, { 1, len }, [](int64_t) { return 0.0f; }, true) + .pi("M", 1).pi("n", len).ps("from", "f32").ps("to", to); + hs.push_back(std::move(h)); + } + /* 48 wide, whole vectors at every level, so the vector exp's handling of -inf is what + * gets tested (a scalar tail's NaN would mask it). */ + Hand s("rows of -inf: one fully masked, one partly", "softmax", 1e-6); + const int64_t w = 48; + s.dense(RAD_F32, { 3, w }, [w](int64_t i) { + const int64_t r = i / w, c = i % w; + if (r == 0) return -INFINITY; + if (r == 1 && c % 3 == 0) return -INFINITY; + return (float)(c % 7) * 0.5f - 1.0f; + }) + .dense(RAD_F32, { 3, w }, [](int64_t) { return 0.0f; }, true) + .pi("M", 3).pi("n", w).ps("dtype", "f32"); + hs.push_back(std::move(s)); + } + + /* ---- the drafter's walk with the pairwise term in charge -------------------------------- * + * Drawn as weights (sigma 0.02), `pred` and `succ` make the pairwise term too small to move a + * pick. Here the codebooks are unit-scale and `unary` half that, so the pairwise term decides. + * Some candidates and the second sequence's anchor are outside the vocabulary (the "contributes + * nothing" branch). Run with and without `hp`. */ + for (int with_hp : { 1, 0 }) { + const int64_t M = 3, L = 4, K = 8, R = 40, NV = 50; + Hand h(with_hp ? "unit codebooks, hp present, ids outside the vocab" + : "unit codebooks, hp absent (a plane of ones)", "dflash_select", 0.0); + h.dense(RAD_I32, { M * L, K }, [](int64_t i) { return (float)((i * 7 + 3) % 53 - 1); }) + .dense(RAD_F32, { M * L, K }, hfill(31, 0.5f)); + if (with_hp) h.dense(RAD_BF16, { M * L, R }, hfill(32)); + else h.none(); + h.idx({ 5, 60, 17 }) + .dense(RAD_BF16, { NV, R }, hfill(33)) + .dense(RAD_BF16, { NV, R }, hfill(34)) + .dense(RAD_I32, { M, L }, [](int64_t) { return 0.0f; }, true) + .pi("M", M).pi("steps", L).pi("top_k", K).pi("rank", R).pi("n_vocab", NV) + .pi("anchor_stride", 1).ps("dtype", "bf16"); + hs.push_back(std::move(h)); + } + + /* ---- the fp8 fusions without their optional operands ------------------------------------ * + * The cold descriptions always include `residual` and `out_bf16`. `mode` 1 is libr4d's + * spelling of sigmoid. */ + { + const int64_t M = 4, n = 200; + Hand r("no residual, no out_bf16, ragged group", "rmsnorm_quant_fp8", 4e-3); + r.dense(RAD_BF16, { M, n }, hfill(41)) + .none() + .dense(RAD_BF16, { n }, hfill(42, 0.1f)) + .dense(RAD_F8E4M3, { M, n }, [](int64_t) { return 0.0f; }, true) + .dense(RAD_F32, { M, 4 }, [](int64_t) { return 0.0f; }, true) + .pi("M", M).pi("n", n).pf("eps", 1e-6).pi("group", 64).ps("dtype", "bf16") + .pf("wadd", 1.0); + hs.push_back(std::move(r)); + + Hand g("mode 1, no out_bf16", "gated_quant_fp8", 6e-3); + g.dense(RAD_BF16, { M, 2 * n }, hfill(43)) + .dense(RAD_F8E4M3, { M, n }, [](int64_t) { return 0.0f; }, true) + .dense(RAD_F32, { M, 4 }, [](int64_t) { return 0.0f; }, true) + .pi("M", M).pi("n", n).pi("group", 64).ps("dtype", "bf16").pi("mode", 1); + hs.push_back(std::move(g)); + + /* Int8 codes, as the shared expert's gate writes them for its int8 down projection + * (quant_act_i8g's codes), with the bf16 product beside them. */ + Hand gi("silu into int8 codes, with out_bf16", "gated_quant_fp8", 1e-2); + gi.dense(RAD_BF16, { M, 2 * 256 }, hfill(44, 3.0f)) + .dense(RAD_I8, { M, 256 }, [](int64_t) { return 0.0f; }, true) + .dense(RAD_F32, { M, 2 }, [](int64_t) { return 0.0f; }, true) + .dense(RAD_BF16, { M, 256 }, [](int64_t) { return 0.0f; }, true) + .pi("M", M).pi("n", 256).pi("group", 128).ps("dtype", "bf16").ps("act", "silu"); + hs.push_back(std::move(gi)); + } + + /* ---- scale_rows without its optional residual (the table always passes `add`) ---------- */ + { + Hand h("no add, act sigmoid", "scale_rows", 1e-6); + h.dense(RAD_F32, { 4, 70 }, hfill(72)) + .dense(RAD_F32, { 4 }, hfill(73, 2.0f)) + .none() + .dense(RAD_F32, { 4, 70 }, [](int64_t) { return 0.0f; }, true) + .pi("M", 4).pi("n", 70).ps("act", "sigmoid").ps("dtype", "f32"); + hs.push_back(std::move(h)); + } + + /* ---- scatter_rows: a negative index writes nothing, and unnamed rows are kept ----------- */ + { + const int64_t n = 70; + Hand s("idx with -1 over a 12-row pool", "scatter_rows", 0.0); + s.dense(RAD_F32, { 4, n }, hfill(51)) + .idx({ 5, -1, 0, 9 }) + .dense(RAD_F32, { 12, n }, hfill(52), true) + .pi("M", 4).pi("n", n).ps("dtype", "f32"); + hs.push_back(std::move(s)); + + /* W4 rows of 33 codes: odd source rows start mid-byte. The output's row pitch is even, + * so no byte holds two rows' codes. */ + Hand g("W4 rows of 33, odd source rows start mid-byte", "gather_rows", 0.0); + g.dense(RAD_I4, { 5, 33 }, hfill(53, 7.0f)) + .idx({ 3, -1, 0, 1 }) + .view(RAD_I4, { 4, 33 }, { 34, 1 }, 4 * 34, hfill(54, 7.0f), true) + .pi("M", 4).pi("n", 33).ps("dtype", "i4"); + hs.push_back(std::move(g)); + } + + /* ---- ParoQuant's rotation over real pairings: each stage of each group is a permutation of + * its 128 columns read as pairs; two parts of three stages. The dense form uses a drawn matrix + * per (part, group). ------------------------------------------------------------------------ */ + { + const int64_t M = 5, K = 256, S = 3, P = 2, G = 128; + std::vector pr((size_t)(P * S * K)); + for (int64_t ps = 0; ps < P * S; ++ps) + for (int64_t g = 0; g < K / G; ++g) { + std::vector perm((size_t)G); + for (int64_t i = 0; i < G; ++i) perm[(size_t)i] = (int32_t)i; + uint64_t x = 0x9E3779B97F4A7C15ull * (uint64_t)(ps * 31 + g + 1); + for (int64_t i = G - 1; i > 0; --i) { + x ^= x >> 31; x *= 0xBF58476D1CE4E5B9ull; x ^= x >> 29; + std::swap(perm[(size_t)i], perm[(size_t)(x % (uint64_t)(i + 1))]); + } + for (int64_t i = 0; i < G; ++i) + pr[(size_t)(ps * K + g * G + i)] = (int32_t)(g * G + perm[(size_t)i]); + } + const auto h63 = hfill(63); + const auto scl = [h63](int64_t i) { return 1.25f + 0.75f * h63(i); }; /* (0.5, 2) */ + const auto zero = [](int64_t) { return 0.0f; }; + for (uint32_t ydt : { (uint32_t)RAD_F16, (uint32_t)RAD_F32 }) { + Hand h(ydt == RAD_F16 ? "two parts of three stages, y f16" : "two parts of three stages, y f32", + "givens_rotate", 1e-5); + h.dense(RAD_BF16, { M, K }, hfill(61)) + .dense(RAD_I32, { P * S, K }, [pr](int64_t i) { return (float)pr[(size_t)i]; }) + .dense(RAD_F32, { P * S, K / 2 }, hfill(62, 3.0f)) + .dense(RAD_F32, { P, K }, scl) + .dense(ydt, { M, P * K }, zero, true) + .pi("M", M).pi("n", K).pi("group", G).ps("dtype", "bf16").pi("stages", S) + .pi("parts", P); + hs.push_back(std::move(h)); + } + /* libref sums in f64 and libavx in f32, so a code on a rounding edge can differ by one + * grid step; the tolerance allows a few such codes in 2560. */ + for (const char* outq : { "fp8", "i8" }) { + const bool i8 = outq[0] == 'i'; + Hand h(i8 ? "two parts, i8" : "two parts, fp8", "givens_dense_quant", 5e-3); + h.dense(RAD_BF16, { M, K }, hfill(64)) + .dense(RAD_F16, { P * K, G }, hfill(65, 0.1f)) + .dense(RAD_F32, { P, K }, scl) + .dense(i8 ? RAD_I8 : RAD_F8E4M3, { M, P * K }, zero, true) + .dense(RAD_F32, { M, P * K / G }, zero, true) + .pi("M", M).pi("n", K).pi("group", G).ps("dtype", "bf16").pi("parts", P) + .ps("out", outq); + hs.push_back(std::move(h)); + } + } +} + +/* ================================================================== bit patterns and formats */ +void format_cases(std::vector& hs) { + const auto zero = [](int64_t) { return 0.0f; }; + + /* ---- logit_rerank: ties, and candidates outside this rank's rows ----------------------- * + * Head rows 3 and 7 hold the same values, so global ids 13 and 17 score exactly the same and + * the lower id must come first. 9 lies below the shard [10, 30), 30 past it, and -1 is a pad; + * all three must become pads that sort last. */ + { + const int64_t M = 3, R = 6, NV = 20, K = 40, VOFF = 10; + static const int32_t kIds[3][6] = { { 17, 13, 9, 30, -1, 25 }, + { 29, 10, 13, 17, 22, 11 }, + { -1, -1, 30, 5, 17, 13 } }; + const auto hw = hfill(70); + Hand h("tied ids, pads below, past and at -1", "logit_rerank", 1e-5); + h.dense(RAD_F32, { M, K }, hfill(71)) + .dense(RAD_F32, { NV, K }, [hw, K](int64_t i) { + const int64_t r = i / K; + return hw((r == 7 ? 3 : r) * K + i % K); + }) + .dense(RAD_I32, { M, R }, [](int64_t i) { return (float)kIds[i / 6][i % 6]; }) + .dense(RAD_I32, { M, R }, [](int64_t) { return 7.0f; }, true) + .dense(RAD_F32, { M, R }, zero, true) + .dense(RAD_F32, { M, R, 2 }, zero, true) + .pi("M", M).pi("R", R).pi("n_vocab", NV).pi("n_embd", K).pi("vocab_off", VOFF) + .ps("dtype", "f32"); + hs.push_back(std::move(h)); + } + + /* ---- sample_merge_topk: two ranks' runs of (u32 id, f32 logit) words -------------------- * + * Row 0 ties across the ranks at 2.0 and 1.5 (the lower id first), carries ids past 2^24 + * (exact as u32, not as f32), and has five live candidates for six slots. Row 1 asks top_k 2 + * of eight, row 2 is greedy (the chain does not run; every slot a pad). 0xffffffff is a hole. */ + { + const int64_t M = 3, W = 2, PER = 4, NC = 6; + const uint32_t B = 1u << 24, H = 0xffffffffu; + const float NI = -INFINITY; + struct Pair { uint32_t id; float v; }; + const Pair g[3][8] = { + { { B + 5, 2.0f }, { 7, 1.5f }, { B + 1, 1.0f }, { H, NI }, + { B + 3, 2.0f }, { B + 4, 1.5f }, { H, NI }, { H, NI } }, + { { 100, 3.0f }, { 101, 1.0f }, { 102, 0.5f }, { 103, 0.25f }, + { B + 7, 3.0f }, { 200, 2.0f }, { 201, -1.0f }, { H, NI } }, + { { 9, 4.0f }, { 8, 3.0f }, { H, NI }, { H, NI }, + { B + 9, 5.0f }, { H, NI }, { H, NI }, { H, NI } }, + }; + std::vector words((size_t)(M * W * PER * 2)); + for (int64_t m = 0; m < M; ++m) + for (int64_t j = 0; j < W * PER; ++j) { + words[(size_t)((m * W * PER + j) * 2)] = g[m][j].id; + std::memcpy(&words[(size_t)((m * W * PER + j) * 2 + 1)], &g[m][j].v, 4); + } + RadSampleParams sp[3] = {}; + for (RadSampleParams& s : sp) s.temp = 1.0f; + sp[1].top_k = 2; + sp[2].flags = RAD_SP_GREEDY; + const int64_t b = (int64_t)B; + Hand h("ties across ranks, ids past 2^24, holes, top_k 2, greedy", "sample_merge_topk", 0.0); + h.raw(RAD_U32, { M, W * PER * 2 }, words.data()) + .raw(RAD_F32, { M, (int64_t)(sizeof(RadSampleParams) / 4) }, sp) + .dense(RAD_I32, { M, NC }, [](int64_t) { return 7.0f; }, true) + .dense(RAD_F32, { M, NC }, zero, true) + .pi("M", M).pi("n_cand", NC) + .expect(2, { b + 3, b + 5, 7, b + 4, b + 1, -1, + 100, b + 7, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1 }); + hs.push_back(std::move(h)); + } + + /* ---- an fp8 cache read with per-(sequence, head) descales ------------------------------- * + * Decode and a uniform verify of 5 over two sequences, both descales present and different per + * KV head, which libref's description always leaves absent. */ + for (int64_t ql : { 1, 5 }) { + const int64_t S = 2, KVH = 2, G = 2, HD = 64, BS = 16, NB = 4; + Hand h(ql == 1 ? "fp8 cache, k_descale and v_descale, decode" + : "fp8 cache, k_descale and v_descale, verify of 5", "attn_paged", 2e-2); + h.dense(RAD_BF16, { S * ql, KVH * G, HD }, hfill(80)) + .dense(RAD_F8E4M3, { NB, KVH, BS, 2 * HD }, hfill(81, 2.0f)) + .dense(RAD_I32, { S, 2 }, [](int64_t i) { return (float)((i * 3 + 2) % 4); }) + .idx({ 20, 9 }) + .dense(RAD_F32, { S, KVH }, [](int64_t i) { return (float)(0.25 * (1 + (i * 5) % 7)); }) + .dense(RAD_F32, { S, KVH }, [](int64_t i) { return (float)(0.5 * (1 + (i * 3) % 5)); }) + .none() + .dense(RAD_BF16, { S * ql, KVH * G, HD }, zero, true) + .pi("q_len", ql).pi("head_dim", HD).pi("gqa", G).pi("block_size", BS).pi("causal", 1) + .pi("window", 0).ps("q_dtype", "bf16").ps("kv_dtype", "fp8_e4m3").pf("scale", 0.125); + hs.push_back(std::move(h)); + } + + /* ---- OCP-MXFP4 weights: e2m1 codes, one e8m0 exponent per 32 of K ----------------------- * + * Exponents 122..130 (scales 2^-5..2^3) and one 0xFF, which is NaN: weight row 5's fourth + * block, so output column 5 is NaN in every row on both sides. */ + { + const int64_t M = 3, N = 48, K = 256; + Hand h("mxfp4a8, e8m0 scales with one 0xFF (NaN)", "gemm_nt_q", 8e-3); + h.dense(RAD_F8E4M3, { M, K }, hfill(90, 4.0f)) + .dense(RAD_F32, { M, K / 128 }, [](int64_t i) { return 0.01f * (float)(1 + i); }) + .dense(RAD_FP4E2M1, { N, K }, hfill(91, 2.5f)) + .dense(RAD_U8, { N, K / 32 }, [](int64_t i) { + return i == 5 * 8 + 3 ? 255.0f : (float)(122 + i % 9); + }) + .dense(RAD_BF16, { M, N }, zero, true) + .none().none() + .pi("M", M).pi("N", N).pi("K", K).pi("group", 32).ps("dtype", "mxfp4a8"); + hs.push_back(std::move(h)); + } + + /* ---- The same with exponents no fold of a scale into the codes can take: 253 and 254 in the + * first 48 rows (a product up to 6 * 2^127 overflows where the grouped sum need not) and 1 in + * the next 48 (half of 2^-126 is a bf16 subnormal), the last 48 rows ordinary. A small + * activation scale keeps every output finite. -------------------------------------------- */ + { + const int64_t M = 3, N = 144, K = 256; + Hand h("mxfp4a8, e8m0 scales of 1, 253 and 254", "gemm_nt_q", 8e-3); + h.dense(RAD_F8E4M3, { M, K }, hfill(96, 4.0f)) + .dense(RAD_F32, { M, K / 128 }, [](int64_t i) { return 1e-4f * (float)(1 + i % 3); }) + .dense(RAD_FP4E2M1, { N, K }, hfill(97, 2.5f)) + .dense(RAD_U8, { N, K / 32 }, [](int64_t i) { + return i == 7 * 8 + 2 ? 253.0f : i == 30 * 8 ? 254.0f : i == 60 * 8 + 5 ? 1.0f + : (float)(122 + i % 9); + }) + .dense(RAD_BF16, { M, N }, zero, true) + .none().none() + .pi("M", M).pi("N", N).pi("K", K).pi("group", 32).ps("dtype", "mxfp4a8"); + hs.push_back(std::move(h)); + } + + /* ---- ParoQuant's multi-part GEMM: weight rows [0, pb1), [pb1, pb2), [pb2, N) each meet their + * own copy of the activation, the copies side by side in `a` and `a_scale`. Three parts, and + * two (no pb2). -------------------------------------------------------------------------- */ + for (int three : { 1, 0 }) { + const int64_t M = 3, N = 96, K = 256, P = three ? 3 : 2; + Hand h(three ? "mxfp4a8 in three parts, pb1 32, pb2 64" + : "mxfp4a8 in two parts, pb1 48", "gemm_nt_q", 8e-3); + h.dense(RAD_F8E4M3, { M, P * K }, hfill(92 + (uint64_t)three, 4.0f)) + .dense(RAD_F32, { M, P * K / 128 }, [](int64_t i) { return 0.01f + 0.002f * (float)i; }) + .dense(RAD_FP4E2M1, { N, K }, hfill(94 + (uint64_t)three, 2.5f)) + .dense(RAD_U8, { N, K / 32 }, [](int64_t i) { return (float)(122 + i % 9); }) + .dense(RAD_BF16, { M, N }, zero, true) + .none().none() + .pi("M", M).pi("N", N).pi("K", K).pi("group", 32).ps("dtype", "mxfp4a8"); + if (three) h.pi("pb1", 32).pi("pb2", 64); + else h.pi("pb1", 48); + hs.push_back(std::move(h)); + } + + /* ---- an activation grid finer than the weight's: libref applies such a scale per element. + * fp8 against a per-channel weight scale (one group of all K) with an activation scale per 64. + * ---------------------------------------------------------------------------------------- */ + { + const int64_t M = 3, N = 48, K = 256; + Hand h("activation scale per 64 against a per-channel weight", "gemm_nt_q", 8e-3); + h.dense(RAD_F8E4M3, { M, K }, hfill(110, 4.0f)) + .dense(RAD_F32, { M, K / 64 }, [](int64_t i) { return 0.01f + 0.004f * (float)i; }) + .dense(RAD_F8E4M3, { N, K }, hfill(111, 4.0f)) + .dense(RAD_BF16, { N, 1 }, [](int64_t i) { return 0.02f + 0.001f * (float)i; }) + .dense(RAD_BF16, { M, N }, zero, true) + .none().none() + .pi("M", M).pi("N", N).pi("K", K).pi("group", K).ps("dtype", "fp8a8"); + hs.push_back(std::move(h)); + } + + /* ---- the grouped GEMM over 4-bit experts, and over a finer activation grid --------------- * + * Token t's slot j goes to expert (t + 2j) % 4; rows are grouped by expert. Experts are int4 + * with an f16 scale per 128 of K, or e2m1 with an E4M3 scale per 32, against the E4M3 + * activation and its scale per 128; or fp8 per channel against an activation scale per 64. */ + { + const int64_t M = 5, TOPK = 2, NE = 4, T = M * TOPK, N = 32, K = 256; + std::vector sorted, off; + for (int64_t e = 0; e < NE; ++e) { + off.push_back((int64_t)sorted.size()); + for (int64_t t = 0; t < M; ++t) + for (int64_t j = 0; j < TOPK; ++j) + if ((t + 2 * j) % NE == e) sorted.push_back(t * TOPK + j); + } + off.push_back(T); + for (int form : { 0, 1, 2 }) { + const bool fine = form == 2; + const uint32_t wdt = form == 0 ? RAD_I4 : form == 1 ? RAD_FP4E2M1 : RAD_F8E4M3; + const uint32_t sdt = form == 0 ? RAD_F16 : form == 1 ? RAD_F8E4M3 : RAD_BF16; + const int64_t sk = form == 0 ? K / 128 : form == 1 ? K / 32 : 1; + const int64_t ag = fine ? 64 : 128; + Hand h(form == 0 ? "int4 experts, f16 scales per 128" + : form == 1 ? "e2m1 experts, E4M3 scales per 32" + : "activation scale per 64 against per-channel experts", + "moe_gemm_q", 8e-3); + h.dense(RAD_F8E4M3, { M, K }, hfill(100 + (uint64_t)form, 4.0f)) + .dense(RAD_F32, { M, K / ag }, [](int64_t i) { return 0.01f + 0.003f * (float)i; }) + .dense(wdt, { NE / 2, N, K }, hfill(103 + (uint64_t)form, 2.5f)) + .dense(sdt, { NE / 2, N, sk }, [](int64_t i) { return 0.05f + 0.01f * (float)(i % 7); }) + .idx(sorted) + .idx(off) + .dense(wdt, { NE / 2, N, K }, hfill(106 + (uint64_t)form, 2.5f)) + .dense(sdt, { NE / 2, N, sk }, [](int64_t i) { return 0.04f + 0.01f * (float)(i % 5); }) + .dense(RAD_BF16, { T, N }, zero, true) + .pi("M", M).pi("N", N).pi("K", K).pi("n_expert", NE).pi("top_k", TOPK) + .pi("group", ag).ps("a_order", "token") + .ps("dtype", form == 0 ? "w4a8" : "fp8a8"); + hs.push_back(std::move(h)); + } + } +} + + +/* ================================================================== the anchor state form */ + +/* The anchor layout at a [V, K] head (docs/OPS.md `state_form`; libref/ref_gdn.cpp AnchorLayout): + * the normalised k once per 32-row group of V, then v, then (g, beta) once per group, a token's + * factors `fstr` floats apart, as many tokens as fit before the stamp up to libr4d's 16 (`tmax`), + * the stamp at tmax * fstr. */ +struct AnLayout { + int64_t K, V, groups, fstr, gb, tmax, mark; + constexpr AnLayout(int64_t k, int64_t v) + : K(k), V(v), groups((v + 31) / 32), fstr(groups * k + v + 2 * groups), + gb(groups * k + v), tmax(std::min(16, (v * k - 1) / fstr)), + mark(tmax * fstr) {} +}; + +/* Four sequences over 14 state slots: a paged window (slots 0..5), a non-paged pair (6 and 7), a + * sequence with no rows this step (it still replays and publishes), and a padded one (a negative + * column: untouched). The factor blocks at column 4 carry stamps 2 and 1 (heads 0 and 1), 0 + * (zeroed: no shift) and 3 and 2, so the anchor is read at columns 2, 3, 2, 1 and 2; their first + * num_accepted tokens hold factors with a decaying g and a beta in (0, 1). `ql` and `nacc` are the + * first two sequences' rows and acceptances, at most the head's capacity. */ +Hand anchor_case(const AnLayout& L, const char* name, int64_t ql0, int64_t ql1, + std::vector nacc) { + const int64_t H = 2, N = 4, SLOTS = 14, T = ql0 + ql1 + 1; + static const int32_t kIdx[4][6] = { { 0, 1, 2, 3, 4, 5 }, { 6, 6, 6, 7, 7, 7 }, + { 8, 9, 10, 11, 12, 13 }, { -1, 0, 0, 0, 0, 0 } }; + auto stamp = [](int64_t slot, int64_t h) -> float { + if (slot == 4) return h ? 1.0f : 2.0f; + if (slot == 7) return 0.0f; + if (slot == 12) return h ? 2.0f : 3.0f; + return -1.0f; + }; + const auto rnd = hfill(120 + (uint64_t)L.K, 0.1f); + auto state_fill = [stamp, rnd, H, L](int64_t i) { + const int64_t blk = L.V * L.K, slot = i / (H * blk), h = (i / blk) % H, w = i % blk; + const float st = stamp(slot, h); + if (st >= 0.0f) { + if (w == L.mark) return st; + const int64_t t = w / L.fstr, r = w % L.fstr; + if (t < L.tmax && r >= L.gb) return (r - L.gb) % 2 ? 0.3f + 0.05f * (float)t + : -0.2f - 0.03f * (float)t; + } + return rnd(i); + }; + const int64_t K = L.K, V = L.V; + Hand h(name, "gdn_recurrent_update", 2e-5); + h.dense(RAD_F32, { T, 1, K }, hfill(121)) + .dense(RAD_F32, { T, 1, K }, hfill(122)) + .dense(RAD_F32, { T, H, V }, hfill(123)) + .dense(RAD_F32, { T, H }, hfill(124)) + .dense(RAD_F32, { T, H }, hfill(125)) + .dense(RAD_F32, { H }, [](int64_t i) { return -1.5f + 0.5f * (float)i; }) + .dense(RAD_F32, { H }, [](int64_t i) { return -0.75f + 0.25f * (float)i; }) + .dense(RAD_F32, { SLOTS, H, V, K }, state_fill, true) + .dense(RAD_I32, { N, 6 }, [](int64_t i) { return (float)kIdx[i / 6][i % 6]; }) + .idx(std::move(nacc)) + .idx({ 0, ql0, ql0 + ql1, ql0 + ql1, T }) + .dense(RAD_F32, { T, H, V }, hfill(126)) + .dense(RAD_F32, { V }, [](int64_t i) { return 1.0f + 0.01f * (float)(i % 7); }) + .dense(RAD_F32, { T, H, V }, [](int64_t) { return 0.0f; }, true) + .pi("q_len", std::max(ql0, ql1)).pi("head_k", K).pi("head_v", V).pi("n_head_v", H) + .pf("scale", 0.125).pf("eps", 1e-6).pf("l2_eps", 1e-6).pf("softplus_thr", 20.0) + .ps("act", "silu").ps("state_form", "anchor"); + return h; +} + +void anchor_cases(std::vector& hs) { + /* The layout's capacity, by hand: 64 x 64 is libr4d's (16 tokens, stamp at 16 * 196); a + * 16 x 16 block (256 floats, 34 a token) holds 7 tokens and the stamp at 7 * 34. */ + constexpr AnLayout big(64, 64), small(16, 16); + static_assert(big.tmax == 16 && big.mark == 3136, "libr4d's layout at 64 x 64"); + static_assert(small.tmax == 7 && small.mark == 238, "a 16 x 16 head holds 7 tokens"); + hs.push_back(anchor_case(big, "64 x 64: paged, non-paged, no rows, padded", 2, 3, + { 2, 3, 2, 1 })); + /* At the 16 x 16 head's capacity: a seven-token step after seven accepted tokens. */ + hs.push_back(anchor_case(small, "16 x 16 at its 7-token capacity", 7, 3, { 7, 3, 2, 1 })); + /* One past it, in rows or in the accepted prefix: refused before any write, by both. */ + hs.push_back(anchor_case(small, "16 x 16, an 8-token step is refused", 8, 3, { 1, 3, 2, 1 }) + .refuses(RAD_E_SHAPE)); + hs.push_back(anchor_case(small, "16 x 16, 8 accepted tokens are refused", 7, 3, + { 8, 3, 2, 1 }) + .refuses(RAD_E_SHAPE)); +} + +/* The anchor form's contract, on the library alone: with an f32 state the replay repeats the + * per-candidate arithmetic, so over steps accepting `sched` tokens of `ql`-row steps, with the + * paged window sliding by 0, +1, 0 and -1 pages, both forms give the same `o` bit for bit; a run + * that ignores num_accepted (always 1) gives a different one. This is what makes greedy + * speculation emit the same text as greedy decode. Returns false having printed the failure; true + * where the library does not serve the op. */ +bool anchor_replays_per_candidate(const Check& ck, int64_t K, int64_t V, int64_t QL, + const int (&nacc_sched)[4]) { + const Lib& lib = *ck.lib; + const int64_t H = 2, N = 2, T = N * QL, PAGES = 7; + const int win_sched[4] = { 0, 1, 1, 0 }; + const int64_t blk = H * V * K; + char what[64]; + std::snprintf(what, sizeof what, "anchor replay = per_candidate, %lld x %lld", + (long long)V, (long long)K); + std::vector st_pc((size_t)(N * QL * blk), 0.0f), st_an((size_t)(N * PAGES * blk), 0.0f); + std::vector st_one = st_an; + const auto init = hfill(130, 0.1f); + for (int64_t n = 0; n < N; ++n) + for (int64_t i = 0; i < blk; ++i) { + const float x = init(n * blk + i); + st_pc[(size_t)(n * QL * blk + i)] = x; + st_an[(size_t)((n * PAGES + win_sched[0] + 2) * blk + i)] = x; + st_one[(size_t)((n * PAGES + win_sched[0] + 2) * blk + i)] = x; + } + auto tensor = [](void* p, uint32_t dt, std::initializer_list shape) { + RadTensor t{}; + t.data = p; t.dtype = dt; t.rank = (uint32_t)shape.size(); + int i = 0; + for (int64_t x : shape) t.shape[i++] = x; + rad_tensor_pack(&t); + return t; + }; + std::vector alog = { -2.0f, -1.75f }, dtb = { -1.0f, -0.5f }, nw((size_t)V); + for (int64_t e = 0; e < V; ++e) nw[(size_t)e] = 1.0f + 0.01f * (float)(e % 9); + std::vector cu = { 0, (int32_t)QL, (int32_t)(2 * QL) }, idx_pc((size_t)(N * QL)); + for (int64_t i = 0; i < N * QL; ++i) idx_pc[(size_t)i] = (int32_t)i; + + int64_t differ_pc = 0, differ_one = 0; + for (int step = 0; step < 4; ++step) { + auto draw = [step](uint64_t s, int64_t n) { + std::vector v((size_t)n); + const auto f = hfill(140 + 10 * (uint64_t)step + s); + for (int64_t i = 0; i < n; ++i) v[(size_t)i] = f(i); + return v; + }; + std::vector q = draw(1, T * K), k = draw(2, T * K), v = draw(3, T * H * V); + std::vector a = draw(4, T * H), b = draw(5, T * H), z = draw(6, T * H * V); + std::vector nacc = { nacc_sched[step], nacc_sched[step] }, ones = { 1, 1 }; + std::vector idx_an((size_t)(N * 6)); + for (int64_t n = 0; n < N; ++n) + for (int64_t c = 0; c < 6; ++c) + idx_an[(size_t)(n * 6 + c)] = (int32_t)(n * PAGES + win_sched[step] + c); + auto go = [&](std::vector& st, int64_t slots, std::vector& idx, + int64_t idx_w, std::vector& na, const char* form, + std::vector& o) { + RadTensor t[16] = { + tensor(q.data(), RAD_F32, { T, 1, K }), tensor(k.data(), RAD_F32, { T, 1, K }), + tensor(v.data(), RAD_F32, { T, H, V }), tensor(a.data(), RAD_F32, { T, H }), + tensor(b.data(), RAD_F32, { T, H }), tensor(alog.data(), RAD_F32, { H }), + tensor(dtb.data(), RAD_F32, { H }), + tensor(st.data(), RAD_F32, { slots, H, V, K }), + tensor(idx.data(), RAD_I32, { N, idx_w }), tensor(na.data(), RAD_I32, { N }), + tensor(cu.data(), RAD_I32, { N + 1 }), tensor(z.data(), RAD_F32, { T, H, V }), + tensor(nw.data(), RAD_F32, { V }), tensor(o.data(), RAD_F32, { T, H, V }), + RadTensor{}, RadTensor{} }; + RadParam p[] = { { "q_len", RAD_P_INT, QL, 0, nullptr, 0 }, + { "head_k", RAD_P_INT, K, 0, nullptr, 0 }, + { "head_v", RAD_P_INT, V, 0, nullptr, 0 }, + { "n_head_v", RAD_P_INT, H, 0, nullptr, 0 }, + { "scale", RAD_P_F64, 0, 0, nullptr, 0.125 }, + { "eps", RAD_P_F64, 0, 0, nullptr, 1e-6 }, + { "act", RAD_P_STR, 0, 0, "silu", 0 }, + { "state_form", RAD_P_STR, 0, 0, form, 0 } }; + const int np = (int)(sizeof p / sizeof p[0]); + const RadKernelInfo* r = lib.select("gdn_recurrent_update", p, np); + if (!r) return 1; + RadArgs args{}; + args.t = t; args.n_t = 16; args.p = p; args.n_p = np; args.world_size = 1; + return r->launch(&args, nullptr) == RAD_OK ? 0 : -1; + }; + std::vector o_pc((size_t)(T * H * V)), o_an = o_pc, o_one = o_pc; + const int r1 = go(st_pc, N * QL, idx_pc, QL, nacc, "per_candidate", o_pc); + const int r2 = go(st_an, N * PAGES, idx_an, 6, nacc, "anchor", o_an); + const int r3 = go(st_one, N * PAGES, idx_an, 6, ones, "anchor", o_one); + if (r1 > 0 || r2 > 0 || r3 > 0) { + if (ck.own) { + std::printf(" FAIL gdn_recurrent_update %s\n no row of %s admits a form\n", + what, lib.info->name); + return false; + } + return true; + } + if (r1 < 0 || r2 < 0 || r3 < 0) { + std::printf(" FAIL gdn_recurrent_update %s\n step %d refused (per_candidate " + "%d, anchor %d, anchor with num_accepted 1 %d)\n", what, step, r1, r2, + r3); + return false; + } + differ_pc += std::memcmp(o_pc.data(), o_an.data(), o_pc.size() * sizeof(float)) != 0; + differ_one += std::memcmp(o_pc.data(), o_one.data(), o_pc.size() * sizeof(float)) != 0; + } + if (differ_pc || !differ_one) { + std::printf(" FAIL gdn_recurrent_update %s\n %lld of 4 steps' `o` differ from " + "per_candidate; the num_accepted-1 run differs in %lld (must be some)\n", + what, (long long)differ_pc, (long long)differ_one); + return false; + } + if (ck.verbose) + std::printf(" %-22s %-46s bit for bit\n", "gdn_recurrent_update", what); + return true; +} + +/* ================================================================== packed stores */ +void packed_cases(std::vector& hs) { + /* Nearest code, ties to the even code, saturation and NaN, into e2m1, int4 and int2: the + * stores a gather or a cast of packed rows rests on. 27 values, so the last byte is half + * used. */ + static const float kV[] = { 0.74f, 0.76f, -2.5f, 7.0f, -0.25f, 5.0f, 0.25f, 0.75f, 1.25f, + 1.75f, 2.5f, 3.5f, -5.0f, 6.5f, NAN, -0.0f, 3.0f, -8.5f, -8.0f, + 7.5f, -0.5f, 0.5f, 1e9f, -1e9f, 1.5f, -1.5f, 3.49f }; + const int64_t n = (int64_t)(sizeof kV / sizeof kV[0]); + for (const char* to : { "fp4_e2m1", "i4", "i2" }) { + const uint32_t dt = rad_dtype_parse(to); + Hand h((std::string("f32 -> ") + to + ": ties, saturation, NaN").c_str(), "cast", 0.0); + h.dense(RAD_F32, { 1, n }, [](int64_t i) { return kV[i]; }) + .dense(dt, { 1, n }, [](int64_t) { return 0.0f; }, true) + .pi("M", 1).pi("n", n).ps("from", "f32").ps("to", to); + hs.push_back(std::move(h)); + } +} + +/* ================================================================== the codebook experts + * + * moe_gemm_q and moe_gemm_q_mod4 over Qwen3.8-Flash-Next's codebook experts (docs/MOE-W4.md), + * whose views of several planes no description draws. Each case draws canonical planes (codes + * over the whole code range, the shipped w4nl or w5nl table, E4M3 or bf16 scales, the fixed 2^-13 + * level), stores them through each library's own layout hooks, and runs each library on its own + * stored bytes. Besides guard bytes, unchanged inputs and the threaded rerun, it checks: + * + * both libraries store the same bytes, and each unrelayout gives the planes back exactly; + * libavx against libref; + * libref over the stored form against libref over the logical form the oracle and rad-kbench + * pass (table entries as E4M3, scale times level as bf16), bit for bit; + * both against the core's decoder (core/format/encoding.h), when the checker is built in the + * source tree: the decoded weight, its 128-wide Hadamard undone, against the activation rotated + * back, summed in double. + * + * And each library's layout hooks refuse the same selections with the same code. */ +namespace cb { + +constexpr float kW4nl[16] = { 1.125f, 3.25f, 5.5f, 8.0f, 11.0f, 14.0f, 18.0f, 22.0f, + -1.125f, -3.25f, -5.5f, -8.0f, -11.0f, -14.0f, -18.0f, -22.0f }; +constexpr float kW5nl[32] = { 0.8125f, 2.5f, 4.0f, 5.5f, 7.5f, 9.0f, 11.0f, 12.0f, + 14.0f, 16.0f, 18.0f, 20.0f, 22.0f, 24.0f, 26.0f, 30.0f, + -0.8125f, -2.5f, -4.0f, -5.5f, -7.5f, -9.0f, -11.0f, -12.0f, + -14.0f, -16.0f, -18.0f, -20.0f, -22.0f, -24.0f, -26.0f, -30.0f }; + +struct Form { const char* dtype; int bits; int64_t group; uint32_t sdt; bool level; }; +constexpr Form kForms[] = { + { "w4nla8h", 4, 128, RAD_BF16, false }, + { "w4nl64a8h", 4, 64, RAD_F8E4M3, true }, + { "w4nl32a8h", 4, 32, RAD_F8E4M3, true }, + { "w5nl64a8h", 5, 64, RAD_F8E4M3, true }, +}; + +/* The encoding libquant writes for the form: codes, scale, its fixed level, then the table. */ +RadEncoding encoding(const Form& f) { + RadEncoding e; + rad_enc_clear(&e); + rad_enc_copy_str(e.scheme, "affine"); + rad_enc_copy_str(e.transform, "fwht128"); + rad_enc_add_plane(&e, "codes", f.bits == 5 ? RAD_U5 : RAD_U4, 1, 1); + rad_enc_add_plane(&e, "scale", f.sdt, 1, f.group); + if (f.level) rad_enc_add_plane(&e, "scale.1", RAD_F32, 0, 0); + rad_enc_add_table(&e, "table", RAD_F32, 1, (int64_t)1 << f.bits); + return e; +} + +uint64_t mix(uint64_t s, uint64_t i) { + uint64_t x = s * 0x9E3779B97F4A7C15ull + i; + x ^= x >> 31; x *= 0xBF58476D1CE4E5B9ull; x ^= x >> 29; + return x; +} + +/* One expert's planes, in encoding order, dense in their own elements. */ +struct Planes { + std::vector p[RAD_ENC_MAX_PLANES]; + int64_t rows[RAD_ENC_MAX_PLANES] = {}, cols[RAD_ENC_MAX_PLANES] = {}; + int64_t n = 0, k = 0; +}; + +Planes draw(const Form& f, const RadEncoding& e, int64_t n, int64_t k, uint64_t seed) { + Planes w; + w.n = n; + w.k = k; + for (int i = 0; i < e.n_planes; ++i) { + rad_enc_plane_dims(&e.plane[i], n, k, &w.rows[i], &w.cols[i]); + w.p[i].assign((size_t)(w.rows[i] * rad_enc_row_bytes(e.plane[i].dtype, w.cols[i])), 0); + } + const int ic = rad_enc_find(&e, "codes"), is = rad_enc_find(&e, "scale"); + const int il = rad_enc_find(&e, "scale.1"), it = rad_enc_find(&e, "table"); + const int64_t rbc = rad_enc_row_bytes(e.plane[ic].dtype, k); + for (int64_t r = 0; r < n; ++r) + for (int64_t c = 0; c < k; ++c) + rad_store_code(w.p[ic].data() + r * rbc, e.plane[ic].dtype, c, + (int)(mix(seed, (uint64_t)(r * k + c)) % (1u << f.bits))); + /* E4M3 scales over four binades, as the shipped experts' under 2^-13; bf16 at their size. */ + const int64_t sc = w.cols[is]; + for (int64_t r = 0; r < n; ++r) + for (int64_t c = 0; c < sc; ++c) { + const float u = (float)(mix(seed + 1, (uint64_t)(r * sc + c)) % 1000) / 1000.0f; + const float v = f.sdt == RAD_F8E4M3 ? std::ldexp(1.0f + u, (int)(r + c) % 4 - 2) + : 0.0005f + 0.002f * u; + rad_store_f32(w.p[is].data() + r * rad_enc_row_bytes(f.sdt, sc), f.sdt, c, v); + } + if (il >= 0) rad_store_f32(w.p[il].data(), RAD_F32, 0, 0x1p-13f); + std::memcpy(w.p[it].data(), f.bits == 5 ? kW5nl : kW4nl, sizeof(float) << f.bits); + return w; +} + +/* The selected planes as the loader hands them to a hook: rank 2, dense, with their bytes. */ +std::vector selection(const RadEncoding& e, const std::vector& sel, Planes& w) { + std::vector t; + for (int i : sel) { + RadTensor x{}; + x.data = w.p[i].data(); + x.dtype = e.plane[i].dtype; + x.rank = 2; + x.shape[0] = w.rows[i]; + x.shape[1] = w.cols[i]; + x.stride[0] = w.cols[i]; + x.stride[1] = 1; + t.push_back(x); + } + return t; +} + +/* The bytes kernel `k` stores for one view of an expert, and their dtype: its layout's, or the + * one selected plane when it stores that as it is. The layout must be the shared joined form, and + * its inverse must give the planes back. */ +bool store(const RadKernelInfo* k, const std::vector& p, int operand, + const RadEncoding& e, const std::vector& sel, Planes& w, std::vector* out, + uint32_t* dt, std::string* why) { + std::vector t = selection(e, sel, w); + const int n = (int)sel.size(); + RadLayout L{}; + int rc = k->layout ? k->layout(p.data(), (int)p.size(), operand, &e, sel.data(), t.data(), n, + &L) + : RAD_E_UNSUPPORTED; + if (rc == RAD_E_UNSUPPORTED) { + if (n != 1) { + *why = std::string(k->name) + " stores several planes as they are"; + return false; + } + *out = w.p[sel[0]]; + *dt = e.plane[sel[0]].dtype; + return true; + } + if (rc < 0 || !L.tag || std::strcmp(L.tag, RAD_PLANES_TAG) != 0 || !k->relayout || + !k->unrelayout) { + *why = std::string(k->name) + "'s layout answered " + std::to_string(rc) + ", tag " + + (L.tag ? L.tag : "(none)"); + return false; + } + out->assign((size_t)L.bytes, 0); + rc = k->relayout(p.data(), (int)p.size(), operand, &e, sel.data(), t.data(), n, out->data(), + L.bytes); + if (rc < 0) { + *why = std::string(k->name) + "'s relayout returned " + std::to_string(rc); + return false; + } + *dt = L.dtype; + std::vector> back(sel.size()); + std::vector bt = t; + for (size_t i = 0; i < sel.size(); ++i) { + back[i].assign(w.p[sel[i]].size(), 0xEE); + bt[i].data = back[i].data(); + } + rc = k->unrelayout(p.data(), (int)p.size(), operand, &e, sel.data(), out->data(), L.bytes, + bt.data(), n); + for (size_t i = 0; rc >= 0 && i < sel.size(); ++i) + if (back[i] != w.p[sel[i]]) rc = RAD_E_FORMAT; + if (rc < 0) { + *why = std::string(k->name) + "'s unrelayout did not give the planes back (" + + std::to_string(rc) + ")"; + return false; + } + return true; +} + +struct Case { + const char* name; + int form; + int ncls; /* 2: moe_gemm_q, 4: moe_gemm_q_mod4 */ + bool gate_up; /* token order and two parts; else sorted order, one part */ + int64_t M, top_k, ne; + int64_t w[4]; /* each class's intermediate width */ + int64_t n_embd; + bool drop; /* one slot routed outside this call's experts */ +}; + +/* One library's stored experts, as table operands: a buffer an expert and view, and the pointer + * arrays. */ +struct Stored { + std::deque bufs; + std::vector ptrs[8]; + RadTensor t[8]; +}; + +int run_case(const Check& ck, const Case& cs) { + const Lib& ref = *ck.ref; + const Lib& lib = *ck.lib; + const Form& f = kForms[cs.form]; + const char* op = cs.ncls == 4 ? "moe_gemm_q_mod4" : "moe_gemm_q"; + const int nc = cs.ncls; + char name[160]; + std::snprintf(name, sizeof name, "%s %s", f.dtype, cs.name); + auto fail = [&](const std::string& why) { + std::printf(" FAIL %-20s %s\n %s\n", op, name, why.c_str()); + return 1; + }; + int64_t Nq[4], Kq[4], N = 0, K = 0; + for (int q = 0; q < nc; ++q) { + Nq[q] = cs.gate_up ? 2 * cs.w[q] : cs.n_embd; + Kq[q] = cs.gate_up ? cs.n_embd : cs.w[q]; + N = std::max(N, Nq[q]); + K = std::max(K, Kq[q]); + } + const int64_t parts = cs.gate_up ? 2 : 1; + + /* The routing, as moe_scatter leaves it: slot (t, j) to expert (5t + j) % ne. */ + const int64_t T = cs.M * cs.top_k, ne = cs.ne; + std::vector sorted, offs; + auto expert_of = [&](int64_t i) -> int64_t { + const int64_t t = i / cs.top_k, j = i % cs.top_k; + if (cs.drop && t == 1 && j == cs.top_k - 1) return -1; + return (5 * t + j) % ne; + }; + for (int64_t e = 0; e < ne; ++e) { + offs.push_back((int64_t)sorted.size()); + for (int64_t i = 0; i < T; ++i) + if (expert_of(i) == e) sorted.push_back(i); + } + offs.push_back((int64_t)sorted.size()); + while ((int64_t)sorted.size() < T) sorted.push_back(-1); + const int64_t AR = cs.gate_up ? cs.M : T; + + /* Parameters. */ + std::vector p; + auto pi = [&](const char* k, long long v) { p.push_back(RadParam{ k, RAD_P_INT, v, 0, nullptr, 0 }); }; + auto ps = [&](const char* k, const char* v) { p.push_back(RadParam{ k, RAD_P_STR, 0, 0, v, 0 }); }; + pi("M", cs.M); pi("N", Nq[0]); pi("K", Kq[0]); pi("n_expert", ne); pi("top_k", cs.top_k); + pi("group", 128); ps("a_order", cs.gate_up ? "token" : "sorted"); ps("dtype", f.dtype); + static const char* const kN[4] = { "N", "N_1", "N_2", "N_3" }; + static const char* const kK[4] = { "K", "K_1", "K_2", "K_3" }; + for (int q = 1; q < nc; ++q) { + pi(nc == 4 ? kN[q] : "N_odd", Nq[q]); + pi(nc == 4 ? kK[q] : "K_odd", Kq[q]); + } + pi("parts", parts); + + const RadKernelInfo* kr = ref.row(op); + const RadKernelInfo* ka = lib.select(op, p.data(), (int)p.size()); + if (!kr) return fail("no row for the op in libref"); + if (!ka) return ck.own ? fail(std::string("no row of ") + lib.info->name + " admits it") : 0; + + /* The experts' planes and each library's stored bytes. */ + const RadEncoding enc = encoding(f); + const std::vector sel_c = { rad_enc_find(&enc, "codes"), rad_enc_find(&enc, "table") }; + const std::vector sel_s = f.level ? std::vector{ rad_enc_find(&enc, "scale"), + rad_enc_find(&enc, "scale.1") } + : std::vector{ rad_enc_find(&enc, "scale") }; + std::vector ex((size_t)ne); + for (int64_t e = 0; e < ne; ++e) + ex[(size_t)e] = draw(f, enc, Nq[e % nc], Kq[e % nc], 1000 + (uint64_t)(e * 7 + cs.form)); + /* Operand positions of class q's codes and scales. */ + auto opd_w = [&](int q) { return q == 0 ? 2 : 4 + 2 * q; }; + Stored st[2]; + std::vector all_bytes[2]; + for (int side = 0; side < 2; ++side) { + const RadKernelInfo* k = side ? ka : kr; + for (int q = 0; q < nc; ++q) { + uint32_t dtc = 0, dts = 0; + for (int64_t e = q; e < ne; e += nc) { + std::vector bc, bs; + std::string why; + if (!store(k, p, opd_w(q), enc, sel_c, ex[(size_t)e], &bc, &dtc, &why) || + !store(k, p, opd_w(q) + 1, enc, sel_s, ex[(size_t)e], &bs, &dts, &why)) + return fail(why); + all_bytes[side].insert(all_bytes[side].end(), bc.begin(), bc.end()); + all_bytes[side].insert(all_bytes[side].end(), bs.begin(), bs.end()); + st[side].bufs.emplace_back(); + st[side].bufs.back().assign(bc); + st[side].ptrs[2 * q].push_back(st[side].bufs.back().data()); + st[side].bufs.emplace_back(); + st[side].bufs.back().assign(bs); + st[side].ptrs[2 * q + 1].push_back(st[side].bufs.back().data()); + } + /* The declared views: codes at the weight's extents, a joined scale view too, a plain + * scale at its plane's. */ + const int64_t nq = (ne + nc - 1 - q) / nc; + const int64_t scols = f.level ? Kq[q] : (Kq[q] + f.group - 1) / f.group; + for (int v = 0; v < 2; ++v) { + RadTensor& x = st[side].t[2 * q + v]; + x = RadTensor{}; + x.data = st[side].ptrs[2 * q + v].data(); + x.dtype = v ? dts : dtc; + x.rank = 3; + x.shape[0] = nq; + x.shape[1] = Nq[q]; + x.shape[2] = v ? scols : Kq[q]; + x.stride[0] = 0; + x.stride[1] = x.shape[2]; + x.stride[2] = 1; + } + } + } + if (all_bytes[0] != all_bytes[1]) + return fail(std::string("libref and ") + lib.info->name + " store different bytes"); + + /* The activation (E4M3 codes and an f32 scale per 128), the routing, and the output. */ + const int64_t SG = (K + 127) / 128; + std::vector aq((size_t)(AR * K)), asb((size_t)(AR * SG * 4)), yb((size_t)(T * N * 2)); + for (int64_t i = 0; i < AR * K; ++i) + rad_store_f32(aq.data(), RAD_F8E4M3, i, + ((float)(mix(77, (uint64_t)i) % 2001) / 1000.0f - 1.0f) * 6.0f); + for (int64_t i = 0; i < AR * SG; ++i) + rad_store_f32(asb.data(), RAD_F32, i, 0.01f + 0.004f * (float)(i % 9)); + for (int64_t i = 0; i < T * N; ++i) rad_store_f32(yb.data(), RAD_BF16, i, 7.0f); + std::vector sb((size_t)T * 4), ob((size_t)(ne + 1) * 4); + for (int64_t i = 0; i < T; ++i) ((int32_t*)sb.data())[i] = (int32_t)sorted[(size_t)i]; + for (int64_t i = 0; i <= ne; ++i) ((int32_t*)ob.data())[i] = (int32_t)offs[(size_t)i]; + + auto tensor = [](void* d, uint32_t dt, std::vector shape) { + RadTensor t{}; + t.data = d; t.dtype = dt; t.rank = (uint32_t)shape.size(); + for (size_t i = 0; i < shape.size(); ++i) t.shape[i] = shape[i]; + rad_tensor_pack(&t); + return t; + }; + /* Guarded copies, one set a run. */ + struct Io { GBuf a, as, s, o, y; }; + auto make_io = [&](Io& io) { + io.a.assign(aq); io.as.assign(asb); io.s.assign(sb); io.o.assign(ob); io.y.assign(yb); + }; + auto launch = [&](const RadKernelInfo* k, Io& io, const RadTensor* tabs) { + std::vector t((size_t)(nc == 4 ? 13 : 9)); + t[0] = tensor(io.a.data(), RAD_F8E4M3, { AR, K }); + t[1] = tensor(io.as.data(), RAD_F32, { AR, SG }); + t[2] = tabs[0]; t[3] = tabs[1]; + t[4] = tensor(io.s.data(), RAD_I32, { T }); + t[5] = tensor(io.o.data(), RAD_I32, { ne + 1 }); + for (int q = 1; q < nc; ++q) { t[(size_t)(4 + 2 * q)] = tabs[2 * q]; t[(size_t)(5 + 2 * q)] = tabs[2 * q + 1]; } + t.back() = tensor(io.y.data(), RAD_BF16, { T, N }); + RadArgs a{}; + a.t = t.data(); a.n_t = (int)t.size(); a.p = p.data(); a.n_p = (int)p.size(); + a.world_size = 1; + return k->launch(&a, nullptr); + }; + auto intact = [&](Io& io, Stored& s, const char* who) -> std::string { + if (io.y.guard_hit()) return std::string(who) + " wrote outside the output"; + if (std::memcmp(io.a.data(), aq.data(), aq.size()) || + std::memcmp(io.as.data(), asb.data(), asb.size()) || + std::memcmp(io.s.data(), sb.data(), sb.size()) || + std::memcmp(io.o.data(), ob.data(), ob.size()) || io.a.guard_hit() || + io.as.guard_hit() || io.s.guard_hit() || io.o.guard_hit()) + return std::string(who) + " changed an input"; + for (const GBuf& g : s.bufs) + if (g.guard_hit()) return std::string(who) + " touched a stored expert's guard"; + return ""; + }; + + Io ir, ia; + make_io(ir); + make_io(ia); + int rc = launch(kr, ir, st[0].t); + if (rc < 0) return fail("libref returned " + std::to_string(rc)); + rc = launch(ka, ia, st[1].t); + if (rc < 0) return fail(std::string(lib.info->name) + " returned " + std::to_string(rc)); + for (const std::string& w : { intact(ir, st[0], "libref"), intact(ia, st[1], lib.info->name) }) + if (!w.empty()) return fail(w); + if (!std::memcmp(ir.y.data(), yb.data(), yb.size())) + return fail("libref's launch changed no output value, so the comparison is vacuous"); + double rel = 0; + std::string why; + if (!same_values(RAD_BF16, ir.y.data(), ia.y.data(), T * N, 8e-3, &rel, &why)) + return fail(std::string(lib.info->name) + " against libref: " + why); + const double rel_lib = rel; + + /* libref over the logical form: table entries as E4M3 codes, scale times level as bf16, the + * stacked form. */ + { + std::vector> lc(nc), ls(nc); + RadTensor tabs[8]; + for (int q = 0; q < nc; ++q) { + const int64_t nq = (ne + nc - 1 - q) / nc, n = Nq[q], k = Kq[q]; + const int64_t g = f.group, sg = (k + g - 1) / g; + lc[(size_t)q].assign((size_t)(nq * n * k), 0); + ls[(size_t)q].assign((size_t)(nq * n * sg * 2), 0); + for (int64_t e = q, x = 0; e < ne; e += nc, ++x) { + const Planes& w = ex[(size_t)e]; + const int ic = sel_c[0], is = sel_s[0]; + const float lv = f.level ? rad_load_f32(w.p[sel_s[1]].data(), RAD_F32, 0) : 1.0f; + const float* tab = (const float*)w.p[sel_c[1]].data(); + const int64_t rbc = rad_enc_row_bytes(enc.plane[ic].dtype, k); + const int64_t rbs = rad_enc_row_bytes(f.sdt, sg); + for (int64_t r = 0; r < n; ++r) { + for (int64_t c = 0; c < k; ++c) + rad_store_f32(lc[(size_t)q].data(), RAD_F8E4M3, (x * n + r) * k + c, + tab[(int)rad_load_f32(w.p[ic].data() + r * rbc, + enc.plane[ic].dtype, c)]); + for (int64_t c = 0; c < sg; ++c) + rad_store_f32(ls[(size_t)q].data(), RAD_BF16, (x * n + r) * sg + c, + rad_load_f32(w.p[is].data() + r * rbs, f.sdt, c) * lv); + } + } + tabs[2 * q] = tensor(lc[(size_t)q].data(), RAD_F8E4M3, { nq, n, k }); + tabs[2 * q + 1] = tensor(ls[(size_t)q].data(), RAD_BF16, { nq, n, sg }); + } + Io il; + make_io(il); + rc = launch(kr, il, tabs); + if (rc < 0) return fail("libref over the logical form returned " + std::to_string(rc)); + if (std::memcmp(il.y.data(), ir.y.data(), yb.size()) != 0) + return fail("libref over the stored form and over the logical form differ"); + } + +#ifdef AVX_CHECK_CORE_DECODER + /* The core's decoder. The rotation undone on both sides where it tiles K; otherwise both stay + * in the rotated basis, where the product is the same. */ + double rel_or = 0, rel_oa = 0; + { + bool rot = true; + for (int q = 0; q < nc; ++q) rot = rot && Kq[q] % 128 == 0; + std::vector> W((size_t)ne); + for (int64_t e = 0; e < ne; ++e) { + RadEncoding d = enc; + if (!rot) d.transform[0] = 0; + const Planes& w = ex[(size_t)e]; + const void* data[RAD_ENC_MAX_PLANES] = {}; + for (int i = 0; i < d.n_planes; ++i) data[i] = w.p[i].data(); + rad::EncodedView v; + rad::enc_view(d, w.n, w.k, data, &v); + W[(size_t)e].assign((size_t)(w.n * w.k), 0.0f); + std::string dw; + if (rad::enc_decode_rows(v, 0, w.n, W[(size_t)e].data(), &dw) != RAD_OK) + return fail("the core decoder refused expert " + std::to_string(e) + ": " + dw); + } + std::vector al((size_t)(AR * K)); + for (int64_t r = 0; r < AR; ++r) { + float* x = al.data() + r * K; + for (int64_t c = 0; c < K; ++c) + x[c] = rad_load_f32(aq.data(), RAD_F8E4M3, r * K + c) * + rad_load_f32(asb.data(), RAD_F32, r * SG + c / 128); + if (rot) + for (int64_t g = 0; g < K; g += 128) { + rad::fwht_inplace(x + g, 128); + for (int64_t c = g; c < g + 128; ++c) x[c] /= 128.0f; + } + } + std::vector yo((size_t)(T * N * 2), 0); + const int64_t fy = N / parts; + for (int64_t i = 0; i < T; ++i) { + const int64_t flat = sorted[(size_t)i]; + int64_t e = 0; + while (e + 1 < ne && offs[(size_t)(e + 1)] <= i) ++e; + const int64_t tok = flat < 0 ? -1 : (cs.gate_up ? flat / cs.top_k : i); + const int64_t n = Nq[e % nc], k = Kq[e % nc], fc = n / parts; + for (int64_t col = 0; col < N; ++col) { + const int64_t pp = col / fy, j = col % fy; + double s = 0; + if (tok >= 0 && j < fc) + for (int64_t c = 0; c < k; ++c) + s += (double)W[(size_t)e][(size_t)((pp * fc + j) * k + c)] * + (double)al[(size_t)(tok * K + c)]; + rad_store_f32(yo.data(), RAD_BF16, i * N + col, (float)s); + } + } + if (!same_values(RAD_BF16, yo.data(), ir.y.data(), T * N, 1e-2, &rel_or, &why)) + return fail("libref against the core decoder: " + why); + if (!same_values(RAD_BF16, yo.data(), ia.y.data(), T * N, 1e-2, &rel_oa, &why)) + return fail(std::string(lib.info->name) + " against the core decoder: " + why); + } +#endif + + if (ck.threads > 0 && lib.par_force) { + std::string pw; + if (!parallel_rerun(lib, ck.threads, { ia.y.data() }, { ia.y.size() }, + [&] { std::memcpy(ia.y.data(), yb.data(), yb.size()); }, + [&] { return launch(ka, ia, st[1].t); }, &pw)) + return fail(pw); + } + if (ck.verbose) { +#ifdef AVX_CHECK_CORE_DECODER + std::printf(" %-22s %-46s rel_l2=%.3e, vs decoder %.3e / %.3e ok\n", op, name, rel_lib, + rel_or, rel_oa); +#else + std::printf(" %-22s %-46s rel_l2=%.3e ok (no core decoder in this build)\n", op, name, + rel_lib); +#endif + } + return 0; +} + +/* Each library's hooks refuse the selections libref refuses, with the same code: a form's planes + * under another codebook dtype, under a dtype that is no codebook, unrotated, or at an operand + * that is neither codes nor scales; and store a single plane as it is. */ +int hook_refusals(const Check& ck) { + struct R { int form; const char* dtype; int operand; bool scale_view; bool unrotated; }; + static const R kR[] = { + { 1, "w4nl32a8h", 3, true, false }, /* scale per 64 named as per 32 */ + { 3, "w4nl64a8h", 2, false, false }, /* five-bit codes named four-bit */ + { 1, "fp8a8", 2, false, false }, /* no codebook */ + { 1, "w4nl64a8h", 2, false, true }, /* unrotated */ + { 1, "w4nl64a8h", 4, false, false }, /* sorted_tok's position */ + { 0, "w4nla8h", 3, true, false }, /* one plane: stored as it is */ + }; + int fails = 0; + for (const R& r : kR) { + const Form& f = kForms[r.form]; + RadEncoding e = encoding(f); + if (r.unrotated) e.transform[0] = 0; + std::vector sel; + if (r.scale_view) { + sel.push_back(rad_enc_find(&e, "scale")); + if (f.level) sel.push_back(rad_enc_find(&e, "scale.1")); + } else { + sel = { rad_enc_find(&e, "codes"), rad_enc_find(&e, "table") }; + } + Planes w = draw(f, e, 32, 128, 5); + std::vector t = selection(e, sel, w); + std::vector p = { RadParam{ "dtype", RAD_P_STR, 0, 0, r.dtype, 0 } }; + int got[2] = { 0, 0 }; + for (int side = 0; side < 2; ++side) { + const Lib& L = side ? *ck.lib : *ck.ref; + const RadKernelInfo* k = L.row("moe_gemm_q"); + RadLayout lay{}; + got[side] = k && k->layout ? k->layout(p.data(), 1, r.operand, &e, sel.data(), + t.data(), (int)sel.size(), &lay) + : RAD_E_UNSUPPORTED; + } + const int want = sel.size() == 1 ? RAD_E_UNSUPPORTED : RAD_E_DTYPE; + if (got[0] != want || got[1] != want) { + std::printf(" FAIL %-20s layout of %s planes as %s at operand %d\n libref %d, " + "%s %d, expected %d\n", "moe_gemm_q", f.dtype, r.dtype, r.operand, got[0], + ck.lib->info->name, got[1], want); + ++fails; + } + } + if (!fails && ck.verbose) + std::printf(" %-22s %-46s same refusals\n", "moe_gemm_q", "codebook layout hooks"); + return fails; +} + +} // namespace cb + +/* Every form at four geometries, which reach each of libavx's decodes at each level: a + * decode-sized gate_up over two classes (one or two rows an expert, the fused form); a + * prefill-sized down over four classes (about a hundred rows an expert, the panel form, a partial + * row block, a dropped slot, an odd output width); a down whose K is not whole AVX-512 decode + * chunks and ends in a partial scale group (the generic decode there, AVX2's chunks); and a gate_up + * whose K is whole chunks but not whole 128-code lines (AVX-512's chunk decode). Returns the + * failures, having printed them, and counts the cases run. */ +int codebook_cases(const Check& ck, int* run) { + static const cb::Case kCases[] = { + { "gate_up, 2 classes 128 / 96 wide, M 5", 0, 2, true, 5, 2, 8, { 128, 96, 0, 0 }, 256, + false }, + { "down, 4 classes 256 / 128 / 128 / 128, M 130", 0, 4, false, 130, 3, 4, + { 256, 128, 128, 128 }, 97, true }, + { "down, 2 classes K 208 / 144, N 61, M 9", 0, 2, false, 9, 2, 6, { 208, 144, 0, 0 }, 61, + false }, + { "gate_up, 2 classes 64 / 32 wide, K 160, M 3", 0, 2, true, 3, 2, 4, { 64, 32, 0, 0 }, + 160, false }, + }; + int fails = 0; + for (int fm = 0; fm < 4; ++fm) + for (cb::Case c : kCases) { + c.form = fm; + const char* op = c.ncls == 4 ? "moe_gemm_q_mod4" : "moe_gemm_q"; + if (!ck.only_op.empty() && ck.only_op != op) continue; + ++*run; + fails += cb::run_case(ck, c); + } + if (ck.only_op.empty() || ck.only_op == "moe_gemm_q") { + ++*run; + fails += cb::hook_refusals(ck) ? 1 : 0; + } + return fails; +} + +/* ================================================================== the image generator */ +/* Forms libref's descriptions do not draw: several entries and an empty one, a modulation row as a + * column slice of the shared [n_seq, 4D] projection, the entry flags and pairings the sampler + * reads, attention over entries of different lengths and prefixes with a missing block and + * column-sliced projections, images whose rows are not back to back, and the signed gather libref + * declines to describe. The sampler, the gate and the copies are held to zero error: they are + * libref's arithmetic bit for bit. */ +void gen_cases(std::vector& hs) { + const auto zero = [](int64_t) { return 0.0f; }; + for (const uint32_t dt : { (uint32_t)RAD_F32, (uint32_t)RAD_BF16 }) { + const char* dn = dt == RAD_F32 ? "f32" : "bf16"; + const std::string sfx = std::string(", ") + dn; + const double norm_tol = dt == RAD_F32 ? 1e-5 : 6e-3; + + /* ---- gather_rows2: both sources, and rows past either ------------------------------ */ + { + Hand h(("a and b rows, past both ends" + sfx).c_str(), "gather_rows2", 0.0); + h.dense(dt, { 5, 67 }, hfill(201)) + .dense(dt, { 3, 67 }, hfill(202)) + .idx({ 0, -1, 4, -3, 5, -4, 2 }) + .dense(dt, { 7, 67 }, hfill(203), true) + .pi("M", 7).pi("n", 67).ps("dtype", dn); + hs.push_back(std::move(h)); + } + + /* ---- the DiT's norms: three entries (one empty), the modulation at a 4D pitch ------ */ + { + const int64_t R = 11, D = 160, W = 4 * D; + Hand h(("three entries, one empty, s at a 4D pitch" + sfx).c_str(), "ln_mod", norm_tol); + h.dense(dt, { R, D }, hfill(210, 2.0f)) + .view(dt, { 3, D }, { W, 1 }, 3 * W, hfill(211, 0.5f)) + .idx({ 0, 4, 4, R }) + .dense(dt, { R, D }, zero, true) + .pi("M", R).pi("n", D).pf("eps", 1e-6).ps("dtype", dn); + hs.push_back(std::move(h)); + + Hand g(("three entries, one empty, g at a 4D pitch" + sfx).c_str(), "gate_add", 0.0); + g.dense(dt, { R, D }, hfill(212)) + .view(dt, { 3, D }, { W, 1 }, 3 * W, hfill(213)) + .idx({ 0, 4, 4, R }) + .dense(dt, { R, D }, hfill(214), true) + .pi("M", R).pi("n", D).ps("dtype", dn); + hs.push_back(std::move(g)); + + for (const bool gated : { true, false }) { + Hand q((std::string(gated ? "gated" : "the first block's, no branch") + + ", three entries, 4D pitch" + sfx).c_str(), "ln_mod_quant_fp8", 1e-2); + if (gated) { + q.dense(dt, { R, D }, hfill(215)) + .view(dt, { 3, D }, { W, 1 }, 3 * W, hfill(216)); + } else { + q.none().none(); + } + q.view(dt, { 3, D }, { W, 1 }, 3 * W, hfill(217, 0.5f)) + .idx({ 0, 4, 4, R }) + .dense(dt, { R, D }, hfill(218, 2.0f), true) + .dense(RAD_F8E4M3, { R, D }, zero, true) + .dense(RAD_F32, { R, D / 32 }, zero, true) + .dense(RAD_BF16, { R, D }, zero, true) + .pi("M", R).pi("n", D).pf("eps", 1e-6).pi("group", 32) + .pi("gated", gated ? 1 : 0).ps("dtype", dn); + hs.push_back(std::move(q)); + } + } + + /* ---- the sampler's state: seeds, flags, pairs and lanes ----------------------------- */ + { + /* Three entries over lanes 2, 0 and 3 of four ten-row lanes, two of them first steps, + * seven channels so a Philox block of four straddles rows. */ + static const uint32_t kSeeds[6] = { 0x9e3779b9u, 1u, 7u, 0u, 0xdeadbeefu, 0x80000001u }; + Hand h(("two first steps of three, n 7" + sfx).c_str(), "randn_lanes", 0.0); + h.idx({ 1, 0, 5 }) + .raw(RAD_U32, { 6 }, kSeeds) + .idx({ 2, 0, 3 }) + .idx({ 0, 4, 6, 13 }) + .dense(dt, { 40, 7 }, hfill(220), true) + .pi("M", 13).pi("n", 7).pi("stride", 10).ps("dtype", dn); + hs.push_back(std::move(h)); + } + for (const int64_t n : { 64, 37 }) { + /* Entry 0 guided against entry 1 (a negative conditioning: pair -2, its lane left as it + * is), with a preview and a repaint; entry 2 unguided with a repaint; entry 3 + * unguided, neither. */ + static const uint32_t kSeeds[8] = { 3u, 0u, 4u, 0u, 5u, 9u, 0xfffffffeu, 2u }; + Hand h(("guided, parked, repainted, previewed, n " + std::to_string(n) + sfx).c_str(), + "flow_euler", 0.0); + h.dense(dt, { 17, n }, hfill(221)) + .dense(RAD_F32, { 4 }, [](int64_t i) { return 0.8f - 0.1f * (float)i; }) + .dense(RAD_F32, { 4 }, [](int64_t i) { return 0.55f - 0.1f * (float)i; }) + .dense(RAD_F32, { 4 }, [](int64_t) { return 3.5f; }) + .idx({ 1, -2, -1, -1 }) + .idx({ 0, 1, 2, 3 }) + .idx({ 6, 0, 2, 0 }) + .raw(RAD_U32, { 8 }, kSeeds) + .idx({ 0, 5, 10, 13, 17 }) + .dense(dt, { 24, n }, hfill(222)) + .dense(RAD_F32, { 24 }, [](int64_t i) { return 0.25f * (float)(i % 5); }) + .dense(dt, { 24, n }, hfill(223), true) + .dense(dt, { 24, n }, hfill(224), true) + .pi("M", 17).pi("n", n).pi("stride", 6).ps("dtype", dn); + hs.push_back(std::move(h)); + } + { + Hand h(("a mask column into three lanes" + sfx).c_str(), "lane_store", 0.0); + h.dense(dt, { 9, 1 }, hfill(225)) + .idx({ 3, 0, 1 }) + .dense(dt, { 40, 1 }, hfill(226), true) + .pi("M", 9).pi("n", 1).pi("stride", 10).ps("dtype", dn); + hs.push_back(std::move(h)); + } + + /* ---- the decoder ---------------------------------------------------------------------- */ + { + /* Pixels past [-1, 1], NaN, and ties at the byte (0 maps to 127.5). */ + static const float kPx[12] = { -2.0f, -1.0f, -0.999f, 0.0f, 0.5f, 1.0f, 1.5f, NAN, + 0.25f, -0.25f, 0.998f, -INFINITY }; + Hand h(("clamps, NaN and ties" + sfx).c_str(), "to_rgba8", 0.0); + h.dense(dt, { 3, 4 }, [](int64_t i) { return kPx[i]; }) + .dense(RAD_U8, { 3, 4 }, zero, true) + .pi("M", 3).pi("n", 4).ps("dtype", dn); + hs.push_back(std::move(h)); + } + for (const int64_t cout : { 52, 4 }) { + /* Output rows five elements apart from the next (one band a row), and a 1 x 1 layer + * over input rows three apart (patches, not the input read in place). */ + const int64_t H = 6, Wd = 7, cin = 20, yr = Wd * cout + 5, xr = Wd * cin + 3; + Hand h(("3 x 3, output rows at a wider pitch, cout " + std::to_string(cout) + sfx) + .c_str(), "conv2d_nhwc", norm_tol); + h.dense(dt, { H, Wd * cin }, hfill(230)) + .dense(dt, { cout, cin, 3, 3 }, hfill(231, 0.1f)) + .dense(dt, { cout }, hfill(232, 0.1f)) + .view(dt, { H, Wd * cout }, { yr, 1 }, H * yr, hfill(233), true) + .pi("M", H * Wd).pi("cin", cin).pi("cout", cout).pi("k", 3).pi("stride", 1) + .ps("pad", "same").pi("up", 1).ps("dtype", dn); + hs.push_back(std::move(h)); + + Hand g(("1 x 1, input rows at a wider pitch, cout " + std::to_string(cout) + sfx) + .c_str(), "conv2d_nhwc", norm_tol); + g.view(dt, { H, Wd * cin }, { xr, 1 }, H * xr, hfill(234)) + .dense(dt, { cout, cin, 1, 1 }, hfill(235, 0.2f)) + .dense(dt, { cout }, hfill(236, 0.1f)) + .dense(dt, { H, Wd * cout }, zero, true) + .pi("M", H * Wd).pi("cin", cin).pi("cout", cout).pi("k", 1).pi("stride", 1) + .ps("pad", "same").pi("up", 1).ps("dtype", dn); + hs.push_back(std::move(g)); + } + { + /* An odd 13-column picture downsampled by the stride-2 `down` form, and upsampled. */ + const int64_t cin = 12, cout = 52; + Hand h(("stride 2 down to 13 x 13" + sfx).c_str(), "conv2d_nhwc", norm_tol); + h.dense(dt, { 26, 26 * cin }, hfill(237)) + .dense(dt, { cout, cin, 3, 3 }, hfill(238, 0.1f)) + .dense(dt, { cout }, hfill(239, 0.1f)) + .dense(dt, { 13, 13 * cout }, zero, true) + .pi("M", 169).pi("cin", cin).pi("cout", cout).pi("k", 3).pi("stride", 2) + .ps("pad", "down").pi("up", 1).ps("dtype", dn); + hs.push_back(std::move(h)); + + Hand g(("upsampled 13 x 13 to 26 x 26" + sfx).c_str(), "conv2d_nhwc", norm_tol); + g.dense(dt, { 13, 13 * cin }, hfill(240)) + .dense(dt, { cout, cin, 3, 3 }, hfill(241, 0.1f)) + .dense(dt, { cout }, hfill(242, 0.1f)) + .dense(dt, { 26, 26 * cout }, zero, true) + .pi("M", 676).pi("cin", cin).pi("cout", cout).pi("k", 3).pi("stride", 1) + .ps("pad", "same").pi("up", 2).ps("dtype", dn); + hs.push_back(std::move(g)); + } + for (const int64_t ft : { 1, 2 }) { + Hand h(("576 -> 288 pattern, ft " + std::to_string(ft) + sfx).c_str(), "d2s_add", 0.0); + h.dense(dt, { 3, 5 * 48 }, hfill(243)) + .dense(dt, { 6, 10 * 24 }, hfill(244), true) + .pi("M", 60).pi("cin", 48).pi("cout", 24).pi("ft", ft).ps("dtype", dn); + hs.push_back(std::move(h)); + + Hand g(("96 -> 192 pattern, ft " + std::to_string(ft) + sfx).c_str(), "s2d_avg_add", + 0.0); + g.dense(dt, { 6, 10 * 12 }, hfill(245)) + .dense(dt, { 3, 5 * 24 }, hfill(246), true) + .pi("M", 15).pi("cin", 12).pi("cout", 24).pi("ft", ft).ps("dtype", dn); + hs.push_back(std::move(g)); + } + + /* ---- the rotaries over three position components ---------------------------------- */ + { + const int64_t M = 9, hd = 64, nh = 2, nkv = 2, W = (nh + 2 * nkv) * hd; + auto pos = [M](int64_t i) { + const int64_t c = i / M, m = i % M; + return (float)(c == 0 ? 3 : c == 1 ? m / 3 : m % 3); + }; + Hand h(("the DiT's 8 12 12 adjacent pairs over (frame, row, column)" + sfx).c_str(), + "qk_norm_rope", norm_tol); + h.dense(dt, { M, W }, hfill(247), true) + .dense(RAD_I32, { 3, M }, pos) + .dense(dt, { hd }, hfill(248, 0.1f)) + .dense(dt, { hd }, hfill(249, 0.1f)) + .pi("M", M).pi("head_dim", hd).pi("n_head", nh).pi("n_head_kv", nkv) + .pf("theta", 10000.0).pf("eps", 1e-6).ps("mode", "gptj_blocks") + .pi("rotary_dim", hd).ps("sections", "8 12 12"); + hs.push_back(std::move(h)); + + Hand g(("Qwen3-VL's interleaved M-RoPE over three components" + sfx).c_str(), + "qk_norm_rope", norm_tol); + g.dense(dt, { M, W }, hfill(250), true) + .dense(RAD_I32, { 3, M }, pos) + .dense(dt, { hd }, hfill(251, 0.1f)) + .dense(dt, { hd }, hfill(252, 0.1f)) + .pi("M", M).pi("head_dim", hd).pi("n_head", nh).pi("n_head_kv", nkv) + .pf("theta", 5e6).pf("eps", 1e-6).ps("mode", "imrope").pi("rotary_dim", hd) + .ps("sections", "12 10 10"); + hs.push_back(std::move(g)); + } + + /* ---- attention over entries of different prefixes ---------------------------------- * + * Two entries of 37 and 8 rows (one query block and part of a second, and a short one) + * against prefixes of 50 and 20 keys; entry 0's second block is missing (-1: zero keys + * that still take their softmax share). q, k, v and out are column slices of a fused + * projection, rows `W` apart. */ + for (const int64_t hd : { 64, 40 }) + for (const bool i8 : { false, true }) + for (const int causal : { 0, 1 }) { + const int64_t T = 45, kvh = 2, gqa = 2, qh = 4, BS = 16, NB = 6; + const int64_t W = (qh + 2 * kvh) * hd; + char nm[128]; + std::snprintf(nm, sizeof nm, "2 entries, prefixes 50/20, a missing block, " + "hd %lld%s%s%s", (long long)hd, i8 ? ", i8" : "", + causal ? ", causal" : "", sfx.c_str()); + Hand h(nm, "attn_prefix_self", dt == RAD_F32 ? 1e-4 : 2e-2); + h.view(dt, { T, qh * hd }, { W, 1 }, T * W, hfill(260)) + .view(dt, { T, kvh * hd }, { W, 1 }, T * W, hfill(261)) + .view(dt, { T, kvh * hd }, { W, 1 }, T * W, hfill(262)) + .dense(dt, { NB, kvh, BS, 2 * hd }, hfill(263)) + .dense(RAD_I32, { 2, 4 }, [](int64_t i) { + static const int32_t kBt[8] = { 0, -1, 2, 3, 4, 5, 1, -1 }; + return (float)kBt[i]; + }) + .idx({ 50, 20 }) + .idx({ 0, 37, T }) + .none().none(); + if (i8) { + h.dense(RAD_I8, { T, kvh * hd }, [](int64_t i) { + return (float)((int)((i * 37) % 255) - 127); + }) + .dense(RAD_F32, { T, kvh }, [](int64_t i) { + return 0.004f + 0.0005f * (float)(i % 7); + }); + } else { + h.none().none(); + } + h.view(dt, { T, qh * hd }, { W, 1 }, T * W, zero, true) + .pi("q_len", T).pi("head_dim", hd).pi("gqa", gqa).pi("block_size", BS) + .pi("causal", causal).ps("q_dtype", dn).ps("kv_dtype", dn) + .pf("scale", 1.0 / std::sqrt((double)hd)).ps("qk", i8 ? "i8" : "bf16"); + hs.push_back(std::move(h)); + } + { + /* One segment of a longer sequence: cu is its two bounding offsets, rows [5, 30), and + * the rows outside it stay as they were. */ + const int64_t T = 30, kvh = 1, hd = 64, BS = 16; + Hand h(("a segment at rows 5..30, causal" + sfx).c_str(), "attn_prefix_self", + dt == RAD_F32 ? 1e-4 : 2e-2); + h.dense(dt, { T, kvh * hd }, hfill(264)) + .dense(dt, { T, kvh * hd }, hfill(265)) + .dense(dt, { T, kvh * hd }, hfill(266)) + .dense(dt, { 3, kvh, BS, 2 * hd }, hfill(267)) + .dense(RAD_I32, { 1, 3 }, [](int64_t i) { return (float)(2 - i); }) + .idx({ 40 }) + .idx({ 5, T }) + .none().none().none().none() + .dense(dt, { T, kvh * hd }, hfill(268), true) + .pi("q_len", T).pi("head_dim", hd).pi("gqa", 1).pi("block_size", BS) + .pi("causal", 1).ps("q_dtype", dn).ps("kv_dtype", dn).pf("scale", 0.125); + hs.push_back(std::move(h)); + } + } + + /* ---- an fp8 cache read with per-(entry, kv head) descales ------------------------------ */ + { + const int64_t T = 20, kvh = 2, gqa = 1, hd = 64, BS = 16; + Hand h("fp8 cache, k and v descales, bf16 rows", "attn_prefix_self", 2e-2); + h.dense(RAD_BF16, { T, kvh * gqa * hd }, hfill(270)) + .dense(RAD_BF16, { T, kvh * hd }, hfill(271)) + .dense(RAD_BF16, { T, kvh * hd }, hfill(272)) + .dense(RAD_F8E4M3, { 4, kvh, BS, 2 * hd }, hfill(273, 8.0f)) + .dense(RAD_I32, { 2, 2 }, [](int64_t i) { return (float)i; }) + .idx({ 30, 17 }) + .idx({ 0, 12, T }) + .dense(RAD_F32, { 4 }, [](int64_t i) { return 0.1f + 0.05f * (float)i; }) + .dense(RAD_F32, { 4 }, [](int64_t i) { return 0.2f - 0.03f * (float)i; }) + .none().none() + .dense(RAD_BF16, { T, kvh * gqa * hd }, zero, true) + .pi("q_len", T).pi("head_dim", hd).pi("gqa", gqa).pi("block_size", BS).pi("causal", 0) + .ps("q_dtype", "bf16").ps("kv_dtype", "fp8_e4m3").pf("scale", 0.125); + hs.push_back(std::move(h)); + } + + /* ---- scatter_add_rows: a repeated destination adds in index order ----------------------- */ + { + Hand h("a destination three times, one skip", "scatter_add_rows", 0.0); + h.dense(RAD_BF16, { 5, 67 }, hfill(280)) + .idx({ 2, -1, 2, 0, 2 }) + .dense(RAD_BF16, { 4, 67 }, hfill(281), true) + .pi("M", 5).pi("n", 67).ps("dtype", "bf16"); + hs.push_back(std::move(h)); + + Hand r("an index past x's rows is refused", "scatter_add_rows", 0.0); + r.dense(RAD_F32, { 2, 67 }, hfill(282)) + .idx({ 1, 7 }) + .dense(RAD_F32, { 4, 67 }, hfill(283), true) + .pi("M", 2).pi("n", 67).ps("dtype", "f32") + .refuses(RAD_E_INVAL); + hs.push_back(std::move(r)); + } +} + +/* ================================================================== the QSA indexer and DFlash2 + * What libref's descriptions cannot draw: cu not starting at 0 and rows no sequence holds, -1 + * pages, the score plane as a column slice of the declared width, the block keys in the KV + * cache's rank, ring wrap in the tail and the work list, a slot-less sequence, M-RoPE positions, + * and the delta and base views the drafter issues. Outputs start as a sentinel, so an element one + * side writes and the other leaves shows as a difference. */ +void qsa_cases(std::vector& hs) { + const auto sent = [](int64_t) { return 7.0f; }; + + /* ---- qsa_score ----------------------------------------------------------------------- */ + { + const int64_t n = 128, H = 4, S = 3, M = 12, P = 200, W = 64, live = 50, pitch = 80; + Hand h("cu from 2, unheld rows, -1 pages, a dead sequence, a padded plane, rank-5 keys", + "qsa_score", 6e-3); + h.dense(RAD_BF16, { M, H * n }, hfill(201)) + .dense(RAD_BF16, { P, 2, 4, 1, 16 }, hfill(202)) + .dense(RAD_I32, { S, W }, [=](int64_t i) { + return (i / W == 2 || i % 7 == 3) ? -1.0f : (float)((i * 37 + 11) % P); + }) + .idx({ 2, 5, 6, 10 }) + .idx({ 37, 50, 17 }) + .view(RAD_F32, { M, live }, { pitch, 1 }, M * pitch, sent, true) + .pi("M", M).pi("n", n).pi("heads", H).pi("blocks", W).pi("seqs", S).ps("dtype", "bf16"); + hs.push_back(std::move(h)); + } + { + const int64_t n = 40, H = 2, M = 19, P = 70; + Hand h("19 rows of one sequence (three tiles), n 40, q a column slice", "qsa_score", 1e-5); + h.view(RAD_F32, { M, H * n }, { (H + 1) * n, 1 }, M * (H + 1) * n, hfill(203)) + .dense(RAD_F32, { P, n }, hfill(204)) + .dense(RAD_I32, { 1, P }, [=](int64_t i) { return (float)((i * 23 + 5) % P); }) + .idx({ 0, M }) + .idx({ P }) + .dense(RAD_F32, { M, P }, sent, true) + .pi("M", M).pi("n", n).pi("heads", H).pi("blocks", P).pi("seqs", 1).ps("dtype", "f32"); + hs.push_back(std::move(h)); + } + { + Hand h("a page id past the key store is refused before any write", "qsa_score", 0.0); + h.dense(RAD_F32, { 2, 32 }, hfill(205)) + .dense(RAD_F32, { 8, 16 }, hfill(206)) + .dense(RAD_I32, { 1, 4 }, [](int64_t i) { return i == 3 ? 8.0f : (float)i; }) + .idx({ 0, 2 }) + .idx({ 4 }) + .dense(RAD_F32, { 2, 4 }, sent, true) + .pi("M", 2).pi("n", 16).pi("heads", 2).pi("blocks", 4).pi("seqs", 1).ps("dtype", "f32") + .refuses(RAD_E_INVAL); + hs.push_back(std::move(h)); + } + + /* ---- qsa_select ---------------------------------------------------------------------- */ + { + /* libr4d's eight rows (r4d_selftest.cpp: qsa_select_few_live_case), which pinned its + * selection to libref's rule: 100, 400, 200 and 512 live keys under topk 512; 2000 live + * of which most score zero; every block dead; 300 blocks with -1 pages; 8000 live. Each + * row is mid-block, so its partial page is considered. The expected table is the rule + * itself, computed here, so both libraries are held to it and not only to each other. */ + const int64_t S = 8, M = S, nb = 9000, topk = 512, ratio = 4, pages = 1 << 20; + const int64_t nrow[S] = { 8000, 8000, 8000, 8000, 2000, 8000, 300, 8000 }; + std::vector sc((size_t)(M * nb), -INFINITY); + std::vector bt((size_t)(S * nb), -1), nc((size_t)S), pos((size_t)M), + cuh((size_t)(S + 1)); + uint64_t x = 0x9E3779B97F4A7C15ull; + auto rnd = [&]() { x ^= x << 13; x ^= x >> 7; x ^= x << 17; return x; }; + for (int64_t s = 0; s < S; ++s) { + const int64_t n = nrow[s]; + nc[(size_t)s] = (int32_t)n; + cuh[(size_t)s] = (int32_t)s; + pos[(size_t)s] = (int32_t)(n * ratio + (s % 3)); + for (int64_t b = 0; b < n; ++b) { + float* v = &sc[(size_t)(s * nb + b)]; + int32_t* pg = &bt[(size_t)(s * nb + b)]; + const uint64_t u = rnd(); + const float cont = (float)(u % 1000003) / 1000.0f + 0.001f; + *pg = (int32_t)(u % pages); + switch (s) { + case 0: if (b % 80 != 3) *pg = -1; *v = cont; break; + case 1: if (b % 20 != 7) *pg = -1; + *v = (b / 20) % 4 == 0 ? cont + : (b / 20) % 3 == 0 ? -2.5f : (b / 20) % 3 == 1 ? -0.0f : 0.0f; + break; + case 2: *v = (b % 40 == 1) ? cont : -INFINITY; break; + case 3: if (b % 15 != 2 || b >= 15 * 512) *pg = -1; + *v = (b % 45 == 2) ? 0.0f : cont; break; + case 4: *v = (b % 7 == 0) ? cont : (b % 2 ? 0.0f : -0.0f); break; + case 5: *pg = -1; *v = cont; break; + case 6: if (b % 9 == 4) *pg = -1; *v = (float)(u % 13) * 0.5f; break; + default: *v = cont; break; + } + } + bt[(size_t)(s * nb + n)] = (s % 2 == 0) ? (int32_t)(rnd() % pages) : -1; + } + cuh[(size_t)S] = (int32_t)M; + std::vector want((size_t)(M * (topk + 1)), -1); + for (int64_t m = 0; m < M; ++m) { + const int64_t n = nrow[m]; + std::vector live; + std::vector val((size_t)n, 0.0f); + for (int64_t b = 0; b < n; ++b) { + const float v = sc[(size_t)(m * nb + b)]; + if (bt[(size_t)(m * nb + b)] < 0 || !(v > -1e30f)) continue; + val[(size_t)b] = v > 0.0f ? v : 0.0f; + live.push_back(b); + } + std::vector take; + if ((int64_t)live.size() <= topk) { + take = live; + } else { + std::vector ord; + for (int64_t b : live) ord.push_back(val[(size_t)b]); + std::nth_element(ord.begin(), ord.begin() + (topk - 1), ord.end(), + [](float l, float r) { return l > r; }); + const float thr = ord[(size_t)(topk - 1)]; + for (int64_t b : live) if (val[(size_t)b] > thr) take.push_back(b); + for (int64_t b : live) + if ((int64_t)take.size() < topk && val[(size_t)b] == thr) take.push_back(b); + } + int64_t* row = &want[(size_t)(m * (topk + 1))]; + int64_t out = 0; + for (int64_t b : take) row[out++] = bt[(size_t)(m * nb + b)]; + const int32_t part = (pos[(size_t)m] + 1) % ratio != 0 ? bt[(size_t)(m * nb + n)] : -1; + if (part >= 0) row[out++] = part; + } + Hand h("libr4d's eight few-live rows, against the rule", "qsa_select", 0.0); + h.raw(RAD_F32, { M, nb }, sc.data()) + .raw(RAD_I32, { S, nb }, bt.data()) + .raw(RAD_I32, { S }, nc.data()) + .raw(RAD_I32, { M }, pos.data()) + .raw(RAD_I32, { S + 1 }, cuh.data()) + .dense(RAD_I32, { M, topk + 1 }, sent, true) + .dense(RAD_I32, { M }, sent, true) + .dense(RAD_I32, { M }, sent, true) + .pi("M", M).pi("blocks", nb).pi("topk", topk).pi("ratio", ratio).pi("seqs", S) + .expect(5, std::move(want)); + hs.push_back(std::move(h)); + } + { + /* Rows 0 and 5 are in no span and read sequence 0. Scores repeat 1.0 (ties at the + * threshold), and carry NaN and -inf (dead), +inf and -0 (live). */ + const int64_t S = 2, M = 6, live = 40, pitch = 56, W = 48, topk = 8, ratio = 4; + Hand h("cu from 1, unheld rows, a column slice, ties, NaN, inf and -0", "qsa_select", 0.0); + h.view(RAD_F32, { M, live }, { pitch, 1 }, M * pitch, [=](int64_t i) { + switch ((i % pitch + i / pitch) % 9) { + case 0: case 1: case 7: return 1.0f; + case 2: return NAN; + case 3: return INFINITY; + case 4: return -0.0f; + case 5: return -INFINITY; + case 6: return -1.5f; + default: return 0.25f * (float)(i % 5); + } + }) + .dense(RAD_I32, { S, W }, [](int64_t i) { + return i % 11 == 4 ? -1.0f : (float)((i * 13 + 3) % 500); + }) + .idx({ 40, 25 }) + .idx({ 160, 98, 99, 161, 40, 7 }) + .idx({ 1, 3, 5 }) + .dense(RAD_I32, { M, topk + 1 }, sent, true) + .dense(RAD_I32, { M }, sent, true) + .dense(RAD_I32, { M }, sent, true) + .pi("M", M).pi("blocks", W).pi("topk", topk).pi("ratio", ratio).pi("seqs", S); + hs.push_back(std::move(h)); + } + { + /* Row 0: three keys above a threshold 1997 blocks share. Row 1: the same history to a + * mid-block position, so the partial page follows. Row 2: every odd block dead by score + * and the rest scoring zero, so the threshold is the smallest live key, in the bin dead + * keys share. */ + const int64_t nb = 2000, M = 3, topk = 100, ratio = 4; + Hand h("2000 blocks: 1997-way ties, a partial page, live zeros beside dead keys", + "qsa_select", 0.0); + h.dense(RAD_F32, { M, nb }, [=](int64_t i) { + const int64_t m = i / nb, b = i % nb; + if (m == 2) return b % 2 ? -INFINITY : -1.0f; + return (b == 17 || b == 900 || b == 1999) ? 3.0f + (float)b : 0.5f; + }) + .dense(RAD_I32, { 1, nb }, [](int64_t i) { return (float)(3 * i + 1); }) + .idx({ nb }) + .idx({ 4 * nb + 3, 4001, 4 * nb + 3 }) + .idx({ 0, M }) + .dense(RAD_I32, { M, topk + 1 }, sent, true) + .dense(RAD_I32, { M }, sent, true) + .dense(RAD_I32, { M }, sent, true) + .pi("M", M).pi("blocks", nb).pi("topk", topk).pi("ratio", ratio).pi("seqs", 1); + hs.push_back(std::move(h)); + } + { + Hand h("a negative block count is refused before any write", "qsa_select", 0.0); + h.dense(RAD_F32, { 1, 4 }, hfill(207)) + .dense(RAD_I32, { 1, 4 }, [](int64_t i) { return (float)i; }) + .idx({ -1 }) + .idx({ 9 }) + .idx({ 0, 1 }) + .dense(RAD_I32, { 1, 3 }, sent, true) + .dense(RAD_I32, { 1 }, sent, true) + .dense(RAD_I32, { 1 }, sent, true) + .pi("M", 1).pi("blocks", 4).pi("topk", 2).pi("ratio", 4).pi("seqs", 1) + .refuses(RAD_E_INVAL); + hs.push_back(std::move(h)); + } + + /* ---- qsa_tail_store ------------------------------------------------------------------ */ + { + /* Sequence 0 is a 12-token chunk at positions 30..40 and 42: only its last 7 rows write, + * so the ring wraps, the last row overwrites ring row 0, and the row before the seven + * (position 34, ring row 6) must not write. Sequence 1 has no slot. Rows 0..2 and 19 are + * in no span. */ + const int64_t n = 32, ratio = 4, ring = 7, S = 3, T = 20, slots = 4; + std::vector pos((size_t)T); + for (int64_t t = 0; t < T; ++t) + pos[(size_t)t] = t < 3 ? 5 : t < 14 ? 30 + (t - 3) : t == 14 ? 42 : t == 15 ? 7 + : t < 19 ? 100 + (t - 16) : 5; + Hand h("a chunk past the ring, cu from 3, a slot-less sequence, sidx at pitch 2, k a " + "column slice", "qsa_tail_store", 0.0); + h.view(RAD_BF16, { T, n }, { 5 * n, 1 }, T * 5 * n, hfill(210)) + .idx(pos) + .idx({ 3, 15, 16, 19 }) + .dense(RAD_BF16, { slots, 1, ring, n }, hfill(211), true) + .dense(RAD_I32, { S, 2 }, [](int64_t i) { + static const float v[6] = { 2, 3, -1, 0, 0, 1 }; + return v[i]; + }) + .pi("M", T).pi("n", n).pi("ratio", ratio).pi("ring", ring).pi("seqs", S) + .ps("dtype", "bf16"); + hs.push_back(std::move(h)); + } + + /* ---- qsa_work ------------------------------------------------------------------------ */ + /* Sequence 0 (rows 2..7, positions 6..11) completes blocks 1 and 2, block 1 straddling the + * chunk start (positions 4 and 5 from the tail); sequence 1 (row 8, position 3) completes block + * 0 but has no slot; sequence 2 (rows 9..12, positions 13..16) completes block 3, position 12 + * from ring row 5. Four items for eight slots. */ + for (const bool mrope : { false, true }) { + const int64_t n = 32, ratio = 4, ring = 7, S = 3, T = 14, slots = 3, mw = 8; + std::vector pos((size_t)T, 0); + for (int64_t t = 2; t < 8; ++t) pos[(size_t)t] = 4 + t; + pos[8] = 3; + for (int64_t t = 9; t < 13; ++t) pos[(size_t)t] = 4 + t; + Hand h(mrope ? "straddling blocks, a slot-less sequence, items past the count, M-RoPE" + : "straddling blocks, a slot-less sequence, items past the count", + "qsa_work", 0.0); + h.view(RAD_BF16, { T, n }, { 5 * n, 1 }, T * 5 * n, hfill(212)) + .idx(pos) + .idx({ 2, 8, 9, 13 }) + .dense(RAD_BF16, { slots, 1, ring, n }, hfill(213)) + .dense(RAD_I32, { S, 2 }, [](int64_t i) { + static const float v[6] = { 1, 2, -1, 0, 0, 2 }; + return v[i]; + }) + .dense(RAD_I32, { S, 6 }, [](int64_t i) { return (float)(100 + 3 * i); }); + if (mrope) + h.dense(RAD_I32, { 3, T }, [=](int64_t i) { + return (float)(1000 * (i / T) + 2 * (i % T) + 7); + }); + else + h.none(); + h.dense(RAD_BF16, { mw * ratio, n }, sent, true) + .dense(RAD_I32, { mw }, sent, true); + if (mrope) h.dense(RAD_I32, { mw, 3 }, sent, true); + else h.dense(RAD_I32, { mw }, sent, true); + h.dense(RAD_I32, { S }, sent, true) + .pi("M", T).pi("n", n).pi("ratio", ratio).pi("ring", ring).pi("seqs", S).pi("work", mw) + .ps("dtype", "bf16"); + hs.push_back(std::move(h)); + } + { + /* Three blocks complete and `work` admits two: the list stops at the bound and nc still + * counts all three. */ + const int64_t n = 16, ratio = 4, ring = 4, T = 12, mw = 2; + std::vector pos((size_t)T); + for (int64_t t = 0; t < T; ++t) pos[(size_t)t] = t; + Hand h("more blocks complete than `work` admits", "qsa_work", 0.0); + h.dense(RAD_F32, { T, n }, hfill(214)) + .idx(pos) + .idx({ 0, T }) + .dense(RAD_F32, { 1, 1, ring, n }, hfill(215)) + .idx({ 0 }) + .dense(RAD_I32, { 1, 4 }, [](int64_t i) { return (float)(9 - i); }) + .none() + .dense(RAD_F32, { mw * ratio, n }, sent, true) + .dense(RAD_I32, { mw }, sent, true) + .dense(RAD_I32, { mw }, sent, true) + .dense(RAD_I32, { 1 }, sent, true) + .pi("M", T).pi("n", n).pi("ratio", ratio).pi("ring", ring).pi("seqs", 1).pi("work", mw) + .ps("dtype", "f32"); + hs.push_back(std::move(h)); + } + + /* ---- dflash_conv --------------------------------------------------------------------- */ + { + /* Groups of 24 take the broadcast path at 8 lanes and the expanded one at 16. */ + const int64_t T = 9, H = 96, taps = 2, G = 24, NG = 4, bsz = 4; + Hand h("delta [T, taps, NG] at padded strides, a rank-3 base, x at a row pitch, groups " + "of 24", "dflash_conv", 6e-3); + h.view(RAD_BF16, { T, H }, { H + 8, 1 }, T * (H + 8), hfill(220)) + .view(RAD_BF16, { T, taps, NG }, { 16, 6, 1 }, T * 16, hfill(221)) + .dense(RAD_BF16, { 1, taps, H }, hfill(222)) + .dense(RAD_BF16, { T, H }, sent, true) + .pi("T", T).pi("hidden_size", H).pi("taps", taps).pi("group_size", G).pi("NG", NG) + .pi("block_size", bsz).ps("dtype", "bf16"); + hs.push_back(std::move(h)); + } + { + Hand h("zero rows are refused", "dflash_conv", 0.0); + h.dense(RAD_F32, { 0, 32 }, sent) + .dense(RAD_F32, { 0, 8 }, sent) + .dense(RAD_F32, { 2, 32 }, hfill(223)) + .dense(RAD_F32, { 0, 32 }, sent, true) + .pi("T", 0).pi("hidden_size", 32).pi("taps", 2).pi("group_size", 8).pi("NG", 4) + .pi("block_size", 4).ps("dtype", "f32") + .refuses(RAD_E_SHAPE); + 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 + * (abi/rad_planes.h): an fp8 or int8 lm head, E4M3 mixing and fc rows with f32 group scales, and + * the scale and zero of the zero-point grids. No description draws one, so each case builds the + * canonical planes, asks both libraries' layout hooks for the stored form (which must agree byte + * for byte and invert back to the planes), and launches both over those bytes. + * + * Each GEMM case is also held to an answer neither library computed: the core's affine decoder + * (core/format/encoding.h) dequantises the planes and the activation's codes, and a double + * product of the two is the output. In a standalone build, which has no core, that comparison is + * left out and said so. */ + +/* A weight's canonical planes over [rows, cols], filled by value. */ +struct Planes { + RadEncoding enc{}; + int64_t rows = 0, cols = 0; + std::vector> data; + std::vector prow, pcol; + + Planes(const RadEncoding& e, int64_t r, int64_t c) : enc(e), rows(r), cols(c) { + for (int i = 0; i < e.n_planes; ++i) { + int64_t pr = 0, pc = 0; + rad_enc_plane_dims(&e.plane[i], r, c, &pr, &pc); + prow.push_back(pr); + pcol.push_back(pc); + data.emplace_back((size_t)(pr * rad_enc_row_bytes(e.plane[i].dtype, pc)), 0); + } + } + uint8_t* row_at(int i, int64_t r) { + return data[(size_t)i].data() + r * rad_enc_row_bytes(enc.plane[i].dtype, pcol[(size_t)i]); + } + /* Element (r, c) of plane i: a float stored in its dtype, or an integer code. */ + void set(int i, int64_t r, int64_t c, float v) { + const uint32_t dt = enc.plane[i].dtype; + if (dt == RAD_F32 || dt == RAD_F16 || dt == RAD_BF16) rad_store_f32(row_at(i, r), dt, c, v); + else rad_store_code(row_at(i, r), dt, c, (int)v); + } + void fill(int i, const std::function& f) { + for (int64_t r = 0; r < prow[(size_t)i]; ++r) + for (int64_t c = 0; c < pcol[(size_t)i]; ++c) set(i, r, c, f(r, c)); + } + /* The planes `sel` names as a layout hook takes them: dense rank 2, data when `with_data`. */ + std::vector tensors(const std::vector& sel, bool with_data) { + std::vector t; + for (int i : sel) { + RadTensor x{}; + x.dtype = enc.plane[i].dtype; + x.rank = 2; + x.shape[0] = prow[(size_t)i]; + x.shape[1] = pcol[(size_t)i]; + x.stride[0] = x.shape[1]; + x.stride[1] = 1; + x.data = with_data ? data[(size_t)i].data() : nullptr; + t.push_back(x); + } + return t; + } +}; + +/* The joined bytes of planes `sel` for operand `opd`, through `lib`'s own hooks: RAD_OK from + * layout, relayout to the size it named, unrelayout back to the same planes. */ +bool join_with(const Lib& lib, const char* op, const std::vector& p, int opd, + Planes& w, const std::vector& sel, RadLayout* lay, std::vector* out, + std::string* why) { + const RadKernelInfo* k = lib.row(op); + if (!k || !k->layout || !k->relayout || !k->unrelayout) { + *why = std::string(lib.info->name) + " has no layout hooks on " + op; + return false; + } + std::vector geo = w.tensors(sel, false); + const int st = k->layout(p.data(), (int)p.size(), opd, &w.enc, sel.data(), geo.data(), + (int)sel.size(), lay); + if (st != RAD_OK) { + *why = std::string(lib.info->name) + "'s layout hook answered " + std::to_string(st); + return false; + } + out->assign((size_t)lay->bytes, 0xA5); + std::vector full = w.tensors(sel, true); + if (k->relayout(p.data(), (int)p.size(), opd, &w.enc, sel.data(), full.data(), + (int)sel.size(), out->data(), lay->bytes) != RAD_OK) { + *why = std::string(lib.info->name) + "'s relayout refused its own layout"; + return false; + } + std::vector> back; + std::vector bt = w.tensors(sel, false); + for (size_t j = 0; j < sel.size(); ++j) { + back.emplace_back(w.data[(size_t)sel[j]].size(), 0); + bt[j].data = back.back().data(); + } + if (k->unrelayout(p.data(), (int)p.size(), opd, &w.enc, sel.data(), out->data(), lay->bytes, + bt.data(), (int)sel.size()) != RAD_OK) { + *why = std::string(lib.info->name) + "'s unrelayout refused its own stored form"; + return false; + } + for (size_t j = 0; j < sel.size(); ++j) + if (back[j] != w.data[(size_t)sel[j]]) { + *why = std::string(lib.info->name) + "'s unrelayout did not give back plane " + + std::to_string(sel[j]); + return false; + } + return true; +} + +/* Both libraries' joined form of `w`: identical layouts and bytes, or a failure in `why`. */ +bool join_both(const Check& ck, const char* op, const std::vector& p, int opd, + Planes& w, const std::vector& sel, std::vector* out, + uint32_t* dtype, std::string* why) { + RadLayout la{}, lb{}; + std::vector a, b; + if (!join_with(*ck.ref, op, p, opd, w, sel, &la, &a, why)) return false; + if (!ck.lib->row(op) || !ck.lib->row(op)->layout) { + /* A host library without the hooks reads nothing joined; the case reports it absent. */ + *out = a; + *dtype = la.dtype; + return true; + } + if (!join_with(*ck.lib, op, p, opd, w, sel, &lb, &b, why)) return false; + if (std::strcmp(la.tag ? la.tag : "", lb.tag ? lb.tag : "") != 0 || la.bytes != lb.bytes || + la.dtype != lb.dtype || a != b) { + *why = "the two libraries store the joined planes differently"; + return false; + } + *out = a; + *dtype = la.dtype; + return true; +} + +/* The weight the core's affine decoder gives for `w`'s planes, f32 [rows, cols]; empty when this + * build has no core. */ +std::vector core_decode(const Planes& w) { +#ifdef AVX_CHECK_CORE_DECODER + std::vector d; + for (const auto& v : w.data) d.push_back(v.data()); + rad::EncodedView v; + rad::enc_view(w.enc, w.rows, w.cols, d.data(), &v); + std::vector out((size_t)(w.rows * w.cols)); + std::string why; + if (rad::enc_decode_rows(v, 0, w.rows, out.data(), &why) != RAD_OK) { + std::printf(" core decoder refused a hand-built weight: %s\n", why.c_str()); + return {}; + } + return out; +#else + (void)w; + return {}; +#endif +} + +/* y[m][n] = sum_k a[m][off(n) + k] * W[n][k] in double: `a` [M, acols], W [N, K], `off(n)` the + * column where row n's part starts. */ +std::vector oracle_gemm(const std::vector& a, int64_t acols, + const std::vector& W, int64_t M, int64_t N, int64_t K, + const std::function& off) { + std::vector y((size_t)(M * N), 0.0f); + if (W.empty()) return {}; + for (int64_t m = 0; m < M; ++m) + for (int64_t n = 0; n < N; ++n) { + double s = 0; + const int64_t o = off(n); + for (int64_t k = 0; k < K; ++k) + s += (double)a[(size_t)(m * acols + o + k)] * (double)W[(size_t)(n * K + k)]; + y[(size_t)(m * N + n)] = (float)s; + } + return y; +} + +/* Deterministic integer in [lo, hi] for element i under seed s. */ +int64_t hint(uint64_t s, int64_t i, int64_t lo, int64_t hi) { + uint64_t x = s * 0x9E3779B97F4A7C15ull + (uint64_t)i; + x ^= x >> 31; x *= 0xBF58476D1CE4E5B9ull; x ^= x >> 29; + return lo + (int64_t)(x % (uint64_t)(hi - lo + 1)); +} + +/* A case whose joined weight did not build is a failure of the case, reported as one. */ +struct Broken { + std::vector why; +}; + +void planes_cases(const Check& ck, std::vector& hs, Broken& broken) { + const auto zero = [](int64_t) { return 0.0f; }; + auto rp = [](std::initializer_list> ints, + std::initializer_list> strs) { + std::vector p; + for (auto& [k, v] : ints) p.push_back(RadParam{ k, RAD_P_INT, v, 0, nullptr, 0 }); + for (auto& [k, v] : strs) p.push_back(RadParam{ k, RAD_P_STR, 0, 0, v, 0 }); + return p; + }; + /* The stored bytes as the engine passes them: the joined form's dtype, the declared extents. */ + auto add_joined = [](Hand& h, uint32_t dt, std::vector shape, + const std::vector& bytes) -> Hand& { + const int64_t span = (int64_t)bytes.size() * 8 / rad_dtype_bits(dt); + return h.bytes(dt, shape, { shape.size() > 1 ? shape[1] : 1, 1 }, span, bytes, false); + }; + + /* ---- the lm head: E4M3 with a bf16 scale per 128 x 128, int8 with one per (row, 128) ---- * + * N = 200 gives a second, partial block row and K = 320 a partial last column block. M = 9 + * is past every register block's edge and 5 inside it. */ + for (int i8 : { 0, 1 }) { + const int64_t N = i8 ? 100 : 200, K = i8 ? 256 : 320; + RadEncoding e = rad_enc_affine(i8 ? RAD_I8 : RAD_F8E4M3, RAD_BF16, i8 ? 1 : 128, 128); + Planes w(e, N, K); + w.fill(0, [i8](int64_t r, int64_t c) { + const int64_t v = hint(200 + i8, r * 4099 + c, i8 ? -127 : 0, i8 ? 127 : 254); + return i8 ? (float)v : (float)(v == 0x7f ? 0x7e : v); + }); + w.fill(1, [](int64_t r, int64_t c) { return 0.004f * (float)(1 + (r * 7 + c) % 9); }); + const std::vector W = core_decode(w); + for (const char* adt : { "bf16", "f32" }) + for (int64_t M : { 1, 5, 9 }) { + const std::vector p = + rp({ { "M", M }, { "n_vocab", N }, { "n_embd", K } }, { { "dtype", adt } }); + std::vector j; + uint32_t jdt = 0; + std::string why; + if (!join_both(ck, "logits_gemm", p, 1, w, { 0, 1 }, &j, &jdt, &why)) { + broken.why.push_back(std::string("logits_gemm: ") + why); + continue; + } + const uint32_t ad = rad_dtype_parse(adt); + std::vector a((size_t)(M * K)); + for (int64_t t = 0; t < M * K; ++t) a[(size_t)t] = hfill(210)(t); + if (ad == RAD_BF16) + for (float& v : a) v = rad_bf16_to_f32(rad_f32_to_bf16(v)); + const std::string nm = + std::string(i8 ? "i8*bf16[1x128] head" : "fp8_e4m3*bf16[128x128] head") + + ", " + adt + ", M=" + std::to_string(M); + Hand h(nm.c_str(), "logits_gemm", ad == RAD_F32 ? 2e-5 : 8e-3); + h.dense(ad, { M, K }, [&a](int64_t t) { return a[(size_t)t]; }); + add_joined(h, jdt, { N, K }, j); + h.dense(RAD_F32, { M, N }, zero, true) + .pi("M", M).pi("n_vocab", N).pi("n_embd", K).ps("dtype", adt); + h.oracle_opd = 2; + h.oracle = oracle_gemm(a, K, W, M, N, K, [](int64_t) { return 0; }); + h.oracle_tol = 1e-5; + hs.push_back(std::move(h)); + } + + /* logit_rerank over the same head: candidates across both block rows, a pad, and ids + * outside this rank's rows. */ + const int64_t M = 3, R = 5, VOFF = 20; + const std::vector p = rp({ { "M", M }, { "R", R }, { "n_vocab", N }, + { "n_embd", K }, { "vocab_off", VOFF } }, + { { "dtype", "f32" } }); + std::vector j; + uint32_t jdt = 0; + std::string why; + if (!join_both(ck, "logit_rerank", p, 1, w, { 0, 1 }, &j, &jdt, &why)) { + broken.why.push_back(std::string("logit_rerank: ") + why); + continue; + } + static const int32_t kIds[3][5] = { { 21, 150, 19, -1, 60 }, + { 199, 20, 140, 77, 300 }, + { 33, 34, 35, 36, 37 } }; + Hand h(i8 ? "int8 head joined, ids across the shard" : "fp8 head joined, ids across both " + "block rows", "logit_rerank", 1e-5); + h.dense(RAD_F32, { M, K }, hfill(220)); + add_joined(h, jdt, { N, K }, j); + h.dense(RAD_I32, { M, R }, [](int64_t t) { return (float)kIds[t / 5][t % 5]; }) + .dense(RAD_I32, { M, R }, [](int64_t) { return 7.0f; }, true) + .dense(RAD_F32, { M, R }, zero, true) + .dense(RAD_F32, { M, R, 2 }, zero, true) + .pi("M", M).pi("R", R).pi("n_vocab", N).pi("n_embd", K).pi("vocab_off", VOFF) + .ps("dtype", "f32"); + hs.push_back(std::move(h)); + } + + /* ---- hc_read and mtp_enter over E4M3 rows with f32 scales in their rows' groups --------- * + * Flash-Next's geometry scaled down: mix_down [lowrank, hc*n] per 128 columns, mix_up + * [hc*n, lowrank] per quarter row (lowrank 64: groups of 16), the fc matrices per 128. */ + { + const int64_t M = 5, n = 128, hc = 4, lr = 64, HN = hc * n; + auto rows = [&](int64_t R, int64_t C, int64_t G, uint64_t seed) { + Planes w(rad_enc_affine(RAD_F8E4M3, RAD_F32, 1, G), R, C); + w.fill(0, [seed](int64_t r, int64_t c) { + const int64_t v = hint(seed, r * 977 + c, 0, 254); + return (float)(v == 0x7f ? 0x7e : v); + }); + w.fill(1, [seed](int64_t r, int64_t c) { + return 0.002f * (float)(1 + hint(seed + 1, r * 31 + c, 0, 6)) + 1e-7f * (float)r; + }); + return w; + }; + Planes dn = rows(lr, HN, 128, 230), up = rows(HN, lr, lr / 4, 232); + for (const char* dt : { "bf16", "f32" }) + for (int inject : { 1, 0 }) { + const std::vector p = + rp({ { "M", M }, { "n", n }, { "hc", hc }, { "lowrank", lr }, + { "inject", inject }, { "group", 0 } }, + { { "dtype", dt }, { "mix", "e4m3" } }); + std::vector jd, ju; + uint32_t dd = 0, ud = 0; + std::string why; + if (!join_both(ck, "hc_read", p, 2, dn, { 0, 1 }, &jd, &dd, &why) || + !join_both(ck, "hc_read", p, 3, up, { 0, 1 }, &ju, &ud, &why)) { + broken.why.push_back(std::string("hc_read: ") + why); + continue; + } + const uint32_t ad = rad_dtype_parse(dt); + const std::string nm = std::string("mix e4m3 joined, ") + dt + + (inject ? ", inject" : ", final mixer"); + Hand h(nm.c_str(), "hc_read", ad == RAD_F32 ? 1e-5 : 6e-3); + h.dense(ad, { M, HN }, hfill(234)) + .dense(RAD_F32, { HN }, [](int64_t i) { return 0.1f * (float)(i % 7); }); + add_joined(h, dd, { lr, HN }, jd); + add_joined(h, ud, { HN, lr }, ju); + if (inject) h.dense(RAD_BF16, { hc, HN }, hfill(235, 0.05f)); + else h.none(); + h.dense(ad, { M, n }, zero, true); + if (inject) h.dense(RAD_F32, { M, hc }, zero, true); + else h.none(); + h.none().none().none().none() + .pi("M", M).pi("n", n).pi("hc", hc).pi("lowrank", lr).pf("eps", 1e-6) + .ps("dtype", dt).pf("wadd", 1.0).pi("inject", inject).pi("group", 0) + .ps("mix", "e4m3"); + hs.push_back(std::move(h)); + } + + Planes fh = rows(n, n, 128, 236), fe = rows(n, n, 128, 238); + for (const char* dt : { "bf16", "f32" }) { + const std::vector p = + rp({ { "M", M }, { "n", n }, { "hc", hc }, { "ngroup", hc } }, + { { "dtype", dt }, { "fc", "e4m3" } }); + std::vector jh, je; + uint32_t hd = 0, ed = 0; + std::string why; + if (!join_both(ck, "mtp_enter", p, 4, fh, { 0, 1 }, &jh, &hd, &why) || + !join_both(ck, "mtp_enter", p, 5, fe, { 0, 1 }, &je, &ed, &why)) { + broken.why.push_back(std::string("mtp_enter: ") + why); + continue; + } + const uint32_t ad = rad_dtype_parse(dt); + Hand h((std::string("fc e4m3 joined, ") + dt).c_str(), "mtp_enter", + ad == RAD_F32 ? 1e-5 : 6e-3); + h.dense(ad, { M, HN }, hfill(240)) + .dense(ad, { M, n }, hfill(241)) + .dense(RAD_F32, { HN }, [](int64_t i) { return 0.05f * (float)(i % 5); }) + .dense(RAD_F32, { n }, [](int64_t i) { return 0.03f * (float)(i % 3); }); + add_joined(h, hd, { n, n }, jh); + add_joined(h, ed, { n, n }, je); + h.dense(ad, { M, HN }, zero, true) + .pi("M", M).pi("n", n).pi("hc", hc).pf("eps", 1e-6).ps("dtype", dt).pf("wadd", 1.0) + .pi("ngroup", hc).ps("fc", "e4m3"); + hs.push_back(std::move(h)); + } + } + + /* ---- the zero-point grids of gemm_nt_q ---------------------------------------------------- * + * Codes across their whole range, zeros at both ends of it (0 and the largest code) beside + * values between, an f16 scale and a u8 zero per (row, 128 of K). M = 13 is the small-M + * paths' 8 + 4 + 1 rows, 17 past them, padding quant_act_i8's code sums to 32 rows; N = 40, + * 41, 48 and 96 are not multiples of the driver's 6-row block, 40 and 41 not of the small-M + * paths' 16, and 41 leaves the 16-bit path's row pairs one row over. The ParoQuant grids + * also run in parts (pb1, pb2), each part meeting its own activation copy; the int8 ones also + * at M = 40 over K = 2304, two of the bf16 grouped driver's K chunks. */ + struct Grid { const char* dtype; uint32_t codes; int act; int parts; }; + static const Grid kGrids[] = { + { "w2a8", RAD_U2, 0, 1 }, { "w4a8_asym", RAD_U4, 0, 1 }, + { "w4a16_asym", RAD_U4, 2, 1 }, { "w4a16_asym", RAD_U4, 2, 2 }, + { "w5a16", RAD_U5, 2, 1 }, { "w5a16", RAD_U5, 2, 3 }, + { "w4a8i8_asym", RAD_U4, 1, 1 }, { "w4a8i8_asym", RAD_U4, 1, 2 }, + { "w5a8i8", RAD_U5, 1, 1 }, { "w5a8i8", RAD_U5, 1, 3 }, + }; + for (const Grid& gd : kGrids) + for (int64_t M : { 1, 13, 17, 40 }) { + if (M == 40 && gd.act != 1) continue; + const int64_t N = gd.parts == 3 ? 96 : gd.parts == 2 ? 48 : gd.act == 0 ? 40 : 41; + const int64_t K = M == 40 ? 2304 : 256, GS = 128; + const int64_t G = K / GS, P = gd.parts; + const int64_t top = (1 << rad_dtype_bits(gd.codes)) - 1; + RadEncoding e = rad_enc_affine(gd.codes, RAD_F16, 1, GS); + rad_enc_add_plane(&e, "zero", RAD_U8, 1, GS); + Planes w(e, N, K); + w.fill(0, [top](int64_t r, int64_t c) { + return (float)hint(250, r * 1031 + c, 0, top); + }); + w.fill(1, [](int64_t r, int64_t c) { return 0.01f * (float)(1 + (r * 3 + c) % 11); }); + w.fill(2, [top, G](int64_t r, int64_t c) { + const int64_t k = (r * G + c) % 4; + return (float)(k == 0 ? 0 : k == 1 ? top : hint(251, r * G + c, 0, top)); + }); + const int64_t pb1 = P > 1 ? (P == 3 ? 32 : 16) : 0, pb2 = P == 3 ? 64 : 0; + std::vector p = rp({ { "M", M }, { "N", N }, { "K", K }, { "group", GS } }, + { { "dtype", gd.dtype } }); + if (pb1) p.push_back(RadParam{ "pb1", RAD_P_INT, pb1, 0, nullptr, 0 }); + if (pb2) p.push_back(RadParam{ "pb2", RAD_P_INT, pb2, 0, nullptr, 0 }); + std::vector j; + uint32_t jdt = 0; + std::string why; + if (!join_both(ck, "gemm_nt_q", p, 3, w, { 1, 2 }, &j, &jdt, &why)) { + broken.why.push_back(std::string("gemm_nt_q ") + gd.dtype + ": " + why); + continue; + } + const int64_t AC = P * K; + /* The activation as the grid means it, for the oracle, and its operands. */ + std::vector af((size_t)(M * AC)); + std::vector codes((size_t)(M * AC)), sa; + if (gd.act == 0) { + for (int64_t t = 0; t < M * AC; ++t) + codes[(size_t)t] = (float)hint(252, t, -127, 127); + sa.resize((size_t)M); + for (int64_t m = 0; m < M; ++m) sa[(size_t)m] = 0.003f * (float)(1 + m % 5); + for (int64_t t = 0; t < M * AC; ++t) + af[(size_t)t] = codes[(size_t)t] * sa[(size_t)(t / AC)]; + } else if (gd.act == 1) { + for (int64_t t = 0; t < M * AC; ++t) + codes[(size_t)t] = (float)hint(253, t, -127, 127); + sa.resize((size_t)(M * P * G)); + for (size_t t = 0; t < sa.size(); ++t) sa[t] = 0.002f * (float)(1 + t % 7); + for (int64_t t = 0; t < M * AC; ++t) + af[(size_t)t] = + codes[(size_t)t] * sa[(size_t)((t / AC) * P * G + (t % AC) / GS)]; + } else { + for (int64_t t = 0; t < M * AC; ++t) + af[(size_t)t] = rad_f16_to_f32(rad_f32_to_f16(hfill(254)(t))); + } + const std::string nm = std::string(gd.dtype) + + (P > 1 ? ", " + std::to_string(P) + " parts" : "") + ", M=" + + std::to_string(M) + (K != 256 ? ", K=" + std::to_string(K) : "") + + ", zeros 0 and " + std::to_string(top); + Hand h(nm.c_str(), "gemm_nt_q", 8e-3); + if (gd.act == 0) { + /* quant_act_i8's codes in the step order, its per-row scale and code sums. */ + std::vector st((size_t)(M * K)); + for (int64_t m = 0; m < M; ++m) + for (int64_t c = 0; c < K; ++c) { + const int64_t pos = (c & ~(int64_t)12) | ((c & 4) << 1) | ((c & 8) >> 1); + st[(size_t)(m * K + pos)] = codes[(size_t)(m * K + c)]; + } + const int64_t mpad = (M + 15) / 16 * 16; + std::vector sums((size_t)(G * mpad), 0.0f); + for (int64_t g = 0; g < G; ++g) + for (int64_t m = 0; m < M; ++m) { + float s = 0; + for (int64_t k = g * GS; k < (g + 1) * GS; ++k) + s += codes[(size_t)(m * K + k)]; + sums[(size_t)(g * mpad + m)] = s; + } + h.dense(RAD_I8, { M, K }, [st](int64_t t) { return st[(size_t)t]; }) + .dense(RAD_F32, { M, 1 }, [sa](int64_t t) { return sa[(size_t)t]; }); + h.raw(gd.codes, { N, K }, w.data[0].data()); + add_joined(h, jdt, { N, K }, j); + h.dense(RAD_BF16, { M, N }, zero, true) + .dense(RAD_F32, { G, mpad }, [sums](int64_t t) { return sums[(size_t)t]; }) + .none(); + } else if (gd.act == 1) { + h.dense(RAD_I8, { M, AC }, [codes](int64_t t) { return codes[(size_t)t]; }) + .dense(RAD_F32, { M, P * G }, [sa](int64_t t) { return sa[(size_t)t]; }); + h.raw(gd.codes, { N, K }, w.data[0].data()); + add_joined(h, jdt, { N, K }, j); + h.dense(RAD_BF16, { M, N }, zero, true).none().none(); + } else { + h.dense(RAD_F16, { M, AC }, [af](int64_t t) { return af[(size_t)t]; }).none(); + h.raw(gd.codes, { N, K }, w.data[0].data()); + add_joined(h, jdt, { N, K }, j); + h.dense(RAD_BF16, { M, N }, zero, true).none().none(); + } + h.pi("M", M).pi("N", N).pi("K", K).pi("group", GS).ps("dtype", gd.dtype); + if (pb1) h.pi("pb1", pb1); + if (pb2) h.pi("pb2", pb2); + /* The oracle reads the codes untransformed, as the GEMM does: a ParoQuant weight's + * rotation is the activation's. */ + const int64_t e1 = pb1 ? pb1 : N, e2 = pb2 ? pb2 : N; + h.oracle_opd = 4; + h.oracle = oracle_gemm(af, AC, core_decode(w), M, N, K, [e1, e2, K](int64_t n) { + return (n < e1 ? 0 : n < e2 ? 1 : 2) * K; + }); + h.oracle_tol = 6e-3; + hs.push_back(std::move(h)); + } + + /* ---- refusals ------------------------------------------------------------------------ * + * A zero-point grid's `b_scale` that is not joined has no zero to read: both refuse. */ + { + const int64_t M = 2, N = 16, K = 128; + Hand h("w4a16_asym with a plain scale, no zero", "gemm_nt_q", 1e-5); + h.dense(RAD_F16, { M, K }, hfill(260)) + .none() + .dense(RAD_U4, { N, K }, [](int64_t i) { return (float)(i % 16); }) + .dense(RAD_F16, { N, 1 }, [](int64_t) { return 0.5f; }) + .dense(RAD_BF16, { M, N }, zero, true) + .none().none() + .pi("M", M).pi("N", N).pi("K", K).pi("group", 128).ps("dtype", "w4a16_asym") + .refuses(RAD_E_DTYPE); + hs.push_back(std::move(h)); + } +} + +/* What the layout hooks refuse, identically in both libraries: an encoding the op does not + * compute is RAD_E_DTYPE, and a single plane is stored as it is (RAD_E_UNSUPPORTED). */ +bool planes_refusals(const Check& ck, int* run) { + struct R { const char* what; const char* op; int opd; std::vector p; RadEncoding e; + std::vector sel; int want; }; + std::vector rs; + auto P = [](std::initializer_list> ints, const char* dtype) { + std::vector p; + for (auto& [k, v] : ints) p.push_back(RadParam{ k, RAD_P_INT, v, 0, nullptr, 0 }); + if (dtype) p.push_back(RadParam{ "dtype", RAD_P_STR, 0, 0, dtype, 0 }); + return p; + }; + auto zp = [](uint32_t codes, uint32_t zdt, int64_t g, const char* tf) { + RadEncoding e = rad_enc_affine(codes, RAD_F16, 1, g); + rad_enc_add_plane(&e, "zero", zdt, 1, g); + if (tf) rad_enc_copy_str(e.transform, tf); + return e; + }; + const auto head = P({ { "M", 4 }, { "n_vocab", 256 }, { "n_embd", 256 } }, "bf16"); + const auto gq = [&](const char* dt) { + return P({ { "M", 4 }, { "N", 256 }, { "K", 256 }, { "group", 128 } }, dt); + }; + rs.push_back({ "a u4 head", "logits_gemm", 1, head, rad_enc_affine(RAD_U4, RAD_BF16, 1, 128), + { 0, 1 }, RAD_E_DTYPE }); + rs.push_back({ "an fp8 head under fwht128", "logits_gemm", 1, head, + [] { RadEncoding e = rad_enc_affine(RAD_F8E4M3, RAD_BF16, 128, 128); + rad_enc_copy_str(e.transform, "fwht128"); return e; }(), { 0, 1 }, + RAD_E_DTYPE }); + rs.push_back({ "a plain bf16 head", "logits_gemm", 1, head, rad_enc_plain(RAD_BF16), { 0 }, + RAD_E_UNSUPPORTED }); + rs.push_back({ "the scale plane alone", "gemm_nt_q", 3, gq("w2a8"), + zp(RAD_U2, RAD_U8, 128, nullptr), { 1 }, RAD_E_UNSUPPORTED }); + rs.push_back({ "w2a8 over u4 codes", "gemm_nt_q", 3, gq("w2a8"), + zp(RAD_U4, RAD_U8, 128, nullptr), { 1, 2 }, RAD_E_DTYPE }); + rs.push_back({ "w5a16 with a zero per 64", "gemm_nt_q", 3, gq("w5a16"), + zp(RAD_U5, RAD_U8, 64, nullptr), { 1, 2 }, RAD_E_DTYPE }); + rs.push_back({ "w4a16_asym under fwht128", "gemm_nt_q", 3, gq("w4a16_asym"), + zp(RAD_U4, RAD_U8, 128, "fwht128"), { 1, 2 }, RAD_E_DTYPE }); + rs.push_back({ "zero then scale", "gemm_nt_q", 3, gq("w4a16_asym"), + zp(RAD_U4, RAD_U8, 128, nullptr), { 2, 1 }, RAD_E_DTYPE }); + rs.push_back({ "scale and zero at fp8a8", "gemm_nt_q", 3, gq("fp8a8"), + zp(RAD_U4, RAD_U8, 128, nullptr), { 1, 2 }, RAD_E_DTYPE }); + bool ok = true; + for (R& r : rs) { + for (const Lib* lib : { ck.ref, ck.lib }) { + const RadKernelInfo* k = lib->row(r.op); + if (!k || !k->layout) { + if (lib == ck.lib && !ck.own) continue; + std::printf(" FAIL %-20s %s\n %s has no layout hook\n", r.op, r.what, + lib->info->name); + ok = false; + continue; + } + std::vector t(r.sel.size()); + for (size_t i = 0; i < r.sel.size(); ++i) { + int64_t pr = 0, pc = 0; + rad_enc_plane_dims(&r.e.plane[r.sel[i]], 256, 256, &pr, &pc); + t[i] = RadTensor{}; + t[i].dtype = r.e.plane[r.sel[i]].dtype; + t[i].rank = 2; + t[i].shape[0] = pr; + t[i].shape[1] = pc; + } + RadLayout L{}; + const int st = k->layout(r.p.data(), (int)r.p.size(), r.opd, &r.e, r.sel.data(), + t.data(), (int)t.size(), &L); + ++*run; + if (st != r.want) { + std::printf(" FAIL %-20s %s\n %s's layout hook answered %d, expected %d\n", + r.op, r.what, lib->info->name, st, r.want); + ok = false; + } else if (ck.verbose) { + std::printf(" %-22s %-46s %s: %d\n", r.op, r.what, lib->info->name, st); + } + } + } + return ok; +} + +/* ================================================================== a chunked audio encoder + * The forms Qwen3-ASR's tower issues and EmbeddingGemma 2's subsampler keeps issuing, which no + * description draws: conv2d with no bias or no row mask, segment bounds in frames read at a + * cu_div, attention in blocks over several clips, rows no segment covers left as they were, and + * a linear whose residual is its own output. */ +void encoder_cases(std::vector& hs) { + /* gemm_nt_bias with `res` the output itself, as every pre-norm encoder layer adds its + * attention output and its feed-forward to the residual stream in place (Qwen3-ASR's tower, + * the Qwen-VL and SigLIP2 vision towers). The residual must be read before the product is + * stored over it; both libraries are held to an answer computed apart, since a library that + * stores first adds the product to itself and agrees with another that does the same. At + * Qwen3-ASR's geometries: the out-projection (K 1024) and the second feed-forward linear + * (K 4096), 76 rows (one 6 s clip), and a gelu epilogue on a smaller shape. */ + struct Res { int64_t M, N, K; const char* act; uint32_t dt; }; + for (const Res& c : { Res{ 76, 1024, 1024, "none", RAD_BF16 }, Res{ 76, 256, 4096, "none", RAD_BF16 }, + Res{ 9, 96, 64, "gelu", RAD_BF16 }, Res{ 9, 96, 64, "none", RAD_F32 } }) { + auto round = [&](float v) { + return c.dt == RAD_BF16 ? rad_bf16_to_f32(rad_f32_to_bf16(v)) : v; + }; + std::vector a((size_t)(c.M * c.K)), w((size_t)(c.N * c.K)), bias((size_t)c.N), + res((size_t)(c.M * c.N)); + for (size_t i = 0; i < a.size(); ++i) a[i] = round(hfill(951)((int64_t)i)); + for (size_t i = 0; i < w.size(); ++i) w[i] = round(hfill(952, 0.05f)((int64_t)i)); + for (size_t i = 0; i < bias.size(); ++i) bias[i] = round(hfill(953)((int64_t)i)); + for (size_t i = 0; i < res.size(); ++i) res[i] = round(hfill(954, 4.0f)((int64_t)i)); + std::vector want = oracle_gemm(a, c.K, w, c.M, c.N, c.K, [](int64_t) { return 0; }); + for (int64_t m = 0; m < c.M; ++m) + for (int64_t n = 0; n < c.N; ++n) { + float v = round(want[(size_t)(m * c.N + n)] + bias[(size_t)n]); + if (!std::strcmp(c.act, "gelu")) + v = round(0.5f * v * (1.0f + sc_erf(v * 0.70710678118654752f))); + want[(size_t)(m * c.N + n)] = round(res[(size_t)(m * c.N + n)] + v); + } + const std::string nm = "res is y, M=" + std::to_string(c.M) + " N=" + std::to_string(c.N) + + " K=" + std::to_string(c.K) + " " + c.act + + (c.dt == RAD_BF16 ? " bf16" : " f32"); + Hand h(nm.c_str(), "gemm_nt_bias", c.dt == RAD_F32 ? 1e-5 : 8e-3); + h.dense(c.dt, { c.M, c.K }, [&a](int64_t i) { return a[(size_t)i]; }) + .dense(c.dt, { c.N, c.K }, [&w](int64_t i) { return w[(size_t)i]; }) + .dense(c.dt, { c.N }, [&bias](int64_t i) { return bias[(size_t)i]; }) + .dense(c.dt, { c.M, c.N }, [&res](int64_t i) { return res[(size_t)i]; }, true) + .alias(3) + .pi("M", c.M).pi("N", c.N).pi("K", c.K).ps("dtype", c.dt == RAD_BF16 ? "bf16" : "f32") + .ps("act", c.act); + h.oracle_opd = 4; + h.oracle = want; + h.oracle_tol = c.dt == RAD_F32 ? 1e-5 : 1e-2; + hs.push_back(std::move(h)); + } + for (const uint32_t dt : { (uint32_t)RAD_F32, (uint32_t)RAD_BF16 }) { + const char* dn = dt == RAD_F32 ? "f32" : "bf16"; + const double tol = dt == RAD_F32 ? 1e-5 : 6e-3; + /* Two clips of 10 and 14 frames, 12 output rows in all, with a row mask and no bias: the + * call a model without a bias makes, five operands as before the bias existed. */ + { + const int64_t M = 24, W = 16, cin = 1, cout = 8, Wo = 8; + Hand h(dt == RAD_F32 ? "no bias, masked rows, two clips" : "no bias, masked rows, bf16", + "conv2d", tol); + h.dense(dt, { M, W * cin }, hfill(901)) + .dense(dt, { cout, cin, 3, 3 }, hfill(902, 0.5f)) + .idx({ 0, 10, 24 }) + .dense(RAD_I32, { M }, [](int64_t i) { return (float)(i % 7 != 3); }) + .dense(dt, { 12, Wo * cout }, hfill(903), true) + .pi("M", M).pi("width", W).pi("cin", cin).pi("cout", cout).pi("kh", 3).pi("kw", 3) + .pi("stride", 2).pi("pad", 1).ps("dtype", dn); + hs.push_back(std::move(h)); + } + /* A bias and gelu with no row mask, over a time-last kernel. */ + { + const int64_t M = 16, W = 8, cin = 3, cout = 5, Wo = 4; + Hand h(dt == RAD_F32 ? "bias, gelu, time last, no mask" : "bias, gelu, no mask, bf16", + "conv2d", tol); + h.dense(dt, { M, W * cin }, hfill(911)) + .dense(dt, { cout, cin, 3, 3 }, hfill(912, 0.5f)) + .idx({ 0, 6, 16 }) + .none() + .dense(dt, { 8, Wo * cout }, hfill(913), true) + .dense(dt, { cout }, hfill(914)) + .pi("M", M).pi("width", W).pi("cin", cin).pi("cout", cout).pi("kh", 3).pi("kw", 3) + .pi("stride", 2).pi("pad", 1).ps("dtype", dn).pi("t_last", 1).ps("act", "gelu"); + hs.push_back(std::move(h)); + } + /* The tower's output projection as Qwen3-ASR issues it: a 1 x f3 kernel over rows whose + * clip bounds are in frames (cu_div 8), no mask, and four rows past the last clip. */ + { + const int64_t R = 24, f3 = 2, C = 6; + Hand h(dt == RAD_F32 ? "1 x 2 kernel, cu_div 8, uncovered rows" + : "1 x 2 kernel, cu_div 8, bf16", "conv2d_unfold", tol); + h.dense(dt, { R, f3 * C }, hfill(921)) + .idx({ 0, 104, 160 }) + .none() + .dense(dt, { R, C * f3 }, hfill(922), true) + .pi("M", R).pi("width", f3).pi("cin", C).pi("kh", 1).pi("kw", f3).pi("stride", 1) + .pi("pad", 0).pi("cu_div", 8).pi("valid_stride", 8).ps("dtype", dn); + hs.push_back(std::move(h)); + } + /* Attention in 13-row blocks over two clips of 30 and 10 rows, bounds in frames, q, k and v + * column slices of one fused projection, as the tower's layers read it. */ + { + const int64_t R = 40, H = 2, HD = 64, Wd = 3 * H * HD; + Hand h(dt == RAD_F32 ? "blocks of 13 over two clips, cu_div 8, fused qkv" + : "blocks of 13, cu_div 8, fused qkv, bf16", "attn_dense", + dt == RAD_F32 ? 1e-4 : 2e-2); + h.view(dt, { R, H * HD }, { Wd, 1 }, R * Wd, hfill(931)) + .view(dt, { R, H * HD }, { Wd, 1 }, R * Wd, hfill(932)) + .view(dt, { R, H * HD }, { Wd, 1 }, R * Wd, hfill(933)) + .idx({ 0, 240, 320 }) + .dense(dt, { R, H * HD }, hfill(934), true) + .pi("M", R).pi("head_dim", HD).pi("gqa", 1).pi("causal", 0).ps("dtype", dn) + .pf("scale", 0.125).pi("max_seqlen", 30).pi("cu_div", 8).pi("block", 13); + hs.push_back(std::move(h)); + } + /* Positions restarting every 13 rows of three clips (bounds in frames), and seven rows + * past the last clip that keep what they held. */ + { + const int64_t R = 40, n = 64; + Hand h(dt == RAD_F32 ? "three clips at cu_div 8, uncovered rows" + : "three clips at cu_div 8, bf16", "seg_sinusoid", tol); + h.idx({ 0, 104, 208, 264 }) + .dense(dt, { R, n }, hfill(941), true) + .pi("M", R).pi("n", n).pi("period", 13).pi("cu_div", 8).ps("dtype", dn); + hs.push_back(std::move(h)); + } + } +} + +} // namespace + +bool hand_cases(const Check& ck) { + std::vector hs; + shape_cases(hs); + format_cases(hs); + anchor_cases(hs); + packed_cases(hs); + gen_cases(hs); + qsa_cases(hs); + encoder_cases(hs); + Broken broken; + planes_cases(ck, hs, broken); + + bool ok = true; + int run = 0, fails = 0, absent = 0; + for (Hand& h : hs) { + if (!ck.only_op.empty() && ck.only_op != h.op) continue; + ++run; + switch (h.run(ck)) { + case Hand::PASS: break; + case Hand::FAIL: ok = false; ++fails; break; + case Hand::ABSENT: ++absent; break; + } + } + if (ck.only_op.empty() || ck.only_op == "gdn_recurrent_update") { + /* libr4d's layout over 3-row steps, and a 16 x 16 head up to its 7-token capacity. */ + static const int kSched64[4] = { 1, 2, 3, 1 }, kSched16[4] = { 1, 7, 4, 2 }; + for (const bool small : { false, true }) { + ++run; + const bool good = small ? anchor_replays_per_candidate(ck, 16, 16, 7, kSched16) + : anchor_replays_per_candidate(ck, 64, 64, 3, kSched64); + if (!good) { ok = false; ++fails; } + } + } + if (const int cf = codebook_cases(ck, &run)) { + ok = false; + fails += cf; + } + if (ck.only_op.empty() || ck.only_op == "gemm_nt_q" || ck.only_op == "logits_gemm") { + int lay = 0; + if (!planes_refusals(ck, &lay)) { ok = false; ++fails; } + run += lay > 0; + } + for (const std::string& w : broken.why) { + std::printf(" FAIL a joined weight could not be built: %s\n", w.c_str()); + ok = false; + ++fails; + ++run; + } +#ifndef AVX_CHECK_CORE_DECODER + std::printf(" joined weights: no core decoder in this build; libavx is compared with libref " + "only\n"); +#endif + if (!run) return true; + std::printf(" hand-built: %d checked, %d failed", run - absent, fails); + if (absent) std::printf(", %d for ops %s does not serve", absent, ck.lib->info->name); + std::printf("\n"); + return ok; +} diff --git a/libavx/avx_check_rows.cpp b/libavx/avx_check_rows.cpp index 535c216d..90699997 100644 --- a/libavx/avx_check_rows.cpp +++ b/libavx/avx_check_rows.cpp @@ -1,31 +1,32 @@ -/* avx_check_rows.cpp -- embed_lookup_q over a FILE-BACKED table, the form a model serves it in. +/* avx_check_rows.cpp -- embed_lookup_q over a file-backed table, as a model serves it. * - * The geometry table checks the op against libref over a heap buffer, which the gather reads as - * memory. A table in a container is not read that way: its rows come through a row cache every - * thread shares, with direct reads of the file for the cache's misses and a reader thread a call - * ahead (avx_ngram.cpp). What can go wrong there is WHICH bytes arrive -- a slot claimed twice, a - * row decoded from a slot that was taken over, a wait on a claim that was given up -- and libref - * has no such path to compare against, so the answer here is the file's own bytes. + * The geometry table checks the op against libref over a heap buffer. A table in a container is + * read differently: through a shared row cache, direct file reads for misses and a reader thread + * one call ahead (avx_ngram.cpp). The failures there are about which bytes arrive (a slot claimed + * twice, a row decoded from a slot taken over, a wait on an abandoned claim), and libref has no + * such path, so the reference is the file's own bytes. * - * Two threads play the ranks of one call, as the engine's rank threads do: the same ids, rank 0 - * and 1 of 2, released together, so a thread claims rows, waits on rows the other has claimed, and - * meets its own claim again when an id repeats within a call. Half the ids come from a small hot - * set the cache keeps; the rest from a table four times the cache's 2^19 rows, so sets fill and - * rows are evicted while the other thread may be reading them. Every call also hands over the NEXT - * call's ids as `ahead`, as the engine's prefill does, so the reader thread claims and reads those - * rows while this call's threads are still decoding theirs: a third thread in every race above. + * Two threads act as ranks 0 and 1 of 2 over the same ids, released together, so each claims rows, + * waits on the other's claims and meets its own claim again when an id repeats. Half the ids come + * from a small hot set; the rest from a table four times the cache's 2^19 rows, so sets fill and + * rows are evicted while the other thread may be reading them. Each call also passes the next + * call's ids as `ahead`, so the reader thread races both ranks. * - * Every output row is compared bit for bit with that id's bytes in the file through the call's - * scale, and a padding id must come back as a zero row. The row is 40 codes, so the AVX-512 decode - * takes one full 32-code step and a masked tail. The table is a file in `dir`, and the filesystem - * there decides how the gather aligns its direct reads: by the alignment the filesystem reports - * (ext4, XFS), or by its block size where it reports none (btrfs, and a tmpfs since Linux 6.6). The - * case says which it ran. */ -#include "avx_harness.h" + * Each output row is compared bit for bit with the file's bytes through the call's scale; a padding + * id must give a zero row. Rows are 40 codes, so the AVX-512 decode runs one 32-code step plus a + * masked tail. Direct reads align to the filesystem's reported DIO alignment (ext4, XFS) or to its + * block size where none is reported (btrfs, tmpfs since Linux 6.6); the case reports which. + * + * Each table is written once per process under a name of its own (mkostemp), stays mapped for the + * rest of the process and is unlinked once the gather has opened it: the ISA levels share the file + * reads and differ only in the decode. */ +#include "avx_check.h" #include #include +#include #include +#include #include #include @@ -41,16 +42,30 @@ #include #include -/* EMBED_LOOKUP_Q'S INIT REFUSES A PROCESS THAT MAY NOT MAKE AN io_uring RING, and says why: Docker's - * default seccomp profile answers EPERM to io_uring_setup, and a server started that way used to - * load the whole model and then fail every request as "unsupported". A child process installs the - * same refusal as a seccomp filter and asks the kernel's init, which must refuse a gather into - * bf16 -- the one that reads through the ring -- name the Docker option on stderr, and accept a - * gather into f32, which reads the table as memory. Then this process asks: it must accept where a - * ring can be made and refuse where it cannot, as in a build sandbox. */ -bool ngram_init_case(const Lib& avx) { +/* The errno of creating a ring as the gather does (avx_ngram.cpp: ReadRing::init), or 0. */ +static int ring_probe() { + io_uring_params p{}; + p.flags = IORING_SETUP_SINGLE_ISSUER | IORING_SETUP_DEFER_TASKRUN; + const long ring = syscall(__NR_io_uring_setup, 4096, &p); + if (ring < 0) return errno; + ::close((int)ring); + return 0; +} + +/* Ring memory can count against the locked-memory limit, which every process of the user shares, + * so a run beside other io_uring users can be refused one (ENOMEM) for a while. That is the + * machine, not the gather: the cases name it and skip. */ +static const char* const kRingMemory = "io_uring ring memory refused (ENOMEM); the locked-memory " + "limit is shared with this user's other processes"; + +/* embed_lookup_q's init must refuse a process that cannot create an io_uring ring, and say why + * (Docker's default seccomp profile returns EPERM for io_uring_setup). A child installs that + * refusal as a seccomp filter; init must then refuse a bf16 gather (read through the ring), name + * the Docker option on stderr, and accept an f32 gather (read as memory). This process must then be + * accepted where a ring can be created and refused where it cannot, as in a build sandbox. */ +bool ngram_init_case(const Lib& lib) { const char* what = "embed_lookup_q's init"; - const RadKernelInfo* r = avx.row("embed_lookup_q"); + const RadKernelInfo* r = lib.row("embed_lookup_q"); if (!r || !r->init) { std::printf(" %s: the row has no init\n", what); return false; @@ -114,53 +129,43 @@ bool ngram_init_case(const Lib& avx) { std::printf(" %s, where io_uring is refused: refused, naming the Docker option\n", what); } - io_uring_params p{}; - const long ring = syscall(__NR_io_uring_setup, 1, &p); - const bool here = ring >= 0; - if (here) ::close((int)ring); + /* The init tests the ring once per process, so the probes bracket it. */ + const int before = ring_probe(); void* inst = nullptr; const int st = r->init(bf16, 2, 0, 1, &inst); + const int after = ring_probe(); + if (st == RAD_E_UNSUPPORTED && (before == ENOMEM || after == ENOMEM)) { + std::printf(" %s, in this process: SKIPPED -- %s\n", what, kRingMemory); + return ok; + } + const bool here = before == 0; const bool right = here ? st == RAD_OK : st == RAD_E_UNSUPPORTED; std::printf(" %s, in this process (io_uring %s): %s\n", what, here ? "available" : "refused", right ? (here ? "accepted" : "refused") : "FAIL"); return ok && right; } -bool row_gather_case(const Lib& avx, const std::string& dir, int64_t calls, bool verbose, - bool bf16) { - const RadKernelInfo* r = avx.row("embed_lookup_q"); - const char* what = bf16 ? "embed_lookup_q from a file, bf16 table" : "embed_lookup_q from a file"; - if (!r || !r->launch) { - std::printf(" %s: no row\n", what); - return false; - } - /* A bf16 table is twice the bytes a row and is read with no scale: its rows are their output, - * so what this checks there is the cache and the reads at a row size the E4M3 table never - * has. */ - /* The gather's misses are io_uring reads, and a sandbox can forbid io_uring outright -- Docker's - * default seccomp profile does. There the gather refuses every call by design, so the case - * says why it cannot run rather than counting a refusal per call. */ - { - io_uring_params p{}; - const long ring = syscall(__NR_io_uring_setup, 1, &p); - if (ring < 0) { - std::printf(" %s: SKIPPED -- io_uring is unavailable here (%s)\n", what, - std::strerror(errno)); - return true; - } - ::close((int)ring); - } - const int64_t n = 40, V = int64_t(1) << 21, M = 512, hot = 4096; - const int64_t rb = bf16 ? 2 * n : n; - const float scale = 0.375f; +/* A table file, written and mapped once per process. */ +struct RowTable { + enum { OK, SKIP, FAIL } state = FAIL; + std::string path, note; /* note: the skip or failure reason, or the read granule */ + const uint8_t* tab = nullptr; + bool unlinked = false; +}; - const std::string path = dir + "/rad-avx-check-rows.bin"; +static RowTable* row_table(const std::string& dir, bool bf16, int64_t V, int64_t rb) { + static std::map, RowTable> tables; + const auto key = std::make_pair(dir, bf16); + if (auto it = tables.find(key); it != tables.end()) return &it->second; + RowTable& t = tables[key]; + + /* A name of its own, so a concurrent run cannot truncate the file under this one's mapping. */ + std::string path = dir + "/rad-avx-check-rows.XXXXXX"; uint64_t x = 0x9e3779b97f4a7c15ull; auto rnd = [&x]() { x ^= x << 13; x ^= x >> 7; x ^= x << 17; return x; }; { - const int fd = ::open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); - if (fd < 0) { std::printf(" %s: cannot create %s\n", what, path.c_str()); - return false; } + const int fd = ::mkostemp(path.data(), O_CLOEXEC); + if (fd < 0) { t.note = "cannot create " + path; return &t; } std::vector chunk(1 << 16); bool wrote = true; for (int64_t done = 0; done < V * rb && wrote; done += (int64_t)(chunk.size() * 8)) { @@ -170,13 +175,11 @@ bool row_gather_case(const Lib& avx, const std::string& dir, int64_t calls, bool } wrote = wrote && ::fsync(fd) == 0; ::close(fd); - if (!wrote) { ::unlink(path.c_str()); std::printf(" %s: short write\n", what); - return false; } + if (!wrote) { ::unlink(path.c_str()); t.note = "short write"; return &t; } } - /* A filesystem without direct I/O -- one that refuses the open, as a tmpfs did before Linux - * 6.6, or one that reports the file has none -- is one the gather refuses by design, so the - * case cannot run there; it says so rather than counting a refusal per call. Every other - * filesystem the gather has to read, with or without a reported alignment. */ + /* The gather refuses a filesystem without direct I/O (the O_DIRECT open fails, as on tmpfs + * before Linux 6.6, or it reports a zero DIO alignment), so the case is skipped there. Every + * other filesystem must work, with or without a reported alignment. */ bool reported = false; { const int dfd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC | O_DIRECT); @@ -188,18 +191,62 @@ bool row_gather_case(const Lib& avx, const std::string& dir, int64_t calls, bool if (dfd >= 0) ::close(dfd); if (!dio) { ::unlink(path.c_str()); - std::printf(" %s: SKIPPED -- %s cannot do direct I/O\n", what, dir.c_str()); - return true; + t.state = RowTable::SKIP; + t.note = dir + " cannot do direct I/O"; + return &t; } } - const char* granule = reported ? "the alignment the filesystem reports" - : "no alignment reported, read by the block size"; const int fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC); void* map = fd < 0 ? MAP_FAILED : mmap(nullptr, (size_t)(V * rb), PROT_READ, MAP_SHARED, fd, 0); if (fd >= 0) ::close(fd); - if (map == MAP_FAILED) { ::unlink(path.c_str()); std::printf(" %s: mmap\n", what); - return false; } - const uint8_t* tab = static_cast(map); + if (map == MAP_FAILED) { ::unlink(path.c_str()); t.note = "mmap"; return &t; } + /* The mapping stays for the life of the process. libavx resolves a table to its file once, by + * the mapping's address range (avx_ngram.cpp: table_file), so no other file may be mapped at + * these addresses while the process runs. */ + t.tab = static_cast(map); + t.path = path; + t.note = reported ? "the alignment the filesystem reports" + : "no alignment reported, read by the block size"; + t.state = RowTable::OK; + return &t; +} + +bool row_gather_case(const Lib& lib, const std::string& dir, int64_t calls, uint64_t seed, + bool verbose, bool bf16) { + const RadKernelInfo* r = lib.row("embed_lookup_q"); + const char* what = bf16 ? "embed_lookup_q from a file, bf16 table" : "embed_lookup_q from a file"; + if (!r || !r->launch) { + std::printf(" %s: no row\n", what); + return false; + } + /* A bf16 table has twice the row bytes and no scale, so it exercises the cache and the reads + * at a row size the E4M3 table never has. */ + /* Misses are io_uring reads. Where a sandbox forbids io_uring the gather refuses every call by + * design, so the case is skipped with the reason. */ + if (const int e = ring_probe()) { + std::printf(" %s: SKIPPED -- %s\n", what, + e == ENOMEM ? kRingMemory + : (std::string("io_uring is unavailable here (") + + std::strerror(e) + ")").c_str()); + return true; + } + const int64_t n = 40, V = int64_t(1) << 21, M = 512, hot = 4096; + const int64_t rb = bf16 ? 2 * n : n; + const float scale = 0.375f; + + RowTable* rt = row_table(dir, bf16, V, rb); + if (rt->state == RowTable::SKIP) { + std::printf(" %s: SKIPPED -- %s\n", what, rt->note.c_str()); + return true; + } + if (rt->state != RowTable::OK) { + std::printf(" %s: %s\n", what, rt->note.c_str()); + return false; + } + const char* granule = rt->note.c_str(); + const uint8_t* tab = rt->tab; + uint64_t x = seed ? seed : 1; + auto rnd = [&x]() { x ^= x << 13; x ^= x >> 7; x ^= x << 17; return x; }; std::vector hotset((size_t)hot); for (auto& h : hotset) h = (int32_t)(rnd() % (uint64_t)V); @@ -229,7 +276,8 @@ bool row_gather_case(const Lib& avx, const std::string& dir, int64_t calls, bool }; std::barrier<> go(2); - int64_t bad[2] = {0, 0}, refused[2] = {0, 0}; + int64_t bad[2] = {0, 0}, refused[2] = {0, 0}, failed[2] = {0, 0}; + /* Each rank thread makes its own ring on its first call. */ auto rank = [&](int rk) { uint16_t sc = rad_f32_to_bf16(scale); std::vector out((size_t)(M * n)); @@ -248,11 +296,15 @@ bool row_gather_case(const Lib& avx, const std::string& dir, int64_t calls, bool a.rank = rk; a.world_size = 2; for (int64_t c = 0; c < calls; ++c) { ts[0].data = &ids[(size_t)(c * M)]; - /* The last call has nothing ahead of it, and says so with an absent operand. */ + /* The last call passes no `ahead` (absent operand). */ ts[4].data = c + 1 < calls ? &ids[(size_t)((c + 1) * M)] : nullptr; std::fill(out.begin(), out.end(), (uint16_t)0xdead); go.arrive_and_wait(); - if (r->launch(&a, nullptr) != RAD_OK) { ++refused[rk]; continue; } + if (const int rc = r->launch(&a, nullptr); rc != RAD_OK) { + ++refused[rk]; + if (rc != RAD_E_UNSUPPORTED) ++failed[rk]; + continue; + } for (int64_t m = 0; m < M; ++m) { const int32_t id = ids[(size_t)(c * M + m)]; for (int64_t i = 0; i < n; ++i) { @@ -264,19 +316,33 @@ bool row_gather_case(const Lib& avx, const std::string& dir, int64_t calls, bool } } }; - std::thread t0(rank, 0), t1(rank, 1); - t0.join(); - t1.join(); - /* THE ADDRESS RANGE STAYS RESERVED. libavx resolves a table to its file once, by the address - * range of its mapping, for the life of the process (avx_ngram.cpp, table_file) -- the - * engine's container mapping is one. A case that unmapped here could have the next case's file - * mapped at the same addresses, and the gather would read this file through the fd it kept: - * every row of the next case wrong, on whichever run the kernel happens to reuse the range. - * An inaccessible anonymous mapping over the same range frees the file and keeps the range. */ - if (mmap(map, (size_t)(V * rb), PROT_NONE, MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS | - MAP_NORESERVE, -1, 0) == MAP_FAILED) - munmap(map, (size_t)(V * rb)); - ::unlink(path.c_str()); + auto race = [&] { + bad[0] = bad[1] = refused[0] = refused[1] = failed[0] = failed[1] = 0; + std::thread t0(rank, 0), t1(rank, 1); + t0.join(); + t1.join(); + }; + /* Calls refused as unsupported with every delivered row right mean a ring the kernel would + * not make. Under contention for ring memory the case runs again on fresh threads, which make + * fresh rings, up to three times; it is skipped by name only if a probe saw ENOMEM meanwhile. + * Refusals without that evidence fail. */ + bool pressure = false; + for (int attempt = 0; attempt < 3; ++attempt) { + race(); + const bool ring_refused = refused[0] + refused[1] && bad[0] + bad[1] == 0 && + failed[0] + failed[1] == 0; + if (!ring_refused) break; + if (ring_probe() == ENOMEM) pressure = true; + } + /* The gather holds its own descriptor from the first call on, so the name can go. */ + if (!rt->unlinked) { + ::unlink(rt->path.c_str()); + rt->unlinked = true; + } + if (pressure && refused[0] + refused[1] && bad[0] + bad[1] + failed[0] + failed[1] == 0) { + std::printf(" %s: SKIPPED -- %s\n", what, kRingMemory); + return true; + } const bool pass = bad[0] + bad[1] + refused[0] + refused[1] == 0; if (verbose || !pass) diff --git a/libavx/avx_common.h b/libavx/avx_common.h index 4907ee14..99a2f477 100644 --- a/libavx/avx_common.h +++ b/libavx/avx_common.h @@ -1,31 +1,20 @@ -/* avx_common.h -- what every kernel in this plugin needs and the ABI does not give it. +/* avx_common.h -- helpers every kernel in this plugin needs that the ABI does not provide. * - * Deliberately thin. rad_plugin.h already carries the parameter readers, the absent-operand rule, - * the row-pitch helper and every narrowing conversion, and its header explains at length why those - * belong in the ABI rather than once per plugin. This plugin calls them. What is here is the three - * things that are genuinely this plugin's: + * rad_plugin.h already has the parameter readers, the absent-operand rule, the row-pitch helper + * and the narrowing conversions. This header adds three things: * - * THE SCRATCH ARENA. Every kernel converts a row to f32 before it computes (avx_vec.h), so every - * kernel needs a row of scratch. RadArgs::scratch would be the ABI's answer and it is the wrong - * one here: it is sized once at declare from the band's upper bound, it is one buffer, and this - * plugin runs its outer loop under OpenMP -- so every thread needs its own, and the number of - * threads is not known at declare. A thread_local arena that grows to a high-water - * mark and is then reused is allocation-free on the hot path, which is what the ABI's "must not - * allocate" is protecting, and it is what libref does too (it holds std::vector in its kernels). - * The growth is logged under AVX_TRACE so a kernel that reallocates per call is visible. + * Scratch arena. Every kernel converts rows to f32 before computing (avx_vec.h), so it needs row + * scratch. RadArgs::scratch does not fit: it is one buffer sized at declare, while the outer loop + * runs under OpenMP with a thread count unknown at declare. A thread_local arena grows to a + * high-water mark and is reused, so the hot path does not allocate (libref does the same). * - * THE OPERAND PREAMBLE. Sixty-eight launches open by fetching n operands, refusing if a required - * one is absent, and reading the extents off the tensors rather than off the parameters -- - * libref/ref_ops.h explains why that rule exists and it is the same rule here: a ranged parameter - * is collapsed to a BAND, so a loop bounded by `M` runs to the band's upper bound and walks off - * the arena. Every extent in this plugin comes from a RadTensor. + * Operand addressing. Every extent comes from a RadTensor, never from a parameter: a ranged + * parameter is collapsed to a band, so a loop bounded by `M` would run to the band's upper bound + * and walk off the arena (libref/ref_ops.h). * - * THE THREADING DECISION, in one place. OpenMP over the OUTER dimension only, one thread owning - * whole output rows, no reduction() clause anywhere -- the same rule libref states, for a - * different reason. libref wants bit-identical answers across thread counts because it is the - * oracle. This plugin wants them because a kernel whose answer moves with the machine's load is - * a kernel no measurement can rank: two runs of the same binary would differ, and the difference - * would be read as whatever change was under test. + * Threading. OpenMP over the outer dimension only, one thread owning whole output rows, no + * reduction() clause. Results are bit-identical across thread counts, so two runs of the same + * binary agree regardless of machine load and measurements stay comparable. */ #ifndef RAD_AVX_COMMON_H #define RAD_AVX_COMMON_H @@ -38,24 +27,44 @@ #include #include +/* Scalar transcendentals as libref evaluates them: in double, rounded once to float. glibc's float + * routines differ between releases (2.41 made log1pf, tanhf and erff correctly rounded), so a float + * call would agree with libref on one host and not on another; the double routines are stable, + * and the rounded float is the same everywhere. The vector paths (avx_vec.h) are checked to a + * tolerance and do not use these. */ +static inline float sc_exp(float x) { return (float)std::exp((double)x); } +static inline float sc_log(float x) { return (float)std::log((double)x); } +static inline float sc_log1p(float x) { return (float)std::log1p((double)x); } +static inline float sc_tanh(float x) { return (float)std::tanh((double)x); } +static inline float sc_erf(float x) { return (float)std::erf((double)x); } +static inline float sc_sin(float x) { return (float)std::sin((double)x); } +static inline float sc_cos(float x) { return (float)std::cos((double)x); } +static inline float sc_pow(float b, float e) { return (float)std::pow((double)b, (double)e); } + #ifdef _OPENMP #include #include +#include #include -#include -/* THE TEAM IS ONE THREAD A PHYSICAL CORE, not one a logical CPU. These kernels are FMA- or - * bandwidth-bound, so an SMT sibling adds next to nothing to them -- and the engine runs threads - * of its own beside the team (a worker per stream, the scheduler, the HTTP server). A team as - * wide as the logical CPU count leaves those nowhere to run but on a core a team thread is - * spinning on, and a team barrier then waits for a descheduled thread: measured on a 16-core, - * 32-thread part, an encoder step of 576 tokens took 0.75 s at 32 threads and 0.09 s at 16. - * Counted over the process's affinity mask, so a pinned or containerised engine sizes its team to - * what it was given; OMP_NUM_THREADS, when set, is the operator's and wins, and a thread that - * asked OpenMP for fewer (omp_set_num_threads) gets fewer. */ +/* The checker's override, set through avx_par_force (avx_isa.h): 0, or the team size every + * parallel region takes whatever its work threshold. Defined in avx_dispatch.cpp; one relaxed load + * per region. */ +extern std::atomic avx_par_threads; +static inline bool avx_par_forced() { + return avx_par_threads.load(std::memory_order_relaxed) > 0; +} +/* One team thread per physical core, not per logical CPU. These kernels are FMA- or + * bandwidth-bound, so an SMT sibling adds little, and the engine runs its own threads (stream + * workers, scheduler, HTTP server) beside the team. A team as wide as the logical CPU count makes + * team barriers wait on descheduled threads: on a 16-core, 32-thread part a 576-token encoder + * step takes 0.75 s at 32 threads and 0.09 s at 16. Cores are counted over the process affinity + * mask, so a pinned or containerised engine uses what it was given. OMP_NUM_THREADS, when set, + * wins, and a thread that asked for fewer (omp_set_num_threads) gets fewer. */ static inline int avx_team_size() { - /* The physical core count is a property of the process and counted once; the OpenMP request - * is the calling thread's and read every time, so a caller that asks for fewer threads - * (omp_set_num_threads, as the benchmark does for its single-thread figures) gets them. */ + if (const int forced = avx_par_threads.load(std::memory_order_relaxed); forced > 0) + return forced; + /* The core count is per process and computed once; the OpenMP request is per calling thread + * and read on every call (the benchmark lowers it for single-thread figures). */ static const int cores = [] { if (const char* e = std::getenv("OMP_NUM_THREADS"); e && *e) return 0; cpu_set_t set; @@ -83,15 +92,13 @@ static inline int avx_team_size() { } #define AVX_PRAGMA(x) _Pragma(#x) #define AVX_PARALLEL_FOR AVX_PRAGMA(omp parallel for schedule(static) num_threads(avx_team_size())) -/* THE OUTER LOOP IS WORTH A TEAM ONLY WHEN THERE IS ENOUGH WORK TO PAY FOR STARTING ONE, and the - * `if` clause is how that is said without writing the serial loop twice. A fork/join costs a few - * microseconds; an op below the threshold spends more time in the barrier than in the arithmetic, - * which is the same shape of problem a small device dispatch has, one level down. The crossover is - * measured by `rad-avx-bench --threads`. - * - * `cond` is pasted into the pragma text, so it must contain no comma. */ +/* Parallelise the outer loop only when the work pays for a fork/join, which costs a few + * microseconds; `rad-avx-bench --threads` measures the crossover. `cond` is pasted into the + * pragma text, so it must contain no comma. avx_par_force overrides it, so the checker runs every + * parallel body with several threads at its small geometries. */ #define AVX_PARALLEL_FOR_IF(cond) \ - AVX_PRAGMA(omp parallel for schedule(static) if(cond) num_threads(avx_team_size())) + AVX_PRAGMA(omp parallel for schedule(static) if((cond) || avx_par_forced()) \ + num_threads(avx_team_size())) #else #define AVX_PARALLEL_FOR #define AVX_PARALLEL_FOR_IF(cond) @@ -107,58 +114,20 @@ namespace avx { * Aligned to 64 so a 512-bit aligned load is legal off it at every level. Returns a buffer of at * least `n` floats, valid until the next call on this thread that asks for more. */ float* scratch_f32(size_t n); -/* A second and third independent buffer, for kernels that need two rows live at once (every gated - * op: gate and up, a and b, x and residual). Separate functions rather than an index so the call - * site says which buffer it means. */ +/* Independent second and third buffers, for kernels with several rows live at once (gate and up, + * a and b, x and residual). */ float* scratch_f32_b(size_t n); float* scratch_f32_c(size_t n); void* scratch_raw(size_t bytes); -/* ================================================================== operand preamble */ -/* Fetch the first `n` operands into `out`, returning 0 if any is absent. The array is indexed - * positionally and an absent OPTIONAL operand past `n` is fetched with rad_arg_in directly. */ -static inline int take(const RadArgs* a, int n, const RadTensor** out) { - for (int i = 0; i < n; ++i) { - out[i] = rad_arg_in(a, i); - if (!out[i]) return 0; - } - return 1; -} - -/* The (rows, lastdim) reading of a tensor, and the pitch between rows. Three lines every kernel - * would otherwise write. */ -struct Plane { - void* p; - uint32_t dt; - int64_t rows, n, pitch; -}; - -static inline Plane plane(const RadTensor* t) { - Plane s; - s.p = t->data; - s.dt = t->dtype; - s.rows = rad_tensor_rows(t); - s.n = rad_tensor_lastdim(t); - s.pitch = rad_tensor_row_pitch(t); - return s; -} - -/* Element offset of row r. Strides are in ELEMENTS (rad_types.h), so this is what a caller adds to - * a typed pointer -- never a byte count, which is what makes it safe for W4/W2 where a byte count - * would be fractional. */ -static inline int64_t row_off(const Plane& s, int64_t r) { return r * s.pitch; } - /* ================================================================== libref's addressing, exactly * - * THESE ARE COPIED FROM libref/ref_common.h AND THEY HAVE TO BE. They are not conveniences, they - * are the ADDRESSING CONTRACT: which bytes an operand's element (r, i) lives at, how a rank-3 - * tensor is read as [rows, cols], and what a strided view means. A plugin that computed the right - * arithmetic over the wrong bytes would be checked against the oracle and would fail in a way that - * looks like a numerical bug, which is the most expensive kind to chase. + * Copied from libref/ref_common.h and must stay identical. They are the addressing contract: + * where element (r, i) lives, how a rank-3 tensor reads as [rows, cols], and what a strided view + * means. Diverging here fails the oracle check in a way that looks like a numerical bug. * - * `numel` returning 0 for a null-data tensor is part of it: that is how libref's shape checks - * refuse an absent required operand, and a copy that returned the product of the shape instead - * would accept the call and fault. */ + * `numel` returns 0 for a null-data tensor; libref's shape checks rely on that to refuse an absent + * required operand. */ static inline int64_t numel(const RadTensor* t) { if (!t || !t->data || t->rank == 0) return 0; int64_t n = 1; @@ -188,9 +157,9 @@ static inline int64_t offlin(const RadTensor* t, int64_t lin) { return off; } -/* The element offset of logical row `r` read as [rows, cols]. The leading axes are walked with - * their OWN strides, so a [T, H, V] tensor read as [T*H, V] lands correctly even when H's stride - * is not V -- which is exactly the fused-projection column slice docs/OPS.md warns about. */ +/* Element offset of logical row `r` read as [rows, cols]. Leading axes use their own strides, so + * a [T, H, V] tensor read as [T*H, V] is correct even when H's stride is not V (the + * fused-projection column slice in docs/OPS.md). */ static inline int64_t rowoff(const RadTensor* t, int64_t r, int64_t cols) { if (t->rank >= 2 && t->shape[t->rank - 1] == cols) { int64_t off = 0; @@ -207,17 +176,17 @@ static inline int64_t rowoff(const RadTensor* t, int64_t r, int64_t cols) { static inline int64_t rows_of(const RadTensor* t, int64_t n) { return n > 0 ? numel(t) / n : 0; } -/* THE OPERAND'S EXTENT, WITH THE RANGED PARAMETER AS A CEILING. libref/ref_common.h's band_rows, - * copied for the reason the header gives: `M`, `numel` and `q_len` arrive as the band's upper - * bound, so the call's row count is the operand's and a count above the band is a caller bug. */ +/* The operand's row count, with the ranged parameter as a ceiling (libref/ref_common.h: + * band_rows). `M`, `numel` and `q_len` arrive as the band's upper bound, so the count comes from + * the operand; a count above the band is a caller bug and yields 0. */ static inline int64_t band_rows(int64_t from_operand, int64_t band) { if (from_operand <= 0) return 0; return (band > 0 && from_operand > band) ? 0 : from_operand; } -/* THE BLOCK A SCALE GRID OF `blocks` PIECES IMPLIES OVER `ext` ELEMENTS -- libref/ref_gemm.h's - * grid_block, which says why it is the power of two whose ceiling division gives `blocks` and not - * the quotient ext / blocks: a grid's last block may be partial. */ +/* Block size implied by a scale grid of `blocks` pieces over `ext` elements (libref/ref_gemm.h: + * grid_block): the power of two whose ceiling division gives `blocks`, not ext / blocks, because + * the last block may be partial. */ static inline int64_t grid_block(int64_t ext, int64_t blocks) { if (ext <= 0) return 1; if (blocks <= 1) return ext; @@ -227,11 +196,10 @@ static inline int64_t grid_block(int64_t ext, int64_t blocks) { return (ext + b - 1) / b == blocks ? b : lo; } -/* `row_stride`: which axis carries a row of `cols` elements, at whatever rank the operand arrived - * in -- libref/ref_gemm.h's rule, copied for the header's reason. A rank-2 operand is not dense - * because it is rank 2: the engine hands attention a COLUMN SLICE of the fused QKV plane, - * [tokens, kv_heads * head_dim] with the whole projection's width as its row stride, and deriving - * the stride from the shape reads every token after the first out of the previous token's row. */ +/* Stride between rows of `cols` elements, at any rank (libref/ref_gemm.h's rule). Rank 2 does not + * imply dense: attention receives a column slice of the fused QKV plane, [tokens, kv_heads * + * head_dim] with the full projection width as row stride, so the stride must not be derived from + * the shape. */ static inline int64_t row_stride(const RadTensor* t, int64_t cols) { if (!t || t->rank < 2) return cols; int64_t span = 1; @@ -243,15 +211,13 @@ static inline int64_t row_stride(const RadTensor* t, int64_t cols) { return t->stride[t->rank - 2]; } -/* ONE ELEMENT, AS f32 AND BACK, with the two things the ABI's accessors do not do. - * - * THE PACKED CODES. rad_load_f32 returns 0 for W4, W2 and MXFP4 -- its contract says a dtype it - * cannot read is a refusal and not a value -- so every strided or odd-offset read of a packed - * weight that falls off the row converter would decode as zeros. The codes are libref's - * (ref_common.h: w4_code, w2_code, mxfp4_code), the same ones row_to_f32 unpacks in bulk. - * - * THE INTEGER STORE ROUNDS TO NEAREST-EVEN AND SATURATES, as libref's st_dt does, where - * rad_store_f32 truncates and converts out-of-range values with a plain cast. A NaN stores 0. */ +/* One element as f32 and back: + * - Packed codes. rad_load_f32 returns 0 for W4, W2 and MXFP4 (an unreadable dtype is a + * refusal), so strided or odd-offset reads of packed weights decode here, with libref's codes + * (ref_common.h: w4_code, w2_code, mxfp4_code), the same ones row_to_f32 unpacks in bulk. + * - Integer and packed-code stores to the dtypes listed in st_elem round to the nearest code and + * saturate, NaN storing 0, as libref's st_dt does; every other dtype (u16, bool, the floats) + * is rad_store_f32's. */ static inline float ld_elem(const void* p, uint32_t dt, int64_t i) { switch (dt) { case RAD_I4: { @@ -282,16 +248,46 @@ static inline double round_sat(float v, double lo, double hi) { return r < lo ? lo : (r > hi ? hi : r); } +/* A packed code's low `bits` into element `i` of a bit stream, lowest bits first. The atomics + * touch only this element's bits, so rows written by different threads may share a byte. */ +static inline void st_packed(void* p, int64_t i, int bits, unsigned c) { + const int per = 8 / bits; + uint8_t* b = (uint8_t*)p + i / per; + const int sh = (int)(i % per) * bits; + const uint8_t mask = (uint8_t)(((1u << bits) - 1u) << sh); + __atomic_fetch_and(b, (uint8_t)~mask, __ATOMIC_RELAXED); + __atomic_fetch_or(b, (uint8_t)((c << sh) & mask), __ATOMIC_RELAXED); +} + +/* The e2m1 code nearest `v`, ties to the even code, saturating at 6; NaN is +0 (libref's). */ +static inline unsigned e2m1_code(float v) { + static const float kMag[8] = { 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f }; + if (v != v) return 0u; + const unsigned sign = std::signbit(v) ? 8u : 0u; + const float a = std::fabs(v); + unsigned best = 0; + for (unsigned c = 1; c < 8; ++c) { + const float d = std::fabs(kMag[c] - a), db = std::fabs(kMag[best] - a); + if (d < db || (d == db && (c & 1u) == 0u)) best = c; + } + return sign | best; +} + static inline void st_elem(void* p, uint32_t dt, int64_t i, float v) { switch (dt) { + /* Packed codes: the nearest code, saturated, so a code ld_elem read stores back as itself + * (a gather or scatter of packed rows moves them exactly). */ + case RAD_I4: st_packed(p, i, 4, (unsigned)(int)round_sat(v, -8.0, 7.0) & 0xFu); break; + case RAD_I2: st_packed(p, i, 2, (unsigned)(int)round_sat(v, -2.0, 1.0) & 0x3u); break; + case RAD_FP4E2M1: st_packed(p, i, 4, e2m1_code(v)); break; case RAD_I8: ((int8_t*)p)[i] = (int8_t)round_sat(v, -128.0, 127.0); break; case RAD_U8: ((uint8_t*)p)[i] = (uint8_t)round_sat(v, 0.0, 255.0); break; case RAD_I16: ((int16_t*)p)[i] = (int16_t)round_sat(v, -32768.0, 32767.0); break; case RAD_I32: ((int32_t*)p)[i] = (int32_t)round_sat(v, -2147483648.0, 2147483647.0); break; case RAD_U32: ((uint32_t*)p)[i] = (uint32_t)round_sat(v, 0.0, 4294967295.0); break; case RAD_I64: { - /* 2^63 is the first float past the range, so the bound is a comparison, not a clamp - * value a double could hold. */ + /* 2^63 is the first float past the int64 range, so it is tested by comparison + * rather than used as a clamp value. */ const double r = round_sat(v, -9223372036854775808.0, 9223372036854775808.0); ((int64_t*)p)[i] = r >= 9223372036854775808.0 ? INT64_MAX : (int64_t)r; break; @@ -305,18 +301,31 @@ static inline void stt(const RadTensor* t, int64_t off, float v) { st_elem(t->data, t->dtype, off, v); } -/* IS THIS OPERAND'S ROW DENSE? The whole vectorised path is predicated on it: a row whose elements - * are one apart can be converted with one call and then read as a flat f32 array, and a row whose - * elements are not has to go through the strided gather. Almost every operand in a real step is - * dense; the exceptions are named in docs/OPS.md and are a handful of sites. */ +/* `v` rounded through a store and load of dtype `dt` (libref's round_dt). */ +static inline float narrow1(uint32_t dt, float v) { + uint32_t buf[2] = { 0, 0 }; + rad_store_f32(buf, dt, 0, v); + return rad_load_f32(buf, dt, 0); +} + +/* True when the row's elements are contiguous. A dense row converts with one call and is read as + * a flat f32 array; any other row goes through the strided gather. Nearly every operand is dense; + * docs/OPS.md names the exceptions. */ static inline bool dense_row(const RadTensor* t) { return laststride(t) == 1; } +/* The gemm_nt_q dtypes whose activation is quant_act_i8's, codes in the int8 WMMA's step order + * (libref/ref_common.h). */ +static inline bool i8_steps_dtype(const char* dt) { + static const char* const kDtypes[] = { "w4a8", "w4a8_asym", "w8a8", "w2a8" }; + for (const char* d : kDtypes) + if (dt && std::strcmp(dt, d) == 0) return true; + return false; +} + /* ================================================================== parameters - * Deliberately LAXER than rad_param_geti, and for libref's reason rather than a different one: a - * tool or a test may call a launch directly with no declare in front of it to enforce the type, so - * a range and a string spelling of an integer are both read rather than refused. The ABI's own - * reader is right for a kernel reached through declare and wrong for one reached through a - * checker, and this plugin is reached through both. */ + * Laxer than rad_param_geti, as in libref: a tool or test may call a launch directly with no + * declare to enforce the type, so a range or a string spelling of an integer is read rather than + * refused. */ static inline const RadParam* p_find(const RadArgs* a, const char* k) { return a ? rad_param_find(a->p, a->n_p, k) : nullptr; } @@ -347,6 +356,8 @@ static inline float p_f32(const RadArgs* a, const char* k, float dflt) { return dflt; } +/* An enumerated parameter spelled as a name or libr4d's integer; an unknown name is -1, for the + * caller to refuse (as libref). */ static inline int p_enum(const RadArgs* a, const char* k, const char* const* names, int n, int dflt) { const RadParam* p = p_find(a, k); @@ -354,7 +365,7 @@ static inline int p_enum(const RadArgs* a, const char* k, const char* const* nam if (p->kind == RAD_P_STR && p->sval) { for (int i = 0; i < n; ++i) if (names[i] && std::strcmp(names[i], p->sval) == 0) return i; - return dflt; + return -1; } if (p->kind == RAD_P_INT) return (int)p->ival; return dflt; @@ -388,8 +399,8 @@ static inline void st_int_dt(uint32_t dt, void* p, int64_t i, int64_t v) { static inline int64_t ldi(const RadTensor* t, int64_t off) { return ld_int_dt(t->dtype, t->data, off); } -/* Bytes of element i for a dtype whose element is not a whole byte. Only the packed weight codes - * need it and they are always read through row_to_f32, but `dequant` addresses a group start. */ +/* Address of the byte holding element i, for dtypes whose element is not a whole byte. Packed + * codes are otherwise read through row_to_f32; `dequant` uses this to address a group start. */ static inline const void* byte_at(const void* base, uint32_t dt, int64_t i) { const uint8_t* b = (const uint8_t*)base; switch (dt) { diff --git a/libavx/avx_dispatch.cpp b/libavx/avx_dispatch.cpp index dc56d3c7..a4aac9e3 100644 --- a/libavx/avx_dispatch.cpp +++ b/libavx/avx_dispatch.cpp @@ -1,33 +1,15 @@ -/* avx_dispatch.cpp -- the one translation unit that may not contain a vector instruction. +/* avx_dispatch.cpp -- ISA detection and level selection; must contain no vector instruction. * - * ============================== THE RULE THIS FILE EXISTS TO ENFORCE ============================== + * Every other object in the plugin is built with -mavx/-mavx2/-mavx512f and may only execute once + * this file has established that the CPU supports it. So this file is built with no -m flags, set + * as a target property in CMakeLists.txt. Avoiding intrinsics is not enough: under -mavx512f the + * compiler may auto-vectorise anything, such as the table copies below, and a SIGILL here would + * hit before main on exactly the machines the fallback is for. * - * Everything else in this plugin is compiled with -mavx2 or -mavx512f and therefore may not be - * EXECUTED until something has established that the machine can run it. This file is what - * establishes it, so it is compiled with no -m flags at all, and CMakeLists.txt states that as a - * property of the target rather than leaving it to habit. - * - * The failure mode if this is got wrong is worth naming because it is not a wrong answer, it is a - * SIGILL in the fallback that exists to prevent SIGILLs, and it happens before main, on whichever - * machine the build was not tested on. A compiler is free to auto-vectorise anything it likes in a file - * compiled with -mavx512f -- including the table-of-function-pointers copy below, which is exactly - * the shape a vectoriser likes -- so "this function contains no intrinsics" is not the same claim - * as "this function contains no AVX-512", and only the flags on the object give the second one. - * - * ============================== WHAT IS DETECTED, AND WHY __builtin_cpu_supports ============================== - * - * Raw CPUID is not enough and the reason is the OS, not the CPU. AVX and AVX-512 add architectural - * state (YMM, then ZMM and the mask registers) that the kernel must agree to save across a context - * switch; it signals that through XCR0, read with XGETBV. A CPU may enumerate AVX-512 in CPUID - * while the OS has left the ZMM state disabled -- a VM with a restricted feature mask, an older - * kernel, a hypervisor hiding it -- and using AVX-512 then faults on the first instruction. - * __builtin_cpu_supports does the XGETBV check; a hand-rolled CPUID dispatch usually does not, and - * that omission is the single most common way this kind of code is wrong. - * - * AVX-512 IS ALSO NOT ONE FEATURE. The check below is the conjunction of F, BW, DQ and VL because - * the kernels use all four: BW for the byte and word shuffles the bf16 pack needs, DQ for the - * 64-bit integer forms, VL for the 128/256-bit encodings of the AVX-512 instructions. A Knights - * Landing has F and not the others, and a kernel that tested F alone would fault on it. + * Detection uses __builtin_cpu_supports, which also reads XCR0 via XGETBV: the OS must enable + * YMM/ZMM/mask state, and a VM or older kernel may leave it off while CPUID still reports AVX-512. + * AVX-512 needs F, BW, DQ and VL together: BW for the byte and word shuffles of the bf16 pack, DQ + * for the 64-bit integer forms, VL for the 128/256-bit encodings. */ #include "avx_isa.h" #include "avx_common.h" @@ -35,15 +17,14 @@ #include #include #include +#include #include #include /* ================================================================== the fp8 decode tables * - * Built at load from the ABI's OWN converters, not typed out. A typed-out table is a second - * definition of the format and can drift from rad_fp8e4m3_to_f32, which is exactly what - * rad_plugin.h's header argues against at length. 256 calls at startup cost nothing and cannot - * disagree. */ + * Built at load from the ABI's converters rather than typed out, so they cannot drift from + * rad_fp8e4m3_to_f32 / rad_fp8e5m2_to_f32. */ extern "C" { float avx_fp8e4m3_tab[256] = { 0 }; float avx_fp8e5m2_tab[256] = { 0 }; } @@ -54,31 +35,34 @@ static void fp8_tables_init(void) { } } -/* ================================================================== detection */ -static int g_detected = -1; -static int g_level = -1; +/* ================================================================== detection + * Atomics, since the first launches may run on several threads at once; every racer computes the + * same values. */ +static std::atomic g_detected{-1}; +static std::atomic g_level{-1}; -extern "C" int avx_isa_detect(void) { - if (g_detected >= 0) return g_detected; +static int detect(void) { #if defined(__x86_64__) || defined(_M_X64) || defined(__i386__) __builtin_cpu_init(); if (__builtin_cpu_supports("avx512f") && __builtin_cpu_supports("avx512bw") && __builtin_cpu_supports("avx512dq") && __builtin_cpu_supports("avx512vl")) - g_detected = AVX_LEVEL_AVX512; - else if (__builtin_cpu_supports("avx2") && __builtin_cpu_supports("fma") && - __builtin_cpu_supports("f16c")) - g_detected = AVX_LEVEL_AVX2; - else if (__builtin_cpu_supports("avx")) - g_detected = AVX_LEVEL_AVX; - else - g_detected = AVX_LEVEL_SCALAR; + return AVX_LEVEL_AVX512; + if (__builtin_cpu_supports("avx2") && __builtin_cpu_supports("fma") && + __builtin_cpu_supports("f16c")) + return AVX_LEVEL_AVX2; + if (__builtin_cpu_supports("avx")) return AVX_LEVEL_AVX; + return AVX_LEVEL_SCALAR; #else - /* Not x86. The plugin still loads and still computes the right answers -- that is the whole - * point of the scalar level being a real implementation rather than a stub -- it is simply - * slow, and `rad_plugin_info().build_target` says "host" so nothing is being claimed. */ - g_detected = AVX_LEVEL_SCALAR; + /* Not x86: the scalar level is a full implementation, just slow; rad_plugin_info().build_target + * reports "host". */ + return AVX_LEVEL_SCALAR; #endif - return g_detected; +} + +extern "C" int avx_isa_detect(void) { + int d = g_detected.load(std::memory_order_relaxed); + if (d < 0) g_detected.store(d = detect(), std::memory_order_relaxed); + return d; } extern "C" const char* avx_isa_name(int level) { @@ -100,44 +84,59 @@ extern "C" const AvxKernelTable* avx_table_for(int level) { } } -static const AvxKernelTable* g_tab = 0; +static std::atomic g_tab{nullptr}; extern "C" const AvxKernelTable* avx_table_live(void) { - if (!g_tab) { g_level = avx_isa_detect(); g_tab = avx_table_for(g_level); } - return g_tab; + const AvxKernelTable* t = g_tab.load(std::memory_order_acquire); + if (t) return t; + const int level = avx_isa_detect(); + g_level.store(level, std::memory_order_relaxed); + t = avx_table_for(level); + g_tab.store(t, std::memory_order_release); + return t; } extern "C" int avx_isa_level(void) { - if (g_level < 0) (void)avx_table_live(); - return g_level; + if (g_level.load(std::memory_order_relaxed) < 0) (void)avx_table_live(); + return g_level.load(std::memory_order_relaxed); } extern "C" int avx_isa_force(int level) { const int cap = avx_isa_detect(); - /* CLAMPED, NOT HONOURED. Asking for a level the machine cannot execute is a caller error, and - * the only honest response is to run what the machine has -- returning the level actually - * selected so a checker can report "asked for avx512, ran avx2" rather than believing it - * tested something it did not. Honouring it would be a SIGILL. */ + /* Clamp to what the CPU can execute and return the level selected, so a checker can report + * that it ran a lower level than it asked for. */ if (level < 0) level = 0; if (level > cap) level = cap; - g_level = level; - g_tab = avx_table_for(level); + g_level.store(level, std::memory_order_relaxed); + g_tab.store(avx_table_for(level), std::memory_order_release); return level; } +/* ================================================================== the thread override + * + * Every check geometry is below the kernels' parallel thresholds, so without this the checker + * would run each OpenMP body on one thread only. */ +#ifdef _OPENMP +std::atomic avx_par_threads{0}; +#endif + +extern "C" int avx_par_force(int threads) { +#ifdef _OPENMP + if (threads < 0) threads = 0; + avx_par_threads.store(threads, std::memory_order_relaxed); + return threads; +#else + (void)threads; + return 0; +#endif +} + /* ================================================================== the thunks * - * One baseline-compiled function per op, pointed at by the registry row, doing one indirect call - * into the selected level's table. - * - * WHY NOT REPOINT THE ROWS THEMSELVES. RadKernelInfo is returned by rad_kernel_at as a - * `const RadKernelInfo*` out of a static table, and the loader is entitled to read it before - * rad_plugin_open has run (it reads the op names to check schema agreement). A row whose `launch` - * was null until open() had patched it is a row that is briefly wrong, and a row that is briefly - * wrong during startup is read as a row that was never wired at all. A - * thunk is always correct, needs no mutation of a table the ABI hands out as const, and costs one - * predicted indirect branch per launch -- which against a kernel whose cheapest form touches a - * 4096-element row is not measurable. */ + * One baseline-compiled function per op, pointed at by the registry row, making one indirect call + * into the selected level's table. The rows themselves are not repointed: rad_kernel_at returns + * them as const from a static table, and the loader may read them before rad_plugin_open runs, so + * a row patched in open() would be briefly null. The extra indirect branch is not measurable. */ #define AVX_THUNK(nm) \ extern "C" int avx_thunk_##nm(const RadArgs* a, RadStream s) { \ return avx_table_live()->nm(a, s); \ @@ -147,15 +146,12 @@ AVX_OP_LIST(AVX_THUNK) /* ================================================================== scratch * - * One growable arena per thread per slot. The first call at a given size allocates; every call - * after it at or below that size does not, which is what makes the hot path allocation-free - * without pretending a host kernel can work in zero bytes. + * One growable arena per thread per slot. Only a call larger than any before it allocates, so the + * hot path is allocation-free. * - * ALIGNED TO 64 so that a _mm512_load_ps off it is legal -- an aligned load from a 32-byte-aligned - * buffer is a fault at AVX-512, and `new float[]` promises only 16. The kernels mostly use the - * unaligned loads (on every core since Nehalem the penalty is zero when the address happens to be - * aligned, so there is nothing to win by demanding alignment), but the GEMM packing buffers use - * aligned stores and they come from here. */ + * Aligned to 64 so _mm512_load_ps is legal on it (`new float[]` guarantees only 16). Kernels mostly + * use unaligned loads, which cost nothing extra on aligned addresses since Nehalem, but the GEMM + * packing buffers use aligned stores. */ namespace { struct Arena { @@ -164,18 +160,14 @@ struct Arena { ~Arena() { std::free(p); } void* get(size_t want) { if (want <= bytes) return p; - /* Grow geometrically: a kernel called at a ladder of increasing sizes would otherwise - * realloc at every rung. A request past half the address space is taken as asked, so the - * doubling cannot wrap to zero and spin. */ + /* Grow geometrically so increasing sizes do not realloc every call. A request past half + * the address space is taken as asked, so the doubling cannot wrap to zero and spin. */ size_t nb = bytes ? bytes : 4096; while (nb < want) nb = nb > SIZE_MAX / 2 ? want : nb * 2; void* q = nb <= SIZE_MAX - 63 ? std::aligned_alloc(64, (nb + 63) & ~(size_t)63) : nullptr; - /* NO BUFFER IS A STOP, NOT A SMALLER BUFFER. The contract is "at least the size asked - * for" and no caller checks it: every kernel writes the full row into what comes back, - * most of them inside an OpenMP body that cannot return a status. Handing back the old, - * smaller buffer turns an allocation failure into a heap overflow that corrupts whatever - * sits after it; a null would be a fault at an address that says nothing. So the process - * stops here, with the size that could not be had. */ + /* Allocation failure aborts. Callers do not check the result (most run inside an OpenMP + * body that cannot return a status), so returning the old smaller buffer would overflow + * the heap and returning null would fault with no diagnostic. */ if (!q) { std::fprintf(stderr, "libavx: could not allocate %zu bytes of kernel scratch\n", want); std::abort(); @@ -198,10 +190,8 @@ void* scratch_raw (size_t b) { return g_raw.get(b); } } /* ================================================================== plugin open/close - * The loader resolves these by these exact names (rad_abi.h) and a plugin that spells them - * differently is silently never initialised -- which here would mean an fp8 table of zeros and - * every fp8 operand reading as 0.0, a wrong answer with no diagnostic. Spelled from the ABI's own - * typedefs so a signature drift is a compile error. */ + * The loader resolves these exact names (rad_abi.h); a misspelling would silently skip init and + * leave the fp8 tables zero. The typedef checks below make a signature drift a compile error. */ extern "C" int rad_plugin_open(void) { fp8_tables_init(); (void)avx_table_live(); @@ -215,15 +205,11 @@ extern "C" void rad_plugin_close(void) {} /* ================================================================== the measured FMA ceiling * - * Exported for rad-avx-bench, and it has to come from HERE rather than from the bench because the - * bench is baseline-compiled (see the top of this file) and can only emit SSE2. The per-level - * probes live in avx_support.cpp, compiled with the same flags as every kernel, so what they - * report is the ceiling the kernels are actually up against -- including whatever clock the part - * holds under a sustained vector load, which on anything with an AVX-512 frequency offset is not - * the advertised boost. + * Exported for rad-avx-bench, which is baseline-compiled and cannot emit vector code itself. The + * per-level probes live in avx_support.cpp, built with the kernels' flags, so they measure the + * ceiling the kernels see, including any AVX-512 frequency offset under sustained load. * - * Returns the FLOPS PERFORMED, not a rate: the caller owns the clock, because it is the caller - * that knows to take a median over repetitions rather than trusting one. */ + * Returns the FLOPs performed, not a rate; the caller owns the clock and takes the median. */ extern "C" double avx_peak_fma_sc(int64_t); extern "C" double avx_peak_fma_v1(int64_t); extern "C" double avx_peak_fma_v2(int64_t); diff --git a/libavx/avx_elementwise.cpp b/libavx/avx_elementwise.cpp index 2d2540c5..1d991cac 100644 --- a/libavx/avx_elementwise.cpp +++ b/libavx/avx_elementwise.cpp @@ -1,43 +1,29 @@ -/* avx_elementwise.cpp -- the elementwise vocabulary: add, mul, the activations, the gated product, - * the row gather and scatter, cast, softmax and the per-row scale. +/* avx_elementwise.cpp -- add, mul, activations, gated products, row gather/scatter, cast, softmax + * and per-row scaling. * - * ============================== THESE ARE MEMORY-BOUND, NOT COMPUTE-BOUND ============================== + * These ops are memory-bound: a constant number of touches and a few flops per element. * - * Every op in this file touches each element a constant number of times and does a handful of - * flops with it, so the ceiling is the load/store units and then the cache hierarchy. That decides - * the shape of the code twice over: + * The dtype switch is per row. `in_row`/`out_row` (avx_support.cpp) convert a whole row once + * (returning the operand's own pointer for f32), instead of libref's per-element ld_dt(), whose + * branch blocks vectorisation. * - * THE DTYPE SWITCH IS HOISTED TO THE ROW. libref calls ld_dt() per element, which is a switch on - * every load and the reason it is slow -- it is not the scalar arithmetic, it is that no - * vectoriser can cross that branch. `in_row`/`out_row` (avx_support.cpp) convert a whole row - * once and hand back f32. For an f32 operand they hand back the caller's own pointer and copy - * nothing. + * Fused forms round where libref rounds. E.g. `softmax` writes the unnormalised exponentials to + * `y`, reads them back through the output dtype and multiplies by 1/sum, so a bf16 result has + * two roundings; `rmsnorm_add` does the same with `residual_out`. Staying in f32 would be half an + * ulp more accurate and disagree with the oracle and the device kernels. The round trip uses a + * hot scratch buffer instead of the output operand. * - * THE FUSED FORMS ROUND EXACTLY WHERE libref ROUNDS. This is the part that is not a performance - * decision and cannot be traded: `softmax` writes the un-normalised exponentials to `y`, reads - * them BACK through the output dtype, and multiplies by 1/sum -- so at bf16 the answer carries - * two roundings and not one. `rmsnorm_add` does the same with `residual_out`. A faster - * implementation that kept f32 all the way through would be half an ulp BETTER and would - * disagree with the oracle and with every device kernel this is checked beside. The round trip - * is done in a hot scratch buffer rather than through the output operand, which is the same - * arithmetic at cache-resident cost. - * - * ============================== THE BROADCAST RULES ARE TWO DIFFERENT OPS ============================== - * - * `mul` broadcasts a single ROW down the rows -- a bias's shape. `scale_rows` broadcasts a single - * COLUMN across them -- a per-token gate's. They are separate ops precisely so that neither has to - * guess, and the guess would be ambiguous exactly when rows == n. libref's header makes the same - * point; it is repeated here because the temptation to merge them is real and the failure is a - * plausible number rather than an error. + * Broadcasting: `mul` broadcasts one row down the rows (a bias's shape); `scale_rows` broadcasts one + * column across them (a per-token gate). They are separate ops because the two readings are + * ambiguous when rows == n, and a wrong guess gives plausible numbers. */ #include "avx_vec.h" #include "avx_common.h" using namespace avx; -/* Round a row of f32 through an operand's storage dtype and back, which is what a fused op that - * writes an intermediate and reads it again computes. A no-op for f32, which is why the f32 - * tolerance for these ops is as tight as it is. */ +/* Round a row through an operand's storage dtype and back, as an unfused store-and-reload would. + * A no-op for f32. */ static inline void roundtrip(uint32_t dt, float* v, int64_t n, void* tmp) { if (dt == RAD_F32) return; row_from_f32(dt, v, tmp, n); @@ -45,9 +31,8 @@ static inline void roundtrip(uint32_t dt, float* v, int64_t n, void* tmp) { } /* ------------------------------------------------------------------ add / mul */ -/* y = a op b over the output's extent. `b` may carry exactly one row and is then broadcast down - * the rows; nothing else broadcasts, because silent broadcasting of an arbitrary shape is how a - * shape bug becomes a plausible number. */ +/* y = a op b over the output's extent. A one-row `b` is broadcast down the rows; nothing else + * broadcasts, so a shape bug fails instead of producing plausible numbers. */ template static int elementwise2(const RadArgs* a) { if (!rad_args_have(a, 3)) return RAD_E_INVAL; @@ -90,7 +75,7 @@ AVX_KERNEL(mul_weight) { if (rows <= 0 || numel(X) < rows * n) return RAD_E_SHAPE; const bool scalar = numel(W) == 1; if (!scalar && numel(W) != n) return RAD_E_SHAPE; - /* The gain, widened once: it is the same row for every row of x. */ + /* Widened once; the same row applies to every row of x. */ float* wrow = (float*)scratch_raw((size_t)n * sizeof(float) + 64); if (scalar) { const float v = ldt(W, 0); for (int64_t i = 0; i < n; ++i) wrow[i] = v; } else for (int64_t i = 0; i < n; ++i) wrow[i] = ldt(W, i * laststride(W)); @@ -110,26 +95,24 @@ AVX_KERNEL(mul_weight) { } /* ------------------------------------------------------------------ act_mul */ -/* y = act(a) * b over two operands, libref's contract: the activation is rounded to y's dtype - * before the product, because the unfused pair stores it. +/* y = act(a) * b. As in libref, the activation is rounded to y's dtype before the product, + * because the unfused pair stores it. * - * silu and gelu_tanh are VECTORISED on vf_exp. An encoder's gated FFN puts this op on every token - * of every layer, and the scalar libm form was 9% of an EmbeddingGemma 2 step on a 9950X3D -- a - * per-element tanhf behind 2048 columns. gelu_tanh keeps the reference's own structure, + * silu and gelu_tanh are vectorised on vf_exp: in an encoder's gated FFN this op runs on every + * token of every layer, and scalar libm made it about 9% of an EmbeddingGemma 2 step. gelu_tanh + * keeps torch's structure, * * 0.5 g (1 + tanh z), z = sqrt(2/pi) (g + 0.044715 g^3), tanh z = (1 - e^(-2z)) / (1 + e^(-2z)) * - * and not the algebraically equal g / (1 + e^(-2z)): the two differ by an ulp or two of f32, and - * after the bf16 rounding the rearranged form moved an EmbeddingGemma 2 embedding measurably - * further from transformers' (cosine 0.999919 -> 0.999894 on one input; torch computes this same - * 0.5 g (1 + tanh) in f32). vf_exp saturates rather than overflowing, so the large-|g| limits come - * out as g and 0. erf has no vector form in this plugin, so gelu stays scalar. */ + * rather than the algebraically equal g / (1 + e^(-2z)), which differs by an ulp or two and after + * bf16 rounding measurably moves embeddings away from transformers'. vf_exp saturates, so the + * large-|g| limits come out as g and 0. erf has no vector form here, so gelu stays scalar. */ static inline float act_of(int act, float g) { - if (act == 0) return g / (1.0f + std::exp(-g)); - if (act == 1) return 0.5f * g * (1.0f + std::erf(g * 0.70710678118654752f)); - if (act == 3) return 1.0f / (1.0f + std::exp(-g)); + if (act == 0) return g / (1.0f + sc_exp(-g)); + if (act == 1) return 0.5f * g * (1.0f + sc_erf(g * 0.70710678118654752f)); + if (act == 3) return 1.0f / (1.0f + sc_exp(-g)); const float k0 = 0.7978845608028654f, k1 = 0.044715f; - return 0.5f * g * (1.0f + std::tanh(k0 * (g + k1 * g * g * g))); + return 0.5f * g * (1.0f + sc_tanh(k0 * (g + k1 * g * g * g))); } /* sy[0..n) = act(g[0..n)) for silu (0) and gelu_tanh (2); the tail is the scalar form. */ @@ -174,8 +157,8 @@ AVX_KERNEL(act_mul) { const float* g = in_row(A, rowoff(A, r, n), n, sa); const float* u = in_row(B, rowoff(B, r, n), n, sb); act_row(act, g, sy, n); - /* sa is free once the activation is taken (g is either sa or the tensor itself); sb may - * hold u, which the product still reads. */ + /* sa is free once the activation is taken (g is sa or the tensor); sb may hold u, which + * is still needed. */ roundtrip(Y->dtype, sy, n, sa); for (int64_t i = 0; i < n; ++i) sy[i] *= u[i]; out_row(Y, rowoff(Y, r, n), n, sy); @@ -184,8 +167,8 @@ AVX_KERNEL(act_mul) { } /* ------------------------------------------------------------------ relu / clamp */ -/* y = max(x, 0), and y = min(max(x, lo), hi) with lo and hi WEIGHTS of one element each (a - * clipped linear's range). Row-wise at each operand's own pitch, like the libref forms. */ +/* y = max(x, 0), and y = min(max(x, lo), hi) with lo and hi one-element weights (a clipped + * linear's range). Row-wise at each operand's own pitch, as in libref. */ AVX_KERNEL(relu) { if (!rad_args_have(a, 2)) return RAD_E_INVAL; const RadTensor *X = &a->t[0], *Y = &a->t[1]; @@ -231,15 +214,21 @@ AVX_KERNEL(clamp) { } /* ------------------------------------------------------------------ conv2d */ -/* libref's segment-wise convolution over (time, width), channels innermost. The weight is turned - * once a launch from PyTorch's [cout, cin, kh, kw] into [kh][kw][cin][cout], so each input value is - * broadcast against a contiguous run of output channels: the inner loop is a vector FMA over cout - * rather than a dot product over cin. Same sum (in a different order), one rounding. */ +/* libref's segment-wise convolution over (time, width), channels innermost. The weight is + * transposed once per launch from PyTorch's [cout, cin, kh, kw] (or [cout, cin, kw, kh] with + * t_last) to [kh][kw][cin][cout], so the inner loop is a vector FMA over cout rather than a dot + * product over cin. Same sum in a different order plus the optional bias, one rounding; then + * `act` and a second rounding, as libref does. */ AVX_KERNEL(conv2d) { if (!a || a->n_t < 5 || !a->t[0].data || !a->t[1].data || !a->t[2].data || !a->t[4].data) return RAD_E_INVAL; const RadTensor *X = &a->t[0], *Wt = &a->t[1], *cu = &a->t[2], *Y = &a->t[4]; const RadTensor* V = a->t[3].data ? &a->t[3] : nullptr; + const RadTensor* B = a->n_t > 5 && a->t[5].data ? &a->t[5] : nullptr; + const bool tlast = p_int(a, "t_last", 0) != 0; + const char* act = p_str(a, "act", "none"); + const bool gelu = !std::strcmp(act, "gelu"); + if (!gelu && std::strcmp(act, "none")) return RAD_E_UNSUPPORTED; const int64_t W = p_int(a, "width", 0), cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0); const int64_t kh = p_int(a, "kh", 0), kw = p_int(a, "kw", 0); const int64_t st = p_int(a, "stride", 1), pad = p_int(a, "pad", 0); @@ -249,19 +238,25 @@ AVX_KERNEL(conv2d) { return RAD_E_SHAPE; const int64_t Wo = (W + 2 * pad - kw) / st + 1; if (Wo <= 0 || numel(Wt) < cout * cin * kh * kw) return RAD_E_SHAPE; + if (B && numel(B) < cout) return RAD_E_SHAPE; const int64_t S = numel(cu) - 1; if (S <= 0) return RAD_E_SHAPE; const int64_t rin = W * cin, rout = Wo * cout; const int64_t Min = rows_of(X, rin), Mout = rows_of(Y, rout); + if (Min <= 0 || Mout <= 0 || ldi(cu, offlin(cu, S)) <= ldi(cu, offlin(cu, 0))) + return RAD_E_SHAPE; /* zero rows is not a call (docs/OPS.md) */ - float* wt = (float*)scratch_raw((size_t)(kh * kw * cin * cout) * sizeof(float) + 64); + float* wt = (float*)scratch_raw((size_t)(kh * kw * cin * cout + cout) * sizeof(float) + 64); + float* bias = wt + kh * kw * cin * cout; + for (int64_t co = 0; co < cout; ++co) bias[co] = B ? ldt(B, offlin(B, co)) : 0.0f; const int64_t ws = laststride(Wt); for (int64_t co = 0; co < cout; ++co) for (int64_t ci = 0; ci < cin; ++ci) for (int64_t i = 0; i < kh; ++i) for (int64_t j = 0; j < kw; ++j) wt[((i * kw + j) * cin + ci) * cout + co] = - ldt(Wt, (((co * cin + ci) * kh + i) * kw + j) * ws); + ldt(Wt, (tlast ? ((co * cin + ci) * kw + j) * kh + i + : ((co * cin + ci) * kh + i) * kw + j) * ws); for (int64_t s = 0; s < S; ++s) { const int64_t c0 = ldi(cu, offlin(cu, s)), c1 = ldi(cu, offlin(cu, s + 1)); @@ -302,15 +297,82 @@ AVX_KERNEL(conv2d) { } } } + if (B) + for (int64_t wo = 0; wo < Wo; ++wo) + for (int64_t co = 0; co < cout; ++co) acc[wo * cout + co] += bias[co]; out_row(Y, rowoff(Y, o0 + to, rout), rout, acc); + if (gelu) { + /* The biased sum as y's dtype holds it, then the activation of the rounded value. */ + const float* yr = in_row(Y, rowoff(Y, o0 + to, rout), rout, acc); + for (int64_t e = 0; e < rout; ++e) acc[e] = act_of(1, yr[e]); + out_row(Y, rowoff(Y, o0 + to, rout), rout, acc); + } + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ conv2d_unfold */ +/* libref's receptive fields as rows, a copy: each input row is widened once and the taps are + * gathered from it. */ +AVX_KERNEL(conv2d_unfold) { + if (!a || a->n_t < 4 || !a->t[0].data || !a->t[1].data || !a->t[3].data) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *cu = &a->t[1], *Y = &a->t[3]; + const RadTensor* V = a->t[2].data ? &a->t[2] : nullptr; + const int64_t W = p_int(a, "width", 0), cin = p_int(a, "cin", 0); + const int64_t kh = p_int(a, "kh", 0), kw = p_int(a, "kw", 0); + const int64_t st = p_int(a, "stride", 1), pad = p_int(a, "pad", 0); + const int64_t cdiv = p_int(a, "cu_div", 1), vst = p_int(a, "valid_stride", 1); + const bool tlast = p_int(a, "t_last", 0) != 0; + if (W <= 0 || cin <= 0 || kh <= 0 || kw <= 0 || st <= 0 || pad < 0 || cdiv <= 0 || vst <= 0) + return RAD_E_SHAPE; + const int64_t Wo = (W + 2 * pad - kw) / st + 1, K = cin * kh * kw; + const int64_t S = numel(cu) - 1; + if (Wo <= 0 || S <= 0) return RAD_E_SHAPE; + const int64_t rin = W * cin, Min = rows_of(X, rin), Mout = rows_of(Y, K); + if (Min <= 0 || Mout <= 0 || ldi(cu, offlin(cu, S)) <= ldi(cu, offlin(cu, 0))) + return RAD_E_SHAPE; /* zero rows is not a call (docs/OPS.md) */ + + for (int64_t s = 0; s < S; ++s) { + const int64_t c0 = ldi(cu, offlin(cu, s)), c1 = ldi(cu, offlin(cu, s + 1)); + if (c0 % cdiv || c1 % cdiv || (c0 / cdiv) % st || c1 < c0) return RAD_E_SHAPE; + const int64_t t0 = c0 / cdiv, T = c1 / cdiv - t0; + if (T <= 0) continue; + const int64_t To = (T + 2 * pad - kh) / st + 1, o0 = t0 / st; + if (To <= 0) continue; + if (t0 + T > Min || (o0 + To) * Wo > Mout) return RAD_E_SHAPE; + if (V && numel(V) < (t0 + T - 1) * vst + 1) return RAD_E_SHAPE; + + AVX_PARALLEL_FOR_IF(To * Wo * K >= AVX_PAR_MIN) + for (int64_t to = 0; to < To; ++to) { + float* row = scratch_f32((size_t)K); + float* sx = scratch_f32_b((size_t)(kh * rin)); + const float** xr = (const float**)scratch_raw((size_t)kh * sizeof(const float*)); + for (int64_t i = 0; i < kh; ++i) { + const int64_t ti = to * st - pad + i, tg = t0 + ti; + const bool ok = ti >= 0 && ti < T && !(V && ldi(V, offlin(V, tg * vst)) == 0); + xr[i] = ok ? in_row(X, rowoff(X, tg, rin), rin, sx + i * rin) : nullptr; + } + for (int64_t wo = 0; wo < Wo; ++wo) { + for (int64_t i = 0; i < kh; ++i) + for (int64_t j = 0; j < kw; ++j) { + const int64_t wi = wo * st - pad + j; + const float* xv = xr[i] && wi >= 0 && wi < W ? xr[i] + wi * cin : nullptr; + for (int64_t ci = 0; ci < cin; ++ci) { + const int64_t k = tlast ? (ci * kw + j) * kh + i : (ci * kh + i) * kw + j; + row[k] = xv ? xv[ci] : 0.0f; + } + } + out_row(Y, rowoff(Y, (o0 + to) * Wo + wo, K), K, row); + } } } return RAD_OK; } /* ------------------------------------------------------------------ conv1d_dw */ -/* libref's causal depthwise convolution over time, the weight turned to [k][C] once a launch so - * a row is a vector FMA per tap. */ +/* libref's causal depthwise convolution over time. The weight is transposed to [k][C] once per + * launch so each tap is a vector FMA over the row. */ AVX_KERNEL(conv1d_dw) { if (!rad_args_have(a, 4)) return RAD_E_INVAL; const RadTensor *X = &a->t[0], *Wt = &a->t[1], *cu = &a->t[2], *Y = &a->t[3]; @@ -319,6 +381,8 @@ AVX_KERNEL(conv1d_dw) { const int64_t S = numel(cu) - 1; if (S <= 0) return RAD_E_SHAPE; const int64_t Mx = rows_of(X, C), My = rows_of(Y, C); + if (Mx <= 0 || My <= 0 || ldi(cu, offlin(cu, S)) <= ldi(cu, offlin(cu, 0))) + return RAD_E_SHAPE; /* zero rows is not a call (docs/OPS.md) */ float* wt = (float*)scratch_raw((size_t)(K * C) * sizeof(float) + 64); for (int64_t c = 0; c < C; ++c) @@ -352,7 +416,7 @@ AVX_KERNEL(conv1d_dw) { } /* ------------------------------------------------------------------ rel_sinusoid */ -/* libref's table, to the operation: the same f32 steps and the same libm calls. */ +/* libref's table, with the same f32 steps and libm calls. */ AVX_KERNEL(rel_sinusoid) { if (!rad_args_have(a, 1)) return RAD_E_INVAL; const RadTensor* Y = &a->t[0]; @@ -368,19 +432,53 @@ AVX_KERNEL(rel_sinusoid) { for (int64_t d = 0; d < rows; ++d) { float* sy = scratch_f32((size_t)n); for (int64_t i = 0; i < h; ++i) { - const float inv = std::exp((float)i * -inc); + const float inv = sc_exp((float)i * -inc); const float ang = (float)d * inv; - sy[i] = std::sin(ang); - sy[h + i] = std::cos(ang); + sy[i] = sc_sin(ang); + sy[h + i] = sc_cos(ang); } out_row(Y, rowoff(Y, d, n), n, sy); } return RAD_OK; } +/* ------------------------------------------------------------------ seg_sinusoid */ +/* libref's per-segment table, to the operation: position (r - start) mod period. */ +AVX_KERNEL(seg_sinusoid) { + if (!rad_args_have(a, 2)) return RAD_E_INVAL; + const RadTensor *cu = &a->t[0], *Y = &a->t[1]; + const int64_t n = p_int(a, "n", 0), period = p_int(a, "period", 0), cdiv = p_int(a, "cu_div", 1); + if (n <= 0 || n % 2 || period <= 0 || cdiv <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_of(Y, n), S = numel(cu) - 1; + if (rows <= 0 || S <= 0 || ldi(cu, offlin(cu, S)) <= ldi(cu, offlin(cu, 0))) + return RAD_E_SHAPE; /* zero rows is not a call (docs/OPS.md) */ + const int64_t h = n / 2; + const double mt = (double)p_f32(a, "max_timescale", 10000.0f); + const float inc = (float)(std::log(mt / 1.0) / (double)(h - 1 > 1 ? h - 1 : 1)); + + for (int64_t s = 0; s < S; ++s) { + const int64_t c0 = ldi(cu, offlin(cu, s)), c1 = ldi(cu, offlin(cu, s + 1)); + if (c0 % cdiv || c1 % cdiv || c1 < c0 || c1 / cdiv > rows) return RAD_E_SHAPE; + const int64_t r0 = c0 / cdiv, r1 = c1 / cdiv; + AVX_PARALLEL_FOR_IF((r1 - r0) * n >= AVX_PAR_MIN) + for (int64_t r = r0; r < r1; ++r) { + float* sy = scratch_f32((size_t)n); + const int64_t p = (r - r0) % period; + for (int64_t i = 0; i < h; ++i) { + const float inv = sc_exp((float)i * -inc); + const float ang = (float)p * inv; + sy[i] = sc_sin(ang); + sy[h + i] = sc_cos(ang); + } + out_row(Y, rowoff(Y, r, n), n, sy); + } + } + return RAD_OK; +} + /* ------------------------------------------------------------------ seg_mean */ -/* One row a cu_seqlens segment: the mean of its rows, summed in double and rounded once, which is - * libref's arithmetic -- a pooled embedding should not depend on which host kernel pooled it. */ +/* One output row per cu_seqlens segment: the mean of its rows, summed in double and rounded once, + * as in libref. */ AVX_KERNEL(seg_mean) { if (!rad_args_have(a, 3)) return RAD_E_INVAL; const RadTensor *X = &a->t[0], *cu = &a->t[1], *Y = &a->t[2]; @@ -388,7 +486,7 @@ AVX_KERNEL(seg_mean) { const int64_t S = numel(cu) - 1; if (n <= 0 || S <= 0 || numel(Y) < S * n) return RAD_E_SHAPE; const int64_t total = ldi(cu, offlin(cu, S)); - if (total < 0 || numel(X) < total * n) return RAD_E_SHAPE; + if (total <= 0 || numel(X) < total * n) return RAD_E_SHAPE; /* zero rows is not a call */ AVX_PARALLEL_FOR_IF(S >= 2) for (int64_t s = 0; s < S; ++s) { @@ -409,8 +507,8 @@ AVX_KERNEL(seg_mean) { } /* ------------------------------------------------------------------ pool_rows */ -/* libref's: the mean of each k consecutive rows summed in f32 and rounded to y's dtype, then the - * multiplier and a second rounding -- the unfused pair. Parallel over output rows. */ +/* As libref: the mean of each k consecutive rows, summed in f32 and rounded to y's dtype, then the + * multiplier and a second rounding (the unfused pair). Parallel over output rows. */ AVX_KERNEL(pool_rows) { if (!rad_args_have(a, 2)) return RAD_E_INVAL; const RadTensor *X = &a->t[0], *Y = &a->t[1]; @@ -441,18 +539,17 @@ AVX_KERNEL(pool_rows) { } /* ------------------------------------------------------------------ scale_rows */ -/* y[m, i] = x[m, i] * act(s[m]), then + add[m, i] if the optional residual is passed. +/* y[m, i] = x[m, i] * act(s[m]), plus add[m, i] when the optional residual is passed. * - * The activation is applied to the SCALAR and not to the product, which is what a gate means -- - * Qwen3.5-MoE's shared expert is scaled by sigmoid(shared_expert_gate(x)). + * The activation applies to the per-row scalar, as a gate does (Qwen3.5-MoE scales its shared + * expert by sigmoid(shared_expert_gate(x))). * - * THE RESIDUAL ADD IS A ROUND TRIP AND THAT IS THE CONTRACT. libref stores the product into `y`, - * READS IT BACK, and stores the sum -- so at bf16 the product is narrowed before the add sees it. - * That is not an artefact of writing it as two statements: it is what a fused kernel does, because - * the product has to be stored anyway. Reproduced here in a hot buffer rather than through the - * operand, which is the same arithmetic without the second pass over memory. */ + * With a residual, the product is narrowed to y's dtype before the add, as libref (and a fused + * kernel) does by storing the product and reading it back. Done here in a scratch buffer. */ AVX_KERNEL(scale_rows) { - if (!rad_args_have(a, 4)) return RAD_E_INVAL; + /* `add` (operand 2) is optional; the other three are required. */ + if (a->n_t < 4 || !rad_arg_in(a, 0) || !rad_arg_in(a, 1) || !rad_arg_in(a, 3)) + return RAD_E_INVAL; const RadTensor *x = &a->t[0], *sc = &a->t[1], *y = &a->t[3]; const RadTensor* ad = rad_arg_in(a, 2); const int64_t n = p_int(a, "n", numel(y)); @@ -469,10 +566,8 @@ AVX_KERNEL(scale_rows) { AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) for (int64_t r = 0; r < rows; ++r) { const float v0 = ldt(sc, r * ss); - /* The SCALAR sigmoid, through the ABI's arithmetic and not the vector polynomial: one - * value per row, so there is nothing to vectorise, and going through the same expf the - * oracle does removes a source of disagreement for free. */ - const float v = sig ? 1.0f / (1.0f + std::exp(-v0)) : v0; + /* One value per row, so use libm's expf as the oracle does, not the vector polynomial. */ + const float v = sig ? 1.0f / (1.0f + sc_exp(-v0)) : v0; float* sx = scratch_f32((size_t)n); float* sy = scratch_f32_b((size_t)n); const float* xr = in_row(x, rowoff(x, r, n), n, sx); @@ -496,16 +591,12 @@ AVX_KERNEL(scale_rows) { } /* ------------------------------------------------------------------ silu_mul */ -/* y[.., i] = silu(gate_up[.., i]) * gate_up[.., n + i]. The gate is the FIRST half, which is the - * order rad-convert fuses gate and up into one weight in, so the two conventions cannot drift. +/* y[.., i] = silu(gate_up[.., i]) * gate_up[.., n + i]. The gate is the first half, the order in + * which rad-convert fuses gate and up into one weight. * - * THE bf16 OUTPUT TAKES A CHEAPER SILU, and that is a precision argument rather than a - * punt: vf_silu's degree-5 minimax exp plus a full division is ~0.6 ulp, while a bf16 store - * rounds at 3e-3 -- the output cannot carry what the exact path computes. The fast form is - * vf_silu_fast (avx_vec.h -- shared with the conv kernels since, same rule: keyed on the - * OUTPUT dtype, twentyfold inside the bf16 bucket), and f32 outputs keep the exact path. - * Local to ops whose product is consumed once -- shared vf_sigmoid feeds gate chains whose - * errors accumulate. */ + * A bf16 output uses vf_silu_fast (avx_vec.h): the exact path's ~0.6 ulp is wasted on a store that + * rounds at 3e-3. f32 outputs keep the exact path. Only for ops whose product is consumed once; + * vf_sigmoid feeds gate chains whose errors accumulate. */ AVX_KERNEL(silu_mul) { if (!rad_args_have(a, 2)) return RAD_E_INVAL; @@ -517,23 +608,21 @@ AVX_KERNEL(silu_mul) { AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) for (int64_t r = 0; r < rows; ++r) { - /* One in_row over the WHOLE 2n row rather than two over its halves: the two halves are - * adjacent in memory and one conversion of 2n beats two of n by the call overhead and by - * keeping the hardware prefetcher on a single stream. */ + /* One in_row over the whole 2n row: the halves are adjacent, and one conversion saves a + * call and keeps the prefetcher on one stream. */ float* s = scratch_f32((size_t)(2 * n)); float* sy = scratch_f32_b((size_t)n); const float* g = in_row(gu, rowoff(gu, r, 2 * n), 2 * n, s); const float* u = g + n; #if AVX_LEVEL >= 2 - /* The fast silu is a precision decision keyed on the OUTPUT dtype (see above): a bf16 - * store cannot carry 6e-5, an f32 one is held at 1e-6. */ + /* Keyed on the output dtype (see above). */ if (y->dtype == RAD_BF16) { int64_t i = 0; for (; i + VF_N <= n; i += VF_N) vf_storeu(sy + i, vf_mul(vf_silu_fast(vf_loadu(g + i)), vf_loadu(u + i))); for (; i < n; ++i) { const float gi = g[i]; - sy[i] = (gi / (1.0f + std::exp(-gi))) * u[i]; + sy[i] = (gi / (1.0f + sc_exp(-gi))) * u[i]; } out_row(y, rowoff(y, r, n), n, sy); continue; @@ -544,7 +633,7 @@ AVX_KERNEL(silu_mul) { vf_storeu(sy + i, vf_mul(vf_silu(vf_loadu(g + i)), vf_loadu(u + i))); for (; i < n; ++i) { const float gi = g[i]; - sy[i] = (gi / (1.0f + std::exp(-gi))) * u[i]; + sy[i] = (gi / (1.0f + sc_exp(-gi))) * u[i]; } out_row(y, rowoff(y, r, n), n, sy); } @@ -553,11 +642,8 @@ AVX_KERNEL(silu_mul) { /* ------------------------------------------------------------------ gelu_mul * - * y[i] = gelu_tanh(gate_up[i]) * gate_up[n + i], the gate the FIRST half exactly as in silu_mul. - * The activation keeps libref's ONE definition of gelu_tanh (act_gelu_tanh, std::tanh): the tree's - * rule for a non-polynomial activation is a single source of truth, so this runs libref's scalar - * formula into the f32 scratch rather than a second vectorised tanh whose agreement with the first - * would be a property of its coefficients -- the same decision the unary gelu above makes. */ + * y[i] = gelu_tanh(gate_up[i]) * gate_up[n + i], gate first as in silu_mul. Uses libref's scalar + * gelu_tanh formula (act_gelu_tanh, std::tanh) rather than a second, vectorised definition. */ AVX_KERNEL(gelu_mul) { if (!rad_args_have(a, 2)) return RAD_E_INVAL; const RadTensor *gu = &a->t[0], *y = &a->t[1]; @@ -568,15 +654,14 @@ AVX_KERNEL(gelu_mul) { AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) for (int64_t r = 0; r < rows; ++r) { - /* One in_row over the whole 2n row, as silu_mul does: the halves are adjacent and one - * conversion of 2n beats two of n. */ + /* One in_row over the whole 2n row, as in silu_mul. */ float* s = scratch_f32((size_t)(2 * n)); float* sy = scratch_f32_b((size_t)n); const float* g = in_row(gu, rowoff(gu, r, 2 * n), 2 * n, s); const float* u = g + n; for (int64_t i = 0; i < n; ++i) { const float x = g[i]; - const float t = std::tanh(0.7978845608028654f * (x + 0.044715f * x * x * x)); + const float t = sc_tanh(0.7978845608028654f * (x + 0.044715f * x * x * x)); sy[i] = 0.5f * x * (1.0f + t) * u[i]; } out_row(y, rowoff(y, r, n), n, sy); @@ -586,18 +671,12 @@ AVX_KERNEL(gelu_mul) { /* ------------------------------------------------------------------ gelu / silu / sigmoid * - * These run over the whole tensor rather than row by row -- libref's `unary` does the same -- so - * the blocking is over a fixed tile that stays in L1 rather than over a row whose length the op - * does not know. + * These run over the whole tensor, as libref's `unary` does, in fixed L1-sized tiles (the op has + * no row length). * - * GELU IS THE ONE OP HERE WITH A SCALAR INNER LOOP AND IT IS DELIBERATE. libref computes - * 0.5*x*(1 + erf(x/sqrt2)) with libm's erff, and the kbench tolerance for a `*`/f32 op is 1e-5 -- - * which a minimax erf polynomial can meet, and which is not the point: the polynomial would put a - * second definition of gelu in the tree whose agreement with the first is a property of the - * coefficients. The dtype switch is still hoisted, so this is far from libref's speed even - * scalar; if gelu ever appears on a hot path in a model this project serves, the polynomial is - * the obvious next step and --bench gelu is where it would be justified. Qwen and Gemma are silu - * throughout, so today it does not. */ + * gelu stays scalar on purpose: libref uses libm's erff, and a minimax erf polynomial would be a + * second definition of gelu. The dtype switch is still hoisted. If gelu lands on a hot path, a + * polynomial is the next step (--bench gelu); Qwen and Gemma use silu. */ enum { UN_GELU = 0, UN_SILU = 1, UN_SIGMOID = 2 }; template @@ -607,17 +686,16 @@ static int unary(const RadArgs* a) { const int64_t nel = numel(y); if (nel <= 0 || numel(x) < nel) return RAD_E_SHAPE; - /* The strided case falls back to element-at-a-time, as libref does: `offlin` has to be - * evaluated per element there and no amount of vectorisation survives it. */ + /* Strided: element at a time through `offlin`, as libref does. */ if (!dense_row(x) || !dense_row(y) || !rad_tensor_is_contiguous(x) || !rad_tensor_is_contiguous(y)) { AVX_PARALLEL_FOR_IF(nel >= AVX_PAR_MIN) for (int64_t i = 0; i < nel; ++i) { const float v = ldt(x, offlin(x, i)); float o; - if (WHICH == UN_GELU) o = 0.5f * v * (1.0f + std::erf(v * 0.70710678118654752f)); - else if (WHICH == UN_SILU) o = v / (1.0f + std::exp(-v)); - else o = 1.0f / (1.0f + std::exp(-v)); + if (WHICH == UN_GELU) o = 0.5f * v * (1.0f + sc_erf(v * 0.70710678118654752f)); + else if (WHICH == UN_SILU) o = v / (1.0f + sc_exp(-v)); + else o = 1.0f / (1.0f + sc_exp(-v)); stt(y, offlin(y, i), o); } return RAD_OK; @@ -641,9 +719,9 @@ static int unary(const RadArgs* a) { } for (; i < m; ++i) { const float u = v[i]; - if (WHICH == UN_GELU) so[i] = 0.5f * u * (1.0f + std::erf(u * 0.70710678118654752f)); - else if (WHICH == UN_SILU) so[i] = u / (1.0f + std::exp(-u)); - else so[i] = 1.0f / (1.0f + std::exp(-u)); + if (WHICH == UN_GELU) so[i] = 0.5f * u * (1.0f + sc_erf(u * 0.70710678118654752f)); + else if (WHICH == UN_SILU) so[i] = u / (1.0f + sc_exp(-u)); + else so[i] = 1.0f / (1.0f + sc_exp(-u)); } out_row(y, off, m, so); } @@ -655,8 +733,7 @@ AVX_KERNEL(silu) { return unary(a); } AVX_KERNEL(sigmoid) { return unary(a); } /* ------------------------------------------------------------------ fill */ -/* y = value over [M, n] at y's own row pitch, the value rounded once by the store. Nothing to - * vectorise that the store does not already do: it is a write of one number. */ +/* y = value over [M, n] at y's own row pitch, rounded once by the store. */ AVX_KERNEL(fill) { if (!rad_args_have(a, 1)) return RAD_E_INVAL; const RadTensor* y = &a->t[0]; @@ -674,11 +751,9 @@ AVX_KERNEL(fill) { } /* ------------------------------------------------------------------ logit_softcap */ -/* y = cap * tanh(x / cap). Its own list entry rather than another unary, because WHICH is - * a compile-time choice and `cap` is a runtime parameter -- the template has nowhere to put it. - * The vector path keeps the tree's one definition of the non-polynomial part: tanh(z) is - * 2*sigmoid(2z) - 1, so the work is vf_sigmoid's existing minimax exp plus two multiplies. The - * scalar fallback is libm's tanhf, which is what libref's oracle computes. */ +/* y = cap * tanh(x / cap). Not a unary because `cap` is a runtime parameter. The vector + * path uses tanh(z) = 2*sigmoid(2z) - 1 on vf_sigmoid; the scalar tail uses libm's tanhf, as + * libref does. */ AVX_KERNEL(logit_softcap) { if (!rad_args_have(a, 2)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *y = &a->t[1]; @@ -692,7 +767,7 @@ AVX_KERNEL(logit_softcap) { AVX_PARALLEL_FOR_IF(nel >= AVX_PAR_MIN) for (int64_t i = 0; i < nel; ++i) { const float v = ldt(x, offlin(x, i)); - stt(y, offlin(y, i), cap * std::tanh(v / cap)); + stt(y, offlin(y, i), cap * sc_tanh(v / cap)); } return RAD_OK; } @@ -706,27 +781,22 @@ AVX_KERNEL(logit_softcap) { float* s = scratch_f32((size_t)TILE); float* so = scratch_f32_b((size_t)TILE); const float* v = in_row(x, off, m, s); - const vf z = vf_set1(2.0f / cap); /* x / cap, doubled: the argument of the sigmoid */ + const vf z = vf_set1(2.0f / cap); /* sigmoid argument: 2x / cap */ const vf c2 = vf_set1(2.0f * cap); /* 2*cap * sigmoid(...) */ const vf c1 = vf_set1(-cap); /* ... - cap */ int64_t i = 0; for (; i + VF_N <= m; i += VF_N) vf_storeu(so + i, vf_fma(c2, vf_sigmoid(vf_mul(vf_loadu(v + i), z)), c1)); for (; i < m; ++i) - so[i] = cap * std::tanh(v[i] / cap); + so[i] = cap * sc_tanh(v[i] / cap); out_row(y, off, m, so); } return RAD_OK; } /* ------------------------------------------------------------------ scale */ -/* y = x * s, s a [1] weight broadcast over every element. A plain multiply by a scalar: the - * vector path is vf_mul against a broadcast, and the scalar fallback is a plain multiply. There is - * no non-polynomial part, so nothing is reused from the sigmoid path; it is its own list entry - * (rather than a `mul` with a [1] operand) for the same reason `mul` refuses a scalar broadcast -- - * a silent choice between a row-broadcast and a scalar-broadcast is how a shape bug becomes a - * plausible number. The scalar is read once, outside the loop: a per-element reload of a [1] - * tensor is the same value every time and costs a load per element. */ +/* y = x * s, with s a [1] weight broadcast over every element. A separate op rather than `mul` + * with a [1] operand, for the reason `mul` refuses a scalar broadcast (see the file header). */ AVX_KERNEL(scale) { if (!rad_args_have(a, 3)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *s = &a->t[1], *y = &a->t[2]; @@ -763,10 +833,9 @@ AVX_KERNEL(scale) { } /* ------------------------------------------------------------------ gather_rows */ -/* y[i, :] = x[idx[i], :]. A negative index writes a ZERO ROW -- the padding rule embed_lookup - * follows, and what a step with fewer sampled rows than the buffer's extent leaves behind. An - * index at or past x's row count is RAD_E_INVAL and is checked BEFORE the loop, because an OpenMP - * body cannot return. */ +/* y[i, :] = x[idx[i], :]. A negative index writes a zero row (embed_lookup's padding rule, used + * when a step has fewer rows than the buffer). An index >= x's row count is RAD_E_INVAL, checked + * before the loop because an OpenMP body cannot return. */ AVX_KERNEL(gather_rows) { if (!rad_args_have(a, 3)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *idx = &a->t[1], *y = &a->t[2]; @@ -779,10 +848,10 @@ AVX_KERNEL(gather_rows) { for (int64_t m = 0; m < M; ++m) if (ldi(idx, offlin(idx, m)) >= src_rows) return RAD_E_INVAL; - /* A ROW COPY, NOT A CONVERSION, when the dtypes match -- which they always do for a gather. - * memcpy on a whole row beats a widen/narrow round trip by the width of the dtype, and a - * gather that changed the bits of what it moved would be a cast wearing a gather's name. */ - const bool same = x->dtype == y->dtype && dense_row(x) && dense_row(y); + /* Matching whole-byte dtypes (the normal case) copy rows bytewise, which is faster than a + * widen/narrow round trip and cannot change the bits. A sub-byte row can start mid-byte. */ + const bool same = x->dtype == y->dtype && dense_row(x) && dense_row(y) && + rad_dtype_bits(x->dtype) % 8 == 0; const size_t rowb = same ? (size_t)((rad_dtype_bits(x->dtype) * n) / 8) : 0; AVX_PARALLEL_FOR_IF(M * n >= AVX_PAR_MIN) @@ -807,10 +876,9 @@ AVX_KERNEL(gather_rows) { } /* ------------------------------------------------------------------ scatter_rows */ -/* x[idx[i], :] = v[i, :], the mirror of gather_rows. `x` is INOUT and the write is PARTIAL: a row - * no index names keeps what it held, and a NEGATIVE index writes nothing, as a negative one reads - * a zero row on the gather side. Indices are distinct by contract (RAD_OPD_F_IDX_UNIQUE), which is - * what lets the rows go to the threads in any order. */ +/* x[idx[i], :] = v[i, :], the mirror of gather_rows. `x` is INOUT and partially written: rows no + * index names keep their contents, and a negative index writes nothing. Indices are distinct by + * contract (RAD_OPD_F_IDX_UNIQUE), so rows can be written by threads in any order. */ AVX_KERNEL(scatter_rows) { if (!rad_args_have(a, 3)) return RAD_E_INVAL; const RadTensor *v = &a->t[0], *idx = &a->t[1], *x = &a->t[2]; @@ -823,8 +891,9 @@ AVX_KERNEL(scatter_rows) { for (int64_t m = 0; m < M; ++m) if (ldi(idx, offlin(idx, m)) >= dst_rows) return RAD_E_INVAL; - /* A row copy when the dtypes match, for gather_rows' reason. */ - const bool same = v->dtype == x->dtype && dense_row(v) && dense_row(x); + /* Bytewise row copy when the dtypes match, as in gather_rows. */ + const bool same = v->dtype == x->dtype && dense_row(v) && dense_row(x) && + rad_dtype_bits(x->dtype) % 8 == 0; const size_t rowb = same ? (size_t)((rad_dtype_bits(x->dtype) * n) / 8) : 0; AVX_PARALLEL_FOR_IF(M * n >= AVX_PAR_MIN) @@ -844,13 +913,11 @@ AVX_KERNEL(scatter_rows) { } /* ------------------------------------------------------------------ cast */ -/* The tensors carry their own dtypes and those are what the bytes actually are; `from`/`to` are in - * the schema because the SELECTOR needs them, and a disagreement between the parameter and the - * tensor is a caller bug this cannot diagnose better than the caller can. libref says the same. +/* Reads the tensors' own dtypes. `from`/`to` exist in the schema for the selector; a mismatch with + * the tensors is a caller bug (as in libref). * - * Integer pairs go through the INTEGER path, so a token id or a block index above 2^24 survives a - * cast that f32 would round. That is not a tolerance question -- it is the difference between a - * token id and a different token id. */ + * Integer-to-integer casts take an integer path, so token ids and block indices above 2^24 are not + * rounded through f32. */ AVX_KERNEL(cast) { if (!rad_args_have(a, 2)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *y = &a->t[1]; @@ -884,14 +951,11 @@ AVX_KERNEL(cast) { } /* ------------------------------------------------------------------ softmax */ -/* Max-subtracted, f32, over the last n elements of a row. The max subtraction is not an - * optimisation: without it a 60-nat logit range overflows, and every kernel this is checked beside - * does it, so doing it differently would be a difference larger than rounding. +/* Max-subtracted softmax in f32 over the last n elements of a row. The max subtraction is needed + * (a 60-nat logit range overflows) and every kernel this is checked against does it. * - * THE ROUND TRIP IS THE CONTRACT. libref writes the exponentials to `y`, reads them back, and - * multiplies by 1/sum -- so a bf16 output carries two roundings. This does the same arithmetic in - * a hot scratch buffer instead of through the output operand: identical result, one pass over - * memory instead of three. */ + * As in libref, the exponentials are rounded through y's dtype before the 1/sum multiply, so a + * bf16 output has two roundings; done here in a scratch buffer instead of through `y`. */ AVX_KERNEL(softmax) { if (!rad_args_have(a, 2)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *y = &a->t[1]; @@ -918,7 +982,7 @@ AVX_KERNEL(softmax) { acc = vf_add(acc, t); } float sum = vf_hsum(acc); - for (; i < n; ++i) { e[i] = std::exp(v[i] - mx); sum += e[i]; } + for (; i < n; ++i) { e[i] = sc_exp(v[i] - mx); sum += e[i]; } roundtrip(y->dtype, e, n, tp); const vf inv = vf_set1(1.0f / sum); diff --git a/libavx/avx_gdn.cpp b/libavx/avx_gdn.cpp index 840649bd..a823a337 100644 --- a/libavx/avx_gdn.cpp +++ b/libavx/avx_gdn.cpp @@ -1,80 +1,57 @@ /* avx_gdn.cpp -- the gated delta net: the two convolution forms, the triangular solve, the chunked * scan, the decode recurrence, and the gated norm. * - * ============================== WHAT IS ACTUALLY SLOW HERE ============================== + * These ops contract heads (128 elements of k against 128 of q, or a [128, 128] state against a + * key), and libref reads every operand of every product through `ldt`, a dtype switch per element. + * In the quadratic ops that is the whole cost (gdn_kkt_solve at chunk 64, head_k 128: 1 M switched + * loads over 8 K distinct elements). Here each chunk's q, k and v rows are widened once into f32 + * panels and every dot is a vector reduction. The algorithms are libref's, step for step: * - * These are not elementwise ops and the win is not the vector width. Every one of them contracts a - * HEAD -- 128 elements of k against 128 of q, or a [128, 128] recurrent state against a key -- and - * libref reads both sides of every one of those products through `ldt`, which is a dtype switch per - * element. In the quadratic ops that is the whole cost: + * The decay is applied per element as e^{g_i - g_j}, not split around a per-chunk reference. + * Only i > j is used and g decreases along the chunk, so the exponent is <= 0 and cannot + * overflow; the split form can, at spans this model reaches. * - * gdn_kkt_solve reads k[ti] and k[tj] for every (i, j) pair of a chunk. At chunk 64 and - * head_k 128 that is 64*64*2*128 = 1.0 M switched loads to compute 64*64 dots - * over data that is 64*128 = 8 K elements. THE K ROWS OF A CHUNK ARE READ ONCE - * HERE, into an f32 panel, and every dot is then a vector reduction over it. + * The triangular inverse is a forward substitution. I + M is unit lower triangular, so the + * inverse is unique and libr4d's blocked WMMA merge agrees with it. * - * gdn_chunk_scan does the same for q, k and v, and additionally re-reads `g` inside three - * separate double loops. Same treatment: one panel per chunk. + * The conv output is rounded before the L2 norm, as the unfused pair does (the conv writes a + * tensor that the prep reads back): it is written to q/k/v and re-read for the norm. * - * That is a change of constant, not of asymptotics -- the algorithms below ARE libref's, step for - * step, because every one of them is a definition rather than a choice: + * The L2 norm does not divide by the head width: rsqrt(sum(x^2) + l2_eps), l2_eps 1e-6 (FLA's + * and libr4d's L2NORM_EPS). * - * THE DECAY IS APPLIED PER ELEMENT as e^{g_i - g_j}, not split about a per-chunk reference. Only - * i > j is kept and g decreases along the chunk, so the difference is always <= 0 and the direct - * form cannot overflow at any span -- which the split form can, at spans this model reaches. + * Rollback contract (spec §10): speculative rejection without recompute. The recurrent state and + * conv window have already absorbed the rejected tokens, so `num_accepted` is required and a + * rejection is a change of read offset: * - * THE TRIANGULAR INVERSE IS A FORWARD SUBSTITUTION. I + M is unit lower triangular, so its - * inverse is unique and the substitution computes it exactly; libr4d's blocked WMMA merge agrees - * with it because there is only one answer to agree with. - * - * THE CONV OUTPUT IS ROUNDED BEFORE THE L2 NORM. A fused kernel rounds to bf16 there because the - * pair of kernels it replaces does -- the conv writes a tensor and the prep reads it back -- and - * matching that is what lets the fused form stand in for the unfused pair on real weights. So the - * conv result is WRITTEN to q/k/v and READ BACK for the norm, rather than carried in registers. - * - * THE L2 NORM HAS NO DIVISION BY THE HEAD WIDTH. It is a norm, not an RMS: - * rsqrt(sum(x^2) + l2_eps), with l2_eps 1e-6, which is FLA's and libr4d's L2NORM_EPS. - * - * ============================== THE ROLLBACK CONTRACT ============================== - * - * A linear-attention kernel pair must support speculative rejection WITHOUT RECOMPUTE (spec §10). - * The recurrent state and the conv window have already absorbed the rejected tokens, so - * `num_accepted` is a required operand and a rejection is a CHANGE OF READ OFFSET: - * - * conv state read at `num_accepted - 1`, rewritten shifted DOWN BY ONE so slots + * conv state read at `num_accepted - 1`, rewritten shifted down by one, so slots * 0..conv_width-3 take the tail of the old history and this step's token t lands at * slot t + conv_width - 2. - * linear state read from state_idx[s, num_accepted - 1]; EVERY candidate token writes its own - * state to state_idx[s, t], because which of them survives verification is not - * known until after this layer has run. + * linear state read from state_idx[s, num_accepted - 1]; every candidate token writes its own + * state to state_idx[s, t], since which survives is known only after this layer. * - * `num_accepted` IS ONE-BASED: it counts the tokens the previous step committed, so 1 is an - * ordinary decode that drafted nothing and 0 is not a value either op can read. + * `num_accepted` is one-based: the number of tokens the previous step committed, so 1 is a plain + * decode with no drafts and 0 is invalid. * - * THE OP DECLARES WHICH STATE CONTRACT IT RUNS UNDER, in its `state_form` parameter. libref and - * this plugin implement "per_candidate", the reading above; libr4d also serves "anchor" -- one - * committed state plus a small replay block, two slots a sequence instead of 1 + n_spec. The two - * produce the same `o` from different states, so both host plugins decline "anchor" by name - * rather than run the per-candidate reading over a cache laid out the other way. libref is the - * oracle for this plugin under per_candidate, and that is what rad-avx-check exercises. + * `state_form` names the state contract: "per_candidate" (above), or "anchor", one committed state + * a sequence plus each token's replay factors beside it, in libr4d's cache layout (AnchorLayout, + * at gdn_recurrent_update). Both forms give the same `o`; an implementation handed the other form + * would continue from the wrong state, so the form is a parameter, never inferred. */ #include "avx_vec.h" #include "avx_common.h" +#include #include using namespace avx; -/* THE VIEW HELPERS ARE `view2` / `view3` / `view4` AND NOT `v2` / `v3` / `v4`, which is what - * libref calls them. The per-level inline namespace in avx_vec.h is named `sc` / `v1` / `v2` / `v3` - * (AVX_SUFFIX), so a file-scope function called `v3` is ambiguous with the namespace at AVX-512 and - * with a different one at each other level -- three of the four levels would fail to compile and - * the fourth would build cleanly, so a build of that one level alone would not show it. +/* The view helpers are `view2` / `view3` / `view4`, not libref's `v2` / `v3` / `v4`: those names + * collide with the per-level inline namespaces (AVX_SUFFIX: sc / v1 / v2 / v3) at three of the four + * levels. * - * The deepest convolution history held in a stack frame. libr4d's width is 4 and no linear- - * attention model in circulation exceeds it by much; a wider request returns RAD_E_UNSUPPORTED by - * name rather than convolving a truncated window, which would be numerically plausible and - * completely wrong. Same number as libref's, so the two refuse the same calls. */ + * Deepest convolution history held on the stack. libr4d's width is 4; a wider request returns + * RAD_E_UNSUPPORTED rather than convolving a truncated window. Same bound as libref. */ enum { AVX_CONV_HIST_MAX = 16 }; struct V3 { const RadTensor* t; int64_t s0, s1, s2; }; @@ -90,10 +67,9 @@ static inline V3 view3(const RadTensor* t, int64_t d1, int64_t d2) { } return v; } -/* The same [tokens, d1, d2] reading for an operand that may be a COLUMN VIEW of a wider row: the - * fp8 delta net's output gate is the tail of a fused [q|k|v|z] projection, so its token stride is - * its own rather than d1*d2. A rank-3 spelling carries all three strides; a rank-2 one carries the - * token stride in stride[0] and view3() would have guessed d1*d2 for it. */ +/* view3 for an operand that may be a column view of a wider row (the fp8 delta net's output gate is + * the tail of a fused [q|k|v|z] projection). At rank 2 the token stride is stride[0], where view3 + * would assume d1*d2. */ static inline V3 view3_rows(const RadTensor* t, int64_t d1, int64_t d2) { if (t->rank != 2) return view3(t, d1, d2); return V3{ t, t->stride[0], d2 * t->stride[1], t->stride[1] }; @@ -108,11 +84,9 @@ static inline int64_t at3(const V3& v, int64_t i, int64_t j, int64_t k) { } static inline int64_t at2(const V2& v, int64_t i, int64_t j) { return i * v.s0 + j * v.s1; } -/* [N, heads, head_v, head_k] -- the shape both the chunked scan's h0/ht and the paged recurrent - * state have. THE SLOT AND HEAD STRIDES ARE READ OFF THE TENSOR and not derived from the shape: a - * paged state cache is padded so its page matches the attention page, and a kernel that derived - * the stride would read every slot but the first at the wrong offset -- which looks exactly like a - * correct kernel producing noise. */ +/* [N, heads, head_v, head_k], the shape of the chunked scan's h0/ht and of the paged recurrent + * state. Slot and head strides come from the tensor, not the shape: a paged state cache is padded + * so its page matches the attention page. */ static inline V4 view4(const RadTensor* t, int64_t d1, int64_t d2, int64_t d3) { V4 v{ t, d1 * d2 * d3, d2 * d3, d3, 1 }; if (t->rank >= 4) { @@ -129,22 +103,24 @@ static inline int64_t at4(const V4& v, int64_t i, int64_t j, int64_t k, int64_t static inline int64_t cu_at(const RadTensor* cu, int64_t i) { return ldi(cu, offlin(cu, i)); } -/* The conv state is [n_slots, conv_dim, state_len]; a rank the caller flattened is read as the - * tight layout that shape implies. */ +/* The conv state is [n_slots, conv_dim, state_len]; a flattened tensor is read as the dense layout + * that shape implies. */ static inline V3 conv_state_view(const RadTensor* cs, int64_t conv_dim, int64_t width, int64_t* state_len) { *state_len = cs->rank >= 3 ? cs->shape[cs->rank - 1] : (width > 1 ? width - 1 : 1); return view3(cs, conv_dim, *state_len); } -/* softplus in the two-sided form, with the large-x cutoff FLA and libr4d both use: above the - * threshold log1p(e^x) IS x to every bit f32 holds, and evaluating it costs an overflow. */ +/* Two-sided softplus with FLA's and libr4d's large-x cutoff: above the threshold log1p(e^x) equals + * x in f32, and evaluating it would overflow. */ static inline float softplus(float x, float thr) { if (x > thr) return x; - return x > 0.0f ? x + std::log1p(std::exp(-x)) : std::log1p(std::exp(x)); + return x > 0.0f ? x + sc_log1p(sc_exp(-x)) : sc_log1p(sc_exp(x)); } -static inline float dotf(const float* a, const float* b, int64_t n) { +/* A dot product with two accumulators: the delta net's summation order, which differs from + * avx_vec.h's four-accumulator dotf. */ +static inline float dot2(const float* a, const float* b, int64_t n) { vf a0 = vf_zero(), a1 = vf_zero(); int64_t i = 0; for (; i + 2 * VF_N <= n; i += 2 * VF_N) { @@ -157,13 +133,10 @@ static inline float dotf(const float* a, const float* b, int64_t n) { return s; } -/* dst += c * src */ -/* Widen-transpose a [cbw, width] tap block starting at channel c0 into tapT[j*cbw + c]: - * the token loops read tap COLUMNS, and this makes them contiguous. 8 rows at a time: - * vector-widen into a 32-float staging block, then scatter the 32 values into the four - * columns (~15ns a block, L1-hot). Loads/stores only, so bit-exact; anything the vector - * form cannot spell -- another width, unpacked rows, an exotic dtype, levels 0/1 -- and - * the ragged tail take the scalar form below it. */ +/* Widen and transpose a [cbw, width] tap block starting at channel c0 into tapT[j*cbw + c], so the + * token loops read tap columns contiguously. The vector form (width 4, dense f32 or bf16 rows, + * AVX2+) widens 8 rows into a 32-float staging block and scatters them into the four columns; + * loads and stores only, so bit-exact. Everything else, and the ragged tail, is scalar. */ static inline void fill_tapT(const RadTensor* w, V2 wv, int64_t c0, int64_t cbw, int64_t width, float* tapT) { #if AVX_LEVEL >= 2 @@ -180,8 +153,8 @@ static inline void fill_tapT(const RadTensor* w, V2 wv, int64_t c0, int64_t cbw, _mm256_store_ps(stg + 16, _mm256_loadu_ps(base + 16)); _mm256_store_ps(stg + 24, _mm256_loadu_ps(base + 24)); } else { - /* bf16 -> f32 is a zero-extend and a shift, NOT cvtph (which reads FP16). - * Same values as cvt_bf16_to_f32, same order. */ + /* bf16 -> f32 is a zero-extend and shift (not cvtph, which reads f16), as in + * cvt_bf16_to_f32. */ const uint16_t* base = (const uint16_t*)w->data + (c0 + c) * 4; for (int k = 0; k < 4; ++k) { __m128i h = _mm_loadu_si128((const __m128i*)(base + k * 8)); @@ -211,8 +184,8 @@ static inline void axpy(float* dst, const float* src, float c, int64_t n) { for (; i < n; ++i) dst[i] += c * src[i]; } -/* A [rows, width] panel of an operand read as [token, head, d], widened into f32 once. This is the - * whole optimisation in the quadratic ops -- see the file header. */ +/* A [rows, width] panel of an operand read as [token, head, d], widened to f32 once (see the file + * header). */ static void panel3(const RadTensor* t, const V3& v, int64_t t0, int64_t rows, int64_t h, int64_t width, float* dst) { for (int64_t r = 0; r < rows; ++r) { @@ -222,12 +195,10 @@ static void panel3(const RadTensor* t, const V3& v, int64_t t0, int64_t rows, in } } -/* One token's convolution output over a channel panel [c0, c0 + cbw), split into q, k and v by - * region and written to each at its head AND ITS OFFSET WITHIN THE HEAD. A panel is 1024 channels - * and a head is K or V of them, so a panel edge falls mid-head whenever the head width does not - * divide 1024 -- 96 or 192, say -- and the piece that starts there begins part way into a head - * and may end part way into another. Each run below is cut at the next head boundary, so it is - * always contiguous within one head's row. */ +/* Writes one token's convolution output over channel panel [c0, c0 + cbw) into q, k and v, each + * piece at its head and its offset within the head. Panels are 1024 channels, so an edge falls + * mid-head when the head width does not divide 1024 (e.g. 96 or 192); runs are cut at head + * boundaries so each is contiguous within one head's row. */ static inline void store_pieces(const float* acc, int64_t cbw, int64_t c0, int64_t bos, int64_t t, const RadTensor* q, const RadTensor* k, const RadTensor* v, V3 qv, V3 kv, V3 vv, int64_t Hg, int64_t K, int64_t V, @@ -257,7 +228,7 @@ static inline void store_pieces(const float* acc, int64_t cbw, int64_t c0, int64 /* ------------------------------------------------------------------ gdn_conv_prep */ /* Everything between the qkv projection and the chunked scan: the width-`conv_width` depthwise - * causal convolution with silu and its state cache, the q/k/v split, the l2 norm over each q and k + * causal convolution with silu and its state cache, the q/k/v split, the L2 norm over each q and k * head, the gate with its per-chunk cumsum, and beta. */ AVX_KERNEL(gdn_conv_prep) { if (a->n_t < 16) return RAD_E_INVAL; @@ -273,15 +244,13 @@ AVX_KERNEL(gdn_conv_prep) { const RadTensor* hini = rad_arg_in(a, 10); if (!x->data || !w->data || !cu->data || !q->data || !k->data || !v->data || !g->data || !beta->data) return RAD_E_INVAL; - /* One of the two, not one of each: a caller that names the gate has to name beta as well, or - * the second read silently falls back into a fused row that may not be there. */ + /* Both or neither: with only one, the other would be read from a fused row that may not + * exist. */ if ((ta != nullptr) != (tb != nullptr)) return RAD_E_INVAL; const int64_t K = p_int(a, "head_k", 0), V = p_int(a, "head_v", 0); - /* `chunk` is RAD_DERIVED and NOTHING HERE CARRIES IT: the gate cumsum is cut at the chunk - * boundary and no operand's shape records where that is. A caller who omitted it gets - * RAD_E_SHAPE by name; the alternative -- treating the sequence as one chunk -- is a decay - * summed over the wrong span, numerically plausible and completely wrong. */ + /* `chunk` is RAD_DERIVED but no operand's shape records it, and the gate cumsum restarts at + * each chunk boundary, so a missing value is refused rather than defaulted. */ const int64_t chunk = p_int(a, "chunk", 0), width = p_int(a, "conv_width", 0); const float l2eps = p_f32(a, "l2_eps", 1e-6f); const float spthr = p_f32(a, "softplus_thr", 20.0f); @@ -291,7 +260,7 @@ AVX_KERNEL(gdn_conv_prep) { const int64_t N = numel(cu) - 1; if (N <= 0) return RAD_E_SHAPE; const int64_t T = cu_at(cu, N); - if (T <= 0) return RAD_OK; /* an empty step is not an error */ + if (T <= 0) return RAD_E_SHAPE; /* zero rows is not a call (docs/OPS.md) */ const int64_t Hg = numel(q) / (T * K); const int64_t H = numel(v) / (T * V); if (Hg <= 0 || H <= 0 || H % Hg != 0) return RAD_E_SHAPE; @@ -301,9 +270,8 @@ AVX_KERNEL(gdn_conv_prep) { const int64_t xrow = x->rank >= 2 ? x->stride[x->rank - 2] : (conv_dim + (ta ? 0 : 2 * H)); const int64_t xcol = laststride(x); - /* THE BOUND IS THE VIEW'S AND NOT THE BUFFER'S. `x` may be a column slice of a wider row, and - * a slice's numel counts only the elements it names -- so the flat product would refuse a call - * that is perfectly in range. Rank 2 or more spells the extent in the shape. */ + /* Bound by the view, not numel: `x` may be a column slice of a wider row, whose numel counts + * only the named elements. At rank >= 2 the shape gives the extent. */ const int64_t xneed = conv_dim + (ta ? 0 : 2 * H); if (x->rank >= 2) { if (x->shape[x->rank - 1] < xneed || x->shape[x->rank - 2] < T) return RAD_E_SHAPE; @@ -323,14 +291,11 @@ AVX_KERNEL(gdn_conv_prep) { const V2 bgv = tb ? view2(tb, H) : V2{ nullptr, 0, 0 }; /* ---- phase 1: the convolution, straight into q / k / v ---------------------------------- */ - /* TOKENS OUTER, CHANNELS VECTOR. The other nest -- each channel walked down the tokens -- - * reads x strided (a cache line per bf16) and issues a dtype switch plus a scalar exp per - * element. Walking tokens outer over channel panels turns the tap loop into vector FMA - * over contiguous rows. Per element the order is unchanged -- bias, taps ascending, silu - * last -- and the multiply and add stay SEPARATE ops: an FMA would fuse one rounding the - * reference keeps. The silu goes through vf_silu (the exact minimax, ~1 ulp from libm), - * which the bf16 store that follows cannot carry. Panels are 1024 channels, and a panel - * edge may fall inside a head; store_pieces places each piece at its offset in the head. */ + /* Tokens outer, channels vectorised over contiguous rows (channel-outer would read x + * strided, one cache line per element, with a dtype switch and scalar exp each). Per element + * the order is bias, taps ascending, silu last, with separate mul and add rather than FMA, to + * keep the reference's roundings. vf_silu is ~1 ulp from libm, below what the bf16 store + * keeps. Panels are 1024 channels; store_pieces handles edges inside a head. */ const int64_t CB = 1024; const int64_t npan = (conv_dim + CB - 1) / CB; AVX_PARALLEL_FOR_IF(N * npan >= 4) @@ -340,20 +305,17 @@ AVX_KERNEL(gdn_conv_prep) { const int64_t bos = cu_at(cu, n), slen = cu_at(cu, n + 1) - bos; if (slen <= 0) continue; const int64_t slot = sidx ? ldi(sidx, offlin(sidx, n)) : n; - /* A zero `has_init` means the slot holds no history: the window in front of the - * sequence's first token is ZEROS, not whatever the slot last held. Without it a - * fresh sequence landing on a recycled slot convolves the previous sequence's tail - * into its first conv_width-1 tokens, which is fluent output with the wrong prefix. */ + /* `has_init` zero: the slot holds no history and the window before the first token is + * zeros, so a new sequence on a recycled slot does not read the previous one's tail. */ const bool warm = !hini || ldi(hini, offlin(hini, n)) != 0; float* acc = scratch_f32((size_t)cbw); float* xr = scratch_f32_b((size_t)cbw); - /* Taps transposed to [width][cbw], widened once per panel: the token loop reads tap - * columns, which are contiguous in this layout. Launch-constant, thread-local. */ + /* Taps transposed to [width][cbw], widened once per panel. */ float* tapT = scratch_f32_c((size_t)width * (size_t)cbw); fill_tapT(w, wv, c0, cbw, width, tapT); - /* Bias, widened once per panel into the raw slot (the three f32 slots are taken); - * each token starts its accumulator as a copy of this. */ + /* Bias, widened once per panel into the raw scratch slot (the three f32 slots are in + * use); each token's accumulator starts as a copy. */ float* bs = (float*)scratch_raw((size_t)cbw * sizeof(float) + 64); if (bias) { if (laststride(bias) == 1) @@ -365,7 +327,7 @@ AVX_KERNEL(gdn_conv_prep) { } for (int64_t t = 0; t < slen; ++t) { - /* Fresh accumulator per token: bias copy, then taps ascending. */ + /* Per token: bias, then taps ascending. */ int64_t c = 0; for (; c + VF_N <= cbw; c += VF_N) vf_storeu(acc + c, vf_loadu(bs + c)); for (; c < cbw; ++c) acc[c] = bs[c]; @@ -388,11 +350,9 @@ AVX_KERNEL(gdn_conv_prep) { for (int64_t c = 0; c < cbw; ++c) xr[c] = ldt(cs, at3(cvs, slot, c0 + c, src + width - 1)); } else { - for (int64_t c = 0; c < cbw; c += VF_N) vf_storeu(xr + c, vf_zero()); - for (int64_t c = (cbw / VF_N) * VF_N; c < cbw; ++c) xr[c] = 0.0f; + std::memset(xr, 0, (size_t)cbw * sizeof(float)); } - /* Separate mul and add -- NOT an FMA -- so the rounding matches the reference's - * scalar loop bit for bit. */ + /* Separate mul and add, not FMA, to match the reference bit for bit. */ const float* tc = tapT + j * cbw; c = 0; for (; c + VF_N <= cbw; c += VF_N) @@ -400,17 +360,16 @@ AVX_KERNEL(gdn_conv_prep) { vf_loadu(acc + c))); for (; c < cbw; ++c) acc[c] += xr[c] * tc[c]; } - /* Silu in place, then split into q/k/v, through the same helper the decode entry - * uses (below), which places a piece at its head AND its offset within the head. */ + /* Silu in place, then split into q/k/v. */ c = 0; for (; c + VF_N <= cbw; c += VF_N) vf_storeu(acc + c, vf_silu(vf_loadu(acc + c))); - for (; c < cbw; ++c) acc[c] /= (1.0f + std::exp(-acc[c])); + for (; c < cbw; ++c) acc[c] /= (1.0f + sc_exp(-acc[c])); store_pieces(acc, cbw, c0, bos, t, q, k, v, qv, kv, vv, Hg, K, V, conv_dim); } } - /* ---- phase 2: the l2 norm over each q and k head, reading the ROUNDED conv output -------- */ + /* ---- phase 2: the L2 norm over each q and k head, reading the rounded conv output -------- */ AVX_PARALLEL_FOR_IF(T * Hg * 2 >= 32) for (int64_t th = 0; th < T * Hg * 2; ++th) { const int64_t which = th / (T * Hg); @@ -423,7 +382,7 @@ AVX_KERNEL(gdn_conv_prep) { const float* u = (zv.s2 == 1) ? row_f32_in(z->dtype, byte_at(z->data, z->dtype, b), buf, K) : buf; if (zv.s2 != 1) for (int64_t d = 0; d < K; ++d) buf[d] = ldt(z, b + d * zv.s2); - /* No division by K: this is an L2 norm, not an RMS. */ + /* L2 norm, not RMS: no division by K. */ const float inv = 1.0f / std::sqrt(row_sumsq(u, K) + l2eps); if (zv.s2 == 1) { float* o2 = scratch_f32_b((size_t)K); @@ -438,17 +397,15 @@ AVX_KERNEL(gdn_conv_prep) { } /* ---- phase 3: the gate, its per-chunk cumsum, and beta ----------------------------------- */ - /* The cumsum is per CHUNK and per sequence, because that is what the scan consumes: g[j] is the - * decay from the start of j's chunk up to and including j. Sequential in t by construction -- - * a running sum is the one shape no vectorisation reaches, and the exp/softplus per token is - * what it costs. */ + /* The cumsum restarts per chunk and per sequence, as the scan consumes it: g[j] is the decay + * from the start of j's chunk through j. A running sum, so sequential in t. */ AVX_PARALLEL_FOR_IF(N * H >= 4) for (int64_t nh = 0; nh < N * H; ++nh) { const int64_t n = nh / H, h = nh % H; const int64_t bos = cu_at(cu, n), slen = cu_at(cu, n + 1) - bos; const float alog = A_log ? ldt(A_log, h * laststride(A_log)) : 0.0f; const float dtb = dt_bias ? ldt(dt_bias, h * laststride(dt_bias)) : 0.0f; - const float negexp = -std::exp(alog); + const float negexp = -sc_exp(alog); float run = 0.0f; for (int64_t t = 0; t < slen; ++t) { if (t % chunk == 0) run = 0.0f; @@ -458,14 +415,13 @@ AVX_KERNEL(gdn_conv_prep) { : ldt(x, (bos + t) * xrow + (conv_dim + H + h) * xcol); run += negexp * softplus(av_ + dtb, spthr); stt(g, at2(gv, bos + t, h), run); - stt(beta, at2(bv, bos + t, h), 1.0f / (1.0f + std::exp(-bvl))); + stt(beta, at2(bv, bos + t, h), 1.0f / (1.0f + sc_exp(-bvl))); } } /* ---- phase 4: rewrite the conv state from the sequence's last width-1 tokens -------------- */ - /* After phase 1, so the history it overwrites has already been read. A sequence shorter than - * width-1 keeps what the old state held in front of its tokens, which is what makes chunked - * prefill work: the second chunk of a sequence continues from the first. */ + /* After phase 1, which has read the old history. A sequence shorter than width-1 keeps the + * old state ahead of its tokens, so a sequence's next prefill chunk continues from this one. */ if (cs->data && width > 1) { AVX_PARALLEL_FOR_IF(N * conv_dim >= 32) for (int64_t nc = 0; nc < N * conv_dim; ++nc) { @@ -487,28 +443,25 @@ AVX_KERNEL(gdn_conv_prep) { return RAD_OK; } -/* Silu in place over a channel panel, then split into q/k/v by region. Shared by the two - * convolution entry points; the split itself is store_pieces, above both. */ +/* Silu in place over a channel panel, then store_pieces. */ static inline void silu_store_pieces(float* acc, int64_t cbw, int64_t c0, int64_t bos, int64_t t, const RadTensor* q, const RadTensor* k, const RadTensor* v, V3 qv, V3 kv, V3 vv, int64_t Hg, int64_t K, int64_t V, int64_t conv_dim) { - /* Exact silu only: the cheap form (vf_silu_fast, as silu_mul uses), keyed on all-bf16 - * outputs, measures unmeasurably different here -- the token loop is frontend-bound and the - * extra branch buys nothing. Do not switch to it without measuring. */ + /* Exact silu only: vf_silu_fast (as silu_mul uses for bf16 outputs) made no measurable + * difference here, since the token loop is frontend-bound. */ int64_t c = 0; for (; c + VF_N <= cbw; c += VF_N) vf_storeu(acc + c, vf_silu(vf_loadu(acc + c))); - for (; c < cbw; ++c) acc[c] /= (1.0f + std::exp(-acc[c])); + for (; c < cbw; ++c) acc[c] /= (1.0f + sc_exp(-acc[c])); store_pieces(acc, cbw, c0, bos, t, q, k, v, qv, kv, vv, Hg, K, V, conv_dim); } /* ------------------------------------------------------------------ gdn_conv_update */ -/* The same convolution for a decode step, against the rolling window. The two things that matter - * are that the READ starts at num_accepted-1 and that the rewrite shifts the buffer DOWN BY ONE so - * the next step can do the same -- a rejection is a change of read offset and not a recompute, - * which is the whole reason this is a separate entry point rather than a flag on the prefill one. +/* The convolution for a decode step against the rolling window: the read starts at + * num_accepted - 1 and the rewrite shifts the window down by one (the rollback contract in the + * file header). * - * No l2 norm here: on the decode path the recurrent update does it, which is where libr4d puts it. */ + * No L2 norm here; on the decode path the recurrent update applies it, as in libr4d. */ AVX_KERNEL(gdn_conv_update) { if (a->n_t < 10) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *w = &a->t[1], *cs = &a->t[3], *cu = &a->t[6]; @@ -527,7 +480,7 @@ AVX_KERNEL(gdn_conv_update) { const int64_t N = numel(cu) - 1; if (N <= 0) return RAD_E_SHAPE; const int64_t T = cu_at(cu, N); - if (T <= 0) return RAD_OK; + if (T <= 0) return RAD_E_SHAPE; const int64_t Hg = numel(q) / (T * K); const int64_t H = numel(v) / (T * V); if (Hg <= 0 || H <= 0 || H % Hg != 0) return RAD_E_SHAPE; @@ -539,9 +492,8 @@ AVX_KERNEL(gdn_conv_update) { int64_t state_len = 0; const V3 cvs = conv_state_view(cs, conv_dim, width, &state_len); - /* Checked rather than clamped: a cache too shallow for this step's offset is a caller bug - * whose symptom would otherwise be a silently truncated history. Before the loop, because an - * OpenMP body cannot return. */ + /* A state too shallow for this step's offset is refused, not clamped (that would silently + * truncate history). Checked before the loop; an OpenMP body cannot return. */ for (int64_t n = 0; n < N; ++n) { const int64_t slen = cu_at(cu, n + 1) - cu_at(cu, n); const int64_t off = nacc ? ldi(nacc, offlin(nacc, n)) - 1 : 0; @@ -553,9 +505,8 @@ AVX_KERNEL(gdn_conv_update) { const V3 qv = view3(q, Hg, K), kv = view3(k, Hg, K), vv = view3(v, H, V); const V2 wv = view2(w, width); - /* Tokens outer, channels vector -- the prefill entry's form. The channel-outer nest reads a - * cache line per bf16 and pays a switch and a scalar exp per element; at decode slen is 1 but - * conv_dim is 10240, so the problem is the same one. */ + /* Tokens outer, channels vectorised, as in gdn_conv_prep (at decode slen is 1 but conv_dim + * is 10240). */ const int64_t CB = 1024; const int64_t npan = (conv_dim + CB - 1) / CB; AVX_PARALLEL_FOR_IF(N * npan >= 4) @@ -572,9 +523,8 @@ AVX_KERNEL(gdn_conv_update) { float* xr = scratch_f32_b((size_t)cbw); float* tapT = scratch_f32_c((size_t)width * (size_t)cbw); fill_tapT(w, wv, c0, cbw, width, tapT); - /* ONE raw block, partitioned by hand (single arena slot): bias panel, then the - * (width-1) history rows over this panel, widened once -- only the first width-1 - * tokens read history. */ + /* One raw block (single scratch slot): the bias panel, then the width-1 history rows of + * this panel, widened once. Only the first width-1 tokens read history. */ float* raw = (float*)scratch_raw(((size_t)cbw + (size_t)(width - 1) * (size_t)cbw) * sizeof(float) + 64); float* bs = raw; @@ -610,12 +560,11 @@ AVX_KERNEL(gdn_conv_update) { for (int64_t c = 0; c < cbw; ++c) xr[c] = ldt(x, (bos + src) * xrow + (c0 + c) * xcol); } else { - /* src + width - 1 lies in [0, width - 2]: the history segment above. */ + /* src + width - 1 is in [0, width - 2]: the history segment. */ const float* hs = hseg + (src + width - 1) * cbw; for (int64_t c = 0; c < cbw; ++c) xr[c] = hs[c]; } - /* Separate mul and add -- NOT an FMA -- matching the scalar reference's two - * roundings. */ + /* Separate mul and add, not FMA, to match the reference's two roundings. */ const float* tc = tapT + j * cbw; c = 0; for (; c + VF_N <= cbw; c += VF_N) @@ -625,17 +574,15 @@ AVX_KERNEL(gdn_conv_update) { } silu_store_pieces(acc, cbw, c0, bos, t, q, k, v, qv, kv, vv, Hg, K, V, conv_dim); } - /* Shift down by one: the tail of the history this step READ -- the window at - * `off`, not the one at zero -- then this step's tokens. Row memcpys where both - * sides are channel-contiguous and the dtypes match (a move, not a conversion); - * the scalar form otherwise. Slot i takes slot off + i + 1, which no earlier - * iteration has written, so the ascending walk is safe in place. */ + /* Shift down by one: the tail of the window this step read (at `off`, not zero), then + * this step's tokens. Slot i takes slot off + i + 1, which no earlier iteration has + * written, so the ascending walk is safe in place. Byte moves when both sides are + * channel-contiguous with the same dtype; scalar otherwise. */ if (width > 1) { const uint32_t csbits = rad_dtype_bits(cs->dtype); const size_t elbytes = (size_t)csbits / 8; - /* memmove, not memcpy: the shift reads row off+i+1 after row i was written, so the - * ranges can overlap when the history stride is short. Byte dtypes only -- a - * sub-byte element has no whole-byte row to move. */ + /* memmove: the ranges can overlap when the history stride is short. Whole-byte + * dtypes only. */ if (cvs.s1 == 1 && xcol == 1 && x->dtype == cs->dtype && csbits % 8 == 0 && elbytes > 0) { for (int64_t i = 0; i + 1 < width - 1; ++i) @@ -665,26 +612,21 @@ AVX_KERNEL(gdn_conv_update) { } /* ------------------------------------------------------------------ gdn_kkt_solve */ -/* A = (I + strict_lower(diag(beta) . K K^T . e^{g_i - g_j}))^{-1}, per chunk, per v head. - * - * THE K ROWS OF A CHUNK ARE WIDENED ONCE. libref reads k[ti] and k[tj] through `ldt` for every - * (i, j) pair, which at chunk 64 and head_k 128 is a million switched loads over eight thousand - * distinct elements. One panel per chunk makes every dot a vector reduction, and `g` and `beta` - * are pulled into the same frame for the same reason. */ +/* A = (I + strict_lower(diag(beta) . K K^T . e^{g_i - g_j}))^{-1}, per chunk, per v head. The + * chunk's k rows, `g` and `beta` are widened once (see the file header). */ AVX_KERNEL(gdn_kkt_solve) { if (!rad_args_have(a, 5)) return RAD_E_INVAL; const RadTensor *k = &a->t[0], *beta = &a->t[1], *g = &a->t[2], *cu = &a->t[3], *A = &a->t[4]; const int64_t K = p_int(a, "head_k", 0); - /* RAD_DERIVED: A is [T, heads, chunk] and the caller sized it, which is this plugin's rule for - * every other extent too. */ + /* RAD_DERIVED: taken from A's shape [T, heads, chunk] when absent. */ const int64_t chunk = p_int(a, "chunk", A->rank >= 3 ? A->shape[A->rank - 1] : 0); if (K <= 0 || chunk <= 0) return RAD_E_SHAPE; const int64_t N = numel(cu) - 1; if (N <= 0) return RAD_E_SHAPE; const int64_t T = cu_at(cu, N); - if (T <= 0) return RAD_OK; + if (T <= 0) return RAD_E_SHAPE; const int64_t H = numel(beta) / T; const int64_t Hg = numel(k) / (T * K); if (H <= 0 || Hg <= 0 || H % Hg != 0) return RAD_E_SHAPE; @@ -698,7 +640,7 @@ AVX_KERNEL(gdn_kkt_solve) { for (int64_t nh = 0; nh < N * H; ++nh) { const int64_t n = nh / H, h = nh % H, hk = h / grp; const int64_t bos = cu_at(cu, n), slen = cu_at(cu, n + 1) - bos; - /* ONE scratch call, carved by hand: a second may reallocate and invalidate the first. */ + /* One scratch call, carved by hand; a second could reallocate the first. */ const size_t need = (size_t)(chunk * chunk + chunk + chunk * K + 2 * chunk + chunk) + 16; float* wsp = scratch_f32(need); float* Am = wsp; /* [chunk, chunk] the inverse, in f32 */ @@ -717,23 +659,21 @@ AVX_KERNEL(gdn_kkt_solve) { } for (int64_t i = 0; i < L; ++i) { const int64_t ti = bos + c0 + i; - /* e^{g_i - g_j} over the row, vectorised (vf_exp ~1 ulp from libm -- the - * gate's question): one L1 pass instead of i scalar exps. */ + /* e^{g_i - g_j} over the row with vf_exp (~1 ulp from libm, within tolerance). */ { const vf vg = vf_set1(gp[i]); int64_t j = 0; for (; j + VF_N <= i; j += VF_N) vf_storeu(ev + j, vf_exp(vf_sub(vg, vf_loadu(gp + j)))); - for (; j < i; ++j) ev[j] = std::exp(gp[i] - gp[j]); + for (; j < i; ++j) ev[j] = sc_exp(gp[i] - gp[j]); } for (int64_t j = 0; j < i; ++j) - row[j] = bp[i] * dotf(kp + i * K, kp + j * K, K) * ev[j]; + row[j] = bp[i] * dot2(kp + i * K, kp + j * K, K) * ev[j]; /* (I + M) A = I, row by row: A[i][j] = delta - sum_{j<=lt[4], *beta = &a->t[5], *cu = &a->t[7]; const RadTensor *o = &a->t[8], *ht = &a->t[9]; const RadTensor* h0 = rad_arg_in(a, 6); - /* THE STATE SLOT, when the caller keeps its recurrent states in a pool the batch does not - * index positionally. Absent, a row owns slot n. */ + /* Optional state slot per sequence, for a state pool not indexed by batch position; absent, + * sequence n owns slot n. */ const RadTensor* sidx = rad_arg_in(a, 10); if (!q->data || !k->data || !v->data || !A->data || !g->data || !beta->data || !cu->data || !o->data) return RAD_E_INVAL; @@ -779,7 +719,7 @@ AVX_KERNEL(gdn_chunk_scan) { const int64_t N = numel(cu) - 1; if (N <= 0) return RAD_E_SHAPE; const int64_t T = cu_at(cu, N); - if (T <= 0) return RAD_OK; + if (T <= 0) return RAD_E_SHAPE; const int64_t H = numel(beta) / T; const int64_t Hg = numel(q) / (T * K); if (H <= 0 || Hg <= 0 || H % Hg != 0) return RAD_E_SHAPE; @@ -802,16 +742,15 @@ AVX_KERNEL(gdn_chunk_scan) { for (int64_t nh = 0; nh < N * H; ++nh) { const int64_t n = nh / H, h = nh % H, hk = h / grp; const int64_t bos = cu_at(cu, n), slen = cu_at(cu, n + 1) - bos; - /* COLUMN 0 IS THE STATE. A row may be wider -- a decode kernel serving speculation asks - * for scratch beside it -- and the scan writes the state and nothing else. */ + /* Column 0 of state_idx is the slot. A row may be wider (a speculative decode kernel + * keeps more slots beside it); the scan writes only this one. */ const int64_t sw = sidx && sidx->rank >= 1 ? sidx->stride[0] : 1; const int64_t sn = sidx ? ldi(sidx, n * sw) : n; - if (sn < 0) continue; /* a padded row owns no state */ + if (sn < 0) continue; /* padded row: no state */ - /* One scratch request, carved by hand. The three panels (q, k, v) are what makes the - * quadratic loops below vector work instead of a dtype switch per element. Ap/expv do - * the same for the A weights and the gate exponentials: at chunk 64 the O-loop issues - * L*L/2 scalar exps a chunk, which is most of the wall time at model shape. */ + /* One scratch request, carved by hand: the q/k/v panels, plus Ap/expv holding the A + * weights and gate exponentials once per chunk (scalar exps in the O loop were most of the + * time at model shape). */ const size_t need = (size_t)(V * K + 3 * chunk * V + 2 * chunk * K + 3 * chunk + V + K + chunk * chunk + chunk + K * V) + 32; float* wsp = scratch_f32(need); @@ -824,18 +763,14 @@ AVX_KERNEL(gdn_chunk_scan) { float* vp = kp + chunk * K; /* [chunk, V] */ float* gp = vp + chunk * V; /* [chunk] */ float* bp = gp + chunk; /* [chunk] */ - /* Two more, and they get their own names rather than reusing a dead buffer: the output row - * and the decayed key. Carving them out of `Wm`'s tail and out of `row` would be correct - * only while chunk*V >= V and K <= chunk -- two conditions that hold at every shape this is - * checked at and neither of which the op promises. A buffer aliased under a size - * assumption fails first on a geometry nobody checked. */ + /* Own buffers for the output row and the decayed key, not aliases of `Wm` or `row`, + * which would only fit while K <= chunk, a condition the op does not promise. */ float* acc = bp + chunk; /* [V] the output row being formed */ float* gk = acc + V; /* [K] e^{g_last - g_j} . k[j] */ float* Ap = gk + K; /* [chunk, chunk] A weights, one row per i */ float* expv = Ap + chunk * chunk; /* [chunk] e^{g_j} */ - /* The initial state, widened a row at a time rather than switched per element -- the - * recurrent update's form, same values. */ + /* Initial state, widened a row at a time. */ if (h0 && h0v.s3 == 1) { for (int64_t e = 0; e < V; ++e) row_to_f32(h0->dtype, @@ -856,17 +791,14 @@ AVX_KERNEL(gdn_chunk_scan) { bp[j] = ldt(beta, at2(bv, bos + c0 + j, h)); } const float glast = gp[L - 1]; - /* e^{g_j} once per j, vectorised: the W-loop and the decay below each spent a - * scalar exp per (j) and per (i, j). vf_exp's minimax is ~1 ulp from libm -- - * a tolerance question the gate answers, not a second definition. */ + /* e^{g_j} once per j, vectorised (vf_exp is ~1 ulp from libm, within tolerance). */ { int64_t j = 0; for (; j + VF_N <= L; j += VF_N) vf_storeu(expv + j, vf_exp(vf_loadu(gp + j))); - for (; j < L; ++j) expv[j] = std::exp(gp[j]); + for (; j < L; ++j) expv[j] = sc_exp(gp[j]); } - /* The A rows for this chunk's tokens, widened once: the triangle below reads - * A[ti, h, 0..i] 2k times a chunk through a dtype switch. */ + /* The chunk's A rows, widened once for the triangle below. */ if (Av.s2 == 1) { for (int64_t i = 0; i < L; ++i) row_to_f32(A->dtype, @@ -874,16 +806,16 @@ AVX_KERNEL(gdn_chunk_scan) { Ap + i * chunk, chunk); } - /* W = beta . (V - e^g . (K S)). Two transposed-S k-outer forms -- Wm-streaming and - * register-blocked over a 4-chain -- both measure slower than this dot loop. */ + /* W = beta . (V - e^g . (K S)). Transposed-S k-outer forms (streaming Wm, or + * register-blocked) measured slower than this dot loop. */ for (int64_t j = 0; j < L; ++j) { const float ge = expv[j]; for (int64_t e = 0; e < V; ++e) Wm[j * V + e] = - bp[j] * (vp[j * V + e] - ge * dotf(kp + j * K, S + e * K, K)); + bp[j] * (vp[j * V + e] - ge * dot2(kp + j * K, S + e * K, K)); } - /* V' = A W, with A unit lower triangular so only j <= i contributes. Accumulated over - * e as a vector, which is the same j order libref sums in. */ + /* V' = A W; A is unit lower triangular, so only j <= i contributes. Vectorised over e, + * summing in libref's j order. */ for (int64_t i = 0; i < L; ++i) { const int64_t ti = bos + c0 + i; for (int64_t e = 0; e < V; ++e) Vp[i * V + e] = 0.0f; @@ -899,29 +831,27 @@ AVX_KERNEL(gdn_chunk_scan) { for (int64_t i = 0; i < L; ++i) { const int64_t ti = bos + c0 + i; const float gi = gp[i]; - const float ge = std::exp(gi); - /* e^{gi - g_j} over the row, vectorised, then the dots: splitting the exp - * out of the dot loop costs one L1 pass over 64 floats and removes L - * scalar exps per i. */ + const float ge = sc_exp(gi); + /* e^{gi - g_j} over the row, vectorised, before the dots. */ { const vf vg = vf_set1(gi), vs = vf_set1(scale); int64_t j = 0; for (; j + VF_N <= i + 1; j += VF_N) vf_storeu(row + j, vf_mul(vs, vf_exp(vf_sub(vg, vf_loadu(gp + j))))); - for (; j <= i; ++j) row[j] = scale * std::exp(gi - gp[j]); + for (; j <= i; ++j) row[j] = scale * sc_exp(gi - gp[j]); } for (int64_t j = 0; j <= i; ++j) - row[j] *= dotf(qp + i * K, kp + j * K, K); + row[j] *= dot2(qp + i * K, kp + j * K, K); for (int64_t e = 0; e < V; ++e) - acc[e] = scale * ge * dotf(qp + i * K, S + e * K, K); + acc[e] = scale * ge * dot2(qp + i * K, S + e * K, K); for (int64_t j = 0; j <= i; ++j) axpy(acc, Vp + j * V, row[j], V); if (ov.s2 == 1) out_row(o, at3(ov, ti, h, 0), V, acc); else for (int64_t e = 0; e < V; ++e) stt(o, at3(ov, ti, h, e), acc[e]); } /* S = e^{g_last} S + V'^T (e^{g_last - g_j} . K) */ { - const float el = std::exp(glast); + const float el = sc_exp(glast); for (int64_t e = 0; e < V; ++e) { const vf ve = vf_set1(el); int64_t d = 0; @@ -929,21 +859,18 @@ AVX_KERNEL(gdn_chunk_scan) { vf_storeu(S + e * K + d, vf_mul(vf_loadu(S + e * K + d), ve)); for (; d < K; ++d) S[e * K + d] *= el; } - /* e^{g_last - g_j} over the chunk, vectorised into `row` (dead here): one - * pass instead of L scalar exps. */ + /* e^{g_last - g_j} over the chunk, vectorised into `row` (free here). */ { const vf vg = vf_set1(glast); int64_t j = 0; for (; j + VF_N <= L; j += VF_N) vf_storeu(row + j, vf_exp(vf_sub(vg, vf_loadu(gp + j)))); - for (; j < L; ++j) row[j] = std::exp(glast - gp[j]); + for (; j < L; ++j) row[j] = sc_exp(glast - gp[j]); } for (int64_t j = 0; j < L; ++j) { const float gs = row[j]; - /* gs . k[j] formed ONCE per j rather than per (e, d), and in THAT ASSOCIATION: - * libref writes `Vp * (gs * k)`, and f32 multiplication is not associative, so - * forming (Vp * gs) * k instead would move the answer in the last bits on - * every element of the state. */ + /* gs * k[j] formed once per j, in libref's association `Vp * (gs * k)`; + * (Vp * gs) * k would differ in the last bits. */ const vf vg = vf_set1(gs); int64_t d = 0; for (; d + VF_N <= K; d += VF_N) @@ -970,11 +897,48 @@ AVX_KERNEL(gdn_chunk_scan) { return RAD_OK; } +/* ------------------------------------------------------------------ the anchor state form + * + * docs/OPS.md `state_form`, libref's reading (ref_gdn.cpp) of libr4d's layout: under `anchor` a + * sequence keeps one committed state, and each step records its tokens' rank-1 update factors + * beside it; the next step replays the first `num_accepted` of them onto the state before running + * its own tokens. + * + * state_idx six columns: 0..2 the anchor, 3..5 the factor block. A paged caller's window can + * shift by -1, 0 or +1 pages a step; the anchor is published at column 2 and each + * factor copy is stamped with its column (1, 2, 3), so the next step reads the stamp + * at column 4 and the anchor at the column it implies. A zeroed block reads as no + * shift. + * factors per token, inside the head's [V, K] block of the factor slot: the normalised k once + * per 32-row group of V, then v, then (g, beta) once per group, each group's rows + * replaying from their own copy; room for `tmax` tokens, the stamp just past them. + * + * libr4d's kernel is K = V = 128, where the block holds kTmax = 16 tokens and the stamp sits at + * 16 * fstr; square heads from 64 up hold 16 too, so there the layout is libr4d's byte for byte. + * A smaller head's block holds fewer tokens' factors (a 16 x 16 head: 7), so `tmax` is as many as + * fit before the stamp, and a step or an accepted prefix longer than that is refused (libref's + * rule, docs/OPS.md). */ +namespace { +struct AnchorLayout { + static constexpr int64_t kTmax = 16; + int64_t groups, fstr, vb, gb, tmax, mark; + AnchorLayout(int64_t K, int64_t V) + : groups((V + 31) / 32), fstr(groups * K + V + 2 * groups), vb(groups * K), + gb(groups * K + V), tmax(std::min(kTmax, (V * K - 1) / fstr)), + mark(tmax * fstr) {} + /* The anchor's column, from the stamp at the factor block `fb`'s `mark`. */ + int anchor_col(const RadTensor* st, int64_t fb) const { + const int m = (int)(ldt(st, fb + mark) + 0.5f) - 1; + return 3 - ((m >= 0 && m <= 2) ? m : 1); + } +}; +} // namespace + /* ------------------------------------------------------------------ gdn_recurrent_update */ -/* What decode runs where prefill runs the chunked scan, against the PAGED state cache: the initial - * state comes from the slot the last accepted token wrote and EVERY candidate token writes its own - * slot, because which of them survives verification is not known until after this layer has run. - * The gated RMS norm is folded into the epilogue, which is where libr4d puts it too. */ +/* Decode's counterpart of the chunked scan, against the paged state cache: the initial state is + * read from the slot the last accepted token wrote, and every candidate token writes its own slot + * (see the rollback contract), or under `anchor` the replayed state is published and each token's + * factors are written instead. The gated RMS norm is folded into the epilogue, as in libr4d. */ AVX_KERNEL(gdn_recurrent_update) { if (a->n_t < 14) return RAD_E_INVAL; const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *av = &a->t[3], *bvt = &a->t[4]; @@ -986,19 +950,15 @@ AVX_KERNEL(gdn_recurrent_update) { const RadTensor* cu = rad_arg_in(a, 10); const RadTensor* z = rad_arg_in(a, 11); const RadTensor* nw = rad_arg_in(a, 12); - /* The out projection's quantiser, folded in. Optional and all-or-nothing. */ + /* Optional fused quantiser for the out projection (o_q and o_scale). */ const RadTensor* oq = (a->n_t > 14 && a->t[14].data) ? &a->t[14] : nullptr; const RadTensor* osc = (a->n_t > 15 && a->t[15].data) ? &a->t[15] : nullptr; if (!q->data || !k->data || !v->data || !av->data || !bvt->data || !state->data || !o->data || !cu) return RAD_E_INVAL; - /* ONLY THE PER-CANDIDATE STATE CONTRACT, AND ANY OTHER IS DECLINED BY NAME, as libref declines - * it. Under "anchor" the cache holds one committed state a sequence plus a block of replay - * factors and the accepted prefix is replayed onto it next step; the `o` that contract - * produces is the same, the state is not, so running this reading over an anchor cache would - * compute the right output once and resume every later step from the wrong state. */ const char* sf = p_str(a, "state_form", "per_candidate"); - if (sf && std::strcmp(sf, "per_candidate") != 0) return RAD_E_UNSUPPORTED; + const bool anchor = sf && std::strcmp(sf, "anchor") == 0; + if (!anchor && sf && std::strcmp(sf, "per_candidate") != 0) return RAD_E_UNSUPPORTED; const int64_t K = p_int(a, "head_k", 0), V = p_int(a, "head_v", 0); const float scale = p_f32(a, "scale", 1.0f); @@ -1007,10 +967,11 @@ AVX_KERNEL(gdn_recurrent_update) { const float spthr = p_f32(a, "softplus_thr", 20.0f); static const char* kActs[] = { "silu", "sigmoid" }; const int nact = p_enum(a, "act", kActs, 2, 0); + if (nact != 0 && nact != 1) return RAD_E_INVAL; if (K <= 0 || V <= 0) return RAD_E_SHAPE; - /* The head count and the token count come off the operands: v is [T, head_v_count, head_v], so - * a rank-3 value tensor names both. `n_head_v` overrides it for a flattened view. */ + /* Head and token counts come from v ([T, n_head_v, head_v]); `n_head_v` overrides for a + * flattened view. */ int64_t Hv = p_int(a, "n_head_v", 0); if (Hv <= 0) Hv = v->rank >= 3 ? v->shape[v->rank - 2] : 0; if (Hv <= 0) return RAD_E_SHAPE; @@ -1020,9 +981,7 @@ AVX_KERNEL(gdn_recurrent_update) { if (Hg <= 0 || Hv % Hg != 0) return RAD_E_SHAPE; const int64_t grp = Hv / Hg; - /* N COMES FROM cu AND NOTHING ELSE: cu is [N+1] and its length minus one IS the sequence - * count. Deriving it from state_idx and trusting cu to be at least as long is an off-by-one - * waiting to happen. */ + /* The sequence count comes from cu ([N+1]) only. */ const int64_t n_seq = numel(cu) - 1; if (n_seq <= 0) return RAD_E_SHAPE; if (cu_at(cu, n_seq) != Tk) return RAD_E_SHAPE; @@ -1035,19 +994,54 @@ AVX_KERNEL(gdn_recurrent_update) { const V3 zv = z ? view3_rows(z, Hv, V) : vv; const V2 a2 = view2(av, Hv), b2 = view2(bvt, Hv); const V2 si = sidx ? view2(sidx, sw) : V2{ nullptr, 0, 0 }; + /* The anchor form keeps its factors inside a head's [V, K] block of a state slot, at libr4d's + * offsets, so the block must be dense and large enough. Checked before any write. */ + const AnchorLayout al(K, V); + if (anchor) { + if (!sidx || sw < 6) return RAD_E_SHAPE; + if (state->rank >= 4 && (state->stride[3] != 1 || state->stride[2] != K)) + return RAD_E_STRIDE; + if (al.tmax < 1) return RAD_E_SHAPE; + for (int64_t n = 0; n < n_seq; ++n) { + const int64_t na = nacc ? ldi(nacc, offlin(nacc, n)) : 1; + if (cu_at(cu, n + 1) - cu_at(cu, n) > al.tmax || na > al.tmax) return RAD_E_SHAPE; + } + } AVX_PARALLEL_FOR_IF(n_seq * Hv >= 4) for (int64_t nh = 0; nh < n_seq * Hv; ++nh) { const int64_t n = nh / Hv, h = nh % Hv, hk = h / grp; const int64_t bos = cu_at(cu, n), q_len = cu_at(cu, n + 1) - bos; - if (q_len <= 0) continue; + const int64_t sstride = state->rank >= 4 ? state->stride[0] : (int64_t)Hv * V * K; + const int64_t hstride = state->rank >= 4 ? state->stride[1] : (int64_t)V * K; + const int64_t vstride = state->rank >= 4 ? state->stride[2] : K; + const int64_t dstride = state->rank >= 4 ? state->stride[3] : 1; + /* Under `anchor` a sequence with no rows this step still folds its accepted prefix in. */ + if (q_len <= 0 && !anchor) continue; const int64_t na = nacc ? ldi(nacc, offlin(nacc, n)) : 1; const int64_t rd = na > 0 ? na - 1 : 0; - const int64_t slot_in = sidx ? ldi(sidx, at2(si, n, rd < sw ? rd : sw - 1)) : n; - if (slot_in < 0) continue; + int64_t col[6] = { 0, 0, 0, 0, 0, 0 }; + int64_t slot_in = 0; + if (anchor) { + bool pad = false; + for (int c = 0; c < 6; ++c) { + col[c] = ldi(sidx, at2(si, n, c)); + pad = pad || col[c] < 0; + } + if (pad) continue; + slot_in = col[al.anchor_col(state, col[4] * sstride + h * hstride)]; + } else { + slot_in = sidx ? ldi(sidx, at2(si, n, rd < sw ? rd : sw - 1)) : n; + if (slot_in < 0) continue; + } + /* The factor blocks: column 4's is read, and 3, 4 and 5 are written (each a page the + * window can shift onto). */ + const int64_t fb = anchor ? col[4] * sstride + h * hstride : 0; + const int64_t fbs[3] = { anchor ? col[3] * sstride + h * hstride : 0, fb, + anchor ? col[5] * sstride + h * hstride : 0 }; + const bool dup_f = anchor && (col[3] != col[4] || col[5] != col[4]); - /* vrow/zrow widen the per-token value and gate rows once: the loops below read them - * V times each, and per-element ldt there is a dtype switch per element. */ + /* vrow/zrow hold the per-token value and gate rows, widened once. */ const size_t need = (size_t)(V * K + 2 * K + 5 * V) + 16; float* wsp = scratch_f32(need); float* S = wsp; @@ -1059,15 +1053,7 @@ AVX_KERNEL(gdn_recurrent_update) { float* vrow = gainv + V; float* zrow = vrow + V; - const int64_t sstride = state->rank >= 4 ? state->stride[0] : (int64_t)Hv * V * K; - const int64_t hstride = state->rank >= 4 ? state->stride[1] : (int64_t)V * K; - const int64_t vstride = state->rank >= 4 ? state->stride[2] : K; - const int64_t dstride = state->rank >= 4 ? state->stride[3] : 1; - - /* ONE SWITCH PER ROW, NOT PER ELEMENT (avx_vec.h): the state tile is V*K scalar - * dtype-switched loads below, and the widened row loop is what the hardware - * prefetcher can see through. Same f32 values either way, so the arithmetic is - * untouched. */ + /* Widen the state a row at a time (one dtype switch per row, avx_vec.h). */ if (dstride == 1) { for (int64_t e = 0; e < V; ++e) row_to_f32(state->dtype, @@ -1083,17 +1069,52 @@ AVX_KERNEL(gdn_recurrent_update) { const float alog = A_log ? ldt(A_log, h * laststride(A_log)) : 0.0f; const float dtb = dt_bias ? ldt(dt_bias, h * laststride(dt_bias)) : 0.0f; - const float negexp = -std::exp(alog); - /* The norm gain, read once per head rather than once per (token, channel). */ + const float negexp = -sc_exp(alog); + /* Norm gain, read once per head. */ if (nw) { if (laststride(nw) == 1) row_to_f32(nw->dtype, nw->data, gainv, V); else for (int64_t e = 0; e < V; ++e) gainv[e] = ldt(nw, e * laststride(nw)); } + if (anchor) { + /* Replay the previous step's accepted tokens from their factors, with the token + * loop's own arithmetic, so the replayed state is the one per_candidate would hold. + * Then publish it at column 2 and stamp each factor copy with its column. */ + for (int64_t t = 0; t < na; ++t) { + const int64_t f = fb + t * al.fstr; + for (int64_t e = 0; e < V; ++e) vrow[e] = ldt(state, f + al.vb + e); + /* Each 32-row group of V replays from its own copy of k and its own (g, beta), as + * libr4d's kernel and libref read them; writers store equal copies. */ + for (int64_t gi = 0; gi < al.groups; ++gi) { + const int64_t e0 = 32 * gi, e1 = std::min(V, e0 + 32); + for (int64_t d = 0; d < K; ++d) kn[d] = ldt(state, f + gi * K + d); + const float gval = ldt(state, f + al.gb + 2 * gi); + const float bt = ldt(state, f + al.gb + 2 * gi + 1); + const float dec = sc_exp(gval); + const vf vdec = vf_set1(dec); + for (int64_t e = e0; e < e1; ++e) { + float* Se = S + e * K; + int64_t d = 0; + for (; d + VF_N <= K; d += VF_N) + vf_storeu(Se + d, vf_mul(vf_loadu(Se + d), vdec)); + for (; d < K; ++d) Se[d] *= dec; + uu[e] = bt * (vrow[e] - dot2(Se, kn, K)); + } + for (int64_t e = e0; e < e1; ++e) axpy(S + e * K, kn, uu[e], K); + } + } + for (int64_t e = 0; e < V; ++e) /* the anchor block is dense (checked) */ + row_from_f32(state->dtype, S + e * K, + (void*)byte_at(state->data, state->dtype, + col[2] * sstride + h * hstride + e * K), + K); + for (int c = 0; c < 3; ++c) stt(state, fbs[c] + al.mark, (float)(c + 1)); + } + for (int64_t t = 0; t < q_len; ++t) { const int64_t tok = bos + t; const float gval = negexp * softplus(ldt(av, at2(a2, tok, h)) + dtb, spthr); - const float bt = 1.0f / (1.0f + std::exp(-ldt(bvt, at2(b2, tok, h)))); + const float bt = 1.0f / (1.0f + sc_exp(-ldt(bvt, at2(b2, tok, h)))); if (qv.s2 == 1 && kv.s2 == 1) { row_to_f32(q->dtype, byte_at(q->data, q->dtype, at3(qv, tok, hk, 0)), qn, K); @@ -1104,13 +1125,12 @@ AVX_KERNEL(gdn_recurrent_update) { kn[d] = ldt(k, at3(kv, tok, hk, d)); } } - /* The value row, widened once per token: the decay loop below reads it V times. */ + /* Value row, widened once per token. */ if (vv.s2 == 1) row_to_f32(v->dtype, byte_at(v->data, v->dtype, at3(vv, tok, h, 0)), vrow, V); else for (int64_t e = 0; e < V; ++e) vrow[e] = ldt(v, at3(vv, tok, h, e)); - /* The l2 norms: no division by K, and `scale` folded into q's -- libref multiplies - * them in that order and the product is not associative in f32. */ + /* L2 norms (no division by K), with `scale` folded into q's in libref's order. */ const float qs = 1.0f / std::sqrt(row_sumsq(qn, K) + l2eps) * scale; const float ks = 1.0f / std::sqrt(row_sumsq(kn, K) + l2eps); { @@ -1123,7 +1143,7 @@ AVX_KERNEL(gdn_recurrent_update) { for (; d < K; ++d) { qn[d] *= qs; kn[d] *= ks; } } - const float dec = std::exp(gval); + const float dec = sc_exp(gval); const vf vdec = vf_set1(dec); for (int64_t e = 0; e < V; ++e) { float* Se = S + e * K; @@ -1131,15 +1151,29 @@ AVX_KERNEL(gdn_recurrent_update) { for (; d + VF_N <= K; d += VF_N) vf_storeu(Se + d, vf_mul(vf_loadu(Se + d), vdec)); for (; d < K; ++d) Se[d] *= dec; - uu[e] = bt * (vrow[e] - dotf(Se, kn, K)); + uu[e] = bt * (vrow[e] - dot2(Se, kn, K)); } for (int64_t e = 0; e < V; ++e) { float* Se = S + e * K; axpy(Se, kn, uu[e], K); - orow[e] = dotf(Se, qn, K); + orow[e] = dot2(Se, qn, K); } - /* The gate row, widened once per token like the value row above. */ + /* This token's factors, for the next step to replay: the normalised k once per + * 32-row group, v, then the decay exponent and beta once per group. */ + if (anchor) + for (int c = 0; c < 3; ++c) { + if (c != 1 && !dup_f) continue; + const int64_t f = fbs[c] + t * al.fstr; + for (int64_t gi = 0; gi < al.groups; ++gi) { + for (int64_t d = 0; d < K; ++d) stt(state, f + gi * K + d, kn[d]); + stt(state, f + al.gb + 2 * gi, gval); + stt(state, f + al.gb + 2 * gi + 1, bt); + } + for (int64_t e = 0; e < V; ++e) stt(state, f + al.vb + e, vrow[e]); + } + + /* Gate row, widened once per token. */ if (z) { if (zv.s2 == 1) row_to_f32(z->dtype, byte_at(z->data, z->dtype, at3(zv, tok, h, 0)), zrow, @@ -1147,14 +1181,14 @@ AVX_KERNEL(gdn_recurrent_update) { else for (int64_t e = 0; e < V; ++e) zrow[e] = ldt(z, at3(zv, tok, h, e)); } - /* The gated RMS norm, over the head's V channels. */ + /* Gated RMS norm over the head's V channels. */ const float sc = 1.0f / std::sqrt(row_sumsq(orow, V) / (float)V + neps); for (int64_t e = 0; e < V; ++e) { float r = orow[e] * sc; if (nw) r *= gainv[e]; if (z) { const float zz = zrow[e]; - const float sg = 1.0f / (1.0f + std::exp(-zz)); + const float sg = 1.0f / (1.0f + sc_exp(-zz)); r *= (nact == 1 ? sg : zz * sg); } orow[e] = r; @@ -1162,9 +1196,8 @@ AVX_KERNEL(gdn_recurrent_update) { if (ov.s2 == 1) out_row(o, at3(ov, tok, h, 0), V, orow); else for (int64_t e = 0; e < V; ++e) stt(o, at3(ov, tok, h, e), orow[e]); - /* QUANTISE WHAT WAS WRITTEN, not what produced it: the standalone quant_act_fp8 this - * replaces read `o` back out of memory, so it saw the rounded store and not the f32. - * One group per (token, head), because head_v is the fp8 block width. */ + /* Quantise `o` as stored (read back), as the standalone quant_act_fp8 would see it. + * One group per (token, head): head_v is the fp8 block width. */ if (oq && osc) { if (ov.s2 == 1) row_to_f32(o->dtype, byte_at(o->data, o->dtype, at3(ov, tok, h, 0)), uu, V); @@ -1197,6 +1230,7 @@ AVX_KERNEL(gdn_recurrent_update) { stt(osc, rowoff(osc, tok, Hv) + h * laststride(osc), qsc); } + if (anchor) continue; const int64_t so = sidx ? ldi(sidx, at2(si, n, t < sw ? t : sw - 1)) : n; if (so >= 0) { if (dstride == 1) { @@ -1218,14 +1252,12 @@ AVX_KERNEL(gdn_recurrent_update) { } /* ------------------------------------------------------------------ gdn_conv_recurrent_update */ -/* gdn_conv_update into a staging q, k and v, then gdn_recurrent_update over them. The fused op is - * DEFINED as that pair, so this is the pair -- this level's own two kernels, called with the - * operands and parameters each one takes -- and nothing is restated. The head geometry the staging - * needs comes off `o` ([T, Hv, head_v]) and `x` (2 Hg head_k + Hv head_v columns). +/* Defined as gdn_conv_update into a staging q, k and v, then gdn_recurrent_update over them, and + * implemented as exactly that pair of this level's kernels. The staging geometry comes from `o` + * ([T, Hv, head_v]) and `x` (2 Hg head_k + Hv head_v columns). * - * The staging is sized from x's dtype, a whole element each; a sub-byte activation is refused - * rather than given a buffer the convolution would write past. It lives in a buffer the calling - * thread keeps, so a call allocates nothing once the thread has seen its widest. */ + * The staging uses x's dtype; sub-byte dtypes are refused. It is a per-thread buffer that only + * grows. */ AVX_KERNEL(gdn_conv_recurrent_update) { if (a->n_t < 16) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *o = &a->t[15]; @@ -1268,28 +1300,23 @@ AVX_KERNEL(gdn_conv_recurrent_update) { const int rc = AVX_FN(avx_gdn_conv_update)(&ca, stream); if (rc != RAD_OK) return rc; - std::vector rp; - for (int i = 0; i < a->n_p; ++i) - if (std::strcmp(a->p[i].key, "conv_width")) rp.push_back(a->p[i]); /* q, k, v, a, b, A_log, dt_bias, state, state_idx, num_accepted, cu, z, norm_w, o, o_q, - * o_scale */ + * o_scale. The parameters pass as they are: the recurrence reads its own by name. */ RadTensor rt[16] = { tq, tk, tv, a->t[5], a->t[6], a->t[7], a->t[8], a->t[9], a->t[10], a->t[11], a->t[12], a->t[13], a->t[14], a->t[15], a->n_t > 16 ? a->t[16] : RadTensor{}, a->n_t > 17 ? a->t[17] : RadTensor{} }; RadArgs ra = *a; - ra.t = rt; ra.n_t = 16; ra.p = rp.data(); ra.n_p = (int)rp.size(); + ra.t = rt; ra.n_t = 16; return AVX_FN(avx_gdn_recurrent_update)(&ra, stream); } /* ------------------------------------------------------------------ gdn_gated_rmsnorm */ -/* out = x * rsqrt(mean_channels(x^2) + eps) * w * act(z), one row per (token, head). The prefill - * path's form of the epilogue the recurrent update folds in. +/* out = x * rsqrt(mean_channels(x^2) + eps) * w * act(z), one row per (token, head): the prefill + * form of the epilogue the recurrent update folds in. * - * THE GATE HAS A THIRD SPELLING the shared rowoff() cannot see. It walks [tokens, heads, ch], and a - * flat [rows, ch] projection is its product; but a COLUMN SLICE of a wider projection row -- the - * fp8 delta net fuses [q|k|v|z] into one GEMM -- has heads*ch as its last axis, so rowoff reads it - * as a dense row and lands in the next token. Spelled out here rather than generalised into - * avx_common.h, because it is a property of THIS operand and not of every one. */ + * The gate may be a rank-2 column slice of a wider projection row (the fp8 delta net fuses + * [q|k|v|z] into one GEMM) with heads*ch as its last axis, which rowoff() would read as a dense row. + * Handled here since it is specific to this operand. */ static inline int64_t gate_rowoff(const RadTensor* t, int64_t r, int64_t ch) { if (t->rank == 2 && ch > 0 && t->shape[1] != ch && t->shape[1] % ch == 0) { const int64_t heads = t->shape[1] / ch; @@ -1305,6 +1332,7 @@ AVX_KERNEL(gdn_gated_rmsnorm) { const float eps = p_f32(a, "eps", 1e-6f); static const char* kActs[] = { "silu", "sigmoid" }; const int act = p_enum(a, "act", kActs, 2, 0); + if (act != 0 && act != 1) return RAD_E_INVAL; if (ch <= 0) return RAD_E_SHAPE; const int64_t rows = numel(x) / ch; if (rows <= 0 || numel(o) < rows * ch || numel(z) < rows * ch || numel(w) < ch) @@ -1339,7 +1367,7 @@ AVX_KERNEL(gdn_gated_rmsnorm) { } for (; i < ch; ++i) { const float zz = zv2[i]; - const float sg = 1.0f / (1.0f + std::exp(-zz)); + const float sg = 1.0f / (1.0f + sc_exp(-zz)); obuf[i] = xv[i] * sc * gain[i] * (act == 1 ? sg : zz * sg); } if (os == 1) out_row(o, ob, ch, obuf); diff --git a/libavx/avx_gemm.cpp b/libavx/avx_gemm.cpp index 0969d2db..a7c2e0dc 100644 --- a/libavx/avx_gemm.cpp +++ b/libavx/avx_gemm.cpp @@ -2,33 +2,19 @@ * * nt: C[M,N] = A[M,K] @ B[N,K]^T * - * B is stored TRANSPOSED because that is the layout every weight in a transformer already has, so - * both operands are k-contiguous and the inner loop is a DOT PRODUCT over k rather than an outer - * product over n. That single fact decides the whole shape of this file, and it is worth being - * explicit about what it costs, because the textbook GEMM does the opposite. + * B is stored transposed, as transformer weights are, so both operands are k-contiguous. * - * ============================== WHY DOT PRODUCT AND NOT OUTER PRODUCT ============================== + * Which product runs: + * gemm_q_bf16 (avx_gemm_tile.cpp) on AVX512_BF16 parts: bf16 x bf16 and every plain + * gemm_nt_q form, including a joined lm head read as codes and a scale grid + * gemm_tile_f32 (avx_gemm_tile.cpp) everything else, at every level + * gemm_drive's own loop, below: the forms the tile drivers decline (an E8M0 scale they cannot + * fold, a decoded weight with a separate scale stream) + * the zero-point grids' small-M paths: their integer and 16-bit forms at M <= 16 * - * The classical high-performance GEMM (Goto's, and every BLAS since) packs B into panels laid out - * so the inner loop broadcasts one A element against a VECTOR of n, accumulating C[m, n0:n0+w] in - * registers with no horizontal reduction anywhere. It is the right shape when you may choose B's - * layout. - * - * Here B's layout is given, it is k-contiguous, and a transformer weight is READ ONCE PER LAUNCH -- - * there is no second GEMM against the same weight to amortise a pack over. Packing B into n-major - * panels would mean touching the largest operand twice to save horizontal reductions that only - * happen once per output element. At decode (M = 1) the whole GEMM is a matvec: the weight is - * streamed exactly once, the arithmetic intensity is 2 flops a byte, and nothing about the - * instruction mix matters because the memory system is the wall. At prefill the register blocking - * below recovers most of what a packed form would give. - * - * So: REGISTER-BLOCKED DOT PRODUCT. MR rows of A against NR rows of B, MR*NR vector accumulators - * live across the whole k loop, MR + NR vector loads per k step, and the horizontal reduction paid - * once per output element rather than once per k step. - * - * ============================== THE BLOCK SIZE IS THE REGISTER FILE, AND IT WAS SWEPT ============================== - * - * MEASURED, gemm_nt bf16 at M=512, N=2048, K=2048, one thread, on the part libavx/README.md names: + * gemm_drive's loop is a dot-product register block: MR rows of A against NR rows of B, MR*NR + * vector accumulators across the k loop, one horizontal reduction per output and group. The block + * was swept (gemm_nt bf16, M=512, N=2048, K=2048, one thread; libavx/README.md names the part): * * AVX-512, 32 ZMM 4x4 23.2 ms 4x6 22.1 ms <-- chosen * 6x4 24.2 ms 6x6 24.0 ms @@ -37,60 +23,16 @@ * 2x5 31.9 ms 2x4 34.8 ms 2x3 40.5 ms * 3x4 58.4 ms 4x3 58.1 ms * - * TWO THINGS IN THAT TABLE ARE WORTH MORE THAN THE CHOICE. The first is the cliff: 3x4 and 4x3 at - * AVX2 are 58 ms against 31-34 for everything around them, because 12 accumulators plus 3 or 4 A - * vectors plus one B vector is 16 or 17 live in a 16-register file -- the spill lands INSIDE the k - * loop and costs 1.9x. That is why this is written out per level rather than derived from a - * formula, and why the numbers sit next to the code. - * - * The second is that WIDER IN N BEAT WIDER IN M at both levels, at equal arithmetic intensity: - * 2x6 and 3x3 both load 8 vectors for 12 and 9 FMAs respectively -- intensity 1.5 either way -- and - * 2x6 is 11% faster. The B vector is loaded once and reused across the MR inner iterations, so a - * small MR keeps fewer values live and schedules better. Nothing about the flop count predicts - * this; it came out of the sweep. - * - * scalar stays 2x2, where "vector" is one float and the blocking only helps the load/store - * scheduler. - * - * ============================== ONE MICROKERNEL, NOT TWENTY-EIGHT ============================== - * - * libref templates its inner loop on (A dtype, B dtype) and selects through a function pointer, - * because for it the per-element dtype switch WOULD be the cost -- one element is read per FLOP. - * That is 16 instantiations for the plain family and 28 for the quantised one. - * - * This plugin instead PACKS TO f32 and has ONE microkernel: - * - * A is widened once into a contiguous [M, K] f32 buffer -- M*K conversions - * each B row is widened once, per n-block, into a thread-local buffer -- N*K conversions - * - * The conversion count is the same as the fused form's (every element of both operands is - * converted exactly once either way); what it buys is that W4, W2, MXFP4, fp8 and i8 all arrive at - * the same code, so the packed-nibble unpack is written once (avx_support.cpp) and the microkernel - * never sees a dtype. 28 instantiations x 4 ISA levels of hand-written vector code is not a - * maintainable object, and the ones nobody runs would be the ones that are wrong. - * - * What it costs is an L1 round trip: the packed rows are written and read back. Against an operand - * that came from L2 or DRAM -- which a weight always did -- that is not measurable, and the - * exception is stated where it happens (an f32 contiguous A is used in place, unpacked). - * - * THE MEMORY THIS COSTS IS BOUNDED BY THE M BLOCK below -- the pack is MB*K floats, not M*K -- and - * it is not blocked over K. That is a deliberate omission: K-blocking would bound the pack further - * but would force the C accumulator into memory, because the k reduction could then no longer live - * in registers across the whole launch. C is M*N floats, larger than the pack at every shape this - * plugin sees, and another pass over it. - * - * ============================== PARALLELISM IS OVER N ============================== - * - * A decode step is M = 1 and a verify step is M <= 64, so an M-major split leaves all but one core - * idle on exactly the shape the engine spends its life in. N is thousands in every GEMM a - * transformer issues. libref made the same choice for the same reason. Each thread owns whole - * output elements, so the summation order does not depend on the thread count and two runs at - * different loads are bit-identical. + * At AVX2, 3x4 and 4x3 need 12 accumulators + 3-4 A vectors + 1 B vector, 16-17 live registers in a + * 16-register file: the spill lands inside the k loop and costs 1.9x. The scalar level uses 2x2. + * Both operands are packed to f32 (A once per M block, each B row once per n-block), so every + * weight format reaches one microkernel. Parallelism is over N; each thread owns whole outputs, so + * results do not depend on the thread count. */ -#include "avx_vec.h" -#include "avx_common.h" +#include "avx_gemm.h" #include "avx_rows.h" +#include #include using namespace avx; @@ -106,12 +48,10 @@ constexpr int64_t MR = 2, NR = 6; constexpr int64_t MR = 2, NR = 2; #endif -/* MR x NR dot products over [k0, k1), accumulated into `out` (which is ADDED to, not overwritten, - * so the grouped GEMM can call this per group). +/* MR x NR dot products over [k0, k1), added into `out` so the grouped GEMM can call it per group. * - * The tail is summed separately and added to the horizontal reduction rather than folded into a - * masked vector: the two give different orders and the masked form is only free at AVX-512. One - * order, four levels. */ + * The k tail is summed scalar after the horizontal reduction rather than in a masked vector (free + * only at AVX-512), so all four levels share one summation order. */ template static inline void dot_block(const float* A, int64_t lda, const float* B, int64_t ldb, int64_t k0, int64_t k1, float out[MB_][NB_]) { @@ -136,124 +76,100 @@ static inline void dot_block(const float* A, int64_t lda, const float* B, int64_ } } -/* One dot product, for the ragged edge of the M and N loops. Four accumulators, which is what - * covers the FMA latency; the edge is at most MR-1 by NR-1 blocks of a launch, so its cost is - * noise, but writing it as a scalar loop would make a narrow GEMM (N < NR) run scalar throughout - * and a draft head's lm_head is exactly that shape. */ -static inline float dot1(const float* a, const float* b, int64_t k0, int64_t k1) { - vf a0 = vf_zero(), a1 = vf_zero(), a2 = vf_zero(), a3 = vf_zero(); - int64_t k = k0; - for (; k + 4 * VF_N <= k1; k += 4 * VF_N) { - a0 = vf_fma(vf_loadu(a + k), vf_loadu(b + k), a0); - a1 = vf_fma(vf_loadu(a + k + VF_N), vf_loadu(b + k + VF_N), a1); - a2 = vf_fma(vf_loadu(a + k + 2 * VF_N), vf_loadu(b + k + 2 * VF_N), a2); - a3 = vf_fma(vf_loadu(a + k + 3 * VF_N), vf_loadu(b + k + 3 * VF_N), a3); - } - for (; k + VF_N <= k1; k += VF_N) a0 = vf_fma(vf_loadu(a + k), vf_loadu(b + k), a0); - float s = vf_hsum(vf_add(vf_add(a0, a1), vf_add(a2, a3))); - for (; k < k1; ++k) s += a[k] * b[k]; - return s; -} - -/* ================================================================== operand readings - * libref/ref_gemm.h's, and they are copied for the same reason avx_common.h copies the addressing - * helpers: they are the CONTRACT for which bytes an operand's (row, col) lives at, not a - * convenience. `row_stride` (avx_common.h) in particular is the one that makes an oracle wrong - * when it is wrong -- a rank-3 [tokens, heads, width] activation read as [tokens, heads*width] has - * a row stride that is the product of the trailing dimensions and NOT stride[rank-2], and taking - * the head stride instead lands row 0 correctly and starts every row after it `width` elements - * in. */ - -struct Mat { const RadTensor* t; int64_t rs, cs; }; - -static inline Mat as_mat(const RadTensor* t, int64_t cols) { - Mat m{ t, cols, 1 }; - if (t->rank < 2) return m; - m.cs = t->stride[t->rank - 1]; - m.rs = row_stride(t, cols); - return m; -} - -/* A quantised operand's scale stream. libref/ref_gemm.h is the definition, including the `rblk` - * rule that makes a DeepSeek-style [ceil(N/128)][ceil(K/128)] block grid readable: without it a - * 17408-row weight's 136-row scale plane is read as if it had 17408 rows and lands on groups = 0, - * which is a plausible wrong number rather than a diagnosable failure. */ -struct Scales { - const void* p; - uint32_t dt; - int64_t rs, cs, group, rblk; - bool e8m0; - inline float grp(int64_t row, int64_t g) const { - const int64_t i = (rblk > 1 ? row / rblk : row) * rs + g * cs; - if (e8m0) { - const uint8_t e = ((const uint8_t*)p)[i]; - return e == 0xff ? std::nanf("") : std::ldexp(1.0f, (int)e - 127); - } - return rad_load_f32(p, dt, i); - } -}; - -static Scales make_scales(const RadTensor* s, int64_t rows, int64_t K, bool mxfp4_weight) { - Scales q{}; - q.rblk = 1; - if (!s || !s->data || rows <= 0 || numel(s) <= 0) { - q.p = nullptr; q.group = K; q.dt = RAD_F32; return q; - } - q.p = s->data; - q.dt = s->dtype; - /* libref's reading, block for block: a rank-2 stream with fewer rows than the operand is a - * block grid whatever the remainder, and a flat stream shorter than the row count is one - * scale per block of rows rather than a per-row stream to read past its end. */ - int64_t groups = 0; - if (s->rank >= 2) { - const int64_t srows = s->shape[s->rank - 2]; - q.rblk = srows >= rows ? 1 : grid_block(rows, srows); - groups = s->shape[s->rank - 1]; - q.rs = s->stride[s->rank - 2]; - q.cs = s->stride[s->rank - 1]; - } else { - const int64_t nel = numel(s); - if (nel >= rows) { groups = nel / rows; q.rs = groups; } - else { groups = 1; q.rblk = grid_block(rows, nel); q.rs = 1; } - q.cs = 1; - } - q.group = grid_block(K, groups); - q.e8m0 = mxfp4_weight && (s->dtype == RAD_U8); - return q; -} /* ================================================================== packing - * A row of an operand, widened into f32 and made contiguous. Returns the caller's own pointer when - * the operand is ALREADY dense f32 -- the one case where the pack is skipped entirely, and the - * reason a f32 GEMM does not pay for the generality. */ + * Rows of an operand widened to contiguous f32. Returns a pointer into the operand itself when it + * is already dense f32 with the right pitch, skipping the pack. */ static const float* pack_rows(const Mat& m, int64_t r0, int64_t nrows, int64_t K, float* dst, int64_t ldd) { + if (m.dec) { + for (int64_t r = 0; r < nrows; ++r) m.dec->row(r0 + r, dst + r * ldd); + return dst; + } const RadTensor* t = m.t; if (m.cs == 1 && t->dtype == RAD_F32 && m.rs == ldd) return (const float*)t->data + r0 * m.rs; - for (int64_t r = 0; r < nrows; ++r) { - const int64_t base = (r0 + r) * m.rs; - if (m.cs == 1) { - const int sub = (t->dtype == RAD_I4 || t->dtype == RAD_FP4E2M1) ? 1 - : (t->dtype == RAD_I2) ? 3 : 0; - if (!sub || (base & sub) == 0) { - row_to_f32(t->dtype, byte_at(t->data, t->dtype, base), dst + r * ldd, K); - continue; - } - } - for (int64_t k = 0; k < K; ++k) - dst[r * ldd + k] = ld_elem(t->data, t->dtype, base + k * m.cs); - } + for (int64_t r = 0; r < nrows; ++r) widen_cols(m, r0 + r, 0, K, dst + r * ldd); return dst; } +/* ================================================================== joined weights + * + * Row decoders for weights stored joined (avx_planes.h). Each writes a row as f32 with its scales + * folded in, so the driver multiplies it like a plain row in one group: + * + * HeadDec codes times the scale covering them: an lm head, a mixing or fc row. Each element is + * the f32 the core's affine decoder gives, the head libref multiplies. + * ZpDec a zero-point grid's row, (code - zero) * scale. For the grids that remove the zero + * through `a_sum` it is code * scale with one more column a group holding + * -zero * scale, against an activation whose matching column holds that group's sum. + * + * With the scales folded into the rows each product rounds once, where libref rounds each + * group's sub-sum once; the two differ within the tolerance. */ + +/* Rows of codes and one scale (avx_planes.h: ScaledRows), `K` wide. */ +struct HeadDec final : RowDecoder { + avxp::ScaledRows sr; + int64_t K = 0; + void row(int64_t r, float* dst) const override { scaled_row(sr, r, K, dst); } + void cols(int64_t r, int64_t k0, int64_t k1, float* dst) const override { + const uint8_t* c = sr.codes.p + r * sr.codes.row_bytes; + const int64_t span = sr.span(K); + for (int64_t c0 = k0; c0 < k1; c0 += span) + decode_scaled(sr.codes.dt, c + c0, sr.scale_at(r, c0), dst + (c0 - k0), + std::min(span, k1 - c0)); + } + int64_t align() const override { return sr.span(K); } + void codes(int64_t r, int64_t k0, int64_t k1, const void** p, int64_t* bytes) const override { + *p = sr.codes.p + r * sr.codes.row_bytes + k0; + *bytes = k1 - k0; + } +}; + +/* A zero-point grid's rows (avx_planes.h: ZpGrid) from row `n0` on: codes at `codes_p`, `rb` bytes + * a row, with the joined scale and zero planes. `aug` writes code * scale and the extra column of + * -zero * scale per group, `group + 1` columns a group; otherwise (code - zero) * scale. */ +struct ZpDec final : RowDecoder { + const uint8_t* codes_p = nullptr; + int64_t rb = 0, K = 0, group = 0, n0 = 0; + int bits = 0; + bool aug = false; + avxp::JPlane sc, zp; + void row(int64_t r, float* dst) const override { cols(r, 0, K / group * align(), dst); } + /* Whole groups: [k0, k1) in the decoded row's columns, `group + 1` a group when aug. */ + void cols(int64_t r, int64_t k0, int64_t k1, float* dst) const override { + const int64_t n = n0 + r; + const uint8_t* cr = codes_p + n * rb; + const int64_t gw = align(); + for (int64_t g = k0 / gw; g * gw < k1; ++g) { + const float s = sc.at(n, g); + const int32_t z = (int32_t)zp.at(n, g); + float* d = dst + (g * gw - k0); + if (aug) { + decode_zp(cr, bits, g * group, group, 0, s, d); + d[group] = -(float)z * s; + } else { + decode_zp(cr, bits, g * group, group, z, s, d); + } + } + } + int64_t align() const override { return aug ? group + 1 : group; } + void codes(int64_t r, int64_t k0, int64_t k1, const void** p, int64_t* bytes) const override { + const int64_t gw = align(); + *p = codes_p + (n0 + r) * rb + (k0 / gw) * group * bits / 8; + *bytes = ((k1 - k0 + gw - 1) / gw) * group * bits / 8; + } +}; + /* ================================================================== the driver * - * `SB`/`SA` null means the unquantised family, which is the same loop with one group of width K - * and both scales 1 -- so there is one driver and not two. The grouped form accumulates the - * sub-sum from the RAW CODES and scales once at the end of the group, which is what an int8 WMMA - * kernel does and what libref does; folding the scales into every product instead would be a - * different number in the last bits and the checker would blame the kernel for the choice. */ + * Null `SB`/`SA` is the unquantised family: one group of width K, scales 1. The grouped form sums + * raw codes and applies the scales once per group, as libref and an int8 WMMA kernel do; scaling + * every product would differ in the last bits. */ +static int gemm_drive_fine_a(const Mat& ma, const Mat& mb, const Scales* SA, const Scales* SB, + const RadTensor* Y, const RadTensor* bias, int64_t M, int64_t N, + int64_t K); + static int gemm_drive(const Mat& ma, const Mat& mb, const Scales* SA, const Scales* SB, const RadTensor* Y, const RadTensor* bias, int64_t M, int64_t N, int64_t K) { @@ -261,46 +177,31 @@ static int gemm_drive(const Mat& ma, const Mat& mb, const Scales* SA, const Scal const int64_t ys_c = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1; const int64_t g = (SB && SB->p && SB->group > 0) ? SB->group : K; const int64_t ngrp = (K + g - 1) / g; - /* An activation grid FINER than the weight's cannot have its scale hoisted out of the group. - * No format in this project has one; the branch exists so that a format that did would be - * refused rather than silently mis-scaled. */ + /* An activation scale grid finer than the weight's cannot be hoisted out of the group. */ const bool coarse_a = !SA || !SA->p || SA->group >= g; - if (!coarse_a) return RAD_E_UNSUPPORTED; + if (!coarse_a) return gemm_drive_fine_a(ma, mb, SA, SB, Y, bias, M, N, K); + if (gemm_tile_f32(ma, mb, SA, SB, Y, bias, M, N, K)) return RAD_OK; - /* ================================================== THE M BLOCK, AND A NULL RESULT + /* ================================================== the M block * - * The loop nest below is (M block) x (N block) x (K). With the N loop outermost and the whole - * of A packed, every one of the N/NR n-blocks walks the ENTIRE packed A, so at M=512, K=2048 - * that is a 4 MiB panel re-read 341 times: 1.4 GiB of traffic to do 4.3 GFLOP. Blocking M so - * the panel stays resident is the textbook fix, and the traffic argument predicts a large win. + * Loop nest: (M block) x (N block) x K. Unblocked, every n-block re-reads the whole packed A + * (at M=512, K=2048, a 4 MiB panel read 341 times). Blocking M keeps the panel in L2. * - * MEASURED, AND THE PREDICTION DOES NOT HOLD HERE. gemm_nt bf16 at M=512, N=2048, K=2048, - * AVX-512, one thread, sweeping the panel target: + * On a part with 128 MiB of L3 the gain is only ~6% (gemm_nt bf16, M=512, N=2048, K=2048, + * AVX-512, one thread: 23.4 ms at a 256 KiB panel vs 25.0 ms unblocked), because the panel + * stays in L3 anyway; at M=64 it is ~2% slower (B is packed twice). It is kept for parts with + * small L3, where the re-reads go to DRAM. * - * 128 KiB 26.0 ms 4 MiB 25.4 ms - * 256 KiB 23.4 ms 16 MiB 25.4 ms - * 1 MiB 24.0 ms 256 MiB 25.0 ms (= no blocking at this shape) - * - * Six percent, not the several-fold the traffic argument implies -- and at M=64 it is WORSE - * (2.85 ms unblocked against 2.91 at 256 KiB), because there the block splits a batch that did - * not need splitting and B gets packed twice. - * - * THE REASON IS THE PART. The measurement above comes from one with 128 MiB of L3, where the - * 4 MiB A panel never leaves cache however many times it is walked -- so the traffic the - * blocking removes is served at L3 bandwidth and not DRAM's. On a part with a 32 MiB L3 - * the same argument still holds; on one with 8 MiB the blocking is the several-fold win the - * theory predicts. It is kept because it is never much worse and is much better on hardware - * the measurement above cannot represent -- but it is recorded here as a SIX PERCENT effect on - * a large-cache part, and not as the fix it looks like. - * - * THE BLOCK SIZE IS COMPUTED FROM K, NOT TUNED: the panel is MB x K floats against a fixed - * byte target. There is nothing to search -- unlike a GPU tile it does not interact with an - * occupancy limit -- which is why avx_registry.cpp declares no tunable axes. The target is - * stated rather than probed from CPUID because the cache descriptors there are a fiction on - * more parts than they are a fact, and the sweep above shows the curve is flat enough that - * being wrong about it costs ten percent rather than an order. */ + * MB is derived from K against a fixed byte target, not tuned (hence no tunable axes in + * avx_registry.cpp). The target is a constant rather than read from CPUID cache descriptors, + * which are unreliable; the measured curve is flat, so a wrong guess costs about 10%. */ enum { AVX_L2_PANEL = 256 * 1024 }; int64_t MB = (int64_t)AVX_L2_PANEL / ((int64_t)K * (int64_t)sizeof(float)); + /* A decoded weight (a joined head, a zero-point grid) costs a decode per M block on top of + * the read, so its M block is as tall as a 16 MiB panel allows: an lm head at K = 5120 is + * decoded once up to M = 819 instead of once every 12 rows. The panel is read-only and + * shared by the threads through the last level. */ + if (mb.dec) MB = (int64_t)(16 << 20) / ((int64_t)K * (int64_t)sizeof(float)); if (MB < MR) MB = MR; if (MB > M) MB = M; @@ -310,8 +211,8 @@ static int gemm_drive(const Mat& ma, const Mat& mb, const Scales* SA, const Scal for (int64_t mb0 = 0; mb0 < M; mb0 += MB) { const int64_t mrows = (M - mb0) < MB ? (M - mb0) : MB; - /* Packed on the calling thread, before the parallel region: every worker reads it, and - * nothing inside the region touches this arena, so the pointer cannot move under them. */ + /* Packed on the calling thread before the parallel region; nothing in the region calls + * scratch_raw, so the pointer stays valid for the workers. */ const float* Ap = pack_rows(ma, mb0, mrows, K, apack, lda); AVX_PARALLEL_FOR_IF(mrows * N * K >= 65536) @@ -349,8 +250,8 @@ static int gemm_drive(const Mat& ma, const Mat& mb, const Scales* SA, const Scal for (int64_t i = 0; i < mm; ++i) { const float sa = (SA && SA->p) ? SA->grp(mb0 + m0 + i, k0 / SA->group) : 1.0f; - acc[i][j] += - dot1(Ap + (m0 + i) * lda, Bp + j * ldb, k0, k1) * sa * sb; + acc[i][j] += dotf(Ap + (m0 + i) * lda + k0, Bp + j * ldb + k0, + k1 - k0) * sa * sb; } } } @@ -367,337 +268,39 @@ static int gemm_drive(const Mat& ma, const Mat& mb, const Scales* SA, const Scal return RAD_OK; } -/* ================================================================== the bf16 outer-product path - * - * AN ENCODER'S GEMM IS ALL PREFILL: M is the step's whole token count, thousands of rows, every - * launch. The driver above is shaped for decode -- it packs A on the calling thread one M block at - * a time and re-widens each weight row into f32 once per M block -- and at M = 3000, K = 2048 that - * is the weight widened a hundred times over, behind a single-threaded pack, for 0.14 TFLOPS on a - * 16-core part. - * - * Where both operands are bf16 with unit element stride and the CPU has AVX512_BF16 (Zen 4 on, - * Cooper Lake and Sapphire Rapids on), this path runs instead, and it is the OUTER-PRODUCT form - * this file otherwise argues against -- because here M is large enough to pay for the one thing - * that argument says it costs, a pack of B: - * - * B is packed ONCE A CALL, in parallel, into panels of 48 columns in vdpbf16ps's pair layout, - * Bp[panel][K/2][48][2]: one k-pair of 48 columns is three zmm, read contiguously. Columns past - * N and the second half of an odd K's last pair are zeros. - * The microkernel is 8 rows of A by one panel: per k-pair, three panel loads, eight 32-bit - * broadcasts of A's (k, k+1) pair, 24 vdpbf16ps into 24 accumulators. NO HORIZONTAL REDUCTION - * anywhere -- each accumulator lane is one output element -- and a row is stored as three - * 16-wide vectors. - * Threads take tiles of (64 rows) x (up to four panels), dynamically. Within a tile the panel - * loop is outer, so a panel (K x 96 bytes: 48 KiB at K = 512, 192 KiB at K = 2048) stays in L2 - * while the tile's row blocks stream through it. - * - * MEASURED on a 9950X3D, 16 threads, M = 2048: 6.9 TFLOPS at N = 4096, K = 512 and 6.1 at - * N = 512, K = 2048. The dot-product form -- vdpbf16ps along K straight out of both rows, 4 x 6 - * blocks -- reached 1.5 at both: at K = 512 a block does sixteen k steps and then 24 sixteen-lane - * reductions, so the reductions were most of its instruction stream. Below 128 rows the per-call - * pack is not paid back, and that form (gemm_bf16_dot) still runs there. - * - * It is one instruction stream inside the AVX-512 object, compiled for the extra feature with a - * function attribute and entered only after __builtin_cpu_supports says the CPU has it: an - * AVX-512 part without BF16 takes the driver above, unchanged. - * - * THE ARITHMETIC: products of bf16 pairs in f32, accumulated per output in k order two at a time, - * with bf16 denormals read as zero (the instruction's DAZ); the bias is the accumulator's start - * and the store rounds to nearest even. A different summation order from the driver's, inside the - * checker's bf16 tolerance like every vectorised reduction here. Each output element is computed - * by one thread, so the result does not depend on the thread count. */ -#if AVX_LEVEL == 3 -#define AVX_BF16_TARGET __attribute__((target("avx512f,avx512bw,avx512vl,avx512bf16"))) - -constexpr int64_t BP_COLS = 48; /* columns a panel: three zmm of f32 accumulators */ -constexpr int64_t BP_MR = 8; /* rows of A a microkernel */ - -/* f32 -> bf16 round-to-nearest-even, sixteen lanes, a NaN kept a (quiet) NaN: the scalar - * converter's arithmetic, vectorised. */ -AVX_BF16_TARGET static inline __m256i bf16_rne16(__m512 x) { - const __m512i u = _mm512_castps_si512(x); - const __m512i lsb = _mm512_and_si512(_mm512_srli_epi32(u, 16), _mm512_set1_epi32(1)); - __m512i r = _mm512_srli_epi32(_mm512_add_epi32(_mm512_add_epi32(u, _mm512_set1_epi32(0x7fff)), - lsb), 16); - const __mmask16 nan = _mm512_cmpgt_epu32_mask(_mm512_and_si512(u, _mm512_set1_epi32(0x7fffffff)), - _mm512_set1_epi32(0x7f800000)); - r = _mm512_mask_mov_epi32(r, nan, _mm512_or_si512(_mm512_srli_epi32(u, 16), - _mm512_set1_epi32(0x40))); - return _mm512_cvtepi32_epi16(r); +/* gemm_drive over an activation scale grid finer than the weight's. No supported format has one, + * but libref applies such a scale to each element before the product, so A is scaled into an f32 + * copy here and the product read with no activation scale. The copy is one pass over A. */ +static int gemm_drive_fine_a(const Mat& ma, const Mat& mb, const Scales* SA, const Scales* SB, + const RadTensor* Y, const RadTensor* bias, int64_t M, int64_t N, + int64_t K) { + static thread_local std::vector scaled; + scaled.resize((size_t)(M * K)); + for (int64_t m = 0; m < M; ++m) { + float* row = scaled.data() + m * K; + const float* src = pack_rows(ma, m, 1, K, row, K); + for (int64_t k = 0; k < K; ++k) row[k] = src[k] * SA->grp(m, k / SA->group); + } + RadTensor a{}; + a.data = scaled.data(); + a.dtype = RAD_F32; + a.rank = 2; + a.shape[0] = M; a.shape[1] = K; + a.stride[0] = K; a.stride[1] = 1; + return gemm_drive(as_mat(&a, K), mb, nullptr, SB, Y, bias, M, N, K); } -/* MR_ rows of A against one packed panel, over all of K, stored to the panel's `cols` columns of - * Y rows 0..MR_-1 (Y already offset to the block's first element). `bv` starts the accumulators: - * the bias, or zeros. */ -template -AVX_BF16_TARGET static inline void op_block(const uint16_t* A, int64_t lda, const uint16_t* panel, - int64_t K, const __m512* bv, void* Y, int64_t ys_r, - bool yb, int64_t cols) { - __m512 acc[MR_][3]; -#pragma GCC unroll 8 - for (int i = 0; i < MR_; ++i) { - acc[i][0] = bv[0]; - acc[i][1] = bv[1]; - acc[i][2] = bv[2]; - } - const int64_t kp_full = K / 2; - const uint16_t* bp = panel; - for (int64_t kp = 0; kp < kp_full; ++kp, bp += 2 * BP_COLS) { - const __m512bh b0 = (__m512bh)_mm512_loadu_si512((const void*)bp); - const __m512bh b1 = (__m512bh)_mm512_loadu_si512((const void*)(bp + 32)); - const __m512bh b2 = (__m512bh)_mm512_loadu_si512((const void*)(bp + 64)); -#pragma GCC unroll 8 - for (int i = 0; i < MR_; ++i) { - uint32_t pr; - std::memcpy(&pr, A + i * lda + 2 * kp, 4); - const __m512bh av = (__m512bh)_mm512_set1_epi32((int)pr); - acc[i][0] = _mm512_dpbf16_ps(acc[i][0], av, b0); - acc[i][1] = _mm512_dpbf16_ps(acc[i][1], av, b1); - acc[i][2] = _mm512_dpbf16_ps(acc[i][2], av, b2); - } - } - if (K & 1) { - /* The odd last k: A's element alone in the pair's low half, never the one past the row. */ - const __m512bh b0 = (__m512bh)_mm512_loadu_si512((const void*)bp); - const __m512bh b1 = (__m512bh)_mm512_loadu_si512((const void*)(bp + 32)); - const __m512bh b2 = (__m512bh)_mm512_loadu_si512((const void*)(bp + 64)); -#pragma GCC unroll 8 - for (int i = 0; i < MR_; ++i) { - const __m512bh av = (__m512bh)_mm512_set1_epi32((int)(uint32_t)A[i * lda + K - 1]); - acc[i][0] = _mm512_dpbf16_ps(acc[i][0], av, b0); - acc[i][1] = _mm512_dpbf16_ps(acc[i][1], av, b1); - acc[i][2] = _mm512_dpbf16_ps(acc[i][2], av, b2); - } - } - /* Every accumulator index is a constant, so the block never leaves the registers. */ - auto mask = [&](int64_t c0) { - const int64_t w = cols - c0 <= 0 ? 0 : (cols - c0 < 16 ? cols - c0 : 16); - return (__mmask16)((1u << w) - 1); - }; - const __mmask16 m0 = mask(0), m1 = mask(16), m2 = mask(32); -#pragma GCC unroll 8 - for (int i = 0; i < MR_; ++i) { - if (yb) { - uint16_t* yr = (uint16_t*)Y + i * ys_r; - _mm256_mask_storeu_epi16(yr, m0, bf16_rne16(acc[i][0])); - _mm256_mask_storeu_epi16(yr + 16, m1, bf16_rne16(acc[i][1])); - _mm256_mask_storeu_epi16(yr + 32, m2, bf16_rne16(acc[i][2])); - } else { - float* yr = (float*)Y + i * ys_r; - _mm512_mask_storeu_ps(yr, m0, acc[i][0]); - _mm512_mask_storeu_ps(yr + 16, m1, acc[i][1]); - _mm512_mask_storeu_ps(yr + 32, m2, acc[i][2]); - } - } +/* A quantised product (gemm_nt_q and its gated and parted forms): the bf16 grouped driver + * (avx_gemm_tile.cpp) where it applies, which keeps libref's group structure, else gemm_drive. */ +static int gemm_q_drive(const Mat& ma, const Mat& mb, const Scales* SA, const Scales* SB, + const RadTensor* Y, const RadTensor* bias, int64_t M, int64_t N, + int64_t K) { + if (gemm_q_bf16(ma, mb, SA, SB, Y, bias, M, N, K)) return RAD_OK; + return gemm_drive(ma, mb, SA, SB, Y, bias, M, N, K); } -/* THE SMALL-M FORM: vdpbf16ps along K straight out of both rows, 4 x 6 blocks, no pack. The pack - * in gemm_bf16_dp touches every weight once a call -- 250 MB a forward pass for EmbeddingGemma - * 2 -- which an encoder step of thousands of rows amortises and a single 16-token query does not: - * there the outer-product path took a query from 13 to 17 ms. The pack pays for itself where the rows it - * serves are many; by the measured rates (1.5 against 6 TFLOPS, the pack streaming at memory - * speed) that is from about 75 rows, and 128 is the switch. */ -template -AVX_BF16_TARGET static inline void dp_block(const uint16_t* A, int64_t lda, const uint16_t* B, - int64_t ldb, int64_t K, float out[MB_][NB_]) { - __m512 acc[MB_][NB_]; - for (int i = 0; i < MB_; ++i) - for (int j = 0; j < NB_; ++j) acc[i][j] = _mm512_setzero_ps(); - int64_t k = 0; - for (; k + 32 <= K; k += 32) { - __m512bh av[MB_]; - for (int i = 0; i < MB_; ++i) - av[i] = (__m512bh)_mm512_loadu_si512((const void*)(A + i * lda + k)); - for (int j = 0; j < NB_; ++j) { - const __m512bh bv = (__m512bh)_mm512_loadu_si512((const void*)(B + j * ldb + k)); - for (int i = 0; i < MB_; ++i) acc[i][j] = _mm512_dpbf16_ps(acc[i][j], av[i], bv); - } - } - if (k < K) { - const __mmask32 mk = (__mmask32)((1ull << (K - k)) - 1); - __m512bh av[MB_]; - for (int i = 0; i < MB_; ++i) - av[i] = (__m512bh)_mm512_maskz_loadu_epi16(mk, (const void*)(A + i * lda + k)); - for (int j = 0; j < NB_; ++j) { - const __m512bh bv = (__m512bh)_mm512_maskz_loadu_epi16(mk, (const void*)(B + j * ldb + k)); - for (int i = 0; i < MB_; ++i) acc[i][j] = _mm512_dpbf16_ps(acc[i][j], av[i], bv); - } - } - for (int i = 0; i < MB_; ++i) - for (int j = 0; j < NB_; ++j) out[i][j] = _mm512_reduce_add_ps(acc[i][j]); -} - -static inline uint16_t f32_bf16_rne(float f) { - uint32_t u; - std::memcpy(&u, &f, 4); - if ((u & 0x7f800000u) == 0x7f800000u && (u & 0x007fffffu)) return (uint16_t)((u >> 16) | 0x40u); - return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); -} - -AVX_BF16_TARGET static void gemm_bf16_dot(const uint16_t* A, int64_t lda, const uint16_t* B, - int64_t ldb, const RadTensor* Y, int64_t ys_r, - const RadTensor* bias, int64_t M, int64_t N, int64_t K) { - const bool yb = Y->dtype == RAD_BF16; - /* The tile grid: 64 rows of A by a column count chosen so there are at least four tiles a - * thread, capped at 192 columns. */ - constexpr int64_t BMR = 4, BNR = 6, MC = 64; - const int64_t mt = (M + MC - 1) / MC; -#ifdef _OPENMP - const int64_t nth = (int64_t)avx_team_size(); -#else - const int64_t nth = 1; -#endif - int64_t want_nt = (4 * nth + mt - 1) / mt; - if (want_nt < 1) want_nt = 1; - int64_t NC = (N + want_nt - 1) / want_nt; - NC = ((NC + BNR - 1) / BNR) * BNR; - if (NC > 192) NC = 192; - if (NC < BNR) NC = BNR; - const int64_t ntl = (N + NC - 1) / NC; - - auto store = [&](int64_t m, int64_t n, float v) { - if (bias) v += ldt(bias, n * laststride(bias)); - if (yb) ((uint16_t*)Y->data)[m * ys_r + n] = f32_bf16_rne(v); - else ((float*)Y->data)[m * ys_r + n] = v; - }; - -#ifdef _OPENMP -#pragma omp parallel for schedule(dynamic, 1) num_threads(avx_team_size()) -#endif - for (int64_t t = 0; t < mt * ntl; ++t) { - const int64_t m_lo = (t / ntl) * MC, n_lo = (t % ntl) * NC; - const int64_t m_hi = m_lo + MC < M ? m_lo + MC : M; - const int64_t n_hi = n_lo + NC < N ? n_lo + NC : N; - for (int64_t n0 = n_lo; n0 < n_hi; n0 += BNR) { - const int64_t nn = n_hi - n0 < BNR ? n_hi - n0 : BNR; - for (int64_t m0 = m_lo; m0 < m_hi; m0 += BMR) { - const int64_t mm = m_hi - m0 < BMR ? m_hi - m0 : BMR; - if (mm == BMR && nn == BNR) { - float o[BMR][BNR]; - dp_block(A + m0 * lda, lda, B + n0 * ldb, ldb, K, o); - for (int i = 0; i < BMR; ++i) - for (int j = 0; j < BNR; ++j) store(m0 + i, n0 + j, o[i][j]); - } else { - for (int64_t i = 0; i < mm; ++i) - for (int64_t j = 0; j < nn; ++j) { - float o[1][1]; - dp_block<1, 1>(A + (m0 + i) * lda, lda, B + (n0 + j) * ldb, ldb, K, o); - store(m0 + i, n0 + j, o[0][0]); - } - } - } - } - } -} - -/* A bf16 x bf16 product into Y, or false when this path does not apply and the driver should run. */ -AVX_BF16_TARGET static bool gemm_bf16_dp(const Mat& ma, const Mat& mb, const RadTensor* Y, - const RadTensor* bias, int64_t M, int64_t N, int64_t K) { - static const bool have = __builtin_cpu_supports("avx512bf16"); - if (!have || M < 16) return false; - if (ma.t->dtype != RAD_BF16 || mb.t->dtype != RAD_BF16 || ma.cs != 1 || mb.cs != 1) return false; - if (Y->dtype != RAD_BF16 && Y->dtype != RAD_F32) return false; - const int64_t ys_r = row_stride(Y, N); - const int64_t ys_c = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1; - if (ys_c != 1) return false; - - const uint16_t* A = (const uint16_t*)ma.t->data; - const uint16_t* B = (const uint16_t*)mb.t->data; - const int64_t lda = ma.rs, ldb = mb.rs; - if (M < 128) { - gemm_bf16_dot(A, lda, B, ldb, Y, ys_r, bias, M, N, K); - return true; - } - const bool yb = Y->dtype == RAD_BF16; - const size_t yel = yb ? 2 : 4; - - /* ---- the pack, into the calling thread's arena before any worker reads it */ - const int64_t np = (N + BP_COLS - 1) / BP_COLS; - const int64_t kp_n = (K + 1) / 2; - const int64_t pstride = kp_n * 2 * BP_COLS; /* uint16 a panel */ - uint16_t* Bp = (uint16_t*)scratch_raw((size_t)(np * pstride) * sizeof(uint16_t) + 64); -#ifdef _OPENMP -#pragma omp parallel for schedule(static) num_threads(avx_team_size()) if(np * pstride >= 65536) -#endif - for (int64_t p = 0; p < np; ++p) { - uint32_t* dst = (uint32_t*)(Bp + p * pstride); - const int64_t n0 = p * BP_COLS; - for (int64_t c = 0; c < BP_COLS; ++c) { - const int64_t n = n0 + c; - if (n >= N) { - for (int64_t kp = 0; kp < kp_n; ++kp) dst[kp * BP_COLS + c] = 0; - continue; - } - const uint16_t* row = B + n * ldb; - for (int64_t kp = 0; kp < K / 2; ++kp) { - uint32_t pr; - std::memcpy(&pr, row + 2 * kp, 4); - dst[kp * BP_COLS + c] = pr; - } - if (K & 1) dst[(kp_n - 1) * BP_COLS + c] = (uint32_t)row[K - 1]; - } - } - - /* ---- the tile grid: 64-row M blocks by groups of panels, at least four tiles a thread */ - constexpr int64_t MC = 64; - const int64_t mt = (M + MC - 1) / MC; -#ifdef _OPENMP - const int64_t nth = (int64_t)avx_team_size(); -#else - const int64_t nth = 1; -#endif - int64_t groups = (4 * nth + mt - 1) / mt; - if (groups < 1) groups = 1; - int64_t PG = (np + groups - 1) / groups; - if (PG > 4) PG = 4; - if (PG < 1) PG = 1; - const int64_t ng = (np + PG - 1) / PG; - -#ifdef _OPENMP -#pragma omp parallel for schedule(dynamic, 1) num_threads(avx_team_size()) -#endif - for (int64_t t = 0; t < mt * ng; ++t) { - const int64_t m_lo = (t / ng) * MC, p_lo = (t % ng) * PG; - const int64_t m_hi = m_lo + MC < M ? m_lo + MC : M; - const int64_t p_hi = p_lo + PG < np ? p_lo + PG : np; - for (int64_t p = p_lo; p < p_hi; ++p) { - const int64_t n0 = p * BP_COLS; - const int64_t cols = N - n0 < BP_COLS ? N - n0 : BP_COLS; - __m512 bv[3]; - for (int v = 0; v < 3; ++v) { - alignas(64) float bb[16]; - for (int e = 0; e < 16; ++e) { - const int64_t n = n0 + 16 * v + e; - bb[e] = (bias && n < N) ? ldt(bias, n * laststride(bias)) : 0.0f; - } - bv[v] = _mm512_load_ps(bb); - } - const uint16_t* panel = Bp + p * pstride; - for (int64_t m0 = m_lo; m0 < m_hi; m0 += BP_MR) { - const int64_t mm = m_hi - m0 < BP_MR ? m_hi - m0 : BP_MR; - const uint16_t* Ar = A + m0 * lda; - void* Yr = (char*)Y->data + (size_t)(m0 * ys_r + n0) * yel; - switch (mm) { - case 8: op_block<8>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break; - case 7: op_block<7>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break; - case 6: op_block<6>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break; - case 5: op_block<5>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break; - case 4: op_block<4>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break; - case 3: op_block<3>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break; - case 2: op_block<2>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break; - default: op_block<1>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break; - } - } - } - } - return true; -} -#endif - -/* Shared entry for gemm_nt / gemm_nt_bias / logits_gemm. `nkey`/`kkey` name which parameters carry - * N and K, because logits_gemm spells them n_vocab and n_embd. */ -/* gemm_nt_bias's epilogue (docs/OPS.md): an activation of the stored product, then a residual, - * each step read back from and stored to the output's dtype -- the unfused chain, as libref has it. */ +/* gemm_nt_bias's epilogue (docs/OPS.md): activation of the stored product, then the residual add, + * each step read from and stored to the output's dtype (the unfused chain, as in libref). */ static void gemm_epilogue(const RadTensor* Y, const RadTensor* res, int act, int64_t M, int64_t N) { const int64_t ys = laststride(Y), yr = Y->rank >= 2 ? Y->stride[Y->rank - 2] : N; const int64_t rs = res ? laststride(res) : 0, rr = res && res->rank >= 2 ? res->stride[res->rank - 2] : N; @@ -706,15 +309,51 @@ static void gemm_epilogue(const RadTensor* Y, const RadTensor* res, int act, int for (int64_t n = 0; n < N; ++n) { const int64_t o = m * yr + n * ys; float v = ldt(Y, o); - if (act == 1) { v = 0.5f * v * (1.0f + std::erf(v * 0.70710678118654752f)); stt(Y, o, v); } + if (act == 1) { v = 0.5f * v * (1.0f + sc_erf(v * 0.70710678118654752f)); stt(Y, o, v); } else if (act == 2) { - v = 0.5f * v * (1.0f + std::tanh(0.7978845608028654f * (v + 0.044715f * v * v * v))); + v = 0.5f * v * (1.0f + sc_tanh(0.7978845608028654f * (v + 0.044715f * v * v * v))); stt(Y, o, v); } if (res) stt(Y, o, ldt(res, m * rr + n * rs) + ldt(Y, o)); } } +/* Whether two operands' memory overlaps: from the first element to one past the last element + * their strides reach. A residual may be the output itself (an in-place residual add). */ +static bool spans_overlap(const RadTensor* a, const RadTensor* b) { + auto span = [](const RadTensor* t, const char** lo, const char** hi) { + int64_t last = 0; + for (uint32_t i = 0; i < t->rank; ++i) last += (t->shape[i] - 1) * t->stride[i]; + const int64_t eb = (rad_dtype_bits(t->dtype) + 7) / 8; + *lo = static_cast(t->data); + *hi = *lo + (last + 1) * eb; + }; + const char *alo, *ahi, *blo, *bhi; + span(a, &alo, &ahi); + span(b, &blo, &bhi); + return alo < bhi && blo < ahi; +} + +/* The residual as f32 [M, N], read before the product overwrites it when it is the output's own + * memory. Widening is exact for every float dtype, so the epilogue's sum is unchanged. */ +static RadTensor snapshot_res(const RadTensor* res, int64_t M, int64_t N, std::vector* buf) { + const int64_t rs_r = res->rank >= 2 ? res->stride[res->rank - 2] : N, rs_c = laststride(res); + buf->resize((size_t)(M * N)); + for (int64_t m = 0; m < M; ++m) + for (int64_t n = 0; n < N; ++n) (*buf)[(size_t)(m * N + n)] = ldt(res, m * rs_r + n * rs_c); + RadTensor t{}; + t.dtype = RAD_F32; + t.rank = 2; + t.shape[0] = M; + t.shape[1] = N; + t.stride[0] = N; + t.stride[1] = 1; + t.data = buf->data(); + return t; +} + +/* Shared entry for gemm_nt / gemm_nt_bias / logits_gemm. `nkey`/`kkey` name the N and K + * parameters (logits_gemm uses n_vocab and n_embd). */ static int gemm_nt_impl(const RadArgs* a, bool bias_operand, const char* nkey, const char* kkey) { /* gemm_nt_bias is a, b, bias, res?, y; the other two are a, b, y. */ const int nt = bias_operand ? 5 : 3; @@ -724,22 +363,59 @@ static int gemm_nt_impl(const RadArgs* a, bool bias_operand, const char* nkey, c const RadTensor* res = bias_operand ? rad_arg_in(a, 3) : nullptr; static const char* kActs[] = { "none", "gelu", "gelu_tanh" }; const int act = bias_operand ? p_enum(a, "act", kActs, 3, 0) : 0; + if (act < 0 || act > 2) return RAD_E_INVAL; const int64_t K = p_int(a, kkey, B->rank >= 2 ? B->shape[B->rank - 1] : 0); const int64_t N = p_int(a, nkey, B->rank >= 2 ? B->shape[B->rank - 2] : 0); if (K <= 0 || N <= 0) return RAD_E_SHAPE; const int64_t M = numel(Y) / N; if (M <= 0) return RAD_E_SHAPE; - if (numel(A) < M * K || numel(B) < N * K) return RAD_E_SHAPE; + /* A head of codes and scale, joined (avx_planes.h); its extents are its planes'. */ + const bool joined = avxp::is_joined(B); + if (numel(A) < M * K || (!joined && numel(B) < N * K)) return RAD_E_SHAPE; if (bias && numel(bias) < N) return RAD_E_SHAPE; if (res && numel(res) < M * N) return RAD_E_SHAPE; + std::vector res_buf; + RadTensor res_copy{}; + if (res && spans_overlap(res, Y)) { + res_copy = snapshot_res(res, M, N, &res_buf); + res = &res_copy; + } - const Mat ma = as_mat(A, K), mb = as_mat(B, K); -#if AVX_LEVEL == 3 - if (!gemm_bf16_dp(ma, mb, Y, bias, M, N, K)) -#endif - { + const Mat ma = as_mat(A, K); + if (joined) { + HeadDec dec; + int st = avxp::scaled_rows(B, N, K, &dec.sr); + if (st != RAD_OK) return st; + dec.K = K; + /* The codes and their scale grid read as a quantised weight, where the bf16 grouped + * driver applies (E4M3 or int8 codes against a bf16 activation). */ + RadTensor ct{}, sct{}; + const avxp::JPlane& cp = dec.sr.codes; + const avxp::JPlane& sp = dec.sr.scale; + const int64_t ses = rad_dtype_bits(sp.dt) / 8; + if (ses > 0 && sp.row_bytes % ses == 0) { + ct.data = (void*)cp.p; ct.dtype = cp.dt; ct.rank = 2; + ct.shape[0] = N; ct.shape[1] = K; ct.stride[0] = cp.row_bytes; ct.stride[1] = 1; + sct.data = (void*)sp.p; sct.dtype = sp.dt; sct.rank = 2; + sct.shape[0] = sp.rows; sct.shape[1] = sp.cols; + sct.stride[0] = sp.row_bytes / ses; sct.stride[1] = 1; + const Scales SB = make_scales(&sct, N, K, false); + if (gemm_q_bf16(ma, as_mat(&ct, K), nullptr, &SB, Y, bias, M, N, K)) { + if (act || res) gemm_epilogue(Y, res, act, M, N); + return RAD_OK; + } + } + const Mat mb{ B, K, 1, &dec }; + st = gemm_drive(ma, mb, nullptr, nullptr, Y, bias, M, N, K); + if (st < 0) return st; + if (act || res) gemm_epilogue(Y, res, act, M, N); + return RAD_OK; + } + const Mat mb = as_mat(B, K); + /* bf16 x bf16 takes the grouped driver where the CPU has AVX512_BF16, as one group. */ + if (!gemm_q_bf16(ma, mb, nullptr, nullptr, Y, bias, M, N, K)) { const int st = gemm_drive(ma, mb, nullptr, nullptr, Y, bias, M, N, K); if (st < 0) return st; } @@ -747,6 +423,547 @@ static int gemm_nt_impl(const RadArgs* a, bool bias_operand, const char* nkey, c return RAD_OK; } +/* Parts (`pb1`, `pb2`): weight rows [0, pb1), [pb1, pb2) and [pb2, N) each multiply their own + * copy of the activation, for a fused projection whose pieces were rotated separately (ParoQuant, + * MXFP4 weights). The copies sit side by side, so `a` is [M, parts * K] and its scale + * [M, parts * K / 128]; each part is a plain product over its rows. 0 omits a bound: no `pb1` is + * one part, no `pb2` ends the second at N. libref's reading and refusals (ref_gemm.cpp). */ +static int gemm_ntq_parts(const RadTensor* A, const RadTensor* as_, const RadTensor* B, + const RadTensor* bs_, const RadTensor* Y, int64_t pb1, int64_t pb2, + int64_t M, int64_t N, int64_t K) { + if (B->dtype != RAD_FP4E2M1 || A->rank < 2) return RAD_E_UNSUPPORTED; + const int64_t e1 = pb1 > 0 ? std::min(pb1, N) : N; + const int64_t e2 = pb2 > 0 ? std::max(e1, std::min(pb2, N)) : N; + const int64_t bound[4] = { 0, e1, e2, N }; + const int64_t acols = A->shape[A->rank - 1]; + const int64_t parts = e2 < N ? 3 : (e1 < N ? 2 : 1); + if (acols != parts * K || (e1 % 16) || (e2 % 16)) return RAD_E_SHAPE; + if (!as_ || as_->rank < 2 || !bs_ || bs_->rank < 1) return RAD_E_INVAL; + const int64_t sa_cols = as_->shape[as_->rank - 1]; + if (sa_cols % parts) return RAD_E_SHAPE; + const int64_t sa_part = sa_cols / parts; /* K / 128 */ + const int64_t bs_cols = bs_->shape[bs_->rank - 1]; + const int64_t ys = row_stride(Y, N); + for (int p = 0; p < 3; ++p) { + const int64_t n0 = bound[p], n1 = bound[p + 1]; + if (n1 <= n0) continue; + RadTensor Ap = *A, Sp = *as_, Bp = *B, Bsp = *bs_, Yp = *Y; + Ap.data = (uint8_t*)A->data + rad_dtype_bytes(A->dtype, p * K); + Ap.rank = 2; Ap.shape[0] = M; Ap.shape[1] = K; + Ap.stride[0] = row_stride(A, acols); Ap.stride[1] = 1; + Sp.data = (uint8_t*)as_->data + rad_dtype_bytes(as_->dtype, p * sa_part); + Sp.shape[Sp.rank - 1] = sa_part; + Bp.data = (uint8_t*)B->data + rad_dtype_bytes(B->dtype, n0 * K); + Bp.rank = 2; Bp.shape[0] = n1 - n0; Bp.shape[1] = K; Bp.stride[0] = K; Bp.stride[1] = 1; + Bsp.data = (uint8_t*)bs_->data + rad_dtype_bytes(bs_->dtype, n0 * bs_cols); + Bsp.rank = 2; Bsp.shape[0] = n1 - n0; Bsp.shape[1] = bs_cols; + Bsp.stride[0] = bs_cols; Bsp.stride[1] = 1; + Yp.data = (uint8_t*)Y->data + rad_dtype_bytes(Y->dtype, n0); + Yp.rank = 2; Yp.shape[0] = M; Yp.shape[1] = n1 - n0; Yp.stride[0] = ys; Yp.stride[1] = 1; + const Scales SAp = make_scales(&Sp, M, K, false); + const Scales SBp = make_scales(&Bsp, n1 - n0, K, true); + const int rc = gemm_q_drive(as_mat(&Ap, K), as_mat(&Bp, K), &SAp, &SBp, &Yp, nullptr, M, + n1 - n0, K); + if (rc != RAD_OK) return rc; + } + return RAD_OK; +} + +/* ================================================================== the small-M integer path + * + * w2a8 and w4a8_asym at decode and draft row counts (M <= 16, a draft head's rows): the weight is + * read once and never widened. Each 32 bytes of codes split into code planes in registers (four + * of u2, two of u4, one shift and mask each), and the activation is rearranged once per call into + * the same plane order, so a plane meets its activation bytes with vpmaddubsw (unsigned code times + * signed code, pairs summed exactly: at most 2 * 15 * 127) and vpmaddwd into int32. Per row and + * group of 128 the integer sum is exact; it is widened and scaled into f32 lanes, and the zero is + * removed per (row, group) through a_sum: + * + * y[m][n] = a_scale[m] * (sum_g scale[n][g] * sum(a * code) - sum_g scale * zero * a_sum[g][m]) + * + * the arithmetic libref's reference states, in another order. Levels below AVX2 use the decoded + * driver. At AVX-512 a CPU with VNNI multiplies each plane in one vpdpbusd. */ +#if AVX_LEVEL >= 2 + +/* A joined zero-point grid's scale and zero for (row, group), read directly for the planes the + * grids are stored in (f16, u8) and through the generic reader otherwise. */ +static inline float zp_scale_at(const avxp::JPlane& p, int64_t i, int64_t j) { + if (p.dt == RAD_F16) return _cvtsh_ss(((const uint16_t*)(p.p + i * p.row_bytes))[j]); + return p.at(i, j); +} +static inline int32_t zp_zero_at(const avxp::JPlane& p, int64_t i, int64_t j) { + if (p.dt == RAD_U8) return p.p[i * p.row_bytes + j]; + return (int32_t)p.at(i, j); +} + +/* The activation codes in the weight's plane order: per group of 128 and per 32 bytes of codes + * (`cpb` codes a byte), plane t's byte j meets code cpb * j + t of those 32 bytes' codes. */ +static void zp_planes_a(const int8_t* a, int64_t K, int cpb, int8_t* out) { + const int64_t span = 32 * (int64_t)cpb; /* codes in 32 bytes */ + for (int64_t c0 = 0; c0 < K; c0 += span) + for (int t = 0; t < cpb; ++t) + for (int64_t j = 0; j < 32; ++j) out[c0 + t * 32 + j] = a[c0 + cpb * j + t]; +} + +/* At AVX-512 the integer path is compiled for VNNI as well, and the VNNI instantiations run only + * where the CPU reports it; the others use no VNNI instruction. */ +#if AVX_LEVEL == 3 +#define AVX_ZP_I8_TARGET __attribute__((target("avx512vnni,avx512vl"))) +#else +#define AVX_ZP_I8_TARGET +#endif + +/* One plane's products into the int32 lanes: vpmaddubsw then vpmaddwd, or with VNNI the one + * vpdpbusd that does both, exactly (u8 times s8, four products a lane, no saturation either way at + * these code widths). */ +template +AVX_ZP_I8_TARGET static inline __m256i zp_dot_plane(__m256i acc, __m256i w, __m256i a, + __m256i ones) { +#if AVX_LEVEL == 3 + if constexpr (VNNI) return _mm256_dpbusd_epi32(acc, w, a); +#endif + return _mm256_add_epi32(acc, _mm256_madd_epi16(_mm256_maddubs_epi16(w, a), ones)); +} + +template +AVX_ZP_I8_TARGET +static void zp_rows_i8(const int8_t* ap, int64_t K, const uint8_t* codes, int64_t rb, + const avxp::JPlane& sc, const avxp::JPlane& zp, const float* sa, + const float* asum, int64_t asum_ld, int64_t n0, int64_t n1, int64_t m0, + const RadTensor* Y, int64_t ys_r, int64_t ys_c) { + constexpr int CPB = 8 / BITS; /* codes a byte */ + constexpr int64_t SPAN = 32 * CPB; /* codes a 32-byte chunk */ + const int64_t G = K / 128; + const __m256i mask = _mm256_set1_epi8((char)((1 << BITS) - 1)); + const __m256i ones = _mm256_set1_epi16(1); + for (int64_t n = n0; n < n1; ++n) { + const uint8_t* cr = codes + n * rb; + __m256 acc[MB]; + for (int i = 0; i < MB; ++i) acc[i] = _mm256_setzero_ps(); + float corr[MB] = {}; + for (int64_t g = 0; g < G; ++g) { + const float s = zp_scale_at(sc, n, g); + const float zs = (float)zp_zero_at(zp, n, g) * s; + const __m256 vs = _mm256_set1_ps(s); + for (int i = 0; i < MB; ++i) corr[i] += zs * asum[g * asum_ld + m0 + i]; + for (int64_t c0 = g * 128; c0 < (g + 1) * 128; c0 += SPAN) { + const __m256i x = _mm256_loadu_si256((const __m256i*)(cr + c0 / CPB)); + __m256i w[CPB]; + for (int t = 0; t < CPB; ++t) + w[t] = _mm256_and_si256(_mm256_srli_epi16(x, BITS * t), mask); + for (int i = 0; i < MB; ++i) { + const int8_t* ar = ap + (m0 + i) * K + c0; + __m256i d = _mm256_setzero_si256(); + for (int t = 0; t < CPB; ++t) + d = zp_dot_plane( + d, w[t], _mm256_loadu_si256((const __m256i*)(ar + 32 * t)), ones); + acc[i] = _mm256_fmadd_ps(_mm256_cvtepi32_ps(d), vs, acc[i]); + } + } + } + for (int i = 0; i < MB; ++i) { + __m128 h = _mm_add_ps(_mm256_castps256_ps128(acc[i]), + _mm256_extractf128_ps(acc[i], 1)); + h = _mm_add_ps(h, _mm_movehl_ps(h, h)); + h = _mm_add_ss(h, _mm_movehdup_ps(h)); + stt(Y, (m0 + i) * ys_r + n * ys_c, (_mm_cvtss_f32(h) - corr[i]) * sa[m0 + i]); + } + } +} + +/* y for rows [0, M) of the integer path; false when it does not apply (M over 16, a group other + * than 128, codes other than u2 / u4). `a` is column-order int8 [M, K]. */ +static bool zp_small_i8(int bits, const int8_t* a, int64_t lda, const float* sa, + const RadTensor* asum, int64_t mpad, const uint8_t* codes, int64_t rb, + const avxp::JPlane& sc, const avxp::JPlane& zp, int64_t group, + const RadTensor* Y, int64_t M, int64_t N, int64_t K) { + if (M > 16 || group != 128 || K % 128 || (bits != 2 && bits != 4)) return false; + if (asum->dtype != RAD_F32 || laststride(asum) != 1) return false; + const int cpb = 8 / bits; + static thread_local std::vector ap; + ap.resize((size_t)(M * K)); + for (int64_t m = 0; m < M; ++m) zp_planes_a(a + m * lda, K, cpb, ap.data() + m * K); + const float* as = (const float*)asum->data; + const int64_t ys_r = row_stride(Y, N), ys_c = laststride(Y); + /* Rows a thread takes at a time: enough to amortise the scheduling, few enough to spread a + * 5120-row projection over every core. */ + const int64_t NB = 16, nblk = (N + NB - 1) / NB; + using Fn = void (*)(const int8_t*, int64_t, const uint8_t*, int64_t, const avxp::JPlane&, + const avxp::JPlane&, const float*, const float*, int64_t, int64_t, + int64_t, int64_t, const RadTensor*, int64_t, int64_t); + static const Fn kFn[2][2][4] = { + { { zp_rows_i8<1, 2, false>, zp_rows_i8<2, 2, false>, zp_rows_i8<4, 2, false>, + zp_rows_i8<8, 2, false> }, + { zp_rows_i8<1, 4, false>, zp_rows_i8<2, 4, false>, zp_rows_i8<4, 4, false>, + zp_rows_i8<8, 4, false> } }, + { { zp_rows_i8<1, 2, true>, zp_rows_i8<2, 2, true>, zp_rows_i8<4, 2, true>, + zp_rows_i8<8, 2, true> }, + { zp_rows_i8<1, 4, true>, zp_rows_i8<2, 4, true>, zp_rows_i8<4, 4, true>, + zp_rows_i8<8, 4, true> } }, + }; + /* AVX512-VNNI is not in the level's flags (many AVX-512 parts lack it) and is checked here. */ +#if AVX_LEVEL == 3 + static const bool vnni = __builtin_cpu_supports("avx512vnni"); +#else + static const bool vnni = false; +#endif + const Fn* fn = kFn[vnni ? 1 : 0][bits == 4 ? 1 : 0]; + /* Taken here: inside the region `ap` names each worker's own (empty) thread_local. */ + const int8_t* apd = ap.data(); + AVX_PARALLEL_FOR_IF(M * N * K >= 65536) + for (int64_t b = 0; b < nblk; ++b) { + const int64_t n0 = b * NB, n1 = n0 + NB < N ? n0 + NB : N; + for (int64_t m0 = 0; m0 < M;) { + const int64_t left = M - m0; + const int lv = left >= 8 ? 3 : left >= 4 ? 2 : left >= 2 ? 1 : 0; + fn[lv](apd, K, codes, rb, sc, zp, sa, as, mpad, n0, n1, m0, Y, ys_r, ys_c); + m0 += (int64_t)1 << lv; + } + } + return true; +} +#endif + +/* ================================================================== the small-M 16-bit path + * + * w4a16_asym and w5a16 at decode and verify row counts (M <= 16): every weight row decodes in + * registers, sixteen codes at a time, to (code - zero) * scale, and meets each activation row + * (widened to f32 once per call) with one FMA, so the weight is read once and never stored widened. + * The decoded driver writes each row to a packing buffer and reads it back, a pass through L2 this + * path does not make. u4 is split by mask and shift, u5 by pdep (BMI2, checked at run time: the + * path is taken only where the CPU has it). */ +#if AVX_LEVEL >= 2 + +/* Sixteen codes of a row's 4- or 5-bit stream from element k (a multiple of 16), one a byte. In the + * last 16 codes of a row the u5 read takes only the bytes asked for. */ +template +__attribute__((target("bmi2"))) static inline __m128i zp_codes16(const uint8_t* row, int64_t k, + bool last) { + if (BITS == 4) { + const __m128i x = _mm_loadl_epi64((const __m128i*)(row + k / 2)); + const __m128i m4 = _mm_set1_epi8(0x0f); + return _mm_unpacklo_epi8(_mm_and_si128(x, m4), _mm_and_si128(_mm_srli_epi16(x, 4), m4)); + } + const uint8_t* p = row + k / 8 * 5; + uint64_t v0 = 0, v1 = 0; + if (!last) { + std::memcpy(&v0, p, 8); + std::memcpy(&v1, p + 5, 8); + v0 &= 0xffffffffffull; + v1 &= 0xffffffffffull; + } else { + std::memcpy(&v0, p, 5); + std::memcpy(&v1, p + 5, 5); + } + const unsigned long long kLow5 = 0x1f1f1f1f1f1f1f1full; + return _mm_set_epi64x((long long)_pdep_u64(v1, kLow5), (long long)_pdep_u64(v0, kLow5)); +} + +/* Rows [n0, n1) (at most 16) against activation rows [m0, m0 + MB). K is walked in chunks of + * whole groups, about 512 columns, and within a chunk every weight row of the block: the chunk of + * activation rows (MB x 512 floats, 16 KiB at MB = 8) stays in L1 while the block's rows stream + * past it, where a row at a time would read every activation row from L2 per weight row. The + * accumulators wait in `accb` between chunks. U independent accumulators a row (4 at MB = 1, 2 at + * MB = 2) cover the FMA latency a single dependent chain would wait on. NR weight rows (2 at + * AVX-512 from MB = 4, whose 32 registers hold both rows' accumulators) decode side by side and + * share each activation load. A block never straddles a part: parts end on multiples of 16. */ +template +__attribute__((target("bmi2"))) static void zp_rows_f16( + const float* af, int64_t lda, int64_t K, const uint8_t* codes, int64_t rb, + const avxp::JPlane& sc, const avxp::JPlane& zp, int64_t group, int64_t n0, int64_t n1, + int64_t m0, int64_t e1, int64_t e2, const RadTensor* Y, int64_t ys_r, int64_t ys_c) { +#if AVX_LEVEL == 3 + using V = __m512; + using VI = __m512i; +#else + using V = __m256; + using VI = __m256i; +#endif + constexpr int64_t kNB = 16; + alignas(64) V accb[kNB][MB * U]; + for (int64_t r = 0; r < n1 - n0; ++r) + for (int i = 0; i < MB * U; ++i) accb[r][i] = (V){}; + const int64_t kc = group * (group >= 512 ? 1 : 512 / group); + const float* a0 = af + m0 * lda + (n0 < e1 ? 0 : n0 < e2 ? 1 : 2) * K; + for (int64_t c0 = 0; c0 < K; c0 += kc) { + const int64_t c1 = c0 + kc < K ? c0 + kc : K; + for (int64_t n = n0; n < n1; n += NR) { + const int nr = n + NR <= n1 ? NR : 1; + const uint8_t* cr[NR]; + V acc[NR][MB * U]; + for (int r = 0; r < NR; ++r) { + cr[r] = codes + (n + (r < nr ? r : 0)) * rb; + for (int i = 0; i < MB * U; ++i) acc[r][i] = accb[n - n0 + (r < nr ? r : 0)][i]; + } + for (int64_t g = c0 / group; g < c1 / group; ++g) { + VI vz[NR]; + V vs[NR]; + for (int r = 0; r < NR; ++r) { + const int64_t row = n + (r < nr ? r : 0); +#if AVX_LEVEL == 3 + vz[r] = _mm512_set1_epi32(zp_zero_at(zp, row, g)); + vs[r] = _mm512_set1_ps(zp_scale_at(sc, row, g)); +#else + vz[r] = _mm256_set1_epi32(zp_zero_at(zp, row, g)); + vs[r] = _mm256_set1_ps(zp_scale_at(sc, row, g)); +#endif + } + for (int64_t k0 = g * group; k0 < (g + 1) * group; k0 += 16 * U) + for (int u = 0; u < U; ++u) { + const int64_t k = k0 + 16 * u; +#if AVX_LEVEL == 3 + __m512 w[NR]; + for (int r = 0; r < NR; ++r) { + const __m128i b = zp_codes16(cr[r], k, k + 16 == K); + w[r] = _mm512_mul_ps(_mm512_cvtepi32_ps(_mm512_sub_epi32( + _mm512_cvtepu8_epi32(b), vz[r])), vs[r]); + } + for (int i = 0; i < MB; ++i) { + const __m512 a = _mm512_loadu_ps(a0 + i * lda + k); + for (int r = 0; r < NR; ++r) + acc[r][i * U + u] = _mm512_fmadd_ps(a, w[r], acc[r][i * U + u]); + } +#else + __m256 w0[NR], w1[NR]; + for (int r = 0; r < NR; ++r) { + const __m128i b = zp_codes16(cr[r], k, k + 16 == K); + w0[r] = _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_sub_epi32( + _mm256_cvtepu8_epi32(b), vz[r])), vs[r]); + w1[r] = _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_sub_epi32( + _mm256_cvtepu8_epi32(_mm_srli_si128(b, 8)), + vz[r])), vs[r]); + } + for (int i = 0; i < MB; ++i) { + const __m256 a = _mm256_loadu_ps(a0 + i * lda + k); + const __m256 b8 = _mm256_loadu_ps(a0 + i * lda + k + 8); + for (int r = 0; r < NR; ++r) { + V& c = acc[r][i * U + u]; + c = _mm256_fmadd_ps(a, w0[r], c); + c = _mm256_fmadd_ps(b8, w1[r], c); + } + } +#endif + } + } + for (int r = 0; r < nr; ++r) + for (int i = 0; i < MB * U; ++i) accb[n - n0 + r][i] = acc[r][i]; + } + } + for (int64_t n = n0; n < n1; ++n) + for (int i = 0; i < MB; ++i) { + V a = accb[n - n0][i * U]; + for (int u = 1; u < U; ++u) a = a + accb[n - n0][i * U + u]; +#if AVX_LEVEL == 3 + const float v = _mm512_reduce_add_ps(a); +#else + __m128 h = _mm_add_ps(_mm256_castps256_ps128(a), _mm256_extractf128_ps(a, 1)); + h = _mm_add_ps(h, _mm_movehl_ps(h, h)); + h = _mm_add_ss(h, _mm_movehdup_ps(h)); + const float v = _mm_cvtss_f32(h); +#endif + stt(Y, (m0 + i) * ys_r + n * ys_c, v); + } +} + +/* y over the rows of every part; false when the path does not apply (no BMI2, M over 16, a group + * that is not whole 64s, codes other than u4 / u5). `af` is the activation as f32 [M, lda]. */ +static bool zp_small_f16(int bits, const float* af, int64_t lda, const uint8_t* codes, int64_t rb, + const avxp::JPlane& sc, const avxp::JPlane& zp, int64_t group, + int64_t e1, int64_t e2, const RadTensor* Y, int64_t M, int64_t N, + int64_t K) { + static const bool bmi2 = __builtin_cpu_supports("bmi2"); + if (!bmi2 || M > 16 || group % 64 || K % group || (bits != 4 && bits != 5)) return false; + using Fn = void (*)(const float*, int64_t, int64_t, const uint8_t*, int64_t, + const avxp::JPlane&, const avxp::JPlane&, int64_t, int64_t, int64_t, + int64_t, int64_t, int64_t, const RadTensor*, int64_t, int64_t); +#if AVX_LEVEL == 3 + constexpr int kNR = 2; +#else + constexpr int kNR = 1; +#endif + static const Fn kFn[2][4] = { + { zp_rows_f16<1, 4, 4, 1>, zp_rows_f16<2, 4, 2, 1>, zp_rows_f16<4, 4, 1, kNR>, + zp_rows_f16<8, 4, 1, kNR> }, + { zp_rows_f16<1, 5, 4, 1>, zp_rows_f16<2, 5, 2, 1>, zp_rows_f16<4, 5, 1, kNR>, + zp_rows_f16<8, 5, 1, kNR> }, + }; + const Fn* fn = kFn[bits == 5 ? 1 : 0]; + const int64_t ys_r = row_stride(Y, N), ys_c = laststride(Y); + const int64_t NB = 16, nblk = (N + NB - 1) / NB; + AVX_PARALLEL_FOR_IF(M * N * K >= 65536) + for (int64_t b = 0; b < nblk; ++b) { + const int64_t n0 = b * NB, n1 = n0 + NB < N ? n0 + NB : N; + for (int64_t m0 = 0; m0 < M;) { + const int64_t left = M - m0; + const int lv = left >= 8 ? 3 : left >= 4 ? 2 : left >= 2 ? 1 : 0; + fn[lv](af, lda, K, codes, rb, sc, zp, group, n0, n1, m0, e1, e2, Y, ys_r, ys_c); + m0 += (int64_t)1 << lv; + } + } + return true; +} +#endif + +/* gemm_nt_q over a zero-point grid (avx_planes.h: ZpGrid), with libref's checks and refusals + * (libref/ref_gemm.cpp: gemm_zp). Each part of the weight is one plain product over decoded rows + * (ZpDec), against an f32 activation that carries what the grid scales by: + * + * ZP_F16 the activation as it is; the rows are (code - zero) * scale + * ZP_I8_GROUP code * a_scale[m][g], against (code - zero) * scale + * ZP_I8_ROW code * a_scale[m] with a_sum[g][m] * a_scale[m] after each group, against + * code * scale and -zero * scale after each group + * + * so every output is a sum over k of a'(k) * w'(k) in one group, which the driver blocks over M + * and N. `a` arrives in column order (the caller undoes the step order). */ +static int gemm_zp(const avxp::ZpGrid& zg, const RadTensor* A, const RadTensor* as_, + const RadTensor* B, const RadTensor* bs_, const RadTensor* asum, + const RadTensor* Y, int64_t M, int64_t N, int64_t K, int64_t group, + int64_t pb1, int64_t pb2) { + using namespace avxp; + if (!is_joined(bs_)) return RAD_E_DTYPE; + const JPlane sc = jplane(bs_, "scale"), zp = jplane(bs_, "zero"); + if (!sc || !zp || !float_scale_dt(sc.dt) || !zero_dt(zp.dt)) return RAD_E_DTYPE; + if (B->dtype != zg.codes) return RAD_E_DTYPE; + if (group <= 0 || K % group) return RAD_E_SHAPE; + const int64_t G = K / group; + if (sc.rows != N || sc.cols != G || zp.rows != N || zp.cols != G) return RAD_E_SHAPE; + if (!rad_tensor_is_contiguous(B)) return RAD_E_STRIDE; + + const bool parted = pb1 > 0 || pb2 > 0; + if (parted && zg.act == ZP_I8_ROW) return RAD_E_UNSUPPORTED; + const int64_t e1 = pb1 > 0 ? std::min(pb1, N) : N; + const int64_t e2 = pb2 > 0 ? std::max(e1, std::min(pb2, N)) : N; + const int64_t parts = e2 < N ? 3 : (e1 < N ? 2 : 1); + if (parted && ((e1 % 16) || (e2 % 16))) return RAD_E_SHAPE; + const int64_t acols = parts * K; + if (numel(A) < M * acols) return RAD_E_SHAPE; + if (A->rank >= 2 && A->shape[A->rank - 1] != acols) return RAD_E_SHAPE; + const int64_t ars = row_stride(A, acols), acs = laststride(A); + + const bool i8 = zg.act != ZP_F16; + if (i8 && A->dtype != RAD_I8) return RAD_E_DTYPE; + if (!i8 && !float_scale_dt(A->dtype)) return RAD_E_DTYPE; + const int64_t mpad = (M + 15) / 16 * 16; + if (zg.act == ZP_I8_ROW) { + if (!as_ || numel(as_) < M) return RAD_E_INVAL; + if (!asum || numel(asum) < G * mpad) return RAD_E_INVAL; + } + if (zg.act == ZP_I8_GROUP && (!as_ || numel(as_) < M * parts * G)) return RAD_E_INVAL; + const int64_t sa_rs = as_ ? row_stride(as_, zg.act == ZP_I8_GROUP ? parts * G : 1) : 0; + const int64_t sa_cs = as_ ? laststride(as_) : 0; + const int64_t ys = row_stride(Y, N), yc = laststride(Y); + const bool aug = zg.act == ZP_I8_ROW; + const int64_t Kw = aug ? G * (group + 1) : K; +#if AVX_LEVEL >= 2 + if (zg.act == ZP_F16 && acs == 1 && M <= 16) { + static thread_local std::vector afv; + afv.resize((size_t)(M * acols)); + for (int64_t m = 0; m < M; ++m) + row_to_f32(A->dtype, (const uint8_t*)A->data + rad_dtype_bytes(A->dtype, m * ars), + afv.data() + m * acols, acols); + if (zp_small_f16(rad_dtype_bits(B->dtype), afv.data(), acols, (const uint8_t*)B->data, + rad_enc_row_bytes(B->dtype, K), sc, zp, group, e1, e2, Y, M, N, K)) + return RAD_OK; + } + if (aug && acs == 1) { + static thread_local std::vector sav; + sav.resize((size_t)M); + for (int64_t m = 0; m < M; ++m) sav[(size_t)m] = ldt(as_, m * sa_rs); + if (zp_small_i8(rad_dtype_bits(B->dtype), (const int8_t*)A->data, ars, sav.data(), asum, + mpad, (const uint8_t*)B->data, rad_enc_row_bytes(B->dtype, K), sc, zp, + group, Y, M, N, K)) + return RAD_OK; + } +#endif + + /* The int8-activation grids on the bf16 grouped driver (avx_gemm_tile.cpp): code - zero and + * the int8 codes are exact in bf16, so each group's sub-sum is libref's exact integer, then + * (sub * a_scale) * scale. One job a part, each part against its own copy of the activation; + * where a part is declined, the decoded driver below computes all of Y. */ + if (zg.act == ZP_I8_GROUP && acs == 1 && zp.dt == RAD_U8 && + rad_enc_row_bytes(B->dtype, K) * 8 == K * rad_dtype_bits(B->dtype)) { + RadTensor ct{}, st{}; + ct.data = B->data; ct.dtype = B->dtype; ct.rank = 2; + ct.shape[0] = N; ct.shape[1] = K; ct.stride[0] = K; ct.stride[1] = 1; + const int64_t ses = rad_dtype_bits(sc.dt) / 8; + st.data = (void*)sc.p; st.dtype = sc.dt; st.rank = 2; + st.shape[0] = N; st.shape[1] = G; st.stride[0] = sc.row_bytes / ses; st.stride[1] = 1; + const Scales SBz = make_scales(&st, N, K, false); + const int64_t bound[4] = { 0, e1, e2, N }; + bool ok = true; + for (int p = 0; p < 3 && ok; ++p) { + const int64_t n0 = bound[p], n1 = bound[p + 1]; + if (n1 <= n0) continue; + RadTensor Ap = *A, Sp = *as_; + Ap.data = (uint8_t*)A->data + p * K * acs; + Ap.rank = 2; Ap.shape[0] = M; Ap.shape[1] = K; Ap.stride[0] = ars; Ap.stride[1] = 1; + Sp.data = (uint8_t*)as_->data + rad_dtype_bytes(as_->dtype, p * G * sa_cs); + Sp.rank = 2; Sp.shape[0] = M; Sp.shape[1] = G; Sp.stride[0] = sa_rs; + Sp.stride[1] = sa_cs; + const Scales SAz = make_scales(&Sp, M, K, false); + TileJob jb{}; + jb.mb = as_mat(&ct, K); + jb.SB = SBz; + jb.b0 = n0; jb.a0 = 0; jb.M = M; jb.N = n1 - n0; jb.K = K; + jb.y0 = 0; jb.yc0 = n0; + jb.zero = zp; + ok = gemm_q_bf16_jobs(as_mat(&Ap, K), nullptr, M, &SAz, &jb, 1, Y, N); + } + if (ok) return RAD_OK; + } + + ZpDec dec; + dec.codes_p = (const uint8_t*)B->data; + dec.rb = rad_enc_row_bytes(B->dtype, K); + dec.K = K; + dec.group = group; + dec.bits = rad_dtype_bits(B->dtype); + dec.aug = aug; + dec.sc = sc; + dec.zp = zp; + + static thread_local std::vector aw; + const int64_t bound[4] = { 0, e1, e2, N }; + for (int p = 0; p < 3; ++p) { + const int64_t n0 = bound[p], n1 = bound[p + 1]; + if (n1 <= n0) continue; + dec.n0 = n0; + RadTensor Ap{}, Yp = *Y; + Yp.data = (uint8_t*)Y->data + rad_dtype_bytes(Y->dtype, n0 * yc); + Yp.rank = 2; Yp.shape[0] = M; Yp.shape[1] = n1 - n0; Yp.stride[0] = ys; Yp.stride[1] = yc; + if (i8) { + /* The scaled activation, f32 [M, Kw], which the driver reads in place. */ + aw.resize((size_t)(M * Kw)); + const int8_t* ar = (const int8_t*)A->data; + for (int64_t m = 0; m < M; ++m) { + float* d = aw.data() + m * Kw; + const int64_t ab = m * ars + p * K * acs; + for (int64_t g = 0; g < G; ++g) { + const float sa = zg.act == ZP_I8_ROW + ? ldt(as_, m * sa_rs) + : ldt(as_, m * sa_rs + (p * G + g) * sa_cs); + float* dg = d + g * (aug ? group + 1 : group); + for (int64_t k = 0; k < group; ++k) + dg[k] = (float)ar[ab + (g * group + k) * acs] * sa; + if (aug) dg[group] = ldt(asum, (g * mpad + m) * laststride(asum)) * sa; + } + } + Ap.data = aw.data(); + Ap.dtype = RAD_F32; + Ap.rank = 2; Ap.shape[0] = M; Ap.shape[1] = Kw; Ap.stride[0] = Kw; Ap.stride[1] = 1; + } else { + Ap = *A; + Ap.data = (uint8_t*)A->data + rad_dtype_bytes(A->dtype, p * K * acs); + Ap.rank = 2; Ap.shape[0] = M; Ap.shape[1] = K; Ap.stride[0] = ars; Ap.stride[1] = acs; + } + const Mat mb{ B, Kw, 1, &dec }; + const int rc = gemm_drive(as_mat(&Ap, Kw), mb, nullptr, nullptr, &Yp, nullptr, M, + n1 - n0, Kw); + if (rc != RAD_OK) return rc; + } + return RAD_OK; +} + static int gemm_ntq_impl(const RadArgs* a, bool bias_operand) { const int nt = bias_operand ? 6 : 5; if (a->n_t < nt || !a->t[0].data || !a->t[2].data || !a->t[nt - 1].data) return RAD_E_INVAL; @@ -754,10 +971,14 @@ static int gemm_ntq_impl(const RadArgs* a, bool bias_operand) { const RadTensor* as_ = rad_arg_in(a, 1); const RadTensor* bs_ = rad_arg_in(a, 3); const RadTensor* bias = bias_operand ? rad_arg_in(a, 4) : nullptr; - - /* `pb1`/`pb2` split the weight's rows into parts that meet separate copies of the activation - * (ParoQuant); this driver reads one. Refused rather than computed against the wrong copy. */ - if (p_int(a, "pb1", 0) || p_int(a, "pb2", 0)) return RAD_E_UNSUPPORTED; + /* libref's refusals (ref_gemm.cpp): the zero-point grids have no bias form, `a_sum` belongs + * to the grids that remove a zero through it, `b_ref` to an e2m1 weight. */ + const avxp::ZpGrid* zg = avxp::zp_grid(p_str(a, "dtype", nullptr)); + if (zg && bias_operand) return RAD_E_UNSUPPORTED; + if (!bias_operand) { + if (rad_arg_in(a, 5) && (!zg || zg->act != avxp::ZP_I8_ROW)) return RAD_E_UNSUPPORTED; + if (rad_arg_in(a, 6) && B->dtype != RAD_FP4E2M1) return RAD_E_UNSUPPORTED; + } const int64_t K = p_int(a, "K", B->rank >= 2 ? B->shape[B->rank - 1] : 0); const int64_t N = p_int(a, "N", B->rank >= 2 ? B->shape[B->rank - 2] : 0); @@ -767,17 +988,49 @@ static int gemm_ntq_impl(const RadArgs* a, bool bias_operand) { if (numel(A) < M * K || numel(B) < N * K) return RAD_E_SHAPE; if (bias && numel(bias) < N) return RAD_E_SHAPE; + /* quant_act_i8's codes arrive with the middle two dwords of every 16-byte step exchanged; + * exchange them back into a contiguous copy. */ + RadTensor Ac; + if (A->dtype == RAD_I8 && i8_steps_dtype(p_str(a, "dtype", nullptr))) { + if (K % 16) return RAD_E_SHAPE; + if (!dense_row(A)) return RAD_E_STRIDE; + static thread_local std::vector cols; + cols.resize((size_t)(M * K)); + for (int64_t m = 0; m < M; ++m) { + const int8_t* row = (const int8_t*)A->data + rowoff(A, m, K); + int8_t* dst = cols.data() + m * K; + for (int64_t k = 0; k < K; k += 16) { + std::memcpy(dst + k, row + k, 4); + std::memcpy(dst + k + 4, row + k + 8, 4); + std::memcpy(dst + k + 8, row + k + 4, 4); + std::memcpy(dst + k + 12, row + k + 12, 4); + } + } + Ac = *A; + Ac.data = cols.data(); + Ac.rank = 2; Ac.shape[0] = M; Ac.shape[1] = K; Ac.stride[0] = K; Ac.stride[1] = 1; + A = &Ac; + } + + const int64_t pb1 = p_int(a, "pb1", 0), pb2 = p_int(a, "pb2", 0); + if (zg) + return gemm_zp(*zg, A, as_, B, bs_, rad_arg_in(a, 5), Y, M, N, K, p_int(a, "group", 0), + pb1, pb2); + if (pb1 > 0 || pb2 > 0) { + if (bias_operand) return RAD_E_UNSUPPORTED; + return gemm_ntq_parts(A, as_, B, bs_, Y, pb1, pb2, M, N, K); + } + const bool mx = B->dtype == RAD_FP4E2M1; Scales SA = make_scales(as_, M, K, false); Scales SB = make_scales(bs_, N, K, mx); - /* `group` is what the SELECTOR matches on; the loop uses the group the scale stream actually - * implies. They agree in every well-formed call, and where they do not the stream is the one - * that describes the bytes -- so a disagreement is refused rather than silently resolved. */ + /* `group` is what the selector matches on; the loop uses the group the scale stream implies. + * A disagreement is refused. */ const int64_t gp = p_int(a, "group", 0); if (gp > 0 && SB.p && SB.group != gp) return RAD_E_SHAPE; const Mat ma = as_mat(A, K), mb = as_mat(B, K); - return gemm_drive(ma, mb, &SA, &SB, Y, bias, M, N, K); + return gemm_q_drive(ma, mb, &SA, &SB, Y, bias, M, N, K); } AVX_KERNEL(gemm_nt) { return gemm_nt_impl(a, false, "N", "K"); } @@ -786,19 +1039,16 @@ AVX_KERNEL(gemm_nt_q) { return gemm_ntq_impl(a, false); } AVX_KERNEL(gemm_nt_q_bias) { return gemm_ntq_impl(a, true); } /* ------------------------------------------------------------------ gemm_nt_q_gated */ -/* gemm_nt_q over a [N, K] gate_up plane -- N is the WEIGHT's rows, twice the fused width, gate half - * first -- with gated_quant_fp8 as the epilogue; the output is [M, N/2]. +/* gemm_nt_q over an [N, K] gate_up weight (N is twice the fused width, gate half first), with + * gated_quant_fp8 as the epilogue; output [M, N/2]. * - * BYTE-IDENTICAL TO THE PAIR IT STANDS FOR, gemm_nt_q into a bf16 [M, N] tensor and then - * gated_quant_fp8 over it. The product is gemm_drive's, the same driver at the same blocking; both - * halves are narrowed to bf16 by the ABI's own converter, which is what gemm_nt_q's element store - * does to a bf16 output; and the gate and the codes are avx_had.h's, which gated_quant_fp8 runs. - * Taking either half off the f32 accumulator instead would be a different function. + * Byte-identical to gemm_nt_q into a bf16 [M, N] tensor followed by gated_quant_fp8: same driver + * and blocking, both halves narrowed to bf16 with the ABI's converter (as gemm_nt_q's bf16 store + * does), then avx_had.h's gate and codes. * - * The f32 plane between the two is materialised whole, in a buffer the calling thread keeps: the - * driver parallelises over the plane's columns, and the epilogue over its rows. `act` is REQUIRED - * here where the quantiser defaults it -- an implementation may compile one gate, and a default - * would let it resolve for the other. */ + * The f32 plane between the two is materialised whole in a thread-kept buffer, since the driver + * parallelises over columns and the epilogue over rows. `act` is required here (the quantiser + * defaults it) so an implementation that compiles one gate cannot match a call for the other. */ AVX_KERNEL(gemm_nt_q_gated) { if (a->n_t < 6) return RAD_E_INVAL; const RadTensor *A = &a->t[0], *B = &a->t[2], *q = &a->t[4], *s = &a->t[5]; @@ -835,7 +1085,7 @@ AVX_KERNEL(gemm_nt_q_gated) { Y.rank = 2; Y.shape[0] = M; Y.shape[1] = N; Y.stride[0] = N; Y.stride[1] = 1; - const int rc = gemm_drive(ma, mb, &SA, &SB, &Y, nullptr, M, N, K); + const int rc = gemm_q_drive(ma, mb, &SA, &SB, &Y, nullptr, M, N, K); if (rc != RAD_OK) return rc; const float* P = plane.data(); @@ -851,25 +1101,39 @@ AVX_KERNEL(gemm_nt_q_gated) { return RAD_OK; } -/* The same arithmetic as gemm_nt, and a separate op anyway: lm_head is its own access class - * (RAD_ACCESS_VOCAB) and the sampler wants to fuse against it, so the two have to be selectable - * apart even when one kernel serves both. N and K are spelled n_vocab and n_embd. */ +/* gemm_nt's arithmetic as a separate op: lm_head has its own access class (RAD_ACCESS_VOCAB) and + * the sampler fuses against it, so the two must be selectable apart. N and K are n_vocab and + * n_embd. */ AVX_KERNEL(logits_gemm) { return gemm_nt_impl(a, false, "n_vocab", "n_embd"); } +/* gemm_nt's product for this plugin's composite kernels (the image convolution, avx_gen.cpp), over + * operands they assembled: Y = A B^T + bias, f32 accumulation, one rounding. Runs on the calling + * thread's team like gemm_nt and uses the same scratch arenas, so a caller keeps its own buffers + * elsewhere. */ +namespace avx { +inline namespace AVX_SUFFIX { +int gemm_nt_into(const RadTensor* A, const RadTensor* B, const RadTensor* bias, const RadTensor* Y, + int64_t M, int64_t N, int64_t K) { + const Mat ma = as_mat(A, K), mb = as_mat(B, K); + if (gemm_q_bf16(ma, mb, nullptr, nullptr, Y, bias, M, N, K)) return RAD_OK; + return gemm_drive(ma, mb, nullptr, nullptr, Y, bias, M, N, K); +} +} /* inline namespace AVX_SUFFIX */ +} /* namespace avx */ + /* ================================================================== the vocabulary edges * - * A gather, not a GEMM. A NEGATIVE token id writes a ZERO ROW -- the padding convention a batch - * with a short sequence needs. `vocab_offset` makes the table this rank's slice of a vocab-parallel - * embedding: ids stay GLOBAL, one outside the slice writes a zero row, and summing the ranks - * reconstructs x. + * Embedding gather. A negative token id writes a zero row (padding). `vocab_offset` makes the table + * this rank's slice of a vocab-parallel embedding: ids stay global, ids outside the slice write + * zero rows, and summing the ranks reconstructs x. * - * WITHOUT AN OFFSET AN ID AT OR ABOVE n_vocab STILL FAILS THE LAUNCH, because there it is a caller - * bug rather than another rank's token and a plausible embedding is the worst possible answer. - * With one, this kernel cannot know the global vocabulary, so the bound is the caller's. */ + * When this rank holds the whole vocabulary, an id >= n_vocab fails the launch (a caller bug). + * Under a split, rank 0 included, the kernel cannot know the global vocabulary, so bounds are the + * caller's responsibility. */ template static int embed_impl(const RadArgs* a) { const int nt = QUANT ? 4 : 3; - /* embed_lookup_q's scale (operand 2) is optional; everything else must be there. */ + /* embed_lookup_q's scale (operand 2) is optional; the rest are required. */ for (int i = 0; i < nt; ++i) if (!(QUANT && i == 2) && !rad_arg_in(a, i)) return RAD_E_INVAL; const RadTensor* tok = &a->t[0]; @@ -882,29 +1146,28 @@ static int embed_impl(const RadArgs* a) { if (n_embd <= 0 || n_vocab <= 0 || voff < 0) return RAD_E_SHAPE; const int64_t M = numel(x) / n_embd; if (M <= 0 || numel(tok) < M || numel(wte) < n_vocab * n_embd) return RAD_E_SHAPE; - /* An absent scale is one (ref_embed_lookup_q says why the op allows it). embed_lookup's - * `mult` is the same multiply, a parameter instead of a table scale. */ + /* An absent scale is 1 (see ref_embed_lookup_q). embed_lookup's `mult` is the same multiply + * as a parameter. */ const float scale = QUANT ? (sc->data && numel(sc) >= 1 ? ldt(sc, 0) : 1.0f) : p_f32(a, "mult", 1.0f); - /* Validated before the loop, because an OpenMP body cannot return. */ - if (voff == 0) + /* Validated before the loop; an OpenMP body cannot return. */ + if (voff == 0 && a->world_size <= 1) for (int64_t m = 0; m < M; ++m) if (ldi(tok, offlin(tok, m)) >= n_vocab) return RAD_E_INVAL; const int64_t ws = wte->rank >= 2 ? wte->stride[wte->rank - 2] : n_embd; const int64_t wc = wte->rank >= 2 ? wte->stride[wte->rank - 1] : 1; - /* A ROW COPY WHEN NOTHING HAS TO CHANGE, which for the unquantised gather is the usual case: - * the table and the activation are the same dtype and a memcpy moves the row at the width of - * the machine instead of through an f32 round trip that would also re-round it. */ + /* Byte copy when nothing changes (same dtype, no scale), the usual case for the unquantised + * gather. Whole-byte dtypes only: a sub-byte row can start mid-byte. */ const bool copy = !QUANT && scale == 1.0f && wte->dtype == x->dtype && wc == 1 && - laststride(x) == 1; + laststride(x) == 1 && rad_dtype_bits(x->dtype) % 8 == 0; const size_t rowb = copy ? (size_t)((rad_dtype_bits(x->dtype) * n_embd) / 8) : 0; AVX_PARALLEL_FOR_IF(M * n_embd >= AVX_PAR_MIN) for (int64_t m = 0; m < M; ++m) { const int64_t id = ldi(tok, offlin(tok, m)) - voff; - const int64_t xb = rowoff(x, m, n_embd), xs = laststride(x); + const int64_t xb = rowoff(x, m, n_embd); const bool have_row = id >= 0 && id < n_vocab; if (copy) { void* dst = (void*)byte_at(x->data, x->dtype, xb); @@ -927,8 +1190,7 @@ static int embed_impl(const RadArgs* a) { for (int64_t i = 0; i < n_embd; ++i) s[i] = ld_elem(wte->data, wte->dtype, id * ws + i * wc) * scale; } - if (xs == 1) out_row(x, xb, n_embd, s); - else for (int64_t i = 0; i < n_embd; ++i) stt(x, xb + i * xs, s[i]); + out_row(x, xb, n_embd, s); } return RAD_OK; } @@ -937,20 +1199,17 @@ AVX_KERNEL(embed_lookup) { return embed_impl(a); } /* ================================================================== the E4M3 table into bf16 * - * The form a model serves -- an E4M3 table, a bf16 activation -- is a gather whose rows are usually - * not in memory, and avx_ngram.cpp is where they come from: a row cache shared by every thread, a - * direct read for each miss, a reader a step ahead. What stays here is the part that is this - * level's: turning a row of codes into bf16 through the call's 256-entry table. + * The served form (E4M3 table, bf16 activation) gathers rows that are usually not in memory; they + * are fetched by avx_ngram.cpp (shared row cache, direct reads for misses, a reader one step + * ahead). This level only decodes a row of codes to bf16 through the call's 256-entry table. * - * AT AVX-512 THE TABLE LIVES IN EIGHT REGISTERS. 256 bf16 are 512 bytes; vpermt2w indexes 64 words - * across a register pair, so four of them look every code up in its quarter and the code's top two - * bits pick the quarter -- a dozen instructions for 32 codes, against 32 dependent loads. Below - * AVX-512 the table has no in-register form (vpshufb indexes 16 bytes and a gather issues one load - * a lane, the null result in README.md), so those levels look a code up at a time. + * At AVX-512 the table (256 bf16, 512 bytes) lives in eight registers. vpermt2w indexes 64 words + * across a register pair, so four of them look up each code in its quarter and the code's top two + * bits select the quarter: about a dozen instructions per 32 codes. Lower levels have no + * in-register form (vpshufb indexes 16 bytes; a gather is one load per lane, see README.md) and + * look up one code at a time. * - * EVERY ROW IS A CACHE MISS, so each row's lines are requested kAhead rows before its decode: - * a batch is thousands of rows scattered over the row cache, and a decode that waited for each - * row's lines in turn would spend its time on the memory latency rather than the lookups. */ + * Every row is a cache miss, so each row's lines are prefetched kAhead rows before its decode. */ static void decode_e4m3_rows(const uint8_t* const* src, uint16_t* const* dst, int64_t count, int64_t n, const uint16_t* lut) { constexpr int64_t kAhead = 8; @@ -994,17 +1253,16 @@ static void decode_e4m3_rows(const uint8_t* const* src, uint16_t* const* dst, in } } -/* A bf16 table's rows ARE their output: the decode is a copy, and the row cache in front of it is - * the whole of the work, as it is for the E4M3 table. */ +/* A bf16 table's rows are the output: the decode is a copy. */ static void decode_bf16_rows(const uint8_t* const* src, uint16_t* const* dst, int64_t count, int64_t n, const uint16_t*) { for (int64_t r = 0; r < count; ++r) std::memcpy(dst[r], src[r], (size_t)n * sizeof(uint16_t)); } -/* The call in avx_ngram.cpp's form, or false: i32 ids, a dense E4M3 table with its scale or a - * dense bf16 table without one, bf16 rows at one pitch. */ +/* Fills `g` for avx_ngram.cpp's gather, or returns false: i32 ids, a dense E4M3 table with a + * scale or a dense bf16 table without, bf16 output rows at one pitch. */ static bool rows_form(const RadArgs* a, RowGather* g) { - /* The scale is optional, so it is not part of what must be present. */ + /* The scale (operand 2) is optional. */ if (!rad_arg_in(a, 0) || !rad_arg_in(a, 1) || !rad_arg_in(a, 3)) return false; const RadTensor* tok = &a->t[0]; const RadTensor* wte = &a->t[1]; @@ -1047,10 +1305,9 @@ AVX_KERNEL(embed_lookup_q) { if (!rows_form(a, &g)) return embed_impl(a); if (g.voff < 0 || g.M <= 0 || numel(&a->t[0]) < g.M || numel(&a->t[1]) < g.n_vocab * g.n_embd) return RAD_E_SHAPE; - /* Checked before the gather, not inside it: a refusal halfway through would leave the output - * half written and the step would carry on over it. The bound is embed_impl's -- with an offset - * an id outside this rank's slice is another rank's row and writes a zero one. */ - if (g.voff == 0) + /* Checked before the gather so a refusal never leaves the output half written. Same bound + * as embed_impl. */ + if (g.voff == 0 && g.world_size <= 1) for (int64_t m = 0; m < g.M; ++m) if ((int64_t)g.ids[m] >= g.n_vocab) return RAD_E_INVAL; return row_gather(g, g.row_bytes == g.n_embd ? decode_e4m3_rows : decode_bf16_rows); diff --git a/libavx/avx_gemm.h b/libavx/avx_gemm.h new file mode 100644 index 00000000..a1062947 --- /dev/null +++ b/libavx/avx_gemm.h @@ -0,0 +1,207 @@ +/* avx_gemm.h -- how the GEMM family reads its operands, and the two large-M drivers. + * + * Shared by avx_gemm.cpp (the ops, the decode-shaped driver) and avx_gemm_tile.cpp (the tile + * drivers). Compiled once per ISA level like every kernel source, so everything here lives in the + * level's inline namespace (avx_vec.h): the four objects never share a definition. + * + * The readings are copied from libref/ref_gemm.h and must match it: where an operand's (row, col) + * lives, and which scale covers it. Note `row_stride` (avx_common.h): a rank-3 [tokens, heads, + * width] activation read as [tokens, heads*width] has its row stride on the tokens axis, not + * stride[rank-2]. + */ +#ifndef RAD_AVX_GEMM_H +#define RAD_AVX_GEMM_H + +#include "avx_vec.h" +#include "avx_common.h" +#include "avx_planes.h" + +namespace avx { +inline namespace AVX_SUFFIX { + +/* A weight whose rows are produced by a decoder instead of read as stored: codes and their scales + * joined (avx_planes.h), widened to f32 with the scales folded in. Called from parallel regions; + * an implementation only writes `dst`. + * + * row the whole row, `K` columns + * cols columns [k0, k1) into dst[0, k1 - k0); k0 is a multiple of align(), and k1 is too or + * is the row's end */ +struct RowDecoder { + virtual void row(int64_t r, float* dst) const = 0; + virtual void cols(int64_t r, int64_t k0, int64_t k1, float* dst) const = 0; + virtual int64_t align() const = 0; + /* The stored bytes cols(r, k0, k1) reads first (the codes), for a prefetch ahead of it. */ + virtual void codes(int64_t r, int64_t k0, int64_t k1, const void** p, int64_t* bytes) const = 0; +}; + +struct Mat { + const RadTensor* t; + int64_t rs, cs; + const RowDecoder* dec = nullptr; +}; + +static inline Mat as_mat(const RadTensor* t, int64_t cols) { + Mat m{ t, cols, 1 }; + if (t->rank < 2) return m; + m.cs = t->stride[t->rank - 1]; + m.rs = row_stride(t, cols); + return m; +} + +/* n E8M0 exponents as f32, rad_e8m0_to_f32's values: e << 23, with 0 the subnormal 2^-127 and + * 0xFF a NaN. */ +static inline void e8m0_to_f32(const uint8_t* src, float* dst, int64_t n) { + int64_t i = 0; +#if AVX_LEVEL == 3 + for (; i + 16 <= n; i += 16) { + const __m512i e = _mm512_cvtepu8_epi32(_mm_loadu_si128((const __m128i*)(src + i))); + __m512i u = _mm512_slli_epi32(e, 23); + u = _mm512_mask_mov_epi32(u, _mm512_cmpeq_epi32_mask(e, _mm512_setzero_si512()), + _mm512_set1_epi32(0x00400000)); + u = _mm512_mask_mov_epi32(u, _mm512_cmpeq_epi32_mask(e, _mm512_set1_epi32(0xff)), + _mm512_set1_epi32(0x7fc00000)); + _mm512_storeu_si512((void*)(dst + i), u); + } +#elif AVX_LEVEL == 2 + for (; i + 8 <= n; i += 8) { + const __m256i e = _mm256_cvtepu8_epi32(_mm_loadl_epi64((const __m128i*)(src + i))); + __m256i u = _mm256_slli_epi32(e, 23); + u = _mm256_blendv_epi8(u, _mm256_set1_epi32(0x00400000), + _mm256_cmpeq_epi32(e, _mm256_setzero_si256())); + u = _mm256_blendv_epi8(u, _mm256_set1_epi32(0x7fc00000), + _mm256_cmpeq_epi32(e, _mm256_set1_epi32(0xff))); + _mm256_storeu_si256((__m256i*)(dst + i), u); + } +#endif + for (; i < n; ++i) dst[i] = rad_e8m0_to_f32(src[i]); +} + +/* A quantised operand's scale stream, as defined in libref/ref_gemm.h. `rblk` makes a + * DeepSeek-style [ceil(N/128)][ceil(K/128)] block grid readable: without it a 17408-row weight's + * 136-row scale plane would be read as 17408 rows. MXFP4 weights may carry e8m0 (u8) scales. */ +struct Scales { + const void* p; + uint32_t dt; + int64_t rs, cs, group, rblk; + bool e8m0; + inline float grp(int64_t row, int64_t g) const { + const int64_t i = (rblk > 1 ? row / rblk : row) * rs + g * cs; + if (e8m0) { + const uint8_t e = ((const uint8_t*)p)[i]; + return e == 0xff ? std::nanf("") : std::ldexp(1.0f, (int)e - 127); + } + return rad_load_f32(p, dt, i); + } + /* Groups [g0, g0 + n) of `row` into dst, the same values grp() returns, with the dtype + * resolved once rather than per scale. */ + inline void row_groups(int64_t row, int64_t g0, int64_t n, float* dst) const { + const int64_t base = (rblk > 1 ? row / rblk : row) * rs + g0 * cs; + const uint8_t* b = (const uint8_t*)p; + if (cs == 1) { + switch (e8m0 ? (uint32_t)RAD_E8M0 : dt) { + case RAD_E8M0: e8m0_to_f32(b + base, dst, n); return; + case RAD_BF16: cvt_bf16_to_f32((const uint16_t*)p + base, dst, n); return; + case RAD_F16: cvt_f16_to_f32((const uint16_t*)p + base, dst, n); return; + case RAD_F32: std::memcpy(dst, (const float*)p + base, (size_t)n * 4); return; + default: break; + } + } + if (e8m0 || dt == RAD_E8M0) { + for (int64_t g = 0; g < n; ++g) dst[g] = rad_e8m0_to_f32(b[base + g * cs]); + } else if (dt == RAD_BF16) { + for (int64_t g = 0; g < n; ++g) + dst[g] = rad_bf16_to_f32(((const uint16_t*)p)[base + g * cs]); + } else if (dt == RAD_F16) { + for (int64_t g = 0; g < n; ++g) + dst[g] = rad_f16_to_f32(((const uint16_t*)p)[base + g * cs]); + } else if (dt == RAD_F32) { + for (int64_t g = 0; g < n; ++g) dst[g] = ((const float*)p)[base + g * cs]; + } else { + for (int64_t g = 0; g < n; ++g) dst[g] = rad_load_f32(p, dt, base + g * cs); + } + } +}; + +static inline Scales make_scales(const RadTensor* s, int64_t rows, int64_t K, bool mxfp4_weight) { + Scales q{}; + q.rblk = 1; + if (!s || !s->data || rows <= 0 || numel(s) <= 0) { + q.p = nullptr; q.group = K; q.dt = RAD_F32; return q; + } + q.p = s->data; + q.dt = s->dtype; + /* As libref: a rank-2 stream with fewer rows than the operand is a block grid, and a flat + * stream shorter than the row count is one scale per block of rows. */ + int64_t groups = 0; + if (s->rank >= 2) { + const int64_t srows = s->shape[s->rank - 2]; + q.rblk = srows >= rows ? 1 : grid_block(rows, srows); + groups = s->shape[s->rank - 1]; + q.rs = s->stride[s->rank - 2]; + q.cs = s->stride[s->rank - 1]; + } else { + const int64_t nel = numel(s); + if (nel >= rows) { groups = nel / rows; q.rs = groups; } + else { groups = 1; q.rblk = grid_block(rows, nel); q.rs = 1; } + q.cs = 1; + } + q.group = grid_block(K, groups); + q.e8m0 = mxfp4_weight && (s->dtype == RAD_U8); + return q; +} + +/* Columns [k0, k0 + n) of row r of a plain operand as raw f32 codes: the row converter where the + * columns are contiguous and start on a byte, element by element otherwise. */ +static inline void widen_cols(const Mat& m, int64_t r, int64_t k0, int64_t n, float* dst) { + const RadTensor* t = m.t; + const int64_t base = r * m.rs + k0 * m.cs; + if (m.cs == 1) { + const int sub = (t->dtype == RAD_I4 || t->dtype == RAD_FP4E2M1) ? 1 + : (t->dtype == RAD_I2) ? 3 : 0; + if (!sub || (base & sub) == 0) { + row_to_f32(t->dtype, byte_at(t->data, t->dtype, base), dst, n); + return; + } + } + for (int64_t k = 0; k < n; ++k) dst[k] = ld_elem(t->data, t->dtype, base + k * m.cs); +} + +/* ================================================================== the tile drivers + * (avx_gemm_tile.cpp). Y = A B^T (+ bias), the product gemm_drive forms, at any M. Each returns + * false when it does not apply, and the caller then computes all of Y another way. + * + * gemm_q_bf16 AVX512_BF16 parts: weight codes exact in bf16 (E4M3, int8, int4, e2m1) against + * an E4M3, int8 or bf16 activation; the group structure kept, as libref's + * gemm_tile_f32 any operands, both scales folded into the f32 operands (it may have written Y + * when it returns false: an E8M0 scale it cannot fold is found as it runs) + * + * SA must be coarse (no finer than the weight's group); gemm_drive takes the other case first. */ +bool gemm_q_bf16(const Mat& ma, const Mat& mb, const Scales* SA, const Scales* SB, + const RadTensor* Y, const RadTensor* bias, int64_t M, int64_t N, int64_t K); +bool gemm_tile_f32(const Mat& ma, const Mat& mb, const Scales* SA, const Scales* SB, + const RadTensor* Y, const RadTensor* bias, int64_t M, int64_t N, int64_t K); + +/* A batch of independent products in one parallel region, as a grouped GEMM's experts are. Job j + * computes Y[y0 + i][yc0 + c] = sum_k A[a0 + i][k] * B[b0 + c][k] (+ bias[c]) for i < M, c < N, + * k < K: rows of one batch activation, columns of its own weight. Batch row r is A's row + * arow[r] (or r with no map), and a negative entry a zero row. Every job's weight is the same + * format at the same group (SB.p null: unscaled); SA scales A's rows as libref's Scales. `ycols` + * is Y's logical width, which sets its row pitch. With `zero` (a zero-point grid's u8 plane, one + * per row and group of SB) the weight is (code - zero) * scale over u4 or u5 codes, which only the + * bf16 grouped driver takes. */ +struct TileJob { + Mat mb; + Scales SB; + int64_t b0, a0, M, N, K, y0, yc0; + const RadTensor* bias; + avxp::JPlane zero; +}; +bool gemm_q_bf16_jobs(const Mat& ma, const int64_t* arow, int64_t arows, const Scales* SA, + const TileJob* jobs, int64_t njobs, const RadTensor* Y, int64_t ycols); +bool gemm_tile_f32_jobs(const Mat& ma, const int64_t* arow, int64_t arows, const Scales* SA, + const TileJob* jobs, int64_t njobs, const RadTensor* Y, int64_t ycols); + +} /* inline namespace AVX_SUFFIX */ +} /* namespace avx */ + +#endif /* RAD_AVX_GEMM_H */ diff --git a/libavx/avx_gemm_tile.cpp b/libavx/avx_gemm_tile.cpp new file mode 100644 index 00000000..e8a4bfa1 --- /dev/null +++ b/libavx/avx_gemm_tile.cpp @@ -0,0 +1,1108 @@ +/* avx_gemm_tile.cpp -- the GEMM's tile drivers: an M x N tile loop over packed column panels. + * + * avx_gemm.cpp's register-blocked dot-product driver forks a parallel region per L2-sized block of + * A rows and widens every weight row again in each, so at prefill B is streamed from DRAM once per + * 6-16 rows of A. These drivers serve every M, one batch of products (avx_gemm.h: TileJob) a + * parallel region: a dense product is one job per super-block of A rows (sized to stay in the L3), + * a grouped GEMM one job per expert and part. + * + * convert the batch's A rows once, in parallel + * parallel over tasks = (job, column panel or group of panels, row sub-block), dynamically + * for each K chunk (the packed panel chunk sized for the L2) + * pack the chunk: the panel's weight rows decoded and transposed to k-major order + * run the microkernel over every MR rows of the sub-block, into the task's C tile + * store the C tile (+ bias) + * + * At decode the same loop reads each weight row once, as a few long runs (the chunk is longer + * where few rows share a panel, and the next rows are prefetched), and stays at the DRAM read + * stream's rate for the byte-wide codes. + * + * The microkernels are outer products: per k, a broadcast of each A row against vectors of panel + * columns, every lane one output, no horizontal reduction. + * + * gemm_q_bf16 AVX512_BF16 parts, weight codes exact in bf16 (E4M3, int8, int4, e2m1) against + * an E4M3, int8 or bf16 activation, which every quantised dense format here is. + * Codes are packed as bf16 pairs ([k pair][48 columns][2], vdpbf16ps's operand + * layout), and each scale group's sub-sum of raw codes is accumulated by + * vdpbf16ps in f32 (products of two such codes are exact), then scaled once, + * (sub * sa) * sb, as libref's quant_dot does. Plain bf16 weights take the same + * path unscaled. 8 rows x 48 columns. + * gemm_tile_f32 every level and operand pair: A widened to f32 with its scale folded in, the + * panel likewise (a weight code times its scale is exact in f32 for every format + * here), one f32 FMA per element. 8 x 48 at AVX-512, 6 x 16 at AVX2; with eight + * rows or fewer, dot products against the untransposed rows instead. + * + * An output's arithmetic does not depend on the blocking: a row's lane in the outer product is + * the same whichever rows share its microkernel call, groups lie whole in a chunk, and the f32 + * chain runs over k in order through the C tile. So results do not depend on the team (avx_common.h's + * threading rule) or on the chunk length. + */ +#include "avx_gemm.h" + +#include +#include +#include +#include + +namespace avx { +inline namespace AVX_SUFFIX { + +namespace { + +static int tile_team() { +#ifdef _OPENMP + return avx_team_size(); +#else + return 1; +#endif +} + +/* A super-block's tasks: `pg` panels by `sub` rows each. With at most eight panels and 64 rows + * or more a task takes all the panels, iterated inside each K chunk, so its rows of A for a chunk + * come into its L2 once rather than once per panel on other cores (a 144-channel convolution has + * three); its sub-block is then at most 128 rows, which keeps that chunk of A, a panel's chunk and + * the C tiles in the L2. More panels already give enough tasks one panel each, and fewer rows + * (decode) take one a task for parallelism. The row sub-blocks give eight tasks per thread where + * the panel groups are fewer, none shorter than 64 rows (a task packs its own panel chunks) and + * none longer than 512. `rows` is a multiple of `mr` except in the last super-block. */ +static void tile_split(int64_t rows, int64_t np, int64_t mr, int nth, int64_t* sub, + int64_t* nsub, int64_t* pg) { + *pg = rows >= 64 && np <= 8 ? np : 1; + const int64_t ngr = (np + *pg - 1) / *pg; + int64_t ns = 1; + const int64_t want = 8 * (int64_t)nth; + if (ngr < want) ns = (want + ngr - 1) / ngr; + const int64_t most = std::max(1, rows / 64); + if (ns > most) ns = most; + const int64_t cap = *pg > 1 ? 128 : 512; + ns = std::max(ns, (rows + cap - 1) / cap); + int64_t s = (rows + ns - 1) / ns; + s = (s + mr - 1) / mr * mr; + *sub = s; + *nsub = (rows + s - 1) / s; +} + +/* Columns [n0, n0 + w) of Y's row m from the f32 accumulators `c`, plus `bias` (w values, or null), + * rounded once into Y's dtype by the row converter (bit-exact with the ABI's), element by element + * where the row is strided or its dtype narrower than a byte. */ +static void tile_store(const RadTensor* Y, int64_t ys_r, int64_t ys_c, int64_t m, int64_t n0, + int64_t w, const float* c, const float* bias, float* tmp) { + const float* v = c; + if (bias) { + for (int64_t j = 0; j < w; ++j) tmp[j] = c[j] + bias[j]; + v = tmp; + } + const int64_t off = m * ys_r + n0 * ys_c; + if (ys_c == 1 && rad_dtype_bits(Y->dtype) >= 8) { + row_from_f32(Y->dtype, v, (void*)byte_at(Y->data, Y->dtype, off), w); + return; + } + for (int64_t j = 0; j < w; ++j) stt(Y, off + j * ys_c, v[j]); +} + +/* Bias values of columns [n0, n0 + w), zero past N; false when there is no bias. */ +static bool tile_bias(const RadTensor* bias, int64_t n0, int64_t w, int64_t N, float* dst) { + if (!bias) return false; + const int64_t bs = laststride(bias); + for (int64_t j = 0; j < w; ++j) dst[j] = n0 + j < N ? ldt(bias, (n0 + j) * bs) : 0.0f; + return true; +} + +#ifdef _OPENMP +/* The task loop's schedule, set for the calling thread's next region and restored after. One + * product of few rows is a stream of B in uniform tasks, split statically so a thread takes + * contiguous panels: the rows of B a static loop over them wrote (a convolution's patches, as y^T) + * are then in its own core complex's L3. Otherwise tasks are handed out one at a time. */ +struct TileSchedule { + omp_sched_t kind; + int chunk; + explicit TileSchedule(int64_t njobs, int64_t rows) { + omp_get_schedule(&kind, &chunk); + if (njobs == 1 && rows <= 32) omp_set_schedule(omp_sched_static, 0); + else omp_set_schedule(omp_sched_dynamic, 1); + } + ~TileSchedule() { omp_set_schedule(kind, chunk); } +}; +#endif + +/* The lines of [p, p + bytes), requested ahead of their read: the panel's weight rows are short + * runs at a row's pitch, too short for the hardware's stream detection to cover. */ +static inline void tile_prefetch(const void* p, int64_t bytes) { + const uintptr_t a = (uintptr_t)p, e = a + (uintptr_t)bytes; + for (uintptr_t q = a & ~(uintptr_t)63; q < e; q += 64) __builtin_prefetch((const void*)q, 0, 3); +} + +} /* namespace */ + +/* ================================================================== the bf16 grouped driver */ +#if AVX_LEVEL == 3 +#define AVX_QB_TARGET __attribute__((target("avx512f,avx512bw,avx512vl,avx512bf16"))) + +namespace { + +constexpr int64_t QB_COLS = 48; /* panel columns: three zmm of f32 accumulators */ +constexpr int64_t QB_MR = 8; /* rows of A per microkernel call */ +/* K chunk, in codes. Where few rows share a panel the weight rows stream from DRAM, and a long + * chunk keeps each row one sequential read (8192: a 768 KiB panel); with many rows the chunk is + * sized for the L2 (2048: 192 KiB). */ +constexpr int64_t QB_KC_FEW = 8192, QB_KC = 2048, QB_FEW_ROWS = 32; + +/* bf16 bit patterns of every code of the four weight formats and the two activation formats + * that are not bf16 already. Each value has at most eight significant bits, so the top half of + * its f32 pattern is the value exactly. */ +struct QbLut { + alignas(64) uint16_t e4m3[256]; + alignas(64) uint16_t i8[256]; + alignas(64) uint16_t i4[32]; + alignas(64) uint16_t e2m1[32]; +}; + +static uint16_t qb_hi(float f) { + uint32_t u; + std::memcpy(&u, &f, 4); + return (uint16_t)(u >> 16); +} + +static const QbLut& qb_lut() { + static const QbLut L = [] { + QbLut l{}; + static const float kMag[8] = { 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f }; + for (int c = 0; c < 256; ++c) { + l.e4m3[c] = qb_hi(rad_fp8e4m3_to_f32((uint8_t)c)); + l.i8[c] = qb_hi((float)(int8_t)c); + } + for (int c = 0; c < 32; ++c) { + const int n = c & 15; + l.i4[c] = qb_hi((float)((n ^ 8) - 8)); + l.e2m1[c] = qb_hi((n & 8) ? -kMag[n & 7] : kMag[n & 7]); + } + return l; + }(); + return L; +} + +/* A code format's table, loaded once per task: eight registers for a byte code (vpermt2w looks + * up 64 words across a pair, the top two bits pick the pair), one for a nibble. */ +struct QbTab { + __m512i t[8]; + bool nib; + bool copy; /* the codes are bf16 already */ +}; + +AVX_QB_TARGET static QbTab qb_tab(uint32_t dt) { + const QbLut& L = qb_lut(); + QbTab q{}; + q.copy = dt == RAD_BF16; + if (q.copy) return q; + const uint16_t* src = dt == RAD_F8E4M3 ? L.e4m3 : dt == RAD_I8 ? L.i8 + : dt == RAD_I4 ? L.i4 : L.e2m1; + q.nib = dt == RAD_I4 || dt == RAD_FP4E2M1; + for (int k = 0; k < (q.nib ? 1 : 8); ++k) + q.t[k] = _mm512_loadu_si512((const void*)(src + 32 * k)); + return q; +} + +AVX_QB_TARGET static inline __m512i qb_pick(const QbTab& q, __m512i ix) { + if (q.nib) return _mm512_permutexvar_epi16(ix, q.t[0]); + const __m512i q0 = _mm512_permutex2var_epi16(q.t[0], ix, q.t[1]); + const __m512i q1 = _mm512_permutex2var_epi16(q.t[2], ix, q.t[3]); + const __m512i q2 = _mm512_permutex2var_epi16(q.t[4], ix, q.t[5]); + const __m512i q3 = _mm512_permutex2var_epi16(q.t[6], ix, q.t[7]); + const __mmask32 h6 = _mm512_test_epi16_mask(ix, _mm512_set1_epi16(0x40)); + const __mmask32 h7 = _mm512_test_epi16_mask(ix, _mm512_set1_epi16(0x80)); + return _mm512_mask_blend_epi16(h7, _mm512_mask_blend_epi16(h6, q0, q1), + _mm512_mask_blend_epi16(h6, q2, q3)); +} + +/* `n` codes from `src` (the byte holding the first) as bf16 into dst[0, npad), npad a multiple of + * 32, the words past n zero. Zero is not code 0 in every format (int4's 0 is -8), so the padding + * is applied to the values. With `ex`, each 32 codes are multiplied by the E8M0 scale ex[i / 32] + * through their exponents: exact for an exponent byte in [2, 252] (qb_foldable), and 0xFF makes + * them all NaN, as the scale's product would. */ +AVX_QB_TARGET static void qb_codes(const QbTab& q, const uint8_t* src, int64_t n, int64_t npad, + uint16_t* dst, const uint8_t* ex = nullptr) { + for (int64_t i = 0; i < npad; i += 32) { + const int64_t left = n - i; + const __mmask32 keep = left >= 32 ? ~(__mmask32)0 + : left <= 0 ? (__mmask32)0 : (__mmask32)((1u << left) - 1u); + if (q.copy) { + _mm512_storeu_si512((void*)(dst + i), + _mm512_maskz_loadu_epi16(keep, (const uint16_t*)src + i)); + continue; + } + __m256i x; + if (!q.nib) { + x = left >= 32 ? _mm256_loadu_si256((const __m256i*)(src + i)) + : _mm256_maskz_loadu_epi8(keep, src + i); + } else { + const int64_t nb = left >= 32 ? 16 : left <= 0 ? 0 : (left + 1) / 2; + const __m128i b = _mm_maskz_loadu_epi8((__mmask16)((1u << nb) - 1u), src + i / 2); + const __m128i m4 = _mm_set1_epi8(0x0f); + const __m128i lo = _mm_and_si128(b, m4); + const __m128i hi = _mm_and_si128(_mm_srli_epi16(b, 4), m4); + x = _mm256_set_m128i(_mm_unpackhi_epi8(lo, hi), _mm_unpacklo_epi8(lo, hi)); + } + __m512i v = qb_pick(q, _mm512_cvtepu8_epi16(x)); + if (ex) { + const int e = ex[i / 32]; + if (e == 0xff) { + v = _mm512_set1_epi16(0x7fc0); + } else { + const __mmask32 nz = _mm512_test_epi16_mask(v, _mm512_set1_epi16(0x7fff)); + v = _mm512_mask_add_epi16(v, nz, v, _mm512_set1_epi16((short)((e - 127) * 128))); + } + } + _mm512_storeu_si512((void*)(dst + i), _mm512_maskz_mov_epi16(keep, v)); + } +} + +/* `n` codes of `bits` (4 or 5) of a zero-point grid, from `row` (the byte holding the chunk's + * first code), as code - zero in bf16 into dst[0, npad), the words past n zero. zr[j] is the zero + * of the j-th 32 codes. A code minus its zero lies in [-31, 31], exact in bf16: `t` holds bf16(i - + * 32) for i < 64, which one vpermt2w indexes by code - zero + 32. u5 codes are 40 bits for each + * eight, deposited into bytes by pdep (BMI2, which the caller checked). */ +AVX_QB_TARGET __attribute__((target("bmi2"))) static void qb_codes_zp( + const uint8_t* row, int bits, int64_t n, int64_t npad, uint16_t* dst, const int32_t* zr, + const __m512i* t) { + for (int64_t i = 0; i < npad; i += 32) { + const int64_t left = n - i; + const __mmask32 keep = left >= 32 ? ~(__mmask32)0 + : left <= 0 ? (__mmask32)0 : (__mmask32)((1u << left) - 1u); + __m256i x; + if (bits == 4) { + const int64_t nb = left >= 32 ? 16 : left <= 0 ? 0 : (left + 1) / 2; + const __m128i b = _mm_maskz_loadu_epi8((__mmask16)((1u << nb) - 1u), row + i / 2); + const __m128i m4 = _mm_set1_epi8(0x0f); + const __m128i lo = _mm_and_si128(b, m4); + const __m128i hi = _mm_and_si128(_mm_srli_epi16(b, 4), m4); + x = _mm256_set_m128i(_mm_unpackhi_epi8(lo, hi), _mm_unpacklo_epi8(lo, hi)); + } else { + /* Four runs of eight codes, 5 bytes each; only the bytes the row holds are read. */ + const int64_t nb = left >= 32 ? 20 : left <= 0 ? 0 : (left * 5 + 7) / 8; + alignas(8) uint8_t buf[24] = {}; + std::memcpy(buf, row + i / 8 * 5, (size_t)nb); + const unsigned long long kLow5 = 0x1f1f1f1f1f1f1f1full; + uint64_t q[4]; + for (int r = 0; r < 4; ++r) { + uint64_t v = 0; + std::memcpy(&v, buf + 5 * r, 8); + q[r] = _pdep_u64(v & 0xffffffffffull, kLow5); + } + x = _mm256_set_epi64x((long long)q[3], (long long)q[2], (long long)q[1], + (long long)q[0]); + } + const __m512i ix = _mm512_add_epi16(_mm512_cvtepu8_epi16(x), + _mm512_set1_epi16((short)(32 - zr[i / 32]))); + const __m512i v = _mm512_permutex2var_epi16(t[0], ix, t[1]); + _mm512_storeu_si512((void*)(dst + i), _mm512_maskz_mov_epi16(keep, v)); + } +} + +/* E8M0 exponents whose products with every e2m1 code (0.5 to 6 in magnitude) are bf16 normals, + * or the NaN. */ +static inline bool qb_foldable(const uint8_t* ex, int64_t n) { + for (int64_t i = 0; i < n; ++i) + if ((ex[i] < 2 || ex[i] > 252) && ex[i] != 0xff) return false; + return true; +} + +/* r[j] <- column j of the 16 x 16 matrix of 32-bit elements whose row i is r[i]. */ +AVX_QB_TARGET static inline void tr16(__m512i r[16]) { + __m512i t[16], u[16], v[16]; + for (int i = 0; i < 8; ++i) { + t[2 * i] = _mm512_unpacklo_epi32(r[2 * i], r[2 * i + 1]); + t[2 * i + 1] = _mm512_unpackhi_epi32(r[2 * i], r[2 * i + 1]); + } + /* u[4q + c], 128-bit lane L: column 4L + c of rows 4q .. 4q + 3. */ + for (int q = 0; q < 4; ++q) { + u[4 * q + 0] = _mm512_unpacklo_epi64(t[4 * q], t[4 * q + 2]); + u[4 * q + 1] = _mm512_unpackhi_epi64(t[4 * q], t[4 * q + 2]); + u[4 * q + 2] = _mm512_unpacklo_epi64(t[4 * q + 1], t[4 * q + 3]); + u[4 * q + 3] = _mm512_unpackhi_epi64(t[4 * q + 1], t[4 * q + 3]); + } + for (int c = 0; c < 4; ++c) { + v[c] = _mm512_shuffle_i32x4(u[c], u[4 + c], 0x88); + v[4 + c] = _mm512_shuffle_i32x4(u[c], u[4 + c], 0xdd); + v[8 + c] = _mm512_shuffle_i32x4(u[8 + c], u[12 + c], 0x88); + v[12 + c] = _mm512_shuffle_i32x4(u[8 + c], u[12 + c], 0xdd); + } + for (int c = 0; c < 4; ++c) { + r[c] = _mm512_shuffle_i32x4(v[c], v[8 + c], 0x88); + r[8 + c] = _mm512_shuffle_i32x4(v[c], v[8 + c], 0xdd); + r[4 + c] = _mm512_shuffle_i32x4(v[4 + c], v[12 + c], 0x88); + r[12 + c] = _mm512_shuffle_i32x4(v[4 + c], v[12 + c], 0xdd); + } +} + +/* MR rows of A against a packed chunk: per group, the sub-sums of 48 columns over its k pairs, + * then C += (sub * sa) * sb. `A` is the rows' bf16 at the chunk's first column, `P` the chunk's + * pairs [kp][48], `S` its scales [group][48], `gk` each group's k pairs, `sa` the rows' + * activation scales of the chunk's groups (row i, group g at sa[i * sald + g * sastep]). */ +template +AVX_QB_TARGET static void qb_kernel(const uint16_t* A, int64_t lda, const uint32_t* P, + const float* S, const int64_t* gk, int64_t ng, const float* sa, + int64_t sald, int64_t sastep, float* C) { + const uint16_t* a = A; + const uint32_t* p = P; + for (int64_t gi = 0; gi < ng; ++gi) { + __m512 acc[MR][3]; +#pragma GCC unroll 8 + for (int i = 0; i < MR; ++i) + acc[i][0] = acc[i][1] = acc[i][2] = _mm512_setzero_ps(); + for (int64_t kp = 0; kp < gk[gi]; ++kp, p += QB_COLS, a += 2) { + const __m512bh b0 = (__m512bh)_mm512_load_si512((const void*)p); + const __m512bh b1 = (__m512bh)_mm512_load_si512((const void*)(p + 16)); + const __m512bh b2 = (__m512bh)_mm512_load_si512((const void*)(p + 32)); +#pragma GCC unroll 8 + for (int i = 0; i < MR; ++i) { + uint32_t pr; + std::memcpy(&pr, a + i * lda, 4); + const __m512bh av = (__m512bh)_mm512_set1_epi32((int)pr); + acc[i][0] = _mm512_dpbf16_ps(acc[i][0], av, b0); + acc[i][1] = _mm512_dpbf16_ps(acc[i][1], av, b1); + acc[i][2] = _mm512_dpbf16_ps(acc[i][2], av, b2); + } + } + const __m512 s0 = _mm512_loadu_ps(S + gi * QB_COLS); + const __m512 s1 = _mm512_loadu_ps(S + gi * QB_COLS + 16); + const __m512 s2 = _mm512_loadu_ps(S + gi * QB_COLS + 32); +#pragma GCC unroll 8 + for (int i = 0; i < MR; ++i) { + const __m512 sv = _mm512_set1_ps(sa[i * sald + gi * sastep]); + float* c = C + i * QB_COLS; + _mm512_storeu_ps(c, _mm512_fmadd_ps(_mm512_mul_ps(acc[i][0], sv), s0, + _mm512_loadu_ps(c))); + _mm512_storeu_ps(c + 16, _mm512_fmadd_ps(_mm512_mul_ps(acc[i][1], sv), s1, + _mm512_loadu_ps(c + 16))); + _mm512_storeu_ps(c + 32, _mm512_fmadd_ps(_mm512_mul_ps(acc[i][2], sv), s2, + _mm512_loadu_ps(c + 32))); + } + } +} + +using QbKernel = void (*)(const uint16_t*, int64_t, const uint32_t*, const float*, + const int64_t*, int64_t, const float*, int64_t, int64_t, float*); +static const QbKernel kQbKernel[QB_MR + 1] = { + nullptr, qb_kernel<1>, qb_kernel<2>, qb_kernel<3>, qb_kernel<4>, + qb_kernel<5>, qb_kernel<6>, qb_kernel<7>, qb_kernel<8>, +}; + +/* The activation formats whose codes this path reads as bf16, and the weight formats. */ +static bool qb_act(uint32_t dt) { return dt == RAD_BF16 || dt == RAD_F8E4M3 || dt == RAD_I8; } +static bool qb_weight(uint32_t dt) { + return dt == RAD_F8E4M3 || dt == RAD_I8 || dt == RAD_I4 || dt == RAD_FP4E2M1 || + dt == RAD_BF16; +} + +} /* namespace */ + +/* A job's task layout, fixed before the parallel region. */ +struct QbPlan { + int64_t np, sub, nsub, pg, ngr, t0, KC; +}; + +/* The batch (avx_gemm.h: TileJob) on the bf16 grouped driver. Batch row r is A's row arow[r], or + * abase + r unmapped; `ycols` is Y's logical width, for its row pitch. */ +AVX_QB_TARGET static bool qb_core(const Mat& ma, int64_t abase, const int64_t* arow, int64_t arows, + const Scales* SA, const TileJob* jobs, int64_t njobs, + const RadTensor* Y, int64_t ycols) { + if (njobs <= 0) return true; + if (ma.dec || arows <= 0) return false; + const uint32_t adt = ma.t->dtype, bdt = jobs[0].mb.t->dtype; + const bool zpw = jobs[0].zero.p != nullptr; + const int zbits = bdt == RAD_U4 ? 4 : bdt == RAD_U5 ? 5 : 0; + static const bool bmi2 = __builtin_cpu_supports("bmi2"); + if (zpw && (!zbits || (zbits == 5 && !bmi2))) return false; + if (!qb_act(adt) || (!zpw && !qb_weight(bdt)) || ma.cs != 1) return false; + if (Y->dtype != RAD_BF16 && Y->dtype != RAD_F32) return false; + const int64_t ys_r = row_stride(Y, ycols), ys_c = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1; + if (ys_c != 1) return false; + const bool nib = bdt == RAD_I4 || bdt == RAD_FP4E2M1; + const bool sb_on = jobs[0].SB.p != nullptr; + int64_t Kmax = 0; + bool even = true; + for (int64_t j = 0; j < njobs; ++j) { + const TileJob& jb = jobs[j]; + if (jb.mb.dec || jb.mb.t->dtype != bdt || jb.mb.cs != 1 || (nib && (jb.mb.rs & 1))) + return false; + if ((jb.SB.p != nullptr) != sb_on || (sb_on && jb.SB.group != jobs[0].SB.group)) + return false; + /* A zero-point job: whole-byte rows of codes, a u8 zero per (row, scale group), groups of + * whole 32s. */ + if ((jb.zero.p != nullptr) != zpw) return false; + if (zpw && (!sb_on || jb.zero.dt != RAD_U8 || (jb.mb.rs * zbits) % 8 || + jb.SB.group % 32 || jb.SB.rblk > 1)) + return false; + Kmax = std::max(Kmax, jb.K); + even = even && !(jb.K & 1); + } + const bool sa_on = SA && SA->p; + /* Unscaled (bf16 x bf16), the group is only where a sub-sum joins the C tile: a chunk. */ + const int64_t G = sb_on && jobs[0].SB.group > 0 ? jobs[0].SB.group + : (!sa_on && Kmax > QB_KC) ? QB_KC : Kmax; + const int64_t ngrp = (Kmax + G - 1) / G; + /* Pairs must not straddle a group: every group but the last is even. */ + if (ngrp > 1 && (G & 1)) return false; + if (sa_on && SA->group < G) return false; + /* MXFP4's E8M0 scales fold into the packed codes (qb_codes), chunk by chunk where every scale + * of the chunk allows it; the sub-sums then run over the activation's group (Gf), four of + * the weight's, and close the vdpbf16ps chain a quarter as often. */ + const bool e8 = jobs[0].SB.e8m0 || jobs[0].SB.dt == RAD_E8M0; + const int64_t Gf = sa_on ? SA->group : 0; + const bool fold = bdt == RAD_FP4E2M1 && sb_on && e8 && jobs[0].SB.cs == 1 && G == 32 && + (!sa_on || (Gf % G == 0 && QB_KC % Gf == 0)); + + const int nth = tile_team(); + std::vector plan((size_t)njobs); + int64_t tasks = 0, sub_max = 0, KC_max = 0, work = 0; + for (int64_t j = 0; j < njobs; ++j) { + const TileJob& jb = jobs[j]; + QbPlan& pl = plan[(size_t)j]; + const int64_t kc_want = jb.M <= QB_FEW_ROWS ? QB_KC_FEW : QB_KC; + pl.KC = G >= kc_want ? G : kc_want / G * G; + pl.np = (jb.N + QB_COLS - 1) / QB_COLS; + tile_split(jb.M, pl.np, QB_MR, nth, &pl.sub, &pl.nsub, &pl.pg); + pl.ngr = (pl.np + pl.pg - 1) / pl.pg; + pl.t0 = tasks; + tasks += pl.ngr * pl.nsub; + sub_max = std::max(sub_max, pl.sub * pl.pg); + KC_max = std::max(KC_max, pl.KC); + work += jb.M * jb.N * jb.K; + } + /* sub_max is the rows of a task's C tiles, a sub-block's for each panel of its group. */ + const int64_t kpad_max = (KC_max + 31) / 32 * 32; + const int64_t ng_max = (KC_max + G - 1) / G; + if (zpw && KC_max > QB_KC_FEW) return false; + + /* A as bf16: read in place when it is bf16, unmapped, with every pair inside its row; else + * converted into rows of `lda`, zero past the width. */ + const bool in_place = adt == RAD_BF16 && !arow && even; + const int64_t lda = in_place ? ma.rs : (Kmax + 1) / 2 * 2; + const size_t a_bytes = in_place ? 0 : (size_t)(arows * lda) * sizeof(uint16_t); + const size_t sa_floats = (size_t)(arows * ngrp); + uint8_t* blk = (uint8_t*)scratch_raw(a_bytes + sa_floats * sizeof(float) + 128); + uint16_t* abuf = (uint16_t*)blk; + float* satab = (float*)(blk + (a_bytes + 63) / 64 * 64); + const uint16_t* Ab = in_place ? (const uint16_t*)ma.t->data + abase * ma.rs : abuf; + const QbTab qa = qb_tab(adt == RAD_BF16 ? (uint32_t)RAD_I8 : adt); + +#ifdef _OPENMP + const TileSchedule sched_scope(njobs, jobs[0].M); +#pragma omp parallel num_threads(nth) if(work >= 65536 || avx_par_forced()) +#endif + { +#ifdef _OPENMP +#pragma omp for schedule(static) +#endif + for (int64_t r = 0; r < arows; ++r) { + const int64_t m = arow ? arow[r] : abase + r; + float* sr = satab + r * ngrp; + for (int64_t g = 0; g < ngrp; ++g) + sr[g] = sa_on && m >= 0 ? SA->grp(m, (g * G) / SA->group) : 1.0f; + if (in_place) continue; + uint16_t* d = abuf + r * lda; + if (m < 0) { + std::memset(d, 0, (size_t)lda * 2); + continue; + } + const uint8_t* src = (const uint8_t*)byte_at(ma.t->data, adt, m * ma.rs); + if (adt == RAD_BF16) { + std::memcpy(d, src, (size_t)Kmax * 2); + for (int64_t k = Kmax; k < lda; ++k) d[k] = 0; + continue; + } + /* lda is even and qb_codes writes whole 32s, so the last block goes through a small + * buffer rather than past the row. */ + const int64_t full = lda / 32 * 32; + qb_codes(qa, src, std::min(Kmax, full), full, d); + if (full < lda) { + alignas(64) uint16_t tail[32]; + qb_codes(qa, src + full, Kmax - full, 32, tail); + std::memcpy(d + full, tail, (size_t)(lda - full) * 2); + } + } + +#ifdef _OPENMP +#pragma omp for schedule(runtime) +#endif + for (int64_t t = 0; t < tasks; ++t) { + int64_t ji = 0; + for (int64_t lo = 0, hi = njobs - 1; lo <= hi;) { + const int64_t mid = (lo + hi) / 2; + if (plan[(size_t)mid].t0 <= t) { ji = mid; lo = mid + 1; } else hi = mid - 1; + } + const TileJob& jb = jobs[ji]; + const QbPlan& pl = plan[(size_t)ji]; + const int64_t tl = t - pl.t0, N = jb.N, K = jb.K, KC = pl.KC, sub = pl.sub; + const int64_t s = tl / pl.ngr, pe = std::min(pl.np, (tl % pl.ngr) * pl.pg + pl.pg); + const int64_t r0 = s * sub, r1 = std::min(jb.M, r0 + sub); + const uint8_t* bbase = (const uint8_t*)jb.mb.t->data; + auto brow = [&](int64_t n, int64_t k0) { + if (zpw) return bbase + ((jb.b0 + n) * jb.mb.rs + k0) * zbits / 8; + return (const uint8_t*)byte_at(bbase, bdt, (jb.b0 + n) * jb.mb.rs + k0); + }; + /* Task buffers: the C tile, the packed chunk, its scales, the decoded rows of one + * 16-row block, the bias and the store's row, and the groups' k pairs. */ + const size_t f_c = (size_t)(sub_max * QB_COLS); + const size_t f_p = (size_t)((kpad_max / 2) * QB_COLS); + const size_t f_s = (size_t)(ng_max * QB_COLS); + const size_t f_t = (size_t)(16 * (kpad_max + 32) / 2); + const size_t f_g = (size_t)(2 * ng_max + 16); + float* C = scratch_f32(f_c + f_p + f_s + f_t + f_g + 2 * QB_COLS + 64); + uint32_t* P = (uint32_t*)(C + f_c); + float* S = C + f_c + f_p; + uint16_t* T = (uint16_t*)(S + f_s); + float* bv = S + f_s + f_t; + float* tmp = bv + QB_COLS; + int64_t* gk = (int64_t*)(((uintptr_t)(tmp + QB_COLS) + 7) & ~(uintptr_t)7); + const QbTab qb = qb_tab(zpw ? (uint32_t)RAD_I8 : bdt); + /* A zero-point grid's table, bf16(i - 32), and one row's zeros per 32 codes. */ + __m512i zt[2]; + int32_t zr[QB_KC_FEW / 32]; + if (zpw) + for (int h = 0; h < 2; ++h) { + alignas(64) uint16_t w[32]; + for (int j = 0; j < 32; ++j) w[j] = qb_hi((float)(32 * h + j - 32)); + zt[h] = _mm512_load_si512((const void*)w); + } + const int64_t p0 = (tl % pl.ngr) * pl.pg; + for (int64_t p = p0; p < pe; ++p) + std::memset(C + (p - p0) * sub * QB_COLS, 0, + (size_t)((r1 - r0) * QB_COLS) * sizeof(float)); + /* K chunks outermost and the group's panels within (tile_split). */ + for (int64_t k0 = 0; k0 < K; k0 += KC) { + for (int64_t p = p0; p < pe; ++p) { + const int64_t n0 = p * QB_COLS; + float* Cp = C + (p - p0) * sub * QB_COLS; + const int64_t k1 = std::min(K, k0 + KC), kc = k1 - k0; + const int64_t kpc = (kc + 1) / 2, kpad = (kc + 31) / 32 * 32; + /* The decoded rows' pitch, one line past the chunk: a power-of-two pitch + * puts the transpose's sixteen loads in one L1 set. */ + const int64_t tld = kpad + 32; + const int64_t g0 = k0 / G, ng = (k1 - k0 + G - 1) / G; + /* The chunk's scales fold into its codes when all of them can (one byte a + * group, the rows' own: rblk is 1 for MXFP4). */ + auto exps = [&](int64_t n) { + const Scales& S8 = jb.SB; + return (const uint8_t*)S8.p + + ((jb.b0 + n) / (S8.rblk > 1 ? S8.rblk : 1)) * S8.rs + g0; + }; + bool fc = fold; + for (int64_t c = 0; fc && c < QB_COLS && n0 + c < N; ++c) + fc = qb_foldable(exps(n0 + c), ng); + const int64_t gc = fc ? (sa_on ? Gf : kc) : G; + const int64_t ngc = (kc + gc - 1) / gc; + for (int64_t gi = 0; gi < ngc; ++gi) { + const int64_t a0 = k0 + gi * gc, a1 = std::min(k1, a0 + gc); + gk[gi] = (a1 - a0 + 1) / 2; + } + /* ---- the chunk's pairs, sixteen panel columns at a time */ + for (int64_t rb = 0; rb < QB_COLS; rb += 16) { + for (int64_t r = 0; r < 16; ++r) { + const int64_t n = n0 + rb + r; + uint16_t* tr = T + r * tld; + if (n + 4 < N && rb + r + 4 < QB_COLS) + tile_prefetch(brow(n + 4, k0), rad_dtype_bytes(bdt, kc)); + if (n < N && zpw) { + for (int64_t j = 0; j < kpad / 32; ++j) + zr[j] = jb.zero.p[(jb.b0 + n) * jb.zero.row_bytes + + (k0 + 32 * j) / G]; + qb_codes_zp(brow(n, k0), zbits, kc, kpad, tr, zr, zt); + } else if (n < N) { + qb_codes(qb, brow(n, k0), kc, kpad, tr, fc ? exps(n) : nullptr); + } else { + std::memset(tr, 0, (size_t)kpad * 2); + } + } + for (int64_t kb = 0; kb < kpad / 2; kb += 16) { + __m512i rr[16]; + for (int r = 0; r < 16; ++r) + rr[r] = _mm512_loadu_si512((const void*)(T + r * tld + 2 * kb)); + tr16(rr); + const int64_t lim = std::min(16, kpc - kb); + for (int64_t j = 0; j < lim; ++j) + _mm512_store_si512((void*)(P + (kb + j) * QB_COLS + rb), rr[j]); + } + } + /* ---- the chunk's weight scales, [group][column]: sixteen columns' rows of + * scales staged in T (free once the pairs are stored), then transposed; ones + * where they are folded. */ + const int64_t ngp = (ng + 15) / 16 * 16, sld = tld / 2; + float* SR = (float*)T; + if (fc) + for (int64_t i = 0; i < ngc * QB_COLS; ++i) S[i] = 1.0f; + for (int64_t rb = 0; !fc && rb < QB_COLS; rb += 16) { + for (int64_t r = 0; r < 16; ++r) { + const int64_t n = n0 + rb + r; + float* sr = SR + r * sld; + if (n < N && sb_on) jb.SB.row_groups(jb.b0 + n, g0, ng, sr); + else for (int64_t gi = 0; gi < ng; ++gi) sr[gi] = n < N ? 1.0f : 0.0f; + for (int64_t gi = ng; gi < ngp; ++gi) sr[gi] = 0.0f; + } + for (int64_t gb = 0; gb < ngp; gb += 16) { + __m512i rr[16]; + for (int r = 0; r < 16; ++r) + rr[r] = _mm512_loadu_si512((const void*)(SR + r * sld + gb)); + tr16(rr); + const int64_t lim = std::min(16, ng - gb); + for (int64_t j = 0; j < lim; ++j) + _mm512_storeu_si512((void*)(S + (gb + j) * QB_COLS + rb), rr[j]); + } + } + /* ---- every MR rows of the sub-block */ + for (int64_t m0 = r0; m0 < r1; m0 += QB_MR) { + const int64_t mm = std::min(QB_MR, r1 - m0), ar = jb.a0 + m0; + kQbKernel[mm](Ab + ar * lda + k0, lda, P, S, gk, ngc, + satab + ar * ngrp + g0, ngrp, gc / G, Cp + (m0 - r0) * QB_COLS); + } + } + } + for (int64_t p = p0; p < pe; ++p) { + const int64_t n0 = p * QB_COLS, cols = std::min(QB_COLS, N - n0); + const float* Cp = C + (p - p0) * sub * QB_COLS; + const bool hb = tile_bias(jb.bias, n0, cols, N, bv); + for (int64_t m = r0; m < r1; ++m) + tile_store(Y, ys_r, 1, jb.y0 + m, jb.yc0 + n0, cols, Cp + (m - r0) * QB_COLS, + hb ? bv : nullptr, tmp); + } + } + } + return true; +} + +/* One product as a batch of one job per super-block of A rows: a super-block's rows stay in the + * L3 (16 MiB), and a call has few super-blocks, since each is a parallel region of its own. */ +AVX_QB_TARGET static bool qb_run(const Mat& ma, const Mat& mb, const Scales* SA, const Scales* SB, + const RadTensor* Y, const RadTensor* bias, int64_t M, int64_t N, + int64_t K) { + const bool in_place = ma.t->dtype == RAD_BF16 && !(K & 1); + const int64_t lda = in_place ? ma.rs : (K + 1) / 2 * 2; + int64_t mcb = (int64_t)(16 << 20) / (2 * std::max(lda, 1)); + mcb = std::max(64, std::min(mcb, 8192)) / QB_MR * QB_MR; + if (mcb > M) mcb = M; + for (int64_t mb0 = 0; mb0 < M; mb0 += mcb) { + TileJob jb{}; + jb.mb = mb; + if (SB) jb.SB = *SB; + jb.a0 = 0; jb.M = std::min(mcb, M - mb0); jb.N = N; jb.K = K; + jb.y0 = mb0; jb.yc0 = 0; jb.bias = bias; + if (!qb_core(ma, mb0, nullptr, jb.M, SA, &jb, 1, Y, N)) return false; + } + return true; +} + +/* Entered only where the CPU has AVX512_BF16; the target-specific bodies are functions of their + * own, since a declaration and definition that differ in `target` would be two versions. */ +bool gemm_q_bf16(const Mat& ma, const Mat& mb, const Scales* SA, const Scales* SB, + const RadTensor* Y, const RadTensor* bias, int64_t M, int64_t N, int64_t K) { + static const bool have = __builtin_cpu_supports("avx512bf16"); + if (!have) return false; + return qb_run(ma, mb, SA, SB, Y, bias, M, N, K); +} + +bool gemm_q_bf16_jobs(const Mat& ma, const int64_t* arow, int64_t arows, const Scales* SA, + const TileJob* jobs, int64_t njobs, const RadTensor* Y, int64_t ycols) { + static const bool have = __builtin_cpu_supports("avx512bf16"); + if (!have) return false; + return qb_core(ma, 0, arow, arows, SA, jobs, njobs, Y, ycols); +} + +#else +bool gemm_q_bf16(const Mat&, const Mat&, const Scales*, const Scales*, const RadTensor*, + const RadTensor*, int64_t, int64_t, int64_t) { + return false; +} +bool gemm_q_bf16_jobs(const Mat&, const int64_t*, int64_t, const Scales*, const TileJob*, int64_t, + const RadTensor*, int64_t) { + return false; +} +#endif + +/* ================================================================== the f32 driver */ +namespace { + +/* Register block: MR rows by NV vectors of columns. AVX-512: 24 accumulators, three panel loads + * and eight broadcasts per k. AVX2: the 6 x 16 block of 12 accumulators that fits 16 registers + * with its two panel vectors and a broadcast. */ +#if AVX_LEVEL == 3 +#define TF_MR_MAX 8 +constexpr int TF_NV = 3; +#elif AVX_LEVEL == 2 +#define TF_MR_MAX 6 +constexpr int TF_NV = 2; +#elif AVX_LEVEL == 1 +#define TF_MR_MAX 4 +constexpr int TF_NV = 2; +#else +#define TF_MR_MAX 4 +constexpr int TF_NV = 4; +#endif +constexpr int TF_MR = TF_MR_MAX; +constexpr int64_t TF_NR = TF_NV * VF_N; /* panel columns */ +/* K chunk: sized for the L2 (96 KiB of panel at AVX-512), and longer where few rows share a + * panel, as the bf16 driver's. */ +constexpr int64_t TF_KC = 512, TF_KC_FEW = 2048, TF_FEW_ROWS = 32; + +template +static void tf_kernel(const float* A, int64_t lda, const float* P, int64_t kc, float* C) { + vf acc[MR][TF_NV]; +#pragma GCC unroll 8 + for (int i = 0; i < MR; ++i) + for (int v = 0; v < TF_NV; ++v) acc[i][v] = vf_loadu(C + i * TF_NR + v * VF_N); + for (int64_t k = 0; k < kc; ++k) { + vf b[TF_NV]; + for (int v = 0; v < TF_NV; ++v) b[v] = vf_load(P + k * TF_NR + v * VF_N); +#pragma GCC unroll 8 + for (int i = 0; i < MR; ++i) { + const vf a = vf_set1(A[i * lda + k]); + for (int v = 0; v < TF_NV; ++v) acc[i][v] = vf_fma(a, b[v], acc[i][v]); + } + } +#pragma GCC unroll 8 + for (int i = 0; i < MR; ++i) + for (int v = 0; v < TF_NV; ++v) vf_storeu(C + i * TF_NR + v * VF_N, acc[i][v]); +} + +using TfKernel = void (*)(const float*, int64_t, const float*, int64_t, float*); +static const TfKernel kTfKernel[] = { + nullptr, tf_kernel<1>, tf_kernel<2>, tf_kernel<3>, tf_kernel<4>, +#if TF_MR_MAX > 4 + tf_kernel<5>, tf_kernel<6>, +#endif +#if TF_MR_MAX > 6 + tf_kernel<7>, tf_kernel<8>, +#endif +}; + +/* dst[k * TF_NR + c] = src[c * ld + k] for c < TF_NR, k < kn: the panel's k-major order from its + * rows, whole 16 x 16 (AVX-512) or 8 x 8 blocks in registers and the last k one at a time. */ +static void tf_transpose(const float* src, int64_t ld, int64_t kn, float* dst) { + int64_t k = 0; +#if AVX_LEVEL == 3 + for (; k + 16 <= kn; k += 16) + for (int64_t c0 = 0; c0 < TF_NR; c0 += 16) { + __m512i r[16]; + for (int i = 0; i < 16; ++i) + r[i] = _mm512_castps_si512(_mm512_loadu_ps(src + (c0 + i) * ld + k)); + /* The same 16 x 16 transpose as the bf16 driver's, on f32 bits. */ + __m512i t[16], u[16], v[16]; + for (int i = 0; i < 8; ++i) { + t[2 * i] = _mm512_unpacklo_epi32(r[2 * i], r[2 * i + 1]); + t[2 * i + 1] = _mm512_unpackhi_epi32(r[2 * i], r[2 * i + 1]); + } + for (int q = 0; q < 4; ++q) { + u[4 * q + 0] = _mm512_unpacklo_epi64(t[4 * q], t[4 * q + 2]); + u[4 * q + 1] = _mm512_unpackhi_epi64(t[4 * q], t[4 * q + 2]); + u[4 * q + 2] = _mm512_unpacklo_epi64(t[4 * q + 1], t[4 * q + 3]); + u[4 * q + 3] = _mm512_unpackhi_epi64(t[4 * q + 1], t[4 * q + 3]); + } + for (int c = 0; c < 4; ++c) { + v[c] = _mm512_shuffle_i32x4(u[c], u[4 + c], 0x88); + v[4 + c] = _mm512_shuffle_i32x4(u[c], u[4 + c], 0xdd); + v[8 + c] = _mm512_shuffle_i32x4(u[8 + c], u[12 + c], 0x88); + v[12 + c] = _mm512_shuffle_i32x4(u[8 + c], u[12 + c], 0xdd); + } + for (int c = 0; c < 4; ++c) { + r[c] = _mm512_shuffle_i32x4(v[c], v[8 + c], 0x88); + r[8 + c] = _mm512_shuffle_i32x4(v[c], v[8 + c], 0xdd); + r[4 + c] = _mm512_shuffle_i32x4(v[4 + c], v[12 + c], 0x88); + r[12 + c] = _mm512_shuffle_i32x4(v[4 + c], v[12 + c], 0xdd); + } + for (int j = 0; j < 16; ++j) + _mm512_store_ps(dst + (k + j) * TF_NR + c0, _mm512_castsi512_ps(r[j])); + } +#elif AVX_LEVEL >= 1 + for (; k + 8 <= kn; k += 8) + for (int64_t c0 = 0; c0 < TF_NR; c0 += 8) { + __m256 r[8], t[8], u[8]; + for (int i = 0; i < 8; ++i) r[i] = _mm256_loadu_ps(src + (c0 + i) * ld + k); + for (int i = 0; i < 4; ++i) { + t[2 * i] = _mm256_unpacklo_ps(r[2 * i], r[2 * i + 1]); + t[2 * i + 1] = _mm256_unpackhi_ps(r[2 * i], r[2 * i + 1]); + } + /* u[4h + c], 128-bit lane L: column 4L + c of rows 4h .. 4h + 3. */ + for (int h = 0; h < 2; ++h) { + u[4 * h + 0] = _mm256_shuffle_ps(t[4 * h], t[4 * h + 2], 0x44); + u[4 * h + 1] = _mm256_shuffle_ps(t[4 * h], t[4 * h + 2], 0xee); + u[4 * h + 2] = _mm256_shuffle_ps(t[4 * h + 1], t[4 * h + 3], 0x44); + u[4 * h + 3] = _mm256_shuffle_ps(t[4 * h + 1], t[4 * h + 3], 0xee); + } + for (int c = 0; c < 4; ++c) { + _mm256_store_ps(dst + (k + c) * TF_NR + c0, _mm256_permute2f128_ps(u[c], u[4 + c], 0x20)); + _mm256_store_ps(dst + (k + 4 + c) * TF_NR + c0, + _mm256_permute2f128_ps(u[c], u[4 + c], 0x31)); + } + } +#endif + for (; k < kn; ++k) + for (int64_t c = 0; c < TF_NR; ++c) dst[k * TF_NR + c] = src[c * ld + k]; +} + +/* The dot-product form for a few rows: MRD rows of A against NRD decoded weight rows, each output + * a vector of partial sums (lane l holds the k = l mod VF_N terms, in k order) carried in `V` + * between chunks, [row][TF_NR] vectors. No transpose: with eight rows or fewer an outer product + * would reuse each panel load too few times to pay for one. `kv` is a multiple of VF_N; both + * operands are zero past the chunk. */ +template +static void td_kernel(const float* A, int64_t lda, const float* T, int64_t ldt, int64_t kv, + float* V) { + vf acc[MRD][NRD]; + for (int i = 0; i < MRD; ++i) + for (int j = 0; j < NRD; ++j) acc[i][j] = vf_loadu(V + (i * TF_NR + j) * VF_N); + for (int64_t k = 0; k < kv; k += VF_N) { + vf a[MRD]; + for (int i = 0; i < MRD; ++i) a[i] = vf_loadu(A + i * lda + k); + for (int j = 0; j < NRD; ++j) { + const vf b = vf_loadu(T + j * ldt + k); + for (int i = 0; i < MRD; ++i) acc[i][j] = vf_fma(a[i], b, acc[i][j]); + } + } + for (int i = 0; i < MRD; ++i) + for (int j = 0; j < NRD; ++j) vf_storeu(V + (i * TF_NR + j) * VF_N, acc[i][j]); +} + +/* Rows of A for which the dot-product form runs, and its blocks: two rows by four weight rows + * (eight accumulators, two A loads and four weight loads a step) where the 16 registers allow, + * four by four at AVX-512, one by eight for a last single row. */ +constexpr int64_t TF_DOT_ROWS = 8; +#if AVX_LEVEL == 3 +constexpr int TD_MR = 4; +#else +constexpr int TD_MR = 2; +#endif + +} /* namespace */ + +/* A job's task layout, fixed before the parallel region. */ +struct TfPlan { + int64_t np, sub, nsub, pg, ngr, t0, KC; + bool dot; +}; + +/* The batch (avx_gemm.h: TileJob) on the f32 driver, as qb_core's. */ +static bool tf_core(const Mat& ma, int64_t abase, const int64_t* arow, int64_t arows, + const Scales* SA, const TileJob* jobs, int64_t njobs, const RadTensor* Y, + int64_t ycols) { + if (njobs <= 0) return true; + if (arows <= 0) return false; + const bool sa_on = SA && SA->p, sb_on = jobs[0].SB.p != nullptr; + int64_t Kmax = 0; + bool any_dot = false; + for (int64_t j = 0; j < njobs; ++j) { + const TileJob& jb = jobs[j]; + if ((jb.SB.p != nullptr) != sb_on || (sb_on && jb.mb.dec)) return false; + Kmax = std::max(Kmax, jb.K); + any_dot = any_dot || jb.M <= TF_DOT_ROWS; + } + /* A code times an E8M0 scale 2^(e - 127) is exact in f32 up to e = 252; at 253 and 254 it can + * overflow where libref's grouped sum would not. No weight has such scales, so the tasks only + * note one, and the call is then left to the grouped driver, which rewrites all of Y. */ + const bool e8 = sb_on && (jobs[0].SB.e8m0 || jobs[0].SB.dt == RAD_E8M0); + std::atomic unfoldable{ false }; + const int64_t ys_r = row_stride(Y, ycols), ys_c = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1; + const int nth = tile_team(); + + std::vector plan((size_t)njobs); + int64_t tasks = 0, sub_max = 0, kpad = 0, ng_max = 0, work = 0; + for (int64_t j = 0; j < njobs; ++j) { + const TileJob& jb = jobs[j]; + TfPlan& pl = plan[(size_t)j]; + pl.dot = jb.M <= TF_DOT_ROWS; + /* The chunk is whole decoder spans (a joined head's scale block, a grid's group) and + * starts on a byte of any packed code; the dot-product form's lanes start each chunk on a + * multiple of 16 columns. */ + int64_t unit = jb.mb.dec ? jb.mb.dec->align() : 64; + if (pl.dot) unit = unit / std::gcd(unit, 16) * 16; + const int64_t kcw = jb.M <= TF_FEW_ROWS ? TF_KC_FEW : TF_KC; + pl.KC = unit >= kcw ? unit : kcw / unit * unit; + pl.np = (jb.N + TF_NR - 1) / TF_NR; + tile_split(jb.M, pl.np, TF_MR, nth, &pl.sub, &pl.nsub, &pl.pg); + pl.ngr = (pl.np + pl.pg - 1) / pl.pg; + pl.t0 = tasks; + tasks += pl.ngr * pl.nsub; + sub_max = std::max(sub_max, pl.sub * pl.pg); /* a task's C tiles */ + /* The widened rows' pitch: one line past the chunk, so the transpose's loads do not share + * an L1 set (see the bf16 driver). */ + kpad = std::max(kpad, (pl.KC + 15) / 16 * 16 + 16); + const int64_t gb = sb_on && jb.SB.group > 0 ? jb.SB.group : jb.K; + ng_max = std::max(ng_max, pl.KC / gb + 2); + work += jb.M * jb.N * jb.K; + } + + /* A in place when it is dense f32, unmapped and unscaled; else widened (and scaled) into + * rows zero to a multiple of 16, since the dot-product form reads whole vectors. */ + const bool in_place = ma.t->dtype == RAD_F32 && ma.cs == 1 && !sa_on && !ma.dec && !arow && + !any_dot; + const int64_t lda = in_place ? ma.rs : (Kmax + 15) / 16 * 16; + float* abuf = in_place ? nullptr + : (float*)scratch_raw((size_t)(arows * lda) * sizeof(float) + 64); + const float* Ab = in_place ? (const float*)ma.t->data + abase * ma.rs : abuf; + const int64_t sag = sa_on && SA->group > 0 ? SA->group : Kmax; + +#ifdef _OPENMP + const TileSchedule sched_scope(njobs, jobs[0].M); +#pragma omp parallel num_threads(nth) if(work >= 65536 || avx_par_forced()) +#endif + { + if (!in_place) { +#ifdef _OPENMP +#pragma omp for schedule(static) +#endif + for (int64_t r = 0; r < arows; ++r) { + const int64_t m = arow ? arow[r] : abase + r; + float* d = abuf + r * lda; + if (m < 0) { + std::memset(d, 0, (size_t)lda * sizeof(float)); + continue; + } + if (ma.dec) ma.dec->row(m, d); + else widen_cols(ma, m, 0, Kmax, d); + for (int64_t k = Kmax; k < lda; ++k) d[k] = 0.0f; + if (!sa_on) continue; + for (int64_t k0 = 0; k0 < Kmax; k0 += sag) { + const float s = SA->grp(m, k0 / sag); + const int64_t k1 = std::min(Kmax, k0 + sag); + const vf vs = vf_set1(s); + int64_t k = k0; + for (; k + VF_N <= k1; k += VF_N) vf_storeu(d + k, vf_mul(vf_loadu(d + k), vs)); + for (; k < k1; ++k) d[k] *= s; + } + } + } + +#ifdef _OPENMP +#pragma omp for schedule(runtime) +#endif + for (int64_t t = 0; t < tasks; ++t) { + int64_t ji = 0; + for (int64_t lo = 0, hi = njobs - 1; lo <= hi;) { + const int64_t mid = (lo + hi) / 2; + if (plan[(size_t)mid].t0 <= t) { ji = mid; lo = mid + 1; } else hi = mid - 1; + } + const TileJob& jb = jobs[ji]; + const TfPlan& pl = plan[(size_t)ji]; + const Mat& mb = jb.mb; + const int64_t tl = t - pl.t0, N = jb.N, K = jb.K, KC = pl.KC, sub = pl.sub; + const bool dot = pl.dot; + const int64_t gb = sb_on && jb.SB.group > 0 ? jb.SB.group : K; + const int64_t s = tl / pl.ngr, pe = std::min(pl.np, (tl % pl.ngr) * pl.pg + pl.pg); + const int64_t r0 = s * sub, r1 = std::min(jb.M, r0 + sub); + const size_t f_c = (size_t)(sub_max * TF_NR * VF_N); + const size_t f_p = (size_t)(kpad * TF_NR); + const size_t f_t = (size_t)(TF_NR * kpad); + float* C = scratch_f32(f_c + f_p + f_t + (size_t)ng_max + 2 * TF_NR + 64); + float* P = C + (f_c + 15) / 16 * 16; + float* T = P + f_p; + float* gs = T + f_t; + float* bv = gs + ng_max; + float* tmp = bv + TF_NR; + const int64_t p0 = (tl % pl.ngr) * pl.pg, ct = sub * TF_NR * (dot ? VF_N : 1); + for (int64_t p = p0; p < pe; ++p) + std::memset(C + (p - p0) * ct, 0, + (size_t)((r1 - r0) * TF_NR * (dot ? VF_N : 1)) * sizeof(float)); + /* K chunks outermost and the group's panels within (tile_split). */ + for (int64_t k0 = 0; k0 < K; k0 += KC) { + for (int64_t p = p0; p < pe; ++p) { + const int64_t n0 = p * TF_NR; + float* Cp = C + (p - p0) * ct; + const int64_t k1 = std::min(K, k0 + KC), kc = k1 - k0; + /* ---- the panel's rows, widened (and scaled), then k-major */ + for (int64_t c = 0; c < TF_NR; ++c) { + const int64_t n = n0 + c, wr = jb.b0 + n; + float* tr = T + c * kpad; + if (n >= N) { std::memset(tr, 0, (size_t)kpad * sizeof(float)); continue; } + if (c + 4 < TF_NR && n + 4 < N) { + const void* pp = nullptr; + int64_t pb = 0; + if (mb.dec) { + mb.dec->codes(wr + 4, k0, k1, &pp, &pb); + } else if (mb.cs == 1) { + pp = byte_at(mb.t->data, mb.t->dtype, (wr + 4) * mb.rs + k0); + pb = rad_dtype_bytes(mb.t->dtype, kc); + } + if (pp) tile_prefetch(pp, pb); + } + if (mb.dec) mb.dec->cols(wr, k0, k1, tr); + else widen_cols(mb, wr, k0, kc, tr); + for (int64_t k = kc; k < kpad; ++k) tr[k] = 0.0f; + if (!sb_on) continue; + const int64_t g0 = k0 / gb, g1 = (k1 - 1) / gb; + jb.SB.row_groups(wr, g0, g1 - g0 + 1, gs); + if (e8) + for (int64_t g = 0; g <= g1 - g0; ++g) + if (gs[g] >= 0x1p126f) unfoldable.store(true, std::memory_order_relaxed); + for (int64_t g = g0; g <= g1; ++g) { + const int64_t a0 = std::max(k0, g * gb) - k0; + const int64_t a1 = std::min(k1, (g + 1) * gb) - k0; + const vf vs = vf_set1(gs[g - g0]); + int64_t k = a0; + for (; k + VF_N <= a1; k += VF_N) + vf_storeu(tr + k, vf_mul(vf_loadu(tr + k), vs)); + for (; k < a1; ++k) tr[k] *= gs[g - g0]; + } + } + if (dot) { + const int64_t kv = (kc + VF_N - 1) / VF_N * VF_N; + int64_t m0 = r0; + for (; m0 + TD_MR <= r1; m0 += TD_MR) + for (int64_t c0 = 0; c0 < TF_NR; c0 += 4) + td_kernel(Ab + (jb.a0 + m0) * lda + k0, lda, + T + c0 * kpad, kpad, kv, + Cp + ((m0 - r0) * TF_NR + c0) * VF_N); + for (; m0 < r1; ++m0) + for (int64_t c0 = 0; c0 < TF_NR; c0 += 4) + td_kernel<1, 4>(Ab + (jb.a0 + m0) * lda + k0, lda, T + c0 * kpad, + kpad, kv, Cp + ((m0 - r0) * TF_NR + c0) * VF_N); + continue; + } + tf_transpose(T, kpad, kc, P); + for (int64_t m0 = r0; m0 < r1; m0 += TF_MR) { + const int64_t mm = std::min(TF_MR, r1 - m0); + kTfKernel[mm](Ab + (jb.a0 + m0) * lda + k0, lda, P, kc, + Cp + (m0 - r0) * TF_NR); + } + } + } + for (int64_t p = p0; p < pe; ++p) { + const int64_t n0 = p * TF_NR, cols = std::min(TF_NR, N - n0); + float* Cp = C + (p - p0) * ct; + if (dot) { + /* Each output's partial sums, reduced by the fixed tree of vf_hsum. */ + for (int64_t i = 0; i < (r1 - r0) * TF_NR; ++i) + Cp[i] = vf_hsum(vf_loadu(Cp + i * VF_N)); + } + const bool hb = tile_bias(jb.bias, n0, cols, N, bv); + for (int64_t m = r0; m < r1; ++m) + tile_store(Y, ys_r, ys_c, jb.y0 + m, jb.yc0 + n0, cols, Cp + (m - r0) * TF_NR, + hb ? bv : nullptr, tmp); + } + } + } + return !unfoldable.load(std::memory_order_relaxed); +} + +bool gemm_tile_f32(const Mat& ma, const Mat& mb, const Scales* SA, const Scales* SB, + const RadTensor* Y, const RadTensor* bias, int64_t M, int64_t N, int64_t K) { + /* One job per super-block of A rows, which stays in the L3 (16 MiB), as qb_run's. */ + int64_t mcb = (int64_t)(16 << 20) / (4 * std::max(K, 1)); + mcb = std::max(64, std::min(mcb, 8192)) / TF_MR * TF_MR; + if (mcb > M) mcb = M; + bool ok = true; + for (int64_t mb0 = 0; mb0 < M; mb0 += mcb) { + TileJob jb{}; + jb.mb = mb; + if (SB) jb.SB = *SB; + jb.a0 = 0; jb.M = std::min(mcb, M - mb0); jb.N = N; jb.K = K; + jb.y0 = mb0; jb.yc0 = 0; jb.bias = bias; + ok = tf_core(ma, mb0, nullptr, jb.M, SA, &jb, 1, Y, N) && ok; + } + return ok; +} + +bool gemm_tile_f32_jobs(const Mat& ma, const int64_t* arow, int64_t arows, const Scales* SA, + const TileJob* jobs, int64_t njobs, const RadTensor* Y, int64_t ycols) { + return tf_core(ma, 0, arow, arows, SA, jobs, njobs, Y, ycols); +} + +} /* inline namespace AVX_SUFFIX */ +} /* namespace avx */ diff --git a/libavx/avx_gen.cpp b/libavx/avx_gen.cpp new file mode 100644 index 00000000..038c1d6d --- /dev/null +++ b/libavx/avx_gen.cpp @@ -0,0 +1,1047 @@ +/* avx_gen.cpp -- the image generator's ops (docs/OPS.md, "Image generation") except + * attn_prefix_self (avx_gen_attn.cpp): the diffusion transformer's adaptive norms and gated + * residual, the timestep embedding, the per-image latent lanes and the flow-matching sampler, and + * the image decoder's convolution, channel norm, resampling shortcuts and pixel output. + * + * Each op rounds where libref/ref_gen.cpp rounds, which is where the upstream bf16 model stores a + * tensor. Rows are computed in f32 scratch and every such rounding is a pass through the stored + * dtype (`narrow_row`), so a fused kernel produces the bytes of the unfused chain. + * + * Bit-exact with libref, not only within tolerance: randn_lanes and flow_euler (a seed gives the + * same picture on every plugin, and the sampler's state feeds every later step), gate_add, + * chan_affine, to_rgba8, s2d_avg_add, d2s_add, the lane copies and timestep_embed. Where libref + * multiplies and then adds in two roundings, `keep` stops the compiler from fusing the pair (this + * plugin is built with -ffp-contract=fast, libref without contraction). The norms reduce in a + * different order from libref's and are held to the tolerance table. + * + * Per-entry tables (a sequence's modulation row, its tanh gate) are built once per launch before + * the parallel region, in scratch_raw; the row loops use only scratch_f32 / _b / _c, so the + * calling thread's table is never reallocated under its readers. + */ +#include "avx_vec.h" +#include "avx_common.h" +#include "rad_philox.h" + +#include +#include + +using namespace avx; + +#include "avx_had.h" + +namespace avx { +inline namespace AVX_SUFFIX { +/* gemm_nt's product over operands assembled by a composite kernel (avx_gemm.cpp). */ +int gemm_nt_into(const RadTensor* A, const RadTensor* B, const RadTensor* bias, const RadTensor* Y, + int64_t M, int64_t N, int64_t K); +} /* inline namespace AVX_SUFFIX */ +} /* namespace avx */ + +namespace { + +/* An entry's flags (docs/OPS.md, flow_euler): RadGenBatch's RAD_GEN_F_* values, restated as + * libref restates them, since a kernel library compiles against rad_abi.h only. */ +enum { kFirst = 1, kInpaint = 2, kPreview = 4 }; + +/* Entry `i` of a cu_seqlens operand, and the entry owning row `r` (libref's linear scan). */ +inline int64_t cu_at(const RadTensor* cu, int64_t i) { return ldi(cu, offlin(cu, i)); } +inline int64_t seq_of(const RadTensor* cu, int64_t n_seq, int64_t r) { + int64_t s = 0; + while (s + 1 < n_seq && cu_at(cu, s + 1) <= r) ++s; + return s; +} + +/* v[0, n) rounded through dtype `dt` in place, as a store and reload rounds it. `tmp` holds n + * floats. */ +inline void narrow_row(uint32_t dt, float* v, int64_t n, float* tmp) { + if (dt == RAD_F32) return; + row_from_f32(dt, v, tmp, n); + row_to_f32(dt, tmp, v, n); +} + +/* A value the compiler may not fuse into the next add. */ +#if AVX_LEVEL == 0 +inline vf keep(vf x) { __asm__("" : "+x"(x)); return x; } +#elif AVX_LEVEL == 3 +inline vf keep(vf x) { __asm__("" : "+v"(x)); return x; } +inline float keep(float x) { __asm__("" : "+v"(x)); return x; } +#else +inline vf keep(vf x) { __asm__("" : "+x"(x)); return x; } +inline float keep(float x) { __asm__("" : "+x"(x)); return x; } +#endif + +/* Sum of (x[i] - mean)^2 with four accumulators: layer norm's second pass. */ +inline float dev_sumsq(const float* x, float mean, int64_t n) { + const vf vm = vf_set1(mean); + vf a0 = vf_zero(), a1 = vf_zero(), a2 = vf_zero(), a3 = vf_zero(); + int64_t i = 0; + for (; i + 4 * VF_N <= n; i += 4 * VF_N) { + const vf d0 = vf_sub(vf_loadu(x + i), vm), d1 = vf_sub(vf_loadu(x + i + VF_N), vm); + const vf d2 = vf_sub(vf_loadu(x + i + 2 * VF_N), vm); + const vf d3 = vf_sub(vf_loadu(x + i + 3 * VF_N), vm); + a0 = vf_fma(d0, d0, a0); + a1 = vf_fma(d1, d1, a1); + a2 = vf_fma(d2, d2, a2); + a3 = vf_fma(d3, d3, a3); + } + for (; i + VF_N <= n; i += VF_N) { + const vf d = vf_sub(vf_loadu(x + i), vm); + a0 = vf_fma(d, d, a0); + } + float s = vf_hsum(vf_add(vf_add(a0, a1), vf_add(a2, a3))); + for (; i < n; ++i) { const float d = x[i] - mean; s += d * d; } + return s; +} + +/* out = (x - mean) * rs: the normalised row before its rounding, as libref forms it. */ +inline void center_scale(const float* x, float mean, float rs, float* out, int64_t n) { + const vf vm = vf_set1(mean), vr = vf_set1(rs); + int64_t i = 0; + for (; i + VF_N <= n; i += VF_N) vf_storeu(out + i, vf_mul(vf_sub(vf_loadu(x + i), vm), vr)); + for (; i < n; ++i) out[i] = (x[i] - mean) * rs; +} + +inline void mul_rows(float* v, const float* w, int64_t n) { + int64_t i = 0; + for (; i + VF_N <= n; i += VF_N) vf_storeu(v + i, vf_mul(vf_loadu(v + i), vf_loadu(w + i))); + for (; i < n; ++i) v[i] *= w[i]; +} + +inline void add_rows(float* v, const float* w, int64_t n) { + int64_t i = 0; + for (; i + VF_N <= n; i += VF_N) vf_storeu(v + i, vf_add(vf_loadu(v + i), vf_loadu(w + i))); + for (; i < n; ++i) v[i] += w[i]; +} + +/* An entry's modulation row through `f`, rounded to `dt`, for every entry: [n_seq][n] floats in + * scratch_raw. `s` is [n_seq, >= n] at its own row pitch (a column slice of the shared + * modulation projection), read as libref reads it. `f` 0 is 1 + s, 1 is tanh(s), the exact libm + * tanh: a gate is per entry and column, so n_seq * n tanh calls per launch, not one per element. */ +float* entry_rows(const RadTensor* s, int64_t n_seq, int64_t n, uint32_t dt, int f) { + float* t = (float*)scratch_raw((size_t)(n_seq * n + 16) * sizeof(float)); + const int64_t rs = row_stride(s, n), cs = laststride(s); + for (int64_t e = 0; e < n_seq; ++e) { + float* row = t + e * n; + for (int64_t i = 0; i < n; ++i) { + const float v = ldt(s, e * rs + i * cs); + row[i] = narrow1(dt, f ? sc_tanh(v) : 1.0f + v); + } + } + return t; +} + +/* A row copied between operands, converted through f32 as libref's element loop is. Whole-byte + * float rows of one dtype are copied as bytes, which is the same thing for every non-NaN value. */ +inline void copy_row(const RadTensor* src, int64_t sb, const RadTensor* dst, int64_t db, int64_t n, + float* scr) { + const uint32_t dt = src->dtype; + const bool flt = dt == RAD_F32 || dt == RAD_BF16 || dt == RAD_F16 || dt == RAD_F8E4M3 || + dt == RAD_F8E5M2; + if (flt && dt == dst->dtype && laststride(src) == 1 && laststride(dst) == 1) { + const size_t w = (size_t)(rad_dtype_bits(dt) / 8); + std::memcpy((char*)dst->data + (size_t)db * w, (const char*)src->data + (size_t)sb * w, + (size_t)n * w); + return; + } + out_row(dst, db, n, in_row(src, sb, n, scr)); +} + +/* Elements [e0, e0 + cnt) of `seed`'s normal stream into out (abi/rad_philox.h): the same + * arithmetic as rad_philox_normal, with one Philox block and one log per element pair instead of + * one each per element. */ +void philox_normals(uint64_t seed, uint64_t e0, int64_t cnt, float* out) { + uint64_t e = e0; + int64_t i = 0; + while (i < cnt) { + const uint64_t g = e >> 2; + uint32_t c[4] = { (uint32_t)g, (uint32_t)(g >> 32), 0u, 0u }; + rad_philox4x32_10(c, (uint32_t)seed, (uint32_t)(seed >> 32)); + for (int pair = (int)((e & 3u) >> 1); pair < 2 && i < cnt; ++pair) { + const uint32_t wa = c[pair * 2], wb = c[pair * 2 + 1]; + const float ua = ((float)(wa >> 8) + 0.5f) * (1.0f / 16777216.0f); + const float ub = ((float)(wb >> 8) + 0.5f) * (1.0f / 16777216.0f); + const float r = sqrtf(-2.0f * logf(ua)); + const float t = 6.28318530717958647692f * ub; + if ((e & 1u) == 0) { out[i++] = r * cosf(t); ++e; } + if (i < cnt) { out[i++] = r * sinf(t); ++e; } + } + } +} + +inline uint64_t seed_of(const RadTensor* seed, int64_t e) { + return (uint64_t)(uint32_t)ldi(seed, offlin(seed, 2 * e)) | + ((uint64_t)(uint32_t)ldi(seed, offlin(seed, 2 * e + 1)) << 32); +} + +/* The bf16 values of a space-separated list (libref's parse_list): up to `cap` into out. */ +int64_t parse_list(const char* s, float* out, int64_t cap) { + int64_t k = 0; + while (s && *s) { + char* end = nullptr; + const double v = std::strtod(s, &end); + if (end == s) break; + if (k < cap) out[k] = narrow1(RAD_BF16, (float)v); + ++k; + s = end; + } + return k; +} + +} /* namespace */ + +/* ------------------------------------------------------------------ ln_mod */ +/* y = bf16( bf16(LN(x)) * bf16(1 + s[seq]) ), the roundings in y's dtype. */ +AVX_KERNEL(ln_mod) { + if (!rad_args_have(a, 4)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *S = &a->t[1], *cu = &a->t[2], *Y = &a->t[3]; + const int64_t n = p_int(a, "n", 0); + const float eps = p_f32(a, "eps", 1e-6f); + if (n <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_of(Y, n), n_seq = numel(cu) - 1; + if (rows <= 0 || n_seq <= 0 || rows_of(X, n) < rows) return RAD_E_SHAPE; + const float* gain = entry_rows(S, n_seq, n, Y->dtype, 0); + + AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + float* buf = scratch_f32((size_t)(3 * n + 48)); + float *xs = buf, *d = buf + n + 16, *tmp = d + n + 16; + const float* xv = in_row(X, rowoff(X, r, n), n, xs); + const float mean = row_sum(xv, n) / (float)n; + const float rs = 1.0f / std::sqrt(dev_sumsq(xv, mean, n) / (float)n + eps); + center_scale(xv, mean, rs, d, n); + narrow_row(Y->dtype, d, n, tmp); + mul_rows(d, gain + seq_of(cu, n_seq, r) * n, n); + out_row(Y, rowoff(Y, r, n), n, d); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ gate_add */ +/* x = bf16( x + bf16( bf16(tanh(g[seq])) * y ) ), the roundings in x's dtype. */ +AVX_KERNEL(gate_add) { + if (!rad_args_have(a, 4)) return RAD_E_INVAL; + const RadTensor *Yv = &a->t[0], *G = &a->t[1], *cu = &a->t[2], *X = &a->t[3]; + const int64_t n = p_int(a, "n", 0); + if (n <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_of(Yv, n), n_seq = numel(cu) - 1; + if (rows <= 0 || n_seq <= 0 || rows_of(X, n) < rows) return RAD_E_SHAPE; + const float* gate = entry_rows(G, n_seq, n, X->dtype, 1); + + AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + float* buf = scratch_f32((size_t)(4 * n + 64)); + float *ys = buf, *xs = buf + n + 16, *p = xs + n + 16, *tmp = p + n + 16; + const float* yv = in_row(Yv, rowoff(Yv, r, n), n, ys); + const float* xv = in_row(X, rowoff(X, r, n), n, xs); + const float* t = gate + seq_of(cu, n_seq, r) * n; + int64_t i = 0; + for (; i + VF_N <= n; i += VF_N) vf_storeu(p + i, vf_mul(vf_loadu(t + i), vf_loadu(yv + i))); + for (; i < n; ++i) p[i] = t[i] * yv[i]; + narrow_row(X->dtype, p, n, tmp); + add_rows(p, xv, n); + out_row(X, rowoff(X, r, n), n, p); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ ln_mod_quant_fp8 */ +/* gate_add (with `gated` 1), ln_mod and quant_act_fp8 in one pass over each row: the residual + * rounded to x's dtype and stored, the norm to bf16, the codes as quant_act_fp8 writes them over + * that bf16 row (avx_had.h: fp8_emit), and the bf16 row into `z` when bound. */ +AVX_KERNEL(ln_mod_quant_fp8) { + if (a->n_t < 8) return RAD_E_INVAL; + const RadTensor *Yv = rad_arg_in(a, 0), *G = rad_arg_in(a, 1), *S = &a->t[2], *cu = &a->t[3]; + const RadTensor *X = &a->t[4], *Q = &a->t[5], *SC = &a->t[6], *Z = rad_arg_in(a, 7); + const int64_t n = p_int(a, "n", 0), grp = p_int(a, "group", 0); + const bool gated = p_int(a, "gated", 0) != 0; + const float eps = p_f32(a, "eps", 1e-6f); + if (n <= 0 || grp <= 0 || n % grp || (gated && (!Yv || !G))) return RAD_E_SHAPE; + const int64_t rows = rows_of(Q, n), n_seq = numel(cu) - 1, ngrp = n / grp; + if (rows <= 0 || n_seq <= 0 || rows_of(X, n) < rows || numel(SC) < rows * ngrp) + return RAD_E_SHAPE; + if (!S->data) return RAD_E_INVAL; + /* Both tables from one scratch_raw call: a second may reallocate the first. */ + float* tabs = (float*)scratch_raw((size_t)(2 * n_seq * n + 32) * sizeof(float)); + { + const int64_t s_rs = row_stride(S, n), s_cs = laststride(S); + const int64_t g_rs = gated ? row_stride(G, n) : 0, g_cs = gated ? laststride(G) : 0; + for (int64_t e = 0; e < n_seq; ++e) + for (int64_t i = 0; i < n; ++i) { + tabs[e * n + i] = narrow1(RAD_BF16, 1.0f + ldt(S, e * s_rs + i * s_cs)); + if (gated) + tabs[(n_seq + e) * n + i] = + narrow1(X->dtype, sc_tanh(ldt(G, e * g_rs + i * g_cs))); + } + } + const float* gain = tabs; + const float* gate = tabs + n_seq * n; + + AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + float* buf = scratch_f32((size_t)(5 * n + 80)); + float *xs = buf, *v = buf + n + 16, *o = v + n + 16, *codes = o + n + 16; + float* tmp = codes + n + 16; + const int64_t e = seq_of(cu, n_seq, r); + const float* xv = in_row(X, rowoff(X, r, n), n, xs); + if (gated) { + const float* yv = in_row(Yv, rowoff(Yv, r, n), n, codes); + const float* t = gate + e * n; + int64_t i = 0; + for (; i + VF_N <= n; i += VF_N) + vf_storeu(v + i, vf_mul(vf_loadu(t + i), vf_loadu(yv + i))); + for (; i < n; ++i) v[i] = t[i] * yv[i]; + narrow_row(X->dtype, v, n, tmp); + add_rows(v, xv, n); + narrow_row(X->dtype, v, n, tmp); + out_row(X, rowoff(X, r, n), n, v); + } else { + std::memcpy(v, xv, (size_t)n * sizeof(float)); + } + const float mean = row_sum(v, n) / (float)n; + const float rs = 1.0f / std::sqrt(dev_sumsq(v, mean, n) / (float)n + eps); + center_scale(v, mean, rs, o, n); + narrow_row(RAD_BF16, o, n, tmp); + mul_rows(o, gain + e * n, n); + narrow_row(RAD_BF16, o, n, tmp); + fp8_emit(o, codes, n, grp, Q, SC, Z, r); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ timestep_embed */ +/* y[m] = [cos(t' f_0) .. cos(t' f_{h-1}) | sin(t' f_0) .. sin(t' f_{h-1})] with libref's libm + * calls: a pass embeds one row per entry, so this is a few thousand transcendentals. */ +AVX_KERNEL(timestep_embed) { + if (!rad_args_have(a, 2)) return RAD_E_INVAL; + const RadTensor *T = &a->t[0], *Y = &a->t[1]; + const int64_t n = p_int(a, "n", 0); + const float scale = p_f32(a, "scale", 1000.0f); + const double mp = p_f32(a, "max_period", 10000.0f); + const int round = (int)p_int(a, "round", 0); + if (n <= 0 || (n & 1)) return RAD_E_SHAPE; + const int64_t rows = rows_of(Y, n); + if (rows <= 0 || numel(T) < rows) return RAD_E_SHAPE; + const int64_t h = n / 2; + const float coef = (float)(-std::log(mp)); + float* buf = scratch_f32((size_t)(2 * n + 16)); + float *f = buf, *row = buf + n; + for (int64_t i = 0; i < h; ++i) f[i] = sc_exp(coef * (float)i / (float)h); + for (int64_t m = 0; m < rows; ++m) { + const float tv = ldt(T, offlin(T, m)); + const float tt = round ? scale * narrow1(RAD_BF16, narrow1(RAD_BF16, tv * scale) / scale) + : scale * tv; + for (int64_t i = 0; i < h; ++i) { + const float arg = tt * f[i]; + row[i] = sc_cos(arg); + row[h + i] = sc_sin(arg); + } + out_row(Y, rowoff(Y, m, n), n, row); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ gather_rows2 */ +/* y[i] = idx[i] >= 0 ? a[idx[i]] : b[-1 - idx[i]], zeros past either source. */ +AVX_KERNEL(gather_rows2) { + if (!rad_args_have(a, 4)) return RAD_E_INVAL; + const RadTensor *A = &a->t[0], *B = &a->t[1], *I = &a->t[2], *Y = &a->t[3]; + const int64_t n = p_int(a, "n", 0); + if (n <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_of(Y, n); + if (rows <= 0 || numel(I) < rows) return RAD_E_SHAPE; + const int64_t ra = rows_of(A, n), rb = rows_of(B, n); + + AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) + for (int64_t i = 0; i < rows; ++i) { + float* scr = scratch_f32((size_t)n + 16); + const int64_t r = ldi(I, offlin(I, i)); + const RadTensor* src = r >= 0 ? A : B; + const int64_t row = r >= 0 ? r : -1 - r; + if (row >= (r >= 0 ? ra : rb)) { + for (int64_t c = 0; c < n; ++c) scr[c] = 0.0f; + out_row(Y, rowoff(Y, i, n), n, scr); + continue; + } + copy_row(src, rowoff(src, row, n), Y, rowoff(Y, i, n), n, scr); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ lane_gather / lane_store */ +/* lane_gather: y[cu[e] + k] = src[lane[e] * stride + k]. Every entry is checked before any row is + * written (libref checks each as it reaches it), and an entry whose rows lie past y's end is + * refused rather than written past it. */ +AVX_KERNEL(lane_gather) { + if (!rad_args_have(a, 4)) return RAD_E_INVAL; + const RadTensor *src = &a->t[0], *lane = &a->t[1], *cu = &a->t[2], *Y = &a->t[3]; + const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0); + if (n <= 0 || stride <= 0) return RAD_E_SHAPE; + const int64_t n_seq = numel(cu) - 1, src_rows = rows_of(src, n), y_rows = rows_of(Y, n); + if (n_seq <= 0 || numel(lane) < n_seq || cu_at(cu, n_seq) <= cu_at(cu, 0)) return RAD_E_SHAPE; + for (int64_t e = 0; e < n_seq; ++e) { + const int64_t L = ldi(lane, offlin(lane, e)), b0 = cu_at(cu, e), b1 = cu_at(cu, e + 1); + if (L < 0 || b1 - b0 > stride || (L + 1) * stride > src_rows) return RAD_E_SHAPE; + if (b1 > b0 && (b0 < 0 || b1 > y_rows)) return RAD_E_SHAPE; + } + for (int64_t e = 0; e < n_seq; ++e) { + const int64_t L = ldi(lane, offlin(lane, e)), b0 = cu_at(cu, e), len = cu_at(cu, e + 1) - b0; + AVX_PARALLEL_FOR_IF(len * n >= AVX_PAR_MIN) + for (int64_t k = 0; k < len; ++k) { + float* scr = scratch_f32((size_t)n + 16); + copy_row(src, rowoff(src, L * stride + k, n), Y, rowoff(Y, b0 + k, n), n, scr); + } + } + return RAD_OK; +} + +/* lane_store: every listed lane's rows [0, rows) become src's rows. */ +AVX_KERNEL(lane_store) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const RadTensor *src = &a->t[0], *lane = &a->t[1], *dst = &a->t[2]; + const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0); + if (n <= 0 || stride <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_of(src, n), dst_rows = rows_of(dst, n), nl = numel(lane); + if (rows <= 0 || rows > stride) return RAD_E_SHAPE; + for (int64_t l = 0; l < nl; ++l) { + const int64_t L = ldi(lane, offlin(lane, l)); + if (L < 0 || (L + 1) * stride > dst_rows) return RAD_E_SHAPE; + } + for (int64_t l = 0; l < nl; ++l) { + const int64_t L = ldi(lane, offlin(lane, l)); + AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) + for (int64_t k = 0; k < rows; ++k) { + float* scr = scratch_f32((size_t)n + 16); + copy_row(src, rowoff(src, k, n), dst, rowoff(dst, L * stride + k, n), n, scr); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ randn_lanes */ +/* An image's first step: its lane's rows [0, cu[e+1] - cu[e]) become the seed's normal stream, + * element (k, c) the stream's k * n + c, bit for bit libref's. */ +AVX_KERNEL(randn_lanes) { + if (!rad_args_have(a, 5)) return RAD_E_INVAL; + const RadTensor *fl = &a->t[0], *seed = &a->t[1], *lane = &a->t[2], *cu = &a->t[3]; + const RadTensor* dst = &a->t[4]; + const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0); + if (n <= 0 || stride <= 0) return RAD_E_SHAPE; + const int64_t n_seq = numel(cu) - 1, dst_rows = rows_of(dst, n); + if (n_seq <= 0 || numel(fl) < n_seq || numel(lane) < n_seq || numel(seed) < 2 * n_seq) + return RAD_E_SHAPE; + if (cu_at(cu, n_seq) <= cu_at(cu, 0)) return RAD_E_SHAPE; + for (int64_t e = 0; e < n_seq; ++e) { + if (!(ldi(fl, offlin(fl, e)) & kFirst)) continue; + const int64_t L = ldi(lane, offlin(lane, e)), len = cu_at(cu, e + 1) - cu_at(cu, e); + if (L < 0 || len > stride || (L + 1) * stride > dst_rows) return RAD_E_SHAPE; + } + for (int64_t e = 0; e < n_seq; ++e) { + if (!(ldi(fl, offlin(fl, e)) & kFirst)) continue; + const int64_t L = ldi(lane, offlin(lane, e)), len = cu_at(cu, e + 1) - cu_at(cu, e); + const uint64_t sd = seed_of(seed, e); + AVX_PARALLEL_FOR_IF(len * n * 8 >= AVX_PAR_MIN) + for (int64_t k = 0; k < len; ++k) { + float* row = scratch_f32((size_t)n + 16); + philox_normals(sd, (uint64_t)(k * n), n, row); + out_row(dst, rowoff(dst, L * stride + k, n), n, row); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ flow_euler */ +/* One Euler step for every entry that moves a lane (pair != -2), libref's roundings in the state's + * dtype: + * + * v' = pair >= 0 ? bf16(neg + bf16(cfg * bf16(v - neg))) : v + * x' = bf16(x + bf16(bf16(sigma_next - sigma) * v')) + * + * flag 4 writes x - sigma v' to the lane's preview, and flag 2 restores the kept region, + * x' = bf16(m x' + (1 - m)((1 - sigma_next) src + sigma_next noise)). libref requires every + * operand, the optional three included. Every entry is checked before any lane is written. */ +AVX_KERNEL(flow_euler) { + if (!rad_args_have(a, 13)) return RAD_E_INVAL; + const RadTensor *V = &a->t[0], *sg = &a->t[1], *sgn = &a->t[2], *cfg = &a->t[3]; + const RadTensor *pair = &a->t[4], *lane = &a->t[5], *fl = &a->t[6], *seed = &a->t[7]; + const RadTensor *cu = &a->t[8], *inp = &a->t[9], *mask = &a->t[10], *st = &a->t[11]; + const RadTensor* pv = &a->t[12]; + const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0); + if (n <= 0 || stride <= 0) return RAD_E_SHAPE; + const int64_t n_seq = numel(cu) - 1, st_rows = rows_of(st, n), v_rows = rows_of(V, n); + if (n_seq <= 0 || cu_at(cu, n_seq) <= cu_at(cu, 0)) return RAD_E_SHAPE; + for (int64_t e = 0; e < n_seq; ++e) { + const int64_t pr = ldi(pair, offlin(pair, e)); + if (pr == -2) continue; + const int64_t L = ldi(lane, offlin(lane, e)); + const int64_t b0 = cu_at(cu, e), len = cu_at(cu, e + 1) - b0; + if (L < 0 || len > stride || (L + 1) * stride > st_rows) return RAD_E_SHAPE; + if (pr >= n_seq || (pr >= 0 && cu_at(cu, pr + 1) - cu_at(cu, pr) != len)) + return RAD_E_SHAPE; + if (len > 0 && (b0 < 0 || b0 + len > v_rows)) return RAD_E_SHAPE; + if (pr >= 0 && len > 0 && (cu_at(cu, pr) < 0 || cu_at(cu, pr) + len > v_rows)) + return RAD_E_SHAPE; + } + const uint32_t dt = st->dtype; + for (int64_t e = 0; e < n_seq; ++e) { + const int64_t pr = ldi(pair, offlin(pair, e)); + if (pr == -2) continue; + const int64_t L = ldi(lane, offlin(lane, e)); + const int64_t b0 = cu_at(cu, e), len = cu_at(cu, e + 1) - b0; + const int64_t p0 = pr >= 0 ? cu_at(cu, pr) : 0; + const float s = ldt(sg, offlin(sg, e)), sn = ldt(sgn, offlin(sgn, e)); + const float w = ldt(cfg, offlin(cfg, e)); + const int64_t f = ldi(fl, offlin(fl, e)); + const uint64_t sd = seed_of(seed, e); + const float dts = narrow1(dt, sn - s); + const float one_sn = 1.0f - sn; + AVX_PARALLEL_FOR_IF(len * n * 8 >= AVX_PAR_MIN) + for (int64_t k = 0; k < len; ++k) { + float* buf = scratch_f32((size_t)(5 * n + 80)); + float *vv = buf, *xs = vv + n + 16, *u = xs + n + 16, *nz = u + n + 16; + float* tmp = nz + n + 16; + const float* vin = in_row(V, rowoff(V, b0 + k, n), n, u); + std::memcpy(vv, vin, (size_t)n * sizeof(float)); + if (pr >= 0) { + const float* vn = in_row(V, rowoff(V, p0 + k, n), n, u); + int64_t c = 0; + for (; c + VF_N <= n; c += VF_N) + vf_storeu(vv + c, vf_sub(vf_loadu(vv + c), vf_loadu(vn + c))); + for (; c < n; ++c) vv[c] -= vn[c]; + narrow_row(dt, vv, n, tmp); + const vf vw = vf_set1(w); + for (c = 0; c + VF_N <= n; c += VF_N) vf_storeu(vv + c, vf_mul(vw, vf_loadu(vv + c))); + for (; c < n; ++c) vv[c] *= w; + narrow_row(dt, vv, n, tmp); + add_rows(vv, vn, n); + narrow_row(dt, vv, n, tmp); + } + const int64_t sb = rowoff(st, L * stride + k, n); + const float* x = in_row(st, sb, n, xs); + if (f & kPreview) { + const vf vs = vf_set1(s); + int64_t c = 0; + for (; c + VF_N <= n; c += VF_N) + vf_storeu(tmp + c, vf_sub(vf_loadu(x + c), keep(vf_mul(vs, vf_loadu(vv + c))))); + for (; c < n; ++c) tmp[c] = x[c] - keep(s * vv[c]); + out_row(pv, rowoff(pv, L * stride + k, n), n, tmp); + } + { + const vf vd = vf_set1(dts); + int64_t c = 0; + for (; c + VF_N <= n; c += VF_N) vf_storeu(u + c, vf_mul(vd, vf_loadu(vv + c))); + for (; c < n; ++c) u[c] = dts * vv[c]; + narrow_row(dt, u, n, tmp); + add_rows(u, x, n); + narrow_row(dt, u, n, tmp); + } + if (f & kInpaint) { + const float m = ldt(mask, offlin(mask, L * stride + k)); + const float one_m = 1.0f - m; + const float* src = in_row(inp, rowoff(inp, L * stride + k, n), n, xs); + philox_normals(sd, (uint64_t)(k * n), n, nz); + const vf v1 = vf_set1(one_sn), v2 = vf_set1(sn), vm = vf_set1(m), v3 = vf_set1(one_m); + int64_t c = 0; + for (; c + VF_N <= n; c += VF_N) { + const vf kept = vf_add(keep(vf_mul(v1, vf_loadu(src + c))), + keep(vf_mul(v2, vf_loadu(nz + c)))); + vf_storeu(u + c, vf_add(keep(vf_mul(vm, vf_loadu(u + c))), + keep(vf_mul(v3, kept)))); + } + for (; c < n; ++c) { + const float kept = keep(one_sn * src[c]) + keep(sn * nz[c]); + u[c] = keep(m * u[c]) + keep(one_m * kept); + } + narrow_row(dt, u, n, tmp); + } + out_row(st, sb, n, u); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ chan_affine */ +/* A per-channel affine from two lists of n bf16 values: `fma` is bf16(bf16(x * mul) + add), `inv` + * is bf16(bf16(x - add) / mul), the inner rounding in y's dtype. */ +AVX_KERNEL(chan_affine) { + if (!rad_args_have(a, 2)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *Y = &a->t[1]; + const int64_t n = p_int(a, "n", 0); + if (n <= 0) return RAD_E_SHAPE; + const char* ms = p_str(a, "mul", ""), *as = p_str(a, "add", ""); + /* Each number takes at least two characters but the last, so this bounds the count. */ + const int64_t cap = (int64_t)((std::strlen(ms) + std::strlen(as)) / 2 + 2); + float* lists = (float*)scratch_raw((size_t)(2 * cap + 16) * sizeof(float)); + float *mul = lists, *add = lists + cap; + if (parse_list(ms, mul, cap) != n || parse_list(as, add, cap) != n) return RAD_E_SHAPE; + const char* mode = p_str(a, "mode", "fma"); + const bool inv = mode && !std::strcmp(mode, "inv"); + if (!inv && mode && std::strcmp(mode, "fma")) return RAD_E_INVAL; + const int64_t rows = rows_of(Y, n); + if (rows <= 0 || rows_of(X, n) < rows) return RAD_E_SHAPE; + + AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + float* buf = scratch_f32((size_t)(3 * n + 48)); + float *xs = buf, *t = buf + n + 16, *tmp = t + n + 16; + const float* x = in_row(X, rowoff(X, r, n), n, xs); + int64_t c = 0; + if (inv) { + for (; c + VF_N <= n; c += VF_N) + vf_storeu(t + c, vf_sub(vf_loadu(x + c), vf_loadu(add + c))); + for (; c < n; ++c) t[c] = x[c] - add[c]; + narrow_row(Y->dtype, t, n, tmp); + for (c = 0; c + VF_N <= n; c += VF_N) + vf_storeu(t + c, vf_div(vf_loadu(t + c), vf_loadu(mul + c))); + for (; c < n; ++c) t[c] /= mul[c]; + } else { + for (; c + VF_N <= n; c += VF_N) + vf_storeu(t + c, vf_mul(vf_loadu(x + c), vf_loadu(mul + c))); + for (; c < n; ++c) t[c] = x[c] * mul[c]; + narrow_row(Y->dtype, t, n, tmp); + add_rows(t, add, n); + } + out_row(Y, rowoff(Y, r, n), n, t); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ conv2d_nhwc */ +/* An image convolution as GEMMs over patch rows. x [Hin, Win * cin] and y [Ho, Wo * cout] are + * images whose sizes come from the operands, rows at their own pitch and channels contiguous, as + * libref reads them; w is PyTorch's [cout, cin, k, k] and b [cout]. + * + * The weight is re-laid once per launch as [cout][kh][kw][cin], so an output pixel's patch row is + * its k * k input pixels' channel runs back to back: k * k contiguous copies, zeros outside the + * image, the upsample read as x[y / 2, x / 2]. A band of output rows' patches is one gemm_nt_into + * call (A the patches, B the weight, the bias added before the one rounding), which takes the bf16 + * outer-product path where the CPU has AVX512_BF16. A 1 x 1 convolution reads x itself as A. A + * layer narrower than one 48-column panel (the decoder's last, four channels) computes + * y^T = W A^T into f32 instead, so the parallel axis is the pixels rather than four channels, and + * adds the bias as it rounds into y. + * + * Patch rows stay in x's dtype when it is bf16 (exact copies) and are f32 otherwise; the weight + * likewise. They live in thread_local vectors that keep their high-water size, so the GEMM's own + * scratch arenas stay free for it. */ +AVX_KERNEL(conv2d_nhwc) { + if (!rad_args_have(a, 4)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *W = &a->t[1], *B = &a->t[2], *Y = &a->t[3]; + const int64_t cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0), k = p_int(a, "k", 0); + const int64_t stride = p_int(a, "stride", 1), up = p_int(a, "up", 1); + const char* pad = p_str(a, "pad", "same"); + const bool down = pad && !std::strcmp(pad, "down"); + if (cin <= 0 || cout <= 0 || k <= 0 || stride <= 0 || up <= 0) return RAD_E_SHAPE; + if (X->rank != 2 || Y->rank != 2 || X->shape[1] % cin || Y->shape[1] % cout) return RAD_E_SHAPE; + const int64_t Hin = X->shape[0], Win = X->shape[1] / cin; + const int64_t Ho = Y->shape[0], Wo = Y->shape[1] / cout; + if (Hin <= 0 || Win <= 0 || Ho <= 0 || Wo <= 0) return RAD_E_SHAPE; + const int64_t Hv = Hin * up, Wv = Win * up; + const int64_t pt = down ? 0 : k / 2, pb = down ? 1 : k / 2; + if ((Hv + pt + pb - k) / stride + 1 != Ho || (Wv + pt + pb - k) / stride + 1 != Wo) + return RAD_E_SHAPE; + if (numel(W) < cout * cin * k * k || numel(B) < cout) return RAD_E_SHAPE; + const int64_t xr = X->stride[0], yr = Y->stride[0]; + const int64_t KK = k * k * cin; + const bool xb = X->dtype == RAD_BF16; + const uint32_t adt = xb ? (uint32_t)RAD_BF16 : (uint32_t)RAD_F32; + const size_t ael = xb ? 2 : 4; + const bool narrow = cout < 48; + static thread_local std::vector wbuf, pbuf; + static thread_local std::vector ybuf, bbuf; + + /* ---- the weight, [cout][kh][kw][cin] */ + const bool wb16 = W->dtype == RAD_BF16; + const uint32_t wdt = wb16 ? (uint32_t)RAD_BF16 : (uint32_t)RAD_F32; + const size_t wel = wb16 ? 2 : 4; + const bool w_as_is = k == 1 && (wb16 || W->dtype == RAD_F32); + if (!w_as_is) { + wbuf.resize((size_t)(cout * KK) * wel + 64); + uint8_t* wp = wbuf.data(); + AVX_PARALLEL_FOR_IF(cout * KK >= AVX_PAR_MIN) + for (int64_t co = 0; co < cout; ++co) + for (int64_t ci = 0; ci < cin; ++ci) + for (int64_t t = 0; t < k * k; ++t) { + const int64_t src = (co * cin + ci) * k * k + t, dst = co * KK + t * cin + ci; + if (wb16) ((uint16_t*)wp)[dst] = ((const uint16_t*)W->data)[src]; + else ((float*)wp)[dst] = ld_elem(W->data, W->dtype, src); + } + } + RadTensor wt{}; + wt.data = w_as_is ? W->data : (void*)wbuf.data(); + wt.dtype = wdt; + wt.rank = 2; + wt.shape[0] = cout; wt.shape[1] = KK; + wt.stride[0] = KK; wt.stride[1] = 1; + + /* ---- bands of whole output rows, or one row a band when y's rows are not back to back */ + const bool y_dense = yr == Wo * cout; + const bool direct = k == 1 && stride == 1 && up == 1 && !down && xr == Win * cin && + (xb || X->dtype == RAD_F32); + /* A band's patches: at least 8 Mi elements (thousands of pixels, enough M for the GEMM's + * tiles to fill the threads) and eight times the weight, so the GEMM's per-call weight pack + * is amortised, but at most 32 Mi (64 MiB of bf16 the buffer keeps after the call). */ + int64_t band = Ho; + if (!direct) { + const int64_t want = std::min((int64_t)1 << 25, + std::max((int64_t)1 << 23, 8 * cout * KK)); + band = std::max(1, want / std::max(1, Wo * KK)); + } + if (!y_dense) band = 1; + band = std::min(band, Ho); + if (!direct) pbuf.resize((size_t)(band * Wo * KK) * ael + 64); + if (narrow) { + ybuf.resize((size_t)(band * Wo * cout) + 16); + bbuf.resize((size_t)cout + 16); + for (int64_t co = 0; co < cout; ++co) bbuf[(size_t)co] = ldt(B, co); + } + char* pp = (char*)pbuf.data(); + float* yp = ybuf.data(); + const float* bp = bbuf.data(); + for (int64_t oy0 = 0; oy0 < Ho; oy0 += band) { + const int64_t nb = std::min(band, Ho - oy0), P = nb * Wo; + RadTensor at{}; + at.dtype = adt; + at.rank = 2; + at.shape[0] = P; at.shape[1] = KK; + at.stride[0] = KK; at.stride[1] = 1; + if (direct) { + at.data = (char*)X->data + (size_t)(oy0 * xr) * ael; + } else { + at.data = pp; + AVX_PARALLEL_FOR_IF(P * KK >= AVX_PAR_MIN) + for (int64_t p = 0; p < P; ++p) { + const int64_t oy = oy0 + p / Wo, ox = p % Wo; + char* dst = pp + (size_t)(p * KK) * ael; + for (int64_t kh = 0; kh < k; ++kh) { + const int64_t iy = oy * stride + kh - pt; + for (int64_t kw = 0; kw < k; ++kw) { + const int64_t ix = ox * stride + kw - pt; + char* d = dst + (size_t)((kh * k + kw) * cin) * ael; + if (iy < 0 || iy >= Hv || ix < 0 || ix >= Wv) { + std::memset(d, 0, (size_t)cin * ael); + continue; + } + const int64_t xo = (iy / up) * xr + (ix / up) * cin; + if (xb) std::memcpy(d, (const uint16_t*)X->data + xo, (size_t)cin * 2); + else row_to_f32(X->dtype, byte_at(X->data, X->dtype, xo), (float*)d, cin); + } + } + } + } + RadTensor yt{}; + yt.rank = 2; + if (narrow) { + /* y^T [cout, P] = W A^T into f32 pixel-major rows, then the bias and the rounding. */ + yt.data = yp; + yt.dtype = RAD_F32; + yt.shape[0] = cout; yt.shape[1] = P; + yt.stride[0] = 1; yt.stride[1] = cout; + const int st = gemm_nt_into(&wt, &at, nullptr, &yt, cout, P, KK); + if (st < 0) return st; + AVX_PARALLEL_FOR_IF(P * cout >= AVX_PAR_MIN) + for (int64_t p = 0; p < P; ++p) { + float* row = yp + p * cout; + add_rows(row, bp, cout); + const int64_t yo = (oy0 + p / Wo) * yr + (p % Wo) * cout; + row_from_f32(Y->dtype, row, (void*)byte_at(Y->data, Y->dtype, yo), cout); + } + } else { + yt.data = (void*)byte_at(Y->data, Y->dtype, oy0 * yr); + yt.dtype = Y->dtype; + yt.shape[0] = P; yt.shape[1] = cout; + yt.stride[0] = cout; yt.stride[1] = 1; + const int st = gemm_nt_into(&at, &wt, B, &yt, P, cout, KK); + if (st < 0) return st; + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ l2norm_chan */ +/* n1 = bf16(x / max(||x||, 1e-12)), n2 = bf16(n1 * sqrt(n)), y = bf16(n2 * gamma), then `act` + * none or silu (bf16(y * sigmoid(y))), the roundings in y's dtype. */ +AVX_KERNEL(l2norm_chan) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *G = &a->t[1], *Y = &a->t[2]; + const int64_t n = p_int(a, "n", 0); + if (n <= 0 || numel(G) < n) return RAD_E_SHAPE; + const char* act = p_str(a, "act", "none"); + const bool silu = act && !std::strcmp(act, "silu"); + if (!silu && act && std::strcmp(act, "none")) return RAD_E_INVAL; + const int64_t rows = rows_of(Y, n); + if (rows <= 0 || rows_of(X, n) < rows) return RAD_E_SHAPE; + const float sq = (float)std::sqrt((double)n); + const uint32_t dt = Y->dtype; + /* gamma read at linear offsets, as libref reads its [C, 1, 1(, 1)] weight. */ + float* gam = (float*)scratch_raw((size_t)(n + 16) * sizeof(float)); + for (int64_t c = 0; c < n; ++c) gam[c] = ld_elem(G->data, G->dtype, c); + + AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + float* buf = scratch_f32((size_t)(3 * n + 48)); + float *xs = buf, *v = buf + n + 16, *tmp = v + n + 16; + const float* x = in_row(X, rowoff(X, r, n), n, xs); + const float nrm = std::max(std::sqrt(row_sumsq(x, n)), 1e-12f); + const vf vn = vf_set1(nrm), vq = vf_set1(sq); + int64_t c = 0; + for (; c + VF_N <= n; c += VF_N) vf_storeu(v + c, vf_div(vf_loadu(x + c), vn)); + for (; c < n; ++c) v[c] = x[c] / nrm; + narrow_row(dt, v, n, tmp); + for (c = 0; c + VF_N <= n; c += VF_N) vf_storeu(v + c, vf_mul(vf_loadu(v + c), vq)); + for (; c < n; ++c) v[c] *= sq; + narrow_row(dt, v, n, tmp); + mul_rows(v, gam, n); + narrow_row(dt, v, n, tmp); + if (silu) { + const vf one = vf_set1(1.0f); + for (c = 0; c + VF_N <= n; c += VF_N) { + const vf y = vf_loadu(v + c); + vf_storeu(v + c, vf_div(y, vf_add(one, vf_exp(vf_sub(vf_zero(), y))))); + } + for (; c < n; ++c) v[c] = v[c] / (1.0f + sc_exp(-v[c])); + } + out_row(Y, rowoff(Y, r, n), n, v); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ d2s_add / s2d_avg_add */ +/* d2s_add: y [2H, 2W * cout] += x [H, W * cin] repeated and dealt into 2x2 blocks, + * y[2r+i, 2c+j, o] += x[r, c, (o F + off + 2i + j) / rep] (docs/OPS.md). Output row by output row: + * the input row and the output row in f32, each output pixel's channels a gather of its input + * pixel's through a per-(i, j) channel map, which is the identity when cin == cout. */ +AVX_KERNEL(d2s_add) { + if (!rad_args_have(a, 2)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *Y = &a->t[1]; + const int64_t cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0), ft = p_int(a, "ft", 1); + if (cin <= 0 || cout <= 0 || (ft != 1 && ft != 2)) return RAD_E_SHAPE; + if (X->rank != 2 || Y->rank != 2 || X->shape[1] % cin || Y->shape[1] % cout) return RAD_E_SHAPE; + const int64_t H = X->shape[0], W = X->shape[1] / cin; + if (H <= 0 || W <= 0) return RAD_E_SHAPE; + if (Y->shape[0] != 2 * H || Y->shape[1] / cout != 2 * W) return RAD_E_SHAPE; + const int64_t F = 4 * ft, off = ft == 2 ? 4 : 0; + if ((cout * F) % cin) return RAD_E_SHAPE; + const int64_t rep = cout * F / cin; + const int64_t xr = X->stride[0], yr = Y->stride[0]; + int32_t* map = (int32_t*)scratch_raw((size_t)(4 * cout + 16) * sizeof(int32_t)); + bool ident = true; + for (int64_t ij = 0; ij < 4; ++ij) + for (int64_t o = 0; o < cout; ++o) { + map[ij * cout + o] = (int32_t)((o * F + off + ij) / rep); + ident = ident && map[ij * cout + o] == o; + } + const int64_t xn = W * cin, yn = 2 * W * cout; + + AVX_PARALLEL_FOR_IF(2 * H * yn >= AVX_PAR_MIN) + for (int64_t oy = 0; oy < 2 * H; ++oy) { + float* buf = scratch_f32((size_t)(xn + yn + 32)); + float *xs = buf, *ys = buf + xn + 16; + const float* xrow = in_row(X, (oy / 2) * xr, xn, xs); + const float* yrow = in_row(Y, oy * yr, yn, ys); + if (yrow != ys) std::memcpy(ys, yrow, (size_t)yn * sizeof(float)); + const int64_t i = oy & 1; + for (int64_t ox = 0; ox < 2 * W; ++ox) { + const float* xp = xrow + (ox / 2) * cin; + float* yp = ys + ox * cout; + if (ident) { + add_rows(yp, xp, cout); + continue; + } + const int32_t* m = map + (2 * i + (ox & 1)) * cout; + for (int64_t o = 0; o < cout; ++o) yp[o] += xp[m[o]]; + } + out_row(Y, oy * yr, yn, ys); + } + return RAD_OK; +} + +/* s2d_avg_add: y [H, W * cout] += the mean of each output channel's gs = cin F / cout dealt + * values of x [2H, 2W * cin]; a dealt channel (c, t, i, j) is c F + 4t + 2i + j, and with ft 2 + * the frame t = 0 is the zero frame the mean still counts. Each sum runs in libref's order, over + * the two input rows of an output row widened once. */ +AVX_KERNEL(s2d_avg_add) { + if (!rad_args_have(a, 2)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *Y = &a->t[1]; + const int64_t cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0), ft = p_int(a, "ft", 1); + if (cin <= 0 || cout <= 0 || (ft != 1 && ft != 2)) return RAD_E_SHAPE; + if (X->rank != 2 || Y->rank != 2 || X->shape[1] % cin || Y->shape[1] % cout) return RAD_E_SHAPE; + const int64_t H = Y->shape[0], W = Y->shape[1] / cout; + if (H <= 0 || W <= 0) return RAD_E_SHAPE; + if (X->shape[0] != 2 * H || X->shape[1] / cin != 2 * W) return RAD_E_SHAPE; + const int64_t F = 4 * ft; + if ((cin * F) % cout) return RAD_E_SHAPE; + const int64_t gs = cin * F / cout; + const int64_t xr = X->stride[0], yr = Y->stride[0]; + const int64_t xn = 2 * W * cin, yn = W * cout; + /* Each output channel's dealt values, as offsets into the two widened input rows (the second + * row starts at xn); -1 marks a zero-frame value. */ + int32_t* rel = (int32_t*)scratch_raw((size_t)(cout * gs + 16) * sizeof(int32_t)); + for (int64_t o = 0; o < cout; ++o) + for (int64_t gg = 0; gg < gs; ++gg) { + const int64_t g = o * gs + gg; + const int64_t c = g / F, rem = g % F, t = rem / 4, i = (rem % 4) / 2, j = rem % 2; + rel[o * gs + gg] = (ft == 2 && t == 0) ? -1 : (int32_t)(i * xn + j * cin + c); + } + const float fgs = (float)gs; + + AVX_PARALLEL_FOR_IF(H * yn * gs >= AVX_PAR_MIN) + for (int64_t oy = 0; oy < H; ++oy) { + float* buf = scratch_f32((size_t)(2 * xn + 2 * yn + 64)); + float *xs = buf, *ys = buf + 2 * xn + 16, *tmp = ys + yn + 16; + for (int64_t i = 0; i < 2; ++i) { + const float* row = in_row(X, (2 * oy + i) * xr, xn, xs + i * xn); + if (row != xs + i * xn) std::memcpy(xs + i * xn, row, (size_t)xn * sizeof(float)); + } + for (int64_t ox = 0; ox < W; ++ox) { + const float* xp = xs + 2 * ox * cin; + for (int64_t o = 0; o < cout; ++o) { + const int32_t* rr = rel + o * gs; + float acc = 0.0f; + for (int64_t gg = 0; gg < gs; ++gg) + if (rr[gg] >= 0) acc += xp[rr[gg]]; + tmp[ox * cout + o] = acc / fgs; + } + } + narrow_row(Y->dtype, tmp, yn, ys); + const float* yrow = in_row(Y, oy * yr, yn, ys); + add_rows(tmp, yrow, yn); + out_row(Y, oy * yr, yn, tmp); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ to_rgba8 */ +/* v = clamp(x, -1, 1), u = clamp(bf16(bf16(v / 2) + 0.5), 0, 1), byte = round-half-even(u * 255), + * as diffusers' postprocess makes them. A NaN pixel is 0, as libref's conversion leaves it. */ +AVX_KERNEL(to_rgba8) { + if (!rad_args_have(a, 2)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *Y = &a->t[1]; + const int64_t n = p_int(a, "n", 0); + if (n <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_of(Y, n); + if (rows <= 0 || rows_of(X, n) < rows || Y->dtype != RAD_U8) return RAD_E_SHAPE; + + AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + float* buf = scratch_f32((size_t)(3 * n + 48)); + float *xs = buf, *u = buf + n + 16, *tmp = u + n + 16; + const float* x = in_row(X, rowoff(X, r, n), n, xs); + const vf lo = vf_set1(-1.0f), hi = vf_set1(1.0f), half = vf_set1(0.5f); + int64_t c = 0; + /* max(x, -1) takes -1 for a NaN lane, which ends at byte 0. */ + for (; c + VF_N <= n; c += VF_N) + vf_storeu(u + c, vf_mul(vf_min(vf_max(vf_loadu(x + c), lo), hi), half)); + for (; c < n; ++c) { + float v = x[c]; + v = v < -1.0f ? -1.0f : (v > 1.0f ? 1.0f : v); + u[c] = v != v ? -0.5f : v * 0.5f; + } + narrow_row(RAD_BF16, u, n, tmp); + for (c = 0; c + VF_N <= n; c += VF_N) vf_storeu(u + c, vf_add(vf_loadu(u + c), half)); + for (; c < n; ++c) u[c] += 0.5f; + narrow_row(RAD_BF16, u, n, tmp); + const vf zero = vf_zero(), k255 = vf_set1(255.0f); + for (c = 0; c + VF_N <= n; c += VF_N) + vf_storeu(u + c, vf_mul(vf_min(vf_max(vf_loadu(u + c), zero), hi), k255)); + for (; c < n; ++c) { + const float v = u[c] < 0.0f ? 0.0f : (u[c] > 1.0f ? 1.0f : u[c]); + u[c] = v * 255.0f; + } + const int64_t yb = rowoff(Y, r, n), ys = laststride(Y); + uint8_t* out = (uint8_t*)Y->data; + c = 0; + if (ys == 1) { +#if AVX_LEVEL == 3 + for (; c + 16 <= n; c += 16) + _mm_storeu_si128((__m128i*)(out + yb + c), + _mm512_cvtepi32_epi8(_mm512_cvtps_epi32(_mm512_loadu_ps(u + c)))); +#elif AVX_LEVEL == 2 + for (; c + 8 <= n; c += 8) { + const __m256i q = _mm256_cvtps_epi32(_mm256_loadu_ps(u + c)); + __m128i p = _mm_packus_epi32(_mm256_castsi256_si128(q), _mm256_extracti128_si256(q, 1)); + p = _mm_packus_epi16(p, p); + _mm_storel_epi64((__m128i*)(out + yb + c), p); + } +#endif + } + for (; c < n; ++c) out[yb + c * ys] = (uint8_t)std::nearbyintf(u[c]); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ gelu_tanh */ +/* 0.5 x (1 + tanh(sqrt(2/pi) (x + 0.044715 x^3))), tanh as (1 - e^(-2z)) / (1 + e^(-2z)) on + * vf_exp, torch's form (avx_elementwise.cpp: act_mul says why that form). */ +AVX_KERNEL(gelu_tanh) { + if (!rad_args_have(a, 2)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *Y = &a->t[1]; + const int64_t n = p_int(a, "n", 0); + if (n <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_of(Y, n); + if (rows <= 0 || rows_of(X, n) < rows) return RAD_E_SHAPE; + + AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + float* buf = scratch_f32((size_t)(2 * n + 32)); + float *xs = buf, *y = buf + n + 16; + const float* x = in_row(X, rowoff(X, r, n), n, xs); + const vf one = vf_set1(1.0f), half = vf_set1(0.5f); + const vf m2k0 = vf_set1(-2.0f * 0.7978845608028654f), k1 = vf_set1(0.044715f); + int64_t c = 0; + for (; c + VF_N <= n; c += VF_N) { + const vf g = vf_loadu(x + c); + const vf inner = vf_fma(vf_mul(k1, g), vf_mul(g, g), g); + const vf e = vf_exp(vf_mul(m2k0, inner)); + const vf t = vf_div(vf_sub(one, e), vf_add(one, e)); + vf_storeu(y + c, vf_mul(vf_mul(half, g), vf_add(one, t))); + } + for (; c < n; ++c) { + const float g = x[c]; + y[c] = 0.5f * g * (1.0f + sc_tanh(0.7978845608028654f * (g + 0.044715f * g * g * g))); + } + out_row(Y, rowoff(Y, r, n), n, y); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ scatter_add_rows */ +/* x[idx[i]] = x[idx[i]] + v[i], rounded to x's dtype; a negative index adds nothing. Every index + * is checked before the first write. Rows run in parallel only when no destination repeats: a + * repeated one adds in index order, as libref adds it. */ +AVX_KERNEL(scatter_add_rows) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const RadTensor *V = &a->t[0], *I = &a->t[1], *X = &a->t[2]; + const int64_t n = p_int(a, "n", 0); + if (n <= 0) return RAD_E_SHAPE; + const int64_t M = rows_of(V, n), dst_rows = rows_of(X, n); + if (M <= 0 || numel(I) < M) return RAD_E_SHAPE; + for (int64_t m = 0; m < M; ++m) + if (ldi(I, offlin(I, m)) >= dst_rows) return RAD_E_INVAL; + uint8_t* seen = (uint8_t*)scratch_raw((size_t)dst_rows + 64); + std::memset(seen, 0, (size_t)dst_rows); + bool distinct = true; + for (int64_t m = 0; m < M && distinct; ++m) { + const int64_t r = ldi(I, offlin(I, m)); + if (r < 0) continue; + distinct = !seen[r]; + seen[r] = 1; + } + + auto add_row = [&](int64_t m) { + const int64_t r = ldi(I, offlin(I, m)); + if (r < 0) return; + float* buf = scratch_f32((size_t)(2 * n + 32)); + float *vs = buf, *xs = buf + n + 16; + const float* v = in_row(V, rowoff(V, m, n), n, vs); + const float* x = in_row(X, rowoff(X, r, n), n, xs); + if (x != xs) std::memcpy(xs, x, (size_t)n * sizeof(float)); + add_rows(xs, v, n); + out_row(X, rowoff(X, r, n), n, xs); + }; + if (!distinct) { + for (int64_t m = 0; m < M; ++m) add_row(m); + return RAD_OK; + } + AVX_PARALLEL_FOR_IF(M * n >= AVX_PAR_MIN) + for (int64_t m = 0; m < M; ++m) add_row(m); + return RAD_OK; +} diff --git a/libavx/avx_gen_attn.cpp b/libavx/avx_gen_attn.cpp new file mode 100644 index 00000000..050055ec --- /dev/null +++ b/libavx/avx_gen_attn.cpp @@ -0,0 +1,670 @@ +/* avx_gen_attn.cpp -- attn_prefix_self: attention over a cached conditioning prefix and the pass's + * own rows (docs/OPS.md, "Image generation"), the diffusion transformer's attention. + * + * Keys of entry s, in order: its `seqused[s]` prefix positions in the paged cache, every one + * visible, then its own rows [cu[s], cu[s+1]) beside q, of which own row i sees j <= i with + * `causal` and all of them otherwise. A prefix key in a missing block (a negative table entry) is + * a zero key and a zero value that still takes its share of the softmax, as libref reads it. + * + * Flash-attention form. Each (entry, kv head)'s key sequence is packed once per launch into + * 64-key tiles, then a task is (entry, kv head, 32 query positions) with the gqa query heads of + * that kv head: per tile, S = Q K^T as broadcast-against-tile products (no horizontal sums), the + * causal mask, the online softmax (running max moved at tile boundaries), then O += P V. Packs are + * made for a group of kv heads at a time, at most ~64 MiB, so the packed tiles of the heads in + * flight stay near cache instead of all heads' at once. + * + * bf16 (AVX512_BF16 and bf16 q, k, v, cache, head_dim a multiple of 64): vdpbf16ps for both + * products, P rounded to bf16 for P V as PyTorch's CPU flash attention does (and + * avx_attn.cpp: attn_dense_bf16). + * f32 every other case: f32 tiles, vf FMAs, P in f32. + * + * The int8 score form (`qk` "i8"): the query and each prefix key are quantised per (row, head) by + * libref's rule (scale amax / 127, 1 for an all-zero row; code rint(clamp(x / scale, +-127))), the + * own keys arrive as codes and scales, and a score is ((dot * sq) * sk) * scale with the integer + * dot exact in f32 (|dot| < 2^24 up to head_dim 1024). Codes are exact in bf16 too, so the bf16 + * path computes the same scores; only P V differs from libref, by the softmax order and P's + * rounding. + * + * Results differ from libref's two-pass softmax in summation order and the rescales' roundings, + * within the attention tolerance. Each output row is one task's, so they do not depend on the + * thread count. + */ +#include "avx_vec.h" +#include "avx_common.h" + +#include +#include + +using namespace avx; + +namespace { + +/* The widest head, libref's (its stack rows, and the int8 dot's exact range). */ +enum { PS_HD_MAX = 1024 }; +/* Keys per tile and query positions per task. */ +enum { KT = 64, QB = 32 }; +/* The packed tiles of the kv heads in flight. */ +constexpr int64_t kPackBudget = (int64_t)64 << 20; + +struct Geo { + const RadTensor *q, *k, *v, *kv, *bt, *su, *cu, *o, *kdes, *vdes, *k8, *ks; + bool i8; + int causal; + int64_t hd, gqa, kvh, qh, n_seq, bs, max_blocks, bt_rs, bt_cs; + int64_t q_rs, k_rs, v_rs, o_rs, k8_rs, ks_rs, sb, sh, so; + float scale; +}; + +inline int64_t cu_at(const RadTensor* cu, int64_t i) { return ldi(cu, offlin(cu, i)); } + +/* One (entry, kv head)'s key sequence: P prefix keys then the entry's own rows from b0. */ +struct Seq { + int64_t s, kh, P, b0, len, nk, ntile; + size_t off; /* bytes into the pack */ +}; + +/* libref's per-row int8 rule: codes into `code` (may be `x`), the scale returned. */ +inline float q8_row(const float* x, int64_t n, float* code) { + const float am = row_amax(x, n); + const float sc = am > 0.0f ? am * (1.0f / 127.0f) : 1.0f; + const float inv = 1.0f / sc; + const vf vi = vf_set1(inv), lo = vf_set1(-127.0f), hi = vf_set1(127.0f); + int64_t d = 0; +#if AVX_LEVEL >= 1 + for (; d + VF_N <= n; d += VF_N) { + const vf c = vf_min(vf_max(vf_mul(vf_loadu(x + d), vi), lo), hi); +#if AVX_LEVEL == 3 + vf_storeu(code + d, _mm512_roundscale_ps(c, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC)); +#else + vf_storeu(code + d, _mm256_round_ps(c, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC)); +#endif + } +#else + (void)vi; (void)lo; (void)hi; +#endif + for (; d < n; ++d) code[d] = std::rint(std::min(std::max(x[d] * inv, -127.0f), 127.0f)); + return sc; +} + +/* Key (or value) j of `q`'s sequence as f32 into out[0, hd). A prefix key carries its entry's + * descale per element, as libref applies it. */ +void key_f32(const Geo& g, const Seq& q, int64_t j, bool val, float* out) { + const int64_t hd = g.hd; + if (j < q.P) { + const int64_t blk = ldi(g.bt, q.s * g.bt_rs + (j / g.bs) * g.bt_cs); + if (blk < 0) { + for (int64_t d = 0; d < hd; ++d) out[d] = 0.0f; + return; + } + const int64_t base = blk * g.sb + q.kh * g.sh + (j % g.bs) * g.so + (val ? hd : 0); + row_to_f32(g.kv->dtype, byte_at(g.kv->data, g.kv->dtype, base), out, hd); + const RadTensor* des = val ? g.vdes : g.kdes; + const float m = des ? ldt(des, q.s * g.kvh + q.kh) : 1.0f; + if (m != 1.0f) + for (int64_t d = 0; d < hd; ++d) out[d] *= m; + return; + } + const int64_t row = q.b0 + j - q.P; + const RadTensor* t = val ? g.v : g.k; + const int64_t base = row * (val ? g.v_rs : g.k_rs) + q.kh * hd; + row_to_f32(t->dtype, byte_at(t->data, t->dtype, base), out, hd); +} + +/* The int8 form's key j: codes into out and its scale. */ +float key_i8(const Geo& g, const Seq& q, int64_t j, float* out) { + if (j < q.P) { + key_f32(g, q, j, false, out); + return q8_row(out, g.hd, out); + } + const int64_t row = q.b0 + j - q.P; + row_to_f32(g.k8->dtype, byte_at(g.k8->data, g.k8->dtype, row * g.k8_rs + q.kh * g.hd), out, + g.hd); + return ldt(g.ks, row * g.ks_rs + q.kh); +} + +/* The keys a task's last query can see: all, or with `causal` up to its own row. */ +inline int64_t visible_keys(const Geo& g, const Seq& q, int64_t q1) { + return g.causal ? std::min(q.nk, q.P + q1) : q.nk; +} + +/* S *= scale, or the int8 form's ((S * sq[r]) * sk) * scale; then -inf past the tile's last key + * and, with `causal`, for own keys after a row's position. */ +void finish_scores(const Geo& g, const Seq& q, float* S, int64_t R, int64_t t, int64_t q0, + const float* sq, const float* sk) { + const vf vs = vf_set1(g.scale); + for (int64_t r = 0; r < R; ++r) { + float* sr = S + r * KT; + if (g.i8) { + const vf vq = vf_set1(sq[r]); + int64_t j = 0; + for (; j + VF_N <= KT; j += VF_N) + vf_storeu(sr + j, vf_mul(vf_mul(vf_mul(vf_loadu(sr + j), vq), vf_loadu(sk + j)), vs)); + for (; j < KT; ++j) sr[j] = ((sr[j] * sq[r]) * sk[j]) * g.scale; + } else { + int64_t j = 0; + for (; j + VF_N <= KT; j += VF_N) vf_storeu(sr + j, vf_mul(vf_loadu(sr + j), vs)); + for (; j < KT; ++j) sr[j] *= g.scale; + } + const int64_t i = q0 + r / g.gqa; + const int64_t end = g.causal ? std::min(q.nk, q.P + i + 1) : q.nk; + for (int64_t j = std::max(0, end - t * KT); j < KT; ++j) sr[j] = -INFINITY; + } +} + +/* The online softmax over one tile of R rows: m, l and acc (rows of `ld`) rescaled at a new + * maximum, S replaced by exp(S - m). A row with nothing visible in the tile becomes zeros. */ +void softmax_tile(float* S, int64_t R, float* m, float* l, float* acc, int64_t ld, int64_t width) { + for (int64_t r = 0; r < R; ++r) { + float* sr = S + r * KT; + const float tmax = row_max(sr, KT); + if (tmax == -INFINITY) { + for (int64_t j = 0; j < KT; ++j) sr[j] = 0.0f; + continue; + } + if (tmax > m[r]) { + const float alpha = m[r] == -INFINITY ? 0.0f : sc_exp(m[r] - tmax); + if (alpha != 1.0f) { + float* ar = acc + r * ld; + const vf va = vf_set1(alpha); + int64_t d = 0; + for (; d + VF_N <= width; d += VF_N) vf_storeu(ar + d, vf_mul(vf_loadu(ar + d), va)); + for (; d < width; ++d) ar[d] *= alpha; + l[r] *= alpha; + } + m[r] = tmax; + } + const vf vm = vf_set1(m[r]); + int64_t j = 0; + for (; j + VF_N <= KT; j += VF_N) vf_storeu(sr + j, vf_exp(vf_sub(vf_loadu(sr + j), vm))); + for (; j < KT; ++j) sr[j] = sc_exp(sr[j] - m[r]); + l[r] += row_sum(sr, KT); + } +} + +/* out = acc / l (0 for a row that saw nothing), stored to `o` at its row and head. */ +void store_rows(const Geo& g, const Seq& q, int64_t q0, int64_t R, float* acc, int64_t ld, + const float* m, const float* l) { + for (int64_t r = 0; r < R; ++r) { + const int64_t row = q.b0 + q0 + r / g.gqa, h = q.kh * g.gqa + r % g.gqa; + float* ar = acc + r * ld; + const float inv = (m[r] == -INFINITY || l[r] <= 0.0f) ? 0.0f : 1.0f / l[r]; + const vf vi = vf_set1(inv); + int64_t d = 0; + for (; d + VF_N <= g.hd; d += VF_N) vf_storeu(ar + d, vf_mul(vf_loadu(ar + d), vi)); + for (; d < g.hd; ++d) ar[d] *= inv; + out_row(g.o, row * g.o_rs + h * g.hd, g.hd, ar); + } +} + +/* ================================================================== the f32 form + * + * A tile packed as Kt [hd][64] (each dimension's 64 keys contiguous, so a query element broadcast + * against four vectors gives 4 * VF_N scores) and V [64][hp], hp the head rounded up to 4 * VF_N + * with zero columns, so P V runs whole vectors. The int8 form's key scales follow, [64]. */ +#if AVX_LEVEL == 3 +constexpr int RB = 6; +#else +constexpr int RB = 2; +#endif +constexpr int64_t CK = 4 * VF_N; + +/* The next row block of a tile: `top` rows, except that the last two blocks are kept at four or + * more (32 rows go 6 6 6 6 4 4). A one- or two-row block has four or eight accumulators, too few + * to cover the dot product's latency, and would cost nearly as much as a full one. */ +inline int row_block(int64_t left, int top) { + if (top < 4) return left >= top ? top : (int)left; + if (left >= top + 4 || left == top) return top; + return left > top ? (int)(left - 4) : (int)left; +} + +/* fn(args...) for a block of 1..6 rows. */ +#define PS_ROWS(fn, mb, ...) \ + switch (mb) { \ + case 6: fn<6>(__VA_ARGS__); break; \ + case 5: fn<5>(__VA_ARGS__); break; \ + case 4: fn<4>(__VA_ARGS__); break; \ + case 3: fn<3>(__VA_ARGS__); break; \ + case 2: fn<2>(__VA_ARGS__); break; \ + default: fn<1>(__VA_ARGS__); break; \ + } + +inline int64_t f32_hp(int64_t hd) { return (hd + CK - 1) / CK * CK; } +inline size_t f32_tile_floats(int64_t hd) { return (size_t)(hd * KT + KT * f32_hp(hd) + KT); } + +void pack_tile_f32(const Geo& g, const Seq& q, int64_t t, float* tile, float* row) { + const int64_t hd = g.hd, hp = f32_hp(hd); + float* Kt = tile; + float* Vt = tile + hd * KT; + float* sk = Vt + KT * hp; + for (int64_t jj = 0; jj < KT; ++jj) { + const int64_t j = t * KT + jj; + float* vr = Vt + jj * hp; + if (j >= q.nk) { + for (int64_t d = 0; d < hd; ++d) Kt[d * KT + jj] = 0.0f; + for (int64_t d = 0; d < hp; ++d) vr[d] = 0.0f; + sk[jj] = 0.0f; + continue; + } + sk[jj] = g.i8 ? key_i8(g, q, j, row) : (key_f32(g, q, j, false, row), 1.0f); + for (int64_t d = 0; d < hd; ++d) Kt[d * KT + jj] = row[d]; + key_f32(g, q, j, true, vr); + for (int64_t d = hd; d < hp; ++d) vr[d] = 0.0f; + } +} + +/* S[i][0, 64) = Q[i] . K for MB_ rows of Q (pitch ldq) over the packed Kt. */ +template +inline void qk_f32(const float* Q, int64_t ldq, const float* Kt, int64_t hd, float* S) { + for (int64_t c = 0; c < KT; c += CK) { + vf acc[MB_][4]; + for (int i = 0; i < MB_; ++i) + for (int v = 0; v < 4; ++v) acc[i][v] = vf_zero(); + for (int64_t d = 0; d < hd; ++d) { + const float* kr = Kt + d * KT + c; + const vf k0 = vf_loadu(kr), k1 = vf_loadu(kr + VF_N); + const vf k2 = vf_loadu(kr + 2 * VF_N), k3 = vf_loadu(kr + 3 * VF_N); + for (int i = 0; i < MB_; ++i) { + const vf b = vf_set1(Q[i * ldq + d]); + acc[i][0] = vf_fma(b, k0, acc[i][0]); + acc[i][1] = vf_fma(b, k1, acc[i][1]); + acc[i][2] = vf_fma(b, k2, acc[i][2]); + acc[i][3] = vf_fma(b, k3, acc[i][3]); + } + } + for (int i = 0; i < MB_; ++i) + for (int v = 0; v < 4; ++v) vf_storeu(S + i * KT + c + v * VF_N, acc[i][v]); + } +} + +/* acc[i][0, hp) += P[i] . V for MB_ rows over the tile's `kt` keys. */ +template +inline void pv_f32(float* acc, int64_t hp, const float* Pm, const float* Vt, int64_t kt) { + for (int64_t c = 0; c < hp; c += CK) { + vf o[MB_][4]; + for (int i = 0; i < MB_; ++i) + for (int v = 0; v < 4; ++v) o[i][v] = vf_loadu(acc + i * hp + c + v * VF_N); + for (int64_t j = 0; j < kt; ++j) { + const float* vr = Vt + j * hp + c; + const vf v0 = vf_loadu(vr), v1 = vf_loadu(vr + VF_N); + const vf v2 = vf_loadu(vr + 2 * VF_N), v3 = vf_loadu(vr + 3 * VF_N); + for (int i = 0; i < MB_; ++i) { + const vf p = vf_set1(Pm[i * KT + j]); + o[i][0] = vf_fma(p, v0, o[i][0]); + o[i][1] = vf_fma(p, v1, o[i][1]); + o[i][2] = vf_fma(p, v2, o[i][2]); + o[i][3] = vf_fma(p, v3, o[i][3]); + } + } + for (int i = 0; i < MB_; ++i) + for (int v = 0; v < 4; ++v) vf_storeu(acc + i * hp + c + v * VF_N, o[i][v]); + } +} + +void task_f32(const Geo& g, const Seq& q, const uint8_t* pack, int64_t q0, int64_t q1) { + const int64_t hd = g.hd, hp = f32_hp(hd), R = (q1 - q0) * g.gqa, R_MAX = QB * g.gqa; + float* frame = scratch_f32((size_t)(R_MAX * hp + R_MAX * hd + R_MAX * KT + 3 * R_MAX + hp) + 64); + float* acc = frame; + float* Q = acc + R_MAX * hp; + float* S = Q + R_MAX * hd; + float* m = S + R_MAX * KT; + float* l = m + R_MAX; + float* sq = l + R_MAX; + for (int64_t r = 0; r < R; ++r) { + const int64_t row = q.b0 + q0 + r / g.gqa, h = q.kh * g.gqa + r % g.gqa; + float* qr = Q + r * hd; + row_to_f32(g.q->dtype, byte_at(g.q->data, g.q->dtype, row * g.q_rs + h * hd), qr, hd); + sq[r] = g.i8 ? q8_row(qr, hd, qr) : 1.0f; + m[r] = -INFINITY; + l[r] = 0.0f; + } + std::memset(acc, 0, sizeof(float) * (size_t)(R * hp)); + const int64_t nvis = visible_keys(g, q, q1); + const size_t tf = f32_tile_floats(hd); + for (int64_t t = 0; t * KT < nvis; ++t) { + const float* tile = (const float*)(pack + q.off) + (size_t)t * tf; + const float* Kt = tile; + const float* Vt = tile + hd * KT; + const float* sk = Vt + KT * hp; + for (int64_t r = 0, mb; r < R; r += mb) { + mb = row_block(R - r, RB); + PS_ROWS(qk_f32, mb, Q + r * hd, hd, Kt, hd, S + r * KT); + } + finish_scores(g, q, S, R, t, q0, sq, sk); + softmax_tile(S, R, m, l, acc, hp, hp); + const int64_t kt = std::min(KT, q.nk - t * KT); + for (int64_t r = 0, mb; r < R; r += mb) { + mb = row_block(R - r, RB); + PS_ROWS(pv_f32, mb, acc + r * hp, hp, S + r * KT, Vt, kt); + } + } + store_rows(g, q, q0, R, acc, hp, m, l); +} + +/* ================================================================== the bf16 form + * + * A tile packed as kp [hd/2][64] u32, key j's dimensions (2d, 2d+1) as one bf16 pair, and + * vp [32][hd] u32, keys (2k, 2k+1) at column d as one pair; the int8 form's key scales follow, + * [64] f32. Codes are integers of at most 127 in magnitude, exact in bf16. */ +#if AVX_LEVEL == 3 +#define PS_BF16 __attribute__((target("avx512f,avx512bw,avx512vl,avx512bf16"))) + +inline size_t bf16_tile_bytes(int64_t hd) { + return (size_t)(hd / 2 * KT) * 4 + (size_t)(KT / 2 * hd) * 4 + (size_t)KT * 4; +} + +/* A key row's hd bf16 values (the cache's or the own rows' own bits, or exact codes), and for the + * int8 form its scale. `row` holds hd floats. */ +float key_bf16(const Geo& g, const Seq& q, int64_t j, bool val, uint16_t* out, float* row) { + const int64_t hd = g.hd; + if (g.i8 && !val) { + const float sk = key_i8(g, q, j, row); + row_from_f32(RAD_BF16, row, out, hd); + return sk; + } + const uint16_t* src = nullptr; + if (j < q.P) { + const int64_t blk = ldi(g.bt, q.s * g.bt_rs + (j / g.bs) * g.bt_cs); + if (blk >= 0) + src = (const uint16_t*)g.kv->data + blk * g.sb + q.kh * g.sh + (j % g.bs) * g.so + + (val ? hd : 0); + } else { + const int64_t r = q.b0 + j - q.P; + src = (const uint16_t*)(val ? g.v : g.k)->data + r * (val ? g.v_rs : g.k_rs) + q.kh * hd; + } + if (src) std::memcpy(out, src, (size_t)hd * 2); + else std::memset(out, 0, (size_t)hd * 2); + return 1.0f; +} + +void pack_tile_bf16(const Geo& g, const Seq& q, int64_t t, uint8_t* tile, float* row, + uint16_t* kv2) { + const int64_t hd = g.hd, D2 = hd / 2; + uint32_t* kp = (uint32_t*)tile; + uint32_t* vp = kp + D2 * KT; + float* sk = (float*)(vp + (KT / 2) * hd); + uint16_t* ka = kv2; + uint16_t* va = kv2 + 2 * hd; + for (int64_t k2 = 0; k2 < KT / 2; ++k2) { + for (int e = 0; e < 2; ++e) { + const int64_t jj = 2 * k2 + e, j = t * KT + jj; + uint16_t* kr = ka + e * hd; + uint16_t* vr = va + e * hd; + if (j >= q.nk) { + std::memset(kr, 0, (size_t)hd * 2); + std::memset(vr, 0, (size_t)hd * 2); + sk[jj] = 0.0f; + continue; + } + sk[jj] = key_bf16(g, q, j, false, kr, row); + key_bf16(g, q, j, true, vr, row); + for (int64_t d2 = 0; d2 < D2; ++d2) + kp[d2 * KT + jj] = (uint32_t)kr[2 * d2] | ((uint32_t)kr[2 * d2 + 1] << 16); + } + uint32_t* vo = vp + k2 * hd; + for (int64_t d = 0; d < hd; ++d) vo[d] = (uint32_t)va[d] | ((uint32_t)va[hd + d] << 16); + } +} + +/* S[i][0, 64) = Q[i] . K over the packed tile, MB_ query rows given as bf16 row pointers. */ +template +PS_BF16 inline void qk_bf16(const uint16_t* const* qr, const uint32_t* kp, int64_t D2, float* S) { + __m512 acc[MB_][4]; +#pragma GCC unroll 8 + for (int i = 0; i < MB_; ++i) +#pragma GCC unroll 4 + for (int v = 0; v < 4; ++v) acc[i][v] = _mm512_setzero_ps(); + for (int64_t d2 = 0; d2 < D2; ++d2) { + const uint32_t* kr = kp + d2 * KT; + const __m512bh b0 = (__m512bh)_mm512_loadu_si512((const void*)(kr)); + const __m512bh b1 = (__m512bh)_mm512_loadu_si512((const void*)(kr + 16)); + const __m512bh b2 = (__m512bh)_mm512_loadu_si512((const void*)(kr + 32)); + const __m512bh b3 = (__m512bh)_mm512_loadu_si512((const void*)(kr + 48)); +#pragma GCC unroll 8 + for (int i = 0; i < MB_; ++i) { + uint32_t pr; + std::memcpy(&pr, qr[i] + 2 * d2, 4); + const __m512bh a = (__m512bh)_mm512_set1_epi32((int)pr); + acc[i][0] = _mm512_dpbf16_ps(acc[i][0], a, b0); + acc[i][1] = _mm512_dpbf16_ps(acc[i][1], a, b1); + acc[i][2] = _mm512_dpbf16_ps(acc[i][2], a, b2); + acc[i][3] = _mm512_dpbf16_ps(acc[i][3], a, b3); + } + } +#pragma GCC unroll 8 + for (int i = 0; i < MB_; ++i) +#pragma GCC unroll 4 + for (int v = 0; v < 4; ++v) _mm512_storeu_ps(S + i * KT + 16 * v, acc[i][v]); +} + +/* acc[i][c0, c0 + 64) += P[i] . V, MB_ rows of bf16 P pairs (pp[i * 32 + k2]) against the + * tile's value pairs. */ +template +PS_BF16 inline void pv_bf16(float* acc, int64_t hd, const uint32_t* pp, const uint32_t* vp, + int64_t K2, int64_t c0) { + __m512 o[MB_][4]; +#pragma GCC unroll 8 + for (int i = 0; i < MB_; ++i) +#pragma GCC unroll 4 + for (int v = 0; v < 4; ++v) o[i][v] = _mm512_loadu_ps(acc + i * hd + c0 + 16 * v); + for (int64_t k2 = 0; k2 < K2; ++k2) { + const uint32_t* vr = vp + k2 * hd + c0; + const __m512bh b0 = (__m512bh)_mm512_loadu_si512((const void*)(vr)); + const __m512bh b1 = (__m512bh)_mm512_loadu_si512((const void*)(vr + 16)); + const __m512bh b2 = (__m512bh)_mm512_loadu_si512((const void*)(vr + 32)); + const __m512bh b3 = (__m512bh)_mm512_loadu_si512((const void*)(vr + 48)); +#pragma GCC unroll 8 + for (int i = 0; i < MB_; ++i) { + const __m512bh a = (__m512bh)_mm512_set1_epi32((int)pp[i * 32 + k2]); + o[i][0] = _mm512_dpbf16_ps(o[i][0], a, b0); + o[i][1] = _mm512_dpbf16_ps(o[i][1], a, b1); + o[i][2] = _mm512_dpbf16_ps(o[i][2], a, b2); + o[i][3] = _mm512_dpbf16_ps(o[i][3], a, b3); + } + } +#pragma GCC unroll 8 + for (int i = 0; i < MB_; ++i) +#pragma GCC unroll 4 + for (int v = 0; v < 4; ++v) _mm512_storeu_ps(acc + i * hd + c0 + 16 * v, o[i][v]); +} + +/* A row of 64 probabilities to 32 bf16 key pairs, round to nearest even. */ +PS_BF16 inline void p_pairs(const float* sr, uint32_t* pr) { + _mm512_storeu_si512((void*)pr, + (__m512i)_mm512_cvtne2ps_pbh(_mm512_loadu_ps(sr + 16), _mm512_loadu_ps(sr))); + _mm512_storeu_si512((void*)(pr + 16), (__m512i)_mm512_cvtne2ps_pbh(_mm512_loadu_ps(sr + 48), + _mm512_loadu_ps(sr + 32))); +} + +PS_BF16 void task_bf16(const Geo& g, const Seq& q, const uint8_t* pack, int64_t q0, int64_t q1) { + const int64_t hd = g.hd, D2 = hd / 2, R = (q1 - q0) * g.gqa, R_MAX = QB * g.gqa; + float* frame = scratch_f32((size_t)(R_MAX * hd + R_MAX * KT + 3 * R_MAX + R_MAX * KT / 2 + + R_MAX * hd / 2 + hd) + 64); + float* acc = frame; + float* S = acc + R_MAX * hd; + float* m = S + R_MAX * KT; + float* l = m + R_MAX; + float* sq = l + R_MAX; + uint32_t* pp = (uint32_t*)(sq + R_MAX); + uint16_t* qcodes = (uint16_t*)(pp + R_MAX * KT / 2); + float* row = (float*)(qcodes + R_MAX * hd); + const uint16_t* qrow[16 * QB]; + for (int64_t r = 0; r < R; ++r) { + const int64_t qrw = q.b0 + q0 + r / g.gqa, h = q.kh * g.gqa + r % g.gqa; + const uint16_t* src = (const uint16_t*)g.q->data + qrw * g.q_rs + h * hd; + if (g.i8) { + row_to_f32(RAD_BF16, src, row, hd); + sq[r] = q8_row(row, hd, row); + uint16_t* c = qcodes + r * hd; + row_from_f32(RAD_BF16, row, c, hd); + qrow[r] = c; + } else { + sq[r] = 1.0f; + qrow[r] = src; + } + m[r] = -INFINITY; + l[r] = 0.0f; + } + std::memset(acc, 0, sizeof(float) * (size_t)(R * hd)); + const int64_t nvis = visible_keys(g, q, q1); + const size_t tb = bf16_tile_bytes(hd); + for (int64_t t = 0; t * KT < nvis; ++t) { + const uint8_t* tile = pack + q.off + (size_t)t * tb; + const uint32_t* kp = (const uint32_t*)tile; + const uint32_t* vp = kp + D2 * KT; + const float* sk = (const float*)(vp + (KT / 2) * hd); + for (int64_t r = 0, mb; r < R; r += mb) { + mb = row_block(R - r, 6); + PS_ROWS(qk_bf16, mb, qrow + r, kp, D2, S + r * KT); + } + finish_scores(g, q, S, R, t, q0, sq, sk); + softmax_tile(S, R, m, l, acc, hd, hd); + for (int64_t r = 0; r < R; ++r) p_pairs(S + r * KT, pp + r * 32); + const int64_t K2 = (std::min(KT, q.nk - t * KT) + 1) / 2; + for (int64_t c0 = 0; c0 < hd; c0 += 64) + for (int64_t r = 0, mb; r < R; r += mb) { + mb = row_block(R - r, 6); + PS_ROWS(pv_bf16, mb, acc + r * hd, hd, pp + r * 32, vp, K2, c0); + } + } + store_rows(g, q, q0, R, acc, hd, m, l); +} +#endif + +} /* namespace */ + +/* ------------------------------------------------------------------ attn_prefix_self */ +AVX_KERNEL(attn_prefix_self) { + if (a->n_t < 12) return RAD_E_INVAL; + Geo g{}; + g.q = &a->t[0]; g.k = &a->t[1]; g.v = &a->t[2]; g.kv = &a->t[3]; + g.bt = &a->t[4]; g.su = &a->t[5]; g.cu = &a->t[6]; g.o = &a->t[11]; + g.kdes = rad_arg_in(a, 7); + g.vdes = rad_arg_in(a, 8); + g.k8 = rad_arg_in(a, 9); + g.ks = rad_arg_in(a, 10); + g.i8 = std::strcmp(p_str(a, "qk", "bf16"), "i8") == 0; + if (g.i8 != (g.k8 != nullptr) || g.i8 != (g.ks != nullptr)) return RAD_E_INVAL; + if (g.i8 && (g.kdes || g.vdes)) return RAD_E_UNSUPPORTED; + g.hd = p_int(a, "head_dim", 0); + g.gqa = p_int(a, "gqa", 1); + g.causal = (int)p_int(a, "causal", 0); + g.bs = g.kv->rank == 4 ? g.kv->shape[2] : p_int(a, "block_size", 0); + if (g.hd <= 0 || g.gqa <= 0 || g.bs <= 0) return RAD_E_SHAPE; + if (g.hd > PS_HD_MAX) return RAD_E_UNSUPPORTED; + g.kvh = g.kv->rank == 4 ? g.kv->shape[1] : 0; + if (g.kvh <= 0) return RAD_E_SHAPE; + g.qh = g.kvh * g.gqa; + g.n_seq = numel(g.cu) - 1; + if (g.n_seq <= 0 || numel(g.su) < g.n_seq) return RAD_E_SHAPE; + if (cu_at(g.cu, g.n_seq) - cu_at(g.cu, 0) <= 0) return RAD_E_SHAPE; + g.max_blocks = g.bt->rank >= 2 ? g.bt->shape[1] : numel(g.bt) / g.n_seq; + g.bt_rs = g.bt->rank >= 2 ? g.bt->stride[0] : g.max_blocks; + g.bt_cs = g.bt->rank >= 2 ? g.bt->stride[1] : 1; + for (int64_t s = 0; s < g.n_seq; ++s) + if (ldi(g.su, offlin(g.su, s)) > g.max_blocks * g.bs) return RAD_E_SHAPE; + g.q_rs = row_stride(g.q, g.qh * g.hd); + g.k_rs = row_stride(g.k, g.kvh * g.hd); + g.v_rs = row_stride(g.v, g.kvh * g.hd); + g.o_rs = row_stride(g.o, g.qh * g.hd); + g.k8_rs = g.i8 ? row_stride(g.k8, g.kvh * g.hd) : 0; + g.ks_rs = g.i8 ? row_stride(g.ks, g.kvh) : 0; + g.sb = g.kv->stride[0]; g.sh = g.kv->stride[1]; g.so = g.kv->stride[2]; + g.scale = p_f32(a, "scale", 1.0f / std::sqrt((float)g.hd)); + + /* ---- which form, and each (entry, kv head)'s key sequence */ + [[maybe_unused]] bool bf16 = false; +#if AVX_LEVEL == 3 + static const bool have_bf16 = __builtin_cpu_supports("avx512bf16"); + bf16 = have_bf16 && g.hd % 64 == 0 && g.gqa <= 16 && !g.kdes && !g.vdes && + g.q->dtype == RAD_BF16 && g.kv->dtype == RAD_BF16 && g.v->dtype == RAD_BF16 && + (g.i8 || g.k->dtype == RAD_BF16); +#endif + const size_t tile_bytes = +#if AVX_LEVEL == 3 + bf16 ? bf16_tile_bytes(g.hd) : +#endif + f32_tile_floats(g.hd) * sizeof(float); + /* Kept at their high-water size; the parallel regions read them through pointers taken on + * this thread. */ + static thread_local std::vector seqs; + static thread_local std::vector pack; + static thread_local std::vector tile_of, task_of; + seqs.clear(); + for (int64_t kh = 0; kh < g.kvh; ++kh) + for (int64_t s = 0; s < g.n_seq; ++s) { + Seq q{}; + q.s = s; q.kh = kh; + q.P = ldi(g.su, offlin(g.su, s)); + q.b0 = cu_at(g.cu, s); + q.len = std::max(0, cu_at(g.cu, s + 1) - q.b0); + /* A negative prefix count makes key j own row b0 + j - P, as libref indexes it. */ + q.nk = std::max(0, q.P + q.len); + q.ntile = (q.nk + KT - 1) / KT; + seqs.push_back(q); + } + + /* ---- kv heads in groups whose packs fit the budget: pack each group, then run its tasks */ + size_t i0 = 0; + while (i0 < seqs.size()) { + size_t i1 = i0, bytes = 0; + do { + /* Whole kv heads: an entry's tasks of one head share nothing with another head's. */ + const int64_t kh = seqs[i1].kh; + size_t hb = 0, j = i1; + for (; j < seqs.size() && seqs[j].kh == kh; ++j) hb += (size_t)seqs[j].ntile * tile_bytes; + if (i1 > i0 && bytes + hb > (size_t)kPackBudget) break; + for (; i1 < j; ++i1) { + seqs[i1].off = bytes; + bytes += (size_t)seqs[i1].ntile * tile_bytes; + } + } while (i1 < seqs.size()); + pack.resize(bytes + 64); + uint8_t* pk = pack.data(); + tile_of.assign(1, 0); + task_of.assign(1, 0); + for (size_t i = i0; i < i1; ++i) { + tile_of.push_back(tile_of.back() + seqs[i].ntile); + task_of.push_back(task_of.back() + (seqs[i].len + QB - 1) / QB); + } + const int64_t n_tiles = tile_of.back(), n_tasks = task_of.back(); + const int64_t n_grp = (int64_t)(i1 - i0); + const Seq* sq0 = seqs.data() + i0; + const int64_t* t_of = tile_of.data(); + const int64_t* k_of = task_of.data(); + + AVX_PARALLEL_FOR_IF(n_tiles * KT * g.hd >= AVX_PAR_MIN) + for (int64_t u = 0; u < n_tiles; ++u) { + const int64_t i = (int64_t)(std::upper_bound(t_of, t_of + n_grp + 1, u) - t_of) - 1; + const Seq& q = sq0[i]; + const int64_t t = u - t_of[i]; + uint8_t* tile = pk + q.off + (size_t)t * tile_bytes; + float* row = scratch_f32((size_t)(4 * g.hd + 64)); +#if AVX_LEVEL == 3 + if (bf16) { + pack_tile_bf16(g, q, t, tile, row, (uint16_t*)(row + g.hd + 16)); + continue; + } +#endif + pack_tile_f32(g, q, t, (float*)tile, row); + } + +#ifdef _OPENMP +#pragma omp parallel for schedule(dynamic, 1) num_threads(avx_team_size()) \ + if(n_tasks > 1 || avx_par_forced()) +#endif + for (int64_t u = 0; u < n_tasks; ++u) { + const int64_t i = (int64_t)(std::upper_bound(k_of, k_of + n_grp + 1, u) - k_of) - 1; + const Seq& q = sq0[i]; + const int64_t q0 = (u - k_of[i]) * QB, q1 = std::min(q0 + QB, q.len); +#if AVX_LEVEL == 3 + if (bf16) { + task_bf16(g, q, pk, q0, q1); + continue; + } +#endif + task_f32(g, q, pk, q0, q1); + } + i0 = i1; + } + return RAD_OK; +} diff --git a/libavx/avx_had.h b/libavx/avx_had.h index 65d4272d..b7ecb534 100644 --- a/libavx/avx_had.h +++ b/libavx/avx_had.h @@ -1,27 +1,24 @@ -/* avx_had.h -- the Hadamard rotation, the fp8 group quantiser and the epilogue the fp8 fusions - * share, for the kernels that emit a rotated or block-scaled fp8 row: had_quant_act_fp8, the fused - * quantisers (avx_quant.cpp), gemm_nt_q_gated (avx_gemm.cpp) and hc_read's rotated twin - * (avx_hc.cpp). Compiled per level with the file that includes it; include it after avx_vec.h and - * avx_common.h, with `using namespace avx` in effect. */ +/* avx_had.h -- Hadamard rotation, fp8 group quantiser and the shared fp8-fusion epilogue, for the + * kernels that emit a rotated or block-scaled fp8 row: had_quant_act_fp8, the fused quantisers + * (avx_quant.cpp), gemm_nt_q_gated (avx_gemm.cpp) and hc_read (avx_hc.cpp). + * Compiled per level with its includer; include after avx_vec.h and avx_common.h, with + * `using namespace avx` in effect. */ #ifndef RAD_AVX_HAD_H #define RAD_AVX_HAD_H static inline bool pow2(int64_t v) { return v > 0 && (v & (v - 1)) == 0; } -/* The widest rotation this plugin performs. libr4d caps `had` at 512 -- a power of two dividing - * the per-rank K, and 8704 admits no more -- so 4096 is four doublings of headroom, and it is - * libref's cap too so the two agree about what they refuse. A wider request returns - * RAD_E_UNSUPPORTED BY NAME rather than silently rotating a narrower block: a half-applied - * rotation is numerically plausible and completely wrong. */ +/* Widest rotation supported. libr4d caps `had` at 512 (the largest power of two dividing a + * per-rank K of 8704); 4096 matches libref's cap so both refuse the same requests. A wider request + * returns RAD_E_UNSUPPORTED rather than rotating a narrower block, whose output would look + * plausible but be wrong. */ enum { AVX_HAD_MAX = 4096 }; /* ================================================================== the butterfly - * One stride of the transform over a g-element block. `h` is the stride; the caller runs it - * ascending from 1. */ + * One stride `h` of the transform over a g-element block; strides run ascending from 1. */ #if AVX_LEVEL >= 1 -/* The partner of each lane under a swap at stride `h`, for h < VF_N, and the mask of lanes that - * take the SUM (the ones with (i & h) == 0; the others take partner - self, which is the - * subtraction with the operands the right way round). */ +/* In-register stride for h < VF_N: permute each lane with its partner at stride h, then lanes with + * (i & h) == 0 take self + partner and the others partner - self. */ static inline void fwht_small(float* v, int64_t g, int64_t h) { for (int64_t b = 0; b < g; b += VF_N) { vf x = vf_loadu(v + b); @@ -34,7 +31,6 @@ static inline void fwht_small(float* v, int64_t g, int64_t h) { case 4: p = _mm512_shuffle_f32x4(x, x, 0xB1); m = 0x0F0F; break; default:p = _mm512_shuffle_f32x4(x, x, 0x4E); m = 0x00FF; break; /* h == 8 */ } - /* sum where (i & h) == 0, partner - self elsewhere. One blend, no branch per lane. */ vf_storeu(v + b, _mm512_mask_blend_ps(m, _mm512_sub_ps(p, x), _mm512_add_ps(x, p))); #else switch (h) { @@ -84,39 +80,38 @@ static inline void fwht_row(float* v, int64_t n, int64_t g) { } /* ================================================================== the fp8 group - * out[k0, k1) = v[k0, k1) / scale, clamped to E4M3's finite range, with scale = amax / 448 (1 for an - * all-zero group). */ -static inline void fp8_group(const float* v, float* out, int64_t k0, int64_t k1, float* scale_out) { + * out[k0, k1) = v[k0, k1) / scale, clamped to +-top, with scale = amax / top (1 for an all-zero + * group): `top` 448 is E4M3's finite range, 127 int8's. */ +static inline void fp8_group(const float* v, float* out, int64_t k0, int64_t k1, float* scale_out, + float top = 448.0f) { const float amax = row_amax(v + k0, k1 - k0); - const float sc = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f; + const float sc = amax > 0.0f ? amax * (1.0f / top) : 1.0f; const float inv = 1.0f / sc; - const vf vi = vf_set1(inv), hi = vf_set1(448.0f), lo = vf_set1(-448.0f); + const vf vi = vf_set1(inv), hi = vf_set1(top), lo = vf_set1(-top); int64_t i = k0; for (; i + VF_N <= k1; i += VF_N) vf_storeu(out + i, vf_min(vf_max(vf_mul(vf_loadu(v + i), vi), lo), hi)); for (; i < k1; ++i) { float t = v[i] * inv; - out[i] = t > 448.0f ? 448.0f : (t < -448.0f ? -448.0f : t); + out[i] = t > top ? top : (t < -top ? -top : t); } *scale_out = sc; } /* ================================================================== the fp8 fusions' epilogue * - * A fused fp8 op stands in for a pair whose first half writes a bf16 tensor and whose second half - * quantises the bytes it reads back. So the codes are taken over the bf16-NARROWED value whatever - * the activation dtype, and `out_bf16` holds exactly that value -- libref's contract for all three - * (ref_quant.cpp), and the reason the helpers below narrow before they quantise. */ + * A fused fp8 op replaces a pair that writes a bf16 tensor and then quantises it. So the codes are + * taken over the bf16-narrowed value whatever the activation dtype, and `out_bf16` holds that + * value (libref's contract, ref_quant.cpp). The helpers below therefore narrow before quantising. */ -/* v[0, n) narrowed to bf16 and read back, in place. `tmp` holds n floats, which is room for the n - * bf16 in between. */ +/* Round v[0, n) through bf16 in place. `tmp` holds n floats (room for the n bf16). */ static inline void narrow_bf16(float* v, int64_t n, float* tmp) { row_from_f32(RAD_BF16, v, tmp, n); row_to_f32(RAD_BF16, tmp, v, n); } -/* out = act(gate) * up, narrowed to bf16: act 0 is silu (down_proj's input), 1 sigmoid (a gated - * attention o_proj's). `tmp` holds n floats. */ +/* out = act(gate) * up, narrowed to bf16. act 0 is silu (down_proj's input), 1 is sigmoid (a + * gated attention's o_proj input). `tmp` holds n floats. */ static inline void gate_bf16(const float* gv, const float* uv, float* out, int64_t n, int act, float* tmp) { int64_t i = 0; @@ -131,16 +126,18 @@ static inline void gate_bf16(const float* gv, const float* uv, float* out, int64 narrow_bf16(out, n, tmp); } -/* Row r of the codes `q` and their group scales `s` over v[0, n), in groups of `g` with a ragged - * last one; and v itself into `ob` when a caller asked for it. `codes` holds n floats. */ +/* Writes row r of the codes `q` and group scales `s` over v[0, n), in groups of `g` (the last may + * be short), and v itself into `ob` when given. `codes` holds n floats. An int8 `q` takes + * quant_act_i8g's codes (libref/ref_quant.cpp: fp8_row). */ static inline void fp8_emit(const float* v, float* codes, int64_t n, int64_t g, const RadTensor* q, const RadTensor* s, const RadTensor* ob, int64_t r) { if (ob) out_row(ob, rowoff(ob, r, n), n, v); const int64_t ngrp = (n + g - 1) / g; + const float top = q->dtype == RAD_I8 ? 127.0f : 448.0f; for (int64_t gi = 0; gi < ngrp; ++gi) { const int64_t k0 = gi * g, k1 = (k0 + g < n) ? k0 + g : n; float sc; - fp8_group(v, codes, k0, k1, &sc); + fp8_group(v, codes, k0, k1, &sc, top); stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc); } out_row(q, rowoff(q, r, n), n, codes); diff --git a/libavx/avx_harness.h b/libavx/avx_harness.h index 4ead8d92..e5c2f205 100644 --- a/libavx/avx_harness.h +++ b/libavx/avx_harness.h @@ -1,19 +1,17 @@ -/* avx_harness.h -- opening a plugin, sizing its operands, drawing them, and the geometry table. +/* avx_harness.h -- plugin loading, operand sizing and drawing, and the geometry table. * - * SHARED BY rad-avx-check AND rad-avx-bench, AND THAT SHARING IS THE POINT. A benchmark taken at a - * different extent from the correctness check is a measurement of something else, and two copies - * of a geometry table drift the moment one of them gains a case. tools/opshapes.h makes exactly - * this argument for rad-kbench and rad-tune; the same argument applies one level down. - * - * Header-only and included by two translation units, so everything here is `static` or `inline`. - * Neither binary links either plugin: both dlopen by path, which is what makes the claim be about - * the .so the engine would load rather than about a differently-inlined copy of the same source. + * Shared by rad-avx-check and rad-avx-bench so that both run the same extents from one table + * (tools/opshapes.h does the same for rad-kbench and rad-tune). Header-only for two translation + * units, so everything is `static` or `inline`. Neither binary links a plugin: both dlopen by path, + * so the results describe the .so the engine would load. */ #ifndef RAD_AVX_HARNESS_H #define RAD_AVX_HARNESS_H #include "rad_abi.h" #include "rad_plugin.h" +#include "rad_sample.h" +#include "avx_common.h" #include @@ -35,11 +33,12 @@ struct Lib { int (*schema_count)() = nullptr; const RadOpSchema* (*schema_at)(int) = nullptr; int (*plugin_open)() = nullptr; - /* libavx's own, and absent from any other plugin -- which is how a caller learns whether it - * can sweep ISA levels at all rather than assuming it is looking at libavx. */ + /* libavx-only exports; null for other plugins, which tells a caller it cannot sweep ISA + * levels or force its parallel regions. */ int (*isa_force)(int) = nullptr; int (*isa_detect)() = nullptr; const char* (*isa_name)(int) = nullptr; + int (*par_force)(int) = nullptr; bool open(const char* p) { path = p; @@ -56,14 +55,14 @@ struct Lib { isa_force = (int (*)(int))sym("avx_isa_force"); isa_detect = (int (*)())sym("avx_isa_detect"); isa_name = (const char* (*)(int))sym("avx_isa_name"); + par_force = (int (*)(int))sym("avx_par_force"); if (!abi || !inf || !kernel_count || !kernel_at || !schema_count || !schema_at) { std::fprintf(stderr, "%s: not a kernel plugin (missing exports)\n", p); return false; } if (abi() != RAD_ABI_VERSION) { - /* THE LOADER'S RULE, REPRODUCED: a plugin that does not report exactly this version is - * refused by name with both versions printed. A harness that shrugged at it would be - * measuring a plugin the engine will not load. */ + /* Same rule as the engine's loader: refuse any version but this one, so the tool never + * measures a plugin the engine would not load. */ std::fprintf(stderr, "%s: ABI %u, this tool is built for %u\n", p, abi(), RAD_ABI_VERSION); return false; @@ -90,17 +89,124 @@ struct Lib { } return nullptr; } + /* True when some row of the op runs on the host, i.e. can be launched with host pointers. */ + bool host_row(const char* op) const { + for (int i = 0, n = kernel_count(); i < n; ++i) { + const RadKernelInfo* k = kernel_at(i); + if (k && k->op && std::strcmp(k->op, op) == 0 && k->domain == RAD_DOMAIN_HOST) + return true; + } + return false; + } + + /* The host row the selector would resolve this geometry to: every constraint holds, highest + * priority, earlier declaration on a tie (core/plugin/select.cpp). A constraint on a derived + * parameter the geometry does not name is skipped, and a "device." key never holds, as + * without an engine nothing measured the machine. Tunables are not chosen; the kernel reads its + * defaults. Null when no host row admits the geometry. */ + const RadKernelInfo* select(const char* op, const RadParam* p, int n_p) const { + const RadOpSchema* sch = schema(op); + const RadKernelInfo* best = nullptr; + for (int i = 0, n = kernel_count(); i < n; ++i) { + const RadKernelInfo* k = kernel_at(i); + if (!k || !k->op || std::strcmp(k->op, op) != 0 || k->domain != RAD_DOMAIN_HOST) + continue; + bool ok = true; + for (int c = 0; c < k->n_constraints && ok; ++c) + ok = constraint_holds(k->constraints[c], sch, p, n_p); + if (ok && (!best || k->priority > best->priority)) best = k; + } + return best; + } + + static bool constraint_holds(const RadConstraint& c, const RadOpSchema* sch, const RadParam* p, + int n_p) { + static const size_t kFact = std::strlen(RAD_DEVICE_FACT_PREFIX); + if (!c.key || std::strncmp(c.key, RAD_DEVICE_FACT_PREFIX, kFact) == 0) return false; + const RadParam* v = rad_param_find(p, n_p, c.key); + if (!v) { + for (int i = 0; sch && i < sch->n_params; ++i) + if (sch->params[i].key && !std::strcmp(sch->params[i].key, c.key)) + return sch->params[i].required == RAD_DERIVED; + return false; + } + char num[32]; + const char* sv = v->kind == RAD_P_STR ? v->sval : nullptr; + if (c.op == RAD_C_IN) { + if (!sv) { + if (v->kind != RAD_P_INT) return false; + std::snprintf(num, sizeof num, "%lld", v->ival); + sv = num; + } + const size_t len = std::strlen(sv); + for (const char* t = c.sval ? c.sval : ""; *t;) { + while (*t == ' ') ++t; + const char* e = t; + while (*e && *e != ' ') ++e; + if ((size_t)(e - t) == len && len && !std::strncmp(t, sv, len)) return true; + t = e; + } + return false; + } + if (v->kind != RAD_P_INT) return false; + switch (c.op) { + case RAD_C_EQ: return v->ival == c.ival; + case RAD_C_LE: return v->ival <= c.ival; + case RAD_C_GE: return v->ival >= c.ival; + case RAD_C_DIV: return c.ival != 0 && v->ival % c.ival == 0; + default: return false; + } + } +}; + +/* ================================================================== guarded buffers + * + * Every buffer a kernel is handed has H_GUARD bytes of a known pattern on each side, checked after + * the launch: a write past either end of an operand or of the scratch shows up as a changed guard + * rather than as a corrupted neighbour that may never be read. */ +enum { H_GUARD = 64 }; + +static inline uint8_t h_guard_byte(size_t i) { return (uint8_t)(0xA5u ^ (uint8_t)(i * 29u)); } + +struct GBuf { + std::vector v; + size_t n = 0; + + void assign(const uint8_t* src, size_t bytes) { + n = bytes; + v.resize(bytes + 2 * H_GUARD); + for (size_t i = 0; i < H_GUARD; ++i) { + v[i] = h_guard_byte(i); + v[H_GUARD + bytes + i] = h_guard_byte(i + 1); + } + if (bytes) { + if (src) std::memcpy(v.data() + H_GUARD, src, bytes); + else std::memset(v.data() + H_GUARD, 0, bytes); + } + } + void assign(const std::vector& src) { assign(src.data(), src.size()); } + uint8_t* data() { return v.data() + H_GUARD; } + const uint8_t* data() const { return v.data() + H_GUARD; } + size_t size() const { return n; } + bool empty() const { return n == 0; } + /* 0 when both guards are intact, otherwise -1 for the leading guard and 1 for the trailing. */ + int guard_hit() const { + if (v.empty()) return 0; + for (size_t i = 0; i < H_GUARD; ++i) + if (v[i] != h_guard_byte(i)) return -1; + for (size_t i = 0; i < H_GUARD; ++i) + if (v[H_GUARD + n + i] != h_guard_byte(i + 1)) return 1; + return 0; + } }; /* ================================================================== the draw * - * The laws are RadOpdDesc's (rad_abi.h) and they are not decoration. A gated-delta-net `g` is an - * intra-chunk cumulative sum of log-decays; fed normals, the ORACLE overflows to 2e38 while the - * kernel does something else and the comparison measures the test rather than the kernel. The same - * is true of a sigmoid gate, a unit-triangular factor, a unit-norm key, and of every index - * operand -- a KV slot indexes n_blocks * block_size and a block-table entry indexes n_blocks, and - * drawing either from the wrong range tests out-of-range handling and calls the result - * correctness. rad_abi.h and tools/kfixture.cpp both record having been bitten by each of these. + * Values follow the fill laws in RadOpdDesc (rad_abi.h). A gated-delta-net `g` is an intra-chunk + * cumulative sum of log-decays; drawn as normals, the oracle overflows to 2e38 and the comparison + * tests the input rather than the kernel. The same holds for sigmoid gates, unit-triangular + * factors, unit-norm keys and every index operand (a KV slot indexes n_blocks * block_size, a + * block-table entry n_blocks); an index drawn out of range tests only out-of-range handling. */ static inline uint64_t hsplitmix(uint64_t& x) { uint64_t z = (x += 0x9E3779B97F4A7C15ull); @@ -127,7 +233,8 @@ struct Opd { bool absent = false; int role = RAD_OPD_IN; int64_t n = 0; - std::vector master, a, b; /* the drawn bytes, then one copy per side */ + std::vector master; /* the drawn bytes */ + GBuf a, b; /* one guarded copy per side */ }; static inline int64_t desc_numel(const RadOpdDesc& d) { @@ -140,11 +247,9 @@ static inline size_t dt_bytes(uint32_t dt, int64_t n) { return (size_t)((n * rad_dtype_bits(dt) + 7) / 8); } -/* W4 / W2 / MXFP4 have no store side in the ABI's accessor, and the packed grids are WEIGHT - * operands a fixture would lay out rather than draw. Writing the CODE directly is the honest - * alternative: both plugins decode the same symmetric two's-complement nibble - * (libref/ref_common.h), so the bytes mean the same thing to both sides, which is the only - * property the comparison needs. */ +/* W4, W2 and MXFP4 have no store in the ABI's accessor, so the codes are written directly. Both + * plugins decode them with libref's codes (libref/ref_common.h), so the bytes mean the same to + * both sides, which is all the comparison needs. */ static inline void h_narrow(const float* src, uint32_t dt, int64_t n, void* dst) { if (dt == RAD_I4 || dt == RAD_FP4E2M1) { uint8_t* b = (uint8_t*)dst; @@ -156,6 +261,17 @@ static inline void h_narrow(const float* src, uint32_t dt, int64_t n, void* dst) } return; } + if (dt == RAD_E8M0) { + /* An MX block's exponent byte: the power of two nearest the drawn magnitude, so a scale + * drawn at weight size lands near 2^-6, not at the store's 0 (2^-127). */ + uint8_t* b = (uint8_t*)dst; + for (int64_t i = 0; i < n; ++i) { + const float a = std::fabs(src[i]); + const long e = a > 0.0f && std::isfinite(a) ? 127 + std::lrint(std::log2(a)) : 127; + b[i] = (uint8_t)(e < 1 ? 1 : (e > 254 ? 254 : e)); + } + return; + } if (dt == RAD_I2) { uint8_t* b = (uint8_t*)dst; std::memset(b, 0, dt_bytes(dt, n)); @@ -169,33 +285,9 @@ static inline void h_narrow(const float* src, uint32_t dt, int64_t n, void* dst) for (int64_t i = 0; i < n; ++i) rad_store_f32(dst, dt, i, src[i]); } +/* Packed codes decode with libref's codes, through avx_common.h's ld_elem. */ static inline void h_widen(const void* src, uint32_t dt, int64_t n, float* dst) { - if (dt == RAD_I4) { - for (int64_t i = 0; i < n; ++i) { - const uint8_t by = ((const uint8_t*)src)[i >> 1]; - const uint8_t nb = (i & 1) ? (uint8_t)(by >> 4) : (uint8_t)(by & 0xf); - dst[i] = (float)((int)(nb ^ 0x8u) - 8); - } - return; - } - if (dt == RAD_I2) { - for (int64_t i = 0; i < n; ++i) { - const uint8_t by = ((const uint8_t*)src)[i >> 2]; - const uint8_t c = (uint8_t)((by >> (2 * (i & 3))) & 0x3u); - dst[i] = (float)((int)(c ^ 0x2u) - 2); - } - return; - } - if (dt == RAD_FP4E2M1) { - static const float mag[8] = { 0, 0.5f, 1, 1.5f, 2, 3, 4, 6 }; - for (int64_t i = 0; i < n; ++i) { - const uint8_t by = ((const uint8_t*)src)[i >> 1]; - const uint8_t nb = (i & 1) ? (uint8_t)(by >> 4) : (uint8_t)(by & 0xf); - dst[i] = (nb & 8u) ? -mag[nb & 7u] : mag[nb & 7u]; - } - return; - } - for (int64_t i = 0; i < n; ++i) dst[i] = rad_load_f32(src, dt, i); + for (int64_t i = 0; i < n; ++i) dst[i] = avx::ld_elem(src, dt, i); } static inline void h_draw(std::vector& o, size_t k, int64_t M, uint64_t seed) { @@ -203,27 +295,49 @@ static inline void h_draw(std::vector& o, size_t k, int64_t M, uint64_t see const int64_t n = d.n; d.master.assign(dt_bytes(d.d.dtype, n > 0 ? n : 0), 0); if (n <= 0 || d.absent) return; - if (d.role != RAD_OPD_IN && d.role != RAD_OPD_INOUT && d.role != RAD_OPD_WEIGHT) return; + /* A weight table (a MoE layer's experts) is described stacked, [n_expert, ...], and drawn as + * any weight; left undrawn, every expert would be zeros and the product would compare zeros. */ + const bool weight = d.role == RAD_OPD_WEIGHT || d.role == RAD_OPD_WTAB; + if (d.role != RAD_OPD_IN && d.role != RAD_OPD_INOUT && !weight) return; std::vector tmp((size_t)n, 0.0f); const bool is_index = d.d.fill == RAD_FILL_INDEX; const bool idx_cu = (d.d.flags & RAD_OPD_F_IDX_CU) != 0; const bool idx_uniq = (d.d.flags & RAD_OPD_F_IDX_UNIQUE) != 0; + const bool idx_pre = (d.d.flags & RAD_OPD_F_IDX_PREFIX) != 0; - if (d.role == RAD_OPD_WEIGHT && !is_index) { - /* 0.02 sigma, and it is not cosmetic: a checkpoint's weights are that size, and drawing - * them at unit variance puts an fp8 quantiser's amax three orders of magnitude off where a - * real one sits -- so the case would measure the quantiser on data no model produces. */ + /* Integer and packed codes are whole numbers, so a draw at weight scale would store every + * code as 0 and the product would compare zeros with zeros. They are drawn to span their grid + * instead: int8 at sigma 40, the 4- and 2-bit codes at unit sigma (h_narrow scales a 4-bit + * draw by 3). */ + const bool codes = d.d.dtype == RAD_I8 || d.d.dtype == RAD_I4 || d.d.dtype == RAD_I2 || + d.d.dtype == RAD_FP4E2M1; + if (codes && !is_index) { + fill_normal(tmp.data(), n, seed, d.d.dtype == RAD_I8 ? 40.0f : 1.0f); + } else if (weight && !is_index) { + /* Sigma 0.02, the size of real checkpoint weights. At unit variance an fp8 quantiser's + * amax would be orders of magnitude away from anything a model produces. */ fill_normal(tmp.data(), n, seed, 0.02f); } else if (is_index && idx_cu) { - /* Cumulative sequence lengths, [0 .. T]: the batch's shape, not a draw. */ + /* Cumulative sequence lengths over [0, T]: the batch's shape, not random. */ const int64_t S = n > 1 ? n - 1 : 1; for (int64_t i = 0; i < n; ++i) tmp[(size_t)i] = (float)((i * M) / S); } else if (is_index && d.d.idx_const >= 0) { for (int64_t i = 0; i < n; ++i) tmp[(size_t)i] = (float)d.d.idx_const; + } else if (is_index && idx_pre) { + /* A routing histogram's offsets (moe_scatter's `expert_offset`): non-decreasing from 0 to + * idx_max - 1. Drawn at random they are a malformed histogram, which a binary and a linear + * search read differently with neither wrong. Sorted draws, pinned at both ends. */ + uint64_t s2 = seed; + const int64_t top = d.d.idx_max > 0 ? d.d.idx_max - 1 : 0; + for (int64_t i = 0; i < n; ++i) + tmp[(size_t)i] = (float)(hsplitmix(s2) % (uint64_t)(top + 1)); + std::sort(tmp.begin(), tmp.end()); + tmp[0] = 0.0f; + tmp[(size_t)(n - 1)] = (float)top; } else if (is_index && idx_uniq) { - /* A scatter's destinations, distinct: two tokens on one slot is a race the two - * implementations resolve differently, so the comparison would measure the scheduler. */ + /* Distinct scatter destinations: two writes to one slot race, and the two plugins would + * resolve the race differently. */ uint64_t s2 = seed; const int64_t range = d.d.idx_max > 0 ? d.d.idx_max : n; std::vector pool((size_t)range); @@ -245,13 +359,12 @@ static inline void h_draw(std::vector& o, size_t k, int64_t M, uint64_t see fill_normal(tmp.data(), n, seed, 1.0f); if (d.d.fill == RAD_FILL_SIGMOID) { for (int64_t i = 0; i < n; ++i) - tmp[(size_t)i] = 1.0f / (1.0f + std::exp(-tmp[(size_t)i])); + tmp[(size_t)i] = 1.0f / (1.0f + sc_exp(-tmp[(size_t)i])); } else if (d.d.fill == RAD_FILL_TRI_LOWER) { - /* UNIT DIAGONAL, SMALL OFF-DIAGONAL. `A` is the chunked delta rule's intra-chunk - * matrix I + tril(diag(beta) K K^T, -1), unit lower triangular by construction, and - * its inverse is bounded only because of that. A normal on the diagonal makes the - * inverse enormous, and what the comparison then reports is the condition number of - * the TEST. */ + /* Unit diagonal, small off-diagonal. `A` is the chunked delta rule's intra-chunk + * matrix I + tril(diag(beta) K K^T, -1), which is unit lower triangular; that is what + * keeps its inverse bounded. A random diagonal would make the comparison measure the + * input's condition number. */ const int64_t ch = d.d.fill_chunk > 0 ? d.d.fill_chunk : 1; const int64_t heads = d.d.rank >= 3 ? d.d.shape[1] : 1; const int64_t rows = (heads * ch) != 0 ? n / (heads * ch) : n; @@ -272,7 +385,7 @@ static inline void h_draw(std::vector& o, size_t k, int64_t M, uint64_t see float acc = 0.0f; for (int64_t t = 0; t < rows; ++t) { if (t % ch == 0) acc = 0.0f; - acc -= std::log1p(std::exp(tmp[(size_t)(t * heads + h)])); + acc -= sc_log1p(sc_exp(tmp[(size_t)(t * heads + h)])); tmp[(size_t)(t * heads + h)] = acc; } } @@ -293,11 +406,10 @@ static inline void h_draw(std::vector& o, size_t k, int64_t M, uint64_t see /* ================================================================== the geometry table * - * THE ONE PLACE THESE TOOLS KNOW ANYTHING ABOUT AN OP, and it is a PARAMETER list rather than a - * shape: the shapes come from libref's own `opd_shape`. The values are chosen to be small but not - * degenerate -- a row wider than any vector, a row count above one, a group that divides, and - * where the op allows it a row length that does NOT divide the vector width, because the tail is - * where a hand-vectorised kernel is wrong. + * The only op-specific knowledge in these tools, given as parameters; shapes come from libref's + * `opd_shape`. Values are small but not degenerate: rows wider than a vector, more than one row, a + * dividing group and, where allowed, a row length that is not a multiple of the vector width, to + * exercise the tail. */ struct P { const char* k; int kind; long long i; const char* s; double d; }; @@ -313,33 +425,24 @@ static inline RadParam h_mk(const P& p) { struct Case { const char* op; std::vector

p; - /* Bytes moved and flops done, for the bench's rate columns. 0 means "do not report a rate": - * an op whose cost is not a simple function of its geometry gets a time and no invented - * denominator. */ + /* Bytes moved and flops done, for the bench's rate columns. 0 means no rate is reported (the + * cost is not a simple function of the geometry). */ double bytes = 0, flops = 0; - /* A case worth TIMING at a real model shape and not worth checking there. Correctness is a - * property of the arithmetic and a 640-wide row exercises every path a 2048-wide one does, so - * the checker would spend minutes inside libref to learn nothing; speed is not, because it is - * the cache hierarchy that decides it and a shape that fits L1 answers a different question. - * The same split tools/kfixture.h draws, and for the same reason. rad-avx-check skips these. */ + /* Timed at a real model shape but not checked there; rad-avx-check skips it. A 640-wide row + * exercises every code path a 2048-wide one does, but speed depends on the cache hierarchy + * and needs the real shape. Same split as tools/kfixture.h. */ bool speed_only = false; }; -/* THE TOTAL TOKEN COUNT OF THE BATCH, which is what the cumulative-length draw divides across the - * sequences and what no operand carries. +/* Total token count of the batch, which the cumulative-length draw divides across sequences and + * which no operand carries. * - * IT IS NOT ALWAYS THE RANGED PARAMETER, and that distinction cost four silently skipped ops. An - * op banded on `M` is banded on the TOTAL -- `gdn_conv_prep` sizes its activation [M, conv_dim] and - * its cu spans M. An op banded on `q_len` is banded on the PER-SEQUENCE length: `gdn_conv_update` - * sizes its activation [n_seq * q_len, conv_dim], because a decode step presents q_len candidate - * rows for each of n_seq sequences. Drawing cu to sum to q_len there gives a batch whose cu says - * two tokens over operands sized for four, and libref recomputes its head count from - * numel(q) / (T * head_k) -- which comes out double, makes conv_dim double, and refuses the launch - * with RAD_E_SHAPE. The case was then SKIPPED, and a skip with no reason printed is indistinguishable - * from an op that has no case at all. - * - * `attn_paged` is also banded on `q_len` and is unaffected only because libref describes it at one - * sequence; the rule below is right for both. */ + * It is not always the ranged parameter. An op banded on `M` is banded on the total + * (`gdn_conv_prep`: activation [M, conv_dim], cu spans M). An op banded on `q_len` is banded on + * the per-sequence length (`gdn_conv_update`: activation [n_seq * q_len, conv_dim], q_len candidate + * rows per sequence), so the total is q_len * n_seq. With cu summing to q_len instead, libref + * derives a doubled head count from numel(q) / (T * head_k) and refuses the case with RAD_E_SHAPE. + * `attn_paged` is also banded on `q_len`; libref describes it at one sequence. */ static inline int64_t case_M(const Case& c) { int64_t n_seq = 1; for (const P& p : c.p) if (std::strcmp(p.k, "n_seq") == 0 && p.i > 0) n_seq = p.i; @@ -357,11 +460,6 @@ static inline const char* case_dtype(const Case& c) { return "*"; } -static inline long long case_geti(const Case& c, const char* k, long long dflt) { - for (const P& p : c.p) if (std::strcmp(p.k, k) == 0) return p.i; - return dflt; -} - /* A one-line rendering of a case, so a failure names a geometry a reader can reproduce. */ static inline std::string case_str(const Case& c) { std::string s; @@ -377,18 +475,17 @@ static inline std::string case_str(const Case& c) { } /* ================================================================== a prepared case - * Operands sized by the ORACLE's description, drawn once, and copied into one buffer per side. - * The two plugins must see byte-identical inputs or the comparison is noise; drawing twice from - * one seed would work too and would be one more place for the two to diverge. */ + * Operands sized by the oracle's description, drawn once and copied into one buffer per side, so + * both plugins see byte-identical inputs. */ struct Prepared { bool ok = false; - bool skipped = false; /* the oracle declined this geometry -- a real answer */ + bool skipped = false; /* the oracle declined this geometry */ std::vector params; std::vector opd; const RadOpSchema* schema = nullptr; std::vector ta, tb; RadArgs aa{}, ab{}; - std::vector sa, sb; + GBuf sa, sb; /* each side's scratch, when its kernel asks for one */ }; static inline void h_build_tensors(std::vector& opd, bool side_a, @@ -409,10 +506,64 @@ static inline void h_build_tensors(std::vector& opd, bool side_a, } } -/* `describe` is the kernel whose opd_shape is asked. A correctness check passes the ORACLE's (the - * two sides must be handed the same bytes, and where they could disagree about an extent the - * reference semantics define the op); a benchmark of a kernel with no oracle passes its own. - * rad-kbench makes the same distinction for the same reason, in tools/opshapes.h. */ +/* The samplers' per-row `params` are a RadSampleParams struct (abi/rad_sample.h). libref describes + * them with RAD_FILL_SAMPLE_PARAMS and the history with RAD_OPD_F_IDX_HISTORY, laws h_draw does not + * implement: it draws such a plane as normals, whose integer fields and `flags` are bit patterns + * no stage acts on, and such a history as uniform ids, which never repeat. Each row is written as + * a request instead, rows differing in temperature, top-p, min-p and typical-p, with every stage + * switched on except on the last row, which is greedy. The history's second half repeats its + * first, so DRY finds repeats to penalise. rad-kbench draws the laws themselves. */ +static inline void h_sampler_rows(Prepared& pr, const Case& c) { + if (std::strncmp(c.op, "sample_", 7) != 0) return; + Opd* params = nullptr; + Opd* hist = nullptr; + for (size_t k = 0; k < pr.opd.size(); ++k) { + const char* nm = pr.schema->operands[k].name; + if (!nm || pr.opd[k].absent || pr.opd[k].d.rank != 2) continue; + if (!std::strcmp(nm, "params")) params = &pr.opd[k]; + if (!std::strcmp(nm, "history") && pr.opd[k].d.dtype == RAD_I32) hist = &pr.opd[k]; + } + const int64_t words = (int64_t)(sizeof(RadSampleParams) / 4); + if (!params || rad_dtype_bits(params->d.dtype) != 32 || params->d.shape[1] != words) return; + const int64_t M = params->d.shape[0]; + const int64_t hw = hist ? hist->d.shape[1] : 0; + for (int64_t r = 0; r < M; ++r) { + RadSampleParams sp{}; + sp.seed = 0x5eed0000u + (uint64_t)r; + sp.pos = 7 * (uint64_t)r; + sp.temp = 0.6f + 0.2f * (float)(r % 4); + sp.top_p = 0.9f - 0.1f * (float)(r % 3); + sp.min_p = 0.02f + 0.03f * (float)(r % 3); + sp.typical_p = 0.95f - 0.1f * (float)(r % 3); + sp.rep_penalty = 1.1f; + sp.freq_penalty = 0.2f; + sp.pres_penalty = 0.3f; + sp.xtc_probability = r % 2 ? 0.5f : 1.0f; + sp.xtc_threshold = 0.05f; + sp.dry_multiplier = 0.8f; + sp.dry_base = 1.75f; + sp.top_k = r % 2 ? 0 : 8; + sp.penalty_last_n = r % 3 ? (int32_t)hw : -1; + sp.dry_allowed_length = 2; + sp.dry_penalty_last_n = -1; + sp.hist_off = 0; + sp.hist_len = (int32_t)hw; + sp.mask_row = r % 2 ? (int32_t)r : -1; + sp.flags = RAD_SP_PENALTY | RAD_SP_XTC | RAD_SP_DRY | RAD_SP_LOGPROBS | + (sp.mask_row >= 0 ? RAD_SP_MASK : 0); + if (r == M - 1 && M > 1) sp.flags = RAD_SP_GREEDY; + std::memcpy(params->master.data() + (size_t)r * sizeof sp, &sp, sizeof sp); + } + if (hist) + for (int64_t r = 0; r < hist->d.shape[0]; ++r) { + int32_t* row = (int32_t*)hist->master.data() + r * hw; + for (int64_t j = hw / 2; j < hw; ++j) row[j] = row[j - hw / 2]; + } +} + +/* `describe` is the kernel whose opd_shape sizes the operands. A correctness check passes the + * oracle's, since the reference semantics define the extents; a benchmark of a kernel with no + * oracle passes its own (as tools/opshapes.h does for rad-kbench). */ static inline Prepared h_prepare(const Lib& oracle, const RadKernelInfo* describe, const Case& c, const RadKernelInfo* ka, const RadKernelInfo* kb) { Prepared pr; @@ -425,7 +576,7 @@ static inline Prepared h_prepare(const Lib& oracle, const RadKernelInfo* describ pr.opd.assign((size_t)pr.schema->n_operands, Opd{}); for (int i = 0; i < pr.schema->n_operands; ++i) { RadOpdDesc d{}; - d.idx_const = -1; /* the ABI's "draw", so a hook that leaves it alone means default */ + d.idx_const = -1; /* the ABI's "draw"; a hook that leaves it gets the default */ if (describe->opd_shape(pr.params.data(), (int)pr.params.size(), i, &d) < 0) { pr.skipped = true; return pr; @@ -435,8 +586,8 @@ static inline Prepared h_prepare(const Lib& oracle, const RadKernelInfo* describ o.absent = (d.flags & RAD_OPD_F_ABSENT) != 0; o.role = pr.schema->operands[i].role; o.n = o.absent ? 0 : desc_numel(d); - /* A rank the ABI cannot express is a hook bug, not a declined geometry, and it must not - * become a zero-extent buffer that every comparison then passes vacuously. */ + /* A rank the ABI cannot express is a hook bug; it must not become a zero-extent buffer + * that every comparison passes vacuously. */ if (!o.absent && (d.rank == 0 || d.rank > RAD_MAX_RANK)) { pr.skipped = true; return pr; } } @@ -448,8 +599,11 @@ static inline Prepared h_prepare(const Lib& oracle, const RadKernelInfo* describ for (size_t k = 0; k < pr.opd.size(); ++k) { uint64_t s = seed ^ (0x100000001b3ull * (k + 1)); h_draw(pr.opd, k, case_M(c), s ? s : 1); - pr.opd[k].a = pr.opd[k].master; - pr.opd[k].b = pr.opd[k].master; + } + h_sampler_rows(pr, c); + for (Opd& o : pr.opd) { + o.a.assign(o.master); + o.b.assign(o.master); } h_build_tensors(pr.opd, true, &pr.ta); @@ -461,25 +615,30 @@ static inline Prepared h_prepare(const Lib& oracle, const RadKernelInfo* describ pr.ab = pr.aa; pr.ab.t = pr.tb.data(); - /* The scratch hook is honoured rather than assumed away: a kernel that grew one and was handed - * null would fault, and the fault would read as a kernel bug. */ + /* Honour the scratch hook; a kernel that declares one and gets null would fault. */ if (ka && ka->scratch) { const int64_t n = ka->scratch(&pr.aa); - if (n > 0) { pr.sa.assign((size_t)n, 0); pr.aa.scratch = pr.sa.data(); pr.aa.scratch_bytes = n; } + if (n > 0) { + pr.sa.assign(nullptr, (size_t)n); + pr.aa.scratch = pr.sa.data(); + pr.aa.scratch_bytes = n; + } } if (kb && kb->scratch) { const int64_t n = kb->scratch(&pr.ab); - if (n > 0) { pr.sb.assign((size_t)n, 0); pr.ab.scratch = pr.sb.data(); pr.ab.scratch_bytes = n; } + if (n > 0) { + pr.sb.assign(nullptr, (size_t)n); + pr.ab.scratch = pr.sb.data(); + pr.ab.scratch_bytes = n; + } } pr.ok = true; return pr; } -/* Restore both sides to the drawn bytes. A benchmark that loops a launch must do this between - * iterations for any op with an INOUT operand, or it is timing a different computation each time - * -- a twenty-iteration loop over `rope` leaves the tensor rotated twenty-one times, which a - * checker then reports as a large error against a kernel that is correct (tools/opshapes.h and - * rad-kbench make the same point). */ +/* Restore both sides to the drawn bytes. A loop that relaunches an op with an INOUT operand must + * reset between iterations, or each iteration computes something different (twenty runs of + * `rope` rotate the tensor twenty times over). */ static inline void h_reset(Prepared& pr) { for (Opd& o : pr.opd) { if (o.absent || o.n <= 0) continue; diff --git a/libavx/avx_hc.cpp b/libavx/avx_hc.cpp index a60641b2..a2462447 100644 --- a/libavx/avx_hc.cpp +++ b/libavx/avx_hc.cpp @@ -1,12 +1,9 @@ -/* avx_hc.cpp -- the GATED RESIDUAL pair and the MTP head's entry. +/* avx_hc.cpp -- the gated residual pair (hc_read / hc_write) and the MTP head's entry. * - * ============================== WHAT THE GATED RESIDUAL IS ============================== - * - * Qwen4-Exp's replacement for a pre-norm and a residual add. The residual stream is `hc` times as - * wide as the model -- hidden 2560 at hc 4 is a 10240-wide stream carried through every layer, - * entered as hc identical copies of the embedding and collapsed once at the end. Every block reads - * a 2560 mix of the four and writes its output back into all four, and BOTH the read's mix and the - * write's per-stream gain are data-dependent, which is what "gated" means here. + * Gated residual: Qwen4-Exp's replacement for pre-norm + residual add. The residual stream is `hc` + * times the model width (hidden 2560 at hc 4 is a 10240-wide stream), entered as hc copies of the + * embedding and collapsed once at the end. Each block reads a mix of the streams and writes its + * output back into all of them; both the mix and the per-stream write gain are data-dependent. * * hc_read N = grouped_rmsnorm(h) one rsqrt per n-wide stream, one gain of * hc*n over all of them, `1 + w` @@ -15,86 +12,51 @@ * inj[s] = 2 * sigmoid(W_inj[s] . N / hc) * hc_write h[s] += inj[s] * y * - * THREE FACTS THAT ARE NOT DERIVABLE FROM THE OTHERS, and a second implementation has to match all - * three (docs/OPS.md states them and they are restated here because each is a silent failure): + * Three independent facts any implementation must match (docs/OPS.md); each fails silently: + * - The write updates the unnormed `h`, not `N`. Writing into `N` re-normalises the residual at + * every connection and diverges within a few layers while still producing fluent text. + * - The mix is a mean over the hc dimension, not a sum. + * - Each gate argument has its own `/ hc` (before the silu and before the inject sigmoid). * - * THE WRITE READS THE UNNORMED `h`, NOT `N`. The normalisation is consumed by the block input - * and the gates and never enters the stream. Writing into `N` instead re-normalises the residual - * at every one of 96 connections, diverges within a few layers, and still produces fluent text. + * Rounding: the reference model's grouped norm returns `.type_as(x)`, so both matrix products and + * the final multiply read a bf16 `N`. As in libref, N is rounded through h's dtype (per row here, + * via the row converter); likewise the silu output, the sigmoid gate, and `x` before the optional + * fp8 quantiser reads it back. * - * THE MIX IS A MEAN, NOT A SUM -- `.mean(dim=-2)` over the hc dimension. - * - * THERE IS A SEPARATE `/ hc` INSIDE EACH GATE ARGUMENT, before the silu and before the inject - * sigmoid. Three divisions by hc in total, none implied by the others. - * - * ============================== THE ROUNDING IS PART OF THE OP ============================== - * - * The arithmetic here is f32, but the REFERENCE MODEL's is not: torch's grouped norm returns - * `.type_as(x)`, so both matrix products and the final multiply read a bf16 `N`. libref rounds - * once per element for that reason and so does this -- through the row converter rather than - * element by element, which is the same value and one pass. The same applies to the silu output, - * the sigmoid gate, and to `x` before the optional fp8 quantiser reads it back. - * - * ============================== THE WEIGHTS ARE WIDENED ONCE PER LAUNCH ============================== - * - * This is the structural change from libref, and it is worth more here than vectorisation. Every - * product below contracts a WEIGHT against a per-token vector -- `down` is [lowrank, hc*n], `up` is - * [hc*n, lowrank], `inject_w` is [hc, hc*n] -- and libref reads those weights through `ldt` inside - * the token loop, so a 2048-row prefill chunk converts the same 10240-wide weight row 2048 times. - * Widening all three into one scratch block before the token loop makes every dot product a - * straight f32 vector reduction and converts each weight element exactly once. - * - * ONE scratch_raw CALL FOR ALL OF THEM, because the arena grows: a second call at a larger size - * frees the first block, and every worker thread would then be reading a dangling weight. + * hc_read runs as three parallel passes over the mixing matrices' rows, each row decoded in the + * kernel (E4M3 codes times their scales, or a plain row widened) into the thread's own buffer and + * met by every token row before the next: `down` [lowrank, hc*n] over its rows, then `up` [hc*n, + * lowrank] over the n output columns (hc rows each). A decode step reads each matrix once, spread + * over the team, and no widened copy of either is written. The token rows' norms, gates and mixes + * live in one scratch_raw block between the passes, since a second scratch_raw call may + * reallocate the first while workers read it. */ #include "avx_vec.h" #include "avx_common.h" +#include "avx_planes.h" using namespace avx; #include "avx_had.h" -/* A single value narrowed to a tensor's dtype and read back -- the scalar form of the rounding - * rule above, for the handful of places where it lands on one number rather than a row. */ -static inline float narrow1(uint32_t dt, float v) { - uint32_t buf[2] = { 0, 0 }; - rad_store_f32(buf, dt, 0, v); - return rad_load_f32(buf, dt, 0); -} - -/* A weight plane widened into f32, row-major and contiguous. `rows` x `cols` of the operand read - * the way libref reads it (rowoff / laststride), so a strided or rank-3 weight lands correctly. */ -static void widen_plane(const RadTensor* t, int64_t rows, int64_t cols, float* dst) { - const int64_t st = laststride(t); - for (int64_t r = 0; r < rows; ++r) { - const int64_t b = rowoff(t, r, cols); - if (st == 1) row_to_f32(t->dtype, byte_at(t->data, t->dtype, b), dst + r * cols, cols); - else for (int64_t i = 0; i < cols; ++i) dst[r * cols + i] = ldt(t, b + i * st); +/* Row r of a weight plane `cols` wide as f32, addressed as libref does (rowoff / laststride) so + * strided or rank-3 weights work. A joined plane (codes and a scale, avx_planes.h) decodes; `jr` + * is its view. */ +static void plane_row(const RadTensor* t, const avxp::ScaledRows* jr, int64_t r, int64_t cols, + float* dst) { + if (jr) { + scaled_row(*jr, r, cols, dst); + return; } + const int64_t st = laststride(t), b = rowoff(t, r, cols); + if (st == 1) row_to_f32(t->dtype, byte_at(t->data, t->dtype, b), dst, cols); + else for (int64_t i = 0; i < cols; ++i) dst[i] = ldt(t, b + i * st); } -static inline float dotf(const float* a, const float* b, int64_t n) { - vf a0 = vf_zero(), a1 = vf_zero(), a2 = vf_zero(), a3 = vf_zero(); - int64_t i = 0; - for (; i + 4 * VF_N <= n; i += 4 * VF_N) { - a0 = vf_fma(vf_loadu(a + i), vf_loadu(b + i), a0); - a1 = vf_fma(vf_loadu(a + i + VF_N), vf_loadu(b + i + VF_N), a1); - a2 = vf_fma(vf_loadu(a + i + 2 * VF_N), vf_loadu(b + i + 2 * VF_N), a2); - a3 = vf_fma(vf_loadu(a + i + 3 * VF_N), vf_loadu(b + i + 3 * VF_N), a3); - } - for (; i + VF_N <= n; i += VF_N) a0 = vf_fma(vf_loadu(a + i), vf_loadu(b + i), a0); - float s = vf_hsum(vf_add(vf_add(a0, a1), vf_add(a2, a3))); - for (; i < n; ++i) s += a[i] * b[i]; - return s; -} -/* THE SUM OF SQUARES IS ACCUMULATED IN f64 HERE AND IN f32 IN avx_norm.cpp, and that is libref's - * split reproduced rather than an inconsistency. `rmsnorm` accumulates in f32 because it is the - * op every fast kernel is checked against and an oracle tighter than the thing it certifies turns - * a tolerance into a guess; the gated residual's norm is an INTERNAL step of a fused op that no - * kernel computes separately, so libref takes the tighter accumulation there and this matches it. - * Not vectorised: it is one reduction per stream against two matrix products that dominate, and a - * vector f64 path would be a fifth numeric convention in the file. */ +/* Sum of squares in f64, unlike avx_norm.cpp's f32, matching libref's split: `rmsnorm` is checked + * against fast kernels and accumulates in f32, while this norm is an internal step of a fused op. + * Scalar: one reduction per stream, dominated by the two matrix products. */ static float rsqrt_meansq_f64(const float* v, int64_t n, float eps) { double ss = 0.0; for (int64_t i = 0; i < n; ++i) ss += (double)v[i] * (double)v[i]; @@ -102,11 +64,9 @@ static float rsqrt_meansq_f64(const float* v, int64_t n, float eps) { } /* ------------------------------------------------------------------ hc_enter */ -/* THE WIDE STREAM'S FIRST VALUE: hc identical copies of the embedding. One launch for the whole - * step. It exists rather than being folded into the embedding lookup because the lookup's weight - * is [vocab, n] and its output width is n -- a wide output would be a different op with a - * different weight shape. The streams are identical here and diverge at the first connection, - * because each block writes into all of them with a different per-branch gain. */ +/* The wide stream's initial value: hc identical copies of the embedding, one launch per step. A + * separate op because the embedding lookup's output width is n. The streams diverge at the first + * connection, where each gets its own write gain. */ AVX_KERNEL(hc_enter) { if (!rad_args_have(a, 2)) return RAD_E_INVAL; const RadTensor* x = &a->t[0]; @@ -123,9 +83,7 @@ AVX_KERNEL(hc_enter) { const int64_t hs = laststride(h); float* buf = scratch_f32((size_t)n); const float* v = in_row(x, xb, n, buf); - /* The copy is per STREAM and contiguous, where libref's inner loop is over i with the - * stream inside it -- which writes with a stride of n and defeats the store buffer. Same - * bytes, one stream at a time. */ + /* One contiguous stream at a time (libref interleaves streams, writing at stride n). */ if (hs == 1) for (int64_t c = 0; c < hc; ++c) out_row(h, hb + c * n, n, v); else for (int64_t c = 0; c < hc; ++c) for (int64_t i = 0; i < n; ++i) stt(h, hb + (c * n + i) * hs, v[i]); @@ -135,8 +93,8 @@ AVX_KERNEL(hc_enter) { /* ------------------------------------------------------------------ hc_read */ AVX_KERNEL(hc_read) { - /* NOT `rad_args_have(a, 6)`: operand 4 is the OPTIONAL inject weight, and a prefix test would - * refuse the final mixer -- the one connection that has none. The required ones are 0..3 and 5. */ + /* Not `rad_args_have(a, 6)`: operand 4 (the inject weight) is optional and absent on the + * final mixer. Operands 0..3 and 5 are required. */ if (a->n_t < 6) return RAD_E_INVAL; if (!rad_arg_in(a, 0) || !rad_arg_in(a, 1) || !rad_arg_in(a, 2) || !rad_arg_in(a, 3) || !rad_arg_in(a, 5)) return RAD_E_INVAL; @@ -149,7 +107,7 @@ AVX_KERNEL(hc_read) { const RadTensor* inj = rad_arg_in(a, 6); const RadTensor* q = rad_arg_in(a, 7); const RadTensor* s = rad_arg_in(a, 8); - const RadTensor* rq = rad_arg_in(a, 9); /* the ROTATED fp8 form, for a w4a8h consumer */ + const RadTensor* rq = rad_arg_in(a, 9); /* rotated fp8 form, for a w4a8h consumer */ const RadTensor* rs = rad_arg_in(a, 10); const int64_t n = p_int(a, "n", 0); @@ -161,11 +119,24 @@ AVX_KERNEL(hc_read) { const int64_t hn = hc * n; const int64_t rows = numel(h) / hn; - if (rows <= 0 || numel(x) < rows * n || numel(w) < hn || - numel(down) < lr * hn || numel(up) < hn * lr) return RAD_E_SHAPE; + if (rows <= 0 || numel(x) < rows * n || numel(w) < hn) return RAD_E_SHAPE; + /* Plain mixing matrices, or codes and a scale joined (`mix` e4m3), libref's reading: a plain + * matrix's dtype is what its gate is narrowed to, a joined one's gates are narrowed to h's. */ + avxp::ScaledRows jd, ju; + const bool jdown = avxp::is_joined(down), jup = avxp::is_joined(up); + if (jdown) { + if (const int st = avxp::scaled_rows(down, lr, hn, &jd); st != RAD_OK) return st; + } else if (numel(down) < lr * hn) { + return RAD_E_SHAPE; + } + if (jup) { + if (const int st = avxp::scaled_rows(up, hn, lr, &ju); st != RAD_OK) return st; + } else if (numel(up) < hn * lr) { + return RAD_E_SHAPE; + } + const uint32_t ddt = jdown ? h->dtype : down->dtype, udt = jup ? h->dtype : up->dtype; if (injw && numel(injw) < hc * hn) return RAD_E_SHAPE; - /* `inj` is what the paired hc_write consumes, so an inject WEIGHT with no inject OUTPUT is a - * caller that computed hc scalars and threw them away -- refused rather than ignored. */ + /* An inject weight without an `inj` output (consumed by hc_write) is a caller error. */ if (injw && (!inj || !inj->data || numel(inj) < rows * hc)) return RAD_E_SHAPE; int64_t g = 0, ngrp = 0; @@ -175,10 +146,8 @@ AVX_KERNEL(hc_read) { ngrp = (n + g - 1) / g; if (numel(q) < rows * n || !s || !s->data || numel(s) < rows * ngrp) return RAD_E_SHAPE; } - /* The rotated form rotates each scale group whole, so the group must tile the row exactly and - * be a power of two: a block that straddled the end of the row would mix real values with - * padding, and no weight block was rotated that way. It is had_quant_act_fp8 of the stored `x` - * -- the operand's consumer cannot tell which op wrote it. */ + /* The rotated form is had_quant_act_fp8 of the stored `x`: each scale group is rotated whole, + * so the group must be a power of two that tiles the row. */ int64_t rg = 0; if (rq && rq->data) { rg = p_int(a, "group", 0); @@ -188,40 +157,40 @@ AVX_KERNEL(hc_read) { if (rg > AVX_HAD_MAX) return RAD_E_UNSUPPORTED; } - /* The gain and all three weight planes, widened once. See the header on why this is one call. */ + /* The gain, the inject rows (hc of them, widened once), and the token rows' norms N [rows][hn], + * gates D [rows][lr] and mixes X [rows][n], in one scratch_raw block (see header). */ auto pad = [](size_t v) { return (v + 15) & ~(size_t)15; }; const size_t o_gain = 0; - const size_t o_down = pad(o_gain + (size_t)hn); - const size_t o_up = pad(o_down + (size_t)lr * (size_t)hn); - const size_t o_inj = pad(o_up + (size_t)hn * (size_t)lr); - const size_t total = o_inj + (injw ? (size_t)hc * (size_t)hn : 0) + 16; + const size_t o_inj = pad(o_gain + (size_t)hn); + const size_t o_N = pad(o_inj + (injw ? (size_t)hc * (size_t)hn : 0)); + const size_t o_D = pad(o_N + (size_t)rows * (size_t)hn); + const size_t o_X = pad(o_D + (size_t)rows * (size_t)lr); + const size_t total = o_X + (size_t)rows * (size_t)n + 16; float* blk = (float*)scratch_raw(total * sizeof(float)); float* gain = blk + o_gain; - float* dn = blk + o_down; - float* upw = blk + o_up; float* iw = blk + o_inj; + float* NP = blk + o_N; + float* DP = blk + o_D; + float* XP = blk + o_X; { const int64_t ws = laststride(w); if (ws == 1) row_to_f32(w->dtype, w->data, gain, hn); else for (int64_t i = 0; i < hn; ++i) gain[i] = ldt(w, i * ws); if (wadd != 0.0f) for (int64_t i = 0; i < hn; ++i) gain[i] += wadd; } - widen_plane(down, lr, hn, dn); - widen_plane(up, hn, lr, upw); - if (injw) widen_plane(injw, hc, hn, iw); + if (injw) + for (int64_t c = 0; c < hc; ++c) plane_row(injw, nullptr, c, hn, iw + c * hn); + const avxp::ScaledRows* jdp = jdown ? &jd : nullptr; + const avxp::ScaledRows* jup_p = jup ? &ju : nullptr; + const float invhc = 1.0f / (float)hc; + /* ---- grouped norm: one rsqrt per stream, the full-width gain, then one round trip through + * h's dtype for the whole wide row. */ AVX_PARALLEL_FOR_IF(rows >= 2) for (int64_t r = 0; r < rows; ++r) { - const int64_t hb = rowoff(h, r, hn), xb = rowoff(x, r, n); - const int64_t xs = laststride(x); - float* N = scratch_f32((size_t)hn); - float* tmp = scratch_f32_b((size_t)hn); - float* dv = scratch_f32_c((size_t)(lr + n) + 16); - float* xv = dv + lr + 8; - - /* ---- the grouped norm: one rsqrt per stream over its own n, then the full-width gain, - * then a single round trip through h's dtype for the whole wide row. */ - const float* hv = in_row(h, hb, hn, tmp); + float* N = NP + r * hn; + float* tmp = scratch_f32((size_t)hn); + const float* hv = in_row(h, rowoff(h, r, hn), hn, tmp); for (int64_t c = 0; c < hc; ++c) { const float sc = rsqrt_meansq_f64(hv + c * n, n, eps); const vf vs = vf_set1(sc); @@ -235,68 +204,71 @@ AVX_KERNEL(hc_read) { row_from_f32(h->dtype, N, tmp, hn); row_to_f32(h->dtype, tmp, N, hn); } + } - /* ---- the read gate: hc*n -> lowrank -> hc*n, silu between and sigmoid after. */ - for (int64_t j = 0; j < lr; ++j) { - const float t = dotf(N, dn + j * hn, hn) / (float)hc; - dv[j] = narrow1(down->dtype, t / (1.0f + std::exp(-t))); /* silu */ + /* ---- the read gate's first product, hc*n -> lowrank, and the silu, one row of `down` at a + * time against every token row. */ + AVX_PARALLEL_FOR_IF(rows * lr * hn >= 65536) + for (int64_t j = 0; j < lr; ++j) { + float* wr = scratch_f32((size_t)hn); + plane_row(down, jdp, j, hn, wr); + for (int64_t r = 0; r < rows; ++r) { + const float t = dotf(NP + r * hn, wr, hn) / (float)hc; + DP[r * lr + j] = narrow1(ddt, t / (1.0f + sc_exp(-t))); /* silu */ } + } - /* ---- the mix, and the MEAN over the streams. */ - const float invhc = 1.0f / (float)hc; - for (int64_t i = 0; i < n; ++i) { + /* ---- the second product, lowrank -> hc*n, its sigmoid, and the mix: the mean over the + * streams. Output column i reads `up` rows c*n + i of every stream c. */ + AVX_PARALLEL_FOR_IF(rows * lr * hn >= 65536) + for (int64_t i = 0; i < n; ++i) { + float* ur = scratch_f32((size_t)(hc * lr)); + for (int64_t c = 0; c < hc; ++c) plane_row(up, jup_p, c * n + i, lr, ur + c * lr); + for (int64_t r = 0; r < rows; ++r) { + const float* N = NP + r * hn; float acc = 0.0f; for (int64_t c = 0; c < hc; ++c) { - const int64_t row = c * n + i; - const float gv = dotf(dv, upw + row * lr, lr); - acc += narrow1(up->dtype, 1.0f / (1.0f + std::exp(-gv))) * N[row]; + const float gv = dotf(DP + r * lr, ur + c * lr, lr); + acc += narrow1(udt, 1.0f / (1.0f + sc_exp(-gv))) * N[c * n + i]; } - xv[i] = acc * invhc; + XP[r * n + i] = acc * invhc; } - if (xs == 1) out_row(x, xb, n, xv); - else for (int64_t i = 0; i < n; ++i) stt(x, xb + i * xs, xv[i]); + } + + AVX_PARALLEL_FOR_IF(rows >= 2) + for (int64_t r = 0; r < rows; ++r) { + float* N = NP + r * hn; + float* xv = XP + r * n; + float* tmp = scratch_f32((size_t)hn); + out_row(x, rowoff(x, r, n), n, xv); /* ---- the per-branch write gates. */ if (injw && inj) { const int64_t ib = rowoff(inj, r, hc), is = laststride(inj); for (int64_t c = 0; c < hc; ++c) { const float acc = dotf(N, iw + c * hn, hn) * invhc; - stt(inj, ib + c * is, 2.0f / (1.0f + std::exp(-acc))); + stt(inj, ib + c * is, 2.0f / (1.0f + sc_exp(-acc))); } } - /* ---- the optional fp8 form of x, READ BACK FROM WHAT WAS STORED. `x` is narrowed to its - * own dtype first and the codes come from the narrowed value, not from the accumulator, - * because that is what a fused kernel necessarily does and the two have to agree bit for - * bit. The round trip is done in this buffer rather than by re-reading the operand: same - * arithmetic, and it does not depend on the store having retired. */ + /* ---- optional fp8 form of x, taken from the stored (narrowed) value rather than the + * accumulator, as a fused kernel must, so the two agree bit for bit. */ if (((q && q->data) || rg) && x->dtype != RAD_F32) { row_from_f32(x->dtype, xv, tmp, n); row_to_f32(x->dtype, tmp, xv, n); } if (q && q->data) { - const int64_t qb = rowoff(q, r, n), qs = laststride(q); - float* qv = N; /* N is dead from here; the codes reuse its storage. */ + float* qv = N; /* the row's norm is dead here; its storage takes the codes. */ for (int64_t gi = 0; gi < ngrp; ++gi) { const int64_t k0 = gi * g, k1 = (k0 + g < n) ? k0 + g : n; - const float amax = row_amax(xv + k0, k1 - k0); - const float sc = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f; - const float invs = 1.0f / sc; - const vf vi = vf_set1(invs), hi = vf_set1(448.0f), lo = vf_set1(-448.0f); - int64_t i = k0; - for (; i + VF_N <= k1; i += VF_N) - vf_storeu(qv + i, vf_min(vf_max(vf_mul(vf_loadu(xv + i), vi), lo), hi)); - for (; i < k1; ++i) { - float v = xv[i] * invs; - qv[i] = v > 448.0f ? 448.0f : (v < -448.0f ? -448.0f : v); - } + float sc; + fp8_group(xv, qv, k0, k1, &sc); stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc); } - if (qs == 1) out_row(q, qb, n, qv); - else for (int64_t i = 0; i < n; ++i) stt(q, qb + i * qs, qv[i]); + out_row(q, rowoff(q, r, n), n, qv); } - /* ---- the optional ROTATED fp8 form of x, from the same stored values. */ + /* ---- optional rotated fp8 form of x, from the same stored values. */ if (rg) { float* rv = N; /* N and tmp are dead once the plain codes are stored. */ float* rc = tmp; @@ -308,17 +280,15 @@ AVX_KERNEL(hc_read) { fp8_group(rv, rc, gi * rg, gi * rg + rg, &sc); stt(rs, rowoff(rs, r, rgrp) + gi * laststride(rs), sc); } - const int64_t qb = rowoff(rq, r, n), qs = laststride(rq); - if (qs == 1) out_row(rq, qb, n, rc); - else for (int64_t i = 0; i < n; ++i) stt(rq, qb + i * qs, rc[i]); + out_row(rq, rowoff(rq, r, n), n, rc); } } return RAD_OK; } /* ------------------------------------------------------------------ hc_write */ -/* `h[s] += inj[s] * y` for each of the hc streams, in place. `h` is the only output and it is the - * stream the paired read was handed, UNNORMED and unchanged by it. */ +/* h[s] += inj[s] * y for each of the hc streams, in place, on the unnormed stream the paired read + * received. */ AVX_KERNEL(hc_write) { if (!rad_args_have(a, 3)) return RAD_E_INVAL; const RadTensor* y = &a->t[0]; @@ -363,36 +333,27 @@ AVX_KERNEL(hc_write) { /* ================================================================== mtp_enter * - * THE MULTI-TOKEN-PREDICTION HEAD'S ENTRY, for a model whose residual stream is `hc` wide. + * Entry of the multi-token-prediction head for a model with an `hc`-wide residual stream. * - * A pre-norm MTP head joins the trunk's hidden state and the next token's embedding with ONE `fc` - * over their concatenation. Qwen4-Exp's cannot: its hidden state is the WIDE stream and the - * checkpoint carries TWO square matrices, so the hidden half is `fc_h` applied to EACH of the hc - * sub-streams and the embedding half is one n-wide product added into all of them. + * A pre-norm MTP head usually joins the trunk's hidden state and the next token's embedding with one + * `fc` over their concatenation. Qwen4-Exp's hidden state is the wide stream and the checkpoint has + * two square matrices: `fc_h` is applied to each of the hc sub-streams, and one n-wide embedding + * product is added into all of them. * * ne[j] = e[j] * rsqrt(mean(e^2) + eps) * (w_e[j] + wadd) * fe[i] = sum_j fc_e[i][j] * ne[j] * nh[k][j] = h[k*n+j] * rs[k] * (w_h[k*n+j] + wadd) * x[k*n+i] = sum_j fc_h[i][j] * nh[k][j] + fe[i] * - * `ngroup` IS THE ONE THING THE CHECKPOINT DOES NOT SAY: a [hc*n] gain fits both a grouped norm - * (hc rsqrts) and a flat one (a single rsqrt over the wide row). Both are self-consistent and no - * per-op oracle can tell them apart; the cheap empirical answer is the draft acceptance rate, so - * the choice is carried as a parameter and asked once at declare. + * `ngroup` is not determined by the checkpoint: a [hc*n] gain fits both a grouped norm (hc rsqrts) + * and a flat one (one rsqrt over the wide row). No per-op oracle distinguishes them (the draft + * acceptance rate does), so it is a parameter fixed at declare. * - * ============================== IT IS A GEMM AND IS RUN AS ONE ============================== - * - * libref computes this token by token, converting `fc_h` and `fc_e` out of their stored dtype - * inside the innermost loop -- so an [n, n] weight is converted `rows * hc` times. Restructured - * here as what it is: the norms are materialised into a PANEL first ([rows*hc, n] for the hidden - * half, [rows, n] for the embedding), and then the loop runs over the OUTPUT COLUMN i, packing - * `fc_h` row i and `fc_e` row i once and contracting them against every panel row. - * - * That is the same choice avx_gemm.cpp makes and for the same reason -- but note what it does NOT - * do: it does not pre-widen the whole [n, n] weight, which at n = 2560 would be 26 MiB per matrix. - * One row at a time, thread-local, is bounded by n floats and the weight is still read exactly - * once. The panel is the thing that had to be materialised, and it is rows*hc*n -- 328 KiB on a - * draft round, which is what this op is for. + * Run as a GEMM. libref converts `fc_h` and `fc_e` inside the innermost loop, `rows * hc` times. + * Here the norms are first materialised into panels ([rows*hc, n] hidden, [rows, n] embedding), + * then each output column i widens row i of `fc_h` and `fc_e` once and contracts it against every + * panel row. The whole [n, n] weight is never widened (26 MiB per matrix at n = 2560); each weight + * element is still converted once. */ AVX_KERNEL(mtp_enter) { if (!rad_args_have(a, 7)) return RAD_E_INVAL; @@ -416,7 +377,19 @@ AVX_KERNEL(mtp_enter) { const int64_t rows = numel(h) / hn; if (rows <= 0 || numel(e) < rows * n || numel(x) < rows * hn) return RAD_E_SHAPE; if (numel(w_h) < hn || numel(w_e) < n) return RAD_E_SHAPE; - if (numel(fc_h) < n * n || numel(fc_e) < n * n) return RAD_E_SHAPE; + /* Plain fc matrices, or codes and a scale joined (`fc` e4m3), as hc_read's. */ + avxp::ScaledRows jh, je; + const bool jfh = avxp::is_joined(fc_h), jfe = avxp::is_joined(fc_e); + if (jfh) { + if (const int st = avxp::scaled_rows(fc_h, n, n, &jh); st != RAD_OK) return st; + } else if (numel(fc_h) < n * n) { + return RAD_E_SHAPE; + } + if (jfe) { + if (const int st = avxp::scaled_rows(fc_e, n, n, &je); st != RAD_OK) return st; + } else if (numel(fc_e) < n * n) { + return RAD_E_SHAPE; + } auto pad = [](size_t v) { return (v + 15) & ~(size_t)15; }; const size_t o_gh = 0; @@ -441,8 +414,8 @@ AVX_KERNEL(mtp_enter) { } } - /* Phase one: the two norms, into the panel. Both are rounded to their source tensor's dtype, - * which is what `.type_as(x)` does in the reference model and what the products then read. */ + /* Phase one: both norms into the panels, rounded to their source tensor's dtype (the + * reference model's `.type_as(x)`). */ AVX_PARALLEL_FOR_IF(rows * hn >= AVX_PAR_MIN) for (int64_t r = 0; r < rows; ++r) { float* buf = scratch_f32((size_t)hn); @@ -470,17 +443,19 @@ AVX_KERNEL(mtp_enter) { } } - /* Phase two: one output column at a time, so each weight row is widened exactly once. */ + /* Phase two: one output column at a time, so each weight row is widened once. */ const int64_t xs = laststride(x); AVX_PARALLEL_FOR_IF(rows * hc * n >= AVX_PAR_MIN) for (int64_t i = 0; i < n; ++i) { float* fh = scratch_f32((size_t)n); float* fe = scratch_f32_b((size_t)n); - const int64_t fhb = rowoff(fc_h, i, n), fhs = laststride(fc_h); - const int64_t feb = rowoff(fc_e, i, n), fes = laststride(fc_e); - if (fhs == 1) row_to_f32(fc_h->dtype, byte_at(fc_h->data, fc_h->dtype, fhb), fh, n); + const int64_t fhb = jfh ? 0 : rowoff(fc_h, i, n), fhs = laststride(fc_h); + const int64_t feb = jfe ? 0 : rowoff(fc_e, i, n), fes = laststride(fc_e); + if (jfh) scaled_row(jh, i, n, fh); + else if (fhs == 1) row_to_f32(fc_h->dtype, byte_at(fc_h->data, fc_h->dtype, fhb), fh, n); else for (int64_t j = 0; j < n; ++j) fh[j] = ldt(fc_h, fhb + j * fhs); - if (fes == 1) row_to_f32(fc_e->dtype, byte_at(fc_e->data, fc_e->dtype, feb), fe, n); + if (jfe) scaled_row(je, i, n, fe); + else if (fes == 1) row_to_f32(fc_e->dtype, byte_at(fc_e->data, fc_e->dtype, feb), fe, n); else for (int64_t j = 0; j < n; ++j) fe[j] = ldt(fc_e, feb + j * fes); for (int64_t r = 0; r < rows; ++r) { diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index 8fceca98..e98f93fa 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -1,49 +1,34 @@ -/* avx_isa.h -- what this machine can execute, and the one list of ops the whole plugin is built - * around. +/* avx_isa.h -- CPU feature detection, and the single list of ops the plugin is built around. * - * ============================== WHY A DISPATCH AT ALL ============================== + * Why dispatch. The plugin is a shared object the engine dlopens (spec.md §2) and runs on machines + * it was not built on, so -march=native is out: an AVX-512 build SIGILLs on older CPUs. A baseline + * build gives up most of the machine (an AVX-512 rmsnorm moves 64 bytes a cycle, SSE2 16). So the + * kernels are compiled once per ISA level into separate objects with their own -m flags, and one + * baseline translation unit (avx_dispatch.cpp) picks between them at load. Nothing outside the + * per-level objects may contain an instruction above the baseline: the dispatcher, registry and + * schemas are built without -m flags, since a stray intrinsic there would fault before dispatch. * - * A kernel plugin is a shared object the engine dlopens (spec.md §2). It is shipped, copied, - * copied and run on machines nobody compiled it on, so `-march=native` is not an option here even - * though it is the obvious one: a binary built with it on an AVX-512 part SIGILLs on the first - * vmovdqu64 anywhere older, and the failure is a signal rather than a diagnostic. The - * alternative -- compile everything baseline -- gives up most of the machine: an AVX-512 rmsnorm - * moves 64 bytes a cycle where the SSE2 one moves 16. - * - * So: the kernels are compiled ONCE PER ISA LEVEL into separate objects, each with its own - * -m flags, and ONE baseline-compiled translation unit (avx_dispatch.cpp) picks between them at - * load. Nothing outside those per-level objects may contain an instruction above the baseline, - * which is why the dispatcher, the registry and the schemas are all in files with no -m flags on - * them: a single stray intrinsic in the registry would fault before the dispatch ever ran. - * - * ============================== THE FOUR LEVELS ============================== - * - * AVX_LEVEL_SCALAR (0) x86-64 baseline. SSE2 exists on every x86-64 and the compiler uses it - * for scalar float, but nothing here is hand-vectorised. ALWAYS CORRECT, - * always selectable, and the answer every other level is checked against. - * AVX_LEVEL_AVX (1) AVX. 256-bit FLOAT only -- Sandy/Ivy Bridge have no 256-bit integer - * ALU and no FMA, so the bf16<->f32 conversions in avx_vec.h split into - * two 128-bit halves and every a*b+c is a separate mul and add. + * Levels: + * AVX_LEVEL_SCALAR (0) x86-64 baseline. The compiler uses SSE2 for scalar float, but nothing is + * hand-vectorised. Always selectable; every other level is checked + * against it. + * AVX_LEVEL_AVX (1) AVX. 256-bit float only: Sandy/Ivy Bridge have no 256-bit integer ALU + * and no FMA, so the bf16<->f32 conversions in avx_vec.h split into two + * 128-bit halves and every a*b+c is a separate mul and add. * AVX_LEVEL_AVX2 (2) AVX2 + FMA + F16C. 256-bit integer, vpermd/vpgatherdd, hardware f16. - * This is the level almost every x86 machine made since 2013 runs. - * AVX_LEVEL_AVX512 (3) AVX-512 F/BW/DQ/VL. 512-bit, and -- what actually matters more than the - * width -- 32 architectural vector registers instead of 16, which is what - * lets the GEMM microkernel hold a 12x2 accumulator block in registers, - * and write masks, which remove the scalar tail loop from every op. + * Nearly every x86 machine since 2013. + * AVX_LEVEL_AVX512 (3) AVX-512 F/BW/DQ/VL. Besides the width: 32 vector registers instead of 16 + * (room for the GEMM microkernel's 12x2 accumulator block) and write + * masks, which remove the scalar tail loops. * - * AVX-512 IS NOT ONE FEATURE and the check has to be the conjunction: a Knights Landing has F but - * not BW/DQ/VL, and a kernel that tested `avx512f` alone and then used a byte shuffle would fault - * on it. __builtin_cpu_supports is used rather than raw CPUID because it also consults XGETBV -- - * a CPU may enumerate AVX-512 while the OS has not enabled the ZMM state, and using it then - * faults. Missing that check is the single most common way a hand-rolled CPUID dispatch is wrong. + * AVX-512 is checked as the conjunction F && BW && DQ && VL: Knights Landing has F without the + * others. __builtin_cpu_supports is used instead of raw CPUID because it also checks XGETBV; a CPU + * may enumerate AVX-512 while the OS has not enabled ZMM state, and using it then faults. * - * ============================== THE OP LIST IS A MACRO ============================== - * - * AVX_OP_LIST below is the only place the op set is written down. It generates the dispatch table - * struct, the four extern table declarations, the baseline thunks the registry rows point at, and - * the harness's op enumeration. Adding an op means adding one line here and one definition per - * level; forgetting either is a link error rather than a row that silently resolves to null. - * libref uses the same technique for its shape hooks (`fn ## _shape`, libref/ref_ops.h). + * AVX_OP_LIST is the only place the op set is written. It generates the table struct, the four + * table declarations, the registry's baseline thunks and the harness's op enumeration. An op + * missing a definition at any level is a link error, never a null table entry. (libref uses the + * same technique for its shape hooks, libref/ref_ops.h.) */ #ifndef RAD_AVX_ISA_H #define RAD_AVX_ISA_H @@ -68,17 +53,17 @@ int avx_isa_detect(void); int avx_isa_level(void); const char* avx_isa_name(int level); -/* FORCE A LEVEL, FOR THE CHECKER AND FOR NOTHING ELSE. - * - * It is an exported C symbol rather than an environment variable on purpose: this project's rule - * is that an env switch that changes what a kernel computes is exactly the defect that makes "what - * actually ran" unanswerable, and the engine must never be able to reach this. A symbol the test - * binary dlsym's cannot be set by accident in a deployment and does not appear in a shell - * history. Returns the level actually selected, which is - * min(requested, detected) -- asking for a level the machine cannot execute is clamped rather than - * honoured, because honouring it means SIGILL. */ +/* Force a level; for the checker only. An exported symbol rather than an environment variable, so + * a deployment cannot change what a kernel computes by accident and the engine never reaches it. + * Returns the level selected, min(requested, detected): a level the CPU cannot execute would + * SIGILL. */ int avx_isa_force(int level); +/* Run every parallel region with `threads` team threads whatever its work threshold, or restore + * the thresholds with 0; for the checker only, like avx_isa_force. Returns the team size now + * forced, 0 when the plugin was built without OpenMP. */ +int avx_par_force(int threads); + /* ================================================================== the op list * X(name) -- `name` is both the op name in the conventional vocabulary (docs/OPS.md) and the * suffix of every implementation symbol: avx__sc / _v1 / _v2 / _v3. */ @@ -94,9 +79,11 @@ int avx_isa_force(int level); X(scale_rows) X(scale) X(fill) X(act_mul) \ X(seg_mean) X(mul_weight) X(pool_rows) X(relu) \ X(clamp) X(conv2d) X(conv1d_dw) X(rel_sinusoid) \ + X(seg_sinusoid) X(conv2d_unfold) \ /* ---- quantisation and rotation */ \ - X(quant_act_i8) X(had_quant_act_i8) X(quant_act_fp8) X(had_quant_act_fp8) \ - X(gram_accum) X(rmsnorm_had_quant_i8) X(gated_had_quant_i8) X(dequant) \ + X(quant_act_i8) X(quant_act_i8g) X(had_quant_act_i8) X(quant_act_fp8) \ + X(had_quant_act_fp8) X(gram_accum) X(rmsnorm_had_quant_i8) X(gated_had_quant_i8) \ + X(dequant) \ X(rmsnorm_quant_fp8) X(gated_quant_fp8) X(givens_rotate) X(givens_dense_quant) \ /* ---- gemm and the vocabulary edges */ \ X(gemm_nt) X(gemm_nt_bias) X(gemm_nt_q) X(gemm_nt_q_bias) \ @@ -104,6 +91,7 @@ int avx_isa_force(int level); /* ---- attention */ \ X(attn_paged) X(attn_dense) X(kv_store) 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) \ /* ---- mixture of experts */ \ X(router_topk) X(moe_scatter) X(moe_gemm) X(moe_gemm_q) \ X(moe_gather) X(row_topk) X(row_topk_merge) X(logit_rerank) \ @@ -113,14 +101,20 @@ int avx_isa_force(int level); X(gdn_recurrent_update) X(gdn_conv_recurrent_update) X(gdn_gated_rmsnorm) \ /* ---- collectives */ \ X(all_reduce) X(all_gather) \ + /* ---- image generation */ \ + X(ln_mod) X(gate_add) X(ln_mod_quant_fp8) X(timestep_embed) \ + X(gather_rows2) X(lane_gather) X(lane_store) X(randn_lanes) \ + X(flow_euler) X(chan_affine) X(conv2d_nhwc) X(l2norm_chan) \ + X(d2s_add) X(s2d_avg_add) X(to_rgba8) X(gelu_tanh) \ + X(scatter_add_rows) X(attn_prefix_self) \ /* ---- sampling, and the drafter's token walk */ \ X(sample_penalties) X(sample_dry) X(sample_temp) X(sample_topk) \ X(sample_topp) X(sample_minp) X(sample_typical) X(sample_xtc) \ X(sample_merge_topk) X(sample_mask) X(sample_pick) X(sample_argmax) \ - X(sample_logprobs) X(dflash_select) + X(sample_logprobs) X(dflash_select) X(dflash_conv) -/* The table one ISA level fills. One member per op, same order as AVX_OP_LIST. A missing - * definition is a link error against the level's own table definition in avx_table.cpp. */ +/* One ISA level's table: one member per op, in AVX_OP_LIST order. A missing definition is a link + * error from that level's avx_table.cpp object. */ typedef struct AvxKernelTable { #define AVX_DECL_MEMBER(nm) int (*nm)(const RadArgs*, RadStream); AVX_OP_LIST(AVX_DECL_MEMBER) @@ -135,7 +129,7 @@ extern const AvxKernelTable avx_table_v3; /* The table for a level, or the scalar table if that level was not built. */ const AvxKernelTable* avx_table_for(int level); -/* The live table -- what the thunks call. Repointed by avx_isa_force. */ +/* The live table the thunks call. Repointed by avx_isa_force. */ const AvxKernelTable* avx_table_live(void); #ifdef __cplusplus diff --git a/libavx/avx_misc.cpp b/libavx/avx_misc.cpp index 061722df..75b5cc6f 100644 --- a/libavx/avx_misc.cpp +++ b/libavx/avx_misc.cpp @@ -1,41 +1,26 @@ -/* avx_misc.cpp -- the PLE pair, the hashed n-gram ids, and the two collectives. +/* avx_misc.cpp -- the PLE pair, the hashed n-gram ids, and the two collectives. Mostly scalar: * - * Grouped because none of them is a vector kernel and the reason differs in each case, which is - * worth saying rather than leaving as an absence: + * ple_gate vectorises the per-stream norms and the gated broadcast of `v`. The dot between the + * two normed streams is accumulated in f64, as in libref: it feeds a signed square root, whose + * relative sensitivity is unbounded near zero, so an f32 reduction over a 10240-wide product + * would move the gate past tolerance on rows near the hinge. * - * ple_gate IS vectorised, in the two places that carry the work -- the per-stream norms and the - * gated broadcast of `v`. What is not is the dot between the two normed streams, which is - * accumulated in f64 because libref accumulates it in f64 and this is the one op where that - * choice is visible: the dot feeds a SIGNED SQUARE ROOT, which has unbounded relative sensitivity - * near zero, so an f32 reduction of a 10240-wide product would move the gate by more than the - * tolerance on exactly the rows where the gate is near its hinge. + * ple_conv is a width-4 depthwise convolution with taps `dilation` apart; channels are the + * parallel axis and the four-term inner loop has nothing to vectorise. * - * ple_conv is a depthwise convolution of width 4 over a channel, which is 4 multiplies per - * output element with the taps `dilation` apart. The channel loop is the parallel axis and the - * inner one is four terms; there is no vector work in it that the outer parallelism does not - * already have. What it gets instead is the rolling-window rule written out exactly. + * ngram_ids is integer hashing with a data-dependent early cut, using torch's arithmetic (a + * wrapping 64-bit multiply and a flooring modulo). * - * ngram_ids is INTEGER HASHING with a data-dependent early cut, and its arithmetic is defined by - * torch's -- a wrapping 64-bit multiply and a FLOORING modulo, neither of which is C's. There is - * nothing here to vectorise and a great deal to get exactly right. - * - * all_reduce / all_gather serve WORLD SIZE 1 and refuse anything wider by name. See the note on - * the collectives below; it is a deliberate limit, not an omission. + * all_reduce / all_gather serve world size 1 only and refuse wider worlds (see below). */ #include "avx_vec.h" #include "avx_common.h" using namespace avx; -static inline float narrow1(uint32_t dt, float v) { - uint32_t buf[2] = { 0, 0 }; - rad_store_f32(buf, dt, 0, v); - return rad_load_f32(buf, dt, 0); -} - -/* One group's reciprocal RMS over `n` contiguous f32. f64 accumulation, matching libref's - * `group_rsqrt`: the rsqrt is per n-wide stream while the gain below it spans all hc*n, and that - * asymmetry is the whole of what `group_size` means on Qwen4ExpTextRMSNorm. */ +/* Reciprocal RMS of one n-wide stream, accumulated in f64 as libref's `group_rsqrt`. The rsqrt is + * per stream while the gain spans all hc*n; that is what `group_size` means on + * Qwen4ExpTextRMSNorm. */ static float group_rsqrt_f64(const float* v, int64_t n, float eps) { double acc = 0; for (int64_t d = 0; d < n; ++d) acc += (double)v[d] * (double)v[d]; @@ -43,21 +28,18 @@ static float group_rsqrt_f64(const float* v, int64_t n, float eps) { } /* ------------------------------------------------------------------ ple_gate */ -/* k [M][hc*n] key_proj(embedding), UN-normed - * q [M][hc*n] the incoming hyper-connection stream, UN-normed - * v [M][n] value_proj(embedding) -- ONE row, gated differently per stream +/* k [M][hc*n] key_proj(embedding), unnormed + * q [M][hc*n] the incoming hyper-connection stream, unnormed + * v [M][n] value_proj(embedding): one row, gated differently per stream * w_key / w_query / w_conv [hc*n] gains - * gv [M][hc*n] out, UN-normed: what the residual add reads - * gvn [M][hc*n] out, normed: what the convolution reads + * gv [M][hc*n] out, unnormed: read by the residual add + * gvn [M][hc*n] out, normed: read by the convolution * - * THE THIRD NORM IS TAKEN OVER WHAT THIS OP ITSELF WROTE, and it is READ BACK rather than carried - * in registers -- which is why the op owns all three norms instead of the graph owning the last - * one. Splitting it would make two definitions of the same rounding. + * The third norm is taken over gv as stored (rounded through its dtype), which is why this op owns + * all three norms. * - * THE SIGNED SQUARE ROOT IS IN THE REFERENCE'S ORDER: the magnitude is clamped to `gate_eps`, the - * root is taken of the clamped magnitude, and the sign is reapplied afterwards. Clamping after the - * root, or taking the root of the signed value, are both different functions near zero and the - * gate spends its life near zero. */ + * Signed square root in the reference's order: clamp the magnitude to `gate_eps`, take the root, + * reapply the sign. Other orders differ near zero, where the gate usually sits. */ AVX_KERNEL(ple_gate) { if (!rad_args_have(a, 8)) return RAD_E_INVAL; const RadTensor* k = &a->t[0]; @@ -70,12 +52,12 @@ AVX_KERNEL(ple_gate) { const RadTensor* gvn = &a->t[7]; const int64_t n = p_int(a, "n", 0); - /* `v` is [M, n] and it is the call; `M` is the band. */ + /* Rows come from `v` ([M, n]); the `M` parameter is the band's upper bound. */ const int64_t M = n > 0 ? band_rows(numel(v) / n, p_int(a, "M", 0)) : 0; const int64_t hc = p_int(a, "hc", 0); const float eps = p_f32(a, "eps", 1e-6f); const float wadd = p_f32(a, "wadd", 0.0f); - /* The floor the gate's magnitude is clamped to before the square root. */ + /* Floor for the gate's magnitude before the square root. */ const float geps = p_f32(a, "gate_eps", 1e-6f); if (M <= 0 || n <= 0 || hc <= 0) return RAD_E_SHAPE; const int64_t hn = hc * n; @@ -83,8 +65,8 @@ AVX_KERNEL(ple_gate) { if (numel(wk) < hn || numel(wq) < hn || numel(wc) < hn) return RAD_E_SHAPE; if (numel(gv) < M * hn || numel(gvn) < M * hn) return RAD_E_SHAPE; - /* The three gains, widened once with `wadd` folded in. One allocation -- the arena grows, so a - * second scratch_raw would free this one under the worker threads. */ + /* The three gains, widened once with `wadd` folded in, in one allocation: a second + * scratch_raw call could free this one under the worker threads. */ float* gains = (float*)scratch_raw((size_t)(3 * hn) * sizeof(float) + 64); float* gk = gains; float* gq = gains + hn; @@ -98,7 +80,6 @@ AVX_KERNEL(ple_gate) { } } - const int64_t gls = laststride(gv), gnls = laststride(gvn); AVX_PARALLEL_FOR_IF(M >= 2) for (int64_t m = 0; m < M; ++m) { @@ -116,8 +97,7 @@ AVX_KERNEL(ple_gate) { for (int64_t c = 0; c < hc; ++c) { const float rk = group_rsqrt_f64(kk + c * n, n, eps); const float rq = group_rsqrt_f64(qq + c * n, n, eps); - /* f64, and see the file header: the dot feeds a signed square root whose relative - * sensitivity is unbounded near zero. */ + /* f64: the dot feeds the signed square root (see the file header). */ double dot = 0; for (int64_t d = 0; d < n; ++d) { const int64_t j = c * n + d; @@ -128,7 +108,7 @@ AVX_KERNEL(ple_gate) { float s = (float)(dot / std::sqrt((double)n)); const float mag = std::sqrt(std::fabs(s) < geps ? geps : std::fabs(s)); s = s > 0.0f ? mag : (s < 0.0f ? -mag : 0.0f); - const float g = 1.0f / (1.0f + std::exp(-s)); + const float g = 1.0f / (1.0f + sc_exp(-s)); const vf vg = vf_set1(g); int64_t d = 0; @@ -136,12 +116,9 @@ AVX_KERNEL(ple_gate) { vf_storeu(out + c * n + d, vf_mul(vg, vf_loadu(vv + d))); for (; d < n; ++d) out[c * n + d] = g * vv[d]; } - if (gls == 1) out_row(gv, gb, hn, out); - else for (int64_t j = 0; j < hn; ++j) stt(gv, gb + j * gls, out[j]); + out_row(gv, gb, hn, out); - /* The third norm, over what was just written -- read BACK through gv's dtype, not carried - * in registers. The round trip is done here rather than by re-reading the operand: same - * arithmetic, and it does not depend on the store having retired. */ + /* Third norm over gv as stored: round `out` through gv's dtype in scratch. */ if (gv->dtype != RAD_F32) { row_from_f32(gv->dtype, out, kv, hn); row_to_f32(gv->dtype, kv, out, hn); @@ -153,31 +130,30 @@ AVX_KERNEL(ple_gate) { qv[j] = narrow1(gvn->dtype, out[j] * r * gc[j]); } } - if (gnls == 1) out_row(gvn, nb, hn, qv); - else for (int64_t j = 0; j < hn; ++j) stt(gvn, nb + j * gnls, qv[j]); + out_row(gvn, nb, hn, qv); } return RAD_OK; } /* ------------------------------------------------------------------ ple_conv */ -/* PLE's dilated depthwise convolution, silu AFTER it, and the residual add folded in. +/* PLE's dilated depthwise convolution, then silu, with the residual add folded in. Two rules, + * both silent when broken: * - * TWO RULES THAT ARE NOT DERIVABLE AND ARE BOTH SILENT WHEN WRONG: + * `has_init` zero means the slot holds no history: the window before the first token is zeros. + * Otherwise a new sequence on a recycled slot convolves the previous sequence's tail into its + * first (width-1)*dilation tokens. * - * A ZERO `has_init` MEANS THE SLOT HOLDS NO HISTORY -- the window in front of the first token is - * ZEROS, not whatever the slot last held. Without it a fresh sequence landing on a recycled slot - * convolves the previous sequence's tail into its first `(width-1)*dilation` tokens: fluent - * output with the wrong prefix. + * `num_accepted` shifts the read and selects the window left behind (full contract: libref's + * ref_ple.cpp). Present, this is a decode step whose drafts may be rejected: the history read is + * offset by num_accepted - 1 and the state keeps the shifted history followed by every input of + * the step, so a next step that kept k tokens reads at k - 1. Absent, every token commits and the + * last (width-1)*dilation inputs land at offset zero. * - * `num_accepted` SHIFTS THE READ AND ITS PRESENCE PICKS THE WINDOW LEFT BEHIND -- libref's - * ref_ple.cpp states the contract in full. Present, the step is a decode step whose drafts a - * verify may reject: the history read is shifted down by one and every input of the step follows - * it, so a next step that kept k tokens reads at k - 1 and finds the history ending at the k-th. - * Absent, every token commits and the last (width-1)*dilation inputs land at offset zero. The - * write happens in a SECOND pass after every read is done, because a sequence longer than the - * window would otherwise overwrite history it is still reading. */ -/* ONE BODY FOR ple_conv AND causal_conv1d (LFM2's short convolution: undilated, no activation, no - * residual), as in libref, so the two cannot disagree about the window's layout. */ + * The state is written in a second pass after all reads, since a sequence longer than the window + * would otherwise overwrite history it still reads. + * + * One body serves ple_conv and causal_conv1d (LFM2's short convolution: undilated, no activation, + * no residual), as in libref, so both use the same window layout. */ struct ConvOps { const RadTensor *x, *w, *cs, *cu, *resid, *sidx, *hini, *nacc, *y; bool silu; @@ -189,14 +165,14 @@ static int depthwise_causal_conv(const RadArgs* a, const ConvOps& o) { if (!x || !w || !cs || !cu || !y) return RAD_E_INVAL; const int64_t n = p_int(a, "n", 0); - /* `x` is [M, n] and it is the call; `M` is the band. */ + /* Rows come from `x` ([M, n]); the `M` parameter is the band's upper bound. */ const int64_t M = n > 0 ? band_rows(numel(x) / n, p_int(a, "M", 0)) : 0; const int64_t wid = p_int(a, "width", 0); const int64_t dil = p_int(a, "dilation", 1); if (M <= 0 || n <= 0 || wid <= 0 || dil <= 0) return RAD_E_SHAPE; const int64_t hist_len = (wid - 1) * dil; - /* The read window lives in a stack frame. Nine at this model's shape; the bound is stated so a - * wider one is refused by name rather than overflowing. Same number as libref's. */ + /* The read window is a stack array (9 at PLE's shape); wider windows are refused rather than + * overflowing. Same bound as libref. */ enum { kHistMax = 64 }; if (hist_len > kHistMax) return RAD_E_UNSUPPORTED; @@ -208,9 +184,8 @@ static int depthwise_causal_conv(const RadArgs* a, const ConvOps& o) { const int64_t state_len = cs->rank >= 3 ? cs->shape[cs->rank - 1] : hist_len; if (cs->data && state_len < hist_len) return RAD_E_SHAPE; - /* Checked for every sequence BEFORE any of them is written: a state too shallow for the offset, - * or for the window a decode step leaves behind, is a caller error, and an OpenMP body cannot - * return. */ + /* Validate every sequence before writing any (an OpenMP body cannot return): the state must + * be deep enough for the offset and for the window a decode step leaves behind. */ for (int64_t s = 0; s < N; ++s) { const int64_t off = nacc ? ldi(nacc, offlin(nacc, s)) - 1 : 0; if (off < 0) return RAD_E_INVAL; @@ -225,7 +200,7 @@ static int depthwise_causal_conv(const RadArgs* a, const ConvOps& o) { const int64_t rrow = resid ? rowoff(resid, 1, n) : 0; const int64_t rcol = resid ? laststride(resid) : 0; const int64_t wrow = rowoff(w, 1, wid), wcol = laststride(w); - /* [n_slots, n, state_len], tight -- the layout gdn's conv state already uses. */ + /* [n_slots, n, state_len], dense, the same layout as gdn's conv state. */ const int64_t cs_slot = n * state_len, cs_ch = state_len; AVX_PARALLEL_FOR_IF(N * n >= 64) @@ -243,10 +218,8 @@ static int depthwise_causal_conv(const RadArgs* a, const ConvOps& o) { for (int64_t i = 0; i < hist_len; ++i) hist[i] = (warm && cs->data) ? ldt(cs, slot * cs_slot + c * cs_ch + off + i) : 0.0f; - /* The taps, read once per channel rather than per output element -- libref reads them - * through `ldt` inside the t loop, which is `slen * width` dtype switches for `width` - * distinct values. In scratch rather than a stack array so `width` carries no bound of its - * own: the only limit this op has is the read window's, stated above. */ + /* Taps read once per channel (libref reads them per output element). Kept in scratch, not + * on the stack, so `width` needs no bound of its own. */ float* tap = scratch_f32((size_t)wid); for (int64_t j = 0; j < wid; ++j) tap[j] = ldt(w, c * wrow + j * wcol); @@ -259,7 +232,7 @@ static int depthwise_causal_conv(const RadArgs* a, const ConvOps& o) { acc += vv * tap[j]; } const float r = resid ? ldt(resid, (bos + t) * rrow + c * rcol) : 0.0f; - stt(y, (bos + t) * yrow + c * ycol, r + (o.silu ? acc / (1.0f + std::exp(-acc)) : acc)); + stt(y, (bos + t) * yrow + c * ycol, r + (o.silu ? acc / (1.0f + sc_exp(-acc)) : acc)); } } @@ -304,7 +277,7 @@ AVX_KERNEL(ple_conv) { rad_arg_in(a, 6), rad_arg_in(a, 7), rad_arg_in(a, 8), true }); } -/* ple_conv's operands without `resid`, at dilation one and with no activation. */ +/* ple_conv's operands without `resid`, dilation 1, no activation. */ AVX_KERNEL(causal_conv1d) { if (a->n_t < 8) return RAD_E_INVAL; if (p_int(a, "dilation", 1) != 1) return RAD_E_INVAL; @@ -315,25 +288,16 @@ AVX_KERNEL(causal_conv1d) { /* ------------------------------------------------------------------ ngram_ids * - * ids[m][h] = (hash of the n-gram ending at m) % vocab[h] + offset[h]. + * ids[m][h] = (hash of the n-gram ending at m) % vocab[h] + offset[h], in torch's arithmetic: * - * THE ARITHMETIC IS TORCH'S, NOT C's, and both differences bite: + * Signed overflow is UB in C++ but wraps in torch, so the multiply goes through uint64. + * `torch.remainder` floors where C's `%` truncates, so the modulo is written out. * - * A SIGNED OVERFLOW IS UB IN C++ AND WRAPPING IN TORCH, so the multiply goes through uint64 and - * comes back -- two's complement, which is what an int64 tensor does on every machine this runs - * on. + * Neither matters on a real checkpoint (multipliers are bounded by (2^63-1)//vocab_size, so real + * products are non-negative); they make random test inputs match torch. * - * `torch.remainder` FLOORS WHERE C TRUNCATES, so the modulo is written out rather than left to - * `%`. - * - * On a real checkpoint neither can fire -- the multiplier build bounds every multiplier by - * (2^63-1)//vocab_size, so a real token's product has its sign bit clear and truncating and - * flooring agree on a non-negative dividend. They are here so that a DRAWN case, whose indices no - * vocabulary bounds, gets torch's answer rather than a platform's. - * - * THE EOS RULE IS COLLAPSED: once a shift falls off the front of the sequence, every longer shift - * is EOS too, so the cut is carried rather than re-tested. A COLD slot's window is EOS and not - * zero, because zero is a real token. */ + * Once a shift reaches EOS, every longer shift is EOS too, so the cut is carried. A cold slot's + * window is EOS, not zero, because zero is a real token. */ static inline int64_t wrap_mul(int64_t x, int64_t y) { return (int64_t)((uint64_t)x * (uint64_t)y); } @@ -354,24 +318,24 @@ AVX_KERNEL(ngram_ids) { const RadTensor* hini = rad_arg_in(a, 7); const RadTensor* nacc = rad_arg_in(a, 8); const RadTensor* ids = rad_arg_in(a, 9); - /* THE PROMPT THAT FOLLOWS, optional: `tok` holds its row count more tokens after the step's, - * continuing the LAST sequence, and their ids go here. The window is the step's own. */ + /* Optional ids for the prompt that follows: `tok` holds that many more tokens after the + * step's, continuing the last sequence. The state window is still the step's own. */ const RadTensor* ahead = a->n_t > 10 ? rad_arg_in(a, 10) : nullptr; if (!tok || !st || !cu || !mult || !vsz || !off_ || !ids) return RAD_E_INVAL; const int64_t heads = p_int(a, "heads", 0); if (heads <= 0) return RAD_E_SHAPE; - /* The token vector is the call and the prompt that follows it; `M` is the band. */ + /* Rows come from `tok` minus the prompt ahead; the `M` parameter is the band's upper bound. */ const int64_t A = ahead ? numel(ahead) / heads : 0; const int64_t M = band_rows(numel(tok) - A, p_int(a, "M", 0)); const int64_t ngram = p_int(a, "ngram", 0); const int64_t eos = p_int(a, "eos", -1); - if (M <= 0 || heads <= 0 || ngram < 2 || eos < 0) return RAD_E_SHAPE; - /* Heads are `ngram - 1` blocks of `heads_per_ngram`, block b using the (b+2)-gram. */ + if (M <= 0 || ngram < 2 || eos < 0) return RAD_E_SHAPE; + /* Heads form `ngram - 1` blocks of `heads_per_ngram`; block b uses the (b+2)-gram. */ if (heads % (ngram - 1)) return RAD_E_SHAPE; const int64_t per = heads / (ngram - 1); const int64_t ctx = ngram - 1; - if (ngram > 8) return RAD_E_UNSUPPORTED; /* the shift window lives in a stack frame */ + if (ngram > 8) return RAD_E_UNSUPPORTED; /* the shift window is a stack array */ if (numel(mult) < ngram || numel(vsz) < heads || numel(off_) < heads) return RAD_E_SHAPE; if (numel(tok) < M + A || numel(ids) < M * heads) return RAD_E_SHAPE; @@ -380,8 +344,8 @@ AVX_KERNEL(ngram_ids) { if (n_seq <= 0) return RAD_E_SHAPE; const int64_t W = st->rank >= 2 ? st->shape[st->rank - 1] : ctx; if (W < ctx) return RAD_E_SHAPE; - /* The read window, and the window a decode step leaves behind: `ctx - 1` ids of history plus - * every id of the step. */ + /* The state must hold the read window and the window a decode step leaves behind (`ctx - 1` + * ids of history plus every id of the step). */ for (int64_t s = 0; s < n_seq; ++s) { const int64_t o = nacc ? ldi(nacc, offlin(nacc, s)) - 1 : 0; if (o < 0) return RAD_E_INVAL; @@ -393,8 +357,7 @@ AVX_KERNEL(ngram_ids) { const int64_t ids_ld = rowoff(ids, 1, heads); const int64_t ahd_ld = ahead ? rowoff(ahead, 1, heads) : 0; - /* The per-head tables, read once. libref reads `vocab_sizes` and `offsets` through ld_int - * inside the innermost loop, which is `M * heads` dtype switches for `heads` distinct values. */ + /* Per-head tables read once (libref reads them in the innermost loop). */ int64_t* tab = (int64_t*)scratch_raw((size_t)(2 * heads + ngram) * sizeof(int64_t) + 64); int64_t* vtab = tab; int64_t* otab = tab + heads; @@ -406,9 +369,8 @@ AVX_KERNEL(ngram_ids) { } for (int64_t k = 0; k < ngram; ++k) mtab[k] = ldi(mult, k); - /* Serial over sequences, as libref is: each writes its own state slot, the work per sequence is - * a token loop with a handful of integer ops, and a parallel region over a handful of - * sequences would cost more than it saves. */ + /* Serial over sequences, as in libref: the per-sequence work is a short integer loop, too + * little to pay for a parallel region. */ for (int64_t s = 0; s < n_seq; ++s) { const int64_t bos = ldi(cu, offlin(cu, s)); const int64_t eot = ldi(cu, offlin(cu, s + 1)); @@ -439,8 +401,8 @@ AVX_KERNEL(ngram_ids) { sh[k] = hist(p - k); } - /* One mix per n-gram order, EXTENDED IN PLACE: the (b+2)-gram's mix is the - * (b+1)-gram's XOR'd with one more term, which saves recomputing the shared prefix. */ + /* Mixes are extended in place: the (b+2)-gram's is the (b+1)-gram's XOR one more + * term. */ int64_t mixed = 0; int64_t blk = -1; for (int64_t k = 0; k < ngram; ++k) { @@ -460,9 +422,9 @@ AVX_KERNEL(ngram_ids) { } } - /* The window this step leaves behind, written after every read of it is done, in the - * layout ple_conv's state follows: shifted by one with every id of the step behind it when - * `num_accepted` is present, the last `ctx` ids at offset zero when it is not. */ + /* State window, written after all reads, in ple_conv's layout: with `num_accepted`, the + * history shifted by one followed by every id of the step; without, the last `ctx` ids at + * offset zero. */ const int64_t base = rowoff(st, slot, W); if (nacc) { for (int64_t i = 0; i + 1 < ctx; ++i) @@ -482,37 +444,21 @@ AVX_KERNEL(ngram_ids) { /* ================================================================== the collectives * - * WORLD SIZE 1 ONLY, AND THAT IS A DELIBERATE LIMIT RATHER THAN AN OMISSION. + * World size 1 only, by design. libref implements real host collectives (one process, one thread + * per rank, a shared address space: a rendezvous, read every rank's pointer, rendezvous again), + * which lets the host backend exercise tensor-parallel graphs without a second card. That state (a + * barrier, a generation counter, a timeout) must exist once per process: a second copy in this + * plugin would form a separate rendezvous group, and ranks would deadlock whenever selection put + * them in different plugins. So above world 1 these return RAD_E_UNSUPPORTED and the selector + * falls through to libref. * - * libref implements the real thing, and it can because of how this engine is shaped: one process, - * one thread per rank, one address space, so a peer's buffer is a POINTER and the whole collective - * is a rendezvous, a read of every rank's pointer, and a second rendezvous before anyone - * overwrites theirs. That makes the host backend a fake multi-device backend, which is genuinely - * useful -- the sharded declare, the collective placement and the distributed top-k can all be - * exercised on a box with no second card. - * - * It is also a piece of SHARED MUTABLE STATE with a barrier, a generation counter and a timeout, - * and there is exactly one of it per process. Two kernel plugins each carrying their own would be - * two rendezvous groups for one world, and which one a rank joined would depend on which plugin - * won selection for that op -- a deadlock that appears only when the hierarchy changes. A CPU - * kernel library has no business owning the wire; libref already owns it and sits below this - * plugin in the hierarchy, so a tensor-parallel host deployment resolves the collectives there and - * everything else here. - * - * So: at world 1 both are the degenerate case and are served exactly. Above 1 this refuses by name - * with RAD_E_UNSUPPORTED, which makes the selector fall through to libref's row rather than - * producing a wrong sum. - * - * `exact` IS HONOURED IN ONE DIRECTION ONLY, as libref does: exact=1 gets the exact sum, and - * exact=0 -- a caller that has declared it will accept a lossy quantised wire -- ALSO gets the - * exact sum, because there is no wire here to quantise. Serving a lossy request exactly is safe; - * the constraint exists so a caller who wanted exactness cannot be handed a lossy result by - * accident, not the reverse. */ + * `exact` is honoured one way, as in libref: exact=0 permits a lossy wire but there is none here, + * so both settings get the exact result. */ AVX_KERNEL(all_reduce) { if (!rad_args_have(a, 1)) return RAD_E_INVAL; const RadTensor* x = &a->t[0]; const RadTensor* y = rad_arg_in(a, 1); - /* The message is the operand; `numel` is the band. */ + /* The element count comes from the operand; the `numel` parameter is the band. */ const int64_t nel = band_rows(numel(x), p_int(a, "numel", 0)); if (nel <= 0) return RAD_E_SHAPE; if (y && numel(y) < nel) return RAD_E_SHAPE; @@ -520,8 +466,7 @@ AVX_KERNEL(all_reduce) { const int world = (int)p_int(a, "world_size", a->world_size > 0 ? a->world_size : 1); if (world > 1) return RAD_E_UNSUPPORTED; - /* In place: the answer is already there. With a separate destination it still has to be COPIED - * there, because a caller that passed one reads it and not x. */ + /* In place: nothing to do. With a separate destination, copy x into it. */ if (!y) return RAD_OK; if (rad_tensor_is_contiguous(x) && rad_tensor_is_contiguous(y)) { const int64_t TILE = 8192; @@ -539,16 +484,14 @@ AVX_KERNEL(all_reduce) { AVX_KERNEL(all_gather) { if (!rad_args_have(a, 2)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *y = &a->t[1]; - /* The contribution is the operand; `numel` is the band. */ + /* The element count comes from the operand; the `numel` parameter is the band. */ const int64_t nel = band_rows(numel(x), p_int(a, "numel", 0)); const int world = (int)p_int(a, "world_size", a->world_size > 0 ? a->world_size : 1); if (nel <= 0 || numel(y) < nel * world) return RAD_E_SHAPE; if (world > 1) return RAD_E_UNSUPPORTED; - /* THE `row` PLACEMENT DOES NOT MATTER AT WORLD 1 and is still checked, because a caller that - * passes an illegal one at world 1 would get a silent pass here and a refusal at world 2 -- - * and the whole value of running a tensor-parallel graph at world 1 is that it is the same - * graph. */ + /* `row` has no effect at world 1 but is still validated, so an invalid graph fails the same + * way at world 1 as at world 2. */ const int64_t row = p_int(a, "row", 0); if (row < 0 || (row > 0 && nel % row)) return RAD_E_SHAPE; diff --git a/libavx/avx_moe.cpp b/libavx/avx_moe.cpp index bbbe0c38..1650698d 100644 --- a/libavx/avx_moe.cpp +++ b/libavx/avx_moe.cpp @@ -1,104 +1,45 @@ /* avx_moe.cpp -- routing, the scatter/gather pair, the grouped GEMM, and the exact row top-R. * - * ============================== WHAT sorted_tok CARRIES ============================== + * sorted_tok holds the flattened (token, slot) index, token * top_k + slot, grouped by expert, not + * the bare token id, so `moe_gather` knows which routing weight applies to each row. This is vLLM's + * `sorted_token_ids` convention. A slot whose expert id is outside [0, n_expert) is dropped: not + * counted, and the tail from expert_offset[n_expert] to M*top_k is filled with -1 (so padded batch + * rows are expressible). * - * The FLATTENED (token, slot) index -- token * top_k + slot -- grouped by expert, not the bare - * token id. With the bare id, `moe_gather` would have no way to find which of a token's top_k - * routing weights applies to a row and would have to search. It is also vLLM's - * `sorted_token_ids` convention, so a kernel lifted from there needs no translation. + * Three loops are restructured relative to libref, each with an identical result: * - * A slot whose expert id is outside [0, n_expert) is DROPPED: not counted, and the tail from - * expert_offset[n_expert] to M*top_k is filled with -1. A padded batch row has to be expressible. + * moe_scatter is O(T + n_expert) instead of O(T * n_expert): one pass with a per-expert write + * cursor instead of rescanning the ids per expert. Same stable order (ascending i within an + * expert). * - * ============================== THREE ALGORITHMIC CHANGES, NOT JUST VECTORISATION ============================== + * moe_gather builds the inverse permutation once, O(T). libref rebuilds it per token block in a + * 4096-entry stack array to avoid allocating, at (M / block) passes over sorted_tok. * - * This is the file where the reference's asymptotics, rather than its instruction mix, are the - * thing to beat -- so three loops are rewritten rather than widened, and each produces the - * identical answer: + * moe_gemm runs every expert's rows as one batch of products on the GEMM's tile drivers + * (avx_gemm_tile.cpp), each (expert, part) a job; libref re-reads the expert's weight for every + * row. Where the drivers decline, it gathers activation rows into a panel and runs a dot over + * each weight row packed once per expert. * - * moe_scatter is O(T + n_expert) instead of O(T * n_expert). libref places the rows by looping - * over experts and scanning the whole id array for each one, which is a stable sort and is - * quadratic in the expert count; at 256 experts that is 256 passes over the batch. A single pass - * with a per-expert write cursor is the same stable order -- rows are still appended in - * ascending i within an expert -- for one pass. - * - * moe_gather builds the inverse permutation ONCE, O(T), instead of once per block of tokens. - * libref rebuilds it in blocks into a 4096-entry stack array specifically to avoid allocating, - * and pays (M / block) full passes over sorted_tok for it. The scratch arena removes the reason. - * - * moe_gemm gathers the activation rows into a PANEL per expert and then runs the same - * register-blocked dot product avx_gemm.cpp uses. libref walks output rows and, for each, loops - * over N doing a fresh dot -- which means the expert's weight is re-read from memory once per - * row of that expert. Gathering first makes the weight pass contiguous and shared. - * - * The one thing NOT changed is the ORDER of moe_gather's summation. It is ascending slot j, and - * that is what makes the op reproducible: an implementation that walked the expert-sorted rows - * instead would sum a token's contributions in expert-id order and the two differ in the last bits. + * moe_gather's summation order is unchanged: ascending slot j. Summing in expert-sorted order + * instead would differ in the last bits. */ -#include "avx_vec.h" -#include "avx_common.h" +#include "avx_gemm.h" +#include "rad_planes.h" #include #include +#include #include using namespace avx; /* ================================================================== operand readings - * avx_gemm.cpp's, and libref/ref_gemm.h's before that. Duplicated here rather than shared through - * a header because these two translation units are compiled four times each and a shared header - * would be a fifth definition to keep in step; the bodies are short and the contract they encode - * is stated where it matters, in avx_gemm.cpp. `row_stride` and `grid_block` are avx_common.h's, - * which every kernel here already shares. */ + * Mat, Scales, make_scales and widen_cols are avx_gemm.h's (libref/ref_gemm.h's contract); + * `row_stride` and `grid_block` come from avx_common.h. */ -struct Mat { const RadTensor* t; int64_t rs, cs; }; - -static inline Mat as_mat(const RadTensor* t, int64_t cols) { - Mat m{ t, cols, 1 }; - if (t->rank < 2) return m; - m.cs = t->stride[t->rank - 1]; - m.rs = row_stride(t, cols); - return m; -} - -struct Scales { - const void* p; - uint32_t dt; - int64_t rs, cs, group, rblk; - inline float grp(int64_t row, int64_t g) const { - return rad_load_f32(p, dt, (rblk > 1 ? row / rblk : row) * rs + g * cs); - } -}; - -static Scales make_scales(const RadTensor* s, int64_t rows, int64_t K) { - Scales q{}; - q.rblk = 1; - if (!s || !s->data || rows <= 0 || numel(s) <= 0) { - q.p = nullptr; q.group = K; q.dt = RAD_F32; return q; - } - q.p = s->data; - q.dt = s->dtype; - int64_t groups = 0; - if (s->rank >= 2) { - const int64_t srows = s->shape[s->rank - 2]; - q.rblk = srows >= rows ? 1 : grid_block(rows, srows); - groups = s->shape[s->rank - 1]; - q.rs = s->stride[s->rank - 2]; - q.cs = s->stride[s->rank - 1]; - } else { - const int64_t nel = numel(s); - if (nel >= rows) { groups = nel / rows; q.rs = groups; } - else { groups = 1; q.rblk = grid_block(rows, nel); q.rs = 1; } - q.cs = 1; - } - q.group = grid_block(K, groups); - return q; -} - -/* A RAD_OPD_WTAB operand: `data` is a host array of shape[0] pointers, one per expert, and - * stride[0] is 0 to say so. The STACKED form -- a plain rank-3 [n_expert, N, K] with an ordinary - * leading stride -- is accepted too and is what a caller outside the engine hands over, since a - * checker drawing one dense plane has nowhere to put a pointer array. */ +/* Expert e of a RAD_OPD_WTAB operand: `data` is a host array of shape[0] pointers, one per expert, + * marked by stride[0] == 0. The stacked form, a dense rank-3 [n_expert, N, K], is also accepted + * (what callers outside the engine, such as a checker, pass). */ static RadTensor expert_entry(const RadTensor* w, int64_t e) { RadTensor t{}; if (!w || !w->data || w->rank < 2 || e < 0 || e >= w->shape[0]) return t; @@ -112,8 +53,8 @@ static RadTensor expert_entry(const RadTensor* w, int64_t e) { void* const* tab = (void* const*)w->data; t.data = tab[e]; } else { - /* An element offset in a packed dtype can be mid-byte; the stacked form is only ever whole - * planes, so the arithmetic is done in bytes off the leading stride. */ + /* Offset in bits, since a packed dtype's element offset can be mid-byte; a plane must + * start on a byte. */ const int64_t bits = rad_dtype_bits(w->dtype); const int64_t nbits = bits * w->stride[0] * e; if (bits <= 0 || (nbits & 7)) return t; /* data stays null: unreadable */ @@ -122,43 +63,17 @@ static RadTensor expert_entry(const RadTensor* w, int64_t e) { return t; } -static void pack_row(const Mat& m, int64_t r, int64_t K, float* dst) { - const RadTensor* t = m.t; - const int64_t base = r * m.rs; - if (m.cs == 1) { - const int sub = (t->dtype == RAD_I4 || t->dtype == RAD_FP4E2M1) ? 1 - : (t->dtype == RAD_I2) ? 3 : 0; - if (!sub || (base & sub) == 0) { - row_to_f32(t->dtype, byte_at(t->data, t->dtype, base), dst, K); - return; - } - } - for (int64_t k = 0; k < K; ++k) dst[k] = ld_elem(t->data, t->dtype, base + k * m.cs); -} - -static inline float dotf(const float* a, const float* b, int64_t k0, int64_t k1) { - vf a0 = vf_zero(), a1 = vf_zero(), a2 = vf_zero(), a3 = vf_zero(); - int64_t k = k0; - for (; k + 4 * VF_N <= k1; k += 4 * VF_N) { - a0 = vf_fma(vf_loadu(a + k), vf_loadu(b + k), a0); - a1 = vf_fma(vf_loadu(a + k + VF_N), vf_loadu(b + k + VF_N), a1); - a2 = vf_fma(vf_loadu(a + k + 2 * VF_N), vf_loadu(b + k + 2 * VF_N), a2); - a3 = vf_fma(vf_loadu(a + k + 3 * VF_N), vf_loadu(b + k + 3 * VF_N), a3); - } - for (; k + VF_N <= k1; k += VF_N) a0 = vf_fma(vf_loadu(a + k), vf_loadu(b + k), a0); - float s = vf_hsum(vf_add(vf_add(a0, a1), vf_add(a2, a3))); - for (; k < k1; ++k) s += a[k] * b[k]; - return s; +static inline void pack_row(const Mat& m, int64_t r, int64_t K, float* dst) { + widen_cols(m, r, 0, K, dst); } /* ------------------------------------------------------------------ router_topk */ -/* Softmax over ALL n_expert logits, then the top_k by probability, then -- if `norm` -- - * renormalise the kept weights to sum to one. Softmax first and select second is the order - * Mixtral, Qwen3 and every model in this engine's scope use; selecting first and normalising the - * raw logits would be a different router, so the order is part of the op. +/* Softmax over all n_expert logits, then the top_k by probability, then (if `norm`) renormalise + * the kept weights to sum to one. Softmax before selection is the order Mixtral, Qwen3 and the + * other supported models use; the order is part of the op. * - * The SELECTION runs on the LOGITS, not the probabilities: softmax is monotone, so the order is - * identical and the comparison is exact rather than through an exp. */ + * Selection compares logits, not probabilities: softmax is monotone, so the order is the same and + * the comparison is exact. */ AVX_KERNEL(router_topk) { if (!rad_args_have(a, 3)) return RAD_E_INVAL; const RadTensor *lg = &a->t[0], *ids = &a->t[1], *w = &a->t[2]; @@ -175,7 +90,7 @@ AVX_KERNEL(router_topk) { const float* v = in_row(lg, rowoff(lg, m, n_expert), n_expert, buf); const float mx = row_max(v, n_expert); float sum = 0.0f; - for (int64_t e = 0; e < n_expert; ++e) sum += std::exp(v[e] - mx); + for (int64_t e = 0; e < n_expert; ++e) sum += sc_exp(v[e] - mx); const float inv = sum > 0.0f ? 1.0f / sum : 0.0f; float pv = INFINITY; @@ -183,7 +98,7 @@ AVX_KERNEL(router_topk) { float wsum = 0.0f; for (int64_t r = 0; r < top_k; ++r) { if (!topk_next_f32(v, n_expert, &pv, &pi)) break; - const float p = std::exp(pv - mx) * inv; + const float p = sc_exp(pv - mx) * inv; st_int_dt(ids->dtype, ids->data, rowoff(ids, m, top_k) + r * laststride(ids), pi); stt(w, rowoff(w, m, top_k) + r * laststride(w), p); wsum += p; @@ -201,9 +116,9 @@ AVX_KERNEL(router_topk) { } /* ------------------------------------------------------------------ moe_scatter */ -/* `protect`: local experts the sort places LAST, in the order listed, the rest closed up -- the - * layout a layer that serves a few experts with a second grouped GEMM needs (libr4d's sort_place). - * Returns false on a list that is not strictly ascending inside [0, n). */ +/* `protect`: local experts the sort places last, in the listed order, with the rest closed up; + * the layout for a layer that serves a few experts with a second grouped GEMM (libr4d's + * sort_place). Returns false unless the list is strictly ascending within [0, n). */ static bool sort_places(const char* s, int64_t n, std::vector* place) { std::vector prot; for (const char* c = s ? s : ""; *c;) { @@ -223,20 +138,18 @@ static bool sort_places(const char* s, int64_t n, std::vector* place) { return true; } -/* A stable counting sort of the (token, slot) pairs by expert id, in ONE placement pass with a - * per-expert write cursor rather than libref's expert-major rescan. The order is identical: within - * an expert, rows are still appended in ascending i. +/* Stable counting sort of the (token, slot) pairs by expert id: one placement pass with a + * per-expert write cursor. Within an expert, rows are appended in ascending i, as in libref. * - * Serial on purpose. It is O(T) over a batch's worth of small integers, and a parallel version - * needs a per-thread histogram and a prefix pass to stay stable -- more code than the work it - * saves, and a stability bug there routes a token to a different expert. */ + * Serial: O(T) over small integers. A stable parallel version needs per-thread histograms and a + * prefix pass, which costs more than it saves. */ AVX_KERNEL(moe_scatter) { if (!rad_args_have(a, 4)) return RAD_E_INVAL; const RadTensor *ids = &a->t[0], *sorted = &a->t[1], *off = &a->t[2], *cnt = &a->t[3]; const int64_t n_expert = p_int(a, "n_expert", 0); const int64_t top_k = p_int(a, "top_k", 1); - /* THIS RANK'S FIRST EXPERT, subtracted from every routed id so the sort is over local indices - * -- which is what the weight table, the offsets and the GEMM downstream are indexed by. */ + /* This rank's first expert, subtracted from every routed id so the sort uses local indices + * (as the weight table, offsets and GEMM do). */ const int64_t base = p_int(a, "expert_base", 0); if (n_expert <= 0 || top_k <= 0 || base < 0) return RAD_E_SHAPE; const int64_t M = numel(ids) / top_k; @@ -265,7 +178,7 @@ AVX_KERNEL(moe_scatter) { for (int64_t e = 0; e < n_expert; ++e) { st_int_dt(off->dtype, off->data, offlin(off, e), run); const int64_t c = cur[e]; - cur[e] = run; /* the cursor becomes the write position */ + cur[e] = run; /* now the write cursor */ run += c; } st_int_dt(off->dtype, off->data, offlin(off, n_expert), run); @@ -281,19 +194,786 @@ AVX_KERNEL(moe_scatter) { return RAD_OK; } -/* ------------------------------------------------------------------ moe_gemm, moe_gemm_q */ -/* y[i, :] = a[row(i), :] @ w[e]^T, where e is the expert whose offset range contains i and - * `a_order` picks row(i): `sorted_tok[i] / top_k` when the activation has one row per TOKEN, and i - * itself when it already has one per (token, slot). The output is in SORTED order, which is the - * layout that makes the expert loop contiguous -- the entire point of the scatter. moe_gather puts - * it back. +/* ------------------------------------------------------------------ the codebook experts * - * `a_order` HAS TO BE SAID AND NOT DERIVED. The two grouped GEMMs of one routed block disagree - * about it: gate_up reads the block's input, one row per token; down reads gate_up's output, one - * row per (token, slot). The row count would give it away -- M against M*top_k -- but an operand - * whose meaning changes with its extent is exactly the shape a checker cannot see: if both - * implementations gather they agree with each other, and a harness that sizes the operand the way - * the gather wants never exercises the other reading. */ + * Qwen3.8-Flash-Next's served experts (docs/MOE-W4.md): u4 or u5 codes indexing a table of 16 or + * 32 f32 levels, a scale per (row, group of K), bf16 per 128 (w4nla8h) or E4M3 per 64 or 32 times + * one fixed f32 (w4nl64a8h, w4nl32a8h, w5nl64a8h). The codes view, and the two-level forms' scale + * view, arrive in the joined form of abi/rad_planes.h, which the registry rows' layout hooks ask + * for; the planes accepted and refused are libref's (libref/ref_moe.cpp). + * + * Arithmetic: each activation row is multiplied by its own scale as it is packed, and the weight's + * scale is applied to the table (one register multiply a group) or, in AVX-512's line decode, to + * each lane's partial sum once a line; the dot runs over all of K with one horizontal sum per + * output. libref sums each weight group and scales the sum, `(sub * sa) * sb`; the two differ in + * rounding order only. + * + * Decode: codes are expanded through the table in registers, never into an f32 copy of an expert. + * u4 at AVX-512 takes a cache line (128 codes) at a time: see cb_fused_lines. Elsewhere a chunk of + * kCbCH codes: sixteen bytes of u4 widen to sixteen dword lanes, and one vpermps each on the low + * and high nibbles gives the chunk's even and odd elements (the 16-entry table is one register); + * u5 places each code's two bytes in its lane with vpshufb, aligns it with a variable shift and + * looks it up in the 32 entries with vpermt2ps. AVX2 does the same over 8-entry vpermps, two (u4) + * or four (u5) of them blended on the index bits. The activation is packed in the matching order. + * The scalar and AVX levels, and a geometry whose K or scale group is not whole chunks, decode a + * weight row through the table into L1 and take the generic dot. + * + * Two forms over an expert's rows. With at most kCbFused rows (decode and short verify steps) each + * weight row is decoded once and multiplied into every row's accumulators as it is decoded, the + * next rows' codes prefetched a pass ahead. With more, kCbNR weight rows at a time are decoded over + * all of K into a panel (L2-resident at Flash-Next's K), and a kCbMR x kCbNR register block + * multiplies it into every row of a block of up to kCbRB, one horizontal sum per output. + * + * The activation rows a call reads are packed once (times their scales, in the decode's order) + * and shared by every expert that reads them. Work is (expert, block of its rows, kCbNC or, for + * the panel form, kCbNCP weight rows) items, taken dynamically. Each output is computed by one + * item in an order fixed by the call's geometry, so the result does not depend on the thread + * count. */ + +/* The panel form's register block: 3 x 8 accumulators in AVX-512's 32 registers, 2 x 4 in AVX2's + * 16. Both divide kCbNC and the experts' widths. */ +#if AVX_LEVEL == 3 +constexpr int64_t kCbMR = 3, kCbNR = 8; +#else +constexpr int64_t kCbMR = 2, kCbNR = 4; +#endif +constexpr int64_t kCbFused = 4, kCbRB = 64, kCbNC = 64, kCbNCP = 256; +constexpr int64_t kCbCH = 2 * VF_N; /* codes a decode step expands */ + +/* One expert's codes, table and scales, read from its joined form. */ +struct CbExp { + const uint8_t* codes = nullptr; + int64_t row_bytes = 0, n = 0, k = 0; + int bits = 0; + float tab[32]; + Scales s{}; /* the scale plane; `s.p` null for none */ + float mul = 1.0f; /* the level above the scale, 1 for none */ + int64_t group = 0; /* K elements a scale covers */ + inline float sc(int64_t row, int64_t g) const { + return (s.p ? s.grp(row, g) : 1.0f) * mul; + } + int64_t groups() const { return (k + group - 1) / group; } +}; + +/* Weight row `row`'s scales times their level into `dst`, the values sc() gives: one row + * conversion where the scales are contiguous, instead of a dtype switch a group. */ +static void cb_scales(const CbExp& x, int64_t row, float* dst) { + const int64_t ng = x.groups(); + if (x.s.p && x.s.cs == 1) { + const int64_t base = (x.s.rblk > 1 ? row / x.s.rblk : row) * x.s.rs; + row_to_f32(x.s.dt, (const uint8_t*)x.s.p + base * (rad_dtype_bits(x.s.dt) / 8), dst, ng); + if (x.mul != 1.0f) + for (int64_t g = 0; g < ng; ++g) dst[g] *= x.mul; + return; + } + for (int64_t g = 0; g < ng; ++g) dst[g] = x.sc(row, g); +} + +/* The joined form's header when weight entry `t` holds one; an entry smaller than a header is a + * plain plane and is not read past its end (libref's cb_joined). */ +static const RadPlanesHeader* cb_joined(const RadTensor& t) { + int64_t n = 1; + for (uint32_t i = 0; i < t.rank; ++i) n *= t.shape[i]; + if (!t.data || rad_dtype_bytes(t.dtype, n) < (int64_t)sizeof(RadPlanesHeader)) return nullptr; + return rad_planes_header(t.data); +} + +/* An expert's codes from its joined form: 1, 0 for a plain plane (any dtype but u4 and u5), + * RAD_E_DTYPE for planes these kernels do not read, RAD_E_SHAPE for codes not covering [n, k]. */ +static int cb_codes(const RadTensor& w, int64_t n, int64_t k, CbExp* out) { + if (w.dtype != RAD_U4 && w.dtype != RAD_U5) return 0; + const RadPlanesHeader* h = rad_planes_header(w.data); + const RadPlanesEntry *ec = nullptr, *et = nullptr; + const void* codes = h ? rad_planes_find(w.data, "codes", &ec) : nullptr; + const void* tab = h ? rad_planes_find(w.data, "table", &et) : nullptr; + if (!codes || !tab || h->n_planes != 2) return RAD_E_DTYPE; + const int bits = ec->dtype == RAD_U4 ? 4 : ec->dtype == RAD_U5 ? 5 : 0; + if (!bits || ec->kind != RAD_PLANE_TILED || ec->block[0] != 1 || ec->block[1] != 1 || + et->kind != RAD_PLANE_TABLE || et->dtype != RAD_F32 || + et->rows * et->cols != ((int64_t)1 << bits)) + return RAD_E_DTYPE; + if (ec->rows < n || ec->cols < k) return RAD_E_SHAPE; + out->codes = (const uint8_t*)codes; + out->row_bytes = ec->row_bytes; + out->n = n; + out->k = k; + out->bits = bits; + std::memcpy(out->tab, tab, sizeof(float) << bits); + return 1; +} + +/* An expert's scales beside joined codes: the joined `scale,scale.1` form, else the plane as + * make_scales reads it (w4nla8h's bf16 scale, or none). RAD_E_DTYPE for other joined planes. */ +static int cb_scale(const RadTensor* ws, CbExp* x) { + x->mul = 1.0f; + const RadPlanesHeader* h = ws ? cb_joined(*ws) : nullptr; + if (!h) { + x->s = make_scales(ws, x->n, x->k, false); + x->group = x->s.p && x->s.group > 0 ? x->s.group : x->k; + return RAD_OK; + } + const RadPlanesEntry *es = nullptr, *e1 = nullptr; + const void* sp = rad_planes_find(ws->data, "scale", &es); + const void* lp = rad_planes_find(ws->data, "scale.1", &e1); + if (!sp || !lp || h->n_planes != 2) return RAD_E_DTYPE; + const uint32_t dt = es->dtype; + if (es->kind != RAD_PLANE_TILED || es->block[0] < 1 || es->block[1] < 1 || + (dt != RAD_F8E4M3 && dt != RAD_BF16 && dt != RAD_F16 && dt != RAD_F32) || + e1->kind != RAD_PLANE_TILED || e1->dtype != RAD_F32 || e1->block[0] != 0 || + e1->block[1] != 0 || e1->rows != 1 || e1->cols != 1) + return RAD_E_DTYPE; + if ((x->n + es->block[0] - 1) / es->block[0] > es->rows || + (x->k + es->block[1] - 1) / es->block[1] > es->cols) + return RAD_E_SHAPE; + x->s.p = sp; + x->s.dt = dt; + x->s.rs = es->cols; + x->s.cs = 1; + x->s.group = es->block[1]; + x->s.rblk = es->block[0]; + x->group = es->block[1]; + std::memcpy(&x->mul, lp, sizeof x->mul); + return 1; +} + +/* ---- the in-register decode: a chunk of kCbCH codes at `p` into two vectors, `v0` and `v1`. + * For u4 those are the chunk's even and odd elements; for u5 its two halves in element order. The + * table registers hold the table times the current group's scale. */ +#if AVX_LEVEL == 3 +struct CbDec { + __m512 t0, t1; /* entries 0..15 and 16..31 */ + __m512i shuf, shift; /* u5: each lane's two source bytes, and its bit offset in them */ +}; +static inline CbDec cb_dec_init() { + alignas(64) int8_t sh[64]; + alignas(64) int32_t sv[16]; + for (int j = 0; j < 16; ++j) { + const int b = (5 * j) >> 3; + sh[4 * j] = (int8_t)b; + sh[4 * j + 1] = (int8_t)(b + 1); + sh[4 * j + 2] = sh[4 * j + 3] = (int8_t)0x80; + sv[j] = (5 * j) & 7; + } + CbDec d; + d.t0 = d.t1 = _mm512_setzero_ps(); + d.shuf = _mm512_load_si512(sh); + d.shift = _mm512_load_si512(sv); + return d; +} +template static inline void cb_dec_scale(CbDec& d, const float* tab, float s) { + const __m512 vs = _mm512_set1_ps(s); + d.t0 = _mm512_mul_ps(_mm512_loadu_ps(tab), vs); + if (BITS == 5) d.t1 = _mm512_mul_ps(_mm512_loadu_ps(tab + 16), vs); +} +template static inline void cb_dec(const uint8_t* p, const CbDec& d, vf& v0, vf& v1); +template <> inline void cb_dec<4>(const uint8_t* p, const CbDec& d, vf& v0, vf& v1) { + const __m512i x = _mm512_cvtepu8_epi32(_mm_loadu_si128((const __m128i*)p)); + v0 = _mm512_permutexvar_ps(x, d.t0); + v1 = _mm512_permutexvar_ps(_mm512_srli_epi32(x, 4), d.t0); +} +/* Reads 16 bytes at `p` and at `p + 10`: 6 past the chunk's 20. */ +template <> inline void cb_dec<5>(const uint8_t* p, const CbDec& d, vf& v0, vf& v1) { + const __m512i b0 = _mm512_broadcast_i32x4(_mm_loadu_si128((const __m128i*)p)); + const __m512i b1 = _mm512_broadcast_i32x4(_mm_loadu_si128((const __m128i*)(p + 10))); + v0 = _mm512_permutex2var_ps(d.t0, _mm512_srlv_epi32(_mm512_shuffle_epi8(b0, d.shuf), d.shift), + d.t1); + v1 = _mm512_permutex2var_ps(d.t0, _mm512_srlv_epi32(_mm512_shuffle_epi8(b1, d.shuf), d.shift), + d.t1); +} +#elif AVX_LEVEL == 2 +struct CbDec { + __m256 t[4]; /* entries 0..7, 8..15, 16..23, 24..31 */ + __m256i shuf, shift; /* u5, as at AVX-512, eight lanes over 5 bytes */ +}; +static inline CbDec cb_dec_init() { + alignas(32) int8_t sh[32]; + alignas(32) int32_t sv[8]; + for (int j = 0; j < 8; ++j) { + const int b = (5 * j) >> 3; + sh[4 * j] = (int8_t)b; + sh[4 * j + 1] = (int8_t)(b + 1); + sh[4 * j + 2] = sh[4 * j + 3] = (int8_t)0x80; + sv[j] = (5 * j) & 7; + } + CbDec d; + d.t[0] = d.t[1] = d.t[2] = d.t[3] = _mm256_setzero_ps(); + d.shuf = _mm256_load_si256((const __m256i*)sh); + d.shift = _mm256_load_si256((const __m256i*)sv); + return d; +} +template static inline void cb_dec_scale(CbDec& d, const float* tab, float s) { + const __m256 vs = _mm256_set1_ps(s); + for (int i = 0; i < (BITS == 5 ? 4 : 2); ++i) + d.t[i] = _mm256_mul_ps(_mm256_loadu_ps(tab + 8 * i), vs); +} +/* Entry x & 15 of the 16 in (a, b): vpermps reads the low three bits, bit 3 picks the half. */ +static inline __m256 cb_lut16(__m256 a, __m256 b, __m256i x) { + return _mm256_blendv_ps(_mm256_permutevar8x32_ps(a, x), _mm256_permutevar8x32_ps(b, x), + _mm256_castsi256_ps(_mm256_slli_epi32(x, 28))); +} +template static inline void cb_dec(const uint8_t* p, const CbDec& d, vf& v0, vf& v1); +template <> inline void cb_dec<4>(const uint8_t* p, const CbDec& d, vf& v0, vf& v1) { + const __m256i x = _mm256_cvtepu8_epi32(_mm_loadl_epi64((const __m128i*)p)); + v0 = cb_lut16(d.t[0], d.t[1], x); + v1 = cb_lut16(d.t[0], d.t[1], _mm256_srli_epi32(x, 4)); +} +static inline __m256 cb_u5_half(const uint8_t* p, const CbDec& d) { + const __m256i b = _mm256_broadcastsi128_si256(_mm_loadl_epi64((const __m128i*)p)); + const __m256i x = _mm256_srlv_epi32(_mm256_shuffle_epi8(b, d.shuf), d.shift); + return _mm256_blendv_ps(cb_lut16(d.t[0], d.t[1], x), cb_lut16(d.t[2], d.t[3], x), + _mm256_castsi256_ps(_mm256_slli_epi32(x, 27))); +} +/* Reads 8 bytes at `p` and at `p + 5`: 3 past the chunk's 10. */ +template <> inline void cb_dec<5>(const uint8_t* p, const CbDec& d, vf& v0, vf& v1) { + v0 = cb_u5_half(p, d); + v1 = cb_u5_half(p + 5, d); +} +#endif + +#if AVX_LEVEL >= 2 +/* Chunk `c` of a row of `nch`: its bytes, or for u5's last chunk, whose decode reads past it, a + * copy in `bounce`. */ +template +static inline const uint8_t* cb_chunk(const uint8_t* row, int64_t c, int64_t nch, + uint8_t* bounce) { + constexpr int64_t cb = kCbCH * BITS / 8; + const uint8_t* q = row + c * cb; + if (BITS == 5 && c + 1 == nch) { + std::memcpy(bounce, q, (size_t)cb); + return bounce; + } + return q; +} + +/* Weight rows wr .. wr + W - 1 against R packed activation rows `ar`, decoded and multiplied in + * one pass; out[w * R + r]. `sv` holds the W rows' scales (cb_scales), `ng` a row. Two weight rows + * give the FMA chains of one-row decode enough independence to cover their latency. */ +template +static void cb_fused(const CbExp& x, int64_t wr, const float* const* ar, const float* sv, + int64_t ng, float* out) { + vf acc[W][R][2]; + for (int w = 0; w < W; ++w) + for (int r = 0; r < R; ++r) acc[w][r][0] = acc[w][r][1] = vf_zero(); + CbDec d[W]; + for (int w = 0; w < W; ++w) d[w] = cb_dec_init(); + const int64_t nch = x.k / kCbCH, cpg = x.group / kCbCH; + alignas(16) uint8_t bounce[W][32] = {}; + for (int64_t c = 0; c < nch;) { + for (int w = 0; w < W; ++w) cb_dec_scale(d[w], x.tab, sv[w * ng + c / cpg]); + const int64_t ce = c + cpg < nch ? c + cpg : nch; + for (; c < ce; ++c) { + const int64_t a = c * kCbCH; + constexpr int64_t cb = kCbCH * BITS / 8; + /* The next W rows' line at this column, one pass ahead of the decode. */ + if (((c * cb) & 63) < cb) + for (int w = 0; w < W; ++w) + _mm_prefetch((const char*)(x.codes + (wr + W + w) * x.row_bytes + c * cb), + _MM_HINT_T0); + for (int w = 0; w < W; ++w) { + vf v0, v1; + cb_dec(cb_chunk(x.codes + (wr + w) * x.row_bytes, c, nch, bounce[w]), + d[w], v0, v1); + for (int r = 0; r < R; ++r) { + acc[w][r][0] = vf_fma(v0, vf_loadu(ar[r] + a), acc[w][r][0]); + acc[w][r][1] = vf_fma(v1, vf_loadu(ar[r] + a + VF_N), acc[w][r][1]); + } + } + } + } + for (int w = 0; w < W; ++w) + for (int r = 0; r < R; ++r) out[w * R + r] = vf_hsum(vf_add(acc[w][r][0], acc[w][r][1])); +} + +/* Weight rows [wr, wr + nr), chunks [c0, c1), decoded into `P`, row i at P + i * ldp; `sv` holds + * the rows' scales as for cb_fused. */ +template +static void cb_panel(const CbExp& x, int64_t wr, int64_t nr, int64_t c0, int64_t c1, + const float* sv, int64_t ng, float* P, int64_t ldp) { + const int64_t nch = x.k / kCbCH, cpg = x.group / kCbCH; + alignas(16) uint8_t bounce[32] = {}; + CbDec d = cb_dec_init(); + for (int64_t i = 0; i < nr; ++i) { + const uint8_t* row = x.codes + (wr + i) * x.row_bytes; + float* dst = P + i * ldp; + for (int64_t c = c0; c < c1;) { + cb_dec_scale(d, x.tab, sv[i * ng + c / cpg]); + const int64_t ce = (c / cpg + 1) * cpg < c1 ? (c / cpg + 1) * cpg : c1; + for (; c < ce; ++c) { + vf v0, v1; + cb_dec(cb_chunk(row, c, nch, bounce), d, v0, v1); + vf_storeu(dst + (c - c0) * kCbCH, v0); + vf_storeu(dst + (c - c0) * kCbCH + VF_N, v1); + } + } + } +} +#endif + +#if AVX_LEVEL == 3 +/* ---- u4 at AVX-512 a cache line at a time: 128 codes, of which dword lane j holds codes 8j to + * 8j + 7 as nibbles. A shift by 4m and one vpermps, which reads the low four bits of each lane, + * give code 8j + m in lane j: eight vpermps a line and no widening. The activation is packed to + * match (vector m of a line holds its elements 8j + m), and since a lane's eight codes share a + * scale group, each lane's partial sum is multiplied by its group's scale once a line. */ +constexpr int64_t kCbLine = 128; + +/* Lane j's scale in line c of a row whose scales are `sv`: group (128c + 8j) / group. */ +static inline __m512 cb_line_scale(const float* sv, int64_t c, int64_t group) { + if (group % kCbLine == 0) return _mm512_set1_ps(sv[c * kCbLine / group]); + if (group == 64) + return _mm512_mask_mov_ps(_mm512_set1_ps(sv[2 * c]), 0xFF00, _mm512_set1_ps(sv[2 * c + 1])); + __m512 v = _mm512_set1_ps(sv[4 * c]); + v = _mm512_mask_mov_ps(v, 0x00F0, _mm512_set1_ps(sv[4 * c + 1])); + v = _mm512_mask_mov_ps(v, 0x0F00, _mm512_set1_ps(sv[4 * c + 2])); + return _mm512_mask_mov_ps(v, 0xF000, _mm512_set1_ps(sv[4 * c + 3])); +} + +/* Whether expert `x` takes the line form: u4, whole lines, and a group whole lanes divide. */ +static inline bool cb_lines(const CbExp& x) { + return x.bits == 4 && x.k % kCbLine == 0 && + (x.group % kCbLine == 0 || x.group == 64 || x.group == 32); +} + +/* cb_fused in lines: weight rows wr .. wr + W - 1 against R rows `ar`, out[w * R + r]. Two + * partial chains a row cover the FMA latency with the decode's shuffles. */ +template +static void cb_fused_lines(const CbExp& x, int64_t wr, const float* const* ar, const float* sv, + int64_t ng, float* out) { + __m512 acc[W][R]; + for (int w = 0; w < W; ++w) + for (int r = 0; r < R; ++r) acc[w][r] = _mm512_setzero_ps(); + const __m512 T = _mm512_loadu_ps(x.tab); + const int64_t nl = x.k / kCbLine; + for (int64_t c = 0; c < nl; ++c) { + const int64_t a = c * kCbLine; + /* The next W rows' line at this column, one pass ahead of the decode. */ + for (int w = 0; w < W; ++w) + _mm_prefetch((const char*)(x.codes + (wr + W + w) * x.row_bytes + c * 64), _MM_HINT_T0); + auto act = [&](int r, int m) { return _mm512_loadu_ps(ar[r] + a + 16 * m); }; + for (int w = 0; w < W; ++w) { + const __m512i q = _mm512_loadu_si512(x.codes + (wr + w) * x.row_bytes + c * 64); + __m512 s0[R], s1[R]; + { + const __m512 v0 = _mm512_permutexvar_ps(q, T); + const __m512 v1 = _mm512_permutexvar_ps(_mm512_srli_epi32(q, 4), T); + for (int r = 0; r < R; ++r) { + s0[r] = _mm512_mul_ps(v0, act(r, 0)); + s1[r] = _mm512_mul_ps(v1, act(r, 1)); + } + } + for (int m = 2; m < 8; m += 2) { + const __m512 v0 = _mm512_permutexvar_ps(_mm512_srli_epi32(q, 4 * m), T); + const __m512 v1 = _mm512_permutexvar_ps(_mm512_srli_epi32(q, 4 * m + 4), T); + for (int r = 0; r < R; ++r) { + s0[r] = _mm512_fmadd_ps(v0, act(r, m), s0[r]); + s1[r] = _mm512_fmadd_ps(v1, act(r, m + 1), s1[r]); + } + } + const __m512 sc = cb_line_scale(sv + w * ng, c, x.group); + for (int r = 0; r < R; ++r) + acc[w][r] = _mm512_fmadd_ps(_mm512_add_ps(s0[r], s1[r]), sc, acc[w][r]); + } + } + for (int w = 0; w < W; ++w) + for (int r = 0; r < R; ++r) out[w * R + r] = _mm512_reduce_add_ps(acc[w][r]); +} + +/* cb_panel in lines: weight rows [wr, wr + nr) over all of K into `P`, row i at P + i * ldp, each + * lane times its scale. */ +static void cb_panel_lines(const CbExp& x, int64_t wr, int64_t nr, const float* sv, int64_t ng, + float* P, int64_t ldp) { + const __m512 T = _mm512_loadu_ps(x.tab); + const int64_t nl = x.k / kCbLine; + for (int64_t i = 0; i < nr; ++i) { + const uint8_t* row = x.codes + (wr + i) * x.row_bytes; + float* dst = P + i * ldp; + for (int64_t c = 0; c < nl; ++c) { + const __m512i q = _mm512_loadu_si512(row + c * 64); + const __m512 sc = cb_line_scale(sv + i * ng, c, x.group); + for (int m = 0; m < 8; ++m) + _mm512_storeu_ps(dst + c * kCbLine + 16 * m, + _mm512_mul_ps(_mm512_permutexvar_ps( + _mm512_srli_epi32(q, 4 * m), T), sc)); + } + } +} +#endif + +/* MB x NB dot products over [0, kl), kl a multiple of VF_N, added into `out`. */ +template +static inline void cb_block(const float* const* A, const float* B, int64_t ldb, int64_t kl, + float out[MB][NB]) { + vf acc[MB][NB]; + for (int i = 0; i < MB; ++i) + for (int j = 0; j < NB; ++j) acc[i][j] = vf_zero(); + for (int64_t k = 0; k < kl; k += VF_N) { + vf av[MB]; + for (int i = 0; i < MB; ++i) av[i] = vf_loadu(A[i] + k); + for (int j = 0; j < NB; ++j) { + const vf bv = vf_loadu(B + j * ldb + k); + for (int i = 0; i < MB; ++i) acc[i][j] = vf_fma(av[i], bv, acc[i][j]); + } + } + for (int i = 0; i < MB; ++i) + for (int j = 0; j < NB; ++j) out[i][j] += vf_hsum(acc[i][j]); +} + +/* A call's operands and geometry, as moe_gemm_impl read them. */ +struct CbCall { + const RadTensor *A = nullptr, *sorted = nullptr, *off = nullptr, *Y = nullptr; + const RadTensor* Wq[4] = {}; + const RadTensor* wsq[4] = {}; + int64_t Nq[4] = {}, Kq[4] = {}; + int nc = 2; + int64_t parts = 1, n_expert = 0, top_k = 1, N = 0, K = 0, T = 0, AR = 0, y_rs = 0, y_cs = 1; + bool sorted_a = false; + Mat ma{}; + Scales SA{}; +}; + +/* Live rows [r0, r1) of the list (one expert's) against its weight rows [n0, n1). */ +struct CbItem { int64_t e, r0, r1, n0, n1; }; + +/* How a call decodes, the same for all its experts: a weight row through the table into L1, the + * register decode in chunks of kCbCH, or AVX-512's u4 lines. */ +enum CbPath { kCbGeneric = 0, kCbChunks = 1, kCbLines = 2 }; +/* Row `tok` of the activation as f32 times its own scale, `k` elements in the order the call's + * decode produces the weights' (`path`, and `bits` for the chunk decode). `tmp` holds k floats. */ +static void cb_pack(const CbCall& c, int64_t tok, int64_t k, int bits, float* dst, float* tmp, + int path) { + pack_row(c.ma, tok, k, tmp); + if (c.SA.p) + for (int64_t g0 = 0; g0 < k; g0 += c.SA.group) { + const int64_t g1 = g0 + c.SA.group < k ? g0 + c.SA.group : k; + const float s = c.SA.grp(tok, g0 / c.SA.group); + const vf vs = vf_set1(s); + int64_t i = g0; + for (; i + VF_N <= g1; i += VF_N) vf_storeu(tmp + i, vf_mul(vf_loadu(tmp + i), vs)); + for (; i < g1; ++i) tmp[i] *= s; + } + if (path == kCbLines) { + /* Vector m of each 128-element line holds elements 8j + m. */ + for (int64_t c0 = 0; c0 < k; c0 += 128) + for (int64_t m = 0; m < 8; ++m) + for (int64_t j = 0; j < 16; ++j) dst[c0 + 16 * m + j] = tmp[c0 + 8 * j + m]; + } else if (path == kCbChunks && bits == 4) { + for (int64_t c0 = 0; c0 < k; c0 += kCbCH) + for (int64_t j = 0; j < VF_N; ++j) { + dst[c0 + j] = tmp[c0 + 2 * j]; + dst[c0 + VF_N + j] = tmp[c0 + 2 * j + 1]; + } + } else { + std::memcpy(dst, tmp, (size_t)k * sizeof(float)); + } +} + +/* The scales of weight rows [n0, n1) into `sv`, ng a row: one conversion when the plane's rows are + * contiguous, as a joined form's are. */ +static void cb_scale_rows(const CbExp& x, int64_t n0, int64_t n1, float* sv) { + const int64_t ng = x.groups(); + if (x.s.p && x.s.cs == 1 && x.s.rblk == 1 && x.s.rs == ng) { + row_to_f32(x.s.dt, (const uint8_t*)x.s.p + n0 * ng * (rad_dtype_bits(x.s.dt) / 8), sv, + (n1 - n0) * ng); + if (x.mul != 1.0f) + for (int64_t i = 0; i < (n1 - n0) * ng; ++i) sv[i] *= x.mul; + return; + } + for (int64_t wr = n0; wr < n1; ++wr) cb_scales(x, wr, sv + (wr - n0) * ng); +} + +/* An item's products, store(r, wr, value) for its rows and weight rows: the generic decode, the + * fused form or the panel form. `ar` points at the packed rows, `tmp` holds kCbNR rows of K floats + * and `sv` the item's weight rows' scales. */ +template +static void cb_compute(const CbExp& x, const CbItem& it, int64_t R, const float* const* ar, + float* tmp, const float* sv, int64_t ng, const Store& store, int path) { + const int64_t k = x.k; + auto rs = [&](int64_t wr) { return sv + (wr - it.n0) * ng; }; + if (path == kCbGeneric) { + /* A weight row through the table into L1, scaled per group, then the generic dot. */ + for (int64_t wr = it.n0; wr < it.n1; ++wr) { + const uint8_t* row = x.codes + wr * x.row_bytes; + for (int64_t g0 = 0; g0 < k; g0 += x.group) { + const float s = rs(wr)[g0 / x.group]; + const int64_t g1 = g0 + x.group < k ? g0 + x.group : k; + for (int64_t i = g0; i < g1; ++i) tmp[i] = x.tab[rad_load_bits(row, x.bits, i)] * s; + } + for (int64_t r = 0; r < R; ++r) store(r, wr, dotf(ar[r], tmp, k)); + } + return; + } +#if AVX_LEVEL == 3 + if (path == kCbLines && R <= kCbFused) { + /* Four weight rows at a time for one row, two for more: eight or more partial chains. */ + float o[4 * kCbFused]; + auto run = [&](auto w, auto rr) { + constexpr int Wn = decltype(w)::value, Rn = decltype(rr)::value; + int64_t wr = it.n0; + for (; wr + Wn <= it.n1; wr += Wn) { + cb_fused_lines(x, wr, ar, rs(wr), ng, o); + for (int ww = 0; ww < Wn; ++ww) + for (int r = 0; r < Rn; ++r) store(r, wr + ww, o[ww * Rn + r]); + } + for (; wr < it.n1; ++wr) { + cb_fused_lines<1, Rn>(x, wr, ar, rs(wr), ng, o); + for (int r = 0; r < Rn; ++r) store(r, wr, o[r]); + } + }; + using W4 = std::integral_constant; + using W2 = std::integral_constant; + switch (R) { + case 1: run(W4{}, std::integral_constant{}); break; + case 2: run(W2{}, std::integral_constant{}); break; + case 3: run(W2{}, std::integral_constant{}); break; + default: run(W2{}, std::integral_constant{}); break; + } + return; + } +#endif +#if AVX_LEVEL >= 2 + if (R <= kCbFused) { + float o[2 * kCbFused]; + auto run = [&](auto bits, auto w, auto rr) { + constexpr int B = decltype(bits)::value, Wn = decltype(w)::value; + constexpr int Rn = decltype(rr)::value; + int64_t wr = it.n0; + for (; wr + Wn <= it.n1; wr += Wn) { + cb_fused(x, wr, ar, rs(wr), ng, o); + for (int ww = 0; ww < Wn; ++ww) + for (int r = 0; r < Rn; ++r) store(r, wr + ww, o[ww * Rn + r]); + } + for (; wr < it.n1; ++wr) { + cb_fused(x, wr, ar, rs(wr), ng, o); + for (int r = 0; r < Rn; ++r) store(r, wr, o[r]); + } + }; + using I4 = std::integral_constant; + using I5 = std::integral_constant; + /* AVX2's sixteen registers hold two weight rows' accumulators for up to two rows. */ + using W2 = std::integral_constant; + using WB = std::integral_constant; + auto by_r = [&](auto bits) { + switch (R) { + case 1: run(bits, W2{}, std::integral_constant{}); break; + case 2: run(bits, W2{}, std::integral_constant{}); break; + case 3: run(bits, WB{}, std::integral_constant{}); break; + default: run(bits, WB{}, std::integral_constant{}); break; + } + }; + if (x.bits == 5) by_r(I5{}); + else by_r(I4{}); + return; + } + /* The panel form: kCbNR weight rows over all of K, against every row in kCbMR blocks, so each + * output takes one horizontal sum. */ + float* const P = tmp; + const int64_t nch = k / kCbCH; + for (int64_t wr0 = it.n0; wr0 < it.n1; wr0 += kCbNR) { + const int64_t nr = it.n1 - wr0 < kCbNR ? it.n1 - wr0 : kCbNR; +#if AVX_LEVEL == 3 + if (path == kCbLines) cb_panel_lines(x, wr0, nr, rs(wr0), ng, P, k); + else +#endif + if (x.bits == 5) cb_panel<5>(x, wr0, nr, 0, nch, rs(wr0), ng, P, k); + else cb_panel<4>(x, wr0, nr, 0, nch, rs(wr0), ng, P, k); + int64_t r0 = 0; + for (; r0 + kCbMR <= R; r0 += kCbMR) { + if (nr == kCbNR) { + float o[kCbMR][kCbNR] = {}; + cb_block(ar + r0, P, k, k, o); + for (int64_t i = 0; i < kCbMR; ++i) + for (int64_t j = 0; j < kCbNR; ++j) store(r0 + i, wr0 + j, o[i][j]); + continue; + } + for (int64_t j = 0; j < nr; ++j) { + float o[kCbMR][1] = {}; + cb_block(ar + r0, P + j * k, k, k, o); + for (int64_t i = 0; i < kCbMR; ++i) store(r0 + i, wr0 + j, o[i][0]); + } + } + for (; r0 < R; ++r0) { + if (nr == kCbNR) { + float o[1][kCbNR] = {}; + cb_block<1, kCbNR>(ar + r0, P, k, k, o); + for (int64_t j = 0; j < kCbNR; ++j) store(r0, wr0 + j, o[0][j]); + continue; + } + for (int64_t j = 0; j < nr; ++j) { + float o[1][1] = { { 0.0f } }; + cb_block<1, 1>(ar + r0, P + j * k, k, k, o); + store(r0, wr0 + j, o[0][0]); + } + } + } +#else + (void)R; (void)ar; (void)tmp; (void)sv; (void)ng; (void)store; +#endif +} + +/* One item: its products and the outputs written. `apk` holds the call's packed activation rows, + * `kp` floats apart. Scratch: a decoded weight row or the panel (_b), the outputs and the weight + * rows' scales (_c). */ +static void cb_item(const CbCall& c, const CbExp* ex, const int64_t* lr, const int64_t* atok, + const float* apk, int64_t kp, const CbItem& it, int path) { + const CbExp& x = ex[it.e]; + const int64_t R = it.r1 - it.r0, k = x.k, nw = it.n1 - it.n0; + const float* ar[kCbRB]; + for (int64_t r = 0; r < R; ++r) ar[r] = apk + atok[lr[it.r0 + r]] * kp; + float* tmp = scratch_f32_b((size_t)(kCbNR * k)); + const int64_t ng = x.groups(); + float* const ob = scratch_f32_c((size_t)(R * nw + nw * ng)); + float* const sv = ob + R * nw; + cb_scale_rows(x, it.n0, it.n1, sv); + auto store = [&](int64_t r, int64_t wr, float v) { ob[r * nw + wr - it.n0] = v; }; + cb_compute(x, it, R, ar, tmp, sv, ng, store, path); + + /* Weight row wr is output column (wr / fc) * fy + wr % fc, so each part's rows are one run of + * columns, converted at once where the output is dense. */ + const int64_t fc = x.n / c.parts, fy = c.N / c.parts; + const int ybits = rad_dtype_bits(c.Y->dtype); + const bool direct = c.y_cs == 1 && ybits % 8 == 0; + for (int64_t r = 0; r < R; ++r) { + const int64_t yr = lr[it.r0 + r] * c.y_rs; + for (int64_t w0 = it.n0; w0 < it.n1;) { + const int64_t w1 = std::min(it.n1, (w0 / fc + 1) * fc); + const int64_t col = (w0 / fc) * fy + w0 % fc; + const float* v = ob + r * nw + (w0 - it.n0); + if (direct) + row_from_f32(c.Y->dtype, v, (uint8_t*)c.Y->data + (yr + col) * (ybits / 8), + w1 - w0); + else + for (int64_t i = 0; i < w1 - w0; ++i) stt(c.Y, yr + (col + i) * c.y_cs, v[i]); + w0 = w1; + } + } +} + +static int moe_codebook(const CbCall& c) { + const int64_t T = c.T, ne = c.n_expert, nc = c.nc, K = c.K, AR = c.AR; + /* Upper bound on the items: each expert's row blocks, the last one partial, by its weight + * blocks. */ + const int64_t nblk = (c.N + kCbNC - 1) / kCbNC; + const int64_t max_items = (T / kCbRB + ne + 1) * nblk; + auto pad64 = [](size_t x) { return (x + 63) & ~(size_t)63; }; + const size_t o_ex = 0; + const size_t o_tok = pad64(o_ex + (size_t)ne * sizeof(CbExp)); + const size_t o_exp = pad64(o_tok + (size_t)T * sizeof(int64_t)); + const size_t o_lr = pad64(o_exp + (size_t)T * sizeof(int64_t)); + const size_t o_it = pad64(o_lr + (size_t)T * sizeof(int64_t)); + const size_t o_use = pad64(o_it + (size_t)max_items * sizeof(CbItem)); + const size_t o_apk = pad64(o_use + (size_t)AR); + uint8_t* base = (uint8_t*)scratch_raw(o_apk + (size_t)(AR * K) * sizeof(float) + 64); + CbExp* ex = (CbExp*)(base + o_ex); + int64_t* atok = (int64_t*)(base + o_tok); + int64_t* aexp = (int64_t*)(base + o_exp); + int64_t* lr = (int64_t*)(base + o_lr); + CbItem* items = (CbItem*)(base + o_it); + uint8_t* used = base + o_use; + float* apk = (float*)(base + o_apk); + + /* Every expert, in libref's order of checks; refused before any parallel region. And the + * fastest decode every expert admits; the chunk decode packs u4 and u5 rows differently, so + * a call mixing them takes the generic one. */ + int path = AVX_LEVEL == 3 ? kCbLines : AVX_LEVEL == 2 ? kCbChunks : kCbGeneric; + for (int64_t e = 0; e < ne; ++e) { + const int q = (int)(e % nc); + const int64_t ix = e / nc, n = c.Nq[q], k = c.Kq[q]; + const RadTensor w = expert_entry(c.Wq[q], ix); + if (!w.data) return RAD_E_STRIDE; + if (w.rank < 2 || w.shape[0] < n || w.shape[1] < k) return RAD_E_SHAPE; + RadTensor s{}; + if (c.wsq[q]) { + s = expert_entry(c.wsq[q], ix); + if (!s.data) return RAD_E_STRIDE; + } + CbExp& x = ex[e]; + x = CbExp{}; + const int jc = cb_codes(w, n, k, &x); + if (jc < 0) return jc; + if (jc == 0) return RAD_E_DTYPE; + const int js = cb_scale(c.wsq[q] ? &s : nullptr, &x); + if (js < 0) return js; +#if AVX_LEVEL == 3 + if (path == kCbLines && !cb_lines(x)) path = kCbChunks; +#endif + if (path == kCbChunks && + (k % kCbCH != 0 || x.group % kCbCH != 0 || x.bits != ex[0].bits)) + path = kCbGeneric; + } + + /* Each row's token, -1 for a dropped slot or a token past `a`, and its expert (libref's + * binary search, as one sweep over the offsets). */ + std::memset(used, 0, (size_t)AR); + for (int64_t i = 0; i < T; ++i) { + const int64_t flat = ldi(c.sorted, offlin(c.sorted, i)); + const int64_t tok = flat < 0 ? -1 : (c.sorted_a ? i : flat / c.top_k); + atok[i] = (tok >= 0 && tok < AR) ? tok : -1; + if (atok[i] >= 0) used[atok[i]] = 1; + } + { + int64_t e = 0; + for (int64_t i = 0; i < T; ++i) { + while (e + 1 < ne && ldi(c.off, offlin(c.off, e + 1)) <= i) ++e; + aexp[i] = e; + } + } + + /* Every activation row a live row reads, packed once for all its experts' items. */ + AVX_PARALLEL_FOR_IF(AR * K >= AVX_PAR_MIN) + for (int64_t t = 0; t < AR; ++t) { + if (!used[t]) continue; + cb_pack(c, t, K, ex[0].bits, apk + t * K, scratch_f32_b((size_t)K), path); + } + + /* Zeros: every column of a dropped row, and each part's columns past a narrower class's. */ + const int64_t fy = c.N / c.parts; + AVX_PARALLEL_FOR_IF(T * c.N >= AVX_PAR_MIN) + for (int64_t i = 0; i < T; ++i) { + const int64_t fc = atok[i] < 0 ? 0 : ex[aexp[i]].n / c.parts; + for (int64_t pp = 0; fc < fy && pp < c.parts; ++pp) + for (int64_t n = pp * fy + fc; n < (pp + 1) * fy; ++n) + stt(c.Y, i * c.y_rs + n * c.y_cs, 0.0f); + } + + /* The live rows, grouped by expert since the experts ascend with the row, and the items. */ + int64_t nl = 0, n_items = 0; + double work = 0; + for (int64_t i = 0; i < T; ++i) + if (atok[i] >= 0) lr[nl++] = i; + for (int64_t l0 = 0; l0 < nl;) { + const int64_t e = aexp[lr[l0]]; + int64_t l1 = l0; + while (l1 < nl && aexp[lr[l1]] == e) ++l1; + { + /* The panel form's items are wider: each re-reads its rows once a panel. */ + const int64_t w = l1 - l0 > kCbFused ? kCbNCP : kCbNC; + for (int64_t r0 = l0; r0 < l1; r0 += kCbRB) + for (int64_t n0 = 0; n0 < ex[e].n; n0 += w) + items[n_items++] = CbItem{ e, r0, r0 + kCbRB < l1 ? r0 + kCbRB : l1, n0, + n0 + w < ex[e].n ? n0 + w : ex[e].n }; + } + work += (double)(l1 - l0) * (double)ex[e].n * (double)ex[e].k; + l0 = l1; + } + +#ifdef _OPENMP + AVX_PRAGMA(omp parallel for schedule(dynamic, 1) + if(work >= (double)AVX_PAR_MIN || avx_par_forced()) num_threads(avx_team_size())) +#endif + for (int64_t it = 0; it < n_items; ++it) + cb_item(c, ex, lr, atok, apk, K, items[it], path); + return RAD_OK; +} + +/* ------------------------------------------------------------------ moe_gemm, moe_gemm_q */ +/* y[i, :] = a[row(i), :] @ w[e]^T, where e is the expert whose offset range contains i, and + * `a_order` picks row(i): `sorted_tok[i] / top_k` when the activation has one row per token, i when + * it has one row per (token, slot). The output is in sorted order, so each expert's rows are + * contiguous; moe_gather restores token order. + * + * `a_order` is explicit rather than inferred from the row count (M vs M*top_k): gate_up reads one + * row per token, down reads one per (token, slot), and a meaning that depended on the extent would + * be invisible to a checker that sizes the operand one way. */ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) { const int n_opd = quant ? (ncls == 4 ? 13 : 9) : 5; if (!rad_args_have(a, n_opd)) return RAD_E_INVAL; @@ -304,9 +984,8 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) { const RadTensor* sorted = &a->t[quant ? 4 : 2]; const RadTensor* off = &a->t[quant ? 5 : 3]; const RadTensor* Y = &a->t[quant ? (ncls == 4 ? 12 : 8) : 4]; - /* THE QUANTISED ARM'S EXPERTS ARE TWO TABLES BY PARITY, expert e at entry e / 2 of class - * e % 2 -- or for `moe_gemm_q_mod4` four, entry e / 4 of class e % 4; the plain arm's are - * one. */ + /* Quantised experts are split into tables by parity: expert e is entry e / 2 of class e % 2 + * (for `moe_gemm_q_mod4`, entry e / 4 of class e % 4). The plain arm has one table. */ const bool two = quant; const int nc = quant ? ncls : 1; const RadTensor* W1 = two ? &a->t[6] : W; @@ -322,7 +1001,8 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) { const int64_t N0 = p_int(a, "N", W->rank >= 3 ? W->shape[1] : 0); const int64_t K0 = p_int(a, "K", W->rank >= 3 ? W->shape[2] : 0); - /* Each class's geometry, defaulting to class 0's: N_odd/K_odd at two, N_q/K_q at four. */ + /* Per-class geometry, defaulting to class 0's: N_odd/K_odd for two classes, N_1..N_3 / + * K_1..K_3 for four. */ static const char* const kN4[4] = { "N", "N_1", "N_2", "N_3" }; static const char* const kK4[4] = { "K", "K_1", "K_2", "K_3" }; int64_t Nq[4] = { N0, N0, N0, N0 }, Kq[4] = { K0, K0, K0, K0 }; @@ -334,8 +1014,8 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) { const int64_t n_expert = p_int(a, "n_expert", W->rank >= 3 ? W->shape[0] : 0); const int64_t top_k = p_int(a, "top_k", 1); if (parts <= 0 || n_expert <= 0 || top_k <= 0) return RAD_E_SHAPE; - /* The output is the widest class's width, the activation the longest class's K; class q - * holds ceil((n - q) / nc) experts. */ + /* Output width is the widest class's N, activation width the largest K; class q holds + * ceil((n - q) / nc) experts. */ int64_t N = 0, K = 0; for (int q = 0; q < nc; ++q) { if (Nq[q] <= 0 || Kq[q] <= 0 || Nq[q] % parts) return RAD_E_SHAPE; @@ -352,39 +1032,50 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) { if (M <= 0 || numel(A) < AR * K) return RAD_E_SHAPE; const Mat ma = as_mat(A, K); - const Scales SA = make_scales(as_, AR, K); + const Scales SA = make_scales(as_, AR, K, false); const int64_t gp = p_int(a, "group", 0); if (quant && gp > 0 && SA.p && SA.group != gp) return RAD_E_SHAPE; const int64_t y_rs = row_stride(Y, N); const int64_t y_cs = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1; - /* ONE ARENA CALL FOR EVERYTHING THE PARALLEL REGIONS READ, and that is not tidiness. The - * scratch arena GROWS -- a second scratch_raw at a larger size frees the first block and - * returns a new one, so splitting this into two calls leaves every worker thread reading a - * dangling expert table while the main thread walks a valid panel. The layout is computed - * once, 64-aligned between sections so a vector load off the panel is legal. */ - const size_t ne = (size_t)n_expert; - auto pad64 = [](size_t x) { return (x + 63) & ~(size_t)63; }; - const size_t off_we = 0; - const size_t off_wse = pad64(off_we + ne * sizeof(RadTensor)); - const size_t off_mw = pad64(off_wse + ne * sizeof(RadTensor)); - const size_t off_sw = pad64(off_mw + ne * sizeof(Mat)); - const size_t off_pan = pad64(off_sw + ne * sizeof(Scales)); - const size_t off_tok = pad64(off_pan + (size_t)T * (size_t)K * sizeof(float)); - const size_t off_exp = pad64(off_tok + (size_t)T * sizeof(int64_t)); - uint8_t* base = (uint8_t*)scratch_raw(off_exp + (size_t)T * sizeof(int64_t) + 64); - RadTensor* we = (RadTensor*)(base + off_we); - RadTensor* wse = (RadTensor*)(base + off_wse); - Mat* mw = (Mat*)(base + off_mw); - Scales* SW = (Scales*)(base + off_sw); - float* apanel = (float*)(base + off_pan); - int64_t* atok = (int64_t*)(base + off_tok); - int64_t* aexp = (int64_t*)(base + off_exp); + /* u4 or u5 codes are the codebook experts' joined form, which only their own path reads. */ + if (quant && (Wq[0]->dtype == RAD_U4 || Wq[0]->dtype == RAD_U5)) { + CbCall c; + c.A = A; c.sorted = sorted; c.off = off; c.Y = Y; + for (int q = 0; q < 4; ++q) { + c.Wq[q] = Wq[q]; c.wsq[q] = wsq[q]; c.Nq[q] = Nq[q]; c.Kq[q] = Kq[q]; + } + c.nc = nc; c.parts = parts; c.n_expert = n_expert; c.top_k = top_k; + c.N = N; c.K = K; c.T = T; c.AR = AR; c.y_rs = y_rs; c.y_cs = y_cs; + c.sorted_a = sorted_a; + c.ma = ma; c.SA = SA; + return moe_codebook(c); + } - /* Per-expert readings, built once outside the loops. A null `data` means the operand could not - * be read as a table at all, which is refused BEFORE any parallel region because an OpenMP - * body cannot return. */ + /* The per-expert readings and the rows' sources and experts, which the parallel regions read, + * in vectors this thread keeps: the tile drivers take scratch_raw blocks of their own, and a + * second scratch_raw call may free the first under the worker threads. */ + static thread_local std::vector we_v, wse_v; + static thread_local std::vector mw_v; + static thread_local std::vector sw_v; + static thread_local std::vector atok_v, aexp_v; + we_v.assign((size_t)n_expert, RadTensor{}); + wse_v.assign((size_t)n_expert, RadTensor{}); + mw_v.assign((size_t)n_expert, Mat{}); + sw_v.assign((size_t)n_expert, Scales{}); + atok_v.resize((size_t)T); + aexp_v.resize((size_t)T); + RadTensor* we = we_v.data(); + RadTensor* wse = wse_v.data(); + Mat* mw = mw_v.data(); + Scales* SW = sw_v.data(); + int64_t* atok = atok_v.data(); + int64_t* aexp = aexp_v.data(); + + /* Per-expert readings, built once. Unreadable tables (null `data`) are refused here, before + * any parallel region, since an OpenMP body cannot return. */ + bool fine_a = false; for (int64_t e = 0; e < n_expert; ++e) { const int q = (int)(e % nc); const RadTensor* tw = Wq[q]; @@ -394,35 +1085,36 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) { we[e] = expert_entry(tw, ix); if (!we[e].data) return RAD_E_STRIDE; if (we[e].rank < 2 || we[e].shape[0] < n || we[e].shape[1] < k) return RAD_E_SHAPE; - mw[e] = as_mat(&we[e], k); if (quant && ts) { wse[e] = expert_entry(ts, ix); if (!wse[e].data) return RAD_E_STRIDE; - SW[e] = make_scales(&wse[e], n, k); - } else { - SW[e] = make_scales(nullptr, n, k); } - /* An activation grid FINER than the weight's cannot have its scale hoisted out of the - * group. No format in this project has one; refusing here, before any work, is the honest - * answer and it cannot be done inside the loop because an OpenMP body cannot return. */ + if (quant) { + /* Expert 0 is plain, so codebook codes or a joined scale here mix two forms in one + * call, refused as libref refuses them. */ + CbExp cx; + const int jc = cb_codes(we[e], n, k, &cx); + if (jc < 0) return jc; + if (jc > 0 || (ts && cb_joined(wse[e]))) return RAD_E_DTYPE; + } + mw[e] = as_mat(&we[e], k); + SW[e] = make_scales(quant && ts ? &wse[e] : nullptr, n, k, false); + /* An activation scale grid finer than an expert's cannot be hoisted out of the group. No + * supported format has one, but libref answers it by scaling each element, so the panel + * below is scaled as it is packed and the dot reads no activation scale (`SAg`). */ const int64_t g = SW[e].p && SW[e].group > 0 ? SW[e].group : k; - if (SA.p && SA.group < g) return RAD_E_UNSUPPORTED; + if (SA.p && SA.group < g) fine_a = true; } + Scales SAg = SA; + if (fine_a) SAg.p = nullptr; - /* THE ACTIVATION PANEL. Every output row's source row is widened into f32 once, here, so the - * dot products below never touch a dtype -- and so the N loop can read the same panel row for - * all its outputs instead of re-converting it N times. Dropped slots are marked with a - * negative token and their output row is zeroed rather than left as stale arena bytes. */ - AVX_PARALLEL_FOR_IF(T * K >= AVX_PAR_MIN) + /* Each sorted row's activation row (-1: a dropped slot) and owning expert, in one linear + * sweep over the offsets (rows are expert-sorted). */ for (int64_t i = 0; i < T; ++i) { const int64_t flat = ldi(sorted, offlin(sorted, i)); const int64_t tok = flat < 0 ? -1 : (sorted_a ? i : flat / top_k); atok[i] = (tok >= 0 && tok < AR) ? tok : -1; - if (atok[i] >= 0) pack_row(ma, atok[i], K, apanel + i * K); } - - /* Which expert owns row i, walked once off the offsets rather than binary-searched per - * (row, n) pair -- the rows are expert-sorted, so one linear sweep answers every row. */ { int64_t e = 0; for (int64_t i = 0; i < T; ++i) { @@ -431,9 +1123,60 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) { } } - /* Output column n is weight row (n / fy) * fc + n % fy of its expert, and zero past a narrower - * class's part. */ + /* Output column n is weight row (n / fy) * fc + n % fy of its expert, and zero past the end of + * a narrower class's part. */ const int64_t fy = N / parts; + + /* The tile drivers: one job per (run of an expert's rows, part), every job's tasks in one + * parallel region, the activation rows read through atok. Dropped slots and the columns past + * a narrower class's part are zero, written after. */ + { + static thread_local std::vector jobs; + jobs.clear(); + for (int64_t i0 = 0; i0 < T;) { + int64_t i1 = i0 + 1; + while (i1 < T && aexp[i1] == aexp[i0]) ++i1; + const int64_t e = aexp[i0]; + const int q = (int)(e % nc); + const int64_t fc = Nq[q] / parts; + for (int64_t pp = 0; pp < parts; ++pp) { + TileJob jb{}; + jb.mb = mw[e]; + jb.SB = SW[e]; + jb.b0 = pp * fc; + jb.a0 = i0; jb.M = i1 - i0; jb.N = fc; jb.K = Kq[q]; + jb.y0 = i0; jb.yc0 = pp * fy; + jobs.push_back(jb); + } + i0 = i1; + } + const Scales* sap = SA.p ? &SA : nullptr; + if (gemm_q_bf16_jobs(ma, atok, T, sap, jobs.data(), (int64_t)jobs.size(), Y, N) || + gemm_tile_f32_jobs(ma, atok, T, sap, jobs.data(), (int64_t)jobs.size(), Y, N)) { + AVX_PARALLEL_FOR_IF(T * N >= AVX_PAR_MIN) + for (int64_t i = 0; i < T; ++i) { + const int64_t fc = atok[i] < 0 ? 0 : Nq[(int)(aexp[i] % nc)] / parts; + if (fc >= fy) continue; + for (int64_t pp = 0; pp < parts; ++pp) + for (int64_t n = pp * fy + fc; n < (pp + 1) * fy; ++n) + stt(Y, i * y_rs + n * y_cs, 0.0f); + } + return RAD_OK; + } + } + + /* Activation panel: each output row's source row widened to f32 once, so the N loop reuses + * it. Dropped slots have a negative token, and their output rows are zeroed below. */ + float* apanel = (float*)scratch_raw((size_t)T * (size_t)K * sizeof(float) + 64); + AVX_PARALLEL_FOR_IF(T * K >= AVX_PAR_MIN) + for (int64_t i = 0; i < T; ++i) { + if (atok[i] < 0) continue; + float* row = apanel + i * K; + pack_row(ma, atok[i], K, row); + if (fine_a) + for (int64_t k = 0; k < K; ++k) row[k] *= SA.grp(atok[i], k / SA.group); + } + AVX_PARALLEL_FOR_IF(T * N * K >= AVX_PAR_MIN) for (int64_t n = 0; n < N; ++n) { float* bbuf = scratch_f32((size_t)K); @@ -446,9 +1189,8 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) { const int64_t fc = Nq[q] / parts, ke = Kq[q]; if (j >= fc) { stt(Y, i * y_rs + n * y_cs, 0.0f); continue; } const int64_t wr = pp * fc + j; - /* The expert's weight row is packed when the expert CHANGES, which -- because the - * rows are expert-sorted -- is at most n_expert times over the whole i loop. That is - * the win over walking (row, n) and re-reading the weight per row. */ + /* Repack the weight row only when the expert changes: at most n_expert times per + * column, since rows are expert-sorted. */ if (e != packed_e) { pack_row(mw[e], wr, ke, bbuf); packed_e = e; } const Scales& SB = SW[e]; const int64_t g = SB.p && SB.group > 0 ? SB.group : ke; @@ -458,8 +1200,9 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) { for (int64_t gi = 0; gi < ngrp; ++gi) { const int64_t k0 = gi * g, k1 = (k0 + g < ke) ? k0 + g : ke; const float sb = SB.p ? SB.grp(wr, gi) : 1.0f; - const float sa = (SA.p && SA.group > 0) ? SA.grp(atok[i], k0 / SA.group) : 1.0f; - acc += dotf(av, bbuf, k0, k1) * sa * sb; + const float sa = (SAg.p && SAg.group > 0) ? SAg.grp(atok[i], k0 / SAg.group) + : 1.0f; + acc += dotf(av + k0, bbuf + k0, k1 - k0) * sa * sb; } stt(Y, i * y_rs + n * y_cs, acc); } @@ -472,20 +1215,13 @@ AVX_KERNEL(moe_gemm_q) { return moe_gemm_impl(a, true); } AVX_KERNEL(moe_gemm_q_mod4) { return moe_gemm_impl(a, true, 4); } /* ------------------------------------------------------------------ moe_gather */ -/* y[t] = sum over the token's slots of expert_w[t, j] * y_expert[position of (t, j)]. - * - * THE SUMMATION ORDER IS ASCENDING SLOT j, which is what makes this reproducible: walking the - * expert-sorted rows instead would sum a token's contributions in expert-id order and the two - * differ in the last bits. - * - * The inverse permutation is built ONCE over the whole batch. libref rebuilds it per block of - * tokens into a fixed stack array specifically to avoid allocating, which costs (M / block) full - * passes over sorted_tok; the scratch arena removes the reason for that. */ +/* y[t] = sum over the token's slots of expert_w[t, j] * y_expert[position of (t, j)], summed in + * ascending slot j (see the file header). The inverse permutation is built once per batch. */ AVX_KERNEL(moe_gather) { if (!rad_args_have(a, 6)) return RAD_E_INVAL; const RadTensor *ye = &a->t[0], *ew = &a->t[1], *sorted = &a->t[2], *Y = &a->t[5]; - /* The shared arm, folded: y = narrow(shared * act(gate)) + narrow(gathered). - * A pair or neither, exactly libref's opening lines. */ + /* Optional shared-expert fold: y = narrow(shared * act(gate)) + narrow(gathered). Both + * operands or neither, as in libref. */ const RadTensor *sh = rad_arg_in(a, 3), *sg = rad_arg_in(a, 4); if ((sh != nullptr) != (sg != nullptr)) return RAD_E_INVAL; const char* act = p_str(a, "act", "none"); @@ -507,10 +1243,9 @@ AVX_KERNEL(moe_gather) { const int64_t ye_rs = ye->rank >= 2 ? ye->stride[ye->rank - 2] : n; const int64_t ye_cs = ye->rank >= 2 ? ye->stride[ye->rank - 1] : 1; - /* libref's Y addressing, for the fold below: stride[rank-2]/stride[rank-1], not the - * rowoff/laststride reading out_row uses. The two agree on every rank-2 [M, n] this op is - * described with; the fold uses this one so a hostile higher-rank Y still lands where the - * reference puts it. */ + /* libref's Y addressing for the fold: stride[rank-2] / stride[rank-1], rather than out_row's + * rowoff/laststride. They agree for rank-2 [M, n]; this matches the reference for higher + * ranks too. */ const int64_t y_rs = Y->rank >= 2 ? Y->stride[Y->rank - 2] : n; const int64_t y_cs = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1; @@ -541,11 +1276,11 @@ AVX_KERNEL(moe_gather) { out_row(Y, rowoff(Y, t, n), n, acc); continue; } - /* THE NARROWS ARE THE UNFUSED PAIR'S, in libref's order: narrow the gathered row into Y, - * narrow the shared product into Y, narrow their sum. The gate is one scalar per token, - * through the same expf the oracle uses (see scale_rows on why not the vector form). */ + /* The unfused pair's roundings, in libref's order: store the gathered row into Y, store + * the shared product into Y, store their sum. The per-token gate uses libm's expf, as the + * oracle does. */ const float v0 = ldt(sg, t * laststride(sg)); - const float gate = sig ? 1.0f / (1.0f + std::exp(-v0)) : v0; + const float gate = sig ? 1.0f / (1.0f + sc_exp(-v0)) : v0; const int64_t shb = rowoff(sh, t, n), shs = laststride(sh); for (int64_t c = 0; c < n; ++c) { const int64_t yo = t * y_rs + c * y_cs; @@ -559,33 +1294,16 @@ AVX_KERNEL(moe_gather) { } /* ------------------------------------------------------------------ logit_rerank */ -/* R candidate ids rescored against the full-precision head and re-sorted, the second half of a - * coarse top-R. `idx_in` carries GLOBAL ids, `vocab_off` is this rank's first column, - * and an id outside the head's rows becomes a pad that sorts last with -inf. +/* Rescores R candidate ids against the full-precision head and re-sorts them: the second half of + * a coarse top-R. `idx_in` holds global ids, `vocab_off` is this rank's first column, and an id + * outside the head's rows becomes a pad that sorts last with -inf. * - * THE DOTS ARE f32-VECTOR, the reference's are f64-scalar IN ORDER, and that is a tolerance - * question rather than a defect: at K = 2048 the tree differs ~1e-6 relative and the op has no - * tight entry, so it lands in the dtype bucket (1e-5 f32). What is EXACT is the selection -- - * descending by value, ties to the lower id, pads dropped -- copied rather than paraphrased, - * because a tie resolved differently from row_topk is a silent routing divergence. + * The dots are f32 vector sums (libref sums in f64 in order); at K = 2048 they differ ~1e-6 + * relative, inside the f32 tolerance of 1e-5. The selection is exact: descending, ties to the + * lower id, pads dropped, the same rule as row_topk. * - * `head` is read FLAT ([NV, K] row-major, unit stride), exactly as the reference reads it: the - * row for candidate id g starts at g * K elements. That is the contract, not a convenience. */ -static inline float dotf(const float* a, const float* b, int64_t n) { - vf a0 = vf_zero(), a1 = vf_zero(), a2 = vf_zero(), a3 = vf_zero(); - int64_t k = 0; - for (; k + 4 * VF_N <= n; k += 4 * VF_N) { - a0 = vf_fma(vf_loadu(a + k), vf_loadu(b + k), a0); - a1 = vf_fma(vf_loadu(a + k + VF_N), vf_loadu(b + k + VF_N), a1); - a2 = vf_fma(vf_loadu(a + k + 2 * VF_N), vf_loadu(b + k + 2 * VF_N), a2); - a3 = vf_fma(vf_loadu(a + k + 3 * VF_N), vf_loadu(b + k + 3 * VF_N), a3); - } - for (; k + VF_N <= n; k += VF_N) a0 = vf_fma(vf_loadu(a + k), vf_loadu(b + k), a0); - float s = vf_hsum(vf_add(vf_add(a0, a1), vf_add(a2, a3))); - for (; k < n; ++k) s += a[k] * b[k]; - return s; -} - + * `head` is read flat ([NV, K] row-major, unit stride), as the reference reads it: candidate g's + * row starts at element g * K. */ AVX_KERNEL(logit_rerank) { if (!rad_args_have(a, 5)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *w = &a->t[1], *in = &a->t[2]; @@ -599,7 +1317,15 @@ AVX_KERNEL(logit_rerank) { const int64_t M = numel(x) / K; if (M <= 0 || numel(in) < M * R) return RAD_E_SHAPE; if (numel(idx) < M * R || numel(val) < M * R) return RAD_E_SHAPE; - if (numel(w) < NV * K) return RAD_E_SHAPE; + /* A head of codes and scale, joined (avx_planes.h), decodes a candidate's row as the core's + * decoder does, so its scores are those of the decoded f32 head. */ + avxp::ScaledRows sr; + const bool joined = avxp::is_joined(w); + if (joined) { + if (const int st = avxp::scaled_rows(w, NV, K, &sr); st != RAD_OK) return st; + } else if (numel(w) < NV * K) { + return RAD_E_SHAPE; + } AVX_PARALLEL_FOR_IF(M * R * K >= AVX_PAR_MIN) for (int64_t m = 0; m < M; ++m) { @@ -607,8 +1333,8 @@ AVX_KERNEL(logit_rerank) { float* wb = scratch_f32_b((size_t)K); float* sc = scratch_f32_c((size_t)R); const float* xv = in_row(x, rowoff(x, m, K), K, xb); - /* ONE raw block, partitioned by hand: the arena has a single slot, so two get() calls - * would hand back the SAME pointer and `used` would clobber `id`. */ + /* One raw block for `id` and `used`: scratch_raw has a single slot, so a second call + * would return the same pointer. */ int32_t* id = (int32_t*)scratch_raw((size_t)R * sizeof(int32_t) + (size_t)R + 64); for (int64_t r = 0; r < R; ++r) { const int64_t g = ldi(in, rowoff(in, m, R) + r * laststride(in)); @@ -618,7 +1344,8 @@ AVX_KERNEL(logit_rerank) { sc[r] = -INFINITY; continue; } - row_to_f32(w->dtype, byte_at(w->data, w->dtype, local * K), wb, K); + if (joined) scaled_row(sr, local, K, wb); + else row_to_f32(w->dtype, byte_at(w->data, w->dtype, local * K), wb, K); id[r] = (int32_t)g; sc[r] = dotf(xv, wb, K); } @@ -647,13 +1374,12 @@ AVX_KERNEL(logit_rerank) { } /* ------------------------------------------------------------------ row_topk */ -/* Exact per-row top-R, descending, ties to the lower column. The same selection the router uses, - * exposed as its own op because a drafter's candidate set and a speculative tree both want it - * without a softmax in front. +/* Exact per-row top-R, descending, ties to the lower column: the router's selection without the + * softmax (for drafter candidate sets and speculative trees). * - * The vocab-parallel form: `vocab_off` shifts every column reported so a rank's slice reports - * GLOBAL ids, and `pairs` is the [M, R, 2] plane an all_gather moves -- an int32 id bit-copied - * into the first float slot beside its value. Both absent is the ordinary single-rank top-R. */ + * Vocab-parallel form: `vocab_off` shifts reported columns to global ids, and `pairs` is the + * [M, R, 2] plane an all_gather moves (int32 id bit-copied into the first float, then the value). + * Without either it is the single-rank top-R. */ AVX_KERNEL(row_topk) { if (!rad_args_have(a, 3)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *idx = &a->t[1], *val = &a->t[2]; @@ -689,27 +1415,21 @@ AVX_KERNEL(row_topk) { } /* ------------------------------------------------------------------ row_topk_merge */ -/* The R largest of world_size all-gathered per-rank candidate sets, in the same descending - * (idx, val) form the single-rank path produces. +/* The R largest of world_size all-gathered per-rank candidate sets, in the single-rank path's + * descending (idx, val) form. * - * TIES BREAK ON THE LOWER ID, which is what makes the merge EXACT rather than approximate: a dense - * top-R over the whole vocabulary breaks ties on the lower column, so a merge that broke them on - * rank order would disagree with it exactly when two shards hold the same logit. + * Ties break on the lower id, so the merge matches a dense top-R over the whole vocabulary exactly. + * Unfilled slots carry id -1 and are dropped (an id sentinel, since -inf is a legitimate masked + * logit). * - * A slot the producing rank could not fill carries id -1 and is DROPPED -- a sentinel rather than - * a -inf value, because -inf is a value a masked logit legitimately takes. - * - * LEFT SCALAR, AND THE REASON IS THE SIZE. W*R is 32 entries at world 2 and R 16; the selection - * sort over it is 512 comparisons against a vector setup that would cost more than it saves, and - * the tie rule is a lexicographic compare that no vector max expresses. */ + * Scalar: W*R is small (32 at world 2, R 16) and the (value, id) tie rule has no vector max. */ AVX_KERNEL(row_topk_merge) { if (!rad_args_have(a, 3)) return RAD_E_INVAL; const RadTensor *g = &a->t[0], *idx = &a->t[1], *val = &a->t[2]; const int64_t R = p_int(a, "R", 1); const int64_t W = p_int(a, "world_size", 1); if (R <= 0 || W <= 0) return RAD_E_SHAPE; - /* The rows are the OPERAND'S, not the parameter's: `M` is declared as a band ceiling and the - * gathered plane is narrowed to the rows this step actually has. */ + /* Rows come from the operand; `M` is only the band's ceiling. */ const int64_t M = numel(g) / (W * R * 2); if (M <= 0) return RAD_E_SHAPE; if (g->dtype != RAD_F32 || numel(g) < M * W * R * 2) return RAD_E_SHAPE; @@ -728,7 +1448,7 @@ AVX_KERNEL(row_topk_merge) { if (used[c]) continue; int32_t id; std::memcpy(&id, row + c * 2, sizeof id); - if (id < 0) continue; /* a pad, not a candidate */ + if (id < 0) continue; /* pad */ const float v = row[c * 2 + 1]; if (best < 0 || v > bv || (v == bv && id < bid)) { best = c; bv = v; bid = id; } } @@ -742,11 +1462,9 @@ AVX_KERNEL(row_topk_merge) { } /* ------------------------------------------------------------------ pair_argmax */ -/* row_topk_merge at R = 1, one id a row at the output's own pitch: the vocab-sharded draft head's - * proposal. Same pads, same tie rule, -1 and -inf for a row with nothing valid; `val` optional. - * - * LEFT SCALAR for the merge's reason, more so: `n` is world_size * R -- sixteen pairs at TP8 and - * R 2 -- and the whole op is one pass over them a row. */ +/* row_topk_merge at R = 1, one id per row at the output's own pitch: the vocab-sharded draft + * head's proposal. Same pads and tie rule; -1 and -inf for a row with nothing valid; `val` is + * optional. Scalar: `n` is world_size * R (16 pairs at TP8, R 2). */ AVX_KERNEL(pair_argmax) { if (!rad_args_have(a, 2)) return RAD_E_INVAL; const RadTensor *p = &a->t[0], *idx = &a->t[1]; @@ -765,7 +1483,7 @@ AVX_KERNEL(pair_argmax) { for (int64_t j = 0; j < n; ++j) { int32_t id; std::memcpy(&id, pf + offlin(p, (m * n + j) * 2), sizeof id); - if (id < 0) continue; /* a pad, not a candidate */ + if (id < 0) continue; /* pad */ const float v = pf[offlin(p, (m * n + j) * 2 + 1)]; if (bid < 0 || v > bv || (v == bv && id < bid)) { bid = id; bv = v; } } diff --git a/libavx/avx_ngram.cpp b/libavx/avx_ngram.cpp index c300553d..ccb735d4 100644 --- a/libavx/avx_ngram.cpp +++ b/libavx/avx_ngram.cpp @@ -1,63 +1,34 @@ -/* avx_ngram.cpp -- where embed_lookup_q's rows come from, and the table's stored arrangement. - * BASELINE-COMPILED: no -m flags, like avx_dispatch.cpp. Nothing here is vector arithmetic; the - * decode that is arrives from the calling level (avx_rows.h). +/* avx_ngram.cpp -- the row source for embed_lookup_q, and the table's stored layout. + * Baseline-compiled (no -m flags), like avx_dispatch.cpp; the vector decode comes from the calling + * level (avx_rows.h). * - * ============================== WHY THIS GATHER IS A HOST KERNEL ============================== + * Why a host kernel. The n-gram embedding is 320,001,536 rows of 160 E4M3 bytes (51.2 GB), read 16 + * rows per token. The engine's mechanisms for oversized weights do not fit that access pattern: + * Tier::SSD + DeviceStaged stages whole movement units, Site::DeviceZeroCopy needs pinned host RAM, + * and hipHostRegister on the mapping would pin all 51.2 GB. core/format/radfile.cpp mmaps the + * container, so the table already sits at a host address backed by an NVMe file. The gather runs + * on the host over that mapping and only the [T, n_embd] bf16 result crosses the link. The placement + * planner puts an op on the host when all its weight operands are Site::Host (core/runtime/ctx.cpp), + * so the table must be a weight operand (a plain `gather_rows` input would not trigger it), and a + * production host kernel is needed since libref is not served (rad_gate_reference_kernels). * - * An n-gram embedding of 320,001,536 rows of 160 E4M3 is 51.2 GB, read SIXTEEN ROWS A TOKEN, and - * every mechanism for an oversized weight is built for a different shape of access: + * Row cache plus direct reads. Decoding a row takes a few dozen cycles; fetching it is the cost, + * and at decode about half the rows a step wants have never been read before. The page cache is + * the wrong cache: a buffered miss costs the submitting thread ~4 us (page allocation, insertion, + * block mapping, bio), serialising a call's cold rows, and it keeps a 4 KiB page per 160-byte row + * (pages average ~1 useful row out of 25). So RowCache (below) holds rows, shared by every gathering + * thread, and a miss is an O_DIRECT read of the aligned span holding the row (~2 us to submit, + * 512 bytes instead of 4096). With eight varied sequences a 2^19-row cache (80 MiB) misses 51.0% of + * rows against 50.6% for an unbounded one. * - * Tier::SSD + DeviceStaged stages a WHOLE movement unit into a slab slot and DMAs it. Staging - * 51.2 GB to use 5 KB is not a slow path, it is the wrong shape. - * Site::DeviceZeroCopy wants it in pinned host RAM, which a table this size does not fit. - * hipHostRegister on the map pins, so it would force all 51.2 GB resident. Same wall. + * Each miss is read once. Every rank gathers every row. A thread claims a missing row by marking + * its slot LOADING, reads it and publishes it READY; others wait instead of re-reading. Ranks start + * at different rows of a call, so the misses are split between them with no barrier. * - * core/format/radfile.cpp mmaps the whole container -- "LOAD IS MAP-AND-GO" -- so the table is at - * a HOST virtual address the moment the model opens, backed by a file on an NVMe. A sparse gather - * of sixteen rows out of 320 million is a caching problem -- nothing can predict which rows are hot - * -- but for a cache of ROWS, not of the 4 KiB pages the OS would keep; see the row cache below. - * (core/place/mover.h rejects mmap for the WEIGHT POOL and that argument does not reach here -- it - * is about SWEEPING a working set, where residency is controlled explicitly.) - * - * So the gather runs on the host, over the container's own mapping, and its [T, n_embd] bf16 - * result crosses the link once -- a few kilobytes a token at decode. The placement planner puts an - * op on the host when every WEIGHT operand of it is Site::Host (core/runtime/ctx.cpp), which is why - * the table has to be a weight operand: `gather_rows` takes a plain IN operand and would never - * trigger it. A host op needs a host kernel in a production plugin -- libref is the oracle and - * rad_gate_reference_kernels refuses to serve on it -- and host kernels are this plugin's. - * - * ============================== A SHARED ROW CACHE, AND DIRECT READS FOR ITS MISSES ============================== - * - * The gather is not arithmetic. 160 table bytes decode to 160 bf16 in a few dozen cycles; what a - * row costs is getting its bytes, and at decode most of them have never been read before: eight - * varied sequences want ~487 distinct rows a step, and about half of those are an n-gram hashed for - * the first time (see the trace note below). No cache serves those; they are reads. - * - * THE PAGE CACHE IS THE WRONG CACHE FOR THIS TABLE, twice over. A buffered read of an uncached page - * costs the submitting thread ~4 us -- page allocation, page-cache insertion, block mapping and the - * bio all run inside the submission -- so a call's cold rows are started one after another: ~380 of - * them take ~1.5 ms to submit, and the drive finishes the burst ~0.25 ms after the last one. And it - * caches a 4 KiB page for a 160-byte row that shares its page with nothing else a gather wants, so - * every miss evicts 4 KiB of some other file's cache to keep 160 bytes of this one. - * - * SO THE ROWS HAVE THEIR OWN CACHE, AND A MISS IS A DIRECT READ. RowCache below holds rows, not - * pages, and every thread that gathers from the table shares it. A miss is an O_DIRECT read of the - * aligned span holding the row: ~2 us to submit, nothing inserted anywhere, 512 bytes off the drive - * where a page read takes 4096. At eight varied sequences a cache of 2^19 rows (80 MiB at 160 bytes) - * misses 51.0% of rows, against 50.6% for an unbounded one. - * - * EACH MISS IS READ ONCE, BY WHICHEVER THREAD CLAIMS IT. Every rank gathers every row. A thread - * claims a missing row by marking its slot LOADING, reads it and publishes it READY; a thread that - * finds a row another thread is loading waits for it instead of reading it again. The ranks walk a - * call's rows from different starting points, so each claims about its own share of the misses and - * the cold work is divided between them rather than duplicated -- with no barrier between the - * ranks: a late rank finds the rows already there. - * - * THE FILE COMES FROM THE MAPPING. The table operand is a pointer into the container's mmap and the - * plugin ABI carries no file, so /proc/self/maps says which file and offset back that address, once - * a table. A table no file backs -- a test's heap buffer -- is read as the memory it is. A file on a - * filesystem that cannot do direct I/O is refused; direct_granule below finds the alignment the - * reads keep, including on a filesystem that does not report one. */ + * The file is found from the mapping: the ABI passes a pointer, so /proc/self/maps gives the file + * and offset, once per table. A table not backed by a file (a test's heap buffer) is read as + * memory. A file on a filesystem without direct I/O is refused; direct_granule finds the read + * alignment, also where the filesystem reports none. */ #include "avx_rows.h" #include "avx_common.h" @@ -89,35 +60,33 @@ namespace { -/* How many rows ahead of the one being looked up or decoded its cache lines are requested. The - * rows are scattered over an 80 MiB cache and the set words over 4 MiB, so every row is a miss to - * L3 or DRAM; a row's lines requested this far ahead arrive while the rows before it are worked on - * instead of one after another. */ +/* 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; -/* One read of a row's aligned span: row m of the call, its key, and its cache slot (-1: the row is - * decoded straight from the read, not kept). */ +/* One read of a row's aligned span: row m of the call, its key, and its cache slot (-1: decoded + * straight from the read, not cached). */ struct SpanRead { long long m; uint64_t key; int64_t slot; }; -/* A thread's working state for one call, kept between calls so a call allocates nothing once the - * thread has seen its largest. */ +/* Per-thread working state for a call, kept between calls so steady-state calls do not + * allocate. */ struct Gather { std::vector slot; /* per row: its cache slot */ std::vector kind; /* per row: a RowCache::Found, or PAD / DONE below */ std::vector reads; /* the rows this thread reads */ std::vector waits; /* rows another thread is reading */ std::vector again; /* rows whose slot changed under the decode */ - /* One decode batch: each row's source and destination, and for a row decoded from the cache, - * its call index and the slot word it was read under. */ + /* One decode batch: each row's source and destination and, for cached rows, its call index + * and the slot word it was read under. */ std::vector src; std::vector dst; std::vector dm; std::vector dw; - /* The same for rows decoded straight from a read's bounce buffer. */ + /* Sources and destinations for rows decoded from a read's bounce buffer. */ std::vector bsrc; std::vector bdst; uint8_t* bounce = nullptr; @@ -126,9 +95,8 @@ struct Gather { enum : uint8_t { PAD = 16, DONE }; - /* A buffer of at least `bytes` on a page and on `align`, a power of two: a direct read's - * buffer has to keep the file's granule, which a filesystem with large blocks puts above a - * page. */ + /* A buffer of at least `bytes`, aligned to max(page, `align`) (a power of two): direct reads + * need the file's granule, which can exceed a page on large-block filesystems. */ uint8_t* bounce_for(size_t bytes, size_t align) { if (align < 4096) align = 4096; if (bytes > bounce_bytes || align > bounce_align) { @@ -149,9 +117,8 @@ inline Gather& gather_state() { #if defined(__linux__) -/* The file behind a table: the address range of its mapping, the file offset of that range's first - * byte, and the file opened for direct reads with the granule their offsets and lengths must keep. - * `fd` is -1 for memory no file backs. */ +/* The file behind a table: its mapping's address range, the file offset of the range's first byte, + * an O_DIRECT fd, and the granule reads must align to. `fd` is -1 for memory with no file. */ struct TableFile { const uint8_t* lo = nullptr; const uint8_t* hi = nullptr; @@ -160,23 +127,18 @@ struct TableFile { long long align = 0; }; -/* THE GRANULE OF A DIRECT READ of `t`'s file, opened for them as `t.fd`: the alignment a read's - * file offset, its length and its buffer's address must all keep. 0, with `*why` saying why, when - * the file cannot be read that way. [p, p + n) is the table, inside the mapping, and `ino` the - * mapped file's inode. +/* Granule of a direct read of `t`'s file (`t.fd`): the alignment the file offset, length and buffer + * address must all keep. Returns 0, with `*why`, if the file cannot be read that way. [p, p + n) is + * the table inside the mapping; `ino` is the mapped file's inode. * - * STATX_DIOALIGN is the filesystem's own answer, and not every filesystem gives one: btrfs does - * direct reads and reports nothing, and so does a tmpfs since Linux 6.6. Without the report the - * granule is the file's block size, stx_blksize. No block filesystem's direct reads need more -- - * a filesystem's blocks are never smaller than its device's sectors -- and btrfs needs exactly - * that: its sector size, below which it does not refuse a direct read but serves it through the - * page cache instead. + * STATX_DIOALIGN is used when reported. btrfs (and tmpfs since Linux 6.6) does direct reads but + * reports nothing; then the granule is stx_blksize. No block filesystem needs more (blocks are never + * smaller than device sectors), and btrfs needs exactly its sector size: below it, it silently + * serves direct reads through the page cache. * - * Reported or not, one read proves the granule before any row is served: a span of the table at - * an offset and into a buffer each aligned to the granule and to no more, which has to return the - * bytes the mapping holds there. That catches a filesystem refusing the granule and a file that is - * not the one mapped. A btrfs serving the read through the page cache returns the right bytes and - * passes it; the block size is what keeps btrfs off that path. */ + * One test read then proves the granule: a span at an offset and into a buffer aligned to the + * granule and no more, which must return the bytes the mapping holds. This catches a refused + * granule and a file that is not the one mapped. */ long long direct_granule(const TableFile& t, const uint8_t* p, long long n, unsigned long long ino, const char* path, const char** why) { struct statx sx; @@ -204,7 +166,7 @@ long long direct_granule(const TableFile& t, const uint8_t* p, long long n, unsi return 0; } - /* An odd multiple of the granule, so neither the offset nor the buffer keeps more than it. */ + /* An odd multiple of the granule, so neither offset nor buffer is over-aligned. */ const long long tab_lo = t.off + (long long)(p - t.lo); long long o = (tab_lo + a - 1) & ~(a - 1); if ((o / a) % 2 == 0) o += a; @@ -234,10 +196,9 @@ long long direct_granule(const TableFile& t, const uint8_t* p, long long n, unsi return a; } -/* The file behind [p, p + n): the mapping holding `p`, extended over the mappings that continue it - * in the same file (a madvise over a sub-range splits one mapping into several). Looked up once per - * table and kept for the life of the process; every rank thread shares the entry and the fd, and a - * read at an explicit offset has no file position to share. */ +/* The file behind [p, p + n): the mapping holding `p`, extended over following mappings of the same + * file (madvise on a sub-range splits a mapping). Looked up once per table and kept for the life of + * the process; rank threads share the entry and fd (reads use explicit offsets). */ const TableFile* table_file(const uint8_t* p, long long n, int* err) { static std::mutex mu; static std::vector> known; @@ -267,7 +228,7 @@ const TableFile* table_file(const uint8_t* p, long long n, int* err) { while (!name.empty() && (name.back() == '\n' || name.back() == ' ')) name.pop_back(); if (!found) { if ((uintptr_t)p < lo || (uintptr_t)p >= hi) continue; - if (inode == 0 || name.empty() || name[0] != '/') break; /* no file: memory */ + if (inode == 0 || name.empty() || name[0] != '/') break; /* not file-backed */ found = true; t->lo = (const uint8_t*)(uintptr_t)lo; t->off = (long long)off; @@ -303,22 +264,21 @@ const TableFile* table_file(const uint8_t* p, long long n, int* err) { return known.back().get(); } -/* ============================== THE ROW CACHE ============================== +/* ============================== the row cache ============================== * - * Set-associative: a row's key -- its byte offset in the file -- hashes to a set of kWays slots, and - * a slot is one atomic word plus the row's bytes. The word is the slot's whole state: + * Set-associative: a row's key (its byte offset in the file) hashes to a set of kWays slots; a slot + * is one atomic word plus the row's bytes. The word is the slot's whole state: * * key << 10 | owner << 2 | state state: EMPTY (word 0), LOADING, READY * - * owner names the thread loading the row, so a thread that meets its own claim again (a row twice in - * one call) does not wait on itself. A reader of a READY slot copies the bytes and then reads the - * word again: a slot's bytes are only rewritten after its word has left READY, so an unchanged word - * means the copy was that row's (a seqlock). The victim in a full set is chosen by CLOCK over - * per-slot reference bits, kept outside the word so that marking a row used never fails another - * reader's check; a LOADING slot is never a victim. + * `owner` is the loading thread, so a thread meeting its own claim (a row twice in one call) does + * not wait on itself. Readers copy a READY slot's bytes and re-read the word: bytes are rewritten + * only after the word leaves READY, so an unchanged word means a valid copy (a seqlock). Victims are + * chosen by CLOCK over per-slot reference bits kept outside the word (so marking a row used never + * fails a reader's check); LOADING slots are never victims. * - * A set's eight words are one 64-byte line. The arrays are anonymous mappings, so a slot costs - * memory once a row lands in it. */ + * A set's eight words are one 64-byte line. The arrays are anonymous mappings, so memory is + * committed only as slots fill. */ struct RowCache { static constexpr int kWays = 8; static constexpr uint64_t kRows = 1ull << 19; @@ -331,7 +291,7 @@ struct RowCache { std::atomic* ref = nullptr; std::atomic* hand = nullptr; uint8_t* data = nullptr; - std::atomic published{0}; /* bumped, and waited on, as a batch of rows lands */ + std::atomic published{0}; /* bumped (and waited on) as each batch lands */ static uint64_t ready(uint64_t key) { return key << 10 | READY; } @@ -345,9 +305,8 @@ struct RowCache { enum Found { HIT, CLAIMED, MINE, THEIRS, NONE }; - /* The slot holding `key` -- READY (HIT), being loaded by this thread (MINE) or by another - * (THEIRS) -- or a slot claimed for it now (CLAIMED), or none when every slot of its set is - * being loaded. */ + /* The slot holding `key`: READY (HIT), loading by this thread (MINE) or another (THEIRS); or a + * slot claimed for it now (CLAIMED); or NONE when every slot of the set is loading. */ Found find_or_claim(uint64_t key, uint64_t me, int64_t* slot) { const uint64_t set = mix(key) & set_mask; const uint64_t s0 = set * kWays; @@ -367,7 +326,7 @@ struct RowCache { if (x == EMPTY && victim < 0) victim = (int64_t)(s0 + w); } /* CLOCK: clear reference bits until a READY slot without one comes round. Two turns - * clear them all, so a victim is found unless every slot is LOADING. */ + * clear them all, so this fails only if every slot is LOADING. */ for (int k = 0; victim < 0 && k < 2 * kWays; ++k) { const uint8_t h = hand[set].load(std::memory_order_relaxed); hand[set].store((uint8_t)((h + 1) % kWays), std::memory_order_relaxed); @@ -384,12 +343,12 @@ struct RowCache { if (victim < 0) { *slot = -1; return NONE; } if (word[victim].compare_exchange_strong(vw, key << 10 | me << 2 | LOADING, std::memory_order_acq_rel)) { - /* The bytes are rewritten only after this; see the seqlock note above. */ + /* Bytes are rewritten only after this (seqlock, above). */ std::atomic_thread_fence(std::memory_order_release); *slot = victim; return CLAIMED; } - /* Another thread changed the set between the look and the claim: look again. */ + /* The set changed between the scan and the claim: retry. */ } } }; @@ -401,8 +360,7 @@ T* anon_array(size_t count) { return p == MAP_FAILED ? nullptr : static_cast(p); } -/* The cache for rows of `n` bytes from `tf`, made on first use and kept for the life of the - * process. */ +/* The cache for `n`-byte rows of `tf`, created on first use and kept for the process lifetime. */ RowCache* row_cache(const TableFile* tf, long long n) { static std::mutex mu; static std::vector> caches; @@ -422,11 +380,31 @@ RowCache* row_cache(const TableFile* tf, long long n) { return caches.back().get(); } -/* This thread's owner tag in a LOADING word: distinct for every thread that gathers, 1..255. */ +/* This thread's owner tag for LOADING words, 1..255, or 0 while 255 live threads hold one (such a + * thread cannot gather through the cache). A thread holds LOADING words only inside a call, so its + * tag is returned for reuse when it exits. */ inline uint64_t owner_tag() { - static std::atomic next{0}; - static thread_local const uint32_t me = ++next; - return me <= 255 ? me : 0; + struct Pool { + std::mutex mu; + std::vector free; + uint32_t next = 0; + }; + static Pool& pool = *new Pool; /* never destroyed: threads may exit after statics are */ + struct Tag { + uint32_t v = 0; + Tag() { + std::lock_guard lk(pool.mu); + if (!pool.free.empty()) { v = pool.free.back(); pool.free.pop_back(); } + else if (pool.next < 255) v = ++pool.next; + } + ~Tag() { + if (!v) return; + std::lock_guard lk(pool.mu); + pool.free.push_back(v); + } + }; + static thread_local const Tag me; + return me.v; } struct ReadRing { @@ -439,11 +417,10 @@ struct ReadRing { io_uring_cqe *cqes = nullptr; void *sq_ring = nullptr, *cq_ring = nullptr; size_t sq_sz = 0, cq_sz = 0, sqe_sz = 0; - int err = 0; /* the errno that stopped init(), for ring_refusal() */ + int err = 0; /* errno from a failed init(), for ring_refusal() */ - /* One thread submits and reaps (SINGLE_ISSUER), and completions are run when it asks for them - * rather than by interrupting it (DEFER_TASKRUN): the ring is thread-local and the thread only - * ever waits for a batch it has just submitted. */ + /* SINGLE_ISSUER and DEFER_TASKRUN: the ring is thread-local, and its thread only waits for + * batches it has just submitted, so completions run when it asks for them. */ bool init() { io_uring_params p; std::memset(&p, 0, sizeof p); @@ -489,9 +466,8 @@ struct ReadRing { } ~ReadRing() { shut(); } - /* The aligned span holding each row of `r[0, count)` (count <= entries) into `bounce`, one span - * every `stride` bytes; submitted with one call that also waits for all of them. Every read - * must return its whole span. */ + /* Reads the aligned span holding each row of `r[0, count)` (count <= entries) into `bounce`, + * 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) { const long long A = tf.align; @@ -531,9 +507,8 @@ struct ReadRing { } }; -/* Thread-local: each rank thread issues its own step, so each gets its own ring and the two never - * contend. Built on that thread's first gather over a file and torn down when the thread exits. */ -/* This thread's ring, made on its first gather. Null if it could not be made, with the errno in +/* This thread's ring, created on its first gather over a file and destroyed at thread exit (each + * rank thread has its own, so they never contend). Null if it could not be made, with the errno in * `*why`. */ inline ReadRing* read_ring(int* why) { static thread_local bool tried = false; @@ -549,10 +524,9 @@ inline ReadRing* read_ring(int* why) { return r.get(); } -/* WHY THIS PROCESS CANNOT MAKE A RING, said in terms of what to change. Docker's default seccomp - * profile is by far the commonest: it answers EPERM to io_uring_setup, and so does the - * kernel.io_uring_disabled sysctl. A kernel too old for SINGLE_ISSUER and DEFER_TASKRUN answers - * EINVAL. */ +/* Explains a ring failure in terms of the fix. EPERM: Docker's default seccomp profile or the + * kernel.io_uring_disabled sysctl. EINVAL: a kernel without SINGLE_ISSUER / DEFER_TASKRUN. + * ENOMEM: the ring's memory refused, e.g. over a locked-memory limit shared with other processes. */ std::string ring_refusal(int e) { std::string s = "libavx: the n-gram table is read through io_uring, and this process cannot " "make a ring (" + std::string(std::strerror(e)) + "). "; @@ -565,11 +539,14 @@ std::string ring_refusal(int e) { else if (e == EINVAL) s += "The ring needs IORING_SETUP_SINGLE_ISSUER and IORING_SETUP_DEFER_TASKRUN, which " "Linux 6.1 added."; + else if (e == ENOMEM) + s += "The kernel refused the ring's memory. It can count against the locked-memory limit " + "(ulimit -l), which every process of this user shares: raise it (LimitMEMLOCK= in a " + "systemd unit, --ulimit memlock=-1 for Docker) or stop other io_uring users."; return s; } -/* Whether this process can make the ring every gathering thread makes: 0, or the errno that - * stopped it. Asked once, by making one and closing it. */ +/* 0 if this process can create a ring, else the errno. Tested once by creating and closing one. */ int ring_errno() { static const int e = [] { ReadRing r; @@ -578,10 +555,9 @@ int ring_errno() { return e; } -/* Read `reads` through the ring, a batch at a time: a row with a slot is copied into the cache and - * published READY; a row without one is decoded straight into its output row. On a failed read, - * every claim not yet published is given up (its word back to EMPTY) so no other thread waits on - * it. */ +/* 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. */ 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) { @@ -622,17 +598,15 @@ int read_and_publish(const TableFile& tf, RowCache& rc, ReadRing& rr, Gather& g, return RAD_OK; } -/* out[m] = the decoded row ids[m] - voff for every m < M, through the cache: find or claim every - * row starting at row `first`, read this thread's claims, wait for the rows other threads are - * reading, then decode everything from the cache. A row whose slot is taken over while it is being - * decoded is read again, without the cache. */ +/* 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) { Gather& g = gather_state(); const uint64_t me = owner_tag(); if (!me) return RAD_E_UNSUPPORTED; - /* `n` is a row's BYTES -- what the cache holds and the file offsets step by -- and `ne` its - * elements, what the decode and a padding row write. */ + /* `n` is a row's bytes (cache and file offsets); `ne` its elements (decode and padding). */ 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; }; @@ -666,9 +640,9 @@ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowG int rs = read_and_publish(tf, rc, rr, g, g.reads, n, ne, decode, lut, q.out, x_ld); if (rs != RAD_OK) return rs; - /* The rows another thread claimed: wait for each to turn READY. `published` is read before the - * words, so a batch that lands after the look changes it and the wait returns at once. A claim - * given up (a failed read) or a slot that moved on is read here instead. */ + /* 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. */ while (!g.waits.empty()) { const uint32_t e = rc.published.load(std::memory_order_acquire); size_t keep = 0; @@ -684,9 +658,8 @@ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowG if (keep) rc.published.wait(e, std::memory_order_acquire); } - /* Every READY row, decoded in one batch: each row's word is read before its bytes and read - * again after all of them (the seqlock above, over the batch), and a row whose word changed in - * between is read again. */ + /* 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. */ g.src.clear(); g.dst.clear(); g.dm.clear(); @@ -716,21 +689,17 @@ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowG return read_and_publish(tf, rc, rr, g, g.reads, n, ne, decode, lut, q.out, x_ld); } -/* ============================== THE READER THAT RUNS A STEP AHEAD ============================== +/* ============================== the reader that runs a step ahead ============================== * - * A prefill chunk gathers `heads` rows a token -- 32,768 at a 2048-token chunk -- and on text the - * cache has not seen, most of them are reads from the file: ~30 ms of random reads a chunk on an - * NVMe drive, during which the step's issuing thread waits in this op and the card idles - * behind it. The NEXT chunk's ids are known a step early (RadBatch::n_ahead, ngram_ids' - * `ahead_ids`), so the call hands them to one process-wide reader thread and returns. The reader - * claims each row the cache lacks, reads it and publishes it READY while the chunk runs on the - * card; the next call finds its rows in the cache, or LOADING under the reader's tag, and waits - * for those exactly as it waits for a row the other rank is reading. + * 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 + * 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. * - * Both ranks hand over the same ids, and the second hand-over of a list the reader already has is - * dropped. A failed read gives its claims up (read_and_publish), and the next call reads those - * rows itself. The reader lives as long as the process: it is never joined, so neither it nor its - * queue is ever destroyed under it. */ + * 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 { const TableFile* tf = nullptr; RowCache* rc = nullptr; @@ -742,7 +711,7 @@ struct AheadReader { std::mutex mu; std::condition_variable cv; std::deque q; - uint64_t last = 0; /* the last id list taken, hashed */ + uint64_t last = 0; /* hash of the last id list accepted */ void run() { Gather& g = gather_state(); @@ -765,7 +734,7 @@ struct AheadReader { if (j.rc->find_or_claim(j.keys[i], me, &slot) == RowCache::CLAIMED) g.reads.push_back({0, j.keys[i], slot}); } - /* Every read has a slot, so nothing is decoded and there is no output to write. */ + /* 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); } @@ -781,7 +750,7 @@ AheadReader* ahead_reader() { return r; } -/* Hand the rows of `q.ahead` -- rows a later call will gather -- to the reader. */ +/* Hands the rows of `q.ahead` (to be gathered by a later call) to the reader. */ 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; } @@ -808,61 +777,9 @@ void read_ahead(const TableFile& tf, RowCache& rc, const avx::RowGather& q) { r->cv.notify_one(); } -/* ============================== THE ROW-ID TRACE ============================== - * - * AVX_PLE_TRACE= appends every row id this op gathers, one per line. Off unless the variable - * is set, and it changes nothing the op computes. Two design questions -- "does the page cache ever - * hit" and "would a userspace cache of 160-byte rows beat it, being 25x denser than a 4 KiB page - * holding one useful row" -- are the SAME question about the n-gram reuse rate, and that is a - * property of the text being generated rather than of this code. This is how to measure it on a - * real generation. - * - * ---- WHAT IT SHOWS ON A PREFILL, WHICH IS WHERE THE ROWS ARE ---------------------------------- - * - * A ~24k-token prefill of prose, both ranks traced, with the rows read through the container's - * mapping rather than the row cache (fault counts from /proc//stat): - * - * 762,432 rows gathered 277,911 distinct 450,608 MINOR faults 2 MAJOR - * - * THE PAGE CACHE HITS ESSENTIALLY ALWAYS once warm. Two major faults over a whole prefill: what a - * read through the mapping pays instead is PAGE-TABLE POPULATION -- a minor fault to map an - * already-cached page, about 1.2 of them per row gathered, at roughly a microsecond each. - * - * THE DENSITY ARGUMENT HOLDS AND IT IS THE WHOLE PRIZE. The distinct rows a prefill wants land on - * 274,887 distinct 4 KiB pages: 1.011 USEFUL ROWS A PAGE, where a page holds 25. So 44.5 MB of - * wanted row bytes is reached through 1.13 GB of page mapping. The packed row cache above keeps - * only the rows touched and pays no mapping at all. - * - * THE REUSE RATE ALONE DOES NOT CARRY IT. Per rank the same prefill gathers 381,216 rows over - * 277,911 distinct ones -- 1.37x, and 86% of rows are wanted exactly once. A cache justified by - * reuse would be a poor bet; one justified by density is a good one, and those are different - * arguments for the same structure. - * - * ---- AND AT DECODE, WHERE THE STEP WAITS ON IT ------------------------------------------------ - * - * Eight varied sequences at a depth-3 verify, one rank traced: a call is 512 rows over ~487 - * distinct ones, and 50.6% of those are rows the generation has never asked for before -- the - * floor for any cache. The rest recur within a short window: a row-granular LRU of 10^5 rows misses - * 57.8%, of 4 x 10^5 rows 51.2%, and larger buys nothing. RowCache -- 2^19 rows, eight ways, CLOCK, - * shared by the ranks -- misses 51.0% on the same trace. - * - * (The even split in the raw trace is the two RANKS, not reuse. Both hash the same ids and gather - * the same rows -- see the replication note in arch/common/rad_block_ple.h, which prices that.) */ -inline std::FILE* trace_file() { - static thread_local bool tried = false; - static thread_local std::FILE* f = nullptr; - if (!tried) { - tried = true; - const char* p = std::getenv("AVX_PLE_TRACE"); - if (p && *p) f = std::fopen(p, "ae"); - } - return f; -} - #else /* not Linux: no file reads; a table is read as memory */ struct TableFile { int fd = -1; }; inline const TableFile* table_file(const uint8_t*, long long, int*) { static TableFile m; return &m; } -inline std::FILE* trace_file() { return nullptr; } #endif } // namespace @@ -872,25 +789,18 @@ int avx::row_gather(const RowGather& q, RowDecode decode) { q.row_bytes < q.n_embd) return RAD_E_INVAL; - /* WHAT THIS OP COSTS HAS TWO REGIMES, and a benchmark that repeats one prompt only ever shows - * the cheap one. Greedy repeat traffic walks the SAME n-gram rows every step, so every row is - * already in the row cache and the call reads nothing. Varied serving makes about half of every - * step's rows new, and the call waits on the NVMe for those. /proc//io says which regime a - * number came from, and AVX_PLE_TRACE records the rows themselves. */ - if (std::FILE* tf = trace_file()) { - for (long long m = 0; m < q.M; ++m) - std::fprintf(tf, "%lld\n", (long long)q.ids[m] - q.voff); - } + /* Cost has two regimes: repeated prompts hit the cache and read nothing, while varied serving + * makes about half of each step's rows new NVMe reads. A benchmark that repeats one prompt + * only measures the first. /proc//io shows which regime applied. */ - /* Every E4M3 code's bf16 at this call's scale, so the decode is a table lookup. The ABI's own - * converters, so the answer is libref's by construction. */ + /* bf16 value of every E4M3 code at this call's scale, built with the ABI's converters (so it + * matches libref); the decode is a table lookup. */ uint16_t lut[256]; for (int b = 0; b < 256; ++b) lut[b] = rad_f32_to_bf16(rad_fp8e4m3_to_f32((uint8_t)b) * q.scale); - /* The rows: through the shared cache from the file behind the table, or, for a table no file - * backs, from the table itself. The caller has refused an id past the table already; an id - * turned into a file offset has to be one. */ + /* File-backed tables go through the shared cache; others are read from memory. The caller + * has already refused ids past the table, which matters once they become file offsets. */ int ferr = RAD_OK; const TableFile* tfile = table_file(q.tab, q.n_vocab * q.row_bytes, &ferr); if (!tfile) return ferr; @@ -909,8 +819,7 @@ 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; - /* The rows a later call will gather, read while the step runs. After this call's own - * rows, so they never compete with them. */ + /* 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; } @@ -933,39 +842,34 @@ int avx::row_gather(const RowGather& q, RowDecode decode) { return RAD_OK; } -/* ============================== THE TABLE'S ENCODING, AND ITS ONE SCALE ============================== +/* ============================== the table's encoding and its one scale ============================== * - * Asked at declare, not by a step (spec §4.3). + * Checked at declare (spec §4.3). * - * The table is E4M3, row-major, with ONE bf16 scale for all of it -- `fp8_e4m3*bf16[*x*]`. That - * is not a simplification of a per-block scheme: it is the shipped format, and the structure of - * the data is why it works. E4M3 carries its own exponent; a row of this table has a dynamic range - * of only about 2.3x; and the error sits on a THREE-OCTAVE PLATEAU in the scale, so any value from - * 2^-13 to 2^-10 gives the same relative L2 error to five digits. A per-row scale would buy a few - * percent of that error for 1.25% more bytes, which is why the format has none. (INT8 in the same - * byte would buy several times more, because it spends all eight bits on resolution rather than - * four on an exponent this data does not need. That is a different format.) + * The table is row-major E4M3 with one bf16 scale for the whole table, `fp8_e4m3*bf16[*x*]` (the + * shipped format). E4M3 carries its own exponent, a row's dynamic range is only ~2.3x, and the + * error is flat across scales from 2^-13 to 2^-10, so a per-row scale would buy a few percent of + * error for 1.25% more bytes. (INT8 in the same byte would do much better; that is a different + * format.) * - * IT IS STORED AS IT IS: the gather reads the canonical rows, and that is what lets the table be - * read in place from the container's mapping -- a relayout would need a copy of 51 GB. So this - * hook only checks, and a table quantised any other way is refused at declare rather than - * gathered as noise. A plain bf16 table -- the checkpoint's own, 102 GB -- is the one other form - * it takes, read the same way with no scale. */ + * The table is stored as is, so it can be read in place from the container's mapping (a relayout + * would copy 51 GB). This hook only validates; any other quantisation is refused. The one other + * accepted form is the checkpoint's plain bf16 table (102 GB), read the same way with no scale. */ namespace { enum { EQ_TOK = 0, EQ_WTE, EQ_SCALE, EQ_X, EQ_AHEAD }; } /* namespace */ +/* RAD_E_UNSUPPORTED is the accepted answer: the plane is stored as is (rad_abi.h, RadLayoutFn). */ extern "C" int avx_layout_ngram(const RadParam* p, int n_p, int operand, const RadEncoding* enc, - const int* sel, const RadTensor* pl, int n, RadLayout* out) { - (void)out; + const int* sel, const RadTensor* pl, int n, RadLayout*) { if (operand != EQ_WTE && operand != EQ_SCALE) return RAD_E_UNSUPPORTED; const long long rows = rad_param_geti(p, n_p, "n_vocab", 0); const long long dim = rad_param_geti(p, n_p, "n_embd", 0); if (rows <= 0 || dim <= 0) return RAD_E_SHAPE; - /* OR THE TABLE AS THE CHECKPOINT SHIPS IT: plain bf16, no scale -- the gather copies its rows - * through the same cache. It has no scale plane, so only the table is ever asked about. */ + /* Or the checkpoint's plain bf16 table, with no scale plane; rows go through the same + * cache. */ if (rad_enc_is(enc, "plain") && enc->n_planes == 1 && enc->plane[0].dtype == RAD_BF16) { if (operand != EQ_WTE) return RAD_E_DTYPE; if (n != 1 || !pl) return RAD_E_SHAPE; @@ -985,14 +889,12 @@ extern "C" int avx_layout_ngram(const RadParam* p, int n_p, int operand, const R return RAD_E_UNSUPPORTED; } -/* ============================== THE INSTANCE: CAN THIS PROCESS READ THE TABLE ============================== +/* ============================== the instance: can this process read the table ============================== * - * Every miss of the gather into bf16 is an io_uring read, and a process that may not make a ring - * fails every step that gathers: the first request fails, after the whole model has loaded, and - * the engine stops. So the instance asks at declare, before a byte is loaded, and refuses with - * the reason. A gather into any other dtype takes the general path, which reads the table as - * memory and makes no ring. rad-convert declares without instances -- it launches nothing -- so a - * sandbox that forbids io_uring still converts the model. */ + * A bf16 gather reads misses through io_uring, so a process that cannot create a ring would fail + * its first request after the whole model loaded. The instance checks at declare and refuses with + * the reason. Gathers into other dtypes read the table as memory and need no ring. rad-convert + * declares without instances, so a sandbox without io_uring can still convert models. */ extern "C" int avx_init_ngram(const RadParam* p, int n_p, int rank, int world_size, void** out) { (void)rank; (void)world_size; diff --git a/libavx/avx_norm.cpp b/libavx/avx_norm.cpp index 06d0632a..79e95665 100644 --- a/libavx/avx_norm.cpp +++ b/libavx/avx_norm.cpp @@ -1,48 +1,28 @@ -/* avx_norm.cpp -- rmsnorm, rmsnorm_add and layernorm. +/* avx_norm.cpp -- rmsnorm, rmsnorm_add, layernorm and the vision position-table adds. * - * ============================== ONE PASS OVER THE ROW, TWICE ============================== + * Each norm is a reduction followed by a scale, so two passes over the row. The row is converted + * to f32 scratch once and both passes read the scratch (libref converts per element, three times + * per element in rmsnorm_add). * - * Every norm here is a REDUCTION followed by a SCALE, which means two passes over the row and no - * way around it: the scale needs a number the whole row contributed to. What can be avoided is - * paying for the dtype conversion twice, and that is the shape of every kernel below -- convert - * the row to f32 ONCE into scratch, reduce out of scratch, scale out of scratch. libref converts - * per element and therefore converts each element three times in rmsnorm_add. + * The reduction is `row_sumsq` (avx_support.cpp), a four-accumulator vector tree. It does not sum + * in libref's ascending-index order, which is why the bf16 tolerance for a norm is 4e-3, not 0. * - * The reduction itself is `row_sumsq` (avx_support.cpp), which is a four-accumulator vector tree. - * That does NOT sum in libref's ascending-index order, and it is the whole reason the bf16 - * tolerance for a norm is 4e-3 rather than zero. Stated here because it is the one thing about - * these kernels that a reader should not have to derive: the arithmetic is the same, the ORDER is - * not, and the order is what a tolerance is for. + * Rounding contracts: + * `wadd` is GemmaRMSNorm's `1 +`, added in f32 after the weight is widened, never to the stored + * bf16 gain (Qwen3.5, Qwen3-Next and Gemma store a zero-centred gain; `1 + w` in bf16 loses 0.3% + * per channel). libr4d's fused norms do the same. * - * ============================== THE TWO ROUNDING CONTRACTS ============================== - * - * `wadd` is GemmaRMSNorm's `1 +`, and it is added to the weight in f32 AFTER the weight has been - * widened -- never to the stored bf16 gain. Qwen3.5, Qwen3-Next and Gemma all store a zero-centred - * gain, and forming `1 + w` in bf16 first loses 0.3% per channel. libr4d's fused norms say the - * same thing; this is the third implementation of that sentence and they agree. - * - * `rmsnorm_add` takes the variance from the UNROUNDED f32 sum and the multiply from the sum AFTER - * it has been narrowed into residual_out. That asymmetry is not an accident of libref's loop: it - * is what vLLM's fused_add_rms_norm does, because the residual has to be stored anyway and - * re-reading it is free, and every fused kernel in this project will do it. An implementation that - * kept f32 throughout would be half an ulp better and would fail against every kernel it is meant - * to certify. + * `rmsnorm_add` takes the variance from the unrounded f32 sum but multiplies the sum after it is + * narrowed into residual_out, as vLLM's fused_add_rms_norm does. Keeping f32 throughout would + * disagree with every fused kernel this is checked against. */ #include "avx_vec.h" #include "avx_common.h" using namespace avx; -/* The gain row, widened once per LAUNCH rather than once per row. - * - * WHY THIS IS WORTH ITS OWN BUFFER: `w` is the same n elements for every one of `rows` rows, so - * converting it inside the row loop converts it `rows` times -- at a 4096-wide bf16 gain and a - * 2048-token prefill chunk that is 8 M pointless conversions. It cannot go in the thread_local - * scratch, because every thread needs it and they would each build their own; it is built once - * into a caller-provided buffer before the parallel region and read by all of them. - * - * `wadd` is folded in HERE, which is also where it is cheapest: once per element of the gain, - * rather than once per element of the output. */ +/* Widen the gain once per launch, not once per row, into a caller buffer built before the + * parallel region and shared by all threads. `wadd` is folded in here, once per gain element. */ static void widen_gain(const RadTensor* w, int64_t n, float wadd, float* out) { const int64_t ws = laststride(w); if (ws == 1) { @@ -63,7 +43,7 @@ static void widen_gain(const RadTensor* w, int64_t n, float wadd, float* out) { AVX_KERNEL(rmsnorm) { if (!a || a->n_t < 3 || !a->t[0].data || !a->t[2].data) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *y = &a->t[2]; - /* An absent gain is one (libref's reading), and `wadd` belongs to a gain. */ + /* An absent gain is 1 (as in libref); `wadd` requires a gain. */ const RadTensor* w = a->t[1].data ? &a->t[1] : nullptr; const int64_t n = p_int(a, "n", w && w->rank ? w->shape[w->rank - 1] : 0); const float eps = p_f32(a, "eps", 1e-6f); @@ -76,7 +56,7 @@ AVX_KERNEL(rmsnorm) { float* gain = (float*)scratch_raw((size_t)n * sizeof(float)); if (w) widen_gain(w, n, wadd, gain); else for (int64_t i = 0; i < n; ++i) gain[i] = 1.0f; - /* `mult` folded into the gain: the row is scaled before its one rounding. */ + /* `mult` is folded into the gain, so the row is scaled before its single rounding. */ const float mult = p_f32(a, "mult", 1.0f); if (mult != 1.0f) for (int64_t i = 0; i < n; ++i) gain[i] *= mult; @@ -99,9 +79,7 @@ AVX_KERNEL(rmsnorm) { } /* ------------------------------------------------------------------ rmsnorm_p */ -/* y = x * rsqrt(mean(x^2) + eps) -- the rmsnorm with no gain. Same one-conversion, two-pass shape - * and same four-accumulator sum of squares as rmsnorm; the only difference is there is no weight - * to widen and no gain to multiply in, because the op has no `w` at all. */ +/* y = x * rsqrt(mean(x^2) + eps): rmsnorm without a gain operand. */ AVX_KERNEL(rmsnorm_p) { if (!rad_args_have(a, 2)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *y = &a->t[1]; @@ -167,19 +145,15 @@ AVX_KERNEL(rmsnorm_add) { float ss = vf_hsum(vf_add(acc0, acc1)); for (; i < n; ++i) { float v = xv[i] + rv[i]; sm[i] = v; ss += v * v; } - /* The residual is written from the UNROUNDED sum... */ + /* The residual is written from the unrounded sum... */ out_row(ro, rowoff(ro, r, n), n, sm); const float s = 1.0f / std::sqrt(ss / (float)n + eps); - /* ...and read back NARROWED for the multiply. Done in registers rather than by re-reading - * the operand: `row_from_f32` then `row_to_f32` over a hot buffer is the same arithmetic - * and does not depend on the store having retired. */ - /* `sr` is reused as the narrowing buffer and that is not a shortcut, it is the ONLY slot - * available: `gain` lives in this thread's scratch_raw arena and calling scratch_raw again - * inside the parallel region would grow that arena, free the old block, and leave every - * other thread reading a dangling `gain`. `sr` is n floats -- 4n bytes -- which holds any - * dtype this operand can be, and `rv` (which may or may not be `sr`, depending on whether - * `residual` was already f32) is dead the moment the sum is formed. */ + /* ...and narrowed for the multiply by a round trip through `sr`, rather than re-reading + * the operand. `sr` is the only free buffer: `gain` lives in the launching thread's + * scratch_raw arena, and another scratch_raw call inside the parallel region could + * reallocate it under the other threads. `sr` holds 4n bytes, enough for any dtype, and + * `rv` (possibly `sr`) is dead once the sum is formed. */ if (ro_dt != RAD_F32) { row_from_f32(ro_dt, sm, sr, n); row_to_f32(ro_dt, sr, sm, n); @@ -196,9 +170,8 @@ AVX_KERNEL(rmsnorm_add) { } /* ------------------------------------------------------------------ layernorm */ -/* y = (x - mean) * rsqrt(var + eps) * w + b, BIASED variance (divide by n), which is what every - * transformer implementation means by layer norm. `b` is optional -- a ViT that dropped its bias - * passes a null operand rather than a zero tensor. */ +/* y = (x - mean) * rsqrt(var + eps) * w + b, with the biased variance (divide by n). `b` is + * optional: a model without a bias passes a null operand. */ AVX_KERNEL(layernorm) { if (a->n_t < 4 || !a->t[0].data || !a->t[1].data || !a->t[3].data) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *w = &a->t[1], *y = &a->t[3]; @@ -210,9 +183,8 @@ AVX_KERNEL(layernorm) { if (rows <= 0 || numel(y) < rows * n || numel(w) < n) return RAD_E_SHAPE; if (b && numel(b) < n) return RAD_E_SHAPE; - /* Both the gain and the bias are launch-invariant, so both are widened once, into one - * allocation so there is a single scratch_raw call live at a time (avx_common.h: a second call - * may reallocate and invalidate the first pointer). */ + /* Gain and bias are widened once, into one allocation: a second scratch_raw call may + * reallocate and invalidate the first pointer. */ float* gb = (float*)scratch_raw((size_t)(2 * n) * sizeof(float)); float* gain = gb; float* bias = gb + n; @@ -230,12 +202,9 @@ AVX_KERNEL(layernorm) { float* sy = scratch_f32_b((size_t)n); const float* v = in_row(x, rowoff(x, r, n), n, sx); - /* TWO PASSES, NOT THE ONE-PASS (sum, sumsq) FORM. The single-pass variance - * E[x^2] - E[x]^2 is one reduction instead of two and is catastrophically worse when the - * mean is large relative to the spread -- which is exactly a post-attention residual. What - * it costs here is one extra read of a row that is in L1 by then; what it would buy is a - * cancellation the tolerance would hide until it did not. libref takes the mean first too, - * so this also keeps the two agreeing for the right reason. */ + /* Two passes (mean, then squared deviations), as in libref. The one-pass E[x^2] - E[x]^2 + * cancels catastrophically when the mean is large relative to the spread, as in a + * post-attention residual; the extra pass reads a row already in L1. */ const float mean = row_sum(v, n) / (float)n; const vf vm = vf_set1(mean); vf acc = vf_zero(); @@ -266,10 +235,17 @@ AVX_KERNEL(layernorm) { } /* ------------------------------------------------------------------ grid_embed */ -/* A learned side x side position table resampled bilinearly to each row's grid (corners aligned, - * edge taps clamped) and added in -- libref's grid_embed, operation for operation: the four taps - * summed in f32 in the same order, rounded to x's dtype, then added and rounded again. One row a - * vision-tower patch, off every step path, so it is written for clarity over lanes. */ +/* `v` rounded to an activation dtype (f32, bf16 or f16), as the position term is stored. */ +static inline float round_act(uint32_t dt, float v) { + if (dt == RAD_BF16) return rad_bf16_to_f32(rad_f32_to_bf16(v)); + if (dt == RAD_F16) return rad_f16_to_f32(rad_f32_to_f16(v)); + return v; +} + +/* Adds a learned side x side position table, resampled bilinearly to each row's grid (corners + * aligned, edge taps clamped). Matches libref's grid_embed operation for operation: four taps + * summed in f32 in the same order, rounded to x's dtype, then added and rounded again. One row per + * vision-tower patch, off the step path, so it is scalar. */ AVX_KERNEL(grid_embed) { if (!rad_args_have(a, 3)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *tab = &a->t[1], *crd = &a->t[2]; @@ -307,8 +283,7 @@ AVX_KERNEL(grid_embed) { for (int kj = 0; kj < 2; ++kj) acc += ldt(tab, rowoff(tab, th[ki] * side + tw[kj], n) + i * ts) * (wh[ki] * ww[kj]); - float pe = acc; - if (x->dtype == RAD_BF16) pe = rad_bf16_to_f32(rad_f32_to_bf16(pe)); + const float pe = round_act(x->dtype, acc); stt(x, xb + i * xs, ldt(x, xb + i * xs) + pe); } } @@ -316,11 +291,11 @@ AVX_KERNEL(grid_embed) { } /* ------------------------------------------------------------------ grid_embed_aa */ -/* The table resampled as torch's F.interpolate(bilinear, align_corners=False, antialias=True) does - * it -- SigLIP2's position embedding -- and added in: libref's grid_embed_aa, operation for - * operation. Per axis a triangle filter on half-pixel centres, widened by the scale when - * shrinking, its taps inside the table normalised; the rows summed first, f32, rounded once - * before the add. A coordinate outside its grid is clamped into it. */ +/* Adds the table resampled as torch's F.interpolate(bilinear, align_corners=False, + * antialias=True) does (SigLIP2's position embedding); matches libref's grid_embed_aa. Per axis: a + * triangle filter on half-pixel centres, widened by the scale when shrinking, with the in-table + * taps normalised. Rows are summed first in f32 and rounded once before the add. Out-of-grid + * coordinates are clamped. */ static void aa_taps(int64_t at, int64_t size, int64_t side, float* w, int64_t* lo, int64_t* cnt) { if (size < 1) size = 1; at = at < 0 ? 0 : (at >= size ? size - 1 : at); @@ -371,8 +346,7 @@ AVX_KERNEL(grid_embed_aa) { row += ldt(tab, rowoff(tab, (h0 + y) * side + w0 + c, n) + i * ts) * ww[c]; acc += row * wh[y]; } - float pe = acc; - if (x->dtype == RAD_BF16) pe = rad_bf16_to_f32(rad_f32_to_bf16(pe)); + const float pe = round_act(x->dtype, acc); stt(x, xb + i * xs, ldt(x, xb + i * xs) + pe); } } diff --git a/libavx/avx_planes.cpp b/libavx/avx_planes.cpp new file mode 100644 index 00000000..e86c016f --- /dev/null +++ b/libavx/avx_planes.cpp @@ -0,0 +1,175 @@ +/* avx_planes.cpp -- decoding the rows of a weight joined over several planes (avx_planes.h), + * compiled once per ISA level. The GEMM's packing, the head rescore and the mixing matrices widen + * such a row to f32 here, scale folded in, where a plain row would go through row_to_f32. */ +#include "avx_vec.h" +#include "avx_common.h" +#include "avx_planes.h" + +namespace avx { +inline namespace AVX_SUFFIX { + +/* n E4M3 or int8 codes, each times `s`. The E4M3 decode is avx_vec.h's reconstruction + * (cvt_fp8e4m3_to_f32), so the code's value is bit-exact before the one rounding of the + * product. */ +void decode_scaled(uint32_t dt, const uint8_t* src, float s, float* dst, int64_t n) { + int64_t i = 0; + if (dt == RAD_I8) { + const int8_t* q = (const int8_t*)src; +#if AVX_LEVEL == 3 + const __m512 vs = _mm512_set1_ps(s); + for (; i + 16 <= n; i += 16) + _mm512_storeu_ps(dst + i, _mm512_mul_ps(_mm512_cvtepi32_ps(_mm512_cvtepi8_epi32( + _mm_loadu_si128((const __m128i*)(q + i)))), vs)); +#elif AVX_LEVEL == 2 + const __m256 vs = _mm256_set1_ps(s); + for (; i + 8 <= n; i += 8) + _mm256_storeu_ps(dst + i, _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_cvtepi8_epi32( + _mm_loadl_epi64((const __m128i*)(q + i)))), vs)); +#endif + for (; i < n; ++i) dst[i] = (float)q[i] * s; + return; + } +#if AVX_LEVEL == 3 + const __m512i c7f = _mm512_set1_epi32(0x7f); + const __m512i cbias = _mm512_set1_epi32(120 << 23); + const __m512 chalf = _mm512_set1_ps(0.0078125f); + const __m512 cnan = _mm512_castsi512_ps(_mm512_set1_epi32(0x7fc00000)); + const __m512 vs = _mm512_set1_ps(s); + for (; i + 16 <= n; i += 16) { + const __m512i b = _mm512_cvtepu8_epi32(_mm_loadu_si128((const __m128i*)(src + i))); + const __m512i mag = _mm512_and_si512(b, c7f); + __m512 f = _mm512_castsi512_ps(_mm512_add_epi32(_mm512_slli_epi32(mag, 20), cbias)); + const __mmask16 sub = _mm512_cmplt_epi32_mask(mag, _mm512_set1_epi32(8)); + f = _mm512_mask_blend_ps(sub, f, + _mm512_mul_ps(_mm512_sub_ps(f, chalf), _mm512_set1_ps(2.0f))); + f = _mm512_mask_blend_ps(_mm512_cmpeq_epi32_mask(mag, c7f), f, cnan); + const __m512i sign = _mm512_slli_epi32(_mm512_and_si512(b, _mm512_set1_epi32(0x80)), 24); + f = _mm512_castsi512_ps(_mm512_or_si512(_mm512_castps_si512(f), sign)); + _mm512_storeu_ps(dst + i, _mm512_mul_ps(f, vs)); + } +#elif AVX_LEVEL == 2 + const __m256i c7f = _mm256_set1_epi32(0x7f); + const __m256i cbias = _mm256_set1_epi32(120 << 23); + const __m256 chalf = _mm256_set1_ps(0.0078125f); + const __m256 cnan = _mm256_castsi256_ps(_mm256_set1_epi32(0x7fc00000)); + const __m256 vs = _mm256_set1_ps(s); + for (; i + 8 <= n; i += 8) { + const __m256i b = _mm256_cvtepu8_epi32(_mm_loadl_epi64((const __m128i*)(src + i))); + const __m256i mag = _mm256_and_si256(b, c7f); + __m256 f = _mm256_castsi256_ps(_mm256_add_epi32(_mm256_slli_epi32(mag, 20), cbias)); + const __m256i sub = _mm256_cmpgt_epi32(_mm256_set1_epi32(8), mag); + f = _mm256_blendv_ps(f, _mm256_mul_ps(_mm256_sub_ps(f, chalf), _mm256_set1_ps(2.0f)), + _mm256_castsi256_ps(sub)); + f = _mm256_blendv_ps(f, cnan, _mm256_castsi256_ps(_mm256_cmpeq_epi32(mag, c7f))); + const __m256i sign = _mm256_slli_epi32(_mm256_and_si256(b, _mm256_set1_epi32(0x80)), 24); + f = _mm256_castsi256_ps(_mm256_or_si256(_mm256_castps_si256(f), sign)); + _mm256_storeu_ps(dst + i, _mm256_mul_ps(f, vs)); + } +#endif + for (; i < n; ++i) dst[i] = avx_fp8e4m3_tab[src[i]] * s; +} + +#if AVX_LEVEL >= 2 +/* Sixteen codes, one per byte of `b` in natural order, each (code - z) * s, into dst. */ +static inline void zp_emit16(__m128i b, int32_t z, float s, float* dst) { +#if AVX_LEVEL == 3 + const __m512i v = _mm512_sub_epi32(_mm512_cvtepu8_epi32(b), _mm512_set1_epi32(z)); + _mm512_storeu_ps(dst, _mm512_mul_ps(_mm512_cvtepi32_ps(v), _mm512_set1_ps(s))); +#else + const __m256i v0 = _mm256_sub_epi32(_mm256_cvtepu8_epi32(b), _mm256_set1_epi32(z)); + const __m256i v1 = _mm256_sub_epi32(_mm256_cvtepu8_epi32(_mm_srli_si128(b, 8)), + _mm256_set1_epi32(z)); + _mm256_storeu_ps(dst, _mm256_mul_ps(_mm256_cvtepi32_ps(v0), _mm256_set1_ps(s))); + _mm256_storeu_ps(dst + 8, _mm256_mul_ps(_mm256_cvtepi32_ps(v1), _mm256_set1_ps(s))); +#endif +} + +/* u5 codes by pdep: eight codes are 40 bits, and one pdep deposits them into the low five bits of + * eight bytes. BMI2 is not in the level's flags (it is a CPUID bit of its own) and is checked at + * run time; Zen 1 and 2 microcode pdep, slowly but correctly. Each 40 bits are read as one + * 8-byte load, masked, except in the last 16 codes, where 3 of those bytes would lie past the + * ones asked for. Returns the codes decoded, a multiple of 16. */ +__attribute__((target("bmi2"))) static int64_t zp_u5_pdep(const uint8_t* src, int64_t n, + int32_t z, float s, float* dst) { + const unsigned long long kLow5 = 0x1f1f1f1f1f1f1f1full, k40 = 0xffffffffffull; + int64_t i = 0; + for (; i + 16 <= n; i += 16) { + const uint8_t* p = src + i / 8 * 5; + uint64_t v0 = 0, v1 = 0; + if (i + 16 < n) { + std::memcpy(&v0, p, 8); + std::memcpy(&v1, p + 5, 8); + v0 &= k40; + v1 &= k40; + } else { + std::memcpy(&v0, p, 5); + std::memcpy(&v1, p + 5, 5); + } + const __m128i b = _mm_set_epi64x((long long)_pdep_u64(v1, kLow5), + (long long)_pdep_u64(v0, kLow5)); + zp_emit16(b, z, s, dst + i); + } + return i; +} +#endif + +/* `n` unsigned codes of `bits` from element k0 of a packed row, each (code - z) * s. Grid groups + * start on a byte for every width here (k0 a multiple of 128); other starts take the bit reader. */ +void decode_zp(const uint8_t* row, int bits, int64_t k0, int64_t n, int32_t z, float s, + float* dst) { + int64_t i = 0; +#if AVX_LEVEL >= 2 + const bool aligned = (k0 * bits) % 8 == 0; + const uint8_t* src = row + (k0 * bits) / 8; + if (aligned && bits == 4) { + const __m128i m4 = _mm_set1_epi8(0x0f); + for (; i + 16 <= n; i += 16) { + const __m128i x = _mm_loadl_epi64((const __m128i*)(src + i / 2)); + const __m128i lo = _mm_and_si128(x, m4); + const __m128i hi = _mm_and_si128(_mm_srli_epi16(x, 4), m4); + zp_emit16(_mm_unpacklo_epi8(lo, hi), z, s, dst + i); + } + } else if (aligned && bits == 2) { + const __m128i m2 = _mm_set1_epi8(0x03); + for (; i + 16 <= n; i += 16) { + int32_t w; + std::memcpy(&w, src + i / 4, 4); + const __m128i x = _mm_cvtsi32_si128(w); + const __m128i p0 = _mm_and_si128(x, m2); + const __m128i p1 = _mm_and_si128(_mm_srli_epi16(x, 2), m2); + const __m128i p2 = _mm_and_si128(_mm_srli_epi16(x, 4), m2); + const __m128i p3 = _mm_and_si128(_mm_srli_epi16(x, 6), m2); + zp_emit16(_mm_unpacklo_epi16(_mm_unpacklo_epi8(p0, p1), _mm_unpacklo_epi8(p2, p3)), + z, s, dst + i); + } + } else if (aligned && bits == 5) { + static const bool bmi2 = __builtin_cpu_supports("bmi2"); + if (bmi2) { + i = zp_u5_pdep(src, n, z, s, dst); + } else { + for (; i + 16 <= n; i += 16) { + alignas(16) uint8_t q[16]; + for (int h = 0; h < 2; ++h) { + uint64_t v = 0; + std::memcpy(&v, src + (i + 8 * h) / 8 * 5, 5); + for (int t = 0; t < 8; ++t) q[8 * h + t] = (uint8_t)((v >> (5 * t)) & 31u); + } + zp_emit16(_mm_load_si128((const __m128i*)q), z, s, dst + i); + } + } + } +#endif + for (; i < n; ++i) dst[i] = (float)((int32_t)rad_load_bits(row, bits, k0 + i) - z) * s; +} + +void scaled_row(const avxp::ScaledRows& sr, int64_t r, int64_t K, float* dst) { + const uint8_t* c = sr.codes.p + r * sr.codes.row_bytes; + const int64_t span = sr.span(K); + for (int64_t c0 = 0; c0 < K; c0 += span) { + const int64_t c1 = c0 + span < K ? c0 + span : K; + decode_scaled(sr.codes.dt, c + c0, sr.scale_at(r, c0), dst + c0, c1 - c0); + } +} + +} /* inline namespace AVX_SUFFIX */ +} /* namespace avx */ diff --git a/libavx/avx_planes.h b/libavx/avx_planes.h new file mode 100644 index 00000000..3b201740 --- /dev/null +++ b/libavx/avx_planes.h @@ -0,0 +1,226 @@ +/* avx_planes.h -- libavx's reading of a weight operand joined over several planes + * (abi/rad_planes.h), and the layout hooks that ask for that form. + * + * The rules are libref's (libref/ref_planes.h), stated again because a plugin links only abi/: + * the same selections are joined and the same ones refused, so the selector can resolve either + * library for a band of an op that reads such a weight, and both read one stored form. A single + * plane is stored as it is, so these rows still read the plain forms a tool describes. + * + * Plain functions with internal linkage, no vector code: avx_registry.cpp (baseline) installs the + * hooks and every ISA level's kernels read the planes through the same helpers. + */ +#ifndef RAD_AVX_PLANES_H +#define RAD_AVX_PLANES_H + +#include "rad_abi.h" +#include "rad_plugin.h" +#include "rad_planes.h" + +#include +#include + +namespace avxp { + +/* ================================================================== reading at launch */ + +/* One plane of a joined operand, as its entry describes it. */ +struct JPlane { + const uint8_t* p = nullptr; + uint32_t dt = 0; + int64_t rows = 0, cols = 0, row_bytes = 0; + int64_t br = 0, bc = 0; /* logical rows x columns one element covers; 0 is all */ + + explicit operator bool() const { return p != nullptr; } + float at(int64_t i, int64_t j) const { return rad_load_f32(p + i * row_bytes, dt, j); } +}; + +static inline bool is_joined(const RadTensor* t) { + return t && t->data && rad_planes_header(t->data) != nullptr; +} + +static inline JPlane jplane(const RadTensor* t, const char* role) { + JPlane v; + const RadPlanesEntry* e = nullptr; + const void* d = t && t->data ? rad_planes_find(t->data, role, &e) : nullptr; + if (!d) return v; + v.p = (const uint8_t*)d; + v.dt = e->dtype; + v.rows = e->rows; + v.cols = e->cols; + v.row_bytes = e->row_bytes; + v.br = e->block[0]; + v.bc = e->block[1]; + return v; +} + +static inline int64_t cdiv_or_1(int64_t n, int64_t b) { return b > 0 ? (n + b - 1) / b : 1; } + +static inline bool float_scale_dt(uint32_t dt) { + return dt == RAD_BF16 || dt == RAD_F16 || dt == RAD_F32; +} + +/* Codes with one scale over [rows, cols]; element (r, c) is code(r, c) * scale covering it, one + * f32 rounding, as the core's affine decoder gives it (libref/ref_planes.h: ScaledRows). */ +struct ScaledRows { + JPlane codes, scale; + /* Columns one scale covers, the whole row for a block extent of 0. */ + int64_t span(int64_t cols) const { return scale.bc > 0 ? scale.bc : cols; } + float scale_at(int64_t r, int64_t c) const { + return scale.at(scale.br > 0 ? r / scale.br : 0, scale.bc > 0 ? c / scale.bc : 0); + } +}; + +static inline int scaled_rows(const RadTensor* t, int64_t rows, int64_t cols, ScaledRows* v) { + const RadPlanesHeader* h = t && t->data ? rad_planes_header(t->data) : nullptr; + if (!h) return RAD_E_INVAL; + v->codes = jplane(t, "codes"); + v->scale = jplane(t, "scale"); + if (h->n_planes != 2 || !v->codes || !v->scale) return RAD_E_DTYPE; + if ((v->codes.dt != RAD_F8E4M3 && v->codes.dt != RAD_I8) || !float_scale_dt(v->scale.dt) || + v->codes.br != 1 || v->codes.bc != 1) + return RAD_E_DTYPE; + if (v->codes.rows != rows || v->codes.cols != cols || + v->scale.rows != cdiv_or_1(rows, v->scale.br) || + v->scale.cols != cdiv_or_1(cols, v->scale.bc)) + return RAD_E_SHAPE; + return RAD_OK; +} + +/* ================================================================== the zero-point grids + * As libref/ref_planes.h: unsigned codes read as (code - zero) * scale, one f16 scale and one + * integer zero per (row, `group` of K) joined in `b_scale`, against one of three activations. */ +enum ZpAct { ZP_I8_ROW = 0, ZP_I8_GROUP = 1, ZP_F16 = 2 }; + +struct ZpGrid { + const char* name; + uint32_t codes; + ZpAct act; +}; + +static inline const ZpGrid* zp_grid(const char* dtype) { + static const ZpGrid kGrids[] = { + { "w2a8", RAD_U2, ZP_I8_ROW }, { "w4a8_asym", RAD_U4, ZP_I8_ROW }, + { "w4a16_asym", RAD_U4, ZP_F16 }, { "w5a16", RAD_U5, ZP_F16 }, + { "w4a8i8_asym", RAD_U4, ZP_I8_GROUP }, { "w5a8i8", RAD_U5, ZP_I8_GROUP }, + }; + if (!dtype) return nullptr; + for (const ZpGrid& g : kGrids) + if (std::strcmp(g.name, dtype) == 0) return &g; + return nullptr; +} + +static inline bool zero_dt(uint32_t dt) { + return dt == RAD_U8 || dt == RAD_U2 || dt == RAD_U4 || dt == RAD_U5; +} + +/* ================================================================== the layout hooks */ + +static inline bool sel_roles(const RadEncoding* enc, const int* sel, int n, const char* r0, + const char* r1) { + if (!enc || !sel || n != 2) return false; + for (int i = 0; i < 2; ++i) + if (sel[i] < 0 || sel[i] >= enc->n_planes) return false; + return std::strncmp(enc->plane[sel[0]].role, r0, RAD_ENC_STR) == 0 && + std::strncmp(enc->plane[sel[1]].role, r1, RAD_ENC_STR) == 0; +} + +static inline bool enc_scaled_rows(const RadEncoding* enc, const int* sel, int n) { + if (!rad_enc_is(enc, "affine") || enc->transform[0] || enc->n_planes != 2) return false; + if (!sel_roles(enc, sel, n, "codes", "scale")) return false; + const RadEncPlane& c = enc->plane[sel[0]]; + const RadEncPlane& s = enc->plane[sel[1]]; + return c.kind == RAD_PLANE_TILED && c.block[0] == 1 && c.block[1] == 1 && + (c.dtype == RAD_F8E4M3 || c.dtype == RAD_I8) && s.kind == RAD_PLANE_TILED && + float_scale_dt(s.dtype); +} + +static inline int layout_scaled(int operand, int rows_opd, int rows_opd2, const RadEncoding* enc, + const int* sel, const RadTensor* planes, int n, RadLayout* out) { + if (n < 2 || (operand != rows_opd && operand != rows_opd2)) return RAD_E_UNSUPPORTED; + if (!enc_scaled_rows(enc, sel, n)) return RAD_E_DTYPE; + return rad_planes_layout(enc, sel, planes, n, out); +} + +/* logits_gemm and logit_rerank: the head is operand 1 of both. */ +static inline int avx_layout_head(const RadParam*, int, int operand, const RadEncoding* enc, + const int* sel, const RadTensor* planes, int n, RadLayout* out) { + return layout_scaled(operand, 1, -1, enc, sel, planes, n, out); +} + +/* hc_read: mix_down and mix_up (operands 2 and 3). */ +static inline int avx_layout_hc(const RadParam*, int, int operand, const RadEncoding* enc, + const int* sel, const RadTensor* planes, int n, RadLayout* out) { + return layout_scaled(operand, 2, 3, enc, sel, planes, n, out); +} + +/* mtp_enter: fc_h and fc_e (operands 4 and 5). */ +static inline int avx_layout_mtp(const RadParam*, int, int operand, const RadEncoding* enc, + const int* sel, const RadTensor* planes, int n, RadLayout* out) { + return layout_scaled(operand, 4, 5, enc, sel, planes, n, out); +} + +/* gemm_nt_q: `b_scale` (operand 3) as the scale and zero of the grid `dtype` names. */ +static inline int avx_layout_gemm_q(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* planes, int n, RadLayout* out) { + if (n < 2 || operand != 3) return RAD_E_UNSUPPORTED; + const ZpGrid* zg = zp_grid(rad_param_gets(p, n_p, "dtype", nullptr)); + const long long group = rad_param_geti(p, n_p, "group", 0); + if (!zg || group <= 0 || !rad_enc_is(enc, "affine")) return RAD_E_DTYPE; + if (enc->transform[0] && std::strncmp(enc->transform, "givens", RAD_ENC_STR) != 0) + return RAD_E_DTYPE; + if (!sel_roles(enc, sel, n, "scale", "zero") || enc->n_planes < 3) return RAD_E_DTYPE; + const RadEncPlane& c = enc->plane[0]; + const RadEncPlane& s = enc->plane[sel[0]]; + const RadEncPlane& z = enc->plane[sel[1]]; + if (std::strncmp(c.role, "codes", RAD_ENC_STR) != 0 || c.dtype != zg->codes || + c.block[0] != 1 || c.block[1] != 1) + return RAD_E_DTYPE; + if (s.kind != RAD_PLANE_TILED || s.dtype != RAD_F16 || s.block[0] != 1 || s.block[1] != group || + z.kind != RAD_PLANE_TILED || !zero_dt(z.dtype) || z.block[0] != 1 || z.block[1] != group) + return RAD_E_DTYPE; + return rad_planes_layout(enc, sel, planes, n, out); +} + +template +static int avx_relayout_planes(const RadParam* p, int n_p, int operand, const RadEncoding* enc, + const int* sel, const RadTensor* planes, int n, void* dst, + int64_t dst_bytes) { + RadLayout lay{}; + const int st = L(p, n_p, operand, enc, sel, planes, n, &lay); + if (st != RAD_OK) return st; + return rad_planes_relayout(enc, sel, planes, n, dst, dst_bytes); +} + +template +static int avx_unrelayout_planes(const RadParam* p, int n_p, int operand, const RadEncoding* enc, + const int* sel, const void* src, int64_t src_bytes, + const RadTensor* planes, int n) { + RadLayout lay{}; + const int st = L(p, n_p, operand, enc, sel, planes, n, &lay); + if (st != RAD_OK) return st; + return rad_planes_unrelayout(enc, sel, src, src_bytes, planes, n); +} + +} /* namespace avxp */ + +#ifdef AVX_LEVEL +/* The per-level decoders (avx_planes.cpp). */ +namespace avx { +inline namespace AVX_SUFFIX { + +/* n E4M3 or int8 codes, each times `s`: the code's exact value, then one rounding. */ +void decode_scaled(uint32_t dt, const uint8_t* src, float s, float* dst, int64_t n); + +/* `n` unsigned codes of `bits` from element k0 of a packed row, each (code - z) * s. */ +void decode_zp(const uint8_t* row, int bits, int64_t k0, int64_t n, int32_t z, float s, + float* dst); + +/* Row `r` of a ScaledRows weight, `K` wide, as f32. */ +void scaled_row(const avxp::ScaledRows& sr, int64_t r, int64_t K, float* dst); + +} /* inline namespace AVX_SUFFIX */ +} /* namespace avx */ +#endif + +#endif /* RAD_AVX_PLANES_H */ diff --git a/libavx/avx_qsa.cpp b/libavx/avx_qsa.cpp new file mode 100644 index 00000000..fb869202 --- /dev/null +++ b/libavx/avx_qsa.cpp @@ -0,0 +1,873 @@ +/* avx_qsa.cpp -- the QSA indexer's score, selection, tail store and work list, and DFlash2's + * grouped convolution (docs/OPS.md, "Sparse attention (QSA)" and "Draft heads"). + * + * libref/ref_qsa.cpp is the contract: the same refusals in the same order, the same elements left + * unwritten and the same order of every output. `cu` holds absolute row indices; a row belongs to + * the first sequence whose span holds it, and cu[0] need not be 0. + * + * qsa_score A tile of up to kQT query rows of one sequence is scored against VF_N block keys + * at a time. Each (row, head, block) dot is a vector accumulator over the head's + * lanes, and a fixed transpose-and-add tree turns VF_N of them into one vector with + * one block per lane, so the relu, the sum over heads and the store are vector work. + * The keys are read once per tile, which at decode is once per sequence. The dots + * sum in vector order (libref's order at the scalar level); the heads in order. + * qsa_select Linear time per row: an order key per block (the bits of max(score, 0) plus one, + * 0 for a dead block), a histogram of the keys' top bits, an exact select among the + * keys in the bin that holds the topk-th largest, and one emitting pass in block + * order. The ids match libref's byte for byte. + * qsa_tail_store, qsa_work Row copies through f32, as libref copies, so every value lands + * with the bits libref's would. + * dflash_conv Channels across lanes, in blocks of columns that walk their rows, so a block's base + * kernel and its slice of the row above stay in L1; one pass in registers a row. + */ +#include "avx_vec.h" +#include "avx_common.h" + +#include +#include +#include + +using namespace avx; + +namespace { + +int64_t cu_at(const RadTensor* cu, int64_t i) { return ldi(cu, offlin(cu, i)); } + +/* Offset of entry `i` of a rank-1 operand, or of column 0 of row `i` of a rank-2 one (a state + * index row's committed slot). */ +int64_t col0(const RadTensor* t, int64_t i) { + return t->rank >= 2 ? i * t->stride[0] : offlin(t, i); +} + +/* Whether the dimensions after the first are dense, so a row of a paged store is + * `numel / shape[0]` contiguous values from `row * stride[0]`. */ +bool rows_dense(const RadTensor* t) { + int64_t acc = 1; + for (int i = (int)t->rank - 1; i >= 1; --i) { + if (t->shape[i] != 1 && t->stride[i] != acc) return false; + acc *= t->shape[i]; + } + return true; +} + +/* seq[m] for every m < M: the first sequence whose cu span holds row m, or `none` (libref's + * seq_holding), filled from the spans instead of scanning every span for every row. */ +void seq_rows(const RadTensor* cu, int64_t n_seq, int64_t M, int64_t none, int64_t* seq) { + const int64_t unset = INT64_MIN; + std::fill(seq, seq + M, unset); + for (int64_t s = 0; s < n_seq; ++s) { + const int64_t lo = std::max(cu_at(cu, s), 0); + const int64_t hi = std::min(cu_at(cu, s + 1), M); + for (int64_t m = lo; m < hi; ++m) + if (seq[m] == unset) seq[m] = s; + } + for (int64_t m = 0; m < M; ++m) + if (seq[m] == unset) seq[m] = none; +} + +/* `n` elements of `t` from `base`, `st` apart, as f32, and back. Whole-byte dtypes convert a row + * at a time; the conversions are libref's bit for bit either way. */ +void widen(const RadTensor* t, int64_t base, int64_t st, int64_t n, float* dst) { + if (st == 1 && rad_dtype_bits(t->dtype) >= 8) { + row_to_f32(t->dtype, byte_at(t->data, t->dtype, base), dst, n); + return; + } + for (int64_t i = 0; i < n; ++i) dst[i] = ldt(t, base + i * st); +} + +void narrow(const RadTensor* t, int64_t base, int64_t st, int64_t n, const float* src) { + if (st == 1 && rad_dtype_bits(t->dtype) >= 8) { + row_from_f32(t->dtype, src, (void*)byte_at(t->data, t->dtype, base), n); + return; + } + for (int64_t i = 0; i < n; ++i) stt(t, base + i * st, src[i]); +} + +/* ================================================================== qsa_score */ + +/* Query rows a tile: the key history is read once per tile, and kQT * heads rows of f32 queries + * stay in L1 beside VF_N widened keys (16 KiB and 8 KiB at Flash-Next's 4 heads of 128). */ +enum { kQT = 8 }; +/* Blocks a work unit. Units are ordered chunk-major and handed out in order, so the threads work + * through one chunk's keys across the tiles of a prefill chunk while they are in L3. */ +enum { kChunk = 256 }; +/* Blocks the software prefetch runs ahead of the keys being widened. */ +enum { kAhead = 32 }; + +/* lane_sums leaves the total of accumulator slot i in lane kSlot[i]; slot i is loaded with block + * kSlot[i] of the group, so lane j holds block j. */ +#if AVX_LEVEL == 3 +const int kSlot[16] = { 0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15 }; +#elif AVX_LEVEL >= 1 +const int kSlot[8] = { 0, 4, 1, 5, 2, 6, 3, 7 }; +#else +const int kSlot[1] = { 0 }; +#endif + +/* The VF_N horizontal sums of a[0 .. VF_N), one a lane, by a fixed tree: each level halves every + * vector and adds pairs of them, so a level costs one vector of adds per output vector. */ +static inline vf lane_sums(const vf* a) { +#if AVX_LEVEL == 3 + __m512 s[8], t[4]; + for (int i = 0; i < 8; ++i) + s[i] = _mm512_add_ps(_mm512_shuffle_f32x4(a[2 * i], a[2 * i + 1], 0x44), + _mm512_shuffle_f32x4(a[2 * i], a[2 * i + 1], 0xEE)); + for (int i = 0; i < 4; ++i) + t[i] = _mm512_add_ps(_mm512_shuffle_f32x4(s[2 * i], s[2 * i + 1], 0x88), + _mm512_shuffle_f32x4(s[2 * i], s[2 * i + 1], 0xDD)); + const __m512 u0 = _mm512_add_ps(_mm512_shuffle_ps(t[0], t[1], 0x44), + _mm512_shuffle_ps(t[0], t[1], 0xEE)); + const __m512 u1 = _mm512_add_ps(_mm512_shuffle_ps(t[2], t[3], 0x44), + _mm512_shuffle_ps(t[2], t[3], 0xEE)); + return _mm512_add_ps(_mm512_shuffle_ps(u0, u1, 0x88), _mm512_shuffle_ps(u0, u1, 0xDD)); +#elif AVX_LEVEL >= 1 + __m256 s[4]; + for (int i = 0; i < 4; ++i) + s[i] = _mm256_add_ps(_mm256_permute2f128_ps(a[2 * i], a[2 * i + 1], 0x20), + _mm256_permute2f128_ps(a[2 * i], a[2 * i + 1], 0x31)); + const __m256 t0 = _mm256_add_ps(_mm256_shuffle_ps(s[0], s[1], 0x44), + _mm256_shuffle_ps(s[0], s[1], 0xEE)); + const __m256 t1 = _mm256_add_ps(_mm256_shuffle_ps(s[2], s[3], 0x44), + _mm256_shuffle_ps(s[2], s[3], 0xEE)); + return _mm256_add_ps(_mm256_shuffle_ps(t0, t1, 0x88), _mm256_shuffle_ps(t0, t1, 0xDD)); +#else + return a[0]; +#endif +} + +/* Lane j: the dot of the query row `q` with block key j of the group in `kf` (slot order, rows + * `np` apart). `np` is a multiple of 16 and the tails of both rows are zero. */ +static inline vf dot_group(const float* q, const float* kf, int64_t np) { + vf acc[VF_N]; + for (int i = 0; i < VF_N; ++i) acc[i] = vf_zero(); + for (int64_t c = 0; c < np; c += VF_N) { + const vf vq = vf_load(q + c); +#pragma GCC unroll 16 + for (int i = 0; i < VF_N; ++i) acc[i] = vf_fma(vq, vf_load(kf + i * np + c), acc[i]); + } + return lane_sums(acc); +} + +struct ScoreTile { int64_t m0, rows, s, nbs; }; + +struct ScoreJob { + const RadTensor *q, *bk, *bt, *o; + int64_t n, np, heads; + int64_t q_rs, q_cs, pg_rs, bt_rs, bt_cs, o_rs, o_cs; + int64_t esz; /* bytes an element of bk, 0 for a packed dtype */ + float rn; +}; + +/* Scores blocks [b0, b1) of one tile. */ +static void score_unit(const ScoreJob& j, const ScoreTile& t, int64_t b0, int64_t b1) { + const int64_t n = j.n, np = j.np, R = t.rows * j.heads; + float* qf = scratch_f32((size_t)(R * np)); + float* kf = scratch_f32_b((size_t)(VF_N * np)); + for (int64_t r = 0; r < R; ++r) { + const int64_t m = t.m0 + r / j.heads, h = r % j.heads; + float* d = qf + r * np; + widen(j.q, m * j.q_rs + h * n * j.q_cs, j.q_cs, n, d); + std::fill(d + n, d + np, 0.0f); + } + for (int i = 0; i < VF_N; ++i) std::fill(kf + i * np + n, kf + (i + 1) * np, 0.0f); + const bool f32_out = j.o->dtype == RAD_F32; + const uint8_t* bkb = (const uint8_t*)j.bk->data; + const int64_t bt_row = t.s * j.bt_rs; + alignas(64) float lanes[VF_N]; + /* Software prefetch kAhead blocks ahead of the group being widened, from the unit's first + * block: a block table need not be in page order, so the hardware prefetcher cannot follow + * it, and a unit's head would otherwise wait on DRAM. */ + int64_t pf = b0; + auto prefetch_to = [&](int64_t lim) { + for (lim = std::min(lim, b1); pf < lim; ++pf) { + const int64_t p = ldi(j.bt, bt_row + pf * j.bt_cs); + if (p < 0 || j.esz == 0) continue; + const uint8_t* at = bkb + p * j.pg_rs * j.esz; + for (int64_t off = 0; off < n * j.esz; off += 64) __builtin_prefetch(at + off); + } + }; + prefetch_to(b0 + kAhead); + for (int64_t g = b0; g < b1; g += VF_N) { + const int nv = (int)std::min(VF_N, b1 - g); + prefetch_to(g + VF_N + kAhead); + int64_t pg[VF_N]; + for (int L = 0; L < VF_N; ++L) + pg[L] = L < nv ? ldi(j.bt, bt_row + (g + L) * j.bt_cs) : -1; + for (int i = 0; i < VF_N; ++i) { + const int64_t p = pg[kSlot[i]]; + float* d = kf + i * np; + if (p >= 0) widen(j.bk, p * j.pg_rs, 1, n, d); + else std::fill(d, d + n, 0.0f); + } + for (int64_t qi = 0; qi < t.rows; ++qi) { + vf s = vf_zero(); + for (int64_t h = 0; h < j.heads; ++h) + s = vf_add(s, vf_max(dot_group(qf + (qi * j.heads + h) * np, kf, np), vf_zero())); + vf_store(lanes, vf_div(s, vf_set1(j.rn))); + const int64_t ob = (t.m0 + qi) * j.o_rs + g * j.o_cs; + if (f32_out) { + float* o = (float*)j.o->data; + for (int L = 0; L < nv; ++L) o[ob + L * j.o_cs] = pg[L] < 0 ? -INFINITY : lanes[L]; + } else { + for (int L = 0; L < nv; ++L) + stt(j.o, ob + L * j.o_cs, pg[L] < 0 ? -INFINITY : lanes[L]); + } + } + } +} + +} /* namespace */ + +/* ------------------------------------------------------------------ qsa_score */ +/* score[m][b] = (sum over heads h of relu(q[m][h] . bk[bt[seq(m)][b]])) / sqrt(n) for b below + * min(nc[seq], the table's width, the score plane's width); a negative page id scores -inf. + * Columns past the bound, and rows no sequence holds, are not written. */ +AVX_KERNEL(qsa_score) { + if (!rad_args_have(a, 6)) return RAD_E_INVAL; + const RadTensor *q = &a->t[0], *bk = &a->t[1], *bt = &a->t[2], *cu = &a->t[3]; + const RadTensor *nc = &a->t[4], *o = &a->t[5]; + const int64_t n = p_int(a, "n", 0), heads = p_int(a, "heads", 0); + if (n <= 0 || heads <= 0) return RAD_E_SHAPE; + if (bt->rank != 2 || o->rank != 2 || bk->rank < 2) return RAD_E_SHAPE; + const int64_t M = o->shape[0], nb = std::min(bt->shape[1], o->shape[1]); + const int64_t n_seq = numel(cu) - 1, pages = bk->shape[0]; + if (M <= 0 || nb <= 0 || n_seq <= 0 || pages <= 0) return RAD_E_SHAPE; + if (bt->shape[0] < n_seq || numel(nc) < n_seq || rows_of(q, heads * n) < M) return RAD_E_SHAPE; + if (numel(bk) / pages != n) return RAD_E_SHAPE; + if (!rows_dense(bk)) return RAD_E_STRIDE; + const int64_t bt_rs = bt->stride[0], bt_cs = bt->stride[1]; + /* Every page id the launch will read must name a page of `bk`. */ + for (int64_t s = 0; s < n_seq; ++s) { + const int64_t nbs = std::min(ldi(nc, offlin(nc, s)), nb); + for (int64_t b = 0; b < nbs; ++b) + if (ldi(bt, s * bt_rs + b * bt_cs) >= pages) return RAD_E_INVAL; + } + + ScoreJob j{}; + j.q = q; j.bk = bk; j.bt = bt; j.o = o; + j.n = n; j.np = (n + 15) & ~(int64_t)15; j.heads = heads; + j.q_rs = row_stride(q, heads * n); j.q_cs = laststride(q); + j.pg_rs = bk->stride[0]; j.bt_rs = bt_rs; j.bt_cs = bt_cs; + j.o_rs = o->stride[0]; j.o_cs = o->stride[1]; + j.esz = rad_dtype_bits(bk->dtype) / 8; + j.rn = std::sqrt((float)n); + + /* Tiles: runs of up to kQT consecutive rows of one sequence. One allocation, as a second + * scratch_raw call could move the first. */ + int64_t* seq = (int64_t*)scratch_raw((size_t)M * (sizeof(int64_t) + sizeof(ScoreTile)) + 64); + ScoreTile* tiles = (ScoreTile*)(seq + M); + seq_rows(cu, n_seq, M, -1, seq); + int64_t nt = 0, widest = 0, work = 0; + for (int64_t m = 0; m < M;) { + const int64_t s = seq[m]; + int64_t e = m + 1; + while (e < M && e - m < kQT && seq[e] == s) ++e; + if (s >= 0) { + const int64_t nbs = std::min(ldi(nc, offlin(nc, s)), nb); + if (nbs > 0) { + tiles[nt++] = ScoreTile{ m, e - m, s, nbs }; + widest = std::max(widest, nbs); + work += (e - m) * heads * n * nbs; + } + } + m = e; + } + const int64_t nch = (widest + kChunk - 1) / kChunk, units = nt * nch; + /* Dynamic: a unit's arithmetic does not depend on the thread that runs it, so the output is + * the same bytes for any schedule, and a preempted thread does not hold up the rest. */ +#ifdef _OPENMP + AVX_PRAGMA(omp parallel for schedule(dynamic, 1) if(work >= ((int64_t)1 << 19) || + avx_par_forced()) num_threads(avx_team_size())) +#endif + for (int64_t u = 0; u < units; ++u) { + const ScoreTile& t = tiles[u % nt]; + const int64_t b0 = (u / nt) * kChunk, b1 = std::min(b0 + kChunk, t.nbs); + if (b0 < b1) score_unit(j, t, b0, b1); + } + return RAD_OK; +} + +/* ================================================================== qsa_select */ +namespace { + +/* Bins of the first selection pass: the top 10 bits of a key, which is below 2^31. */ +enum { kBins = 1024, kBinShift = 21 }; + +struct SelJob { + const RadTensor *sc, *bt, *nc, *po, *se, *ns, *su; + const int64_t* seq; + int64_t nb, topk, ratio; + int64_t s_rs, s_cs, bt_rs, bt_cs, o_rs, o_cs; +}; + +/* The order key of each of the row's first `n` blocks: bits(max(score, 0)) + 1 for a live block + * (page id >= 0 and score > -1e30), 0 for a dead one. Non-negative floats order as their bits, so + * keys order as libref's values; max(score, 0) maps -0 to +0 as libref's `v > 0 ? v : 0` does. + * Returns the live count. */ +static int64_t order_keys(const SelJob& j, int64_t m, int64_t s, int64_t n, uint32_t* key) { + const int64_t sb = m * j.s_rs, bb = s * j.bt_rs; + int64_t live = 0, b = 0; +#if AVX_LEVEL >= 2 + if (j.sc->dtype == RAD_F32 && j.s_cs == 1 && j.bt->dtype == RAD_I32 && j.bt_cs == 1) { + const float* v = (const float*)j.sc->data + sb; + const int32_t* p = (const int32_t*)j.bt->data + bb; +#if AVX_LEVEL == 3 + const __m512 lo = _mm512_set1_ps(-1e30f); + const __m512i one = _mm512_set1_epi32(1); + for (; b + 16 <= n; b += 16) { + const __m512 x = _mm512_loadu_ps(v + b); + const __m512i pg = _mm512_loadu_si512((const void*)(p + b)); + const __mmask16 lv = _mm512_cmp_ps_mask(x, lo, _CMP_GT_OQ) & + _mm512_cmpge_epi32_mask(pg, _mm512_setzero_si512()); + const __m512i k = _mm512_add_epi32( + _mm512_castps_si512(_mm512_max_ps(x, _mm512_setzero_ps())), one); + _mm512_storeu_si512((void*)(key + b), _mm512_maskz_mov_epi32(lv, k)); + live += __builtin_popcount((unsigned)lv); + } +#else + const __m256 lo = _mm256_set1_ps(-1e30f); + const __m256i one = _mm256_set1_epi32(1), neg = _mm256_set1_epi32(-1); + for (; b + 8 <= n; b += 8) { + const __m256 x = _mm256_loadu_ps(v + b); + const __m256i pg = _mm256_loadu_si256((const __m256i*)(p + b)); + const __m256 lv = _mm256_and_ps(_mm256_cmp_ps(x, lo, _CMP_GT_OQ), + _mm256_castsi256_ps(_mm256_cmpgt_epi32(pg, neg))); + const __m256i k = _mm256_add_epi32( + _mm256_castps_si256(_mm256_max_ps(x, _mm256_setzero_ps())), one); + _mm256_storeu_si256((__m256i*)(key + b), + _mm256_and_si256(k, _mm256_castps_si256(lv))); + live += __builtin_popcount((unsigned)_mm256_movemask_ps(lv)); + } +#endif + } +#endif + for (; b < n; ++b) { + const float v = ldt(j.sc, sb + b * j.s_cs); + if (ldi(j.bt, bb + b * j.bt_cs) < 0 || !(v > -1e30f)) { key[b] = 0; continue; } + const float x = v > 0.0f ? v : 0.0f; + uint32_t u; + std::memcpy(&u, &x, 4); + key[b] = u + 1u; + ++live; + } + return live; +} + +/* The topk-th largest key of a row with more than `topk` live keys, and how many keys are above + * it. A histogram of the top bits finds the bin holding it; the keys in that bin are gathered and + * the exact value taken among them. `cand` holds up to n keys. */ +static uint32_t threshold(const uint32_t* key, int64_t n, int64_t topk, uint32_t* hist, + uint32_t* cand, int64_t* above_out) { + /* Four interleaved histograms, so runs of keys in one bin do not serialise on one counter. */ + std::memset(hist, 0, 4 * kBins * sizeof(uint32_t)); + int64_t b = 0; + for (; b + 4 <= n; b += 4) { + ++hist[0 * kBins + (key[b] >> kBinShift)]; + ++hist[1 * kBins + (key[b + 1] >> kBinShift)]; + ++hist[2 * kBins + (key[b + 2] >> kBinShift)]; + ++hist[3 * kBins + (key[b + 3] >> kBinShift)]; + } + for (; b < n; ++b) ++hist[key[b] >> kBinShift]; + for (int i = 0; i < kBins; ++i) + hist[i] += hist[kBins + i] + hist[2 * kBins + i] + hist[3 * kBins + i]; + /* Bin 0 is never counted: it is the last one left, and holds the dead keys (0) beside the + * smallest live ones, which the gather below tells apart. */ + int64_t above = 0; + int bin = kBins - 1; + for (; bin > 0; --bin) { + if (above + (int64_t)hist[bin] >= topk) break; + above += hist[bin]; + } + /* The keys of the bin, i.e. in [lo, hi], with key 0 (dead) left out of bin 0. Few keys fall in + * one bin, so the vector forms test a vector and walk only its hits. */ + const uint32_t lo = std::max((uint32_t)bin << kBinShift, 1u); + const uint32_t hi = (((uint32_t)bin + 1u) << kBinShift) - 1u; + int64_t nc = 0; + b = 0; +#if AVX_LEVEL == 3 + const __m512i vlo = _mm512_set1_epi32((int)lo), vhi = _mm512_set1_epi32((int)hi); + for (; b + 16 <= n; b += 16) { + const __m512i k = _mm512_loadu_si512((const void*)(key + b)); + const __mmask16 in = _mm512_cmpge_epu32_mask(k, vlo) & _mm512_cmple_epu32_mask(k, vhi); + _mm512_mask_compressstoreu_epi32((void*)(cand + nc), in, k); + nc += __builtin_popcount((unsigned)in); + } +#elif AVX_LEVEL == 2 + /* Keys are below 2^31, so the signed compares order them. */ + const __m256i vlo = _mm256_set1_epi32((int)lo - 1), vhi = _mm256_set1_epi32((int)hi + 1); + for (; b + 8 <= n; b += 8) { + const __m256i k = _mm256_loadu_si256((const __m256i*)(key + b)); + const __m256i in = _mm256_and_si256(_mm256_cmpgt_epi32(k, vlo), _mm256_cmpgt_epi32(vhi, k)); + unsigned hit = (unsigned)_mm256_movemask_ps(_mm256_castsi256_ps(in)); + while (hit) { + cand[nc++] = key[b + __builtin_ctz(hit)]; + hit &= hit - 1; + } + } +#endif + for (; b < n; ++b) { + const uint32_t k = key[b]; + if (k >= lo && k <= hi) cand[nc++] = k; + } + const int64_t want = topk - above; /* 1 .. nc */ + std::nth_element(cand, cand + (want - 1), cand + nc, std::greater()); + const uint32_t thr = cand[want - 1]; + for (int64_t i = 0; i < nc; ++i) above += cand[i] > thr; + *above_out = above; + return thr; +} + +/* Writes the page ids of the keys above `thr` in block order at row[0 .. gt), then the first + * `ties` keys equal to it in block order at row[gt ..). */ +static void emit(const SelJob& j, const uint32_t* key, int64_t n, int64_t s, uint32_t thr, + int64_t gt, int64_t ties, int32_t* row) { + const int64_t bb = s * j.bt_rs; + int64_t og = 0, ot = 0, b = 0; + auto one = [&](int64_t i) { + const uint32_t k = key[i]; + if (k > thr) row[og++] = (int32_t)ldi(j.bt, bb + i * j.bt_cs); + else if (k == thr && ot < ties) row[gt + ot++] = (int32_t)ldi(j.bt, bb + i * j.bt_cs); + }; +#if AVX_LEVEL == 3 + const __m512i vt = _mm512_set1_epi32((int)thr); + for (; b + 16 <= n && (og < gt || ot < ties); b += 16) { + const __m512i k = _mm512_loadu_si512((const void*)(key + b)); + unsigned hit = (unsigned)(_mm512_cmpge_epu32_mask(k, vt)); + while (hit) { + one(b + __builtin_ctz(hit)); + hit &= hit - 1; + } + } +#elif AVX_LEVEL == 2 + /* Keys are below 2^31, so the signed compare orders them. */ + const __m256i vt = _mm256_set1_epi32((int)thr - 1); + for (; b + 8 <= n && (og < gt || ot < ties); b += 8) { + const __m256i k = _mm256_loadu_si256((const __m256i*)(key + b)); + unsigned hit = (unsigned)_mm256_movemask_ps(_mm256_castsi256_ps(_mm256_cmpgt_epi32(k, vt))); + while (hit) { + one(b + __builtin_ctz(hit)); + hit &= hit - 1; + } + } +#endif + for (; b < n && (og < gt || ot < ties); ++b) one(b); +} + +static void select_row(const SelJob& j, int64_t m) { + const int64_t s = j.seq[m]; + const int64_t p = ldi(j.po, offlin(j.po, m)); + const int64_t n = std::min(std::min(ldi(j.nc, offlin(j.nc, s)), j.nb), (p + 1) / j.ratio); + const int64_t topk = j.topk; + uint32_t* key = (uint32_t*)scratch_f32((size_t)std::max(n, 1)); + int32_t* row = (int32_t*)scratch_f32_b((size_t)(4 * kBins + topk + 1)); + uint32_t* hist = (uint32_t*)(row + topk + 1); + const int64_t live = n > 0 ? order_keys(j, m, s, n, key) : 0; + int64_t out = 0; + if (live <= topk) { + const int64_t bb = s * j.bt_rs; + for (int64_t b = 0; b < n && out < live; ++b) + if (key[b]) row[out++] = (int32_t)ldi(j.bt, bb + b * j.bt_cs); + } else { + uint32_t* cand = (uint32_t*)scratch_f32_c((size_t)n); + int64_t gt = 0; + const uint32_t thr = threshold(key, n, topk, hist, cand, >); + emit(j, key, n, s, thr, gt, topk - gt, row); + out = topk; + } + if (n < j.nb && (p + 1) % j.ratio != 0) { + const int64_t part = ldi(j.bt, s * j.bt_rs + n * j.bt_cs); + if (part >= 0) row[out++] = (int32_t)part; + } + for (int64_t i = out; i <= topk; ++i) row[i] = -1; + const int64_t ob = m * j.o_rs; + if (j.se->dtype == RAD_I32 && j.o_cs == 1) { + std::memcpy((int32_t*)j.se->data + ob, row, (size_t)(topk + 1) * sizeof(int32_t)); + } else { + for (int64_t i = 0; i <= topk; ++i) + st_int_dt(j.se->dtype, j.se->data, ob + i * j.o_cs, row[i]); + } + st_int_dt(j.ns->dtype, j.ns->data, offlin(j.ns, m), out); + st_int_dt(j.su->dtype, j.su->data, offlin(j.su, m), + out == 0 ? 0 : (out - 1) * j.ratio + p % j.ratio + 1); +} + +} /* namespace */ + +/* ------------------------------------------------------------------ qsa_select */ +/* The page-id table the sparse attention reads (docs/OPS.md): over the query's complete blocks + * n = min(nc[seq], (pos + 1) / ratio, width), the live ones (page id >= 0, score > -1e30) ranked + * by max(score, 0). All of them when `topk` or fewer are live, else every block above the topk-th + * largest value in block order, then the blocks equal to it in block order until topk are taken. + * The partial page bt[n] follows when (pos + 1) % ratio != 0 and n < width, and -1 pads the row + * to topk + 1. A row no sequence holds reads sequence 0, as libref's and libr4d's do. */ +AVX_KERNEL(qsa_select) { + if (!rad_args_have(a, 8)) return RAD_E_INVAL; + const RadTensor *sc = &a->t[0], *bt = &a->t[1], *nc = &a->t[2], *po = &a->t[3]; + const RadTensor *cu = &a->t[4], *se = &a->t[5], *ns = &a->t[6], *su = &a->t[7]; + const int64_t topk = p_int(a, "topk", 0), ratio = p_int(a, "ratio", 0); + if (topk <= 0 || ratio <= 0) return RAD_E_SHAPE; + if (sc->rank != 2 || bt->rank != 2 || se->rank != 2) return RAD_E_SHAPE; + const int64_t M = sc->shape[0], nb = std::min(bt->shape[1], sc->shape[1]); + const int64_t n_seq = numel(cu) - 1; + if (M <= 0 || nb <= 0 || n_seq <= 0) return RAD_E_SHAPE; + if (bt->shape[0] < n_seq || numel(nc) < n_seq) return RAD_E_SHAPE; + if (se->shape[0] < M || se->shape[1] < topk + 1) return RAD_E_SHAPE; + if (numel(ns) < M || numel(po) < M || numel(su) < M) return RAD_E_SHAPE; + for (int64_t s = 0; s < n_seq; ++s) + if (ldi(nc, offlin(nc, s)) < 0) return RAD_E_INVAL; + for (int64_t m = 0; m < M; ++m) + if (ldi(po, offlin(po, m)) < 0) return RAD_E_INVAL; + + int64_t* seq = (int64_t*)scratch_raw((size_t)M * sizeof(int64_t) + 64); + seq_rows(cu, n_seq, M, 0, seq); + SelJob j{}; + j.sc = sc; j.bt = bt; j.nc = nc; j.po = po; j.se = se; j.ns = ns; j.su = su; + j.seq = seq; j.nb = nb; j.topk = topk; j.ratio = ratio; + j.s_rs = sc->stride[0]; j.s_cs = sc->stride[1]; + j.bt_rs = bt->stride[0]; j.bt_cs = bt->stride[1]; + j.o_rs = se->stride[0]; j.o_cs = se->stride[1]; + AVX_PARALLEL_FOR_IF(M * nb >= AVX_PAR_MIN && M > 1) + for (int64_t m = 0; m < M; ++m) select_row(j, m); + return RAD_OK; +} + +/* ------------------------------------------------------------------ qsa_tail_store */ +/* state[sidx[s][0]][0][pos[t] % ring] = k[t] for the last `ring` rows of each sequence, rows in + * ascending order, so a later row wins a shared target as in libref's serial loop (a row whose + * slot is -1, or that no sequence holds, writes nothing). At most `ring` rows a sequence write, so + * the copy is serial. */ +AVX_KERNEL(qsa_tail_store) { + if (!rad_args_have(a, 5)) return RAD_E_INVAL; + const RadTensor *k = &a->t[0], *po = &a->t[1], *cu = &a->t[2], *st = &a->t[3]; + const RadTensor *sx = &a->t[4]; + const int64_t n = p_int(a, "n", 0), ratio = p_int(a, "ratio", 0), ring = p_int(a, "ring", 0); + if (n <= 0 || ratio <= 0 || ring < ratio) return RAD_E_INVAL; + if (k->rank != 2 || st->rank != 4 || st->shape[1] != 1) return RAD_E_SHAPE; + const int64_t T = k->shape[0], slots = st->shape[0], n_seq = numel(cu) - 1; + if (T <= 0 || k->shape[1] != n || st->shape[2] < ring || st->shape[3] != n) return RAD_E_SHAPE; + if (n_seq <= 0 || numel(po) < T) return RAD_E_SHAPE; + if ((sx->rank >= 2 ? sx->shape[0] : numel(sx)) < n_seq) return RAD_E_SHAPE; + + /* The rows that write, as (row, slot), validated before any write. */ + int64_t* seq = (int64_t*)scratch_raw((size_t)T * 3 * sizeof(int64_t) + 64); + int64_t* w = seq + T; + seq_rows(cu, n_seq, T, -1, seq); + int64_t nw = 0; + for (int64_t t = 0; t < T; ++t) { + const int64_t s = seq[t]; + if (s < 0 || t < cu_at(cu, s + 1) - ring) continue; + const int64_t si = ldi(sx, col0(sx, s)); + if (si < 0) continue; + if (si >= slots || ldi(po, offlin(po, t)) < 0) return RAD_E_INVAL; + w[2 * nw] = t; + w[2 * nw + 1] = si; + ++nw; + } + float* buf = scratch_f32((size_t)n); + for (int64_t i = 0; i < nw; ++i) { + const int64_t t = w[2 * i], si = w[2 * i + 1]; + const int64_t row = ldi(po, offlin(po, t)) % ring; + widen(k, t * k->stride[0], k->stride[1], n, buf); + narrow(st, si * st->stride[0] + row * st->stride[2], st->stride[3], n, buf); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ qsa_work */ +/* The blocks that complete in this batch, in sequence order and ascending within one (libref's + * ref_qsa_work has the full statement): page bt[s][b] (-1 without a tail slot), the first token's + * position in bpos (three components with `rope`), and, with a slot, the block's `ratio` raw keys + * in stage rows w * ratio + i, each from this step's rows or the tail's. Items past the count get + * page -1 and position 0 and leave `stage` alone. nc[s] = (last position + 1) / ratio. Items are + * independent, so they are split across threads. */ +AVX_KERNEL(qsa_work) { + if (a->n_t < 11) return RAD_E_INVAL; + const RadTensor *k = rad_arg_in(a, 0), *po = rad_arg_in(a, 1), *cu = rad_arg_in(a, 2); + const RadTensor *tl = rad_arg_in(a, 3), *sx = rad_arg_in(a, 4), *bt = rad_arg_in(a, 5); + const RadTensor *rp = rad_arg_in(a, 6), *stg = rad_arg_in(a, 7), *pg = rad_arg_in(a, 8); + const RadTensor *bp = rad_arg_in(a, 9), *nc = rad_arg_in(a, 10); + if (!k || !po || !cu || !tl || !sx || !bt || !stg || !pg || !bp || !nc) return RAD_E_INVAL; + const int64_t n = p_int(a, "n", 0), ratio = p_int(a, "ratio", 0), ring = p_int(a, "ring", 0); + if (n <= 0 || ratio <= 0 || ring < ratio) return RAD_E_INVAL; + if (k->rank != 2 || bt->rank != 2 || stg->rank != 2) return RAD_E_SHAPE; + if (tl->rank != 4 || tl->shape[1] != 1 || tl->shape[2] < ring || tl->shape[3] != n) + return RAD_E_SHAPE; + const int64_t T = k->shape[0], n_seq = numel(cu) - 1, slots = tl->shape[0]; + if (T <= 0 || n_seq <= 0 || numel(po) < T || k->shape[1] != n || stg->shape[1] != n) + return RAD_E_SHAPE; + if (bt->shape[0] < n_seq || (sx->rank >= 2 ? sx->shape[0] : numel(sx)) < n_seq) + return RAD_E_SHAPE; + const int64_t mw = numel(pg); + if (mw < n_seq || stg->shape[0] < mw * ratio || numel(nc) < n_seq) return RAD_E_SHAPE; + int64_t bstep = 1; + if (bp->rank == 2) { + if (bp->shape[0] < mw || bp->stride[1] != 1 || bp->stride[0] < bp->shape[1] || + (rp && bp->shape[1] < 3)) + return RAD_E_SHAPE; + bstep = bp->stride[0]; + } else if (rp || numel(bp) < mw) { + return RAD_E_SHAPE; + } + if (rp && (rp->rank != 2 || rp->shape[0] < 3 || rp->shape[1] < T)) return RAD_E_SHAPE; + for (int64_t t = 0; t < T; ++t) + if (ldi(po, offlin(po, t)) < 0) return RAD_E_INVAL; + + /* The work list as (sequence, block), validated before any write. */ + int64_t* items = (int64_t*)scratch_raw((size_t)mw * 2 * sizeof(int64_t) + 64); + int64_t ni = 0; + for (int64_t s = 0; s < n_seq; ++s) { + const int64_t t0 = cu_at(cu, s), t1 = cu_at(cu, s + 1); + if (t1 <= t0) continue; + if (t0 < 0 || t1 > T) return RAD_E_SHAPE; + const int64_t p0 = ldi(po, offlin(po, t0)), p1 = ldi(po, offlin(po, t1 - 1)); + for (int64_t b = p0 / ratio; b <= (p1 + 1) / ratio - 1; ++b) { + if (ni >= mw) break; + if (b >= bt->shape[1]) return RAD_E_SHAPE; + const int64_t si = ldi(sx, col0(sx, s)); + if (si >= slots) return RAD_E_INVAL; + for (int64_t i = 0; si >= 0 && i < ratio; ++i) { + const int64_t q = b * ratio + i; + if (q >= p0 && t0 + (q - p0) >= T) return RAD_E_SHAPE; + } + items[2 * ni] = s; + items[2 * ni + 1] = b; + ++ni; + } + } + + for (int64_t s = 0; s < n_seq; ++s) { + const int64_t t0 = cu_at(cu, s), t1 = cu_at(cu, s + 1); + st_int_dt(nc->dtype, nc->data, offlin(nc, s), + t1 > t0 ? (ldi(po, offlin(po, t1 - 1)) + 1) / ratio : 0); + } + const int ncomp = rp ? 3 : 1; + AVX_PARALLEL_FOR_IF(mw * ratio * n >= AVX_PAR_MIN) + for (int64_t w = 0; w < mw; ++w) { + auto bpos_at = [&](int c) { return bp->rank == 2 ? w * bstep + c : offlin(bp, w); }; + if (w >= ni) { + st_int_dt(pg->dtype, pg->data, offlin(pg, w), -1); + for (int c = 0; c < ncomp; ++c) st_int_dt(bp->dtype, bp->data, bpos_at(c), 0); + continue; + } + const int64_t s = items[2 * w], b = items[2 * w + 1]; + const int64_t t0 = cu_at(cu, s), p0 = ldi(po, offlin(po, t0)); + const int64_t si = ldi(sx, col0(sx, s)); + st_int_dt(pg->dtype, pg->data, offlin(pg, w), + si < 0 ? -1 : ldi(bt, s * bt->stride[0] + b * bt->stride[1])); + const int64_t f = b * ratio; + if (!rp) { + st_int_dt(bp->dtype, bp->data, bpos_at(0), f); + } else { + const int64_t rs = rp->stride[0], rc = rp->stride[1]; + for (int c = 0; c < 3; ++c) + st_int_dt(bp->dtype, bp->data, bpos_at(c), + f >= p0 ? ldi(rp, c * rs + (t0 + f - p0) * rc) + : f + (ldi(rp, t0 * rc) - p0)); + } + if (si < 0) continue; + float* buf = scratch_f32((size_t)n); + for (int64_t i = 0; i < ratio; ++i) { + const int64_t q = f + i; + if (q >= p0) widen(k, (t0 + q - p0) * k->stride[0], k->stride[1], n, buf); + else widen(tl, si * tl->stride[0] + (q % ring) * tl->stride[2], tl->stride[3], n, buf); + narrow(stg, (w * ratio + i) * stg->stride[0], stg->stride[1], n, buf); + } + } + return RAD_OK; +} + +namespace { + +/* VF_N bf16 values widened, and VF_N floats narrowed RTNE with the ABI's NaN rule: avx_vec.h's + * row conversions at one vector, for a kernel that keeps the vector in a register. */ +static inline vf load_bf16(const uint16_t* p) { +#if AVX_LEVEL == 3 + return _mm512_castsi512_ps( + _mm512_slli_epi32(_mm512_cvtepu16_epi32(_mm256_loadu_si256((const __m256i*)p)), 16)); +#elif AVX_LEVEL == 2 + return _mm256_castsi256_ps( + _mm256_slli_epi32(_mm256_cvtepu16_epi32(_mm_loadu_si128((const __m128i*)p)), 16)); +#elif AVX_LEVEL == 1 + const __m128i h = _mm_loadu_si128((const __m128i*)p); + const __m128i lo = _mm_slli_epi32(_mm_cvtepu16_epi32(h), 16); + const __m128i hi = _mm_slli_epi32(_mm_cvtepu16_epi32(_mm_srli_si128(h, 8)), 16); + return _mm256_insertf128_ps(_mm256_castps128_ps256(_mm_castsi128_ps(lo)), + _mm_castsi128_ps(hi), 1); +#else + return rad_bf16_to_f32(*p); +#endif +} + +static inline void store_bf16(uint16_t* p, vf v) { +#if AVX_LEVEL == 3 + _mm256_storeu_si256((__m256i*)p, _mm512_cvtepi32_epi16(bf16_round_bits(v))); +#elif AVX_LEVEL == 2 + const __m256i w = bf16_round_bits(v); + _mm_storeu_si128((__m128i*)p, _mm_packus_epi32(_mm256_castsi256_si128(w), + _mm256_extracti128_si256(w, 1))); +#elif AVX_LEVEL == 1 + const __m128i lo = bf16_round_bits128(_mm256_castps256_ps128(v)); + const __m128i hi = bf16_round_bits128(_mm256_extractf128_ps(v, 1)); + _mm_storeu_si128((__m128i*)p, _mm_packus_epi32(lo, hi)); +#else + *p = rad_f32_to_bf16(v); +#endif +} + +} /* namespace */ + +/* ------------------------------------------------------------------ dflash_conv */ +namespace { + +struct ConvJob { + const RadTensor *x, *dl, *bs, *o; + int64_t T, H, taps, group, NG, bsz; + int64_t x_rs, o_rs, d_rs, d_ts, d_gs; +}; + +/* Channels and rows a block: a block's widened base kernel (8 KiB a tap) and its slice of the row + * above stay in L1 while the block walks its rows. */ +enum { kConvCols = 2048, kConvRows = 16 }; + +/* Rows [t0, t1) of groups [g0, g1), for dense rows of bf16 (XB, OB) or f32 and groups that span + * whole vectors. The rows a tap reads above are inputs, so any split of the rows is exact. */ +template +static void conv_block(const ConvJob& j, int64_t t0, int64_t t1, int64_t g0, int64_t g1) { + const int64_t G = j.group, ng = g1 - g0, cb = ng * G, h0 = g0 * G, taps = j.taps; + float* bf = scratch_f32((size_t)(taps * cb)); + float* dg = scratch_f32_b((size_t)(taps * ng)); + for (int64_t jt = 0; jt < taps; ++jt) + widen(j.bs, rowoff(j.bs, jt, j.H) + h0 * laststride(j.bs), laststride(j.bs), cb, + bf + jt * cb); + /* Element pointers as locals: through `j` the compiler reloads them after every store. */ + using XT = typename std::conditional::type; + using OT = typename std::conditional::type; + const XT* const xd = (const XT*)j.x->data; + OT* const od = (OT*)j.o->data; + const int64_t x_rs = j.x_rs; + auto load = [](const XT* p) { + if constexpr (XB) return load_bf16(p); + else return vf_loadu(p); + }; + auto store = [](OT* p, vf v) { + if constexpr (OB) store_bf16(p, v); + else vf_storeu(p, v); + }; + for (int64_t t = t0; t < t1; ++t) { + /* Tap jt applies when jt == 0 or t % block_size >= jt, i.e. taps 0 .. nt - 1. */ + const int64_t nt = std::min(taps, t % j.bsz + 1); + for (int64_t jt = 0; jt < nt; ++jt) + widen(j.dl, t * j.d_rs + jt * j.d_ts + g0 * j.d_gs, j.d_gs, ng, dg + jt * ng); + const XT* const x0 = xd + t * x_rs + h0; + OT* const out = od + t * j.o_rs + h0; + /* One and two taps (DFlash2's) straight-line; more in a loop. */ + for (int64_t k = 0; k < ng; ++k) { + const vf d0 = vf_set1(dg[k]); + const int64_t i1 = (k + 1) * G; + if (nt == 1) { + for (int64_t i = k * G; i < i1; i += VF_N) + store(out + i, vf_mul(vf_add(vf_loadu(bf + i), d0), load(x0 + i))); + } else if (nt == 2) { + const vf d1 = vf_set1(dg[ng + k]); + const XT* const x1 = x0 - x_rs; + const float* const b1 = bf + cb; + for (int64_t i = k * G; i < i1; i += VF_N) { + const vf acc = vf_mul(vf_add(vf_loadu(bf + i), d0), load(x0 + i)); + store(out + i, vf_fma(vf_add(vf_loadu(b1 + i), d1), load(x1 + i), acc)); + } + } else { + for (int64_t i = k * G; i < i1; i += VF_N) { + vf acc = vf_mul(vf_add(vf_loadu(bf + i), d0), load(x0 + i)); + for (int64_t jt = 1; jt < nt; ++jt) + acc = vf_fma(vf_add(vf_loadu(bf + jt * cb + i), vf_set1(dg[jt * ng + k])), + load(x0 - jt * x_rs + i), acc); + store(out + i, acc); + } + } + } + } +} + +/* Any other rows: row t through f32 copies of x. */ +static void conv_row(const ConvJob& j, const float* bf, int64_t t) { + const int64_t H = j.H, NG = j.NG, G = j.group; + const int64_t nt = std::min(j.taps, t % j.bsz + 1); + float* acc = scratch_f32((size_t)H); + float* xr = scratch_f32_b((size_t)H); + float* dg = scratch_f32_c((size_t)NG); + for (int64_t jt = 0; jt < nt; ++jt) { + const float* xv = in_row(j.x, (t - jt) * j.x_rs, H, xr); + const float* bj = bf + jt * H; + widen(j.dl, t * j.d_rs + jt * j.d_ts, j.d_gs, NG, dg); + for (int64_t g = 0; g < NG; ++g) + for (int64_t h = g * G; h < (g + 1) * G; ++h) { + const float term = (bj[h] + dg[g]) * xv[h]; + acc[h] = jt == 0 ? term : acc[h] + term; + } + } + out_row(j.o, t * j.o_rs, H, acc); +} + +} /* namespace */ + +/* DFlash2's grouped dynamic depthwise convolution over the [T, H] rows of x, blocks of + * `block_size` rows starting at row 0: + * + * out[t][h] = sum over taps j with j == 0 or t % block_size >= j of + * (base[j][h] + delta[t][j][h / group_size]) * x[t - j][h] + * + * in tap order, the coefficient add rounded as libref's, the product and sum fused. `delta` is + * [T, taps, NG], or [T, >= taps * NG] at its own row pitch. `out` must not alias `x`. */ +AVX_KERNEL(dflash_conv) { + if (!rad_args_have(a, 4)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *dl = &a->t[1], *bs = &a->t[2], *o = &a->t[3]; + const int64_t taps = p_int(a, "taps", 0), group = p_int(a, "group_size", 0); + const int64_t NG = p_int(a, "NG", 0), bsz = p_int(a, "block_size", 0); + if (taps <= 0 || group <= 0 || NG <= 0 || bsz <= 0) return RAD_E_INVAL; + if (x->data == o->data) return RAD_E_INVAL; + if (x->rank != 2 || o->rank != 2) return RAD_E_SHAPE; + const int64_t T = x->shape[0], H = x->shape[1]; + if (T <= 0 || o->shape[0] != T || o->shape[1] != H || H != NG * group) return RAD_E_SHAPE; + if (numel(bs) < taps * H) return RAD_E_SHAPE; + ConvJob j{}; + j.x = x; j.dl = dl; j.bs = bs; j.o = o; + j.T = T; j.H = H; j.taps = taps; j.group = group; j.NG = NG; j.bsz = bsz; + j.x_rs = x->stride[0]; j.o_rs = o->stride[0]; + if (dl->rank == 3) { + if (dl->shape[0] < T || dl->shape[1] < taps || dl->shape[2] < NG) return RAD_E_SHAPE; + j.d_rs = dl->stride[0]; j.d_ts = dl->stride[1]; j.d_gs = dl->stride[2]; + } else if (dl->rank == 2) { + if (dl->shape[0] < T || dl->shape[1] < taps * NG) return RAD_E_SHAPE; + j.d_rs = dl->stride[0]; j.d_gs = dl->stride[1]; j.d_ts = NG * j.d_gs; + } else { + return RAD_E_SHAPE; + } + + /* Dense bf16 and f32 rows, with groups of whole vectors so a group's delta is one broadcast: + * blocks of columns and rows, converted in the loads and the store. */ + const bool fused = group % VF_N == 0 && laststride(x) == 1 && laststride(o) == 1 && + (x->dtype == RAD_BF16 || x->dtype == RAD_F32) && + (o->dtype == RAD_BF16 || o->dtype == RAD_F32); + if (fused) { + const int64_t gpb = std::max(1, kConvCols / group); + const int64_t ncb = (NG + gpb - 1) / gpb, nrb = (T + kConvRows - 1) / kConvRows; + const bool xb = x->dtype == RAD_BF16, ob = o->dtype == RAD_BF16; + AVX_PARALLEL_FOR_IF(T * H * taps >= ((int64_t)1 << 18)) + for (int64_t u = 0; u < ncb * nrb; ++u) { + const int64_t g0 = (u % ncb) * gpb, g1 = std::min(g0 + gpb, NG); + const int64_t t0 = (u / ncb) * kConvRows, t1 = std::min(t0 + kConvRows, T); + if (xb && ob) conv_block(j, t0, t1, g0, g1); + else if (xb) conv_block(j, t0, t1, g0, g1); + else if (ob) conv_block(j, t0, t1, g0, g1); + else conv_block(j, t0, t1, g0, g1); + } + return RAD_OK; + } + /* The base kernel widened once; read-only inside the parallel loop. */ + float* bf = (float*)scratch_raw((size_t)(taps * H) * sizeof(float) + 64); + for (int64_t jt = 0; jt < taps; ++jt) + widen(bs, rowoff(bs, jt, H), laststride(bs), H, bf + jt * H); + AVX_PARALLEL_FOR_IF(T * H * taps >= ((int64_t)1 << 18)) + for (int64_t t = 0; t < T; ++t) conv_row(j, bf, t); + return RAD_OK; +} diff --git a/libavx/avx_quant.cpp b/libavx/avx_quant.cpp index f362eaf3..6e8a1734 100644 --- a/libavx/avx_quant.cpp +++ b/libavx/avx_quant.cpp @@ -1,55 +1,32 @@ /* avx_quant.cpp -- the quantisers, the rotation, and the Gram accumulator. * - * ============================== THE WALSH-HADAMARD IS BIT-IDENTICAL, ON PURPOSE ============================== + * Walsh-Hadamard, bit-identical to libref. The rotation is butterflies at strides 1, 2, 4, ... g/2, + * pairing i with i + h where (i & h) == 0. The stride matrices commute in exact arithmetic but not + * in f32, so libref's ascending order is kept: each butterfly is the same add and subtract on the + * same two floats, the rotated block is bit-identical, and the rotated-int8 family holds at the + * quantiser tolerance (1e-6). Only the lane mapping is vectorised (avx_had.h): * - * The rotation is a sequence of butterflies at ascending strides 1, 2, 4, ... g/2, pairing i with - * i + h where (i & h) == 0. The butterfly matrices for different strides COMMUTE -- H is a tensor - * power of the 2x2 Hadamard -- so any order of `h` gives the same transform in exact arithmetic, - * and it is tempting to reorder them for the vectoriser. + * h >= VF_N the pair (i, i+h) is two whole vectors: one add, one sub, two stores. + * h < VF_N the partner is a swizzle within one vector (adjacent lanes, lane pairs, 128-bit + * lanes, 256-bit halves), results selected by a lane mask. Four such strides at + * AVX-512, three at AVX2; left scalar they would dominate at g = 128. * - * That temptation is refused here and the order is libref's exactly, ASCENDING, because commuting - * in exact arithmetic is not the same as commuting in f32: the intermediate values differ and the - * roundings land in different places. Keeping the order means every butterfly is the same add and - * the same subtract on the same two floats as the reference performs, so the rotated block is - * BIT-IDENTICAL and not merely close -- which is what lets the whole rotated-int8 family be held - * at the quantiser tolerance (1e-6) instead of a loosened one. What is vectorised is WHICH LANES a - * butterfly runs on, not the arithmetic: + * The rotation runs once per row. libref rotates each block twice (once for amax, once for the + * codes) because it has no row-sized scratch; here the row is rotated into scratch once. * - * h >= VF_N the pair (i, i+h) is two whole vectors. One load, one add, one sub, two stores. - * h < VF_N the pair is inside one vector, so the partner is a SWIZZLE of it -- swap adjacent - * lanes, pairs of lanes, 128-bit lanes, 256-bit halves -- and the two results are - * selected by a lane mask. Four such steps at AVX-512, three at AVX2. + * `group` has three meanings (docs/OPS.md); reading the wrong one gives plausible numbers: * - * Doing the small strides scalar was the obvious first implementation and it is the wrong one: at - * g = 128 and VF_N = 16 that is four scalar passes over 128 elements against three vector passes, - * so the part that was left scalar would be most of the cost. - * - * ============================== THE ROTATION IS PERFORMED ONCE, NOT TWICE ============================== - * - * libref rotates each block twice -- once to find the absolute maximum and once to write the codes - * -- because it has a 4096-float stack frame and no row-sized scratch. That is a factor of two on - * every rotated op and it is pure recomputation: the rotated row is deterministic. Here the whole - * row is rotated once into scratch, the maximum is taken over it, and the codes are written from - * it. Identical arithmetic, half the butterflies. - * - * ============================== THE TWO `group` READINGS, AND THE TWO sqrt(g) CONVENTIONS ============================== - * - * docs/OPS.md is explicit that `group` means two different things in this table and that a kernel - * reading it the other way is WRONG rather than slow: - * - * quant_act_i8, quant_act_fp8, dequant `group` is the number of contiguous elements sharing - * and the fp8 fusions one scale. `scale` is [M, ceil(n/group)]. - * every had_* INT8 form `group` is the ROTATION WIDTH and the scale is per ROW, - * carrying the 1/sqrt(group). - * the had_* FP8 forms `group` is BOTH, and there is NO normalisation at all: - * = g and the whole factor g is folded - * into the stored weight scale at convert, where dividing - * a bf16 by a power of two is exact. Splitting it as the - * int8 forms do would round amax/7/sqrt(g) into bf16 and - * land ~0.2% of multiplicative error on every group. - * - * Three readings of one parameter name is not a pleasant fact, and it is the vocabulary's rather - * than this plugin's. It is restated here because getting it wrong produces a plausible number. + * quant_act_i8 one scale per row; `group` is the width of the code + * sums `asum` holds. + * quant_act_i8g, quant_act_fp8, dequant contiguous elements sharing one scale; `scale` is + * and the fp8 fusions [M, ceil(n/group)]. + * had_* int8 forms the rotation width; one scale per row, carrying + * 1/sqrt(group). + * had_* fp8 forms both, with no normalisation: = g , and + * the whole g is folded into the stored weight scale at + * convert, where dividing a bf16 by a power of two is + * exact. Splitting it as int8 does would round + * amax/7/sqrt(g) into bf16 (~0.2% error per group). */ #include "avx_vec.h" #include "avx_common.h" @@ -58,14 +35,8 @@ using namespace avx; #include "avx_had.h" -/* ================================================================== int8 store - * `q` is almost always RAD_I8, in which case the row store is the vectorised cvtps/packs path - * (avx_vec.h) whose rounding is MXCSR round-to-nearest-even and whose saturation is the pack - * instruction's -- exactly libref's nearbyintf-and-clamp, bit for bit. Anything else falls back to - * the generic row store, which is correct and slower. */ -static inline void store_codes(const RadTensor* q, int64_t base, int64_t n, const float* v) { - out_row(q, base, n, v); -} +/* Codes are stored with out_row; for RAD_I8 that is the vectorised clamp + cvtps/packs path + * (avx_vec.h), bit-exact with libref's nearbyintf-and-clamp. */ /* Scale a row by a scalar, in place. */ static inline void scale_row(float* v, int64_t n, float s) { @@ -76,10 +47,52 @@ static inline void scale_row(float* v, int64_t n, float s) { } /* ------------------------------------------------------------------ quant_act_i8 */ -/* q = round(x * 127 / amax), scale = amax / 127, per `group` contiguous elements. An all-zero - * group gets scale 0 and codes 0, which dequantises back to zero -- the alternative, a tiny - * epsilon scale, turns a zero row into denormal noise in the GEMM that reads it. */ +/* libref's arithmetic (ref_quant.cpp): one scale per row, max(amax, 1e-8) / 127, codes rounded to + * nearest even and stored in the step order, the middle two dwords of every 16-byte step + * exchanged. `asum` gets the per-`group` code sums, group-major [n/group][ceil(M/16)*16], taken + * from the row-major codes before the exchange. */ AVX_KERNEL(quant_act_i8) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *q = &a->t[1], *s = &a->t[2]; + const RadTensor* as = rad_arg_in(a, 3); + const int64_t n = p_int(a, "n", 0); + if (n <= 0 || n % 16) return RAD_E_SHAPE; + if (q->dtype != RAD_I8) return RAD_E_DTYPE; + if (!dense_row(q)) return RAD_E_STRIDE; + const int64_t rows = numel(x) / n; + if (rows <= 0 || numel(q) < rows * n || numel(s) < rows) return RAD_E_SHAPE; + const int64_t g = as ? p_int(a, "group", 0) : 0; + const int64_t mpad = (rows + 15) / 16 * 16; + if (as && (g <= 0 || n % g || numel(as) < n / g * mpad)) return RAD_E_SHAPE; + + AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + float* buf = scratch_f32((size_t)n); + const float* v = in_row(x, rowoff(x, r, n), n, buf); + int8_t* qb = (int8_t*)byte_at(q->data, q->dtype, rowoff(q, r, n)); + const float scale = std::max(row_amax(v, n), 1e-8f) / 127.0f; + cvt_scaled_f32_to_i8(v, 1.0f / scale, qb, n); + stt(s, rowoff(s, r, 1), scale); + for (int64_t gi = 0; as && gi < n / g; ++gi) { + int64_t sum = 0; + for (int64_t i = gi * g; i < (gi + 1) * g; ++i) sum += qb[i]; + stt(as, gi * mpad + r, (float)sum); + } + for (int64_t k = 0; k < n; k += 16) { + uint32_t d1, d2; + std::memcpy(&d1, qb + k + 4, 4); + std::memcpy(&d2, qb + k + 8, 4); + std::memcpy(qb + k + 4, &d2, 4); + std::memcpy(qb + k + 8, &d1, 4); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ quant_act_i8g */ +/* libr4d's quant_act_i8g: per `group` contiguous elements a scale amax * (1/127) (1 for an + * all-zero group), codes x * (1/scale) rounded to nearest even, row-major. */ +AVX_KERNEL(quant_act_i8g) { if (!rad_args_have(a, 3)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *q = &a->t[1], *s = &a->t[2]; const int64_t n = p_int(a, "n", 0); @@ -92,48 +105,36 @@ AVX_KERNEL(quant_act_i8) { const int64_t ngrp = (n + g - 1) / g; if (numel(s) < rows * ngrp) return RAD_E_SHAPE; - /* DENSE-i8 FAST PATH: the per-group scale feeds the int8 encoder directly, with no f32 - * scratch round trip between them. */ - if (q->dtype == RAD_I8 && dense_row(q)) { - AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) - for (int64_t r = 0; r < rows; ++r) { - float* buf = scratch_f32((size_t)n); - const float* v = in_row(x, rowoff(x, r, n), n, buf); - int8_t* qb = (int8_t*)byte_at(q->data, q->dtype, rowoff(q, r, n)); - for (int64_t gi = 0; gi < ngrp; ++gi) { - const int64_t k0 = gi * g, k1 = (k0 + g < n) ? k0 + g : n; - const float amax = row_amax(v + k0, k1 - k0); - const float inv = amax > 0.0f ? 127.0f / amax : 0.0f; - cvt_scaled_f32_to_i8(v + k0, inv, qb + k0, k1 - k0); - stt(s, rowoff(s, r, ngrp) + gi * laststride(s), amax / 127.0f); - } - } - return RAD_OK; - } - + const bool dense_i8 = q->dtype == RAD_I8 && dense_row(q); AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) for (int64_t r = 0; r < rows; ++r) { float* buf = scratch_f32((size_t)n); const float* v = in_row(x, rowoff(x, r, n), n, buf); - float* w = scratch_f32_b((size_t)n); + int8_t* qb = dense_i8 ? (int8_t*)byte_at(q->data, q->dtype, rowoff(q, r, n)) : nullptr; + float* w = dense_i8 ? nullptr : scratch_f32_b((size_t)n); for (int64_t gi = 0; gi < ngrp; ++gi) { const int64_t k0 = gi * g, k1 = (k0 + g < n) ? k0 + g : n; const float amax = row_amax(v + k0, k1 - k0); - const float inv = amax > 0.0f ? 127.0f / amax : 0.0f; - const vf vi = vf_set1(inv); - int64_t i = k0; - for (; i + VF_N <= k1; i += VF_N) vf_storeu(w + i, vf_mul(vf_loadu(v + i), vi)); - for (; i < k1; ++i) w[i] = v[i] * inv; - stt(s, rowoff(s, r, ngrp) + gi * laststride(s), amax / 127.0f); + const float sc = amax > 0.0f ? amax * (1.0f / 127.0f) : 1.0f; + const float inv = 1.0f / sc; + if (dense_i8) { + cvt_scaled_f32_to_i8(v + k0, inv, qb + k0, k1 - k0); + } else { + const vf vi = vf_set1(inv); + int64_t i = k0; + for (; i + VF_N <= k1; i += VF_N) vf_storeu(w + i, vf_mul(vf_loadu(v + i), vi)); + for (; i < k1; ++i) w[i] = v[i] * inv; + } + stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc); } - store_codes(q, rowoff(q, r, n), n, w); + if (!dense_i8) out_row(q, rowoff(q, r, n), n, w); } return RAD_OK; } /* ------------------------------------------------------------------ had_quant_act_i8 */ -/* Rotation at width `group`, then symmetric int8 with ONE scale per ROW carrying the - * 1/sqrt(group). The absolute maximum is over the WHOLE rotated row, because the scale is per row. */ +/* Rotation at width `group`, then symmetric int8 with one scale per row carrying the + * 1/sqrt(group); amax is over the whole rotated row. */ AVX_KERNEL(had_quant_act_i8) { if (!rad_args_have(a, 3)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *q = &a->t[1], *s = &a->t[2]; @@ -145,9 +146,7 @@ AVX_KERNEL(had_quant_act_i8) { if (rows <= 0 || numel(q) < rows * n || numel(s) < rows) return RAD_E_SHAPE; const float norm = 1.0f / std::sqrt((float)g); - /* Same dense-i8 fusion as quant_act_i8: the rotation stays, but its output is scaled + - * encoded straight to bytes. The amax here is whole-row (one scale per row), so the fusion - * is a single call rather than per group. */ + /* Dense i8: one fused scale+encode call per row. */ if (q->dtype == RAD_I8 && dense_row(q)) { AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) for (int64_t r = 0; r < rows; ++r) { @@ -166,34 +165,27 @@ AVX_KERNEL(had_quant_act_i8) { AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) for (int64_t r = 0; r < rows; ++r) { float* buf = scratch_f32((size_t)n); - /* in_row may hand back the operand's own pointer for a dense f32 input, and the rotation - * is IN PLACE -- so the row is copied into scratch whenever that happened. Rotating the - * caller's activation would be a kernel that destroys its own input. */ + /* in_row may return the operand itself for dense f32; copy before the in-place rotation + * so the input is not modified. */ const float* v = in_row(x, rowoff(x, r, n), n, buf); if (v != buf) std::memcpy(buf, v, (size_t)n * sizeof(float)); fwht_row(buf, n, g); const float amax = row_amax(buf, n); scale_row(buf, n, amax > 0.0f ? 127.0f / amax : 0.0f); - store_codes(q, rowoff(q, r, n), n, buf); + out_row(q, rowoff(q, r, n), n, buf); stt(s, r * laststride(s), amax / 127.0f * norm); } return RAD_OK; } /* ------------------------------------------------------------------ rmsnorm_had_quant_i8 */ -/* The fused rmsnorm + hadamard + quant_act_i8 a w4a8 layer wants where a bf16 layer wants a plain - * rmsnorm. +/* Fused rmsnorm + Hadamard + quant_act_i8, the w4a8 counterpart of a plain rmsnorm. * - * `residual` PRESENT IS THE fused_add_rms_norm FORM: the add happens first, the sum is written - * back into `residual` (that is what makes it INOUT and what the next layer's shortcut reads), and - * the norm is taken over the sum. The variance comes from the f32 sum and the rotation reads the - * sum back AFTER it has been narrowed to the residual tensor's own dtype -- which is what the pair - * of kernels this replaces does, and matching it is what makes the fused form substitutable for - * that pair. + * With `residual` (the fused_add_rms_norm form) the sum is written back into `residual` (INOUT; + * the next layer's shortcut reads it). As in libref, the variance comes from the f32 sum and the + * rotation reads the sum narrowed to the residual's dtype. * - * `out_bf16` is the post-norm, PRE-ROTATION tensor for a layer that also has a bf16 consumer: the - * rotation is an artefact of the int8 path, and a bf16 consumer wants the normalised activation - * rather than a Walsh-Hadamard of it. */ + * `out_bf16` receives the post-norm, pre-rotation row for a layer that also has a bf16 consumer. */ AVX_KERNEL(rmsnorm_had_quant_i8) { if (a->n_t < 5) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *w = &a->t[2], *q = &a->t[3], *s = &a->t[4]; @@ -212,8 +204,7 @@ AVX_KERNEL(rmsnorm_had_quant_i8) { if (ob && numel(ob) < rows * n) return RAD_E_SHAPE; const float norm = 1.0f / std::sqrt((float)g); - /* The gain, widened once per launch with `wadd` already folded in -- see avx_norm.cpp on why - * this cannot live in the per-thread scratch. */ + /* Gain with `wadd` folded in, widened once per launch (as in avx_norm.cpp). */ float* gain = (float*)scratch_raw((size_t)n * sizeof(float)); { const int64_t ws = laststride(w); @@ -228,14 +219,15 @@ AVX_KERNEL(rmsnorm_had_quant_i8) { float* buf = scratch_f32_b((size_t)n); float* tmp = scratch_f32_c((size_t)n); + float ss; if (res) { - /* x + residual, stored back, then READ BACK NARROWED -- the round trip is the - * contract. Done through a hot buffer rather than by re-reading the operand: same - * arithmetic, and it does not depend on the store having retired. */ + /* x + residual, stored, its variance taken, then narrowed through the residual's + * dtype in scratch. */ const float* xv = in_row(x, rowoff(x, r, n), n, src); const float* rv = in_row(res, rowoff(res, r, n), n, tmp); for (int64_t i = 0; i < n; ++i) buf[i] = xv[i] + rv[i]; out_row(res, rowoff(res, r, n), n, buf); + ss = row_sumsq(buf, n); if (res->dtype != RAD_F32) { row_from_f32(res->dtype, buf, tmp, n); row_to_f32(res->dtype, tmp, buf, n); @@ -244,34 +236,33 @@ AVX_KERNEL(rmsnorm_had_quant_i8) { } else { const float* xv = in_row(x, rowoff(x, r, n), n, src); if (xv != src) std::memcpy(src, xv, (size_t)n * sizeof(float)); + ss = row_sumsq(src, n); } - const float sc = 1.0f / std::sqrt(row_sumsq(src, n) / (float)n + eps); + const float sc = 1.0f / std::sqrt(ss / (float)n + eps); const vf vsc = vf_set1(sc); int64_t i = 0; for (; i + VF_N <= n; i += VF_N) vf_storeu(buf + i, vf_mul(vf_mul(vf_loadu(src + i), vsc), vf_loadu(gain + i))); for (; i < n; ++i) buf[i] = src[i] * sc * gain[i]; - if (ob) out_row(ob, rowoff(ob, r, n), n, buf); /* post-norm, PRE-rotation */ + if (ob) out_row(ob, rowoff(ob, r, n), n, buf); /* post-norm, pre-rotation */ fwht_row(buf, n, g); const float amax = row_amax(buf, n); scale_row(buf, n, amax > 0.0f ? 127.0f / amax : 0.0f); - store_codes(q, rowoff(q, r, n), n, buf); + out_row(q, rowoff(q, r, n), n, buf); stt(s, r * laststride(s), amax / 127.0f * norm); } return RAD_OK; } /* ------------------------------------------------------------------ gated_had_quant_i8 */ -/* An elementwise gated product, then the rotation and the quantiser. `act` picks between the two - * rotated sites a w4a8 model has: silu(a)*b is down_proj's input, sigmoid(a)*b is o_proj's on a - * gated-attention layer. `mode` is libr4d's integer spelling of the same choice. +/* Gated product, then the rotation and the quantiser. `act` selects the w4a8 site: silu(a)*b is + * down_proj's input, sigmoid(a)*b is o_proj's on a gated-attention layer. `mode` is libr4d's + * integer spelling of the same choice. * - * `b` ABSENT IS THE PACKED FORM: `a` is [M, 2n], gate first half, up second -- which is what a - * fused gate_up projection produces. Two operands with the second optional is the only shape that - * expresses both readings. */ + * With `b` absent, `a` is a packed [M, 2n] gate_up plane, gate first. */ AVX_KERNEL(gated_had_quant_i8) { if (a->n_t < 4) return RAD_E_INVAL; const RadTensor *ga = &a->t[0], *q = &a->t[2], *s = &a->t[3]; @@ -307,24 +298,22 @@ AVX_KERNEL(gated_had_quant_i8) { } for (; i < n; ++i) { const float gt = gv[i]; - const float sg = 1.0f / (1.0f + std::exp(-gt)); + const float sg = 1.0f / (1.0f + sc_exp(-gt)); out[i] = (act == 1 ? sg : gt * sg) * uv[i]; } fwht_row(out, n, g); const float amax = row_amax(out, n); scale_row(out, n, amax > 0.0f ? 127.0f / amax : 0.0f); - store_codes(q, rowoff(q, r, n), n, out); + out_row(q, rowoff(q, r, n), n, out); stt(s, r * laststride(s), amax / 127.0f * norm); } return RAD_OK; } /* ------------------------------------------------------------------ dequant */ -/* q * scale, with the SCALE STREAM'S OWN EXTENT deciding how many groups there are. The inverse of - * quant_act_i8 and NOT of the rotated forms: undoing a rotation is a second Hadamard, and an op - * that silently did one would make `dequant(had_quant(x)) == x` look true when the two have - * different meanings. */ +/* q * scale, with the scale tensor's extent giving the group count. The inverse of quant_act_i8 + * only; it does not undo a rotation. */ AVX_KERNEL(dequant) { if (!rad_args_have(a, 3)) return RAD_E_INVAL; const RadTensor *q = &a->t[0], *s = &a->t[1], *y = &a->t[2]; @@ -343,9 +332,8 @@ AVX_KERNEL(dequant) { float* out = scratch_f32_b((size_t)n); const float* v = in_row(q, rowoff(q, r, n), n, buf); const int64_t sb = rowoff(s, r, ngrp), ss = laststride(s); - /* GROUP BY GROUP, with the scale hoisted out of the element loop. libref reads the scale - * per element through a divide; the group edge is known here, so the divide happens once - * per group and the body is a vector multiply. Same product, same order. */ + /* Per group, with the scale hoisted (libref divides per element to find it). Same + * product. */ for (int64_t gi = 0; gi < ngrp; ++gi) { const int64_t k0 = gi * g; if (k0 >= n) break; @@ -356,8 +344,8 @@ AVX_KERNEL(dequant) { for (; i + VF_N <= k1; i += VF_N) vf_storeu(out + i, vf_mul(vf_loadu(v + i), vs)); for (; i < k1; ++i) out[i] = v[i] * sc; } - /* A row longer than the groups describe takes the LAST group's scale, which is libref's - * clamp (`gi < ngrp ? gi : ngrp - 1`) and is what a ragged final group means. */ + /* Elements past the described groups use the last group's scale, as libref clamps + * (`gi < ngrp ? gi : ngrp - 1`). */ if (ngrp * g < n) { const float sc = ldt(s, sb + (ngrp - 1) * ss); for (int64_t i = ngrp * g; i < n; ++i) out[i] = v[i] * sc; @@ -368,18 +356,14 @@ AVX_KERNEL(dequant) { } /* ------------------------------------------------------------------ quant_act_fp8 */ -/* The three choices this shares with libr4d's kernel, none of them derivable: +/* Conventions shared with libr4d's kernel: * - * 448 E4M3's largest finite value, and the scale is `amax / 448` -- a DEQUANT multiplier, - * the same sense as the checkpoint's `weight_scale_inv`, so the GEMM's fold multiplies - * the two scales together and nothing has to be inverted. - * scale 1 for an all-zero group, where amax/448 is zero and its reciprocal infinite. NOT the - * zero scale quant_act_i8 uses: that kernel's consumer reads a per-row int8 scale and - * a zero row is a zero row, while here the GEMM multiplies the two block scales and a - * zero would erase the weight's. - * the clamp is not defensive. amax * (1/scale) is 448 in exact arithmetic and can land an ulp - * above it once the reciprocal is rounded, which encodes as a NaN rather than as the - * largest finite. */ + * 448 E4M3's largest finite value. scale = amax / 448 is a dequant multiplier, the same + * sense as a checkpoint's `weight_scale_inv`, so the GEMM multiplies the two scales. + * scale 1 for an all-zero group (amax/448 = 0 has no reciprocal), because the GEMM + * multiplies the block scales and 0 would erase the weight's. + * the clamp amax * (1/scale) can land an ulp above 448 after rounding the reciprocal, which + * would encode as NaN. */ AVX_KERNEL(quant_act_fp8) { if (!rad_args_have(a, 3)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *q = &a->t[1], *s = &a->t[2]; @@ -410,13 +394,12 @@ AVX_KERNEL(quant_act_fp8) { } /* ------------------------------------------------------------- rmsnorm_quant_fp8 */ -/* RMS norm, an optional residual add, and quant_act_fp8, in one pass. +/* RMS norm, optional residual add, and quant_act_fp8 in one pass. * - * `residual` PRESENT IS THE fused_add_rms_norm FORM and the add is STORED BEFORE THE VARIANCE READS - * IT: the sum goes back into `residual`, narrowed to that tensor's dtype, and the norm -- variance - * included -- is taken over the narrowed sum. That is the `add` + `rmsnorm` pair, and not - * rmsnorm_add, which takes its variance from the unrounded sum. The normalised row is then narrowed - * to bf16 and the codes taken over it (avx_had.h). */ + * With `residual`, the sum is written back narrowed to that tensor's dtype and the whole norm, + * variance included, is taken over the narrowed sum: the `add` + `rmsnorm` pair, unlike + * rmsnorm_add, which takes its variance from the unrounded sum. The normalised row is narrowed to + * bf16 before the codes are taken (avx_had.h). */ AVX_KERNEL(rmsnorm_quant_fp8) { if (a->n_t < 5) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *w = &a->t[2], *q = &a->t[3], *s = &a->t[4]; @@ -436,8 +419,7 @@ AVX_KERNEL(rmsnorm_quant_fp8) { if (res && numel(res) < rows * n) return RAD_E_SHAPE; if (ob && numel(ob) < rows * n) return RAD_E_SHAPE; - /* The gain with `wadd` folded in, widened once on the calling thread -- see avx_norm.cpp on - * why it cannot live in the per-thread scratch. */ + /* Gain with `wadd` folded in, widened once on the calling thread (as in avx_norm.cpp). */ float* gain = (float*)scratch_raw((size_t)n * sizeof(float)); { const int64_t ws = laststride(w); @@ -480,9 +462,9 @@ AVX_KERNEL(rmsnorm_quant_fp8) { } /* ------------------------------------------------------------- gated_quant_fp8 */ -/* act(gate) * up over a PACKED [M, 2n] gate_up plane, gate half first, then quant_act_fp8 over the - * bf16-narrowed product. `act` is silu or sigmoid, `mode` libr4d's integer spelling of the same - * choice, silu when neither is given. */ +/* act(gate) * up over a packed [M, 2n] gate_up plane (gate first), then quant_act_fp8 over the + * bf16-narrowed product. `act` is silu or sigmoid (`mode` is libr4d's integer form); default + * silu. */ AVX_KERNEL(gated_quant_fp8) { if (!rad_args_have(a, 3)) return RAD_E_INVAL; const RadTensor *gu = &a->t[0], *q = &a->t[1], *s = &a->t[2]; @@ -512,21 +494,18 @@ AVX_KERNEL(gated_quant_fp8) { } /* ------------------------------------------------------------- had_quant_act_fp8 */ -/* The same quantiser with a `group`-wide Hadamard in front of the absmax, which is the only place - * a rotation can go: the whole benefit is that the maximum the grid is scaled by gets smaller. +/* quant_act_fp8 with a `group`-wide Hadamard before the absmax, which shrinks the maximum the grid + * is scaled by. * - * THE sqrt(g) IS NOT UNDONE HERE, and that is a deliberate difference from had_quant_act_i8 above, - * which folds 1/sqrt(g) into its own scale. H is symmetric, so = g , and the - * residual g has to be divided out exactly once between the two sides. The int8 op splits it; this - * one gives the WHOLE factor to the weight, where dividing a bf16 scale by a power of two is an - * exponent shift and therefore exact. */ + * Unlike had_quant_act_i8, 1/sqrt(g) is not applied here. = g , and the whole g is + * divided out of the weight scale instead, where dividing a bf16 by a power of two is exact. */ AVX_KERNEL(had_quant_act_fp8) { if (!rad_args_have(a, 3)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *q = &a->t[1], *s = &a->t[2]; const int64_t n = p_int(a, "n", 0); const int64_t g = p_int(a, "group", 0); - /* n % g != 0 is refused rather than rounded: a rotation block that straddled the end of the - * row would mix real values with padding, and no weight block was rotated that way. */ + /* n % g != 0 is refused: a block straddling the row end would mix in padding, unlike any + * rotated weight block. */ if (n <= 0 || !pow2(g) || n % g != 0) return RAD_E_SHAPE; if (g > AVX_HAD_MAX) return RAD_E_UNSUPPORTED; const int64_t rows = numel(x) / n; @@ -552,12 +531,11 @@ AVX_KERNEL(had_quant_act_fp8) { } /* ------------------------------------------------------------- givens_rotate */ -/* ParoQuant's activation side for a 16-bit GEMM: each row divided by its channel scales and rotated - * by `stages` rounds of disjoint Givens pairs, once a part, the parts side by side in y. libref's - * arithmetic (ref_quant.cpp) in its order: the divide, then a' = a cos t + b sin t, - * b' = b cos t - a sin t in f32, stage by stage. A pair walk is a gather and a scatter with nothing - * to vectorise; what is hoisted is the cos and sin of every angle, a property of the weight and the - * same for every row, so they are taken once a call rather than once a row. */ +/* ParoQuant's activation side for a 16-bit GEMM: each row is divided by its channel scales and + * rotated by `stages` rounds of disjoint Givens pairs, once per part, parts side by side in y. + * libref's arithmetic and order (ref_quant.cpp): the divide, then a' = a cos t + b sin t, + * b' = b cos t - a sin t in f32, stage by stage. The pair walk is a gather/scatter and stays + * scalar; the cos and sin of each angle are computed once per call. */ AVX_KERNEL(givens_rotate) { if (!rad_args_have(a, 5)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *pr = &a->t[1], *an = &a->t[2], *sc = &a->t[3], *y = &a->t[4]; @@ -582,8 +560,8 @@ AVX_KERNEL(givens_rotate) { } for (int64_t j = 0; j < NP; ++j) { const float th = ldt(an, j); - cs[j] = std::cos(th); - sn[j] = std::sin(th); + cs[j] = sc_cos(th); + sn[j] = sc_sin(th); } for (int64_t k = 0; k < P * n; ++k) rs[k] = ldt(sc, k); @@ -612,12 +590,12 @@ AVX_KERNEL(givens_rotate) { } /* --------------------------------------------------------- givens_dense_quant */ -/* The quantising form: the rotation as one dense 128 x 128 f16 matrix a (part, group) -- `tdense`, - * which rad-convert composes from the pairs and angles and stores as the weight's "t.dense" table -- - * then the block-scaled quantiser `out` names: "fp8" E4M3 with scale amax / 448, "i8" scale - * amax / 127 rounded to nearest; scale 1 for an all-zero group, as libref. The matrices are widened - * to f32 once a call; a row is then a matrix-vector product a group, in f32 where libref sums in - * f64, so a code can differ from libref's where the value sits on a rounding edge. */ +/* Quantising form: the rotation as one dense 128 x 128 f16 matrix per (part, group) (`tdense`, + * which rad-convert composes from the pairs and angles as the weight's "t.dense" table), then the + * block-scaled quantiser named by `out`: "fp8" E4M3 with scale amax / 448, or "i8" with scale + * amax / 127, rounded to nearest; scale 1 for an all-zero group, as libref. The matrices are widened + * to f32 once per call. Each group is a matrix-vector product summed in f32 (libref uses f64), so a + * code on a rounding edge can differ from libref's. */ AVX_KERNEL(givens_dense_quant) { if (!rad_args_have(a, 5)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *tm = &a->t[1], *sc = &a->t[2], *q = &a->t[3], *s = &a->t[4]; @@ -673,26 +651,17 @@ AVX_KERNEL(givens_dense_quant) { /* ---------------------------------------------------------------- the Gram accumulator * - * h[k1][k2] += sum over rows of x[m][k1] * x[m][k2], where x is the DEQUANTISED E4M3 input, or a - * bf16 input as it stands when no scale is passed -- the second moment GPTQ's error feedback - * needs, over exactly the operand the expert GEMM contracts. + * h[k1][k2] += sum over rows of x[m][k1] * x[m][k2], where x is the dequantised E4M3 input, or a + * bf16 input as is when no scale is passed: the second moment GPTQ's error feedback needs, over the + * operand the expert GEMM contracts. * - * `h` IS READ AS WELL AS WRITTEN and that is the op: the caller zeroes it once and drives a whole - * calibration corpus through the graph, so each launch adds its own block. An implementation that - * stored instead of added would agree on one call and disagree on a corpus. + * `h` accumulates across launches: the caller zeroes it once and runs a calibration corpus through. * - * THE ACCUMULATION IS f64 HERE AND f32 ON THE DEVICE, and that is libref's choice reproduced - * rather than an accident: this is the one op in the vocabulary whose result is consumed OFFLINE, - * by the packer, through a file -- so being tighter than the kernel is the right trade, and the - * kbench tolerance covers the gap. It also means the inner reduction is NOT the f32 vector path - * the rest of this file uses; there is nothing to vectorise about an f64 accumulation of an f32 - * product that would not change the answer. - * - * What IS vectorised is the dequantisation: rows are widened and scaled once into a scratch plane - * rather than inside the k2 loop, which is O(n^2 * rows) with a per-element dtype dispatch in it - * otherwise. */ + * Accumulation is f64 here (f32 on the device), as in libref: the result is consumed offline by + * the packer, and the kbench tolerance covers the gap. The f64 inner reduction stays scalar; only + * the dequantisation is vectorised, once per row into a scratch plane rather than in the k2 loop. */ AVX_KERNEL(gram_accum) { - /* `a_scale` is optional: absent, `a` is read as it stands, which is the bf16 form. */ + /* `a_scale` is optional; without it `a` is read as is (the bf16 form). */ if (a->n_t < 3) return RAD_E_INVAL; const RadTensor *x = rad_arg_in(a, 0), *s = rad_arg_in(a, 1), *h = rad_arg_in(a, 2); if (!x || !h) return RAD_E_INVAL; @@ -721,16 +690,21 @@ AVX_KERNEL(gram_accum) { } } + /* The upper triangle, each sum added to both (k1, k2) and (k2, k1): the products commute, so + * the two sums are the same bits. Rows of the triangle shrink, hence the dynamic schedule. */ const int64_t hst = laststride(h); - AVX_PARALLEL_FOR_IF(n * n >= 1024) +#ifdef _OPENMP + AVX_PRAGMA(omp parallel for schedule(dynamic, 8) if(n * n >= 1024 || avx_par_forced()) + num_threads(avx_team_size())) +#endif for (int64_t k1 = 0; k1 < n; ++k1) { - const int64_t hb = rowoff(h, k1, n); - for (int64_t k2 = 0; k2 < n; ++k2) { + for (int64_t k2 = k1; k2 < n; ++k2) { double acc = 0.0; for (int64_t r = 0; r < rows; ++r) acc += (double)xs[r * n + k1] * (double)xs[r * n + k2]; - const int64_t off = hb + k2 * hst; - stt(h, off, (float)((double)ldt(h, off) + acc)); + const int64_t o12 = rowoff(h, k1, n) + k2 * hst, o21 = rowoff(h, k2, n) + k1 * hst; + stt(h, o12, (float)((double)ldt(h, o12) + acc)); + if (k2 != k1) stt(h, o21, (float)((double)ldt(h, o21) + acc)); } } return RAD_OK; diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 769103c8..bad5a93d 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -1,64 +1,40 @@ -/* avx_registry.cpp -- what libavx contains, in the two forms the core reads it in. +/* avx_registry.cpp -- the op schemas and kernel rows libavx exports. * - * ============================== THE SCHEMAS ARE libref's, DELIBERATELY IDENTICAL ============================== + * Schemas match libref's exactly. The first plugin in hierarchy order to declare an op fixes its + * schema; a later plugin declaring it differently is refused at load (rad_abi.h, + * core/plugin/loader.cpp: schema_same). That compares parameters position by position (key, type, + * requiredness) and operands (role, optionality), not operand names. The table is copied rather + * than shared because a plugin links only abi/; rad-avx-check runs the loader's comparison against + * libref over every schema before checking any number, so the copy cannot drift silently. * - * The first plugin in hierarchy order to declare an op FIXES its schema, and a later plugin - * declaring the same op name with a different one is refused AT LOAD with both plugins named - * (rad_abi.h). The check is core/plugin/loader.cpp:schema_same, and what it holds is: the - * parameter list position for position -- key, type, requiredness -- and the operand list position - * for position -- role and optionality. Operand NAMES are explicitly not load-bearing. + * No opd_shape. That hook sizes an op's operands for a tool calling it cold; libref implements it + * for the whole conventional vocabulary (docs/OPS.md), and libavx computes the same ops at the same + * shapes. A second set of answers could disagree with libref's. A tool with libavx but not libref + * could not size buffers; both host plugins ship together. * - * So this table is libref's, slot for slot. It is COPIED rather than shared, and that is the ABI - * boundary working as designed rather than a missed refactor: a plugin links abi/ and nothing - * else, so there is no header for libref's table to live in that libavx could include without - * making one plugin depend on another's source. What replaces the shared header is a TEST: - * rad-avx-check opens both plugins and runs the loader's own comparison over all seventy-five - * schemas before it checks a single number, and fails loudly on the first disagreement. A copy - * that is checked on every run is a copy that cannot drift; a copy that is merely intended to - * match is a copy that eventually does. - * - * ============================== WHY THE ROWS CARRY NO opd_shape ============================== - * - * `RadKernelInfo::opd_shape` answers "how big is operand i of this op at this geometry" for a tool - * calling the op cold, and libref implements one for every op in the conventional vocabulary -- - * 88 KB of judgement calls about index ranges, fill domains and what a ragged batch means. libavx - * computes exactly those ops at exactly those shapes, so libref's answers are libavx's answers, - * and the ABI says so in as many words: "libref supplies it for the whole conventional vocabulary, - * so an op that stays inside docs/OPS.md is describable even when the kernel under test is not." - * - * Writing a second copy would be writing a second set of judgement calls about the SAME ops, and - * the two would disagree somewhere -- which is worse than having one, because a tool would then - * size a buffer from one plugin and check it against the other. The cost is stated plainly: a - * tool that has libavx and NOT libref cannot size libavx's buffers. That tool does not exist (both - * are host plugins and ship together) and if it ever does, the fix is to implement the hook, not - * to have guessed. - * - * ============================== AND NO TUNABLES ============================== - * - * ABI v8 has kernels declare tunable AXES and the core take the cross product (rad_abi.h). libavx - * declares none, and the reason is that its axes are not free: the vector width is fixed by the - * ISA level, which is fixed by the CPU, and the GEMM's blocking is chosen from the cache sizes - * CPUID reports rather than from a search. There is one thing worth tuning -- the L2 block edge -- - * and it is read from the machine rather than measured per shape, because unlike a GPU tile it - * does not interact with an occupancy limit. A declared axis whose best value is computable is a - * declared axis that wastes the tuner's time. + * No tunables. The vector width is fixed by the ISA level, and the GEMM's M block is derived from K + * against a fixed L2 byte target (avx_gemm.cpp), with no occupancy interaction to search over. */ #include "avx_isa.h" +#include "avx_planes.h" #include "avx_rows.h" #include "rad_abi.h" +#include "rad_planes.h" #include "rad_plugin.h" +#include + /* ================================================================== parameter specs - * The macro names are libref's too. Two files that must agree line for line should look the same - * when they are diffed, and `diff libref/ref_registry.cpp libavx/avx_registry.cpp` over the schema - * section is a real review step. */ + * Same macro names as libref, so the schema sections of libref/ref_registry.cpp and this file can + * be diffed directly. */ #define P_INT(k) { k, RAD_P_INT, RAD_REQUIRED } #define P_INTO(k) { k, RAD_P_INT, RAD_OPTIONAL } #define P_STR(k) { k, RAD_P_STR, RAD_REQUIRED } #define P_STRO(k) { k, RAD_P_STR, RAD_OPTIONAL } #define P_INTD(k) { k, RAD_P_INT, RAD_DERIVED } #define P_CHUNK(k) { k, RAD_P_INT, RAD_DERIVED, RAD_PROLE_SEQ_CHUNK } +#define P_CAP(k) { k, RAD_P_INT, RAD_REQUIRED, RAD_PROLE_CAPACITY } #define P_F64(k) { k, RAD_P_F64, RAD_REQUIRED } #define P_F64O(k) { k, RAD_P_F64, RAD_OPTIONAL } @@ -75,12 +51,12 @@ #define ARR(a) (a), (int)(sizeof(a) / sizeof((a)[0])) /* ---- elementwise and norms ---------------------------------------------------------------- */ -/* rmsnorm_add has no `mult`: it is the fused pair, and nothing fuses a scaled branch. */ +/* rmsnorm_add has no `mult`: no fused residual-norm site uses a scaled branch. */ static const RadParamSpec pRmsnormAdd[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype"), P_F64O("wadd") }; static const RadParamSpec pRmsnorm[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype"), P_F64O("wadd"), P_F64O("mult") }; -/* `w` optional: absent, the gain is one. */ +/* `w` is optional; absent means a gain of 1. */ static const RadOperandSpec oRmsnorm[] = { OPD("x"), WGT_O("w"), OUT("y") }; static const RadParamSpec pHcRead[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_INT("lowrank"), @@ -136,7 +112,7 @@ static const RadOperandSpec oGridEmbed[] = { INOUT("x"), WGT("table"), OPD("coor static const RadParamSpec pMnD[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; static const RadParamSpec pMulWeight[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_INTO("scalar") }; -/* `cap` required, for the reason libref's pMnCap states: a softcap without a cap is a different op. */ +/* `cap` is required (as in libref's pMnCap). */ static const RadParamSpec pMnCap[] = { P_INT("M"), P_INT("n"), P_F64("cap"), P_STR("dtype") }; static const RadOperandSpec oBinary[] = { OPD("a"), OPD("b"), OUT("y") }; static const RadOperandSpec oMulWeight[] = { OPD("x"), WGT("w"), OUT("y") }; @@ -147,26 +123,36 @@ static const RadParamSpec pPoolRows[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_ P_STR("dtype") }; static const RadOperandSpec oGateUp[] = { OPD("gate_up"), OUT("y") }; static const RadOperandSpec oUnary[] = { OPD("x"), OUT("y") }; -/* The audio (USM conformer) tower's operators; libref's lists, field for field. */ +/* The audio (USM conformer) tower's operators, as in libref. */ static const RadOperandSpec oClamp[] = { OPD("x"), WGT("lo"), WGT("hi"), OUT("y") }; static const RadParamSpec pConv2d[] = { P_INT("M"), P_INT("width"), P_INT("cin"), P_INT("cout"), P_INT("kh"), P_INT("kw"), P_INT("stride"), P_INT("pad"), P_INTO("cu_div"), P_INTO("valid_stride"), - P_STR("dtype") }; + P_STR("dtype"), P_INTO("t_last"), P_STRO("act") }; static const RadOperandSpec oConv2d[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OPD_O("valid"), - OUT("y") }; + OUT("y"), WGT_O("b") }; +static const RadParamSpec pConv2dUnfold[] = { P_INT("M"), P_INT("width"), P_INT("cin"), + P_INT("kh"), P_INT("kw"), P_INT("stride"), + P_INT("pad"), P_INTO("cu_div"), + P_INTO("valid_stride"), P_INTO("t_last"), + P_STR("dtype") }; +static const RadOperandSpec oConv2dUnfold[] = { OPD("x"), OPD("cu_seqlens"), OPD_O("valid"), + OUT("y") }; static const RadParamSpec pConv1dDw[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_INTO("cu_div"), P_STR("dtype") }; static const RadOperandSpec oConv1dDw[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OUT("y") }; static const RadParamSpec pRelSin[] = { P_INT("M"), P_INT("n"), P_F64O("max_timescale"), P_STR("dtype") }; static const RadOperandSpec oRelSin[] = { OUT("y") }; +static const RadParamSpec pSegSin[] = { P_INT("M"), P_INT("n"), P_INT("period"), + P_F64O("max_timescale"), P_INTO("cu_div"), P_STR("dtype") }; +static const RadOperandSpec oSegSin[] = { OPD("cu_seqlens"), OUT("y") }; static const RadParamSpec pAttnLocalRel[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"), P_INT("left"), P_INT("right"), P_F64("softcap"), P_INTO("cu_div"), P_STR("dtype") }; static const RadOperandSpec oAttnLocalRel[] = { OPD("q"), OPD("k"), OPD("v"), OPD("relk"), WGT("pds"), OPD("cu_seqlens"), OUT("out") }; -/* `fill` has no input: `value` is the whole of what it writes. */ +/* `fill` has no input; it writes `value`. */ static const RadParamSpec pFill[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_F64O("value") }; static const RadOperandSpec oFill[] = { OUT("y") }; static const RadOperandSpec oScale[] = { OPD("x"), WGT("s"), OUT("y") }; @@ -181,8 +167,8 @@ static const RadParamSpec pQuant[] = { P_INT("M"), P_INT("n"), P_INT("group static const RadOperandSpec oQuant[] = { OPD("x"), OUT("q"), OUT("scale"), OUT_O("asum") }; static const RadOperandSpec oHadQuant[] = { OPD("x"), OUT("q"), OUT("scale") }; static const RadOperandSpec oQuantFp8[] = { OPD("x"), OUT("q"), OUT("scale") }; -/* ParoQuant's rotation, libref's declaration: the tables are the "givens" encoding's - * (abi/rad_encoding.h) and WEIGHT operands, resolved and placed with the weight they belong to. */ +/* ParoQuant's rotation, as libref declares it: the tables come from the "givens" encoding + * (abi/rad_encoding.h) and are weight operands, placed with the weight they belong to. */ static const RadParamSpec pGivensRotate[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype"), P_INT("stages"), P_INT("parts") }; static const RadParamSpec pGivensDense[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype"), @@ -192,8 +178,8 @@ static const RadOperandSpec oGivensDense[] = { OPD("x"), WGT("tdense"), WGT("rsc static const RadOperandSpec oGivensRotate[] = { OPD("x"), WGT("pairs"), WGT("angle"), WGT("rscale"), OUT("y") }; -/* The fp8 fusions: the unfused pair's operands minus the tensor between them, and `out_bf16` to - * put even that back. */ +/* The fp8 fusions: the unfused pair's operands minus the intermediate tensor, which `out_bf16` + * can optionally still produce. */ static const RadParamSpec pRmsQuantFp8[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"), P_STR("dtype"), P_F64O("wadd") }; static const RadOperandSpec oRmsQuantFp8[] = { OPD("x"), INOUT_O("residual"), WGT("w"), @@ -212,7 +198,7 @@ static const RadParamSpec pGatedQuant[] = { P_INT("M"), P_INT("n"), P_INT("gro P_STR("dtype"), P_STRO("act"), P_INTO("mode") }; static const RadOperandSpec oGatedQuant[] = { OPD("a"), OPD_O("b"), OUT("q"), OUT("scale") }; -/* `a_scale` is optional: dtype "bf16" is a plain activation and carries none. */ +/* `a_scale` is optional: a "bf16" activation has none. */ static const RadOperandSpec oGram[] = { OPD("a"), OPD_O("a_scale"), INOUT("h") }; static const RadParamSpec pDequant[] = { P_INT("M"), P_INT("n"), P_INT("group"), @@ -235,7 +221,7 @@ static const RadOperandSpec oGemmQ[] = { OPD("a"), OPD_O("a_scale"), WGT("b OUT("y"), OPD_O("a_sum"), WGT_O("b_ref") }; static const RadOperandSpec oGemmQBias[] = { OPD("a"), OPD("a_scale"), WGT("b"), WGT("b_scale"), WGT("bias"), OUT("y") }; -/* `act` REQUIRED, where the quantiser has it optional; `N` is the weight's rows, twice the output's +/* `act` is required here (optional in the quantiser); `N` is the weight's rows, twice the output * width. */ static const RadParamSpec pGemmQGated[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"), P_STR("dtype"), P_STR("act") }; @@ -256,7 +242,8 @@ static const RadConstraint cPagedBlock[] = { RAD_CGE("block_size", 1) }; static const RadParamSpec pAttnDense[] = { P_INT("M"), P_INT("head_dim"), P_INT("gqa"), P_INT("causal"), P_STR("dtype"), P_F64O("scale"), - P_INTO("max_seqlen"), P_INTO("window") }; + P_INTO("max_seqlen"), P_INTO("window"), + P_INTO("cu_div"), P_INTO("block") }; static const RadOperandSpec oAttnDense[] = { OPD("q"), OPD("k"), OPD("v"), OPD("cu_seqlens"), OUT("out") }; @@ -281,8 +268,8 @@ static const RadParamSpec pRopeTable[] = { P_INT("M"), P_INT("rot"), P_F64("th P_INTO("head_dim"), P_STRO("ladder") }; static const RadOperandSpec oRopeTable[] = { OPD("positions"), OUT("cos_sin") }; -/* QSA's compressed key, libr4d's schema exactly (libr4d/r4d_rows.cpp): `block_size` is `ratio` - * spelled for the KV group the block-key store is, `page` and `pos` are optional. */ +/* QSA's compressed key, libr4d's schema (libr4d/r4d_rows.cpp): `block_size` is `ratio` under the + * name the block-key store's KV group uses; `page` and `pos` are optional. */ static const RadParamSpec pQsaBlockKey[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), P_INT("rotary_dim"), P_INTO("pos0"), P_INTO("block_size"), P_F64("eps"), P_F64("theta"), @@ -293,6 +280,27 @@ static const RadParamSpec pQsaBlockKey[] = { P_INT("M"), P_INT("n"), P_INT("rati static const RadOperandSpec oQsaBlockKey[] = { OPD("k"), WGT("w"), OPD_O("page"), OPD_O("pos"), OUT("out") }; +/* The rest of the QSA indexer, as libref declares it. `M` counts query rows (score, select) or + * tokens (tail store, work list); `seqs` is the declared height of `cu`'s sequences, whose count is + * cu's length less one. `work` bounds the blocks that can complete. */ +static const RadParamSpec pQsaScore[] = { P_INT("M"), P_INT("n"), P_INT("heads"), P_INT("blocks"), + P_INT("seqs"), P_STR("dtype") }; +static const RadOperandSpec oQsaScore[] = { OPD("q"), OPD("bk"), OPD("bt"), OPD("cu"), OPD("nc"), + OUT("score") }; +static const RadParamSpec pQsaSelect[] = { P_INT("M"), P_INT("blocks"), P_INT("topk"), + P_INT("ratio"), P_INT("seqs") }; +static const RadOperandSpec oQsaSelect[] = { OPD("score"), OPD("bt"), OPD("nc"), OPD("pos"), + OPD("cu"), OUT("sel"), OUT("nsel"), OUT("seqused") }; +static const RadParamSpec pQsaTailStore[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), P_INT("ring"), + P_INT("seqs"), P_STR("dtype") }; +static const RadOperandSpec oQsaTailStore[] = { OPD("k"), OPD("pos"), OPD("cu"), INOUT("state"), + OPD("sidx") }; +static const RadParamSpec pQsaWork[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), P_INT("ring"), + P_INT("seqs"), P_CAP("work"), P_STR("dtype") }; +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") }; + static const RadParamSpec pQkNormRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"), P_INT("n_head_kv"), P_F64("theta"), P_F64("eps"), P_F64O("scale"), P_STRO("mode"), @@ -305,10 +313,7 @@ static const RadOperandSpec oQkNormRope[] = { INOUT("qkv"), OPD("positions"), WG /* ---- mixture of experts ------------------------------------------------------------------- */ static const RadParamSpec pScaleRows[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_STR("dtype") }; -/* `add` is OPTIONAL and sits BEFORE `y`, which is the kind of detail a hand-kept copy gets wrong: - * operands are positional, so reading `y` at index 2 writes the output into the residual the - * caller passed. rad-avx-check compares this table against libref's on every run, which is what - * catches exactly this drift. */ +/* `add` is optional and comes before `y`; operands are positional, so `y` is index 3. */ static const RadOperandSpec oScaleRows[] = { OPD("x"), OPD("s"), OPD_O("add"), OUT("y") }; static const RadParamSpec pRouter[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"), @@ -326,9 +331,9 @@ static const RadParamSpec pMoeGemm[] = { P_INT("M"), P_INT("N"), P_INT("K"), P static const RadOperandSpec oMoeGemm[] = { OPD("a"), WTAB("w"), OPD("sorted_tok"), OPD("expert_offset"), OUT("y") }; -/* The experts are two tables by parity -- `w` the even ones at [N, K], `w_odd` the odd ones at - * [N_odd, K_odd] -- with `parts` stacked parts along the rows and the output; libr4d's schema - * says why. */ +/* Experts in two tables by parity: `w` the even ones at [N, K], `w_odd` the odd ones at + * [N_odd, K_odd], with `parts` parts stacked along the rows and the output (see libr4d's + * schema). */ static const RadParamSpec pMoeGemmQ[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("n_expert"), P_INT("top_k"), P_INT("group"), P_STR("a_order"), P_STR("dtype"), P_INTO("N_odd"), P_INTO("K_odd"), @@ -336,8 +341,8 @@ static const RadParamSpec pMoeGemmQ[] = { P_INT("M"), P_INT("N"), P_INT("K"), static const RadOperandSpec oMoeGemmQ[] = { OPD("a"), OPD_O("a_scale"), WTAB("w"), WTAB("w_scale"), OPD("sorted_tok"), OPD("expert_offset"), WTAB("w_odd"), WTAB("w_odd_scale"), OUT("y") }; -/* The same over four classes by the expert's number mod 4, `w_q` class q at [N_q, K_q]. Mirrors - * libref's and libr4d's schema exactly. */ +/* The same over four classes by expert number mod 4, `w_q` class q at [N_q, K_q], as in libref + * and libr4d. */ static const RadParamSpec pMoeGemmQMod4[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("n_expert"), P_INT("top_k"), P_INT("group"), P_STR("a_order"), P_STR("dtype"), P_INTO("N_1"), @@ -349,10 +354,9 @@ static const RadOperandSpec oMoeGemmQMod4[] = { OPD("a"), OPD_O("a_scale"), WTAB WTAB("w_1_scale"), WTAB("w_2"), WTAB("w_2_scale"), WTAB("w_3"), WTAB("w_3_scale"), OUT("y") }; -/* `shared` + `shared_gate` present = the shared arm folded in: y = narrow(shared * - * act(gate)) + narrow(gathered), the unfused pair's two narrows carried in the stores. `act` is - * scale_rows' spelling, sigmoid or none, and applies to the SCALAR. Mirrors libref's schema - * exactly -- the loader refuses the whole plugin on any disagreement. */ +/* With `shared` and `shared_gate`, the shared expert is folded in: y = narrow(shared * act(gate)) + * + narrow(gathered), the unfused pair's roundings. `act` is sigmoid or none, as in scale_rows, + * applied to the per-token gate scalar. */ static const RadParamSpec pMoeGather[] = { P_INT("M"), P_INT("n"), P_INT("top_k"), P_STR("dtype"), P_STRO("act") }; static const RadOperandSpec oMoeGather[] = { OPD("y_expert"), OPD("expert_w"), OPD("sorted_tok"), @@ -368,9 +372,9 @@ static const RadOperandSpec oRowTopkMerge[] = { OPD("gathered"), OUT("idx"), OUT static const RadParamSpec pPairArgmax[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; static const RadOperandSpec oPairArgmax[] = { OPD("pairs"), OUT("idx"), OUT_O("val") }; -/* Mirrors libref's row exactly: R candidates rescored against the full-precision head, ties to the - * lower id, pads sort last. libref's shape hook declines to describe this op, so the checker skips - * its geometries -- but the row must exist or the whole-plugin coverage gate fails. */ +/* As libref: R candidates rescored against the full-precision head, ties to the lower id, pads + * last. libref's shape hook does not describe this op, so the checker skips its geometries, but + * the row is needed for the coverage gate. */ static const RadParamSpec pLogitRerank[] = { P_INT("M"), P_INT("R"), P_INT("n_vocab"), P_INT("n_embd"), P_INTO("vocab_off"), P_STR("dtype") }; @@ -416,8 +420,7 @@ static const RadOperandSpec oRecurrent[] = { }; /* gdn_conv_update folded into gdn_recurrent_update: the convolution's operands, then the - * recurrence's minus q, k and v; the parameters are the union of the two ops' under their own - * names. */ + * recurrence's minus q, k and v; parameters are the union of both ops'. */ static const RadParamSpec pConvRecurrent[] = { P_INT("q_len"), P_INT("head_k"), P_INT("head_v"), P_INT("conv_width"), P_INTO("n_head_v"), P_F64O("scale"), P_F64O("eps"), P_F64O("l2_eps"), @@ -444,6 +447,46 @@ static const RadParamSpec pAllGather[] = { P_INT("world_size"), P_INT("numel") P_INTO("row") }; static const RadOperandSpec oAllGather[] = { OPD("x"), OUT("y") }; +/* ---- image generation --------------------------------------------------------------------- */ +static const RadParamSpec pLnMod[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype") }; +static const RadOperandSpec oLnMod[] = { OPD("x"), OPD("s"), OPD("cu_seqlens"), OUT("y") }; +static const RadOperandSpec oGateAdd[] = { OPD("y"), OPD("g"), OPD("cu_seqlens"), INOUT("x") }; +static const RadParamSpec pLnModQ[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"), + P_INT("gated"), P_STR("dtype") }; +static const RadOperandSpec oLnModQ[] = { OPD_O("y"), OPD_O("g"), OPD("s"), OPD("cu_seqlens"), + INOUT("x"), OUT("q"), OUT("scale"), OUT_O("z") }; +static const RadParamSpec pTimestep[] = { P_INT("M"), P_INT("n"), P_F64("scale"), P_F64("max_period"), + P_INTO("round"), P_STR("dtype") }; +static const RadOperandSpec oTimestep[] = { OPD("t"), OUT("y") }; +static const RadOperandSpec oGather2[] = { OPD("a"), OPD("b"), OPD("idx"), OUT("y") }; +static const RadParamSpec pLane[] = { P_INT("M"), P_INT("n"), P_INT("stride"), P_STR("dtype") }; +static const RadOperandSpec oLaneGather[] = { OPD("src"), OPD("lane"), OPD("cu_seqlens"), OUT("y") }; +static const RadOperandSpec oLaneStore[] = { OPD("src"), OPD("lane"), INOUT("dst") }; +static const RadOperandSpec oRandnLanes[] = { OPD("flags"), OPD("seed"), OPD("lane"), + OPD("cu_seqlens"), INOUT("dst") }; +static const RadOperandSpec oFlowEuler[] = { OPD("v"), OPD("sigma"), OPD("sigma_next"), OPD("cfg"), + OPD("pair"), OPD("lane"), OPD("flags"), OPD("seed"), + OPD("cu_seqlens"), OPD_O("inp_lat"), OPD_O("inp_mask"), + INOUT("state"), INOUT_O("preview") }; +static const RadParamSpec pChanAffine[] = { P_INT("M"), P_INT("n"), P_STR("mul"), P_STR("add"), + P_STR("mode"), P_STR("dtype") }; +static const RadParamSpec pConvNhwc[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"), + P_INT("stride"), P_STR("pad"), P_INT("up"), P_STR("dtype") }; +static const RadOperandSpec oConvNhwc[] = { OPD("x"), WGT("w"), WGT("b"), OUT("y") }; +static const RadParamSpec pL2Norm[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_STR("dtype") }; +static const RadOperandSpec oL2Norm[] = { OPD("x"), WGT("gamma"), OUT("y") }; +static const RadParamSpec pSpaceDepth[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("ft"), + P_STR("dtype") }; +static const RadOperandSpec oSpaceDepth[] = { OPD("x"), INOUT("y") }; +static const RadParamSpec pAttnPS[] = { P_INT("q_len"), P_INT("head_dim"), P_INT("gqa"), + P_INTD("block_size"), P_INT("causal"), P_STR("q_dtype"), + P_STR("kv_dtype"), P_F64O("scale"), P_INTO("max_ctx"), + P_INTO("n_head"), P_INTO("max_seqs"), P_STRO("qk") }; +static const RadOperandSpec oAttnPS[] = { OPD("q"), OPD("k"), OPD("v"), OPD("kv_cache"), + OPD("block_table"), OPD("seqused"), OPD("cu_seqlens"), + OPD_O("k_descale"), OPD_O("v_descale"), OPD_O("k_i8"), + OPD_O("k_scale"), OUT("out") }; + /* ---- vocabulary edges --------------------------------------------------------------------- */ static const RadParamSpec pEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_vocab"), P_STR("dtype"), P_INTO("vocab_offset"), @@ -462,8 +505,8 @@ static const RadOperandSpec oLogits[] = { OPD("x"), WGT("lm_head"), OUT("logits" /* ---- sampling ----------------------------------------------------------------------------- */ static const RadParamSpec pMVocab[] = { P_INT("M"), P_INT("n_vocab") }; static const RadParamSpec pMCand[] = { P_INT("M"), P_INT("n_cand") }; -/* libref's schema: the history stages take the rank's first vocabulary row, and DRY an optional - * plane of breaker marks beside the history. */ +/* As libref: the history stages take the rank's first vocabulary row (`vocab_off`), and DRY an + * optional plane of breaker marks beside the history. */ static const RadParamSpec pPenal[] = { P_INT("M"), P_INT("n_vocab"), P_INTO("vocab_off") }; static const RadOperandSpec oPenalties[] = { INOUT("logits"), OPD("params"), OPD("history") }; @@ -491,23 +534,25 @@ static const RadParamSpec pDflashSelect[] = { P_INT("M"), P_INT("steps"), P_I static const RadOperandSpec oDflashSelect[] = { OPD("cand"), OPD("unary"), OPD_O("hp"), OPD("anchor"), WGT("pred"), WGT("succ"), OUT("tokens") }; +/* DFlash2's grouped convolution, as libref declares it. */ +static const RadParamSpec pDflashConv[] = { P_INT("T"), P_INT("hidden_size"), P_INT("taps"), + P_INT("group_size"), P_INT("NG"), P_INT("block_size"), + P_STR("dtype") }; +static const RadOperandSpec oDflashConv[] = { OPD("x"), OPD("delta"), WGT("base"), OUT("out") }; /* ================================================================== the schema table - * The doc strings are libavx's own and say what this plugin does with the op -- which of the two - * plugins' strings a reader sees depends on which one fixed the schema first, and schema_same does - * not compare them. Where the op is subtle the string points at libref's, which is the definition. + * Doc strings are libavx's own (schema_same does not compare them); which plugin's string a reader + * sees depends on which fixed the schema first. libref's are the definition. */ static const RadOpSchema kSchemas[] = { { "rmsnorm", ARR(pRmsnorm), ARR(oRmsnorm), - "y = x * rsqrt(mean(x^2) + eps) * (w + wadd). The sum of squares is a four-accumulator vector " - "reduction, so it does not sum in libref's order and does not claim to." }, + "y = x * rsqrt(mean(x^2) + eps) * (w + wadd); the sum of squares is a four-accumulator vector " + "reduction, in a different order from libref's." }, { "rmsnorm_p", ARR(pLayernorm), ARR(oUnary), - "y = x * rsqrt(mean(x^2) + eps), the rmsnorm with no gain at all. Same four-accumulator sum of " - "squares as rmsnorm; the only difference is there is no weight to widen, so the op has no `w`." }, + "y = x * rsqrt(mean(x^2) + eps): rmsnorm with no gain, summed as rmsnorm sums." }, { "rmsnorm_add", ARR(pRmsnormAdd), ARR(oRmsnormAdd), - "residual_out = x + residual, then y = rmsnorm(residual_out) * w. The variance is taken from the " - "unrounded f32 sum and the multiply reads residual_out back AFTER narrowing -- both are libref's " - "rule and both are observable, so both are reproduced exactly." }, + "residual_out = x + residual, then y = rmsnorm(residual_out) * w: the variance from the unrounded " + "f32 sum, the multiply from residual_out after narrowing, as libref." }, { "hc_enter", ARR(pHcWrite), ARR(oHcEnter), "h[s] = x for each of the hc streams -- the wide residual stream's first value." }, { "hc_read", ARR(pHcRead), ARR(oHcRead), @@ -525,9 +570,9 @@ static const RadOpSchema kSchemas[] = { "x += a side x side position table resampled bilinearly to the row's grid." }, { "grid_embed_aa", ARR(pGridEmbed), ARR(oGridEmbed), "x += the table resampled as torch's antialiased half-pixel bilinear, SigLIP2's." }, -{ "add", ARR(pMnD), ARR(oBinary), "elementwise sum." }, -{ "mul", ARR(pMnD), ARR(oBinary), - "elementwise product; `b` may have extent 1 on any axis `a` does not and is broadcast along it." }, +{ "add", ARR(pMnD), ARR(oBinary), + "y = a + b; a `b` of exactly n elements against a taller output broadcasts along rows." }, +{ "mul", ARR(pMnD), ARR(oBinary), "y = a * b, with the same broadcast rule as `add`." }, { "mul_weight", ARR(pMulWeight), ARR(oMulWeight), "y = x * w, `w` a weight of one element or one row, broadcast; f32 product rounded once." }, { "act_mul", ARR(pActMul), ARR(oBinary), @@ -541,6 +586,10 @@ static const RadOpSchema kSchemas[] = { { "conv1d_dw", ARR(pConv1dDw), ARR(oConv1dDw), "segment-wise causal depthwise convolution over time." }, { "rel_sinusoid", ARR(pRelSin), ARR(oRelSin), "the sinusoidal relative-position table." }, +{ "conv2d_unfold", ARR(pConv2dUnfold), ARR(oConv2dUnfold), + "a convolution's receptive fields as rows, columns in the weight's order." }, +{ "seg_sinusoid", ARR(pSegSin), ARR(oSegSin), + "sinusoidal absolute positions restarting every `period` rows of a segment." }, { "attn_local_rel", ARR(pAttnLocalRel), ARR(oAttnLocalRel), "local attention with a relative-position term and a softcap (Gemma 4's audio)." }, { "pool_rows", ARR(pPoolRows), ARR(oUnary), @@ -568,12 +617,13 @@ static const RadOpSchema kSchemas[] = { "x[idx[i],:] = v[i,:], the mirror of gather_rows: `x` is INOUT and the write is partial, a " "negative index writes nothing, and indices are distinct." }, { "cast", ARR(pCast), ARR(oUnary), - "dtype conversion. The narrowing direction is the ABI's RTNE, bit for bit -- a vectorised cast " - "that rounded differently could not be checked against anything." }, + "dtype conversion; narrowing is the ABI's round-to-nearest-even, bit for bit." }, { "softmax", ARR(pMnD), ARR(oUnary), "row-wise softmax, max-subtracted." }, { "quant_act_i8", ARR(pQuant), ARR(oQuant), - "symmetric int8 activation quantiser, one f32 scale per `group` contiguous elements. `asum` is " - "not produced -- libavx has no asymmetric grid to feed, exactly as libref has none." }, + "symmetric int8, one f32 scale a row, codes in the int8 WMMA's step order; `asum` gets the " + "per-`group` code sums (libref's description)." }, +{ "quant_act_i8g", ARR(pQuant), ARR(oQuantFp8), + "symmetric int8, one f32 scale per `group` contiguous elements, row-major." }, { "quant_act_fp8", ARR(pQuant), ARR(oQuantFp8), "symmetric block-scaled E4M3 quantiser." }, { "had_quant_act_fp8", ARR(pQuant), ARR(oQuantFp8), "width-`group` Hadamard, then the same symmetric block-scaled E4M3 quantiser. No normalisation: " @@ -603,9 +653,8 @@ static const RadOpSchema kSchemas[] = { "act(gate) * up over a packed [M, 2n] plane, gate half first, then the E4M3 quantiser over the " "bf16-narrowed product. `act` is silu or sigmoid, silu by default." }, { "gemm_nt", ARR(pGemm), ARR(oGemm), - "C = A B^T, f32 accumulate, cache-blocked with a register-blocked microkernel. Sums in a " - "different order from libref's straight loop by construction; the kbench tolerance for a bf16 " - "gemm_nt (8e-3) is what that costs." }, + "C = A B^T, f32 accumulate, cache-blocked with a register-blocked microkernel; it sums in a " + "different order from libref's straight loop." }, { "gemm_nt_bias", ARR(pGemmBias), ARR(oGemmBias), "C = act(A B^T + bias) + res, each step rounded to C's dtype." }, { "gemm_nt_q", ARR(pGemmQ), ARR(oGemmQ), @@ -625,6 +674,21 @@ static const RadOpSchema kSchemas[] = { "QSA's compressed key: the mean of a block's `ratio` rows rounded to k's dtype, RMS-normed with " "gain (wadd + w), rotated at the block's position with `rope`'s ladder and YaRN; libref's " "arithmetic with the angles from one table a block." }, +{ "qsa_score", ARR(pQsaScore), ARR(oQsaScore), + "score[m][b] = (sum over heads of relu(q[m][h] . bk[bt[seq(m)][b]])) / sqrt(n) for the sequence's " + "first min(nc, width) blocks, a negative page id scoring -inf; the dots in vector order, the " + "heads summed in order. Columns past the bound are not written." }, +{ "qsa_select", ARR(pQsaSelect), ARR(oQsaSelect), + "the topk highest-scoring complete blocks as page ids, libref's order exactly: the blocks above " + "the threshold in block order, then its ties in block order, then the partial page, then -1 to " + "topk + 1; a radix select, linear in the blocks." }, +{ "qsa_tail_store", ARR(pQsaTailStore), ARR(oQsaTailStore), + "state[sidx[s][0]][pos[t] % ring] = k[t] for the last `ring` tokens of each sequence; the other " + "rows of the tail keep what they held." }, +{ "qsa_work", ARR(pQsaWork), ARR(oQsaWork), + "the blocks completing in this batch: each block's `ratio` raw keys staged contiguously, its " + "block-key page and first-token position; slots past the count get page -1. nc is each " + "sequence's complete-block count." }, { "rope", ARR(pRope), ARR(oRope), "rotary embedding in place." }, { "qk_norm_rope", ARR(pQkNormRope), ARR(oQkNormRope), "per-head QK norm then rotary embedding." }, { "scale_rows", ARR(pScaleRows), ARR(oScaleRows), @@ -652,9 +716,10 @@ static const RadOpSchema kSchemas[] = { { "gdn_kkt_solve", ARR(pKkt), ARR(oKkt), "gdn chunk preamble: the triangular inverse." }, { "gdn_chunk_scan", ARR(pChunkScan), ARR(oChunkScan), "gdn chunked scan." }, { "gdn_recurrent_update", ARR(pRecurrent), ARR(oRecurrent), - "gdn decode recurrence against the paged state cache, in the PER-CANDIDATE reading libref " - "implements. `state_form` names the reading; any other form, libr4d's two-slot \"anchor\" " - "among them, is declined by name as libref declines it." }, + "gdn decode recurrence against the paged state cache. `state_form` names the reading: " + "\"per_candidate\" (one state per candidate token) or libr4d's two-slot \"anchor\" (one " + "committed state and its tokens' replay factors), both as libref reads them; any other form is " + "declined by name." }, { "gdn_conv_recurrent_update", ARR(pConvRecurrent), ARR(oConvRecurrent), "gdn_conv_update followed by gdn_recurrent_update, with q, k and v never written: the operands " "are the convolution's (`conv_idx` is its state_idx) and then the recurrence's without those " @@ -663,6 +728,49 @@ static const RadOpSchema kSchemas[] = { { "all_reduce", ARR(pAllReduce), ARR(oAllReduce), "sum across ranks, f32, ascending rank order." }, { "all_gather", ARR(pAllGather), ARR(oAllGather), "gather every rank's shard." }, +{ "ln_mod_quant_fp8", ARR(pLnModQ), ARR(oLnModQ), + "gate_add (with `gated` 1), ln_mod and quant_act_fp8 in one pass, each value rounded as its own " + "store would round it; z written when bound." }, +{ "ln_mod", ARR(pLnMod), ARR(oLnMod), + "y = bf16(bf16(LN(x)) * bf16(1 + s[seq])): a gainless layer norm and the row's entry's " + "modulation row of `s` ([n_seq, >= n] at its own pitch)." }, +{ "gate_add", ARR(pMnD), ARR(oGateAdd), + "x = bf16(x + bf16(bf16(tanh(g[seq])) * y)), bit for bit libref's." }, +{ "timestep_embed", ARR(pTimestep), ARR(oTimestep), + "the sinusoidal timestep embedding [cos | sin], libref's libm calls; `round` 1 takes t through " + "bf16 at scale and back first." }, +{ "gather_rows2", ARR(pMnD), ARR(oGather2), + "y[i] = idx[i] >= 0 ? a[idx[i]] : b[-1 - idx[i]], zeros past either source." }, +{ "lane_gather", ARR(pLane), ARR(oLaneGather), + "y[cu[e] + k] = src[lane[e] * stride + k]; every entry checked before a row is written." }, +{ "lane_store", ARR(pLane), ARR(oLaneStore), + "dst[l * stride + k] = src[k] for every lane l listed." }, +{ "randn_lanes", ARR(pLane), ARR(oRandnLanes), + "an image's first step: its lane's rows become its seed's normal stream (abi/rad_philox.h), " + "bit for bit libref's." }, +{ "flow_euler", ARR(pLane), ARR(oFlowEuler), + "one flow-matching Euler step per entry that moves a lane, with guidance, the preview and the " + "repaint's kept region; libref's roundings bit for bit." }, +{ "chan_affine", ARR(pChanAffine), ARR(oUnary), + "a per-channel affine from two lists of n bf16 values, `fma` or `inv`." }, +{ "conv2d_nhwc", ARR(pConvNhwc), ARR(oConvNhwc), + "an image convolution, channels innermost, as GEMMs over bands of patch rows; `up` 2 reads the " + "input upsampled nearest-neighbour, `pad` same or down." }, +{ "l2norm_chan", ARR(pL2Norm), ARR(oL2Norm), + "each pixel's channels to unit L2, times sqrt(n), times gamma (three roundings), then `act`." }, +{ "d2s_add", ARR(pSpaceDepth), ARR(oSpaceDepth), + "y [2H, 2W * cout] += x [H, W * cin] repeated and dealt into 2x2 blocks (DupUp3D, one frame)." }, +{ "s2d_avg_add", ARR(pSpaceDepth), ARR(oSpaceDepth), + "y [H, W * cout] += the 2x2 blocks of x dealt into channels and averaged in groups (AvgDown3D, " + "one frame)." }, +{ "to_rgba8", ARR(pMnD), ARR(oUnary), + "decoded pixels in [-1, 1] to bytes as diffusers' postprocess makes them, u8 out." }, +{ "gelu_tanh", ARR(pMnD), ARR(oUnary), "the tanh approximation of gelu." }, +{ "scatter_add_rows", ARR(pMnD), ARR(oScatterRows), + "x[idx[i]] += v[i], rounded to x's dtype; a negative index adds nothing." }, +{ "attn_prefix_self", ARR(pAttnPS), ARR(oAttnPS), + "attention over `seqused[s]` prefix positions in the paged cache and the step's own rows, " + "flash-attention tiles; `qk` \"i8\" is the int8 score form (docs/OPS.md)." }, { "embed_lookup", ARR(pEmbedM), ARR(oEmbed), "embedding gather, vocab-parallel with an offset; `mult` multiplies every row (rounded once)." }, { "embed_lookup_q", ARR(pEmbed), ARR(oEmbedQ), @@ -681,13 +789,16 @@ static const RadOpSchema kSchemas[] = { { "sample_mask", ARR(pMVocab), ARR(oMask), "grammar bitmask application." }, { "sample_pick", ARR(pMCand), ARR(oPick), "seeded inverse-CDF draw. The uniform is splitmix64 over (seed * 0x9E3779B97F4A7C15 + pos), " - "top 24 bits as a float in [0,1) -- specified rather than left to a library, because the same " - "stream has to come out of a host reference, a device kernel and a rerun." }, + "top 24 bits as a float in [0,1), so a host reference, a device kernel and a rerun draw the " + "same stream." }, { "sample_merge_topk", ARR(pMCand), ARR(oMerge), "the vocab-parallel candidate merge." }, { "sample_argmax", ARR(pMVocab), ARR(oArgmax), "greedy, ties to the lower token id." }, { "sample_logprobs", ARR(pLogprobs), ARR(oLogprobs), "the raw logits' max, sum of exp(l - max) and k largest (id, logit) pairs, for a row with " "RAD_SP_LOGPROBS." }, +{ "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]." }, { "dflash_select", ARR(pDflashSelect), ARR(oDflashSelect), "a greedy walk over a candidate lattice: score[l, c] = unary[l, c] + sum_r pred[pid(l)][r] * " "hp[l][r] * succ[cand[l, c]][r], pid(0) the anchor and pid(l) the walk's own previous pick. " @@ -696,18 +807,13 @@ static const RadOpSchema kSchemas[] = { /* ================================================================== the kernel table * - * Every row is domain HOST at priority 0, unconstrained except where the op's own structure needs - * a value the operands do not carry. That last clause is kv_store's `block_size`, and it is - * libref's rule for the same reason: the constraint admits every value and refuses only a query - * that does not NAME one, because an absent key fails a constraint and a cache cannot be walked - * without knowing its block edge. + * Every row is domain HOST at priority 0 and unconstrained, except `block_size` on attn_paged and + * kv_store (as in libref): the constraint admits any value but requires the key to be present, + * since the cache cannot be walked without the block edge. * - * SHAPE SAYS "any" ON EVERY ROW, and that is a claim about this plugin rather than a copied - * phrase: every extent is read off the operands (avx_common.h), so there is no geometry these - * refuse. Which ISA level runs is NOT part of the shape and deliberately does not appear in a - * constraint -- a row that said `avx512` would be a row that vanishes from the hierarchy on a - * machine without it, and the whole point of the dispatch is that the ROW is the same everywhere - * and only the instruction stream underneath it changes. */ + * Every row's shape is "any", since every extent is read from the operands (avx_common.h). The + * ISA level is deliberately not a constraint: rows are identical on every CPU and only the code + * underneath changes. */ #define SHAPE_ANY "any: every extent is read off the operands, strides included" #define ROW(nm, opname, fam, what, dts, cons, ncons, fn) \ @@ -717,11 +823,88 @@ static const RadOpSchema kSchemas[] = { #define SIMPLE(nm, opname, fam, what, dts, fn) ROW(nm, opname, fam, what, dts, nullptr, 0, fn) +/* ---- the codebook experts' layout hooks, on moe_gemm_q and moe_gemm_q_mod4 + * + * A codebook expert's codes view (`codes,table`) and two-level scale view (`scale,scale.1`) are + * stored joined (abi/rad_planes.h); a view of one plane is stored as it is. The selections + * accepted are libref's (libref/ref_moe.cpp: cb_check), so a weight libref refuses at declare is + * refused here too, and both libraries store the same bytes under one tag. */ +struct CbForm { int bits; int64_t group; uint32_t sdt; bool level; }; +static CbForm cb_form(const RadParam* p, int n_p) { + const RadParam* d = rad_param_find(p, n_p, "dtype"); + const char* s = d && d->kind == RAD_P_STR ? d->sval : nullptr; + if (s && !std::strcmp(s, "w4nla8h")) return CbForm{ 4, 128, RAD_BF16, false }; + if (s && !std::strcmp(s, "w4nl64a8h")) return CbForm{ 4, 64, RAD_F8E4M3, true }; + if (s && !std::strcmp(s, "w4nl32a8h")) return CbForm{ 4, 32, RAD_F8E4M3, true }; + if (s && !std::strcmp(s, "w5nl64a8h")) return CbForm{ 5, 64, RAD_F8E4M3, true }; + return CbForm{ 0, 0, 0, false }; +} +static int cb_check(const RadParam* p, int n_p, int operand, const RadEncoding* enc, + const int* sel, int n_planes) { + const CbForm f = cb_form(p, n_p); + const bool codes = operand == 2 || operand == 6 || operand == 8 || operand == 10; + const bool scale = operand == 3 || operand == 7 || operand == 9 || operand == 11; + if (!f.bits || (!codes && !scale) || !enc || !sel || n_planes != 2 || + std::strcmp(enc->transform, "fwht128") != 0) + return RAD_E_DTYPE; + for (int i = 0; i < 2; ++i) + if (sel[i] < 0 || sel[i] >= enc->n_planes) return RAD_E_SHAPE; + const RadEncPlane& a = enc->plane[sel[0]]; + const RadEncPlane& b = enc->plane[sel[1]]; + if (codes) + return !std::strcmp(a.role, "codes") && a.kind == RAD_PLANE_TILED && + a.dtype == (f.bits == 5 ? (uint32_t)RAD_U5 : (uint32_t)RAD_U4) && + a.block[0] == 1 && a.block[1] == 1 && !std::strcmp(b.role, "table") && + b.kind == RAD_PLANE_TABLE && b.dtype == RAD_F32 && b.extent[0] == 1 && + b.extent[1] == ((int64_t)1 << f.bits) + ? RAD_OK : RAD_E_DTYPE; + return f.level && !std::strcmp(a.role, "scale") && a.kind == RAD_PLANE_TILED && + a.dtype == f.sdt && a.block[0] == 1 && a.block[1] == f.group && + !std::strcmp(b.role, "scale.1") && b.kind == RAD_PLANE_TILED && b.dtype == RAD_F32 && + b.block[0] == 0 && b.block[1] == 0 + ? RAD_OK : RAD_E_DTYPE; +} +static int avx_moe_cb_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, + const int* sel, const RadTensor* planes, int n_planes, + RadLayout* out) { + if (n_planes <= 1) return RAD_E_UNSUPPORTED; + const int rc = cb_check(p, n_p, operand, enc, sel, n_planes); + return rc < 0 ? rc : rad_planes_layout(enc, sel, planes, n_planes, out); +} +static int avx_moe_cb_relayout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, + const int* sel, const RadTensor* planes, int n_planes, void* dst, + int64_t dst_bytes) { + if (n_planes <= 1) return RAD_E_UNSUPPORTED; + const int rc = cb_check(p, n_p, operand, enc, sel, n_planes); + return rc < 0 ? rc : rad_planes_relayout(enc, sel, planes, n_planes, dst, dst_bytes); +} +static int avx_moe_cb_unrelayout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, + const int* sel, const void* src, int64_t src_bytes, + const RadTensor* planes, int n_planes) { + if (n_planes <= 1) return RAD_E_UNSUPPORTED; + const int rc = cb_check(p, n_p, operand, enc, sel, n_planes); + return rc < 0 ? rc : rad_planes_unrelayout(enc, sel, src, src_bytes, planes, n_planes); +} + +#define ROW_CB(nm, opname, fam, what, dts, fn) \ + { nm, opname, fam, what, SHAPE_ANY, dts, RAD_DOMAIN_HOST, 0, \ + nullptr, 0, nullptr, 0, nullptr, nullptr, nullptr, fn, nullptr, avx_moe_cb_layout, \ + avx_moe_cb_relayout, nullptr, avx_moe_cb_unrelayout, nullptr } + +/* A row whose weight operands may be joined over several planes (avx_planes.h): libref's hooks for + * the op, restated, so both libraries store and read one form. */ +#define ROWL(nm, opname, fam, what, dts, fn, lay) \ + { nm, opname, fam, what, SHAPE_ANY, dts, RAD_DOMAIN_HOST, 0, \ + nullptr, 0, nullptr, 0, nullptr, nullptr, nullptr, fn, nullptr, avxp::lay, \ + avxp::avx_relayout_planes, nullptr, avxp::avx_unrelayout_planes, \ + nullptr } + #define DT_FLOAT "bf16 f16 f32 fp8_e4m3 fp8_e5m2 i8 i32, chosen per operand from its own dtype" #define DT_ANY "any dtype rad_types.h names, per operand" +#define DT_FLOAT_CB DT_FLOAT "; or u4 / u5 codes into an f32 table, joined (w4nl* / w5nl*)" -/* The launch is the baseline-compiled thunk, never the level's own symbol -- see avx_dispatch.cpp - * on why the row must be correct before rad_plugin_open has run. */ +/* Rows launch through the baseline-compiled thunks, which are valid before rad_plugin_open + * (avx_dispatch.cpp). */ #define L(nm) avx_thunk_##nm #define AVX_THUNK_DECL(nm) extern "C" int avx_thunk_##nm(const RadArgs*, RadStream); AVX_OP_LIST(AVX_THUNK_DECL) @@ -735,12 +918,16 @@ SIMPLE("avx_rmsnorm_add", "rmsnorm_add", "norm", "residual add then RMS norm", D L(rmsnorm_add)), SIMPLE("avx_hc_enter", "hc_enter", "norm", "gated residual entry: hc copies of x", DT_FLOAT, L(hc_enter)), -SIMPLE("avx_hc_read", "hc_read", "norm", - "gated residual read: grouped norm, low-rank gate, stream mix", DT_FLOAT, L(hc_read)), +ROWL("avx_hc_read", "hc_read", "norm", + "gated residual read: grouped norm, low-rank gate, stream mix", + DT_FLOAT ", or mixing matrices of E4M3 / int8 codes with a scale plane, joined", L(hc_read), + avx_layout_hc), SIMPLE("avx_hc_write", "hc_write", "norm", "gated residual write: h[s] += inj[s] * y", DT_FLOAT, L(hc_write)), -SIMPLE("avx_mtp_enter", "mtp_enter", "norm", - "MTP head entry: two norms, a per-sub-stream fc and a broadcast fc", DT_FLOAT, L(mtp_enter)), +ROWL("avx_mtp_enter", "mtp_enter", "norm", + "MTP head entry: two norms, a per-sub-stream fc and a broadcast fc", + DT_FLOAT ", or fc matrices of E4M3 / int8 codes with a scale plane, joined", L(mtp_enter), + avx_layout_mtp), SIMPLE("avx_layernorm", "layernorm", "norm", "layer norm with gain and bias", DT_FLOAT, L(layernorm)), SIMPLE("avx_grid_embed", "grid_embed", "elem", @@ -765,6 +952,12 @@ SIMPLE("avx_conv1d_dw", "conv1d_dw", "elem", "segment-wise causal depthwise conv DT_FLOAT, L(conv1d_dw)), SIMPLE("avx_rel_sinusoid", "rel_sinusoid", "elem", "sinusoidal relative-position table", DT_FLOAT, L(rel_sinusoid)), +SIMPLE("avx_conv2d_unfold", "conv2d_unfold", "elem", + "a convolution's receptive fields as rows, for a GEMM against its weight", + DT_FLOAT, L(conv2d_unfold)), +SIMPLE("avx_seg_sinusoid", "seg_sinusoid", "elem", + "sinusoidal absolute positions, restarting every `period` rows of a segment", + DT_FLOAT, L(seg_sinusoid)), SIMPLE("avx_attn_local_rel", "attn_local_rel", "attn", "local attention with a relative-position term and a softcap", DT_FLOAT, L(attn_local_rel)), @@ -795,8 +988,12 @@ SIMPLE("avx_softmax", "softmax", "elem", "row-wise softmax", DT_FLOAT, L(softmax SIMPLE("avx_scale_rows", "scale_rows", "elem", "one scalar per row, broadcast across the row", DT_FLOAT, L(scale_rows)), -SIMPLE("avx_quant_act_i8", "quant_act_i8", "quant", "symmetric int8 activation quantiser", +SIMPLE("avx_quant_act_i8", "quant_act_i8", "quant", + "symmetric int8 activation quantiser, one scale a row, codes in the WMMA step order", "float in, i8 out, f32 scale", L(quant_act_i8)), +SIMPLE("avx_quant_act_i8g", "quant_act_i8g", "quant", + "symmetric int8 activation quantiser, one scale per group, row-major", + "float in, i8 out, f32 scale", L(quant_act_i8g)), SIMPLE("avx_had_quant_act_i8", "had_quant_act_i8", "quant", "Walsh-Hadamard rotation then symmetric int8", "float in, i8 out, f32 scale", L(had_quant_act_i8)), @@ -835,8 +1032,9 @@ SIMPLE("avx_gated_quant_fp8", "gated_quant_fp8", "quant", SIMPLE("avx_gemm_nt", "gemm_nt", "gemm", "C = A B^T, f32 accumulate, cache-blocked", DT_FLOAT, L(gemm_nt)), SIMPLE("avx_gemm_nt_bias", "gemm_nt_bias", "gemm", "C = A B^T + bias", DT_FLOAT, L(gemm_nt_bias)), -SIMPLE("avx_gemm_nt_q", "gemm_nt_q", "gemm", "C = A B^T with group-scaled quantised operands", - "i8 / fp8 / float A; w4, w2, mxfp4, i8 or float B; f32 accumulate", L(gemm_nt_q)), +ROWL("avx_gemm_nt_q", "gemm_nt_q", "gemm", "C = A B^T with group-scaled quantised operands", + "i8 / fp8 / float A; w4, w2, mxfp4, i8 or float B; u2 / u4 / u5 codes with an f16 scale " + "and integer zero per group, joined; f32 accumulate", L(gemm_nt_q), avx_layout_gemm_q), SIMPLE("avx_gemm_nt_q_bias", "gemm_nt_q_bias", "gemm", "quantised C = A B^T + bias", "i8 / fp8 / float A; w4, w2, mxfp4, i8 or float B; f32 accumulate", L(gemm_nt_q_bias)), SIMPLE("avx_gemm_nt_q_gated", "gemm_nt_q_gated", "gemm", @@ -860,6 +1058,16 @@ SIMPLE("avx_qsa_block_key", "qsa_block_key", "attn", L(qsa_block_key)), SIMPLE("avx_qk_norm_rope", "qk_norm_rope", "attn", "per-head QK norm then rotary embedding", DT_FLOAT, L(qk_norm_rope)), +SIMPLE("avx_qsa_score", "qsa_score", "attn", + "QSA block scores: per-head relu dots summed over the heads", DT_FLOAT, L(qsa_score)), +SIMPLE("avx_qsa_select", "qsa_select", "attn", + "QSA selection: the top-k blocks as a page-id table, partial page last", + "f32 scores, i32 tables", L(qsa_select)), +SIMPLE("avx_qsa_tail_store", "qsa_tail_store", "attn", + "QSA tail: the raw keys of open blocks into a per-sequence ring", DT_FLOAT, + L(qsa_tail_store)), +SIMPLE("avx_qsa_work", "qsa_work", "attn", + "QSA work list: completing blocks' keys, pages and positions", DT_FLOAT, L(qsa_work)), SIMPLE("avx_router_topk", "router_topk", "moe", "softmax then exact top-k routing", DT_FLOAT, L(router_topk)), @@ -867,11 +1075,12 @@ SIMPLE("avx_moe_scatter", "moe_scatter", "moe", "stable counting sort of routing "i32 indices", L(moe_scatter)), SIMPLE("avx_moe_gemm", "moe_gemm", "moe", "grouped GEMM over the expert-sorted rows", DT_FLOAT, L(moe_gemm)), -SIMPLE("avx_moe_gemm_q", "moe_gemm_q", "moe", - "grouped GEMM over the expert-sorted rows, quantised operands", DT_FLOAT, L(moe_gemm_q)), -SIMPLE("avx_moe_gemm_q_mod4", "moe_gemm_q_mod4", "moe", +ROW_CB("avx_moe_gemm_q", "moe_gemm_q", "moe", + "grouped GEMM over the expert-sorted rows, quantised operands", DT_FLOAT_CB, + L(moe_gemm_q)), +ROW_CB("avx_moe_gemm_q_mod4", "moe_gemm_q_mod4", "moe", "grouped GEMM over the expert-sorted rows, quantised operands, four classes by number mod 4", - DT_FLOAT, L(moe_gemm_q_mod4)), + DT_FLOAT_CB, L(moe_gemm_q_mod4)), SIMPLE("avx_moe_gather", "moe_gather", "moe", "weighted scatter back to token order", DT_FLOAT, L(moe_gather)), SIMPLE("avx_row_topk", "row_topk", "moe", "exact per-row top-R", DT_FLOAT, L(row_topk)), @@ -880,9 +1089,10 @@ SIMPLE("avx_row_topk_merge", "row_topk_merge", "moe", SIMPLE("avx_pair_argmax", "pair_argmax", "moe", "the global top-1 of a row of gathered (id, value) pairs, one id a row", DT_FLOAT, L(pair_argmax)), -SIMPLE("avx_logit_rerank", "logit_rerank", "moe", - "R candidates a row rescored exactly against the full-precision head", DT_FLOAT, - L(logit_rerank)), +ROWL("avx_logit_rerank", "logit_rerank", "moe", + "R candidates a row rescored exactly against the full-precision head", + DT_FLOAT ", or a head of E4M3 / int8 codes with a scale plane, joined", L(logit_rerank), + avx_layout_head), SIMPLE("avx_gdn_conv_prep", "gdn_conv_prep", "gdn", "gdn prefill preamble: conv, split, l2 norm, gate cumsum, beta", DT_FLOAT, @@ -901,33 +1111,65 @@ SIMPLE("avx_gdn_conv_recurrent_update", "gdn_conv_recurrent_update", "gdn", SIMPLE("avx_gdn_gated_rmsnorm", "gdn_gated_rmsnorm", "gdn", "gated RMS norm over a head", DT_FLOAT, L(gdn_gated_rmsnorm)), -/* THE COLLECTIVES HAVE NO init/fini AND THAT IS NOT AN OVERSIGHT. libref's rows carry - * ref_collective_init because its all-reduce establishes a shared rendezvous across ranks in one - * process. libavx serves the ONE-RANK case only -- world_size 1, where an all-reduce is a copy and - * an all-gather is a copy -- and refuses anything wider by name rather than pretending. A - * multi-rank host collective is a real piece of work (shared memory, a barrier, an ordering rule) - * and it is not this plugin's: a CPU kernel library has no business owning the wire. */ +/* No init/fini on the collectives: unlike libref's (ref_collective_init sets up a cross-rank + * rendezvous), these serve world_size 1 only, where both are copies (see avx_misc.cpp). */ SIMPLE("avx_all_reduce", "all_reduce", "ar", "sum across ranks; world_size 1 only", DT_FLOAT, L(all_reduce)), SIMPLE("avx_all_gather", "all_gather", "ar", "gather every rank's shard; world_size 1 only", DT_FLOAT, L(all_gather)), +SIMPLE("avx_ln_mod", "ln_mod", "norm", "gainless layer norm times (1 + an entry's scale row)", + DT_FLOAT, L(ln_mod)), +SIMPLE("avx_gate_add", "gate_add", "elem", "x += tanh(gate row) * y", DT_FLOAT, L(gate_add)), +SIMPLE("avx_ln_mod_quant_fp8", "ln_mod_quant_fp8", "norm", + "gated residual, adaptive norm and the E4M3 quantiser in one pass", + "float in, fp8_e4m3 out, f32 scale, bf16 z", L(ln_mod_quant_fp8)), +SIMPLE("avx_timestep_embed", "timestep_embed", "elem", "sinusoidal timestep embedding", DT_FLOAT, + L(timestep_embed)), +SIMPLE("avx_gather_rows2", "gather_rows2", "elem", "rows from two sources by a signed index", + DT_ANY, L(gather_rows2)), +SIMPLE("avx_lane_gather", "lane_gather", "elem", "each entry's rows out of its lane", DT_ANY, + L(lane_gather)), +SIMPLE("avx_lane_store", "lane_store", "elem", "one source's rows into several lanes", DT_ANY, + L(lane_store)), +SIMPLE("avx_randn_lanes", "randn_lanes", "elem", "a lane's rows from its seed's normal stream", + DT_FLOAT, L(randn_lanes)), +SIMPLE("avx_flow_euler", "flow_euler", "elem", "a flow-matching Euler step with guidance", + DT_FLOAT, L(flow_euler)), +SIMPLE("avx_chan_affine", "chan_affine", "elem", "a per-channel affine from parameter lists", + DT_FLOAT, L(chan_affine)), +SIMPLE("avx_conv2d_nhwc", "conv2d_nhwc", "conv", + "an image convolution, channels innermost, as GEMMs over patch rows", DT_FLOAT, + L(conv2d_nhwc)), +SIMPLE("avx_l2norm_chan", "l2norm_chan", "norm", "unit-L2 channel norm, scaled, optional silu", + DT_FLOAT, L(l2norm_chan)), +SIMPLE("avx_d2s_add", "d2s_add", "elem", "an upsampling shortcut added in", DT_FLOAT, L(d2s_add)), +SIMPLE("avx_s2d_avg_add", "s2d_avg_add", "elem", "a downsampling shortcut added in", DT_FLOAT, + L(s2d_avg_add)), +SIMPLE("avx_to_rgba8", "to_rgba8", "elem", "decoded pixels to bytes", DT_FLOAT, L(to_rgba8)), +SIMPLE("avx_gelu_tanh", "gelu_tanh", "elem", "tanh gelu", DT_FLOAT, L(gelu_tanh)), +SIMPLE("avx_scatter_add_rows", "scatter_add_rows", "elem", "x[idx[i]] += v[i]", DT_FLOAT, + L(scatter_add_rows)), +SIMPLE("avx_attn_prefix_self", "attn_prefix_self", "attn", + "attention over a paged prefix and the step's own rows, flash-attention tiles", + "bf16 or f32 q, k, v and cache; int8 score form", L(attn_prefix_self)), + SIMPLE("avx_embed_lookup", "embed_lookup", "vocab", "embedding gather", DT_FLOAT, L(embed_lookup)), -/* THE ONE ROW WITH A LAYOUT HOOK, and it only checks: the table is read as it is stored, and the - * hook refuses a table encoded any other way (avx_ngram.cpp). An E4M3 table into bf16 goes through - * the row cache; every other dtype pair takes the general gather. Its init refuses a process that - * may not make the io_uring ring the cache's misses are read through, at declare and not at the - * first request. */ +/* Its layout hook only validates: the table is read as stored and other encodings are refused + * (avx_ngram.cpp). An E4M3 table into bf16 goes through the row cache; other dtype pairs take + * the general gather. The init hook refuses, at declare, a process that cannot create the + * io_uring ring the cache misses are read through. */ { "avx_embed_lookup_q", "embed_lookup_q", "vocab", "embedding gather, one scale for the table: an E4M3 table into bf16 through a shared row cache " "and direct reads of the container, a later call's rows read ahead", SHAPE_ANY, DT_ANY, RAD_DOMAIN_HOST, 0, nullptr, 0, nullptr, 0, nullptr, - /* INIT, fini, LAUNCH, scratch, layout, relayout, opd_shape, unrelayout */ + /* init, fini, launch, scratch, layout, relayout, opd_shape, unrelayout, replaces */ avx_init_ngram, nullptr, L(embed_lookup_q), nullptr, avx_layout_ngram, nullptr, nullptr, nullptr, - nullptr, nullptr }, -SIMPLE("avx_logits_gemm", "logits_gemm", "vocab", "the lm_head projection", DT_FLOAT, - L(logits_gemm)), + nullptr }, +ROWL("avx_logits_gemm", "logits_gemm", "vocab", "the lm_head projection", + DT_FLOAT ", or a head of E4M3 / int8 codes with a scale plane, joined", L(logits_gemm), + avx_layout_head), SIMPLE("avx_sample_penalties", "sample_penalties", "sample", "repetition, frequency and presence penalties", DT_FLOAT, L(sample_penalties)), @@ -954,6 +1196,8 @@ SIMPLE("avx_sample_pick", "sample_pick", "sample", "seeded inverse-CDF draw", DT SIMPLE("avx_sample_argmax", "sample_argmax", "sample", "greedy pick", DT_FLOAT, L(sample_argmax)), SIMPLE("avx_sample_logprobs", "sample_logprobs", "sample", "the raw distribution's summary", DT_FLOAT, L(sample_logprobs)), +SIMPLE("avx_dflash_conv", "dflash_conv", "draft", + "DFlash2 grouped dynamic depthwise convolution", DT_FLOAT, L(dflash_conv)), SIMPLE("avx_dflash_select", "dflash_select", "draft", "DFlash2's greedy walk over the candidate lattice", "i32 candidates and tokens, float unary and codebooks", L(dflash_select)), @@ -965,10 +1209,9 @@ static const RadPluginInfo kInfo = { "libavx", "0.1.0", "the conventional op vocabulary in hand-written x86 SIMD, dispatched by CPU feature at load: " - "scalar / AVX / AVX2+FMA / AVX-512. Same ops as libref, same schemas, same answers to a " - "tolerance -- the difference is the instruction stream", - /* NOT a -march string. The binary runs everywhere x86-64 runs and picks its own path, so a - * build_target naming one machine would be a claim the plugin does not make. */ + "scalar / AVX / AVX2+FMA / AVX-512. Same ops and schemas as libref, the same answers to a " + "tolerance", + /* Not a -march string: the binary runs on any x86-64 and picks its own path at load. */ "host" }; diff --git a/libavx/avx_rows.h b/libavx/avx_rows.h index d54ccb42..3cae2cbb 100644 --- a/libavx/avx_rows.h +++ b/libavx/avx_rows.h @@ -1,13 +1,11 @@ -/* avx_rows.h -- the quantised embedding gather's two halves: the row source, compiled once at the - * baseline, and the row decode, compiled per ISA level. +/* avx_rows.h -- the quantised embedding gather, split in two: the row source, compiled once at + * the baseline, and the row decode, compiled per ISA level. * - * embed_lookup_q over an E4M3 table into bf16 is a gather of rows that are, most of the time, not in - * memory at all: the n-gram table it exists for is tens of gigabytes in a container that is mapped - * and never loaded. Getting the bytes is the whole cost and is the same work at every ISA level -- - * a row cache every thread shares, direct reads for its misses, a reader thread that runs a step - * ahead -- so that half is avx_ngram.cpp, compiled baseline, with one row cache for the process - * whatever level runs. Turning a row's codes into bf16 is the half that differs per level, so the - * level's kernel hands its own decoder in. */ + * embed_lookup_q over an E4M3 table into bf16 serves the n-gram table, tens of gigabytes in a + * mapped container that is never loaded, so fetching the rows is the whole cost. That half (a + * shared row cache, direct reads for misses, a reader thread one step ahead) is the same at every + * level and lives in avx_ngram.cpp, with one row cache per process. Decoding codes to bf16 differs + * per level, so each level's kernel passes its own decoder. */ #ifndef RAD_AVX_ROWS_H #define RAD_AVX_ROWS_H @@ -47,13 +45,12 @@ int row_gather(const RowGather& g, RowDecode decode); } /* namespace avx */ -/* What the table must be: the E4M3 plane with ONE scale, or a plain bf16 one, stored as it is - * (avx_ngram.cpp). */ +/* The table must be an E4M3 plane with one scale, or plain bf16, stored as is (avx_ngram.cpp). */ extern "C" int avx_layout_ngram(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int, RadLayout*); -/* Whether this process can read the table's rows: refused, with the reason on stderr, where it may - * not make an io_uring ring (avx_ngram.cpp). */ +/* Refuses, with the reason on stderr, when this process may not create an io_uring ring and so + * cannot read the table's rows (avx_ngram.cpp). */ extern "C" int avx_init_ngram(const RadParam*, int, int, int, void**); #endif /* RAD_AVX_ROWS_H */ diff --git a/libavx/avx_sample.cpp b/libavx/avx_sample.cpp index 1297e292..5f037ad8 100644 --- a/libavx/avx_sample.cpp +++ b/libavx/avx_sample.cpp @@ -1,45 +1,27 @@ /* avx_sample.cpp -- the sampler ops. * - * ============================== THESE ARE NOT WHERE THE TIME GOES, EXCEPT WHERE THEY ARE ============================== + * Most of these work over a candidate set of at most about a thousand entries, where the cost is + * control flow; they widen candidate values to f32 once and otherwise keep libref's structure. The + * three that touch the whole vocabulary (a megabyte per row at 248K) are vectorised: * - * Eleven of these twelve ops work over a CANDIDATE SET of a thousand entries at most, and their - * cost is control flow rather than arithmetic. Vectorising them would be work spent where no time - * is; what they get here is the one thing that does matter -- the candidate values widened once - * into f32 so the per-element dtype switch is gone -- and otherwise the reference's structure, - * which is legible and provably right. + * sample_temp a row multiply. + * sample_argmax maximum, lowest index on a tie, through the same `topk_next_f32` the routers + * use, so greedy and top-1 agree on ties (a greedy request is staged at + * top_k = 1 when lm_head is vocab-sharded). + * sample_mask a vocabulary bitmask. At AVX-512 a grammar half-word is a `__mmask16`, so 16 + * tokens take one masked store of -inf; lower levels shift and test per token. * - * The exceptions are the three that touch the WHOLE VOCABULARY, and at a 248K vocabulary that is a - * megabyte a row: + * Per-request settings (`rep`, `freq`, `pres`, `k`, `p`, seed, position) are fields of a params row + * (abi/rad_sample.h), not op parameters: parameters are geometry fixed at declare, so they could + * not differ between requests in one batch. * - * sample_temp a row multiply. Pure vector work, and the trivial one. - * sample_argmax a maximum with the LOWEST index on a tie. Vectorised through the same - * `topk_next_f32` the routers use, so the greedy path and a top-1 path cannot - * disagree about a tie -- which they must not, because a greedy request is - * staged at top_k = 1 when lm_head is vocab-sharded. - * sample_mask a bitmask over the vocabulary. This one has an AVX-512 form that is not - * available below it and is worth the `#if`: the mask word IS a `__mmask16`, - * so applying 16 tokens of grammar is one masked store of -inf and no shifts at - * all. Below AVX-512 it is a shift and a test per token. + * Candidate set: `sample_topk` writes a fixed-width set and the narrowing stages edit it in place. + * A dropped candidate is index -1, value -infinity; kept candidates stay in place, in descending + * order. `cand_val` holds logits, and each stage takes its own softmax over the set (as llama.cpp + * does), so stages compose in any order. * - * ============================== EVERY SCALAR IS PER ROW ============================== - * - * `rep`, `freq`, `pres`, `k`, `p`, the seed and the position are FIELDS OF A ROW (abi/rad_sample.h), - * not parameters. A parameter is geometry -- frozen at declare, matched on by the selector -- so - * two requests in one batch with different top_p would be two resolutions of one op and a - * deployment would have exactly one top_p, which is not a sampler. - * - * ============================== THE CANDIDATE SET ============================== - * - * `sample_topk` produces a FIXED-WIDTH set and the narrowing stages work IN PLACE. The tensors do - * not shrink, so a dropped candidate needs a spelling: index -1, value -infinity. Kept candidates - * stay where they are, in descending order. - * - * `cand_val` carries LOGITS, not probabilities, and each narrowing stage takes its own softmax over - * the set -- which is what llama.cpp does and what keeps the stages composable in any order. - * - * A GREEDY ROW (RAD_SP_GREEDY) HAS NO CANDIDATES: its token is sample_argmax's, top-k and the - * merge write it an empty set, the narrowing stages leave it alone and the pick does not touch its - * token -- libref's contract, for the reason given there. + * A greedy row (RAD_SP_GREEDY) has no candidates: its token comes from sample_argmax, top-k and the + * merge write it an empty set, and the narrowing stages and the pick skip it (libref's contract). */ #include "avx_vec.h" #include "avx_common.h" @@ -50,15 +32,10 @@ using namespace avx; -/* The params operand, checked once. A sampler op with no rows to act on is not an error -- it is a - * step in which nothing asked for that stage. - * - * The row array is a BYTE BLOB viewed through a 32-bit dtype: the sampler declares it - * [rows, sizeof(RadSampleParams)/4] u32, which is the only way the builder can express "this many - * bytes a row". The dtype is REQUIRED to be a 32-bit one rather than run through - * rad_dtype_bytes -- "any width as long as the arithmetic works out" is the wrong contract, since - * the blob is addressed as 32-bit words and a 16-bit view would pass a byte count and then misread - * every row. */ +/* Validates the params operand. A row array is a byte blob declared as + * [rows, sizeof(RadSampleParams)/4] u32 (the builder's only way to say "this many bytes a row"), so + * the dtype must be a 32-bit one; a 16-bit view would pass a byte-count check and misread every + * row. */ struct Rows { const RadSampleParams* p; int64_t n; }; static inline int rows_of_params(const RadTensor* t, int64_t M, Rows* out) { @@ -72,10 +49,10 @@ static inline int rows_of_params(const RadTensor* t, int64_t M, Rows* out) { #define AVX_TRY(expr) do { const int _s = (expr); if (_s < 0) return _s; } while (0) -/* The history window both history stages read, libref's reading (ref_sample.cpp): `hist_off` and - * `hist_len` address the row's own row of the history plane, clamped to it, and `last_n` keeps - * the TAIL of that span. last_n 0 turns the stage off for the row, a negative one keeps the whole - * span -- llama.cpp's meaning for repeat_last_n and dry_penalty_last_n. */ +/* History window for the penalty and DRY stages, as in libref (ref_sample.cpp): `hist_off` and + * `hist_len` address this row of the history plane, clamped to it, and `last_n` keeps the tail of + * that span. last_n 0 disables the stage for the row; negative keeps the whole span (llama.cpp's + * repeat_last_n / dry_penalty_last_n). */ static inline bool hist_window(const RadSampleParams& sp, int32_t last_n, int64_t hmax, int64_t* ho_out, int64_t* hl_out) { if (last_n == 0) return false; @@ -95,20 +72,17 @@ static inline bool hist_window(const RadSampleParams& sp, int32_t last_n, int64_ /* ------------------------------------------------------------------ sample_penalties */ /* llama.cpp's ordering, in one pass over the row's history: * - * repetition logit = logit > 0 ? logit / rep : logit * rep (once per DISTINCT token) + * repetition logit = logit > 0 ? logit / rep : logit * rep (once per distinct token) * frequency logit -= count * freq * presence logit -= pres (once per distinct token) * - * The repetition penalty being multiplicative and SIGN-DEPENDENT is the part everyone gets wrong: - * dividing a negative logit would make it larger, so it is multiplied instead. + * The repetition penalty is sign-dependent: dividing a negative logit would raise it. * - * The history is pulled into a small int array once. libref reads it back through ld_int inside - * the O(hl^2) first-occurrence test, which is a dtype switch per comparison on a loop that runs - * hl^2 times; the array makes the inner test an integer compare. The ORDER and the answer are - * unchanged -- this is the same quadratic scan, over the same values. + * The history is copied into an int array once, so libref's O(hl^2) first-occurrence scan + * compares integers instead of switching on dtype; same scan, same result. * - * History ids are GLOBAL and the logits row is this rank's shard, so a token's column is its id - * less `vocab_off`, and a token outside the shard is another rank's to penalise. */ + * History ids are global and the logits row is this rank's shard: a token's column is its id minus + * `vocab_off`, and tokens outside the shard belong to another rank. */ AVX_KERNEL(sample_penalties) { if (!rad_args_have(a, 3)) return RAD_E_INVAL; const RadTensor *lg = &a->t[0], *pr = &a->t[1], *hist = &a->t[2]; @@ -142,8 +116,7 @@ AVX_KERNEL(sample_penalties) { const int32_t tok = h[i]; const int64_t col = (int64_t)tok - voff; if (tok < 0 || col < 0 || col >= n_vocab) continue; - /* First occurrence only: the penalties are per distinct token, and the count is what - * carries the multiplicity. */ + /* First occurrence only; `count` carries the multiplicity. */ bool first = true; int64_t count = 0; for (int64_t j = 0; j < hl; ++j) { @@ -163,18 +136,15 @@ AVX_KERNEL(sample_penalties) { } /* ------------------------------------------------------------------ sample_dry */ -/* DRY -- "don't repeat yourself". libref's definition (ref_sample.cpp), which is llama.cpp's: - * each token that would EXTEND a suffix of the window that has occurred before is penalised ONCE, - * by multiplier * base^(L - allowed_length) for the LONGEST repeat L it would extend, repeats - * capped at the row's `dry_rep_limit`. A position the optional `breakers` plane marks holds a - * whole sequence breaker, which is never penalised. The penalty is formed by repeated - * multiplication stopping short of overflow, the way every implementation of this op forms it, - * so they agree to the bit. +/* DRY ("don't repeat yourself"), as in libref (ref_sample.cpp) and llama.cpp: each token that + * would extend a previously seen suffix of the window is penalised once, by + * multiplier * base^(L - allowed_length) for the longest repeat L it extends, with repeats capped at + * the row's `dry_rep_limit`. Positions marked in the optional `breakers` plane hold sequence + * breakers and are never penalised. The penalty is built by repeated multiplication that stops + * short of overflow, as other implementations do, so results agree to the bit. * - * The window is pulled into an int array once, as the penalties do, and the per-position repeat - * lengths go into a second one; the longest per token is then found by scanning those lengths for - * each qualifying position, which needs no map and keeps the quadratic scan's memory access - * inside two small arrays. */ + * The window and the per-position repeat lengths are kept in two int arrays; the longest repeat + * per token is found by scanning them, with no map. */ static inline float dry_penalty(float multiplier, float base, int64_t e) { float pen = multiplier; if (base == 1.0f) return pen; @@ -222,9 +192,8 @@ AVX_KERNEL(sample_dry) { int32_t* len = (int32_t*)scratch_f32_b((size_t)hl); for (int64_t i = 0; i < hl; ++i) h[i] = (int32_t)ldi(hist, hb + i * hs); - /* len[j]: how long a suffix of the window also ends at position j, capped; 0 where the - * continuation after j is exempt or outside this rank's shard, since such a j is never - * penalised and never the longest for a token that is. */ + /* len[j]: length of the window suffix that also ends at j, capped; 0 when the token + * after j is a breaker or outside this rank's shard. */ for (int64_t j = 0; j + 1 < hl; ++j) { const int64_t lim = j + 1 < cap ? j + 1 : cap; int64_t n = 0; @@ -238,9 +207,7 @@ AVX_KERNEL(sample_dry) { const float base = sp.dry_base > 0.0f ? sp.dry_base : 1.75f; for (int64_t j = 0; j + 1 < hl; ++j) { if (len[j] < allowed) continue; - /* The representative of this continuation token: its longest repeat, the earliest - * position on a tie. Every other position of the same token defers to it, so the - * token is penalised once. */ + /* Penalise each token once, at its longest repeat (earliest position on a tie). */ const int32_t next = h[j + 1]; bool rep = true; for (int64_t j2 = 0; j2 + 1 < hl && rep; ++j2) { @@ -256,8 +223,7 @@ AVX_KERNEL(sample_dry) { } /* ------------------------------------------------------------------ sample_temp */ -/* temp <= 0 leaves the row untouched: greedy decoding is `sample_argmax`, and a temperature of - * zero silently meaning something else is how a sampler chain becomes unreadable. */ +/* temp <= 0 leaves the row untouched; greedy decoding is `sample_argmax`. */ AVX_KERNEL(sample_temp) { if (!rad_args_have(a, 2)) return RAD_E_INVAL; const RadTensor *lg = &a->t[0], *pr = &a->t[1]; @@ -300,24 +266,21 @@ AVX_KERNEL(sample_topk) { if (M <= 0) return RAD_E_SHAPE; Rows R; AVX_TRY(rows_of_params(pr, M, &R)); - /* The candidate WIDTH is the buffer's, not the request's: it is the deployment bound the arena - * was sized for, and every later stage reads it. */ + /* The candidate width is the buffer's (the deployment bound), not the request's top_k. */ const int64_t n_cand = ci->rank >= 2 ? ci->shape[ci->rank - 1] : numel(ci) / M; if (n_cand <= 0 || numel(cv) < M * n_cand) return RAD_E_SHAPE; - /* THE VOCAB-PARALLEL PAIR PLANE, optional. cand_idx stays LOCAL -- it indexes this rank's - * logits row and every stage after top-k reads it that way -- and `pairs` carries the same - * candidates with `vocab_off` added, as (u32 GLOBAL id, f32 logit), which is what the - * all-gather moves and what sample_merge_topk reads. */ + /* Optional vocab-parallel pair plane. cand_idx stays local (it indexes this rank's logits); + * `pairs` holds the same candidates as (u32 global id = local + vocab_off, f32 logit bits), + * which the all-gather moves and sample_merge_topk reads. */ const RadTensor* pp = a->n_t > 4 && a->t[4].data ? &a->t[4] : nullptr; const int64_t voff = p_int(a, "vocab_off", 0); if (pp && numel(pp) < M * 2 * n_cand) return RAD_E_SHAPE; AVX_PARALLEL_FOR_IF(M * n_vocab >= AVX_PAR_MIN) for (int64_t m = 0; m < M; ++m) { - /* A row's own top_k, clamped to the buffer. 0 or negative means "the whole candidate - * width", which is what a request that set no top_k asks for. A greedy row takes none, - * and its row of logits is not even read. */ + /* The row's top_k, clamped to the buffer; <= 0 means the full width. A greedy row takes + * none and its logits are not read. */ int64_t k = R.p[m].top_k; if (k <= 0 || k > n_cand) k = n_cand; if (R.p[m].flags & RAD_SP_GREEDY) k = 0; @@ -335,8 +298,7 @@ AVX_KERNEL(sample_topk) { st_int_dt(ci->dtype, ci->data, ib + r * is, ok ? pi : -1); stt(cv, vb + r * vs, ok ? pv : -INFINITY); if (!pp) continue; - /* 0xffffffff is the hole, which the merge tests as a negative signed id -- the same - * convention cand_idx carries as -1. */ + /* 0xffffffff marks a hole; the merge reads it as a negative id (cand_idx's -1). */ uint32_t bits; const float val = ok ? pv : -INFINITY; std::memcpy(&bits, &val, 4); @@ -350,17 +312,12 @@ AVX_KERNEL(sample_topk) { /* ================================================================== the narrowing stages * - * All four widen the candidate values into f32 ONCE and then work on that array, which is the only - * change from libref's structure: it reads `cand_val` back through `ldt` inside loops that are - * O(n_cand) (top-p, min-p, XTC) and O(n_cand^2) (typical), so the dtype switch runs up to a - * million times on a thousand-wide set for one row. + * Unlike libref, which reads `cand_val` through `ldt` inside O(n_cand) and O(n_cand^2) loops, all + * four widen the candidate values to f32 once. Otherwise libref's structure is kept. * - * The typical stage additionally precomputes the probability and the surprisal distance per - * candidate, because libref recomputes `exp` and `log` inside its threshold search -- three libm - * calls per (candidate, candidate) pair. The search itself stays O(n_cand^2) and stays exactly the - * scan libref performs, because the answer is a threshold chosen among the distances that actually - * occur and any faster search would have to sort, which changes which of two equal distances is - * found first. */ + * The typical stage also precomputes each candidate's probability and surprisal distance (libref + * recomputes exp and log inside the threshold search). The search stays libref's O(n_cand^2) scan: + * a faster one would sort, which could change which of two equal distances is found first. */ enum Narrow { NR_TOPP, NR_MINP, NR_TYPICAL, NR_XTC }; static int narrow(const RadArgs* a, Narrow which) { @@ -400,39 +357,34 @@ static int narrow(const RadArgs* a, Narrow which) { if (which == NR_MINP) { const float p = sp.min_p; if (!(p > 0.0f)) continue; - /* Keep everything within a factor p of the most likely candidate. Comparing - * exp(v - max) against p is the same test as prob >= p * max_prob without forming the - * normaliser -- one fewer pass and one fewer rounding. */ + /* Keep candidates within a factor p of the most likely. exp(v - max) >= p is + * prob >= p * max_prob without the normaliser. */ for (int64_t i = 0; i < n_cand; ++i) { if (!alive[i]) continue; if (val[i] == mx) continue; /* the max always survives */ - if (std::exp(val[i] - mx) < p) drop(i); + if (sc_exp(val[i] - mx) < p) drop(i); } continue; } float sum = 0.0f; - for (int64_t i = 0; i < n_cand; ++i) if (alive[i]) sum += std::exp(val[i] - mx); + for (int64_t i = 0; i < n_cand; ++i) if (alive[i]) sum += sc_exp(val[i] - mx); const float inv = sum > 0.0f ? 1.0f / sum : 0.0f; for (int64_t i = 0; i < n_cand; ++i) - prob[i] = alive[i] ? std::exp(val[i] - mx) * inv : 0.0f; + prob[i] = alive[i] ? sc_exp(val[i] - mx) * inv : 0.0f; if (which == NR_TOPP) { const float p = sp.top_p; if (!(p < 1.0f) || !(p > 0.0f)) continue; - /* The candidates arrive in DESCENDING order from sample_topk and this op does not - * re-sort them. Keep the shortest prefix whose cumulative probability reaches p, and - * always keep at least one -- a p small enough to select nothing still has to produce - * a token. */ + /* Candidates arrive in descending order from sample_topk and are not re-sorted. Keep + * the shortest prefix whose cumulative probability reaches p, at least one. */ float cum = 0.0f; bool done = false; - int64_t kept = 0; for (int64_t i = 0; i < n_cand; ++i) { if (!alive[i]) continue; if (done) { drop(i); continue; } cum += prob[i]; - ++kept; - if (cum >= p && kept >= 1) done = true; + if (cum >= p) done = true; } continue; } @@ -441,17 +393,16 @@ static int narrow(const RadArgs* a, Narrow which) { const float p = sp.typical_p; if (!(p < 1.0f) || !(p > 0.0f)) continue; /* Locally typical sampling: keep the candidates whose surprisal -log(prob) is closest - * to the distribution's entropy, until their mass reaches p. The candidate order is by - * probability and this order is by |surprisal - H|, so the two disagree and the - * selection is a threshold on the distance rather than a prefix. Ties are kept, which - * can overshoot p slightly -- the alternative is an order that depends on the + * to the entropy H until their mass reaches p. This orders by |surprisal - H|, not by + * probability, so the selection is a distance threshold rather than a prefix. Ties at + * the threshold are all kept (may overshoot p), so the result does not depend on * candidate index. */ float H = 0.0f; for (int64_t i = 0; i < n_cand; ++i) - if (alive[i] && prob[i] > 0.0f) H -= prob[i] * std::log(prob[i]); - float* dist = val; /* `val` is dead from here: the distances reuse its storage. */ + if (alive[i] && prob[i] > 0.0f) H -= prob[i] * sc_log(prob[i]); + float* dist = val; /* `val` is dead here; reuse its storage. */ for (int64_t i = 0; i < n_cand; ++i) - dist[i] = (alive[i] && prob[i] > 0.0f) ? std::fabs(-std::log(prob[i]) - H) : 0.0f; + dist[i] = (alive[i] && prob[i] > 0.0f) ? std::fabs(-sc_log(prob[i]) - H) : 0.0f; float cut = 0.0f; bool have_cut = false; @@ -473,11 +424,9 @@ static int narrow(const RadArgs* a, Narrow which) { continue; } - /* XTC -- "exclude top choices". With probability `xtc_probability`, DROP every candidate - * above `xtc_threshold` except the LEAST likely of them, which is the opposite of every - * other stage here and is the point: it removes the obvious continuations and leaves the - * interesting one. The draw is per row and comes from the row's own stream, so it - * reproduces. */ + /* XTC ("exclude top choices"): with probability `xtc_probability`, drop every candidate + * above `xtc_threshold` except the least likely of them. The draw comes from the row's + * own random stream, so it is reproducible. */ { if (!(sp.xtc_probability > 0.0f) || !(sp.xtc_threshold > 0.0f)) continue; if (rad_sample_uniform01(sp.seed ^ RAD_SAMPLE_KEY_XTC, sp.pos) >= sp.xtc_probability) @@ -487,8 +436,7 @@ static int narrow(const RadArgs* a, Narrow which) { if (!alive[i]) continue; if (prob[i] >= sp.xtc_threshold) { last_above = i; ++n_above; } } - /* Nothing to do unless at least two candidates clear the threshold: dropping the only - * one would leave the row without its own choice. */ + /* Needs at least two candidates above the threshold. */ if (n_above < 2) continue; for (int64_t i = 0; i < n_cand; ++i) { if (!alive[i] || i == last_above) continue; @@ -505,18 +453,13 @@ AVX_KERNEL(sample_typical) { return narrow(a, NR_TYPICAL); } AVX_KERNEL(sample_xtc) { return narrow(a, NR_XTC); } /* ------------------------------------------------------------------ sample_mask */ -/* Where a GBNF grammar lands. The state machine stays on host and what crosses is a token bitmask - * per sequence -- 19 KiB at a 151K vocab, cheap enough to upload every step. +/* Applies a GBNF grammar's token bitmask (the state machine runs on the host; the mask is 19 KiB + * per sequence at a 151K vocab). A set bit means allowed. Word w bit b covers token 32*w + b, LSB + * first. * - * A SET BIT MEANS ALLOWED. That polarity has to be stated: a grammar produces a set of admissible - * tokens, and the mask is that set rather than its complement. Word w bit b covers token 32*w + b, - * least significant bit first. - * - * THE AVX-512 FORM IS DIFFERENT IN KIND, not just in width, and that is why it gets an `#if`. A - * `__mmask16` IS sixteen bits of the grammar word, so applying sixteen tokens is one masked store - * of -inf with the mask inverted -- no shift, no test, no branch per token. Below AVX-512 the mask - * has to be materialised as a vector of 0/-1 and blended, which costs more than the shift-and-test - * it replaces at these widths, so those levels keep the scalar loop and say so. */ + * At AVX-512 sixteen bits of a mask word are a `__mmask16`, so sixteen tokens take one masked store + * of -inf with the mask inverted. Below AVX-512 the mask would have to be expanded to a 0/-1 vector + * and blended, which costs more than the scalar shift-and-test. */ AVX_KERNEL(sample_mask) { if (!rad_args_have(a, 3)) return RAD_E_INVAL; const RadTensor *lg = &a->t[0], *pr = &a->t[1], *bm = &a->t[2]; @@ -548,8 +491,7 @@ AVX_KERNEL(sample_mask) { int64_t i = 0; for (; i + 32 <= n_vocab; i += 32) { const uint32_t bits = w[i / 32]; - /* The mask is the COMPLEMENT: a set grammar bit is allowed and must be left - * alone, so -inf is stored where the bit is clear. */ + /* Store -inf where the grammar bit is clear. */ _mm512_mask_storeu_ps(p + i, (__mmask16)(~(uint16_t)(bits & 0xffffu)), neg); _mm512_mask_storeu_ps(p + i + 16, (__mmask16)(~(uint16_t)(bits >> 16)), neg); } @@ -567,15 +509,12 @@ AVX_KERNEL(sample_mask) { } /* ------------------------------------------------------------------ sample_pick */ -/* The inverse CDF, walked in candidate order, accumulating in f32. The fallback is the LAST - * CANDIDATE ABOVE -INFINITY: `u` is strictly below 1 and the probabilities sum to 1 in exact - * arithmetic, but they do not in f32, and a draw that falls through the last comparison must still - * produce a token the distribution allows -- not one of the grammar-masked candidates that top-k - * leaves at -infinity at the tail of the set. A greedy row is skipped: its token is the argmax's. +/* Inverse CDF in candidate order, accumulated in f32. If rounding lets `u` (< 1) fall through, + * the fallback is the last candidate above -infinity, never a grammar-masked one top-k left at + * -infinity at the tail. Greedy rows are skipped (their token is the argmax's). * - * THE DRAW IS SPECIFIED rather than left to a library (abi/rad_sample.h): splitmix64 over - * (seed * golden ratio + pos), 24 bits as a float in [0, 1). The same stream has to come out of a - * host reference, a device kernel and a rerun. */ + * The draw is specified (abi/rad_sample.h): splitmix64 over (seed * golden ratio + pos), 24 bits as + * a float in [0, 1), so host, device and reruns produce the same stream. */ AVX_KERNEL(sample_pick) { if (!rad_args_have(a, 4)) return RAD_E_INVAL; const RadTensor *ci = &a->t[0], *cv = &a->t[1], *pr = &a->t[2], *tok = &a->t[3]; @@ -603,7 +542,7 @@ AVX_KERNEL(sample_pick) { float sum = 0.0f; for (int64_t i = 0; i < n_cand; ++i) { if (ldi(ci, ib + i * is) < 0) continue; - sum += std::exp(ldt(cv, vb + i * vs) - mx); + sum += sc_exp(ldt(cv, vb + i * vs) - mx); } const float inv = sum > 0.0f ? 1.0f / sum : 0.0f; const float u = rad_sample_uniform01(R.p[m].seed ^ RAD_SAMPLE_KEY_PICK, R.p[m].pos); @@ -615,7 +554,7 @@ AVX_KERNEL(sample_pick) { if (id < 0) continue; const float v = ldt(cv, vb + i * vs); if (v > -INFINITY) last = id; - cum += std::exp(v - mx) * inv; + cum += sc_exp(v - mx) * inv; if (u < cum) { chosen = id; break; } } st_int_dt(tok->dtype, tok->data, offlin(tok, m), chosen >= 0 ? chosen : last); @@ -624,12 +563,9 @@ AVX_KERNEL(sample_pick) { } /* ------------------------------------------------------------------ sample_argmax */ -/* Greedy, ties to the LOWER token id -- the same tie rule the top-k selection uses, so a greedy - * step and a top-1 step cannot disagree. That is not decoration: when lm_head is vocab-sharded, - * `sample_argmax` is unusable (its answer is a LOCAL column) and a greedy request is staged at - * top_k = 1 through the chain instead, so the two paths must select the same token. - * - * Run through the same `topk_next_f32` the routers use, for exactly that reason. */ +/* Greedy, ties to the lower token id, through the same `topk_next_f32` as top-k. When lm_head is + * vocab-sharded this op is unusable (its answer is a local column) and greedy requests run at + * top_k = 1 instead, so both paths must pick the same token. */ AVX_KERNEL(sample_argmax) { if (!rad_args_have(a, 3)) return RAD_E_INVAL; const RadTensor *lg = &a->t[0], *tok = &a->t[2]; @@ -651,20 +587,18 @@ AVX_KERNEL(sample_argmax) { } /* ------------------------------------------------------------------ sample_logprobs */ -/* The raw distribution's summary for a row with RAD_SP_LOGPROBS -- max, sum of exp(l - max), and - * the k largest as (id, logit) pairs, descending, ties to the lower id -- libref's contract - * (ref_sample.cpp). A row without the flag is not written. +/* For rows with RAD_SP_LOGPROBS: max, sum of exp(l - max), and the k largest as (id, logit) + * pairs, descending, ties to the lower id (libref's contract, ref_sample.cpp). Other rows are not + * written. * - * ONE PASS FOR THE k LARGEST, not k passes of topk_next_f32: `k` is the deployment's width (the - * largest top_logprobs any request may ask for), and k full sweeps of a 248K row would cost k times - * the argmax. The set is seeded with the row's first k columns, kept sorted, and the rest of the - * row is compared a vector at a time against its smallest value; a lane strictly above it is - * inserted. Strictly, because the scan runs in increasing id, and an equal value further along has - * the higher id and loses the tie. After the first few thousand columns almost no vector has such - * a lane, so the pass costs what the maximum does. + * One pass for the k largest instead of k passes of topk_next_f32 (`k` is the deployment's maximum + * top_logprobs). A sorted set is seeded with the first k columns; the rest of the row is compared + * a vector at a time against the set's smallest value, and lanes strictly above it are inserted. + * Strictly, because ids increase along the scan and an equal later value loses the tie. Few vectors + * pass the test after the first few thousand columns. * - * The sum is f32 in four vector accumulators. Its terms are all in (0, 1] and the relative error - * of the sum is what a logprob carries (log of it), so f32 is ample next to libref's double. */ + * The sum is f32 in four accumulators. Its terms are in (0, 1] and a logprob carries only its + * relative error, so f32 suffices (libref uses double). */ AVX_KERNEL(sample_logprobs) { if (!rad_args_have(a, 3)) return RAD_E_INVAL; const RadTensor *lg = &a->t[0], *pr = &a->t[1], *st = &a->t[2]; @@ -700,7 +634,7 @@ AVX_KERNEL(sample_logprobs) { } for (; i + VF_N <= n_vocab; i += VF_N) s0 = vf_add(s0, vf_exp(vf_sub(vf_loadu(v + i), vmx))); sum = vf_hsum(vf_add(vf_add(s0, s1), vf_add(s2, s3))); - for (; i < n_vocab; ++i) sum += std::exp(v[i] - mx); + for (; i < n_vocab; ++i) sum += sc_exp(v[i] - mx); } /* Insert (x, id) into the sorted set of n entries, the set at most k long. */ @@ -745,22 +679,17 @@ AVX_KERNEL(sample_logprobs) { } /* ------------------------------------------------------------------ sample_merge_topk */ -/* THE VOCAB-PARALLEL MERGE. lm_head is vocab-sharded, so each rank runs top-k over ITS OWN shard - * and the candidate sets are all-gathered -- k * world_size pairs, 2 KiB at k=64 and world_size=4, - * against the ~77 MiB a full-logits gather would move. +/* Vocab-parallel merge. With lm_head vocab-sharded, each rank runs top-k over its own shard and the + * candidate sets are all-gathered: k * world_size pairs (2 KiB at k=64, world_size=4) instead of + * the full logits. * - * `gathered` is [M, world_size * n_cand] pairs of (token id, logit) as raw u32 words. The token id - * is already GLOBAL, because each rank adds its own vocab offset before the gather -- a merge that - * had to know the offsets would need the shard layout, which is the caller's business. THE LOGIT - * IS READ BY BIT PATTERN: the buffer's dtype can only be one of the two halves' types, it is u32, - * and a float read through it would turn 0x40800000 into 1.08e9 instead of 4.0. + * `gathered` is [M, world_size * n_cand] (token id, logit) pairs as raw u32 words. Ids are already + * global (each rank adds its vocab offset before the gather). The logit is read by bit pattern, + * since the buffer's dtype is u32. * - * THE ROW'S OWN top_k IS RE-APPLIED, and that is why this takes `params`. Every rank ran top-k over - * its own shard before the gather, so the merged set holds up to world_size * k candidates where - * the request asked for k, and no stage after this one narrows again. At k = 1 that is not a - * slightly wider support, it is a different ANSWER: a greedy row is staged at top_k = 1 exactly so - * this chain returns the argmax, and with world_size candidates alive `sample_pick` draws among - * them against the request's seed. */ + * The row's top_k is re-applied (hence `params`): the merged set holds up to world_size * k + * candidates and no later stage narrows it. At k = 1 this matters: greedy rows are staged at + * top_k = 1, and with world_size candidates left sample_pick would draw among them. */ AVX_KERNEL(sample_merge_topk) { if (!rad_args_have(a, 4)) return RAD_E_INVAL; const RadTensor *gt = &a->t[0], *pr = &a->t[1], *ci = &a->t[2], *cv = &a->t[3]; @@ -790,10 +719,8 @@ AVX_KERNEL(sample_merge_topk) { const int64_t keep = (R.p[m].flags & RAD_SP_GREEDY) ? 0 : (tk > 0 && (int64_t)tk < n_cand) ? (int64_t)tk : n_cand; - /* The pairs are unpacked ONCE into two arrays. libref reads both halves back through - * ld_int inside the O(n_cand * n_in) selection, which is two dtype switches per comparison. - * The selection itself stays a selection sort over n_in entries, ties to the lower token - * id -- the tie rule every other selection in this vocabulary uses. */ + /* Unpack the pairs once (libref reads them inside the O(n_cand * n_in) selection). The + * selection sort is libref's, ties to the lower token id. */ float* gv = scratch_f32((size_t)n_in); int32_t* gi = (int32_t*)scratch_f32_b((size_t)n_in); for (int64_t j = 0; j < n_in; ++j) { @@ -834,18 +761,17 @@ AVX_KERNEL(sample_merge_topk) { /* ================================================================== dflash_select * - * Not a sampler, and here because it is the other op that picks TOKENS: DFlash2's greedy walk over - * a candidate lattice. A block-diffusion drafter proposes every position of a block in one pass, so - * it cannot condition position l+1 on its pick at l; this puts that dependence back. + * Not a sampler, but it also picks tokens: DFlash2's greedy walk over a candidate lattice. A + * block-diffusion drafter proposes all positions of a block in one pass, so it cannot condition + * position l+1 on its pick at l; this walk restores that dependence. * * score[l, c] = unary[l, c] + sum_r pred[pid(l)][r] * hp[l][r] * succ[cand[l, c]][r] * pid(0) = anchor[s * anchor_stride], pid(l) = cand[l - 1, chosen(l - 1)] * - * `hp` ABSENT IS A PLANE OF ONES -- a plain low-rank bigram. The walk is SERIAL IN l, since the - * predecessor is not known until the previous step is decided, so the parallel axis is the - * sequence and the vector work is the rank-R dot a candidate costs. A predecessor or a candidate - * outside the vocabulary contributes nothing rather than reading past a codebook; the highest - * score wins and a tie goes to the lower candidate, libref's rule. */ + * An absent `hp` is a plane of ones (a plain low-rank bigram). The walk is serial in l, so the + * parallel axis is the sequence and the vector work is each candidate's rank-R dot. A predecessor + * or candidate outside the vocabulary contributes nothing. Highest score wins, ties to the lower + * candidate (libref's rule). */ static inline float dot_r(const float* a, const float* b, int64_t n) { vf acc = vf_zero(); int64_t i = 0; @@ -865,7 +791,8 @@ AVX_KERNEL(dflash_select) { const int64_t steps = p_int(a, "steps", 0); const int64_t K = p_int(a, "top_k", 0); - /* `cand` is [M * steps, K] and it is the call; `M` is the band (avx_common.h, band_rows). */ + /* Rows come from `cand` ([M * steps, K]); the `M` parameter is the band (avx_common.h: + * band_rows). */ const int64_t M = steps > 0 && K > 0 ? band_rows(numel(cand) / (steps * K), p_int(a, "M", 0)) : 0; const int64_t R = p_int(a, "rank", pred->rank >= 2 ? pred->shape[pred->rank - 1] : 0); @@ -888,7 +815,7 @@ AVX_KERNEL(dflash_select) { for (int64_t l = 0; l < steps; ++l) { const int64_t r = m * steps + l; const int64_t cb = rowoff(cand, r, K), ub = rowoff(un, r, K); - /* The half of the form that does not depend on the candidate, once a step. */ + /* The candidate-independent factor, once per step. */ const bool ok = pid >= 0 && pid < nv; const float* pv = ok ? in_row(pred, rowoff(pred, pid, R), R, rv) : nullptr; const float* hw = hp ? in_row(hp, rowoff(hp, r, R), R, hv) : nullptr; diff --git a/libavx/avx_support.cpp b/libavx/avx_support.cpp index d8ca95c9..edb57a6b 100644 --- a/libavx/avx_support.cpp +++ b/libavx/avx_support.cpp @@ -1,18 +1,12 @@ -/* avx_support.cpp -- the dtype-generic row and the row reductions, compiled once per ISA level. +/* avx_support.cpp -- dtype-generic row conversion and row reductions, compiled once per ISA level. * - * WHY THESE ARE OUT OF LINE AND NOT IN THE HEADER. They are called from every kernel with a - * runtime dtype, so inlining them would paste a fifteen-way switch into sixty-eight call sites and - * the switch is the thing being hoisted out of the loop in the first place. Out of line, the - * branch is taken ONCE PER ROW and the body it lands in is a straight vector loop the hardware - * prefetcher can see through. + * Out of line rather than in the header: every kernel calls these with a runtime dtype, so inlining + * would paste the dtype switch into every call site. Out of line, the switch is taken once per row + * and lands in a straight vector loop. * - * The conversion rates per level are measured by `rad-avx-bench --cvt` and recorded in - * libavx/README.md rather than here, because they are a property of the machine the bench last ran - * on and a number typed into a comment outlives the machine that produced it. - * - * The two fp8 decodes take different paths and avx_vec.h says why: e4m3 is a branchless bit - * reconstruction, e5m2 a table gather, and the scalar level and every tail element read the table - * in both cases. + * Conversion rates per level come from `rad-avx-bench --cvt` (libavx/README.md). The two fp8 + * decodes differ (avx_vec.h explains): e4m3 is a branchless bit reconstruction, e5m2 a table + * gather; the scalar level and tail elements use the table for both. */ #include "avx_vec.h" #include "avx_common.h" @@ -21,18 +15,14 @@ namespace avx { inline namespace AVX_SUFFIX { /* ================================================================== packed weight codes - * The conventions are libr4d's, because a .rad is specific to a kernel set (spec §4.2) and this - * plugin has to read the same bytes: W4 is two nibbles a byte with element 2i LOW and a symmetric - * two's-complement code ((n ^ 8) - 8), W2 four codes a byte with the same construction one radix - * down, MXFP4 two e2m1 nibbles with the magnitude table below. libref/ref_common.h is the written - * definition and this is the vectorised reading of it. + * The canonical planes a container stores (abi/rad_encoding.h), read as stored: libavx rearranges + * no plane, its relayouts only join whole planes (avx_planes.h). Definition: libref/ref_common.h. + * W4: two nibbles a byte, element 2i in the low nibble, code (n ^ 8) - 8. W2: four codes a byte, + * code (c ^ 2) - 2. MXFP4: two e2m1 nibbles, as avx_common.h: ld_elem decodes them. * - * THE W4 UNPACK IS A SHUFFLE, NOT A SHIFT PER ELEMENT. Sixteen nibble pairs are one 128-bit load; - * the low nibbles are an AND and the high ones a shift, and the two interleave back with a - * punpcklbw -- four instructions for 32 elements against 32 shifts and 32 masks scalar. W2 and - * MXFP4 are left scalar: W2 appears only in the draft head's lm_head and MXFP4 only in an expert - * grid this plugin does not serve at speed, so neither is on a path worth the code. */ -static const float kMxfp4Mag[8] = { 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f }; + * W4 unpacks 32 elements from one 128-bit load: AND for the low nibbles, shift for the high, then + * interleave with punpcklbw; MXFP4 takes the same unpack and a register table. W2 stays scalar: no + * plain W2 weight is served. */ static void w4_to_f32(const uint8_t* src, float* dst, int64_t n) { int64_t i = 0; @@ -59,28 +49,46 @@ static void w4_to_f32(const uint8_t* src, float* dst, int64_t n) { #endif } #endif - for (; i < n; ++i) { - uint8_t b = src[i >> 1]; - uint8_t nb = (i & 1) ? (uint8_t)(b >> 4) : (uint8_t)(b & 0xf); - dst[i] = (float)((int)(nb ^ 0x8u) - 8); - } + for (; i < n; ++i) dst[i] = ld_elem(src, RAD_I4, i); } -static void w2_to_f32(const uint8_t* src, float* dst, int64_t n) { - for (int64_t i = 0; i < n; ++i) { - uint8_t b = src[i >> 2]; - uint8_t c = (uint8_t)((b >> (2 * (i & 3))) & 0x3u); - dst[i] = (float)((int)(c ^ 0x2u) - 2); - } -} - -static void mxfp4_to_f32(const uint8_t* src, float* dst, int64_t n) { - for (int64_t i = 0; i < n; ++i) { - uint8_t b = src[i >> 1]; - uint8_t nb = (i & 1) ? (uint8_t)(b >> 4) : (uint8_t)(b & 0xf); - float v = kMxfp4Mag[nb & 7u]; - dst[i] = (nb & 8u) ? -v : v; +/* MXFP4: the same nibble unpack, then the e2m1 value of each code from a register table. AVX-512 + * looks all sixteen up in one vpermps; AVX2's vpermps indexes eight, so it takes the magnitude by + * the low three bits and ors in the sign (bit 3). Code 8 is -0, as ld_elem gives it. */ +static void fp4_to_f32(const uint8_t* src, float* dst, int64_t n) { + int64_t i = 0; +#if AVX_LEVEL >= 2 + const __m128i lomask = _mm_set1_epi8(0x0f); +#if AVX_LEVEL >= 3 + const __m512 tab = _mm512_setr_ps(0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f, -0.0f, + -0.5f, -1.0f, -1.5f, -2.0f, -3.0f, -4.0f, -6.0f); +#else + const __m256 mag = _mm256_setr_ps(0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f); + auto emit8 = [&](__m128i codes8, float* d) { + const __m256i ix = _mm256_cvtepu8_epi32(codes8); + const __m256 m = _mm256_permutevar8x32_ps(mag, ix); + const __m256i sg = _mm256_slli_epi32(_mm256_and_si256(ix, _mm256_set1_epi32(8)), 28); + _mm256_storeu_ps(d, _mm256_or_ps(m, _mm256_castsi256_ps(sg))); + }; +#endif + for (; i + 32 <= n; i += 32) { + const __m128i b = _mm_loadu_si128((const __m128i*)(src + (i >> 1))); + const __m128i lo = _mm_and_si128(b, lomask); + const __m128i hi = _mm_and_si128(_mm_srli_epi16(b, 4), lomask); + const __m128i e0 = _mm_unpacklo_epi8(lo, hi); /* codes 0..15 */ + const __m128i e1 = _mm_unpackhi_epi8(lo, hi); /* codes 16..31 */ +#if AVX_LEVEL >= 3 + _mm512_storeu_ps(dst + i, _mm512_permutexvar_ps(_mm512_cvtepu8_epi32(e0), tab)); + _mm512_storeu_ps(dst + i + 16, _mm512_permutexvar_ps(_mm512_cvtepu8_epi32(e1), tab)); +#else + emit8(e0, dst + i); + emit8(_mm_srli_si128(e0, 8), dst + i + 8); + emit8(e1, dst + i + 16); + emit8(_mm_srli_si128(e1, 8), dst + i + 24); +#endif } +#endif + for (; i < n; ++i) dst[i] = ld_elem(src, RAD_FP4E2M1, i); } /* ================================================================== the generic row */ @@ -93,11 +101,10 @@ void row_to_f32(uint32_t dt, const void* src, float* dst, int64_t n) { case RAD_F8E5M2: cvt_fp8e5m2_to_f32((const uint8_t*)src, dst, n); break; case RAD_I8: cvt_i8_to_f32((const int8_t*)src, dst, n); break; case RAD_I4: w4_to_f32((const uint8_t*)src, dst, n); break; - case RAD_I2: w2_to_f32((const uint8_t*)src, dst, n); break; - case RAD_FP4E2M1: mxfp4_to_f32((const uint8_t*)src, dst, n); break; + case RAD_I2: for (int64_t i = 0; i < n; ++i) dst[i] = ld_elem(src, RAD_I2, i); break; + case RAD_FP4E2M1: fp4_to_f32((const uint8_t*)src, dst, n); break; default: - /* Everything left is an integer or a bool, none of them hot. The ABI's own accessor is - * the definition and there is nothing to vectorise about a u8 widen nobody runs. */ + /* Remaining integer and bool dtypes are not hot; use the ABI accessor. */ for (int64_t i = 0; i < n; ++i) dst[i] = rad_load_f32(src, dt, i); break; } @@ -120,19 +127,17 @@ void row_from_f32(uint32_t dt, const float* src, void* dst, int64_t n) { void row_to_f32_strided(uint32_t dt, const void* src, int64_t stride, float* dst, int64_t n) { if (stride == 1) { row_to_f32(dt, src, dst, n); return; } - /* A GATHER, AND IT IS LEFT SCALAR. vpgatherdd issues one cache line per lane where the scalar - * loop's loads coalesce in the load queue, and every strided operand in this plugin is a - * column slice of a fused projection (docs/OPS.md on `z`) -- a handful of rows per launch. Not - * a hot path, and not worth a second code path that would need its own check. */ + /* Scalar gather. vpgatherdd issues one cache line per lane, while scalar loads coalesce in + * the load queue; and strided operands here are only column slices of a fused projection + * (docs/OPS.md on `z`), a few rows per launch. */ for (int64_t i = 0; i < n; ++i) dst[i] = ld_elem(src, dt, i * stride); } /* ================================================================== row reductions - * FIXED TREES. The accumulator count is written out rather than left to the unroller, because the - * summation order has to be a property of the source and not of the optimiser: a rebuild that - * moved the answer in the last ulp would show up in the checker as a tolerance move and be read as - * whatever change was under test. Four accumulators is what it takes to cover the FMA latency on a modern core - * -- the sweep that says so is `rad-avx-bench --reduce`. */ + * Fixed summation trees. The accumulators are written out rather than left to the unroller so the + * summation order is fixed by the source, not the optimiser, and results do not move by an ulp + * between builds. Four accumulators cover the FMA latency on current cores (`rad-avx-bench + * --reduce`). */ float row_sumsq(const float* x, int64_t n) { vf a0 = vf_zero(), a1 = vf_zero(), a2 = vf_zero(), a3 = vf_zero(); int64_t i = 0; @@ -193,75 +198,57 @@ float row_max(const float* x, int64_t n) { } /* ================================================================== an operand's row, as f32 */ +/* Whether a dense row starting at element `base` can be addressed by a byte pointer. A sub-byte + * dtype starting mid-byte cannot (`byte_at` maps elements 2i and 2i+1 to the same byte), so it + * takes the element path rather than reading the row shifted by a nibble. Real W4 rows start on a + * group boundary. */ +static inline bool byte_aligned(const RadTensor* t, int64_t base) { + const int sub = (t->dtype == RAD_I4 || t->dtype == RAD_FP4E2M1) ? 1 + : (t->dtype == RAD_I2) ? 3 : 0; + return (base & sub) == 0; +} + const float* in_row(const RadTensor* t, int64_t base, int64_t n, float* scr) { const int64_t st = laststride(t); - if (st == 1) { - /* SUB-BYTE DTYPES AT AN ODD ELEMENT OFFSET are the one case a byte pointer cannot express, - * and they take the slow path rather than being silently truncated: `byte_at` maps element - * 2i and 2i+1 to the same byte, so a W4 row starting at an odd element would read the whole - * row shifted by one nibble -- a permutation, and the kind that produces plausible numbers. - * Every real W4 row starts on a group boundary, so this costs nothing. */ - const int sub = (t->dtype == RAD_I4 || t->dtype == RAD_FP4E2M1) ? 1 - : (t->dtype == RAD_I2) ? 3 : 0; - if (!sub || (base & sub) == 0) { - const void* p = byte_at(t->data, t->dtype, base); - return row_f32_in(t->dtype, p, scr, n); - } - } + if (st == 1 && byte_aligned(t, base)) + return row_f32_in(t->dtype, byte_at(t->data, t->dtype, base), scr, n); for (int64_t i = 0; i < n; ++i) scr[i] = ldt(t, base + i * st); return scr; } void out_row(const RadTensor* t, int64_t base, int64_t n, const float* src) { const int64_t st = laststride(t); - if (st == 1) { - const int sub = (t->dtype == RAD_I4 || t->dtype == RAD_FP4E2M1) ? 1 - : (t->dtype == RAD_I2) ? 3 : 0; - if (!sub || (base & sub) == 0) { - row_from_f32(t->dtype, src, (void*)byte_at(t->data, t->dtype, base), n); - return; - } + if (st == 1 && byte_aligned(t, base)) { + row_from_f32(t->dtype, src, (void*)byte_at(t->data, t->dtype, base), n); + return; } for (int64_t i = 0; i < n; ++i) stt(t, base + i * st, src[i]); } /* ================================================================== exact top-R * - * ONE STEP OF AN EXACT SELECTION, descending by value and on a tie by the LOWER index. libref's - * `topk_next` is the definition and this is the vectorised reading of it. + * One step of an exact selection: the next element in descending value order, ties to the lower + * index (libref's `topk_next`). * - * THE ELIGIBILITY TEST SPLITS AT THE PREVIOUS PICK, and that is what makes it vectorisable at all. - * The rule is "skip anything above the last pick, and skip the last pick itself and everything - * before it that equals it" -- which reads as an index comparison and is not a lane predicate. But - * it is equivalent to two PURE VALUE tests over two ranges: + * Eligibility ("not above the last pick, and not the last pick or an equal element before it") + * splits at the previous pick into two value-only tests, which vectorise as compare + blend + max: * * i <= pi eligible iff !(v > pv) and v != pv * i > pi eligible iff !(v > pv) * - * so each range is one compare and one blend, and the maximum over them is a vector max. Recovering - * WHICH index held that maximum is a second pass that early-exits at the first match -- on real - * data it reads a fraction of the row. libref does one scalar pass with two unpredictable branches - * per element; at a 248K vocabulary and R = 16 that is eight million of them. + * A second pass finds the index of the maximum and exits at the first match. * - * `!(v > pv)` RATHER THAN `v <= pv` IS DELIBERATE and is why the comparisons below are the - * unordered NGT form: for a NaN both are different answers, and libref's `if (v > *pv) continue;` - * treats a NaN as eligible. Matching it costs nothing here. - * - * WHAT DOES NOT MATCH, stated rather than hidden: libref seeds its running best with the FIRST - * eligible element and only replaces it on a strict `>`, so an eligible NaN encountered first stays - * the winner for the whole row. A vector max cannot reproduce that, and this returns the largest - * non-NaN instead. Both are arbitrary -- a NaN logit has no correct selection -- and no path in - * this project produces one (a masked logit is -inf, which IS ordered and IS handled). */ + * `!(v > pv)` (the unordered NGT compare) rather than `v <= pv` matches libref, which treats a NaN + * as eligible. One known difference: libref keeps an eligible NaN that it meets first as the + * winner, while the vector max returns the largest non-NaN. No path produces NaN logits (a masked + * logit is -inf, which is handled). */ bool topk_next_f32(const float* v, int64_t n, float* pv, int64_t* pi) { const float prev = *pv; const int64_t pidx = *pi; #if AVX_LEVEL == 0 - /* ONE PASS AT THE SCALAR LEVEL, WHICH IS libref's LOOP. The two-pass form below -- a vector - * maximum and then a scan for the index that held it -- pays only because the first pass is - * vector work; with a vector of one float it is strictly two passes where libref does one, and - * it measures slower than the reference it is meant to replace. A fallback that loses to the - * thing it falls back from is not a fallback, so the scalar level gets its own loop. */ + /* Scalar level: libref's single pass. The two-pass form below only pays when the first pass + * is vector work; scalar, it is slower than one pass. */ float best = 0.0f; int64_t bi = -1; for (int64_t j = 0; j < n; ++j) { @@ -276,7 +263,7 @@ bool topk_next_f32(const float* v, int64_t n, float* pv, int64_t* pi) { return true; #else const float NEG = -INFINITY; - /* The split point: indices at or below `pidx` must also differ from `prev`. */ + /* Indices below `split` (at or below `pidx`) must also differ from `prev`. */ const int64_t split = (pidx + 1 > 0) ? (pidx + 1 < n ? pidx + 1 : n) : 0; float best = NEG; int64_t i = 0; @@ -284,7 +271,7 @@ bool topk_next_f32(const float* v, int64_t n, float* pv, int64_t* pi) { { const vf vprev = vf_set1(prev), vneg = vf_set1(NEG); vf acc = vf_set1(NEG); - /* Range one: below or at the previous pick -- equality is excluded here. */ + /* At or below the previous pick: equality excluded. */ for (; i + VF_N <= split; i += VF_N) { const vf x = vf_loadu(v + i); #if AVX_LEVEL == 3 @@ -302,7 +289,7 @@ bool topk_next_f32(const float* v, int64_t n, float* pv, int64_t* pi) { if (x > prev || x == prev) continue; if (x > best) best = x; } - /* Range two: past the previous pick -- equality is allowed. */ + /* Past the previous pick: equality allowed. */ for (; i + VF_N <= n; i += VF_N) { const vf x = vf_loadu(v + i); #if AVX_LEVEL == 3 @@ -323,25 +310,16 @@ bool topk_next_f32(const float* v, int64_t n, float* pv, int64_t* pi) { if (x > best) best = x; } - /* THE LOWEST INDEX HOLDING THAT MAXIMUM -- "ties to the lower column" -- AND THIS PASS IS - * VECTORISED TOO, because it costs as much as the maximum does when it is not. + /* Lowest index holding the maximum (ties to the lower column). Vectorised as well: a scalar + * scan reads n/2 elements on average and would dominate `sample_argmax`. * - * The maximum can sit anywhere in the row, so a scalar scan for it reads n/2 elements on - * average: over a 32000-logit row that is sixteen thousand unpredictable compares, and it - * dominates `sample_argmax`. Comparing a whole vector against `best` and taking the lowest set - * bit of the mask turns that into n/2/VF_N iterations. + * The range below the previous pick must be scanned first, since the lowest index over the + * whole row wins. Scanning the vector range first returns the wrong index when the maximum + * occurs on both sides, which is common at bf16. * - * THE LOW RANGE IS SCANNED FIRST AND THAT IS NOT A DETAIL. "Lowest index" means lowest over the - * WHOLE row, so a match below the previous pick beats one above it -- and scanning the long - * vector range first and only then the short scalar one returns the wrong index exactly when - * the maximum occurs twice, once on each side. That failure only bites on ties: it does not - * show at f32 or at the scalar level, and it shows at bf16, where a narrow row quantised to a - * handful of distinct values makes a repeated maximum common. - * - * Below the previous pick the extra `x != prev` test applies, and that range is at most pidx+1 - * long -- zero for an argmax, R-1 for the R-th selection -- so it stays scalar. Past it, - * eligibility is exactly `!(x > prev)` and `x == best` already implies it, since `best` was - * drawn from eligible lanes and is therefore <= prev. */ + * That low range needs the extra `x != prev` test and is at most pidx+1 long (0 for an argmax, + * R-1 for the R-th pick), so it stays scalar. Past it, `x == best` implies eligibility, since + * best <= prev. */ for (int64_t j = 0; j < split; ++j) { const float x = v[j]; if (x != best || x == prev) continue; @@ -374,28 +352,18 @@ bool topk_next_f32(const float* v, int64_t n, float* pv, int64_t* pi) { /* ================================================================== the machine's FMA ceiling * - * THE CEILING HAS TO BE MEASURED WITH THE FLAGS THE KERNELS ARE COMPILED WITH, which is why this - * lives here -- in a file compiled once per ISA level -- and not in rad-avx-bench, which is - * baseline-compiled like the dispatcher and can only ever emit SSE2. A bench that reported the - * scalar chain as "the machine's peak" would be reporting something ten times below what a GEMM - * at this level is up against, and every kernel would look like it was doing well. + * Measured here, with the kernels' per-level flags, because rad-avx-bench is baseline-compiled + * and could only measure a scalar chain far below what a GEMM at this level faces. * - * WHAT IT MEASURES: a dependency-free chain of independent FMA accumulators, all in registers, - * nothing touching memory. What comes out is what the machine RETIRES, including whatever clock it - * actually holds under a sustained vector load -- which on a part with an AVX-512 frequency offset - * is not the advertised boost, and is exactly the number a kernel is competing with. + * Independent FMA accumulators in registers, no memory traffic. The result is what the core + * retires at the clock it holds under sustained vector load (below advertised boost on parts with + * an AVX-512 frequency offset). * - * THE ACCUMULATOR COUNT IS THE REGISTER FILE, and getting it wrong understates the ceiling rather - * than overstating it -- which is worse, because every kernel then looks good against it. Sixteen - * accumulators plus the two constants is EIGHTEEN live vectors, which fits AVX-512's 32 registers - * and spills on AVX2's and AVX's 16. With sixteen everywhere the AVX2 peak comes out barely above - * the AVX one -- a step of a few percent for turning two instructions into one, where the ports - * say 2x -- because the spill is inside the loop. Ten accumulators covers a 4-5 cycle FMA latency - * against 2 FMA ports with room to spare and leaves six registers free. + * The accumulator count must fit the register file; a spill inside the loop understates the + * ceiling. 16 accumulators plus 2 constants fit AVX-512's 32 registers but spill on AVX/AVX2's 16. + * 10 covers a 4-5 cycle FMA latency on 2 FMA ports and leaves six registers free. * - * `volatile` on the sink, so the whole loop is not deleted. The accumulators are read out through - * it; without that the compiler is entirely within its rights to remove the work and report an - * infinite ceiling, which is the classic way this measurement is wrong. */ + * The `volatile` sink keeps the compiler from deleting the loop. */ extern "C" double AVX_FN(avx_peak_fma)(int64_t iters) { using namespace avx; #if AVX_LEVEL == 1 || AVX_LEVEL == 2 @@ -412,6 +380,6 @@ extern "C" double AVX_FN(avx_peak_fma)(int64_t iters) { for (int i = 0; i < NACC; ++i) sink += vf_hsum(acc[i]); volatile float keep = sink; (void)keep; - /* 2 flops an FMA, NACC of them an iteration, VF_N lanes each. */ + /* 2 flops per FMA, NACC FMAs per iteration, VF_N lanes each. */ return 2.0 * (double)iters * (double)NACC * (double)VF_N; } diff --git a/libavx/avx_table.cpp b/libavx/avx_table.cpp index 82f83543..1230c06d 100644 --- a/libavx/avx_table.cpp +++ b/libavx/avx_table.cpp @@ -1,12 +1,8 @@ /* avx_table.cpp -- one ISA level's table of kernel entry points, compiled once per level. * - * There is nothing to read here and that is the point. The table is generated from AVX_OP_LIST in - * avx_isa.h, so the member order and the initialiser order are the SAME MACRO EXPANSION and cannot - * drift: a table whose members were typed out twice is a table where `silu` and `sigmoid` end up - * swapped one day, and the symptom of that is a model that produces fluent wrong text rather than - * a failure anything reports. The declarations come from the same list too, so an op added to - * AVX_OP_LIST without an implementation at every level is a LINK error naming the missing symbol - * and the level it is missing from -- which is the diagnostic you want, four times over. + * Members, initialisers and declarations all expand from AVX_OP_LIST (avx_isa.h), so their order + * cannot drift (a swapped entry would run the wrong op silently). An op added to the list without + * an implementation at some level is a link error naming the symbol and the level. */ #include "avx_vec.h" #include "avx_isa.h" diff --git a/libavx/avx_vec.h b/libavx/avx_vec.h index 3c3a653d..84332eea 100644 --- a/libavx/avx_vec.h +++ b/libavx/avx_vec.h @@ -1,40 +1,24 @@ -/* avx_vec.h -- the vector abstraction every kernel in this plugin is written against, and the - * dtype conversions that feed it. +/* avx_vec.h -- the vector abstraction every kernel is written against, and the dtype conversions + * that feed it. * - * THIS HEADER IS COMPILED FOUR TIMES, once per ISA level, with AVX_LEVEL defined on the command - * line and the matching -m flags on the object. Nothing in here is selected at runtime: by the - * time this is preprocessed the level is a constant, so `vf` is one concrete type and every - * operation below is one instruction or a short fixed sequence. The runtime choice happens once, - * in avx_dispatch.cpp, between whole tables of already-compiled functions. + * Compiled four times, once per ISA level, with AVX_LEVEL defined on the command line and matching + * -m flags. The level is a compile-time constant here, so `vf` is one concrete type and each + * operation is one instruction or a short fixed sequence. The runtime choice is made once, in + * avx_dispatch.cpp, between tables of compiled functions. * - * ============================== WHY AN ABSTRACTION AND NOT FOUR COPIES ============================== + * One source per kernel instead of four copies: the AVX-512 path is the same algorithm as the + * scalar path, and the checker only has to prove the arithmetic agrees. The abstraction cannot + * express what differs in kind between levels (AVX-512 write masks, 32 registers, + * compress/expand), so where that matters a kernel has an `#if AVX_LEVEL >= 3` block with a + * comment (e.g. the GEMM microkernel's register blocking, top-k's compress). * - * Four hand-written copies of seventy-five kernels is three hundred implementations - * to keep in agreement, and they would not stay in agreement -- the levels whatever machine you - * develop on cannot execute are the ones that rot, and they are the levels the plugin exists for. - * Written once against `vf`, the AVX-512 path is THE SAME ALGORITHM as the scalar path and the - * checker's job is to prove the arithmetic agrees, not to re-derive the op. + * Everything computes in f32, as libref does (f32 accumulation, IEEE RTNE narrowing; + * libref/ref_common.h). A whole row is converted to f32 scratch once, computed, and converted + * back, instead of libref's per-element dtype switch, which blocks vectorisation. * - * The cost is real and is stated rather than hidden: an abstraction cannot express the things that - * differ in KIND between levels -- AVX-512's write masks, its 32 registers, its compress/expand. - * So where one of those is the whole point, the kernel writes an `#if AVX_LEVEL >= 3` block and - * says why in a comment next to it. That is a handful of places (the GEMM microkernel's register - * blocking, top-k's compress), not the general case. - * - * ============================== EVERYTHING COMPUTES IN f32 ============================== - * - * libref's contract is f32 accumulation with IEEE RTNE narrowing (libref/ref_common.h) and this - * plugin is checked against it, so f32 is the working type here too. Operands arrive as bf16, f16, - * fp8 or i8; the rule is CONVERT A WHOLE ROW ONCE into an f32 scratch, compute, convert back. Not - * per element, which is what libref does and what makes it slow: a per-element dtype switch inside - * the inner loop is a branch the vectoriser cannot cross. The size of that effect is measured per - * op by rad-avx-bench and recorded in each kernel's own header, not guessed at here. - * - * WHAT THIS PLUGIN DOES NOT PROMISE, and libref does: no reassociation and no FMA. Both are given - * up deliberately and both are why the tolerances in avx_check.cpp are the kbench ones rather than - * zero. A vector reduction sums in a different order by construction -- that IS the vectorisation - * -- and refusing FMA would throw away half the machine's flops. The narrowing conversions are the - * part that must be bit-exact, because they define what a result IS, and they are (see below). + * Unlike libref, this plugin reassociates reductions and uses FMA, so avx_check.cpp uses the kbench + * tolerances rather than zero. The narrowing conversions are bit-exact, since they define the + * stored result. */ #ifndef RAD_AVX_VEC_H #define RAD_AVX_VEC_H @@ -76,19 +60,15 @@ /* avx_rmsnorm -> avx_rmsnorm_v2 at AVX_LEVEL 2. */ #define AVX_FN(name) AVX_CAT(name, AVX_SUFFIX) -/* The header of every kernel in this plugin. `a` is the RadArgs and `stream` the RadStream, which - * a host kernel ignores -- the house rule is that every entry point is (const RadArgs*, RadStream) - * whatever domain it runs in (libr4d/r4d_plugin.h), and a host plugin that dropped the second - * parameter would not be substitutable for a device one. */ +/* Signature of every kernel. A host kernel ignores `stream`, but every entry point is + * (const RadArgs*, RadStream) in every domain (libr4d/r4d_plugin.h). */ #define AVX_KERNEL(nm) \ extern "C" int AVX_FN(avx_##nm)(const RadArgs* a, [[maybe_unused]] RadStream stream) namespace avx { -/* EVERY LEVEL GETS ITS OWN NAMESPACE, and it is an `inline` one so that a kernel writes `avx::vf` - * without knowing which level it is being compiled at. Without this the four objects would define - * four `avx::row_to_f32` symbols and the link would pick one of them for all four tables -- which - * is not a link error, it is an AVX-512 helper silently running inside the scalar path, and on a - * machine without AVX-512 that is a SIGILL from the fallback that exists to prevent SIGILLs. */ +/* One inline namespace per level, so kernels write `avx::vf` without naming the level. Without it + * the four objects would define the same `avx::row_to_f32` symbol and the linker would silently + * pick one (e.g. the AVX-512 one) for all four tables. */ inline namespace AVX_SUFFIX { /* ================================================================== the vector type */ @@ -131,9 +111,8 @@ static inline vf vf_min(vf a, vf b) { return _mm256_min_ps(a, b); } #if AVX_LEVEL >= 2 static inline vf vf_fma(vf a, vf b, vf c) { return _mm256_fmadd_ps(a, b, c); } #else -/* AVX HAS NO FMA -- it is a separate feature that arrived with Haswell, and Sandy Bridge is the - * whole reason this level exists. Two roundings here, which makes this level numerically CLOSER - * to libref than AVX2 is, not further. */ +/* AVX has no FMA (it arrived with Haswell). Two roundings, which is closer to libref than AVX2's + * fused form. */ static inline vf vf_fma(vf a, vf b, vf c) { return _mm256_add_ps(_mm256_mul_ps(a, b), c); } #endif static inline vf vf_sqrt(vf a) { return _mm256_sqrt_ps(a); } @@ -141,8 +120,8 @@ static inline vf vf_abs(vf a) { return _mm256_and_ps(a, _mm256_castsi256_ps(_mm256_set1_epi32(0x7fffffff))); } static inline float vf_hsum(vf a) { - /* Lane-crossing first, then within the 128. Fixed order, so the answer does not depend on - * which of two equally valid trees the compiler picks. */ + /* Fixed order (cross-lane, then within 128 bits) so the result does not depend on the + * compiler's choice of tree. */ __m128 lo = _mm256_castps256_ps128(a); __m128 hi = _mm256_extractf128_ps(a, 1); __m128 s = _mm_add_ps(lo, hi); @@ -181,47 +160,15 @@ static inline float vf_hsum(vf a) { return _mm512_reduce_add_ps(a); static inline float vf_hmax(vf a) { return _mm512_reduce_max_ps(a); } #endif -/* Tail handling. A masked load is the right instruction at AVX-512 and there is no such thing - * below it, so `vf_load_n` is a mask at level 3 and a small stack copy elsewhere. Kernels use it - * only for the RAGGED END of a row: a model width is a multiple of 128 and the tail almost never - * runs, so this is about correctness at odd shapes, not about speed. */ -static inline vf vf_load_n(const float* p, int n) { -#if AVX_LEVEL == 3 - return _mm512_maskz_loadu_ps((__mmask16)((1u << n) - 1u), p); -#elif AVX_LEVEL == 0 - return n > 0 ? *p : 0.0f; -#else - float tmp[VF_N] = { 0 }; - for (int i = 0; i < n; ++i) tmp[i] = p[i]; - return _mm256_loadu_ps(tmp); -#endif -} - -static inline void vf_store_n(float* p, vf v, int n) { -#if AVX_LEVEL == 3 - _mm512_mask_storeu_ps(p, (__mmask16)((1u << n) - 1u), v); -#elif AVX_LEVEL == 0 - if (n > 0) *p = v; -#else - float tmp[VF_N]; - _mm256_storeu_ps(tmp, v); - for (int i = 0; i < n; ++i) p[i] = tmp[i]; -#endif -} - /* ================================================================== narrowing conversions * - * THE BIT-EXACTNESS RULE. rad_plugin.h defines f32->bf16 as RTNE with the tie broken on the - * surviving bit's parity, NaN forced quiet, and overflow allowed to carry into the bf16 infinity. - * That definition IS the result (rad_plugin.h says so at length), and the kbench tolerance for - * `cast` is 1e-6 -- which is to say: exact. So the vector forms below are the SAME INTEGER - * ARITHMETIC, lane for lane, not an approximation of it, and avx_check.cpp checks `cast` over - * every dtype pair against libref at that tolerance to hold them there. + * Bit-exact. rad_plugin.h defines f32->bf16 as RTNE with ties to the even surviving bit, NaN + * forced quiet, and overflow carrying into the bf16 infinity. The vector forms below are the same + * integer arithmetic lane for lane; avx_check.cpp checks `cast` over every dtype pair against + * libref at 1e-6, i.e. exactly. * - * NOT `_mm512_cvtneps_pbh`. Zen 5 has AVX512-BF16 and its convert is also RTNE, but its NaN - * handling is the hardware's rather than the ABI's, and the ABI's is what libref computes. One - * instruction saved against a conversion that is a mask and two integer ops is not worth a - * divergence the checker would have to be loosened to accept. + * Not `_mm512_cvtneps_pbh`: AVX512-BF16 (e.g. Zen 5) also rounds RTNE, but its NaN handling is the + * hardware's, not the ABI's. */ static inline void cvt_bf16_to_f32(const uint16_t* src, float* dst, int64_t n) { int64_t i = 0; @@ -238,9 +185,8 @@ static inline void cvt_bf16_to_f32(const uint16_t* src, float* dst, int64_t n) { _mm256_storeu_ps(dst + i, _mm256_castsi256_ps(w)); } #elif AVX_LEVEL == 1 - /* AVX has no 256-bit integer ALU: the shift has to happen in two 128-bit halves and the - * result is glued with vinsertf128, which is a FLOAT-domain instruction and therefore legal - * here. This is the shape every integer helper at this level takes. */ + /* AVX has no 256-bit integer ALU: shift in two 128-bit halves and join with vinsertf128, a + * float-domain instruction. Every integer helper at this level has this shape. */ for (; i + 8 <= n; i += 8) { __m128i h = _mm_loadu_si128((const __m128i*)(src + i)); __m128i lo = _mm_slli_epi32(_mm_cvtepu16_epi32(h), 16); @@ -254,8 +200,8 @@ static inline void cvt_bf16_to_f32(const uint16_t* src, float* dst, int64_t n) { } #if AVX_LEVEL >= 1 -/* The RTNE core, on a vector of f32 bit patterns, leaving 16-bit results in the low half of each - * lane. Shared by the three vector levels; the pack differs and the arithmetic does not. */ +/* RTNE core on f32 bit patterns, leaving the 16-bit result in the low half of each lane. Same + * arithmetic at all three vector levels; only the pack differs. */ #if AVX_LEVEL == 3 static inline __m512i bf16_round_bits(__m512 f) { __m512i u = _mm512_castps_si512(f); @@ -303,7 +249,7 @@ static inline void cvt_f32_to_bf16(const float* src, uint16_t* dst, int64_t n) { __m256i w = bf16_round_bits(_mm256_loadu_ps(src + i)); __m128i lo = _mm256_castsi256_si128(w); __m128i hi = _mm256_extracti128_si256(w, 1); - /* Every lane is already <= 0xffff, so packus is exact rather than saturating. */ + /* Every lane is <= 0xffff, so packus does not saturate. */ _mm_storeu_si128((__m128i*)(dst + i), _mm_packus_epi32(lo, hi)); } #elif AVX_LEVEL == 1 @@ -317,11 +263,9 @@ static inline void cvt_f32_to_bf16(const float* src, uint16_t* dst, int64_t n) { for (; i < n; ++i) dst[i] = rad_f32_to_bf16(src[i]); } -/* f16 IS HARDWARE FROM AVX2 UP AND SOFTWARE BELOW IT. F16C is its own CPUID bit and arrived one - * generation after AVX, so the level-1 path cannot use vcvtph2ps and falls through to the ABI's - * software convert. That is the honest thing: a level named `avx` that quietly required F16C - * would fault on the only machines it exists for. F16C's rounding is IEEE RTNE, which is what - * rad_f32_to_f16 computes, so the two agree bit for bit -- checked by `cast` at 1e-6. */ +/* f16 is hardware (F16C) from the AVX2 level up and the ABI's software convert below. F16C is a + * separate CPUID bit that arrived a generation after AVX, so the `avx` level cannot assume it. + * F16C rounds RTNE, as rad_f32_to_f16 does, so the two agree bit for bit (`cast` at 1e-6). */ static inline void cvt_f16_to_f32(const uint16_t* src, float* dst, int64_t n) { int64_t i = 0; #if AVX_LEVEL == 3 @@ -348,67 +292,38 @@ static inline void cvt_f32_to_f16(const float* src, uint16_t* dst, int64_t n) { for (; i < n; ++i) dst[i] = rad_f32_to_f16(src[i]); } -/* ---- fp8. THE DECODE IS A 256-ENTRY TABLE AT THE SCALAR LEVEL and a bit reconstruction above it; - * the encode is a masked fast path. +/* ---- fp8. Decode: a 256-entry table at the scalar level and for tails, built at load from the + * ABI's converters (avx_dispatch.cpp: fp8_tables_init); e4m3 is a bit reconstruction on the vector + * levels (see cvt_fp8e4m3_to_f32), e5m2 a table gather. * - * DECODE: every possible byte is one of 256 floats, so the exact answer is a lookup and there is - * nothing to round. The table is built by the ABI's own converter at load (avx_fp8_table_init), so - * it cannot drift from rad_fp8e4m3_to_f32, and it is what the scalar path and every tail element - * read. The vector e4m3 path reconstructs the bits instead, for the reason set out above - * cvt_fp8e4m3_to_f32; e5m2 still gathers from its table. - * - * ENCODE: the bit-exact algorithm has three branches (subnormal, normal, saturate) and vectorising - * all three costs more than it saves. Instead the normal case -- |x| in [2^-6, 448), which is - * every element of a normalised activation -- is done with vector integer arithmetic, and a mask - * of the elements that are NOT in that range drives a scalar fixup through the ABI's converter. On - * real activations the mask is empty and the fixup loop does not run; when it does run the answer - * is the ABI's, which is the definition. */ -} /* the tables are at GLOBAL scope with C linkage, deliberately: they are defined once in the - baseline-compiled avx_dispatch.cpp and read by all four levels, so they must NOT pick up the - per-level inline namespace the rest of this header is wrapped in. */ + * Encode: the bit-exact algorithm has three branches (subnormal, normal, saturate). Only the normal + * case, |x| in [2^-6, 448), which covers a normalised activation, is vectorised; a mask of the + * other elements drives a scalar fixup through the ABI's converter. */ +} /* The tables have C linkage at global scope: defined once in the baseline avx_dispatch.cpp and + read by all four levels, so they must stay outside the per-level inline namespace. */ } extern "C" { -/* NOT `const`, and that is forced: the tables are filled at load by rad_plugin_open from the - ABI's own converters (a typed-out table would be a second definition of the format that can - drift), so the object has to be writable. A const declaration here against a non-const - definition would link -- C linkage does not mangle the type -- and would be a quiet type - mismatch that no tool reports. */ +/* Not const: rad_plugin_open fills them at load. A const declaration against the non-const + definition would still link (C linkage does not mangle the type), unreported. */ extern float avx_fp8e4m3_tab[256]; extern float avx_fp8e5m2_tab[256]; } namespace avx { inline namespace AVX_SUFFIX { -/* THE DECODE IS A BIT RECONSTRUCTION, AND THE TABLE GATHER IS THE NULL RESULT. +/* e4m3 decode by bit reconstruction rather than a vpgatherdd table lookup. A gather issues one L1 + * access per lane even for a 1 KiB table, and `rad-avx-bench --cvt` shows it no faster than the + * scalar lookup; the reconstruction is about 2.5x faster at AVX2 and 3.3x at AVX-512. * - * The obvious implementation is a 256-entry table -- every byte is one of 256 floats, so the answer - * is a lookup and there is nothing to round -- gathered with vpgatherdd. `rad-avx-bench --cvt` says - * that form LOSES TO THE SCALAR TABLE LOOKUP at both vector levels. A gather issues one cache line - * per lane however small the table is; a 1 KiB table resident in L1 does not make that cheap, it - * just makes it not slower than DRAM. Sixteen lanes of vpgatherdd is sixteen L1 accesses in - * sequence. - * - * The reconstruction below is pure integer arithmetic and no memory at all: - * - * u = (b & 0x7f) << 20 + 120 << 23 puts e in the f32 exponent field (bias 7 -> 127) and m - * in the top three mantissa bits, in one add - * e == 0 is an fp8 SUBNORMAL, where the implicit 1 that f32 just - * supplied is wrong: (f - 2^-7) * 2 removes it and - * rescales, which is exact -- both operands are powers of - * two times a 3-bit mantissa - * mag == 0x7f is the format's ONLY NaN (S1111111); blended in + * u = (b & 0x7f) << 20 + 120 << 23 e into the f32 exponent field (bias 7 -> 127), m into + * the top three mantissa bits, in one add + * e == 0 fp8 subnormal: (f - 2^-7) * 2 removes the implicit 1 + * and rescales, exactly + * mag == 0x7f the format's only NaN (S1111111); blended in * sign (b & 0x80) << 24 * - * The reconstruction is worth roughly 2.5x the gather at AVX2 and 3.3x at AVX-512 on that bench, - * and the gather and the scalar table are within a few percent of each other. - * - * The table stays for the scalar path, where it is exact, has no branch, and is what the level is - * for. It also stays because rad_plugin_open builds it from the ABI's own converter, so it remains - * the definition the reconstruction above is checked against. - * - * WHAT IS NOT CLAIMED: that avoiding memory is obviously faster. Both forms are measured rather - * than argued, and the checker proves the answer is identical over all 256 input bytes, NaN and - * subnormals included, which a draw of normals never would. */ + * The table remains for the scalar level and tails. The checker compares all 256 input bytes, + * NaN and subnormals included. */ static inline void cvt_fp8e4m3_to_f32(const uint8_t* src, float* dst, int64_t n) { int64_t i = 0; #if AVX_LEVEL == 3 @@ -470,15 +385,12 @@ static inline void cvt_fp8e5m2_to_f32(const uint8_t* src, float* dst, int64_t n) static inline void cvt_f32_to_fp8e4m3(const float* src, uint8_t* dst, int64_t n) { int64_t i = 0; #if AVX_LEVEL == 3 - /* q = ((e+7) << 3) | rtne(mantissa >> 20), valid while 2^-6 <= |x| < 448 and x is finite. - * Anything else takes the scalar fixup below. + /* q = ((e+7) << 3) | rtne(mantissa >> 20), valid for finite 2^-6 <= |x| < 448; anything + * else takes the scalar fixup. * - * THE LOWER BOUND IS 2^-6 AND NOTHING ELSE. e4m3's smallest NORMAL is 2^-6; below it the - * format is subnormal and the mantissa has to be renormalised with a variable shift, which is - * the branch this fast path exists to avoid. A bound set any lower lets fp8-subnormal - * magnitudes through the normal path, where they produce an exponent field of zero or below - * and an answer that is wrong by orders of magnitude. The bound is written as its float bit - * pattern with the value beside it so the next reader can check it rather than trust it. */ + * The lower bound must be exactly 2^-6, e4m3's smallest normal. Below it the format is + * subnormal and needs a variable renormalising shift; a lower bound would send subnormals + * through this path with an exponent field <= 0, wrong by orders of magnitude. */ const __m512i c_lo = _mm512_set1_epi32(0x3c800000); /* 2^-6, the smallest e4m3 normal */ const __m512i c_hi = _mm512_set1_epi32(0x43e00000); /* 448, the largest e4m3 finite */ for (; i + 16 <= n; i += 16) { @@ -488,31 +400,23 @@ static inline void cvt_f32_to_fp8e4m3(const float* src, uint8_t* dst, int64_t n) __mmask16 fast = _kand_mask16(_mm512_cmpge_epi32_mask(mag, c_lo), _mm512_cmplt_epi32_mask(mag, c_hi)); __m512i sign = _mm512_srli_epi32(_mm512_and_si512(u, _mm512_set1_epi32(0x80000000u)), 24); - /* RTNE on the 20 bits below the kept mantissa: add half, plus one more when the surviving - * bit is odd -- the same tie rule as bf16, one field down. The exponent field rides along - * in the same add, so a mantissa carry increments it for free. */ + /* RTNE on the 20 dropped bits: add half, plus one when the surviving bit is odd (bf16's + * tie rule). A mantissa carry propagates into the exponent in the same add. */ __m512i lsb = _mm512_and_si512(_mm512_srli_epi32(mag, 20), _mm512_set1_epi32(1)); __m512i r = _mm512_add_epi32(_mm512_add_epi32(mag, _mm512_set1_epi32(0x7ffff)), lsb); __m512i e = _mm512_sub_epi32(_mm512_srli_epi32(r, 23), _mm512_set1_epi32(127 - 7)); __m512i m = _mm512_and_si512(_mm512_srli_epi32(r, 20), _mm512_set1_epi32(7)); __m512i q = _mm512_or_si512(sign, _mm512_or_si512(_mm512_slli_epi32(e, 3), m)); - /* A carry out of the top mantissa bit can push e past 15, and (e, m) = (15, 7) is the - * format's only NaN encoding rather than a number. Neither can be produced by an input - * strictly below 448, but the guard costs one compare and the alternative is a silent NaN - * in a weight: elements that reach either drop into the fixup, which saturates. */ + /* A carry can push e past 15, and (e, m) = (15, 7) is the NaN encoding. Neither occurs + * for inputs below 448, but such lanes are sent to the saturating fixup rather than risk + * a silent NaN. */ __mmask16 ovf = _kor_mask16( _mm512_cmpgt_epi32_mask(e, _mm512_set1_epi32(15)), _kand_mask16(_mm512_cmpeq_epi32_mask(e, _mm512_set1_epi32(15)), _mm512_cmpeq_epi32_mask(m, _mm512_set1_epi32(7)))); fast = _kandn_mask16(ovf, fast); - /* THE ALL-FAST CASE IS THE WHOLE POINT AND IT GETS ITS OWN EXIT. Every element of a - * normalised activation is in [2^-6, 448), so `fast` is 0xffff on essentially every vector - * a model produces, and the answer is one narrowing store of sixteen bytes. - * - * Without this exit the sixteen lanes spill to a stack array and a scalar loop tests one - * mask bit per element -- a loop that then runs on exactly the path the vector arithmetic - * was written to avoid, and dominates the op. A "fast path" whose epilogue is a - * per-element branch is not a fast path. */ + /* All lanes fast (the normal case for activations): one narrowing store. Without this + * exit, the per-lane fixup loop below would run on every vector and dominate the op. */ if (fast == (__mmask16)0xffff) { _mm_storeu_si128((__m128i*)(dst + i), _mm512_cvtepi32_epi8(q)); continue; @@ -523,21 +427,17 @@ static inline void cvt_f32_to_fp8e4m3(const float* src, uint8_t* dst, int64_t n) dst[i + k] = (fast >> k) & 1 ? (uint8_t)tmp[k] : rad_f32_to_fp8e4m3(src[i + k]); } #elif AVX_LEVEL == 2 - /* THE SAME ARITHMETIC AT 256 BITS, and it exists because without it AVX2 falls all the way - * through to the ABI's scalar converter: an order of magnitude slower than the AVX-512 body, - * not the 2x its width would suggest. AVX2 is the level most machines in the world run, so a - * gap there is not a rounding error in the coverage. - * - * The mask is a movemask rather than a k-register, and the all-fast exit is the same: eight - * lanes narrowed to eight bytes with two packs. */ + /* The same arithmetic at 256 bits (the scalar converter is an order of magnitude slower). + * The mask is a movemask instead of a k-register; the all-fast exit narrows eight lanes to + * eight bytes with two packs. */ for (; i + 8 <= n; i += 8) { __m256 f = _mm256_loadu_ps(src + i); __m256i u = _mm256_castps_si256(f); __m256i mag = _mm256_and_si256(u, _mm256_set1_epi32(0x7fffffff)); const __m256i c_lo = _mm256_set1_epi32(0x3c800000); /* 2^-6 */ const __m256i c_hi = _mm256_set1_epi32(0x43e00000); /* 448 */ - /* cmpgt is the only signed compare AVX2 has, so `mag >= c_lo` is written as - * `!(c_lo > mag)` and `mag < c_hi` as `c_hi > mag`. Both operands are non-negative. */ + /* AVX2 has only signed cmpgt: `mag >= c_lo` is `!(c_lo > mag)`, `mag < c_hi` is + * `c_hi > mag`. Both operands are non-negative. */ __m256i ge = _mm256_andnot_si256(_mm256_cmpgt_epi32(c_lo, mag), _mm256_cmpgt_epi32(c_hi, mag)); __m256i sign = _mm256_srli_epi32(_mm256_and_si256(u, _mm256_set1_epi32(0x80000000u)), 24); @@ -572,15 +472,13 @@ static inline void cvt_f32_to_fp8e5m2(const float* src, uint8_t* dst, int64_t n) for (int64_t i = 0; i < n; ++i) dst[i] = rad_f32_to_fp8e5m2(src[i]); } -/* ---- int8. `_mm*_cvtps_epi32` rounds under MXCSR, which is round-to-nearest-even unless a - * caller has changed it -- the same rule `std::nearbyintf` follows, which is what libref uses. +/* ---- int8. `_mm*_cvtps_epi32` rounds under MXCSR (round-to-nearest-even by default), the same + * rule as libref's `std::nearbyintf`. * - * THE CLAMP IS TAKEN IN FLOAT, BEFORE THE CONVERSION, and the saturating packs are not a - * substitute for it: a value past the int32 range and +inf both convert to 0x80000000, the - * "integer indefinite", which the packs then saturate to -128 -- the opposite end of the range. - * Clamping to [-128, 127] first and rounding second lands where libref's round-then-clamp does for - * every input, the .5 ties at the ends included, so this stays bit-exact against the reference and - * `quant_act` can be held at 1e-6. A NaN stores 0, which is also what the scalar tail does. */ + * The clamp is applied in float before conversion. The saturating packs are not enough: +inf and + * values beyond int32 convert to 0x80000000 ("integer indefinite"), which packs to -128. + * Clamp-then-round matches libref's round-then-clamp for every input, including .5 ties at the + * ends, so `quant_act` holds at 1e-6. NaN stores 0, as in the scalar tail. */ #if AVX_LEVEL == 3 static inline __m512 i8_range_ps(__m512 x) { const __mmask16 ord = _mm512_cmp_ps_mask(x, x, _CMP_ORD_Q); @@ -619,13 +517,9 @@ static inline void cvt_f32_to_i8(const float* src, int8_t* dst, int64_t n) { for (; i < n; ++i) dst[i] = i8_round_sat(src[i]); } -/* Fused scale + int8-encode for the quant_act_i8 family: t = src*inv computed in a register - * feeds the same cvtps/packs sequence the split form uses (MXCSR round-to-nearest-even, - * saturating packs -- exactly libref's nearbyintf-and-clamp, bit for bit), so the bytes match - * the scale-then-store form while a full f32 write + read of the row disappears. Kept to the - * int8 family: the fp8 encode's bit-twiddle is a long integer chain and folding the scale into - * it measures slower, where this one measures a few percent faster -- the same traffic saved, - * the opposite instruction-level trade. */ +/* Fused scale + int8 encode for the quant_act_i8 family: src * inv in a register feeds the same + * clamp/cvtps/packs sequence, so the bytes match scale-then-encode without an f32 round trip + * through memory. Not done for fp8: folding the scale into its longer integer chain is slower. */ static inline void cvt_scaled_f32_to_i8(const float* src, float inv, int8_t* dst, int64_t n) { int64_t i = 0; #if AVX_LEVEL == 3 @@ -666,27 +560,18 @@ static inline void cvt_i8_to_f32(const int8_t* src, float* dst, int64_t n) { /* ================================================================== the dtype-generic row * - * ONE SWITCH PER ROW, NOT PER ELEMENT. This is the single most valuable thing in this header: - * libref's inner loops call ld_dt(), which is a switch on every element, and hoisting it to the - * row is most of the speedup on every memory-bound op before a single vector instruction is - * issued. The f32 case is a memcpy the caller can skip entirely -- see row_f32_in below. + * One dtype switch per row instead of libref's per-element ld_dt(); for memory-bound ops this + * accounts for most of the speedup. The f32 case can be skipped entirely (row_f32_in). * - * W4 / W2 / MXFP4 are the packed WEIGHT codes and are decoded here too, because `dequant` and the - * quantised GEMMs both need them and the unpack is the same nibble arithmetic in both. They are - * raw CODES: the group scale belongs to the caller, which is the only component that knows where - * the scale stream is (libref/ref_common.h makes the same split). */ + * The packed weight codes W4 / W2 / MXFP4 decode here too (for `dequant` and the quantised GEMMs), + * as raw codes: the caller applies the group scale (the same split as libref/ref_common.h). */ void row_to_f32 (uint32_t dt, const void* src, float* dst, int64_t n); void row_from_f32(uint32_t dt, const float* src, void* dst, int64_t n); -/* The strided form: element i of the row is at src[i * stride]. A separate function because the - * contiguous one is the case that matters and a stride parameter in it would cost a multiply per - * element on the path that does not need one. */ +/* Element i at src[i * stride]. Separate so the contiguous path carries no stride multiply. */ void row_to_f32_strided(uint32_t dt, const void* src, int64_t stride, float* dst, int64_t n); -/* When the source is already f32, hand back the pointer instead of copying. Returns `src` for - * RAD_F32 and `scratch` (filled) otherwise, so a kernel reads: - * const float* x = avx::row_f32_in(dt, p, scratch, n); - * and pays nothing at all on the f32 path. */ +/* Returns `src` itself for RAD_F32, otherwise `scratch` filled with the converted row. */ static inline const float* row_f32_in(uint32_t dt, const void* src, float* scratch, int64_t n) { if (dt == RAD_F32) return (const float*)src; row_to_f32(dt, src, scratch, n); @@ -695,30 +580,23 @@ static inline const float* row_f32_in(uint32_t dt, const void* src, float* scrat /* ================================================================== math * - * exp AND THE SIGMOID IT FEEDS. Every softmax, every gate and every attention row goes through - * this, so a call to libm's expf per element is most of the cost of those ops. How much is - * measured per op by rad-avx-bench. + * exp and sigmoid. Softmax, gates and attention rows all go through these, and a per-element libm + * expf would dominate those ops. * - * THE POLYNOMIAL IS MINIMAX DEGREE 5 ON [-ln2/2, ln2/2] after range reduction, which is ~0.6 ulp - * and comfortably inside every tolerance in this project -- softmax's 1e-6 included, because the - * softmax NORMALISES: a relative error common to every term cancels in the quotient, and what - * survives is the DIFFERENCE between lanes' errors, an order smaller again. + * Minimax degree 5 on [-ln2/2, ln2/2] after range reduction, ~0.6 ulp. That fits softmax's 1e-6 + * because normalisation cancels the relative error common to all terms. * - * NULL RESULT, on the two ways of not writing this: the _mm512_exp_ps SVML form is not available - * without Intel's runtime, and GCC's libmvec vectorises expf only when it can prove the loop is - * safe to call `_ZGVeN16v_expf` from, which it cannot do inside a kernel that also does integer - * work. Hand-writing the polynomial is not a micro-optimisation here, it is the only way to get a - * vector exp at all. */ + * Hand-written because SVML's _mm512_exp_ps needs Intel's runtime, and GCC's libmvec only + * vectorises expf where it can prove the call safe, which fails in kernels that mix integer work. */ static inline vf vf_exp(vf x) { #if AVX_LEVEL == 0 return std::exp(x); #else - /* Clamp first: the reduction below overflows the integer exponent construction outside this - * range. The TOP saturates, which every consumer here wants rather than an infinity. The - * BOTTOM and a NaN are put right after the polynomial, because the clamp alone answers - * wrongly for both: e^-inf would come out as e^lo, a tiny positive number, and a NaN would be - * clamped to lo and vanish -- so a fully masked softmax row would read 1/n instead of the NaN - * libref gives. Below lo e^x is under the smallest normal float and is taken as zero. */ + /* Clamp first: outside this range the integer exponent construction overflows. The top + * saturates, which every consumer here prefers to an infinity. Below lo (under the smallest + * normal float) the result is set to zero, and NaN is passed through, after the polynomial; + * the clamp alone would turn e^-inf into e^lo and lose a NaN, so a fully masked softmax row + * would give 1/n instead of libref's NaN. */ const vf hi = vf_set1(88.3762626647949f), lo = vf_set1(-87.3365447504f); const vf x0 = x; x = vf_min(vf_max(x, lo), hi); @@ -733,8 +611,7 @@ static inline vf vf_exp(vf x) { vf r = vf_fma(n, c1, x); r = vf_fma(n, c2, r); vf r2 = vf_mul(r, r); - /* exp(r) on [-ln2/2, ln2/2]. Horner, so the dependency chain is the depth of the polynomial - * and not of a wider evaluation tree. */ + /* exp(r) on [-ln2/2, ln2/2], Horner form. */ vf p = vf_set1(1.9875691500e-4f); p = vf_fma(p, r, vf_set1(1.3981999507e-3f)); p = vf_fma(p, r, vf_set1(8.3334519073e-3f)); @@ -768,22 +645,18 @@ static inline vf vf_exp(vf x) { } static inline vf vf_sigmoid(vf x) { - /* 1 / (1 + e^-x). Not the tanh form: this is what libref computes and the two differ in the - * last ulp, which `sigmoid`'s 1e-5 f32 tolerance would pass but `hc_read`'s gate chain -- a - * sigmoid of a dot product of a sigmoid -- accumulates. */ + /* 1 / (1 + e^-x), as libref computes it. The tanh form differs in the last ulp, which + * `hc_read`'s chained sigmoid gates accumulate. */ return vf_div(vf_set1(1.0f), vf_add(vf_set1(1.0f), vf_exp(vf_sub(vf_zero(), x)))); } static inline vf vf_silu(vf x) { return vf_mul(x, vf_sigmoid(x)); } #if AVX_LEVEL >= 2 -/* The CHEAP silu, for consumers that round to bf16 on the next store: a Taylor-4 exp head - * (truncation ~6e-5) and a raw reciprocal seed (2^-14 avx512, 2^-12 avx2, no Newton step) - * instead of the minimax tail and the division. ~3e-4 worst lane against the 6e-3 bf16 - * bucket: twentyfold of margin -- but NOT for f32 consumers, where 3e-4 does not fit 1e-5. - * Declared here rather than inside one kernel so every bf16-store consumer can reach it; - * silu_mul is the only caller today, because in a frontend-bound token loop -- the conv - * kernels -- the difference is unmeasurable. Callers key on their OUTPUT dtype. */ +/* Cheap silu, only for consumers whose output is bf16: a Taylor-4 exp (truncation ~6e-5) and a + * raw reciprocal seed (2^-14 avx512, 2^-12 avx2, no Newton step). Worst lane ~3e-4, well inside the + * bf16 tolerance of 6e-3 but not f32's 1e-5, so callers key on their output dtype. silu_mul uses + * it; in the frontend-bound conv kernels it makes no measurable difference. */ static inline vf vf_exp_t4(vf x) { const vf hi = vf_set1(88.3762626647949f), lo = vf_set1(-87.3365447504f); x = vf_min(vf_max(x, lo), hi); @@ -796,9 +669,8 @@ static inline vf vf_exp_t4(vf x) { #endif vf r = vf_fma(n, c1, x); r = vf_fma(n, c2, r); - /* Taylor-4 head: 1 + r(1 + r(1/2 + r(1/6 + r/24))). Four FMAs against the exact path's - * seven-op minimax tail -- the reduction above is unchanged, so the exponent build below - * is too. */ + /* Taylor-4: 1 + r(1 + r(1/2 + r(1/6 + r/24))). Same range reduction and exponent build as + * vf_exp. */ vf p = vf_fma(r, vf_set1(1.0f / 24.0f), vf_set1(1.0f / 6.0f)); p = vf_fma(p, r, vf_set1(0.5f)); p = vf_fma(p, r, vf_set1(1.0f)); @@ -822,36 +694,45 @@ static inline vf vf_silu_fast(vf x) { vf d = vf_add(vf_set1(1.0f), e); vf r = _mm256_rcp_ps(d); #endif - /* No Newton step: d lies in [1, emax] so the seed is in range and nothing overflows. */ + /* No Newton step: d is in [1, emax], so the seed is in range and nothing overflows. */ return vf_mul(x, r); } #endif -/* Sum of squares of a row, vectorised, with a FIXED reduction tree so the answer does not depend - * on the compiler's unrolling. Used by every norm. */ -/* ================================================================== an operand's row, as f32 - * - * THE TWO FUNCTIONS EVERY KERNEL OPENS WITH. `in_row` hands back a pointer to `n` floats holding - * element (base + i * laststride) of the operand -- which is `t->data` itself when the operand is - * already dense f32, so the common case copies nothing at all. `out_row` is the inverse. - * - * They are where the DENSE/STRIDED split lives, and it lives in one place on purpose: every op in - * this vocabulary has to accept a strided view (libref/ref_ops.h: "no geometry constraints" has to - * mean strides too), and seventy-five kernels each writing their own stride test is seventy-five - * chances to write `t->stride[0]` where `laststride(t)` was meant. */ -/* ONE STEP OF AN EXACT TOP-R SELECTION over a row of f32: descending by value and, ON A TIE, by - * the LOWER index. That tie rule is libr4d's and it has to be stated rather than left to a sort's - * stability -- a router that breaks ties differently from the kernel it is checked against routes a - * token to a different expert, and the diff is a whole layer wide. - * - * `pv`/`pi` carry the previously selected (value, index); seed them with +infinity and -1. Returns - * false when nothing is left to select. Shared by row_topk, router_topk and sample_topk, which is - * why it is here rather than in one of them. */ +/* ================================================================== exact top-R + * One step of an exact top-R selection over an f32 row: descending by value, ties to the lower + * index (libr4d's rule; a router that broke ties differently would pick a different expert). + * `pv`/`pi` carry the previous pick; seed them with +infinity and -1. Returns false when nothing + * is left. Shared by row_topk, router_topk and sample_topk. */ bool topk_next_f32(const float* v, int64_t n, float* pv, int64_t* pi); +/* ================================================================== an operand's row, as f32 + * `in_row` returns `n` floats holding elements (base + i * laststride) of the operand: `t->data` + * itself when it is dense f32, otherwise `scr` filled. `out_row` is the inverse. Every op must + * accept strided views (libref/ref_ops.h), and this is the one place the dense/strided split is + * made. */ const float* in_row (const struct RadTensor* t, int64_t base, int64_t n, float* scr); void out_row(const struct RadTensor* t, int64_t base, int64_t n, const float* src); +/* A dot product with four accumulators to cover FMA latency, combined (a0 + a1) + (a2 + a3) before + * the scalar tail: a fixed summation tree. Inline, since the attention and GEMM edges call it per + * element. */ +static inline float dotf(const float* a, const float* b, int64_t n) { + vf a0 = vf_zero(), a1 = vf_zero(), a2 = vf_zero(), a3 = vf_zero(); + int64_t i = 0; + for (; i + 4 * VF_N <= n; i += 4 * VF_N) { + a0 = vf_fma(vf_loadu(a + i), vf_loadu(b + i), a0); + a1 = vf_fma(vf_loadu(a + i + VF_N), vf_loadu(b + i + VF_N), a1); + a2 = vf_fma(vf_loadu(a + i + 2 * VF_N), vf_loadu(b + i + 2 * VF_N), a2); + a3 = vf_fma(vf_loadu(a + i + 3 * VF_N), vf_loadu(b + i + 3 * VF_N), a3); + } + for (; i + VF_N <= n; i += VF_N) a0 = vf_fma(vf_loadu(a + i), vf_loadu(b + i), a0); + float s = vf_hsum(vf_add(vf_add(a0, a1), vf_add(a2, a3))); + for (; i < n; ++i) s += a[i] * b[i]; + return s; +} + +/* Row reductions with a fixed summation tree, independent of compiler unrolling. */ float row_sumsq(const float* x, int64_t n); float row_sum (const float* x, int64_t n); float row_amax (const float* x, int64_t n); diff --git a/libquant/CMakeLists.txt b/libquant/CMakeLists.txt index c90eac12..3d7b1fc7 100644 --- a/libquant/CMakeLists.txt +++ b/libquant/CMakeLists.txt @@ -1,11 +1,9 @@ # libquant -- the built-in quantisers (spec §4.5). Host C++ only. # -# It links rad_abi AND NOTHING ELSE, like every plugin: abi/rad_quant.h is the whole contract, and a -# quantiser that reached into core/ would stop being substitutable -- which is the property that -# lets a user ship a quantiser of their own beside it. -# A plugin like any other: built here inside radiance's tree, or on its own against an installed -# radiance (`cmake -S libquant -B build -DCMAKE_PREFIX_PATH=`) -- the same -# rad_add_plugin either way (cmake/RadAddPlugin.cmake). +# Links rad_abi and nothing else, like every plugin: abi/rad_quant.h is the whole contract, which +# keeps it substitutable by a third-party quantiser. +# Built in radiance's tree, or standalone against an installed radiance +# (`cmake -S libquant -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake. if(NOT COMMAND rad_add_plugin) cmake_minimum_required(VERSION 3.21) project(libquant LANGUAGES CXX) @@ -17,14 +15,12 @@ file(GLOB LQ_SRC CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) rad_add_plugin(libquant quantizers SOURCES ${LQ_SRC} INCLUDES ${CMAKE_CURRENT_SOURCE_DIR}) -# -ffp-contract=off because a quantiser's output is a stored file: the same weights converted by two -# builds have to give the same bytes, and an FMA the compiler chose in one and not the other moves a -# value on a rounding boundary into the next code. +# -ffp-contract=off: quantiser output is a stored file, so two builds must produce the same bytes. A +# compiler-chosen FMA can move a value on a rounding boundary into the next code. target_compile_options(libquant PRIVATE -ffp-contract=off) -# OpenMP over rows: GPTQ over a 512-expert layer is N*K^2/2 flops an expert, and round-to-nearest -# over a 51 GB table is a long single-threaded loop. Rows are independent in both, so the result -# does not depend on the thread count. Optional: without it everything is correct and serial. +# Optional OpenMP over rows (GPTQ and round-to-nearest over large tables are long serial loops). +# Rows are independent, so the result does not depend on the thread count. find_package(OpenMP QUIET) if(OpenMP_CXX_FOUND) target_link_libraries(libquant PRIVATE OpenMP::OpenMP_CXX) diff --git a/libquant/lq_autoround.cpp b/libquant/lq_autoround.cpp index 7b8ff2a9..0a566011 100644 --- a/libquant/lq_autoround.cpp +++ b/libquant/lq_autoround.cpp @@ -1,23 +1,21 @@ /* lq_autoround.cpp -- AutoRound: rounding by signed gradient descent (Cheng et al., 2023). * - * WHAT IT DOES. Rounding to nearest decides each value on its own; the output error is a property - * of the whole row against the input it meets. AutoRound learns, for every value, an offset V in - * [-0.5, 0.5] added before the rounding -- q = round(w / s + V) -- and for every scale block a - * factor on its range (one for a symmetric block, one for each end of an asymmetric one, in - * [0.5, 1]), and descends on the output error with the SIGN of each gradient, through the rounding - * by the straight-through estimator: d round(x) / dx = 1. The step is `lr` (by default 1/iters) - * decaying linearly to zero, and every row keeps the parameters of its lowest error seen, so - * the result is never worse than the start -- which is rounding to nearest. + * Rounding to nearest decides each value alone, but the output error depends on the whole row. + * AutoRound learns a per-value offset V in [-0.5, 0.5], q = round(w / s + V), and per scale block a + * range factor in [0.5, 1] (one for a symmetric block, one per end for an asymmetric one). It + * descends on the output error with the sign of each gradient, through the rounding by the + * straight-through estimator (d round(x) / dx = 1). The step is `lr` (default 1/iters) decaying + * linearly to zero. Each row keeps its lowest-error parameters, so the result is never worse than + * the starting point, round-to-nearest. * - * THE ERROR IS THE HESSIAN'S QUADRATIC FORM (lq_hess.h) rather than the block output over - * calibration samples the paper uses: it is the same function of the weight for one linear layer, - * and it decomposes over rows, so every row descends on its own -- no batch, no sample noise, and - * a row block per call. What it costs is N K^2 multiply-adds a step, which at the default 200 steps - * is the whole of a conversion's time; `iters` trades it. + * Error: the Hessian's quadratic form (lq_hess.h) instead of the paper's block output over + * calibration samples. For one linear layer it is the same function of the weight, and it + * decomposes over rows, so each row descends alone: no batch, no sample noise, a row block per + * call. Cost is N K^2 multiply-adds per step, which dominates conversion time at the default 200 + * steps; `iters` trades it. * - * THE GRID is integer codes, symmetric or with a zero, with blocks of one row: the descent is over - * a rounding, so a codebook or a float code has none to learn, and a second level or a scale block - * that spans rows ties rows together. + * Grid: integer codes, symmetric or with a zero, blocks of one row. A codebook or float code has + * no rounding to learn, and a second level or a multi-row block would tie rows together. */ #include "lq_autoround.h" #include "lq_hess.h" @@ -156,10 +154,10 @@ void autoround_rows(const Grid& g, const float* w, int64_t N, int64_t K, const f errors(); keep(); const float step = (float)(lr * (1.0 - (double)t / iters)); - /* THE GRADIENTS, by the straight-through rounding: dL/dw_hat = 2 G, and w_hat = s (q - z) + /* Gradients through the straight-through rounding: dL/dw_hat = 2 G, and w_hat = s (q - z) * with q = round(w/s + V) + z clamped. Unclamped, dw_hat/dV = s and dw_hat/ds = (q - z) - * w/s; clamped, the first is 0 and the second (q - z). The range factors reach the loss - * through s alone (the zero is held where the rounding put it). */ + * through s only (the zero is held where the rounding put it). */ #ifdef _OPENMP #pragma omp parallel for schedule(static) #endif @@ -198,7 +196,7 @@ void autoround_rows(const Grid& g, const float* w, int64_t N, int64_t K, const f errors(); keep(); - /* ---- the best parameters, written: each block's scale and zero, then the codes */ + /* Write the best parameters: each block's scale and zero, then the codes. */ #ifdef _OPENMP #pragma omp parallel for schedule(static) #endif @@ -235,7 +233,7 @@ int ar_grid(const RadParam* o, int n_o, const RadQuantWeight* w, Grid* g) { if (st != RAD_OK) return st; const std::string no = autoround_refusal(*g); if (!no.empty()) return refuse(w, ("autoround: " + no).c_str()); - if (rad_param_geti(o, n_o, "iters", 200) < 0) return refuse(w, "iters= is >= 0"); + if (rad_param_geti(o, n_o, "iters", 200) < 0) return refuse(w, "iters= must be >= 0"); return RAD_OK; } @@ -248,8 +246,8 @@ int ar_encoding(const RadParam* o, int n_o, const RadQuantWeight* w, RadEncoding return RAD_OK; } -/* Rows descend on their own, so a call is any number of them; 512 keeps the state a few hundred - * megabytes at the widest K while every call still fills the threads. */ +/* Rows descend independently, so any block size works; 512 keeps the state to a few hundred MB at + * the widest K while still filling the threads. */ int64_t ar_row_block(const RadParam*, int, const RadQuantWeight*) { return 512; } int ar_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src, int64_t row0, @@ -257,7 +255,6 @@ int ar_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src, Grid g; const int st = ar_grid(o, n_o, w, &g); if (st != RAD_OK) return st; - (void)row0; const int64_t K = w->cols; grid_transform_rows(g, src, rows, K); const char* dir = rad_param_gets(o, n_o, "calib", nullptr); @@ -269,7 +266,7 @@ int ar_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src, const float* diag = (!H && !g.fwht) ? w->importance : nullptr; const Planes p = grid_planes(g, K, planes); if (!H && !diag) { - /* with nothing to weigh the error by, the best rounding of each value is the nearest */ + /* With no error weighting, round-to-nearest is optimal. */ return grid_rtn(g, src, row0, rows, K, p, nullptr); } if (!H) diff --git a/libquant/lq_autoround.h b/libquant/lq_autoround.h index 14de85ff..10bb5063 100644 --- a/libquant/lq_autoround.h +++ b/libquant/lq_autoround.h @@ -10,9 +10,9 @@ namespace lq { * of one row. Empty when it can, the reason when not. */ std::string autoround_refusal(const Grid& g); -/* Rows [0, N) of `w` [N, K] -- already in the grid's domain, transformed if it has a transform -- - * descended on for `iters` steps against H (K x K) or, when H is null, the diagonal `diag` (K), at - * learning rate `lr`; the result's scales into `planes` (the grid's) and its codes too. */ +/* Run `iters` descent steps at learning rate `lr` on rows [0, N) of `w` [N, K], already in the + * grid's (transformed) domain, against H (K x K) or, when H is null, the diagonal `diag` (K). + * Writes the resulting scales and codes into `planes` (the grid's). */ void autoround_rows(const Grid& g, const float* w, int64_t N, int64_t K, const float* H, const float* diag, int iters, double lr, const Planes& planes); diff --git a/libquant/lq_awq.cpp b/libquant/lq_awq.cpp index 929bf910..3f610d15 100644 --- a/libquant/lq_awq.cpp +++ b/libquant/lq_awq.cpp @@ -1,30 +1,27 @@ /* lq_awq.cpp -- AWQ: activation-aware weight quantisation (Lin et al., 2023), on any grid. * - * WHAT IT DOES. A few input channels carry most of a layer's activation energy, and the error a - * weight column contributes to the output scales with its channel's activation. AWQ scales each - * column UP by s_j before quantising -- so the channels that matter use more of the grid -- and the - * reader multiplies the column back down. The scales are s_j = a_j^alpha over the channels' - * activation magnitudes a_j, normalised so their geometric middle is one, and alpha is chosen from - * a grid of `alpha_steps` values in [0, 1) by the output error it gives; alpha = 0 is plain - * rounding, so the search can only improve on it. A per-block clip search follows: each scale - * block's range is pulled in by up to half, in twentieths, and the fraction of least output error - * kept -- which is AWQ's auto_clip, the clamped weight quantised as it stands. + * A few input channels carry most of a layer's activation energy, and a weight column's output + * error scales with its channel's activation. AWQ scales each column up by s_j before quantising, + * so important channels use more of the grid, and the reader scales it back down. s_j = a_j^alpha + * over the channel activation magnitudes a_j, normalised so their geometric middle is one; alpha + * is picked from `alpha_steps` values in [0, 1) by output error. alpha = 0 is plain rounding, so + * the search never does worse. A per-block clip search follows (AWQ's auto_clip): each scale + * block's range is shrunk in steps of 0.05 and the factor with least output error is kept. * - * THE OUTPUT ERROR IS THE HESSIAN'S QUADRATIC FORM (lq_hess.h), over a sample of `sample_rows` rows - * for the alpha search and over each block's own columns -- H restricted to them -- for the clip, - * which is the error AWQ measures on its calibration activations, without needing them. a_j is - * sqrt(H_jj), the channel's root mean square. With no Hessian for a weight but an imatrix, the - * imatrix is the diagonal: a_j is sqrt of its importance and the error is diagonal-weighted; with - * neither, alpha is 0 and only the plain grid remains -- each said on stderr. + * Output error: the Hessian's quadratic form (lq_hess.h), over `sample_rows` rows for the alpha + * search and over each block's own columns (H restricted to them) for the clip. This is the error + * AWQ measures on calibration activations, without needing them. a_j = sqrt(H_jj), the channel's + * RMS. With no Hessian but an imatrix, the imatrix is the diagonal (a_j = sqrt(importance), error + * diagonal-weighted); with neither, alpha is 0 and only the plain grid remains. Each fallback is + * reported on stderr. * - * THE SCALES ARE STORED, NOT FOLDED. AWQ's reference implementation folds 1/s into the layer - * before (a norm or the previous projection), which needs the model's graph; here they are the - * encoding's last scale level, a [* x 1] plane of one value a column, `colscale` wide, and the - * stored value is the multiplier itself, c_j = 1/s_j rounded to that dtype. The weight is divided - * by the ROUNDED c_j before it is quantised, so what a reader multiplies back is what was divided. + * The scales are stored, not folded. The reference implementation folds 1/s into the preceding + * norm or projection, which needs the model graph. Here they are the encoding's last scale level, + * a [* x 1] plane with one `colscale`-typed value per column holding the multiplier c_j = 1/s_j. + * The weight is divided by the rounded c_j, so the reader multiplies back exactly what was divided. * - * NO TRANSFORM: the statistics are of the input's own channels, and a rotated weight's columns are - * not those channels. + * No transform: the statistics describe the input's own channels, which a rotated weight's columns + * are not. */ #include "lq_hess.h" #include "lq_quant.h" @@ -59,8 +56,8 @@ int awq_grid(const RadParam* o, int n_o, const RadQuantWeight* w, Grid* g, uint3 const char* c = rad_param_gets(o, n_o, "colscale", "f16"); *cdt = rad_dtype_parse(c); if (*cdt != RAD_F32 && *cdt != RAD_BF16 && *cdt != RAD_F16) - return refuse(w, "colscale= is f32, bf16 or f16"); - if (rad_param_geti(o, n_o, "alpha_steps", 20) < 1) return refuse(w, "alpha_steps= is >= 1"); + return refuse(w, "colscale= must be f32, bf16 or f16"); + if (rad_param_geti(o, n_o, "alpha_steps", 20) < 1) return refuse(w, "alpha_steps= must be >= 1"); return RAD_OK; } @@ -81,14 +78,6 @@ int awq_encoding(const RadParam* o, int n_o, const RadQuantWeight* w, RadEncodin int64_t awq_row_block(const RadParam*, int, const RadQuantWeight*) { return 0; } -float to_dt(uint32_t dt, float v) { - switch (dt) { - case RAD_BF16: return bf16_to_f32(f32_to_bf16(v)); - case RAD_F16: return f16_to_f32(f32_to_f16(v)); - default: return v; - } -} - /* The output error of a candidate, D = w_hat - w over `rows` rows: the Hessian's form, or the * diagonal's. */ struct Err { @@ -139,7 +128,7 @@ int awq_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src } const bool have = err.H || err.diag; - /* the channels' activation magnitudes, floored as AWQ floors them */ + /* Channel activation magnitudes, floored as AWQ floors them. */ std::vector a((size_t)K, 1.0); if (have) for (int64_t j = 0; j < K; ++j) { @@ -147,26 +136,17 @@ int awq_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src a[(size_t)j] = std::max(std::sqrt(std::max(e, 0.0)), 1e-4); } - /* THE SAMPLE: whole scale blocks of rows, evenly spread, so a candidate is quantised exactly - * as the full weight will be. */ + /* The sample: whole row blocks of the scale grid, evenly spread, so a candidate is quantised + * exactly as the full weight will be. */ const int64_t unit = g.br > 0 ? g.br : N; const int64_t nunits = (N + unit - 1) / unit; const int64_t take = std::min(nunits, std::max(1, want / unit)); std::vector pick; for (int64_t i = 0; i < take; ++i) pick.push_back(i * nunits / take); - int64_t srows = 0; - for (int64_t u : pick) srows += std::min(unit, N - u * unit); - std::vector ws((size_t)(srows * K)); - { - int64_t at = 0; - for (int64_t u : pick) { - const int64_t n = std::min(unit, N - u * unit); - std::memcpy(ws.data() + at * K, src + u * unit * K, (size_t)(n * K) * sizeof(float)); - at += n; - } - } + std::vector ws; + const int64_t srows = gather_units(src, N, K, unit, pick, &ws); - /* c_j for an exponent: the stored column multiplier, 1 / s_j rounded */ + /* c_j for an exponent: the stored column multiplier 1 / s_j, rounded to its dtype. */ auto colscales = [&](double alpha, std::vector* c) { std::vector s((size_t)K); double mx = 0.0, mn = 1e300; @@ -177,10 +157,11 @@ int awq_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src } const double norm = std::sqrt(mx * mn); c->resize((size_t)K); - for (int64_t j = 0; j < K; ++j) (*c)[(size_t)j] = to_dt(cdt, (float)(norm / s[(size_t)j])); + for (int64_t j = 0; j < K; ++j) + (*c)[(size_t)j] = round_to(cdt, (float)(norm / s[(size_t)j])); }; - /* ---- the exponent */ + /* Search the exponent. */ std::vector c, best_c, scaled((size_t)(srows * K)), fake((size_t)(srows * K)); colscales(0.0, &best_c); if (have) { @@ -203,12 +184,12 @@ int awq_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src std::fprintf(stderr, "libquant: awq: '%s' alpha %.3f\n", w->name, (double)best_k / steps); } - /* ---- the weight in its scaled form, every row */ + /* Scale the whole weight. */ for (int64_t r = 0; r < N; ++r) for (int64_t j = 0; j < K; ++j) src[r * K + j] /= best_c[(size_t)j]; - /* ---- the clip, block by block: the clamped block's own quantisation, measured in the - * original units against H over the block's columns */ + /* Clip search per block: quantise the clamped block and measure the error in original units + * against H over the block's columns. */ if (clip && have) { const int64_t br = g.br > 0 ? g.br : N, bc = g.bc > 0 ? g.bc : K; const int64_t nr = (N + br - 1) / br, nc = (K + bc - 1) / bc; @@ -267,9 +248,9 @@ int awq_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src } } - /* ---- the grid over the scaled, clipped weight, and the column scales after it. A column's - * importance in the scaled weight is its own times c_j squared: the error there is c_j times - * larger once the reader multiplies the column back. */ + /* Quantise the scaled, clipped weight, then store the column scales. A column's importance in + * the scaled weight is its own times c_j^2, since its error grows by c_j when the reader + * multiplies the column back. */ std::vector imp; if (w->importance) { imp.resize((size_t)K); diff --git a/libquant/lq_common.h b/libquant/lq_common.h index e1987a85..173ed9ee 100644 --- a/libquant/lq_common.h +++ b/libquant/lq_common.h @@ -1,11 +1,10 @@ -/* lq_common.h -- the number conversions every libquant quantiser shares, written out once. +/* lq_common.h -- number conversions shared by every libquant quantiser. * - * WHY THESE ARE NOT rad_plugin.h's. They are the rules the containers in service were quantised by, - * and a converter that wants to reproduce those containers byte for byte has to round exactly as - * they were rounded. Where a rule here and rad_plugin.h's agree on every finite input the - * difference is only in what a NaN becomes; where they could disagree -- the integer round, which - * is half AWAY from zero, and the fp4 encoder, which breaks a tie toward the even CODE -- the - * comment says so. Each is a pure function of its input. + * These are kept apart from rad_plugin.h's because they are the rules the containers in service + * were quantised with, and reproducing those containers byte for byte needs the same rounding. + * Where a rule here agrees with rad_plugin.h on every finite input, only the NaN result differs; + * where they can disagree (the integer round is half away from zero, the fp4 encoder breaks ties + * toward the even code) the function's comment says so. Each is a pure function of its input. */ #pragma once #include "rad_plugin.h" @@ -58,9 +57,9 @@ inline uint16_t f32_to_f16(float f) { } inline float f16_to_f32(uint16_t h) { return rad_f16_to_f32(h); } -/* E4M3-fn: clamp at 448, round to nearest even on the 3-bit mantissa, a real subnormal rung below - * 2^-6, and a NaN encoded as a signed zero -- a weight is never NaN, and the one place a NaN could - * come from is a scale of zero, which the scale rules below never produce. */ +/* E4M3-fn: clamp at 448, round to nearest even on the 3-bit mantissa, real subnormals below 2^-6. + * A NaN encodes as a signed zero: a weight is never NaN, and the only other source, a zero scale, + * is never produced by the scale rules. */ inline uint8_t f32_to_e4m3(float f) { uint32_t bits; std::memcpy(&bits, &f, 4); @@ -85,9 +84,9 @@ inline uint8_t f32_to_e4m3(float f) { return (uint8_t)(sign | m); } -/* FP4 e2m1 by nearest magnitude, a tie going to the EVEN CODE -- which on this grid is the - * smaller magnitude except at 2.5, where it is 2.0 (code 4) over 3.0 (code 5), the hardware's - * own round-to-nearest-even. */ +/* FP4 e2m1 by nearest magnitude, ties to the even code. On this grid that is the smaller magnitude + * except at 2.5, which goes to 2.0 (code 4) over 3.0 (code 5), as hardware round-to-nearest-even + * does. */ inline uint8_t f32_to_e2m1(float v) { static const float k[8] = { 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f }; const uint8_t sign = (v < 0.0f) ? 0x8u : 0x0u; @@ -101,15 +100,25 @@ inline uint8_t f32_to_e2m1(float v) { return (uint8_t)(sign | (uint8_t)best); } -/* Any small float grid by exhaustive nearest search over its codes, ties to the even code. For - * fp6 and e5m2, which nothing here needs to be fast. */ +/* `v` as a bf16, f16 or E4M3 value holds it, widened back; other dtypes pass it through. */ +inline float round_to(uint32_t dt, float v) { + switch (dt) { + case RAD_BF16: return bf16_to_f32(f32_to_bf16(v)); + case RAD_F16: return f16_to_f32(f32_to_f16(v)); + case RAD_F8E4M3: return rad_fp8e4m3_to_f32(f32_to_e4m3(v)); + default: return v; + } +} + +/* Any small float grid by exhaustive nearest search over its codes, ties to the even code. Used for + * fp6 and e5m2, where speed does not matter. */ inline uint32_t f32_to_small_float(float v, uint32_t dt) { const int bits = rad_dtype_bits(dt); const uint32_t n = 1u << bits; uint32_t best = 0; float bd = -1.0f; - /* Eight bytes, not one: rad_load_f32 reads any dtype up to 64 bits, and the compiler cannot - * see that `dt` is a small one. */ + /* Eight bytes: rad_load_f32 handles dtypes up to 64 bits, and the compiler cannot see that + * `dt` is small. */ uint8_t buf[8] = {}; for (uint32_t c = 0; c < n; ++c) { buf[0] = (uint8_t)c; @@ -121,21 +130,21 @@ inline uint32_t f32_to_small_float(float v, uint32_t dt) { return best; } -/* The integer round every integer grid here uses: HALF AWAY FROM ZERO, by truncation of v +- 0.5. - * It is what the containers in service were packed with, and lround differs from it only at - * values no representable f32 product reaches -- but "only" is a claim, and the byte-for-byte - * reproduction of those containers is a fact. */ +/* The integer round of every integer grid: half away from zero, by truncating v +- 0.5. The + * containers in service were packed with it. lround should agree on every value an f32 product + * reaches, but this is what is known to reproduce those containers byte for byte. */ inline int round_away(float v) { return (int)(v < 0.0f ? v - 0.5f : v + 0.5f); } inline int clampi(int v, int lo, int hi) { return v < lo ? lo : (v > hi ? hi : v); } -/* The unnormalised Sylvester Walsh-Hadamard transform in place, the butterfly keeping a+b low and - * a-b high: the transform an "fwhtN" encoding names and libr4d's r4d_fwht_wave computes. */ -inline void fwht_inplace(float* v, int64_t n) { +/* Unnormalised Sylvester Walsh-Hadamard transform in place, butterfly a+b low and a-b high: the + * transform an "fwhtN" encoding names and libr4d's r4d_fwht_wave computes. */ +template +inline void fwht_inplace(T* v, int64_t n) { for (int64_t h = 1; h < n; h <<= 1) for (int64_t i = 0; i < n; i += h << 1) for (int64_t j = i; j < i + h; ++j) { - const float a = v[j], b = v[j + h]; + const T a = v[j], b = v[j + h]; v[j] = a + b; v[j + h] = a - b; } diff --git a/libquant/lq_ggml.cpp b/libquant/lq_ggml.cpp index e0f45158..83eaeab8 100644 --- a/libquant/lq_ggml.cpp +++ b/libquant/lq_ggml.cpp @@ -1,13 +1,12 @@ /* lq_ggml.cpp -- the `ggml` quantiser: llama.cpp's formats, llama.cpp's codes, radiance's planes. * * A row is quantised by llama.cpp's own quantize_ (lq_ggml_port.h), with the imatrix's - * column importances as its quant_weights, and the GGUF blocks it writes are then UNPACKED into - * the affine planes of rad_encoding.h. The codes and scales are therefore exactly llama.cpp's -- - * a llama.cpp model and a radiance container quantised from the same weights and the same imatrix - * hold the same numbers -- while the container holds an encoding every reader decodes, rather - * than a block layout one kernel family was written against. + * column importances as quant_weights, and the resulting GGUF blocks are unpacked into the affine + * planes of rad_encoding.h. A llama.cpp model and a radiance container quantised from the same + * weights and imatrix therefore hold the same numbers, but the container stores a generic encoding + * instead of a block layout tied to one kernel family. * - * ===================================================================== THE PLANES + * ===================================================================== The planes * * Each type's planes, in order. [R x C] is a TILED plane's block, {R x C} a TABLE's extents, * a * whole extent; d and dmin are the block's f16 super-scales, copied bit for bit. @@ -40,32 +39,30 @@ * iq1_m codes u11 [1x8]; grid i8 {2048x8}; scale u4 [1x16] = 2ls+1; scale.1 f16 [1x256] = d * (assembled from the scale words' top nibbles); zero bf16 [1x8] = -delta * - * Every line is llama.cpp's dequantize_row_ rewritten in the affine order, q = code | - * grid | table, negated by its sign, less its zero, times every scale level, less every min level: + * Each line is llama.cpp's dequantize_row_ rewritten in the affine order (q = code | grid | + * table, negated by its sign, less its zero, times every scale level, less every min level): * q4_1's `q*d + m` is `q*d - (-m)`, iq1's `dl*(grid + delta)` is `(grid - (-delta))*scale*d`, and - * the IQ2/IQ3 `d*(0.5 + ls)*0.25` is `(2ls+1)*d/8`. Nothing is rounded on the way: every plane - * holds a value of the block exactly, so the planes go back to the same GGUF blocks. + * the IQ2/IQ3 `d*(0.5 + ls)*0.25` is `(2ls+1)*d/8`. Nothing is rounded: every plane holds a block + * value exactly, so the planes convert back to the same GGUF blocks. * - * THE 1/8 AND 1/4 ARE A PER-TENSOR LEVEL OF THEIR OWN, NOT FOLDED INTO d. d/8 in f16 is exact only - * while it stays normal, d >= 2^-11, and an IQ2 d is about a super-block's largest value over 155: - * on Gaussian weights of standard deviation 0.02, a transformer linear's usual spread, 98-100% of - * IQ2 and IQ3_XXS super-blocks have d/8 or d/4 below f16's normal range, and folded in they would - * lose up to three bits of their scale. As an f32 [*x*] constant the factor costs four bytes a - * weight and multiplies exactly. + * The 1/8 and 1/4 are a per-tensor level, not folded into d. d/8 in f16 is exact only while it + * stays normal (d >= 2^-11), and an IQ2 d is about a super-block's largest value over 155. On + * Gaussian weights with std 0.02, typical for transformer linears, 98-100% of IQ2 and IQ3_XXS + * super-blocks have d/8 or d/4 below f16's normal range and would lose up to three bits of scale. + * As an f32 [*x*] constant the factor costs four bytes per tensor and multiplies exactly. * - * EVERY PRODUCT IN THE DECODE IS EXACT IN F32, so the affine order -- code times sub-scale times - * d, where llama.cpp forms d times sub-scale first -- gives llama.cpp's dequantised values bit for - * bit. d is an f16, eleven significant bits, and a code or grid value times its sub-scale has at - * most twelve (q6_K's 31 x 127 and iq4_xs's 127 x 31 are the widest), so no product of the chain - * rounds in either order; only the subtraction of a min -- q4_1, q5_1, q2_K, q4_K, q5_K -- rounds, - * once, on the same two operands. + * Every product in the decode is exact in f32, so the affine order (code * sub-scale * d, where + * llama.cpp forms d * sub-scale first) reproduces llama.cpp's dequantised values bit for bit. d is + * an f16 with 11 significant bits and a code or grid value times its sub-scale has at most 12 + * (q6_K's 31 x 127 and iq4_xs's 127 x 31 are the widest), so no product rounds in either order. + * Only the min subtraction (q4_1, q5_1, q2_K, q4_K, q5_K) rounds, once, on the same two operands. */ #include "lq_ggml.h" #include "lq_ggml_port.h" +#include "lq_quant.h" #include "rad_plugin.h" #include -#include #include #include #include @@ -78,10 +75,9 @@ using namespace lq::ggml; /* ================================================================== writing a plane row */ -/* A plane row written front to back, `bits` an element, lowest bits first -- the bit stream - * rad_encoding.h defines. Thirty-two bits go out at a time and the tail on flush(), so every byte - * of the row is written exactly once and nothing is read back: the row arrives zeroed, but a - * writer that ORs into it would be relying on that, and one that stores whole bytes is not. */ +/* Writes a plane row front to back, `bits` per element, lowest bits first (rad_encoding.h's bit + * stream). 32 bits go out at a time and the tail on flush(), so each byte is stored exactly once + * and never read back; this does not rely on the row arriving zeroed. */ class Bits { public: explicit Bits(uint8_t* row) : p_(row) {} @@ -115,7 +111,7 @@ inline void put16(uint8_t* row, int64_t i, uint16_t h) { row[2 * i + 1] = (uint8_t)(h >> 8); } -/* Two 4-bit codes a byte, element 2k low: q[] holds a block's codes in value order. */ +/* Two 4-bit codes per byte, element 2k low; q[] holds a block's codes in value order. */ inline void put_nibbles(uint8_t* row, const uint8_t* q, int n) { for (int k = 0; k < n / 2; ++k) row[k] = (uint8_t)((q[2 * k] & 15) | ((q[2 * k + 1] & 15) << 4)); @@ -131,9 +127,9 @@ inline uint16_t iq1_zero(bool negative_delta) { return negative_delta ? 0x3E00 : /* ================================================================== unpacking a row's blocks * - * Each unpack_ reads `nb` blocks -- one row -- and writes plane i's row at row[i]; a TABLE - * or per-tensor plane's slot is null and is written once a call, by write_shared. The index - * arithmetic is the inverse of the type's dequantize_row_, value by value. */ + * Each unpack_ reads the `nb` blocks of one row and writes plane i's row at row[i]. A TABLE + * or per-tensor plane's slot is null; write_shared writes those once per call. The index + * arithmetic inverts the type's dequantize_row_, value by value. */ void unpack_q8_0(const void* v, int64_t nb, uint8_t* const* row) { const block_q8_0* b = (const block_q8_0*)v; @@ -233,10 +229,10 @@ void unpack_q3_K(const void* v, int64_t nb, uint8_t* const* row) { Bits c(row[0]), s(row[1]); for (int64_t i = 0; i < nb; ++i) { const block_q3_K& x = b[i]; - /* the high bit of value k is bit k/32 of hmask[k%32] */ + /* The high bit of value k is bit k/32 of hmask[k%32]. */ for (int k = 0; k < QK_K; ++k) c.put(k_low2(x.qs, k) + 4u * ((x.hmask[k % 32] >> (k / 32)) & 1u) - 4u, 3); - /* the sixteen 6-bit scales, unpacked as quantize_row_q3_K_ref re-reads them */ + /* The sixteen 6-bit scales, unpacked as quantize_row_q3_K_ref re-reads them. */ for (int j = 0; j < QK_K / 16; ++j) { const int lo = j < 8 ? x.scales[j] & 0xF : x.scales[j - 8] >> 4; const int sc = lo | (((x.scales[8 + j % 4] >> (2 * (j / 4))) & 3) << 4); @@ -354,8 +350,8 @@ void unpack_iq4_xs(const void* v, int64_t nb, uint8_t* const* row) { s.flush(); } -/* The IQ2 and IQ3 types: a sign byte covers eight values, bit j value j, which is the u1 plane's - * own order -- so a group of eight's signs are one byte of it. */ +/* IQ2 and IQ3: a sign byte covers eight values, bit j for value j. That is the u1 plane's own + * order, so a group of eight's signs is one byte of it. */ void unpack_iq2_xxs(const void* v, int64_t nb, uint8_t* const* row) { const block_iq2_xxs* b = (const block_iq2_xxs*)v; Bits s(row[3]); @@ -435,7 +431,7 @@ void unpack_iq3_s(const void* v, int64_t nb, uint8_t* const* row) { Bits c(row[0]), s(row[3]); for (int64_t i = 0; i < nb; ++i) { const block_iq3_s& x = b[i]; - /* the ninth bit of the grid index of 4-group g is bit g%8 of qh[g/8] */ + /* The ninth bit of 4-group g's grid index is bit g%8 of qh[g/8]. */ for (int g = 0; g < QK_K / 4; ++g) c.put(x.qs[g] | (uint32_t)((x.qh[g / 8] >> (g % 8)) & 1) << 8, 9); std::memcpy(row[2] + (QK_K / 8) * i, x.signs, QK_K / 8); @@ -529,7 +525,7 @@ const Kind kKinds[] = { { "iq1_m", GGML_TYPE_IQ1_M, QK_K, quantize_iq1_m, unpack_iq1_m }, }; -/* The encoding a type writes; the mapping in the header comment, plane for plane. */ +/* The encoding a type writes, plane for plane as listed in the file header. */ RadEncoding encoding_of(ggml_type t) { RadEncoding e; rad_enc_clear(&e); @@ -634,8 +630,8 @@ void fill_grid(uint8_t* out, const W* grid, int n) { out[k * (int)sizeof(W) + j] = (uint8_t)(grid[k] >> (8 * j)); } -/* The planes every row shares -- a codebook, IQ4's levels, IQ2/IQ3's 1/8 or 1/4 -- written whole - * by every call, because rad-convert decodes each call's rows as soon as they are written. */ +/* The planes all rows share (a codebook, IQ4's levels, IQ2/IQ3's 1/8 or 1/4). Every call writes + * them in full, because rad-convert decodes each call's rows as soon as they are written. */ void write_shared(ggml_type t, const RadEncoding& e, void* const* planes) { for (int i = 0; i < e.n_planes; ++i) { const RadEncPlane& p = e.plane[i]; @@ -668,16 +664,11 @@ bool same_name(const char* a, const char* b) { return *a == *b; } -const char* wname(const RadQuantWeight* w) { return w && w->name ? w->name : "?"; } - -/* The type the options name. RAD_E_INVAL, said with the weight's name, when there is none. */ +/* The type the options name, or RAD_E_INVAL with a message naming the weight. */ int kind_of(const RadParam* o, int n_o, const RadQuantWeight* w, const Kind** out) { const char* t = rad_param_gets(o, n_o, "type", nullptr); - if (!t) { - std::fprintf(stderr, "libquant: %s: type= is required: the llama.cpp type to write, e.g. " - "q4_K, q8_0, iq4_xs\n", wname(w)); - return RAD_E_INVAL; - } + if (!t) + return refuse(w, "type= is required: the llama.cpp type to write, e.g. q4_K, q8_0, iq4_xs"); for (const Kind& k : kKinds) if (same_name(t, k.name)) { *out = &k; @@ -685,15 +676,14 @@ int kind_of(const RadParam* o, int n_o, const RadQuantWeight* w, const Kind** ou } std::string all; for (const Kind& k : kKinds) all += std::string(all.empty() ? "" : " ") + k.name; - std::fprintf(stderr, "libquant: %s: type=%s is not a llama.cpp type this quantiser writes " - "(%s)\n", wname(w), t, all.c_str()); - return RAD_E_INVAL; + return refuse(w, ("type=" + std::string(t) + " is not a llama.cpp type this quantiser writes (" + + all + ")").c_str()); } -/* A rank-1 weight, and one whose rows do not divide into the type's blocks, is declined: the next - * rule takes it -- a norm, or a 2880-wide projection that a q4_K pattern happened to match. */ +/* A rank-1 weight, or one whose rows do not divide into the type's blocks, is declined so the next + * rule takes it (a norm, or a 2880-wide projection a q4_K pattern happened to match). */ int ggml_encoding(const RadParam* o, int n_o, const RadQuantWeight* w, RadEncoding* out) { - if (!w || w->rank < 2) return RAD_E_UNSUPPORTED; + if (declines(w)) return RAD_E_UNSUPPORTED; const Kind* k = nullptr; const int st = kind_of(o, n_o, w, &k); if (st != RAD_OK) return st; @@ -703,7 +693,7 @@ int ggml_encoding(const RadParam* o, int n_o, const RadQuantWeight* w, RadEncodi return RAD_OK; } -/* Rows are independent in every type: a block never spans two, and the imatrix is per column. */ +/* Rows are independent in every type: a block never spans rows, and the imatrix is per column. */ int64_t ggml_row_block(const RadParam*, int, const RadQuantWeight*) { return 1; } int ggml_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src, int64_t row0, @@ -714,14 +704,12 @@ int ggml_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* sr if (!w || w->rank < 2 || w->cols <= 0 || w->rows <= 0 || w->cols % k->block || row0 < 0 || rows < 0 || row0 + rows > w->rows) return RAD_E_SHAPE; - /* NO SEARCH WITHOUT ITS WEIGHTS. llama.cpp's iq2_xxs, iq2_xs and iq1_s assert the imatrix is - * there and have no other path; substituting one would write a format llama.cpp could not - * have written, under its name. */ - if (!w->importance && ggml_quantize_requires_imatrix(k->type)) { - std::fprintf(stderr, "libquant: %s: type=%s needs an imatrix, and the converter has none " - "for this weight (rad-convert --imatrix FILE)\n", wname(w), k->name); - return RAD_E_INVAL; - } + /* llama.cpp's iq2_xxs, iq2_xs and iq1_s require the imatrix and have no other path; + * substituting one would write, under llama.cpp's type name, data llama.cpp could not have + * produced. */ + if (!w->importance && ggml_quantize_requires_imatrix(k->type)) + return refuse(w, ("type=" + std::string(k->name) + " needs an imatrix, and the converter " + "has none for this weight (rad-convert --imatrix FILE)").c_str()); ggml_quantize_init(k->type); const RadEncoding e = encoding_of(k->type); diff --git a/libquant/lq_ggml_port.cpp b/libquant/lq_ggml_port.cpp index cfa36f29..3a1f548c 100644 --- a/libquant/lq_ggml_port.cpp +++ b/libquant/lq_ggml_port.cpp @@ -19,10 +19,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * The functions below are ggml/src/ggml-quants.c's at 06938ac12, in that file's order, each under - * a `ggml-quants.c:A-B` marker naming the lines it came from; the conversions and the init - * dispatch at the head and the foot are ggml-impl.h's and ggml.c's. The bodies are left as - * upstream wrote them -- their comments, their spacing, their commented-out lines -- because the - * point of the port is that it can be read against the original line by line. + * a `ggml-quants.c:A-B` marker naming its source lines; the conversions at the head and the init + * dispatch at the foot are ggml-impl.h's and ggml.c's. The bodies keep upstream's comments, + * spacing and commented-out lines so the port can be diffed against the original line by line. */ #include "lq_ggml_port.h" @@ -42,8 +41,8 @@ namespace lq::ggml { #define GGML_RESTRICT __restrict__ -/* ggml.h's assertion, which aborts the process with a message in every build: a broken invariant - * in a quantiser is a corrupt container if it is allowed to continue. */ +/* ggml.h's assertion: prints and aborts in every build, since a quantiser that continues past a + * broken invariant writes a corrupt container. */ #define GGML_ABORT(msg) \ do { \ std::fprintf(stderr, "libquant: ggml port: %s:%d: %s\n", __FILE__, __LINE__, msg); \ @@ -4245,9 +4244,9 @@ size_t quantize_iq2_s(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, /* ================================================================== ggml.c: ggml_quantize_init * - * ggml guards the table build with a global critical section and the build itself with an `if - * (grid) return`; one std::once_flag a table does both. IQ1_S and IQ1_M share a table (the same - * lattice and the same neighbour count), and so share a flag. */ + * ggml guards the table build with a global critical section plus an `if (grid) return`; here one + * std::once_flag per table does both. IQ1_S and IQ1_M share a table (same lattice and neighbour + * count) and so share a flag. */ void ggml_quantize_init(enum ggml_type type) { static std::once_flag once_iq2[4]; static std::once_flag once_iq3[2]; diff --git a/libquant/lq_ggml_port.h b/libquant/lq_ggml_port.h index 7246d59c..964f73d9 100644 --- a/libquant/lq_ggml_port.h +++ b/libquant/lq_ggml_port.h @@ -17,11 +17,11 @@ * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - * ===================================================================== WHAT THIS IS + * ===================================================================== Overview * * The block layouts, value tables and quantisation searches of llama.cpp's ggml library at commit - * 06938ac12, taken over so that the `ggml` quantiser (lq_ggml.cpp) chooses exactly the codes and - * scales llama.cpp would for the same weight and the same imatrix: + * 06938ac12, so that the `ggml` quantiser (lq_ggml.cpp) chooses the same codes and scales as + * llama.cpp for the same weight and imatrix: * * ggml/src/ggml-common.h the block structs below, and the tables in lq_ggml_tables.cpp: * kmask_iq2xs, ksigns_iq2xs, iq2xxs_grid, iq2xs_grid, iq2s_grid, @@ -38,26 +38,24 @@ * ggml/src/ggml.c ggml_quantize_init's choice of table per type, and * ggml_quantize_requires_imatrix's list * - * THE NUMERICS ARE LLAMA.CPP'S TO THE BIT: the same float operations in the same order, the same - * f16 rounding, the same `nearest_int` magic-number round, the same qsort over the same comparators - * -- so the bytes a quantize_ here writes are the bytes llama.cpp's writes, which was checked - * against llama.cpp itself and is pinned in tests/quant_ggml_test.cpp. The port departs from the - * original only where C++ requires it (a cast from void*), where a library inside a converter has - * to (a failed assertion says so on stderr and aborts instead of calling ggml_abort; the Oops - * diagnostics go to stderr, not stdout), and in the one-time table build (std::call_once in place - * of ggml's critical section; the tables live for the life of the process and have no free). + * The numerics match llama.cpp bit for bit: the same float operations in the same order, the same + * f16 rounding, the same `nearest_int` magic-number round and the same qsort comparators, so each + * quantize_ writes the bytes llama.cpp writes (pinned in tests/quant_ggml_test.cpp). The port + * departs from upstream only where C++ requires it (a cast from void*), where a library inside a + * converter must (a failed assertion prints to stderr and aborts instead of calling ggml_abort; + * the Oops diagnostics go to stderr, not stdout), and in the one-time table build (std::call_once + * instead of ggml's critical section; the tables live for the process and are never freed). * - * THE MATCH IS WITH LLAMA.CPP AS ITS OWN BUILD COMPILES ggml-quants.c: into ggml-base, with no - * -march, so with no fused multiply-add. libquant's -ffp-contract=off holds the port there on - * every target. A llama.cpp compiled with FMA contraction -- -march=native on x86-64, or any - * aarch64 build, where FMA is in the base instruction set -- rounds inside the searches and writes - * different bytes for most types. + * The match is with llama.cpp as its own build compiles ggml-quants.c: into ggml-base with no + * -march, so without fused multiply-add. libquant's -ffp-contract=off holds the port there on + * every target. A llama.cpp built with FMA contraction (-march=native on x86-64, or any aarch64 + * build, where FMA is baseline) rounds inside the searches and writes different bytes for most + * types. * - * Each quantize_ keeps llama.cpp's own dispatch: the legacy and K types take the _ref - * round-to-nearest path when `quant_weights` is null and the _impl search otherwise; the I types - * take their _impl with whatever `quant_weights` is, and three of those assert it is there - * (ggml_quantize_requires_imatrix). `quant_weights` is the imatrix's per-column importance, - * n_per_row of it, shared by every row. + * Each quantize_ keeps llama.cpp's dispatch: legacy and K types take the _ref round-to-nearest + * path when `quant_weights` is null and the _impl search otherwise; I types always take _impl, + * and three of them assert `quant_weights` is set (ggml_quantize_requires_imatrix). + * `quant_weights` is the imatrix's per-column importance, n_per_row values shared by every row. */ #pragma once @@ -300,9 +298,9 @@ extern const uint64_t iq1s_grid[NGRID_IQ1S]; /* ================================================================== the quantisers */ -/* Build the search tables an I type needs -- the lattice, its index map and every off-grid - * point's nearest neighbours -- once for the life of the process, whichever thread asks first; a - * no-op for the other types. Every quantize_ below expects it to have run for its type. */ +/* Build the search tables an I type needs (the lattice, its index map and each off-grid point's + * nearest neighbours) once per process, on whichever thread asks first; a no-op for other types. + * Every quantize_ below requires it to have run for its type. */ void ggml_quantize_init(enum ggml_type type); /* ggml_quantize_requires_imatrix: the types whose search has no path without `quant_weights`. */ diff --git a/libquant/lq_ggml_tables.cpp b/libquant/lq_ggml_tables.cpp index 633e3cca..452b41d9 100644 --- a/libquant/lq_ggml_tables.cpp +++ b/libquant/lq_ggml_tables.cpp @@ -19,9 +19,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * ggml/src/ggml-common.h at 06938ac12, the GGML_COMMON_IMPL_C tables, verbatim. These are the - * tables llama.cpp's DEquantisers read: an I-quant's grid index means the entry here, which is - * what the `ggml` quantiser copies into an encoding's grid and table planes. The searches build - * their own lattices from the kgrid tables in lq_ggml_port.cpp, in the same index order. + * tables llama.cpp's dequantisers read; the `ggml` quantiser copies them into an encoding's grid + * and table planes. The searches build their own lattices from the kgrid tables in + * lq_ggml_port.cpp, in the same index order. */ #include "lq_ggml_port.h" diff --git a/libquant/lq_gptq.cpp b/libquant/lq_gptq.cpp index 7c14e159..e8195373 100644 --- a/libquant/lq_gptq.cpp +++ b/libquant/lq_gptq.cpp @@ -16,11 +16,11 @@ namespace lq { namespace { -/* H is damped, inverted and re-factorised into the upper triangle U with U^T U = H^-1, the form - * the sequential loop wants: column i's error is divided by U[i][i] and spread over columns j > i - * with weight U[i][j]. Frantar's formulation, followed rather than re-derived. DOUBLE throughout: - * a Cholesky is K^3/6 accumulations deep, and f32 there costs real conditioning on a matrix that - * is near-singular in the directions a rotation flattened. */ +/* H is damped, inverted and re-factorised into upper U with U^T U = H^-1, the form the sequential + * loop wants: column i's error is divided by U[i][i] and spread over columns j > i with weight + * U[i][j] (Frantar et al.'s formulation). Double throughout: a Cholesky is K^3/6 accumulations + * deep, and f32 loses real conditioning on a matrix near-singular in the directions a rotation + * flattened. */ bool chol_lower(std::vector& a, int64_t k) { for (int64_t i = 0; i < k; ++i) { for (int64_t j = 0; j <= i; ++j) { @@ -98,9 +98,8 @@ std::vector gptq_act_order(const char* dir, const char* name, int64_t K if (!dir || !*dir || !name || !*name || K <= 0) return perm; std::vector acc; if (!calib_sum(dir, calib_resolve(dir, name, K), K, domain, &acc)) return perm; - /* THE COLUMNS OF LARGEST INPUT ENERGY FIRST, a tie in the order the columns sit: the - * recursion has the most freedom to absorb error early, so the columns that cost most to get - * wrong are quantised while every later column is still there to take it. */ + /* Largest input energy first, ties in column order. The recursion absorbs error best early, + * so the costliest columns are quantised while every later column can still take it. */ std::stable_sort(perm.begin(), perm.end(), [&](int32_t x, int32_t y) { return acc[(size_t)x * (size_t)K + (size_t)x] > acc[(size_t)y * (size_t)K + (size_t)y]; }); @@ -117,9 +116,8 @@ Gram gptq_factor(const char* dir, const char* name, int64_t K, int64_t domain, d const std::string key = std::string(dir) + "|" + stem + "|" + std::to_string(K) + "|" + std::to_string(domain) + "|" + dk + (perm ? "|act" : ""); - /* A LAYER'S FACTOR IS SHARED by every expert that reads it, so it is made once under the - * lock and kept; an expert's own is made for its one call, outside it, so experts quantised - * side by side factor side by side. */ + /* A layer's factor is shared by its experts, so it is built once under the lock and cached. + * An expert's own is built for its one call outside the lock, so experts factor in parallel. */ Cache& c = cache(); std::unique_lock lk(c.mu, std::defer_lock); if (layer) { @@ -139,8 +137,8 @@ Gram gptq_factor(const char* dir, const char* name, int64_t K, int64_t domain, d "rounding it to nearest\n", name, dir, stem.c_str()); return keep(nullptr); } - /* Under act order the Hessian is the PERMUTED one, P H P^T: the recursion runs over the - * columns in the order they are quantised, and that is the order the factor has to be in. */ + /* Under act order the factor is of P H P^T, since the recursion runs over columns in + * quantisation order. */ if (perm) { std::vector p((size_t)(K * K)); for (int64_t i = 0; i < K; ++i) @@ -155,9 +153,9 @@ Gram gptq_factor(const char* dir, const char* name, int64_t K, int64_t domain, d if (!(acc[(size_t)(i * K + i)] > 0.0)) ++dead; tr += acc[(size_t)(i * K + i)]; } - /* A DEAD COLUMN IS A CHANNEL THE CORPUS NEVER EXERCISED: its diagonal is zero, the Cholesky - * would fail on it, and the calibration says nothing about it -- so it gets the mean diagonal, - * which makes the recursion leave it alone rather than spend other columns' error on it. */ + /* A dead column is a channel the corpus never exercised: its diagonal is zero, the Cholesky + * would fail on it, and the calibration says nothing about it. It gets the mean diagonal, so + * the recursion does not spend other columns' error on it. */ const double mean = tr / (double)K; const double lam = damp * mean; for (int64_t i = 0; i < K; ++i) { @@ -206,10 +204,9 @@ void gptq_quantise(const Grid& g, float* w, int32_t* codes, const Scales& scales return; } - /* COLUMN BLOCKS OUTSIDE, ROWS INSIDE. The recursion is independent per row, so rows are the - * parallelism; but a row that ran the full K alone would stream all K^2 of `u` for itself. - * With the block outside, every row is at the same columns at the same time and the slice of - * `u` they share -- 128 x K -- stays in cache. */ + /* Column blocks outside, rows inside. Rows are independent and are the parallelism, but a row + * running all of K alone would stream all K^2 of `u`. With the block loop outside, all rows + * work on the same columns together and the shared 128 x K slice of `u` stays in cache. */ const int64_t B = 128; std::vector err((size_t)(N * B)); for (int64_t b0 = 0; b0 < K; b0 += B) { @@ -226,7 +223,7 @@ void gptq_quantise(const Grid& g, float* w, int32_t* codes, const Scales& scales const float v = wr[i]; const float dq = one(n, i, v); wr[i] = dq; - /* d is U[i][i], strictly positive by construction -- chol_upper refuses otherwise */ + /* d is U[i][i], strictly positive: chol_upper refuses otherwise. */ const float e = (v - dq) / d; er[i - b0] = e; for (int64_t j = i + 1; j < b1; ++j) wr[j] -= e * ur[j]; @@ -243,19 +240,21 @@ void gptq_quantise(const Grid& g, float* w, int32_t* codes, const Scales& scales void gptq_refine(const Grid& g, const float* x, float* w, int32_t* codes, const Scales& scales, int64_t N, int64_t K, const float* h, double damp, int passes) { if (!x || !w || !codes || !h || N <= 0 || K <= 0 || passes <= 0) return; - /* THE DAMPING GPTQ'S FACTOR CARRIES, so the two minimise the same form: lambda is `damp` of - * the mean diagonal, and a column the corpus never exercised takes the mean as its diagonal. */ + /* Same damping as gptq_factor, so both minimise the same form: lambda is `damp` times the mean + * diagonal, and an unexercised column takes the mean as its diagonal. `ad` is what the form + * adds to H's diagonal, `dg` the resulting diagonal. */ double tr = 0.0; for (int64_t i = 0; i < K; ++i) tr += h[(size_t)(i * K + i)]; const double mean = tr / (double)K; const float lam = (float)(damp * mean); - std::vector dg((size_t)K); + std::vector ad((size_t)K), dg((size_t)K); for (int64_t i = 0; i < K; ++i) { const float d = h[(size_t)(i * K + i)]; + ad[(size_t)i] = (d > 0.0f ? 0.0f : (float)mean) + lam; dg[(size_t)i] = (d > 0.0f ? d : (float)mean) + lam; } - /* G = E H for every row at once, by the deterministic blocked product; each row then keeps - * its own G current with one row of H per code that moves. */ + /* G = E (H + diag(ad)) for all rows by the deterministic blocked product; each row then keeps + * its G current by adding one row of it per code that moves. */ std::vector e((size_t)(N * K)), gm((size_t)(N * K)); for (size_t i = 0; i < e.size(); ++i) e[i] = w[i] - x[i]; mat_hess(e.data(), N, K, h, gm.data()); @@ -268,7 +267,7 @@ void gptq_refine(const Grid& g, const float* x, float* w, int32_t* codes, const const float* xr = x + (size_t)(n * K); float* wr = w + (size_t)(n * K); int32_t* cr = codes + (size_t)(n * K); - for (int64_t j = 0; j < K; ++j) gr[j] += lam * er[j]; + for (int64_t j = 0; j < K; ++j) gr[j] += ad[(size_t)j] * er[j]; for (int pass = 0; pass < passes; ++pass) { int64_t moved = 0; for (int64_t j = 0; j < K; ++j) { @@ -280,12 +279,12 @@ void gptq_refine(const Grid& g, const float* x, float* w, int32_t* codes, const if (c == cr[j]) continue; const float dq = grid_decode(g, b, c); const float d = (dq - xr[j]) - er[j]; - /* Only a strict improvement moves a code: the change in the form is - * d (2 g_j + d hj), g_j the current gradient, and a tie keeps GPTQ's choice. */ + /* Only a strict improvement moves a code: the form changes by d (2 g_j + d hj), + * g_j the current gradient; a tie keeps GPTQ's choice. */ if (!(d * (2.0f * gr[j] + d * hj) < 0.0f)) continue; const float* hr = h + (size_t)(j * K); for (int64_t t2 = 0; t2 < K; ++t2) gr[t2] += d * hr[t2]; - gr[j] += lam * d; + gr[j] += ad[(size_t)j] * d; er[j] += d; wr[j] = dq; cr[j] = c; diff --git a/libquant/lq_gptq.h b/libquant/lq_gptq.h index 2bfd6d51..0401f9e0 100644 --- a/libquant/lq_gptq.h +++ b/libquant/lq_gptq.h @@ -1,20 +1,18 @@ /* lq_gptq.h -- error-feedback quantisation on any grid, against a calibration Hessian. * - * GPTQ picks the codes of one column at a time and pushes the rounding error of that column into - * the columns it has not reached yet, weighted by the inverse Hessian of the layer's real input. - * It is the difference between a four-bit expert that serves and one that does not: plain - * rounding treats every column as independent, and a 4-bit grid does not have the levels to - * absorb that. + * GPTQ picks the codes one column at a time and pushes each column's rounding error into the + * columns not yet reached, weighted by the inverse Hessian of the layer's real input. Plain + * rounding treats every column as independent, and a 4-bit grid lacks the levels to absorb that. * - * WHAT IS HERE IS THE HESSIAN AND THE LOOP, not the grid: the codes are chosen on whatever grid - * the rule names (lq_grid.h), against scales fixed BEFORE the loop from the (transformed) weight -- - * the "static groups" form, which keeps a scale plane a function of the weight alone. + * This file holds the Hessian and the loop, not the grid: codes are chosen on whatever grid the + * rule names (lq_grid.h), against scales fixed before the loop from the (transformed) weight. This + * "static groups" form keeps a scale plane a function of the weight alone. * - * THE HESSIAN IS AN EXPERT'S OWN WHERE THE TAP RECORDED ONE, the layer's otherwise (lq_hess.h, - * calib_resolve). A layer's pooled Hessian is found from the weight's logical name with an expert - * index stripped, so the experts reading it share one factor and pay for it once; an expert's own - * is factored for its one call. The engine's calibration tap writes both (arch/common/rad_arch.h, - * RADIANCE_CALIB_DIR); docs/MOE-W4.md walks the bootstrap. + * The Hessian is the expert's own where the tap recorded one, else the layer's (lq_hess.h, + * calib_resolve). A layer's pooled Hessian is found from the weight's logical name with the expert + * index stripped, so its experts share one factor; an expert's own is factored for its one call. + * The engine's calibration tap writes both (arch/common/rad_arch.h, RADIANCE_CALIB_DIR); + * docs/MOE-W4.md describes the bootstrap. */ #pragma once #include "lq_grid.h" @@ -22,18 +20,18 @@ namespace lq { -/* The upper Cholesky factor U of the damped inverse Hessian, U^T U = (H + lambda I)^-1, as a K x K - * row-major f32 plane, for the weight named `name`. Null when `dir` has no calibration for it -- - * which is not an error, and the weight is then rounded to nearest -- and also null, with a - * message, when a file is there and unusable, so a typo'd directory is not silently a quality - * regression. With `perm` (gptq_act_order's) it is the factor of the permuted Hessian P H P^T. - * `domain` is the grid's transform width, 0 without one (calib_sum). A layer's is cached for the - * life of the process by (dir, stem, K, domain, damp, act order); an expert's own is not. */ +/* Upper Cholesky factor U of the damped inverse Hessian, U^T U = (H + lambda I)^-1, as a K x K + * row-major f32 plane, for weight `name`. Null when `dir` has no calibration for it (not an error: + * the weight is then rounded to nearest). Also null, with a message, when a file exists but is + * unusable, so a mistyped directory is not a silent quality loss. With `perm` (gptq_act_order's) + * it factors the permuted Hessian P H P^T. `domain` is the grid's transform width, 0 without one + * (calib_sum). A layer's factor is cached for the process by (dir, stem, K, domain, damp, act + * order); an expert's own is not. */ Gram gptq_factor(const char* dir, const char* name, int64_t K, int64_t domain, double damp, const int32_t* perm = nullptr); -/* ACT ORDER: the columns by descending Hessian diagonal -- the input energy each one carries -- - * ties in column order. The identity when `dir` holds nothing for the weight. */ +/* Act order: columns by descending Hessian diagonal (the input energy each carries), ties in + * column order. The identity when `dir` holds nothing for the weight. */ std::vector gptq_act_order(const char* dir, const char* name, int64_t K, int64_t domain); /* Quantise `w` [N, K] in place on grid `g` against `scales` (grid_scales'), writing codes to @@ -42,13 +40,12 @@ std::vector gptq_act_order(const char* dir, const char* name, int64_t K void gptq_quantise(const Grid& g, float* w, int32_t* codes, const Scales& scales, int64_t N, int64_t K, const float* u); -/* COORDINATE DESCENT AFTER THE LOOP: `passes` sweeps over the columns of every row, each code - * re-chosen on the grid at its conditional optimum -- the value that minimises the row's - * e (H + lambda I) e^T, e = decoded - x, with every other column held -- against the same damped - * Hessian GPTQ factored. GPTQ chooses each column once, before the columns after it are known; - * a sweep revisits that choice with all of them in place, and never raises the objective. - * `x` [N, K] is the weight GPTQ was handed (transformed), `w` its decoded result, updated in - * place with `codes`. `h` is the undamped Gram (calib_gram's), null for nothing to do. */ +/* Coordinate descent after the GPTQ loop: `passes` sweeps over each row's columns, re-choosing each + * code at its conditional optimum (the value minimising the row's e (H + lambda I) e^T, + * e = decoded - x, other columns held) against the same damped Hessian. GPTQ fixes each column + * before later ones are known; a sweep revisits it with all in place and never raises the + * objective. `x` [N, K] is the (transformed) weight GPTQ was given, `w` its decoded result, + * updated in place with `codes`. `h` is the undamped Gram (calib_gram's); null means no-op. */ void gptq_refine(const Grid& g, const float* x, float* w, int32_t* codes, const Scales& scales, int64_t N, int64_t K, const float* h, double damp, int passes); diff --git a/libquant/lq_grid.cpp b/libquant/lq_grid.cpp index 74df2935..9efbb6f3 100644 --- a/libquant/lq_grid.cpp +++ b/libquant/lq_grid.cpp @@ -1,5 +1,5 @@ /* lq_grid.cpp -- parsing a grid, choosing a block's scale, and round-to-nearest on it. See - * lq_grid.h for the options, and for why every rule below is exactly the one it is. */ + * lq_grid.h for the options and why the rules must not change. */ #include "lq_grid.h" #include "lq_common.h" @@ -44,18 +44,8 @@ bool is_scale_dt(uint32_t dt) { return dt == RAD_F32 || dt == RAD_BF16 || dt == RAD_F16 || dt == RAD_F8E4M3 || dt == RAD_E8M0; } -/* `v` as the scale dtype holds it, widened back. */ -float round_to(uint32_t dt, float v) { - switch (dt) { - case RAD_BF16: return bf16_to_f32(f32_to_bf16(v)); - case RAD_F16: return f16_to_f32(f32_to_f16(v)); - case RAD_F8E4M3: return rad_fp8e4m3_to_f32(f32_to_e4m3(v)); - default: return v; - } -} - -/* The smallest positive value a float scale dtype holds: what a scale that would round to zero - * becomes, so its reciprocal stays finite. */ +/* The smallest positive value of a float scale dtype; a scale that would round to zero becomes + * this, so its reciprocal stays finite. */ float tiny_of(uint32_t dt) { switch (dt) { case RAD_F16: return 0x1p-24f; @@ -65,8 +55,8 @@ float tiny_of(uint32_t dt) { } } -/* `v` rounded to a float scale dtype, never to zero: the general path's scales are finite and - * nonzero whatever the block held. */ +/* `v` rounded to a float scale dtype, never to zero: general-path scales are always finite and + * nonzero. */ float round_nz(uint32_t dt, float v) { float r = round_to(dt, v); if (r == 0.0f || !std::isfinite(r)) r = std::copysign(tiny_of(dt), v == 0.0f ? 1.0f : v); @@ -87,22 +77,20 @@ const std::vector& named_tables() { 0.7229568362236023f, 1.0f } }, /* llama.cpp's IQ4_NL values: a non-linear 4-bit grid with no zero and unequal ends. */ { "iq4nl", { -127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113 } }, - /* A Hadamard-rotated weight's own sixteen levels: Lloyd's quantiser fitted to the - * rotated, amax-normalised Qwen3.8-Flash-Next experts, the same in every layer and both - * projections, each level then rounded to the nearest E4M3 value. Every entry is exact in - * E4M3, so libr4d's w4nla8h kernel expands a code to the byte the fp8 WMMA reads with no - * rounding; its table (r4d_args.h, kW4nlTable) is these values in this CODE ORDER -- - * magnitudes ascending, then their negatives -- and a container whose table differs is - * refused at load. Against -8..7 under the same searched scale it is ~11% less output - * error at the same bytes. */ + /* Sixteen levels for Hadamard-rotated weights: Lloyd's quantiser fitted to the rotated, + * amax-normalised Qwen3.8-Flash-Next experts (the same in every layer and both + * projections), each level rounded to the nearest E4M3 value. Being exact in E4M3, a code + * expands with no rounding to the byte libr4d's w4nla8h fp8 WMMA reads. Its table + * (r4d_args.h, kW4nlTable) holds these values in this code order (magnitudes ascending, + * then their negatives), and a container whose table differs is refused at load. About + * 11% less output error than -8..7 under the same searched scale, at the same bytes. */ { "w4nl", { 1.125f, 3.25f, 5.5f, 8.0f, 11.0f, 14.0f, 18.0f, 22.0f, -1.125f, -3.25f, -5.5f, -8.0f, -11.0f, -14.0f, -18.0f, -22.0f } }, - /* Its 32-level form, libr4d's w5nl64a8h: Lloyd's quantiser with sixteen magnitudes, fitted - * the same way at groups of 64 -- again the same in every layer and projection -- and - * rounded to E4M3 at the top level that leaves the sixteen distinct and moved least. - * Magnitudes ascending, then their negatives, so a code's high bit is its sign. Against - * w4nl under the same scales, GPTQ and coordinate descent: ~72% less output error energy - * for one more bit a weight. */ + /* The 32-level form for libr4d's w5nl64a8h: sixteen magnitudes fitted the same way at + * groups of 64 (again shared by every layer and projection), rounded to E4M3 at the top + * level that keeps all sixteen distinct with least movement. Magnitudes ascending, then + * their negatives, so a code's high bit is its sign. About 72% less output error energy + * than w4nl under the same scales, GPTQ and coordinate descent, for one more bit. */ { "w5nl", { 0.8125f, 2.5f, 4.0f, 5.5f, 7.5f, 9.0f, 11.0f, 12.0f, 14.0f, 16.0f, 18.0f, 20.0f, 22.0f, 24.0f, 26.0f, 30.0f, -0.8125f, -2.5f, -4.0f, -5.5f, -7.5f, -9.0f, -11.0f, -12.0f, @@ -168,7 +156,7 @@ bool l1_int_range(uint32_t dt, int* lo, int* hi) { /* ------------------------------------------------------------------ one code, the general path */ -/* The unit value -- before the scale -- of code `c`. */ +/* The unit value (before the scale) of code `c`. */ double unit_of(const Grid& g, int c) { if (!g.table.empty()) return g.table[(size_t)c]; if (g.is_float) { @@ -178,7 +166,7 @@ double unit_of(const Grid& g, int c) { return (double)c; } -/* The codebook entry nearest `u`, a tie going to the lower value. */ +/* The codebook entry nearest `u`, ties to the lower value. */ int nearest_entry(const Grid& g, float u) { const std::vector& o = g.table_order; size_t a = 0, b = o.size(); @@ -231,16 +219,14 @@ Fit block_fit(const Grid& g, const float* w, int64_t cols, int64_t r0, int64_t r return f; } -/* THE SEARCH, symmetric: a sweep of 21 multiples of the absmax scale from 0.70 to 1.10, and each - * candidate's least-squares refit -- the scale that minimises the error for the codes that - * candidate chose -- every one rounded to the scale dtype before it is judged, unless a second - * level will round it later. What is returned is the best of the 42, unrounded only in that case. - * The sweep is llama.cpp's make_qx_quants idea over any code; the refit is what makes a coarse - * sweep enough. +/* Symmetric search: 21 multiples of the absmax scale from 0.70 to 1.10, plus each candidate's + * least-squares refit (the scale minimising the error for the codes it chose). Each is rounded to + * the scale dtype before being judged, unless a second level will round it later, in which case + * the best is returned unrounded. The sweep is llama.cpp's make_qx_quants idea over any code; the + * refit makes a coarse sweep sufficient. * - * `t2` IS THE SECOND LEVEL ONCE IT IS KNOWN: every candidate is then judged as it will be stored, - * its first level rounded to the scale dtype relative to t2 (and held inside that dtype's range), - * so the search chooses among the scales a reader can actually decode. */ + * `t2` is the second level once known: candidates are then judged as stored, the first level + * rounded relative to t2 and clamped to its dtype's range, so only decodable scales are chosen. */ double search_sym(const Grid& g, const float* w, int64_t cols, int64_t r0, int64_t r1, int64_t c0, int64_t c1, const float* imp, double s0, double t2 = 0.0) { if (s0 == 0.0) return s0; @@ -265,9 +251,9 @@ double search_sym(const Grid& g, const float* w, int64_t cols, int64_t r0, int64 return best; } -/* And asymmetric: both ends of the range pulled in, each to six fractions from 1.00 to 0.80, the - * pair of least error kept. The zero is chosen against each candidate's rounded scale, as the - * absmax rule chooses it. */ +/* Asymmetric search: both range ends shrunk to six fractions from 1.00 to 0.80; the pair with + * least error is kept. The zero is chosen against each candidate's rounded scale, as under the + * absmax rule. */ void search_asym(const Grid& g, const float* w, int64_t cols, int64_t r0, int64_t r1, int64_t c0, int64_t c1, const float* imp, float* lo, float* hi) { const float lo0 = *lo, hi0 = *hi; @@ -284,6 +270,22 @@ void search_asym(const Grid& g, const float* w, int64_t cols, int64_t r0, int64_ } } +/* A first-level scale as stored under a transform. The plane holds s / N in the scale dtype and the + * reader undoes the transform after multiplying by it, so a code is decoded against N times the + * stored value, and codes are chosen against that. Dividing by N (a power of two) is exact unless + * it leaves the dtype's normal range (an f16 or E4M3 scale in its subnormals, or below them); only + * then does the scale the codes see move, and the stored value is never zero, so a non-empty block + * decodes to something. Without a transform the stored value is the scale itself. */ +void store_first_level(const Grid& g, float resid, BlockScale* b) { + b->stored = round_to(g.scale_dt, b->s * resid); + if (resid == 1.0f || b->stored / resid == b->s) return; + if (b->stored == 0.0f) b->stored = round_nz(g.scale_dt, b->s * resid); + b->s = b->stored / resid; + b->inv = 1.0f / b->s; + b->inv_d = 1.0 / (double)b->s; + if (g.asym) b->zero = clampi((int)(-b->lo / b->s + 0.5f), 0, g.qmax); +} + } /* namespace */ int grid_parse(const RadParam* o, int n_o, Grid* g, std::string* why) { @@ -355,7 +357,7 @@ int grid_parse(const RadParam* o, int n_o, Grid* g, std::string* why) { g->asym = true; } if (tab) { - /* the codebook gave everything an integer code needs */ + /* The codebook already set the code dtype. */ } else if (!g->is_float) { if (g->asym && sgn) { if (why) *why = fmt("codes=%s is signed; an asymmetric grid's codes are unsigned " @@ -394,7 +396,7 @@ int grid_parse(const RadParam* o, int n_o, Grid* g, std::string* why) { } } - /* THE SECOND LEVEL first, because it decides which dtypes the first may be. */ + /* The second level first, because it decides which dtypes the first may use. */ if (const char* s2 = rad_param_gets(o, n_o, "scale2", nullptr)) { g->lv2 = true; g->scale2_dt = rad_dtype_parse(s2); @@ -477,7 +479,7 @@ int grid_parse(const RadParam* o, int n_o, Grid* g, std::string* why) { return RAD_E_INVAL; } if (g->lv2) { - /* each second-level block is a whole number of first-level ones */ + /* Each second-level block must be a whole number of first-level ones. */ auto nests = [](int64_t b1, int64_t b2) { if (b1 == 0) return b2 == 0; return b2 == 0 || b2 % b1 == 0; @@ -546,8 +548,7 @@ RadEncoding grid_encoding(const Grid& g) { return e; } -int64_t grid_row_block(const Grid& g, int64_t rows) { - (void)rows; +int64_t grid_row_block(const Grid& g) { if (g.lv2) return g.br2; /* a multiple of the first level's, or 0 */ if (g.br > 0) return g.br; return g.rule == Grid::FIXED ? 1 : 0; @@ -559,10 +560,9 @@ BlockScale grid_block_scale(const Grid& g, const float* w, int64_t cols, int64_t const float resid = g.fwht ? 1.0f / (float)g.fwht : 1.0f; if (g.rule == Grid::FIXED) { - /* THE RECIPROCAL IS THE UNROUNDED VALUE'S, IN DOUBLE, and the stored scale is the value - * rounded. That is the n-gram table's rule, whose scale was chosen to be exact in bf16 -- - * so the two agree there, and a value that is not exact is quantised against what was - * asked rather than against its rounding. */ + /* The reciprocal is of the unrounded value, in double; the stored scale is the rounded + * value. This is the n-gram table's rule, whose scale is exact in bf16 so the two agree; + * an inexact value is quantised against what was asked, not its rounding. */ b.s = round_to(g.scale_dt, (float)g.fixed); b.inv_d = 1.0 / g.fixed; b.inv = (float)b.inv_d; @@ -571,10 +571,10 @@ BlockScale grid_block_scale(const Grid& g, const float* w, int64_t cols, int64_t } if (g.general()) { - /* THE GENERAL PATH. The ideal scale of the block for its code -- signed for a codebook - * whose ends are not mirror images -- searched when the rule says so, then rounded to - * the scale dtype and never to zero. Under a second level it is returned unrounded, and - * grid_scales rounds it relative to that level. */ + /* General path: the block's ideal scale for its code (signed for a codebook with unequal + * ends), searched under rule=search, then rounded to the scale dtype, never to zero. + * Under a second level it is returned unrounded and grid_scales rounds it relative to + * that level. */ if (g.asym) { float lo = 0.0f, hi = 0.0f; for (int64_t r = r0; r < r1; ++r) @@ -592,7 +592,8 @@ BlockScale grid_block_scale(const Grid& g, const float* w, int64_t cols, int64_t b.inv = 1.0f / b.s; b.inv_d = 1.0 / (double)b.s; b.zero = clampi((int)(-lo / b.s + 0.5f), 0, g.qmax); - b.stored = g.lv2 ? b.s : round_to(g.scale_dt, b.s * resid); + if (g.lv2) b.stored = b.s; + else store_first_level(g, resid, &b); return b; } float amax = 0.0f, peak = 0.0f; @@ -611,15 +612,16 @@ BlockScale grid_block_scale(const Grid& g, const float* w, int64_t cols, int64_t b.s = g.lv2 ? (float)s0 : round_nz(g.scale_dt, (float)s0); b.inv = b.s != 0.0f ? 1.0f / b.s : 0.0f; b.inv_d = b.s != 0.0f ? 1.0 / (double)b.s : 0.0; - b.stored = g.lv2 ? b.s : round_to(g.scale_dt, b.s * resid); + if (g.lv2) b.stored = b.s; + else store_first_level(g, resid, &b); return b; } if (g.asym) { - /* [lo, hi] widened to include 0, so a block of all-positive weights still has an exact - * zero; the scale spans it in (levels - 1) steps, is rounded to its dtype, and the integer - * zero is chosen against the ROUNDED scale -- which is what makes (code - zero) * scale - * decode to the grid point the code was chosen as. */ + /* [lo, hi] is widened to include 0 so an all-positive block still has an exact zero. The + * scale spans it in (levels - 1) steps and is rounded to its dtype; the integer zero is + * chosen against the rounded scale, so (code - zero) * scale decodes to the grid point the + * code was chosen as. */ float lo = 0.0f, hi = 0.0f; bool first = true; for (int64_t r = r0; r < r1; ++r) @@ -633,10 +635,11 @@ BlockScale grid_block_scale(const Grid& g, const float* w, int64_t cols, int64_t if (hi < 0.0f) hi = 0.0f; float s = (hi - lo) / (float)(g.qmax); if (!(s > 0.0f)) s = 1e-12f; + b.lo = lo; b.s = round_to(g.scale_dt, s); b.inv = 1.0f / b.s; b.zero = clampi((int)(-lo / b.s + 0.5f), 0, g.qmax); - b.stored = round_to(g.scale_dt, b.s * resid); + store_first_level(g, resid, &b); return b; } @@ -649,9 +652,9 @@ BlockScale grid_block_scale(const Grid& g, const float* w, int64_t cols, int64_t } if (g.rule == Grid::MX) { - /* THE OCP RULE, SATURATION INCLUDED: X = 2^(floor(log2 amax) - emax), so amax / X lands in + /* The OCP rule, saturation included: X = 2^(floor(log2 amax) - emax), so amax / X lands in * [2^emax, 2^(emax+1)) and the top of that range saturates to the code's largest value. - * Bumping the exponent would double the step for every other element to save one. */ + * Bumping the exponent instead would double the step for every other element. */ int exp = -127; if (amax > 0.0f) { uint32_t u; @@ -659,34 +662,44 @@ BlockScale grid_block_scale(const Grid& g, const float* w, int64_t cols, int64_t exp = (int)((u >> 23) & 0xFFu) - 127 - g.emax; } b.e8 = clampi(exp + 127, 0, 254); - /* 2^-(e8 - 127) in the exponent field, exact and with no libm call */ + /* 2^-(e8 - 127) built in the exponent field: exact, no libm call. */ const uint32_t ui = (uint32_t)clampi(254 - b.e8, 1, 254) << 23; std::memcpy(&b.inv, &ui, 4); b.inv_d = b.inv; b.s = rad_e8m0_to_f32((uint8_t)b.e8); b.stored = b.s; + if (g.fwht) { + /* The exponent stored is the transform's order lower, exactly; codes are chosen + * against N times it, which differs only where the exponent's floor clamps it. */ + int sh = 0; + while (((int64_t)1 << sh) < g.fwht) ++sh; + b.e8 = clampi(b.e8 - sh, 0, 254); + b.stored = rad_e8m0_to_f32((uint8_t)b.e8); + b.s = b.stored * (float)g.fwht; + b.inv = 1.0f / b.s; + b.inv_d = b.inv; + } return b; } if (g.is_float) { - /* A BLOCK OF ZEROS IS SCALED BY ONE, so its reciprocal is finite and its codes are zero. - * The quotient is formed by multiplying by 1/fmax when the scale is narrower than f32 and - * by dividing when it is f32 -- the two forms the block-fp8 linears and the fp8 hyper- - * connection rows were each quantised with, which differ in the last place of the f32 and - * can therefore round a narrow scale differently. */ + /* An all-zero block gets scale 1, so its reciprocal is finite and its codes zero. The + * quotient multiplies by 1/fmax for a scale narrower than f32 and divides for f32: the + * forms the block-fp8 linears and the fp8 hyper-connection rows were quantised with. They + * differ in the last f32 place and can round a narrow scale differently. */ float s = 1.0f; if (amax > 0.0f) s = g.scale_dt == RAD_F32 ? amax / g.fmax : amax * (1.0f / g.fmax); b.s = round_to(g.scale_dt, s); b.inv = 1.0f / b.s; } else { - /* A BLOCK OF ZEROS GETS 1e-12, whose reciprocal is finite and whose codes are zero. */ + /* An all-zero block gets 1e-12: finite reciprocal, zero codes. */ float s = amax / (float)g.qmax; if (!(s > 0.0f)) s = 1e-12f; b.s = round_to(g.scale_dt, s); b.inv = 1.0f / b.s; } b.inv_d = b.inv; - b.stored = round_to(g.scale_dt, b.s * resid); + store_first_level(g, resid, &b); return b; } @@ -786,14 +799,13 @@ Scales grid_scales(const Grid& g, const float* w, int64_t rows, int64_t cols, co } if (!g.lv2) return s; - /* THE SECOND LEVEL. Each of its blocks takes the largest first-level magnitude under it over - * the largest value the first level's dtype holds -- so the widest block's sub-scale is the - * dtype's top and every other one is a fraction of it -- rounded to its own dtype (up to a - * power of two for e8m0, which may not round down past the top). Each first-level scale is - * then stored relative to it: rounded half away for an integer sub-scale, to nearest even for - * a float one, and never to zero for a block that held anything, which would decode it to - * nothing. The codes are chosen against the product, as a reader multiplies it. The - * transform's 1/N goes to the second level. */ + /* Second level: each block takes the largest first-level magnitude under it divided by the + * first level's dtype maximum, so the widest sub-scale sits at the dtype's top. It is rounded + * to its own dtype (up to a power of two for e8m0, so it never rounds down past the top). + * Each first-level scale is then stored relative to it: half away from zero for an integer + * sub-scale, nearest even for a float one, and never zero for a non-empty block (which would + * decode to nothing). Codes are chosen against the product, as the reader multiplies it. The + * transform's 1/N goes into the second level. */ const int64_t br2 = g.br2 > 0 ? g.br2 : rows, bc2 = g.bc2 > 0 ? g.bc2 : cols; s.nr2 = (rows + br2 - 1) / br2; s.nc2 = (cols + bc2 - 1) / bc2; @@ -807,8 +819,8 @@ Scales grid_scales(const Grid& g, const float* w, int64_t rows, int64_t cols, co s.s2.resize(peak.size()); for (size_t k = 0; k < peak.size(); ++k) { if (g.fixed2 > 0.0) { - /* FIXED: the stored value is the one asked for, and the level the first is relative to - * is that over the transform's residual -- what the reader's product undoes. */ + /* Fixed: store the requested value; the first level is relative to it divided by the + * transform's residual, which the reader's product undoes. */ s.s2[k] = (float)g.fixed2; s2r[k] = (float)(g.fixed2 / (double)resid); continue; @@ -826,11 +838,13 @@ Scales grid_scales(const Grid& g, const float* w, int64_t rows, int64_t cols, co s2r[k] = round_nz(g.scale2_dt, v); s.s2[k] = round_nz(g.scale2_dt, s2r[k] * resid); } + /* As for a first level alone (store_first_level): the first level is taken relative to + * what the reader multiplies by, which is N times the stored second level. */ + s2r[k] = s.s2[k] / resid; } - /* A SEARCHED FLOAT FIRST LEVEL IS SEARCHED AGAIN, now that its second level is known, over the - * candidates as they will be stored: an E4M3 sub-scale moves by up to 1/16 when it is rounded, - * which is most of what the first search won. The second level stays where the first search's - * peaks put it. */ + /* A searched float first level is searched again against the now-known second level, over + * candidates as stored: rounding moves an E4M3 sub-scale by up to 1/16, most of what the first + * search gained. The second level stays where the first search's peaks put it. */ if (g.rule == Grid::SEARCH && !g.l1_int && !g.asym) { #ifdef _OPENMP #pragma omp parallel for schedule(dynamic, 1) if (s.nr * s.nc > 64) @@ -867,8 +881,8 @@ Scales grid_scales(const Grid& g, const float* w, int64_t rows, int64_t cols, co b.inv_d = 1.0 / (double)b.s; if (g.asym) b.zero = clampi((int)(-b.lo / b.s + 0.5f), 0, g.qmax); } - /* Only a fixed second level can put a first-level scale past its dtype's top: a derived one - * maps the largest under it to the top by construction. */ + /* Only a fixed second level can push a first-level scale past its dtype's top; a derived one + * maps the largest under it exactly to the top. */ if (held) std::fprintf(stderr, "libquant: %lld of %lld scales sat past %s's top under scale2_value=%g " "and were held there\n", (long long)held, (long long)(s.nr * s.nc), @@ -927,14 +941,14 @@ BlockScale grid_finish(const Grid& g, double s, float lo) { b.inv = 1.0f / b.s; b.inv_d = 1.0 / (double)b.s; if (g.asym) b.zero = clampi((int)(-lo / b.s + 0.5f), 0, g.qmax); - b.stored = round_to(g.scale_dt, b.s * resid); + store_first_level(g, resid, &b); return b; } int grid_rtn(const Grid& g, const float* w, int64_t row0, int64_t rows, int64_t cols, const Planes& p, const float* imp) { if (g.general()) { - const int64_t rb = grid_row_block(g, rows); + const int64_t rb = grid_row_block(g); if (rb > 0 && row0 % rb) return RAD_E_SHAPE; const Scales sc = grid_scales(g, w, rows, cols, imp); grid_store_scales(g, sc, p); @@ -953,8 +967,8 @@ int grid_rtn(const Grid& g, const float* w, int64_t row0, int64_t rows, int64_t const int64_t bc = g.bc > 0 ? g.bc : cols; if (g.br > 0 && row0 % g.br) return RAD_E_SHAPE; const int64_t nband = (rows + br - 1) / br; - /* A fixed scale over the whole extent is one element, written once rather than by every band - * at once. */ + /* A fixed scale over the whole extent is one element, written once here rather than by every + * band concurrently. */ const bool one_scale = g.br == 0; const bool int4 = g.codes == RAD_I4 && !g.is_float && !g.asym && g.rule != Grid::FIXED && g.rule != Grid::MX; @@ -967,7 +981,7 @@ int grid_rtn(const Grid& g, const float* w, int64_t row0, int64_t rows, int64_t #endif for (int64_t band = 0; band < nband; ++band) { const int64_t r0 = band * br, r1 = r0 + br < rows ? r0 + br : rows; - /* the scale plane's row for this band, relative to the call's first */ + /* The scale plane's row for this band, relative to the call's first. */ const int64_t srow = g.br > 0 ? band : 0; uint8_t* sr = p.scale + srow * p.scale_row; uint8_t* zr = p.zero ? p.zero + srow * p.zero_row : nullptr; @@ -975,9 +989,9 @@ int grid_rtn(const Grid& g, const float* w, int64_t row0, int64_t rows, int64_t const int64_t c1 = c0 + bc < cols ? c0 + bc : cols; const BlockScale b = grid_block_scale(g, w, cols, r0, r1, c0, c1); if (!(one_scale && g.rule == Grid::FIXED)) grid_store_scale(g, b, sr, zr, j); - /* SYMMETRIC INT4 OVER AN EVEN SPAN, two codes a byte: grid_code's arithmetic for this - * grid without its per-element branches, and a byte written whole instead of a - * nibble read, masked and written back. Every routed expert of a w4 model is this. */ + /* Fast path for symmetric int4 over an even span (every routed expert of a w4 model): + * grid_code's arithmetic without per-element branches, two codes written as one whole + * byte instead of a nibble read-modify-write. */ if (int4 && !(c0 & 1) && !((c1 - c0) & 1)) { for (int64_t r = r0; r < r1; ++r) { uint8_t* cr = p.codes + r * p.codes_row; @@ -997,7 +1011,6 @@ int grid_rtn(const Grid& g, const float* w, int64_t row0, int64_t rows, int64_t } } } - (void)row0; return RAD_OK; } diff --git a/libquant/lq_grid.h b/libquant/lq_grid.h index a2589267..215f3b83 100644 --- a/libquant/lq_grid.h +++ b/libquant/lq_grid.h @@ -1,17 +1,16 @@ -/* lq_grid.h -- a quantisation GRID: what codes a weight may take and how its scales sit over it. +/* lq_grid.h -- a quantisation grid: the codes a weight may take and how its scales sit over it. * - * libquant separates three things a recipe names independently (spec.md §4.5): the GRID, which is - * the code type and the scale, zero and transform structure around it; the ALGORITHM that picks - * codes on that grid (round-to-nearest, GPTQ, AWQ, ...); and the encoding the result is stored as, - * which follows from the grid alone. Every algorithm takes the same grid options, so a grid - * written once is available to all of them. + * libquant separates three things a recipe names independently (spec.md §4.5): the grid (code type + * plus the scale, zero and transform structure around it); the algorithm that picks codes on it + * (round-to-nearest, GPTQ, AWQ, ...); and the stored encoding, which follows from the grid alone. + * Every algorithm takes the same grid options. * * A grid is parsed from a rule's options: * * codes=DT the code dtype: i2..i8, i16, i32 (symmetric), u1..u8, u16 with zero= * (asymmetric), or a float code: fp8_e4m3, fp8_e5m2, fp6_e2m3, fp6_e3m2, * fp4_e2m1. Required, except beside table=, which implies it. - * table=T a SCALAR CODEBOOK: each code indexes a table of values, which a block's scale + * table=T a scalar codebook: each code indexes a table of values, which a block's scale * multiplies. nf4 (QLoRA's NormalFloat), iq4nl (llama.cpp's IQ4_NL values), * w4nl (the rotated expert grid libr4d's w4nla8h kernel decodes), w5nl (its * 32-level form, libr4d's w5nl64a8h), @@ -22,14 +21,13 @@ * (default: one scale a row, 1x*) * scale=DT the scale dtype: f32, bf16, f16, fp8_e4m3, e8m0 (default bf16); under scale2= * also an integer, u4..u8, i6, i8 -- a K-quant's sub-block scale - * scale2=DT a SECOND SCALE LEVEL the first is relative to: f32, bf16, f16, fp8_e4m3, e8m0. - * NVFP4 is fp4 codes, an fp8_e4m3 scale a [1 x 16] and an f32 scale2 a tensor. - * scale2_value=X the second level FIXED at X for every one of its blocks, rather than taken - * from the largest first-level scale under it: exactly representable in scale2=. - * It is a constant a reader can know -- a first level of E4M3 sub-scales over a - * model whose scales sit inside E4M3's range needs no per-row level, only an - * offset (libr4d's w4nl64a8h experts) -- and a first level it would push past its - * dtype's top is held there, said once on stderr. + * scale2=DT a second scale level the first is relative to: f32, bf16, f16, fp8_e4m3, e8m0. + * NVFP4 is fp4 codes, an fp8_e4m3 scale per [1 x 16] and an f32 scale2 per tensor. + * scale2_value=X the second level fixed at X for all its blocks instead of derived from the + * largest first-level scale under it; must be exact in scale2=. For E4M3 + * sub-scales over a model whose scales fit E4M3's range, only a known offset is + * needed (libr4d's w4nl64a8h experts). A first-level value it would push past its + * dtype's top is clamped there, reported once on stderr. * group2=N the second level's block, [1 x N]; or * block2=RxC in general (default: the whole tensor, *x*). A multiple of the first level's * block in each extent. @@ -43,12 +41,11 @@ * scale_value=X the fixed scale for rule=fixed * clamp=full|sym a signed code's range: [-2^(b-1), 2^(b-1)-1], or symmetric about zero * - * THE RULES ARE THE ONES THE CONTAINERS IN SERVICE WERE MADE WITH, exactly -- the order of a - * division, which number is rounded to the scale dtype before the codes are chosen against it, and - * what a block of zeros gets -- so a recipe reproduces those containers byte for byte. Each is - * stated where it is implemented. The forms no container in service uses -- a codebook, a second - * level, the searched rule and the 16- and 32-bit codes -- go through a general path of their own, - * which leaves those rules where they are. + * The rules are exactly those the containers in service were made with (the order of a division, + * which number is rounded to the scale dtype before codes are chosen, what an all-zero block gets), + * so a recipe reproduces those containers byte for byte. Each is stated where it is implemented. + * Forms no container in service uses (a codebook, a second level, rule=search, 16- and 32-bit + * codes) take a separate general path, which leaves those rules untouched. */ #pragma once #include "rad_quant.h" @@ -97,7 +94,7 @@ struct Grid { int plane_table() const { return table.empty() ? -1 : 2 + (asym ? 1 : 0) + (lv2 ? 1 : 0); } - /* Does this grid take the general path (see the head of the file)? */ + /* Whether this grid takes the general path (see the file header). */ bool general() const { return lv2 || rule == SEARCH || !table.empty() || wide; } }; @@ -109,7 +106,7 @@ RadEncoding grid_encoding(const Grid& g); /* The rows one quantize call may take for this grid: a multiple of every level's block rows, or 0 * when a scale covers every row and has to see them all. */ -int64_t grid_row_block(const Grid& g, int64_t rows); +int64_t grid_row_block(const Grid& g); /* One block's quantiser state: the scale the codes are chosen against, its stored form, the * reciprocal, and for an asymmetric grid the zero. */ @@ -119,8 +116,8 @@ struct BlockScale { double inv_d = 1.0; /* rule=fixed reads its reciprocal in double; see grid.cpp */ int zero = 0; int e8 = 0; /* rule=mx: the shared exponent's E8M0 code */ - float stored = 1.0f; /* what the scale plane holds: s, divided by a transform's order -- - or, under a second level, the first level's own value */ + float stored = 1.0f; /* what the scale plane holds: s divided by a transform's order, or + under a second level the first level's own value */ float lo = 0.0f; /* an asymmetric block's low end, which the zero is taken against */ }; @@ -167,9 +164,9 @@ struct Scales { } }; -/* The whole scale grid of rows [0, rows) of `w`, without choosing a code -- what round-to-nearest - * codes against and the static-groups form an error-feedback algorithm quantises against. `imp` - * is the columns' importances for rule=search, or null. */ +/* The whole scale grid of rows [0, rows) of `w`, without choosing codes: what round-to-nearest and + * the static-groups form of an error-feedback algorithm quantise against. `imp` is the columns' + * importances for rule=search, or null. */ Scales grid_scales(const Grid& g, const float* w, int64_t rows, int64_t cols, const float* imp = nullptr); @@ -179,14 +176,14 @@ void grid_store_scales(const Grid& g, const Scales& s, const Planes& p); /* Store one code into element `i` of a code row, any width this grid writes. */ void grid_store_code(const Grid& g, uint8_t* row, int64_t i, int code); -/* Rows [0, rows) of `w` quantised and decoded again, into `out` [rows, cols]: the weight a reader of - * this grid would see, for an algorithm that measures a candidate. `rows` covers whole blocks. */ +/* Quantise and decode rows [0, rows) of `w` into `out` [rows, cols]: the weight a reader would see, + * for algorithms that measure a candidate. `rows` covers whole blocks. */ void grid_fake(const Grid& g, const float* w, int64_t rows, int64_t cols, float* out, const float* imp = nullptr); -/* A block's state from its scale -- `s` unrounded, `lo` the asymmetric low end the zero is taken - * against -- rounded as the general path rounds one. For an algorithm that chose the scale itself; - * a grid with a second level has its own pass and does not take this. */ +/* A block's state from an unrounded scale `s` and the asymmetric low end `lo` the zero is taken + * against, rounded as the general path rounds. For algorithms that choose the scale themselves; + * not for grids with a second level, which have their own pass. */ BlockScale grid_finish(const Grid& g, double s, float lo); /* Round-to-nearest over rows [0, rows) of `w` (logical rows [row0, row0+rows)). The block scales diff --git a/libquant/lq_hess.cpp b/libquant/lq_hess.cpp index 1af799c0..794e2231 100644 --- a/libquant/lq_hess.cpp +++ b/libquant/lq_hess.cpp @@ -1,5 +1,6 @@ /* lq_hess.cpp -- reading the calibration Hessians, and D . H. See lq_hess.h. */ #include "lq_hess.h" +#include "lq_common.h" #include #include @@ -15,21 +16,21 @@ namespace { * calibration tap writes (arch/common/rad_arch.h, calib_write). The header is 32 bytes. */ constexpr int kHdr = 32; +/* One file per rank, ranks 0 .. kMaxRanks - 1. */ +constexpr int kMaxRanks = 16; + +std::string gram_path(const char* dir, int rank, const std::string& stem) { + return std::string(dir) + "/gram.r" + std::to_string(rank) + "." + stem + ".bin"; +} + /* The unnormalised Hadamard of width `n` over every n-wide block of a length-k row, in place. */ void fwht_row(double* v, int64_t k, int64_t n) { - for (int64_t b0 = 0; b0 < k; b0 += n) - for (int64_t h = 1; h < n; h *= 2) - for (int64_t i = b0; i < b0 + n; i += 2 * h) - for (int64_t j = i; j < i + h; ++j) { - const double x = v[j], y = v[j + h]; - v[j] = x + y; - v[j + h] = x - y; - } + for (int64_t b0 = 0; b0 < k; b0 += n) fwht_inplace(v + b0, n); } /* H -> F H F for the block-diagonal Hadamard F of width `n`: every row, then every column. F is - * symmetric, so the column pass is the row pass over the transpose, and the result stays - * symmetric to the last bit only because both passes are the same butterflies in the same order. */ + * symmetric, so the column pass is the row pass over the transpose; the result stays bit-exactly + * symmetric only because both passes run the same butterflies in the same order. */ void rotate_gram(std::vector& h, int64_t k, int64_t n) { for (int64_t r = 0; r < k; ++r) fwht_row(h.data() + r * k, k, n); std::vector col((size_t)k); @@ -58,8 +59,8 @@ bool read_gram(const std::string& path, int64_t k, int64_t domain, std::vector= 2 && (n & (n - 1)) == 0 && k % n == 0); }; if (!tiles(from) || !tiles(domain)) { @@ -84,9 +85,9 @@ bool read_gram(const std::string& path, int64_t k, int64_t domain, std::vectorempty()) acc->assign(h.size(), 0.0); @@ -94,13 +95,11 @@ bool read_gram(const std::string& path, int64_t k, int64_t domain, std::vector __attribute__((always_inline)) inline void panel(const float* D, int64_t K, const float* P, float* G) { @@ -169,7 +166,7 @@ __attribute__((always_inline)) inline void task(const float* D, int64_t K, const for (int64_t b = b0; b < b1; ++b) panel(D + b * RB * K, K, pack, G + b * RB * K + j0); } -/* The edges: what the blocks leave, one element at a time in the same order. */ +/* The edges the blocks leave, one element at a time in the same k order. */ void edge(const float* D, int64_t K, const float* H, int64_t r0, int64_t r1, int64_t j0, int64_t j1, float* G) { for (int64_t r = r0; r < r1; ++r) @@ -238,16 +235,13 @@ std::string calib_stem(const char* name) { int calib_sum(const char* dir, const std::string& stem, int64_t K, int64_t domain, std::vector* acc) { - /* EVERY RANK'S FILE, SUMMED. Under expert parallelism a rank's `down` Hessian covers only the - * tokens routed to its own experts, so no single file holds the layer's distribution; the - * gate_up files are duplicates across ranks, and summing those multiplies H by the rank count, - * a positive scale every algorithm here is invariant to. 16 bounds the rank count. */ + /* Sum every rank's file. Under expert parallelism a rank's `down` Hessian covers only tokens + * routed to its own experts, so no single file holds the layer's distribution. The gate_up + * files are duplicated across ranks; summing them scales H by the rank count, which every + * algorithm here is invariant to. */ int found = 0; - for (int r = 0; r < 16; ++r) { - char path[1024]; - std::snprintf(path, sizeof path, "%s/gram.r%d.%s.bin", dir, r, stem.c_str()); - if (read_gram(path, K, domain, acc)) ++found; - } + for (int r = 0; r < kMaxRanks; ++r) + if (read_gram(gram_path(dir, r, stem), K, domain, acc)) ++found; return found; } @@ -303,7 +297,7 @@ void mat_hess(const float* D, int64_t R, int64_t K, const float* H, float* G) { if (__builtin_cpu_supports("avx512f")) blocked<8, 32>(D, R, K, H, G, run_avx512, &rf, &cf); else if (__builtin_cpu_supports("avx2")) blocked<4, 16>(D, R, K, H, G, run_avx2, &rf, &cf); else blocked<4, 8>(D, R, K, H, G, run_base, &rf, &cf); - /* the column edge of the blocked rows, then the row edge across every column */ + /* The column edge of the blocked rows, then the row edge across every column. */ if (cf < K && rf > 0) { #ifdef _OPENMP #pragma omp parallel for schedule(static) diff --git a/libquant/lq_hess.h b/libquant/lq_hess.h index 6bb52208..387fbadd 100644 --- a/libquant/lq_hess.h +++ b/libquant/lq_hess.h @@ -1,27 +1,27 @@ -/* lq_hess.h -- the calibration Hessians every calibrated quantiser reads, and the one product they - * all spend their time in. +/* lq_hess.h -- the calibration Hessians the calibrated quantisers read, and the product they spend + * their time in. * - * WHAT A HESSIAN IS HERE. The engine's calibration tap (arch/common/rad_arch.h, calib_write) sums - * x x^T over the real input of a layer's projection, per rank, into `gram.r..bin`. The - * input is the one the KERNEL multiplies, so a file says which DOMAIN it is in: the model's own - * activation (domain 0), or that activation rotated by the unnormalised Hadamard of width N, block - * by block (domain N) -- what a container that stores its weights rotated multiplies. A reader asks - * for the domain its weight is quantised in, the grid's transform, and each file is brought there - * before the sum: rotating is H -> F H F, and back is the same divided by N^2, F being its own - * inverse up to N. So a calibration run on a bf16 model and one on a rotated four-bit container - * both serve a rotated recipe. A layer-local quantiser's error is then the quadratic form + * The engine's calibration tap (arch/common/rad_arch.h, calib_write) sums x x^T over the real + * input of a layer's projection, per rank, into `gram.r..bin`. The input is the one + * the kernel multiplies, so each file records its domain: the model's own activation (domain 0), + * or that activation rotated block by block by the unnormalised Hadamard of width N (domain N), + * which is what a container storing rotated weights multiplies. A reader asks for its grid's + * transform domain and each file is converted before the sum: rotating is H -> F H F, and back is + * the same divided by N^2 (F is its own inverse up to N). So calibration from a bf16 model and from + * a rotated 4-bit container both serve a rotated recipe. + * + * A layer-local quantiser's error is the quadratic form * * L = sum over rows r of (w_hat_r - w_r) H (w_hat_r - w_r)^T * - * which decomposes over rows: two rows of a weight share H and nothing else. GPTQ's recursion, - * AWQ's scale search, AutoRound's rounding descent and ParoQuant's rotation fit are four ways of - * making that number small, and the last three spend their time in D . H, which is what mat_hess - * computes. + * which decomposes over rows: rows share H and nothing else. GPTQ, AWQ's scale search, AutoRound's + * rounding descent and ParoQuant's rotation fit all minimise it; the last three spend their time + * in D . H (mat_hess). * - * THE MOST SPECIFIC HESSIAN THERE IS: a routed expert's own, when the tap recorded one -- the - * engine records one an expert for `down`, whose input is each expert's own intermediate units -- - * and otherwise the layer's, pooled over its experts and found from the weight's name with the - * expert index stripped (calib_stem), which a layer's experts share and the process reads once. + * The most specific Hessian available is used: a routed expert's own when the tap recorded one (it + * does for `down`, whose input is the expert's own intermediate units), else the layer's, pooled + * over its experts and found from the name with the expert index stripped (calib_stem). A layer's + * experts share that one and the process reads it once. */ #pragma once #include @@ -31,42 +31,40 @@ namespace lq { -/* A Hessian or a factor of one as a quantiser holds it: shared, so one the process does not cache - * -- an expert's own -- lives exactly as long as the call that read it. */ +/* A Hessian or a factor of one. Shared, so an uncached one (an expert's own) lives exactly as long + * as the call that read it. */ using Gram = std::shared_ptr>; /* `blk.7.ffn_gate_up_exps.123.weight` -> `blk.7.ffn_gate_up_exps`: the stem a layer's pooled * Hessian file is named by. */ std::string calib_stem(const char* name); -/* The stem `name`'s Hessian is read from in `dir`: the weight's own -- the name less `.weight`, - * `blk.7.ffn_down_exps.123` -- when every rank's file for it together says at least - * kOwnRowsPerK * K rows, and calib_stem's otherwise, said on stderr. A GPTQ fit to a Gram of few - * rows fits those rows: on Qwen3.8-Flash-Next's down projection an expert's own Gram cuts its - * held-out output error by 20-55% against the pooled one's, except for experts routed under ~2K - * rows, where it is worse than rounding to nearest. Those carry a fraction of a percent of the - * routing. */ +/* The stem `name`'s Hessian is read from in `dir`: the weight's own (the name less `.weight`, + * `blk.7.ffn_down_exps.123`) when its rank files together hold at least kOwnRowsPerK * K rows, + * else calib_stem's, noted on stderr. A GPTQ fit to a Gram of few rows overfits them: on + * Qwen3.8-Flash-Next's down projection an expert's own Gram cuts held-out output error by 20-55% + * versus the pooled one, except for experts routed under ~2K rows, where it is worse than + * round-to-nearest. Those carry a fraction of a percent of the routing. */ constexpr int64_t kOwnRowsPerK = 4; std::string calib_resolve(const char* dir, const char* name, int64_t K); -/* Every rank's file for `stem` in `dir`, each brought into `domain` (0, or the Hadamard width a - * rotated grid quantises in), summed into `acc` (K x K, double, row-major). Returns how many files - * were read; 0 when there are none. A file that is there and unusable -- the wrong magic, the wrong - * K, short, a domain that cannot be brought to the one asked for -- is said so on stderr and - * skipped. */ +/* Every rank's file for `stem` in `dir`, each converted into `domain` (0, or the Hadamard width a + * rotated grid quantises in), summed into `acc` (K x K, double, row-major). Returns the number of + * files read, 0 when there are none. A file that exists but is unusable (wrong magic, wrong K, + * short, or a domain that cannot be converted) is reported on stderr and skipped. */ int calib_sum(const char* dir, const std::string& stem, int64_t K, int64_t domain, std::vector* acc); /* The summed Gram of `name`'s input in `domain` as f32 K x K, from calib_resolve's stem, or null - * when `dir` holds none for it (said once on stderr). A layer's is cached for the life of the - * process by (dir, stem, K, domain); an expert's own is read for the call that asked, since each - * is used once and a model's worth would not fit. */ + * when `dir` holds none (noted once on stderr). A layer's is cached for the process by (dir, stem, + * K, domain); an expert's own is read per call, since each is used once and a model's worth would + * not fit. */ Gram calib_gram(const char* dir, const char* name, int64_t K, int64_t domain, const char* who); -/* G [R x K] = D [R x K] . H [K x K], H symmetric. Every element of G is summed over k in ascending - * order whatever the thread count and the vector width, so the result is a function of the inputs - * alone -- a quantiser's output is a stored file, and two converts of the same weight must agree. - * Threads over column panels of H and row blocks of D. */ +/* G [R x K] = D [R x K] . H [K x K], H symmetric. Each element of G sums over k in ascending order + * regardless of thread count and vector width, so the result depends on the inputs alone: two + * converts of the same weight must write the same file. Threads over column panels of H and row + * blocks of D. */ void mat_hess(const float* D, int64_t R, int64_t K, const float* H, float* G); /* out[r] = D_r . G_r, the quadratic form of each row, summed in double. */ diff --git a/libquant/lq_paro.cpp b/libquant/lq_paro.cpp index f30c8b69..acebeeae 100644 --- a/libquant/lq_paro.cpp +++ b/libquant/lq_paro.cpp @@ -1,34 +1,32 @@ /* lq_paro.cpp -- ParoQuant: pairwise rotation quantisation (Liang, Chen, Han, Liu; ICLR 2026). * - * WHAT IT DOES. An outlier channel stretches the range of every scale group it sits in. ParoQuant - * transforms each row's input channels before the grid -- a channel-wise scaling, then `stages` - * rounds of independent Givens rotations, each a set of disjoint channel pairs inside one rotation - * group of `rot_group` channels -- so the values of a group even out, and LEARNS the angles and the - * scales against the output error. The reader undoes the transform on the activation side: the - * encoding's transform is "givens" (abi/rad_encoding.h), T = D . G_1 ... G_S over row vectors, with - * the scales, the pairs and the angles stored as its tables. + * An outlier channel stretches the range of every scale group it sits in. ParoQuant transforms each + * row's input channels before the grid (a channel-wise scaling, then `stages` rounds of independent + * Givens rotations, each a set of disjoint channel pairs within one group of `rot_group` channels) + * so a group's values even out, and learns the angles and scales against the output error. The + * reader undoes the transform on the activation side: the encoding's transform is "givens" + * (abi/rad_encoding.h), T = D . G_1 ... G_S over row vectors, with scales, pairs and angles stored + * as its tables. * - * STAGE ONE fits the transform: Adam at `lr` (cosine-decayed to a twentieth, no weight decay) over - * `steps` steps, each on the next `sample_rows` rows of the weight, the angles starting at zero and - * the scales at one, as the paper's. The weight is quantised through the grid at every step and the gradient - * reaches the transform through the straight-through estimator: w_hat = w + E T^-1, the - * quantisation error E held, so a step moves T^-1 to send E where the input does not look. - * STAGE TWO is the paper's fine-tuning of the transformed weight's rounding and scales; here it is - * AutoRound (lq_autoround.h) on the transformed weight against the transformed Hessian - * T^-1 H T^-T, for `iters` steps -- 0 leaves the transformed weight rounded to nearest. + * Stage one fits the transform with Adam at `lr` (cosine-decayed to lr/20, no weight decay) over + * `steps` steps, each on the next `sample_rows` rows; angles start at zero and scales at one, as in + * the paper. Each step quantises through the grid and the gradient reaches the transform by the + * straight-through estimator: w_hat = w + E T^-1 with the quantisation error E held, so a step + * moves T^-1 to send E where the input does not look. + * Stage two replaces the paper's fine-tuning of rounding and scales with AutoRound + * (lq_autoround.h) on the transformed weight against T^-1 H T^-T, for `iters` steps; 0 rounds the + * transformed weight to nearest. * - * THE PAIRS are drawn at random inside each rotation group, a channel paired at most once a stage - * and a pair, where the group allows, used at most once over all stages -- the paper's diverse - * independent rotations -- from a generator seeded by the weight's name, so two converts of the - * same weight draw the same pairs. + * Pairs are drawn at random within each rotation group: a channel is paired at most once per stage + * and, where the group allows, a pair is used at most once over all stages (the paper's diverse + * independent rotations). The generator is seeded by the weight's name, so converts are repeatable. * - * THE OUTPUT ERROR is the Hessian's quadratic form (lq_hess.h) in the weight's own domain -- the - * layer-local form of the paper's per-layer output loss -- or, with no Hessian for the weight but - * an imatrix, its diagonal. With neither the transform stays the identity, which is said. + * Output error: the Hessian's quadratic form (lq_hess.h) in the weight's own domain, the + * layer-local form of the paper's loss; with no Hessian but an imatrix, its diagonal. With neither, + * the transform stays the identity (reported on stderr). * - * DETERMINISM: every gradient is summed over rows in row order, whatever the thread count, so the - * transform -- and with it the stored file -- is a function of the weight and the calibration - * alone. + * Determinism: gradients are summed over rows in row order regardless of thread count, so the + * stored file depends only on the weight and the calibration. */ #include "lq_autoround.h" #include "lq_hess.h" @@ -73,10 +71,10 @@ int paro_setup(const RadParam* o, int n_o, const RadQuantWeight* w, Paro* p) { if (p->g.fwht) return refuse(w, "paroquant writes its own transform, so it takes no " "transform="); p->stages = (int)rad_param_geti(o, n_o, "stages", 8); - if (p->stages < 1 || p->stages > 64) return refuse(w, "stages= is 1 to 64"); + if (p->stages < 1 || p->stages > 64) return refuse(w, "stages= must be 1 to 64"); p->gr = rad_param_geti(o, n_o, "rot_group", 0); if (p->gr <= 0) p->gr = (p->g.bc > 0 && w->cols % p->g.bc == 0) ? p->g.bc : 128; - if (p->gr < 2 || (p->gr & 1)) return refuse(w, "rot_group= is an even channel count"); + if (p->gr < 2 || (p->gr & 1)) return refuse(w, "rot_group= must be an even channel count"); if (w->cols % p->gr) { char m[160]; std::snprintf(m, sizeof m, "paroquant: %lld columns are not a whole number of %lld-channel " @@ -109,7 +107,7 @@ uint64_t splitmix(uint64_t* s) { return z ^ (z >> 31); } -/* The pairs: [stages x K], stage s pairing columns (pairs[s][2p], pairs[s][2p+1]). */ +/* The pairs, [stages x K]: stage s pairs columns pairs[s][2p] and pairs[s][2p+1]. */ std::vector draw_pairs(const char* name, int stages, int64_t K, int64_t gr) { std::vector pairs((size_t)(stages * K)); for (int64_t g0 = 0; g0 < K; g0 += gr) { @@ -127,7 +125,7 @@ std::vector draw_pairs(const char* name, int stages, int64_t K, int64_t const int a = order[(size_t)x]; if (paired[(size_t)a]) continue; int b = -1; - for (int64_t y = x + 1; y < gr && b < 0; ++y) { /* a pair not used yet */ + for (int64_t y = x + 1; y < gr && b < 0; ++y) { /* an unused pair */ const int c = order[(size_t)y]; if (!paired[(size_t)c] && !used[(size_t)(a * gr + c)]) b = c; } @@ -152,7 +150,7 @@ struct Rot { std::vector angle; /* [S x K/2] */ std::vector scale; /* [K] */ - /* v = w . D . G_1 ... G_S, in place */ + /* v = w . D . G_1 ... G_S, in place. */ void forward(float* x) const { for (int64_t k = 0; k < K; ++k) x[k] *= scale[(size_t)k]; for (int s = 0; s < S; ++s) @@ -164,8 +162,8 @@ struct Rot { x[b] = xb * c - xa * sn; } } - /* y = e . T^-1, keeping every intermediate: ys[k] after the k-th inverse stage (k = 0 is e); - * the result, divided by the scales, into `out`. */ + /* y = e . T^-1, keeping every intermediate in ys[k] (after the k-th inverse stage; k = 0 is + * e). The result, divided by the scales, goes to `out`. */ void inverse(const float* e, float* ys, float* out) const { std::memcpy(ys, e, (size_t)K * sizeof(float)); for (int k = 1; k <= S; ++k) { @@ -195,7 +193,7 @@ void err_grad(const float* D, int64_t R, int64_t K, const float* H, const float* for (int64_t k = 0; k < K; ++k) G[r * K + k] = D[r * K + k] * diag[k]; } -/* STAGE ONE. */ +/* Stage one: fit the transform. */ void fit(const Paro& p, const float* w, int64_t N, int64_t K, const float* H, const float* diag, int steps, double lr, int64_t want, Rot* rot) { const Grid& g = p.g; @@ -210,22 +208,12 @@ void fit(const Paro& p, const float* w, int64_t N, int64_t K, const float* H, co std::vector ws, vs, fake, E, D, G, ys, part; for (int t = 0; t < steps; ++t) { - /* this step's rows: the next `take` units, wrapping */ + /* This step's rows: the next `take` row units, wrapping. */ std::vector us; for (int64_t i = 0; i < take; ++i) us.push_back((t * take + i) % nunits); std::sort(us.begin(), us.end()); us.erase(std::unique(us.begin(), us.end()), us.end()); - int64_t R = 0; - for (int64_t u : us) R += std::min(unit, N - u * unit); - ws.resize((size_t)(R * K)); - { - int64_t at = 0; - for (int64_t u : us) { - const int64_t n = std::min(unit, N - u * unit); - std::memcpy(&ws[(size_t)(at * K)], w + u * unit * K, (size_t)(n * K) * sizeof(float)); - at += n; - } - } + const int64_t R = gather_units(w, N, K, unit, us, &ws); vs = ws; #ifdef _OPENMP #pragma omp parallel for schedule(static) @@ -252,8 +240,8 @@ void fit(const Paro& p, const float* w, int64_t N, int64_t K, const float* H, co } if (t == 0) norm = loss > 0.0 ? loss : 1.0; - /* THE BACKWARD PASS, a row at a time into the row's own slot of `part`: dL/dD = 2 G; D = - * y_S / scale; and each inverse stage (a, b) -> (c a - s b, s a + c b) gives + /* Backward pass, one row at a time into the row's own slot of `part`: dL/dD = 2 G, + * D = y_S / scale, and each inverse stage (a, b) -> (c a - s b, s a + c b) gives * dL/dt = g_a (-y_b) + g_b y_a over its outputs and sends g back by the transpose. */ part.assign((size_t)(R * P), 0.0f); #ifdef _OPENMP @@ -286,7 +274,7 @@ void fit(const Paro& p, const float* w, int64_t N, int64_t K, const float* H, co } } } - /* the sum over rows, in row order, and the Adam step on it */ + /* Sum over rows in row order, then take the Adam step. */ const double lt = lr_min + 0.5 * (lr - lr_min) * (1.0 + std::cos(M_PI * t / steps)); const double c1 = 1.0 - std::pow(b1, t + 1), c2 = 1.0 - std::pow(b2, t + 1); #ifdef _OPENMP @@ -312,9 +300,9 @@ void fit(const Paro& p, const float* w, int64_t N, int64_t K, const float* H, co } } -/* T^-1 H T^-T, block by rotation group: T^-1 is block-diagonal over the groups, so its rows for a - * group are formed once, by sending each unit vector through the inverse, and every block of H is - * multiplied on both sides by them. */ +/* T^-1 H T^-T by rotation group. T^-1 is block-diagonal over the groups, so its rows are formed + * once by sending each unit vector through the inverse, and each block of H is multiplied by them + * on both sides. */ std::vector transformed_hessian(const Rot& rot, const float* H, const float* diag, int64_t K, int64_t gr) { const int64_t ng = K / gr; @@ -371,8 +359,8 @@ int paro_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* sr const int64_t want = std::max(1, rad_param_geti(o, n_o, "sample_rows", 512)); const int iters = (int)std::max(0, rad_param_geti(o, n_o, "iters", 100)); - /* THE MODEL'S OWN DOMAIN: the grid carries no Hadamard (paroquant_info refuses one), and the - * rotation this fits is applied to the weight and the Hessian here, after the read. */ + /* Domain 0: the grid carries no Hadamard (paro_setup refuses one), and the fitted rotation is + * applied to the weight and the Hessian here, after the read. */ const Gram Hg = calib_gram(dir, w->name, K, 0, "paroquant"); const float* H = Hg ? Hg->data() : nullptr; const float* diag = H ? nullptr : w->importance; diff --git a/libquant/lq_quant.h b/libquant/lq_quant.h index 4fb087a0..f2a881f8 100644 --- a/libquant/lq_quant.h +++ b/libquant/lq_quant.h @@ -1,14 +1,17 @@ -/* lq_quant.h -- what every libquant quantiser shares: the grid's options as a recipe spells them, - * reading a grid off a rule, and the table each algorithm file exports its quantiser through. +/* lq_quant.h -- shared by every libquant quantiser: the grid options a recipe spells, reading a + * grid off a rule, and the table each algorithm file exports its quantiser through. * - * lq_registry.cpp holds the plugin's exports and the quantisers that are a few lines each (rtn, - * gptq, cast); an algorithm with a loop of its own (AWQ, AutoRound, ParoQuant) is a file, and its - * RadQuantizerInfo comes back from the function named for it below. + * lq_registry.cpp holds the plugin's exports and the short quantisers (rtn, gptq, cast). An + * algorithm with its own loop (AWQ, AutoRound, ParoQuant) has its own file and returns its + * RadQuantizerInfo from the function named for it below. */ #pragma once #include "lq_grid.h" +#include #include +#include +#include /* The grid options, shared by every quantiser over a grid. */ #define LQ_GRID_OPTIONS \ @@ -48,8 +51,8 @@ namespace lq { * weight's name, when it is refused. */ int grid_of(const RadParam* o, int n_o, const RadQuantWeight* w, Grid* g); -/* A rank-1 weight -- a norm, a bias -- is declined rather than quantised: nothing in a recipe - * should have to spell out every vector a pattern happens to match. */ +/* Rank-1 weights (norms, biases) are declined rather than quantised, so a recipe pattern need not + * exclude every vector it happens to match. */ inline bool declines(const RadQuantWeight* w) { return !w || w->rank < 2; } /* Say why a rule is refused, with the weight's name, and return RAD_E_INVAL. */ @@ -58,6 +61,22 @@ int refuse(const RadQuantWeight* w, const char* why); /* A 64-bit hash of a string, for a seed that is the same on every machine and every run. */ uint64_t name_seed(const char* s); +/* The rows of `w` [N, K] in the listed row units of `unit` rows each (the last unit may be short), + * packed in list order into `out`. Returns the row count. */ +inline int64_t gather_units(const float* w, int64_t N, int64_t K, int64_t unit, + const std::vector& units, std::vector* out) { + int64_t rows = 0; + for (int64_t u : units) rows += std::min(unit, N - u * unit); + out->resize((size_t)(rows * K)); + int64_t at = 0; + for (int64_t u : units) { + const int64_t n = std::min(unit, N - u * unit); + std::memcpy(out->data() + at * K, w + u * unit * K, (size_t)(n * K) * sizeof(float)); + at += n; + } + return rows; +} + /* The algorithm files' quantisers. */ const RadQuantizerInfo& awq_info(); const RadQuantizerInfo& autoround_info(); diff --git a/libquant/lq_registry.cpp b/libquant/lq_registry.cpp index cdc003bf..8dc0dc0a 100644 --- a/libquant/lq_registry.cpp +++ b/libquant/lq_registry.cpp @@ -1,11 +1,10 @@ /* lq_registry.cpp -- libquant's quantiser table and plugin exports. spec.md §4.5. * - * A quantiser here is an ALGORITHM over a GRID (lq_grid.h): `rtn` rounds each value to its nearest - * grid point, `gptq` feeds each column's rounding error into the columns after it, `awq` scales the - * input channels the activations say matter, `autoround` descends on the rounding itself and - * `paroquant` learns a rotation of the input channels first. All of them take the same grid - * options, so a code type, a scale structure or a transform added to the grid is available to each - * the moment it exists. Two are not over a grid: `ggml` writes llama.cpp's own formats by + * Most quantisers are an algorithm over a grid (lq_grid.h): `rtn` rounds each value to its nearest + * grid point, `gptq` feeds each column's rounding error into later columns, `awq` scales the input + * channels the activations say matter, `autoround` descends on the rounding itself and `paroquant` + * first learns a rotation of the input channels. They share the grid options, so anything added to + * the grid is available to all. Two are not over a grid: `ggml` writes llama.cpp's formats by * llama.cpp's own searches (lq_ggml.h), and `cast` converts a weight to another float dtype. */ #include "lq_ggml.h" @@ -23,11 +22,7 @@ namespace lq { int grid_of(const RadParam* o, int n_o, const RadQuantWeight* w, Grid* g) { std::string why; - const int st = grid_parse(o, n_o, g, &why); - if (st != RAD_OK) { - std::fprintf(stderr, "libquant: %s: %s\n", w && w->name ? w->name : "?", why.c_str()); - return st; - } + if (grid_parse(o, n_o, g, &why) != RAD_OK) return refuse(w, why.c_str()); if (!w || w->cols <= 0 || w->rows <= 0) return RAD_E_SHAPE; if (g->fwht && w->cols % g->fwht) return RAD_E_SHAPE; return RAD_OK; @@ -81,7 +76,7 @@ int rtn_encoding(const RadParam* o, int n_o, const RadQuantWeight* w, RadEncodin int64_t rtn_row_block(const RadParam* o, int n_o, const RadQuantWeight* w) { Grid g; if (grid_of(o, n_o, w, &g) != RAD_OK) return 0; - return grid_row_block(g, w->rows); + return grid_row_block(g); } int rtn_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src, int64_t row0, @@ -94,10 +89,10 @@ int rtn_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src } /* ------------------------------------------------------------------ gptq */ -/* ACT ORDER IS A TRANSFORM OF THE ENCODING, not a detail of the loop: the codes are stored in the - * order they were quantised, so the scale groups are runs of that order, and the reader is told - * the permutation ("perm", a t.perm table of one i32 a column) to undo it. It does not compose - * with the grid's own rotation -- an encoding carries one transform. */ +/* Act order is a transform of the encoding: codes are stored in quantisation order, so scale + * groups are runs of that order, and the reader gets the permutation ("perm", a t.perm table of one + * i32 per column) to undo it. It cannot combine with the grid's rotation, since an encoding carries + * one transform. */ int gptq_encoding(const RadParam* o, int n_o, const RadQuantWeight* w, RadEncoding* out) { if (declines(w)) return RAD_E_UNSUPPORTED; Grid g; @@ -149,7 +144,7 @@ int gptq_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* sr } } - /* The scales first, from the weight as it stands, and fixed through the loop. */ + /* Scales come first, from the weight as it stands, and stay fixed through the loop. */ const Scales sc = grid_scales(g, src, N, K, imp); const Planes p = grid_planes(g, K, planes); grid_store_scales(g, sc, p); @@ -178,10 +173,9 @@ int gptq_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* sr } /* ------------------------------------------------------------------ cast */ -/* A FLOAT WEIGHT IN ANOTHER FLOAT DTYPE, rounded to nearest even: an f32 checkpoint served at - * bf16, a bf16 one at f16, or plain fp8 with no scale at all. Every rank is taken, a norm's - * included -- a cast is asked for by name, and a kernel that cannot read the result refuses it at - * declare like any other encoding. */ +/* A float weight in another float dtype, round to nearest even: an f32 checkpoint served as bf16, + * bf16 as f16, or plain unscaled fp8. Every rank is accepted, norms included: a cast is requested by + * name, and a kernel that cannot read the result refuses it at declare like any other encoding. */ int cast_dtype(const RadParam* o, int n_o, const RadQuantWeight* w, uint32_t* dt) { const char* s = rad_param_gets(o, n_o, "dtype", nullptr); *dt = s ? rad_dtype_parse(s) : (uint32_t)RAD_DT_INVALID; @@ -201,25 +195,25 @@ int cast_encoding(const RadParam* o, int n_o, const RadQuantWeight* w, RadEncodi int64_t cast_row_block(const RadParam*, int, const RadQuantWeight*) { return 1; } -int cast_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src, int64_t row0, +int cast_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src, int64_t, int64_t rows, void* const* planes) { uint32_t dt = 0; const int st = cast_dtype(o, n_o, w, &dt); if (st != RAD_OK) return st; - (void)row0; const int64_t n = rows * w->cols; uint8_t* out = (uint8_t*)planes[0]; + auto each = [n](auto store) { #ifdef _OPENMP #pragma omp parallel for schedule(static) #endif - for (int64_t i = 0; i < n; ++i) { - switch (dt) { - case RAD_F32: ((float*)out)[i] = src[i]; break; - case RAD_BF16: ((uint16_t*)out)[i] = f32_to_bf16(src[i]); break; - case RAD_F16: ((uint16_t*)out)[i] = f32_to_f16(src[i]); break; - case RAD_F8E4M3: out[i] = rad_f32_to_fp8e4m3(src[i]); break; - default: out[i] = rad_f32_to_fp8e5m2(src[i]); break; - } + for (int64_t i = 0; i < n; ++i) store(i); + }; + switch (dt) { + case RAD_F32: std::memcpy(out, src, (size_t)n * sizeof(float)); break; + case RAD_BF16: each([&](int64_t i) { ((uint16_t*)out)[i] = f32_to_bf16(src[i]); }); break; + case RAD_F16: each([&](int64_t i) { ((uint16_t*)out)[i] = f32_to_f16(src[i]); }); break; + case RAD_F8E4M3: each([&](int64_t i) { out[i] = rad_f32_to_fp8e4m3(src[i]); }); break; + default: each([&](int64_t i) { out[i] = rad_f32_to_fp8e5m2(src[i]); }); break; } return RAD_OK; } diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index decedb17..17879e15 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -1,17 +1,15 @@ -# THE ARCHITECTURES libr4d SERVES, declared here and nowhere else. Its kernels are written for -# RDNA4: wave32, the gfx12 WMMA fragment layouts, and gfx12-only instructions such as -# global_load_tr_b128. Compiled for anything else they would launch and compute garbage, so the -# coverage is a property of the library and the library is what states it. +# libr4d serves RDNA4 only, declared here and nowhere else. Its kernels rely on wave32, the gfx12 +# WMMA fragment layouts and gfx12-only instructions such as global_load_tr_b128; built for other +# targets they would compute garbage. # -# A build targeting other cards skips libr4d and keeps going. What it gets is an engine with no -# device kernel library for that card, which REFUSES TO SERVE an op only a reference library -# implements unless --debug-accept-reference-kernels is passed (spec §17) -- an unserved card that -# says so, rather than a project that will not configure. Supplying a kernel library for that card -# is the supported answer, and it is the same one an out-of-tree author gives. +# A build targeting other cards skips libr4d. The engine then has no device kernel library for that +# card and refuses ops only a reference library implements, unless +# --debug-accept-reference-kernels is passed (spec §17). The supported fix is a kernel library for +# that card. # -# A plugin like any other: built here inside radiance's tree, or on its own against an installed -# radiance (`cmake -S libr4d -B build -DCMAKE_PREFIX_PATH=`, with the HIP compiler -# named as for the tree) -- the same rad_add_plugin either way (cmake/RadAddPlugin.cmake). +# Built in radiance's tree, or standalone against an installed radiance +# (`cmake -S libr4d -B build -DCMAKE_PREFIX_PATH=`, naming the HIP compiler as for +# the tree); see cmake/RadAddPlugin.cmake. if(NOT COMMAND rad_add_plugin) cmake_minimum_required(VERSION 3.21) project(libr4d LANGUAGES CXX HIP) @@ -26,87 +24,72 @@ if(NOT R4D_GPU_TARGETS) return() endif() -# The libr4d kernel plugin, and THE ONLY BUILD libr4d HAS: this list is the definition of its -# translation units. +# R4D_UNITS is the definitive list of libr4d's device translation units, as "unit|extra flags". +# The GDN chunk scan needs -mcumode. The quantised GEMMs' group sizes are source constants, not +# build options: the host packer reads r4d_args.h and the units their own defaults, which must +# agree (r4d_gemm_args.h static_asserts the w4 and w8 groups). # -# THE PER-UNIT FLAGS ARE NOT DECORATION: the GDN chunk scan needs -mcumode, and every quantised -# GEMM needs its group size, which must match the group the weights were packed at or the kernel -# reads the wrong scales. -# -# Every unit is compiled -ffp-contract=off. The quantised all-reduce REQUIRES it: it sums two -# dequantised products per element, the two ranks see the products in the opposite order, and -# contracting either into an FMA makes them disagree by ~1 ULP -- which breaks the replicated-state -# invariant. For the rest it is reproducibility: the costs the kernels' comments state hold at -# this setting. +# Every unit is compiled -ffp-contract=off. The quantised all-reduce requires it: the two ranks sum +# two dequantised products per element in opposite order, and an FMA on either side makes them +# differ by ~1 ULP, breaking the replicated-state invariant. Elsewhere it keeps results and the +# costs quoted in kernel comments reproducible. -# ONE DIRECTORY: the kernels and libr4d's own declaration -- the row table, the layouts -- live -# together. There is no launch adapter between the plugin ABI and the kernels: every entry point -# takes `(const RadArgs*, RadStream)` and sits beside the kernel it launches. -# -# THIS PLUGIN LINKS rad_abi AND NOTHING ELSE: it is a standalone plugin built on abi/, exactly like -# one written out of tree. - -# The weight group size, as the DEVICE units see it. It is NOT one variable covering both sides: -# the packer is r4d_layout.cpp, a host source in R4D_DECLARATION below, which no -D here reaches -- -# it reads R4D_W4_GROUP from r4d_args.h, a hardcoded 128. So changing this alone re-groups the -# kernel and leaves the packer at 128, which is precisely the silently-wrong-output the single -# variable was supposed to rule out. -# CHANGING THE GROUP MEANS CHANGING BOTH, and the enum is the one that decides what is on disk. -set(RAD_W4_GROUP 128 CACHE STRING "libr4d quantised-weight group size (must match R4D_W4_GROUP in r4d_args.h)") +# Kernels and libr4d's declaration (row table, layouts) share one directory. There is no launch +# adapter: every entry point takes `(const RadArgs*, RadStream)` and sits beside its kernel. The +# plugin links rad_abi only, like one written out of tree. set(R4D_UNITS "r4d_attn_paged_h256_gqa6|" "r4d_attn_paged_h128_gqa4|" # Gemma 4 dense sliding window: head_dim 256, 2 queries per KV head, windowed decode and - # prefill. The windowed twin of the drafter leg above. + # prefill. "r4d_attn_paged_h256_gqa2|" - # Eight queries per KV head, at both head widths: the routed 35B-A3B is 16 over 2 at 256 - # and MiniCPM5-2B is 16 over 2 at 128. Same device code, different instantiations. + # Eight queries per KV head, one body instantiated at head_dim 256 (the routed 35B-A3B) and 128 + # (MiniCPM5-2B). "r4d_attn_paged_gqa8|" - # Twelve, head_dim 256 only: Qwen3.8-Flash-Next's QSA layers are 24 over 2. Four lines that - # set the ratio and include the unit above, which is the parameterised body. + # The gqa12, gqa4 and gqa6_bs4 units set the ratio and include the parameterised body above. + # gqa12, head_dim 256: Qwen3.8-Flash-Next's QSA layers (24 query heads over 2). "r4d_attn_paged_h256_gqa12|" - # Four, head_dim 256: Qwen3.5-0.8B is 8 over 2 at the 27B's head width. Again the body above - # with the ratio set. + # gqa4, head_dim 256: Qwen3.5-0.8B (8 over 2). "r4d_attn_paged_h256_gqa4|" - # Six, head_dim 256 and the same 4-token page: the same QSA layers at four ranks, where each KV - # head is replicated across a rank pair. Again four lines that set the ratio and include the body. + # gqa6, head_dim 256, 4-token page: the same QSA layers at four ranks, each KV head replicated + # across a rank pair. "r4d_attn_paged_h256_gqa6_bs4|" - # head_dim 256 and 512 at 1, 2, 4 or 8 queries per KV head with ANY window: Gemma 4's sliding - # (h256/gqa2, window 1024) and full (h512, gqa 8 at TP1/TP2) layers. One kernel a geometry for - # every q_len, reading q at any row pitch, which is what attn_paged_qrow is. + # head_dim 256 and 512 at 1, 2, 4 or 8 queries per KV head with any window: Gemma 4's sliding + # (h256/gqa2, window 1024) and full (h512, gqa 8 at TP1/TP2) layers. One kernel per geometry + # covers every q_len and reads q at any row pitch (attn_paged_qrow). "r4d_attn_paged_window|" + # Two queries per KV head at head_dim 128 only (Qwen3-1.7B's 16 over 8, Qwen3-ASR's decoder): + # the gqa8 body with the ratio set. + "r4d_attn_paged_h128_gqa2|" "r4d_attn_vit_h72_bf16|" # An encoder's dense attention (bidirectional, GQA in the workgroup, a two-sided window) and # the small ops around it: act_mul, seg_mean, qk_norm_rope with a v norm, the f32 widening. "r4d_attn_dense_bf16|" "r4d_encoder_bf16|" - # The image generator: attention over a paged prefix and the pass's own rows, the causal - # head_dim-128 dense form and the 1152-wide decoder head; and the sampler, adaptive norm, - # implicit-GEMM convolution and pixel ops around them. + # The image generator: attention over a paged prefix plus the pass's own rows, the causal + # head_dim-128 dense form and the 1152-wide decoder head; plus the sampler, adaptive norm, + # implicit-GEMM convolution and pixel ops. "r4d_attn_gen|" "r4d_gen|" - # The vision tower's own small ops: layer norm, the learned-grid position embedding, and the - # biased GEMM with a linear layer's activation and residual in its store. + # Vision tower ops: layer norm, the learned-grid position embedding, and the biased GEMM with + # activation and residual fused into its store. "r4d_vit_bf16|" "r4d_gdn_chunk_scan_k128_v128_c64_bf16|-mcumode" "r4d_gdn_conv_w4_h128_bf16|" "r4d_gdn_kkt_solve_k128_c64_bf16|" "r4d_gdn_recurrent_update_k128_v128_bf16_fp32state|" "r4d_gdn_gated_rmsnorm_h128_bf16|" - # The gated residual, which is what a hyper-connection model has instead of a pre-norm and a - # residual add. ONE unit: hc_read is two launches behind one entry point, because the mix - # depends on every column of the low-rank waist and a kernel boundary is the grid-wide - # barrier that says so. + # The hyper-connection gated residual (in place of pre-norm plus residual add). hc_read is two + # launches behind one entry point: the mix depends on every column of the low-rank waist, so it + # needs a grid-wide barrier. "r4d_hc_bf16|" "r4d_ngram_ids|" "r4d_ple_gate_bf16|" "r4d_ple_conv_bf16|" - # The all-reduce family is ONE unit and not one per kernel: they share a single instance -- - # peer scratch, IPC-equivalent pointers, per-block flags, device sequence counters -- and one - # rendezvous that establishes it across every rank before the first launch. Splitting the entry - # points across the six kernel units would put that state in a header and give each unit its own - # copy of it, which is the one thing it must not have. + # The all-reduce kernels share one instance (peer scratch, IPC-equivalent pointers, per-block + # flags, device sequence counters) set up by one rendezvous across ranks, so all entry points + # live in r4d_ar_entry. Spreading them across the kernel units would give each its own copy. "r4d_ar_entry|" "r4d_ar_gather_2rank|" "r4d_ar_gather_Nrank|" @@ -118,23 +101,22 @@ set(R4D_UNITS "r4d_gemm_bf16_nt_m16|" "r4d_gemm_bf16_nt_m64|" "r4d_gemm_bf16_nt_tiled|" - "r4d_gemm_w4a16_nt_m64|-DR4D_GEMM_W4_GROUP=${RAD_W4_GROUP}" - "r4d_gemm_w5a16_nt_m64|-DR4D_GEMM_W4_GROUP=${RAD_W4_GROUP}" + "r4d_gemm_w4a16_nt_m64|" + "r4d_gemm_w5a16_nt_m64|" "r4d_gemm_wpa8i8_tiled|" "r4d_givens_dense|" - "r4d_gemm_w8a16_nt_m64|-DR4D_GEMM_W8_GROUP=${RAD_W4_GROUP}" - "r4d_gemm_w2a8_nt|-DR4D_GEMM_W2A8_GROUP=${RAD_W4_GROUP}" - "r4d_gemm_w4a8_nt_m64|-DR4D_GEMM_W4A8_GROUP=${RAD_W4_GROUP}" - "r4d_gemm_w8a8_nt_m64|-DR4D_GEMM_W8A8_GROUP=${RAD_W4_GROUP}" - "r4d_gemm_w8a8_tiled|-DR4D_GEMM_W8A8_GROUP=${RAD_W4_GROUP}" - "r4d_gemm_w4a8_tiled|-DR4D_GEMM_W4A8_GROUP=${RAD_W4_GROUP}" - "r4d_gemm_w4a8_prefill|-DR4D_GEMM_W4A8_GROUP=${RAD_W4_GROUP}" + "r4d_gemm_w8a16_nt_m64|" + "r4d_gemm_w2a8_nt|" + "r4d_gemm_w4a8_nt_m64|" + "r4d_gemm_w8a8_nt_m64|" + "r4d_gemm_w8a8_tiled|" + "r4d_gemm_w4a8_tiled|" + "r4d_gemm_w4a8_prefill|" "r4d_gemm_mxfp4a8_nt_m64|" "r4d_gemm_mxfp4a8_tiled|" "r4d_gemm_mxfp4a8_decode|" - # Block-scaled FP8 -- the format Qwen3.8-27B-FP8 ships in. - # No -D: the 128x128 block is a property of the checkpoint on disk and not a quantiser choice - # like RAD_W4_GROUP, so it is a constant in the source and the entry points reject a mismatch. + # Block-scaled FP8 (the format Qwen3.8-27B-FP8 ships in). The 128x128 block is fixed by the + # checkpoint, and the entry points reject a mismatch. "r4d_gemm_fp8a16_nt_m1|" "r4d_gemm_fp8a8|" "r4d_quant_act_fp8|" @@ -163,14 +145,14 @@ set(R4D_UNITS "r4d_rowtopk_bf16|" # The vocab-sharded draft head's cross-rank top-1, one id a row. "r4d_pair_argmax_f32|" - # Gemma 4's two sandwich-norm joins (norm_add_norm, norm_add_norm_route, join_add_scale) and - # expert_scale: each one kernel for a chain of small ones. + # Gemma 4's sandwich-norm joins (norm_add_norm, norm_add_norm_route, join_add_scale) and + # expert_scale, each one kernel for a chain of small ones. "r4d_norm_join_bf16|" "r4d_expert_scale_bf16|" "r4d_dflash_conv_t2_g16_bf16|" "r4d_dflash_select_bf16|" - # The routed mixture of experts: router, scatter, the grouped block-scaled fp8 GEMM and - # gather, in one unit because the other three exist only to feed the GEMM. + # Routed MoE: router, scatter, the grouped block-scaled fp8 GEMM and gather, in one unit because + # the other three only feed the GEMM. "r4d_moe|" ) @@ -193,16 +175,9 @@ foreach(u ${R4D_UNITS}) list(APPEND R4D_SRC "${src}") endforeach() -# THE HOST SOURCES IN libr4d/ ARE DECLARATION. There is no launch adapter: every entry point -# takes `(const RadArgs*, RadStream)` and lives beside the kernel it launches, in libr4d. -# These are the plugin's statements ABOUT those kernels -- the row table, the weight layouts and -# their relayouts, the operand descriptions, the fusion claims -- and all of them are PURE HOST -# C++ that include neither r4d.h nor hip_runtime.h. -# -# That split is what lets the tables a transcription error hides in be compiled and read on a box -# with no ROCm, and it is why an operand description (answered before anything is allocated) and a -# declared fusion (a statement about the op vocabulary, answered with no tensors in hand) belong -# here rather than in a translation unit that needs a compiler for the card. +# The host sources are declaration only: the row table, weight layouts and relayouts, operand +# descriptions and fusion claims. They are pure host C++ that includes neither r4d.h nor +# hip_runtime.h, so these tables compile and can be inspected without ROCm. set(R4D_DECLARATION r4d_rows.cpp r4d_layout.cpp r4d_fp8_layout.cpp r4d_shapes.cpp r4d_fuse.cpp) rad_add_plugin(libr4d kernels @@ -211,18 +186,15 @@ rad_add_plugin(libr4d kernels GPU_TARGETS ${R4D_GPU_TARGETS} INCLUDES ${CMAKE_CURRENT_SOURCE_DIR}) -# The catalogue dump: prints every row and, on a card, calls each launch with a minimal valid -# input. This is how a transcription error in the constraint table is found -- otherwise it is -# invisible until a model silently picks the wrong kernel. It dlopens the plugin rather than -# linking it, because an undefined symbol in the .so is itself one of the things being tested. +# Catalogue dump: prints every row and, on a card, calls each launch with a minimal valid input, to +# catch transcription errors in the constraint table. It dlopens the plugin so an undefined symbol +# in the .so is caught too. add_executable(r4d_selftest ${CMAKE_CURRENT_SOURCE_DIR}/r4d_selftest.cpp) -# It dlopens the plugin but allocates the device buffers it feeds the kernels itself, so it needs -# the HIP runtime even though it links no kernel. +# Links the HIP runtime to allocate the device buffers it feeds the kernels. target_link_libraries(r4d_selftest PRIVATE radiance::abi ${CMAKE_DL_LIBS} ${RAD_HIP_RUNTIME}) target_include_directories(r4d_selftest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) set_target_properties(r4d_selftest PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) -# libr4d is built at -std=c++17: at C++20 clang tightens the address-space check on -# __builtin_amdgcn_global_load_tr_b128_v8i16 in r4d_common.h, and C++17 is the configuration every -# cost stated in the kernels' comments was taken in. +# C++17: at C++20 clang tightens the address-space check on +# __builtin_amdgcn_global_load_tr_b128_v8i16 in r4d_common.h. Kernel cost figures are for C++17. set_target_properties(libr4d PROPERTIES HIP_STANDARD 17 HIP_STANDARD_REQUIRED ON) diff --git a/libr4d/README.md b/libr4d/README.md index e40be5a2..99a5a294 100644 --- a/libr4d/README.md +++ b/libr4d/README.md @@ -1,121 +1,123 @@ # libr4d -R4D is a library of specialized HIP kernels for **gfx1201 (RDNA4, Radeon AI PRO R9700)**. - -It is built by the radiance engine, which is its only consumer: `libr4d/CMakeLists.txt` names -every translation unit and the per-unit flags each one needs. +libr4d is radiance's kernel library for RDNA4 (gfx12, developed on gfx1201, the Radeon AI PRO +R9700): specialised HIP kernels behind a plain C ABI ([`r4d.h`](r4d.h)) and the kernel-plugin rows +the engine selects from (`r4d_rows.cpp`). `libr4d/CMakeLists.txt` names every translation unit and +the per-unit flags each needs. ## Naming An entry point is ``` -__ +r4d___ ``` -and the geometry is not decoration. These are specialised kernels: every dimension in the name is a -compile-time constant, and the entry point **rejects a mismatch rather than running**. -`attn_decode_h256_gqa6_fp8kv` serves head_dim 256 with 6 queries per KV head and an fp8-e4m3 paged -cache, and nothing else. A model with a different head size needs a new instantiation, which gets -its own name beside this one -- no existing name has to change to make room for it, and no caller -can pick up a kernel that does not fit by accident. +Every dimension in the name is a compile-time constant, and the entry point rejects a mismatch +instead of running. `attn_decode_h256_gqa6_fp8kv` serves head_dim 256 with 6 queries per KV head and +an fp8-e4m3 paged cache, and nothing else. A model with another head size needs a new +instantiation under its own name, so no existing name changes and no caller can pick up a kernel +that does not fit. -Dimensions that are the same across the whole library discriminate nothing between entry points and -so stay out of the names: the paged block size (16), the query dtype (bf16 everywhere) and the -target architecture. They are reported by the `r4d_*_dims()` accessors in -[`r4d.h`](r4d.h) and by the `RadKernelInfo` rows in `r4d_rows.cpp`. +Dimensions that are the same across the whole library stay out of the names: the paged block size +(16), the query dtype (bf16) and the target architecture. The `r4d_*_dims()` accessors in +[`r4d.h`](r4d.h) and the `RadKernelInfo` rows in `r4d_rows.cpp` report them. + +The table lists a selection; `r4d_rows.cpp` and `r4d.h` hold the full set. | entry point | what it is | | --- | --- | | `attn_prefill_h256_gqa6_fp8kv` / `..._bf16kv` | paged causal attention, query-tiled; head_dim 256, 6 queries per KV head, fp8-e4m3 or bf16 KV cache | -| `attn_decode_h256_gqa6_fp8kv` / `..._bf16kv` | the same geometry, split-KV, up to 64 query rows | -| `attn_decode_h256_gqa6_scratch_bytes` / `attn_decode_h128_gqa4_scratch_bytes` | how many bytes of split-KV scratch a given launch needs — ask before allocating; the split count is chosen from the geometry | +| `attn_decode_h256_gqa6_fp8kv` / `..._bf16kv` | the same geometry, split-KV, `q_len * gqa` ≤ 64 | +| `attn_decode_h256_gqa6_scratch_bytes` / `attn_decode_h128_gqa4_scratch_bytes` | bytes of split-KV scratch a launch needs; ask before allocating, since the split count is chosen from the geometry | | `attn_vit_h72_bf16` | dense non-causal vision-encoder attention, head_dim 72 native, varlen over images | -| `gdn_conv_prep_w4_h128_bf16` | the gdn prefill preamble in one kernel: causal conv (width 4, silu, with its state cache), q/k/v split, qk l2norm, gating and the per-chunk gate cumsum | -| `gdn_kkt_solve_k128_c64_bf16` | `A = (I + strict_lower(diag(beta) K K^T e^dg))^-1` per chunk of 64 -- the gram and its triangular inverse, without the fp32 gram ever reaching memory | -| `gdn_chunk_scan_k128_v128_c64_bf16` | gated-delta-net chunked scan -- WY recompute, state recurrence and output in one kernel; head_k 128, head_v 128, chunk 64 | +| `gdn_conv_prep_w4_h128_bf16` | the GDN prefill preamble in one kernel: causal conv (width 4, silu, with its state cache), q/k/v split, qk l2norm, gating and the per-chunk gate cumsum | +| `gdn_kkt_solve_k128_c64_bf16` | `A = (I + strict_lower(diag(beta) K K^T e^dg))^-1` per chunk of 64: the gram and its triangular inverse, without the fp32 gram reaching memory | +| `gdn_chunk_scan_k128_v128_c64_bf16` | gated-delta-net chunked scan: WY recompute, state recurrence and output in one kernel; head_k 128, head_v 128, chunk 64 | | `gdn_conv_update_w4_h128_bf16` | the same convolution for a decode step: a rolling speculative window over the conv state cache, writing q/k/v directly | | `gdn_recurrent_update_k128_v128_bf16_fp32state` | the decode-time recurrent delta-rule update against the paged fp32 state cache, gating and qk l2norm included | -| `gdn_gated_rmsnorm_h128_bf16` | gated rms norm over a 128-channel row, `out = rms(x) . w . act(z)` | +| `gdn_gated_rmsnorm_h128_bf16` | gated RMS norm over a 128-channel row, `out = rms(x) . w . act(z)` | | `ar_oneshot_2rank_exact` | one-shot push all-reduce over P2P, exactly 2 ranks, exact bf16/fp16/fp32 | | `ar_oneshot_2rank_wht6` | the same handshake with a Walsh-Hadamard-rotated 6-bit wire payload (lossy) | -| `gemm_bf16_nt_m16` | skinny bf16 GEMM, `C[M,N] = A[M,K] @ W[N,K]^T`, M ≤ 16, split-K. **Superseded on every shape measured by the WMMA row below**, which the shim forwards to — its accumulators are registers indexed by row, so it falls off a cliff past 8 rows and is several times slower at M = 16. `R4D_BF16_M16=1` reaches it. | -| `gemm_bf16_nt_m64` | the same GEMM for M ≤ 64, one 16x16x16 WMMA per row tile per 16 of K | -| `gemm_w4a16_nt_m64` | the same GEMM with a **4-bit weight** — asymmetric scale and integer zero per 128 K, pre-permuted offline into WMMA fragment order so the weight path is one `global_load_b128` per lane per four k steps, f16 activations, bf16 out | -| `gemm_w4a8_nt_m64` | the 4-bit weight against an **int8 activation** through `v_wmma_i32_16x16x16_iu8` — twice the matrix rate of the f16 form. Symmetric scale per 128 K; the skinny decode kernel, M ≤ 64, per-shape (WV, SK, MB, NPW, NT) bands | +| `gemm_bf16_nt_m16` | the M ≤ 16 band (the MoE router gate), forwarded to `gemm_bf16_nt_m64`; no kernel of its own | +| `gemm_bf16_nt_m64` | skinny bf16 GEMM, `C[M,N] = A[M,K] @ W[N,K]^T`, one 16x16x16 WMMA per row tile per 16 of K, split-K; any M, with `gemm_bf16_nt_tiled` taking M > 64 where N ≥ 128 | +| `gemm_w4a16_nt_m64` | the same GEMM with a 4-bit weight: f16 scale and integer zero per 128 K, pre-permuted offline into WMMA fragment order so the weight path is one `global_load_b128` per lane per four k steps; f16 activations, bf16 out | +| `gemm_w4a8_nt_m64` | the 4-bit weight against an int8 activation through `v_wmma_i32_16x16x16_iu8`, twice the matrix rate of the f16 form. Symmetric scale per 128 K; the skinny decode kernel, M ≤ 64, tunable over `wv`, `sk`, `mb`, `npw`, `nt` | | `gemm_w4a8_asym_nt_m64` | the same with an asymmetric grid: unsigned B fragment, per-group zero from the scale dword's high half, minus the activation's per-group row sums | -| `gemm_w4a8_tiled` | the prefill/large-M sibling, block tile 128x256, BK=64 double-buffered through registers; variant-indexed tile table | +| `gemm_w4a8_tiled` | the large-M sibling: block tile 128x256 by default (a `tile` axis selects other compiled arms), BK = 64 double-buffered in LDS | | `gemm_w4a8_asym_tiled` | the asymmetric grid at the tiled shape | -| `gemm_w4a8_prefill` | a second large-M W4A8 kernel, outranking `gemm_w4a8_tiled` in the M > 64 band; a tuned pick that names no prefill variant falls back to the tiled one | +| `gemm_w4a8_prefill` | a second large-M W4A8 kernel for the symmetric grid, ranked above `gemm_w4a8_tiled` | | `gemm_w8a8_nt_m64` | int8 weight against int8 activation, skinny; the promoted (8-bit) linears of a mixed-precision artifact | | `gemm_w8a8_tiled` | the prefill sibling of the above | | `gemm_w8a16_nt_m64` | 8-bit weight, f16 activation, skinny | -| `gemm_w2a8_nt` | 2-bit weight against int8 activation — the fast draft head | +| `gemm_w2a8_nt` | 2-bit weight against int8 activation: the DFlash2 draft head | | `gemm_mxfp4a8_nt_m64` | OCP-MXFP4 weight, fp8 activation, skinny | | `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_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 | -| `attn_decode_h128_gqa4_fp8kv` / `..._bf16kv` | head_dim 128, 4 queries per KV head, sliding window — a block-diffusion drafter's geometry. Decode only; `attn_h128_gqa4_have_prefill()` reports 0 so a caller routes long queries to its own fallback | +| `attn_decode_h128_gqa4_fp8kv` / `..._bf16kv` | head_dim 128, 4 queries per KV head, sliding window: a block-diffusion drafter's geometry. Decode only; there is no prefill row at this geometry | | `rowtopk_bf16` / `rowtopk_bf16_chunks` | exact per-row top-K over a bf16 matrix, two-stage | | `dflash_conv_t2_g16_bf16` | the drafter's causal conv, two taps, 16 groups | | `dflash_select_bf16` | the drafter's candidate selector: edge scores and the greedy path walk | -| `dequant_w4_bf16` | unpack a 4-bit fragment-ordered weight back to bf16 | -| `quant_act_i8` / `quant_act_i8_asum` | per-row int8 activation quantiser, **fragment-ordered** for the r4d GEMMs (see the warning below); the `_asum` form also emits the per-group row sums the asymmetric GEMMs need | -| `had_quant_act_i8` | the same with a block Walsh-Hadamard rotation first — the rotation is what makes one scale per row viable | +| `dequant_w4_bf16` | unpacks a 4-bit fragment-ordered weight back to bf16 | +| `quant_act_i8` / `quant_act_i8_asum` | per-row int8 activation quantiser, in the r4d GEMMs' fragment byte order; the `_asum` form also emits the per-group row sums the asymmetric GEMMs need | +| `had_quant_act_i8` | the same with a block Walsh-Hadamard rotation first, which is what makes one scale per row viable | | `rmsnorm_had_quant_i8` | residual add, RMS norm, rotate and quantise in one kernel | -| `ar_ln_had_quant_i8` | **the all-reduce and the norm that always follows it, fused**: the peer's contribution is a second operand on the norm's load, so the all-reduce's bf16 output never exists. Exact bf16 or rotated 6-bit wire (`wire`) | +| `ar_ln_had_quant_i8` | the all-reduce fused with the norm that follows it: the peer's contribution is a second operand on the norm's load, so the all-reduce's bf16 output never exists. Exact bf16 or rotated 6-bit wire (`wire`) | | `gated_had_quant_i8` | `silu(a)*b` or `sigmoid(a)*b`, then the same rotation and quantiser | -| `gdn_gated_norm_had_quant_i8` | the gdn gated norm with the rotation and quantiser fused onto it | -| `qk_norm_rope_gate` | q/k rms-norm, rope and the attention gate in one kernel | +| `gdn_gated_norm_had_quant_i8` | the GDN gated norm with the rotation and quantiser fused onto it | +| `qk_norm_rope_gate` | q/k RMS norm, rope and the attention gate in one kernel | | `ar_oneshot_{3,4,8}rank_exact`, `ar_twoshot_{3,4,8}rank_exact`, `ar_twoshot_{3,4}rank_ti8`, `ar_gather_3rank` | the wider-world collectives (TP3/TP4/TP8), exact and int8-wire | | `p2p_copy2d`, `p2p_copy2d_kernel`, `p2p_fence` | strided peer device-to-device copy, through the copy engines or a kernel | -## Asking the library instead of remembering -A geometry could be written down three times: in the entry point's name, in the check the entry -point rejects a mismatch on, and again in whatever caller decided it was allowed to make the call. -The third copy is the one that drifts, so the constraints are DATA rather than prose, and they live -where the answers are used rather than in this library's own registry. +## Constraints as data -`libr4d/r4d_rows.cpp` carries one `RadKernelInfo` row per kernel, with its geometry written as -`RadConstraint`s as well as in prose, and the engine's selector reads those rows to decide which -kernel serves a band — so a caller never has to know a geometry in order to ask for one. -`rad-kbench` tests the rows against the reference kernels, and `r4d_selftest` calls every launch -with a minimal valid input, which is how a transcription error in a constraint is found. +A geometry is stated in the entry point's name and in the check that rejects a mismatch. A third +copy in each caller would drift, so the constraints are data in the rows the engine reads. -The kernels themselves are plain HIP behind the C ABI in [`r4d.h`](r4d.h) and know nothing about -any of that. +`r4d_rows.cpp` carries one `RadKernelInfo` row per kernel, its geometry written as `RadConstraint`s +as well as in prose, and the engine's selector reads those rows to choose the kernel for a band; a +caller never needs to know a geometry to ask for one. `rad-kbench` tests the rows against the +reference kernels, and `r4d_selftest` calls every launch with a minimal valid input, which catches +a transcription error in a constraint. + +The kernels themselves are plain HIP behind the C ABI in [`r4d.h`](r4d.h) and know nothing of the +rows. ## Building -There is no build here. `libr4d/CMakeLists.txt` is it -- see the engine's `build.sh`. +libr4d builds inside radiance's tree (see `build.sh`) or on its own against an installed radiance +(`cmake -S libr4d -B build -DCMAKE_PREFIX_PATH=`). It is skipped when the build +targets no gfx12 architecture. -Translation units are compiled separately and linked, so per-kernel target features stay scoped: -`-mcumode` applies to `r4d_gdn_chunk_scan_k128_v128_c64_bf16.o` alone, and `-ffp-contract=off` is -global because the rotated 6-bit all-reduce requires it (the two ranks fuse different products -otherwise and diverge by ~1 ULP). +Translation units are compiled separately and linked, so per-kernel flags stay scoped: `-mcumode` +applies to `r4d_gdn_chunk_scan_k128_v128_c64_bf16` alone. `-ffp-contract=off` applies to every unit +because the quantised all-reduce requires it: otherwise the two ranks fuse different products and +diverge by about 1 ULP. ## Adding a kernel 1. Write the `.hip`; name the entry point for what it computes and the geometry it is compiled for. 2. Declare it in `r4d.h`, and add a `_dims()` accessor if it has compiled-in geometry a caller should be able to read. -3. Name the file after the entry point, geometry included; only shared machinery (`r4d_common.h`, - `r4d_dt16.h`, `r4d_gdn_wmma.h`) is named for what it is, because it provides no kernel. +3. Name the file after the entry point, geometry included. Only shared machinery that provides no + kernel (`r4d_common.h`, `r4d_dt16.h`, `r4d_gdn_wmma.h`) is named for what it is. 4. Add the translation unit to `R4D_UNITS` in `libr4d/CMakeLists.txt`, with any per-unit flags. -5. Add a `RadKernelInfo` row in `libr4d/r4d_rows.cpp` and a shim beside it -- that row is what - the engine's selector reads, so a kernel that is not in it is one no model can resolve to. Give - it the `op` of the operation it implements, which it may share with other rows, and write its - geometry as constraints as well as prose. -6. Add a case to `libr4d/r4d_selftest.cpp` so the row is called at least once. +5. Add a `RadKernelInfo` row in `libr4d/r4d_rows.cpp` whose launch is the + `(const RadArgs*, RadStream)` entry beside the kernel. The selector reads only these rows, so a + kernel without one cannot be resolved. Give it the `op` it implements (rows may share one) and + write its geometry as constraints as well as prose. +6. Add a case to `libr4d/r4d_selftest.cpp` so the row is called at least once; a row without one + reports `no smoke case`. -## Notes for anyone reading the kernels +## Notes on the kernels -Three properties of this architecture are assumed throughout and are not restated per kernel: +Three properties of the architecture are assumed throughout and not restated per kernel: * The wave32 WMMA fragment layout is `idx = lane % 16`, `k = 8*(e>>2) + 4*(lane>>4) + (e&3)`. Both - A and B want K-contiguous rows, so swapping the operands of a WMMA transposes the result for free. -* gfx1201 has no `v_cvt_pk_bf16_f32`, no direct-to-LDS, and no `ds_read_b64_tr_b16`. Packing bf16 is - software, and the cheapest form is two adds plus a `v_perm_b32`. -* LLVM single-buffers LDS and drains before every WMMA unless you tell it not to. - `__builtin_amdgcn_sched_group_barrier` is the fix, and the granularity of the groups matters far - more than their contents -- coarser is better, up to the point where the pattern asks for more + A and B want K-contiguous rows, so swapping the operands of a WMMA transposes the result. +* gfx1201 has no `v_cvt_pk_bf16_f32`, no direct-to-LDS and no `ds_read_b64_tr_b16`. Packing bf16 is + software; the cheapest form is two adds plus a `v_perm_b32`. +* LLVM single-buffers LDS and drains before every WMMA unless told otherwise. + `__builtin_amdgcn_sched_group_barrier` fixes it, and the granularity of the groups matters more + than their contents: coarser is better, up to the point where the pattern asks for more outstanding loads than the hardware can hold. diff --git a/libr4d/isa/README.md b/libr4d/isa/README.md index c3799d19..d1026043 100644 --- a/libr4d/isa/README.md +++ b/libr4d/isa/README.md @@ -1,10 +1,9 @@ -# libr4d/isa -- reading the machine code the kernels actually became +# libr4d/isa: reading the machine code the kernels became -Seven scripts and four microbenchmarks. They exist because "this kernel is slow" and "this kernel -is at the wall" look identical from a wall-clock timer, while the disassembly plus one calibration -number tells them apart without a GPU run at all. The trace tools are the exception: they need the -GPU, and they are the only instruments here that report the geometry a kernel was ACTUALLY launched -with rather than the geometries it could have been. +Nine scripts and four microbenchmarks. A wall-clock timer cannot tell "this kernel is slow" from +"this kernel is at the memory wall"; the disassembly plus one calibration number can, without a GPU +run. The trace tools are the exception: they need the GPU, and they are the only instruments here +that report the geometry a kernel was launched with rather than every geometry it could have had. BUILD=/path/to/build ./res.sh | head -40 # every kernel: vgpr/lds/scratch BUILD=... ./dis.sh r4d_gemm_fp8a8 ILb1ELb0ELj8ELj1ELj8ELj64ELb0E @@ -12,123 +11,118 @@ with rather than the geometries it could have been. ./loop.sh # its K loop, classified ./trace.sh traces/dec -- ./bin/radiance ... # then: ./tsum.sh traces/dec/k_kernel_trace.csv -`res.sh` prints the mangled name; the substring `dis.sh` takes is a template instantiation out of -it, and the parameter order is in the kernel's own declaration (`gemm_fp8a8_kernel` is -``, so `ILb1ELb0ELj8ELj1ELj8ELj64ELb0E` is the prefill tile). -`loop.sh` anchors on `v_wmma` by default and takes the SMALLEST backward branch containing every -anchor -- a plain largest-loop search finds the epilogue, which is a long unrolled store chain. +`res.sh` prints mangled names; the substring `dis.sh` takes picks one template instantiation, and +the parameter order is in the kernel's declaration (`gemm_fp8a8_kernel` is +``, so `ILb1ELb0ELj8ELj1ELj8ELj64ELb0E` is the prefill tile). +`loop.sh` anchors on `v_wmma` by default and takes the smallest backward branch containing every +anchor, because a largest-loop search finds the epilogue, a long unrolled store chain. -## The tools +## Tools | tool | what it answers | |---|---| -| `co.sh` | extracts the gfx1201 code object out of one built `.hip.o`; everything else reads that | -| `dis.sh` | disassembles ONE template instantiation out of one translation unit | +| `co.sh` | extracts the gfx1201 code object from one built `.hip.o`; the other scripts read that | +| `dis.sh` | disassembles one template instantiation from one translation unit | | `loop.sh` | isolates the working loop of that disassembly and classifies its body by instruction class | | `res.sh` | one row per device kernel in a build tree: VGPRs, SGPRs, LDS, scratch, spills, waves a SIMD, workgroup size | | `waterfall.sh` | every kernel that indexes a VGPR array with an index the compiler could not prove uniform | | `trace.sh` | runs a command under `rocprofv3 --kernel-trace` and leaves a CSV | | `tsum.sh` | summarises that CSV over a steady-state window: where device time goes, per (kernel, grid) | -| `gaps.sh` | the other half -- where the device is IDLE, and which op it was waiting for | +| `gaps.sh` | where the device is idle, and which op it was waiting for | | `rskew.sh` | per-kernel device time on each agent, and the skew between ranks | | `isarate.hip` | what one instruction slot is worth on gfx1201 (below) | -| `graphrate.hip` | what a dispatch costs the HOST to submit, and what capturing a fixed sequence saves | +| `graphrate.hip` | what a dispatch costs the host to submit, and what capturing a fixed sequence saves | | `launchreg.hip` + `launchreg_lib.hip` | whether a launch costs more when the module registers more kernels, and what crossing into a `.so` costs | | `blockcopy.hip` | contiguous versus scattered device-to-host copy, at KV-block granularity | -Each script's own header states its traps and how to read its output. The microbenchmarks are built -by hand; the command line is in each file's header, and `build_launchreg.sh` builds the two-object -pair the registration test needs. +Each script's header states its traps and how to read its output. The microbenchmarks are built by +hand: `clang++ -x hip -O3 -std=c++17 --offload-arch=gfx1201 .hip -o ` for `isarate`, +`graphrate` and `blockcopy`, and `build_launchreg.sh` for the two-object launchreg pair. -## What an instruction slot is worth on gfx1201 +## Instruction slot cost on gfx1201 -`isarate.hip` runs each instruction back to back in eight independent chains, so nothing stalls but -issue. The ratio it reports is clock-independent, which is why it reads no clock. +`isarate.hip` runs each instruction back to back in eight independent chains, so nothing stalls +but issue. It reports a ratio, which is clock-independent, so it reads no clock. -**One `v_wmma_f32_16x16x16_fp8_fp8` costs about 12.9 plain VALU issue slots**, and that does not -change when 36 KiB of LDS holds occupancy down to what a real prefill tile gets (at that occupancy -it measures nearer 11.6, for a peak of about 434 TFLOP/s). So a kernel's ceiling is +One `v_wmma_f32_16x16x16_fp8_fp8` costs about 12.9 plain VALU issue slots, and this holds with +36 KiB of LDS limiting occupancy to what a real prefill tile gets (there it measures nearer 11.6, +for a peak of about 434 TFLOP/s). A kernel's ceiling is therefore TFLOP/s = 434 * wmma_slots / (wmma_slots + other_instructions_issued) -with `wmma_slots = 12.9 * (wmma count)`, both counts per loop iteration out of `loop.sh`. +with `wmma_slots = 12.9 * (wmma count)`, both counts per loop iteration from `loop.sh`. -**It is a CEILING and not a prediction**, and the difference matters: a kernel cannot beat it, and a -kernel far under it is under it for some other reason that then has to be found. Issue is frequently -not the binding constraint. Cutting a kernel's non-WMMA instruction count by more than half can make -it SLOWER, because the removed work was covering memory and LDS latency and its removal raises -register pressure; and a memory-bound kernel moves by about a percent under the same cut. Use the -model to rule a lever out, not to predict a gain. +This is a ceiling, not a prediction. A kernel cannot beat it, and a kernel far below it is held +back by something else. Issue is often not the binding constraint: cutting a kernel's non-WMMA +instruction count by more than half can make it slower, because the removed work was covering +memory and LDS latency and its removal raises register pressure, and a memory-bound kernel moves by +about a percent under the same cut. Use the model to rule a lever out, not to predict a gain. -gfx1201 has **no dense 16x16x32 fp8 WMMA** -- `llvm-mc -mcpu=gfx1201` rejects it. The only 32-deep -fp8 form is `v_swmmac_f32_16x16x32_fp8_fp8`, which is the 2:4 sparse one. The GEMMs here are already -on the widest dense op that exists. +gfx1201 has no dense 16x16x32 fp8 WMMA (`llvm-mc -mcpu=gfx1201` rejects it). The only 32-deep fp8 +form is `v_swmmac_f32_16x16x32_fp8_fp8`, the 2:4 sparse one, so the GEMMs here already use the +widest dense op there is. -## The profiler: what works and what does not +## The profiler -`rocprofv3 --pmc` does not work on this platform. Any counter set, any kernel filter, on this tree -or on `isarate` alone: it collects, then hangs in `queue.cpp:939 Timeout while waiting for queue -sync: 1 kernels still active` and aborts on SIGABRT. **There are no hardware counters**, so the -dynamic instruction count is not directly observable -- `loop.sh` plus knowing which blocks are +`rocprofv3 --pmc` does not work on this platform. With any counter set and any kernel filter, on +this tree or on `isarate` alone, it collects, then hangs in `queue.cpp:939 Timeout while waiting +for queue sync: 1 kernels still active` and aborts on SIGABRT. There are no hardware counters, so +the dynamic instruction count is not directly observable; `loop.sh` plus knowing which blocks are predicated is how to get it. -`--kernel-trace` works, unmasked. The abort that names an unsupported agent +`--kernel-trace` works without masking any device. The abort that names an unsupported agent rocprofiler_iterate_agent_supported_counters failed for agent 3 (gfx1036) :: Agent HW architecture is not supported, no counter metrics found. -is **counter** enumeration and appears only under `--pmc`. It names a display GPU integrated on the -CPU, which has no counter support; masking it does not make `--pmc` work, and `--kernel-trace` never -needed it masked. `trace.sh` sets `ROCR_VISIBLE_DEVICES=0,1` only to pin the agent set and keep that -line out of the log. +comes from counter enumeration and appears only under `--pmc`. It names an integrated display GPU, +which has no counter support; masking it does not make `--pmc` work. `trace.sh` sets +`ROCR_VISIBLE_DEVICES=0,1` when it is unset, only to pin the agent set and keep that line out of +the log. It runs `$ROCM/bin/rocprofv3`, with `ROCM` defaulting to `/opt/rocm`. -`rocprofv3` is not on `PATH`; it is `/opt/rocm/bin/rocprofv3`. - -**A killed `rocprofv3` leaves a zombie that outlives its own `timeout`.** The hang is in -finalisation, after the alarm has fired, so the child ignores the timeout and sits in queue-sync -indefinitely. It does not hold CUs, so it does not poison a timing measurement -- but it does hold -VRAM, which makes the *next* tool report allocation failures that read like miscompiled kernels. -Always follow a `--pmc` attempt with `pkill -9 -f rocprofv3`; `trace.sh` does this itself. +**A killed `rocprofv3` can outlive its own `timeout`.** The hang is in finalisation, after the +alarm has fired, so the child ignores the timeout and waits in queue sync indefinitely. It holds no +CUs, so it does not disturb a timing, but it holds VRAM, so the next tool reports allocation +failures that look like miscompiled kernels. Follow a `--pmc` attempt with `pkill -9 -f rocprofv3`; +`trace.sh` does this itself. ### Reading a trace -* Tracing costs about 2 us per dispatch per RANK. The ranks are separate host threads and inflate in - parallel, so per-rank dispatches are what count, not the total. -* Kernel **durations** are hardware timestamps and do not move under tracing. The **gaps** absorb the - whole interception cost, so busy time is real and idle time is an upper bound. `tsum.sh` does that - subtraction and prints both. -* Generated text does not change under tracing, so a traced run can be pointed at a real serving +* Tracing costs about 2 us per dispatch per rank. The ranks are separate host threads and slow down + in parallel, so per-rank dispatch counts are what matter, not the total. +* Kernel durations are hardware timestamps and do not change under tracing. The gaps absorb the + whole interception cost, so busy time is real and idle time is an upper bound. `tsum.sh` does + that subtraction and prints both. +* Generated text does not change under tracing, so a traced run can use a real serving configuration rather than a proxy. -* **Busy is not utilisation, and this is the easiest number here to misread.** A dispatch counts as - busy if it is resident at all, so a 5 us kernel holding 1 of 64 CUs reads exactly like a GEMM - saturating the card. "96% busy" says the step is almost never *waiting* for a launch. It says - nothing about occupancy -- for that, read the blocks column, where anything under ~64 cannot fill - the device however long it runs. -* **A trace can go quiet and still look complete.** A run that idles before its workload records the - startup and nothing else, and the CSV is well formed either way. Send the workload the moment +* Busy is not utilisation. A dispatch counts as busy if it is resident at all, so a 5 us kernel on + 1 of 64 CUs reads the same as a GEMM saturating the card. "96% busy" says the step is almost never + waiting for a launch, nothing about occupancy; for that, read the blocks column, where anything + under ~64 cannot fill the device however long it runs. +* A trace can go quiet and still look complete. A run that idles before its workload records the + startup and nothing else, and the CSV is well formed either way. Send the workload as soon as health answers, keep the run short, and check `dispatches/step` in `tsum.sh`'s header against what - the model should issue before believing any table built from it. + the model should issue before trusting any table built from it. -## What the instruments say in general +## General results -Two results recur often enough to be worth stating up front, because they decide which levers are -worth pulling at all. +Two results recur and decide which levers are worth pulling. -**Every dispatch costs a few microseconds before it does anything.** Across the shapes a decode step -asks the narrow fp8 GEMM for, the time is not six different rates but one line, +**Every dispatch has a fixed cost of a few microseconds.** Across the shapes a decode step asks of +the narrow fp8 GEMM, the time follows one line, t = fixed + bytes / achievable_stream_rate with a fixed term of roughly 4.5 us and a stream rate near the card's achievable bandwidth. The same -fixed cost shows on every small op -- rmsnorm, quant_act, add, gated_quant -- whatever it moves. So -a "slow" small shape is usually a fixed cost failing to amortise, not a kernel with bandwidth left -in it, and **fewer kernels** is the only lever that reaches it. +fixed cost shows on every small op (rmsnorm, quant_act, add, gated_quant) whatever it moves. A +"slow" small shape is usually a fixed cost that does not amortise, not a kernel with bandwidth left, +and fewer kernels is the only lever that reaches it. -**Most of the weight-streaming kernels are at the memory wall.** A narrow GEMM whose K loop issues a -few hundred instructions per few kilobytes of weight per wave has roughly four times more issue -capacity than the card has bandwidth, and measures at the achievable stream rate. Assembly-level -work on such a kernel is not worth doing; confirm the reading with `loop.sh` before spending any. +**Most weight-streaming kernels are at the memory wall.** A narrow GEMM whose K loop issues a few +hundred instructions per few kilobytes of weight per wave has about four times more issue capacity +than the card has bandwidth, and runs at the achievable stream rate. Assembly-level work on such a +kernel does not pay; confirm with `loop.sh` before starting. -**Read the kernel's own header before proposing anything about it.** Each hot kernel's source -carries its own ablations, sweeps and rejected arms with the reason each was rejected, and the -answer to most assembly-level ideas is already recorded there. +**Read a kernel's own header before proposing changes to it.** Each hot kernel's source records +its ablations, sweeps and rejected variants with the reason for each, and most assembly-level ideas +are already answered there. diff --git a/libr4d/isa/blockcopy.hip b/libr4d/isa/blockcopy.hip index 41541f6b..cf17499a 100644 --- a/libr4d/isa/blockcopy.hip +++ b/libr4d/isa/blockcopy.hip @@ -1,13 +1,7 @@ -// WHAT A SCATTERED KV EVICTION COSTS. -// -// Pricing a host-tiered prefix cache from a bulk device-to-host bandwidth figure assumes the -// context moves as ONE transfer. It does not: the prefix cache is block-granular, the blocks are -// scattered through the paged pool, and a long context is many thousands of them. A scattered copy -// is a different machine from a contiguous one, and any such estimate rests on which one it is. -// -// So: one contiguous copy of N*B bytes, against N separate copies of B bytes from scattered -// offsets, against N copies issued back-to-back on one stream (the batched form a real eviction -// would use). +// Cost of a scattered KV eviction. The prefix cache is block-granular and its blocks are scattered +// through the paged pool, so a bulk device-to-host bandwidth figure does not price it. Compares one +// contiguous copy of N*B bytes, N copies of B bytes from scattered offsets with a sync after each, +// and the same N copies issued back-to-back on one stream (the batched form an eviction would use). // // clang++ -x hip -O3 -std=c++17 --offload-arch=gfx1201 blockcopy.hip -o blockcopy #include @@ -35,8 +29,7 @@ int main(int argc, char** argv) { if (hipHostMalloc(&host, (size_t)bytes) != hipSuccess) { std::printf("hipHostMalloc failed\n"); return 1; } hipStream_t s; hipStreamCreate(&s); - /* SCATTERED, not sequential: a real pool hands out blocks in whatever order they were freed, - * so the eviction walks them in an order uncorrelated with address. */ + /* Shuffled order: a pool hands out blocks in free order, uncorrelated with address. */ std::vector order((size_t)n); for (long long i = 0; i < n; ++i) order[(size_t)i] = i; unsigned seed = 12345; diff --git a/libr4d/isa/graphrate.hip b/libr4d/isa/graphrate.hip index 09342980..8633644a 100644 --- a/libr4d/isa/graphrate.hip +++ b/libr4d/isa/graphrate.hip @@ -1,30 +1,25 @@ -// WHAT A DISPATCH COSTS THE HOST TO SUBMIT, and what capturing a fixed sequence saves. +// Host cost of submitting a dispatch, and what capturing a fixed sequence saves. // -// Capture is usually priced against the DEVICE-side gap between dependent kernels, which on this -// part is well under a microsecond and not worth chasing. That is the wrong question for the MTP -// draft loop. There the HOST is on the critical path: every pass embeds the token the previous -// pass sampled, so nothing overlaps the submit, and the device sits idle for the whole of it. The -// trunk never pays that, because it runs well over a thousand dispatches ahead of the device. +// The device-side gap between dependent kernels is well under a microsecond on this part. In the +// MTP draft loop the host is on the critical path instead: each pass embeds the token the previous +// pass sampled, so nothing overlaps the submit and the device idles through it. The trunk runs +// over a thousand dispatches ahead of the device and never pays this. So this times the submit +// loop itself, separate from the sync. // -// So this measures the HOST half: the wall time of the submit loop itself, separated from the sync. +// Every arm runs once per iteration in one loop: clock and scheduler drift between runs exceeds +// the differences being measured. // -// EVERY ARM RUNS ONCE PER ITERATION, IN ONE LOOP. Clock and scheduler state drift between runs by -// more than the differences being measured, so arms taken in sequence are not comparable to each -// other; sharing one loop is what makes them comparable. -// -// individual 45 separate hipLaunchKernelGGL, one per op, as an uncaptured pass issues them. -// graph one captured graph replayed. The floor, and unreachable: the pass is not static. +// individual 45 separate hipLaunchKernelGGL, as an uncaptured pass issues them. +// graph one captured graph replayed. The floor; unreachable, since the pass is not static. // graph+Kset replay after rewriting K nodes. About ten of the draft pass's 45 issues move an -// operand pointer every step, and three of those (qsa_work, qsa_score, qsa_select) -// also move a SHAPE, because the QSA extents grow with context and no arena -// discipline makes them stand still. This is the shape a real implementation has. -// graph+Kg+s the same with the params READ BACK from the node first, because the engine holds -// no launch geometry of its own -- the shim marshals its own kernel arguments and -// the runtime never sees the signature. If this costs what Kset costs, that -// ignorance is free and the design needs no ABI change. +// operand pointer every step, and three (qsa_work, qsa_score, qsa_select) also +// move a shape, because the QSA extents grow with context. +// graph+Kg+s the same, reading the params back from the node first, because the engine holds +// no launch geometry (the shim marshals its own arguments). If this costs what +// Kset costs, no ABI change is needed. // recap+updat re-issue the whole pass under capture and hipGraphExecUpdate the exec. Needs no -// knowledge of which arg slot moved at all, so it is the smallest engine change -- -// if appending a node is cheap enough to pay for itself. +// knowledge of which arg moved, so it is the smallest engine change, if appending +// nodes is cheap enough. // // clang++ -x hip -O3 -std=c++17 --offload-arch=gfx1201 graphrate.hip -o graphrate // ./graphrate 45 300 10 @@ -38,11 +33,9 @@ __global__ void tiny(float* p) { if (threadIdx.x == 0) p[blockIdx.x] = 1.0f; } -/* THE SAME KERNEL WITH A REAL ARGUMENT LIST. An engine issue costs several times what `tiny` - * above submits in, and the difference has two possible homes: HIP marshalling more arguments, or - * the plugin shim's own prologue (band checks, grid derivation, the switch that picks a template - * instantiation). They call for completely different work, so they have to be told apart. This - * signature is r4d_qsa_score_bf16's, argument for argument: six pointers and nine scalars. */ +/* `tiny` with a real argument list, to separate HIP's argument marshalling from the shim's own + * prologue (band checks, grid derivation, template switch) as the cause of an engine issue costing + * several times `tiny`. The signature matches r4d_qsa_score_bf16: six pointers, nine scalars. */ __global__ void fat(const float* q, const float* bk, const int* bt, const int* cu, const int* nc, float* out, int n, int heads, int nb, int nseq, int bpw, int q_ld, int bk_ld, int bt_ld, int out_ld) { @@ -50,12 +43,10 @@ __global__ void fat(const float* q, const float* bk, const int* bt, const int* c out[blockIdx.x] = (float)(n + heads + nb + nseq + bpw + q_ld + bk_ld + bt_ld + out_ld); } -/* A kernel SLOW ENOUGH TO BACK THE QUEUE UP. Every arm above syncs each iteration, so the command - * ring is always empty and a submit only ever costs what the runtime spends writing it. A serving - * engine is not in that state: the host runs far ahead of a device that is nearly always busy, and - * a submit into a FULL ring waits for the device to retire a slot. If backpressure is what an - * engine's launch cost actually is, then the shim prologue is not the story and no amount of - * host-side tidying moves it. */ +/* Slow enough to back the queue up. The other arms sync each iteration, so the command ring is + * empty and a submit costs only the runtime's write. A serving engine runs far ahead of a busy + * device, and a submit into a full ring waits for the device to retire a slot; if that dominates, + * host-side shim tidying cannot help. */ __global__ void slow(float* p, int n) { float a = (float)threadIdx.x; for (int i = 0; i < n; ++i) a = fmaf(a, 1.0000001f, 1.0f); @@ -67,7 +58,7 @@ static double us_since(clk::time_point a, clk::time_point b) { return std::chrono::duration(b - a).count(); } -/* The median, not the mean: one descheduled iteration is worth thirty clean ones to a mean. */ +/* Median, not mean: a single descheduled iteration skews a mean. */ static double med(std::vector& v) { if (v.empty()) return 0.0; std::sort(v.begin(), v.end()); @@ -113,9 +104,8 @@ int main(int argc, char** argv) { std::vector a_ind, a_fat, a_err, a_gra, a_set, a_gs, a_rec, a_cap, a_upd; a_ind.reserve(iters); - /* Warm the clocks, the runtime's lazy module load, and every path below. The cards - * idle-suspend, so a timed loop that starts cold reads the governor ramping rather than the - * steady-state rate -- worth most of a factor of two. */ + /* Warm the clocks, the runtime's lazy module load and every path below. The cards + * idle-suspend, and a cold start times the clock governor ramping (up to ~2x). */ for (int w = 0; w < 400; ++w) { for (int i = 0; i < N; ++i) hipLaunchKernelGGL(tiny, dim3(1), dim3(64), 0, s, d); for (int i = 0; i < N; ++i) @@ -134,10 +124,9 @@ int main(int argc, char** argv) { hipGraphDestroy(g2); } - /* FOUR GRAPHS OVER THE SAME 45 NODES, because that is the shape the real pass has: three - * all-reduces and a gather cut it into segments, and a graph launch costs about the same - * whatever it contains. Whether that fixed cost, paid once per segment, eats the whole saving - * is what decides whether capturing the pass pays at all. */ + /* Four graphs over the same 45 nodes: three all-reduces and a gather cut the real pass into + * segments. A graph launch has a roughly fixed cost whatever it contains, paid per segment, + * and that may eat the saving. */ hipGraphExec_t gef[4] = {nullptr, nullptr, nullptr, nullptr}; { const int seg[4] = {3, 17, 13, 12}; @@ -161,10 +150,8 @@ int main(int argc, char** argv) { hipStreamSynchronize(s); a_ind.push_back(us_since(t0, t1)); - /* ---- fifteen arguments, with the error check libr4d puts after every launch. There are - * dozens of those call sites across the library and a single op's path can make several of - * them. If hipGetLastError is a cheap TLS read this arm sits on top of the one above; if - * it is not, it is a tax on every dispatch in the library. */ + /* ---- fifteen arguments plus the hipGetLastError check libr4d makes after every launch; + * one op's path can make several. Prices that check against the plain 15-argument arm. */ t0 = clk::now(); for (int i = 0; i < N; ++i) { hipLaunchKernelGGL(fat, dim3(1), dim3(64), 0, s, d, d, (const int*)d, @@ -175,10 +162,9 @@ int main(int argc, char** argv) { hipStreamSynchronize(s); a_err.push_back(us_since(t0, t1)); - /* ---- fifteen arguments through hipLaunchKernel + kernelParams: EXACTLY what a shim's - * R4D_EMIT does on its LAUNCH path. Every ordinary dispatch pays this while a graph only - * pays back on replay, so if this sits above `fat` the kernelParams path costs the normal - * path more than it can save the captured one. */ + /* ---- fifteen arguments through hipLaunchKernel + kernelParams, as R4D_EMIT's launch path + * does. Every ordinary dispatch pays this while a graph only pays back on replay, so if + * it costs more than `fat` it loses more on the normal path than it saves on capture. */ t0 = clk::now(); for (int i = 0; i < N; ++i) { void* pv[15]; @@ -202,7 +188,7 @@ int main(int argc, char** argv) { hipStreamSynchronize(s); a_fat.push_back(us_since(t0, t1)); - /* ---- the same 45 nodes as FOUR graphs, plus the five dispatches the cuts leave behind */ + /* ---- the same 45 nodes as four graphs, plus the five dispatches the cuts leave behind */ t0 = clk::now(); for (int q = 0; q < 4; ++q) hipGraphLaunch(gef[q], s); for (int i = 0; i < 5; ++i) hipLaunchKernelGGL(tiny, dim3(1), dim3(64), 0, s, d); @@ -258,15 +244,14 @@ int main(int argc, char** argv) { a_rec.push_back(us_since(t0, t1)); } - /* ---- SUBMIT UNDER BACKPRESSURE. The same launch, but the device cannot keep up, so the ring - * fills and stays full. Reported per dispatch against the empty-ring arms above. */ + /* ---- Submit under backpressure: the device cannot keep up, so the ring stays full. */ std::vector a_bp; for (int w = 0; w < 20; ++w) { for (int i = 0; i < N; ++i) hipLaunchKernelGGL(slow, dim3(8), dim3(256), 0, s, d, 4000); hipStreamSynchronize(s); } for (int it = 0; it < iters; ++it) { - /* Do NOT sync: let the queue stay deep across iterations, the way a decode step does. */ + /* No sync: the queue stays deep across iterations, as in a decode step. */ const auto t0 = clk::now(); for (int i = 0; i < N; ++i) hipLaunchKernelGGL(slow, dim3(8), dim3(256), 0, s, d, 4000); const auto t1 = clk::now(); diff --git a/libr4d/isa/isarate.hip b/libr4d/isa/isarate.hip index 579541ca..b833ba55 100644 --- a/libr4d/isa/isarate.hip +++ b/libr4d/isa/isarate.hip @@ -1,14 +1,11 @@ -// What one instruction slot is worth on gfx1201, so that an instruction COUNT taken out of a -// disassembly can be turned into a time. +// Issue cost of one instruction slot on gfx1201, to turn an instruction count from a disassembly +// into a time. A staged GEMM K tile is a few dozen v_wmma among several hundred other +// instructions, so the wmma-to-VALU cost ratio decides whether trimming the rest pays; no public +// table gives it for this part. Each instruction runs in independent back-to-back chains (issue +// bound) and the rate is reported. The ratio is clock-independent, so no clock is read. // -// A GEMM's staged K tile is a few dozen v_wmma inside several hundred other instructions, so -// whether trimming the shell is worth anything depends entirely on what a wmma costs relative to a -// plain VALU op -- and that ratio is not in any public table for this part. So measure it: run each -// instruction back to back in independent chains (nothing to stall on but issue) and report the -// rate. The RATIO is what matters and it is clock-independent, which is why no clock is read here. -// -// Occupancy is a parameter because a real tile kernel runs at 2 waves a SIMD (36864 B of LDS) and a -// microbenchmark at 8 would answer a different question. +// LDS is a parameter because occupancy matters: a tile kernel runs at 2 waves a SIMD (36864 B of +// LDS), and 8 waves would answer a different question. #include #include #include @@ -46,8 +43,7 @@ __global__ __launch_bounds__(256) void valu_rate(float* out, int iters) { float x0 = threadIdx.x, x1 = x0 + 1, x2 = x0 + 2, x3 = x0 + 3; float x4 = x0 + 4, x5 = x0 + 5, x6 = x0 + 6, x7 = x0 + 7; const float k = 1.0000001f; - // Eight independent chains, eight ops an iteration -- the same shape as the wmma loop so the - // two numbers differ only in the instruction being issued. + // Same shape as the wmma loop (eight independent chains) so only the instruction differs. for (int i = 0; i < iters; ++i) { x0 *= k; x1 *= k; x2 *= k; x3 *= k; x4 *= k; x5 *= k; x6 *= k; x7 *= k; } diff --git a/libr4d/isa/launchreg.hip b/libr4d/isa/launchreg.hip index 5fab5f24..bd9cc772 100644 --- a/libr4d/isa/launchreg.hip +++ b/libr4d/isa/launchreg.hip @@ -1,17 +1,14 @@ -// DOES A LAUNCH COST MORE WHEN THE MODULE REGISTERS MORE KERNELS, and does crossing into a shared -// object cost anything at all? +// Does a launch cost more when the module registers more kernels, and does crossing into a shared +// object cost anything? // -// The engine issues a launch for roughly twice what the same shape costs in a self-contained -// binary, and the excess is roughly CONSTANT across kernels of very different shapes -- the -// signature of a fixed per-issue tax rather than of anything a particular shim does. The error -// check after every launch, a full command ring and the argument count together do not account for -// it. +// An engine launch costs roughly twice what the same shape costs in a self-contained binary, and +// the excess is roughly constant across kernel shapes: a fixed per-issue tax. The per-launch error +// check, a full command ring and the argument count do not account for it. // -// The structural difference this isolates is the MODULE. libr4d is a .so holding every template -// instantiation of every kernel, entered through a function pointer; a self-contained harness has -// a handful of kernels compiled into the binary that launches them. HIP resolves a launch by -// looking the host stub up in the table __hipRegisterFunction fills, so a bigger table is a -// plausible tax -- and if it is the tax, the lever is fewer instantiations, not tidier shims. +// This isolates the module. libr4d is a .so holding every kernel instantiation, entered through a +// function pointer; a self-contained harness compiles a handful of kernels into the binary. HIP +// resolves a launch by looking the host stub up in the table __hipRegisterFunction fills, so a +// bigger table is a plausible tax, and then the lever is fewer instantiations. // // see build_launchreg.sh #include @@ -65,13 +62,13 @@ int main(int argc, char** argv) { L->fn = (LaunchFn)dlsym(L->h, "lr_launch"); L->dfn = (DistinctFn)dlsym(L->h, "lr_launch_distinct"); CountFn c = (CountFn)dlsym(L->h, "lr_registered"); - if (!L->fn || !c) { std::printf("dlsym %s\n", L->path); return 1; } + if (!L->fn || !L->dfn || !c) { std::printf("dlsym %s\n", L->path); return 1; } L->nreg = c(); } std::printf("%d launches a sequence, %d iterations, medians\n", N, iters); std::printf(" few = %d instantiations, many = %d\n", few.nreg, many.nreg); - /* Warm every path: clocks, lazy module load for BOTH objects, and the code itself. */ + /* Warm every path: clocks, lazy module load for both objects, and the code itself. */ for (int w = 0; w < 400; ++w) { for (int i = 0; i < N; ++i) hipLaunchKernelGGL(local_k, dim3(1), dim3(64), 0, s, d); for (int i = 0; i < N; ++i) few.fn(d, s); @@ -107,12 +104,10 @@ int main(int argc, char** argv) { a_dist.push_back(us_since(t0, t1)); } - /* ---- A SECOND SUBMITTING THREAD. The last structural difference between this harness and the - * engine: --tp 2 runs two rank threads, each issuing onto its own stream, and every arm above - * is single-threaded. If HIP takes a process-wide lock on the submit path then a launch costs - * what it costs plus whatever the other rank is holding -- which would be a fixed tax, present - * on every kernel however small, which is exactly the shape the excess has. The second - * thread runs the identical loop on its OWN stream and is not measured; only rank 0 is. */ + /* ---- A second submitting thread. --tp 2 runs two rank threads, each issuing onto its own + * stream. A process-wide lock on HIP's submit path would add a fixed tax to every launch, + * the same shape as the excess. The second thread runs the same loop on its own stream and + * is not measured; only rank 0 is. */ hipStream_t s2; if (hipStreamCreate(&s2) != hipSuccess) { std::printf("second stream\n"); return 1; } std::atomic run{true}; diff --git a/libr4d/isa/launchreg_lib.hip b/libr4d/isa/launchreg_lib.hip index cec20ca6..7f37d656 100644 --- a/libr4d/isa/launchreg_lib.hip +++ b/libr4d/isa/launchreg_lib.hip @@ -1,16 +1,13 @@ -// THE LIBRARY HALF of the registered-kernel test. Built twice, at -DNK=2 and -DNK=512, and -// dlopen'd -- because that is libr4d's actual shape: a shared object holding every template -// instantiation of every kernel, entered through a function pointer. -// -// Both builds launch THE SAME kernel, k<0>, with the same arguments. The only difference is how -// many other instantiations sit in the module beside it. +// Library half of the registered-kernel test, built at -DNK=2 and -DNK=512 and dlopen'd, which +// matches libr4d's shape: one shared object holding every kernel instantiation, entered through a +// function pointer. Both builds launch the same kernel k<0> with the same arguments; only the +// number of other instantiations in the module differs. #include template __global__ void k(float* p) { if (threadIdx.x == 0) p[blockIdx.x] = (float)I; } -/* The table exists to keep the instantiations alive. Without a use, the compiler drops every k - * that is never launched and both builds register one kernel. */ +/* Keeps the instantiations alive; without a use the compiler drops every unlaunched k. */ static const void* g_tab[NK]; template @@ -22,11 +19,9 @@ struct Reg<0> { static void go() { g_tab[0] = (const void*)k<0>; } }; -/* A THUNK PER INSTANTIATION. The arms above launch one kernel over and over, which is the one - * thing a decode step never does: it issues forty-five DIFFERENT kernels, each through its own - * shim, each with its own argument buffer and its own host stub. Everything the tight loop keeps - * in L1 -- the code, the stub, the args -- is cold on every one of those. This makes that - * difference, and only that difference, measurable. */ +/* One thunk per instantiation. A decode step issues ~45 different kernels, each with its + * own shim, argument buffer and host stub, so code, stub and args are cold on each launch; a + * loop over one kernel keeps them in L1. lr_launch_distinct measures that difference. */ typedef void (*Thunk)(float*, hipStream_t); template static void thunk(float* p, hipStream_t st) { diff --git a/libr4d/r4d.h b/libr4d/r4d.h index 292c4984..9c7880de 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -1,47 +1,39 @@ -// R4D -- the RDNA4 (gfx1201) kernel library: attention, gated delta net, all-reduce and a skinny -// bf16 GEMM, compiled into one shared object. Plain C ABI: every entry point takes raw device -// pointers and a stream, so a consumer needs no C++ ABI coupling to call one. Nothing on the -// launch paths allocates or synchronises, so any of them can be recorded into a HIP graph. +// R4D -- the RDNA4 (gfx1201) kernel library: attention, gated delta net, all-reduce, GEMMs and +// the small model ops, compiled into one shared object. Plain C ABI: every entry point takes raw +// device pointers and a stream, so a consumer needs no C++ ABI coupling. Nothing on the launch +// paths allocates or synchronises, so any of them can be recorded into a HIP graph. // -// NAMING. An entry point is +// Naming. An entry point is // // r4d___ // -// and the geometry suffix is not decoration: these are specialised kernels, and every dimension in -// the name is a compile-time constant that the entry point REJECTS a mismatch on rather than -// running. `attn_decode_h256_gqa6_fp8kv` runs for head_dim 256 with 6 queries per KV head and an -// fp8-e4m3 paged cache, and for nothing else. A model with a different head size needs a new -// instantiation, which will sit beside this one under its own name; nothing has to be renamed to -// make room for it. Dimensions that are fixed for the whole library, and so discriminate nothing -// between entry points, stay out of the names and are reported by r4d_*_dims() and the kernel -// registry instead: the paged block size (16), the query dtype (bf16 everywhere -- see -// r4d_attn_paged_h256_gqa6.hip) and the target architecture. +// Every dimension in the geometry suffix is a compile-time constant, and the entry point rejects a +// mismatch instead of running. `attn_decode_h256_gqa6_fp8kv` serves head_dim 256, 6 queries per KV +// head and an fp8-e4m3 paged cache, nothing else; another head size gets its own instantiation +// beside it. Dimensions fixed for the whole library stay out of the names and are reported by +// r4d_*_dims() and the kernel registry: the paged block size (16), the query dtype (bf16 +// everywhere, see r4d_attn_paged_h256_gqa6.hip) and the target architecture. // -// SOURCE FILES CARRY THE SAME NAME. A translation unit is named for the entry point it provides, -// geometry included -- r4d_gdn_kkt_solve_k128_c64_bf16.hip holds r4d_gdn_kkt_solve_k128_c64_bf16 -// and nothing else. Where one unit provides a family that differs only in a suffix, the file name -// stops at the shared part: r4d_gdn_conv_w4_h128_bf16.hip provides the prep and update pair, and -// r4d_attn_paged_h256_gqa6.hip provides all four paged variants by including the two kernel -// templates that sit beside it under their own names. Only the shared machinery -- r4d_common.h, -// r4d_dt16.h, r4d_gdn_wmma.h -- is named for what it is rather than for a kernel, because it -// provides none. +// Source files carry the entry point's name, geometry included: +// r4d_gdn_kkt_solve_k128_c64_bf16.hip holds r4d_gdn_kkt_solve_k128_c64_bf16. A unit providing a +// family that differs only in a suffix stops at the shared part (r4d_gdn_conv_w4_h128_bf16.hip, +// r4d_attn_paged_h256_gqa6.hip). Shared machinery that provides no kernel -- r4d_common.h, +// r4d_dt16.h, r4d_gdn_wmma.h -- is named for what it is. // -// Where a shape is unsupported the attention and GDN entry points return a negative code; the -// all-reduce and GEMM entry points throw std::runtime_error instead, and the plugin shim in front -// of them wraps the call in R4D_TRY, which turns the throw into an ABI status code. Nothing throws -// across the .so boundary. +// On an unsupported shape the attention and GDN entry points return a negative code; the +// all-reduce and GEMM entry points throw std::runtime_error, which the plugin shim's R4D_TRY turns +// into an ABI status code. Nothing throws across the .so boundary. #pragma once #include -// Library version. The git tag it was built from is expected to match -- which is what lets a -// consumer assert it linked the sources it pinned rather than whatever a stale clone happened to -// hold. +// Library version; expected to match the git tag it was built from, so a consumer can assert it +// linked the sources it pinned. #define R4D_VERSION "0.5.0" struct R4DArgs { const void* q; // (num_seqs*q_len, q_heads, head_dim) bf16 const void* kv; // (num_blocks, kv_heads, block_size, 2*head_dim) fp8 e4m3 or bf16 - // strides below are in ELEMENTS of that dtype; K then V per slot + // strides below are in elements of that dtype; K then V per slot const int* block_table; // (num_seqs, max_blocks) int32 const int* seqused_k; // (num_seqs,) int32 void* out; // (total_q, q_heads, head_dim) bf16 @@ -59,29 +51,25 @@ struct R4DArgs { int causal; // 1 = key <= query; 0 = key < seq_len, window two-sided const void* causal_seq; // (num_seqs,) uint8 per-sequence flag, or null for `causal` - // ---- RAGGED BATCHES -------------------------------------------------------------------- - // `q_len` above is a SCALAR, so without these every sequence in a batch has to present the - // same query length. A serving scheduler does not: it mixes one sequence's prefill chunk with - // others' single decode rows in the same step deliberately, because a decode row costs nothing - // once the weights are being read anyway. The uniform form is the special case, not the rule. + // ---- Ragged batches -------------------------------------------------------------------- + // A serving step mixes one sequence's prefill chunk with other sequences' single decode rows, + // so query lengths differ per sequence. // - // `cu_q` is cu_seqlens: [num_seqs + 1] int32 on the DEVICE, cu_q[0] == 0, cu_q[num_seqs] == - // total_q, so sequence s owns query rows [cu_q[s], cu_q[s+1]) of the dense q and out blocks. - // Null means uniform: row r of sequence `seq` is row `seq * q_len + r`, and the launchers, the - // kernels and the scratch layout all reduce to exactly that arithmetic. + // `cu_q` is cu_seqlens: [num_seqs + 1] int32 on the device, cu_q[0] == 0, cu_q[num_seqs] == + // total_q; sequence s owns query rows [cu_q[s], cu_q[s+1]) of q and out. Null means uniform: + // row r of sequence `seq` is row `seq * q_len + r`. // - // `q_len` stays meaningful when cu_q is set: it is then the MAXIMUM query length in the batch, - // which is what sizes the grid and picks the decode kernel's wave count. `total_q` is the row - // count of q and out; it is host-side because the split-KV scratch has to be sized without - // reading device memory. Both are ignored when cu_q is null. + // With cu_q set, `q_len` is the maximum query length in the batch (it sizes the grid and picks + // the decode kernel's wave count) and `total_q` is the row count of q and out, host-side so the + // split-KV scratch can be sized without reading device memory. Both are ignored when cu_q is + // null. const int* cu_q; // (num_seqs+1,) int32 device, or null for a uniform q_len int total_q; // rows of q/out; ignored unless cu_q is set }; -// Rows of q and out in this batch. The split-KV scratch is laid out by dense query row rather than -// by (seq, q_len), so this is the row count both the host sizing hook and the device kernels index -// against, and it must give the same answer in both -- which is why total_q is carried alongside -// cu_q rather than read off the end of it. +// Rows of q and out. The split-KV scratch is laid out by dense query row, so the host sizing hook +// and the device kernels must agree on this count; hence total_q is carried rather than read off +// the end of cu_q. __host__ __device__ __forceinline__ int r4d_q_total(const R4DArgs& a) { return a.cu_q ? a.total_q : a.num_seqs * a.q_len; } @@ -96,39 +84,32 @@ int r4d_attn_prefill_h256_gqa6_fp8kv (const R4DArgs* a, hipStream_t stream); int r4d_attn_prefill_h256_gqa6_bf16kv(const R4DArgs* a, hipStream_t stream); int r4d_attn_decode_h256_gqa6_fp8kv (const R4DArgs* a, hipStream_t stream); int r4d_attn_decode_h256_gqa6_bf16kv (const R4DArgs* a, hipStream_t stream); -// The DFlash2 drafter's geometry: head_dim 128, 4 queries per KV head, sliding window. -// Decode only -- a query long enough to want the prefill kernel goes to the caller's -// fallback, which is what `r4d_attn_h128_gqa4_have_prefill()` reporting 0 tells it. +// The DFlash2 drafter's geometry: head_dim 128, 4 queries per KV head, sliding window. Decode +// only (q_len * gqa <= 64). int r4d_attn_decode_h128_gqa4_fp8kv (const R4DArgs* a, hipStream_t stream); int r4d_attn_decode_h128_gqa4_bf16kv (const R4DArgs* a, hipStream_t stream); long r4d_attn_decode_h128_gqa4_scratch_bytes(const R4DArgs* a); -// 0 means this build has no h128/gqa4 PREFILL kernel, so a caller that sees a query long -// enough to need one must route the whole batch to its fallback rather than this library. -int r4d_attn_h128_gqa4_have_prefill(void); // Bytes of split-KV partial buffer one decode launch of this shape needs. Independent of the cache // dtype: the partials are f16 either way. long r4d_attn_decode_h256_gqa6_scratch_bytes(const R4DArgs* a); - // The Gemma 4 dense sliding-window geometry: head_dim 256, 2 queries per KV head, sliding window. - // Both bands: the decode band (q_len*gqa <= 64, i.e. q_len <= 32) and the windowed prefill band - // (a prefill-length query, WIN on). The prefill leg is the same r4d_attn_prefill_kernel the - // h256/gqa6 dispatch instantiates, with the window bit turned on. - int r4d_attn_prefill_h256_gqa2_fp8kv (const R4DArgs* a, hipStream_t stream); - int r4d_attn_prefill_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t stream); - int r4d_attn_decode_h256_gqa2_fp8kv (const R4DArgs* a, hipStream_t stream); - int r4d_attn_decode_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t stream); - long r4d_attn_decode_h256_gqa2_scratch_bytes(const R4DArgs* a); -// The geometry the attention kernels above are compiled for, so a caller can test a model against -// it instead of discovering the mismatch at the first launch. +// The Gemma 4 dense sliding-window geometry: head_dim 256, 2 queries per KV head. Both bands: +// decode (q_len*gqa <= 64, i.e. q_len <= 32) and windowed prefill, which is the h256/gqa6 +// r4d_attn_prefill_kernel with the window bit on. +int r4d_attn_prefill_h256_gqa2_fp8kv (const R4DArgs* a, hipStream_t stream); +int r4d_attn_prefill_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t stream); +int r4d_attn_decode_h256_gqa2_fp8kv (const R4DArgs* a, hipStream_t stream); +int r4d_attn_decode_h256_gqa2_bf16kv (const R4DArgs* a, hipStream_t stream); +long r4d_attn_decode_h256_gqa2_scratch_bytes(const R4DArgs* a); +// The geometry the attention kernels above are compiled for, so a caller can check a model +// before the first launch. void r4d_attn_dims(int* head_dim, int* gqa, int* block_size, int* max_decode_rows); // ---- attention: vision encoder ------------------------------------------------------------- // Dense, non-causal, multi-head attention at the vision tower's head_dim of 72, bf16 throughout. -// Nothing is paged and nothing is quantised: q, k, v and o are [total_tokens, heads, 72] and -// contiguous, and cu_seqlens [num_seqs + 1] bounds one image (or one attention window) per entry, -// so a whole batch is ONE launch rather than a per-segment loop and a concatenate. `max_seqlen` is -// the host-side bound on those lengths and selects the query-block height; the kernel reads the -// device-side cu_seqlens itself. head_dim 72 is carried natively (5 k-tiles of 16, the last half -// structurally zero) rather than padded to 128. Returns -1 for any other head size. +// q, k, v and o are contiguous [total_tokens, heads, 72]; cu_seqlens [num_seqs + 1] bounds one +// image (or attention window) per entry, so a batch is one launch. `max_seqlen` is the host-side +// bound on those lengths and selects the query-block height. head_dim 72 is carried natively +// (5 k-tiles of 16, the last half zero), not padded to 128. Returns -1 for any other head size. int r4d_attn_vit_h72_bf16(const void* q, const void* k, const void* v, void* o, const void* cu_seqlens, int num_seqs, int max_seqlen, int heads, int head_dim, float scale, void* stream); @@ -140,23 +121,21 @@ int r4d_attn_vit_h72_strided_bf16(const void* q, const void* k, const void* v, int v_ld, int o_ld, void* stream); // ---- gated delta net ----------------------------------------------------------------------- -// One chunked scan over N variable-length sequences: the WY recompute, the recurrent state scan and -// the output in one kernel (FLA's recompute_w_u_fwd + chunk_gated_delta_rule_fwd_h + chunk_fwd_o). -// Layouts, all contiguous and bf16 unless stated: +// One chunked scan over N variable-length sequences: the WY recompute, the recurrent state scan +// and the output in one kernel (FLA's recompute_w_u_fwd + chunk_gated_delta_rule_fwd_h + +// chunk_fwd_o). Layouts, all contiguous and bf16 unless stated: // q,k [T, Hg, K] v,o [T, H, V] A [T, H, bt] g,beta [T, H] fp32 // h0,ht [N, H, V, K] fp32 cu [N+1] int32 -// K, V and bt are the compile-time 128/128/64 in the name; a mismatch returns -1 rather than -// running. Named for the algorithm, not the serving phase: this is the chunked scan, which is what -// prefill and chunked prefill both run. Decode uses the recurrent update, a different kernel. +// K, V and bt must be the compile-time 128/128/64 in the name; a mismatch returns -1. Prefill and +// chunked prefill run this; decode runs the recurrent update. int r4d_gdn_chunk_scan_k128_v128_c64_bf16( const void* q, const void* k, const void* v, const void* A, const void* g, const void* beta, const void* h0, void* o, void* ht, const void* cu, int N, int H, int Hg, int K, int V, int bt, float scale, int state_fp16, void* stream); -// The same scan against a SLOT-INDEXED state cache: `ssm_state_indices` is [N] and names the slot -// each batch row owns, and the two strides are the cache's own, in elements. The call above is -// this one with a null index and the packed [N, H, V, K] strides -- correct only while a slot -// equals its batch row, which stops being true the moment a slot is reused out of order. +// The same scan against a slot-indexed state cache: `ssm_state_indices` [N] names each batch +// row's slot, and the two strides are the cache's, in elements. The call above is this one with a +// null index and packed [N, H, V, K] strides, which is correct only while slot == batch row. int r4d_gdn_chunk_scan_k128_v128_c64_bf16_sidx( const void* q, const void* k, const void* v, const void* A, const void* g, const void* beta, const void* h0, void* o, void* ht, @@ -166,35 +145,32 @@ int r4d_gdn_chunk_scan_k128_v128_c64_bf16_sidx( float scale, int state_fp16, void* stream); void r4d_gdn_dims(int* head_k, int* head_v, int* chunk); -// The chunk preamble: A = (I + strict_lower(diag(beta) K K^T e^{g_i-g_j}))^-1 per chunk, which is -// FLA's chunk_scaled_dot_kkt_fwd followed by solve_tril with the fp32 gram in between never -// reaching HBM. k [T,Hg,K] bf16; beta, g [T,H] fp32 (g already summed along the chunk); -// A [T,H,64] bf16 out; cu [N+1] int32. Returns -1 for a geometry it was not compiled for. +// The chunk preamble: A = (I + strict_lower(diag(beta) K K^T e^{g_i-g_j}))^-1 per chunk, i.e. +// FLA's chunk_scaled_dot_kkt_fwd then solve_tril, with the fp32 gram kept out of HBM. +// k [T,Hg,K] bf16; beta, g [T,H] fp32 (g already summed along the chunk); A [T,H,64] bf16 out; +// cu [N+1] int32. Returns -1 for a geometry it was not compiled for. int r4d_gdn_kkt_solve_k128_c64_bf16(const void* k, const void* beta, const void* g, void* A, const void* cu, int N, int T, int H, int Hg, int K, int bt, void* stream); -// DFlash2's grouped dynamic depthwise convolution, fused into one pass. The reference builds it as -// ~6 full [T, H] elementwise passes plus a materialised [T, taps, num_groups, group] coefficient -// tensor, all consumed exactly once. delta is a SLICE of the [T, 2, taps, NG] kernel projection, so -// dpitch is 2*taps*NG; out must not alias x. block_size must be a power of two. +// DFlash2's grouped dynamic depthwise convolution in one pass (the reference uses ~6 elementwise +// passes and a materialised coefficient tensor). delta is a slice of the [T, 2, taps, NG] kernel +// projection, so dpitch is 2*taps*NG; out must not alias x. block_size must be a power of two. int r4d_dflash_conv_t2_g16_bf16( const void* x, const void* delta, const void* base, void* out, int T, int H, int dpitch, int NG, int taps, int group, int block_size, void* stream); -// DFlash2's candidate selector: the low-rank edge scores and the greedy path walk, one workgroup a -// sequence and no launch between steps. `cand` and `unary` are row_topk's two output planes at row -// s*steps+l, `hp` is hidden_projection(x) for the same row, `anchor` is the token the target just -// committed, read at anchor[s * anchor_stride] so a packed [M] array is the stride-1 case. R must -// be a multiple of 32 and at most 512; K at most 32. +// DFlash2's candidate selector: the low-rank edge scores and the greedy path walk, one workgroup +// a sequence. `cand` and `unary` are row_topk's two output planes at row s*steps+l, `hp` is +// hidden_projection(x) for the same row, and `anchor` is the token the target just committed, +// read at anchor[s * anchor_stride]. R must be a multiple of 32 and at most 512; K at most 32. // -// `hp` MAY BE NULL, and then it is ones: the score becomes the plain bigram -// with no dependence on the hidden state, which is DSpark's rank-256 Markov head over the base -// head's top K. `hp_ld` is ignored in that case. +// A null `hp` means ones: the score is the plain bigram , DSpark's rank-256 +// Markov head over the base head's top K; `hp_ld` is then ignored. // -// `V` is the codebooks' row count. A predecessor or candidate id outside [0, V) -- a merge pad is -// -1 -- reads no codebook row: the predecessor contributes nothing and the candidate scores its -// unary term alone, as ref_dflash_select has it. +// `V` is the codebooks' row count. An id outside [0, V) (a merge pad is -1) reads no codebook row: +// the predecessor contributes nothing and the candidate scores its unary term alone, as in +// ref_dflash_select. int r4d_dflash_select_bf16( const void* cand, const void* unary, const void* hp, const void* anchor, const void* pred, const void* succ, void* out, @@ -204,42 +180,39 @@ int r4d_dflash_select_bf16( // Everything between the qkv projection and the chunked scan, in one kernel: the depthwise causal // convolution (width 4, silu) with its state cache, the q/k/v split, the l2 norm on q and k, the // gate g = -exp(A_log).softplus(a + dt_bias) with its per-chunk cumsum, and beta = sigmoid(b). -// Replaces causal_conv1d_fn + fused_post_conv_prep + chunk_local_cumsum; the conv output never -// reaches HBM. Strides are in ELEMENTS; x may be a padded view (the qkvz split the layer hands it). +// Replaces causal_conv1d_fn + fused_post_conv_prep + chunk_local_cumsum. Strides are in elements; +// x may be a padded view (the qkvz split). `hi_i32` is has_init's width: 1 for int32, 0 for +// unsigned char (reading int32 flags as bytes is right only when the value is 0). int r4d_gdn_conv_prep_w4_h128_bf16( const void* x, long xpitch, const void* wgt, const void* bias, void* cstate, long cs_seq, long cs_dim, long cs_tok, const void* cache_idx, long ci_stride, - /* `hi_i32` gives has_init's WIDTH: 1 for int32, 0 for unsigned char. The caller's derived - * buffers are int32 and this read them as bytes, which is right only when the value is 0. */ const void* has_init, int hi_i32, const void* a, const void* b, long ab_stride, int ab_is_bf16, const void* A_log, const void* dt_bias, void* q, void* k, void* v, void* g, void* beta, const void* cu, int N, int T, int H, int Hg, int K, int V, int width, float softplus_thr, void* stream); -// The same convolution for a decode step: the tokens are a speculative window, the state cache is -// a rolling buffer of width-1 + num_spec entries read at the slot the last ACCEPTED token left, -// and q / k / v are written straight into their own layouts. Replaces causal_conv1d_update and -// the cat that made its output contiguous. +// The same convolution for a decode step over a speculative window. The state cache is a rolling +// buffer of width-1 + num_spec entries read at the slot the last accepted token left; q / k / v +// are written straight into their own layouts. Replaces causal_conv1d_update and its cat. int r4d_gdn_conv_update_w4_h128_bf16( const void* x, long xpitch, const void* wgt, const void* bias, void* cstate, long cs_seq, long cs_dim, long cs_tok, int state_len_max, const void* cache_idx, long ci_stride, const void* num_accepted, void* q, void* k, void* v, const void* cu, int N, int H, int Hg, int K, int V, int width, int max_query_len, void* stream); -// The gated RMS norm the layer applies to its own output: out = rms(x) . w . act(z), one row per -// (token, head). Replaces FLA's rmsnorm_fn. act: 0 = silu/swish, 1 = sigmoid. Only the prefill -// path needs it -- the decode kernel below folds the same arithmetic into its epilogue, because -// its workgroup owns the whole row. +// The gated RMS norm on the layer's output: out = rms(x) . w . act(z), one row per (token, head). +// Replaces FLA's rmsnorm_fn. act: 0 = silu/swish, 1 = sigmoid. Prefill only; the decode kernel +// folds the same arithmetic into its epilogue. int r4d_gdn_gated_rmsnorm_h128_bf16(const void* x, const void* z, const void* w, void* o, long rows, long xrow, long zrow, long orow, long zheads, long ztok, int width, float eps, int act, void* stream); -// The recurrent delta-rule update decode runs where prefill runs the chunked scan: gating, the qk -// l2 norm, the state update and the output, against the paged state cache. The state is fp32 -// (this model's config asks for it) and one is written per candidate token, which is the whole -// cost of the kernel. Replaces fused_sigmoid_gating_delta_rule_update. +// The recurrent delta-rule update decode runs: gating, the qk l2 norm, the state update and the +// output, against the paged state cache. The state is fp32 (per the model config) and one is +// written per candidate token, which dominates the cost. Replaces +// fused_sigmoid_gating_delta_rule_update. int r4d_gdn_recurrent_update_k128_v128_bf16_fp32state( const void* q, const void* k, const void* v, const void* a, const void* b, long ab_stride, int ab_is_bf16, const void* A_log, const void* dt_bias, void* state, @@ -251,16 +224,14 @@ int r4d_gdn_recurrent_update_k128_v128_bf16_fp32state( void* stream); // ---- all-reduce: one-shot, push, 2 ranks over P2P ------------------------------------------ -// One-shot means each rank pushes its whole input into the peer's IPC scratch and then reduces -// locally -- no ring, no two-shot reduce-scatter, so the scratch is sized by the full message. -// Exactly 2 ranks: the handshake is a single peer flag, not a tree. Every 2-rank kernel on one -// buffer set shares its counters: `seq_ctrs` is 2 * r4d_ar_max_blocks() zeroed words, a handshake -// counter and a slot-parity counter per block of capacity (r4d_ar_seq.h). +// Each rank pushes its whole input into the peer's IPC scratch, then reduces locally; no ring, so +// the scratch is sized by the full message. Exactly 2 ranks: the handshake is a single peer flag. +// Every 2-rank kernel on one buffer set shares its counters: `seq_ctrs` is 2 * r4d_ar_max_blocks() +// zeroed words, a handshake and a slot-parity counter per block of capacity (r4d_ar_seq.h). enum { R4D_AR_HANDLE_BYTES = 64 }; -// IPC scratch helpers. Startup-only, and not kernels: alloc returns the device pointer and writes -// the IPC handle (up to HANDLE_BYTES) into out_handle. +// IPC scratch helpers, startup-only: alloc returns the device pointer and writes the IPC handle +// (up to HANDLE_BYTES) into out_handle. long r4d_ar_ipc_alloc(long size, int finegrained, char* out_handle, int* out_len); -long r4d_ar_ipc_open(const char* handle, int len); // Strided peer (or local) device-to-device copy through the copy engines; pitches and width in // bytes, height in rows. Returns 0 or -100 - hipError_t. int r4d_p2p_copy2d_kernel(long dst, long src, long dpitch, long spitch, long width, long height, @@ -269,11 +240,9 @@ int r4d_p2p_fence(long stream); int r4d_p2p_copy2d(long dst, long src, long dpitch, long spitch, long width, long height, long stream); void r4d_ar_ipc_free(long p); -void r4d_ar_ipc_memzero(long p, long size); void r4d_ar_ipc_enable_peer(long peer); -// Exchange buffers in pinned, fine-grained HOST memory, for cards that cannot reach each other's -// VRAM: every card reads and writes the same host pages over its own link. Zeroed, and the -// returned address is valid on every card and on the CPU alike. Startup-only. +// Exchange buffers in pinned, fine-grained host memory, for cards that cannot reach each other's +// VRAM. Zeroed; the address is valid on every card and the CPU. Startup-only. long r4d_ar_host_alloc(long size); void r4d_ar_host_free(long p); // Exact sum, fp32 accumulate, bf16 / fp16 / fp32 payload (dtype 0 / 1 / 2). @@ -281,9 +250,9 @@ void r4d_ar_oneshot_2rank_exact(long peer_scratch, long my_scratch, long peer_fl long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long stream, long nblocks, long nthreads, long drain, long acq); -// Same topology, but the wire payload is Walsh-Hadamard rotated and quantised to 6 bits per element -// over groups of 64 (plus a bf16 scale per group). Lossy, and bf16 / fp16 payload only. Takes this -// rank's own packed copy (loc_pack) as well, so the reduce folds exactly the bytes it sent. +// Same topology, with the wire payload Walsh-Hadamard rotated and quantised to 6 bits per element +// in groups of 64 (plus a bf16 scale per group). Lossy; bf16 / fp16 payload only. loc_pack is this +// rank's own packed copy, so the reduce folds exactly the bytes it sent. void r4d_ar_oneshot_2rank_wht6(long peer_scratch, long my_scratch, long peer_flags, long my_flags, long seq_ctrs, long loc_pack, long slot_stride_bytes, long scale_off_bytes, long inp, long out, long n_elem, long dtype, @@ -291,19 +260,18 @@ void r4d_ar_oneshot_2rank_wht6(long peer_scratch, long my_scratch, long peer_fla // The exact all-reduce of `y` [M][n] bf16 with hc_write as its epilogue: h[r][c*n + i] += // inj[r][c] * y[r][i] over the reduced y, byte-identical to all_reduce then hc_write. `irow` and // `hrow` are the pitches of inj [M][hc] and h [M][hc*n] in elements; y is tight. A non-zero `gate` -// is the engine's link word, ended once the peer's push has landed (r4d_ar_link_landed); `gate_ctr` -// is the instance's block counter for it. The gather form below takes the same pair. +// is the engine's link word, ended once the peer's push has landed (r4d_ar_link_landed); +// `gate_ctr` is its block counter. The gather form below takes the same pair. void r4d_ar_hc_write(long peer_scratch, long my_scratch, long peer_flags, long my_flags, long seq_ctrs, long slot_stride16, long y, long inj, long h, long M, long n, long hc, long irow, long hrow, long stream, long nblocks, long nthreads, long drain, long acq, long gate, long gate_ctr); -// The same with the MoE gather as its prologue: y is not read but produced -- the routed experts' -// rows `ye` [M*top_k][ye_ld] summed back to token order by the weights `ew` [M][ew_ld] and the -// sorted list `sorted` [M*top_k], with the shared arm `sh` [M][sh_ld] and its gate `sg` folded -// when both are non-zero -- byte-identical to moe_gather, then all_reduce, then hc_write. `inv`, -// when non-zero, is M*top_k int32 of device scratch for the inverse slot table a prefill-sized -// call reads instead of its per-block LDS one. Returns 0, or a negative code for a shape it does -// not serve. +// The same with the MoE gather as its prologue: y is produced, not read, from the routed experts' +// rows `ye` [M*top_k][ye_ld] summed to token order by weights `ew` [M][ew_ld] and `sorted` +// [M*top_k], with the shared arm `sh` [M][sh_ld] and its gate `sg` folded when both are non-zero. +// Byte-identical to moe_gather, all_reduce, hc_write. A non-zero `inv` is M*top_k int32 device +// scratch for the inverse slot table a prefill-sized call reads instead of a per-block LDS one. +// Returns 0, or a negative code for a shape it does not serve. int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags, long my_flags, long seq_ctrs, long slot_stride16, long y, long inj, long h, long M, long n, long hc, long irow, long hrow, long ye, long ew, long sorted, @@ -311,12 +279,11 @@ int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags, long top_k, long sig, long stream, long nblocks, long nthreads, long drain, long acq, long inv, long gate, long gate_ctr); // r4d_ar_hc_write and r4d_ar_gather_hc_write on the rotated 6-bit wire (r4d_ar_oneshot_2rank_wht6's -// format and arithmetic, its loc_pack and scratch split): byte-identical to all_reduce on that wire -// then hc_write, and with `ye` non-zero to moe_gather, then those two. The gather's operands are -// r4d_ar_gather_hc_write's; its slot table is built in LDS, and the grid is widened until a -// block's table fits. M*n must be a multiple of 64. A non-zero `gate` is the engine's link word, -// ended by the launch once the peer's bytes have landed (r4d_ar_link_landed); `gate_ctr` is the -// instance's block counter for it. Returns 0, or a negative code for a shape it does not serve. +// format, loc_pack and scratch split): byte-identical to all_reduce on that wire then hc_write, +// with `ye` non-zero preceded by moe_gather. Gather operands as r4d_ar_gather_hc_write; its slot +// table is built in LDS, and the grid is widened until a block's table fits. M*n must be a +// multiple of 64. `gate` / `gate_ctr` as r4d_ar_hc_write. Returns 0, or a negative code for a +// shape it does not serve. int r4d_ar_hc_write_wht6(long peer_scratch, long my_scratch, long peer_flags, long my_flags, long seq_ctrs, long loc_pack, long slot_stride_bytes, long scale_off_bytes, long y, long inj, long h, long M, long n, long hc, @@ -327,26 +294,24 @@ int r4d_ar_hc_write_wht6(long peer_scratch, long my_scratch, long peer_flags, l int r4d_ar_max_blocks(void); // the two 2-rank kernels void r4d_ar_wht6_dims(int* group, int* bits, int* chunk_elems); // rotated-6-bit payload only -// ---- all-GATHER: one-shot, push, exactly 2 ranks over P2P ---------------------------------- -// The same push and the same per-block flag handshake as r4d_ar_oneshot_2rank_exact, with the -// reduction replaced by placement: `out` is 2 * n_elem elements, this rank's input at -// rank * n_elem and the peer's at (1 - rank) * n_elem. `dtype` is used only for the element size -// -- the payload is moved, never summed, because the vocab-parallel sampler gathers (u32 token id, -// f32 logit) pairs and adding the id lanes would destroy them. +// ---- all-gather: one-shot, push, exactly 2 ranks over P2P ---------------------------------- +// The push and per-block flag handshake of r4d_ar_oneshot_2rank_exact, with placement instead of +// reduction: `out` is 2 * n_elem elements, this rank's input at rank * n_elem and the peer's at +// (1 - rank) * n_elem. `dtype` only gives the element size; the payload is never summed, because +// the vocab-parallel sampler gathers (u32 token id, f32 logit) pairs. void r4d_ar_gather_2rank(long peer_scratch, long my_scratch, long peer_flags, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long row_elems, long stream, long nblocks, long nthreads, long drain, long acq); // ---- all-reduce: one-shot, push, 4 or 8 ranks over P2P ------------------------------------- -// The same algorithm at width (r4d_ar_oneshot_Nrank_exact.hip). The peer arguments are ascending -// global rank with the current rank removed. Scratch is 2*world size slots of slot_stride16 16B -// words parity x source rank, this rank's own slot unused); flags are max_blocks*ws words indexed +// The same algorithm at width (r4d_ar_oneshot_Nrank_exact.hip). Peer arguments are in ascending +// global rank with the current rank removed. Scratch is 2*world-size slots of slot_stride16 16B +// words (parity x source rank, this rank's own slot unused); flags are max_blocks*ws words indexed // [block][source rank]; seq_ctrs is 2 * max_blocks words, a handshake and a slot-parity counter // per block of capacity (r4d_ar_seq.h). -// Three ranks: the same kernel instantiated at WS=3 (two peers). Nothing in the wide family is -// power-of-two; the two-shot serves 3 too, with shards one word uneven where the message does not -// divide (r4d_ar_twoshot_3rank_exact, below). +// Three ranks is the same kernel at WS=3; the wide family does not need a power of two. The +// two-shot serves 3 too, with shards one word uneven where the message does not divide. void r4d_ar_oneshot_3rank_exact(long peer_scratch0, long peer_scratch1, long peer_flags0, long peer_flags1, long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, @@ -358,7 +323,11 @@ void r4d_ar_oneshot_4rank_exact(long peer_scratch0, long peer_scratch1, long pee long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long stream, long nblocks, long nthreads, long drain, long acq, - long pub); + long pub, long gate, long gate_ctr); +// The two wide releases' extra pair at four ranks: `gate` is the engine's link word (0 when this +// launch holds nothing -- the host mailbox, a recorded pass, or a width the row does not release), +// `gate_ctr` the block counter beside the sequence counters (r4d_ar_seq.h). The 3- and 8-rank +// entries take neither: their rows answer 1 and the engine releases by barrier. // ---- all-gather at width (r4d_ar_gather_Nrank.hip) ------------------------------------------ // The 2-rank gather's placement on the wide family's transport: `out` is world * n_elem elements, // rank r's slice at r * n_elem, or row-interleaved [rows][world][row] when row_elems > 0. Shares @@ -377,19 +346,19 @@ void r4d_ar_oneshot_8rank_exact(long peer_scratch0, long peer_scratch1, long pee long out, long n_elem, long dtype, long rank, long stream, long nblocks, long nthreads, long drain, long acq, long pub); // r4d_ar_hc_write at four ranks: the 4-rank exact one-shot of `y` [M][n] bf16, in place, with -// hc_write as its epilogue -- byte-identical to that all-reduce then hc_write. Same buffer trio, -// peer order, flag values and slots as r4d_ar_oneshot_4rank_exact, so the two (and the two-shots) -// may share one instance. `irow`/`hrow` as r4d_ar_hc_write's; y is tight. +// hc_write as its epilogue, byte-identical to that all-reduce then hc_write. Buffers, peer order, +// flag values and slots match r4d_ar_oneshot_4rank_exact, so the two (and the two-shots) may share +// one instance. `irow`/`hrow` as r4d_ar_hc_write; y is tight. void r4d_ar_hc_write_4rank(long peer_scratch0, long peer_scratch1, long peer_scratch2, long peer_flags0, long peer_flags1, long peer_flags2, long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, long y, long inj, long h, long M, long n, long hc, long irow, long hrow, long rank, long stream, long nblocks, long nthreads, - long drain, long acq, long pub); -// r4d_ar_gather_hc_write at four ranks: r4d_ar_hc_write_4rank with the MoE gather as its prologue -// -- byte-identical to moe_gather, then the 4-rank exact all-reduce, then hc_write. The gather's -// operands, `inv` and the grid rule are r4d_ar_gather_hc_write's; the buffers, peer order, flag -// values and slots are r4d_ar_oneshot_4rank_exact's. Exact wire only. + long drain, long acq, long pub, long gate, long gate_ctr); +// r4d_ar_hc_write_4rank with the MoE gather as its prologue, byte-identical to moe_gather, the +// 4-rank exact all-reduce, then hc_write. Gather operands, `inv` and the grid rule are +// r4d_ar_gather_hc_write's; buffers, peer order, flag values and slots are +// r4d_ar_oneshot_4rank_exact's. Exact wire only. void r4d_ar_gather_hc_write_4rank(long peer_scratch0, long peer_scratch1, long peer_scratch2, long peer_flags0, long peer_flags1, long peer_flags2, long my_scratch, long my_flags, long seq_ctrs, @@ -398,7 +367,7 @@ void r4d_ar_gather_hc_write_4rank(long peer_scratch0, long peer_scratch1, long p long sh, long sg, long ye_ld, long ew_ld, long sh_ld, long sg_ld, long top_k, long sig, long rank, long stream, long nblocks, long nthreads, long drain, long acq, long pub, - long inv); + long inv, long gate, long gate_ctr); // The inverse slot table both widths' gather forms read at a prefill-sized call: inv[f] = the // sorted row holding slot f, -1 where none does, over T = M*top_k int32. One block, on `stream`. // Returns 0 or a negative / HIP error code. @@ -406,18 +375,15 @@ int r4d_ar_gather_inv(long inv, long sorted, long T, long stream); void r4d_ar_wide_dims(int* max_blocks, int* nb_design, int* max_peers); // ---- all-reduce: two-shot, 3, 4 or 8 ranks over P2P ---------------------------------------- -// Reduce-scatter + all-gather on the same buffer trio and peer-argument order as the wide -// one-shot (r4d_ar_twoshot_Nrank_exact.hip): shard s, a contiguous run of the message's 16-byte -// words, is reduced by rank s (fp32, ascending rank order), then gathered. Sends 2*(ws-1)/ws*N -// bytes per rank in two hops. Covers the sizes where the one-shot's (ws-1)*N send is too heavy. -// Shards are as even as the word count allows (the first n16 % ws take one more word), so a -// message need not divide by the rank count -- at three it almost never does. Regions A and B sit -// at 0 and the longest shard, so the slot stride must hold twice that. Above this bound the caller -// falls back to the one-shot. The bound guards the kernel's int word offsets (the message, the -// slot stride) and nothing else: 2^28 elements is 2^26 words at fp32. It was 20971520 -- a -// 4096-token chunk of a 5120-wide residual -- which handed every larger prefill chunk back to the -// one-shot and its (ws-1)*N send: an 8192-token chunk at Gemma 4's 2816 is 23M elements at the -// attention's reduce and 46M at the feed-forward's, which carries both branches. +// Reduce-scatter + all-gather on the wide one-shot's buffer trio and peer order +// (r4d_ar_twoshot_Nrank_exact.hip): shard s, a contiguous run of 16-byte words, is reduced by +// rank s (fp32, ascending rank order), then gathered. Sends 2*(ws-1)/ws*N bytes per rank in two +// hops, for sizes where the one-shot's (ws-1)*N send is too heavy. Shards are as even as the word +// count allows (the first n16 % ws take one more word), so the message need not divide by the +// rank count. Regions A and B sit at 0 and the longest shard, so the slot stride must hold twice +// that. Above the bound below the caller falls back to the one-shot; it only guards the kernel's +// int word offsets (2^28 elements is 2^26 words at fp32). A lower bound would send large prefill +// chunks (e.g. 8192 tokens at Gemma 4's 2816 width, 23M-46M elements) to the one-shot. enum { R4D_AR_TWOSHOT_WIDE_MAX_ELEMS = 268435456 }; void r4d_ar_twoshot_3rank_exact(long peer_scratch0, long peer_scratch1, long peer_flags0, long peer_flags1, long my_scratch, long my_flags, long seq_ctrs, @@ -429,7 +395,7 @@ void r4d_ar_twoshot_4rank_exact(long peer_scratch0, long peer_scratch1, long pee long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long stream, long nblocks, long nthreads, long drain, - long acq, long pub); + long acq, long pub, long gate, long gate_ctr); void r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long peer_scratch2, long peer_scratch3, long peer_scratch4, long peer_scratch5, long peer_scratch6, long peer_flags0, long peer_flags1, @@ -438,15 +404,14 @@ void r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long pee long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long stream, long nblocks, long nthreads, long drain, long acq, long pub); -// The tiered int8 wire on both of the two-shot's hops (r4d_ar_twoshot_Nrank_ti8.hip; codec -// in r4d_ar_ti8.h), 3 or 4 ranks. The wire: int8 groups of 32 with an fp16 scale and a -// per-group record (T1 plain, T2 top-1-exact, T3 wht32) 38 bytes/group, deterministic -// tiering, bit-identical across ranks. Same peer-argument order and flag layout as the exact -// pair; slot stride in bytes (the wire is not 16B-aligned), holding two wire images; the -// encoder writes its own slot too (no loc_pack). numel must be whole 32-elem groups; the -// groups split over the ranks as evenly as they divide (the first ng % ws shards one group -// longer) and every slot is laid out for the longest shard. The 4-rank entry still asks for -// numel % 128, the even split. +// The tiered int8 wire on both two-shot hops (r4d_ar_twoshot_Nrank_ti8.hip; codec in +// r4d_ar_ti8.h), 3 or 4 ranks. Int8 groups of 32 with an fp16 scale and a per-group record +// (T1 plain, T2 top-1-exact, T3 wht32), 38 bytes/group; tiering is deterministic and +// bit-identical across ranks. Peer order and flag layout as the exact pair; slot stride in bytes +// (the wire is not 16B-aligned), holding two wire images; the encoder writes its own slot too (no +// loc_pack). numel must be whole 32-element groups, split over the ranks as evenly as they divide +// (the first ng % ws shards one group longer), with every slot laid out for the longest shard. +// The 4-rank entry still requires numel % 128 == 0, the even split. void r4d_ar_twoshot_3rank_ti8(long peer_scratch0, long peer_scratch1, long peer_flags0, long peer_flags1, long my_scratch, long my_flags, long seq_ctrs, long slot_stride_bytes, long inp, long out, long n_elem, @@ -457,76 +422,55 @@ void r4d_ar_twoshot_4rank_ti8(long peer_scratch0, long peer_scratch1, long peer_ long my_scratch, long my_flags, long seq_ctrs, long slot_stride_bytes, long inp, long out, long n_elem, long dtype, long rank, long stream, long nblocks, - long nthreads, long drain, long acq, long pub); + long nthreads, long drain, long acq, long pub, long gate, + long gate_ctr); void r4d_ar_ti8_dims(int* group, int* group_bytes); // tiered-int8 wire only // ---- GEMM ---------------------------------------------------------------------------------- -// Skinny bf16 GEMM for M up to 64: the same C[M,N] = A[M,K] @ W[N,K]^T, computed with -// 16x16x16 WMMA so a 16-wide step of K costs ceil(M/16) activation fragments and one weight -// fragment, instead of one weight load and M activation loads. +// Skinny bf16 GEMM for M up to 64: C[M,N] = A[M,K] @ W[N,K]^T with 16x16x16 WMMA, so a 16-wide K +// step costs ceil(M/16) activation fragments and one weight fragment. void r4d_gemm_bf16_nt_m64(long a, long w, long c, int M, int K, int N, int WV, int SK, int MB, long stream); int r4d_gemm_bf16_nt_m64_max_m(void); -// The same GEMM at prefill row counts: LDS-staged tiles, eight waves a block, and output bytes +// The same GEMM at prefill row counts: LDS-staged tiles, eight waves a block, output bytes // identical to r4d_gemm_bf16_nt_m64 at the same split count SK. `tile` picks the block: 1 = 128 x // 128, 2 = 64 x 64; r4d_gemm_bf16_nt_tiled_arm is the automatic choice. K a multiple of 64. -// Returns 0, or negative on a shape it does not serve, or the HIP error of the launch. +// Returns 0, negative on a shape it does not serve, or the launch's HIP error. int r4d_gemm_bf16_nt_tiled(long a, long w, long c, int M, int K, int N, int SK, int tile, long stream); int r4d_gemm_bf16_nt_tiled_arm(int M, int N); -// Skinny GEMM with a 4-BIT weight: C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T, f16 A, bf16 C. The weight +// Skinny GEMM with a 4-bit weight: C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T, f16 A, bf16 C. The weight // is asymmetric per output channel per group of `group()` contiguous K -- w ~= scale * (q - zero), -// q in 0..15, zero an integer -- and is pre-permuted offline into the WMMA fragment order, so the -// kernel's whole weight path is one global_load_b128 per lane per four k steps. Wq is N*K/2 bytes; -// Wsz is one dword per (row, group), the f16 scale in its low half and the f16 of -(1024 + zero) -// in its high half. N must be a multiple of 16 and K divisible by SK * group(). +// q in 0..15, zero an integer -- and pre-permuted offline into WMMA fragment order, so the weight +// path is one global_load_b128 per lane per four k steps. Wq is N*K/2 bytes; Wsz is one dword per +// (row, group): the f16 scale low, the f16 of -(1024 + zero) high. N must be a multiple of 16 and +// K divisible by SK * group(). void r4d_gemm_w4a16_nt_m64(long a, long wq, long wsz, long c, int M, int K, int N, int WV, int SK, int MB, int NPW, int NT, long stream); int r4d_gemm_w4a16_nt_m64_max_m(void); int r4d_gemm_w4a16_nt_m64_group(void); -// Skinny GEMM with an 8-BIT weight: C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T, f16 A, bf16 C. Same -// fragment order, packed-block size and (scale, zero) dword as r4d_gemm_w4a16_nt_m64, with one -// packed block covering 32 K instead of 64. Asymmetric per output channel per group of `group()` -// contiguous K -- w ~= scale * (q - zero), q in 0..255, zero an integer. Wq is N*K bytes; Wsz is -// one dword per (row, group), the f16 scale low and the f16 of -(1024 + zero) high. +// Skinny GEMM with an 8-bit weight: same fragment order, packed-block size and (scale, zero) dword +// as r4d_gemm_w4a16_nt_m64, with one packed block covering 32 K instead of 64. q in 0..255. Wq is +// N*K bytes. void r4d_gemm_w8a16_nt_m64(long a, long wq, long wsz, long c, int M, int K, int N, int WV, int SK, int MB, int NPW, int NT, long stream); int r4d_gemm_w8a16_nt_m64_max_m(void); int r4d_gemm_w8a16_nt_m64_group(void); -// Exact per-row top-R of a wide bf16 matrix, in two launches. `partial` is -// M * rowtopk_chunks(N, NCH) * RC int64, where RC >= R is how many a chunk keeps; `outv` is M*R float and `outi` M*R int32, both descending -// by value and, on a tie, by the LOWER column. NCH is a REQUEST -- the chunk width is rounded up -// to a multiple of eight columns, so ask rowtopk_chunks() what the launch will actually use. -void r4d_rowtopk_bf16(long y, long partial, long outv, long outi, - int M, int N, int R, int RC, int NCH, int PT1, long stream); -// The same top-R over one rank's SLICE of a wider plane. `off` is the first global column the -// slice stands for and is added to every column this writes, so `outi` is global ids; an empty -// slot still writes column 0, because offsetting a pad would make it this rank's first real token. -// `outp` -- 0 for none -- is an M*R plane of (int32 id, float value) pairs, eight bytes an entry, -// which is the element an all-gather moves so ranks can agree on a global top-R without gathering -// the plane itself; a pad writes id -1 there, the sentinel a merge drops. At off = 0 with outp 0 -// this is r4d_rowtopk_bf16 to the bit, which is what the plain entry point calls. -void r4d_rowtopk_bf16_sharded(long y, long partial, long outv, long outi, long outp, - int M, int N, int R, int RC, int NCH, int PT1, int off, - long stream); -// The other half of a sharded top-R: the R largest of `gathered`, an [M, W*R, 2] plane of (int32 -// id, float value) pairs with rank r's at [r*R, (r+1)*R), written in the same (`outv`, `outi`) -// form the two stages above write. Id -1 is a pad and is dropped; ties break on the LOWER id, so -// the answer equals a top-R over the unsharded plane rather than merely approximating it. -void r4d_rowtopk_merge(long gathered, long outv, long outi, int M, int R, int W, long stream); -void r4d_logit_rerank(long x, long idx_in, long head, long outi, long outv, long outp, - int M, int R, long K, long voff, long nv, long stream); +// Exact per-row top-R of a wide bf16 matrix (the row_topk op, r4d_rowtopk_bf16.hip): the number +// of chunks a launch over N columns uses for a requested chunk count NCH. The chunk width is +// rounded up to a multiple of eight columns, and the stage-1 partial plane is M * chunks * RC +// int64, so a scratch sizer asks this rather than recomputing it. int r4d_rowtopk_bf16_chunks(int N, int NCH); -// 2-BIT weight, 8-bit activation, for the DFlash2 draft head. Unsigned 2-bit codes in the byte's +// 2-bit weight, 8-bit activation, for the DFlash2 draft head. Unsigned 2-bit codes in the byte's // high two bits, asymmetric per (row, group of group()) K, corrected with r4d_quant_act_i8_asum's -// [K/group][Mpad] group-major sums -- the same activation, quantiser and layout as -// r4d_gemm_w4a8_asym_nt_m64. Wq is N*K/4 bytes; Ws is the shared (f16 scale, f16 of -(1024+zero)) -// dword per (row, group). +// [K/group][Mpad] group-major sums: the activation, quantiser and layout of +// r4d_gemm_w4a8_asym_nt_m64. Wq is N*K/4 bytes; Ws is the shared (f16 scale, f16 of +// -(1024+zero)) dword per (row, group). void r4d_gemm_w2a8_nt(long a, long ascale, long wq, long ws, long asum, long c, int M, int K, int N, int WV, int SK, int MB, int NPW, int NT, long stream); int r4d_gemm_w2a8_nt_group(void); @@ -534,51 +478,45 @@ int r4d_gemm_w2a8_nt_group(void); // 4-bit weight, 8-bit activation. Signed 4-bit codes, per-row activation scale, int8 WMMA. void r4d_gemm_w4a8_nt_m64(long a, long ascale, long wq, long ws, long c, int M, int K, int N, int WV, int SK, int MB, int NPW, int NT, long stream); -// Asymmetric variant: the weight nibble is read UNSIGNED by the WMMA and the stored zero point is -// corrected out with `asum` from r4d_quant_act_i8_asum. Same packed weight, same scale dword -- -// the zero rides in its high half as the f16 of -(1024 + zero), which is the encoding the f16 -// kernel already requires. +// Asymmetric variant: the WMMA reads the weight nibble unsigned and the stored zero point is +// corrected with `asum` from r4d_quant_act_i8_asum. Same packed weight and scale dword; the zero +// is the f16 of -(1024 + zero) in its high half, the f16 kernel's encoding. void r4d_gemm_w4a8_asym_nt_m64(long a, long ascale, long wq, long ws, long asum, long c, int M, int K, int N, int WV, int SK, int MB, int NPW, int NT, long stream); -// The same GEMM tiled for PREFILL batches, where the skinny kernel gives a block 64 rows and so -// re-reads the weight M/64 times. Same packed weight and same pre-shuffled activation; N must be a -// multiple of 256 and K of the scale group. -// variant 1 is the transposed-accumulator epilogue (see the source); 0 is the M-major original. +// The same GEMM tiled for prefill batches, where the skinny kernel's 64-row block re-reads the +// weight M/64 times. Same packed weight and pre-shuffled activation; N must be a multiple of 256 +// and K of the scale group. `variant` is one of the kernel's compiled tile arms (r4d_rows.cpp, +// kTileArms); 0 is the shipped default. void r4d_gemm_w4a8_tiled(long a, long ascale, long wq, long ws, long c, int M, int K, int N, long stream, int variant = 0); -// Same kernel on the ASYMMETRIC grid: unsigned nibbles plus r4d_quant_act_i8_asum's [G][Mpad] row +// Same kernel on the asymmetric grid: unsigned nibbles plus r4d_quant_act_i8_asum's [G][Mpad] row // sums. void r4d_gemm_w4a8_asym_tiled(long a, long ascale, long wq, long ws, long asum, long c, int M, int K, int N, long stream, int variant = 0); -// The same GEMM again, for PREFILL row counts, where the matrix pipe rather than the weight stream -// is the constraint. Same packed weight and same rotated int8 activation as the tiled kernel; N -// must be a multiple of BN (256 at the default shape) and K of the scale group. The differences -// are in the inner loop: the activation is stored half-major in LDS so one `ds_load_b128` fetches -// two k steps, and the group fold is plain `v_fmac_f32` so the VOPD packer can pair it. +// The same GEMM for prefill row counts where the matrix pipe, not the weight stream, is the limit. +// Same packed weight and rotated int8 activation as the tiled kernel; N a multiple of BN (256 at +// the default shape), K of the scale group. The activation is stored half-major in LDS so one +// `ds_load_b128` fetches two k steps, and the group fold is plain `v_fmac_f32` so VOPD can pair it. void r4d_gemm_w4a8_prefill(long a, long ascale, long wq, long ws, long c, int M, int K, int N, long stream, int variant = 0); int r4d_gemm_w4a8_nt_m64_max_m(void); int r4d_gemm_w4a8_nt_m64_group(void); -int r4d_gemm_w4a8_nt_m64_aperm(void); -int r4d_gemm_w4a8_nt_m64_ws16(void); -// 8-BIT weight, 8-bit activation. The promoted linears of the INT4 target (every down_proj and the -// attention o_proj) and lm_head. Signed int8 codes in the iu8 16x16x16 fragment order -- the same -// order the A side already uses, so the packer is one routine at two radices -- with one f16 scale -// per (output row, group of group() along K) in an f16-ONLY plane, and the per-row activation scale -// applied once at the store. `a` is the SAME permuted int8 buffer r4d_gemm_w4a8_nt_m64 reads, from -// the same fused producer. Wq is N*K bytes; Ws is N*K/group() f16. +// 8-bit weight, 8-bit activation: the promoted linears of the INT4 target (every down_proj and the +// attention o_proj) and lm_head. Signed int8 codes in the iu8 16x16x16 fragment order, the order +// the A side uses, with one f16 scale per (output row, group() of K) in an f16-only plane; the +// per-row activation scale is applied at the store. `a` is the same permuted int8 buffer +// r4d_gemm_w4a8_nt_m64 reads. Wq is N*K bytes; Ws is N*K/group() f16. void r4d_gemm_w8a8_nt_m64(long a, long ascale, long wq, long ws, long c, int M, int K, int N, int WV, int SK, int MB, int NPW, int NT, long stream); int r4d_gemm_w8a8_nt_m64_max_m(void); int r4d_gemm_w8a8_nt_m64_group(void); int r4d_gemm_w8a8_nt_m64_kpb(void); -int r4d_gemm_w8a8_nt_m64_aperm(void); -// The same 8-bit GEMM tiled for PREFILL, where the skinny kernel gives a block MB*16 rows and so -// re-reads the weight M/(MB*16) times. Same packed weight and same permuted activation; N must be -// a multiple of the variant's BN (256 at the default shape) and K of the scale group. Inherited -// from r4d_gemm_w4a8_tiled's "unpack at staging" path, whose LDS buffer already holds bytes. +// The same 8-bit GEMM tiled for prefill, where the skinny kernel's MB*16-row block re-reads the +// weight M/(MB*16) times. Same packed weight and permuted activation; N a multiple of the variant's +// BN (256 at the default shape), K of the scale group. Built on r4d_gemm_w4a8_tiled's "unpack at +// staging" path, whose LDS buffer already holds bytes. void r4d_gemm_w8a8_tiled(long a, long ascale, long wq, long ws, long c, int M, int K, int N, long stream, int variant = 0); @@ -591,11 +529,10 @@ void r4d_gemm_mxfp4a8_nt_m64(long a, long ascale, long wq, long ws, long wref, l int lda = 0, int ldws = 0, int ldc = 0); int r4d_gemm_mxfp4a8_nt_m64_max_m(void); int r4d_gemm_mxfp4a8_nt_m64_group(void); -// The same weight tiled for PREFILL: a 256-row block reads A fragments straight from a -// FRAGMENT-ORDERED copy of the activation (`at`, written by r4d_mxfp4a8_tile_a, at least -// r4d_mxfp4a8_tile_a_bytes long) and unpacks the weight once per K slab. TN (2 or 4, 0 = by M) is -// the per-wave column width in 16-column fragments. as_group 0 = one f32 activation scale per row, -// 128 = one per (row, 128 of K) at row stride as_rs. +// The same weight tiled for prefill: a 256-row block reads A fragments from a fragment-ordered copy +// of the activation (`at`, written by r4d_mxfp4a8_tile_a, at least r4d_mxfp4a8_tile_a_bytes long) +// and unpacks the weight once per K slab. TN (2 or 4, 0 = by M) is the per-wave column width in +// 16-column fragments. as_group as r4d_gemm_mxfp4a8_nt_m64. void r4d_gemm_mxfp4a8_tiled(long at, long ascale, long wq, long ws, long wref, long c, int M, int K, int N, int TN, int as_group, int as_rs, long stream, int ldws = 0, int ldc = 0); @@ -603,43 +540,35 @@ void r4d_gemm_mxfp4a8_tiled(long at, long ascale, long wq, long ws, long wref, l void r4d_mxfp4a8_tile_a(long a, long at, int M, int K, long stream, int lda = 0); long r4d_mxfp4a8_tile_a_bytes(int M, int K); int r4d_gemm_mxfp4a8_tiled_group(void); -// The DECODE band (M <= 128) is r4d_rad_gemm_mxfp4a8_decode alone: its split-K partial is the op's -// scratch, which only the plugin ABI hands over. +// The decode band (M <= 128) is r4d_rad_gemm_mxfp4a8_decode only: its split-K partial is the op's +// scratch, which only the plugin ABI provides. int r4d_gemm_mxfp4a8_decode_max_m(void); -// ---- BLOCK-SCALED FP8: the format a checkpoint ships in ---------------------------------------- +// ---- Block-scaled FP8, as checkpoints ship it ------------------------------------------------- // -// Every other quantised GEMM above reads a weight this library's own quantiser produced. This -// family reads the weight as safetensors stores it: `.weight` F8_E4M3 row-major [N][K] and -// `.weight_scale_inv` BF16 on a [ceil(N/128)][ceil(K/128)] grid -- DeepSeek-style block -// scaling, `quantization_config.weight_block_size = [128, 128]`. No permutation and no scale -// conversion: the bytes in the file are the bytes these kernels read, so a container built for them -// costs exactly what the checkpoint does. +// Reads the weight as safetensors stores it: `.weight` F8_E4M3 row-major [N][K] and +// `.weight_scale_inv` BF16 on a [ceil(N/128)][ceil(K/128)] grid (DeepSeek-style, +// `weight_block_size = [128, 128]`). No permutation and no scale conversion. // -// THE BLOCK IS 128 ON BOTH AXES AND IS NOT A BUILD FLAG, unlike R4D_GEMM_W4A8_GROUP. That group is -// a choice this library's quantiser makes; this one is a property of the file on disk. The -// `_block()` queries report it and every entry point rejects a K that would make the fold read a -// partial one. +// The block is 128 on both axes and is a property of the file, not a build flag (unlike +// R4D_GEMM_W4A8_GROUP). The `_block()` queries report it, and every entry point rejects a K that +// would leave a partial block. // -// Three entry points, one per band, and they are three kernels rather than one with a switch -// because the operand carrying the coarse (per-128-row) scale must be the one whose tile is wide -- -// see the AW comment in r4d_gemm_fp8a8.hip. +// Three kernels, one per band, because the operand carrying the coarse (per-128-row) scale must be +// the one whose tile is wide; see the AW comment in r4d_gemm_fp8a8.hip. // // M == 1 r4d_gemm_fp8a16_nt_m1 bf16 activation read directly, no quantise launch // M <= 16 r4d_gemm_fp8a8_nt_m16 E4M3 activation, one 16-wide token tile, split-K // any M r4d_gemm_fp8a8_tiled E4M3 activation, 128x128 tile, eight waves // -// All of them take `w_ld` in BYTES a weight row and `sw_ld` in ELEMENTS a scale row, 0 meaning -// tight, and all of them return 0 or a NEGATIVE code rather than throwing the way the other GEMM -// entry points do. These are reachable from a C consumer, where an exception crossing an .so -// boundary is precisely the failure mode that boundary exists to avoid. +// `w_ld` is bytes per weight row and `sw_ld` elements per scale row, 0 meaning tight. All return 0 +// or a negative code instead of throwing, since they are reachable from C consumers. int r4d_gemm_fp8a16_nt_m1(long a, long wq, long ws, long c, int M, int K, int N, int w_ld, int sw_ld, int rb, long stream); -// The same GEMM for M <= r4d_gemm_fp8a16_nt_m1_max_m(): M token rows against one weight row, so the -// weight is read ONCE for all of them. `a` is [M][K] with `a_ld` elements a row and `c` is [M][N] -// with `c_ld` (0 = N). This is the speculative-verify width -- the alternative at M = 1 + n_spec is -// the 16-wide fp8a8 tile, which needs the activation quantised first and reaches a lower fraction -// of the memory ceiling on identical weight traffic. +// The same GEMM for M <= r4d_gemm_fp8a16_nt_m1_max_m(): M token rows against each weight row, so +// the weight is read once. `a` is [M][K] with `a_ld` elements a row and `c` is [M][N] with `c_ld` +// (0 = N). This is the speculative-verify width; the 16-wide fp8a8 tile needs a quantise launch +// first and reaches a lower fraction of the memory ceiling on the same weight traffic. int r4d_gemm_fp8a16_nt_mt(long a, long wq, long ws, long c, int M, int K, int N, int a_ld, int c_ld, int w_ld, int sw_ld, long stream); /* The lm_head at fp8, scales interleaved in each row's tail; see the .hip for why that layout. */ @@ -648,81 +577,75 @@ int r4d_logits_gemm_fp8(long a, long wq, long c, int M, int K, int N, int r4d_gemm_fp8a16_nt_m1_block(void); int r4d_gemm_fp8a16_nt_m1_max_m(void); -// `a` is E4M3 [M][K] with `ascale` f32 [M][ceil(K/128)] -- r4d_quant_act_fp8's output. `scratch` is -// the split-K partial plane and may be 0, in which case the launch runs unsplit: correct and slow -// rather than wrong. Size it with the query, whose answer is 0 when this shape will not split. +// `a` is E4M3 [M][K] with `ascale` f32 [M][ceil(K/128)], r4d_quant_act_fp8's output. `scratch` is +// the split-K partial plane; 0 runs the launch unsplit (correct, slower). Size it with the query, +// which returns 0 when this shape will not split. // -// SPLIT-K IS NOT BIT-COMPARABLE ACROSS SETTINGS and cannot be: ksplit repartitions K, so the -// accumulation chain differs and the emitted text can move. The invariant that matters -- two runs -// of the SAME binary agreeing -- is unaffected. +// Split-K is not bit-comparable across settings: ksplit repartitions K, so the accumulation order +// differs. Two runs of the same binary still agree. int r4d_gemm_fp8a8_nt_m16(long a, long ascale, long wq, long ws, long c, int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld, long scratch, long scratch_bytes, long stream); long r4d_gemm_fp8a8_nt_m16_scratch(int M, int K, int N); int r4d_gemm_fp8a8_nt_m16_max_m(void); -// A TEST HOOK, and the only way to ask the bit question about the narrow tile's wave count. The -// wave count is a launch heuristic chosen from (N, M), so two settings of it cannot be compared -// from outside libr4d and the environment pin that sweeps it is read once per process. This -// overrides the rule for every subsequent call on every thread; 0 restores it. Not for a serve -- -// r4d_selftest holds it for the length of one comparison and puts it back. -// -// Unlike the split above, the wave count IS bit-comparable BY CONSTRUCTION, which is what the -// check exists to hold to: it moves which wave owns an output element and not the order of the -// K tiles that element accumulates, and the split is derived from `gx * mw`, which the rule keeps -// invariant. `r4d_selftest` compares the bytes at every legal wave count on every shape it runs. +// Test hook: pins the narrow tile's wave count, normally a launch heuristic over (N, M), for every +// subsequent call on every thread; 0 restores the rule. Not for serving; r4d_selftest holds it for +// one comparison. Unlike the split, the wave count is bit-comparable: it moves which wave owns an +// output element, not the order of the K tiles it accumulates, and the split derives from +// `gx * mw`, which the rule keeps invariant. r4d_selftest compares bytes at every legal count. void r4d_gemm_fp8a8_pin_mw(int mw); -// THE QSA SCORE'S FORM, pinned for a test: 0 is the launcher's rule, 1 the scalar decode form, 2 -// the matrix form (which then refuses a shape it is not built for). The two sum in different -// orders, so r4d_selftest's --perfqsa compares them to a tolerance rather than byte for byte. +// Test hook: pins the QSA score's form. 0 is the launcher's rule, 1 the scalar decode form, 2 the +// matrix form (which refuses a shape it is not built for). The two sum in different orders, so +// r4d_selftest --perfqsa compares them to a tolerance. void r4d_qsa_score_pin_form(int form); -// THE QSA SELECTION'S FORM, pinned for a test: 0 is the launcher's rule, 1 the single-workgroup -// kernel, 2 the wide-launch (three-pass) kernel. The split path keeps its own rule. The two pinned -// forms write the same table bit for bit, and r4d_selftest compares them. -// THE ROUTED-EXPERT GEMM'S FORM, pinned for a test: 0 is the launcher's rule, 1 the run-aligned +// Test hook: pins the QSA selection's form. 0 is the launcher's rule, 1 the single-workgroup +// kernel, 2 the wide-launch (three-pass) kernel; the split path keeps its own rule. The pinned +// forms are bit-identical, and r4d_selftest compares them. +// Test hook: pins the routed-expert GEMM's form. 0 is the launcher's rule, 1 the run-aligned // prefill form, 2 the (tile, run) decode form, 3 the uniform prefill grid. r4d_selftest --perfmoe // times each and compares it with form 1. void r4d_moe_gemm_pin_prefill(int form); -// THE DECODE FORM'S STAGED K, pinned for a test: 0 is the launcher's row limit (kMoeGuFk256Rows), -// 1 one 128-wide block a pass, 2 two wherever the shape allows it (the token-operand projection, -// every class's K a multiple of 256, a format that folds scale groups). The two are bit-identical, -// and r4d_selftest compares their bytes. +// Test hook: pins the decode form's staged K. 0 is the launcher's row limit (kMoeGuFk256Rows), +// 1 one 128-wide block a pass, 2 two wherever the shape allows (the token-operand projection, +// every class's K a multiple of 256, a format that folds scale groups). Bit-identical. void r4d_moe_gemm_pin_fk(int pin); -// THE RUN-ALIGNED FORM'S COLUMN TILE, pinned for a test: 0 is the launcher's shape rule (the down -// projection's 256-column tile wherever the sorted operand, one part, a w4 weight and every class's -// width allow it), 1 never that tile, 2 that tile -- refused where the shape cannot take it or the -// launch is not the aligned form. Bit-identical, and r4d_selftest compares their bytes. +// Test hook: pins the run-aligned form's column tile. 0 is the launcher's rule (the down +// projection's 256-column tile wherever the sorted operand, one part, a w4 weight and every +// class's width allow it), 1 never that tile, 2 always (refused where the shape cannot take it or +// the launch is not the aligned form). Bit-identical. void r4d_moe_gemm_pin_down_tile(int pin); -// THE GATHER'S FORM, pinned for a test: 0 is the launcher's rule, 1 a column a thread +// Test hook: pins the gather's form. 0 is the launcher's rule, 1 a column a thread // (gather_kernel), 2 a wave a token and sixteen bytes a lane (gather_wide_kernel), refused on a -// shape it cannot take. Bit-identical, and r4d_selftest compares their bytes. +// shape it cannot take. Bit-identical. void r4d_moe_gather_pin_form(int form); -// THE SORTED OPERAND'S DECODE KERNEL, pinned for a test: 0 is the launcher's rule -// (moe_down_dec_kernel on the sorted operand, one part, at most 512 experts, at a column-tile count -// set by the routed rows -- kMoeDownDecG2Rows), -1 the (tile, run) form, n > 0 moe_down_dec_kernel -// at n column tiles a block, capped at 16 and refused on a shape the kernel does not serve. Inside -// the decode form only, which r4d_moe_gemm_pin_prefill(2) pins. Bit-identical, and r4d_selftest -// compares their bytes. +// Test hook: pins the sorted operand's decode kernel. 0 is the launcher's rule +// (moe_down_dec_kernel on the sorted operand, one part, at most 512 experts, column tiles set by +// the routed rows -- kMoeDownDecG2Rows), -1 the (tile, run) form, n > 0 moe_down_dec_kernel at n +// column tiles a block (capped at 16, refused on a shape it does not serve). Applies inside the +// decode form only, which r4d_moe_gemm_pin_prefill(2) pins. Bit-identical. void r4d_moe_gemm_pin_down_dec(int pin); -// THE GATED RESIDUAL READ'S PREFILL TILE, pinned for a test: 0 is the launcher's rule, 1 the decode +// Test hook: pins the gated residual read's prefill tile. 0 is the launcher's rule, 1 the decode // tiles' kernels at 128 rows (hc_down_tiled, then hc_up_tiled into `ubuf` and hc_mix), 2 the wide -// kernels (which then refuse a shape they are not built for), 3 the PF2 kernels the rule takes from -// 512 rows (refused likewise, and also at a band under 512 rows, whose scratch is not sized for -// their weight planes). All are bit-identical by construction, and r4d_selftest compares their -// bytes. +// kernels (refusing shapes they are not built for), 3 the PF2 kernels the rule takes from 512 rows +// (refused likewise, and below 512 rows, whose scratch is not sized for their weight planes). +// All bit-identical; r4d_selftest compares their bytes. void r4d_hc_read_pin_prefill(int form); -// THE SAME NARROW GEMM WITH r4d_gated_quant_fp8's PASS IN ITS EPILOGUE, for a gate_up projection -// whose only consumer is that quantiser. `wq` is the [2*nout][K] gate_up plane -- gate first, the -// layout the unfused GEMM already reads -- and the outputs are the quantiser's, not the GEMM's: -// `q` E4M3 [M][nout], `s` f32 [M][ceil(nout/128)], and `y` the bf16 silu product or 0. +// Test hook: records the function each launch dispatches into `fns[0..cap)`, in order, until the +// next call, and returns how many launches the previous recording saw (which may exceed its cap). +// Null `fns` stops recording. r4d_selftest uses it to show that a pinned form dispatches a kernel +// of its own, so a pin that is ignored cannot pass by comparing a form with itself. +int r4d_record_dispatches(const void** fns, int cap); +// The narrow GEMM with r4d_gated_quant_fp8 as its epilogue, for a gate_up projection whose only +// consumer is that quantiser. `wq` is the [2*nout][K] gate_up plane, gate first; outputs are the +// quantiser's: `q` E4M3 [M][nout], `s` f32 [M][ceil(nout/128)], and `y` the bf16 silu product or 0. // -// BYTE-IDENTICAL to the pair, and unlike the split above that is a property this is written to -// hold: the accumulator is rounded to bf16 first and the gate, the product and the amax are all -// taken over the round-tripped values, which is what a GEMM that stores a tensor and a quantiser -// that reads it back compute. `act` is r4d_gated_quant_fp8's, and only 0 (silu) is compiled. +// Byte-identical to the unfused pair: the accumulator is rounded to bf16 first and the gate, +// product and amax are taken over the rounded values. `act` is r4d_gated_quant_fp8's; only 0 +// (silu) is compiled. // -// Refuses -- rather than falling back -- any shape the fold does not fit: M past the band, K not a -// multiple of 256, `nout` not a multiple of 128 (a block emits exactly one 128-column scale group -// and there is nowhere to finish a straddling one), or a grid the split rule would widen. +// Refuses, without fallback, any shape the fold does not fit: M past the band, K not a multiple of +// 256, `nout` not a multiple of 128 (a block emits exactly one 128-column scale group), or a grid +// the split rule would widen. int r4d_gemm_fp8a8_gated_nt_m16(long a, long ascale, long wq, long ws, long q, long s, long y, int act, int M, int K, int nout, @@ -732,15 +655,15 @@ int r4d_gemm_fp8a8_gated_nt_m16_max_m(void); int r4d_gemm_fp8a8_tiled(long a, long ascale, long wq, long ws, long c, int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld, long stream); -// The same two GEMMs at INT8 codes for both operands (r4d_gemm_fp8a8.hip's I8 instantiations): -// the activation i8 with its f32 scale per (row, 128 K) as the fp8 one, the weight i8 in the same -// fragment order with a bf16 scale per ROW per 128 K, tile-major: ws is [N/16][ceil(K/128)][16] -// (r4d_fp8_layout.cpp's i8 hooks write it); sw_ld is not read. +// The same two GEMMs at int8 codes for both operands (r4d_gemm_fp8a8.hip's I8 instantiations): +// the activation i8 with an f32 scale per (row, 128 K), the weight i8 in the same fragment order +// with a bf16 scale per row per 128 K, tile-major: ws is [N/16][ceil(K/128)][16] (written by +// r4d_fp8_layout.cpp's i8 hooks); sw_ld is not read. int r4d_gemm_i8a8_nt_m16(long a, long ascale, long wq, long ws, long c, int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld, long scratch, long scratch_bytes, long stream); -// The lm_head at INT8 codes (logits_gemm_i8): r4d_logits_gemm_fp8's stored row -- codes, the row's -// bf16 scales in its tail, the pad -- with i8 codes and each row's own scale per 128 columns. +// The lm_head at int8 codes: r4d_logits_gemm_fp8's row layout (codes, the row's bf16 scales in its +// tail, the pad) with i8 codes and a scale per 128 columns. int r4d_logits_gemm_i8(long a, long wq, long c, int M, int K, int N, int a_ld, int c_ld, int w_ld, long stream); int r4d_gemm_i8a8_tiled(long a, long ascale, long wq, long ws, long c, @@ -748,49 +671,42 @@ int r4d_gemm_i8a8_tiled(long a, long ascale, long wq, long ws, long c, long stream); int r4d_gemm_fp8a8_block(void); -// Per-(row, 128-column) symmetric E4M3 quantisation of a bf16 activation -- what the two fp8a8 -// GEMMs read. PLAIN ROW-MAJOR output, unlike r4d_quant_act_i8's fragment order: the fp8a8 GEMMs -// stage both operands through the same byte copy and the same swizzle, so a permutation would have -// to be undone. The scale is amax/448, a DEQUANT multiplier in the same sense as the checkpoint's -// weight_scale_inv, so the GEMM multiplies both scales and never divides. +// Per-(row, 128-column) symmetric E4M3 quantisation of a bf16 activation, read by the fp8a8 GEMMs. +// Plain row-major output, unlike r4d_quant_act_i8's fragment order: the fp8a8 GEMMs stage both +// operands through the same byte copy and swizzle. The scale is amax/448, a dequant multiplier +// like the checkpoint's weight_scale_inv, so the GEMM multiplies both scales and never divides. int r4d_quant_act_fp8(long a, long q, long s, int M, int K, int x_ld, int q_ld, int s_ld, long stream); int r4d_quant_act_fp8_group(void); -// The same quantiser riding on the pass that PRODUCED the row, which is where most of a decode -// step's quantise launches come from. Both write the bf16 output the unfused producer wrote AND the -// E4M3 pair, and both quantise the bf16-ROUNDED value so the codes are the ones the unfused pair -// produced -- see r4d_fused_quant_fp8.hip on why that is a requirement and not a nicety. `y` may -// be null where nothing reads the bf16. `w_f32` states the norm gain's width; `mode` is 0 for -// silu and 1 for sigmoid. -// `res` non-null is the fused_add_rms_norm form -- `res += x`, rounded to bf16 and STORED, then -// normalised -- which is bit-for-bit the `add` + `rmsnorm` pair it replaces, and removes one -// launch per block per layer. It may alias `y`. +// The same quantiser fused into the pass that produced the row. Both write the bf16 output the +// unfused producer wrote and the E4M3 pair, quantising the bf16-rounded value so the codes match +// the unfused pair (see r4d_fused_quant_fp8.hip). `y` may be null where nothing reads the bf16. +// `w_f32` gives the norm gain's width; `mode` is 0 for silu and 1 for sigmoid. +// A non-null `res` is the fused_add_rms_norm form: `res += x`, rounded to bf16 and stored, then +// normalised, bit-identical to the `add` + `rmsnorm` pair. It may alias `y`. int r4d_rmsnorm_quant_fp8(long x, long res, long w, long y, long q, long s, int M, int n, float eps, float wadd, int w_f32, int x_ld, int r_ld, int y_ld, int q_ld, int s_ld, long stream); int r4d_gated_quant_fp8(long gu, long y, long q, long s, int M, int n, int mode, int gu_ld, int y_ld, int q_ld, int s_ld, long stream); -// The activation is rounded to bf16 before the product: the unfused pair is `sigmoid` then `mul`, -// two kernels with a bf16 buffer between them, and that round trip is part of what is replaced. -// The same epilogue with the gate in a DIFFERENT buffer from the thing it scales, which is the -// shape a gated attention has: `x` is the attention output and the gate is a column slice of the -// [q|gate] projection. The row is then a (token, head) pair rather than a token -- at that shape -// both sources are a fixed stride apart and the scale plane still lands exactly where the out -// projection reads it. `g` is passed ALREADY OFFSET to the gate half of its row. +// The activation is rounded to bf16 before the product, matching the unfused `sigmoid` then `mul` +// pair with a bf16 buffer between them. +// The same epilogue with the gate in a different buffer from what it scales, as in gated +// attention: `x` is the attention output and the gate a column slice of the [q|gate] projection. +// A row is then a (token, head) pair; both sources are a fixed stride apart and the scale plane +// lands where the out projection reads it. `g` is passed already offset to the gate half. int r4d_gate_quant_fp8(long g, long x, long y, long q, long s, int M, int n, int mode, int g_ld, int x_ld, int y_ld, int q_ld, int s_ld, long stream); -// The same norm again with the tensor-parallel all-reduce that always precedes it folded in. Every -// row-parallel linear's output is all-reduced and then immediately normalised, so the pair is 128 -// adjacent dispatches on a decode step; fused, the all-reduce's bf16 output is never read back and -// the peer's contribution is a second operand on the norm's load. The IPC arguments are -// r4d_ar_oneshot_2rank_exact's; `nblocks` is CLAMPED TO M, because a block owns whole rows, and `x` -// takes no pitch, because it is the message as well as the input. The int8 twin is -// r4d_ar_ln_had_quant_i8, and like it this one carries BOTH wires: `wire` is 0 for the exact bf16 -// payload and 6 for the rotated 6-bit one, which the caller picks the same way the standalone -// all-reduce does. Wire 6 needs `n` to be a multiple of r4d_ar_rmsnorm_quant_fp8_chunk_elems(), -// so that a chunk never straddles a row. +// The same norm with the preceding tensor-parallel all-reduce folded in. Every row-parallel +// linear's output is all-reduced then normalised (128 adjacent dispatches per decode step); fused, +// the all-reduce's bf16 output is never read back and the peer's contribution is a second operand +// on the norm's load. IPC arguments are r4d_ar_oneshot_2rank_exact's; `nblocks` is clamped to M +// because a block owns whole rows, and `x` takes no pitch because it is also the message. Like the +// int8 twin r4d_ar_ln_had_quant_i8 it has two wires: `wire` 0 is the exact bf16 payload, 6 the +// rotated 6-bit one. Wire 6 needs `n` to be a multiple of r4d_ar_rmsnorm_quant_fp8_chunk_elems() +// so a chunk never straddles a row. int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long peer_flags, long my_flags, long seq_ctrs, long slot_stride16, long x, long res, long w, long y, long q, long s, @@ -800,9 +716,9 @@ int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long peer_flag long loc_pack, long loc_scale_off); int r4d_ar_rmsnorm_quant_fp8_chunk_elems(void); -// The same IPC with the sandwich-norm junction after it (r4d_rmsnorm_quant_i8.hip): post-norm of the -// reduced `x` (`wp`), the residual add, the [1] scalar (`sc`), the norm (`w`) and the w4a8 GEMM's -// per-row int8 quantiser. Exact wire only; `x` is the message and takes no pitch. +// The same IPC with the sandwich-norm junction after it (r4d_rmsnorm_quant_i8.hip): post-norm of +// the reduced `x` (`wp`), the residual add, the [1] scalar (`sc`), the norm (`w`) and the w4a8 +// GEMM's per-row int8 quantiser. Exact wire only; `x` is the message and takes no pitch. int r4d_ar_rmsnorm_quant_i8(long peer_scratch, long my_scratch, long peer_flags, long my_flags, long seq_ctrs, long slot_stride16, long x, long res, long w, long wp, long sc, int sc_f32, long y, long q, long s, int M, int n, float eps, @@ -811,53 +727,48 @@ int r4d_ar_rmsnorm_quant_i8(long peer_scratch, long my_scratch, long peer_flags // ---- sampling ---------------------------------------------------------------------------------- // -// One workgroup a position: temperature, softmax, top_k, top_p, min_p, renormalise and the draw, in -// vLLM's order -- reordering changes which tokens survive. Three outputs, because a greedy-draft -// speculative verify needs all of them from one pass: a draw, a draw with the proposed token -// removed and the remainder renormalised, and the proposal's FILTERED probability, which is the -// accept probability under rejection sampling. +// One workgroup a position: temperature, softmax, top_k, top_p, min_p, renormalise and the draw, +// in vLLM's order (reordering changes which tokens survive). Three outputs for a greedy-draft +// speculative verify: a draw, a draw with the proposed token removed and the rest renormalised, +// and the proposal's filtered probability, which is the rejection-sampling accept probability. struct R4DSpecDraw { unsigned int tok; // a draw from the filtered distribution unsigned int tok_excl; // a draw with `query` removed and the remainder renormalised float p_query; // filtered probability of `query` -- the accept probability }; // `logits[pos*col_stride + v*row_stride]`, so either head layout is read without a transpose. -// `query` may be 0; `u` is two uniforms a position. `n_vocab` is the FULL vocabulary: on a -// vocab-parallel rank the caller gathers the other bands first, because a nucleus over half a -// distribution is not a nucleus. +// `query` may be 0; `u` is two uniforms a position. `n_vocab` is the full vocabulary: a +// vocab-parallel rank gathers the other bands first, since a nucleus needs the whole distribution. int r4d_sample_chain_f32(long logits, long query, long u, long out, int M, int n_vocab, int row_stride, int col_stride, float temperature, float top_p, int top_k, float min_p, long stream); // ---------------------------------------------------------------------------- the quantisers // -// THESE TAKE THE PLUGIN ABI'S ARGUMENTS, not a flattened C list: `int r4d_rad_(const -// RadArgs*, RadStream)`, declared in libr4d/r4d_plugin.h because the ROW TABLE is the only -// caller and that header is host-only. The entry point named under each note is the symbol. -// See libr4d/r4d_args.h for why that is the only calling convention libr4d has. +// These take the plugin ABI's arguments: `int r4d_rad_(const RadArgs*, RadStream)`, declared +// in libr4d/r4d_plugin.h because the row table is the only caller and that header is host-only. +// The entry point named under each note is the symbol. See libr4d/r4d_args.h for why this is +// libr4d's only calling convention. // Per-row symmetric int8 quantisation of a bf16 activation, in the A-fragment byte order. The // optional fourth operand asks for the per-row per-group sum of the int8 codes an asymmetric // weight grid needs -- [K/group][Mpad] float, group-major; see r4d_gemm_w4a8_asym_nt_m64. // r4d_rad_quant_act_i8 // Block Hadamard of width `had` along K, then the same per-row int8 quantisation. `had` must be a -// power of two dividing K -- a rotation block cannot cross a tensor-parallel shard boundary, so the -// per-rank K is what it has to divide (5120 / 3072 / 8704 here, which rules 1024 out). +// power of two dividing K; a rotation block cannot cross a tensor-parallel shard, so it must +// divide the per-rank K (5120 / 3072 / 8704 here, which rules 1024 out). // r4d_rad_had_quant_act_i8 -// The residual add, the RMS norm, the same block Hadamard and the same int8 quantiser in ONE pass. -// `residual` and `out_bf16` may be null: pass a residual for vLLM's fused_add_rms_norm form, and an -// out_bf16 only on layers that still have a bf16 consumer of the post-norm tensor (a GDN block's -// in_proj_a / in_proj_b, which stay bf16 and read it unrotated). +// The residual add, the RMS norm, the same block Hadamard and int8 quantiser in one pass. +// `residual` and `out_bf16` may be null: pass a residual for vLLM's fused_add_rms_norm form, and +// out_bf16 only on layers with a bf16 consumer of the post-norm tensor (a GDN block's in_proj_a / +// in_proj_b, which stay bf16 and read it unrotated). // `wadd` is added to every gain element in fp32 after the bf16 load: GemmaRMSNorm (Qwen3.5, -// Qwen3-Next, Gemma) stores a zero-centred gamma and uses `1 + w`, and forming that in bf16 -// first costs 0.3% per channel. Pass 0.0f for a plain RMS norm. +// Qwen3-Next, Gemma) stores a zero-centred gamma and uses `1 + w`, and forming that in bf16 costs +// 0.3% per channel. Pass 0.0f for a plain RMS norm. // r4d_rad_rmsnorm_had_quant_i8 -// The same norm, with the tensor-parallel all-reduce that always precedes it folded in. Every -// row-parallel linear's output is all-reduced and then immediately normalised, so the pair is 128 -// adjacent dispatches on a decode step; fused, the all-reduce's bf16 output never exists and the -// peer's contribution is just a second operand on the norm's load. The IPC arguments are -// r4d_ar_oneshot_2rank_exact's, with the same double-buffered scratch, per-block flags and -// device-resident sequence counters; `nblocks` is CLAMPED TO M, because a block owns whole rows. +// The same norm with the preceding all-reduce folded in, as in r4d_ar_rmsnorm_quant_fp8: IPC +// arguments, double-buffered scratch, per-block flags and device-resident sequence counters +// are r4d_ar_oneshot_2rank_exact's; `nblocks` is clamped to M because a block owns whole rows. void r4d_ar_ln_wire_dims(int* stage_bits, int* chunk_elems, int* chunk_bytes, int* scale_bytes); // The fewest blocks at which [M, K] fits the kernel's LDS at this width and wire (`nthreads` 0 @@ -870,90 +781,81 @@ void r4d_ar_ln_had_quant_i8(long peer_scratch, long my_scratch, long peer_flags, int M, int K, int had, float eps, float wadd, long stream, int nblocks, int nthreads, int drain, int acq, int wire = 0); -// An elementwise gated product, then the same Hadamard and int8 quantiser. Two of the four rotated -// sites have this shape and differ by one multiply: mode 0 is silu(a)*b (down_proj's input, vLLM's -// silu_and_mul) and mode 1 is sigmoid(a)*b (o_proj's input, since Qwen3_5Attention computes -// attn_output * sigmoid(gate)). Strides are in ELEMENTS and may be 0 for a tight K-pitch; pass 2*K -// for vLLM's fused gate_up layout where `b` is `a + K`. +// An elementwise gated product, then the same Hadamard and int8 quantiser. Mode 0 is silu(a)*b +// (down_proj's input, vLLM's silu_and_mul); mode 1 is sigmoid(a)*b (o_proj's input, since +// Qwen3_5Attention computes attn_output * sigmoid(gate)). Strides are in elements and may be 0 for +// a tight K-pitch; pass 2*K for vLLM's fused gate_up layout where `b` is `a + K`. // r4d_rad_gated_had_quant_i8 // The gated-attention QKV preamble: split [q|gate] per head, QK RMS norm, partial NeoX RoPE and -// the gate copy, in one pass. Replaces four elementwise kernels per attention layer. The norm -// output is rounded to bf16 BEFORE the rotation, because the unfused reference stores it and reads -// it back. `wadd` is the GemmaRMSNorm `1 +` (see r4d_rmsnorm_had_quant_i8). Pitches are in -// ELEMENTS. +// the gate copy, in one pass. The norm output is rounded to bf16 before the rotation, because the +// unfused reference stores it and reads it back. `wadd` is the GemmaRMSNorm `1 +` (see +// r4d_rmsnorm_had_quant_i8). Pitches are in elements. // r4d_rad_qk_norm_rope_gate -// Fills the cos/sin table the fused kernel above reads, at each position's OWN row of an -// [max_ctx, rot] plane: `rot` values a row, cos for the first rot/2 and sin for the second. One -// launch a step serves every layer. The arithmetic is r4d_model_bf16.hip's rope_kernel line for -// line, which is what makes the fusion bit-for-bit against the unfused norm + rope pair. +// Fills the cos/sin table the fused kernel above reads, at each position's own row of an +// [max_ctx, rot] plane: `rot` values a row, cos for the first rot/2 and sin for the second. One +// launch a step serves every layer. The arithmetic matches r4d_model_bf16.hip's rope_kernel line +// for line, so the fusion is bit-identical to the unfused norm + rope pair. // r4d_rad_rope_table -// The GDN block's gated RMS norm -- x * rsqrt(mean_head(x^2)+eps) * w * silu(z) over 128-wide heads -// -- then the same Hadamard and int8 quantiser over the flattened row. out_proj's input on the 48 -// linear-attention layers. `wgain` is 128 floats; strides are in elements and may be 0. -// `zgrp`/`zblk` let Z be the INTERLEAVED qkvz projection instead of a compacted gate: element i of -// the flattened row is at (i / zblk) * zgrp + (i % zblk). Pass 0 for a contiguous gate. +// The GDN block's gated RMS norm (x * rsqrt(mean_head(x^2)+eps) * w * silu(z) over 128-wide heads), +// then the same Hadamard and int8 quantiser over the flattened row: out_proj's input on the +// linear-attention layers. `wgain` is 128 floats; strides are in elements and may be 0. +// `zgrp`/`zblk` let Z be the interleaved qkvz projection instead of a compacted gate: element i of +// the flattened row is at (i / zblk) * zgrp + (i % zblk). Pass 0 for a contiguous gate. // r4d_rad_gdn_gated_norm_hq_i8 -// The packed 4-bit weight back to a plain row-major bf16 [N, K], undoing the fragment order. For -// prefill, where W4A8 wins nothing and the skinny GEMM is structurally bad: dequantise a layer into -// a scratch buffer and hand it to the tuned bf16 GEMM. Serves both grids -- the zero comes out of -// the scale dword's high half, which is the constant 8 for symz. -// `twos` says which encoding these bytes carry: 1 for the symmetric grid's two's-complement -// code (value = (n^8)-8, what radiance_w4.pack writes) and 0 for the asymmetric grid's -// unsigned nibble minus a per-group zero. They differ by bit 3 and the wrong one is silently -// wrong -- it agrees for n<8 and is off by 16 above. +// The packed 4-bit weight back to plain row-major bf16 [N, K], undoing the fragment order. For +// prefill, where W4A8 gains nothing: dequantise a layer into scratch and use the bf16 GEMM. Serves +// both grids; the zero comes from the scale dword's high half (the constant 8 for symz). +// `twos` selects the encoding: 1 for the symmetric grid's two's-complement code (value = +// (n^8)-8, what radiance_w4.pack writes), 0 for the asymmetric grid's unsigned nibble minus a +// per-group zero. They differ by bit 3; the wrong one agrees for n<8 and is off by 16 above. void r4d_dequant_w4_bf16(long wq, long ws, long out, int N, int K, int group, int twos, long stream); // ---- the small bf16 model ops (r4d_model_bf16.hip) --------------------------------------------- // -// The embedding gather, the norm, the adds and the rotary that sit BETWEEN the interesting kernels. -// They are here because a step is a chain and a chain with one host link does not run: the buffers -// are in VRAM and the engine refuses an op with no device launch. The arithmetic is libref's -// -- every reduction in f32, only the store narrows, round-to-nearest-even -- because ref is the -// oracle these are compared against. +// The embedding gather, norm, adds and rotary between the larger kernels, on the device because +// the buffers are in VRAM and the engine refuses an op with no device launch. The arithmetic is +// libref's, the oracle they are compared against: every reduction in f32, only the store narrows, +// round-to-nearest-even. // -// Every pitch is in ELEMENTS and 0 means tight. Index arrays are i32 (the engine's derived buffers -// all are). A NEGATIVE index writes a zero row or skips the store; an OUT-OF-RANGE one does the -// same, because a device kernel cannot return a per-row error and a fault is worse than a defined -// answer -- which is why the bounds are arguments. -// `vocab_off` is the first GLOBAL row this rank holds: the table is a vocab-parallel SLICE and an -// id outside it takes the zero-row arm, so summing the ranks reconstructs the embedding. 0 is the -// whole table, an unsliced lookup. +// Every pitch is in elements and 0 means tight. Index arrays are i32. A negative or out-of-range +// index writes a zero row or skips the store: a kernel cannot return a per-row error, and a +// defined answer beats a fault, which is why the bounds are arguments. +// `vocab_off` is the first global row this rank holds: the table is a vocab-parallel slice and an +// id outside it writes zeros, so summing the ranks reconstructs the embedding. 0 means the whole +// table. int r4d_embed_lookup_bf16(long tok, long wte, long x, int M, int n_embd, int n_vocab, int vocab_off, int x_ld, long stream); -// The same lookup with a RUNTIME gather scale on the rows that are found (x = table[id] * -// scale); 1.0 is the plain copy, and a missed row still writes zero rather than zero * scale. -// Gemma 4's embedding is scaled by sqrt(n_embd) at the lookup, not baked into the table. +// The same lookup with a runtime scale on found rows (x = table[id] * scale); 1.0 is the plain +// copy, and a missed row still writes zero. Gemma 4 scales its embedding by sqrt(n_embd) at the +// lookup rather than in the table. int r4d_embed_lookup_bf16_scaled(long tok, long wte, long x, int M, int n_embd, int n_vocab, int vocab_off, int x_ld, float scale, long stream); int r4d_gather_rows_bf16(long x, long idx, long y, int M, int n, int src_rows, int x_ld, int y_ld, long stream); -// y = x * rsqrt(mean(x^2) + eps) * (w + wadd). `wadd` is GemmaRMSNorm's `1 +`, added in f32 after -// the bf16 load for the reason r4d_rmsnorm_had_quant_i8 gives. -// `w_f32` says whether the gain is f32 -- which every norm gain the architecture plugins declare -// is -- or bf16. The activation either side is bf16 in both cases. +// y = x * rsqrt(mean(x^2) + eps) * (w + wadd). `wadd` is GemmaRMSNorm's `1 +`, added in f32 after +// the bf16 load (see r4d_rmsnorm_had_quant_i8). `w_f32` says whether the gain is f32 (as every +// architecture plugin declares it) or bf16; the activation is bf16 either way. int r4d_rmsnorm_bf16(long x, long w, long y, int M, int n, float eps, float wadd, int w_f32, int x_ld, int y_ld, long stream); -// y = x * rsqrt(mean(x^2) + eps). The weightless RMS: the same two-pass sum of squares as rmsnorm -// with the gain multiply dropped, gemma's bare value normalisation. +// y = x * rsqrt(mean(x^2) + eps): rmsnorm without the gain multiply, Gemma's value normalisation. int r4d_rmsnorm_p_bf16(long x, long y, int M, int n, float eps, int x_ld, int y_ld, long stream); -// `op` 0 sums, 1 multiplies. A `b_ld` of 0 is the ONE broadcast form: every row reads the same n -// elements, which is what makes a bias add this op rather than a second one. +// `op` 0 sums, 1 multiplies. A `b_ld` of 0 broadcasts one row of n elements to every row (a bias +// add). int r4d_binary_bf16(long a, long b, long y, int M, int n, int op, int a_ld, int b_ld, int y_ld, long stream); int r4d_sigmoid_bf16(long x, long y, int M, int n, int x_ld, int y_ld, long stream); int r4d_fill_bf16(long y, int M, int n, int y_ld, float value, long stream); -// y[.., i] = silu(gu[.., i]) * gu[.., n + i]. The GATE IS THE FIRST HALF -- the order rad-convert +// y[.., i] = silu(gu[.., i]) * gu[.., n + i]. The gate is the first half, the order rad-convert // fuses gate_proj and up_proj in. int r4d_silu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y_ld, long stream); -// y[.., i] = gelu_tanh(gu[.., i]) * gu[.., n + i]. The GATE IS THE FIRST HALF, the tanh -// approximation (gemma's gelu_pytorch_tanh), not the erf one. +// y[.., i] = gelu_tanh(gu[.., i]) * gu[.., n + i]. The gate is the first half; the tanh +// approximation (Gemma's gelu_pytorch_tanh), not erf. int r4d_gelu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y_ld, long stream); -// In place over `n_rope_heads` consecutive heads of a row; anything after them (the V heads of a -// fused projection) is untouched. `gptj` 0 pairs i with i + rot/2 (NeoX, and mrope, which is the -// same arithmetic when every position component is equal); 1 pairs 2i with 2i+1. `rot` may be less -// than head_dim -- the frequency exponent divides by `rot`, so the rotated prefix is a complete -// rotary of its own width. +// In place over `n_rope_heads` consecutive heads of a row; later heads (the V heads of a fused +// projection) are untouched. `gptj` 0 pairs i with i + rot/2 (NeoX, and mrope when every position +// component is equal); 1 pairs 2i with 2i+1. `rot` may be less than head_dim: the frequency +// exponent divides by `rot`, so the rotated prefix is a complete rotary of its own width. int r4d_rope_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads, int rot, int gptj, float theta, float rscale, int row_pitch, long stream); // The multi-component rotary (docs/OPS.md, `rope`): `mode` 2 mrope, 3 imrope, 4 axial over @@ -964,20 +866,18 @@ int r4d_rope_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads, int int r4d_rope_mc_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads, int rot, int den, int gptj, float theta, float rscale, int row_pitch, int mode, const int* sec, int n_sec, int plane, long stream); -// C[M,N] f32 = A[M,K] bf16 @ W[N,K]^T bf16, f32 accumulate. THE OUTPUT IS f32 and that is why this -// is not r4d_gemm_bf16_nt_m16 under another name: the engine declares its logits buffer f32, -// because a bf16 logit has eight bits of mantissa and a nucleus cut compares neighbouring -// probabilities. K must be a multiple of 8. +// C[M,N] f32 = A[M,K] bf16 @ W[N,K]^T bf16, f32 accumulate. The output is f32 because the +// engine's logits buffer is: a bf16 logit has eight mantissa bits, too coarse for a nucleus cut +// that compares neighbouring probabilities. K must be a multiple of 8. int r4d_logits_gemm_bf16(long a, long w, long c, int M, int K, int N, int a_ld, int c_ld, long stream); // Scatter into kv_cache[n_blocks, kv_heads, block_size, 2*head_dim]: K at [.., d], V at // [.., head_dim + d], slot decomposing as block = slot / block_size, offset = slot % block_size. int r4d_kv_store_bf16(long k, long v, long slot, long kv, int M, int head_dim, int kv_heads, int block_size, int n_blocks, int k_ld, int v_ld, long stream); -// The same scatter into an E4M3 cache, which is what the fp8kv attention family reads. `k_scale` -// and `v_scale` are the DESCALES the reader multiplies back by, so this divides by them; they are -// one number per (sequence, head) on the read side, hence a caller constant here rather than -// anything derived from the tokens being written. 1.0 is vLLM's default and is what the attention +// The same scatter into an E4M3 cache, read by the fp8kv attention family. `k_scale` and `v_scale` +// are the descales the reader multiplies by, so this divides by them; the read side has one per +// (sequence, head), hence a caller constant here. 1.0 is vLLM's default and what the attention // kernels assume when their descale pointers are null. head_dim must be a multiple of 4. int r4d_kv_store_fp8(long k, long v, long slot, long kv, int M, int head_dim, int kv_heads, int block_size, int n_blocks, int k_ld, int v_ld, @@ -985,28 +885,24 @@ int r4d_kv_store_fp8(long k, long v, long slot, long kv, int M, int head_dim, in // ---- the decomposed sampler chain (r4d_sample_stages_f32.hip) ----------------------------------- // -// docs/OPS.md's eleven ops, one entry point each, as opposed to r4d_sample_chain_f32's fused form. -// Both exist and neither replaces the other: the fused one is right when the order is fixed and is -// what a speculative verify wants; these are what an engine that composes the chain per request -// needs, and they carry the stages the fused one has no room for -- penalties, DRY, a grammar -// bitmask, locally-typical, XTC. +// docs/OPS.md's eleven ops, one entry point each, beside r4d_sample_chain_f32's fused form. The +// fused one suits a fixed order and a speculative verify; these let an engine compose the chain +// per request and add the stages the fused one lacks: penalties, DRY, a grammar bitmask, +// locally-typical, XTC. // -// `params` is an array of abi/rad_sample.h's RadSampleParams, one row per sampled -// position. This unit includes that header rather than restating the struct, so there is nothing -// for a caller to check the two layouts of. Logits are f32. A dropped candidate is index -1, -// value -infinity, and the buffers never shrink. +// `params` is an array of abi/rad_sample.h's RadSampleParams, one row per sampled position; the +// header is included, not restated. Logits are f32. A dropped candidate is index -1, value +// -infinity, and the buffers never shrink. // // The entry points are r4d_rad_sample_{temp,mask,penalties,dry,argmax,topk,topp,minp,typical,xtc, -// pick,merge_topk}, declared in libr4d/r4d_plugin.h with the plugin ABI's signature. The -// flattened `(long lg, long params, int M, ...)` launch forms are private to -// r4d_sample_stages_f32.hip -- see the note at the entry points there. +// pick,merge_topk}, declared in libr4d/r4d_plugin.h with the plugin ABI's signature. The flattened +// `(long lg, long params, int M, ...)` launch forms are private to r4d_sample_stages_f32.hip. // // Exact top-k: a radix select over the monotone logit key, a second over the token id to break a -// tie at the threshold by the LOWER id, then a bitonic sort of the survivors -- descending, which -// every later stage assumes. The optional `pairs` plane is the vocab-parallel path: (u32 global -// id, f32 logit) pairs with vocab_off already added, which is what the all-gather moves and what -// the merge reads. The merge RE-APPLIES the row's top_k -- each rank ran its own before the -// gather, so the merged set holds up to world_size * k where the request asked for k, and nothing -// downstream narrows again. At k = 1 that is the difference between an argmax and a draw. +// tie at the threshold by the lower id, then a descending bitonic sort of the survivors, which +// every later stage assumes. The optional `pairs` plane is the vocab-parallel path: (u32 global +// id, f32 logit) pairs with vocab_off added, what the all-gather moves and the merge reads. The +// merge re-applies the row's top_k: each rank kept k, so the merged set holds up to +// world_size * k and nothing downstream narrows again (at k = 1 it would no longer be an argmax). } diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index b4a825cd..1283c5f1 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -1,29 +1,21 @@ -/* The all-reduce shims, and the init/fini that make them possible. +/* The all-reduce shims, and the init/fini they need. * - * THIS IS WHY init/fini EXIST IN THE ABI (spec §2.1). libr4d's all-reduces handshake through peer - * signal buffers and an IPC scratch region that has to be allocated on every rank, published to - * every other rank, and made peer-accessible BEFORE the first launch. None of that can happen on - * the step path -- it allocates, it synchronises, and it needs every rank present. + * init/fini exist in the ABI for this (spec §2.1): libr4d's all-reduces handshake through peer + * signal buffers and a scratch region that must be allocated on every rank, published to every + * other rank and made peer-accessible before the first launch. That allocates, synchronises and + * needs every rank, so it cannot run on the step path. * - * THE EXCHANGE IS NOT IPC HERE, AND THAT IS THE POINT. A one-process-per-rank layout has no - * choice: hipIpcGetMemHandle on each rank, a collective gather of the 64-byte handles, - * hipIpcOpenMemHandle on the other side. Radiance runs ONE PROCESS with one thread per rank sharing - * an address space (spec §1). A device pointer allocated on rank 0's card is already a valid - * address on rank 1's card once hipDeviceEnablePeerAccess has run -- that is what unified virtual - * addressing means within a process -- so the "handle exchange" degenerates to writing a pointer - * into a shared array and waiting on a barrier. The single-process path (`r4d_ar_ipc_enable_peer`) - * IS the runtime path. + * No IPC handles: radiance runs one process with a thread per rank sharing an address space + * (spec §1). Once hipDeviceEnablePeerAccess has run, a device pointer from rank 0's card is valid + * on rank 1's card (unified virtual addressing), so the exchange is a pointer written to a shared + * array plus a barrier (`r4d_ar_ipc_enable_peer`). This avoids handle marshalling and + * hipIpcOpenMemHandle, which maps a second VA range for the same pages and must be closed in order + * at shutdown. * - * What that buys, concretely: no 64-byte handle marshalling, no hipIpcOpenMemHandle (which maps a - * second VA range for the same physical pages and has to be closed in the right order at - * shutdown), and no serialisation layer between ranks at all -- which is most of what a Python - * engine spends its multiprocessing budget on. - * - * THE BARRIER ASSUMES EVERY RANK RUNS THE SAME DECLARE. It does: rad_arch_declare runs once per - * rank with the same architecture plugin and the same model, so the Nth all-reduce instance on - * rank 0 is the Nth on every other rank. The rendezvous is therefore keyed on nothing but arrival - * order, and a rank that declares a different graph deadlocks at startup with a 60-second timeout - * and a named error rather than corrupting a later step. + * The barrier assumes every rank runs the same declare: rad_arch_declare runs once per rank with + * the same plugin and model, so the Nth all-reduce instance is the Nth on every rank and the + * rendezvous is keyed on arrival order alone. A rank declaring a different graph fails at startup + * with a 60-second timeout and a named error. */ #include "r4d_args.h" @@ -44,10 +36,9 @@ static_assert(R4D_MAX_RANKS == 8, "the 8-rank entry point names exactly seven pe /* ------------------------------------------------------------------ throw conversion * - * The all-reduce family is the half of libr4d that THROWS instead of returning. Errors are values - * here, so every call is wrapped. The shim pre-checks everything - * the entry point throws about, so a throw that still escapes is a library or device fault rather - * than a bad call -- which is why it becomes RAD_E_DEVICE and prints once with the text. */ + * The all-reduce entry points throw; the ABI returns error codes, so every call is wrapped. The + * shim pre-checks everything the entry points throw about, so an escaping throw is a library or + * device fault: it becomes RAD_E_DEVICE and is printed once. */ static int r4d_caught(const char* who, const char* what) { static bool said = false; if (!said) { @@ -82,10 +73,9 @@ struct Rendezvous { Rendezvous g_rv; -/* Sense-reversing barrier on a monotone epoch, so a rank that wakes and immediately re-enters for - * the next instance cannot be counted twice. The timeout is not a recovery path -- a startup - * deadlock is fatal either way -- it is there so the failure is a named error at declare instead - * of a hung process with no output. */ +/* Sense-reversing barrier on a monotone epoch, so a rank that wakes and re-enters for the next + * instance cannot be counted twice. The timeout is not recovery; it turns a startup deadlock into + * a named error instead of a silent hang. */ int rv_barrier(int world) { std::unique_lock lk(g_rv.m); const int e = g_rv.epoch; @@ -101,33 +91,30 @@ int rv_barrier(int world) { } /* One resolved instance's view of the world: its own buffers and its peers', the latter in - * ASCENDING GLOBAL RANK WITH THIS RANK REMOVED, which is the order libr4d's wide entry points - * take their pointer arguments in. */ + * ascending global rank with this rank removed (the order libr4d's wide entry points take). */ struct ArInst { int rank = 0, world = 0; long my_scratch = 0, my_flags = 0, my_seq = 0, locpack = 0; long peer_scratch[R4D_MAX_PEERS] = { 0 }; long peer_flags [R4D_MAX_PEERS] = { 0 }; long slot_bytes = 0; /* per-slot capacity, 16-byte aligned */ - long slot16 = 0; /* the same in 16-byte words, which is what most take */ + long slot16 = 0; /* the same in 16-byte words */ long max_numel = 0; /* the declared bound the sizing was computed from */ int esize = 2; int dtype = 0; /* libr4d code: 0 bf16, 1 fp16, 2 fp32 */ - int max_blocks = 0; /* what the flag array was sized for -- a hard bound */ - /* What a LAUNCH is allowed to ask for, which is a much smaller number and a different kind of - * number. max_blocks is a capacity; this is a tuning. Every block drives its own flag - * handshake, so block count buys parallel pushes up to the point the link saturates and after - * that buys nothing but round trips: at a 2048-token prefill chunk the capacity rule asks for - * 936 blocks and the tuning rule asks for 24. */ + int max_blocks = 0; /* what the flag array was sized for; a hard bound */ + /* Block count a launch may use: a tuning, unlike the max_blocks capacity. Each block drives its + * own flag handshake, so more blocks help only until the link saturates, then add round trips + * (at a 2048-token chunk the capacity allows 936 blocks; 24 is used). */ int nb_cap = 0; - /* Where the exchange buffers live: 0 in each rank's own VRAM, written by its peers over P2P; - * 1 in pinned host memory that every card reaches over its own link (build, below). */ + /* Exchange buffers: 0 in each rank's VRAM, written by peers over P2P; 1 in pinned host memory + * each card reaches over its own link (see build). */ int host = 0; long gate_ctr = 0; /* the blocks that have seen their peer's bytes land (r4d_ar_seq.h) */ }; -/* A parameter that may have been declared as a RANGE: init is handed the frozen geometry for one - * band, and the band's UPPER bound is what a buffer has to be sized for. */ +/* A parameter that may be declared as a range: init gets one band's frozen geometry, and buffers + * are sized for the band's upper bound. */ long long pgeti_hi(const RadParam* p, int n_p, const char* k, long long dflt) { if (!p || !k) return dflt; for (int i = 0; i < n_p; ++i) { @@ -140,24 +127,19 @@ long long pgeti_hi(const RadParam* p, int n_p, const char* k, long long dflt) { long align16(long v) { return (v + 15) & ~15L; } -/* The sequence counters' allocation in words: 2 * nbw (r4d_ar_seq.h) and, after them, the block - * counter r4d_ar_link_landed keeps, padded to a cache line. */ +/* Sequence counter allocation in words: 2 * nbw (r4d_ar_seq.h), then r4d_ar_link_landed's block + * counter, padded to a cache line. */ long kSeqWords(long nbw) { return 2L * nbw + 32; } -/* Build the world. `max_numel` is the largest message any launch on this instance will carry. +/* Build the world. `max_numel` is the largest message any launch on this instance carries. * - * ONE SIZING RULE FOR THE WHOLE FAMILY, which is also what libr4d's own driver did ("one set - * serves every kernel in the family"): a slot holds a full message. The one-shots need exactly - * that; the two-shot's two regions are 2 * (message / world_size), which is smaller for every - * world >= 2; and the tiered-int8 wire's two images are 2 * ceil(shard/32) * 38 bytes, smaller - * again. Sizing for the maximum costs the difference in VRAM and removes a per-row branch that - * would otherwise have to reconstruct which kernel this instance is -- RadInitFn is not told. - * That is the one thing missing from the hook: init knows the geometry but not the row. + * One sizing rule for the whole family: a slot holds a full message. The one-shots need exactly + * that; the two-shot's two regions (2 * message / world_size) and the tiered-int8 wire's two + * images (2 * ceil(shard/32) * 38 bytes) are smaller. RadInitFn is not told which row resolved, + * so sizing for the maximum avoids reconstructing which kernel this instance serves. * - * THE COST, NAMED: a slot holds a full message, so at a 4096-token prefill chunk on a 5120-wide - * residual that is 40 MiB a slot and 80 MiB for the pair. ONE set serves every op that resolved - * to the same (rank, world, dtype, bound) -- see the cache below, which is what keeps a 64-layer - * model from building 128 of these. */ + * Cost: at a 4096-token chunk on a 5120-wide residual, 40 MiB a slot and 80 MiB for the pair. One + * set serves every op with the same (rank, world, dtype, bound); see the cache below. */ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, int host) { if (world < 2 || world > R4D_MAX_RANKS) return RAD_E_SHAPE; if (rank < 0 || rank >= world) return RAD_E_INVAL; @@ -181,17 +163,16 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, } if (maxb <= 0) return RAD_E_DEVICE; in->max_blocks = maxb; - /* The launch ceilings are the library driver's (radiance_allreduce.py): 24 at two - * ranks, and at width the library's own design count, which is what that file asks for by - * name. The compressed 2-rank wire runs to 48 and takes it at its own call site -- it moves - * three eighths of the bytes, so it saturates the link with more blocks, not fewer. */ + /* Launch ceilings: 24 at two ranks, the library's design count at width. The compressed + * 2-rank wire uses up to 48, set at its own call site: it moves three eighths of the bytes, so + * it needs more blocks to saturate the link. */ in->nb_cap = (world == 2) ? 24 : (nb_design > 0 ? nb_design : maxb); if (in->nb_cap > maxb) in->nb_cap = maxb; - /* Slots: one per (parity, source rank) at width; at world 2 parity alone names the single - * remote writer, so two. Flags: one word per (block, source rank) at width, one per block at - * world 2. Sequence counters: a handshake word and a parity word per block of capacity - * (r4d_ar_seq.h), device-resident so a captured graph replays. */ + /* Slots: one per (parity, source rank) at width; two at world 2, where there is one remote + * writer. Flags: one word per (block, source rank) at width, one per block at world 2. + * Sequence counters: a handshake and a parity word per block of capacity (r4d_ar_seq.h), + * device-resident so a captured graph replays. */ const int nslots = (world == 2) ? 2 : 2 * world; const long flag_words = (long)maxb * ((world == 2) ? 1 : world); @@ -200,20 +181,16 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, long sc = 0, fl = 0, sq = 0, lp = 0; int dev = 0; - /* FINE-GRAINED: the scratch is written by the peer and read here without going through L2, so - * a coarse-grained allocation would leave the peer's bytes in a cache this rank never - * invalidates. libr4d's driver falls back to coarse when fine fails; so does this, because a - * deterministic fallback stays symmetric across ranks (same environment, same hardware). */ - int fine_sc = 1, fine_fl = 1, fine_sq = 1; - /* WITHOUT PEER ACCESS THE MAILBOX MOVES TO THE HOST, AND NOTHING ELSE CHANGES. Every kernel in - * the family touches another rank only through its scratch slots and its flag words -- its - * input, its output and its sequence counters are its own card's -- so with those two in - * pinned host memory no card ever addresses another card's VRAM, and the same kernels run on a - * machine whose PCIe topology or IOMMU forbids peer traffic. A push then lands in host memory - * over the writer's link and the reduce reads it back over the reader's, so a message crosses - * two links where P2P crosses one; that is the price, and it is paid only where P2P is absent - * (the rows that take this path require device.p2p == 0, r4d_rows.cpp). The sequence counters - * stay in VRAM: only their own rank reads them. */ + /* Fine-grained: the peer writes the scratch and this rank reads it bypassing L2, so a + * coarse-grained allocation could leave the peer's bytes in a cache this rank never + * invalidates, and the launches run without an acquire fence. r4d_ar_ipc_alloc throws when it + * cannot allocate fine-grained memory; there is no coarse fallback. + * + * Without peer access the scratch and flags move to pinned host memory and nothing else + * changes: kernels touch other ranks only through those two, so no card addresses another's + * VRAM. A message then crosses two links instead of one; only rows requiring device.p2p == 0 + * take this path (r4d_rows.cpp). Sequence counters stay in VRAM, since only their own rank + * reads them. */ R4D_TRY("ar_ipc_alloc", if (hipGetDevice(&dev) != hipSuccess) return RAD_E_DEVICE; if (host) { @@ -221,34 +198,13 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, fl = r4d_ar_host_alloc(flag_words * 4); } else { sc = r4d_ar_ipc_alloc((long)nslots * in->slot_bytes, 1, handle, &hlen); - if (!sc) { fine_sc = 0; sc = r4d_ar_ipc_alloc((long)nslots * in->slot_bytes, 0, handle, &hlen); } fl = r4d_ar_ipc_alloc(flag_words * 4, 1, handle, &hlen); - if (!fl) { fine_fl = 0; fl = r4d_ar_ipc_alloc(flag_words * 4, 0, handle, &hlen); } } - sq = r4d_ar_ipc_alloc(kSeqWords(maxb) * 4, 1, handle, &hlen); - if (!sq) { fine_sq = 0; sq = r4d_ar_ipc_alloc(kSeqWords(maxb) * 4, 0, handle, &hlen); }); - if (!sc || !fl || !sq) return RAD_E_NOMEM; + sq = r4d_ar_ipc_alloc(kSeqWords(maxb) * 4, 1, handle, &hlen)); - /* SAY IT, because the fallback above changes what the KERNEL's fence settings mean. The - * launches run acq=0 -- no acquire fence -- on the argument that an uncached read is already - * fresh, and that argument holds for FINE-GRAINED scratch and for nothing else: on a coarse - * allocation the peer's bytes can sit in an L2 this rank never invalidates, and the reduce - * then folds a stale slot. That failure is not a crash and not a wrong shape. It is a sum - * that is occasionally a little wrong, which at greedy decode is a completion that differs - * between runs of the same prompt. Silence here would make that unfindable. */ - if (!fine_sc || !fine_fl || !fine_sq) - std::fprintf(stderr, "[r4d] WARNING: all-reduce scratch is COARSE-GRAINED " - "(scratch %s, flags %s, seq %s). The kernels run without an acquire " - "fence, which is only sound on fine-grained memory -- expect " - "occasional stale peer data.\n", - fine_sc ? "fine" : "COARSE", fine_fl ? "fine" : "COARSE", - fine_sq ? "fine" : "COARSE"); - - /* This rank's own packed copy, for the rotated 6-bit wire only: the reduce has to fold exactly - * the bytes it sent, not a re-derivation of them. The sizing is libr4d's driver's, transcribed - * -- payload at 6 bits an element is 3/8 of the bf16 message and the bf16 scale per group of - * 64 is 1/64 of it, so half the message plus a thirty-second plus a page is generous by - * construction and cheap enough not to tighten. */ + /* This rank's own packed copy, for the rotated 6-bit wire only: the reduce must fold exactly + * the bytes it sent. The 6-bit payload is 3/8 of the bf16 message and the scales 1/64, so half + * the message plus a thirty-second plus a page is ample. */ if (in->dtype != 2) { R4D_TRY("ar_ipc_alloc(locpack)", lp = r4d_ar_ipc_alloc(in->slot_bytes / 2 + in->slot_bytes / 32 + 4096, 0, @@ -271,10 +227,9 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, int rc = rv_barrier(world); if (rc != RAD_OK) return rc; - /* Peer access is a property of THIS rank's context, so every rank enables its own. It has to - * happen after the publish barrier only because that is where the peer device ordinals are - * known -- a host can expose more HIP devices than there are ranks (an integrated part among - * them), so the ordinal is read from the peer rather than assumed to equal the rank. */ + /* Peer access is per context, so each rank enables its own, after the publish barrier where + * peer device ordinals are known. A host can expose more HIP devices than ranks (e.g. an + * integrated GPU), so the ordinal comes from the peer rather than the rank. */ int j = 0; for (int r = 0; r < world; ++r) { if (r == rank) continue; @@ -292,30 +247,20 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, /* ------------------------------------------------------------------ one world, shared * - * ONE INSTANCE PER (rank, world, dtype, message bound), NOT ONE PER OP. The core calls init once - * per resolved instance -- one op, one band, one domain -- and a 64-layer tensor-parallel model - * declares 128 all-reduces with identical parameters. One peer scratch per instance would be - * ruinous, because the scratch is sized by the LARGEST message the band can carry: at a 2048-token - * chunk on a 5120-wide residual that is 21 MiB a slot, two slots, plus the rotated wire's packed - * copy, so about 53 MiB per instance and 6.7 GiB a card for a graph that needs 53 MiB. It is - * allocated straight from hipMalloc rather than out of a radiance pool, so it is invisible to the - * VRAM budget and shows up instead as the KV cache refusing to fit, or as a large prefill chunk - * refusing to start at all. + * One instance per (rank, world, dtype, message bound), not per op. The core calls init per + * resolved instance, and a 64-layer tensor-parallel model declares 128 identical all-reduces. + * Scratch is sized by the largest message (at a 2048-token chunk on a 5120-wide residual, ~53 MiB + * per instance), so per-op instances would cost 6.7 GiB a card. It comes from hipMalloc, outside + * the VRAM budget, so over-allocation shows up as the KV cache or a prefill chunk failing to fit. * - * SHARING IS SAFE AND IS NOT AN OPTIMISATION OF THE HANDSHAKE. The slots are double-buffered by - * the parity of the LAUNCH on this instance and every all-reduce on a rank rides one stream in - * declared order, so all-reduce k+2 -- the next user of k's slot -- cannot launch until k+1 - * completed, which required the peer's k+1 flag, which the peer sets only after its own k+1 - * kernel started, which is after its k kernel finished reading that slot. The same argument is - * why two slots suffice. It needs the parity to be the launch's and not a block's: the ops that - * share an instance run different block counts, so per-block counts drift apart, and a block's - * own parity would let launch k+1 push into bytes a different block of launch k is still reading - * (r4d_ar_seq.h). + * Sharing is safe. Slots are double-buffered by the parity of the launch on this instance, and a + * rank's all-reduces run on one stream in declared order, so all-reduce k+2 (the next user of k's + * slot) cannot launch until k+1 completed, which needed the peer's k+1 flag, set only after the + * peer's k kernel finished reading that slot. This needs the launch's parity, not a block's: ops + * sharing an instance use different block counts (r4d_ar_seq.h). * - * The rendezvous stays symmetric because every rank declares the same graph in the same order - * (rad_arch_declare runs once per rank against one plugin): the Nth all-reduce misses the cache - * on every rank and the (N+1)th hits it on every rank, so a barrier is either entered by - * everybody or by nobody. */ + * The rendezvous stays symmetric because every rank declares the same graph in the same order: + * the Nth all-reduce misses the cache on every rank or on none. */ struct CacheKey { int rank, world, dtype; long long numel; @@ -341,9 +286,9 @@ int acquire(const CacheKey& k, ArInst** out) { for (CacheSlot& s : g_cache) if (s.key == k && s.in) { ++s.refs; *out = s.in; return RAD_OK; } } - /* Built OUTSIDE the lock: build() rendezvouses with the other ranks and holding a mutex - * across that barrier is a deadlock with the peer's own lookup. One declare thread per rank - * and a rank-keyed entry means no two builders race for the same key. */ + /* Built outside the lock: build() rendezvouses with the other ranks, and holding the mutex + * across that barrier would deadlock with the peer's lookup. Keys include the rank and each + * rank has one declare thread, so no two builders race for one key. */ ArInst* in = new (std::nothrow) ArInst(); if (!in) return RAD_E_NOMEM; int rc = build(in, k.rank, k.world, k.numel, k.dtype, k.host); @@ -367,8 +312,7 @@ void release(ArInst* in) { break; } } - /* Only this rank's own allocations. A peer pointer is the peer's to free, and freeing it here - * would be a double free the moment two ranks tear down in either order. */ + /* Free only this rank's own allocations; peer pointers belong to the peer. */ if (in->host) { r4d_ar_host_free(in->my_scratch); r4d_ar_host_free(in->my_flags); @@ -389,10 +333,9 @@ static int ar_init(const RadParam* p, int n_p, int rank, int world, int host, vo if (!out) return RAD_E_INVAL; *out = nullptr; - /* world_size is both an ABI argument and a declared parameter, and they must agree: the - * parameter is what the constraint matched on and the argument is what the engine will - * actually run, so a disagreement means the graph and the process do not describe the same - * deployment. Refusing here is cheaper than finding out at the first handshake. */ + /* world_size is both an ABI argument and a declared parameter. The parameter is what the + * constraint matched; the argument is what the engine runs. A mismatch means the graph and the + * process describe different deployments, so refuse here instead of at the first handshake. */ const long long ws_param = pgeti_hi(p, n_p, "world_size", world); if (ws_param != world) return RAD_E_SHAPE; @@ -416,8 +359,8 @@ extern "C" int r4d_rad_ar_host_init(const RadParam* p, int n_p, int rank, int wo return ar_init(p, n_p, rank, world, 1, out); } -/* The fused all-reduce + norm declares `M`(range) and `n` rather than `numel`: its message is the - * post-projection activation. Same world, same buffers, different arithmetic to get the bound. */ +/* The fused all-reduce + norm declares `M` (range) and `n` instead of `numel`; the bound is + * M * n, over the same world and buffers. */ static int ar_mn_acquire(const RadParam* p, int n_p, int rank, int world, int host, void** out) { const long long M = pgeti_hi(p, n_p, "M", 0); @@ -450,14 +393,11 @@ extern "C" int r4d_rad_ar_ln_host_init(const RadParam* p, int n_p, int rank, int return ar_ln_init(p, n_p, rank, world, 1, out); } -/* The four-rank ar_hc_write and ar_gather_hc_write. The key is the family's -- {rank, 4, bf16, - * M_hi * n} -- so the instance is sized for the most rows the op was declared for, and it is the - * same instance as a standalone all_reduce band's only where the two bounds agree. Either way is - * safe on one stream: every wide kernel takes its flag value from the instance's seq counters, - * advances them once per all-reduce and writes only the (parity, source) slot that value names - * (r4d_ar_wide.h), so ops sharing an instance interleave in any order every rank issues them in, - * and ops on separate instances touch nothing of each other's. Exact wire only: the rows constrain - * `wire` to 0, and a `wire` 6 that reaches this init anyway is refused. */ +/* The four-rank ar_hc_write and ar_gather_hc_write. The key is {rank, 4, bf16, M_hi * n}, shared + * with a standalone all_reduce band only where the bounds agree. Either way is safe on one stream: + * every wide kernel advances the instance's seq counters once per all-reduce and writes only its + * (parity, source) slot (r4d_ar_wide.h), so ops on one instance interleave in any order all ranks + * share. Exact wire only; `wire` 6 is refused. */ static int ar_hc_wide_init(const RadParam* p, int n_p, int rank, int world, int host, void** out) { if (!out) return RAD_E_INVAL; @@ -481,17 +421,16 @@ extern "C" int r4d_rad_ar_hc_wide_host_init(const RadParam* p, int n_p, int rank } extern "C" void r4d_rad_ar_fini(void* instance) { - /* One fini per successful init, and the instance is shared across every op that resolved to - * the same world: the last release frees it. */ + /* One fini per successful init; the instance is shared, so the last release frees it. */ release((ArInst*)instance); } /* ------------------------------------------------------------------ launch helpers */ -/* THE ENGINE'S LINK WORD, where it handed one (rad_abi.h, `link_gate`). Over P2P the fused kernels - * end the hold as the peer's push lands, on either wire, and say so (RAD_LINK_ENDED); through the - * host mailbox it is the reduce that reads those bytes across the link, so those launches return - * RAD_OK and leave the hold to the engine. */ +/* The engine's link word, if it passed one (rad_abi.h, `link_gate`). Over P2P the fused kernels + * end the hold when the peer's push lands, on either wire, and return RAD_LINK_ENDED. Through the + * host mailbox the reduce itself reads across the link, so those launches return RAD_OK and leave + * the hold to the engine. */ static long link_gate(const RadArgs* a) { long long g = 0; return rad_args_geti(a, "link_gate", &g) ? (long)g : 0L; @@ -506,10 +445,9 @@ struct ArCall { int nblocks, nthreads, drain, acq, pub; }; -/* Block count. libr4d takes it as an argument because PCIe saturates with very few blocks and - * everything above that only helps the local reduce, so the right number scales with the message - * and then stops. 1400 sixteen-byte words per block, floor 4, ceiling 24, is the driver's - * rule; a tuned `nblocks` that names a fixed count overrides it. */ +/* Block count. PCIe saturates with very few blocks and more only help the local reduce, so the + * count scales with the message and then stops: 1400 sixteen-byte words per block, floor 4, + * ceiling max_nb. A tuned `nblocks` overrides it. */ static int nb_for(long words16, int max_nb) { long nb = words16 / 1400; if (nb < 4) nb = 4; @@ -518,9 +456,9 @@ static int nb_for(long words16, int max_nb) { return (int)nb; } -/* Shared front half of every all-reduce launch: find the instance, check the message against what - * init sized for, resolve the tuned point. Every kernel of the family runs in place (`y` absent or - * equal to `x`); each says why at its entry. */ +/* Shared front half of every all-reduce launch: find the instance, check the message against + * init's sizing, resolve the tuned point. Every kernel of the family is safe in place (`y` absent + * or equal to `x`); each entry point says why. */ static int ar_setup(const RadArgs* a, ArCall* c, int shard_nb) { const ArInst* in = (const ArInst*)(a ? a->instance : nullptr); if (!in) return RAD_E_STATE; /* init did not run: a core sequencing bug */ @@ -538,95 +476,48 @@ static int ar_setup(const RadArgs* a, ArCall* c, int shard_nb) { if (n <= 0) return RAD_E_SHAPE; if (n > in->max_numel) return RAD_E_SHAPE; /* the peer scratch was sized for max_numel */ - /* The push is a 16-byte vector store and libr4d throws on a message that is not a whole - * number of them; checked here so the throw never happens. */ + /* The push uses 16-byte vector stores and libr4d throws on a partial word; check it here. */ if (((long long)n * in->esize) % 16) return RAD_E_ALIGN; if (!r4d_aligned(x->data, 16)) return RAD_E_ALIGN; if (y && !r4d_aligned(y->data, 16)) return RAD_E_ALIGN; R4dArCfg cfgv; r4d_cfg_ar(a, &cfgv); - const R4dArCfg* cfg = &cfgv; c->in = in; c->inp = r4d_addr(x); c->out = y ? r4d_addr(y) : r4d_addr(x); c->numel = n; - c->nthreads = cfg->nthreads; - c->drain = cfg->drain; - c->acq = cfg->acq; - c->pub = cfg->pub; + c->nthreads = cfgv.nthreads; + c->drain = cfgv.drain; + c->acq = cfgv.acq; + c->pub = cfgv.pub; const long words16 = (long)n * in->esize / 16; const long basis = shard_nb ? words16 / in->world : words16; - /* The two-shots move SHARDS, so they take both the smaller basis and the tighter ceiling: the - * full-message rule over-launches the whole mid band. */ + /* The two-shots move shards, so they use the smaller basis and a tighter ceiling; the + * full-message rule over-launches across the mid band. */ int cap = in->nb_cap; if (shard_nb && cap > 24) cap = 24; - c->nblocks = cfg->nblocks > 0 ? cfg->nblocks : nb_for(basis, cap); + c->nblocks = cfgv.nblocks > 0 ? cfgv.nblocks : nb_for(basis, cap); if (c->nblocks > in->max_blocks) c->nblocks = in->max_blocks; return RAD_OK; } -/* ------------------------------------------------------------------ 2-rank all-gather */ -/* NOT ar_setup: every all-reduce there requires numel(y) == numel(x), and an all-gather's output - * is world_size times its input. The instance, the scratch and the flags are the all-reduce's -- - * a slot holds a full message and this message is the INPUT, so r4d_rad_ar_init sizes it right - * from the same `numel` parameter. */ -extern "C" int r4d_rad_ar_gather_2rank(const RadArgs* a, RadStream s) { - const ArInst* in = (const ArInst*)(a ? a->instance : nullptr); - if (!in) return RAD_E_STATE; /* init did not run: a core sequencing bug */ - if (in->world != 2) return RAD_E_SHAPE; /* the handshake is one peer flag, not a tree */ - - const RadTensor* x = r4d_opt(a, AR_X); - const RadTensor* y = r4d_opt(a, AR_Y); - if (!x || !y) return RAD_E_INVAL; /* the gather has no in-place form */ - if (!r4d_contig(x) || !r4d_contig(y)) return RAD_E_STRIDE; - if (y->data == x->data) return RAD_E_INVAL; - - const long n = (long)r4d_numel(x); - if (n <= 0 || n > in->max_numel) return RAD_E_SHAPE; - /* "y is [world_size * numel] with rank r's contribution at offset r * numel" (docs/OPS.md). - * A y of any other extent is a caller that means something this kernel does not do. */ - if ((long long)r4d_numel(y) != (long long)n * in->world) return RAD_E_SHAPE; - - /* The row width, if the caller asked for the row-interleaved placement. It has to divide the - * message and be a whole number of 16-byte words, both of which libr4d rechecks. */ - const long long row = r4d_pgeti_or(a->p, a->n_p, "row", 0); - if (row < 0 || (row > 0 && (n % row || (row * in->esize) % 16))) return RAD_E_SHAPE; - - /* 16-byte vector stores, and libr4d throws on a message that is not a whole number of them. */ - if (((long long)n * in->esize) % 16) return RAD_E_ALIGN; - if (!r4d_aligned(x->data, 16) || !r4d_aligned(y->data, 16)) return RAD_E_ALIGN; - - R4dArCfg cfgv; - r4d_cfg_ar(a, &cfgv); - const R4dArCfg* cfg = &cfgv; - const long words16 = (long)n * in->esize / 16; - int nblocks = cfg->nblocks > 0 ? cfg->nblocks : nb_for(words16, in->nb_cap); - if (nblocks > in->max_blocks) nblocks = in->max_blocks; - - R4D_TRY("ar_gather_2rank", - r4d_ar_gather_2rank(in->peer_scratch[0], in->my_scratch, in->peer_flags[0], in->my_flags, - in->my_seq, in->slot16, r4d_addr(x), r4d_addr(y), n, in->dtype, - in->rank, (long)row, (long)(uintptr_t)s, nblocks, cfg->nthreads, - cfg->drain, cfg->acq)); - return RAD_OK; -} - -/* ------------------------------------------------------------------ wide (3 / 4 / 8 rank) all-gather - * The gather the 2-rank one cannot be at width: its handshake is one peer flag per block, so the - * wide form takes the wide family's peer arrays and r4d_ar_handshake instead (r4d_ar_wide.h), and - * it rides the SAME instance, scratch, flags and counters as the wide one-shots above -- a slot - * holds a full message here exactly as it does there, and this message is the INPUT. The two - * launchers live in r4d_ar_gather_Nrank.hip, which is the only family unit whose caller is inside - * the plugin, so they are declared here rather than in r4d.h. */ +/* ------------------------------------------------------------------ all-gather + * + * The instance, scratch and flags are the all-reduce's; a slot holds a full input message, so + * r4d_rad_ar_init sizes it from the same `numel` parameter. The wide form uses the wide family's + * peer arrays and r4d_ar_handshake (r4d_ar_wide.h), as the wide one-shots do. Its launchers live in + * r4d_ar_gather_Nrank.hip and are declared here, not in r4d.h, since their only caller is this + * plugin. */ extern "C" void r4d_ar_gather_4rank(long peer_scratch0, long peer_scratch1, long peer_scratch2, long peer_flags0, long peer_flags1, long peer_flags2, long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long row_elems, long stream, - long nblocks, long nthreads, long drain, long acq, long pub); + long nblocks, long nthreads, long drain, long acq, long pub, + long gate, long gate_ctr); extern "C" void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long peer_scratch2, long peer_scratch3, long peer_scratch4, long peer_scratch5, long peer_scratch6, long peer_flags0, long peer_flags1, @@ -637,8 +528,7 @@ extern "C" void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long long stream, long nblocks, long nthreads, long drain, long acq, long pub); -/* Every check the 2-rank gather makes, and the same `row` rule: an all-gather's output is - * world_size times its input, so this is not ar_setup either. */ +/* Not ar_setup: an all-gather's output is world_size times its input. */ static int ar_gather_wide_setup(const RadArgs* a, int ws, const ArInst** out_in, ArCall* c, long long* row_out) { const ArInst* in = (const ArInst*)(a ? a->instance : nullptr); @@ -653,16 +543,12 @@ static int ar_gather_wide_setup(const RadArgs* a, int ws, const ArInst** out_in, const long n = (long)r4d_numel(x); if (n <= 0 || n > in->max_numel) return RAD_E_SHAPE; - /* "y is [world_size * numel] with rank r's contribution at offset r * numel" (docs/OPS.md). - * A y of any other extent is a caller that means something this kernel does not do. */ + /* y is [world_size * numel], rank r's contribution at offset r * numel (docs/OPS.md). */ if ((long long)r4d_numel(y) != (long long)n * in->world) return RAD_E_SHAPE; - /* The row width, if the caller asked for the row-interleaved placement. It has to divide the - * message and be a whole number of 16-byte words, both of which libr4d rechecks. */ const long long row = r4d_pgeti_or(a->p, a->n_p, "row", 0); if (row < 0 || (row > 0 && (n % row || (row * in->esize) % 16))) return RAD_E_SHAPE; - /* 16-byte vector stores, and libr4d throws on a message that is not a whole number of them. */ if (((long long)n * in->esize) % 16) return RAD_E_ALIGN; if (!r4d_aligned(x->data, 16) || !r4d_aligned(y->data, 16)) return RAD_E_ALIGN; @@ -686,6 +572,20 @@ static int ar_gather_wide_setup(const RadArgs* a, int ws, const ArInst** out_in, return RAD_OK; } +extern "C" int r4d_rad_ar_gather_2rank(const RadArgs* a, RadStream s) { + const ArInst* in = nullptr; + ArCall c; + long long row = 0; + int rc = ar_gather_wide_setup(a, 2, &in, &c, &row); + if (rc != RAD_OK) return rc; + R4D_TRY("ar_gather_2rank", + r4d_ar_gather_2rank(in->peer_scratch[0], in->my_scratch, in->peer_flags[0], in->my_flags, + in->my_seq, in->slot16, c.inp, c.out, c.numel, in->dtype, in->rank, + (long)row, (long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, + c.acq)); + return RAD_OK; +} + extern "C" int r4d_rad_ar_gather_3rank(const RadArgs* a, RadStream s) { const ArInst* in = nullptr; ArCall c; @@ -707,13 +607,16 @@ extern "C" int r4d_rad_ar_gather_4rank(const RadArgs* a, RadStream s) { long long row = 0; int rc = ar_gather_wide_setup(a, 4, &in, &c, &row); if (rc != RAD_OK) return rc; + /* One handshake, placement after it local: the release is the one-shot's. */ + const long gate = link_gate(a), early = in->host ? 0L : gate; R4D_TRY("ar_gather_4rank", r4d_ar_gather_4rank(in->peer_scratch[0], in->peer_scratch[1], in->peer_scratch[2], in->peer_flags[0], in->peer_flags[1], in->peer_flags[2], in->my_scratch, in->my_flags, in->my_seq, in->slot16, c.inp, c.out, c.numel, in->dtype, in->rank, (long)row, - (long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq, c.pub)); - return RAD_OK; + (long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq, c.pub, + early, early ? in->gate_ctr : 0L)); + return early ? RAD_LINK_ENDED : RAD_OK; } extern "C" int r4d_rad_ar_gather_8rank(const RadArgs* a, RadStream s) { @@ -750,23 +653,20 @@ extern "C" int r4d_rad_ar_oneshot_2rank_exact(const RadArgs* a, RadStream s) { return RAD_OK; } -/* Where the compressed wire stops paying. A decode step's all-reduce is eight rows of the residual - * stream, 80 KiB, and the exact kernel already moves that at about 92% of what the link delivers - * one way -- the message is on the wire, not in latency, and there is nothing for a 2.4x smaller - * payload to recover against the rotate, the pack and the unpack. A prefill chunk is forty times - * that and squarely bandwidth-bound. So the row is chosen once at declare and the WIRE is chosen - * per launch. */ +/* Below this size the compressed wire does not pay. A decode all-reduce (eight residual rows, + * 80 KiB) already runs at ~92% of one-way link bandwidth on the exact kernel, leaving nothing for a + * 2.4x smaller payload to recover against rotate, pack and unpack. A prefill chunk is 40x larger + * and bandwidth-bound. So the row is chosen at declare and the wire per launch. */ enum { R4D_AR_WHT6_MIN_BYTES = 128 * 1024 }; -/* The compressed path's own ceiling: it moves three eighths of the bytes, so it wants more blocks - * to saturate the same link, not fewer. */ +/* Block ceiling for the compressed path: it moves three eighths of the bytes, so it needs more + * blocks to saturate the same link. */ enum { R4D_AR_WHT6_NB_CAP = 48 }; -/* THE ROTATED WIRE'S FUSED WRITES RUN 512 THREADS A BLOCK, not the axis's 1024. Their waves are - * latency-bound on the reads behind the message -- the routed rows of the gather, the streams of - * the write -- and at a 2048-row chunk half the waves a block, twice as many blocks resident, - * is 5-9% faster per call (gather 491 us against 536, write 317 against 329) where 96 or 192 - * blocks of 1024 do not help. */ +/* The rotated wire's fused writes run 512 threads per block, not 1024. Their waves are + * latency-bound on the gather's routed rows and the write's streams; at a 2048-row chunk, twice as + * many resident blocks of half the size is 5-9% faster per call, while 96 or 192 blocks of 1024 + * do not help. */ enum { R4D_AR_WHT6_FUSED_THREADS = 512 }; extern "C" int r4d_rad_ar_oneshot_2rank_wht6(const RadArgs* a, RadStream s) { @@ -780,12 +680,10 @@ extern "C" int r4d_rad_ar_oneshot_2rank_wht6(const RadArgs* a, RadStream s) { int group = 0, bits = 0, chunk = 0; r4d_ar_wht6_dims(&group, &bits, &chunk); - /* THE SIZE GATE. Below the floor -- or on a message the rotation's group does not tile -- this - * row serves the message with the EXACT kernel instead. That is safe and it is not a - * workaround: the two kernels share this instance's scratch, flags and sequence counters and - * publish in one flag value space, so a stream that mixes them is protocol-safe, which is the - * property libr4d's driver relies on to make the same choice per call. A caller that needs the - * rotated wire unconditionally asks for a floor of 0. */ + /* Size gate: below the floor, or when the rotation's group does not tile the message, use the + * exact kernel. Both share this instance's scratch, flags and sequence counters and one flag + * value space, so mixing them on a stream is protocol-safe. A floor of 0 forces the rotated + * wire. */ const long long floor_b = r4d_pgeti_or(a->p, a->n_p, "min_bytes", R4D_AR_WHT6_MIN_BYTES); const long long msg_b = (long long)c.numel * c.in->esize; if (group <= 0 || c.numel % group || msg_b < floor_b) { @@ -799,8 +697,7 @@ extern "C" int r4d_rad_ar_oneshot_2rank_wht6(const RadArgs* a, RadStream s) { R4dArCfg cfgv; r4d_cfg_ar(a, &cfgv); - const R4dArCfg* cfg = &cfgv; - if (cfg && cfg->nblocks <= 0) { + if (cfgv.nblocks <= 0) { int nb = nb_for((long)msg_b / 16, R4D_AR_WHT6_NB_CAP); if (nb > c.in->max_blocks) nb = c.in->max_blocks; c.nblocks = nb; @@ -817,12 +714,12 @@ extern "C" int r4d_rad_ar_oneshot_2rank_wht6(const RadArgs* a, RadStream s) { /* ------------------------------------------------------------------ wide (3 / 4 / 8 rank) * - * The peer arguments are ascending global rank with the current rank removed, which is exactly - * the order build() filled peer_scratch/peer_flags in. */ + * Peer arguments are in ascending global rank with the current rank removed, the order build() + * filled peer_scratch/peer_flags in. */ -/* The one-shots run in place: the thread that stores word k of the output is the one that read - * word k of the input, for its push and again as its own term of the fold, and peers read only - * their own scratch (r4d_ar_oneshot_Nrank_exact.hip). */ +/* The one-shots are safe in place: the thread that stores output word k is the one that read + * input word k (for its push and its own term of the fold), and peers read only their own scratch + * (r4d_ar_oneshot_Nrank_exact.hip). */ extern "C" int r4d_rad_ar_oneshot_3rank_exact(const RadArgs* a, RadStream s) { ArCall c; int rc = ar_setup(a, &c, 0); @@ -845,14 +742,19 @@ extern "C" int r4d_rad_ar_oneshot_4rank_exact(const RadArgs* a, RadStream s) { if (rc != RAD_OK) return rc; if (c.in->world != 4) return RAD_E_SHAPE; const ArInst* in = c.in; + /* The wide release, the two-rank family's rule: over P2P the kernel ends the engine's hold + * itself once the peers' pushes have landed (the kernel after the handshake is local VRAM + * traffic); through the host mailbox the reduce reads the bytes across the link, so early + * stays 0 and the engine releases by barrier. */ + const long gate = link_gate(a), early = in->host ? 0L : gate; R4D_TRY("ar_oneshot_4rank_exact", r4d_ar_oneshot_4rank_exact(in->peer_scratch[0], in->peer_scratch[1], in->peer_scratch[2], in->peer_flags[0], in->peer_flags[1], in->peer_flags[2], in->my_scratch, in->my_flags, in->my_seq, in->slot16, c.inp, c.out, c.numel, in->dtype, in->rank, (long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq, - c.pub)); - return RAD_OK; + c.pub, early, early ? in->gate_ctr : 0L)); + return early ? RAD_LINK_ENDED : RAD_OK; } extern "C" int r4d_rad_ar_oneshot_8rank_exact(const RadArgs* a, RadStream s) { @@ -875,22 +777,16 @@ extern "C" int r4d_rad_ar_oneshot_8rank_exact(const RadArgs* a, RadStream s) { return RAD_OK; } -/* The two-shots shard the message, so their block count scales with the SHARD -- a full-message - * count over-launches the whole mid band. +/* The two-shots shard the message, so their block count scales with the shard. * - * IN PLACE IS SAFE (r4d_ar_twoshot_Nrank_exact.hip). A thread takes one set of word offsets k - * within a shard and uses it in all three phases: the push reads word k of every peer's shard out - * of the input, the reduce reads word k of its own shard and stores the sum over it, and the - * assemble writes word k of every peer's shard. Each input word is therefore overwritten only by - * the thread that already read it, later in its own program order, and no peer reads this rank's - * input -- peers read their own scratch. The selector hands the two-shot the messages above the - * one-shot's size bound (r4d_rows.cpp, cArTsExact4). */ -/* AT THREE RANKS THE SHARDS ARE UNEVEN, so there is no divisibility to check: a 2048-wide bf16 - * row is 256 words and a step's message is 256 * rows of them, a multiple of 3 only one step in - * three. The kernel gives the first (words % 3) shards one word more, the slot holds two of the - * longest, and the fold is the one-shot's -- fp32, ascending rank order -- so the two rows that - * share this op produce the same bits and the band edge between them moves nothing a request - * could see. */ + * In place is safe (r4d_ar_twoshot_Nrank_exact.hip): a thread uses the same word offsets k in all + * three phases (push reads word k of every peer's shard, reduce overwrites word k of its own, + * assemble writes word k of every peer's shard), so each input word is overwritten only by the + * thread that already read it, and peers read only their own scratch. The selector gives the + * two-shot messages above the one-shot's size bound (r4d_rows.cpp, cArTsExact4). */ +/* At three ranks the shards are uneven, so there is no divisibility check: the first + * (words % 3) shards get one extra word and the slot holds two of the longest. The fold is the + * one-shot's (fp32, ascending rank), so the band edge between the two rows changes no bits. */ extern "C" int r4d_rad_ar_twoshot_3rank_exact(const RadArgs* a, RadStream s) { ArCall c; int rc = ar_setup(a, &c, 1); @@ -918,20 +814,22 @@ extern "C" int r4d_rad_ar_twoshot_4rank_exact(const RadArgs* a, RadStream s) { if (rc != RAD_OK) return rc; if (c.in->world != 4) return RAD_E_SHAPE; if (c.numel > R4D_AR_TWOSHOT_WIDE_MAX_ELEMS) return RAD_E_SHAPE; - /* The message must shard evenly over the ranks in whole 16-byte words, and 2*shard must fit - * the slot -- both are throws in the entry point. */ + /* The message must shard evenly in whole 16-byte words and 2*shard must fit the slot. */ const long words16 = c.numel * c.in->esize / 16; if (words16 % c.in->world) return RAD_E_SHAPE; if (2 * (c.numel * c.in->esize) / c.in->world > c.in->slot_bytes) return RAD_E_SCRATCH; const ArInst* in = c.in; + /* The kernel ends the hold after its second handshake (its reduce is fused with the phase-2 + * push); through the host mailbox early stays 0 and the engine releases by barrier. */ + const long gate = link_gate(a), early = in->host ? 0L : gate; R4D_TRY("ar_twoshot_4rank_exact", r4d_ar_twoshot_4rank_exact(in->peer_scratch[0], in->peer_scratch[1], in->peer_scratch[2], in->peer_flags[0], in->peer_flags[1], in->peer_flags[2], in->my_scratch, in->my_flags, in->my_seq, in->slot16, c.inp, c.out, c.numel, in->dtype, in->rank, (long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq, - c.pub)); - return RAD_OK; + c.pub, early, early ? in->gate_ctr : 0L)); + return early ? RAD_LINK_ENDED : RAD_OK; } extern "C" int r4d_rad_ar_twoshot_8rank_exact(const RadArgs* a, RadStream s) { @@ -958,21 +856,17 @@ extern "C" int r4d_rad_ar_twoshot_8rank_exact(const RadArgs* a, RadStream s) { return RAD_OK; } -/* The tiered-int8 wire. Its slot stride is in BYTES, not 16-byte words: the wire is 38 bytes per - * group of 32 and so is not 16-byte aligned at all. +/* The tiered-int8 wire. Its slot stride is in bytes, not 16-byte words: the wire is 38 bytes per + * group of 32. * - * It is the only lossy row at four ranks, so a lossy request resolves it at every message size. As - * in r4d_rad_ar_oneshot_2rank_wht6, a message under `min_bytes` (or one the groups do not tile) - * goes to the exact one-shot. The default floor is the two-rank wire's: every block declares - * `min_bytes` from --tp-wire-min-kb, so the default serves only a caller that leaves it out, and no - * four-rank crossover has been measured to set another. In place is safe for the exact two-shot's - * reason: a thread owns the same 8 elements of a shard in all three phases, reads them from the - * input before it writes them, and no peer reads this rank's input. */ -/* The same wire at three ranks, over the uneven two-shot (r4d_ar_twoshot_Nrank_ti8.hip): the only - * lossy row at three, so as at four a lossy request resolves it at every size and a message - * under `min_bytes` -- or one that is not whole 32-element groups -- goes to the exact one-shot. - * A 2048-wide row is 64 groups, so the residual is always whole groups; what it rarely is, is a - * multiple of three groups, and the kernel's split does not need it to be. */ + * It is the only lossy row at three and four ranks, so a lossy request resolves it at every size. + * As in r4d_rad_ar_oneshot_2rank_wht6, a message under `min_bytes` (or not whole groups) goes to + * the exact one-shot. The default floor is the two-rank wire's; blocks declare `min_bytes` from + * --tp-wire-min-kb, and no four-rank crossover has been measured. In place is safe for the exact + * two-shot's reason: a thread owns the same 8 elements of a shard in all phases and reads them + * before writing them, and no peer reads this rank's input. */ +/* Three ranks run over the uneven two-shot (r4d_ar_twoshot_Nrank_ti8.hip), so the group count + * need not divide by three. */ extern "C" int r4d_rad_ar_twoshot_3rank_ti8(const RadArgs* a, RadStream s) { ArCall c; int rc = ar_setup(a, &c, 1); @@ -987,11 +881,11 @@ extern "C" int r4d_rad_ar_twoshot_3rank_ti8(const RadArgs* a, RadStream s) { const long n_groups = c.numel / group; if ((long long)c.numel * c.in->esize < floor_b || c.numel % group || n_groups < c.in->world) return r4d_rad_ar_oneshot_3rank_exact(a, s); - /* The slot holds two wire images of the LONGEST shard. */ + /* The slot holds two wire images of the longest shard. */ const long sg = (n_groups + c.in->world - 1) / c.in->world; const long wire = (sg * group_bytes + 15) / 16 * 16; if (2 * wire > c.in->slot_bytes) return RAD_E_SCRATCH; - /* nthreads must be a multiple of the encoder's group width -- a throw in the entry point. */ + /* nthreads must be a multiple of the encoder's group width; the entry point throws otherwise. */ if (c.nthreads % 32) return RAD_E_INVAL; const ArInst* in = c.in; @@ -1018,21 +912,22 @@ extern "C" int r4d_rad_ar_twoshot_4rank_ti8(const RadArgs* a, RadStream s) { const long long floor_b = r4d_pgeti_or(a->p, a->n_p, "min_bytes", R4D_AR_WHT6_MIN_BYTES); if ((long long)c.numel * c.in->esize < floor_b || c.numel % ((long)group * c.in->world)) return r4d_rad_ar_oneshot_4rank_exact(a, s); - /* The slot holds two wire images of one shard. */ - const long wire = (c.numel / c.in->world / group) * group_bytes; + /* The slot holds two wire images of one shard, each 16-byte aligned. */ + const long wire = ((c.numel / c.in->world / group) * group_bytes + 15) / 16 * 16; if (2 * wire > c.in->slot_bytes) return RAD_E_SCRATCH; - /* nthreads must be a multiple of the encoder's group width -- a throw in the entry point. */ if (c.nthreads % 32) return RAD_E_INVAL; const ArInst* in = c.in; + /* Released after the second handshake, as in the exact two-shot. */ + const long gate = link_gate(a), early = in->host ? 0L : gate; R4D_TRY("ar_twoshot_4rank_ti8", r4d_ar_twoshot_4rank_ti8(in->peer_scratch[0], in->peer_scratch[1], in->peer_scratch[2], in->peer_flags[0], in->peer_flags[1], in->peer_flags[2], in->my_scratch, in->my_flags, in->my_seq, in->slot_bytes, c.inp, c.out, c.numel, in->dtype, in->rank, (long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq, - c.pub)); - return RAD_OK; + c.pub, early, early ? in->gate_ctr : 0L)); + return early ? RAD_LINK_ENDED : RAD_OK; } /* ------------------------------------------------------------------ the fused all-reduce + norm */ @@ -1052,7 +947,7 @@ extern "C" int r4d_rad_ar_ln_had_quant_i8(const RadArgs* a, RadStream s) { const RadTensor* ob = r4d_opt(a, AL_OUTBF16); if (!x || !w || !q || !sc) return RAD_E_INVAL; if (x->rank < 2 || q->rank < 2) return RAD_E_SHAPE; - /* One workgroup owns whole rows and walks them with a vector load: nothing here is pitched. */ + /* A workgroup owns whole rows and walks them with vector loads, so nothing may be pitched. */ if (!r4d_contig(x) || !r4d_contig(q) || !r4d_contig(w) || !r4d_contig(sc)) return RAD_E_STRIDE; if (rs && !r4d_contig(rs)) return RAD_E_STRIDE; @@ -1069,7 +964,7 @@ extern "C" int r4d_rad_ar_ln_had_quant_i8(const RadArgs* a, RadStream s) { const float eps = (float)r4d_getf(a, "eps", 1e-6); const float wadd = (float)r4d_getf(a, "wadd", 0.0); - /* Everything the entry point throws about, checked here so it does not have to. */ + /* Everything the entry point throws about, checked here. */ if (K % 16) return RAD_E_SHAPE; if (had < 2 || (had & (had - 1))) return RAD_E_INVAL; if (had != 128 && had != 256 && had != 512) return RAD_E_SHAPE; @@ -1083,20 +978,17 @@ extern "C" int r4d_rad_ar_ln_had_quant_i8(const RadArgs* a, RadStream s) { R4dArCfg cfgv; r4d_cfg_ar(a, &cfgv); - const R4dArCfg* cfg = &cfgv; - int nthreads = cfg->nthreads; + int nthreads = cfgv.nthreads; if (nthreads != 128 && nthreads != 256 && nthreads != 512 && nthreads != 1024) return RAD_E_INVAL; - /* `nblocks` is CLAMPED TO M inside the kernel because a block owns whole rows; clamping here - * too keeps the number this shim reports and the number the kernel runs the same. */ - int nblocks = cfg->nblocks > 0 ? cfg->nblocks : nb_for(M * K * 2 / 16, in->max_blocks); + /* The entry point clamps nblocks to M (a block owns whole rows); clamping here too keeps the + * shim's count equal to the kernel's. */ + int nblocks = cfgv.nblocks > 0 ? cfgv.nblocks : nb_for(M * K * 2 / 16, in->max_blocks); if (nblocks > (int)M) nblocks = (int)M; - /* THE LDS FLOOR ON THE BLOCK COUNT. The compressed wire stages every row a block owns, so a - * count chosen for the push alone hands a block more rows than LDS holds -- at K = 5120 that - * is anything past two -- and the launch is refused from M = 9 up. Raising the count to the - * kernel's own floor serves those shapes; a shape no count below the flag capacity serves is - * refused here by name instead of thrown on in the entry point. Block count changes no bytes: - * a block owns whole rows and every reduction closes over one. */ + /* LDS floor on the block count. The compressed wire stages every row a block owns, so a count + * chosen for the push alone can exceed LDS (at K = 5120, more than two rows per block). Raise + * the count to the kernel's floor; refuse shapes no count within the flag capacity serves. + * Block count changes no bytes, since every reduction closes over one row. */ const int nb_min = r4d_ar_ln_blocks_min((int)M, (int)K, (int)had, nthreads, wire); if (nb_min < 1 || nb_min > in->max_blocks) return RAD_E_SHAPE; if (nblocks < nb_min) nblocks = nb_min; @@ -1107,25 +999,21 @@ extern "C" int r4d_rad_ar_ln_had_quant_i8(const RadArgs* a, RadStream s) { r4d_addr(x), r4d_addr(rs), r4d_addr(w), r4d_addr(ob), r4d_addr(q), r4d_addr(sc), (int)M, (int)K, (int)had, eps, wadd, - (long)(uintptr_t)s, nblocks, nthreads, cfg->drain, cfg->acq, + (long)(uintptr_t)s, nblocks, nthreads, cfgv.drain, cfgv.acq, wire)); return RAD_OK; } -/* The fp8 twin: deliberately the same shim as the int8 form with the Hadamard rotation taken out. +/* The fp8 counterpart: the int8 shim without the Hadamard rotation. * - * `x` IS INOUT HERE, which is the one operand difference from the int8 form: that kernel keeps the - * reduced row in LDS and never writes it, while this one stores it back exactly as the standalone - * all-reduce does -- so a reader of `x` that is not the norm still finds the bytes the unfused - * pair would have left, and the buffer planner has to know `x` is written. That holds on both - * wires. + * `x` is inout here, unlike the int8 form (which keeps the reduced row in LDS): the reduced row is + * stored back as the standalone all-reduce does, so other readers of `x` see the unfused pair's + * bytes. This holds on both wires. * - * `wire` is read and passed through, 0 for the exact bf16 payload and 6 for the rotated 6-bit one. - * The architecture asks the same question the standalone `all_reduce` row answers -- an install - * that forbids a lossy wire, a message the rotation's group does not tile, or a message under - * --tp-wire-min-kb -- and both ranks evaluate it on the same T, so neither can take a different - * branch. Wire 6 additionally needs a chunk not to straddle a row; that is a shape this shim - * refuses rather than a decision it makes. */ + * `wire` is passed through: 0 for exact bf16, 6 for the rotated 6-bit payload. The architecture + * chooses it as the standalone `all_reduce` row would (lossy wire allowed, group tiles the message, + * size above --tp-wire-min-kb), and both ranks decide on the same T. A wire-6 chunk that would + * straddle a row is refused as a shape. */ extern "C" int r4d_rad_ar_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) { const ArInst* in = (const ArInst*)(a ? a->instance : nullptr); if (!in) return RAD_E_STATE; @@ -1140,14 +1028,14 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) { if (!x || !w || !q || !sc) return RAD_E_INVAL; if (!r4d_contig(w)) return RAD_E_STRIDE; - /* Rank 2 everywhere, and for rmsnorm_quant_fp8's reason: a norm has a gain per channel, so - * "everything after dim 0 is the row" would put one gain across several heads. */ + /* Rank 2 everywhere, as in rmsnorm_quant_fp8: a norm has a gain per channel, so flattening + * everything after dim 0 into the row would put one gain across several heads. */ if (x->rank != 2 || q->rank != 2 || sc->rank != 2) return RAD_E_SHAPE; if (ob && ob->rank != 2) return RAD_E_SHAPE; const long long M = x->shape[0], K = x->shape[1]; if (M < 1 || K < 1) return RAD_E_SHAPE; if (M * K > in->max_numel) return RAD_E_SHAPE; - /* A row must be a whole number of 16B words, because a block pushes its rows as words. */ + /* A row must be whole 16B words, since a block pushes its rows as words. */ if (K % 8) return RAD_E_SHAPE; const long long grp = r4d_quant_act_fp8_group(); @@ -1159,8 +1047,7 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) { if (sc->shape[0] != M || sc->shape[1] != nkb) return RAD_E_SHAPE; if (ob && (ob->shape[0] != M || ob->shape[1] != K)) return RAD_E_SHAPE; if (rs && (rs->rank != 2 || rs->shape[0] != M || rs->shape[1] != K)) return RAD_E_SHAPE; - /* x IS THE MESSAGE, so its rows must be where the push says they are: tight. The other - * operands may be pitched and the entry point takes their pitches. */ + /* x is the message, so it must be tight; other operands may be pitched. */ const long long xp = r4d_row_pitch(x), qp = r4d_row_pitch(q), sp = r4d_row_pitch(sc); const long long yp = ob ? r4d_row_pitch(ob) : 0, rp = rs ? r4d_row_pitch(rs) : 0; if (xp < 0 || qp < 0 || sp < 0 || yp < 0 || rp < 0) return RAD_E_STRIDE; @@ -1168,7 +1055,7 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) { const float eps = (float)r4d_getf(a, "eps", 1e-6); const float wadd = (float)r4d_getf(a, "wadd", 0.0); - /* The gain's width is read off the operand, exactly as rmsnorm_quant_fp8's shim reads it. */ + /* Gain dtype comes from the operand, as in rmsnorm_quant_fp8's shim. */ const int w_f32 = w->dtype == RAD_F32; const int wire = (int)r4d_geti_or(a, "wire", 0); @@ -1176,59 +1063,32 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) { if (wire == 6) { const int ce = r4d_ar_rmsnorm_quant_fp8_chunk_elems(); if (ce <= 0 || K % ce) return RAD_E_SHAPE; - /* The side buffer holding this rank's own packed half. Allocated for every bf16 instance, - * so its absence is a broken init rather than a shape this row declines. */ + /* This rank's packed-half side buffer exists for every bf16 instance; missing means a + * broken init. */ if (!in->locpack) return RAD_E_STATE; } R4dArCfg cfgv; r4d_cfg_ar(a, &cfgv); - const R4dArCfg* cfg = &cfgv; - /* THE WIDTH IS NOT A TUNING KNOB ON THIS ROW: passing the tuned `nthreads` through here is a - * latent output change. It decides which columns a thread accumulates into the sum of squares, - * so the fused kernel and the standalone `rmsnorm_quant_fp8` it stands in for must pick the - * same one -- and the standalone asks r4d_act_threads(M, n), whose answer DEPENDS ON M: 1024 to - * 32 rows and 512 above. Every point in the all-reduce space pins a width (the default is - * 1024), so at M = 64 -- eight concurrent sequences at DFlash2 depth 7 -- a pinned width would - * sum a row in a different order from the kernel it replaces and move the generated text. The - * divergence is invisible on the exact wire alone, because that band tops out at one sequence. - * - * Zero means "the norm's width" and the entry point resolves it from M. The tuned - * block count, drain and acq are still honoured: those change no bytes. */ + /* The width is not tunable here: it decides which columns a thread accumulates into the sum of + * squares, so it must match the standalone rmsnorm_quant_fp8, which uses r4d_act_threads(M, n) + * (1024 up to 32 rows, 512 above). A pinned width would change the summation order, and the + * generated text, at M = 64. Zero means the norm's width, resolved from M by the entry point. + * The tuned block count, drain and acq change no bytes and are honoured. */ const int nthreads = 0; - /* ONE BLOCK A ROW, which is the NORM's shape and not the all-reduce's, and the two halves - * genuinely want different numbers. The push saturates the fabric at four blocks and every - * block past that pays its own flag round trip over it (r4d_ar_ln_had_quant_i8.hip carries the - * block sweep); the norm's sum of squares closes over a whole row, so a block holding two rows - * does them one after the other and the second waits for the first. The norm wins that - * argument by a wide margin: at nb_for()'s 4 blocks the fused kernel gives back more in - * serialised rows than the saved dispatch is worth. M is eight at one concurrent sequence and - * sixty-four at eight, so one block a row is a block count the fabric is comfortable with - * either way, and on wire 6 it also hands every block a whole row's worth of chunks to rotate. - * A tuned `nblocks` may name a smaller number; the LDS the compressed wire needs then grows - * with the rows a block owns, and the entry point refuses what will not fit. + /* One block per row, the norm's shape rather than the all-reduce's. The push saturates the + * fabric at four blocks, but the norm serialises the rows a block owns, which costs more than + * the saved dispatch; M is 8 to 64 at decode, a block count the fabric handles. nb_cap (24, the + * push's number) is the wrong ceiling: at M = 64 it would serialise three rows per block. * - * `nb_cap` IS THE WRONG CEILING HERE. It is 24 at world 2 and it is the PUSH's number: past - * four blocks the fabric is saturated and every block after that is another flag round trip. - * The norm's number is M. Below 24 rows they do not conflict and above them they do -- at - * M = 64 a capped form runs 24 blocks of three rows and does those three IN SEQUENCE, against - * the standalone norm's 64 blocks of one, and a row's norm is two barriers and a handful of - * elements a thread. + * Cap at 256. The wire alone prefers ~64 blocks, but a 2048-row chunk at 64 gives each block 32 + * serial rows, costing several times what the wire gains; 256 is the combined knee and 512 is + * within noise. At decode, nblocks is simply M. * - * So: one block a row, under a cap of 256. The wire prefers a low cap -- its own knee is near - * 64 blocks -- but a prefill chunk of 2048 rows under a cap of 64 hands every block - * THIRTY-TWO rows to do in sequence, and those serialised norms cost several times what the - * wire gains. 256 is the knee of the combined cost and 512 is inside its noise. Nothing at - * decode is affected: M is at most 64 there (eight sequences at DFlash2 depth 7), so - * `nblocks = min(M, cap)` is simply M. - * - * BLOCK COUNT CHANGES NO BYTES either way: a block owns whole rows, the wire's chunk of 512 - * tiles a row, and every reduction closes over one row, so no element's arithmetic depends on - * which block held it. - * - * The caps are not reachable at decode sizes; they are here because a block count is a hard - * bound on the flag array and a tuned `nblocks` may name any number it likes. */ - int nblocks = cfg->nblocks > 0 ? cfg->nblocks : (int)M; + * Block count changes no bytes: a block owns whole rows, the wire's 512-element chunk tiles a + * row, and every reduction closes over one row. A tuned `nblocks` may name a smaller count; the + * entry point refuses one whose LDS does not fit. The caps bound the flag array. */ + int nblocks = cfgv.nblocks > 0 ? cfgv.nblocks : (int)M; if (nblocks > (int)M) nblocks = (int)M; constexpr int kNbCap = 256; if (nblocks > kNbCap) nblocks = kNbCap; @@ -1241,18 +1101,16 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) { in->slot16, r4d_addr(x), r4d_addr(rs), r4d_addr(w), r4d_addr(ob), r4d_addr(q), r4d_addr(sc), (int)M, (int)K, eps, wadd, w_f32, (int)rp, (int)yp, (int)qp, (int)sp, - (long)(uintptr_t)s, nblocks, nthreads, cfg->drain, cfg->acq, wire, + (long)(uintptr_t)s, nblocks, nthreads, cfgv.drain, cfgv.acq, wire, in->locpack, in->slot_bytes / 2); return e == 0 ? RAD_OK : RAD_E_SHAPE; } -/* THE ALL-REDUCE AND THE SANDWICH-NORM JUNCTION AFTER IT, int8 out: `all_reduce` (exact) of `x`, then - * `rmsnorm_quant_i8` -- post-norm of the reduced x, the residual add, the scalar, the norm and the - * per-row int8 quantiser the w4a8 skinny GEMM reads. Operands are rmsnorm_quant_i8's with `x` - * INOUT, because it is the message and the reduced sum lands back in it. The exact wire only: a - * deployment that allows the lossy one keeps the standalone all-reduce. Width and block count as - * ar_rmsnorm_quant_fp8 resolves them, for the same reasons: the norm's width from M, one block a - * row. */ +/* The all-reduce and the sandwich-norm junction after it, int8 out: exact `all_reduce` of `x`, then + * `rmsnorm_quant_i8` (post-norm of the reduced x, residual add, scalar, norm and the per-row int8 + * quantiser the w4a8 skinny GEMM reads). Operands are rmsnorm_quant_i8's with `x` inout, since the + * reduced sum lands back in it. Exact wire only; a lossy deployment keeps the standalone + * all-reduce. Width and block count as in ar_rmsnorm_quant_fp8. */ enum { AQ8_X = 0, AQ8_RES, AQ8_W, AQ8_Q, AQ8_S, AQ8_Y, AQ8_WP, AQ8_SC }; extern "C" int r4d_rad_ar_rmsnorm_quant_i8(const RadArgs* a, RadStream s) { @@ -1302,27 +1160,25 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_i8(const RadArgs* a, RadStream s) { return e == 0 ? RAD_OK : RAD_E_SHAPE; } -/* THE ALL-REDUCE WITH THE GATED RESIDUAL'S WRITE IN IT: `all_reduce` of `y` and then `hc_write` - * of the reduced `y` into `h`, one kernel. A block whose output feeds a hyper-connection write - * skips its own collective when this runs, and the write carries it. +/* The all-reduce with the gated residual write: `all_reduce` of `y`, then `hc_write` of the reduced + * `y` into `h`, in one kernel. A block whose output feeds a hyper-connection write skips its own + * collective when this runs. * - * `y` IS THE MESSAGE and is pushed as 16B words, so it must be tight -- the same rule the fused - * norm states. The streams may be pitched; each is written as whole 16B words, which n and the - * pitch being multiples of eight guarantee. + * `y` is the message, pushed as 16B words, so it must be tight. The streams may be pitched; n and + * the pitch being multiples of eight keep every write whole 16B words. * - * `wire` is 0 for the exact bf16 payload and 6 for the rotated 6-bit one, and it is the op's and - * not the message's: the architecture declares one op a wire and issues the one ar_wire_is_exact - * picks for the step, which both ranks decide from the same T. So a wire-6 op is 6 at every size, - * with no floor of its own. */ + * `wire` (0 exact bf16, 6 rotated 6-bit) belongs to the op, not the message: the architecture + * declares one op per wire and issues the one ar_wire_is_exact picks for the step, decided on both + * ranks from the same T. A wire-6 op is 6 at every size, with no floor. */ enum { AH_Y = 0, AH_INJ, AH_H }; /* ---- ar_gather_hc_write: moe_gather, then ar_hc_write, in one kernel. Operands: * [0] y_expert [1] expert_w [2] sorted_tok [3] shared? [4] shared_gate? [5] y [6] inj [7] h - * The first five are moe_gather's and the last three ar_hc_write's; see those two. `wire` is - * ar_hc_write's; wire 6 builds its slot table in LDS at every size and takes no scratch. */ + * The first five are moe_gather's and the last three ar_hc_write's. `wire` is as in ar_hc_write; + * wire 6 builds its slot table in LDS at every size and needs no scratch. */ enum { AG_YE = 0, AG_EW, AG_SORTED, AG_SH, AG_SG, AG_Y, AG_INJ, AG_H }; -/* The operand and shape rules ar_gather_hc_write states at every width: moe_gather's five and +/* ar_gather_hc_write's operand and shape rules at every width: moe_gather's five operands, * ar_hc_write's three, and the inverse table's scratch. */ struct GatherHcWriteArgs { const RadTensor *ye = nullptr, *ew = nullptr, *so = nullptr, *sh = nullptr, *sg = nullptr; @@ -1359,7 +1215,7 @@ static int ar_gather_hc_write_args(const RadArgs* a, const ArInst* in, GatherHcW if (hrow % 8) return RAD_E_ALIGN; if (!r4d_aligned(y->data, 16) || !r4d_aligned(h->data, 16)) return RAD_E_ALIGN; - /* moe_gather's side: the same pitches and the same shared-arm pair. */ + /* moe_gather's side: its pitches and the shared-arm pair. */ const long long T = M * top_k; long long Te = 0, Mw = 0; const long long ye_ld = r4d_rows_pitch(ye, n, &Te); @@ -1449,13 +1305,11 @@ extern "C" int r4d_rad_ar_gather_hc_write(const RadArgs* a, RadStream s) { return early ? RAD_LINK_ENDED : RAD_OK; } -/* AT FOUR RANKS, EXACT WIRE ONLY: r4d_rad_ar_hc_write_4rank with the gather in front, on an - * instance from the same init (r4d_rad_ar_hc_wide_init). The architecture issues it only on a step - * whose write takes the exact fused form (ar_exact_write_takes, arch/common/rad_fp8.h) and whose - * gather is one pass's. - * The block count is that write's rule, widened by the launcher until a block's slot table fits in - * LDS -- or, where that would take more blocks than the rule asks for and the scratch is there, - * kept and served from the inverse table, as at two ranks. */ +/* Four ranks, exact wire only: r4d_rad_ar_hc_write_4rank with the gather in front, on an instance + * from r4d_rad_ar_hc_wide_init. Issued only on steps whose write takes the exact fused form + * (ar_exact_write_takes, arch/common/rad_fp8.h) and whose gather is a single pass. The block count + * is the write's rule, widened by the launcher until a block's slot table fits in LDS, or, when + * that needs more blocks and scratch is present, kept and served from the inverse table. */ extern "C" int r4d_rad_ar_gather_hc_write_4rank(const RadArgs* a, RadStream s) { const ArInst* in = (const ArInst*)(a ? a->instance : nullptr); if (!in) return RAD_E_STATE; @@ -1472,6 +1326,7 @@ extern "C" int r4d_rad_ar_gather_hc_write_4rank(const RadArgs* a, RadStream s) { const long words16 = (long)(g.M * g.n * 2 / 16); int nblocks = cfgv.nblocks > 0 ? cfgv.nblocks : nb_for(words16, in->nb_cap); if (nblocks > in->max_blocks) nblocks = in->max_blocks; + const long gate = link_gate(a), early = in->host ? 0L : gate; R4D_TRY("ar_gather_hc_write_4rank", r4d_ar_gather_hc_write_4rank( @@ -1483,19 +1338,20 @@ extern "C" int r4d_rad_ar_gather_hc_write_4rank(const RadArgs* a, RadStream s) { g.sh ? r4d_addr(g.sh) : 0L, g.sh ? r4d_addr(g.sg) : 0L, (long)g.ye_ld, (long)g.ew_ld, (long)g.sh_ld, (long)g.sg_ld, (long)g.top_k, (long)g.sig, (long)in->rank, (long)(uintptr_t)s, nblocks, cfgv.nthreads, cfgv.drain, cfgv.acq, - cfgv.pub, g.has_inv ? (long)(uintptr_t)a->scratch : 0L)); - return RAD_OK; + cfgv.pub, g.has_inv ? (long)(uintptr_t)a->scratch : 0L, early, + early ? in->gate_ctr : 0L)); + return early ? RAD_LINK_ENDED : RAD_OK; } -/* The inverse slot table the exact wire's prefill form reads: one int a (token, slot) at the - * band's M. The rotated wire's table is in LDS. */ +/* Inverse slot table for the exact wire's prefill form: one int per (token, slot) at the band's M. + * The rotated wire keeps its table in LDS. */ extern "C" int64_t r4d_rad_ar_gather_hc_write_scratch(const RadArgs* a) { if (r4d_geti_or(a, "wire", 0) == 6) return 0; const long long M = r4d_geti_or(a, "M", 0), k = r4d_geti_or(a, "top_k", 0); return M > 0 && k > 0 ? M * k * (int64_t)sizeof(int) : 0; } -/* The operand and shape rules ar_hc_write states at every width. */ +/* ar_hc_write's operand and shape rules at every width. */ struct HcWriteArgs { const RadTensor* y = nullptr; const RadTensor* inj = nullptr; @@ -1577,17 +1433,14 @@ extern "C" int r4d_rad_ar_hc_write(const RadArgs* a, RadStream s) { return early ? RAD_LINK_ENDED : RAD_OK; } -/* AT FOUR RANKS, EXACT WIRE ONLY: the wide one-shot with the write as its epilogue. The four-rank - * lossy wire is the ti8 two-shot and has no fused form: the row constrains `wire` to 0, and a - * `wire` 6 that reaches this entry anyway is refused. Every message up to the instance's bound is - * served correctly here as a one-shot. Which steps take it is the caller's choice -- the - * architecture issues it on decode and verify steps (ar_wide_write_exact, arch/common/rad_fp8.h) -- - * and a message the standalone all_reduce's bands would have sent as a two-shot costs more traffic - * here for the same bytes. +/* Four ranks, exact wire only: the wide one-shot with the write as its epilogue. The four-rank + * lossy wire (the ti8 two-shot) has no fused form, so `wire` 6 is refused. Any message up to the + * instance's bound is correct here as a one-shot; the architecture issues it on decode and verify + * steps (ar_wide_write_exact, arch/common/rad_fp8.h), since a message the standalone bands would + * send as a two-shot costs more traffic here. * - * The block count is the plain one-shot's rule (ar_setup's nb_for over the whole message under - * nb_cap); a block's words, flags and slot are the one-shot's, which is what lets the two share an - * instance where their keys agree. */ + * Block count follows the plain one-shot's rule (nb_for over the whole message under nb_cap); + * words, flags and slot match the one-shot's, so the two can share an instance. */ extern "C" int r4d_rad_ar_hc_write_4rank(const RadArgs* a, RadStream s) { const ArInst* in = (const ArInst*)(a ? a->instance : nullptr); if (!in) return RAD_E_STATE; @@ -1604,6 +1457,9 @@ extern "C" int r4d_rad_ar_hc_write_4rank(const RadArgs* a, RadStream s) { const long words16 = (long)(w.M * w.n * 2 / 16); int nblocks = cfgv.nblocks > 0 ? cfgv.nblocks : nb_for(words16, in->nb_cap); if (nblocks > in->max_blocks) nblocks = in->max_blocks; + /* The two-rank fused write's release, at width: the reduce and the write behind the + * handshake are local VRAM traffic, so the kernel ends the hold once the pushes land. */ + const long gate = link_gate(a), early = in->host ? 0L : gate; R4D_TRY("ar_hc_write_4rank", r4d_ar_hc_write_4rank(in->peer_scratch[0], in->peer_scratch[1], in->peer_scratch[2], @@ -1612,6 +1468,7 @@ extern "C" int r4d_rad_ar_hc_write_4rank(const RadArgs* a, RadStream s) { r4d_addr(w.y), r4d_addr(w.inj), r4d_addr(w.h), (long)w.M, (long)w.n, (long)w.hc, (long)w.irow, (long)w.hrow, (long)in->rank, (long)(uintptr_t)s, nblocks, cfgv.nthreads, - cfgv.drain, cfgv.acq, cfgv.pub)); - return RAD_OK; + cfgv.drain, cfgv.acq, cfgv.pub, early, + early ? in->gate_ctr : 0L)); + return early ? RAD_LINK_ENDED : RAD_OK; } diff --git a/libr4d/r4d_ar_gather_2rank.hip b/libr4d/r4d_ar_gather_2rank.hip index e3d296b8..3d1461f2 100644 --- a/libr4d/r4d_ar_gather_2rank.hip +++ b/libr4d/r4d_ar_gather_2rank.hip @@ -1,25 +1,18 @@ // r4d_ar_gather_2rank.hip: r4d_ar_gather_2rank -- multi-block one-shot P2P all-GATHER, exactly two // ranks, for dual R9700 (gfx1201/RDNA4, PCIe). // -// WHY IT EXISTS AS A KERNEL AND NOT AS A COPY. r4d_ar_oneshot_2rank_exact.hip says of -// r4d_p2p_copy2d that a strided device-to-device copy "is what an ALL-GATHER between two ranks is -// once the peer's buffer is IPC-mapped", and that is true of the DATA MOVEMENT and false of the -// whole operation: a copy carries no handshake, so the reader has no way to know the writer's -// bytes have landed. Ordering that with a separate fence plus a barrier collective is three -// launches and a second rendezvous to keep aligned with this one. This is the same kernel as the -// one-shot all-reduce with the reduction removed -- same push, same per-block flag protocol, same -// double-buffered slot -- and it is a separate file rather than a template variant because the -// all-reduce's shape (out is numel) and this one's (out is world_size * numel) differ. +// A kernel rather than r4d_p2p_copy2d: a copy moves the data but carries no handshake, so the +// reader cannot know the writer's bytes have landed, and ordering it with a fence plus a barrier +// collective costs three launches and a second rendezvous. This is the one-shot all-reduce minus +// the reduction (same push, per-block flag protocol and double-buffered slot); it is a separate +// file because the output shapes differ (numel vs world_size * numel). // -// WHAT IT IS FOR. The vocab-parallel sampler. lm_head is row-sharded, so each rank reduces its own -// slice of the vocabulary to k candidates and only the CANDIDATE SETS are combined: at 4 rows and -// 1024 candidates the message is 32 KiB, against the ~1 GiB a full-logits gather would move. The -// payload is (u32 global token id, f32 logit) pairs, which is why this MOVES bytes and does not -// sum them -- adding two f32 lanes would work on the logit and destroy the id, whose bit pattern -// at any real vocabulary size is an f32 denormal. +// Used by the vocab-parallel sampler. lm_head is row-sharded, so each rank reduces its vocabulary +// slice to k candidates and only the candidate sets are combined (32 KiB at 4 rows x 1024 +// candidates, against ~1 GiB for full logits). The payload is (u32 token id, f32 logit) pairs, +// so the bytes are moved, never summed. // -// The element type is therefore irrelevant beyond its size: `dtype` is taken for symmetry with the -// rest of the family and used only to turn n_elem into bytes. +// `dtype` only converts n_elem to bytes. #include "r4d.h" #include "r4d_ar_seq.h" #include @@ -36,19 +29,16 @@ __device__ __forceinline__ unsigned int r4d_g_load_acq(const unsigned int* p) { return __hip_atomic_load(p, __ATOMIC_ACQUIRE, __HIP_MEMORY_SCOPE_SYSTEM); } -// WHERE A RANK'S WORDS LAND. `row16` is one ROW of this rank's contribution, in 16-byte words. +// Where a rank's words land. `row16` is one row of this rank's contribution, in 16-byte words. // -// row16 <= 0 or row16 == n16 -- one row: rank r's whole slice at r * n16, the plain -// concatenation an all-gather is usually taken to mean. -// otherwise -- ROW-INTERLEAVED: the input is [rows][row16] and the output is -// [rows][world][row16], so row m carries every rank's words for +// row16 <= 0 or row16 == n16 -- one row: rank r's whole slice at r * n16 (plain concatenation). +// otherwise -- row-interleaved: input [rows][row16], output +// [rows][world][row16], so row m holds every rank's words for // that row side by side. // -// The second form is the one the vocab-parallel sampler needs and it is not a convenience. The -// merge that consumes this reads ONE ROW of gathered candidates per sampled position, at a single -// row stride; the concatenated form puts rank 1's row m a whole message away from rank 0's, which -// no row stride can express. Interleaving here costs one division per word in a kernel that moves -// 32 KiB and saves a transpose launch on the step path. +// The vocab-parallel sampler's merge reads one row of gathered candidates per position at a single +// row stride, which the concatenated form cannot express. Interleaving costs one division per word +// and saves a transpose launch. __device__ __forceinline__ int r4d_g_dst(int k, int row16, int n16, int who) { if (row16 <= 0 || row16 >= n16) return who * n16 + k; const int m = k / row16, c = k - m * row16; @@ -56,7 +46,7 @@ __device__ __forceinline__ int r4d_g_dst(int k, int row16, int n16, int who) { } // Block b owns words [start,end) of the 16B-word space and drives its own flag handshake; no -// cross-block sync, exactly as in the all-reduce. +// cross-block sync, as in the all-reduce. __global__ void r4d_ar_gather_2rank_kernel( const int4* __restrict__ in4, int4* peer_base, const int4* my_base, int4* __restrict__ out4, unsigned int* peer_flags, unsigned int* my_flags, unsigned int* seq_ctrs, @@ -73,8 +63,8 @@ __global__ void r4d_ar_gather_2rank_kernel( const int start = b * w; int end = start + w; if (end > n16) end = n16; - // push chunk -> peer slot, and place this rank's own slice while the push is in flight: it is a - // local store that needs no handshake, so it costs nothing to hide here. + // 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. { int k = start + tid; for (; k + 3 * nt < end; k += 4 * nt) { @@ -87,8 +77,8 @@ __global__ void r4d_ar_gather_2rank_kernel( } for (; k < end; k += nt) { int4 v = in4[k]; ps[k] = v; out4[r4d_g_dst(k, row16, n16, rank)] = v; } } - // Drain modes, identical to the all-reduce's: they order the pushes against the release flag so - // the peer cannot see the flag before the data. + // Drain modes, as in the all-reduce: order the pushes before the release flag so the peer cannot + // see the flag before the data. if (drain == 1) __threadfence_system(); else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory"); __syncthreads(); @@ -96,8 +86,8 @@ __global__ void r4d_ar_gather_2rank_kernel( if (drain == 2) __threadfence_system(); r4d_g_store_rel(&peer_flags[b], s); unsigned long long z = 0; - // A handshake that cannot complete is a lockstep violation, and placing a slot the peer never - // filled would pass stale bytes on as the peer's, so it traps instead. + // A handshake that cannot complete is a lockstep violation; trap rather than pass on stale + // bytes as the peer's. while (r4d_ar_seq_behind(r4d_g_load_acq(&my_flags[b]), s)) { if (++z > R4D_AR_GATHER_SPIN_MAX) __builtin_trap(); } @@ -105,7 +95,7 @@ __global__ void r4d_ar_gather_2rank_kernel( __syncthreads(); if (acq) __threadfence_system(); - // The peer's slice, now staged in this rank's scratch, into the places that name it. + // Place the peer's slice, now staged in this rank's scratch. { const int who = 1 - rank; int k = start + tid; @@ -128,9 +118,10 @@ void r4d_ar_gather_2rank(long peer_scratch, long my_scratch, long peer_flags, lo const long nbytes = (long)n_elem * esize; if (nbytes % 16 != 0) throw std::runtime_error("all_gather: n_elem*esize not 16B-aligned"); if (rank != 0 && rank != 1) throw std::runtime_error("all_gather: rank must be 0 or 1"); + if (nbytes / 16 > slot_stride16) throw std::runtime_error("all_gather: message larger than a slot"); const int n16 = (int)(nbytes / 16); - // One row of this rank's contribution, in 16-byte words. Zero means "one row", which is the - // plain concatenation; anything else has to divide evenly or a row would straddle a word. + // One row of this rank's contribution, in 16-byte words. Zero means one row (plain + // concatenation); otherwise rows must be whole 16-byte words and divide the message. long rowb = (long)row_elems * esize; if (row_elems > 0 && (rowb % 16 != 0 || nbytes % rowb != 0)) throw std::runtime_error("all_gather: row is not a whole number of 16B words"); @@ -139,8 +130,7 @@ void r4d_ar_gather_2rank(long peer_scratch, long my_scratch, long peer_flags, lo if (nb < 1) nb = 1; if (nb > n16) nb = n16; if (nb > R4D_AR_GATHER_MAX_BLOCKS) nb = R4D_AR_GATHER_MAX_BLOCKS; - // The counter allocation's block capacity, shared with the all-reduce this rides beside - // (r4d_ar_seq.h). + // Block capacity of the counter allocation shared with the all-reduce (r4d_ar_seq.h). const unsigned nbw = (unsigned)r4d_ar_max_blocks(); if ((unsigned)nb > nbw) nb = (int)nbw; int nt = (int)nthreads; diff --git a/libr4d/r4d_ar_gather_Nrank.hip b/libr4d/r4d_ar_gather_Nrank.hip index 3a521e5d..f98e0a3f 100644 --- a/libr4d/r4d_ar_gather_Nrank.hip +++ b/libr4d/r4d_ar_gather_Nrank.hip @@ -1,39 +1,32 @@ // r4d_ar_gather_Nrank.hip: r4d_ar_gather_3rank, r4d_ar_gather_4rank, r4d_ar_gather_8rank -- one-shot P2P all-GATHER, -// 4 or 8 ranks, gfx1201. WS is compile-time; the 2-rank gather keeps its own file, exactly as the -// one-shot all-reduce's does. +// 3, 4 or 8 ranks, gfx1201. WS is compile-time; the 2-rank gather has its own file, as does the +// 2-rank one-shot all-reduce. // -// WHY IT EXISTS. r4d_ar_gather_2rank.hip is the engine's only device all-gather and its handshake -// is ONE PEER FLAG per block, not a tree (r4d_ar_entry.hip:492), so it is compiled for two ranks -// and refuses every other width. The vocab-parallel sampler declares an all_gather whenever the -// vocabulary is sharded, so at world 4 nothing but libref's host ref_all_gather resolves and the -// serve is refused by name. This is the wide one-shot all-reduce with the reduction REMOVED: same -// push, same per-block handshake, same double-buffered (parity, source) scratch, and the fp32 sum -// replaced by placement. +// r4d_ar_gather_2rank.hip handshakes with one peer flag per block, so it serves two ranks only. The +// vocab-parallel sampler declares an all_gather whenever the vocabulary is sharded; without this +// kernel only libref's host ref_all_gather resolves at wider worlds and the serve is refused. It is +// the wide one-shot all-reduce with the reduction removed: same push, per-block handshake and +// double-buffered (parity, source) scratch, with the fp32 sum replaced by placement. // -// THE PAYLOAD IS MOVED AND NEVER SUMMED. What the sampler gathers is (u32 global token id, f32 -// logit) pairs; a token id's bit pattern read as f32 is a denormal, so adding two lanes would -// work on the logit and destroy the id. `dtype` is taken for symmetry with the family and used -// only to turn n_elem into bytes. +// The payload is (u32 token id, f32 logit) pairs, so it is moved and never summed. `dtype` only +// converts n_elem to bytes. // -// THE PLACEMENT. row16 is one ROW of this rank's contribution in 16-byte words and r4d_g_dst_ws -// says where a rank's words land: the plain concatenation when there is one row, and otherwise -// ROW-INTERLEAVED -- input [rows][row16], output [rows][WS][row16] -- because the merge that -// consumes this reads one row of gathered candidates per sampled position at a single row stride. -// See r4d_ar_gather_2rank.hip, whose comment states why that is not a convenience. +// Placement: row16 is one row of this rank's contribution in 16-byte words. r4d_g_dst_ws +// concatenates when there is one row, and otherwise interleaves rows (input [rows][row16], output +// [rows][WS][row16]) so the merge reads each position's candidates at a single row stride (see +// r4d_ar_gather_2rank.hip). // -// The IPC helpers and the handshake live in r4d_ar_wide.h; this unit links beside r4d_ar_entry.hip, -// which owns the instance and the peer arrays. +// The IPC helpers and the handshake live in r4d_ar_wide.h; r4d_ar_entry.hip owns the instance and +// the peer arrays. #include "r4d.h" #include "r4d_ar_wide.h" #include #include #include -// The launchers this unit provides, in the family's shape: the peer arguments are ascending global -// rank with the current rank removed, and `out` is world_size * n_elem elements. Declared extern -// "C" here, at arm's length from the definitions below, so those definitions get C linkage; the -// caller is r4d_ar_entry.hip, which owns the instance and repeats the two prototypes at its call -// site (r4d.h declares the rest of the family and is not this unit's file). +// Peer arguments are in ascending global rank with the current rank removed; `out` is +// world_size * n_elem elements. Declared extern "C" here so the definitions below get C linkage; +// r4d_ar_entry.hip repeats the prototypes at its call site, since r4d.h does not declare them. extern "C" void r4d_ar_gather_3rank(long peer_scratch0, long peer_scratch1, long peer_flags0, long peer_flags1, long my_scratch, long my_flags, long seq_ctrs, @@ -45,7 +38,8 @@ extern "C" void r4d_ar_gather_4rank(long peer_scratch0, long peer_scratch1, long long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long row_elems, long stream, - long nblocks, long nthreads, long drain, long acq, long pub); + long nblocks, long nthreads, long drain, long acq, long pub, + long gate, long gate_ctr); extern "C" void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long peer_scratch2, long peer_scratch3, long peer_scratch4, long peer_scratch5, long peer_scratch6, long peer_flags0, long peer_flags1, @@ -56,9 +50,8 @@ extern "C" void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long long stream, long nblocks, long nthreads, long drain, long acq, long pub); -// WHERE A RANK'S WORDS LAND -- the 2-rank r4d_g_dst at a compile-time width. Named apart from it -// on purpose: same rule, different WS, and two __device__ definitions of one name would be an ODR -// violation between the two units. +// Where a rank's words land: the 2-rank r4d_g_dst generalised to WS. Named differently because two +// __device__ definitions of one name in the two units would violate the ODR. __device__ __forceinline__ int r4d_g_dst_ws(int k, int row16, int n16, int WS, int who) { if (row16 <= 0 || row16 >= n16) return who * n16 + k; const int m = k / row16, c = k - m * row16; @@ -66,20 +59,22 @@ __device__ __forceinline__ int r4d_g_dst_ws(int k, int row16, int n16, int WS, i } // Block b owns words [start,end) of the 16B-word space and drives its own handshake; no cross-block -// sync, exactly as in the all-reduce this rides beside. +// sync, as in the all-reduce. template __global__ void r4d_ar_gather_wide_kernel( const int4* __restrict__ in4, R4DArWidePeers peers, const int4* __restrict__ my_base, int4* __restrict__ out4, unsigned int* __restrict__ my_flags, unsigned int* __restrict__ seq_ctrs, - int n16, int slot_stride16, int rank, int row16, int drain, int acq, int pub) { + int n16, int slot_stride16, int rank, int row16, int drain, int acq, int pub, + long long* gate, unsigned int* gate_ctr) { constexpr int NPEERS = WS - 1; - // The placement holds WS source words live per output word, so the 2x unroll spills at ws=8 -- - // the same ceiling the one-shot all-reduce draws for the same reason. + // Placement holds WS source words live per output word, so the 2x unroll spills at ws=8 (same + // limit as the one-shot all-reduce). constexpr int RU = (WS <= 4) ? 2 : 1; const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x; __shared__ unsigned int s_seq, s_slot; + const long long gate_word = r4d_ar_link_word(gate, (unsigned int)tid); r4d_ar_seq_take(seq_ctrs, R4D_AR_WIDE_MAX_BLOCKS, s_seq, s_slot); // device-resident, replay-safe const unsigned int s = s_seq; const int parity = (int)s_slot; @@ -88,18 +83,15 @@ __global__ void r4d_ar_gather_wide_kernel( const int start = b * w; int end = start + w; if (end > n16) end = n16; - // Every peer lays its scratch out identically, so one index serves all of them: the slot that - // NAMES THE SOURCE RANK. We write our own words into the same slot number of every peer's - // scratch, and every peer reads them out of the slot numbered by OUR rank. + // Every peer lays its scratch out identically, with one slot per source rank. Our words go into + // the slot numbered by our rank in every peer's scratch. int4* ps[NPEERS]; #pragma unroll for (int p = 0; p < NPEERS; ++p) ps[p] = peers.scratch[p] + ((size_t)parity * WS + rank) * (size_t)slot_stride16; - // push: 4x-unrolled, and the loaded words are reused across peers so the input is read once. - // This rank's own slice is NOT placed here -- the pass after the handshake places every rank's - // slice from one src[] table, and duplicating the local store to hide it here would be the only - // thing the all-reduce's shape does not carry over. + // Push, 4x unrolled; loaded words are reused across peers so the input is read once. This rank's + // own slice is placed after the handshake with all the others, from one src[] table. { int k = start + tid; for (; k + 3 * nt < end; k += 4 * nt) { @@ -116,15 +108,16 @@ __global__ void r4d_ar_gather_wide_kernel( } } - // The wide family's own protocol: publish 2*seq to every peer's flag word [b][our rank], then - // wait on our own [b][source] for every source. Flag values, parity and the slot guard are - // r4d_ar_wide.h's, shared with the all-reduces this instance's buffers serve, and a handshake - // that cannot complete traps rather than pass stale bytes on as a peer's. + // Publish 2*seq to every peer's flag word [b][our rank], then wait on our own [b][source] for + // every source. The protocol is r4d_ar_wide.h's, shared with the all-reduces on these buffers; a + // handshake that cannot complete traps rather than pass on stale bytes. r4d_ar_handshake(peers, my_flags, b, rank, 2u * s, drain, acq, pub); + // One handshake, and the placement after it reads this card's scratch and input only: the last + // block here ends the engine's hold, as in the one-shot all-reduce this rides beside. + r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid); - // The peers' slices, now staged in this rank's scratch, into the places that name them. Slot - // [parity][our rank] of my own scratch is written by nobody, so -- exactly as in the all-reduce - // -- the source that names OUR rank is the input itself and every lane is branch-free. + // Place every rank's slice. Slot [parity][our rank] of our own scratch is never written, so, as + // in the all-reduce, our rank's source is the input itself and the loop is branch-free. const int4* src[WS]; #pragma unroll for (int r = 0; r < WS; ++r) @@ -150,15 +143,14 @@ __global__ void r4d_ar_gather_wide_kernel( } // --- host side --- -// `row_elems` is the row width in ELEMENTS, 0 for the plain concatenation; the entry point has -// already checked that it divides the message and is a whole number of 16-byte words, and it is -// rechecked here because this is the half that throws. +// `row_elems` is the row width in elements, 0 for plain concatenation. The entry point checks it +// already; it is rechecked here because this is the half that throws. template static void ar_gather_wide_launch(const long* peer_scratch, const long* peer_flags, long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long row_elems, long stream_i, long nblocks, long nthreads, long drain, long acq, - long pub) { + long pub, long gate, long gate_ctr) { constexpr int NPEERS = WS - 1; static_assert(NPEERS <= R4D_AR_WIDE_MAX_PEERS, "npeers exceeds the peer bundle bound"); @@ -200,9 +192,9 @@ static void ar_gather_wide_launch(const long* peer_scratch, const long* peer_fla peers.rank[i] = (i < (int)rank) ? i : i + 1; } - // Same buffers, same rule as the all-reduce this shares an instance with: scratch backs 2*WS - // slots of the declared stride, flags one word per (block, source rank), seq a handshake and a - // parity word per block of capacity -- checked against the allocations, not the arguments. + // As in the all-reduce sharing this instance, check against the allocations: scratch backs 2*WS + // slots of the stride, flags one word per (block, source rank), seq a handshake and a parity + // word per block of capacity. const long slot_bytes = 2L * WS * (long)slot_stride16 * 16; const long flag_bytes = (long)nb * WS * (long)sizeof(unsigned int); r4d_ar_check_extent(my_scratch, slot_bytes, "all_gather", "my_scratch"); @@ -218,11 +210,10 @@ static void ar_gather_wide_launch(const long* peer_scratch, const long* peer_fla r4d_ar_gather_wide_kernel<<>>( (const int4*)inp, peers, (const int4*)my_scratch, (int4*)out, (unsigned int*)my_flags, (unsigned int*)seq_ctrs, n16, (int)slot_stride16, (int)rank, row16, (int)drain, (int)acq, - (int)pub); + (int)pub, (long long*)gate, (unsigned int*)gate_ctr); } -/* Three ranks: the same launch with two peers. The vocab-parallel sampler's gather at a world of - * three (Qwen3.8-Flash-Next padded to 36 heads / 3 KV heads, docs/TP3.md) resolves here. */ +/* Three ranks, e.g. Qwen3.8-Flash-Next padded to 36 heads / 3 KV heads (docs/TP3.md). */ void r4d_ar_gather_3rank(long peer_scratch0, long peer_scratch1, long peer_flags0, long peer_flags1, long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, @@ -230,19 +221,23 @@ void r4d_ar_gather_3rank(long peer_scratch0, long peer_scratch1, long nblocks, long nthreads, long drain, long acq, long pub) { const long ps[2] = {peer_scratch0, peer_scratch1}; const long pf[2] = {peer_flags0, peer_flags1}; + /* No link gate at three ranks: the row answers 1, the engine releases by barrier. */ ar_gather_wide_launch<3>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem, - dtype, rank, row_elems, stream, nblocks, nthreads, drain, acq, pub); + dtype, rank, row_elems, stream, nblocks, nthreads, drain, acq, pub, + 0L, 0L); } void r4d_ar_gather_4rank(long peer_scratch0, long peer_scratch1, long peer_scratch2, long peer_flags0, long peer_flags1, long peer_flags2, long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long row_elems, long stream, - long nblocks, long nthreads, long drain, long acq, long pub) { + long nblocks, long nthreads, long drain, long acq, long pub, long gate, + long gate_ctr) { const long ps[3] = {peer_scratch0, peer_scratch1, peer_scratch2}; const long pf[3] = {peer_flags0, peer_flags1, peer_flags2}; ar_gather_wide_launch<4>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem, - dtype, rank, row_elems, stream, nblocks, nthreads, drain, acq, pub); + dtype, rank, row_elems, stream, nblocks, nthreads, drain, acq, pub, + gate, gate_ctr); } void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long peer_scratch2, @@ -257,6 +252,8 @@ void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long peer_scrat peer_scratch4, peer_scratch5, peer_scratch6}; const long pf[7] = {peer_flags0, peer_flags1, peer_flags2, peer_flags3, peer_flags4, peer_flags5, peer_flags6}; + /* No link gate at eight ranks: the row answers 1, the engine releases by barrier. */ ar_gather_wide_launch<8>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem, - dtype, rank, row_elems, stream, nblocks, nthreads, drain, acq, pub); + dtype, rank, row_elems, stream, nblocks, nthreads, drain, acq, pub, + 0L, 0L); } diff --git a/libr4d/r4d_ar_hc.h b/libr4d/r4d_ar_hc.h index b845120e..db739295 100644 --- a/libr4d/r4d_ar_hc.h +++ b/libr4d/r4d_ar_hc.h @@ -1,17 +1,15 @@ #pragma once -// r4d_ar_hc.h: the per-word arithmetic of the all-reduces that end in the gated residual's write -- -// the MoE gather in front of the message and the hc write behind the reduction -- shared by the -// exact kernels (r4d_ar_oneshot_2rank_exact.hip) and the rotated 6-bit ones -// (r4d_ar_oneshot_2rank_wht6.hip). One copy of it is what makes the two wires' fused forms produce -// the bytes of the same unfused chain: moe_gather, the all-reduce, hc_write. +// r4d_ar_hc.h: per-word arithmetic of the all-reduces fused with the gated residual write: the MoE +// gather before the message and the hc write after the reduction. Shared by the exact kernels +// (r4d_ar_oneshot_2rank_exact.hip) and the rotated 6-bit ones (r4d_ar_oneshot_2rank_wht6.hip), so +// both fused forms produce the same bytes as the unfused chain moe_gather, all-reduce, hc_write. // -// A WORD is eight consecutive bf16 elements of one row -- a row is `n` elements and n is a multiple +// A word is eight consecutive bf16 elements of one row. A row is `n` elements and n is a multiple // of eight, so a word never straddles a row. #include #include "r4d_gdn_wmma.h" // f2bf / bf2f: the gated residual's own bf16 arithmetic -// The LDS slot table's bounds: the rows one block of the table form covers, and the slots a row -// holds. +// LDS slot table bounds: rows per block, and slots per row. #define R4D_ARG_ROWS 8 #define R4D_ARG_SLOTS 64 @@ -30,13 +28,13 @@ struct R4dArGather { int top_k, T, sig; }; -// ONE WORD OF THE GATHER: y[row][i0 .. i0+8) = sum over the row's slots, ascending, of -// w[row][j] * y_expert[slot][i0 ..], rounded to bf16, with the shared arm folded as moe_gather -// folds it -- its narrows are round-to-nearest-even, not hc_write's. +// One word of the gather: y[row][i0 .. i0+8) = sum over the row's slots, ascending, of +// w[row][j] * y_expert[slot][i0 ..], rounded to bf16, with the shared arm folded in as moe_gather +// does it. Its narrows are round-to-nearest-even, unlike hc_write's. // -// With INV the slots come from the inverse table inv[token * top_k + slot] (the sorted row holding -// it, or -1) and the weights and the gate from global memory; without it from the block's LDS -// table, `r` being the row's index in it. +// With INV, slots come from the inverse table inv[token * top_k + slot] (the sorted row holding +// it, or -1) and weights and gate from global memory. Without it they come from the block's LDS +// table, where `r` is the row's index. template __device__ __forceinline__ int4 r4d_ar_gather_word(const R4dArGather& G, const int* __restrict__ inv, const int* s_i, @@ -46,10 +44,9 @@ __device__ __forceinline__ int4 r4d_ar_gather_word(const R4dArGather& G, float acc[8]; #pragma unroll for (int e = 0; e < 8; ++e) acc[e] = 0.0f; - /* FOUR SLOTS' ROWS IN FLIGHT AT ONCE. Loaded one at a time behind the test for an empty slot, - * each row's read waits for the one before it; so the four are issued first -- an empty slot - * reads row 0, which is always there -- and then added in the same ascending order, the empty - * ones skipped. */ + /* Four slot rows in flight at once: all four loads issue before any add, so they do not + * serialise behind the empty-slot test. An empty slot reads row 0, which always exists, and is + * skipped in the ascending add. */ constexpr int kU = 4; for (int j0 = 0; j0 < K; j0 += kU) { int4 v[kU]; @@ -92,9 +89,9 @@ __device__ __forceinline__ int4 r4d_ar_gather_word(const R4dArGather& G, return out; } -// ONE WORD OF THE WRITE: h[row][c*n + i0 ..] += inj[row][c] * y[row][i0 ..] for every stream c, in -// hc_write's arithmetic (r4d_hc_bf16.hip) over `yv`, the reduced word as the bf16 the reduction -// stored -- which is what hc_write reads back from memory. +// One word of the write: h[row][c*n + i0 ..] += inj[row][c] * y[row][i0 ..] for every stream c, in +// hc_write's arithmetic (r4d_hc_bf16.hip). `yv` is the reduced word as stored bf16, which is what +// hc_write reads back from memory. __device__ __forceinline__ void r4d_ar_hc_write_word(const unsigned short* __restrict__ inj, unsigned short* __restrict__ h, int row, int i0, int n, int hc, long irow, long hrow, diff --git a/libr4d/r4d_ar_ln_had_quant_i8.hip b/libr4d/r4d_ar_ln_had_quant_i8.hip index 37ccdcf9..98d548ba 100644 --- a/libr4d/r4d_ar_ln_had_quant_i8.hip +++ b/libr4d/r4d_ar_ln_had_quant_i8.hip @@ -1,44 +1,30 @@ -// r4d_ar_ln_had_quant_i8.hip -- r4d_ar_ln_had_quant_i8: the tensor-parallel all-reduce and the -// residual add, RMS norm, block Hadamard and int8 quantiser that always follow it, in ONE kernel. +// r4d_ar_ln_had_quant_i8.hip -- r4d_ar_ln_had_quant_i8: the tensor-parallel all-reduce plus the +// residual add, RMS norm, block Hadamard and int8 quantiser that always follow it, in one kernel. // -// WHY. Every row-parallel linear in the model is followed by an all-reduce, and every one of those -// all-reduces is followed by a norm -- 128 of each on a 64-layer decode step, always adjacent and -// always in that order: +// Every row-parallel linear is followed by an all-reduce and then a norm (128 of each on a +// 64-layer decode step): // // out_proj / o_proj / down_proj -> all_reduce -> (residual add, RMS norm, rotate, quantise) // -// and the norm's output is the next quantised linear's A. A decode step is launch-bound: over a -// thousand dispatches with ~2.3 us of unavoidable gap between each is several milliseconds of pure -// gap, and the standalone norm is itself latency- rather than bandwidth-bound (4.1 us for an -// 80 KiB row set, against a ~2.6 us launch floor). Merging the pair removes 128 dispatches AND -// nearly all of the norm's fixed cost, because the norm's work is bolted onto a kernel that has -// already paid it. +// and the norm's output is the next quantised linear's A. Decode is launch-bound (~2.3 us gap per +// dispatch), and the standalone norm is latency-bound (4.1 us for an 80 KiB row set against a +// ~2.6 us launch floor). Fusing removes 128 dispatches and most of the norm's fixed cost. The +// all-reduce output is never materialised: the peer's contribution is a second operand on the +// norm's load, `t = mine + peer + residual`. // -// The all-reduce OUTPUT never exists. In the unfused pair it is a bf16 [M, K] tensor written by -// the all-reduce and read straight back by the norm; here the peer's contribution is simply a -// second operand on the norm's load -- `t = mine + peer + residual` -- so the round trip is gone -// as well. +// Partition by row. r4d_ar_oneshot_2rank_exact gives each block a chunk of 16B words and an +// independent flag with no grid barrier. A norm needs whole rows for its sum of squares, but rows +// are contiguous, so giving block b a contiguous row range makes its words exactly those rows' +// bytes. Both ranks derive the range from (M, gridDim.x), so the handshake stays per-block with no +// grid barrier. This caps nb at M, which costs nothing here: the standalone all-reduce uses 4 +// blocks on an 80 KiB decode message and M is 8 or more. // -// WHY THE PARTITION IS BY ROW. r4d_ar_oneshot_2rank_exact gives block b a contiguous chunk of 16B -// WORDS and an independent flag, with no grid barrier anywhere: b pushes its chunk to the peer, -// releases peer_flags[b], spins on my_flags[b], then reduces its own chunk. A norm cannot use that -// partition -- a sum of squares closes only over a whole row -- but it does not need a grid barrier -// either, because rows are contiguous: give block b a contiguous range of ROWS and its chunk of -// words is exactly the bytes of those rows. Both ranks compute the same range from (M, gridDim.x), -// so the handshake stays per-block and the kernel keeps the no-grid-barrier structure. -// -// The block count therefore has a ceiling the standalone all-reduce does not have (nb <= M), which -// costs nothing at the sizes this runs at: the standalone all-reduce asks for 4 blocks on an 80 KiB -// decode message and the row count is 8 or more. The number of threads actually pushing is n16 -// either way. -// -// Everything below the handshake is r4d_rmsnorm_had_quant_i8 unchanged -- the same one-pass -// argument (the FWHT is linear and inv_rms is a per-row scalar, so the rotation runs before the -// norm closes and the scale absorbs it), the same register staging rather than an LDS round trip, -// the same `wadd` added inside the fp32 arithmetic for GemmaRMSNorm's `x_hat * (1 + w)`, and the -// same optional unrotated bf16 output for a GDN block's bf16 in_proj_ba. The only change is that -// the row is loaded from two places and that LDS is re-used across the rows a block owns, which -// needs one more barrier per row. +// Below the handshake this is r4d_rmsnorm_had_quant_i8: one pass (the FWHT is linear and inv_rms +// is a per-row scalar, so the rotation runs before the norm closes and the scale absorbs it), +// register staging, `wadd` inside the fp32 arithmetic for GemmaRMSNorm's `x_hat * (1 + w)`, and an +// optional unrotated bf16 output for a GDN block's bf16 in_proj_ba. The differences: the row is +// loaded from two places, and LDS is reused across a block's rows, which costs one more barrier +// per row. #include "r4d.h" #include "r4d_ar_seq.h" #include "r4d_common.h" @@ -47,14 +33,7 @@ #include #include #include - -// The compressed all-reduce this fuses stores its fp32 sum to a bf16 tensor and the norm reads -// that back, so the fused kernel rounds the sum to bf16 too and reproduces the unfused pair's -// output exactly. Build with -DARN_W6_MATCH=0 to keep the fp32 sum, which is strictly more -// accurate and NOT token-exact against the pair. -#ifndef ARN_W6_MATCH -#define ARN_W6_MATCH 1 -#endif +#include #define R4D_ARN_SPIN_MAX 4000000000ULL #define R4D_ARN_MAXVALS 72 @@ -67,46 +46,38 @@ __device__ __forceinline__ unsigned int arn_load_acq(const unsigned int* p) { } // --------------------------------------------------------------------------------------------- -// THE ROTATED 6-BIT WIRE. Same format and the same arithmetic as r4d_ar_oneshot_2rank_wht6 -- -// orthonormal Walsh-Hadamard over a group of 64, amax-scaled, 6 uniform bits plus a bf16 scale -- -// but packed at a CHUNK of 1024 elements instead of 2048, so that a chunk never straddles a row. -// That is what lets the norm keep its row partition: block b owns rows [r0, r1), and because K is -// a whole number of chunks its element range is a whole number of chunks too. +// Rotated 6-bit wire: same format and arithmetic as r4d_ar_oneshot_2rank_wht6 (orthonormal +// Walsh-Hadamard over groups of 64, amax-scaled, 6 uniform bits plus a bf16 scale), but packed in +// chunks of ARN_CE elements instead of 2048 so a chunk never straddles a row. K is a whole number +// of chunks, so a block's rows [r0, r1) are too, and the row partition holds. // -// The wire is why this exists. Above ~200 KiB the message is bandwidth-bound and the compressed -// payload is 2.6x smaller, which is worth far more than the launch the fusion saves. Carrying the -// payload in here lets the two wins compose: a message large enough to want the compressed wire -// still avoids a second dispatch and a bf16 round trip through memory. +// Above ~200 KiB the message is bandwidth-bound and the compressed payload is 2.6x smaller, which +// outweighs the saved launch; carrying it here gets both savings. // -// The helpers are duplicated rather than included from r4d_ar_oneshot_2rank_wht6.h on purpose: -// that header also carries the standalone kernel and its launcher, so including it would -// instantiate a second copy of a shipped kernel in this translation unit. +// The helpers are duplicated from r4d_ar_oneshot_2rank_wht6.h on purpose: that header also holds +// the standalone kernel and launcher, which would be instantiated again in this unit. #define ARN_GROUP 64 #define ARN_BITS 6 #define ARN_EPL 8 #define ARN_LPG (ARN_GROUP / ARN_EPL) // 8 lanes span one group #define ARN_WV 32 #define ARN_GPW (ARN_WV * ARN_EPL / ARN_GROUP) // 4 groups per wave-iteration -// GROUPS PER CHUNK, and the only real tuning knob on the wire. 8 here, against the standalone -// kernel's 32: a wave owns a whole chunk, so the chunk size is what decides how many waves have -// work. A 5120-group message is 160 chunks at 32 and 640 at 8, and the block count cannot make up -// the difference, because every block pays its own flag round trip over the fabric -- raising the -// count from 24 to 32 costs ~3%, to 64 ~4%, and to 160 ~24%. Shrinking the chunk buys the same -// parallelism for nothing, and the wire's cost falls monotonically from 32 groups to 8. -#ifndef ARN_CG +// Groups per chunk, the wire's one tuning knob: 8 here against the standalone kernel's 32. A wave +// owns a whole chunk, so chunk size sets how many waves have work (a 5120-group message is 160 +// chunks at 32, 640 at 8). More blocks cannot substitute, since each pays its own flag round trip +// (24 -> 32 blocks costs ~3%, 64 ~4%, 160 ~24%). The wire's cost falls monotonically from 32 groups +// to 8. #define ARN_CG 8 -#endif - // groups per chunk -#define ARN_CE (ARN_CG * ARN_GROUP) // 1024 elements per chunk -#define ARN_ITERS (ARN_CE / (ARN_WV * ARN_EPL)) // 4 iterations to cover a chunk -#define ARN_NWORD (ARN_ITERS * ARN_EPL * ARN_BITS / 32) // 6 dwords a lane holds for a chunk -#define ARN_CBYTES (ARN_CE * ARN_BITS / 8) // 768 wire bytes a chunk +#define ARN_CE (ARN_CG * ARN_GROUP) // elements per chunk (512 at ARN_CG 8) +#define ARN_ITERS (ARN_CE / (ARN_WV * ARN_EPL)) // wave-iterations per chunk +#define ARN_NWORD (ARN_ITERS * ARN_EPL * ARN_BITS / 32) // dwords a lane holds per chunk +#define ARN_CBYTES (ARN_CE * ARN_BITS / 8) // wire bytes per chunk #define ARN_QMAX ((1 << (ARN_BITS - 1)) - 1) #define ARN_QMIN (-(1 << (ARN_BITS - 1))) #define ARN_MASK ((1u << ARN_BITS) - 1u) -// RTNE to bf16 and back: the scale ships as its top 16 bits, so the sender's own copy has to be -// exactly what the receiver reconstructs. +// RTNE to bf16 and back: the scale ships as its top 16 bits, and the sender's own copy must equal +// what the receiver reconstructs. __device__ __forceinline__ float arn_bf16_round(float v) { unsigned u = __float_as_uint(v); const unsigned lsb = (u >> 16) & 1u; @@ -115,10 +86,9 @@ __device__ __forceinline__ float arn_bf16_round(float v) { } -// `lo ? (v + o) : (o - v)` written as `o + (lo ? v : -v)`. The sign flip is one XOR against a -// mask that is uniform over the whole stage, so the select disappears: two instructions an element -// (xor, then the DPP-sourced add) instead of an add, a subtract and a v_cndmask. Bit-identical -- -// IEEE negation is exact and addition commutes. +// `lo ? (v + o) : (o - v)` written as `o + (lo ? v : -v)`. The sign flip is one XOR with a mask +// uniform over the stage: two instructions per element (xor, DPP-sourced add) instead of add, +// subtract and v_cndmask. Bit-identical, since IEEE negation is exact and addition commutes. template __device__ __forceinline__ void arn_xstage(float* v, int lig) { const unsigned int sm = (lig & M) ? 0x80000000u : 0u; @@ -159,11 +129,9 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel( constexpr int VPL = HAD / 32, NW = THR / 32; constexpr int MAXB = R4D_ARN_MAXVALS / VPL; extern __shared__ float lds[]; - // One staging slice per row the block owns. The exact wire needs only one (the norm reads the - // row straight from memory), but the compressed wire has to REDUCE first, and a per-row reduce - // would put cpr chunks -- five at K = 5120 -- in front of NW waves behind a barrier, three times - // over. With the whole block's rows staged, the reduce is one pass over every chunk the block - // owns and there is one barrier, not one per row. + // One staging slice per owned row on the compressed wire (the exact wire needs one, since the + // norm reads rows from memory). The compressed wire must reduce first; staging all rows makes + // the reduce one pass over the block's chunks behind one barrier instead of one per row. const int r0_ = (int)(((long)blockIdx.x * M) / gridDim.x); const int nrows = (int)(((long)(blockIdx.x + 1) * M) / gridDim.x) - r0_; float* red = lds + (size_t)(WIRE ? nrows : 1) * K; @@ -179,10 +147,9 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel( int4* ps = peer_base + (size_t)s_slot * slot_stride16; const int4* ms = my_base + (size_t)s_slot * slot_stride16; - // WIRE == 6 only. The slot is split exactly as the standalone compressed all-reduce splits it: - // packed symbols from the base, bf16 group scales from half way up. Chunk indices are GLOBAL - // over the whole [M, K] message, so both ranks address the same bytes without exchanging - // anything; a block simply owns the chunks its rows cover. + // WIRE == 6 only. The slot is split as in the standalone compressed all-reduce: packed symbols + // from the base, bf16 group scales from halfway. Chunk indices are global over the [M, K] + // message, so both ranks address the same bytes; a block owns the chunks its rows cover. const int cpr = K / ARN_CE; // chunks a row spans (K % ARN_CE == 0, checked) const int c00 = r0 * cpr, cpb = (r1 - r0) * cpr; char* p_pay = (char*)ps; @@ -190,16 +157,15 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel( unsigned short* p_sc = (unsigned short*)((char*)ps + (size_t)(slot_stride16 >> 1) * 16); const unsigned short* m_sc = (const unsigned short*)((const char*)ms + (size_t)(slot_stride16 >> 1) * 16); - // This rank's own packed half, kept in LDS so the reduce folds exactly the bytes it sent - // without a global round trip -- the standalone kernel needs a side buffer for this because it - // has no LDS to spare; here the norm's staging array is already the reason there is a barrier. + // This rank's own packed half, kept in LDS so the reduce folds exactly the bytes it sent without + // a global round trip (the standalone kernel uses a side buffer instead). unsigned int* Lpk = (unsigned int*)(red + 2 * NW); float* Lsc = (float*)(Lpk + (size_t)cpb * ARN_WV * ARN_NWORD); const int lig = lane & (ARN_LPG - 1), gw = lane / ARN_LPG; if constexpr (WIRE == 0) { - // push my rows -> peer slot. K bf16 is K/8 16B words, and rows are contiguous, so a row range - // is a word range. + // 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. const int wpr = K >> 3; const int wstart = r0 * wpr, wend = r1 * wpr; const int4* in4 = (const int4*)X; @@ -210,9 +176,9 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel( } for (; k < wend; k += THR) ps[k] = in4[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 flush is lane-uniform: one 512B uint4 store and one 256B uint2 store a wave a chunk. + // 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 + // flush is lane-uniform. for (int ci = wave; ci < cpb; ci += NW) { const int c = c00 + ci; unsigned int acc[ARN_NWORD]; @@ -249,7 +215,7 @@ __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 6 at ARN_CG 16 and 3 at 8. + // store of ARN_WV x width bytes (ARN_NWORD is 3). char* pb = p_pay + (size_t)c * ARN_CBYTES; #pragma unroll for (int w4 = 0; w4 + 4 <= ARN_NWORD; w4 += 4) @@ -272,8 +238,7 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel( if (drain == 2) __threadfence_system(); arn_store_rel(&peer_flags[b], sq); unsigned long long z = 0; - // A handshake that cannot complete is a lockstep violation: norming a slot the peer never - // filled would hand stale bytes on as a sum, so it traps instead. + // A handshake that cannot complete is a lockstep violation; trap rather than use stale bytes. while (r4d_ar_seq_behind(arn_load_acq(&my_flags[b]), sq)) { if (++z > R4D_ARN_SPIN_MAX) __builtin_trap(); } @@ -281,14 +246,14 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel( __syncthreads(); if (acq) __threadfence_system(); - // The peer's rows are now in MY scratch, in the same [M, K] layout as X. + // 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; if constexpr (WIRE == 6) { - // REDUCE: unpack both halves of every chunk this block owns, add in fp32, inverse-rotate and - // leave the reduced value in the norm's own staging slice. The norm then reads it exactly - // where it would have read `x + p`, and overwrites the same slot with its rotated result -- - // one lane owns a slot in both passes, so the aliasing needs no second array. + // Reduce: unpack both halves of every owned chunk, add in fp32, inverse-rotate, and leave the + // result in the norm's staging slice. The norm reads it where it would read `x + p` and + // overwrites it with its rotated result; one lane owns a slot in both passes, so the aliasing + // is safe. for (int ci = wave; ci < cpb; ci += NW) { const int c = c00 + ci; const char* pb = m_pay + (size_t)c * ARN_CBYTES; @@ -321,22 +286,20 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel( psy |= pac[wi + 1] << (32 - bo); lsy |= lac[wi + 1] << (32 - bo); } - // The two ranks fold the identical pair in OPPOSITE order; fp32 add commutes exactly, so - // they stay bit-identical as long as neither product is contracted into an FMA. - // libr4d/CMakeLists.txt passes -ffp-contract=off for exactly this. + // The ranks fold the same pair in opposite order; fp32 add commutes, so they stay + // bit-identical as long as neither product becomes an FMA (libr4d/CMakeLists.txt passes + // -ffp-contract=off). v[i] = (float)((int)(psy & ARN_MASK) + ARN_QMIN) * psc + (float)((int)(lsy & ARN_MASK) + ARN_QMIN) * lsc; } arn_wht(v, lig); const int e0 = (int)((long)(c * ARN_CG + gl) * ARN_GROUP + (long)lig * ARN_EPL - (long)r0 * K); + // Rounded to bf16, as the unfused compressed all-reduce stores its sum and the norm reads + // it back, so this matches the pair exactly. #pragma unroll for (int i = 0; i < ARN_EPL; ++i) -#if ARN_W6_MATCH lds[e0 + i] = __bfloat162float(__float2bfloat16(v[i])); -#else - lds[e0 + i] = v[i]; -#endif } } __syncthreads(); @@ -356,15 +319,11 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel( float v[VPL]; #pragma unroll for (int j = 0; j < VPL; j++) { - // WIRE == 0: ROUNDED TO bf16 ON PURPOSE. The standalone all-reduce accumulates in fp32 - // and STORES bf16, and the norm then reads that back -- so folding the reduce into the - // norm's load would otherwise drop a rounding step and change the token stream. It would - // change it for the better, but keeping the fused form bit-identical to the pair it - // replaces is worth more than the accuracy. The price is one software RTNE per element - // (gfx1201 has no bf16 convert instruction) on a kernel that is launch-bound rather than - // ALU-bound. WIRE == 6 has no such pair to match: the compressed all-reduce it - // replaces stores the fp32 sum straight to bf16 and the norm reads that, so here the sum - // is taken from LDS in fp32 and the bf16 round trip is simply gone. + // WIRE == 0 rounds to bf16 on purpose: the standalone all-reduce stores its fp32 sum as + // bf16 and the norm reads that, so skipping the rounding would change the token stream. + // Bit-identity with the unfused pair is preferred over the extra accuracy; the software + // RTNE (gfx1201 has no bf16 convert) is cheap on this launch-bound kernel. WIRE == 6 reads + // the reduced value from LDS, already rounded. float t; if constexpr (WIRE == 0) { t = __bfloat162float(__float2bfloat16( @@ -416,31 +375,27 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel( const int t = __float2int_rn(rl[sr] * inv); q[i] = (signed char)(t < -128 ? -128 : (t > 127 ? 127 : t)); } - // lds and red are re-used by the next row this block owns. + // lds and red are reused by the block's next row. __syncthreads(); } } -// What the compressed wire costs in LDS, so the caller can pick its block count instead of -// guessing. A block owns whole rows and holds, per row, a staging slice at `stage_bits` bits an -// element plus the packed half of its own chunks; getting this wrong is not a slow launch but a -// refused one. +// LDS cost of the compressed wire, so the caller can choose a block count. A block owns whole +// rows and holds, per row, a staging slice at `stage_bits` bits per element plus the packed half +// of its own chunks; a block count that does not fit is refused. void r4d_ar_ln_wire_dims(int* stage_bits, int* chunk_elems, int* chunk_bytes, int* scale_bytes) { - // 32: the reduced values are staged as fp32 IN THE NORM'S OWN ARRAY -- the norm reads a slot - // and overwrites it with its rotated result, so the staging is not extra LDS at all. Staging - // at bf16 instead would fit half again as many rows per block, but all that buys is a LOWER - // block count and this kernel wants a higher one; at the row counts it actually runs, the two - // occupy the same LDS and bf16 only adds conversions. + // 32: reduced values are staged as fp32 in the norm's own array, so staging costs no extra LDS. + // bf16 staging would fit more rows per block, but only lowers the block count, which this + // kernel does not want; at the row counts it runs, the LDS is the same. if (stage_bits) *stage_bits = 32; if (chunk_elems) *chunk_elems = ARN_CE; if (chunk_bytes) *chunk_bytes = ARN_WV * ARN_NWORD * (int)sizeof(unsigned int); if (scale_bytes) *scale_bytes = ARN_CG * (int)sizeof(float); } -// The LDS one launch asks for: the norm's fp32 staging -- one row on the exact wire, every row the -// block owns on the compressed one -- the two reduction planes, and on the compressed wire this -// rank's packed half of every chunk the block owns. One formula for the launcher and for -// r4d_ar_ln_blocks_min, so the block count a caller is told fits is the one the launcher accepts. +// LDS per launch: the norm's fp32 staging (one row on the exact wire, every owned row on the +// compressed one), the two reduction planes, and on the compressed wire this rank's packed half of +// every owned chunk. Shared by the launcher and r4d_ar_ln_blocks_min so they agree. static size_t ar_ln_lds_bytes(int rows_max, int K, int thr, int wire) { size_t b = (size_t)(wire ? rows_max : 1) * K * sizeof(float) + 2 * (thr / 32) * sizeof(float); if (wire) { @@ -449,14 +404,13 @@ static size_t ar_ln_lds_bytes(int rows_max, int K, int thr, int wire) { } return b; } -// The ceiling on that dynamic allocation: a workgroup's 64 KiB less the kernel's own static words -// (the sequence and the slot), which the runtime places in front of it. +// 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; -// The fewest blocks at which this shape fits: every block owns ceil(M / nb) rows, and on the -// compressed wire each of them costs a staging slice and its chunks' packed half. -1 when no -// block count serves it -- a row too wide to stage even alone, or too wide for the register -// staging at this width -- which is the case the launcher would otherwise throw on. +// 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 +// row too wide to stage alone, or for the register staging), where the launcher would throw. int r4d_ar_ln_blocks_min(int M, int K, int had, int nthreads, int wire) { if (M < 1 || K < 1 || had < 32 || K % had) return -1; if (wire != 0 && wire != 6) return -1; @@ -478,7 +432,6 @@ void r4d_ar_ln_had_quant_i8(long peer_scratch, long my_scratch, long peer_flags, int M, int K, int had, float eps, float wadd, long stream, int nblocks, int nthreads, int drain, int acq, int wire) { if (K % 16) throw std::runtime_error("r4d ar_ln_had_quant_i8: K must be a multiple of 16"); - if (K % 8) throw std::runtime_error("r4d ar_ln_had_quant_i8: K*2 must be 16B-aligned"); if (M < 1) throw std::runtime_error("r4d ar_ln_had_quant_i8: M must be positive"); if (had < 2 || (had & (had - 1))) throw std::runtime_error( "r4d ar_ln_had_quant_i8: had must be a power of two"); @@ -496,10 +449,10 @@ void r4d_ar_ln_had_quant_i8(long peer_scratch, long my_scratch, long peer_flags, const int rows_max = (M + nb - 1) / nb; if (wire) { if (wire != 6) throw std::runtime_error("r4d ar_ln_had_quant_i8: wire must be 0 or 6"); - // A chunk may not straddle a row, or a block's rows would not be a whole number of chunks - // and the two ranks would disagree about who owns which bytes. + // A chunk may not straddle a row, or the ranks would disagree on byte ownership. if (K % ARN_CE) throw std::runtime_error( - "r4d ar_ln_had_quant_i8: the 6-bit wire needs K to be a multiple of 1024"); + "r4d ar_ln_had_quant_i8: the 6-bit wire needs K to be a multiple of " + + std::to_string(ARN_CE)); } const size_t shmem = ar_ln_lds_bytes(rows_max, K, thr, wire); if (shmem > kArnLdsCap) throw std::runtime_error( diff --git a/libr4d/r4d_ar_oneshot_2rank_exact.hip b/libr4d/r4d_ar_oneshot_2rank_exact.hip index 1af343d8..9d6a5137 100644 --- a/libr4d/r4d_ar_oneshot_2rank_exact.hip +++ b/libr4d/r4d_ar_oneshot_2rank_exact.hip @@ -1,28 +1,23 @@ // r4d_ar_oneshot_2rank_exact.hip: r4d_ar_oneshot_2rank_exact -- multi-block one-shot P2P-BAR -// all-reduce, exactly two ranks, for dual R9700 (gfx1201/RDNA4, PCIe). "One-shot" is the -// algorithm class: each rank pushes its whole input, so the scratch is sized by the full message -// and there is no ring or reduce-scatter stage. "2rank" is a hard constraint, not a tuning -// choice -- the handshake is one peer flag per block, not a tree. Pure HIP behind the C ABI in -// r4d.h (wheel-ROCm ships no rocThrust, which torch/extension.h needs); the caller passes raw -// data_ptr / numel / dtype / stream. +// all-reduce, exactly two ranks, for dual R9700 (gfx1201/RDNA4, PCIe). One-shot: each rank pushes +// its whole input, so scratch is sized by the full message and there is no ring or reduce-scatter +// stage. Two ranks is a hard constraint: the handshake is one peer flag per block. Pure HIP behind +// the C ABI in r4d.h; the caller passes raw pointers, element count, dtype and stream. // // Design: -// * PUSH model: each rank writes ITS input into the PEER's IPC scratch, then reduces -// (local input + peer's data now in MY scratch) -> out. Only scratch+flags are -// IPC-shared; input/output stay local -> no cudagraph buffer registration needed. -// * MULTI-BLOCK, per-chunk independent flags (NO grid barrier): block b owns a -// contiguous chunk of 16B words -> pushes it to peer, sets peer_flags[b], spins on -// my_flags[b], reduces its chunk. Spreads the push across CUs (PCIe saturation) and -// the reduce across CUs (HBM saturation): the single-block bandwidth fix. -// * cudagraph-safe: seq is a DEVICE-resident PER-BLOCK counter the kernel increments. -// Both ranks execute the identical graph sequence (SPMD) so seq_ctr[b] stays in -// lockstep across ranks regardless of which batch-size graphs ran. -// * race-free reuse: scratch DOUBLE-BUFFERED by a per-LAUNCH parity (r4d_ar_seq.h says why it -// is not seq&1); same-stream serialization + the per-block flag handshake guarantee a slot -// is drained before reuse. -// * FINE-GRAINED memory (hipDeviceMallocFinegrained) => uncached => posted straight to -// the fabric => SCOPE_SYS release/acquire skip the L2 writeback. drain/acq explicit -// fences are tunable (all-thread system fences; default drain=1/acq=0 on fine-grained). +// * Push: each rank writes its input into the peer's IPC scratch, then reduces local input + +// peer data (now in its own scratch) into out. Only scratch and flags are IPC-shared; input and +// output stay local, so graph capture needs no buffer registration. +// * Multi-block with per-chunk flags and no grid barrier: block b owns a contiguous chunk of 16B +// words, pushes it, sets peer_flags[b], spins on my_flags[b] and reduces its chunk. This +// spreads the push (PCIe) and the reduce (memory) across CUs. +// * Graph-safe: seq is a device-resident per-block counter the kernel increments. Both ranks run +// the same launch sequence (SPMD), so seq_ctr[b] stays in lockstep across ranks. +// * Reuse: scratch is double-buffered by a per-launch parity (r4d_ar_seq.h explains why not +// seq&1); same-stream serialisation plus the handshake drain a slot before reuse. +// * 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 "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 @@ -51,7 +46,7 @@ __device__ __forceinline__ void rd_from_f(float v, float& o) { o = v; } __device__ __forceinline__ void rd_from_f(float v, __half& o) { o = __float2half(v); } __device__ __forceinline__ void rd_from_f(float v, __hip_bfloat16& o) { o = (__hip_bfloat16)v; } -// vectorized 128-bit add: an int4 packs LANES elements of T; fp32-accumulate reduce. +// Vectorised 128-bit add: an int4 packs LANES elements of T, summed in fp32. template __device__ __forceinline__ int4 vadd(const int4& a, const int4& b) { int4 r; @@ -63,8 +58,8 @@ __device__ __forceinline__ int4 vadd(const int4& a, const int4& b) { return r; } -// Multi-block one-shot all-reduce. Each block owns words [start,end) of the 16B-word -// space and drives its own flag handshake; fully independent, no cross-block sync. +// Multi-block one-shot all-reduce. Each block owns words [start,end) of the 16B-word space and +// drives its own flag handshake; no cross-block sync. template __global__ void r4d_ar_oneshot_2rank_exact_kernel( const int4* __restrict__ in4, int4* peer_base, const int4* my_base, int4* __restrict__ out4, @@ -82,7 +77,7 @@ __global__ void r4d_ar_oneshot_2rank_exact_kernel( const int start = b * w; int end = start + w; if (end > n16) end = n16; - // push chunk -> peer slot, 4x-unrolled for memory-level parallelism (PCIe saturation) + // Push the chunk to the peer slot, 4x unrolled for memory-level parallelism. { int k = start + tid; for (; k + 3 * nt < end; k += 4 * nt) { @@ -91,15 +86,14 @@ __global__ void r4d_ar_oneshot_2rank_exact_kernel( } for (; k < end; k += nt) ps[k] = in4[k]; } - // drain modes (ordering of the pushes vs the release flag, so the peer sees data first): - // 0 = none (relies purely on PCIe posted-write ordering + the release flag) - // 1 = all-thread __threadfence_system (safe but emits an L2 wb-invalidate per - // wavefront (WASTED on fine-grained/uncached memory; floods at high nt*nb) - // 2 = single-thread __threadfence_system (cheap but only drains wavefront 0's stores) - // 3 = all-thread store-completion wait (s_wait_storecnt 0): every wavefront drains - // its posted writes into the fabric with NO L2 wb-invalidate; PCIe keeps posted - // writes to the same peer ordered, so the later release flag lands after the data. - // Correct for FINE-GRAINED memory (uncached; coarse would leave data in L2). + // 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) + // 1 = all-thread __threadfence_system: safe, but an L2 writeback-invalidate per wave, wasted + // on fine-grained memory and costly at high nt*nb + // 2 = single-thread __threadfence_system: cheap, but drains only wave 0's stores + // 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). if (drain == 1) __threadfence_system(); else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory"); __syncthreads(); @@ -107,15 +101,14 @@ __global__ void r4d_ar_oneshot_2rank_exact_kernel( if (drain == 2) __threadfence_system(); store_sys_rel(&peer_flags[b], s); unsigned long long z = 0; - // A handshake that cannot complete is a lockstep violation: reducing a slot the peer never - // filled would hand stale bytes on as a sum, so it traps instead. + // 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)) { if (++z > R4D_AR_SPIN_MAX) __builtin_trap(); } } __syncthreads(); if (acq) __threadfence_system(); - // reduce chunk (vectorized, 4x-unrolled): out = local input + peer input (staged in local scratch) + // Reduce the chunk, 4x unrolled: out = local input + peer input (staged in local scratch). { int k = start + tid; for (; k + 3 * nt < end; k += 4 * nt) { @@ -128,16 +121,14 @@ __global__ void r4d_ar_oneshot_2rank_exact_kernel( } } -// THE SAME ALL-REDUCE WITH THE GATED RESIDUAL'S WRITE AS ITS EPILOGUE. `y` is the message: every -// word is reduced exactly as the kernel above reduces it and stored back, and then the hc streams -// behind it take the write, h[r][c*n + i] += inj[r][c] * y[r][i], in hc_write's arithmetic -// (r4d_hc_bf16.hip) -- its bf16 helpers, its expression, and the reduced value read as the bf16 -// the reduction stored, which is what hc_write reads back from memory. So the pair's output is -// reproduced to the byte with no second launch: on this part a dependent launch is a gap of about -// three microseconds, around a write that costs one or two. +// The same all-reduce with the gated residual write as its epilogue. `y` is the message: each word +// is reduced as above and stored back, then the hc streams take +// h[r][c*n + i] += inj[r][c] * y[r][i] in hc_write's arithmetic (r4d_hc_bf16.hip) over the stored +// bf16 value. The output matches the two-kernel pair byte for byte without the second launch (a +// dependent launch gap is about 3 us on this part, against a 1-2 us write). // -// A word is eight elements and a row is `n` of them with n a multiple of eight, so a word never -// straddles a row and the block that reduces it owns every stream element behind it. +// n is a multiple of eight, so a word never straddles a row and the block that reduces it owns +// every stream element behind it. __global__ void r4d_ar_hc_write_kernel( int4* __restrict__ y4, int4* peer_base, const int4* my_base, unsigned int* peer_flags, unsigned int* my_flags, unsigned int* seq_ctrs, const unsigned short* __restrict__ inj, @@ -190,28 +181,24 @@ __global__ void r4d_ar_hc_write_kernel( } } -// THE SAME WRITE WITH THE MoE GATHER AS ITS PROLOGUE. The routed experts' rows go back to token -// order -- y[t][i] = sum over t's slots, ascending, of w[t][j] * y_expert[slot][i], rounded to -// bf16 -- with the shared arm folded as moe_gather folds it, and the word is pushed to the peer -// and kept as this rank's message exactly as if moe_gather had written it and this kernel had read -// it back. The arithmetic is moe_gather's, rounding helpers included: its narrows are -// round-to-nearest-even (r4d_common.h), where the hc write below keeps hc_write's own. So the -// three kernels' bytes are reproduced with two fewer dependent launches. +// The same write with the MoE gather as its prologue. The routed experts' rows go back to token +// order, y[t][i] = sum over t's slots, ascending, of w[t][j] * y_expert[slot][i] rounded to bf16, +// with the shared arm folded in as moe_gather does; the word is pushed to the peer and kept as this +// rank's message. The gather uses moe_gather's round-to-nearest-even narrows (r4d_common.h), the hc +// write keeps hc_write's, so the bytes match the three separate kernels with two fewer launches. // -// A block's words sit in at most R4D_ARG_ROWS rows (the launcher sizes the grid so), and the -// slots of those rows are found once, in LDS, by one pass over the sorted list -- the scan -// moe_gather makes a token at a time. +// A block's words sit in at most R4D_ARG_ROWS rows (the launcher sizes the grid for it), and their +// slots are found once, in LDS, in one pass over the sorted list. // -// AT A PREFILL CHUNK THAT TABLE IS THE WRONG SHAPE. Eight rows a block is what makes it fit in -// LDS, and at 2048 rows it takes hundreds of blocks -- each scanning the whole sorted list, and -// each paying its own flag round trip over a fabric the all-reduce saturates with a few dozen. So -// with INV the slots come from an inverse table instead -- inv[token * top_k + slot] = the sorted -// row holding it, or -1 -- built by one launch in front (r4d_ar_gather_inv_kernel), and a block -// owns as many rows as the all-reduce's own block count gives it. The gather's reads of the -// routed rows then run beside the push of the words already summed, where the pair of kernels runs -// them one after the other. The arithmetic is the table form's, value for value. -/* inv[f] = i for every sorted row i holding slot f, and -1 for a slot no row holds: one block, so - * the clear and the scatter are two phases with a barrier between them. */ +// That table does not suit a prefill chunk: eight rows per block means hundreds of blocks at 2048 +// rows, each scanning the whole sorted list and paying its own flag round trip, where a few dozen +// already saturate the fabric. With INV the slots come from an inverse table instead +// (inv[token * top_k + slot] = sorted row holding it, or -1), built by r4d_ar_gather_inv_kernel +// beforehand, and the block count stays the all-reduce's. The gather's reads then overlap the push +// of words already summed. The arithmetic is identical to the table form. + +/* inv[f] = i for every sorted row i holding slot f, -1 for a slot no row holds. One block, so the + * clear and the scatter are separated by a barrier. */ __global__ void r4d_ar_gather_inv_kernel(int* __restrict__ inv, const int* __restrict__ sorted, int T) { for (int x = threadIdx.x; x < T; x += blockDim.x) inv[x] = -1; @@ -249,8 +236,8 @@ __global__ void r4d_ar_gather_hc_write_kernel( const int nrow = end > start ? (end - 1) / wpr - row_lo + 1 : 0; const int K = G.top_k; - /* The slot table. A slot no sorted row claims reads -1, so the clear and the scan are two - * phases with a barrier between them, as in moe_gather. */ + /* Slot table. A slot no sorted row claims reads -1, so clear and scan are separated by a + * barrier, as in moe_gather. */ if (!INV) { for (int x = tid; x < nrow * K; x += nt) s_i[x] = -1; __syncthreads(); @@ -271,7 +258,7 @@ __global__ void r4d_ar_gather_hc_write_kernel( __syncthreads(); } - /* The gather, one word a thread a pass, pushed and kept. */ + /* Gather one word per thread per pass; push it and keep it. */ for (int k = start + tid; k < end; k += nt) { const int row = k / wpr, i0 = (k - row * wpr) * 8; const int4 out = r4d_ar_gather_word(G, inv, s_i, s_w, s_g, row, row - row_lo, i0); @@ -302,8 +289,7 @@ __global__ void r4d_ar_gather_hc_write_kernel( } } -// The IPC handle is returned through a caller-owned buffer rather than a std::string so this -// stays a C ABI; R4D_AR_HANDLE_BYTES is the fixed size the header promises. +// The IPC handle goes into a caller-owned buffer of R4D_AR_HANDLE_BYTES so this stays a C ABI. static_assert(sizeof(hipIpcMemHandle_t) <= R4D_AR_HANDLE_BYTES, "ipc handle larger than the ABI buffer"); long r4d_ar_ipc_alloc(long size, int finegrained, char* out_handle, int* out_len) { @@ -311,8 +297,8 @@ long r4d_ar_ipc_alloc(long size, int finegrained, char* out_handle, int* out_len if (finegrained) HIPOK(hipExtMallocWithFlags(&p, size, hipDeviceMallocFinegrained)); else HIPOK(hipMalloc(&p, size)); HIPOK(hipMemset(p, 0, size)); - // The zeroes must be in memory before the pointer is handed to a peer, whose first push or flag - // store would otherwise race a memset still queued behind it. + // The zeroes must land before the pointer reaches a peer, or its first push or flag store could + // race the queued memset. HIPOK(hipStreamSynchronize(nullptr)); hipIpcMemHandle_t h; HIPOK(hipIpcGetMemHandle(&h, p)); @@ -320,34 +306,18 @@ long r4d_ar_ipc_alloc(long size, int finegrained, char* out_handle, int* out_len *out_len = (int)sizeof(h); return (long)p; } -long r4d_ar_ipc_open(const char* handle, int len) { - hipIpcMemHandle_t h; - if (len != (int)sizeof(h)) throw std::runtime_error("bad ipc handle size"); - std::memcpy(&h, handle, sizeof(h)); - void* p = nullptr; - HIPOK(hipIpcOpenMemHandle(&p, h, hipIpcMemLazyEnablePeerAccess)); - return (long)p; -} -// A strided device-to-device copy, which is what an ALL-GATHER between two ranks is once the -// peer's buffer is IPC-mapped: no reduction, no codec, nothing to schedule. The runtime's copy -// path is the fast one for peer traffic on this part -- 13.52 GB/s per direction with both -// directions running, against 9.30 for a kernel doing b128 peer loads and 10.1 for RCCL. -// `dpitch`, `spitch` and `width` are BYTES; `height` is rows. -// THE SAME COPY AS A KERNEL, WITH A BOUNDED WORKGROUP COUNT. +// r4d_p2p_copy2d as a kernel with a bounded workgroup count. // -// `hipMemcpy2DAsync` is not a DMA engine on this part -- it runs as -// `__amd_rocclr_copyBufferRectAligned` -- and it launches ONE 16-thread workgroup per 16 bytes of -// a row: a 64 x 248 KB rectangle is 62080 workgroups. Alone that is fine and reaches the link -// rate. Sharing the part with a GEMM it is meant to hide under, it fills every scheduling slot, -// costs that GEMM around 60% of its runtime again, and gains almost nothing itself. +// hipMemcpy2DAsync is not a DMA engine on this part: it runs as +// `__amd_rocclr_copyBufferRectAligned`, one 16-thread workgroup per 16 bytes of a row (62080 +// workgroups for 64 x 248 KB). Alone it reaches link rate, but beside the GEMM it should hide +// under, it fills every scheduling slot and slows that GEMM by about 60%. // -// A peer copy needs a very small grid: across access width x workgroup size x workgroup count x -// loads-in-flight (swept by `dev/prrun.py`), 32 workgroups of 64 threads is within 0.1% of the -// best point at every size. So this takes the grid as an argument and defaults to 64 workgroups, -// which is a 0.1% footprint against the blit's 62080. +// A peer copy needs only a small grid: 32 workgroups of 64 threads is within 0.1% of the best +// configuration at every size. The grid is an argument and defaults to at most 64 workgroups. // -// 16-byte accesses, so every pitch, the width and both base addresses must be 16-byte aligned; the -// caller checks and falls back to `r4d_p2p_copy2d` when they are not. +// 16-byte accesses: every pitch, the width and both base addresses must be 16-byte aligned; the +// caller checks and falls back to r4d_p2p_copy2d otherwise. typedef unsigned r4d_u4v __attribute__((ext_vector_type(4))); __global__ __launch_bounds__(256) void r4d_p2p_copy2d_k(const r4d_u4v* __restrict__ src, @@ -378,12 +348,10 @@ int r4d_p2p_copy2d_kernel(long dst, long src, long dpitch, long spitch, long wid return e == hipSuccess ? 0 : -100 - (int)e; } -// A SYSTEM-SCOPE RELEASE on `stream`, for the case where this device has written into the PEER's -// memory and something other than this device is about to read it. A peer write issued by a copy -// or a kernel is a posted write: it retires from the wave long before it lands, and the only thing -// that orders it against a later handshake on a different path is a system-scope release. One -// thread is enough -- the fence is a memory-system operation, not a per-lane one -- and it costs a -// dispatch. +// A system-scope release on `stream`, for when this device has written into peer memory that +// another agent will read. A peer write from a copy or kernel is posted and retires long before it +// lands; only a system-scope release orders it against a later handshake on a different path. One +// thread suffices, since the fence is a memory-system operation. __global__ void r4d_p2p_fence_kernel() { __threadfence_system(); } int r4d_p2p_fence(long stream) { @@ -392,6 +360,10 @@ int r4d_p2p_fence(long stream) { return e == hipSuccess ? 0 : -100 - (int)e; } +// A strided device-to-device copy: a two-rank all-gather once the peer's buffer is IPC-mapped. +// The runtime's copy path is the fast one for peer traffic on this part (13.52 GB/s per direction +// with both directions busy, against 9.30 for a b128-load kernel and 10.1 for RCCL). +// `dpitch`, `spitch` and `width` are bytes; `height` is rows. int r4d_p2p_copy2d(long dst, long src, long dpitch, long spitch, long width, long height, long stream) { hipError_t e = hipMemcpy2DAsync((void*)dst, (size_t)dpitch, (const void*)src, (size_t)spitch, @@ -407,6 +379,7 @@ void r4d_ar_hc_write(long peer_scratch, long my_scratch, long peer_flags, long m hipStream_t st = (hipStream_t)stream_i; if (n <= 0 || M <= 0 || n % 8) throw std::runtime_error("ar_hc_write: n must be a positive multiple of 8"); if (hc < 1 || hrow % 8) throw std::runtime_error("ar_hc_write: the streams must be whole 16B words"); + if (M * n * 2 / 16 > slot_stride16) throw std::runtime_error("ar_hc_write: message larger than a slot"); const int n16 = (int)(M * n * 2 / 16); int nb = (int)nblocks; if (nb < 1) nb = 1; @@ -434,20 +407,20 @@ int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags, if (n <= 0 || M <= 0 || n % 8 || hc < 1 || hrow % 8) return -1; if (top_k < 1 || top_k > R4D_ARG_SLOTS) return -2; if (ye_ld % 8 || (sh && sh_ld < n)) return -3; + if (M * n * 2 / 16 > slot_stride16) return -5; /* larger than a slot */ const int n16 = (int)(M * n * 2 / 16); const int wpr = (int)(n / 8); const unsigned nbw = (unsigned)r4d_ar_max_blocks(); int nb = (int)nblocks; if (nb < 1) nb = 1; - /* THE GRID IS AT LEAST WIDE ENOUGH THAT NO BLOCK SPANS MORE THAN R4D_ARG_ROWS ROWS: a block of - * w words starting anywhere touches at most (w - 1) / wpr + 2 rows. Both ranks compute the same - * count from the same M and n, which the per-block handshake requires. */ + /* Enough blocks that none spans more than R4D_ARG_ROWS rows: a block of w words touches at most + * (w - 1) / wpr + 2 rows. Both ranks compute the same count from the same M and n, as the + * per-block handshake requires. */ const int wmax = (R4D_ARG_ROWS - 2) * wpr + 1; const int nb_min = (n16 + wmax - 1) / wmax; - /* THE INVERSE TABLE WHEN THE LDS ONE WOULD NEED MORE BLOCKS THAN THE REDUCTION WANTS, which is - * a prefill chunk and never a decode step. Both ranks decide it from the same M and n. The - * block count stays the reduction's: at a 2048-row chunk 48 and 96 blocks measure within half - * a percent of its 24, and 192 no better. */ + /* Use the inverse table when the LDS table would need more blocks than requested (a prefill + * chunk, never a decode step); both ranks decide from the same M and n. The block count stays + * the requested one: at a 2048-row chunk, 48, 96 and 192 blocks are no faster than 24. */ const bool by_inv = inv != 0 && nb_min > nb; if (!by_inv && nb < nb_min) nb = nb_min; if (nb > n16) nb = n16; @@ -455,8 +428,8 @@ 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; - /* Zeroed whole, padding included: the struct is passed by value, so its tail padding is - * kernel-argument bytes too, and a recorded pass's audit compares those bytes. */ + /* 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; std::memset(&G, 0, sizeof G); G.ye = (const unsigned short*)ye; @@ -483,8 +456,8 @@ int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags, return (int)hipGetLastError(); } -/* The inverse slot table alone, on `stream`, for the wide fused gather (r4d_ar_oneshot_Nrank_exact.hip): - * the same kernel and the same launch as above, so both widths read one table. */ +/* The inverse slot table alone, for the wide fused gather (r4d_ar_oneshot_Nrank_exact.hip); same + * kernel and launch as above. */ int r4d_ar_gather_inv(long inv, long sorted, long T, long stream_i) { if (!inv || !sorted || T < 1) return -1; r4d_ar_gather_inv_kernel<<<1, 1024, 0, (hipStream_t)stream_i>>>((int*)inv, (const int*)sorted, @@ -493,14 +466,11 @@ int r4d_ar_gather_inv(long inv, long sorted, long T, long stream_i) { } void r4d_ar_ipc_free(long p) { if (p) (void)hipFree((void*)p); } -void r4d_ar_ipc_memzero(long p, long size) { if (p) HIPOK(hipMemset((void*)p, 0, size)); } -// THE HOST MAILBOX. Coherent so a peer's stores are not held in a CPU cache line this card reads -// around, mapped so the cards address it, portable so every card does and not only the one -// current at allocation. A card reaches it through the same fine-grained path a peer's VRAM -// scratch is reached by, so the kernels' fences mean what they mean there. The address a card -// uses must be the CPU's own, because one pointer is published to every rank: a mapping that put -// the pages elsewhere on some card would have each rank write where no other rank reads. +// Host mailbox. Coherent so a peer's stores are not held in a CPU cache line, mapped so cards can +// address it, portable so every card can (not only the current one). Cards reach it over the same +// fine-grained path as a peer's VRAM scratch, so the kernels' fences apply unchanged. The card +// address must equal the CPU address, because one pointer is published to every rank. long r4d_ar_host_alloc(long size) { void* p = nullptr; HIPOK(hipHostMalloc(&p, size, hipHostMallocCoherent | hipHostMallocMapped | @@ -518,9 +488,8 @@ long r4d_ar_host_alloc(long size) { } void r4d_ar_host_free(long p) { if (p) (void)hipHostFree((void*)p); } -// Enable direct peer access. radiance runs one process with a thread per rank sharing an address -// space, so a peer pointer is valid here once this has run and no IPC handle exchange is needed; -// see the header of r4d_ar_entry.hip. +// Enable direct peer access. Ranks are threads of one process sharing an address space, so a peer +// pointer is valid once this has run and no IPC handle exchange is needed (see r4d_ar_entry.hip). void r4d_ar_ipc_enable_peer(long peer) { hipError_t e = hipDeviceEnablePeerAccess((int)peer, 0); if (e == hipErrorPeerAccessAlreadyEnabled) { (void)hipGetLastError(); return; } @@ -537,13 +506,14 @@ void r4d_ar_oneshot_2rank_exact(long peer_scratch, long my_scratch, long peer_fl const int esize = (dtype == 2) ? 4 : 2; const long nbytes = (long)n_elem * esize; if (nbytes % 16 != 0) throw std::runtime_error("all_reduce: n_elem*esize not 16B-aligned"); + if (nbytes / 16 > slot_stride16) throw std::runtime_error("all_reduce: message larger than a slot"); const int n16 = (int)(nbytes / 16); int nb = (int)nblocks; if (nb < 1) nb = 1; if (nb > n16) nb = n16; if (nb > R4D_AR_MAX_BLOCKS) nb = R4D_AR_MAX_BLOCKS; - // The counter allocation's block capacity, which every 2-rank kernel on an instance must agree - // on because the parity counters sit that many words in (r4d_ar_seq.h). + // Block capacity of the counter allocation. Every 2-rank kernel on an instance must agree on it, + // because the parity counters start that many words in (r4d_ar_seq.h). const unsigned nbw = (unsigned)r4d_ar_max_blocks(); if ((unsigned)nb > nbw) nb = (int)nbw; int nt = (int)nthreads; diff --git a/libr4d/r4d_ar_oneshot_2rank_wht6.h b/libr4d/r4d_ar_oneshot_2rank_wht6.h index 68ba6aba..576747dc 100644 --- a/libr4d/r4d_ar_oneshot_2rank_wht6.h +++ b/libr4d/r4d_ar_oneshot_2rank_wht6.h @@ -1,37 +1,34 @@ #pragma once // r4d_ar_oneshot_2rank_wht6.h: device code for r4d_ar_oneshot_2rank_wht6, the rotated 6-bit payload of the -// one-shot 2-rank P2P all-reduce on dual R9700 (gfx1201/RDNA4, PCIe). Companion to -// r4d_ar_oneshot_2rank_exact.hip: reuses the IPC scratch, per-block flags and device-resident seq -// counters that module allocates. Dispatched for large messages, where the wire time dominates -// and 6.25 bits per element buys more than the rotation and packing cost. +// one-shot 2-rank P2P all-reduce on dual R9700 (gfx1201/RDNA4, PCIe). Reuses the IPC scratch, +// per-block flags and device-resident seq counters of r4d_ar_oneshot_2rank_exact.hip. Used for +// large messages, where wire time dominates and 6.25 bits per element saves more than the rotation +// and packing cost. // // Design: -// * Each group of GROUP=64 is rotated by an orthonormal Walsh-Hadamard, scaled by its own -// amax and stored as BITS=6 uniform bits plus a bf16 scale -> 6.25 bits/element. The -// rotation removes the outlier channel, which is what makes 6 uniform bits enough. -// * PUSH rotates, quantizes and packs straight into the peer's scratch, keeping a copy of -// the same words locally. REDUCE unpacks both halves, adds in fp32, inverse-rotates (the -// transform is its own inverse) and stores bf16/fp16. -// * The local half is kept packed rather than recomputed: re-deriving it would repeat the -// rotation and the amax reduction. -// * Both ranks fold the identical pair and fp32 add commutes, so the ranks stay -// bit-identical. MUST be built with -ffp-contract=off: the two ranks see the two products -// in opposite order, and contracting either into an FMA makes them disagree by ~1 ULP. -// * cudagraph-safe and double-buffered as in r4d_ar_oneshot_2rank_exact.hip: per-block device-resident -// seq counter, slot from the per-launch parity counters (r4d_ar_seq.h). +// * Each group of GROUP=64 is rotated by an orthonormal Walsh-Hadamard, scaled by its own amax +// and stored as BITS=6 uniform bits plus a bf16 scale (6.25 bits/element). The rotation +// spreads the outlier channel, which is what makes 6 uniform bits enough. +// * Push rotates, quantizes and packs straight into the peer's scratch and keeps a local copy +// of the same words (cheaper than repeating the rotation and amax). Reduce unpacks both +// halves, adds in fp32, inverse-rotates (the transform is its own inverse) and stores +// bf16/fp16. +// * Both ranks fold the same pair and fp32 add commutes, so the ranks stay bit-identical. Must +// be built with -ffp-contract=off: the ranks see the two products in opposite order, and an +// FMA on either makes them differ by ~1 ULP. +// * Graph-safe and double-buffered as in r4d_ar_oneshot_2rank_exact.hip: per-block +// device-resident seq counter, slot from the per-launch parity counters (r4d_ar_seq.h). // // Layout, per slot, inside the shared 2*max_bytes scratch: // [ packed symbols, chunk-interleaved ] ... [ scale_off_bytes ] ... [ bf16 scales: n_groups ] -// A CHUNK is 32 groups = 2048 elements here. One wave owns a chunk and every lane emits exactly 64 -// symbols = 384 bits = three uint4, so flush points are lane-uniform and lane L's u-th uint4 -// lands at c*96 + u*WAVE + L: one coalesced 512B store per wave. A chunk of fewer groups -// (Wht6Chunk, below) packs its lane's NW words the same way, as dwords when NW is not a multiple of -// four. +// A chunk is 32 groups = 2048 elements by default. One wave owns a chunk and every lane emits 64 +// symbols = 384 bits = three uint4, so flush points are lane-uniform and lane L's u-th uint4 lands +// at c*96 + u*WAVE + L: one coalesced 512B store per wave. Smaller chunks (Wht6Chunk) pack a +// lane's NW words the same way, as dwords when NW is not a multiple of four. // -// n_groups need not tile a chunk. Groups past the end quantize zeros and are skipped on the way -// out. That is only safe because a group spans LPG lane-contiguous lanes and every cross-lane -// exchange in wht() is intra-group (m < LPG), so a group is wholly active or wholly inactive and -// no shuffle is ever split across the guard. +// n_groups need not tile a chunk: groups past the end quantize zeros and are skipped on output. +// This is safe only because a group spans LPG contiguous lanes and every cross-lane exchange in +// wht() stays inside the group (m < LPG), so no shuffle is split across the guard. #include #include #include @@ -67,8 +64,8 @@ __device__ __forceinline__ float rd_to_f(const __hip_bfloat16& x) { return (floa __device__ __forceinline__ void rd_from_f(float v, __half& o) { o = __float2half(v); } __device__ __forceinline__ void rd_from_f(float v, __hip_bfloat16& o) { o = (__hip_bfloat16)v; } -// RTNE to bf16 and back: the scale ships as its top 16 bits, so the sender's local copy has to be -// exactly what the receiver reconstructs. +// RTNE to bf16 and back: the scale ships as its top 16 bits, and the sender's local copy must +// equal what the receiver reconstructs. __device__ __forceinline__ float bf16_round(float v) { unsigned u = __float_as_uint(v); const unsigned lsb = (u >> 16) & 1u; @@ -77,9 +74,9 @@ __device__ __forceinline__ float bf16_round(float v) { } -// `lo ? (v + o) : (o - v)` written as `o + (lo ? v : -v)`: the sign flip is one XOR against a mask -// that is uniform over the whole stage, so the per-element select disappears. Bit-identical -- -// IEEE negation is exact and addition commutes. +// `lo ? (v + o) : (o - v)` written as `o + (lo ? v : -v)`: the sign flip is one XOR with a mask +// uniform over the stage, so the per-element select disappears. Bit-identical, since IEEE negation +// is exact and addition commutes. template __device__ __forceinline__ void ar6_xstage(float* v, int lig) { const unsigned int sm = (lig & M) ? 0x80000000u : 0u; @@ -108,17 +105,16 @@ __device__ __forceinline__ void wht(float* v, int lig) { for (int i = 0; i < EPL; ++i) v[i] *= nrm; } -// THE WIRE'S TWO HALVES OVER ONE WAVE-CHUNK, so every kernel carrying the rotated payload -- the -// all-reduce below and the fused gated-residual writes in r4d_ar_oneshot_2rank_wht6.hip -- packs and -// unpacks the same bytes by the same arithmetic. `ld(off, v)` fills the EPL elements of a LIVE group -// that start at message element `off`; `st(off, v)` takes the reduced EPL elements there. Each is -// called once per live group a lane, and a dead group quantizes zeros and is skipped on the way out. +// Push and reduce over one wave-chunk, shared by every kernel carrying the rotated payload (the +// all-reduce below and the fused gated-residual writes in r4d_ar_oneshot_2rank_wht6.hip), so all +// pack and unpack the same bytes. `ld(off, v)` fills the EPL elements of a live group starting at +// message element `off`; `st(off, v)` takes the reduced EPL elements there. Each runs once per +// live group per lane; a dead group quantizes zeros and is skipped on output. // -// CG IS THE CHUNK, in groups: 32 here (2048 elements, three uint4 a lane), fewer where a kernel -// wants more waves at work. It decides who owns which bytes and where they sit in the slot, never -// their values -- the rotation and the amax close over a group at any chunking -- so two kernels -// agree on the wire exactly when they agree on CG, which the kernel pair on the two ranks always -// does. A chunk of NW words a lane that is not a whole number of uint4 goes out as dwords. +// CG is the chunk in groups: 32 by default (2048 elements, three uint4 per lane), fewer where a +// kernel wants more waves. It sets byte ownership and placement in the slot, never values (the +// rotation and amax are per group), so two kernels agree on the wire iff they agree on CG. A +// lane's NW words go out as dwords when NW is not a multiple of four. template struct Wht6Chunk { static constexpr int ITERS = CG * GROUP / (WAVE * EPL); // group-iterations a chunk @@ -129,7 +125,7 @@ struct Wht6Chunk { static_assert(ITERS * EPL * BITS % 32 == 0, "a lane's symbols fill whole words"); }; -// PUSH: rotate, amax, quantize, pack -> peer scratch, plus a local copy for the reduce. +// Push: rotate, amax, quantize, pack into peer scratch, plus a local copy for the reduce. template __device__ __forceinline__ void wht6_push_chunk(const Ld& ld, int c, int n_groups, int lane, int lig, int gw, uint4* p_pay, @@ -194,9 +190,8 @@ __device__ __forceinline__ void wht6_push_chunk(const Ld& ld, int c, int n_group } } -// The handshake: drain the pushes into the fabric, then a per-block release flag and a spin on the -// peer's. A handshake that cannot complete is a lockstep violation -- reducing a slot the peer never -// filled would hand stale bytes on as a sum -- so it traps instead. +// Handshake: drain the pushes into the fabric, set a per-block release flag and spin on the peer's. +// A handshake that cannot complete is a lockstep violation; trap rather than sum stale bytes. __device__ __forceinline__ void wht6_handshake(unsigned int* peer_flags, unsigned int* my_flags, int b, unsigned int s, int tid, int drain, int acq) { @@ -214,7 +209,7 @@ __device__ __forceinline__ void wht6_handshake(unsigned int* peer_flags, unsigne if (acq) __threadfence_system(); } -// REDUCE: unpack both halves, add in fp32, inverse-rotate, hand each live group's EPL elements on. +// 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, int lig, int gw, const uint4* m_pay, @@ -293,7 +288,7 @@ __global__ void r4d_ar_oneshot_2rank_wht6_kernel( const int lane = tid & (WAVE - 1), wid = tid / WAVE, nwarp = nt / WAVE; const int lig = lane & (LPG - 1), gw = lane / LPG; __shared__ unsigned int s_seq, s_slot; - r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe (cudagraph) + r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe const unsigned int s = s_seq; const Wht6Slot w = wht6_slot(peer_scratch, my_scratch, loc_pack, (int)s_slot, slot_stride_bytes, scale_off_bytes); diff --git a/libr4d/r4d_ar_oneshot_2rank_wht6.hip b/libr4d/r4d_ar_oneshot_2rank_wht6.hip index afe25030..67a2575a 100644 --- a/libr4d/r4d_ar_oneshot_2rank_wht6.hip +++ b/libr4d/r4d_ar_oneshot_2rank_wht6.hip @@ -1,12 +1,12 @@ // r4d_ar_oneshot_2rank_wht6.hip: translation unit for r4d_ar_oneshot_2rank_wht6, the all-reduce whose wire -// payload is Walsh-Hadamard rotated and quantised to 6 bits. The device code and the launcher live -// in r4d_ar_oneshot_2rank_wht6.h so the same source also compiles standalone (no Python, no r4d); this file gives -// them the library's C ABI and reports the packing constants the caller needs to size its scratch. -// It also holds the rotated wire's fused forms of ar_hc_write and ar_gather_hc_write, which need -// the library's gather and hc-write arithmetic (r4d_ar_hc.h) and so live here, not in the header. +// payload is Walsh-Hadamard rotated and quantised to 6 bits. Device code and launcher live in +// r4d_ar_oneshot_2rank_wht6.h so they also compile standalone without r4d; this file exports them +// through the library's C ABI with the packing constants for sizing scratch. It also holds the +// rotated wire's fused ar_hc_write and ar_gather_hc_write, which need r4d_ar_hc.h. #include "r4d.h" #include "r4d_ar_hc.h" // the gather word and the hc write word, shared with the exact wire #include "r4d_ar_oneshot_2rank_wht6.h" +#include void r4d_ar_oneshot_2rank_wht6(long peer_scratch, long my_scratch, long peer_flags, long my_flags, long seq_ctrs, long loc_pack, long slot_stride_bytes, @@ -20,7 +20,7 @@ void r4d_ar_oneshot_2rank_wht6(long peer_scratch, long my_scratch, long peer_fla // Block cap of both all-reduce kernels (the flag array is sized from it). int r4d_ar_max_blocks(void) { return R4D_AR_MAX_BLOCKS; } -// The rotated-6-bit wire format, which the caller needs to size its packed scratch. +// Rotated 6-bit wire format dimensions, for sizing the caller's packed scratch. void r4d_ar_wht6_dims(int* group, int* bits, int* chunk_elems) { if (group) *group = GROUP; if (bits) *bits = BITS; @@ -28,37 +28,33 @@ void r4d_ar_wht6_dims(int* group, int* bits, int* chunk_elems) { } // --------------------------------------------------------------------------------------------- -// THE ROTATED WIRE WITH THE GATED RESIDUAL'S WRITE AS ITS EPILOGUE, and with GATHER the MoE gather -// as its prologue: the 6-bit twins of r4d_ar_hc_write_kernel and r4d_ar_gather_hc_write_kernel -// (r4d_ar_oneshot_2rank_exact.hip). Each reproduces the unfused chain it replaces to the byte -- -// moe_gather, r4d_ar_oneshot_2rank_wht6, hc_write -- because every stage is the same code: the -// gather word and the write word are r4d_ar_hc.h's, and the wire is wht6_push_chunk and -// wht6_reduce_chunk (r4d_ar_oneshot_2rank_wht6.h) at a smaller chunk, which moves bytes between -// owners and never changes them. The message's words are the chain's words: the gather's are rounded to -// bf16 as moe_gather stores them, and the reduced sum is rounded to bf16 as the standalone -// all-reduce stores it, stored into `y`, and read back as that bf16 by the write. +// The rotated wire with the gated residual write as epilogue and, with GATHER, the MoE gather as +// prologue: 6-bit counterparts of r4d_ar_hc_write_kernel and r4d_ar_gather_hc_write_kernel +// (r4d_ar_oneshot_2rank_exact.hip). Each matches the unfused chain (moe_gather, +// r4d_ar_oneshot_2rank_wht6, hc_write) byte for byte because every stage is the same code: the +// gather and write words from r4d_ar_hc.h, and wht6_push_chunk / wht6_reduce_chunk at a smaller +// chunk, which changes byte ownership but not values. Gathered words are rounded to bf16 as +// moe_gather stores them; the reduced sum is rounded to bf16, stored into `y` and read back as +// such by the write. // -// A lane's EPL elements are one word, so a word -- and the write behind it -- never straddles a row -// even where a group or a chunk does: the rotation closes over the flattened message, the write -// over the row the word sits in. +// A lane's EPL elements are one word, so a word and its write never straddle a row even where a +// group or chunk does: the rotation spans the flattened message, the write the word's row. // -// THE GATHER READS ITS SLOTS FROM A TABLE IN LDS, built by the block from the sorted list: the -// rows a block owns (whole wave-chunks, so tens of rows at a prefill chunk) and every slot of them, -// found by one pass over the list -- the exact form's decode-sized table, sized here by the launch -// rather than fixed at R4D_ARG_ROWS. A word's reads of the routed rows then wait on nothing but -// their own addresses, where the inverse table puts a dependent load of the slot in front of each. -// The launcher widens the grid until a block's table fits. +// The gather reads its slots from an LDS table the block builds in one pass over the sorted list, +// covering every row it owns (whole wave-chunks, so tens of rows at a prefill chunk); unlike the +// exact form it is sized by the launch, not fixed at R4D_ARG_ROWS. Reads of the routed rows then +// depend only on their own addresses, where an inverse table adds a dependent slot load before +// each. The launcher widens the grid until a block's table fits. static_assert(EPL == 8, "a lane's share of a group is one 16B word of the message"); // The LDS a block's slot table may take; the handshake's two words sit beside it. static constexpr size_t kWht6TableBytes = 60 * 1024; -// THE FUSED FORMS' CHUNK IS 8 GROUPS -- 512 elements, two group-iterations a wave -- where the -// standalone all-reduce's is 32. A wave walks its chunk's groups one after another and each one -// waits on its own reads -- the routed rows of the gather, the streams of the write -- so a -// quarter of the chunk is four times the waves at work on the same message: at a 2048-row chunk -// the gather form takes 403 us a call, against 500 at the standalone chunk and 416 at 16 groups. -// The two ranks run the same kernel, so the chunking both push and reduce under is the same. +// The fused forms use 8-group chunks (512 elements, two group-iterations per wave) instead of the +// standalone 32. A wave walks its groups serially, each waiting on its own reads (routed rows, +// streams), so a quarter-size chunk puts four times as many waves on the message: at a 2048-row +// chunk the gather form takes 403 us against 500 at 32 groups and 416 at 16. Both ranks run the +// same kernel, so they push and reduce under the same chunking. static constexpr int kWht6FusedCG = 8; // The rows block b's chunks of `ce` elements touch: [row_lo, row_lo + nrow). @@ -85,7 +81,7 @@ __global__ void r4d_ar_hc_write_wht6_kernel( __shared__ unsigned int s_seq, s_slot; extern __shared__ int s_tab[]; // slots, weights: [rows_max * top_k]; gates: [rows_max] const long long gate_word = r4d_ar_link_word(gate, (unsigned int)tid); - r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe (cudagraph) + r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe const unsigned int s = s_seq; const Wht6Slot w = wht6_slot(peer_scratch, my_scratch, loc_pack, (int)s_slot, slot_stride_bytes, scale_off_bytes); @@ -93,8 +89,8 @@ __global__ void r4d_ar_hc_write_wht6_kernel( const int cpb = (n_chunks + nb - 1) / nb; // block b owns chunks [c0,c1) const int c0 = b * cpb; int c1 = c0 + cpb; if (c1 > n_chunks) c1 = n_chunks; - /* The slot table, as the exact form's: a slot no sorted row claims reads -1, so the clear and - * the scan are two phases with a barrier between them. */ + /* Slot table, as in the exact form: a slot no sorted row claims reads -1, so clear and scan are + * separated by a barrier. */ int* s_i = s_tab; float* s_w = reinterpret_cast(s_tab + rows_max * G.top_k); float* s_g = s_w + rows_max * G.top_k; @@ -172,8 +168,8 @@ int r4d_ar_hc_write_wht6(long peer_scratch, long my_scratch, long peer_flags, lo const int n_chunks = (n_groups + kWht6FusedCG - 1) / kWht6FusedCG; int nb = clamp_blocks((int)nblocks, n_chunks); const int nt = clamp_threads((int)nthreads); - /* THE TABLE HAS TO FIT, so the grid widens until it does: a block of cpb chunks touches at most - * (cpb * ce - 1) / n + 2 rows. Both ranks compute the same grid from the same M and n, which the + /* Widen the grid until the table fits: a block of cpb chunks touches at most + * (cpb * ce - 1) / n + 2 rows. Both ranks compute the same grid from the same M and n, as the * per-block handshake requires. */ int rows_max = 0; size_t lds = 0; @@ -187,7 +183,10 @@ int r4d_ar_hc_write_wht6(long peer_scratch, long my_scratch, long peer_flags, lo } if (lds > kWht6TableBytes || nb > R4D_AR_MAX_BLOCKS) return -3; } - R4dArGather G{}; + /* Zeroed including padding, as in r4d_ar_gather_hc_write: the tail padding is part of the + * kernel-argument bytes a recorded pass's audit compares. */ + R4dArGather G; + std::memset(&G, 0, sizeof G); if (gather) { G.ye = (const unsigned short*)ye; G.ew = (const unsigned short*)ew; diff --git a/libr4d/r4d_ar_oneshot_Nrank_exact.hip b/libr4d/r4d_ar_oneshot_Nrank_exact.hip index c3a06d78..35daea6a 100644 --- a/libr4d/r4d_ar_oneshot_Nrank_exact.hip +++ b/libr4d/r4d_ar_oneshot_Nrank_exact.hip @@ -1,17 +1,15 @@ // r4d_ar_oneshot_Nrank_exact.hip: r4d_ar_oneshot_3rank_exact, r4d_ar_oneshot_4rank_exact, -// r4d_ar_oneshot_8rank_exact -- one-shot P2P push all-reduce, 3, 4 or 8 -// ranks, gfx1201. WS is compile-time; the 2-rank kernel keeps its own file. +// r4d_ar_oneshot_8rank_exact -- one-shot P2P push all-reduce, 3, 4 or 8 ranks, gfx1201. WS is +// compile-time; the 2-rank kernel has its own file. // -// Per-block handshake: block b waits only on the peers' block b, so push -// and reduce overlap. Scratch slot per (parity, source), flag per (block, -// source). Reduce is fp32 in ascending rank order, one round at the store -// -- required, or ranks diverge. Stuck handshake traps. -// Sends (ws-1)*N bytes per rank: for small messages only, where latency dominates. -// The two-shot covers larger sizes. +// Per-block handshake: block b waits only on the peers' block b, so push and reduce overlap. +// Scratch slot per (parity, source), flag per (block, source). The reduce is fp32 in ascending +// rank order with one rounding at the store; any other order makes ranks diverge. A stuck +// handshake traps. Sends (ws-1)*N bytes per rank, so it serves small, latency-bound messages; the +// two-shot covers larger sizes. // -// Also r4d_ar_hc_write_4rank: the same one-shot with hc_write as its epilogue (ar_hc_write at -// width, exact wire only), and r4d_ar_gather_hc_write_4rank: that with moe_gather as its prologue -// (ar_gather_hc_write at width, exact wire only). +// Also r4d_ar_hc_write_4rank (the same one-shot with hc_write as epilogue) and +// r4d_ar_gather_hc_write_4rank (that plus moe_gather as prologue), exact wire only. // // The IPC helpers live in r4d_ar_oneshot_2rank_exact.hip; this unit links beside it. #include "r4d.h" @@ -48,13 +46,14 @@ __global__ void r4d_ar_oneshot_wide_exact_kernel( const int4* __restrict__ my_base, unsigned int* __restrict__ my_flags, int4* __restrict__ out4, unsigned int* __restrict__ seq_ctrs, int n16, int slot_stride16, int rank, - int drain, int acq, int pub) { + int drain, int acq, int pub, long long* gate, unsigned int* gate_ctr) { constexpr int NPEERS = WS - 1; - // The reduce holds WS source words live per output word, so the 2-rank unroll spills at ws=8. + // The reduce holds WS source words live per output word, so the 2x unroll spills at ws=8. constexpr int RU = (WS <= 4) ? 2 : 1; const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x; __shared__ unsigned int s_seq, s_slot; + const long long gate_word = r4d_ar_link_word(gate, (unsigned int)tid); r4d_ar_seq_take(seq_ctrs, R4D_AR_WIDE_MAX_BLOCKS, s_seq, s_slot); // device-resident, replay-safe const unsigned int s = s_seq; const int parity = (int)s_slot; @@ -69,7 +68,7 @@ __global__ void r4d_ar_oneshot_wide_exact_kernel( for (int p = 0; p < NPEERS; ++p) ps[p] = peers.scratch[p] + ((size_t)parity * WS + rank) * (size_t)slot_stride16; - // push: 4x-unrolled, and the loaded words are reused across peers so the input is read once + // Push, 4x unrolled; loaded words are reused across peers so the input is read once. { int k = start + tid; for (; k + 3 * nt < end; k += 4 * nt) { @@ -86,15 +85,14 @@ __global__ void r4d_ar_oneshot_wide_exact_kernel( } } - // Flag values live in the 2*seq space shared by the whole wide family (the two-shot's - // half-step is 2s-1, its full step 2s), so one flag/seq/scratch set serves a mixed - // kernel stream: every kernel advances seq_ctrs[b] once per AR, parity alternates - // across the stream, and the monotonic wait stays coherent at a band crossover. The - // slot guard is the same shared discipline: each AR's writes land in its (parity, - // source) slot, the handshake keeps any rank at most one AR ahead, and the caller - // sizes the stride for the largest family in the mix -- so a crossover neighbour can - // never overlap this AR's bytes. + // Flags use the 2*seq space shared by the wide family (the two-shot's half-step is 2s-1, its + // full step 2s), so one flag/seq/scratch set serves a mixed kernel stream. Each AR writes only + // its (parity, source) slot, the handshake keeps any rank at most one AR ahead, and the caller + // sizes the stride for the largest family in the mix, so neighbouring ARs never overlap. r4d_ar_handshake(peers, my_flags, b, rank, 2u * s, drain, acq, pub); + // Every peer's push for this launch has landed and my own retired behind its flag store, so + // the link is free for the reduce: the last block here ends the engine's hold (r4d_ar_seq.h). + r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid); // Our own contribution comes from the input; slot[my rank] in my scratch is never written. const int4* src[WS]; @@ -114,28 +112,28 @@ __global__ void r4d_ar_oneshot_wide_exact_kernel( } } -// THE SAME ONE-SHOT WITH THE GATED RESIDUAL'S WRITE AS ITS EPILOGUE, bf16 only. `y` is the -// message and is reduced IN PLACE; everything up to the reduce is the kernel above, step for step, -// because the two may run on one instance's buffers in one stream: the same seq take, the same -// handshake value 2*s, the same (parity, source) slots and the same block partition of the word -// space. The reduce is the same ar_vsum, so the stored word is the plain all-reduce's to the bit; -// then h[r][c*n + i] += inj[r][c] * y[r][i] in hc_write's arithmetic over that bf16 word -// (r4d_ar_hc_write_word, as the two-rank r4d_ar_hc_write_kernel). +// The same one-shot with the gated residual write as its epilogue, bf16 only. `y` is the message +// and is reduced in place. Up to the reduce it must match the kernel above step for step (seq take, +// handshake value 2*s, (parity, source) slots, block partition), because both may run on one +// instance's buffers in one stream. The reduce is the same ar_vsum, so the stored word matches the +// plain all-reduce bit for bit; then h[r][c*n + i] += inj[r][c] * y[r][i] in hc_write's arithmetic +// (r4d_ar_hc_write_word, as in the two-rank r4d_ar_hc_write_kernel). // -// In place is safe: a thread reads every source of word k before it stores word k, its own block -// pushed that word to the peers before the handshake, and no peer reads this rank's `y`. A word is -// eight elements and n is a multiple of eight, so a word never straddles a row and the thread that -// reduces it owns every stream element behind it. +// In place is safe: a thread reads every source of word k before storing it, its block pushed the +// word before the handshake, and no peer reads this rank's `y`. A word never straddles a row +// (n is a multiple of eight), so the thread that reduces it owns every stream element behind it. template __global__ void r4d_ar_hc_write_wide_kernel( int4* __restrict__ y4, R4DArWidePeers peers, const int4* __restrict__ my_base, unsigned int* __restrict__ my_flags, unsigned int* __restrict__ seq_ctrs, const unsigned short* __restrict__ inj, unsigned short* __restrict__ h, int n16, int n, - int hc, long irow, long hrow, int slot_stride16, int rank, int drain, int acq, int pub) { + int hc, long irow, long hrow, int slot_stride16, int rank, int drain, int acq, int pub, + long long* gate, unsigned int* gate_ctr) { constexpr int NPEERS = WS - 1; const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x; __shared__ unsigned int s_seq, s_slot; + const long long gate_word = r4d_ar_link_word(gate, (unsigned int)tid); r4d_ar_seq_take(seq_ctrs, R4D_AR_WIDE_MAX_BLOCKS, s_seq, s_slot); // device-resident, replay-safe const unsigned int s = s_seq; const int parity = (int)s_slot; @@ -166,6 +164,9 @@ __global__ void r4d_ar_hc_write_wide_kernel( } r4d_ar_handshake(peers, my_flags, b, rank, 2u * s, drain, acq, pub); + // The two-rank fused write's release, at width: the reduce and the hc write behind it are + // local VRAM traffic, so the last block here ends the engine's hold (r4d_ar_seq.h). + r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid); const int4* src[WS]; #pragma unroll @@ -183,26 +184,23 @@ __global__ void r4d_ar_hc_write_wide_kernel( } } -// THE SAME WRITE WITH THE MoE GATHER AS ITS PROLOGUE, bf16 only: the four-rank form of the -// two-rank r4d_ar_gather_hc_write_kernel. `y` is not read but produced -- a block's words are -// summed back to token order from the routed experts' rows by r4d_ar_gather_word, kept as this -// rank's message and pushed to every peer, exactly as if moe_gather had written y and the kernel -// above had read it back. From the handshake on it IS the kernel above: the same seq take, the -// same value 2*s, the same (parity, source) slots, the same ar_vsum in ascending rank order over -// the same sources -- this rank's own word from y, which the same thread stored before the -// handshake -- and the same r4d_ar_hc_write_word over the stored bf16 word. So the bytes are those -// of moe_gather, the four-rank exact all-reduce and hc_write. +// The same write with the MoE gather as its prologue, bf16 only; the four-rank form of the two-rank +// r4d_ar_gather_hc_write_kernel. `y` is produced, not read: r4d_ar_gather_word sums each word back +// to token order from the routed experts' rows, stores it as this rank's message and pushes it to +// every peer. From the handshake on it is the kernel above (own word read from y, stored by the +// same thread before the handshake), so the bytes equal moe_gather, the four-rank exact all-reduce +// and hc_write run separately. // -// The slot table is the two-rank kernel's: without INV a block's rows (at most R4D_ARG_ROWS, which -// the launcher sizes the grid for) find their slots once, in LDS, by one pass over the sorted -// list; with INV they read the inverse table r4d_ar_gather_inv built in front. +// Slot table as in the two-rank kernel: without INV a block's rows (at most R4D_ARG_ROWS; the +// launcher sizes the grid for it) find their slots once, in LDS, in one pass over the sorted list; +// with INV they read the inverse table r4d_ar_gather_inv built beforehand. template __global__ void r4d_ar_gather_hc_write_wide_kernel( int4* __restrict__ y4, R4DArWidePeers peers, const int4* __restrict__ my_base, unsigned int* __restrict__ my_flags, unsigned int* __restrict__ seq_ctrs, const unsigned short* __restrict__ inj, unsigned short* __restrict__ h, int n16, int n, int hc, long irow, long hrow, int slot_stride16, int rank, int drain, int acq, int pub, - R4dArGather G, const int* __restrict__ inv) { + R4dArGather G, const int* __restrict__ inv, long long* gate, unsigned int* gate_ctr) { constexpr int NPEERS = WS - 1; const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x; @@ -210,6 +208,7 @@ __global__ void r4d_ar_gather_hc_write_wide_kernel( __shared__ int s_i[R4D_ARG_ROWS * R4D_ARG_SLOTS]; __shared__ float s_w[R4D_ARG_ROWS * R4D_ARG_SLOTS]; __shared__ float s_g[R4D_ARG_ROWS]; + const long long gate_word = r4d_ar_link_word(gate, (unsigned int)tid); r4d_ar_seq_take(seq_ctrs, R4D_AR_WIDE_MAX_BLOCKS, s_seq, s_slot); // device-resident, replay-safe const unsigned int s = s_seq; const int parity = (int)s_slot; @@ -227,8 +226,8 @@ __global__ void r4d_ar_gather_hc_write_wide_kernel( for (int p = 0; p < NPEERS; ++p) ps[p] = peers.scratch[p] + ((size_t)parity * WS + rank) * (size_t)slot_stride16; - /* The slot table. A slot no sorted row claims reads -1, so the clear and the scan are two - * phases with a barrier between them, as in moe_gather. */ + /* Slot table. A slot no sorted row claims reads -1, so clear and scan are separated by a + * barrier, as in moe_gather. */ if (!INV) { for (int x = tid; x < nrow * K; x += nt) s_i[x] = -1; __syncthreads(); @@ -249,7 +248,7 @@ __global__ void r4d_ar_gather_hc_write_wide_kernel( __syncthreads(); } - /* The gather, one word a thread a pass, kept and pushed to every peer. */ + /* Gather one word per thread per pass; keep it and push it to every peer. */ for (int k = start + tid; k < end; k += nt) { const int row = k / wpr, i0 = (k - row * wpr) * 8; const int4 out = r4d_ar_gather_word(G, inv, s_i, s_w, s_g, row, row - row_lo, i0); @@ -259,6 +258,9 @@ __global__ void r4d_ar_gather_hc_write_wide_kernel( } r4d_ar_handshake(peers, my_flags, b, rank, 2u * s, drain, acq, pub); + // As in the kernel this is the gather form of: from the handshake on, the reduce and the + // write are local, so the last block here ends the engine's hold (r4d_ar_seq.h). + r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid); const int4* src[WS]; #pragma unroll @@ -280,7 +282,8 @@ template static void ar_wide_launch(const long* peer_scratch, const long* peer_flags, long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long stream_i, long nblocks, - long nthreads, long drain, long acq, long pub) { + long nthreads, long drain, long acq, long pub, long gate, + long gate_ctr) { constexpr int NPEERS = WS - 1; static_assert(NPEERS <= R4D_AR_WIDE_MAX_PEERS, "npeers exceeds the peer bundle bound"); @@ -317,9 +320,8 @@ static void ar_wide_launch(const long* peer_scratch, const long* peer_flags, lon peers.rank[i] = (i < (int)rank) ? i : i + 1; } - // scratch must back 2*WS slots of the declared stride, flags one word per (block, source - // rank), seq a handshake and a parity word per block of capacity (r4d_ar_seq.h) -- checked - // against the allocations, not the arguments. + // Checked against the allocations: scratch backs 2*WS slots of the stride, flags one word per + // (block, source rank), seq a handshake and a parity word per block of capacity (r4d_ar_seq.h). const long slot_bytes = 2L * WS * (long)slot_stride16 * 16; const long flag_bytes = (long)nb * WS * (long)sizeof(unsigned int); r4d_ar_check_extent(my_scratch, slot_bytes, "all_reduce", "my_scratch"); @@ -336,7 +338,7 @@ static void ar_wide_launch(const long* peer_scratch, const long* peer_flags, lon r4d_ar_oneshot_wide_exact_kernel<<>>( \ (const int4*)inp, peers, (const int4*)my_scratch, (unsigned int*)my_flags, \ (int4*)out, (unsigned int*)seq_ctrs, n16, (int)slot_stride16, (int)rank, \ - (int)drain, (int)acq, (int)pub) + (int)drain, (int)acq, (int)pub, (long long*)gate, (unsigned int*)gate_ctr) if (dtype == 0) R4D_AR_WIDE_LAUNCH(__hip_bfloat16, 8); else if (dtype == 1) R4D_AR_WIDE_LAUNCH(__half, 8); else if (dtype == 2) R4D_AR_WIDE_LAUNCH(float, 4); @@ -344,11 +346,8 @@ static void ar_wide_launch(const long* peer_scratch, const long* peer_flags, lon #undef R4D_AR_WIDE_LAUNCH } -// Three ranks: the same kernel at WS=3. Nothing in the push, the handshake or the ascending-rank -// reduce assumes a power of two -- the peer bundle is WS-1 wide and the slot/flag layout is -// parity x source rank -- so this is an instantiation, not a variant. It exists because a 3-card -// box is a real configuration (three R9700s) and the two-shot cannot serve it: that one shards the -// message `world` ways and a residual width of 2560 does not divide by 3. +// Three ranks: the same kernel at WS=3; nothing in it assumes a power of two. Needed for 3-card +// systems because a residual width of 2560 does not split evenly three ways for the two-shot. void r4d_ar_oneshot_3rank_exact(long peer_scratch0, long peer_scratch1, long peer_flags0, long peer_flags1, long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, @@ -357,8 +356,9 @@ void r4d_ar_oneshot_3rank_exact(long peer_scratch0, long peer_scratch1, long pub) { const long ps[2] = {peer_scratch0, peer_scratch1}; const long pf[2] = {peer_flags0, peer_flags1}; + /* No link gate at three ranks: the row answers 1, the engine releases by barrier. */ ar_wide_launch<3>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem, - dtype, rank, stream, nblocks, nthreads, drain, acq, pub); + dtype, rank, stream, nblocks, nthreads, drain, acq, pub, 0L, 0L); } void r4d_ar_oneshot_4rank_exact(long peer_scratch0, long peer_scratch1, long peer_scratch2, @@ -366,11 +366,11 @@ void r4d_ar_oneshot_4rank_exact(long peer_scratch0, long peer_scratch1, long pee long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long stream, long nblocks, long nthreads, long drain, long acq, - long pub) { + long pub, long gate, long gate_ctr) { const long ps[3] = {peer_scratch0, peer_scratch1, peer_scratch2}; const long pf[3] = {peer_flags0, peer_flags1, peer_flags2}; ar_wide_launch<4>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem, - dtype, rank, stream, nblocks, nthreads, drain, acq, pub); + dtype, rank, stream, nblocks, nthreads, drain, acq, pub, gate, gate_ctr); } void r4d_ar_oneshot_8rank_exact(long peer_scratch0, long peer_scratch1, long peer_scratch2, @@ -385,18 +385,19 @@ void r4d_ar_oneshot_8rank_exact(long peer_scratch0, long peer_scratch1, long pee peer_scratch4, peer_scratch5, peer_scratch6}; const long pf[7] = {peer_flags0, peer_flags1, peer_flags2, peer_flags3, peer_flags4, peer_flags5, peer_flags6}; + /* No link gate at eight ranks: the row answers 1, the engine releases by barrier. */ ar_wide_launch<8>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem, - dtype, rank, stream, nblocks, nthreads, drain, acq, pub); + dtype, rank, stream, nblocks, nthreads, drain, acq, pub, 0L, 0L); } -// ar_wide_launch's checks, for the fused write: the same rank range, slot stride, grid clamps and -// allocation extents, plus the write's own two shape rules. +// ar_wide_launch's checks plus the fused write's two shape rules. template static void ar_hc_write_wide_launch(const long* peer_scratch, const long* peer_flags, long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, long y, long inj, long h, long M, long n, long hc, long irow, long hrow, long rank, long stream_i, - long nblocks, long nthreads, long drain, long acq, long pub) { + long nblocks, long nthreads, long drain, long acq, long pub, + long gate, long gate_ctr) { constexpr int NPEERS = WS - 1; static_assert(NPEERS <= R4D_AR_WIDE_MAX_PEERS, "npeers exceeds the peer bundle bound"); @@ -449,7 +450,8 @@ static void ar_hc_write_wide_launch(const long* peer_scratch, const long* peer_f r4d_ar_hc_write_wide_kernel<<>>( (int4*)y, peers, (const int4*)my_scratch, (unsigned int*)my_flags, (unsigned int*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h, n16, (int)n, (int)hc, irow, hrow, - (int)slot_stride16, (int)rank, (int)drain, (int)acq, (int)pub); + (int)slot_stride16, (int)rank, (int)drain, (int)acq, (int)pub, (long long*)gate, + (unsigned int*)gate_ctr); } void r4d_ar_hc_write_4rank(long peer_scratch0, long peer_scratch1, long peer_scratch2, @@ -457,25 +459,26 @@ void r4d_ar_hc_write_4rank(long peer_scratch0, long peer_scratch1, long peer_scr long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, long y, long inj, long h, long M, long n, long hc, long irow, long hrow, long rank, long stream, long nblocks, long nthreads, - long drain, long acq, long pub) { + long drain, long acq, long pub, long gate, long gate_ctr) { const long ps[3] = {peer_scratch0, peer_scratch1, peer_scratch2}; const long pf[3] = {peer_flags0, peer_flags1, peer_flags2}; ar_hc_write_wide_launch<4>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, y, inj, h, M, n, hc, irow, hrow, rank, stream, nblocks, nthreads, drain, acq, - pub); + pub, gate, gate_ctr); } -// ar_hc_write_wide_launch's checks plus the gather's, and the two-rank gather's grid rule: at least -// wide enough that no block spans more than R4D_ARG_ROWS rows, or -- where that would take more -// blocks than the reduction asked for and `inv` is given -- the reduction's count over the inverse -// table. Every rank computes the same count and the same choice from the same M, n and scratch. +// ar_hc_write_wide_launch's checks plus the gather's, and the two-rank gather's grid rule: enough +// blocks that none spans more than R4D_ARG_ROWS rows, or, when that exceeds the requested count and +// `inv` is given, the requested count over the inverse table. Every rank makes the same choice from +// the same M, n and scratch. template static void ar_gather_hc_write_wide_launch( const long* peer_scratch, const long* peer_flags, long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, long y, long inj, long h, long M, long n, long hc, long irow, long hrow, long ye, long ew, long sorted, long sh, long sg, long ye_ld, long ew_ld, long sh_ld, long sg_ld, long top_k, long sig, long rank, long stream_i, - long nblocks, long nthreads, long drain, long acq, long pub, long inv) { + long nblocks, long nthreads, long drain, long acq, long pub, long inv, long gate, + long gate_ctr) { constexpr int NPEERS = WS - 1; static_assert(NPEERS <= R4D_AR_WIDE_MAX_PEERS, "npeers exceeds the peer bundle bound"); @@ -539,8 +542,8 @@ static void ar_gather_hc_write_wide_launch( r4d_ar_check_extent(peer_flags[i], flag_bytes, "ar_gather_hc_write", "peer flags"); } - /* Zeroed whole, padding included: the struct is passed by value, so its tail padding is - * kernel-argument bytes too, and a recorded pass's audit compares those bytes. */ + /* 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; std::memset(&G, 0, sizeof G); G.ye = (const unsigned short*)ye; @@ -561,13 +564,13 @@ static void ar_gather_hc_write_wide_launch( (int4*)y, peers, (const int4*)my_scratch, (unsigned int*)my_flags, (unsigned int*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h, n16, (int)n, (int)hc, irow, hrow, (int)slot_stride16, (int)rank, (int)drain, (int)acq, (int)pub, G, - (const int*)inv); + (const int*)inv, (long long*)gate, (unsigned int*)gate_ctr); } else { r4d_ar_gather_hc_write_wide_kernel<<>>( (int4*)y, peers, (const int4*)my_scratch, (unsigned int*)my_flags, (unsigned int*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h, n16, (int)n, (int)hc, irow, hrow, (int)slot_stride16, (int)rank, (int)drain, (int)acq, (int)pub, G, - nullptr); + nullptr, (long long*)gate, (unsigned int*)gate_ctr); } } @@ -579,13 +582,13 @@ void r4d_ar_gather_hc_write_4rank(long peer_scratch0, long peer_scratch1, long p long sh, long sg, long ye_ld, long ew_ld, long sh_ld, long sg_ld, long top_k, long sig, long rank, long stream, long nblocks, long nthreads, long drain, long acq, long pub, - long inv) { + long inv, long gate, long gate_ctr) { const long ps[3] = {peer_scratch0, peer_scratch1, peer_scratch2}; const long pf[3] = {peer_flags0, peer_flags1, peer_flags2}; ar_gather_hc_write_wide_launch<4>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, y, inj, h, M, n, hc, irow, hrow, ye, ew, sorted, sh, sg, ye_ld, ew_ld, sh_ld, sg_ld, top_k, sig, rank, stream, nblocks, - nthreads, drain, acq, pub, inv); + nthreads, drain, acq, pub, inv, gate, gate_ctr); } void r4d_ar_wide_dims(int* max_blocks, int* nb_design, int* max_peers) { diff --git a/libr4d/r4d_ar_seq.h b/libr4d/r4d_ar_seq.h index 27622d0f..9613548c 100644 --- a/libr4d/r4d_ar_seq.h +++ b/libr4d/r4d_ar_seq.h @@ -1,51 +1,43 @@ #pragma once -// r4d_ar_seq.h: the step every all-reduce and all-gather kernel takes first -- its handshake -// sequence number and the scratch slot it pushes into -- and the wrap-safe wait that follows the -// push. One definition for the 2-rank and the wide families, because every kernel that shares an -// instance's buffers has to take the step identically or the two ranks stop agreeing. +// r4d_ar_seq.h: the first step of every all-reduce and all-gather kernel (its handshake sequence +// number and scratch slot) and the wrap-safe wait after the push. Shared by the 2-rank and wide +// families: kernels sharing an instance's buffers must take the step identically or the ranks +// disagree. // -// THE COUNTER ALLOCATION IS 2 * nbw WORDS, zeroed once, where nbw is the block capacity the flag -// array was sized for, and the landed counter after them (r4d_ar_link_landed): +// Counter allocation: 2 * nbw words, zeroed once (nbw = block capacity the flag array was sized +// for), then the landed counter (r4d_ar_link_landed): // -// [0, nbw) HANDSHAKE counters, one a block. Block b advances word b once per launch it -// runs in, publishes the new value to the peer and waits for the peer's. Kept per -// block so that a block which sat out a run of narrow launches resumes exactly -// one step past the flag its peer last published: the wrap-safe compare below is -// only sound while that gap stays far under 2^31, and a counter every block -// shared would let an idle block's flag fall arbitrarily far behind. +// [0, nbw) Handshake counters, one per block. Block b advances word b once per launch it +// runs in, publishes it to the peer and waits for the peer's. Per block so a +// block idle through narrow launches resumes one step past its peer's last flag; +// the wrap-safe compare needs that gap far under 2^31. // -// [nbw, 2*nbw) PARITY counters. Every launch advances ALL nbw of them exactly once, whatever -// its own block count -- block b takes words b, b + nb, b + 2*nb, ... -- so all -// of them always equal the number of launches, and each block reads the slot -// parity off its own word without talking to any other block. +// [nbw, 2*nbw) Parity counters. Every launch advances all nbw of them once, whatever its block +// count (block b takes words b, b + nb, b + 2*nb, ...), so each equals the launch +// count and a block reads the slot parity off its own word. // -// [2*nbw] the LANDED counter: the blocks of the running launch that have seen their -// peer's push land, back at zero when the launch ends. +// [2*nbw] Landed counter: blocks of the running launch that have seen their peer's push +// land; back at zero when the launch ends. // -// WHY THE SLOT CANNOT COME OFF THE HANDSHAKE COUNTER. The double-buffered scratch is safe only if -// consecutive launches on one instance use opposite slots: launch k+1 may push while the peer is -// still reducing launch k, and it must not land in the bytes being read. Block counts differ from -// launch to launch -- the standalone all-reduce scales with the message, the fused norm takes one -// block a row -- and so does the byte range a block owns. The handshake counters therefore drift -// apart block by block, and a slot taken from them lets a block of launch k+1 push into the slot a -// DIFFERENT block of launch k is still reading on the peer, whenever their byte ranges overlap -// and their counters happen to share a parity. The parity counters move in lockstep, so the slot -// alternates per launch for every block, as the double buffer requires. +// The slot cannot come from the handshake counter. Consecutive launches on one instance must use +// opposite scratch slots, since launch k+1 may push while the peer still reduces launch k. Block +// counts and per-block byte ranges vary by launch, so handshake counters drift apart per block, +// and a block of launch k+1 could push into the slot a different block of launch k is still +// reading. The parity counters move in lockstep, so the slot alternates per launch for every block. // -// THE COST is one more returning atomic, issued from a second wave so its round trip overlaps the -// handshake one rather than following it, and nbw / nb fire-and-forget atomics spread over the -// other threads. Nothing waits on those: the barrier below orders LDS only, so they land in the -// background, and all they need is to land before the next launch on the stream, which the kernel -// boundary guarantees. Everything stays device-resident, so a captured graph still replays. +// Cost: one more returning atomic, issued from a second wave so its round trip overlaps the +// handshake's, plus nbw / nb fire-and-forget atomics over the other threads. Those only need to +// land before the next launch, which the kernel boundary guarantees. All state is device-resident, +// so a captured graph replays. #include // Sets `s_seq` to this block's handshake value and `s_slot` to the launch's scratch slot (0 or 1), // then barriers so every thread can read both. `nbw` is the capacity the counters were allocated // for, and gridDim.x must not exceed it. // -// The barrier is fenced on LDS alone. The only thing it publishes is the two words in LDS; a full -// __syncthreads would also wait for every thread's outstanding parity atomics and invalidate the -// vector caches, which puts the fire-and-forget traffic on the path to the first push. +// The barrier fences LDS only, since it publishes just the two LDS words. A full __syncthreads +// would wait for the outstanding parity atomics and invalidate the vector caches, putting that +// traffic on the path to the first push. __device__ __forceinline__ void r4d_ar_seq_take(unsigned int* __restrict__ ctrs, unsigned int nbw, unsigned int& s_seq, unsigned int& s_slot) { const unsigned int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x; @@ -59,19 +51,16 @@ __device__ __forceinline__ void r4d_ar_seq_take(unsigned int* __restrict__ ctrs, __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup", "local"); } -// THE ENGINE'S HOLD ON THE LINK, ENDED BY THE LAUNCH (rad_abi.h, rad_kernel_collective answering -// 2). The word is odd exactly while the engine holds the link for this launch, and nothing else -// writes it while the launch runs, so its value is read once, at the start, by each block's first -// thread (r4d_ar_link_word): the read crosses to host memory, and at the start it overlaps the push -// where at the end it would hold up the reduce. +// The engine's hold on the link, released by the launch (rad_abi.h, rad_kernel_collective +// returning 2). The word is odd exactly while the engine holds the link for this launch and +// nothing else writes it meanwhile, so each block's first thread reads it once at the start +// (r4d_ar_link_word), where the host-memory read overlaps the push instead of delaying the reduce. // -// r4d_ar_link_landed is called by every block once its handshake has seen the peer's push to it -// land. The last block to get there knows every byte the peer sends this card has arrived, so the -// link is free for the rest of the kernel's run -- the reduce and whatever it writes -- and takes -// one off the word if it was odd, with an atomic so it commutes with any barrier counting the same -// word down. `ctr` counts the blocks and is back at zero when the launch ends, ready for the next -// one on the stream. The word is in memory the DMA engine polls past every cache, so it is read and -// written at system scope. +// Every block calls r4d_ar_link_landed once its handshake has seen the peer's push land. The last +// block knows all of the peer's bytes have arrived, so the link is free for the rest of the +// kernel; it decrements the word if odd, atomically so it commutes with any barrier counting the +// same word down. `ctr` counts blocks and returns to zero at the end of the launch. The DMA engine +// polls the word past every cache, so it is accessed at system scope. __device__ __forceinline__ long long r4d_ar_link_word(const long long* gate, unsigned int tid) { return gate && tid == 0 ? __hip_atomic_load(gate, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM) : 0; @@ -88,10 +77,9 @@ __device__ __forceinline__ void r4d_ar_link_landed(long long* gate, long long wo if (word & 1) __hip_atomic_fetch_add(gate, -1LL, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); } -// True while `flag` has not yet reached `want`. The counters are u32 and wrap, so the comparison is -// on the signed difference: a peer at or past `want` -- it may already be a launch ahead -- reads -// as arrived on either side of the wrap, where a plain `flag < want` stops waiting altogether once -// `want` wraps to a small number. +// True while `flag` has not reached `want`. The u32 counters wrap, so compare the signed +// difference: a peer at or past `want` (possibly a launch ahead) reads as arrived across the wrap, +// where a plain `flag < want` would stop waiting once `want` wraps to a small number. __device__ __forceinline__ bool r4d_ar_seq_behind(unsigned int flag, unsigned int want) { return (int)(flag - want) < 0; } diff --git a/libr4d/r4d_ar_ti8.h b/libr4d/r4d_ar_ti8.h index 3a363a19..ae91a089 100644 --- a/libr4d/r4d_ar_ti8.h +++ b/libr4d/r4d_ar_ti8.h @@ -1,31 +1,30 @@ #pragma once -// r4d_ar_ti8.h: the three-tiered INT8 all-reduce wire codec, shared machinery for the wide -// quantized kernels. A group's record tags which tier encoded it: Tier 1 is a plain amax-scaled -// int8, Tier 2 lifts one dominant element out of the scale and ships it exactly in the record, and -// Tier 3 rotates by an orthonormal WHT-32 first. The tiering keeps a massive outlier exact while -// leaving ordinary groups on the cheapest path. -// WIRE LAYOUT per slot, ng = numel/32 groups (fixed size, no escapes, no atomics): +// r4d_ar_ti8.h: the three-tier INT8 all-reduce wire codec shared by the wide quantized kernels. +// A group's record tags its tier: Tier 1 is plain amax-scaled int8, Tier 2 lifts one dominant +// element out of the scale and ships it exactly in the record, Tier 3 applies an orthonormal +// WHT-32 first. A massive outlier stays exact while ordinary groups take the cheapest path. +// Wire layout per slot, ng = numel/32 groups (fixed size, no escapes, no atomics): // codes u8 [32*ng] at 0 (uint2 per 8-element lane vector) // rec u32[ng] at 32*ng // scale fp16[ng] at 36*ng -> 38 bytes/group = 9.5 bits/element // Slot base must be 16B-aligned; 32*ng keeps the u32 records 4B-aligned for any ng. // -// A group of 32 = TI8_LPG=4 adjacent lanes x TI8_EPL=8 consecutive elements. All -// cross-lane exchanges use masks < 4, so a group never leaves its 4-lane cluster and -// never straddles a wave; kernels partition work in whole groups so the cluster always -// branches together (the shuffles sit inside tier branches). +// A group of 32 = TI8_LPG=4 adjacent lanes x TI8_EPL=8 consecutive elements. Cross-lane +// exchanges use masks < 4, so a group stays in its 4-lane cluster and never straddles a wave. +// Kernels partition work in whole groups so a cluster branches together (the shuffles sit inside +// tier branches). #include #include #include #include -// TI8_-prefixed (unlike the 2-rank header's bare GROUP/EPL): these must be includable -// beside other codec headers in one TU without a macro collision. +// TI8_-prefixed (unlike the 2-rank header's bare GROUP/EPL) so this header can share a TU with +// other codec headers without macro collisions. #define TI8_GROUP 32 #define TI8_EPL 8 #define TI8_LPG 4 -// Per-group wire layout, derived from the spec above so a codec rev lands everywhere at once: -// codes u8[GROUP] at 0, the u32 record at TI8_REC_OFF, the fp16 scale at TI8_SC_OFF. +// Per-group wire layout: codes u8[GROUP] at 0, the u32 record at TI8_REC_OFF, the fp16 scale at +// TI8_SC_OFF. #define TI8_REC_OFF TI8_GROUP #define TI8_SC_OFF (TI8_GROUP + 4) #define TI8_GROUP_BYTES (TI8_SC_OFF + 2) @@ -116,13 +115,12 @@ __device__ __forceinline__ void ti8_wht32(float* v, int lig) { for (int i = 0; i < TI8_EPL; ++i) v[i] *= nrm; } -// Encode one lane's 8 elements of a group into the wire words: this lane's 8 int8 codes, -// plus the group record and scale (identical on all 4 lanes; the lig==0 lane stores them). -// All 4 lanes of the group must call together (cross-lane classifier + Tier 3 rotation); -// the caller fans the words to every destination slot. The _v form takes the values -// already in registers (the phase-2 reduced vector, never stored exact) and consumes -// them -- Tier 3 rotates v in place, so a caller wanting the reconstruction must decode -// the wire words, exactly as every peer will. +// Encode one lane's 8 elements of a group: this lane's 8 int8 codes, plus the group record and +// scale (identical on all 4 lanes; the lig==0 lane stores them). All 4 lanes of the group must +// call together (cross-lane classifier and Tier 3 rotation); the caller fans the words out to every +// destination slot. The _v form consumes values already in registers (the phase-2 reduced vector): +// Tier 3 rotates v in place, so a caller wanting the reconstruction must decode the wire words as +// every peer does. template __device__ __forceinline__ void ti8_encode_group_v(float* v, int lig, uint2* codes, unsigned int* rec, __half* scale) { diff --git a/libr4d/r4d_ar_twoshot_Nrank_exact.hip b/libr4d/r4d_ar_twoshot_Nrank_exact.hip index e5c90023..a1f021cf 100644 --- a/libr4d/r4d_ar_twoshot_Nrank_exact.hip +++ b/libr4d/r4d_ar_twoshot_Nrank_exact.hip @@ -6,20 +6,18 @@ // Shard s = a contiguous run of the message's 16-byte words, owned by rank s. Phase 1: push my // contribution to each peer-owned shard into the owner's slot[me] region A, flag 2s-1; reduce my // shard fp32 in ascending rank order (own contribution from the input). Phase 2: reduced words go -// to my out AND every peer's slot[me] region B, flag 2s; assemble out from region B. Region A at +// to my out and every peer's slot[me] region B, flag 2s; assemble out from region B. Region A at // 0, B at sh_max; the slot stride must hold 2*sh_max. // -// UNEVEN SHARDS. A message of n16 words splits into base = n16/ws words a shard, and the first -// n16 % ws shards take one more: shard s starts at s*base + min(s, rem). At 4 and 8 ranks every -// residual the engine issues divides evenly and this is the plain 1/ws split. At 3 it almost never -// does -- a 2048-wide bf16 row is 256 words, and 256 * rows is a multiple of 3 only when rows is -- -// so the split has to tolerate it rather than refuse it. The sum per word is the same fp32 fold in -// ascending rank order whichever rank owns it, so the bits match the one-shot's. +// Uneven shards: n16 words split into base = n16/ws words per shard, and the first n16 % ws shards +// take one more, so shard s starts at s*base + min(s, rem). At 4 and 8 ranks engine residuals +// divide evenly; at 3 they rarely do (a 2048-wide bf16 row is 256 words). Each word is the same +// fp32 fold in ascending rank order whoever owns it, so the bits match the one-shot's. // -// SHARES the wide family's flag/seq/scratch set: every wide kernel publishes in the 2*seq flag -// space (this one adds the 2s-1 half-step) and advances the per-block counter once per AR, so -// parity and the monotonic spin survive any mixed one-shot/two-shot stream on one buffer set. -// The slot stride must hold the largest requirement of every family in the mix. +// Shares the wide family's flag/seq/scratch set (r4d_ar_wide.h): it publishes in the 2*seq flag +// space plus the 2s-1 half-step and advances the per-block counter once per AR, so one buffer set +// can carry any mix of one-shot and two-shot launches. The slot stride must hold the largest +// requirement in the mix. #include "r4d.h" #include "r4d_ar_wide.h" #include @@ -30,10 +28,12 @@ __global__ void r4d_ar_twoshot_wide_exact_kernel( const int4* __restrict__ in4, R4DArWidePeers peers, const int4* __restrict__ my_base, unsigned int* __restrict__ my_flags, int4* __restrict__ out4, unsigned int* __restrict__ seq_ctrs, int n16, - int slot_stride16, int rank, int drain, int acq, int pub) { + int slot_stride16, int rank, int drain, int acq, int pub, + long long* gate, unsigned int* gate_ctr) { constexpr int NPEERS = WS - 1; const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x; __shared__ unsigned int s_seq, s_slot; + const long long gate_word = r4d_ar_link_word(gate, (unsigned int)tid); r4d_ar_seq_take(seq_ctrs, R4D_AR_WIDE_MAX_BLOCKS, s_seq, s_slot); // device-resident, replay-safe const unsigned int s = s_seq; const int parity = (int)s_slot; @@ -93,6 +93,12 @@ __global__ void r4d_ar_twoshot_wide_exact_kernel( for (int p = 0; p < NPEERS; ++p) pa[p][sh_max + k] = o; // region B } r4d_ar_handshake(peers, my_flags, b, rank, 2u * s, drain, acq, pub); + /* The hold ends after the second handshake, not the first: the reduce above is fused with the + * phase-2 push (every reduced word goes to each peer's region B), so at the first handshake the + * link still carries this launch's phase-2 bytes. Here every phase-1 and phase-2 remote store + * has retired behind its flag store and every peer's pushes to this rank have been waited on; + * only the local assemble is left (r4d_ar_seq.h). */ + r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid); // ---- assemble: every peer-owned shard from my region B copies for (int p = 0; p < NPEERS; ++p) { @@ -111,7 +117,8 @@ template static void ar_twoshot_launch(const long* peer_scratch, const long* peer_flags, long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long stream_i, - long nblocks, long nthreads, long drain, long acq, long pub) { + long nblocks, long nthreads, long drain, long acq, long pub, + long gate, long gate_ctr) { constexpr int NPEERS = WS - 1; if (rank < 0 || rank >= WS) throw std::runtime_error("all_reduce: rank " + std::to_string(rank) + @@ -154,9 +161,8 @@ static void ar_twoshot_launch(const long* peer_scratch, const long* peer_flags, peers.rank[i] = (i < (int)rank) ? i : i + 1; } - // scratch must back 2*WS slots of the declared stride, flags one word per (block, source - // rank), seq a handshake and a parity word per block of capacity (r4d_ar_seq.h) -- checked - // against the allocations, not the arguments. + // Checked against the allocations: scratch backs 2*WS slots of the stride, flags one word per + // (block, source rank), seq a handshake and a parity word per block of capacity (r4d_ar_seq.h). const long slot_bytes = 2L * WS * (long)slot_stride16 * 16; const long flag_bytes = (long)nb * WS * (long)sizeof(unsigned int); r4d_ar_check_extent(my_scratch, slot_bytes, "all_reduce", "my_scratch"); @@ -173,7 +179,8 @@ static void ar_twoshot_launch(const long* peer_scratch, const long* peer_flags, r4d_ar_twoshot_wide_exact_kernel<<>>( \ (const int4*)inp, peers, (const int4*)my_scratch, (unsigned int*)my_flags, \ (int4*)out, (unsigned int*)seq_ctrs, (int)n16, (int)slot_stride16, \ - (int)rank, (int)drain, (int)acq, (int)pub) + (int)rank, (int)drain, (int)acq, (int)pub, (long long*)gate, \ + (unsigned int*)gate_ctr) if (dtype == 0) R4D_AR_TS_LAUNCH(__hip_bfloat16, 8); else if (dtype == 1) R4D_AR_TS_LAUNCH(__half, 8); else if (dtype == 2) R4D_AR_TS_LAUNCH(float, 4); @@ -188,8 +195,9 @@ void r4d_ar_twoshot_3rank_exact(long peer_scratch0, long peer_scratch1, long pee long acq, long pub) { const long ps[2] = {peer_scratch0, peer_scratch1}; const long pf[2] = {peer_flags0, peer_flags1}; + /* No link gate at three ranks: the row answers 1, the engine releases by barrier. */ ar_twoshot_launch<3>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem, - dtype, rank, stream, nblocks, nthreads, drain, acq, pub); + dtype, rank, stream, nblocks, nthreads, drain, acq, pub, 0L, 0L); } void r4d_ar_twoshot_4rank_exact(long peer_scratch0, long peer_scratch1, long peer_scratch2, @@ -197,11 +205,11 @@ void r4d_ar_twoshot_4rank_exact(long peer_scratch0, long peer_scratch1, long pee long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long stream, long nblocks, long nthreads, long drain, - long acq, long pub) { + long acq, long pub, long gate, long gate_ctr) { const long ps[3] = {peer_scratch0, peer_scratch1, peer_scratch2}; const long pf[3] = {peer_flags0, peer_flags1, peer_flags2}; ar_twoshot_launch<4>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem, - dtype, rank, stream, nblocks, nthreads, drain, acq, pub); + dtype, rank, stream, nblocks, nthreads, drain, acq, pub, gate, gate_ctr); } void r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long peer_scratch2, @@ -216,6 +224,7 @@ void r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long pee peer_scratch4, peer_scratch5, peer_scratch6}; const long pf[7] = {peer_flags0, peer_flags1, peer_flags2, peer_flags3, peer_flags4, peer_flags5, peer_flags6}; + /* No link gate at eight ranks: the row answers 1, the engine releases by barrier. */ ar_twoshot_launch<8>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem, - dtype, rank, stream, nblocks, nthreads, drain, acq, pub); + dtype, rank, stream, nblocks, nthreads, drain, acq, pub, 0L, 0L); } diff --git a/libr4d/r4d_ar_twoshot_Nrank_ti8.hip b/libr4d/r4d_ar_twoshot_Nrank_ti8.hip index 16b1b574..550af74a 100644 --- a/libr4d/r4d_ar_twoshot_Nrank_ti8.hip +++ b/libr4d/r4d_ar_twoshot_Nrank_ti8.hip @@ -1,22 +1,20 @@ // r4d_ar_twoshot_Nrank_ti8.hip: r4d_ar_twoshot_{3,4}rank_ti8 -- reduce-scatter + all-gather with // the tiered-int8 wire on both hops, at 3 or 4 ranks. Codec (tiers 1/2/3) from r4d_ar_ti8.h, -// transport from r4d_ar_twoshot_Nrank_exact.hip. The second hop costs 38/64 of its exact -// bytes. Own contribution reads exact from the input at fold time. +// transport from r4d_ar_twoshot_Nrank_exact.hip. The second hop costs 38/64 of its exact bytes. +// The own contribution is read exact from the input at fold time. // -// Cross-rank identity: the phase-2 encode input is the deterministic fp32 fold, so the wire -// words are identical on every rank by construction, and the owner stores the decode of the -// words it published -- never the exact fold -- so every rank holds the same bytes for -// every shard. +// Cross-rank identity: the phase-2 encode input is the deterministic fp32 fold, and the owner +// stores the decode of the words it published, never the exact fold, so every rank holds the same +// bytes for every shard. // // Slot: region A = ti8 wire (38*sg bytes, codes | rec | scales), region B at align16(A end) // a second wire image of the same layout; the stride must hold both. // -// UNEVEN SHARDS, in whole groups (the exact two-shot's rule one level up): ng = numel/32 groups -// split ng/ws a shard and the first ng % ws take one more, so shard s starts at group -// s*base + min(s, rem). Every slot is laid out for the LONGEST shard (sg_max), whichever shard it -// carries, so a writer and a reader never have to agree on anything but sg_max. At 4 ranks the -// entry still requires numel to tile 32 x 4 and this is the even split it always was; at 3 a -// 2048-wide row is 64 groups and 64 * rows divides by 3 one step in three. +// Uneven shards, in whole groups (the exact two-shot's rule applied to groups): ng = numel/32 +// groups split ng/ws per shard and the first ng % ws take one more, so shard s starts at group +// s*base + min(s, rem). Every slot is laid out for the longest shard (sg_max), so writer and reader +// agree on sg_max alone. At 4 ranks the entry requires numel to tile 32 x 4, so the split is even; +// at 3, a 2048-wide row is 64 groups. #include "r4d.h" #include "r4d_ar_ti8.h" #include "r4d_ar_wide.h" @@ -28,10 +26,12 @@ __global__ void r4d_ar_twoshot_wide_ti8_kernel( const T* __restrict__ in, R4DArWidePeers peers, char* __restrict__ my_base, unsigned int* __restrict__ my_flags, T* __restrict__ out, unsigned int* __restrict__ seq_ctrs, int n_groups, long slot_stride_bytes, - long b_off_bytes, int rank, int drain, int acq, int pub) { + long b_off_bytes, int rank, int drain, int acq, int pub, + long long* gate, unsigned int* gate_ctr) { constexpr int NPEERS = WS - 1; const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x; __shared__ unsigned int s_seq, s_slot; + const long long gate_word = r4d_ar_link_word(gate, (unsigned int)tid); r4d_ar_seq_take(seq_ctrs, R4D_AR_WIDE_MAX_BLOCKS, s_seq, s_slot); // device-resident, replay-safe const unsigned int s = s_seq; const int parity = (int)s_slot; @@ -51,8 +51,8 @@ __global__ void r4d_ar_twoshot_wide_ti8_kernel( for (int p = 0; p < NPEERS; ++p) pslot[p] = peers.scratch[p] + ((size_t)parity * WS + rank) * (size_t)slot_stride_bytes; - // ---- phase 1: encode my contribution to each peer-owned shard into its owner's - // region A. My own shard's contribution stays exact, read from the input at fold time. + // ---- phase 1: encode my contribution to each peer-owned shard into its owner's region A. My + // own shard's contribution stays exact, read from the input at fold time. for (int p = 0; p < NPEERS; ++p) { const T* src = in + R4D_TI8_OFF(peers.rank[p]); const int gE = gB < R4D_TI8_LEN(peers.rank[p]) ? gB : R4D_TI8_LEN(peers.rank[p]); @@ -72,9 +72,9 @@ __global__ void r4d_ar_twoshot_wide_ti8_kernel( } r4d_ar_handshake(peers, my_flags, b, rank, 2u * s - 1u, drain, acq, pub); - // ---- reduce my shard: own contribution exact from the input, peers decoded from - // region A, fp32 fold in ascending rank order; the reduced group is re-encoded and its - // wire words go to every peer's region B, the owner keeping their decode. + // ---- reduce my shard: own contribution exact, peers decoded from region A, fp32 fold in + // ascending rank order. The reduced group is re-encoded to every peer's region B and the owner + // keeps its decode. const T* my_in = in + R4D_TI8_OFF(rank); T* my_out = out + R4D_TI8_OFF(rank); const int gM = gB < R4D_TI8_LEN(rank) ? gB : R4D_TI8_LEN(rank); @@ -117,9 +117,12 @@ __global__ void r4d_ar_twoshot_wide_ti8_kernel( ti8_store8(my_out + k * TI8_EPL, v2); } r4d_ar_handshake(peers, my_flags, b, rank, 2u * s, drain, acq, pub); + /* As in the exact two-shot, the hold ends after the second handshake: the reduce above is fused + * with the phase-2 wire push. Only the local decode-assemble is left (r4d_ar_seq.h). */ + r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid); - // ---- assemble: decode each peer-owned shard from region B, the mirror of the owner's - // roundtrip store. + // ---- assemble: decode each peer-owned shard from region B, matching the owner's roundtrip + // store. for (int p = 0; p < NPEERS; ++p) { const int owner = peers.rank[p]; const char* baseB = my_base + @@ -147,7 +150,8 @@ static void ar_twoshot_ti8_launch(const long* peer_scratch, const long* peer_fla long my_scratch, long my_flags, long seq_ctrs, long slot_stride_bytes, long inp, long out, long n_elem, long dtype, long rank, long stream_i, long nblocks, - long nthreads, long drain, long acq, long pub) { + long nthreads, long drain, long acq, long pub, long gate, + long gate_ctr) { constexpr int NPEERS = WS - 1; if (rank < 0 || rank >= WS) throw std::runtime_error("ti8 ar: rank " + std::to_string(rank) + @@ -174,11 +178,10 @@ static void ar_twoshot_ti8_launch(const long* peer_scratch, const long* peer_fla int nt = (int)nthreads; if (nt < 64) nt = 64; if (nt > 1024) nt = 1024; - // A wire group is TI8_LPG adjacent lanes and every cross-lane exchange in the codec is a - // __shfl_xor masked below TI8_LPG, so the group has to land on lanes 4j..4j+3. The kernel - // walks work as k = 4*gA + tid stepping by nt, which keeps k%TI8_LPG == lane%TI8_LPG only - // while nt divides by TI8_LPG. A nt that does not would rotate the mapping and give - // silently wrong answers with divergent shuffles, so refuse it instead of clamping. + // A wire group is TI8_LPG adjacent lanes (codec shuffles use masks below TI8_LPG), so it must + // land on lanes 4j..4j+3. The kernel walks k = 4*gA + tid in steps of nt, which keeps + // k%TI8_LPG == lane%TI8_LPG only while TI8_LPG divides nt; otherwise the results are silently + // wrong, so refuse rather than clamp. if (nt % TI8_LPG) throw std::runtime_error("ti8 ar: nthreads must be a multiple of " + std::to_string(TI8_LPG) + " (a wire group is that many " @@ -194,9 +197,8 @@ static void ar_twoshot_ti8_launch(const long* peer_scratch, const long* peer_fla peers.rank[i] = (i < (int)rank) ? i : i + 1; } - // scratch must back 2*WS slots of the declared stride, flags one word per (block, source - // rank), seq a handshake and a parity word per block of capacity (r4d_ar_seq.h) -- checked - // against the allocations, not the arguments. + // Checked against the allocations: scratch backs 2*WS slots of the stride, flags one word per + // (block, source rank), seq a handshake and a parity word per block of capacity (r4d_ar_seq.h). const long slot_bytes = 2L * WS * slot_stride_bytes; const long flag_bytes = (long)nb * WS * (long)sizeof(unsigned int); r4d_ar_check_extent(my_scratch, slot_bytes, "ti8 ar", "my_scratch"); @@ -213,7 +215,7 @@ static void ar_twoshot_ti8_launch(const long* peer_scratch, const long* peer_fla r4d_ar_twoshot_wide_ti8_kernel<<>>( \ (const T*)inp, peers, (char*)my_scratch, (unsigned int*)my_flags, (T*)out, \ (unsigned int*)seq_ctrs, (int)n_groups, (long)slot_stride_bytes, b_off, (int)rank, \ - (int)drain, (int)acq, (int)pub) + (int)drain, (int)acq, (int)pub, (long long*)gate, (unsigned int*)gate_ctr) if (dtype == 0) R4D_AR_TS8_LAUNCH(__hip_bfloat16); else R4D_AR_TS8_LAUNCH(__half); #undef R4D_AR_TS8_LAUNCH @@ -226,9 +228,10 @@ void r4d_ar_twoshot_3rank_ti8(long peer_scratch0, long peer_scratch1, long peer_ long nthreads, long drain, long acq, long pub) { const long ps[2] = {peer_scratch0, peer_scratch1}; const long pf[2] = {peer_flags0, peer_flags1}; + /* No link gate at three ranks: the row answers 1, the engine releases by barrier. */ ar_twoshot_ti8_launch<3>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride_bytes, inp, out, n_elem, dtype, rank, stream, nblocks, nthreads, drain, - acq, pub); + acq, pub, 0L, 0L); } void r4d_ar_twoshot_4rank_ti8(long peer_scratch0, long peer_scratch1, long peer_scratch2, @@ -236,15 +239,16 @@ void r4d_ar_twoshot_4rank_ti8(long peer_scratch0, long peer_scratch1, long peer_ long my_scratch, long my_flags, long seq_ctrs, long slot_stride_bytes, long inp, long out, long n_elem, long dtype, long rank, long stream, long nblocks, - long nthreads, long drain, long acq, long pub) { + long nthreads, long drain, long acq, long pub, long gate, + long gate_ctr) { const long ps[3] = {peer_scratch0, peer_scratch1, peer_scratch2}; const long pf[3] = {peer_flags0, peer_flags1, peer_flags2}; ar_twoshot_ti8_launch<4>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride_bytes, inp, out, n_elem, dtype, rank, stream, nblocks, nthreads, drain, - acq, pub); + acq, pub, gate, gate_ctr); } -// The tiered-int8 wire format, which the caller needs to size its packed scratch. +// Tiered-int8 wire format dimensions, for sizing the caller's packed scratch. void r4d_ar_ti8_dims(int* group, int* group_bytes) { if (group) *group = TI8_GROUP; if (group_bytes) *group_bytes = TI8_GROUP_BYTES; diff --git a/libr4d/r4d_ar_wide.h b/libr4d/r4d_ar_wide.h index f76a22b4..353b5d13 100644 --- a/libr4d/r4d_ar_wide.h +++ b/libr4d/r4d_ar_wide.h @@ -1,14 +1,13 @@ #pragma once -// r4d_ar_wide.h: the wide (ws>2) all-reduce family's shared transport. Every wide kernel -- -// one-shot exact, two-shot exact, two-shot ti8 -- publishes in the 2*seq flag space (the -// two-shots add the 2s-1 half-step), advances seq_ctrs[b] once per AR, and lays scratch out -// as 2*ws slots of one stride (parity x source rank). The parity is the launch's, from the -// counters r4d_ar_seq.h keeps beside the handshake ones, so seq_ctrs is 2 * R4D_AR_WIDE_MAX_BLOCKS -// words. The constants that size that shared flag/seq/scratch set live here exactly once, a -// safety against drift over time across them. +// r4d_ar_wide.h: shared transport of the wide (ws>2) all-reduce family. Every wide kernel +// (one-shot exact, two-shot exact, two-shot ti8) publishes in the 2*seq flag space (the two-shots +// add the 2s-1 half-step), advances seq_ctrs[b] once per AR, and lays scratch out as 2*ws slots of +// one stride (parity x source rank). The parity is the launch's, from the parity counters in +// r4d_ar_seq.h, so seq_ctrs is 2 * R4D_AR_WIDE_MAX_BLOCKS words. The constants sizing the shared +// flag/seq/scratch set are defined only here so they cannot drift apart. // -// The 2-rank pair is deliberately NOT here: it has its own flag layout (one word per block, -// no ws stride), an acquire-on-load spin, and its own block ceiling. +// The 2-rank pair is not here: it has its own flag layout (one word per block, no ws stride), an +// acquire-on-load spin and its own block ceiling. #include #include #include @@ -60,10 +59,10 @@ __device__ __forceinline__ void r4d_ar_acquire(int acq) { else if (acq != 2) __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, ""); } -// publish `val` to every peer's flag word [b][rank], then wait until every one of this block's -// own words has reached or passed it (peers may already be a step ahead; the counter only -// grows). One spin lane per source, wrap-safe monotonic compare, never equality. Every rank -// publishes before it waits, so there is no cycle; a handshake that cannot complete traps. +// Publish `val` to every peer's flag word [b][rank], then wait until each of this block's own +// words has reached or passed it (peers may be a step ahead; counters only grow). One spin lane +// per source, wrap-safe monotonic compare, never equality. Every rank publishes before it waits, +// so there is no cycle; a handshake that cannot complete traps. template __device__ __forceinline__ void r4d_ar_handshake(const R4DArWidePeers& peers, unsigned int* __restrict__ my_flags, int b, @@ -75,8 +74,8 @@ __device__ __forceinline__ void r4d_ar_handshake(const R4DArWidePeers if (tid == 0) { if (drain == 2) __threadfence_system(); if (pub) { - // One system writeback for the whole publish, then relaxed stores: the extra writebacks - // a per-peer release store inserts add no ordering, since the flags go to different peers. + // One system writeback for the whole publish, then relaxed stores. Per-peer release stores + // would add writebacks that order nothing, since the flags go to different peers. __builtin_amdgcn_fence(__ATOMIC_RELEASE, ""); #pragma unroll for (int p = 0; p < NPEERS; ++p) @@ -99,10 +98,9 @@ __device__ __forceinline__ void r4d_ar_handshake(const R4DArWidePeers r4d_ar_acquire(acq); } -// Host side. The stride and grid are enforced against the real allocations, not trusted: -// every scratch, flag, and seq pointer came from hipMalloc / hipIpcOpenMemHandle, so the -// runtime can report the extent behind it. A pointer the runtime cannot size is refused -// rather than assumed. +// Host side: checks stride and grid against the real allocations. Every scratch, flag and seq +// pointer comes from hipMalloc / hipIpcOpenMemHandle, so the runtime can report its extent; a +// pointer it cannot size is refused. inline void r4d_ar_check_extent(long p, long need, const char* prefix, const char* what) { hipDeviceptr_t base = nullptr; size_t sz = 0; diff --git a/libr4d/r4d_args.h b/libr4d/r4d_args.h index 6dd38edd..31187233 100644 --- a/libr4d/r4d_args.h +++ b/libr4d/r4d_args.h @@ -1,18 +1,14 @@ /* r4d_args.h -- how a libr4d entry point reads its arguments. * - * THERE IS NO ADAPTER LAYER. An entry point takes `(const RadArgs*, RadStream)` and returns a - * status, which is the SAME contract RadLaunchFn publishes to every other plugin. An adapter - * between the core and a first-party library would be a statement that the interface is wrong: an - * out-of-tree author could not write the same kernel without also writing the same adapter, and - * that adapter would live in this repository where they cannot reach it. + * There is no adapter layer. An entry point takes `(const RadArgs*, RadStream)` and returns a + * status, the same RadLaunchFn contract every other plugin implements; an out-of-tree author can + * write the same kernel without an adapter they could not reach. * - * What this header holds is the part that is not translation: reading a parameter, finding an - * operand, asking whether a tensor is contiguous. Every plugin needs it, none of it is libr4d's, - * and most of it is one line over rad_abi.h -- which is the shape a shared helper should have. + * This header holds the shared helpers: reading a parameter, finding an operand, testing + * contiguity. Most are one line over rad_abi.h. * - * Nothing here includes r4d.h or HIP: a host translation unit (the row table, the layouts, the - * shape hooks) includes this too, and that split is what lets the tables a transcription error - * hides in be compiled and read on a machine with no ROCm. + * Nothing here includes r4d.h or HIP: host translation units (the row table, the layouts, the + * shape hooks) include it too, so those tables compile and can be checked without ROCm. */ #ifndef R4D_ARGS_H #define R4D_ARGS_H @@ -27,9 +23,8 @@ /* ================================================================== parameter access * - * ONE-LINE FORWARDS. rad_args_geti and rad_args_gets are static inline in rad_abi.h -- the header - * a third-party plugin gets -- so every plugin shares ONE definition rather than writing its own. - * These keep libr4d's spelling for its own call sites and forward. */ + * Forwards to rad_abi.h's static inline helpers, the ones a third-party plugin gets, keeping + * libr4d's spelling at its call sites. */ static inline int r4d_geti(const RadArgs* a, const char* k, long long* out) { return rad_args_geti(a, k, out); } @@ -42,11 +37,10 @@ static inline const char* r4d_gets(const RadArgs* a, const char* k) { return rad_args_gets(a, k); } -/* A float parameter is RAD_P_F64 (rad_types.h, docs/OPS.md "The four rules"), so `dval` is what - * arrives and the step path runs no strtod. This one does NOT forward, because it - * is deliberately laxer than rad_args_getf_or: the string and integer spellings are still read, - * since a tool or a selftest may call a launch directly with no declare in front of it to enforce - * the type, and failing such a caller over a spelling tells it nothing useful. */ +/* A float parameter is RAD_P_F64 (rad_types.h, docs/OPS.md "The four rules"), so `dval` arrives + * and the step path runs no strtod. Deliberately laxer than rad_args_getf_or: string and integer + * spellings are still read, because a tool or selftest may call a launch directly with no declare + * to enforce the type. */ static inline double r4d_getf(const RadArgs* a, const char* k, double dflt) { if (!a || !k) return dflt; for (int i = 0; i < a->n_p; ++i) { @@ -63,12 +57,10 @@ static inline double r4d_getf(const RadArgs* a, const char* k, double dflt) { return dflt; } -/* An enumerated parameter. `act` is "silu" or "sigmoid" and NOT 0 or 1: a --debug-graph dump - * reading `act=1` is exactly the "unclear what actually runs" complaint this engine exists to - * answer. The mapping to libr4d's integer belongs here, in the shim, and not in the caller. - * Returns -1 for a name that is not in the list, which every caller turns into RAD_E_INVAL rather - * than running the other activation. `alt` is libr4d's own integer spelling of the same key -- - * `mode` on gated_had_quant_i8 -- consulted only when the name is absent. */ +/* An enumerated parameter: `act` is "silu" or "sigmoid", not 0 or 1, so a --debug-graph dump says + * what runs; the mapping to libr4d's integer lives in the shim. Returns -1 for an unknown name, + * which every caller turns into RAD_E_INVAL. `alt` is libr4d's own integer spelling of the same + * key (`mode` on gated_had_quant_i8), consulted only when the name is absent. */ static inline int r4d_act_code(const RadArgs* a, const char* key, const char* alt, int dflt) { if (const char* s = r4d_gets(a, key)) { if (!std::strcmp(s, "silu") || !std::strcmp(s, "swish")) return 0; @@ -80,15 +72,8 @@ static inline int r4d_act_code(const RadArgs* a, const char* key, const char* al return dflt; } -/* Same, off a RadParam list rather than RadArgs -- init() and the layout hooks get the bare list. - * rad_plugin.h calls these rad_param_*; these keep libr4d's spelling for its call sites. */ -static inline int r4d_pgeti(const RadParam* p, int n_p, const char* k, long long* out) { - const RadParam* f = rad_param_find(p, n_p, k); - if (!f || f->kind != RAD_P_INT) return 0; - if (out) *out = f->ival; - return 1; -} - +/* Same, off a bare RadParam list (init() and the layout hooks); forwards to rad_plugin.h's + * rad_param_*. */ static inline long long r4d_pgeti_or(const RadParam* p, int n_p, const char* k, long long dflt) { return rad_param_geti(p, n_p, k, dflt); } @@ -99,18 +84,17 @@ static inline const char* r4d_pgets(const RadParam* p, int n_p, const char* k) { /* ================================================================== operand access * - * An absent optional operand is a null RadTensor.data (rad_abi.h). r4d_opt() returns null for - * both "index past the end" and "present but null", so a shim's optional-operand test is one - * pointer test. r4d_req() is the same lookup for a required operand and the caller turns a null - * into RAD_E_INVAL -- a missing required operand is a bug in the issue, not a shape this kernel - * declines. + * An absent optional operand is a null RadTensor.data (rad_abi.h). r4d_opt() returns null both + * past the end and for a present-but-null operand, so an optional test is one pointer test. For a + * required operand the caller turns null into RAD_E_INVAL: it is a bug in the issue, not a shape + * the kernel declines. */ static inline const RadTensor* r4d_opt(const RadArgs* a, int i) { return rad_arg_in(a, i); } static inline const void* r4d_p(const RadTensor* t) { return t ? t->data : nullptr; } -/* ...and the same for an operand a kernel WRITES. RadTensor::data is `void*` already; this exists - * so an output cast reads as an output cast rather than as a pointer laundered through `long`. */ +/* The same for an operand a kernel writes, so an output cast reads as one rather than as a + * pointer laundered through `long`. */ static inline void* r4d_wp(const RadTensor* t) { return t ? t->data : nullptr; } static inline long r4d_addr(const RadTensor* t) { return t ? (long)(uintptr_t)t->data : 0L; } @@ -126,10 +110,9 @@ static inline long long r4d_stride(const RadTensor* t, int i) { static inline long long r4d_numel(const RadTensor* t) { return rad_tensor_numel(t); } -/* [rows..., K] flattened to (M, K). Every per-row kernel in libr4d owns whole ROWS -- one - * workgroup per row -- so the leading axes are only a row count and just the last axis is - * structural. A rank-3 activation is a rank-2 one here by construction, which is the same fold - * the GEMM has to make explicitly (see gemm_ops). */ +/* [rows..., K] flattened to (M, K). Every per-row kernel in libr4d owns whole rows (one + * workgroup per row), so the leading axes are only a row count. The GEMM makes the same fold + * explicitly (see gemm_ops). */ static inline int r4d_rows_of(const RadTensor* t, long long* M, long long* K) { if (!t || t->rank < 1) return RAD_E_SHAPE; @@ -139,14 +122,14 @@ static inline int r4d_rows_of(const RadTensor* t, long long* M, long long* K) { return (*M >= 1 && *K >= 1) ? RAD_OK : RAD_E_SHAPE; } -/* Dense row-major over the whole tensor. libr4d's entry points take raw pointers and, where they - * take a pitch at all, take exactly ONE -- so anything they do not pitch has to be tight, and the - * shim is where that is checked. This is the "necessary condition only" boundary from spec §2.1: - * the constraint table settles the geometry, contiguity is a property of the call. */ +/* Dense row-major over the whole tensor. libr4d's entry points take at most one pitch, so + * everything else must be tight, and the shim checks it. This is the "necessary condition only" + * boundary of spec §2.1: the constraint table settles geometry, contiguity is a property of the + * call. */ static inline int r4d_contig(const RadTensor* t) { return rad_tensor_is_contiguous(t); } /* Contiguous in every axis but the leading one, whose stride is the row pitch libr4d takes as an - * explicit argument (`xpitch`, `a_stride`, `xrow`, ...). Returns the pitch in ELEMENTS, or -1. */ + * explicit argument (`xpitch`, `a_stride`, `xrow`, ...). Returns the pitch in elements, or -1. */ static inline long long r4d_row_pitch(const RadTensor* t) { if (!t || t->rank == 0) return -1; if (t->rank == 1) return 1; @@ -159,15 +142,12 @@ static inline long long r4d_row_pitch(const RadTensor* t) { } /* [rows..., n] read as (rows, n): the leading axes are a row count and only the last is - * structural. Returns the pitch in ELEMENTS, or -1. + * structural. Returns the pitch in elements, or -1. * - * THE COLUMN-SLICE CASE MUST REFUSE. A slice of a wider buffer -- k out of a fused - * [tok, 2*kv_dim] projection, read as [tok*n_head_kv, head_dim] for the per-head norm -- is rows - * of `n` that are `n` apart INSIDE a token and a whole buffer row apart BETWEEN tokens. No single - * pitch describes that, and answering with the leading stride gives the between-tokens one: the - * consumer then reads every n_head_kv-th head against the right numbers and the rest against - * garbage, silently, from an op whose own arithmetic is correct. So the trailing axes must be the - * WHOLE of the row before their pitch means anything. */ + * A column slice must refuse. k out of a fused [tok, 2*kv_dim] projection, read as + * [tok*n_head_kv, head_dim] for a per-head norm, has rows `n` apart within a token and a buffer + * row apart between tokens; no single pitch describes that, and the leading stride would make the + * consumer read most heads from garbage. So the trailing axes must cover the whole row. */ static inline long long r4d_rows_pitch(const RadTensor* t, long long n, long long* rows) { if (!t || t->rank < 1 || n <= 0) return -1; const long long nel = rad_tensor_numel(t); @@ -184,23 +164,31 @@ static inline long long r4d_rows_pitch(const RadTensor* t, long long n, long lon return trail == n ? r4d_row_pitch(t) : -1; } -/* 16-byte alignment. Every libr4d kernel that pushes over P2P or issues a global_load_b128 needs - * it, and the kernels themselves do not check, so the shim is where it is checked. */ +/* An attention operand, [tokens, heads * head_dim] over its trailing axes: the token count, head + * count and row pitch in elements. False when the trailing axes are not whole heads or no single + * pitch describes the rows. */ +static inline bool r4d_head_rows(const RadTensor* t, long long head_dim, long long* n_tok, + long long* n_head, long long* ld) { + long long width = 1; + for (uint32_t i = 1; i < t->rank; ++i) width *= t->shape[i]; + if (t->rank < 2 || width % head_dim) return false; + *n_head = width / head_dim; + *ld = r4d_rows_pitch(t, width, n_tok); + return *ld >= 0; +} + +/* 16-byte alignment, needed by every kernel that pushes over P2P or issues a global_load_b128. + * The kernels do not check it, so the shim does. */ static inline int r4d_aligned(const void* p, unsigned bytes) { return p ? (((uintptr_t)p & (uintptr_t)(bytes - 1)) == 0) : 1; } /* ================================================================== which check refused * - * A shim rejects a call in a dozen places and returns the same three or four codes from all of - * them, so the engine's report -- "kernel X refused op Y at M=5: shape this kernel does not serve" - * -- names the kernel and the geometry and says nothing about WHICH condition failed. Distinct - * causes are then indistinguishable in the report: an activation declared [tokens, heads, width] - * where a shim expected [tokens, width] prints identically to any other refusal at that geometry. - * - * So: wrap a refusal in R4D_NO() and it names its own line when RAD_R4D_TRACE is set in the - * environment. Off, it is the bare return it replaces -- one load of a cached flag, on a path that - * is about to fail the step anyway. */ + * A shim refuses in many places with the same few codes, so the engine's report names the kernel + * and geometry but not the failing condition. R4D_NO() wraps a refusal and prints its own line + * when RAD_R4D_TRACE is set; otherwise it is the bare return plus one cached-flag load on a path + * that is failing anyway. */ static inline int r4d_trace_on(void) { static int on = -1; if (on < 0) { const char* e = std::getenv("RAD_R4D_TRACE"); on = (e && *e && *e != '0'); } @@ -213,8 +201,8 @@ static inline int r4d_refused(int code, const char* file, int line) { #define R4D_NO(code) r4d_refused((code), __FILE__, __LINE__) /* ================================================================== dtype helpers */ -/* Widest world any libr4d all-reduce serves. Fixed by the 8-rank entry points' argument lists, - * which name seven peers explicitly. */ +/* Widest world any libr4d all-reduce serves, fixed by the 8-rank entry points' argument lists + * (seven explicit peers). */ enum { R4D_MAX_RANKS = 8, R4D_MAX_PEERS = 7 }; /* libr4d's all-reduce dtype code: 0 bf16, 1 fp16, 2 fp32. Returns -1 for anything else. */ @@ -231,12 +219,9 @@ static inline int r4d_ar_esize(int code) { return code == 2 ? 4 : 2; } /* ================================================================== weight layout constants * - * These are libr4d's compile-time constants, restated here because r4d_layout.cpp must not include - * r4d.h (it is host code compiled without ROCm) and because the .rad container records them in the - * layout tag. THE BUILD CHECKS THEM: libr4d/CMakeLists.txt passes the same - * -DR4D_GEMM_*_GROUP=128 to libr4d's translation units, and r4d_gemm_args.h static_asserts the - * group constants against libr4d's own macros, so a divergence is a compile error rather than a - * silently wrong weight file. + * libr4d's compile-time constants, restated because r4d_layout.cpp is host code built without + * ROCm and cannot include r4d.h, and because the .rad container records them in the layout tag. + * r4d_gemm_args.h static_asserts the group constants against libr4d's macros. */ enum { R4D_W4_GROUP = 128, /* K per (scale, zero) dword; libr4d R4D_GEMM_W4_GROUP */ @@ -245,19 +230,17 @@ enum { R4D_W8_KPB = 32, /* K per packed block: 2 k steps, 16 bytes per lane */ R4D_W2_GROUP = 128, /* libr4d R4D_GEMM_W2A8_GROUP */ R4D_MXFP4_GROUP = 32, /* K per E8M0 exponent, fixed by the OCP MX format */ - /* The block-scaled fp8 family's block, on BOTH axes. Unlike every other constant here it is not - * a choice this project's quantiser made: it is `quantization_config.weight_block_size` in the - * checkpoint's own config.json, and the weight bytes on disk are laid out to it. It cannot be - * static_asserted against libr4d's `r4d_gemm_fp8a8_block()` because that is a function and not - * a macro, so r4d_gemm_fp8a8.hip checks it at launch -- a scalar compare against a constant, - * which is nothing, and the alternative is a silently wrong scale grid. */ + /* The block-scaled fp8 family's block, on both axes. Not a quantiser choice: it is the + * checkpoint's `quantization_config.weight_block_size`, and the bytes on disk follow it. It + * cannot be static_asserted against `r4d_gemm_fp8a8_block()` (a function, not a macro), so + * r4d_gemm_fp8a8.hip checks it at launch. */ R4D_FP8_BLOCK = 128, R4D_WAVE = 32, R4D_NTILE = 16 /* output rows per WMMA n-tile */ }; /* Plugin-private dtypes. The core never interprets these: rad_types.h reserves everything at or - * above RAD_DT_PLUGIN_BASE for exactly this, and the layout hook is what sizes them. */ + * above RAD_DT_PLUGIN_BASE for this, and the layout hook sizes them. */ enum { R4D_DT_W4_FRAG = RAD_DT_PLUGIN_BASE + 0, /* 4-bit codes in WMMA fragment order */ R4D_DT_W4_SZ = RAD_DT_PLUGIN_BASE + 1, /* (f16 scale, f16 -(1024+zero)) dwords */ @@ -266,35 +249,33 @@ enum { R4D_DT_W2_FRAG = RAD_DT_PLUGIN_BASE + 4, R4D_DT_MXFP4_FRAG = RAD_DT_PLUGIN_BASE + 5, R4D_DT_E8M0 = RAD_DT_PLUGIN_BASE + 6, /* [K/32][N] shared exponents, and Wref[N] */ - /* The grouped MoE GEMM's 4-bit expert weight: ROW-MAJOR packed nibbles, each a code into a - * sixteen-entry table, expanded to E4M3 on the way into LDS. Not R4D_DT_W4_FRAG -- that plane - * is a WMMA fragment permutation for a kernel that loads its weight straight from global, and - * this one stages through LDS because its rows are gathered. See r4d_layout.cpp. */ + /* The grouped MoE GEMM's 4-bit expert weight: row-major packed nibbles, each a code into a + * sixteen-entry table, expanded to E4M3 on the way into LDS. Not R4D_DT_W4_FRAG, which is a + * WMMA fragment permutation for a kernel loading its weight from global; this one stages + * through LDS because its rows are gathered. See r4d_layout.cpp. */ R4D_DT_MOEW4 = RAD_DT_PLUGIN_BASE + 7, - /* The same GEMM's 5-bit expert weight: each row is R4D_DT_MOEW4's nibble plane of the codes' - * low four bits -- a magnitude -- followed by one bit a code, the sign, a dword a 32 - * elements in the order the kernel merges them (r4d_layout.cpp, moew5_row). Five bits an - * element, so a row is 5K/8 bytes. */ + /* The same GEMM's 5-bit expert weight: per row, R4D_DT_MOEW4's nibble plane of the codes' low + * four bits (the magnitude), then the sign bits, one dword per 32 elements in the order the + * kernel merges them (r4d_layout.cpp, moew5_row). A row is 5K/8 bytes. */ R4D_DT_MOEW5 = RAD_DT_PLUGIN_BASE + 8 }; -/* THE GROUPED MoE GEMM'S CODE TABLES, as the four dwords w4_e4m3's byte permutes read - * (r4d_moe.hip): entries 0..3, 4..7, 8..11 and 12..15, one E4M3 byte an entry, the lowest entry in - * the low byte. `w4a8` and `w4a8h` decode a two's complement nibble, -8..7. `w4nla8h` decodes - * libquant's `table=w4nl` -- magnitudes ascending, then their negatives -- and kW4nlTable is that - * table as the floats a container stores, which the layout hook compares the container's own table - * plane with before it serves a byte of it. */ +/* The grouped MoE GEMM's code tables, as the four dwords w4_e4m3's byte permutes read + * (r4d_moe.hip): entries 0..3, 4..7, 8..11 and 12..15, one E4M3 byte an entry, lowest entry in the + * low byte. `w4a8` and `w4a8h` decode a two's complement nibble, -8..7. `w4nla8h` decodes + * libquant's `table=w4nl` (magnitudes ascending, then their negatives); kW4nlTable is that table + * as a container stores it, which the layout hook compares with the container's table plane + * before serving it. */ static constexpr uint32_t kW4IntPerm[4] = { 0x44403800u, 0x4E4C4A48u, 0xCACCCED0u, 0xB8C0C4C8u }; static constexpr uint32_t kW4nlPerm[4] = { 0x504B4539u, 0x5B595653u, 0xD0CBC5B9u, 0xDBD9D6D3u }; static constexpr float kW4nlTable[16] = { 1.125f, 3.25f, 5.5f, 8.0f, 11.0f, 14.0f, 18.0f, 22.0f, -1.125f, -3.25f, -5.5f, -8.0f, -11.0f, -14.0f, -18.0f, -22.0f }; -/* `w5nl64a8h` DECODES libquant's `table=w5nl`: thirty-two levels, the sixteen magnitudes - * ascending and then their negatives, so a code's high bit is its sign and its low four bits index - * the magnitudes. The kernel expands the magnitude as it does a w4nl code, out of kW5nlMagPerm -- - * those sixteen magnitudes' E4M3 bytes in w4_e4m3's dword order -- and sets the byte's sign bit - * from the sign plane. Every level is exact in E4M3. */ +/* `w5nl64a8h` decodes libquant's `table=w5nl`: thirty-two levels, sixteen magnitudes ascending + * then their negatives, so a code's high bit is its sign and its low four bits index the + * magnitudes. The kernel expands the magnitude from kW5nlMagPerm (their E4M3 bytes in w4_e4m3's + * dword order) and sets the sign bit from the sign plane. Every level is exact in E4M3. */ static constexpr uint32_t kW5nlMagPerm[4] = { 0x4B484235u, 0x5453514Fu, 0x5A595856u, 0x5F5D5C5Bu }; static constexpr float kW5nlTable[32] = { 0.8125f, 2.5f, 4.0f, 5.5f, 7.5f, 9.0f, 11.0f, 12.0f, @@ -302,41 +283,34 @@ static constexpr float kW5nlTable[32] = { -0.8125f, -2.5f, -4.0f, -5.5f, -7.5f, -9.0f, -11.0f, -12.0f, -14.0f, -16.0f, -18.0f, -20.0f, -22.0f, -24.0f, -26.0f, -30.0f }; -/* `w4nl64a8h`'S, `w4nl32a8h`'S AND `w5nl64a8h`'S FIXED SECOND LEVEL: a weight's E4M3 scale a (row, - * 64 or 32 of K) multiplies it, and a container states it (libquant's scale2_value=, one f32 for - * each weight), which the layout hook compares with this before serving a byte. It is fixed rather - * than per row because the experts' scales -- with the rotation's 1/128 folded in -- sit between - * 2^-15 and 2^-10.6 on Qwen3.8-Flash-Next at a 64 (a 32's sit a little lower, and w5nl's, over a - * top level of 30 rather than 22, half a binade lower), so under 2^-13 every one is a normal E4M3 - * value with binades to spare either side, and E4M3's three mantissa bits are the same in every - * binade a row level would have put it in. */ +/* The fixed second-level scale of `w4nl64a8h`, `w4nl32a8h` and `w5nl64a8h`: it multiplies a + * weight's per-(row, 64 or 32 of K) E4M3 scale. A container states it (libquant's scale2_value=), + * and the layout hook compares it with this before serving. Fixed rather than per row because the + * experts' scales (with the rotation's 1/128 folded in) lie between 2^-15 and 2^-10.6 on + * Qwen3.8-Flash-Next at group 64 (slightly lower at 32, half a binade lower for w5nl). Under + * 2^-13 each is a normal E4M3 value, and E4M3 has three mantissa bits in every binade. */ static constexpr float kW4G64Scale = 0x1p-13f; /* ================================================================== skinny-GEMM variants * - * libr4d's five skinny-GEMM knobs. Exposed as RadVariant.config so `rad-tune` can walk them and - * `--debug-graph` can name the pick (spec §15). The axis earns its keep because the best setting - * is per (N, K) AND per M band, and the spread between the best and a single fixed default is - * large enough to matter on every shape in a step. + * libr4d's five skinny-GEMM knobs, exposed as RadVariant.config so `rad-tune` can walk them and + * `--debug-graph` can name the pick (spec §15). The best setting depends on (N, K) and the M band. * - * sk == 0 means "choose the largest legal split count at issue". The split-K constraint is - * K % (SK * group) == 0, which depends on K, so no fixed default is legal at every shape -- and a - * default that is illegal at a shape would make an UNTUNED install fail rather than be slow, which - * spec §15 says is the wrong way round. The sentinel is the plugin's own rule, declared here and - * resolved in one place (r4d_gemm_args.h:pick_sk), not a hidden fallback. + * sk == 0 means "choose the largest legal split count at issue". Split-K requires + * K % (SK * group) == 0, so no fixed default is legal at every shape, and an illegal default would + * make an untuned install fail rather than run slowly (spec §15). The sentinel is resolved in one + * place, r4d_gemm_args.h:pick_sk. */ struct R4dGemmCfg { int wv, sk, mb, npw, nt; }; -/* The tiled and prefill GEMMs take a single opaque variant index into libr4d's own switch. Only - * arms that compute a CORRECT result are listed. Most arms of that switch are cost ablations that - * compute wrong answers by construction, and a tuner handed one would benchmark a kernel that does - * not compute the GEMM and then pick it. */ +/* The tiled and prefill GEMMs take one opaque variant index into libr4d's own switch of compiled + * tile arms; the row's tunable lists the arms a tuner may pick (r4d_rows.cpp, kTileArms). */ struct R4dTileCfg { int variant; int bm; int bn; }; /* The MXFP4 tiled GEMM's column width in 32-column units per wave: TN=2 gives a 256 x 64 block, - * TN=4 a 256 x 128 one. Its crossover is a function of M (r4d_gemm_mxfp4a8_tiled.hip carries the - * measurement), so 0 -- the default -- decides at issue and a fixed value is for a tuner. */ + * TN=4 a 256 x 128 one. The crossover depends on M (see r4d_gemm_mxfp4a8_tiled.hip), so 0, the + * default, decides at issue; a fixed value is for a tuner. */ struct R4dMxTileCfg { int tn; }; /* The MXFP4 decode GEMM's split-K width, K slab and weight-load hint. 0 on each is the rule in @@ -344,30 +318,27 @@ struct R4dMxTileCfg { int tn; }; * the weight past L2/MALL, 2 loads it plainly. */ struct R4dMxDecCfg { int ks; int bk; int nt; }; -/* Split-KV segment count for the paged decode kernels. 0 is libr4d's own split law, which is - * measured (r4d_attn_paged_h256_gqa6.hip carries the table) and reads num_seqs and max_ctx that - * only exist at issue -- so it stays the default and the fixed counts are there for a tuner that - * has a concrete shape. RadScratchFn is handed the same variant index, so the arena is sized for - * whatever this picks rather than for the law's answer at some other shape. */ +/* Split-KV segment count for the paged decode kernels. 0 is libr4d's split law (table in + * r4d_attn_paged_h256_gqa6.hip), which needs num_seqs and max_ctx from the issue, so it stays the + * default; fixed counts are for a tuner. RadScratchFn gets the same variant index, so the arena + * is sized for what this picks. */ struct R4dSplitCfg { int splits; }; -/* The all-reduce launch geometry. libr4d takes nblocks/nthreads/drain/acq (and `pub` at width) as - * arguments rather than compiling them in. The defaults are nthreads=1024, drain=3 - * (s_wait_storecnt, which is what fine-grained uncached scratch requires), acq=0 and pub=1, with - * nblocks scaled by message size and clamped. nblocks == 0 selects that scaling rule. */ +/* The all-reduce launch geometry, passed to libr4d as nblocks/nthreads/drain/acq (and `pub` at + * width). Defaults: nthreads=1024, drain=3 (s_wait_storecnt, which fine-grained uncached scratch + * requires), acq=0, pub=1, and nblocks scaled by message size and clamped; nblocks == 0 selects + * that rule. */ struct R4dArCfg { int nblocks; int nthreads; int drain; int acq; int pub; }; -/* rowtopk: RC is how many candidates a chunk keeps (>= R), NCH the requested chunk width (a - * REQUEST -- libr4d rounds it up to a multiple of eight columns, so the scratch hook asks - * r4d_rowtopk_bf16_chunks() what the launch will actually use), PT1 the stage-1 thread count. */ +/* rowtopk: RC is how many candidates a chunk keeps (>= R), NCH the requested chunk width (libr4d + * rounds it up to a multiple of eight columns, so the scratch hook asks r4d_rowtopk_bf16_chunks() + * for the real one), PT1 the stage-1 thread count. */ struct R4dTopkCfg { int rc; int nch; int pt1; }; -/* The block-scaled fp8 matvec's rows a wave. Blocking trades waves for memory-level parallelism, so - * where it lands depends on whether the kernel is waiting on loads or on the ALU -- a property of - * the shape AND of the inner loop. THE RULE IS FITTED, so it holds only for the loop it was fitted - * against: any change to the matvec's inner loop (the width of the scale load, the activation - * dtype) invalidates it and it has to be re-fitted. 0 selects libr4d's default rule, so an untuned - * install is fast rather than broken; the rest pin it for rad-tune. */ +/* The block-scaled fp8 matvec's rows a wave. Blocking trades waves for memory-level parallelism, + * so the best value depends on whether the kernel waits on loads or the ALU. The default rule is + * fitted to the current inner loop: any change to it (scale load width, activation dtype) + * requires re-fitting. 0 selects that rule; other values pin it for rad-tune. */ struct R4dMvCfg { int rb; }; @@ -375,13 +346,10 @@ struct R4dMvCfg { int rb; }; extern "C" { /* -- the tuned configuration (r4d_rows.cpp) -- * - * The core resolved one instantiation, picked a point in the space the row declared, and appended - * the choices to RadArgs::p. These read that point back, falling to the axis's own default when a - * cold caller supplied none -- so the default is defined once, in the RadTunable table, and a - * checker calling the kernel with no tuned key gets exactly what an untuned install runs. - * - * They cannot fail: every axis has a default and the loader refuses a plugin whose default is not - * one of that axis's own values, so there is no "out of range" to report. */ + * The core picked a point in the space the row declared and appended it to RadArgs::p. These read + * it back, falling to the axis's default (defined once, in the RadTunable table) when a caller + * supplied none, so a checker with no tuned key runs what an untuned install runs. They cannot + * fail: the loader refuses a plugin whose default is not one of the axis's values. */ void r4d_cfg_gemm (const RadArgs*, struct R4dGemmCfg*); void r4d_cfg_tiled (const RadArgs*, struct R4dTileCfg*); void r4d_cfg_prefill(const RadArgs*, struct R4dTileCfg*); diff --git a/libr4d/r4d_attn_args.h b/libr4d/r4d_attn_args.h index d428ad08..13a8e5c6 100644 --- a/libr4d/r4d_attn_args.h +++ b/libr4d/r4d_attn_args.h @@ -1,20 +1,15 @@ -/* r4d_attn_args.h -- the paged-attention operand list, read once for four kernel geometries. +/* r4d_attn_args.h -- the paged-attention operand reader shared by every paged kernel geometry. * - * The paged kernels -- h256/gqa6, h128/gqa4 and the gqa8/gqa12 instantiations, prefill and decode - * -- take the SAME operands in the same order, because they implement the same op. The reader for - * that list therefore belongs to the family rather than to any one of them, and this is where it - * lives: a header beside the kernels, included by each unit's entry point. + * The paged kernels (h256/gqa6, h128/gqa4, the gqa8/gqa12 instantiations; prefill and decode) take + * the same operands in the same order, so one reader serves them all. * - * It is NOT a translation layer. libr4d's R4DArgs carries the same convention RadTensor does -- - * strides in ELEMENTS (spec 2.1) -- so this is field extraction plus the validation a constraint - * cannot do: a constraint settles whether a kernel EXISTS for a geometry and says nothing about a - * particular call, so contiguity, alignment and buffer sizes are checked here and refused with the - * code that names the class. + * R4DArgs uses RadTensor's convention (strides in elements, spec 2.1), so this is field extraction + * plus the per-call validation a constraint cannot express: contiguity, alignment and buffer + * sizes, each refused with the code that names the class. * - * The kernels already return a negative code for a shape they do not serve (-1 head_dim or - * block_size, -2 gqa, -4 too many decode rows, -100-hipError for a launch failure) and those are - * passed through unchanged: a caller that gets one has hit a selection bug, and the exact value is - * what says which. + * Kernel return codes for an unserved shape (-1 head_dim or block_size, -2 gqa, -4 too many decode + * rows, -100-hipError for a launch failure) pass through unchanged. Getting one means a selection + * bug, and the value says which. */ #ifndef R4D_ATTN_ARGS_H #define R4D_ATTN_ARGS_H @@ -23,10 +18,10 @@ #include "r4d_args.h" #include +#include -/* libr4d's compiled-in geometry, checked against the row table at build time rather than trusted. - * A libr4d rebuilt for a different head size would otherwise change what the rows mean without - * changing the rows. */ +/* Checks libr4d's compiled-in geometry against the row table, so a libr4d rebuilt for a + * different head size cannot silently change what the rows mean. */ static inline int check_dims_once() { int hd = 0, gqa = 0, bs = 0, rows = 0; r4d_attn_dims(&hd, &gqa, &bs, &rows); @@ -38,20 +33,12 @@ enum { AP_Q = 0, AP_KV, AP_BT, AP_SEQ, AP_KDS, AP_VDS, AP_CU, AP_OUT }; /* Fill R4DArgs from a RadArgs. Returns RAD_OK, or the negative code naming what is wrong. * - * RAGGED BATCHES. libr4d's paged kernels take a scalar q_len AND an optional cu_seqlens, and which - * one this call uses is decided here. Without cu_seqlens every sequence in the batch has to present - * the same query length, which is a restriction the scheduler does not honour and cannot be asked - * to: core/sched/scheduler.cpp builds RAD_PHASE_MIXED steps deliberately, because a decode row - * costs nothing once another sequence's prefill chunk is already reading the weights. A step that - * mixes them has total_q that need not divide n_seq, and refusing that with RAD_E_SHAPE would be - * reported by the run phase as a kernel that does not serve the shape, which aborts the engine. So - * the operand is passed whenever it is there and the uniform arithmetic is kept only for the case - * where it is not. - * - * q_len then means the batch MAXIMUM, and it comes from the PARAMETER, which is exactly what the - * arch block issued the op with (RAD_ISSUE_N(..., batch->max_q_len, ...)). Deriving it from the - * tensors is only possible in the uniform case, and that is what the code below does there -- - * total_q / num_seqs -- because the parameter is a band bound there, not a count. + * Ragged batches: the kernels take a scalar q_len and an optional cu_seqlens. Without cu_seqlens + * every sequence must have the same query length, which RAD_PHASE_MIXED steps (decode rows riding + * on another sequence's prefill chunk, core/sched/scheduler.cpp) do not satisfy; refusing them + * would abort the engine. So cu_seqlens is used whenever present, and the uniform arithmetic + * (q_len = total_q / num_seqs) only when it is not. In the ragged case q_len is the batch maximum, + * taken from the parameter the arch block issued the op with (batch->max_q_len). */ static inline int fill_paged(const RadArgs* a, R4DArgs* r, int expect_head_dim) { const RadTensor* q = r4d_opt(a, AP_Q); @@ -65,13 +52,9 @@ static inline int fill_paged(const RadArgs* a, R4DArgs* r, int expect_head_dim) if (q->rank < 2 || o->rank < 2 || bt->rank != 2 || su->rank < 1) return R4D_NO(RAD_E_SHAPE); if (kv->rank != 4) return R4D_NO(RAD_E_SHAPE); - /* THE HEAD AXIS MAY BE SPELLED OR FLATTENED, and both are the same dense block. An architecture - * plugin declares the query buffer [tokens, n_head, head_dim] when something downstream needs - * the head axis and [tokens, n_head*head_dim] when nothing does -- a gated attention block does - * the latter, because its query comes out of a de-interleave and goes straight here. The kernel - * indexes one dense [total_q, q_heads, head_dim] block either way, so the shim reads the rank - * it was given rather than demanding three. `head_dim` is the op's parameter, which is what - * makes the flattened form readable at all. */ + /* The query may be [tokens, n_head, head_dim] or flattened to [tokens, n_head*head_dim] + * (a gated attention block's de-interleaved query). Both are the same dense block, so any rank + * is accepted; head_dim comes from the op parameter, which makes the flattened form readable. */ const long long head_dim = expect_head_dim; const long long total_q = q->shape[0]; const long long num_seqs = bt->shape[0]; @@ -79,7 +62,7 @@ static inline int fill_paged(const RadArgs* a, R4DArgs* r, int expect_head_dim) if (r4d_numel(q) % (total_q * head_dim)) return R4D_NO(RAD_E_SHAPE); const long long q_heads = r4d_numel(q) / (total_q * head_dim); if (q_heads <= 0) return R4D_NO(RAD_E_SHAPE); - /* Ragged unless cu_seqlens says otherwise; see the note above fill_paged. */ + /* Ragged exactly when cu_seqlens is present; see the note above fill_paged. */ const bool ragged = (cu != nullptr) && cu->data; if (ragged) { if (cu->rank != 1 || cu->shape[0] != num_seqs + 1) return R4D_NO(RAD_E_SHAPE); @@ -96,15 +79,14 @@ static inline int fill_paged(const RadArgs* a, R4DArgs* r, int expect_head_dim) if (su->shape[0] != num_seqs) return R4D_NO(RAD_E_SHAPE); if (!r4d_contig(bt) || !r4d_contig(su)) return R4D_NO(RAD_E_STRIDE); - /* The KV cache is the one operand that IS pitched: kv_block_stride and kv_head_stride are - * taken as arguments, so a padded cache is legal. Everything inside a (block, head) slot is - * not, because the kernel walks it with a vector load. */ + /* The KV cache is pitched (kv_block_stride, kv_head_stride), so a padded cache is legal. + * Each (block, head) slot must be dense, because the kernel walks it with vector loads. */ const long long block_size = kv->shape[2]; if (kv->stride[3] != 1) return R4D_NO(RAD_E_STRIDE); if (kv->stride[2] != 2 * head_dim) return R4D_NO(RAD_E_STRIDE); if (kv->shape[3] != 2 * head_dim) return R4D_NO(RAD_E_SHAPE); - /* 16-byte alignment: every one of these is read through a 128-bit load. */ + /* 16-byte alignment for 128-bit loads. */ if (!r4d_aligned(q->data, 16) || !r4d_aligned(o->data, 16) || !r4d_aligned(kv->data, 16)) return R4D_NO(RAD_E_ALIGN); @@ -124,20 +106,12 @@ static inline int fill_paged(const RadArgs* a, R4DArgs* r, int expect_head_dim) r->num_seqs = (int)num_seqs; r->cu_q = ragged ? (const int*)cu->data : nullptr; r->total_q = (int)total_q; - /* q_len is the exact count when the batch is uniform, and an UPPER BOUND on the per-sequence - * lengths when it is ragged -- it sizes the prefill grid and the decode wave count, and the - * kernels take the exact lengths from cu_seqlens. - * - * The bound is the smaller of two things that are both >= the true maximum and neither of - * which is it. The `q_len` parameter is the resolved BAND (RadArgs carries the geometry with - * ranges collapsed, not the value the op was issued with), and the band was selected by - * max_q_len, so it is at least that. total_q is a sum of lengths, so it is at least the - * largest of them. Taking the smaller keeps the decode band legal: its bound is 10 and - * 10 * gqa is 60 rows, under the 64 a decode workgroup holds, while total_q alone would be - * the whole batch and would be refused with -4. - * - * The cost of the bound not being tight is empty workgroups that exit on their first - * comparison -- the prefill kernel's `qb * BLOCK_Q >= qlen` and the decode kernel's `live`. */ + /* q_len is exact for a uniform batch and an upper bound for a ragged one; it sizes the + * prefill grid and the decode wave count, and the kernels read exact lengths from cu_seqlens. + * The bound is min(band, total_q): the `q_len` parameter is the resolved band selected by + * max_q_len, and total_q is a sum of lengths, so both are >= the true maximum. The min keeps + * decode legal (band bound 10 * gqa 6 = 60 rows fits a 64-row workgroup; total_q alone would + * be refused with -4). A loose bound only costs workgroups that exit on their first compare. */ r->q_len = (int)(total_q / num_seqs); if (ragged) { const long long band = r4d_geti_or(a, "q_len", total_q); @@ -154,13 +128,11 @@ static inline int fill_paged(const RadArgs* a, R4DArgs* r, int expect_head_dim) r->causal = (int)r4d_geti_or(a, "causal", 1); r->causal_seq = nullptr; - /* The softmax scale. Absent, 1/sqrt(head_dim) -- right for every model in scope, and a - * parameter rather than a hardcode for the ones that are not. */ + /* Softmax scale; defaults to 1/sqrt(head_dim). */ r->scale = (float)r4d_getf(a, "scale", 1.0 / std::sqrt((double)head_dim)); - /* max_ctx is the HOST-visible context bound; seqused_k is device-side and the split law - * cannot read it. The block table's width times the block size is an exact upper bound on - * what any sequence in this batch can have, so it is a safe default. */ + /* max_ctx is the host-visible context bound for the split law (seqused_k is device-side). + * Block-table width times block size is a safe upper bound. */ long long mc = r4d_geti_or(a, "max_ctx", 0); if (mc <= 0) mc = (long long)r->max_blocks * block_size; r->max_ctx = (int)mc; diff --git a/libr4d/r4d_attn_decode_h256_gqa6.hip b/libr4d/r4d_attn_decode_h256_gqa6.hip index a7e6cc0f..574b6c91 100644 --- a/libr4d/r4d_attn_decode_h256_gqa6.hip +++ b/libr4d/r4d_attn_decode_h256_gqa6.hip @@ -1,22 +1,21 @@ -// R4D decode. The prefill core (lazy reference-max softmax, f16 operands, folded query scale, -// contiguous-k fragments, prefetch + scheduling barrier, dot2 row sum) on the split-KV MTP-verify -// shape, plus two decode-only changes: +// R4D split-KV decode (also the MTP-verify shape). Same core as the prefill kernel (lazy +// reference-max softmax, f16 operands, folded query scale, contiguous-k fragments, prefetch + +// scheduling barrier, dot2 row sum), plus two decode-only options: // -// KLDS0 reads K straight from the paged cache, including when that cache is fp8. The -// widening moves from once-per-workgroup to once-per-warp; it costs VALU on a leg that is -// bandwidth-bound and buys back the whole sK allocation, which at TILE 16 is 8.3 KB of -// the 14.5 KB that sets resident-CTA count. This is the argmin at every depth. -// PF16 split-KV partials as f16 instead of f32. The partial buffer is written once and read -// back once, and at 16K context that round trip is ~14 MB against ~17 MB of KV -- i.e. -// nearly half the leg's DRAM traffic. Storing O/l rather than O bounds the value by -// max|v|, so f16 cannot overflow and its 11-bit mantissa costs ~5e-4 relative. +// KLDS0 reads K straight from the paged cache (bf16 or fp8), widening once per warp instead of +// once per workgroup. Costs VALU on a bandwidth-bound leg and frees sK, which at TILE 16 +// is 8.3 KB of the 14.5 KB that limits resident workgroups. Best at every depth. +// PF16 split-KV partials stored as f16. At 16K context the partial round trip is ~14 MB +// against ~17 MB of KV. Storing O/l instead of O bounds values by max|v|, so f16 cannot +// overflow; the 11-bit mantissa costs ~5e-4 relative. // -// This file compiles neither an fp8-P leg nor an alternative to the CONTIG fragment layout; see -// r4d_attn_prefill_h256_gqa6.hip for the full option set and the reasoning behind each bit. +// No fp8-P leg and no non-CONTIG alternative here; r4d_attn_prefill_h256_gqa6.hip documents the +// full option set. #include "r4d.h" #include "r4d_common.h" #include "r4d_dt16.h" #include "r4d_q8.h" // the gate quantiser's 8-bit codes: E4M3, or int8 (GQ == 2) +#include #include #define O_F16 1 @@ -30,60 +29,29 @@ #define O_PF8 3072 #define O_SGB 4096 #define O_DOT2 16384 -// The tile-staging set, shared with r4d_attn_prefill_h256_gqa6.hip -- see the comments there. -// BTS block table entries for the tile in SGPRs, loaded a tile ahead. On this leg it also -// removes a dependent global load from INSIDE the m-tile loop: with KLDS0 the K address -// comes from bt[kk/BS] on every m-tile. +// Tile-staging options, shared with r4d_attn_prefill_h256_gqa6.hip: +// BTS the tile's block-table entries in SGPRs, loaded a tile ahead. With KLDS0 this also takes +// the dependent bt[kk/BS] load out of the m-tile loop. // GPREV tile ti+1's V fetched into registers before the m-tile loop. -// LDSB an LDS-scoped barrier, so __syncthreads() stops invalidating the vector cache. +// LDSB an LDS-scoped barrier, so the barrier does not invalidate the vector cache. #define O_BTS 262144 #define O_GPREV 1048576 #define O_LDSB 2097152 -// O_KNT: a non-temporal hint on the K global load. The KV a decode step reads is 134 MB a layer -// streamed once and never re-read, and it walks the whole last level on the way past -- so what the -// hint would protect is not this kernel but the GEMMs either side of it, whose activation is small -// enough to live in cache if something stops evicting it. V cannot take the hint at all: it is -// loaded through `global_load_tr_b128` and that intrinsic has no non-temporal form. -// -// OFF BY DEFAULT. The hint changes no bytes and costs nothing, and it also gains nothing: on this -// part the KV stream is not what evicts the neighbouring GEMMs' activation, so neither this kernel -// nor they move when it is set. The bit costs one template parameter and is kept so the option -// stays available for a deployment where the cache pressure is different. -#define O_KNT 4194304 -// O_V8: an fp8 cache's V tile staged in LDS as its codes, converted when a fragment is read. -// -// The f16 tile is 12 KiB a workgroup and a one-wave workgroup has nothing else in LDS, so it is -// what caps residency: ten workgroups a WGP, two and a half waves a SIMD, for a leg whose tile -// loop is a chain of global latencies. The codes are 6 KiB. At one wave a workgroup the number of -// conversions is the same either way -- each V element is read once by the one wave -- and the -// conversion is exact, so the fragments, and every byte after them, match the f16 tile's. With more -// waves a workgroup each would convert the whole tile, so the launcher sets it at one. +// Bit 4194304 is free: a non-temporal hint on the K load gained nothing on the target GPU (the KV +// stream does not evict the neighbouring GEMMs' activations). +// O_V8: an fp8 cache's V tile staged in LDS as codes (6 KiB instead of 12 KiB of f16), converted +// when a fragment is read. For a one-wave workgroup the f16 tile is what caps residency (ten +// workgroups per WGP). At one wave the conversion count is unchanged and the conversion is exact, +// so results are identical; with more waves each would convert the whole tile, so the launcher +// uses it only at one wave. #define O_V8 8388608 -// O_KRAW: with K read straight from the paged cache (KLDS0, CONTIG), an m-tile's K is loaded in ONE -// round -- all HEAD_DIM/16 fragment loads, issued as soon as the row address is known -- and each -// fragment is converted from its registers just before its WMMA. -// -// The prefetch depth (PF) and the scheduling barrier between a group's loads and its WMMAs say -// what may overlap, and a compiler is free to honour them literally: LLVM 24 does, and with PF 2 a -// tile's K then arrives in HEAD_DIM/32 round trips, one after another, which cost the head_dim-128 -// drafter leg 16-19% on a bf16 cache. LLVM 22 lifted the loads over the barriers and issued them in -// one round. This bit asks for that round explicitly. What is held is the cache's own bytes -- 8 a -// fragment from fp8, 16 from bf16 -- not the converted fragment, so a full round costs 2 or 4 x -// HEAD_DIM/16 VGPRs; PF = HEAD_DIM/16 would hold every converted fragment at once and cost the -// waves a SIMD. The fragments, and every byte after them, are unchanged. +// O_KRAW: with K read from the paged cache (KLDS0, CONTIG), issue all HEAD_DIM/16 fragment loads +// of an m-tile in one round and convert each fragment just before its WMMA. LLVM 24 honours the PF +// groups and scheduling barriers literally, so with PF 2 K arrives in HEAD_DIM/32 serial round +// trips (16-19% on the head_dim-128 drafter leg, bf16 cache). Raw cache bytes are held (8 per +// fragment for fp8, 16 for bf16), costing 2 or 4 x HEAD_DIM/16 VGPRs; PF = HEAD_DIM/16 would hold +// converted fragments and cost occupancy. Results are unchanged. #define O_KRAW 16777216 -// `__builtin_nontemporal_load` will not take `uint4`/`uint2` -- they are HIP_vector_type class -// templates, not native vectors -- so the hinted loads go through these and bit-cast the WHOLE -// value back (never a subscript of it, which miscompiles). -typedef unsigned r4d_ntu4 __attribute__((ext_vector_type(4))); -typedef unsigned r4d_ntu2 __attribute__((ext_vector_type(2))); - -template -__device__ __forceinline__ T r4d_kload(const T* p) { - if (!NT) return *p; - return __builtin_bit_cast(T, __builtin_nontemporal_load((const V*)p)); -} - __host__ __device__ __forceinline__ int r4d_attn_tiles(int ctx, int tile) { return (ctx + tile - 1) / tile; } __host__ __device__ __forceinline__ int r4d_attn_tps(int ctx, int tile, int splits) { int t = r4d_attn_tiles(ctx, tile); return (t + splits - 1) / splits; @@ -99,9 +67,8 @@ __host__ __device__ __forceinline__ int r4d_attn_used(int ctx, int tile, int spl int t = r4d_attn_tiles(ctx, tile), tps = r4d_attn_tps(ctx, tile, splits); return (t + tps - 1) / tps; } -// WIN turns on a sliding window (a.window positions, ending at each row's causal -// limit). It is a TEMPLATE parameter and defaults to 0, so a full-attention geometry -// compiles with no bound, no clamp and no extra mask term. +// WIN enables a sliding window (a.window positions ending at each row's causal limit). As a +// template parameter defaulting to 0, full attention compiles with no window code. template __global__ __launch_bounds__(NWARPS * 32) @@ -118,7 +85,6 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) constexpr int DOT2 = ((OPT & O_DOT2) && (OPT & O_F16)) ? 1 : 0; constexpr int BTS = (OPT & O_BTS) ? 1 : 0; constexpr int LDSB = (OPT & O_LDSB) ? 1 : 0; - constexpr int KNT = (OPT & O_KNT) ? 1 : 0; constexpr int V8 = ((OPT & O_V8) && !KVP) ? 1 : 0; static_assert(!V8 || (OPT & O_CONTIG), "the code tile is read in the contiguous layout"); constexpr int KRAW = ((OPT & O_KRAW) && !KLDS) ? 1 : 0; @@ -134,27 +100,18 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) constexpr int NB = TILE / BS; constexpr int NTR = (TILE / 8) * (HEAD_DIM / (KVP ? 32 : 64)); constexpr int VREGS = (NTR + NWARPS - 1) / NWARPS; - // A V prefetch costs VREGS x 4 VGPRs and this leg already carries a 128-VGPR accumulator and a - // 64-VGPR query. At two uint4 (fp8 KV, TILE 16) it is worth 6-8% at depth; at four (fp8 - // TILE 32, or bf16 TILE 16, whose V is twice the bytes) it spills and LOSES 10%. So the - // geometry decides, not the flag. - // THREE is reachable only because the K prefetch needs just two: the three-uint4 form is what - // the 48-row shape (q_len 8, gqa 6, so NWARPS 3 over NTR 8) needs, it stays inside 255 VGPRs - // with no spill, and it is worth a further 2-15% on top -- most at the depths where the K - // stream has the least other work to hide behind. At NWARPS 1 or 2, and for a bf16 cache whose - // V is twice the bytes, VREGS is 4 or more and the prefetch stays off. -#ifndef R4D_GPREV_VREGS -#define R4D_GPREV_VREGS 3 -#endif - constexpr int GPREV = ((OPT & O_GPREV) && VREGS <= R4D_GPREV_VREGS) ? 1 : 0; + // A V prefetch costs VREGS x 4 VGPRs on top of a 128-VGPR accumulator and a 64-VGPR query. + // Up to three uint4 it fits in 255 VGPRs without spilling (two: +6-8% at depth; three, the + // 48-row shape q_len 8 x gqa 6 at NWARPS 3: a further 2-15%). At four or more (NWARPS 1-2, or a + // bf16 cache) it spills and loses ~10%, so the geometry gates it, not just the flag. + constexpr int GPREV = ((OPT & O_GPREV) && VREGS <= 3) ? 1 : 0; constexpr float PSHIFT = D::SHIFT; constexpr float PGROW = D::GROW; __shared__ uint16_t sK[KLDS ? TILE * KSTR : 1]; __shared__ uint16_t sV16[V8 ? 1 : HEAD_DIM * VSTR]; - /* A row of the code tile is 16 keys and 8 of padding: 24 bytes is six dwords, so the sixteen - * lanes of a fragment read land on distinct banks, and a lane's eight codes are one aligned - * 8-byte load. */ + /* 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]; @@ -165,19 +122,16 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) const int ctx = a.seqused_k[seq]; if (ctx <= 0) return; - // Ragged batches (r4d.h, R4DArgs::cu_q): the rows of q and out this sequence owns, and its - // own query length. `a.q_len` is the batch maximum when cu_q is set, and it is what the - // launcher sized the wave count from, so rows past `qlen` are simply not live. + // Ragged batches (r4d.h, R4DArgs::cu_q): this sequence's q/out rows and query length. With + // cu_q, a.q_len is the batch maximum that sized the wave count; rows past qlen are not live. const int qoff = r4d_q_off(a.cu_q, seq, a.q_len); const int qlen = r4d_q_len(a.cu_q, seq, a.q_len); if (qlen <= 0) return; // a slot carrying no query rows this step const int ntl = r4d_attn_tiles(ctx, TILE); - // A sliding-window layer reads only the last `window` positions. The blocks below - // that are not merely useless: the engine has freed them and may already have handed - // them to another sequence, so reading one is wrong rather than wasteful. The walk - // starts at the tile holding the window's first token -- taken at query row 0, - // whose window reaches furthest back -- and the splits divide THAT range. + // A sliding-window layer must not read below the window: those blocks may already be freed + // and reassigned to another sequence. The walk starts at the tile holding row 0's first + // window token (row 0 reaches furthest back), and the splits divide that range. const int wlo0 = WIN ? r4d_attn_wlo(ctx, qlen, 0, a.window) : 0; const int tb = WIN ? wlo0 / TILE : 0; const int neff = ntl - tb; @@ -211,9 +165,9 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) } } - // The row's absolute position. Causal masking bounds the key by it; non-causal - // masking bounds the key by the sequence and lets the window bound it on BOTH - // sides, which is what a block-diffusion drafter's own block needs. + // The row's absolute position. Causal masking bounds the key by it; non-causal masking + // bounds it by the sequence, with the window applied on both sides (a block-diffusion + // drafter's own block). const int pos = ctx - qlen + qrow; const int cz = a.causal_seq ? (int)((const unsigned char*)a.causal_seq)[seq] : a.causal; const int klimit = cz ? pos @@ -287,12 +241,10 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) } }; - // A tile's NB entries are read whole, and when a tile spans several blocks the last one can run - // past the sequence's last block -- past the end of its row, and on the last row past the end - // of the table. Every key is clamped to ctx - 1 before it picks an entry, so no entry past - // `lastb` is ever used and clamping the index there changes no value that is. Only a window - // that reaches past `lastb` takes the clamped form, so every other tile keeps its one wide - // scalar load; at one block a tile no window can reach past it and the test folds away. + // A tile's NB entries are read whole, and a multi-block tile can run past the sequence's last + // block (on the last row, past the end of the table). Keys are clamped to ctx - 1, so entries + // past lastb are never used; only tiles reaching past lastb take the clamped load, and the + // rest keep one wide scalar load. With NB == 1 the test folds away. const int lastb = (ctx - 1) / BS; auto load_bt = [&](int t0, int* out) { if (NB > 1 && t0 + NB - 1 > lastb) { @@ -327,13 +279,11 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) uint16_t* kd = &sK[key * KSTR]; uint32_t w4[4]; if (KVP) { - const uint4 r = r4d_kload( - (const uint4*)((const uint16_t*)a.kv + o + ch * 8)); + const uint4 r = *(const uint4*)((const uint16_t*)a.kv + o + ch * 8); w4[0] = D::from_bf16w(r.x); w4[1] = D::from_bf16w(r.y); w4[2] = D::from_bf16w(r.z); w4[3] = D::from_bf16w(r.w); } else { - fp8x8_to_16x4w(r4d_kload( - (const uint2*)((const uint8_t*)a.kv + o + ch * 8)), w4); + fp8x8_to_16x4w(*(const uint2*)((const uint8_t*)a.kv + o + ch * 8), w4); } *(uint2*)(kd + ch * 8) = make_uint2(w4[0], w4[1]); *(uint2*)(kd + ch * 8 + 4) = make_uint2(w4[2], w4[3]); @@ -355,7 +305,7 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) + (size_t)kvh * a.kv_head_stride + (size_t)(kk % BS) * (2 * HEAD_DIM)) * (KVP ? 2 : 1); } - // A fragment's K bytes: 8 elements at 1 byte (fp8) or 2 (bf16), as the branches below read. + // A fragment's raw K: 8 elements of 1 byte (fp8) or 2 (bf16). typedef typename std::conditional::type kraw_t; kraw_t kraw[KRAW ? NKS : 1]; if constexpr (KRAW) { @@ -373,8 +323,7 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) if (KLDS) { const uint16_t* kp = &sK[(mt * 16 + c) * KSTR + 16 * t]; if (CTG) { - const uint4 u = r4d_kload( - (const uint4*)(kp + 8 * h)); + const uint4 u = *(const uint4*)(kp + 8 * h); kb[j] = D::mk(make_uint2(u.x, u.y), make_uint2(u.z, u.w)); } else { kb[j] = D::mk(*(const uint2*)(kp + 4 * h), *(const uint2*)(kp + 8 + 4 * h)); @@ -395,7 +344,7 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) } else { const uint8_t* kp = grow + 16 * t; uint32_t w4[4]; - // CONTIG makes this ONE 8-byte load where the split map needs two 4-byte. + // CONTIG: one 8-byte load; the split map needs two 4-byte loads. uint2 raw; if constexpr (KRAW && KVP == 0) raw = kraw[t]; else raw = CTG ? *(const uint2*)(kp + 8 * h) @@ -528,29 +477,17 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) } } -// Vectorised merge, and the one the h256 launcher takes whenever the split count fits a wave. -// The arithmetic is identical to r4d_attn_splitkv_combine_kernel below, bit for bit; what changes -// is the thread map. One WAVE owns one output row and each lane owns EIGHT of that row's 256 -// dims, so a segment is one 16-byte load per lane instead of eight 2-byte loads -- the same 512 -// bytes per instruction across the wave, at an eighth of the instructions -- and one block -// carries JPB rows. There is no barrier and no LDS anywhere in it, which is also what lets the -// rows sharing a block have different contexts, and so different segment counts. -// ---- THE OUTPUT GATE AND THE fp8 QUANTISER AS THE MERGE'S EPILOGUE (attn_paged_gate_quant) ---- +// ---- Output gate and fp8 quantiser as the merge's epilogue (attn_paged_gate_quant) ---- // -// A gated attention's output goes from here straight into `gate_quant_fp8`: bf16(sigmoid(gate)), -// times the merged row, rounded to bf16, and E4M3 codes with one scale per 128 columns taken over -// that product. A merge row is one (token, head) pair and 128 columns are one scale group, so the -// row that is merged here is exactly the rows the quantiser would read back -- and it is still in -// registers. The `_gq` forms below finish it in place, with no dispatch between the two. +// A gated attention's merged row feeds gate_quant_fp8: bf16(sigmoid(gate)) times the row, rounded +// to bf16, then E4M3 codes with one scale per 128 columns. A merge row is one (token, head) pair +// and a scale group is 128 columns, so the `_gq` forms finish the row in registers instead of in a +// second dispatch. // -// BYTE-FOR-BYTE `gate_quant_fp8`'s arithmetic, which r4d_fused_quant_fp8.hip states: the gate -// rounded to bf16 before the multiply, the product rounded, the group's absmax (a max, so the -// order it is taken in cannot matter), scale = amax / 448 or 1 at zero, codes over product / scale -// clamped to +-448 -- and the bf16 product is what lands in `out`, as the in-place pair leaves it. -// A padded slot merges to zeros and then takes the same epilogue, as the pair would give it. -// -// GQ == 2 IS THE SAME EPILOGUE AT INT8 CODES, for an int8 out projection: scale amax / 127 and the -// value over it rounded to nearest-even (r4d_q8.h) -- gate_quant_fp8's int8 form, byte for byte. +// Byte-identical to gate_quant_fp8 (r4d_fused_quant_fp8.hip): gate rounded to bf16 before the +// multiply, product rounded, scale = group absmax / 448 (1 at zero), codes clamped to +-448, and +// the bf16 product stored to `out`. A padded slot merges to zeros and takes the same epilogue. +// GQ == 2 is the int8 form (scale amax / 127, round to nearest-even, r4d_q8.h). struct R4DGateQuant { const uint16_t* g; // gate, row `job` at g + job * g_ld uint8_t* q; // E4M3 (or int8, `i8`) codes, row `job` at q + job * q_ld @@ -567,6 +504,10 @@ __device__ __forceinline__ uint16_t r4d_gq_gate(uint16_t gb, uint16_t xb) { } __device__ __forceinline__ float r4d_gq_clamp(float v) { return fminf(fmaxf(v, -448.0f), 448.0f); } +// Vectorised merge, used by the h256 launcher whenever the split count fits a wave. Bit-identical +// to splitkv_combine_body below; only the thread map differs. One wave owns one output row and +// each lane HEAD_DIM/32 dims, so a segment is one 16-byte load per lane; a block carries JPB rows. +// No barrier and no LDS, so rows in one block may have different contexts and segment counts. template __device__ __forceinline__ void splitkv_combine_vec_body(const R4DArgs& a, int splits, int tile, const R4DGateQuant& gq) @@ -580,9 +521,8 @@ void splitkv_combine_vec_body(const R4DArgs& a, int splits, int tile, const R4DG const int ctx = a.seqused_k[seq]; uint16_t* outp = (uint16_t*)a.out + (size_t)job * HEAD_DIM + lane * DPL; - /* The row's bf16 values, then either the plain store or the gated, quantised one. A lane's - * DPL columns sit inside one 128-column group, and the group is the 128 / DPL lanes around it, - * so its absmax is a butterfly over those lanes and nothing wider. */ + /* Plain store, or gated + quantised. A lane's DPL columns lie in one 128-column group of + * 128 / DPL lanes, so the group absmax is a butterfly over those lanes only. */ auto finish = [&](const uint16_t (&ob)[DPL]) { if constexpr (!GQ) { union { uint4 u4; uint2 u2; uint16_t w[DPL]; } o_; @@ -643,9 +583,9 @@ void splitkv_combine_vec_body(const R4DArgs& a, int splits, int tile, const R4DG else { const float* so = (const float*)a.scratch; sm = so + nrow * HEAD_DIM; sl = sm + nrow; } - // max is exact in any order, and taken sequentially it is wave-uniform, so this is a scalar - // walk. The sum keeps the LDS tree association: the stride-32 pre-accumulation is that tree - // off=32 round, and the xor butterfly 16..1 is the rest of it, leaving the value in every lane. + // max is order-independent and wave-uniform, so it is a scalar walk. The sum reproduces the + // LDS tree's association (stride-32 pre-accumulation, then xor butterfly 16..1) so results + // match the non-vector merge bit for bit. float gmax = -INFINITY; for (int s = 0; s < u; ++s) gmax = fmaxf(gmax, sm[base + s]); float tot = 0.0f; @@ -671,7 +611,7 @@ void splitkv_combine_vec_body(const R4DArgs& a, int splits, int tile, const R4DG int s = 0; if (PF16) { const uint16_t* op = (const uint16_t*)a.scratch + base * HEAD_DIM + lane * DPL; - // One aligned access a lane a segment: 16 bytes at head_dim 256, 8 at 128. + // One aligned access per lane per segment: 16 bytes at head_dim 256, 8 at 128. union { uint4 u4; uint2 u2; __fp16 h[DPL]; } r; auto rd = [&](int sx) { if (DPL == 8) r.u4 = *(const uint4*)(op + (size_t)sx * HEAD_DIM); @@ -719,8 +659,7 @@ void splitkv_combine_vec_body(const R4DArgs& a, int splits, int tile, const R4DG float av = 0.0f; #pragma unroll for (int i = 0; i < CHAINS; ++i) av += ch[i][j]; - // (av * vd) / tot, in that order: folding vd/tot into one reciprocal first is a different - // rounding and shows up as a whole bf16 ULP on the merged output. + // (av * vd) / tot in this order; folding vd/tot first rounds differently (one bf16 ULP). ob[j] = f32_to_bf16(tot > 0.0f ? av * vd / tot : 0.0f); } finish(ob); @@ -741,9 +680,9 @@ void r4d_attn_splitkv_combine_vec_gq_kernel(const R4DArgs a, int splits, int til splitkv_combine_vec_body(a, splits, tile, gq); } -// Merge. PF16=1 reads normalised f16 partials and folds l into the weight; PF16=0 is the plain -// path (unnormalised f32 partials, l summed separately). Both walk the segments in FIXED INDEX -// ORDER so a request's rounding never depends on CTA scheduling. +// Merge. PF16=1 reads normalised f16 partials and folds l into the weight; PF16=0 reads +// unnormalised f32 partials with l summed separately. Both walk segments in fixed index order so +// rounding never depends on workgroup scheduling. template __device__ __forceinline__ void splitkv_combine_body(const R4DArgs& a, int splits, int tile, const R4DGateQuant& gq) @@ -755,9 +694,9 @@ void splitkv_combine_body(const R4DArgs& a, int splits, int tile, const R4DGateQ const int seq = r4d_q_seq(a.cu_q, a.num_seqs, a.q_len, tok); const int ctx = a.seqused_k[seq]; - /* One thread a column, so a 128-column scale group is four waves: each takes its own absmax - * and the group's is the max over its four, through `red` -- whose last read, the total's, - * is behind a barrier before the merge loop, and which a padded slot never used. */ + /* One thread per column, so a 128-column scale group is four waves, combined through `red`. + * Reusing `red` is safe: its last read (the total) is behind a barrier before the merge loop, + * and a padded slot never used it. */ auto finish = [&](uint16_t ob) { uint16_t* op = (uint16_t*)a.out + (size_t)job * HEAD_DIM + d; if constexpr (!GQ) { @@ -787,12 +726,11 @@ void splitkv_combine_body(const R4DArgs& a, int splits, int tile, const R4DGateQ } }; - // A padded batch slot has no context at all. Its output is discarded by the caller, but the - // segment count below would divide by zero, so leave zeros and stop. `ctx` is block-uniform, - // so every thread takes this branch together and the barriers further down stay matched. + // A padded slot (ctx 0) would divide by zero below; write zeros and stop. ctx is + // block-uniform, so the barriers below stay matched. if (ctx <= 0) { finish(0); return; } - // Segment count, derived the same way the decode kernel derived it -- including the - // window's tile floor, or the merge would read partials no segment ever wrote. + // Segment count, derived exactly as in the decode kernel, including the window's tile floor; + // otherwise the merge would read partials no segment wrote. const int nef = r4d_attn_tiles(ctx, tile) - (WIN ? r4d_attn_wlo(ctx, r4d_q_len(a.cu_q, seq, a.q_len), 0, a.window) / tile : 0); const int tp_ = (nef + splits - 1) / splits; @@ -874,3 +812,94 @@ void r4d_attn_splitkv_combine_gq_kernel(const R4DArgs a, int splits, int tile, { splitkv_combine_body(a, splits, tile, gq); } + +// ---- host helpers shared by the paged decode dispatches ----------------------------------------- + +// Split law of the full-attention legs (h256/gqa6 and the gqa8 family): as many workgroups as fit +// under 128 (grid = splits * kv_heads * num_seqs), at least two tiles per segment. It does not +// depend on gqa or head_dim. +// +// floor(128 / units), not a power of two: a power of two leaves 96-112 workgroups at 3, 5, 6 and +// 7 requests, and floor is 2-20% faster there. Staying under a multiple of 64 matters (at five +// requests, 13 splits = 130 workgroups is three rounds of 64 and slower than 12). +// +// Fewer splits mainly save partial-buffer traffic (seqs x q_len x q_heads x splits rows of +// 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. +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 cap = tiles / 2; + if (s > cap) s = cap; + if (s > tiles) s = tiles; + if (s < 1) s = 1; + return s; +} + +// Split law of the windowed legs (the DFlash2 drafter at h128/gqa4, Gemma 4 at h256/gqa2): target +// 192 workgroups, round down to a power of two (min 16), keep at least two tiles per segment, then +// step up off splits * units == 256, a slow spot for these geometries. The tile count comes from +// the window when one is set, since that is the span the kernel walks. +static inline int r4d_decode_splits_win(const R4DArgs* a, int tile) { + if (a->splits > 0) return a->splits; + const int span = (a->window > 0 && a->window + a->q_len < a->max_ctx) + ? a->window + a->q_len : a->max_ctx; + const int tiles = (span + tile - 1) / tile; + const int units = std::max(1, a->kv_heads * a->num_seqs); + const int raw = 192 / units; + int s = 128; + while (s > 16 && s > raw) s >>= 1; + const int cap = tiles / 2; + while (s > 16 && s > cap) s >>= 1; + if (s > tiles) s = tiles; + if (s < 1) s = 1; + if (s * units == 256 && s * 2 <= tiles) s <<= 1; + return s; +} + +// Bytes of split-KV partials one decode launch needs, the same for both cache dtypes: f16 O/l plus +// m and l under O_PF16, else f32 O plus m and l. +static inline long r4d_decode_scratch(const R4DArgs* a, int splits, int opt) { + const long rows = (long)r4d_q_total(*a) * a->q_heads; + return (opt & O_PF16) ? rows * splits * (long)(a->head_dim * 2 + 8) + : rows * splits * (long)(a->head_dim + 2) * 4L; +} + +// The windowed legs' decode (WIN = 1): the attention kernel at the gqa-aligned height, then the +// merge, one wave per row when there are enough rows and the segment count fits a wave, else the +// LDS-tree form; both give identical bytes. Tile 16, paged block 16, at most 64 query rows, and +// the full-attention legs' merge constants (two rows a block, the wave form from 256 rows). +// Returns 0, a negative code for a shape it does not serve, or -100 - hipError_t. +template +static int r4d_decode_launch_win(const R4DArgs* a, hipStream_t s) { + constexpr int TILE = 16, BS = 16, JPB = 2, VECMIN = 256, PF16 = (OPT & O_PF16) ? 1 : 0; + if (a->head_dim != HEAD_DIM || a->block_size != BS) return -1; + if (a->q_heads / a->kv_heads != GQA) return -2; + const int rows = a->q_len * GQA; + if (rows > 64) return -4; + const int nw = (rows + 15) / 16; + const int splits = r4d_decode_splits_win(a, TILE); +#define R4D_WIN_LAUNCH(NW) \ + hipLaunchKernelGGL((r4d_attn_decode_kernel), \ + dim3(splits, a->kv_heads, a->num_seqs), dim3(NW * 32), 0, s, *a, splits) + if (nw == 1) R4D_WIN_LAUNCH(1); + else if (nw == 2) R4D_WIN_LAUNCH(2); + else if (nw == 3) R4D_WIN_LAUNCH(3); + else R4D_WIN_LAUNCH(4); +#undef R4D_WIN_LAUNCH + hipError_t e = hipGetLastError(); + if (e != hipSuccess) return -100 - (int)e; + + const int jobs3 = r4d_q_total(*a) * a->q_heads; + if (splits <= 64 && jobs3 >= VECMIN) + hipLaunchKernelGGL((r4d_attn_splitkv_combine_vec_kernel), + dim3((jobs3 + JPB - 1) / JPB), dim3(32 * JPB), 0, s, *a, splits, TILE); + else + hipLaunchKernelGGL((r4d_attn_splitkv_combine_kernel), dim3(jobs3), + dim3(HEAD_DIM), splits * sizeof(float), s, *a, splits, TILE); + e = hipGetLastError(); + return e == hipSuccess ? 0 : -100 - (int)e; +} diff --git a/libr4d/r4d_attn_dense_bf16.hip b/libr4d/r4d_attn_dense_bf16.hip index f5431ccc..bdc0a1cb 100644 --- a/libr4d/r4d_attn_dense_bf16.hip +++ b/libr4d/r4d_attn_dense_bf16.hip @@ -2,25 +2,26 @@ // with an optional two-sided window |i - j| < window. bf16 in and out, f16 operands, f32 // accumulate. Head widths 64, 256 and 512 are compiled; each (head_dim, gqa) pair is a row. // -// The core is the vision kernel's (r4d_attn_vit_h72_bf16.hip): S^T = K.Q^T, so the wave32 -// column-distributed accumulator gives each lane one query row, the softmax state is lane-private, -// and the C fragment of S^T is already the B fragment the PV matmul wants -- P never goes through -// LDS. What this file adds: +// Core from the vision kernel (r4d_attn_vit_h72_bf16.hip): S^T = K.Q^T, so the wave32 +// column-distributed accumulator gives each lane one query row, softmax state is lane-private, and +// the C fragment of S^T is already the B fragment of P.V, so P never goes through LDS. Additions: // -// GQA IN THE WORKGROUP. A workgroup owns one KV head and every query head that reads it, so a -// staged K/V tile is consumed by GQA times as many WMMAs as one head would give it. The grid is -// (query blocks, kv heads, segments). +// GQA in the workgroup: a workgroup owns one KV head and all query heads reading it, so each +// staged K/V tile feeds GQA times as many WMMAs. Grid is (query blocks, kv heads, segments). // -// A WINDOW. A workgroup's key range is cut to the keys any of its queries can see, and the -// per-element test runs only on tiles that straddle a window edge or the segment's end; an -// interior tile pays nothing. Sliding layers at |i - j| <= 512 then cost O(T * window), not -// O(T^2). +// Window: the key range is cut to keys any of the workgroup's queries can see, and the +// per-element mask runs only on tiles straddling a window edge or the segment end. Sliding +// layers cost O(T * window), not O(T^2). // -// A HEAD SPLIT ACROSS WAVES (DSPLIT). One lane's output is head_dim / 2 floats, so head_dim 512 -// would need 256 accumulator VGPRs before the query fragments -- more than a lane has. At -// DSPLIT 2 two waves own the same 16 queries and half the head each: each contracts its half -// of q.k, the two partial scores are summed through LDS, both run the same softmax (a + b == -// b + a, so the two copies agree to the bit), and each accumulates its half of P.V. +// Blocks: `block` cuts a segment into blocks of that many rows from its start, each attending +// only within itself (a chunked audio encoder's windows). The key range is cut to the blocks +// the workgroup's queries are in, and the per-element test runs only where a workgroup or a +// tile straddles a block edge. `cu_div` reads cu_seqlens in units that many rows apart. +// +// Head split across waves (DSPLIT): a lane's output is head_dim / 2 floats, so head_dim 512 +// would need 256 accumulator VGPRs. At DSPLIT 2 two waves share 16 queries and each owns half +// the head: partial q.k scores are summed through LDS, both run the same softmax (a + b == b + a, +// so both copies agree bit for bit), and each accumulates its half of P.V. // // Every operand is read at its own token pitch, so q, k and v may be column slices of one fused // projection; pitches and head offsets must be multiples of 8 elements for the 16-byte fetches. @@ -35,8 +36,8 @@ template __global__ __launch_bounds__(NQB * GQA * DSPLIT * 32) void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk, const uint16_t* __restrict__ gv, uint16_t* __restrict__ go, - const int* __restrict__ cu, float scale, int window, - int q_ld, int k_ld, int v_ld, int o_ld) + const int* __restrict__ cu, float scale, int window, int block, + int cdiv, int q_ld, int k_ld, int v_ld, int o_ld) { typedef DT16<1> D; typedef D::frag frag16; @@ -73,7 +74,7 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re const int kvh = blockIdx.y, seq = blockIdx.z; const int hq = kvh * GQA + g; - const int s0 = cu[seq], slen = cu[seq + 1] - s0; + const int s0 = cu[seq] / cdiv, slen = cu[seq + 1] / cdiv - s0; const int q0 = blockIdx.x * BQ; if (slen <= 0 || q0 >= slen) return; const int qlast = min(q0 + BQ, slen) - 1; @@ -84,6 +85,13 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re kb = max(0, q0 - (window - 1)); ke = min(slen, qlast + window); } + const bool blocks = block > 0; + if (blocks) { + kb = max(kb, q0 / block * block); + ke = min(ke, (qlast / block + 1) * block); + } + // A workgroup whose queries are all in one block masks only the tiles crossing its edges. + const bool q_straddle = blocks && q0 / block != qlast / block; const float mul = scale * 1.44269504089f; const int qpos = q0 + qbi * 16 + c; @@ -117,11 +125,13 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re const int ntiles = (ke - kb + TILE - 1) / TILE; for (int ti = 0; ti < ntiles; ++ti) { const int k0 = kb + ti * TILE; - // Whether any (query, key) pair of this tile is outside the window or past the keys: - // uniform over the workgroup, so the interior tiles skip the test entirely. + // Whether any (query, key) pair of this tile is outside the window or past the keys. + // Workgroup-uniform, so interior tiles skip the test. const bool mask = (k0 + TILE > ke) || (window > 0 && (k0 < qlast - (window - 1) || - k0 + TILE - 1 > q0 + (window - 1))); + k0 + TILE - 1 > q0 + (window - 1))) || + (blocks && (q_straddle || k0 / block != (k0 + TILE - 1) / block || + k0 / block != q0 / block)); uint4 kr[KP], vr[VP]; #pragma unroll @@ -133,8 +143,8 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re kr[p] = *(const uint4*)(kbase + (long)(s0 + kk) * k_ld + gg * 8); } } - // V transposed on the way in: the eight lanes of a group name eight key rows at the same - // eight dims, and global_load_tr_b128 hands lane j dim d0+j across all eight. + // V transposed on load: a group's eight lanes name eight key rows at the same eight dims, + // and global_load_tr_b128 gives lane j dim d0+j across all eight. #pragma unroll for (int r = 0; r < VP; ++r) { const int u = lgi + r * LGRP; @@ -213,13 +223,14 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re for (int e = 0; e < 8; ++e) { const int key = kq + e; const int d = qpos - key; - const bool ok = key < ke && (window <= 0 || (d < window && -d < window)); + const bool ok = key < ke && (window <= 0 || (d < window && -d < window)) && + (!blocks || key / block == qpos / block); sc[e] = ok ? sc[e] : -INFINITY; } } - // The softmax against a reference max, rescaled only when the row max outgrows what - // the f16 P can hold (r4d_dt16.h). + // Softmax against a reference max, rescaled only when the row max outgrows the f16 + // P range (r4d_dt16.h). float smax = sc[0]; #pragma unroll for (int e = 1; e < 8; ++e) smax = fmaxf(smax, sc[e]); @@ -240,7 +251,7 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re #pragma unroll for (int e = 0; e < 8; e += 2) pw[e >> 1] = D::pk(ex2(sc[e] + soff), ex2(sc[e + 1] + soff)); - // The row sum off the packed P, so the denominator is the values P.V used. + // Row sum from the packed P, so the denominator matches the values P.V used. const v2hf one = {(__fp16)1.0f, (__fp16)1.0f}; #pragma unroll for (int e = 0; e < 4; ++e) @@ -290,46 +301,47 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re template static int r4d_attn_dense_launch(const void* q, const void* k, const void* v, void* o, const void* cu, int num_seqs, int max_seqlen, int n_head_kv, - float scale, int window, int q_ld, int k_ld, int v_ld, int o_ld, - hipStream_t s) + float scale, int window, int block, int cdiv, int q_ld, int k_ld, + int v_ld, int o_ld, hipStream_t s) { constexpr int BQ = NQB * 16; dim3 grid((max_seqlen + BQ - 1) / BQ, n_head_kv, num_seqs); hipLaunchKernelGGL((r4d_attn_dense_kernel), grid, dim3(NQB * GQA * DSPLIT * 32), 0, s, (const uint16_t*)q, (const uint16_t*)k, - (const uint16_t*)v, (uint16_t*)o, (const int*)cu, scale, window, q_ld, - k_ld, v_ld, o_ld); + (const uint16_t*)v, (uint16_t*)o, (const int*)cu, scale, window, block, + cdiv, q_ld, k_ld, v_ld, o_ld); const hipError_t e = hipGetLastError(); return e == hipSuccess ? 0 : -100 - (int)e; } // q, o: [tokens, n_head * head_dim]; k, v: [tokens, n_head_kv * head_dim], each at its own token // pitch in elements. cu_seqlens is [num_seqs + 1] int32 on the device; max_seqlen is a host-side -// bound on the segment lengths and sizes the grid. window 0 is the whole segment. +// bound on the segment lengths, in rows, and sizes the grid. window 0 is the whole segment, block +// 0 no blocks; cu_seqlens counts in units cdiv rows apart. extern "C" int r4d_attn_dense_bf16(const void* q, const void* k, const void* v, void* o, const void* cu_seqlens, int num_seqs, int max_seqlen, int n_head, int n_head_kv, int head_dim, float scale, - int window, int q_ld, int k_ld, int v_ld, int o_ld, - void* stream) + int window, int block, int cdiv, int q_ld, int k_ld, int v_ld, + int o_ld, void* stream) { if (n_head <= 0 || n_head_kv <= 0 || n_head % n_head_kv) return -2; if ((q_ld | k_ld | v_ld | o_ld) & 7) return -3; - if (window < 0) return -4; + if (window < 0 || block < 0 || cdiv <= 0) return -4; if (num_seqs <= 0 || max_seqlen <= 0) return 0; const int gqa = n_head / n_head_kv; hipStream_t s = (hipStream_t)stream; if (head_dim == 64 && gqa == 1) return r4d_attn_dense_launch<64, 1, 8, 1, 64>(q, k, v, o, cu_seqlens, num_seqs, max_seqlen, - n_head_kv, scale, window, q_ld, k_ld, v_ld, - o_ld, s); + n_head_kv, scale, window, block, cdiv, q_ld, + k_ld, v_ld, o_ld, s); if (head_dim == 256 && gqa == 2) return r4d_attn_dense_launch<256, 2, 8, 1, 32>(q, k, v, o, cu_seqlens, num_seqs, - max_seqlen, n_head_kv, scale, window, q_ld, - k_ld, v_ld, o_ld, s); + max_seqlen, n_head_kv, scale, window, block, + cdiv, q_ld, k_ld, v_ld, o_ld, s); if (head_dim == 512 && gqa == 4) return r4d_attn_dense_launch<512, 4, 2, 2, 16>(q, k, v, o, cu_seqlens, num_seqs, - max_seqlen, n_head_kv, scale, window, q_ld, - k_ld, v_ld, o_ld, s); + max_seqlen, n_head_kv, scale, window, block, + cdiv, q_ld, k_ld, v_ld, o_ld, s); return -1; } @@ -351,34 +363,31 @@ extern "C" int r4d_rad_attn_dense(const RadArgs* a, RadStream s) { const long long gqa = r4d_geti_or(a, "gqa", 1); if (head_dim <= 0 || gqa <= 0) return R4D_NO(RAD_E_SHAPE); /* [tokens, heads * head_dim] (or [tokens, heads, head_dim]) at the operand's own row pitch. */ - auto rows = [&](const RadTensor* t, long long* n_tok, long long* n_head, long long* ld) { - long long width = 1; - for (uint32_t i = 1; i < t->rank; ++i) width *= t->shape[i]; - if (t->rank < 2 || width % head_dim) return false; - *n_head = width / head_dim; - *ld = r4d_rows_pitch(t, width, n_tok); - return *ld >= 0; - }; long long total = 0, nh = 0, q_ld = 0; long long tk = 0, hk = 0, k_ld = 0, tv = 0, hv = 0, v_ld = 0, to = 0, ho = 0, o_ld = 0; - if (!rows(q, &total, &nh, &q_ld) || !rows(k, &tk, &hk, &k_ld) || - !rows(v, &tv, &hv, &v_ld) || !rows(o, &to, &ho, &o_ld)) + if (!r4d_head_rows(q, head_dim, &total, &nh, &q_ld) || + !r4d_head_rows(k, head_dim, &tk, &hk, &k_ld) || + !r4d_head_rows(v, head_dim, &tv, &hv, &v_ld) || + !r4d_head_rows(o, head_dim, &to, &ho, &o_ld)) return R4D_NO(RAD_E_STRIDE); if (hk != hv || ho != nh || hk * gqa != nh) return R4D_NO(RAD_E_SHAPE); if (tk < total || tv < total || to < total) return R4D_NO(RAD_E_SHAPE); if (cu->rank != 1 || cu->shape[0] < 2) return R4D_NO(RAD_E_SHAPE); const int num_seqs = (int)(cu->shape[0] - 1); - /* max_seqlen sizes the grid and is a bound, not a length: the kernel reads the device-side - * cu_seqlens. Absent, the total token count is a valid bound. */ + /* max_seqlen is a grid-sizing bound (the kernel reads device-side cu_seqlens); defaults to + * the total token count. */ long long msl = r4d_geti_or(a, "max_seqlen", 0); if (msl <= 0 || msl > total) msl = total; const float scale = (float)r4d_getf(a, "scale", 1.0 / std::sqrt((double)head_dim)); const long long window = r4d_geti_or(a, "window", 0); + const long long block = r4d_geti_or(a, "block", 0); + const long long cdiv = r4d_geti_or(a, "cu_div", 1); const int e = r4d_attn_dense_bf16(q->data, k->data, v->data, o->data, cu->data, num_seqs, (int)msl, (int)nh, (int)hk, (int)head_dim, scale, - (int)window, (int)q_ld, (int)k_ld, (int)v_ld, (int)o_ld, s); - if (e == -1) return R4D_NO(RAD_E_SHAPE); - return e == 0 ? RAD_OK : R4D_NO(e == -3 ? RAD_E_STRIDE : RAD_E_DEVICE); + (int)window, (int)block, (int)cdiv, (int)q_ld, (int)k_ld, + (int)v_ld, (int)o_ld, s); + if (e == 0) return RAD_OK; + return R4D_NO(e == -3 ? RAD_E_STRIDE : e <= -100 ? RAD_E_DEVICE : RAD_E_SHAPE); } diff --git a/libr4d/r4d_attn_gen.hip b/libr4d/r4d_attn_gen.hip index 9d746093..a689224e 100644 --- a/libr4d/r4d_attn_gen.hip +++ b/libr4d/r4d_attn_gen.hip @@ -1,33 +1,27 @@ // R4D attention over a paged prefix and the pass's own rows (attn_prefix_self), and the causal // dense attention a text encoder's prompt pass needs (attn_dense, causal 1, head_dim 128). // -// THE KERNEL IS THE DENSE ONE (r4d_attn_dense_bf16.hip) WITH A SECOND KEY SOURCE. S^T = K.Q^T, so a -// lane owns one query row and its softmax state, the C fragment of S^T is the B fragment the P.V -// matmul wants, and P never goes through LDS. A workgroup owns one KV head and every query head -// that reads it. What is new: +// The dense kernel (r4d_attn_dense_bf16.hip) with a second key source. S^T = K.Q^T, so a lane +// owns one query row and its softmax state, the C fragment of S^T is the B fragment of P.V, and P +// never goes through LDS. A workgroup owns one KV head and every query head reading it. // -// THE PREFIX. A sequence's first `used[s]` keys are in the paged cache -- [blocks, kv_heads, 16, -// 2 * HD], K then V in a slot -- and its own rows' keys are dense, beside the queries. The key -// loop walks the prefix tiles first and then the own tiles; a tile is one source or the other, -// and its rows are fetched through that source's address rule. Every prefix key is visible. +// Prefix: a sequence's first `used[s]` keys are in the paged cache ([blocks, kv_heads, 16, +// 2 * HD], K then V per slot); its own rows' keys are dense beside the queries. Prefix tiles are +// walked first, then own tiles; each tile has one source. Every prefix key is visible. // -// CAUSAL OWN KEYS. With `causal` a query sees its own rows up to itself: a text segment of a -// conditioning sequence, and the text encoder's prompt. A tile wholly below every query of the -// workgroup pays no test. +// Causal own keys: with `causal` a query sees its own rows up to itself (a conditioning +// sequence's text segment, a text encoder's prompt). Tiles wholly below every query skip the mask. // -// bf16 operands (DT16<0>): a diffusion transformer's values carry outliers an f16 operand could -// overflow, and the reference takes P to bf16 for its P.V product too (rounded there, truncated -// here -- see the softmax). +// bf16 operands (DT16<0>): diffusion transformer values carry outliers that could overflow f16, +// and the reference also takes P to bf16 for P.V (rounded there, truncated here; see the softmax). // -// THE INT8 Q.K FORM (`I8`, the op's `k_i8` operand present). The score product runs on -// v_wmma_i32_16x16x16_iu8, which issues in half the cycles of the bf16 one; P.V stays bf16. Every -// code is quant_act_i8g's: a scale per (row, head) of amax / 127 (1 for an all-zero row) and a code -// rint(x * (1 / scale)) clamped to +-127. The own rows' keys arrive quantised that way (k_i8 and -// k_scale, one op ahead of this one), the query is quantised here once a workgroup, and a prefix -// tile is quantised as it is staged -- the prefix is a picture's conditioning, a few hundred rows -// against the thousands of own rows. A score is (q . k) * qs * ks, the integer dot product exact. -// At a DiT's 16384 rows this takes the kernel from 38 to about 32 ms; against the bf16 form the -// picture moves by less than swapping between exact attention implementations moves it. +// Int8 Q.K form (`I8`, op operand `k_i8` present): scores run on v_wmma_i32_16x16x16_iu8 (half the +// cycles of bf16); P.V stays bf16. Codes follow quant_act_i8g: per (row, head) scale amax / 127 +// (1 for an all-zero row), code rint(x / scale) clamped to +-127. Own keys arrive quantised +// (k_i8, k_scale, from the preceding op); the query is quantised here once per workgroup, and +// prefix tiles (a few hundred conditioning rows) as they are staged. A score is (q . k) * qs * ks +// with an exact integer dot product. At a DiT's 16384 rows this is ~38 -> ~32 ms, with image +// error below the spread between exact attention implementations. #include "r4d.h" #include "r4d_args.h" #include "r4d_common.h" @@ -39,7 +33,7 @@ typedef int v2i_ps __attribute__((ext_vector_type(2))); typedef int v8i_ps __attribute__((ext_vector_type(8))); -/* quant_act_i8g's scale and codes for eight values against `inv` = 1 / scale. */ +/* quant_act_i8g codes for four values against `inv` = 1 / scale, packed into one dword. */ __device__ __forceinline__ uint32_t ps_q8x4(float a, float b, float c, float d, float inv) { auto q = [inv](float x) { return (uint32_t)((int)rintf(fminf(fmaxf(x * inv, -127.0f), 127.0f)) & 0xff); @@ -91,10 +85,9 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr constexpr float GROW = D::GROW; constexpr int BS = 16; // the paged block, libr4d's (block_size == 16) static_assert(HD % 16 == 0 && TILE % 16 == 0, "geometry"); - // THE INT8 KEY TILE: a key's row is HD bytes, padded by 8 so the sixteen rows a fragment read - // touches land on distinct bank pairs (34 dwords a row), and written as 8-byte halves because - // the padding leaves odd rows 8-byte aligned. A prefix tile's key is DG lanes of 8 dims each, - // which is why those lanes must sit in one half-wave for the row's absolute maximum. + // Int8 key tile: HD bytes per row padded by 8 (34 dwords), so a fragment read's sixteen rows + // hit distinct bank pairs; written as 8-byte halves since odd rows are only 8-byte aligned. + // A prefix key spans DG lanes of 8 dims, which must sit in one half-wave for the row absmax. constexpr int KSTR8 = HD + 8; constexpr int K8G = HD / 16; // 16-byte pieces of an own key's row constexpr int K8P = (TILE * K8G + NTHR - 1) / NTHR; @@ -112,9 +105,9 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr const int kvh = blockIdx.y; const int hq = kvh * GQA + g; - // THE GRID IS FLAT OVER THE SEQUENCES' QUERY BLOCKS: block b is the b-th BQ-row block counting - // through every sequence in order, so a pass of many equal sequences launches what it needs - // rather than (longest sequence) x (sequences). A handful of sequences, so a walk. + // Flat grid over all sequences' query blocks: block b is the b-th BQ-row block counting through + // the sequences in order, instead of (longest sequence) x (sequences). Few sequences, so a + // linear walk. int seq = -1, q0 = 0; for (int s = 0, b = blockIdx.x; s < num_seqs; ++s) { const int nb = (cu[s + 1] - cu[s] + BQ - 1) / BQ; @@ -132,9 +125,9 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr const int qpos = q0 + qbi * 16 + c; const bool live = qpos < slen; - // The query: bf16 fragments pre-multiplied by the softmax scale, or int8 codes against its - // row's absolute maximum -- a lane holds half the head's dims, the lane 16 away the other half - // -- with the scale carried in `qs` and applied to the integer score. + // The query: bf16 fragments pre-multiplied by the softmax scale, or int8 codes against the + // row absmax (a lane holds half the head's dims, lane + 16 the other half) with the scale in + // `qs`, applied to the integer score. qfrag qf[NKS]; float qs = mul; { @@ -199,8 +192,8 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr const int klim = pre ? P : ke; const bool mask = (k0 + TILE > klim) || (!pre && causal && k0 + TILE - 1 > q0); - // An own tile in the int8 form is K8P 16-byte pieces a thread and a scale for the first - // TILE threads; anything else is the bf16 rows (a prefix tile quantised below). + // An int8 own tile is K8P 16-byte pieces per thread plus a scale from each of the first + // TILE threads; otherwise bf16 rows (an int8 prefix tile is quantised below). const bool own8 = I8 && !pre; uint4 kr[KP], vr[VP]; float ksr = 0.0f; @@ -239,8 +232,8 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr vr[r] = __builtin_bit_cast(uint4, load_tr_b128(vrow(pre, kk) + dg * 8)); } } - // A prefix key in the int8 form: its row's maximum across the DG lanes that hold it (one - // half-wave, so a DPP butterfly), then its eight codes a lane. + // Int8 prefix key: row absmax over its DG lanes (one half-wave, DPP butterfly), then eight + // codes per lane. uint2 kq[KP]; float kqs[KP]; if (I8 && pre) { @@ -299,8 +292,8 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr #pragma unroll 1 for (int mt = 0; mt < MT; ++mt) { - // The scores of 16 keys, in log2 units once times `qs` (a no-op 1 for bf16, whose - // query carries the scale already). + // Scores of 16 keys, in log2 units once multiplied by `qs` (int8 only; the bf16 query + // already carries the scale). float sc[8]; if constexpr (I8) { v8i_ps si = (v8i_ps){0, 0, 0, 0, 0, 0, 0, 0}; @@ -356,7 +349,7 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr } } - // `qs` is positive, so the maximum of the scaled scores is the scaled maximum. + // qs > 0, so the max of the scaled scores is the scaled max. float smax = sc[0]; #pragma unroll for (int e = 1; e < 8; ++e) smax = fmaxf(smax, sc[e]); @@ -374,10 +367,10 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr soff = -mnew; } - // P TO BF16 BY TRUNCATION: one v_perm a pair where gfx1201's software round-to-nearest - // is about six VALU a value, on a path where the WMMA and the VALU share the SIMD - // (4-7% of the kernel at a DiT's 16384 rows). Its error is the rounding's in size, and - // its downward bias cancels: the row sum below is taken off the same truncated values. + // P to bf16 by truncation: one v_perm per pair, where gfx1201's software + // round-to-nearest costs ~6 VALU per value on a SIMD shared with the WMMA (4-7% of the + // kernel at 16384 rows). The downward bias cancels because the row sum below uses the + // same truncated values. uint32_t pw[4]; #pragma unroll for (int e = 0; e < 8; e += 2) { @@ -387,7 +380,7 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr const uint32_t hi = __builtin_bit_cast(uint32_t, ex2(a1)); pw[e >> 1] = __builtin_amdgcn_perm(hi, lo, 0x07060302u); } - // The row sum off the packed P, so the denominator is the values P.V used. + // Row sum from the packed P, so the denominator matches the values P.V used. #pragma unroll for (int e = 0; e < 4; ++e) l_i += __builtin_bit_cast(float, pw[e] << 16) + @@ -438,7 +431,7 @@ static int r4d_attn_ps_launch(const void* q, const void* k, const void* k8, cons hipStream_t s) { constexpr int BQ = NQB * 16; - // Every sequence's blocks: at most total / BQ, plus one partial block a sequence. + // At most total / BQ full blocks plus one partial block per sequence. dim3 grid((max_q + BQ - 1) / BQ + num_seqs, n_head_kv, 1); hipLaunchKernelGGL((r4d_attn_ps_kernel), grid, dim3(NQB * GQA * 32), 0, s, (const uint16_t*)q, (const uint16_t*)k, (const int8_t*)k8, ks, @@ -449,10 +442,10 @@ static int r4d_attn_ps_launch(const void* q, const void* k, const void* k8, cons return e == hipSuccess ? 0 : -100 - (int)e; } -/* head_dim 128 at gqa 1, 2, 4 and 8. `used`/`bt`/`kvc` null is no prefix: the dense form. `max_q` - * is the query rows of every sequence together, which bounds the flat grid. `k8` non-null is the - * int8 Q.K form -- the own keys as int8 codes (`k8_ld` bytes a row) with a scale per (row, head) - * in `ks` (`ks_ld` floats a row) -- at gqa 1, the only ratio a DiT has. */ +/* head_dim 128 at gqa 1, 2, 4 and 8. Null `used`/`bt`/`kvc` means no prefix (the dense form). + * `max_q` is the total query rows over all sequences and bounds the flat grid. Non-null `k8` + * selects the int8 Q.K form (own-key codes, `k8_ld` bytes per row; a scale per (row, head) in + * `ks`, `ks_ld` floats per row), gqa 1 only. */ static int r4d_attn_ps(const void* q, const void* k, const void* k8, const float* ks, const void* v, void* o, const int* cu, const int* used, const int* bt, int bt_pitch, const void* kvc, @@ -470,9 +463,9 @@ static int r4d_attn_ps(const void* q, const void* k, const void* k8, const float return r4d_attn_ps_launch<128, G, NQB, T, I8>(q, k, k8, ks, v, o, cu, used, bt, bt_pitch, kvc, \ num_seqs, max_q, n_head_kv, scale, causal, \ q_ld, k_ld, k8_ld, ks_ld, v_ld, o_ld, s) - /* SIXTEEN QUERY TILES A WORKGROUP at gqa 1: a workgroup streams its head's whole K and V once, - * so the rows it serves divide that traffic. At a DiT's 16384 rows a head's K and V are 8 MB - * and fall out of L2; 128 rows a workgroup ran at 66 TFLOP/s, 256 at 111, 512 at 102. */ + /* Sixteen query tiles per workgroup at gqa 1: a workgroup streams its head's whole K and V + * once, so more rows per workgroup divide that traffic. At 16384 rows a head's K/V (8 MB) do + * not fit L2; 128 rows per workgroup gave 66 TFLOP/s, 256 gave 111, 512 gave 102. */ if (k8) { if (gqa != 1) return -1; R4D_PS(1, 16, 64, true); @@ -488,17 +481,6 @@ static int r4d_attn_ps(const void* q, const void* k, const void* k8, const float } // ============================================================== the plugin ABI entry points -/* [tokens, heads * head_dim] (or rank 3) at the operand's own row pitch. */ -static bool ps_rows(const RadTensor* t, long long head_dim, long long* n_tok, long long* n_head, - long long* ld) { - long long width = 1; - for (uint32_t i = 1; i < t->rank; ++i) width *= t->shape[i]; - if (t->rank < 2 || width % head_dim) return false; - *n_head = width / head_dim; - *ld = r4d_rows_pitch(t, width, n_tok); - return *ld >= 0; -} - enum { PS_Q = 0, PS_K, PS_V, PS_KV, PS_BT, PS_USED, PS_CU, PS_KDES, PS_VDES, PS_K8, PS_KS, PS_OUT }; @@ -523,16 +505,18 @@ extern "C" int r4d_rad_attn_prefix_self(const RadArgs* a, RadStream s) { if (r4d_numel(su) < num_seqs) return R4D_NO(RAD_E_SHAPE); long long total = 0, nh = 0, q_ld = 0, tk = 0, hk = 0, k_ld = 0, tv = 0, hv = 0, v_ld = 0; long long to = 0, ho = 0, o_ld = 0; - if (!ps_rows(q, hd, &total, &nh, &q_ld) || !ps_rows(k, hd, &tk, &hk, &k_ld) || - !ps_rows(v, hd, &tv, &hv, &v_ld) || !ps_rows(o, hd, &to, &ho, &o_ld)) + if (!r4d_head_rows(q, hd, &total, &nh, &q_ld) || + !r4d_head_rows(k, hd, &tk, &hk, &k_ld) || + !r4d_head_rows(v, hd, &tv, &hv, &v_ld) || + !r4d_head_rows(o, hd, &to, &ho, &o_ld)) return R4D_NO(RAD_E_STRIDE); if (hk != hv || ho != nh || hk * gqa != nh || hk != kv->shape[1]) return R4D_NO(RAD_E_SHAPE); if (tk < total || tv < total || to < total) return R4D_NO(RAD_E_SHAPE); const long long bt_pitch = bt->rank >= 2 ? bt->shape[1] : r4d_numel(bt) / num_seqs; if (bt->rank >= 2 && bt->stride[1] != 1) return R4D_NO(RAD_E_STRIDE); const long long mq = total; - /* THE INT8 Q.K FORM (`qk` "i8"): the own keys' codes [tokens, kv_heads * head_dim] and their - * scales [tokens, kv_heads], as quant_act_i8g writes them at group head_dim. */ + /* Int8 Q.K form (`qk` "i8"): own-key codes [tokens, kv_heads * head_dim] and scales + * [tokens, kv_heads], as quant_act_i8g writes them at group head_dim. */ const RadTensor* k8 = r4d_opt(a, PS_K8); const RadTensor* ks = r4d_opt(a, PS_KS); const char* qk = r4d_gets(a, "qk"); @@ -543,7 +527,7 @@ extern "C" int r4d_rad_attn_prefix_self(const RadArgs* a, RadStream s) { if (k8) { if (k8->dtype != RAD_I8 || ks->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); long long t8 = 0, h8 = 0, ts = 0; - if (!ps_rows(k8, hd, &t8, &h8, &k8_ld)) return R4D_NO(RAD_E_STRIDE); + if (!r4d_head_rows(k8, hd, &t8, &h8, &k8_ld)) return R4D_NO(RAD_E_STRIDE); ks_ld = r4d_rows_pitch(ks, hk, &ts); if (ks_ld < 0) return R4D_NO(RAD_E_STRIDE); if (h8 != hk || t8 < total || ts < total) return R4D_NO(RAD_E_SHAPE); @@ -556,7 +540,8 @@ extern "C" int r4d_rad_attn_prefix_self(const RadArgs* a, RadStream s) { scale, (int)r4d_geti_or(a, "causal", 0), (int)q_ld, (int)k_ld, (int)k8_ld, (int)ks_ld, (int)v_ld, (int)o_ld, (hipStream_t)s); if (e == -1 || e == -2) return R4D_NO(RAD_E_SHAPE); - return e == 0 ? RAD_OK : R4D_NO(e == -3 ? RAD_E_STRIDE : RAD_E_DEVICE); + if (e == 0) return RAD_OK; + return R4D_NO(e == -3 ? RAD_E_STRIDE : e <= -100 ? RAD_E_DEVICE : RAD_E_SHAPE); } /* attn_dense at head_dim 128, causal or not: the same kernel with no prefix. */ @@ -570,11 +555,16 @@ extern "C" int r4d_rad_attn_dense_h128(const RadArgs* a, RadStream s) { if (!r4d_contig(cu) || cu->rank != 1 || cu->shape[0] < 2) return R4D_NO(RAD_E_SHAPE); const long long hd = r4d_geti_or(a, "head_dim", 0), gqa = r4d_geti_or(a, "gqa", 1); if (hd != 128 || gqa <= 0) return R4D_NO(RAD_E_SHAPE); - if (r4d_geti_or(a, "window", 0) != 0) return R4D_NO(RAD_E_UNSUPPORTED); + /* Every key of a segment, its bounds read as they stand: no window, blocks or cu_div. */ + if (r4d_geti_or(a, "window", 0) != 0 || r4d_geti_or(a, "block", 0) != 0 || + r4d_geti_or(a, "cu_div", 1) != 1) + return R4D_NO(RAD_E_UNSUPPORTED); long long total = 0, nh = 0, q_ld = 0, tk = 0, hk = 0, k_ld = 0, tv = 0, hv = 0, v_ld = 0; long long to = 0, ho = 0, o_ld = 0; - if (!ps_rows(q, hd, &total, &nh, &q_ld) || !ps_rows(k, hd, &tk, &hk, &k_ld) || - !ps_rows(v, hd, &tv, &hv, &v_ld) || !ps_rows(o, hd, &to, &ho, &o_ld)) + if (!r4d_head_rows(q, hd, &total, &nh, &q_ld) || + !r4d_head_rows(k, hd, &tk, &hk, &k_ld) || + !r4d_head_rows(v, hd, &tv, &hv, &v_ld) || + !r4d_head_rows(o, hd, &to, &ho, &o_ld)) return R4D_NO(RAD_E_STRIDE); if (hk != hv || ho != nh || hk * gqa != nh) return R4D_NO(RAD_E_SHAPE); if (tk < total || tv < total || to < total) return R4D_NO(RAD_E_SHAPE); @@ -586,24 +576,24 @@ extern "C" int r4d_rad_attn_dense_h128(const RadArgs* a, RadStream s) { (int)r4d_geti_or(a, "causal", 0), (int)q_ld, (int)k_ld, 0, 0, (int)v_ld, (int)o_ld, (hipStream_t)s); if (e == -1 || e == -2) return R4D_NO(RAD_E_SHAPE); - return e == 0 ? RAD_OK : R4D_NO(e == -3 ? RAD_E_STRIDE : RAD_E_DEVICE); + if (e == 0) return RAD_OK; + return R4D_NO(e == -3 ? RAD_E_STRIDE : e <= -100 ? RAD_E_DEVICE : RAD_E_SHAPE); } // ============================================================== wide heads (attn_dense, h768 / h1152) -// AN IMAGE DECODER'S MID-BLOCK ATTENTION: one head 1152 wide over every latent pixel -- 16384 rows -// at 2048 x 2048. A lane cannot hold a 1152-wide output row (576 accumulator registers), so the -// head is split across the workgroup's eight waves instead of its rows: a wave owns HD/8 of the -// dims for the whole 16-query block. +// Image decoder mid-block attention: one head up to 1152 wide over every latent pixel (16384 rows +// at 2048 x 2048). A lane cannot hold a 1152-wide output row (576 accumulator VGPRs), so the head +// is split across the workgroup's eight waves: a wave owns HD/8 dims of the 16-query block. // -// S = Q.K^T is contracted in eight pieces, a wave's dims each, and the partial score tiles are -// summed through LDS in wave order -- a fixed order, so the sum is the same every run. -// P is formed once, by sixteen threads (a query row each), rounded to bf16, and its row sum is -// taken off the rounded values, the denominator P.V uses. -// O += P.V is a wave's own dims: V^T fragments straight from global with the transposing load -// (no LDS), P^T from LDS. +// S = Q.K^T in eight partial tiles (one per wave), summed through LDS in fixed wave order so +// the result is run-to-run deterministic. +// P formed by sixteen threads (one per query row), rounded to bf16; the row sum uses the +// rounded values. +// O += P.V over the wave's own dims: V^T straight from global via the transposing load, P^T +// from LDS. // -// S^T = K.Q^T as in the dense kernel above, so a partial tile's C layout is (query = lane % 16, -// key = 8 (lane / 16) + e) and both the reduction and the P^T fragment index it the same way. +// S^T = K.Q^T as above, so a partial tile's C layout is (query = lane % 16, key = 8 (lane / 16) + e) +// for both the reduction and the P^T fragment. template __global__ __launch_bounds__(256) void r4d_attn_wide_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk, @@ -733,8 +723,8 @@ void r4d_attn_wide_kernel(const uint16_t* __restrict__ gq, const uint16_t* __res } } -/* attn_dense at head_dim 768 or 1152 (an image encoder's and decoder's mid block), one query head a - * KV head, bidirectional. */ +/* attn_dense at head_dim 768 or 1152 (image encoder/decoder mid block): one query head per KV + * head, bidirectional. */ extern "C" int r4d_rad_attn_dense_wide(const RadArgs* a, RadStream s) { const RadTensor* q = r4d_opt(a, 0); const RadTensor* k = r4d_opt(a, 1); @@ -745,12 +735,15 @@ extern "C" int r4d_rad_attn_dense_wide(const RadArgs* a, RadStream s) { if (!r4d_contig(cu) || cu->rank != 1 || cu->shape[0] < 2) return R4D_NO(RAD_E_SHAPE); const long long hd = r4d_geti_or(a, "head_dim", 0); if ((hd != 768 && hd != 1152) || r4d_geti_or(a, "gqa", 1) != 1 || r4d_geti_or(a, "causal", 0) != 0 || - r4d_geti_or(a, "window", 0) != 0) + r4d_geti_or(a, "window", 0) != 0 || r4d_geti_or(a, "block", 0) != 0 || + r4d_geti_or(a, "cu_div", 1) != 1) return R4D_NO(RAD_E_UNSUPPORTED); long long total = 0, nh = 0, q_ld = 0, tk = 0, hk = 0, k_ld = 0, tv = 0, hv = 0, v_ld = 0; long long to = 0, ho = 0, o_ld = 0; - if (!ps_rows(q, hd, &total, &nh, &q_ld) || !ps_rows(k, hd, &tk, &hk, &k_ld) || - !ps_rows(v, hd, &tv, &hv, &v_ld) || !ps_rows(o, hd, &to, &ho, &o_ld)) + if (!r4d_head_rows(q, hd, &total, &nh, &q_ld) || + !r4d_head_rows(k, hd, &tk, &hk, &k_ld) || + !r4d_head_rows(v, hd, &tv, &hv, &v_ld) || + !r4d_head_rows(o, hd, &to, &ho, &o_ld)) return R4D_NO(RAD_E_STRIDE); if (hk != nh || hv != nh || ho != nh) return R4D_NO(RAD_E_SHAPE); if (tk < total || tv < total || to < total) return R4D_NO(RAD_E_SHAPE); diff --git a/libr4d/r4d_attn_paged_gqa8.hip b/libr4d/r4d_attn_paged_gqa8.hip index c7cc284f..15eb6c03 100644 --- a/libr4d/r4d_attn_paged_gqa8.hip +++ b/libr4d/r4d_attn_paged_gqa8.hip @@ -1,30 +1,23 @@ -// R4D attention dispatch at EIGHT queries per KV head, for head_dim 256 and head_dim 128. +// R4D paged attention dispatch at eight queries per KV head, head_dim 256 and 128. // -// It is the same device code as the 27B target's h256/gqa6 dispatch -- the kernels are templates -// on head_dim and gqa, so this file is a set of instantiations and not a set of kernels -- and it -// exists because two models in scope are gqa 8 and the constraint tables gate on the exact value: +// Instantiations of the h256/gqa6 kernel templates (templated on head_dim and gqa), for the gqa-8 +// models; the constraint tables gate on the exact ratio: // -// Qwen3.6-35B-A3B 16 query heads over 2 KV heads, head_dim 256 (the routed sibling of the -// 27B, which is 24 over 4 at the same head_dim) +// Qwen3.6-35B-A3B 16 query heads over 2 KV heads, head_dim 256 // MiniCPM5-2B 16 query heads over 2 KV heads, head_dim 128 // -// WHAT CHANGES WITH GQA, AND IT IS ONLY THE TWO BOUNDS. A decode workgroup carries `q_len * gqa` -// rows and holds 64 of them, so the verify width falls from 10 at gqa 6 to 8 at gqa 8 -- and that -// bound is the constraint value the selector bands on, so it is stated in the row and nowhere -// else. A prefill block carries `NWARPS * 16 / gqa` query positions, 48 here against 64 there. +// Gqa changes only two bounds. A decode workgroup holds 64 rows of q_len * gqa, so the verify +// width is 8 here (10 at gqa 6); the selector bands on that value, stated in the row. A prefill +// block carries NWARPS * 16 / gqa query positions (48 here, 64 at gqa 6). // -// WHAT CHANGES WITH HEAD_DIM IS HOW K IS FETCHED. `O_KWIDE` fetches 16 K elements a thread and its -// thread-to-(key, channel) map is written for 16 channels of 16 -- which is head_dim 256 exactly. -// At 128 it would stage past the tile, so the h128 prefill runs without it and pays one more pass -// over a tile that is half the size; and its fragments are half as many registers, so it keeps a -// K prefetch of 4 where head_dim 256 takes 2 (3430923 against 3954187). Everything else -- the -// lazy reference-max softmax, f16 operands, the folded query scale, contiguous-k fragments, the -// SGPR block table, the V prefetch, the LDS-scoped barrier -- is unchanged, and each bit is -// defined and justified in r4d_attn_prefill_h256_gqa6.hip. +// Head_dim changes how K is fetched. O_KWIDE's thread-to-(key, channel) map covers exactly 16 x 16 +// channels (head_dim 256); at 128 it would stage past the tile, so the h128 prefill runs without it. +// Its fragments take half the registers, so it keeps K prefetch 4 where h256 uses 2. All other +// option bits are as defined in r4d_attn_prefill_h256_gqa6.hip. // -// NO `r4d_attn_dims` HERE. That entry point and the `check_dims_once` assertion built on it are -// the h256/gqa6 unit's statement about ITSELF, and a second definition would not link. A geometry -// gate is what the row table's constraints are for; this file states its own in the launchers. +// No r4d_attn_dims here: that entry point (and check_dims_once) belongs to the h256/gqa6 unit, +// and a second definition would not link. Geometry is gated by the row constraints and the +// launchers below. #include "r4d.h" #include "r4d_attn_args.h" #include "r4d_emit.h" @@ -32,49 +25,43 @@ #include #include using std::max; -// The decode kernel shares its query conversion and fragment helpers with the prefill one, so the -// prefill header comes first here for the same reason it does in the other two dispatches. +// The decode kernel uses helpers defined in the prefill unit, so prefill is included first. #include "r4d_attn_prefill_h256_gqa6.hip" #include "r4d_attn_decode_h256_gqa6.hip" #define CHK8() do { hipError_t e_ = hipGetLastError(); if (e_ != hipSuccess) return -100 - (int)e_; } while (0) -/* THE QUERIES PER KV HEAD, AND THE SYMBOL NAMES BUILT FROM IT. +/* Queries per KV head, and the symbol names built from it. * - * This unit is a set of INSTANTIATIONS of templates that already take `gqa`, so a second ratio is - * a second set of macro values and not a second kernel -- and a second COPY of this file would be - * the drift the header warns about, in a dispatch two shipped models run. So the geometry comes - * from macros with this unit's own values as the defaults, the entry points paste the ratio into - * their names, and another ratio is a four-line file that defines the macros and includes this - * one (r4d_attn_paged_h256_gqa12.hip). - * - * WHAT CHANGES WITH THE RATIO IS THE TWO BOUNDS AND NOTHING ELSE, exactly as the header says: the - * decode verify width is 64/gqa (8 here, 5 at gqa 12) and a prefill block carries 384/gqa query - * positions (48 here, 32 at gqa 12). Both must divide, and both are stated in the ROW so the - * selector bands on them. */ + * Another ratio reuses this file: it defines these macros and includes this one (e.g. + * r4d_attn_paged_h256_gqa12.hip), and the entry points paste the ratio into their names. Only + * the two bounds change: decode verify width 64/gqa (8 here, 5 at gqa 12) and prefill block + * 384/gqa query positions (48 here, 32 at gqa 12). Both must divide, and both are stated in the + * row so the selector bands on them. */ #ifndef R4D_ATTN_GQA #define R4D_ATTN_GQA 8 #define R4D_ATTN_H128 1 /* this ratio also serves head_dim 128 -- MiniCPM5-2B is 16 over 2 */ #endif -/* A head_dim 64 PREFILL leg, off unless the including unit asks for it: LFM2 is 32 query heads - * over 8 at head_dim 64 (r4d_attn_paged_h256_gqa4.hip). It runs the h128 prefill option set -- - * O_KWIDE's 16-channel staging is written for 256. There is no decode leg: the split-KV kernel - * holds a lane's columns as one or two dwords of codes, which is head_dim 128 or 256, so the - * query-tiled kernel serves every query length at this width. */ +/* Head_dim 64 prefill leg, off unless the including unit enables it (LFM2: 32 query heads over 8, + * r4d_attn_paged_h256_gqa4.hip). Uses the h128 option set (no O_KWIDE). No decode leg: the + * split-KV merge holds a lane's columns as one or two dwords of codes (head_dim 128 or 256), so + * the query-tiled kernel serves every query length at this width. */ #ifndef R4D_ATTN_H64 #define R4D_ATTN_H64 0 #endif +/* Head_dim 256 leg, on unless the including unit serves only head_dim 128 (as R4D_ATTN_H128 0 + * leaves the 128 leg out). */ +#ifndef R4D_ATTN_H256 +#define R4D_ATTN_H256 1 +#endif #define GQ_JOIN_(a, b, c) a##b##c #define GQ_JOIN(a, b, c) GQ_JOIN_(a, b, c) #define GQ_SYM(pre, suf) GQ_JOIN(pre, R4D_ATTN_GQA, suf) #define G8_GQA R4D_ATTN_GQA -/* The KV page, in tokens. Overridable by the including translation unit because the BODY IS - * GENERIC IN IT -- `bt[kk / BS]` picks the page, `kk % BS` the offset inside it, and - * `NB = TILE / BS` is how many block-table entries the O_BTS prefetch stages a tile. 16 is what - * every geometry here has wanted so far; Qwen4-Exp's QSA wants 4, because its indexer selects - * 4-token blocks and a page of 4 makes the selection a block table rather than a new kernel - * (docs/QSA.md). */ +/* KV page size in tokens; the kernel body is generic in it, so an including unit may override. + * Qwen4-Exp's QSA uses 4: its indexer selects 4-token blocks, so the selection is just a block + * table (docs/QSA.md). */ #ifndef G8_BLOCK_SIZE #define G8_BLOCK_SIZE 16 #endif @@ -82,10 +69,10 @@ using std::max; #define G8_P_NWARPS 24 #define G8_P_TILE 48 -// K prefetch 2, as the h256/gqa6 prefill and for the same reason (see P_OPT there): 4 spills the -// m-tile loop. The head_dim-128 set keeps its prefetch of 4, which fits. +// K prefetch 2 at head_dim 256, as in the h256/gqa6 prefill (P_OPT there): 4 spills the m-tile +// loop. The head_dim-128 set keeps prefetch 4, which fits. #define G8_P_OPT_256 3954187 -#define G8_P_OPT_128 3430923 // without O_KWIDE, at prefetch 4; see the header +#define G8_P_OPT_128 3430923 // without O_KWIDE, prefetch 4 #define G8_P_OPT_64 G8_P_OPT_128 #define G8_D_TILE 16 #define G8_D_OPT 3429947 @@ -107,38 +94,16 @@ static int g8_prefill_launch(const R4DArgs* a, hipStream_t s) { } // ---- decode ------------------------------------------------------------------------------------ -// The h256/gqa6 split law verbatim -- as many workgroups as fit under 128, at least two tiles a -// segment. It reads kv_heads, num_seqs and max_ctx and nothing about gqa or head_dim, so there is -// nothing in it to re-derive for this geometry; copying it rather than sharing it is the cost of -// the three dispatches being three translation units, and the target count is the h256 leg's. -static int g8_decode_splits(const R4DArgs* a) { - if (a->splits > 0) return a->splits; - const int tiles = (a->max_ctx + G8_D_TILE - 1) / G8_D_TILE; - const int units = max(1, a->kv_heads * a->num_seqs); - int s = 128 / units; - const int cap = tiles / 2; - if (s > cap) s = cap; - if (s > tiles) s = tiles; - if (s < 1) s = 1; - return s; -} - +// The h256/gqa6 split law (r4d_decode_splits). extern "C" long GQ_SYM(r4d_attn_decode_gqa, _scratch_bytes)(const R4DArgs* a) { - const int splits = g8_decode_splits(a); - const long rows = (long)r4d_q_total(*a) * a->q_heads; - return (G8_D_OPT & 32) ? rows * splits * (long)(a->head_dim * 2 + 8) - : rows * splits * (long)(a->head_dim + 2) * 4L; + return r4d_decode_scratch(a, r4d_decode_splits(a, G8_D_TILE), G8_D_OPT); } template -/* THE DECODE PATH TAKES A SINK, so the same geometry serves the launch and the description. - * Two dispatches: the attention kernel and the split-KV combine that follows it. The kernel takes - * `R4DArgs` BY VALUE -- 168 bytes -- which the descriptor's blob carries like any other argument, - * because a kernel parameter is a kernel parameter whatever its size. - * - * `gq` is attn_paged_gate_quant's epilogue: the same two dispatches, with the combine taking the - * output gate and the fp8 quantiser on (r4d_attn_decode_h256_gqa6.hip, R4DGateQuant). */ -static int g8_decode_launch(const R4DArgs* a, const R4dSink& sk, +/* Two dispatches: the attention kernel and the split-KV combine. R4DArgs is passed by value (168 + * bytes) like any other kernel argument. Non-null `gq` adds the output gate and quantiser to the + * combine (attn_paged_gate_quant; R4DGateQuant in r4d_attn_decode_h256_gqa6.hip). */ +static int g8_decode_launch(const R4DArgs* a, RadStream stream, const R4DGateQuant* gq = nullptr) { int emit_rc = RAD_OK; if (a->head_dim != HEAD_DIM || a->block_size != G8_BLOCK_SIZE) return -1; @@ -146,16 +111,15 @@ static int g8_decode_launch(const R4DArgs* a, const R4dSink& sk, const int rows = a->q_len * G8_GQA; if (rows > G8_MAX_DECODE_ROWS) return -4; const int nw = (rows + 15) / 16; - const int splits = g8_decode_splits(a); + const int splits = r4d_decode_splits(a, G8_D_TILE); #define G8_LAUNCH(NW) \ - emit_rc = R4D_EMIT(sk, (r4d_attn_decode_kernel), \ dim3(splits, a->kv_heads, a->num_seqs), dim3(NW * 32), 0, *a, splits) - /* One wave a workgroup stages V as its codes (O_V8): the one wave converts each element once - * either way, and the tile is half the LDS. */ + /* One-wave workgroups stage V as codes (O_V8): same conversion count, half the LDS. */ if (nw == 1) - emit_rc = R4D_EMIT(sk, (r4d_attn_decode_kernel<1, G8_D_TILE, HEAD_DIM, G8_GQA, + emit_rc = R4D_EMIT(stream, (r4d_attn_decode_kernel<1, G8_D_TILE, HEAD_DIM, G8_GQA, G8_BLOCK_SIZE, KVP, G8_D_OPT | O_V8>), dim3(splits, a->kv_heads, a->num_seqs), dim3(32), 0, *a, splits); else if (nw == 2) G8_LAUNCH(2); @@ -163,21 +127,22 @@ static int g8_decode_launch(const R4DArgs* a, const R4dSink& sk, else G8_LAUNCH(4); #undef G8_LAUNCH if (emit_rc != RAD_OK) return -5; - if (!sk.desc) CHK8(); + CHK8(); - // The same two merge forms and the same rule for choosing between them as the other two - // dispatches: a wave a row while there are enough rows to fill the part and the segment count - // fits a wave, the general LDS-tree form otherwise. Both produce the same bytes. + // Merge form, as in the other dispatches: one wave per row when there are enough rows and the + // segment count fits a wave, else the general LDS-tree form. Both give identical bytes. const int jobs3 = r4d_q_total(*a) * a->q_heads; if (gq) { - /* GQ 2 is the int8 codes' epilogue, 1 the E4M3 one; see R4DGateQuant. */ + /* GQ 2: int8 codes, GQ 1: E4M3; see R4DGateQuant. */ #define G8_GQ_VEC(PF, GQV) \ - R4D_EMIT(sk, (r4d_attn_splitkv_combine_vec_gq_kernel), \ + R4D_EMIT(stream, \ + (r4d_attn_splitkv_combine_vec_gq_kernel), \ dim3((jobs3 + G8_D_JPB - 1) / G8_D_JPB), dim3(32 * G8_D_JPB), 0, *a, splits, \ G8_D_TILE, *gq) #define G8_GQ_GEN(PF, GQV) \ - R4D_EMIT(sk, (r4d_attn_splitkv_combine_gq_kernel), dim3(jobs3), \ - dim3(HEAD_DIM), splits * sizeof(float), *a, splits, G8_D_TILE, *gq) + R4D_EMIT(stream, (r4d_attn_splitkv_combine_gq_kernel), \ + dim3(jobs3), dim3(HEAD_DIM), splits * sizeof(float), *a, splits, G8_D_TILE, \ + *gq) const bool i8 = gq->i8 != 0; if (splits <= 64 && jobs3 >= G8_D_VECMIN) { if (G8_D_OPT & 32) emit_rc = i8 ? G8_GQ_VEC(1, 2) : G8_GQ_VEC(1, 1); @@ -192,34 +157,34 @@ static int g8_decode_launch(const R4DArgs* a, const R4dSink& sk, } else if (splits <= 64 && jobs3 >= G8_D_VECMIN) { const int blocks = (jobs3 + G8_D_JPB - 1) / G8_D_JPB; if (G8_D_OPT & 32) - emit_rc = R4D_EMIT(sk, (r4d_attn_splitkv_combine_vec_kernel), + emit_rc = R4D_EMIT(stream, + (r4d_attn_splitkv_combine_vec_kernel), dim3(blocks), dim3(32 * G8_D_JPB), 0, *a, splits, G8_D_TILE); else - emit_rc = R4D_EMIT(sk, (r4d_attn_splitkv_combine_vec_kernel), + emit_rc = R4D_EMIT(stream, + (r4d_attn_splitkv_combine_vec_kernel), dim3(blocks), dim3(32 * G8_D_JPB), 0, *a, splits, G8_D_TILE); } else if (G8_D_OPT & 32) - /* THE BLOCK IS HEAD_DIM THREADS AND NOT 256: the general combine is - * __launch_bounds__(HEAD_DIM), one thread a channel, so a 128-wide head launched at 256 - * is refused by the runtime. A dispatch that serves only head_dim 256 can write 256 here; - * this one serves both widths and cannot. */ - emit_rc = R4D_EMIT(sk, (r4d_attn_splitkv_combine_kernel), dim3(jobs3), + /* Block of HEAD_DIM threads, not 256: the general combine is __launch_bounds__(HEAD_DIM), + * one thread per channel, and the runtime refuses a larger block. */ + emit_rc = R4D_EMIT(stream, (r4d_attn_splitkv_combine_kernel), dim3(jobs3), dim3(HEAD_DIM), splits * sizeof(float), *a, splits, G8_D_TILE); else - emit_rc = R4D_EMIT(sk, (r4d_attn_splitkv_combine_kernel), dim3(jobs3), + emit_rc = R4D_EMIT(stream, (r4d_attn_splitkv_combine_kernel), dim3(jobs3), dim3(HEAD_DIM), splits * sizeof(float), *a, splits, G8_D_TILE); if (emit_rc != RAD_OK) return -5; - if (!sk.desc) CHK8(); + CHK8(); return 0; } // ============================================================== the plugin ABI entry points +#if R4D_ATTN_H256 extern "C" int GQ_SYM(r4d_rad_attn_prefill_h256_gqa, _fp8)(const RadArgs* a, RadStream s) { R4DArgs r; const int rc = fill_paged(a, &r, 256); if (rc != RAD_OK) return rc; - /* Absent descales mean 1.0, exactly as on the gqa6 leg: the kernels spell it that way and a - * cache written at the default scale needs no plane to allocate or keep in step. */ + /* Absent descales mean 1.0, as on the gqa6 leg. */ return g8_prefill_launch<256, G8_P_OPT_256, 0>(&r, (hipStream_t)s); } extern "C" int GQ_SYM(r4d_rad_attn_prefill_h256_gqa, _bf16)(const RadArgs* a, RadStream s) { @@ -228,6 +193,7 @@ extern "C" int GQ_SYM(r4d_rad_attn_prefill_h256_gqa, _bf16)(const RadArgs* a, Ra if (rc != RAD_OK) return rc; return g8_prefill_launch<256, G8_P_OPT_256, 1>(&r, (hipStream_t)s); } +#endif #if R4D_ATTN_H128 extern "C" int GQ_SYM(r4d_rad_attn_prefill_h128_gqa, _fp8)(const RadArgs* a, RadStream s) { R4DArgs r; @@ -257,13 +223,10 @@ extern "C" int GQ_SYM(r4d_rad_attn_prefill_h64_gqa, _bf16)(const RadArgs* a, Rad } #endif -/* The split-KV partial buffer, sized at declare from the band's upper bound. IT IS CALLED WITH - * PARAMETERS AND NO TENSORS -- that is what declare is -- so the parameters are the primary source - * and the tensors the fallback, which is the trap the h256/gqa6 dispatch documents at length. - * - * The size is the largest over EVERY sequence count up to max_seqs, not the size at max_seqs: - * S * floor(128 / (kv_heads * S)) is not monotone in S, which the h256/gqa6 dispatch also - * spells out. */ +/* Split-KV partial buffer size at declare time, from the band's upper bound. Declare passes + * parameters and no tensors, so parameters come first and tensors are the fallback (see the + * h256/gqa6 dispatch). The size is the maximum over every sequence count up to max_seqs, because + * S * floor(128 / (kv_heads * S)) is not monotone in S. */ static int64_t g8_decode_scratch(const RadArgs* a, int head_dim) { const int sp = split_of(a); if (sp < 0) return R4D_NO(RAD_E_INVAL); @@ -297,9 +260,11 @@ static int64_t g8_decode_scratch(const RadArgs* a, int head_dim) { return GQ_SYM(r4d_attn_decode_gqa, _scratch_bytes)(&r); } +#if R4D_ATTN_H256 extern "C" int64_t GQ_SYM(r4d_rad_attn_decode_h256_gqa, _scratch)(const RadArgs* a) { return g8_decode_scratch(a, 256); } +#endif #if R4D_ATTN_H128 extern "C" int64_t GQ_SYM(r4d_rad_attn_decode_h128_gqa, _scratch)(const RadArgs* a) { return g8_decode_scratch(a, 128); @@ -317,31 +282,17 @@ static int g8_decode_common(const RadArgs* a, R4DArgs* r, int head_dim) { return RAD_OK; } -static int GQ_SYM(rad_attn_decode_h256_gqa, _fp8_body)(const RadArgs* a, const R4dSink& sk) { +#if R4D_ATTN_H256 +extern "C" int GQ_SYM(r4d_rad_attn_decode_h256_gqa, _fp8)(const RadArgs* a, RadStream stream) { R4DArgs r; const int rc = g8_decode_common(a, &r, 256); if (rc != RAD_OK) return rc; - return g8_decode_launch<256, 0>(&r, sk); + return g8_decode_launch<256, 0>(&r, stream); } -/* R4D_ENTRY CANNOT BE USED HERE. It pastes `_describe` onto its first argument, and this - * name is itself a macro -- the paste would land on the GQ_SYM invocation text rather than on - * the symbol it expands to. Both entries are spelled instead, through the same join. */ -extern "C" int GQ_SYM(r4d_rad_attn_decode_h256_gqa, _fp8)(const RadArgs* a, RadStream s) { - R4dSink sk; sk.stream = s; - return GQ_SYM(rad_attn_decode_h256_gqa, _fp8_body)(a, sk); -} -extern "C" int GQ_SYM(r4d_rad_attn_decode_h256_gqa, _fp8_describe)( - const RadArgs* a, RadStream s, RadLaunchDesc* d, int cap, int* n) { - if (!n) return RAD_E_INVAL; - *n = 0; - R4dSink sk; sk.stream = s; sk.desc = d; sk.cap = cap; sk.n = n; - return GQ_SYM(rad_attn_decode_h256_gqa, _fp8_body)(a, sk); -} -/* ---- attn_paged_gate_quant: attn_paged's eight operands, then the gate, the codes and the - * scales. The gate is gate_quant_fp8's: a [T, n_head, head_dim] column view of the [q|gate] - * projection, whose (token, head) rows are one pitch apart only because the view narrowed the last - * axis and nothing above it -- the same test gate_quant_fp8's shim applies (tq_pitch), repeated - * here because this unit cannot link that one. */ +/* ---- attn_paged_gate_quant: attn_paged's eight operands, then the gate, codes and scales. + * The gate is a [T, n_head, head_dim] column view of the [q|gate] projection; its (token, head) + * rows are one pitch apart only if the view narrowed the last axis alone. gq_row_pitch repeats + * gate_quant_fp8's tq_pitch test, which this unit cannot link. */ enum { AP_GQ_G = AP_OUT + 1, AP_GQ_Q, AP_GQ_S }; static long long gq_row_pitch(const RadTensor* t, long long width) { @@ -374,8 +325,8 @@ static int g8_gate_quant_args(const RadArgs* a, const R4DArgs& r, R4DGateQuant* return R4D_NO(RAD_E_SHAPE); const long long gp = gq_row_pitch(g, n), qp = gq_row_pitch(q, n), sp = gq_row_pitch(s, nkb); if (gp < 0 || qp < 0 || sp < 0) return R4D_NO(RAD_E_STRIDE); - /* The vector merge reads a lane's gate as one 16-byte access and stores its codes as one - * 8-byte one. */ + /* The vector merge reads a lane's gate in one 16-byte access and stores its codes in one + * 8-byte access. */ if ((r4d_addr(g) & 15) || (gp % 8) || (r4d_addr(q) & 7) || (qp % 8)) return R4D_NO(RAD_E_STRIDE); gq->g = (const uint16_t*)r4d_addr(g); @@ -388,77 +339,44 @@ static int g8_gate_quant_args(const RadArgs* a, const R4DArgs& r, R4DGateQuant* return RAD_OK; } -static int GQ_SYM(rad_attn_decode_gq_h256_gqa, _fp8_body)(const RadArgs* a, const R4dSink& sk) { +extern "C" int GQ_SYM(r4d_rad_attn_decode_gq_h256_gqa, _fp8)(const RadArgs* a, RadStream stream) { R4DArgs r; const int rc = g8_decode_common(a, &r, 256); if (rc != RAD_OK) return rc; R4DGateQuant gq{}; const int gc = g8_gate_quant_args(a, r, &gq); if (gc != RAD_OK) return gc; - return g8_decode_launch<256, 0>(&r, sk, &gq); -} -extern "C" int GQ_SYM(r4d_rad_attn_decode_gq_h256_gqa, _fp8)(const RadArgs* a, RadStream s) { - R4dSink sk; sk.stream = s; - return GQ_SYM(rad_attn_decode_gq_h256_gqa, _fp8_body)(a, sk); -} -extern "C" int GQ_SYM(r4d_rad_attn_decode_gq_h256_gqa, _fp8_describe)( - const RadArgs* a, RadStream s, RadLaunchDesc* d, int cap, int* n) { - if (!n) return RAD_E_INVAL; - *n = 0; - R4dSink sk; sk.stream = s; sk.desc = d; sk.cap = cap; sk.n = n; - return GQ_SYM(rad_attn_decode_gq_h256_gqa, _fp8_body)(a, sk); + return g8_decode_launch<256, 0>(&r, stream, &gq); } -/* The bf16 cache's decode, plain and with the gate and the quantiser in the merge: the fp8 pair's - * dispatches at KVP 1, described the same way so either cache replays as a graph. */ -static int GQ_SYM(rad_attn_decode_h256_gqa, _bf16_body)(const RadArgs* a, const R4dSink& sk) { +/* bf16-cache decode, plain and gated: the fp8 pair at KVP 1. */ +extern "C" int GQ_SYM(r4d_rad_attn_decode_h256_gqa, _bf16)(const RadArgs* a, RadStream stream) { R4DArgs r; const int rc = g8_decode_common(a, &r, 256); if (rc != RAD_OK) return rc; - return g8_decode_launch<256, 1>(&r, sk); + return g8_decode_launch<256, 1>(&r, stream); } -extern "C" int GQ_SYM(r4d_rad_attn_decode_h256_gqa, _bf16)(const RadArgs* a, RadStream s) { - R4dSink sk; sk.stream = s; - return GQ_SYM(rad_attn_decode_h256_gqa, _bf16_body)(a, sk); -} -extern "C" int GQ_SYM(r4d_rad_attn_decode_h256_gqa, _bf16_describe)( - const RadArgs* a, RadStream s, RadLaunchDesc* d, int cap, int* n) { - if (!n) return RAD_E_INVAL; - *n = 0; - R4dSink sk; sk.stream = s; sk.desc = d; sk.cap = cap; sk.n = n; - return GQ_SYM(rad_attn_decode_h256_gqa, _bf16_body)(a, sk); -} -static int GQ_SYM(rad_attn_decode_gq_h256_gqa, _bf16_body)(const RadArgs* a, const R4dSink& sk) { +extern "C" int GQ_SYM(r4d_rad_attn_decode_gq_h256_gqa, _bf16)(const RadArgs* a, RadStream stream) { R4DArgs r; const int rc = g8_decode_common(a, &r, 256); if (rc != RAD_OK) return rc; R4DGateQuant gq{}; const int gc = g8_gate_quant_args(a, r, &gq); if (gc != RAD_OK) return gc; - return g8_decode_launch<256, 1>(&r, sk, &gq); -} -extern "C" int GQ_SYM(r4d_rad_attn_decode_gq_h256_gqa, _bf16)(const RadArgs* a, RadStream s) { - R4dSink sk; sk.stream = s; - return GQ_SYM(rad_attn_decode_gq_h256_gqa, _bf16_body)(a, sk); -} -extern "C" int GQ_SYM(r4d_rad_attn_decode_gq_h256_gqa, _bf16_describe)( - const RadArgs* a, RadStream s, RadLaunchDesc* d, int cap, int* n) { - if (!n) return RAD_E_INVAL; - *n = 0; - R4dSink sk; sk.stream = s; sk.desc = d; sk.cap = cap; sk.n = n; - return GQ_SYM(rad_attn_decode_gq_h256_gqa, _bf16_body)(a, sk); + return g8_decode_launch<256, 1>(&r, stream, &gq); } +#endif #if R4D_ATTN_H128 extern "C" int GQ_SYM(r4d_rad_attn_decode_h128_gqa, _fp8)(const RadArgs* a, RadStream s) { R4DArgs r; const int rc = g8_decode_common(a, &r, 128); if (rc != RAD_OK) return rc; - return g8_decode_launch<128, 0>(&r, r4d_stream_sink(s)); + return g8_decode_launch<128, 0>(&r, s); } extern "C" int GQ_SYM(r4d_rad_attn_decode_h128_gqa, _bf16)(const RadArgs* a, RadStream s) { R4DArgs r; const int rc = g8_decode_common(a, &r, 128); if (rc != RAD_OK) return rc; - return g8_decode_launch<128, 1>(&r, r4d_stream_sink(s)); + return g8_decode_launch<128, 1>(&r, s); } #endif diff --git a/libr4d/r4d_attn_paged_h128_gqa2.hip b/libr4d/r4d_attn_paged_h128_gqa2.hip new file mode 100644 index 00000000..07b911d2 --- /dev/null +++ b/libr4d/r4d_attn_paged_h128_gqa2.hip @@ -0,0 +1,14 @@ +// R4D attention at two queries per KV head, head_dim 128: Qwen3-1.7B's 16 query heads over 8 KV +// heads, Qwen3-ASR's decoder (arch/qwen3asr_bf16). Geometry only; r4d_attn_paged_gqa8.hip is the +// body. The ratio changes two bounds, both stated in the row table: +// +// decode verify width 64 / gqa = 32 (a workgroup holds 64 (query, head) rows). +// prefill block width 384 / gqa = 192 query positions. +// +// No head_dim 256 leg (R4D_ATTN_H256 0): gqa 2 at 256 is r4d_attn_paged_h256_gqa2.hip's, a +// windowed kernel of its own. Page size 16. +#define R4D_ATTN_GQA 2 +#define R4D_ATTN_H128 1 +#define R4D_ATTN_H256 0 + +#include "r4d_attn_paged_gqa8.hip" diff --git a/libr4d/r4d_attn_paged_h128_gqa4.hip b/libr4d/r4d_attn_paged_h128_gqa4.hip index f6017ee3..d48d88e1 100644 --- a/libr4d/r4d_attn_paged_h128_gqa4.hip +++ b/libr4d/r4d_attn_paged_h128_gqa4.hip @@ -1,132 +1,39 @@ -// R4D attention dispatch for the DFlash2 drafter's geometry: head_dim 128, 4 queries per KV head, -// paged block 16, and a SLIDING WINDOW. It is the same device code as the 27B target's h256/gqa6 -// dispatch -- the kernels are templates on head_dim and gqa, so this file is a second set of -// instantiations and not a second kernel -- with the window bit turned on. +// R4D attention dispatch for the DFlash2 drafter: head_dim 128, 4 queries per KV head, paged +// block 16, sliding window. Instantiations of the h256/gqa6 kernel templates with WIN = 1. // -// Decode only, deliberately. A query long enough to want the query-tiled prefill kernel is rare on -// a drafter (it happens on a prefill step and nowhere else), and the caller has a working fallback -// for it; instantiating a second prefill kernel to serve that case would cost build time and a -// second masking path to keep correct for no measurable return. The caller asks -// r4d_attn_h128_gqa4_have_prefill() and routes the whole batch elsewhere when it is 0. +// Decode only. Queries long enough for the query-tiled prefill kernel occur on a drafter only in +// prefill steps; the rows declare the decode band (q_len * gqa <= 64), so those resolve elsewhere. // -// WHY THIS EXISTS. A general unified-attention kernel (vLLM's) spends 30.9 us a layer on this -// shape at one request and 203.7 at eight -- against a KV stream that the window caps at 2048 -// positions, i.e. 2.1 MB and 16.8 MB, which is 3.3 us and 26.3 us of DRAM. The gap is grid shape, -// not bandwidth: it launches (q_blocks, kv_heads, -// segments) with the query in the GRID and pads q_blocks for capture, so the great majority of its -// workgroups start and immediately return. R4D carries the query INSIDE the workgroup (up to 64 -// rows of q_len * gqa), so its grid is (splits, kv_heads, num_seqs) and has nothing dead in it. +// Rationale: a general unified-attention kernel (vLLM's) launches (q_blocks, kv_heads, segments) +// with q_blocks padded for capture, so most workgroups return immediately; on this shape it is +// 8-9x slower than the window-capped DRAM bound. R4D keeps the query inside the workgroup (up to 64 rows of +// q_len * gqa), so its grid is (splits, kv_heads, num_seqs) with no dead workgroups. #include "r4d.h" #include "r4d_common.h" #include #include using std::max; -// The decode kernel shares its query conversion and fragment helpers with the prefill one, -// so the prefill header comes first here for the same reason it does in the h256 dispatch. -// Nothing in this translation unit instantiates r4d_attn_prefill_kernel. +// The decode kernel uses helpers from the prefill unit, so prefill is included first. +// Nothing here instantiates r4d_attn_prefill_kernel. #include "r4d_attn_prefill_h256_gqa6.hip" #include "r4d_attn_decode_h256_gqa6.hip" -#define CHK4() do { hipError_t e_ = hipGetLastError(); if (e_ != hipSuccess) return -100 - (int)e_; } while (0) - +// Tile, block size, row cap and merge: r4d_decode_launch_win (r4d_attn_decode_h256_gqa6.hip). #define B_HEAD_DIM 128 #define B_GQA 4 -#define B_BLOCK_SIZE 16 -#define B_MAX_DECODE_ROWS 64 // q_len * gqa a single decode workgroup can hold #define B_TILE 16 -// The same option set the h256 decode kernel ships, K prefetch of 2 included. This geometry does -// not need it -- head_dim 128 halves both the accumulator and the query, so it sits at 162-179 -// VGPRs and does not spill at 4 -- but 2 is still 0.3-1.3% faster at every concurrency and window, -// for bit-identical output, so the two legs stay on one number -- plus O_KRAW, which loads an -// m-tile's K codes in one round (see r4d_attn_decode_h256_gqa6.hip): at head_dim 128 that round is -// 16 VGPRs and leaves the residency where it was. +// The h256 decode option set, including K prefetch 2 (head_dim 128 would not spill at 4, but 2 is +// 0.3-1.3% faster here with identical output), plus O_KRAW: one-round K loads +// (r4d_attn_decode_h256_gqa6.hip), 16 VGPRs at head_dim 128 with no occupancy loss. #define B_OPT 20207163 -#ifndef B_JPB -#define B_JPB 2 -#endif -#ifndef B_VECMIN -#define B_VECMIN 256 -#endif - -extern "C" int r4d_attn_h128_gqa4_have_prefill(void) { return 0; } - -// Split law. It aims at 192 workgroups, snaps DOWN to a power of two but never below 16, clamps to -// at least two tiles a segment, and then steps UP off the exact grid size `splits * units == 256`, -// which is a pothole in this geometry's timing. -// -// The one thing it does that the h256 law does not: under a sliding window the context the kernel -// actually walks is the window, not the sequence, so the tile count that feeds the machine-fill -// target and the thin-segment clamp comes from the window. Without that the law reads a 16K -// sequence and asks for segments that are two tiles of a 129-tile walk. -static int decode_splits_h128(const R4DArgs* a) { - if (a->splits > 0) return a->splits; - const int span = (a->window > 0 && a->window + a->q_len < a->max_ctx) - ? a->window + a->q_len : a->max_ctx; - const int tiles = (span + B_TILE - 1) / B_TILE; - const int units = std::max(1, a->kv_heads * a->num_seqs); - const int raw = 192 / units; - int s = 128; - while (s > 16 && s > raw) s >>= 1; - const int cap = tiles / 2; - while (s > 16 && s > cap) s >>= 1; - if (s > tiles) s = tiles; - if (s < 1) s = 1; - if (s * units == 256 && s * 2 <= tiles) s <<= 1; // step off the pothole, see above - return s; -} extern "C" long r4d_attn_decode_h128_gqa4_scratch_bytes(const R4DArgs* a) { - const int splits = decode_splits_h128(a); - const long rows = (long)r4d_q_total(*a) * a->q_heads; - return (B_OPT & 32) ? rows * splits * (long)(a->head_dim * 2 + 8) - : rows * splits * (long)(a->head_dim + 2) * 4L; -} - -template -static int decode_launch_h128(const R4DArgs* a, hipStream_t s) { - if (a->head_dim != B_HEAD_DIM || a->block_size != B_BLOCK_SIZE) return -1; - if (a->q_heads / a->kv_heads != B_GQA) return -2; - const int rows = a->q_len * B_GQA; - if (rows > B_MAX_DECODE_ROWS) return -4; - const int nw = (rows + 15) / 16; - const int splits = decode_splits_h128(a); - -#define B_LAUNCH(NW) \ - hipLaunchKernelGGL((r4d_attn_decode_kernel), \ - dim3(splits, a->kv_heads, a->num_seqs), dim3(NW * 32), 0, s, *a, splits) - if (nw == 1) B_LAUNCH(1); - else if (nw == 2) B_LAUNCH(2); - else if (nw == 3) B_LAUNCH(3); - else B_LAUNCH(4); -#undef B_LAUNCH - CHK4(); - - // Same two merge forms, and the same rule for choosing between them, as the h256 dispatch: - // a wave a row while there are enough rows to fill the part and the segment count fits a - // wave, the general LDS-tree form otherwise. Both produce the same bytes. - const int jobs3 = r4d_q_total(*a) * a->q_heads; - if (splits <= 64 && jobs3 >= B_VECMIN) { - const int blocks = (jobs3 + B_JPB - 1) / B_JPB; - if (B_OPT & 32) - hipLaunchKernelGGL((r4d_attn_splitkv_combine_vec_kernel), - dim3(blocks), dim3(32 * B_JPB), 0, s, *a, splits, B_TILE); - else - hipLaunchKernelGGL((r4d_attn_splitkv_combine_vec_kernel), - dim3(blocks), dim3(32 * B_JPB), 0, s, *a, splits, B_TILE); - } else if (B_OPT & 32) - hipLaunchKernelGGL((r4d_attn_splitkv_combine_kernel), dim3(jobs3), - dim3(B_HEAD_DIM), splits * sizeof(float), s, *a, splits, B_TILE); - else - hipLaunchKernelGGL((r4d_attn_splitkv_combine_kernel), dim3(jobs3), - dim3(B_HEAD_DIM), splits * sizeof(float), s, *a, splits, B_TILE); - CHK4(); - return 0; + return r4d_decode_scratch(a, r4d_decode_splits_win(a, B_TILE), B_OPT); } extern "C" int r4d_attn_decode_h128_gqa4_fp8kv(const R4DArgs* a, hipStream_t s) { - return decode_launch_h128<0>(a, s); + return r4d_decode_launch_win(a, s); } extern "C" int r4d_attn_decode_h128_gqa4_bf16kv(const R4DArgs* a, hipStream_t s) { - return decode_launch_h128<1>(a, s); + return r4d_decode_launch_win(a, s); } diff --git a/libr4d/r4d_attn_paged_h256_gqa12.hip b/libr4d/r4d_attn_paged_h256_gqa12.hip index bf09236f..971a915c 100644 --- a/libr4d/r4d_attn_paged_h256_gqa12.hip +++ b/libr4d/r4d_attn_paged_h256_gqa12.hip @@ -1,37 +1,21 @@ -// R4D attention at TWELVE queries per KV head, head_dim 256 -- Qwen3.8-Flash-Next's QSA layers, -// which are 24 query heads over 2 KV heads. +// R4D attention at twelve queries per KV head, head_dim 256: Qwen3.8-Flash-Next's QSA layers +// (24 query heads over 2 KV heads). Geometry only; r4d_attn_paged_gqa8.hip is the body. The ratio +// changes two bounds, both stated in the row table: // -// Four lines of geometry and the dispatch itself, because r4d_attn_paged_gqa8.hip's kernels are -// templates on `gqa` and that unit is the parameterised body. What the ratio changes is -// exactly two bounds, and both are in the ROW table rather than here: +// decode verify width 64 / gqa = 5. A wider speculative verify takes the prefill kernel. +// prefill block width 384 / gqa = 32 query positions. // -// the decode verify width 64 / gqa = 5, against 8 at gqa 8 and 10 at gqa 6. A workgroup holds -// 64 (query, head) rows and carries q_len * gqa of them, so a -// speculative verify wider than five positions takes the prefill -// kernel instead -- which serves any q_len and is what the row says. -// a prefill block's width 384 / gqa = 32 query positions, against 48 at gqa 8. -// -// NO head_dim 128 LEG. Nothing in scope is gqa 12 at 128, and an instantiation nothing resolves is -// a kernel nobody has run: R4D_ATTN_H128 leaves those four entry points out of this translation -// unit entirely rather than shipping them untested. +// No head_dim 128 leg: nothing in scope is gqa 12 at 128, so those entry points are not built. #define R4D_ATTN_GQA 12 #define R4D_ATTN_H128 0 -// THE KV PAGE IS FOUR TOKENS HERE, as in the gqa 6 unit that serves the same layers at four -// ranks; every other geometry in this library pages at 16. +// KV page of 4 tokens (as in the gqa6-bs4 unit for the same layers at four ranks; 16 elsewhere). +// The QSA indexer selects 4-token blocks, so a selected block is a page and sparse attention is +// this kernel with a different block table (docs/QSA.md). The only cost is reading NB = TILE / BS +// table entries per tile (4 at TILE 16), within step noise; output is identical. // -// Qwen3.8-Flash-Next's QSA indexer selects 4-TOKEN BLOCKS of the key history. With a page of 4 a -// selected block IS a page, so the selection is a paged block table and the sparse attention is -// this kernel with a different table -- instead of a new attention kernel, which is the most -// expensive kind of kernel in this tree to get right. docs/QSA.md is the decomposition. -// -// IT COSTS NOTHING. A page size is pure storage, so the only thing it can move is the block-table -// walk -- `NB = TILE / BS` entries a tile instead of one, four instead of one at TILE 16 -- and at -// a realistic context that is inside the noise of the step, with identical output either way. -// -// THE ROWS HAVE TO AGREE. `C_EQ("block_size", 4)` on all four gqa12 rows is what makes the core -// size the pages at 4 (RadKVGroupDecl carries no block size on purpose -- it is taken off the -// resolved kernel). A row that says 16 against this define is a kernel that refuses at issue -// rather than at declare. +// Note: the rows must agree. C_EQ("block_size", 4) on all four gqa12 rows makes the core size the +// pages at 4 (RadKVGroupDecl takes the block size from the resolved kernel). A row saying 16 here +// would refuse at issue rather than at declare. #define G8_BLOCK_SIZE 4 #include "r4d_attn_paged_gqa8.hip" diff --git a/libr4d/r4d_attn_paged_h256_gqa2.hip b/libr4d/r4d_attn_paged_h256_gqa2.hip index fdb80a90..297dd4ec 100644 --- a/libr4d/r4d_attn_paged_h256_gqa2.hip +++ b/libr4d/r4d_attn_paged_h256_gqa2.hip @@ -1,26 +1,18 @@ -// R4D attention dispatch for the Gemma 4 dense model's sliding-window geometry: head_dim 256, -// 2 queries per KV head, paged block 16, and a SLIDING WINDOW (window 1024 in the model, 50 of its -// 60 layers). It is the same device code as the 27B target's h256/gqa6 dispatch -- the kernels are -// templates on head_dim and gqa, so this file is another set of instantiations, not a second -// kernel -- with the window bit (template arg WIN) turned on, the way the DFlash2 drafter leg does -// it at head_dim 128. +// R4D attention dispatch for Gemma 4 dense's sliding-window layers: head_dim 256, 2 queries per KV +// head, paged block 16, window 1024 (50 of 60 layers). Instantiations of the h256/gqa6 kernel +// templates with WIN = 1, as the DFlash2 drafter leg does at head_dim 128. // -// Both bands, now. The decode band (q_len * gqa <= 64, i.e. q_len <= 32 at gqa 2) is the -// windowed decode kernel above. The prefill band (a query long enough to want the query-tiled -// prefill kernel) is the windowed prefill kernel below -- the same r4d_attn_prefill_kernel the -// h256/gqa6 dispatch instantiates, with the window bit (template arg WIN) turned on, the way the -// decode leg does. A trunk layer prefills, so it needs the prefill band on the device: -// libref is an opt-in fallback the engine refuses by default (spec §17). The drafter leg is -// decode-only because a drafter never prefills. +// Both bands: decode (q_len * gqa <= 64, so q_len <= 32) and the query-tiled prefill kernel. Unlike +// the drafter leg, a trunk layer prefills, and the libref fallback is opt-in and refused by +// default (spec §17). #include "r4d.h" #include "r4d_attn_args.h" #include "r4d_common.h" #include #include using std::max; -// The decode and prefill kernels share their query conversion and fragment helpers, so the prefill -// header comes first here for the same reason it does in the h256 dispatch. This translation unit -// instantiates BOTH r4d_attn_prefill_kernel (below, WIN=1) and the windowed decode kernel. +// The decode kernel uses helpers from the prefill unit, so prefill is included first. Both kernels +// are instantiated here with WIN = 1. #include "r4d_attn_prefill_h256_gqa6.hip" #include "r4d_attn_decode_h256_gqa6.hip" @@ -29,110 +21,26 @@ using std::max; #define B_HEAD_DIM 256 #define B_GQA 2 #define B_BLOCK_SIZE 16 -#define B_MAX_DECODE_ROWS 64 // q_len * gqa a single decode workgroup can hold -#define B_TILE 16 -// The same option set the h256 decode kernel ships, K prefetch of 2 included. At head_dim 256 it -// is the same register picture gqa6 has (256 VGPRs with a small spill), so this is a correctness -// instantiation here -- the register count is a 3b tuning question, not a 3a one. The window bit -// is already in the template; this file only turns it on. +#define B_TILE 16 // decode: r4d_decode_launch_win (r4d_attn_decode_h256_gqa6.hip) +// The h256 decode option set, K prefetch 2 included. Same register use as gqa6 (256 VGPRs, small +// spill); not separately tuned for this geometry. #define B_OPT 3429947 -#ifndef B_JPB -#define B_JPB 2 -#endif -#ifndef B_VECMIN -#define B_VECMIN 256 -#endif - -// Split law, the drafter leg's with the same window-aware term. It aims at 192 workgroups, snaps -// DOWN to a power of two but never below 16, clamps to at least two tiles a segment, and then steps -// UP off the exact grid size `splits * units == 256`, a pothole in this geometry's timing. -// -// THE WINDOW-AWARE TERM is the one thing it does that the h256 full-attention law does not: under a -// sliding window the context the kernel actually walks is the window, not the sequence, so the tile -// count that feeds the machine-fill target and the thin-segment clamp comes from the window. -// Without that the law reads a 16K sequence and asks for segments two tiles deep off a 1024-token -// walk. -static int decode_splits_h256_gqa2(const R4DArgs* a) { - if (a->splits > 0) return a->splits; - const int span = (a->window > 0 && a->window + a->q_len < a->max_ctx) - ? a->window + a->q_len : a->max_ctx; - const int tiles = (span + B_TILE - 1) / B_TILE; - const int units = std::max(1, a->kv_heads * a->num_seqs); - const int raw = 192 / units; - int s = 128; - while (s > 16 && s > raw) s >>= 1; - const int cap = tiles / 2; - while (s > 16 && s > cap) s >>= 1; - if (s > tiles) s = tiles; - if (s < 1) s = 1; - if (s * units == 256 && s * 2 <= tiles) s <<= 1; // step off the pothole, see above - return s; -} extern "C" long r4d_attn_decode_h256_gqa2_scratch_bytes(const R4DArgs* a) { - const int splits = decode_splits_h256_gqa2(a); - const long rows = (long)r4d_q_total(*a) * a->q_heads; - return (B_OPT & 32) ? rows * splits * (long)(a->head_dim * 2 + 8) - : rows * splits * (long)(a->head_dim + 2) * 4L; -} - -template -static int decode_launch_h256_gqa2(const R4DArgs* a, hipStream_t s) { - if (a->head_dim != B_HEAD_DIM || a->block_size != B_BLOCK_SIZE) return -1; - if (a->q_heads / a->kv_heads != B_GQA) return -2; - const int rows = a->q_len * B_GQA; - if (rows > B_MAX_DECODE_ROWS) return -4; - const int nw = (rows + 15) / 16; - const int splits = decode_splits_h256_gqa2(a); - -#define B_LAUNCH(NW) \ - hipLaunchKernelGGL((r4d_attn_decode_kernel), \ - dim3(splits, a->kv_heads, a->num_seqs), dim3(NW * 32), 0, s, *a, splits) - if (nw == 1) B_LAUNCH(1); - else if (nw == 2) B_LAUNCH(2); - else if (nw == 3) B_LAUNCH(3); - else B_LAUNCH(4); -#undef B_LAUNCH - CHK4(); - - // Same two merge forms, and the same rule for choosing between them, as the h256 dispatch: - // a wave a row while there are enough rows to fill the part and the segment count fits a - // wave, the general LDS-tree form otherwise. Both produce the same bytes, and both carry the - // window bit here (the final template argument) for the same reason the decode kernel does. - const int jobs3 = r4d_q_total(*a) * a->q_heads; - if (splits <= 64 && jobs3 >= B_VECMIN) { - const int blocks = (jobs3 + B_JPB - 1) / B_JPB; - if (B_OPT & 32) - hipLaunchKernelGGL((r4d_attn_splitkv_combine_vec_kernel), - dim3(blocks), dim3(32 * B_JPB), 0, s, *a, splits, B_TILE); - else - hipLaunchKernelGGL((r4d_attn_splitkv_combine_vec_kernel), - dim3(blocks), dim3(32 * B_JPB), 0, s, *a, splits, B_TILE); - } else if (B_OPT & 32) - hipLaunchKernelGGL((r4d_attn_splitkv_combine_kernel), dim3(jobs3), - dim3(B_HEAD_DIM), splits * sizeof(float), s, *a, splits, B_TILE); - else - hipLaunchKernelGGL((r4d_attn_splitkv_combine_kernel), dim3(jobs3), - dim3(B_HEAD_DIM), splits * sizeof(float), s, *a, splits, B_TILE); - CHK4(); - return 0; + return r4d_decode_scratch(a, r4d_decode_splits_win(a, B_TILE), B_OPT); } extern "C" int r4d_attn_decode_h256_gqa2_fp8kv(const R4DArgs* a, hipStream_t s) { - return decode_launch_h256_gqa2<0>(a, s); + return r4d_decode_launch_win(a, s); } extern "C" int r4d_attn_decode_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t s) { - return decode_launch_h256_gqa2<1>(a, s); + return r4d_decode_launch_win(a, s); } // ---- prefill --------------------------------------------------------------------------------- -// The h256/gqa6 prefill option set (P_OPT 3955211) is reused unchanged: at head_dim 256 the wide K -// fetch (O_KWIDE) is valid -- it is written for 16 channels = head_dim 256 exactly, and a wider head -// would read past the tile -- so this leg keeps it. gqa 2 makes -// BLOCK_Q (NWARPS*16/2 = 192) larger than gqa 6's 64, so a workgroup covers more query positions: -// fewer grid.x blocks, the same KV tile. WIN is on (the last template arg); window <= 0 folds it -// away to the full-attention form, so a windowless launch is safe. +// The h256/gqa6 prefill option set but at K prefetch 4 (P_OPT there is 3954187); O_KWIDE is valid +// at head_dim 256. At gqa 2 a block covers NWARPS * 16 / 2 = 192 query positions. WIN is on; +// window <= 0 gives full attention. #define P_NWARPS 24 #define P_TILE 48 #define P_OPT 3955211 @@ -157,9 +65,8 @@ extern "C" int r4d_attn_prefill_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t s return prefill_launch_h256_gqa2<1>(a, s); } -/* The prefill RadArgs wrappers, defined here (not in the h256 dispatch): an entry point appended to - * a textual inclusion compiles into nothing. - * Absent descales mean 1.0 (fill_paged leaves them null and the kernel reads 1.0). */ +/* Prefill RadArgs wrappers, defined in this unit rather than the h256 dispatch. Absent descales + * mean 1.0 (fill_paged leaves them null). */ extern "C" int r4d_rad_attn_prefill_h256_gqa2_fp8(const RadArgs* a, RadStream s) { R4DArgs r; int rc = fill_paged(a, &r, B_HEAD_DIM); diff --git a/libr4d/r4d_attn_paged_h256_gqa4.hip b/libr4d/r4d_attn_paged_h256_gqa4.hip index 133654a3..25576018 100644 --- a/libr4d/r4d_attn_paged_h256_gqa4.hip +++ b/libr4d/r4d_attn_paged_h256_gqa4.hip @@ -1,19 +1,13 @@ -// R4D attention at FOUR queries per KV head, head_dim 256 -- Qwen3.5-0.8B and its siblings that -// keep the 27B's head width with fewer heads (8 query heads over 2 KV heads). +// R4D attention at four queries per KV head, head_dim 256: Qwen3.5-0.8B and siblings (8 query heads +// over 2 KV heads). Geometry only; r4d_attn_paged_gqa8.hip is the body. The ratio changes two +// bounds, both stated in the row table: // -// The geometry and the dispatch only, as r4d_attn_paged_h256_gqa12.hip is: r4d_attn_paged_gqa8.hip -// is the parameterised body and its kernels are templates on `gqa`. What the ratio changes is the -// two bounds, and both are in the ROW table rather than here: +// decode verify width 64 / gqa = 16. +// prefill block width 384 / gqa = 96 query positions. // -// the decode verify width 64 / gqa = 16, against 8 at gqa 8 and 10 at gqa 6. A workgroup holds -// 64 (query, head) rows and carries q_len * gqa of them. -// a prefill block's width 384 / gqa = 96 query positions, against 48 at gqa 8. -// -// NO head_dim 128 LEG. gqa 4 at 128 is the DFlash2 drafter's windowed geometry, which -// r4d_attn_paged_h128_gqa4.hip serves; R4D_ATTN_H128 leaves those entry points out of this unit. -// A head_dim 64 PREFILL leg, for LFM2 (32 query heads over 8, d1-3B among them), which serves -// every query length: the split-KV decode kernel has no 64-wide form. -// The page is the body's default 16. +// No head_dim 128 leg: gqa 4 at 128 is the DFlash2 drafter's windowed geometry, served by +// r4d_attn_paged_h128_gqa4.hip. A head_dim 64 prefill leg serves LFM2 (32 query heads over 8) at +// every query length, since the split-KV decode kernel has no 64-wide form. Page size 16. #define R4D_ATTN_GQA 4 #define R4D_ATTN_H128 0 #define R4D_ATTN_H64 1 diff --git a/libr4d/r4d_attn_paged_h256_gqa6.hip b/libr4d/r4d_attn_paged_h256_gqa6.hip index b6a67c85..947612a1 100644 --- a/libr4d/r4d_attn_paged_h256_gqa6.hip +++ b/libr4d/r4d_attn_paged_h256_gqa6.hip @@ -1,24 +1,20 @@ -// R4D attention dispatch. One translation unit so the KV-dtype variants share the device code: -// each is a template instantiation, not a copy. The entry points are named for the geometry they -// are compiled for (head_dim 256, 6 queries per KV head, paged block 16) because that geometry is -// a hard gate -- everything else is rejected below rather than run. +// R4D paged attention dispatch for head_dim 256, 6 queries per KV head, paged block 16. The +// KV-dtype variants are template instantiations of one device code. The geometry is a hard gate: +// anything else is rejected. // -// The query is bf16 in every variant. A single-term 8-bit query is an order of magnitude worse -// against an fp32 reference (2.58e-02 relative against ~2.3e-03), and the two-term e4m3 form that -// DOES reach f16 accuracy is 4-10% slower end to end, so no 8-bit query variant is compiled. Two -// families ship, differing only in KV cache dtype: bf16 KV (all 16-bit) and fp8 KV (16/8 mixed, -// the production configuration). +// The query is bf16 in every variant. A single-term 8-bit query is ~10x less accurate against an +// fp32 reference (2.58e-02 vs ~2.3e-03 relative), and the two-term e4m3 form that reaches f16 +// accuracy is 4-10% slower end to end. Two families ship, differing in KV dtype: bf16 and fp8 +// (the production configuration). // -// `opt` is a bitmask of the optimisation steps, all of them on: +// `opt` is a bitmask of optimisation steps: // prefill 3954187 = f16 operands | mask skip | folded query scale | contiguous-k fragments // | prefetch 2 + scheduling barrier | dot2 row sum | block table in SGPRs // | wide K fetch | V prefetch across the m-tile loop | LDS-scoped barrier -// decode 3429947 = the same, minus the wide K fetch (its K never reaches LDS), with the K -// prefetch at 2 rather than 4, plus reading K straight from the paged cache -// (bit 16) and f16 split-KV partials (32). -// Each bit is defined and justified where it is used, in r4d_attn_prefill_h256_gqa6.hip and -// r4d_attn_decode_h256_gqa6.hip. -// They are kept separable so any one of them can be turned off on its own after a geometry change. +// decode 3429947 = the same minus the wide K fetch (its K never reaches LDS), plus K read +// straight from the paged cache (bit 16) and f16 split-KV partials (32). +// Each bit is defined where it is used (r4d_attn_prefill_h256_gqa6.hip, +// r4d_attn_decode_h256_gqa6.hip) and can be turned off on its own after a geometry change. #include "r4d.h" #include "r4d_attn_args.h" #include "r4d_common.h" @@ -30,9 +26,8 @@ using std::max; #define CHK() do { hipError_t e_ = hipGetLastError(); if (e_ != hipSuccess) return -100 - (int)e_; } while (0) -// The geometry every kernel in this translation unit is compiled for. HEAD_DIM and GQA appear in -// the entry-point names; BLOCK_SIZE does not, because it is 16 for the whole library and so -// discriminates nothing between them. +// The geometry of every kernel in this unit. BLOCK_SIZE is not in the entry-point names because +// it is 16 for all of them. #define A_HEAD_DIM 256 #define A_GQA 6 #define A_BLOCK_SIZE 16 @@ -46,13 +41,12 @@ extern "C" void r4d_attn_dims(int* head_dim, int* gqa, int* block_size, int* max } // ---- prefill --------------------------------------------------------------------------------- -// LDS, head_dim 256, 16-bit K and V: sK = TILE*264*2, sV = 256*(TILE+8)*2. bf16 KV at TILE 64 -// would need 68096 B > 65536, so the geometry stops at 48. +// LDS at head_dim 256, 16-bit K and V: sK = TILE*264*2, sV = 256*(TILE+8)*2. TILE 64 would need +// 68096 B > 65536, so TILE is 48. #define P_NWARPS 24 #define P_TILE 48 -// K PREFETCH 2, NOT 4. Four fragments in flight hold more than the m-tile loop has to give at six -// waves a SIMD, and the loop then spills: LLVM 22 to 36 bytes a lane and LLVM 24 to 48, which cost -// LLVM 24 4% of the prefill. At 2 both compilers spill the same 20 bytes, outside the WMMA groups. +// K prefetch 2, not 4: four fragments in flight make the m-tile loop spill at six waves per SIMD +// (36-48 bytes per lane, ~4% of the prefill). At 2 the spill is 20 bytes, outside the WMMA groups. #define P_OPT 3954187 // KVP: 0 = fp8 e4m3 cache, 1 = bf16 cache. Reached only through the two named wrappers below. @@ -77,72 +71,23 @@ extern "C" int r4d_attn_prefill_h256_gqa6_bf16kv(const R4DArgs* a, hipStream_t s } // ---- decode ---------------------------------------------------------------------------------- -#ifndef D_TILE #define D_TILE 16 -#endif -// The decode leg prefetches TWO K fragments per WMMA group, not four. Four costs 8 more VGPRs at -// the peak of the QK loop and that is exactly the amount this kernel is over: it allocates 256 -// VGPRs, spills 18 of them, and reloads three 16-byte groups of the query FROM SCRATCH ON EVERY -// TILE. Two fits in 255 with no spill and is 1.7-7.5% faster across concurrency and depth, for -// bit-identical output. -#ifndef D_OPT +// Decode prefetches two K fragments per WMMA group, not four. Four costs 8 more VGPRs at the peak +// of the QK loop and spills 18, reloading part of the query from scratch on every tile. Two fits in +// 255 VGPRs and is 1.7-7.5% faster, with identical output. #define D_OPT 3429947 -#endif -// Output rows per block in the vectorised merge: 32 threads own a row, so this is the block width -// in waves. 1, 2 and 4 are within 1% of each other everywhere the vectorised form is taken; 2 is -// the best of them on average across concurrency and depth. -#ifndef D_JPB +// Output rows (waves) per block in the vectorised merge. 1, 2 and 4 are within 1%; 2 is best on +// average. #define D_JPB 2 -#endif -// Output rows below which the vectorised merge is NOT taken. It gives a row 32 lanes where the -// general form gives it 256, so it trades parallelism for eight-times-fewer load instructions -- -// and that trade is only good while there are enough rows to fill the part. At one request there -// are 96 rows and the segment count is at its largest (the split law scales splits with 1/num_seqs), -// so each of 96 waves walks 64 segments on an idle machine and the vectorised form LOSES up to -// 23%. The crossover is around 192 rows, and above 288 the vectorised form wins by 1.2-20%; the -// cut is set at four rows per CU. -#ifndef D_VECMIN +// Minimum output rows for the vectorised merge. It gives a row 32 lanes instead of 256, trading +// parallelism for 8x fewer loads, which pays only when there are enough rows to fill the GPU. At +// one request (96 rows, most segments) it loses up to 23%; the crossover is ~192 rows and above +// 288 it wins by 1.2-20%. The cut is four rows per CU. #define D_VECMIN 256 -#endif -// Split law: AS MANY WORKGROUPS AS FIT UNDER 128. `splits * kv_heads * num_seqs` is the whole -// grid, and 128 of them is the argmin at every concurrency this serve reaches on this geometry. -// -// THE COUNT IS `128 / units`, NOT THE LARGEST POWER OF TWO UNDER IT. A power of two lands exactly -// on 128 only when units is one too -- one, two, four and eight requests -- and at three, five, -// six and seven it lands on 96, 80, 96 and 112 workgroups instead, which is a third of the part -// idle in the last round. `floor(128 / units)` is the argmin at all eight, worth 2-20% over a -// power-of-two law at the four counts where they differ. -// -// Nearby counts are not interchangeable: at five requests 13 splits is 130 workgroups, three -// rounds of 64 for two rounds of work, and is slower than 12. UNDER a multiple of 64 is what -// matters, not near it. -// -// What the count buys is partial-buffer traffic, not parallelism. The split-KV scratch is -// `seqs x q_len x q_heads x splits` rows of head_dim f16, written once by the decode kernel and -// read back once by the combine: at eight requests that is 12.8 MB at splits 32 against 3.2 at 8, -// which is 19% of a 16K step's KV and 1.2% of a 128K one. So the win shrinks with depth -- a few -// percent up to 16K, under 2% at 64K and a wash at 128K -- and never reverses enough to be worth a -// context term. -static int decode_splits(const R4DArgs* a) { - if (a->splits > 0) return a->splits; - const int tiles = (a->max_ctx + D_TILE - 1) / D_TILE; - const int units = max(1, a->kv_heads * a->num_seqs); - int s = 128 / units; // as many workgroups as fit under 128 - const int cap = tiles / 2; // >= 2 tiles per segment - if (s > cap) s = cap; - if (s > tiles) s = tiles; - if (s < 1) s = 1; - return s; -} - -// Same for both cache dtypes: the split law does not read the dtype, and the partials are f16 -// either way (opt bit 32). +// Split law: r4d_decode_splits (r4d_attn_decode_h256_gqa6.hip). extern "C" long r4d_attn_decode_h256_gqa6_scratch_bytes(const R4DArgs* a) { - const int splits = decode_splits(a); - const long rows = (long)r4d_q_total(*a) * a->q_heads; - return (D_OPT & 32) ? rows * splits * (long)(a->head_dim * 2 + 8) // f16 O/l + m + l - : rows * splits * (long)(a->head_dim + 2) * 4L; // f32 O partials + m + l + return r4d_decode_scratch(a, r4d_decode_splits(a, D_TILE), D_OPT); } template @@ -152,7 +97,7 @@ static int decode_launch(const R4DArgs* a, hipStream_t s) { const int rows = a->q_len * A_GQA; if (rows > A_MAX_DECODE_ROWS) return -4; // verify width <= 10 at gqa 6 const int nw = (rows + 15) / 16; // gqa-aligned height; no dead m-tiles issued - const int splits = decode_splits(a); + const int splits = r4d_decode_splits(a, D_TILE); #define D_LAUNCH(NW) \ hipLaunchKernelGGL((r4d_attn_decode_kernelq_heads; if (splits <= 64 && jobs3 >= D_VECMIN) { const int blocks = (jobs3 + D_JPB - 1) / D_JPB; @@ -198,14 +141,11 @@ extern "C" int r4d_attn_decode_h256_gqa6_bf16kv(const R4DArgs* a, hipStream_t s) // ============================================================== the plugin ABI entry points // -// The operand reader is r4d_attn_args.h, a header this kernel family shares because the paged -// geometries implement one op and take one operand list. See libr4d/r4d_args.h for why there is no -// adapter directory between the core and these launches. +// The operand reader is r4d_attn_args.h, shared by every paged geometry. // -// THEY GO IN THE TRANSLATION UNIT AND NOT IN THE FILES IT #includes. r4d_attn_prefill_*.hip and -// r4d_attn_decode_*.hip are textual inclusions of this one -- appending an entry point to either -// compiles it into nothing, and the .so then carries an UNDEFINED symbol that no build step -// reports. The plugin still links; only r4d_selftest catches the missing symbol. +// Note: entry points belong in this translation unit, not in the r4d_attn_prefill_*.hip or +// r4d_attn_decode_*.hip files it includes. An entry point added there does not get compiled, and +// the .so carries an undefined symbol that only r4d_selftest catches. /* ------------------------------------------------------------------ paged prefill */ extern "C" int r4d_rad_attn_prefill_h256_fp8(const RadArgs* a, RadStream s) { @@ -213,13 +153,10 @@ extern "C" int r4d_rad_attn_prefill_h256_fp8(const RadArgs* a, RadStream s) { R4DArgs r; int rc = fill_paged(a, &r, 256); if (rc != RAD_OK) return rc; - /* ABSENT DESCALES MEAN 1.0, they are not an error. The kernels already spell it that way -- - * `a.k_descale ? a.k_descale[seq * kv_heads + kvh] : 1.0f` -- and 1.0 is what vLLM defaults - * both scales to, so a cache written by kv_store_fp8 at its default scale is read back by - * exactly this path with no descale plane to allocate, fill or keep in step. Refusing here - * would make the operands mandatory in the shim while they stay optional in the schema and - * optional in the kernel, which is three answers to one question. A CALIBRATED pair still - * works: pass the operands and they are used. */ + /* Absent descales mean 1.0, not an error: the kernels read them that way, vLLM defaults both + * scales to 1.0, and kv_store_fp8 at its default scale needs no descale plane. The operands + * are optional in the schema and the kernel, so they are optional here too. A calibrated pair + * is used when passed. */ return r4d_attn_prefill_h256_gqa6_fp8kv(&r, (hipStream_t)s); } @@ -233,30 +170,19 @@ extern "C" int r4d_rad_attn_prefill_h256_bf16(const RadArgs* a, RadStream s) { /* ------------------------------------------------------------------ paged decode */ -/* The split-KV partial buffer. The decode kernel writes it and the combine reads it back, and - * nothing else touches it -- so it is arena scratch, sized at declare from the band's upper bound - * exactly as RadScratchFn intends. +/* Split-KV partial buffer: written by the decode kernel, read by the combine, nothing else. Arena + * scratch sized at declare from the band's upper bound (RadScratchFn). * - * IT IS CALLED WITH PARAMETERS AND NO TENSORS. That is what declare is: the op is known, the batch - * is not, and there is nothing to point at yet. So the parameters are the primary source here and - * the tensors are the fallback, not the other way round -- reading tensors first makes this hook - * refuse every attn_paged row in the model with "invalid argument", which presents as a pile of - * missing kernels rather than as one hook asking the wrong question. + * Declare passes parameters and no tensors (the batch is not known yet), so parameters are the + * primary source and tensors the fallback. Reading tensors first would refuse every attn_paged + * row with "invalid argument". q_len is the band's upper bound, since the region is sized once + * for the worst step. * - * q_len is the band's upper bound, deliberately: this region is sized once for the worst step the - * arena will ever hold, so the bound is the right number and a per-step count would be the wrong - * one. - * - * THE SEQUENCE COUNT IS EVERY COUNT UP TO max_seqs, NOT max_seqs ALONE. Both split laws hand a - * step of S sequences a split count that falls as S grows -- about 128 / (kv_heads * S) -- so the - * partials are S * splits(S) rows a (query position, head), and that product is not monotone in - * S: at kv_heads 2 the h256 law gives 60 at twelve sequences and 63 at nine, and the h128 law's - * step off its pothole doubles the splits at one count and not at the next. A step may carry any - * count up to the bound, so the region is the largest over all of them. The laws are closed forms - * and this runs at declare, so the sweep costs nothing a step. */ -// One hook per geometry but one shared (seqs x heads x rows) partial layout, so the worst-over- -// the-batch sweep below asks each geometry its own bytes in one place instead of triplicating the -// sweep. which: 0 = h256/gqa6, 1 = h128/gqa4, 2 = h256/gqa2 (the Gemma 4 windowed leg). + * The size is the maximum over every sequence count up to max_seqs: S * splits(S) is not monotone + * in S (at kv_heads 2 the h256 law gives 60 at twelve sequences and 63 at nine, and the h128 law's + * step-up doubles splits at one count only). The laws are closed forms, so the sweep is cheap. */ +// Per-geometry byte counts over the shared partial layout, so one sweep serves all. +// which: 0 = h256/gqa6, 1 = h128/gqa4, 2 = h256/gqa2 (Gemma 4 windowed). static int64_t decode_scratch_bytes_of(const R4DArgs* r, int which) { if (which == 1) return (int64_t)r4d_attn_decode_h128_gqa4_scratch_bytes(r); if (which == 2) return (int64_t)r4d_attn_decode_h256_gqa2_scratch_bytes(r); @@ -281,8 +207,8 @@ static int64_t decode_scratch(const RadArgs* a, int head_dim, int which) { r.max_ctx = (int)r4d_geti_or(a, "max_ctx", 0); r.block_size = (int)r4d_geti_or(a, "block_size", 16); r.splits = sp; - /* max_ctx feeds the split law only. Zero would make it choose one split, which UNDERSIZES - * the buffer for the launch that later picks more, so refuse rather than guess low. */ + /* max_ctx feeds only the split law. Zero would pick one split and undersize the buffer + * for a launch that later picks more, so refuse. */ if (r.max_ctx <= 0) return R4D_NO(RAD_E_INVAL); int64_t worst = 0; for (long long n = 1; n <= max_seqs; ++n) { @@ -350,10 +276,9 @@ extern "C" int r4d_rad_attn_decode_h128_bf16(const RadArgs* a, RadStream s) { return r4d_attn_decode_h128_gqa4_bf16kv(&r, (hipStream_t)s); } -/* Gemma 4 dense sliding window -- head_dim 256, 2 queries per KV head, window 1024. Decode only; - * a prefill step does not match the row's q_len band and takes the caller's (windowed) fallback. - * Same shape as the drafter leg above (h128): one `which` routing to the gqa2 scratch law and the - * gqa2 decode launch, no check_dims_once because this is not the geometry that reports dims. */ +/* Gemma 4 dense sliding window (head_dim 256, gqa 2, window 1024) decode; its prefill entry points + * are in r4d_attn_paged_h256_gqa2.hip. No check_dims_once: this is not the geometry that reports + * dims. */ extern "C" int64_t r4d_rad_attn_decode_h256_gqa2_scratch(const RadArgs* a) { return decode_scratch(a, 256, 2); } diff --git a/libr4d/r4d_attn_paged_h256_gqa6_bs4.hip b/libr4d/r4d_attn_paged_h256_gqa6_bs4.hip index 35662959..6330c1bd 100644 --- a/libr4d/r4d_attn_paged_h256_gqa6_bs4.hip +++ b/libr4d/r4d_attn_paged_h256_gqa6_bs4.hip @@ -1,44 +1,23 @@ -// R4D attention at SIX queries per KV head, head_dim 256 -- the same QSA layers of -// Qwen3.8-Flash-Next that r4d_attn_paged_h256_gqa12.hip serves at two ranks, served at FOUR: the -// two KV heads are replicated across the rank pairs, so each rank answers 6 queries for the one KV -// head it holds and the ratio the constraint table gates on is 6 rather than 12. +// R4D attention at six queries per KV head, head_dim 256: Qwen3.8-Flash-Next's QSA layers at four +// ranks (r4d_attn_paged_h256_gqa12.hip serves them at two). The two KV heads are replicated across +// rank pairs, so each rank serves 6 queries for its one KV head. Geometry only; +// r4d_attn_paged_gqa8.hip is the body. The ratio changes two bounds, both stated in the row table: // -// Four lines of geometry and the dispatch itself, because r4d_attn_paged_gqa8.hip's kernels are -// templates on `gqa` and that unit is the parameterised body. What the ratio changes is -// exactly two bounds, and both are in the ROW table rather than here: +// decode verify width 64 / gqa = 10. MTP's K=3 verify (q_len 4) fits either ratio; a draft +// block of six or seven positions fits decode here but not at gqa 12. +// prefill block width 384 / gqa = 64 query positions. // -// the decode verify width 64 / gqa = 10, against 5 at gqa 12 and 8 at gqa 8. A workgroup holds -// 64 (query, head) rows and carries q_len * gqa of them, so this is -// the WIDEST of the three legs: MTP's K=3 verify is q_len 4 and fits -// either ratio, and a draft block of six or seven positions -- which -// the gqa12 leg has to send to the prefill kernel -- fits the decode -// kernel here. -// a prefill block's width 384 / gqa = 64 query positions, against 32 at gqa 12 and 48 at -// gqa 8. -// -// NO head_dim 128 LEG, for the gqa12 file's reason: nothing in scope is gqa 6 at 128, and an -// instantiation nothing resolves is a kernel nobody has run. R4D_ATTN_H128 leaves those four entry -// points out of this translation unit entirely rather than shipping them untested. +// No head_dim 128 leg: nothing in scope is gqa 6 at 128, so those entry points are not built. #define R4D_ATTN_GQA 6 #define R4D_ATTN_H128 0 -// THE KV PAGE IS FOUR TOKENS HERE, as in the gqa 12 unit; every other geometry in this library -// pages at 16. +// KV page of 4 tokens, as in the gqa12 unit (the model's page; TP4 changes only queries per head). +// The QSA indexer selects 4-token blocks, so a selected block is a page and sparse attention is +// this kernel with a different block table (docs/QSA.md). The only cost is reading NB = TILE / BS +// table entries per tile, within step noise; output is identical. // -// Qwen3.8-Flash-Next's QSA indexer selects 4-TOKEN BLOCKS of the key history. With a page of 4 a -// selected block IS a page, so the selection is a paged block table and the sparse attention is -// this kernel with a different table -- instead of a new attention kernel, which is the most -// expensive kind of kernel in this tree to get right. docs/QSA.md is the decomposition. The page -// is 4 at this ratio for exactly the reason it is 4 at gqa 12 -- the model's page, not the -// parallelism's; what TP4 changes is the queries a head, not the storage. -// -// IT COSTS NOTHING. A page size is pure storage, so the only thing it can move is the block-table -// walk -- `NB = TILE / BS` entries a tile instead of one, four instead of one at TILE 16 -- and at -// a realistic context that is inside the noise of the step, with identical output either way. -// -// THE ROWS HAVE TO AGREE. `C_EQ("block_size", 4)` on all four gqa6-bs4 rows is what makes the core -// size the pages at 4 (RadKVGroupDecl carries no block size on purpose -- it is taken off the -// resolved kernel). A row that says 16 against this define is a kernel that refuses at issue -// rather than at declare. +// Note: the rows must agree. C_EQ("block_size", 4) on all four gqa6-bs4 rows makes the core size +// the pages at 4 (RadKVGroupDecl takes the block size from the resolved kernel). A row saying 16 +// here would refuse at issue rather than at declare. #define G8_BLOCK_SIZE 4 #include "r4d_attn_paged_gqa8.hip" diff --git a/libr4d/r4d_attn_paged_window.hip b/libr4d/r4d_attn_paged_window.hip index c28d25d5..7a1056a5 100644 --- a/libr4d/r4d_attn_paged_window.hip +++ b/libr4d/r4d_attn_paged_window.hip @@ -1,22 +1,20 @@ /* r4d_attn_paged_window.hip -- paged attention at head_dim 256 and 512, 1/2/4/8 queries per KV - * head, ANY sliding window, causal or not, bf16 or fp8-e4m3 cache, q at any row pitch. + * head, any sliding window, causal or not, bf16 or fp8-e4m3 cache, q at any row pitch. * - * Gemma 4's text layers are two of these geometries: its sliding layers are 16 query heads over 8 - * KV heads at head_dim 256 with a 1024-token window (gqa 2 at every TP), and its full layers 16 - * over 2 at head_dim 512 (gqa 8 at TP1/TP2, 4 at TP4, 2 at TP8). The library's other h256 legs are - * gqa 2 (windowed, q dense) and gqa 4/6/8/12 (`window == 0`); the row table says which serves - * where two meet (r4d_rows.cpp). + * Gemma 4's text layers: sliding layers are 16 query heads over 8 KV heads at head_dim 256 with a + * 1024-token window (gqa 2 at every TP); full layers are 16 over 2 at head_dim 512 (gqa 8 at + * TP1/TP2, 4 at TP4, 2 at TP8). Where this overlaps the library's other h256 legs, the row table + * decides (r4d_rows.cpp). * - * WHAT THIS IS. Two kernels behind one entry point. The scalar one, for decode and verify steps: one - * workgroup owns one (sequence, KV head, slice of BQ query positions, split of the key range); each - * wave owns RW of the tile's R = BQ*gqa query rows; K and V come through LDS one paged block (or - * two) at a time, prefetched into registers while the previous tile is being consumed; the dot - * products are scalar FMAs with a butterfly reduce-scatter that leaves key j's score in lane j; the - * softmax is online, in the log2 domain. It is memory-bound at decode, where that is the only thing - * that matters. A prefill-shaped launch takes the WMMA kernel further down instead (its own header - * says how), which feeds RDNA4's matrix cores. + * Two kernels behind one entry point: + * - Scalar, for decode and verify: a workgroup owns one (sequence, KV head, slice of BQ query + * positions, split of the key range); each wave owns RW of the tile's R = BQ*gqa query rows. + * K/V go through LDS one or two paged blocks at a time, prefetched into registers while the + * previous tile is consumed. Dot products are scalar FMAs with a butterfly reduce-scatter that + * leaves key j's score in lane j; online softmax in the log2 domain. Memory-bound at decode. + * - WMMA, for prefill-shaped launches (see its header below). * - * WHAT IT COMPUTES is libref's ref_attn_paged, predicate for predicate: + * Both compute libref's ref_attn_paged, predicate for predicate: * pos = seqused[s] - q_len(s) + i (seqused INCLUDES this step's queries) * causal key j visible when j <= pos; non-causal when j < seqused[s] * window causal: pos - j < window; non-causal: |pos - j| < window; 0 = none @@ -24,16 +22,15 @@ * no visible key at all -> a zero row * k_descale / v_descale per (sequence, kv head), absent = 1 * - * THE PAGED LAYOUT is kv_cache[n_blocks, kv_heads, 16, 2*head_dim], K then V inside a slot, which - * makes one block of one KV head ONE contiguous run of 16 * 2 * head_dim elements: a key tile is - * one or two such runs, fetched as 16-byte loads. + * Paged layout: kv_cache[n_blocks, kv_heads, 16, 2*head_dim], K then V per slot, so one block of + * one KV head is a contiguous run of 16 * 2 * head_dim elements; a key tile is one or two runs, + * fetched as 16-byte loads. * - * SPLIT-KV. A launch with few (tile, kv head) pairs -- a decode step, a short verify -- would leave - * most of the card idle, so the key range of each tile is cut into `n_split` pieces, each written - * as an unnormalised partial (acc, max, sum) into the op's scratch, and a second kernel merges - * them. The split count is chosen at launch from host-side numbers only (rows, sequences, the - * window or max_ctx); each workgroup divides ITS OWN key range by it, so a split that receives no - * keys writes (0, -inf, 0) and the merge needs no host knowledge of the device-side context. + * Split-KV: with few (tile, kv head) pairs (decode, short verify) each tile's key range is cut into + * `n_split` pieces, each writing an unnormalised partial (acc, max, sum) to scratch, merged by a + * second kernel. The split count comes from host-side numbers only (rows, sequences, window or + * max_ctx); each workgroup divides its own key range, so a split with no keys writes (0, -inf, 0) + * and the merge needs no device-side context. * * Nothing here allocates, synchronises, or uses anything but hipLaunchKernel (docs/PLUGIN.md §5). * Wave32 (RDNA): the shuffles and the reduce-scatter are written for 32 lanes. @@ -56,16 +53,15 @@ namespace r4d_win { constexpr int kThreads = 256; constexpr int kWaves = kThreads / 32; -/* split-KV bookkeeping: at most this many (tile, kv head, split) triples carry partials, and the - * tile table behind them holds at most kTinfoMax tiles. The launch keeps under both by - * construction; the scratch hook sizes for exactly these. */ +/* Split-KV bookkeeping: at most kPartBudget (tile, kv head, split) triples carry partials and the + * tile table holds at most kTinfoMax tiles. The launch stays under both; scratch is sized for them. */ constexpr int kPartBudget = 192; constexpr int kTinfoMax = 128; constexpr int kMaxSplit = 64; template struct Geo; -/* R query rows a workgroup (R / 8 a wave), BK keys a tile. BK * 2 * HD bf16 = 32 KiB of LDS either - * way: two paged blocks at 256, one at 512. */ +/* R query rows per workgroup (R / 8 per wave), BK keys per tile. BK * 2 * HD bf16 = 32 KiB of LDS + * either way: two paged blocks at 256, one at 512. */ template <> struct Geo<256> { static constexpr int R = 32, BK = 32; }; template <> struct Geo<512> { static constexpr int R = 16, BK = 16; }; @@ -102,10 +98,9 @@ __device__ __forceinline__ float ex2(float x) { __device__ __forceinline__ int imin(int a, int b) { return a < b ? a : b; } __device__ __forceinline__ int imax(int a, int b) { return a > b ? a : b; } -/* f(Ic<0>{}), ..., f(Ic{}): a loop whose index is a CONSTANT in every body, unconditionally. - * `#pragma unroll` is a request the unroller drops past a size threshold -- the fp8 legs of the - * row loop crossed it -- and a register array indexed by a loop variable that survives is demoted - * to scratch memory. This cannot be dropped. */ +/* f(Ic<0>{}), ..., f(Ic{}): a loop whose index is a compile-time constant in every body. + * `#pragma unroll` is dropped past a size threshold (the fp8 row loop crosses it), and a register + * array indexed by a surviving loop variable is demoted to scratch. This guarantees the unroll. */ template struct Ic { static constexpr int value = I; }; template struct StaticFor { template __device__ __forceinline__ static void run(F& f) { @@ -122,7 +117,7 @@ __device__ __forceinline__ void bf16x4(uint2 w, float (&f)[4]) { f[2] = __uint_as_float(w.y << 16); f[3] = __uint_as_float(w.y & 0xffff0000u); } -/* OCP E4M3 (e4m3fn, bias 7, 0x7f/0xff NaN, no infinity) -- the KV cache's bytes at +/* OCP E4M3 (e4m3fn, bias 7, 0x7f/0xff NaN, no infinity), the KV cache format at * --kv-cache-dtype fp8 (docs/PLUGIN.md §10). Exact; subnormals kept. */ __device__ __forceinline__ float fp8e4m3(unsigned b) { const unsigned e = (b >> 3) & 15u, m = b & 7u; @@ -132,8 +127,7 @@ __device__ __forceinline__ float fp8e4m3(unsigned b) { } __device__ __forceinline__ void fp8x4(unsigned w, float (&f)[4]) { #if defined(__GFX12__) - /* v_cvt_pk_f32_fp8: RDNA4 converts OCP E4M3 in hardware, two bytes an instruction -- the same - * instruction the library's other attention kernels read their fp8 cache with. */ + /* v_cvt_pk_f32_fp8: RDNA4 hardware OCP E4M3 conversion, two bytes per instruction. */ const auto a = __builtin_amdgcn_cvt_pk_f32_fp8((int)w, false); const auto b = __builtin_amdgcn_cvt_pk_f32_fp8((int)w, true); f[0] = a[0]; f[1] = a[1]; f[2] = b[0]; f[3] = b[1]; @@ -160,18 +154,17 @@ __device__ __forceinline__ void lds4(const unsigned char* row, int e, float (&f) else bf16x4(*(const uint2*)(row + 2 * e), f); } -/* THE REDUCE-SCATTER. Each lane holds a partial dot for every key of the tile; after it, lane l - * holds key l's full sum. Each step keeps the half of the vector its lane bit selects and adds the - * partner's copy of that half: 16 + 8 + 4 + 2 + 1 = 31 shuffles for 32 keys, against 32 * 5 for 32 - * separate reductions. */ +/* Reduce-scatter: each lane holds a partial dot for every key of the tile; afterwards lane l holds + * key l's full sum. Each step keeps the half its lane bit selects and adds the partner's copy: + * 16 + 8 + 4 + 2 + 1 = 31 shuffles for 32 keys, instead of 32 * 5 for separate reductions. */ template __device__ __forceinline__ void reduce_scatter(float (&v)[N], int lane) { if constexpr (H >= 1) { const bool up = (lane & H) != 0; #pragma unroll for (int i = 0; i < H; ++i) { - /* VALUES, not lvalues: `up ? v[i + H] : v[i]` selects between two ADDRESSES, and an - * array addressed by a lane-dependent pointer is demoted to scratch memory. */ + /* Select values, not lvalues: `up ? v[i + H] : v[i]` selects an address, and an array + * addressed by a lane-dependent pointer is demoted to scratch. */ const float lo = v[i], hi = v[i + H]; const float keep = up ? hi : lo; const float send = up ? lo : hi; @@ -197,10 +190,9 @@ struct AttnArgs { int max_blocks, n_seq, q_len, tps, kv_heads, causal, window, n_split; }; -/* Tile `tile` of a ragged batch: the sequence it belongs to and which BQ-position slice of that - * sequence's query it is. Tiles are numbered sequence by sequence, ceil(q_len(s) / BQ) each, so the - * answer is a prefix sum over cu_seqlens -- done by the whole block, 256 sequences a pass. Every - * thread returns the same answer: it is read back out of LDS after a barrier. */ +/* Tile `tile` of a ragged batch: its sequence and which BQ-position slice of that sequence's query + * it is. Tiles are numbered sequence by sequence, ceil(q_len(s) / BQ) each, so this is a block-wide + * prefix sum over cu_seqlens, NT sequences per pass. All threads get the same answer from LDS. */ template __device__ void find_tile(const int* cu, int n_seq, int tile, int* s_scan, int* s_res, int& s_out, int& lt_out) { @@ -336,9 +328,9 @@ __global__ __launch_bounds__(kThreads) void attn_kernel(AttnArgs A) { int blk = -1; if (lb < A.max_blocks && (lb << 4) < hi) blk = A.bt[(long long)s * A.bt_rs + lb]; pre_ok[b] = blk >= 0; - /* never a null: a select against null makes the pointer FLAT rather than global, and - * every tile load a flat_load. A missing block points at the cache's base and its - * value is replaced by zeros below. */ + /* Never null: selecting against null makes the pointer flat instead of global, and every + * tile load a flat_load. A missing block points at the cache base; its value is + * replaced by zeros below. */ src[b] = A.kv + ((long long)(blk >= 0 ? blk : 0) * A.kv_sb + (long long)kh * A.kv_sh) * ESZ; } #pragma unroll @@ -451,42 +443,33 @@ __global__ __launch_bounds__(kThreads) void attn_kernel(AttnArgs A) { /* ================================================================== the WMMA prefill kernel * - * WHY A SECOND KERNEL. The kernel above is scalar FMAs: right for decode, where a step is a few - * rows and the cache read is the whole cost, and about 8 TFLOP/s a card on a long prefill, where - * the global layers' attention is quadratic in the prompt and 46% of a 48k-token prefill. RDNA4's - * matrix cores do a 16x16x16 bf16 product a WMMA instruction; this kernel feeds them. It is chosen - * at launch for prefill-shaped steps only (a sequence with >= kWmmaMinQ query rows) and computes - * the same function, predicate for predicate. + * The scalar kernel reaches ~8 TFLOP/s on a long prefill, where global-layer attention is + * quadratic and 46% of a 48k-token prefill. This kernel uses RDNA4's 16x16x16 WMMA instead. It is + * chosen only for prefill-shaped steps (a sequence with >= kWmmaMinQ query rows) and computes the + * same function. * - * THE LAYOUTS (RDNA4, wave32, v_wmma_f32_16x16x16_bf16 -- confirmed against llama.cpp's mma.cuh, - * which runs on the card): A[M][K] gives lane L row M = L % 16 and K = 8 * (L / 16) .. + 7; B[K][N] - * gives lane L column N = L % 16 and the same K; the f32 result gives lane L column N = L % 16 and - * rows M = 8 * (L / 16) .. + 7. So the kernel computes S TRANSPOSED: S^T = K * Q^T puts each - * lane's eight values in ONE query row (row L % 16, keys 8h .. 8h + 7), the row's other eight keys - * in lane L ^ 16 -- the softmax statistics are one shuffle -- and those eight values, as bf16, are - * exactly the B operand of O^T = V^T * P^T. O^T's lane L likewise holds only row L % 16, so the - * online-softmax rescale is a per-lane scalar. + * Layouts (wave32 v_wmma_f32_16x16x16_bf16): A[M][K] gives lane L row M = L % 16 and + * K = 8 * (L / 16) .. + 7; B[K][N] gives lane L column N = L % 16, same K; the f32 result gives lane + * L column N = L % 16, rows M = 8 * (L / 16) .. + 7. So the kernel computes S^T = K * Q^T: each lane + * holds eight keys of one query row (row L % 16, keys 8h .. 8h + 7), the other eight are in lane + * L ^ 16 (softmax statistics are one shuffle), and those values as f16 are the B operand of + * O^T = V^T * P^T. O^T's lane L also holds only row L % 16, so the rescale is a per-lane scalar. * - * THE SPLIT. O^T for 16 rows of a 512-dim head is 256 f32 a lane -- the whole register file. So a - * wave owns 16 rows by a 128-dim slice of the head (kDQ): its Q^T (32 VGPRs) and O^T (64). The - * slices of one row group each compute S^T over their own dims; the partials meet in LDS and every - * slice sums them in the same order, so all of them see bit-identical scores and take identical - * softmax steps. 16 waves: h512 is 4 row groups of 4 slices (64 rows), h256 8 of 2 (128 rows). + * Head split: O^T for 16 rows of a 512-dim head is 256 f32 per lane, the whole register file, so a + * wave owns 16 rows by a 128-dim slice (kDQ): Q^T in 32 VGPRs, O^T in 64. Slices compute partial + * S^T over their own dims; partials meet in LDS and every slice sums them in the same order, so all + * see bit-identical scores. 16 waves: h512 is 4 row groups x 4 slices (64 rows), h256 8 x 2 (128). * - * THE TILE is one paged block, 16 keys. K goes to LDS as it is ([key][dim] bf16, a 16-byte pad a row - * so the A-fragment reads hit 32 different banks); V goes TRANSPOSED ([dim][key], rows of 48 - * bytes), since the PV product reduces over keys and an operand's eight K-values must be - * contiguous. The transposed write is two keys' dims packed a dword, the dword index rotated per - * lane group so a wave's 32 writes land in 32 banks. An fp8 cache is widened on the way in -- exact, - * e4m3 has 3 mantissa bits. Keys outside the tile's range or in a missing block are written as - * zeros: a probability of 0 times a NaN in a recycled slot is still NaN. + * Tile = one paged block, 16 keys. K goes to LDS as [key][dim] bf16 with a 16-byte row pad so + * A-fragment reads hit 32 banks. V goes transposed ([dim][key], 48-byte rows) because P.V reduces + * over keys; two keys are packed per dword with the dword index rotated per lane group so a wave's + * 32 writes hit 32 banks. An fp8 cache is widened on load (exact). Keys outside the range or in a + * missing block are written as zeros, since 0 * NaN from a recycled slot is still NaN. * - * P AND V IN f16, Q AND K IN bf16. The probabilities are rounded for the matrix product, and bf16's - * 8 bits leave 2^-9 of |v| in every output -- measured in the emulator against f64 at up to 0.25% - * of the V range, four times the scalar kernel's error. f16 runs at the same rate with 11 bits. V's - * bf16 values are exact in f16 between 2^-14 and 65504 (clamped beyond, NaN kept); an fp8 cache's - * are exact outright. The denominator sums the probabilities as rounded, so a row is a true - * weighted mean of V: a dominant key keeps weight 1 exactly. + * P and V in f16, Q and K in bf16: bf16 P leaves up to 2^-9 |v| error per output (up to 0.25% of the + * V range against f64, 4x the scalar kernel), while f16 runs at the same rate with 11 bits. bf16 V + * is exact in f16 within [2^-14, 65504] (clamped beyond, NaN kept); fp8 V is always exact. The + * denominator sums P as rounded, so a row is a true weighted mean of V. */ typedef short win_v8s __attribute__((ext_vector_type(8))); /* 8 bf16, as the builtin takes them */ typedef float win_v8f __attribute__((ext_vector_type(8))); @@ -733,9 +716,9 @@ __global__ __launch_bounds__(kWThreads) void attn_wmma_kernel(AttnArgs A) { #pragma unroll for (int e = 0; e < 8; ++e) sacc[e] = 0.0f; { - /* one accumulator: a second one hides the chain's latency but costs 12 VGPRs, and at - * 187 two 16-wave workgroups share a WGP (8 waves a SIMD, 1536 VGPRs) where at 200 - * one does -- the other waves hide the latency better */ + /* One accumulator: a second hides the chain latency but costs 12 VGPRs; at 187 VGPRs + * two 16-wave workgroups fit a WGP (8 waves per SIMD), at 200 only one, and the extra + * waves hide latency better. */ const unsigned char* ka = kb + n * KS + (sl * kDQ + 8 * h) * 2; #pragma unroll for (int kc = 0; kc < kDQ / 16; ++kc) @@ -813,12 +796,9 @@ __global__ __launch_bounds__(kWThreads) void attn_wmma_kernel(AttnArgs A) { /* ------------------------------------------------------------------ the split-KV merge * - * ONE WAVE A ROW, THE SPLITS ACROSS ITS LANES. Lane z reads split z's (max, sum) and lane z + 32 - * split z + 32's -- kMaxSplit is 64 -- so the row's max and denominator are one wave reduction - * each; then one sweep over the splits that saw a key, four at a time, every lane accumulating - * its 4 * NC dims. The first version walked the splits three times over, - * serially, in one thread block per tile: at the 64 splits a decode step of a full-attention layer - * gets, that was 750 us a call, a quarter of the step's device time. */ + * One wave per row, splits across lanes: lane z holds split z's (max, sum) and z + 32's + * (kMaxSplit is 64), so the row max and denominator are one wave reduction each. Then one sweep + * over the splits that saw a key, four at a time, each lane accumulating its 4 * NC dims. */ template __global__ __launch_bounds__(kThreads) void merge_kernel(AttnArgs A) { constexpr int R = Geo::R, NC = HD / 128; @@ -855,10 +835,9 @@ __global__ __launch_bounds__(kThreads) void merge_kernel(AttnArgs A) { for (int c = 0; c < NC; ++c) #pragma unroll for (int e = 0; e < 4; ++e) acc[c][e] = 0.0f; - /* The splits that carry weight, as a 64-bit set every lane holds the same copy of, taken - * four at a time so 4 * NC loads are in flight before the first FMA waits on one. A short - * group repeats its first split at weight 0: the index is a written one, so the product is - * 0 * finite. An empty split's accumulator was never written and is never read. */ + /* Splits with weight, as a wave-uniform 64-bit set, taken four at a time so 4 * NC loads + * are in flight before the first FMA. A short group repeats its first split at weight 0 + * (a written split, so 0 * finite). An empty split's accumulator is never read. */ uint64_t live = (uint64_t)__builtin_amdgcn_ballot_w32(w0 != 0.0f) | ((uint64_t)__builtin_amdgcn_ballot_w32(w1 != 0.0f) << 32); while (live) { @@ -898,9 +877,9 @@ __global__ __launch_bounds__(kThreads) void merge_kernel(AttnArgs A) { /* ------------------------------------------------------------------ host: the launch adapter */ -/* q and out as [rows, heads, head_dim] at whatever rank they arrived in: rank 3 (or more, leading - * axes dense), or rank 2 [rows, heads * head_dim] with its own row pitch -- a column slice of a - * fused projection. The last axis must be dense. */ +/* q and out as [rows, heads, head_dim]: rank >= 3 (leading axes dense), rank 2 + * [rows, heads * head_dim] with its own row pitch (a column slice of a fused projection), or flat. + * The last axis must be dense. */ static bool head_view(const RadTensor* t, int64_t heads, int64_t hd, int64_t* rows, int64_t* rs, int64_t* hs) { if (t->rank >= 3) { @@ -1015,11 +994,10 @@ static int launch_attn(const RadArgs* a, RadStream stream) { if (nt <= 0) return RAD_OK; if (nt > 0x7fffffff) return RAD_E_SHAPE; - /* THE WMMA PATH, for a prefill-shaped step: the longest query at least kWmmaMinQ rows and the - * mean at least half that -- a decode or verify batch, a few rows a sequence however many - * sequences, keeps the scalar kernel and its split-KV below. 16-byte query and output rows. - * Both forms agree with libref's attention within 0.02 on the engine's own operands (the op - * oracle, Gemma 4 26B-A4B at two ranks); they differ from each other by summation order. */ + /* WMMA path for prefill-shaped steps: longest query >= kWmmaMinQ rows and mean >= half that. + * Decode and verify batches keep the scalar kernel and its split-KV. Needs 16-byte aligned + * query and output rows. Both kernels agree with libref within 0.02 (Gemma 4 26B-A4B operands) + * and differ from each other only in summation order. */ { int64_t qmax_w = qlen_u; if (cu) { @@ -1067,7 +1045,7 @@ static int launch_attn(const RadArgs* a, RadStream stream) { } } - /* SPLIT-KV: only where (tile, kv head) pairs are too few to fill the card */ + /* Split-KV only when (tile, kv head) pairs are too few to fill the GPU */ int64_t ns = 1; const int64_t pairs = nt * kvh; if (pairs < kTinfoMax) { @@ -1130,8 +1108,8 @@ R4D_WIN_DEF(256, 1) R4D_WIN_DEF(256, 2) R4D_WIN_DEF(256, 4) R4D_WIN_DEF(256, 8) R4D_WIN_DEF(512, 1) R4D_WIN_DEF(512, 2) R4D_WIN_DEF(512, 4) R4D_WIN_DEF(512, 8) #undef R4D_WIN_DEF -/* Called at declare with the band's bound and no tensors: the split-KV partials are capped at - * kPartBudget (tile, head, split) triples whatever the batch, so the answer is a constant. */ +/* Called at declare with no tensors. Partials are capped at kPartBudget (tile, head, split) + * triples for any batch, so the size is a constant. */ int64_t r4d_rad_attn_window_h256_scratch(const RadArgs*) { return r4d_win::scratch_need<256>(); } int64_t r4d_rad_attn_window_h512_scratch(const RadArgs*) { return r4d_win::scratch_need<512>(); } diff --git a/libr4d/r4d_attn_prefill_h256_gqa6.hip b/libr4d/r4d_attn_prefill_h256_gqa6.hip index 6e124859..57f643f2 100644 --- a/libr4d/r4d_attn_prefill_h256_gqa6.hip +++ b/libr4d/r4d_attn_prefill_h256_gqa6.hip @@ -2,33 +2,27 @@ // 128-VGPR accumulator. The query is bf16 and the KV cache is fp8 or bf16; the 16-bit operand // format for both matmuls is f16 (see r4d_dt16.h for why). // -// Two families are compiled: all-16-bit (bf16 KV) and 16/8 mixed (bf16 query, fp8 KV). A variant -// far off the optimum is not kept behind a flag, so there is no fp8-P variant here. +// Two families: all-16-bit (bf16 KV) and 16/8 mixed (bf16 query, fp8 KV). No fp8-P variant. // -// The options below each stay separable, so any one of them can be turned off on its own after a -// geometry change: +// Each option below can be turned off on its own after a geometry change: // -// LAZY (always on, and the reason this file exists) -// The obvious form rescales all 128 accumulator VGPRs by alpha on EVERY m-tile. Here the -// softmax runs against a REFERENCE max instead of a running one: p = 2^(s - m_ref + SHIFT) -// with m_ref updated -- and the accumulator rescaled -- only when some row's max exceeds -// m_ref by more than the P format can absorb (DT16::GROW octaves). Accuracy is unchanged: -// eager rescaling by alpha and lazy accumulation at a shifted scale produce the SAME -// relative weighting in an f32 accumulator. -// F16 f16 rather than bf16 as the 16-bit operand format. gfx1201 has NO bf16 convert, so an -// f32->bf16 is ~6 VALU of software RTNE; v_cvt_pkrtz_f16_f32 does two f32->f16 in ONE. -// Both are exact for these operands (fp8 has 3 mantissa bits, bf16 has 7, f16 has 10). -// MSKIP Causal masking applied only on m-tiles that straddle the limit. Interior tiles pay -// nothing. -// FOLDQ scale * k_descale * log2(e) folded into the query ONCE at load. -// CONTIG The k axis of a WMMA is only ever CONTRACTED, so relabelling it on BOTH operands is -// free; reading eight contiguous elements at 8*h gives one aligned ds_read_b128 per -// fragment, deletes 16 address adds, and makes the P fragment lane-local. -// PF/SGB Prefetch PF fragments before the matching PF WMMAs, with a hard scheduling barrier -// between the two groups. Without the barrier PF is INERT. -// DOT2 v_dot2_f32_f16 row sum off the packed f16 P: 4 instructions for 8, and the denominator -// becomes the p values the PV matmul actually used. -// BTS/KWIDE/GPREV the tile-staging set -- see the comments on each define. +// LAZY (always on) Softmax against a reference max instead of a running one: +// p = 2^(s - m_ref + SHIFT), with m_ref updated and the 128-VGPR accumulator rescaled only +// when a row max exceeds m_ref by more than the P format absorbs (DT16::GROW octaves), +// instead of on every m-tile. Same relative weighting in an f32 accumulator. +// F16 f16 as the 16-bit operand format. gfx1201 has no bf16 convert (software RTNE is ~6 VALU); +// v_cvt_pkrtz_f16_f32 converts two values in one. Exact for these operands (fp8 has 3 +// mantissa bits, bf16 7, f16 10). +// MSKIP Causal masking only on m-tiles that straddle the limit. +// FOLDQ scale * k_descale * log2(e) folded into the query once at load. +// CONTIG The WMMA k axis is only contracted, so relabelling it on both operands is free. Reading +// eight contiguous elements at 8*h gives one aligned ds_read_b128 per fragment, removes 16 +// address adds and makes the P fragment lane-local. +// PF/SGB Load PF fragments before the matching PF WMMAs, with a scheduling barrier between the +// groups. Without the barrier PF has no effect. +// DOT2 v_dot2_f32_f16 row sum from the packed f16 P: 4 instructions instead of 8, and the +// denominator uses the p values the PV matmul used. +// BTS/KWIDE/GPREV tile staging; see each define. #include "r4d.h" #include "r4d_common.h" #include "r4d_dt16.h" @@ -42,30 +36,22 @@ #define O_PF8 3072 #define O_SGB 4096 #define O_DOT2 16384 -// BTS: the block table entries for a tile are TILE/BS values at a WAVE-UNIFORM index, so they -// belong in SGPRs. Without this, every staging pass is `global_load_b32` (block table), -// `s_wait_loadcnt 0x0`, fourteen instructions of address arithmetic, `global_load_b64` (the KV), -// `s_wait_loadcnt 0x0` -- TWO serialised memory round trips, inside a barrier-bounded phase with -// nothing else to run. A scalar load hoisted to the top of the tile collapses that to one. +// BTS: a tile's TILE/BS block-table entries are at a wave-uniform index, so load them into SGPRs +// once per tile. Otherwise each staging pass does two serialised memory round trips (block table, +// then KV) inside a barrier-bounded phase with nothing else to run. #define O_BTS 262144 // KWIDE: one 16-byte K fetch per thread instead of two 8-byte ones. 768 threads x 16 B is exactly -// a 48-key tile, so the staging loop becomes straight-line: half the global loads, half the block -// table lookups, half the dependency chains. -// The naive assignment (key = tid/16) makes a warp write ONE row at a 32-byte stride, which is a -// 4-way LDS bank conflict: bank = 8*ch mod 32 takes only four values. Interleaving two keys across -// the warp instead -- key = 2*warp + (lane&1), ch = (lane&31)>>1 -- gives eight distinct 4-bank -// groups covering all 32 banks, i.e. the conflict-free minimum, and the global side still reads two -// contiguous 256-byte runs. +// a 48-key fp8 tile, so staging is straight-line with half the loads and block-table lookups. +// key = tid/16 would make a warp write one row at a 32-byte stride (4-way LDS bank conflict, since +// 8*ch mod 32 takes four values). key = 2*warp + (lane&1), ch = (lane&31)>>1 interleaves two keys +// so the writes cover all 32 banks, while global reads stay two contiguous 256-byte runs. #define O_KWIDE 524288 -// GPREV: fetch tile ti+1's V into REGISTERS immediately after the second barrier, so its memory -// latency is covered by tile ti's 96 WMMAs and only the LDS stores stay between the barriers. -// V ONLY. A second prefetch, for K, does not pay at any issue point: this kernel already sits at -// 240 VGPRs, so the allocator spills it, and a spilled prefetch is waited on immediately, which is -// not a prefetch at all. +// GPREV: fetch tile ti+1's V into registers right after the second barrier, so its latency is +// hidden by tile ti's 96 WMMAs and only the LDS stores remain between barriers. V only: at +// 240 VGPRs a K prefetch would be spilled, and a spilled prefetch is waited on immediately. #define O_GPREV 1048576 -// LDSB: an LDS-scoped barrier instead of __syncthreads(). See lds_barrier() in r4d_common.h -- -// the default fence invalidates the vector cache twice per tile for a synchronisation that only -// ever orders LDS. +// LDSB: an LDS-scoped barrier instead of __syncthreads() (lds_barrier() in r4d_common.h). The +// default fence invalidates the vector cache twice per tile, though only LDS needs ordering. #define O_LDSB 2097152 // bf16 dword -> 16-bit dword in the target format, optionally scaled. Used once per kernel on Q. @@ -76,11 +62,9 @@ __device__ __forceinline__ uint32_t r4d_qcvt(uint32_t w, float s) { __builtin_bit_cast(float, w & 0xffff0000u) * s); } -// WIN turns on a sliding window (a.window positions, ending at each row's causal limit), the way -// the decode kernel's WIN does. The window's lower bound masks the keys before it, and the KV walk -// starts at the tile holding the window's first token (taken at query row 0, whose window reaches -// furthest back) so the tiles no row can reach are never walked. window <= 0 (or WIN off) is the -// full-attention form, unchanged. +// WIN enables a sliding window (a.window positions ending at each row's causal limit), as in the +// decode kernel. Keys below the window are masked, and the KV walk starts at the tile holding the +// workgroup's earliest window token. window <= 0 (or WIN off) is full attention. template __global__ __launch_bounds__(NWARPS * 32) void r4d_attn_prefill_kernel(const R4DArgs a) @@ -127,9 +111,8 @@ void r4d_attn_prefill_kernel(const R4DArgs a) const int ctx = a.seqused_k[seq]; if (ctx <= 0) return; - // Ragged batches: this sequence owns rows [qoff, qoff+qlen) of the dense q and out blocks. - // grid.x is sized from the batch MAXIMUM q_len, so a shorter sequence has blocks past its own - // end -- they exit here rather than run a full KV walk to write nothing. + // Ragged batches: this sequence owns rows [qoff, qoff+qlen) of q and out. grid.x is sized from + // the batch maximum q_len, so blocks past a shorter sequence's end exit here. const int qoff = r4d_q_off(a.cu_q, seq, a.q_len); const int qlen = r4d_q_len(a.cu_q, seq, a.q_len); if (qb * BLOCK_Q >= qlen) return; @@ -153,7 +136,7 @@ void r4d_attn_prefill_kernel(const R4DArgs a) + ((size_t)(qoff + qrow) * a.q_heads + qhead) * HEAD_DIM; #pragma unroll for (int t = 0; t < NKS; ++t) { - // CONTIG reads the same 8 d as ONE run; the split map takes them 4+4. + // CONTIG reads the 8 dims as one run; the split map takes them 4+4. const uint2 l0 = *(const uint2*)(qp + 16 * t + (CTG ? 8 * h : 4 * h)); const uint2 h0 = *(const uint2*)(qp + 16 * t + (CTG ? 8 * h + 4 : 8 + 4 * h)); qf[t] = D::mk(make_uint2(r4d_qcvt(l0.x, mul), @@ -164,9 +147,8 @@ void r4d_attn_prefill_kernel(const R4DArgs a) } const int klimit = ctx - qlen + qpos; - // The window's first key this row may attend to: the causal limit back by the window, floored - // at zero. The decode kernel's r4d_attn_wlo is the same formula, inlined here because the - // prefill header is compiled before the decode one that defines it. + // First key in this row's window, floored at zero. Same formula as r4d_attn_wlo, which is + // defined in the decode unit, included after this one. int wlo = (WIN && a.window > 0) ? (ctx - qlen + qpos - a.window + 1) : 0; if (WIN && a.window > 0 && wlo < 0) wlo = 0; @@ -180,17 +162,14 @@ void r4d_attn_prefill_kernel(const R4DArgs a) const int qmax_cta = min(qb * BLOCK_Q + BLOCK_Q - 1, qlen - 1); const int klimit_cta = ctx - qlen + qmax_cta; const int ntiles = (min(klimit_cta + 1, ctx) + TILE - 1) / TILE; - // The window's first tile, taken at THIS CTA's first query row (whose window reaches furthest - // back among the rows it holds); the walk starts there, so no tile below every row's window is - // fetched. Taken at the CHUNK's row 0 instead, the last CTA of an 8192-token chunk walked eight - // thousand keys none of its rows can see -- fully masked tiles, so skipping them changes no - // value. WIN off (or window <= 0) starts at 0. + // First window tile, taken at this workgroup's first query row (the one reaching furthest + // back), not the chunk's row 0, so fully masked tiles are never walked. Starts at 0 without a + // window. const int wlo0 = (WIN && a.window > 0) ? (ctx - qlen + qb * BLOCK_Q - a.window + 1) : 0; const int tstart = (WIN && a.window > 0 && wlo0 > 0) ? (wlo0 / TILE) : 0; - // ---- staging, split into a global FETCH (registers) and an LDS STORE ------------------------ - // Splitting them is what lets GPREV move the fetch out from between the barriers; without - // GPREV the two simply run back to back. + // ---- staging, split into a global fetch (registers) and an LDS store ------------------------ + // The split lets GPREV move the fetch out from between the barriers. const int vg = lane >> 3, vj = lane & 7; uint4 kreg[KREGS], vreg[VREGS]; @@ -282,8 +261,8 @@ void r4d_attn_prefill_kernel(const R4DArgs a) *(uint2*)(dst) = make_uint2(D::from_bf16w(v.x), D::from_bf16w(v.y)); *(uint2*)(dst + 4) = make_uint2(D::from_bf16w(v.z), D::from_bf16w(v.w)); } else { - // tr_b128 transposes 16-BIT lanes, so each transposed short is two fp8 from - // ADJACENT d; v_perm_b32 splits them back into two d rows. + // tr_b128 transposes 16-bit lanes, so each short holds two fp8 from adjacent + // dims; v_perm_b32 splits them into two dim rows. const uint32_t lo0 = byte_gather(v.x, v.y, 0), lo1 = byte_gather(v.z, v.w, 0); const uint32_t hi0 = byte_gather(v.x, v.y, 1), hi1 = byte_gather(v.z, v.w, 1); uint32_t wl[4], wh[4]; @@ -300,14 +279,10 @@ void r4d_attn_prefill_kernel(const R4DArgs a) } }; - // The block table for tile ti is fetched during tile ti-1, so the scalar load has an entire - // store phase and two barriers to complete instead of stalling the KV address chain. - // A tile's NB entries are read whole, and when a tile spans several blocks the last one can run - // past the sequence's last block -- past the end of its row, and on the last row past the end - // of the table. Every key is clamped to ctx - 1 before it picks an entry, so no entry past - // `lastb` is ever used and clamping the index there changes no value that is. Only a window - // that reaches past `lastb` takes the clamped form, so every other tile keeps its one wide - // scalar load; at one block a tile no window can reach past it and the test folds away. + // Tile ti's block-table entries are loaded during tile ti-1, off the KV address chain. + // A multi-block tile can run past the sequence's last block (on the last row, past the end of + // the table). Keys are clamped to ctx - 1, so entries past lastb are never used; only tiles + // reaching past lastb take the clamped load. With NB == 1 the test folds away. const int lastb = (ctx - 1) / BS; auto load_bt = [&](int t0, int* out) { if (NB > 1 && t0 + NB - 1 > lastb) { @@ -331,11 +306,11 @@ void r4d_attn_prefill_kernel(const R4DArgs a) if (LDSB) lds_barrier(); else __syncthreads(); fetchK(k0, blk); if (!GPREV) fetchV(k0, blk); - storeV(); // V first: its data is already in registers, so it covers K's wait + storeV(); // V first: already in registers, so it covers K's load latency storeK(); if (LDSB) lds_barrier(); else __syncthreads(); - // The next tile's global loads are issued HERE, before the 96 WMMAs below, and the wait - // that consumes them does not appear until after the next barrier. + // Issue the next tile's V loads before the WMMAs below; they are consumed after the next + // barrier. if (GPREV && ti + 1 < ntiles) fetchV(k0 + TILE, blkn); #pragma unroll 1 @@ -343,8 +318,8 @@ void r4d_attn_prefill_kernel(const R4DArgs a) v8f s = (v8f){0,0,0,0,0,0,0,0}; { const uint16_t* krow = &sK[(mt * 16 + c) * KSTR] + (CTG ? 8 * h : 0); - // PF fragments are LOADED before the matching PF WMMAs are ISSUED, so the wait in - // front of each WMMA becomes `s_wait_dscnt PF-1` instead of a full drain. + // Load PF fragments before issuing their WMMAs, so each WMMA waits on + // s_wait_dscnt PF-1 instead of a full drain. #pragma unroll for (int g = 0; g < NKS; g += PF) { frag16 kb[PF]; @@ -369,8 +344,7 @@ void r4d_attn_prefill_kernel(const R4DArgs a) for (int e = 0; e < 8; ++e) sc[e] = FOLDQ ? s[e] : s[e] * mul; const int kbase = k0 + mt * 16 + 8 * h; - // The causal bound masks the keys past klimit; the window bound (WIN) also masks the - // keys before wlo. MSKIP skips both when an m-tile straddles neither limit. + // Mask keys past klimit and, with WIN, before wlo. MSKIP skips tiles straddling neither. if (!MSKIP || wave_any(kbase + 7 > klimit) || (WIN && wave_any(kbase < wlo))) { #pragma unroll for (int e = 0; e < 8; ++e) sc[e] = ((kbase + e <= klimit) && (!WIN || kbase + e >= wlo)) @@ -414,8 +388,8 @@ void r4d_attn_prefill_kernel(const R4DArgs a) } const uint2 lo = make_uint2(pw[0], pw[1]); const uint2 hi2 = make_uint2(pw[2], pw[3]); - // QK leaves lane (c,h) holding keys 8h+e. Under CONTIG that IS the B fragment, so - // the cross-half exchange the two-runs-of-four map needed is simply not there. + // QK leaves lane (c,h) holding keys 8h+e. Under CONTIG that is already the B + // fragment; the split map needs a cross-half exchange. frag16 p16; if (CTG) { p16 = D::mk(lo, hi2); diff --git a/libr4d/r4d_attn_vit_h72_bf16.hip b/libr4d/r4d_attn_vit_h72_bf16.hip index 0f35398d..f6f35cb7 100644 --- a/libr4d/r4d_attn_vit_h72_bf16.hip +++ b/libr4d/r4d_attn_vit_h72_bf16.hip @@ -1,34 +1,23 @@ // R4D vision-encoder attention: dense, non-causal, head_dim 72, bf16 in and out. // -// This is the same transposed core as the paged prefill kernel -- S^T = K.Q^T, so the wave32 -// column-distributed accumulator gives each lane exactly ONE query row and the softmax state is -// lane-private. That choice is worth more here than it is at head_dim 256, because it is what -// removes the QK-C-fragment -> PV-A-fragment transpose of P through LDS: the C fragment of S^T -// (lane holds query `c`, keys 8h+i) IS the B fragment the PV matmul wants (P^T, key rows, -// query columns). A formulation that carries that LDS round trip instead does not get past torch -// SDPA for this shape. +// Same transposed core as the paged prefill kernel: S^T = K.Q^T, so each lane of the wave32 +// column-distributed accumulator owns one query row and the softmax state is lane-private. The C +// fragment of S^T (lane holds query c, keys 8h+i) is the B fragment of P.V (P^T), so P never goes +// through LDS; with that round trip this shape does not beat torch SDPA. // -// head_dim 72 is carried natively as 5 k-tiles of 16 = 80, with dims 72..79 structurally zero: -// the Q fragment of the last tile is zeroed on the h==1 half, the last 8 columns of every staged -// K row are zeroed once, and the last tile's output store is taken only by the h==0 half (the -// h==1 half would run off the end of the 72-element row). 80/72 = 11% of padded WMMA work, the -// same overhead the 64+16 Triton split pays. +// head_dim 72 runs as 5 k-tiles of 16 = 80, with dims 72..79 zero: the last Q tile is zeroed on +// the h==1 half, the last 8 columns of every staged K row are zeroed once, and only the h==0 half +// stores the last output tile (h==1 would run past the 72-element row). 11% padded WMMA work. // -// What differs from the paged kernel, beyond the geometry: -// * K and V are contiguous [tokens, heads, 72] bf16, so there is no block table, no descale and -// no fp8 widening -- the whole two-round-trip staging problem that cost the paged kernel 20% -// is simply absent. K is fetched 16 bytes per thread; V is transposed into LDS with -// global_load_tr_b128 exactly as there. -// * Non-causal: no per-row key limit. Only the last key tile is masked, and the branch is -// workgroup-uniform rather than per-wave. -// * Varlen over segments: one launch covers every image in the batch (grid.z), so the caller -// does not split by cu_seqlens and concatenate. +// Differences from the paged kernel: +// * K and V are contiguous [tokens, heads, 72] bf16: no block table, descale or fp8 widening. +// K is fetched 16 bytes per thread; V is transposed into LDS with global_load_tr_b128. +// * Non-causal: only the last key tile is masked, with a workgroup-uniform branch. +// * Varlen: one launch covers every image in the batch (grid.z over cu_seqlens segments). // -// The 16-bit operand format is f16, for the reason in r4d_dt16.h: gfx1201 has no bf16 convert, so -// the softmax's f32 -> 16-bit pack is 1 instruction per pair instead of ~6. A bf16 operand build -// stays reachable (V_O_F16 off) because it makes the K/V staging a pure byte copy; it is the -// slower of the two overall, and the option exists so the trade can be re-checked after a geometry -// change rather than assumed. +// Operands are f16 (r4d_dt16.h: gfx1201 has no bf16 convert, so packing P costs 1 instruction per +// pair instead of ~6). A bf16 build (V_O_F16 off) makes K/V staging a byte copy but is slower +// overall; it is kept so the trade can be rechecked after a geometry change. #include "r4d.h" #include "r4d_args.h" #include "r4d_common.h" @@ -43,30 +32,15 @@ #define V_O_DOT2 16384 // v_dot2_f32_f16 row sum off the packed P #define V_O_GPREV 1048576 // next tile's V fetched into registers across the m-tile loop #define V_O_LDSB 2097152 // LDS-scoped barrier instead of __syncthreads() -// GPREK: the same register prefetch for K. Unlike the paged kernel -- which sits at 240 VGPRs and -// spills any second prefetch, so a wait lands on it immediately and it stops being a prefetch -- -// this geometry runs at ~130, and the K fetch is only three uint4. Without it the tile's global -// load is issued between the two barriers with only the V LDS stores to cover it. +// GPREK: register prefetch for K too. The paged kernel (240 VGPRs) would spill it; this one runs at +// ~130 and the K fetch is three uint4. Without it the K load sits between the barriers with only +// the V LDS stores to cover it. #define V_O_GPREK 4194304 -// MIXFMT: bf16 operands for QK, f16 for PV. The two matmuls have opposite conversion costs. K and -// V arrive as bf16 and are staged through LDS, so an f16 LDS carries a bf16 -> f16 convert per -// element (3 VALU per dword) on the staging path; but P is produced in f32 by the softmax every -// m-tile, and f32 -> bf16 is ~6 VALU of software RTNE against ONE v_cvt_pkrtz_f16_f32. Splitting -// the formats takes the cheap side of both: K is copied into LDS as raw bf16 with no conversion -// at all and the query is converted once at load, while V and P stay f16. Accuracy is unchanged -- -// K and V are bf16 sources, so both widenings are exact. +// MIXFMT: bf16 operands for QK, f16 for PV. Staging bf16 K into an f16 LDS costs a convert per +// element (3 VALU per dword), while packing f32 P to bf16 costs ~6 VALU vs one v_cvt_pkrtz_f16_f32. +// So K is copied raw as bf16 (query converted once), and V and P stay f16. Both widenings are exact. #define V_O_MIXFMT 8388608 -// Pricing probes, wrong on purpose. A probe that changes the DATAFLOW measures nothing (making p -// constant makes s dead and deletes the QK loop), so each of these deletes work while leaving every -// value's producer-consumer chain intact. Count the emitted instructions before believing a number. -#ifndef V_ABL -#define V_ABL 0 -#endif -#define V_ABL_EXP 1 // the 8 v_exp_f32 per m-tile become the identity -#define V_ABL_STAGE 2 // no K/V fetch or LDS store inside the tile loop (barriers kept) -#define V_ABL_MAX 4 // no running-max test and no lazy rescale -#define V_ABL_LDS 8 // every K/V fragment read once before the tile loop and reused // bf16 dword -> 16-bit dword in the target format, with the query scale folded in. template @@ -90,10 +64,6 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest constexpr int DOT2 = ((OPT & V_O_DOT2) && F16) ? 1 : 0; constexpr int GPREV = (OPT & V_O_GPREV) ? 1 : 0; constexpr int LDSB = (OPT & V_O_LDSB) ? 1 : 0; - constexpr int ABL_EXP = (V_ABL & V_ABL_EXP) ? 1 : 0; - constexpr int ABL_STAGE = (V_ABL & V_ABL_STAGE) ? 1 : 0; - constexpr int ABL_MAX = (V_ABL & V_ABL_MAX) ? 1 : 0; - constexpr int ABL_LDS = (V_ABL & V_ABL_LDS) ? 1 : 0; constexpr int GPREK = (OPT & V_O_GPREK) ? 1 : 0; constexpr int MIXF = (OPT & V_O_MIXFMT) ? 1 : 0; typedef DT16 D; // V and P: the format the softmax packs into @@ -108,9 +78,8 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest constexpr int ROWS = NWARPS * 16 * QB; constexpr int MT = TILE / 16; constexpr int NTHR = NWARPS * 32; - // Row strides padded by 8 shorts: 16-byte aligned (a 16-byte LDS access at an 8-byte-aligned - // address splits back into two b64) and off the bank period, which puts both fragment reads - // at the 8-distinct-bank-group minimum. + // Row strides padded by 8 shorts: 16-byte aligned (an 8-byte-aligned 16-byte LDS access splits + // into two b64) and off the bank period, so both fragment reads hit 8 distinct bank groups. constexpr int KSTR = HDP + 8; constexpr int VSTR = TILE + 8; constexpr int KGRP = TILE / 8; // eight-key groups per tile; a power of two @@ -135,16 +104,14 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest const int s0 = cu[seq], slen = cu[seq + 1] - s0; if (slen <= 0 || qb * ROWS >= slen) return; - // Elements between consecutive tokens, per operand: heads * HD for a dense [tokens, heads, - // 72] tensor, and the projection's row for a column slice of a fused [q|k|v] one. + // q_ld, k_ld, v_ld, o_ld are token pitches in elements: heads * HD for a dense tensor, or the + // projection row for a column slice of a fused [q|k|v] one. const float mul = scale * 1.44269504089f; // ---- the query fragments, held for the life of the workgroup ----------------------------- - // A warp owns QB tiles of 16 query rows rather than one. Every K and V fragment read out of - // LDS is then consumed by QB WMMAs instead of one, which is the point: at QB = 1 this kernel - // issues ten ds_load_b128 per ten WMMAs, and LDS delivers less per cycle than the matrix - // units consume. The accumulator is only 8 VGPRs per output tile, so the second query tile is - // affordable where it would not be at head_dim 256. + // A warp owns QB tiles of 16 query rows, so each K/V fragment read from LDS feeds QB WMMAs. At + // QB = 1 there is one ds_load_b128 per WMMA, and LDS delivers less per cycle than the matrix + // units consume. The accumulator is 8 VGPRs per output tile, so QB > 1 is affordable here. int qpos[QB]; bool live[QB]; fragK qf[QB][NKS]; @@ -156,9 +123,8 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest const uint16_t* qp = gq + (long)(s0 + qrow) * q_ld + (long)hd * HD; #pragma unroll for (int t = 0; t < NKS; ++t) { - // The padded half of the last k-tile: dims 72..79 do not exist. Zeroing the query - // side is not enough on its own -- the K side is zeroed too, because a WMMA - // contracts, and NaN * 0 would poison the whole score row rather than one element. + // Padded half of the last k-tile (dims 72..79). K is zeroed too: the WMMA contracts, + // so a NaN * 0 there would poison the whole score row. if (t == NKS - 1 && h == 1) { qf[b][t] = DK::mk(make_uint2(0, 0), make_uint2(0, 0)); continue; } const uint4 u = *(const uint4*)(qp + 16 * t + 8 * h); qf[b][t] = DK::mk(make_uint2(r4d_vit_qcvt(u.x, mul), @@ -168,7 +134,7 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest } } - // The padded lanes of the staging buffers, written once: staging only ever fills dims 0..71. + // Zero the padding of the staging buffers once; staging only fills dims 0..71. #pragma unroll 1 for (int i = tid; i < TILE; i += NTHR) *(uint4*)&sK[i * KSTR + HD] = make_uint4(0, 0, 0, 0); #pragma unroll 1 @@ -178,14 +144,14 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest v8f acc[QB][NKS]; #pragma unroll for (int b = 0; b < QB; ++b) { - m_ref[b] = ABL_MAX ? 0.0f : -3.0e38f; - soff[b] = ABL_MAX ? PSHIFT : (PSHIFT + 3.0e38f); + m_ref[b] = -3.0e38f; + soff[b] = PSHIFT + 3.0e38f; l_i[b] = 0.0f; #pragma unroll for (int t = 0; t < NKS; ++t) acc[b][t] = (v8f){0, 0, 0, 0, 0, 0, 0, 0}; } - // ---- staging, split into a global FETCH (to registers) and an LDS STORE ------------------- + // ---- staging, split into a global fetch (to registers) and an LDS store ------------------- const int vj = tid & 7, lgi = tid >> 3; uint4 kregA[KPA], kregB[KPB], vreg[VPASS]; @@ -232,9 +198,8 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest } }; - // V is read transposed straight out of global memory: the eight lanes of a group each name a - // different key row at the same 8 dims, and global_load_tr_b128 hands lane j the column for - // dim d0+j across all eight of them -- one contiguous 16-byte LDS row of V^T per lane. + // V is read transposed from global: a group's eight lanes name eight key rows at the same 8 + // dims, and global_load_tr_b128 gives lane j dim d0+j across all eight, one 16-byte row of V^T. auto fetchV = [&](int k0) { #pragma unroll for (int r = 0; r < VPASS; ++r) { @@ -263,32 +228,22 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest } }; - fragK kb0; frag16 vb0; - if (ABL_LDS) { - const uint4 u = *(const uint4*)(&sK[c * KSTR] + 8 * h); - kb0 = DK::mk(make_uint2(u.x, u.y), make_uint2(u.z, u.w)); - const uint4 w = *(const uint4*)(&sV[c * VSTR] + 8 * h); - vb0 = D::mk(make_uint2(w.x, w.y), make_uint2(w.z, w.w)); - } - const int ntiles = (slen + TILE - 1) / TILE; - if (GPREV && !ABL_STAGE) fetchV(0); - if (GPREK && !ABL_STAGE) fetchK(0); + if (GPREV) fetchV(0); + if (GPREK) fetchK(0); for (int ti = 0; ti < ntiles; ++ti) { const int k0 = ti * TILE; const bool tail = (k0 + TILE > slen); if (LDSB) lds_barrier(); else __syncthreads(); - if (!ABL_STAGE) { - if (!GPREK) fetchK(k0); - if (!GPREV) fetchV(k0); - storeV(); // V first: already in registers, so it covers K's load wait - storeK(); - } + if (!GPREK) fetchK(k0); + if (!GPREV) fetchV(k0); + storeV(); // V first: already in registers, so it covers K's load wait + storeK(); if (LDSB) lds_barrier(); else __syncthreads(); - // Issued here, before the WMMAs below; the wait that consumes it is past the next barrier. - if (GPREV && !ABL_STAGE && ti + 1 < ntiles) fetchV(k0 + TILE); - if (GPREK && !ABL_STAGE && ti + 1 < ntiles) fetchK(k0 + TILE); + // Issued before the WMMAs below; consumed after the next barrier. + if (GPREV && ti + 1 < ntiles) fetchV(k0 + TILE); + if (GPREK && ti + 1 < ntiles) fetchK(k0 + TILE); #pragma unroll 1 for (int mt = 0; mt < MT; ++mt) { @@ -303,7 +258,6 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest #pragma unroll for (int j = 0; j < PF; ++j) { if (g + j < NKS) { - if (ABL_LDS) { kb[j] = kb0; continue; } const uint4 u = *(const uint4*)(krow + 16 * (g + j)); kb[j] = DK::mk(make_uint2(u.x, u.y), make_uint2(u.z, u.w)); } @@ -324,8 +278,7 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest #pragma unroll for (int e = 0; e < 8; ++e) sc[e] = FOLDQ ? s[b][e] : s[b][e] * mul; - // Non-causal: only the last tile can hold keys past the end of the segment, and - // the test is workgroup-uniform rather than per-row. + // Non-causal: only the last tile can hold keys past the segment end. if (tail) { const int kbase = k0 + mt * 16 + 8 * h; #pragma unroll @@ -335,7 +288,7 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest float smax = sc[0]; #pragma unroll for (int e = 1; e < 8; ++e) smax = fmaxf(smax, sc[e]); - if (!ABL_MAX && wave_any(smax > m_ref[b] + PGROW)) { + if (wave_any(smax > m_ref[b] + PGROW)) { const float rmax = fmaxf(smax, swap16(smax)); const float mnew = fmaxf(fmaxf(m_ref[b], rmax), -3.0e38f); const float alpha = ex2(m_ref[b] - mnew); @@ -351,7 +304,7 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest float pv[8], lsum = 0.0f; #pragma unroll for (int e = 0; e < 8; ++e) { - const float p = ABL_EXP ? (sc[e] + soff[b]) : ex2(sc[e] + soff[b]); + const float p = ex2(sc[e] + soff[b]); pv[e] = p; if (!DOT2) lsum += p; } @@ -367,8 +320,7 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest l_i[b] = __builtin_amdgcn_fdot2(__builtin_bit_cast(v2hf, pw[e]), one, l_i[b], false); } - // QK left lane (c,h) holding keys 8h+e of query c. That IS the B fragment of - // P^T for the PV matmul, so no exchange and no LDS round trip. + // Lane (c,h) holds keys 8h+e of query c, which is already the B fragment of P^T. p16[b] = D::mk(make_uint2(pw[0], pw[1]), make_uint2(pw[2], pw[3])); } @@ -380,7 +332,6 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest #pragma unroll for (int j = 0; j < PF; ++j) { if (g + j < NKS) { - if (ABL_LDS) { vb[j] = vb0; continue; } const uint4 u = *(const uint4*)(vbase + (g + j) * 16 * VSTR); vb[j] = D::mk(make_uint2(u.x, u.y), make_uint2(u.z, u.w)); } @@ -405,8 +356,7 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest uint16_t* op = go + (long)(s0 + qpos[b]) * o_ld + (long)hd * HD; #pragma unroll for (int dt = 0; dt < NKS; ++dt) { - // The last tile covers dims 64..79; the h==1 half of it is padding and would store - // past the end of a 72-element row. + // The last tile's h==1 half (dims 72..79) is padding and would store past the row. if (dt == NKS - 1 && h == 1) continue; uint32_t tw[4]; #pragma unroll @@ -419,44 +369,24 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest } // ---- entry point ----------------------------------------------------------------------------- -// Two instantiations, chosen on the segment length. Both are the same kernel; they differ only in -// how many query rows a workgroup owns. ROWS 256 is the argmin from 1K patches upward, but it -// quantises badly below that -- at 576 patches it leaves a workgroup two thirds dead and reaches -// only 1.33x the Triton kernel where ROWS 128 reaches 1.76x. The crossover sits between 576 and -// 1024; 768 is the midpoint and neither instantiation is far off at that length. -// -// Every geometry constant is overridable, so a retuned build is one -D away, and V_SPLIT = 0 -// forces every length through the large instantiation. -#ifndef V_NWARPS +// Two instantiations of the same kernel, chosen by segment length; they differ in query rows per +// workgroup. ROWS 256 is fastest from 1K patches up but quantises badly below (at 576 patches a +// workgroup is two thirds idle: 1.33x Triton vs 1.76x for ROWS 128). The crossover is between 576 +// and 1024; V_SPLIT 768 is the midpoint. #define V_NWARPS 16 // large instantiation: ROWS = 256 -#endif -#ifndef V_TILE #define V_TILE 128 -#endif -#ifndef V_QB #define V_QB 1 -#endif -#ifndef V_SNWARPS #define V_SNWARPS 8 // small instantiation: ROWS = 128 -#endif -#ifndef V_STILE #define V_STILE 64 -#endif -#ifndef V_SQB #define V_SQB 1 -#endif -#ifndef V_SPLIT #define V_SPLIT 768 -#endif -// F16 | FOLDQ | PF4 | SGB | DOT2 | GPREV | LDSB | GPREK. MIXFMT is off: it performs identically -// here, and one operand format with one WMMA variant is the simpler thing to keep. -#ifndef V_OPT +// F16 | FOLDQ | PF4 | SGB | DOT2 | GPREV | LDSB | GPREK. MIXFMT is off: same speed, and one +// operand format is simpler. #define V_OPT 7362569 -#endif -// q, k, v, o are [total_tokens, heads, 72] contiguous bf16; cu_seqlens is [num_seqs + 1] int32 and -// bounds one image (or one attention window) per entry, so a whole batch is one launch. max_seqlen -// is the host-side bound on those lengths -- the kernel reads the device-side cu_seqlens itself. +// q, k, v, o are [total_tokens, heads, 72] contiguous bf16; cu_seqlens is [num_seqs + 1] int32, one +// image (or attention window) per segment. max_seqlen is a host-side bound on the lengths; the +// kernel reads the device-side cu_seqlens. extern "C" int r4d_attn_vit_h72_bf16(const void* q, const void* k, const void* v, void* o, const void* cu_seqlens, int num_seqs, int max_seqlen, int heads, int head_dim, float scale, void* stream) @@ -466,9 +396,9 @@ extern "C" int r4d_attn_vit_h72_bf16(const void* q, const void* k, const void* v head_dim, scale, ld, ld, ld, ld, stream); } -// The same, each operand at its own token pitch in elements -- a column slice of a fused [q|k|v] -// projection reads at the projection's row. Every pitch and every head offset stays a multiple of -// 8 elements, which is what the 16-byte K and V fetches need. +// As above, each operand at its own token pitch in elements (e.g. a column slice of a fused +// [q|k|v] projection). Pitches and head offsets must be multiples of 8 elements for the 16-byte +// K and V fetches. extern "C" int r4d_attn_vit_h72_strided_bf16(const void* q, const void* k, const void* v, void* o, const void* cu_seqlens, int num_seqs, int max_seqlen, int heads, int head_dim, float scale, int q_ld, @@ -489,8 +419,8 @@ extern "C" int r4d_attn_vit_h72_strided_bf16(const void* q, const void* k, const (const int*)cu_seqlens, heads, scale, q_ld, k_ld, v_ld, o_ld); \ } while (0) - if (V_SPLIT > 0 && max_seqlen < V_SPLIT) V_LAUNCH(V_SNWARPS, V_STILE, V_SQB); - else V_LAUNCH(V_NWARPS, V_TILE, V_QB); + if (max_seqlen < V_SPLIT) V_LAUNCH(V_SNWARPS, V_STILE, V_SQB); + else V_LAUNCH(V_NWARPS, V_TILE, V_QB); #undef V_LAUNCH hipError_t e = hipGetLastError(); @@ -498,8 +428,7 @@ extern "C" int r4d_attn_vit_h72_strided_bf16(const void* q, const void* k, const return 0; } -// The geometry this build is compiled for: head_dim, the two query-block heights, and the length -// at which the launcher switches between them. +// Compiled geometry: head_dim, the two query-block heights, and the switch length. extern "C" void r4d_attn_vit_dims(int* head_dim, int* rows_large, int* rows_small, int* split) { if (head_dim) *head_dim = 72; if (rows_large) *rows_large = V_NWARPS * 16 * V_QB; @@ -508,10 +437,6 @@ extern "C" void r4d_attn_vit_dims(int* head_dim, int* rows_large, int* rows_smal } // ============================================================== the plugin ABI entry points -// -// The operand reader is r4d_attn_args.h, a header this kernel family shares because the paged -// geometries implement one op and take one operand list. See libr4d/r4d_args.h for why there is no -// adapter directory between the core and these launches. /* ------------------------------------------------------------------ dense (vision) */ @@ -526,25 +451,21 @@ extern "C" int r4d_rad_attn_vit(const RadArgs* a, RadStream s) { if (!q || !k || !v || !cu || !o) return R4D_NO(RAD_E_INVAL); if (!r4d_contig(cu)) return R4D_NO(RAD_E_STRIDE); - /* [tokens, heads, 72] dense, or [tokens, heads * 72] read at its own row pitch -- a column - * slice of a fused projection. The width of a row is the operand's; its pitch is what the - * kernel steps by. */ + /* [tokens, heads, 72] dense, or [tokens, heads * 72] at its own row pitch (a column slice of + * a fused projection). */ const long long head_dim = r4d_geti_or(a, "head_dim", q->rank == 3 ? q->shape[2] : 72); if (head_dim != 72) return R4D_NO(RAD_E_SHAPE); - /* Every key of a segment is attended to; a window would be ignored, so it is refused. */ - if (r4d_geti_or(a, "window", 0) != 0) return R4D_NO(RAD_E_INVAL); - auto rows = [&](const RadTensor* t, long long* n_tok, long long* n_head, long long* ld) { - long long width = 1; - for (uint32_t i = 1; i < t->rank; ++i) width *= t->shape[i]; - if (t->rank < 2 || width % head_dim) return false; - *n_head = width / head_dim; - *ld = r4d_rows_pitch(t, width, n_tok); - return *ld >= 0; - }; + /* The kernel attends every key of a segment, its bounds read as they stand, so a window, + * blocks or a cu_seqlens in finer units are refused. */ + if (r4d_geti_or(a, "window", 0) != 0 || r4d_geti_or(a, "block", 0) != 0 || + r4d_geti_or(a, "cu_div", 1) != 1) + return R4D_NO(RAD_E_INVAL); long long total = 0, heads = 0, q_ld = 0; long long tk = 0, hk = 0, k_ld = 0, tv = 0, hv = 0, v_ld = 0, to = 0, ho = 0, o_ld = 0; - if (!rows(q, &total, &heads, &q_ld) || !rows(k, &tk, &hk, &k_ld) || - !rows(v, &tv, &hv, &v_ld) || !rows(o, &to, &ho, &o_ld)) + if (!r4d_head_rows(q, head_dim, &total, &heads, &q_ld) || + !r4d_head_rows(k, head_dim, &tk, &hk, &k_ld) || + !r4d_head_rows(v, head_dim, &tv, &hv, &v_ld) || + !r4d_head_rows(o, head_dim, &to, &ho, &o_ld)) return R4D_NO(RAD_E_STRIDE); if (hk != heads || hv != heads || ho != heads) return R4D_NO(RAD_E_SHAPE); if (tk < total || tv < total || to < total) return R4D_NO(RAD_E_SHAPE); @@ -552,9 +473,8 @@ extern "C" int r4d_rad_attn_vit(const RadArgs* a, RadStream s) { const int num_seqs = (int)(cu->shape[0] - 1); - /* max_seqlen selects the query-block height and is a bound, not a length: the kernel reads the - * device-side cu_seqlens itself. Absent, the total token count is a valid bound and picks the - * tall instantiation -- a speed choice, never a correctness one. */ + /* max_seqlen is a bound that selects the query-block height (speed only); the kernel reads + * device-side cu_seqlens. Defaults to the total token count. */ long long msl = r4d_geti_or(a, "max_seqlen", 0); if (msl <= 0) msl = total; @@ -564,5 +484,6 @@ extern "C" int r4d_rad_attn_vit(const RadArgs* a, RadStream s) { num_seqs, (int)msl, (int)heads, (int)head_dim, scale, (int)q_ld, (int)k_ld, (int)v_ld, (int)o_ld, s); - return e == 0 ? RAD_OK : R4D_NO(e == -3 ? RAD_E_STRIDE : RAD_E_DEVICE); + if (e == 0) return RAD_OK; + return R4D_NO(e == -3 ? RAD_E_STRIDE : e <= -100 ? RAD_E_DEVICE : RAD_E_SHAPE); } diff --git a/libr4d/r4d_common.h b/libr4d/r4d_common.h index a3d7b6f8..4ceeed76 100644 --- a/libr4d/r4d_common.h +++ b/libr4d/r4d_common.h @@ -1,34 +1,26 @@ -// Shared device-side machinery for R4D. Everything here is layout algebra verified on hardware -// by targeted layout probes. Do not "fix" any of it from a vendor doc. +// Shared device-side machinery for R4D. The layout algebra here was verified on hardware with +// targeted probes; do not "fix" it from a vendor doc. #pragma once #include #include -// THE W4A8 SCALE GROUP LIVES HERE, not in either GEMM, because BOTH of them read the same packed -// artifact and a build where they disagree is silently wrong rather than a link error. The -// plugin build passes -DR4D_GEMM_W4A8_GROUP to every W4 translation unit; this is the fallback for -// a translation unit built without it, and it has to be the same number for all of them. -#ifndef R4D_GEMM_W4A8_GROUP +// The W4A8 scale group lives here, not in either GEMM, because both read the same packed weight and +// a disagreement would be silently wrong, not a link error. r4d_gemm_args.h restates it and checks +// it against the layout constant. #define R4D_GEMM_W4A8_GROUP 128 // K per scale -#endif // ---- ragged query batches ---------------------------------------------------------------------- -// A paged-attention batch may present a DIFFERENT query length per sequence: see R4DArgs::cu_q in -// r4d.h for why that is the ordinary case rather than an exotic one. These are the two lookups -// every kernel that indexes the dense q or out block needs, plus the inverse the split-KV combine -// needs because it walks output rows rather than sequences. -// -// The uniform case -- cu_q null -- compiles to one multiply and no load. The branch is -// wave-uniform (cu_q is a kernel argument), so it is a scalar test, and the loads it guards are -// scalar too. +// A paged-attention batch may have a different query length per sequence (R4DArgs::cu_q in r4d.h). +// These are the two lookups every kernel indexing the dense q or out block needs, plus the inverse +// for the split-KV combine, which walks output rows rather than sequences. With cu_q null they +// compile to one multiply and no load; the branch is wave-uniform (cu_q is a kernel argument). __device__ __forceinline__ int r4d_q_off(const int* cu_q, int seq, int q_len) { return cu_q ? cu_q[seq] : seq * q_len; } __device__ __forceinline__ int r4d_q_len(const int* cu_q, int seq, int q_len) { return cu_q ? (cu_q[seq + 1] - cu_q[seq]) : q_len; } -// num_seqs is at most a few tens, so the search is three or four scalar loads, taken once per -// block rather than per lane. +// num_seqs is at most a few tens, so the search is a few scalar loads, once per block. __device__ __forceinline__ int r4d_q_seq(const int* cu_q, int num_seqs, int q_len, int tok) { if (!cu_q) return tok / q_len; int lo = 0, hi = num_seqs; // invariant: cu_q[lo] <= tok < cu_q[hi] @@ -40,24 +32,21 @@ __device__ __forceinline__ int r4d_q_seq(const int* cu_q, int num_seqs, int q_le } // ---- the occupancy a kernel is built for --------------------------------------------------------- -// R4D_WAVES(n) fixes the waves a SIMD the compiler schedules a kernel for. Left to itself the -// scheduler picks that target, trading registers for occupancy or the reverse, and the choice -// moves between compiler releases: LLVM 24 serialises a GEMM's loads to win one more wave a SIMD, -// paying a load round trip per WMMA, and elsewhere hoists more loads and gives a wave up. A kernel -// whose speed rests on a register budget states the budget with this, so the source and not the -// compiler version decides it. `n` may depend on template arguments. +// R4D_WAVES(n) fixes the waves per SIMD the compiler schedules a kernel for. Otherwise the +// scheduler picks that target itself and the choice moves between compiler releases (LLVM 24 +// serialises a GEMM's loads to win one more wave, paying a load round trip per WMMA). A kernel +// whose speed rests on a register budget states it here. `n` may depend on template arguments. #define R4D_WAVES(n) __attribute__((amdgpu_waves_per_eu((n), (n)))) typedef short v8s __attribute__((ext_vector_type(8))); typedef float v8f __attribute__((ext_vector_type(8))); typedef float v2f __attribute__((ext_vector_type(2))); // what cvt_pk_f32_fp8 actually returns -/* A 16-BYTE STAGING REGISTER AS A NATIVE VECTOR. HIP's uint4 is a class template wrapping a union, - * and an array of them that a K loop carries -- the next tile's chunks, loaded while this tile is - * computed -- is not promoted to registers: LLVM 22 and LLVM 24 both keep it in scratch, so every - * staged chunk goes global load, scratch store, scratch load, LDS store. The same array of an - * ext_vector_type is promoted. Loaded and stored whole only; r4d_dflash_conv_body.h declares the - * same type for a source that is also compiled without this header. */ +/* A 16-byte staging register as a native vector. HIP's uint4 is a class template wrapping a + * union, and an array of them carried across a K loop (the next tile's chunks) is kept in scratch + * by LLVM 22 and 24, adding a scratch store and load per chunk; an ext_vector_type array is + * promoted to registers. Loaded and stored whole only. r4d_dflash_conv_body.h declares the same + * type for a source also compiled without this header. */ typedef unsigned int r4d_u32x4 __attribute__((ext_vector_type(4))); // exp2 with the hardware transcendental. @@ -70,36 +59,34 @@ __device__ __forceinline__ float ex2(float x) { #endif } -// f32 -> bf16, round-to-nearest-even. gfx1201 has NO bf16 convert instruction, so this is the -// software form (verified absent: v_cvt_pk_bf16_f32). +// f32 -> bf16, round-to-nearest-even, in software: gfx1201 has no v_cvt_pk_bf16_f32. __device__ __forceinline__ uint16_t f32_to_bf16(float f) { uint32_t u = __builtin_bit_cast(uint32_t, f); return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); } -// ...and back, which is a shift and not a conversion: every bf16 is exactly a float. +// And back: a shift, since every bf16 is exactly a float. __device__ __forceinline__ float bf16_to_f32(uint16_t h) { return __builtin_bit_cast(float, (uint32_t)h << 16); } // ---- 16-bit values held in whole registers ------------------------------------------------------- -// LLVM 24 gives gfx12 real 16-bit registers: a value of a 16-bit type lives in one HALF of a VGPR. -// Two bf16 assembled into a word then cost a shift and a half move each pair where LLVM 22 used one -// v_perm_b32, a bf16 widened to a float costs a half move and a shift, and a 16-bit load goes into a -// half (global_load_d16_b16), so it depends on the register's earlier contents and the waitcnt pass -// waits for them. The helpers below keep bf16 data in whole 32-bit registers from load to store, -// which compiles to the same code under both compilers. The bits are the same as the 16-bit forms. +// LLVM 24 gives gfx12 real 16-bit registers: a 16-bit value lives in one half of a VGPR. Packing +// two bf16 then costs a shift and a half move per pair instead of one v_perm_b32, widening costs a +// half move and a shift, and a 16-bit load into a half (global_load_d16_b16) depends on the +// register's earlier contents, so the waitcnt pass waits for them. The helpers below keep bf16 data +// in whole 32-bit registers from load to store, which compiles the same under LLVM 22 and 24 and +// gives the same bits as the 16-bit forms. -// f32 -> bf16 rounded to nearest even, as the HIGH half of a word whose low half is not zero: -// f32_to_bf16 before its final shift. A NaN can round to infinity here, as there. +// f32 -> bf16 rounded to nearest even, as the high half of a word whose low half is not zero +// (f32_to_bf16 before its final shift). A NaN can round to infinity, as there. __device__ __forceinline__ uint32_t bf16_hi_rne(float f) { const uint32_t u = __float_as_uint(f); return u + 0x7fffu + ((u >> 16) & 1u); } -// The same as (__hip_bfloat16)f computes it (LLVM's own expansion of the conversion): a NaN stays -// a NaN, made quiet, and everything else rounds to nearest even. Both results are formed before -// the choice so it compiles to one v_cndmask: written as `nan ? u | 0x400000 : u + ...`, the -// rounding is too long to speculate and each element becomes an exec-masked branch. +// Rounds as (__hip_bfloat16)f does (LLVM's expansion): a NaN stays NaN, quieted; everything else +// rounds to nearest even. Both results are formed before the select so it compiles to one +// v_cndmask; `nan ? u | 0x400000 : u + ...` makes each element an exec-masked branch. __device__ __forceinline__ uint32_t bf16_hi_rne_nan(float f) { const uint32_t u = __float_as_uint(f); const uint32_t r = u + 0x7fffu + ((u >> 16) & 1u), q = u | 0x400000u; @@ -122,23 +109,20 @@ __device__ __forceinline__ float bf16w_lo(uint32_t w) { return __uint_as_float(w __device__ __forceinline__ float bf16w_hi(uint32_t w) { return __uint_as_float(w & 0xffff0000u); } // One 16-bit element of global memory, zero-extended into a whole register (global_load_u16). -// Read as a uint16_t and widened afterwards, it is loaded into a register half instead -// (global_load_d16_b16, or d16_hi_b16 straight into the bf16's float position), which waits for -// the register's other half; through a generic pointer it is a flat load as well. The pointer -// must address global memory. +// Loaded as uint16_t it would go into a register half (global_load_d16_b16 or d16_hi_b16) and wait +// for the other half; through a generic pointer it would also be a flat load. The pointer must +// address global memory. typedef __attribute__((address_space(1))) const uint16_t* r4d_gu16; __device__ __forceinline__ uint32_t ldg_u16(const uint16_t* p) { return *(r4d_gu16)p; } // The same element as a bf16 widened to float. __device__ __forceinline__ float ldg_bf16(const uint16_t* p) { return bf16w_lo(ldg_u16(p)); } -// `lane ^ N` WITHOUT THE LDS PIPE. `__shfl_xor` lowers to `ds_bpermute_b32` plus an -// `s_wait_dscnt` -- an LDS round trip, and when the exchange sits on a dependency chain (a dot -// product closed inside a token loop, say) that latency is the loop. gfx10 and up carry ROW_XMASK -// (0x160 | N) in DPP16, so for N < 16 the partner read is a MODIFIER on the VALU op that consumes -// it and costs nothing at all: the compiler emits `v_add_f32_dpp ... row_xmask:2`. N = 16 crosses -// the two 16-lane rows of a wave32 and takes v_permlanex16, still one VALU op. -// Identical arithmetic to the shuffle it replaces -- same lane mapping, same value -- on a wave -// whose lanes are all active, which is every caller's case: a butterfly is a whole-wave step. +// `lane ^ N` without the LDS pipe. `__shfl_xor` lowers to `ds_bpermute_b32` plus `s_wait_dscnt`, +// an LDS round trip that dominates a dependency chain (e.g. a dot product closed in a token loop). +// gfx10+ DPP16 has ROW_XMASK (0x160 | N), so for N < 16 the partner read is a modifier on the +// consuming VALU op (`v_add_f32_dpp ... row_xmask:2`). N = 16 crosses the two 16-lane rows of a +// wave32 and uses v_permlanex16, still one VALU op. Same lane mapping and value as the shuffle, +// provided all lanes are active, which every caller's whole-wave butterfly guarantees. template __device__ __forceinline__ uint32_t r4d_xor_lane_u32(uint32_t v) { static_assert(N >= 1 && N <= 16 && (N & (N - 1)) == 0, "a lane xor within the wave"); @@ -154,8 +138,7 @@ __device__ __forceinline__ float r4d_xor_lane(float v) { return __uint_as_float(r4d_xor_lane_u32(__float_as_uint(v))); } -// A 64-bit value's partner: the two halves exchanged separately, which is what a 64-bit -// `__shfl_xor` does too. +// A 64-bit value's partner: the halves exchanged separately, as a 64-bit `__shfl_xor` does. template __device__ __forceinline__ unsigned long long r4d_xor_lane_u64(unsigned long long v) { const uint32_t lo = r4d_xor_lane_u32((uint32_t)v); @@ -163,29 +146,20 @@ __device__ __forceinline__ unsigned long long r4d_xor_lane_u64(unsigned long lon return ((unsigned long long)hi << 32) | lo; } -// Exchange a value between lane L and lane L^16 (the two halves a wave32 WMMA fragment splits a -// row across). v_permlanex16_b32 needs IDENTITY selectors to act as a swap: each 4-bit field names -// the source lane in the other half. sel0 covers lanes 0-7, sel1 lanes 8-15. Zero selectors would -// broadcast lane 0, which is silently wrong rather than obviously wrong. +// Exchange between lane L and lane L^16 (the two halves a wave32 WMMA fragment splits a row +// across). v_permlanex16_b32 swaps only with identity selectors (each 4-bit field names the source +// lane in the other half; sel0 covers lanes 0-7, sel1 lanes 8-15); zero selectors would silently +// broadcast lane 0. __device__ __forceinline__ float swap16(float x) { return r4d_xor_lane<16>(x); } -// A WAVE32 SUM, WITHOUT THE LDS CROSSBAR. `__shfl_xor` lowers to `ds_bpermute_b32` on gfx1201 -// whatever the offset is, and a bpermute is an LDS-pipe instruction: it queues behind every other -// LDS access and its latency is LDS latency. On a kernel whose arithmetic between reductions is -// small, a five-stage shuffle butterfly is most of the run -- the reductions cost more than the -// work between them. +// A wave32 sum on DPP instead of the LDS crossbar. `__shfl_xor` is a `ds_bpermute_b32` on gfx1201 +// at any offset, queued behind other LDS traffic; where little arithmetic separates reductions, a +// five-stage shuffle butterfly dominates the run. Offsets 8..1 use row_xmask (dpp_ctrl 0x160 | N) +// as a modifier on the add; 16 uses v_permlanex16_b32 (see swap16). // -// DPP does the exchange as a MODIFIER ON THE ADD, in the VALU, and gfx10 and later carry -// `row_xmask` (dpp_ctrl 0x160 | N) which is an XOR within each row of sixteen -- so four of the -// five butterfly offsets are expressible and only 16 crosses rows, where `v_permlanex16_b32` with -// IDENTITY selectors is the exchange (see swap16 above on why the selectors must be identity). -// -// THE LANES EXCHANGED AND THE ORDER OF THE ADDS ARE THE SAME AS THE SHUFFLE LOOP'S, so this is -// bit-identical and not merely equivalent: a kernel may be moved onto it without its generated -// text changing at any context length. -// -// Row and bank masks are all-ones because every lane participates; `bound_ctrl` only decides what -// a lane with no partner reads, and inside a full wave every lane has one. +// The lanes exchanged and the order of the adds match the shuffle loop, so this is bit-identical +// and a kernel can move onto it without its output changing. Row and bank masks are all-ones since +// every lane participates; `bound_ctrl` is moot because every lane has a partner. template __device__ __forceinline__ float r4d_dpp_xor_add(float v) { return v + __builtin_bit_cast(float, @@ -201,10 +175,9 @@ __device__ __forceinline__ float r4d_wave_sum(float v) { return v; } -// THE SAME BUTTERFLY OVER A GROUP OF W LANES, W a power of two up to the wave, for a reduction that -// closes over fewer lanes than the wave as well as over all of it: the exchanges the loop -// `for (o = W / 2; o; o >>= 1) v = op(v, __shfl_xor(v, o))` makes, in its order, so bit-identical -// to that loop for the reason r4d_wave_sum gives. +// The same butterfly over a group of W lanes (W a power of two up to the wave): the exchanges of +// `for (o = W / 2; o; o >>= 1) v = op(v, __shfl_xor(v, o))`, in its order, so bit-identical to +// that loop. template __device__ __forceinline__ float r4d_xor_sum(float v) { static_assert(W >= 1 && W <= 32 && (W & (W - 1)) == 0, "a power-of-two group within the wave"); @@ -229,11 +202,10 @@ __device__ __forceinline__ float r4d_xor_max(float v) { __device__ __forceinline__ float r4d_wave_max(float v) { return r4d_xor_max<32>(v); } -/* A WAVE'S INCLUSIVE PREFIX AND SUFFIX SUMS, in registers: row_shr (or row_shl) 1, 2, 4 and 8 - * within each row of sixteen, then the other row's total from one readlane. Lane L ends holding - * the sum over lanes 0..L (prefix) or L..31 (suffix). For the scans a workgroup would otherwise run - * as step-doubling rounds through LDS, two barriers a round; integer sums, so the order the lanes - * combine in does not matter. Every lane of the wave must be active. */ +/* A wave's inclusive prefix and suffix sums in registers: row_shr (or row_shl) 1, 2, 4 and 8 + * within each row of sixteen, then the other row's total from one readlane. Lane L ends with the + * sum over lanes 0..L (prefix) or L..31 (suffix). Replaces LDS step-doubling scans (two barriers a + * round); integer sums, so combine order does not matter. Every lane must be active. */ __device__ __forceinline__ uint32_t r4d_wave_prefix_u32(uint32_t x, int lane) { x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x111, 0xF, 0xF, true); /* row_shr:1 */ x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x112, 0xF, 0xF, true); /* row_shr:2 */ @@ -255,10 +227,8 @@ __device__ __forceinline__ uint32_t r4d_wave_suffix_u32(uint32_t x, int lane) { // 8x8 transpose of 16-bit elements across each group of 8 lanes. Lane j receives element j from // each of the 8 lanes in its group; the 8 addresses may be arbitrarily strided. __device__ __forceinline__ v8s load_tr_b128(const void* p) { - // This builtin requires a GLOBAL (address_space(1)) pointer from ROCm 7.2 / LLVM 22 on: a - // generic pointer does not convert implicitly and the library does not compile without the - // cast. The cast is sound here: every caller passes a global address, which is what - // "global_load" means. + // This builtin requires a global (address_space(1)) pointer from ROCm 7.2 / LLVM 22 on; a + // generic pointer does not convert implicitly. Every caller passes a global address. return __builtin_amdgcn_global_load_tr_b128_v8i16( (__attribute__((address_space(1))) v8s*)const_cast(p)); } @@ -275,11 +245,10 @@ __device__ __forceinline__ uint32_t byte_gather(uint32_t w0, uint32_t w1, int se __device__ __forceinline__ void sched_barrier() { __builtin_amdgcn_sched_barrier(0); } -// __syncthreads() is a workgroup-scope acquire-release fence over ALL address spaces, so on gfx12 -// it emits `global_inv scope:SCOPE_SE` on both sides of the barrier -- a vector-cache invalidate. -// Every one of those throws away the L0/L1 lines the next tile's KV loads would have hit. These -// barriers only ever order LDS traffic, so scoping the fence to the local address space makes -// the invalidate disappear. +// __syncthreads() is a workgroup-scope acquire-release fence over all address spaces, so on gfx12 +// it emits `global_inv scope:SCOPE_SE` on both sides, discarding the L0/L1 lines the next tile's +// KV loads would hit. These barriers only order LDS traffic, so the fence is scoped to the local +// address space and the invalidate disappears. __device__ __forceinline__ void lds_barrier() { __builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "local"); __builtin_amdgcn_s_barrier(); @@ -293,26 +262,21 @@ __device__ __forceinline__ uint2 swap16_u2p(uint2 v) { } // --------------------------------------------------------------------------------------------- -// WORKGROUP WIDTH FOR THE ACTIVATION-PATH KERNELS +// Workgroup width for the activation-path kernels // -// All four of them (had_quant_act_i8, rmsnorm_had_quant_i8, gated_had_quant_i8, -// gdn_gated_norm_had_quant_i8) launch ONE workgroup per row, so at a decode batch the grid is a few -// tens of workgroups on a 64-CU part and they are latency bound, not bandwidth bound: a row moves -// tens of kilobytes and costs a small multiple of the launch floor. Widening the workgroup is the -// only knob that adds parallelism without changing the algorithm, and it is the large win at small -// M. +// had_quant_act_i8, rmsnorm_had_quant_i8, gated_had_quant_i8 and gdn_gated_norm_had_quant_i8 launch +// one workgroup per row, so at decode batch sizes the grid is a few tens of workgroups on a 64-CU +// part and they are latency bound. Widening the workgroup is the only knob that adds parallelism, +// and it is the large win at small M. // -// It stops paying, and then reverses hard, once the grid alone fills the machine. At 1024 threads -// there is a RESIDENCY CLIFF just past M=32 -- the wider workgroup stops fitting and the cost -// roughly doubles. It is a residency effect and not an address effect; the buffer's placement does -// not move it. So 1024 is taken only where there is clearance below the cliff, because a batch -// that lands just above it would pay multiples of what the narrow width costs. +// It reverses once the grid alone fills the machine. At 1024 threads there is a residency cliff +// just past M=32 where the wider workgroup stops fitting and the cost roughly doubles, so 1024 is +// used only with clearance below it. // -// WHERE 512 STOPS PAYING MOVES WITH K, because the LDS a row needs (K floats) is what caps how -// many of these workgroups a CU can hold. At K=8704 only one fits at either width, so the wider -// workgroup is simply more waves per SIMD and it wins out to large M. At K=3072 five fit, the grid -// fills the part on its own, and past M~72 the narrow one is even. The thresholds below are those -// crossovers. +// Where 512 stops paying depends on K, because the K floats of LDS a row needs cap how many +// workgroups a CU holds. At K=8704 only one fits at either width, so wider wins out to large M; at +// K=3072 five fit, the grid fills the part, and past M~72 the narrow width is even. The thresholds +// below are those crossovers. __host__ __device__ __forceinline__ int r4d_act_threads(int M, int K) { if (M <= 32) return 1024; const int lim = K >= 8192 ? (1 << 24) : (K >= 4096 ? 120 : 72); diff --git a/libr4d/r4d_dequant_w4_bf16.hip b/libr4d/r4d_dequant_w4_bf16.hip index 1fd0992a..7d1701df 100644 --- a/libr4d/r4d_dequant_w4_bf16.hip +++ b/libr4d/r4d_dequant_w4_bf16.hip @@ -1,30 +1,24 @@ // r4d_dequant_w4_bf16.hip - r4d_dequant_w4_bf16: the packed 4-bit weight back to a plain row-major // bf16 [N, K]. // -// WHY THIS EXISTS. W4A8 buys nothing at prefill: the iu8 and fp8 matrix rates are within a couple -// of percent of each other and the shape is compute-bound. But once the weights are STORED at 4 -// bits there is no fp8 copy to fall back on, so the requirement at prefill is "do not regress", not -// "win" -- and the skinny W4A8 GEMM cannot meet even that, because a block owns 64 rows and -// therefore re-reads the whole weight slice once per 64 output rows. Its rate is flat in M for -// that reason; it is structural and no choice of geometry fixes it. Dequantising one layer into a -// scratch buffer and handing it to the tuned bf16 GEMM costs one extra write and read of the bf16 -// weight, a few percent of the GEMM it feeds. +// Used at prefill. W4A8 gains nothing there (iu8 and fp8 matrix rates are within a few percent and +// the shape is compute-bound), and the skinny W4A8 GEMM re-reads the whole weight slice once per +// 64 output rows, so its rate is flat in M. Dequantising one layer into scratch and running the +// tuned bf16 GEMM costs one extra write and read of the bf16 weight, a few percent of the GEMM. // -// TWO ENCODINGS SHARE THESE BYTES AND THEY DIFFER BY BIT 3, so the caller has to say which. The -// symmetric grid stores a TWO'S COMPLEMENT code -- that is what lets the int8 GEMM read the -// high-nibble byte signed and get 16*q directly -- and its value is (n^8)-8, i.e. n=8 means -8. -// The asymmetric grid stores an UNSIGNED nibble and subtracts a per-group zero, which is what lets -// the same GEMM read it unsigned and correct with an activation row-sum. Feeding one to the other -// is silently wrong rather than obviously wrong: it agrees for n<8 and is off by 16 above. +// Two encodings share these bytes and differ by bit 3, so the caller must say which. The +// symmetric grid stores a two's complement code, value (n^8)-8, so the int8 GEMM can read the +// high-nibble byte signed and get 16*q. The asymmetric grid stores an unsigned nibble minus a +// per-group zero, corrected in the GEMM by an activation row-sum. Mixing them up agrees for n<8 +// and is off by 16 above. // -// It is very nearly lossless: the stored value is a 4-bit code times an f16 scale, and bf16's -// 8-bit mantissa holds that to within a ULP. +// Nearly lossless: a 4-bit code times an f16 scale fits bf16's 8-bit mantissa to within a ULP. // -// UNDOING THE FRAGMENT ORDER. radiance_w4.pack lays a dword out as [t][kb][lh][r][s] with eight -// nibbles along i, where t = n/16, r = n%16, kb = k/64, s = (k%64)/16, and the k inside the step is -// 4*lh + _KOFF[i] with _KOFF = {0,8,1,9,2,10,3,11}. One thread per dword scatters its eight -// nibbles; the scale dword lives at [t][g][r] and carries the f16 scale low and -(1024+zero) high, -// so the same routine serves the symmetric grid (zero == 8) and the asymmetric one. +// Fragment order: radiance_w4.pack lays a dword out as [t][kb][lh][r][s] with eight nibbles along +// i, where t = n/16, r = n%16, kb = k/64, s = (k%64)/16, and the k inside the step is +// 4*lh + _KOFF[i] with _KOFF = {0,8,1,9,2,10,3,11}. One thread per dword scatters its eight +// nibbles. The scale dword at [t][g][r] holds the f16 scale low and -(1024+zero) high, so one +// routine serves the symmetric grid (zero == 8) and the asymmetric one. #include "r4d.h" #include "r4d_gemm_args.h" #include @@ -63,8 +57,8 @@ __global__ __launch_bounds__(R4D_DQ_THREADS) void r4d_dequant_w4_bf16_kernel( for (int i = 0; i < 8; i++) { const int n = (int)((w >> (4 * i)) & 0xF); const float q = twos ? (float)((n ^ 8) - 8) : (float)n; - // 4*lh is part of the k, not just of the scale lookup: position (lh, i) holds - // kk = 4*lh + _KOFF[i], so lh=0 covers {0,8,1,9,2,10,3,11} and lh=1 the other eight. + // Position (lh, i) holds kk = 4*lh + _KOFF[i]: lh=0 covers {0,8,1,9,2,10,3,11}, lh=1 + // the other eight. const int k = kbase + r4d_dq_koff[i]; Out[(size_t)row_n * K + k] = __float2bfloat16((q - (twos ? 0.f : zero)) * sc); } @@ -86,8 +80,7 @@ void r4d_dequant_w4_bf16(long wq, long ws, long out, int N, int K, int group, in // ============================================================== the plugin ABI entry points // -// The operand reader and the split law are in r4d_gemm_args.h. See libr4d/r4d_args.h for why an -// entry point takes the ABI's own argument list directly rather than going through an adapter. +// The operand reader and the split law are in r4d_gemm_args.h; see libr4d/r4d_args.h. /* ------------------------------------------------------------------ dequant */ enum { D_WQ = 0, D_WS, D_Y }; diff --git a/libr4d/r4d_dflash_conv_body.h b/libr4d/r4d_dflash_conv_body.h index 2fa3b2f7..5af7c401 100644 --- a/libr4d/r4d_dflash_conv_body.h +++ b/libr4d/r4d_dflash_conv_body.h @@ -1,28 +1,26 @@ // DFlash2 grouped dynamic depthwise convolution -- device math only. // -// Deliberately free of so the identical source can be compiled standalone to -// gfx1201 assembly with a stock clang (no ROCm install) for ISA review, and as part of libr4d.so. +// Free of so the same source compiles standalone to gfx1201 assembly with a +// stock clang (no ROCm) for ISA review, as well as into libr4d.so. // // The op, per DFlash2's _grouped_conv with taps=2, group_size=16: // // out[t,h] = (base[0,h] + delta[t,0,g]) * x[t,h] // + (base[1,h] + delta[t,1,g]) * x[t-1,h] * ((t % block) >= 1) g = h / group // -// The reference builds this as ~6 full [T,H] elementwise passes plus a materialised -// [T, taps, num_groups, group] coefficient tensor. Every one of those intermediates is consumed -// exactly once, so the fused form reads x, delta and base once and writes out once. +// The reference uses ~6 [T,H] elementwise passes plus a materialised [T, taps, num_groups, group] +// coefficient tensor; the fused form reads x, delta and base once and writes out once. #pragma once typedef unsigned int r4d_u32; typedef unsigned short r4d_u16; typedef r4d_u32 r4d_u32x4 __attribute__((ext_vector_type(4))); -// A 16-byte load addressed both ways. The subscript must come off a union member and never off a -// vector via __builtin_bit_cast: bit-casting a vector SUBSCRIPT silently yields element 0's bits. +// A 16-byte load addressed both ways. Subscript the union member, never a bit-cast vector: +// bit-casting a vector subscript silently yields element 0's bits. union R4dV8 { r4d_u32x4 v; r4d_u16 h[8]; }; -// Under hipcc these are device functions; the standalone ISA harness compiles the same source with -// a plain clang targeting amdgcn, where there is no __device__ and everything is already device code. +// Device functions under hipcc; plain always-inline functions under a standalone amdgcn clang. #ifndef R4D_DEV #ifdef __HIP__ #define R4D_DEV __device__ __forceinline__ @@ -41,9 +39,8 @@ R4D_DEV r4d_u16 r4d_f2bf(float f) { return (r4d_u16)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); } -// One thread owns 8 contiguous channels: a single dwordx4 in and out. group_size 16 divides that -// span, so the group index -- and therefore both delta scalars -- are uniform over the thread's 8 -// channels and are loaded once rather than per channel. +// One thread owns 8 contiguous channels (one dwordx4 in and out). The group size (16) is a multiple +// of 8, so the group index and both delta scalars are uniform per thread and loaded once. template R4D_DEV void r4d_dflash_conv_body(const r4d_u16* __restrict__ x, const r4d_u16* __restrict__ delta, @@ -53,16 +50,13 @@ R4D_DEV void r4d_dflash_conv_body(const r4d_u16* __restrict__ x, int blockmask, int t, int hv) { if (hv >= vpr) return; - // Split every address into a wave-uniform pointer and a lane offset the backend can keep in a - // single 32-bit VGPR -- gfx12's saddr form. Two things are load-bearing: - // - // * the mask. The backend will only fold a lane offset into saddr if it can prove the - // byte-scaled offset stays inside 32 bits. A lane index built from workgroup_id has no - // known bound, so it widens the address to a 64-bit vector add and pays a - // v_add_co_u32 / v_add_co_ci_u32 pair per load. __builtin_assume does NOT propagate here; - // the AND does, for one cheap VALU op. - // * pointer + offset, NOT a vector-typed array indexed by lane. The array form makes the - // backend materialise a separate 64-bit address per pointer instead of sharing one offset. + // Split each address into a wave-uniform pointer and a 32-bit lane offset (gfx12 saddr form). + // Do not change either of these: + // * The mask: the backend folds a lane offset into saddr only if it can prove the byte offset + // fits 32 bits. Without it each load pays a 64-bit v_add_co_u32/v_add_co_ci_u32 pair; + // __builtin_assume does not propagate here, the AND does. + // * Pointer + offset, not a vector-typed array indexed by lane, which makes the backend + // materialise a 64-bit address per pointer. const unsigned off = ((unsigned)hv & 0xFFFFFu) * 8u; const unsigned g = off / (unsigned)GROUP; @@ -79,17 +73,13 @@ R4D_DEV void r4d_dflash_conv_body(const r4d_u16* __restrict__ x, for (int j = 0; j < 8; ++j) acc[j] = (r4d_bf2f(b0.h[j]) + d0) * r4d_bf2f(x0.h[j]); - // Tap `tap` contributes only where the position within the block is at least `tap`. t is the - // workgroup's y index, so the predicate is wave-uniform and the skip is a scalar branch -- - // and on the rows it skips, the shifted load is never issued at all. + // Tap `tap` contributes only where the position within the block is >= tap. t is the + // workgroup's y index, so this is a scalar branch and skipped rows issue no shifted load. #pragma unroll for (int tap = 1; tap < TAPS; ++tap) { - // Same rule as above, applied to the shifted operands: every uniform term folds into its - // own pointer so the only thing left varying per lane is the bounded offset. Adding tap*NG - // into the delta INDEX instead of the pointer is enough to lose saddr again. These are - // hoisted OUT of the predicate: they are scalar address arithmetic on a path the backend - // will not fold into saddr from inside a branch, and an address that is merely formed and - // never dereferenced costs nothing. + // Same saddr rule: uniform terms go into the pointer (adding tap*NG to the delta index + // instead loses saddr). The pointers are formed outside the branch, because the backend + // does not fold them into saddr from inside it; an unused address costs nothing. const r4d_u16* __restrict__ xprev = xrow - (long)tap * H; const r4d_u16* __restrict__ btap = base + (long)tap * H; const r4d_u16* __restrict__ dtap = drow + (long)tap * NG; diff --git a/libr4d/r4d_dflash_conv_t2_g16_bf16.hip b/libr4d/r4d_dflash_conv_t2_g16_bf16.hip index edd79e24..489efba0 100644 --- a/libr4d/r4d_dflash_conv_t2_g16_bf16.hip +++ b/libr4d/r4d_dflash_conv_t2_g16_bf16.hip @@ -1,7 +1,6 @@ // DFlash2 grouped dynamic depthwise convolution, fused. // -// The device math lives in r4d_dflash_conv_body.h, deliberately free of HIP headers so the same -// source compiles standalone to gfx1201 assembly with a stock clang for ISA review. +// Device math is in r4d_dflash_conv_body.h (HIP-header-free for standalone ISA review). #include #include "r4d_gdn_args.h" #include "r4d_dflash_conv_body.h" @@ -21,11 +20,11 @@ __global__ __launch_bounds__(DFC_THREADS) void r4d_dflash_conv_kernel( } // x [T, H] bf16, row pitch H -// delta [T, taps, NG] bf16, row pitch dpitch -- this is a SLICE of the [T, 2, taps, NG] kernel -// projection, so dpitch is 2*taps*NG, not taps*NG. Passing the packed pitch -// silently reads the other side's coefficients; it is not a shape error. +// delta [T, taps, NG] bf16, row pitch dpitch: a slice of the [T, 2, taps, NG] kernel projection, +// so dpitch is 2*taps*NG. The packed pitch (taps*NG) would silently read the +// other half's coefficients. // base [taps, H] bf16, contiguous -// out [T, H] bf16. Must not alias x -- tap 1 of row t reads row t-1 of the INPUT. +// out [T, H] bf16. Must not alias x: tap 1 of row t reads input row t-1. extern "C" int r4d_dflash_conv_t2_g16_bf16( const void* x, const void* delta, const void* base, void* out, int T, int H, int dpitch, int NG, int taps, int group, int block_size, void* stream) @@ -44,9 +43,7 @@ extern "C" int r4d_dflash_conv_t2_g16_bf16( } // ============================================================== the plugin ABI entry points -// -// The shared operand helpers are r4d_gdn_args.h. See libr4d/r4d_args.h for why there is no -// adapter directory between the core and these launches. +// Shared operand helpers: r4d_gdn_args.h. /* ------------------------------------------------------------------ dflash conv */ enum { DC_X = 0, DC_DELTA, DC_BASE, DC_OUT }; @@ -60,16 +57,15 @@ extern "C" int r4d_rad_dflash_conv(const RadArgs* a, RadStream s) { if (x->rank != 2 || o->rank != 2 || d->rank < 2) return R4D_NO(RAD_E_SHAPE); if (!r4d_contig(x) || !r4d_contig(o) || !r4d_contig(bs)) return R4D_NO(RAD_E_STRIDE); - /* "out must not alias x" is in the entry point's own contract and nothing downstream checks - * it -- the kernel reads x while writing out, so an alias is silent corruption. */ + /* out must not alias x (the kernel reads x while writing out); nothing downstream checks it. */ if (x->data == o->data) return R4D_NO(RAD_E_INVAL); const long long T = x->shape[0]; const long long H = x->shape[1]; if (o->shape[0] != T || o->shape[1] != H) return R4D_NO(RAD_E_SHAPE); - /* delta is a SLICE of the [T, 2, taps, NG] kernel projection, so its row pitch is 2*taps*NG - * and not the slice's own width. Reading it off stride[0] is what makes the slice legal. */ + /* delta is a slice of the [T, 2, taps, NG] projection: its row pitch (from stride[0]) is + * 2*taps*NG, not the slice width. */ const long long dpitch = r4d_row_pitch(d); if (dpitch < 0) return R4D_NO(RAD_E_STRIDE); @@ -78,14 +74,12 @@ extern "C" int r4d_rad_dflash_conv(const RadArgs* a, RadStream s) { const int NG = (int)r4d_geti_or(a, "NG", 0); const int bsz = (int)r4d_geti_or(a, "block_size", 0); if (NG <= 0 || bsz <= 0) return R4D_NO(RAD_E_INVAL); - /* block_size is masked with block_size-1 in the kernel body, so only a power of two is - * admissible. That is a property of the VALUE and not a bound a constraint can express, which - * is why libr4d's registry leaves it out of the predicates and the entry point rejects it -- - * except that libr4d's entry point does not, so this shim does. */ + /* The kernel masks with block_size-1, so block_size must be a power of two; a row constraint + * cannot express that, so it is checked here. */ if (bsz & (bsz - 1)) return R4D_NO(RAD_E_INVAL); if (dpitch != 2LL * taps * NG) return R4D_NO(RAD_E_STRIDE); - return r4d_dflash_conv_t2_g16_bf16(x->data, d->data, bs->data, o->data, - (int)T, (int)H, (int)dpitch, NG, taps, group, bsz, s); + return R4D_RAW(r4d_dflash_conv_t2_g16_bf16(x->data, d->data, bs->data, o->data, (int)T, + (int)H, (int)dpitch, NG, taps, group, bsz, s)); } diff --git a/libr4d/r4d_dflash_select_bf16.hip b/libr4d/r4d_dflash_select_bf16.hip index 781c7fc6..e0f0069f 100644 --- a/libr4d/r4d_dflash_select_bf16.hip +++ b/libr4d/r4d_dflash_select_bf16.hip @@ -1,10 +1,9 @@ -// DFlash2's candidate selector: the edge scores and the path walk, one workgroup a sequence. +// DFlash2's candidate selector: edge scores and the path walk, one workgroup per sequence. // -// A block-diffusion drafter proposes every position of a block in ONE backbone pass, so it has no -// way to condition position l+1 on what it chose at position l -- the two were computed together. -// The selector is what puts that dependence back. Each position keeps the draft head's top K -// candidates and a low-rank bilinear form scores every (predecessor, candidate) EDGE between -// consecutive positions; a greedy walk over those edges picks one token per position. +// A block-diffusion drafter proposes every position of a block in one backbone pass, so position +// l+1 cannot condition on the choice at l. The selector restores that dependence: each position +// keeps the draft head's top K candidates, a low-rank bilinear form scores each (predecessor, +// candidate) edge between consecutive positions, and a greedy walk picks one token per position. // // score[s, l, c] = unary[s, l, c] // + sum_r pred[pid(s,l)][r] * hp[s,l][r] * succ[cand[s,l,c]][r] @@ -12,26 +11,20 @@ // pid(s, 0) = anchor[s * anchor_stride] the token the target just committed // pid(s, l) = cand[s, l-1, chosen(s, l-1)] the walk's own previous pick // -// `hp` IS OPTIONAL, AND ABSENT IT IS ONES -- which drops the trilinear form to a plain BIGRAM one, -// score = unary + , with no dependence on the hidden state at all. That is -// not a degenerate case: it is exactly DSpark's Markov head, a rank-256 learned -// bigram bias `markov_w2 @ markov_w1[prev]` added to the draft logits, whose previous token is the -// anchor at position 0 and the drafter's own last pick after it. The head is a full-vocabulary -// [rank, n_vocab] GEMM per position in the reference and it is SERIAL in exactly the way this walk -// already is, so running it here costs the candidate rows of two codebooks instead of seven passes -// over 66 MiB -- and the greedy argmax over the base head's top K is what makes that exact enough -// to matter only to acceptance (a draft is verified; see the 2-bit head's argument). +// `hp` is optional; absent means ones, giving the bigram form score = unary + . That is DSpark's Markov head (a rank-256 learned bigram bias +// markov_w2 @ markov_w1[prev] on the draft logits, prev = anchor at position 0, then the last +// pick). The reference runs it as a full-vocabulary [rank, n_vocab] GEMM per position, serially; +// here it costs only the candidate rows of two codebooks. Restricting to the base head's top K +// affects only acceptance, since drafts are verified. // -// THE WALK IS SERIAL IN l and that is the whole reason this is a kernel and not a batched GEMM -// followed by an argmax. The reference materialises the full [steps, K, K] score tensor -- vLLM's -// `_score_edges` einsum -- of which exactly one row per step is ever read, because the predecessor -// index is not known until the previous step has been decided. Scoring K*K edges to use K of them -// is 16x the work and a round trip per step; here the predecessor's codebook row is fetched after -// the previous step's argmax, inside one workgroup, with no launch between. +// The walk is serial in l, which is why this is a kernel rather than a batched GEMM plus argmax. +// The reference (vLLM's _score_edges einsum) materialises [steps, K, K] scores and reads one row +// per step, since the predecessor is only known after the previous step. Here the predecessor's +// codebook row is fetched after the previous argmax, inside one workgroup. // -// The arithmetic is tiny -- steps * K * R multiply-adds a sequence, 28K at the shipped 7/16/256 -- -// so this is a latency kernel, not a throughput one. It is written for one workgroup a sequence -// with no global synchronisation at all. +// The arithmetic is tiny (steps * K * R multiply-adds per sequence, 28K at 7/16/256), so this is a +// latency kernel: one workgroup per sequence, no global synchronisation. #include #include "r4d_gdn_args.h" #include "r4d_dflash_conv_body.h" // r4d_bf2f, r4d_u16 @@ -51,11 +44,9 @@ // succ [vocab, R] bf16 successor codebook // out [M, out_ld] i32 the chosen token per step // -// AN ID OUTSIDE [0, V) IS NOT A CODEBOOK ROW, and one reaches this kernel: row_topk_merge reports a -// slot no rank could fill as id -1, and step 0's predecessor is whatever the anchor plane holds. So -// the codebook reads are guarded exactly as ref_dflash_select guards them -- a predecessor out of -// range contributes nothing, and a candidate out of range scores its unary term alone -- rather -// than gathering a row from before or past the codebook. +// Ids outside [0, V) do occur (row_topk_merge reports an unfilled slot as -1, and step 0's +// predecessor is whatever the anchor plane holds). As in ref_dflash_select, an out-of-range +// predecessor contributes nothing and an out-of-range candidate scores its unary term alone. __global__ __launch_bounds__(DSL_THREADS) void r4d_dflash_select_kernel( const int* __restrict__ cand, const float* __restrict__ unary, const r4d_u16* __restrict__ hp, const int* __restrict__ anchor, @@ -68,21 +59,19 @@ __global__ __launch_bounds__(DSL_THREADS) void r4d_dflash_select_kernel( const int lane = tid & (DSL_WAVE - 1); const int wave = tid / DSL_WAVE; - // a[r] = pred[pid][r] * hp[r] -- the half of the bilinear form that does not depend on the - // candidate, so it is computed once per step and read K times out of LDS. + // a[r] = pred[pid][r] * hp[r]: the candidate-independent half, computed once per step. __shared__ float sa[DSL_MAX_R]; __shared__ float ssc[DSL_MAX_K]; __shared__ int spid; // the token the previous step chose: this step's predecessor - // THE CANDIDATES A WAVE SCORES, at most this many: c = wave, wave + DSL_WAVES, ... + // Candidates per wave, at most: c = wave, wave + DSL_WAVES, ... constexpr int CPW = (DSL_MAX_K + DSL_WAVES - 1) / DSL_WAVES; for (int l = 0; l < steps; ++l) { const long row = (long)s * steps + l; - // THE STEP'S OWN READS GO FIRST. The candidates' ids and unary scores do not depend on the - // predecessor, so they are in flight with its codebook row instead of behind the barrier, each - // a round trip of its own in a walk that is nothing but round trips. A wave past K re-reads - // the last candidate and scores nothing. + // Candidate ids and unary scores do not depend on the predecessor, so load them first, + // overlapping the codebook row fetch. A wave past K re-reads the last candidate and scores + // nothing. int cid[CPW]; float un[CPW]; #pragma unroll @@ -92,15 +81,13 @@ __global__ __launch_bounds__(DSL_THREADS) void r4d_dflash_select_kernel( cid[i] = cand[at]; un[i] = unary[at]; } - // Step 0's predecessor is the committed anchor; every later step's is the token this walk - // picked last time round, which thread 0 left in LDS before the barrier that ended that step. + // Step 0's predecessor is the committed anchor; later steps use the previous pick, left in + // LDS by thread 0 before the barrier that ended that step. const int pid = (l == 0) ? anchor[(long)s * anchor_stride] : spid; const bool pid_ok = pid >= 0 && pid < V; const r4d_u16* __restrict__ prow = pred + (long)(pid_ok ? pid : 0) * R; - /* hp absent is hp == 1: the predecessor's codebook row goes in untouched. Branching outside - * the loop rather than multiplying by a materialised plane of ones keeps the bigram case from - * reading R bf16 a step for a number it already knows. */ + /* hp absent means ones: the predecessor's row is used as is, without reading a plane. */ if (!pid_ok) { for (int r = tid; r < R; r += DSL_THREADS) sa[r] = 0.0f; } else if (hp) { @@ -113,10 +100,9 @@ __global__ __launch_bounds__(DSL_THREADS) void r4d_dflash_select_kernel( } __syncthreads(); - // One wave a candidate. R is a multiple of the wave, so the strided loop is balanced and the - // reduction is five xor-butterfly steps with no barrier inside it. A candidate out of range - // reads codebook row 0 and drops the sum, so the row's loads are never in a branch of their - // own; its score is its unary term alone either way. + // One wave per candidate. R is a multiple of the wave size, so the reduction is a barrier-free + // xor butterfly. An out-of-range candidate reads row 0 and drops the sum, keeping the loads + // out of a branch. #pragma unroll for (int i = 0; i < CPW; ++i) { const int c = wave + i * DSL_WAVES; @@ -132,9 +118,9 @@ __global__ __launch_bounds__(DSL_THREADS) void r4d_dflash_select_kernel( } __syncthreads(); - // K is at most 32 and the walk is serial anyway, so the argmax is one thread. Ties go to the - // lower index, which is `row_topk`'s own tie rule and therefore the more likely candidate. - // Seeded below every score, as ref seeds it, so a NaN in the first slot cannot win by position. + // K <= 32 and the walk is serial, so one thread does the argmax. Ties go to the lower index + // (row_topk's rule, the more likely candidate). Seeded at -inf, as in ref, so a NaN in the + // first slot cannot win by position. if (tid == 0) { int best = 0; float bv = -INFINITY; @@ -144,8 +130,7 @@ __global__ __launch_bounds__(DSL_THREADS) void r4d_dflash_select_kernel( spid = tok; out[(long)s * out_ld + l] = tok; } - // Both directions: the next step reads `spid` and overwrites `sa`, and every other thread - // is still reading this step's. + // The next step reads spid and overwrites sa, which other threads may still be reading. __syncthreads(); } } @@ -161,7 +146,7 @@ extern "C" int r4d_dflash_select_bf16( if (R < DSL_WAVE || R > DSL_MAX_R || (R % DSL_WAVE)) return -1; if (V < 1) return -1; if (cand_ld < K || out_ld < steps || anchor_stride < 1) return -1; - /* `hp` may be null -- the bigram form -- and then there is no plane to have a pitch. */ + /* hp may be null (the bigram form); then hp_ld is unused. */ if (hp && hp_ld < R) return -1; hipLaunchKernelGGL(r4d_dflash_select_kernel, dim3(M), dim3(DSL_THREADS), 0, (hipStream_t)stream, @@ -172,16 +157,14 @@ extern "C" int r4d_dflash_select_bf16( } // ============================================================== the plugin ABI entry points -// -// The shared operand helpers are r4d_gdn_args.h. See libr4d/r4d_args.h for why there is no -// adapter directory between the core and these launches. +// Shared operand helpers: r4d_gdn_args.h. /* ------------------------------------------------------------------ dflash select */ enum { DS_CAND = 0, DS_UNARY, DS_HP, DS_ANCHOR, DS_PRED, DS_SUCC, DS_OUT }; -/* A rank-2 [rows, width] operand whose row pitch libr4d takes explicitly. `width` is checked - * rather than derived: this op reads three planes at the SAME row index and a plane whose width is - * not what the parameters say would still have a plausible number of rows. */ +/* A rank-2 [rows, width] operand with an explicit row pitch. `width` is checked, not derived: + * three planes are read at the same row index, and a wrong-width plane could still have a + * plausible row count. */ static long long ds_plane(const RadTensor* t, uint32_t dtype, long long width, long long rows) { if (!t || !t->data || t->rank != 2) return -1; if (t->dtype != dtype) return -1; @@ -198,57 +181,49 @@ extern "C" int r4d_rad_dflash_select(const RadArgs* a, RadStream s) { const RadTensor* pr = r4d_opt(a, DS_PRED); const RadTensor* sc = r4d_opt(a, DS_SUCC); const RadTensor* out = r4d_opt(a, DS_OUT); - /* `hp` is the one that may be absent; every other operand is load-bearing. */ + /* Only hp may be absent. */ if (!cand || !un || !anc || !pr || !sc || !out) return R4D_NO(RAD_E_INVAL); const long long steps = r4d_geti_or(a, "steps", 0); const long long K = r4d_geti_or(a, "top_k", 0); const long long R = r4d_geti_or(a, "rank", 0); const long long V = r4d_geti_or(a, "n_vocab", 0); - /* M IS THE OPERAND'S ROW COUNT AND NOT THE PARAMETER'S. RadArgs carries the geometry with its - * RANGES COLLAPSED -- `M` here is the band's bound, max_seqs, and not the sequence count this - * step issued (the same trap fill_paged spells out for q_len). Reading the parameter would - * make the selector demand max_seqs * steps rows of candidates on a one-sequence step and - * refuse every launch. The output plane is one row a sequence, so it is the count. */ + /* M comes from the output plane (one row per sequence), not the parameter: RadArgs carries the + * band's bound (max_seqs) for M, as for q_len in fill_paged. The parameter would demand + * max_seqs * steps candidate rows on a one-sequence step. */ if (out->rank != 2) return R4D_NO(RAD_E_SHAPE); const long long M = out->shape[0]; if (M <= 0 || steps <= 0 || K <= 0 || R <= 0 || V <= 0) return R4D_NO(RAD_E_INVAL); - /* The three input planes are read at row s*steps+l, so between them they must hold M*steps - * rows -- a short one is a walk that reads another sequence's candidates and proposes a - * perfectly plausible draft belonging to the wrong request. */ + /* The input planes are read at row s*steps+l and must hold M*steps rows; a short plane would + * silently draft from another request's candidates. */ const long long rows = M * steps; const long long cand_ld = ds_plane(cand, RAD_I32, K, rows); const long long un_ld = ds_plane(un, RAD_F32, K, rows); const long long out_ld = ds_plane(out, RAD_I32, steps, M); - /* ABSENT IS A NULL `data`, NOT A MISSING OPERAND: operands are positional, so a graph that - * does not use the hidden projection still passes it, empty. Both spellings arrive here and - * both mean the bigram form. */ + /* Absent hp may arrive as a missing operand or as an empty one with null data (operands are + * positional); both mean the bigram form. */ const bool has_hp = hp && hp->data; const long long hp_ld = has_hp ? ds_plane(hp, RAD_BF16, R, rows) : 0; if (cand_ld < 0 || un_ld < 0 || hp_ld < 0 || out_ld < 0) return R4D_NO(RAD_E_SHAPE); - /* One pitch for both, because the kernel indexes them with the same expression. */ + /* The kernel indexes cand and unary with one pitch. */ if (cand_ld != un_ld) return R4D_NO(RAD_E_STRIDE); - /* The codebooks are gathered by GLOBAL token id, so a row-sharded one would let a rank score - * only the candidates that happen to land in its own vocabulary slice -- and the candidates - * arrive already merged across ranks. Both are declared replicated at the whole vocabulary; - * this is where that would otherwise fail silently. */ + /* The codebooks are gathered by global token id, and candidates arrive merged across ranks, so + * both must be replicated over the whole vocabulary; a row-sharded one would fail silently. */ if (pr->dtype != RAD_BF16 || sc->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); if (!r4d_contig(pr) || !r4d_contig(sc)) return R4D_NO(RAD_E_STRIDE); if (r4d_numel(pr) < V * R || r4d_numel(sc) < V * R) return R4D_NO(RAD_E_SHAPE); - /* `anchor` is usually the step's own token_ids, which carries `block` ids a sequence with the - * anchor first -- so the stride is a parameter and a packed [M] array is the stride-1 case. */ + /* anchor is usually the step's token_ids (`block` ids per sequence, anchor first), hence the + * stride; a packed [M] array is stride 1. */ const long long astr = r4d_geti_or(a, "anchor_stride", 1); if (anc->dtype != RAD_I32 && anc->dtype != RAD_U32) return R4D_NO(RAD_E_DTYPE); if (astr < 1 || !r4d_contig(anc)) return R4D_NO(RAD_E_SHAPE); if (r4d_numel(anc) < (M - 1) * astr + 1) return R4D_NO(RAD_E_SHAPE); - - return r4d_dflash_select_bf16(cand->data, un->data, has_hp ? hp->data : nullptr, - anc->data, pr->data, sc->data, - out->data, (int)M, (int)steps, (int)K, (int)R, (int)V, - (int)cand_ld, (int)hp_ld, (int)out_ld, (int)astr, s) == 0 - ? RAD_OK : RAD_E_DEVICE; + return R4D_RAW(r4d_dflash_select_bf16(cand->data, un->data, has_hp ? hp->data : nullptr, + anc->data, pr->data, sc->data, + out->data, (int)M, (int)steps, (int)K, (int)R, (int)V, + (int)cand_ld, (int)hp_ld, (int)out_ld, (int)astr, s)); } diff --git a/libr4d/r4d_dt16.h b/libr4d/r4d_dt16.h index 4688b731..d7a241c1 100644 --- a/libr4d/r4d_dt16.h +++ b/libr4d/r4d_dt16.h @@ -1,11 +1,10 @@ -// 16-bit operand traits. The QK and PV matmuls both take a 16-bit A/B pair; which 16-bit format is -// a free choice because BOTH sources are exactly representable in either: -// * an fp8 e4m3 K/V has 3 mantissa bits, so widening to bf16 (7) or f16 (10) is exact; -// * a bf16 query has 7, so bf16->f16 is exact for |q| in [6.1e-5, 65504]. -// The formats are NOT equal in cost. gfx1201 has NO bf16 convert instruction, so every f32->bf16 -// is ~6 VALU of software RTNE, while v_cvt_pkrtz_f16_f32 does TWO f32->f16 in ONE. On the softmax -// path that is 24 VALU per 8-element P fragment against 4. f16 also carries 3 more mantissa bits. -// What f16 gives up is exponent range, and that is exactly what GROW below prices. +// 16-bit operand traits. The QK and PV matmuls take a 16-bit A/B pair, and both sources are exact +// in either format: an fp8 e4m3 K/V has 3 mantissa bits (bf16 has 7, f16 10), and a bf16 query's +// 7 bits are exact in f16 for |q| in [6.1e-5, 65504]. +// The costs differ. gfx1201 has no bf16 convert, so each f32->bf16 is ~6 VALU of software RTNE, +// while v_cvt_pkrtz_f16_f32 converts two f32 in one; on the softmax path that is 24 VALU per +// 8-element P fragment against 4. f16 also has 3 more mantissa bits; it gives up exponent range, +// which GROW below accounts for. #pragma once #include "r4d_common.h" @@ -13,11 +12,10 @@ typedef __bf16 v8bf __attribute__((ext_vector_type(8))); typedef __fp16 v8hf __attribute__((ext_vector_type(8))); // what the f16 WMMA builtin takes typedef __fp16 v2hf __attribute__((ext_vector_type(2))); // what cvt_pkrtz returns -// GROW = how many octaves the running row max may exceed the REFERENCE max before the -// accumulator has to be rescaled. p = 2^(s - m_ref) must stay inside the format, so GROW is -// log2(format max) with margin. This is the whole point of the lazy-rescale scheme: the eager -// online-softmax form pays 128 multiplies EVERY m-tile; with a reference max it pays them only -// when the max moves more than GROW, which at long context is almost never. +// GROW = how many octaves the running row max may exceed the reference max before the accumulator +// must be rescaled. p = 2^(s - m_ref) must stay inside the format, so GROW is log2(format max) with +// margin. Eager online softmax pays 128 multiplies every m-tile; with a reference max they are paid +// only when the max moves by more than GROW, which at long context is rare. template struct DT16; template<> struct DT16<0> { // bf16: exponent range of f32 diff --git a/libr4d/r4d_emit.h b/libr4d/r4d_emit.h index 898245f4..e44185a4 100644 --- a/libr4d/r4d_emit.h +++ b/libr4d/r4d_emit.h @@ -1,26 +1,10 @@ -// r4d_emit.h -- one launch, two destinations: the stream, or a description of it. +// r4d_emit.h -- the one launch path every libr4d kernel goes through. // -// ============================== WHY A SINK ============================== -// -// ABI v10 lets a kernel DESCRIBE its dispatch (`RadDescribeFn`) so the runtime can replay a -// repeatedly issued sequence as a graph instead of submitting it node by node. That gives every -// shim two entry points, and the typedef's comment names the trap they create: `launch` and -// `describe` must dispatch the SAME kernel with the SAME arguments, nothing can check that, and a -// divergence is not a crash -- it is a wrong number produced only after a capture, which reads as -// a numerics bug anywhere but here. -// -// The structural answer is to make the two paths unable to disagree: ONE body computes the -// geometry and emits into a sink, and the sink is either a stream or a descriptor array. Neither -// path can drift, because there is only one of them. -// -// ============================== THE COPY HAZARD ============================== -// -// `RadLaunchDesc::params[i]` points INTO `RadLaunchDesc::blob`. Pack into a local and copy the -// struct into place and every pointer still aims at the dead local -- garbage, and only on the -// graph path. So `r4d_emit` packs DIRECTLY into the destination and the launch path uses a -// descriptor of its own rather than a separate argument list. That is also why the launch path -// goes through `hipLaunchKernel` (which takes kernelParams) rather than the triple-chevron: the -// two paths then share not just the arithmetic but the marshalling. +// `hipLaunchKernel` takes the arguments as an array of pointers (kernelParams) and copies each +// slot's bytes without conversion, so a `long long` passed for a `uint32_t` parameter would fill a +// four-byte slot with eight bytes and corrupt every later argument. r4d_emit takes the kernel +// typed, converts every argument to its declared parameter type, and checks the arity at compile +// time. It also traces each dispatch under RAD_R4D_TRACE and feeds r4d_record_dispatches (r4d.h). #ifndef R4D_EMIT_H #define R4D_EMIT_H @@ -34,152 +18,62 @@ #include "rad_abi.h" #include "r4d_args.h" -/* Where a described launch goes. `desc` null means PERFORM the dispatch; otherwise append to - * `desc[0..cap)` and count it in `*n`. - * - * `stream` is set either way, and is not redundant when describing: a shim whose launch depends on - * which stream it is going onto -- the split-K GEMM takes its arrival counter from a per-stream - * pool -- must make the same choice in both modes, or the description is of a launch that never - * happens. */ -struct R4dSink; -static inline R4dSink r4d_stream_sink(RadStream s); +/* r4d_record_dispatches' log (r4d_rows.cpp): while `r4d_dispatch_log` is set, each launch appends + * its function and counts it in `r4d_dispatch_n`, which may run past `r4d_dispatch_cap`. */ +extern const void** r4d_dispatch_log; +extern int r4d_dispatch_cap; +extern int r4d_dispatch_n; -struct R4dSink { - RadStream stream = nullptr; - RadLaunchDesc* desc = nullptr; - int cap = 0; - int* n = nullptr; -}; - -/* A sink that only launches, for a caller that has a stream and no descriptor. */ -static inline R4dSink r4d_stream_sink(RadStream s) { R4dSink k; k.stream = s; return k; } - -/* Pack one argument into `d` at the next aligned offset and point `params[i]` at it. */ -template -inline bool r4d_pack_one(RadLaunchDesc& d, size_t& off, int& i, const T& v) { - static_assert(__is_trivially_copyable(T), "a kernel argument must be trivially copyable"); - off = (off + alignof(T) - 1) & ~(size_t)(alignof(T) - 1); - if (i >= RAD_MAX_KPARAMS || off + sizeof(T) > RAD_KPARAM_BLOB) return false; - memcpy(d.blob + off, &v, sizeof(T)); - d.param_size[i] = (uint16_t)sizeof(T); - d.params[i++] = d.blob + off; - off += sizeof(T); - return true; -} - -/* A kernel's parameter list as r4d_pack_one lays it out -- each value at its own alignment, in - * declaration order -- so that a kernel whose list runs close to RAD_KPARAM_BLOB or - * RAD_MAX_KPARAMS can assert at compile time that it fits, rather than meet RAD_E_FULL at its - * first launch. `F` is the kernel's function type: `decltype(kernel)`, or for a template - * `decltype(kernel)`. */ -template struct R4dParams; -template struct R4dParams { - static constexpr size_t count = sizeof...(P); - static constexpr size_t bytes() { - size_t off = 0; - ((off = ((off + alignof(P) - 1) & ~(size_t)(alignof(P) - 1)) + sizeof(P)), ...); - return off; - } -}; - -/* THE ONE EMIT, AND IT TAKES THE KERNEL TYPED. - * - * `hipLaunchKernelGGL` type-checks its arguments against the kernel's signature and CONVERTS them - * -- pass a `long long` where the kernel declares `uint32_t` and the compiler narrows it at the - * call. `hipLaunchKernel` takes `kernelParams`, which is raw bytes: the same call would copy eight - * bytes into a slot the kernel reads as four and corrupt every argument after it, silently, with - * no diagnostic anywhere. Over a library's worth of shims that is a defect generator. - * - * So the kernel arrives as `void (*)(P...)`, which deduces its parameter types, and every argument - * is packed as the P the kernel actually declares. The arity is checked too. What the chevron - * launch does for free is done explicitly here, and a mismatch is a compile error rather than a - * wrong number. - * - * `func` is the kernel's host stub -- for a template instantiation, its own symbol, which is the - * point: an instantiation chosen by a parameter moves the FUNCTION and not merely an argument, and - * the runtime has to rebuild rather than update such a node. */ +/* `func` is the kernel's host stub; for a template, the instantiation's own symbol. */ template -inline int r4d_emit(const R4dSink& sk, void (*kernel)(P...), dim3 grid, dim3 block, +inline int r4d_emit(RadStream stream, void (*kernel)(P...), dim3 grid, dim3 block, uint32_t shared_bytes, const A&... args) { static_assert(sizeof...(P) == sizeof...(A), "a kernel argument list must match the kernel's parameter list"); const void* func = (const void*)kernel; - RadLaunchDesc local; - RadLaunchDesc* dst = &local; - if (sk.desc) { - if (!sk.n || *sk.n >= sk.cap) return RAD_E_FULL; - dst = &sk.desc[*sk.n]; - } - RadLaunchDesc& d = *dst; - d.func = func; - d.grid[0] = grid.x; d.grid[1] = grid.y; d.grid[2] = grid.z; - d.block[0] = block.x; d.block[1] = block.y; d.block[2] = block.z; - d.shared_bytes = shared_bytes; - d.n_params = 0; - - size_t off = 0; - int i = 0; - bool ok = true; - /* Converted to the kernel's declared type FIRST, then packed -- see the note above. Left to - * right, so slot i is parameter i. */ std::tuple vals(static_cast

(args)...); - std::apply([&](const P&... v) { ((ok = ok && r4d_pack_one(d, off, i, v)), ...); }, vals); - if (!ok) return RAD_E_FULL; - d.n_params = (uint32_t)i; + void* params[sizeof...(P) + 1]; + std::apply([&](P&... v) { + int i = 0; + ((params[i++] = (void*)&v), ...); + }, vals); + params[sizeof...(P)] = nullptr; - if (sk.desc) { ++*sk.n; return RAD_OK; } - /* THE LAST THING SUBMITTED, NAMED BEFORE IT IS SUBMITTED. A launch that faults inside the - * driver leaves a backtrace through this frame and nothing else: the geometry is in registers - * that -O3 has reused and the kernel is a stub address. Printing it first costs a line per - * dispatch under a flag nobody sets in production, and it is the difference between a shape - * to reproduce and a stack of question marks. Flushed, because the fault is the next - * instruction. */ - /* THE LAST THING SUBMITTED, NAMED BEFORE IT IS SUBMITTED. A launch that faults inside the - * driver leaves a backtrace through this frame and nothing else: the geometry is in registers - * that -O3 has reused and the kernel is a stub address. Printed first, so an `emit` with no - * `ret` after it IS the faulting dispatch. - * - * ONE WRITE A LINE, BECAUSE EVERY RANK IS A THREAD. A line assembled by a sequence of - * fprintf calls interleaves with the other rank's, and the trace then shows dispatches that - * never returned next to returns that belong to nothing -- which is worse than no trace, - * because it reads as evidence. */ + if (r4d_dispatch_log) { + if (r4d_dispatch_n < r4d_dispatch_cap) r4d_dispatch_log[r4d_dispatch_n] = func; + ++r4d_dispatch_n; + } + /* Trace the dispatch before submitting it: a fault inside the driver leaves only this frame, + * with the geometry in reused registers and the kernel a stub address. An `emit` with no + * `ret` after it is the faulting dispatch; flushed because the fault may be next. Each line is + * one write, since every rank is a thread and piecewise fprintf calls would interleave. */ if (r4d_trace_on()) { + static constexpr size_t kSize[] = { sizeof(P)..., 0 }; char line[1024]; int o = snprintf(line, sizeof line, "[r4d] emit %p grid=%ux%ux%u block=%ux%ux%u lds=%u np=%u", func, grid.x, grid.y, grid.z, block.x, block.y, block.z, - shared_bytes, d.n_params); - for (uint32_t k = 0; k < d.n_params && o > 0 && o < (int)sizeof line - 32; ++k) { + shared_bytes, (unsigned)sizeof...(P)); + for (size_t k = 0; k < sizeof...(P) && o > 0 && o < (int)sizeof line - 32; ++k) { unsigned long long v = 0; - memcpy(&v, d.params[k], d.param_size[k] > 8 ? 8 : d.param_size[k]); - o += snprintf(line + o, sizeof line - (size_t)o, " %u:%llx", d.param_size[k], v); + memcpy(&v, params[k], kSize[k] > 8 ? 8 : kSize[k]); + o += snprintf(line + o, sizeof line - (size_t)o, " %u:%llx", (unsigned)kSize[k], v); } std::fprintf(stderr, "%s\n", line); std::fflush(stderr); } - const int rc = hipLaunchKernel(func, grid, block, d.params, shared_bytes, - (hipStream_t)sk.stream) == hipSuccess ? RAD_OK : RAD_E_DEVICE; + const int rc = hipLaunchKernel(func, grid, block, params, shared_bytes, + (hipStream_t)stream) == hipSuccess ? RAD_OK : RAD_E_DEVICE; if (r4d_trace_on()) { std::fprintf(stderr, "[r4d] ret %p %d\n", func, rc); std::fflush(stderr); } return rc; } /* `kernel` is named, not passed as a value, so a template instantiation is spelled at the call - * site exactly as the triple-chevron spelled it. */ -#define R4D_EMIT(sink, kernel, grid, block, lds, ...) \ - r4d_emit((sink), (kernel), (grid), (block), (uint32_t)(lds), __VA_ARGS__) - -/* The two entry points, from one body. `body` is `int (*)(const RadArgs*, const R4dSink&)`. */ -#define R4D_ENTRY(sym, body) \ - extern "C" int sym(const RadArgs* a, RadStream s) { \ - R4dSink sk; sk.stream = s; \ - return body(a, sk); \ - } \ - extern "C" int sym##_describe(const RadArgs* a, RadStream s, RadLaunchDesc* d, \ - int cap, int* n) { \ - if (!n) return RAD_E_INVAL; \ - *n = 0; \ - R4dSink sk; sk.stream = s; sk.desc = d; sk.cap = cap; sk.n = n; \ - return body(a, sk); \ - } + * site exactly as the triple-chevron spelled it. A test may define R4D_EMIT to drive the same + * sources through a host SIMT emulator, as with R4D_KLAUNCH (r4d_launch.h). */ +#ifndef R4D_EMIT +#define R4D_EMIT(stream, kernel, grid, block, lds, ...) \ + r4d_emit((stream), (kernel), (grid), (block), (uint32_t)(lds), __VA_ARGS__) +#endif #endif /* R4D_EMIT_H */ diff --git a/libr4d/r4d_enc.h b/libr4d/r4d_enc.h index 2caed87f..c7df2ad5 100644 --- a/libr4d/r4d_enc.h +++ b/libr4d/r4d_enc.h @@ -1,9 +1,8 @@ -/* r4d_enc.h -- what libr4d's relayouts check of an encoding before they rearrange it. +/* r4d_enc.h -- the encoding checks libr4d's relayouts make before rearranging a weight. * - * A container holds encodings; libr4d's kernels each read a few. A relayout that met an encoding - * its kernel does not read and rearranged it anyway would hand the kernel bytes that decode to - * other numbers -- the failure the layout hook exists to refuse, by name, at declare. These are the - * questions it asks. Pure host C++, like the rest of the declaration side. + * A relayout that rearranged an encoding its kernel does not read would hand the kernel bytes + * that decode to other numbers; the layout hook refuses such a declaration by name instead. Pure + * host C++, like the rest of the declaration side. */ #pragma once #include "rad_abi.h" @@ -32,10 +31,10 @@ inline bool affine(const RadEncoding* e, uint32_t codes, uint32_t scale, int64_t return true; } -/* The same with a SCALAR CODEBOOK: `codes` indexing a `table` plane of `entries` values of dtype - * `tab`, the `scale` as above, `transform` exactly, and no other plane. What the table HOLDS is not - * in an encoding -- a declaration has no plane bytes -- so a kernel that decodes one fixed table - * compares the plane with it when it relayouts. */ +/* The same with a scalar codebook: `codes` indexing a `table` plane of `entries` values of dtype + * `tab`, the `scale` as above, `transform` exactly, and no other plane. A declaration carries no + * plane bytes, so a kernel that decodes one fixed table compares the plane's contents at + * relayout. */ inline bool affine_table(const RadEncoding* e, uint32_t codes, uint32_t scale, int64_t br, int64_t bc, uint32_t tab, int64_t entries, const char* transform = "") { if (!e || !rad_enc_is(e, "affine")) return false; @@ -50,9 +49,8 @@ inline bool affine_table(const RadEncoding* e, uint32_t codes, uint32_t scale, i e->plane[t].extent[0] == 1 && e->plane[t].extent[1] == entries; } -/* affine_table's codebook with a SECOND SCALE LEVEL beside the first: `scale.1` of dtype `scale2`, - * one value for the whole tensor (libquant's block2=*x*). Four planes: codes, scale, scale.1, - * table. */ +/* affine_table's codebook with a second scale level: `scale.1` of dtype `scale2`, one value for + * the whole tensor (libquant's block2=*x*). Four planes: codes, scale, scale.1, table. */ inline bool affine_table2(const RadEncoding* e, uint32_t codes, uint32_t scale, int64_t br, int64_t bc, uint32_t scale2, uint32_t tab, int64_t entries, const char* transform = "") { diff --git a/libr4d/r4d_encoder_bf16.hip b/libr4d/r4d_encoder_bf16.hip index 20972e1f..fc27f612 100644 --- a/libr4d/r4d_encoder_bf16.hip +++ b/libr4d/r4d_encoder_bf16.hip @@ -1,9 +1,8 @@ -// The small ops an encoder issues between its GEMMs and its attention: a gated activation over two -// operands, the QK(V)-norm-and-rotary preamble over a fused projection, mean pooling over -// cu_seqlens segments, and the bf16 -> f32 widening of a pooled row. r4d_model_bf16.hip's rules -// hold here too: each kernel equals a libref function, reductions accumulate in f32 (seg_mean in -// f64, as ref does) and only the store narrows, and the transcendental functions are the accurate -// libm forms. +// Small encoder ops between GEMMs and attention: gated activation over two operands, QK(V) norm + +// rotary over a fused projection, mean pooling over cu_seqlens segments, bf16 -> f32 widening, +// and the audio tower's ops. As in r4d_model_bf16.hip, each kernel equals a libref function: +// reductions accumulate in f32 (seg_mean in f64, as ref does), only the store narrows, and +// transcendentals use the accurate libm forms. #include "r4d.h" #include "r4d_args.h" #include "r4d_common.h" @@ -31,9 +30,8 @@ __device__ __forceinline__ float act_of(float g) { return 0.5f * g * (1.0f + tanhf(0.7978845608028654f * (g + 0.044715f * g * g * g))); } -// THE ROW AXIS IS GRID-STRIDED. A grid's y extent stops at 65535, and an elementwise op over the -// audio subsampler's (time, frequency) rows is 96000 of them: a launch of y = M runs nothing past -// row 65535. A row kernel takes M, launches min(M, kGridYMax) and walks the rest. +// The row axis is grid-strided: grid y is capped at 65535, and the audio subsampler's +// (time, frequency) rows reach 96000. Row kernels launch min(M, kGridYMax) and loop over the rest. constexpr uint32_t kGridYMax = 65535; static inline uint32_t grid_rows(int64_t M) { return (uint32_t)(M < (int64_t)kGridYMax ? M : (int64_t)kGridYMax); @@ -82,20 +80,18 @@ __global__ __launch_bounds__(kThreads) void seg_mean_kernel( // RMS-normed against its gain and rounded to bf16 (the unfused pair stores the norm), then // rotated; with v_norm each v head is RMS-normed with a unit gain and not rotated. // -// ONE WORKGROUP A TOKEN, A WAVE A HEAD, THE HEAD IN REGISTERS. Lane l holds the head's elements -// l, l+32, l+64, ... (neox) or the pairs 2l, 2l+1, 2l+64, 2l+65, ... (gptj), which puts both -// halves of every rotary pair in the same lane: the norm is a wave sum and the rotation needs no -// exchange at all. The token's sin/cos are computed once into LDS for all its heads -- 4 KiB, so -// occupancy is not what LDS decides. A first form staged the token's whole fused row in LDS -// (12 KiB a workgroup at head_dim 512) and ran slower than a workgroup a (token, head). +// One workgroup per token, one wave per head, the head in registers. Lane l holds elements +// l, l+32, l+64, ... (neox) or pairs 2l, 2l+1, 2l+64, 2l+65, ... (gptj), so both halves of every +// rotary pair are in one lane: the norm is a wave sum and the rotation needs no exchange. The +// token's sin/cos are computed once into LDS (4 KiB, not an occupancy limit). // -// The layout needs head_dim a multiple of 32 and, for neox, rotary_dim / 2 a multiple of 32 (for -// gptj, head_dim a multiple of 64); the launcher refuses anything else. +// Requires head_dim a multiple of 32 and, for neox, rotary_dim / 2 a multiple of 32 (gptj: +// head_dim a multiple of 64); the launcher refuses anything else. constexpr uint32_t kQkThreads = 256; constexpr uint32_t kQkMaxHalf = 512; // rotary pairs a head constexpr int kQkMaxE = 32; // elements a lane: head_dim up to 1024 -/* The `blocks` mode's sections: pairs a section, and the position component each one reads. */ +/* `blocks` mode sections: pairs per section and the position component each reads. */ struct QkBlocks { int n = 0; int sec[8] = {}; @@ -217,13 +213,13 @@ __global__ __launch_bounds__(kQkThreads) void qk_norm_rope_kernel( } } -// The `blocks` mode at any head_dim and section size (Gemma 4's vision tower: 72-wide heads, two -// sections of 18 pairs) -- what the register layout above cannot hold. A wave a head and a lane a -// rotated pair: the norm's sum of squares first, then each lane re-reads its pair, norms, gains, -// rounds (the norm rounded before the rotation, as above) and rotates it. Channels past `rot` -// are normed only; a v head (v_norm) is normed at unit gain. +// Section modes at any head_dim and section size, which the register layout above cannot hold +// (e.g. Gemma 4's vision tower: 72-wide heads, two sections of 18 pairs). One wave per head, one +// lane per rotated pair: sum of squares first, then each lane re-reads its pair, norms, applies +// the gain, rounds (before rotation, as above) and rotates. Channels past `rot` are normed only; +// a v head (v_norm) is normed at unit gain. // -// `pm` picks the pairing, which is all that separates three rotaries over the same table: +// `pm` selects the pairing: // 0 blocks a section's pairs are (start + j, start + sec + j), its own ladder // 1 gptj_blocks a section's pairs are ADJACENT, (start + 2j, start + 2j + 1), its own ladder: // the complex-number form of a 3-axis image rotary (Qwen-Image) @@ -298,7 +294,7 @@ __global__ __launch_bounds__(kQkThreads) void qk_norm_rope_any_kernel( // ---------------------------------------------------------------------------- pool_rows // ref_pool_rows: row r of y is the mean of x's rows [r*k, r*k + k), summed in f32 and rounded to -// bf16, then times `mult` and rounded again. A workgroup an output row, a thread a column. +// bf16, then times `mult` and rounded again. One thread per column. __global__ __launch_bounds__(kThreads) void pool_rows_kernel( const uint16_t* __restrict__ x, uint16_t* __restrict__ y, uint32_t n, uint32_t k, float mult, uint32_t x_ld, uint32_t y_ld, uint32_t M) { @@ -323,11 +319,11 @@ __global__ __launch_bounds__(kThreads) void widen_kernel( } // ---------------------------------------------------------------------------- the audio tower -// Gemma 4's USM conformer: an elementwise rectifier and clamp, the subsampler's segment-wise +// Gemma 4's USM conformer: elementwise rectifier and clamp, the subsampler's segment-wise // convolution, the light-conv block's causal depthwise convolution, the relative-position table, -// and the local attention with a relative term. An audio pass is at most a few thousand frames -// (750 tokens for 30 s), so each kernel is the plain form -- a workgroup a row, a thread an -// element -- and equal to its libref function in arithmetic: f32 throughout, one rounding. +// and local attention with a relative term. An audio pass is at most a few thousand frames +// (750 tokens for 30 s), so each kernel is the plain form (a workgroup per row, a thread per +// element) and matches its libref function: f32 throughout, one rounding. // ref_relu. __global__ __launch_bounds__(kThreads) void relu_kernel( @@ -341,8 +337,8 @@ __global__ __launch_bounds__(kThreads) void relu_kernel( } } -// ref_silu: x * sigmoid(x) with the sigmoid taken first, libref's act_silu term for term. The -// audio tower's feed-forward issues it on its own between two clipped linears. +// ref_silu: x * sigmoid(x) with the sigmoid taken first, as libref's act_silu. Used standalone +// between two clipped linears in the audio feed-forward. __global__ __launch_bounds__(kThreads) void silu_kernel( const uint16_t* __restrict__ x, uint16_t* __restrict__ y, uint32_t n, uint32_t x_ld, uint32_t y_ld, uint32_t M) { @@ -372,15 +368,33 @@ __global__ __launch_bounds__(kThreads) void clamp_kernel( struct ConvGeom { int W, cin, cout, kh, kw, st, pad, cdiv, vst, Wo, S; + int tl; /* the weight is [cout, cin, kw, kh]: time last */ + int gelu; /* the epilogue's activation */ }; -// ref_conv2d. A workgroup an OUTPUT time row of the pass: it finds the segment whose output rows -// hold it (a scan over cu_seqlens, which is a handful of entries), and a thread computes output -// elements (width, channel) of that row. Rows no segment covers are left alone, as libref does. +// Kernel tap (i over time, j over width) of channel pair (co, ci), in either weight layout; the +// next input channel is kh * kw further on in both. +__device__ __forceinline__ size_t conv_w(const ConvGeom& g, int co, int ci, int i, int j) { + return g.tl ? (((size_t)co * g.cin + ci) * g.kw + j) * g.kh + i + : (((size_t)co * g.cin + ci) * g.kh + i) * g.kw + j; +} + +// ref_conv2d's epilogue: the sum plus the bias, one rounding; gelu of the rounded value, a second +// rounding. +__device__ __forceinline__ uint16_t conv_out(const ConvGeom& g, float acc, + const uint16_t* __restrict__ bias, int co) { + if (bias) acc += bf2f(bias[co]); + const uint16_t r = f32_to_bf16(acc); + return g.gelu ? f32_to_bf16(act_of<1>(bf2f(r))) : r; +} + +// ref_conv2d. One workgroup per output time row: it finds the covering segment (a scan over the +// few cu_seqlens entries), and threads compute the row's (width, channel) outputs. Rows no +// segment covers are left untouched, as in libref. __global__ __launch_bounds__(kThreads) void conv2d_kernel( const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, const int* __restrict__ cu, - const int* __restrict__ valid, uint16_t* __restrict__ y, ConvGeom g, uint32_t x_ld, - uint32_t y_ld) { + const int* __restrict__ valid, const uint16_t* __restrict__ bias, uint16_t* __restrict__ y, + ConvGeom g, uint32_t x_ld, uint32_t y_ld) { const int r = (int)blockIdx.x; int t0 = -1, T = 0, to = 0; for (int s = 0; s < g.S; ++s) { @@ -406,30 +420,64 @@ __global__ __launch_bounds__(kThreads) void conv2d_kernel( const int wi = wo * g.st - g.pad + j; if (wi < 0 || wi >= g.W) continue; const uint16_t* xv = xr + (size_t)wi * g.cin; - const uint16_t* wv = w + (((size_t)co * g.cin) * g.kh + i) * g.kw + j; + const uint16_t* wv = w + conv_w(g, co, 0, i, j); for (int ci = 0; ci < g.cin; ++ci) acc += bf2f(xv[ci]) * bf2f(wv[(size_t)ci * g.kh * g.kw]); } } - y[(size_t)r * y_ld + e] = f32_to_bf16(acc); + y[(size_t)r * y_ld + e] = conv_out(g, acc, bias, co); } } -// conv2d_kernel's arithmetic with each kernel row's input row and weights staged in LDS: the form -// for the audio subsampler's second convolution, 64 x 128 channels in and 32 x 32 out a row, -// where the plain kernel re-reads every weight from global memory for every output and spends -// 6 ms on a 30 s clip. Weights sit [j][ci][co] so the lanes of a wave -- consecutive output -// channels -- read consecutive LDS words, and each input element is one broadcast. A thread owns -// kConvEpt outputs strided by the workgroup, all of one output channel. The sum runs over i, j, -// ci in the plain kernel's order. +// ref_conv2d_unfold. One workgroup per output time row, found as conv2d_kernel finds it, and one +// thread per (wo, k) element of its Wo unfolded rows: the tap value conv2d would multiply weight +// column k by, or zero in the padding and on a masked row. Columns are in the weight's order, so a +// row's writes are consecutive. +__global__ __launch_bounds__(kThreads) void conv2d_unfold_kernel( + const uint16_t* __restrict__ x, const int* __restrict__ cu, const int* __restrict__ valid, + uint16_t* __restrict__ y, ConvGeom g, uint32_t x_ld, uint32_t y_ld) { + const int r = (int)blockIdx.x; + int t0 = -1, T = 0, to = 0; + for (int s = 0; s < g.S; ++s) { + const int c0 = cu[s], c1 = cu[s + 1]; + if (c0 % g.cdiv || c1 % g.cdiv || (c0 / g.cdiv) % g.st || c1 < c0) continue; + const int a = c0 / g.cdiv, Ts = c1 / g.cdiv - a; + if (Ts <= 0) continue; + const int To = (Ts + 2 * g.pad - g.kh) / g.st + 1, o0 = a / g.st; + if (r >= o0 && r < o0 + To) { t0 = a; T = Ts; to = r - o0; break; } + } + if (t0 < 0) return; + const int K = g.cin * g.kh * g.kw, nel = g.Wo * K; + for (int e = threadIdx.x; e < nel; e += kThreads) { + const int wo = e / K, k = e % K; + int ci, i, j; + if (g.tl) { i = k % g.kh; j = (k / g.kh) % g.kw; ci = k / (g.kh * g.kw); } + else { j = k % g.kw; i = (k / g.kw) % g.kh; ci = k / (g.kh * g.kw); } + const int ti = to * g.st - g.pad + i, wi = wo * g.st - g.pad + j; + uint16_t v = 0; + if (ti >= 0 && ti < T && wi >= 0 && wi < g.W) { + const int tg = t0 + ti; + if (!valid || valid[(size_t)tg * g.vst] != 0) + v = x[(size_t)tg * x_ld + (size_t)wi * g.cin + ci]; + } + y[((size_t)r * g.Wo + wo) * y_ld + k] = v; + } +} + +// conv2d_kernel's arithmetic with each kernel row's input row and weights staged in LDS, for the +// audio subsampler's second convolution (64 x 128 channels in, 32 x 32 out per row), where the +// plain kernel re-reads every weight from global per output (6 ms on a 30 s clip). Weights are +// [j][ci][co] so a wave's lanes (consecutive output channels) read consecutive LDS words and each +// input element is a broadcast. A thread owns kConvEpt outputs strided by the workgroup, all of +// one output channel. Summation order (i, j, ci) matches the plain kernel. constexpr int kConvEpt = 4; constexpr int kConvXs = 8192; /* W * cin, one input row */ constexpr int kConvWs = 12288; /* kw * cin * cout, one kernel row's weights */ __global__ __launch_bounds__(kThreads) void conv2d_lds_kernel( const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, const int* __restrict__ cu, - const int* __restrict__ valid, uint16_t* __restrict__ y, ConvGeom g, uint32_t x_ld, - uint32_t y_ld) { + const int* __restrict__ valid, const uint16_t* __restrict__ bias, uint16_t* __restrict__ y, + ConvGeom g, uint32_t x_ld, uint32_t y_ld) { __shared__ uint16_t xs[kConvXs]; __shared__ uint16_t ws[kConvWs]; const int r = (int)blockIdx.x; @@ -458,7 +506,7 @@ __global__ __launch_bounds__(kThreads) void conv2d_lds_kernel( for (int e = tid; e < nx; e += kThreads) xs[e] = xr[e]; for (int e = tid; e < nw; e += kThreads) { const int co = e % g.cout, rest = e / g.cout, ci = rest % g.cin, j = rest / g.cin; - ws[e] = w[(((size_t)co * g.cin + ci) * g.kh + i) * g.kw + j]; + ws[e] = w[conv_w(g, co, ci, i, j)]; } __syncthreads(); #pragma unroll @@ -480,11 +528,11 @@ __global__ __launch_bounds__(kThreads) void conv2d_lds_kernel( #pragma unroll for (int q = 0; q < kConvEpt; ++q) { const int e = tid + q * kThreads; - if (e < nel) y[(size_t)r * y_ld + e] = f32_to_bf16(acc[q]); + if (e < nel) y[(size_t)r * y_ld + e] = conv_out(g, acc[q], bias, e % g.cout); } } -// ref_conv1d_dw. A thread a (row, channel); the segment found by a scan over cu_seqlens. +// ref_conv1d_dw. One thread per (row, channel); the segment is found by a scan over cu_seqlens. __global__ __launch_bounds__(kThreads) void conv1d_dw_kernel( const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, const int* __restrict__ cu, uint16_t* __restrict__ y, int C, int K, int cdiv, int S, uint32_t x_ld, uint32_t y_ld, @@ -521,8 +569,29 @@ __global__ __launch_bounds__(kThreads) void rel_sinusoid_kernel( } } -// ref_attn_local_rel. A workgroup a (query row, head), a thread a head dimension; each of the at -// most left + 1 logits is a workgroup sum, then the softmax over them and the weighted sum of v. +// ref_seg_sinusoid: rel_sinusoid's table at position (r - segment start) mod period. One workgroup +// per row; its segment is found by a scan over the few cu_seqlens entries, and rows no segment +// covers are left untouched, as in libref. +__global__ __launch_bounds__(kThreads) void seg_sinusoid_kernel( + const int* __restrict__ cu, uint16_t* __restrict__ y, uint32_t h, float inc, uint32_t y_ld, + int S, int cdiv, int period) { + const int r = (int)blockIdx.x; + int p = -1; + for (int s = 0; s < S; ++s) { + const int r0 = cu[s] / cdiv, r1 = cu[s + 1] / cdiv; + if (r >= r0 && r < r1) { p = (r - r0) % period; break; } + } + if (p < 0) return; + for (uint32_t i = threadIdx.x; i < h; i += kThreads) { + const float inv = expf((float)i * -inc); + const float ang = (float)p * inv; + y[(size_t)r * y_ld + i] = f32_to_bf16(sinf(ang)); + y[(size_t)r * y_ld + h + i] = f32_to_bf16(cosf(ang)); + } +} + +// ref_attn_local_rel. One workgroup per (query row, head), one thread per head dimension. Each of +// the at most left + 1 logits is a workgroup sum, followed by the softmax and the weighted sum of v. constexpr uint32_t kLrThreads = 128; constexpr int kLrMaxKeys = 64; @@ -624,7 +693,7 @@ extern "C" int r4d_qk_norm_rope_bf16(long qkv, long pos, long qw, long kw, int M (rot & 1) || rot / 2 > (int)kQkMaxHalf || head_dim > 32 * kQkMaxE || mode < 0 || mode > 4) return -2; if (mode >= 3) { - /* The two forms only the general kernel takes: its pair table is built per mode. */ + /* gptj_blocks and imrope: general kernel only (its pair table is built per mode). */ if (!blk || blk->n <= 0 || blk->n > 8) return -2; int total = 0; for (int c = 0; c < blk->n; ++c) { @@ -645,7 +714,7 @@ extern "C" int r4d_qk_norm_rope_bf16(long qkv, long pos, long qw, long kw, int M if (mode == 1 && head_dim % 64) return -2; if (mode == 0 && (rot / 2) % 32) return -2; QkBlocks b{}; - bool any = false; /* the blocks mode outside the register layout: qk_norm_rope_any_kernel */ + bool any = false; /* blocks mode outside the register layout: use qk_norm_rope_any_kernel */ if (mode == 2) { if (!blk || blk->n <= 0 || blk->n > 8) return -2; b = *blk; @@ -729,10 +798,9 @@ extern "C" int r4d_clamp_bf16(long x, long lo, long hi, int b_f32, long y, int M return hipGetLastError() == hipSuccess ? 0 : -4; } -/* `rows_out` is the output operand's rows: a workgroup each, every one a segment does not cover - * returning at once. */ -extern "C" int r4d_conv2d_bf16(long x, long w, long cu, long valid, long y, int rows_out, - const ConvGeom* g, int x_ld, int y_ld, long stream) { +/* One workgroup per output row (`rows_out`); rows no segment covers return at once. */ +extern "C" int r4d_conv2d_bf16(long x, long w, long cu, long valid, long bias, long y, + int rows_out, const ConvGeom* g, int x_ld, int y_ld, long stream) { if (!x || !w || !cu || !y || !g) return -1; if (rows_out <= 0 || g->Wo <= 0 || g->S <= 0) return -2; const bool lds = g->W * g->cin <= kConvXs && g->kw * g->cin * g->cout <= kConvWs && @@ -740,13 +808,24 @@ extern "C" int r4d_conv2d_bf16(long x, long w, long cu, long valid, long y, int if (lds) hipLaunchKernelGGL(conv2d_lds_kernel, dim3((uint32_t)rows_out), dim3(kThreads), 0, (hipStream_t)stream, (const uint16_t*)x, (const uint16_t*)w, - (const int*)cu, (const int*)valid, (uint16_t*)y, *g, (uint32_t)x_ld, - (uint32_t)y_ld); + (const int*)cu, (const int*)valid, (const uint16_t*)bias, (uint16_t*)y, + *g, (uint32_t)x_ld, (uint32_t)y_ld); else hipLaunchKernelGGL(conv2d_kernel, dim3((uint32_t)rows_out), dim3(kThreads), 0, (hipStream_t)stream, (const uint16_t*)x, (const uint16_t*)w, - (const int*)cu, (const int*)valid, (uint16_t*)y, *g, (uint32_t)x_ld, - (uint32_t)y_ld); + (const int*)cu, (const int*)valid, (const uint16_t*)bias, (uint16_t*)y, + *g, (uint32_t)x_ld, (uint32_t)y_ld); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* One workgroup per output time row (`rows_out`, the operand's rows over Wo). */ +extern "C" int r4d_conv2d_unfold_bf16(long x, long cu, long valid, long y, int rows_out, + const ConvGeom* g, int x_ld, int y_ld, long stream) { + if (!x || !cu || !y || !g) return -1; + if (rows_out <= 0 || g->Wo <= 0 || g->S <= 0) return -2; + hipLaunchKernelGGL(conv2d_unfold_kernel, dim3((uint32_t)rows_out), dim3(kThreads), 0, + (hipStream_t)stream, (const uint16_t*)x, (const int*)cu, + (const int*)valid, (uint16_t*)y, *g, (uint32_t)x_ld, (uint32_t)y_ld); return hipGetLastError() == hipSuccess ? 0 : -4; } @@ -773,6 +852,18 @@ extern "C" int r4d_rel_sinusoid_bf16(long y, int rows, int n, double max_timesca return hipGetLastError() == hipSuccess ? 0 : -4; } +extern "C" int r4d_seg_sinusoid_bf16(long cu, int S, long y, int rows, int n, int period, int cdiv, + double max_timescale, int y_ld, long stream) { + if (!cu || !y) return -1; + if (rows <= 0 || n <= 0 || (n & 1) || period <= 0 || cdiv <= 0 || S <= 0) return -2; + const int h = n / 2; + const float inc = (float)(std::log(max_timescale / 1.0) / (double)(h - 1 > 1 ? h - 1 : 1)); + hipLaunchKernelGGL(seg_sinusoid_kernel, dim3((uint32_t)rows), dim3(kThreads), 0, + (hipStream_t)stream, (const int*)cu, (uint16_t*)y, (uint32_t)h, inc, + (uint32_t)y_ld, S, cdiv, period); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + extern "C" int r4d_attn_local_rel_bf16(long q, long k, long v, long rk, long pds, long cu, long o, int rows, const LocalRelGeom* g, long stream) { if (!q || !k || !v || !rk || !pds || !cu || !o || !g) return -1; @@ -791,6 +882,13 @@ static inline int dt_bf16(const RadTensor* t) { } #define R4D_NEED(x) do { const int _s = (x); if (_s != RAD_OK) return R4D_NO(_s); } while (0) +/* The entry points above return 0, -4 for a failed launch, or another negative code for a shape + * they do not serve. */ +static inline int enc_status(int rc) { + if (rc == 0) return RAD_OK; + return R4D_NO(rc == -4 ? RAD_E_DEVICE : RAD_E_SHAPE); +} + /* ------------------------------------------------------------------ act_mul */ extern "C" int r4d_rad_act_mul(const RadArgs* a, RadStream s) { const RadTensor* A = r4d_opt(a, 0); @@ -815,9 +913,8 @@ extern "C" int r4d_rad_act_mul(const RadArgs* a, RadStream s) { const long long b_ld = r4d_rows_pitch(B, n, &Mb); if (y_ld < 0 || a_ld < 0 || b_ld < 0) return R4D_NO(RAD_E_STRIDE); if (M <= 0 || Ma < M || Mb < M) return R4D_NO(RAD_E_SHAPE); - return r4d_act_mul_bf16(r4d_addr(A), r4d_addr(B), r4d_addr(Y), (int)M, (int)n, ai, (int)a_ld, - (int)b_ld, (int)y_ld, (long)(uintptr_t)s) == 0 ? RAD_OK - : RAD_E_DEVICE; + return enc_status(r4d_act_mul_bf16(r4d_addr(A), r4d_addr(B), r4d_addr(Y), (int)M, (int)n, ai, + (int)a_ld, (int)b_ld, (int)y_ld, (long)(uintptr_t)s)); } /* ------------------------------------------------------------------ seg_mean */ @@ -837,8 +934,8 @@ extern "C" int r4d_rad_seg_mean(const RadArgs* a, RadStream s) { const long long y_ld = r4d_rows_pitch(Y, n, &My); if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE); if (My < S) return R4D_NO(RAD_E_SHAPE); - return r4d_seg_mean_bf16(r4d_addr(X), r4d_addr(cu), r4d_addr(Y), (int)S, (int)n, (int)x_ld, - (int)y_ld, (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; + return enc_status(r4d_seg_mean_bf16(r4d_addr(X), r4d_addr(cu), r4d_addr(Y), (int)S, (int)n, + (int)x_ld, (int)y_ld, (long)(uintptr_t)s)); } /* ------------------------------------------------------------------ qk_norm_rope */ @@ -873,8 +970,7 @@ extern "C" int r4d_rad_qk_norm_rope(const RadArgs* a, RadStream s) { const long long rot = r4d_geti_or(a, "rotary_dim", hd); if (hd <= 0 || nh <= 0 || nkv <= 0 || r4d_numel(qw) < hd || r4d_numel(kw) < hd) return R4D_NO(RAD_E_SHAPE); - /* A head lives in a wave's registers with both halves of a rotary pair in one lane (or, for a - * 16-pair block, in the two half-waves): head_dim a multiple of 32 up to 1024. */ + /* The register layout holds head_dim up to 1024 (32 lanes x kQkMaxE). */ if (hd > 1024 || rot > hd || (rot & 1)) return R4D_NO(RAD_E_SHAPE); const char* mode = r4d_gets(a, "mode"); int md = 0; @@ -888,7 +984,7 @@ extern "C" int r4d_rad_qk_norm_rope(const RadArgs* a, RadStream s) { QkBlocks blk{}; long long M = 0, pplane = 0; if (md == 4) { - /* Interleaved M-RoPE reads three position planes, its sections only bound the + /* Interleaved M-RoPE reads three position planes; its sections only bound the * interleave. */ blk.n = parse_ints(r4d_gets(a, "sections"), blk.sec, 8); if (blk.n < 3 || pos->rank != 2 || pos->shape[0] < 3) return R4D_NO(RAD_E_SHAPE); @@ -922,7 +1018,7 @@ extern "C" int r4d_rad_qk_norm_rope(const RadArgs* a, RadStream s) { (float)r4d_getf(a, "wadd", 0.0), (int)ld, &blk, (int)pplane, (long)(uintptr_t)s); if (e == -2) return R4D_NO(RAD_E_SHAPE); - return e == 0 ? RAD_OK : RAD_E_DEVICE; + return enc_status(e); } /* ------------------------------------------------------------------ pool_rows */ @@ -939,9 +1035,9 @@ extern "C" int r4d_rad_pool_rows(const RadArgs* a, RadStream s) { const long long y_ld = r4d_rows_pitch(Y, n, &My); if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE); if (Mx <= 0 || Mx % k || My < Mx / k) return R4D_NO(RAD_E_SHAPE); - return r4d_pool_rows_bf16(r4d_addr(X), r4d_addr(Y), (int)(Mx / k), (int)n, (int)k, - (float)r4d_getf(a, "mult", 1.0), (int)x_ld, (int)y_ld, - (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; + return enc_status(r4d_pool_rows_bf16(r4d_addr(X), r4d_addr(Y), (int)(Mx / k), (int)n, (int)k, + (float)r4d_getf(a, "mult", 1.0), (int)x_ld, (int)y_ld, + (long)(uintptr_t)s)); } /* ------------------------------------------------------------------ cast bf16 -> f32 */ @@ -958,8 +1054,8 @@ extern "C" int r4d_rad_cast_widen(const RadArgs* a, RadStream s) { const long long x_ld = r4d_rows_pitch(x, n, &Mx); if (y_ld < 0 || x_ld < 0) return R4D_NO(RAD_E_STRIDE); if (M <= 0 || Mx < M) return R4D_NO(RAD_E_SHAPE); - return r4d_widen_bf16_f32(r4d_addr(x), r4d_addr(y), (int)M, (int)n, (int)x_ld, (int)y_ld, - (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; + return enc_status(r4d_widen_bf16_f32(r4d_addr(x), r4d_addr(y), (int)M, (int)n, (int)x_ld, + (int)y_ld, (long)(uintptr_t)s)); } /* ------------------------------------------------------------------ the audio tower */ @@ -977,8 +1073,8 @@ extern "C" int r4d_rad_relu(const RadArgs* a, RadStream s) { const long long x_ld = r4d_rows_pitch(X, n, &Mx); if (y_ld < 0 || x_ld < 0) return R4D_NO(RAD_E_STRIDE); if (M <= 0 || Mx < M) return R4D_NO(RAD_E_SHAPE); - return r4d_relu_bf16(r4d_addr(X), r4d_addr(Y), (int)M, (int)n, (int)x_ld, (int)y_ld, - (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; + return enc_status(r4d_relu_bf16(r4d_addr(X), r4d_addr(Y), (int)M, (int)n, (int)x_ld, (int)y_ld, + (long)(uintptr_t)s)); } extern "C" int r4d_rad_silu(const RadArgs* a, RadStream s) { @@ -994,8 +1090,8 @@ extern "C" int r4d_rad_silu(const RadArgs* a, RadStream s) { const long long x_ld = r4d_rows_pitch(X, n, &Mx); if (y_ld < 0 || x_ld < 0) return R4D_NO(RAD_E_STRIDE); if (M <= 0 || Mx < M) return R4D_NO(RAD_E_SHAPE); - return r4d_silu_bf16(r4d_addr(X), r4d_addr(Y), (int)M, (int)n, (int)x_ld, (int)y_ld, - (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; + return enc_status(r4d_silu_bf16(r4d_addr(X), r4d_addr(Y), (int)M, (int)n, (int)x_ld, (int)y_ld, + (long)(uintptr_t)s)); } extern "C" int r4d_rad_clamp(const RadArgs* a, RadStream s) { @@ -1016,9 +1112,9 @@ extern "C" int r4d_rad_clamp(const RadArgs* a, RadStream s) { const long long x_ld = r4d_rows_pitch(X, n, &Mx); if (y_ld < 0 || x_ld < 0) return R4D_NO(RAD_E_STRIDE); if (M <= 0 || Mx < M) return R4D_NO(RAD_E_SHAPE); - return r4d_clamp_bf16(r4d_addr(X), r4d_addr(L), r4d_addr(H), L->dtype == RAD_F32, - r4d_addr(Y), (int)M, (int)n, (int)x_ld, (int)y_ld, - (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; + return enc_status(r4d_clamp_bf16(r4d_addr(X), r4d_addr(L), r4d_addr(H), L->dtype == RAD_F32, + r4d_addr(Y), (int)M, (int)n, (int)x_ld, (int)y_ld, + (long)(uintptr_t)s)); } extern "C" int r4d_rad_conv2d(const RadArgs* a, RadStream s) { @@ -1027,10 +1123,12 @@ extern "C" int r4d_rad_conv2d(const RadArgs* a, RadStream s) { const RadTensor* cu = r4d_opt(a, 2); const RadTensor* V = r4d_opt(a, 3); const RadTensor* Y = r4d_opt(a, 4); + const RadTensor* B = r4d_opt(a, 5); if (!X || !Wt || !cu || !Y) return R4D_NO(RAD_E_INVAL); R4D_NEED(dt_bf16(X)); R4D_NEED(dt_bf16(Wt)); R4D_NEED(dt_bf16(Y)); + if (B && (dt_bf16(B) != RAD_OK || !r4d_contig(B))) return R4D_NO(RAD_E_DTYPE); if (cu->dtype != RAD_I32 || !r4d_contig(cu) || r4d_numel(cu) < 2) return R4D_NO(RAD_E_SHAPE); if (V && (V->dtype != RAD_I32 || !r4d_contig(V))) return R4D_NO(RAD_E_DTYPE); if (!r4d_contig(Wt)) return R4D_NO(RAD_E_STRIDE); @@ -1044,6 +1142,11 @@ extern "C" int r4d_rad_conv2d(const RadArgs* a, RadStream s) { g.pad = (int)r4d_geti_or(a, "pad", 0); g.cdiv = (int)r4d_geti_or(a, "cu_div", 1); g.vst = (int)r4d_geti_or(a, "valid_stride", 1); + g.tl = r4d_geti_or(a, "t_last", 0) != 0 ? 1 : 0; + const char* act = r4d_gets(a, "act"); + if (!act) act = "none"; + g.gelu = !std::strcmp(act, "gelu") ? 1 : 0; + if (!g.gelu && std::strcmp(act, "none")) return R4D_NO(RAD_E_UNSUPPORTED); if (g.W <= 0 || g.cin <= 0 || g.cout <= 0 || g.kh <= 0 || g.kw <= 0 || g.st <= 0 || g.pad < 0 || g.cdiv <= 0 || g.vst <= 0) return R4D_NO(RAD_E_SHAPE); @@ -1051,14 +1154,52 @@ extern "C" int r4d_rad_conv2d(const RadArgs* a, RadStream s) { g.S = (int)(r4d_numel(cu) - 1); if (g.Wo <= 0 || r4d_numel(Wt) < (long long)g.cout * g.cin * g.kh * g.kw) return R4D_NO(RAD_E_SHAPE); + if (B && r4d_numel(B) < g.cout) return R4D_NO(RAD_E_SHAPE); long long Mx = 0, My = 0; const long long x_ld = r4d_rows_pitch(X, (long long)g.W * g.cin, &Mx); const long long y_ld = r4d_rows_pitch(Y, (long long)g.Wo * g.cout, &My); if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE); if (Mx <= 0 || My <= 0) return R4D_NO(RAD_E_SHAPE); - return r4d_conv2d_bf16(r4d_addr(X), r4d_addr(Wt), r4d_addr(cu), V ? r4d_addr(V) : 0, - r4d_addr(Y), (int)My, &g, (int)x_ld, (int)y_ld, - (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; + return enc_status(r4d_conv2d_bf16(r4d_addr(X), r4d_addr(Wt), r4d_addr(cu), V ? r4d_addr(V) : 0, + B ? r4d_addr(B) : 0, r4d_addr(Y), (int)My, &g, (int)x_ld, + (int)y_ld, (long)(uintptr_t)s)); +} + +extern "C" int r4d_rad_conv2d_unfold(const RadArgs* a, RadStream s) { + const RadTensor* X = r4d_opt(a, 0); + const RadTensor* cu = r4d_opt(a, 1); + const RadTensor* V = r4d_opt(a, 2); + const RadTensor* Y = r4d_opt(a, 3); + if (!X || !cu || !Y) return R4D_NO(RAD_E_INVAL); + R4D_NEED(dt_bf16(X)); + R4D_NEED(dt_bf16(Y)); + if (cu->dtype != RAD_I32 || !r4d_contig(cu) || r4d_numel(cu) < 2) return R4D_NO(RAD_E_SHAPE); + if (V && (V->dtype != RAD_I32 || !r4d_contig(V))) return R4D_NO(RAD_E_DTYPE); + ConvGeom g{}; + g.W = (int)r4d_geti_or(a, "width", 0); + g.cin = (int)r4d_geti_or(a, "cin", 0); + g.cout = 1; + g.kh = (int)r4d_geti_or(a, "kh", 0); + g.kw = (int)r4d_geti_or(a, "kw", 0); + g.st = (int)r4d_geti_or(a, "stride", 1); + g.pad = (int)r4d_geti_or(a, "pad", 0); + g.cdiv = (int)r4d_geti_or(a, "cu_div", 1); + g.vst = (int)r4d_geti_or(a, "valid_stride", 1); + g.tl = r4d_geti_or(a, "t_last", 0) != 0 ? 1 : 0; + if (g.W <= 0 || g.cin <= 0 || g.kh <= 0 || g.kw <= 0 || g.st <= 0 || g.pad < 0 || + g.cdiv <= 0 || g.vst <= 0) + return R4D_NO(RAD_E_SHAPE); + g.Wo = (g.W + 2 * g.pad - g.kw) / g.st + 1; + g.S = (int)(r4d_numel(cu) - 1); + if (g.Wo <= 0) return R4D_NO(RAD_E_SHAPE); + long long Mx = 0, My = 0; + const long long x_ld = r4d_rows_pitch(X, (long long)g.W * g.cin, &Mx); + const long long y_ld = r4d_rows_pitch(Y, (long long)g.cin * g.kh * g.kw, &My); + if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE); + if (Mx <= 0 || My <= 0 || My % g.Wo) return R4D_NO(RAD_E_SHAPE); + return enc_status(r4d_conv2d_unfold_bf16(r4d_addr(X), r4d_addr(cu), V ? r4d_addr(V) : 0, + r4d_addr(Y), (int)(My / g.Wo), &g, (int)x_ld, + (int)y_ld, (long)(uintptr_t)s)); } extern "C" int r4d_rad_conv1d_dw(const RadArgs* a, RadStream s) { @@ -1080,9 +1221,10 @@ extern "C" int r4d_rad_conv1d_dw(const RadArgs* a, RadStream s) { const long long y_ld = r4d_rows_pitch(Y, C, &My); if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE); if (My <= 0 || Mx < My) return R4D_NO(RAD_E_SHAPE); - return r4d_conv1d_dw_bf16(r4d_addr(X), r4d_addr(Wt), r4d_addr(cu), r4d_addr(Y), (int)My, - (int)C, (int)K, (int)cdiv, (int)(r4d_numel(cu) - 1), (int)x_ld, - (int)y_ld, (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; + return enc_status(r4d_conv1d_dw_bf16(r4d_addr(X), r4d_addr(Wt), r4d_addr(cu), r4d_addr(Y), + (int)My, (int)C, (int)K, (int)cdiv, + (int)(r4d_numel(cu) - 1), (int)x_ld, (int)y_ld, + (long)(uintptr_t)s)); } extern "C" int r4d_rad_rel_sinusoid(const RadArgs* a, RadStream s) { @@ -1095,11 +1237,29 @@ extern "C" int r4d_rad_rel_sinusoid(const RadArgs* a, RadStream s) { const long long y_ld = r4d_rows_pitch(Y, n, &M); if (y_ld < 0) return R4D_NO(RAD_E_STRIDE); if (M <= 0) return R4D_NO(RAD_E_SHAPE); - /* libref reads the parameter as a float before widening it; the same here, so a timescale - * that is not a float is rounded in both. */ + /* Round through float, as libref reads the parameter, so both agree. */ const double mt = (double)(float)r4d_getf(a, "max_timescale", 10000.0); - return r4d_rel_sinusoid_bf16(r4d_addr(Y), (int)M, (int)n, mt, (int)y_ld, - (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; + return enc_status(r4d_rel_sinusoid_bf16(r4d_addr(Y), (int)M, (int)n, mt, (int)y_ld, + (long)(uintptr_t)s)); +} + +extern "C" int r4d_rad_seg_sinusoid(const RadArgs* a, RadStream s) { + const RadTensor* cu = r4d_opt(a, 0); + const RadTensor* Y = r4d_opt(a, 1); + if (!cu || !Y) return R4D_NO(RAD_E_INVAL); + R4D_NEED(dt_bf16(Y)); + if (cu->dtype != RAD_I32 || !r4d_contig(cu) || r4d_numel(cu) < 2) return R4D_NO(RAD_E_SHAPE); + const long long n = r4d_geti_or(a, "n", 0), period = r4d_geti_or(a, "period", 0); + const long long cdiv = r4d_geti_or(a, "cu_div", 1); + if (n <= 0 || (n & 1) || period <= 0 || cdiv <= 0) return R4D_NO(RAD_E_SHAPE); + long long M = 0; + const long long y_ld = r4d_rows_pitch(Y, n, &M); + if (y_ld < 0) return R4D_NO(RAD_E_STRIDE); + if (M <= 0) return R4D_NO(RAD_E_SHAPE); + const double mt = (double)(float)r4d_getf(a, "max_timescale", 10000.0); + return enc_status(r4d_seg_sinusoid_bf16(r4d_addr(cu), (int)(r4d_numel(cu) - 1), r4d_addr(Y), + (int)M, (int)n, (int)period, (int)cdiv, mt, (int)y_ld, + (long)(uintptr_t)s)); } extern "C" int r4d_rad_attn_local_rel(const RadArgs* a, RadStream s) { @@ -1142,7 +1302,7 @@ extern "C" int r4d_rad_attn_local_rel(const RadArgs* a, RadStream s) { g.ks = (float)(std::log(1.0 + std::exp(1.0)) / std::log(2.0)); g.q_ld = (uint32_t)q_ld; g.k_ld = (uint32_t)k_ld; g.v_ld = (uint32_t)v_ld; g.r_ld = (uint32_t)r_ld; g.o_ld = (uint32_t)o_ld; - return r4d_attn_local_rel_bf16(r4d_addr(q), r4d_addr(k), r4d_addr(v), r4d_addr(rk), - r4d_addr(pds), r4d_addr(cu), r4d_addr(o), (int)Mo, &g, - (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; + return enc_status(r4d_attn_local_rel_bf16(r4d_addr(q), r4d_addr(k), r4d_addr(v), r4d_addr(rk), + r4d_addr(pds), r4d_addr(cu), r4d_addr(o), (int)Mo, &g, + (long)(uintptr_t)s)); } diff --git a/libr4d/r4d_expert_scale_bf16.hip b/libr4d/r4d_expert_scale_bf16.hip index 650f4561..a43948ae 100644 --- a/libr4d/r4d_expert_scale_bf16.hip +++ b/libr4d/r4d_expert_scale_bf16.hip @@ -1,16 +1,14 @@ /* r4d_expert_scale_bf16.hip -- expert_scale: each routing weight times its expert's own scale, in place. * - * Gemma 4's router renormalises its top-k and then multiplies each weight by per_expert_scale of - * the expert it chose. Said in the conventional vocabulary that is two launches a MoE layer -- an - * `embed_lookup` of the [n_expert, 1] scale table by the expert ids, then a `mul` into the weights - * -- each a few dozen elements behind a full dispatch at decode. This is the pair as one: + * Gemma 4's router renormalises its top-k, then multiplies each weight by its expert's + * per_expert_scale. Unfused that is two launches per MoE layer (`embed_lookup` of the [n_expert, 1] + * scale table by expert id, then `mul`), each a few dozen elements at decode. Fused: * * ew[t, k] = bf16( ew[t, k] * scale[ids[t, k]] ) * - * THE CHAIN'S VALUE, BIT FOR BIT: the lookup copies a bf16 scale and the multiply is one f32 - * product rounded once to nearest even, which is all this does. An id outside the table reads a - * zero scale, as embed_lookup writes a zero row for an id it does not hold, and the product's sign - * survives it the same way. One thread an element; a decode step is a handful of rows. + * Bit-identical to the pair: one f32 product of two bf16 values, rounded once to nearest even. An + * id outside the table reads a zero scale, as embed_lookup writes a zero row, so the product's + * sign matches too. One thread per element. */ #include diff --git a/libr4d/r4d_fp8_args.h b/libr4d/r4d_fp8_args.h index 84d163e0..2446a3b7 100644 --- a/libr4d/r4d_fp8_args.h +++ b/libr4d/r4d_fp8_args.h @@ -1,10 +1,8 @@ -/* r4d_fp8_args.h -- the block-scaled fp8 family's operand list, read once for five kernels. +/* r4d_fp8_args.h -- operand list of the block-scaled fp8 GEMM family. * - * Every kernel that reads `.weight` as the checkpoint stores it -- F8_E4M3 [N][K] with a - * BF16 scale on a [ceil(N/128)][ceil(K/128)] grid -- takes the same five operands in the same - * order, because they implement the same op at different M. The reader belongs to the family, so - * it is a header beside them rather than an adapter between them and the core. See - * libr4d/r4d_args.h. + * Every kernel that reads `.weight` as the checkpoint stores it (F8_E4M3 [N][K] with a + * BF16 scale on a [ceil(N/128)][ceil(K/128)] grid) implements the same op at a different M and + * takes the same five operands in the same order. See libr4d/r4d_args.h. */ #ifndef R4D_FP8_ARGS_H #define R4D_FP8_ARGS_H @@ -15,38 +13,29 @@ enum { F_A = 0, F_ASCALE = 1, F_B = 2, F_BSCALE = 3, F_Y = 4 }; /* ...and for `quant_act_fp8` and `sample_chain`. */ enum { QF_X = 0, QF_Q = 1, QF_S = 2 }; -/* The two fused forms. Shaped on their int8 siblings (`rmsnorm_had_quant_i8`, - * `gated_had_quant_i8`) minus the operands the rotation needs, so an architecture that switches - * activation format changes op names and not operand order. */ +/* The fused forms follow their int8 siblings (`rmsnorm_had_quant_i8`, `gated_had_quant_i8`) + * minus the rotation's operands, so switching activation format changes op names only. */ enum { RQ_X = 0, RQ_RES = 1, RQ_W = 2, RQ_Q = 3, RQ_S = 4, RQ_Y = 5 }; enum { GQ_GU = 0, GQ_Q = 1, GQ_S = 2, GQ_Y = 3 }; enum { TQ_G = 0, TQ_X = 1, TQ_Q = 2, TQ_S = 3, TQ_Y = 4 }; enum { SC_LOGITS = 0, SC_QUERY = 1, SC_U = 2, SC_DRAW = 3 }; -/* A required integer parameter, or 0. Distinct from r4d_geti_or's defaulting because these three - * have no sensible default: a geometry without M, N and K is not a geometry. */ -static inline long long aff_or(const RadArgs* a, const char* k) { return r4d_geti_or(a, k, 0); } - struct Fp8Ops { const RadTensor *a, *ascale, *b, *bscale, *y; long long M, N, K, nkb; - long a_ld, sa_ld, w_ld, sw_ld; /* a_ld / w_ld in ELEMENTS here; see the note at each use */ + long a_ld, sa_ld, w_ld, sw_ld; /* a_ld / w_ld in elements here; see the note at each use */ }; -/* Pitches, and the one place this family's two operand pitches are read. - * - * libr4d takes the WEIGHT pitch in BYTES and the SCALE pitch in ELEMENTS, which is not an - * inconsistency: an E4M3 row is bytes and a bf16 scale row is not, and giving both the same unit - * would make one of the two conversions invisible at the call site. Restated here so the shim - * cannot get it wrong quietly. */ -/* The weight's scale plane: per 128x128 tile (block E4M3), or per ROW per 128 K (the int8 twins). */ +/* Reads this family's operands and pitches. libr4d takes the weight pitch in bytes and the scale + * pitch in elements: an E4M3 row is bytes, a bf16 scale row is not. */ +/* The weight's scale plane: per 128x128 tile (block E4M3), or per row per 128 K (the int8 twins). */ enum { FP8_OPS_BLOCK_SCALE = 0, FP8_OPS_ROW_SCALE = 1 }; static inline int fp8_ops(const RadArgs* a, Fp8Ops* g, int want_ascale, int wscale = FP8_OPS_BLOCK_SCALE) { std::memset(g, 0, sizeof(*g)); - /* No fp8 or int8 block GEMM reads a partitioned weight's `pb1`/`pb2`; refused, not ignored (see - * gemm_ops). */ + /* No fp8 or int8 block GEMM reads a partitioned weight's `pb1`/`pb2`; refuse rather than + * ignore (see gemm_ops). */ if (r4d_geti_or(a, "pb1", 0) > 0 || r4d_geti_or(a, "pb2", 0) > 0) return R4D_NO(RAD_E_UNSUPPORTED); g->a = r4d_opt(a, F_A); g->ascale = r4d_opt(a, F_ASCALE); @@ -57,27 +46,23 @@ static inline int fp8_ops(const RadArgs* a, Fp8Ops* g, int want_ascale, if (want_ascale && !g->ascale) return R4D_NO(RAD_E_INVAL); if (g->b->rank != 2 || g->bscale->rank != 2) return R4D_NO(RAD_E_SHAPE); - /* ROWS ARE DIM 0 AND EVERYTHING AFTER IT IS THE ROW -- the same reading r4d_rad_quant_act_fp8 - * takes of its input, and for the same reason. A gated attention block's q|gate projection is - * declared [tokens, heads, 2*head_dim] because the de-interleaving that follows needs the head - * axis; its N is heads*2*head_dim and the GEMM neither knows nor cares. Demanding rank 2 here - * would refuse that projection, which is the first thing a gated attention layer does. */ + /* Rows are dim 0 and everything after it is the row, as in r4d_rad_quant_act_fp8. A gated + * attention q|gate projection is declared [tokens, heads, 2*head_dim] for the de-interleave + * that follows; to the GEMM its N is heads*2*head_dim, so rank > 2 must be accepted. */ if (g->y->rank < 2) return R4D_NO(RAD_E_SHAPE); g->M = g->y->shape[0]; if (g->M < 1 || r4d_numel(g->y) % g->M) return R4D_NO(RAD_E_SHAPE); g->N = r4d_numel(g->y) / g->M; g->K = g->b->shape[1]; if (g->b->shape[0] != g->N) return R4D_NO(RAD_E_SHAPE); - if (g->M < 1 || g->N < 1 || g->K < 1) return R4D_NO(RAD_E_SHAPE); + if (g->N < 1 || g->K < 1) return R4D_NO(RAD_E_SHAPE); - /* The layout hook and the .rad it wrote are built against R4D_FP8_BLOCK; libr4d compiles its - * own copy in. A scalar compare against a constant costs nothing and the alternative is a - * silently wrong scale grid. */ + /* The layout hook and the .rad it wrote use R4D_FP8_BLOCK and libr4d compiles its own copy; + * a mismatch would be a silently wrong scale grid. */ const long long blk = r4d_gemm_fp8a8_block(); if (blk != R4D_FP8_BLOCK) return R4D_NO(RAD_E_SHAPE); g->nkb = (g->K + blk - 1) / blk; - /* The scale plane's own extents, checked rather than assumed: this is the operand a converter - * is most likely to hand over at the wrong grid, and a wrong grid reads a plausible number. */ + /* Check the scale plane's extents: a wrong grid still reads plausible numbers. */ if (g->bscale->shape[0] != (wscale == FP8_OPS_ROW_SCALE ? g->N : (g->N + blk - 1) / blk)) return R4D_NO(RAD_E_SHAPE); if (g->bscale->shape[1] != g->nkb) return R4D_NO(RAD_E_SHAPE); @@ -102,10 +87,8 @@ static inline int fp8_ops(const RadArgs* a, Fp8Ops* g, int want_ascale, if (asp < 0) return R4D_NO(RAD_E_STRIDE); g->sa_ld = asp; } - /* 16, not 128. The widest weight load in the family is a uint4 in the matvec and a 32-byte - * staged pair in the GEMM, both at a 16-byte offset from the row base. A 128-byte demand would - * be a claim about the cacheline, which is 256 on this part and is not an alignment rule of any - * load here. */ + /* 16 bytes: the widest weight load in the family is a uint4 (matvec) or a 32-byte staged pair + * (GEMM), both at a 16-byte offset from the row base. */ if (!r4d_aligned(g->a->data, 16) || !r4d_aligned(g->b->data, 16)) return R4D_NO(RAD_E_ALIGN); return RAD_OK; } diff --git a/libr4d/r4d_fp8_frag.h b/libr4d/r4d_fp8_frag.h index b3484ac9..b6c78992 100644 --- a/libr4d/r4d_fp8_frag.h +++ b/libr4d/r4d_fp8_frag.h @@ -1,34 +1,21 @@ -// r4d_fp8_frag.h -- where a byte of a block-scaled FP8 WEIGHT lives once it is stored in WMMA -// FRAGMENT ORDER, and nothing else. Pure C++: no HIP, no r4d.h, so the host layout hook and the -// device kernels can include the same arithmetic instead of writing it twice and drifting. +// r4d_fp8_frag.h -- where a byte of a block-scaled FP8 weight lives in WMMA fragment order. Pure +// C++ (no HIP, no r4d.h) so the host layout hook and the device kernels share one definition. // -// ---- why the weight is permuted at all ----------------------------------------------------- +// Why permute: the fp8a8 GEMMs read operands through r4d_fp8::frag(), which wants lane `l` to hold +// row `l & 15` of a 16-row tile at k `(l >> 4) * 8`, eight bytes. From a row-major weight those +// sixteen rows are `K` bytes apart, so a wave's load is sixteen transactions; the kernels stage +// through LDS to transpose, at the cost of a barrier, 36 KiB per block and a second pass over the +// weight. In fragment order the bytes are already in lane order. // -// The fp8a8 GEMMs read both operands through r4d_fp8::frag(), which wants lane `l` to hold ROW -// `l & 15` of a 16-row tile at k `(l >> 4) * 8`, eight bytes. A row-major weight cannot deliver -// that from a coalesced load: a wave's sixteen rows are `K` bytes apart, so asking for them -// together is sixteen separate transactions off a 256-byte cacheline, and reaches well under the -// rate a wide contiguous read does. That is why the kernels stage through LDS -- the LDS round -// trip IS the 16-row transpose -- and the staging costs a barrier, 36 KiB a block, and a second -// pass over every weight byte. +// Why 64 k and not 16: a single fragment (16 rows x 16 k = 256 bytes) gives a wave one 256-byte +// cacheline per request, which loses even to LDS staging. Four fragments give each lane 32 +// contiguous bytes and the wave a 1 KiB request, which beats both at every N and K in the family. // -// Stored in fragment order the same bytes are already in lane order and none of it is needed. -// -// ---- the shape of it, and why it is 64 k and not 16 ------------------------------------------ -// -// The obvious layout is one fragment: 16 rows x 16 k = 256 bytes, lane `l` taking bytes -// `l * 8`. A wave then asks for 256 contiguous bytes, which LOSES even to the staged path: a -// 256-byte request is a single cacheline and the memory system wants more in flight than one -// cacheline a wave. FOUR fragments together give each lane 32 contiguous bytes and the wave a -// 1 KiB request, which beats both the 8-byte form and LDS staging at every N and K in this family. -// -// So the unit is a (16 row, 64 k) TILE of 1024 bytes, laid out as 32 lanes x 32 bytes, and lane -// `l`'s 32 bytes are its four fragments back to back: bytes `8t` are fragment `t`, which covers +// The unit is a (16 row, 64 k) tile of 1024 bytes, laid out as 32 lanes x 32 bytes. Lane `l`'s +// 32 bytes are its four fragments back to back: bytes `8t` are fragment `t`, covering // k `t*16 + (l>>4)*8` of row `l & 15`. // -// K must be a multiple of 64 and N a multiple of 16. Every fp8 weight in this family already -// satisfies both by a wide margin -- the constraint rows demand K and N divisible by 128, because -// that is the scale block -- so this adds no restriction anyone can hit. +// K must be a multiple of 64 and N of 16; the 128 scale block already guarantees both. #pragma once #include @@ -39,18 +26,8 @@ enum { kFragRows = 16, kFragK = 16, kSuperK = 64, kTileBytes = 1024, kLaneBytes // Bytes one [N][K] weight occupies in fragment order: exactly N*K, since this is a permutation. inline int64_t frag_bytes(int64_t N, int64_t K) { return N * K; } -// The 1 KiB tile holding row tile `rt` and k supertile `ks`, in bytes from the plane's base. -// `ksuper` is K / 64 -- the number of supertiles a row tile spans. -inline int64_t frag_tile_off(int64_t rt, int64_t ks, int64_t ksuper) { - return (rt * ksuper + ks) * (int64_t)kTileBytes; -} - -// ...and within that tile, the 32 bytes lane `l` owns. Its four fragments are at +0, +8, +16, +24. -inline int64_t frag_lane_off(int64_t lane) { return lane * (int64_t)kLaneBytes; } - -// The source element a given (tile, lane, fragment, byte) came from, as a row and a k. This is the -// ONE definition of the permutation; the host transform walks it forwards and the device kernels -// index it backwards, and both are wrong together or right together. +// The source (row, k) of a given (tile, lane, fragment, byte). The single definition of the +// permutation: the host transform walks it forwards, the device kernels index it backwards. inline void frag_src(int64_t rt, int64_t ks, int64_t lane, int64_t t, int64_t j, int64_t* row, int64_t* k) { *row = rt * (int64_t)kFragRows + (lane & 15); diff --git a/libr4d/r4d_fp8_layout.cpp b/libr4d/r4d_fp8_layout.cpp index 68534e75..b74b6efa 100644 --- a/libr4d/r4d_fp8_layout.cpp +++ b/libr4d/r4d_fp8_layout.cpp @@ -1,41 +1,37 @@ -/* r4d_fp8_layout.cpp -- what libr4d's FP8 kernels store for a weight, and the relayouts that +/* r4d_fp8_layout.cpp -- the stored form of libr4d's FP8 and int8 weights, and the relayouts that * produce it from the weight's canonical planes (spec.md §4.3). Pure host C++: nothing here - * includes r4d.h or , so it compiles and can be exercised on a box with no - * ROCm, which is where a packing bug is cheapest to find. + * includes r4d.h or , so packing can be tested without ROCm. * * ================================================================= what they read * * The block-scaled linears read the encoding a block-FP8 checkpoint ships, `fp8_e4m3*bf16[128x128]`: * - * codes F8_E4M3, [N][K] -- exactly as safetensors stores `X.weight` - * scale BF16, [ceil(N/128)][ceil(K/128)] -- exactly `X.weight_scale_inv` + * codes F8_E4M3, [N][K] -- as safetensors stores `X.weight` + * scale BF16, [ceil(N/128)][ceil(K/128)] -- as `X.weight_scale_inv` * - * In a Qwen3.8-27B-FP8 checkpoint, `mlp.gate_proj.weight` is F8_E4M3 [17408, 5120] with - * `mlp.gate_proj.weight_scale_inv` BF16 [136, 40], and 17408/136 = 5120/40 = 128. The kernels - * index `S[(row / 128) * sc_cols + (c / 128)]`, which is that grid, so the scale plane is stored as - * it is and only the codes move: into WMMA fragment order for the fp8a8 GEMMs, which read a lane's - * own bytes straight from a coalesced load, and nowhere at all for the fp8a16 matvec, which reads - * sixteen consecutive k of one row. The two cannot share a stored form, so a weight is declared - * for one or the other and the builder refuses the pair. + * E.g. Qwen3.8-27B-FP8 `mlp.gate_proj.weight` is F8_E4M3 [17408, 5120] with a BF16 [136, 40] + * scale. The kernels index `S[(row / 128) * sc_cols + (c / 128)]`, so the scale plane is stored + * unchanged and only the codes move: into WMMA fragment order for the fp8a8 GEMMs (a lane reads + * its own bytes from one coalesced load), and not at all for the fp8a16 matvec, which reads + * sixteen consecutive k of one row. The two forms differ, so a weight is declared for one or the + * other and the builder refuses the pair. * - * The lm_head carries each row's block scales in the row's own tail, because it has one operand - * and is ROW-sharded: [K codes][K/128 bf16 scales], the row padded to 16 bytes so a uint4 load of - * the next row is aligned (r4d_fp8_lm.h). hc_read's mixing matrices and mtp_enter's fc are the - * same with an f32 scale per group of the row (r4d_hc_fp8.h). + * The lm_head is a single row-sharded operand, so each row carries its block scales in its own + * tail: [K codes][K/128 bf16 scales], padded to 16 bytes so a uint4 load of the next row is + * aligned (r4d_fp8_lm.h). hc_read's mixing matrices and mtp_enter's fc use the same form with an + * f32 scale per group of the row (r4d_hc_fp8.h). * * ================================================================= BF16 scales, not UE8M0 * - * Some block-FP8 checkpoints carry a UE8M0 exponent BYTE per tile rather than a bf16. Converting - * to it is not free: UE8M0 stores an exponent and nothing else, so rounding a bf16 scale into it - * changes the tile's gain, and correcting for that means requantising every E4M3 byte against the - * new power-of-two scale. And nothing is gained -- decoding either is one shift and one bitcast. - * The bf16 plane is 0.02% of its weight. + * Some block-FP8 checkpoints carry a UE8M0 exponent byte per tile instead of a bf16. Converting to + * UE8M0 rounds each scale to a power of two, which changes the tile's gain and would mean + * requantising every E4M3 byte. Decoding either costs one shift and one bitcast, and the bf16 + * plane is 0.02% of its weight. * - * Choosing the numbers is not this file's job: a checkpoint's own planes are served as they are, - * and anything quantised -- a bf16 lm_head made fp8 -- was quantised by a quantiser before the - * container was written (libquant's `rtn` over `fp8_e4m3` with a 128x128 bf16 block, whose rule is - * the one these kernels' activation quantiser uses: amax/448 rounded to bf16, a zero block scaled - * by one). + * This file chooses no numbers: a checkpoint's planes are served as they are, and anything + * quantised (e.g. a bf16 lm_head made fp8) was quantised before the container was written, by + * libquant's `rtn` over `fp8_e4m3` with a 128x128 bf16 block. Its rule matches these kernels' + * activation quantiser: amax/448 rounded to bf16, a zero block scaled by one. */ #include "r4d_plugin.h" @@ -48,20 +44,19 @@ #include #include -/* Operand indices for `gemm_nt_q`. Named rather than literal because the schema is positional and a - * reorder in r4d_rows.cpp is otherwise a silent miscompile here. */ +/* Operand indices of `gemm_nt_q`. The schema is positional, so these must follow its order in + * r4d_rows.cpp. */ enum { FL_A = 0, FL_ASCALE = 1, FL_B = 2, FL_BSCALE = 3, FL_Y = 4 }; -/* The k a fragment-order tile spans, which libr4d compiles in. */ +/* K span of one fragment-order tile, compiled into libr4d. */ enum { R4D_FP8_SUPER_K = r4d_fp8::kSuperK }; namespace { -/* THE WALK BOTH DIRECTIONS SHARE: the fragment-order plane front to back, eight bytes at a time, - * each with the row-major offset of the [N][K] weight it holds. A fragment is eight consecutive k - * of one row -- r4d_fp8_frag.h's frag_src over j = 0..7 -- so it moves as one word, and the - * stored side is written or read in order. A byte at a time, with the divisions that place it, - * the same permutation is most of the CPU a block-FP8 model's load spends. */ +/* Walks the fragment-order plane front to back, eight bytes at a time, passing each word's + * row-major offset in the [N][K] weight; used in both directions. A fragment is eight consecutive + * k of one row (r4d_fp8_frag.h frag_src over j = 0..7), so it moves as one word. Placing each byte + * separately would dominate the CPU cost of loading a block-FP8 model. */ template void frag_walk(long long N, long long K, Move move) { constexpr int kLanes = r4d_fp8::kTileBytes / r4d_fp8::kLaneBytes; @@ -84,9 +79,8 @@ int fgeom(const RadParam* p, int n_p, FGeom* g) { g->N = r4d_pgeti_or(p, n_p, "N", 0); g->K = r4d_pgeti_or(p, n_p, "K", 0); if (g->N <= 0 || g->K <= 0) return RAD_E_SHAPE; - /* The block is compiled into the kernels as `>> 7`. A geometry that asks for another group is - * asking for a format nothing here reads; the constraint table already refused it, and this is - * the second line of defence for a tool calling the hook without going through selection. */ + /* The block is compiled into the kernels as `>> 7`. The constraint table already refuses + * other groups; this catches a caller that invokes the hook without selection. */ if (r4d_pgeti_or(p, n_p, "group", R4D_FP8_BLOCK) != R4D_FP8_BLOCK) return RAD_E_SHAPE; g->sn = (g->N + R4D_FP8_BLOCK - 1) / R4D_FP8_BLOCK; g->sk = (g->K + R4D_FP8_BLOCK - 1) / R4D_FP8_BLOCK; @@ -152,12 +146,12 @@ int mgeom(const RadParam* p, int n_p, int operand, HGeom* g) { /* ==================================================================== the hooks * - * Each checks the encoding its kernel reads and refuses any other with RAD_E_DTYPE, which is the - * declare-time error a mis-converted container meets; then it moves bits and chooses none. */ + * Each checks the encoding its kernel reads and refuses any other with RAD_E_DTYPE (the + * declare-time error for a mis-converted container). They move bits and choose none. */ namespace { -/* gemm_nt_q's weight and scale over block fp8: e4m3 codes with a bf16 scale a 128x128 block. */ +/* gemm_nt_q's block-fp8 weight: e4m3 codes with a bf16 scale per 128x128 block. */ bool fp8_block_enc(const RadEncoding* e) { return r4d_enc::affine(e, RAD_F8E4M3, RAD_BF16, R4D_FP8_BLOCK, R4D_FP8_BLOCK); } @@ -227,14 +221,14 @@ extern "C" int r4d_rad_unrelayout_fp8_block(const RadParam* p, int n_p, int oper return RAD_OK; } -/* ---- the int8 twin: i8 codes in the same fragment order, with a bf16 scale per ROW per 128 K. - * The codes move exactly as E4M3 codes do -- the permutation does not read them. +/* ---- the int8 twin: i8 codes in the same fragment order as E4M3, with a bf16 scale per row per + * 128 K. * - * THE SCALE PLANE IS TILE-MAJOR, [N/16][K/128][16]: the sixteen rows of a fragment tile side by side - * for one 128-K block. On the narrow path a lane's eight accumulator rows are eight CONSECUTIVE - * rows of one tile, so their scales are one 16-byte load in the fold where the row-major plane - * would need eight scattered ones -- which, if-converted into every k step, cost the decode - * kernel 70% at M = 4. The prefill tile reads one row's scale a lane, from either form. */ + * The scale plane is tile-major, [N/16][K/128][16]: the sixteen rows of a fragment tile side by + * side for one 128-K block. On the narrow path a lane's eight accumulator rows are eight + * consecutive rows of one tile, so their scales are one 16-byte load. A row-major plane needs + * eight scattered loads, which if-converted into every k step cost the decode kernel 70% at + * M = 4. The prefill tile reads one row's scale per lane and works with either form. */ namespace { int i8_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel, const RadTensor* pl, int n, RadLayout* out) { @@ -316,9 +310,8 @@ extern "C" int r4d_rad_unrelayout_i8_block(const RadParam* p, int n_p, int opera /* ---- the lm_head: codes and scales in one row, the scales of the row's 128-row block repeated * into its tail. */ namespace { -/* `i8`: the int8 head (logits_gemm_i8) -- i8 codes with a bf16 scale a row per 128 columns, the - * same stored row with each row's OWN scales in its tail where the E4M3 head repeats its 128-row - * block's. */ +/* `i8` selects the int8 head (logits_gemm_i8): i8 codes with a bf16 scale per row per 128 + * columns. Same stored row, but each row's tail holds its own scales instead of its block's. */ int lm_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel, const RadTensor* pl, int n, RadLayout* out, FGeom* gout, bool i8 = false) { if (!out || !pl) return RAD_E_INVAL; @@ -436,8 +429,8 @@ extern "C" int r4d_rad_unrelayout_i8_logits(const RadParam* p, int n_p, int oper return RAD_OK; } -/* ---- hc_read's mixing matrices and mtp_enter's fc: e4m3 codes with an f32 scale a group of the - * row, the scales in the row's tail and the row padded to 16 bytes. */ +/* ---- hc_read's mixing matrices and mtp_enter's fc: e4m3 codes with an f32 scale per group of + * the row, the scales in the row's tail and the row padded to 16 bytes. */ namespace { int hcrows_enc_layout(const HGeom& g, const char* tag, const RadEncoding* enc, const int* sel, const RadTensor* pl, int n, RadLayout* out) { @@ -542,11 +535,10 @@ extern "C" int r4d_rad_unrelayout_mtp_e4m3(const RadParam* p, int n_p, int opera /* ================================================================= embed_lookup_q's table * - * The gather reads the table AS IT IS, so this hook only answers whether it can: E4M3 codes with - * ONE bf16 scale for the whole table (`fp8_e4m3*bf16[*x*]`, the n-gram table's recipe), or the - * table as the checkpoint ships it, plain bf16 with no scale. The same two forms libavx's host - * gather accepts (avx_layout_ngram), checked the same way, so a model whose table one of them - * reads is never refused by the other at declare. */ + * The gather reads the table as stored, so this hook only checks that it can: E4M3 codes with one + * bf16 scale for the whole table (`fp8_e4m3*bf16[*x*]`, the n-gram table's recipe), or plain bf16 + * as the checkpoint ships it. libavx's host gather (avx_layout_ngram) accepts the same two forms + * with the same checks, so neither refuses at declare a table the other reads. */ extern "C" int r4d_rad_layout_embed_q(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel, const RadTensor* pl, int n, RadLayout* out) { diff --git a/libr4d/r4d_fp8_lm.h b/libr4d/r4d_fp8_lm.h index f2037fd9..c18c55ab 100644 --- a/libr4d/r4d_fp8_lm.h +++ b/libr4d/r4d_fp8_lm.h @@ -1,53 +1,32 @@ -// r4d_fp8_lm.h -- the STORED ROW GEOMETRY of the fp8 lm_head, and nothing else. Pure C++: no HIP, -// no r4d.h, so the host layout hook (r4d_fp8_layout.cpp), the device entry point -// (r4d_gemm_fp8a16_nt_m1.hip) and the selftest all derive the row width from the same line instead -// of writing `K + 2 * (K / 128)` four times and drifting. +// r4d_fp8_lm.h -- stored row geometry of the fp8 lm_head. Pure C++ (no HIP, no r4d.h) so the +// layout hook (r4d_fp8_layout.cpp), the entry point (r4d_gemm_fp8a16_nt_m1.hip) and the selftest +// derive the row width from one definition. // -// WHY THE ROW LOOKS LIKE THIS AT ALL is r4d_rad_layout_fp8_logits' argument and is not repeated -// here: `logits_gemm` carries ONE weight operand, so the block scales have nowhere to go but the -// row's own tail, and that is what keeps a row-sharded lm_head a plain byte range under tensor -// parallelism. +// `logits_gemm` carries one weight operand, so the block scales live in each row's tail (see +// r4d_rad_layout_fp8_logits); a row-sharded lm_head stays a plain byte range under TP. // -// ---- THE PADDING, which is the only thing this header adds to `K + 2*nkb` --------------------- -// -// Both kernels that read this plane -- the M <= 2 matvec and the WMMA tile above it -- load the -// weight SIXTEEN BYTES AT A TIME through a uint4, at `row * w_ld + (a multiple of 16)`. So the row -// pitch has to be a multiple of 16 or every odd row is misaligned, and the unpadded width is a -// multiple of 16 only when +// Padding: both kernels that read this plane (the M <= 2 matvec and the WMMA tile) load the weight +// as uint4 at `row * w_ld + (a multiple of 16)`, so the row pitch must be a multiple of 16. The +// unpadded width is one only when // // K + 2*(K/128) = 130m (K = 128m) is 0 mod 16 <=> m is 0 mod 8 <=> K is 0 mod 1024 // -// which is a property of the MODEL, not of anything the kernel chose. K = 5120 has it; K = 2560 -// does not. Without the pad such a head cannot be served in fp8 at all: it falls to the bf16 -// projection, which reads twice the bytes and is then the single largest op in the step -- for -// want of eight bytes a row. +// e.g. K = 5120 qualifies, K = 2560 does not. The pad costs under 16 bytes per row (0.3% at +// K = 2560) and is a no-op when K is a multiple of 1024, where the plane is byte-identical to the +// unpadded one. // -// So pad. The cost is under 16 bytes on a row that is already K + K/64 long -- 0.3% at K = 2560, -// and ZERO at every K that is a multiple of 1024, where the rounding is a no-op and the plane is -// byte-for-byte the unpadded one. **The padding never changes a valid container's plane**, and -// that is not luck: the layout hook refuses a K without the property rather than writing a plane -// its own kernels would fault on, so every K a container can already hold is one the rounding -// leaves alone. -// -// This is NOT the padding r4d_gemm_fp8a16_nt_m1.hip's header prices and rejects. That one is about -// padding an ALREADY-ALIGNED 5200-byte row out to 5376 to make it 128-aligned, chasing the -// cacheline straddle, and it loses to FK = 256. This is 16-byte alignment, which is a correctness -// floor rather than a tuning knob, and it is what decides whether the row can be served at all. +// This is a 16-byte correctness floor, unrelated to the 128-byte row padding that +// r4d_gemm_fp8a16_nt_m1.hip's header evaluates and rejects. #pragma once #include namespace r4d_fp8 { -// BYTES one stored lm_head row occupies: K E4M3 codes, then K/128 bf16 block scales, then the +// Bytes one stored lm_head row occupies: K E4M3 codes, then K/128 bf16 block scales, then the // alignment tail. K must be a multiple of 128 (the scale block); the caller checks that. inline int64_t lm_row_bytes(int64_t K) { const int64_t used = K + 2 * (K / 128); return (used + 15) & ~(int64_t)15; } -// ...and where the pad starts, which is the only part of the row nothing reads. The transform -// zeroes it so that a container's bytes are a function of its weights and not of what the -// allocator happened to leave there. -inline int64_t lm_row_used(int64_t K) { return K + 2 * (K / 128); } - } // namespace r4d_fp8 diff --git a/libr4d/r4d_fp8_wmma.h b/libr4d/r4d_fp8_wmma.h index fbb720c0..e743af51 100644 --- a/libr4d/r4d_fp8_wmma.h +++ b/libr4d/r4d_fp8_wmma.h @@ -1,50 +1,40 @@ -// Shared device-side machinery for the BLOCK-SCALED FP8 family: the 16x16x16 fp8 WMMA fragment -// map, the E4M3 decoders, and the bf16 block-scale load. Named for what it is rather than for a -// kernel, like r4d_common.h and r4d_gdn_wmma.h, because it provides none. +// Shared device code for the block-scaled FP8 family: the 16x16x16 fp8 WMMA fragment map, the +// E4M3 decoders and the bf16 block-scale load. // -// ---- the lane->element mapping, which AMD does not document ------------------------------------ +// ---- lane->element mapping (undocumented by AMD; ROCm issue #6025) ------------------------------ // -// AMD does not publish it, and ROCm issue #6025, which asks for it, is closed without an answer. -// With lane `l`, `c = l % 16`, `h = l / 16` it is: +// With lane `l`, `c = l % 16`, `h = l / 16`: // // A, row-major A[m][k] lane l holds A[c][h*8 + j], j = 0..7 // B, row-major B[k][n] lane l holds B[h*8 + j][c], j = 0..7 // C/D accumulator acc[j] IS D[h*8 + j][c] // -// The accumulator is COLUMN-distributed: a lane owns one column and eight consecutive rows, lanes -// 0-15 rows 0-7 and lanes 16-31 rows 8-15. The intuitive "a lane owns a row" is wrong, produces a -// silently transposed tile, and gives no compile or runtime error. +// The accumulator is column-distributed: a lane owns one column and eight consecutive rows (lanes +// 0-15 rows 0-7, lanes 16-31 rows 8-15). Assuming a lane owns a row gives a silently transposed +// tile. Identity, diagonal and symmetric test matrices cannot detect that; tests of fragment code +// must use asymmetric operands. // -// IDENTITY, DIAGONAL AND SYMMETRIC TEST MATRICES CANNOT TELL THE TWO APART -- both give 0 errors. -// Any test of fragment code here must use asymmetric operands. +// ---- K labelling -------------------------------------------------------------------------------- // -// ---- the K labelling --------------------------------------------------------------------------- +// The hardware K-order is not contiguous: lanes 0-15 hold k = 0,1,2,3,8,9,10,11. Labelling slot j +// of lane-half h as "k = 8h + j" is a permutation of K applied identically to A and B, so the +// product is bit-identical. Two rules keep it that way: // -// The canonical hardware K-order is not contiguous: lanes 0-15 really hold k = 0,1,2,3,8,9,10,11. -// Calling slot j of lane-half h "k = 8h + j" above is a permutation of K applied IDENTICALLY to A -// and B, and D = sum_k A[m][k] B[k][n] is invariant under it, so the product is bit-identical. Two -// rules keep it that way: +// 1. Both operands must use this labelling. Mixing GLOBAL_LOAD_TR_B128 (canonical order) with a +// plain load misaligns K silently. Every kernel here stages both operands through `stage8` +// and reads both through `r4d_fp8::frag`. +// 2. A sparse path may not use it: SWMMAC's index bits are tied to the hardware K groups. // -// 1. BOTH OPERANDS must use this labelling. If one ever comes from GLOBAL_LOAD_TR_B128 (which -// emits the canonical order) and the other from a plain load, the K labels do not line up and -// the result is silently wrong. Every kernel in this family stages both operands through the -// same `stage8` and reads both through `r4d_fp8_frag`, which is what makes that safe. -// 2. A SPARSE path may NOT use this labelling: SWMMAC's index bits are tied to the hardware K -// groups. Nothing in this family is sparse. +// ---- hazards ------------------------------------------------------------------------------------ // -// ---- hazards ----------------------------------------------------------------------------------- +// A WMMA whose A, B or index overlaps the previous WMMA's D needs an independent VALU instruction +// in between (required for correctness; the compiler inserts it). Feeding D back as C of the same +// opcode is exempt, so these kernels keep one accumulator chain of a single opcode. // -// A WMMA whose A, B or index overlaps the PREVIOUS WMMA's D needs at least one independent VALU -// instruction in between -- required for correct function, not a perf hint. The compiler inserts it -// for these intrinsics. Feeding D straight back as C of the same opcode is the fast path and is -// exempt, which is why these kernels keep one long accumulator chain of a single opcode rather than -// mixing WMMA types in the inner loop. -// -// And WMMA does NOT co-issue with VALU on RDNA4, for every opcode. Dequantisation and address math -// inside a wave are serial with its matrix work. That is the whole argument for an fp8 GEMM whose -// inner loop converts nothing: v_wmma_f32_16x16x16_fp8_fp8 issues at 412 TF/s (2.99 cycles), the -// same rate as v_wmma_i32_16x16x16_iu8, and here it is reached because both operands are already -// E4M3 bytes and nothing is unpacked between the LDS read and the mma. +// WMMA does not co-issue with VALU on RDNA4, so dequantisation and address math are serial with +// matrix work. v_wmma_f32_16x16x16_fp8_fp8 issues at 412 TF/s (2.99 cycles), the same rate as +// v_wmma_i32_16x16x16_iu8, and is reached here because both operands are already E4M3 bytes and +// nothing is unpacked between the LDS read and the mma. #pragma once #include "r4d_common.h" #include "r4d_fp8_frag.h" @@ -54,24 +44,22 @@ namespace r4d_fp8 { -// A/B operand widths are the RDNA4 ones -- half of RDNA3's, because RDNA4 dropped the cross-half -// replication. Passing a gfx11-width vector compiles for gfx1100 and fails here, which is the -// intended way to find out the unsuffixed builtin was used. +// A/B operand widths are RDNA4's: half of RDNA3's, since RDNA4 dropped the cross-half +// replication. A gfx11-width vector fails to compile here. typedef int i2v __attribute__((ext_vector_type(2))); // fp8 A or B, 2 VGPRs typedef float f8v __attribute__((ext_vector_type(8))); // f32 accumulator, 8 VGPRs constexpr uint32_t kM = 16, kN = 16, kK = 16; -// Always the _gfx12-suffixed builtin. The unsuffixed name is the RDNA3 form with different operand -// widths; it does not compile for gfx1201, which is the good outcome. +// Always the _gfx12-suffixed builtin; the unsuffixed RDNA3 form has different operand widths. __device__ __forceinline__ f8v mma(i2v a, i2v b, f8v c) { return __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(a, b, c); } -// THE INT8 TWIN, for the same kernels at i8 codes: v_wmma_i32_16x16x16_iu8, both operands signed, -// at the fp8 instruction's rate. Its int32 accumulator rides in the f8v registers as bits, so one -// accumulator type serves both instantiations; acc_val reads a slot back as the number it holds. -// A 128-K scale block of products is at most 128 * 127 * 127, far inside int32. +// Int8 twin for the same kernels at i8 codes: v_wmma_i32_16x16x16_iu8, both operands signed, at +// the fp8 rate. The int32 accumulator is carried in f8v registers as bits so one accumulator type +// serves both; acc_val reads a slot back as a number. A 128-K block sums at most 128 * 127 * 127, +// well inside int32. typedef int i8v __attribute__((ext_vector_type(8))); template __device__ __forceinline__ f8v mma8(i2v a, i2v b, f8v c) { @@ -103,17 +91,12 @@ __device__ __forceinline__ f8v acc_zero() { // ---- E4M3 -> f32 ------------------------------------------------------------------------------- // -// ONE INSTRUCTION on gfx1201: v_cvt_f32_fp8. The software form is ~11 VALU ops and is the fallback -// for a target without the builtin. Over all 256 byte values the two agree on 254. The two that -// differ are 0x7F and 0xFF, E4M3-fn's NaN encodings -- the hardware returns NaN, as the format -// says, and the software form returns +-480. Nothing here writes those bytes (both quantisers -// clamp to +-448 = 0x7E), so the difference is inert on real data and turns a silent 480 into a -// visible NaN if that ever stops being true. +// One instruction on gfx1201 (v_cvt_f32_fp8); the software fallback is ~11 VALU ops. They agree on +// all bytes except 0x7F and 0xFF, E4M3-fn's NaN encodings: hardware returns NaN, the fallback +// +-480. Both quantisers clamp to +-448 = 0x7E, so real data never holds them. // -// There is no subnormal-free fast path here. That path is only -// correct where the encoder clamps entries to exponent 1..7 by construction, as an expert codebook -// can; an arbitrary checkpoint weight has no such precondition, and for a subnormal that path -// silently returns 2^-7 * 1.MMM instead of MMM * 2^-9. The hardware instruction handles them. +// No subnormal-free fast path: a checkpoint weight may hold subnormals, which such a path would +// decode as 2^-7 * 1.MMM instead of MMM * 2^-9. __device__ __forceinline__ float e4m3(uint32_t b) { #if __has_builtin(__builtin_amdgcn_cvt_f32_fp8) return __builtin_amdgcn_cvt_f32_fp8(b, 0); @@ -127,10 +110,9 @@ __device__ __forceinline__ float e4m3(uint32_t b) { #endif } -// TWO E4M3 bytes of a packed dword to two f32 in ONE instruction -- v_cvt_pk_f32_fp8, which gfx1201 -// has because RDNA4 carries the fp8 WMMA path. `HI` selects bytes 2,3 over bytes 0,1 and must be a -// template parameter because the builtin's word select is a constant. Returns r4d_common.h's `v2f`, -// which is what the builtin actually returns. +// Two E4M3 bytes of a packed dword to two f32 in one instruction (v_cvt_pk_f32_fp8). `HI` selects +// bytes 2,3 over 0,1 and is a template parameter because the builtin's word select is a constant. +// Returns r4d_common.h's `v2f`, the builtin's own return type. template __device__ __forceinline__ v2f e4m3_pk(uint32_t q) { #if __has_builtin(__builtin_amdgcn_cvt_pk_f32_fp8) @@ -144,59 +126,42 @@ __device__ __forceinline__ v2f e4m3_pk(uint32_t q) { #endif } -// ---- THE BLOCK SCALE: why the checkpoint's bf16 scales are read natively ------------------------ +// ---- block scale -------------------------------------------------------------------------------- // -// Qwen3.8-27B-FP8 carries a BF16 `weight_scale_inv`, one per 128x128 tile in row-major order, and -// the decode is `__uint_as_float(s << 16)` -- ONE SHIFT, ONE BITCAST. -// -// The alternative encoding is one UE8M0 exponent BYTE per tile, decoded -// `__uint_as_float(e ? (e << 23) : 0u)`: the same shift and bitcast at a different -// distance. Converting to it would round every tile's gain to a power of two, and correcting for -// that means requantising the E4M3 bytes against the new scale -- half a bit off a 3-bit mantissa, -// everywhere, to save nothing. The scale plane is 21.8 KiB against an 89 MiB weight at gate_proj's -// shape. -// -// No zero test, unlike the UE8M0 form: exponent 0 encodes 2^-127 in that format's convention and -// needs one, while bf16 encodes zero as zero and `0u << 16` is +0.0f. +// The checkpoint's BF16 `weight_scale_inv` (one per 128x128 tile, row-major) is read natively: +// decode is one shift and one bitcast. Converting to UE8M0 would round every tile's gain to a +// power of two and force requantising the E4M3 bytes, for no saving (the scale plane is 21.8 KiB +// against an 89 MiB weight at gate_proj's shape). Unlike UE8M0, bf16 needs no zero test: +// `0u << 16` is +0.0f. __device__ __forceinline__ float bscale(uint16_t s) { return __uint_as_float((uint32_t)s << 16); } -/* The same scale held zero-extended in a whole register: the form a 16-bit value should stay in - * from its load on (see u16_load_w in r4d_moe.hip). The upper sixteen bits must be zero. */ +/* The same scale zero-extended in a full register (see u16_load_w in r4d_moe.hip). The upper + * sixteen bits must be zero. */ __device__ __forceinline__ float bscale(uint32_t s) { return __uint_as_float(s << 16); } // ---- LDS staging, shared by both fp8a8 instantiations ------------------------------------------- // -// An fp8 fragment is 8 bytes a lane, so the granule is 8 B and a 64 B row holds 8 of them. A -// fragment read is ONE granule column over SIXTEEN CONSECUTIVE ROWS, and the whole question is -// which bank each of those rows lands in. +// A fragment is 8 B per lane, so a 64 B row holds 8 granules, and a fragment read is one granule +// column over sixteen consecutive rows. LDS has 32 banks of 4 B; a row pitch of P bytes puts row r +// at bank (r * P/4) % 32. With the tile width as pitch (64 or 256 B) rows collide and the read +// serialises. // -// THE ROW PITCH IS NOT THE TILE WIDTH, and that is the point. LDS has 32 banks of 4 B, so bank = -// (byte address / 4) % 32 and a row pitch of P bytes puts row r at bank (r * P/4) % 32. With the -// tile width itself as the pitch -- 64 or 256, both multiples of 128 B -- that is 16r % 32 or -// 0, so rows 8 apart (or all of them) collide and the read serialises. +// An XOR granule swizzle `(k >> 3) ^ (row & 7)` only permutes within a row, so it separates at most +// 8 rows: rows r and r+8 still collide and the read takes two bank cycles. // -// An XOR granule swizzle -- `(k >> 3) ^ (row & 7)` -- does not solve it. It -// permutes only WITHIN a row, and a 64 B row holds 8 granules, so it can separate at most 8 rows: -// rows r and r+8 still land together and the sixteen lanes of a fragment read take two bank cycles -// rather than one. Fragment reads are a large share of this kernel's time, so the second cycle is -// not a small cost. -// -// A PADDED PITCH separates all sixteen instead, and needs no permutation at all. P = FK + 8 gives -// P/4 = 18 words at FK = 64, and 18r % 32 over r = 0..15 is +// A padded pitch P = FK + 8 separates all sixteen. At FK = 64, P/4 = 18 words and 18r % 32 over +// r = 0..15 is // // 0 18 4 22 8 26 12 30 16 2 20 6 24 10 28 14 // -// -- sixteen distinct even banks, so the sixteen lanes cover all 32 banks exactly once and the -// read is one bank cycle. At FK = 256 it is 66 words and 66r % 32 = 2r % 32, distinct likewise. -// The pad must be a multiple of 8 to keep the 8 B granule aligned for ds_read_b64; +8 is the -// smallest that works, and a larger pad only costs LDS without separating any better -- +16 is -// four words, and 4r % 32 has period 8, so it collides again. -// -// Cost is 8 B a row of LDS: the prefill tile is 36 KiB a block rather than 32, which leaves room -// for 3 resident blocks a WGP rather than 4. The bank cycle saved outweighs the lost block. +// sixteen distinct even banks, so the read is one bank cycle. At FK = 256, 66r % 32 = 2r % 32, +// likewise distinct. The pad must be a multiple of 8 to keep the granule aligned for ds_read_b64; +// +16 (4r % 32, period 8) collides again. The cost is 8 B per row: the prefill tile is 36 KiB per +// block instead of 32, allowing 3 resident blocks per WGP instead of 4, which the saved bank +// cycle outweighs. template __device__ __forceinline__ constexpr uint32_t lds_pitch() { return FK + 8u; } @@ -213,17 +178,12 @@ __device__ __forceinline__ i2v frag(const uint8_t* __restrict__ lds, uint32_t ro } // The 32 bytes a thread stages, held in registers between the global load and the LDS store. -// -// They are SPLIT into a load and a store because of what sits between them. Issued as one call, the -// load is followed immediately by the barrier that publishes it, so a thread has exactly one -// 32-byte request in flight and then waits -- and the K loop becomes a chain of memory latencies -// rather than a stream. The symptom is a block sweep that saturates well below the card's coalesced -// ceiling and then does not move when the block count doubles. +// Load and store are split so the next load can be issued before the barrier; as one call, a +// thread has a single 32-byte request in flight and the K loop becomes a chain of latencies. struct Stage8 { uint4 v, w; }; -// One of the FOUR fragments held in a 32-byte fragment-order load. `t` selects which: bytes 8t, -// and a Stage8 is two uint4, so fragment 0 and 1 come out of `v` and 2 and 3 out of `w`. `t` is a -// constant at every call site after unrolling, so this is a register rename and not a branch. +// Fragment `t` (bytes 8t) of a 32-byte fragment-order load: 0 and 1 from `v`, 2 and 3 from `w`. +// `t` is constant after unrolling, so this is a register rename, not a branch. __device__ __forceinline__ i2v frag_of(const Stage8& s, uint32_t t) { const uint2 g[4] = { make_uint2(s.v.x, s.v.y), make_uint2(s.v.z, s.v.w), make_uint2(s.w.x, s.w.y), make_uint2(s.w.z, s.w.w) }; @@ -233,39 +193,20 @@ __device__ __forceinline__ i2v frag_of(const Stage8& s, uint32_t t) { return f; } -/* `NT` asks the cache to evict this line first. It is for an operand THE KERNEL READS ONCE AND NO - * OTHER BLOCK READS AT ALL -- the weight -- and it exists to stop that stream from evicting the one - * operand every block DOES share. `__builtin_nontemporal_load` will not take `uint4`: that is a - * HIP_vector_type class template, not a native vector, so the hinted load goes through an - * ext_vector_type and the WHOLE value is bit-cast back (never a subscript of it, which - * miscompiles). Nothing about the bytes changes -- this is a cache hint and the arithmetic that - * follows is identical. */ -typedef unsigned r4d_f8_ntu4 __attribute__((ext_vector_type(4))); - -template __device__ __forceinline__ Stage8 stage8_load(const uint8_t* __restrict__ src, bool live) { Stage8 r; r.v = make_uint4(0, 0, 0, 0); r.w = make_uint4(0, 0, 0, 0); if (live) { - if constexpr (NT) { - r.v = __builtin_bit_cast(uint4, - __builtin_nontemporal_load((const r4d_f8_ntu4*)src)); - r.w = __builtin_bit_cast(uint4, - __builtin_nontemporal_load((const r4d_f8_ntu4*)(src + 16))); - } else { - r.v = *(const uint4*)src; - r.w = *(const uint4*)(src + 16); - } + r.v = *(const uint4*)src; + r.w = *(const uint4*)(src + 16); } return r; } -// The fragment-order counterpart: the 32 bytes a lane holds in a (16 row, 64 k) tile are four -// granules of ONE row at k `k0 + t*16`, not four consecutive ones. So a fragment-order operand is -// de-permuted on the way INTO LDS and everything downstream -- the padded pitch, the bank layout, -// frag() itself -- is untouched. That matters: the pitch is what makes a fragment read one bank -// cycle, and reading fragment order straight out of LDS would put eight lanes on one bank. +// Fragment-order counterpart: a lane's 32 bytes in a (16 row, 64 k) tile are four granules of one +// row at k `k0 + t*16`. They are de-permuted on the way into LDS, so the padded pitch and frag() +// apply unchanged; reading fragment order straight from LDS would put eight lanes on one bank. template __device__ __forceinline__ void stage8_store_frag(uint8_t* __restrict__ lds, uint32_t row, uint32_t k0, Stage8 r) { diff --git a/libr4d/r4d_fuse.cpp b/libr4d/r4d_fuse.cpp index 61e2983a..668ef541 100644 --- a/libr4d/r4d_fuse.cpp +++ b/libr4d/r4d_fuse.cpp @@ -1,132 +1,89 @@ -/* r4d_fuse.cpp -- what chain of conventional ops does this kernel compute in one launch. +/* r4d_fuse.cpp -- the chain of unfused ops each fused kernel computes in one launch. * - * `RadKernelInfo::replaces` (rad_abi.h) turns a claim that sixteen rows of this plugin make in - * PROSE -- "byte-identical to the two ops it replaces" -- into something a tool can execute. The - * value is an ORACLE: eleven of libr4d's fusions have no libref kernel at all, so rad-kbench - * otherwise skips them BY NAME. A fused row that names its chain can be run against that chain - * built out of THIS PLUGIN'S OWN unfused rows, and the answer should not be within a tolerance -- - * it should be the same bytes. + * `RadKernelInfo::replaces` (rad_abi.h) makes a fused row's claim to be byte-identical to the ops + * it replaces executable. Eleven of libr4d's fusions have no libref kernel, so this is their only + * oracle: a caller runs the fused row against its chain built from this plugin's own unfused rows, + * and expects identical bytes, not a tolerance. * - * THE AUTHORITY FOR EVERY CHAIN BELOW IS THE DEVICE KERNEL, not the row's prose and not this file. - * A fusion is exact or it is not, and the difference is one `f2bf` in a kernel body: the fp8 folds - * round their intermediate to bf16 and read it back precisely so that the fused and unfused forms - * agree, and the int8 folds deliberately do NOT, because their reference is a different pair. So - * each chain below names the libr4d source and the line that decides it, and a reader can check - * one against the other. That is not decoration. `qk_norm_rope_gate` is the worked counter-example - * -- it folds a sum of squares over one wave per head where `rmsnorm` folds it over - * r4d_act_threads(M, n) threads, so the two differ by a ULP and it publishes NO HOOK -- and the ABI - * says why: "a kernel that is merely close to the sequence it names should publish no hook at all", - * because a false failure is worse than a skip and drowns the true ones. + * The authority for each chain is the device kernel, not the row's prose, and each chain names the + * source that decides it. Exactness often comes down to one `f2bf`: the fp8 folds round their + * intermediate to bf16 and read it back so the fused and unfused forms agree; the int8 folds do + * not, because their reference is a different pair. A kernel that is merely close to a sequence + * publishes no hook (rad_abi.h): a false failure is worse than a skip. * - * ============================================================ WHICH OPERANDS THE CALL PASSES + * ============================================================ operand presence * - * `rmsnorm_quant_fp8` computes `add` then `rmsnorm` then the quantiser when it is given a residual, - * and `rmsnorm` then the quantiser when it is not: THE CHAIN LENGTH DEPENDS ON AN OPERAND. That is - * the reason the chain is a hook rather than a table, and the reason the hook has to be told which - * operands the call carries rather than only `(p, n_p)`. + * `rmsnorm_quant_fp8` computes `add` + `rmsnorm` + quantiser when given a residual, and `rmsnorm` + * + quantiser when not, so the chain length depends on an operand. That is why the chain is a hook + * rather than a table, and why the hook receives `present`: one bit per fused operand, read with + * RAD_FUSE_HAS(). Two alternatives are wrong: * - * Two other ways of deciding it look plausible and both are wrong: + * - Deriving it from a parameter: there is none. `wadd` is GemmaRMSNorm's `1 +`, a property of + * the gain, and arch/common/rad_fp8.h passes it in both forms. + * - Marking the operands RAD_FUSE_NONE: that marks an optional operand a step does not pass. + * Here the operands that vary are required ones (`add`'s `b`, `rmsnorm`'s `x`) and the chain + * length itself changes. * - * DERIVE IT FROM A PARAMETER. There is no such parameter, and `wadd` in particular is not one. - * `wadd` is GemmaRMSNorm's `1 +` -- a property of the norm GAIN, not of the residual -- and - * arch/common/rad_fp8.h:369 passes it unconditionally in both forms. Keying on it would - * answer "three steps" for a Gemma-style model that passes no residual and "two steps" for a - * Llama-style one that does, which is a wrong chain rather than a missing one. + * A caller that does not know passes RAD_FUSE_PRESENT_ALL, meaning every operand this plugin's own + * description lists; r4d_shape_rmsnorm_quant_fp8 publishes all six as present. Where a fold's step + * carries the same optional operands as the fold (ar_rmsnorm_quant_fp8 below), absence propagates + * through the wiring and `present` need not be read. Prefer that shape where there is a choice. * - * DECLARE BOTH WIRINGS WITH RAD_FUSE_NONE. That spelling marks an OPTIONAL operand of a STEP - * that this chain does not pass. It cannot express this difference, because the operands that - * vary are REQUIRED ones -- `add`'s `b` and `rmsnorm`'s `x` -- and because the CHAIN LENGTH - * itself changes, which no per-operand marker reaches. + * ============================================================ rows with no hook * - * So the ABI carries it: `present` is a bit per operand of the fused op, and this file reads it - * with RAD_FUSE_HAS(). A caller that genuinely does not know passes RAD_FUSE_PRESENT_ALL, which - * means "answer for every operand your own description says exists" -- and that is a contract - * rather than a coupling, because this plugin's `r4d_shape_rmsnorm_quant_fp8` publishes all six as - * present and is the list a cold caller allocated from. - * - * Note how the question VANISHES wherever a fold's step carries the same optional operand the fold - * does: `ar_rmsnorm_quant_fp8` below wires its residual and its out_bf16 straight through to a - * `rmsnorm_quant_fp8` step where both are optional as well, so absence propagates and that chain - * needs no knowledge of presence at all. That is worth preferring where a chain has the choice. - * - * ============================================================ WHAT IS DECLINED, AND WHY - * - * A decline is a real answer here, the same way it is in r4d_shapes.cpp: the caller counts the row - * as uncovered, which is true, where a chain that is merely close produces a FAILURE that means - * nothing. These rows carry a null `replaces` deliberately. + * These rows carry a null `replaces`; the caller counts them as uncovered. * * rmsnorm_had_quant_i8, gated_had_quant_i8, gdn_gated_norm_had_quant_i8 - * NOT because the vocabulary has no `hadamard` op -- it does not, but that is not what stops - * these. The rotation is inside `had_quant_act_i8`, which IS an op, so the algebra - * `rmsnorm` + `had_quant_act_i8` is available and it still does not hold. The reason is the - * fusion's own trick: r4d_rmsnorm_had_quant_i8.hip runs the FWHT on `x * (w + wadd)` BEFORE - * the norm closes -- legitimate, since the transform is linear and `inv_rms` is a per-row - * scalar that the int8 codes cancel -- and folds `inv_rms` into `S[row]` instead. So the - * codes are taken over values that were never normalised and never rounded to bf16, while - * the unfused pair would rotate a stored bf16 norm output. That file states the gap itself - * ("normalising from a bf16-rounded sum produces thousands of +/-1 code errors and a 1e-3 - * scale error against 5e-7") and calls storing bf16 correct and normalising from it not. - * r4d_gated_had_quant_i8.hip is the same shape and says so outright: "silu(x) = x * - * sigmoid(x) is computed in fp32. Doing it in bf16 would cost more than the quantiser that - * follows" -- which is the exact opposite of the fp8 sibling's bargain, and it is what makes - * `silu_mul` + `had_quant_act_i8` a different function. That row also reads a CLIP from the - * environment (R4D_CLIP_MLP_DOWN), so it is not even a pure function of the geometry. + * `rmsnorm` + `had_quant_act_i8` is expressible but does not hold. + * r4d_rmsnorm_had_quant_i8.hip runs the FWHT on `x * (w + wadd)` before the norm closes + * (valid: the transform is linear and the int8 codes cancel the per-row `inv_rms`) and folds + * `inv_rms` into `S[row]`. Its codes come from values never normalised or rounded to bf16, + * while the unfused pair rotates a stored bf16 norm output. r4d_gated_had_quant_i8.hip + * likewise computes silu(x) in fp32, which `silu_mul` + `had_quant_act_i8` does not. * * had_quant_act_i8, quant_act_i8, quant_act_fp8 - * NOT FUSIONS. They are primitive ops of the vocabulary with nothing to decompose into: the - * rotation has no op name of its own, and a chain of one step naming the op itself would be - * a tautology that inflates the coverage metric and checks nothing. + * Primitive ops, not fusions. A one-step chain naming the op itself would check nothing. * * ar_ln_had_quant_i8 - * The collective's half is expressible -- `all_reduce` then `rmsnorm_had_quant_i8`, both ops - * -- and the arithmetic is not. r4d_ar_ln_had_quant_i8.hip states its whole design as "the - * all-reduce OUTPUT never exists ... the peer's contribution is simply a second operand on - * the norm's load -- `t = mine + peer + residual`": one f32 expression, with no bf16 round - * between the reduce and the add. The pair it would replace has one, because the standalone - * all-reduce stores bf16. Its `ARN_W6_MATCH` makes only the COMPRESSED wire round, and only - * to match the compressed all-reduce. The fp8 sibling below took the opposite decision -- - * `a = f2bf(bf2f(xr[i]) + bf2f(pr[i])); xr[i] = a;` -- and that one difference is why one of - * these two rows gets a hook and the other does not. + * `all_reduce` + `rmsnorm_had_quant_i8` is expressible but the arithmetic differs: the kernel + * computes `t = mine + peer + residual` in f32 with no bf16 round after the reduce, while the + * standalone all-reduce stores bf16 (the compressed wire rounds to bf16, to match the + * compressed all-reduce). The fp8 sibling ar_rmsnorm_quant_fp8 rounds there and has a hook. * * qk_norm_rope_gate - * Stated in docs/OPS.md and in the row itself: "It is not byte-identical to the four kernels - * it replaces", the summation partition differs, and selecting it is a rebaseline. + * Not byte-identical to the four kernels it replaces (docs/OPS.md): it folds a sum of + * squares over one wave per head where `rmsnorm` folds over r4d_act_threads(M, n) threads, + * so the two differ by a ULP. * * sample_chain - * It "stands beside the decomposed stages rather than replacing them" (r4d_rows.cpp). One - * workgroup walking an L2-resident row is not eight launches over a 248K vocabulary in any - * rounding sense, nothing in this project implements those eight on a device, and the fused - * row additionally produces `tok_excl` and `p_query`, which no chain of them writes. + * Stands beside the decomposed sampling stages rather than replacing them: one workgroup + * over an L2-resident row does not round like separate launches, and the fused row also + * writes `tok_excl` and `p_query`, which no chain of them produces. * * dflash_conv, dflash_select, the five gdn_* rows - * "Neither op has an unfused equivalent in the vocabulary" (r4d_shapes.cpp), and the GDN - * preamble's constituents -- a causal conv against a state cache, an L2 norm, a per-chunk - * gate cumsum -- have no op names either. + * No unfused equivalent in the vocabulary. The GDN preamble's parts (a causal conv against a + * state cache, an L2 norm, a per-chunk gate cumsum) have no op names. * - * NO TUNED AXIS IS READ HERE, for the reason r4d_shapes.cpp gives about extents: no axis this - * plugin declares changes WHAT a kernel computes. They name tile shapes, split counts, wave - * counts and all-reduce launch geometry. An axis that changed the chain would be read from `p`, - * where the core appends the chosen point alongside the geometry. + * No tuned axis is read here: this plugin's axes (tile shapes, split counts, wave counts, + * all-reduce launch geometry) do not change what a kernel computes. An axis that did would be read + * from `p`, where the core appends the chosen point. * - * Pure host code: no r4d.h, no HIP. It is in the CMake `SOURCES` list beside r4d_rows.cpp, - * r4d_layout.cpp and r4d_shapes.cpp for the reason that split exists -- the tables a transcription - * error hides in should compile and be readable on a box with no ROCm. + * Pure host code (no r4d.h, no HIP), like r4d_rows.cpp, r4d_layout.cpp and r4d_shapes.cpp, so the + * tables compile and can be read without ROCm. */ #include "r4d_plugin.h" +#include #include namespace { /* ==================================================================== reading the fused geometry * - * NOT r4d_pgeti_or(), and the difference is the one r4d_shapes.cpp spells out: that reader takes - * RAD_P_INT only, which is right for a LAUNCH -- by then the core has collapsed every range to the - * band's value -- and wrong here, because this hook, like `opd_shape`, can be called with a - * geometry whose ranges are still ranges. A RAD_P_RANGE reads as its HIGH bound wherever a scalar - * is needed, which is the same reading the operand descriptions take and therefore the reading a - * caller's buffers were sized under. */ + * Not r4d_pgeti_or(): that reads RAD_P_INT only, which suits a launch (every range has collapsed + * to the band's value), but this hook, like `opd_shape`, can see ranges still open. A RAD_P_RANGE + * reads as its high bound, as in the operand descriptions the caller's buffers were sized from. */ int64_t pi(const RadParam* p, int n_p, const char* k, int64_t dflt = 0) { if (!p || !k) return dflt; for (int i = 0; i < n_p; ++i) { @@ -138,19 +95,19 @@ int64_t pi(const RadParam* p, int n_p, const char* k, int64_t dflt = 0) { return dflt; } +/* Fused operand i when `present` has it, else RAD_FUSE_NONE: the wiring of an optional operand. */ +int16_t opt_opd(uint64_t present, int i) { + return RAD_FUSE_HAS(present, i) ? (int16_t)i : (int16_t)RAD_FUSE_NONE; +} + /* ==================================================================== building one step * - * A step is built by naming its op, then its parameters in the STEP op's own spelling, then its - * operand wiring in the STEP op's schema order. Building it in that order rather than filling a - * struct field by field is what makes the operand COUNT checkable by eye against the schema in - * r4d_rows.cpp -- the ABI checks it too, and a hook that has drifted from its schema is a - * diagnosable error rather than a silent misfire, but a list a reader can count is the half that - * stops the drift happening. + * A step names its op, then its parameters in the step op's spelling, then its operand wiring in + * the step op's schema order, so the operand count can be checked by eye against r4d_rows.cpp + * (the ABI checks it too). * - * `ok` carries a required parameter the fused geometry did not have. It is checked once, at - * `wire()`, for the reason r4d_shapes.cpp checks its whole operand list before handing out one - * entry: a chain whose second step is missing an `eps` is a chain a caller would run and compare, - * and a step resolved at the wrong geometry produces a difference that reads as the kernel's. + * `ok` records a required parameter the fused geometry lacks, and wire() refuses the step. A step + * resolved at the wrong geometry would produce a difference that reads as a kernel fault. */ struct Step { RadFuseStep* s; @@ -161,11 +118,9 @@ struct Step { s->op = op; } - /* Copy a parameter of the fused op VERBATIM, kind and all. Verbatim matters: `M` is the ranged - * parameter of every op in these chains, and re-emitting a range as its collapsed high bound - * would hand the step a different BAND from the one the fused kernel was selected for -- which - * for a banded family like the fp8 GEMMs is a different kernel with a different summation - * order. `eps` and `wadd` are RAD_P_F64 and would be destroyed by an integer reader. */ + /* Copies a fused-op parameter verbatim, kind included. `M` is ranged on every op here, and + * collapsing it would select a different band, which for a banded family like the fp8 GEMMs + * is a different kernel and summation order. `eps` and `wadd` are RAD_P_F64. */ Step& mirror(const RadParam* p, int n_p, const char* key) { const RadParam* f = rad_param_find(p, n_p, key); if (!f || s->n_p >= RAD_MAX_FUSE_PARAMS) { ok = false; return *this; } @@ -173,19 +128,17 @@ struct Step { return *this; } - /* The same, for a parameter that is OPTIONAL in both ops: absent stays absent rather than - * becoming an explicit default. The two are not the same thing to a constraint -- libr4d's - * rule is that a constraint whose key the geometry does not carry does not hold -- so - * inventing `wadd = 0` where the caller supplied none could route a step to a different row. */ + /* As mirror(), for a parameter optional in both ops: absent stays absent. A constraint whose + * key the geometry lacks does not hold, so inventing `wadd = 0` could route the step to a + * different row. */ Step& mirror_opt(const RadParam* p, int n_p, const char* key) { const RadParam* f = rad_param_find(p, n_p, key); if (!f) return *this; return mirror(p, n_p, key); } - /* Built field by field rather than through rad_types.h's RAD_INT / RAD_STR: those are compound - * literals, which are C and only a GNU extension in C++, and this file is ordinary host C++ - * that has to compile with or without ROCm present. */ + /* Built field by field: rad_types.h's RAD_INT / RAD_STR are C compound literals, only a GNU + * extension in C++. */ Step& pint(const char* key, long long v) { if (s->n_p >= RAD_MAX_FUSE_PARAMS) { ok = false; return *this; } RadParam q{}; @@ -206,9 +159,9 @@ struct Step { return *this; } - /* ONE ENTRY PER OPERAND OF THE STEP'S OP, in its schema's order. A non-negative value is an - * operand index of the FUSED kernel, RAD_FUSE_TMP(t) a temporary this chain passes between its - * own steps, RAD_FUSE_NONE an optional operand this step does not pass. */ + /* One entry per operand of the step's op, in schema order: a fused-kernel operand index, + * RAD_FUSE_TMP(t) for a temporary between steps, or RAD_FUSE_NONE for an optional operand the + * step does not pass. */ int wire(std::initializer_list from) { if (!ok) return RAD_E_UNSUPPORTED; if (from.size() > RAD_MAX_FUSE_OPD) return RAD_E_INVAL; @@ -217,22 +170,18 @@ struct Step { } }; -/* The activation a gated fold applies, in the vocabulary's spelling. `act` is OPTIONAL on both - * quantiser ops and the two shims default it DIFFERENTLY -- r4d_fp8.cpp reads `mode` 0 (silu) for - * `gated_quant_fp8` and `mode` 1 (sigmoid) for `gate_quant_fp8`, because the first serves - * down_proj's input and the second a gated attention's o_proj -- so the default is the caller's, - * not this file's, and each hook passes its own. An `act` this plugin does not compile is - * RAD_E_UNSUPPORTED at the launch too, so a chain for it would be a chain for a kernel that - * refuses the call. */ +/* Whether a gated fold's `act` (vocabulary spelling) is `want`. `act` is optional and the shims + * default it differently: r4d_fused_quant_fp8.hip uses `mode` 0 (silu) for `gated_quant_fp8`, which feeds + * down_proj, and `mode` 1 (sigmoid) for `gate_quant_fp8`, which feeds a gated attention's o_proj. + * Each hook passes its row's default. */ bool act_is(const RadParam* p, int n_p, const char* dflt, const char* want) { const char* a = r4d_pgets(p, n_p, "act"); return std::strcmp(a ? a : dflt, want) == 0; } -/* Every fp8 fold in this file quantises on the CHECKPOINT'S scale grid and refuses anything else - * by name -- the shims test `group` against r4d_quant_act_fp8_group() and so do the operand - * descriptions. A geometry that declares a different one has no fused kernel, so it has no chain - * either, and saying so here keeps the two hooks answering the same set. */ +/* The fp8 folds quantise only on the checkpoint's scale grid: the shims and the operand + * descriptions test `group` against r4d_quant_act_fp8_group(). Any other group has no fused kernel + * and so no chain. */ bool fp8_geometry_ok(const RadParam* p, int n_p, int64_t M, int64_t n) { return M > 0 && n > 0 && pi(p, n_p, "group", R4D_FP8_BLOCK) == R4D_FP8_BLOCK; } @@ -241,53 +190,35 @@ bool fp8_geometry_ok(const RadParam* p, int n_p, int64_t M, int64_t n) { /* ========================================================================================== * rmsnorm_quant_fp8 -- the RMS norm and the fp8 activation quantiser in one pass. - * (kernel: libr4d/r4d_fused_quant_fp8.hip, rmsnorm_quant_fp8_kernel; shim: r4d_fp8.cpp) + * (kernel: libr4d/r4d_fused_quant_fp8.hip, rmsnorm_quant_fp8_kernel and its shim) * * Operands: [0] x [1] residual? [2] w [3] q [4] scale [5] out_bf16? * - * THE CHAIN IS `add` + `rmsnorm` + `quant_act_fp8`, AND IT IS NOT `rmsnorm_add` + `quant_act_fp8`. - * That distinction is the reason to read the kernel rather than the row's prose: the other choice - * produces a chain that fails a byte comparison for no visible reason. The two candidates differ - * in ONE place -- which value the sum of squares is taken over: + * The chain is `add` + `rmsnorm` + `quant_act_fp8`, not `rmsnorm_add` + `quant_act_fp8`. The two + * differ in which value the sum of squares is taken over: * * this kernel `h = f2bf(bf2f(rr[i]) + bf2f(xr[i])); rr[i] = h; v = bf2f(h); ss += v * v;` - * The sum is rounded to bf16, STORED, and read back before the variance. Its own - * entry point says so in as many words: "`res += x` in f32, ROUNDED TO BF16 and - * stored, and the norm is then taken of the stored value -- which is bit-for-bit - * the `add` + `rmsnorm` pair this replaces". + * The sum is rounded to bf16, stored, and read back before the variance: the + * `add` + `rmsnorm` pair bit for bit. * * rmsnorm_add `float v = ldt(x, ..) + ldt(res, ..); ss += v * v; stt(ro, .., v);` - * (libref/ref_elementwise.cpp). The variance comes off the UNROUNDED f32 sum - * and only the multiply reads the stored value back. That file calls the choice - * "THE ROUNDING IS THE CONTRACT" and is right to -- it is vLLM's - * fused_add_rms_norm -- but it is a different function from this kernel's, by - * half a ULP on every channel, and the whole point of the declaration is that a - * caller may compare the bytes. + * (libref/ref_elementwise.cpp, matching vLLM's fused_add_rms_norm). The variance + * uses the unrounded f32 sum, half a ULP away on every channel. * - * So the residual add is spelled as the op that actually matches, and the payoff is larger than - * correctness alone: `add`, `rmsnorm` and `quant_act_fp8` are all rows of THIS plugin - * (add_bf16, rmsnorm_bf16, quant_act_fp8), so the chain can be checked libr4d-against-libr4d, - * which is the byte-identical comparison the ABI describes rather than a tolerance against a host - * oracle. `rmsnorm_add` has no libr4d row at all and would have forced the check cross-plugin. + * All three steps are libr4d rows (add_bf16, rmsnorm_bf16, quant_act_fp8), so the check stays + * within libr4d; `rmsnorm_add` has no libr4d row. * - * THE BYTE-IDENTITY RESTS ON THE WORKGROUP WIDTH AGREEING, which is worth knowing because it is - * the thing most likely to break silently. Both kernels pick their thread count from - * `r4d_act_threads(M, n)` and the width decides which columns a thread folds into the sum of - * squares; r4d_model_bf16.hip's launcher says "r4d_rmsnorm_quant_fp8 calls the SAME function, and - * it has to". `M` is mirrored verbatim below for exactly that reason. + * Byte identity depends on the workgroup width agreeing: both kernels take their thread count from + * `r4d_act_threads(M, n)`, which decides the columns each thread folds into the sum of squares + * (see the launcher in r4d_model_bf16.hip). `M` is mirrored verbatim for that reason. * - * Step 0 writes its output INTO the fused residual operand, which is both its own `b` and the - * fused kernel's INOUT residual. That is not an accident of the wiring: the fused kernel overwrites - * the residual in place, so a chain that wrote the sum anywhere else would leave a different set of - * buffers behind and the comparison would miss the difference. `add_bf16` is safe in place -- - * binary_kernel reads a[i] and b[i] and writes y[i], one element per thread, no neighbours. + * Step 0 writes the sum into the fused residual operand, both its own `b` and the fused kernel's + * in-place residual, so both sides leave the same buffers behind. `add_bf16` is safe in place: + * one element per thread, no neighbours. * - * Step 1's `y` is fused operand 5 rather than a temporary, and the ABI's own note explains why: - * the fold still WRITES its intermediate when asked to, precisely so that the fused and unfused - * forms leave the same buffers behind. `norm_quant_row` stores exactly the bf16 it then quantises - * (`h = f2bf(bf2f(nr[c]) * rs * (g + wadd)); if (yr) yr[c] = h; v[j] = bf2f(h);`), so operand 5 is - * not an optimisation the chain can route around -- it IS the value the codes were taken over. See - * the file header for why passing it is assumed rather than observed. + * The norm writes fused operand 5 when present. The kernel stores exactly the bf16 it quantises + * (`h = f2bf(bf2f(nr[c]) * rs * (g + wadd)); if (yr) yr[c] = h; v[j] = bf2f(h);`), so the codes + * are taken over that buffer. */ extern "C" int r4d_fuse_rmsnorm_quant_fp8(const RadParam* p, int n_p, uint64_t present, int step, RadFuseStep* out) { @@ -296,30 +227,23 @@ extern "C" int r4d_fuse_rmsnorm_quant_fp8(const RadParam* p, int n_p, uint64_t p const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"); if (!fp8_geometry_ok(p, n_p, M, n)) return RAD_E_UNSUPPORTED; - /* The two optional operands, read off the call rather than assumed. `residual` decides whether - * there is an `add` at all -- and therefore how long the chain is -- and `out_bf16` decides - * whether the bf16 the codes are taken over is a buffer the caller can see or one the chain - * has to make for itself. */ + /* `residual` decides whether there is an `add` step; `out_bf16` decides whether the norm + * output is a caller-visible buffer or a temporary. */ const bool has_res = RAD_FUSE_HAS(present, 1) != 0; const bool has_out = RAD_FUSE_HAS(present, 5) != 0; - /* The value the quantiser reads: the fused kernel's own out_bf16 where it has one, so both - * sides leave the same buffers behind, and a temporary where it does not. The kernel writes - * that bf16 either way (`h = f2bf(...); if (yr) yr[c] = h; v[j] = bf2f(h);`) -- operand 5 is - * not an optimisation the chain can route around, it IS the value the codes were taken over. */ const int16_t mid = has_out ? (int16_t)5 : RAD_FUSE_TMP(0); - /* Without a residual there is no `add`, so every step shifts down by one. */ + /* Without a residual there is no `add`, so the steps shift down by one. */ const int s = has_res ? step : step + 1; switch (s) { case 0: { - /* residual = x + residual, rounded to bf16 -- the store the norm then reads back. */ + /* residual = x + residual, rounded to bf16; the norm reads this store back. */ Step st(out, "add"); st.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "dtype"); return st.wire({ 0, 1, 1 }); /* a, b, y */ } case 1: { - /* The norm of the STORED sum -- or of `x` itself when nothing was added to it. `wadd` is - * mirrored only when the caller supplied it. */ + /* The norm of the stored sum, or of `x` without a residual. `wadd` only if supplied. */ Step st(out, "rmsnorm"); st.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "eps") .mirror(p, n_p, "dtype").mirror_opt(p, n_p, "wadd"); @@ -342,30 +266,19 @@ extern "C" int r4d_fuse_rmsnorm_quant_fp8(const RadParam* p, int n_p, uint64_t p * * Operands: [0] gate_up [1] q [2] scale [3] out_bf16? * - * `act` silu IS expressible and `act` sigmoid is NOT, and the reason is not the one it looks like. - * Both `sigmoid` and `mul` are ops of the vocabulary and both have libr4d rows (sigmoid_bf16, - * mul_bf16), so the missing piece is not an activation -- it is that `gate_up` is ONE [M, 2n] - * buffer whose halves are the gate and the up, and NOTHING IN THE OPERAND WIRING CAN NAME HALF OF - * AN OPERAND. `silu_mul` is the one op in the vocabulary that takes the packed plane and does the - * split itself, which is what makes the silu form reachable; there is no `sigmoid_mul` beside it. + * Only `act` silu has a chain. `gate_up` is one [M, 2n] buffer (gate half, then up half), and the + * wiring cannot name half an operand. `silu_mul` splits the packed plane itself; there is no + * `sigmoid_mul`. * - * There is a second, independent reason, and it is the one that would still bite if such an op - * were added carelessly. This kernel keeps the activation in f32 through the product and rounds - * ONCE: + * The kernel also keeps the activation in f32 through the product and rounds once: * * const float a = ACT == 0 ? g / (1.0f + expf(-g)) : 1.0f / (1.0f + expf(-g)); * const uint16_t h = f2bf(a * bf2f(gr[n + c])); * - * which is `silu_mul_bf16` element for element -- `f32_to_bf16((g / (1.0f + expf(-g))) * bf2f(gr[n - * + i]))` in r4d_model_bf16.hip -- and is NOT `sigmoid` followed by `mul`, which would round the - * activation to bf16 in between. Its sibling `gate_quant_fp8` below rounds there deliberately, - * because ITS reference is two kernels; this one's is one. A `sigmoid_mul` op would have to make - * the same choice this kernel did or the chain would be a different function again. - * - * So the sigmoid form gets RAD_E_UNSUPPORTED -- an honest decline, and the vocabulary gap it names - * is a `sigmoid_mul` over a packed [M, 2n] plane that rounds once, not a missing `sigmoid`. - * Nothing is lost: cGemmNtQGatedFp8 and the arch both reach the sigmoid gate through - * `gate_quant_fp8`, whose operands are two buffers rather than one plane. + * That matches `silu_mul_bf16` in r4d_model_bf16.hip element for element, and differs from + * `sigmoid` + `mul`, which round the activation in between. A future `sigmoid_mul` op would have to + * round once too. The sigmoid gate is reached through `gate_quant_fp8` instead (cGemmNtQGatedFp8 + * and the arch use it), whose gate is a separate operand. */ extern "C" int r4d_fuse_gated_quant_fp8(const RadParam* p, int n_p, uint64_t present, int step, RadFuseStep* out) { @@ -373,7 +286,7 @@ extern "C" int r4d_fuse_gated_quant_fp8(const RadParam* p, int n_p, uint64_t pre if (!out) return RAD_E_INVAL; const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"); if (!fp8_geometry_ok(p, n_p, M, n)) return RAD_E_UNSUPPORTED; - /* r4d_fp8.cpp's shim defaults this row's `mode` to 0, which is silu. */ + /* The shim (r4d_fused_quant_fp8.hip) defaults this row's `mode` to 0 (silu). */ if (!act_is(p, n_p, "silu", "silu")) return RAD_E_UNSUPPORTED; switch (step) { @@ -399,33 +312,23 @@ extern "C" int r4d_fuse_gated_quant_fp8(const RadParam* p, int n_p, uint64_t pre * * Operands: [0] gate [1] x [2] q [3] scale [4] out_bf16? * - * THIS ONE IS EXPRESSIBLE AND ITS SIBLING ABOVE IS NOT, which is the opposite of what the operand - * lists suggest, and the kernel says why in a comment written for exactly this question: + * Unlike the packed sibling above, this has a chain. The kernel rounds the activation before the + * multiply, because its reference is `sigmoid` then `mul`, two kernels with a bf16 buffer between: * * const uint16_t ab = f2bf(ACT == 0 ? gv / (1.0f + expf(-gv)) : 1.0f / (1.0f + expf(-gv))); * const uint16_t h = f2bf(bf2f(ab) * bf2f(xr[c])); - * // THE ACTIVATION IS ROUNDED BEFORE THE MULTIPLY, which is the one place this differs from - * // gated_quant_fp8 above and it is not an oversight. [...] This one's is `sigmoid` then - * // `mul`, TWO kernels with a bf16 buffer between them -- so the round trip is part of the - * // arithmetic being replaced, and skipping it changes the model's output. [...] * - * That round trip is the chain. `sigmoid_bf16` computes `f32_to_bf16(1.0f / (1.0f + - * expf(-bf2f(xr[i]))))` and `mul_bf16` computes `f32_to_bf16(bf2f(a) * bf2f(b))`, which are the - * two lines above term for term, and the gate arrives as its own [M, n] operand so there is no - * half-of-an-operand problem. Three launches an attention layer becoming one is what the fusion - * bought; the three are named here. + * `sigmoid_bf16` (`f32_to_bf16(1.0f / (1.0f + expf(-bf2f(xr[i]))))`) and `mul_bf16` + * (`f32_to_bf16(bf2f(a) * bf2f(b))`) match those two lines term for term. * - * `act` silu IS DECLINED because the arithmetic differs in the last bit. The chain's `silu` step - * resolves to silu_bf16 or libref, and both compute libref's `act_silu(x)`, `x * act_sigmoid(x)` - * -- two f32 roundings where this kernel does one divide, `f2bf(gv / (1.0f + expf(-gv)))`. A - * chain checked against it would report a difference in the last bit of many elements and call it - * a fault in the kernel, and a false failure is worse than a skip. Accepting silu needs this - * kernel to take the sigmoid first as well. Nothing in the tree issues this row with silu -- the gated attention's gate is a - * sigmoid, which is why the shim's `mode` defaults to 1. + * `act` silu is declined: the chain's `silu` step (silu_bf16 or libref) computes libref's + * `x * act_sigmoid(x)`, two f32 roundings, where this kernel does one divide, so many elements + * would differ in the last bit. Accepting silu needs the kernel to take the sigmoid first as well. + * The gated attention's gate is a sigmoid, so nothing issues this row with silu and the shim's + * `mode` defaults to 1. * - * TMP(0) is act(gate): an [M, n] bf16 plane the fusion genuinely never writes, so it is a - * temporary rather than an operand. `out_bf16` is not -- the kernel stores the product there when - * asked, and the codes are taken over those same bytes. + * TMP(0) is act(gate), an [M, n] bf16 plane the fusion never writes. `out_bf16` is an operand: the + * kernel stores the product there when asked and takes the codes over those bytes. */ extern "C" int r4d_fuse_gate_quant_fp8(const RadParam* p, int n_p, uint64_t present, int step, RadFuseStep* out) { @@ -433,12 +336,12 @@ extern "C" int r4d_fuse_gate_quant_fp8(const RadParam* p, int n_p, uint64_t pres if (!out) return RAD_E_INVAL; const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"); if (!fp8_geometry_ok(p, n_p, M, n)) return RAD_E_UNSUPPORTED; - /* r4d_fp8.cpp's shim defaults this row's `mode` to 1, which is sigmoid. */ + /* The shim (r4d_fused_quant_fp8.hip) defaults this row's `mode` to 1 (sigmoid). */ if (!act_is(p, n_p, "sigmoid", "sigmoid")) return RAD_E_UNSUPPORTED; switch (step) { case 0: { - /* The gate through the logistic, rounded to bf16 -- the buffer the pair had between them. */ + /* sigmoid(gate) rounded to bf16: the buffer the unfused pair had between them. */ Step s(out, "sigmoid"); s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "dtype"); return s.wire({ 0, RAD_FUSE_TMP(0) }); /* x, y */ @@ -460,43 +363,32 @@ extern "C" int r4d_fuse_gate_quant_fp8(const RadParam* p, int n_p, uint64_t pres /* ========================================================================================== * gemm_nt_q_gated -- the narrow fp8 GEMM with the SwiGLU and the quantiser in its epilogue. - * (row: gemm_fp8a8_gated_nt_m16; shim: r4d_fp8.cpp) + * (row: gemm_fp8a8_gated_nt_m16; shim: r4d_gemm_fp8a8.hip) * * Operands: [0] a [1] a_scale [2] b [3] b_scale [4] q [5] scale [6] out_bf16? * - * The row already states the claim -- "Byte-identical to gemm_nt_q followed by gated_quant_fp8 -- - * the accumulator is rounded to bf16 before the gate and the multiply, and the amax is an fmaxf - * reduction, which is exact and order-free however it is regrouped across the waves" -- and this - * is that sentence made executable. Both steps are libr4d rows, so the check is - * libr4d-against-libr4d. + * Byte-identical to gemm_nt_q followed by gated_quant_fp8: the accumulator is rounded to bf16 + * before the gate and the multiply, and the amax is an fmaxf reduction, exact under any regrouping + * across waves. Both steps are libr4d rows. * - * TMP(0) IS THE ONE GENUINE TEMPORARY IN THIS FILE: the [M, N] bf16 plane the unfused pair passed - * between the GEMM and the quantiser, and the plane whose non-existence is the entire point of the - * fusion ("no [M, 2n] tensor is ever written"). Its extents come from step 0's own `opd_shape`, - * which is the ABI's rule for a temporary, and `r4d_shape_gemm_nt_q` answers [M, N] bf16 for - * operand 4 while `r4d_shape_gated_quant_fp8` answers [M, 2n] for operand 0 -- the same plane, - * since `n` below is N/2. + * TMP(0) is the [M, N] bf16 plane between the GEMM and the quantiser, which the fusion never + * writes. Its extents come from step 0's `opd_shape` (the ABI rule for temporaries): + * r4d_shape_gemm_nt_q gives [M, N] for operand 4 and r4d_shape_gated_quant_fp8 gives [M, 2n] for + * operand 0, the same plane since `n` = N/2. * - * TWO PLACES WHERE A PARAMETER CANNOT SIMPLY BE COPIED, and both are the kind of thing that - * resolves to a plausible wrong kernel rather than to an error: + * Two parameters are not copies: * - * `n` is N/2 and not N. `N` on the fused op is the WEIGHT'S ROWS -- twice the fused width, - * gate then up -- which is exactly why this op has a schema of its own rather than a - * flag on `gemm_nt_q`. The quantiser's row is the OUTPUT width. + * `n` is N/2. The fused `N` is the weight's rows, gate then up, twice the output width + * (hence a schema of its own rather than a flag on `gemm_nt_q`). * - * `dtype` is "bf16" on the quantiser step and "fp8a8" on the GEMM step, from one key on the - * fused op. `dtype` names the operand COMBINATION for a GEMM and the width of the - * tensor an activation op READS, and the constraint rows disagree accordingly: - * cGemmNtQGatedFp8 has `C_IN("dtype", "fp8a8")` and cGatedQuantFp8 has - * `C_IN("dtype", "bf16")`. Mirroring the fused value into step 1 would match no row of - * this plugin, and the chain would be unresolvable rather than wrong -- but only - * because nothing else declares a bf16-named `gated_quant_fp8`, which is not a - * guarantee worth relying on. + * `dtype` is "fp8a8" on the GEMM step and "bf16" on the quantiser step. For a GEMM it names the + * operand combination, for an activation op the width of its input: cGemmNtQGatedFp8 + * has `C_IN("dtype", "fp8a8")`, cGatedQuantFp8 `C_IN("dtype", "bf16")`. Copying the + * fused value fails to resolve only because no other row declares that combination. * - * `a_sum` and `b_ref` are the two operands libr4d appended after `gemm_nt_q`'s `y`, and an fp8 - * grid has neither -- `a_sum` belongs to the asymmetric integer grids and `b_ref` to mxfp4, and - * r4d_shape_gemm_nt_q says the same by describing both as absent. They are RAD_FUSE_NONE and not - * simply omitted, because ONE ENTRY PER SCHEMA OPERAND is what makes the count a drift check. + * `a_sum` (asymmetric integer grids) and `b_ref` (mxfp4) follow `gemm_nt_q`'s `y`; an fp8 grid has + * neither, and r4d_shape_gemm_nt_q describes both as absent. They are wired RAD_FUSE_NONE, not + * omitted, to keep one entry per schema operand. */ extern "C" int r4d_fuse_gemm_nt_q_gated(const RadParam* p, int n_p, uint64_t present, int step, RadFuseStep* out) { @@ -507,13 +399,13 @@ extern "C" int r4d_fuse_gemm_nt_q_gated(const RadParam* p, int n_p, uint64_t pre if (M <= 0 || N <= 0 || K <= 0 || N % 2) return RAD_E_UNSUPPORTED; if (pi(p, n_p, "group", R4D_FP8_BLOCK) != R4D_FP8_BLOCK) return RAD_E_UNSUPPORTED; if (!dt || std::strcmp(dt, "fp8a8")) return RAD_E_UNSUPPORTED; - /* REQUIRED on this op, unlike the quantiser's, because only the silu form is compiled -- an - * optional parameter would let the row resolve for a gate it cannot serve. */ + /* Required on this op, unlike on the quantiser, because only silu is compiled; an optional + * parameter would let the row resolve for a gate it cannot serve. */ if (!act_is(p, n_p, "silu", "silu")) return RAD_E_UNSUPPORTED; switch (step) { case 0: { - /* The GEMM over the whole [N, K] gate_up plane, into the bf16 that never exists. */ + /* The GEMM over the whole [N, K] gate_up weight, into the temporary plane. */ 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"); @@ -521,7 +413,7 @@ extern "C" int r4d_fuse_gemm_nt_q_gated(const RadParam* p, int n_p, uint64_t pre return s.wire({ 0, 1, 2, 3, RAD_FUSE_TMP(0), RAD_FUSE_NONE, RAD_FUSE_NONE }); } case 1: { - /* The gate, the multiply and the codes over the accumulator plane, at half its width. */ + /* Gate, multiply and codes over the accumulator plane, at half its width. */ Step s(out, "gated_quant_fp8"); s.mirror(p, n_p, "M").pint("n", (long long)(N / 2)).mirror(p, n_p, "group") .pstr("dtype", "bf16").mirror(p, n_p, "act"); @@ -541,14 +433,12 @@ extern "C" int r4d_fuse_gemm_nt_q_gated(const RadParam* p, int n_p, uint64_t pre * [8] dt_bias [9] state [10] state_idx [11] num_accepted [12] cu [13] z * [14] norm_w [15] o [16] o_q [17] o_scale * - * The pair's q, k and v are the three temporaries. Every parameter is the step's own under the - * same name, so the chain is copies: the convolution's four, then the recurrent update's. */ + * The pair's q, k and v are the three temporaries. Every parameter has the same name in the step + * op, so each step mirrors its own: the convolution's four, then the recurrent update's. */ extern "C" int r4d_fuse_gdn_conv_recurrent_update(const RadParam* p, int n_p, uint64_t present, int step, RadFuseStep* out) { if (!out) return RAD_E_INVAL; - const int16_t cb = RAD_FUSE_HAS(present, 2) ? 2 : RAD_FUSE_NONE; - const int16_t oq = RAD_FUSE_HAS(present, 16) ? 16 : RAD_FUSE_NONE; - const int16_t os = RAD_FUSE_HAS(present, 17) ? 17 : RAD_FUSE_NONE; + const int16_t cb = opt_opd(present, 2), oq = opt_opd(present, 16), os = opt_opd(present, 17); switch (step) { case 0: { Step s(out, "gdn_conv_update"); @@ -587,9 +477,7 @@ extern "C" int r4d_fuse_gdn_conv_recurrent_update(const RadParam* p, int n_p, ui extern "C" int r4d_fuse_qk_norm_rope_gate_kv_store(const RadParam* p, int n_p, uint64_t present, int step, RadFuseStep* out) { if (!out) return RAD_E_INVAL; - auto opt = [&](int i) -> int16_t { - return RAD_FUSE_HAS(present, i) ? (int16_t)i : (int16_t)RAD_FUSE_NONE; - }; + auto opt = [present](int i) { return opt_opd(present, i); }; switch (step) { case 0: { Step s(out, "qk_norm_rope_gate"); @@ -612,51 +500,6 @@ extern "C" int r4d_fuse_qk_norm_rope_gate_kv_store(const RadParam* p, int n_p, u } } -/* ========================================================================================== - * ar_rmsnorm_quant_fp8 -- the two-rank all-reduce with the norm and the quantiser folded on. - * (kernel: libr4d/r4d_fused_quant_fp8.hip, ar_rmsnorm_quant_fp8_kernel; shim: r4d_ar.cpp) - * - * Operands: [0] x (inout) [1] residual? [2] w [3] q [4] scale [5] out_bf16? - * - * THE CHEAPEST HONEST CHAIN IN THE FILE, and the one that needs no assumption about optional - * operands at all. Its second step is `rmsnorm_quant_fp8`, which is itself an op of the vocabulary - * and carries the SAME two optional operands in the same positions -- so `residual` and `out_bf16` - * are wired straight through and absence propagates through the wiring rather than having to be - * observed. That is worth noticing as a design rule: a fold whose tail is itself a declared op - * hands the discrimination to the step, and the ABI gap described in the file header disappears. - * - * BOTH WIRES, and the kernel earns the claim rather than approximating it. On the exact wire pass - * one is `a = f2bf(bf2f(xr[i]) + bf2f(pr[i])); xr[i] = a;` -- the standalone one-shot's own f32 sum - * stored as bf16, written back into `x` so that "a reader of `x` that is not this norm still finds - * the same bytes". On the compressed wire the reduce loop stores the inverse-rotated sum into `x` - * as bf16 "which is what the standalone compressed all-reduce wrote, so pass two below reads the - * bytes it would have read". Everything after the handshake is `norm_quant_row`, the same device - * function the standalone fold above runs. Contrast `ar_ln_had_quant_i8`, which takes the opposite - * decision (`t = mine + peer + residual` with no round between) and therefore publishes no hook. - * - * THREE PARAMETERS THAT ARE NOT COPIES, and each of them decides which all-reduce row serves the - * step: - * - * `numel` is M * n. The fused op declares the message by its [M, n] operand and - * `all_reduce` declares it as an element count -- and as THE LARGEST message the - * instance will carry, not the one a step passes, which is why the band's high - * bound is the right value and `pi` reads a range as one. - * - * `exact` is the fused `wire` inverted. It is REQUIRED on `all_reduce` and it is the - * predicate that separates cArExact from cArWht6; a caller that does not declare it - * gets no kernel at all. - * - * `min_bytes` is 0, and ONLY on the compressed wire. The wht6 shim serves a message below its - * floor with the EXACT kernel instead -- safe, because both kernels share the - * instance's scratch and flag space -- and the fused kernel has no such fallback: a - * `wire` of 6 is 6 at every size. Its comment names the spelling for this exact - * case: "A caller that needs the rotated wire unconditionally asks for a floor of - * 0." Leaving the key out would let a small message go out exact on one side of the - * comparison and rotated on the other. - * - * `hops` is not emitted: no libr4d row reads it, and two ranks have only the one-shot. `y` is - * RAD_FUSE_NONE: the fused kernel reduces in place into `x`, as every all-reduce row does. - */ /* ========================================================================================== * attn_paged_gate_quant -- attn_paged, then gate_quant_fp8 over its output. * (row: attn_decode_gq_h256_gqa12_fp8kv; kernels: libr4d/r4d_attn_decode_h256_gqa6.hip, the @@ -665,16 +508,14 @@ extern "C" int r4d_fuse_qk_norm_rope_gate_kv_store(const RadParam* p, int n_p, u * Operands: [0] q [1] kv_cache [2] block_table [3] seqused [4] k_descale? [5] v_descale? * [6] cu_seqlens? [7] out [8] gate [9] q8 [10] q8_scale * - * No temporaries: gate_quant_fp8 reads `out` and writes its bf16 product back over it, which is - * the in-place pair the fold replaces. Its rows are attn_paged's (token, head) pairs, so its `M` is - * the band's query rows times the head count -- a bound, which is all its shim reads it as -- and - * its `n` is `head_dim`. */ + * No temporaries: gate_quant_fp8 reads `out` and writes its bf16 product back over it, the + * in-place pair the fold replaces. Its rows are attn_paged's (token, head) pairs, so its `M` is the + * band's query rows times the head count (a bound, which is how its shim reads it) and its `n` is + * `head_dim`. */ extern "C" int r4d_fuse_attn_paged_gate_quant(const RadParam* p, int n_p, uint64_t present, int step, RadFuseStep* out) { if (!out) return RAD_E_INVAL; - auto opt = [&](int i) -> int16_t { - return RAD_FUSE_HAS(present, i) ? (int16_t)i : (int16_t)RAD_FUSE_NONE; - }; + auto opt = [present](int i) { return opt_opd(present, i); }; const int64_t q_len = pi(p, n_p, "q_len"), nh = pi(p, n_p, "n_head"); const int64_t hd = pi(p, n_p, "head_dim"), seqs = pi(p, n_p, "max_seqs", 1); if (q_len <= 0 || nh <= 0 || hd <= 0 || seqs <= 0) return RAD_E_UNSUPPORTED; @@ -707,15 +548,14 @@ extern "C" int r4d_fuse_attn_paged_gate_quant(const RadParam* p, int n_p, uint64 * Operands: [0] y_expert [1] expert_w [2] sorted_tok [3] shared? [4] shared_gate? [5] y (inout) * [6] inj [7] h (inout) * - * Two declared ops and nothing in between: the gather writes `y`, which is the reduction's message - * and is then reduced in place and written into the streams. The shared-arm pair is optional in - * both ops at the same positions, so its absence propagates through the wiring. `wire` is the - * reducing write's, and it goes to that step unchanged; so does `world_size`, which at four selects - * ar_hc_write_4rank, the reduction and write the four-rank row runs. + * Two declared ops with nothing in between: the gather writes `y`, the message that is then + * reduced in place and written into the streams. The shared-arm pair is optional at the same + * positions in both ops, so its absence propagates through the wiring. `wire` and `world_size` go + * to the reducing step unchanged; `world_size` 4 selects ar_hc_write_4rank, as the four-rank row + * runs. */ extern "C" int r4d_fuse_ar_gather_hc_write(const RadParam* p, int n_p, uint64_t present, int step, RadFuseStep* out) { - (void)present; 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, "top_k"); if (M <= 0 || n <= 0 || k <= 0) return RAD_E_UNSUPPORTED; @@ -737,6 +577,38 @@ extern "C" int r4d_fuse_ar_gather_hc_write(const RadParam* p, int n_p, uint64_t } } +/* ========================================================================================== + * ar_rmsnorm_quant_fp8 -- the two-rank all-reduce with the norm and the quantiser folded on. + * (kernel: libr4d/r4d_fused_quant_fp8.hip, ar_rmsnorm_quant_fp8_kernel; shim: r4d_ar_entry.hip) + * + * Operands: [0] x (inout) [1] residual? [2] w [3] q [4] scale [5] out_bf16? + * + * The second step is `rmsnorm_quant_fp8`, an op with the same two optional operands in the same + * positions, so `residual` and `out_bf16` are wired straight through and absence propagates + * without reading `present`. + * + * Both wires match exactly. On the exact wire, pass one stores the standalone one-shot's f32 sum + * as bf16 back into `x` (`a = f2bf(bf2f(xr[i]) + bf2f(pr[i])); xr[i] = a;`). On the compressed + * wire the reduce loop stores the inverse-rotated sum into `x` as bf16, as the standalone + * compressed all-reduce does. After the handshake both run `norm_quant_row`, the device function + * of rmsnorm_quant_fp8. Contrast ar_ln_had_quant_i8, which does not round and has no hook. + * + * Three parameters are not copies, and each selects which all-reduce row serves the step: + * + * `numel` is M * n. `all_reduce` declares the largest message the instance carries, as an + * element count, so the band's high bound (how `pi` reads a range) is right. + * + * `exact` is the fused `wire` inverted. It is required on `all_reduce` and separates + * cArExact from cArWht6. + * + * `min_bytes` is 0, on the compressed wire only. The wht6 shim serves a message below its floor + * with the exact kernel (both share the instance's scratch and flag space), but the + * fused kernel has no such fallback. Without the key a small message could go out + * exact on one side of the comparison and rotated on the other. + * + * `hops` is not emitted: no libr4d row reads it, and two ranks have only the one-shot. `y` is + * RAD_FUSE_NONE: the fused kernel reduces in place into `x`, as every all-reduce row does. + */ extern "C" int r4d_fuse_ar_rmsnorm_quant_fp8(const RadParam* p, int n_p, uint64_t present, int step, RadFuseStep* out) { @@ -745,8 +617,7 @@ extern "C" int r4d_fuse_ar_rmsnorm_quant_fp8(const RadParam* p, int n_p, uint64_ const int64_t world = pi(p, n_p, "world_size"); const int64_t wire = pi(p, n_p, "wire", 0); if (!fp8_geometry_ok(p, n_p, M, n) || world <= 0) return RAD_E_UNSUPPORTED; - /* The entry point serves 0 and 6 and refuses anything else; a chain for a wire that has no - * kernel would name a payload neither side can produce. */ + /* The entry point serves wires 0 and 6 only; any other has no kernel and so no chain. */ if (wire != 0 && wire != 6) return RAD_E_UNSUPPORTED; switch (step) { diff --git a/libr4d/r4d_fused_quant_fp8.hip b/libr4d/r4d_fused_quant_fp8.hip index 70430172..7fb8b679 100644 --- a/libr4d/r4d_fused_quant_fp8.hip +++ b/libr4d/r4d_fused_quant_fp8.hip @@ -1,49 +1,34 @@ -// r4d_fused_quant_fp8.hip - the two producers that already have an activation row in registers, -// with r4d_quant_act_fp8 riding along on the same pass. +// r4d_fused_quant_fp8.hip - producers that already hold an activation row in registers, fused with +// r4d_quant_act_fp8's per-(row, 128) E4M3 quantisation. // -// WHY FUSE, AND WHY THESE TWO. The fp8a8 GEMMs need an E4M3 activation with an f32 scale per -// (row, 128 columns) in front of EVERY quantised linear, and `activation_scheme: dynamic` means -// there is no shipped scale to skip it with. A decode step of this model issues ~300 of those -// quantisers -- one per activation per layer, on both ranks -- each costing microseconds on a step -// budgeted in tens of milliseconds. That is not bandwidth: the row is 8 tokens by 5120 channels, -// 82 KiB, which is 0.13 us of a 638 GB/s card. It is a launch, a grid fill and a second pass over -// a row some other kernel had in registers a moment earlier. +// The fp8a8 GEMMs need a quantised activation before every linear (`activation_scheme: dynamic`, +// so no shipped scale). A decode step issues ~300 quantisers; each costs a launch, a grid fill and +// a second pass over a row another kernel just had in registers, not bandwidth. Fused producers: // -// Two of the three producers hand the quantiser a row they have just computed: +// rmsnorm -> quant the input of every attention, GDN and MLP linear +// silu_mul -> quant down_proj's input // -// rmsnorm -> quant the input of every attention, GDN and MLP linear. ~128 a step. -// silu_mul -> quant down_proj's input. ~64 a step. +// A GEMM output feeding the next linear stays a separate launch. The int8 path has the same fusion +// (r4d_rmsnorm_had_quant_i8, r4d_gated_had_quant_i8), where the rotation is required to survive one +// scale per row; a 128-wide block scale does not need it. // -// The third (a GEMM's own output feeding the next linear) is not fusable this way and stays a -// launch of its own. The int8 path carries the same fusion -- r4d_rmsnorm_had_quant_i8 and -// r4d_gated_had_quant_i8 -- and this is the fp8 form of it, minus the rotation, which is what the -// int8 grid needs to survive one scale per row and a 128-wide block scale does not. +// Bit-identical to the unfused pair it replaces (generated text is compared byte for byte across +// builds). The pair writes a bf16 norm output and the quantiser reads it back, so amax and codes +// are taken over bf16-rounded values; these kernels round to bf16 first and quantise the +// round-tripped float. // -// BIT-IDENTICAL TO THE PAIR IT REPLACES, and that is a hard requirement rather than a nicety, -// because the engine's generated text is compared byte for byte across builds. The unfused pair -// writes a BF16 norm output and the quantiser then reads those bf16 bytes back, so the amax and -// the codes are taken over -// bf16-ROUNDED values. Both kernels here round to bf16 first and quantise the round-tripped float, -// which costs one v_cvt per element and is the difference between "the same text" and "very nearly -// the same text". +// The norm re-reads its row for the second pass, with or without the residual. Unlike +// r4d_rmsnorm_had_quant_i8 (which normalises the f32 sum), the sum is rounded to bf16 and stored +// first, matching `add` writing a bf16 residual that `rmsnorm` reads back; the re-read is L1-hot. // -// THE NORM RE-READS ITS ROW FOR THE SECOND PASS rather than keeping it in registers or LDS, and -// that stays true WITH the residual, which is where this differs from r4d_rmsnorm_had_quant_i8. -// That kernel keeps the row because it normalises the f32 sum, and re-reading would normalise a -// bf16-rounded one, which costs thousands of +/-1 codes. This one rounds the sum to bf16 and -// stores it FIRST, because that is what the pair it replaces does: `add` writes a bf16 residual and -// `rmsnorm` reads those bytes back. So the value normalised here is the value normalised there, -// the re-read is L1-hot, and the output does not move. Less accurate than the int8 path's choice, -// and bit-identical to the pair it replaces, which is the property that matters here. +// The residual may alias `out_bf16`, and every caller here does so: a block reads the previous +// block's delta from the shared `h` buffer and writes its norm output back into it. Pass one reads +// every `x` element before the block_sum barrier and pass two writes `y` after it, so they never +// race. // -// THE RESIDUAL MAY ALIAS `out_bf16`, and every caller in this tree makes it do so: a block reads -// the PREVIOUS block's delta out of the shared `h` buffer and writes its own norm output back into -// it. Pass one reads every `x` element before the block_sum barrier and pass two writes `y` only -// after it, so the two never race. -// -// `wadd` IS ADDED TO EVERY GAIN IN f32, for the reason r4d_rmsnorm_had_quant_i8 gives at length: -// Qwen3.5's norms are GemmaRMSNorm over a zero-centred gamma, and forming `1 + w` in bf16 first is -// a systematic 0.3% per channel. Pass 0 for a plain RMS norm. +// `wadd` is added to every gain in f32 (see r4d_rmsnorm_had_quant_i8): Qwen3.5's GemmaRMSNorm uses +// a zero-centred gamma, and forming `1 + w` in bf16 is a systematic 0.3% error. Pass 0 for a plain +// RMS norm. // // Returns a negative code rather than throwing, for the reason given in r4d_gemm_fp8a8.hip. @@ -62,16 +47,15 @@ constexpr uint32_t kGroup = 128; __device__ __forceinline__ float bf2f(uint16_t h) { return __uint_as_float((uint32_t)h << 16); } -// Round-to-nearest-even, the same three lines every bf16 store in this library uses. +// Round-to-nearest-even, as every bf16 store in this library rounds. __device__ __forceinline__ uint16_t f2bf(float f) { const uint32_t u = __float_as_uint(f); return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); } -// Both reductions exchange through DPP and permlanex16 (r4d_xor_lane, r4d_wave_sum) rather than -// `__shfl_xor`, which gfx1201 lowers to ds_bpermute_b32 -- an LDS round trip a stage, five a -// reduction, with nothing else in flight on the wave to hide them. Same partners in the same order, -// so the same bits. +// Both reductions use DPP and permlanex16 (r4d_xor_lane, r4d_wave_sum) rather than `__shfl_xor`, +// which gfx1201 lowers to ds_bpermute_b32, an LDS round trip per stage. Same partners in the same +// order, so the same bits. __device__ __forceinline__ float wave_max(float v) { v = fmaxf(v, r4d_xor_lane<16>(v)); v = fmaxf(v, r4d_xor_lane<8>(v)); @@ -93,15 +77,11 @@ __device__ __forceinline__ float block_sum(float v, float* lds) { return s; } -// One 128-column group's worth of quantisation, given the four bf16-rounded values a lane owns. -// Lifted out because both kernels below end the same way, and because getting the clamp wrong is -// the failure r4d_quant_act_fp8.hip spends a paragraph on: v_cvt_pk_fp8_f32 answers an -// out-of-range input with a NaN rather than saturating, and `amax * (1/scale)` is 448 in exact -// arithmetic but can land an ulp above it in float -- so without the fmin every block containing -// its own maximum produces a NaN. +// Quantise one 128-column group from the four bf16-rounded values a lane owns. The clamp in +// q8_pack4 is required (see r4d_q8.h): v_cvt_pk_fp8_f32 returns NaN out of range, and +// `amax * (1/scale)` can land an ulp above 448. // -// I8 writes int8 codes at amax / 127 instead (r4d_q8.h), the codes quant_act_i8g would take over -// the same bf16 values: an int8 linear reads them where an fp8 one reads the E4M3 pair. +// I8 writes int8 codes at amax / 127 instead (r4d_q8.h), the same codes quant_act_i8g produces. template __device__ __forceinline__ void quant_group(const float v[4], float* __restrict__ s, uint8_t* __restrict__ q, size_t s_at, uint32_t c0, @@ -112,17 +92,15 @@ __device__ __forceinline__ void quant_group(const float v[4], float* __restrict_ if (lane == 0) s[s_at] = sc; const float inv = 1.0f / sc; const uint32_t pk = q8_pack4(v[0], v[1], v[2], v[3], inv); - // A ragged last group is written zero-padded rather than partially, exactly as - // r4d_quant_act_fp8 does, and the caller owns `n` rounded up to 4 bytes of `q`. + // A ragged last group is written zero-padded, as in r4d_quant_act_fp8; the caller owns `n` + // rounded up to 4 bytes of `q`. if (c0 < n) *(uint32_t*)(q + c0) = pk; } -// Pass two, shared by every kernel in this file that ends in a block-scaled fp8 activation: give -// each wave a whole 128-column group and each lane four consecutive columns of it, which is what -// makes the group's amax a wave reduction and the E4M3 store a single dword. `nr` is the row the -// norm was taken OF, already in memory -- rounding it to bf16 and reading it back is the whole -// bit-identity argument at the top of this file, and it is written once here so that the fused -// all-reduce below cannot drift from the standalone norm above it. +// Pass two of every norm kernel here: each wave takes a 128-column group and each lane four +// consecutive columns, so the group's amax is a wave reduction and the store a single dword. `nr` +// is the row the norm is taken of, already in memory (see the bit-identity note above). Shared so +// the fused all-reduce cannot drift from the standalone norm. template __device__ __forceinline__ void norm_quant_row( const uint16_t* __restrict__ nr, const void* __restrict__ w, uint16_t* __restrict__ yr, @@ -132,10 +110,8 @@ __device__ __forceinline__ void norm_quant_row( for (uint32_t kb = wave; kb < nkb; kb += THR / kWave) { const uint32_t c0 = kb * kGroup + lane * 4u; float v[4] = {0.0f, 0.0f, 0.0f, 0.0f}; - // ONE BRANCH FOR ALL FOUR COLUMNS. Every launcher refuses an `n` that is not a multiple of - // four, so a lane's columns are all in the row or all past it. Guarded one column at a - // time, each load sits in its own branch with its use straight after it and the compiler - // waits for every one before issuing the next; under one branch they all issue first. + // One branch for all four columns: every launcher requires n % 4 == 0, so a lane's columns + // are all in or all out. Per-column guards would serialise the loads. if (c0 < n) { float g[4]; uint16_t x[4]; @@ -146,8 +122,7 @@ __device__ __forceinline__ void norm_quant_row( } #pragma unroll for (int j = 0; j < 4; ++j) { - // THE BF16 ROUND TRIP IS THE POINT. The unfused quantiser reads these bytes, not - // the f32 that produced them. + // The bf16 round trip is deliberate: the unfused quantiser reads these bytes. const uint16_t h = f2bf(bf2f(x[j]) * rs * (g[j] + wadd)); if (yr) yr[c0 + j] = h; v[j] = bf2f(h); @@ -158,9 +133,7 @@ __device__ __forceinline__ void norm_quant_row( } // ---------------------------------------------------------------------------- rmsnorm -> quant -// One block a row. Pass one is the sum of squares across all 256 threads; pass two gives each wave -// a whole 128-column group and each lane four consecutive columns of it, which is what makes the -// group's amax a wave reduction and the E4M3 store a single dword. +// One block per row. Pass one is the block-wide sum of squares; pass two is norm_quant_row. template __global__ __launch_bounds__(THR) void rmsnorm_quant_fp8_kernel( const uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w, @@ -171,14 +144,12 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_fp8_kernel( const uint32_t row = blockIdx.x; const uint16_t* __restrict__ xr = x + (size_t)row * x_ld; uint16_t* __restrict__ rr = RES ? res + (size_t)row * r_ld : nullptr; - // What the norm is taken OF: the residual once there is one, the input otherwise. + // The norm is taken of the residual when there is one, else of the input. const uint16_t* __restrict__ nr = RES ? rr : xr; - // FOUR STRIDES OF THE ROW ARE LOADED BEFORE ANY IS USED. A plain `i += THR` loop waits for - // each stride's load before issuing the next, one round trip per stride; here a stride past - // the row reloads this thread's first column, which is always in the row, and is skipped - // below. The sum still takes this thread's columns in the order `i = tid; i += THR` does, - // which is the order every kernel sharing r4d_act_threads' partition takes them in. + // Four strides are loaded before any is used, avoiding one round trip per stride. A stride past + // the row reloads this thread's first column and is skipped below. The summation order is still + // that of `i = tid; i += THR`, shared by every kernel using r4d_act_threads' partition. constexpr uint32_t kU = 4; float ss = 0.0f; for (uint32_t i0 = threadIdx.x; i0 < n; i0 += kU * THR) { @@ -212,23 +183,16 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_fp8_kernel( } // ---------------------------------------------------------------------------- gate -> quant -// silu(gate) * up, or sigmoid(gate) * up, then the same quantiser. No reduction across the row, so -// there is no first pass and no barrier: one wave, one group, done. +// silu(gate) * up or sigmoid(gate) * up, then the same quantiser. No row reduction, so no first +// pass and no barrier: one wave per group. // -// ROT INSERTS THE WIDTH-128 HADAMARD between the product and the absmax, which is where it has to -// go: the benefit of a rotation is entirely that the maximum the grid is scaled by gets smaller. -// It is free here for the same reason it is free in r4d_quant_act_fp8 -- this kernel's mapping, -// one wave a 128-group and four consecutive values a lane, IS r4d_fwht_wave<128>'s, so the seven -// stages are register arithmetic and five shuffles on a launch already being paid. +// ROT inserts the width-128 Hadamard between the product and the absmax, in registers, since this +// mapping (one wave per group, four values per lane) is r4d_fwht_wave<128>'s. `y` still receives +// the unrotated product: it is for a bf16 consumer, and the rotation belongs to the quantised pair +// only. // -// `y` STILL RECEIVES THE UNROTATED PRODUCT, and that is not an inconsistency. `y` exists for a -// bf16 consumer of the silu output; the rotation is a property of the QUANTISED pair alone, and -// the weight that undoes it never sees `y`. -// -// A WAVE A GROUP, AND NO IDLE WAVES. With no reduction across the row the workgroup's width changes -// nothing but how many groups run at once, so the launcher sizes it to the row's groups, capped at -// r4d_act_threads' width, and the kernel reads the width from blockDim. A fixed width leaves most -// of the waves of a narrow row with nothing to do: at 1024 threads and three groups, 29 of 32. +// The launcher sizes the workgroup to the row's groups (capped at r4d_act_threads' width) and the +// kernel reads the width from blockDim, so a narrow row does not leave most waves idle. template __global__ __launch_bounds__(1024) void gated_quant_fp8_kernel( const uint16_t* __restrict__ gu, uint16_t* __restrict__ y, uint8_t* __restrict__ q, @@ -243,8 +207,7 @@ __global__ __launch_bounds__(1024) void gated_quant_fp8_kernel( for (uint32_t kb = wave; kb < nkb; kb += blockDim.x / kWave) { const uint32_t c0 = kb * kGroup + lane * 4u; float v[4] = {0.0f, 0.0f, 0.0f, 0.0f}; - // One branch for all four columns, so all eight loads issue before any is waited on; see - // norm_quant_row. + // One branch for all four columns; see norm_quant_row. if (c0 < n) { uint16_t gb[4], ub[4]; #pragma unroll @@ -261,8 +224,7 @@ __global__ __launch_bounds__(1024) void gated_quant_fp8_kernel( v[j] = bf2f(h); } } - // The rotated launcher refuses an n that is not a multiple of the group, so no block that - // reaches this line mixes real values with the padding zeros above. + // The rotated launcher requires n % 128 == 0, so no rotated group contains padding. if constexpr (ROT) r4d_fwht_wave<(int)kGroup>(v, (int)lane); quant_group(v, s, qr, (size_t)row * s_ld + kb, c0, n, lane); } @@ -270,15 +232,12 @@ __global__ __launch_bounds__(1024) void gated_quant_fp8_kernel( // -------------------------------------------------- gate . x -> quant, two source buffers // -// THE SAME EPILOGUE WITH THE GATE SOMEWHERE ELSE. A gated attention's output gate is not packed -// beside the thing it scales: `x` is the attention output [T, n_head * head_dim] and the gate is a -// COLUMN SLICE of the [q|gate] projection, [T * n_head, 2 * head_dim] with the gate half at -// `g_off`. So the row is a (token, head) pair rather than a token, which is the whole trick: at -// that shape `x` is contiguous, the gate is a fixed stride apart, and the fp8 scale plane of -// [T * n_head, head_dim / 128] is byte-for-byte the [T, n_head * head_dim / 128] the out -// projection reads. Three launches an attention layer -- sigmoid, the multiply, the quantiser -- -// become one, and at a decode batch the dispatch gap between those three is comparable to the work -// they do. +// The same epilogue with the gate in a separate buffer. For gated attention, `x` is the attention +// output [T, n_head * head_dim] and the gate is a column slice of the [q|gate] projection, +// [T * n_head, 2 * head_dim] with the gate half at `g_off`. A row is a (token, head) pair: `x` is +// then contiguous, the gate a fixed stride apart, and the scale plane [T * n_head, head_dim / 128] +// is byte-identical to the [T, n_head * head_dim / 128] the out projection reads. Replaces three +// launches (sigmoid, multiply, quantise) per attention layer. template __global__ __launch_bounds__(1024) void gate_quant_fp8_kernel( const uint16_t* __restrict__ g, const uint16_t* __restrict__ x, uint16_t* __restrict__ y, @@ -294,8 +253,7 @@ __global__ __launch_bounds__(1024) void gate_quant_fp8_kernel( for (uint32_t kb = wave; kb < nkb; kb += blockDim.x / kWave) { const uint32_t c0 = kb * kGroup + lane * 4u; float v[4] = {0.0f, 0.0f, 0.0f, 0.0f}; - // One branch for all four columns, so all eight loads issue before any is waited on; see - // norm_quant_row. + // One branch for all four columns; see norm_quant_row. if (c0 < n) { uint16_t gb[4], xb[4]; #pragma unroll @@ -306,13 +264,9 @@ __global__ __launch_bounds__(1024) void gate_quant_fp8_kernel( #pragma unroll for (int j = 0; j < 4; ++j) { const float gv = bf2f(gb[j]); - // THE ACTIVATION IS ROUNDED BEFORE THE MULTIPLY, which is the one place this - // differs from gated_quant_fp8 above and it is not an oversight. That kernel's - // unfused reference is silu_mul_bf16, ONE kernel that keeps the activation in f32 - // through the product. This one's is `sigmoid` then `mul`, TWO kernels with a - // bf16 buffer between them -- so the round trip is part of the arithmetic being - // replaced, and skipping it changes the model's output: the emitted text moves and - // the drafter's acceptance rate falls. + // The activation is rounded to bf16 before the multiply, unlike gated_quant_fp8: + // the unfused reference here is `sigmoid` then `mul` with a bf16 buffer between + // them (silu_mul_bf16 keeps f32). Skipping the round trip changes the output. const uint16_t ab = f2bf(ACT == 0 ? gv / (1.0f + expf(-gv)) : 1.0f / (1.0f + expf(-gv))); const uint16_t h = f2bf(bf2f(ab) * bf2f(xb[j])); @@ -326,59 +280,37 @@ __global__ __launch_bounds__(1024) void gate_quant_fp8_kernel( // -------------------------------------------------------- all-reduce -> rmsnorm -> quant // -// The same norm again, with the tensor-parallel all-reduce that always precedes it folded in. -// Every row-parallel linear's output is all-reduced and then immediately normalised -- o_proj, -// out_proj and down_proj, 128 of each on a 64-layer decode step, always adjacent and always in -// that order. The norm's own body is a small fraction of what the pair costs; the rest is a launch, -// a dispatch gap and a round trip through memory for a tensor that exists for one kernel. The int8 -// path carries the same fusion (r4d_ar_ln_had_quant_i8); this is the fp8 form of it, minus the -// rotation. +// The same norm with the tensor-parallel all-reduce that always precedes it folded in (o_proj, +// out_proj and down_proj outputs are all-reduced, then normalised). Saves a launch, a dispatch gap +// and a round trip through memory. The int8 path has the same fusion (r4d_ar_ln_had_quant_i8). // -// THE PARTITION IS BY ROW, for the reason that file gives at length: r4d_ar_oneshot_2rank_exact -// hands block b a contiguous chunk of 16B WORDS with an independent flag and no grid barrier -// anywhere, and a norm cannot use that partition because a sum of squares closes only over a whole -// row -- but rows are contiguous, so a contiguous range of ROWS is a contiguous range of words. -// Both ranks compute the same range from (M, gridDim.x), so the handshake stays per-block. +// Partitioned by row: r4d_ar_oneshot_2rank_exact gives block b a contiguous range of 16B words with +// its own flag and no grid barrier, but a sum of squares needs whole rows. Rows are contiguous, so a +// row range is a word range; both ranks derive it from (M, gridDim.x), keeping the handshake +// per block. // -// BIT-IDENTICAL TO THE PAIR IT REPLACES, and by construction rather than by inspection. Pass two -// is norm_quant_row above, the same code the standalone kernel runs. Pass one reproduces the -// all-reduce's own arithmetic exactly -- an f32 sum STORED AS BF16 (r4d_ar_oneshot_2rank_exact's -// vadd) and then read as the norm's input -- and stores it back into `x`, which is not bookkeeping: -// it is what the kernel this replaces wrote, so a reader of `x` that is not this norm still finds -// the same bytes. The column partition of the sum of squares is `i = tid; i += THR` on both, which -// is the agreement r4d_act_threads exists to keep. +// Bit-identical to the pair it replaces. Pass two is norm_quant_row. Pass one reproduces the +// all-reduce's arithmetic (an f32 sum stored as bf16, as in r4d_ar_oneshot_2rank_exact's vadd) and +// stores it back into `x`, as the replaced kernel did, so other readers of `x` see the same bytes. +// Both sum the squares in r4d_act_threads' `i = tid; i += THR` order. // -// BOTH WIRES ARE SERVED, and the compressed one is why this kernel is worth its size. Above -// --tp-wire-min-kb the message goes out 6-bit rotated, and that payload is worth more than the -// launch a fusion saves. A kernel that served only the exact wire would hand every message above -// the floor back to the standalone pair, and the fusion would run at one sequence and nowhere -// else -- which is the wrong band, because a step carries n_seq * (1 + n_spec) rows, so the message -// crosses the floor at the SECOND concurrent sequence and stays across it. Serving WIRE == 6 here -// is what lets the two wins compose. +// Both wires are served. Above --tp-wire-min-kb the message is sent 6-bit rotated; a step carries +// n_seq * (1 + n_spec) rows, so it crosses that floor from the second concurrent sequence on, and +// an exact-wire-only fusion would rarely apply. // -// The wire is r4d_ar_oneshot_2rank_wht6's format and arithmetic unchanged -- orthonormal -// Walsh-Hadamard over a group of 64, amax-scaled, 6 uniform bits plus a bf16 scale -- packed at a -// CHUNK of 512 elements instead of 2048. The chunk size is not numerics: the rotation and the amax -// close over a GROUP, and a group is 64 elements at either chunking, so the codes and the scales -// are the same bytes. What it decides is who owns what. A chunk may not straddle a row, or a -// block's rows would not be a whole number of chunks and the two ranks would disagree about which -// bytes a block owns; and a wave owns a whole chunk, so a smaller chunk puts more waves to work, -// which is why a chunk is 8 groups and not 32 (see r4d_ar_ln_had_quant_i8.hip). +// The compressed wire is r4d_ar_oneshot_2rank_wht6's format (orthonormal Walsh-Hadamard over 64, +// amax-scaled, 6 uniform bits plus a bf16 scale) packed in chunks of 512 elements instead of 2048. +// Rotation and amax close over a 64-element group, so the bytes are identical; the chunk size only +// sets ownership. A chunk may not straddle a row (both ranks must agree on a block's bytes), and a +// wave owns a whole chunk, so a smaller chunk employs more waves (see r4d_ar_ln_had_quant_i8.hip). // -// THE REDUCED ROW GOES BACK TO GLOBAL `x`, not to an LDS staging slice. The int8 twin stages it, -// because its norm needs the row again for a rotation it performs in place; this one does not -- -// pass two re-reads the row it just wrote, which is the same re-read the standalone norm does and -// the same L1-hot argument the top of this file makes. It costs a bf16 round trip that the int8 -// form avoids and buys back all of the LDS. +// The reduced row goes back to global `x`, not LDS: unlike the int8 twin this norm needs no +// in-place rotation, and pass two re-reads the row L1-hot as the standalone norm does. // -// AND THIS RANK'S OWN PACKED HALF GOES TO GLOBAL TOO, in the side buffer the standalone kernel -// already allocates (`loc_pack`), rather than to LDS. LDS cannot hold it, and the failure only a -// long enough prompt shows: LDS is 64 KiB and a row's packed half is ~4 KiB at n = 5120, so a block -// holds fifteen rows where a PREFILL chunk is two thousand. The launch is then refused with a shape -// error, which in this engine aborts the step and fails the requests in it. A bound that depends on -// the block count is not a bound this op gets to have: the same op serves M = 8 and -// M = 2048. The side buffer costs 0.75 bytes an element written and read straight back, which is -// under half a microsecond at decode width and stays in L2. +// This rank's own packed half also goes to global, in the standalone kernel's side buffer +// (`loc_pack`). LDS (64 KiB) holds only ~15 rows of ~4 KiB packed halves at n = 5120, while one op +// serves M = 8 through a 2048-row prefill chunk; a refused launch would abort the step. The side +// buffer costs 0.75 bytes per element, written and read back from L2. #define R4D_ARQ_SPIN_MAX 4000000000ULL #define ARQ_GROUP 64 @@ -396,8 +328,8 @@ __global__ __launch_bounds__(1024) void gate_quant_fp8_kernel( #define ARQ_QMIN (-(1 << (ARQ_BITS - 1))) #define ARQ_MASK ((1u << ARQ_BITS) - 1u) -// `lo ? (v + o) : (o - v)` written as `o + (lo ? v : -v)`: the sign flip is one XOR against a mask -// uniform over the stage, so the select disappears. Bit-identical -- IEEE negation is exact. +// `lo ? (v + o) : (o - v)` written as `o + (lo ? v : -v)`: the sign flip is one XOR with a mask +// uniform over the stage, removing the select. Bit-identical, since IEEE negation is exact. template __device__ __forceinline__ void arq_xstage(float* v, int lig) { const unsigned int sm = (lig & M) ? 0x80000000u : 0u; @@ -445,8 +377,8 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel( const uint32_t tid = threadIdx.x; /* Integer arithmetic only, so both ranks land on the same split. */ const int r0 = (int)(((long)b * M) / nb), r1 = (int)(((long)(b + 1) * M) / nb); - /* Chunks a row spans, and this block's window into the message's global chunk numbering. Both - * ranks derive them from the same (M, nb, n), so neither has to be told. */ + /* Chunks per row and this block's window into the global chunk numbering, derived identically + * on both ranks from (M, nb, n). */ const int cpr = WIRE ? (int)(n / ARQ_CE) : 0; const int c00 = r0 * cpr, cpb = (r1 - r0) * cpr; const uint32_t lane = tid & (ARQ_WV - 1), wave = tid / ARQ_WV; @@ -456,34 +388,31 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel( const unsigned int sq = s_seq; int4* const ps = peer_base + (size_t)s_slot * slot_stride16; const int4* const ms = my_base + (size_t)s_slot * slot_stride16; - /* The slot is split exactly as the standalone compressed all-reduce splits it: packed symbols - * from the base, bf16 group scales from half way up. Group indices are GLOBAL over the whole - * [M][n] message, so a block simply addresses the groups its rows cover. */ + /* The slot is split as in the standalone compressed all-reduce: packed symbols from the base, + * bf16 group scales from half way up. Group indices are global over the [M][n] message. */ char* const p_pay = (char*)ps; const char* const m_pay = (const char*)ms; unsigned short* const p_sc = (unsigned short*)((char*)ps + (size_t)(slot_stride16 >> 1) * 16); const unsigned short* const m_sc = (const unsigned short*)((const char*)ms + (size_t)(slot_stride16 >> 1) * 16); - /* This rank's own packed half, in the side buffer split exactly as the peer slot is: symbols - * from the base, scales from `loc_scale_off`. Indexed by the GLOBAL chunk and group number, so - * a block writes and reads only what its own rows cover and no two blocks overlap. */ + /* This rank's own packed half, laid out like the peer slot (symbols from the base, scales from + * `loc_scale_off`) and indexed by global chunk and group, so blocks never overlap. */ unsigned int* const Lpk = (unsigned int*)loc_pack; float* const Lsc = (float*)(loc_pack + loc_scale_off); 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. */ + /* 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]; } 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 ARQ_NWORD dwords a chunk and - * the flush is lane-uniform. No group is ever partial: n is a whole number of chunks and a - * block owns whole rows, so the `live` guard the standalone kernel needs is not needed - * here -- which is also why every cross-lane stage below is wholly active. */ + /* 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 + * partial (n is whole chunks, a block owns whole rows), so the standalone kernel's `live` + * guard is unnecessary and every cross-lane stage is fully active. */ for (int ci = (int)wave; ci < cpb; ci += (int)(THR / ARQ_WV)) { const int c = c00 + ci; unsigned int acc[ARQ_NWORD]; @@ -536,8 +465,7 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel( Lpk[((size_t)c * ARQ_NWORD + wi) * ARQ_WV + lane] = acc[wi]; } } - /* The drain modes are r4d_ar_oneshot_2rank_exact's, and the variant table picks between them - * for the same reasons; the kernel only has to honour them identically. */ + /* 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"); __syncthreads(); @@ -545,8 +473,8 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel( if (drain == 2) __threadfence_system(); arq_store_rel(&peer_flags[b], sq); unsigned long long z = 0; - /* A handshake that cannot complete is a lockstep violation: norming a slot the peer never - * filled would hand stale bytes on as a sum, so it traps instead. */ + /* A handshake that cannot complete is a lockstep violation; trap rather than sum a slot the + * peer never filled. */ while (r4d_ar_seq_behind(arq_load_acq(&my_flags[b]), sq)) { if (++z > R4D_ARQ_SPIN_MAX) __builtin_trap(); } @@ -555,10 +483,8 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel( if (acq) __threadfence_system(); if constexpr (WIRE == 6) { - /* REDUCE: unpack both halves of every chunk this block owns, add in fp32, inverse-rotate, - * and store the bf16 sum back into `x` -- which is what the standalone compressed - * all-reduce wrote, so pass two below reads the bytes it would have read and a reader of - * `x` that is not this norm still finds the same ones. */ + /* Reduce: unpack both halves of every chunk this block owns, add in fp32, inverse-rotate, + * and store the bf16 sum into `x`, as the standalone compressed all-reduce does. */ 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; @@ -593,9 +519,9 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel( psy |= pac[wi + 1] << (32 - bo); lsy |= lac[wi + 1] << (32 - bo); } - /* The two ranks fold the identical pair in OPPOSITE order; fp32 add commutes - * exactly, so they stay bit-identical as long as neither product is contracted - * into an FMA. libr4d/CMakeLists.txt passes -ffp-contract=off for exactly this. */ + /* The two ranks add the pair in opposite order; fp32 add commutes exactly, so + * they agree bit for bit as long as neither product is contracted into an FMA + * (libr4d/CMakeLists.txt passes -ffp-contract=off for this). */ v[i] = (float)((int)(psy & ARQ_MASK) + ARQ_QMIN) * psc + (float)((int)(lsy & ARQ_MASK) + ARQ_QMIN) * lsc; } @@ -605,12 +531,11 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel( for (int i = 0; i < ARQ_EPL; ++i) x[off + i] = f2bf(v[i]); } } - /* Pass two reads `x` across the whole row and a wave only wrote its own chunks of it. */ + /* Pass two reads all of `x`'s row; each wave wrote only its own chunks. */ __syncthreads(); } - /* The peer's rows are now in MY scratch, in the same [M][n] layout as x -- WIRE == 0 only; - * the compressed wire has already reduced into `x` above. */ + /* WIRE == 0: the peer's rows are now in this rank's scratch, in x's [M][n] layout. */ const uint16_t* __restrict__ P = (const uint16_t*)ms; for (int row = r0; row < r1; ++row) { @@ -622,8 +547,8 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel( (void)pr; float ss = 0.0f; for (uint32_t i = tid; i < n; i += THR) { - /* The exact wire reduces HERE, on the norm's own pass; the compressed one has already - * reduced into `x` and this reads what it stored. */ + /* The exact wire reduces here, in the norm's first pass; the compressed one already + * reduced into `x`. */ uint16_t a; if constexpr (WIRE == 0) { a = f2bf(bf2f(xr[i]) + bf2f(pr[i])); xr[i] = a; } else { a = xr[i]; } @@ -636,26 +561,24 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel( const float rs = rsqrtf(block_sum(ss, lds) / (float)n + eps); norm_quant_row(nr, w, y ? y + (size_t)row * y_ld : nullptr, q + (size_t)row * q_ld, s, (size_t)row * s_ld, n, nkb, rs, wadd); - /* lds is re-used by the next row this block owns, and a thread still reading it for this - * row would otherwise race the next row's write. The one-row-a-block kernel above never - * needed this barrier and that is the only structural difference between them. */ + /* lds is reused by this block's next row; without the barrier a thread still reading it + * would race the next row's write. */ __syncthreads(); } } } // namespace -// `w` is the norm gain, f32 when `w_f32` and bf16 otherwise -- every gain in this project's -// architecture plugins is declared f32, and the width is the caller's to state for the reason -// r4d_model_bf16's rmsnorm gives. `y` may be null on a layer with no bf16 consumer of the -// post-norm tensor; every caller in this tree has one, because the fp8a16 matvec reads it at M = 1. +// `w` is the norm gain, f32 when `w_f32` and bf16 otherwise (see r4d_model_bf16's rmsnorm). `y` +// may be null when nothing reads the bf16 post-norm tensor; every current caller has a reader (the +// fp8a16 matvec at M = 1). // -// `res`, when given, is the fused_add_rms_norm form: `res += x` in f32, ROUNDED TO BF16 and stored, -// and the norm is then taken of the stored value -- which is bit-for-bit the `add` + `rmsnorm` pair -// this replaces. Pass 0 for the plain form. It may alias `y`; see the note at the top of the file. +// `res`, when given, is the fused_add_rms_norm form: `res += x` in f32, rounded to bf16 and stored, +// and the norm is taken of the stored value, bit-identical to `add` + `rmsnorm`. Pass 0 for the +// plain form. It may alias `y`; see the note at the top of the file. // // x [M][n] bf16, `x_ld` elements a row (0 = n) -// res [M][n] bf16, `r_ld` elements a row (0 = n), optional, READ AND WRITTEN +// res [M][n] bf16, `r_ld` elements a row (0 = n), optional, read and written // w [n] f32 or bf16 // y [M][n] bf16, `y_ld` elements a row (0 = n), optional // q [M][n] E4M3, `q_ld` bytes a row (0 = n), rounded up to 4 @@ -673,16 +596,11 @@ extern "C" int r4d_rmsnorm_quant_fp8(long x, long res, long w, long y, long q, l const int nkb = (n + (int)kGroup - 1) / (int)kGroup; if (!s_ld) s_ld = nkb; - // ONE WORKGROUP A ROW, so at a decode batch the grid is 8-72 workgroups on a 64-CU part and - // the kernel is latency bound rather than bandwidth bound: it moves ~205 KiB, which is far less - // work than the ~2.6 us launch floor costs. Widening the workgroup is the only knob that adds - // parallelism without changing the algorithm. r4d_act_threads holds the crossover table, and - // the reasoning behind it is written out with it. + // One workgroup per row, so a decode batch is 8-72 workgroups and the kernel is latency bound; + // the workgroup width is the parallelism knob (crossover table in r4d_act_threads). // - // rmsnorm_bf16 PICKS THE SAME WIDTH FROM THE SAME FUNCTION, and it has to: the width decides - // which columns a thread accumulates into the sum of squares, so two kernels that disagree - // about it produce sums that differ in the last bits. This fusion is required to be - // byte-identical to the pair it replaces, which is exactly that agreement. + // rmsnorm_bf16 must pick the same width from the same function: the width decides which + // columns a thread sums, so a different width changes the last bits and breaks bit identity. const int thr = r4d_act_threads(M, n); #define R4D_RQ_T(wf, rs, T) \ hipLaunchKernelGGL((rmsnorm_quant_fp8_kernel), dim3((uint32_t)M), dim3(T), 0, \ @@ -701,20 +619,18 @@ extern "C" int r4d_rmsnorm_quant_fp8(long x, long res, long w, long y, long q, l return hipGetLastError() == hipSuccess ? 0 : -4; } -// `mode` is 0 for silu (down_proj's input) and 1 for sigmoid (a gated attention o_proj's), the same -// spelling r4d_gated_had_quant_i8 takes. +// `mode` is 0 for silu (down_proj's input) and 1 for sigmoid (a gated attention o_proj's), as in +// r4d_gated_had_quant_i8. // // gu [M][2n] bf16, gate first then up, `gu_ld` elements a row (0 = 2n) // y [M][n] bf16, `y_ld` elements a row (0 = n), optional // q [M][n] E4M3 (int8 when `i8`), `q_ld` bytes a row (0 = n), rounded up to 4 // s [M][ceil(n/128)] f32, `s_ld` elements a row (0 = ceil(n/128)) // -// `rot` is a STRICTER call, not a flag on the same one: a ragged last group is legal unrotated -// (it is written zero-padded and the GEMM's bounds guard stops the padding reaching anything) and -// is not legal rotated, because a butterfly that mixed real values with padding has no matching -// weight block on the other side. +// `rot` additionally requires n % 128 == 0: a ragged last group is fine unrotated (zero-padded, +// masked by the GEMM) but a butterfly mixing real values with padding has no matching weight block. static int gated_quant_fp8_launch(long gu, long y, long q, long s, int M, int n, int mode, - int gu_ld, int y_ld, int q_ld, int s_ld, const R4dSink& sk, + int gu_ld, int y_ld, int q_ld, int s_ld, RadStream stream, bool rot, bool i8 = false) { int emit_rc = RAD_OK; if (!gu || !q || !s) return -1; @@ -729,13 +645,12 @@ static int gated_quant_fp8_launch(long gu, long y, long q, long s, int M, int n, if (!q_ld) q_ld = n; const int nkb = (n + (int)kGroup - 1) / (int)kGroup; if (!s_ld) s_ld = nkb; - // A wave a group, capped at r4d_act_threads' width; see the kernel. There is no cross-row - // reduction here, so the width changes nothing numerically -- only how many waves share the - // groups. The ROTATION is wave-local too (r4d_fwht.h), so that stays true with it. + // One wave per group, capped at r4d_act_threads' width. The width does not affect the numerics: + // there is no cross-row reduction and the rotation is wave-local (r4d_fwht.h). const int thr = std::min(nkb, r4d_act_threads(M, n) / (int)kWave) * (int)kWave; #define R4D_GQ_R(a, R, I) \ - emit_rc = R4D_EMIT(sk, (gated_quant_fp8_kernel), dim3((uint32_t)M), dim3(thr), 0, \ - (const uint16_t*)gu, (uint16_t*)y, (uint8_t*)q, \ + emit_rc = R4D_EMIT(stream, (gated_quant_fp8_kernel), dim3((uint32_t)M), dim3(thr), \ + 0, (const uint16_t*)gu, (uint16_t*)y, (uint8_t*)q, \ (float*)s, (uint32_t)n, (uint32_t)nkb, (uint32_t)gu_ld, (uint32_t)y_ld, \ (uint32_t)q_ld, (uint32_t)s_ld) #define R4D_GQ(a) \ @@ -747,25 +662,24 @@ static int gated_quant_fp8_launch(long gu, long y, long q, long s, int M, int n, #undef R4D_GQ #undef R4D_GQ_R if (emit_rc != RAD_OK) return -4; - return (!sk.desc && hipGetLastError() != hipSuccess) ? -4 : 0; + return (hipGetLastError() != hipSuccess) ? -4 : 0; } extern "C" int r4d_gated_quant_fp8(long gu, long y, long q, long s, int M, int n, int mode, int gu_ld, int y_ld, int q_ld, int s_ld, long stream) { return gated_quant_fp8_launch(gu, y, q, s, M, n, mode, gu_ld, y_ld, q_ld, s_ld, - r4d_stream_sink((RadStream)(uintptr_t)stream), false); + (RadStream)(uintptr_t)stream, false); } extern "C" int r4d_gated_had_quant_fp8(long gu, long y, long q, long s, int M, int n, int mode, int gu_ld, int y_ld, int q_ld, int s_ld, long stream) { return gated_quant_fp8_launch(gu, y, q, s, M, n, mode, gu_ld, y_ld, q_ld, s_ld, - r4d_stream_sink((RadStream)(uintptr_t)stream), true); + (RadStream)(uintptr_t)stream, true); } -// act . x, with the gate and the thing it scales in DIFFERENT buffers -- see the kernel above for -// why the row is a (token, head) pair. `mode` is spelled as r4d_gated_quant_fp8 spells it. The -// activation is ROUNDED TO BF16 before the product, because the pair this replaces is two kernels -// with a bf16 buffer between them -- unlike r4d_gated_quant_fp8, whose reference is one. +// act . x with the gate and x in separate buffers; see the kernel for why a row is a (token, head) +// pair and why the activation is rounded to bf16 before the product. `mode` as in +// r4d_gated_quant_fp8. // // g [M][.] bf16, `g_ld` elements a row; the gate starts at element 0 of the row, // so a caller with a [q|gate] projection passes g already offset @@ -775,7 +689,7 @@ extern "C" int r4d_gated_had_quant_fp8(long gu, long y, long q, long s, int M, i // s [M][ceil(n/128)] f32, `s_ld` elements a row (0 = ceil(n/128)) static int gate_quant_fp8_emit(long g, long x, long y, long q, long s, int M, int n, int mode, int g_ld, int x_ld, int y_ld, int q_ld, int s_ld, - const R4dSink& sk, bool i8 = false) { + RadStream stream, bool i8 = false) { int emit_rc = RAD_OK; if (!g || !x || !q || !s) return -1; if (M <= 0 || n <= 0) return -2; @@ -790,7 +704,7 @@ static int gate_quant_fp8_emit(long g, long x, long y, long q, long s, int M, in // A wave a group, capped at r4d_act_threads' width, as gated_quant_fp8 above. const int thr = std::min(nkb, r4d_act_threads(M, n) / (int)kWave) * (int)kWave; #define R4D_GTQ_I(a, I) \ - emit_rc = R4D_EMIT(sk, (gate_quant_fp8_kernel), dim3((uint32_t)M), dim3(thr), 0, \ + emit_rc = R4D_EMIT(stream, (gate_quant_fp8_kernel), dim3((uint32_t)M), dim3(thr), 0, \ (const uint16_t*)g, (const uint16_t*)x, \ (uint16_t*)y, (uint8_t*)q, (float*)s, (uint32_t)n, (uint32_t)nkb, \ (uint32_t)g_ld, (uint32_t)x_ld, (uint32_t)y_ld, (uint32_t)q_ld, \ @@ -801,27 +715,24 @@ static int gate_quant_fp8_emit(long g, long x, long y, long q, long s, int M, in #undef R4D_GTQ #undef R4D_GTQ_I if (emit_rc != RAD_OK) return -4; - return (!sk.desc && hipGetLastError() != hipSuccess) ? -4 : 0; + return (hipGetLastError() != hipSuccess) ? -4 : 0; } extern "C" int r4d_gate_quant_fp8(long g, long x, long y, long q, long s, int M, int n, int mode, int g_ld, int x_ld, int y_ld, int q_ld, int s_ld, long stream) { - R4dSink sk; sk.stream = (RadStream)(uintptr_t)stream; - return gate_quant_fp8_emit(g, x, y, q, s, M, n, mode, g_ld, x_ld, y_ld, q_ld, s_ld, sk); + return gate_quant_fp8_emit(g, x, y, q, s, M, n, mode, g_ld, x_ld, y_ld, q_ld, s_ld, + (RadStream)(uintptr_t)stream); } -// The fused all-reduce. The IPC arguments are r4d_ar_oneshot_2rank_exact's -- the same -// double-buffered scratch, per-block flags and device-resident sequence counters -- and everything -// after them is r4d_rmsnorm_quant_fp8's, with two differences the caller has to know about: +// The fused all-reduce. The IPC arguments are r4d_ar_oneshot_2rank_exact's (double-buffered +// scratch, per-block flags, device-resident sequence counters); the rest are r4d_rmsnorm_quant_fp8's, +// except: // -// * `x` HAS NO PITCH. It is the all-reduce's message as well as the norm's input, and a block -// pushes its rows as a range of 16B words; a pitched x would make the two ranks disagree about -// which bytes a block owns. Refused rather than silently strided. -// * `nblocks` IS CLAMPED TO M, because a block owns whole rows. At a decode batch that is 8 to -// 64 blocks, which is the range the standalone all-reduce asks for anyway. +// * `x` has no pitch: it is also the all-reduce message, pushed as a range of 16B words, and a +// pitch would make the ranks disagree about a block's bytes. +// * `nblocks` is clamped to M, since a block owns whole rows. // -// `res` is the fused_add_rms_norm form and behaves exactly as it does there. Returns 0, or a -// negative code for a shape it does not serve. +// `res` behaves as in r4d_rmsnorm_quant_fp8. Returns 0, or a negative code for an unserved shape. extern "C" int r4d_ar_rmsnorm_quant_fp8_chunk_elems(void) { return ARQ_CE; } extern "C" int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long peer_flags, @@ -834,11 +745,11 @@ extern "C" int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long if (!x || !w || !q || !s) return -1; if (!peer_scratch || !my_scratch || !peer_flags || !my_flags || !seq_ctrs) return -1; if (M <= 0 || n <= 0) return -2; - if (n % 4) return -3; // a lane owns four columns; see norm_quant_row - if (n % 8) return -5; // n bf16 is a whole number of 16B words; see the push + // n % 8: n bf16 is a whole number of 16B words (see the push), which also gives every lane its + // four columns (see norm_quant_row). + if (n % 8) return -5; if (wire != 0 && wire != 6) return -7; - // A chunk may not straddle a row, or a block's rows would not be a whole number of chunks and - // the two ranks would disagree about which bytes a block owns. + // A chunk may not straddle a row, or the ranks would disagree about a block's bytes. if (wire == 6 && (n % ARQ_CE)) return -8; if (wire == 6 && (!loc_pack || loc_scale_off <= 0)) return -9; if (!r_ld) r_ld = n; @@ -851,9 +762,7 @@ extern "C" int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long if (nb > M) nb = M; const int nbw = r4d_ar_max_blocks(); // the counter capacity; see r4d_ar_seq.h if (nb > nbw) nb = nbw; - // The width is r4d_act_threads for the reason the standalone norm gives: it decides which - // columns a thread accumulates into the sum of squares, so a fused kernel that picked a - // different one would produce a different sum in the last bits and a different token stream. + // The width must be r4d_act_threads', as for the standalone norm (it fixes the summation order). const int thr = nthreads ? nthreads : r4d_act_threads(M, n); if (thr != 256 && thr != 512 && thr != 1024) return -6; #define R4D_ARQ_T(wf, rs, T, W) \ @@ -882,14 +791,11 @@ extern "C" int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long // ============================================================== the plugin ABI entry points // -// The shared operand reader is r4d_fp8_args.h. See libr4d/r4d_args.h for why there is no adapter -// directory between the core and these launches. +// The shared operand reader is r4d_fp8_args.h; see libr4d/r4d_args.h. /* ================================================================== the two fused quantisers * - * The shape rules are the standalone quantiser's, applied to the operand that PRODUCES the row - * rather than to the row itself, plus the one thing the fusion adds: the bf16 output is optional - * because a layer with no bf16 consumer of the post-norm tensor should not pay for the store, and - * every caller in this tree has one anyway (the fp8a16 matvec reads it at M = 1). */ + * The standalone quantiser's shape rules, applied to the operand that produces the row. The bf16 + * output is optional so a layer without a bf16 consumer skips the store. */ extern "C" int r4d_rad_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) { const RadTensor* x = r4d_opt(a, RQ_X); @@ -899,9 +805,9 @@ extern "C" int r4d_rad_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) { const RadTensor* sc = r4d_opt(a, RQ_S); const RadTensor* y = r4d_opt(a, RQ_Y); if (!x || !w || !q || !sc) return R4D_NO(RAD_E_INVAL); - /* Rank 2 on the input too, unlike the standalone quantiser: a norm has a gain per channel, so - * "everything after dim 0 is the row" would put one gain across several heads. The GDN block's - * rank-3 activation is quantised by the standalone op, and its gated norm by its own kernel. */ + if (q->dtype != RAD_F8E4M3) return R4D_NO(RAD_E_DTYPE); + /* Rank 2 on the input too, unlike the standalone quantiser: a norm has one gain per channel, + * and folding trailing dims would spread a gain across heads. */ if (x->rank != 2 || q->rank != 2 || sc->rank != 2) return R4D_NO(RAD_E_SHAPE); if (y && y->rank != 2) return R4D_NO(RAD_E_SHAPE); const long long M = x->shape[0], K = x->shape[1]; @@ -913,9 +819,8 @@ extern "C" int r4d_rad_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) { if (q->shape[0] != M || q->shape[1] != K) return R4D_NO(RAD_E_SHAPE); if (sc->shape[0] != M || sc->shape[1] != nkb) return R4D_NO(RAD_E_SHAPE); if (y && (y->shape[0] != M || y->shape[1] != K)) return R4D_NO(RAD_E_SHAPE); - /* The residual is the same extent as the input and is READ AND WRITTEN. It is allowed to alias - * `out_bf16` -- every caller in this tree makes it do so -- which is safe because pass one - * reads all of `x` before the kernel's only barrier and pass two writes `y` after it. */ + /* The residual has the input's extent and is read and written. It may alias `out_bf16` (see + * the note at the top of the file). */ if (rs && (rs->rank != 2 || rs->shape[0] != M || rs->shape[1] != K)) return R4D_NO(RAD_E_SHAPE); const long long xp = r4d_row_pitch(x), qp = r4d_row_pitch(q), sp = r4d_row_pitch(sc); const long long yp = y ? r4d_row_pitch(y) : 0, rp = rs ? r4d_row_pitch(rs) : 0; @@ -929,7 +834,17 @@ extern "C" int r4d_rad_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) { return e == 0 ? RAD_OK : RAD_E_SHAPE; } -static int rad_gated_quant_fp8(const RadArgs* a, const R4dSink& sk, bool rot) { +/* The gate's activation: `act` by name overrides `mode` (libr4d's integer: 0 silu, 1 sigmoid) when + * both are given, as for r4d_gated_had_quant_i8. Returns -1 for an unknown name. */ +static int act_mode(const RadArgs* a, int dflt) { + const char* act = r4d_gets(a, "act"); + if (!act) return (int)r4d_geti_or(a, "mode", dflt); + if (!std::strcmp(act, "silu")) return 0; + if (!std::strcmp(act, "sigmoid")) return 1; + return -1; +} + +static int rad_gated_quant_fp8(const RadArgs* a, RadStream stream, bool rot) { const RadTensor* gu = r4d_opt(a, GQ_GU); const RadTensor* q = r4d_opt(a, GQ_Q); const RadTensor* sc = r4d_opt(a, GQ_S); @@ -944,8 +859,7 @@ static int rad_gated_quant_fp8(const RadArgs* a, const R4dSink& sk, bool rot) { const long long grp = r4d_quant_act_fp8_group(); const long long nkb = (K + grp - 1) / grp; if (r4d_geti_or(a, "group", grp) != grp) return R4D_NO(RAD_E_SHAPE); - /* The gated operand is [M][2K] and the halves are gate then up -- one buffer, because that is - * how the fused gate_up projection writes it and splitting would be a copy. */ + /* The gated operand is [M][2K], gate then up, as the fused gate_up projection writes it. */ if (gu->shape[1] != 2 * K) return R4D_NO(RAD_E_SHAPE); if (q->shape[0] != M) return R4D_NO(RAD_E_SHAPE); if (sc->shape[0] != M || sc->shape[1] != nkb) return R4D_NO(RAD_E_SHAPE); @@ -953,60 +867,45 @@ static int rad_gated_quant_fp8(const RadArgs* a, const R4dSink& sk, bool rot) { const long long gp = r4d_row_pitch(gu), qp = r4d_row_pitch(q), sp = r4d_row_pitch(sc); const long long yp = y ? r4d_row_pitch(y) : 0; if (gp < 0 || qp < 0 || sp < 0 || yp < 0) return R4D_NO(RAD_E_STRIDE); - /* `act` is the vocabulary's name and `mode` is libr4d's integer spelling of the same choice; - * `act` wins where both are given, which is what r4d_gated_had_quant_i8's row promises. */ - const char* act = r4d_gets(a, "act"); - int mode = (int)r4d_geti_or(a, "mode", 0); - if (act) { - if (!std::strcmp(act, "silu")) mode = 0; - else if (!std::strcmp(act, "sigmoid")) mode = 1; - else return R4D_NO(RAD_E_UNSUPPORTED); - } + const int mode = act_mode(a, 0); /* silu: the gated MLP */ + if (mode < 0) return R4D_NO(RAD_E_UNSUPPORTED); const int e = gated_quant_fp8_launch(r4d_addr(gu), y ? r4d_addr(y) : 0, r4d_addr(q), r4d_addr(sc), (int)M, (int)K, mode, (int)gp, (int)yp, - (int)qp, (int)sp, sk, rot, q->dtype == RAD_I8); + (int)qp, (int)sp, stream, rot, q->dtype == RAD_I8); return e == 0 ? RAD_OK : RAD_E_SHAPE; } -static int rad_gated_quant_fp8_body(const RadArgs* a, const R4dSink& sk) { - return rad_gated_quant_fp8(a, sk, false); +extern "C" int r4d_rad_gated_quant_fp8(const RadArgs* a, RadStream stream) { + return rad_gated_quant_fp8(a, stream, false); } -R4D_ENTRY(r4d_rad_gated_quant_fp8, rad_gated_quant_fp8_body) -/* THE ROTATED FORM, a different op for the same reason had_quant_act_fp8 is: the codes it writes - * are not the codes the other one writes, so a graph with one substituted for the other is a - * different model that still runs and still answers. It pairs with a down-projection weight - * stored at dtype w4a8h and with nothing else. */ -static int rad_gated_had_quant_fp8_body(const RadArgs* a, const R4dSink& sk) { - return rad_gated_quant_fp8(a, sk, true); +/* The rotated form is a separate op for the same reason as had_quant_act_fp8 (different codes in + * the same shape). It pairs only with a down-projection weight stored at dtype w4a8h. */ +extern "C" int r4d_rad_gated_had_quant_fp8(const RadArgs* a, RadStream stream) { + return rad_gated_quant_fp8(a, stream, true); } -R4D_ENTRY(r4d_rad_gated_had_quant_fp8, rad_gated_had_quant_fp8_body) -/* Elements between consecutive `width`-wide rows, the same rule r4d_gdn.cpp's gn_row_pitch uses: - * a [.., heads, width] operand steps a row with the stride of the axis above the last, and a - * flattened one is contiguous and steps by `width`. It is the only way to read a column view of - * an interleaved projection, which is what a gated attention's gate is. */ +/* Elements between consecutive `width`-wide rows, as r4d_gdn.cpp's gn_row_pitch: a + * [.., heads, width] operand steps by the stride of the second-to-last axis; a flattened one is + * contiguous and steps by `width`. This reads a column view of an interleaved projection (a gated + * attention's gate). */ static long long tq_pitch(const RadTensor* t, long long width) { if (!t || t->rank < 1) return -1; if (t->shape[t->rank - 1] != width) return r4d_contig(t) ? width : -1; if (t->stride[t->rank - 1] != 1) return -1; if (t->rank == 1) return width; - /* AND THE ROWS HAVE TO BE UNIFORMLY THAT FAR APART, which the width test alone does not say. - * A [T, n_head, head_dim] column view of the [q|gate] projection flattens to T * n_head rows - * only if T's stride is exactly n_head of them -- true here, because the narrowing shrank the - * last axis and left every stride alone, and false for anything that also sliced an axis - * above it. Refusing is the only safe answer: a wrong pitch reads the next head's gate. */ + /* Rows must also be uniformly spaced: a [T, n_head, head_dim] column view flattens to + * T * n_head rows only if T's stride is n_head of them, which fails if an outer axis was also + * sliced. Refuse otherwise; a wrong pitch would read the next head's gate. */ for (int i = (int)t->rank - 2; i >= 1; --i) if (t->stride[i - 1] != t->shape[i] * t->stride[i]) return -1; return t->stride[t->rank - 2]; } -/* THE SAME EPILOGUE WITH THE GATE SOMEWHERE ELSE. A gated attention's output gate is not packed - * beside the thing it scales -- `x` is the attention output [M][n] and the gate is a COLUMN SLICE - * of the [q|gate] projection -- so this takes two operands where gated_quant_fp8 takes one. The - * caller narrows the gate to its own columns with a column view and the shim reads the offset off - * the tensor, which is why there is no `gate_offset` parameter. */ -static int rad_gate_quant_fp8_body(const RadArgs* a, const R4dSink& sk) { +/* Two-operand form of gated_quant_fp8 for gated attention: `x` is the attention output and the + * gate a column view of the [q|gate] projection. The gate offset comes from the view, so there is + * no `gate_offset` parameter. */ +extern "C" int r4d_rad_gate_quant_fp8(const RadArgs* a, RadStream stream) { const RadTensor* g = r4d_opt(a, TQ_G); const RadTensor* x = r4d_opt(a, TQ_X); const RadTensor* q = r4d_opt(a, TQ_Q); @@ -1014,12 +913,8 @@ static int rad_gate_quant_fp8_body(const RadArgs* a, const R4dSink& sk) { const RadTensor* y = r4d_opt(a, TQ_Y); if (!g || !x || !q || !sc) return R4D_NO(RAD_E_INVAL); if (q->dtype != RAD_F8E4M3 && q->dtype != RAD_I8) return R4D_NO(RAD_E_DTYPE); - /* M IS COUNTED OFF `x`, NOT READ OUT OF THE PARAMETERS. `M` is the row's RANGED parameter, so - * what arrives here is the band's declared maximum and not the issue -- a shim that trusts it - * refuses every real step. And shape[0] is no better: the row here is a (token, head) pair and - * neither operand spells it that way, the gate being a [T, n_head, head_dim] column view of - * the [q|gate] projection and x a flat [T, n_head * head_dim]. The element count over the - * known width is the one reading both agree on. */ + /* M is numel(x) / n. The `M` parameter is the band's declared maximum, not this issue's, and + * shape[0] counts tokens while a row here is a (token, head) pair. */ const long long K = r4d_geti_or(a, "n", 0); const long long grp = r4d_quant_act_fp8_group(); if (K <= 0 || r4d_numel(x) % K) return R4D_NO(RAD_E_SHAPE); @@ -1034,18 +929,12 @@ static int rad_gate_quant_fp8_body(const RadArgs* a, const R4dSink& sk) { const long long qp = tq_pitch(q, K), sp = tq_pitch(sc, nkb); const long long yp = y ? tq_pitch(y, K) : 0; if (gp < 0 || xp < 0 || qp < 0 || sp < 0 || yp < 0) return R4D_NO(RAD_E_STRIDE); - const char* act = r4d_gets(a, "act"); - int mode = (int)r4d_geti_or(a, "mode", 1); - if (act) { - if (!std::strcmp(act, "silu")) mode = 0; - else if (!std::strcmp(act, "sigmoid")) mode = 1; - else return R4D_NO(RAD_E_UNSUPPORTED); - } + const int mode = act_mode(a, 1); /* sigmoid: gated attention */ + if (mode < 0) return R4D_NO(RAD_E_UNSUPPORTED); const int e = gate_quant_fp8_emit(r4d_addr(g), r4d_addr(x), y ? r4d_addr(y) : 0, r4d_addr(q), r4d_addr(sc), (int)M, (int)K, mode, - (int)gp, (int)xp, (int)yp, (int)qp, (int)sp, sk, + (int)gp, (int)xp, (int)yp, (int)qp, (int)sp, stream, q->dtype == RAD_I8); return e == 0 ? RAD_OK : RAD_E_SHAPE; } -R4D_ENTRY(r4d_rad_gate_quant_fp8, rad_gate_quant_fp8_body) diff --git a/libr4d/r4d_fwht.h b/libr4d/r4d_fwht.h index a0a684f0..047be7f7 100644 --- a/libr4d/r4d_fwht.h +++ b/libr4d/r4d_fwht.h @@ -1,30 +1,25 @@ -// r4d_fwht.h - a wave-local fast Walsh-Hadamard transform, in registers, with no LDS and no barrier. +// r4d_fwht.h - a wave-local fast Walsh-Hadamard transform in registers, with no LDS and no barrier. // -// WHY IT IS IN REGISTERS. Staging the row in LDS and running the butterfly there costs seven -// stages, each a read-modify-write of every element plus a __syncthreads() -- roughly 28 LDS -// operations and 7 barriers per element. The transform's own ARITHMETIC is a fraction of a percent -// of a rotated quantiser; the LDS traffic and the barriers around it are what a butterfly staged in -// LDS actually costs, and they are several times the rest of the kernel. None of that is the -// transform, so none of it is paid here. +// A butterfly staged in LDS costs seven stages, each a read-modify-write of every element plus a +// __syncthreads() (about 28 LDS operations and 7 barriers per element), several times the rest of +// a rotated quantiser; the transform's arithmetic is a fraction of a percent. // -// THE MAPPING. Give one wave a `HAD`-wide block, VPL = HAD/32 contiguous values per lane, so lane l -// holds indices l*VPL .. l*VPL+VPL-1. A butterfly at stride h pairs index i with i+h: +// Mapping: one wave holds a `HAD`-wide block, VPL = HAD/32 contiguous values per lane, so lane l +// holds indices l*VPL .. l*VPL+VPL-1. A butterfly at stride h pairs index i with i+h: // -// h < VPL both indices are in the SAME lane -- plain register arithmetic, no communication -// h >= VPL the partner is lane l + h/VPL -- one lane exchange with mask h/VPL +// h < VPL both indices in the same lane -- plain register arithmetic +// h >= VPL the partner is lane l + h/VPL -- one lane exchange with mask h/VPL // -// Since HAD/VPL is always 32, the cross-lane masks are exactly 1, 2, 4, 8, 16 whatever HAD is: five -// exchanges per register (r4d_xor_lane, DPP rather than LDS) and no barrier at any width. The lane holding the LOW index of a pair keeps -// (v + partner) and the high one keeps (partner - v), which is the same butterfly written twice. -// -// The caller still needs one barrier before a whole-row reduction, but ONE, not seven. +// HAD/VPL is always 32, so the cross-lane masks are 1, 2, 4, 8, 16 at any HAD: five exchanges per +// register (r4d_xor_lane, DPP) and no barrier. The lane holding the low index keeps (v + partner), +// the high one (partner - v). The caller still needs one barrier before a whole-row reduction. #pragma once #include #include "r4d_common.h" -// `hi ? (o - v) : (v + o)` written as `o + (hi ? -v : v)`: the sign flip is one XOR against a mask -// that is uniform over the stage, so the per-element select disappears. Bit-identical -- IEEE -// negation is exact and addition commutes. +// `hi ? (o - v) : (v + o)` written as `o + (hi ? -v : v)`, with the sign flip one XOR against a +// stage-uniform mask, so there is no per-element select. Bit-identical: negation is exact and +// addition commutes. template __device__ __forceinline__ void r4d_fwht_xstage(float* v, int lane) { const unsigned int sm = (lane & MASK) ? 0x80000000u : 0u; diff --git a/libr4d/r4d_gated_had_quant_i8.hip b/libr4d/r4d_gated_had_quant_i8.hip index ed2a8289..a1826eb4 100644 --- a/libr4d/r4d_gated_had_quant_i8.hip +++ b/libr4d/r4d_gated_had_quant_i8.hip @@ -1,33 +1,28 @@ -// r4d_gated_had_quant_i8.hip - r4d_gated_had_quant_i8: an elementwise GATED product, then the block +// r4d_gated_had_quant_i8.hip - r4d_gated_had_quant_i8: an elementwise gated product, then the block // Hadamard, then the per-row int8 quantiser, in one pass. // -// TWO OF THE FOUR ROTATED SITES HAVE THIS SHAPE, and they differ by one multiply: +// Two of the four rotated sites have this shape and differ by one multiply: // -// MODE 0, down_proj's input silu(a) * b = a * sigmoid(a) * b (vLLM's silu_and_mul) -// MODE 1, o_proj's input sigmoid(a) * b (Qwen3_5Attention does +// mode 0, down_proj's input silu(a) * b = a * sigmoid(a) * b (vLLM's silu_and_mul) +// mode 1, o_proj's input sigmoid(a) * b (Qwen3_5Attention does // attn_output * sigmoid(gate)) // // so one kernel serves the MLP of all 64 layers and the attention output of the 16 full-attention -// ones. The 48 linear-attention layers reach out_proj through a gated RMSNorm instead and need -// their own variant. +// ones. The 48 linear-attention layers reach out_proj through a gated RMSNorm instead. // -// Mode 0 is the WIDEST of the four and the one the rotation width is decided by. An intermediate of -// 17408 at TP=2 leaves each rank 8704 = 2^9 * 17 -- so 512 is the largest power of two that tiles -// it and 1024 is not available anywhere in the model, because a rotation block cannot straddle a -// shard boundary. Between 128 and 512 the activation's quantisation error moves by far less than -// the weight error that dominates both, so the width is chosen on cost. +// Mode 0 is the widest site and sets the rotation width. An intermediate of 17408 at TP=2 leaves +// 8704 = 2^9 * 17 per rank, so 512 is the largest power of two that tiles it (a rotation block +// cannot straddle a shard boundary). Between 128 and 512 the activation's quantisation error moves +// far less than the dominant weight error, so the width is chosen on cost. // -// GATE AND UP ARRIVE AS SEPARATE TENSORS. vLLM fuses gate_proj and up_proj into one gate_up -// projection and then splits it, so the two halves are either two tensors or two halves of one with -// a row pitch of 2*K. `up` may alias `gate + K` for the fused layout; pass the pointers and the -// stride and the kernel does not care which. +// Gate and up arrive as two tensors, or as two halves of vLLM's fused gate_up with a row pitch of +// 2*K (`up` aliasing `gate + K`); the kernel takes pointers and strides either way. // -// The transform is in registers (r4d_fwht.h), so this is ONE pass: read gate and up, silu-multiply, +// The transform is in registers (r4d_fwht.h), so this is one pass: read gate and up, multiply, // rotate inside the wave, stage once for the row absmax. // -// silu(x) = x * sigmoid(x) is computed in fp32. Doing it in bf16 would cost more than the -// quantiser that follows: the product feeds a rotation, which mixes 128 values, so a rounding error -// in one lands on all 128. +// silu is computed in fp32: the product feeds a rotation that mixes 128 values, so a bf16 rounding +// error in one lands on all of them. #include "r4d.h" #include "r4d_args.h" #include "r4d_common.h" @@ -35,19 +30,12 @@ #include #include #include -#include - -// 0 = choose the workgroup width from M at launch (see r4d_act_threads in r4d_common.h); a -// non-zero build-time value pins one width for every M. -#ifndef R4D_GHQ_THREADS -#define R4D_GHQ_THREADS 0 -#endif template __global__ __launch_bounds__(THR) void r4d_gated_had_quant_i8_kernel( const __hip_bfloat16* __restrict__ G, const __hip_bfloat16* __restrict__ U, signed char* __restrict__ Q, float* __restrict__ S, - int K, long gstride, long ustride, float rnorm, float clip) { + int K, long gstride, long ustride, float rnorm) { constexpr int VPL = HAD / 32, NW = THR / 32; extern __shared__ float lds[]; float* red = lds + K; @@ -79,11 +67,7 @@ __global__ __launch_bounds__(THR) void r4d_gated_had_quant_i8_kernel( m = red[0]; #pragma unroll for (int i = 1; i < NW; i++) m = fmaxf(m, red[i]); - // CLIPPED ABSMAX. The row scale is set by the single largest rotated value in 8704 channels, - // so one outlier costs every other channel a bit of resolution. clip < 1 trades a few saturated - // channels for a finer grid on the rest; the saturate below is what makes it safe, and clip = 1 - // is the unclipped quantiser byte for byte. - m = fmaxf(m, 1e-8f) * clip; + m = fmaxf(m, 1e-8f); const float inv = 127.f / m; if (threadIdx.x == 0) S[row] = m * rnorm / 127.f; @@ -96,25 +80,11 @@ __global__ __launch_bounds__(THR) void r4d_gated_had_quant_i8_kernel( } } -// R4D_CLIP_MLP_DOWN / R4D_CLIP_ATTN_OUT: one clip factor per site this kernel serves. They are -// separate because the two distributions are -- a SwiGLU product and a sigmoid-gated attention -// output. Read once and cached; unset or out of (0, 1] means the unclipped absmax. -static float r4d_gated_act_clip(int mode) { - static float cached[2] = {-1.f, -1.f}; - if (cached[mode] < 0.f) { - const char* v = getenv(mode == 0 ? "R4D_CLIP_MLP_DOWN" : "R4D_CLIP_ATTN_OUT"); - const float f = v ? (float)atof(v) : 1.f; - cached[mode] = (f > 0.f && f <= 1.f) ? f : 1.f; - } - return cached[mode]; -} - // The launch, as the plugin ABI's RadLaunchFn. See the note at the head of r4d_quant_act_i8.hip. // -// THE SECOND OPERAND MAY BE ABSENT, and that is the packed gate_up form: `b` missing means the two -// halves are one [M, 2n] tensor and `b` is `a + n`, which is vLLM's layout and the one the MLP -// actually produces -- so both row pitches are 2n and the second pointer is computed rather than -// passed. bf16 is two bytes an element, and the row's dtype constraint is what guarantees that. +// A missing second operand is the packed gate_up form: one [M, 2n] tensor with `b` = `a + n` +// (vLLM's layout and what the MLP produces), so both row pitches are 2n. The row's dtype +// constraint guarantees bf16. enum { GH_A = 0, GH_B, GH_Q, GH_S }; extern "C" int r4d_rad_gated_had_quant_i8(const RadArgs* args, RadStream stream) { @@ -152,29 +122,25 @@ extern "C" int r4d_rad_gated_had_quant_i8(const RadArgs* args, RadStream stream) const long long had = r4d_geti_or(args, "group", 0); if (had != 128 && had != 256 && had != 512) return R4D_NO(RAD_E_SHAPE); - // A rotation block cannot straddle a tensor-parallel shard boundary; down_proj's input is 8704 - // per rank, so 512 is the widest available and 1024 is not. + // A rotation block cannot straddle a tensor-parallel shard; down_proj's input is 8704 per rank, + // so 512 is the widest available. if (K % had) return R4D_NO(RAD_E_SHAPE); if (K % 16) return R4D_NO(RAD_E_SHAPE); - // `act` is the vocabulary's name -- "silu" or "sigmoid" -- and `mode` is this kernel's integer - // for the same choice. The mapping happens here and nowhere else; the caller names the - // activation. + // `act` names the activation ("silu" or "sigmoid"); `mode` is this kernel's integer for it. const int mode = r4d_act_code(args, "act", "mode", 0); if (mode != 0 && mode != 1) return R4D_NO(RAD_E_INVAL); if (r4d_numel(q) != M * K) return R4D_NO(RAD_E_SHAPE); - const int thr = R4D_GHQ_THREADS ? R4D_GHQ_THREADS : r4d_act_threads((int)M, (int)K); + const int thr = r4d_act_threads((int)M, (int)K); const size_t shmem = (size_t)K * sizeof(float) + (thr / 32) * sizeof(float); if (shmem > 65536) return R4D_NO(RAD_E_SCRATCH); const long gs = (long)(a_stride ? a_stride : K), us = (long)(b_stride ? b_stride : K); const float rn = 1.f / sqrtf((float)had); - const float clip = r4d_gated_act_clip(mode); #define R4D_GHQ_LAUNCH(H, MD, T) hipLaunchKernelGGL((r4d_gated_had_quant_i8_kernel), \ dim3((int)M), dim3(T), shmem, (hipStream_t)stream, pa, pb, (signed char*)r4d_wp(q), \ - (float*)r4d_wp(sc), (int)K, gs, us, rn, clip) + (float*)r4d_wp(sc), (int)K, gs, us, rn) #define R4D_GHQ_T(H, MD) switch (thr) { \ - case 128: R4D_GHQ_LAUNCH(H, MD, 128); break; \ case 256: R4D_GHQ_LAUNCH(H, MD, 256); break; \ case 512: R4D_GHQ_LAUNCH(H, MD, 512); break; \ case 1024: R4D_GHQ_LAUNCH(H, MD, 1024); break; \ @@ -187,5 +153,5 @@ extern "C" int r4d_rad_gated_had_quant_i8(const RadArgs* args, RadStream stream) #undef R4D_GHQ_MODE #undef R4D_GHQ_T #undef R4D_GHQ_LAUNCH - return RAD_OK; + return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); } diff --git a/libr4d/r4d_gdn_args.h b/libr4d/r4d_gdn_args.h index 7b010ad7..0e3bff4a 100644 --- a/libr4d/r4d_gdn_args.h +++ b/libr4d/r4d_gdn_args.h @@ -1,9 +1,5 @@ -/* r4d_gdn_args.h -- what the gated-delta-net kernels share when they read their arguments. - * - * The GDN family is seven kernels across six translation units, and they share two things: a - * dtype check that has to be by name, and `num_seqs` read off the cu_seqlens tensor. Both belong - * to the family rather than to any one kernel, so they live here -- a header beside them, not an - * adapter directory between them and the core. See libr4d/r4d_args.h. +/* r4d_gdn_args.h -- argument helpers shared by the gated-delta-net kernels (and the DFlash ops): + * dtype checks, num_seqs from cu_seqlens, the compiled-geometry check and a row-pitch reader. */ #ifndef R4D_GDN_ARGS_H #define R4D_GDN_ARGS_H @@ -12,29 +8,28 @@ #include "r4d_args.h" -/* EVERY POINTER libr4d TAKES AS `const void*` HAS ONE ELEMENT TYPE, AND THE CAST IS INSIDE THE - * KERNEL. `r4d_gdn_conv_prep_w4_h128_bf16` casts `wgt` to `const unsigned short*` and `A_log` to - * `const float*`; nothing in the signature says so. - * - * The hazard is concrete, not theoretical. A plugin that declares `ssm_conv1d.weight` f32 or the - * `gdn_kkt` buffer f32 hands libr4d planes it reads as bf16: the convolution takes two bf16 - * elements out of every float, and the chunk scan's inverse is written as bf16 into a plane sized - * and read as f32. Neither shows up on the host path, because libref reads every operand through - * its OWN dtype and is therefore correct with either -- so the two implementations disagree and - * only the device one is wrong. - * - * A shim exists to reject what the entry point would reject if it could see the argument (spec - * §2.1, and the file header above says the same about pitches). A dtype the kernel silently - * reinterprets is the strongest case of that there is, so it is checked here, by name. */ +/* Every `const void*` libr4d takes has one element type, cast inside the kernel (e.g. + * r4d_gdn_conv_prep_w4_h128_bf16 reads `wgt` as bf16 and `A_log` as f32); the signature does not + * say so. A plugin declaring `ssm_conv1d.weight` or the `gdn_kkt` buffer as f32 would be read as + * bf16 on the device, while libref (which honours each operand's dtype) stays correct, so the bug + * would show only on the device path. The shim therefore checks dtypes by name (spec §2.1). */ static inline int r4d_dt(const RadTensor* t, uint32_t want) { if (!t) return RAD_OK; /* an absent optional operand has no dtype */ return t->dtype == want ? RAD_OK : RAD_E_DTYPE; } -#define R4D_DT(t, want) do { const int _d = r4d_dt((t), (want)); if (_d != RAD_OK) return _d; } while (0) +#define R4D_DT(t, want) \ + do { const int _d = r4d_dt((t), (want)); if (_d != RAD_OK) return R4D_NO(_d); } while (0) -/* num_seqs from the cu_seqlens tensor: it is [N+1] and nothing else in the argument list carries - * N. Refusing a cu of rank != 1 here is what stops an off-by-one N reaching a kernel that indexes - * cu[N] unconditionally. */ +/* A raw r4d.h entry point's result as a RAD status. Those return 0, a negative code for a + * geometry they were not compiled for, or the positive hipError_t of a failed launch. */ +static inline int r4d_raw_status(int rc, const char* file, int line) { + if (rc == 0) return RAD_OK; + return r4d_refused(rc < 0 ? RAD_E_SHAPE : RAD_E_DEVICE, file, line); +} +#define R4D_RAW(rc) r4d_raw_status((rc), __FILE__, __LINE__) + +/* num_seqs from the [N+1] cu_seqlens tensor, the only operand that carries N. Requiring rank 1 + * keeps an off-by-one N from reaching kernels that index cu[N] unconditionally. */ static inline int seqs_of(const RadTensor* cu, int* out) { if (!cu || cu->rank != 1 || cu->shape[0] < 2) return R4D_NO(RAD_E_SHAPE); if (!r4d_contig(cu)) return R4D_NO(RAD_E_STRIDE); @@ -51,9 +46,8 @@ static inline int gdn_dims_ok(void) { } -/* Elements between consecutive `width`-wide rows, for an operand that spells them either way: a - * [.., heads, width] tensor steps a row with the stride of the axis above the last, and a flattened - * [tokens, heads*width] one steps it with `width`. Negative when neither holds densely. */ +/* Elements between consecutive `width`-wide rows: the second-to-last stride of a [.., heads, width] + * tensor, or `width` for a dense flattened [tokens, heads*width] one. Negative otherwise. */ static inline long long gn_row_pitch(const RadTensor* t, long long width) { if (!t || t->rank < 1) return -1; if (t->shape[t->rank - 1] == width) { diff --git a/libr4d/r4d_gdn_chunk_scan_k128_v128_c64_bf16.hip b/libr4d/r4d_gdn_chunk_scan_k128_v128_c64_bf16.hip index 076e78e5..77af249a 100644 --- a/libr4d/r4d_gdn_chunk_scan_k128_v128_c64_bf16.hip +++ b/libr4d/r4d_gdn_chunk_scan_k128_v128_c64_bf16.hip @@ -1,113 +1,48 @@ // r4d_gdn: the gated-delta-net chunked scan, gfx1201 WMMA. Entry point // r4d_gdn_chunk_scan_k128_v128_c64_bf16 -- head_k 128, head_v 128, chunk 64, bf16 in. -// Named for the algorithm rather than the serving phase: the chunked scan is what prefill and -// chunked prefill both run, while decode runs the recurrent update, which is a different kernel. -// It replaces FLA's recompute_w_u_fwd + chunk_gated_delta_rule_fwd_h + chunk_fwd_o: the -// recurrent state lives in WMMA accumulators across the whole chunk loop, so h / w / u / -// v_new are never written to or read from HBM. +// Used by prefill and chunked prefill; decode uses the recurrent update kernel. Replaces FLA's +// recompute_w_u_fwd + chunk_gated_delta_rule_fwd_h + chunk_fwd_o: the recurrent state stays in +// WMMA accumulators across the chunk loop, so h / w / u / v_new never touch HBM. // -// Every decay factor this kernel forms is <= 1. That is a correctness requirement, not -// a style: the intra-chunk gate span reaches 558 nats on real Qwen3.8 prefill -// activations, so any factorisation that puts part of the exponent on -// its own -- e^{g_i-c} and e^{c-g_j} about a per-chunk reference c, say -- sends one half -// past fp32's e^88 while the other underflows to 0, whatever c is chosen. The pair -// e^{g_i-g_j} (j <= i) and e^{g_last-g_j} never leave (0, 1]. +// Invariant: every decay factor formed is <= 1. The intra-chunk gate span reaches 558 nats on +// real Qwen3.8 prefill activations, so splitting the exponent about a per-chunk reference c +// (e^{g_i-c} * e^{c-g_j}) overflows fp32 on one side and underflows on the other for any c. +// e^{g_i-g_j} (j <= i) and e^{g_last-g_j} stay in (0, 1]. // // ge[j]=e^{g_j} gg[j]=g_j gs[j]=e^{g_last-g_j} // U = K@S W = beta*(V - ge*U) V' = A@W (undecayed) // P = Q@K^T sA = scale*e^{g_i-g_j}*tril(P) // O = scale*ge*(Q@S) + sA@V' // S = e^{g_last}*S + V'^T@(gs*K) -// A is FLA's solve_tril output (decay already folded in), so no decay enters W or V'. -// The (i,j) weight is therefore applied per element in the score step -- eight __expf per -// tile -- and the state's e^{g_last-g_j} rides on K, which is dead by then. V' itself has -// to stay undecayed because its two consumers want different references: the output wants -// e^{g_i-g_j}, which is row-dependent, and the state wants e^{g_last-g_j}. One shared -// scaling of V' can only serve both through a split, which is exactly what has no safe c. +// A is FLA's solve_tril output (decay folded in), so no decay enters W or V'. The (i,j) weight +// is applied per element in the score step (eight __expf per tile), and the state's +// e^{g_last-g_j} is applied to K, which is otherwise dead by then. V' stays undecayed because its +// consumers need different references (e^{g_i-g_j} for the output, e^{g_last-g_j} for the state), +// and serving both from one scaling would need the unsafe split. #include #include "r4d.h" +#include "r4d_common.h" #include "r4d_gdn_args.h" #include "r4d_gdn_wmma.h" -// TRIL: skip GEMM tiles above the diagonal (A from solve_tril is unit lower -// triangular, and sA is masked). 2.4% slower, and left off; the reason is -// structural rather than tuning: the waves rendezvous at a workgroup barrier, so only -// the critical path matters. Every wave computes 2 P tiles; only 10 of the 16 are -// needed, but 10 tiles over 8 waves still leaves some wave holding 2 -- the barrier's -// arrival time does not move, and the skipped waves just wait longer. On top of that -// the guards stop the compiler batching fragment loads ahead of the WMMA chain. -// Correctness is unaffected either way, which is why the flag can stay. -#ifndef TRIL -#define TRIL 0 -#endif -// LDSBAR: __syncthreads() is an ALL-address-space fence, so the barrier that follows -// the global O store compiles to s_wait_storecnt_dscnt 0x0 -- every wave waits for its -// output stores to reach cache before an LDS-only rendezvous. Scoping the fence to -// "local" keeps the required LDS ordering and drops the storecnt wait. -#ifndef LDSBAR -#define LDSBAR 1 -#endif -#if LDSBAR -#define BAR() do { \ - __builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "local"); \ - __builtin_amdgcn_s_barrier(); \ - __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup", "local"); \ - } while (0) -#else -#define BAR() __syncthreads() -#endif +// Barriers are lds_barrier(): __syncthreads() fences all address spaces, so the barrier after the +// global O store would wait on s_wait_storecnt_dscnt 0x0. #define BT 64 #define KD 128 #define VD 128 #define BV 64 // V per workgroup; also halves the Q@K^T redundancy -#ifndef KP #define KP 132 // row pitch of the [.][KD] buffers, in shorts -#endif -#ifndef AP #define AP 68 // row pitch of the [.][BT] buffers, in shorts -#endif #define WP AP -// NW: waves per workgroup. The [4 token][4 v] tile grid is fixed by BT and BV, so the -// wave count decides how many tiles each wave carries: 8 waves take two, 16 take one. -// One tile per wave halves the live accumulators (and the state slice), which is what -// this kernel is short of -- at NW=8 it sits on 242 VGPRs and keeping one more address -// live spills 146 of them. -#ifndef NW +// Waves per workgroup. The [4 token][4 v] tile grid is fixed by BT and BV, so 8 waves carry two +// tiles each. The kernel is at 242 VGPRs; one more live address spills. #define NW 8 -#endif #define NTHR (NW * 32) -#if NW == 8 #define NTV 2 // n tiles per wave in the main / V' / O loops -#elif NW == 16 -#define NTV 1 -#else -#error "NW must be 8 or 16" -#endif -// SASG: how a wave's slice of the 8 k-tile x 4 v-tile state grid is shaped. The A -// operand of the state update is K TRANSPOSED, which costs eight scalar LDS reads per -// fragment against one for an untransposed one, so the shape that reads the FEWEST -// k-tiles per wave would win: one k-tile x four v-tiles reads 4 fragT + 16 fragP per chunk -// where two x two reads 8 + 8. The transposed reads are only ~3% of the kernel (ABL=7 -// prices them), and the 1x4 shape is about 20% SLOWER: reading half as many transposed -// fragments does not pay for holding four V' fragments live per k step, because the shape -// that reads fewer k-tiles reads more of everything else. Left at 0 (two k-tiles x two -// v-tiles). -#ifndef SASG -#define SASG 0 -#endif -#if SASG && NW == 8 -#define SKT 1 // state k-tiles per wave -#define SVT 4 // state v-tiles per wave -#elif SASG && NW == 16 -#define SKT 1 -#define SVT 2 -#elif NW == 8 +// A wave's slice of the 8 k-tile x 4 v-tile state grid is 2 x 2. 1 x 4 halves the transposed-K +// reads (fragT) but is ~20% slower: holding four V' fragments live costs more than they save. #define SKT 2 #define SVT 2 -#else -#define SKT 1 -#define SVT 2 -#endif #define NST (SKT * SVT) // state tiles per wave struct Smem { @@ -116,145 +51,24 @@ struct Smem { unsigned short S[BV][KP]; // B: state, V-major (matches FLA's [V,K] layout) unsigned short W[BV][WP]; // B: W (transposed) unsigned short D[BV][AP]; // staged V as [token][v]; then V' as [v][token]. - // Both live inside one chunk and never overlap: V dies - // in the W update, V' is written after barrier (2). - float ge[BT], gv[BT], gg[BT], bt[BT]; // gv = gs (or e^{c-g} under GSPLIT), gg = raw g + // V dies in the W update; V' is written after barrier (2). + float ge[BT], gv[BT], gg[BT], bt[BT]; // gv = gs, gg = raw g }; -// LDSO: hold each LDS row pointer as one opaque 32-bit byte offset (see fragO). -#ifndef LDSO -#define LDSO 1 -#endif -#ifndef SCHED -#define SCHED 5 -#endif -#ifndef SB // k steps per sched group in the V' and O+= loops -#define SB 2 -#endif -#ifndef SS // k steps per sched group in the state update -#define SS 1 -#endif -// GO: address the global q / A fragments as a 32-bit element offset off a uniform base -// (fragGo) instead of a per-lane 64-bit pointer (rowG + fragP). See r4d_gdn_wmma.h -- -// the pointer form makes LLVM rebuild v_mad_co_i64_i32 + v_lshlrev_b64 + a 64-bit add -// per fragment at this kernel's register pressure. -#ifndef GO -#define GO 1 -#endif -// LDSO2: the same treatment for the V' / O / state loops' LDS rows -- one opaque byte -// offset per buffer, so every k step is an immediate on ds_load_2addr_b32 (LDSO already -// does this for the main loop's five fragments). -// It SPILLS at NW=8 (242 VGPRs already, 146 spilled, 2.5x slower) and is only usable -// when a wave carries one tile. -#ifndef LDSO2 -#define LDSO2 (NW == 16) -#endif -// WIDE: stage k and v eight shorts per lane (global_load_b128) instead of four, and -// address them as a 32-bit element offset off a chunk-uniform base. Halves the staging -// loads, and with a wave-uniform row (PFV >= 1) the address is one v_add on an SALU row -// offset instead of v_mad_co_i64_i32 + v_lshlrev_b64 + a 64-bit add. -#ifndef WIDE -#define WIDE 1 -#endif -// PFIN: issue the next chunk's six staging loads INSIDE the main WMMA loop, one per k step, -// instead of as a block before it. Nothing orders them -- they read global memory and write -// registers consumed a whole chunk later -- and as a block they land in the 267-instruction -// stretch between the main loop's last WMMA and the V' loop's first, which has no WMMA to hide -// their addressing behind. -// It is ~5% slower and left at 0: the loads themselves are one v_min and an access, but -// interleaving them costs the main loop's WMMA schedule more than the block costs in the gap. -// (Nor does an in-loop bf16 rounding trick exist to shrink that gap: gfx1201 has no -// v_add_nc_u64, so two floats cannot be rounded with one add, and v_pk_add_u16 does not carry -// between halves -- which IS the rounding.) -#ifndef PFIN -#define PFIN 0 -#endif -// APRE: issue the V' loop's four A fragments (global) BEFORE the main WMMA loop instead -// of at the top of the V' loop. They are read immediately after barrier (2), so their HBM -// latency is otherwise fully exposed; hoisted, they land during the main loop's 48 WMMAs. -// Costs 16 VGPRs. -// It is ~16% slower and left at 0. It does not spill (227 VGPRs), but the sixteen registers -// it keeps live across the main loop cost more than the latency it hides, and the V' loop's -// sched group already batches those loads a whole step ahead. -#ifndef APRE -#define APRE 0 -#endif -// ABL: timing-only ablation ladder -- every nonzero value produces WRONG results and -// exists solely to price one stage. 1 = drop the state-update WMMAs, 2 = drop O += sA@V', -// 3 = drop V' = A@W, 4 = drop P from the main loop, 5 = drop U, 6 = drop O^T, -// 7 = read the state update's K^T operand with a normal (untransposed) fragP, which has -// the same WMMA count and 2 LDS reads per fragment instead of 8. -#ifndef ABL -#define ABL 0 -#endif -// BFR: which bf16 packs round. 1 = all (safe), 2 = intermediates truncate but the -// recurrent state and the kernel output still round, 0 = all truncate. -// Left at 1: truncating is 1.5% (BFR=2) / 2.2% (BFR=0) faster, but it takes the fp64-oracle -// error from 3.30e-03 (FLA parity) to 9.02e-03 / 1.17e-02, and the state error from -// 2.4e-03 to 5.1e-03 -- W/sA/V' feed the recurrence, so even BFR=2 pollutes the state. -#ifndef BFR -#define BFR 1 -#endif -// GSPLIT: the split-decay form, e^{g_i-g_j} = e^{g_i-c}.e^{c-g_j} about the chunk midpoint, -// with both halves clamped at e^80. IT IS WRONG AND IT IS OFF; it stays reachable only so -// the failure it produces can be reproduced on demand. It is one exp per token instead of -// eight per tile, but a chunk whose gate span passes ~176 nats has the growing half clamped -// and the shrinking one at 0, and the terms it should have produced are attenuated to -// nothing. On real prefill activations that fires on 3.5% of (head, chunk) pairs and takes -// the fp64-oracle error from 3.4e-03 to 4.0e-02 - 7.2e-02, bimodally: a chunk is either -// untouched or wrecked. This is the factorisation the file header rules out. -#ifndef GSPLIT -#define GSPLIT 0 -#endif -// PRIO: raise this wave's issue priority across the WMMA-dense region so it is not -// starved by waves in their memory phase. -#ifndef PRIO -#define PRIO 0 -#endif -// SID: give each WMMA loop its own sched_group_barrier syncid, so one loop's group -// pattern cannot be satisfied by another loop's instructions when the scheduler puts -// them in the same region. -#ifndef SID -#define SID 0 -#endif -// NOVM: leave the global q/A loads out of the group pattern and let the scheduler -// place them freely. -#ifndef NOVM -#define NOVM 0 -#endif -#if SID -#define SIDF 1 -#define SIDV 2 -#define SIDO 3 -#define SIDS 4 -#else -#define SIDF 0 -#define SIDV 0 -#define SIDO 0 -#define SIDS 0 -#endif -#if PRIO -#define PRIO_HI() __builtin_amdgcn_s_setprio(1) -#define PRIO_LO() __builtin_amdgcn_s_setprio(0) -#else -#define PRIO_HI() ((void)0) -#define PRIO_LO() ((void)0) -#endif -#if BFR == 1 -#define F2BF4I f2bf4 // W, sA, V' -- consumed inside one chunk -#define F2BF4O f2bf4 // s.S and o -- carried across chunks / returned -#elif BFR == 2 -#define F2BF4I f2bf4t -#define F2BF4O f2bf4 -#else -#define F2BF4I f2bf4t -#define F2BF4O f2bf4t -#endif -// LDS reads and WMMAs per k step of the main loop, for the sched groups below: -// one A fragment (K row mt) shared by every tile, plus S and K per n tile. -// One ds_load_2addr_b64 per LDS fragment (see fragP in r4d_gdn_wmma.h) -- these counts -// are what the sched groups below pattern on, and a count that does not match what the -// loop actually contains produces a WORSE schedule than no pattern at all. +// Choices measured against their alternatives on gfx1201, kept so they are not undone: +// - LDS rows in the main loop are opaque 32-bit byte offsets (fragO), global q / A fragments a +// 32-bit offset off a uniform base (fragGo). The V' / O / state loops keep plain pointers: +// offsets there spill at 8 waves. +// - k and v are staged eight shorts per lane (global_load_b128), issued as a block before the +// main loop: interleaving them into it is ~5% slower. +// - The V' loop's A fragments are not preloaded: 16 more live VGPRs cost ~16%. +// - Every bf16 pack rounds (f2bf4). Truncating W, sA and V' is ~2% faster but roughly triples +// the fp64-oracle error, since they feed the recurrence. +#define SB 2 // k steps per sched group in the V' and O += loops +#define SS 1 // k steps per sched group in the state update +// LDS reads and WMMAs per main-loop k step, for the sched groups: one A fragment (K row mt) shared +// by every tile, plus S and K per n tile, one ds_load_2addr_b64 each (fragP). These must match the +// loop exactly; a wrong count schedules worse than no pattern. #define MLDS (1 + 2 * NTV) #define MWMA (3 * NTV) // byte offset of buffer[base + lo][4*hi] from the base of the shared block @@ -262,19 +76,16 @@ struct Smem { ((unsigned)((const char*)&(buf)[0][0] - (const char*)&s) + \ (unsigned)((((base) + lo) * (pitch) + 4 * hi) * 2)) -// SDT is the STATE CACHE's element type -- 0 = fp32, 1 = fp16 -- and nothing else: every value -// this kernel computes with is fp32 either way, and the recurrence still carries the state in -// WMMA accumulators across the whole chunk loop. It exists because vLLM allocates the mamba cache -// from --mamba-ssm-cache-dtype and the recurrent update, whose time IS the state traffic, wants -// the narrow one; the two kernels share the cache, so they have to agree on its width. +// SDT is the state cache's element type (0 = fp32, 1 = fp16) and nothing else; all arithmetic is +// fp32. The cache is shared with the recurrent update (whose time is the state traffic, so it +// favours fp16) and allocated from vLLM's --mamba-ssm-cache-dtype, so both kernels must agree. typedef _Float16 cs_h8 __attribute__((ext_vector_type(8))); template struct cs_state { using T = float; }; template <> struct cs_state<1> { using T = _Float16; }; -// H0 / HT say whether the optional initial and final state operands were passed. They are template -// parameters rather than runtime tests so that the form every caller in this tree launches -- both -// present -- carries no test for them; the absent forms are what libref reads the op as: no initial -// state starts the recurrence from zero, no final state stores nothing. +// H0 / HT: whether the optional initial and final state operands are present (template parameters, +// so the common both-present form has no runtime test). As in libref, no initial state starts from +// zero and no final state stores nothing. template __global__ __launch_bounds__(NTHR) void r4d_gdn_chunk_scan_kernel( const unsigned short* __restrict__ q, const unsigned short* __restrict__ k, @@ -290,182 +101,64 @@ __global__ __launch_bounds__(NTHR) void r4d_gdn_chunk_scan_kernel( const int tid = threadIdx.x, w = tid >> 5, lane = tid & 31; const int hq = hv / (H / Hg), v0 = bv * BV; const int tb = cu[nq], te = cu[nq + 1]; - // THE STATE SLOT IS THE MANAGER'S, NOT THE BATCH POSITION. Without `sidx` this kernel writes - // state[nq] -- correct only while a sequence's slot happens to equal its row in the batch, - // which holds until the first slot is reused out of order and then silently does not. - // COLUMN 0 IS THE STATE. A row may name more than one slot -- a decode kernel serving - // speculation asks for scratch beside the state -- but the scan writes the state and nothing - // else, so it reads the first column and ignores the width. + // The state slot comes from the cache manager (sidx), not the batch position; without sidx the + // kernel uses state[nq], valid only while slots match batch order. A row may name several slots + // (speculative decode adds scratch slots); column 0 is the state and the only one used here. const long si = sidx ? (long)sidx[(size_t)nq * sidx_stride] : (long)nq; if (si < 0) return; // a padded row owns no state const size_t st_base = (size_t)si * st_slot + (size_t)hv * st_head; const int nchunk = (te - tb + BT - 1) / BT; const int lo = lane & 15, hi = lane >> 4; -#if NW == 8 const int mt = w >> 1, ntb = (w & 1) * 2; // [BT][BV]: 2 tiles/wave -#else - const int mt = w >> 2, ntb = (w & 3); // [BT][BV]: 1 tile/wave -#endif - // The state accumulator is held TRANSPOSED, C[m=k-dim][n=v]. WMMA A and B fragments - // share a lane layout, so swapping the operands of the state update is free -- and it - // makes k-dim the per-lane contiguous axis, so the per-chunk writeback to s.S is four - // packed 8-short stores instead of 32 scalar ds_store_b16. -#if SASG && NW == 8 - const int kt0 = w, vt0 = 0; // [KD][BV]: 1 x 4 tiles/wave -#elif SASG && NW == 16 - const int kt0 = (w >> 1), vt0 = (w & 1) * 2; // 1 x 2 -#elif NW == 8 + // The state accumulator is held transposed, C[m=k-dim][n=v]. A and B fragments share a lane + // layout, so swapping the state update's operands is free, and k-dim becomes the per-lane + // contiguous axis: the per-chunk writeback to s.S is four 8-short stores instead of 32 scalar. const int kt0 = (w >> 1) * 2, vt0 = (w & 1) * 2; // 2 x 2 -#else - const int kt0 = (w >> 1), vt0 = (w & 1) * 2; // 1 x 2 -#endif -#if WIDE #define PFW 8 // shorts staged per lane per step -#define pfv_t uint4 #define PFZERO make_uint4(0u, 0u, 0u, 0u) -#else -#define PFW 4 -#define pfv_t uint2 -#define PFZERO make_uint2(0u, 0u) -#endif #define NKB (BT * KD / (NTHR * PFW)) #define NVB (BT * BV / (NTHR * PFW)) - pfv_t kb[NKB], vb[NVB]; - // Staging index, split into a WAVE-UNIFORM row and a loop-invariant lane column. - // Written as `i = tid*4 + u*NTHR*4; r = i>>7` the row is opaquely divergent to LLVM, - // so each of the 12 loads rebuilt a full 64-bit address (v_mad_co_i64_i32 + - // v_lshlrev_b64 + 64-bit add) with the bounds test as exec-mask manipulation -- - // ~13 instructions per 8-byte load. readfirstlane makes the row provably uniform, so - // the row address is SALU and the vector part is one loop-invariant register. + uint4 kb[NKB], vb[NVB]; + // Staging index, split into a wave-uniform row and a loop-invariant lane column. As + // `i = tid*4 + u*NTHR*4; r = i>>7` the row looks divergent to LLVM and each load costs ~13 + // instructions of 64-bit address math; readfirstlane makes the row provably uniform (SALU). // Identities (exact, since u*NTHR*4 is a multiple of both 128 and 64): // k: r = (tid>>5) + NW*u c = (tid*4) & 127 // v: r = 2*(tid>>5) + vh + 2*NW*u c = (tid*4) & 63 vh = (tid>>4) & 1 const int wu = __builtin_amdgcn_readfirstlane(tid >> 5); const int kc = (tid * PFW) & (KD - 1), vc = (tid * PFW) & (BV - 1); -#if WIDE const int kr0 = 2 * wu + ((tid >> 4) & 1), vr0 = 4 * wu + ((tid >> 3) & 3); #define KRU (2 * NW) #define VRU (4 * NW) -#else - const int kr0 = wu, vr0 = 2 * wu + ((tid >> 4) & 1); -#define KRU NW -#define VRU (2 * NW) -#endif - // ROWS PAST THE CHUNK END ARE ZEROED, AND CLAMPING THEM TO THE LAST LIVE ROW IS WRONG. - // DO NOT "OPTIMISE" THIS BACK TO A CLAMP. The apparent argument that a duplicated row - // cannot matter is: - // * beta[t>=nval] = 0, so W = beta*(V - ge*U) is 0 whatever V and U hold; - // * gv[t>=nval] = 0, and s.k is scaled by gv before the state update, so the - // contraction over t already drops those columns; - // * the tril mask kills j>i, so a padding j never reaches a live row of sA; - // * the O store is guarded by tok < nval. - // Every clause of that is true and the conclusion is false. With the clamp, any prompt - // whose trailing chunk is not a multiple of 16 tokens -- 65, 75, 81, 200 -- comes back as - // one token repeated, and the process never serves a correct answer again; 64, 80, 96, - // 112 and 128 stay right. Zeroing the staged rows makes all of them right, and zeroing k - // alone is enough with v still clamped -- so the leak is through a consumer of s.k, and - // the four clauses above cover every consumer of s.k this kernel has. One of them is - // therefore not the whole story. Until it is known which, the padding rows do not get to - // hold live data. -// PFV: 0 = divergent index, predicated 1 = wave-uniform + predicate -// 2 = wave-uniform + clamp 3 = divergent index + clamp -// All four produce bit-identical output where the clamp is safe. Variant 1 is ~12% faster than -// variant 0, and the CLAMPED variants only pay once the load is wide: at PFW=4 a clamp saves the -// selects but nothing else, while at PFW=8 it also removes the exec-mask manipulation around -// a 128-bit load, which is worth a further ~4%. -// The clamped variants are unreachable in the shipped configuration -- see the paragraph above -- -// and are LEFT IN only as the comparison point for that cost. -#ifndef PFV -#define PFV 1 -#endif -// 4 = the clamp applied to a HOISTED per-lane byte offset. Once a lane stages eight -// shorts the staging row is no longer wave-uniform (lanes 0-15 and 16-31 are different -// rows), so `r * (Hg*KD)` is a v_mul_lo_u32 per load per chunk. Clamping the OFFSET -// instead of the row is the same value -- both add the same column -- and lets the whole -// product be computed once, outside the chunk loop. -#if PFV == 0 || PFV == 3 -#define PFROWK (i / KD) -#define PFROWV (i / BV) -#define PFCOLK (i & (KD - 1)) -#define PFCOLV (i % BV) -#define PFIDX int i = tid * PFW + u * NTHR * PFW; -#else -#define PFROWK (kr0 + KRU * u) -#define PFROWV (vr0 + VRU * u) -#define PFCOLK kc -#define PFCOLV vc -#define PFIDX -#endif -#if PFV == 0 || PFV == 1 -#define PFK(r, pnv, e) ((r) < (pnv) ? (e) : PFZERO) -/* The `(void)` is what keeps PREFETCH's `prl` from being an unused local in this variant -- it is - * the last row of the chunk, and only the unconditional-read variant below needs it to clamp with. - * Here the read is already guarded by PFK's `(r) < (pnv)`, so there is nothing to clamp. - * Discarding it in the macro rather than not declaring it keeps ONE PREFETCH body for both. */ -#define PFCLAMP(r, prl) ((void)(prl), (r)) -#else -#define PFK(r, pnv, e) (e) -#define PFCLAMP(r, prl) min((r), (prl)) -#endif -#if PFV == 4 -#define PFHOIST() \ - const unsigned krs = (unsigned)(Hg * KD), vrs = (unsigned)(H * VD); \ - unsigned koff0[NKB], voff0[NVB]; \ - _Pragma("unroll") for (int u = 0; u < NKB; ++u) \ - koff0[u] = (unsigned)(kr0 + KRU * u) * krs + (unsigned)kc; \ - _Pragma("unroll") for (int u = 0; u < NVB; ++u) \ - voff0[u] = (unsigned)(vr0 + VRU * u) * vrs + (unsigned)vc; -#else -#define PFHOIST() -#endif + // Do not change: staged rows past the chunk end are zeroed, not clamped to the last live row + // (~4% faster). A clamp looks harmless (beta and gv are 0 there, the tril mask drops padding j, + // the O store is guarded), yet with it any prompt whose trailing chunk is not a multiple of 16 + // tokens returns one repeated token. Zeroing k alone fixes it, so the leak is through some + // consumer of s.k whose path is not yet understood. #define PFSTORE(dst, val) \ do { \ unsigned short* dp_ = (dst); \ *(uint2*)dp_ = make_uint2((val).x, (val).y); \ - if (PFW == 8) *(uint2*)(dp_ + 4) = make_uint2(*(&(val).x + 2), *(&(val).x + 3)); \ + *(uint2*)(dp_ + 4) = make_uint2((val).z, (val).w); \ } while (0) -#if PFV == 4 -// the chunk-uniform half, so the loads themselves are one v_min plus the access -#define PFBASE(CH) \ - const int pc0_ = tb + (CH) * BT, prl_ = min(BT, te - pc0_) - 1; \ - const unsigned short* kb_ = k + ((size_t)pc0_ * Hg + hq) * KD; \ - const unsigned short* vb_ = v + ((size_t)pc0_ * H + hv) * VD + v0; \ - const unsigned kcl = (unsigned)prl_ * krs + (unsigned)kc; \ - const unsigned vcl = (unsigned)prl_ * vrs + (unsigned)vc; -#define PFONE(u) \ - do { \ - if ((u) < NKB) kb[(u) < NKB ? (u) : 0] = \ - *(const pfv_t*)(kb_ + min(koff0[(u) < NKB ? (u) : 0], kcl)); \ - else if ((u) - NKB < NVB) vb[(u) >= NKB ? (u) - NKB : 0] = \ - *(const pfv_t*)(vb_ + min(voff0[(u) >= NKB ? (u) - NKB : 0], vcl)); \ - } while (0) #define PREFETCH(CH) \ { \ - PFBASE(CH) \ - _Pragma("unroll") for (int u = 0; u < NKB + NVB; ++u) PFONE(u); \ - } -#else -#define PREFETCH(CH) \ - { \ - int pc0 = tb + (CH) * BT, pnv = min(BT, te - pc0), prl = pnv - 1; \ + const int pc0 = tb + (CH) * BT, pnv = min(BT, te - pc0); \ const unsigned short* kb_ = k + ((size_t)pc0 * Hg + hq) * KD; \ const unsigned short* vb_ = v + ((size_t)pc0 * H + hv) * VD + v0; \ _Pragma("unroll") for (int u = 0; u < NKB; ++u) { \ - PFIDX int r0 = PFROWK, r = PFCLAMP(r0, prl); \ - kb[u] = PFK(r0, pnv, \ - *(const pfv_t*)(kb_ + (unsigned)(r * (Hg * KD)) + PFCOLK)); \ + const int r = kr0 + KRU * u; \ + kb[u] = r < pnv ? *(const uint4*)(kb_ + (unsigned)(r * (Hg * KD)) + kc) : PFZERO; \ } \ _Pragma("unroll") for (int u = 0; u < NVB; ++u) { \ - PFIDX int r0 = PFROWV, r = PFCLAMP(r0, prl); \ - vb[u] = PFK(r0, pnv, \ - *(const pfv_t*)(vb_ + (unsigned)(r * (H * VD)) + PFCOLV)); \ + const int r = vr0 + VRU * u; \ + vb[u] = r < pnv ? *(const uint4*)(vb_ + (unsigned)(r * (H * VD)) + vc) : PFZERO; \ } \ } -#endif - v8f St[NST]; // state: NSK k-tiles x 2 v-tiles + v8f St[NST]; // state: SKT k-tiles x SVT v-tiles #define KT(t) (kt0 + (t) / SVT) #define VT(t) (vt0 + (t) % SVT) #define SROW(t) ((size_t)(v0 + VT(t) * 16 + lo) * KD + KT(t) * 16 + 8 * hi) @@ -478,8 +171,8 @@ __global__ __launch_bounds__(NTHR) void r4d_gdn_chunk_scan_kernel( const typename cs_state::T* p = h0 + st_base; #pragma unroll for (int t = 0; t < NST; ++t) { - // Eight elements a row-tile: two 16-byte accesses in fp32, ONE in fp16. SROW ends in - // 8*hi, so the fp16 arm is 16-byte aligned for the same reason the fp32 arm is. + // Eight elements per row-tile: two 16-byte accesses in fp32, one in fp16 (16-byte + // aligned since SROW ends in 8*hi). if constexpr (SDT) { const cs_h8 x = *(const cs_h8*)(p + SROW(t)); #pragma unroll @@ -495,19 +188,17 @@ __global__ __launch_bounds__(NTHR) void r4d_gdn_chunk_scan_kernel( #define SWRITE() \ _Pragma("unroll") for (int t = 0; t < NST; ++t) { \ unsigned short* sp = &s.S[VT(t) * 16 + lo][KT(t) * 16 + 8 * hi]; \ - *(uint2*)sp = F2BF4O(St[t][0], St[t][1], St[t][2], St[t][3]); \ - *(uint2*)(sp + 4) = F2BF4O(St[t][4], St[t][5], St[t][6], St[t][7]); \ + *(uint2*)sp = f2bf4(St[t][0], St[t][1], St[t][2], St[t][3]); \ + *(uint2*)(sp + 4) = f2bf4(St[t][4], St[t][5], St[t][6], St[t][7]); \ } SWRITE(); - PFHOIST(); - BAR(); + lds_barrier(); PREFETCH(0); const char* const sbase = (const char*)&s; - // scale rides inside the score exponent: exp(g_i + log(scale) - g_j) is the same - // instruction count as exp(g_i - g_j) and drops the eight multiplies per tile. + // scale goes inside the score exponent, exp(g_i + log(scale) - g_j), saving eight multiplies + // per tile. const float lgs = __logf(scale); - (void)lgs; for (int ci = 0; ci < nchunk; ++ci) { const int c0 = tb + ci * BT, nval = min(BT, te - c0); const int lim = nval - 1; @@ -515,81 +206,44 @@ __global__ __launch_bounds__(NTHR) void r4d_gdn_chunk_scan_kernel( const unsigned short* ag = Amat + ((size_t)c0 * H + hv) * BT; const size_t qrs = (size_t)Hg * KD, ars = (size_t)H * BT; const float gl = gcs[(size_t)(c0 + lim) * H + hv]; -#if GSPLIT - const float cref = 0.5f * (gcs[(size_t)c0 * H + hv] + gl); -#endif - // Issued before the staging store so the LDS writes below cover their latency: - // only waves 0-1 (tid < BT) run this, and every other wave waits for them at (1). + // Issued before the staging store so the LDS writes cover their latency. Only waves 0-1 + // (tid < BT) run this; the others wait at (1). float ggr = 0.f, btr = 0.f; if (tid < BT) { bool ok = tid < nval; ggr = ok ? gcs[(size_t)(c0 + tid) * H + hv] : 0.f; btr = ok ? beta[(size_t)(c0 + tid) * H + hv] : 0.f; } - { // consume the previous iteration's prefetch: the s_wait_loadcnt for these - // loads now sits a whole chunk of compute after they were issued + { // consume the previous iteration's prefetch, issued a whole chunk of compute ago #pragma unroll - for (int u = 0; u < NKB; ++u) { PFIDX PFSTORE(&s.k[PFROWK][PFCOLK], kb[u]); } + for (int u = 0; u < NKB; ++u) PFSTORE(&s.k[kr0 + KRU * u][kc], kb[u]); #pragma unroll - for (int u = 0; u < NVB; ++u) { PFIDX PFSTORE(&s.D[PFROWV][PFCOLV], vb[u]); } + for (int u = 0; u < NVB; ++u) PFSTORE(&s.D[vr0 + VRU * u][vc], vb[u]); } if (tid < BT) { bool ok = tid < nval; s.bt[tid] = btr; s.ge[tid] = __expf(ggr); -#if GSPLIT - s.gg[tid] = ok ? scale * __expf(fminf(ggr - cref, 80.0f)) : 0.f; // rs - s.gv[tid] = ok ? __expf(fminf(cref - ggr, 80.0f)) : 0.f; -#else - // g is a within-chunk cumsum of log-sigmoid gates, so it is non-increasing and gl is - // its minimum: gl - ggr <= 0, and gs underflowing to 0 is the right answer for a token - // the chunk's own decay has already annihilated. - // A PADDING ROW GETS gl, NOT 0. The score exponent is exp(g_i - g_j + log scale) and the - // mask only removes j > i, so a padding row i (which has no gate of its own) is scored - // against LIVE j with a real, very negative g_j: at 0 that is exp(+400) = inf, written - // into s.A as bf16 and multiplied by V-prime. The row is discarded either way -- the O - // store is guarded by tok < nval -- but an inf that only exists because a lane had no - // token is not something to leave in a shared buffer. gl is the chunk minimum, so - // gl - g_j <= 0 and the exponent cannot leave (0, scale]. + // g is a within-chunk cumsum of log-sigmoid gates, so it is non-increasing and gl is its + // minimum: gl - ggr <= 0, and gs underflowing to 0 is correct. + // A padding row gets gl, not 0: it is scored against live j with very negative g_j, and + // g_i = 0 would give exp(+400) = inf in s.A. With gl (the chunk minimum) the exponent + // stays in (0, scale]. The row is discarded anyway (O store is guarded). s.gg[tid] = ok ? ggr : gl; s.gv[tid] = ok ? __expf(gl - ggr) : 0.f; // gs -#endif } - BAR(); // (1) -#if PFIN && PFV == 4 - PFBASE(min(ci + 1, nchunk - 1)) // issued one per k step in the loop below -#else + lds_barrier(); // (1) PREFETCH(min(ci + 1, nchunk - 1)); // issue only; consumed next iteration -#endif -#if APRE - v8bf apre[BT / 16]; - { -#if GO - const unsigned aoh = rowGo((unsigned)ars, mt * 16, lim, lane); -#pragma unroll - for (int sk = 0; sk < BT / 16; ++sk) apre[sk] = fragGo(ag, aoh + sk * 16); -#else - const unsigned short* pah = rowG(ag, ars, mt * 16, lim, lane); -#pragma unroll - for (int sk = 0; sk < BT / 16; ++sk) apre[sk] = fragP(pah + sk * 16); -#endif - } -#endif // ---- U = K@S, O^T = S@Q^T and P^T = K@Q^T share the q and k fragments. - // tril: a whole P tile is masked away when its j-tile is above the i-tile, and the - // O += sA@V' below skips the same tiles, so they need neither computing nor storing. + // Tiles above the diagonal (A is unit lower triangular, sA is masked) are computed anyway: + // skipping them is 2.4% slower, since some wave still carries two tiles, so the barrier + // arrival does not move, and the guards stop fragment loads batching ahead of the WMMAs. v8f O[NTV], u[NTV], p[NTV]; - bool doP[NTV]; #pragma unroll - for (int i = 0; i < NTV; ++i) { - O[i] = (v8f){}; u[i] = (v8f){}; p[i] = (v8f){}; - doP[i] = (TRIL ? ntb + i <= mt : true); - } - PRIO_HI(); + for (int i = 0; i < NTV; ++i) { O[i] = (v8f){}; u[i] = (v8f){}; p[i] = (v8f){}; } { -#if LDSO const char* sb = sbase; unsigned oSn[NTV], okn[NTV]; unsigned okm = ROWO(s.k, KP, mt * 16); @@ -603,103 +257,33 @@ __global__ __launch_bounds__(NTHR) void r4d_gdn_chunk_scan_kernel( #define pSnf(i, ko) fragO(sb, oSn[i] + (ko) * 2u) #define pkmf(ko) fragO(sb, okm + (ko) * 2u) #define pknf(i, ko) fragO(sb, okn[i] + (ko) * 2u) -#else - const unsigned short* pSn[NTV]; - const unsigned short* pkn[NTV]; - const unsigned short* pkm = rowP(&s.k[0][0], KP, mt * 16, lane); -#pragma unroll - for (int i = 0; i < NTV; ++i) { - pSn[i] = rowP(&s.S[0][0], KP, (ntb + i) * 16, lane); - pkn[i] = rowP(&s.k[0][0], KP, (ntb + i) * 16, lane); - } -#define pSnf(i, ko) fragP(pSn[i] + (ko)) -#define pkmf(ko) fragP(pkm + (ko)) -#define pknf(i, ko) fragP(pkn[i] + (ko)) -#endif -#if GO const unsigned qo = rowGo((unsigned)qrs, mt * 16, lim, lane); #define pqf(ko) fragGo(qg, qo + (ko)) -#else - const unsigned short* pq = rowG(qg, qrs, mt * 16, lim, lane); -#define pqf(ko) fragP(pq + (ko)) -#endif #pragma unroll for (int sk = 0; sk < KD / 16; ++sk) { const int ko = sk * 16; v8bf ak = pkmf(ko), aq = pqf(ko); -#if PFIN && PFV == 4 - if (sk < NKB + NVB) PFONE(sk); -#endif #pragma unroll for (int i = 0; i < NTV; ++i) { v8bf b = pSnf(i, ko); -#if ABL != 5 u[i] = mma(ak, b, u[i]); -#endif -#if ABL != 6 O[i] = mma(b, aq, O[i]); // O^T: m = v-tile, n = token-tile -#endif -#if ABL != 4 - if (doP[i]) p[i] = mma(pknf(i, ko), aq, p[i]); // P^T: m = j -#endif + p[i] = mma(pknf(i, ko), aq, p[i]); // P^T: m = j } } -#if SCHED - // Ask for one k step's LDS reads to issue against the previous step's WMMAs. - // Per step: 5 LDS fragments = 10 ds_read2_b32, 1 global q fragment = 2 loads, - // 6 WMMA. Without this the scheduler sinks each read onto its consumer and - // every WMMA is preceded by a full s_wait_dscnt 0x0 drain. -#if SCHED == 4 - // Explicit one-step software pipeline: ask for step i+1's operand reads to be - // issued BEFORE step i's WMMAs, so the wait in front of each WMMA group is for - // loads that have had a full WMMA group to land. - __builtin_amdgcn_sched_group_barrier(0x020, 2, 0); - __builtin_amdgcn_sched_group_barrier(0x100, MLDS, 0); -#pragma unroll - for (int i = 0; i < KD / 16 - 1; ++i) { - __builtin_amdgcn_sched_group_barrier(0x008, MWMA, 0); // WMMA step i - __builtin_amdgcn_sched_group_barrier(0x020, 2, 0); // reads step i+1 - __builtin_amdgcn_sched_group_barrier(0x100, MLDS, 0); - } - __builtin_amdgcn_sched_group_barrier(0x008, MWMA, 0); -#elif SCHED == 5 || SCHED == 6 || SCHED == 7 - // GRAN k steps per group. Coarser is better here: the group barrier PINS the - // order at every boundary, so a per-step pattern over-constrains a loop the - // scheduler can already interleave -- it just needs to be told not to sink every - // read onto its consumer. -#if SCHED == 5 + // Issue one k step's LDS reads against the previous step's WMMAs (per step: 5 LDS + // fragments, 1 global q fragment = 2 loads, 6 WMMA). Otherwise the scheduler sinks each + // read onto its consumer and every WMMA waits on a full s_wait_dscnt 0x0 drain. + // GRAN k steps per group. Coarser is better: the group barrier pins the order at every + // boundary, and a per-step pattern over-constrains a loop the scheduler can interleave. #define GRAN 2 -#elif SCHED == 6 -#define GRAN 4 -#else -#define GRAN 8 -#endif #pragma unroll for (int i = 0; i < KD / (16 * GRAN); ++i) { -#if NOVM == 0 - __builtin_amdgcn_sched_group_barrier(0x020, 2 * GRAN, SIDF); -#endif - __builtin_amdgcn_sched_group_barrier(0x100, MLDS * GRAN, SIDF); - __builtin_amdgcn_sched_group_barrier(0x008, MWMA * GRAN, SIDF); + __builtin_amdgcn_sched_group_barrier(0x020, 2 * GRAN, 0); + __builtin_amdgcn_sched_group_barrier(0x100, MLDS * GRAN, 0); + __builtin_amdgcn_sched_group_barrier(0x008, MWMA * GRAN, 0); } -#else -#pragma unroll - for (int i = 0; i < KD / 16; ++i) { -#if SCHED == 3 // finer: rotate reads through the WMMA stream - _Pragma("unroll") for (int j = 0; j < 3; ++j) { - __builtin_amdgcn_sched_group_barrier(0x100, MLDS / 2, 0); - __builtin_amdgcn_sched_group_barrier(0x008, MWMA / 2, 0); - } -#else - __builtin_amdgcn_sched_group_barrier(0x020, 2, 0); // VMEM read (q) - __builtin_amdgcn_sched_group_barrier(0x100, MLDS, 0); // DS read - __builtin_amdgcn_sched_group_barrier(0x008, MWMA, 0); // WMMA -#endif - } -#endif -#endif } - PRIO_LO(); { float g = scale * s.ge[mt * 16 + lo]; // token index is constant per lane #pragma unroll @@ -721,165 +305,97 @@ __global__ __launch_bounds__(NTHR) void r4d_gdn_chunk_scan_kernel( #pragma unroll for (int i = 0; i < NTV; ++i) { unsigned short* wp = &s.W[(ntb + i) * 16 + lo][mt * 16 + 8 * hi]; - *(uint2*)wp = F2BF4I(wa[i][0], wa[i][1], wa[i][2], wa[i][3]); - *(uint2*)(wp + 4) = F2BF4I(wa[i][4], wa[i][5], wa[i][6], wa[i][7]); + *(uint2*)wp = f2bf4(wa[i][0], wa[i][1], wa[i][2], wa[i][3]); + *(uint2*)(wp + 4) = f2bf4(wa[i][4], wa[i][5], wa[i][6], wa[i][7]); } } - // sA = scale * e^{g_i-g_j} * tril(P). The row token ii is constant per lane and the - // eight g_j are contiguous and wave-uniform in groups of 16 lanes, so this is eight - // broadcast LDS reads, eight v_sub and eight v_exp per tile -- no multiply, because - // log(scale) is already inside the exponent. The mask makes g_i - g_j <= 0 wherever the - // value is kept, so the exp cannot overflow and its underflow is the true answer. + // sA = scale * e^{g_i-g_j} * tril(P). Row ii is constant per lane and the eight g_j are + // uniform per 16 lanes: eight broadcast LDS reads, v_sub and v_exp per tile (log(scale) is + // in the exponent). Where kept, g_i - g_j <= 0, so the exp cannot overflow. { const int ii = mt * 16 + lo; -#if GSPLIT - const float r = s.gg[ii]; // rs -#else const float gis = s.gg[ii] + lgs; -#endif #pragma unroll for (int i = 0; i < NTV; ++i) { const int j0 = (ntb + i) * 16 + 8 * hi; float a[8]; -#if GSPLIT -#pragma unroll - for (int e = 0; e < 8; ++e) a[e] = (j0 + e <= ii) ? p[i][e] * r : 0.f; -#else #pragma unroll for (int e = 0; e < 8; ++e) a[e] = (j0 + e <= ii) ? p[i][e] * __expf(gis - s.gg[j0 + e]) : 0.f; -#endif - if (doP[i]) { - *(uint2*)&s.A[ii][j0] = F2BF4I(a[0], a[1], a[2], a[3]); - *(uint2*)&s.A[ii][j0 + 4] = F2BF4I(a[4], a[5], a[6], a[7]); - } + *(uint2*)&s.A[ii][j0] = f2bf4(a[0], a[1], a[2], a[3]); + *(uint2*)&s.A[ii][j0 + 4] = f2bf4(a[4], a[5], a[6], a[7]); } } - BAR(); // (2) + lds_barrier(); // (2) // ---- V' = gv * (A @ W) -> D (transposed store is one contiguous pair of dwords) { v8f d[NTV]; #pragma unroll for (int i = 0; i < NTV; ++i) d[i] = (v8f){}; -#if APRE -#define paf(ko) apre[(ko) / 16] -#elif GO const unsigned ao = rowGo((unsigned)ars, mt * 16, lim, lane); #define paf(ko) fragGo(ag, ao + (ko)) -#else - const unsigned short* pa = rowG(ag, ars, mt * 16, lim, lane); -#define paf(ko) fragP(pa + (ko)) -#endif -#if LDSO2 - unsigned own[NTV]; -#pragma unroll - for (int i = 0; i < NTV; ++i) { own[i] = ROWO(s.W, WP, (ntb + i) * 16); - LDSOPAQUE(own[i]); } -#define pwnf(i, ko) fragO(sbase, own[i] + (ko) * 2u) -#else const unsigned short* pwn[NTV]; #pragma unroll for (int i = 0; i < NTV; ++i) pwn[i] = rowP(&s.W[0][0], WP, (ntb + i) * 16, lane); #define pwnf(i, ko) fragP(pwn[i] + (ko)) -#endif #pragma unroll for (int sk = 0; sk < BT / 16; ++sk) { - if (TRIL && sk > mt) break; // A is unit lower triangular const int ko = sk * 16; v8bf a = paf(ko); -#if ABL != 3 #pragma unroll for (int i = 0; i < NTV; ++i) d[i] = mma(a, pwnf(i, ko), d[i]); -#endif } -#if SCHED >= 2 // per group: SB steps x (1 global A frag, NTV LDS, NTV WMMA) + // Per group: SB steps x (1 global A fragment, NTV LDS, NTV WMMA). #pragma unroll for (int i = 0; i < BT / (16 * SB); ++i) { -#if NOVM == 0 && APRE == 0 - __builtin_amdgcn_sched_group_barrier(0x020, 2 * SB, SIDV); -#endif - __builtin_amdgcn_sched_group_barrier(0x100, NTV * SB, SIDV); - __builtin_amdgcn_sched_group_barrier(0x008, NTV * SB, SIDV); + __builtin_amdgcn_sched_group_barrier(0x020, 2 * SB, 0); + __builtin_amdgcn_sched_group_barrier(0x100, NTV * SB, 0); + __builtin_amdgcn_sched_group_barrier(0x008, NTV * SB, 0); } -#endif -#if GSPLIT - float gvv[8]; -#pragma unroll - for (int e = 0; e < 8; ++e) gvv[e] = s.gv[mt * 16 + 8 * hi + e]; -#endif #pragma unroll for (int i = 0; i < NTV; ++i) { unsigned short* dp = &s.D[(ntb + i) * 16 + lo][mt * 16 + 8 * hi]; -#if GSPLIT - *(uint2*)dp = F2BF4I(d[i][0]*gvv[0], d[i][1]*gvv[1], - d[i][2]*gvv[2], d[i][3]*gvv[3]); - *(uint2*)(dp + 4) = F2BF4I(d[i][4]*gvv[4], d[i][5]*gvv[5], - d[i][6]*gvv[6], d[i][7]*gvv[7]); -#else - *(uint2*)dp = F2BF4I(d[i][0], d[i][1], d[i][2], d[i][3]); - *(uint2*)(dp + 4) = F2BF4I(d[i][4], d[i][5], d[i][6], d[i][7]); -#endif + *(uint2*)dp = f2bf4(d[i][0], d[i][1], d[i][2], d[i][3]); + *(uint2*)(dp + 4) = f2bf4(d[i][4], d[i][5], d[i][6], d[i][7]); } } -#if !GSPLIT - // K <- gs * K, in place, for the state's V'^T @ K. The state wants - // sum_j e^{gl-g_j} v'_j k_j^T, and (diag(gs) V')^T K == V'^T (diag(gs) K), so the - // per-token factor can ride on either operand; K is the one that is already dead. - // Every raw-K read -- U = K@S and P = Q@K^T -- retired before barrier (2), the state - // matmul is the only reader left, and s.k is restaged from the prefetch registers at - // the top of the next chunk, so the scaling dies with the chunk. Barrier (3) below - // publishes it. 32 elements per lane; the alternative, a second decayed copy of V', - // costs an extra workgroup barrier because s.S is the only buffer free to hold it and - // SWRITE races the state matmul for it. + // K <- gs * K in place, for the state's V'^T @ K: (diag(gs) V')^T K == V'^T (diag(gs) K), + // and K is otherwise dead. All raw-K reads (U, P) retired before barrier (2); s.k is + // restaged next chunk; barrier (3) publishes the scaled K. A decayed copy of V' would need + // an extra barrier, since s.S is the only free buffer and SWRITE races the state matmul. #pragma unroll for (int u = 0; u < BT * (KD / 4) / NTHR; ++u) { const int idx = tid + u * NTHR; const int t = idx / (KD / 4), c = (idx % (KD / 4)) * 4; const float f = s.gv[t]; unsigned short* kp = &s.k[t][c]; - *(uint2*)kp = F2BF4O(bf2f(kp[0]) * f, bf2f(kp[1]) * f, + *(uint2*)kp = f2bf4(bf2f(kp[0]) * f, bf2f(kp[1]) * f, bf2f(kp[2]) * f, bf2f(kp[3]) * f); } -#endif - BAR(); // (3) + lds_barrier(); // (3) // ---- O += sA @ V' ; store. V' also feeds the state update, unchanged. { -#if LDSO2 - unsigned oA = ROWO(s.A, AP, mt * 16); // sA as [n=i][k=j] - unsigned odn[NTV]; - LDSOPAQUE(oA); -#pragma unroll - for (int i = 0; i < NTV; ++i) { odn[i] = ROWO(s.D, AP, (ntb + i) * 16); - LDSOPAQUE(odn[i]); } -#define pAf(ko) fragO(sbase, oA + (ko) * 2u) -#define pdnf(i, ko) fragO(sbase, odn[i] + (ko) * 2u) -#else const unsigned short* pA = rowP(&s.A[0][0], AP, mt * 16, lane); const unsigned short* pdn[NTV]; #pragma unroll for (int i = 0; i < NTV; ++i) pdn[i] = rowP(&s.D[0][0], AP, (ntb + i) * 16, lane); #define pAf(ko) fragP(pA + (ko)) #define pdnf(i, ko) fragP(pdn[i] + (ko)) -#endif #pragma unroll for (int sk = 0; sk < BT / 16; ++sk) { - if (TRIL && sk > mt) break; // sA is masked to lower triangular const int ko = sk * 16; v8bf b = pAf(ko); -#if ABL != 2 #pragma unroll for (int i = 0; i < NTV; ++i) O[i] = mma(pdnf(i, ko), b, O[i]); -#endif } -#if SCHED >= 2 // per group: SB steps x (1 + NTV LDS frags, NTV WMMA) + // Per group: SB steps x (1 + NTV LDS fragments, NTV WMMA). #pragma unroll for (int i = 0; i < BT / (16 * SB); ++i) { - __builtin_amdgcn_sched_group_barrier(0x100, (1 + NTV) * SB, SIDO); - __builtin_amdgcn_sched_group_barrier(0x008, NTV * SB, SIDO); + __builtin_amdgcn_sched_group_barrier(0x100, (1 + NTV) * SB, 0); + __builtin_amdgcn_sched_group_barrier(0x008, NTV * SB, 0); } -#endif } { int tok = mt * 16 + lo; @@ -888,35 +404,23 @@ __global__ __launch_bounds__(NTHR) void r4d_gdn_chunk_scan_kernel( #pragma unroll for (int i = 0; i < NTV; ++i) { unsigned short* q2 = op + (ntb + i) * 16 + 8 * hi; - *(uint2*)q2 = F2BF4O(O[i][0], O[i][1], O[i][2], O[i][3]); - *(uint2*)(q2 + 4) = F2BF4O(O[i][4], O[i][5], O[i][6], O[i][7]); + *(uint2*)q2 = f2bf4(O[i][0], O[i][1], O[i][2], O[i][3]); + *(uint2*)(q2 + 4) = f2bf4(O[i][4], O[i][5], O[i][6], O[i][7]); } } } // ---- S = e^{gl} * S + V'^T @ (gs*K) (B needs K as [dim][token] -> strided fragT) { -#if GSPLIT - const float ec = __expf(cref), lam = __expf(gl - cref); -#else const float ec = __expf(gl); // gl <= 0: no lam, the decay is already on K -#endif #pragma unroll for (int t = 0; t < NST; ++t) #pragma unroll for (int e = 0; e < 8; ++e) St[t][e] *= ec; -#if LDSO2 - unsigned ovn[SVT]; -#pragma unroll - for (int j = 0; j < SVT; ++j) { ovn[j] = ROWO(s.D, AP, (vt0 + j) * 16); - LDSOPAQUE(ovn[j]); } // V': n = v -#define pvnf(j, ko) fragO(sbase, ovn[j] + (ko) * 2u) -#else const unsigned short* pvn[SVT]; #pragma unroll for (int j = 0; j < SVT; ++j) pvn[j] = rowP(&s.D[0][0], AP, (vt0 + j) * 16, lane); #define pvnf(j, ko) fragP(pvn[j] + (ko)) -#endif #pragma unroll for (int sk = 0; sk < BT / 16; ++sk) { v8bf bv[SVT]; @@ -924,42 +428,23 @@ __global__ __launch_bounds__(NTHR) void r4d_gdn_chunk_scan_kernel( for (int j = 0; j < SVT; ++j) bv[j] = pvnf(j, sk * 16); #pragma unroll for (int ki = 0; ki < SKT; ++ki) { -#if ABL == 7 - v8bf ak = fragP(rowP(&s.k[0][0], KP, (kt0 + ki) * 16, lane) + sk * 16); -#else v8bf ak = fragT(&s.k[0][0], KP, (kt0 + ki) * 16, sk * 16, lane); // K^T: m = k-dim -#endif -#if ABL != 1 #pragma unroll for (int j = 0; j < SVT; ++j) St[ki * SVT + j] = mma(ak, bv[j], St[ki * SVT + j]); -#else - (void)ak; -#endif } -#if ABL == 1 -#pragma unroll - for (int j = 0; j < SVT; ++j) (void)bv[j]; -#endif } -#if SCHED >= 2 // per group: SS steps x (SKT fragT = 8 scalar reads each + SVT fragP, NST WMMA) + // Per group: SS steps x (SKT fragT of 8 scalar reads each + SVT fragP, NST WMMA). #pragma unroll for (int i = 0; i < BT / (16 * SS); ++i) { - __builtin_amdgcn_sched_group_barrier(0x100, (8 * SKT + SVT) * SS, SIDS); - __builtin_amdgcn_sched_group_barrier(0x008, NST * SS, SIDS); + __builtin_amdgcn_sched_group_barrier(0x100, (8 * SKT + SVT) * SS, 0); + __builtin_amdgcn_sched_group_barrier(0x008, NST * SS, 0); } -#endif -#if GSPLIT -#pragma unroll - for (int t = 0; t < NST; ++t) -#pragma unroll - for (int e = 0; e < 8; ++e) St[t][e] *= lam; -#endif } - // no barrier: s.S aliases nothing, and barrier (2) already proves every wave - // finished its U/O reads of s.S this chunk + // No barrier needed: s.S aliases nothing, and barrier (2) proves every wave finished its + // U/O reads of s.S this chunk. SWRITE(); - BAR(); // (4) + lds_barrier(); // (4) } if constexpr (!HT) return; @@ -978,12 +463,10 @@ __global__ __launch_bounds__(NTHR) void r4d_gdn_chunk_scan_kernel( } } -// THE SLOT-INDEXED FORM, and the one radiance calls. `sidx` names the state slot each row of the -// batch owns; without it the kernel indexes the cache by ROW, which is the same thing only while -// slots are handed out in batch order. `st_slot` and `st_head` are the strides of the cache -// itself, in elements: a manager that pads a linear slot to the attention page size (radiance -// does) has a slot wider than H*V*K, and the packed formula then reads the wrong memory for every -// slot but the first. Pass sidx = null and either stride 0 for the packed [N, H, V, K] layout. +// Slot-indexed form (the one radiance calls). `sidx` names each batch row's state slot; without +// it the cache is indexed by row. `st_slot` and `st_head` are the cache strides in elements, which +// may exceed H*V*K when a caller pads its slots (vLLM pads to the attention page size). Pass +// sidx = null and strides 0 for the packed [N, H, V, K] layout. extern "C" int r4d_gdn_chunk_scan_k128_v128_c64_bf16_sidx( const void* q, const void* k, const void* v, const void* A, const void* g, const void* beta, const void* h0, void* o, void* ht, const void* cu, @@ -992,10 +475,8 @@ extern "C" int r4d_gdn_chunk_scan_k128_v128_c64_bf16_sidx( int N, int H, int Hg, int K, int V, int bt, float scale, int state_fp16, void* stream) { if (K != KD || V != VD || bt != BT) return -1; - // The kernel maps a v head to its k head with `hq = hv / (H / Hg)`, a truncating divide. An H - // that is not a multiple of Hg sends every v head to the wrong k head -- wrong numbers, no - // error. The two siblings that share the mapping refuse it with the same -2 - // (r4d_gdn_kkt_solve_k128_c64_bf16, r4d_gdn_recurrent_update_k128_v128_bf16_fp32state). + // hq = hv / (H / Hg) truncates: H not a multiple of Hg would silently map v heads to the wrong + // k heads. Refused with -2, as in the kkt_solve and recurrent_update siblings. if (Hg <= 0 || H % Hg) return -2; const long st_head = state_head_stride > 0 ? state_head_stride : (long)VD * KD; const long st_slot = state_slot_stride > 0 ? state_slot_stride : (long)H * VD * KD; @@ -1019,7 +500,7 @@ extern "C" int r4d_gdn_chunk_scan_k128_v128_c64_bf16_sidx( return (int)hipGetLastError(); } -// The packed-layout entry point, for the out-of-tree vLLM caller: one state per batch row, +// Packed-layout entry point for the out-of-tree vLLM caller: one state per batch row, // [N, H, V, K]. extern "C" int r4d_gdn_chunk_scan_k128_v128_c64_bf16( const void* q, const void* k, const void* v, const void* A, const void* g, @@ -1031,8 +512,7 @@ extern "C" int r4d_gdn_chunk_scan_k128_v128_c64_bf16( state_fp16, stream); } -// The geometry baked into the kernel above, so a caller can test a model's GDN shape against it -// instead of hardcoding a copy of these three numbers. +// The compiled geometry, so callers can check a model's GDN shape against it. extern "C" void r4d_gdn_dims(int* head_k, int* head_v, int* chunk) { if (head_k) *head_k = KD; if (head_v) *head_v = VD; @@ -1040,9 +520,7 @@ extern "C" void r4d_gdn_dims(int* head_k, int* head_v, int* chunk) { } // ============================================================== the plugin ABI entry points -// -// The shared operand helpers are r4d_gdn_args.h. See libr4d/r4d_args.h for why there is no -// adapter directory between the core and these launches. +// Shared operand helpers: r4d_gdn_args.h. /* ------------------------------------------------------------------ chunk scan */ enum { CS_Q = 0, CS_K, CS_V, CS_A, CS_G, CS_BETA, CS_H0, CS_CU, CS_O, CS_HT, CS_SIDX }; @@ -1068,29 +546,22 @@ extern "C" int r4d_rad_gdn_chunk_scan(const RadArgs* a, RadStream s) { int rc = seqs_of(cu, &N); if (rc != RAD_OK) return rc; - /* Everything is dense: the entry point takes no pitch at all. */ + /* The entry point takes no pitches: everything must be dense. */ if (!r4d_contig(q) || !r4d_contig(k) || !r4d_contig(v) || !r4d_contig(A) || !r4d_contig(g) || !r4d_contig(bt) || !r4d_contig(o)) return R4D_NO(RAD_E_STRIDE); - /* "bf16 q/k/v/A, fp32 gate/beta/state, bf16 out, fp32 final state" -- this row's own dtype - * line, enforced here rather than merely described. */ + /* bf16 q/k/v/A/out, fp32 gate/beta. */ R4D_DT(q, RAD_BF16); R4D_DT(k, RAD_BF16); R4D_DT(v, RAD_BF16); R4D_DT(A, RAD_BF16); R4D_DT(o, RAD_BF16); R4D_DT(g, RAD_F32); R4D_DT(bt, RAD_F32); - /* THE STATE CACHE IS f32 OR f16 AND THE OPERAND SAYS WHICH. libr4d compiles both -- `SDT` is a - * template parameter on this kernel and on the decode recurrent update, and the state read and - * write ARE those kernels. Taking the width from a declared `state_fp16` parameter instead - * leaves half the instantiation unreachable unless something remembers to set it. The cache's - * dtype is the one honest source: it is a property of the allocation, and the two kernels that - * share the cache cannot disagree about it if both read it off the operand. */ + /* The state cache is f32 or f16, taken from the operand's dtype (a property of the + * allocation), so this kernel and the recurrent update, which share the cache, agree on it. */ const uint32_t st_dt = h0 ? h0->dtype : (ht ? ht->dtype : (uint32_t)RAD_F32); if (st_dt != RAD_F32 && st_dt != RAD_F16) return R4D_NO(RAD_E_DTYPE); if (h0) R4D_DT(h0, st_dt); if (ht) R4D_DT(ht, st_dt); - /* THE SLOT STRIDES COME OFF THE TENSOR, NOT OFF THE SHAPE. A linear slot is padded to the - * attention page size (spec 7.2), so the cache is not dense in [N, H, V, K] and requiring - * contiguity here would refuse the very layout the manager hands out. What has to hold is - * that a head is dense and that h0 and ht agree, because the kernel reads and writes one - * base address for both. */ + /* Slot strides come from the tensor, not from H, V and K, so a cache with padded slots is + * served too; the engine's own state cache is dense ([n_states, H, V, K] per layer). h0 and + * ht must share strides, since the kernel uses one base offset for both. */ long long st_slot = 0, st_head = 0; if (h0) { if (h0->rank < 2) return R4D_NO(RAD_E_SHAPE); @@ -1127,11 +598,11 @@ extern "C" int r4d_rad_gdn_chunk_scan(const RadArgs* a, RadStream s) { const float scale = (float)r4d_getf(a, "scale", 1.0); const int state_fp16 = st_dt == RAD_F16; - return r4d_gdn_chunk_scan_k128_v128_c64_bf16_sidx( + return R4D_RAW(r4d_gdn_chunk_scan_k128_v128_c64_bf16_sidx( q->data, k->data, v->data, A->data, g->data, bt->data, h0 ? h0->data : nullptr, o->data, ht ? ht->data : nullptr, cu->data, sidx ? sidx->data : nullptr, sidx && sidx->rank >= 2 ? (long)sidx->stride[0] : 1, (long)st_slot, (long)st_head, - N, (int)H, (int)Hg, (int)K, (int)V, (int)bt_chunk, scale, state_fp16, s); + N, (int)H, (int)Hg, (int)K, (int)V, (int)bt_chunk, scale, state_fp16, s)); } diff --git a/libr4d/r4d_gdn_conv_tap.h b/libr4d/r4d_gdn_conv_tap.h index 8241bb20..d7e65939 100644 --- a/libr4d/r4d_gdn_conv_tap.h +++ b/libr4d/r4d_gdn_conv_tap.h @@ -1,26 +1,16 @@ // r4d_gdn_conv_tap.h -- the arithmetic of one gated-delta-net convolution output, shared by the // standalone conv kernels (r4d_gdn_conv_w4_h128_bf16.hip) and the recurrent update that folds the // decode convolution into its prologue (r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip). -// One definition is what makes the fold byte-identical to the standalone pair: the activation's -// reciprocal form below changes the last bit of a bf16 output, so two copies that drift apart -// would disagree on a real fraction of channels. +// A single definition keeps the fold byte-identical to the standalone path: the reciprocal form +// below changes the last bit of some bf16 outputs. #pragma once #define R4D_GDN_CONV_W 4 // conv width; the state holds R4D_GDN_CONV_W - 1 taps of history -#ifndef CU_RCP -#define CU_RCP 1 -#endif - -// The divide here is IEEE-exact and the result is rounded to bf16 on the very next instruction, so -// the exactness buys nothing: v_rcp_f32 is 1 ULP (~1e-7 relative) against bf16 s 2^-8 quantum. The -// exact form costs a v_div_scale pair, a v_rcp, a Newton chain, v_div_fmas and v_div_fixup -- about -// ten instructions and a long dependent chain -- where this costs two. The conv update runs four -// waves on five workgroups, so its instruction count IS its time. +// The result is rounded to bf16 immediately, so an IEEE-exact divide buys nothing: v_rcp_f32 is +// 1 ULP (~1e-7 relative) against bf16's 2^-8 quantum. The exact form is ~10 dependent instructions +// (v_div_scale, v_rcp, Newton, v_div_fmas, v_div_fixup); this is two. The conv update runs four +// waves on five workgroups, so its time is its instruction count. __device__ __forceinline__ float cp_silu(float z) { -#if CU_RCP return z * __builtin_amdgcn_rcpf(1.0f + __expf(-z)); -#else - return z / (1.0f + __expf(-z)); -#endif } diff --git a/libr4d/r4d_gdn_conv_w4_h128_bf16.hip b/libr4d/r4d_gdn_conv_w4_h128_bf16.hip index beebed0c..ab3a1c00 100644 --- a/libr4d/r4d_gdn_conv_w4_h128_bf16.hip +++ b/libr4d/r4d_gdn_conv_w4_h128_bf16.hip @@ -11,28 +11,20 @@ // gate g = -exp(A_log) . softplus(a + dt_bias), beta = sigmoid(b) // cumsum g summed along the chunk, which is what the scan actually consumes // -// It replaces causal_conv1d_fn + fused_post_conv_prep + chunk_local_cumsum. The pair it replaces -// spends most of its time moving the conv output: causal_conv1d_fn writes all conv_dim channels of -// every token to HBM and fused_post_conv_prep reads every one of them straight back, which at this -// model's shape is 34 MB out and 34 MB in per layer per rank for a tensor that is dead two -// microseconds later. Here the conv output only ever exists in registers. +// Replaces causal_conv1d_fn + fused_post_conv_prep + chunk_local_cumsum. The unfused pair writes +// the whole conv output to HBM and reads it straight back (34 MB each way per layer per rank at +// this model's shape); here it stays in registers. // -// The layout falls out of the l2norm. A workgroup is HPB waves, one wave per 128-dim head, one -// lane per four dims -- so the norm of a head is a wave reduction with no LDS and no barrier, and -// four contiguous bf16 per lane is one 8-byte access on both sides. Channel groups are counted in -// heads rather than in channels so that a group never straddles the q/k/v boundaries (they fall on -// head multiples at every tensor-parallel size). +// Layout: a workgroup is HPB waves, one wave per 128-dim head, four dims per lane, so a head's +// norm is a barrier-free wave reduction and each lane does one 8-byte access. Channel groups are +// counted in heads so a group never straddles the q/k/v boundaries (head multiples at every TP). // -// Tokens are blocked by the chunk, 64, because the cumsum is per chunk: the whole scan is then a -// wave-level prefix over 32 lanes holding two tokens each, and no workgroup needs another's -// partial sums. The conv reads three tokens of halo per block, 4.7% of the traffic, which is -// cheaper than the barrier a shared staging buffer would need. +// Tokens are blocked by the 64-token chunk because the cumsum is per chunk: it becomes a wave +// prefix over 32 lanes of two tokens each. Each block reads three tokens of halo (4.7% of the +// traffic), cheaper than a barrier around a shared staging buffer. // -// The conv output is rounded to bf16 BEFORE the norm and the store, which is what the two kernels -// it replaces do (the conv writes a bf16 tensor and the prep reads it back). Keeping the fp32 -// accumulator through the norm would be slightly finer and slightly different; matching is worth -// more than the last half ULP here, because it makes this kernel a bit-for-bit drop-in for the -// pair it replaces. +// The conv output is rounded to bf16 before the norm and the store, as in the unfused pair, so +// this kernel is a bit-exact drop-in for it. #include #include "r4d.h" #include "r4d_gdn_args.h" @@ -44,66 +36,37 @@ #define CP_BT 64 // token block = the scan's chunk, so the cumsum stays wave-local #define CP_W R4D_GDN_CONV_W // conv width #define CP_ST (CP_W - 1) // conv state depth -// CU_MAXT: tokens the DECODE update pre-loads into registers. 16 is about 13% slower than 8: the -// sixteen ushort4 cost more in register pressure and predicated-load exec-mask work than the round -// trips they hide, and the compiler already batches the loop's loads. -// 1 disables it (slen is num_spec+1 > 1 on every speculative step). -// CU_STATIC=1: index the xb[] preload with a COMPILE-TIME t. The preload exists so a token tap is -// not an HBM round trip, but a register array under a RUNTIME index is not a register read: the -// compiler builds a select tree for it. With both readers -- the token loop and the cache rewrite -// -- indexing at runtime, the HPB=1 ISA census is 2033 instructions for 41 loads and 29 stores, -// 193 s_cselect_b32 + 138 s_cmp_eq_u32 + 132 v_cndmask_b16 of it: about a third of the kernel -// choosing which register to read. That is also why a larger CU_MAXT loses -- twice the array is -// twice the tree, not twice the reuse. Unrolling both readers over CU_MAXT with a wave-uniform -// `t < slen` guard turns every access into a static index; `slen` is uniform, so the guard is a -// scalar branch, not a per-lane select. -#ifndef CU_STATIC -#define CU_STATIC 1 -#endif -// CU_ISSUE=1: put the input preload AHEAD of the history load. `xrow` depends only on the token -// range and this lane's channels, while `hp` depends on `slot`, which has to come back from -// cache_idx first -- and the history block consumes its loads immediately (bf2f), so the compiler -// waits on them before it issues a single input load and the two HBM round trips run back to back. -// One wave per SIMD means nothing else hides either of them. -#ifndef CU_ISSUE -#define CU_ISSUE 1 -#endif -#ifndef CU_MAXT +// Tokens the decode update preloads into registers. 16 is ~13% slower than 8 (register pressure +// and predicated-load overhead outweigh the hidden round trips). +// +// The xb[] preload is indexed with a compile-time t: a register array under a runtime index +// compiles to a select tree (about a third of the kernel's instructions at HPB=1). Both readers +// unroll over CU_MAXT with a wave-uniform `t < slen` guard, so every index is static and the guard +// is a scalar branch. The preload is issued before the history load: the history address depends +// on `slot` (a cache_idx load) and its values are consumed immediately, so otherwise the two +// memory round trips serialise, with no other wave on the SIMD to hide them. #define CU_MAXT 8 -#endif -// WVEC: read a channel's CP_W conv weights as one vector load instead of CP_W scalar ones. -#ifndef WVEC -#define WVEC 1 -#endif #define CP_DPL 4 // dims per lane (CP_HD / 32) -// cp_silu, and the reason it is a reciprocal and not a divide, is r4d_gdn_conv_tap.h: the -// recurrent update folds the decode convolution in and has to compute the same bits. +// cp_silu is in r4d_gdn_conv_tap.h, shared with the recurrent update's folded convolution. -// softplus, in the two-sided form FLA uses, with the same large-x cutoff +// softplus, in FLA's two-sided form with the same large-x cutoff __device__ __forceinline__ float cp_softplus(float x, float thr) { if (x > thr) return x; return (x > 0.0f) ? (x + __logf(1.0f + __expf(-x))) : __logf(1.0f + __expf(x)); } -// a and b arrive as the layer holds them: a chunk() of the ba projection, so bf16 and strided by -// 2*H, not the fp32 contiguous pair FLA's own kernels are usually handed. Reading them where they -// lie is what keeps this a single kernel -- a .float().contiguous() per tensor per layer would put -// two more launches and 0.6 MB back on the path this exists to shorten. +// a and b are read where they lie: a chunk() of the ba projection, bf16 with row stride 2*H (or +// fp32), avoiding a .float().contiguous() copy and two launches per layer. template __device__ __forceinline__ float cp_ab(const void* p, size_t i) { return ABF16 ? bf2f(((const unsigned short*)p)[i]) : ((const float*)p)[i]; } -// `has_init` SAYS WHETHER THE SLOT HOLDS A HISTORY, and its width is the caller's -- the flag is -// the caller's answer, like ab_is_bf16 above. Guessing the width is not safe. The engine hands -// over RadBatch::ctx_lens, which is int32 like every derived buffer the core computes; reading -// that as `unsigned char` takes byte n of an int32 array. At n = 0 with a cold sequence that is 0 -// by luck and correct; at the SECOND chunk of a long prompt, ctx_len 512 has a zero low byte, so -// the conv window would silently start from zeros and the sequence would lose its history. libref -// reads the operand through its own dtype and is right either way, so a width mismatch shows up -// only as the two implementations disagreeing, with the fast path wrong. +// `has_init` says whether the slot holds a history; its element width (int32 or byte) is given by +// the caller. The engine passes RadBatch::ctx_lens (int32); read as bytes, a ctx_len of 512 would +// look like 0 and the conv window would silently start from zeros. __device__ __forceinline__ bool r4d_has_init(const void* p, int i32, int n) { if (!p) return false; return i32 ? ((const int*)p)[n] != 0 : ((const unsigned char*)p)[n] != 0; @@ -128,8 +91,8 @@ void r4d_gdn_conv_prep_kernel(const unsigned short* __restrict__ x, long xpitch, { const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; - // flat chunk id -> (sequence, chunk); see r4d_gdn_kkt_solve_k128_c64_bf16.hip for why the grid is an upper - // bound rather than the exact count + // flat chunk id -> (sequence, chunk); the grid is an upper bound (see + // r4d_gdn_kkt_solve_k128_c64_bf16.hip) int n = -1, t0 = 0, bos = 0, rows = 0, slen = 0; { int acc = 0, want = blockIdx.x; @@ -145,8 +108,7 @@ void r4d_gdn_conv_prep_kernel(const unsigned short* __restrict__ x, long xpitch, const bool first = (t0 == 0); // ---- the gating half, on one workgroup per chunk ---------------------------------------- - // g and beta come from a and b alone, so this is independent of the convolution; it rides on - // the y == 0 workgroup rather than costing a launch of its own. + // g and beta depend only on a and b; computed by the y == 0 workgroups instead of a launch. if (blockIdx.y == 0) { for (int hv = warp; hv < H; hv += HPB) { const float alog = __expf(A_log[hv]), dtb = dt_bias[hv]; @@ -192,8 +154,8 @@ void r4d_gdn_conv_prep_kernel(const unsigned short* __restrict__ x, long xpitch, bs[c] = bias ? bf2f(bias[d0 + c]) : 0.0f; } - // window[i] holds x[t - (W-1) + i]; seed it from the previous tokens, or from the conv state - // cache when this is the first chunk of the sequence + // win[i] holds x[t - (W-1) + i]; seeded from the previous tokens, or from the conv state cache + // at the sequence's first chunk float win[CP_W][CP_DPL]; { const bool init = first && r4d_has_init(has_init, hi_i32, n); @@ -213,17 +175,15 @@ void r4d_gdn_conv_prep_kernel(const unsigned short* __restrict__ x, long xpitch, } // ---- write the new conv state, from x, at the sequence's first chunk --------------------- - // Ordering: the cache line is updated in place, so the read above and this write must be in the - // same workgroup for the same channels -- which they are, and this is why the FIRST chunk owns - // the write even though the tokens it stores belong to the last one. + // The cache is updated in place, so the read above and this write must be in the same workgroup + // for the same channels. That is why the first chunk writes the state even though its tokens + // come from the last chunk. if (first && cache_idx) { unsigned short* sp = cstate + (size_t)cache_idx[(size_t)n * ci_stride] * cs_seq + (size_t)d0 * cs_dim; const bool init = r4d_has_init(has_init, hi_i32, n); - // Channel-major, because the cache is [dim][slot] with the slot contiguous: this lane owns - // CP_DPL consecutive channels, so its CP_DPL*CP_ST shorts are one contiguous run and the wave - // covers 32 of those back to back. A slot-major order would make every store a strided 2-byte - // scalar. + // Channel-major: the cache is [dim][slot] with slot contiguous, so a lane's CP_DPL*CP_ST + // shorts are one contiguous run. Slot-major order would make every store a strided scalar. #pragma unroll for (int c = 0; c < CP_DPL; ++c) { #pragma unroll @@ -253,7 +213,7 @@ void r4d_gdn_conv_prep_kernel(const unsigned short* __restrict__ x, long xpitch, float acc = bs[c]; #pragma unroll for (int i = 0; i < CP_W; ++i) acc += wt[i][c] * win[i][c]; - // the pair this replaces rounds here, on the way to HBM; keep that + // round as the unfused pair does on the way to HBM o[c] = bf2f(f2bf(cp_silu(acc))); } @@ -318,15 +278,10 @@ extern "C" int r4d_gdn_conv_prep_w4_h128_bf16( } // --------------------------------------------------------------------------------------------- -// The decode-time convolution. Same depthwise causal filter, but the tokens of a step are a -// speculative window rather than a chunk, and the state cache is a rolling buffer of -// width-1 + num_spec entries rather than width-1: a step reads its window starting at the slot -// the last ACCEPTED token left behind, and rewrites the buffer shifted by one so the next step -// can do the same. That offset is the only thing the caller has to get right, and it is why this -// is a separate entry point rather than a flag on the one above. -// -// It writes q, k and v in their own layouts, which also removes the torch.cat the reference layer -// needs to make the three views contiguous for the recurrent kernel. +// Decode-time convolution. Same filter, but a step's tokens are a speculative window and the +// state cache is a rolling buffer of width-1 + num_spec entries: a step reads its window starting +// at the slot the last accepted token left, and rewrites the buffer shifted by one. Writes q, k +// and v in their own layouts (no torch.cat for the recurrent kernel). // --------------------------------------------------------------------------------------------- template __global__ __launch_bounds__(HPB * 32) @@ -346,55 +301,42 @@ void r4d_gdn_conv_update_kernel(const unsigned short* __restrict__ x, long xpitc const int bos = cu[n], slen = cu[n + 1] - bos; if (slen <= 0) return; const int slot = cache_idx[(size_t)n * ci_stride]; - // A NEGATIVE slot is the pad and ZERO IS A REAL SLOT. `slot <= 0` would be vLLM's NULL_BLOCK_ID - // convention, where 0 is reserved; radiance's block manager hands out 0-based state slots, so - // that test would skip the FIRST sequence on the card entirely -- no convolution at all, on - // every decode step and every linear-attention layer, silently. libref skips only a negative - // slot (libref/ref_gdn.cpp) and so does every index in libr4d. + // A negative slot is padding; 0 is a real slot. (vLLM reserves 0 as NULL_BLOCK_ID, but this + // engine's state slots are 0-based, as in libref/ref_gdn.cpp.) if (slot < 0) return; const int off = naccept ? (naccept[n] - 1) : 0; - // the cache depth this step actually uses; FLA shrinks the caller's max_query_len bound by the - // tokens this sequence did not bring + // cache depth this step uses: as in FLA, the bound shrinks by the tokens this sequence lacks const int slen_eff = state_len_max - (maxq - slen); const int unit = blockIdx.y * HPB + warp; const int d0 = unit * CP_HD + lane * CP_DPL; - // The weight of one channel is CP_W contiguous shorts, so a lane's four channels are four - // vector loads, not sixteen scalar ones. + // A channel's weights are CP_W contiguous shorts: one vector load per channel. + static_assert(CP_W == 4, "the weight load reads a channel's taps as one ushort4"); float wt[CP_W][CP_DPL], bs[CP_DPL]; #pragma unroll for (int c = 0; c < CP_DPL; ++c) { - if (WVEC && CP_W == 4) { - const ushort4 w4 = *(const ushort4*)(wgt + (size_t)(d0 + c) * CP_W); - const unsigned short* ws = (const unsigned short*)&w4; + const ushort4 w4 = *(const ushort4*)(wgt + (size_t)(d0 + c) * CP_W); + const unsigned short* ws = (const unsigned short*)&w4; #pragma unroll - for (int i = 0; i < CP_W; ++i) wt[i][c] = bf2f(ws[i]); - } else { -#pragma unroll - for (int i = 0; i < CP_W; ++i) wt[i][c] = bf2f(wgt[(size_t)(d0 + c) * CP_W + i]); - } + for (int i = 0; i < CP_W; ++i) wt[i][c] = bf2f(ws[i]); bs[c] = bias ? bf2f(bias[d0 + c]) : 0.0f; } - // ADDRESS ARITHMETIC IS WHAT THIS KERNEL SPENDS ITS TIME ON. Indexing with (size_t)i * cs_tok - // and (size_t)(bos + ti) * xpitch gives every one of the ~40 cache stores and every input tap a - // 64-bit multiply: that form costs 1297 instructions -- 252 of them s_wait_alu and about 330 - // scalar address ALU -- to move 290 KB. The strides are small (cs_dim is the per-channel row, a - // handful of tokens; xpitch is conv_dim), so every offset below is an int taken from a base - // pointer that already carries the 64-bit part, and the loops walk their pointers rather than - // re-deriving them. + // This kernel's time is address arithmetic. size_t indexing gives each of the ~40 cache stores + // and every input tap a 64-bit multiply. The strides are small, so offsets are 32-bit ints off + // base pointers that carry the 64-bit part, and loops walk their pointers. const int csd = (int)cs_dim, cst = (int)cs_tok, xpi = (int)xpitch; unsigned short* const sp = cstate + (size_t)slot * cs_seq + (size_t)d0 * cs_dim; const unsigned short* const xrow = x + (size_t)bos * xpitch + d0; -#if CU_ISSUE + // Every input load of the step is issued before any is waited on; the cache rewrite below + // reuses the same values. ushort4 xb[CU_MAXT]; const bool xpre = (slen <= CU_MAXT); #pragma unroll for (int t = 0; t < CU_MAXT; ++t) if (xpre && t < slen) xb[t] = *(const ushort4*)(xrow + t * xpi); -#endif float win[CP_W][CP_DPL]; unsigned short hist[CP_ST][CP_DPL]; // the raw history, for the shifted rewrite { @@ -412,21 +354,7 @@ void r4d_gdn_conv_update_kernel(const unsigned short* __restrict__ x, long xpitc const int hq = unit, hk = unit - Hg, hv = unit - 2 * Hg; const int region = (unit < Hg) ? 0 : ((unit < 2 * Hg) ? 1 : 2); - // This step's inputs, all issued before the first is waited on. With the load inside the loop - // each of the (num_spec + 1) four-tap taps pays an HBM round trip that nothing hides: a decode - // step launches one wave per channel group, so there is no other wave on the SIMD to run - // meanwhile. They are also exactly the values the cache rewrite at the bottom re-reads. -#if !CU_ISSUE - ushort4 xb[CU_MAXT]; - const bool xpre = (slen <= CU_MAXT); -#pragma unroll - for (int t = 0; t < CU_MAXT; ++t) - if (xpre && t < slen) xb[t] = *(const ushort4*)(xrow + t * xpi); -#endif - - // The destination of a token is the previous one plus a fixed stride, so it is walked rather - // than rebuilt: recomputing ((bos + t) * H + hv) * CP_HD per token is a 64-bit multiply each - // time. + // Output pointer walked by a fixed stride per token, avoiding a 64-bit multiply each. unsigned short* op = (region == 2) ? (v + ((size_t)bos * H + hv) * CP_HD + lane * CP_DPL) : ((region ? k : q) + ((size_t)bos * Hg + (region ? hk : hq)) * CP_HD + lane * CP_DPL); @@ -452,10 +380,9 @@ void r4d_gdn_conv_update_kernel(const unsigned short* __restrict__ x, long xpitc _Pragma("unroll") \ for (int c = 0; c < CP_DPL; ++c) win[i][c] = win[i + 1][c]; \ } -#if CU_STATIC if (xpre) { - // A GUARD, NOT A BREAK. `#pragma unroll` needs a constant trip count; a data-dependent exit - // leaves the loop rolled and `t` a runtime variable again, which is the whole thing being fixed. + // A guard, not a break: a data-dependent exit would leave the loop rolled and t a runtime + // index again. #pragma unroll for (int t = 0; t < CU_MAXT; ++t) { if (t < slen) CU_TOKEN_BODY(xb[t]) // static index: a register read, not a tree @@ -463,66 +390,40 @@ void r4d_gdn_conv_update_kernel(const unsigned short* __restrict__ x, long xpitc } else { for (int t = 0; t < slen; ++t) CU_TOKEN_BODY(*(const ushort4*)(xrow + t * xpi)) } -#else - for (int t = 0; t < slen; ++t) - CU_TOKEN_BODY(xpre ? xb[t] : *(const ushort4*)(xrow + t * xpi)) -#endif - // Rewrite the cache shifted by one: the tail of the old history, then this step's tokens. The - // first CP_ST-1 entries are exactly the history already in registers, so the rewrite costs no - // extra reads -- and reading before writing is what makes the in-place update safe. - // Channel-major for the same reason as the prefill path, and it matters more here: this is - // width-1 + num_spec slots per channel, so the slot-major order made it 44 strided 2-byte - // stores per lane where channel-major is one 88-byte run. - // The two halves of this run have different sources -- the tail of the old history, then this - // step's tokens -- and testing for it per store put a branch and a select in front of every one - // of the ~40. The split point is a loop bound instead. `nh` is CP_W-2 by construction - // (state_len_max is (CP_W-1)+(maxq-1) and slen_eff takes off the tokens this sequence did not - // bring), but it is computed rather than assumed so a caller that shrinks the window differently - // still gets the shipped answer. + // Rewrite the cache shifted by one: the tail of the old history (already in registers, read + // before any write, so the in-place update is safe), then this step's tokens. Channel-major, as + // in prefill: one contiguous run per lane instead of strided 2-byte stores. + // The split between the two sources is a loop bound, not a per-store test. `nh` is CP_W-2 on the + // shipped path but computed, so a caller that shrinks the window differently stays correct. const int VAL = CP_W - 2; const int nh = slen_eff - slen < 0 ? 0 : (slen_eff - slen); #pragma unroll for (int c = 0; c < CP_DPL; ++c) { unsigned short* dst = sp + c * csd; -#if CU_STATIC - // The history half is bounded by the array it reads: `hist[i + 1]` with i < nh already required - // nh <= CP_ST - 1, so unrolling to that bound reads exactly what the runtime loop did. + // History half, unrolled to hist's bound (i + 1 < CP_ST). #pragma unroll for (int i = 0; i + 1 < CP_ST; ++i) if (i < nh && i < slen_eff) dst[i * cst] = hist[i + 1][c]; - // The token half, walked by TOKEN rather than by slot, so the index into xb is the loop counter. + // Token half, walked by token so the xb index is the loop counter. if (xpre) { #pragma unroll for (int t = 0; t < CU_MAXT; ++t) { const int i = t + VAL; if (i >= nh && i < slen_eff && t < slen) { - // NOT `((const unsigned short*)&xb[t])[c]`. Taking the address of an element makes the - // whole array address-taken, and an address-taken array does not become registers however - // static the index is -- that one `&` costs 80 bytes a thread of SCRATCH under the - // preload. With t and c both compile-time this ternary folds to a register read. + // Not `((const unsigned short*)&xb[t])[c]`: taking an element's address forces the + // whole array to scratch. With t and c compile-time, this ternary is a register read. const ushort4 vv = xb[t]; dst[i * cst] = (c == 0) ? vv.x : (c == 1) ? vv.y : (c == 2) ? vv.z : vv.w; } } } - // Whatever the two loops above did not cover: a slot whose token is outside [0, slen), and the - // whole range when the caller brought more tokens than the preload holds. Both are empty on the - // shipped path (slen_eff is slen + CP_ST - 1 and nh is CP_W - 2), so this stores nothing. + // Remainder: slots whose token is outside [0, slen), or the whole range when slen exceeds the + // preload. Empty on the shipped path. for (int i = nh; i < slen_eff; ++i) { const int ti = i - VAL; if (!xpre || ti < 0 || ti >= slen) dst[i * cst] = xrow[ti * xpi + c]; } -#else - int i = 0; - for (; i < nh && i < slen_eff; ++i) dst[i * cst] = hist[i + 1][c]; - for (; i < slen_eff; ++i) { - const int ti = i - VAL; - dst[i * cst] = (xpre && ti >= 0 && ti < slen) - ? ((const unsigned short*)&xb[ti])[c] - : xrow[ti * xpi + c]; - } -#endif } #undef CU_TOKEN_BODY } @@ -537,9 +438,8 @@ extern "C" int r4d_gdn_conv_update_w4_h128_bf16( const int units = 2 * Hg + H; int hpb = 8; while (hpb > 1 && (Hg % hpb || H % hpb)) hpb >>= 1; - // A decode step is a handful of sequences, so the channel grouping is what decides whether the - // grid covers the device: at 8 sequences and 8 heads per block this launches 40 workgroups for - // 64 CUs. Narrow the block until there are enough of them. + // A decode step has few sequences, so narrow the channel group until the grid covers the + // device (8 sequences at 8 heads per block would be 40 workgroups for 64 CUs). while (hpb > 1 && (long)N * (units / hpb) < 256) hpb >>= 1; dim3 grid(N, units / hpb), blk(hpb * 32); #define CU_LAUNCH(P) \ @@ -559,14 +459,9 @@ extern "C" int r4d_gdn_conv_update_w4_h128_bf16( return (int)hipGetLastError(); } -// THE OPERAND ENUMS CARRY AN `OPD_` PREFIX: this kernel's own tile constants are already called -// CP_W and CP_ST, and an unprefixed operand index named CP_W in the same translation unit is a -// redefinition -- caught by the compiler, but only because the spellings happen to collide. The -// prefix says which namespace a name is in. // ============================================================== the plugin ABI entry points -// -// The shared operand helpers are r4d_gdn_args.h. See libr4d/r4d_args.h for why there is no -// adapter directory between the core and these launches. +// Shared operand helpers: r4d_gdn_args.h. Operand enums use an OPD_ prefix because CP_W and CP_ST +// are already kernel constants in this unit. /* ------------------------------------------------------------------ conv prep */ @@ -596,8 +491,8 @@ extern "C" int r4d_rad_gdn_conv_prep(const RadArgs* a, RadStream s) { if (!x || !w || !alog || !dtb || !cst || !cu || !q || !k || !v || !g || !beta) return R4D_NO(RAD_E_INVAL); - /* Optional in the SCHEMA so docs/OPS.md's shorter list stays a positional prefix, required by - * the KERNEL: it dereferences all three unconditionally. Named rather than crashed. */ + /* Optional in the schema (so docs/OPS.md's shorter list stays a positional prefix) but + * required here: the kernel dereferences all three. */ if (!ta || !tb || !cidx) return R4D_NO(RAD_E_INVAL); if (x->rank < 2 || q->rank != 3 || k->rank != 3 || v->rank != 3) return R4D_NO(RAD_E_SHAPE); @@ -607,8 +502,8 @@ extern "C" int r4d_rad_gdn_conv_prep(const RadArgs* a, RadStream s) { int rc = seqs_of(cu, &N); if (rc != RAD_OK) return rc; - /* x may be a padded VIEW -- the qkvz split the layer hands it -- so its row pitch is an - * argument. Its inner axes still have to be tight. */ + /* x may be a padded view (the layer's qkvz split), so its row pitch is an argument; inner + * axes must be dense. */ const long long xpitch = r4d_row_pitch(x); if (xpitch < 0) return R4D_NO(RAD_E_STRIDE); const long long ab_stride = r4d_row_pitch(ta); @@ -633,32 +528,27 @@ extern "C" int r4d_rad_gdn_conv_prep(const RadArgs* a, RadStream s) { const int width = (int)r4d_geti_or(a, "conv_width", 4); const float thr = (float)r4d_getf(a, "softplus_thr", 20.0); - /* libr4d's l2 norm is rsqrt(ss + 1e-6f) with the epsilon COMPILED IN, not an argument. A - * caller that names a different one is asking for arithmetic this kernel does not do, and - * running it anyway would be a silently different normalisation. Refused by name instead. */ + /* The l2 norm epsilon is compiled in (1e-6f); refuse any other value. */ if ((float)r4d_getf(a, "l2_eps", 1e-6) != 1e-6f) return R4D_NO(RAD_E_UNSUPPORTED); - /* `a` and `b` may be bf16 or f32; libr4d takes a flag rather than two entry points. */ + /* a and b may be bf16 or f32 (a flag, not two entry points). */ const int ab_is_bf16 = (ta->dtype == RAD_BF16) ? 1 : 0; if (tb->dtype != ta->dtype) return R4D_NO(RAD_E_DTYPE); if (!ab_is_bf16 && ta->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); - /* "bf16 x / weights / conv state / q,k,v out, fp32 a,b and gate/beta out". The CONV WEIGHT is - * bf16: the kernel takes it as `const unsigned short*` and reads it through bf2f. */ + /* bf16 x, weights, conv state and q/k/v; fp32 A_log, dt_bias, g and beta. */ R4D_DT(x, RAD_BF16); R4D_DT(w, RAD_BF16); R4D_DT(cst, RAD_BF16); R4D_DT(q, RAD_BF16); R4D_DT(k, RAD_BF16); R4D_DT(v, RAD_BF16); R4D_DT(alog, RAD_F32); R4D_DT(dtb, RAD_F32); R4D_DT(g, RAD_F32); R4D_DT(beta, RAD_F32); - return r4d_gdn_conv_prep_w4_h128_bf16( + return R4D_RAW(r4d_gdn_conv_prep_w4_h128_bf16( x->data, (long)xpitch, w->data, b ? b->data : nullptr, cst->data, (long)cst->stride[0], (long)cst->stride[1], (long)cst->stride[2], cidx->data, (long)cidx->stride[0], hin ? hin->data : nullptr, - /* The WIDTH of has_init, not a guess: the engine hands over RadBatch::ctx_lens, which is - * int32 like every derived buffer. Reading it as bytes is silent for a cold first chunk - * and wrong for every one after it. */ + /* has_init element width (see r4d_has_init) */ hin && (hin->dtype == RAD_I32 || hin->dtype == RAD_U32), ta->data, tb->data, (long)ab_stride, ab_is_bf16, alog->data, dtb->data, q->data, k->data, v->data, g->data, beta->data, - cu->data, N, (int)T, (int)H, (int)Hg, (int)K, (int)V, width, thr, s); + cu->data, N, (int)T, (int)H, (int)Hg, (int)K, (int)V, width, thr, s)); } /* ------------------------------------------------------------------ conv update */ @@ -698,35 +588,29 @@ extern "C" int r4d_rad_gdn_conv_update(const RadArgs* a, RadStream s) { if (H == 0 || Hg == 0 || H % Hg) return R4D_NO(RAD_E_SHAPE); if (v->shape[0] != T || k->shape[0] != T) return R4D_NO(RAD_E_SHAPE); - /* "bf16 x / weights / conv state / q,k,v out" -- same casts as the prefill conv. */ + /* bf16 x, weights, conv state and q/k/v, as in the prefill conv. */ R4D_DT(x, RAD_BF16); R4D_DT(w, RAD_BF16); R4D_DT(cst, RAD_BF16); R4D_DT(q, RAD_BF16); R4D_DT(k, RAD_BF16); R4D_DT(v, RAD_BF16); const int width = (int)r4d_geti_or(a, "conv_width", 4); - /* THE TWO WINDOW ARGUMENTS DESCRIBE ONE WINDOW, SO ONLY ONE OF THEM IS FREE. The state cache - * is a rolling window read at the slot the last ACCEPTED token left, which is how a - * speculative rejection becomes a change of read offset rather than a recompute (spec 10). - * The kernel lays it out as `width - 2` history entries followed by the step's tokens, and it - * finds the split as `state_len_max - max_query_len` -- so that difference MUST be width - 2, - * whatever the two of them are individually. The cache depth fixes one; the other follows. + /* state_len_max and max_query_len describe one window, so only one is free. The state cache + * is a rolling window read at the slot the last accepted token left, so a speculative + * rejection is a change of read offset, not a recompute (spec 10). The kernel splits it into + * `width - 2` history entries and the step's tokens at state_len_max - max_query_len, so that + * difference must be width - 2; max_query_len follows from the cache depth. * - * DO NOT DERIVE max_query_len FROM THE STEP. The mean tokens per sequence is wrong twice over: - * it is not the max when one request in the step drafts and another does not, and even the max - * is not what this kernel wants, because the pool is sized for the deepest draft the - * DEPLOYMENT allows. A decode step that drafts nothing would then put the split at - * width - 2 + n_spec instead of width - 2. The history half runs past what the kernel has in - * registers, this step's tokens land outside the range the next step reads, and the - * convolution advances over a window that never changes: the model stops hearing its own last - * three tokens and repeats one phrase forever. */ + * Do not derive max_query_len from the step: the pool is sized for the deployment's deepest + * draft, and a non-drafting step would misplace the split, so the convolution would stop + * seeing the latest tokens and the model would loop on one phrase. */ const long long state_len_max = cst->shape[2]; const long long mql = state_len_max - (width - 2); if (width < 2 || mql < 1) return R4D_NO(RAD_E_SHAPE); - return r4d_gdn_conv_update_w4_h128_bf16( + return R4D_RAW(r4d_gdn_conv_update_w4_h128_bf16( x->data, (long)xpitch, w->data, b ? b->data : nullptr, cst->data, (long)cst->stride[0], (long)cst->stride[1], (long)cst->stride[2], (int)state_len_max, sidx->data, (long)sidx->stride[0], nacc ? nacc->data : nullptr, q->data, k->data, v->data, cu->data, - N, (int)H, (int)Hg, (int)K, (int)V, width, (int)mql, s); + N, (int)H, (int)Hg, (int)K, (int)V, width, (int)mql, s)); } diff --git a/libr4d/r4d_gdn_gated_norm_had_quant_i8.hip b/libr4d/r4d_gdn_gated_norm_had_quant_i8.hip index 87aac553..24f3d661 100644 --- a/libr4d/r4d_gdn_gated_norm_had_quant_i8.hip +++ b/libr4d/r4d_gdn_gated_norm_had_quant_i8.hip @@ -1,22 +1,20 @@ -// r4d_gdn_gated_norm_had_quant_i8.hip - r4d_gdn_gated_norm_had_quant_i8: the GDN block's gated -// RMS norm, the block Hadamard and the per-row int8 quantiser in one pass. This is out_proj's -// input on the 48 linear-attention layers -- the fourth and last rotated site in a W4A8 layer. +// r4d_gdn_gated_norm_had_quant_i8.hip -- the GDN block's gated RMS norm, block Hadamard and +// per-row int8 quantiser in one pass: out_proj's input on the 48 linear-attention layers (the +// fourth rotated site in a W4A8 layer). // // out = x * rsqrt(mean_head(x^2) + eps) * w * silu(z) // -// TWO DIFFERENT EXTENTS IN ONE KERNEL, which is the whole reason it cannot reuse -// r4d_gdn_gated_rmsnorm_h128_bf16. The RMS is per HEAD (head_v_dim = 128), while the rotation and -// the int8 scale are per TOKEN, over the flattened H*128 that out_proj consumes. So the reduction -// is segmented: a head is 128/VPL consecutive lanes, and an xor exchange with masks below that stays -// inside one head by construction. +// Two extents, which is why r4d_gdn_gated_rmsnorm_h128_bf16 cannot be reused: the RMS is per head +// (head_v_dim = 128), while the rotation and int8 scale are per token over the flattened H*128. +// The reduction is segmented: a head is 128/VPL consecutive lanes, and xor masks below that stay +// inside one head. // // HAD=128 VPL=4 32 lanes/head one head per rotation block // HAD=256 VPL=8 16 lanes/head two heads per block // HAD=512 VPL=16 8 lanes/head four heads per block // -// At width 128 the rotation lines up exactly with head boundaries and mixes only within a head; -// wider widths mix across heads. That is not in itself a reason to prefer one: on this layout the -// activation error is 0.00679 at width 128 against 0.00521 at 512, so the trade is already priced. +// At width 128 the rotation mixes only within a head; wider widths mix across heads. Activation +// error is 0.00679 at width 128 vs 0.00521 at 512. #include "r4d.h" #include "r4d_args.h" #include "r4d_common.h" @@ -25,11 +23,6 @@ #include #include -// 0 = choose the workgroup width from M at launch (see r4d_act_threads in r4d_common.h); a -// non-zero build-time value pins one width instead. -#ifndef R4D_GNHQ_THREADS -#define R4D_GNHQ_THREADS 0 -#endif #define R4D_GNHQ_HEAD 128 template @@ -44,12 +37,9 @@ __global__ __launch_bounds__(THR) void r4d_gdn_gated_norm_had_quant_i8_kernel( const int row = blockIdx.x; const __hip_bfloat16* x = X + (size_t)row * xrow; const __hip_bfloat16* z = Z + (size_t)row * zrow; - // zgrp != 0: Z is the INTERLEAVED qkvz projection rather than a compacted copy of the gate, so - // element i of the flattened row lives at (i / zblk) * zgrp + (i % zblk). vLLM materialises that - // copy with `z_out[:] = z` inside _forward_core_rocm; a single-sequence decode step pays it 48 - // times -- 94.5 us of kernel and as much again in launch gap -- for 65 KiB a layer this kernel - // can read where it already is. `zblk` is a multiple of the rotation width, so a HAD-block never straddles - // a group boundary and the offset is constant across the block. + // zgrp != 0: Z is read in place from the interleaved qkvz projection (avoiding vLLM's + // `z_out[:] = z` copy per layer): element i is at (i / zblk) * zgrp + (i % zblk). zblk is a + // multiple of HAD, so a rotation block never straddles a group. const int lane = threadIdx.x & 31, wave = threadIdx.x >> 5; float m = 0.f; @@ -98,7 +88,7 @@ __global__ __launch_bounds__(THR) void r4d_gdn_gated_norm_had_quant_i8_kernel( } } -// The launch, as the plugin ABI's RadLaunchFn. See the note at the head of r4d_quant_act_i8.hip. +// The plugin ABI launch (RadLaunchFn); see the note at the head of r4d_quant_act_i8.hip. enum { GG_X = 0, GG_Z, GG_W, GG_Q, GG_S }; extern "C" int r4d_rad_gdn_gated_norm_hq_i8(const RadArgs* args, RadStream stream) { @@ -127,14 +117,13 @@ extern "C" int r4d_rad_gdn_gated_norm_hq_i8(const RadArgs* args, RadStream strea const long long zrow = r4d_row_pitch(z); if (xrow < 0 || zrow < 0) return R4D_NO(RAD_E_STRIDE); - // Z may be the INTERLEAVED qkvz projection rather than a compacted gate: element i of the - // flattened row lives at (i / zblk) * zgrp + (i % zblk). 0 means contiguous. + // Interleaved-gate layout (see the kernel); zgrp 0 means contiguous. const long long zgrp = r4d_geti_or(args, "zgrp", 0); const long long zblk = r4d_geti_or(args, "zblk", 0); if (zgrp && (zblk % had || zblk < had || zgrp < zblk)) return R4D_NO(RAD_E_INVAL); const float eps = (float)r4d_getf(args, "eps", 1e-6); - const int thr = R4D_GNHQ_THREADS ? R4D_GNHQ_THREADS : r4d_act_threads((int)M, (int)K); + const int thr = r4d_act_threads((int)M, (int)K); const size_t shmem = (size_t)K * sizeof(float) + (thr / 32) * sizeof(float); if (shmem > 65536) return R4D_NO(RAD_E_SCRATCH); const float rn = 1.f / sqrtf((float)had); @@ -144,7 +133,6 @@ extern "C" int r4d_rad_gdn_gated_norm_hq_i8(const RadArgs* args, RadStream strea (const __hip_bfloat16*)r4d_p(z), (const float*)r4d_p(w), (signed char*)r4d_wp(q), \ (float*)r4d_wp(sc), (int)K, xr, zr, (int)zgrp, (int)zblk, eps, rn) #define R4D_GNHQ_T(H) switch (thr) { \ - case 128: R4D_GNHQ_LAUNCH(H, 128); break; \ case 256: R4D_GNHQ_LAUNCH(H, 256); break; \ case 512: R4D_GNHQ_LAUNCH(H, 512); break; \ case 1024: R4D_GNHQ_LAUNCH(H, 1024); break; \ @@ -156,5 +144,5 @@ extern "C" int r4d_rad_gdn_gated_norm_hq_i8(const RadArgs* args, RadStream strea } #undef R4D_GNHQ_T #undef R4D_GNHQ_LAUNCH - return RAD_OK; + return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); } diff --git a/libr4d/r4d_gdn_gated_rmsnorm_h128_bf16.hip b/libr4d/r4d_gdn_gated_rmsnorm_h128_bf16.hip index 493c6a12..0bf97cff 100644 --- a/libr4d/r4d_gdn_gated_rmsnorm_h128_bf16.hip +++ b/libr4d/r4d_gdn_gated_rmsnorm_h128_bf16.hip @@ -3,17 +3,14 @@ // // out[r][d] = x[r][d] . rsqrt(mean_d(x[r][:]^2) + eps) . w[d] . act(z[r][d]) // -// one row per (token, head), 128 wide. It replaces FLA's `rmsnorm_fn` (mamba/ops/layernorm_gated), -// which is the last Triton kernel in the layer. +// one row per (token, head), 128 wide. Replaces FLA's `rmsnorm_fn` (mamba/ops/layernorm_gated). // -// It exists as its own kernel only because the chunked scan cannot host it: that kernel's -// workgroup owns 64 of the 128 v channels of a row (BV=64, and widening it to 128 leaves 24 -// workgroups on 64 CUs), while an RMS needs the whole row. The DECODE kernel does own the whole -// row, so there the same arithmetic is fused into the epilogue and this kernel is not launched at -// all -- see r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip. +// A separate kernel because the chunked scan's workgroup owns only 64 of a row's 128 v channels +// (BV=64; 128 would leave 24 workgroups on 64 CUs). The decode recurrent update owns whole rows and +// fuses this into its epilogue (r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip). // -// One wave per row, four channels per lane: the reduction is five shuffles with no LDS and no -// barrier, and both loads and the store are one 8-byte access per lane. +// One wave per row, four channels per lane: a barrier-free five-shuffle reduction, and one 8-byte +// access per lane for each load and the store. #include #include "r4d.h" #include "r4d_gdn_args.h" @@ -42,10 +39,8 @@ void r4d_gdn_gated_rmsnorm_kernel(const unsigned short* __restrict__ x, const long r = (long)blockIdx.x * GN_NW + warp; if (r >= rows) return; const int d0 = lane * GN_DPL; - // THE GATE CAN BE A COLUMN VIEW, and then its rows are not evenly spaced: the fp8 delta net - // projects [q|k|v|z] in one GEMM, so within a token the `zheads` gate rows are `zrow` apart and - // the next token is `ztok` away, which is wider. zheads <= 0 is the flat case and the one every - // other caller passes. + // The gate may be a column view of a fused [q|k|v|z] projection: within a token the `zheads` + // gate rows are `zrow` apart and the next token is `ztok` away. zheads <= 0 is the flat case. const long zoff = zheads > 0 ? (r / zheads) * ztok + (r % zheads) * zrow : r * zrow; const ushort4 xv = *(const ushort4*)(x + r * xrow + d0); @@ -88,9 +83,7 @@ extern "C" int r4d_gdn_gated_rmsnorm_h128_bf16(const void* x, const void* z, con } // ============================================================== the plugin ABI entry points -// -// The shared operand helpers are r4d_gdn_args.h. See libr4d/r4d_args.h for why there is no -// adapter directory between the core and these launches. +// Shared operand helpers: r4d_gdn_args.h. /* ------------------------------------------------------------------ gated rms norm */ enum { GN_X = 0, GN_Z, GN_W, GN_O }; @@ -100,22 +93,17 @@ extern "C" int r4d_rad_gdn_gated_rmsnorm(const RadArgs* a, RadStream s) { const RadTensor* z = r4d_opt(a, GN_Z); const RadTensor* w = r4d_opt(a, GN_W); const RadTensor* o = r4d_opt(a, GN_O); - /* "bf16 x / z / out, fp32 weight". */ + /* bf16 x, z, out; fp32 weight. */ R4D_DT(x, RAD_BF16); R4D_DT(z, RAD_BF16); R4D_DT(o, RAD_BF16); R4D_DT(w, RAD_F32); if (!x || !z || !w || !o) return R4D_NO(RAD_E_INVAL); if (x->rank < 2 || z->rank < 2 || o->rank < 2) return R4D_NO(RAD_E_SHAPE); if (!r4d_contig(w)) return R4D_NO(RAD_E_STRIDE); - /* ONE ROW IS ONE (token, head), and the three operands do not agree on how that is spelled. - * The norm's input and output are [tokens, heads, channels] -- rank 3, because the chunk scan - * before them requires it -- while the gate arrives as the [tokens, heads*channels] projection - * it was produced by. Both are the same rows in the same order; only the rank differs, and - * taking the last axis as the width would refuse the gate for having 6144 columns instead of - * 128. So the WIDTH comes from the op's `channels` (or x's last axis, which agrees), the row - * COUNT comes from x's extent, and each operand's pitch is read according to which of the two - * shapes it has. libr4d wants a pitch between consecutive (token, head) rows, which for a - * flattened projection is the width itself and not the token stride. */ + /* One row is one (token, head). x and out are [tokens, heads, channels] (rank 3, as the chunk + * scan requires) while the gate may be the flat [tokens, heads*channels] projection. So the + * width comes from `channels` (or x's last axis), the row count from x, and each operand's + * pitch between consecutive (token, head) rows is read per its shape. */ const long long width = r4d_geti_or(a, "channels", x->shape[x->rank - 1]); if (width <= 0 || r4d_numel(x) % width) return R4D_NO(RAD_E_SHAPE); const long long rows = r4d_numel(x) / width; @@ -125,31 +113,29 @@ extern "C" int r4d_rad_gdn_gated_rmsnorm(const RadArgs* a, RadStream s) { const long long orow = gn_row_pitch(o, width); if (xrow < 0 || orow < 0) return R4D_NO(RAD_E_STRIDE); - /* AND THE GATE HAS A THIRD SPELLING: a COLUMN SLICE of a wider projection row, which the fp8 - * delta net hands it because [q|k|v|z] is one GEMM there. Its (token, head) rows are then not - * evenly spaced -- heads are `width` apart inside a token and tokens are the slice's own - * stride apart -- so one pitch cannot describe it and the kernel takes the head count too. - * `zheads` is 0 for the two flat spellings, which is every other caller. */ + /* The gate may also be a column slice of a wider [q|k|v|z] row (fp8 delta net): heads are + * `width` apart within a token and tokens are the slice's stride apart, so the kernel also + * takes the head count. zheads stays 0 for the flat layouts. */ long long zrow = gn_row_pitch(z, width), zheads = 0, ztok = 0; if (zrow < 0 && z->rank == 2 && z->stride[1] == 1 && z->shape[1] % width == 0) { zheads = z->shape[1] / width; ztok = z->stride[0]; zrow = width; - /* The gate's head count has to divide the row count, and where x spells its own it has to - * agree: two operands disagreeing about how many heads a token carries would interleave - * silently rather than run off the end. */ + /* The gate's head count must divide the row count and match x's head axis if it has one; + * a mismatch would silently interleave rows. */ if (zheads <= 0 || rows % zheads) return R4D_NO(RAD_E_SHAPE); if (x->rank >= 3 && x->shape[x->rank - 2] != zheads) return R4D_NO(RAD_E_SHAPE); } if (zrow < 0) return R4D_NO(RAD_E_STRIDE); const float eps = (float)r4d_getf(a, "eps", 1e-6); - /* "silu" or "sigmoid". The integer libr4d wants is produced here and nowhere else. */ + /* "silu" (0) or "sigmoid" (1). */ const int act = r4d_act_code(a, "act", nullptr, -1); if (act != 0 && act != 1) return R4D_NO(RAD_E_INVAL); - return r4d_gdn_gated_rmsnorm_h128_bf16(x->data, z->data, w->data, o->data, - (long)rows, (long)xrow, (long)zrow, (long)orow, - (long)zheads, (long)ztok, (int)width, eps, act, s); + return R4D_RAW(r4d_gdn_gated_rmsnorm_h128_bf16(x->data, z->data, w->data, o->data, + (long)rows, (long)xrow, (long)zrow, + (long)orow, (long)zheads, (long)ztok, + (int)width, eps, act, s)); } diff --git a/libr4d/r4d_gdn_kkt_solve_k128_c64_bf16.hip b/libr4d/r4d_gdn_kkt_solve_k128_c64_bf16.hip index e645b1e9..a748513e 100644 --- a/libr4d/r4d_gdn_kkt_solve_k128_c64_bf16.hip +++ b/libr4d/r4d_gdn_kkt_solve_k128_c64_bf16.hip @@ -2,117 +2,74 @@ // // A = (I + strict_lower(diag(beta) . K K^T . e^{g_i - g_j}))^{-1} per chunk of 64 // -// It replaces FLA's chunk_scaled_dot_kkt_fwd + solve_tril, whose intermediate is a 64x64 fp32 -// matrix per (chunk, head) written to HBM and read straight back -- 16 KB in and 16 KB out per -// chunk-head, for a matrix that is dead the moment the inverse is formed. Here the gram never -// leaves LDS, and only the bf16 inverse is stored. +// Replaces FLA's chunk_scaled_dot_kkt_fwd + solve_tril, whose 64x64 fp32 intermediate per +// (chunk, head) round-trips through HBM. Here the gram stays in LDS and only the bf16 inverse is +// stored. Also: // -// Two structural wins over the pair it replaces, both from doing the whole thing at once: +// * The gram is computed once per k head, not per v head: K K^T does not depend on beta or g, +// so one workgroup owns a (chunk, k head) and applies each v head's scales to it. +// * The gram is computed as its upper-triangle tiles. K K^T is symmetric, and read transposed +// into A's strictly lower half each accumulator holds eight consecutive columns of one row: +// one 16-byte LDS store instead of eight 2-byte ones. // -// * THE GRAM IS COMPUTED ONCE PER K HEAD, NOT ONCE PER V HEAD. K K^T does not depend on beta or -// g, and this model has three v heads per k head, so FLA computes the same 64x64x128 matmul -// three times. One workgroup owns a (chunk, k head) and applies each v head's scales to the -// gram it already holds in registers. -// * THE GRAM IS COMPUTED IN ITS UPPER TRIANGLE. K K^T is symmetric, so the strictly LOWER half -// of A can be read out of the upper tiles -- and that orientation is the one where a WMMA -// accumulator's eight elements are eight CONSECUTIVE columns of one row of A, i.e. one -// 16-byte LDS store instead of eight 2-byte ones. +// The decay is applied per element as e^{g_i-g_j}, not split about a per-chunk reference c: each +// half of e^{g_i-c} * e^{c-g_j} can overflow fp32 on its own. Here the exponent is always <= 0 +// (g decreases along the chunk and only i > j is kept), and the eight exps per tile are cheap in +// a memory-bound kernel. // -// The decay is applied as e^{g_i-g_j} PER ELEMENT, not split across a per-chunk reference. The -// split form (e^{g_i-c} . e^{c-g_j}) is one exp per token instead of eight per tile, and it is what -// the chunked scan uses -- but it only holds while the chunk's gate span stays inside fp32's -// exponent range, and each half can overflow on its own even where the product cannot. Here the -// difference is always <= 0 (g decreases along the chunk and only i > j is kept), so the direct -// form cannot overflow at any span, and the exps it costs are eight per tile against a kernel -// whose cost is memory. -// -// The inverse is blocked 16 -> 32 -> 64. The four diagonal blocks are inverted by fp32 forward -// substitution (one wave each, one lane per column), which is both cheaper than a WMMA Neumann -// series at this size and exact in fp32 -- FLA does the same thing for the same reason. The two -// 32-merges and the 64-merge are WMMA, using the identity +// The inverse is blocked 16 -> 32 -> 64. The four diagonal blocks use fp32 forward substitution +// (one wave each, one lane per column), cheaper than a WMMA Neumann series at this size and exact +// in fp32, as in FLA. The 32-merges and the 64-merge are WMMA, using // // [[P, 0], [R, Q]]^-1 = [[P^-1, 0], [-Q^-1 R P^-1, Q^-1]] // -// Every buffer is named for the layout it holds because the WMMA contract fixes it: -// mma(X, Y) computes X . Y^T from two row-major, k-contiguous operands, so a product's left -// operand must be row-major and its right operand must be stored transposed. An accumulator -// writes its transpose contiguously and its row-major form scattered, which is why the -// intermediates below are staged transposed and the final M is assembled row-major (it is stored -// to HBM by rows). +// mma(X, Y) computes X . Y^T from two k-contiguous operands, so a left operand is row-major and a +// right operand is stored transposed. An accumulator writes its transpose contiguously, so the +// intermediates are staged transposed; the final inverse is assembled row-major for the HBM store. #include #include "r4d.h" +#include "r4d_common.h" // lds_barrier #include "r4d_gdn_args.h" #include "r4d_gdn_wmma.h" #define BT 64 // chunk #define KD 128 // head_k #define NBK 4 // 16x16 blocks per chunk edge -#ifndef AP -#define AP 68 // row pitch of the [BT][BT] buffers, in shorts. 136 B: 8-byte -#endif // aligned for the paired stores, and 136 mod 128 has gcd 8 with - // 128, so 16 rows still cover every bank -#ifndef NW +#define AP 68 // row pitch of the [BT][BT] buffers, in shorts (136 B): 8-byte + // aligned for the paired stores, and 16 rows still cover every + // bank #define NW 4 -#endif #define NTHR (NW * 32) #define NTILE 10 // upper-triangular tiles of a 4x4 tiling #define MAXT ((NTILE + NW - 1) / NW) -#ifndef LDSBAR -#define LDSBAR 1 -#endif -#if LDSBAR -#define BAR() do { \ - __builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "local"); \ - __builtin_amdgcn_s_barrier(); \ - __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup", "local"); \ - } while (0) -#else -#define BAR() __syncthreads() -#endif - -// LDS is what limits how many of these run per CU, and this kernel spends most of its time waiting -// on memory -- so a buffer is worth keeping only if it buys more than the occupancy it costs. The -// inverse's transposed form does not: it is needed as the right operand of three fragments per -// head, and fragT rebuilds those from the row-major copy for eight scalar reads each. -// ... and by the same argument the inverse does not need a buffer of its own either. Each stage -// reads the block of A it is about to overwrite BEFORE writing it, and the stages are separated by -// workgroup barriers, so the inverse can be formed in place: +// LDS limits occupancy, and this kernel is memory-bound, so buffers are minimised. No transposed +// inverse is kept (fragT rebuilds the three right operands that need it). The inverse is formed +// in place in A, since each stage reads the block it overwrites before writing it, with barriers +// between stages: // diagonal p reads A[p][p], writes it after the substitution has finished reading // 32-merge reads A10 and the two diagonal inverses, writes A10 -// 64-merge reads R = A[32:,:32] into registers everywhere, barriers, then writes it -// That leaves one 64x64 buffer plus a 32x32 scratch: 11 KB, against 31 KB for a form that gives -// every stage a buffer of its own. +// 64-merge reads R = A[32:,:32] into TMP everywhere, barrier, then writes it +// One 64x64 buffer plus a 32x32 scratch: 11 KB instead of 31 KB. struct KkSmem { unsigned short A[BT][AP]; // A on the way in, its inverse on the way out unsigned short TMP[32][36]; // one 32x32 intermediate, transposed float gb[BT], bt[BT]; // the chunk's gate cumsum and beta, per token }; -// The (mt, nt) of the NTILE upper-triangular tiles, walked out arithmetically rather than read -// from a __constant__ table: the table form is one byte load per tile from a segment this kernel -// is otherwise never touching, and it is wave-uniform arithmetic either way. +// (mt, nt) of upper-triangular tile ti, computed with wave-uniform arithmetic instead of a +// __constant__ table load. __device__ __forceinline__ void kkt_tile(int ti, int* mt, int* nt) { int m = 0, n = ti; while (n >= NBK - m) { n -= (NBK - m); ++m; } *mt = m; *nt = n + m; } -// OCC: minimum waves per SIMD to compile for. This kernel is memory wait, not arithmetic -// (~2000 instructions per wave against its wall clock), so occupancy is its lever -- and at -// HG_RATIO=3 it lands on 190 VGPRs, which caps it at 8 waves/SIMD where its 11.5 KB of LDS -// would allow 10. The trade does not pay: OCC=10 reaches 10 waves (144 VGPRs) but spills 148 -// bytes per lane and runs about 57% slower. Left at 0. -#ifndef OCC -#define OCC 0 -#endif +// No occupancy hint: at HG_RATIO=3 the kernel uses 190 VGPRs (8 waves per SIMD; LDS would allow +// 10), and forcing 10 waves spills 148 bytes per lane and is ~57% slower. template __global__ -#if OCC -__launch_bounds__(NTHR, OCC) -#else __launch_bounds__(NTHR) -#endif void r4d_gdn_kkt_solve_kernel(const unsigned short* __restrict__ k, const float* __restrict__ beta, const float* __restrict__ g, @@ -125,10 +82,9 @@ void r4d_gdn_kkt_solve_kernel(const unsigned short* __restrict__ k, const int lo = lane & 15, hi = lane >> 4; const int hg = blockIdx.y; - // Resolve the flat chunk id to (sequence, chunk). The grid is launched with an upper bound on - // the total chunk count, so this also decides which workgroups have nothing to do -- it costs - // N+1 scalar loads and saves the host a device-to-host sync it would otherwise need to size the - // grid exactly. + // Resolve the flat chunk id to (sequence, chunk). The grid is an upper bound on the chunk + // count, so surplus workgroups exit here; this saves the host a device-to-host sync to size + // the grid exactly. int n = -1, t0 = 0, bos = 0, rows = 0; { int acc = 0, want = blockIdx.x; @@ -142,11 +98,8 @@ void r4d_gdn_kkt_solve_kernel(const unsigned short* __restrict__ k, if (n < 0) return; } - // ---- zero the parts no store ever reaches: the upper tiles of A, and everything in M / MT - // outside the blocks the inverse writes. Done once; the write pattern is the same for every - // head, so it cannot be dirtied between heads. - // 16 bytes per thread per step, not 2: as shorts this is 34 ds_store_b16 per thread for a - // buffer that is 8704 bytes and 16-byte aligned. + // ---- zero A once: the parts no store reaches (the upper tiles) are the same for every head. + // 16-byte stores (the buffer is 8704 bytes, 16-byte aligned). for (int i = tid; i < BT * AP / 8; i += NTHR) ((uint4*)&s.A[0][0])[i] = make_uint4(0, 0, 0, 0); // ---- the gram, once for all HG_RATIO v heads of this k head ----------------------------- @@ -160,10 +113,7 @@ void r4d_gdn_kkt_solve_kernel(const unsigned short* __restrict__ k, const int ti = warp + t * NW; if (ti < NTILE) { int mt, nt; kkt_tile(ti, &mt, &nt); - // One 32-bit element offset per operand row, hoisted out of the k loop. The pointer form - // (fragG) rebuilds v_mad_co_i64_i32 + v_lshlrev_b64 + a 64-bit add for EVERY one of the - // sixteen fragments, because the size_t row stride forces 64-bit arithmetic and LLVM will - // not keep the address live across the loop. + // One 32-bit offset per operand row, hoisted out of the k loop (see rowGo/fragGo). const unsigned om = rowGo(krow, mt * 16, rows - 1, lane); const unsigned on = rowGo(krow, nt * 16, rows - 1, lane); #pragma unroll @@ -181,12 +131,12 @@ void r4d_gdn_kkt_solve_kernel(const unsigned short* __restrict__ k, s.gb[tid] = g[(size_t)(bos + t0 + t) * H + hv]; s.bt[tid] = beta[(size_t)(bos + t0 + t) * H + hv]; } - BAR(); + lds_barrier(); // ---- scale, mask and place the gram as the strictly lower half of A --------------------- - // Tile (mt, nt) holds P[m][n]; the element written is A[n][m] = rs[n] gv[m] P[m][n], which is - // in the lower triangle exactly when n > m. n is fixed per lane and m runs over the eight - // accumulator elements, so this is one row of A and one 16-byte store. + // Tile (mt, nt) holds P[m][n]; the element written is A[n][m], in the lower triangle when + // n > m. n is fixed per lane and m runs over the eight accumulator elements: one row of A, + // one 16-byte store. #pragma unroll for (int t = 0; t < MAXT; ++t) { const int ti = warp + t * NW; @@ -201,14 +151,10 @@ void r4d_gdn_kkt_solve_kernel(const unsigned short* __restrict__ k, #pragma unroll for (int e = 0; e < 8; ++e) { const int j = j0 + e; - // i > j means g_i <= g_j, so this exponent is never positive whatever the span is -- - // but ONLY for a live row. On a padding row (i >= rows) gi is forced to 0 above while - // gb[j] keeps its real, negative cumsum, so gi - gb[j] = -gb[j] is large POSITIVE, - // __expf overflows to +INF, and bi * INF = 0 * INF = NaN. Those NaNs sit in padding - // rows of the 64x64 tile, and the blocked inverse below merges the whole tile with - // WMMA, so they reach live rows and poison the chunk's output for the head. On real - // Qwen3.8-27B inputs that is a handful of non-finite values in A, which chunk_scan then - // spreads across an entire head_v-wide head of the layer output. + // For a live row, i > j gives g_i <= g_j, so the exponent is never positive. Padding + // rows and columns must be masked to -inf: with gi = 0 the exponent -gb[j] is large and + // positive, 0 * inf = NaN, and the WMMA merges in the blocked inverse would spread it + // into live rows. const float d = (live && i > j && j < rows) ? (gi - s.gb[j]) : -INFINITY; vv[e] = bi * __expf(d) * P[t][e]; } @@ -216,11 +162,11 @@ void r4d_gdn_kkt_solve_kernel(const unsigned short* __restrict__ k, *(uint2*)(&s.A[i][j0 + 4]) = f2bf4(vv[4], vv[5], vv[6], vv[7]); } } - BAR(); + lds_barrier(); // ---- 1. the four diagonal blocks, by fp32 forward substitution -------------------------- - // D = (I + N)^-1 solves D = I - N D one row at a time. Lane l owns column l of D, so the - // dot product over j < i is 16 registers deep and N[i][j] is a broadcast LDS read. + // D = (I + N)^-1 solves D = I - N D row by row. Lane l owns column l of D, so the dot product + // over j < i is in 16 registers and N[i][j] is a broadcast LDS read. for (int p = warp; p < NBK; p += NW) { const int b0 = p * 16; float d[16]; @@ -237,7 +183,7 @@ void r4d_gdn_kkt_solve_kernel(const unsigned short* __restrict__ k, for (int i = 0; i < 16; ++i) s.A[b0 + i][b0 + lo] = f2bf(d[i]); } } - BAR(); + lds_barrier(); // ---- 2. the two 32-merges: M10 = -D1 A10 D0 -------------------------------------------- for (int blk = warp; blk < 2; blk += NW) { @@ -246,11 +192,10 @@ void r4d_gdn_kkt_solve_kernel(const unsigned short* __restrict__ k, v8f X = (v8f){0, 0, 0, 0, 0, 0, 0, 0}; X = mma(frag(&s.A[0][0], AP, r0 + 16, r0, lane), fragT(&s.A[0][0], AP, r0, r0, lane), X); - // stage X transposed for the next product. The two merges run on two waves against the - // same scratch, so each owns 16 rows of it. + // Stage X transposed for the next product; each of the two merges owns 16 rows of TMP. *(uint2*)(&s.TMP[blk * 16 + lo][8 * hi]) = f2bf4(X[0], X[1], X[2], X[3]); *(uint2*)(&s.TMP[blk * 16 + lo][8 * hi + 4]) = f2bf4(X[4], X[5], X[6], X[7]); - // fragT reads A column-wise below, so the merge result only needs the row-major copy + // fragT reads A column-wise below, so the merge result needs only the row-major copy __builtin_amdgcn_wave_barrier(); // M10 = -D1 . X (left D1 row-major, in place in A; right X transposed, in TMP) v8f Y = (v8f){0, 0, 0, 0, 0, 0, 0, 0}; @@ -261,7 +206,7 @@ void r4d_gdn_kkt_solve_kernel(const unsigned short* __restrict__ k, #pragma unroll for (int e = 0; e < 8; ++e) s.A[i + e][j] = f2bf(-Y[e]); } - BAR(); + lds_barrier(); // ---- 3. the 64-merge: M[32:,:32] = -Q^-1 (R P^-1) -------------------------------------- // Y = R . P^-1, R = A[32:,:32] row-major, P^-1 read transposed out of A[:32,:32] by fragT @@ -275,7 +220,7 @@ void r4d_gdn_kkt_solve_kernel(const unsigned short* __restrict__ k, *(uint2*)(&s.TMP[nt * 16 + lo][mt * 16 + 8 * hi]) = f2bf4(Y[0], Y[1], Y[2], Y[3]); *(uint2*)(&s.TMP[nt * 16 + lo][mt * 16 + 8 * hi + 4]) = f2bf4(Y[4], Y[5], Y[6], Y[7]); } - BAR(); // every wave has read R into TMP; now it may be overwritten + lds_barrier(); // every wave has read R into TMP; now it may be overwritten // Z = -Q^-1 . Y, Q^-1 = A[32:,32:] row-major, Y transposed = TMP for (int t = warp; t < 4; t += NW) { const int mt = t >> 1, nt = t & 1; @@ -289,7 +234,7 @@ void r4d_gdn_kkt_solve_kernel(const unsigned short* __restrict__ k, #pragma unroll for (int e = 0; e < 8; ++e) s.A[i + e][j] = f2bf(-Z[e]); } - BAR(); + lds_barrier(); // ---- store: one row of the inverse is 64 bf16, contiguous in HBM ----------------------- { @@ -300,7 +245,7 @@ void r4d_gdn_kkt_solve_kernel(const unsigned short* __restrict__ k, *(uint4*)(op + (size_t)r * orow + c8) = *(const uint4*)(&s.A[r][c8]); } } - if (hh + 1 < HG_RATIO) BAR(); + if (hh + 1 < HG_RATIO) lds_barrier(); } } @@ -330,9 +275,7 @@ extern "C" int r4d_gdn_kkt_solve_k128_c64_bf16(const void* k, const void* beta, } // ============================================================== the plugin ABI entry points -// -// The shared operand helpers are r4d_gdn_args.h. See libr4d/r4d_args.h for why there is no -// adapter directory between the core and these launches. +// Shared operand helpers: r4d_gdn_args.h. /* ------------------------------------------------------------------ kkt solve */ enum { KS_K = 0, KS_BETA, KS_G, KS_CU, KS_A }; @@ -348,8 +291,7 @@ extern "C" int r4d_rad_gdn_kkt_solve(const RadArgs* a, RadStream s) { if (k->rank != 3 || bt->rank != 2 || g->rank != 2 || A->rank != 3) return R4D_NO(RAD_E_SHAPE); if (!r4d_contig(k) || !r4d_contig(bt) || !r4d_contig(g) || !r4d_contig(A)) return R4D_NO(RAD_E_STRIDE); - /* "bf16 k and A out, fp32 beta / gate / gram / inverse" -- and `A` is the OUT, written as - * unsigned short by r4d_gdn_kkt_solve_kernel. */ + /* bf16 k and A (the output, written as bf16); fp32 beta and gate. */ R4D_DT(k, RAD_BF16); R4D_DT(A, RAD_BF16); R4D_DT(bt, RAD_F32); R4D_DT(g, RAD_F32); int N = 0; @@ -365,7 +307,8 @@ extern "C" int r4d_rad_gdn_kkt_solve(const RadArgs* a, RadStream s) { if (A->shape[0] != T || A->shape[1] != H) return R4D_NO(RAD_E_SHAPE); if (H == 0 || Hg == 0 || H % Hg) return R4D_NO(RAD_E_SHAPE); - return r4d_gdn_kkt_solve_k128_c64_bf16(k->data, bt->data, g->data, A->data, cu->data, - N, (int)T, (int)H, (int)Hg, (int)K, (int)chunk, s); + return R4D_RAW(r4d_gdn_kkt_solve_k128_c64_bf16(k->data, bt->data, g->data, A->data, + cu->data, N, (int)T, (int)H, (int)Hg, (int)K, + (int)chunk, s)); } diff --git a/libr4d/r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip b/libr4d/r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip index a8107675..df5c79fd 100644 --- a/libr4d/r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip +++ b/libr4d/r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip @@ -1,21 +1,18 @@ -// r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip -- the gated-delta-net recurrent state update, which is what -// decode runs where prefill runs the chunked scan. One kernel for the whole step: +// r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip -- the gated-delta-net recurrent state +// update, run by decode (prefill runs the chunked scan). One kernel for the whole step: // // g = -exp(A_log) . softplus(a + dt_bias) beta = sigmoid(b) q, k l2-normalised // S *= e^g // u = beta . (v - S k) S += u k^T o = S q // -// per token, against a PAGED state cache: the initial state is read from the slot the last -// accepted token wrote, and every candidate token writes its own slot, because which of them -// survives verification is not known until after this layer has run. It replaces FLA's -// fused_sigmoid_gating_delta_rule_update, and its non-speculative sibling falls out as the -// width-1 case. +// per token, against a paged state cache: the initial state is read from the slot the last +// accepted token wrote, and every candidate token writes its own slot, since which survives +// verification is unknown until after this layer. Replaces FLA's +// fused_sigmoid_gating_delta_rule_update; the non-speculative case is width 1. // -// THE STATE TRAFFIC IS THE WHOLE COST. One [V,K] state is 64 KB, and a speculative step writes -// one per candidate token per head: at width 9 that is 113 MB per layer per rank, at the -// bandwidth limit of this part. So this kernel is a port that removes a Triton dependency and -// a kernel launch, not an arithmetic win, and it is written to keep the state resident rather -// than to be clever: one thread owns one v row and half its k range, so +// State traffic is the whole cost: one fp32 [V,K] state is 64 KB, written per candidate token per +// head (113 MB per layer per rank at width 9, at the memory bandwidth limit). So the design keeps +// the state in registers: one thread owns one v row and half its k range, so // // * S k and S q are in-lane dot products closed by a single lane<->lane^1 exchange, not a // tree reduction; @@ -23,14 +20,12 @@ // * a thread's 64 state elements are contiguous in k, so the load and every store is four // 16-byte accesses over one 256-byte run. // -// The state cache is fp32 -- this model's HF config sets mamba_ssm_dtype=float32, which vLLM -// honours over the `auto` mamba dtype, so the temporal state is fp32 while the conv state is -// bf16. That is also what makes the state traffic the cost: one [V,K] state is 64 KB, not 32. +// The state cache is fp32 by default (the model's HF config sets mamba_ssm_dtype=float32, which +// vLLM honours); the conv state is bf16. An fp16 state cache is also supported (SDT). // -// The slot and head strides are ARGUMENTS, not H*V*K: vLLM pads the mamba page so it matches the -// attention page size (here 421888 elements per slot against the 393216 the shape implies), and a -// kernel that derives the stride from the shape reads every slot but the first at the wrong -// offset -- which looks like a correct kernel producing noise. +// Slot and head strides are arguments, not H*V*K: vLLM's hybrid cache pads a mamba page to the +// attention page size (e.g. 421888 elements per slot vs 393216 from the shape), so a shape-derived +// stride would read every slot but the first at the wrong offset there. #include #include "r4d.h" #include "r4d_gdn_args.h" @@ -49,55 +44,32 @@ #define RU_HK 64 // k elements per thread (RU_K / 2) #define RU_THR (RU_V * 2) // two threads per v row -// THE STATE TRAFFIC IS DEAD ON ARRIVAL AND IT TAXES THE NEXT GEMM. A speculative step writes one -// full [128,128] fp32 state per candidate token per head -- 12 MB a layer, ~660 MB a step -- and -// exactly one state per head is read again, a whole step later. None of it can live in a 64 MB -// last level, so the dirty lines are written back while the layer's out_proj is streaming its -// weight, and that GEMM pays for it: behind a matched 12 MB write flood the same (5120, 3072) GEMM -// goes from 14.9 us clean to 20.4 us, and to 18.4 us when the flood is marked non-temporal. The -// hint changes no byte of the result -- the line stays coherent, it is only evicted first -- and -// whether it pays depends on the flood size, so it is a runtime switch (see RU_NT_MB below). It -// applies to the state LOAD as well: the initial state is read once per layer per step and never -// again. +// The state written per step (~12 MB a layer, ~660 MB a step) is read again only once, a step +// later, and cannot stay in the 64 MB last-level cache; its write-back slows the next GEMM (a +// (5120, 3072) GEMM goes from 14.9 us to 20.4 us behind a 12 MB write flood, 18.4 us when the +// flood is non-temporal). A non-temporal hint on the state load and store changes no result, and +// whether it pays depends on the flood size, so it is chosen per launch (RU_NT_MB below). typedef float ru_f4 __attribute__((ext_vector_type(4))); typedef _Float16 ru_h8 __attribute__((ext_vector_type(8))); -// SDT is the STATE CACHE's element type -- 0 = fp32, 1 = fp16 -- and nothing else: every value -// this kernel computes with is fp32 either way. It exists because the state read and the state -// write ARE this kernel. At the shape a decode step runs (eight sequences, eight candidate -// tokens) a call is ~68 us, of which the token loop is ~3.1 us a token and the rest -- ~45 us -- -// is 24 MB of state moving at 88% of what a launch that size can reach. Nothing else in the -// kernel is worth a percent, and halving the state width is worth a third. +// SDT is the state cache's element type (0 = fp32, 1 = fp16); all arithmetic is fp32. At eight +// sequences x eight candidates a call is ~68 us, of which ~45 us is 24 MB of state traffic at 88% +// of achievable bandwidth; halving the state width saves about a third. // -// ---- THE COST MODEL. Draft depth is the one axis that moves the token count without moving the -// state traffic: the anchor writes ONE state a sequence whatever the block width. Fitting a call -// at eight sequences and 16k of context across two depths separates the two terms cleanly: +// Cost model (eight sequences, 16k context, anchor state): ~3.2 us per token walked plus ~57 us +// fixed per layer. State traffic largely overlaps the token loop (fp16 state saves only about a +// fifth of what its byte count predicts), and the loop is on the critical path. // -// ~3.2 us per token walked, on top of ~57 us fixed per layer +// Shipped instantiation: 207 VGPRs, 7 waves/SIMD, no spill, 384 B LDS. At seven waves the serial +// `dot +=` and `on +=` chains are hidden; splitting them would only change the summation order. // -// so a speculative step is simply the fixed cost plus about eleven token iterations. -// -// AND THE TWO HALVES OVERLAP. Halving the state bytes (the fp16 cache below) is worth about a -// fifth of what the byte count alone predicts, so the state traffic hides under the token loop -// rather than running before it, while the depth split says the loop IS on the critical path. -// Shrinking either half alone therefore buys little, and the loop is the delta rule itself: four -// passes over 64 registers, not three. -// -// Resource use of the shipped instantiation: 207 VGPRs, 7 waves/SIMD, ZERO spill, 384 B LDS. At -// seven waves a dependent FMA chain is hidden, so the serial `dot +=` and `on +=` accumulations are -// throughput and not latency -- splitting them into partial sums would move the summation order, -// and the text, for nothing. -// -// fp16 and not bf16 because the state is O(1) with no range problem and eleven mantissa bits are -// four more than bf16's: the elements are sums of beta.(v - Sk) k^T over an effective horizon of -// order 1/(1-e^g) with |k| l2-normalised, which puts them around 0.1 and the round-trip error at -// 5e-4 relative. vLLM allocates the cache from --mamba-ssm-cache-dtype, which already accepts -// float16, so this is a serve flag rather than a private format the prefill path has to invent. +// fp16 rather than bf16: state elements are O(0.1) (sums of beta (v - Sk) k^T with l2-normalised +// k), so range is no issue and fp16's mantissa gives ~5e-4 relative round-trip error. vLLM's +// --mamba-ssm-cache-dtype already accepts float16. template struct ru_state { using T = float; }; template <> struct ru_state<1> { using T = _Float16; }; -// Eight elements a time: two 16-byte accesses in fp32 and ONE in fp16, so the fp16 cache halves -// the access count as well as the bytes. +// Eight elements per call: two 16-byte accesses in fp32, one in fp16. template __device__ __forceinline__ void ru_load8(float* d, const typename ru_state::T* p) { if constexpr (SDT) { @@ -130,124 +102,91 @@ __device__ __forceinline__ void ru_store8(typename ru_state::T* p, const fl } } } -// VS: how many workgroups share a head's 128 v rows. The grid is (sequences, heads), which at -// one sequence is 24 workgroups on 64 CUs -- 37% of the machine, and the kernel is not DRAM -// bound there (its whole working set fits the 64 MB last level). Nothing in a v row's update -// crosses to another v row: the two dot products contract over k, and the outer-product update -// is per (v, k). Only the fused RMS norm spans the row, so VS > 1 is compiled without it. -#ifndef WGTARGET -#define WGTARGET 64 -#endif -#ifndef VSMAX -#define VSMAX 4 -#endif +// VS: workgroups sharing a head's 128 v rows. At one sequence the (sequences, heads) grid is 24 +// workgroups on 64 CUs, and the working set fits the last-level cache. v rows are independent +// (dot products contract over k; the update is per (v, k)); only the fused RMS norm spans the +// row, so VS > 1 is compiled without it. +#define WGTARGET 64 // workgroups the v-row split aims for __device__ __forceinline__ float ru_softplus(float x, float thr) { if (x > thr) return x; return (x > 0.0f) ? (x + __logf(1.0f + __expf(-x))) : __logf(1.0f + __expf(x)); } -// a and b are a chunk() of the ba projection: bf16, strided by 2*H. See r4d_gdn_conv_w4_h128_bf16.hip. +// a and b are a chunk() of the ba projection (see r4d_gdn_conv_w4_h128_bf16.hip). template __device__ __forceinline__ float ru_ab(const void* p, size_t i) { return ABF16 ? bf2f(((const unsigned short*)p)[i]) : ((const float*)p)[i]; } -// The layer's gated RMS norm, folded into the epilogue. A workgroup here owns one (sequence, -// head) and therefore the WHOLE 128-channel row of the output, which is exactly what an RMS needs -// -- so on this path the norm costs one workgroup reduction per token and no kernel launch, no -// second pass over the output, and no read of it back from HBM. The prefill path cannot do this -// (its workgroup owns half a row) and calls r4d_gdn_gated_rmsnorm_h128_bf16 instead. +// The layer's gated RMS norm, folded into the epilogue: with NORM a workgroup owns one (sequence, +// head) and so the whole 128-channel output row, and the norm is one workgroup reduction per +// token. Prefill owns half a row and uses r4d_gdn_gated_rmsnorm_h128_bf16 instead. __device__ __forceinline__ float ru_act(float z, int kind) { const float s = 1.0f / (1.0f + __expf(-z)); return kind ? s : z * s; } -// One token's replay factors, inside the head's block of state slot sidx[n][1]: +// One token's replay factors (anchor state), inside the head's block of a factor slot: // // [0 .. 4*K) normalised k, FOUR copies -- one per fixed 32-row group // [4*K .. 4*K+V) the v row, one float per v row // [4*K+V .. +8) decay and beta, one pair per row group // -// The k copies are the price of not needing a barrier ACROSS workgroups. The launcher splits a -// head's v rows over up to four workgroups, and the split changes with the batch size, so a single -// shared copy would be read by one workgroup while another was overwriting it. Fixed 32-row groups -// make every byte belong to exactly one workgroup at every split the launcher can pick, and the -// read-before-write inside a workgroup is ordered by a barrier. +// Four k copies avoid a cross-workgroup barrier: a head's v rows may be split over up to four +// workgroups, and fixed 32-row groups make every byte belong to exactly one workgroup at any split. +// Read-before-write within a workgroup is ordered by a barrier. #define RU_FSTR (4 * RU_K + RU_V + 8) -// RU_TMAX bounds the candidate block STG can stage: two floats a token of LDS, plus four -// partials while they are being combined. The launcher checks the caller's width against it. +// RU_TMAX bounds the candidate block STG can stage (LDS for four partials and two scales per +// token). The launcher checks the caller's width against it. #define RU_TMAX 16 -// RU_ANC_DUP=0 drops the two neighbouring-page copies of the anchor and of the replay factors and -// keeps only the one the read column points at. -// -// WITHOUT THE MARKER IT IS NOT CORRECT and only measures the cost of the duplication -- a -// sequence whose page index moves reads a slot nothing wrote. WITH the marker it is the whole -// point: the marker already says which column to read, so the anchor is written once (RU_ANC_MARK -// does that on its own) and the factor block is written once too (this switch). The factor block -// is the bigger of the two, RU_TMAX * RU_FSTR against RU_V * RU_K of a head's slot, so -// `-DRU_ANC_MARK=1 -DRU_ANC_DUP=0` is the shape to build. +// RU_ANC_DUP=0 drops the two neighbouring-page copies of the replay factors (and, without the +// marker, of the anchor). Incorrect without RU_ANC_MARK (a moved page index reads an unwritten +// slot). With the marker it writes the factor block once; `-DRU_ANC_MARK=1 -DRU_ANC_DUP=0` is the +// leanest build, since the factor block (RU_TMAX * RU_FSTR) outweighs the state (RU_V * RU_K). #ifndef RU_ANC_DUP #define RU_ANC_DUP 1 #endif -// SHIFT MARKER. Three copies of the anchor is the price of not knowing which way the page index -// moved -- and the factor block, which has to be written in three copies anyway, can just SAY. -// Each copy carries the column it was written to, so the reader finds `m` at its own fixed factor -// column, learns that the page index moved by `m - 1`, and reads the anchor at the one column that -// follows from it. The anchor is then written ONCE: at eight sequences that is 6.3 MB a layer -// instead of 18.9, and the whole discovery costs one element. +// Shift marker: instead of writing the anchor three times (one per possible page shift), each of +// the three factor-block copies records the column it was written to. The reader finds `m` at its +// fixed factor column, so the page index moved by `m - 1`, and reads the anchor at the matching +// column; the anchor is written once (6.3 MB a layer instead of 18.9 at eight sequences, roughly a +// fifth of the layer's time). // -// The marker sits past everything the factor data can reach -- RU_TMAX tokens of RU_FSTR -- and -// inside one head's slice of a slot, so the three copies never touch each other's and no workgroup -// reads a marker another one is writing (different `hv`, different address). Its stored values -// are 1, 2 and 3 (one-based, see the read), exact in fp16 as well as fp32. +// The marker lies past all factor data (RU_TMAX tokens of RU_FSTR) within one head's slice, so no +// workgroup reads a marker another is writing. Stored values are 1, 2, 3 (one-based; see the read), +// exact in fp16 and fp32. // -// WRITE THE ANCHOR AT COLUMN 2, NOT COLUMN 1. vLLM MIGRATES the mamba state across a page boundary -// itself: `precopy_mamba_align_fused_kernel` copies state[bt[src_col + num_accepted - 1]] into -// state[bt[dst_col]] before the forward, and dst_col is the page the new window starts on -- this -// window's column 0. Writing the anchor at column 1 and reading it at 2 - m lands on column 0 for -// a +1 shift, which the migration has already overwritten; the damage is intermittent, because a -// generation that never crosses with the wrong count is unaffected while one that does degenerates -// mid-word. Column 2 / 3 - m keeps the read in {1, 2, 3} and never lands on 0. -// -// The single-write anchor is worth roughly a fifth of the layer's time on its own, and about 14% -// of the whole decode step. +// Invariant: the anchor is written at column 2 and read at 3 - m, never column 0. vLLM's +// precopy_mamba_align_fused_kernel copies state[bt[src_col + num_accepted - 1]] into this window's +// column 0 before the forward on a page crossing, so a read of column 0 (anchor at 1, read at +// 2 - m, shift +1) would see migrated data and degenerate intermittently. #ifndef RU_ANC_MARK #define RU_ANC_MARK 1 #endif #define RU_MARK_OFF (RU_TMAX * RU_FSTR) -// RU_ANC_FRD=1 is a diagnostic build: it takes the displaced factor read (column 5 - m) WITHOUT -// dropping the two spare factor copies. With all three written every step the read column cannot -// change what is read, so it separates the column algebra and `m` itself from the write side: -// degenerate output under it means the marker cannot steer a read reliably, while clean output -// under it and degenerate output under RU_ANC_DUP=0 place the fault on the WRITE side -- a step -// that writes no factors at all, whose stale page the three-copy form makes harmless. +// RU_ANC_FRD=1 (diagnostic): use the displaced factor read (column 5 - m) while still writing all +// three factor copies, isolating the marker's read-column logic from the write side. #ifndef RU_ANC_FRD #define RU_ANC_FRD 0 #endif -// THE DECODE CONVOLUTION, FOLDED IN (CV). gdn_conv_update's only reader at decode is this kernel, -// and as two kernels the pair pays a launch and a dependent-dispatch gap for a few microseconds of -// work. Under CV -// the workgroup computes the convolution its own token loop reads -- the 128 q and 128 k channels -// of its key head and the 128 v channels of its value head -- straight from the projection's -// output rows into LDS, and q, k and v never reach memory. +// Decode convolution folded in (CV). This kernel is gdn_conv_update's only decode reader, so the +// fold saves a launch and a dependent-dispatch gap. Each workgroup computes the convolution its +// token loop reads (its key head's 128 q and 128 k channels and its value head's 128 v channels) +// from the projection rows into LDS; q, k and v never reach memory. The arithmetic is +// gdn_conv_update's (same taps, order, cp_silu and bf16 rounding), so results are byte-identical. // -// THE ARITHMETIC IS gdn_conv_update's, channel by channel: the same taps in the same order, the -// same cp_silu (r4d_gdn_conv_tap.h), rounded to bf16 where that kernel stores, so the fold is -// byte-identical to the pair. -// -// THE CONV STATE IS REWRITTEN IN PLACE, and the key head's channels are read by every value head -// of its group -- H / Hg workgroups -- so no one of them may rewrite those channels until all of -// them have read the history. Each workgroup arrives on a counter once its history is in hand, -// and the LAST to arrive rewrites the key head's q and k channels at its end; nothing waits. A -// value head's own v channels have one reader, so it rewrites them itself. The counter resets -// itself, which is sound while two launches sharing it never overlap: it is keyed on the stream -// and the output, the rule split_ctr in r4d_gemm_fp8a8.hip states. +// The conv state is rewritten in place, and a key head's channels are read by all H / Hg value-head +// workgroups of its group, so none may rewrite them until all have read the history. Each +// workgroup arrives on a counter after reading; the last arriver rewrites the key head's q and k +// channels and resets the counter (no waiting). A value head's v channels have one reader and are +// rewritten by it. Two launches sharing a counter block must not overlap; blocks are keyed on +// (stream, output), as split_ctr in r4d_gemm_fp8a8.hip. struct RuConv { const unsigned short* x; long xpitch; // the projection's [q | k | v] columns, row pitch const unsigned short* w; // [conv_dim, R4D_GDN_CONV_W] @@ -257,14 +196,12 @@ struct RuConv { const int* cidx; long ci_stride; // conv state slot per sequence; negative is padding unsigned int* ctr; // one arrival counter per (sequence, key head) }; -// Tokens a sequence may bring to the folded convolution: the history and the step's inputs are -// preloaded into registers and indexed at compile time, as in the standalone update. +// Max tokens per sequence for the folded convolution (preloaded into registers, static indices). #define RU_CVT 8 -// A channel's conv state rewritten as gdn_conv_update rewrites it: shifted down by one, the tail of -// the old history and then this step's tokens. The launcher requires the window split the -// standalone update computes as `state_len_max - max_query_len` to be R4D_GDN_CONV_W - 2, which -// makes these the same stores that kernel issues. +// A channel's conv state rewritten as gdn_conv_update does: shifted by one, the old history's +// tail then this step's tokens. The launcher requires the window split to be R4D_GDN_CONV_W - 2, +// so these are the same stores. __device__ __forceinline__ void ru_conv_rewrite(unsigned short* sp, const unsigned short* hist, const unsigned short* xs, int T, long cs_tok) { constexpr int NH = R4D_GDN_CONV_W - 2; @@ -309,41 +246,33 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q, __shared__ float sscl [STG ? RU_TMAX * 2 : 1]; // per token: the two closed scales const int n = blockIdx.x, hv = blockIdx.y; const int bos = cu[n], T = cu[n + 1] - bos; - // A sequence with no tokens still has an anchor to advance: ANCHOR mode is called with T == 0 - // on purpose, to fold the previous step's accepted prefix in before something else reads the - // state cache. Without ANCHOR there is nothing to do and the workgroup leaves. + // With ANC, T == 0 is valid: it folds the previous step's accepted prefix into the anchor before + // something else reads the state cache. Without ANC there is nothing to do. const bool empty = (T <= 0); if (empty && !ANC) return; const int tid = threadIdx.x; const int row = (tid >> 1) + (VS > 1 ? blockIdx.z * NR : 0), half = tid & 1, k0 = half * RU_HK; const int hk = hv / (H / Hg); - /* The head's two constants, read here so their latency runs under the prologue's loads rather - * than behind the barriers in front of the token loop. */ + /* Read early so their latency overlaps the prologue's loads. */ const float a_log_h = A_log[hv], dtb = dt_bias[hv]; - // ---- CV: the convolution's inputs, issued first so the history and this step's tokens are in - // flight while the anchor replay below runs; they are consumed after it. Thread `tid` owns one - // q|k channel of the key head (q below RU_K, k above) and, below RU_V, one v channel of the - // value head. + // ---- CV: issue the convolution's inputs first so they are in flight during the anchor replay. + // Thread tid owns one q|k channel of the key head (q below RU_K, k above) and, below RU_V, one v + // channel of the value head. static_assert(!CV || (NORM && VS == 1 && STG == 0), "the folded convolution is the decode shape"); static_assert(RU_K == RU_V, "one LDS row pitch serves the q, k and v taps"); constexpr int CW = R4D_GDN_CONV_W, CS = R4D_GDN_CONV_W - 1; __shared__ unsigned short cvq[CV ? RU_CVT * RU_K : 1], cvk[CV ? RU_CVT * RU_K : 1]; __shared__ unsigned short cvv[CV ? RU_CVT * RU_V : 1]; __shared__ int cvlast; - /* THE KEY HEAD'S HISTORY FOR THE REWRITE AT THE END, parked here once its taps are computed: the - * two newest history entries and this step's inputs, one channel a thread. Held in registers they - * stay live across the whole token loop, ten values a thread that the loop's h, q and k leave no - * room for -- they went to scratch, and other values with them. */ + /* The key head's history for the final rewrite (two newest history entries and this step's + * inputs, one channel per thread), parked in LDS: in registers across the token loop they spill. */ __shared__ unsigned short cvh[CV ? (CS - 1 + RU_CVT) * THR : 1]; - /* THE TOKEN LOOP'S OWN GLOBAL READS, STAGED THE SAME WAY. Per token the loop reads `a` and `b` - * (the decay and beta inputs, one scalar each) and the output gate's row, and at decode there - * is well under a wave a SIMD to hide a load behind -- read in the loop, each is a full global - * latency on every token. They are issued here with the history, parked in LDS at the - * convolution's barrier and read from there: `ca_b` is one token's a (tid < T) or b - * (T <= tid < 2T), `czg` four channels of the step's gate rows, thread-strided so the loads - * stay coalesced. The values are the loaded ones, so every product downstream is unchanged. */ + /* The token loop's per-token global reads (a, b and the output gate row) are also staged: at + * decode there is too little occupancy to hide a global load per token. They are issued here, + * parked in LDS at the convolution's barrier and read from there: `ca_b` is one token's a + * (tid < T) or b (T <= tid < 2T), `czg` this thread's strided share of the gate rows. */ constexpr int ZPT = (RU_CVT * RU_V + THR - 1) / THR; // gate values a thread stages __shared__ float sab[CV ? 2 * RU_CVT : 1]; __shared__ unsigned short szg[CV ? RU_CVT * RU_V : 1]; @@ -358,8 +287,8 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q, if constexpr (CV) { if (!empty) { const int cslot = cv.cidx[(size_t)n * cv.ci_stride]; - // A NEGATIVE slot is padding, as it is to gdn_conv_update, and nothing of the sequence runs: - // every workgroup of the sequence leaves here, so none of them arrives on the counter. + // A negative slot is padding: every workgroup of the sequence leaves here, so none arrives + // on the counter. if (cslot < 0) return; const int off = naccept ? naccept[n] - 1 : 0; const int ca = tid < RU_K ? hk * RU_K + tid : (Hg + hk) * RU_K + (tid - RU_K); @@ -399,110 +328,73 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q, } } - // Without ANCHOR the initial state is the one the last accepted token of the previous step - // wrote; with it there is only ever one state per sequence and the accepted prefix is replayed - // onto it below. + // Without ANC the initial state is the one the last accepted token wrote; with ANC there is one + // state per sequence and the accepted prefix is replayed onto it below. const int nacc = naccept ? naccept[n] : 1; - // PAGED ANCHOR. vLLM addresses the mamba state by PAGE and re-derives the page every step as - // (seq_lens - 1) / block_size, so a sequence whose page index moves finds column 0 where some - // other column used to be. A scheme that keeps one state in a fixed column therefore reads its - // anchor out of the wrong slot whenever the index moves. - // - // THE INDEX MOVES BOTH WAYS. `seq_lens` is the context PLUS this step's query, and the query is - // the draft depth, which the dynamic controller changes from step to step. So + // Paged anchor. vLLM addresses mamba state by page, re-derived each step as + // (seq_lens - 1) / block_size, so the column holding a sequence's state can move. seq_lens + // includes this step's query (the draft depth, which varies), so // start' - start = ((ctx + acc + q') - 1)/bs - ((ctx + q) - 1)/bs - // is +1 when the committed context crosses, 0 almost always, and -1 when a step drafts fewer - // tokens than the one before it did -- the whole row slides BACK a column. Duplicating into - // column 1 alone covers +1 and 0 and is wrong on -1, where a long greedy generation diverges - // from the per-candidate path at the second page. + // is +1 when the committed context crosses a page, usually 0, and -1 when a step drafts fewer + // tokens than the previous one. // - // Three copies is the minimum that needs no extra metadata. With the shift in {-1, 0, +1}, one - // FIXED read column works iff the three pages it can land on were all written, so the anchor is - // written to columns 0, 1, 2 and read from column 1, and the replay factors are written to - // columns 3, 4, 5 and read from column 4: + // With the shift in {-1, 0, +1}, a fixed read column works only if all three pages it can land + // on were written. So the anchor is written to columns 0, 1, 2 and read from column 1, and the + // replay factors are written to columns 3, 4, 5 and read from column 4: // shift -1 -> next column 1 is this column 0 (and next column 4 is this column 3) // shift 0 -> next column 1 is this column 1 (and next column 4 is this column 4) // shift +1 -> next column 1 is this column 2 (and next column 4 is this column 5) - // The six columns are real, distinct, writable slots: vLLM's own Triton path writes one state - // per candidate to exactly these indices, so `indices_stride` of them exist whenever a spec step - // runs, and `indices_stride` here is num_spec + 1 = 8 whatever depth the controller picked. + // The six columns are distinct writable slots: vLLM's per-candidate path writes to the same + // indices, and indices_stride is num_spec + 1 = 8 whatever the draft depth. // - // AND vLLM MIGRATES THE STATE ITSELF, WHICH IS THE OTHER HALF OF WHY THIS LAYOUT IS THE ONE. - // `precopy_mamba_align_fused_kernel` runs before the forward on any step that crosses a boundary - // and copies state[bt[src_col + num_accepted - 1]] into state[bt[dst_col]] -- it assumes the - // per-candidate layout, so under the anchor its source is usually a factor block and its - // destination, page start_prev + 1, is garbage afterwards. Reading the anchor at column 1 - // resolves to page start_prev + 2 and the factors at column 4 to start_prev + 5, both of which - // the migration never writes, so it does not matter what it put there. Any future scheme that - // moves these columns has to be re-derived against that kernel, not only against - // (seq_lens - 1) / block_size. + // vLLM also migrates state itself: precopy_mamba_align_fused_kernel copies + // state[bt[src_col + num_accepted - 1]] into state[bt[dst_col]] on a page crossing, assuming the + // per-candidate layout. The anchor and factor read columns resolve to pages it never writes. + // Any change to these columns must be re-derived against that kernel too. // - // NOTHING ELSE MAY WRITE THIS CACHE. A path that advances column 0 alone leaves the other two - // copies stale, so every step shape a generation can take is covered by the fused path -- - // including the non-speculative decode the controller emits when it declines to draft - // (`kind == "decode1"` in radiance_gdn.py) -- and a step that still falls out folds the accepted - // prefix back into a single state first. + // Nothing else may write this cache: advancing one copy alone leaves the others stale. Every step + // shape, including non-speculative decode (`kind == "decode1"` in radiance_gdn.py), goes through + // the fused path, and any other step first folds the accepted prefix into a single state. const int sa0 = ANC ? sidx[(size_t)n * sidx_stride + 0] : 0; // anchor, page before const int sa1 = ANC ? sidx[(size_t)n * sidx_stride + 1] : 0; // anchor, written here const int sa2 = ANC ? sidx[(size_t)n * sidx_stride + 2] : 0; // anchor, page after const int sf0 = ANC ? sidx[(size_t)n * sidx_stride + 3] : 0; // factors, marker 0 const int sf = ANC ? sidx[(size_t)n * sidx_stride + 4] : 0; // factors, marker 1, read here const int sf2 = ANC ? sidx[(size_t)n * sidx_stride + 5] : 0; // factors, marker 2 - // A NEGATIVE slot is the pad and ZERO IS A REAL SLOT, the same rule the per-candidate read - // below follows. Testing <= 0 here would drop every update for whoever holds slot - // 0, silently: its state would simply never advance. + // A negative slot is padding; 0 is a real slot (as for the per-candidate read below). if (ANC && (sa0 < 0 || sa1 < 0 || sa2 < 0 || sf0 < 0 || sf < 0 || sf2 < 0)) return; ST* const fb = ANC ? (state + (size_t)sf * st_slot + (size_t)hv * st_head) : nullptr; ST* const fb0 = ANC ? (state + (size_t)sf0 * st_slot + (size_t)hv * st_head) : nullptr; ST* const fb2 = ANC ? (state + (size_t)sf2 * st_slot + (size_t)hv * st_head) : nullptr; - // Which column the anchor is in. Without markers it is column 1 and all three copies were - // written; with them the factor block this step reads says how far the index moved. - // COLUMN 0 IS THE MIGRATION'S TARGET, so the anchor is written at column 2 and read at 3 - m, - // which is 1, 2 or 3 -- never 0. `precopy_mamba_align_fused_kernel` derives its destination from - // num_computed_tokens, i.e. the page of the COMMITTED context, which is this window's column 0 - // (or below it when the query itself crossed). Writing the anchor at column 1 and reading at - // 2 - m resolves to column 0 on a +1 shift, where the migration has already put - // state[bt[src + num_accepted - 1]]. The failure is intermittent: a generation that never - // crosses with the wrong count is unaffected, one that does degenerates mid-word. - // A CALLER WHOSE STATE DOES NOT PAGE NAMES ONE SLOT IN EVERY COLUMN, and then every duplicate - // below is the same bytes written again. The copies exist because vLLM's mamba cache is - // addressed by page and the page index moves; radiance's linear pool gives a sequence one slot - // for its life. Comparing the indices costs one uniform branch and saves two thirds of the - // factor traffic -- 8.2 MB a layer at eight sequences -- for the caller that does not need it. + // Anchor column: without markers, column 1 (all three copies written); with them, 3 - m, never 0 + // (column 0 is the migration's target, derived from the committed context; see RU_ANC_MARK). + // A caller whose state does not page (this engine's linear pool: one slot per sequence for its + // life) names the same slot in every column; then duplicates are skipped, saving two thirds of + // the factor traffic. const bool dup_a = ANC && RU_ANC_DUP && (sa0 != sa2 || sa1 != sa2); const bool dup_f = ANC && RU_ANC_DUP && (sf0 != sf || sf2 != sf); int acol = RU_ANC_MARK ? 2 : 1; int mrk = 1; if (ANC && RU_ANC_MARK) { - // THE MARKER IS ONE-BASED so that a ZEROED factor block reads as absent rather than as - // shift 0. A freshly handed out slot is zeroed by the engine, and a zero-based marker would - // steer the state read to column 3 -- a FACTOR column -- which on the first step after a - // prefill is those zeros: the sequence would start from an empty state and then write that - // over the state the prefill had just built. Values 1, 2, 3 read back as shifts 0, 1, 2, so a - // paged caller sees no difference; only the unwritten case moves, and it moves to the default - // column, which is an anchor. + // The marker is one-based so a zeroed (freshly allocated) factor block reads as absent and + // falls back to the default anchor column. Zero-based, it would steer the first read after a + // prefill to column 3, a factor column of zeros, discarding the prefill's state. const int m = (int)((float)fb[RU_MARK_OFF] + 0.5f) - 1; mrk = (m >= 0 && m <= 2) ? m : 1; acol = 3 - mrk; } - // AND THE FACTORS FOLLOW THE SAME RULE. Once the marker says how far the index moved there is - // no reason to write the factor block three times either: it is written at column 4 and read at - // 5 - m, which is 3, 4 or 5. That is the larger of the two saves -- a head's factors are - // RU_TMAX * RU_FSTR of its RU_V * RU_K slot, so three copies of them outweigh three copies of - // the state. The MARKER still lives at the fixed column 4 that produced m, and is still stamped - // into all three: it is one element, and it is what makes the rest of this work. + // With RU_ANC_DUP=0 (or RU_ANC_FRD) the factors are read at 5 - m (3, 4 or 5) and written only + // at column 4. The marker itself stays at fixed column 4 and is stamped into all three copies. const ST* const fr = (ANC && RU_ANC_MARK && (RU_ANC_FRD || !RU_ANC_DUP)) ? (const ST*)(state + (size_t)(mrk == 0 ? sf2 : (mrk == 1 ? sf : sf0)) * st_slot + (size_t)hv * st_head) : (const ST*)fb; const int si = sidx[(size_t)n * sidx_stride + (ANC ? acol : (nacc - 1))]; - // A NEGATIVE slot is the pad and ZERO IS A REAL SLOT -- see the same rule in - // r4d_gdn_conv_w4_h128_bf16.hip. A `<= 0` test here loses the first sequence's state entirely. + // A negative slot is padding; 0 is a real slot. if (si < 0) return; - /* Fixed 32-row group, see RU_FSTR. One per WAVE: a wave's 32 threads are 16 consecutive rows from - * a multiple of 16, inside one group whatever VS is (a workgroup's first row is a multiple of - * NR >= 32). Said so to the compiler, the factor addresses it scales are scalar; as a lane value - * they were 64-bit VGPR offsets live across the token loop and reloaded from scratch there. */ + /* Fixed 32-row group (see RU_FSTR), uniform per wave for any VS (a wave is 16 consecutive rows + * from a multiple of 16). readfirstlane makes the factor addresses scalar instead of 64-bit + * VGPR offsets live across the token loop. */ const int grp = __builtin_amdgcn_readfirstlane(row >> 5); float h[RU_HK]; @@ -525,13 +417,13 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q, float dot = 0.0f; #pragma unroll for (int j = 0; j < RU_HK; ++j) { h[j] *= eg; dot += h[j] * kk[j]; } - dot += r4d_xor_lane<1>(dot); // a DPP modifier, not an LDS round trip + dot += r4d_xor_lane<1>(dot); // DPP, no LDS round trip const float u = (vv - dot) * bt; #pragma unroll for (int j = 0; j < RU_HK; ++j) h[j] += u * kk[j]; } - // Publish the advanced anchor to BOTH pages, then fence the factor block: every replay read - // above must happen before the loop below overwrites it with this step's factors. + // Publish the advanced anchor, then barrier: every replay read above must complete before the + // token loop overwrites the factor block with this step's factors. const size_t rowoff = (size_t)hv * st_head + (size_t)row * RU_K + k0; ST* p = state + (size_t)(RU_ANC_MARK ? sa2 : sa1) * st_slot + rowoff; ST* p0 = state + (size_t)sa0 * st_slot + rowoff; @@ -545,11 +437,8 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q, for (int j = 0; j < RU_HK; j += 8) ru_store8(p2 + j, &h[j]); } __syncthreads(); - // THE STAMP COMES AFTER THE BARRIER. Every thread read `fb`'s marker at the top to pick its - // anchor and factor columns, and a wave can reach that read after thread 0 has finished its - // own replay: stamped before the barrier, the new marker could steer a late wave to a - // different column from the rest of the workgroup. The replay reads are done by now and the - // marker lies past everything the factor writes below can reach. + // Stamp after the barrier: every thread read fb's marker at the top, and stamping earlier + // could steer a late wave to a different column from the rest of the workgroup. if (RU_ANC_MARK && tid == 0) { // the three copies say where they are fb0[RU_MARK_OFF] = (ST)1.0f; fb[RU_MARK_OFF] = (ST)2.0f; @@ -559,8 +448,7 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q, if (empty) return; if constexpr (CV) { - // gdn_conv_update's token body, one channel a thread: the same taps in the same order and the - // same rounding, into LDS instead of q, k and v. + // gdn_conv_update's token body, one channel per thread, into LDS instead of q, k and v. auto conv = [&](const float* wt, float bs, const unsigned short* hist, const unsigned short* xs, unsigned short* dst) { float win[CW]; @@ -595,8 +483,8 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q, const int zi = tid + i * THR; if (zi < T * RU_V) szg[zi] = czg[i]; } - // Every thread's history is consumed by now -- its taps are in LDS -- so after the barrier - // this workgroup no longer reads the key head's state and may be counted out. + // All history is consumed (taps are in LDS), so after the barrier this workgroup no longer + // reads the key head's conv state and may arrive on the counter. __syncthreads(); if (G > 1 && tid == 0) arrived = __hip_atomic_fetch_add(cv.ctr + (size_t)n * Hg + hk, 1u, __ATOMIC_RELAXED, @@ -606,7 +494,7 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q, const float alog = __expf(a_log_h); if (STG) { - // One lane per (token, half) does exactly the sum a v-row takes for itself on the STG=0 path. + // One lane per (token, half) computes the same sums each v row computes on the STG=0 path. if (tid < 2 * T) { const int ut = tid >> 1, uk0 = (tid & 1) * RU_HK; const unsigned short* qp = q + ((size_t)(bos + ut) * Hg + hk) * RU_K + uk0; @@ -628,7 +516,7 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q, } __syncthreads(); if (tid < T) { - // Same order the shfl closed them in: own half plus the other half's partial. + // Same order as the STG=0 exchange: own half plus the other half. const float ssq = spart[tid * 4] + spart[tid * 4 + 2]; const float ssk = spart[tid * 4 + 1] + spart[tid * 4 + 3]; sscl[tid * 2] = __frsqrt_rn(ssq + 1e-6f) * scale; @@ -664,11 +552,8 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q, sk += r4d_xor_lane<1>(sk); qs = __frsqrt_rn(sq + 1e-6f) * scale; ks = __frsqrt_rn(sk + 1e-6f); } - // STG 2 leaves qq/kk RAW and carries the scales into the reductions below instead. - if (STG != 2) { #pragma unroll - for (int j = 0; j < RU_HK; ++j) { qq[j] *= qs; kk[j] *= ks; } - } + for (int j = 0; j < RU_HK; ++j) { qq[j] *= qs; kk[j] *= ks; } const float ra = CV ? sab[t] : ru_ab(av, (size_t)tok * ab_stride + hv); const float rb = CV ? sab[T + t] : ru_ab(bv, (size_t)tok * ab_stride + hv); @@ -680,15 +565,13 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q, #pragma unroll for (int j = 0; j < RU_HK; ++j) { h[j] *= eg; dot += h[j] * kk[j]; } dot += r4d_xor_lane<1>(dot); - if (STG == 2) dot *= ks; const float vraw = bf2f(CV ? cvv[t * RU_V + row] : v[((size_t)tok * H + hv) * RU_V + row]); const float u = (vraw - dot) * bt; - const float uk = (STG == 2) ? u * ks : u; if (ANC) { - // This step's factors, for the next step's replay. One thread pair per row group writes the - // group's k copy and its decay/beta; every row writes its own v. + // This step's factors for the next step's replay: one thread pair per row group writes the + // group's k copy and decay/beta; every row writes its own v. ST* f = fb + (size_t)t * RU_FSTR; ST* f0 = fb0 + (size_t)t * RU_FSTR; ST* f2 = fb2 + (size_t)t * RU_FSTR; @@ -697,7 +580,7 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q, for (int j = 0; j < RU_HK; j += 8) { float kn[8]; #pragma unroll - for (int e = 0; e < 8; ++e) kn[e] = (STG == 2) ? kk[j + e] * ks : kk[j + e]; + for (int e = 0; e < 8; ++e) kn[e] = kk[j + e]; ru_store8<0, SDT>(f + grp * RU_K + k0 + j, kn); if (dup_f) { ru_store8<0, SDT>(f0 + grp * RU_K + k0 + j, kn); @@ -723,15 +606,13 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q, float on = 0.0f; #pragma unroll - for (int j = 0; j < RU_HK; ++j) { h[j] += uk * kk[j]; on += h[j] * qq[j]; } + for (int j = 0; j < RU_HK; ++j) { h[j] += u * kk[j]; on += h[j] * qq[j]; } on += r4d_xor_lane<1>(on); - if (STG == 2) on *= qs; if (NORM) { - // sum of squares over the row: each pair holds one channel, so one wave covers 16 of them + // sum of squares over the row: one channel per thread pair, 16 per wave float sq = (half == 0) ? on * on : 0.0f; - // unrolled so each mask is a compile-time constant: 16 takes v_permlanex16 and the - // rest are DPP row_xmask. Same order, same value. + // compile-time masks: 16 uses v_permlanex16, the rest DPP row_xmask sq += r4d_xor_lane<16>(sq); sq += r4d_xor_lane<8>(sq); sq += r4d_xor_lane<4>(sq); sq += r4d_xor_lane<2>(sq); sq += r4d_xor_lane<1>(sq); if ((threadIdx.x & 31) == 0) wsum[threadIdx.x >> 5] = sq; @@ -749,22 +630,13 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q, const unsigned short ob = f2bf(on); if (half == 0) o[((size_t)tok * H + hv) * RU_V + row] = ob; - // THE OUT PROJECTION'S QUANTISER, FOLDED IN. `o` is read by exactly one thing -- the fp8 - // out projection -- and a standalone quant_act_fp8 between them is 48 launches a decode step - // for 3.1 us of work each, which on this part is less than the 3.2 us gap that precedes each - // one. The fold is free because THE GROUP IS THE ROW: r4d_quant_act_fp8_group() is - // 128, V is 128, and NORM already requires one workgroup per (token, head), so the group's - // amax is a reduction this workgroup can already do and the scale plane index is (tok, hv). - // - // BIT-IDENTICAL TO THE STANDALONE QUANTISER, and deliberately: `ob` is the bf16 this kernel - // stores, and quantising `bf2f(ob)` rather than `on` is what makes it so -- the standalone - // quantiser reads these bytes, not the f32 that produced them. Everything after is - // the same arithmetic as r4d_fused_quant_fp8.hip's quant_group, including the fmin that keeps - // the group's own maximum from converting to a NaN. - // - // NORM == 2 WRITES INT8 CODES instead, for an int8 out projection (gemm_i8a8_*): the scale - // amax / 127 and the value over it rounded to nearest-even -- quant_act_i8g's arithmetic over - // the same bf16 bytes, so the codes are the ones that quantiser would have written. + // The out projection's quantiser, folded in (saves 48 launches per decode step, each with less + // work than its launch gap). The quant group (128) is the row and NORM gives one workgroup per + // (token, head), so the amax is a workgroup reduction and the scale index is (tok, hv). + // Bit-identical to the standalone quantiser: it quantises the stored bf16 `ob`, not the f32 + // `on`, with r4d_fused_quant_fp8.hip's quant_group arithmetic (including the clamp that keeps + // the group maximum from becoming NaN). NORM == 2 writes int8 codes instead (quant_act_i8g: + // scale amax / 127, round to nearest-even). if (NORM && oq) { const float ov = bf2f(ob); float mv = (half == 0) ? fabsf(ov) : 0.0f; @@ -793,13 +665,8 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q, if (!ANC) { const int so = sidx[(size_t)n * sidx_stride + t]; - // `>= 0`, NOT `> 0`. A NEGATIVE slot is the pad and ZERO IS A REAL SLOT -- the same rule - // the READ above follows, and the same one r4d_gdn_conv_w4_h128_bf16.hip follows. With `> 0` - // a single-sequence decode, whose only slot IS zero, never writes the state back at all: - // every step then recurs from the state prefill left behind, the model re-reads its own - // prompt and the generation degenerates into repeating it. A correct read side hides this - // one -- the kernel still produces a correct `o` for the first decoded token and a stale one - // for every token after it. + // `>= 0`, not `> 0`: a negative slot is padding and 0 is a real slot (a single-sequence + // decode's only slot), as for the read above. if (so >= 0) { ST* p = state + (size_t)so * st_slot + (size_t)hv * st_head + (size_t)row * RU_K + k0; @@ -810,8 +677,8 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q, } if constexpr (CV) { - // The key head's q and k channels, rewritten by the last of its readers to arrive. The count - // was taken before the token loop, so its latency is hidden behind it. + // The last arriving reader rewrites the key head's q and k channels. The count was taken + // before the token loop, hiding its latency. if (G > 1) { if (tid == 0) { cvlast = arrived == (unsigned)(G - 1); @@ -833,29 +700,17 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q, } } -// THE NON-TEMPORAL HINT on the state load and store (th:TH_STORE_NT / TH_LOAD_NT). -// It changes no byte of the result -- the line stays coherent, it is only evicted first -- and it -// is chosen per launch because its cost and its saving land in different kernels and the trade is -// only visible in a whole step. ISOLATED the hint is 43.8% SLOWER (20.76 us against 14.44 at -// 12 MB a call): non-temporal, this kernel is DRAM-write bound, where without the hint the writes -// stay in the last level and a later kernel pays for the write-back. In a step there is no later -// escape -- 48 layers write ~660 MB and a 64 MB last level holds none of it -- so what the hint -// really moves is WHO pays. With a matched 12 MB write flood between the decode GEMMs, the same -// (5120, 3072) GEMM is 14.9 us clean, 20.4 us behind the flood and 18.4 us behind a non-temporal -// flood, and the whole 64-layer sequence is 110 us faster with the hint. Under anchor state the -// balance is about -140 us on the tiled GEMM against +25 us here. +// Non-temporal hint on the state load and store (TH_LOAD_NT / TH_STORE_NT): no result changes; +// chosen per launch because its cost and saving land in different kernels. In isolation it makes +// this kernel 43.8% slower (DRAM-write bound), but no state survives the 64 MB last-level cache +// within a step, so the hint only decides who pays for the write-back, and it saves the following +// GEMMs more (about -140 us on the tiled GEMM vs +25 us here under anchor state). // -// ANCHOR STATE: one state per sequence, with the accepted prefix replayed onto it. It needs the -// caller's cooperation -- the prefill path must zero state slot sidx[n][1] for every sequence it -// writes -- so the kernel and radiance_gdn have to agree, and they do so by both being built this -// way rather than by reading a switch. -// It is a RUNTIME switch, not a build-time one, because the anchor scheme is NOT PAGED (see the -// block comment in radiance_gdn.py): vLLM addresses the mamba state by page, and the anchor keeps -// one state per sequence in the page holding the last token, so a sequence crossing a page reads -// its anchor out of the previous step's replay factors. Off, every candidate writes its own slot -// -- which is exactly the indexing vLLM's own Triton path uses, so it is correct by construction -// and stays clean across consecutive page crossings. radiance_gdn.py reads THE SAME variable, so -// the kernel and its caller cannot disagree about what the state cache means. +// Anchor state: one state per sequence with the accepted prefix replayed onto it. The caller's +// prefill path must zero state slot sidx[n][1] for every sequence it writes. Off (per_candidate), +// every candidate writes its own slot, matching vLLM's Triton path. A radiance caller declares the +// form as the op's `state_form` (ru_state_form); the raw C entry, which vLLM's radiance_gdn.py +// calls, has no op parameters and reads RADIANCE_GDN_ANCHOR, as that caller does. static bool ru_anchor() { static const bool v = [] { const char* e = getenv("RADIANCE_GDN_ANCHOR"); @@ -864,39 +719,16 @@ static bool ru_anchor() { return v; } -// Shared q/k l2 scales across the 128 v-rows of a head: bit-identical to computing them per row. -// Folding the scales into the reductions instead (STG 2) deletes 128 multiplies a token and is -// SLOWER for it, so the multiplies are not what the loop waits on -- and it stops being -// bit-identical, moving about one output in 600 by a single bf16 ULP. -#ifndef RU_STG_D -#define RU_STG_D 1 -#endif -static constexpr int RU_STG = RU_STG_D; - -// A non-temporal store on the state write. THE FLOOD SIZE DECIDES THE SIGN, so the default is -// off and the decision is made per launch below. -// Under anchor state a layer floods 12.6 MB of state plus 4.1 MB of replay factors, and at that -// size the hint is worth about -140 us a step on the tiled W4A8 GEMM against +25 us on this -// kernel: net about -100 us. -// UNDER PER-CANDIDATE STATE THE SIGN FLIPS. With one state per candidate the flood is eight -// times larger and the non-temporal store is DRAM-write bound for all of it, at which point -// leaving the hint off wins: without it this kernel runs about 20% faster than FLA's Triton kernel, -// where with it it is about 20% slower. It stays switchable because the hint moves cost onto the -// GEMMs rather than deleting it, and that half of the trade is only visible in a whole step. -#ifndef RU_NT_D -#define RU_NT_D 0 -#endif -// IT IS THE FLOOD SIZE THAT DECIDES, NOT THE SHAPE. Non-temporal costs this kernel time and saves -// the GEMMs behind it time, so it wins exactly when the state a layer writes would otherwise have -// stayed in the 64 MB last level and been handed to the next GEMM as write-back. At one sequence -// a layer floods 6.3 MB and the hint is worth about 3% of a whole step; at eight it floods 50 MB, -// none of it survives, and the hint costs about 2%. +// STG: the q/k l2 scales are computed once per head and shared by the 128 v rows (bit-identical to +// per row). Folding the scales into the reductions instead is slower and moves about one output in +// 600 by a bf16 ULP. // -// The threshold is the last level with room left for the weights streaming through it, not the -// whole 64 MB. -#ifndef RU_NT_MB +// Flood size (MB of state a launch writes) up to which the non-temporal hint is used. It wins when +// the state would otherwise stay in the last-level cache and become the next GEMM's write-back +// (6.3 MB at one sequence: ~3% of a step) and loses when nothing survives anyway (50 MB at eight: +// ~2% slower). The threshold leaves cache room for the streaming weights. Under anchor state the +// hint nets about -100 us a step; under per-candidate state the flood is ~8x larger. #define RU_NT_MB 16 -#endif // `oq_i8` picks the folded quantiser's codes: E4M3 (0) or int8 (1); see the kernel's epilogue. static int ru_update_launch( @@ -907,29 +739,22 @@ static int ru_update_launch( const void* ssm_state_indices, long indices_stride, const void* num_accepted, const void* z_gate, long z_pitch, const void* norm_weight, float norm_eps, int norm_act, int N, int H, int Hg, int K, int V, float scale, float softplus_thr, int state_fp16, - void* stream, int oq_i8) + void* stream, int oq_i8, bool anc) { if (K != RU_K || V != RU_V) return -1; if (H % Hg) return -2; const int nm0 = (z_gate && norm_weight) ? 1 : 0; - // Fill the machine: at one sequence the (N, H) grid is 24 workgroups. Split a head's v rows - // until there are at least 64 workgroups, but never past four (that is 64 threads, two waves). + // Fill the GPU: split a head's v rows until there are at least WGTARGET workgroups, at most + // four ways (64 threads, two waves). int vs = 1; if (!nm0) { const int want = (WGTARGET + N * H - 1) / (N * H); - vs = want >= 4 ? 4 : (want >= 2 ? 2 : 1); - if (vs > VSMAX) vs = VSMAX; } - // THE SHIFT MARKER FORBIDS SPLITTING A HEAD. vs > 1 puts several workgroups on the same - // (sequence, head) and therefore on the same marker element: one of them can stamp this step's - // marker before another has read the previous step's, and the readers then disagree about how - // far the page index moved. The output degenerates, a greedy generation collapsing mid-word - // within a couple of thousand tokens. One workgroup per (sequence, head) removes the sharing - // entirely, and it is not a loss: the wave count is the same either way (vs halves the workgroup - // and doubles their number), and vs == 1 is the shape the staged path is instantiated for. - if (ru_anchor() && RU_ANC_MARK) vs = 1; + vs = want >= 4 ? 4 : (want >= 2 ? 2 : 1); } + // The shift marker forbids splitting a head: with vs > 1 one workgroup could stamp this step's + // marker before another read the previous one, and they would disagree on the page shift. The + // wave count is the same either way. + if (anc && RU_ANC_MARK) vs = 1; dim3 grid(N, H, vs), blk(RU_V / vs * 2); - // The state dtype is a template parameter and so is every other switch, so the picks are written - // as nested macros rather than #define/#undef pairs: five binary or ternary choices is 72 - // instantiations, and the preprocessor form makes it easy to leave some of them unreachable. + // Every switch is a template parameter; the nested pick macros enumerate the instantiations. #define RU_LAUNCH(AB, NM, VSC, NTC, ANCC, STGC, SDTC) \ hipLaunchKernelGGL((r4d_gdn_recurrent_update_kernel), \ grid, blk, 0, (hipStream_t)stream, \ @@ -959,38 +784,23 @@ static int ru_update_launch( #define RU_PICKANC(SDTC) \ do { if (anc) RU_PICKNT(1, SDTC); else RU_PICKNT(0, SDTC); } while (0) - // The staged path is instantiated for the shape a decode step runs: bf16 a/b, no fused row - // norm, VS 1, anchor on. Everything else keeps the per-row path, which is why STG defaults - // to 0 in the template rather than being threaded through every instantiation. + // The staged path (STG) is instantiated only for the decode shape: bf16 a/b, no fused row norm, + // VS 1. Everything else uses the per-row path (STG 0). const int sdt = state_fp16 ? 1 : 0; - const int stg = RU_STG; - const bool anc = ru_anchor(); - // Bytes of state this launch will write. ONE SLOT A SEQUENCE UNDER THE ANCHOR, one a candidate - // without it, and the difference is a factor of six: assuming the per-candidate count - // unconditionally makes the RU_NT_MB threshold read an eight-request anchored step as a 37.7 MB - // flood when it is really 6.3 MB, and puts it on the wrong side of the branch. + // Bytes of state this launch writes: one slot per sequence under the anchor, one per candidate + // without it. const long slots_written = anc ? 1 : (long)indices_stride; const long flood = (long)N * slots_written * state_slot_stride * (sdt ? 2 : 4); const bool nt = flood <= (long)RU_NT_MB * 1024 * 1024; - // The factor block lives inside one head's slice of a state slot, so it has to fit: one token is - // RU_FSTR elements and there are `indices_stride` (= the candidate width) of them. - // SIX columns are addressed under the anchor -- three copies of the state and three of the - // factor block, so one fixed read column is right whichever way the page index moved -- and a - // caller whose candidate width is narrower than that cannot use it. - // - // THESE RUN BEFORE THE STAGED PATH, NOT AFTER IT. The staged branch below returns, and it is - // instantiated with ANCC=1, RU_STG's default of 1 and the vs == 1 the anchor forces -- so the - // shipped anchor path is precisely the one that reaches sidx[n*stride + 0..5] and writes the - // factor block. Placing these checks after it would leave both bounds untested on exactly that - // path. + // Anchor bounds: six columns are addressed (three anchor, three factor), and the factor block + // (indices_stride tokens of RU_FSTR) must fit in one head's slice of a slot. Keep these before + // the staged path, which returns early and is the shipped anchor path. if (anc && indices_stride < 6) return -4; if (anc && (long)indices_stride * RU_FSTR > state_head_stride) return -3; - if (stg && ab_is_bf16 && !nm0 && vs == 1 && indices_stride <= RU_TMAX) { + if (ab_is_bf16 && !nm0 && vs == 1 && indices_stride <= RU_TMAX) { #define RU_PICKSTG2(ANCC, SDTC) \ - do { if (nt) { if (stg == 1) RU_LAUNCH(1, 0, 1, 1, ANCC, 1, SDTC); \ - else RU_LAUNCH(1, 0, 1, 1, ANCC, 2, SDTC); } \ - else { if (stg == 1) RU_LAUNCH(1, 0, 1, 0, ANCC, 1, SDTC); \ - else RU_LAUNCH(1, 0, 1, 0, ANCC, 2, SDTC); } } while (0) + do { if (nt) RU_LAUNCH(1, 0, 1, 1, ANCC, 1, SDTC); \ + else RU_LAUNCH(1, 0, 1, 0, ANCC, 1, SDTC); } while (0) #define RU_PICKSTG(SDTC) do { if (anc) RU_PICKSTG2(1, SDTC); else RU_PICKSTG2(0, SDTC); } while (0) if (sdt) RU_PICKSTG(1); else RU_PICKSTG(0); #undef RU_PICKSTG @@ -1021,16 +831,15 @@ extern "C" int r4d_gdn_recurrent_update_k128_v128_bf16_fp32state( state_slot_stride, state_head_stride, o, oq, os, oq_pitch, os_ld, cu, ssm_state_indices, indices_stride, num_accepted, z_gate, z_pitch, norm_weight, norm_eps, norm_act, N, H, Hg, K, V, scale, softplus_thr, - state_fp16, stream, 0); + state_fp16, stream, 0, ru_anchor()); } // ============================================================== the folded convolution -// The folded convolution's arrival counters, ONE BLOCK A (STREAM, OUTPUT), zeroed once and kept -// zero by the last arriver of every group -- the invariant, and the keying, of split_ctr in -// r4d_gemm_fp8a8.hip: two launches that share a block must never run at once, launches on two -// streams are told apart by the stream, and launches on one stream that share an output are -// ordered by the dependency between them. +// Arrival counters for the folded convolution: one block per (stream, output), zeroed once and +// reset by the last arriver of each group. As with split_ctr in r4d_gemm_fp8a8.hip, launches +// sharing a block must not overlap: different streams get different blocks, and launches on one +// stream sharing an output are ordered by their dependency. constexpr unsigned kMaxConvCtr = 4096; static unsigned int* ru_conv_ctr(RadStream s, const void* out) { @@ -1049,10 +858,9 @@ static unsigned int* ru_conv_ctr(RadStream s, const void* out) { return (unsigned int*)p; } -// The recurrent update with gdn_conv_update folded into its prologue: the decode shape only -- -// bf16 a/b, the fused row norm, one workgroup per (sequence, value head) -- which is the one a -// decode step runs. The state contract, the non-temporal choice and the factor-block bounds are -// the unfolded launcher's. +// The recurrent update with gdn_conv_update folded in, decode shape only (bf16 a/b, fused row +// norm, one workgroup per (sequence, value head)). State contract, non-temporal choice and +// factor-block bounds are as in ru_update_launch. static int ru_conv_recurrent_launch(const RuConv& cv, const void* a, const void* b, long ab_stride, const void* A_log, const void* dt_bias, void* state, long st_slot, long st_head, void* o, void* oq, void* os, @@ -1060,8 +868,7 @@ static int ru_conv_recurrent_launch(const RuConv& cv, const void* a, const void* long sidx_stride, const void* nacc, const void* z, long z_pitch, const void* nw, float neps, int nact, int N, int H, int Hg, float scale, float thr, int state_fp16, - RadStream stream, int oq_i8) { - const bool anc = ru_anchor(); + RadStream stream, int oq_i8, bool anc) { if (anc && sidx_stride < 6) return RAD_E_SHAPE; if (anc && sidx_stride * RU_FSTR > st_head) return RAD_E_SHAPE; const int sdt = state_fp16 ? 1 : 0; @@ -1093,16 +900,22 @@ static int ru_conv_recurrent_launch(const RuConv& cv, const void* a, const void* return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; } -// The operand enum carries an `OPD_` prefix: RU_K and RU_V are this kernel's head widths. // ============================================================== the plugin ABI entry points -// -// The shared operand helpers are r4d_gdn_args.h. See libr4d/r4d_args.h for why there is no -// adapter directory between the core and these launches. +// Shared operand helpers: r4d_gdn_args.h. Operand enums use an OPD_ prefix because RU_K and RU_V +// are kernel constants. /* ------------------------------------------------------------------ recurrent update */ enum { OPD_RU_Q = 0, OPD_RU_K, OPD_RU_V, OPD_RU_A, OPD_RU_B, OPD_RU_ALOG, OPD_RU_DTB, OPD_RU_STATE, OPD_RU_SIDX, OPD_RU_NACC, OPD_RU_CU, OPD_RU_Z, OPD_RU_NORMW, OPD_RU_O, OPD_RU_OQ, OPD_RU_OS }; +/* The op's `state_form`: 1 for anchor, 0 for per_candidate (also the default), -1 for a form this + * kernel does not implement. The pool behind `state` was sized for the declared form. */ +static int ru_state_form(const RadArgs* a) { + const char* sf = r4d_gets(a, "state_form"); + if (!sf || std::strcmp(sf, "per_candidate") == 0) return 0; + return std::strcmp(sf, "anchor") == 0 ? 1 : -1; +} + extern "C" int r4d_rad_gdn_recurrent_update(const RadArgs* a, RadStream s) { if (gdn_dims_ok() != RAD_OK) return R4D_NO(RAD_E_SHAPE); const RadTensor* q = r4d_opt(a, OPD_RU_Q); @@ -1126,10 +939,8 @@ extern "C" int r4d_rad_gdn_recurrent_update(const RadArgs* a, RadStream s) { if (q->rank != 3 || k->rank != 3 || v->rank != 3 || o->rank != 3) return R4D_NO(RAD_E_SHAPE); if (state->rank < 2 || sidx->rank < 1 || ta->rank != 2 || tb->rank != 2) return R4D_NO(RAD_E_SHAPE); - /* N COMES FROM cu, not from the state-index tensor. The kernel reads cu[n] and cu[n+1] for - * every n in the grid, so cu's own length is the only thing that bounds the grid safely -- - * deriving N from state_idx and trusting cu to be at least as long is the off-by-one that - * seqs_of() exists to refuse. state_idx is then checked against it rather than defining it. */ + /* N comes from cu (the kernel reads cu[n + 1] for every n in the grid); state_idx is checked + * against it. */ int N = 0; int rc = seqs_of(cu, &N); if (rc != RAD_OK) return rc; @@ -1146,49 +957,33 @@ extern "C" int r4d_rad_gdn_recurrent_update(const RadArgs* a, RadStream s) { const long long V = v->shape[2]; if (H == 0 || Hg == 0 || H % Hg) return R4D_NO(RAD_E_SHAPE); - /* THE TWO SIDES OF THE STATE CONTRACT HAVE TO AGREE, AND THEY SAY SO. The anchor form is - * selected by RADIANCE_GDN_ANCHOR because the kernel serves a second, out-of-tree caller that - * has no RadArgs to declare it in -- but a caller that DOES declare `state_form` is naming the - * shape its pool was sized for, and running the other form against that pool is silently wrong - * rather than slow: per-candidate indexing into a two-slot pool gives three candidate tokens - * the same slot, so a partially accepted step resumes from a state two tokens too far along. - * Refusing by name turns the one configuration nothing would catch into a selection error, - * which the run phase reports with both the kernel and the geometry. */ - if (const char* sf = r4d_gets(a, "state_form")) { - const int want_anc = std::strcmp(sf, "anchor") == 0; - if (!want_anc && std::strcmp(sf, "per_candidate") != 0) return R4D_NO(RAD_E_UNSUPPORTED); - if (want_anc != (ru_anchor() ? 1 : 0)) return R4D_NO(RAD_E_UNSUPPORTED); - } + const int anc = ru_state_form(a); + if (anc < 0) return R4D_NO(RAD_E_UNSUPPORTED); const float scale = (float)r4d_getf(a, "scale", 1.0); const float thr = (float)r4d_getf(a, "softplus_thr", 20.0); - /* The vocabulary's names for the folded gated norm, mapped here to libr4d's arguments. */ + /* Folded gated norm parameters. */ const float neps = (float)r4d_getf(a, "eps", 0.0); const int nact = r4d_act_code(a, "act", "norm_act", 0); if (nact < 0) return R4D_NO(RAD_E_INVAL); - /* Same compiled-in 1e-6f as the prefill preamble's l2 norm; see r4d_rad_gdn_conv_prep. */ + /* The l2 norm epsilon is compiled in, as in r4d_rad_gdn_conv_prep. */ if ((float)r4d_getf(a, "l2_eps", 1e-6) != 1e-6f) return R4D_NO(RAD_E_UNSUPPORTED); - /* See the note on the chunk scan: the cache's dtype is what says how wide the state is, not a - * declared parameter. Both kernels read it off the same operand so they cannot disagree. */ + /* State width from the cache's dtype, as in the chunk scan. */ const int sfp16 = state->dtype == RAD_F16; const int ab_is_bf16 = (ta->dtype == RAD_BF16) ? 1 : 0; if (tb->dtype != ta->dtype) return R4D_NO(RAD_E_DTYPE); - /* `n_head_v` is optional and, where the caller states it, has to agree with the value tensor - * -- two sources for one number, and the disagreement would stride through the wrong heads. */ + /* Optional n_head_v must agree with the value tensor. */ const long long nhv = r4d_geti_or(a, "n_head_v", 0); if (nhv > 0 && nhv != H) return R4D_NO(RAD_E_SHAPE); - /* "bf16 q/k/v and out, fp32 a,b and state cache", plus fp32 A_log / dt_bias / norm weight and - * a bf16 z gate -- the casts in r4d_gdn_recurrent_update_k128_v128_bf16_fp32state. */ + /* bf16 q/k/v/out/z; f32 or f16 state; fp32 A_log, dt_bias and norm weight. */ R4D_DT(q, RAD_BF16); R4D_DT(k, RAD_BF16); R4D_DT(v, RAD_BF16); R4D_DT(o, RAD_BF16); R4D_DT(z, RAD_BF16); if (state->dtype != RAD_F32 && state->dtype != RAD_F16) return R4D_NO(RAD_E_DTYPE); R4D_DT(alog, RAD_F32); R4D_DT(dtb, RAD_F32); R4D_DT(nw, RAD_F32); - /* THE FOLDED QUANTISER IS ALL-OR-NOTHING, and it needs the fused norm: without z and norm_w - * the kernel splits a head's rows across workgroups (VS > 1 above), and a block-scaled group - * whose amax is spread over several workgroups cannot be reduced in one of them. Refusing is - * the only safe answer -- a partial scale plane is wrong numbers, not a slow path. */ + /* The folded quantiser needs oq and os together, and the fused norm: without it a head's rows + * may be split across workgroups (VS > 1), and a group amax cannot span workgroups. */ if ((oq != nullptr) != (os != nullptr)) return R4D_NO(RAD_E_INVAL); if (oq) { if (!z || !nw) return R4D_NO(RAD_E_UNSUPPORTED); @@ -1198,17 +993,14 @@ extern "C" int r4d_rad_gdn_recurrent_update(const RadArgs* a, RadStream s) { if (!r4d_contig(oq)) return R4D_NO(RAD_E_STRIDE); } - /* THE GATE MAY BE A COLUMN VIEW. The delta net's in-projection and its output gate are one - * GEMM (rad_block_gdn_fp8.h), so `z` is the right-hand columns of a wider row: its tokens are - * `z_row` elements apart, not H*V. Every other layout this op accepts -- a [tokens, H*V] - * buffer of its own, a [tokens, H, V] one -- answers the same number. */ + /* z may be a column view of the fused in-projection (rad_block_gdn_fp8.h): tokens are z_row + * elements apart, not H*V. */ const long long z_row = z ? gn_row_pitch(z, H * V) : 0; if (z && z_row < 0) return R4D_NO(RAD_E_STRIDE); - /* THE SLOT AND HEAD STRIDES COME FROM THE TENSOR. The KV manager pads a linear-state page to - * the attention page size (spec §7.2), so a slot is wider than H*V*K and deriving the stride - * from the shape reads the wrong memory for every slot but the first. */ - return ru_update_launch( + /* Slot and head strides come from the tensor, so a cache with padded slots is served too + * (see the header); the engine's own state cache is dense ([n_states, H, V, K] per layer). */ + return R4D_RAW(ru_update_launch( q->data, k->data, v->data, ta->data, tb->data, (long)ab_stride, ab_is_bf16, alog->data, dtb->data, state->data, (long)state->stride[0], (long)state->stride[1], @@ -1218,14 +1010,14 @@ extern "C" int r4d_rad_gdn_recurrent_update(const RadArgs* a, RadStream s) { nacc ? nacc->data : nullptr, z ? z->data : nullptr, (long)z_row, nw ? nw->data : nullptr, neps, nact, N, (int)H, (int)Hg, (int)K, (int)V, scale, thr, sfp16, s, - oq && oq->dtype == RAD_I8 ? 1 : 0); + oq && oq->dtype == RAD_I8 ? 1 : 0, anc != 0)); } /* ------------------------------------------------------------------ conv + recurrent update */ -/* gdn_conv_update's inputs, then gdn_recurrent_update's minus q, k and v, which are the pair's - * intermediate and never reach memory here. Inputs first, outputs last -- docs/OPS.md. */ +/* gdn_conv_update's inputs, then gdn_recurrent_update's minus q, k and v (never materialised). + * Inputs first, outputs last (docs/OPS.md). */ enum { OPD_CR_X = 0, OPD_CR_CW, OPD_CR_CB, OPD_CR_CSTATE, OPD_CR_CIDX, OPD_CR_A, OPD_CR_B, OPD_CR_ALOG, OPD_CR_DTB, OPD_CR_STATE, OPD_CR_SIDX, OPD_CR_NACC, OPD_CR_CU, OPD_CR_Z, OPD_CR_NORMW, OPD_CR_O, OPD_CR_OQ, OPD_CR_OS }; @@ -1250,8 +1042,8 @@ extern "C" int r4d_rad_gdn_conv_recurrent_update(const RadArgs* a, RadStream s) const RadTensor* o = r4d_opt(a, OPD_CR_O); const RadTensor* oq = r4d_opt(a, OPD_CR_OQ); const RadTensor* os = r4d_opt(a, OPD_CR_OS); - /* THE ROW NORM IS REQUIRED: the fold is the decode shape, one workgroup per (sequence, value - * head), and that is the shape the norm already forces on the unfolded kernel. */ + /* The row norm is required: the fold is the decode shape, one workgroup per (sequence, value + * head). */ if (!x || !cw || !cst || !cidx || !ta || !tb || !alog || !dtb || !state || !sidx || !cu || !z || !nw || !o) return R4D_NO(RAD_E_INVAL); @@ -1265,8 +1057,7 @@ extern "C" int r4d_rad_gdn_conv_recurrent_update(const RadArgs* a, RadStream s) if (rc != RAD_OK) return rc; if (sidx->shape[0] != N) return R4D_NO(RAD_E_SHAPE); - /* THE HEAD GEOMETRY COMES FROM `o` AND `x`: `o` is [tokens, H, V] and `x` is the projection's - * [q | k | v] columns, 2 Hg K + H V wide. There is no q, k or v operand to read it off. */ + /* Head geometry from o ([tokens, H, V]) and x ([q | k | v] columns, 2 Hg K + H V wide). */ const long long T = o->shape[0]; const long long H = o->shape[1]; const long long V = o->shape[2]; @@ -1297,20 +1088,16 @@ extern "C" int r4d_rad_gdn_conv_recurrent_update(const RadArgs* a, RadStream s) if (!r4d_contig(oq)) return R4D_NO(RAD_E_STRIDE); } - /* THE WINDOW, as gdn_conv_update derives it: the cache depth fixes max_query_len as - * state_len_max - (width - 2), and a sequence brings at most that many tokens. The fold holds - * them in registers, so the deployment's window has to fit RU_CVT. */ + /* The window as in gdn_conv_update: max_query_len = state_len_max - (width - 2), and it must + * fit RU_CVT, since the fold holds the tokens in registers. */ if (r4d_geti_or(a, "conv_width", 0) != R4D_GDN_CONV_W) return R4D_NO(RAD_E_UNSUPPORTED); const long long mql = cst->shape[2] - (R4D_GDN_CONV_W - 2); if (mql < 1) return R4D_NO(RAD_E_SHAPE); if (mql > RU_CVT) return R4D_NO(RAD_E_UNSUPPORTED); - /* The recurrent half's contract checks, as r4d_rad_gdn_recurrent_update makes them. */ - if (const char* sf = r4d_gets(a, "state_form")) { - const int want_anc = std::strcmp(sf, "anchor") == 0; - if (!want_anc && std::strcmp(sf, "per_candidate") != 0) return R4D_NO(RAD_E_UNSUPPORTED); - if (want_anc != (ru_anchor() ? 1 : 0)) return R4D_NO(RAD_E_UNSUPPORTED); - } + /* The recurrent half's checks, as in r4d_rad_gdn_recurrent_update. */ + const int anc = ru_state_form(a); + if (anc < 0) return R4D_NO(RAD_E_UNSUPPORTED); const float scale = (float)r4d_getf(a, "scale", 1.0); const float thr = (float)r4d_getf(a, "softplus_thr", 20.0); const float neps = (float)r4d_getf(a, "eps", 0.0); @@ -1337,5 +1124,5 @@ extern "C" int r4d_rad_gdn_conv_recurrent_update(const RadArgs* a, RadStream s) os ? (long)r4d_row_pitch(os) : 0, cu->data, sidx->data, (long)sidx->stride[0], nacc ? nacc->data : nullptr, z->data, (long)z_row, nw->data, neps, nact, N, (int)H, (int)Hg, scale, thr, state->dtype == RAD_F16 ? 1 : 0, s, - oq && oq->dtype == RAD_I8 ? 1 : 0); + oq && oq->dtype == RAD_I8 ? 1 : 0, anc != 0); } diff --git a/libr4d/r4d_gdn_wmma.h b/libr4d/r4d_gdn_wmma.h index 2c4923e6..a8cf7a3c 100644 --- a/libr4d/r4d_gdn_wmma.h +++ b/libr4d/r4d_gdn_wmma.h @@ -2,17 +2,16 @@ // Layout (probed on this hardware, not documented by AMD): // 16-bit A/B : idx = lane%16 , k = 8*(e>>2) + 4*(lane>>4) + (e&3) ("two runs of four") // f32 C/D : n = lane%16 , m = 8*(lane>>4) + e -// So A wants [M][K] and B wants [N][K] -- both K-contiguous -- and a D written to an -// [N][M] buffer is one contiguous 8-element store while [M][N] costs eight scalar ones. +// So A wants [M][K] and B wants [N][K] (both K-contiguous), and D stored to an [N][M] buffer is +// one contiguous 8-element store, while [M][N] costs eight scalar ones. #pragma once #include typedef __bf16 v8bf __attribute__((ext_vector_type(8))); typedef float v8f __attribute__((ext_vector_type(8))); -// gfx1201 has no bf16 convert instruction, so this is software. Round-half-away -// (u + 0x8000) is one add where RTNE needs bfe + add3 + shift; the two differ only -// when the discarded mantissa is exactly 0x8000, i.e. ~2^-16 of values. +// Software f32 -> bf16 (gfx1201 has no convert). Round-half-away (u + 0x8000) is one add where +// RTNE needs bfe + add3 + shift; they differ only when the discarded bits are exactly 0x8000. __device__ __forceinline__ unsigned short f2bf(float f) { return (unsigned short)((__builtin_bit_cast(unsigned, f) + 0x8000u) >> 16); } @@ -26,29 +25,16 @@ __device__ __forceinline__ unsigned f2bf2(float a, float b) { __device__ __forceinline__ uint2 f2bf4(float a, float b, float c, float d) { return make_uint2(f2bf2(a, b), f2bf2(c, d)); } -// Truncating pack: ONE v_perm_b32 per pair. The +0x8000 rounding adds cannot be -// dual-issued (VOPD rejects the literal), so each is a full VALU slot -- 96 per chunk. -// Truncation costs up to 1 ULP of bf16 instead of 0.5. -__device__ __forceinline__ unsigned f2bf2t(float a, float b) { - return __builtin_amdgcn_perm(__builtin_bit_cast(unsigned, b), - __builtin_bit_cast(unsigned, a), 0x07060302u); -} -__device__ __forceinline__ uint2 f2bf4t(float a, float b, float c, float d) { - return make_uint2(f2bf2t(a, b), f2bf2t(c, d)); -} __device__ __forceinline__ float bf2f(unsigned short h) { return __builtin_bit_cast(float, (unsigned)h << 16); } -// K-contiguous fragment from a row pointer already advanced to this lane's row and -// half-K. The four dwords are indexed off ONE base so the assembler folds them into -// two ds_read2_b32 with immediate offsets; writing `p + 8` instead makes LLVM -// materialise a second address register per fragment (262 v_add_nc_u32 in the loop). -// The four dwords are two 8-BYTE groups 16 bytes apart, so reading them as uint2 gets -// one ds_load_2addr_b64 where reading them as four unsigned gets two ds_load_2addr_b32: -// LLVM will only pair dwords into a b64 access if the pointer proves 8-byte alignment, -// which every fragment address has (all row pitches are multiples of 4 shorts and the -// lane's k offset is 4*(lane>>4)). Halves the fragment-load instruction count. +// K-contiguous fragment from a row pointer already advanced to this lane's row and half-K. +// Indexed off one base so the loads take immediate offsets (`p + 8` makes LLVM materialise a +// second address register per fragment). The data is two 8-byte groups 16 bytes apart; reading +// them as uint2 gives one ds_load_2addr_b64 instead of two ds_load_2addr_b32. LLVM pairs into b64 +// only with provable 8-byte alignment, which holds: row pitches are multiples of 4 shorts and the +// lane's k offset is 4*(lane>>4). __device__ __forceinline__ v8bf fragP(const unsigned short* p) { const uint2* pw = (const uint2*)p; union { uint2 w[2]; v8bf f; } u; @@ -60,22 +46,12 @@ __device__ __forceinline__ const unsigned short* rowP(const unsigned short* src, int pitch, int base, int lane) { return src + (base + (lane & 15)) * pitch + 4 * (lane >> 4); } -// Row pointer for a global source; `lim` clamps so a partial last chunk cannot read -// past the tensor (those rows are discarded downstream). -__device__ __forceinline__ const unsigned short* rowG(const unsigned short* base, - size_t rowstride, int row0, - int lim, int lane) { - int r = row0 + (lane & 15); r = r < lim ? r : lim; - return base + (size_t)r * rowstride + 4 * (lane >> 4); -} -// 32-BIT element offset for a global fragment source, split from a UNIFORM base. -// The pointer form above compiles to ~13 instructions per fragment at this kernel's -// register pressure: the `size_t` row stride forces v_mad_co_i64_i32 + v_lshlrev_b64 + -// a 64-bit add, the ternary becomes exec-mask manipulation, LLVM will not keep the -// address live across the k loop so it remats all of it per load, and a generic -// pointer emits flat_load (which bumps BOTH loadcnt and dscnt on gfx12, so an LDS -// drain also waits on HBM). Keeping the offset in one 32-bit register instead lets -// the whole k loop be global_load_b64 vdst, voff, s[base] with a 13-bit immediate. +// 32-bit element offset for a global fragment, split from a uniform base. `lim` clamps the row so a +// partial last chunk cannot read past the tensor (those rows are discarded downstream). A per-lane +// 64-bit row pointer costs ~13 instructions per fragment under register pressure (64-bit stride +// math, exec-mask ternary, rematerialised per load) and can emit flat_load, which on gfx12 bumps +// both loadcnt and dscnt so LDS drains also wait on memory. A 32-bit offset makes the k loop +// global_load_b64 vdst, voff, s[base] with a 13-bit immediate. __device__ __forceinline__ unsigned rowGo(unsigned rowstride, int row0, int lim, int lane) { int r = row0 + (lane & 15); r = r < lim ? r : lim; @@ -87,14 +63,10 @@ __device__ __forceinline__ v8bf fragGo(const unsigned short* base, unsigned off) u.w[0] = pw[0]; u.w[1] = pw[2]; return u.f; } -// Fragment from a 32-BIT LDS BYTE OFFSET off the shared-block base. LDS row pointers -// into different buffers of a large __shared__ block are further apart than -// ds_read2_b32's immediate reach (8-bit fields in dwords = 1020 B), so LLVM will not -// keep one base register per buffer live -- it rematerialises -// `v_add_nc_u32 vaddr, , vbase` in front of EVERY fragment, and then -// splits the fragment's two dword pairs across two address registers as well. -// Holding the offset in one opaque register instead makes all 8 k steps immediates -// (8 dwords apart, 61 max -- well inside the field). +// Fragment from a 32-bit LDS byte offset off the shared-block base. Buffers in a large __shared__ +// block are further apart than ds_read2_b32's immediate reach (1020 B), so LLVM rematerialises +// `v_add_nc_u32 vaddr, , vbase` before every fragment. An opaque offset register +// (LDSOPAQUE) keeps all 8 k steps as immediates (8 dwords apart, 61 max). __device__ __forceinline__ v8bf fragO(const char* sb, unsigned off) { const uint2* pw = (const uint2*)(sb + off); union { uint2 w[2]; v8bf f; } u; @@ -137,15 +109,3 @@ __device__ __forceinline__ v8f gemm(const unsigned short* A, int Ap, int mt, acc = mma(frag(A, Ap, mt * 16, s * 16, lane), frag(B, Bp, nt * 16, s * 16, lane), acc); return acc; } - -// Fragment straight from global memory (no LDS staging). `lim` clamps the row so a -// partial last chunk cannot read past the tensor; those rows are discarded downstream. -__device__ __forceinline__ v8bf fragG(const unsigned short* base, size_t rowstride, - int row0, int lim, int kbase, int lane) { - int r = row0 + (lane & 15); r = r < lim ? r : lim; - const unsigned short* p = base + (size_t)r * rowstride + kbase + 4 * (lane >> 4); - union { unsigned w[4]; v8bf f; } u; - u.w[0] = ((const unsigned*)p)[0]; u.w[1] = ((const unsigned*)p)[1]; - u.w[2] = ((const unsigned*)(p + 8))[0]; u.w[3] = ((const unsigned*)(p + 8))[1]; - return u.f; -} diff --git a/libr4d/r4d_gelu_mul_quant_i8.hip b/libr4d/r4d_gelu_mul_quant_i8.hip index 86901ff8..6da55173 100644 --- a/libr4d/r4d_gelu_mul_quant_i8.hip +++ b/libr4d/r4d_gelu_mul_quant_i8.hip @@ -1,12 +1,10 @@ // r4d_gelu_mul_quant_i8.hip - r4d_gelu_mul_quant_i8: gelu(gate) * up and the per-row int8 quantiser // r4d_gemm_w4a8_nt_m64 reads, in one pass over the row. // -// The down projection's input of a GELU-gated feed-forward (Gemma) on a w4a8 grid: unfused it is -// gelu_mul and quant_act_i8, two single-row dispatches at a decode batch. This is the pair as one, -// BYTE-IDENTICAL to it: the product is formed exactly as gelu_mul_kernel forms it (the tanh form, -// the same constants, rounded to bf16), and the absmax, scale and codes are quant_act_i8's over -// those bf16 values -- the absmax is a max and so takes no partition, and every code is a function -// of its own value and the row scale. +// The down projection's input of a GELU-gated feed-forward (Gemma) on a w4a8 grid, replacing the +// gelu_mul + quant_act_i8 pair and byte-identical to it: the product is formed as gelu_mul_kernel +// forms it (tanh form, same constants, rounded to bf16), and the absmax, scale and codes are +// quant_act_i8's over those bf16 values. The absmax is a max, so partitioning does not change it. #include "r4d.h" #include "r4d_args.h" #include "r4d_emit.h" @@ -15,8 +13,6 @@ namespace { -__device__ __forceinline__ float bf2f(uint16_t h) { return __uint_as_float((uint32_t)h << 16); } - template __global__ __launch_bounds__(THR) void gelu_mul_quant_i8_kernel( const uint16_t* __restrict__ gu, signed char* __restrict__ q, float* __restrict__ S, @@ -29,13 +25,13 @@ __global__ __launch_bounds__(THR) void gelu_mul_quant_i8_kernel( float m = 0.0f; for (uint32_t i = threadIdx.x; i < n; i += THR) { - const float g = bf2f(gr[i]); + const float g = bf16_to_f32(gr[i]); const float k0 = 0.7978845608028654f, k1 = 0.044715f; const float gelu = 0.5f * g * (1.0f + tanhf(k0 * (g + k1 * g * g * g))); - const uint16_t y = f32_to_bf16(gelu * bf2f(gr[n + i])); + const uint16_t y = f32_to_bf16(gelu * bf16_to_f32(gr[n + i])); ybuf[i] = y; if (yo) yo[(size_t)row * y_ld + i] = y; - m = fmaxf(m, fabsf(bf2f(y))); + m = fmaxf(m, fabsf(bf16_to_f32(y))); } m = r4d_wave_max(m); if ((threadIdx.x & 31) == 0) lm[threadIdx.x >> 5] = m; @@ -50,7 +46,7 @@ __global__ __launch_bounds__(THR) void gelu_mul_quant_i8_kernel( for (uint32_t i = threadIdx.x; i < n; i += THR) { const uint32_t s = i >> 4, j = i & 15; const uint32_t src = (s << 4) + 8 * ((j & 7) >> 2) + 4 * (j >> 3) + (j & 3); - const int t = __float2int_rn(bf2f(ybuf[src]) * inv); + const int t = __float2int_rn(bf16_to_f32(ybuf[src]) * inv); qr[i] = (signed char)(t < -128 ? -128 : (t > 127 ? 127 : t)); } } @@ -61,7 +57,7 @@ __global__ __launch_bounds__(THR) void gelu_mul_quant_i8_kernel( // fragment order, scale [M][1] f32, out_bf16 [M][n] bf16 optional. enum { GM_GU = 0, GM_Q, GM_S, GM_Y }; -static int rad_gelu_mul_quant_i8_body(const RadArgs* a, const R4dSink& sk) { +extern "C" int r4d_rad_gelu_mul_quant_i8(const RadArgs* a, RadStream stream) { int emit_rc = RAD_OK; const RadTensor* gu = r4d_opt(a, GM_GU); const RadTensor* q = r4d_opt(a, GM_Q); @@ -83,7 +79,7 @@ static int rad_gelu_mul_quant_i8_body(const RadArgs* a, const R4dSink& sk) { const size_t lds = (size_t)n * sizeof(uint16_t); if (lds > 60 * 1024) return R4D_NO(RAD_E_SHAPE); const int thr = r4d_act_threads((int)M, (int)n); -#define R4D_GMQ_T(T) emit_rc = R4D_EMIT(sk, (gelu_mul_quant_i8_kernel), dim3((uint32_t)M), dim3(T), lds, \ +#define R4D_GMQ_T(T) emit_rc = R4D_EMIT(stream, (gelu_mul_quant_i8_kernel), dim3((uint32_t)M), dim3(T), lds, \ (const uint16_t*)r4d_p(gu), (signed char*)r4d_wp(q), (float*)r4d_wp(s), (uint16_t*)r4d_wp(y), \ (uint32_t)n, (uint32_t)gp, (uint32_t)yp) if (thr == 1024) R4D_GMQ_T(1024); @@ -93,4 +89,3 @@ static int rad_gelu_mul_quant_i8_body(const RadArgs* a, const R4dSink& sk) { #undef R4D_GMQ_T return emit_rc; } -R4D_ENTRY(r4d_rad_gelu_mul_quant_i8, rad_gelu_mul_quant_i8_body) diff --git a/libr4d/r4d_gemm_args.h b/libr4d/r4d_gemm_args.h index 37c21ae7..14d83c2a 100644 --- a/libr4d/r4d_gemm_args.h +++ b/libr4d/r4d_gemm_args.h @@ -1,13 +1,11 @@ -/* r4d_gemm_args.h -- the skinny GEMMs' operand list and their split law. +/* r4d_gemm_args.h -- the skinny GEMMs' operand lists and their split law. * - * The launch law -- ladders, caps, `pick_sk`, a bound rule per weight grid -- lives beside the - * kernels it decides for, so a kernel library built out of tree carries its own rule instead of - * depending on one held in the engine. The declared tunable axes (r4d_rows.cpp) are the half of - * that a tuner walks; this is the half that answers when a shape is left on the axis defaults. + * The launch law (ladders, caps, `pick_sk`, a bound rule per weight grid) lives beside the kernels + * so an out-of-tree kernel library carries its own rule. The tunable axes (r4d_rows.cpp) are what + * a tuner walks; this resolves a shape left on the axis defaults. * - * The operand plumbing is here for the ordinary reason: eleven kernels across eleven translation - * units read the same two operand lists -- [A, B, Y] for the bf16 grid and [A, a_scale, B, - * b_scale, Y, a_sum, B_ref] for every quantised one -- because they implement two ops. + * Eleven kernels read one of two operand lists: [A, B, Y] for bf16 and + * [A, a_scale, B, b_scale, Y, a_sum, B_ref] for every quantised grid. */ #ifndef R4D_GEMM_ARGS_H #define R4D_GEMM_ARGS_H @@ -21,29 +19,18 @@ #include -/* The build passes the same -DR4D_GEMM_*_GROUP to libr4d's translation units and to this one, so - * these cannot drift apart silently -- a weight file written for one group and read by a kernel - * compiled for another is wrong by a factor of nothing visible. */ -#ifndef R4D_GEMM_W4_GROUP -#define R4D_GEMM_W4_GROUP 128 -#endif -#ifndef R4D_GEMM_W8_GROUP -#define R4D_GEMM_W8_GROUP 128 -#endif -#ifndef R4D_GEMM_W4A8_GROUP +/* K per scale group of each quantised weight layout. A mismatch between weight file and kernel + * would be silently wrong, so each is checked against r4d_args.h's layout constant. */ +#define R4D_GEMM_W4_GROUP 128 +#define R4D_GEMM_W8_GROUP 128 #define R4D_GEMM_W4A8_GROUP 128 -#endif -#ifndef R4D_GEMM_W8A8_GROUP #define R4D_GEMM_W8A8_GROUP 128 -#endif -#ifndef R4D_GEMM_W2A8_GROUP #define R4D_GEMM_W2A8_GROUP 128 -#endif -static_assert(R4D_W4_GROUP == R4D_GEMM_W4_GROUP, "w4 group differs from libr4d's build"); -static_assert(R4D_W8_GROUP == R4D_GEMM_W8_GROUP, "w8 group differs from libr4d's build"); -static_assert(R4D_W4_GROUP == R4D_GEMM_W4A8_GROUP, "w4a8 group differs from libr4d's build"); -static_assert(R4D_W8_GROUP == R4D_GEMM_W8A8_GROUP, "w8a8 group differs from libr4d's build"); -static_assert(R4D_W2_GROUP == R4D_GEMM_W2A8_GROUP, "w2a8 group differs from libr4d's build"); +static_assert(R4D_W4_GROUP == R4D_GEMM_W4_GROUP, "w4 group differs from the layout constant"); +static_assert(R4D_W8_GROUP == R4D_GEMM_W8_GROUP, "w8 group differs from the layout constant"); +static_assert(R4D_W4_GROUP == R4D_GEMM_W4A8_GROUP, "w4a8 group differs from the layout constant"); +static_assert(R4D_W8_GROUP == R4D_GEMM_W8A8_GROUP, "w8a8 group differs from the layout constant"); +static_assert(R4D_W2_GROUP == R4D_GEMM_W2A8_GROUP, "w2a8 group differs from the layout constant"); static inline int gemm_caught(const char* who, const char* what) { @@ -64,41 +51,23 @@ static inline int gemm_caught(const char* who, const char* what) { /* ------------------------------------------------------------------ the split count * - * libr4d's skinny GEMMs put split-K IN THE WORKGROUP: SK k-splits per column tile, reduced in LDS, - * which is what fills a 64-CU part at M=1. The legality rule is K % (SK * unit) == 0, so no single - * SK is legal at every K -- and a DEFAULT that is illegal at a shape would make an untuned install - * FAIL rather than be slow, which is the wrong way round (spec §15). - * - * So the `sk` axis carries 0 as its DEFAULT and 0 means "the largest legal split from this K", - * resolved here. The candidate ladder is the set of split counts that tuned configurations use, in - * descending order, so an untuned install lands on a split count some shape was tuned to rather - * than on 1. The cost of the sentinel is that two shapes with different K both running - * `sk = 0` get different split counts; --debug-graph prints the chosen point, so a 0 there has to - * be read as "the law decided" and not as a number. + * The skinny GEMMs split K inside the workgroup: SK k-splits per column tile, reduced in LDS, to + * fill a 64-CU part at M=1. Legality is K % (SK * unit) == 0, so no single SK is legal at every K, + * and an illegal default would make an untuned install fail instead of run slowly (spec §15). + * The `sk` axis therefore defaults to 0, meaning "the largest legal split for this K" from a + * descending ladder of split counts tuned configurations use. A 0 in --debug-graph means the law + * decided, not a literal split. */ -/* THE LAUNCH BOUND IS PART OF A SPLIT'S LEGALITY. +/* The launch bound is part of a split's legality. The skinny kernels' __launch_bounds__ tighten as + * MB and NPW grow (w2a8: (MB >= 4) ? 256 : ((MB >= 2 || NPW >= 4) ? 512 : 1024)), and a block of + * WV*SK*32 threads over its bound fails to launch, surfacing later as a device error at the next + * sync. MB comes from M, so this only bites under concurrency: on the DFlash2 2-bit draft head + * (N = 248320), M >= 49 gives a bound of 256 where sk = 10 needs 320 threads. * - * libr4d's skinny kernels carry __launch_bounds__ that TIGHTEN as MB and NPW grow -- w2a8's is - * (MB >= 4) ? 256 : ((MB >= 2 || NPW >= 4) ? 512 : 1024) -- and a block of WV*SK*32 threads wider - * than its own bound is a launch failure, which surfaces later as a device error from whatever - * happens to synchronise next. A split count picked against a flat 1024 is therefore not - * necessarily legal. - * - * MB comes from M (`ceil(M/16)`, capped at 4), so this is an M-dependent trap that only springs - * under CONCURRENCY. On the DFlash2 2-bit draft head, N = 248320: M >= 49 gives MB = 4 and a bound - * of 256, where sk = 10 asks for 320 threads a block; M in [17, 48] gives MB = 2 and a bound of - * 512, where sk = 20 asks for 640. Any bench that runs M <= 16 sees none of it. The engine refuses - * the op at issue and fails the step, exactly as spec 17 says it must, so the symptom is - * concurrent requests coming back empty rather than a wrong number. - * - * EACH CALLER NAMES ITS OWN RULE, because they genuinely differ and one conservative rule costs - * real throughput: the bf16, w4a16, w8a16 and mxfp4 kernels declare a flat 1024 (or no - * __launch_bounds__ at all, which is the same 1024), and capping them as if they were w2a8 costs - * prefill throughput for nothing. w4a8 tightens on NPW alone and w8a8 on MT*NPW, both because the - * bound is a REGISTER budget, which their own headers say at length. Where a kernel's macro is - * switched off by a build flag the TIGHT branch is named here anyway: over-constraining a build - * that relaxed its bound loses a little parallelism, and under-constraining one that did not is the - * launch failure above. + * Each caller names its own rule because one conservative rule costs throughput: bf16, w4a16, + * w8a16 and mxfp4 are a flat 1024; w4a8 tightens on NPW and w8a8 on MB*NPW (a register budget). + * Where a build flag can disable a kernel's bound, the tight rule is named anyway: over-constraining + * loses a little parallelism, under-constraining fails to launch. */ enum BoundRule { BR_FLAT = 0, BR_W2A8, BR_NPW, BR_MBNPW }; @@ -111,154 +80,75 @@ static inline int block_bound(BoundRule r, int mb, int npw) { } } -static inline int pick_sk(long long K, long long unit, int wv, int bound) { - /* The ladder enumerates the candidate splits the law above can reach, so its top entry is the - * largest split any untuned shape will be given. 20 is on it because K = 5120 -- every - * projection in this model -- divides by it, and 20 is the fastest legal split at that K on the - * GDN a|b projection, which runs forty-eight times a step. `cap` still bounds the block at 1024 - * threads, which is what keeps wv = 2 from reaching 20 at all. - * - * 32 IS LEFT OUT ON PURPOSE. It is legal at K = 5120 and it is slower there than 20, so - * including it would move the default AWAY from the fastest split purely to reach a bigger - * number. The ladder tops out where the fastest split is, not where legality ends. */ - static const int ladder[] = { 20, 16, 10, 8, 5, 4, 2, 1 }; - const int cap = (wv > 0) ? (bound / (wv * 32)) : 1; /* threads/block <= this MB/NPW's bound */ - for (int s : ladder) { - if (s > cap) continue; - if (unit > 0 && (K % ((long long)s * unit)) == 0) return s; - } - return 1; -} - -/* "THE LARGEST LEGAL SPLIT" IS THE WRONG LAW WHERE N ALREADY SUPPLIES THE PARALLELISM, and the - * bf16 skinny GEMM is where that shows. The split exists to fill a 64-CU part at M = 1; a shape - * with eighty N tiles is already full, and splitting it twenty ways is 1600 workgroups whose only - * extra effect is the reduction. At K = 5120 the fastest split falls as N grows: at N = 48 (three - * N tiles) the split IS the parallelism and the largest legal one wins; at N = 256 (sixteen tiles) - * a split of 4 wins; at N = 1280 (eighty tiles) 1 or 2 does. - * - * So the law is the SMALLEST split whose `n_tiles * sk` reaches a target workgroup count, falling - * back to the largest legal split at small N because nothing smaller reaches it. kFlatTileTarget - * is that count; it is the same quantity `narrow_ksplit` targets in the fp8 kernel, where it is - * called kSplitTarget. - * - * N = 48 IS THE ONLY TRUNK CALLER (the GDN a|b projection, forty-eight times a step); N = 1280 and - * N = 256 are the DFlash2 drafter's. So at the trunk shape this law reduces to the largest legal - * split, and the shapes it actually moves are the ones the drafter PROPOSES. */ +/* Where N already supplies the parallelism, the largest legal split is wrong: it only adds + * reduction work. At K = 5120 the fastest split falls as N grows: largest legal at N = 48 (3 N + * tiles), 4 at N = 256 (16 tiles), 1 or 2 at N = 1280 (80 tiles). So with `n_tiles` (the shape's + * 16-row N tiles) this picks the smallest split whose `n_tiles * sk` reaches kFlatTileTarget + * workgroups. Without it, or when none reaches, it picks the largest legal split. kFlatTileTarget + * is the same quantity as kSplitTarget in the fp8 kernel's `narrow_ksplit`. */ enum { kFlatTileTarget = 128 }; -static inline int pick_sk_for(long long n_tiles, long long K, long long unit, int wv, int bound) { - static const int ladder[] = { 1, 2, 4, 5, 8, 10, 16, 20 }; /* ascending: the SMALLEST that fits */ - const int cap = (wv > 0) ? (bound / (wv * 32)) : 1; - int best = 0; +static inline int pick_sk(long long n_tiles, long long K, long long unit, int wv, int bound) { + /* The top entry is the largest split an untuned shape gets. 20 divides K = 5120 and is the + * fastest legal split there on the GDN a|b projection; 32 is left out on purpose (legal at + * K = 5120 but slower). `cap` keeps the block within its bound (wv = 2 cannot reach 20). */ + static const int ladder[] = { 1, 2, 4, 5, 8, 10, 16, 20 }; + const int cap = (wv > 0) ? (bound / (wv * 32)) : 1; /* threads/block <= this MB/NPW's bound */ + int best = 1; for (int s : ladder) { - if (s > cap) continue; - if (unit > 0 && (K % ((long long)s * unit))) continue; - best = s; /* legal; remember it in case none reaches */ - if (n_tiles * s >= (long long)kFlatTileTarget) return s; + if (s > cap || unit <= 0 || (K % ((long long)s * unit))) continue; + best = s; + if (n_tiles > 0 && n_tiles * s >= (long long)kFlatTileTarget) return s; } - return best > 0 ? best : 1; /* nothing reaches the target: the largest legal */ + return best; } /* Resolve the tuned point into (WV, SK, MB, NPW, NT) for a shape whose split unit is `unit`. */ struct Cfg { int wv, sk, mb, npw, nt; }; -/* `n_tiles` is how many 16-row N tiles the shape has, and it is what turns "the largest legal - * split" into "enough split to fill the machine". Zero keeps the largest legal split, which is - * right wherever the split is the only source of parallelism. See the note at pick_sk_for. */ +/* `n_tiles` is the shape's number of 16-row N tiles, for pick_sk. Zero keeps the largest legal + * split, right wherever the split is the only source of parallelism. */ static inline int cfg_for(const RadArgs* a, long long K, long long M, long long unit, BoundRule br, - Cfg* out, long long n_tiles = 0); - -static inline int cfg_for(const RadArgs* a, long long K, long long M, long long unit, BoundRule br, - Cfg* out, long long n_tiles) { + Cfg* out, long long n_tiles = 0) { R4dGemmCfg cv; r4d_cfg_gemm(a, &cv); const R4dGemmCfg* c = &cv; out->wv = c->wv > 0 ? c->wv : 1; - /* MB IS HOW MANY ROW TILES ONE BLOCK COVERS, and mb <= 0 means "all of them", the same way - * sk <= 0 means "the largest legal split". It matters far more than it looks: grid.y is - * ceil(ceil(M/16)/MB), and every block in a grid.y column reads THE WHOLE WEIGHT for its N - * tile. At these shapes the weight is the entire cost, so MB = 1 at M = 64 reads it four times - * -- on the DFlash2 drafter's fc, [5120, 25600] and 250 MiB, that is a gibibyte moved at peak - * bandwidth to compute a 64-row slice. Covering every row tile in one block is right whenever - * the weight is bigger than the activation, which is every caller here. */ + /* MB is the number of row tiles one block covers; mb <= 0 means all of them. grid.y is + * ceil(ceil(M/16)/MB) and each grid.y row of blocks reads the whole weight, so MB = 1 at M = 64 + * reads it four times. Covering every row tile is right when the weight outweighs the + * activation. */ out->mb = c->mb > 0 ? c->mb : (int)((M + 15) / 16); if (out->mb < 1) out->mb = 1; if (out->mb > 4) out->mb = 4; - /* ...AND IN THE DECODE BAND IT IS THE OPPOSITE RULE, because there the weight is not the cost: - * the GRID is. `grid.y` is ceil(ceil(M/16)/MB), so MB = ceil(M/16) makes it ONE -- and at the - * GDN a|b projection, N = 48, that is a THREE-BLOCK grid on a 32-WGP part for the whole kernel. - * MB = 1 makes it twelve at M = 64 and reads a 0.5 MiB weight four times, and those extra - * reads cost far less than the idle machine does. Across the decode band MB = 1 is the fastest - * choice at every (N, M) these callers run; MB = 2 edges it only at the widest N and the top of - * the band, by less than a second threshold would be worth. + /* In the decode band (M <= 64, four row tiles) the grid is the cost, not the weight: at + * N = 48, MB = ceil(M/16) gives a three-block grid on a 32-WGP part. MB = 1 is fastest at + * every decode (N, M) these callers run despite re-reading the weight. Prefill (hundreds of + * row tiles) is excluded by the bound. * - * FOUR ROW TILES IS THE BAND, and the bound is what makes it safe rather than a guess: a - * PREFILL chunk is hundreds of row tiles, where grid.y is already large and MB = 1 would read - * the weight a hundred and seventy times. `mtiles <= 4` is exactly M <= 64, which is exactly - * the decode band this kernel's callers run (C * (1 + n_spec) at n_spec 7 tops out at 64), and - * prefill is untouched by construction. - * - * BR_FLAT ONLY, and that is what leaves the output bits unchanged. `block_bound` ignores MB - * for BR_FLAT, so the split `pick_sk_for` answers below does not move -- and with the same - * split every output element is still one wave's accumulation over the same K slices in the - * same ascending order. MB moves which block owns the element, not what it adds. On a rule - * whose bound DOES read MB (BR_W2A8, BR_MBNPW) this would change the split and therefore the - * bits, which is why it is gated rather than applied to every auto. - * - * `R4D_GEMM_MB1=0` disables this branch and leaves MB on the shape-derived default. */ - static const bool mb1 = [] { const char* e = std::getenv("R4D_GEMM_MB1"); - return !(e && e[0] == '0'); }(); - if (mb1 && c->mb <= 0 && br == BR_FLAT && ((M + 15) / 16) <= 4) out->mb = 1; - /* ...AND PAST THE DECODE BAND WHEN N IS NARROW. Above 64 rows an N of 128 or more belongs to - * the tiled row (r4d_gemm_bf16_nt_tiled.hip), and what stays here is the narrow projections -- - * the GDN a|b at 48, a shared-expert gate at 1 -- whose weight is a few hundred KiB against an - * activation of megabytes, so the "weight is the cost" reading above is backwards for them. - * Measured at K = 2560 over M 80..2048 and N 16/48/112, MB = 1 is 2-5x faster than covering - * every row tile at every point (M 2048, N 48: 27.8 -> 14.9 us; N 16: 27.9 -> 8.8). The same - * BR_FLAT argument as above keeps the bits. */ + * BR_FLAT only: its bound ignores MB, so the split is unchanged and every output element keeps + * the same accumulation order, hence the same bits. Under BR_W2A8 or BR_MBNPW, MB would move + * the split. */ + if (c->mb <= 0 && br == BR_FLAT && ((M + 15) / 16) <= 4) out->mb = 1; + /* Also past the decode band when N is narrow. Above 64 rows, N >= 128 goes to the tiled row + * (r4d_gemm_bf16_nt_tiled.hip); what stays here are narrow projections (GDN a|b at 48, a + * shared-expert gate at 1) whose weight is small against the activation. At K = 2560, + * M 80..2048, N 16..112, MB = 1 is 2-5x faster. BR_FLAT keeps the bits as above. */ if (c->mb <= 0 && br == BR_FLAT && n_tiles > 0 && n_tiles < 8) out->mb = 1; out->npw = c->npw > 0 ? c->npw : 1; out->nt = c->nt; - /* W2A8 PAST ONE ROW TILE NEEDS A WIDER BLOCK, not a taller one, and the shape-derived default - * gives it a taller one. The DFlash2 draft head is the only w2a8 caller and it runs - * M = n_seq * steps, so M crosses 16 at the SECOND concurrent sequence: a single-stream bench - * never reaches this branch at all. + /* W2A8 past one row tile needs a wider block, not a taller one. Its only caller (the DFlash2 + * draft head, N = 124160, K = 5120) runs M = n_seq * steps, so M > 16 from the second + * concurrent sequence on. At NPW = 1 the kernel then drops to about a third of memory + * bandwidth; NPW = 4 gives each block four N tiles to hide the dequantise behind. MB is pinned + * at 2: MB = 4 with NPW = 4 spills (MT * NPW accumulators), and MB = 3 (12 accumulators vs 8) + * is slower even where it moves the same bytes. Reading the weight twice is cheaper than any + * shape that reads it once; see rad_block_dflash2.h for the vocabulary shard. * - * At one row tile the kernel runs at memory bandwidth on its 170.5 MiB weight, N = 124160 and - * K = 5120. Past one row tile, at NPW = 1, it falls to roughly a third of the bus even though - * the weight read has not changed -- MB covers every row tile in one block throughout -- so the - * collapse is entirely the block shape. Widening the block over N recovers most of it: NPW = 4 - * gives each block four N tiles to hide the dequantise behind, where NPW = 1 has only its own. - * MB is pinned at 2 rather than left to grow because MB = 4 with NPW = 4 spills -- accumulators - * are MT * NPW -- and reading the weight twice is cheaper than spilling, which is the same - * conclusion the kernel's own header reaches from its sweep. - * - * Only mb = 0 is touched: a tuned mb is the tuner's decision and must survive. */ - /* AND THE SPLIT IS PINNED WITH THEM, because `pick_sk` takes the LARGEST split the bound - * allows and the largest is not the fastest here. At K = 5120 the unit is 128, so the legal - * counts are the divisors of 40 up to bound/(wv*32) = 16, and pick_sk answers 10. Eight is - * uniformly faster than ten across the whole M band this branch covers. The one cost step - * inside that band is where grid.y grows and the weight is read again; it sits in the same - * place at either split count. - * - * MB = 4 WOULD REMOVE THE SECOND WEIGHT READ AND IS STILL WRONG: at NPW = 4 it spills, and - * below NPW = 4 the block is too narrow to hide the dequantise. Reading the weight twice - * really is cheaper than any block shape that reads it once, which is the same conclusion the - * kernel's own header reaches. The lever that IS left is a vocabulary shard -- see - * rad_block_dflash2.h. - * - * MB = 3 IS THE COUNT BETWEEN THEM AND IT IS ALSO WRONG, which is worth stating because the - * analogous hole at three in the fp8 GEMM's NT ladder is a real loss there (r4d_gemm_fp8a8.hip, - * "...AND THE TOKEN-TILE COUNT HAD A HOLE IN IT AT THREE"). At three row tiles -- M = 33..48 -- - * MB = 2 makes grid.y two and reads the whole weight twice while MB = 3 makes it one, and - * MB = 3 is still slower: MT * NPW accumulators is twelve against eight, which costs more than - * the read it saves. It is slower even at an M where grid.y and the bytes moved are identical - * between them, so the accumulator count is the whole of it. The second weight read past 32 - * rows stands. - * - * A pin that this K cannot divide, or that overruns the bound, falls back to pick_sk rather - * than becoming a refusal: this branch is the AUTO path and auto must serve every shape. */ + * The split is pinned to 8: pick_sk would answer 10 (divisors of 40 up to 16), and 8 is faster + * across this M band. Only mb = 0 is touched, so a tuned mb survives. A pin this K cannot + * divide or that overruns the bound falls back to pick_sk, since the auto path must serve + * every shape. */ int sk_pin = 0; if (br == BR_W2A8 && c->mb <= 0 && out->mb >= 2) { out->mb = 2; @@ -269,26 +159,18 @@ static inline int cfg_for(const RadArgs* a, long long K, long long M, long long if (sk_pin && (out->wv * sk_pin * 32 > bound || (unit > 0 && (K % ((long long)sk_pin * unit))))) sk_pin = 0; - out->sk = c->sk > 0 ? c->sk - : (sk_pin ? sk_pin - : (n_tiles > 0 ? pick_sk_for(n_tiles, K, unit, out->wv, bound) - : pick_sk(K, unit, out->wv, bound))); - /* A NAMED split that overruns the bound is a REFUSAL, not a device error. The tuner has to see - * "does not serve this shape" so it never records the candidate, and the selector must not be - * able to hand a cached name to a shape whose MB has since grown. */ + out->sk = c->sk > 0 ? c->sk : (sk_pin ? sk_pin : pick_sk(n_tiles, K, unit, out->wv, bound)); + /* A named split that overruns the bound is refused, so the tuner never records the candidate + * and the selector cannot hand a cached name to a shape whose MB has grown. */ if (out->wv * out->sk * 32 > bound) return R4D_NO(RAD_E_UNSUPPORTED); - /* A NAMED split count that this K cannot divide is a refusal, not a silent clamp: the tuner - * has to see that this candidate does not serve this shape, or it will record a measurement - * for a configuration that never ran. */ + /* A named split this K cannot divide is refused rather than clamped, so the tuner never + * records a configuration that did not run. */ if (unit > 0 && (K % ((long long)out->sk * unit))) return R4D_NO(RAD_E_SHAPE); - if (out->wv * out->sk * 32 > 1024) return R4D_NO(RAD_E_SHAPE); - /* R4D_GEMMCFG=1 prints each DISTINCT (tuned point, K, M, n_tiles) this resolved, once. The rule - * above is shape-dependent and the harness cannot see which branch it took. */ + /* R4D_GEMMCFG=1 prints each distinct (tuned point, K, M, n_tiles) resolution once. */ static const bool dbg = [] { const char* e = std::getenv("R4D_GEMMCFG"); return e && e[0] && e[0] != '0'; }(); if (dbg) { - /* Once per DISTINCT key, to at most 64 of them: the engine resolves this on every issue - * of every GEMM row and a line each would be the log. */ + /* At most 64 keys: this runs on every issue of every GEMM row. */ static uint64_t seen[64]; static int nseen = 0; const uint64_t key = ((uint64_t)(unsigned)(c->wv * 41 + c->sk * 7 + c->mb * 3 + c->npw) << 56) @@ -314,18 +196,17 @@ enum { G_A = 0, G_B, G_Y }; /* gemm_nt enum { Q_A = 0, Q_ASCALE, Q_B, Q_BSCALE, Q_Y, Q_ASUM, Q_BREF }; /* gemm_nt_q */ struct GemmOps { - /* A flattened view of `a`, when the caller declared it rank 3; see gemm_ops. Held by value - * because the operand array it was folded from belongs to the core. */ + /* Flattened views of a rank-3 `a` / `y`; see gemm_ops. Held by value because the operand + * array belongs to the core. */ RadTensor a_flat, y_flat; const RadTensor *a, *ascale, *b, *bscale, *y, *asum, *bref; long long M, N, K; }; -/* THE MXFP4 GEMMS' ACTIVATION SCALE GRID, read off the operand rather than assumed. One f32 a row - * (`[M]` or `[M][1]`: a per-token quantiser) is group 0; one per (row, 128 of K) (`[M][ceil(K/128)]`: - * the block-scaled fp8 family's quantisers, which every fused producer in arch/common writes) is - * group 128, read at the operand's own row stride. Anything else is refused by shape: a grid read - * at the wrong width is an answer that is merely wrong. */ +/* The MXFP4 GEMMs' activation scale grid, read off the operand. One f32 per row (`[M]` or + * `[M][1]`, a per-token quantiser) is group 0; one per (row, 128 of K) (`[M][ceil(K/128)]`, the + * block-scaled fp8 quantisers every fused producer in arch/common writes) is group 128, read at the + * operand's row stride. Anything else is refused. */ static inline int mx_ascale_grid(const GemmOps& g, int* group, int* rs, int parts = 1) { const RadTensor* s = g.ascale; if (!s || g.M <= 0) return R4D_NO(RAD_E_INVAL); @@ -340,28 +221,26 @@ static inline int mx_ascale_grid(const GemmOps& g, int* group, int* rs, int part rstride = cols; } const long long kb = (g.K + 127) / 128; - /* PARTS: the activation's copies sit side by side in a row, so its scale row is `parts` times - * as long; each part reads its own kb of them at the row stride. */ + /* With parts, the activation's copies sit side by side in a row, so its scale row is `parts` + * times as long; each part reads its own kb entries. */ if (parts == 1 && cols == 1 && (s->rank < 2 || rstride == 1)) { *group = 0; *rs = 1; return RAD_OK; } if (cols == kb * parts && rstride >= kb * parts) { *group = 128; *rs = (int)rstride; return RAD_OK; } return R4D_NO(RAD_E_SHAPE); } -/* THE PARTS OF A PARTITIONED MXFP4 WEIGHT (gemm_nt_q's `pb1`/`pb2`), as launches. +/* The parts of a partitioned MXFP4 weight (gemm_nt_q's `pb1`/`pb2`), as launches. * * A fused projection whose pieces were rotated apart (ParoQuant: gate|up, q|k|v) has one copy of - * the activation a piece, written side by side in a row of `a` -- [M, parts * K] -- and its scales - * the same, so the weight's rows [0, pb1), [pb1, pb2), [pb2, N) each meet THEIR copy. A part is - * then the ordinary product over a window of the planes: the activation from byte p * K of each row - * and its scales from p * ceil(K/128), the fragment-order weight from tile n0 / 16 (its bytes are - * n0 * K / 2 in), the exponents and reference from column n0, the output from column n0, the last - * three with the full planes' row pitch. So the kernels learn only row pitches (`lda`, `ldws`, - * `ldc`) and a part is one launch of the kernel the shape would have picked anyway. + * the activation per piece, side by side in a row of `a` ([M, parts * K]), and its scales likewise; + * weight rows [0, pb1), [pb1, pb2), [pb2, N) each meet their own copy. A part is the ordinary + * product over a window of the planes: activation from byte p * K of each row, scales from + * p * ceil(K/128), fragment-order weight from tile n0 / 16 (byte n0 * K / 2), exponents, reference + * and output from column n0 at the full planes' row pitch. The kernels learn only row pitches + * (`lda`, `ldws`, `ldc`), and each part is one launch of the kernel the shape would pick anyway. * * `pb1` = 0 is one part and `pb2` = 0 ends the second part at N, as libref reads them. Bounds are - * whole 16-row tiles (the weight's fragment unit). Returns the parts in `p`, K corrected to the - * op's own (gemm_ops read the row's width, which is parts * K), and the activation's row pitch in - * `lda`. */ + * whole 16-row tiles. Fills `p`, corrects K to the op's own (gemm_ops read parts * K) and sets the + * activation's row pitch in `lda`. */ struct MxParts { int n = 1; long long n0[3] = { 0, 0, 0 }, n1[3] = { 0, 0, 0 }; @@ -405,14 +284,28 @@ static inline int mx_parts(const RadArgs* a, GemmOps* g, MxParts* p) { return RAD_OK; } -/* Common shape and layout checks. A is [M,K] row-major, C is [M,N] row-major and the weight is - * an opaque packed blob whose element count the layout hook owns -- so the weight's SHAPE is not - * checked here beyond being present, which is deliberate: the byte count that matters is the one - * rad-convert wrote from RadLayout.bytes, and re-deriving it from N and K would be a second - * source for one number. */ -/* `parts`: the caller reads a partitioned weight's `pb1`/`pb2` (mx_parts). Any other row REFUSES them - * rather than ignore them -- a part bound it does not apply would multiply every row of the weight by - * the first copy of the activation. */ +/* Folds a contiguous rank-3+ operand to rank 2 (rows x the product of the rest), held by value in + * `flat` because the operand array is the core's; a rank-2 operand is left as it is. */ +static inline int fold_rows(const RadTensor** t, RadTensor* flat) { + if ((*t)->rank < 2) return R4D_NO(RAD_E_SHAPE); + if ((*t)->rank == 2) return RAD_OK; + if (!r4d_contig(*t)) return R4D_NO(RAD_E_STRIDE); + *flat = **t; + int64_t k = 1; + for (uint32_t d = 1; d < (*t)->rank; ++d) k *= (*t)->shape[d]; + flat->rank = 2; + flat->shape[1] = k; flat->stride[1] = 1; + flat->stride[0] = k; + *t = flat; + return RAD_OK; +} + +/* Common shape and layout checks. A is [M,K] row-major, C is [M,N] row-major. The weight is an + * opaque packed blob whose size the layout hook owns (RadLayout.bytes), so only its presence is + * checked here. + * + * `parts`: the caller applies a partitioned weight's `pb1`/`pb2` (mx_parts). Any other caller + * refuses them; ignoring them would multiply every weight row by the first activation copy. */ static inline int gemm_ops(const RadArgs* a, GemmOps* g, int quantised, int parts = 0) { std::memset(g, 0, sizeof(*g)); if (quantised && !parts && (r4d_geti_or(a, "pb1", 0) > 0 || r4d_geti_or(a, "pb2", 0) > 0)) @@ -432,46 +325,14 @@ static inline int gemm_ops(const RadArgs* a, GemmOps* g, int quantised, int part g->y = r4d_opt(a, G_Y); if (!g->a || !g->b || !g->y) return R4D_NO(RAD_E_INVAL); } - /* A CONTIGUOUS RANK-3 ACTIVATION IS A RANK-2 ACTIVATION, and refusing it would refuse a real - * model: the bf16 plugin's gated delta net writes its output into a [tokens, heads, - * head_v] buffer -- rank 3 because `gdn_chunk_scan` declares its `o` operand that way -- and - * hands the same bytes to `gemm_nt` for the out projection. libref computes that correctly, - * because it takes K from the op's K PARAMETER and reads A as M x K whatever the declared rank; - * this shim derived K from shape[1] instead, which is the HEAD COUNT, so it refused the rank - * rather than computing with 48 where K is 3072. The fp8 plugin never reached it only because - * its quantiser writes a separate rank-2 codes buffer. - * - * The fold is exact for a CONTIGUOUS tensor and gives the same M x K the parameter names. It is - * held by value here rather than written back through g->a: those tensors are the core's - * operand array, which every other kernel in the step also reads. - * - * A STRIDED rank-3 tensor is still refused, and must be: it is not a rank-2 one. */ - if (g->a->rank < 2) return R4D_NO(RAD_E_SHAPE); - if (g->a->rank > 2) { - if (!r4d_contig(g->a)) return R4D_NO(RAD_E_STRIDE); - g->a_flat = *g->a; - int64_t k = 1; - for (uint32_t d = 1; d < g->a->rank; ++d) k *= g->a->shape[d]; - g->a_flat.rank = 2; - g->a_flat.shape[1] = k; g->a_flat.stride[1] = 1; - g->a_flat.stride[0] = k; - g->a = &g->a_flat; - } - if (g->y->rank < 2) return R4D_NO(RAD_E_SHAPE); - /* ...AND THE SAME ON THE OUTPUT SIDE, for the same reason and from the same plugin. The gated - * attention writes its query-and-gate projection into a [tokens, heads, 2*head_dim] buffer -- - * rank 3 so that q and gate are ordinary column slices of the last dimension, which is what - * makes the interleaving addressable at all -- and N is the product of the trailing two. */ - if (g->y->rank > 2) { - if (!r4d_contig(g->y)) return R4D_NO(RAD_E_STRIDE); - g->y_flat = *g->y; - int64_t n = 1; - for (uint32_t d = 1; d < g->y->rank; ++d) n *= g->y->shape[d]; - g->y_flat.rank = 2; - g->y_flat.shape[1] = n; g->y_flat.stride[1] = 1; - g->y_flat.stride[0] = n; - g->y = &g->y_flat; - } + /* The gated delta net hands its [tokens, heads, head_v] output (as `gdn_chunk_scan` declares + * `o`) to `gemm_nt`, so K is the product of the trailing dims, not shape[1]. Gated attention + * writes q|gate into [tokens, heads, 2*head_dim], so q and gate are column slices of the last + * dim and N is the product of the trailing two. A strided rank-3 tensor is refused. */ + int rc = fold_rows(&g->a, &g->a_flat); + if (rc != RAD_OK) return rc; + rc = fold_rows(&g->y, &g->y_flat); + if (rc != RAD_OK) return rc; if (!r4d_contig(g->a) || !r4d_contig(g->y)) return R4D_NO(RAD_E_STRIDE); if (!r4d_aligned(g->a->data, 16) || !r4d_aligned(g->b->data, 16)) return R4D_NO(RAD_E_ALIGN); @@ -485,20 +346,18 @@ static inline int gemm_ops(const RadArgs* a, GemmOps* g, int quantised, int part -/* The asymmetric grid is a different WEIGHT FORMAT, not a different call: the nibble is read - * UNSIGNED and the stored per-group zero is corrected out with the activation's per-group row - * sums. So it is selected by `dtype`, which is what the weight file was written for, and never by - * whether a_sum happens to be present -- guessing from an operand would make a caller that forgot - * to pass the sums silently compute the symmetric answer against asymmetric bytes. */ +/* The asymmetric grid is a different weight format: the nibble is read unsigned and the per-group + * zero is corrected with the activation's per-group row sums. It is selected by `dtype`, never by + * whether a_sum is present: inferring it would silently give the symmetric answer to a caller + * that forgot the sums. */ static inline int is_asym(const RadArgs* a) { const char* dt = r4d_gets(a, "dtype"); return dt && std::strstr(dt, "_asym") != nullptr; } -/* The tiled and prefill kernels take a single opaque tile VARIANT into libr4d's own tile switch. - * The block width BN is a property of the variant, and N must be a multiple of it -- which the ROW - * cannot express, because BN varies by variant. So the row constrains N % 256 (the default - * variant's BN) and this is where a variant whose BN does not divide N is refused. */ +/* The tiled and prefill kernels take an opaque tile variant into libr4d's tile switch. N must be a + * multiple of the variant's BN, which the row cannot express since BN varies; the row constrains + * N % 256 (the default BN) and this refuses a variant whose BN does not divide N. */ static inline int tile_ok(const R4dTileCfg* t, long long N) { if (!t) return R4D_NO(RAD_E_INVAL); if (t->bn > 0 && (N % t->bn)) return R4D_NO(RAD_E_SHAPE); diff --git a/libr4d/r4d_gemm_bf16_nt_m16.hip b/libr4d/r4d_gemm_bf16_nt_m16.hip index 6ab68fbb..7cc34b35 100644 --- a/libr4d/r4d_gemm_bf16_nt_m16.hip +++ b/libr4d/r4d_gemm_bf16_nt_m16.hip @@ -1,18 +1,11 @@ -// r4d_gemm_bf16_nt_m16.hip -- THE ROW THAT FORWARDS. There is no kernel in this file. +// r4d_gemm_bf16_nt_m16.hip -- forwarding entry, no kernel. // -// This row owns the M <= 16 band -- the MoE router gate's band -- and serves it with the WMMA -// kernel behind the M <= 64 row, which is faster than a scalar split-K kernel at every point of it. +// This row owns the M <= 16 band (the MoE router gate) and serves it with the M <= 64 WMMA kernel, +// which is faster than a scalar split-K kernel across the band. The result is not bit-identical to +// a scalar kernel: the reduction tree differs, which moves emitted text at N = 48 (GDN a|b +// projection). A reduction order is not a quality bar, so that is accepted. // -// THE FORWARD IS NOT BIT-NEUTRAL against a scalar kernel of the same band. Both formulations are -// deterministic fp32 reductions over the same split, but they are different reduction TREES, so the -// last bit differs. At N = 1280 and N = 256, which are the DFlash2 drafter's shapes, a bit change -// is not a text change; at N = 48, the trunk's GDN a|b projection and 48 calls a step, the emitted -// text does move where M <= 16. A reduction order is not a quality bar, so that is accepted. -// -// THE ROW STAYS EVEN THOUGH THERE IS NO KERNEL. Deleting the registry row would leave the M <= 16 -// band to whatever else claims it, and a band that resolves to a kernel which cannot serve it is -// invisible until a request lands in it. One forwarding entry is cheap and the band stays -// explicitly owned. +// The row is kept so the band stays explicitly owned rather than falling to whatever else claims it. #include "r4d.h" #include "r4d_gemm_args.h" diff --git a/libr4d/r4d_gemm_bf16_nt_m64.hip b/libr4d/r4d_gemm_bf16_nt_m64.hip index eb08f8c6..e383d27d 100644 --- a/libr4d/r4d_gemm_bf16_nt_m64.hip +++ b/libr4d/r4d_gemm_bf16_nt_m64.hip @@ -1,33 +1,21 @@ // r4d_gemm_bf16_nt_m64.hip - r4d_gemm_bf16_nt_m64: skinny bf16 GEMM at any M, gfx1201. // -// THE NAME SAYS 64 AND THE KERNEL IS GENERAL IN M. MT row tiles live in a block and `grid.y` -// covers the rest -- `mt0 = blockIdx.y * MT`, fragment rows clamped to M-1, the store guarded by -// `m < M` -- so any M up to R4D_GEMM64_MAX_M is served. The 64 is the registry band this row is -// listed under, not a limit of the kernel; the M <= 16 row forwards here as well. -// // C[M,N] = A[M,K] @ W[N,K]^T, bf16 in and out, fp32 accumulate. // -// THE SCALAR ALTERNATIVE is a wave per output COLUMN holding M accumulators for it, so every -// 16-wide step of K costs one weight load and M activation loads. That ratio is the whole cost at -// these shapes: at M=16, N=48, K=5120 the activation is re-read sixteen times per weight element, -// 7.9 MB against a 480 KiB weight, so the kernel is bound by traffic it did not need to move. -// Above M=16 that form cannot run at all -- 64 accumulators per column leaves nothing to prefetch -// with. +// General in M up to R4D_GEMM64_MAX_M: MT row tiles per block, grid.y covers the rest. The 64 is +// the registry band, not a kernel limit; the M <= 16 row forwards here too. // -// WMMA fixes the ratio by construction. One wmma_f32_16x16x16 consumes a 16x16 activation fragment -// and a 16x16 weight fragment and produces a whole 16(M) x 16(N) tile, so a step of 16 K costs -// ceil(M/16) activation fragments and ONE weight fragment however large M is, and the accumulator -// for a tile is 8 VGPRs per lane instead of 16 scalars per output element. At M=64 that is four -// fragments and four wmma per weight fragment, against sixty-four loads before. +// A scalar kernel (one wave per output column, M accumulators) costs one weight load and M +// activation loads per 16 K, and cannot run above M=16. One wmma_f32_16x16x16 produces a whole +// 16x16 tile, so a 16-K step costs ceil(M/16) activation fragments and one weight fragment, with +// 8 VGPRs per lane of accumulator per tile. // -// Parallel decomposition: a block is WV column-tiles x SK k-splits -// waves, each wave owning one 16-wide N tile over one contiguous slice of K, and the k-splits are -// reduced through LDS in wave order so the result does not depend on how the waves are scheduled. -// N=48 (a TP=2 shard of the gated-delta-net b/a projection) is three tiles; three waves would leave -// the machine idle, so SK is what fills it. +// A block is WV column tiles x SK k-splits waves; each wave owns one 16-wide N tile over one +// contiguous K slice. Splits are reduced through LDS in wave order, so the result does not depend +// on scheduling. SK fills the machine when N is small (N=48 is three tiles). // -// Fragment rows are CLAMPED, not masked: a tile whose rows run past M or N re-reads the last valid -// row, computes a result nobody stores, and never touches memory it does not own. +// Fragment rows are clamped, not masked: rows past M or N re-read the last valid row and their +// results are never stored. #include "r4d.h" #include "r4d_gemm_args.h" #include "r4d_gdn_wmma.h" @@ -38,19 +26,15 @@ #define R4D_GEMM64_MAX_M 65536 #define WAVE32 32 -// A fragment from a base pointer plus a COMPILE-TIME k step. The header's fragGo takes a 32-bit -// element offset, which is correct but leaves LLVM re-deriving a 64-bit address per fragment per -// step -- a b64 shift and a carry-in add pair, three instructions each, twenty per step around four -// WMMA. Holding one pointer per fragment and stepping it with a constant turns those into the -// 13-bit immediate field of global_load_b64: a k step is 32 bytes, so eight of them fit. +// A fragment from a base pointer plus a compile-time k step. With fragGo's 32-bit element offset, +// LLVM re-derives a 64-bit address per fragment per step (a b64 shift and a carry-in add pair); a +// constant step instead folds into the 13-bit immediate of global_load_b64 (32 bytes per k step, +// so eight fit). // -// The pointer is explicitly in the global address space. Held as a plain `const uint2*` it is a -// GENERIC pointer once it lives in an array across loop iterations -- LLVM's address-space -// inference does not see through that -- and every load becomes flat_load_b64, which on gfx12 -// increments dscnt as well as loadcnt, so any later LDS wait also waits on HBM. -// The element type is a scalar rather than uint2: HIP's vector types are structs whose assignment -// operator does not accept an address-space-qualified source, and an 8-byte scalar carries the same -// alignment the paired load needs. +// The pointer is explicitly global: a plain pointer held in an array across iterations becomes +// generic, so loads become flat_load_b64, which on gfx12 also increments dscnt and makes later LDS +// waits wait on HBM. The element is a scalar because HIP's vector structs cannot be assigned from +// an address-space-qualified source. typedef __attribute__((address_space(1))) const unsigned long long* r4d_gu2; __device__ __forceinline__ v8bf fragU(r4d_gu2 p, int u) { @@ -60,13 +44,10 @@ __device__ __forceinline__ v8bf fragU(r4d_gu2 p, int u) { return x.f; } -// MT = row tiles per BLOCK, held as MT v8f accumulators (8 VGPRs each); grid.y covers the rest. -// More row tiles per block amortises the weight fragment over more WMMA, fewer of them put more -// blocks on the machine -- which one wins is a per-shape question, so MT is tunable, not assumed. -// KU is how many k steps the loop unrolls; see the loop for why it exists. -#ifndef KU -#define KU 8 -#endif +// MT = row tiles per block, held as MT v8f accumulators (8 VGPRs each); grid.y covers the rest. +// More amortises each weight fragment, fewer puts more blocks on the machine, so MT is tunable. +// KU is the k-step unroll; see the loop. +constexpr int KU = 8; template __global__ __launch_bounds__(1024) void r4d_gemm_bf16_nt_m64_kernel( const unsigned short* __restrict__ A, const unsigned short* __restrict__ W, @@ -83,20 +64,16 @@ __global__ __launch_bounds__(1024) void r4d_gemm_bf16_nt_m64_kernel( #pragma unroll for (int i = 0; i < MT; i++) acc[i] = (v8f)(0.f); - // Row offsets as 32-bit ELEMENT offsets: computing them as pointers instead makes the size_t row - // stride a 64-bit multiply-add and the row clamp exec-mask work, none of which LLVM keeps live - // across the loop. They are turned into pointers ONCE, below. + // Row offsets as 32-bit element offsets, turned into pointers once below; as pointers, LLVM + // would not keep the 64-bit stride math and the row clamp out of the loop. unsigned woff = rowGo((unsigned)K, n0, N - 1, lane) + (unsigned)kbase; unsigned aoff[MT]; #pragma unroll for (int i = 0; i < MT; i++) aoff[i] = rowGo((unsigned)K, (mt0 + i) * 16, M - 1, lane) + (unsigned)kbase; - // Unrolled so the k step is a load IMMEDIATE rather than an address update. Rolled, LLVM widens - // each offset to a 64-bit induction variable and rebuilds the address every step: a b64 shift and - // a carry-in add pair per fragment, twenty instructions per step around four WMMA. Unrolled, the - // sub-step offset is a constant that folds into the 13-bit field of global_load_b64, and the base - // offsets advance once per block of KU. + // Unrolled so the k step is a load immediate (the 13-bit field of global_load_b64) and the base + // pointers advance once per KU steps; rolled, LLVM rebuilds a 64-bit address every step. if (n0 < N) { r4d_gu2 pw = (r4d_gu2)(const unsigned long long*)(W + woff); r4d_gu2 pa[MT]; @@ -125,11 +102,8 @@ __global__ __launch_bounds__(1024) void r4d_gemm_bf16_nt_m64_kernel( } } - // Reduce one row tile at a time: SK partial tiles is WV*SK KiB of LDS whatever MT is, where - // holding all MT at once would be four times that at M=64. The sum is spread over every thread - // in the block rather than left to the k-split-0 waves, which at SK=8 is one output element per - // thread instead of sixty-four; the order over splits is fixed, so the result does not depend on - // how the waves were scheduled. + // Reduce one row tile at a time, so LDS is WV*SK KiB regardless of MT. Every thread in the block + // shares the sum (one element per thread at SK=8); the order over splits is fixed. const int slot = (col_local * SK + ksplit) * 256; const int nthreads = WV * SK * WAVE32; #pragma unroll @@ -145,15 +119,15 @@ __global__ __launch_bounds__(1024) void r4d_gemm_bf16_nt_m64_kernel( const int l = off & 31; const int n = (blockIdx.x * WV + col) * 16 + (l & 15); const int m = (mt0 + i) * 16 + 8 * (l >> 4) + (off >> 5); - // The language's own float-to-bf16 conversion, deliberately and not the header's f2bf, - // which rounds half away from zero. + // The language's float-to-bf16 conversion on purpose; the header's f2bf rounds half away + // from zero. if (n < N && m < M) C[(size_t)m * N + n] = (__hip_bfloat16)v; } } } -// grid = ceil(ceil(N/16)/WV) blocks; block = WV*SK waves. MT is compile-time so the accumulators -// and the fragment loop are exactly the size M needs. +// grid = ceil(ceil(N/16)/WV) x ceil(ceil(M/16)/MB) blocks; block = WV*SK waves. MT = MB is +// compile-time so the accumulators are sized exactly. void r4d_gemm_bf16_nt_m64(long a, long w, long c, int M, int K, int N, int WV, int SK, int MB, long stream) { if (M < 1 || M > R4D_GEMM64_MAX_M) throw std::runtime_error("r4d gemm_bf16_nt_m64: M out of range"); @@ -182,8 +156,7 @@ int r4d_gemm_bf16_nt_m64_max_m(void) { return R4D_GEMM64_MAX_M; } // ============================================================== the plugin ABI entry points // -// The operand reader and the split law are in r4d_gemm_args.h. See libr4d/r4d_args.h for why there -// is no adapter directory between the core and these launches. +// The operand reader and the split law are in r4d_gemm_args.h; see libr4d/r4d_args.h. extern "C" int r4d_rad_gemm_bf16_m64(const RadArgs* a, RadStream s) { GemmOps g; int rc = gemm_ops(a, &g, 0); diff --git a/libr4d/r4d_gemm_bf16_nt_tiled.hip b/libr4d/r4d_gemm_bf16_nt_tiled.hip index 7e06cab0..3e7b2076 100644 --- a/libr4d/r4d_gemm_bf16_nt_tiled.hip +++ b/libr4d/r4d_gemm_bf16_nt_tiled.hip @@ -3,30 +3,21 @@ // C[M,N] = A[M,K] @ W[N,K]^T, bf16 in and out, fp32 accumulate: gemm_bf16_nt_m64's arithmetic in a // block shape that reuses what it loads. // -// WHY THE SKINNY KERNEL IS THE WRONG SHAPE ABOVE 64 ROWS. It gives a wave one 16-wide N tile and -// reads every fragment straight from global memory, so each WMMA costs an activation fragment -// load, and every N tile re-reads the whole activation. That is the right trade at decode, where -// the weight is the cost; at a 2048-row prefill chunk the activation is the larger operand and it -// is read N/16 times. Measured at M = 2048, K = 2560: the MoE router (N 512) 224 us, ~24 TF/s, and -// the PLE key projection (N 10240) 3.5 ms, ~31 TF/s, at the kernel's untuned point -- and no point -// of its space reaches 50. +// The skinny kernel reads every fragment from global memory and re-reads the whole activation per +// N tile: right at decode, where the weight is the cost, but at a 2048-row prefill chunk the +// activation is read N/16 times and no configuration reaches 50 TF/s. // -// HERE a block of eight waves stages a BM x 64 activation tile and a BN x 64 weight tile through -// LDS, and each wave computes a (BM/2) x (BN/4) patch from them: every staged fragment feeds -// TM or TN WMMA instead of one. The next K tile is loaded into registers while the current one is -// computed, so the global latency sits behind four k steps of WMMA. +// Here a block of eight waves stages a BM x 64 activation tile and a BN x 64 weight tile through +// LDS, and each wave computes a (BM/2) x (BN/4) patch, so each staged fragment feeds TM or TN WMMA. +// The next K tile is loaded into registers while the current one is computed. // -// BYTE-IDENTICAL TO gemm_bf16_nt_m64, and that is a contract rather than a coincidence. That -// kernel splits K into SK slices, accumulates each slice from zero with one WMMA per 16 K in -// ascending order, and sums the slices in ascending order starting from 0.f. This one issues the -// same WMMA sequence for every output tile, with the same fragment layout, and at the end of each -// slice adds the slice into a running fp32 sum that started at 0.f -- the same additions in the -// same order. SK comes from the same automatic rule (cfg_for), so an op whose band moves from one -// row to the other changes no bit of its output. What differs is only where the operands sit -// between global memory and the matrix unit. +// Contract: byte-identical to gemm_bf16_nt_m64. Both accumulate each of SK slices from zero with +// one WMMA per 16 K in ascending order, using the same fragment layout, and sum the slices in +// ascending order from 0.f. SK comes from the same rule (cfg_for), so an op moving between the two +// rows changes no output bit. // -// Fragment rows are CLAMPED, as in the skinny kernel: a tile that runs past M or N re-reads the -// last valid row, computes a result nobody stores, and never touches memory it does not own. +// Fragment rows are clamped as in the skinny kernel: rows past M or N re-read the last valid row +// and their results are never stored. #include "r4d.h" #include "r4d_gemm_args.h" #include "r4d_common.h" @@ -35,10 +26,9 @@ #include #define BT_BK 64 // K per staged tile: four WMMA k steps -// THE LDS ROW PITCH, in elements: 144 bytes. A fragment read has sixteen lanes on sixteen rows at -// one k, each reading 8 bytes; at 36 dwords a row the sixteen land on distinct bank pairs, and the -// upper half-wave's +2 dwords lands between them. 144 is also a multiple of 16, so a staged -// 16-byte chunk is one aligned ds_store_b128. +// LDS row pitch in elements (144 bytes). A fragment read is sixteen lanes on sixteen rows, 8 bytes +// each; at 36 dwords per row they land on distinct bank pairs, and the upper half-wave's +2 dwords +// fall between them. 144 is a multiple of 16, so a staged chunk is one aligned ds_store_b128. #define BT_PITCH (BT_BK + 8) #define BT_WM 2 // waves over M #define BT_WN 4 // waves over N @@ -58,21 +48,19 @@ __global__ __launch_bounds__(256) void r4d_gemm_bf16_nt_tiled_kernel( const int tid = threadIdx.x, wave = tid >> 5, lane = tid & 31; const int wm = wave / BT_WN, wn = wave % BT_WN; - // THE GRID RUNS IN GROUPS OF 8 ACTIVATION BANDS, M fastest inside a group. Blocks are - // dispatched in flattened-id order, and the launch's x-fastest grid swept every weight band for - // each activation band, reading the whole weight once per 128 rows: free while it sits in the - // 64 MB MALL, and half the rate once it does not (N 12288 x K 4096, 96 MB, ran at 68 TFLOP/s - // where N 8192 ran at 118). A group keeps its bands' weight tiles shared by the blocks in - // flight and reads the weight once a group. Small grids take it too: with fewer bands than a - // group the order is plain M-fastest, which is what reads the weight once. + // Blocks are remapped into groups of 8 activation bands, M fastest within a group. Blocks + // dispatch in flattened-id order; x-fastest order would read the whole weight once per 128 rows, + // which halves the rate once the weight exceeds the 64 MB MALL. A group shares weight tiles among + // blocks in flight and reads the weight once per group; with fewer bands than a group the order + // is plain M-fastest. constexpr unsigned kGroupM = 8; const unsigned per = kGroupM * gridDim.x, lin = blockIdx.y * gridDim.x + blockIdx.x; const unsigned first = lin / per * kGroupM, r = lin % per; const unsigned gm = min(gridDim.y - first, kGroupM); const int m0 = (int)(first + r % gm) * BM, n0 = (int)(r / gm) * BN; - // Staging: chunk c = tid + 256 i is row c / CPR, elements (c % CPR) * 8 of it. Eight threads - // cover a row's 128 bytes, so a warp's loads are four whole lines. + // Staging: chunk c = tid + 256 i is row c / CPR, elements (c % CPR) * 8. Eight threads cover a + // row's 128 bytes, so a wave's loads are four whole lines. unsigned aoff[AL], woff[WL]; unsigned short* adst[AL]; unsigned short* wdst[WL]; @@ -140,10 +128,9 @@ __global__ __launch_bounds__(256) void r4d_gemm_bf16_nt_tiled_kernel( for (int i = 0; i < TM; ++i) #pragma unroll for (int j = 0; j < TN; ++j) acc[i][j] = mma(af[i], bf[j], acc[i][j]); - /* A K STEP'S FRAGMENT READS, THEN ITS PRODUCTS, as the scheduler's groups. Left to itself, - * gfx12's compiler spreads each step's LDS reads among the previous step's WMMAs and waits on - * them early; grouped, the 128 x 128 tile measured 6 to 9% faster than LLVM 22's schedule at - * Flash-Next's shapes (M 384 to 2048, K 2560, N 2560 and 10240). */ + /* Schedule each k step's fragment reads, then its products. Otherwise the compiler spreads + * LDS reads among the previous step's WMMAs and waits on them early; grouping is 6-9% faster + * on the 128 x 128 tile at M 384..2048, K 2560. */ __builtin_amdgcn_sched_group_barrier(0x100, TM + TN, 0); /* DS reads */ __builtin_amdgcn_sched_group_barrier(0x008, TM * TN, 0); /* WMMA */ if constexpr (SPLIT) { @@ -179,13 +166,10 @@ __global__ __launch_bounds__(256) void r4d_gemm_bf16_nt_tiled_kernel( } } -// THE TWO TILES, and the rule between them. A block walks the whole of K alone, so its time is a -// floor -- ~40 us at K = 2560 -- and a grid too small to fill the part pays it with idle CUs: -// at M = 200, N = 512 the 128 x 128 tile is an eight-block grid. Measured at K = 2560 (us, 128 x -// 128 / 64 x 64): M 2048 N 512 66 / 114, N 2560 341 / 644, N 10240 1627 / 2661; M 500 N 512 41 / 31, -// N 2560 92 / 163; M 200 N 512 39 / 26, N 2560 66 / 72; M 80 N 2560 50 / 45. The large tile wins -// once its grid is 32 blocks, half the part's CUs, and loses by less than the small one does -// below that. (64 x 128 and 128 x 64 gain no more than a few percent over these.) +// Tile choice. A block walks all of K alone, so its time is a floor (~40 us at K = 2560), and a +// grid too small to fill the part leaves CUs idle (M = 200, N = 512 is eight 128 x 128 blocks). +// At K = 2560 the 128 x 128 tile wins once its grid reaches 32 blocks (half the CUs) and loses by +// less than the 64 x 64 tile does below that. 64 x 128 and 128 x 64 gain only a few percent. enum { kBtLargeGrid = 32 }; int r4d_gemm_bf16_nt_tiled_arm(int M, int N) { @@ -221,8 +205,7 @@ extern "C" int r4d_rad_gemm_bf16_tiled(const RadArgs* a, RadStream s) { GemmOps g; int rc = gemm_ops(a, &g, 0); if (rc != RAD_OK) return rc; - // THE SPLIT IS THE SKINNY ROW'S, resolved by the same rule from the same arguments, which is - // what keeps the two rows' outputs identical. + // The skinny row's split rule with the same arguments keeps the two rows' outputs identical. Cfg c; rc = cfg_for(a, g.K, g.M, 16, BR_FLAT, &c, (g.N + 15) / 16); if (rc != RAD_OK) return rc; diff --git a/libr4d/r4d_gemm_fp8a16_nt_m1.hip b/libr4d/r4d_gemm_fp8a16_nt_m1.hip index af3d4cd5..c7a7ef27 100644 --- a/libr4d/r4d_gemm_fp8a16_nt_m1.hip +++ b/libr4d/r4d_gemm_fp8a16_nt_m1.hip @@ -1,57 +1,29 @@ -// BLOCK-SCALED FP8 weight, bf16 activation, ONE row. The decode form of the checkpoint's own dense -// format: `.weight` as F8_E4M3 [N][K] with `.weight_scale_inv` in BF16 on a -// [ceil(N/128)][ceil(K/128)] grid. +// Block-scaled FP8 weight, bf16 activation, few rows: the decode form of the checkpoint's dense +// format, `.weight` as F8_E4M3 [N][K] with `.weight_scale_inv` in BF16 on a +// [ceil(N/128)][ceil(K/128)] grid. Also the fp8 lm_head (logits_gemm), whose scales sit in each +// row's tail (r4d_fp8_lm.h). // -// WHY IT IS NOT r4d_gemm_fp8a8_nt_m16 WITH M = 1. That kernel's narrowest token tile is sixteen -// wide, so at one row it issues sixteen times the matrix work for the same weight bytes -- both are -// weight-bandwidth-bound, so that alone is survivable -- but it also needs the activation quantised -// to E4M3 first, which is a whole launch and a round trip through VRAM for one 5120-float vector. -// This reads the bf16 activation directly. The difference at decode is the launch, and decode is -// where launches are the budget. +// Unlike r4d_gemm_fp8a8_nt_m16 at M = 1, this reads the bf16 activation directly: no E4M3 +// quantiser launch in front of the linear, and no 16-row tile of wasted matrix work. // -// It is also the ONLY member of this family that does not need r4d_quant_act_fp8, which makes it -// the path for a caller with no fp8 quantiser in front of the linear. +// The scale is bf16 per 128x128 tile (r4d_fp8_wmma.h); the activation and C are bf16 (logits: f32). // -// Three properties of the dot loops: -// -// 1. THE SCALE DTYPE is bf16, one per 128x128 tile: one shift and one bitcast to decode. See -// r4d_fp8_wmma.h. -// 2. THE ACTIVATION IS bf16, not f32, as every activation in this library is, and the accessor is -// where that lives rather than a second copy of the dot. It also halves the activation read, -// which matters at RB > 1 where sixteen of them are held in registers per pass. -// 3. bf16 C, not f32, for the same reason every other GEMM here writes bf16. -// -// `rb`, the rows a wave, is a tuning argument and not a shape: blocking trades waves for -// memory-level parallelism, so where it lands depends on whether the kernel is waiting on loads or -// on the ALU -- a property of the shape AND of the inner loop, which means a value fitted against -// one inner loop does not carry to another. 0 takes the default rule (rb_default) so an untuned -// caller is fast rather than broken; 1, 2, 4 and 8 pin it. +// `rb` (rows per wave) is a tuning argument: blocking trades waves for memory-level parallelism, +// and the best value depends on the shape and the inner loop. 0 takes rb_default; 1, 2, 4 and 8 +// pin it. // // Returns a negative code rather than throwing, for the reason given in r4d_gemm_fp8a8.hip. // -// ---- THE MT LOOP IS ISSUE-BOUND AND v_dot2_f32_bf16 DOES NOT FIX IT (gfx1201) ------------------- +// ---- the multi-row loop is issue-bound (gfx1201) ----------------------------------------------- // -// At MT = 8 this kernel reaches well under the rate M = 1 does on identical weight traffic, and the -// ISA says why: 394 instructions per 16 weight bytes a lane, ~136 of them FMA and ~89 doing nothing -// but widening bf16 activations to f32, because v_fma_f32 cannot read a bf16. At this part's -// 307 G wave-instructions/s that instruction count alone accounts for the whole of the rate. +// At MT = 8 the loop is ~394 instructions per 16 weight bytes per lane, ~89 of them widening bf16 +// activations to f32 (v_fma_f32 cannot read bf16); the instruction count accounts for the rate. +// v_pk_fma_f32 does not exist on RDNA4. v_dot2_f32_bf16 does, and E4M3 -> bf16 is exact, but a loop +// around it (215 instructions) is ~30% slower: dot instructions run at a fraction of v_fmac_f32's +// rate on this part. The instruction count is not the cost. // -// TWO WAYS OUT, AND NEITHER IS AVAILABLE ON THIS PART: -// -// v_pk_fma_f32 does not exist on RDNA4. __builtin_elementwise_fma on a float2 lowers to two -// scalar FMAs. It would be bit-preserving and free; it is simply not in the ISA. -// -// v_dot2_f32_bf16 IS in the ISA and IS SLOWER. E4M3 -> bf16 is exact (three mantissa bits into -// seven), so a bf16-pair dot multiplies exactly the same numbers, and a loop written around it is -// 215 instructions instead of 394 -- 64 v_dot2 and not one activation-widening op -- with register -// pressure down from 57 VGPRs to 47. It is still about 30% slower: the DOT instructions on this -// consumer part run at a fraction of v_fmac_f32's rate, so the scalar form is the right one here -// however it reads. Do not re-derive this from the instruction count; the count is not the cost. -// -// THE WMMA PATH IS BELOW: lm_wmma_kernel decodes E4M3 to bf16 fragments on the fly and stages two -// scale blocks a round. It holds close to the card's stream rate from M = 1 to M = 16 where this -// loop has already fallen well below it, so `r4d_logits_gemm_fp8` sends everything past M = 2 -// there. This matvec keeps M <= 2. +// lm_wmma_kernel below decodes E4M3 to bf16 fragments for the bf16 WMMA and holds close to stream +// rate from M = 1 to 16, so r4d_logits_gemm_fp8 uses it above M = 2. #include "r4d.h" #include "r4d_fp8_args.h" @@ -59,39 +31,23 @@ #include "r4d_fp8_lm.h" #include "r4d_fp8_wmma.h" -#include #include -/* Local to this file, like r4d_gemm_fp8a8.hip's env_u32: a pin read once, with the rule below - * deciding whenever it is unset, which is what a serve runs. */ -static uint32_t env_u32_lm(const char* k) { - const char* v = std::getenv(k); - return v ? (uint32_t)std::strtoul(v, nullptr, 10) : 0u; -} - -/* ROWS A WAVE; see rows_dot_mt for what RB is buying. The activation traffic is what MT costs and - * RB divides it, but RB * MT is also the accumulator count, so the two pull opposite ways and the - * best RB rises with MT and then falls back again: +/* Rows per wave for the multi-row matvec (see rows_dot_mt). RB divides the activation traffic but + * RB * MT is the accumulator count: * - * - at MT <= 2 the activation is already amortised over the whole weight, so blocking only - * shortens the grid and RB = 1 wins; - * - through the middle of the band the activation re-read dominates and RB = 2 then RB = 4 win; - * - at MT = 32 RB = 4 is 128 accumulators a lane and falls off a cliff, so RB drops back to 2. - * - * R4D_LM_RB pins it. */ + * - MT <= 2: the activation is already amortised, so RB = 1; + * - middle of the band: the activation re-read dominates, RB = 2 then 4; + * - MT = 32: RB = 4 would be 128 accumulators per lane, so RB = 2. */ static uint32_t mvm_rb(int mt) { - const uint32_t pin = env_u32_lm("R4D_LM_RB"); - if (pin == 1 || pin == 2 || pin == 4) return pin; if (mt <= 2) return 1u; if (mt <= 8) return 2u; if (mt <= 16) return 4u; return 2u; } -/* HOW MUCH K ONE STAGING ROUND COVERS, by MT = ceil(M / 16); see lm_wmma_kernel for the argument. - * Two scale blocks a round hide most of the cost of the stored row's 16-byte-only alignment, a - * large win at MT = 1 and a smaller one at MT = 2; from MT = 3 the wider tile costs more LDS than - * the straddle costs traffic and one block wins again. */ +/* Scale blocks per staging round, by MT = ceil(M / 16) (see lm_wmma_kernel): two at MT <= 2, one + * from MT = 3, where the wider tile's LDS costs more than the row straddle. */ static uint32_t lm_fkb_rule(uint32_t mt) { return mt <= 2u ? 2u : 1u; } namespace { @@ -102,19 +58,12 @@ constexpr int kWave = 32; constexpr int kDenseWaves = 8; constexpr int kDenseThreads = kDenseWaves * kWave; constexpr uint32_t kBlock = 128; // the scale block; see r4d_gemm_fp8a8.hip -// The widest token count the multi-row form serves. It is a REGISTER budget, not a shape: a lane -// holds MT accumulators and the decoded weight window, so past this the kernel spills and the -// 16-wide fp8a8 tile is the better answer anyway. 8 covers n_spec up to 7. +// The widest token count r4d_gemm_fp8a16_nt_mt serves: a register budget (MT accumulators plus the +// decoded weight window). 8 covers n_spec up to 7. constexpr uint32_t kMaxMt = 8; -__device__ __forceinline__ float wave_add(float v) { - v = r4d_wave_sum(v); - return v; -} - // The activation, seen as f32 by the dot. `XV` is anything with `operator[](uint32_t) -> float`, -// which lets an RMS norm fold into the same loop without a second copy of it -- an -// `r4d_rmsnorm_fp8a16_nt_m1` would be exactly that. +// so a fused input transform (e.g. an RMS norm) could reuse the same loop. struct Bf16V { const uint16_t* __restrict__ x; __device__ __forceinline__ float operator[](uint32_t i) const { @@ -124,12 +73,9 @@ struct Bf16V { // One output row, reduced across the wave. // -// 32 lanes x uint4 = 512 contiguous bytes a pass, fully coalesced. That width also fixes the -// reduction: a 512 B pass spans four scale tiles and 128/16 = 8, so lanes 0-7 land entirely inside -// the first tile, 8-15 the second, and so on. Every lane's 16 columns therefore share one scale, so -// a lane applies its own scale locally and the row needs a SINGLE wave reduction at the end rather -// than one per tile. Summation order changes -- per-lane then across, rather than across then -// per-tile -- but the value does not. +// 32 lanes x uint4 = 512 contiguous bytes per pass, four scale tiles: lanes 0-7 fall in the first +// tile, 8-15 the second, and so on. A lane's 16 columns share one scale, so each lane applies its +// own and the row needs a single wave reduction at the end. template __device__ __forceinline__ float row_dot(const uint8_t* __restrict__ W, const uint16_t* __restrict__ S, const XV& xv, @@ -148,9 +94,7 @@ __device__ __forceinline__ float row_dot(const uint8_t* __restrict__ W, for (int k = 0; k < 4; ++k) { const uint32_t p = pw[k]; const uint32_t c4 = c + (uint32_t)k * 4u; - // Two instructions for four bytes: v_cvt_pk_f32_fp8. No precondition: these are - // arbitrary model weights and can be subnormal, which the HARDWARE handles correctly - // where a software fast path does not. + // Two v_cvt_pk_f32_fp8 for four bytes; handles subnormal weights (see e4m3()). const v2f e01 = e4m3_pk(p); const v2f e23 = e4m3_pk(p); a0 = fmaf(e01.x, xv[c4 + 0], a0); @@ -163,18 +107,13 @@ __device__ __forceinline__ float row_dot(const uint8_t* __restrict__ W, // Tail, when K is not a multiple of 512. Same per-lane-scale rule, one column at a time. for (uint32_t c = full + (uint32_t)lane; c < cols; c += kWave) acc = fmaf(e4m3(w[c]) * xv[c], bscale(srow[c / kBlock]), acc); - return wave_add(acc); + return r4d_wave_sum(acc); } -// The same dot, RB rows at a time, so one activation load feeds RB weight loads. The one-row form -// spends six memory instructions per 16 weight bytes and only ONE of them is the weight, which sits -// alone on the critical path; a narrow matrix runs too few inner iterations to hide that latency. -// -// RB consecutive rows share the activation window AND the scale row -- `r0` is RB-aligned and RB -// divides 128, so `row / 128` cannot change inside the block. What multiplies is the weight load, -// which is the point: RB of them issue back to back and are in flight together. -// -// Summation order is untouched: each row still accumulates per lane and reduces once at the end. +// The same dot, RB rows at a time: one activation load feeds RB weight loads, which issue back to +// back. The one-row form has only one weight load per six memory instructions on the critical +// path, and a narrow matrix has too few iterations to hide it. `r0` is RB-aligned and RB divides +// 128, so the rows share a scale row. Summation order per row is unchanged. template __device__ __forceinline__ void rows_dot(const uint8_t* __restrict__ W, const uint16_t* __restrict__ S, const XV& xv, @@ -183,9 +122,7 @@ __device__ __forceinline__ void rows_dot(const uint8_t* __restrict__ W, const uint32_t stride = kWave * 16u; const uint32_t full = (cols / stride) * stride; const uint8_t* w[RB]; - // Rows past `N` re-read row0 rather than branching: the result is discarded by the caller, and a - // guarded load inside the inner loop would cost more than the duplicate traffic on the one - // ragged wave of the grid. + // Rows past `N` re-read row0 rather than branch; the caller discards them. #pragma unroll for (uint32_t r = 0; r < RB; ++r) w[r] = W + (size_t)(row0 + (r < nr ? r : 0)) * w_ld; const uint16_t* srow = S + (size_t)(row0 / kBlock) * sc_cols; @@ -224,53 +161,11 @@ __device__ __forceinline__ void rows_dot(const uint8_t* __restrict__ W, for (uint32_t r = 0; r < RB; ++r) acc[r] = fmaf(e4m3(w[r][c]) * xc, sc, acc[r]); } #pragma unroll - for (uint32_t r = 0; r < RB; ++r) acc[r] = wave_add(acc[r]); + for (uint32_t r = 0; r < RB; ++r) acc[r] = r4d_wave_sum(acc[r]); } -// MT TOKEN ROWS AGAINST ONE WEIGHT ROW, which is what a speculative verify step is. -// -// A verify step runs at M = 1 + n_spec, and without this form one row past M = 1 sends every linear -// in the model to r4d_gemm_fp8a8_nt_m16, which is slower on the identical 24.9 GB of weights -- so -// turning speculation on would cost milliseconds a step before a single draft was proposed. -// -// The weight is read ONCE for all MT rows and that is the entire point: this loop is bound by the -// weight stream, six memory instructions per 16 weight bytes with only one of them the weight, and -// MT activation rows amortise it MT ways without reading another weight byte. -// -// The activations are a few KB, so they stay in L1 -- but they are read once per OUTPUT ROW, and -// past MT = 4 that L1 traffic is the kernel. rows_dot_mt below is the answer. -// -// TWO THINGS ARE DELIBERATE HERE: -// -// - the E4M3 decode is hoisted out of the token loop. It is a property of the weight, and doing it -// per token would multiply the only non-FMA work in the loop by MT -- four times the -// v_cvt_pk_f32_fp8 count at MT = 4, for no extra arithmetic. -// - the a0/a1 split keeps row_dot's summation order EXACTLY: even columns into a0, odd into a1, -// per lane, one wave reduction at the end. So MT = 1 here is bit-identical to row_dot, and a -// deployment that turns speculation on does not change the trunk's arithmetic. - -// RB ROWS A WAVE, because the ACTIVATION is what makes MT expensive and not the weight. -// -// row_dot_mt above gives one output row to one wave, so every wave reads the whole of X for its -// own row: the weight stream is read once and X is read `rows` times. That is free at MT = 1 and -// it is the whole cost at MT = 32, where the rate over the stored weight has fallen to a fifth of -// what it is at M = 1. -// -// The weight is the same bytes at every M, so a rate that falls with M is not a memory-bound -// kernel -- and it is not registers either: no instantiation spills and every one reaches 16 -// waves/SIMD. It is L1. Per 16 weight bytes a lane reads MT x 32 bytes of X, so on this model's -// lm_head (124160 x 5120) at MT = 32 the kernel pulls 40 GB through L1 to stream 0.65 GB from HBM, -// and that L1 traffic cannot hide under the weight stream. -// -// Giving a wave RB CONSECUTIVE rows divides the X traffic by RB: one load of X[m][c..c+15] now -// feeds RB rows instead of one. The weight is untouched -- RB rows means RB weight chunks, which -// is the same bytes in the same order. -// -// IT IS BIT-IDENTICAL. Each row keeps its own a0/a1 split, its own lane sum and its own -// wave_add, in the same order row_dot_mt used; RB only changes which wave owns a row and when the -// activation is fetched. RB = 1 compiles to the same arithmetic as before. -// THE INT8 HEAD'S CODES (logits_gemm_i8): a signed byte per weight, exact in f32 and in bf16, where -// the E4M3 head's are decoded by v_cvt_pk_f32_fp8. One form for both, picked at compile time. +// The int8 head's codes (logits_gemm_i8): a signed byte per weight, exact in f32 and bf16, where +// the E4M3 head's are decoded by v_cvt_pk_f32_fp8. template __device__ __forceinline__ v2f code_pk(uint32_t p) { if constexpr (I8) { @@ -288,6 +183,15 @@ __device__ __forceinline__ float code1(uint8_t b) { else return e4m3(b); } +// MT token rows against RB weight rows per wave: a speculative verify step (M = 1 + n_spec) reads +// the weight once for all MT rows instead of falling to r4d_gemm_fp8a8_nt_m16. +// +// Each wave reads all of X for its rows, so past MT = 4 the L1 traffic of X (MT x 32 bytes per 16 +// weight bytes) is the cost, not HBM or registers. RB consecutive rows per wave divide it by RB. +// +// The E4M3 decode is hoisted out of the token loop. The a0/a1 split (even columns, odd columns, per +// lane, one wave reduction) keeps row_dot's summation order, so MT = 1 is bit-identical to row_dot +// and RB changes only which wave owns a row. template __device__ __forceinline__ void rows_dot_mt(const uint8_t* __restrict__ W, const uint16_t* __restrict__ S, @@ -297,11 +201,9 @@ __device__ __forceinline__ void rows_dot_mt(const uint8_t* __restrict__ W, int lane, float* __restrict__ acc) { const uint32_t stride = kWave * 16u; const uint32_t full = (cols / stride) * stride; - // THE ACTIVATION ROW A TOKEN SLOT READS. Instantiations above kMaxMt are launched only with M - // rounded up to a multiple of four, and X holds `m_real` rows, not MT: a padded slot reads the - // last real row again -- a duplicate read of live memory, like the clamped weight rows below -- - // and the epilogue drops its outputs. At or below kMaxMt every instantiation is exact, the - // test folds away and the loop is unchanged. + // The activation row a token slot reads. Above kMaxMt, M is rounded up to a multiple of four and + // X holds only `m_real` rows: a padded slot re-reads the last real row and its outputs are + // dropped. At or below kMaxMt the test folds away. auto xrow = [m_real](uint32_t m) -> uint32_t { return (MT > kMaxMt && m >= m_real) ? m_real - 1u : m; }; @@ -309,9 +211,8 @@ __device__ __forceinline__ void rows_dot_mt(const uint8_t* __restrict__ W, const uint16_t* srow[RB]; #pragma unroll for (uint32_t r = 0; r < RB; ++r) { - // CLAMPED, not skipped. A tail wave whose block runs past the last row computes the last - // row again and the store below drops it -- a duplicate read of live memory, where a - // branch would cost the whole loop its uniformity. + // Clamped, not skipped: a tail wave recomputes the last row and the store drops it, keeping + // the loop uniform. const uint32_t rr = (row0 + r < rows) ? (row0 + r) : (rows - 1); w[r] = W + (size_t)rr * w_ld; srow[r] = SROW ? (const uint16_t*)(w[r] + cols) : S + (size_t)(rr / kBlock) * sc_cols; @@ -319,13 +220,11 @@ __device__ __forceinline__ void rows_dot_mt(const uint8_t* __restrict__ W, #pragma unroll for (uint32_t i = 0; i < RB * MT; ++i) acc[i] = 0.0f; - /* AT MT <= 2 EACH PASS'S WEIGHT CHUNK, SCALE AND ACTIVATION ARE LOADED ONE PASS AHEAD (kPre), - * so a pass's loads run under the previous pass's arithmetic. Loaded in the pass that uses - * them, LLVM 24 issues them and then waits for the first three before it converts anything, - * and at M = 2 the head ran 0.65% behind LLVM 22's build; loaded ahead it is level, and M = 1 - * is unchanged. Held a pass, the activation is eight registers a row, which the wider tiles do - * not have: at MT = 32 it spills a thousand slots, so they load in the pass. The last pass - * reloads its own chunk rather than reading past the row. */ + /* At MT <= 2 (kPre) each pass's weight chunk, scale and activation are loaded one pass ahead, + * so the loads run under the previous pass's arithmetic; otherwise the compiler waits on them + * before converting anything. Wider tiles cannot hold the activation a pass (MT = 32 would + * spill), so they load in the pass. The last pass reloads its own chunk rather than reading + * past the row. */ constexpr bool kPre = MT <= 2u; [[maybe_unused]] uint4 wn[RB]; [[maybe_unused]] uint32_t sn[RB]; @@ -380,10 +279,8 @@ __device__ __forceinline__ void rows_dot_mt(const uint8_t* __restrict__ W, } #pragma unroll for (uint32_t m = 0; m < MT; ++m) { - /* THE SIXTEEN bf16 AS EIGHT DWORDS, each widened by a shift (the even element) and a - * mask (the odd one): the same floats. Read a uint16_t at a time, LLVM 24 moves each - * into a 16-bit register half before shifting it -- two instructions an element where - * LLVM 22 took one. */ + /* The sixteen bf16 as eight dwords, widened by a shift (even element) and a mask (odd). + * Read a uint16_t at a time, the compiler spends two instructions per element. */ uint4 x0, x1; if constexpr (kPre) { x0 = xc[m][0]; @@ -424,12 +321,11 @@ __device__ __forceinline__ void rows_dot_mt(const uint8_t* __restrict__ W, } } #pragma unroll - for (uint32_t i = 0; i < RB * MT; ++i) acc[i] = wave_add(acc[i]); + for (uint32_t i = 0; i < RB * MT; ++i) acc[i] = r4d_wave_sum(acc[i]); } -// bf16 for a GEMM output, f32 for a LOGITS one. The engine declares its logits buffer f32 -// because a bf16 logit has eight bits of mantissa and a nucleus cut compares neighbours; -// r4d_model.cpp explains at length why writing bf16 into it is wrong. +// bf16 for a GEMM output, f32 for logits (a bf16 logit's 8-bit mantissa is too coarse for a +// nucleus cut; see r4d_model.cpp). template __device__ __forceinline__ OT mvm_store(float v); template <> __device__ __forceinline__ uint16_t mvm_store(float v) { return f32_to_bf16(v); } template <> __device__ __forceinline__ float mvm_store(float v) { return v; } @@ -448,12 +344,8 @@ __global__ __launch_bounds__(kDenseThreads) void mvm_kernel( float acc[RB * MT]; rows_dot_mt(W, S, X, a_ld, r0, rows, cols, w_ld, sc_cols, m_real, lane, acc); - // C is [M][N], so MT lanes-0 write MT addresses `c_ld` apart. Scattered, and it is 2 bytes - // per output row against a whole-weight read -- the same trade the AW epilogue makes in - // r4d_gemm_fp8a8.hip, at a hundredth of the row count. - // `m_real` is MT for every exact instantiation and smaller only where M was rounded up to - // one -- the padded rows are computed and discarded, which is what buys ONE weight read - // for the whole batch instead of one a chunk. + // C is [M][N]: lane 0 writes MT scattered values `c_ld` apart, negligible against the + // weight read. Rows m >= m_real are padding (M rounded up) and are discarded. if (lane == 0) { #pragma unroll for (uint32_t r = 0; r < RB; ++r) { @@ -501,9 +393,8 @@ __global__ __launch_bounds__(kDenseThreads) void mv_kernel( } } -// The default rule. Wide rows already have enough loads in flight, so blocking -// would only remove waves; narrow rows cannot hide a load behind two inner iterations, so block -- -// harder the fewer rows there are to make waves from. +// Default RB: wide rows already have enough loads in flight, so blocking would only remove waves; +// narrow rows cannot hide a load behind two inner iterations, so block more when rows are few. uint32_t rb_default(uint32_t rows, uint32_t cols) { if (cols > 2048u) return 1u; return rows >= 8192u ? 2u : 4u; @@ -511,54 +402,27 @@ uint32_t rb_default(uint32_t rows, uint32_t cols) { // ---------------------------------------------------------------------------- the lm head, on WMMA // -// THE MATVEC ABOVE CANNOT SERVE A WIDE BATCH AND THE REASON IS NOT MEMORY. Its rate falls steeply -// with M (rows_dot_mt has the L1 argument) and row blocking recovers only part of it: what is left -// is that it is scalar FMA and the fp8a8 tile, which holds its rate across the same range on the -// identical weight, is not. +// The scalar matvec's rate falls steeply with M (see rows_dot_mt); this is the fp8a8 tile's shape +// for a bf16 activation, one weight read for up to 64 rows (e.g. eight sequences at DFlash2 +// depth 7). // -// This is that tile's shape for a bf16 activation. It costs one weight read at ANY M up to 64, -// which is what a served deployment needs: a step runs 1 + n_spec rows a SEQUENCE, so eight -// concurrent sequences at DFlash2 depth 7 put 64 rows through here, where the matvec would take -// two chunks of 32 and read the whole weight twice. +// No precision is lost: the bf16 WMMA accumulates in f32, the activation is already bf16, an E4M3 +// code is exact in bf16 (its low sixteen f32 mantissa bits are zero), and the block scale is +// applied after each 128-wide K block's accumulation. Only the summation order differs from the +// matvec. // -// IT LOSES NO PRECISION. WMMA's bf16 form takes bf16 A and bf16 B and accumulates in f32: -// -// - the activation is ALREADY bf16, so A is exact; -// - an E4M3 code has three mantissa bits and an exponent inside bf16's range, so the dequantised -// code is exact in bf16 too -- f32_to_bf16 of a value whose low sixteen mantissa bits are zero -// is a shift, and every E4M3 value has them zero; -// - the BLOCK SCALE is applied AFTER the accumulation of its own 128-wide K block, not folded -// into the operand, so it never rounds either. -// -// What changes is the ORDER of the sum -- WMMA's sixteen-wide reduction against the matvec's -// per-lane a0/a1 chains -- which is the same kind of change the split-K target already makes. -// -// THE FRAGMENT MAP IS WHY NO RE-LAYOUT IS NEEDED. r4d_fp8_wmma.h: for lane l, c = l % 16 and -// h = l / 16, the B operand of a row-major B[k][n] wants B[8h + j][c] for j = 0..7. Here -// B[k][n] = W[n][k], so a lane wants EIGHT CONSECUTIVE K of ONE weight row -- eight contiguous -// bytes at `wrow + k`, a single load out of the plain row-major plane this row already stores. The -// A operand wants A[c][8h + j], also eight consecutive K of one activation row, sixteen contiguous -// bytes. Both operands come from the same K labelling, which is rule 1 of that header. -// -// The accumulator is the other half of the map: slot j of lane l is D[8h + j][c]. So a lane owns -// ONE output column for all its slots -- one weight row, and therefore ONE block scale per K block -// rather than sixteen. That is what makes the scale a scalar multiply in the epilogue of each -// block instead of a per-element gather. +// No re-layout is needed (r4d_fp8_wmma.h's map): with c = l % 16 and h = l / 16 the B operand +// wants B[8h + j][c] = W[c][8h + j], eight consecutive K bytes of one weight row, and A wants +// A[c][8h + j], sixteen contiguous bytes; both use the same K labelling. Accumulator slot j of +// lane l is D[8h + j][c], so a lane owns one output column and one block scale per K block. typedef short lm_s8v __attribute__((ext_vector_type(8))); typedef unsigned lm_u4v __attribute__((ext_vector_type(4))); -/* TWO DECODED CODES AS ONE bf16 PAIR: the high halves of both floats, by one byte permute. A code - * decodes to a float whose low sixteen bits are zero (E4M3's three mantissa bits, an int8's seven), - * so its bf16 is exactly those high bits -- f32_to_bf16's rounding adds less than one to the low - * half and carries nothing out of it -- and packed here it is one v_perm_b32 a pair, the rounding - * adds gone too. Built from f32_to_bf16 and the vector's lanes instead, LLVM 24's 16-bit register - * halves turn each pair into two half moves and a shift where LLVM 22 had the permute: 24 more - * instructions a K step of the M = 32 tile. The same bits either way. The floats are read with - * __float_as_uint, by value: __builtin_bit_cast of a vector's element miscompiles (see the - * nontemporal load in r4d_fp8_wmma.h), and here it fed the WMMA garbage. - * - * Every tile takes it: against the f32_to_bf16 form it is 0.3 to 0.7% faster at M = 4 to 16 - * (MT 1, K 2048 to 5120), 0.8% at M = 32 (MT 2) and 7.7% at M = 64 (MT 4). */ +/* Two decoded codes as one bf16 pair: the high halves of both floats, by one v_perm_b32. A code + * decodes to a float whose low sixteen bits are zero (E4M3: three mantissa bits, int8: seven), so + * its bf16 is exactly the high half and no rounding is needed. Building it from f32_to_bf16 gives + * the same bits but more instructions. The floats are read with __float_as_uint by value: + * __builtin_bit_cast of a vector element miscompiles. */ __device__ __forceinline__ uint32_t lm_bf16_pair(v2f p) { return __builtin_amdgcn_perm(__float_as_uint(p.y), __float_as_uint(p.x), 0x07060302u); } @@ -575,134 +439,42 @@ __device__ __forceinline__ lm_s8v e4m3x8_to_bf16(uint32_t lo, uint32_t hi) { return __builtin_bit_cast(lm_s8v, r); } -// MT is ceil(M / 16): how many 16-row activation tiles ride the one weight read. +// MT is ceil(M / 16): the 16-row activation tiles sharing one weight read. // -// THE WEIGHT GOES THROUGH LDS, for the reason r4d_fp8_wmma.h's staging section gives and one more. -// A fragment read wants eight bytes of ONE weight row per lane, so a wave straight off global -// issues sixteen eight-byte requests a K step, each pulling a 128 B line that the next seven K -// steps then need to still be resident. Sixteen rows a wave times eight waves is a 16 KiB working -// set against a 32 KiB L1, which thrashes and costs roughly a third of the rate the fp8a8 tile -// reaches on the same bytes. Staged, the line is requested ONCE, by a cooperative load of -// contiguous bytes a thread, and every later read of it is an LDS read. +// The weight is staged through LDS. Read straight from global, each wave would issue sixteen +// 8-byte requests per K step whose 128 B lines must stay resident for the next seven steps: a +// 16 KiB working set per workgroup against a 32 KiB L1, which thrashes. The LDS pitch is +// lds_pitch() (r4d_fp8_wmma.h), so sixteen rows land on distinct banks. // -// The pitch is lds_pitch() and not FK, which is that header's padded-pitch argument applied -// unchanged: sixteen rows at a pitch of FK + 8 bytes land on sixteen distinct banks, where a pitch -// of FK would put all sixteen on one. +// FK (= FKB * 128) is the K one staging round covers, and the tile's main tunable. The stored row +// is [K bytes of E4M3][nkb bf16 scales], only 16-byte aligned (5200 bytes at K = 5120), so a +// 128-byte round straddles two cache lines on every row; that costs latency (a second transaction +// on the critical path), not traffic. FK = 256 reads three lines per 256 bytes instead of four and +// at MT <= 2 brings the tile within a few percent of stream rate. From MT = 3 the doubled LDS +// costs more workgroups per WGP than the straddle costs (lm_fkb_rule). Padding the stored stride +// to 128 bytes (+3.4% bytes at K = 5120) is slower than FKB = 2. // -// ------------------------------------------------- FK, and it is the whole of what this tile tunes +// Alternatives that lose and are not in the code: +// - staging the activation in LDS too: a wash at FKB = 2 and over the 64 KiB limit at MT = 4; +// - double-buffering the staged tile: matches FK at FKB = 1 (it hides the straddle rather than +// removing it), loses at MT >= 3, and does not fit at FKB = 2. Restore it if a K that is not a +// multiple of 256 ships; +// - NW = 2 weight tiles per wave: slower at every M, spills at MT = 4; +// - non-temporal weight loads: about 2x slower here (they lose coalescing on these unaligned +// rows; the 128-aligned fragment-order planes are a different case). // -// The obvious staging round is ONE 128-wide scale block, and in that form the tile's rate depends -// on MT while the weight stream does not -- which is not a memory-bound kernel. +// FK changes no arithmetic: the scale loop is nested inside the staged tile, so every element +// accumulates its K in the same order and applies each block scale after that block. // -// FK IS HOW MUCH K ONE STAGING ROUND COVERS, and widening it is the whole fix. The stored row is -// `[K bytes of E4M3][nkb bf16 scales]`, so at K = 5120 a row is 5200 BYTES -- sixteen-byte aligned -// and nothing more. A one-block round reads 128 bytes at `n * 5200 + kb`, which lands at byte 80, -// 160, 240, 64 ... inside a 128-byte line and therefore STRADDLES TWO LINES for every row of every -// round. The rest of each line is the SAME row's next block, wanted seven rounds later and long -// since evicted. FK = 256 makes it three lines a 256 bytes instead of four. +// MT >= 3 remains well short of stream rate, and the following were measured and ruled out: the +// register file (a seventh wave via a shallower unroll is ~12% slower), staging latency, the +// straddle, the activation loads (M = 56 and M = 64 take the same time), the WMMA issue rate, and +// the activation re-read (a wider workgroup reading it fewer times is slower: NW = 16 does not +// tile a WGP, and NW = 12 still loses). The cause is unknown. // -// The straddle's size is separable from FK: a K whose stored stride IS 128-aligned -// (`K + 2*K/128 == 0 (mod 128)`, which K = 8192 satisfies) runs ~39% faster at MT = 1 and ~29% at -// MT = 4 than a neighbouring K that straddles, and identically at MT = 2, which already reaches the -// aligned rate. FKB = 2 recovers most of that without a re-convert, and at MT <= 2 it brings the -// tile to within a few percent of the card's stream rate. From MT = 3 the wider tile loses: 33792 -// bytes of LDS against 17408 is fewer workgroups a WGP, and MT >= 3 has the accumulators to want -// them. lm_fkb_rule above is that rule. -// -// FOUR ARMS THAT LOSE AND ARE NOT IN THE CODE: -// -// ALDS, the activation tile staged in LDS beside the weight. Every wave in the workgroup reads -// the SAME activation bytes -- the fragment address has no `wv` in it -- so a round pulls -// MT x 2 x FK bytes through L1 eight times over, and staging it cooperatively would read it once. -// It is worth a few percent at FKB = 1 and MT <= 2, and FK DOMINATES IT: at FKB = 2 it is a wash -// at MT = 1 and a loss everywhere else. The amplification is not the constraint; the straddle -// is. At MT = 4 and FKB = 2 the two tiles also want 67584 bytes, over the 64 KiB a workgroup -// gets. -// -// DOUBLE-BUFFERING THE STAGED TILE, which is the other way to cover a staging round and the one -// that says what the straddle actually costs. Two buffers at FKB = 1 fit (34816 bytes) and turn -// the round's two barriers into one, with the next tile's global loads issued BEFORE this tile's -// WMMA. It recovers almost exactly what FK does WITHOUT MOVING A BYTE LESS, so the straddle's -// cost is LATENCY and not traffic: a 128-byte read at byte 80 of a line is two memory -// transactions instead of one, and with four loads a thread in flight the second one is on the -// critical path. FK removes the transaction, double-buffering hides it, and FK is slightly better -// because it does both. At MT >= 3 double-buffering is a small LOSS, and at FKB = 2 there is no -// room for it, so it survives nowhere. If a K that is not a multiple of 256 ever ships, FKB falls -// back to 1 and this is what to put back. -// -// NW, weight tiles a wave -- the N-direction dual of MT, meant for MT = 1 where a K step is one -// activation load, one LDS read, eight cvt and ONE wmma. NW = 2 is SLOWER at every M: it doubles -// kRows and so the LDS and the staging round, and at MT = 4 it spills 60 registers. -// -// `__builtin_nontemporal_load` on the weight stream -- the operand no block re-reads, and the -// textbook case for the hint. It is about TWICE AS SLOW at every shape. On this part the hint -// costs the stream its coalescing and there is no shape where it pays. (r4d_fp8_wmma.h's -// stage8_load offers the same hint for the fragment-order planes; this says nothing about those, -// whose rows ARE 128-aligned.) -// -// FK CHANGES NO ARITHMETIC. Every output element still accumulates its K in the same order and -// still applies its block scale after its own 128-wide block, which is why the scale loop below is -// nested INSIDE the staged tile rather than wrapped around it -- FK is a staging width and it must -// not reach the arithmetic. -// -// PADDING THE STORED STRIDE TO A 128-ALIGNED ONE IS NOT WORTH IT, and it would cost a re-convert. -// At K = 5120 the pad is 5200 -> 5376 bytes, +3.4% on every byte read, and FKB = 2 on the 5200-byte -// stride already beats an aligned stride at FKB = 1 at both ends of the M band. The straddle is -// cheaper than the padding. -// -// WHAT IS LEFT AT MT >= 3, AND IT IS FIVE THINGS IT IS NOT. MT <= 2 is within a few percent of the -// card's stream rate and is done; MT = 4 is well short of it, and every mechanism that explains the -// MT <= 2 gap has been tried there and falsified: -// -// not the register file -- the rate does track waves a SIMD (14 at MT = 1 down to 6 at MT = 4), -// and MT = 4 sits at 220 VGPRs against the 216 that would buy a seventh wave, so dropping the -// K-step unroll from two to one is the one-line way to buy it. It buys it -- 200 VGPRs, seven -// waves, no spill -- and it is about 12% SLOWER at MT = 3 and MT = 4 alike. Two K steps in flight -// are worth more than the wave. Same shape as the prefill tile's null in r4d_gemm_fp8a8.hip: a -// resource count is not a cost; -// not the staging latency -- double-buffering is a wash to a small loss there (above); -// not the straddle -- FKB = 2 is a loss there (above); -// not the activation loads -- they scale with m_real and the time does not. M = 56 and M = 64 are -// the same MT = 4 kernel doing the same WMMA, with 12% fewer activation loads at 56, and they -// take the same time; -// not the activation re-read, which is the one worth spelling out, below. -// -// It is also not the WMMA issue rate: the tile is far under the matrix pipe's throughput at MT = 4, -// and the E4M3 conversion is per WEIGHT fragment, so MT = 4 has four times MT = 1's arithmetic per -// cvt and not less. Whatever it is, five separate mechanisms have been priced and none of them is -// it, and the band is a small share of a wide-batch step. -// -// ---- WHY IT IS NOT THE ACTIVATION RE-READ ------------------------------------------------------ -// -// r4d_gemm_fp8a8.hip's narrow tile records the fall past 16 rows as the activation being staged -// once per WORKGROUP, and its fix is a wider workgroup. The arithmetic here says the same thing -// at first: the activation is read from GLOBAL inside the K loop and every workgroup reads the -// whole [M][K], so a call moves -// -// weight rows * (K + 2*nkb) + activation M * K * 2 * (rows / (NW*16)) -// -// which at this shape is 646 MB against 636 MB at M = 64 -- the same size. Halving the workgroup -// count halves the second term at no cost in parallelism, since NW * (rows/(NW*16)) is rows/16 -// whatever NW is. It does not help. NW = 16 is ~38% slower, and that part IS occupancy: the same -// 220 VGPRs and 6 waves a SIMD, but A WORKGROUP IS THE GRANULE -- 24 waves a WGP is three 8-wave -// groups or ONE 16-wave group, and the second does not tile. NW = 12 is the count that tiles -// exactly (two groups, 24 waves, 26112 B of LDS against 3 x 17408) and it is STILL a few percent -// slower while doing a third fewer activation reads. So the re-read is served out of cache and -// costs nothing measurable, and a wider workgroup makes every __syncthreads wait on more waves -- -// the same reading the double-buffering result above gives. -// -// The band is five things it is not: not the register file, not staging latency, not the straddle, -// not the activation loads, not the activation re-read. It needs a new hypothesis, not another -// pass over these. -// -// ---- THE WAVES A SIMD EACH TILE RUNS AT (R4D_WAVES) -------------------------------------------- -// -// Two staged blocks a round (FKB = 2) hold 33 KB of LDS, which caps a SIMD at six waves whatever -// the registers, so six is the target there. One block a round at MT >= 3 is a register budget: -// seven waves at MT = 3 and six at MT = 4, where two K steps in flight are worth more than a -// seventh wave (above). MT <= 2 at one block is reachable only through R4D_LM_FKB and keeps the -// budget it was measured at. Without the target the scheduler is free to trade the activation -// loads' overlap for occupancy, and at MT = 4 that trade cost 40%. +// Waves per SIMD (R4D_WAVES): FKB = 2 holds 33 KB of LDS, capping a SIMD at six waves; at one +// block per round, MT = 3 targets seven and MT = 4 six. Without the target the scheduler trades +// the activation loads' overlap for occupancy, which cost 40% at MT = 4. constexpr uint32_t lm_waves(uint32_t mt, uint32_t fkb) { return fkb == 2u ? 6u : mt >= 4u ? 6u : mt == 3u ? 7u : mt == 2u ? 9u : 12u; } @@ -727,8 +499,7 @@ __global__ __launch_bounds__(kDenseThreads) R4D_WAVES(lm_waves(MT, FKB)) void lm const uint32_t h = lane >> 4; /* which half of the K step */ for (uint32_t base = (uint32_t)blockIdx.x * kRows; base < rows; base += gridDim.x * kRows) { - /* Clamped, not skipped: a tail workgroup stages and computes - * the last row again and the store drops it. */ + /* Clamped, not skipped: a tail workgroup recomputes the last row; the store drops it. */ const uint32_t n = base + wv * 16u + c; const uint32_t nc = (n < rows) ? n : (rows - 1u); const uint16_t* scl = (const uint16_t*)(W + (size_t)nc * w_ld + cols); @@ -738,15 +509,10 @@ __global__ __launch_bounds__(kDenseThreads) R4D_WAVES(lm_waves(MT, FKB)) void lm for (uint32_t t = 0; t < MT; ++t) acc[t] = (f8v)(0.0f); for (uint32_t kt = 0; kt < cols; kt += kFK) { - /* THE ACTIVATION FRAGMENTS ARE LOADED ONE K STEP AHEAD at MT <= 3 (kPre): each step - * takes the fragments the step before it loaded and issues the next step's, so their - * round trip runs under a step's WMMAs; the tile's first step is issued here, while the - * tile stages. Loaded in the step that uses them, LLVM 24 waits for them right after - * issuing them, every step -- LLVM 22's schedule had moved the loads a step early - * itself. Against LLVM 22's build: M = 4 from +0.44% to level, M = 32 to -1.4%. At - * MT = 4 the held fragments take the tile to 238 VGPRs and it runs 3.4% slower, so it - * loads in place there. The last step reloads its own fragments rather than reading - * past the tile. */ + /* At MT <= 3 (kPre) activation fragments are loaded one K step ahead, so their round + * trip runs under a step's WMMAs; the first step's are issued here, while the tile + * stages. At MT = 4 holding them costs too many VGPRs, so they load in place. The last + * step reloads its own fragments rather than reading past the tile. */ [[maybe_unused]] lm_s8v an[kPre ? MT : 1]; auto aload = [&](uint32_t kf) { #pragma unroll @@ -756,23 +522,18 @@ __global__ __launch_bounds__(kDenseThreads) R4D_WAVES(lm_waves(MT, FKB)) void lm } }; if constexpr (kPre) aload(0u); - /* THE TILE'S BLOCK SCALES ARE READ HERE, ahead of the staging barrier, so they land - * while the tile stages and computes. Read where they are used, after a block's - * WMMAs, each is a global round trip the wave waits out with nothing else in flight, - * and a compiler is free to put the load there: LLVM 24 does for the second block of - * an FKB = 2 tile. Read here, M = 4 to 64 run 0.2 to 0.6% faster. */ + /* The tile's block scales are read ahead of the staging barrier so they arrive while + * the tile stages and computes, rather than as an exposed round trip after the WMMAs. */ uint16_t sraw[FKB]; #pragma unroll for (uint32_t sb = 0; sb < FKB; ++sb) sraw[sb] = scl[(kt + sb * kBlock) / kBlock]; - /* Before the store, because the previous tile's fragment reads are still in flight. - * Both barriers order LDS only: no thread reads global memory another one writes, and - * __syncthreads() is a fence over every address space, which on gfx12 waits for every - * load in flight -- the scale read above and the prefetched fragments with it. */ + /* Before the store: the previous tile's fragment reads may still be in flight. Both + * barriers order LDS only (no thread reads global memory another writes); on gfx12 + * __syncthreads() would also wait for the scale and fragment loads in flight. */ lds_barrier(); -/* HOW MANY STAGING LOADS ARE IN FLIGHT, and it is a REGISTER decision, not a memory one. A round - * is kFK/32 units a thread -- eight at FKB = 2 -- and unrolling it whole holds eight uint4 results - * live across the stores, 32 VGPRs on top of MT accumulators and MT partials. At MT >= 3 unrolling - * it whole puts FKB = 2 at 256 VGPRs with six spill slots, which is why the unroll narrows there. */ +/* Staging loads in flight is a register decision: a round is kFK/32 uint4 units per thread (eight + * at FKB = 2), and a full unroll holds them all live. At MT >= 3 that spills, so the unroll + * narrows. */ #pragma unroll MT >= 3 ? 4 : 8 for (uint32_t i = 0; i < kWUnits / kDenseThreads; ++i) { const uint32_t u = tid + i * kDenseThreads; @@ -783,17 +544,14 @@ __global__ __launch_bounds__(kDenseThreads) R4D_WAVES(lm_waves(MT, FKB)) void lm } lds_barrier(); - /* One scale block at a time INSIDE the staged tile, so the partial that the block - * scale multiplies is exactly the one a one-block round forms. FK is a staging width and - * nothing else; it must not reach the arithmetic. */ + /* One scale block at a time inside the staged tile, so each block scale multiplies the + * same partial a one-block round forms. */ #pragma unroll for (uint32_t sb = 0; sb < FKB; ++sb) { f8v part[MT]; #pragma unroll for (uint32_t t = 0; t < MT; ++t) part[t] = (f8v)(0.0f); -/* Four K steps in flight is the right depth until MT = 4, where four accumulators, four partials - * and four activation fragments an iteration reach 249 VGPRs and five waves a SIMD. Below MT = 4 - * the deeper unroll wins clearly; at MT = 4 the register pressure reverses it. */ +/* Four K steps in flight below MT = 4; at MT = 4 the registers (249 VGPRs) favour two. */ #pragma unroll MT >= 4 ? 2 : 4 for (uint32_t ks = 0; ks < kBlock; ks += 16u) { const uint32_t kf = sb * kBlock + ks; /* K inside the staged tile */ @@ -806,11 +564,9 @@ __global__ __launch_bounds__(kDenseThreads) R4D_WAVES(lm_waves(MT, FKB)) void lm const i2v raw = frag(s_w, wv * 16u, kf, lane); const lm_s8v bf = e4m3x8_to_bf16((uint32_t)raw[0], (uint32_t)raw[1]); -/* THE ACTIVATION LOAD IS UNCONDITIONAL: a padding row reads the last real row again and a select - * zeroes it. Guarding the load with `m < m_real` puts each one in its own branch with its WMMA - * right behind it, and the compiler is then free to wait for every load before issuing the next - * -- MT round trips a K step where one would do. LLVM 24 does exactly that, and it cost M = 64 - * 40%. The clamped row is always in bounds and already in cache, so the extra loads are free. */ +/* The activation load is unconditional: a padding row re-reads the last real row and a select + * zeroes it. A guarded load would sit in its own branch and serialise the loads (MT round trips + * per K step). */ #pragma unroll for (uint32_t t = 0; t < MT; ++t) { const uint32_t m = t * 16u + c; @@ -853,10 +609,8 @@ extern "C" int r4d_gemm_fp8a16_nt_m1_max_m(void) { return (int)kMaxMt; } // ws [ceil(N/128)][ceil(K/128)] bf16, `sw_ld` elements a row (0 = ceil(K/128)) // c [M][N] bf16, `c_ld` elements a row (0 = N) // -// M IS A TEMPLATE ARGUMENT, not a loop bound, and the switch instantiates every value rather than -// rounding up to a power of two: a verify step at n_spec 2 is M = 3, and padding it to 4 would -// spend a third of the FMAs on a row whose output is discarded. The kernel is small enough that -// eight instantiations cost less than that would. +// M is a template argument with every value 1..8 instantiated, so e.g. M = 3 does not pay for a +// padded fourth row. extern "C" int r4d_gemm_fp8a16_nt_mt(long a, long wq, long ws, long c, int M, int K, int N, int a_ld, int c_ld, int w_ld, int sw_ld, long stream) { @@ -901,44 +655,26 @@ extern "C" int r4d_gemm_fp8a16_nt_mt(long a, long wq, long ws, long c, } -// C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T, f32 out, with the SCALES IN EACH ROW'S OWN TAIL. +// C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T, f32 out, with the scales in each row's own tail. // -// This is the lm_head, the last bf16 weight in an otherwise fp8 model: 248320 rows by 5120, which -// is 1.27 GiB a rank a step and 10% of everything a decode step reads. As bf16 the projection runs -// at the card's stream rate on those bytes, so the only lever is FEWER BYTES. +// The fp8 lm_head: halves the bytes of the largest single weight read in a decode step (a bf16 +// head already runs at stream rate). // -// WHY THE SCALES RIDE IN THE ROW instead of the separate [ceil(N/128)][ceil(K/128)] plane every -// other fp8 weight here uses. `logits_gemm` has exactly ONE weight operand -- there is no second -// tensor in the schema to hand a scale plane through, and giving it one is a change to the op, to -// ref, and to every architecture that declares it. The alternative, appending the plane to the end -// of the same stream, does not survive TENSOR PARALLELISM: lm_head is ROW-sharded, and the loader -// takes a rank's rows as a byte range `rows * row_bytes` long, which would copy codes only and -// leave the scales behind. Interleaving makes every row self-contained, so the shard stays a plain -// byte range and needs to know nothing about the layout. -// -// It costs a duplicate: a 128-row block shares one scale per 128 columns and storing it per row -// repeats it 128 times. At K = 5120 that is 40 scales, 80 bytes against 5120 code bytes -- 1.6%, -// against the 50% the format saves. The kernel gets a slightly better deal than it pays: the row's -// scales are on the same pages as its codes. +// The scales ride in the row because `logits_gemm` has one weight operand, and lm_head is +// row-sharded under TP: the loader takes a rank's rows as a plain byte range, so a separate scale +// plane appended to the stream would be left behind. Each row repeats its block's scales (80 bytes +// per 5120 at K = 5120, 1.6%). // // a [M][K] bf16, `a_ld` elements a row (0 = K) // wq [N][lm_row_bytes(K)] E4M3 codes, nkb bf16 scales, pad; `w_ld` BYTES a row (0 = that) // c [M][N] f32, `c_ld` elements a row (0 = N) // -// M up to 32 is one pass: exact instantiations to 8, rounded up to a multiple of 4 above that -// with the padded rows discarded in the epilogue. Chunking re-reads the whole 636 MiB once a -// chunk, which is the entire saving, so the ceiling is as high as the accumulators allow. +// The WMMA path takes M > 2 in chunks of 64 rows, each re-reading the weight; the matvec takes +// M <= 2. // -// IT STILL HAS TO SERVE EVERY M, and that is not a preference. The bands of one op can resolve to -// different kernels, and they all read the same stored bytes -- so a row that re-layouts a weight -// and covers only part of the range leaves the rest to a kernel reading its codes as something -// else. The failure mode is not a slow path but a wrong one: if the band above 32 fell to the bf16 -// projection it would read E4M3 codes as bf16, and the model would return EMPTY completions as soon -// as enough sequences batched together while every request under 32 rows stayed perfect. -// core/build/rad_builder.cpp refuses that at declare time; this covers the range so there is -// nothing to refuse. Above 32 rows the weight is read once -// a chunk, which is what the bf16 kernel cost anyway, and a batch that wide amortises it over -// thirty-two sequences' worth of tokens. +// This row must serve every M: all bands of one op read the same stored bytes, so a band falling +// to another kernel (e.g. the bf16 projection) would misread the E4M3 codes. +// core/build/rad_builder.cpp refuses such a split at declare time. template static int logits_gemm_8(long a, long wq, long c, int M, int K, int N, int a_ld, int c_ld, int w_ld, long stream); @@ -948,8 +684,8 @@ extern "C" int r4d_logits_gemm_fp8(long a, long wq, long c, int M, int K, int N, return logits_gemm_8(a, wq, c, M, K, N, a_ld, c_ld, w_ld, stream); } -// The int8 head: the same stored row -- codes, the row's bf16 scales in its tail, the pad -- with -// i8 codes and each row's OWN scale per 128 columns where the E4M3 head repeats its block's. +// The int8 head: the same stored row (codes, bf16 scales in the tail, pad) with i8 codes and each +// row's own scale per 128 columns, where the E4M3 head repeats its block's. extern "C" int r4d_logits_gemm_i8(long a, long wq, long c, int M, int K, int N, int a_ld, int c_ld, int w_ld, long stream) { return logits_gemm_8(a, wq, c, M, K, N, a_ld, c_ld, w_ld, stream); @@ -964,41 +700,22 @@ static int logits_gemm_8(long a, long wq, long c, int M, int K, int N, int a_ld, if (!a_ld) a_ld = K; if (!c_ld) c_ld = N; if (!w_ld) w_ld = (int)r4d_fp8::lm_row_bytes(K); - /* BOTH PATHS BELOW LOAD THE WEIGHT THROUGH A uint4, at `row * w_ld + 16k`, so an odd w_ld is - * not a slow row -- it is a misaligned load on every second row. It is the layout's job to pad - * (r4d_fp8_lm.h) and this is the floor that says so out loud, because the only thing that ever - * gets this wrong is a caller passing a stride it derived itself. */ + /* Both paths load the weight as uint4 at `row * w_ld + 16k`, so w_ld must be a multiple of 16 + * (the layout pads it; see r4d_fp8_lm.h). */ if (w_ld % 16) return -5; const uint32_t rows = (uint32_t)N, cols = (uint32_t)K; - /* WMMA FROM M = 3, THE MATVEC AT OR BELOW IT. The tile's rate is nearly flat in M across this - * range, while the matvec's falls away from M = 4 up, so the crossover sits wherever the matvec - * leaves its own best row. At M = 2 the matvec is marginally ahead and at M = 1 clearly so -- - * the activation is already amortised over the whole weight there -- so the matvec keeps the - * bottom of the range and the tile takes the whole of what a speculative verify step issues. A - * step runs 1 + n_spec rows a SEQUENCE, so at DFlash2 depth 7 every served M is 8, 16, 24 ... - * R4D_LM_WMMA pins the choice (1 = tile, 2 = matvec). Both paths read the SAME stored bytes -- - * this is one kernel row with one layout, so there is no band and no claim to get wrong. */ - const uint32_t wpin = env_u32_lm("R4D_LM_WMMA"); - if (wpin == 1u || (wpin != 2u && M > 2)) { - /* THE SHAPE OF THE STAGED TILE; see lm_wmma_kernel for the argument. FKB is how many - * 128-wide scale blocks one staging round covers. R4D_LM_FKB pins it without a rebuild; - * unset means the rule. It is bit-identical either way, so a pin can only change the - * time. */ - const uint32_t fpin = env_u32_lm("R4D_LM_FKB"); - /* Sixty-four rows a pass, not thirty-two: the accumulator is four WMMA tiles and costs - * thirty-two registers, so the chunk is bounded by nothing that matters and one weight - * read covers eight concurrent sequences at DFlash2 depth 7. */ + /* WMMA from M = 3, the matvec at or below. The tile's rate is nearly flat in M; the matvec is + * marginally ahead at M = 2 and clearly at M = 1. Both read the same stored bytes. */ + if (M > 2) { + /* Sixty-four rows per pass: four WMMA accumulator tiles (32 registers). */ for (int m0 = 0; m0 < M; m0 += 64) { const int Mc = (M - m0) < 64 ? (M - m0) : 64; const uint32_t mt = (uint32_t)((Mc + 15) / 16); - /* FKB = 4 is not available: kRows * (512 + 8) is 66560 bytes of LDS against a 64 KiB - * workgroup limit, and kRows is eight waves owning a 16-row tile each. */ - uint32_t fkb = (fpin >= 1u && fpin <= 2u) ? fpin : lm_fkb_rule(mt); - /* FK has to divide K. Every real lm head is a multiple of 512, but the harness and the - * reference shapes are not, and a staging round that runs off the end of a row would - * read the next row's scales as codes. */ + /* FKB = 4 would need kRows * (512 + 8) = 66560 bytes of LDS, over the 64 KiB limit. */ + uint32_t fkb = lm_fkb_rule(mt); + /* FK must divide K, or a staging round would read the row's scales as codes. */ while (fkb > 1u && (cols % (fkb * kBlock)) != 0u) fkb >>= 1; const uint32_t per = kDenseWaves * 16u; /* weight rows a workgroup covers */ const uint32_t blocks = std::min(4096u, (rows + per - 1u) / per); @@ -1016,53 +733,22 @@ static int logits_gemm_8(long a, long wq, long c, int M, int K, int N, int a_ld, default: R4D_LMW(4); break; } #undef R4D_LMW - #undef R4D_LMW2 if (hipGetLastError() != hipSuccess) return -6; } return 0; } - for (int m0 = 0; m0 < M; m0 += 32) { - const int Mc = (M - m0) < 32 ? (M - m0) : 32; - const uint32_t rb = mvm_rb(Mc); - const uint32_t blocks = - std::min(2048u, (rows + kDenseWaves * rb - 1) / (kDenseWaves * rb)); - const uint16_t* ac = (const uint16_t*)a + (size_t)m0 * a_ld; - float* cc = (float*)c + (size_t)m0 * c_ld; -#define R4D_LGF8_RB(NM, RBV) \ - hipLaunchKernelGGL((mvm_kernel), dim3(blocks), dim3(kDenseThreads), \ - 0, \ - (hipStream_t)stream, (const uint8_t*)wq, (const uint16_t*)nullptr, \ - ac, (uint32_t)a_ld, cc, (uint32_t)c_ld, \ - rows, cols, (uint32_t)w_ld, 0u, (uint32_t)Mc) + const uint32_t blocks = std::min(2048u, (rows + kDenseWaves - 1) / kDenseWaves); #define R4D_LGF8(NM) \ - do { if (rb == 4) R4D_LGF8_RB(NM, 4); \ - else if (rb == 2) R4D_LGF8_RB(NM, 2); \ - else R4D_LGF8_RB(NM, 1); } while (0) - switch (Mc) { - case 1: R4D_LGF8(1); break; - case 2: R4D_LGF8(2); break; - case 3: R4D_LGF8(3); break; - case 4: R4D_LGF8(4); break; - case 5: R4D_LGF8(5); break; - case 6: R4D_LGF8(6); break; - case 7: R4D_LGF8(7); break; - case 8: R4D_LGF8(8); break; - default: - if (Mc <= 12) R4D_LGF8(12); - else if (Mc <= 16) R4D_LGF8(16); - else if (Mc <= 20) R4D_LGF8(20); - else if (Mc <= 24) R4D_LGF8(24); - else if (Mc <= 28) R4D_LGF8(28); - else R4D_LGF8(32); - break; - } + hipLaunchKernelGGL((mvm_kernel), dim3(blocks), dim3(kDenseThreads), \ + 0, (hipStream_t)stream, (const uint8_t*)wq, (const uint16_t*)nullptr, \ + (const uint16_t*)a, (uint32_t)a_ld, (float*)c, (uint32_t)c_ld, \ + rows, cols, (uint32_t)w_ld, 0u, (uint32_t)M) + if (M == 1) R4D_LGF8(1); + else R4D_LGF8(2); #undef R4D_LGF8 -#undef R4D_LGF8_RB - if (hipGetLastError() != hipSuccess) return -6; - } - return 0; + return hipGetLastError() == hipSuccess ? 0 : -6; } // C[1,N] = A[1,K] @ dequant(Wq)[N,K]^T. @@ -1072,9 +758,7 @@ static int logits_gemm_8(long a, long wq, long c, int M, int K, int N, int a_ld, // ws [ceil(N/128)][ceil(K/128)] bf16, `sw_ld` elements a row (0 = ceil(K/128)) // c [N] bf16 // -// NO LDS STAGING, deliberately. With uint4 loads a lane reads 16 consecutive activations, so 16 -// lanes land on the same LDS bank and the conflicts cost more than the staging saves; `a` is small -// enough that every wave in the block keeps it in L1 regardless. +// No LDS staging: with uint4 loads, 16 lanes would hit the same bank, and `a` stays in L1 anyway. // // Returns 0, or a negative code for a shape it does not serve. extern "C" int r4d_gemm_fp8a16_nt_m1(long a, long wq, long ws, long c, @@ -1084,9 +768,7 @@ extern "C" int r4d_gemm_fp8a16_nt_m1(long a, long wq, long ws, long c, if (M <= 0 || K <= 0 || N <= 0) return -2; if (M > 1) return -3; // `srow[c / 128]` reads one scale per 128 columns; a ragged last block would read past the - // plane. Every dense tensor in the target checkpoint has K a multiple of 1024, so this is a - // guard rather than a path -- but a guard that is absent is a kernel that reads other people's - // memory on the first model that is not this one. + // plane. if (K % (int)kBlock) return -4; if (rb != 0 && rb != 1 && rb != 2 && rb != 4 && rb != 8) return -5; if (!w_ld) w_ld = K; @@ -1118,31 +800,20 @@ extern "C" int r4d_gemm_fp8a16_nt_m1(long a, long wq, long ws, long c, } // ============================================================== the plugin ABI entry point -// The helpers this uses are libr4d/r4d_args.h's. See the note in r4d_model_bf16.hip. +// Helpers from libr4d/r4d_args.h; see the note in r4d_model_bf16.hip. enum { LG_X = 0, LG_W, LG_Y }; -#define R4D_NEED(x) do { const int _s = (x); if (_s != RAD_OK) return R4D_NO(_s); } while (0) -static inline int lg_dt_bf16(const RadTensor* t) { - return (t && t->dtype == RAD_BF16) ? RAD_OK : RAD_E_DTYPE; -} /* ------------------------------------------------------------------ logits_gemm, fp8 weight * - * The same projection over a quantised head. The lm_head is 248320 x 5120 on this model -- 1.27 - * GiB a rank a step, 10% of everything a decode step reads, and the last bf16 weight in an - * otherwise fp8 container. The bf16 kernel above runs at the card's stream rate, so the only - * lever is fewer bytes. - * - * The weight arrives as [n_vocab][r4d_fp8::lm_row_bytes(n_embd)]: E4M3 codes, the row's own - * bf16 scales in its tail, and the 16-byte alignment pad after those. - * r4d_rad_layout_fp8_logits explains why the scales are interleaved rather than kept in the - * separate plane every other fp8 weight here uses -- it is tensor parallelism, not taste. + * The weight arrives as [n_vocab][r4d_fp8::lm_row_bytes(n_embd)]: E4M3 codes, the row's bf16 + * scales in its tail, then the 16-byte alignment pad (see r4d_rad_layout_fp8_logits). */ static int rad_logits_gemm_8(const RadArgs* a, RadStream s, bool i8) { const RadTensor* x = r4d_opt(a, LG_X); const RadTensor* w = r4d_opt(a, LG_W); const RadTensor* y = r4d_opt(a, LG_Y); if (!x || !w || !y) return R4D_NO(RAD_E_INVAL); - R4D_NEED(lg_dt_bf16(x)); + if (x->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); if (w->dtype != (i8 ? RAD_I8 : RAD_F8E4M3)) return R4D_NO(RAD_E_DTYPE); if (y->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); if (!r4d_contig(w)) return R4D_NO(RAD_E_STRIDE); @@ -1152,13 +823,9 @@ static int rad_logits_gemm_8(const RadArgs* a, RadStream s, bool i8) { if (n_vocab <= 0 || n_embd <= 0) return R4D_NO(RAD_E_SHAPE); if (n_embd % 128) return R4D_NO(RAD_E_SHAPE); const long long stride = r4d_fp8::lm_row_bytes(n_embd); - /* THE DECLARED SHAPE, not the stored one, because the declared shape is what arrives. - * core/runtime/ctx.cpp builds a weight's RadTensor from `decl.shape` with the layout hook's - * `stored_dtype` -- so this operand comes through as [n_vocab][n_embd] E4M3 even though the - * plane is [n_vocab][n_embd + 2*nkb]. The stored width therefore cannot be checked here and is - * DERIVED, above, by the same rule the layout hook used. What guarantees the two agree is the - * engine's layout-tag check, which refuses a container laid out for any other row before a - * byte of it moves -- a better test than this one could be, and it runs earlier. */ + /* Check the declared shape: core/runtime/ctx.cpp builds the RadTensor from `decl.shape`, so it + * arrives as [n_vocab][n_embd] even though the plane is wider. The stored stride is derived + * above by the layout hook's rule; the engine's layout-tag check guarantees they agree. */ if (w->rank != 2 || w->shape[0] != n_vocab || w->shape[1] != n_embd) return R4D_NO(RAD_E_SHAPE); @@ -1182,12 +849,10 @@ extern "C" int r4d_rad_logits_gemm_fp8(const RadArgs* a, RadStream s) { extern "C" int r4d_rad_logits_gemm_i8(const RadArgs* a, RadStream s) { return rad_logits_gemm_8(a, s, true); } -#undef R4D_NEED // ============================================================== the plugin ABI entry points // -// The shared operand reader is r4d_fp8_args.h. See libr4d/r4d_args.h for why there is no adapter -// directory between the core and these launches. +// The shared operand reader is r4d_fp8_args.h; see libr4d/r4d_args.h. /* ================================================================== the fp8 GEMMs */ extern "C" int r4d_rad_gemm_fp8a16_m1(const RadArgs* a, RadStream s) { @@ -1195,19 +860,11 @@ extern "C" int r4d_rad_gemm_fp8a16_m1(const RadArgs* a, RadStream s) { int rc = fp8_ops(a, &g, 0); if (rc != RAD_OK) return rc; if (g.M > r4d_gemm_fp8a16_nt_m1_max_m()) return R4D_NO(RAD_E_SHAPE); - /* An activation scale is meaningless to this kernel -- it reads bf16 directly. A caller that - * supplies one has asked for the wrong dtype string, and running anyway would silently drop a - * scale the caller believes was applied. */ + /* This kernel reads bf16 directly; refuse an activation scale rather than silently drop it. */ if (g.ascale) return R4D_NO(RAD_E_INVAL); - /* ONE ROW KEEPS THE ONE-ROW KERNEL, and that is not just thrift: it is the RB-blocked form with - * its own tuning argument, it is what every non-speculative decode step runs, and routing it - * through the multi-row entry would change the arithmetic of a deployment that never - * speculates. The multi-row form is bit-identical at MT = 1 by construction, but "by - * construction" is a claim and this is a guarantee. - * - * Above one row it is the multi-row form, which reads the weight ONCE for all M rows. The - * alternative at M = 1 + n_spec is the 16-wide fp8a8 tile, which is slower here on identical - * weight traffic. */ + /* M = 1 keeps the one-row kernel (its own RB tuning; every non-speculative decode step), so a + * deployment that never speculates runs exactly that arithmetic. Above one row, the multi-row + * form reads the weight once for all M rows. */ if (g.M == 1) { R4dMvCfg mv; r4d_cfg_mv(a, &mv); @@ -1223,13 +880,3 @@ extern "C" int r4d_rad_gemm_fp8a16_m1(const RadArgs* a, RadStream s) { (long)(uintptr_t)s); return e == 0 ? RAD_OK : RAD_E_SHAPE; } - -/* Split-K's partial plane. Called at declare with the band's upper bound, so the arena is sized for - * the worst step in the band -- which is what makes the answer safe at every M inside it, since the - * plane is ksplit*M*N and both factors only fall as M does. - * - * SIZED FROM THE PARAMETERS, not the operands. The scratch hook is a DECLARE-time question and the - * geometry is what declare has; a hook that read `y->shape` would answer 0 whenever the core asked - * before the buffers existed, and 0 is not an error here -- it means "run unsplit", which is correct - * and slow. A correctness-preserving silent slowdown is the worst kind, because nothing reports it, - * and split-K is a large share of decode on this shape. */ diff --git a/libr4d/r4d_gemm_fp8a8.hip b/libr4d/r4d_gemm_fp8a8.hip index 4197bfd3..12fffcdd 100644 --- a/libr4d/r4d_gemm_fp8a8.hip +++ b/libr4d/r4d_gemm_fp8a8.hip @@ -1,46 +1,28 @@ -// BLOCK-SCALED FP8 weight, fp8 activation. Two entry points from one translation unit, because -// they are one K loop with two tile shapes and keeping two copies of this much staging code is how -// they drift: +// Block-scaled FP8 weight, fp8 activation. Two entry points share one K loop with two tile shapes: // -// r4d_gemm_fp8a8_nt_m16 M <= 16, the decode and speculative-verify band. One 16-wide token -// tile, split-K over the caller's scratch. -// r4d_gemm_fp8a8_tiled any M, the prefill band. 128x128 tile, eight waves. +// r4d_gemm_fp8a8_nt_m16 M <= 16 (decode and speculative verify). One 16-wide token tile, +// split-K over the caller's scratch. +// r4d_gemm_fp8a8_tiled any M (prefill). 128x128 tile, eight waves. // -// WHY THE LIBRARY NEEDS IT. Every other quantised GEMM here reads a weight this library's own -// quantiser produced. This one reads the weight A CHECKPOINT SHIPS: Qwen3.8-27B-FP8 stores -// `.weight` as F8_E4M3 [N][K] with a companion `.weight_scale_inv` in BF16 on a -// [ceil(N/128)][ceil(K/128)] grid -- `quantization_config.weight_block_size = [128, 128]`, -// DeepSeek-style block scaling. Without an entry point that reads it, serving that checkpoint means -// dequantising it to bf16 at conversion, which is twice the weight bytes of a 27B model across two -// 32 GB cards. There is no repacking and no scale conversion: the bytes in the safetensors file are -// the bytes these kernels read. +// Reads block-scaled FP8 checkpoints as shipped (DeepSeek-style, e.g. Qwen3.8-27B-FP8): +// `.weight` is F8_E4M3 [N][K] and `.weight_scale_inv` is a BF16 scale per +// 128x128 block, [ceil(N/128)][ceil(K/128)]. No repacking and no scale conversion, so the +// checkpoint never has to be dequantised to bf16 (2x the weight bytes). // -// Four properties of the K loop, each marked where it happens: +// Properties of the K loop: +// 1. The bf16 scale decodes as `__uint_as_float(s << 16)` (r4d_fp8_wmma.h). +// 2. Operand roles are a template parameter (`AW`): with the weight on A the kernel computes +// Y[rows][nb], i.e. C^T of `C[M,N] = A[M,K] @ W[N,K]^T`. +// 3. Split-K uses the caller's scratch (nothing on a launch path allocates), sized by +// r4d_gemm_fp8a8_nt_m16_scratch(). The summation order is fixed. +// 4. C is bf16, like every GEMM in this library. // -// 1. THE SCALE DTYPE. The checkpoint carries a bf16 scale per 128x128 tile; it decodes as -// `__uint_as_float(s << 16)` -- one shift and one bitcast. See r4d_fp8_wmma.h. +// Load-bearing: the padded LDS row pitch (r4d_fp8_wmma.h `lds_pitch`), the one-K-tile-ahead +// register prefetch, the two accumulator sets, and the staging assignment (`kTPR`). Reasons are at +// each. // -// 2. THE OPERAND ROLES ARE A TEMPLATE PARAMETER. With the WEIGHT on the A operand the kernel -// computes Y[rows][nb], which is C^T for this library's `C[M,N] = A[M,K] @ W[N,K]^T` -// convention. See the `AW` comment on the body. -// -// 3. SPLIT-K USES THE CALLER'S SCRATCH. Nothing on an R4D launch path allocates, so the partial -// plane is an argument and `r4d_gemm_fp8a8_nt_m16_scratch()` sizes it. The summation order is -// fixed. -// -// 4. bf16 C, NOT f32. Every GEMM in this library writes bf16 and its consumers expect that. At -// prefill's 1536x17408 that is 53 MB a store instead of 107. -// -// LOAD-BEARING: the padded LDS row pitch (r4d_fp8_wmma.h, `lds_pitch`), the one-K-tile-ahead -// register prefetch, and the two accumulator sets. The reason for each is at the line. -// -// THE STAGING ASSIGNMENT. Two threads a row at every tile width (`tid >> 1`) costs a third of this -// card's read bandwidth on the narrow tile, which is the whole of decode. The assignment used, and -// the measurement behind it, are at `kTPR` in the body. -// -// THIS ENTRY POINT RETURNS A NEGATIVE CODE rather than throwing. It is reachable from radiance's -// kernel plugin, where an error is a value and an exception crossing an .so boundary is the -// failure mode that boundary exists to avoid. +// Entry points return a negative code rather than throwing: they are reachable from a kernel +// plugin, and an exception must not cross the .so boundary. #include "r4d.h" #include "r4d_fp8_args.h" @@ -61,287 +43,134 @@ using namespace r4d_fp8; constexpr uint32_t kWave = 32; -// THE BLOCK, on both axes. One constant and not two because the checkpoint's scale grid, the -// activation quantiser's group (r4d_quant_act_fp8) and this fold must agree, and a disagreement is -// silently wrong output rather than a link error. It is NOT a build flag like R4D_GEMM_W4A8_GROUP: -// that group is a choice this library's quantiser makes, and this one is a property of the file on -// disk. +// The scale block on both axes. The checkpoint's scale grid, the activation quantiser's group +// (r4d_quant_act_fp8) and this fold must agree, so it is one constant, and not a build flag: it is +// a property of the checkpoint. constexpr uint32_t kBlock = 128; -// kFN 128 and 8 waves. A block re-reads its whole row band of the weight once per M tile, so weight -// traffic is `N*K * ceil(M/FM)`, and at M = 512 that is four passes over the weight -- which LOOKS -// like the wall and is not one. Two things say so: a shape whose whole weight fits in cache -// (N=1024, 5 MB) runs at the same TFLOP/s as one that cannot (N=34816, 178 MB), and doubling FM, -// which halves that traffic outright, is SLOWER. The four passes are absorbed by the 64 MB MALL, -// because the grid is x-fastest and the M tiles of one N band are dispatched together. -// -// What the tile really loses to is LDS BANK CONFLICTS on the fragment read, and that is fixed in -// r4d_fp8_wmma.h's row pitch rather than here -- see the bank arithmetic at `lds_pitch`. -// -// Past that, removing each remaining per-iteration cost in turn (arithmetically wrong but -// timing-valid) shows where the rest of the time is. The four that matter are the -// per-128-column fold, the global fetch, seven of the eight B fragment reads and the fold's 8-way -// per-lane activation-scale gather; each is worth 4-13% on its own and all four together are worth -// about half. So with EVERY per-iteration cost deleted this loop shape reaches about 65% of the -// rate the WMMA issues at on its own -- the gap from where it runs to that ceiling is not one -// thing. Roughly a third of it is these four, and the rest is the loop itself: the barrier eight -// waves rendezvous on once per K tile, the staging stores, the loop arithmetic. +// Prefill tile: kFN 128, 8 waves. A block re-reads its weight row band once per M tile, but that is +// not the limit: the passes are absorbed by the 64 MB MALL (the grid is x-fastest, so one N band's +// M tiles dispatch together), and doubling FM to halve the traffic is slower. The fragment read's +// LDS bank conflicts are fixed by the padded pitch (r4d_fp8_wmma.h `lds_pitch`). The remaining time +// is spread over the per-128-column fold, the global fetch, the B fragment reads, the activation +// scale gather (4-13% each) and the loop itself (barrier, staging stores, loop arithmetic); with all +// per-iteration costs removed the loop reaches about 65% of the WMMA issue rate. constexpr uint32_t kFN = 128, kFK = 64; // kFK is BYTES per LDS row -// One gfx1201 cacheline -- 256 B, not 128. This is the tile width for the narrow instantiation and -// it carries a second job: `kTPR` is FK/32, so a 256-byte tile puts EIGHT threads on a row and -// that is what makes the weight stream coalesce. 64 would put two there and cost a third of the -// bandwidth. 128 (four threads) is also full speed; 512 does not build at all, the eight staged -// granule pairs a thread being 64 VGPRs of prefetch on top of the accumulators. -// -// The prefill tile stays at 64 rather than following: it is not fetch-bound, and widening it is -// slower at every width, because its LDS tile is 128 rows and 256 bytes of that is 32 KiB of A -// alone. +// Narrow-tile K width: one gfx1201 cacheline, 256 B. `kTPR` is FK/32, so this puts eight threads +// on a row, which makes the weight stream coalesce (64 B would put two and cost a third of the +// bandwidth; 128 B is also full speed; 512 B needs 64 VGPRs of prefetch and does not build). The +// prefill tile stays at 64: it is not fetch-bound, and a 256 B row of its 128-row LDS tile would be +// 32 KiB of A alone. constexpr uint32_t kFKNarrow = 256; constexpr uint32_t kFWaves = 8; -// Activation bands a raster group of the prefill tile holds in cache -- see the kernel's grouping. +// Activation bands per raster group of the prefill tile; see the kernel's grouping. constexpr uint32_t kGroupM = 16; -// 1 M tile x 8 N tiles a wave, so the 8 waves cover 8 DISTINCT row tiles. -// -// The register tile is the two of these together and it is a genuine knob -- the body takes it as a -// template parameter so the narrow instantiation can keep 1x1 while this one is set independently. -// EIGHT ACCUMULATOR TILES IS A HARD CAP: a tile is two f32 accumulator sets, so MT*NT past 8 is -// past 128 VGPRs of accumulator and the spill is immediate. 1x8 and 2x4 are the two shapes at the -// cap and they tie; 2x8 spills 233 bytes and runs at a third the rate, 4x4 and 4x8 spill thousands -// and collapse. -// -// 1x4 ANSWERS THE RESIDENCY QUESTION. FN = 64 takes the LDS from -// 36868 B to 27652, which is FOUR blocks in a WGP's 128 KiB rather than three, and the accumulators -// from 128 registers to 64, which takes the kernel from 203 VGPRs to 136. It is about 20% SLOWER. -// So the fourth block does not pay for halving the work a wave does, and residency joins iteration -// size and instruction count on the list of things that are not what binds this loop. -// -// 2x4 IS THE INTERESTING ONE and the wave grid has to be held fixed to read it. Reshaping the -// register tile alone changes the block tile too (FN = NT*16), so a plain 2x4 is a 128x64 block and -// not a squarer wave. With a second wave axis -- grid (MW/NW) x NW, so 8 waves as 4x2 hold the SAME -// 128x128 block with 2x4 a wave -- the fragment reads fall from 9 per 8 WMMA to 6, a third off the -// LDS read traffic, and it is a WASH. -// -// That is why the second wave axis is not in the code: the fragment reads, which do not -// bank-conflict, are not the wall, and the ablation agrees -- removing SEVEN of the nine is worth -// ~10%, so removing three is worth about nothing. -// -// Also slower or neutral: widening the tile so a whole 128-column scale block is one iteration -// (which makes the fold position compile-time and deletes 39 SALU and four guarded fold sites) -- -// the bigger scheduling window costs 44 VGPRs and two waves a SIMD, and loses; the same via a -// maintained tile counter rather than an unroll, also a loss; clearing `raw` by feeding a zero -// accumulator to the first WMMA of a block instead of 64 v_mov in the fold, neutral; explicit -// `sched_group_barrier` interleavings of DS reads against WMMA, neutral to slightly worse; and an -// explicit one-slot software pipeline of the fragment reads, slightly worse, the compiler having -// already done it. -// -// And one that r4d_common.h's lds_barrier() makes look free and is not: swapping this loop's -// __syncthreads() for the LDS-scoped fence the attention kernels use costs a few percent on both -// gate_up and ffn_down. The vector-cache invalidate it removes is worth having here, which is the -// opposite of what it is worth in an attention kernel streaming KV. -// -// ---- ...AND THE WAVE GRID CANNOT BE TRANSPOSED TO REACH A WIDER TILE, AND IT IS THE ------------ -// ---- ACTIVATION SCALE THAT SAYS SO -------------------------------------------------------------- -// -// The cap above bounds MT*NT a WAVE, not the block, so the obvious way round it is to put the wave -// count on FN instead of FM: a 1xMW grid with MT = 4, NT = 2 gives a 64x256 block at the same eight -// tiles a wave as this 128x128 does at 1x8. That shape is what a SwiGLU epilogue needs here -- 256 -// weight columns is 128 gate and 128 up, so a block would emit exactly one 128-column scale group, -// which is what the narrow tile's `GATED` epilogue does. That grid loses badly. -// -// THE GRID IS THE COST. Running the SAME 128x128 tile with the same eight tiles a wave on a -// 1xMW grid -- only which wave owns which quarter of it changes -- is about FOUR TIMES slower than -// the MWx1 grid, at every shape. So the cost is not the tile shape and no tile shape reachable this -// way can pay for it. -// -// WHY, and it is the reason the activation is on A in the first place: the AW=false scale fold -// below builds `as[MT][8]`, one f32 per activation ROW the wave owns, because an activation carries -// a scale per token. MT is exactly what a transposed grid has to raise -- 1 -> 8 for the same tile, -// 1 -> 4 for the wide one -- and the cost scales with it: MT=8 is about twice MT=4's time, and -// 64 against 32 live f32 on top of 128 VGPRs of accumulator. The MWx1 grid exists so -// that a wave owns ONE row tile and eight column tiles, and the weight's scale, which is one -// scalar for 128 columns, is the operand that tolerates being spread. -// -// So the epilogue fold has a decode half and no prefill half, and the reason is a register file -// rather than a fixable oversight. See GATED on the body. +// Prefill register tile: 1 M tile x 8 N tiles per wave, so the 8 waves cover 8 distinct row tiles. +// It is a template parameter so the narrow instantiation keeps 1x1. Eight accumulator tiles is a +// hard cap: each is two f32 accumulator sets, so MT*NT > 8 spills (2x8 runs at a third the rate). +// 1x8 and 2x4 tie. Measured and rejected: +// - 1x4 (FN = 64, four resident blocks instead of three): ~20% slower; +// - 2x4 on a second wave axis (4x2 waves, same 128x128 block, a third fewer fragment reads): +// a wash, since the fragment reads are not the limit; +// - a whole 128-column scale block per iteration (compile-time fold position): costs 44 VGPRs +// and two waves per SIMD, slower; zero-C first WMMA instead of clearing `raw`, explicit +// sched_group_barrier interleaving, and a manual fragment-read pipeline: neutral or worse; +// - lds_barrier() instead of __syncthreads(): a few percent slower here (the vector-cache +// invalidate it skips is worth having in this loop); +// - a transposed 1xMW wave grid (e.g. 64x256 blocks for a SwiGLU epilogue): about 4x slower even +// at the same 128x128 tile. The AW=false fold keeps one activation scale per row the wave owns +// (`as[MT][8]`), so a grid that raises MT pays in registers; the MWx1 grid gives a wave one row +// tile, and the weight's scale (one scalar per 128 columns) tolerates being spread. Hence the +// GATED epilogue exists only for the decode tile. constexpr uint32_t kFMTiles = 1, kFNTiles = 8; -// Blocks the split is aiming for. A TUNING DEFAULT, deliberately NOT derived from the device's CU -// count: `ksplit` sets the ORDER the K partials are summed in, so deriving it would make the -// emitted text a function of which card the binary is on. +// Blocks the split aims for. A fixed tuning default, not derived from the CU count: `ksplit` sets +// the order K partials are summed in, so deriving it would make output depend on the card. // -// `gx * mw` is N/16 whatever MW is, so this rule is a function of N alone -- which is why the -// target has to be fitted against the shapes whose GRIDS fall near it and not only against the -// largest and the smallest. A target of 512 leaves the attention projections (4096 and 5120 output -// rows, a third of decode's GEMM time) running at about 60% of what the same kernel does when it is -// given enough blocks, and one 2-way split recovers it. A target of 256 leaves the mid-sized -// projections (3072 and 2048 rows, a fifth of the decode GEMM) short in the same way, by 3-12%. -// Past 8192 rows the grid is already big and splitting costs, which is why this is a target and not -// a multiplier: the guard below is what stops it there. -// -// AND IT IS 128 ACROSS THE WHOLE BAND, not only at narrow M. At M = 64 a larger target makes trunk -// shapes split that do not at 128, and every one of them loses 30-70% by it. The reason is the one -// the narrow-M reading gives from the other side: the split's cost is a partial plane of M*N f32, -// which at 64 rows is EIGHT TIMES what it is at 8, while the parallelism it buys is unchanged. A -// wider band wants a LOWER target, not a higher one, and 128 is already below every grid a trunk -// shape produces. Do not re-sweep it. +// `gx * mw` is N/16, so the rule depends on N alone. A target of 512 leaves the attention +// projections (4096-5120 rows) at ~60% of their split speed; 256 leaves the 2048-3072-row +// projections 3-12% short. Above 8192 rows splitting costs, and the guard below stops it there. +// 128 holds across the whole M band: the split's cost (an M*N f32 partial plane) grows with M while +// its benefit does not, so a wider band wants a lower target, and 128 is already below every trunk +// grid. Do not re-sweep it. constexpr uint32_t kSplitTarget = 128u; -/* AND IT DOES NOT WANT TO FALL PAST EIGHT ROWS, although isolation says it does. The split's - * BENEFIT is parallelism and its COST is the reduction -- `ksplit * M * N` floats written and read - * back -- and only the cost scales with M, so a target expressed as a tile count is blind to the - * row count. `gx * mw` is N/16 whatever the wave count is, so this decides only for N < 16*tgt, - * and AMONG THE SHAPES THIS MODEL ISSUES THE ONLY ONE THAT SPLITS AT ALL is N = 512, the attention - * k and v projections, fifty-two calls a step. At N = 512 the target picks ksplit 4 (128), 3 (96) - * or 2 (64). Best of seven, us, --perf 512 5120 M: +/* A lower target at M > 8 would split N = 512 (the attention k/v projections) three ways instead + * of four and save ~0.1 ms per step in the engine, but a split repartitions K, which changes the + * emitted text at M > 8 (short prefill chunks). Not worth the output change. * - * M 8 16 24 32 40 48 56 64 - * tgt 64 14.1 15.3 18.3 20.1 26.0 26.1 29.2 30.0 - * tgt 96 12.4 15.3 17.8 20.4 24.5 25.1 28.0 29.1 - * tgt 128 12.0 16.0 18.8 21.8 25.1 26.2 29.1 31.1 - * - * Four ways wins at M = 8 and three wins at every M above it, by 0.7 to 2.0 us in isolation -- - * which across fifty-two calls looks like most of a millisecond a step and, in the engine, is about - * a tenth of one. - * - * THE ISOLATED HARNESS OVERSTATES A SMALL WEIGHT. It rotates a 768 MB working set to defeat the - * cache; in the engine this weight is 2.6 MB and stays resident, and --profile-ops reads the call - * about a fifth faster than isolation does. What is left after that is a quarter of a percent of a - * step. - * - * AND IT IS NOT FREE: a split repartitions K, so the k/v projections at M > 8 accumulate in a - * different order and the emitted text moves. Decode at one sequence is M = 8 and untouched, but a - * short PREFILL chunk is not. A tenth of a millisecond is not a reason to spend the model's output, - * so the lower target is NOT used. A change here needs a gain worth a change in the output bits. - * - * A rule that DID want this would also have to fix the scratch query: it is asked once at declare - * with the band's upper bound and is safe only because `ksplit * M * N` falls as M does. A target - * that gives M <= 8 a larger split breaks that on both factors, and at a narrow band -- an upper - * bound of 9, say -- the answer at the bound (3*9) is under the need at M = 8 (4*8). The launch - * then degrades to ksplit 1 silently, which is the failure that query exists to prevent. */ -// ...and the cap when the OUTPUT is thin, which is a different question: a shape with `M*N < 8192` -// makes a reduce that can be thinner than the GEMM the split was widening. The reduce keeps eight -// loads in flight rather than running as a dependent chain, which is what lets the cap sit this -// high. + * Any such rule would also have to fix the scratch query: it is asked once at declare with the + * band's upper bound and is safe only because `ksplit * M * N` falls with M. A larger split at + * M <= 8 can exceed the bound's answer (e.g. 3*9 < 4*8), and the launch would silently fall back + * to ksplit 1. */ +// Split cap when the output is thin (`M*N < 8192`), where the reduce could be thinner than the GEMM +// the split widened. The reduce keeps eight loads in flight, which lets the cap sit this high. constexpr uint32_t kSplitThinCap = 64u; - -// ---- WHY THE WEIGHT IS IN FRAGMENT ORDER ------------------------------------------------------- +// ---- fragment-order weight --------------------------------------------------------------------- // -// From a row-major weight this tile reaches 515 GB/s at gate_up's decode shape where -// r4d_gemm_fp8a16_nt_m1 reaches 620 on the identical bytes, and the difference is the SHAPE OF THE -// READ. A 16x16 fragment out of a row-major [N][K] plane is 8 bytes every `w_ld`, so the weight has -// to go global -> LDS -> fragment: a staging pass, a barrier a K tile, and 36 KiB of LDS a block. -// Stored in FRAGMENT ORDER the same bytes are contiguous and none of that is needed. The order is a -// container property -- the layout hook applies it at convert time -- so it has to serve the -// prefill tile and the matvec too. -// -// THE REQUEST WIDTH IS MOST OF THE ANSWER. At 8 bytes a lane the fragment read is a 256 B request -// and LOSES to the staged path's 1 KiB on the wide shapes; at 32 bytes a lane -- four fragments, -// 1 KiB a wave -- it wins everywhere, by around 13% at the shape decode spends a third of its GEMM -// time in and 2-3% elsewhere. The layout does not win on its own; as with the staging assignment -// below, the request width does. +// A 16x16 fragment from a row-major [N][K] plane is 8 bytes every `w_ld`, so the weight must go +// global -> LDS -> fragment (a staging pass, a barrier per K tile, 36 KiB of LDS). In fragment +// order (r4d_fp8_frag.h, applied by the layout hook at convert) the bytes are contiguous and none +// of that is needed. The order is a container property, so the prefill tile and matvec serve it +// too. The win comes from the request width: 8 bytes per lane (a 256 B request) loses to staging; +// 32 bytes per lane (1 KiB per wave) wins everywhere, by ~13% on gate_up's decode shape. // ---- the body ---------------------------------------------------------------------------------- // -// fp8 x fp8 -> f32. Nothing is converted anywhere in the loop: both operands are already E4M3 bytes -// and both go global -> LDS -> fragment as raw bytes. That is the signature of a correct fp8 GEMM -// on this card -- zero 16-bit WMMA and zero in-loop dequant v_cvt in the disassembly. +// fp8 x fp8 -> f32 with no conversion in the loop: both operands are E4M3 bytes, staged as raw +// bytes (no 16-bit WMMA, no in-loop v_cvt). // -// Both operands carry a scale per 128 along K, so the two are constant together over a 128-column -// block and are applied ONCE per block to the partial sum rather than per element. That is why -// there are two accumulator sets: `raw` collects 128 columns of K unscaled, then folds into `out`. -// It costs 64 extra VGPRs and it is what keeps the inner loop free of per-element arithmetic. +// Both operands carry a scale per 128 along K, constant together over a 128-column block, so they +// are applied once per block: `raw` accumulates 128 columns unscaled and then folds into `out` +// (64 extra VGPRs, no per-element arithmetic in the inner loop). // -// Both operands are ROW-major [row][k] byte planes, which is what makes staging a pure byte copy: a -// thread wants 32 consecutive k for one row, which is 32 consecutive bytes. A dim-major activation -// would make it 32 separate strided reads. +// Both operands are row-major [row][k] byte planes, so staging is a byte copy of 32 consecutive k. // -// ---- AW: which operand is the weight, and why it is a template parameter ----------------------- +// ---- AW: which operand is the weight ----------------------------------------------------------- // -// The two operands are NOT interchangeable, because their scales have different shapes: a weight -// carries one scale per 128 ROWS, an activation one per TOKEN. And the accumulator is -// column-distributed, so a lane owns ONE B row and EIGHT A rows -- which makes a per-B-row scale -// one scalar a lane and a per-A-row scale eight. +// The scales differ in shape (weight: one per 128 rows; activation: one per token), and the +// accumulator is column-distributed (a lane owns one B row and eight A rows), so a per-B-row scale +// is one scalar per lane and a per-A-row scale eight. // -// AW = true A is the weight. Then D is [N][M] and the epilogue TRANSPOSES on the way out: -// sixteen lanes write sixteen addresses `N` elements apart, which is scattered. Used -// only at M <= 16, where the output is at most 16*N against a whole-weight read of -// N*K bytes -- 0.6% of the traffic at gate_proj's shape. Named because it is a real -// cost, bounded because the band is. It buys the decode tile shape: the small -// dimension lands on B, where a 16-wide tile is one N tile, and the M grid is over -// N, which is where the blocks are. +// AW = true A is the weight. D is [N][M] and the epilogue transposes on the way out (sixteen +// lanes write addresses `N` apart). Used only at M <= 16, where the output is +// negligible against the weight read. The small dimension lands on B (one 16-wide +// N tile) and the grid runs over the weight rows. // -// AW = false A is the activation. Then D is already [M][N] and the epilogue is a plain -// coalesced store. This is prefill. It is correct ONLY at FN == 128, because the -// weight's block scale then covers exactly the block's 128 B rows and the fold can -// treat it as one scalar; static_assert'd below. -// ---- GATED: the SwiGLU and the quantiser folded into the epilogue ----------------------------- +// AW = false A is the activation (prefill). D is [M][N] and the store is coalesced. Correct +// only when FN divides 128, so the weight's block scale is one scalar per block +// (static_assert'd below). +// ---- GATED: SwiGLU and the quantiser folded into the epilogue --------------------------------- // -// `gated_quant_fp8` reads this kernel's [M, 2n] bf16 output back and writes [M, n] E4M3 plus a -// scale per (token, 128 columns). At M = 64 that is 2.23 MB re-read, 13.1 us of launch and pass, -// and 2.23 MB of SCATTERED bf16 the transposing store had to write in the first place -- around a -// sixtieth of a wide-batch step for the quantiser alone, and the largest op left that is not -// already at a wall. +// Replaces `gated_quant_fp8` re-reading this kernel's [M, 2n] bf16 output and writing [M, n] E4M3 +// plus a scale per (token, 128 columns). It fits the narrow tile (and cannot fit the prefill tile; +// see the 8-accumulator cap): a block owns FM = 256 weight rows, 16 per wave. The first half of the +// waves takes gate rows `[c0, c0+128)`, the second half up rows `[n + c0, n + c0 + 128)`, so: // -// THE SHAPE FITS THE NARROW TILE EXACTLY, which is the whole reason this exists here and not in -// the prefill tile (where it is dead: see kSplitTarget's neighbour, the 8-accumulator cap). A -// block owns FM = 256 weight rows and a wave owns 16 of them. Give the FIRST half of the waves -// the gate rows `[c0, c0+128)` and the second half the up rows `[n + c0, n + c0 + 128)`, and: +// * a block emits exactly 128 output columns, one scale group, and the amax closes in the block; +// * waves w and w + MW/2 hold the same 16 output columns for the same tokens in the same lane +// (the accumulator mapping does not depend on the weight rows), so the gate stash is a +// straight per-lane copy through LDS with no bank conflict; +// * `acc_row(lane, t) = (lane >> 4) * 8 + t` is eight consecutive output columns for one token, +// so the E4M3 store is one 8-byte access; +// * block count and total WMMA are unchanged. // -// * a block emits exactly 128 fused output columns -- ONE 128-column scale group, so the -// quantiser's amax closes inside the block and no second pass is needed; -// * wave w and wave w + MW/2 hold the SAME 16 output columns for the SAME tokens, in the same -// lane, because the accumulator's (frag_c, acc_row) mapping does not depend on which weight -// rows were multiplied. So the gate stash is a straight per-lane copy through LDS with no -// permutation and no bank conflict; -// * `acc_row(lane, t) = (lane >> 4) * 8 + t` is EIGHT CONSECUTIVE output columns for one token, -// so the E4M3 store is one 8-byte access rather than the dword `quant_group` manages; -// * the block count and the total WMMA are UNCHANGED -- 8704/128 blocks against 17408/256. +// The stash reuses `s_b`, dead after the K loop (16 KiB at NT = 4 of the 16.5 KiB it holds); only +// the 2 KiB amax plane is new. // -// THE STASH COSTS NO LDS. `s_b` is dead once the K loop ends, and MW/2 * kWave * NT * 8 bf16 is -// 16 KiB at NT = 4 against the 16.5 KiB it already holds. Only the amax plane is new, 2 KiB. +// Byte-identical to the unfused pair: the accumulator is rounded to bf16 first and silu and the +// multiply run on the round-tripped values. The amax is an fmaxf reduction, exact and order-free. // -// AND IT IS BYTE-IDENTICAL TO THE PAIR, which is a requirement and not a hope: the accumulator is -// rounded to bf16 FIRST and the silu and the multiply run on the round-tripped values, because -// that is what a GEMM which stores a bf16 tensor and a quantiser which reads it back compute. -// The amax is an fmaxf reduction, which is exact and order-free, so folding it across waves rather -// than across a wave's lanes cannot move a bit. -// ---- AN EVICT-FIRST HINT ON THE NARROW PATH'S WEIGHT STREAM, AND WHY IT IS OFF ---------------- -// -// The two operands of a decode GEMM have opposite reuse and the cache cannot tell. On the narrow -// path A is the WEIGHT: every block reads a DIFFERENT 16-row slice, once, and no block ever reads -// it again. B is the ACTIVATION: every block reads ALL of it, so at gate_up's 68 blocks a 320 KiB -// activation is read 68 times -- 22 MiB of requests off 320 KiB of data, which is a cache hit if -// and only if the 89 MiB of weight streaming past it has not evicted it. LRU says it has. -// -// So the hint goes on the weight load and not on the activation load. Nothing about the arithmetic -// moves; it is a replacement policy hint on one of the two loads. -// -// NOT ON THE PREFILL TILE, where the sharing is the other way round: its grid is -// ceil(M/128) x ceil(N/128) and the M blocks of one N band all read the SAME weight tile, 32 of -// them at a 4096-token chunk. Hinting a shared operand evict-first is the opposite of this. -// -// IT IS OFF. In isolation the hint is worth 2-7% at every shape and in both bands; in the engine -// the step does not move at all. The isolated benchmark runs one shape 50 times over 20 weight -// copies with ONE activation buffer, so the activation is hot across iterations and the hint -// measures its own repetition. The engine calls each GEMM once, on an activation the previous -// kernel has just written -- already resident, with nothing to protect it from. The re-read model -// above ("68 blocks x 320 KiB") is right about the request count and wrong about where those -// requests are served: they already hit. -// -// It stays as one template argument, off, so the measurement stays with the code -- as -// r4d_attn_decode's O_KNT does for the KV stream. -constexpr bool kNarrowWeightNT = false; +// The narrow path's weight loads carry no nontemporal hint: the activation every block re-reads +// was just written by the previous kernel and is resident, so protecting it does not move a step. -/* I8 IS THE SAME KERNEL AT INT8 CODES (gemm_i8a8_*): both operands i8 bytes in the same staging - * and fragment order, v_wmma_i32_16x16x16_iu8 for the fp8 mma, and the WEIGHT's scale per ROW per - * 128 K -- bf16, tile-major [N/16][K/128][16] (r4d_fp8_layout.cpp) -- where the fp8 weight's is - * per 128x128 tile. Only the fold reads the difference: one weight scale per accumulator row on - * the narrow path, one per lane's column on the prefill tile. The fp8 instantiations are - * unaffected. */ -/* THE WAVES A SIMD EACH TILE SHAPE RUNS AT (R4D_WAVES): the register budget every shape here was - * tuned at. The narrow tile's NT accumulators and its K-step unroll are sized against it, and a - * compiler left to choose moves it either way -- LLVM 24 spends 25 to 55 more VGPRs on NT 3 and 4 - * at FK 256 and drops a wave or two, which cost the 64-row verify step 15%. One and two waves a - * block are held by LDS, not registers, and carry the LDS-bound count. */ +/* I8 is the same kernel at int8 codes (gemm_i8a8_*): i8 operands in the same staging and fragment + * order, v_wmma_i32_16x16x16_iu8, and a weight scale per row per 128 K (bf16, tile-major + * [N/16][K/128][16], r4d_fp8_layout.cpp) instead of per 128x128 tile. Only the fold differs: one + * weight scale per accumulator row on the narrow path, one per lane's column on the prefill tile. */ +/* Waves per SIMD for each tile shape (R4D_WAVES): pins the register budget each shape was tuned at + * (the narrow tile's NT accumulators and K-step unroll are sized against it), so a compiler release + * cannot change occupancy. Shapes with one or two waves per block are LDS-bound and use that + * count. */ constexpr uint32_t f8_waves(bool full, bool aw, uint32_t nt, uint32_t mw, uint32_t fk, bool i8) { if (!aw) return 6u; if (mw == 1u) return nt == 1u ? 8u : nt == 2u ? 4u : nt == 3u ? 3u : 2u; @@ -376,55 +205,42 @@ void gemm_fp8a8_kernel( constexpr uint32_t FN = NT * 16; // B rows a block constexpr uint32_t FM = MW * MT * 16; // A rows a block - // The AW=false fold reads the weight's scale as ONE scalar for the block's B rows, so those rows - // must sit in one 128-row scale row: FN divides 128 and n0 is FN-aligned, which gives it. + // The AW=false fold reads the weight's scale as one scalar for the block's B rows, so they must + // sit in one 128-row scale row: FN divides 128 and n0 is FN-aligned. static_assert(AW || kBlock % FN == 0, "AW=false folds the weight scale as one scalar per block"); - // Only the AW branch folds the A-side scale as one scalar; with AW=false the A side is the - // activation and carries a scale per ROW, so FM is free of the block. THE UNIT IS THE WAVE AND - // NOT THE BLOCK: the fold below indexes at `(m0 + wm) / kBlock`, so what has to sit in one - // 128-row scale row is a wave's MT*16 rows, not the block's FM of them. Requiring it of the - // block would cap FM at 128 and so MW at 8 -- and the block's activation re-read is the whole - // cost past 16 token rows. + // With AW the A-side (weight) scale is folded as one scalar per wave, indexed at + // `(m0 + wm) / kBlock`, so a wave's MT*16 rows (not the block's FM) must sit in one 128-row + // scale row. Requiring it of the block would cap MW at 8. static_assert(!AW || (MT * 16 <= kBlock && kBlock % (MT * 16) == 0), "a wave's A rows must sit in one scale row"); // ...and m0 is FM-aligned with FM a multiple of MT*16, so a wave's rows never straddle either. static_assert(!AW || FM % (MT * 16) == 0, "FM must be a whole number of wave row tiles"); - // DOUBLE BUFFERED, on the prefill tile only. A single buffer needs two barriers a K tile -- one - // to know every wave has finished READING the tile before it is overwritten, one to publish the - // new one -- and there are only 32 WMMA between them, so eight waves rendezvous twice per tile. - // With two buffers the overwrite lands somewhere nobody is reading and only the publish barrier - // remains, which is worth about 5% at gate_up's prefill shape -- and it pays even though the - // extra LDS drops the block from 4 resident a WGP to 3. - // - // The narrow tile keeps one buffer: it is 256 B wide and two of them are 74 KiB against the - // 64 KiB a workgroup may hold. It loses nothing -- decode waits on HBM, not on a barrier -- and - // the two-barrier structure is preserved there by the `else` at the loop foot. + // Double-buffered on the prefill tile only: one buffer needs two barriers per K tile (finish + // reading, then publish) around just 32 WMMA; two buffers leave only the publish barrier (~5% + // at gate_up's prefill shape, despite 3 resident blocks per WGP instead of 4). The narrow tile + // keeps one buffer (two would be 74 KiB, over the 64 KiB limit; decode waits on HBM anyway) and + // the two-barrier structure is kept by the `else` at the loop foot. constexpr uint32_t kBufs = AW ? 1u : 2u; __shared__ uint8_t s_b[kBufs][FN * lds_pitch()]; - // NO LDS FOR A WHERE A IS THE WEIGHT. Fragment order delivers a lane its own fragment bytes - // straight from global, so there is no 16-row transpose to stage -- and the narrow tile needs - // 4 KiB of LDS a block rather than 38, which is occupancy on top of the fetch. One byte rather - // than zero because a zero-length array is not a type. + // No LDS for A when A is the (fragment-order) weight: a lane loads its fragment bytes straight + // from global, so the narrow tile needs 4 KiB of LDS instead of 38. One byte, since a + // zero-length array is not a type. __shared__ uint8_t s_a[kBufs][AW ? 1u : FM * lds_pitch()]; uint32_t buf = 0; const uint32_t tid = threadIdx.x, lane = tid & (kWave - 1), wave = tid / kWave; - // Split-K. `ck` is a multiple of both 128 (the scale block) and FK (the staged tile), and - // ksplit is derived FROM it at the launcher, so every slice has work and starts on a scale - // boundary. + // Split-K. `ck` is a multiple of both 128 (the scale block) and FK, and the launcher derives + // ksplit from it, so every slice has work and starts on a scale boundary. const uint32_t kbeg = ck ? blockIdx.z * ck : 0u; const uint32_t kend = ck ? min(cols, kbeg + ck) : cols; if (kbeg >= kend) return; - // THE PREFILL TILE RUNS IN GROUPS OF kGroupM ACTIVATION BANDS. Blocks are dispatched in - // flattened-id order, so with the plain x-fastest grid every weight band sweeps ALL of the - // activation, and the activation is read once per 128 weight rows. That is free while it sits - // in the 64 MB MALL and is the whole cost once it does not: at M = 16384 x K = 4096 (64 MB) - // gate_up's 192 bands read 12 GB and ran at half the rate of M = 4096. Within a group the - // kGroupM bands stay cached across the full N sweep, and the weight is read once a group. - // With kGroupM bands or fewer the order is the plain one, and skipping the division keeps a - // short prefill chunk at its old rate (2% at M = 512). + // The prefill grid runs in groups of kGroupM activation bands. Blocks dispatch in flattened-id + // order; with the plain x-fastest grid the activation is read once per 128 weight rows, which + // halves the rate once it exceeds the 64 MB MALL. Within a group the bands stay cached across + // the N sweep and the weight is read once per group. With kGroupM bands or fewer the plain order + // is used and the division skipped. uint32_t bm = blockIdx.x, bn = blockIdx.y; if (!AW && gridDim.x > kGroupM) { const uint32_t per = kGroupM * gridDim.y; @@ -436,16 +252,12 @@ void gemm_fp8a8_kernel( } const uint32_t m0 = bm * FM; const uint32_t n0 = bn * FN; - // Wave grid MW(M) x 1(N): a wave owns MT*16 A rows and all FN B rows. A 4x2 grid at the same - // 128x128 tile -- 2x4 a wave, so 6 fragment reads per 8 WMMA rather than 9 -- is a WASH, which - // says the fragment reads, which do not bank-conflict, are not the wall. There is no - // second wave axis in the code for that reason. + // Wave grid MW(M) x 1(N): a wave owns MT*16 A rows and all FN B rows (see kFMTiles for why + // there is no second wave axis). const uint32_t wm = wave * (MT * 16), wn = 0; - /* THE ONE THING GATED CHANGES BEFORE THE EPILOGUE: which weight rows a wave owns. The gate - * half and the up half are `rows/2` apart, so the assignment stops being contiguous and every - * later use of `m0 + wm` -- the fragment tile, the liveness test, the A-side block scale -- - * goes through this instead. A wave still owns 16 consecutive rows, 16 still divides 128, so - * the "a wave's rows sit in one scale row" invariant that lets FM be 256 is untouched. */ + /* GATED changes which weight rows a wave owns before the epilogue: the gate and up halves are + * `rows/2` apart, so later uses of `m0 + wm` (fragment tile, liveness, A-side scale) go through + * wrow0. A wave still owns 16 consecutive rows, so they stay in one scale row. */ constexpr uint32_t kGHalf = GATED ? (MW / 2u) : MW; const uint32_t wrow0 = GATED ? ((wave < kGHalf ? 0u : rows / 2u) + blockIdx.x * (FM / 2u) @@ -462,36 +274,24 @@ void gemm_fp8a8_kernel( #pragma unroll for (uint32_t j = 0; j < NT; ++j) { raw[i][j] = acc_zero(); out[i][j] = acc_zero(); } - // ---- THE STAGING ASSIGNMENT, which is a bandwidth decision and not a bookkeeping one -------- + // ---- staging assignment (a bandwidth decision) ------------------------------------------------ // - // A thread stages one 32-byte granule pair; the question is WHICH one, and the answer is worth - // 1.5x of the weight stream. The threads that share a row are CONSECUTIVE, so `kTPR` of them - // cover a whole row of the tile and a wave's single load instruction asks for - // `32 * 32 / kTPR` rows of `kTPR * 32` contiguous bytes each. + // A thread stages one 32-byte granule pair, and the threads sharing a row are consecutive, so + // `kTPR` threads cover a row and one wave load asks for `32 * 32 / kTPR` rows of `kTPR * 32` + // contiguous bytes. Streaming 5120-byte rows on gfx1201: // - // With `tid >> 1` -- two threads a row at every FK -- a wave asks for SIXTEEN 64-byte pieces of - // sixteen different rows, each row `ld` bytes from the last. That is sixteen separate - // transactions off a 256-byte cacheline. A kernel that reads the same bytes in the same order - // and does nothing else (rows of 5120 B, 1 GiB total, gfx1201): - // - // threads a row 2 4 8 16 32 + // threads per row 2 4 8 16 32 // GB/s 422 626 633 635 636 (plain stream: 638) // - // So two threads a row leaves a third of the card's bandwidth on the table, and four already - // recovers effectively all of it. Since a thread's granule pair is 32 B, kTPR is FK/32 -- which - // is 2 for the prefill tile, where the fetch is not the limit, and 8 for the 256-byte narrow - // tile, where it IS the limit: decode reads every weight in the - // model exactly once and does nothing else. - // - // Rows a pass covers is then blockDim/kTPR, and the tile takes as many passes as it needs. The - // register cost is that of two threads a row: a thread holds kAP granule pairs at one column - // across kAP rows rather than spread along one row. Same bytes, same count, same LDS stores. + // Two threads per row leaves a third of the bandwidth unused; four recover it. kTPR = FK/32: 2 on + // the prefill tile (not fetch-bound), 8 on the 256-byte narrow tile (fetch-bound). A pass covers + // blockDim/kTPR rows; a thread holds kAP granule pairs at one column across kAP rows. constexpr uint32_t kSeg = 32; // bytes a thread stages, contiguous constexpr uint32_t kTPR = FK / kSeg; // threads covering one row constexpr uint32_t kRPP = (MW * kWave) / kTPR; // rows one pass covers constexpr uint32_t kAP = AW ? 0u : (FM + kRPP - 1) / kRPP; // passes over the A tile - // Fragment-order supertiles a staged K tile spans, when A is the weight: one 32-byte load a - // lane each, and each carries FOUR fragments (r4d_fp8_frag.h says why four and not one). + // Fragment-order supertiles per staged K tile when A is the weight: one 32-byte load per lane, + // four fragments each (see r4d_fp8_frag.h). constexpr uint32_t kAF = AW ? FK / r4d_fp8::kSuperK : 0u; constexpr uint32_t kBP = AW ? (FN + kRPP - 1) / kRPP : 0u; // ... and over the B tile static_assert(kTPR >= 1 && kRPP >= 1, "FK must be at least 32 B and no wider than the block"); @@ -499,46 +299,37 @@ void gemm_fp8a8_kernel( const uint32_t sn = tid / kTPR, sk = (tid % kTPR) * kSeg; const uint32_t am = sn; // A staging, identical assignment - // The B rows this lane owns, one per N tile -- a lane owns column `frag_c` of each of its NT - // accumulators, and those are 16 columns apart. Folding a per-B-row scale with only the first - // one is wrong for the others, which reads as a ~2.0 relative error rather than as noise. + // The B rows this lane owns, one per N tile (column `frag_c` of each of its NT accumulators, + // 16 apart). A per-B-row scale must be looked up for each, not just the first. const uint32_t brow0 = n0 + wn + frag_c(lane); - // ---- B, WHEN B IS THE WEIGHT, comes from the fragment-order plane ------------------------ + // ---- B from the fragment-order plane, when B is the weight ----------------------------------- // - // A wave reads ONE (16 row, 64 k) tile per pass: 32 lanes x 32 contiguous bytes is the whole - // 1 KiB tile, which is the request width the layout exists for. The de-permutation happens in - // the LDS store, so the tile in LDS is the same row-major padded one every fragment read in - // this family expects. + // A wave reads one (16 row, 64 k) tile per pass: 32 lanes x 32 contiguous bytes, the full 1 KiB. + // It is de-permuted in the LDS store, so LDS holds the usual row-major padded tile. constexpr uint32_t kBSK = FK / r4d_fp8::kSuperK; // k supertiles a staged tile constexpr uint32_t kBTL = (FN / 16u) * (kBSK ? kBSK : 1u); // 16-row tiles in it constexpr uint32_t kBFP = AW ? 0u : (kBTL * 32u + MW * kWave - 1u) / (MW * kWave); const uint32_t btile = tid / 32u, blane = tid % 32u; const uint8_t* bsrc = Bp + (size_t)(n0 + sn) * b_ld + sk; const uint8_t* asrc = Ap + (size_t)(m0 + am) * a_ld + sk; - // A AS FRAGMENTS. A wave owns ONE 16-row tile of the weight (MT is 1 on the narrow path), so - // its whole A operand for 64 k is the 32 bytes this lane holds in that tile. `ksuper` is the - // plane's tile stride; `arow` is this wave's row tile, which is out of range only when N is - // not a multiple of the block's FM rows. + // A as fragments: a wave owns one 16-row weight tile (MT is 1 on the narrow path), so its A + // operand for 64 k is this lane's 32 bytes. `ksuper` is the plane's tile stride; `arow` is out + // of range only when N is not a multiple of FM. const uint32_t ksuper = cols / r4d_fp8::kSuperK; const uint32_t arow = wrow0 / 16u; const bool alive = !AW || wrow0 < rows; const uint8_t* afrag = Ap + (size_t)lane * r4d_fp8::kLaneBytes; - // One K tile ahead, in registers. The load for tile c0+FK is issued before the WMMA for tile c0 - // and consumed after it, so the memory latency sits under the arithmetic instead of in front of - // a barrier. Nothing about what is computed changes -- same operands, same order. - // - // `sk` is the same column for every pass, so the liveness test against `cols` is too, and the - // per-pass part of the predicate is only whether that row exists. + // One K tile ahead in registers: the load for tile c0+FK is issued before tile c0's WMMA and + // consumed after it, hiding memory latency under arithmetic. `sk` is the same column for every + // pass, so only row existence varies per pass. const bool k_live = Full || (kbeg + sk + kSeg <= cols); - // `pa` stages A row-major into LDS; `pf` is A read as fragments. Exactly one of them is live, - // and the other is a zero-length array the compiler drops. - /* `pf` is the ONLY operand the mma loop reads straight from registers -- everything else has - * been stored to LDS by then -- so its prefetch cannot land in the registers the CURRENT tile - * is about to be multiplied out of. `pfn` takes the next tile and the loop foot rotates. - * Without it the prefetch destroys the tile it sits in front of, which is invisible wherever - * split-K makes each block run ONE K iteration and the prefetch never fires. */ + // `pa` stages A row-major into LDS; `pf` is A read as fragments. Exactly one is live; the other + // is a zero-length array. + /* `pf` is read straight from registers by the mma loop, so its prefetch goes to `pfn` and the + * loop foot rotates them; prefetching into `pf` would overwrite the current tile (a bug hidden + * whenever split-K gives a block only one K iteration). */ Stage8 pb[kBP ? kBP : 1u], pa[kAP ? kAP : 1u], pw[kBFP ? kBFP : 1u]; Stage8 pf[kAF ? kAF : 1u], pfn[kAF ? kAF : 1u]; #pragma unroll @@ -565,7 +356,7 @@ void gemm_fp8a8_kernel( #pragma unroll for (uint32_t p = 0; p < kAF; ++p) { const uint32_t st = kbeg / r4d_fp8::kSuperK + p; - pf[p] = stage8_load( + pf[p] = stage8_load( afrag + (size_t)(arow * ksuper + st) * r4d_fp8::kTileBytes, alive && st < ksuper); } @@ -618,16 +409,15 @@ void gemm_fp8a8_kernel( #pragma unroll for (uint32_t p = 0; p < kAF; ++p) { const uint32_t st = c1 / r4d_fp8::kSuperK + p; - pfn[p] = stage8_load( + pfn[p] = stage8_load( afrag + (size_t)(arow * ksuper + st) * r4d_fp8::kTileBytes, alive && st < ksuper); } } - /* THE FOLD'S ACTIVATION SCALES, A TILE AHEAD (fp8 prefill tile): eight a lane, read at the - * top of the staged tile that ends in a fold so its WMMA cover them. Loaded where the fold - * runs, LLVM 24 issues them there and waits for each one in turn. At FK <= kBlock the fold - * fires only at a tile's last step, so the tile is known here. */ + /* fp8 prefill tile: the fold's activation scales (eight per lane) are read at the top of a + * staged tile that ends in a fold, so its WMMA hide them. At FK <= kBlock the fold fires + * only at a tile's last step, so that tile is known here. */ constexpr bool kAsAhead = !AW && !I8 && FK <= kBlock; [[maybe_unused]] float asn[kAsAhead ? MT : 1][8]; if constexpr (kAsAhead) { @@ -646,9 +436,9 @@ void gemm_fp8a8_kernel( #pragma unroll for (uint32_t ks = 0; ks < FK; ks += kK) { i2v af[MT], bf[NT]; - // A FROM REGISTERS WHERE IT IS THE WEIGHT: the 32 bytes this lane loaded for the - // 64-k supertile ARE its four fragments, at +0, +8, +16 and +24. `ks` is a constant - // after unrolling, so the selection folds away entirely. + // When A is the weight it comes from registers: the 32 bytes this lane loaded for the + // 64-k supertile are its four fragments (+0, +8, +16, +24). `ks` is constant after + // unrolling, so the selection folds away. if (AW) { af[0] = frag_of(pf[ks / r4d_fp8::kSuperK], (ks % r4d_fp8::kSuperK) / 16u); } else { @@ -663,39 +453,21 @@ void gemm_fp8a8_kernel( #pragma unroll for (uint32_t j = 0; j < NT; ++j) raw[i][j] = mma8(af[i], bf[j], raw[i][j]); - // End of a 128-column scale block: fold both scales in and reset. INSIDE the ks loop, - // because at FK = 256 one staged tile spans two scale blocks and folding once would - // apply the second block's scale to the first block's products. + // End of a 128-column scale block: fold both scales in and reset. Inside the ks loop + // because at FK = 256 one staged tile spans two scale blocks. // - // THE TEST IS NOT COMPILE-TIME AND THE BODY RUNS AT EVERY ks. `c0` is a runtime value, - // so the modulo is a runtime test at each unrolled position and the compiler - // IF-CONVERTS it rather than branching: `libr4d/isa/loop.sh` shows all four of the - // prefill tile's ks blocks carrying eight scale loads with a 64-bit address each, 64 - // scaled adds and 64 resets -- ~150 of ~190 instructions against eight WMMA, where once - // every OTHER staged tile is what the arithmetic asks for. - // - // GATING IT IS LEGAL, BYTE-IDENTICAL, AND ABOUT 16% SLOWER on the prefill tile, which - // is the same wall the tile-widening variant in the header hits and a sharper reading - // of it. Both entry points require K to be a multiple of kBlock and of FK, so the - // position IS constant after unrolling -- at FK <= kBlock only a tile's last step can - // fire, at FK > kBlock the boundaries sit at fixed ks. Gated, the loop is 310 - // instructions instead of 847 at the same 32 WMMA (the narrow tiles 295 instead of 989 - // and 513 instead of 2140), the narrow tiles do not move, and the prefill tile loses. - // Hoisting the scale loads to the top of the staged tile as well, so a whole tile of - // WMMA covers them, changes nothing further. - // - // The header blames 44 VGPRs and two waves a SIMD for the widening variant. Gating - // widens nothing and still takes the kernel from 203 to 253 VGPRs, so it is the - // REGISTERS the fold's live range costs and not the iteration size -- and deleting - // instructions from this loop is not the lever. See libr4d/isa/README.md for the - // issue-rate arithmetic that says the same thing from the other side. + // `c0` is a runtime value, so the compiler if-converts this test at every unrolled ks + // (libr4d/isa/loop.sh: ~150 of ~190 instructions per eight WMMA on the prefill tile). + // Gating it at the compile-time-known positions is legal and byte-identical, cuts the + // loop from 847 to 310 instructions, but raises the kernel from 203 to 253 VGPRs and is + // ~16% slower on the prefill tile (narrow tiles unchanged). The fold's register live + // range, not the instruction count, is the cost; see libr4d/isa/README.md. if ((c0 + ks + kK) % kBlock == 0 || c0 + ks + kK >= kend) { const uint32_t kb = (c0 + ks) / kBlock; if (AW && I8) { - // A is the int8 weight: a bf16 scale per ROW, and a lane's eight accumulator - // slots are eight CONSECUTIVE rows of one 16-row tile -- which the tile-major - // plane, [N/16][K/128][16], stores side by side: one 16-byte load. B is the - // activation, as below. + // A is the int8 weight with a bf16 scale per row. A lane's eight accumulator + // slots are eight consecutive rows of one 16-row tile, adjacent in the + // tile-major [N/16][K/128][16] plane: one 16-byte load. B is the activation. const uint32_t nkb8 = (cols + kBlock - 1) / kBlock; float wsr[MT][8]; #pragma unroll @@ -724,9 +496,9 @@ void gemm_fp8a8_kernel( } } } else if (I8) { - // B is the int8 weight: a bf16 scale per row, and a lane owns ONE weight row a - // tile -- its column, frag_c -- so one scale a lane a tile. A is the activation - // with its f32 scale per (token, 128 K), eight a lane a tile. + // B is the int8 weight with a bf16 scale per row; a lane owns one weight row per + // tile (frag_c), so one scale. A is the activation, f32 scale per (token, + // 128 K), eight per lane per tile. const uint32_t nkb8 = (cols + kBlock - 1) / kBlock; float wsc[NT]; #pragma unroll @@ -756,11 +528,9 @@ void gemm_fp8a8_kernel( raw[i][j][t] = 0.0f; } } else if (AW) { - // A is the weight: one bf16 scale for THIS WAVE's A rows. A wave owns MT*16 of - // them, 16 divides 128 and m0 + wm is a multiple of MT*16, so those rows sit in - // one scale row whether or not the whole block does -- which is what lets FM be - // 256. B is the activation: one f32 scale per (token, 128-column block), one - // scalar a lane a tile. + // A is the weight: one bf16 scale for this wave's MT*16 rows, which sit in one + // scale row (see the static_assert). B is the activation: one f32 scale per + // (token, 128-column block), one per lane per tile. const float ws = bscale(((const uint16_t*)Sa)[(size_t)(wrow0 / kBlock) * sa_ld + kb]); #pragma unroll @@ -778,9 +548,8 @@ void gemm_fp8a8_kernel( } } } else { - // B is the weight: one bf16 scale for the block's 128 B rows. A is the - // activation: one f32 scale per token, and a lane owns EIGHT A rows through - // acc_row, so eight scalars a lane a tile. Same load count as the AW branch. + // B is the weight: one bf16 scale for the block's B rows. A is the activation: + // one f32 scale per token, eight per lane (acc_row). const float ws = bscale(((const uint16_t*)Sb)[(size_t)(n0 / kBlock) * sb_ld + kb]); float as[MT][8]; #pragma unroll @@ -807,9 +576,8 @@ void gemm_fp8a8_kernel( } } } - // Two buffers: nothing to wait for, the next store lands in the other one. One buffer: this - // is the barrier that says every wave is done reading before it is overwritten. - /* The next tile's fragments become this one's, after the mma has consumed them. */ + // Two buffers: the next store lands in the other one. One buffer: wait until every wave has + // finished reading before it is overwritten. The prefetched fragments become current. #pragma unroll for (uint32_t p = 0; p < kAF; ++p) pf[p] = pfn[p]; if (kBufs > 1u) buf ^= 1u; else __syncthreads(); @@ -837,17 +605,14 @@ void gemm_fp8a8_kernel( } __syncthreads(); - // Every arithmetic step below is r4d_fused_quant_fp8.hip's gated_quant_fp8_kernel, in its - // order: the gate and the up value BOTH round-tripped through bf16, silu in f32, the - // product rounded to bf16, and the quantiser reading that. + // Same arithmetic and order as r4d_fused_quant_fp8.hip's gated_quant_fp8_kernel: gate and up + // both round-tripped through bf16, silu in f32, product rounded to bf16, then quantised. float v[NT][8]; if (half != 0u) { #pragma unroll for (uint32_t j = 0; j < NT; ++j) { - /* A WHOLLY DEAD TOKEN TILE IS SKIPPED BY THE WHOLE WAVE, which is the only - * saving available here: `tok` is a function of the LANE, so the per-element - * guard in the store below is divergence and costs what it skips. `n0 + j*16` is - * uniform, and at M = 48 with NT = 4 the last tile is entirely past the end. */ + /* Skip a token tile wholly past the end (wave-uniform test); the per-lane guard in + * the store is divergent and saves nothing. */ if (!Full && n0 + wn + j * 16u >= nb) continue; float m = 0.0f; #pragma unroll @@ -859,9 +624,8 @@ void gemm_fp8a8_kernel( v[j][t] = bf16_to_f32(h); m = fmaxf(m, fabsf(v[j][t])); } - // A wave's 16 output columns for one token live in lanes `c` and `c ^ 16`; the - // group's other 112 columns are the other MW/2 - 1 waves, and fmaxf is exact and - // order-free, so this reduction is the wave one `quant_group` does, regrouped. + // A wave's 16 output columns for one token are in lanes `c` and `c ^ 16`; the other + // 112 columns of the group are in the other waves. fmaxf is exact and order-free. m = fmaxf(m, r4d_xor_lane<16>(m)); if (lane < 16u) s_amx[w2][j * 16u + lane] = m; } @@ -880,9 +644,8 @@ void gemm_fp8a8_kernel( const float sc = mm > 0.0f ? mm * (1.0f / 448.0f) : 1.0f; if (w2 == 0u && (lane >> 4) == 0u) Sc[(size_t)tok * s_ld + blockIdx.x] = sc; const float inv = 1.0f / sc; - // The clamp is r4d_quant_act_fp8.hip's and it is not belt and braces: the builtin - // answers an out-of-range input with a NaN rather than saturating, and - // `amax * (1/scale)` is 448 in exact arithmetic but can land an ulp above it. + // The clamp is required (see r4d_q8.h): the builtin returns NaN out of range, and + // `amax * (1/scale)` can land an ulp above 448. float qc[8]; #pragma unroll for (uint32_t t = 0; t < 8; ++t) @@ -895,13 +658,13 @@ void gemm_fp8a8_kernel( pk[d] = __builtin_amdgcn_cvt_pk_fp8_f32(qc[d * 4 + 2], qc[d * 4 + 3], pk[d], true); } - // Eight consecutive columns, so one 8-byte store where the standalone quantiser - // manages a dword. `q_ld` is a multiple of 128 and col0 of 8, so it is aligned. + // Eight consecutive columns: one 8-byte store, aligned since `q_ld` is a multiple of + // 128 and col0 of 8. *(uint2*)(Q + (size_t)tok * q_ld + col0) = make_uint2((uint32_t)pk[0], (uint32_t)pk[1]); if (Yb) { - /* Packed in whole registers (bf16x2_rne, f32_to_bf16's bits): written through - * a uint16_t[8], LLVM 24 assembles the pairs from register halves. */ + /* Packed in whole registers (bf16x2_rne, f32_to_bf16's bits); a uint16_t[8] + * would be assembled from register halves. */ uint16_t* const yr = Yb + (size_t)tok * y_ld + col0; *(uint4*)yr = make_uint4(bf16x2_rne(v[j][0], v[j][1]), bf16x2_rne(v[j][2], v[j][3]), bf16x2_rne(v[j][4], v[j][5]), bf16x2_rne(v[j][6], v[j][7])); @@ -917,35 +680,16 @@ void gemm_fp8a8_kernel( uint16_t* const c16 = (uint16_t*)Y; const uint32_t c = frag_c(lane); - /* ---- THE STORE IS EIGHT CONSECUTIVE ELEMENTS AND ONE INSTRUCTION --------------------------- + /* ---- eight consecutive elements in one store --------------------------------------------- * - * `acc_row(lane, t)` is `(lane>>4)*8 + t`, so a lane's eight accumulator slots are eight - * CONSECUTIVE output columns; with AW the output index is `col * rows + r`, which makes them - * eight consecutive addresses. Writing them one at a time is a 2-byte store instruction each, - * and the eight of them land in ONE 16-byte piece of one line -- so the wave issues eight - * requests where one would do, and the neighbouring lanes it shares a line with are `rows` - * elements away and cannot help it. - * - * WHAT THAT COSTS, AND HOW TO SEE IT. Fix N and sweep K: the SLOPE is 610 GB/s at M = 8 and at - * M = 64 alike, and the whole M penalty is in the INTERCEPT -- at N = 8192 the M = 8 to M = 64 - * difference is the same ~10 us at K = 512 as at K = 8192. A cost that does not move with K is - * not bandwidth and not a re-read; it is the epilogue, whose only M-proportional work is this. - * - * The GATED epilogue above already writes its eight as one `uint2` (fp8) or one `uint4` - * (bf16). This is the same store, and it is the same bytes at the same addresses: bit-identical - * by construction. - * - * Two things gate it. It needs AW -- with B as the weight the index is `r * nb + col` and the - * eight are `nb` apart, not adjacent. And it needs the eight to be 16-byte aligned, which they - * are exactly when `rows` is a multiple of 8: `r` is already one (m0, wm, i*16 and - * `(lane>>4)*8` all are), so `col * rows + r` is too. */ + * `acc_row(lane, t)` is `(lane>>4)*8 + t`, so with AW (output index `col * rows + r`) a lane's + * eight slots are eight consecutive addresses in one 16-byte piece; one store instead of eight + * removes the epilogue's M-proportional cost. Bit-identical. Requires AW (otherwise the eight + * are `nb` apart) and `rows` % 8 == 0 for 16-byte alignment (`r` is already a multiple of 8). */ const bool vec8 = AW && (rows & 7u) == 0u; - /* THE SPLIT-K AND VEC8 TESTS ARE TAKEN ONCE, outside the store loop. Inside it, gfx12's - * compiler keeps a scalar compare and branch on each at every one of the tile's stores -- 64 - * of each at NT 8 -- where LLVM 22 unswitched the loop; and with the per-element fallback in - * the same body it rounds both paths' values to 16-bit halves once, so the vec8 words are - * assembled from register halves instead of one byte permute a pair. The same stores either - * way. */ + /* The split-K and vec8 tests are hoisted out of the store loop as template arguments; + * otherwise the compiler keeps a compare and branch at every store and assembles the vec8 + * words from register halves. */ auto store = [&](auto split, auto v8) { constexpr bool CK = decltype(split)::value; constexpr bool V8 = decltype(v8)::value; @@ -966,9 +710,8 @@ void gemm_fp8a8_kernel( *(uint4*)(part + o) = *(const uint4*)pv; *(uint4*)(part + o + 4) = *(const uint4*)(pv + 4); } else { - /* Packed in whole registers (bf16x2_rne, f32_to_bf16's bits): written - * through a uint16_t[8], LLVM 24 assembles the pairs from register halves - * where LLVM 22 used one byte permute a pair. */ + /* Packed in whole registers (bf16x2_rne, f32_to_bf16's bits); a + * uint16_t[8] would be assembled from register halves. */ const f8v& ov = out[i][j]; *(uint4*)(c16 + o) = make_uint4(bf16x2_rne(ov[0], ov[1]), bf16x2_rne(ov[2], ov[3]), bf16x2_rne(ov[4], ov[5]), bf16x2_rne(ov[6], ov[7])); @@ -979,8 +722,7 @@ void gemm_fp8a8_kernel( for (uint32_t t = 0; t < 8; ++t) { const uint32_t r = rb + acc_row(lane, t); if (!Full && r >= rows) continue; - // AW: A held the weight, so [r][col] is [N][M] and C is [M][N]. See the AW - // comment. + // AW: A held the weight, so [r][col] is [N][M] and C is [M][N]. const size_t o = AW ? (size_t)col * rows + r : (size_t)r * nb + col; if constexpr (CK) part[o] = out[i][j][t]; else c16[o] = f32_to_bf16(out[i][j][t]); @@ -995,30 +737,20 @@ void gemm_fp8a8_kernel( else store(std::false_type{}, std::false_type{}); } - // ---- THE SPLIT'S FINISHER, WHICH IS WHY THERE IS USUALLY NO SECOND LAUNCH ------------------ + // ---- split finisher --------------------------------------------------------------------------- // - // Back-to-back DEPENDENT dispatches on this part cost 2.8 us of nothing between them, even for - // an empty kernel, and a hipGraph takes that to 2.3 -- so it is the command processor and not - // the host, and the only lever on it is launching fewer kernels. A decode step issues ~1600, - // and a separate reduce for this GEMM would be 272 of them: 1.2 ms of a 41 ms step to sum two - // f32 planes of at most 2048 elements a block. + // Dependent dispatches cost ~2.8 us each on this part (2.3 in a hipGraph), so a separate reduce + // launch per split GEMM is expensive. Instead the last z block of a column reduces it: + // `ctr[blockIdx.x]` counts arrivals, and the block that reaches gridDim.z resets it and sums. + // The z loop runs in fixed ascending order with no atomic on an accumulator, so the result is + // bit-identical to the separate reduce and deterministic. // - // So the LAST z block of a column reduces that column itself. `ctr[blockIdx.x]` counts the - // arrivals; the block that takes it to gridDim.z resets it to zero for the next launch and does - // the sum. That keeps the property the separate kernel had and the reason it exists: the z loop - // is in a FIXED ascending order and no atomic touches an accumulator, so the answer is - // bit-identical to the unfused one and to itself from run to run. - // - // The counter lives in a small per-device, PER-STREAM allocation this file owns, NOT in the - // caller's scratch, because the scratch is one shared arena region and any other op's kernel - // would write over it between our launches. The self-reset is what keeps it zeroed; it is - // sound only because two launches of this kernel never overlap -- they are ordered by the same - // stream. A caller that runs two concurrently on ONE DEVICE needs a counter block each, and - // `rad_lane` is exactly such a caller, so `split_ctr` is keyed on the stream: two launches on - // one stream cannot overlap and two streams cannot collide. + // The counters are a small allocation keyed on (stream, output) (`split_ctr`), not the caller's + // scratch, which other ops overwrite. The self-reset keeps them zero, which is sound only while + // launches sharing a counter block never overlap; see split_ctr. if (ck && Ctr) { - // Every store above must be visible device-wide BEFORE the arrival is published, and to - // every thread of the block, so the fence is per-thread and the barrier follows it. + // Every thread's stores must be visible device-wide before the arrival is published: a + // per-thread fence, then the barrier. __threadfence(); __syncthreads(); __shared__ unsigned int s_arrived; @@ -1031,9 +763,8 @@ void gemm_fp8a8_kernel( __hip_atomic_store(&Ctr[blockIdx.x], 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); __threadfence(); // acquire the other slices' partials - // This block owns A rows [m0, m0+FM) and every one of the nb output columns; with - // AW the output index is col * rows + r, so the two loops are over exactly what the - // stores above wrote and nothing else. + // This block owns A rows [m0, m0+FM) and all nb output columns, exactly what the stores + // above wrote. const uint32_t rlo = m0, rhi = min(m0 + FM, rows); const float* const w0 = (const float*)Y; uint16_t* const cy = (uint16_t*)C; @@ -1048,11 +779,8 @@ void gemm_fp8a8_kernel( } } -// Sum the split-K partials into bf16 C. The z loop is in a FIXED order and there is no atomic -// anywhere. It is LATENCY bound, not bandwidth bound, which is why the loads are batched: written -// as one `acc +=` per iteration the adds are a dependent chain and each load sits behind the -// previous add, so the few blocks this grid has issue one small round of requests and wait. -// Batching eight loads before the adds breaks the chain without touching the ORDER of the adds. +// Sum the split-K partials into bf16 C, in fixed z order with no atomics. Latency bound, so eight +// loads are issued before their adds; the order of the adds is unchanged. __global__ void splitk_reduce_kernel(const float* __restrict__ ws, uint16_t* __restrict__ y, uint32_t n_out, uint32_t ksplit) { const size_t i = (size_t)blockIdx.x * blockDim.x + threadIdx.x; @@ -1073,56 +801,23 @@ __global__ void splitk_reduce_kernel(const float* __restrict__ ws, uint16_t* __r y[i] = f32_to_bf16(acc); } -// A SWEEP HOOK and not a deployment knob. Both fp8a8 rows are NOVAR -- there is no variant list -// for rad-tune to search -- and what wants sweeping here is a LAUNCH heuristic, which is reachable -// only from inside this file. `R4D_F8_MW` pins the wave count and `R4D_F8_SPLITTGT` the split's -// block target, so `r4d_selftest --perf N K M` can compare the rules below without a rebuild, and -// so a pin can be applied to a SERVING engine and compared at a real step time on one build. -// `R4D_F8_MWLOG` prints the distinct (N, M) the narrow GEMM is asked for, which is what says WHICH -// shapes to measure: guessing them from the model dimensions is wrong by a factor of two here, -// because n_ff in a container is already per rank. Read once. Unset is the default rule, and the -// default rule is what a serve runs: nothing here reads the environment on a path that matters. -uint32_t env_u32(const char* k) { - const char* v = std::getenv(k); - return v ? (uint32_t)std::strtoul(v, nullptr, 10) : 0u; -} +// The narrow tile's K width is kFKNarrow (256 B); 128 B loses at every wave count (see `kTPR`), and +// is used only via narrow_fk for a K that 256 does not divide. +// Double-buffering the narrow tile is ~10% slower even where it fits (MW = 2): the tile is short +// of LDS, not waiting on the barrier. - -// The staged tile's width in K is kFKNarrow and 256 B -- one whole cacheline a row -- is the value. -// A 128-byte tile loses everywhere, and by a lot, at every wave count. It halves the LDS a block -// holds, which is not what this kernel is short of; what it also halves is the threads that cover -// one row, and the staging table at `kTPR` says four threads a row is where the fetch starts giving -// bandwidth back. (128 is still reachable through narrow_fk for a K that 256 does not divide.) - - -// TWO BUFFERS ON THIS TILE ARE WORSE, although the prefill tile above gains 5% from double -// buffering and it is natural to assume the narrow tile skips it only because MW = 8's pair does -// not fit in 64 KiB. It fits at MW = 2 -- 25 KiB -- and it -// costs about 10% at both a narrow and a very wide N. The barrier it removes is not what this tile -// waits on; the LDS it spends is what the tile is short of. - -// The finisher's arrival counters, one per grid.x column. See the finisher in the kernel for why -// they are here and not in the caller's scratch: the scratch is a shared arena region and any -// other op would write over them between two of our launches. -// -// Zeroed once, and kept zero by the finisher resetting its own counter. That invariant holds only -// while two launches sharing a counter block never run at once. Failure to allocate is not an -// error: the caller falls back to the separate reduce kernel, which computes the same bytes. +// The finisher's arrival counters, one per grid.x column (see the finisher). Zeroed once and kept +// zero by the finisher. If allocation fails, the caller falls back to the separate reduce kernel, +// which computes the same bytes. constexpr uint32_t kMaxCtr = 8192; -/* ONE COUNTER BLOCK A (STREAM, OUTPUT), which is what lets two of these GEMMs run at once. - * - * Two launches overlap in two ways: on two streams -- `rad_lane` runs a dense GEMM on lane 1 - * beside the routed experts on lane 0 -- and on ONE stream, when the engine starts a launch before - * the independent ones in front of it have finished (rad_kernel_concurrent). Two launches sharing - * a block would each see the other's arrivals: a hang or a wrong answer, whichever came first. - * - * Launches that overlap on one stream write disjoint outputs -- that is what made them - * independent -- and launches on two streams are told apart by the stream, so the pair names a - * block no concurrent launch shares. Launches that do share an output on one stream are ordered by - * the dependency between them, and reuse the block safely. A step writes a few dozen distinct - * outputs, so the blocks are a few dozen times 32 KiB, taken once. */ +/* One counter block per (stream, output), so concurrent launches never share one (sharing would + * mean a hang or a wrong answer). Launches overlap across streams (`rad_lane`) or on one stream + * (rad_kernel_concurrent); overlapping launches on one stream write disjoint outputs, and launches + * sharing an output on one stream are ordered by their dependency. A step has a few dozen distinct + * outputs at fixed arena addresses, so this is a few dozen 32 KiB blocks, allocated once. A block + * is never freed: a recorded pass replays the pointer. */ unsigned int* split_ctr(RadStream s, const void* out) { static std::mutex m; static std::map, unsigned int*> blocks; @@ -1138,138 +833,46 @@ unsigned int* split_ctr(RadStream s, const void* out) { blocks.emplace(key, (unsigned int*)p); return (unsigned int*)p; } -// The M tile for the narrow instantiation. MW is the wave count and it IS the tile: the wave grid -// is MW(M) x 1, so a block covers MW*16 rows of the weight and the grid over N is N/(MW*16). The -// rule is NOT monotone, so "throughput is a clean monotone function of the block count, so lower -// MW is free" is wrong past 8192 rows. +// The narrow tile's wave count MW, which is its M tile: the wave grid is MW x 1, so a block covers +// MW*16 weight rows and the grid over N is N/(MW*16). The rule is fitted together with +// kSplitTarget (which shapes split decides whether narrow or wide blocks win) on the shapes the +// engine actually issues (R4D_F8_MWLOG; n_ff is already per rank). // -// IT ALSO DEPENDS ON kSplitTarget, which is why the two are fitted together: which shapes split, -// and how many ways, is what decides whether a narrow block or a wide one wins, so changing the -// split target invalidates the MW rule. At the current target, and across this model's own decode -// geometries at M <= 16, MW = 4 is best or within a microsecond of best at every -// point -- where a rule that answers 2 at 17408 rows takes the WORST of 2/4/8 there, and one that -// answers 8 at 512 rows costs a couple of microseconds on a call the model makes fifty times a -// step. MW = 8 also degrades as M grows through that band while MW = 4 is flat. +// - M <= 16: MW = 4, best or within a microsecond on every decode shape. +// - M > 16: MW = 8. The weight is streamed once whatever MW is, but every block stages the whole +// [M, K] activation, so a call moves N*K + M*K*N/(MW*16) bytes; the second term matches the +// weight at M = 64 (served from cache, but it is the drop from 586 to 460 GB/s on gate_up). +// MW = 8 halves it at the same N/16 waves. The crossover is where NT leaves 1. +// - M > 32 and N >= 2048: MW = 16 (FM = 256, legal because the AW fold reads the weight scale +// per wave). Halves the re-read again; narrower N would leave too few blocks for 32 WGPs. // -// ---- ...AND PAST 16 ROWS IT IS THE OTHER NUMBER, BECAUSE THE ACTIVATION IS RE-READ PER BLOCK ---- +// Token tiles NT = ceil(M/16), including 3: rounding 33..48 up to a 64-token tile would spend +// three-eighths of the work at M = 40 on padding. NT = 3 (FN = 48) is legal only here, where AW = +// true; the prefill tile requires FN to divide 128. // -// The weight is the A operand and a lane takes its fragment from global, so the weight is streamed -// exactly once whatever MW is. THE ACTIVATION IS NOT: it is the B operand, every block stages the -// whole [M, K] of it into LDS, and there are `N / (MW * 16)` blocks. So the bytes a call moves are +// Neither MW nor NT changes the output bits: `narrow_ksplit` depends on `gx * mw` = N/16 (the rule +// requires `n % 128` so that holds), so every element is one wave's accumulation over the same K +// tiles in the same order. The selftest checks this with the pin_mw / pin_nt hooks. // -// weight N * K + activation M * K * N / (MW * 16) -// -// and the second term is nothing at M = 8 -- 13% of the first at MW = 4 -- and is THE SAME SIZE AS -// THE WEIGHT at M = 64. It is served out of the last level of cache rather than HBM, which is why -// the kernel does not simply halve, but it is the whole of the fall from 586 GB/s at M = 8 to 460 -// at M = 64 on gate_up. MW = 8 halves the block count and therefore halves that term, at no cost -// in parallelism: MW * (N / (MW * 16)) waves is N/16 either way. -// -// THE SHAPES THIS IS FITTED ON ARE THE ONES THE ENGINE ASKS FOR, read off `R4D_F8_MWLOG=1` on a -// running server and not derived from the model's dimensions: `n_ff` in a container is ALREADY -// per rank, so gate_up is N = 17408 on each card and not 8704, and a sweep of the model dims halved -// measures a model that does not exist. The set is gate_up, down, gdn in_qkv|z, the out -// projections, attn q|gate, the drafter's q, and k/v. -// -// Across it, MW = 8 beats MW = 4 at every shape from M = 24 up, by 5-20% at the wide end, and the -// crossover is exactly where NT stops being 1 -- which is not a coincidence, since NT is how many -// 16-token tiles the staged activation holds and so is the multiplier on the term above. Two shapes -// go the other way just past the threshold and both lose to the rest of the set. -// -// A CAUTION ON MEASURING THIS PART: it throws occasional +5 us outliers, and they are NOT -// independent between repetitions, so three reps can leave a whole cell polluted and invent a shape -// that wants the other wave count. A cell that breaks the monotonicity of its own row is a -// re-measurement, not a discovery. -// -// ---- ...AND PAST 32 ROWS IT IS SIXTEEN, ON EVERY SHAPE WIDE ENOUGH TO STILL FILL THE CARD ------ -// -// Reading the weight's scale ONCE A BLOCK at `m0 / kBlock` would cap MW at eight, FM = MW*16 having -// to fit in one 128-row scale row. A wave owns 16 rows and 16 divides 128, so the AW branch reads -// it at `(m0 + wm) / kBlock` -- per WAVE -- which is identical wherever the per-block index is -// legal and correct where it is not. That lifts FM to 256 and halves the activation re-read again: -// 272 blocks at MW = 4 over gate_up, 136 at 8, 68 at 16. -// -// It stops there, and for the other reason a block count matters. 68 workgroups over 32 WGPs is -// 2.1 each, which still tiles; 34 would be 1.06 and the tail would be the whole kernel. So the -// rule takes 16 only where N is wide enough to keep the grid full, and the measurements say the -// same thing from the other side: 512 rows is four blocks at MW = 16 and loses everywhere, while -// the wide shapes lose to MW = 8 below 48 rows and win above it. Hence `m > 32 && n >= 2048`, and -// `n % 256` for the same ksplit invariant as above. In a served step that is worth a couple of -// percent at eight concurrent sequences and nothing at four -- four is M = 32, the wrong side of -// the threshold. -// -// ---- ...AND THE TOKEN-TILE COUNT HAS NO HOLE AT THREE ------------------------------------------ -// -// Jumping NT 2 -> 4 at M = 32 would make the whole 33..48 band run a 64-token tile: at M = 40 that -// is three-eighths of the staged activation, the accumulator registers and the WMMA spent on rows -// that do not exist. M = 8*C with a depth-7 drafter, so the band is exactly five and six -// concurrent sequences. With a 64-token tile there, each added concurrent sequence costs 1.2-1.9 ms -// of step time everywhere except the one that crosses M = 32, which costs 3.3. -// -// NT = 3 IS LEGAL HERE AND ILLEGAL IN THE PREFILL TILE, which is why only this dispatch has it: -// `static_assert(AW || kBlock % FN == 0)` makes FN divide 128, and 48 does not. That assert guards -// the AW = false fold, which treats a block's weight scale as ONE SCALAR and so needs the block to -// sit inside one 128-row scale row. This dispatch is AW = true -- the scale is read per wave, the -// same change that lifted MW to 16 above -- so FN = 48 binds nothing. -// -// In isolation NT = 3 wins on every shape the engine issues, at every M in the band, and the MW -// rule holds under it: at M = 40/48/56 sixteen waves still beats eight on every shape wide enough -// for the rule to ask. -// -// In the engine it is worth most of a millisecond a step at the two concurrencies that land in the -// band. `R4D_F8_NT=4` prices the mechanism directly: forcing a 64-token tile onto M = 32 costs -// about a millisecond of step, so ONE dead token tile is the size of the effect. -// -// M = 56 IS ALREADY MINIMAL. ceil(56/16) is 4, so seven concurrent sequences have no smaller tile -// to take and their 12% of padding is not addressable by this rule. -// -// The bits do not move, and the selftest checks it the way it checks the wave count: a `pin_nt` -// hook and a sweep over every NT that covers M, memcmp'd against the rule's own output, at -// M = 1, 8, 24, 32, 40, 48 and 64. -// THE SPLIT IS UNCHANGED BY THIS AND SO ARE THE OUTPUT BITS. `narrow_ksplit` decides from -// `gx * mw`, which is N/16 whatever MW is -- but only when N divides MW*16, so the rule asks for -// `n % 128` rather than trusting it. With the same ksplit every output element is still one wave's -// accumulation over the same K tiles in the same order; MW moves which wave, not what it adds. -/* The test hook behind r4d_gemm_fp8a8_pin_mw. Zero is the rule; anything else overrides it for - * every call until it is put back. It is separate from the environment pin because the environment - * is read once a process and the bit check has to run BOTH settings inside one. */ +// This part shows occasional correlated +5 us outliers across repetitions; a cell that breaks its +// row's monotonicity needs re-measuring. +/* Test hook behind r4d_gemm_fp8a8_pin_mw: zero is the rule, anything else overrides every call. + * Separate from the environment pin, which is read once per process, so a bit check can compare + * both settings in one process. */ std::atomic g_mw_force{0u}; uint32_t narrow_mw(uint32_t n, uint32_t m) { - static const uint32_t pin = env_u32("R4D_F8_MW"); uint32_t mw = 4u; if (m > 16u && (n % 128u) == 0u) mw = 8u; if (m > 32u && n >= 2048u && (n % 256u) == 0u) mw = 16u; - /* 10 and 12 are here for the BLOCK-COUNT question and not for the wave count: the narrow grid - * is ceil(N / (16*MW)) blocks over 32 WGPs, so at N = 5120 sixteen waves is twenty blocks and - * five-eighths of the card, while ten waves is thirty-two blocks and all of it. They are pins - * only; `narrow_mw`'s rule never returns them. */ - /* THE NARROW BAND'S BLOCK COUNT IS NOT A LEVER, IN EITHER DIRECTION. - * - * The split's test is `gx * mw >= kSplitTarget`, and gx * mw is N/16 whatever MW is -- a WAVE - * count. So below N = 2048 the split multiplies the grid and at N >= 4096 the grid is already - * 64 blocks or more, but BETWEEN them it does neither: N = 2560 at MW 4 is forty blocks over - * 32 WGPs, 1.25 each, which reads like a second scheduling round at a quarter occupancy. It - * is the only shape this model asks for that lands there -- R4D_F8_MWLOG says the decode band - * is N = 256, 640, 1280, 2560, 6144 and 8192, and only 2560 has both no split and under 64 - * blocks -- and it is a few percent of traced device time. - * - * Halving MW deals the same 160 waves into 80 blocks instead of 40, and doubling it into 20, - * and BOTH are slower at the decode shape, with the text unchanged either way. - * - * The asymmetry is the explanation: finer costs about three times what coarser does, so what - * is being paid is PER-BLOCK work -- the activation re-read, the scale plane, the prologue -- - * and not scheduling balance. 160 waves is 160 waves; how they are grouped is not the lever, - * because with 4608 bytes of LDS and 112 VGPRs a WGP already holds many blocks at once and - * there is no "round" to be half-empty. */ - if (pin == 1u || pin == 2u || pin == 4u || pin == 8u || pin == 10u || pin == 12u || - pin == 16u) mw = pin; + /* Regrouping the same waves into more or fewer blocks (e.g. N = 2560: 40 blocks at MW 4) is + * slower both ways: the cost is per-block work (activation re-read, scale plane, prologue), not + * scheduling balance. */ if (const uint32_t f = g_mw_force.load(std::memory_order_relaxed)) mw = f; - /* `R4D_F8_MWLOG` prints each DISTINCT (N, M) this rule is asked about, once, to at most 64 of - * them. Shapes derived from the model's dimensions are not the shapes the engine asks for -- - * n_ff in a container is already per rank -- and a sweep of shapes that do not exist measures - * nothing. */ - static const uint32_t mwlog = env_u32("R4D_F8_MWLOG"); + /* `R4D_F8_MWLOG` prints each distinct (N, M) once, up to 64 (n_ff in a container is already + * per rank, so the shapes must be read, not derived). */ + static const bool mwlog = [] { const char* v = std::getenv("R4D_F8_MWLOG"); + return v && std::strtoul(v, nullptr, 10) != 0; }(); if (mwlog) { static std::mutex lm; static uint64_t seen[64]; @@ -1286,55 +889,31 @@ uint32_t narrow_mw(uint32_t n, uint32_t m) { return mw; } -// SPLITTING N = 2560 IS FREE AND BUYS NOTHING, so the target is 128. -// -// At the decode band this model asks for N = 256, 640, 1280, 2560, 6144 and 8192 (R4D_F8_MWLOG). -// Of those, 2560 is the one the split declines while still being under 64 blocks: gx * mw is N/16 -// = 160, over the 128 target, so it runs 40 blocks of 4 waves. It is second only to the 8192 row -// in traced device time, and 160 waves against 8192's 512 reads like the shape that is short of -// parallelism. -// -// R4D_F8_SPLITTGT=256 makes it split, and the kernel does not move: twice the waves, the same time -// per dispatch. So this shape is not parallelism-starved and the target is not leaving anything on -// the table -- the same answer the MW rule gives from the other direction: at the narrow band the -// grid of this kernel is settled. -// -// READ grid.z, NOT grid.x. The split lives in the Z dimension: a fired split leaves gx at 40 and -// only Z moves, so a per-grid table that divides Grid_Size_X alone reports "40 blocks" either way -// and shows the split as never having fired. -// -// The split, given the narrow grid. Factored out so the sizing query and the launch cannot disagree -// about how many planes the scratch holds -- a disagreement there is a read past the end of a -// buffer the caller sized from the other one. -/* THE STAGED TILE'S WIDTH, and 256 is not always it. K = 640 -- the shared expert's down - * projection at n_ff_shared wide -- is a multiple of 128 and not of 256, and refusing it would send - * a DECODE call to r4d_gemm_fp8a8_tiled: a kernel whose own header says it is for prefill, - * computing 128 M rows for the four that are live at 190 GB/s. - * - * FK is a template parameter and the tiled instantiation already runs it at 64, so 128 is between - * two widths that both work rather than a new regime. It also lands on the SIMPLER half of the - * scale fold -- the loop's `FK <= kBlock` branch, where only a tile's last step can fire. - * - * ONE FUNCTION, because the scratch query and the launch both need this answer: if they drift, - * the query answers 0, the launch forces ksplit to 1, and nothing reports it. */ +// Raising the split target so N = 2560 (160 waves, 40 blocks) splits does not change its time, so +// the narrow grid is not parallelism-starved at 128. A split shows in grid.z, not grid.x. + +/* The narrow tile's K width: 256, or 128 when K is a multiple of 128 but not 256 (e.g. K = 640, a + * shared expert's down projection), which would otherwise fall to the prefill kernel. At 128 the + * fold takes the `FK <= kBlock` branch. One function, because the scratch query and the launch + * must agree. */ inline uint32_t narrow_fk(uint32_t K) { return (K % kFKNarrow == 0u) ? kFKNarrow : 128u; } +// The split, given the narrow grid. Shared by the scratch query and the launch so they agree on the +// number of partial planes. uint32_t narrow_ksplit(uint32_t N, uint32_t K, uint32_t M, uint32_t* ck_out) { *ck_out = 0; const uint32_t mw = narrow_mw(N, M); const uint32_t fm = mw * 16u; // the narrow tile is one M tile a wave const uint32_t gx = (N + fm - 1) / fm; // the M grid runs over N here: AW = true - const uint32_t tgt = env_u32("R4D_F8_SPLITTGT") ? env_u32("R4D_F8_SPLITTGT") : kSplitTarget; - if (K < 512u || gx * mw >= tgt) return 1; - const uint32_t want = (tgt + gx * mw - 1) / (gx * mw); + if (K < 512u || gx * mw >= kSplitTarget) return 1; + const uint32_t want = (kSplitTarget + gx * mw - 1) / (gx * mw); uint32_t ckw = ((K / want) + kBlock - 1u) / kBlock * kBlock; if (ckw < kBlock) ckw = kBlock; uint32_t k2 = (K + ckw - 1) / ckw; if (k2 > kSplitThinCap && (uint64_t)N * M < 8192) k2 = kSplitThinCap; if (k2 < 2) return 1; - // Rounded to the STAGED TILE, not to the 128-column scale block: a narrow tile is 256 wide, so a - // slice whose length is only a multiple of 128 runs one tile past its own end and accumulates - // the next slice's columns as well -- a wrong answer that still decodes fluently. + // Round the slice to the staged tile, not the 128-column scale block: a slice that is only a + // multiple of 128 would run one 256-wide tile past its end into the next slice. const uint32_t fk = narrow_fk(K); uint32_t ck = ((K + k2 - 1) / k2 + fk - 1u) / fk * fk; @@ -1351,31 +930,27 @@ uint32_t narrow_ksplit(uint32_t N, uint32_t K, uint32_t M, uint32_t* ck_out) { extern "C" int r4d_gemm_fp8a8_block(void) { return (int)kBlock; } static int gemm_fp8a8_nt_m16_emit(long a, long ascale, long wq, long ws, long c, int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld, - long scratch, long scratch_bytes, const R4dSink& sk, + long scratch, long scratch_bytes, RadStream stream, bool i8 = false); extern "C" int r4d_gemm_fp8a8_nt_m16(long a, long ascale, long wq, long ws, long c, int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld, long scratch, long scratch_bytes, long stream) { - R4dSink sk; sk.stream = (RadStream)(uintptr_t)stream; return gemm_fp8a8_nt_m16_emit(a, ascale, wq, ws, c, M, K, N, a_ld, sa_ld, w_ld, sw_ld, - scratch, scratch_bytes, sk); + scratch, scratch_bytes, (RadStream)(uintptr_t)stream); } extern "C" int r4d_gemm_fp8a8_nt_m16_max_m(void) { return 64; } -/* r4d.h says what this is for and why the environment pin cannot do the job. An mw the dispatch - * does not instantiate would fall through to its last arm, so only the four it has are taken and - * anything else clears the override rather than silently meaning 16. */ +/* See r4d.h. Only instantiated wave counts are accepted; anything else clears the override rather + * than falling through to the dispatch's last arm. */ extern "C" void r4d_gemm_fp8a8_pin_mw(int mw) { const uint32_t v = (mw == 1 || mw == 2 || mw == 4 || mw == 8 || mw == 16) ? (uint32_t)mw : 0u; g_mw_force.store(v, std::memory_order_relaxed); } -/* The same hook for the TOKEN-TILE count, and it needs one more guard than the wave count does. - * `nt` may be pinned UP but never down: NT*16 is how many token columns the epilogue is allowed to - * write, so a pin below ceil(M/16) does not run a slower variant, it drops rows. Both dispatches - * read it, and both apply the same ceiling. */ +/* The same hook for the token-tile count. `nt` may be pinned up but never below ceil(M/16): NT*16 + * is how many token columns the epilogue writes, so a lower pin would drop rows. */ std::atomic g_nt_force{0u}; extern "C" void r4d_gemm_fp8a8_pin_nt(int nt) { @@ -1384,14 +959,8 @@ extern "C" void r4d_gemm_fp8a8_pin_nt(int nt) { } // Bytes of f32 scratch one r4d_gemm_fp8a8_nt_m16 call needs, or 0 when it will not split. The -// caller may always pass more, and may pass none -- the launch then runs unsplit, which is correct -// and slow rather than wrong. -// -// THE BOUND IS max_m(), NOT A LITERAL, so the query and the band cannot drift apart. A query that -// refuses rows the band admits answers 0, and every such M is handed no scratch and runs with -// ksplit forced to 1. The launch below reports nothing when that happens; it is the -// correctness-preserving silent slowdown the plugin's hook warns about, arriving through the one -// door the hook does not guard. +// caller may pass more, or none (the launch then runs unsplit: correct but slow, and unreported). +// The bound is max_m() so the query and the band cannot drift apart. extern "C" long r4d_gemm_fp8a8_nt_m16_scratch(int M, int K, int N) { if (M <= 0 || K <= 0 || N <= 0 || M > r4d_gemm_fp8a8_nt_m16_max_m()) return 0; uint32_t ck = 0; @@ -1408,38 +977,17 @@ extern "C" long r4d_gemm_fp8a8_nt_m16_scratch(int M, int K, int N) { // c [M][N] bf16 // // Returns 0, or a negative code for a shape it does not serve. `scratch` may be 0. -/* The body takes a sink, so one set of geometry serves both the launch and the description. - * `r4d.h`'s long-stream entry is libr4d's driver API and keeps its signature exactly. */ static int gemm_fp8a8_nt_m16_emit(long a, long ascale, long wq, long ws, long c, int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld, - long scratch, long scratch_bytes, const R4dSink& sk, bool i8) { + long scratch, long scratch_bytes, RadStream stream, bool i8) { int emit_rc = RAD_OK; if (!a || !ascale || !wq || !ws || !c) return -1; if (M <= 0 || K <= 0 || N <= 0) return -2; - // THE STAGED TILE IS 256 BYTES WHERE IT CAN BE AND 128 WHERE IT CANNOT -- see narrow_fk. - // - // Refusing K % 256 outright costs one real shape, K = 640: the shared expert's down - // projection at n_ff_shared wide, a multiple of 128 and not of 256. That refusal sends a - // DECODE call to r4d_gemm_fp8a8_tiled, whose own header says it exists for prefill and - // is "hundreds of blocks at any prefill shape". At M = 4 that kernel computes FM = 128 rows for - // four live ones on a (1, 20) grid: about 190 GB/s where the part does 621, on thousands of - // dispatches a run, ALL on one agent -- because the shared arm runs on rank 0 alone, the rank - // the all-reduce is already waiting for. - // - // 128 IS NOT A NEW REGIME. FK is a template parameter and the tiled instantiation runs it at - // 64, so this sits between two widths that already work, and it lands on the loop's - // `FK <= kBlock` branch where only a tile's last step of the scale fold can fire. The split's - // `ck` follows the same width through narrow_fk, so the slice cannot overrun its own end. - // - // So the tiled family does not appear in a decode trace at all, and the same work costs less - // here: a fraction of a millisecond a step off the slower rank, and the text is unchanged. - // - // RELAXING THE RUNTIME GUARD ALONE DOES NOTHING: the DECLARED constraint has to move with it - // -- see cGemmNtFp8A8M16 in r4d_rows.cpp. The resolver offers a call by what a row claims, not - // by what its entry point will accept. + // K must be a multiple of 128; the staged tile is 256 bytes where K allows and 128 otherwise + // (narrow_fk). The declared constraint must match this guard (cGemmNtFp8A8M16 in r4d_rows.cpp): + // the resolver offers a call by what a row claims, not by what the entry point accepts. if (K % 128) return -4; - // A wave owns 16 rows of the weight and the transposing store writes `N`-strided columns, so a - // ragged N would make the output pitch differ from the logical one. + // A wave owns 16 weight rows and the transposing store writes `N`-strided columns. if (N % 16) return -5; if (!a_ld) a_ld = K; if (!w_ld) w_ld = K; @@ -1458,172 +1006,86 @@ static int gemm_fp8a8_nt_m16_emit(long a, long ascale, long wq, long ws, long c, const dim3 grid(gx, 1, ksplit); void* const dst = ksplit > 1 ? (void*)scratch : (void*)c; - /* TOKEN TILES A WAVE. The activation is the B operand here, so NT of them cover NT*16 tokens - * and the weight is read ONCE for all of them -- the same trade the lm head makes. */ - /* THREE IS A TILE COUNT THE BAND ACTUALLY ASKS FOR. The cost of this kernel is NT and not M -- - * NT decides the staged activation, the accumulator registers and the WMMA issued, and every - * row past M is padding that costs all three. Jumping 2 -> 4 at M = 32 would make the whole - * 33..48 band pay the 64-row price: in a steady-state step, going from four to five concurrent - * sequences would cost 3.33 ms where every other added sequence costs 1.2-1.9. M = 8*C with - * a depth-7 drafter, so 40 and 48 are five and six sequences -- see the token-tile note above - * narrow_mw. - * - * NT = 3 IS LEGAL HERE AND NOT IN THE PREFILL TILE. `static_assert(AW || kBlock % FN == 0)` - * is what makes FN divide 128, and it guards the AW = false fold that treats a block's weight - * scale as one scalar. This dispatch is AW = true -- the scale is read per wave -- so FN = 48 - * binds nothing. The gate stash is the other size constraint and it scales with NT on both - * sides (4096*NT bytes against FN * (256+8) = 4224*NT), so it holds unchanged. */ - static const uint32_t ntpin = env_u32("R4D_F8_NT"); + /* Token tiles per wave: the activation is the B operand, so NT tiles cover NT*16 tokens with + * one weight read. NT = ceil(M/16), including 3 (see the note above narrow_mw). The gate stash + * scales with NT on both sides (4096*NT bytes against FN * (256+8) = 4224*NT), so it fits. */ uint32_t nt = (M > 48) ? 4u : ((M > 32) ? 3u : ((M > 16) ? 2u : 1u)); - /* A pin that drops rows is not a slower variant, it is a wrong answer. */ - if (ntpin >= 1u && ntpin <= 4u && (uint32_t)M <= ntpin * 16u) nt = ntpin; if (const uint32_t f = g_nt_force.load(std::memory_order_relaxed)) { if ((uint32_t)M <= f * 16u) nt = f; } - /* `Full` DROPS THE COLUMN GUARD, so it has to mean "every one of the NT tiles is live" and not - * "M is a multiple of 16". At M = 48 with NT = 4 the second is true and the first is false, and - * the epilogue then writes columns 48..63 -- past the end of a split-K scratch sized for 48, - * over the arrival counter, and the finisher spins forever: a hang, not a wrong answer. */ + /* `Full` drops the column guard, so it must mean all NT tiles are live, not just M % 16 == 0. + * Otherwise (e.g. M = 48, NT = 4) the epilogue writes past a split-K scratch sized for M, over + * the arrival counter, and the finisher hangs. */ const bool full = ((uint32_t)N % fm == 0) && ((uint32_t)M % (nt * 16u) == 0) && (K % (int)kBlock == 0); - // The finisher needs one counter a column; past that, and if the allocation ever fails, the - // separate reduce kernel runs instead and computes the same bytes -- as it does under - // `R4D_F8_NOFUSE`, which is how the two are compared. + // The finisher needs one counter per column; beyond kMaxCtr or on allocation failure, the + // separate reduce kernel computes the same bytes. unsigned int* const ctr = - (ksplit > 1 && gx <= kMaxCtr && !env_u32("R4D_F8_NOFUSE")) ? split_ctr(sk.stream, (const void*)c) : nullptr; + (ksplit > 1 && gx <= kMaxCtr) ? split_ctr(stream, (const void*)c) : nullptr; -#define R4D_F8D_NT(f, mw_, nt_) \ - emit_rc = R4D_EMIT(sk, (gemm_fp8a8_kernel), grid, \ - dim3(mw_ * kWave), \ +#define R4D_F8D(f, mw_, nt_, fk_, i8_) \ + emit_rc = R4D_EMIT(stream, (gemm_fp8a8_kernel), \ + grid, dim3(mw_ * kWave), \ 0, (const uint8_t*)wq, (const void*)ws, \ (const uint8_t*)a, (const void*)ascale, dst, (void*)c, ctr, \ (uint32_t)N, (uint32_t)K, \ (uint32_t)M, (uint32_t)w_ld, (uint32_t)a_ld, (uint32_t)sw_ld, \ (uint32_t)sa_ld, ck, \ - /* THE KERNEL'S SIX DEFAULTED PARAMETERS, SPELLED. The chevron fills a \ - * default argument in at the call; kernelParams is an array and cannot, \ - * so a described launch would supply fifteen values for twenty-one slots \ - * and the kernel would read six arguments' worth of whatever followed. \ - * r4d_emit deduces the parameter list and static_asserts the arity, \ - * which is the only reason this is a build error and not a quantiser \ - * reading a garbage pointer. */ \ + /* The six defaulted parameters, spelled out: r4d_emit passes \ + * kernelParams as an array, which cannot fill defaults, and asserts the \ + * arity. */ \ (uint8_t*)nullptr, (float*)nullptr, (uint16_t*)nullptr, \ (uint32_t)0, (uint32_t)0, (uint32_t)0) -#define R4D_F8D(f, mw_) \ - do { if (nt == 4u) R4D_F8D_NT(f, mw_, 4u); \ - else if (nt == 3u) R4D_F8D_NT(f, mw_, 3u); \ - else if (nt == 2u) R4D_F8D_NT(f, mw_, 2u); \ - else R4D_F8D_NT(f, mw_, 1u); } while (0) -#define R4D_F8D_MW(f) \ - do { \ - if (mw == 1u) R4D_F8D(f, 1u); \ - else if (mw == 2u) R4D_F8D(f, 2u); \ - else if (mw == 4u) R4D_F8D(f, 4u); \ - else if (mw == 8u) R4D_F8D(f, 8u); \ - else if (mw == 10u) R4D_F8D(f, 10u); \ - else if (mw == 12u) R4D_F8D(f, 12u); \ - else R4D_F8D(f, 16u); \ - } while (0) -/* THE 128-WIDE SET IS DELIBERATELY NARROWER. Every extra (f, mw, nt) triple is another - * instantiation of a WMMA kernel, and mirroring the whole ladder would double this file's object - * for one shape. `narrow_mw`'s RULE only ever answers 4, 8 or 16 -- 1, 2, 10 and 12 are pins -- - * so those three cover every K % 256 call the engine can make, and a pinned mw at such a K falls - * back to the refusal, which is the same answer a pinned mw at an unsupported K always gets. */ -#define R4D_F8D_NT128(f, mw_, nt_) \ - emit_rc = R4D_EMIT(sk, (gemm_fp8a8_kernel), grid, \ - dim3(mw_ * kWave), \ - 0, (const uint8_t*)wq, (const void*)ws, \ - (const uint8_t*)a, (const void*)ascale, dst, (void*)c, ctr, \ - (uint32_t)N, (uint32_t)K, \ - (uint32_t)M, (uint32_t)w_ld, (uint32_t)a_ld, (uint32_t)sw_ld, \ - (uint32_t)sa_ld, ck, \ - /* THE KERNEL'S SIX DEFAULTED PARAMETERS, SPELLED. The chevron fills a \ - * default argument in at the call; kernelParams is an array and cannot, \ - * so a described launch would supply fifteen values for twenty-one slots \ - * and the kernel would read six arguments' worth of whatever followed. \ - * r4d_emit deduces the parameter list and static_asserts the arity, \ - * which is the only reason this is a build error and not a quantiser \ - * reading a garbage pointer. */ \ - (uint8_t*)nullptr, (float*)nullptr, (uint16_t*)nullptr, \ - (uint32_t)0, (uint32_t)0, (uint32_t)0) -#define R4D_F8D128(f, mw_) \ - do { if (nt == 4u) R4D_F8D_NT128(f, mw_, 4u); \ - else if (nt == 3u) R4D_F8D_NT128(f, mw_, 3u); \ - else if (nt == 2u) R4D_F8D_NT128(f, mw_, 2u); \ - else R4D_F8D_NT128(f, mw_, 1u); } while (0) -#define R4D_F8D_MW128(f) \ - do { \ - if (mw == 4u) R4D_F8D128(f, 4u); \ - else if (mw == 8u) R4D_F8D128(f, 8u); \ - else R4D_F8D128(f, 16u); \ - } while (0) -/* THE INT8 TWIN TAKES ONLY THE THREE WAVE COUNTS THE RULE ANSWERS, at both staged widths: the - * fp8 ladder's pins are tuning probes, and mirroring them would double the object again. */ -#define R4D_I8D_NT(f, mw_, nt_, fk_) \ - emit_rc = R4D_EMIT(sk, (gemm_fp8a8_kernel), grid, \ - dim3(mw_ * kWave), \ - 0, (const uint8_t*)wq, (const void*)ws, \ - (const uint8_t*)a, (const void*)ascale, dst, (void*)c, ctr, \ - (uint32_t)N, (uint32_t)K, \ - (uint32_t)M, (uint32_t)w_ld, (uint32_t)a_ld, (uint32_t)sw_ld, \ - (uint32_t)sa_ld, ck, \ - (uint8_t*)nullptr, (float*)nullptr, (uint16_t*)nullptr, \ - (uint32_t)0, (uint32_t)0, (uint32_t)0) -#define R4D_I8D(f, mw_, fk_) \ - do { if (nt == 4u) R4D_I8D_NT(f, mw_, 4u, fk_); \ - else if (nt == 3u) R4D_I8D_NT(f, mw_, 3u, fk_); \ - else if (nt == 2u) R4D_I8D_NT(f, mw_, 2u, fk_); \ - else R4D_I8D_NT(f, mw_, 1u, fk_); } while (0) -#define R4D_I8D_MW(f, fk_) \ - do { \ - if (mw == 4u) R4D_I8D(f, 4u, fk_); \ - else if (mw == 8u) R4D_I8D(f, 8u, fk_); \ - else R4D_I8D(f, 16u, fk_); \ - } while (0) - if (i8) { - if (!(mw == 4u || mw == 8u || mw == 16u)) return -4; - if (narrow_fk((uint32_t)K) == kFKNarrow) { - if (full) R4D_I8D_MW(true, kFKNarrow); else R4D_I8D_MW(false, kFKNarrow); - } else { - if (full) R4D_I8D_MW(true, 128u); else R4D_I8D_MW(false, 128u); - } - } else if (narrow_fk((uint32_t)K) == kFKNarrow) { - if (full) R4D_F8D_MW(true); else R4D_F8D_MW(false); +#define R4D_F8D_NT(f, mw_, fk_, i8_) \ + do { if (nt == 4u) R4D_F8D(f, mw_, 4u, fk_, i8_); \ + else if (nt == 3u) R4D_F8D(f, mw_, 3u, fk_, i8_); \ + else if (nt == 2u) R4D_F8D(f, mw_, 2u, fk_, i8_); \ + else R4D_F8D(f, mw_, 1u, fk_, i8_); } while (0) +#define R4D_F8D_MW(fk_, i8_) \ + do { if (full) { \ + if (mw == 4u) R4D_F8D_NT(true, 4u, fk_, i8_); \ + else if (mw == 8u) R4D_F8D_NT(true, 8u, fk_, i8_); \ + else R4D_F8D_NT(true, 16u, fk_, i8_); \ + } else { \ + if (mw == 4u) R4D_F8D_NT(false, 4u, fk_, i8_); \ + else if (mw == 8u) R4D_F8D_NT(false, 8u, fk_, i8_); \ + else R4D_F8D_NT(false, 16u, fk_, i8_); \ + } } while (0) + const uint32_t fk = narrow_fk((uint32_t)K); + if (mw == 1u || mw == 2u) { + /* Only the selftest's pin reaches these (narrow_mw answers 4, 8 or 16), and only the fp8 + * set at the 256-wide K step builds them, to keep the object size down. */ + if (i8 || fk != kFKNarrow) return -4; + if (full) { if (mw == 1u) R4D_F8D_NT(true, 1u, kFKNarrow, false); + else R4D_F8D_NT(true, 2u, kFKNarrow, false); } + else { if (mw == 1u) R4D_F8D_NT(false, 1u, kFKNarrow, false); + else R4D_F8D_NT(false, 2u, kFKNarrow, false); } + } else if (fk == kFKNarrow) { + if (i8) R4D_F8D_MW(kFKNarrow, true); else R4D_F8D_MW(kFKNarrow, false); } else { - if (!(mw == 4u || mw == 8u || mw == 16u)) return -4; - if (full) R4D_F8D_MW128(true); else R4D_F8D_MW128(false); + if (i8) R4D_F8D_MW(128u, true); else R4D_F8D_MW(128u, false); } -#undef R4D_I8D_MW -#undef R4D_I8D -#undef R4D_I8D_NT -#undef R4D_F8D_MW128 -#undef R4D_F8D128 -#undef R4D_F8D_NT128 #undef R4D_F8D_MW +#undef R4D_F8D_NT #undef R4D_F8D - /* On the launch path this is the dispatch's status; on the describe path it says the - * description fitted. Either way a failure here is a failure of the call. */ if (emit_rc != RAD_OK) return -6; - if (!sk.desc && hipGetLastError() != hipSuccess) return -6; + if (hipGetLastError() != hipSuccess) return -6; if (ksplit > 1 && !ctr) { const uint32_t n = (uint32_t)M * (uint32_t)N; - /* The second dispatch of this call; the descriptor array carries both. */ - if (R4D_EMIT(sk, splitk_reduce_kernel, dim3((n + 255) / 256), dim3(256), 0, + if (R4D_EMIT(stream, splitk_reduce_kernel, dim3((n + 255) / 256), dim3(256), 0, (const float*)scratch, (uint16_t*)c, n, ksplit) != RAD_OK) return -7; } return 0; } -// ...AND THE SAME GEMM WITH gated_quant_fp8's PASS FOLDED INTO ITS EPILOGUE. The kernel comment at -// `GATED` says what the fold is and why it is byte-identical; this is what the shape has to satisfy -// for it to exist at all, and every one of these is a REFUSAL rather than a slow path, because a -// gated call that quietly ran ungated would write the wrong buffer. +// The same GEMM with gated_quant_fp8's pass folded into its epilogue (see `GATED` on the kernel). +// Every unmet shape condition is a refusal: a gated call running ungated would write the wrong +// buffer. // // q [M][nout] E4M3, `q_ld` bytes a row (0 = nout) // s [M][ceil(nout/128)] f32, `s_ld` elements a row // y [M][nout] or 0 bf16, the silu product the unfused pair also wrote // -// The weight is the gate_up plane [2*nout][K] with gate first, exactly as the unfused GEMM reads -// it, so nothing about the checkpoint or the layout hook changes. +// The weight is the gate_up plane [2*nout][K], gate first, as the unfused GEMM reads it. extern "C" int r4d_gemm_fp8a8_gated_nt_m16_max_m(void) { return 64; } extern "C" int r4d_gemm_fp8a8_gated_nt_m16(long a, long ascale, long wq, long ws, @@ -1635,12 +1097,9 @@ extern "C" int r4d_gemm_fp8a8_gated_nt_m16(long a, long ascale, long wq, long ws if (M <= 0 || K <= 0 || nout <= 0) return -2; if (M > r4d_gemm_fp8a8_gated_nt_m16_max_m()) return -3; if (K % (int)kFKNarrow) return -4; - // The block emits FM/2 = 128 fused columns and that is ONE 128-column scale group, which is - // the whole reason the quantiser's reduction closes inside it. A nout that is not a multiple - // of 128 would put a group across two blocks and there is nowhere to finish it. + // A block emits 128 fused columns, one scale group, so nout must be a multiple of 128. if (nout % 128) return -5; - // Only silu is compiled: `gated_quant_fp8`'s sigmoid form is a gated attention's o_proj, whose - // gate is a column slice of another projection and reaches `gate_quant_fp8` instead. + // Only silu: the sigmoid form (gated attention) goes through `gate_quant_fp8` instead. if (act != 0) return -8; const int N = 2 * nout; if (!a_ld) a_ld = K; @@ -1652,21 +1111,15 @@ extern "C" int r4d_gemm_fp8a8_gated_nt_m16(long a, long ascale, long wq, long ws if (!s_ld) s_ld = nout / 128; if (!y_ld) y_ld = nout; - // The fold has no partial plane to reduce and no second launch to fold into, so a shape whose - // grid the split rule would widen is REFUSED rather than served unsplit -- at gate_up's shape - // (N/16 = 1088 against a target of 128) it never fires, and a shape where it would is a shape - // this kernel is the wrong answer for. + // The fold cannot split K, so a shape the split rule would split is refused (gate_up's shape, + // N/16 = 1088, never splits). uint32_t ck = 0; if (narrow_ksplit((uint32_t)N, (uint32_t)K, (uint32_t)M, &ck) != 1u) return -9; constexpr uint32_t kGmw = 16u; // FM = 256: 128 gate rows and 128 up rows - /* Same rule as the narrow dispatch above, and for the same reason. The epilogue skips a token - * tile wholly past M in the gate stash ("at M = 48 with NT = 4 the last tile is entirely past - * the end"), but a tile count above ceil(M/16) still pays for that tile in every K - * iteration. */ - static const uint32_t ntping = env_u32("R4D_F8_NT"); + /* Same NT rule as the narrow dispatch: a tile past M is skipped in the epilogue but still costs + * every K iteration. */ uint32_t nt = (M > 48) ? 4u : ((M > 32) ? 3u : ((M > 16) ? 2u : 1u)); - if (ntping >= 1u && ntping <= 4u && (uint32_t)M <= ntping * 16u) nt = ntping; if (const uint32_t f = g_nt_force.load(std::memory_order_relaxed)) { if ((uint32_t)M <= f * 16u) nt = f; } const bool full = ((uint32_t)M % (nt * 16u) == 0) && (K % (int)kBlock == 0); const dim3 grid((uint32_t)(nout / 128), 1, 1); @@ -1691,10 +1144,9 @@ extern "C" int r4d_gemm_fp8a8_gated_nt_m16(long a, long ascale, long wq, long ws return hipGetLastError() == hipSuccess ? 0 : -6; } -// The same GEMM for PREFILL row counts. Same operands and same layouts; the difference is the tile -// shape and that the ACTIVATION lands on the A operand, which makes the epilogue a coalesced store -// instead of a scattered one. No split-K: the grid is already ceil(M/128) x ceil(N/128), which is -// in the hundreds of blocks at any prefill shape, and that is the condition the split exists for. +// The same GEMM for prefill row counts: same operands and layouts, but a 128x128 tile with the +// activation on A, so the store is coalesced. No split-K: the grid is ceil(M/128) x ceil(N/128), +// hundreds of blocks at any prefill shape. template static int gemm_8a8_tiled(long a, long ascale, long wq, long ws, long c, int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld, long stream); @@ -1705,8 +1157,8 @@ extern "C" int r4d_gemm_fp8a8_tiled(long a, long ascale, long wq, long ws, long return gemm_8a8_tiled(a, ascale, wq, ws, c, M, K, N, a_ld, sa_ld, w_ld, sw_ld, stream); } -// The int8 twins: i8 codes for both operands, the weight's bf16 scale per row per 128 K -- ws is -// [N][ceil(K/128)] -- and otherwise the fp8 entry points' arguments, bands and refusals. +// The int8 twins: i8 codes for both operands and a bf16 weight scale per row per 128 K (ws is +// [N][ceil(K/128)]); otherwise as the fp8 entry points. extern "C" int r4d_gemm_i8a8_tiled(long a, long ascale, long wq, long ws, long c, int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld, long stream) { @@ -1716,9 +1168,8 @@ extern "C" int r4d_gemm_i8a8_tiled(long a, long ascale, long wq, long ws, long c extern "C" int r4d_gemm_i8a8_nt_m16(long a, long ascale, long wq, long ws, long c, int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld, long scratch, long scratch_bytes, long stream) { - R4dSink sk; sk.stream = (RadStream)(uintptr_t)stream; return gemm_fp8a8_nt_m16_emit(a, ascale, wq, ws, c, M, K, N, a_ld, sa_ld, w_ld, sw_ld, - scratch, scratch_bytes, sk, true); + scratch, scratch_bytes, (RadStream)(uintptr_t)stream, true); } template @@ -1726,8 +1177,8 @@ static int gemm_8a8_tiled(long a, long ascale, long wq, long ws, long c, int M, int a_ld, int sa_ld, int w_ld, int sw_ld, long stream) { if (!a || !ascale || !wq || !ws || !c) return -1; if (M <= 0 || K <= 0 || N <= 0) return -2; - // Required, not preferred: the fold at the end of the K loop assumes a whole 128-column scale - // block, and the AW=false branch reads the weight's scale as one scalar for 128 B rows. + // Required: the fold assumes whole 128-column scale blocks, and the AW=false branch reads the + // weight's scale as one scalar for 128 B rows. if (K % (int)kBlock) return -4; if (N % (int)kBlock) return -5; if (!a_ld) a_ld = K; @@ -1756,36 +1207,32 @@ static int gemm_8a8_tiled(long a, long ascale, long wq, long ws, long c, int M, // ============================================================== the plugin ABI entry points // -// The shared operand reader is r4d_fp8_args.h. See libr4d/r4d_args.h for why there is no adapter -// directory between the core and these launches. +// The shared operand reader is r4d_fp8_args.h; see libr4d/r4d_args.h. extern "C" int64_t r4d_rad_gemm_fp8a8_m16_scratch(const RadArgs* a) { - const long long M = aff_or(a, "M"), N = aff_or(a, "N"), K = aff_or(a, "K"); + const long long M = r4d_geti_or(a, "M", 0), N = r4d_geti_or(a, "N", 0), + K = r4d_geti_or(a, "K", 0); if (M < 1 || N < 1 || K < 1) return 0; if (M > r4d_gemm_fp8a8_nt_m16_max_m()) return 0; return (int64_t)r4d_gemm_fp8a8_nt_m16_scratch((int)M, (int)K, (int)N); } -static int rad_gemm_fp8a8_m16_body(const RadArgs* a, const R4dSink& sk) { +extern "C" int r4d_rad_gemm_fp8a8_m16(const RadArgs* a, RadStream stream) { Fp8Ops g; int rc = fp8_ops(a, &g, 1); if (rc != RAD_OK) return rc; if (g.M > r4d_gemm_fp8a8_nt_m16_max_m()) return R4D_NO(RAD_E_SHAPE); - /* A short scratch is not an error: libr4d runs unsplit, which is correct and slow. Passing the - * length is what lets it make that decision rather than reading past the end of an arena the - * core sized for a different band. */ + /* A short scratch is not an error: the launch runs unsplit (correct, slower). The length is + * passed so the launch never reads past an arena sized for a different band. */ const int e = gemm_fp8a8_nt_m16_emit( r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b), r4d_addr(g.bscale), r4d_addr(g.y), (int)g.M, (int)g.K, (int)g.N, (int)g.a_ld, (int)g.sa_ld, (int)g.w_ld, (int)g.sw_ld, - (long)(uintptr_t)a->scratch, (long)a->scratch_bytes, sk); + (long)(uintptr_t)a->scratch, (long)a->scratch_bytes, stream); return e == 0 ? RAD_OK : RAD_E_SHAPE; } -R4D_ENTRY(r4d_rad_gemm_fp8a8_m16, rad_gemm_fp8a8_m16_body) -/* THE SAME GEMM WITH THE QUANTISER'S PASS IN ITS EPILOGUE. A shim of its own rather than a case of - * `fp8_ops`, because that helper derives M and N from operand 4 -- which here is the QUANTISER's - * [M, nout] output and not the GEMM's [M, 2*nout] one, so every extent it checks would be off by - * the factor the fold exists to remove. Operand indices are `gemm_nt_q_gated`'s, from - * oGemmNtQGated in r4d_rows.cpp. */ +/* The gated GEMM's shim. Not fp8_ops: that derives M and N from operand 4, which here is the + * quantiser's [M, nout] output rather than the GEMM's [M, 2*nout]. Operand indices are + * `gemm_nt_q_gated`'s (oGemmNtQGated in r4d_rows.cpp). */ enum { GG_A = 0, GG_AS = 1, GG_B = 2, GG_BS = 3, GG_Q = 4, GG_S = 5, GG_Y = 6 }; extern "C" int r4d_rad_gemm_fp8a8_gated_m16(const RadArgs* a, RadStream s) { @@ -1805,8 +1252,8 @@ extern "C" int r4d_rad_gemm_fp8a8_gated_m16(const RadArgs* a, RadStream s) { if (blk != R4D_FP8_BLOCK) return R4D_NO(RAD_E_SHAPE); if (r4d_geti_or(a, "group", blk) != blk) return R4D_NO(RAD_E_SHAPE); - /* The FUSED width is the quantiser's, and the weight is twice it. Taking nout from `q` rather - * than from the `N` parameter is deliberate: the buffer is what the kernel writes into. */ + /* nout is the fused (quantiser) width, taken from `q`, the buffer written; the weight is twice + * it. */ const long long M = q->shape[0], nout = q->shape[1], K = w->shape[1]; if (M < 1 || nout < 1 || K < 1) return R4D_NO(RAD_E_SHAPE); if (M > r4d_gemm_fp8a8_gated_nt_m16_max_m()) return R4D_NO(RAD_E_SHAPE); @@ -1826,7 +1273,7 @@ extern "C" int r4d_rad_gemm_fp8a8_gated_m16(const RadArgs* a, RadStream s) { if (ap < 0 || asp < 0 || wp < 0 || wsp < 0 || qp < 0 || sp < 0 || yp < 0) return R4D_NO(RAD_E_STRIDE); - /* `act` is required by this schema, unlike gated_quant_fp8's, and only silu is compiled. */ + /* `act` is required by this schema (unlike gated_quant_fp8's); only silu is compiled. */ const char* act = r4d_gets(a, "act"); if (!act || std::strcmp(act, "silu")) return R4D_NO(RAD_E_UNSUPPORTED); @@ -1844,7 +1291,7 @@ extern "C" int64_t r4d_rad_gemm_i8a8_m16_scratch(const RadArgs* a) { return r4d_rad_gemm_fp8a8_m16_scratch(a); } -static int rad_gemm_i8a8_m16_body(const RadArgs* a, const R4dSink& sk) { +extern "C" int r4d_rad_gemm_i8a8_m16(const RadArgs* a, RadStream stream) { Fp8Ops g; int rc = fp8_ops(a, &g, 1, FP8_OPS_ROW_SCALE); if (rc != RAD_OK) return rc; @@ -1853,10 +1300,9 @@ static int rad_gemm_i8a8_m16_body(const RadArgs* a, const R4dSink& sk) { const int e = gemm_fp8a8_nt_m16_emit( r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b), r4d_addr(g.bscale), r4d_addr(g.y), (int)g.M, (int)g.K, (int)g.N, (int)g.a_ld, (int)g.sa_ld, (int)g.w_ld, (int)g.sw_ld, - (long)(uintptr_t)a->scratch, (long)a->scratch_bytes, sk, true); + (long)(uintptr_t)a->scratch, (long)a->scratch_bytes, stream, true); return e == 0 ? RAD_OK : RAD_E_SHAPE; } -R4D_ENTRY(r4d_rad_gemm_i8a8_m16, rad_gemm_i8a8_m16_body) extern "C" int r4d_rad_gemm_i8a8_tiled(const RadArgs* a, RadStream s) { Fp8Ops g; diff --git a/libr4d/r4d_gemm_mxfp4a8_decode.hip b/libr4d/r4d_gemm_mxfp4a8_decode.hip index d68d6fd9..eaab1ce8 100644 --- a/libr4d/r4d_gemm_mxfp4a8_decode.hip +++ b/libr4d/r4d_gemm_mxfp4a8_decode.hip @@ -1,57 +1,45 @@ -// r4d_gemm_mxfp4a8_decode.hip - r4d_gemm_mxfp4a8_decode: the OCP-MXFP4 x fp8 GEMM for the DECODE -// band, M <= 128, gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T over the same operands, weight -// layout and fold as r4d_gemm_mxfp4a8_nt_m64 and r4d_gemm_mxfp4a8_tiled. +// r4d_gemm_mxfp4a8_decode.hip - r4d_gemm_mxfp4a8_decode: the OCP-MXFP4 x fp8 GEMM for the decode +// band, M <= 128, gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T with the operands, weight layout and +// fold of r4d_gemm_mxfp4a8_nt_m64 and r4d_gemm_mxfp4a8_tiled. // -// WHY A THIRD MXFP4 KERNEL. At decode the GEMM is a weight stream: a speculative verify step is -// a handful of rows against the whole 4-bit trunk, and the only number that matters is how close -// the stream runs to the card's DRAM bandwidth. The skinny kernel splits K inside one workgroup -// and reads the weight straight into registers, which leaves the narrow projections well short of -// it. This one splits K ACROSS workgroups with a fused last-arriver reduction, unpacks the weight -// through LDS, gives each block one 16-row A fragment per M tile, and streams the weight with -// non-temporal loads. +// At decode the GEMM is a weight stream and the goal is DRAM bandwidth. The skinny kernel (split-K +// within a workgroup, weight straight to registers) falls short on narrow projections. This one +// splits K across workgroups with a fused last-arriver reduction, unpacks the weight through LDS, +// and streams it with non-temporal loads. // -// THE TILE. A block is DWN = 8 waves over BND = 128 output columns, one 16-column fragment a wave, -// and DTM 16-row M fragments -- the SMALLEST that covers M, because a wider tile computes rows -// nobody asked for. A K slab of DBK bytes is staged: A (16*DTM rows) and the weight's 128 rows, -// unpacked to e4m3 with the block exponent folded in through r4d_mxfp4.h, as the other two MXFP4 -// kernels fold it. +// Tile: DWN = 8 waves over BND = 128 output columns (one 16-column fragment per wave) and DTM +// 16-row M fragments, the fewest that cover M. Each K slab of DBK bytes stages A (16*DTM rows) and +// 128 weight rows, unpacked to e4m3 through r4d_mxfp4.h. // -// SPLIT-K IS NOT OPTIONAL. With one 16-row M fragment the independent N fragments number N/16, so -// N=5120 is 320 waves -- 2.5 a SIMD however the N tile is chosen. DKS blocks split the K slabs; -// each writes an fp32 partial [DKS][M][N] and the LAST to arrive (an agent-scope counter per column -// block) sums them in place, so there is no second launch. +// Split-K is required: N/16 fragments alone (320 waves at N=5120) do not fill the part. DKS blocks +// split the K slabs; each writes an fp32 partial [DKS][M][N], and the last to arrive (an +// agent-scope counter per column block) sums them, with no second launch. // -// THE SPLIT, SLAB AND LOAD HINT are a rule measured cell by cell on this kernel -- every split x -// slab x hint against the 27B's per-rank shapes at M = 8..128, DRAM-fed -- because no single -// fill target fits: the split is the smallest power of two whose grid reaches 48 blocks at M <= 16, -// 56 at M <= 96 and 40 above (an unsplit 40-block grid already streams a short-K weight at the -// card's rate there, and a split's partial traffic grows with M); a deep K (8192 or more, down at -// K=8704) keeps doubling while a split still has 24 or more 128-wide slabs, since 40-odd blocks -// do not keep its long slab loop fed; and no split goes past ks*M = 512, where the partials -// outweigh what the split buys. The slab is 128 except where LDS per block, (16*DTM + 128) * -// (DBK+8) bytes, would cost a wide or deeply split grid its resident blocks (see mxd_plan); a K -// that is not a multiple of 128 takes 64 (and a 2-way split widens to 4). Weight loads are non-temporal for weights of 4 MiB or more, -// plain below, where the weight is too small to evict anything the split partials need. All three -// are tunables (`ks`, `bk`, `nt`) whose 0 is this rule. +// Split, slab and load hint follow a rule tuned per cell on the 27B's per-rank shapes at +// M = 8..128 (tunables `ks`, `bk`, `nt`; 0 selects the rule): +// - split: the smallest power of two whose grid reaches 48 blocks at M <= 16, 56 at M <= 96 and +// 40 above; for K >= 8192 keep doubling while a split has >= 24 128-wide slabs; never past +// ks*M = 512, where partial traffic outweighs the gain. +// - slab: 128, or 64 where LDS per block, (16*DTM + 128) * (DBK+8) bytes, would cost a wide or +// deeply split grid its resident blocks (see mxd_plan). A K not a multiple of 128 takes 64 (and +// a 2-way split widens to 4). +// - non-temporal weight loads for weights of 4 MiB or more. // -// NO STATE IS KEYED ON THE STREAM. The split partial is the op's own scratch -- the core sizes it -// from the scratch hook and treats it as read+write, so two ops that could overlap get disjoint -// slices -- and the arrival counters are a small block keyed on the OUTPUT buffer (mxd_out_ctr), -// zero at entry and left zero by the reducer. A recorded pass is replayed with its recorded -// arguments, possibly on another stream than it was recorded on, so a pointer that depended on the -// stream would make the replay differ from its recording. Two launches writing the same output are -// ordered by that dependency; two that can overlap write different outputs. The row is therefore -// concurrent (rad_kernel_concurrent), as gemm_fp8a8_nt_m16 is. A scratch shorter than the split -// needs is refused: the hook sizes it for every M of the band, so a short one is a caller's error. +// No state is keyed on the stream, since a recorded pass may replay on another stream. The split +// partial is the op's scratch (sized by the scratch hook, read+write, so overlapping ops get +// disjoint slices); the arrival counters are keyed on the output buffer (mxd_out_ctr), zero at +// entry and reset by the reducer. Launches writing the same output are ordered; overlapping ones +// write different outputs. The row is therefore concurrent (rad_kernel_concurrent), like +// gemm_fp8a8_nt_m16. A scratch shorter than the split needs is refused. // -// Every thread fences its partial stores before the counter: a fence on thread 0 alone orders -// only thread 0's stores, and the reducer would then read whatever happened to drain. +// Every thread fences its partial stores before the counter; a fence on thread 0 alone would order +// only its own stores. // -// TWO ACTIVATION SCALE GRIDS, as in the tiled kernel: one f32 a row, or one a (row, 128 of K). The -// per-block form carries each row's accumulator in the current block's scale and rescales it by -// s_prev / s_next at each 128 boundary, the ratio computed once a row into LDS from scales loaded a -// boundary early; with the accumulator transposed a lane reads one ratio for each of its rows. A split's partial is brought back -// to absolute units before it is written, because the splits end in different blocks. +// Two activation scale grids as in the tiled kernel: one f32 per row, or one per (row, 128 of K). +// The block form carries each row's accumulator in the current block's scale, rescaling by +// s_prev / s_next at each boundary (ratio computed once per row into LDS from scales loaded a +// boundary early). Each split's partial is converted to absolute units before it is written, +// since splits end in different blocks. #include "r4d.h" #include "r4d_gemm_args.h" #include "r4d_common.h" @@ -81,22 +69,17 @@ static __device__ __forceinline__ T mxd_ld(const T* p) { else return *p; } -// ---- what both kernels share: the scale grid at a 128 boundary, and the epilogue. +// ---- shared by both kernels: the scale grid at a 128 boundary, and the epilogue. // -// THE ACCUMULATOR IS C TRANSPOSED. The WMMA takes the weight fragment as its A operand and the -// activation fragment as its B operand -- the two fragments have the same register layout, so -// this is only an argument order -- and computes C^T: a lane's accumulator for M fragment i holds -// ONE row, m = 16i + col, and the eight consecutive columns n0 + 16*wave + kb8 + e. So a row's -// activation scale is one value a lane, not eight: the (row, 128) grid's boundary rescale reads -// DTM scales instead of 8*DTM, and the epilogue writes each lane's eight outputs as one 16-byte -// store (one 32-byte store of partials) instead of eight 2-byte ones. +// The accumulator is C transposed: the WMMA takes the weight fragment as A and the activation as B +// (same register layout), so a lane's accumulator for M fragment i holds one row, m = 16i + col, +// and eight consecutive columns n0 + 16*wave + kb8 + e. A lane needs one activation scale per row, +// and writes its eight outputs as one 16-byte store (one 32-byte store of partials). -// THE (ROW, 128) SCALE GRID, computed once a row: thread t < ROWS owns row t. It loads the next -// 128 boundary's two scales -- the block that starts there and the one before it -- a boundary -// early, writes the row's ratio s_prev / s_next to LDS at the boundary (published by the staging -// barrier), and a lane then reads ONE ratio for each of its rows. A zero block keeps the carried -// scale; a zero block before this one sends the carried scale back to the grid, which only an -// all-zero activation block ever does. +// The (row, 128) scale grid: thread t < ROWS owns row t, loads the next boundary's two scales a +// boundary early and writes s_prev / s_next to LDS at the boundary (published by the staging +// barrier). A zero next block keeps the carried scale; after a zero block the carried scale is +// looked up from the grid. static __device__ __forceinline__ float mxd_ratio(float ns, float np, const float* __restrict__ row, int kb) { return ns > 0.f ? (np > 0.f ? np : r4d_mxfp4_carried(row, kb - 2)) / ns : 1.f; @@ -112,9 +95,9 @@ static __device__ __forceinline__ void mxd_rescale(v8f (&acc)[DTM], const float* } } -// The split's result: written straight to C when the accumulator holds the whole K range, else as -// an fp32 partial that the last block to arrive on this column block sums. `kb_end` is the block -// the split's last slab ends in (ABLK: the scale the accumulators are carried in). +// The split's result: written to C when the accumulator covers all of K, else as an fp32 partial +// that the last block to arrive on this column block sums. `kb_end` is the block the split's last +// slab ends in (ABLK: the scale the accumulators are carried in). template static __device__ __forceinline__ void mxd_epilogue( const v8f (&acc)[DTM], const float* __restrict__ As, int as_rs, @@ -125,8 +108,8 @@ static __device__ __forceinline__ void mxd_epilogue( constexpr int ROWS = R4D_MXD_MTILE * DTM; const int tid = threadIdx.x; const int nb = n0 + wave * 16 + kb8; // this lane's eight columns; N % 16 == 0 keeps all or none - // Each row's final scale, once a row: the scale the split's accumulators end in (ABLK), or the - // row's own. The K loop's closing barrier retired the last ratio reads. + // Each row's final scale: the one the split's accumulators end in (ABLK), or the row's own. The + // K loop's closing barrier retired the last ratio reads. if (tid < ROWS) { const int m = tid < M ? tid : M - 1; sR[tid] = ABLK ? r4d_mxfp4_carried(As + (size_t)m * as_rs, kb_end) : As[(size_t)m * as_rs]; @@ -178,7 +161,7 @@ static __device__ __forceinline__ void mxd_epilogue( } } } - // EVERY thread's partial stores are ordered before the counter, then the last arriver reduces. + // Every thread's partial stores are ordered before the counter; then the last arriver reduces. __threadfence(); __syncthreads(); if (tid == 0) @@ -186,7 +169,7 @@ static __device__ __forceinline__ void mxd_epilogue( __HIP_MEMORY_SCOPE_AGENT); __syncthreads(); if (*s_last != (unsigned)(DKS - 1)) return; - if (tid == 0) cnt[blockIdx.x] = 0u; // left clean for the next launch on this stream + if (tid == 0) cnt[blockIdx.x] = 0u; // reset for the next launch __threadfence(); // acquire, before reading the other partials const int nhi = min(n0 + BND, N); for (int nn = n0 + tid; nn < nhi; nn += NTHR) { @@ -200,12 +183,10 @@ static __device__ __forceinline__ void mxd_epilogue( } } -/* THE WAVES A SIMD EACH TILE SHAPE RUNS AT (R4D_WAVES): the register budget the decode tile was - * tuned at, by K block, M fragments and activation-scale form, so a compiler release cannot move - * it -- LLVM 24 adds two VGPRs to the DBK 64, three-fragment form and drops it from sixteen waves to - * twelve. Where LLVM 22 itself ran out of registers (DBK 128 at seven and eight fragments without - * block activation scales, 256 VGPRs and a spill) the budget is the one the tile reaches without - * spilling. */ +/* Waves per SIMD for each tile shape (R4D_WAVES), by K block, M fragments and scale form: pins + * the register budget the tile was tuned at so a compiler release cannot change occupancy (LLVM 24 + * would drop the DBK 64, three-fragment form from 16 waves to 12). Where a shape spilled at 256 + * VGPRs, the budget is the one it reaches without spilling. */ constexpr int mxd_waves(int dbk, int dtm, bool ablk) { if (dbk == 64) return dtm <= 3 ? 16 : dtm == 4 ? 12 : dtm == 5 ? 10 : dtm == 6 ? (ablk ? 9 : 10) @@ -281,8 +262,8 @@ void r4d_gemm_mxfp4a8_decode_kernel( const int kst = rest % KSTEPS_T, ntl = rest / KSTEPS_T; const int r = ntl * 16 + (lane_ & 15), kloc = kst * 16 + (lane_ >> 4) * 8; const int gn = n0 + r; - // gn is even and N % 16 == 0: clamping to the last even row keeps the 8 B read aligned and - // gc + 1 in bounds; the slot address is recomputed from the clamped row. + // gn is even and N % 16 == 0, so clamping to N - 2 keeps the 8 B read aligned and gc + 1 in + // bounds; the slot address is recomputed from the clamped row. const int gc = gn < N - 2 ? gn : N - 2; const int lanec = (lane_ & 16) | (gc & 15); const mxd_u2 wv = @@ -328,13 +309,10 @@ void r4d_gemm_mxfp4a8_decode_kernel( kb_end, &s_last, sR); } -// THE ONE-FRAGMENT FORM (M <= 16), which is every single-sequence verify step. The same tile, fold -// and split as above, with two changes that pay only when one M fragment leaves the block waiting -// on memory: the NEXT slab's A, codes and exponents are loaded into registers while this slab -// computes, so a block keeps its loads in flight across the WMMA phase instead of draining at every -// barrier; and a thread takes four adjacent slots, one 16 B load instead of two 8 B ones. Each -// row's reference exponent is read once, not once a slab. Bit-identical to the kernel above at -// every split: the K order, the fold and the reduction are unchanged. +// The one-fragment form (M <= 16), every single-sequence verify step. Same tile, fold and split as +// above, plus: the next slab's A, codes and exponents are loaded into registers while this slab +// computes, keeping loads in flight across barriers; a thread takes four adjacent slots (one 16 B +// load); and each row's reference exponent is read once. Bit-identical to the kernel above. template __global__ __launch_bounds__(R4D_MXD_DWN * 32) R4D_WAVES(DBK == 64 ? 16 : 12) void r4d_gemm_mxfp4a8_decode1_kernel( @@ -479,10 +457,10 @@ void r4d_gemm_mxfp4a8_decode1_kernel( } namespace { -// THE ARRIVAL COUNTERS, one block an output buffer -- see the header. The counters cannot live in -// the scratch: other ops write the arena between two of ours, and the counters must be zero at -// entry. So they are a small device allocation of their own, taken once per (device, output) and -// kept zero by the reducer, as gemm_fp8a8_nt_m16 keys its split_ctr. +// The arrival counters, one block per output buffer (see the header). They cannot live in the +// scratch, which other ops overwrite, because 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), as gemm_fp8a8_nt_m16's split_ctr. unsigned* mxd_out_ctr(const void* out) { static std::mutex mu; static std::map, unsigned*> blocks; @@ -499,9 +477,8 @@ unsigned* mxd_out_ctr(const void* out) { return p; } -// THE SPLIT, SLAB AND LOAD HINT A LAUNCH RUNS, from M, the shape and the tunables (0 = the rule). -// One function for the launch and the scratch hook, so the partial the hook sizes is the one -// written. See the header for the rule and what it was measured on. +// The split, slab and load hint for a launch, from M, the shape and the tunables (0 = the rule; see +// the header). Shared by the launch and the scratch hook so the sized partial is the one written. struct MxdPlan { int ks, bk; bool nt; }; MxdPlan mxd_plan(int M, int K, int N, int KS, int BK, int NT) { const int nblk = (N + R4D_MXD_DWN * 16 - 1) / (R4D_MXD_DWN * 16); @@ -513,9 +490,8 @@ MxdPlan mxd_plan(int M, int K, int N, int KS, int BK, int NT) { if (K >= 8192) // a deep K: a split of 24 or more slabs still waits on them while (ks < R4D_MXD_MAX_KS && (K / 128) / ks >= 24 && 2 * ks * M <= 512) ks <<= 1; p.ks = KS > 0 ? KS : ks; - // 64-wide slabs where LDS per block, (16*DTM + 128)*(DBK+8) bytes, costs a wide or deeply split - // grid its resident blocks: DTM 4 unsplit on 110+ column blocks, and DTM 8 on those or at a 4-way - // split. + // 64-wide slabs where LDS per block would cost resident blocks: DTM 4 unsplit on 110+ column + // blocks, and DTM 8 on those or at a split of 4 or more. const bool slab64 = (tm == 4 && p.ks == 1 && nblk >= 110) || (tm == 8 && (nblk >= 110 || p.ks >= 4)); p.bk = BK > 0 ? BK : (slab64 ? 64 : 128); p.nt = NT == 1 || (NT == 0 && (long)N * K / 2 >= (4l << 20)); @@ -632,11 +608,10 @@ extern "C" int r4d_rad_gemm_mxfp4a8_decode(const RadArgs* a, RadStream s) { return RAD_OK; } -/* The core sizes the op's scratch from this. `M` is the band's widest, and a narrower M can split - * wider (the fill rule asks for more blocks at M <= 24), so the size is the widest split over the - * band times its widest M -- an upper bound on every launch the band can make. A partitioned - * weight launches each part at ITS rows, which splits wider than the whole would, so the bound is - * the largest of the parts' (they run one after another and share the scratch). */ +/* The op's scratch size. A narrower M can split wider than the band's widest M, so the size is the + * widest split over the band times the widest M, an upper bound for every launch. Parts of a + * partitioned weight split at their own N and run in turn sharing the scratch, so the bound is the + * largest part's. */ extern "C" int64_t r4d_rad_gemm_mxfp4a8_decode_scratch(const RadArgs* a) { const long long M = r4d_geti_or(a, "M", 0), N = r4d_geti_or(a, "N", 0); const long long K = r4d_geti_or(a, "K", 0); diff --git a/libr4d/r4d_gemm_mxfp4a8_nt_m64.hip b/libr4d/r4d_gemm_mxfp4a8_nt_m64.hip index 345bda3c..070db714 100644 --- a/libr4d/r4d_gemm_mxfp4a8_nt_m64.hip +++ b/libr4d/r4d_gemm_mxfp4a8_nt_m64.hip @@ -3,87 +3,51 @@ // e4m3 and W stored as OCP micro-scaling fp4: an e2m1 element per nibble and one E8M0 exponent // per 32 elements along K. // -// WHY THIS EXISTS ALONGSIDE r4d_gemm_w4a8_nt_m64. That kernel's 4-bit code is an int4 the library -// derives at load; this one's is a checkpoint format it does not get to choose. An MXFP4 -// checkpoint arrives with its own per-32 E8M0 exponents, and a serving stack that re-derives them -// as int4 has quantised twice. The two also want different matrix instructions -- iu8 there, fp8 -// here -- and on this part both run at the same rate, so the format is the whole decision: +// Unlike r4d_gemm_w4a8_nt_m64, whose int4 code the library derives, this reads a checkpoint +// format: MXFP4 ships its own per-32 E8M0 exponents, and re-deriving int4 would quantise twice. The +// fp8 WMMA runs at the iu8 rate on this part (f16 207 TF/s; fp8 412; iu8 407). // -// v_wmma_f32_16x16x16_f16 207 TF/s 5.95 cyc/instr -// v_wmma_f32_16x16x16_fp8_fp8 412 2.99 -// v_wmma_i32_16x16x16_iu8 407 3.03 +// The per-32 exponent is folded into the element. With a per-row reference Wref[n] = +// max_k E8M0[n][k] (computed offline), d = Wref[n] - E8M0[n][blk] is folded into the e4m3 value: +// the e2m1 magnitudes {0, .5, 1, 1.5, 2, 3, 4, 6} scaled by 2^-d are e4m3 numbers, so a 16-entry +// table indexed by d replaces the per-element multiply with a v_perm_b32. One factor per row, +// 2^(Wref[n]-127), is applied in the epilogue with the activation scale. // -// THE PER-32 EXPONENT IS FOLDED INTO THE ELEMENT, WHICH IS WHY THE UNPACK IS CHEAP. The naive -// MXFP4 dequant multiplies each element by 2^(E8M0-127), which is a per-32-block rescale inside -// the inner loop and puts a multiply on every weight. Instead, take a per-ROW reference exponent -// Wref[n] = max_k E8M0[n][k] once, offline, and fold the difference d = Wref[n] - E8M0[n][blk] -// into the e4m3 VALUE: the eight e2m1 magnitudes {0, .5, 1, 1.5, 2, 3, 4, 6} scaled by 2^-d are -// themselves e4m3 numbers, so a 16-entry table of packed e4m3 bytes indexed by d replaces the -// multiply with a v_perm_b32. What is left is one factor per row, 2^(Wref[n]-127), applied once -// in the epilogue next to the activation's own per-row scale. +// The table extends into e4m3 subnormals: stopping at 2^-6 would flush 6.7% of one checkpoint's +// weights (per-channel errors up to 18.7%). Down to 2^-9 every d <= 8 is exact, which relies on the +// gfx12 fp8 WMMA honouring e4m3 subnormals (exact for every m*2^-9, m = 1..7). d >= 13 is zero. // -// The table runs into e4m3 SUBNORMALS on purpose. Stopping at the smallest normal (2^-6) flushes -// every element whose block exponent is more than 5 binades below its row reference; on this -// checkpoint that is 6.7% of the weights on 36 output channels, for per-channel errors up to -// 18.7%. Extending to 2^-9 makes every d <= 8 exact. That is only sound because the gfx12 fp8 -// WMMA HONOURS e4m3 subnormals rather than flushing them: the product is exact for every m*2^-9, -// m = 1..7. d >= 13 rounds to zero, which is correct: those elements are below the -// representable range of the row. +// Unpack (r4d_mxfp4.h): four v_perm_b32 per eight weights, no multiply. The scale lookup is once +// per fragment: eight consecutive k at an offset that is a multiple of 8 lie in one 32-block. // -// UNPACK IS FOUR v_perm_b32 PER EIGHT WEIGHTS. A lane's fragment is eight consecutive k, which is -// four packed bytes. Splitting the low and high nibbles gives the even and odd elements; each is -// mapped through the folded-magnitude table by a v_perm_b32 that indexes it with the 3-bit -// magnitude, the sign rides along as bit 3 shifted into the e4m3 sign position, and two more -// v_perm_b32 interleave the halves back into k order. No multiply, no exponent arithmetic in the -// loop, and the scale lookup is once per fragment rather than once per element: eight consecutive -// k always lie inside one 32-element block, because the fragment's k offset is a multiple of 8. +// Split-K is within the workgroup, reduced in LDS: N/16 tiles alone do not fill the part (320 +// waves at N=5120), and a cross-workgroup split would need an HBM partial buffer and a counter. +// The kernel needs no scratch, so it is graph-replay safe. // -// SPLIT-K IS IN THE WORKGROUP, AS EVERYWHERE ELSE IN THIS LIBRARY. With one 16-row M fragment the -// independent N fragments number N/16 -- 320 waves at N=5120 -- which does not fill the part, so -// the K range has to be split. Doing it across workgroups needs an fp32 partial buffer in HBM and -// a counter to decide who reduces; doing it across waves of one workgroup reduces in LDS and needs -// neither. The LDS form is also what keeps this kernel cudagraph-safe with no scratch to register: -// a caller can replay it without having handed the library any memory. -// -// THE WEIGHT IS PRE-PERMUTED INTO FRAGMENT ORDER, AS IT IS FOR w4a16/w4a8. A B fragment maps lane -// l onto N row l&15, so in checkpoint order the sixteen lanes of a half-wave read sixteen rows K/2 -// bytes apart -- a fully strided read on the operand that dominates traffic. Reordering the weight -// once at load fixes it and is what lets this kernel skip LDS entirely. -// -// The layout is one 32-lane slot per (n-tile, k-step): +// The weight is pre-permuted into fragment order (as for w4a16/w4a8). In checkpoint order the +// sixteen lanes of a half-wave would read rows K/2 bytes apart. The layout is one 32-lane slot per +// (n-tile, k-step): // // Wp[((n/16) * (K/16) + (k/16)) * 32 + lane] one uint32 = 4 packed bytes = 8 elements // -// where lane's row is 16*(n/16) + (lane&15) and its eight elements start at k + 8*(lane>>4). A -// wave then reads 128 contiguous bytes per step. In checkpoint terms, taking W as -// [N/16][16][K/16][8] bytes, slot l of tile (nt, ks) is W[nt][l&15][ks][4*(l>>4) .. +4]. -// permute_w() in mxfp4_layout.py is the reference implementation. +// where lane's row is 16*(n/16) + (lane&15) and its eight elements start at k + 8*(lane>>4); a wave +// reads 128 contiguous bytes per step. Taking W as [N/16][16][K/16][8] bytes, slot l of tile +// (nt, ks) is W[nt][l&15][ks][4*(l>>4) .. +4]. permute_w() in mxfp4_layout.py is the reference. +// With the permute this LDS-free kernel beats an LDS-staged one on every shape; without it, it +// loses on every shape. The E8M0 scales stay in [K/32][N] order (a half-wave reads sixteen +// consecutive bytes). // -// The permute is what makes the LDS-free form worth having. Reading checkpoint order directly, -// this kernel is slower than an LDS-staged one on every shape; with the permute it is faster than -// the LDS-staged form on every shape, at both ends of the M range. It also moves the tuning: the -// fastest configs are the ones with deeper split-K (SK 4-8) and NPW 2, which only pay once the -// weight read coalesces. +// Two activation scale grids, as in r4d_gemm_mxfp4a8_tiled.hip: one f32 per row (ABLK=false) or +// one per (row, 128 of K) (ABLK=true). With ABLK each wave carries its partial sums in units of the +// current block's scale, rescaling by s_prev / s_next at each boundary. Split-K segments end in +// different blocks, so each partial is multiplied by its last scale before the LDS reduction, and +// the epilogue applies only the weight's reference factor. // -// The E8M0 scales are left in [K/32][N] order -- a half-wave reads sixteen consecutive bytes of -// those already. +// Benchmarking note: a weight of tens of MB streamed in a loop stays Infinity-Cache resident, so +// such a bandwidth figure can exceed the DRAM roofline. // -// TWO ACTIVATION SCALE GRIDS, as in r4d_gemm_mxfp4a8_tiled.hip: one f32 per row (ABLK=false), or -// one per (row, 128 of K) (ABLK=true, the block-scaled fp8 family's grid). With ABLK each wave -// carries its partial sums in units of the current 128-block's scale and rescales them by -// s_prev / s_next at each block boundary inside its split-K segment. The segments end in -// DIFFERENT blocks, so each partial is brought back to absolute units -- multiplied by its own -// last scale -- before the LDS reduction adds them, and the epilogue applies only the weight's -// reference factor. -// -// TRAP FOR ANYONE MEASURING THIS KERNEL: a weight of tens of megabytes streamed in a loop is -// Infinity-Cache resident on this part, so a bandwidth figure taken that way can read above the -// DRAM roofline. It ranks kernels reading the same bytes; it is not achieved DRAM bandwidth. -// -// A IS NOT STAGED IN LDS. A lane's A fragment is eight consecutive bytes of one row, so the -// global load already has the shape the fragment wants; staging it would cost LDS, a barrier and a -// second read for nothing. Rows past M are CLAMPED rather than masked -- a tile past M recomputes -// the last valid row and the store discards it -- which keeps the inner loop branch-free. +// A is not staged in LDS: a lane's A fragment is eight consecutive bytes of one row. Rows past M are +// clamped, not masked, keeping the inner loop branch-free. #include "r4d_gemm_args.h" #include "r4d_common.h" #include "r4d_mxfp4.h" @@ -99,8 +63,8 @@ typedef int v2i __attribute__((ext_vector_type(2))); typedef unsigned uint2v __attribute__((ext_vector_type(2))); -// Eight e2m1 codes (four packed bytes) -> the B fragment, eight e4m3 bytes in k order with the -// block's exponent difference folded in (r4d_mxfp4.h, shared with the other two MXFP4 kernels). +// Eight e2m1 codes (four packed bytes) -> the B fragment: eight e4m3 bytes in k order with the +// block's exponent difference folded in (r4d_mxfp4.h). __device__ __forceinline__ v2i r4d_mxfp4_frag8(unsigned int wv, int d) { unsigned int lo, hi; r4d_mxfp4_unpack8(wv, d, &lo, &hi); @@ -130,11 +94,9 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel( #pragma unroll for (int i = 0; i < MT; i++) acc[j][i] = (v8f)(0.f); - // Column tiles this wave owns, CLAMPED to the last real tile. grid.x rounds N/16 up to a - // multiple of ncols = WV*NPW, so the tail block addresses tiles that do not exist -- at N=48 - // with ncols=4 it reaches tile 3 of 3. Clamping the TILE (not just the row) matters because the - // weight is indexed by tile: an unclamped tile index walks off the end of the buffer, which is a - // GPU memory fault rather than a wrong answer. The epilogue still drops these columns. + // Column tiles this wave owns, clamped to the last real tile: grid.x rounds N/16 up to a multiple + // of WV*NPW, and the weight is indexed by tile, so an unclamped index would fault. The epilogue + // drops these columns. const int ntmax = N / 16 - 1; int wtile[NPW], wrow[NPW]; unsigned char wref[NPW]; @@ -149,7 +111,7 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel( const unsigned int* __restrict__ Wp = (const unsigned int*)W; const int ksteps = K / 16; - // ABLK: the scale each accumulator row of this lane is carried in -- row (mt0+i)*16 + mhalf + e. + // ABLK: the scale each accumulator row of this lane is carried in (row (mt0+i)*16 + mhalf + e). float scur[ABLK ? MT : 1][8]; if constexpr (ABLK) { #pragma unroll @@ -196,9 +158,7 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel( #pragma unroll for (int j = 0; j < NPW; j++) { const int n = wrow[j]; - // Fragment-order weight: lane l's four bytes for this (n-tile, k-step) sit at slot l, so the - // wave reads 128 contiguous bytes. In checkpoint order these would be sixteen rows K/2 bytes - // apart -- a fully strided read on the operand that dominates traffic. + // Fragment-order weight: lane l's four bytes for this (n-tile, k-step) are at slot l. const unsigned int wv = Wp[((size_t)wtile[j] * ksteps + kstep) * WAVE32 + lane]; const v2i wf = r4d_mxfp4_frag8(wv, r4d_mxfp4_fold_d(wref[j], Ws[(size_t)blk * ldws + n])); #pragma unroll @@ -223,10 +183,9 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel( // One pass over the block's 256-element tiles; every thread takes a stride. for (int t = tid; t < ncols * 256; t += blockDim.x) { const int col = t >> 8, off = t & 255; - // off = lane*8 + e, so the lane is off>>3 -- but a lane's N index is lane&15, and its - // eight accumulator elements are the M values 8*(lane>>4)+e. Using the whole lane id for N - // writes the upper half-wave into the NEXT column tile; it is invisible for M <= 8 because - // those rows are then out of range and dropped by the guard below. + // off = lane*8 + e. A lane's N index is lane&15 and its eight elements are M rows + // 8*(lane>>4)+e; using the whole lane id for N would write the upper half-wave into the + // next column tile. const int n = (blockIdx.x * ncols + col) * 16 + ((off >> 3) & 15); const int m = (mt0 + i) * 16 + ((off >> 7) << 3) + (off & 7); if (n >= N || m >= M) continue; @@ -245,9 +204,8 @@ extern "C" void r4d_gemm_mxfp4a8_nt_m64(long a, long ascale, long wq, long ws, l int M, int K, int N, int WV, int SK, int MB, int NPW, int as_group, int as_rs, long stream, int lda, int ldws, int ldc) { - // The operands of one PART of a partitioned weight (ParoQuant) are windows of larger planes: - // the activation a row of lda bytes, the exponents a row of ldws, the output a row of ldc. - // 0 is the plane's own width, which is every other caller. + // A part of a partitioned weight (ParoQuant) reads windows of larger planes: activation rows of + // lda bytes, exponent rows of ldws, output rows of ldc. 0 means the plane's own width. if (!lda) lda = K; if (!ldws) ldws = N; if (!ldc) ldc = N; @@ -304,8 +262,7 @@ extern "C" void r4d_gemm_mxfp4a8_nt_m64(long a, long ascale, long wq, long ws, l // ============================================================== the plugin ABI entry points // -// The operand reader and the split law are in r4d_gemm_args.h. See libr4d/r4d_args.h for why there -// is no adapter directory between the core and these launches. +// The operand reader and the split law are in r4d_gemm_args.h; see libr4d/r4d_args.h. extern "C" int r4d_rad_gemm_mxfp4a8_m64(const RadArgs* a, RadStream s) { GemmOps g; int rc = gemm_ops(a, &g, 1, /*parts=*/1); @@ -313,9 +270,8 @@ extern "C" int r4d_rad_gemm_mxfp4a8_m64(const RadArgs* a, RadStream s) { if (g.N % 16) return R4D_NO(RAD_E_SHAPE); if (g.M > r4d_gemm_mxfp4a8_nt_m64_max_m()) return R4D_NO(RAD_E_SHAPE); if (!g.ascale) return R4D_NO(RAD_E_INVAL); - /* The per-row reference exponent is a weight aux stream and RadArgs has no way to deliver one, - * so gemm_nt_q carries it as a trailing optional weight operand. Without it the fold has no - * reference and every element would be scaled against zero. */ + /* The per-row reference exponent arrives as gemm_nt_q's trailing optional operand (RadArgs + * cannot carry a weight aux stream); the fold needs it. */ if (!g.bref) return R4D_NO(RAD_E_INVAL); MxParts mp; rc = mx_parts(a, &g, &mp); diff --git a/libr4d/r4d_gemm_mxfp4a8_tiled.hip b/libr4d/r4d_gemm_mxfp4a8_tiled.hip index f5a0ec95..54a4ee88 100644 --- a/libr4d/r4d_gemm_mxfp4a8_tiled.hip +++ b/libr4d/r4d_gemm_mxfp4a8_tiled.hip @@ -1,74 +1,52 @@ -// r4d_gemm_mxfp4a8_tiled.hip - r4d_gemm_mxfp4a8_tiled: the OCP-MXFP4 x fp8 GEMM for PREFILL row -// counts, gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T with the same operands, the same weight -// layout and the same fold as r4d_gemm_mxfp4a8_nt_m64 and r4d_gemm_mxfp4a8_decode -- the band -// above theirs. +// r4d_gemm_mxfp4a8_tiled.hip - r4d_gemm_mxfp4a8_tiled: the OCP-MXFP4 x fp8 GEMM for prefill row +// counts, gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T with the operands, weight layout and fold +// of r4d_gemm_mxfp4a8_nt_m64 and r4d_gemm_mxfp4a8_decode, for the band above theirs. // -// WHY A SEPARATE KERNEL. The decode kernels give a block at most 128 rows, so at prefill they -// would re-read the whole weight ceil(M/128) times. Here a block is a 256 x (32*TN) tile and each -// weight byte is unpacked once per K slab into LDS, where all four row-waves of the block read it. +// The decode kernels cover at most 128 rows per block, so at prefill they would re-read the weight +// ceil(M/128) times. Here a block is a 256 x (32*TN) tile and each weight byte is unpacked once per +// K slab into LDS, shared by the block's four row-waves. // -// A COMES STRAIGHT FROM GLOBAL INTO REGISTERS, NOT THROUGH LDS. Staging A through LDS costs a -// write, a barrier and a second read of the operand the block uses most, and a WMMA A fragment -- -// lane l holds row l%16, k-bytes 8*(l/16)..+8 of a 16 x 16 tile -- is 16 rows apart in a row-major -// plane, so it cannot be loaded straight from one either. So A is re-tiled first, into the op's -// scratch, in FRAGMENT ORDER: +// A goes from global straight into registers. A WMMA A fragment (lane l holds row l%16, k-bytes +// 8*(l/16)..+8) spans 16 rows of a row-major plane, and staging it through LDS would cost a write, +// a barrier and a second read. So A is first re-tiled into the op's scratch in fragment order: // // AT[((m/16) * (K/16) + k/16) * 256 + ((m%16) + 16 * ((k/8)%2)) * 8 + k%8] = A[m][k] // -// One 16 x 16 fragment is 256 contiguous bytes and a lane's eight are one aligned 8-byte load, so -// every A fragment a wave needs for a slab issues as one clause of global loads off a wave-uniform -// base (SGPR, the SADDR form) and is consumed at the WMMAs. The re-tile is one read and one write -// of A -- tens of microseconds at a 2048-row chunk against the hundreds the A-direct loop saves on -// every large projection -- and it is the op's own, so no producer has to know about the layout. -// Rows past M in the last fragment are written as zeros; they only reach accumulators the -// epilogue drops. +// A fragment is 256 contiguous bytes and a lane's eight are one aligned 8-byte load, so a slab's A +// fragments issue as one clause of global loads off a wave-uniform SGPR base (SADDR form). The +// re-tile costs one read and write of A, far less than it saves on large projections, and is +// internal to the op. Rows past M in the last fragment are written as zeros. // -// THE WEIGHT AND THE FOLD ARE THE SKINNY KERNEL'S. It reads the fragment-order weight that -// r4d_rad_layout_mxfp4 stores and folds each block's exponent into the e4m3 value through the -// table in r4d_mxfp4.h, so all three MXFP4 kernels produce the same e4m3 byte for every element. -// The table is copied to LDS once per block: read from global it would be a dependent load issued -// behind the A fragments, and the in-order load counter would make the fold wait for all of them. -// 2^(Wref[n]-127) is applied once in the epilogue next to the activation's scale; see -// r4d_gemm_mxfp4a8_nt_m64.hip for the fold and its error analysis. +// Weight and fold as in the skinny kernel: the fragment-order weight from r4d_rad_layout_mxfp4, +// folded through r4d_mxfp4.h's table, so all three MXFP4 kernels produce identical e4m3 bytes. The +// table is copied to LDS per block; from global it would be a dependent load behind the A +// fragments, and the in-order load counter would make the fold wait for all of them. +// 2^(Wref[n]-127) is applied in the epilogue (see r4d_gemm_mxfp4a8_nt_m64.hip). // -// THE TILE. 8 waves as 4 (M) x 2 (N); a wave owns TM=4 x TN accumulator fragments, so the block -// covers BMF = 4*4*16 = 256 rows and BNF = 2*TN*16 columns. The tall tile is for reuse: every -// weight byte staged is multiplied against 256 rows. TN is the axis that depends on M. Widening -// N halves the column-block count while BMF still masks most of a short M, so TN=4 wins only on -// long prompts; on a 17408x5120 weight the two cross near M=2048. Hence tn=0, the default, picks -// TN=4 from M >= 2048 and TN=2 below. The K slab is 128 at TN=2 and 64 at TN=4 (and 64 at TN=2 -// when K is not a multiple of 128): TN=4 holds twice the accumulators, and a 128 slab's A -// fragments on top of them would cost occupancy. +// Tile: 8 waves as 4 (M) x 2 (N), each owning TM=4 x TN fragments, so a block covers BMF = 256 +// rows and BNF = 2*TN*16 columns. TN=4 halves the column-block count and only wins on long prompts +// (crossover near M=2048 on a 17408x5120 weight), so tn=0 picks TN=4 from M >= 2048. The K slab is +// 128 at TN=2 (64 if K % 128 != 0) and 64 at TN=4, which holds twice the accumulators. // -// BARRIERS FENCE LDS ONLY. __syncthreads() is a workgroup acquire/release over every address -// space, which drains the global load counter at each barrier. Nothing in global memory is -// shared between the block's waves, so the barrier is scoped to LDS and the next slab's A loads -// stay in flight across it. +// Barriers fence LDS only: __syncthreads() also drains the global load counter, and nothing in +// global memory is shared between the waves, so the next slab's A loads stay in flight. // -// STAGING IS CLAMPED, NEVER PREDICATED. A bounds-predicated load lands in its own exec-mask -// region and the compiler then cannot carry a counted s_wait_loadcnt across the merge. Clamped -// (a tile past M reads the last real tile, a weight row past N the last aligned group), a slab's -// loads issue back to back; the epilogue drops what they computed. +// Staging is clamped, never predicated: a predicated load gets its own exec-mask region and the +// compiler cannot carry a counted s_wait_loadcnt across the merge. Clamped loads (tile past M -> +// last real tile, row past N -> last aligned group) issue back to back; the epilogue drops them. // -// THE ACCUMULATOR IS C TRANSPOSED. The WMMA takes the weight fragment as its A operand and the -// activation fragment as its B operand -- the two have the same register layout, so this is only -// an argument order -- and computes C^T: a lane's accumulator for (M fragment i, N fragment j) -// holds ONE row and eight consecutive columns. So a row's activation scale is one value a lane -// for each of its TM rows, and the epilogue writes each (i, j) as one 16-byte store. +// The accumulator is C transposed: the WMMA takes the weight fragment as A and the activation as B +// (same register layout), so a lane's accumulator for (i, j) holds one row and eight consecutive +// columns. A lane needs one activation scale per row, and each (i, j) is one 16-byte store. // -// TWO ACTIVATION SCALE GRIDS. `a_scale` is either one f32 per row (ABLK=false) or one per (row, -// 128 of K) (ABLK=true: the block-scaled fp8 family's grid, which every fused producer in -// arch/common writes). Per-block scales vary along K and so cannot wait for the epilogue. The -// accumulator is carried IN UNITS OF THE CURRENT BLOCK'S SCALE: at each 128 boundary every row's -// partial sum is multiplied by s_prev / s_next, and the epilogue applies the last block's scale -- -// one multiply per accumulator element per 128 of K, ~K/128 fp32 ulps of extra rounding. The -// ratio is computed once a row: thread t owns row t of the block, loads the next boundary's two -// scales a boundary early (no slab waits on a scale load) and writes the ratio to LDS, and a lane -// reads one ratio for each of its TM rows. +// Two activation scale grids: one f32 per row (ABLK=false) or one per (row, 128 of K) (ABLK=true, +// as every fused producer in arch/common writes). With ABLK the accumulator is carried in units of +// the current block's scale: at each 128 boundary every row is multiplied by s_prev / s_next +// (~K/128 fp32 ulps of extra rounding), and the epilogue applies the last scale. Thread t owns row +// t of the block, loads the next boundary's two scales a boundary early and writes the ratio to +// LDS; a lane reads one ratio per row. // -// TRAP FOR ANYONE MEASURING THIS KERNEL: the same as the skinny kernel's. A weight of tens of -// megabytes streamed in a loop is Infinity-Cache resident on this part, so a bandwidth figure -// taken that way reads above the DRAM roofline. +// Benchmarking note: as for the skinny kernel, a looped weight stays Infinity-Cache resident. #include "r4d.h" #include "r4d_gemm_args.h" #include "r4d_common.h" @@ -91,14 +69,7 @@ typedef int mxt_v2i __attribute__((ext_vector_type(2))); typedef unsigned mxt_u2 __attribute__((ext_vector_type(2))); typedef unsigned mxt_u4 __attribute__((ext_vector_type(4))); -static __device__ __forceinline__ void mxt_lds_barrier() { - __builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "local"); - __builtin_amdgcn_s_barrier(); - __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup", "local"); -} - -// The re-tile: one thread per 8-byte slot of the fragment-ordered plane, so the writes are -// contiguous and each lane reads one 8-byte group of one row. +// The re-tile: one thread per 8-byte slot of the fragment-ordered plane; writes are contiguous. __global__ __launch_bounds__(256) void r4d_mxfp4a8_tile_a_kernel( const unsigned char* __restrict__ A, unsigned char* __restrict__ AT, int M, int K, long long slots, int lda) { @@ -139,8 +110,8 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel( if (tid < 32) sMag[tid] = (&kMxfp4Mag[0][0])[tid]; - // One A base per M fragment: wave-uniform, so readfirstlane keeps it in an SGPR and every load - // takes the SADDR form with a 32-bit lane offset. A tile past M reads the last real one. + // One A base per M fragment, wave-uniform: readfirstlane keeps it in an SGPR so loads take the + // SADDR form with a 32-bit lane offset. A tile past M reads the last real one. const unsigned char* abase[TM]; #pragma unroll for (int i = 0; i < TM; ++i) { @@ -176,19 +147,18 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel( #pragma unroll for (int j = 0; j < TN; ++j) acc[i][j] = (v8f)(0.f); - // ABLK, once a row: thread t owns row m0 + t (BMF == NTHR) and loads the next 128 boundary's two - // scales -- the block that starts there and the one before it -- a boundary early. + // ABLK: thread t owns row m0 + t (BMF == NTHR) and loads the next 128 boundary's two scales (the + // block starting there and the one before it) a boundary early. const int trow = m0 + tid < M ? m0 + tid : M - 1; const float* __restrict__ asrow = As + (size_t)trow * as_rs; float ns = 0.f, np = 0.f; const unsigned int* __restrict__ Wp = (const unsigned int*)W; - mxt_lds_barrier(); // sMag + lds_barrier(); // sMag for (int k0 = 0; k0 < K; k0 += LBK) { - // ABLK: a new 128-wide activation block starts with this slab; each row's ratio goes to LDS, - // published by the staging barrier below (sR's previous readers were behind the last slab's - // closing barrier). A zero block keeps the carried scale; a zero block before this one sends - // the carried scale back to the grid, which only an all-zero activation block ever does. + // ABLK: at a 128 boundary each row's ratio goes to LDS, published by the staging barrier below + // (sR's previous readers finished before the last slab's closing barrier). A zero block keeps + // the carried scale; after a zero block the carried scale is looked up from the grid. const bool bnd = ABLK && k0 && (k0 & 127) == 0; if constexpr (ABLK) { if (bnd) @@ -231,7 +201,7 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel( *(mxt_u2*)(&sW[(wrow[it] + q) * STR + wkloc[it]]) = mxt_u2{lo, hi}; } } - mxt_lds_barrier(); + lds_barrier(); if constexpr (ABLK) { // Re-express each row's partial sum in the new block's scale: one ratio a lane a row. @@ -261,8 +231,8 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel( const unsigned char* p = &sW[(wn * TN * 16 + j * 16 + col) * STR + kk]; wf[j][0] = *(const int*)p; wf[j][1] = *(const int*)(p + 4); } - // One step's W fragments live at a time: without the fence the compiler hoists every - // step's loads above the first WMMA and holds them all. + // Keep one step's W fragments live at a time; otherwise the compiler hoists every step's + // loads above the first WMMA. __builtin_amdgcn_sched_barrier(0); #pragma unroll for (int i = 0; i < TM; ++i) @@ -271,17 +241,17 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel( acc[i][j] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf[j], af[i][step], acc[i][j]); } - mxt_lds_barrier(); + lds_barrier(); } - // Epilogue. A lane holds row m0 + 64*wm + 16i + col of M fragment i and eight consecutive columns of N fragment - // j, so each (i, j) is one 16-byte store. 2^(Wref[n]-127) is exactly the float whose exponent - // field is Wref[n]; N % 16 == 0 keeps a lane's eight columns all inside N or all outside it. + // Epilogue. A lane holds row m0 + 64*wm + 16i + col of M fragment i and eight consecutive columns + // of N fragment j, one 16-byte store per (i, j). 2^(Wref[n]-127) is the float whose exponent + // field is Wref[n]; N % 16 == 0 keeps a lane's eight columns all inside or all outside N. float sc[TM]; if constexpr (ABLK) { // the scale each row ends in, once a row; the K loop's closing barrier retired the ratio reads sR[tid] = r4d_mxfp4_carried(asrow, (K - 1) >> 7); - mxt_lds_barrier(); + lds_barrier(); #pragma unroll for (int i = 0; i < TM; ++i) sc[i] = sR[wm * TM * 16 + i * 16 + col]; } else { @@ -341,8 +311,8 @@ extern "C" void r4d_gemm_mxfp4a8_tiled(long at, long ascale, long wq, long ws, l if (N < 16 || N % 16) throw std::runtime_error("r4d gemm_mxfp4a8_tiled: N must be a multiple of 16"); if (K < R4D_MXT_KUNIT || K % R4D_MXT_KUNIT) throw std::runtime_error("r4d gemm_mxfp4a8_tiled: K must be a multiple of 64"); - // tn=0: TN=4 from the M crossover on, unless its 128-wide tile leaves the grid short of 128 - // blocks (a narrow N): there the TN=2 grid's extra blocks win. + // tn=0: TN=4 from the M crossover on, unless its 128-wide tile leaves fewer than 128 blocks + // (narrow N), where TN=2's extra blocks win. if (TN == 0) TN = M >= R4D_MXT_TN4_MIN_M && (long)((N + 127) / 128) * ((M + R4D_MXT_BMF - 1) / R4D_MXT_BMF) >= 128 ? 4 : 2; @@ -372,17 +342,15 @@ extern "C" void r4d_gemm_mxfp4a8_tiled(long at, long ascale, long wq, long ws, l } // ============================================================== the plugin ABI entry point -// The row-major activation is re-tiled into the op's scratch, then the GEMM reads it from there. -// A partitioned weight re-tiles each part's copy of the activation into the scratch in turn and -// runs the GEMM over that part's rows (mx_parts). +// The row-major activation is re-tiled into the op's scratch and the GEMM reads it there. For a +// partitioned weight (mx_parts), each part's activation copy is re-tiled and multiplied in turn. extern "C" int r4d_rad_gemm_mxfp4a8_tiled(const RadArgs* a, RadStream s) { GemmOps g; int rc = gemm_ops(a, &g, 1, /*parts=*/1); if (rc != RAD_OK) return rc; if (g.N < 16 || g.N % 16) return R4D_NO(RAD_E_SHAPE); if (!g.ascale) return R4D_NO(RAD_E_INVAL); - /* The per-row reference exponent, as in r4d_rad_gemm_mxfp4a8_m64: without it the fold has no - * reference and every element would be scaled against zero. */ + /* The per-row reference exponent is required, as in r4d_rad_gemm_mxfp4a8_m64. */ if (!g.bref) return R4D_NO(RAD_E_INVAL); MxParts mp; rc = mx_parts(a, &g, &mp); @@ -410,9 +378,9 @@ extern "C" int r4d_rad_gemm_mxfp4a8_tiled(const RadArgs* a, RadStream s) { return RAD_OK; } -/* The core sizes the op's scratch from this, at the band's widest M: the fragment-tiled copy of - * the activation, whole 16-row fragments. One copy for every part: the parts run one after another - * on the op's stream, so a part's re-tile cannot overtake the previous part's GEMM. */ +/* The op's scratch, sized at the band's widest M: the fragment-tiled activation in whole 16-row + * fragments. One copy serves every part: parts run in order on the op's stream, so a re-tile + * cannot overtake the previous part's GEMM. */ extern "C" int64_t r4d_rad_gemm_mxfp4a8_tiled_scratch(const RadArgs* a) { const long long M = r4d_geti_or(a, "M", 0), K = r4d_geti_or(a, "K", 0); return (int64_t)r4d_mxfp4a8_tile_a_bytes((int)M, (int)K); diff --git a/libr4d/r4d_gemm_w2a8_nt.hip b/libr4d/r4d_gemm_w2a8_nt.hip index 3ccb2f73..f8beae18 100644 --- a/libr4d/r4d_gemm_w2a8_nt.hip +++ b/libr4d/r4d_gemm_w2a8_nt.hip @@ -1,39 +1,31 @@ // r4d_gemm_w2a8_nt.hip - r4d_gemm_w2a8_nt: 2-bit-weight, 8-bit-activation skinny GEMM, gfx1201. // C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T with A quantised per row and W asymmetric per (row, group). // -// WHAT IT IS FOR. The DFlash2 draft head is `x[M,5120] @ W[124160,5120]^T` at two bits, run once -// per decode step. Its 178.8 MB weight puts a one-pass memory floor near 280 us; at M = 64 its -// 64 x 124160 x 5120 MACs cost around 815 us on the f16 WMMA at 207 TF/s, which is the rate a bf16 -// dequant form (`0x3F80 | v<<5`) runs at. So a bf16 form is COMPUTE bound once several sequences -// are in flight, not memory bound. The same codes on v_wmma_i32_16x16x16_iu8 at 407 TF/s put the -// compute floor near 200 us, under the memory floor, so this kernel is a stream at both ends of -// the M range. +// Used for the DFlash2 draft head, `x[M,5120] @ W[124160,5120]^T` at two bits, once per decode +// step. Its 178.8 MB weight gives a memory floor near 280 us. A bf16 dequant form runs on the f16 +// WMMA (207 TF/s) and is compute bound at M = 64 (~815 us); v_wmma_i32_16x16x16_iu8 at 407 TF/s +// puts the compute floor near 200 us, under the memory floor, across the M range. // -// STRUCTURE AND ACTIVATION ARE r4d_gemm_w4a8_nt_m64's: same 512-byte -// packed block (32 lanes x 16 bytes), same permuted int8 activation from r4d_quant_act_i8_asum, -// same [K/group][Mpad] group-major activation sums, same split-K reduction, same per-row scale -// applied once at the store. A packed block covers 128 K here instead of 64, because the code is -// half as wide. +// Structure and activation as r4d_gemm_w4a8_nt_m64: 512-byte packed block (32 lanes x 16 bytes), +// permuted int8 activation from r4d_quant_act_i8_asum, [K/group][Mpad] group-major activation sums, +// split-K reduction, per-row scale at the store. A packed block covers 128 K (64 for 4-bit). // -// THE UNPACK PUTS THE CODE IN THE BYTE'S HIGH TWO BITS. For q in 0..3 the byte 64*q is exactly -// the UNSIGNED int8 of 64*q, so +// The unpack puts the code in the byte's high two bits; for q in 0..3 the byte 64*q is the +// unsigned int8 of 64*q: // // t0 = (w << 6) & 0xC0C0C0C0 bytes <- fields 0, 4, 8, 12 // t1 = (w << 4) & 0xC0C0C0C0 bytes <- fields 1, 5, 9, 13 // t2 = (w << 2) & 0xC0C0C0C0 bytes <- fields 2, 6, 10, 14 // t3 = w & 0xC0C0C0C0 bytes <- fields 3, 7, 11, 15 // -// is the whole dequant: seven instructions per dword, which is two 16x16x16 fragments, and the -// factor of 64 folds into the group scale at the store. Fragment 2d+0 is (t0, t1) and 2d+1 is -// (t2, t3), so element e of fragment h reads field 4*(e&3) + (e>>2) + 2h of dword d -- which is -// what the packer writes and nothing else has to know. +// Seven instructions per dword (two 16x16x16 fragments); the factor 64 is removed at the store. +// Fragment 2d+0 is (t0, t1) and 2d+1 is (t2, t3), so element e of fragment h reads field +// 4*(e&3) + (e>>2) + 2h of dword d, as the packer writes it. // -// WHY UNSIGNED, AND WHAT IT COSTS. Four levels are not enough for a symmetric grid: the draft -// head's quantiser is asymmetric per (row, group of 128), w ~= sc*(q - zp), and 16*nibble-style -// offset binary is affine in the code where two's complement is affine only on each half of the -// range. So the WMMA reads B unsigned and the zero point comes out afterwards as -// sc*( - zp*sum a), with the group's activation sum loaded from Asum. That is the same -// arrangement r4d_gemm_w4a8_asym_nt_m64 uses, and the same quantiser produces both. +// Unsigned because four levels are too few for a symmetric grid: the quantiser is asymmetric per +// (row, group of 128), w ~= sc*(q - zp). The WMMA reads B unsigned and the zero point is removed +// as sc*( - zp*sum a) with the group's activation sum from Asum, as in +// r4d_gemm_w4a8_asym_nt_m64. #include "r4d.h" #include "r4d_gemm_args.h" #include "r4d_common.h" @@ -43,9 +35,6 @@ #include #include -#ifndef R4D_GEMM_W2A8_GROUP -#define R4D_GEMM_W2A8_GROUP 128 // K per (scale, zero) pair -#endif #define R4D_GEMM_W2A8_KPB 128 // K per packed block: 8 k steps, 16 bytes per lane #define WAVE32 32 @@ -81,13 +70,10 @@ __device__ __forceinline__ v8i w2_mmai(v2i a, v2i b, v8i c) { return __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(true, a, false, b, c, false); } -// __launch_bounds__ HAS TO SEE MT, NOT JUST NPW. A block cannot exceed 1024 threads, but this -// kernel's accumulators scale with MT * NPW: at MT=4 the two arrays alone are 8*MT*NPW VGPRs and -// the group's activation sums are another 8*MT. Telling the compiler 1024 makes it budget for 32 -// waves on ONE workgroup, which on this part is 1536/32 = 48 VGPRs per wave, so every MT=4 config -// spills hard enough that MB=2 -- which reads the WHOLE WEIGHT TWICE at M=64 -- is faster than any -// of them. The bound has to be what the config can actually run, and an MT=4 config can never run -// 32 waves. The same rule, on NPW alone, is in r4d_gemm_w4a8_nt_m64. +// __launch_bounds__ depends on MT as well as NPW. Accumulators are 8*MT*NPW VGPRs per array plus +// 8*MT for the activation sums; a bound of 1024 budgets 1536/32 = 48 VGPRs per wave, and every MT=4 +// config then spills badly. The bound must be what the config can run. r4d_gemm_w4a8_nt_m64 has +// the same rule on NPW alone. #define R4D_W2A8_BOUNDS(MT, NPW) \ ((MT) >= 4 ? 256 : (((MT) >= 2 || (NPW) >= 4) ? 512 : 1024)) @@ -137,18 +123,12 @@ __global__ __launch_bounds__(R4D_W2A8_BOUNDS(MT, NPW)) void r4d_gemm_w2a8_nt_ker (size_t)(t * nsz + kbase / R4D_GEMM_W2A8_GROUP) * 16 + (lane & 15); } - // PREFETCHING THE NEXT GROUP'S WEIGHT IS A LOSS, and the MB=4 configs it would most help -- - // they read the weight once where MB=2 reads it twice -- lose the most by it. One more uint4v - // a column tile is four more VGPRs on a kernel already at 214, and a wave fewer per SIMD costs - // more latency cover than the prefetch buys. The same holds in r4d_gemm_w4a8_nt_m64. + // No next-group weight prefetch: four more VGPRs per column tile on a kernel at 214 costs a wave + // per SIMD, which loses more latency cover than the prefetch gains (likewise in w4a8_nt_m64). for (int g = 0; g < groups; g++) { - // TWO FMAs, NOT A MUL-SUB-FMA. Written as fmaf(g_acc - z64*asum, sc, acc) the compiler emits - // v_mul + v_sub + v_fma_mix per accumulator element -- three instructions on top of the - // v_cvt, 238 VALU a group against 512 cycles of WMMA. Splitting the group's contribution - // into sc*g_acc and (-sc*z64)*asum makes both halves plain f32 FMAs into the same - // accumulator, which is one instruction less and a VOPD pair rather than a mixed-precision - // op. The scale is converted to f32 once a group here instead of riding into every - // v_fma_mix as an f16. + // Two f32 FMAs, sc*g_acc and (-sc*z64)*asum, rather than fmaf(g_acc - z64*asum, sc, acc), + // which compiles to v_mul + v_sub + v_fma_mix per element. This saves an instruction and + // pairs as VOPD; the scale is converted to f32 once per group. float sc[NPW], scz[NPW]; #pragma unroll for (int j = 0; j < NPW; j++) { @@ -157,15 +137,14 @@ __global__ __launch_bounds__(R4D_W2A8_BOUNDS(MT, NPW)) void r4d_gemm_w2a8_nt_ker const float nz = __half2float(__ushort_as_half((unsigned short)(sz >> 16))); scz[j] = -sc[j] * (64.f * (-nz - 1024.f)); } - // Element e of tile i at this lane is output row (mt0+i)*16 + 8*(lane>>4) + e, so the eight - // rows a lane needs are contiguous at a fixed group -- which is why Asum is [G][Mpad]. + // Element e of tile i at this lane is output row (mt0+i)*16 + 8*(lane>>4) + e, so a lane's + // eight rows are contiguous at a fixed group; hence Asum is [G][Mpad]. float asum[MT][8]; { const size_t gi = (size_t)(kbase / R4D_GEMM_W2A8_GROUP + g) * Mpad; #pragma unroll for (int i = 0; i < MT; i++) { - // Clamped: MB past the number of row tiles is a legal config, and rows past M produce - // results the store discards -- but an unclamped read here is a page fault, not garbage. + // Clamped: MB may exceed the row tiles, and an unclamped read could fault. int rb = (mt0 + i) * 16 + 8 * (lane >> 4); rb = rb < Mpad - 8 ? rb : Mpad - 8; const v4f* pv = (const v4f*)(Asum + gi + rb); @@ -251,13 +230,9 @@ void r4d_gemm_w2a8_nt(long a, long ascale, long wq, long ws, long asum, long c, if (K % (SK * R4D_GEMM_W2A8_GROUP)) throw std::runtime_error("r4d gemm_w2a8_nt: K must be divisible by SK*group"); if (!asum) throw std::runtime_error("r4d gemm_w2a8_nt: asum is required"); - if (WV * SK * WAVE32 > 1024) throw std::runtime_error("r4d gemm_w2a8_nt: threads/block > 1024"); - // __launch_bounds__ is a MAXIMUM BLOCK SIZE, not a hint: a block wider than the bound the - // instantiation was compiled with does not run slowly, it fails to launch -- and on this runtime - // that surfaces as `hipErrorLaunchFailure` from whatever unrelated call happens to synchronise - // next. So the launcher has to know the same rule the macro does. - const int bound = (MB >= 4) ? 256 : (((MB >= 2) || (NPW >= 4)) ? 512 : 1024); - if (WV * SK * WAVE32 > bound) + // __launch_bounds__ is a hard maximum: a wider block fails to launch, surfacing as + // hipErrorLaunchFailure at the next sync. + if (WV * SK * WAVE32 > R4D_W2A8_BOUNDS(MB, NPW)) throw std::runtime_error("r4d gemm_w2a8_nt: block wider than this MB/NPW's launch bound"); if (MB < 1 || MB > 4) throw std::runtime_error("r4d gemm_w2a8_nt: MB must be 1..4"); if (NPW != 1 && NPW != 2 && NPW != 4) @@ -297,15 +272,14 @@ int r4d_gemm_w2a8_nt_group(void) { return R4D_GEMM_W2A8_GROUP; } // ============================================================== the plugin ABI entry points // -// The operand reader and the split law are in r4d_gemm_args.h. See libr4d/r4d_args.h for why there -// is no adapter directory between the core and these launches. +// The operand reader and the split law are in r4d_gemm_args.h; see libr4d/r4d_args.h. extern "C" int r4d_rad_gemm_w2a8(const RadArgs* a, RadStream s) { GemmOps g; int rc = gemm_ops(a, &g, 1); if (rc != RAD_OK) return rc; if (g.N % 16) return R4D_NO(RAD_E_SHAPE); if (!g.ascale) return R4D_NO(RAD_E_INVAL); - /* The 2-bit grid is asymmetric by construction, so the group sums are not optional. */ + /* The 2-bit grid is always asymmetric, so the group sums are required. */ if (!g.asum) return R4D_NO(RAD_E_INVAL); const int group = r4d_gemm_w2a8_nt_group(); Cfg c; diff --git a/libr4d/r4d_gemm_w4a16_nt_m64.hip b/libr4d/r4d_gemm_w4a16_nt_m64.hip index 82c758d5..9054c01f 100644 --- a/libr4d/r4d_gemm_w4a16_nt_m64.hip +++ b/libr4d/r4d_gemm_w4a16_nt_m64.hip @@ -1,60 +1,41 @@ // r4d_gemm_w4a16_nt_m64.hip - r4d_gemm_w4a16_nt_m64: 4-bit-weight skinny GEMM for M up to 64, // gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T, f16 A, bf16 C, fp32 accumulate. // -// Same problem and the same decomposition as r4d_gemm_bf16_nt_m64 -- a weight-streaming GEMM whose -// M is a speculative decode batch, so every output element is read once and the whole cost is the -// weight -- with the weight at 4 bits instead of 16. That is the entire point: at M=8 a projection -// moves M*K*2 bytes of activation against N*K bytes of weight, 82 KiB against 44 MiB on the -// drafter's MLP, so the format of the WEIGHT is the only thing in the cost model. +// The decomposition of r4d_gemm_bf16_nt_m64 with the weight at 4 bits. M is a speculative decode +// batch, so the weight dominates the cost (at M=8 on the drafter's MLP: 82 KiB of activation +// against 44 MiB of weight). // -// WHY f16 AND NOT bf16. A 4-bit weight has to be widened to a WMMA input type, and the cheapest -// widening is a byte permute into a fixed exponent: `0x6400 | n` is the f16 for 1024 + n, exactly, -// for every n in 0..15, so four v_perm_b32 turn one dword of eight nibbles into a whole 16x16x16 -// fragment. The quantizer's zero point then has to be subtracted, and gfx1201 has NO packed bf16 -// arithmetic (v_pk_add_bf16 is not an instruction on this part) while v_pk_add_f16 is -- so the -// subtract is four instructions in f16 and would be sixteen in bf16, through f32 and back. Ten -// VALU per fragment against one WMMA leaves the kernel memory-bound over the whole M band; the -// bf16 route does not. Everything the WMMA sees is exact: the activation is an f16 value, the -// weight is a small integer, and the group scale is applied to the f32 accumulator afterwards. +// f16, not bf16: `0x6400 | n` is exactly the f16 for 1024 + n, so four v_perm_b32 turn a dword of +// eight nibbles into a 16x16x16 fragment, and the zero point is subtracted with v_pk_add_f16. +// gfx1201 has no packed bf16 arithmetic, so in bf16 that subtract would be sixteen instructions +// instead of four. The WMMA inputs are exact; the group scale is applied to the f32 accumulator. // -// AND WHY THAT CAPS IT. Widening to f16 reaches the SLOWEST matrix instruction on this part: -// v_wmma_f32_16x16x16_f16 issues at 207 TF/s where v_wmma_i32_16x16x16_iu8 and -// v_wmma_f32_16x16x16_fp8_fp8 both issue at 407-412 and v_wmma_i32_16x16x32_iu4 at 830. Below -// M=32 that costs nothing, because this kernel is at the DRAM roofline there -- 620-648 GB/s on -// this part -- and the arithmetic hides under the weight stream. At M=64 the matrix instruction -// is the whole cost, and r4d_gemm_w4a8_nt_m64 runs the SAME packed weight through the int8 form -// instead. So this kernel owns the small-M band and the int8 one owns the rest. +// The cost is the slowest matrix instruction on this part: v_wmma_f32_16x16x16_f16 at 207 TF/s +// (iu8 and fp8 at 407-412, iu4 at 830). Below M=32 the kernel is at the DRAM roofline (620-648 GB/s) +// and the arithmetic hides; at M=64 r4d_gemm_w4a8_nt_m64 runs the same packed weight through the +// int8 form. This kernel owns the small-M band. // -// WHY THE SCALE IS NOT FOLDED INTO THE FRAGMENT. It is tempting to fold both quantizer parameters -// into one v_pk_fma_f16 -- fma(1024 + n, s, -(1024 + z) * s) -- and drop the per-group epilogue. -// That is wrong by 12%: -(1024 + z) * s is not representable in f16, and the term it cancels is -// ~1024*s against a result of ~4*s, so half an f16 ULP of the addend is an eighth of the answer. -// The subtraction has to happen where 1024 + z is exact, which is the integer grid, and the scale -// has to be applied where the cancellation has already happened, which is the f32 accumulator. +// The scale is not folded into the fragment as fma(1024 + n, s, -(1024 + z) * s): the addend is +// not representable in f16 and cancels ~1024*s against a result of ~4*s, an error of ~12%. The +// subtraction must happen on the integer grid and the scale after the cancellation. // -// THE ACTIVATION IS NOT FREE, EVEN AT M=8. A 16x16x16 fragment covers sixteen ROWS whether M is 8 -// or 64, and every column tile re-reads the whole of A, so a wave that owns one column tile moves -// 16*K*2 bytes of activation against 16*K/2 bytes of weight -- four times as much, out of cache -// rather than DRAM, but four times as many load instructions. NPW (column tiles per WAVE) is the -// answer and it costs no LDS and no barrier: the wave loads one activation fragment and spends it -// on NPW weight fragments, so the ratio falls to 4*MT/NPW. WV still exists and still sets how many -// column tiles a BLOCK covers, but WV alone does nothing for this -- the waves of a block issue -// their own loads and only share through the cache. +// A fragment covers sixteen rows whatever M is, and every column tile re-reads A: one column tile +// per wave moves four times as many activation bytes (from cache) as weight bytes. NPW (column +// tiles per wave) reuses one activation fragment on NPW weight fragments, with no LDS or barrier, +// dropping the ratio to 4*MT/NPW. WV alone does not help: a block's waves share only through cache. // -// LAYOUT. Wq is pre-permuted offline into exactly the order the fragment wants, so a lane's 16 -// bytes are contiguous and a wave's weight load for four k steps is one 512-byte global_load_b128. -// Nothing is staged through LDS on the weight path and nothing is masked: with +// Layout: Wq is pre-permuted offline into fragment order, so a lane's 16 bytes are contiguous and a +// wave's weight load for four k steps is one 512-byte global_load_b128, with no LDS and no mask: // // idx = lane%16 , k = 8*(e>>2) + 4*(lane>>4) + (e&3) (r4d_gdn_wmma.h) // -// fragment element e of lane l is W[n0 + (l&15)][16s + 8*(e>>2) + 4*(l>>4) + (e&3)], and the dword -// holding it stores that value in nibble 2e for e<4 and nibble 2(e-4)+1 for e>=4 -- the order the -// two-mask, four-permute unpack below produces. The packer in radiance_w4.py builds this layout. +// fragment element e of lane l is W[n0 + (l&15)][16s + 8*(e>>2) + 4*(l>>4) + (e&3)], stored in +// nibble 2e for e<4 and nibble 2(e-4)+1 for e>=4, the order the unpack below produces. The packer +// in radiance_w4.py builds this layout. // -// QUANTIZER. Asymmetric, per output channel, per group of R4D_GEMM_W4_GROUP contiguous K: -// w ~= scale * (q - zero) with q in 0..15 and an INTEGER zero, which is what makes the subtract -// exact. Both parameters live in one dword per (row, group): the f16 scale in the low half and the -// f16 of -(1024 + zero) in the high half, ready to be broadcast into a v_pk_add_f16. +// Quantiser: per output channel, per group of R4D_GEMM_W4_GROUP contiguous K: w ~= scale * (q - zero) +// with q in 0..15 and an integer zero, which keeps the subtract exact. One dword per (row, group): +// the f16 scale low and the f16 of -(1024 + zero) high, broadcast into a v_pk_add_f16. #include "r4d.h" #include "r4d_gemm_args.h" #include "r4d_gdn_wmma.h" @@ -64,34 +45,23 @@ #include #define R4D_GEMM_W4_MAX_M 64 -#ifndef R4D_GEMM_W4_GROUP -#define R4D_GEMM_W4_GROUP 128 // K per (scale, zero) pair -#endif #define R4D_GEMM_W4_KPB 64 // K per packed block: 4 k steps, 16 bytes per lane #define WAVE32 32 typedef _Float16 v8h __attribute__((ext_vector_type(8))); typedef unsigned uint4v __attribute__((ext_vector_type(4))); -// NT reads the weight non-temporally. The weight is streamed once per step and never reused, while -// the activation is re-read once per column tile and wants to stay resident, so telling the cache -// not to keep the weight decides which of the two occupies the last level. It is a gain at M=8 and -// M=16 and a LOSS from M=24 up on the shapes with the longest K, so it is per-call, like every -// other geometry parameter, and the table in radiance_w4.py carries the value per M band. -// -// One copy of any of these weights fits this part's 64 MiB last level, so a bench that streams a -// SINGLE buffer in a loop measures a cache-resident machine and cannot see this effect at all; a -// pooled working set is what makes the difference visible. +// NT reads the weight non-temporally so the re-read activation keeps the last level. It wins at +// M=8 and M=16 and loses from M=24 up on the longest-K shapes, so it is per call; radiance_w4.py +// carries the value per M band. A benchmark must use a pooled working set: one weight fits the +// 64 MiB last level, so looping over a single buffer hides the effect. -// NPW (column tiles per WAVE) is a template parameter because it sizes the accumulator array, and a -// launch argument because the right value is a property of M: at M=8 the kernel is at the DRAM -// roofline and NPW>1 only costs blocks, while at M=64 the activation re-read is four times the -// weight and NPW=4 is what claws it back. Instantiated only for the two values that win in -// practice; anything else is rejected rather than silently rounded. +// NPW is a template parameter (it sizes the accumulators) chosen per M: at M=8 NPW>1 only costs +// blocks; at M=64 NPW=4 recovers the activation re-read. Only 1 and 4 are instantiated; anything +// else is rejected. -// Address-space-qualified so the loads stay global_load rather than flat_load: on gfx12 a flat -// load increments dscnt as well as loadcnt, so a later LDS wait would also wait on HBM. See the -// same declaration in r4d_gemm_bf16_nt_m64.hip for why the element type is a scalar there. +// Address-space-qualified so loads stay global_load, not flat_load (on gfx12 a flat load also +// increments dscnt). See r4d_gemm_bf16_nt_m64.hip for why the element type is a scalar. typedef __attribute__((address_space(1))) const uint4v* r4d_gw4; typedef __attribute__((address_space(1))) const unsigned long long* r4d_gu2; typedef __attribute__((address_space(1))) const unsigned* r4d_gu1; @@ -103,41 +73,22 @@ __device__ __forceinline__ v8h fragA(r4d_gu2 p, int u) { return x.f; } -// One dword of eight nibbles -> one 16x16x16 f16 B fragment, minus the zero point. -// t0/t1 split the even and odd nibbles into bytes; each v_perm_b32 pairs two of those bytes with -// the constant high byte 0x64, which is the f16 exponent field for 1024. nz carries -// -(1024 + zero) in BOTH halves so one v_pk_add_f16 corrects a pair. -// The unpack is under a percent of this kernel at M=8, where it is at the DRAM roofline and the -// arithmetic hides in the load latency. It is a real fraction at M=64, but that band belongs to -// r4d_gemm_w4a8_nt_m64 -- and with no dequant at all the f16 form still trails the int8 one there, -// because the gap is the matrix instruction and not the dequant. Nothing here is worth a knob. -#ifndef R4D_GEMM_W4_TWOS -#define R4D_GEMM_W4_TWOS 1 -#endif +// One dword of eight nibbles -> one 16x16x16 f16 B fragment, minus the zero point. t0/t1 split the +// even and odd nibbles into bytes; each v_perm_b32 pairs two of them with the high byte 0x64 (the +// f16 exponent for 1024). nz holds -(1024 + zero) in both halves. -// DO NOT FOLD THE GROUP SCALE INTO THE B FRAGMENT. One v_pk_mul_f16 per pair on the finished -// integer q is exact in f16, removes the second accumulator array entirely and takes the M=64 shape -// from 192 VGPRs to 135 -- and it is SLOWER on most of the drafter's shapes. The multiply lands -// inside the per-fragment dependent chain between the unpack and the WMMA, where the per-group -// epilogue it replaces sits outside it; this kernel is stall-bound, not register-bound. +// Do not fold the group scale into the B fragment. A v_pk_mul_f16 on the integer q is exact and +// saves registers (192 -> 135 VGPRs at M=64), but it is slower on most shapes: it lengthens the +// dependent chain between unpack and WMMA, and this kernel is stall-bound, not register-bound. __device__ __forceinline__ v8h dequant(unsigned w, __half2 nz) { const unsigned K64 = 0x64646464u; -#if R4D_GEMM_W4_TWOS - // The stored nibble is a 4-bit TWO'S COMPLEMENT code, because that is what - // r4d_gemm_w4a8_nt_m64 needs -- it shifts the nibble into the byte's high half and reads the - // byte signed. This kernel wants OFFSET BINARY, so that 1024 + n minus the constant 1024 + 8 - // is the value. The two differ by bit 3 of the nibble, so one XOR per spread dword converts, - // and the zero point is then pinned to 8 for every group. Two instructions per fragment, on - // the kernel whose whole unpack is a fraction of a percent of its time at M=8 -- which is why - // the conversion lives here and not in the int8 kernel, where the unpack is three instructions - // and does matter. One quantised weight, two kernels, dispatched on M. + // The stored nibble is two's complement, which r4d_gemm_w4a8_nt_m64 reads as a signed high + // nibble. This kernel needs offset binary (1024 + n minus 1024 + 8); the two differ in bit 3, so + // one XOR per dword converts and the zero point is 8 for every group. The conversion lives here, + // where the unpack is negligible, rather than in the int8 kernel. const unsigned t0 = (w & 0x0F0F0F0Fu) ^ 0x08080808u; const unsigned t1 = ((w >> 4) & 0x0F0F0F0Fu) ^ 0x08080808u; -#else - const unsigned t0 = w & 0x0F0F0F0Fu; - const unsigned t1 = (w >> 4) & 0x0F0F0F0Fu; -#endif union { unsigned u[4]; __half2 h2[4]; v8h f; } x; x.u[0] = __builtin_amdgcn_perm(K64, t0, 0x05010400u); // nibbles 0, 2 x.u[1] = __builtin_amdgcn_perm(K64, t0, 0x05030402u); // nibbles 4, 6 @@ -152,8 +103,7 @@ __device__ __forceinline__ v8f mmah(v8h a, v8h b, v8f c) { return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c); } -// MT = row tiles per BLOCK, as in the bf16 kernel: more of them amortise the weight fragment and -// its unpack over more WMMA, fewer put more blocks on the machine. +// MT = row tiles per block, as in the bf16 kernel. template __global__ __launch_bounds__(1024) void r4d_gemm_w4a16_nt_m64_kernel( const unsigned short* __restrict__ A, const unsigned* __restrict__ Wq, @@ -176,8 +126,7 @@ __global__ __launch_bounds__(1024) void r4d_gemm_w4a16_nt_m64_kernel( for (int i = 0; i < MT; i++) acc[j][i] = (v8f)(0.f); if (n0 < N) { - // Activation: rows clamped, never masked -- a tile past M re-reads the last valid row and - // computes a result nobody stores. + // Activation rows are clamped, not masked; results past M are never stored. unsigned aoff[MT]; #pragma unroll for (int i = 0; i < MT; i++) @@ -186,8 +135,8 @@ __global__ __launch_bounds__(1024) void r4d_gemm_w4a16_nt_m64_kernel( #pragma unroll for (int i = 0; i < MT; i++) pa[i] = (r4d_gu2)(const unsigned long long*)(A + aoff[i]); - // Weight: one uint4 per lane per four k steps, tiles already permuted, so the whole k loop is - // global_load_b128 with a constant stride and no address arithmetic per step. + // Weight: one uint4 per lane per four k steps, already permuted, so the k loop is + // global_load_b128 at a constant stride. const int kpb = K / R4D_GEMM_W4_KPB; // packed blocks in a full row of tiles const int nsz = K / R4D_GEMM_W4_GROUP; // (scale, zero) dwords per row of tiles r4d_gw4 pw[NPW]; @@ -195,9 +144,7 @@ __global__ __launch_bounds__(1024) void r4d_gemm_w4a16_nt_m64_kernel( const int ntlast = N / 16 - 1; #pragma unroll for (int j = 0; j < NPW; j++) { - // Clamped, like the row tiles: a wave whose last column tiles run past N re-reads the last - // real tile and computes a result the store discards, rather than reading memory it does not - // own or diverging the whole k loop on a mask. + // Column tiles past N are clamped to the last real tile; the store discards them. const int t = (nt0 + j) < ntlast ? (nt0 + j) : ntlast; pw[j] = (r4d_gw4)(const uint4v*)(Wq) + (size_t)(t * kpb + kbase / R4D_GEMM_W4_KPB) * WAVE32 + lane; @@ -218,8 +165,7 @@ __global__ __launch_bounds__(1024) void r4d_gemm_w4a16_nt_m64_kernel( nz[j] = __half2half2(__ushort_as_half((unsigned short)(sz >> 16))); } - // The first WMMA of a group takes an inline zero for C, so the group accumulator costs no - // instruction to clear. + // The first WMMA of a group takes an inline zero for C, so no clear is needed. v8f g_acc[NPW][MT]; #pragma unroll for (int b = 0; b < bpg; b++) { @@ -256,9 +202,8 @@ __global__ __launch_bounds__(1024) void r4d_gemm_w4a16_nt_m64_kernel( } } - // Split-K reduction and store: identical to r4d_gemm_bf16_nt_m64, one row tile at a time so the - // LDS is WV*SK KiB whatever MT is, and in a fixed order over splits so the result does not depend - // on how the waves were scheduled. + // Split-K reduction and store as in r4d_gemm_bf16_nt_m64: one row tile at a time, fixed split + // order. const int ncols = WV * NPW; const int nthreads = WV * SK * WAVE32; #pragma unroll @@ -325,8 +270,7 @@ int r4d_gemm_w4a16_nt_m64_group(void) { return R4D_GEMM_W4_GROUP; } // ============================================================== the plugin ABI entry points // -// The operand reader and the split law are in r4d_gemm_args.h. See libr4d/r4d_args.h for why there -// is no adapter directory between the core and these launches. +// The operand reader and the split law are in r4d_gemm_args.h; see libr4d/r4d_args.h. /* ------------------------------------------------------------------ f16-activation grids */ extern "C" int r4d_rad_gemm_w4a16_m64(const RadArgs* a, RadStream s) { @@ -334,6 +278,8 @@ extern "C" int r4d_rad_gemm_w4a16_m64(const RadArgs* a, RadStream s) { int rc = gemm_ops(a, &g, 1); if (rc != RAD_OK) return rc; if (g.N % 16) return R4D_NO(RAD_E_SHAPE); + /* Any other activation dtype would read plausible but wrong numbers. */ + if (g.a->dtype != RAD_F16) return R4D_NO(RAD_E_DTYPE); if (g.M > r4d_gemm_w4a16_nt_m64_max_m()) return R4D_NO(RAD_E_SHAPE); const int group = r4d_gemm_w4a16_nt_m64_group(); Cfg c; diff --git a/libr4d/r4d_gemm_w4a8_nt_m64.hip b/libr4d/r4d_gemm_w4a8_nt_m64.hip index 55c648c9..1a7efe1c 100644 --- a/libr4d/r4d_gemm_w4a8_nt_m64.hip +++ b/libr4d/r4d_gemm_w4a8_nt_m64.hip @@ -1,70 +1,43 @@ // r4d_gemm_w4a8_nt_m64.hip - r4d_gemm_w4a8_nt_m64: 4-bit-weight, 8-bit-activation skinny GEMM for // M up to 64, gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T with A quantised per row. // -// WHY THIS EXISTS ALONGSIDE r4d_gemm_w4a16_nt_m64. The f16 kernel is at the DRAM roofline at M=8 -// (620-648 GB/s) and there is nothing left to win there. At M=64 -- the drafter's batch at eight -// concurrent requests -- it is not near memory at all: 300-350 GB/s and 72-78 TF/s, against a -// v_wmma_f32_16x16x16_f16 issue ceiling of 207 TF/s, and removing the unpack entirely barely -// changes that. The wall is the f16 matrix instruction, and on this part it is the slow one: +// Complements r4d_gemm_w4a16_nt_m64, which is at the DRAM roofline at M=8 but capped by the f16 +// matrix instruction at M=64 (72-78 TF/s against a 207 TF/s issue ceiling; removing the unpack +// barely helps). Every 8-bit form runs at twice the f16 rate: // // v_wmma_f32_16x16x16_f16 207 TF/s 5.95 cyc/instr // v_wmma_f32_16x16x16_fp8_fp8 412 2.99 // v_wmma_i32_16x16x16_iu8 407 3.03 // v_wmma_i32_16x16x32_iu4 830 2.97 // -// So the widening that made the f16 kernel cheap is what caps it: every 8-bit form runs at twice -// the rate. This kernel takes the int8 one, which needs no exponent games at all. -// -// THE UNPACK IS THREE INSTRUCTIONS AND NEEDS NO ZERO POINT. Store the weight as a 4-bit TWO'S -// COMPLEMENT code and put the nibble in the HIGH half of its byte: for q in -8..7 the byte 16*q is -// exactly the signed int8 of 16*q, so +// The unpack is three instructions with no zero point. The weight is a 4-bit two's complement code +// placed in the high half of its byte: for q in -8..7 the byte 16*q is the signed int8 of 16*q: // // lo = (w << 4) & 0xF0F0F0F0 bytes <- nibbles 0,2,4,6 (elements 0..3) // hi = w & 0xF0F0F0F0 bytes <- nibbles 1,3,5,7 (elements 4..7) // -// is the whole dequant: two v_and_b32 and one v_lshlrev_b32 per eight weights, against eleven for -// the f16 route, and the factor of 16 folds into the group scale offline. A symmetric grid also -// deletes the zero point, which in an integer kernel would otherwise cost a per-group row-sum of A -// and a second correction term. A symmetric 4-bit grid is the best of the 4-bit options on -// quality anyway, so this costs nothing to pick. +// Two v_and_b32 and one v_lshlrev_b32 per eight weights (eleven on the f16 route); the factor 16 is +// removed at the store. A symmetric grid needs no per-group row sum of A for a zero point. // -// The nibble ORDER is the one r4d_gemm_w4a16_nt_m64 already uses: its f16 unpack pairs nibble 2b -// into element b and nibble 2b+1 into element 4+b, which is exactly what the two masks above -// produce. One packed layout, two kernels. +// The weight is shared byte for byte with r4d_gemm_w4a16_nt_m64. Its f16 unpack pairs nibble 2b +// into element b and 2b+1 into element 4+b, the order the two masks above produce, and with a +// constant zero point 8 it computes the same n-8. Only the low half (the scale) of the +// (scale, -(1024+zero)) dword is read here. Small M stays on the f16 kernel, which needs no +// activation-quantiser launch. // -// IT SHARES ITS WEIGHT WITH r4d_gemm_w4a16_nt_m64, BYTE FOR BYTE. The two kernels want the same -// nibbles in the same order, and a signed 4-bit code is what the f16 kernel computes anyway when -// its integer zero point is the constant 8: it builds 1024+n and adds -(1024+8), leaving n-8. So -// one quantised weight feeds both, and the scale array is the f16 kernel's (scale, -(1024+zero)) -// dword with only the low half read here. The stored scale multiplies q-8 while the WMMA here -// sees 16*(q-8), so the factor of 1/16 rides along with the per-row activation scale at the store, -// where it costs nothing. That matters because the dispatch is per call: below M=16 the f16 -// kernel is already at the DRAM roofline and there is nothing for an int8 one to win, while the -// activation quantiser costs a launch -- so the small-M path stays on f16 and the same bytes serve -// both. +// The activation is shuffled within each k step. Fragment element e of lane l is +// A[row][16s + 8*(e>>2) + 4*(l>>4) + (e&3)], two dwords eight bytes apart in a row-major A. The +// quantiser writes each step's sixteen bytes as [half 0's eight][half 1's eight], so a fragment is +// one global_load_b64 (32 loads per group instead of 64). // -// THE ACTIVATION IS PRE-SHUFFLED TOO, BUT ONLY INSIDE A K STEP. A fragment element e of lane l is -// A[row][16s + 8*(e>>2) + 4*(l>>4) + (e&3)], so read out of a row-major A a lane's eight bytes are -// two dwords eight bytes apart: 64 global_load_b32 against 64 WMMA for one group, and 32 -// s_wait_loadcnt with them. The activation layout is this library's to choose -- the quantiser -// writes it -- so it is written with the sixteen bytes of each k step reordered to -// [half 0's eight][half 1's eight]. A lane's fragment is then one global_load_b64 and the group -// costs 32 loads instead of 64. +// Do not lay A out as two planes ([2][M][K/2]): it allows global_load_b128 but is slower, because +// one instruction then spans two distant regions and touches twice the cache lines. The shuffle +// keeps a wave within the same sixteen rows. // -// DO NOT LAY A OUT AS TWO PLANES. [2][M][K/2] makes a lane's four k steps contiguous and the -// group eight global_load_b128, and it is SLOWER than the shuffle below. Sixteen lanes of a wave -// then address one plane and sixteen the other, Mp*K/2 bytes away, so a single instruction spans -// two distant regions and doubles the cache lines it touches. The shuffle keeps every lane of a -// wave inside the same sixteen rows the row-major version touches, and only makes each lane's own -// eight bytes adjacent. -// -// THE ACTIVATION SCALE COMES OUT OF THE GROUP LOOP. Per-row symmetric quantisation makes the row -// scale a constant in n and in the group index, so sum_g s_g * * ar = ar * sum_g ...: -// it is applied once at the store and never inside the k loop. What does stay in the loop is one -// v_cvt_f32_i32 per accumulator element per group, because group scales differ -- eight of them -// against eight WMMA. That argued for a WIDE group, and this kernel alone would take 256; the -// group is 128 because the f16 kernel at M=8 needs the split-K that a wider group takes away -// (`K % (SK*GROUP) == 0` halves the legal split count), and one artifact feeds every W4 kernel. +// The per-row activation scale is constant over n and groups, so it is applied once at the store. +// The loop keeps one v_cvt_f32_i32 per accumulator element per group. A wider group would suit this +// kernel alone; 128 keeps enough legal split-K counts for the f16 kernel at M=8 (one artifact +// feeds every W4 kernel). #include "r4d.h" #include "r4d_gemm_args.h" #include "r4d_common.h" @@ -74,13 +47,10 @@ #include #include -// M is not structural here -- `mt0 = blockIdx.y * MT` tiles it and the row index is clamped into -// 0..M-1 -- so this is a guard against a garbage shape, not the band the kernel is good at. It is -// set wide enough to reach a prefill chunk as well as the decode band, where at eight concurrent -// sequences with spec width 8 the target verifies 8 x 9 = 72 rows. Whether the tuned geometry -// above M = 64 is still the right one is a separate question and is NOT answered by this bound. +// M is not structural (grid.y tiles it, rows are clamped); this is a sanity bound wide enough for a +// prefill chunk and the decode band (e.g. 8 sequences x 9 verify rows = 72), not a tuning band. #define R4D_GEMM_W4A8_MAX_M 8192 -// R4D_GEMM_W4A8_GROUP comes from r4d_common.h -- see the note there. +// R4D_GEMM_W4A8_GROUP comes from r4d_common.h; see the note there. #define R4D_GEMM_W4A8_KPB 64 // K per packed block: 4 k steps, 16 bytes per lane #define WAVE32 32 @@ -90,91 +60,11 @@ typedef int v2i __attribute__((ext_vector_type(2))); typedef unsigned uint4v __attribute__((ext_vector_type(4))); typedef __attribute__((address_space(1))) const uint4v* r4d_gw4; -typedef __attribute__((address_space(1))) const unsigned* r4d_gu1; typedef __attribute__((address_space(1))) const unsigned* r4d_gh1; -typedef __attribute__((address_space(1))) const unsigned short* r4d_gh2; typedef unsigned uint2v __attribute__((ext_vector_type(2))); typedef __attribute__((address_space(1))) const uint2v* r4d_ga2; -// A fragment out of the pre-permuted plane: eight contiguous bytes per k step, so a uint4 is two -// steps and the whole group is eight global_load_b128 per row tile. -#ifndef R4D_W4A8_APERM -#define R4D_W4A8_APERM 1 // 0 reads A row-major, for a harness with an unpermuted buffer -#endif - -// THE SCALE DWORD IS HALF DEAD ON A SYMMETRIC GRID, AND AT THE DECODE BATCH THAT IS PURE COST. -// The shared (f16 scale, f16 of -(1024 + zero)) dword exists for r4d_gemm_w4a16_nt_m64, which -// builds its value as 1024 + n and needs the second half to subtract. A symz grid only ever -// writes the constant 8 there, and THIS kernel never reads it: the ISA shows one -// `global_load_b32` per group whose high sixteen bits are dropped by the `op_sel_hi` on the -// v_fma_mix that consumes it. -// -// At group 128 the scale array is 4 bytes per 16 columns per group against 1024 bytes of nibbles, -// so the dead half is 32 of every 1088 bytes -- 2.94% of everything the kernel reads. That is not -// an instruction count, it is DRAM traffic, and at M <= 16 this kernel runs at 97-98% of the part's -// 639 GB/s read ceiling, where traffic is the ONLY thing that sets the time. WS16 reads -// an f16-only scale plane instead. Sixteen lanes then take 32 contiguous bytes and consecutive -// groups are adjacent, so the 64-byte line is still fully used -- the halving is real and not an -// artefact of counting bytes the cache would have fetched anyway. -// -// The asymmetric form keeps the dword: its whole reason for existing is the zero point. -#ifndef R4D_GEMM_W4A8_WS16 -#define R4D_GEMM_W4A8_WS16 0 -#endif - -// COST ABLATIONS. Wrong answers by construction; they exist to say what the kernel's time is made -// of. WS16 above deletes 2.94% of the bytes read and does not move the time, so byte counts alone -// do not explain it. -// 1 no scale load (sc = 1) -// 2 no activation load (the A fragment is a constant) -// 4 no weight load (the B fragment is a constant; leaves the A stream and the WMMA) -#ifndef R4D_W4A8_ABL -#define R4D_W4A8_ABL 0 -#endif - -// SOFTWARE-PIPELINE THE WEIGHT. The ablations above say the weight stream IS the kernel at a -// decode M: deleting the scale load or the activation loads barely moves the time, while deleting -// the weight load removes most of it, and that stream runs at 587 GB/s against the part's -// 639.6 GB/s ceiling. The loop as written issues its two `global_load_b128`, waits on them, then -// spends ~80 cycles in VALU and WMMA during which the wave issues no memory at all. PF holds the -// NEXT group's weight in registers so the load is issued a whole group ahead of the wait. -// Costs bpg*NPW*4 more VGPRs (16 instead of 8 at NPW=1, against 58 used). -#ifndef R4D_W4A8_PF -#define R4D_W4A8_PF 0 -#endif - -// STAGGER THE GROUP ORDER PER WAVE, so the block's waves stop marching in lockstep across the -// memory channels. -// -// Wave (col_local, ksplit) reads n-tile plane `nt0+col_local` starting at byte offset -// `ksplit * (Ks/KPB) * 512` and advances 512 bytes per k-block. Every plane pitch here is -// kpb*512 -- 40960 at K=5120, 69632 at 8704, 24576 at 3072 -- and every one of those is an exact -// multiple of 4096. A 256-bit GDDR6 part interleaves 16 channels at 256 B, so the address period -// that sweeps every channel is 4096 B, which means at time t EVERY wave in the grid is at the same -// address modulo 4096 and therefore aimed at the same channel. The block issues 20 concurrent -// streams and they all camp one channel group at a time. -// -// The fix is hipBLASLt's `StaggerU`: start each wave at a different group inside its OWN k-slice -// and wrap. The slice, the split-K partition and the bytes read are all unchanged -- only the -// order is -- so the only cost is that `pa` must be computed from g instead of incremented. -// -// NOTE this reorders an fp32 accumulation, so results move by ~1 ULP against a non-staggered build. -#ifndef R4D_W4A8_STAGGER -#define R4D_W4A8_STAGGER 0 -#endif - -// Under STAGGER the group loop no longer visits groups in order, so the activation pointer is -// indexed rather than bumped; without it the bump stays and this is zero. -#if R4D_W4A8_STAGGER -#if R4D_W4A8_APERM -#define AOFF(g) ((g) * (R4D_GEMM_W4A8_GROUP / 8)) -#else -#define AOFF(g) ((g) * (R4D_GEMM_W4A8_GROUP / 4)) -#endif -#else -#define AOFF(g) 0 -#endif - +// A fragments from the pre-permuted plane: eight contiguous bytes per k step. __device__ __forceinline__ v2i fragA8(r4d_ga2 p, int u) { const uint2v w = p[2 * u]; v2i r; @@ -183,15 +73,7 @@ __device__ __forceinline__ v2i fragA8(r4d_ga2 p, int u) { return r; } -__device__ __forceinline__ v2i fragA8row(r4d_gu1 p, int u) { - v2i r; - r[0] = p[4 * u]; - r[1] = p[4 * u + 2]; - return r; -} - -// The whole dequant: two ands and a shift, no zero point. It is a few percent of the kernel at -// M=64 and under a fifth of a percent at M=8, so there is nothing here worth a knob. +// The whole dequant: two ands and a shift. __device__ __forceinline__ v2i dequant8(unsigned w) { v2i r; r[0] = (int)((w << 4) & 0xF0F0F0F0u); @@ -199,31 +81,19 @@ __device__ __forceinline__ v2i dequant8(unsigned w) { return r; } -// BSIGNED=false reads the unpacked byte as 16*nibble (0..240) rather than 16*twos(nibble) -// (-128..112). That is what makes an ASYMMETRIC grid expressible: 16*nibble is affine in the -// nibble, so sum_k a_k (nibble_k - z) = sum_k a_k nibble_k - z sum_k a_k, whereas twos() is affine -// on each half of the range and not across it. The flag's meaning on gfx1201: a B byte of 0x81 -// gives -2032 signed against 2064 unsigned, a ratio of -127/129 exactly. +// BSIGNED=false reads the unpacked byte as 16*nibble (0..240) instead of 16*twos(nibble) +// (-128..112), which makes an asymmetric grid expressible: 16*nibble is affine in the nibble, so +// sum_k a_k (nibble_k - z) = sum_k a_k nibble_k - z sum_k a_k. template __device__ __forceinline__ v8i mmai(v2i a, v2i b, v8i c) { return __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(true, a, BSIGNED, b, c, false); } -// __launch_bounds__ IS PER NPW, AND A FLAT 1024 COSTS THE WIDE ONES 192 REGISTERS. -// A block cannot exceed 1024 threads, but it also cannot exceed 64 KB of LDS, and the split-K -// buffer is WV*NPW*SK*1024 bytes -- so WV*NPW*SK <= 64 is structural and threads = 32*WV*SK is -// therefore capped at 32*64/NPW. Telling the compiler 1024 for every NPW makes it budget for 32 -// waves on one workgroup, which on this part is 1536/8 = 192 VGPRs per wave, and NPW=4 and NPW=8 -// then SPILL against that cap (up to 1875 bytes at MT=4, NPW=8). Those configs can never run more -// than 8 or 16 waves, so that cap is imaginary and the spill is not. -#ifndef R4D_GEMM_W4A8_LB -#define R4D_GEMM_W4A8_LB 1 -#endif -#if R4D_GEMM_W4A8_LB +// __launch_bounds__ depends on NPW. The split-K buffer (WV*NPW*SK KiB) must fit 64 KiB of LDS, so +// threads = 32*WV*SK <= 32*64/NPW. A flat 1024 would budget 32 waves per workgroup and make NPW=4 +// and NPW=8 spill, though they can never run more than 16 or 8 waves. The bound is a hard launch +// limit, so the host checks WV*SK against the same expression. #define R4D_W4A8_BOUNDS(NPW) ((NPW) >= 8 ? 256 : ((NPW) >= 4 ? 512 : 1024)) -#else -#define R4D_W4A8_BOUNDS(NPW) 1024 -#endif template __global__ __launch_bounds__(R4D_W4A8_BOUNDS(NPW)) void r4d_gemm_w4a8_nt_m64_kernel( @@ -247,138 +117,65 @@ __global__ __launch_bounds__(R4D_W4A8_BOUNDS(NPW)) void r4d_gemm_w4a8_nt_m64_ker #pragma unroll for (int i = 0; i < MT; i++) acc[j][i] = (v8f)(0.f); - // TWO THINGS THAT DO NOT WORK ON THE ASYMMETRIC CORRECTION'S ACTIVATION SUMS. - // - // Loading the sums just before the epilogue instead of at the top of the group, to cut - // asum[MT][8]'s 32-VGPR live range at MT=4, is SLOWER. At the top of the group the load is - // already hidden behind the WMMA block, and the register pressure costs less than exposing that - // latency does. - // - // Staging the sums in LDS is also SLOWER, at both ends of the M range. Every wave of the block - // re-reads a group's sums, and the staging can alias the split-K buffer for free since `red` is - // only touched in the store loop and that loop opens with a barrier -- but the staging prologue - // is (K/GROUP)*(MT*16) loads plus a __syncthreads() on a kernel that runs a few microseconds at a - // decode M, and the sums are not the latency problem. + // The asymmetric activation sums are loaded at the top of each group, hidden behind the WMMA + // block. Loading them later (shorter live range) or staging them in LDS were both slower. if (n0 < N) { - // Rows clamped, never masked, as in the f16 kernel: a tile past M recomputes the last valid - // row and the store discards it. A is int8 so the row stride is K bytes, not 2K. - // Plane (lane >> 4), row clamped into 0..M-1, and the group's byte offset is K/2 per row. -#if R4D_W4A8_APERM + // Rows clamped into 0..M-1, never masked; the store discards rows past M. A is int8, so the + // row stride is K bytes. r4d_ga2 pa[MT]; -#else - r4d_gu1 pa[MT]; -#endif #pragma unroll for (int i = 0; i < MT; i++) { int r = (mt0 + i) * 16 + (lane & 15); r = r < M - 1 ? r : M - 1; -#if R4D_W4A8_APERM const size_t off = (size_t)r * K + kbase + 8 * (lane >> 4); pa[i] = (r4d_ga2)(const uint2v*)(A + off); -#else - const size_t off = (size_t)r * K + kbase + 4 * (lane >> 4); - pa[i] = (r4d_gu1)(const unsigned*)(A + off); -#endif } const int kpb = K / R4D_GEMM_W4A8_KPB; const int nsz = K / R4D_GEMM_W4A8_GROUP; r4d_gw4 pw[NPW]; -#if R4D_GEMM_W4A8_WS16 - r4d_gh2 ps[NPW]; -#else r4d_gh1 ps[NPW]; -#endif const int ntlast = N / 16 - 1; #pragma unroll for (int j = 0; j < NPW; j++) { const int t = (nt0 + j) < ntlast ? (nt0 + j) : ntlast; pw[j] = (r4d_gw4)(const uint4v*)(Wq) + (size_t)(t * kpb + kbase / R4D_GEMM_W4A8_KPB) * WAVE32 + lane; -#if R4D_GEMM_W4A8_WS16 - ps[j] = (r4d_gh2)(const unsigned short*)(Ws) + - (size_t)(t * nsz + kbase / R4D_GEMM_W4A8_GROUP) * 16 + (lane & 15); -#else ps[j] = (r4d_gh1)(const unsigned*)(Ws) + (size_t)(t * nsz + kbase / R4D_GEMM_W4A8_GROUP) * 16 + (lane & 15); -#endif } const int bpg = R4D_GEMM_W4A8_GROUP / R4D_GEMM_W4A8_KPB; -#if R4D_W4A8_PF - uint4v nx[NPW][bpg]; -#pragma unroll - for (int j = 0; j < NPW; j++) -#pragma unroll - for (int b = 0; b < bpg; b++) - nx[j][b] = NT ? __builtin_nontemporal_load(&pw[j][(size_t)b * WAVE32]) - : pw[j][(size_t)b * WAVE32]; -#endif - -#if R4D_W4A8_STAGGER - const int gstag = groups > 1 ? (wave * R4D_W4A8_STAGGER) % groups : 0; -#endif - for (int gi = 0; gi < groups; gi++) { -#if R4D_W4A8_STAGGER - const int g = gi + gstag < groups ? gi + gstag : gi + gstag - groups; -#else - const int g = gi; -#endif + for (int g = 0; g < groups; g++) { float sc[NPW]; #pragma unroll for (int j = 0; j < NPW; j++) -#if R4D_W4A8_ABL & 1 - sc[j] = 1.f; -#elif R4D_GEMM_W4A8_WS16 - sc[j] = __half2float(__ushort_as_half(ps[j][(size_t)g * 16])); -#else sc[j] = __half2float(__ushort_as_half( (unsigned short)(ps[j][(size_t)g * 16] & 0xFFFFu))); -#endif - // The zero point lives in the SAME dword's high half, as the f16 of -(1024 + zero) -- the - // encoding the f16 kernel already needs, and exact because f16 has exactly 1024 steps between - // 1024 and 2048. The symz grid only ever writes the constant 8 there. + // The zero point is the dword's high half, the f16 of -(1024 + zero) (exact: f16 has unit + // steps between 1024 and 2048). The symmetric grid always stores 8 there. float z16[NPW]; float asum[MT][8]; if (ASYM) { -#if R4D_W4A8_ASUM_ABLATE - // Cost ablation only -- same arithmetic, no global loads. Wrong answers by construction; - // it exists to say whether the asymmetric path costs its FMAs or its memory. -#pragma unroll - for (int j = 0; j < NPW; j++) z16[j] = 16.f; -#pragma unroll - for (int i = 0; i < MT; i++) -#pragma unroll - for (int e = 0; e < 8; e++) asum[i][e] = 1.f; -#else #pragma unroll for (int j = 0; j < NPW; j++) { const float nz = __half2float(__ushort_as_half( (unsigned short)(ps[j][(size_t)g * 16] >> 16))); z16[j] = 16.f * (-nz - 1024.f); } - // Element e of tile i at this lane is output row (mt0+i)*16 + 8*(lane>>4) + e, so the eight - // rows a lane needs are CONTIGUOUS at a fixed group -- which is why Asum is [G][Mpad] and - // not [M][G]. - // - // TWO v4f LOADS, NOT EIGHT SCALARS. These loads, and not the correction's arithmetic, are - // most of what an asymmetric grid costs over a symmetric one. - // They vectorise only if the base is 32-byte aligned, which is why the row stride is padded - // to a multiple of 16 (also making the last tile's rb+7 in bounds, since rb reaches - // (mtiles-1)*16 + 8). + // Element e of tile i at this lane is output row (mt0+i)*16 + 8*(lane>>4) + e, so a lane's + // eight rows are contiguous at a fixed group; hence Asum is [G][Mpad]. Two v4f loads need a + // 32-byte aligned base, which Mpad (a multiple of 16) provides; it also keeps the last + // tile's rb+7 in bounds. These loads are most of the asymmetric grid's extra cost. const int Mpad = ((M + 15) / 16) * 16; const size_t gi = (size_t)(kbase / R4D_GEMM_W4A8_GROUP + g) * Mpad; #pragma unroll for (int i = 0; i < MT; i++) { - // CLAMPED, and it has to be. When MB exceeds the number of M tiles -- MB=4 with M=9 is a - // legal config the tuner will pick -- this loop still runs MT tiles, and rb reaches - // (MT-1)*16+8 = 56 against an Mpad of 16. The symz path survives that because its A - // pointer clamps and the store discards rows past M; an unclamped Asum read is a page - // fault. Rows past M produce garbage that is discarded, so clamping the base is enough, - // and it stays a multiple of 8 so the v4f loads stay aligned. + // Clamped: MB may exceed the number of M tiles (MB=4 with M=9 is legal), and an unclamped + // Asum read could fault. The clamped base stays a multiple of 8, keeping v4f alignment. int rb = (mt0 + i) * 16 + 8 * (lane >> 4); rb = rb < Mpad - 8 ? rb : Mpad - 8; const v4f* pv = (const v4f*)(Asum + gi + rb); @@ -389,57 +186,23 @@ __global__ __launch_bounds__(R4D_W4A8_BOUNDS(NPW)) void r4d_gemm_w4a8_nt_m64_ker asum[i][e + 4] = v1[e]; } } -#endif } v8i g_acc[NPW][MT]; -#if R4D_W4A8_PF - // Take this group's weight out of the registers the last iteration filled, and issue the - // next group's loads BEFORE any of it is consumed, so the wait sits a full group away. - uint4v cw[NPW][bpg]; -#pragma unroll - for (int j = 0; j < NPW; j++) -#pragma unroll - for (int b = 0; b < bpg; b++) cw[j][b] = nx[j][b]; - if (g + 1 < groups) { -#pragma unroll - for (int j = 0; j < NPW; j++) -#pragma unroll - for (int b = 0; b < bpg; b++) { - const size_t o = (size_t)((g + 1) * bpg + b) * WAVE32; - nx[j][b] = NT ? __builtin_nontemporal_load(&pw[j][o]) : pw[j][o]; - } - } -#endif #pragma unroll for (int b = 0; b < bpg; b++) { uint4v wv[NPW]; #pragma unroll for (int j = 0; j < NPW; j++) { -#if R4D_W4A8_PF - wv[j] = cw[j][b]; -#else const size_t o = (size_t)(g * bpg + b) * WAVE32; -#if R4D_W4A8_ABL & 4 - (void)o; - wv[j] = (uint4v)(0x21212121u); -#else wv[j] = NT ? __builtin_nontemporal_load(&pw[j][o]) : pw[j][o]; -#endif -#endif } #pragma unroll for (int s = 0; s < 4; s++) { const int u = b * 4 + s; v2i afrag[MT]; #pragma unroll -#if R4D_W4A8_ABL & 2 - for (int i = 0; i < MT; i++) { afrag[i][0] = 0x01010101; afrag[i][1] = 0x01010101; } -#elif R4D_W4A8_APERM - for (int i = 0; i < MT; i++) afrag[i] = fragA8(pa[i] + AOFF(g), u); -#else - for (int i = 0; i < MT; i++) afrag[i] = fragA8row(pa[i] + AOFF(g), u); -#endif + for (int i = 0; i < MT; i++) afrag[i] = fragA8(pa[i], u); #pragma unroll for (int j = 0; j < NPW; j++) { const v2i bfrag = dequant8(wv[j][s]); @@ -460,20 +223,12 @@ __global__ __launch_bounds__(R4D_W4A8_BOUNDS(NPW)) void r4d_gemm_w4a8_nt_m64_ker if (ASYM) t -= z16[j] * asum[i][e]; acc[j][i][e] = fmaf(t, sc[j], acc[j][i][e]); } -#if !R4D_W4A8_STAGGER #pragma unroll -#if R4D_W4A8_APERM for (int i = 0; i < MT; i++) pa[i] += R4D_GEMM_W4A8_GROUP / 8; -#else - for (int i = 0; i < MT; i++) pa[i] += R4D_GEMM_W4A8_GROUP / 4; -#endif -#endif } } - // Split-K reduction and store, one row tile at a time. The per-row activation scale is applied - // here and only here: it is constant over n and over the group index, so it never entered the - // k loop. + // Split-K reduction and store, one row tile at a time, applying the per-row activation scale. const int ncols = WV * NPW; const int nthreads = WV * SK * WAVE32; #pragma unroll @@ -493,7 +248,7 @@ __global__ __launch_bounds__(R4D_W4A8_BOUNDS(NPW)) void r4d_gemm_w4a8_nt_m64_ker const int l = off & 31; const int n = (blockIdx.x * ncols + col) * 16 + (l & 15); const int m = (mt0 + i) * 16 + 8 * (l >> 4) + (off >> 5); - // 0.0625 is the 1/16 the unpack introduced by putting the nibble in the byte's high half. + // 0.0625 undoes the 16 from placing the nibble in the byte's high half. if (n < N && m < M) C[(size_t)m * N + n] = (__hip_bfloat16)(v * Ascale[m] * 0.0625f); } } @@ -507,7 +262,8 @@ static void r4d_gemm_w4a8_impl(long a, long ascale, long wq, long ws, long asum, if (N % 16) throw std::runtime_error("r4d gemm_w4a8_nt_m64: N must be a multiple of 16"); if (K % (SK * R4D_GEMM_W4A8_GROUP)) throw std::runtime_error("r4d gemm_w4a8_nt_m64: K must be divisible by SK*group"); - if (WV * SK * WAVE32 > 1024) throw std::runtime_error("r4d gemm_w4a8_nt_m64: threads/block > 1024"); + if (WV * SK * WAVE32 > R4D_W4A8_BOUNDS(NPW)) + throw std::runtime_error("r4d gemm_w4a8_nt_m64: WV*SK*32 exceeds this tile's launch bound"); if (MB < 1 || MB > 4) throw std::runtime_error("r4d gemm_w4a8_nt_m64: MB must be 1..4"); if (NPW != 1 && NPW != 2 && NPW != 4 && NPW != 8) throw std::runtime_error("r4d gemm_w4a8_nt_m64: NPW must be 1, 2, 4 or 8"); @@ -534,8 +290,9 @@ static void r4d_gemm_w4a8_impl(long a, long ascale, long wq, long ws, long asum, #define LAUNCH_NPW(TT, AS) switch (NPW) { \ case 1: LAUNCH_MB(1, TT, AS); break; \ case 2: LAUNCH_MB(2, TT, AS); break; \ + case 4: LAUNCH_MB(4, TT, AS); break; \ case 8: LAUNCH_MB(8, TT, AS); break; \ - default: LAUNCH_MB(4, TT, AS); break; } + default: throw std::runtime_error("r4d gemm_w4a8_nt_m64: NPW must be 1, 2, 4 or 8"); } if (asym) { if (NT) { LAUNCH_NPW(true, true); } else { LAUNCH_NPW(false, true); } } else { @@ -551,39 +308,25 @@ void r4d_gemm_w4a8_nt_m64(long a, long ascale, long wq, long ws, long c, int M, r4d_gemm_w4a8_impl(a, ascale, wq, ws, 0, c, M, K, N, WV, SK, MB, NPW, NT, false, stream); } -// Asymmetric grid: the weight nibble is read UNSIGNED and the stored zero point is corrected out -// with a per-row per-group sum of the activation, which r4d_quant_act_i8_asum emits. `asum` is -// [K/group][Mpad] float with Mpad = ceil(M/16)*16 -- group-major, because a lane's eight -// accumulator elements are eight CONTIGUOUS output rows at one group, and padded so that base is -// 32-byte aligned for a v4f load and the last tile stays in bounds. Allocate it ZEROED. +// Asymmetric grid: the nibble is read unsigned and the zero point is corrected with the per-row +// per-group activation sums from r4d_quant_act_i8_asum. `asum` is [K/group][Mpad] float, +// Mpad = ceil(M/16)*16 (see the kernel). Allocate it zeroed. void r4d_gemm_w4a8_asym_nt_m64(long a, long ascale, long wq, long ws, long asum, long c, int M, int K, int N, int WV, int SK, int MB, int NPW, int NT, long stream) { if (!asum) throw std::runtime_error("r4d gemm_w4a8_asym_nt_m64: asum is required"); -#if R4D_GEMM_W4A8_WS16 - // The zero point is the only thing in the dword's high half, and WS16 is the build that does not - // store it. The two are mutually exclusive by construction, so say so instead of reading zero. - throw std::runtime_error("r4d gemm_w4a8_asym_nt_m64: built with WS16, which has no zero point"); -#endif r4d_gemm_w4a8_impl(a, ascale, wq, ws, asum, c, M, K, N, WV, SK, MB, NPW, NT, true, stream); } int r4d_gemm_w4a8_nt_m64_max_m(void) { return R4D_GEMM_W4A8_MAX_M; } int r4d_gemm_w4a8_nt_m64_group(void) { return R4D_GEMM_W4A8_GROUP; } -int r4d_gemm_w4a8_nt_m64_aperm(void) { return R4D_W4A8_APERM; } -int r4d_gemm_w4a8_nt_m64_ws16(void) { return R4D_GEMM_W4A8_WS16; } // ============================================================== the plugin ABI entry points // -// The operand reader and the split law are in r4d_gemm_args.h. See libr4d/r4d_args.h for why there -// is no adapter directory between the core and these launches. +// The operand reader and the split law are in r4d_gemm_args.h; see libr4d/r4d_args.h. /* ------------------------------------------------------------------ int8-activation grids */ -/* The asymmetric grid is a different WEIGHT FORMAT, not a different call: the nibble is read - * UNSIGNED and the stored per-group zero is corrected out with the activation's per-group row - * sums. So it is selected by `dtype`, which is what the weight file was written for, and never by - * whether a_sum happens to be present -- guessing from an operand would make a caller that forgot - * to pass the sums silently compute the symmetric answer against asymmetric bytes. */ +/* The asymmetric grid is selected by `dtype`, not by the presence of a_sum (see is_asym). */ extern "C" int r4d_rad_gemm_w4a8_m64(const RadArgs* a, RadStream s) { GemmOps g; diff --git a/libr4d/r4d_gemm_w4a8_prefill.hip b/libr4d/r4d_gemm_w4a8_prefill.hip index 2cb9a70a..bcb2985d 100644 --- a/libr4d/r4d_gemm_w4a8_prefill.hip +++ b/libr4d/r4d_gemm_w4a8_prefill.hip @@ -1,41 +1,24 @@ -// W4A8 GEMM FOR PREFILL: the same packed weight and the same rotated int8 activation as -// r4d_gemm_w4a8_tiled, laid out for the regime where the matrix pipe is the answer. +// W4A8 GEMM for prefill: the packed weight and rotated int8 activation of r4d_gemm_w4a8_tiled, for +// the compute-bound regime. At decode this GEMM is a weight stream at the DRAM ceiling; at M = 4096 +// (730 GFLOP against 44.6 MB) every non-matrix instruction is overhead. // -// WHY A SECOND KERNEL. At a decode batch this GEMM is a weight stream and every question is -// bandwidth: `gate_up_proj` at M = 9 moves 47 MB and runs at the DRAM ceiling, so the inner loop's -// instruction mix does not matter because the loop is waiting on memory. At M = 4096 -// the same call is 730 GFLOP against 44.6 MB, so the loop is waiting on nothing and every -// instruction that is not a matrix instruction is a tax. The two want different code. +// Ceiling: v_wmma_i32_16x16x16_iu8 occupies its SIMD for 8 cycles on gfx1201 (f16/bf16: 16), an +// int8 peak of ~375 TOPS. There is no wider iu8 form (v_wmma_i32_16x16x32_iu8 does not exist), and +// iu4 needs both operands 4-bit. The budget is 8 cycles per matrix instruction plus one per other +// VALU instruction. The group fold is the largest non-matrix item, and as v_fma_mix_f32 (VOP3P, +// never dual-issued) it costs more than as v_fmac_f32, which pairs as v_dual_fmac_f32, the only +// VOPD form this loop can use (no v_dual_and_b32 or v_dual_lshlrev_b32). So the f16 scale is +// materialised and folded with plain FMACs. // -// THE CEILING THIS AIMS AT. `v_wmma_i32_16x16x16_iu8` occupies its SIMD for EIGHT cycles on -// gfx1201 -- half what f16/bf16 take, at 16.0-16.2 cycles -- so the int8 matrix peak is ~375 TOPS, -// not the ~187 an f16 roofline would say. gfx1201 has no wider iu8 form: `llvm-mc` rejects -// `v_wmma_i32_16x16x32_iu8`, and `v_wmma_i32_16x16x32_iu4` is exactly twice the rate but needs -// BOTH operands 4-bit, which the activation is not. So the budget is 8 cycles of matrix work per -// matrix instruction plus one cycle per other VALU instruction, and the job is to make the second -// term small. In a register-only replica of this inner loop, the matrix instructions on their own -// reach most of that peak and the weight unpack costs little on top; the GROUP FOLD is the largest -// non-matrix item in the loop, and it costs materially more as a `v_fma_mix_f32` than as a plain -// `v_fmac_f32`. +// A fragment reads: the tiled kernel stores A k-major and issues one ds_load_b64 per (row tile, +// k step). Here a row's 64 bytes are half-major, [row][lane half][k step][2], so one ds_load_b128 +// fetches a lane's two consecutive k steps (TM*2 reads per 64-k block instead of TM*4). Only the LDS +// copy is permuted; a lane still consumes the k values the weight names. // -// The reason is dual issue. `v_fma_mix_f32` is VOP3P, which can never dual-issue; -// `v_dual_fmac_f32` is the ONLY VOPD form gfx1201 offers that this loop can use -// (`v_dual_and_b32` and `v_dual_lshlrev_b32` do not exist here, so the unpack cannot be packed at -// all). This kernel therefore forces the f16 scale to materialise and folds with plain FMACs. -// -// THE OTHER HALF IS THE ACTIVATION FRAGMENT READ. The tiled kernel stores A in LDS k-major and -// reads one `ds_load_b64` per (row tile, k step): 32 reads and ~30 `s_wait_dscnt` per scale group. -// Here the row's 64 bytes are stored HALF-MAJOR -- [row][lane half][k step][2] instead of -// [row][k step][lane half][2] -- which puts a lane's two consecutive k steps side by side, so one -// `ds_load_b128` fetches them both and a whole 64-k block of A is TM*2 reads instead of TM*4. -// The permutation is inside the LDS copy only: the packed weight is untouched and the activation -// in memory is untouched, because a lane still consumes exactly the k values the weight names. -// -// The 4-dword XOR swizzle keeps that conflict-free. A row is 16 dwords and LDS has 32 banks, so -// the row index contributes only its low bit; the mask has to separate the rest and it has to -// permute whole 4-dword BLOCKS or a `ds_load_b128` lands astride two of them. ((r >> 1) & 3) << 2 -// gives lanes 0..7 the start banks {0,16,4,20,8,24,12,28} -- eight distinct starts, four dwords -// each, all 32 banks once. +// A 4-dword XOR swizzle keeps it conflict-free. A row is 16 dwords across 32 banks, so the row +// index contributes only its low bit; the mask must separate the rest and permute whole 4-dword +// blocks so a ds_load_b128 never straddles two. ((r >> 1) & 3) << 2 gives lanes 0..7 start banks +// {0,16,4,20,8,24,12,28}, all 32 banks once. #include "r4d.h" #include "r4d_gemm_args.h" #include "r4d_common.h" @@ -52,9 +35,8 @@ typedef float v8f_t __attribute__((ext_vector_type(8))); typedef unsigned u4v_t __attribute__((ext_vector_type(4))); typedef float v4f_t __attribute__((ext_vector_type(4))); -// The unpacked byte is 16*nibble, read SIGNED, and the 16 comes back out in the store. Three -// instructions for two dwords is the floor here: gfx1201 has no `v_lshl_and_b32` and no nibble -// permute, so each output dword costs at least its own mask. +// The unpacked byte is 16*nibble, read signed; the 16 is removed at the store. Three instructions +// for two dwords is the floor: gfx1201 has no v_lshl_and_b32 and no nibble permute. __device__ __forceinline__ v2i_t pf_dq8(unsigned w) { v2i_t r; r[0] = (int)((w << 4) & 0xF0F0F0F0u); @@ -63,12 +45,14 @@ __device__ __forceinline__ v2i_t pf_dq8(unsigned w) { } // OPT bits -// 1 grid swizzle: walk GSW m-tiles per n-tile so the resident workgroups form a square and -// both the A row block and the W column block are shared by several of them -// 2 fold with plain `v_fmac_f32` (VOPD) instead of letting the f16 convert contract into a -// `v_fma_mix_f32` -// 4 split barrier: signal after the commit, do the k block's matrix work, wait at the top -// 8 read the A fragments one `ds_load_b64` per k step (the tiled kernel's shape), for comparison +// 1 grid swizzle: walk GSW m-tiles per n-tile so resident workgroups share A row blocks and +// W column blocks +// 2 fold with plain v_fmac_f32 (VOPD) rather than v_fma_mix_f32 +// 8 read A fragments with one ds_load_b64 per k step (the tiled kernel's shape) +// 128 load a row tile's eight Ascale values as two b128: a lane's rows +// (m0 + i*16 + 8*half + e, e = 0..7) are contiguous +// 256 unpredicated stores for blocks wholly inside the matrix (all but the last row block) +// 512 non-temporal stores for C template __global__ __launch_bounds__(WM * WN * 32, 8) void r4d_gemm_w4a8_prefill_kernel( const signed char* __restrict__ A, const float* __restrict__ Ascale, @@ -83,31 +67,13 @@ __global__ __launch_bounds__(WM * WN * 32, 8) void r4d_gemm_w4a8_prefill_kernel( constexpr int NT_ = WM * WN * 32; constexpr int UNR = GRP / BK; // k blocks per scale group constexpr bool VOPD = (OPT & 2) != 0; - constexpr bool SPLITB = (OPT & 4) != 0; constexpr bool NARROWA = (OPT & 8) != 0; - // ABLATIONS. Both compute wrong answers on purpose and both keep every instruction that is not - // the thing being priced, so what they measure is one item and not a deleted pipeline. - // 16 every fragment read comes from buffer 0 at k = 0: the same LDS reads, the same count, - // the same banks, but no dependency on the staging that filled it - // 32 the A fragment never leaves registers: prices the A LDS read itself - constexpr bool ABSTALE = (OPT & 16) != 0; - constexpr bool ABNOA = (OPT & 32) != 0; - // 64 store one output element in eight, with the other seven folded into it so nothing in the - // k loop goes dead: prices the store epilogue, which is 64 predicated bf16 stores, 64 f32 - // multiplies, 64 software bf16 roundings and 32 `Ascale` loads per lane - constexpr bool ABSTORE = (OPT & 64) != 0; - // 128 load the eight `Ascale` values of a row tile as two b128 instead of eight scalars: the - // rows a lane owns (m0 + i*16 + 8*half + e, e = 0..7) are CONTIGUOUS constexpr bool ASCVEC = (OPT & 128) != 0; - // 256 an unpredicated store path for the blocks that are wholly inside the matrix, which at a - // prefill M is all but the last row block: 64 compares and 64 cndmasks per lane go away - // 512 non-temporal stores for C, which is written once and never read by this kernel constexpr bool STFAST = (OPT & 256) != 0; constexpr bool STNT = (OPT & 512) != 0; - // Both stagings move 16 bytes per thread per pass, with a predicate on the last one so a block - // shape does not have to divide the block width. AD/4 = BM*4 and WD/4 = (BN/16)*32, so at 512 - // threads that is exact only for BM = 128 and BN = 256; every other tile in the sweep is ragged. + // Both stagings move 16 bytes per thread per pass, predicated on the last pass so the tile need + // not divide the thread count (exact at 512 threads only for BM = 128, BN = 256). constexpr int AU = AD / 4, WU = WD / 4; constexpr int APT = (AU + NT_ - 1) / NT_, WPT = (WU + NT_ - 1) / NT_; constexpr bool APAD = (AU % NT_) != 0, WPAD = (WU % NT_) != 0; @@ -131,8 +97,7 @@ __global__ __launch_bounds__(WM * WN * 32, 8) void r4d_gemm_w4a8_prefill_kernel( const int m0 = by * BM, n0 = bx * BN; const int kpb = K / BK, nsz = K / GRP; - // A LDS position of (row, lane half, k step). See the header: half-major inside the row, with a - // 4-dword XOR that separates eight rows. + // A LDS position of (row, lane half, k step): half-major within the row, 4-dword XOR swizzle. #define PF_APOS(r, h, u) ((r) * 16 + ((((h) * 8 + (u) * 2)) ^ ((((r) >> 1) & 3) << 2))) v8f_t acc[TN][TM]; @@ -182,13 +147,9 @@ __global__ __launch_bounds__(WM * WN * 32, 8) void r4d_gemm_w4a8_prefill_kernel( } }; auto bar = [&]() { - // THE LDS STORES IN `commit` HAVE TO LAND BEFORE THE SIGNAL, which is what the - // release fence is for. `s_barrier_signal` is not `__syncthreads()`: it emits - // the barrier alone, with no wait on the outstanding `ds_store`s. Without the - // fence a wave announces writes that are still in flight and its neighbours read - // whatever LDS held from the previous k block -- the generated code carries - // `s_wait_loadcnt` for the global loads feeding the stores and no `s_wait_dscnt` - // at all, and the kernel returns a different answer on every call. + // The release fence makes commit's LDS stores land before the signal. Unlike + // __syncthreads(), s_barrier_signal emits no s_wait_dscnt, so without the fence other + // waves would read the previous k block's LDS contents. __builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup"); __builtin_amdgcn_s_barrier_signal(-1); __builtin_amdgcn_s_barrier_wait(-1); @@ -204,29 +165,21 @@ __global__ __launch_bounds__(WM * WN * 32, 8) void r4d_gemm_w4a8_prefill_kernel( const int k0 = kg + h * BK; const int buf = h & 1; if (k0 + BK < K) issue(k0 + BK); - if ((k0 % GRP) == 0) { // the group scale, one whole k block early + if ((k0 % GRP) == 0) { // the group scale, one k block early #pragma unroll for (int j = 0; j < TN; j++) scv[j] = Ws[(unsigned)(((n0 / 16 + wn * TN + j) * nsz + k0 / GRP) * 16 + (lane & 15))]; } - // ---- fragments: the whole 64-k block, up front ---- + // ---- fragments for the whole 64-k block, up front ---- v2i_t af[TM][BK / 16]; #pragma unroll for (int i = 0; i < TM; i++) { const int row = (wm * TM + i) * 16 + (lane & 15); - if (ABNOA) { -#pragma unroll - for (int u = 0; u < BK / 16; u++) { - af[i][u][0] = (int)(0x11111111u + i + u); - af[i][u][1] = (int)(0x22222222u + i); - } - continue; - } if (NARROWA) { #pragma unroll for (int u = 0; u < BK / 16; u++) { - const unsigned* p = lds_a[ABSTALE ? 0 : buf] + PF_APOS(row, half, u); + const unsigned* p = lds_a[buf] + PF_APOS(row, half, u); af[i][u][0] = (int)p[0]; af[i][u][1] = (int)p[1]; } @@ -234,7 +187,7 @@ __global__ __launch_bounds__(WM * WN * 32, 8) void r4d_gemm_w4a8_prefill_kernel( #pragma unroll for (int q = 0; q < BK / 32; q++) { // one b128 = two k steps const u4v_t v = - *(const u4v_t*)(lds_a[ABSTALE ? 0 : buf] + PF_APOS(row, half, 2 * q)); + *(const u4v_t*)(lds_a[buf] + PF_APOS(row, half, 2 * q)); af[i][2 * q][0] = (int)v[0]; af[i][2 * q][1] = (int)v[1]; af[i][2 * q + 1][0] = (int)v[2]; @@ -245,15 +198,12 @@ __global__ __launch_bounds__(WM * WN * 32, 8) void r4d_gemm_w4a8_prefill_kernel( u4v_t wv[TN]; #pragma unroll for (int j = 0; j < TN; j++) - wv[j] = *(const u4v_t*)(lds_w[ABSTALE ? 0 : buf] + (size_t)(wn * TN + j) * 128 + lane * 4); + wv[j] = *(const u4v_t*)(lds_w[buf] + (size_t)(wn * TN + j) * 128 + lane * 4); - if (SPLITB) { // the next block's LDS write, then arrive - if (k0 + BK < K) commit(buf ^ 1); - __builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup"); // see bar() - __builtin_amdgcn_s_barrier_signal(-1); - } - - // ---- the matrix work ---- + // ---- matrix work ---- + // A group's first WMMA seeds C with 0x4B400000 (the float 1.5 * 2^23), so the int32 sum's + // bits read as a float are 12582912 + sum while |sum| < 2^22. The fold below multiplies that + // float by the scale, and the bias 12582912 * sum(scale) is removed after the K loop. #pragma unroll for (int u = 0; u < BK / 16; u++) { #pragma unroll @@ -274,9 +224,8 @@ __global__ __launch_bounds__(WM * WN * 32, 8) void r4d_gemm_w4a8_prefill_kernel( #pragma unroll for (int j = 0; j < TN; j++) { sc[j] = __half2float(__ushort_as_half((unsigned short)(scv[j] & 0xFFFFu))); - // Materialise the convert. Left alone the compiler folds it into `v_fma_mix_f32`, which - // reads the f16 for free and is VOP3P -- and VOP3P never dual-issues, so the fold stays - // at one instruction per accumulator element instead of one per two. + // Materialise the convert; otherwise it contracts into v_fma_mix_f32 (VOP3P, never + // dual-issued). if (VOPD) asm("" : "+v"(sc[j])); csum[j] += sc[j]; } @@ -289,12 +238,8 @@ __global__ __launch_bounds__(WM * WN * 32, 8) void r4d_gemm_w4a8_prefill_kernel( acc[j][i][e] = fmaf(__uint_as_float((unsigned)g[j][i][e]), sc[j], acc[j][i][e]); } - if (SPLITB) { - __builtin_amdgcn_s_barrier_wait(-1); - } else { - if (k0 + BK < K) commit(buf ^ 1); - bar(); - } + if (k0 + BK < K) commit(buf ^ 1); + bar(); } } #undef PF_APOS @@ -308,30 +253,14 @@ __global__ __launch_bounds__(WM * WN * 32, 8) void r4d_gemm_w4a8_prefill_kernel( for (int e = 0; e < 8; e++) acc[j][i][e] += d; } - if (ABSTORE) { -#pragma unroll - for (int j = 0; j < TN; j++) -#pragma unroll - for (int i = 0; i < TM; i++) { - float v = 0.f; -#pragma unroll - for (int e = 0; e < 8; e++) v += acc[j][i][e]; - const int n = n0 + (wn * TN + j) * 16 + (lane & 15); - const int m = m0 + (wm * TM + i) * 16 + 8 * (lane >> 4); - if (n < N && m < M) C[(size_t)m * N + n] = (__hip_bfloat16)(v * Ascale[m] * 0.0625f); - } - return; - } const bool inside = STFAST && (m0 + BM <= M); #pragma unroll for (int i = 0; i < TM; i++) { float as[8]; const int mb = m0 + (wm * TM + i) * 16 + 8 * (lane >> 4); if (ASCVEC) { - // The vector reads Ascale[mc .. mc+7], which lies inside [0, M) only when M >= 8. Below that - // it would read past the last row's scale -- past the operand, when the plane is exactly M - // long -- so a short M takes the clamped scalar read for every lane instead. M is uniform - // over the grid, so the branch costs one compare. + // The vector read Ascale[mc .. mc+7] stays inside [0, M) only when M >= 8; a short M, or a + // lane whose rows were clamped, takes the clamped scalar read instead. const int mc = mb < M - 8 ? mb : (M > 8 ? M - 8 : 0); if (M >= 8) { const v4f_t* pv = (const v4f_t*)(Ascale + mc); @@ -353,7 +282,7 @@ __global__ __launch_bounds__(WM * WN * 32, 8) void r4d_gemm_w4a8_prefill_kernel( const __hip_bfloat16 v = (__hip_bfloat16)(acc[j][i][e] * (ASCVEC ? as[e] : Ascale[m]) * 0.0625f); if (inside || (n < N && m < M)) { - // the non-temporal builtin does not take a __hip_bfloat16*, so go through its bits + // the non-temporal builtin does not take a __hip_bfloat16*, so store its bits if (STNT) __builtin_nontemporal_store(*(const unsigned short*)&v, (unsigned short*)(C + (size_t)m * N + n)); @@ -380,36 +309,22 @@ static void pf_launch(long a, long ascale, long wq, long ws, long c, int M, int void r4d_gemm_w4a8_prefill(long a, long ascale, long wq, long ws, long c, int M, int K, int N, long stream, int variant) { #define PF(...) pf_launch<__VA_ARGS__>(a, ascale, wq, ws, c, M, K, N, stream) + // The arms tile_bmbn in r4d_rows.cpp lists; 8, 9, 10, 13 and 14 change the tile, the rest are + // BM 128 x BN 256 with other OPT bits. switch (variant) { - case 1: PF(2, 8, 4, 2, 0, 1); break; // no VOPD fold, b128 A case 2: PF(2, 8, 4, 2, 8, 1); break; // b64 A, no VOPD fold case 3: PF(2, 8, 4, 2, 10, 1); break; // b64 A, VOPD fold - case 4: PF(2, 8, 4, 2, 6, 1); break; // + split barrier case 5: PF(2, 8, 4, 2, 3, 4); break; // + grid swizzle, GSW 4 case 6: PF(2, 8, 4, 2, 3, 8); break; // + grid swizzle, GSW 8 - case 7: PF(2, 8, 4, 2, 7, 8); break; // swizzle + split barrier case 8: PF(2, 8, 2, 2, 2, 1); break; // BM 64, BN 256 case 9: PF(2, 8, 3, 2, 2, 1); break; // BM 96, BN 256 case 10: PF(2, 8, 4, 1, 2, 1); break; // BM 128, BN 128 - case 11: PF(4, 8, 4, 2, 2, 1); break; // BM 256, BN 256, 1024 threads - case 12: PF(2, 16, 4, 2, 2, 1); break; // BM 128, BN 512, 1024 threads case 13: PF(1, 8, 4, 2, 2, 1); break; // BM 64, BN 256, 256 threads case 14: PF(2, 8, 8, 1, 2, 1); break; // BM 256, BN 128 - case 15: PF(4, 4, 4, 2, 2, 1); break; // BM 256, BN 128, 512 threads - case 20: PF(2, 8, 4, 2, 2 | 16, 1); break; // abl: fragments from a stale buffer - case 21: PF(2, 8, 4, 2, 2 | 32, 1); break; // abl: A fragment never touches LDS - case 22: PF(2, 8, 4, 2, 2 | 16 | 32, 1); break; // abl: both - case 23: PF(2, 8, 4, 2, 8 | 16, 1); break; // abl: stale, b64 A reads - case 24: PF(2, 8, 4, 2, 0, 1); break; // b128 A, fma_mix fold - case 25: PF(2, 8, 4, 2, 2 | 64, 1); break; // abl: one store in eight - case 26: PF(2, 8, 4, 2, 8 | 64, 1); break; // abl: one store in eight, b64 A case 27: PF(2, 8, 4, 2, 2 | 128, 1); break; // vectorised Ascale case 28: PF(2, 8, 4, 2, 8 | 128, 1); break; // vectorised Ascale, b64 A case 29: PF(2, 8, 4, 2, 8 | 128 | 256, 1); break; // + unpredicated store case 30: PF(2, 8, 4, 2, 8 | 128 | 256 | 512, 1); break; // + non-temporal - case 31: PF(2, 8, 4, 2, 2 | 128 | 256, 1); break; // b128 A + both - case 32: PF(2, 8, 4, 2, 8 | 128 | 256 | 1, 4); break; // + grid swizzle 4 - case 33: PF(2, 8, 4, 2, 8 | 128 | 256 | 1, 8); break; // + grid swizzle 8 default: PF(2, 8, 4, 2, 2, 1); break; // b128 A + VOPD fold } #undef PF @@ -417,8 +332,7 @@ void r4d_gemm_w4a8_prefill(long a, long ascale, long wq, long ws, long c, int M, // ============================================================== the plugin ABI entry points // -// The operand reader and the split law are in r4d_gemm_args.h. See libr4d/r4d_args.h for why there -// is no adapter directory between the core and these launches. +// The operand reader and the split law are in r4d_gemm_args.h; see libr4d/r4d_args.h. extern "C" int r4d_rad_gemm_w4a8_prefill(const RadArgs* a, RadStream s) { GemmOps g; int rc = gemm_ops(a, &g, 1); diff --git a/libr4d/r4d_gemm_w4a8_tiled.hip b/libr4d/r4d_gemm_w4a8_tiled.hip index 80fd1690..485477a7 100644 --- a/libr4d/r4d_gemm_w4a8_tiled.hip +++ b/libr4d/r4d_gemm_w4a8_tiled.hip @@ -1,51 +1,37 @@ -// r4d_gemm_w4a8_tiled.hip - r4d_gemm_w4a8_tiled: the W4A8 GEMM for PREFILL batches, where the skinny -// kernel is structurally wrong. +// r4d_gemm_w4a8_tiled.hip - r4d_gemm_w4a8_tiled: the W4A8 GEMM for prefill batches. // -// WHY. r4d_gemm_w4a8_nt_m64 gives a block at most 64 rows, so at M=4096 there are 64 M-blocks and -// each re-reads the whole weight slice: 22.3 MB x 64 = 1.43 GB per call for gate_proj, which is why -// it holds a FLAT ~105 TF/s at every M and loses to a plain bf16 matmul. The bar is the block-fp8 -// prefill GEMM, which runs at ~204 TF/s on the same shapes; without a tiled W4 kernel both W4 -// routes -- the skinny one and dequantise-to-bf16 -- are around twice that time, so prefill -// regresses badly. Nothing slower than the bar ships. +// r4d_gemm_w4a8_nt_m64 covers at most 64 rows per block, so at M=4096 each of 64 M-blocks re-reads +// the weight slice and it holds a flat ~105 TF/s. The target is the block-fp8 prefill GEMM +// (~204 TF/s on the same shapes). // -// THE SHAPE FOLLOWS FROM TRAFFIC. Block tile BM x BN reads (M/BM) copies of the weight and (N/BN) -// copies of the activation. For gate_proj at M=4096, against ~600 GB/s of DRAM and ~1049 from the -// 64 MB MALL (both operands fit, so re-reads are cached): +// Tile shape from traffic: a BM x BN tile reads M/BM copies of the weight and N/BN of the +// activation. For gate_proj at M=4096 (~600 GB/s DRAM, ~1049 GB/s from the 64 MB MALL): // // 64 x 128 (skinny) 4352 blocks 2.85 GB 2.7 ms // 128 x 256 1088 blocks 1.43 GB 1.4 ms // 256 x 256 544 blocks 1.07 GB 1.0 ms // -// 256x256 wants TM=TN=4 per wave, and that does not fit: the group loop needs the int32 accumulator -// AND the float one live at once (16 + 16 vector registers of 8 = 256 VGPRs). TM*TN <= 8 is the -// budget, so this is 128 x 256 -- 1.4 ms projected, still under the 1786 us bar. +// 256x256 needs TM=TN=4 per wave, but the group loop keeps the int32 and float accumulators live +// together (256 VGPRs), so TM*TN <= 8 and the tile is 128 x 256. // -// BK IS HALF THE GROUP, AND DOUBLE-BUFFERED. BK = the group with a SINGLE buffer makes every -// iteration load -> barrier -> compute -> barrier, with 40 global-load latencies fully exposed: that -// form is SLOWER than the skinny kernel while moving HALF the traffic. The loop is latency-bound, -// not bandwidth-bound, which is what a traffic argument alone cannot tell you. +// BK is half the scale group, double-buffered. A single buffer at BK = the group exposes every +// global-load latency and is slower than the skinny kernel: the loop is latency-bound. Double +// buffering must stay under 32 KB of LDS to fit two workgroups per CU; at BK = 64 it is 8 KB of A +// and 8 KB of W per buffer. The int32 accumulator carries across the two iterations of a group. // -// Double buffering needs the working set to stay under 32 KB so two workgroups still fit a CU; at -// BK = the group that would be 64 KB and cost the occupancy. At BK = 64 it is 8 KB of A and 8 KB of -// W per buffer, 32 KB in total. The scale group then spans two iterations, which costs nothing -- -// the int32 accumulator lives in registers and a barrier does not disturb it. +// Padding A's LDS row stride is slower at M = 4096 (one extra dword per row exceeds 32 KB and +// drops a CU to one workgroup); the XOR swizzle below avoids the bank conflicts instead. // -// (Padding A's row stride to dodge LDS bank conflicts is a LOSS here: it helps a little at M = 512 -// and costs far more at M = 4096, because 16 KB + 16 KB is exactly 32 KB and one extra dword per -// row pushes a CU from two workgroups to one. The swizzle below gets the same effect for free.) -// -// LAYOUTS ARE THE SKINNY KERNEL'S, UNCHANGED. The packed weight is already in WMMA fragment order -- -// lane L of a (tile, k-block) owns dwords [4L, 4L+3] of a 128-dword run -- so staging is a contiguous -// copy and the LDS read repeats the global pattern. The activation is pre-shuffled inside each k -// step by the quantiser, so a lane's eight bytes are contiguous there too. One weight, one -// activation, both kernels. +// Layouts are the skinny kernel's: the packed weight is in WMMA fragment order (lane L of a +// (tile, k-block) owns dwords [4L, 4L+3] of a 128-dword run), so staging is a contiguous copy, and +// the quantiser pre-shuffles the activation within each k step. Both kernels share one weight and +// one activation. #include "r4d.h" #include "r4d_gemm_args.h" #include "r4d_common.h" #include #include #include -#include #include #define R4D_TILED_KPB 64 @@ -54,11 +40,10 @@ typedef int v2i_t __attribute__((ext_vector_type(2))); typedef int v8i_t __attribute__((ext_vector_type(8))); typedef float v8f_t __attribute__((ext_vector_type(8))); typedef unsigned u4v_t __attribute__((ext_vector_type(4))); -typedef unsigned u2v_t __attribute__((ext_vector_type(2))); // 8 bytes = four bf16 typedef float v4f_t __attribute__((ext_vector_type(4))); // BSIGNED=false reads the unpacked byte as 16*nibble (0..240) instead of 16*twos(nibble): the -// asymmetric grid, whose per-group zero is then corrected out with a row-sum of the activation. +// asymmetric grid, whose per-group zero is corrected with a row sum of the activation. template __device__ __forceinline__ v8i_t tmmai(v2i_t a, v2i_t b, v8i_t c) { return __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(true, a, BSIGNED, b, c, false); @@ -71,181 +56,38 @@ __device__ __forceinline__ v2i_t tdequant8(unsigned w) { return r; } -__device__ __forceinline__ unsigned tpack2bf(float a, float b) { - unsigned ua = __float_as_uint(a), ub = __float_as_uint(b); - ua += 0x7FFFu + ((ua >> 16) & 1u); // round to nearest even, no NaN branch - ub += 0x7FFFu + ((ub >> 16) & 1u); - return __builtin_amdgcn_perm(ub, ua, 0x07060302u); // {ub.hi16, ua.hi16} -} - -// WM x WN waves, each owning TM x TN WMMA tiles. BM = WM*TM*16, BN = WN*TN*16, BK = the scale group. +// WM x WN waves, each owning TM x TN WMMA tiles. BM = WM*TM*16, BN = WN*TN*16. UNR k blocks are +// unrolled per scale group. // -// BIAS KILLS THE int32 -> float CONVERSION IN THE GROUP EPILOGUE. Every group closes with -// `acc += (float)g * s` over TM*TN*8 = 64 accumulator elements, which is 128 VALU against 64 WMMA -// instructions -- 2 VALU per WMMA, the single largest overhead in the loop. Half of it is -// `v_cvt_f32_i32`, and that half can be deleted outright: for |x| < 2^22, +// The symmetric grid seeds each group's WMMA accumulator with 0x4B400000 (the magic bias), which +// removes the int32 -> float conversion from the group fold. For |x| < 2^22, // // float(x) == __uint_as_float(0x4B400000 + x) - 12582912.0f // -// because 0x4B400000 is 1.5*2^23, whose mantissa field sits exactly at 2^22, so adding x lands x in -// the mantissa unrounded. The group's int32 sum is at most 128 * 127 * 128 = 2,080,768, half the -// budget. BIAS=1 adds the constant with `v_add_nc_u32` (which, unlike v_cvt, is VOPD-eligible and -// can dual-issue with the fmac next to it); BIAS=2 seeds the WMMA's C operand with it instead, so -// the accumulator comes OUT biased and the conversion costs nothing at all -- at the price of eight -// VGPRs held for the constant vector, and 192 is exactly the budget for two workgroups per CU. -// The -12582912*s per group is folded into a per-column running sum and subtracted once at the end. -// -// SKT: A BALANCED LAST ROUND. The part runs 32 workgroups at a time (one 512-thread workgroup per -// WGP), so a grid of T tiles takes ceil(T/32) rounds and the last one runs T mod 32 workgroups on a -// 32-slot machine. `gate_up_proj` is N = 17408 = 2^10 x 17, which is 136 tiles at BN = 128: four -// full rounds and a round of eight, and that round standalone costs well over twice what the same -// work does spread over 32 workgroups at a quarter of K each. -// -// SKT != 0 splits ONLY the tail tiles along K. The first `nfull` tiles are ordinary data-parallel -// blocks that store straight to C; the rest are `r` tiles x `s` K-pieces, which write fp32 partials -// to a workspace and let the LAST piece to arrive reduce them. "Last to arrive" is an atomic -// counter, so there is no spin and no assumption about dispatch order; the reduction reads the s -// slots in INDEX order, so the sum is deterministic run to run even though the arrival order is not. -// It is not bit-identical to the unsplit kernel -- the fp32 adds re-associate at the piece boundary -// -- and it is not meant to be; it is a different, equally valid summation order. It agrees with -// the unsplit kernel to at most one bf16 ULP across every shape, batch and tile it was checked on, -// and against an fp32 reference it is equal or very slightly better. -// -// AND IT DOES NOT PAY at any batch the decode dispatch reaches. The tail round is cheaper split, -// but a full grid run whole is cheaper than running the two halves back to back: the part is -// ALREADY overlapping most of that tail with the round in front of it, and the workspace round trip -// plus the reduction's arrival barrier cost more than the remainder. It is a loss at the narrow -// batches and a wash to a small loss everywhere the dispatch table picks. The two instantiations -// are kept because the path is correct and cheap to re-check, NOT because anything should call it. -template -__global__ __launch_bounds__(WM * WN * 32, WPE) void r4d_gemm_w4a8_tiled_kernel( +// since 0x4B400000 is 1.5*2^23 with unit mantissa steps. A group's int32 sum is at most +// 128 * 127 * 128 = 2,080,768. The -12582912*s per group is summed per column and subtracted once +// at the end. The asymmetric grid converts plainly: with the bias, z16, the row sums and csum on top +// of 128 accumulator registers, it spills. +template +__global__ __launch_bounds__(WM * WN * 32, 8) void r4d_gemm_w4a8_tiled_kernel( const signed char* __restrict__ A, const float* __restrict__ Ascale, const unsigned* __restrict__ Wq, const unsigned* __restrict__ Ws, - const float* __restrict__ Asum, __hip_bfloat16* __restrict__ C, int M, int K, int N, - float* __restrict__ WSP, unsigned* __restrict__ CNT, int nfull, int nrag, int nspl) { + const float* __restrict__ Asum, __hip_bfloat16* __restrict__ C, int M, int K, int N) { constexpr int BK = 64; // half a scale group constexpr int GRP = R4D_GEMM_W4A8_GROUP; constexpr int BM = WM * TM * 16, BN = WN * TN * 16; constexpr int NTILE = BN / 16; constexpr int AW = BM * BK / 4; // A dwords per buffer - // OPT BIT 256: UNPACK THE WEIGHT ONCE, AT STAGING, INSTEAD OF WM TIMES ON READ. - // The fragment read gives wave (wm, wn) the n-tiles of `wn`, so every wave sharing a `wn` -- - // WM of them -- unpacks the SAME dwords. Counted per block per k step: the read path does - // WM*WN waves x 32 lanes x TN*4 dwords x 3 VALU, the staging path does WW dwords once, and the - // ratio is exactly WM. With the 16-row swizzle in place the DCE-proof ablation puts the unpack - // at about a quarter of this kernel at a decode M, and the W LDS read at ~0 (deleting it measures - // the same as deleting the unpack alone), so trading half the unpack for twice the W LDS traffic - // is the right side of that trade. It costs LDS: the W buffer holds bytes rather than nibbles. - constexpr bool WU = (OPT & 256) != 0; - // OPT BIT 512: THE iu4 PATH -- no weight dequant at all. - // `v_wmma_i32_16x16x32_iu4` eats PACKED nibbles, and the DCE-proof ablation puts the unpack at - // about a quarter of this kernel at a decode M, with a no-unpack build landing at 1.09x the - // one-pass memory floor. The activation is the SAME int8, split exactly as - // `a = 16*(a>>4) + (a&15)` with the high half read signed and the low half unsigned, so two iu4 - // replace the two iu8 that covered the same K. Integer accumulation makes the re-association - // exact, and the split holds over all 256 x 16 (a, q) pairs on hardware -- this is bit-identical - // arithmetic, not an approximation. - // - // THE WEIGHT IS NOT RE-PERMUTED. A GEMM is invariant under a permutation of k applied to BOTH - // operands, and the instruction pairs A slot p with B slot p exclusively -- a perfect 16x16 - // diagonal on hardware. So the packed artifact stays byte-identical - // and only the ACTIVATION is laid out to name the k the weight packing already names: - // byte c*32 + P*16 + h*8 + d*4 + i/2, nibble i&1 <- plane P of a[m][64*blk + c*32 + d*16 + - // KIDX[h][i]], KIDX[0] = 0,8,1,9,2,10,3,11 KIDX[1] = 4,12,5,13,6,14,7,15 - // which is the same bytes and the same `ds_load_b64` count as the int8 form. - constexpr bool IU4 = (OPT & 512) != 0; - // OPT BIT 65536: NON-TEMPORAL WEIGHT LOADS. - // At M=64 this kernel is 20-27% over its weight roofline where at M=8 it is 5%, and the inner - // loop is not the reason: per 512 bytes streamed at the full 634 GB/s this part - // gives away 32 iu8 matrix instructions, 96+ VALU and 96+ LDS reads for FREE, and the shipped - // tile spends 20, 12 and 20 of them. What scales with M is the ACTIVATION: - // every column block stages the whole M x K of A, so gate_up's 136 blocks read 44.6 MB of A - // against 47.35 MB of weight, and A is 328 KB -- it should live in L2 and be nearly free. The - // weight stream is what evicts it: 636 MB walked once, never re-read, filling every level on the - // way past. A non-temporal hint on the weight says so, and leaves A where it was. - constexpr bool WNT = (OPT & 65536) != 0; - // OPT BIT 131072: THE WEIGHT NEVER GOES THROUGH LDS. - // The staged weight buys sharing between the WM waves that hold the same `wn`, and every tile a - // decode step picks has WM = 1 -- so it buys nothing and costs a `ds_store_b128` per thread per - // k step, half the LDS budget, and a barrier that has to wait for the weight's global load as - // well as the activation's. The fragment a wave wants is already one contiguous 512-byte block - // read `lane*4` dwords at a time, which is EXACTLY the shape the staging loads it in, so the - // register the prefetch put it in can be read directly. Double buffering moves from LDS to a - // second register set, indexed by the same compile-time `it & 1` the unrolled k loop already has. - constexpr bool WNOLDS = (OPT & 131072) != 0; - // OPT BIT 262144: FETCH THE GROUP SCALE A WHOLE GROUP EARLIER STILL. - // Of everything inside this loop, the group scale is the ONLY item that prices above the control - // spread at the tiles a decode step picks: replacing the load with a constant is worth several - // percent on `gate_up`, where the unpack, the weight LDS read, the activation LDS read and the - // group fold are each inside it. Its bandwidth share is 5.9%, so about a quarter is latency - // the existing one-group prefetch does not cover -- the load lands at the start of the group it - // is used at the end of, and every wave in every workgroup reaches that boundary together. - // Rotate two registers instead: fetch group g+1 at the start of group g. - constexpr bool SCPF2 = (OPT & 262144) != 0; - // OPT BIT 524288: THE SCALE TABLE IS f16, NOT A DWORD. - // The dword per (column, group) carries the f16 scale in its low half and the f16 of -(1024+zero) - // in its high half, and the SYMMETRIC path -- which is what ships -- reads `raw & 0xFFFF` and - // never touches the other two bytes. They are 5.9% of everything `gate_up` streams and the only - // item in this loop that prices above the control spread, and pricing it as latency is wrong: - // a prefetch a whole group deeper buys nothing where deleting the load buys several percent. So - // halve the table. The arithmetic is untouched -- the same f16, the same fold, same output -- - // and the asymmetric path keeps the dword because it needs the other half. - constexpr bool SC16 = (OPT & 524288) != 0; - static_assert(!SC16 || !ASYM, "the asymmetric path needs the zero in the scale dword's high half"); - - // AN ABLATION THAT ALSO DELETES THE STAGING IS TWO ABLATIONS. The variants below 10 are guarded - // by `ABL == 0` at the prefetch and the commit, so every one of them ALSO runs with no global - // loads and no double buffer -- fine for ranking two variants against each other, useless for - // pricing one item against the shipped kernel. ABL >= 10 repeats one of those variants with the - // staging left in, which is what a prefill cost breakdown needs; the variants below 10 keep their - // own meanings. - constexpr int ABX = ABL == 10 ? 5 : ABL == 11 ? 6 : ABL == 12 ? 7 : ABL == 13 ? 3 - : ABL == 14 ? 4 : ABL == 15 ? 9 : ABL == 16 ? 2 : ABL == 17 ? 8 : ABL; - constexpr bool TWOACC = IU4 || ABX == 8; - // THE MAGIC BIAS AND iu4 DO NOT MIX, and the reason is worth stating because the arithmetic - // itself is exact. BIAS=2 seeds the int32 accumulator with 0x4B400000 so the int->float - // conversion is a reinterpretation; the float fold then rounds `(12582912 + G) * s` once. The - // iu4 path multiplies the RAW nibble rather than 16*q, so its integer G is SIXTEEN TIMES smaller - // for the same answer -- the bias is unchanged but the signal under it is not, and the rounding - // that was 1/16 ULP of the signal becomes one. The result is 7.22e-3 against the iu8 path's - // 2.37e-3, three times the 4-bit quantisation error, which is not a rounding difference worth - // arguing about. - // - // Restoring it would mean holding `bias + 16*G` in the accumulator, which costs a second shift - // per element per group. Plain `v_cvt_f32_i32` (BIAS=0) costs a fraction of a percent against - // the biased build here and is MORE accurate than the shipped path (2.33e-3 against 2.37e-3), - // because the product it rounds has no bias in it at all. So iu4 simply does not take the bias. - static_assert(!IU4 || BIAS == 0, "the iu4 path must be built with BIAS = 0"); - // - // REJECTED, and the arithmetic says why in one line. Per scale group this path - // SAVES the unpack, 3 VALU per weight dword = 24*TN - // COSTS the hi/lo combine, one per element = 8*TM*TN - // COSTS the cvt that the magic bias deletes = 8*TM*TN - // so the net is 8*TN*(2*TM - 3): a win only at TM = 1, which means BM = 32 and no batch a serve - // makes wants a row tile that small. It also costs 30 VGPRs (85 -> 115 at BM=96/BN=128), which - // crosses the 96-VGPR step from 16 waves per SIMD to 12, and at BM=128 it spills 65 bytes. - // Against the same tile on iu8 it is bit-identical in output and ranges from a small win to a - // large loss across the tiles these batches pick, with BM=128 more than twice the time. The - // ABL 8 variant looks better than the real path only because it keeps the magic bias, which the - // real path cannot have. One instantiation is kept because it is correct and bit-identical, and - // the only thing that would change the verdict is a tile with TM = 1. - constexpr int WW = NTILE * 128 * (WU ? 2 : 1); // W dwords per buffer (BK == KPB, so one run) + constexpr int WW = NTILE * 128; // W dwords per buffer (BK == KPB, so one run) + constexpr bool BIAS = !ASYM; __shared__ unsigned lds_a[2][AW]; - __shared__ unsigned lds_w[2][WNOLDS ? 4 : WW]; + __shared__ unsigned lds_w[2][WW]; const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; const int wm = wave / WN, wn = wave % WN; - int tilex = blockIdx.x, kbeg = 0, kend = K, slot = -1; - if (SKT && (int)blockIdx.x >= nfull) { - const int jj = (int)blockIdx.x - nfull, kper = K / nspl; - tilex = nfull + jj / nspl; - kbeg = (jj % nspl) * kper; - kend = kbeg + kper; - slot = (int)blockIdx.y * (nrag * nspl) + jj; - } - const int m0 = blockIdx.y * BM, n0 = tilex * BN; + const int bx = blockIdx.x; + const int m0 = blockIdx.y * BM, n0 = bx * BN; const int kpb = K / R4D_TILED_KPB, nsz = K / GRP; constexpr int NT_ = WM * WN * 32; @@ -255,616 +97,168 @@ __global__ __launch_bounds__(WM * WN * 32, WPE) void r4d_gemm_w4a8_tiled_kernel( #pragma unroll for (int i = 0; i < TM; i++) acc[j][i] = (v8f_t)(0.f); v8i_t g[TN][TM]; - // ABL 8 prices the iu4 ROUTE. `v_wmma_i32_16x16x32_iu4` consumes PACKED nibbles, so a kernel - // built on it has no weight unpack at all -- and the DCE-proof ablation puts the unpack at 24.7% - // of this kernel at M=72, with a no-unpack build landing at 1.09x the one-pass memory floor. - // The route is `A_i8 = 16*A_hi + A_lo` with A_hi signed and A_lo unsigned int4, which is exact, - // so ONE iu4 instruction covers K=32 and two of them (hi and lo, sharing the B fragment) replace - // the two iu8 instructions that covered the same K. Instruction count is unchanged; what goes - // away is the unpack, and what it costs is a second int32 accumulator per output tile. - // This variant computes the WRONG ANSWER on purpose -- it feeds whatever bits are to hand, - // because the real thing needs an offline weight re-permutation and a 4-bit-plane activation - // format. It exists to say whether that pipeline is worth building. - v8i_t g2[TWOACC ? TN : 1][TWOACC ? TM : 1]; float csum[TN]; #pragma unroll for (int j = 0; j < TN; j++) csum[j] = 0.f; - unsigned scv[TN], scn[SCPF2 ? TN : 1]; - float asp[ASYM ? TM : 1][8]; + unsigned scv[TN]; - // XOR SWIZZLE instead of padding. A row is BK/4 = 16 dwords and LDS has 32 banks, so a half-wave's - // sixteen lanes -- differing only in the row -- would collide. Padding by one dword fixes that and - // costs more than it saves: A+W is exactly 32 KB and one extra dword per row drops a CU from two - // workgroups to one, a small gain at M=512 and a large loss at M=4096. The mask must stay INSIDE the row: - // (row & 15) << 1 reaches 30, walks into the next row and gives a 0.386 relative error. -// With 128-bit staging (OPT bit 3) the mask has to permute whole 4-dword BLOCKS, or a `ds_store_b128` -// of dwords 0-3 lands at swizzled position 2 and writes {2,3,4,5} instead of {2,3,0,1}: silently -// wrong data (relative error 0.79) and a 16-byte store at an 8-byte-aligned address. (r&3)<<2 is -// 0/4/8/12, which still separates rows two apart -- the LDS bank period at a 16-dword row stride -- -// and still lands inside the row, since 15 ^ 12 = 3. -// OPT BIT 128: A SWIZZLE THAT SEPARATES SIXTEEN ROWS, NOT EIGHT. -// The fragment read has sixteen lanes differing ONLY in the row -- `row = ... + (lane & 15)` -- at a -// fixed column, and the row stride is BK/4 = 16 dwords. Bank = (r*16 + (c ^ mask)) % 32, so the -// row contributes only its low bit and the mask has to separate the other four. `(r & 7) << 1` -// separates eight, so rows r and r+8 land on the same bank: a 2-WAY CONFLICT on every A read. -// `((r >> 1) & 7) << 1` gives the eight EVEN rows eight distinct masks and the eight odd rows the -// same eight in the upper bank half, which is conflict-free at the read. It stays inside the row -// (both operands are 4-bit, so the XOR is) and stays EVEN, which the `ds_load_b64` alignment needs. -// The store side is unaffected either way: there sixteen consecutive lanes share a row and differ -// in c, so they were already spread across all sixteen banks of the row. -// -// This matters because the A LDS read is the LARGEST single item in this inner loop -- the -// DCE-proof ablation puts it at about a third of the kernel at the tiles a decode step picks. -#define ASW(r, c) \ - ((r) * (BK / 4) + ((c) ^ ((OPT & 8) ? (((OPT & 128) ? ((r) >> 1) : (r)) & 3) << 2 \ - : (((OPT & 128) ? ((r) >> 1) : (r)) & 7) << 1))) + // XOR swizzle instead of padding (padding would exceed 32 KB and drop a CU to one workgroup). + // A row is BK/4 = 16 dwords over 32 banks, so the sixteen lanes of a fragment read (differing + // only in the row) would collide. Bank = (r*16 + (c ^ mask)) % 32, so the row only contributes + // its low bit: `(r & 7) << 1` leaves rows r and r+8 colliding (2-way conflict on every A read), + // while `((r >> 1) & 7) << 1` is conflict-free. Both stay inside the row ((row & 15) << 1 would + // reach 30 and corrupt the next row) and even (for ds_load_b64 alignment). The A LDS read is about + // a third of the kernel at decode tiles. The asymmetric kernel keeps the 8-row form. +#define ASW(r, c) ((r) * (BK / 4) + ((c) ^ ((((ASYM ? (r) : ((r) >> 1)) & 7) << 1)))) - // A PREFETCH THAT WRITES LDS DIRECTLY DOES NOT OVERLAP, and it is worth more than a factor of two. - // The LDS store waits on the global load and sits before the compute in program order, so the - // compute waits too. Load into REGISTERS, compute off the other buffer, then commit, so the wait - // lands after the WMMA work. Same buffers, same barriers, same traffic; only the s_waitcnt moves. - // A RAGGED A STAGING, so BM does not have to be a multiple of the workgroup width. - // AW = BM*BK/4 dwords, so 512 threads need BM % 32 == 0 and the tile ladder had to skip 80 and - // 112 -- exactly the sizes that fit a decode M without rounding it up. One predicate on the - // last partial pass costs nothing when it divides (the guard folds away) and unlocks the rest. + // Prefetch into registers, compute off the other buffer, then commit to LDS, so the load wait + // lands after the WMMA work (a prefetch that writes LDS directly would stall the compute; >2x). + // A staging may be ragged (a predicate on the last pass), so BM need not be a multiple of the + // workgroup width (e.g. BM = 80, 112). constexpr int APT = (AW + NT_ - 1) / NT_, WPT = WW / NT_; constexpr bool APAD = (AW % NT_) != 0; - unsigned ra[APT > 0 ? APT : 1], rw[WPT > 0 ? WPT : 1]; - // 128-BIT STAGING (OPT bit 3). Each thread otherwise moves one dword per array per iteration: - // four global loads, four LDS stores and four addresses for 32 bytes. A row is BK/4 = 16 dwords - // and the block is 512 threads, so four threads cover a row exactly -- one `global_load_b128` and - // one `ds_store_b128` each instead of four of each. The wave touches the same segments either - // way: 32 lanes x 16 B over 8 rows is the same 64-byte runs as 32 lanes x 4 B over 2 rows. - // A 128-BIT STAGING PATH THAT DOES NOT TILE LOADS NOTHING AT ALL, SILENTLY. - // Variant 9 (<2,8,4,1>, BM 128 BN 128) is 512 threads against WW = NTILE*128 = 1024 weight - // dwords, so (WW/4)/NT_ is 0, the `OPT & 16` loop has an empty trip count, the dword path is - // switched off by the same bit, and the kernel multiplies whatever was in LDS -- it returns a - // 1.6 relative error rather than raising. Choose the width from whether it actually divides, - // not from the OPT bit alone, so a new tile shape degrades to dword staging instead of breaking. - constexpr int WWP = NTILE * 128; // packed W dwords, whatever the store width - constexpr int WPTU = WU ? (WWP / NT_ > 0 ? WWP / NT_ : 1) : 1; - unsigned rwu[WPTU]; - // OPT BIT 32768: LET THE 128-BIT A STAGING BE RAGGED, the way OPT-less dword staging already is. - // A128 needs (AW/4) % NT_ == 0, and AW/4 = BM*4, so at 512 threads only BM % 128 == 0 qualifies: - // BM = 160 and 192 silently fall back to SIX global_load_b32 + six ds_store_b32 per thread per k - // step instead of two b128, which is ~10 extra instructions per k step and is most of why the - // tall tiles lose at prefill. One predicate on the last pass fixes it. Gated on its own bit so - // that no shape the decode table already picked changes: the tiles where AW/4 < NT_ (BM <= 96 at - // 512 threads, BM <= 80 at 256) keep A128 OFF exactly as before. - constexpr bool A128R = (OPT & 32768) != 0; - constexpr int APT4 = A128R ? ((AW / 4 + NT_ - 1) / NT_) : ((AW / 4) / NT_); - constexpr int WPT4 = WU ? 0 : (WW / 4) / NT_; - constexpr bool A4PAD = A128R && ((AW / 4) % NT_) != 0; - constexpr bool A128 = - (OPT & 8) && APT4 > 0 && (A128R ? (AW / 4) >= NT_ : (AW / 4) % NT_ == 0); - constexpr bool W128 = !WU && (OPT & 16) && WPT4 > 0 && (WW / 4) % NT_ == 0; - u4v_t ra4[APT4 > 0 ? APT4 : 1], rw4[WPT4 > 0 ? WPT4 : 1]; - u4v_t rwg[WNOLDS ? 2 : 1][WNOLDS ? TN : 1]; // the weight double buffer, in registers - - // OPT BIT 32: DO NOT STAGE ROWS PAST M. - // The tiled kernel's cost at these batches is proportional to the PADDED row count, not to M and - // not to the weight traffic: on `gate_up_proj` the BM=96 tile costs exactly 96/64 of what the - // BM=64 tile does at the same M, while the weight read is identical. What scales - // with BM is the activation staging -- APT = (BM*BK/4)/threads dwords per thread per k step, - // 2 for BM=64 at 512 threads and 3 for BM=96 -- and the 256-thread variants, which triple it - // again, cost 2-3x. - // - // At M=72 in a BM=96 tile, 24 of every 96 staged rows are `mm = M-1` clamped duplicates whose - // accumulators the store epilogue throws away. A quarter of the staging is for rows that do not - // exist. Skipping the global load AND the LDS store for them leaves stale LDS under those rows, - // which is exactly as harmless as the duplicate was: the WMMA consumes it, and the epilogue - // discards every m >= M. - constexpr bool MSKIP = (OPT & 32) != 0; - // ABL 9 PRICES TAKING THE ACTIVATION OUT OF LDS ENTIRELY. - // The A fragment read is the largest single item in this loop -- the ABL 7 variant shows halving - // its BYTES is worth close to a fifth of the kernel -- and it exists only because A arrives - // row-major: a lane's eight bytes are one row at a fixed k, so sixteen lanes would each need - // their own 8-byte segment and a direct global load would be sixteen-way scattered. LDS is what - // transposes it. But the quantiser writes the activation, so it could write it FRAGMENT-MAJOR -- - // [row tile][k step][lane][8] -- and then the fragment is one coalesced `global_load_b64` per - // (i, u) and there is no A staging, no `ds_store`, no `ds_load` and no A half of the LDS budget - // at all. This variant loads exactly that address, so the instruction mix and the traffic are - // the real thing's; the ANSWER is wrong because the activation in memory is still row-major. - constexpr bool ANOLDS = (ABX == 9); - // OPT BIT 1024: A BARRIER THAT FENCES LDS ONLY. - // `__syncthreads()` is a full-memory fence, and on gfx12 that means the barrier carries a - // `global_inv` -- the ISA shows two of them per scale group here. Everything this loop - // synchronises is in LDS: the staging writes `lds_a`/`lds_w` and the fragment reads read them - // back. The global loads are into REGISTERS and are ordered by their own load counter, not by - // the barrier. So the release/acquire pair only has to cover the `local` address space, which - // drops the cache invalidate and leaves the barrier itself. - // - // IT IS NEUTRAL, though the variant is not inert: `global_inv` really does go 2 -> 0 per scale - // group, traded for two more `s_wait_dscnt`, at an identical 236 instructions. The time - // difference sits inside the run-to-run spread of a control variant that duplicates the baseline, - // so the cache invalidate is free here. The variant stays because it is correct and the - // comparison needs it. - auto ldsbar = [&]() { - if (OPT & 1024) { - __builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "local"); - __builtin_amdgcn_s_barrier(); - __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup", "local"); - } else { - __syncthreads(); - } - }; - // One index, two containers: the dword table the asymmetric path needs and the f16 table the - // symmetric path is the only reader of. Written as a macro rather than a lambda because it is - // read from inside the epilogue's `#pragma unroll` bodies where a capture would be re-formed. -#define R4D_WS(g_, j_) \ - (SC16 ? (unsigned)((const unsigned short*)Ws)[(unsigned)(((n0 / 16 + wn * TN + (j_)) * nsz + \ - (g_)) * 16 + (lane & 15))] \ - : Ws[(unsigned)(((n0 / 16 + wn * TN + (j_)) * nsz + (g_)) * 16 + (lane & 15))]) - auto issue = [&](int kk, int bufn) { - if constexpr (WNOLDS) { -#pragma unroll - for (int j = 0; j < TN; j++) { - const u4v_t* wp4 = (const u4v_t*)(Wq + (unsigned)(((n0 / 16 + wn * TN + j) * kpb + - kk / R4D_TILED_KPB) * 128 + lane * 4)); - rwg[bufn][j] = WNT ? __builtin_nontemporal_load(wp4) : *wp4; - } - } - if (A128 && !ANOLDS) { -#pragma unroll - for (int x = 0; x < APT4; x++) { - const int t = tid + x * NT_, r = t / (BK / 16), c4 = t % (BK / 16); - if (A4PAD && t >= AW / 4) continue; - if (MSKIP && m0 + r >= M) continue; - const int mm = m0 + r < M ? m0 + r : M - 1; - ra4[x] = *(const u4v_t*)(A + (unsigned)(mm * K + kk + c4 * 16)); - } - } - if (W128 && !WNOLDS) { + unsigned ra[APT], rw[WPT > 0 ? WPT : 1]; + // The weight moves as one global_load_b128 and one ds_store_b128 per thread where that tiles the + // block (four threads cover a 16-dword row), else as dwords. + constexpr int WPT4 = (WW / 4) / NT_; + constexpr bool W128 = WPT4 > 0 && (WW / 4) % NT_ == 0; + u4v_t rw4[WPT4 > 0 ? WPT4 : 1]; + static_assert(W128 || (WPT > 0 && WW % NT_ == 0), "no W staging path tiles this block shape"); + // Global indices are 32-bit: a 64-bit address costs four extra instructions per load. + auto issue = [&](int kk) { + if (W128) { #pragma unroll for (int x = 0; x < WPT4; x++) { const int t = tid + x * NT_, tl = t / 32, off4 = t % 32; - const u4v_t* wp4 = (const u4v_t*)(Wq + (unsigned)(((n0 / 16 + tl) * kpb + - kk / R4D_TILED_KPB) * 128 + off4 * 4)); - rw4[x] = WNT ? __builtin_nontemporal_load(wp4) : *wp4; - } - } - if (WU && !WNOLDS) { - // One dword of nibbles per thread, kept packed in a register until commit; the unpack itself - // rides on the store so the global load is unchanged. -#pragma unroll - for (int x = 0; x < WPTU; x++) { - const int t = tid + x * NT_, tl = t / 128, off = t % 128; - const unsigned* wpu = Wq + (unsigned)(((n0 / 16 + tl) * kpb + kk / R4D_TILED_KPB) * 128 - + off); - rwu[x] = WNT ? __builtin_nontemporal_load(wpu) : *wpu; + rw4[x] = *(const u4v_t*)(Wq + (unsigned)(((n0 / 16 + tl) * kpb + kk / R4D_TILED_KPB) * + 128 + off4 * 4)); } } #pragma unroll - for (int x = 0; x < APT && !A128 && !ANOLDS; x++) { + for (int x = 0; x < APT; x++) { const int t = tid + x * NT_, r = t / (BK / 4), c = t % (BK / 4); if (APAD && t >= AW) continue; - if (MSKIP && m0 + r >= M) continue; const int mm = m0 + r < M ? m0 + r : M - 1; - ra[x] = (OPT & 2) ? *(const unsigned*)(A + (unsigned)(mm * K + kk + c * 4)) - : *(const unsigned*)(A + (size_t)mm * K + kk + c * 4); + ra[x] = *(const unsigned*)(A + (unsigned)(mm * K + kk + c * 4)); } #pragma unroll - for (int x = 0; x < WPT && !W128 && !WU && !WNOLDS; x++) { + for (int x = 0; x < WPT && !W128; x++) { const int t = tid + x * NT_, tl = t / 128, off = t % 128; - const unsigned* wp = (OPT & 2) - ? Wq + (unsigned)(((n0 / 16 + tl) * kpb + kk / R4D_TILED_KPB) * 128 + off) - : Wq + ((size_t)((n0 / 16 + tl) * kpb + kk / R4D_TILED_KPB) * 32) * 4 + off; - rw[x] = WNT ? __builtin_nontemporal_load(wp) : *wp; + rw[x] = Wq[(unsigned)(((n0 / 16 + tl) * kpb + kk / R4D_TILED_KPB) * 128 + off)]; } }; auto commit = [&](int buf) { - if (A128 && !ANOLDS) { -#pragma unroll - for (int x = 0; x < APT4; x++) { - const int t = tid + x * NT_, r = t / (BK / 16), c4 = t % (BK / 16); - if (A4PAD && t >= AW / 4) continue; - if (MSKIP && m0 + r >= M) continue; - *(u4v_t*)(lds_a[buf] + ASW(r, c4 * 4)) = ra4[x]; - } - } - if (W128 && !WNOLDS) { + if (W128) { #pragma unroll for (int x = 0; x < WPT4; x++) *(u4v_t*)(lds_w[buf] + (tid + x * NT_) * 4) = rw4[x]; } - if (WU && !WNOLDS) { #pragma unroll - for (int x = 0; x < WPTU; x++) { - const int t = tid + x * NT_, tl = t / 128, off = t % 128; - const int wl = off / 4, wu_ = off % 4; // the read's lane and k step - const v2i_t d = tdequant8(rwu[x]); - // [tile][lane][u][2], so a wave's fragment for one k step is one ds_load_b64 and its four - // k steps are 32 contiguous bytes -- two b128 where the packed form needed one. - *(v2i_t*)(lds_w[buf] + (size_t)tl * 256 + wl * 8 + wu_ * 2) = d; - } - } -#pragma unroll - for (int x = 0; x < APT && !A128 && !ANOLDS; x++) { + for (int x = 0; x < APT; x++) { const int t = tid + x * NT_, r = t / (BK / 4), c = t % (BK / 4); if (APAD && t >= AW) continue; - if (MSKIP && m0 + r >= M) continue; lds_a[buf][ASW(r, c)] = ra[x]; } #pragma unroll - for (int x = 0; x < WPT && !W128 && !WU && !WNOLDS; x++) lds_w[buf][tid + x * NT_] = rw[x]; + for (int x = 0; x < WPT && !W128; x++) lds_w[buf][tid + x * NT_] = rw[x]; }; - // Neither staging width can move the buffer if it does not divide the block, and the loops above - // would then silently move nothing. Both paths are compile-time constants, so say so at compile - // time rather than returning a wrong answer. - static_assert(ANOLDS || A128 || APT > 0, "no A staging path tiles this block shape"); - static_assert(WNOLDS || WU || W128 || (WPT > 0 && WW % NT_ == 0), - "no W staging path tiles this block shape"); - // Every variant that reads `lds_w` with its own addressing -- the unpack-at-staging path, the iu4 - // route and the two DCE-proof ablations -- would read a four-dword stub under WNOLDS. None of - // them is a shipping path, so refuse the combination rather than measure a wrong answer. - static_assert(!WNOLDS || (ABL == 0 && !WU && !IU4), - "WNOLDS does not compose with the weight-LDS ablations"); - static_assert(!WU || WWP % NT_ == 0, "unpacked W staging does not tile this block shape"); + // The group's scale dword: the f16 scale, and for the asymmetric grid the f16 of -(1024 + zero) + // in the high half. 32-bit index: the table has at most (N/16)*(K/GRP)*16 elements. +#define R4D_WS(g_, j_) Ws[(unsigned)(((n0 / 16 + wn * TN + (j_)) * nsz + (g_)) * 16 + (lane & 15))] - if constexpr (SCPF2) { -#pragma unroll - for (int j = 0; j < TN; j++) - scn[j] = R4D_WS(kbeg / GRP, j); - } - issue(kbeg, 0); - commit(0); // a BUFFER index, not a k offset -- the two only coincide at kbeg = 0 - ldsbar(); + issue(0); + commit(0); + __syncthreads(); - // UNROLL THE K LOOP OVER THE GROUP. At BK = 64 and a 128-wide scale group the group boundary is - // a DYNAMIC branch -- `(k0 % GRP) == 0` alternates -- and the epilogue sits inside it, which stops - // the scheduler from interleaving it with the WMMA work on either side. Unrolling by GRP/BK makes - // both conditions compile-time constants per copy. Worth several percent, and it is what brings - // the kernel from a few points over the block-fp8 bar to PARITY. The tell that the dynamic - // branch is there at all: a group-64 build, where GRP == BK makes the conditions constant for - // free, runs the SAME as group 128 despite doing twice the epilogue arithmetic. - for (int kg = kbeg, it = 0; kg < kend; kg += BK * UNR) { + // Unroll the K loop over the group (UNR = GRP/BK) so the group-boundary tests are compile-time per + // copy; a dynamic branch around the epilogue stops the scheduler interleaving it with the WMMA. + // Worth several percent. + for (int kg = 0, it = 0; kg < K; kg += BK * UNR) { #pragma unroll for (int h = 0; h < UNR; h++, it++) { const int k0 = kg + h * BK; const int buf = it & 1; - if ((ABL == 0 || ABL >= 10) && k0 + BK < kend) issue(k0 + BK, buf ^ 1); // loads in flight across the WMMA work below + if (k0 + BK < K) issue(k0 + BK); // loads in flight across the WMMA work below - constexpr int AGRP = ABX == 3 ? GRP * 8 : GRP; // ABL 3 prices the group epilogue at 1/8 - const bool first_half = (k0 % AGRP) == 0; - // THE GROUP SCALE IS A GLOBAL LOAD THAT NOTHING HIDES. Every wave in every workgroup reaches - // the group boundary on the same k0, so when the epilogue loads Ws right where it uses it, all - // of them stall on the same latency at the same moment and there is no other wave to run. That - // is why the epilogue costs about four times what issuing its 5120 VALU would: most of it is - // the wait. Fetch it at the START of the group instead -- one whole 64-k iteration of WMMA - // work, plus the second iteration's, stands between the load and its use. - // Keep the RAW dword. Converting it here consumes the load here, and the compiler puts the - // s_waitcnt in front of the first USE: calling __half2float() at the prefetch site lands the - // wait immediately after the load, ahead of every WMMA -- a prefetch that prefetches nothing. - // Convert at the group close instead. - if ((OPT & 1) && (k0 % GRP) == 0) { - if constexpr (SCPF2) { - // The rotate has to come first: `scn` is the group this iteration will fold with, and the - // load below is for the NEXT one. The group index is clamped rather than branched -- the - // value fetched past the last group is never folded, and a uniform branch here would sit - // on the boundary every wave arrives at together. + const bool first_half = (k0 % GRP) == 0; + // Fetch the group scale at the start of the group. Every wave reaches the boundary on the same + // k0, so a load at the point of use stalls them all at once. Keep the raw dword and convert at + // the group close: converting here would put the wait right after the load. + if ((k0 % GRP) == 0) { #pragma unroll - for (int j = 0; j < TN; j++) scv[j] = scn[j]; - const int gnx = (k0 / GRP + 1 < nsz) ? k0 / GRP + 1 : nsz - 1; -#pragma unroll - for (int j = 0; j < TN; j++) - scn[j] = R4D_WS(gnx, j); - } else { -#pragma unroll - for (int j = 0; j < TN; j++) - scv[j] = R4D_WS(k0 / GRP, j); - } + for (int j = 0; j < TN; j++) + scv[j] = R4D_WS(k0 / GRP, j); } - // The activation row-sums have exactly the scale's problem, and worse: every wave in every - // workgroup hits the group boundary on the same k0, so eight `v4f` loads issued where they are - // used stall the whole machine at once. An ablation that keeps the correction's arithmetic and - // drops only the loads shows the loads cost about twice what the FMAs do. - // OPT bit 6 issues them a full 64-k iteration ahead, at the cost of TM*8 live VGPRs. - if (ASYM && (OPT & 64) && (k0 % GRP) == 0) { - const int Mpadp = ((M + 15) / 16) * 16; -#pragma unroll - for (int i = 0; i < TM; i++) { - int rb = m0 + (wm * TM + i) * 16 + 8 * (lane >> 4); - rb = rb < Mpadp - 8 ? rb : Mpadp - 8; - const v4f_t* pv = (const v4f_t*)(Asum + (size_t)(k0 / GRP) * Mpadp + rb); - const v4f_t v0 = pv[0], v1 = pv[1]; -#pragma unroll - for (int e = 0; e < 4; e++) { asp[i][e] = v0[e]; asp[i][e + 4] = v1[e]; } - } - } - if (IU4) { -#pragma unroll - for (int c = 0; c < BK / 32; c++) { - // ONE PLANE AT A TIME. Holding ah[TM] and al[TM] together costs TM more v2i of live range - // on a kernel that already pays 8*TM*TN for the second accumulator: 115 VGPRs against the - // iu8 path's 85, straight through the 96-VGPR step and from 16 waves per SIMD down to 12. - // Doing the high plane's WMMAs and then the low plane's reuses the registers; the cost is - // re-reading the weight fragment once per plane, and the - // DCE-proof ablation already showed the W LDS read is free once the unpack is gone. -#pragma unroll - for (int P = 0; P < 2; P++) { - v2i_t af4[TM]; -#pragma unroll - for (int i = 0; i < TM; i++) { - const int row = (wm * TM + i) * 16 + (lane & 15); - // dword offset in the row: c*8 for the K=32 chunk, +4 for the low plane, +2 per half - const unsigned* pa4 = lds_a[buf] + ASW(row, c * 8 + P * 4 + 2 * (lane >> 4)); - af4[i][0] = (int)pa4[0]; - af4[i][1] = (int)pa4[1]; - } -#pragma unroll - for (int j = 0; j < TN; j++) { - const u4v_t wv = *(const u4v_t*)(lds_w[buf] + (size_t)(wn * TN + j) * 128 + lane * 4); - v2i_t bq; // two k steps = one K=32 iu4 B fragment - bq[0] = (int)wv[2 * c]; - bq[1] = (int)wv[2 * c + 1]; -#pragma unroll - for (int i = 0; i < TM; i++) { - const bool f = (first_half && c == 0); - // P = 0 is the signed high half, P = 1 the unsigned low half. - if (P == 0) - g2[j][i] = __builtin_amdgcn_wmma_i32_16x16x32_iu4_w32_gfx12( - true, af4[i], true, bq, f ? (v8i_t)(0) : g2[j][i], false); - else - g[j][i] = __builtin_amdgcn_wmma_i32_16x16x32_iu4_w32_gfx12( - false, af4[i], true, bq, f ? (v8i_t)(0) : g[j][i], false); - } - } - } - } - } else { - // OPT BIT 16384: PREFETCH THE A FRAGMENTS ONE K STEP AHEAD. - // The ISA of the shipped tile issues a k step's `ds_load_2addr_stride64_b64` and then waits on - // it one instruction later -- `s_wait_dscnt 0x1` sits between the load and the first WMMA that - // consumes it, and `s_wait_dscnt 0x0` sits between the second and third WMMA of every triple. - // The loads have essentially no cover. Rotating a second register set moves each load a whole - // WMMA triple plus an unpack earlier, at the cost of TM*2 VGPRs. - v2i_t afp[TM]; - auto aload = [&](int uu, v2i_t* dst) { -#pragma unroll - for (int i = 0; i < TM; i++) { - const int row = (wm * TM + i) * 16 + (lane & 15); - if (ANOLDS) { - const int rt0 = m0 / 16 + wm * TM + i, rtm = (M - 1) / 16; - const int rt = rt0 < rtm ? rt0 : rtm; - dst[i] = *(const v2i_t*)(A + ((size_t)rt * (K / 16) + (k0 / 16 + uu)) * 256 + lane * 8); - continue; - } - const unsigned* pa = lds_a[buf] + ASW(row, uu * 4 + 2 * (lane >> 4)); - dst[i][0] = (int)pa[0]; - dst[i][1] = (ABX == 7) ? (int)pa[0] : (int)pa[1]; - } - }; - if (OPT & 16384) aload(0, afp); #pragma unroll for (int u = 0; u < BK / 16; u++) { v2i_t af[TM]; - if (OPT & 16384) { -#pragma unroll - for (int i = 0; i < TM; i++) af[i] = afp[i]; - if (u + 1 < BK / 16) aload(u + 1, afp); - } else #pragma unroll for (int i = 0; i < TM; i++) { const int row = (wm * TM + i) * 16 + (lane & 15); - if (ANOLDS) { - // [row tile][k step][lane][8 bytes]: lane-contiguous, so one coalesced 8-byte load per - // (i, u). Clamped to the last real row tile only because the CURRENT artifact is not - // padded to a multiple of 16 rows; a real one would be, and the clamp would not exist. - const int rt0 = m0 / 16 + wm * TM + i, rtm = (M - 1) / 16; - const int rt = rt0 < rtm ? rt0 : rtm; - const v2i_t* pg = - (const v2i_t*)(A + ((size_t)rt * (K / 16) + (k0 / 16 + u)) * 256 + lane * 8); - af[i] = *pg; - continue; - } const unsigned* pa = lds_a[buf] + ASW(row, u * 4 + 2 * (lane >> 4)); - // ABL 7 prices the SECOND activation LDS dword only -- halving the A read while keeping - // the staging path live, which is what a wider A permutation would buy. A version that - // dropped both made lds_a dead and deleted the staging, which is not a measurement. af[i][0] = (int)pa[0]; - af[i][1] = (ABX == 7) ? (int)pa[0] : (int)pa[1]; + af[i][1] = (int)pa[1]; } - if (ABX == 8) { - // THE INSTRUCTION MIX HAS TO MATCH THE REAL KERNEL OR THIS PRICES NOTHING. - // Doing both iu4 calls on even u only leaves the odd u's `af` dead -- the compiler deletes - // those `ds_load_b64` and the variant then does HALF the activation reads the real thing - // would. For K=64 the real kernel loads A_hi and A_lo for two K=32 chunks: four - // `ds_load_b64` per (i, BK), exactly what the iu8 path loads. So run every u and do ONE - // iu4 per (i, j, u), alternating the accumulator -- four A loads, four matrix instructions, - // one b128 of B, no dequant. -#pragma unroll - for (int j = 0; j < TN; j++) { - const u4v_t wv4 = *(const u4v_t*)(lds_w[buf] + (size_t)(wn * TN + j) * 128 + lane * 4); - v2i_t bq; - bq[0] = (int)wv4[u & ~1]; - bq[1] = (int)wv4[(u & ~1) + 1]; -#pragma unroll - for (int i = 0; i < TM; i++) { - // The signedness argument must be a literal, so the two halves are two call sites - // rather than one with a computed flag. - const bool f = (first_half && u < 2); - if (u & 1) - g2[j][i] = __builtin_amdgcn_wmma_i32_16x16x32_iu4_w32_gfx12( - false, af[i], true, bq, f ? (v8i_t)(0) : g2[j][i], false); - else - g[j][i] = __builtin_amdgcn_wmma_i32_16x16x32_iu4_w32_gfx12( - true, af[i], true, bq, f ? (v8i_t)(0) : g[j][i], false); - } - } - } else #pragma unroll for (int j = 0; j < TN; j++) { - // ABL 5 prices the UNPACK: same LDS read, no dequant VALU. ABL 6 prices the weight LDS - // read as well. Both compute wrong answers by construction; they exist to say what the gap - // between this kernel's rate and the 407 TOPS matrix ceiling is made of. - u4v_t wv; - if constexpr (WNOLDS) - wv = rwg[buf][j]; - else - wv = (WU || ABX == 6) - ? (u4v_t)(0x21212121u) - : *(const u4v_t*)(lds_w[buf] + (size_t)(wn * TN + j) * 128 + lane * 4); - v2i_t bf; - if (WU) bf = *(const v2i_t*)(lds_w[buf] + (size_t)(wn * TN + j) * 256 + lane * 8 + u * 2); - else - // ABL 5 KEEPS THE DATA DEPENDENCY, and it has to. Assigning constants here would make the - // LDS read dead and let the compiler delete the whole weight staging path, which prices - // something else entirely. Forwarding the raw dword prices the three unpack instructions - // and nothing else: same load, same live range, no masks and no shift. - if (ABX == 5) { bf[0] = (int)wv[u]; bf[1] = (int)wv[u]; } - else if (ABX == 6) { bf[0] = 0x10101010; bf[1] = 0x20202020; } - else bf = tdequant8(wv[u]); + const u4v_t wv = *(const u4v_t*)(lds_w[buf] + (size_t)(wn * TN + j) * 128 + lane * 4); + const v2i_t bf = tdequant8(wv[u]); #pragma unroll for (int i = 0; i < TM; i++) g[j][i] = (first_half && u == 0) - ? tmmai(af[i], bf, (v8i_t)(BIAS == 2 ? 0x4B400000 : 0)) + ? tmmai(af[i], bf, (v8i_t)(BIAS ? 0x4B400000 : 0)) : tmmai(af[i], bf, g[j][i]); } } - } - // OPT BIT 2048: SCHEDULE THE K-BLOCK BY HAND. - // Left alone, LLVM interleaves the fragment reads with the matrix work and drains LDS between - // them -- the ISA reads `WW d W RR d WW d W RR`, an `s_wait_dscnt` inside the WMMA run. The - // same pathology appears in the R4D attention kernel and the same fix applies: name the - // pipeline, DS reads then unpack then matrix, and let the staging fill the gaps. Counts are - // per k-block and are upper bounds -- an unmatched instruction is simply scheduled freely, and - // the A reads in particular collapse into `ds_load_2addr_stride64_b64` pairs, so asking for - // more DS reads than exist is harmless. - if (OPT & 2048) { - constexpr int NW = TM * TN * (BK / 16); // matrix instructions - constexpr int NR = TM * (BK / 16) + TN; // A fragments + the weight b128 - constexpr int NV = 3 * TN * (BK / 16); // the unpack - if (OPT & 4096) { // finer: one stage per k step -#pragma unroll - for (int q = 0; q < BK / 16; q++) { - __builtin_amdgcn_sched_group_barrier(0x100, NR / (BK / 16) + 1, 0); - __builtin_amdgcn_sched_group_barrier(0x002, NV / (BK / 16), 0); - __builtin_amdgcn_sched_group_barrier(0x008, NW / (BK / 16), 0); - } - } else { // coarse: the whole k-block in three stages - __builtin_amdgcn_sched_group_barrier(0x100, NR, 0); - __builtin_amdgcn_sched_group_barrier(0x002, NV, 0); - __builtin_amdgcn_sched_group_barrier(0x008, NW, 0); - } - } - - if ((k0 + BK) % AGRP == 0) { // the group closed: fold it into the float acc - if (TWOACC) { - // The hi/lo combine belongs at the GROUP close, not every k step -- both halves accumulate - // in int32 across the whole group and only the float fold needs them summed. Doing it per - // k step costs 2x at GRP=128/BK=64. One `v_lshl_add_u32` per element per group. -#pragma unroll - for (int j = 0; j < TN; j++) -#pragma unroll - for (int i = 0; i < TM; i++) -#pragma unroll - for (int e = 0; e < 8; e++) g[j][i][e] += g2[j][i][e] << 4; - } + if ((k0 + BK) % GRP == 0) { // the group closed: fold it into the float acc float sc[TN]; #pragma unroll for (int j = 0; j < TN; j++) - { - // 32-BIT INDEX. With size_t the whole address goes 64-bit and every group pays - // v_ashrrev + v_lshlrev_b64 + two v_add_co per scale; the element count here is at most - // (N/16)*(K/GRP)*16, a few hundred thousand. - const unsigned raw = - ABX == 4 ? 0x3C00u /* ABL 4: no scale LOAD, same arithmetic */ - : (OPT & 1) ? scv[j] : R4D_WS(k0 / GRP, j); - sc[j] = __half2float(__ushort_as_half((unsigned short)(raw & 0xFFFFu))); - // OPT BIT 8192: STOP THE f16 CONVERSION FOLDING INTO THE FOLD. - // Left alone the compiler contracts `(float)h * x + acc` into `v_fma_mix_f32`, which reads - // the f16 for free -- and is VOP3P, so it can never dual-issue. `v_fmac_f32` IS on the VOPD - // list (`v_dual_fmac_f32 :: v_dual_fmac_f32` assembles for gfx1201), and the fold is - // TM*TN*8 = 24 of the tile's 221 instructions per scale group. One `asm` per group forces - // the convert to materialise and leaves 24 plain FMACs for the VOPD packer. - if (OPT & 8192) asm("" : "+v"(sc[j])); - } - // THE ASYMMETRIC GRID. With the nibble read unsigned the dequantised weight is - // (q - z) * s, so the group contributes s * (sum_k a_k q_k - z * sum_k a_k) and the second - // term needs a per-row per-group sum of the ACTIVATION -- `r4d_quant_act_i8_asum`'s output, - // laid out [G][Mpad] because element e of tile i at this lane is output row - // (m0 + (wm*TM+i)*16 + 8*(lane>>4) + e), so a lane's eight rows are CONTIGUOUS at a fixed - // group and load as two `v4f`. The zero rides in the scale dword's high half as the f16 of - // -(1024 + z), which is exact because f16 has exactly 1024 steps between 1024 and 2048. - // - // It costs ONE extra fma per element and nothing else: symz needs `cvt` then `fma`, asym - // needs `fma` then `fma`, and the magic bias has already deleted the cvt. The loop is nested - // i-outer so only ONE tile's eight asum values are live -- asum[TM][8] at TM=4 is 32 VGPRs - // against a budget of 192 that is already exactly full. + sc[j] = __half2float(__ushort_as_half((unsigned short)(scv[j] & 0xFFFFu))); if (BIAS) { #pragma unroll for (int j = 0; j < TN; j++) csum[j] += sc[j]; } + // Asymmetric grid: the group contributes s * (sum_k a_k q_k - z * sum_k a_k), using the + // per-row per-group activation sums from r4d_quant_act_i8_asum, laid out [G][Mpad] so a + // lane's eight rows (m0 + (wm*TM+i)*16 + 8*(lane>>4) + e) load as two v4f. The zero is the + // scale dword's high half, the f16 of -(1024 + z) (exact). One extra fma per element; the + // loop is i-outer so only one tile's eight sums are live. float z16[TN]; if (ASYM) { #pragma unroll for (int j = 0; j < TN; j++) { - const unsigned raw = - (OPT & 1) ? scv[j] - : Ws[(unsigned)(((n0 / 16 + wn * TN + j) * nsz + k0 / GRP) * 16 + - (lane & 15))]; - const float nz = __half2float(__ushort_as_half((unsigned short)(raw >> 16))); + const float nz = __half2float(__ushort_as_half((unsigned short)(scv[j] >> 16))); z16[j] = 16.f * (-nz - 1024.f); } } const int Mpad = ((M + 15) / 16) * 16; - // ONE TILE AHEAD (OPT bit 7). Written as load-then-use per tile, the four tiles' asum loads - // serialise: each one's latency is fully exposed because the sixteen fmas that could hide it - // come after it, not before. Holding all TM*8 values instead (the skinny kernel's shape) is - // 32 VGPRs on a kernel that has 6 spare and spills 164 bytes. Two v4f sets -- current and - // next -- is 16, and only the first load's latency is left uncovered. -#define R4D_ASUM_LD(ii, a, b) \ - do { \ - int rb_ = m0 + (wm * TM + (ii)) * 16 + 8 * (lane >> 4); \ - rb_ = rb_ < Mpad - 8 ? rb_ : Mpad - 8; \ - const v4f_t* pv_ = (const v4f_t*)(Asum + (size_t)(k0 / GRP) * Mpad + rb_); \ - (a) = pv_[0]; \ - (b) = pv_[1]; \ - } while (0) - v4f_t c0, c1; - if (ASYM && (OPT & 128)) R4D_ASUM_LD(0, c0, c1); #pragma unroll for (int i = 0; i < TM; i++) { - constexpr int NE = ABX == 5 ? 1 : 8; /* ABL 5: 1/8 of the arithmetic */ float as[8]; if (ASYM) { - if (OPT & 32) { /* prices the fmas without their loads */ + int rb = m0 + (wm * TM + i) * 16 + 8 * (lane >> 4); + rb = rb < Mpad - 8 ? rb : Mpad - 8; // rows past M are stored away, not read + const v4f_t* pv = (const v4f_t*)(Asum + (size_t)(k0 / GRP) * Mpad + rb); + const v4f_t v0 = pv[0], v1 = pv[1]; #pragma unroll - for (int e = 0; e < 8; e++) as[e] = 1.f; - } else if (OPT & 64) { -#pragma unroll - for (int e = 0; e < 8; e++) as[e] = asp[i][e]; - } else if (OPT & 128) { - const v4f_t u0 = c0, u1 = c1; - if (i + 1 < TM) R4D_ASUM_LD(i + 1, c0, c1); // in flight across THIS tile's fmas -#pragma unroll - for (int e = 0; e < 4; e++) { as[e] = u0[e]; as[e + 4] = u1[e]; } - } else { - int rb = m0 + (wm * TM + i) * 16 + 8 * (lane >> 4); - rb = rb < Mpad - 8 ? rb : Mpad - 8; // rows past M are stored away, not read - const v4f_t* pv = (const v4f_t*)(Asum + (size_t)(k0 / GRP) * Mpad + rb); - const v4f_t v0 = pv[0], v1 = pv[1]; -#pragma unroll - for (int e = 0; e < 4; e++) { as[e] = v0[e]; as[e + 4] = v1[e]; } - } + for (int e = 0; e < 4; e++) { as[e] = v0[e]; as[e + 4] = v1[e]; } } #pragma unroll for (int j = 0; j < TN; j++) #pragma unroll - for (int e = 0; e < NE; e++) { - float v = BIAS == 2 ? __uint_as_float((unsigned)g[j][i][e]) - : BIAS == 1 ? __uint_as_float((unsigned)g[j][i][e] + 0x4B400000u) - : (float)g[j][i][e]; + for (int e = 0; e < 8; e++) { + float v = BIAS ? __uint_as_float((unsigned)g[j][i][e]) : (float)g[j][i][e]; if (ASYM) v = fmaf(-z16[j], as[e], v); acc[j][i][e] = fmaf(v, sc[j], acc[j][i][e]); } } -#undef R4D_ASUM_LD } - if ((ABL == 0 || ABL >= 10) && k0 + BK < kend) commit(buf ^ 1); // the wait for those loads lands HERE - if (ABX != 2) ldsbar(); + if (k0 + BK < K) commit(buf ^ 1); // the wait for those loads lands here + __syncthreads(); } } +#undef R4D_WS #undef ASW if (BIAS) { @@ -878,89 +272,9 @@ __global__ __launch_bounds__(WM * WN * 32, WPE) void r4d_gemm_w4a8_tiled_kernel( } } - // ---- the split tail's partial, and its reduction ---- - // - // The partial is the accumulator AFTER the magic-bias correction and BEFORE `Ascale[m]`, because - // the row scale is common to every piece and multiplying it in once at the end is both cheaper - // and exactly what the unsplit path does. Rows past M are never written and never read: at - // M = 72 in a BM = 96 tile that is a quarter of the workspace traffic saved for free. - // - // The counter lives in ONE dword of `lds_a`, not in a `__shared__` of its own: A and W are - // exactly 32 KB together and four more bytes would drop a CU from two workgroups to one. The - // k loop is finished by here, so the buffer is dead. - if (SKT && slot >= 0) { - float* wsp = WSP + (size_t)slot * BM * BN; -#pragma unroll - for (int j = 0; j < TN; j++) -#pragma unroll - for (int i = 0; i < TM; i++) -#pragma unroll - for (int e = 0; e < 8; e++) { - const int nl = (wn * TN + j) * 16 + (lane & 15); - const int ml = (wm * TM + i) * 16 + 8 * (lane >> 4) + e; - if (m0 + ml < M) wsp[(size_t)ml * BN + nl] = acc[j][i][e]; - } - // THE FENCE HAS TO BE ON EVERY THREAD, not just the one that bumps the counter. A fence - // orders the stores of the thread that executes it; `__syncthreads()` is a workgroup-scope - // release and says nothing about when the other 511 threads' stores become visible to another - // CU. With the fence on thread 0 alone this kernel returns a DIFFERENT wrong answer on every - // call -- the reducer reads whatever happens to have drained. - __threadfence(); - __syncthreads(); - const int cidx = (int)blockIdx.y * nrag + (tilex - nfull); - if (tid == 0) - lds_a[0][0] = __hip_atomic_fetch_add(&CNT[cidx], 1u, __ATOMIC_ACQ_REL, - __HIP_MEMORY_SCOPE_AGENT); - __syncthreads(); - if (lds_a[0][0] != (unsigned)(nspl - 1)) return; - if (tid == 0) CNT[cidx] = 0u; // left clean for the next call on this stream - __threadfence(); // acquire, before reading the other pieces - const float* base = - WSP + (size_t)((int)blockIdx.y * (nrag * nspl) + (tilex - nfull) * nspl) * BM * BN; -#pragma unroll - for (int j = 0; j < TN; j++) -#pragma unroll - for (int i = 0; i < TM; i++) -#pragma unroll - for (int e = 0; e < 8; e++) { - const int nl = (wn * TN + j) * 16 + (lane & 15); - const int ml = (wm * TM + i) * 16 + 8 * (lane >> 4) + e; - const int n = n0 + nl, m = m0 + ml; - if (n < N && m < M) { - float v = 0.f; - // SKT == 2 is a DEBUG variant: reduce only the first piece, so the output is piece 0's - // partial and can be scored against the unsplit kernel run on the K slice [0, K/nspl). - for (int q = 0; q < nspl; q++) - v += base[(size_t)q * BM * BN + (size_t)ml * BN + nl]; - C[(size_t)m * N + n] = (__hip_bfloat16)(v * Ascale[m] * (IU4 ? 1.0f : 0.0625f)); - } - } - return; - } - - // ---- store ---- - // - // FIVE FORMS OF THIS EPILOGUE WERE COMPARED; THE FLAT PREDICATED ONE WINS EVERY TIME. - // - // flat predicated store (this) - // transpose through LDS as bf16 - // transpose through LDS as shuffle-packed dwords - // reorder to hoist Ascale, early-out on m - // reorder to hoist Ascale + the 64-bit m*N, pure predication - // - // The epilogue is NOT bandwidth-bound: folding every address down to 64 rows, so the whole output - // is cache-resident while the instruction count is untouched, takes the same time. That is why - // both transposes lose -- they add instructions to fix a bandwidth problem that does not exist. - // (An ablation that simply deletes the stores makes them look like 40% of the kernel, but it also - // deletes the accumulator's only consumer, so most of that is dead-code elimination; the - // transposed-accumulator note below says what happens when the stores really do get cheaper.) - // - // And reducing the count by hand does not help either. Hoisting the Ascale load and the 64-bit - // row multiply out of the j loop is a real reduction -- 16 of each instead of 64 -- and is slower - // whether the guard is a branch or a predicate. Putting j innermost is what does it: the - // accumulator is acc[j][i][e], so j-innermost strides the register file, and the four stores then - // share one guard instead of being independently predicated. The compiler schedules the flat form - // better than any of the four rewrites. + // The flat predicated store beat LDS transposes (bf16 or packed dwords) and hand-hoisted Ascale / + // row-offset variants: the epilogue is not bandwidth-bound (a cache-resident output takes the same + // time), and with j innermost the stores stride the register file and share one guard. #pragma unroll for (int j = 0; j < TN; j++) #pragma unroll @@ -970,160 +284,22 @@ __global__ __launch_bounds__(WM * WN * 32, WPE) void r4d_gemm_w4a8_tiled_kernel( const int n = n0 + (wn * TN + j) * 16 + (lane & 15); const int m = m0 + (wm * TM + i) * 16 + 8 * (lane >> 4) + e; if (n < N && m < M) - // 0.0625 undoes the 16 the iu8 unpack puts in the byte's high nibble. The iu4 path - // multiplies the RAW nibble, so there is no 16 to undo. - C[(size_t)m * N + n] = - (__hip_bfloat16)(acc[j][i][e] * Ascale[m] * (IU4 ? 1.0f : 0.0625f)); + // 0.0625 undoes the 16 from the unpack's high-nibble placement. + C[(size_t)m * N + n] = (__hip_bfloat16)(acc[j][i][e] * Ascale[m] * 0.0625f); } } - -// THE TRANSPOSED ACCUMULATOR IS NEUTRAL. The code is not here; this note is why not. -// -// gfx12's WMMA output is column-distributed -- lanes index the column, the eight accumulator -// registers index the row -- so with the activation as the A operand a lane owns eight DIFFERENT -// ROWS of one column and each of its 64 outputs is an independent 2-byte store. Swapping the A and -// B operands transposes D (AMD's own RDNA4 WMMA guide documents the swap for exactly this), a lane -// then owns eight CONSECUTIVE COLUMNS of one row, and the epilogue collapses to eight -// `global_store_b128` with `Ascale[m]` loaded twice instead of 64 times. Coalescing is unchanged: -// 128 segments for the wave's 4096 bytes either way. -// -// It is EXACTLY NEUTRAL on `gate_proj`, inside the run-to-run spread, and correct to the same -// 2.32e-3. The store epilogue is not the cost: the ablation that appears to make it 40% of the -// kernel deletes the accumulator's only consumer, so most of that 40% is dead-code elimination. -// The transposed form also costs 193 VGPRs unless it is written carefully, which is a fifth of the -// runtime on its own. - -// THE BLOCK TILE IS NOT FIXED, because 128 x 256 is the wrong shape for a mid-sized M. At -// M = 128-256 that tile gives one or two M-blocks and almost no M-parallelism, and that is exactly -// the band where the kernel falls behind the block-fp8 bar while beating it at M = 64 and matching -// it at M = 4096. The grid therefore comes from the template arguments rather than a constant. -// THE TAIL WORKSPACE is a cached allocation, grown on demand and never freed, ONE A (DEVICE, -// STREAM). It is only ever touched by the tail workgroups of a single launch, and two launches on -// one stream cannot overlap on it. The counters are zeroed once here and left at zero by the -// kernel, which is what makes a graph replay safe: nothing per-call runs on the host. -// -// Both halves of that rest on ONE STREAM, which is why the cache is keyed the way gemm_fp8a8's -// split_ctr is. A tensor-parallel process launches on one device a rank, so a single allocation -// would hand one device's pointer to the other's kernel; and `rad_lane` runs a second stream beside -// the first, where two launches sharing one workspace would reduce into each other's pieces and -// each see the other's counter arrivals. A rank runs a compute stream and at most one lane, so the -// table is small and fixed, and a stream past it is refused rather than shared. -constexpr int kSktStreams = 4; -struct SktSlot { - bool used = false; - hipStream_t key = nullptr; - float* ws = nullptr; - size_t ws_bytes = 0; - unsigned* cnt = nullptr; - size_t cnt_n = 0; -}; - -// AND IT IS THE LAST ALLOCATION ON A LAUNCH PATH IN THIS LIBRARY, which the fp8a8 header calls out -// as the thing not to do ("Nothing on an R4D launch path allocates, so the partial plane is an -// argument and r4d_gemm_fp8a8_nt_m16_scratch() sizes it"). It is bounded -- the guard above caps -// mblk*nrag*nspl at 64 and a piece is BM*BN floats, so a couple of MiB at the shapes that take the -// split at all -- and it is taken once and kept, so it costs one hipMalloc a (device, stream) in -// the life of a process rather than one a step. -// -// It is still invisible to the engine's VRAM budget. core/mem/vram_budget.cpp sizes the pools -// down to --gpu-headroom-mib from terms it can compute, and a plugin's own hipMalloc is not one of -// them: core/device/dispatch.cpp's ledger counts what goes through rad_dev_alloc and nothing that -// goes around it. Engine::start reads the card back afterwards for exactly this reason, so the -// bytes show up as "settled at N free against the M --gpu-headroom-mib asked to keep" rather than -// as a number nobody can name. -// -// THE FIX IS THE SCRATCH HOOK, NOT A BIGGER HEADROOM -- with one obstacle worth writing down -// before somebody tries it. The workspace itself would move to a->scratch cleanly: it is written -// and read inside one launch. The COUNTERS cannot, because the contract that makes a graph replay -// safe is that they are zero at kernel entry and left at zero on exit, and the arena's scratch -// region is shared by every op on the stream -- the next kernel to use it would leave them -// anything at all. They need a persistent declared buffer, which the buffer plan would then place -// and the budget would then charge. -static void r4d_skt_reserve(hipStream_t stream, size_t ws_bytes, size_t cnt_n, float** ws, - unsigned** cnt) { - static std::mutex mu; - static SktSlot slot[16][kSktStreams]; - int dev = 0; - if (hipGetDevice(&dev) != hipSuccess || dev < 0 || dev >= 16) - throw std::runtime_error("r4d gemm_w4a8_tiled: no current device for the split-tail workspace"); - std::lock_guard lk(mu); - SktSlot* e = nullptr; - for (SktSlot& x : slot[dev]) - if (x.used && x.key == stream) { e = &x; break; } - if (!e) { - for (SktSlot& x : slot[dev]) - if (!x.used) { e = &x; break; } - if (!e) throw std::runtime_error("r4d gemm_w4a8_tiled: more streams than split-tail workspaces"); - e->used = true; - e->key = stream; - } - if (ws_bytes > e->ws_bytes) { - if (e->ws) (void)hipFree(e->ws); - e->ws = nullptr; - e->ws_bytes = 0; - if (hipMalloc((void**)&e->ws, ws_bytes) != hipSuccess) - throw std::runtime_error("r4d gemm_w4a8_tiled: split-tail workspace alloc failed"); - e->ws_bytes = ws_bytes; - } - if (cnt_n > e->cnt_n) { - if (e->cnt) (void)hipFree(e->cnt); - e->cnt = nullptr; - e->cnt_n = 0; - if (hipMalloc((void**)&e->cnt, cnt_n * sizeof(unsigned)) != hipSuccess) - throw std::runtime_error("r4d gemm_w4a8_tiled: split-tail counter alloc failed"); - (void)hipMemset(e->cnt, 0, cnt_n * sizeof(unsigned)); - e->cnt_n = cnt_n; - } - *ws = e->ws; - *cnt = e->cnt; -} - -// HOW MANY WAYS TO SPLIT THE TAIL. Enough pieces to fill the 32 slots, but the piece boundary has -// to land on a scale group or the group epilogue reads the wrong scale, so `nspl` must divide -// K/GROUP. Capped at 8 because the tail cost turns back up past that point: the pieces become too -// short to hide their own prologue. -static int r4d_skt_split(int nrag, int K) { - const int ngrp = K / R4D_GEMM_W4A8_GROUP; - const int want = 32 / (nrag > 0 ? nrag : 32); - int best = 1; - for (int t = 2; t <= 8 && t <= want; t++) - if (ngrp % t == 0) best = t; - return best; -} - -template +template static void r4d_tiled_launch(long a, long ascale, long wq, long ws, long asum, long c, int M, int K, int N, long stream) { constexpr int BM = WM * TM * 16, BN = WN * TN * 16; if (N % BN) throw std::runtime_error("r4d gemm_w4a8_tiled: N is not a multiple of this variant's block"); - const int tiles = N / BN, mblk = (M + BM - 1) / BM; - int nfull = tiles, nrag = 0, nspl = 1, gx = tiles; - float* skt_ws = nullptr; - unsigned* skt_cnt = nullptr; - if (SKT) { - nrag = tiles & 31; - nfull = tiles - nrag; - nspl = nrag ? r4d_skt_split(nrag, K) : 1; - // A tail worth splitting, and a workspace worth keeping: at decode mblk is 1 and this is a - // couple of MiB. At prefill mblk is large, the tail is a rounding error against the M blocks, - // and the workspace would not be -- so the split is simply off there. - if (nrag == 0 || nspl < 2 || (size_t)mblk * nrag * nspl > 64) { - nfull = tiles; nrag = 0; nspl = 1; - } else { - gx = nfull + nrag * nspl; - r4d_skt_reserve((hipStream_t)stream, (size_t)mblk * nrag * nspl * BM * BN * sizeof(float), - (size_t)mblk * nrag, &skt_ws, &skt_cnt); - } - } - dim3 grid(gx, mblk), block(WM * WN * 32); - hipLaunchKernelGGL( - (r4d_gemm_w4a8_tiled_kernel), grid, - block, 0, (hipStream_t)stream, (const signed char*)a, (const float*)ascale, - (const unsigned*)wq, (const unsigned*)ws, (const float*)asum, (__hip_bfloat16*)c, M, K, N, - skt_ws, skt_cnt, nfull, nrag, nspl); + dim3 grid(N / BN, (M + BM - 1) / BM), block(WM * WN * 32); + hipLaunchKernelGGL((r4d_gemm_w4a8_tiled_kernel), grid, block, 0, + (hipStream_t)stream, (const signed char*)a, (const float*)ascale, + (const unsigned*)wq, (const unsigned*)ws, (const float*)asum, + (__hip_bfloat16*)c, M, K, N); } static void r4d_gemm_w4a8_tiled_impl(long a, long ascale, long wq, long ws, long asum, long c, @@ -1132,319 +308,39 @@ static void r4d_gemm_w4a8_tiled_impl(long a, long ascale, long wq, long ws, long if (K % R4D_GEMM_W4A8_GROUP) throw std::runtime_error("r4d gemm_w4a8_tiled: K must be a multiple of the scale group"); if (M < 1) throw std::runtime_error("r4d gemm_w4a8_tiled: M must be positive"); - // THE UNROLL MUST COVER EXACTLY ONE SCALE GROUP -- no more. GRP/BK makes the group boundary a - // compile-time constant, which is the whole point; going further just doubles live ranges and - // wrecks the register allocation. At group 128, UNR = GRP/BK sits at the fp8 bar, UNR = 1 is - // about a tenth over it, and UNR = 4 is more than twice it; a group-64 build forced to two groups - // a trip is four times it. - constexpr int UNRG = R4D_GEMM_W4A8_GROUP / R4D_TILED_KPB > 1 - ? R4D_GEMM_W4A8_GROUP / R4D_TILED_KPB - : 1; - const bool ufull = (K % (UNRG * R4D_TILED_KPB)) == 0; + // The unroll covers exactly one scale group: less leaves the boundary dynamic (~10% slower), more + // doubles live ranges (over 2x slower). The K check above makes every K a whole number of them. + static_assert(R4D_GEMM_W4A8_GROUP % R4D_TILED_KPB == 0, "the scale group must be whole k blocks"); + constexpr int UNRG = R4D_GEMM_W4A8_GROUP / R4D_TILED_KPB; #define R4D_TILED_LAUNCH(...) \ r4d_tiled_launch<__VA_ARGS__>(a, ascale, wq, ws, asum, c, M, K, N, stream) - // The variant argument selects an alternative tile and exists for the bench; 0 is what ships. - // A variant that lost and has nothing left to say is NOT kept as an instantiation -- each one is - // a kernel to compile. + // The unroll loses on the asymmetric path (186 VGPRs), so it keeps UNR = 1, and it has one tile. if (asym) { - switch (variant) { - // EVERY asym instantiation with the magic bias SPILLS -- z16[TN], as[8] and csum[TN] land on - // top of 128 accumulator registers -- so the asym variants drop it. BIAS=0 at <2,8,4,2> is - // 186 VGPRs with no scratch; BIAS=2 is 192 with 24 bytes. - case 1: R4D_TILED_LAUNCH(2, 8, 4, 2, 0, 0, 51, 8, 1, 1); break; // no asum LOADS - case 2: R4D_TILED_LAUNCH(2, 8, 4, 2, 2, 0, 19, 8, 1, 1); break; // magic bias - // The unroll is a LOSS on the asymmetric path -- 186 VGPRs plus doubled live ranges -- so the - // asym default keeps UNR=1 where symz takes UNR=2. - case 3: R4D_TILED_LAUNCH(2, 8, 4, 2, 0, 0, 19, 8, 1, UNRG); break; // unrolled - // Losers, not instantiated: holding all TM*8 asum values (OPT 64) spills 164 bytes and costs - // half again; pipelining them one tile ahead (OPT 128) is neutral; TM=2 is a few percent - // worse. The code for all three is still in the kernel because each is one branch and - // together they document the wall. - default: R4D_TILED_LAUNCH(2, 8, 4, 2, 0, 0, 19, 8, 1, 1); break; - } - } else { - switch (variant) { - case 1: R4D_TILED_LAUNCH(4, 4, 2, 4, 0, 0, 0, 8, 0, 1); break; // 4x4 waves, 2x4 tiles, plain cvt - case 2: R4D_TILED_LAUNCH(2, 8, 4, 2, 2, 0, 19, 8, 0, 1); break; // UNR=1 - case 3: R4D_TILED_LAUNCH(2, 8, 4, 2, 2, 0, 3, 8, 0, UNRG); break; // no wide W - case 4: R4D_TILED_LAUNCH(2, 8, 4, 2, 0, 0, 19, 8, 0, UNRG); break; // no bias - case 5: R4D_TILED_LAUNCH(2, 8, 4, 2, 2, 0, 19, 8, 0, 2 * UNRG); break; // 2x - // BM=64 for the mid-M band. Same 256-wide N, half the M tile, so M=128 is two blocks instead - // of one and M=256 is four. TM*TN drops 8 -> 4, which also halves the accumulator registers. - case 6: R4D_TILED_LAUNCH(2, 8, 2, 2, 2, 0, 147, 8, 0, UNRG); break; // BM 64, BN 256, 512 thr - case 7: R4D_TILED_LAUNCH(1, 16, 4, 1, 2, 0, 19, 8, 0, UNRG); break; // BM 64, 1 wave deep - case 8: R4D_TILED_LAUNCH(2, 4, 2, 4, 2, 0, 19, 8, 0, UNRG); break; // BM 64, 256 thr - case 9: R4D_TILED_LAUNCH(2, 8, 4, 1, 2, 0, 19, 8, 0, UNRG); break; // BM 128, BN 128 - // BM 96 AND BM 80, FOR THE SPECULATIVE-DECODE BATCH. A serve at eight concurrent requests - // with verify width 9 runs M=72, and 72 is the worst M either kernel has: the skinny one - // needs five row tiles so it walks the weight five times, and BM=64 needs two blocks whose - // second holds 8 of 64 rows. BM=96 covers 72 in ONE block, so the weight is read once and - // nothing is half empty. BM=80 is the tightest fit and the widest tile per wave. - case 10: R4D_TILED_LAUNCH(2, 8, 3, 2, 2, 0, 147, 8, 0, UNRG); break; // BM 96, BN 256, 512 thr - case 12: R4D_TILED_LAUNCH(2, 8, 3, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 96, BN 128, 512 thr - // The staging tilings are not free choices: W needs WM | 4*TN and A needs WN | 8*TM, or the - // static_asserts above fire. That leaves WM*TM = 6 as the only route to BM 96, i.e. <2,_,3,_> - // or <1,_,6,_>, and it is why there is no <3,8,2,2>. Dropped: BM 80 in either width, BM 96 - // at 256 threads, BN 512 anywhere, and BM 64 at 1024 threads -- everything that raises A - // dwords-per-thread costs 2-3x. Also dropped: skipping the staging of rows past M - // (OPT bit 32), which is WORSE -- the divergent branch costs more than the duplicate rows it - // saves. - // Cost ablations on the two tiles that win at these batches. Wrong answers by construction. - case 24: R4D_TILED_LAUNCH(2, 8, 2, 2, 2, 5, 19, 8, 0, UNRG); break; // BM64 no unpack - case 25: R4D_TILED_LAUNCH(2, 8, 2, 2, 2, 6, 19, 8, 0, UNRG); break; // BM64 no W LDS read - case 26: R4D_TILED_LAUNCH(2, 8, 2, 2, 2, 7, 19, 8, 0, UNRG); break; // BM64 no A LDS read - case 27: R4D_TILED_LAUNCH(2, 8, 3, 1, 2, 5, 19, 8, 0, UNRG); break; // BM96 no unpack - case 28: R4D_TILED_LAUNCH(2, 8, 3, 1, 2, 6, 19, 8, 0, UNRG); break; // BM96 no W LDS read - case 29: R4D_TILED_LAUNCH(2, 8, 3, 1, 2, 7, 19, 8, 0, UNRG); break; // BM96 no A LDS read - // The same three against the SWIZZLED baseline, which is what ships; the unswizzled variants - // above overstate the A read, because it is 2-way conflicted there. - case 34: R4D_TILED_LAUNCH(2, 8, 3, 1, 2, 5, 147, 8, 0, UNRG); break; // BM96 swz, no unpack - case 35: R4D_TILED_LAUNCH(2, 8, 3, 1, 2, 6, 147, 8, 0, UNRG); break; // BM96 swz, no W lds - case 36: R4D_TILED_LAUNCH(2, 8, 3, 1, 2, 7, 147, 8, 0, UNRG); break; // BM96 swz, half A lds - case 37: R4D_TILED_LAUNCH(2, 8, 2, 2, 2, 5, 147, 8, 0, UNRG); break; // BM64 swz, no unpack - case 38: R4D_TILED_LAUNCH(2, 8, 2, 2, 2, 7, 147, 8, 0, UNRG); break; // BM64 swz, half A lds - // OPT bit 256: unpack the weight once at staging. 147|256 = 403. - case 40: R4D_TILED_LAUNCH(2, 8, 3, 1, 2, 0, 403, 8, 0, UNRG); break; // BM96 BN128 swz + WU - case 41: R4D_TILED_LAUNCH(2, 8, 2, 2, 2, 0, 403, 8, 0, UNRG); break; // BM64 BN256 swz + WU - case 42: R4D_TILED_LAUNCH(2, 8, 3, 2, 2, 0, 403, 8, 0, UNRG); break; // BM96 BN256 swz + WU - case 43: R4D_TILED_LAUNCH(2, 8, 4, 2, 2, 0, 403, 8, 0, UNRG); break; // BM128 BN256 swz + WU - // TALLER ROW TILES AT BN=128, so that M = 97..256 still reads the weight exactly ONCE. - // A second M-block doubles the weight traffic, and this kernel is weight-bandwidth-bound at - // decode M; BM=64 with two blocks reads 2x45 MiB at M=128 where BM=192 reads 45. - case 56: R4D_TILED_LAUNCH(2, 8, 6, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 192, BN 128, 512 thr - case 57: R4D_TILED_LAUNCH(2, 8, 5, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 160, BN 128, 512 thr - case 58: R4D_TILED_LAUNCH(2, 8, 8, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 256, BN 128, 512 thr - case 59: R4D_TILED_LAUNCH(2, 8, 4, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 128, BN 128, 512 thr - // SAME BLOCK TILE, DIFFERENT WAVE SPLIT. Per WMMA the loop pays 3/TM unpack VALU and 1/TN - // activation `ds_load_b64`, so BM 96 x BN 128 costs 2.0 as <2,8,3,1> and 1.5 either as - // <2,4,3,2> or as <1,8,6,1> -- at half the waves per block. - case 52: R4D_TILED_LAUNCH(2, 4, 3, 2, 2, 0, 147, 8, 0, UNRG); break; // BM 96, BN 128, 256 thr - case 53: R4D_TILED_LAUNCH(1, 8, 6, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 96, BN 128, 256 thr - // OPT bit 1024: the LDS-only barrier (147|1024 = 1171). - case 60: R4D_TILED_LAUNCH(2, 8, 3, 1, 2, 0, 1171, 8, 0, UNRG); break; // BM 96, BN 128 - case 61: R4D_TILED_LAUNCH(2, 8, 2, 2, 2, 0, 1171, 8, 0, UNRG); break; // BM 64, BN 256 - case 62: R4D_TILED_LAUNCH(2, 8, 3, 2, 2, 0, 1171, 8, 0, UNRG); break; // BM 96, BN 256 - case 63: R4D_TILED_LAUNCH(2, 8, 4, 2, 2, 0, 1171, 8, 0, UNRG); break; // BM 128, BN 256 - case 64: R4D_TILED_LAUNCH(2, 8, 5, 1, 2, 0, 1171, 8, 0, UNRG); break; // BM 160, BN 128 - // OPT bit 2048 = hand-scheduled k-block (147|2048 = 2195); |4096 = the finer variant (6291). - case 70: R4D_TILED_LAUNCH(2, 8, 3, 1, 2, 0, 2195, 8, 0, UNRG); break; // BM 96, BN 128 sched - case 71: R4D_TILED_LAUNCH(2, 8, 3, 1, 2, 0, 6291, 8, 0, UNRG); break; // BM 96, BN 128 sched/fine - case 72: R4D_TILED_LAUNCH(2, 8, 2, 2, 2, 0, 2195, 8, 0, UNRG); break; // BM 64, BN 256 sched - case 73: R4D_TILED_LAUNCH(2, 8, 3, 2, 2, 0, 2195, 8, 0, UNRG); break; // BM 96, BN 256 sched - case 74: R4D_TILED_LAUNCH(2, 8, 4, 2, 2, 0, 2195, 8, 0, UNRG); break; // BM 128, BN 256 sched - case 75: R4D_TILED_LAUNCH(2, 8, 4, 2, 2, 0, 6291, 8, 0, UNRG); break; // BM 128, BN 256 sched/fine - // ABL 9: the A fragment straight from global in a fragment-major layout, no A LDS at all. - case 46: R4D_TILED_LAUNCH(2, 8, 3, 1, 2, 9, 147, 8, 0, UNRG); break; // BM96 BN128 abl:A global - case 47: R4D_TILED_LAUNCH(2, 8, 2, 2, 2, 9, 147, 8, 0, UNRG); break; // BM64 BN256 abl:A global - case 48: R4D_TILED_LAUNCH(2, 8, 3, 2, 2, 9, 147, 8, 0, UNRG); break; // BM96 BN256 abl:A global - case 49: R4D_TILED_LAUNCH(2, 8, 4, 2, 2, 9, 147, 8, 0, UNRG); break; // BM128 BN256 abl:A global - case 44: R4D_TILED_LAUNCH(2, 8, 3, 1, 2, 8, 147, 8, 0, UNRG); break; // BM96 BN128 swz, iu4 abl - case 45: R4D_TILED_LAUNCH(2, 8, 2, 2, 2, 8, 147, 8, 0, UNRG); break; // BM64 BN256 swz, iu4 abl - // The iu4 path (147|512 = 659, BIAS 0), and its like-for-like iu8 twin. Rejected on the - // arithmetic above; kept as one pair so the result is reproducible. Takes the i4x2 - // activation (`w4a8pack.quant_act_i4x2`), NOT the int8 one -- same bytes, two 4-bit planes. - case 50: R4D_TILED_LAUNCH(2, 8, 3, 2, 0, 0, 659, 8, 0, UNRG); break; // BM 96, BN 256, iu4 - case 51: R4D_TILED_LAUNCH(2, 8, 3, 2, 0, 0, 147, 8, 0, UNRG); break; // the same tile on iu8 - // THE BALANCED TAIL (SKT = 1). Same tiles, same inner loop; the only difference is that the - // `tiles mod 32` blocks the grid would otherwise run alone in a last round are split along K - // and reduced through a workspace. One instantiation per tile the dispatch table actually - // picks at a decode M. - case 90: R4D_TILED_LAUNCH(2, 8, 3, 1, 2, 0, 147, 8, 0, UNRG, 1); break; // BM 96, BN 128 - case 91: R4D_TILED_LAUNCH(2, 8, 3, 2, 2, 0, 147, 8, 0, UNRG, 1); break; // BM 96, BN 256 - // The inner loop, from the ISA. - // 8192 = the f32 fold (VOPD-eligible FMAC), 16384 = the A-fragment prefetch, 147|... = both. - case 110: R4D_TILED_LAUNCH(2, 8, 3, 1, 2, 0, 147 | 8192, 8, 0, UNRG); break; - case 111: R4D_TILED_LAUNCH(2, 8, 3, 1, 2, 0, 147 | 16384, 8, 0, UNRG); break; - case 112: R4D_TILED_LAUNCH(2, 8, 3, 1, 2, 0, 147 | 8192 | 16384, 8, 0, UNRG); break; - // BM = 80 IS THE SMALLEST TILE THAT COVERS M = 72. The shipped BM = 96 tile does a sixth of - // its WMMA, its fold and its A reads on m-tile 5, which is entirely past M at eight - // sequences. `WM*TM=5` is prime, so one wave deep in M is the only split: TM=5 also drops - // the per-WMMA unpack from 3/TM = 1.0 to 0.6. 512 threads cannot stage BM = 80: AW = 1280 - // dwords and 1280 % 512 != 0, so the only legal width is 256, which triples the staging per - // thread. - case 114: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 80, BN 128, 256 thr - case 116: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 8192 | 16384, 8, 0, UNRG); break; - case 117: R4D_TILED_LAUNCH(2, 4, 3, 2, 2, 0, 147 | 8192 | 16384, 8, 0, UNRG); break; // BM96 BN256 256thr - case 118: R4D_TILED_LAUNCH(1, 8, 6, 1, 2, 0, 147 | 8192 | 16384, 8, 0, UNRG); break; // BM96 BN128 256thr - case 119: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 8192, 8, 0, UNRG); break; // BM 80, BN 128, f32 fold - case 120: R4D_TILED_LAUNCH(1, 8, 5, 2, 2, 0, 147, 8, 0, UNRG); break; // BM 80, BN 256, 256 thr - case 121: R4D_TILED_LAUNCH(1, 4, 5, 2, 2, 0, 147, 8, 0, UNRG); break; // BM 80, BN 128, 128 thr - case 122: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 0, 147, 4, 0, UNRG); break; // BM 80, BN 128, WPE 4 - case 123: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 16384, 8, 0, UNRG); break; // BM 80, A prefetch - case 124: R4D_TILED_LAUNCH(1, 8, 4, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 64, BN 128, 256 thr - case 125: R4D_TILED_LAUNCH(1, 8, 7, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 112, BN 128, 256 thr - case 126: R4D_TILED_LAUNCH(1, 8, 10, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 160, BN 128, 256 thr - // THE BM FAMILY. 512 threads need BM % 32 == 0, which is why the shipped ladder skips 80 and - // 112; at 256 threads `<1, 8, TM, 1>` gives BM = 16*TM for every TM, so the block can be the - // SMALLEST multiple of 16 that covers M instead of the nearest multiple of 32. - case 127: R4D_TILED_LAUNCH(1, 8, 1, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 16 - case 128: R4D_TILED_LAUNCH(1, 8, 2, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 32 - // OPT bit 65536 = non-temporal weight load, on the three tiles a decode step picks. - case 300: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 65536, 8, 0, UNRG); break; // 114 + wnt - case 301: R4D_TILED_LAUNCH(1, 8, 2, 1, 2, 0, 147 | 65536, 8, 0, UNRG); break; // 128 + wnt - case 302: R4D_TILED_LAUNCH(1, 8, 3, 1, 2, 0, 147 | 65536, 8, 0, UNRG); break; // 129 + wnt - case 303: R4D_TILED_LAUNCH(1, 8, 4, 1, 2, 0, 147 | 65536, 4, 0, UNRG); break; // 130 + wnt - case 304: R4D_TILED_LAUNCH(1, 8, 6, 1, 2, 0, 147 | 65536, 4, 0, UNRG); break; // 131 + wnt - case 305: R4D_TILED_LAUNCH(2, 8, 5, 1, 2, 0, 147 | 65536, 8, 0, UNRG); break; // 57 + wnt - case 306: R4D_TILED_LAUNCH(2, 8, 3, 1, 2, 0, 147 | 65536, 8, 0, UNRG); break; // BM96 512thr wnt - // BN=256 HALVES THE COLUMN BLOCKS AND SO THE ACTIVATION RE-READ, which is the term that - // scales with M (see OPT bit 65536 above). These are 62/63/117 with the hint. - case 307: R4D_TILED_LAUNCH(2, 8, 3, 2, 2, 0, 1171 | 65536, 8, 0, UNRG); break; // BM96 BN256 - case 308: R4D_TILED_LAUNCH(2, 8, 4, 2, 2, 0, 1171 | 65536, 8, 0, UNRG); break; // BM128 BN256 - case 309: R4D_TILED_LAUNCH(2, 4, 3, 2, 2, 0, 147 | 8192 | 16384 | 65536, 8, 0, UNRG); break; - case 310: R4D_TILED_LAUNCH(1, 8, 2, 2, 2, 0, 147 | 65536, 8, 0, UNRG); break; // BM32 BN256 - case 311: R4D_TILED_LAUNCH(1, 8, 2, 2, 2, 0, 147, 8, 0, UNRG); break; // BM32 BN256 no hint - // The shipped tiles stage the ACTIVATION a dword at a time -- BM=80 needs - // AW/4 = 320 dwords over 256 threads, which A128 refuses and A128R allows -- and stage the - // WEIGHT through LDS for a sharing that WM=1 does not have. 320-329 cross the three fixes. - case 320: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 8 | 32768 | 65536, 8, 0, UNRG); break; - case 321: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 32 | 65536, 8, 0, UNRG); break; - case 322: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 8 | 32 | 32768 | 65536, 8, 0, UNRG); break; - case 323: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 65536 | 131072, 8, 0, UNRG); break; - case 324: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 8 | 32768 | 65536 | 131072, 8, 0, UNRG); break; - case 325: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 8 | 32 | 32768 | 65536 | 131072, 8, 0, UNRG); break; - case 326: R4D_TILED_LAUNCH(1, 8, 2, 1, 2, 0, 147 | 65536 | 131072, 8, 0, UNRG); break; - case 327: R4D_TILED_LAUNCH(1, 8, 4, 1, 2, 0, 147 | 8 | 65536, 8, 0, UNRG); break; - case 328: R4D_TILED_LAUNCH(1, 8, 4, 1, 2, 0, 147 | 8 | 65536 | 131072, 8, 0, UNRG); break; - case 329: R4D_TILED_LAUNCH(1, 8, 3, 1, 2, 0, 147 | 65536 | 131072, 8, 0, UNRG); break; - // THE COST BREAKDOWN OF THE TILES A DECODE STEP ACTUALLY PICKS. The ablations above are - // taken at BM=96/M=72, which is a prefill shape; 330-341 repeat the same variants on <1,8,5> - // and <1,8,2> at the shipped OPT. The 3xx variants compute wrong answers by construction -- - // they are timings, not results. - case 330: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 10, 147 | 65536, 8, 0, UNRG); break; // no unpack - case 331: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 11, 147 | 65536, 8, 0, UNRG); break; // + no W LDS read - case 332: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 12, 147 | 65536, 8, 0, UNRG); break; // A read halved - case 333: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 15, 147 | 65536, 8, 0, UNRG); break; // A from global - case 334: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 13, 147 | 65536, 8, 0, UNRG); break; // epilogue /8 - case 335: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 14, 147 | 65536, 8, 0, UNRG); break; // no scale load - case 336: R4D_TILED_LAUNCH(1, 8, 2, 1, 2, 12, 147 | 65536, 8, 0, UNRG); break; // BM32 A read halved - case 337: R4D_TILED_LAUNCH(1, 8, 2, 1, 2, 15, 147 | 65536, 8, 0, UNRG); break; // BM32 A from global - case 338: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 1024 | 65536, 8, 0, UNRG); break; - case 339: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 16384 | 65536, 8, 0, UNRG); break; - case 340: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 2048 | 65536, 8, 0, UNRG); break; - case 341: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 8192 | 65536, 8, 0, UNRG); break; - case 342: R4D_TILED_LAUNCH(1, 8, 2, 1, 2, 0, 147 | 16384 | 65536 | 131072, 8, 0, UNRG); break; - case 343: R4D_TILED_LAUNCH(1, 8, 2, 1, 2, 0, 147 | 2048 | 65536 | 131072, 8, 0, UNRG); break; - case 344: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 16, 147 | 65536, 8, 0, UNRG); break; // no barrier - case 345: R4D_TILED_LAUNCH(1, 8, 2, 1, 2, 16, 147 | 65536, 8, 0, UNRG); break; // BM32 no barrier - case 346: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 262144 | 65536, 8, 0, UNRG); break; - case 347: R4D_TILED_LAUNCH(1, 8, 2, 1, 2, 0, 147 | 262144 | 65536 | 131072, 8, 0, UNRG); break; - case 348: R4D_TILED_LAUNCH(1, 8, 2, 1, 2, 0, 147 | 262144 | 65536, 8, 0, UNRG); break; - case 349: R4D_TILED_LAUNCH(1, 8, 2, 1, 2, 14, 147 | 65536, 8, 0, UNRG); break; // BM32 no scale - case 350: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 524288 | 65536, 8, 0, UNRG); break; - case 351: R4D_TILED_LAUNCH(1, 8, 2, 1, 2, 0, 147 | 524288 | 65536 | 131072, 8, 0, UNRG); break; - case 352: R4D_TILED_LAUNCH(1, 8, 2, 1, 2, 0, 147 | 524288 | 65536, 8, 0, UNRG); break; - case 129: R4D_TILED_LAUNCH(1, 8, 3, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 48 - case 130: R4D_TILED_LAUNCH(1, 8, 4, 1, 2, 0, 147, 4, 0, UNRG); break; // BM 64, WPE 4 - case 131: R4D_TILED_LAUNCH(1, 8, 6, 1, 2, 0, 147, 4, 0, UNRG); break; // BM 96, WPE 4 - case 132: R4D_TILED_LAUNCH(1, 8, 7, 1, 2, 0, 147, 4, 0, UNRG); break; // BM 112, WPE 4 - case 133: R4D_TILED_LAUNCH(1, 8, 9, 1, 2, 0, 147, 4, 0, UNRG); break; // BM 144, WPE 4 - case 134: R4D_TILED_LAUNCH(1, 8, 3, 1, 2, 0, 147, 4, 0, UNRG); break; // BM 48, WPE 4 - case 135: R4D_TILED_LAUNCH(1, 8, 2, 1, 2, 0, 147, 4, 0, UNRG); break; // BM 32, WPE 4 - // The same odd BM at 512 threads, which the ragged staging allows. BN is forced to 256 - // there: WM*WN = 16 and WM*TM = 5 leaves WM = 1, so WN = 16. - case 136: R4D_TILED_LAUNCH(1, 16, 5, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 80, BN 256, 512 thr - case 137: R4D_TILED_LAUNCH(1, 16, 5, 1, 2, 0, 147, 4, 0, UNRG); break; // BM 80, BN 256, WPE 4 - case 138: R4D_TILED_LAUNCH(1, 16, 3, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 48, BN 256, 512 thr - case 139: R4D_TILED_LAUNCH(1, 16, 7, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 112, BN 256, 512 thr - // TM = 5 changes the balance the scheduling variants above are aimed at: the loop is 6.30 - // instructions per WMMA instead of 9.21, and five matrix instructions per k step cover the - // LDS reads that three do not. - case 140: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 2048, 8, 0, UNRG); break; // BM 80 + sched - case 141: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 6144, 8, 0, UNRG); break; // BM 80 + sched/fine - case 142: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 1024, 8, 0, UNRG); break; // BM 80 + LDS-only barrier - // NARROW N: `out_proj`/`down_proj` are N = 5120, which is 40 tiles at BN = 128 -- 1.25 rounds - // per M block. BN = 64 doubles the tile count for the same work. - case 143: R4D_TILED_LAUNCH(1, 4, 5, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 80, BN 64, 128 thr - case 144: R4D_TILED_LAUNCH(1, 4, 3, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 48, BN 64, 128 thr - case 145: R4D_TILED_LAUNCH(2, 4, 5, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 160, BN 64, 256 thr - // BM = 144 covers M = 144 in one block, which BM 128 and BM 160 both fail to do well. - case 146: R4D_TILED_LAUNCH(1, 8, 9, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 144, BN 128, 256 thr - case 147: R4D_TILED_LAUNCH(1, 16, 9, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 144, BN 256, 512 thr - // OPT sweep on the BM=80 tile. 32 = do not stage rows past M (8 of 80 at M=72), 1024 = the - // LDS-only barrier, 8|16 = 128-bit staging, 64 = the asum prefetch (inert at ASYM=0). - case 150: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 32, 8, 0, UNRG); break; // BM 80 + MSKIP - case 151: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 32 | 1024, 8, 0, UNRG); break; - case 152: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 0, 155, 8, 0, UNRG); break; // BM 80 + A 128-bit - case 153: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 0, 147 & ~16, 8, 0, UNRG); break; // BM 80, dword W staging - case 154: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 256, 8, 0, UNRG); break; // BM 80 + unpack at staging - case 155: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 0, 147, 8, 0, 1); break; // BM 80, UNR 1 - case 156: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 0, 147, 8, 0, 2 * UNRG); break; // BM 80, UNR 4 - case 157: R4D_TILED_LAUNCH(1, 8, 5, 1, 1, 0, 147, 8, 0, UNRG); break; // BM 80, BIAS 1 - case 158: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 1024 | 32 | 8192, 8, 0, UNRG); break; - // DCE-PROOF ABLATIONS ON THE BM=80 TILE. Each computes a WRONG answer on purpose and keeps - // the data dependency that would otherwise let the compiler delete the path being priced. - case 160: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 5, 147, 8, 0, UNRG); break; // no unpack - case 161: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 6, 147, 8, 0, UNRG); break; // no unpack, no W LDS read - case 162: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 7, 147, 8, 0, UNRG); break; // half the A LDS read - case 163: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 3, 147, 8, 0, UNRG); break; // group epilogue at 1/8 - case 164: R4D_TILED_LAUNCH(1, 8, 5, 1, 2, 2, 147, 8, 0, UNRG); break; // no LDS barrier at all - // THE iu4 ROUTE ON THE BM=80 TILE. The DCE-proof ablation puts the unpack at 24.2% here -- - // three instructions per weight dword, sitting between the LDS read and the matrix - // instruction that consumes it. `v_wmma_i32_16x16x32_iu4` eats the packed nibbles, so the - // unpack goes away entirely; what it costs is a SECOND int32 accumulator per output tile, - // and at TM=5 that is 80 int VGPRs on top of 40 float. Takes the i4x2 activation. - // ---------------- PREFILL VARIANTS ---------------- - // At M >= 1024 this kernel is not a weight stream: gate_up_proj is 730 GFLOP against 44.6 MB - // of weight, so the answer is the matrix pipe. A `v_wmma_i32_16x16x16_iu8` occupies its SIMD - // for 8 cycles (NOT the 16 that f16/bf16 take), so the ceiling is 8/(8+r) - // with r the non-matrix instructions per matrix instruction. The shipped tile's inner loop - // is 361 instructions for 64 WMMA, r = 4.64, a 63% ceiling against 53% achieved. - // - // The three biggest items in that loop, per scale group: the fold (64 v_fma_mix_f32), the - // unpack (48 VALU) and the LDS waits (30 s_wait_dscnt). Bit 8192 is the fold: v_fma_mix_f32 - // is VOP3P and can never dual-issue, and `v_dual_fmac_f32` is the ONLY VOPD form gfx1201 - // offers that this loop can use (v_dual_and_b32 and v_dual_lshlrev_b32 do not exist here, - // so the unpack cannot be packed at all). - case 200: R4D_TILED_LAUNCH(2, 8, 4, 2, 2, 0, 147 | 8192, 8, 0, UNRG); break; - case 201: R4D_TILED_LAUNCH(2, 8, 4, 2, 2, 0, 147 | 8192 | 1024, 8, 0, UNRG); break; - case 202: R4D_TILED_LAUNCH(2, 8, 4, 2, 2, 0, 147 | 1024, 8, 0, 2 * UNRG); break; - case 203: R4D_TILED_LAUNCH(2, 8, 4, 2, 2, 0, 147 | 8192 | 1024, 8, 0, 2 * UNRG); break; - case 204: R4D_TILED_LAUNCH(2, 8, 4, 2, 2, 0, 147 | 8192 | 2048, 8, 0, UNRG); break; - case 205: R4D_TILED_LAUNCH(2, 8, 4, 2, 2, 0, 147 | 8192 | 2048 | 4096, 8, 0, UNRG); break; - // Taller tiles: the unpack is 3 VALU per (n tile, k step) shared over TM matrix instructions, - // so it is 3/TM per WMMA and TM is the only lever on it. Bit 32768 is what makes them worth - // trying -- without ragged 128-bit staging BM = 160 and 192 stage A one dword at a time. - case 206: R4D_TILED_LAUNCH(2, 8, 5, 2, 2, 0, 147 | 8192 | 32768, 8, 0, UNRG); break; - case 207: R4D_TILED_LAUNCH(2, 8, 6, 1, 2, 0, 147 | 8192 | 32768, 8, 0, UNRG); break; - case 208: R4D_TILED_LAUNCH(2, 8, 5, 1, 2, 0, 147 | 8192 | 32768, 8, 0, UNRG); break; - case 209: R4D_TILED_LAUNCH(2, 4, 6, 2, 2, 0, 147 | 8192, 8, 0, UNRG); break; - case 210: R4D_TILED_LAUNCH(4, 4, 4, 2, 2, 0, 147 | 8192, 8, 0, UNRG); break; - case 211: R4D_TILED_LAUNCH(2, 16, 4, 2, 2, 0, 147 | 8192, 8, 0, UNRG); break; - case 212: R4D_TILED_LAUNCH(2, 8, 3, 2, 2, 0, 147 | 8192, 8, 0, UNRG); break; - case 213: R4D_TILED_LAUNCH(1, 8, 4, 2, 2, 0, 147 | 8192, 8, 0, UNRG); break; - case 214: R4D_TILED_LAUNCH(2, 8, 8, 1, 2, 0, 147 | 8192, 8, 0, UNRG); break; - case 215: R4D_TILED_LAUNCH(2, 8, 4, 2, 0, 0, 147 | 8192, 8, 0, UNRG); break; - // THE SHAPE IS ALREADY RIGHT AT PREFILL: every taller, wider, narrower and more-unrolled tile - // loses, and the VOPD fold is a wash on K=5120 and a small win on K=3072. What is left is - // the inner loop, priced at M=4096 with the DCE-proof ablations: the VALU model says - // 8*64 + 146 = 658 cycles per 64 matrix instructions, a 78% ceiling, against 55% achieved. - // These variants say what the missing 23 points are made of. All of them compute wrong - // answers by construction. - case 220: R4D_TILED_LAUNCH(2, 8, 4, 2, 2, 10, 147, 8, 0, UNRG); break; // no unpack - case 221: R4D_TILED_LAUNCH(2, 8, 4, 2, 2, 11, 147, 8, 0, UNRG); break; // + no W LDS read - case 222: R4D_TILED_LAUNCH(2, 8, 4, 2, 2, 12, 147, 8, 0, UNRG); break; // half the A LDS read - case 223: R4D_TILED_LAUNCH(2, 8, 4, 2, 2, 13, 147, 8, 0, UNRG); break; // fold at 1/8 - case 224: R4D_TILED_LAUNCH(2, 8, 4, 2, 2, 16, 147, 8, 0, UNRG); break; // no LDS barrier - case 225: R4D_TILED_LAUNCH(2, 8, 4, 2, 2, 14, 147, 8, 0, UNRG); break; // no scale load - case 226: R4D_TILED_LAUNCH(2, 8, 4, 2, 2, 15, 147, 8, 0, UNRG); break; // A from global - case 227: R4D_TILED_LAUNCH(2, 8, 4, 2, 2, 0, 147 | 16384, 8, 0, UNRG); break; // A prefetch - case 228: R4D_TILED_LAUNCH(2, 8, 4, 2, 2, 0, 147 | 8192 | 16384, 8, 0, UNRG); break; - case 229: R4D_TILED_LAUNCH(2, 8, 4, 2, 2, 17, 147, 8, 0, UNRG); break; // iu4 route, staged - case 165: R4D_TILED_LAUNCH(1, 8, 5, 1, 0, 0, 659, 8, 0, UNRG); break; // BM 80, iu4 - case 166: R4D_TILED_LAUNCH(1, 8, 5, 1, 0, 0, 147, 8, 0, UNRG); break; // the same tile on iu8 - case 167: R4D_TILED_LAUNCH(1, 8, 4, 1, 0, 0, 659, 8, 0, UNRG); break; // BM 64, iu4 - case 168: R4D_TILED_LAUNCH(1, 8, 3, 1, 0, 0, 659, 8, 0, UNRG); break; // BM 48, iu4 - // THE DEFAULT: 2x8 waves of 4x2 tiles, the magic-bias accumulator, the raw scale prefetch, - // 32-bit global indexing and 128-bit staging FOR THE WEIGHT ONLY, at eight waves per EU. - // At M = 4096 it lands within about ten points of the block-fp8 bar on gate_proj, down_proj - // and in_proj_qkv, where the 4x4-wave, 2x4-tile, plain-cvt variant (variant 1) is 25-30% over - // it. - default: - if (ufull) R4D_TILED_LAUNCH(2, 8, 4, 2, 2, 0, 147, 8, 0, UNRG); - else R4D_TILED_LAUNCH(2, 8, 4, 2, 2, 0, 147, 8, 0, 1); - break; - } + R4D_TILED_LAUNCH(2, 8, 4, 2, 1, 1); + return; + } + // The arms tile_bmbn in r4d_rows.cpp lists, each with the (BM, BN) it records there. 512-thread + // tiles are <2, 8, TM, TN> (or <1, 16, ...> for an odd BM at BN 256); at 256 threads <1, 8, TM, 1> + // gives BM = 16*TM for any TM, so the block can be the smallest multiple of 16 covering M. + // Staging constrains shapes (W needs WM | 4*TN, A needs WN | 8*TM). + switch (variant) { + case 6: R4D_TILED_LAUNCH(2, 8, 2, 2, 0, UNRG); break; // BM 64, BN 256 + case 10: R4D_TILED_LAUNCH(2, 8, 3, 2, 0, UNRG); break; // BM 96, BN 256 + case 12: R4D_TILED_LAUNCH(2, 8, 3, 1, 0, UNRG); break; // BM 96, BN 128 + case 57: R4D_TILED_LAUNCH(2, 8, 5, 1, 0, UNRG); break; // BM 160, BN 128 + case 59: R4D_TILED_LAUNCH(2, 8, 4, 1, 0, UNRG); break; // BM 128, BN 128 + case 114: R4D_TILED_LAUNCH(1, 8, 5, 1, 0, UNRG); break; // BM 80, BN 128 + case 124: R4D_TILED_LAUNCH(1, 8, 4, 1, 0, UNRG); break; // BM 64, BN 128 + case 125: R4D_TILED_LAUNCH(1, 8, 7, 1, 0, UNRG); break; // BM 112, BN 128 + case 126: R4D_TILED_LAUNCH(1, 8, 10, 1, 0, UNRG); break; // BM 160, BN 128 + case 128: R4D_TILED_LAUNCH(1, 8, 2, 1, 0, UNRG); break; // BM 32, BN 128 + case 129: R4D_TILED_LAUNCH(1, 8, 3, 1, 0, UNRG); break; // BM 48, BN 128 + case 138: R4D_TILED_LAUNCH(1, 16, 3, 1, 0, UNRG); break; // BM 48, BN 256 + case 139: R4D_TILED_LAUNCH(1, 16, 7, 1, 0, UNRG); break; // BM 112, BN 256 + case 146: R4D_TILED_LAUNCH(1, 8, 9, 1, 0, UNRG); break; // BM 144, BN 128 + // BM 128 x BN 256, 2x8 waves of 4x2 tiles. At M = 4096 it is within ~10% of the block-fp8 + // GEMM on gate_proj, down_proj and in_proj_qkv. + default: R4D_TILED_LAUNCH(2, 8, 4, 2, 0, UNRG); break; } #undef R4D_TILED_LAUNCH } @@ -1454,9 +350,8 @@ void r4d_gemm_w4a8_tiled(long a, long ascale, long wq, long ws, long c, int M, i r4d_gemm_w4a8_tiled_impl(a, ascale, wq, ws, 0, c, M, K, N, stream, variant, false); } -// Asymmetric grid: the nibble is read UNSIGNED and the stored -// per-group zero is corrected out with a per-row per-group sum of the activation, which -// r4d_quant_act_i8_asum emits as [K/group][Mpad] with Mpad = ceil(M/16)*16. +// Asymmetric grid: the nibble is read unsigned and the per-group zero is corrected with the per-row +// per-group activation sums from r4d_quant_act_i8_asum ([K/group][Mpad], Mpad = ceil(M/16)*16). void r4d_gemm_w4a8_asym_tiled(long a, long ascale, long wq, long ws, long asum, long c, int M, int K, int N, long stream, int variant) { if (!asum) throw std::runtime_error("r4d gemm_w4a8_asym_tiled: asum is required"); @@ -1465,14 +360,10 @@ void r4d_gemm_w4a8_asym_tiled(long a, long ascale, long wq, long ws, long asum, // ============================================================== the plugin ABI entry points // -// The operand reader and the split law are in r4d_gemm_args.h. See libr4d/r4d_args.h for why there -// is no adapter directory between the core and these launches. +// The operand reader and the split law are in r4d_gemm_args.h; see libr4d/r4d_args.h. /* ------------------------------------------------------------------ the large-M kernels * - * These take a single opaque tile VARIANT into libr4d's own tile switch rather than five knobs. - * The block width BN is a property of the variant, and N must be a multiple of it -- which the ROW - * cannot express, because BN varies by variant. So the row constrains N % 256 (the default - * variant's BN) and this is where a variant whose BN does not divide N is refused. */ + * These take one opaque tile variant; see tile_ok in r4d_gemm_args.h for the N % BN check. */ extern "C" int r4d_rad_gemm_w4a8_tiled(const RadArgs* a, RadStream s) { GemmOps g; @@ -1502,6 +393,3 @@ extern "C" int r4d_rad_gemm_w4a8_tiled(const RadArgs* a, RadStream s) { t->variant)); return RAD_OK; } - -/* libr4d defines r4d_gemm_w8a8_asym_tiled but does NOT declare it in r4d.h, so this plugin cannot - * reach it and `w8a8_asym` is deliberately absent from the row's dtype set. */ diff --git a/libr4d/r4d_gemm_w5a16_nt_m64.hip b/libr4d/r4d_gemm_w5a16_nt_m64.hip index 46b72580..a7819625 100644 --- a/libr4d/r4d_gemm_w5a16_nt_m64.hip +++ b/libr4d/r4d_gemm_w5a16_nt_m64.hip @@ -1,32 +1,28 @@ // r4d_gemm_w5a16_nt_m64.hip - r4d_gemm_w5a16_nt_m64: 5-bit-weight skinny GEMM for M up to 64, // gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T, f16 A, bf16 C, fp32 accumulate. // -// r4d_gemm_w4a16_nt_m64 with a fifth bit per weight, for ParoQuant's int5 (asymmetric, an f16 scale -// and a 5-bit integer zero per 128 of K, the rotation done on the activation in front of it). The -// reading of that kernel's header holds word for word -- weight-streaming, memory-bound, f16 -// because 1024 + n is exact -- and this file only says what the fifth bit changes. +// r4d_gemm_w4a16_nt_m64 with a fifth bit per weight, for ParoQuant's int5 (asymmetric: an f16 scale +// and a 5-bit integer zero per 128 of K, with the rotation applied to the activation beforehand). +// That kernel's header applies; this one covers only what the fifth bit changes. // -// THE WEIGHT BLOB IS TWO PLANES. The low four bits of every code are w4's fragment order exactly -// (offset binary here: the nibble is q & 15, no sign flip). The fifth bits follow as a second -// plane of 32-bit words, ONE A (n-tile, 64-wide k block, lane): +// The weight blob is two planes. The low four bits of each code are in w4's fragment order (offset +// binary: the nibble is q & 15, no sign flip). The fifth bits follow as 32-bit words, one per +// (n-tile, 64-wide k block, lane): // // hi[(t * (K/64) + kb) * 32 + lane] byte s = k step s of the block, bit e = element e // -// element e of a lane's fragment being the same one nibble 2e / 2(e-4)+1 of dword s holds. So a -// lane's 16 bytes of nibbles and its 4 bytes of fifth bits cover the same 32 weights, and the -// second load is one dword a block. +// where element e is the one nibble 2e / 2(e-4)+1 of dword s holds. A lane's 16 bytes of nibbles and +// 4 bytes of fifth bits cover the same 32 weights; the second load is one dword per block. // -// THE UNPACK ADDS TWO MULTIPLIES TO w4's. The even elements' fifth bits are the byte's low nibble, -// the odd elements' its high one; a 4-bit mask n becomes one bit a byte by n * 0x00204081 (bit j -// lands at 8j and nothing else lands on a multiple of eight below bit 32), masked with 0x01010101 -// and shifted to the 16s place of the nibble's byte. The 5-bit code is then 0..31, 1024 + q is -// exact in f16, and the zero point -- an integer 0..31 in the scale dword's high half as -// -(1024 + zero) -- subtracts exactly. +// The unpack adds two multiplies to w4's. The even elements' fifth bits are the byte's low nibble, +// the odd elements' its high one. n * 0x00204081 moves bit j of a 4-bit mask to bit 8j (no other +// term lands on a multiple of eight below bit 32); masking with 0x01010101 and shifting by 4 puts +// it at the 16s place. The code is then 0..31, 1024 + q is exact in f16, and the integer zero +// (0..31, stored as -(1024 + zero)) subtracts exactly. // -// The dispatcher takes M past 64 as chunks of 64 rows (the weight is re-read per chunk, which at a -// 2048-row prefill chunk is near the compute bound of the f16 matrix instruction anyway), and -// partitioned weights (ParoQuant's gate|up: `pb1`/`pb2`, see r4d_gemm_args.h) as one launch per -// part over windows of the planes. +// The dispatcher runs M past 64 as chunks of 64 rows, re-reading the weight per chunk (near the f16 +// compute bound at a 2048-row prefill chunk anyway), and partitioned weights (ParoQuant's gate|up: +// `pb1`/`pb2`, see r4d_gemm_args.h) as one launch per part. #include "r4d.h" #include "r4d_gemm_args.h" #include "r4d_gdn_wmma.h" @@ -37,34 +33,16 @@ #include #define R4D_GEMM_W4_MAX_M 64 -#ifndef R4D_GEMM_W4_GROUP -#define R4D_GEMM_W4_GROUP 128 // K per (scale, zero) pair -#endif #define R4D_GEMM_W4_KPB 64 // K per packed block: 4 k steps, 16 bytes per lane #define WAVE32 32 typedef _Float16 v8h __attribute__((ext_vector_type(8))); typedef unsigned uint4v __attribute__((ext_vector_type(4))); -// NT reads the weight non-temporally. The weight is streamed once per step and never reused, while -// the activation is re-read once per column tile and wants to stay resident, so telling the cache -// not to keep the weight decides which of the two occupies the last level. It is a gain at M=8 and -// M=16 and a LOSS from M=24 up on the shapes with the longest K, so it is per-call, like every -// other geometry parameter, and the table in radiance_w4.py carries the value per M band. -// -// One copy of any of these weights fits this part's 64 MiB last level, so a bench that streams a -// SINGLE buffer in a loop measures a cache-resident machine and cannot see this effect at all; a -// pooled working set is what makes the difference visible. +// NT and NPW: see r4d_gemm_w4a16_nt_m64.hip. Only NPW 1 and 4 are instantiated. -// NPW (column tiles per WAVE) is a template parameter because it sizes the accumulator array, and a -// launch argument because the right value is a property of M: at M=8 the kernel is at the DRAM -// roofline and NPW>1 only costs blocks, while at M=64 the activation re-read is four times the -// weight and NPW=4 is what claws it back. Instantiated only for the two values that win in -// practice; anything else is rejected rather than silently rounded. - -// Address-space-qualified so the loads stay global_load rather than flat_load: on gfx12 a flat -// load increments dscnt as well as loadcnt, so a later LDS wait would also wait on HBM. See the -// same declaration in r4d_gemm_bf16_nt_m64.hip for why the element type is a scalar there. +// Address-space-qualified so loads stay global_load, not flat_load (on gfx12 a flat load also +// increments dscnt). See r4d_gemm_bf16_nt_m64.hip for why the element type is a scalar. typedef __attribute__((address_space(1))) const uint4v* r4d_gw4; typedef __attribute__((address_space(1))) const unsigned long long* r4d_gu2; typedef __attribute__((address_space(1))) const unsigned* r4d_gu1; @@ -76,18 +54,12 @@ __device__ __forceinline__ v8h fragA(r4d_gu2 p, int u) { return x.f; } -// DO NOT FOLD THE GROUP SCALE INTO THE B FRAGMENT. One v_pk_mul_f16 per pair on the finished -// integer q is exact in f16, removes the second accumulator array entirely and takes the M=64 shape -// from 192 VGPRs to 135 -- and it is SLOWER on most of the drafter's shapes. The multiply lands -// inside the per-fragment dependent chain between the unpack and the WMMA, where the per-group -// epilogue it replaces sits outside it; this kernel is stall-bound, not register-bound. +// Do not fold the group scale into the B fragment; see r4d_gemm_w4a16_nt_m64.hip. // One dword of eight nibbles plus the byte of their fifth bits -> one 16x16x16 f16 B fragment, -// minus the zero point. Nibble 2e (e < 4) / 2(e-4)+1 is fragment element e, so bits 0..3 of `hb` -// are the fifth bits of the even nibbles' elements and bits 4..7 the odd nibbles'. Each v_perm_b32 -// pairs two code bytes with the constant high byte 0x64, the f16 exponent field for 1024, so a half -// is 1024 + code; nz carries -(1024 + zero) in BOTH halves, so one v_pk_add_f16 corrects a pair. -// The codes are offset binary (0..31, or 0..15 without the fifth bit): no sign flip. +// minus the zero point. Bits 0..3 of `hb` are the even nibbles' fifth bits, bits 4..7 the odd +// nibbles'. Each v_perm_b32 pairs two code bytes with the high byte 0x64 (1024 + code); nz holds +// -(1024 + zero) in both halves. Codes are offset binary (0..31, or 0..15 without the fifth bit). __device__ __forceinline__ unsigned spread16(unsigned n) { // 4 bits -> bit 4 of each byte return ((n * 0x00204081u) & 0x01010101u) << 4; } @@ -109,9 +81,8 @@ __device__ __forceinline__ v8f mmah(v8h a, v8h b, v8f c) { return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c); } -// MT = row tiles per BLOCK, as in the bf16 kernel: more of them amortise the weight fragment and -// its unpack over more WMMA, fewer put more blocks on the machine. -// HI false is the 4-bit asymmetric grid (z-lab's plain int4): the same kernel with no fifth-bit plane. +// MT = row tiles per block, as in the bf16 kernel. HI false is the 4-bit asymmetric grid (z-lab's +// plain int4), with no fifth-bit plane. template __global__ __launch_bounds__(1024) void r4d_gemm_w5a16_nt_m64_kernel( const unsigned short* __restrict__ A, const unsigned* __restrict__ Wq, @@ -134,8 +105,7 @@ __global__ __launch_bounds__(1024) void r4d_gemm_w5a16_nt_m64_kernel( for (int i = 0; i < MT; i++) acc[j][i] = (v8f)(0.f); if (n0 < N) { - // Activation: rows clamped, never masked -- a tile past M re-reads the last valid row and - // computes a result nobody stores. + // Activation rows are clamped, not masked; results past M are never stored. unsigned aoff[MT]; #pragma unroll for (int i = 0; i < MT; i++) @@ -144,8 +114,8 @@ __global__ __launch_bounds__(1024) void r4d_gemm_w5a16_nt_m64_kernel( #pragma unroll for (int i = 0; i < MT; i++) pa[i] = (r4d_gu2)(const unsigned long long*)(A + aoff[i]); - // Weight: one uint4 per lane per four k steps, tiles already permuted, so the whole k loop is - // global_load_b128 with a constant stride and no address arithmetic per step. + // Weight: one uint4 per lane per four k steps, already permuted, so the k loop is + // global_load_b128 at a constant stride. const int kpb = K / R4D_GEMM_W4_KPB; // packed blocks in a full row of tiles const int nsz = K / R4D_GEMM_W4_GROUP; // (scale, zero) dwords per row of tiles r4d_gw4 pw[NPW]; @@ -154,15 +124,14 @@ __global__ __launch_bounds__(1024) void r4d_gemm_w5a16_nt_m64_kernel( const int ntlast = N / 16 - 1; #pragma unroll for (int j = 0; j < NPW; j++) { - // Clamped, like the row tiles: a wave whose last column tiles run past N re-reads the last - // real tile and computes a result the store discards, rather than reading memory it does not - // own or diverging the whole k loop on a mask. + // Column tiles past N are clamped to the last real tile; the store discards them. const int t = (nt0 + j) < ntlast ? (nt0 + j) : ntlast; pw[j] = (r4d_gw4)(const uint4v*)(Wq) + (size_t)(t * kpb + kbase / R4D_GEMM_W4_KPB) * WAVE32 + lane; - // Quantizer parameters: 16 distinct dwords per group, read by the 16 lanes that own the rows. + // Fifth-bit plane: one dword per lane per packed block (unused when !HI). ph[j] = (r4d_gu1)(const unsigned*)(HI ? Whi : Wq) + (size_t)(t * kpb + kbase / R4D_GEMM_W4_KPB) * WAVE32 + lane; + // Quantiser parameters: 16 dwords per group, read by the 16 lanes that own the rows. ps[j] = (r4d_gu1)(const unsigned*)(Wsz) + (size_t)(t * nsz + kbase / R4D_GEMM_W4_GROUP) * 16 + (lane & 15); } @@ -179,8 +148,7 @@ __global__ __launch_bounds__(1024) void r4d_gemm_w5a16_nt_m64_kernel( nz[j] = __half2half2(__ushort_as_half((unsigned short)(sz >> 16))); } - // The first WMMA of a group takes an inline zero for C, so the group accumulator costs no - // instruction to clear. + // The first WMMA of a group takes an inline zero for C, so no clear is needed. v8f g_acc[NPW][MT]; #pragma unroll for (int b = 0; b < bpg; b++) { @@ -219,9 +187,8 @@ __global__ __launch_bounds__(1024) void r4d_gemm_w5a16_nt_m64_kernel( } } - // Split-K reduction and store: identical to r4d_gemm_bf16_nt_m64, one row tile at a time so the - // LDS is WV*SK KiB whatever MT is, and in a fixed order over splits so the result does not depend - // on how the waves were scheduled. + // Split-K reduction and store as in r4d_gemm_bf16_nt_m64: one row tile at a time, fixed split + // order. const int ncols = WV * NPW; const int nthreads = WV * SK * WAVE32; #pragma unroll @@ -295,8 +262,7 @@ int r4d_gemm_w5a16_nt_m64_group(void) { return R4D_GEMM_W4_GROUP; } // ============================================================== the plugin ABI entry points // -// The operand reader and the split law are in r4d_gemm_args.h. See libr4d/r4d_args.h for why there -// is no adapter directory between the core and these launches. +// The operand reader and the split law are in r4d_gemm_args.h; see libr4d/r4d_args.h. /* ------------------------------------------------------------------ f16-activation grids */ static int w5_dispatch(const RadArgs* a, RadStream s, bool hi5) { @@ -304,21 +270,21 @@ static int w5_dispatch(const RadArgs* a, RadStream s, bool hi5) { int rc = gemm_ops(a, &g, 1, /*parts=*/1); if (rc != RAD_OK) return rc; if (g.N % 16) return R4D_NO(RAD_E_SHAPE); + /* Any other activation dtype would read plausible but wrong numbers. */ + if (g.a->dtype != RAD_F16) return R4D_NO(RAD_E_DTYPE); MxParts mp; rc = mx_parts(a, &g, &mp); if (rc != RAD_OK) return rc; if (g.K % R4D_GEMM_W4_GROUP) return R4D_NO(RAD_E_SHAPE); const int group = r4d_gemm_w5a16_nt_m64_group(); - // The row's M is the step's, not the kernel's: rows past 64 are chunks of 64, each its own pass - // over the weight, so a prefill chunk costs the weight's bytes once a 64 rows. + // Rows past 64 run as chunks of 64, each a pass over the weight. const long long mc = std::min(g.M, r4d_gemm_w5a16_nt_m64_max_m()); Cfg c; rc = cfg_for(a, g.K, mc, group, BR_FLAT, &c); if (rc != RAD_OK) return rc; - /* cfg_for pins MB = 1 across the decode band (the grid, not the weight, is the cost for the bf16 and - * mxfp4 skinny kernels). Here the dequantise is: one block per row tile unpacks each weight fragment - * once PER TILE, so three streams (M = 24, two tiles) pay it twice. Cover every row tile in one block - * unless the tuner pinned MB; same split, so the output bits are unchanged. */ + /* cfg_for pins MB = 1 in the decode band, but here the dequantise is the cost: with one block per + * row tile, each weight fragment is unpacked once per tile. Cover every row tile in one block + * unless the tuner pinned MB; the split is unchanged, so the output bits are too. */ R4dGemmCfg tuned; r4d_cfg_gemm(a, &tuned); if (tuned.mb <= 0) c.mb = std::min(4, (mc + 15) / 16); diff --git a/libr4d/r4d_gemm_w8a16_nt_m64.hip b/libr4d/r4d_gemm_w8a16_nt_m64.hip index dcdfe758..042c2a26 100644 --- a/libr4d/r4d_gemm_w8a16_nt_m64.hip +++ b/libr4d/r4d_gemm_w8a16_nt_m64.hip @@ -1,47 +1,30 @@ // r4d_gemm_w8a16_nt_m64.hip - r4d_gemm_w8a16_nt_m64: 8-bit-weight skinny GEMM for M up to 64, // gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T, f16 A, bf16 C, fp32 accumulate. // -// WHY THIS EXISTS WHEN THE 4-BIT ONE ALREADY DOES. One site in the decode step is quantised to -// eight bits and not four -- lm_head -- because it is the only layer whose error lands on the -// SAMPLED TOKEN rather than on a residual a later layer can absorb. +// Used for lm_head, quantised to eight bits rather than four because its error lands on the +// sampled token rather than on a residual later layers can absorb. // -// A general int8 library GEMM is the wrong shape for it. Those paths refuse M <= 16, so eight -// speculative rows are padded to SEVENTEEN, which is two 16-row macro tiles, and a weight-streaming -// GEMM with two row tiles READS THE WEIGHT TWICE -- well under the ~640 GB/s this part delivers, -// and the cost only stops rising once M is large enough that the last level absorbs the re-reads. -// A skinny kernel holds every row of M in registers, so the weight is read once whatever M is and -// the time does not move with the batch. +// A skinny kernel holds every row of M in registers, so the weight is read once regardless of M. +// General int8 GEMMs pad M <= 16 to two 16-row macro tiles and read the weight twice. The scale is +// applied to the in-register accumulator and stored as bf16, with no separate epilogue launch. // -// It also folds the epilogue. A library path costs four launches -- quantise the activation, zero -// a padded buffer, GEMM, then scale an M x N int32 buffer -- and the last of those moves tens of -// megabytes at eight requests. Here the scale is applied to the accumulator that is already in -// registers and the store is bf16. +// Structure matches r4d_gemm_w4a16_nt_m64: fragment order, 512 B packed block (32 lanes x 16 B), +// (scale, zero) dword per (row, group), split-K reduction and clamped tiles. Only the bits per +// element differ, so a packed block covers 32 K instead of 64. // -// STRUCTURE IS r4d_gemm_w4a16_nt_m64's, AND DELIBERATELY SO: same fragment order, same packed-block -// size (32 lanes x 16 bytes = 512 B), same (scale, zero) dword per (row, group), same split-K -// reduction, same clamped row and column tiles. Only the weight's bits per element change, and -// with them how much K one packed block covers: 64 at four bits, 32 at eight. +// Dequant: `0x6400 | b` is exactly the f16 for 1024 + b for b in 0..255, so four v_perm_b32 turn +// two dwords into a 16x16x16 fragment, and one v_pk_add_f16 per pair adds -(1024 + zero). The +// subtraction is exact (integers below 2048), so the group scale is applied to the f32 accumulator. // -// THE DEQUANT IS THE SAME TRICK AT A WIDER RADIX. `0x6400 | b` is the f16 for 1024 + b, exactly, -// for every b in 0..255 -- f16 carries eleven significant bits and 1279 needs eleven -- so four -// v_perm_b32 turn two dwords of four bytes into a whole 16x16x16 fragment, and one v_pk_add_f16 -// per pair subtracts the constant -(1024 + zero). That subtraction is exact for the same reason -// (both operands are integers below 2048 and the difference is small), which is what lets the group -// scale wait for the f32 accumulator, where the cancellation has already happened. +// A is f16, not bf16, because bf16's eight significant bits cannot hold 1024 + b. The alternative +// (raw codes plus a per-group activation sum, as in r4d_gemm_w4a8_asym_nt_m64) gains nothing here: +// the adds hide under the weight stream. The caller's bf16 -> f16 cast is exact for a post-norm +// hidden state (O(10)). // -// WHY f16 AND NOT bf16 A. Reaching 1024 + b is the whole reason the unpack is four instructions, -// and bf16 has eight significant bits, so 1024 + b is not representable there at all. The -// alternative -- keep the raw offset-binary code in the fragment and correct with a per-group -// activation sum, which r4d_gemm_w4a8_asym_nt_m64 does -- needs that sum computed somewhere, and at -// this M the four v_pk_add_f16 hide entirely under a weight stream that is 99% of the cost. The -// caller casts bf16 to f16, which is exact: bf16's mantissa is a strict prefix of f16's and a -// post-norm hidden state is O(10). -// -// QUANTIZER. Asymmetric, per output channel, per group of R4D_GEMM_W8_GROUP contiguous K: -// w ~= scale * (q - zero) with q in 0..255 and an INTEGER zero, so the subtract stays on the -// integer grid. Both parameters live in one dword per (row, group): the f16 scale in the low half -// and the f16 of -(1024 + zero) in the high half. The group costs 3.1% more bytes than a -// per-channel scale would and halves the KL divergence against the unquantised layer. +// Quantiser: asymmetric, per output channel, per group of R4D_GEMM_W8_GROUP contiguous K: +// w ~= scale * (q - zero), q in 0..255, integer zero. One dword per (row, group): the f16 scale low, +// the f16 of -(1024 + zero) high. The group costs 3.1% more bytes than a per-channel scale and +// halves the KL divergence against the unquantised layer. #include "r4d.h" #include "r4d_gemm_args.h" #include "r4d_gdn_wmma.h" @@ -51,9 +34,6 @@ #include #define R4D_GEMM_W8_MAX_M 64 -#ifndef R4D_GEMM_W8_GROUP -#define R4D_GEMM_W8_GROUP 128 // K per (scale, zero) pair -#endif #define R4D_GEMM_W8_KPB 32 // K per packed block: 2 k steps, 16 bytes per lane #define WAVE32 32 @@ -71,10 +51,9 @@ __device__ __forceinline__ v8h fragA8(r4d_gu2 p, int u) { return x.f; } -// Two dwords of four bytes -> one 16x16x16 f16 B fragment, minus the zero point. The packer put -// fragment elements 0..3 in the first dword and 4..7 in the second, in order, so each v_perm_b32 -// pairs two consecutive bytes with the constant high byte 0x64 -- the f16 exponent field for 1024. -// nz carries -(1024 + zero) in BOTH halves so one v_pk_add_f16 corrects a pair. +// Two dwords of four bytes -> one 16x16x16 f16 B fragment, minus the zero point. The packer puts +// fragment elements 0..3 in the first dword and 4..7 in the second, so each v_perm_b32 pairs two +// bytes with the high byte 0x64 (the f16 exponent for 1024). nz holds -(1024 + zero) in both halves. __device__ __forceinline__ v8h dequant8(unsigned w0, unsigned w1, __half2 nz) { const unsigned K64 = 0x64646464u; union { unsigned u[4]; __half2 h2[4]; v8h f; } x; @@ -209,12 +188,9 @@ __global__ __launch_bounds__(1024) void r4d_gemm_w8a16_nt_m64_kernel( void r4d_gemm_w8a16_nt_m64(long a, long wq, long wsz, long c, int M, int K, int N, int WV, int SK, int MB, int NPW, int NT, long stream) { - // NO UPPER BOUND ON M. The row tiles a BLOCK covers are MT, and grid.y covers the rest, with - // rows past M clamped on load and masked on the store -- so any M is CORRECT. What ends at 64 - // is the band this kernel is the right shape for: past it every extra row-tile group re-reads - // the whole weight, and the caller should be on a staged kernel. max_m() reports that band; - // this guard only rejects nonsense, because the alternative is a caller silently getting a - // wrong answer from a fallback that was handed a PACKED weight. + // Any M is correct (grid.y covers row tiles past MT; rows past M are clamped and masked). 64 is + // the band this shape suits, since each extra row-tile group re-reads the weight; max_m() + // reports it. if (M < 1) throw std::runtime_error("r4d gemm_w8a16_nt_m64: M must be >= 1"); if (N % 16) throw std::runtime_error("r4d gemm_w8a16_nt_m64: N must be a multiple of 16"); if (K % (SK * R4D_GEMM_W8_GROUP)) @@ -257,14 +233,13 @@ int r4d_gemm_w8a16_nt_m64_group(void) { return R4D_GEMM_W8_GROUP; } // ============================================================== the plugin ABI entry points // -// The operand reader and the split law are in r4d_gemm_args.h. See libr4d/r4d_args.h for why there -// is no adapter directory between the core and these launches. +// The operand reader and the split law are in r4d_gemm_args.h; see libr4d/r4d_args.h. extern "C" int r4d_rad_gemm_w8a16_m64(const RadArgs* a, RadStream s) { GemmOps g; int rc = gemm_ops(a, &g, 1); if (rc != RAD_OK) return rc; if (g.N % 16) return R4D_NO(RAD_E_SHAPE); - /* An f16 kernel handed any other activation reads plausible numbers that are not the input. */ + /* Any other activation dtype would read plausible but wrong numbers. */ if (g.a->dtype != RAD_F16) return R4D_NO(RAD_E_DTYPE); if (g.M > r4d_gemm_w8a16_nt_m64_max_m()) return R4D_NO(RAD_E_SHAPE); const int group = r4d_gemm_w8a16_nt_m64_group(); diff --git a/libr4d/r4d_gemm_w8a8_nt_m64.hip b/libr4d/r4d_gemm_w8a8_nt_m64.hip index 01b79a05..f45814e5 100644 --- a/libr4d/r4d_gemm_w8a8_nt_m64.hip +++ b/libr4d/r4d_gemm_w8a8_nt_m64.hip @@ -2,45 +2,28 @@ // M up to a prefill chunk, gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T, A quantised per row and // W per (row, 128-wide group). // -// WHY THIS EXISTS. The INT4 target promotes 80 of its 256 linears -- every down_proj and the -// sixteen attention o_proj -- to eight bits, because those two groups are where the 4-bit grid -// costs the most KL. Serving those through a library int8 matmul means a composite -- rotate the -// activation with a bf16 matmul, quantise it, call the library, then scale an int32 [M,N] back to -// bf16 -- which is eight launches and three materialised intermediates per site, 80 sites a step. -// It also THROWS AWAY the fused rms+Hadamard+quantise producer the 4-bit sites read: the int8 the -// norm has already written is ignored and the bf16 is re-rotated and re-quantised. +// Serves the linears an INT4 model promotes to eight bits (every down_proj and the attention +// o_proj, where the 4-bit grid costs the most KL) in one launch that reads exactly what the 4-bit +// GEMM reads: the same permuted int8 activation from the fused rms+Hadamard+quantise producer, the +// same per-row scale, and a weight in the same fragment order at twice the radix. // -// This is one launch that reads exactly what the 4-bit GEMM reads: the SAME permuted int8 -// activation buffer, the SAME per-row scale, and a weight in the same fragment order at twice the -// radix. Nothing about the producer changes; only the GEMM does. +// It is r4d_gemm_w4a8_nt_m64 without the unpack: the eight weight bytes are the B fragment. The A +// fragment read, split-K reduction, per-group scale fold and per-row activation scale at the store +// are the same. // -// IT IS r4d_gemm_w4a8_nt_m64 WITH THE UNPACK DELETED. That kernel spends two v_and_b32 and one -// v_lshlrev_b32 turning a dword of nibbles into eight int8 lanes; here the eight bytes ARE the -// fragment, so the B operand is two dwords straight out of the load and the dequant is nothing at -// all. Everything else -- the A fragment read, the split-K reduction, the per-group scale folded -// with one v_cvt_f32_i32 and one fma, the per-row activation scale applied once at the store -- is -// the same code. +// gemm_w8a16_nt_m64 uses the f16 WMMA (207 TF/s vs 407 for iu8), which is fine for lm_head at M=8 +// (DRAM bound) but caps these sites at M=72. // -// WHY NOT gemm_w8a16_nt_m64, WHICH ALREADY EXISTS. It runs v_wmma_f32_16x16x16_f16 at 207 TF/s -// where v_wmma_i32_16x16x16_iu8 runs at 407. For lm_head at M=8 that is invisible -- the kernel is -// at the DRAM roofline and the matrix pipe is free -- but the promoted sites run at M=8 AND at -// M=72, and the f16 form is where the M=64 cliff in that kernel comes from. An 8-bit weight has -// no reason to widen to 16 bits to be multiplied by an 8-bit activation. -// -// THE WEIGHT LAYOUT. Per n-tile t (16 output rows) and k-block kb (KPB=32 columns), 32 lanes hold -// 16 bytes each: 512 bytes covering 16 rows x 32 k, which is TWO WMMA k steps. Byte j of lane l is +// Weight layout: per n-tile t (16 output rows) and k-block kb (KPB=32 columns), 32 lanes hold +// 16 bytes each, 512 bytes covering 16 rows x 32 k (two WMMA k steps). Byte j of lane l is // // W[t*16 + (l & 15)][kb*32 + 16*(j >> 3) + 8*((j & 7) >> 2) + 4*(l >> 4) + (j & 3)] // -// -- the iu8 16x16x16 fragment order the A side already uses, so one permutation serves both -// operands and the packer is the same routine at a different radix. A group is GROUP/KPB blocks -// and its f16 scale is read once per group per n-plane, as in the 4-bit kernel. +// the iu8 16x16x16 fragment order the A side uses, so one permutation serves both operands. A +// group is GROUP/KPB blocks; its f16 scale is read once per group per n-plane. // -// THE SCALE PLANE IS f16-ONLY, NOT THE SHARED (scale, zero) DWORD. There is no zero point on a -// symmetric grid and this kernel is DRAM-bound at the decode batch, so the dead half of that dword -// would be pure traffic: at group 128 it is 32 bytes per 2048 of weight, 1.5% of everything read. -// The 4-bit kernel keeps the dword because r4d_gemm_w4a16_nt_m64 shares its bytes; nothing shares -// these. +// The scale plane is f16 only: a symmetric grid has no zero point, and the unused half of a +// (scale, zero) dword would be 1.5% extra traffic on a DRAM-bound kernel. #include "r4d.h" #include "r4d_gemm_args.h" #include "r4d_common.h" @@ -50,12 +33,8 @@ #include #include -// Not structural: mt0 = blockIdx.y * MT tiles M and the row index is clamped into 0..M-1, so any M -// is correct. It is a guard against a caller handing over a garbage shape. +// Not structural (grid.y tiles M, rows are clamped); a sanity bound only. #define R4D_GEMM_W8A8_MAX_M 32768 -#ifndef R4D_GEMM_W8A8_GROUP -#define R4D_GEMM_W8A8_GROUP 128 -#endif #define R4D_GEMM_W8A8_KPB 32 // K per packed block: 2 k steps, 16 bytes per lane #define WAVE32 32 @@ -68,65 +47,8 @@ typedef unsigned uint2v __attribute__((ext_vector_type(2))); typedef __attribute__((address_space(1))) const uint4v* r4d_gw8; typedef __attribute__((address_space(1))) const unsigned short* r4d_gs2; typedef __attribute__((address_space(1))) const uint2v* r4d_ga2; -typedef __attribute__((address_space(1))) const unsigned* r4d_gu1; -// 0 reads A row-major, which only a harness feeding an unpermuted buffer needs; the serving path -// always feeds the permuted buffer the quantiser writes. -#ifndef R4D_W8A8_APERM -#define R4D_W8A8_APERM 1 -#endif - -// COST ABLATIONS. Wrong answers by construction; they exist to say what the time is made of. -// 1 no scale load (sc = 1) -// 2 no activation load (the A fragment is a constant) -// 4 no weight load (the B fragment is a constant; leaves the A stream and the WMMA) -#ifndef R4D_W8A8_ABL -#define R4D_W8A8_ABL 0 -#endif - -// SOFTWARE-PIPELINE THE WEIGHT: hold the NEXT group's weight in registers so its load is issued a -// whole group ahead of the wait, instead of issuing two loads, waiting, and then spending the WMMA -// block with no memory in flight. Costs bpg*NPW*4 VGPRs. -#ifndef R4D_W8A8_PF -#define R4D_W8A8_PF 0 -#endif - -// STAGGER THE GROUP ORDER PER WAVE. Every plane pitch here is a multiple of 4096 and a 256-bit -// GDDR6 part sweeps all sixteen channels in exactly 4096 bytes, so without this every wave in the -// grid is at the same address modulo 4096 and aimed at the same channel group. Starting each wave -// at a different group inside its OWN k-slice and wrapping changes only the order. -// NOTE this reorders an fp32 accumulation, so results move by ~1 ULP. -#ifndef R4D_W8A8_STAGGER -#define R4D_W8A8_STAGGER 0 -#endif - -#if R4D_W8A8_STAGGER -#if R4D_W8A8_APERM -#define AOFF8(g) ((g) * (R4D_GEMM_W8A8_GROUP / 8)) -#else -#define AOFF8(g) ((g) * (R4D_GEMM_W8A8_GROUP / 4)) -#endif -#else -#define AOFF8(g) 0 -#endif - -// HOIST THE ACTIVATION LOADS OFF THEIR WMMA. -// Read `afrag[i]` inside the k-step loop immediately before the WMMA that consumes it and the group -// loop gets one wait per load: at MT=5, NPW=1 that is 40 `global_load_b64`, 40 WMMA and 37 -// `s_wait_loadcnt`. The wave issues one load, stalls on it, runs one matrix instruction and issues -// the next, so there is no memory-level parallelism and the matrix pipe is fully exposed instead of -// co-issued. The ablations below price that exposure at a significant fraction of the kernel. -// -// A lane's eight A bytes for consecutive k steps are SIXTEEN bytes apart -- the intervening eight -// belong to the other lane half -- so they cannot be merged into one b128, and the layout is fixed: -// the same buffer feeds r4d_gemm_w4a8_nt_m64. What can change is when they are -// issued. 1 loads the two k steps of a weight block up front (2*MT loads, then 2*NPW*MT WMMA); -// 2 loads the whole group (2*bpg*MT), which costs bpg times the registers. -#ifndef R4D_W8A8_AHOIST -#define R4D_W8A8_AHOIST 2 -#endif - -// The A fragment, byte for byte what r4d_gemm_w4a8_nt_m64 reads -- same buffer, same producer. +// The A fragment, as r4d_gemm_w4a8_nt_m64 reads it. __device__ __forceinline__ v2i fragA8w(r4d_ga2 p, int u) { const uint2v w = p[2 * u]; v2i r; @@ -135,44 +57,16 @@ __device__ __forceinline__ v2i fragA8w(r4d_ga2 p, int u) { return r; } -__device__ __forceinline__ v2i fragA8row(r4d_gu1 p, int u) { - v2i r; - r[0] = p[4 * u]; - r[1] = p[4 * u + 2]; - return r; -} - __device__ __forceinline__ v8i mmai8(v2i a, v2i b, v8i c) { return __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(true, a, true, b, c, false); } -// __launch_bounds__ IS A REGISTER BUDGET, AND IT HAS TO SEE MT. -// A block of T threads is T/32 waves spread over four SIMDs, so the compiler budgets 1536/(T/128) -// VGPRs per wave: 1024 threads leaves 192, 512 leaves 256 (the architectural cap), 256 the same. -// The accumulator is what runs out -- `acc` is MT*NPW*8 VGPRs and `g_acc` another MT*NPW*8 while a -// group is in flight -- so MT*NPW is the thing that decides, and a bound written in NPW alone is -// blind to half of it. A flat bound of 1024 leaves 192 VGPRs, and under that bound -// `-Rpass-analysis=kernel-resource-usage` reports every wide tile SPILLING: -// -// MT=5..8, NPW=2 192 VGPRs, 15 / 51 / 87 / 123 spilled -// MT=3,4, NPW=4 256 VGPRs, 11 / 65 spilled -// MT=2,3,4 NPW=8 256 VGPRs, 99 / 287 / 530 spilled -// -// and those are the configs M=72 wants, because MB=5 or 6 is what covers five row tiles in one -// block. A wide tile has plenty of independent WMMA to hide latency with and does not need the -// waves; it needs the registers. Bounding it at 256 threads gives it all 256 VGPRs. -// -// The bound is a REAL constraint on the launch, not a hint: a kernel built for 256 threads cannot -// be launched with more, so the host checks WV*SK against the same expression and refuses instead -// of failing at dispatch. -#ifndef R4D_GEMM_W8A8_LB -#define R4D_GEMM_W8A8_LB 1 -#endif -#if R4D_GEMM_W8A8_LB +// __launch_bounds__ is a register budget and depends on MT*NPW. A block of T threads gives +// 1536/(T/128) VGPRs per wave (1024 threads: 192; 512 or fewer: the 256 cap). `acc` and `g_acc` are +// MT*NPW*8 VGPRs each, so under a flat 1024 bound every wide tile spills. A wide tile has enough +// independent WMMA to hide latency without more waves; bounding it at 256 threads gives it 256 +// VGPRs. The bound is a hard launch limit, so the host checks WV*SK against the same expression. #define R4D_W8A8_BOUNDS(MT, NPW) ((MT) * (NPW) >= 8 ? 256 : ((MT) * (NPW) >= 4 ? 512 : 1024)) -#else -#define R4D_W8A8_BOUNDS(MT, NPW) 1024 -#endif template __global__ __launch_bounds__(R4D_W8A8_BOUNDS(MT, NPW)) void r4d_gemm_w8a8_nt_m64_kernel( @@ -196,24 +90,15 @@ __global__ __launch_bounds__(R4D_W8A8_BOUNDS(MT, NPW)) void r4d_gemm_w8a8_nt_m64 for (int i = 0; i < MT; i++) acc[j][i] = (v8f)(0.f); if (n0 < N) { - // Rows clamped, never masked: a tile past M recomputes the last valid row and the store - // discards it. A is int8, so the row stride is K bytes. -#if R4D_W8A8_APERM + // Rows clamped into 0..M-1, never masked; the store discards rows past M. A is int8, so the + // row stride is K bytes. r4d_ga2 pa[MT]; -#else - r4d_gu1 pa[MT]; -#endif #pragma unroll for (int i = 0; i < MT; i++) { int r = (mt0 + i) * 16 + (lane & 15); r = r < M - 1 ? r : M - 1; -#if R4D_W8A8_APERM const size_t off = (size_t)r * K + kbase + 8 * (lane >> 4); pa[i] = (r4d_ga2)(const uint2v*)(A + off); -#else - const size_t off = (size_t)r * K + kbase + 4 * (lane >> 4); - pa[i] = (r4d_gu1)(const unsigned*)(A + off); -#endif } const int kpb = K / R4D_GEMM_W8A8_KPB; @@ -232,118 +117,41 @@ __global__ __launch_bounds__(R4D_W8A8_BOUNDS(MT, NPW)) void r4d_gemm_w8a8_nt_m64 const int bpg = R4D_GEMM_W8A8_GROUP / R4D_GEMM_W8A8_KPB; -#if R4D_W8A8_PF - uint4v nx[NPW][R4D_GEMM_W8A8_GROUP / R4D_GEMM_W8A8_KPB]; -#pragma unroll - for (int j = 0; j < NPW; j++) -#pragma unroll - for (int b = 0; b < bpg; b++) - nx[j][b] = NT ? __builtin_nontemporal_load(&pw[j][(size_t)b * WAVE32]) - : pw[j][(size_t)b * WAVE32]; -#endif - -#if R4D_W8A8_STAGGER - const int gstag = groups > 1 ? (wave * R4D_W8A8_STAGGER) % groups : 0; -#endif - for (int gi = 0; gi < groups; gi++) { -#if R4D_W8A8_STAGGER - const int g = gi + gstag < groups ? gi + gstag : gi + gstag - groups; -#else - const int g = gi; -#endif + for (int g = 0; g < groups; g++) { float sc[NPW]; #pragma unroll for (int j = 0; j < NPW; j++) -#if R4D_W8A8_ABL & 1 - sc[j] = 1.f; -#else sc[j] = __half2float(__ushort_as_half(ps[j][(size_t)g * 16])); -#endif v8i g_acc[NPW][MT]; -#if R4D_W8A8_PF - uint4v cw[NPW][R4D_GEMM_W8A8_GROUP / R4D_GEMM_W8A8_KPB]; -#pragma unroll - for (int j = 0; j < NPW; j++) -#pragma unroll - for (int b = 0; b < bpg; b++) cw[j][b] = nx[j][b]; - if (g + 1 < groups) { -#pragma unroll - for (int j = 0; j < NPW; j++) -#pragma unroll - for (int b = 0; b < bpg; b++) { - const size_t o = (size_t)((g + 1) * bpg + b) * WAVE32; - nx[j][b] = NT ? __builtin_nontemporal_load(&pw[j][o]) : pw[j][o]; - } - } -#endif -#if R4D_W8A8_AHOIST == 2 - // The whole group's activation, issued before any of it is consumed. + // The whole group's activation, issued before any of it is consumed. Loading each fragment + // just before its WMMA gives one s_wait_loadcnt per load and no memory-level parallelism; a + // lane's A bytes for consecutive k steps are 16 bytes apart, so they cannot merge into one + // b128 and only the issue order can change. v2i afg[2 * (R4D_GEMM_W8A8_GROUP / R4D_GEMM_W8A8_KPB)][MT]; #pragma unroll for (int u = 0; u < 2 * bpg; u++) #pragma unroll for (int i = 0; i < MT; i++) -#if R4D_W8A8_ABL & 2 - { afg[u][i][0] = 0x01010101; afg[u][i][1] = 0x01010101; } -#elif R4D_W8A8_APERM - afg[u][i] = fragA8w(pa[i] + AOFF8(g), u); -#else - afg[u][i] = fragA8row(pa[i] + AOFF8(g), u); -#endif -#endif + afg[u][i] = fragA8w(pa[i], u); #pragma unroll for (int b = 0; b < bpg; b++) { uint4v wv[NPW]; #pragma unroll for (int j = 0; j < NPW; j++) { -#if R4D_W8A8_PF - wv[j] = cw[j][b]; -#else const size_t o = (size_t)(g * bpg + b) * WAVE32; -#if R4D_W8A8_ABL & 4 - (void)o; - wv[j] = (uint4v)(0x01010101u); -#else wv[j] = NT ? __builtin_nontemporal_load(&pw[j][o]) : pw[j][o]; -#endif -#endif } -#if R4D_W8A8_AHOIST == 1 - // Both k steps of this weight block, issued before either is consumed. - v2i afb[2][MT]; -#pragma unroll - for (int s = 0; s < 2; s++) -#pragma unroll - for (int i = 0; i < MT; i++) -#if R4D_W8A8_ABL & 2 - { afb[s][i][0] = 0x01010101; afb[s][i][1] = 0x01010101; } -#elif R4D_W8A8_APERM - afb[s][i] = fragA8w(pa[i] + AOFF8(g), b * 2 + s); -#else - afb[s][i] = fragA8row(pa[i] + AOFF8(g), b * 2 + s); -#endif -#endif // Two WMMA k steps per 16-byte weight load: dwords (0,1) then (2,3). #pragma unroll for (int s = 0; s < 2; s++) { const int u = b * 2 + s; v2i afrag[MT]; #pragma unroll -#if R4D_W8A8_AHOIST == 2 for (int i = 0; i < MT; i++) afrag[i] = afg[u][i]; -#elif R4D_W8A8_AHOIST == 1 - for (int i = 0; i < MT; i++) afrag[i] = afb[s][i]; -#elif R4D_W8A8_ABL & 2 - for (int i = 0; i < MT; i++) { afrag[i][0] = 0x01010101; afrag[i][1] = 0x01010101; } -#elif R4D_W8A8_APERM - for (int i = 0; i < MT; i++) afrag[i] = fragA8w(pa[i] + AOFF8(g), u); -#else - for (int i = 0; i < MT; i++) afrag[i] = fragA8row(pa[i] + AOFF8(g), u); -#endif #pragma unroll for (int j = 0; j < NPW; j++) { - // The eight bytes ARE the fragment: no mask, no shift, no zero point. + // The eight weight bytes are the fragment. v2i bfrag; bfrag[0] = (int)wv[j][2 * s]; bfrag[1] = (int)wv[j][2 * s + 1]; @@ -361,28 +169,17 @@ __global__ __launch_bounds__(R4D_W8A8_BOUNDS(MT, NPW)) void r4d_gemm_w8a8_nt_m64 #pragma unroll for (int e = 0; e < 8; e++) acc[j][i][e] = fmaf((float)g_acc[j][i][e], sc[j], acc[j][i][e]); -#if !R4D_W8A8_STAGGER #pragma unroll -#if R4D_W8A8_APERM for (int i = 0; i < MT; i++) pa[i] += R4D_GEMM_W8A8_GROUP / 8; -#else - for (int i = 0; i < MT; i++) pa[i] += R4D_GEMM_W8A8_GROUP / 4; -#endif -#endif } } - // Split-K reduction and store, one row tile at a time. The per-row activation scale is applied - // here and only here: it is constant over n and over the group index, so it never entered the - // k loop. + // Split-K reduction and store, one row tile at a time, applying the per-row activation scale. const int ncols = WV * NPW; const int nthreads = WV * SK * WAVE32; - // AT SK == 1 THERE IS NOTHING TO REDUCE. The general path below writes eight floats per - // accumulator to LDS and reads them straight back, and pays two __syncthreads() per row tile to - // do it -- MB row tiles is MB barrier pairs on a kernel whose whole job is to keep a load in - // flight. With one k-slice a lane already holds the finished value, and the same (m, n) it - // would have landed on is just the LDS index arithmetic with off = e*32 + lane substituted in. + // At SK == 1 there is nothing to reduce: store directly and skip the two barriers per row tile. + // (m, n) is the LDS path's index arithmetic with off = e*32 + lane. if (SK == 1) { if (n0 >= N) return; #pragma unroll @@ -432,14 +229,8 @@ void r4d_gemm_w8a8_nt_m64(long a, long ascale, long wq, long ws, long c, int M, throw std::runtime_error("r4d gemm_w8a8_nt_m64: K must be divisible by SK*group"); if (WV * SK * WAVE32 > R4D_W8A8_BOUNDS(MB, NPW)) throw std::runtime_error("r4d gemm_w8a8_nt_m64: WV*SK*32 exceeds this tile's launch bound"); - // MB RUNS TO EIGHT, AND THAT IS THE WHOLE POINT AT M = 72. A block covers MB row tiles and - // grid.y takes the rest, so every extra grid.y walks the WHOLE weight again -- the same - // "seventeen rows is two macro tiles" that makes a library GEMM read a 636 MB lm_head twice. At - // eight concurrent sequences the target verifies 8 x 9 = 72 rows, which is mtiles = 5, so a cap - // of 4 would force grid.y = 2 and read the whole weight twice to do LESS work than M = 64 does - // in one pass. Five is the shape the model actually runs. - if (MB < 1 || MB > 8) throw std::runtime_error("r4d gemm_w8a8_nt_m64: MB must be 1..8"); - if (MB * NPW > 10) throw std::runtime_error("r4d gemm_w8a8_nt_m64: MB*NPW > 10 would spill"); + // cfg_for (r4d_gemm_args.h) caps MB at 4. + if (MB < 1 || MB > 4) throw std::runtime_error("r4d gemm_w8a8_nt_m64: MB must be 1..4"); if (NPW != 1 && NPW != 2 && NPW != 4 && NPW != 8) throw std::runtime_error("r4d gemm_w8a8_nt_m64: NPW must be 1, 2, 4 or 8"); const int ntiles = N / 16, mtiles = (M + 15) / 16; @@ -455,39 +246,24 @@ void r4d_gemm_w8a8_nt_m64(long a, long ascale, long wq, long ws, long c, int M, hipStream_t st = (hipStream_t)stream; #define LAUNCH8(MT, NP, TT) hipLaunchKernelGGL((r4d_gemm_w8a8_nt_m64_kernel), \ grid, block, smem, st, Ap, Sp, Wp, Zp, Cp, M, K, N, WV, SK) -// WHICH (MT, NPW) EXIST AT ALL. `acc` is MT*NPW*8 VGPRs and `g_acc` another MT*NPW*8 while a -// group is in flight, so a tile costs 16*MT*NPW registers plus about forty of addressing against -// an architectural cap of 256 -- and `-Rpass-analysis=kernel-resource-usage` puts the boundary -// exactly where that predicts: MT*NPW = 10 lands at 207 VGPRs and does not spill, 12 spills 33, -// and 16 spills 119 to 530. A spilling tile can never win, so it is not built: it would only cost -// compile time and give the tuner configs to reject. -#define LAUNCH8_MB8(NP, TT) switch (MB) { \ +// Only tiles with MT*NPW <= 8 are built: a tile costs about 16*MT*NPW + 40 VGPRs against the 256 +// cap. +#define LAUNCH8_MB4(NP, TT) switch (MB) { \ case 1: LAUNCH8(1, NP, TT); break; \ case 2: LAUNCH8(2, NP, TT); break; \ case 3: LAUNCH8(3, NP, TT); break; \ case 4: LAUNCH8(4, NP, TT); break; \ - case 5: LAUNCH8(5, NP, TT); break; \ - case 6: LAUNCH8(6, NP, TT); break; \ - case 7: LAUNCH8(7, NP, TT); break; \ - case 8: LAUNCH8(8, NP, TT); break; \ default: throw std::runtime_error("r4d gemm_w8a8_nt_m64: MB unsupported"); } -#define LAUNCH8_MB5(NP, TT) switch (MB) { \ - case 1: LAUNCH8(1, NP, TT); break; \ - case 2: LAUNCH8(2, NP, TT); break; \ - case 3: LAUNCH8(3, NP, TT); break; \ - case 4: LAUNCH8(4, NP, TT); break; \ - case 5: LAUNCH8(5, NP, TT); break; \ - default: throw std::runtime_error("r4d gemm_w8a8_nt_m64: MB*NPW > 10 would spill"); } #define LAUNCH8_MB2(NP, TT) switch (MB) { \ case 1: LAUNCH8(1, NP, TT); break; \ case 2: LAUNCH8(2, NP, TT); break; \ - default: throw std::runtime_error("r4d gemm_w8a8_nt_m64: MB*NPW > 10 would spill"); } + default: throw std::runtime_error("r4d gemm_w8a8_nt_m64: MB*NPW > 8 would spill"); } #define LAUNCH8_MB1(NP, TT) switch (MB) { \ case 1: LAUNCH8(1, NP, TT); break; \ - default: throw std::runtime_error("r4d gemm_w8a8_nt_m64: MB*NPW > 10 would spill"); } + default: throw std::runtime_error("r4d gemm_w8a8_nt_m64: MB*NPW > 8 would spill"); } #define LAUNCH8_NPW(TT) switch (NPW) { \ - case 1: LAUNCH8_MB8(1, TT); break; \ - case 2: LAUNCH8_MB5(2, TT); break; \ + case 1: LAUNCH8_MB4(1, TT); break; \ + case 2: LAUNCH8_MB4(2, TT); break; \ case 4: LAUNCH8_MB2(4, TT); break; \ case 8: LAUNCH8_MB1(8, TT); break; \ default: throw std::runtime_error("r4d gemm_w8a8_nt_m64: NPW must be 1, 2, 4 or 8"); } @@ -495,20 +271,17 @@ void r4d_gemm_w8a8_nt_m64(long a, long ascale, long wq, long ws, long c, int M, #undef LAUNCH8_NPW #undef LAUNCH8_MB1 #undef LAUNCH8_MB2 -#undef LAUNCH8_MB5 -#undef LAUNCH8_MB8 +#undef LAUNCH8_MB4 #undef LAUNCH8 } int r4d_gemm_w8a8_nt_m64_max_m(void) { return R4D_GEMM_W8A8_MAX_M; } int r4d_gemm_w8a8_nt_m64_group(void) { return R4D_GEMM_W8A8_GROUP; } int r4d_gemm_w8a8_nt_m64_kpb(void) { return R4D_GEMM_W8A8_KPB; } -int r4d_gemm_w8a8_nt_m64_aperm(void) { return R4D_W8A8_APERM; } // ============================================================== the plugin ABI entry points // -// The operand reader and the split law are in r4d_gemm_args.h. See libr4d/r4d_args.h for why there -// is no adapter directory between the core and these launches. +// The operand reader and the split law are in r4d_gemm_args.h; see libr4d/r4d_args.h. extern "C" int r4d_rad_gemm_w8a8_m64(const RadArgs* a, RadStream s) { GemmOps g; int rc = gemm_ops(a, &g, 1); diff --git a/libr4d/r4d_gemm_w8a8_tiled.hip b/libr4d/r4d_gemm_w8a8_tiled.hip index d4d4bd22..d32b0980 100644 --- a/libr4d/r4d_gemm_w8a8_tiled.hip +++ b/libr4d/r4d_gemm_w8a8_tiled.hip @@ -1,24 +1,16 @@ -// r4d_gemm_w8a8_tiled.hip - r4d_gemm_w8a8_tiled: the W8A8 GEMM for PREFILL batches. +// r4d_gemm_w8a8_tiled.hip - r4d_gemm_w8a8_tiled: the W8A8 GEMM for prefill batches. // -// This is r4d_gemm_w4a8_tiled with the weight radix doubled, and it is a SMALL delta on purpose. -// That kernel already has an "unpack at staging" path (OPT bit 256, `WU`): it turns a dword of -// nibbles into eight bytes as it writes LDS, so the LDS buffer holds BYTES in -// `[tile][lane*8 + u*2]` order and the fragment read is one `ds_load_b64`. An 8-bit weight wants -// exactly that buffer, already in that order -- so the inner loop, the double buffering, the XOR -// swizzle, the magic-bias epilogue and the whole variant table are inherited UNCHANGED, and the -// only thing that differs is where the bytes come from: a copy instead of an unpack. +// r4d_gemm_w4a8_tiled with the weight radix doubled: the inner loop, double buffering, XOR swizzle +// and magic-bias epilogue are that kernel's, and staging copies the weight's bytes to LDS in +// `[tile][lane*8 + u*2]` order instead of unpacking nibbles. // -// AT PREFILL THE PROMOTION IS NEARLY FREE, WHICH IS THE POINT. A tiled GEMM at M=4096 is bound by -// the matrix pipe, not the weight stream, and the WMMA count does not depend on the radix -- the -// same K, the same 16x16x16 iu8 instructions. Eight bits costs twice the weight bytes and twice -// the LDS staging traffic, both of which the tile amortises over BM rows. So the prefill cost of -// promoting down_proj and o_proj should be a few percent, where routing them to a SKINNY kernel -// (which re-reads the weight M/(16*MB) times) costs 0.76-0.89x against the vendor path. +// At prefill the promotion to eight bits is nearly free: the kernel is matrix-bound and the WMMA +// count does not depend on the radix, while twice the weight and LDS bytes are amortised over BM +// rows. (A skinny kernel would re-read the weight M/(16*MB) times.) // -// THE PACKED LAYOUT IS r4d_gemm_w8a8_nt_m64's, UNCHANGED. A lane owns 16 bytes of a 32-column -// block, so a BK of 64 spans TWO of them and a lane stages 2 x 16 bytes that sit 512 bytes apart -- -// two coalesced `global_load_b128`, landing at `lane*8 + kh*4` dwords of the tile's LDS run. One -// weight feeds both kernels, exactly as the two 4-bit kernels share theirs. +// The packed layout is r4d_gemm_w8a8_nt_m64's: a lane owns 16 bytes of a 32-column block, staged +// with coalesced global_load_b128 to `lane*8 + kh*4` dwords of the tile's LDS run. One weight feeds +// both kernels. The scale plane is f16 only: a symmetric 8-bit grid has no zero point. // #include "r4d.h" #include "r4d_gemm_args.h" @@ -26,230 +18,44 @@ #include #include #include -#include #include #define R4D_TILED8_KPB 32 // packed block: 32 columns, 16 bytes a lane -// BK = 32, NOT THE 4-BIT KERNEL'S 64. An 8-bit weight stages twice the bytes, and at BK = 64 that -// is 40960 B of LDS on the 64x256 tile against the 4-bit kernel's 24576 -- ONE workgroup per CU -// instead of two. Halving BK halves both staged buffers: 20480 B, three workgroups, and VGPR -// occupancy 6-12 -> 8-16. On down_proj that is worth several percent at every prefill M: the -// extra barriers per scale group cost less than the occupancy is worth. -#ifndef R4D_W8A8T_BK -#define R4D_W8A8T_BK 32 -#endif -#define R4D_TILED8_BK R4D_W8A8T_BK // the k step of the block loop; the host needs it for UNRG +// BK = 32, not the 4-bit kernel's 64: at BK = 64 the 64x256 tile needs 40960 B of LDS (one +// workgroup per CU); BK = 32 needs 20480 B (three), worth several percent on down_proj at every +// prefill M despite twice the barriers per scale group. +#define R4D_TILED8_BK 32 typedef int v2i8_t __attribute__((ext_vector_type(2))); typedef int v8i8_t __attribute__((ext_vector_type(8))); typedef float v8f8_t __attribute__((ext_vector_type(8))); typedef unsigned u4v8_t __attribute__((ext_vector_type(4))); -typedef unsigned u2v8_t __attribute__((ext_vector_type(2))); // 8 bytes = four bf16 -typedef float v4f8_t __attribute__((ext_vector_type(4))); -// BSIGNED=false reads the unpacked byte as 16*nibble (0..240) instead of 16*twos(nibble): the -// asymmetric grid, whose per-group zero is then corrected out with a row-sum of the activation. -template -__device__ __forceinline__ v8i8_t t8mmai(v2i8_t a, v2i8_t b, v8i8_t c) { - return __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(true, a, BSIGNED, b, c, false); -} - -__device__ __forceinline__ v2i8_t t8dequant8(unsigned w) { - v2i8_t r; - r[0] = (int)((w << 4) & 0xF0F0F0F0u); - r[1] = (int)(w & 0xF0F0F0F0u); - return r; -} - -__device__ __forceinline__ unsigned t8pack2bf(float a, float b) { - unsigned ua = __float_as_uint(a), ub = __float_as_uint(b); - ua += 0x7FFFu + ((ua >> 16) & 1u); // round to nearest even, no NaN branch - ub += 0x7FFFu + ((ub >> 16) & 1u); - return __builtin_amdgcn_perm(ub, ua, 0x07060302u); // {ub.hi16, ua.hi16} -} - -// WM x WN waves, each owning TM x TN WMMA tiles. BM = WM*TM*16, BN = WN*TN*16, BK = the scale group. +// WM x WN waves, each owning TM x TN WMMA tiles. BM = WM*TM*16, BN = WN*TN*16. UNR k blocks are +// unrolled per scale group. The accumulator carries the magic bias of r4d_gemm_w4a8_tiled.hip: +// for |x| < 2^22, float(x) == __uint_as_float(0x4B400000 + x) - 12582912.0f. // -// BIAS KILLS THE int32 -> float CONVERSION IN THE GROUP EPILOGUE. Every group closes with -// `acc += (float)g * s` over TM*TN*8 = 64 accumulator elements, which is 128 VALU against 64 WMMA -// instructions -- 2 VALU per WMMA, the single largest overhead in the loop. Half of it is -// `v_cvt_f32_i32`, and that half can be deleted outright: for |x| < 2^22, -// -// float(x) == __uint_as_float(0x4B400000 + x) - 12582912.0f -// -// because 0x4B400000 is 1.5*2^23, whose mantissa field sits exactly at 2^22, so adding x lands x in -// the mantissa unrounded. The group's int32 sum is at most 128 * 127 * 128 = 2,080,768, half the -// budget. BIAS=1 adds the constant with `v_add_nc_u32` (which, unlike v_cvt, is VOPD-eligible and -// can dual-issue with the fmac next to it); BIAS=2 seeds the WMMA's C operand with it instead, so -// the accumulator comes OUT biased and the conversion costs nothing at all -- at the price of eight -// VGPRs held for the constant vector, and 192 is exactly the budget for two workgroups per CU. -// The -12582912*s per group is folded into a per-column running sum and subtracted once at the end. -// -// SKT: A BALANCED LAST ROUND. The part runs 32 workgroups at a time (one 512-thread workgroup per -// WGP), so a grid of T tiles takes ceil(T/32) rounds and the last one runs T mod 32 workgroups on a -// 32-slot machine. `gate_up_proj` is N = 17408 = 2^10 x 17, which is 136 tiles at BN = 128: four -// full rounds and a round of eight, and that round standalone costs well over twice what the same -// work does spread over 32 workgroups at a quarter of K each. -// -// SKT != 0 splits ONLY the tail tiles along K. The first `nfull` tiles are ordinary data-parallel -// blocks that store straight to C; the rest are `r` tiles x `s` K-pieces, which write fp32 partials -// to a workspace and let the LAST piece to arrive reduce them. "Last to arrive" is an atomic -// counter, so there is no spin and no assumption about dispatch order; the reduction reads the s -// slots in INDEX order, so the sum is deterministic run to run even though the arrival order is not. -// It is not bit-identical to the unsplit kernel -- the fp32 adds re-associate at the piece boundary -// -- and it is not meant to be; it is a different, equally valid summation order. It agrees with -// the unsplit kernel to at most one bf16 ULP across every shape, batch and tile it was checked on, -// and against an fp32 reference it is equal or very slightly better. -// -// AND IT DOES NOT PAY at any batch the decode dispatch reaches. The tail round is cheaper split, -// but a full grid run whole is cheaper than running the two halves back to back: the part is -// ALREADY overlapping most of that tail with the round in front of it, and the workspace round trip -// plus the reduction's arrival barrier cost more than the remainder. It is a loss at the narrow -// batches and a wash to a small loss everywhere the dispatch table picks. The two instantiations -// are kept because the path is correct and cheap to re-check, NOT because anything should call it. -template -__global__ __launch_bounds__(WM * WN * 32, WPE) void r4d_gemm_w8a8_tiled_kernel( +// `Asum` is always null (an 8-bit grid here is symmetric). The slot keeps the 4-bit kernel's +// argument layout: dropping it changes the generated code of the tuned tiles. +template +__global__ __launch_bounds__(WM * WN * 32, 8) void r4d_gemm_w8a8_tiled_kernel( const signed char* __restrict__ A, const float* __restrict__ Ascale, const unsigned* __restrict__ Wq, const unsigned* __restrict__ Ws, - const float* __restrict__ Asum, __hip_bfloat16* __restrict__ C, int M, int K, int N, - float* __restrict__ WSP, unsigned* __restrict__ CNT, int nfull, int nrag, int nspl) { - // BK IS A KNOB HERE, WHERE THE 4-BIT KERNEL COULD LEAVE IT AT 64. An 8-bit weight stages twice - // the bytes, and `-Rpass-analysis=kernel-resource-usage` says what that costs: the 64x256 tile - // takes 40960 B of LDS against the 4-bit kernel's 24576, which is ONE workgroup per CU instead of - // two, and 48x256 the same. Halving BK halves both staged buffers -- 20480 B, three workgroups -- - // at the price of twice as many barriers per scale group. Which way that trades depends on the - // shape, so BK stays a build knob rather than a constant. - constexpr int BK = R4D_W8A8T_BK; // half a scale group at 64 + const float* __restrict__ Asum, __hip_bfloat16* __restrict__ C, int M, int K, int N) { + constexpr int BK = R4D_TILED8_BK; constexpr int GRP = R4D_GEMM_W8A8_GROUP; constexpr int BM = WM * TM * 16, BN = WN * TN * 16; constexpr int NTILE = BN / 16; constexpr int AW = BM * BK / 4; // A dwords per buffer - // OPT BIT 256: UNPACK THE WEIGHT ONCE, AT STAGING, INSTEAD OF WM TIMES ON READ. - // The fragment read gives wave (wm, wn) the n-tiles of `wn`, so every wave sharing a `wn` -- - // WM of them -- unpacks the SAME dwords. Counted per block per k step: the read path does - // WM*WN waves x 32 lanes x TN*4 dwords x 3 VALU, the staging path does WW dwords once, and the - // ratio is exactly WM. With the 16-row swizzle in place the DCE-proof ablation puts the unpack - // at about a quarter of this kernel at a decode M, and the W LDS read at ~0 (deleting it measures - // the same as deleting the unpack alone), so trading half the unpack for twice the W LDS traffic - // is the right side of that trade. It costs LDS: the W buffer holds bytes rather than nibbles. - // AN 8-BIT WEIGHT IS ALWAYS "unpacked": the staged bytes ARE the fragment. The OPT bit that - // selected this path in the 4-bit kernel is therefore not a choice here, and the packed-nibble - // staging paths it selects against do not exist. The same goes for the iu4 route, the - // no-LDS weight path and the dword scale table -- all four bits are simply INERT here, which - // makes some entries of the inherited variant table duplicates of each other. That is better - // than asserting on them: the table is indexed by number from the tuner, and renumbering it - // would silently invalidate every recorded pick. - constexpr bool WU = true; - // OPT BIT 512: THE iu4 PATH -- no weight dequant at all. - // `v_wmma_i32_16x16x32_iu4` eats PACKED nibbles, and the DCE-proof ablation puts the unpack at - // about a quarter of this kernel at a decode M, with a no-unpack build landing at 1.09x the - // one-pass memory floor. The activation is the SAME int8, split exactly as - // `a = 16*(a>>4) + (a&15)` with the high half read signed and the low half unsigned, so two iu4 - // replace the two iu8 that covered the same K. Integer accumulation makes the re-association - // exact, and the split holds over all 256 x 16 (a, q) pairs on hardware -- this is bit-identical - // arithmetic, not an approximation. - // - // THE WEIGHT IS NOT RE-PERMUTED. A GEMM is invariant under a permutation of k applied to BOTH - // operands, and the instruction pairs A slot p with B slot p exclusively -- a perfect 16x16 - // diagonal on hardware. So the packed artifact stays byte-identical - // and only the ACTIVATION is laid out to name the k the weight packing already names: - // byte c*32 + P*16 + h*8 + d*4 + i/2, nibble i&1 <- plane P of a[m][64*blk + c*32 + d*16 + - // KIDX[h][i]], KIDX[0] = 0,8,1,9,2,10,3,11 KIDX[1] = 4,12,5,13,6,14,7,15 - // which is the same bytes and the same `ds_load_b64` count as the int8 form. - constexpr bool IU4 = false; - // OPT BIT 65536: NON-TEMPORAL WEIGHT LOADS. - // At M=64 this kernel is 20-27% over its weight roofline where at M=8 it is 5%, and the inner - // loop is not the reason: per 512 bytes streamed at the full 634 GB/s this part - // gives away 32 iu8 matrix instructions, 96+ VALU and 96+ LDS reads for FREE, and the shipped - // tile spends 20, 12 and 20 of them. What scales with M is the ACTIVATION: - // every column block stages the whole M x K of A, so gate_up's 136 blocks read 44.6 MB of A - // against 47.35 MB of weight, and A is 328 KB -- it should live in L2 and be nearly free. The - // weight stream is what evicts it: 636 MB walked once, never re-read, filling every level on the - // way past. A non-temporal hint on the weight says so, and leaves A where it was. - constexpr bool WNT = (OPT & 65536) != 0; - // OPT BIT 131072: THE WEIGHT NEVER GOES THROUGH LDS. - // The staged weight buys sharing between the WM waves that hold the same `wn`, and every tile a - // decode step picks has WM = 1 -- so it buys nothing and costs a `ds_store_b128` per thread per - // k step, half the LDS budget, and a barrier that has to wait for the weight's global load as - // well as the activation's. The fragment a wave wants is already one contiguous 512-byte block - // read `lane*4` dwords at a time, which is EXACTLY the shape the staging loads it in, so the - // register the prefetch put it in can be read directly. Double buffering moves from LDS to a - // second register set, indexed by the same compile-time `it & 1` the unrolled k loop already has. - constexpr bool WNOLDS = false; - // OPT BIT 262144: FETCH THE GROUP SCALE A WHOLE GROUP EARLIER STILL. - // Of everything inside this loop, the group scale is the ONLY item that prices above the control - // spread at the tiles a decode step picks: replacing the load with a constant is worth several - // percent on `gate_up`, where the unpack, the weight LDS read, the activation LDS read and the - // group fold are each inside it. Its bandwidth share is 5.9%, so about a quarter is latency - // the existing one-group prefetch does not cover -- the load lands at the start of the group it - // is used at the end of, and every wave in every workgroup reaches that boundary together. - // Rotate two registers instead: fetch group g+1 at the start of group g. - constexpr bool SCPF2 = (OPT & 262144) != 0; - // OPT BIT 524288: THE SCALE TABLE IS f16, NOT A DWORD. - // The dword per (column, group) carries the f16 scale in its low half and the f16 of -(1024+zero) - // in its high half, and the SYMMETRIC path -- which is what ships -- reads `raw & 0xFFFF` and - // never touches the other two bytes. They are 5.9% of everything `gate_up` streams and the only - // item in this loop that prices above the control spread, and pricing it as latency is wrong: - // a prefetch a whole group deeper buys nothing where deleting the load buys several percent. So - // halve the table. The arithmetic is untouched -- the same f16, the same fold, same output -- - // and the asymmetric path keeps the dword because it needs the other half. - // The scale plane is f16-only. There is no zero point on a symmetric 8-bit grid, so the dword - // form's high half would be dead traffic on a kernel that streams the weight once. - constexpr bool SC16 = true; - - // AN ABLATION THAT ALSO DELETES THE STAGING IS TWO ABLATIONS. The variants below 10 are guarded - // by `ABL == 0` at the prefetch and the commit, so every one of them ALSO runs with no global - // loads and no double buffer -- fine for ranking two variants against each other, useless for - // pricing one item against the shipped kernel. ABL >= 10 repeats one of those variants with the - // staging left in, which is what a prefill cost breakdown needs; the variants below 10 keep their - // own meanings. - constexpr int ABX = ABL == 10 ? 5 : ABL == 11 ? 6 : ABL == 12 ? 7 : ABL == 13 ? 3 - : ABL == 14 ? 4 : ABL == 15 ? 9 : ABL == 16 ? 2 : ABL == 17 ? 8 : ABL; - constexpr bool TWOACC = IU4 || ABX == 8; - // THE MAGIC BIAS AND iu4 DO NOT MIX, and the reason is worth stating because the arithmetic - // itself is exact. BIAS=2 seeds the int32 accumulator with 0x4B400000 so the int->float - // conversion is a reinterpretation; the float fold then rounds `(12582912 + G) * s` once. The - // iu4 path multiplies the RAW nibble rather than 16*q, so its integer G is SIXTEEN TIMES smaller - // for the same answer -- the bias is unchanged but the signal under it is not, and the rounding - // that was 1/16 ULP of the signal becomes one. The result is 7.22e-3 against the iu8 path's - // 2.37e-3, three times the 4-bit quantisation error, which is not a rounding difference worth - // arguing about. - // - // Restoring it would mean holding `bias + 16*G` in the accumulator, which costs a second shift - // per element per group. Plain `v_cvt_f32_i32` (BIAS=0) costs a fraction of a percent against - // the biased build here and is MORE accurate than the shipped path (2.33e-3 against 2.37e-3), - // because the product it rounds has no bias in it at all. So iu4 simply does not take the bias. - static_assert(!IU4 || BIAS == 0, "the iu4 path must be built with BIAS = 0"); - // - // REJECTED, and the arithmetic says why in one line. Per scale group this path - // SAVES the unpack, 3 VALU per weight dword = 24*TN - // COSTS the hi/lo combine, one per element = 8*TM*TN - // COSTS the cvt that the magic bias deletes = 8*TM*TN - // so the net is 8*TN*(2*TM - 3): a win only at TM = 1, which means BM = 32 and no batch a serve - // makes wants a row tile that small. It also costs 30 VGPRs (85 -> 115 at BM=96/BN=128), which - // crosses the 96-VGPR step from 16 waves per SIMD to 12, and at BM=128 it spills 65 bytes. - // Against the same tile on iu8 it is bit-identical in output and ranges from a small win to a - // large loss across the tiles these batches pick, with BM=128 more than twice the time. The - // ABL 8 variant looks better than the real path only because it keeps the magic bias, which the - // real path cannot have. One instantiation is kept because it is correct and bit-identical, and - // the only thing that would change the verdict is a tile with TM = 1. constexpr int WW = NTILE * BK * 4; // W dwords per buffer: NTILE*16 rows x BK bytes __shared__ unsigned lds_a[2][AW]; - __shared__ unsigned lds_w[2][WNOLDS ? 4 : WW]; + __shared__ unsigned lds_w[2][WW]; const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; const int wm = wave / WN, wn = wave % WN; - int tilex = blockIdx.x, kbeg = 0, kend = K, slot = -1; - if (SKT && (int)blockIdx.x >= nfull) { - const int jj = (int)blockIdx.x - nfull, kper = K / nspl; - tilex = nfull + jj / nspl; - kbeg = (jj % nspl) * kper; - kend = kbeg + kper; - slot = (int)blockIdx.y * (nrag * nspl) + jj; - } - const int m0 = blockIdx.y * BM, n0 = tilex * BN; + const int bx = blockIdx.x; + const int m0 = blockIdx.y * BM, n0 = bx * BN; const int kpb = K / R4D_TILED8_KPB, nsz = K / GRP; constexpr int NT_ = WM * WN * 32; @@ -259,729 +65,147 @@ __global__ __launch_bounds__(WM * WN * 32, WPE) void r4d_gemm_w8a8_tiled_kernel( #pragma unroll for (int i = 0; i < TM; i++) acc[j][i] = (v8f8_t)(0.f); v8i8_t g[TN][TM]; - // ABL 8 prices the iu4 ROUTE. `v_wmma_i32_16x16x32_iu4` consumes PACKED nibbles, so a kernel - // built on it has no weight unpack at all -- and the DCE-proof ablation puts the unpack at 24.7% - // of this kernel at M=72, with a no-unpack build landing at 1.09x the one-pass memory floor. - // The route is `A_i8 = 16*A_hi + A_lo` with A_hi signed and A_lo unsigned int4, which is exact, - // so ONE iu4 instruction covers K=32 and two of them (hi and lo, sharing the B fragment) replace - // the two iu8 instructions that covered the same K. Instruction count is unchanged; what goes - // away is the unpack, and what it costs is a second int32 accumulator per output tile. - // This variant computes the WRONG ANSWER on purpose -- it feeds whatever bits are to hand, - // because the real thing needs an offline weight re-permutation and a 4-bit-plane activation - // format. It exists to say whether that pipeline is worth building. - v8i8_t g2[TWOACC ? TN : 1][TWOACC ? TM : 1]; float csum[TN]; #pragma unroll for (int j = 0; j < TN; j++) csum[j] = 0.f; - unsigned scv[TN], scn[SCPF2 ? TN : 1]; - float asp[ASYM ? TM : 1][8]; + unsigned scv[TN]; - // XOR SWIZZLE instead of padding. A row is BK/4 = 16 dwords and LDS has 32 banks, so a half-wave's - // sixteen lanes -- differing only in the row -- would collide. Padding by one dword fixes that and - // costs more than it saves: A+W is exactly 32 KB and one extra dword per row drops a CU from two - // workgroups to one, a small gain at M=512 and a large loss at M=4096. The mask must stay INSIDE the row: - // (row & 15) << 1 reaches 30, walks into the next row and gives a 0.386 relative error. -// With 128-bit staging (OPT bit 3) the mask has to permute whole 4-dword BLOCKS, or a `ds_store_b128` -// of dwords 0-3 lands at swizzled position 2 and writes {2,3,4,5} instead of {2,3,0,1}: silently -// wrong data (relative error 0.79) and a 16-byte store at an 8-byte-aligned address. (r&3)<<2 is -// 0/4/8/12, which still separates rows two apart -- the LDS bank period at a 16-dword row stride -- -// and still lands inside the row, since 15 ^ 12 = 3. -// OPT BIT 128: A SWIZZLE THAT SEPARATES SIXTEEN ROWS, NOT EIGHT. -// The fragment read has sixteen lanes differing ONLY in the row -- `row = ... + (lane & 15)` -- at a -// fixed column, and the row stride is BK/4 = 16 dwords. Bank = (r*16 + (c ^ mask)) % 32, so the -// row contributes only its low bit and the mask has to separate the other four. `(r & 7) << 1` -// separates eight, so rows r and r+8 land on the same bank: a 2-WAY CONFLICT on every A read. -// `((r >> 1) & 7) << 1` gives the eight EVEN rows eight distinct masks and the eight odd rows the -// same eight in the upper bank half, which is conflict-free at the read. It stays inside the row -// (both operands are 4-bit, so the XOR is) and stays EVEN, which the `ds_load_b64` alignment needs. -// The store side is unaffected either way: there sixteen consecutive lanes share a row and differ -// in c, so they were already spread across all sixteen banks of the row. -// -// This matters because the A LDS read is the LARGEST single item in this inner loop -- the -// DCE-proof ablation puts it at about a third of the kernel at the tiles a decode step picks. -// THE SWIZZLE MASK IS SIZED BY THE ROW, AND THE ROW IS BK/4 DWORDS. The 4-bit kernel can write -// the masks as literals because its BK is always 64, giving a 16-dword row that 7<<1 = 14 and 3<<2 -// = 12 both fit inside. At BK = 32 the row is EIGHT dwords and both literals walk into the next -// row -- which is the exact failure this macro's own note describes, and it makes every tiled -// variant wrong at once rather than silently wrong in one. Derive the masks from BK instead: the -// 2-dword form needs mask < BK/4 stepping by 2, the 4-dword form the same stepping by 4. + // XOR swizzle of the A rows instead of padding, separating rows r >> 1 (see + // r4d_gemm_w4a8_tiled.hip). The XOR must stay inside a row of BK/4 = 8 dwords, so the mask is + // derived from BK and steps by 2 for ds_load_b64 alignment. #define ASW_M2 ((BK / 8) - 1) -#define ASW_M4 ((BK / 16) - 1) -#define ASW(r, c) \ - ((r) * (BK / 4) + ((c) ^ ((OPT & 8) ? (((OPT & 128) ? ((r) >> 1) : (r)) & ASW_M4) << 2 \ - : (((OPT & 128) ? ((r) >> 1) : (r)) & ASW_M2) << 1))) +#define ASW(r, c) ((r) * (BK / 4) + ((c) ^ ((((r) >> 1) & ASW_M2) << 1))) - // A PREFETCH THAT WRITES LDS DIRECTLY DOES NOT OVERLAP, and it is worth more than a factor of two. - // The LDS store waits on the global load and sits before the compute in program order, so the - // compute waits too. Load into REGISTERS, compute off the other buffer, then commit, so the wait - // lands after the WMMA work. Same buffers, same barriers, same traffic; only the s_waitcnt moves. - // A RAGGED A STAGING, so BM does not have to be a multiple of the workgroup width. - // AW = BM*BK/4 dwords, so 512 threads need BM % 32 == 0 and the tile ladder had to skip 80 and - // 112 -- exactly the sizes that fit a decode M without rounding it up. One predicate on the - // last partial pass costs nothing when it divides (the guard folds away) and unlocks the rest. - constexpr int APT = (AW + NT_ - 1) / NT_, WPT = WW / NT_; + // Prefetch into registers, compute off the other buffer, then commit to LDS, so the load wait + // lands after the WMMA work (a prefetch that writes LDS directly would stall the compute; >2x). + // Both stagings may be ragged (a predicate on the last pass), so the tile need not divide the + // workgroup width (e.g. BM = 80, 112; at BK = 32 the NTILE*32 weight chunks). + constexpr int APT = (AW + NT_ - 1) / NT_; constexpr bool APAD = (AW % NT_) != 0; - unsigned ra[APT > 0 ? APT : 1], rw[WPT > 0 ? WPT : 1]; - // 128-BIT STAGING (OPT bit 3). Each thread otherwise moves one dword per array per iteration: - // four global loads, four LDS stores and four addresses for 32 bytes. A row is BK/4 = 16 dwords - // and the block is 512 threads, so four threads cover a row exactly -- one `global_load_b128` and - // one `ds_store_b128` each instead of four of each. The wave touches the same segments either - // way: 32 lanes x 16 B over 8 rows is the same 64-byte runs as 32 lanes x 4 B over 2 rows. - // A 128-BIT STAGING PATH THAT DOES NOT TILE LOADS NOTHING AT ALL, SILENTLY. - // Variant 9 (<2,8,4,1>, BM 128 BN 128) is 512 threads against WW = NTILE*128 = 1024 weight - // dwords, so (WW/4)/NT_ is 0, the `OPT & 16` loop has an empty trip count, the dword path is - // switched off by the same bit, and the kernel multiplies whatever was in LDS -- it returns a - // 1.6 relative error rather than raising. Choose the width from whether it actually divides, - // not from the OPT bit alone, so a new tile shape degrades to dword staging instead of breaking. + unsigned ra[APT]; constexpr int WWP = NTILE * BK; // 16-byte weight chunks per buffer - // RAGGED W STAGING, the way OPT bit 32768 already lets the A side be ragged. At BK = 32 the - // buffer is NTILE*32 chunks, which does not divide 512 threads at BN = 128 -- and a plain - // `WWP / NT_` would silently be zero-or-short rather than failing. Round up and predicate the - // last pass; a thread past the end simply does not load and does not store. - constexpr int WPTU = WU ? ((WWP + NT_ - 1) / NT_ > 0 ? (WWP + NT_ - 1) / NT_ : 1) : 1; - constexpr bool WPAD = WU && (WWP % NT_) != 0; + constexpr int WPTU = (WWP + NT_ - 1) / NT_; + constexpr bool WPAD = (WWP % NT_) != 0; u4v8_t rwu[WPTU]; - // OPT BIT 32768: LET THE 128-BIT A STAGING BE RAGGED, the way OPT-less dword staging already is. - // A128 needs (AW/4) % NT_ == 0, and AW/4 = BM*4, so at 512 threads only BM % 128 == 0 qualifies: - // BM = 160 and 192 silently fall back to SIX global_load_b32 + six ds_store_b32 per thread per k - // step instead of two b128, which is ~10 extra instructions per k step and is most of why the - // tall tiles lose at prefill. One predicate on the last pass fixes it. Gated on its own bit so - // that no shape the decode table already picked changes: the tiles where AW/4 < NT_ (BM <= 96 at - // 512 threads, BM <= 80 at 256) keep A128 OFF exactly as before. - constexpr bool A128R = (OPT & 32768) != 0; - constexpr int APT4 = A128R ? ((AW / 4 + NT_ - 1) / NT_) : ((AW / 4) / NT_); - constexpr int WPT4 = WU ? 0 : (WW / 4) / NT_; - constexpr bool A4PAD = A128R && ((AW / 4) % NT_) != 0; - constexpr bool A128 = - (OPT & 8) && APT4 > 0 && (A128R ? (AW / 4) >= NT_ : (AW / 4) % NT_ == 0); - constexpr bool W128 = !WU && (OPT & 16) && WPT4 > 0 && (WW / 4) % NT_ == 0; - u4v8_t ra4[APT4 > 0 ? APT4 : 1], rw4[WPT4 > 0 ? WPT4 : 1]; - u4v8_t rwg[WNOLDS ? 2 : 1][WNOLDS ? TN : 1]; // the weight double buffer, in registers - - // OPT BIT 32: DO NOT STAGE ROWS PAST M. - // The tiled kernel's cost at these batches is proportional to the PADDED row count, not to M and - // not to the weight traffic: on `gate_up_proj` the BM=96 tile costs exactly 96/64 of what the - // BM=64 tile does at the same M, while the weight read is identical. What scales - // with BM is the activation staging -- APT = (BM*BK/4)/threads dwords per thread per k step, - // 2 for BM=64 at 512 threads and 3 for BM=96 -- and the 256-thread variants, which triple it - // again, cost 2-3x. - // - // At M=72 in a BM=96 tile, 24 of every 96 staged rows are `mm = M-1` clamped duplicates whose - // accumulators the store epilogue throws away. A quarter of the staging is for rows that do not - // exist. Skipping the global load AND the LDS store for them leaves stale LDS under those rows, - // which is exactly as harmless as the duplicate was: the WMMA consumes it, and the epilogue - // discards every m >= M. - constexpr bool MSKIP = (OPT & 32) != 0; - // ABL 9 PRICES TAKING THE ACTIVATION OUT OF LDS ENTIRELY. - // The A fragment read is the largest single item in this loop -- the ABL 7 variant shows halving - // its BYTES is worth close to a fifth of the kernel -- and it exists only because A arrives - // row-major: a lane's eight bytes are one row at a fixed k, so sixteen lanes would each need - // their own 8-byte segment and a direct global load would be sixteen-way scattered. LDS is what - // transposes it. But the quantiser writes the activation, so it could write it FRAGMENT-MAJOR -- - // [row tile][k step][lane][8] -- and then the fragment is one coalesced `global_load_b64` per - // (i, u) and there is no A staging, no `ds_store`, no `ds_load` and no A half of the LDS budget - // at all. This variant loads exactly that address, so the instruction mix and the traffic are - // the real thing's; the ANSWER is wrong because the activation in memory is still row-major. - constexpr bool ANOLDS = (ABX == 9); - // OPT BIT 1024: A BARRIER THAT FENCES LDS ONLY. - // `__syncthreads()` is a full-memory fence, and on gfx12 that means the barrier carries a - // `global_inv` -- the ISA shows two of them per scale group here. Everything this loop - // synchronises is in LDS: the staging writes `lds_a`/`lds_w` and the fragment reads read them - // back. The global loads are into REGISTERS and are ordered by their own load counter, not by - // the barrier. So the release/acquire pair only has to cover the `local` address space, which - // drops the cache invalidate and leaves the barrier itself. - // - // IT IS NEUTRAL, though the variant is not inert: `global_inv` really does go 2 -> 0 per scale - // group, traded for two more `s_wait_dscnt`, at an identical 236 instructions. The time - // difference sits inside the run-to-run spread of a control variant that duplicates the baseline, - // so the cache invalidate is free here. The variant stays because it is correct and the - // comparison needs it. - auto ldsbar = [&]() { - if (OPT & 1024) { - __builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "local"); - __builtin_amdgcn_s_barrier(); - __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup", "local"); - } else { - __syncthreads(); - } - }; - // One index, two containers: the dword table the asymmetric path needs and the f16 table the - // symmetric path is the only reader of. Written as a macro rather than a lambda because it is - // read from inside the epilogue's `#pragma unroll` bodies where a capture would be re-formed. -#define R4D_WS8(g_, j_) \ - (SC16 ? (unsigned)((const unsigned short*)Ws)[(unsigned)(((n0 / 16 + wn * TN + (j_)) * nsz + \ - (g_)) * 16 + (lane & 15))] \ - : Ws[(unsigned)(((n0 / 16 + wn * TN + (j_)) * nsz + (g_)) * 16 + (lane & 15))]) - auto issue = [&](int kk, int bufn) { - if constexpr (WNOLDS) { + // Global indices into A are 32-bit: a 64-bit address costs four extra instructions per load. + auto issue = [&](int kk) { + // Sixteen bytes per thread, copied unchanged. A lane owns 16 bytes of a 32-column packed + // block; at BK = 64 `kh` would pick one of two blocks 512 bytes apart. Coalesced across the + // wave. #pragma unroll - for (int j = 0; j < TN; j++) { - const u4v8_t* wp4 = (const u4v8_t*)(Wq + (unsigned)(((n0 / 16 + wn * TN + j) * kpb + - kk / R4D_TILED8_KPB) * 128 + lane * 4)); - rwg[bufn][j] = WNT ? __builtin_nontemporal_load(wp4) : *wp4; - } - } - if (A128 && !ANOLDS) { -#pragma unroll - for (int x = 0; x < APT4; x++) { - const int t = tid + x * NT_, r = t / (BK / 16), c4 = t % (BK / 16); - if (A4PAD && t >= AW / 4) continue; - if (MSKIP && m0 + r >= M) continue; - const int mm = m0 + r < M ? m0 + r : M - 1; - ra4[x] = *(const u4v8_t*)(A + (unsigned)(mm * K + kk + c4 * 16)); - } - } - if (W128 && !WNOLDS) { -#pragma unroll - for (int x = 0; x < WPT4; x++) { - const int t = tid + x * NT_, tl = t / 32, off4 = t % 32; - const u4v8_t* wp4 = (const u4v8_t*)(Wq + (unsigned)(((n0 / 16 + tl) * kpb + - kk / R4D_TILED8_KPB) * 128 + off4 * 4)); - rw4[x] = WNT ? __builtin_nontemporal_load(wp4) : *wp4; - } - } - if (WU && !WNOLDS) { - // SIXTEEN BYTES PER THREAD, AND NOTHING HAPPENS TO THEM. A lane owns 16 bytes of a 32-column - // packed block, so BK = 64 is two blocks: `kh` picks which, and the two sit 32*16 = 512 bytes - // apart. Both are coalesced across the wave (32 lanes x 16 B contiguous). -#pragma unroll - for (int x = 0; x < WPTU; x++) { - const int t = tid + x * NT_; - if (WPAD && t >= WWP) continue; - const int tl = t / BK, rem = t % BK, kh = rem / 32, ln = rem % 32; - const u4v8_t* wpu = (const u4v8_t*)Wq + - (size_t)(((n0 / 16 + tl) * kpb + kk / R4D_TILED8_KPB + kh) * 32 + ln); - rwu[x] = WNT ? __builtin_nontemporal_load(wpu) : *wpu; - } + for (int x = 0; x < WPTU; x++) { + const int t = tid + x * NT_; + if (WPAD && t >= WWP) continue; + const int tl = t / BK, rem = t % BK, kh = rem / 32, ln = rem % 32; + rwu[x] = *((const u4v8_t*)Wq + + (size_t)(((n0 / 16 + tl) * kpb + kk / R4D_TILED8_KPB + kh) * 32 + ln)); } #pragma unroll - for (int x = 0; x < APT && !A128 && !ANOLDS; x++) { + for (int x = 0; x < APT; x++) { const int t = tid + x * NT_, r = t / (BK / 4), c = t % (BK / 4); if (APAD && t >= AW) continue; - if (MSKIP && m0 + r >= M) continue; const int mm = m0 + r < M ? m0 + r : M - 1; - ra[x] = (OPT & 2) ? *(const unsigned*)(A + (unsigned)(mm * K + kk + c * 4)) - : *(const unsigned*)(A + (size_t)mm * K + kk + c * 4); - } -#pragma unroll - for (int x = 0; x < WPT && !W128 && !WU && !WNOLDS; x++) { - const int t = tid + x * NT_, tl = t / 128, off = t % 128; - const unsigned* wp = (OPT & 2) - ? Wq + (unsigned)(((n0 / 16 + tl) * kpb + kk / R4D_TILED8_KPB) * 128 + off) - : Wq + ((size_t)((n0 / 16 + tl) * kpb + kk / R4D_TILED8_KPB) * 32) * 4 + off; - rw[x] = WNT ? __builtin_nontemporal_load(wp) : *wp; + ra[x] = *(const unsigned*)(A + (unsigned)(mm * K + kk + c * 4)); } }; auto commit = [&](int buf) { - if (A128 && !ANOLDS) { #pragma unroll - for (int x = 0; x < APT4; x++) { - const int t = tid + x * NT_, r = t / (BK / 16), c4 = t % (BK / 16); - if (A4PAD && t >= AW / 4) continue; - if (MSKIP && m0 + r >= M) continue; - *(u4v8_t*)(lds_a[buf] + ASW(r, c4 * 4)) = ra4[x]; - } - } - if (W128 && !WNOLDS) { -#pragma unroll - for (int x = 0; x < WPT4; x++) *(u4v8_t*)(lds_w[buf] + (tid + x * NT_) * 4) = rw4[x]; - } - if (WU && !WNOLDS) { -#pragma unroll - for (int x = 0; x < WPTU; x++) { - const int t = tid + x * NT_; - if (WPAD && t >= WWP) continue; - const int tl = t / BK, rem = t % BK, kh = rem / 32, ln = rem % 32; - // [tile][lane][u][2] dwords, and the 16 bytes a lane holds are k steps 2*kh and 2*kh+1 -- - // exactly four consecutive dwords at `ln*8 + kh*4`. One `ds_store_b128`, no arithmetic. - *(u4v8_t*)(lds_w[buf] + (size_t)tl * (BK * 4) + ln * (BK / 8) + kh * 4) = rwu[x]; - } + for (int x = 0; x < WPTU; x++) { + const int t = tid + x * NT_; + if (WPAD && t >= WWP) continue; + const int tl = t / BK, rem = t % BK, kh = rem / 32, ln = rem % 32; + // [tile][lane][u][2] dwords: a lane's 16 bytes are k steps 2*kh and 2*kh+1, four + // consecutive dwords at `ln*8 + kh*4`, one ds_store_b128. + *(u4v8_t*)(lds_w[buf] + (size_t)tl * (BK * 4) + ln * (BK / 8) + kh * 4) = rwu[x]; } #pragma unroll - for (int x = 0; x < APT && !A128 && !ANOLDS; x++) { + for (int x = 0; x < APT; x++) { const int t = tid + x * NT_, r = t / (BK / 4), c = t % (BK / 4); if (APAD && t >= AW) continue; - if (MSKIP && m0 + r >= M) continue; lds_a[buf][ASW(r, c)] = ra[x]; } -#pragma unroll - for (int x = 0; x < WPT && !W128 && !WU && !WNOLDS; x++) lds_w[buf][tid + x * NT_] = rw[x]; }; - // Neither staging width can move the buffer if it does not divide the block, and the loops above - // would then silently move nothing. Both paths are compile-time constants, so say so at compile - // time rather than returning a wrong answer. - static_assert(ANOLDS || A128 || APT > 0, "no A staging path tiles this block shape"); - static_assert(WNOLDS || WU || W128 || (WPT > 0 && WW % NT_ == 0), - "no W staging path tiles this block shape"); - // Every variant that reads `lds_w` with its own addressing -- the unpack-at-staging path, the iu4 - // route and the two DCE-proof ablations -- would read a four-dword stub under WNOLDS. None of - // them is a shipping path, so refuse the combination rather than measure a wrong answer. - static_assert(!WNOLDS || (ABL == 0 && !WU && !IU4), - "WNOLDS does not compose with the weight-LDS ablations"); - static_assert(!WU || WPTU > 0, "8-bit W staging does not tile this block shape"); - if constexpr (SCPF2) { -#pragma unroll - for (int j = 0; j < TN; j++) - scn[j] = R4D_WS8(kbeg / GRP, j); - } - issue(kbeg, 0); - commit(0); // a BUFFER index, not a k offset -- the two only coincide at kbeg = 0 - ldsbar(); + issue(0); + commit(0); + __syncthreads(); - // UNROLL THE K LOOP OVER THE GROUP. At BK = 64 and a 128-wide scale group the group boundary is - // a DYNAMIC branch -- `(k0 % GRP) == 0` alternates -- and the epilogue sits inside it, which stops - // the scheduler from interleaving it with the WMMA work on either side. Unrolling by GRP/BK makes - // both conditions compile-time constants per copy. Worth several percent, and it is what brings - // the kernel from a few points over the block-fp8 bar to PARITY. The tell that the dynamic - // branch is there at all: a group-64 build, where GRP == BK makes the conditions constant for - // free, runs the SAME as group 128 despite doing twice the epilogue arithmetic. - for (int kg = kbeg, it = 0; kg < kend; kg += BK * UNR) { + // Unroll the K loop over the group (UNR = GRP/BK) so the group-boundary tests are compile-time per + // copy; a dynamic branch around the epilogue stops the scheduler interleaving it with the WMMA. + // Worth several percent. + for (int kg = 0, it = 0; kg < K; kg += BK * UNR) { #pragma unroll for (int h = 0; h < UNR; h++, it++) { const int k0 = kg + h * BK; const int buf = it & 1; - if ((ABL == 0 || ABL >= 10) && k0 + BK < kend) issue(k0 + BK, buf ^ 1); // loads in flight across the WMMA work below + if (k0 + BK < K) issue(k0 + BK); // loads in flight across the WMMA work below - constexpr int AGRP = ABX == 3 ? GRP * 8 : GRP; // ABL 3 prices the group epilogue at 1/8 - const bool first_half = (k0 % AGRP) == 0; - // THE GROUP SCALE IS A GLOBAL LOAD THAT NOTHING HIDES. Every wave in every workgroup reaches - // the group boundary on the same k0, so when the epilogue loads Ws right where it uses it, all - // of them stall on the same latency at the same moment and there is no other wave to run. That - // is why the epilogue costs about four times what issuing its 5120 VALU would: most of it is - // the wait. Fetch it at the START of the group instead -- one whole 64-k iteration of WMMA - // work, plus the second iteration's, stands between the load and its use. - // Keep the RAW dword. Converting it here consumes the load here, and the compiler puts the - // s_waitcnt in front of the first USE: calling __half2float() at the prefetch site lands the - // wait immediately after the load, ahead of every WMMA -- a prefetch that prefetches nothing. - // Convert at the group close instead. - if ((OPT & 1) && (k0 % GRP) == 0) { - if constexpr (SCPF2) { - // The rotate has to come first: `scn` is the group this iteration will fold with, and the - // load below is for the NEXT one. The group index is clamped rather than branched -- the - // value fetched past the last group is never folded, and a uniform branch here would sit - // on the boundary every wave arrives at together. + const bool first_half = (k0 % GRP) == 0; + // Fetch the group scale at the start of the group, so the waves do not all stall on it at the + // fold; keep the raw bits and convert at the group close. 32-bit index: the table has at most + // (N/16)*(K/GRP)*16 elements. + if ((k0 % GRP) == 0) { #pragma unroll - for (int j = 0; j < TN; j++) scv[j] = scn[j]; - const int gnx = (k0 / GRP + 1 < nsz) ? k0 / GRP + 1 : nsz - 1; -#pragma unroll - for (int j = 0; j < TN; j++) - scn[j] = R4D_WS8(gnx, j); - } else { -#pragma unroll - for (int j = 0; j < TN; j++) - scv[j] = R4D_WS8(k0 / GRP, j); - } + for (int j = 0; j < TN; j++) + scv[j] = (unsigned)((const unsigned short*)Ws)[(unsigned)(((n0 / 16 + wn * TN + j) * nsz + + k0 / GRP) * 16 + (lane & 15))]; } - // The activation row-sums have exactly the scale's problem, and worse: every wave in every - // workgroup hits the group boundary on the same k0, so eight `v4f` loads issued where they are - // used stall the whole machine at once. An ablation that keeps the correction's arithmetic and - // drops only the loads shows the loads cost about twice what the FMAs do. - // OPT bit 6 issues them a full 64-k iteration ahead, at the cost of TM*8 live VGPRs. - if (ASYM && (OPT & 64) && (k0 % GRP) == 0) { - const int Mpadp = ((M + 15) / 16) * 16; -#pragma unroll - for (int i = 0; i < TM; i++) { - int rb = m0 + (wm * TM + i) * 16 + 8 * (lane >> 4); - rb = rb < Mpadp - 8 ? rb : Mpadp - 8; - const v4f8_t* pv = (const v4f8_t*)(Asum + (size_t)(k0 / GRP) * Mpadp + rb); - const v4f8_t v0 = pv[0], v1 = pv[1]; -#pragma unroll - for (int e = 0; e < 4; e++) { asp[i][e] = v0[e]; asp[i][e + 4] = v1[e]; } - } - } - if (IU4) { -#pragma unroll - for (int c = 0; c < BK / 32; c++) { - // ONE PLANE AT A TIME. Holding ah[TM] and al[TM] together costs TM more v2i of live range - // on a kernel that already pays 8*TM*TN for the second accumulator: 115 VGPRs against the - // iu8 path's 85, straight through the 96-VGPR step and from 16 waves per SIMD down to 12. - // Doing the high plane's WMMAs and then the low plane's reuses the registers; the cost is - // re-reading the weight fragment once per plane, and the - // DCE-proof ablation already showed the W LDS read is free once the unpack is gone. -#pragma unroll - for (int P = 0; P < 2; P++) { - v2i8_t af4[TM]; -#pragma unroll - for (int i = 0; i < TM; i++) { - const int row = (wm * TM + i) * 16 + (lane & 15); - // dword offset in the row: c*8 for the K=32 chunk, +4 for the low plane, +2 per half - const unsigned* pa4 = lds_a[buf] + ASW(row, c * 8 + P * 4 + 2 * (lane >> 4)); - af4[i][0] = (int)pa4[0]; - af4[i][1] = (int)pa4[1]; - } -#pragma unroll - for (int j = 0; j < TN; j++) { - const u4v8_t wv = *(const u4v8_t*)(lds_w[buf] + (size_t)(wn * TN + j) * 128 + lane * 4); - v2i8_t bq; // two k steps = one K=32 iu4 B fragment - bq[0] = (int)wv[2 * c]; - bq[1] = (int)wv[2 * c + 1]; -#pragma unroll - for (int i = 0; i < TM; i++) { - const bool f = (first_half && c == 0); - // P = 0 is the signed high half, P = 1 the unsigned low half. - if (P == 0) - g2[j][i] = __builtin_amdgcn_wmma_i32_16x16x32_iu4_w32_gfx12( - true, af4[i], true, bq, f ? (v8i8_t)(0) : g2[j][i], false); - else - g[j][i] = __builtin_amdgcn_wmma_i32_16x16x32_iu4_w32_gfx12( - false, af4[i], true, bq, f ? (v8i8_t)(0) : g[j][i], false); - } - } - } - } - } else { - // OPT BIT 16384: PREFETCH THE A FRAGMENTS ONE K STEP AHEAD. - // The ISA of the shipped tile issues a k step's `ds_load_2addr_stride64_b64` and then waits on - // it one instruction later -- `s_wait_dscnt 0x1` sits between the load and the first WMMA that - // consumes it, and `s_wait_dscnt 0x0` sits between the second and third WMMA of every triple. - // The loads have essentially no cover. Rotating a second register set moves each load a whole - // WMMA triple plus an unpack earlier, at the cost of TM*2 VGPRs. - v2i8_t afp[TM]; - auto aload = [&](int uu, v2i8_t* dst) { -#pragma unroll - for (int i = 0; i < TM; i++) { - const int row = (wm * TM + i) * 16 + (lane & 15); - if (ANOLDS) { - const int rt0 = m0 / 16 + wm * TM + i, rtm = (M - 1) / 16; - const int rt = rt0 < rtm ? rt0 : rtm; - dst[i] = *(const v2i8_t*)(A + ((size_t)rt * (K / 16) + (k0 / 16 + uu)) * 256 + lane * 8); - continue; - } - const unsigned* pa = lds_a[buf] + ASW(row, uu * 4 + 2 * (lane >> 4)); - dst[i][0] = (int)pa[0]; - dst[i][1] = (ABX == 7) ? (int)pa[0] : (int)pa[1]; - } - }; - if (OPT & 16384) aload(0, afp); #pragma unroll for (int u = 0; u < BK / 16; u++) { v2i8_t af[TM]; - if (OPT & 16384) { -#pragma unroll - for (int i = 0; i < TM; i++) af[i] = afp[i]; - if (u + 1 < BK / 16) aload(u + 1, afp); - } else #pragma unroll for (int i = 0; i < TM; i++) { const int row = (wm * TM + i) * 16 + (lane & 15); - if (ANOLDS) { - // [row tile][k step][lane][8 bytes]: lane-contiguous, so one coalesced 8-byte load per - // (i, u). Clamped to the last real row tile only because the CURRENT artifact is not - // padded to a multiple of 16 rows; a real one would be, and the clamp would not exist. - const int rt0 = m0 / 16 + wm * TM + i, rtm = (M - 1) / 16; - const int rt = rt0 < rtm ? rt0 : rtm; - const v2i8_t* pg = - (const v2i8_t*)(A + ((size_t)rt * (K / 16) + (k0 / 16 + u)) * 256 + lane * 8); - af[i] = *pg; - continue; - } const unsigned* pa = lds_a[buf] + ASW(row, u * 4 + 2 * (lane >> 4)); - // ABL 7 prices the SECOND activation LDS dword only -- halving the A read while keeping - // the staging path live, which is what a wider A permutation would buy. A version that - // dropped both made lds_a dead and deleted the staging, which is not a measurement. af[i][0] = (int)pa[0]; - af[i][1] = (ABX == 7) ? (int)pa[0] : (int)pa[1]; + af[i][1] = (int)pa[1]; } - if (ABX == 8) { - // THE INSTRUCTION MIX HAS TO MATCH THE REAL KERNEL OR THIS PRICES NOTHING. - // Doing both iu4 calls on even u only leaves the odd u's `af` dead -- the compiler deletes - // those `ds_load_b64` and the variant then does HALF the activation reads the real thing - // would. For K=64 the real kernel loads A_hi and A_lo for two K=32 chunks: four - // `ds_load_b64` per (i, BK), exactly what the iu8 path loads. So run every u and do ONE - // iu4 per (i, j, u), alternating the accumulator -- four A loads, four matrix instructions, - // one b128 of B, no dequant. -#pragma unroll - for (int j = 0; j < TN; j++) { - const u4v8_t wv4 = *(const u4v8_t*)(lds_w[buf] + (size_t)(wn * TN + j) * 128 + lane * 4); - v2i8_t bq; - bq[0] = (int)wv4[u & ~1]; - bq[1] = (int)wv4[(u & ~1) + 1]; -#pragma unroll - for (int i = 0; i < TM; i++) { - // The signedness argument must be a literal, so the two halves are two call sites - // rather than one with a computed flag. - const bool f = (first_half && u < 2); - if (u & 1) - g2[j][i] = __builtin_amdgcn_wmma_i32_16x16x32_iu4_w32_gfx12( - false, af[i], true, bq, f ? (v8i8_t)(0) : g2[j][i], false); - else - g[j][i] = __builtin_amdgcn_wmma_i32_16x16x32_iu4_w32_gfx12( - true, af[i], true, bq, f ? (v8i8_t)(0) : g[j][i], false); - } - } - } else #pragma unroll for (int j = 0; j < TN; j++) { - // ABL 5 prices the UNPACK: same LDS read, no dequant VALU. ABL 6 prices the weight LDS - // read as well. Both compute wrong answers by construction; they exist to say what the gap - // between this kernel's rate and the 407 TOPS matrix ceiling is made of. - u4v8_t wv; - if constexpr (WNOLDS) - wv = rwg[buf][j]; - else - wv = (WU || ABX == 6) - ? (u4v8_t)(0x21212121u) - : *(const u4v8_t*)(lds_w[buf] + (size_t)(wn * TN + j) * 128 + lane * 4); - v2i8_t bf; - if (WU) bf = *(const v2i8_t*)(lds_w[buf] + (size_t)(wn * TN + j) * (BK * 4) - + lane * (BK / 8) + u * 2); - else - // ABL 5 KEEPS THE DATA DEPENDENCY, and it has to. Assigning constants here would make the - // LDS read dead and let the compiler delete the whole weight staging path, which prices - // something else entirely. Forwarding the raw dword prices the three unpack instructions - // and nothing else: same load, same live range, no masks and no shift. - if (ABX == 5) { bf[0] = (int)wv[u]; bf[1] = (int)wv[u]; } - else if (ABX == 6) { bf[0] = 0x10101010; bf[1] = 0x20202020; } - else bf = t8dequant8(wv[u]); + const v2i8_t bf = *(const v2i8_t*)(lds_w[buf] + (size_t)(wn * TN + j) * (BK * 4) + + lane * (BK / 8) + u * 2); #pragma unroll for (int i = 0; i < TM; i++) g[j][i] = (first_half && u == 0) - ? t8mmai(af[i], bf, (v8i8_t)(BIAS == 2 ? 0x4B400000 : 0)) - : t8mmai(af[i], bf, g[j][i]); - } - } - } - - // OPT BIT 2048: SCHEDULE THE K-BLOCK BY HAND. - // Left alone, LLVM interleaves the fragment reads with the matrix work and drains LDS between - // them -- the ISA reads `WW d W RR d WW d W RR`, an `s_wait_dscnt` inside the WMMA run. The - // same pathology appears in the R4D attention kernel and the same fix applies: name the - // pipeline, DS reads then unpack then matrix, and let the staging fill the gaps. Counts are - // per k-block and are upper bounds -- an unmatched instruction is simply scheduled freely, and - // the A reads in particular collapse into `ds_load_2addr_stride64_b64` pairs, so asking for - // more DS reads than exist is harmless. - if (OPT & 2048) { - constexpr int NW = TM * TN * (BK / 16); // matrix instructions - constexpr int NR = TM * (BK / 16) + TN; // A fragments + the weight b128 - constexpr int NV = 3 * TN * (BK / 16); // the unpack - if (OPT & 4096) { // finer: one stage per k step -#pragma unroll - for (int q = 0; q < BK / 16; q++) { - __builtin_amdgcn_sched_group_barrier(0x100, NR / (BK / 16) + 1, 0); - __builtin_amdgcn_sched_group_barrier(0x002, NV / (BK / 16), 0); - __builtin_amdgcn_sched_group_barrier(0x008, NW / (BK / 16), 0); - } - } else { // coarse: the whole k-block in three stages - __builtin_amdgcn_sched_group_barrier(0x100, NR, 0); - __builtin_amdgcn_sched_group_barrier(0x002, NV, 0); - __builtin_amdgcn_sched_group_barrier(0x008, NW, 0); + ? __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12( + true, af[i], true, bf, (v8i8_t)(0x4B400000), false) + : __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12( + true, af[i], true, bf, g[j][i], false); } } - if ((k0 + BK) % AGRP == 0) { // the group closed: fold it into the float acc - if (TWOACC) { - // The hi/lo combine belongs at the GROUP close, not every k step -- both halves accumulate - // in int32 across the whole group and only the float fold needs them summed. Doing it per - // k step costs 2x at GRP=128/BK=64. One `v_lshl_add_u32` per element per group. -#pragma unroll - for (int j = 0; j < TN; j++) -#pragma unroll - for (int i = 0; i < TM; i++) -#pragma unroll - for (int e = 0; e < 8; e++) g[j][i][e] += g2[j][i][e] << 4; - } + if ((k0 + BK) % GRP == 0) { // the group closed: fold it into the float acc float sc[TN]; #pragma unroll for (int j = 0; j < TN; j++) - { - // 32-BIT INDEX. With size_t the whole address goes 64-bit and every group pays - // v_ashrrev + v_lshlrev_b64 + two v_add_co per scale; the element count here is at most - // (N/16)*(K/GRP)*16, a few hundred thousand. - const unsigned raw = - ABX == 4 ? 0x3C00u /* ABL 4: no scale LOAD, same arithmetic */ - : (OPT & 1) ? scv[j] : R4D_WS8(k0 / GRP, j); - sc[j] = __half2float(__ushort_as_half((unsigned short)(raw & 0xFFFFu))); - // OPT BIT 8192: STOP THE f16 CONVERSION FOLDING INTO THE FOLD. - // Left alone the compiler contracts `(float)h * x + acc` into `v_fma_mix_f32`, which reads - // the f16 for free -- and is VOP3P, so it can never dual-issue. `v_fmac_f32` IS on the VOPD - // list (`v_dual_fmac_f32 :: v_dual_fmac_f32` assembles for gfx1201), and the fold is - // TM*TN*8 = 24 of the tile's 221 instructions per scale group. One `asm` per group forces - // the convert to materialise and leaves 24 plain FMACs for the VOPD packer. - if (OPT & 8192) asm("" : "+v"(sc[j])); - } - // THE ASYMMETRIC GRID. With the nibble read unsigned the dequantised weight is - // (q - z) * s, so the group contributes s * (sum_k a_k q_k - z * sum_k a_k) and the second - // term needs a per-row per-group sum of the ACTIVATION -- `r4d_quant_act_i8_asum`'s output, - // laid out [G][Mpad] because element e of tile i at this lane is output row - // (m0 + (wm*TM+i)*16 + 8*(lane>>4) + e), so a lane's eight rows are CONTIGUOUS at a fixed - // group and load as two `v4f`. The zero rides in the scale dword's high half as the f16 of - // -(1024 + z), which is exact because f16 has exactly 1024 steps between 1024 and 2048. - // - // It costs ONE extra fma per element and nothing else: symz needs `cvt` then `fma`, asym - // needs `fma` then `fma`, and the magic bias has already deleted the cvt. The loop is nested - // i-outer so only ONE tile's eight asum values are live -- asum[TM][8] at TM=4 is 32 VGPRs - // against a budget of 192 that is already exactly full. - if (BIAS) { + sc[j] = __half2float(__ushort_as_half((unsigned short)(scv[j] & 0xFFFFu))); #pragma unroll - for (int j = 0; j < TN; j++) csum[j] += sc[j]; - } - float z16[TN]; - if (ASYM) { + for (int j = 0; j < TN; j++) csum[j] += sc[j]; #pragma unroll - for (int j = 0; j < TN; j++) { - const unsigned raw = - (OPT & 1) ? scv[j] - : Ws[(unsigned)(((n0 / 16 + wn * TN + j) * nsz + k0 / GRP) * 16 + - (lane & 15))]; - const float nz = __half2float(__ushort_as_half((unsigned short)(raw >> 16))); - z16[j] = 16.f * (-nz - 1024.f); - } - } - const int Mpad = ((M + 15) / 16) * 16; - // ONE TILE AHEAD (OPT bit 7). Written as load-then-use per tile, the four tiles' asum loads - // serialise: each one's latency is fully exposed because the sixteen fmas that could hide it - // come after it, not before. Holding all TM*8 values instead (the skinny kernel's shape) is - // 32 VGPRs on a kernel that has 6 spare and spills 164 bytes. Two v4f sets -- current and - // next -- is 16, and only the first load's latency is left uncovered. -#define R4D_ASUM_LD(ii, a, b) \ - do { \ - int rb_ = m0 + (wm * TM + (ii)) * 16 + 8 * (lane >> 4); \ - rb_ = rb_ < Mpad - 8 ? rb_ : Mpad - 8; \ - const v4f8_t* pv_ = (const v4f8_t*)(Asum + (size_t)(k0 / GRP) * Mpad + rb_); \ - (a) = pv_[0]; \ - (b) = pv_[1]; \ - } while (0) - v4f8_t c0, c1; - if (ASYM && (OPT & 128)) R4D_ASUM_LD(0, c0, c1); -#pragma unroll - for (int i = 0; i < TM; i++) { - constexpr int NE = ABX == 5 ? 1 : 8; /* ABL 5: 1/8 of the arithmetic */ - float as[8]; - if (ASYM) { - if (OPT & 32) { /* prices the fmas without their loads */ -#pragma unroll - for (int e = 0; e < 8; e++) as[e] = 1.f; - } else if (OPT & 64) { -#pragma unroll - for (int e = 0; e < 8; e++) as[e] = asp[i][e]; - } else if (OPT & 128) { - const v4f8_t u0 = c0, u1 = c1; - if (i + 1 < TM) R4D_ASUM_LD(i + 1, c0, c1); // in flight across THIS tile's fmas -#pragma unroll - for (int e = 0; e < 4; e++) { as[e] = u0[e]; as[e + 4] = u1[e]; } - } else { - int rb = m0 + (wm * TM + i) * 16 + 8 * (lane >> 4); - rb = rb < Mpad - 8 ? rb : Mpad - 8; // rows past M are stored away, not read - const v4f8_t* pv = (const v4f8_t*)(Asum + (size_t)(k0 / GRP) * Mpad + rb); - const v4f8_t v0 = pv[0], v1 = pv[1]; -#pragma unroll - for (int e = 0; e < 4; e++) { as[e] = v0[e]; as[e + 4] = v1[e]; } - } - } + for (int i = 0; i < TM; i++) #pragma unroll for (int j = 0; j < TN; j++) #pragma unroll - for (int e = 0; e < NE; e++) { - float v = BIAS == 2 ? __uint_as_float((unsigned)g[j][i][e]) - : BIAS == 1 ? __uint_as_float((unsigned)g[j][i][e] + 0x4B400000u) - : (float)g[j][i][e]; - if (ASYM) v = fmaf(-z16[j], as[e], v); - acc[j][i][e] = fmaf(v, sc[j], acc[j][i][e]); - } - } -#undef R4D_ASUM_LD + for (int e = 0; e < 8; e++) + acc[j][i][e] = fmaf(__uint_as_float((unsigned)g[j][i][e]), sc[j], acc[j][i][e]); } - if ((ABL == 0 || ABL >= 10) && k0 + BK < kend) commit(buf ^ 1); // the wait for those loads lands HERE - if (ABX != 2) ldsbar(); + if (k0 + BK < K) commit(buf ^ 1); // the wait for those loads lands here + __syncthreads(); } } #undef ASW +#undef ASW_M2 - if (BIAS) { #pragma unroll - for (int j = 0; j < TN; j++) { - const float d = -12582912.0f * csum[j]; + for (int j = 0; j < TN; j++) { + const float d = -12582912.0f * csum[j]; #pragma unroll - for (int i = 0; i < TM; i++) + for (int i = 0; i < TM; i++) #pragma unroll - for (int e = 0; e < 8; e++) acc[j][i][e] += d; - } + for (int e = 0; e < 8; e++) acc[j][i][e] += d; } - // ---- the split tail's partial, and its reduction ---- - // - // The partial is the accumulator AFTER the magic-bias correction and BEFORE `Ascale[m]`, because - // the row scale is common to every piece and multiplying it in once at the end is both cheaper - // and exactly what the unsplit path does. Rows past M are never written and never read: at - // M = 72 in a BM = 96 tile that is a quarter of the workspace traffic saved for free. - // - // The counter lives in ONE dword of `lds_a`, not in a `__shared__` of its own: A and W are - // exactly 32 KB together and four more bytes would drop a CU from two workgroups to one. The - // k loop is finished by here, so the buffer is dead. - if (SKT && slot >= 0) { - float* wsp = WSP + (size_t)slot * BM * BN; -#pragma unroll - for (int j = 0; j < TN; j++) -#pragma unroll - for (int i = 0; i < TM; i++) -#pragma unroll - for (int e = 0; e < 8; e++) { - const int nl = (wn * TN + j) * 16 + (lane & 15); - const int ml = (wm * TM + i) * 16 + 8 * (lane >> 4) + e; - if (m0 + ml < M) wsp[(size_t)ml * BN + nl] = acc[j][i][e]; - } - // THE FENCE HAS TO BE ON EVERY THREAD, not just the one that bumps the counter. A fence - // orders the stores of the thread that executes it; `__syncthreads()` is a workgroup-scope - // release and says nothing about when the other 511 threads' stores become visible to another - // CU. With the fence on thread 0 alone this kernel returns a DIFFERENT wrong answer on every - // call -- the reducer reads whatever happens to have drained. - __threadfence(); - __syncthreads(); - const int cidx = (int)blockIdx.y * nrag + (tilex - nfull); - if (tid == 0) - lds_a[0][0] = __hip_atomic_fetch_add(&CNT[cidx], 1u, __ATOMIC_ACQ_REL, - __HIP_MEMORY_SCOPE_AGENT); - __syncthreads(); - if (lds_a[0][0] != (unsigned)(nspl - 1)) return; - if (tid == 0) CNT[cidx] = 0u; // left clean for the next call on this stream - __threadfence(); // acquire, before reading the other pieces - const float* base = - WSP + (size_t)((int)blockIdx.y * (nrag * nspl) + (tilex - nfull) * nspl) * BM * BN; -#pragma unroll - for (int j = 0; j < TN; j++) -#pragma unroll - for (int i = 0; i < TM; i++) -#pragma unroll - for (int e = 0; e < 8; e++) { - const int nl = (wn * TN + j) * 16 + (lane & 15); - const int ml = (wm * TM + i) * 16 + 8 * (lane >> 4) + e; - const int n = n0 + nl, m = m0 + ml; - if (n < N && m < M) { - float v = 0.f; - // SKT == 2 is a DEBUG variant: reduce only the first piece, so the output is piece 0's - // partial and can be scored against the unsplit kernel run on the K slice [0, K/nspl). - for (int q = 0; q < nspl; q++) - v += base[(size_t)q * BM * BN + (size_t)ml * BN + nl]; - C[(size_t)m * N + n] = (__hip_bfloat16)(v * Ascale[m]); - } - } - return; - } - - // ---- store ---- - // - // FIVE FORMS OF THIS EPILOGUE WERE COMPARED; THE FLAT PREDICATED ONE WINS EVERY TIME. - // - // flat predicated store (this) - // transpose through LDS as bf16 - // transpose through LDS as shuffle-packed dwords - // reorder to hoist Ascale, early-out on m - // reorder to hoist Ascale + the 64-bit m*N, pure predication - // - // The epilogue is NOT bandwidth-bound: folding every address down to 64 rows, so the whole output - // is cache-resident while the instruction count is untouched, takes the same time. That is why - // both transposes lose -- they add instructions to fix a bandwidth problem that does not exist. - // (An ablation that simply deletes the stores makes them look like 40% of the kernel, but it also - // deletes the accumulator's only consumer, so most of that is dead-code elimination; the - // transposed-accumulator note below says what happens when the stores really do get cheaper.) - // - // And reducing the count by hand does not help either. Hoisting the Ascale load and the 64-bit - // row multiply out of the j loop is a real reduction -- 16 of each instead of 64 -- and is slower - // whether the guard is a branch or a predicate. Putting j innermost is what does it: the - // accumulator is acc[j][i][e], so j-innermost strides the register file, and the four stores then - // share one guard instead of being independently predicated. The compiler schedules the flat form - // better than any of the four rewrites. + // The flat predicated store, as in the 4-bit kernel. #pragma unroll for (int j = 0; j < TN; j++) #pragma unroll @@ -991,498 +215,63 @@ __global__ __launch_bounds__(WM * WN * 32, WPE) void r4d_gemm_w8a8_tiled_kernel( const int n = n0 + (wn * TN + j) * 16 + (lane & 15); const int m = m0 + (wm * TM + i) * 16 + 8 * (lane >> 4) + e; if (n < N && m < M) - // NO 1/16 HERE, unlike the 4-bit kernel this was derived from. That factor undoes the - // 16 its unpack puts in the byte's high nibble so a signed 4-bit code reads as 16*q; an - // 8-bit code IS the byte and there is nothing to undo. Leaving it in scales every - // output by exactly 1/16 against the skinny kernel, on every shape. + // No 1/16 here, unlike the 4-bit kernel: an 8-bit code is the byte itself, with no + // high-nibble factor to undo. C[(size_t)m * N + n] = (__hip_bfloat16)(acc[j][i][e] * Ascale[m]); } } - -// THE TRANSPOSED ACCUMULATOR IS NEUTRAL. The code is not here; this note is why not. -// -// gfx12's WMMA output is column-distributed -- lanes index the column, the eight accumulator -// registers index the row -- so with the activation as the A operand a lane owns eight DIFFERENT -// ROWS of one column and each of its 64 outputs is an independent 2-byte store. Swapping the A and -// B operands transposes D (AMD's own RDNA4 WMMA guide documents the swap for exactly this), a lane -// then owns eight CONSECUTIVE COLUMNS of one row, and the epilogue collapses to eight -// `global_store_b128` with `Ascale[m]` loaded twice instead of 64 times. Coalescing is unchanged: -// 128 segments for the wave's 4096 bytes either way. -// -// It is EXACTLY NEUTRAL on `gate_proj`, inside the run-to-run spread, and correct to the same -// 2.32e-3. The store epilogue is not the cost: the ablation that appears to make it 40% of the -// kernel deletes the accumulator's only consumer, so most of that 40% is dead-code elimination. -// The transposed form also costs 193 VGPRs unless it is written carefully, which is a fifth of the -// runtime on its own. - -// THE BLOCK TILE IS NOT FIXED, because 128 x 256 is the wrong shape for a mid-sized M. At -// M = 128-256 that tile gives one or two M-blocks and almost no M-parallelism, and that is exactly -// the band where the kernel falls behind the block-fp8 bar while beating it at M = 64 and matching -// it at M = 4096. The grid therefore comes from the template arguments rather than a constant. -// THE TAIL WORKSPACE is a cached allocation, grown on demand and never freed, ONE A (DEVICE, -// STREAM) -- the w4a8 twin's rule, for its reasons (see the note above SktSlot in -// r4d_gemm_w4a8_tiled.hip): one device's pointer must never reach the other device's kernel, and -// two streams must never share a workspace or its self-resetting counters. -constexpr int kSktStreams = 4; -struct SktSlot { - bool used = false; - hipStream_t key = nullptr; - float* ws = nullptr; - size_t ws_bytes = 0; - unsigned* cnt = nullptr; - size_t cnt_n = 0; -}; - -// The same launch-path allocation the w4a8 twin carries, and the same obstacle to moving it to the -// scratch hook: see the long note above r4d_skt_reserve in r4d_gemm_w4a8_tiled.hip. Bounded at a -// couple of MiB, taken once a (device, stream) in the life of a process, and invisible to the -// engine's VRAM budget -- which is why Engine::start reads the card back and reports what settled. -static void r4d_skt8_reserve(hipStream_t stream, size_t ws_bytes, size_t cnt_n, float** ws, - unsigned** cnt) { - static std::mutex mu; - static SktSlot slot[16][kSktStreams]; - int dev = 0; - if (hipGetDevice(&dev) != hipSuccess || dev < 0 || dev >= 16) - throw std::runtime_error("r4d gemm_w8a8_tiled: no current device for the split-tail workspace"); - std::lock_guard lk(mu); - SktSlot* e = nullptr; - for (SktSlot& x : slot[dev]) - if (x.used && x.key == stream) { e = &x; break; } - if (!e) { - for (SktSlot& x : slot[dev]) - if (!x.used) { e = &x; break; } - if (!e) throw std::runtime_error("r4d gemm_w8a8_tiled: more streams than split-tail workspaces"); - e->used = true; - e->key = stream; - } - if (ws_bytes > e->ws_bytes) { - if (e->ws) (void)hipFree(e->ws); - e->ws = nullptr; - e->ws_bytes = 0; - if (hipMalloc((void**)&e->ws, ws_bytes) != hipSuccess) - throw std::runtime_error("r4d gemm_w8a8_tiled: split-tail workspace alloc failed"); - e->ws_bytes = ws_bytes; - } - if (cnt_n > e->cnt_n) { - if (e->cnt) (void)hipFree(e->cnt); - e->cnt = nullptr; - e->cnt_n = 0; - if (hipMalloc((void**)&e->cnt, cnt_n * sizeof(unsigned)) != hipSuccess) - throw std::runtime_error("r4d gemm_w8a8_tiled: split-tail counter alloc failed"); - (void)hipMemset(e->cnt, 0, cnt_n * sizeof(unsigned)); - e->cnt_n = cnt_n; - } - *ws = e->ws; - *cnt = e->cnt; -} - -// HOW MANY WAYS TO SPLIT THE TAIL. Enough pieces to fill the 32 slots, but the piece boundary has -// to land on a scale group or the group epilogue reads the wrong scale, so `nspl` must divide -// K/GROUP. Capped at 8 because the tail cost turns back up past that point: the pieces become too -// short to hide their own prologue. -static int r4d_skt_split(int nrag, int K) { - const int ngrp = K / R4D_GEMM_W8A8_GROUP; - const int want = 32 / (nrag > 0 ? nrag : 32); - int best = 1; - for (int t = 2; t <= 8 && t <= want; t++) - if (ngrp % t == 0) best = t; - return best; -} - -template -static void r4d_tiled8_launch(long a, long ascale, long wq, long ws, long asum, long c, int M, int K, - int N, long stream) { +template +static void r4d_tiled8_launch(long a, long ascale, long wq, long ws, long c, int M, int K, int N, + long stream) { constexpr int BM = WM * TM * 16, BN = WN * TN * 16; - // AN 8-BIT WEIGHT DOUBLES THE STAGED BYTES, so the widest tiles of the inherited table no longer - // fit 64 KB of LDS: <2,16,4,2> is BN=512, which is 32 KB of weight per buffer and 80 KB in all. - // The check is `if constexpr` rather than a static_assert so that the over-budget shapes are - // never INSTANTIATED -- the compiler would otherwise fail on a kernel nothing is allowed to call - // -- and it throws rather than returning, because a kernel that quietly does not run leaves - // whatever was in C and the caller cannot tell. - constexpr size_t LDSB = - 2 * (size_t)(BM * R4D_W8A8T_BK / 4 + (BN / 16) * R4D_W8A8T_BK * 4) * sizeof(unsigned); - if constexpr (LDSB > 64 * 1024) { - throw std::runtime_error("r4d gemm_w8a8_tiled: this variant needs more than 64 KB of LDS"); - } else { + // An 8-bit weight doubles the staged bytes. + static_assert(2 * (BM * R4D_TILED8_BK / 4 + (BN / 16) * R4D_TILED8_BK * 4) * sizeof(unsigned) <= + 64 * 1024, "this tile needs more than 64 KB of LDS"); if (N % BN) throw std::runtime_error("r4d gemm_w8a8_tiled: N is not a multiple of this variant's block"); - const int tiles = N / BN, mblk = (M + BM - 1) / BM; - int nfull = tiles, nrag = 0, nspl = 1, gx = tiles; - float* skt_ws = nullptr; - unsigned* skt_cnt = nullptr; - if (SKT) { - nrag = tiles & 31; - nfull = tiles - nrag; - nspl = nrag ? r4d_skt_split(nrag, K) : 1; - // A tail worth splitting, and a workspace worth keeping: at decode mblk is 1 and this is a - // couple of MiB. At prefill mblk is large, the tail is a rounding error against the M blocks, - // and the workspace would not be -- so the split is simply off there. - if (nrag == 0 || nspl < 2 || (size_t)mblk * nrag * nspl > 64) { - nfull = tiles; nrag = 0; nspl = 1; - } else { - gx = nfull + nrag * nspl; - r4d_skt8_reserve((hipStream_t)stream, - (size_t)mblk * nrag * nspl * BM * BN * sizeof(float), (size_t)mblk * nrag, - &skt_ws, &skt_cnt); - } - } - dim3 grid(gx, mblk), block(WM * WN * 32); - hipLaunchKernelGGL( - (r4d_gemm_w8a8_tiled_kernel), grid, - block, 0, (hipStream_t)stream, (const signed char*)a, (const float*)ascale, - (const unsigned*)wq, (const unsigned*)ws, (const float*)asum, (__hip_bfloat16*)c, M, K, N, - skt_ws, skt_cnt, nfull, nrag, nspl); - } -} - -static void r4d_gemm_w8a8_tiled_impl(long a, long ascale, long wq, long ws, long asum, long c, - int M, int K, int N, long stream, int variant, bool asym) { - if (N % 256) throw std::runtime_error("r4d gemm_w4a8_tiled: N must be a multiple of 256"); - if (K % R4D_GEMM_W8A8_GROUP) - throw std::runtime_error("r4d gemm_w4a8_tiled: K must be a multiple of the scale group"); - if (M < 1) throw std::runtime_error("r4d gemm_w4a8_tiled: M must be positive"); - // THE UNROLL MUST COVER EXACTLY ONE SCALE GROUP -- no more. GRP/BK makes the group boundary a - // compile-time constant, which is the whole point; going further just doubles live ranges and - // wrecks the register allocation. At group 128, UNR = GRP/BK sits at the fp8 bar, UNR = 1 is - // about a tenth over it, and UNR = 4 is more than twice it; a group-64 build forced to two groups - // a trip is four times it. - // UNRG COUNTS BK STEPS PER SCALE GROUP, NOT PACKED BLOCKS. In the 4-bit kernel those were the - // same number because its packed block was 64 columns, exactly BK. Here a packed block is 32 - // columns -- a lane's 16 bytes -- while the loop still steps BK = 64, so deriving the unroll from - // the block would ask for 4 where the group needs 2, which the note above puts at more than twice - // the fp8 bar. - constexpr int UNRG = R4D_GEMM_W8A8_GROUP / R4D_TILED8_BK > 1 - ? R4D_GEMM_W8A8_GROUP / R4D_TILED8_BK - : 1; - const bool ufull = (K % (UNRG * R4D_TILED8_BK)) == 0; -#define R4D_TILED8_LAUNCH(...) \ - r4d_tiled8_launch<__VA_ARGS__>(a, ascale, wq, ws, asum, c, M, K, N, stream) - // The variant argument selects an alternative tile and exists for the bench; 0 is what ships. - // A variant that lost and has nothing left to say is NOT kept as an instantiation -- each one is - // a kernel to compile. - if (asym) { - switch (variant) { - // EVERY asym instantiation with the magic bias SPILLS -- z16[TN], as[8] and csum[TN] land on - // top of 128 accumulator registers -- so the asym variants drop it. BIAS=0 at <2,8,4,2> is - // 186 VGPRs with no scratch; BIAS=2 is 192 with 24 bytes. - case 1: R4D_TILED8_LAUNCH(2, 8, 4, 2, 0, 0, 51, 8, 1, 1); break; // no asum LOADS - case 2: R4D_TILED8_LAUNCH(2, 8, 4, 2, 2, 0, 19, 8, 1, 1); break; // magic bias - // The unroll is a LOSS on the asymmetric path -- 186 VGPRs plus doubled live ranges -- so the - // asym default keeps UNR=1 where symz takes UNR=2. - case 3: R4D_TILED8_LAUNCH(2, 8, 4, 2, 0, 0, 19, 8, 1, UNRG); break; // unrolled - // Losers, not instantiated: holding all TM*8 asum values (OPT 64) spills 164 bytes and costs - // half again; pipelining them one tile ahead (OPT 128) is neutral; TM=2 is a few percent - // worse. The code for all three is still in the kernel because each is one branch and - // together they document the wall. - default: R4D_TILED8_LAUNCH(2, 8, 4, 2, 0, 0, 19, 8, 1, 1); break; - } - } else { - switch (variant) { - case 1: R4D_TILED8_LAUNCH(4, 4, 2, 4, 0, 0, 0, 8, 0, 1); break; // 4x4 waves, 2x4 tiles, plain cvt - case 2: R4D_TILED8_LAUNCH(2, 8, 4, 2, 2, 0, 19, 8, 0, 1); break; // UNR=1 - case 3: R4D_TILED8_LAUNCH(2, 8, 4, 2, 2, 0, 3, 8, 0, UNRG); break; // no wide W - case 4: R4D_TILED8_LAUNCH(2, 8, 4, 2, 0, 0, 19, 8, 0, UNRG); break; // no bias - case 5: R4D_TILED8_LAUNCH(2, 8, 4, 2, 2, 0, 19, 8, 0, 2 * UNRG); break; // 2x - // BM=64 for the mid-M band. Same 256-wide N, half the M tile, so M=128 is two blocks instead - // of one and M=256 is four. TM*TN drops 8 -> 4, which also halves the accumulator registers. - case 6: R4D_TILED8_LAUNCH(2, 8, 2, 2, 2, 0, 147, 8, 0, UNRG); break; // BM 64, BN 256, 512 thr - case 7: R4D_TILED8_LAUNCH(1, 16, 4, 1, 2, 0, 19, 8, 0, UNRG); break; // BM 64, 1 wave deep - case 8: R4D_TILED8_LAUNCH(2, 4, 2, 4, 2, 0, 19, 8, 0, UNRG); break; // BM 64, 256 thr - case 9: R4D_TILED8_LAUNCH(2, 8, 4, 1, 2, 0, 19, 8, 0, UNRG); break; // BM 128, BN 128 - // BM 96 AND BM 80, FOR THE SPECULATIVE-DECODE BATCH. A serve at eight concurrent requests - // with verify width 9 runs M=72, and 72 is the worst M either kernel has: the skinny one - // needs five row tiles so it walks the weight five times, and BM=64 needs two blocks whose - // second holds 8 of 64 rows. BM=96 covers 72 in ONE block, so the weight is read once and - // nothing is half empty. BM=80 is the tightest fit and the widest tile per wave. - case 10: R4D_TILED8_LAUNCH(2, 8, 3, 2, 2, 0, 147, 8, 0, UNRG); break; // BM 96, BN 256, 512 thr - case 12: R4D_TILED8_LAUNCH(2, 8, 3, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 96, BN 128, 512 thr - // The staging tilings are not free choices: W needs WM | 4*TN and A needs WN | 8*TM, or the - // static_asserts above fire. That leaves WM*TM = 6 as the only route to BM 96, i.e. <2,_,3,_> - // or <1,_,6,_>, and it is why there is no <3,8,2,2>. Dropped: BM 80 in either width, BM 96 - // at 256 threads, BN 512 anywhere, and BM 64 at 1024 threads -- everything that raises A - // dwords-per-thread costs 2-3x. Also dropped: skipping the staging of rows past M - // (OPT bit 32), which is WORSE -- the divergent branch costs more than the duplicate rows it - // saves. - // Cost ablations on the two tiles that win at these batches. Wrong answers by construction. - case 24: R4D_TILED8_LAUNCH(2, 8, 2, 2, 2, 5, 19, 8, 0, UNRG); break; // BM64 no unpack - case 25: R4D_TILED8_LAUNCH(2, 8, 2, 2, 2, 6, 19, 8, 0, UNRG); break; // BM64 no W LDS read - case 26: R4D_TILED8_LAUNCH(2, 8, 2, 2, 2, 7, 19, 8, 0, UNRG); break; // BM64 no A LDS read - case 27: R4D_TILED8_LAUNCH(2, 8, 3, 1, 2, 5, 19, 8, 0, UNRG); break; // BM96 no unpack - case 28: R4D_TILED8_LAUNCH(2, 8, 3, 1, 2, 6, 19, 8, 0, UNRG); break; // BM96 no W LDS read - case 29: R4D_TILED8_LAUNCH(2, 8, 3, 1, 2, 7, 19, 8, 0, UNRG); break; // BM96 no A LDS read - // The same three against the SWIZZLED baseline, which is what ships; the unswizzled variants - // above overstate the A read, because it is 2-way conflicted there. - case 34: R4D_TILED8_LAUNCH(2, 8, 3, 1, 2, 5, 147, 8, 0, UNRG); break; // BM96 swz, no unpack - case 35: R4D_TILED8_LAUNCH(2, 8, 3, 1, 2, 6, 147, 8, 0, UNRG); break; // BM96 swz, no W lds - case 36: R4D_TILED8_LAUNCH(2, 8, 3, 1, 2, 7, 147, 8, 0, UNRG); break; // BM96 swz, half A lds - case 37: R4D_TILED8_LAUNCH(2, 8, 2, 2, 2, 5, 147, 8, 0, UNRG); break; // BM64 swz, no unpack - case 38: R4D_TILED8_LAUNCH(2, 8, 2, 2, 2, 7, 147, 8, 0, UNRG); break; // BM64 swz, half A lds - // OPT bit 256: unpack the weight once at staging. 147|256 = 403. - case 40: R4D_TILED8_LAUNCH(2, 8, 3, 1, 2, 0, 403, 8, 0, UNRG); break; // BM96 BN128 swz + WU - case 41: R4D_TILED8_LAUNCH(2, 8, 2, 2, 2, 0, 403, 8, 0, UNRG); break; // BM64 BN256 swz + WU - case 42: R4D_TILED8_LAUNCH(2, 8, 3, 2, 2, 0, 403, 8, 0, UNRG); break; // BM96 BN256 swz + WU - case 43: R4D_TILED8_LAUNCH(2, 8, 4, 2, 2, 0, 403, 8, 0, UNRG); break; // BM128 BN256 swz + WU - // TALLER ROW TILES AT BN=128, so that M = 97..256 still reads the weight exactly ONCE. - // A second M-block doubles the weight traffic, and this kernel is weight-bandwidth-bound at - // decode M; BM=64 with two blocks reads 2x45 MiB at M=128 where BM=192 reads 45. - case 56: R4D_TILED8_LAUNCH(2, 8, 6, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 192, BN 128, 512 thr - case 57: R4D_TILED8_LAUNCH(2, 8, 5, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 160, BN 128, 512 thr - case 58: R4D_TILED8_LAUNCH(2, 8, 8, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 256, BN 128, 512 thr - case 59: R4D_TILED8_LAUNCH(2, 8, 4, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 128, BN 128, 512 thr - // SAME BLOCK TILE, DIFFERENT WAVE SPLIT. Per WMMA the loop pays 3/TM unpack VALU and 1/TN - // activation `ds_load_b64`, so BM 96 x BN 128 costs 2.0 as <2,8,3,1> and 1.5 either as - // <2,4,3,2> or as <1,8,6,1> -- at half the waves per block. - case 52: R4D_TILED8_LAUNCH(2, 4, 3, 2, 2, 0, 147, 8, 0, UNRG); break; // BM 96, BN 128, 256 thr - case 53: R4D_TILED8_LAUNCH(1, 8, 6, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 96, BN 128, 256 thr - // OPT bit 1024: the LDS-only barrier (147|1024 = 1171). - case 60: R4D_TILED8_LAUNCH(2, 8, 3, 1, 2, 0, 1171, 8, 0, UNRG); break; // BM 96, BN 128 - case 61: R4D_TILED8_LAUNCH(2, 8, 2, 2, 2, 0, 1171, 8, 0, UNRG); break; // BM 64, BN 256 - case 62: R4D_TILED8_LAUNCH(2, 8, 3, 2, 2, 0, 1171, 8, 0, UNRG); break; // BM 96, BN 256 - case 63: R4D_TILED8_LAUNCH(2, 8, 4, 2, 2, 0, 1171, 8, 0, UNRG); break; // BM 128, BN 256 - case 64: R4D_TILED8_LAUNCH(2, 8, 5, 1, 2, 0, 1171, 8, 0, UNRG); break; // BM 160, BN 128 - // OPT bit 2048 = hand-scheduled k-block (147|2048 = 2195); |4096 = the finer variant (6291). - case 70: R4D_TILED8_LAUNCH(2, 8, 3, 1, 2, 0, 2195, 8, 0, UNRG); break; // BM 96, BN 128 sched - case 71: R4D_TILED8_LAUNCH(2, 8, 3, 1, 2, 0, 6291, 8, 0, UNRG); break; // BM 96, BN 128 sched/fine - case 72: R4D_TILED8_LAUNCH(2, 8, 2, 2, 2, 0, 2195, 8, 0, UNRG); break; // BM 64, BN 256 sched - case 73: R4D_TILED8_LAUNCH(2, 8, 3, 2, 2, 0, 2195, 8, 0, UNRG); break; // BM 96, BN 256 sched - case 74: R4D_TILED8_LAUNCH(2, 8, 4, 2, 2, 0, 2195, 8, 0, UNRG); break; // BM 128, BN 256 sched - case 75: R4D_TILED8_LAUNCH(2, 8, 4, 2, 2, 0, 6291, 8, 0, UNRG); break; // BM 128, BN 256 sched/fine - // ABL 9: the A fragment straight from global in a fragment-major layout, no A LDS at all. - case 46: R4D_TILED8_LAUNCH(2, 8, 3, 1, 2, 9, 147, 8, 0, UNRG); break; // BM96 BN128 abl:A global - case 47: R4D_TILED8_LAUNCH(2, 8, 2, 2, 2, 9, 147, 8, 0, UNRG); break; // BM64 BN256 abl:A global - case 48: R4D_TILED8_LAUNCH(2, 8, 3, 2, 2, 9, 147, 8, 0, UNRG); break; // BM96 BN256 abl:A global - case 49: R4D_TILED8_LAUNCH(2, 8, 4, 2, 2, 9, 147, 8, 0, UNRG); break; // BM128 BN256 abl:A global - case 44: R4D_TILED8_LAUNCH(2, 8, 3, 1, 2, 8, 147, 8, 0, UNRG); break; // BM96 BN128 swz, iu4 abl - case 45: R4D_TILED8_LAUNCH(2, 8, 2, 2, 2, 8, 147, 8, 0, UNRG); break; // BM64 BN256 swz, iu4 abl - // The iu4 path (147|512 = 659, BIAS 0), and its like-for-like iu8 twin. Rejected on the - // arithmetic above; kept as one pair so the result is reproducible. Takes the i4x2 - // activation (`w4a8pack.quant_act_i4x2`), NOT the int8 one -- same bytes, two 4-bit planes. - case 50: R4D_TILED8_LAUNCH(2, 8, 3, 2, 0, 0, 659, 8, 0, UNRG); break; // BM 96, BN 256, iu4 - case 51: R4D_TILED8_LAUNCH(2, 8, 3, 2, 0, 0, 147, 8, 0, UNRG); break; // the same tile on iu8 - // THE BALANCED TAIL (SKT = 1). Same tiles, same inner loop; the only difference is that the - // `tiles mod 32` blocks the grid would otherwise run alone in a last round are split along K - // and reduced through a workspace. One instantiation per tile the dispatch table actually - // picks at a decode M. - case 90: R4D_TILED8_LAUNCH(2, 8, 3, 1, 2, 0, 147, 8, 0, UNRG, 1); break; // BM 96, BN 128 - case 91: R4D_TILED8_LAUNCH(2, 8, 3, 2, 2, 0, 147, 8, 0, UNRG, 1); break; // BM 96, BN 256 - // The inner loop, from the ISA. - // 8192 = the f32 fold (VOPD-eligible FMAC), 16384 = the A-fragment prefetch, 147|... = both. - case 110: R4D_TILED8_LAUNCH(2, 8, 3, 1, 2, 0, 147 | 8192, 8, 0, UNRG); break; - case 111: R4D_TILED8_LAUNCH(2, 8, 3, 1, 2, 0, 147 | 16384, 8, 0, UNRG); break; - case 112: R4D_TILED8_LAUNCH(2, 8, 3, 1, 2, 0, 147 | 8192 | 16384, 8, 0, UNRG); break; - // BM = 80 IS THE SMALLEST TILE THAT COVERS M = 72. The shipped BM = 96 tile does a sixth of - // its WMMA, its fold and its A reads on m-tile 5, which is entirely past M at eight - // sequences. `WM*TM=5` is prime, so one wave deep in M is the only split: TM=5 also drops - // the per-WMMA unpack from 3/TM = 1.0 to 0.6. 512 threads cannot stage BM = 80: AW = 1280 - // dwords and 1280 % 512 != 0, so the only legal width is 256, which triples the staging per - // thread. - case 114: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 80, BN 128, 256 thr - case 116: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 8192 | 16384, 8, 0, UNRG); break; - case 117: R4D_TILED8_LAUNCH(2, 4, 3, 2, 2, 0, 147 | 8192 | 16384, 8, 0, UNRG); break; // BM96 BN256 256thr - case 118: R4D_TILED8_LAUNCH(1, 8, 6, 1, 2, 0, 147 | 8192 | 16384, 8, 0, UNRG); break; // BM96 BN128 256thr - case 119: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 8192, 8, 0, UNRG); break; // BM 80, BN 128, f32 fold - case 120: R4D_TILED8_LAUNCH(1, 8, 5, 2, 2, 0, 147, 8, 0, UNRG); break; // BM 80, BN 256, 256 thr - case 121: R4D_TILED8_LAUNCH(1, 4, 5, 2, 2, 0, 147, 8, 0, UNRG); break; // BM 80, BN 128, 128 thr - case 122: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 0, 147, 4, 0, UNRG); break; // BM 80, BN 128, WPE 4 - case 123: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 16384, 8, 0, UNRG); break; // BM 80, A prefetch - case 124: R4D_TILED8_LAUNCH(1, 8, 4, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 64, BN 128, 256 thr - case 125: R4D_TILED8_LAUNCH(1, 8, 7, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 112, BN 128, 256 thr - case 126: R4D_TILED8_LAUNCH(1, 8, 10, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 160, BN 128, 256 thr - // THE BM FAMILY. 512 threads need BM % 32 == 0, which is why the shipped ladder skips 80 and - // 112; at 256 threads `<1, 8, TM, 1>` gives BM = 16*TM for every TM, so the block can be the - // SMALLEST multiple of 16 that covers M instead of the nearest multiple of 32. - case 127: R4D_TILED8_LAUNCH(1, 8, 1, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 16 - case 128: R4D_TILED8_LAUNCH(1, 8, 2, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 32 - // OPT bit 65536 = non-temporal weight load, on the three tiles a decode step picks. - case 300: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 65536, 8, 0, UNRG); break; // 114 + wnt - case 301: R4D_TILED8_LAUNCH(1, 8, 2, 1, 2, 0, 147 | 65536, 8, 0, UNRG); break; // 128 + wnt - case 302: R4D_TILED8_LAUNCH(1, 8, 3, 1, 2, 0, 147 | 65536, 8, 0, UNRG); break; // 129 + wnt - case 303: R4D_TILED8_LAUNCH(1, 8, 4, 1, 2, 0, 147 | 65536, 4, 0, UNRG); break; // 130 + wnt - case 304: R4D_TILED8_LAUNCH(1, 8, 6, 1, 2, 0, 147 | 65536, 4, 0, UNRG); break; // 131 + wnt - case 305: R4D_TILED8_LAUNCH(2, 8, 5, 1, 2, 0, 147 | 65536, 8, 0, UNRG); break; // 57 + wnt - case 306: R4D_TILED8_LAUNCH(2, 8, 3, 1, 2, 0, 147 | 65536, 8, 0, UNRG); break; // BM96 512thr wnt - // BN=256 HALVES THE COLUMN BLOCKS AND SO THE ACTIVATION RE-READ, which is the term that - // scales with M (see OPT bit 65536 above). These are 62/63/117 with the hint. - case 307: R4D_TILED8_LAUNCH(2, 8, 3, 2, 2, 0, 1171 | 65536, 8, 0, UNRG); break; // BM96 BN256 - case 308: R4D_TILED8_LAUNCH(2, 8, 4, 2, 2, 0, 1171 | 65536, 8, 0, UNRG); break; // BM128 BN256 - case 309: R4D_TILED8_LAUNCH(2, 4, 3, 2, 2, 0, 147 | 8192 | 16384 | 65536, 8, 0, UNRG); break; - case 310: R4D_TILED8_LAUNCH(1, 8, 2, 2, 2, 0, 147 | 65536, 8, 0, UNRG); break; // BM32 BN256 - case 311: R4D_TILED8_LAUNCH(1, 8, 2, 2, 2, 0, 147, 8, 0, UNRG); break; // BM32 BN256 no hint - // The shipped tiles stage the ACTIVATION a dword at a time -- BM=80 needs - // AW/4 = 320 dwords over 256 threads, which A128 refuses and A128R allows -- and stage the - // WEIGHT through LDS for a sharing that WM=1 does not have. 320-329 cross the three fixes. - case 320: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 8 | 32768 | 65536, 8, 0, UNRG); break; - case 321: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 32 | 65536, 8, 0, UNRG); break; - case 322: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 8 | 32 | 32768 | 65536, 8, 0, UNRG); break; - case 323: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 65536 | 131072, 8, 0, UNRG); break; - case 324: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 8 | 32768 | 65536 | 131072, 8, 0, UNRG); break; - case 325: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 8 | 32 | 32768 | 65536 | 131072, 8, 0, UNRG); break; - case 326: R4D_TILED8_LAUNCH(1, 8, 2, 1, 2, 0, 147 | 65536 | 131072, 8, 0, UNRG); break; - case 327: R4D_TILED8_LAUNCH(1, 8, 4, 1, 2, 0, 147 | 8 | 65536, 8, 0, UNRG); break; - case 328: R4D_TILED8_LAUNCH(1, 8, 4, 1, 2, 0, 147 | 8 | 65536 | 131072, 8, 0, UNRG); break; - case 329: R4D_TILED8_LAUNCH(1, 8, 3, 1, 2, 0, 147 | 65536 | 131072, 8, 0, UNRG); break; - // THE COST BREAKDOWN OF THE TILES A DECODE STEP ACTUALLY PICKS. The ablations above are - // taken at BM=96/M=72, which is a prefill shape; 330-341 repeat the same variants on <1,8,5> - // and <1,8,2> at the shipped OPT. The 3xx variants compute wrong answers by construction -- - // they are timings, not results. - case 330: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 10, 147 | 65536, 8, 0, UNRG); break; // no unpack - case 331: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 11, 147 | 65536, 8, 0, UNRG); break; // + no W LDS read - case 332: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 12, 147 | 65536, 8, 0, UNRG); break; // A read halved - case 333: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 15, 147 | 65536, 8, 0, UNRG); break; // A from global - case 334: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 13, 147 | 65536, 8, 0, UNRG); break; // epilogue /8 - case 335: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 14, 147 | 65536, 8, 0, UNRG); break; // no scale load - case 336: R4D_TILED8_LAUNCH(1, 8, 2, 1, 2, 12, 147 | 65536, 8, 0, UNRG); break; // BM32 A read halved - case 337: R4D_TILED8_LAUNCH(1, 8, 2, 1, 2, 15, 147 | 65536, 8, 0, UNRG); break; // BM32 A from global - case 338: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 1024 | 65536, 8, 0, UNRG); break; - case 339: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 16384 | 65536, 8, 0, UNRG); break; - case 340: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 2048 | 65536, 8, 0, UNRG); break; - case 341: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 8192 | 65536, 8, 0, UNRG); break; - case 342: R4D_TILED8_LAUNCH(1, 8, 2, 1, 2, 0, 147 | 16384 | 65536 | 131072, 8, 0, UNRG); break; - case 343: R4D_TILED8_LAUNCH(1, 8, 2, 1, 2, 0, 147 | 2048 | 65536 | 131072, 8, 0, UNRG); break; - case 344: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 16, 147 | 65536, 8, 0, UNRG); break; // no barrier - case 345: R4D_TILED8_LAUNCH(1, 8, 2, 1, 2, 16, 147 | 65536, 8, 0, UNRG); break; // BM32 no barrier - case 346: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 262144 | 65536, 8, 0, UNRG); break; - case 347: R4D_TILED8_LAUNCH(1, 8, 2, 1, 2, 0, 147 | 262144 | 65536 | 131072, 8, 0, UNRG); break; - case 348: R4D_TILED8_LAUNCH(1, 8, 2, 1, 2, 0, 147 | 262144 | 65536, 8, 0, UNRG); break; - case 349: R4D_TILED8_LAUNCH(1, 8, 2, 1, 2, 14, 147 | 65536, 8, 0, UNRG); break; // BM32 no scale - case 350: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 524288 | 65536, 8, 0, UNRG); break; - case 351: R4D_TILED8_LAUNCH(1, 8, 2, 1, 2, 0, 147 | 524288 | 65536 | 131072, 8, 0, UNRG); break; - case 352: R4D_TILED8_LAUNCH(1, 8, 2, 1, 2, 0, 147 | 524288 | 65536, 8, 0, UNRG); break; - case 129: R4D_TILED8_LAUNCH(1, 8, 3, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 48 - case 130: R4D_TILED8_LAUNCH(1, 8, 4, 1, 2, 0, 147, 4, 0, UNRG); break; // BM 64, WPE 4 - case 131: R4D_TILED8_LAUNCH(1, 8, 6, 1, 2, 0, 147, 4, 0, UNRG); break; // BM 96, WPE 4 - case 132: R4D_TILED8_LAUNCH(1, 8, 7, 1, 2, 0, 147, 4, 0, UNRG); break; // BM 112, WPE 4 - case 133: R4D_TILED8_LAUNCH(1, 8, 9, 1, 2, 0, 147, 4, 0, UNRG); break; // BM 144, WPE 4 - case 134: R4D_TILED8_LAUNCH(1, 8, 3, 1, 2, 0, 147, 4, 0, UNRG); break; // BM 48, WPE 4 - case 135: R4D_TILED8_LAUNCH(1, 8, 2, 1, 2, 0, 147, 4, 0, UNRG); break; // BM 32, WPE 4 - // The same odd BM at 512 threads, which the ragged staging allows. BN is forced to 256 - // there: WM*WN = 16 and WM*TM = 5 leaves WM = 1, so WN = 16. - case 136: R4D_TILED8_LAUNCH(1, 16, 5, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 80, BN 256, 512 thr - case 137: R4D_TILED8_LAUNCH(1, 16, 5, 1, 2, 0, 147, 4, 0, UNRG); break; // BM 80, BN 256, WPE 4 - case 138: R4D_TILED8_LAUNCH(1, 16, 3, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 48, BN 256, 512 thr - case 139: R4D_TILED8_LAUNCH(1, 16, 7, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 112, BN 256, 512 thr - // TM = 5 changes the balance the scheduling variants above are aimed at: the loop is 6.30 - // instructions per WMMA instead of 9.21, and five matrix instructions per k step cover the - // LDS reads that three do not. - case 140: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 2048, 8, 0, UNRG); break; // BM 80 + sched - case 141: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 6144, 8, 0, UNRG); break; // BM 80 + sched/fine - case 142: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 1024, 8, 0, UNRG); break; // BM 80 + LDS-only barrier - // NARROW N: `out_proj`/`down_proj` are N = 5120, which is 40 tiles at BN = 128 -- 1.25 rounds - // per M block. BN = 64 doubles the tile count for the same work. - case 143: R4D_TILED8_LAUNCH(1, 4, 5, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 80, BN 64, 128 thr - case 144: R4D_TILED8_LAUNCH(1, 4, 3, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 48, BN 64, 128 thr - case 145: R4D_TILED8_LAUNCH(2, 4, 5, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 160, BN 64, 256 thr - // BM = 144 covers M = 144 in one block, which BM 128 and BM 160 both fail to do well. - case 146: R4D_TILED8_LAUNCH(1, 8, 9, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 144, BN 128, 256 thr - case 147: R4D_TILED8_LAUNCH(1, 16, 9, 1, 2, 0, 147, 8, 0, UNRG); break; // BM 144, BN 256, 512 thr - // OPT sweep on the BM=80 tile. 32 = do not stage rows past M (8 of 80 at M=72), 1024 = the - // LDS-only barrier, 8|16 = 128-bit staging, 64 = the asum prefetch (inert at ASYM=0). - case 150: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 32, 8, 0, UNRG); break; // BM 80 + MSKIP - case 151: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 32 | 1024, 8, 0, UNRG); break; - case 152: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 0, 155, 8, 0, UNRG); break; // BM 80 + A 128-bit - case 153: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 0, 147 & ~16, 8, 0, UNRG); break; // BM 80, dword W staging - case 154: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 256, 8, 0, UNRG); break; // BM 80 + unpack at staging - case 155: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 0, 147, 8, 0, 1); break; // BM 80, UNR 1 - case 156: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 0, 147, 8, 0, 2 * UNRG); break; // BM 80, UNR 4 - case 157: R4D_TILED8_LAUNCH(1, 8, 5, 1, 1, 0, 147, 8, 0, UNRG); break; // BM 80, BIAS 1 - case 158: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 0, 147 | 1024 | 32 | 8192, 8, 0, UNRG); break; - // DCE-PROOF ABLATIONS ON THE BM=80 TILE. Each computes a WRONG answer on purpose and keeps - // the data dependency that would otherwise let the compiler delete the path being priced. - case 160: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 5, 147, 8, 0, UNRG); break; // no unpack - case 161: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 6, 147, 8, 0, UNRG); break; // no unpack, no W LDS read - case 162: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 7, 147, 8, 0, UNRG); break; // half the A LDS read - case 163: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 3, 147, 8, 0, UNRG); break; // group epilogue at 1/8 - case 164: R4D_TILED8_LAUNCH(1, 8, 5, 1, 2, 2, 147, 8, 0, UNRG); break; // no LDS barrier at all - // THE iu4 ROUTE ON THE BM=80 TILE. The DCE-proof ablation puts the unpack at 24.2% here -- - // three instructions per weight dword, sitting between the LDS read and the matrix - // instruction that consumes it. `v_wmma_i32_16x16x32_iu4` eats the packed nibbles, so the - // unpack goes away entirely; what it costs is a SECOND int32 accumulator per output tile, - // and at TM=5 that is 80 int VGPRs on top of 40 float. Takes the i4x2 activation. - // ---------------- PREFILL VARIANTS ---------------- - // At M >= 1024 this kernel is not a weight stream: gate_up_proj is 730 GFLOP against 44.6 MB - // of weight, so the answer is the matrix pipe. A `v_wmma_i32_16x16x16_iu8` occupies its SIMD - // for 8 cycles (NOT the 16 that f16/bf16 take), so the ceiling is 8/(8+r) - // with r the non-matrix instructions per matrix instruction. The shipped tile's inner loop - // is 361 instructions for 64 WMMA, r = 4.64, a 63% ceiling against 53% achieved. - // - // The three biggest items in that loop, per scale group: the fold (64 v_fma_mix_f32), the - // unpack (48 VALU) and the LDS waits (30 s_wait_dscnt). Bit 8192 is the fold: v_fma_mix_f32 - // is VOP3P and can never dual-issue, and `v_dual_fmac_f32` is the ONLY VOPD form gfx1201 - // offers that this loop can use (v_dual_and_b32 and v_dual_lshlrev_b32 do not exist here, - // so the unpack cannot be packed at all). - case 200: R4D_TILED8_LAUNCH(2, 8, 4, 2, 2, 0, 147 | 8192, 8, 0, UNRG); break; - case 201: R4D_TILED8_LAUNCH(2, 8, 4, 2, 2, 0, 147 | 8192 | 1024, 8, 0, UNRG); break; - case 202: R4D_TILED8_LAUNCH(2, 8, 4, 2, 2, 0, 147 | 1024, 8, 0, 2 * UNRG); break; - case 203: R4D_TILED8_LAUNCH(2, 8, 4, 2, 2, 0, 147 | 8192 | 1024, 8, 0, 2 * UNRG); break; - case 204: R4D_TILED8_LAUNCH(2, 8, 4, 2, 2, 0, 147 | 8192 | 2048, 8, 0, UNRG); break; - case 205: R4D_TILED8_LAUNCH(2, 8, 4, 2, 2, 0, 147 | 8192 | 2048 | 4096, 8, 0, UNRG); break; - // Taller tiles: the unpack is 3 VALU per (n tile, k step) shared over TM matrix instructions, - // so it is 3/TM per WMMA and TM is the only lever on it. Bit 32768 is what makes them worth - // trying -- without ragged 128-bit staging BM = 160 and 192 stage A one dword at a time. - case 206: R4D_TILED8_LAUNCH(2, 8, 5, 2, 2, 0, 147 | 8192 | 32768, 8, 0, UNRG); break; - case 207: R4D_TILED8_LAUNCH(2, 8, 6, 1, 2, 0, 147 | 8192 | 32768, 8, 0, UNRG); break; - case 208: R4D_TILED8_LAUNCH(2, 8, 5, 1, 2, 0, 147 | 8192 | 32768, 8, 0, UNRG); break; - case 209: R4D_TILED8_LAUNCH(2, 4, 6, 2, 2, 0, 147 | 8192, 8, 0, UNRG); break; - case 210: R4D_TILED8_LAUNCH(4, 4, 4, 2, 2, 0, 147 | 8192, 8, 0, UNRG); break; - case 211: R4D_TILED8_LAUNCH(2, 16, 4, 2, 2, 0, 147 | 8192, 8, 0, UNRG); break; - case 212: R4D_TILED8_LAUNCH(2, 8, 3, 2, 2, 0, 147 | 8192, 8, 0, UNRG); break; - case 213: R4D_TILED8_LAUNCH(1, 8, 4, 2, 2, 0, 147 | 8192, 8, 0, UNRG); break; - case 214: R4D_TILED8_LAUNCH(2, 8, 8, 1, 2, 0, 147 | 8192, 8, 0, UNRG); break; - case 215: R4D_TILED8_LAUNCH(2, 8, 4, 2, 0, 0, 147 | 8192, 8, 0, UNRG); break; - // THE SHAPE IS ALREADY RIGHT AT PREFILL: every taller, wider, narrower and more-unrolled tile - // loses, and the VOPD fold is a wash on K=5120 and a small win on K=3072. What is left is - // the inner loop, priced at M=4096 with the DCE-proof ablations: the VALU model says - // 8*64 + 146 = 658 cycles per 64 matrix instructions, a 78% ceiling, against 55% achieved. - // These variants say what the missing 23 points are made of. All of them compute wrong - // answers by construction. - case 220: R4D_TILED8_LAUNCH(2, 8, 4, 2, 2, 10, 147, 8, 0, UNRG); break; // no unpack - case 221: R4D_TILED8_LAUNCH(2, 8, 4, 2, 2, 11, 147, 8, 0, UNRG); break; // + no W LDS read - case 222: R4D_TILED8_LAUNCH(2, 8, 4, 2, 2, 12, 147, 8, 0, UNRG); break; // half the A LDS read - case 223: R4D_TILED8_LAUNCH(2, 8, 4, 2, 2, 13, 147, 8, 0, UNRG); break; // fold at 1/8 - case 224: R4D_TILED8_LAUNCH(2, 8, 4, 2, 2, 16, 147, 8, 0, UNRG); break; // no LDS barrier - case 225: R4D_TILED8_LAUNCH(2, 8, 4, 2, 2, 14, 147, 8, 0, UNRG); break; // no scale load - case 226: R4D_TILED8_LAUNCH(2, 8, 4, 2, 2, 15, 147, 8, 0, UNRG); break; // A from global - case 227: R4D_TILED8_LAUNCH(2, 8, 4, 2, 2, 0, 147 | 16384, 8, 0, UNRG); break; // A prefetch - case 228: R4D_TILED8_LAUNCH(2, 8, 4, 2, 2, 0, 147 | 8192 | 16384, 8, 0, UNRG); break; - case 229: R4D_TILED8_LAUNCH(2, 8, 4, 2, 2, 17, 147, 8, 0, UNRG); break; // iu4 route, staged - case 165: R4D_TILED8_LAUNCH(1, 8, 5, 1, 0, 0, 659, 8, 0, UNRG); break; // BM 80, iu4 - case 166: R4D_TILED8_LAUNCH(1, 8, 5, 1, 0, 0, 147, 8, 0, UNRG); break; // the same tile on iu8 - case 167: R4D_TILED8_LAUNCH(1, 8, 4, 1, 0, 0, 659, 8, 0, UNRG); break; // BM 64, iu4 - case 168: R4D_TILED8_LAUNCH(1, 8, 3, 1, 0, 0, 659, 8, 0, UNRG); break; // BM 48, iu4 - // THE DEFAULT: 2x8 waves of 4x2 tiles, the magic-bias accumulator, the raw scale prefetch, - // 32-bit global indexing and 128-bit staging FOR THE WEIGHT ONLY, at eight waves per EU. - // At M = 4096 it lands within about ten points of the block-fp8 bar on gate_proj, down_proj - // and in_proj_qkv, where the 4x4-wave, 2x4-tile, plain-cvt variant (variant 1) is 25-30% over - // it. - default: - if (ufull) R4D_TILED8_LAUNCH(2, 8, 4, 2, 2, 0, 147, 8, 0, UNRG); - else R4D_TILED8_LAUNCH(2, 8, 4, 2, 2, 0, 147, 8, 0, 1); - break; - } - } -#undef R4D_TILED8_LAUNCH + dim3 grid(N / BN, (M + BM - 1) / BM), block(WM * WN * 32); + hipLaunchKernelGGL((r4d_gemm_w8a8_tiled_kernel), grid, block, 0, + (hipStream_t)stream, (const signed char*)a, (const float*)ascale, + (const unsigned*)wq, (const unsigned*)ws, nullptr, (__hip_bfloat16*)c, M, K, N); } void r4d_gemm_w8a8_tiled(long a, long ascale, long wq, long ws, long c, int M, int K, int N, long stream, int variant) { - r4d_gemm_w8a8_tiled_impl(a, ascale, wq, ws, 0, c, M, K, N, stream, variant, false); -} - -// Asymmetric grid, the format the 27B's sweep picked: the nibble is read UNSIGNED and the stored -// per-group zero is corrected out with a per-row per-group sum of the activation, which -// r4d_quant_act_i8_asum emits as [K/group][Mpad] with Mpad = ceil(M/16)*16. -void r4d_gemm_w8a8_asym_tiled(long a, long ascale, long wq, long ws, long asum, long c, int M, - int K, int N, long stream, int variant) { - if (!asum) throw std::runtime_error("r4d gemm_w4a8_asym_tiled: asum is required"); - r4d_gemm_w8a8_tiled_impl(a, ascale, wq, ws, asum, c, M, K, N, stream, variant, true); + if (N % 256) throw std::runtime_error("r4d gemm_w8a8_tiled: N must be a multiple of 256"); + if (K % R4D_GEMM_W8A8_GROUP) + throw std::runtime_error("r4d gemm_w8a8_tiled: K must be a multiple of the scale group"); + if (M < 1) throw std::runtime_error("r4d gemm_w8a8_tiled: M must be positive"); + // The unroll covers exactly one scale group (GRP/BK steps); see r4d_gemm_w4a8_tiled.hip. The K + // check above makes every K a whole number of them. + static_assert(R4D_GEMM_W8A8_GROUP % R4D_TILED8_BK == 0, "the scale group must be whole k steps"); + constexpr int UNRG = R4D_GEMM_W8A8_GROUP / R4D_TILED8_BK; +#define R4D_TILED8_LAUNCH(...) \ + r4d_tiled8_launch<__VA_ARGS__>(a, ascale, wq, ws, c, M, K, N, stream) + // The arms tile_bmbn in r4d_rows.cpp lists, with the (BM, BN) it records for each. + switch (variant) { + case 6: R4D_TILED8_LAUNCH(2, 8, 2, 2, UNRG); break; // BM 64, BN 256 + case 10: R4D_TILED8_LAUNCH(2, 8, 3, 2, UNRG); break; // BM 96, BN 256 + case 12: R4D_TILED8_LAUNCH(2, 8, 3, 1, UNRG); break; // BM 96, BN 128 + case 57: R4D_TILED8_LAUNCH(2, 8, 5, 1, UNRG); break; // BM 160, BN 128 + case 59: R4D_TILED8_LAUNCH(2, 8, 4, 1, UNRG); break; // BM 128, BN 128 + case 114: R4D_TILED8_LAUNCH(1, 8, 5, 1, UNRG); break; // BM 80, BN 128 + case 124: R4D_TILED8_LAUNCH(1, 8, 4, 1, UNRG); break; // BM 64, BN 128 + case 125: R4D_TILED8_LAUNCH(1, 8, 7, 1, UNRG); break; // BM 112, BN 128 + case 126: R4D_TILED8_LAUNCH(1, 8, 10, 1, UNRG); break; // BM 160, BN 128 + case 128: R4D_TILED8_LAUNCH(1, 8, 2, 1, UNRG); break; // BM 32, BN 128 + case 129: R4D_TILED8_LAUNCH(1, 8, 3, 1, UNRG); break; // BM 48, BN 128 + case 138: R4D_TILED8_LAUNCH(1, 16, 3, 1, UNRG); break; // BM 48, BN 256 + case 139: R4D_TILED8_LAUNCH(1, 16, 7, 1, UNRG); break; // BM 112, BN 256 + case 146: R4D_TILED8_LAUNCH(1, 8, 9, 1, UNRG); break; // BM 144, BN 128 + default: R4D_TILED8_LAUNCH(2, 8, 4, 2, UNRG); break; // BM 128, BN 256 + } +#undef R4D_TILED8_LAUNCH } // ============================================================== the plugin ABI entry points // -// The operand reader and the split law are in r4d_gemm_args.h. See libr4d/r4d_args.h for why there -// is no adapter directory between the core and these launches. +// The operand reader and the split law are in r4d_gemm_args.h; see libr4d/r4d_args.h. extern "C" int r4d_rad_gemm_w8a8_tiled(const RadArgs* a, RadStream s) { GemmOps g; int rc = gemm_ops(a, &g, 1); @@ -1502,4 +291,3 @@ extern "C" int r4d_rad_gemm_w8a8_tiled(const RadArgs* a, RadStream s) { t->variant)); return RAD_OK; } - diff --git a/libr4d/r4d_gemm_wpa8i8_tiled.hip b/libr4d/r4d_gemm_wpa8i8_tiled.hip index 40665f8e..cbdc49b2 100644 --- a/libr4d/r4d_gemm_wpa8i8_tiled.hip +++ b/libr4d/r4d_gemm_wpa8i8_tiled.hip @@ -1,37 +1,35 @@ -// r4d_gemm_wpa8i8_tiled.hip - r4d_gemm_w4a8i8_tiled / r4d_gemm_w5a8i8_tiled: the 4- and 5-bit ASYMMETRIC -// weight x int8 activation GEMM for PREFILL row counts, gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T with +// r4d_gemm_wpa8i8_tiled.hip - r4d_gemm_w4a8i8_tiled / r4d_gemm_w5a8i8_tiled: the 4- and 5-bit asymmetric +// weight x int8 activation GEMM for prefill row counts, gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T with // // dequant(Wq)[n][k] = scale[n][k/128] * (code[n][k] - zero[n][k/128]), code in 0..15 or 0..31 // -// -- ParoQuant's int4 (z-lab) and int5 once the activation has been rotated (givens_dense_quant) -- in -// 16x16x16 int8 WMMA, which issues at the fp8 instruction's rate. The f16 skinny kernel these weights -// also serve (r4d_gemm_w5a16_nt_m64) is capped by the f16 matrix instruction at about 75 TF/s; this is the -// tall-tile form with no such ceiling, built on r4d_gemm_mxfp4a8_tiled.hip's arrangement: +// (ParoQuant's int4 (z-lab) and int5, after the activation is rotated by givens_dense_quant) in +// 16x16x16 int8 WMMA, which issues at the fp8 rate. The f16 skinny kernel for these weights +// (r4d_gemm_w5a16_nt_m64) is capped by the f16 matrix instruction at about 75 TF/s. Arrangement as in +// r4d_gemm_mxfp4a8_tiled.hip: // // * a 256 x 64 tile (4 x 2 waves, 4 x 2 fragments each); the activation is re-tiled by // r4d_mxfp4a8_tile_a into fragment order (one 16 x 16 fragment = 256 bytes) in the op's scratch and // read straight into registers; the weight slab is staged through LDS; -// * a slab is one scale group (128 of K = 8 WMMA steps): the int32 accumulators start at zero each slab and -// are folded into the running float total as slab * (a_scale[row][g] * w_scale[col][g]), because the -// weight's f16 scale varies by column and so cannot ride inside the matrix instruction; +// * a slab is one scale group (128 of K = 8 WMMA steps): the int32 accumulators restart each slab and +// are folded into the float total as slab * (a_scale[row][g] * w_scale[col][g]), since the weight +// scale varies by column; // * a partitioned weight (pb1/pb2) is one launch per part over windows of the planes. // -// WHY INT8 AND NOT FP8. (code - zero) is -15..15 (int4) or -31..31 (int5); both are exact in an int8, -// so the weight needs no conversion at all -- the staging is a byte-wise subtract -- whereas e4m3's three -// mantissa bits stop at 16 and int5 would need two matrix issues a step. The activation is quantised to -// int8 with one scale a (row, 128 of K): after the rotation a group is flat, so 127 uniform levels of its -// maximum are finer than e4m3's relative 2^-4 for nearly every element (measured: ppl equal to the f16 -// path's, slightly better than the fp8 band's). The accumulators are int32 and exact: a slab is 128 +// Why int8, not fp8: (code - zero) is -15..15 (int4) or -31..31 (int5), exact in int8, so staging is a +// byte-wise subtract; e4m3's three mantissa bits stop at 16. The activation is int8 with one scale per +// (row, 128 of K): after rotation a group is flat, so 127 uniform levels beat e4m3's relative 2^-4 for +// nearly every element (perplexity equals the f16 path's). Accumulators are exact int32: a slab is 128 // products of at most 31 * 127. // -// STAGING. A code byte c (0..31) minus the zero z (0..31): (c | 0x80) - z is 128 + (c - z), never below -// 97 and never carrying into the next byte, and XOR 0x80 turns it into the two's complement byte of -// (c - z). Three ALU ops a dword of four weights. +// Staging: for a code byte c (0..31) and zero z (0..31), (c | 0x80) - z = 128 + (c - z) never drops +// below 97 or borrows across bytes, and XOR 0x80 gives the two's complement byte of (c - z). Three ALU +// ops per dword of four weights. // -// THE WEIGHT BLOB is r4d_gemm_w5a16_nt_m64's (BITS 5): the nibble plane (w4's fragment order), then the -// fifth bits, one dword a (n-tile, 64 of K, lane): byte s = k step s of the block, bit e = element e. For -// BITS 4 it is the nibble plane alone. The scale operand is the f16 kernel's dword plane -// [N/16][K/128][16]: the f16 scale in the low half, -(1024 + zero) in the high. +// Weight blob as r4d_gemm_w5a16_nt_m64's (BITS 5): the nibble plane (w4's fragment order), then the +// fifth bits, one dword per (n-tile, 64 of K, lane): byte s = k step s, bit e = element e. BITS 4 is the +// nibble plane alone. The scale operand is the f16 kernel's dword plane [N/16][K/128][16]: f16 scale +// low, -(1024 + zero) high. #include "r4d.h" #include "r4d_gemm_args.h" #include "r4d_common.h" @@ -73,9 +71,8 @@ __global__ __launch_bounds__(R4D_WPT_NTHR) void r4d_gemm_wpa8i8_tiled_kernel( constexpr int TM = R4D_WPT_TM, TN = R4D_WPT_TN, WN = R4D_WPT_WN, NTHR = R4D_WPT_NTHR, BMF = R4D_WPT_BMF; constexpr int LBK = R4D_WPT_LBK, NS = LBK / 16, STR = LBK + R4D_WPT_PAD, BNF = WN * TN * 16; constexpr int NTILES_T = BNF / 16, TOT_SLOTS = NTILES_T * NS * 32; - // A thread stages one lane's 16 bytes of a 64-wide k block -- four k steps of one weight row, which - // is how the fragment-order plane is laid out (dword (t, kb, lane, s)) -- so a slab of two blocks - // over the block's tiles is TOT_SLOTS / 4 reads. + // A thread stages one lane's 16 bytes of a 64-wide k block (four k steps of one weight row, as the + // plane is laid out: dword (t, kb, lane, s)), so a slab of two blocks is TOT_SLOTS / 4 reads. constexpr int NW = TOT_SLOTS / 4 / NTHR; static_assert(NW * NTHR * 4 == TOT_SLOTS, "the W tile must split evenly over the block"); __shared__ unsigned char sW[BNF * STR]; @@ -239,9 +236,8 @@ static void wpa8i8_launch(long at, long ascale, long wq, long whi, long wsz, lon } // ============================================================== the plugin ABI entry points -// The row-major int8 activation is re-tiled into the op's scratch (one slab, the parts in turn), then the GEMM -// reads it from there -- mxfp4a8_tiled's arrangement exactly, including a partitioned weight as -// one launch per part over windows of the planes. +// The row-major int8 activation is re-tiled into the op's scratch (one part at a time) and the GEMM +// reads it there, as in mxfp4a8_tiled, including one launch per part of a partitioned weight. template static int wpa8i8_dispatch(const RadArgs* a, RadStream s) { GemmOps g; diff --git a/libr4d/r4d_gen.hip b/libr4d/r4d_gen.hip index b68bfa47..c52a86a5 100644 --- a/libr4d/r4d_gen.hip +++ b/libr4d/r4d_gen.hip @@ -3,13 +3,13 @@ // flow-matching sampler over them, and the image decoder's convolution, channel norm, resampling // shortcuts and pixel output. // -// EACH KERNEL ROUNDS WHERE ITS libref FUNCTION DOES (libref/ref_gen.cpp), and libref rounds where -// the reference model materialises a bf16 tensor. A reduction's order differs -- a block sum here, -// a sequential one there -- so a sum can land one bf16 step apart; nothing else does. +// Each kernel rounds where its libref function does (libref/ref_gen.cpp), and libref rounds where +// the reference model materialises a bf16 tensor. Only reduction order differs (a block sum here, +// a sequential one there), so a sum can land one bf16 step apart. // -// IMAGE GEOMETRY IS IN THE OPERANDS. An image operand is [height, width * channels], dense, and -// the shims read both off its shape: a parameter is fixed at declare and an image's size is a -// request's. +// Image geometry comes from the operands: an image operand is a dense [height, width * channels], +// and the shims read both off its shape, because parameters are fixed at declare and image size +// is per request. #include "r4d.h" #include "r4d_args.h" #include "r4d_common.h" @@ -18,6 +18,7 @@ #include "rad_philox.h" #include +#include #include #include @@ -116,17 +117,15 @@ __global__ __launch_bounds__(kT) void gate_add_kernel( // ---------------------------------------------------------------------------- ln_mod_quant_fp8 // gate_add, ln_mod and quant_act_fp8 in one pass over the row: the DiT block's norm in front of -// every quantised linear, with the gated residual of the branch before it folded in. Three passes -// over a 16384 x 4096 activation were ~0.9 GB of traffic a norm; this one reads the delta and the -// residual and writes the residual and the E4M3 pair. The bf16 norm output is written only when -// bound -- the fp8 linears read the codes. +// every quantised linear, with the previous branch's gated residual folded in. Three passes over a +// 16384 x 4096 activation are ~0.9 GB of traffic per norm; this reads the delta and the residual +// and writes the residual and the E4M3 pair. The bf16 norm output is written only when bound. // -// BIT-IDENTICAL TO THE THREE IT REPLACES, which the picture comparing equal across builds needs: -// the residual is the gate_add arithmetic rounded to bf16 as its store rounds it, the mean and the -// variance fold each thread's 8-wide chunks in ln_mod_kernel's order through the same block_sum, -// the norm output is rounded to bf16 before it is quantised as quant_act_fp8 reads it, and the -// codes are r4d_q8.h's. A 128-column group is sixteen consecutive chunks, so sixteen consecutive -// lanes, and its amax is a half-wave reduction. +// Bit-identical to the three kernels it replaces: the residual is gate_add's arithmetic rounded to +// bf16 as its store rounds it, mean and variance fold each thread's 8-wide chunks in +// ln_mod_kernel's order through the same block_sum, the norm output is rounded to bf16 before +// quantising, and the codes are r4d_q8.h's. A 128-column group is sixteen consecutive lanes, so its +// amax is a half-wave reduction. constexpr int kLnqChunks = 4; // 8-wide chunks a thread keeps: n <= kT * 8 * 4 = 8192 template @@ -224,8 +223,8 @@ __global__ __launch_bounds__(kT) void gather2_kernel( *(uint4*)(y + (size_t)r * y_ld + c) = src ? *(const uint4*)(src + c) : make_uint4(0, 0, 0, 0); } -// The lane copies move WORDS: a row is `words` 32-bit words (64 bf16 latent channels are 32, an f32 -// mask value is one), so one kernel serves every dtype the lanes hold. +// The lane copies move 32-bit words: a row is `words` words (64 bf16 latent channels are 32, an +// f32 mask value is one), so one kernel serves every dtype the lanes hold. __global__ __launch_bounds__(kT) void lane_gather_kernel( const uint32_t* __restrict__ src, const int* __restrict__ lane, const int* __restrict__ cu, uint32_t* __restrict__ y, int words, int n_seq, int stride, int s_ldw, int y_ldw, int64_t total) { @@ -317,8 +316,8 @@ __global__ __launch_bounds__(kT) void flow_euler_kernel( } // ---------------------------------------------------------------------------- per-channel ops -// The two lists ride in the kernel's arguments, whose segment the backend caps at 768 bytes: 64 -// channels a list (a latent's) is 512 of them. +// The two lists ride in the kernel arguments, whose segment the backend caps at 768 bytes; two +// lists of 64 channels (a latent's) take 512. constexpr int kChanMax = 64; struct ChanLists { float mul[kChanMax], add[kChanMax]; }; @@ -424,24 +423,22 @@ __global__ __launch_bounds__(kT) void gelu_tanh_kernel( } // ---------------------------------------------------------------------------- conv2d_nhwc -// AN IMPLICIT GEMM: y[pixel][cout] = sum over (tap, cin) of x_virtual[pixel's tap][cin] * -// w[cout][tap][cin], the weight stored TAP-MAJOR (r4d_layout.cpp relayouts PyTorch's -// [cout][cin][k][k] at load) so K runs over taps and then channels and a 64-wide K tile of the -// image is eight 16-byte reads of NHWC rows -- the im2col never exists. +// An implicit GEMM: y[pixel][cout] = sum over (tap, cin) of x_virtual[pixel's tap][cin] * +// w[cout][tap][cin]. The weight is stored tap-major (r4d_layout.cpp relayouts PyTorch's +// [cout][cin][k][k] at load), so K runs over taps then channels and a 64-wide K tile of the image +// is eight 16-byte reads of NHWC rows; no im2col buffer. // // The block is r4d_gemm_bf16_nt_tiled's: eight waves, an activation tile of BP pixels and a weight -// tile of BC output channels staged through LDS 64 K a time, the next tile's loads in flight under -// the current one's WMMA. The weight is the WMMA's A operand and the pixels its B, so a lane's -// accumulator is eight CONSECUTIVE output channels of one pixel and the store is 16 bytes. +// tile of BC output channels staged through LDS 64 K at a time, with the next tile's loads in +// flight under the current WMMA. The weight is the WMMA's A operand and the pixels its B, so a +// lane's accumulator is eight consecutive output channels of one pixel and the store is 16 bytes. // -// An input chunk of eight channels never straddles a tap because cin is a multiple of eight (the -// shim sends anything else to the direct kernel below); a chunk past the image, past K or past the -// last pixel is zeros. +// An eight-channel input chunk never straddles a tap because cin is a multiple of eight (the shim +// sends anything else to the direct kernel); a chunk past the image, K or the last pixel is zeros. // -// THE KERNEL SIZE AND THE UPSAMPLING ARE TEMPLATE PARAMETERS (KS, UP; 0 reads the argument). A tap -// index over a runtime k and a source row over a runtime `up` are two integer divisions per staged -// chunk -- four chunks a thread a K tile, ~500 integer instructions beside 48 WMMA a wave -- and at -// 3 and 2 they are a multiply-shift and a shift. The arithmetic is unchanged. +// Kernel size and upsampling are template parameters (KS, UP; 0 reads the argument): at runtime +// they cost two integer divisions per staged chunk (~500 integer instructions beside 48 WMMA a +// wave), at 3 and 2 a multiply-shift and a shift. #define CV_BK 64 #define CV_PITCH (CV_BK + 8) @@ -826,7 +823,10 @@ extern "C" int r4d_rad_randn_lanes(const RadArgs* a, RadStream s) { const long long dl = r4d_rows_pitch(dst, n, &rd); if (dl < 0) return R4D_NO(RAD_E_STRIDE); const long long n_seq = r4d_numel(cu) - 1; - if (n <= 0 || stride <= 0 || n_seq <= 0) return R4D_NO(RAD_E_SHAPE); + if (n <= 0 || stride <= 0 || n_seq <= 0 || rd < stride) return R4D_NO(RAD_E_SHAPE); + /* One flag and lane an entry, two seed words. A lane's rows (device data) are not checked. */ + if (r4d_numel(fl) < n_seq || r4d_numel(lane) < n_seq || r4d_numel(seed) < 2 * n_seq) + return R4D_NO(RAD_E_SHAPE); hipLaunchKernelGGL(randn_lanes_kernel, dim3(blocks_for(stride * n), (unsigned)n_seq), dim3(kT), 0, (hipStream_t)s, (const int*)fl->data, (const uint32_t*)seed->data, (const int*)lane->data, (const int*)cu->data, (uint16_t*)dst->data, (int)n, @@ -851,7 +851,14 @@ extern "C" int r4d_rad_flow_euler(const RadArgs* a, RadStream s) { const long long il = inp ? r4d_rows_pitch(inp, n, &ri) : 0; if (vl < 0 || sl < 0 || pl < 0 || il < 0) return R4D_NO(RAD_E_STRIDE); const long long n_seq = r4d_numel(cu) - 1; - if (n <= 0 || stride <= 0 || n_seq <= 0) return R4D_NO(RAD_E_SHAPE); + if (n <= 0 || stride <= 0 || n_seq <= 0 || rst < stride) return R4D_NO(RAD_E_SHAPE); + /* One scalar of each kind an entry, two seed words; inp, mask and preview are addressed by the + * state's rows. A lane's rows and a pair's entry (device data) are not checked. */ + for (const RadTensor* e : { sg, sgn, cfg, pair, lane, fl }) + if (r4d_numel(e) < n_seq) return R4D_NO(RAD_E_SHAPE); + if (r4d_numel(seed) < 2 * n_seq || (pv && rp < rst) || (inp && ri < rst) || + (mask && r4d_numel(mask) < rst)) + return R4D_NO(RAD_E_SHAPE); hipLaunchKernelGGL(flow_euler_kernel, dim3(blocks_for(stride * n), (unsigned)n_seq), dim3(kT), 0, (hipStream_t)s, (const uint16_t*)v->data, (const float*)sg->data, (const float*)sgn->data, (const float*)cfg->data, (const int*)pair->data, @@ -918,11 +925,11 @@ extern "C" int r4d_rad_conv2d_nhwc(const RadArgs* a, RadStream s) { (int)x->stride[0], (int)y->stride[0], (int64_t)total); return st_of(hipGetLastError()); } - // 128 pixels a block, and the widest channel tile -- 192, 128, then 64 -- that leaves under a - // third of its last block idle. A wider tile does twice or three times the WMMA a K step for - // the same two barriers, and that pays even with the last block partly empty: on Qwen-Image's - // decoder the 192 tile against the 64 one is 144 channels 39.7 -> 26.3 ms, 288 125.9 -> 95.2 - // (an upsampling layer), 576 109.9 -> 70.8, the same bytes out. 96 channels take 128. + // 128 pixels a block, and the widest channel tile (192, 128, then 64) that leaves under a third + // of its last block idle. A wider tile does two or three times the WMMA per K step for the same + // two barriers, which pays even with the last block partly empty: on Qwen-Image's decoder the + // 192 tile is 1.3-1.55x faster than the 64 tile at 144, 288 and 576 channels. 96 channels + // take 128. auto fits = [cout](long long bc) { const long long padded = (cout + bc - 1) / bc * bc; return (padded - cout) * 3 < padded; diff --git a/libr4d/r4d_givens_dense.hip b/libr4d/r4d_givens_dense.hip index 3ca47151..27185cfd 100644 --- a/libr4d/r4d_givens_dense.hip +++ b/libr4d/r4d_givens_dense.hip @@ -1,30 +1,27 @@ // r4d_givens_dense.hip -- ParoQuant's rotation as a dense per-group matrix on the matrix cores. // // The Givens stages of a 128-column group compose to one orthogonal 128 x 128 matrix T, so -// y = T (x / D) is a small GEMM: out[m][j] = sum_i T[j][i] * (x[m][i] / D[i]). The sequential kernel -// (r4d_givens_rotate.hip) does the same job in `stages` dependent LDS rounds a group and is -// latency bound (~100-130 GB/s of ~640); this one spends ~8x the multiply-adds on the f16 WMMA, which -// is 5 us of math for a 2048-row part, and quantises in the epilogue -- int8 (scale amax / 127, for the -// int8 prefill GEMMs) or E4M3 (amax / 448, for the mxfp4a8 GEMMs), the same scale grid as the -// sequential producer's. About 3x faster at prefill sizes and no slower at decode. +// y = T (x / D) is a small GEMM: out[m][j] = sum_i T[j][i] * (x[m][i] / D[i]). The sequential +// kernel (r4d_givens_rotate.hip) runs `stages` dependent LDS rounds per group and is latency bound +// (~100-130 GB/s of ~640); this one spends ~8x the multiply-adds on f16 WMMA (5 us of math for +// 2048 rows) and quantises in the epilogue: int8 (scale amax / 127, for the int8 prefill GEMMs) or +// E4M3 (amax / 448, for the mxfp4a8 GEMMs), the sequential producer's scale grid. About 3x faster +// at prefill sizes and no slower at decode. // -// THE MATRICES ARE THE WEIGHT: rad-convert composes them from the Givens stages and stores them as the +// The matrices are the weight: rad-convert composes them from the Givens stages into the // encoding's `t.dense` table, [parts * K / 128][128 (j)][128 (i)] f16, which the layout -// (r4d_layout.cpp, r4d.givens.dense) takes as it is, so the serving side never walks a Givens network. The channel scale stays a separate table (`rscale`), a -// divide on the way in: folding 1/D into T would put entries of very different magnitude in one f16 -// matrix. +// (r4d_layout.cpp, r4d.givens.dense) takes as is. The channel scale stays a separate table +// (`rscale`), divided on the way in: folding 1/D into T would mix very different magnitudes in one +// f16 matrix. // -// ONE BLOCK A (part, group) x row chunk. The group's T (32 KiB of f16) is staged in LDS once and each -// of the block's four waves takes 16-row tiles: per k step one B fragment (the activation row's -// eight k, divided by D, as f16) meets the eight j tiles of T. The accumulators are C[j][m]: lane l -// holds column m = l & 15 and rows j = 8 * (l >> 4) + e, so a row's 128 outputs are split over lane m -// and lane m + 16 and its amax is a max over 64 registers and one xor-16 shuffle. +// One block per (part, group) x row chunk. The group's T (32 KiB of f16) is staged in LDS once and +// each of the four waves takes 16-row tiles: per k step one B fragment (the activation row's eight +// k, divided by D, as f16) meets the eight j tiles of T. The accumulators are C[j][m]: lane l holds +// column m = l & 15 and rows j = 8 * (l >> 4) + e, so a row's 128 outputs are split over lanes m +// and m + 16 and its amax is a max over 64 registers and one xor-16 shuffle. // -// WHAT MOVED THE TIME (selftest, 2048 rows x K 5120): the first version waited on one activation load a -// k step and spilled ~190 registers (186 us). A tile's eight loads are now issued together and the -// issue order is pinned per k step (sched_barrier), which is what keeps the A fragments from being -// hoisted whole into registers: 137 VGPRs, no spills, ~100 us. Double-buffering the next tile and -// coalescing the stores through LDS were tried and did not move it. +// A tile's eight activation loads are issued together and the issue order is pinned per k step +// (sched_barrier), so the A fragments are not hoisted whole into registers: 137 VGPRs, no spills. #include "r4d.h" #include "r4d_emit.h" #include "r4d_fp8_args.h" @@ -40,8 +37,8 @@ namespace { constexpr uint32_t kGroup = 128; constexpr uint32_t kThreads = 128; constexpr uint32_t kWaves = kThreads / 32; -constexpr uint32_t kTStride = kGroup + 8; -static_assert(kThreads == kGroup, "a thread stages one channel scale of the group (invd[tid])"); // f16 per LDS row of T: 16 B pad, conflict-free b128 reads +constexpr uint32_t kTStride = kGroup + 8; // T row pitch in f16: 16 B pad for conflict-free b128 +static_assert(kThreads == kGroup, "a thread stages one channel scale of the group (invd[tid])"); typedef _Float16 v8h_t __attribute__((ext_vector_type(8))); @@ -73,9 +70,8 @@ __global__ __launch_bounds__(kThreads) void givens_dense_kernel( const uint32_t Mt = (M + 15) >> 4; const uint32_t step = gridDim.y * kWaves; for (uint32_t tile = blockIdx.y * kWaves + wave; tile < Mt; tile += step) { - // The activation row a lane reads: lane (col, h) takes columns 8h .. 8h+7 of every 16-wide k step of - // row (tile * 16 + col). All eight k steps of a tile are loaded at once, so a tile costs one load - // latency and not eight. + // Lane (col, h) reads columns 8h .. 8h+7 of every 16-wide k step of row tile * 16 + col. + // All eight k steps are loaded at once: one load latency per tile. uint32_t m = tile * 16 + col; const bool live = m < M; if (!live) m = M - 1; @@ -133,7 +129,7 @@ __global__ __launch_bounds__(kThreads) void givens_dense_kernel( // s [M][parts * K/128] f32, `s_ld` elements a row (0 = parts * K/128) enum { GD_X = 0, GD_T = 1, GD_RSCALE = 2, GD_Q = 3, GD_S = 4 }; -static int givens_dense_body(const RadArgs* a, const R4dSink& sk) { +extern "C" int r4d_rad_givens_dense_quant(const RadArgs* a, RadStream stream) { const RadTensor* x = r4d_opt(a, GD_X); const RadTensor* t = r4d_opt(a, GD_T); const RadTensor* rs = r4d_opt(a, GD_RSCALE); @@ -162,12 +158,10 @@ static int givens_dense_body(const RadArgs* a, const R4dSink& sk) { const long long mt = (M + 15) / 16; const uint32_t gy = (uint32_t)std::max(1, (mt + 4 * kWaves - 1) / (4 * kWaves)); const dim3 grid((uint32_t)(parts * nkb), gy); -#define GD_EMIT(I8_) R4D_EMIT(sk, (givens_dense_kernel), grid, dim3(kThreads), 0, \ +#define GD_EMIT(I8_) R4D_EMIT(stream, (givens_dense_kernel), grid, dim3(kThreads), 0, \ (const uint16_t*)x->data, (const uint16_t*)t->data, (const float*)rs->data, (uint8_t*)q->data, \ (float*)sc->data, (uint32_t)M, (uint32_t)K, (uint32_t)nkb, (uint32_t)xp, (uint32_t)qp, (uint32_t)sp) const int rc = i8 ? GD_EMIT(true) : GD_EMIT(false); #undef GD_EMIT - if (rc != RAD_OK) return rc; - return (!sk.desc && hipGetLastError() != hipSuccess) ? RAD_E_DEVICE : RAD_OK; + return rc; } -R4D_ENTRY(r4d_rad_givens_dense_quant, givens_dense_body) diff --git a/libr4d/r4d_givens_rotate.hip b/libr4d/r4d_givens_rotate.hip index 7266be9b..8a1bb6cf 100644 --- a/libr4d/r4d_givens_rotate.hip +++ b/libr4d/r4d_givens_rotate.hip @@ -1,30 +1,27 @@ -// ParoQuant's rotation, to f16: the channel scale and Givens stages applied to a bf16 activation, for the -// 16-bit-activation GEMMs (w5a16 / w4a16_asym, rows up to 64 -- decode). The weight it pairs with is stored -// as v = w . D . G_1 ... G_S (abi/rad_encoding.h, "givens"), so the product with -// x' = x . D^-1 . G_1 ... G_S is : the rotation is the activation's to do, once a token, and the -// weight is read by the GEMM unchanged. The quantising form, for prefill-sized rows and for MXFP4, is +// ParoQuant's rotation to f16: the channel scale and Givens stages applied to a bf16 activation, +// for the 16-bit-activation GEMMs (w5a16 / w4a16_asym, rows up to 64, i.e. decode). The weight is +// stored as v = w . D . G_1 ... G_S (abi/rad_encoding.h, "givens"), so with +// x' = x . D^-1 . G_1 ... G_S, = : the activation is rotated once a token and the +// GEMM reads the weight unchanged. The quantising form, for prefill-sized rows and MXFP4, is // r4d_givens_dense.hip. // -// WHY THE ROTATION IS A GROUP AT A TIME. ParoQuant's pairs never leave a group of 128 columns -- that is -// how the checkpoint is trained, and the converter and the loader (r4d_rad_relayout_givens_pairs) refuse -// one that does -- so a group is a closed system: -// its 128 values are rotated by S stages of 64 disjoint pairs. A wave owns a group. The values sit in LDS -// (128 floats a wave, no barrier needed: a wave's LDS accesses are in order, and the pairs of a stage are -// disjoint so no two lanes touch one address) and each lane takes two pairs a stage. +// A group at a time: ParoQuant's pairs never leave a group of 128 columns (the checkpoint is +// trained that way, and the converter and loader, r4d_rad_relayout_givens_pairs, refuse one that +// does), so a group's 128 values are rotated by S stages of 64 disjoint pairs. A wave owns a group, +// held in LDS (128 floats a wave). No block barrier is needed: a wave's LDS accesses are in order +// and a stage's pairs are disjoint, so no two lanes touch one address. Each lane takes two pairs +// per stage. // -// PARTS. A fused projection (gate|up, q|k|v) was rotated per piece, so a row yields `parts` rotated -// copies, side by side: y is [M, parts * K]. A (part, group) pair is one unit of work, one wave's (a row -// is several blocks, grid.y). The tables stack the parts as the "givens" encoding does -- stages rows each -// of pairs and angle, one row of channel scales. +// Parts: a fused projection (gate|up, q|k|v) is rotated per piece, so a row yields `parts` rotated +// copies side by side: y is [M, parts * K]. A (part, group) is one wave's work (a row spans several +// blocks, grid.y). The tables stack the parts as the "givens" encoding does: `stages` rows each of +// pairs and angle, one row of channel scales. // -// THE CHANNEL SCALE IS A DIVIDE, because the encoding's t.scale is the factor the stored row was -// multiplied by (D), and the activation takes its inverse. A true IEEE divide on both sides: the -// reference (libref) divides in f32 too, so the two agree on this step exactly. +// The channel scale is a true IEEE divide: t.scale is the factor D the stored row was multiplied +// by, and libref also divides in f32, so the two agree exactly on this step. Cos and sin are +// computed here in f32 from the stored angle (sincosf, an ulp or two, as libref's libm). // -// COS AND SIN ARE COMPUTED HERE, in f32, from the stored angle: sincosf is accurate to an ulp or two, -// which is also what libref's libm is. -// -// Returns a negative code rather than throwing, for the reason given in r4d_gemm_fp8a8.hip. +// Returns a negative code instead of throwing, for the reason given in r4d_gemm_fp8a8.hip. #include "r4d.h" #include "r4d_emit.h" @@ -39,10 +36,9 @@ constexpr uint32_t kWaves = kThreads / kWave; constexpr uint32_t kGroup = 128; constexpr uint32_t kPairsPerLane = kGroup / 2 / kWave; // 2 -// kPre stages' tables are loaded and their angles' sine and cosine taken BEFORE the first of them is -// applied, so the dependent chain a stage would otherwise be -- table load, LDS read, rotate, LDS -// write -- overlaps its neighbours' loads. At decode (M of a handful of rows) the kernel is latency -// and not bandwidth: a row is 40 groups of 128 and each group is eight serial stages. +// kPre stages' tables are loaded and their sines and cosines taken before the first is applied, so +// each stage's dependent chain (table load, LDS read, rotate, LDS write) overlaps its neighbours' +// loads. At decode it is latency bound: a row is 40 groups of 128, each eight serial stages. constexpr uint32_t kPre = 8; __device__ __forceinline__ void wave_sync() { @@ -51,10 +47,10 @@ __device__ __forceinline__ void wave_sync() { __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "wavefront"); } -// One wave rotates one (part, group) of one row: grid.x is the row, and grid.y spreads a row's -// `parts * nkb` groups over blocks of kWaves waves -- one group a wave, so a row is several blocks and a -// decode step of a few rows still fills the part. A wave that has no group returns at once; nothing in -// the kernel is a block barrier. The rotated row is written as f16 into `y`, y_ld elements a row. +// One wave rotates one (part, group) of one row: grid.x is the row and grid.y spreads the row's +// `parts * nkb` groups over blocks of kWaves waves, so a decode step of a few rows still fills the +// part. A wave with no group returns at once; there is no block barrier. The rotated row is +// written as f16 into `y`, y_ld elements a row. __global__ __launch_bounds__(kThreads) void givens_rotate_kernel( const uint16_t* __restrict__ x, const int32_t* __restrict__ pairs, const float* __restrict__ angle, const float* __restrict__ rscale, uint16_t* __restrict__ y, @@ -119,8 +115,8 @@ __global__ __launch_bounds__(kThreads) void givens_rotate_kernel( const float4 r = *(const float4*)(buf + lane * 4u); const float v[4] = { r.x, r.y, r.z, r.w }; - // f16 holds +-65504; a rotated post-norm row is orders below that, and the clamp keeps an outlier - // finite instead of inf + // f16 holds +-65504; a rotated post-norm row is far below that, and the clamp keeps an outlier + // finite. union { __half h[4]; uint2 u; } o; #pragma unroll for (int j = 0; j < 4; ++j) o.h[j] = __float2half(fminf(fmaxf(v[j], -65504.0f), 65504.0f)); @@ -136,7 +132,7 @@ __global__ __launch_bounds__(kThreads) void givens_rotate_kernel( // y [M][parts*K] f16 enum { GV_X = 0, GV_PAIRS = 1, GV_ANGLE = 2, GV_RSCALE = 3, GV_Y = 4 }; -static int givens_rotate_body(const RadArgs* a, const R4dSink& sk) { +extern "C" int r4d_rad_givens_rotate(const RadArgs* a, RadStream stream) { const RadTensor* x = r4d_opt(a, GV_X); const RadTensor* pr = r4d_opt(a, GV_PAIRS); const RadTensor* an = r4d_opt(a, GV_ANGLE); @@ -159,16 +155,16 @@ static int givens_rotate_body(const RadArgs* a, const R4dSink& sk) { if (pr->shape[0] != parts * stages || pr->shape[1] != K) return R4D_NO(RAD_E_SHAPE); if (an->shape[0] != parts * stages || an->shape[1] != K / 2) return R4D_NO(RAD_E_SHAPE); if (rs->shape[0] != parts || rs->shape[1] != K) return R4D_NO(RAD_E_SHAPE); - if (!r4d_aligned(rs->data, 16) || !r4d_aligned(pr->data, 8) || !r4d_aligned(y->data, 4)) + // A lane stores four f16 (8 bytes) at a time, so y's base and row pitch keep 8-byte alignment. + if (!r4d_aligned(rs->data, 16) || !r4d_aligned(pr->data, 8) || !r4d_aligned(y->data, 8)) return R4D_NO(RAD_E_ALIGN); const long long xp = r4d_row_pitch(x), yp = r4d_row_pitch(y); if (xp < 0 || yp < 0) return R4D_NO(RAD_E_STRIDE); + if (yp % 4) return R4D_NO(RAD_E_ALIGN); const uint32_t gy = ((uint32_t)(parts * nkb) + kWaves - 1) / kWaves; - const int rc = R4D_EMIT(sk, givens_rotate_kernel, dim3((uint32_t)M, gy), dim3(kThreads), 0, - (const uint16_t*)x->data, (const int32_t*)pr->data, (const float*)an->data, - (const float*)rs->data, (uint16_t*)y->data, (uint32_t)K, (uint32_t)nkb, - (uint32_t)parts, (uint32_t)stages, (uint32_t)(xp ? xp : K), (uint32_t)(yp ? yp : parts * K)); - if (rc != RAD_OK) return rc; - return (!sk.desc && hipGetLastError() != hipSuccess) ? RAD_E_DEVICE : RAD_OK; + return R4D_EMIT(stream, givens_rotate_kernel, dim3((uint32_t)M, gy), dim3(kThreads), 0, + (const uint16_t*)x->data, (const int32_t*)pr->data, (const float*)an->data, + (const float*)rs->data, (uint16_t*)y->data, (uint32_t)K, (uint32_t)nkb, + (uint32_t)parts, (uint32_t)stages, (uint32_t)(xp ? xp : K), + (uint32_t)(yp ? yp : parts * K)); } -R4D_ENTRY(r4d_rad_givens_rotate, givens_rotate_body) diff --git a/libr4d/r4d_gram_accum_fp8.hip b/libr4d/r4d_gram_accum_fp8.hip index 83f6542f..1891f652 100644 --- a/libr4d/r4d_gram_accum_fp8.hip +++ b/libr4d/r4d_gram_accum_fp8.hip @@ -1,39 +1,25 @@ // H += X^T X, in f32, over an E4M3 activation with a per-(row, group) scale, or over a plain bf16 // one. // -// WHAT IT IS FOR. GPTQ needs a Gram matrix of the layer's real input -- the second moment -// `H = sum_t x_t x_t^T` over a calibration corpus -- and this is the device half of producing one; -// `rad_quantize` alone cannot, because it has no calibration harness to run the activations -// through. The 4-bit expert format is the caller: see docs/MOE-W4.md. +// Purpose: the device half of GPTQ's Gram matrix `H = sum_t x_t x_t^T` over a calibration corpus, +// for the 4-bit expert format (docs/MOE-W4.md). // -// IT IS NOT A GEMM AND CANNOT BE ONE. `gemm_nt` contracts the LAST axis of both operands; this -// contracts the FIRST axis of both. Declaring it as a GEMM would need X transposed in memory, -// which is a 26 MB scratch buffer and a transpose kernel for an op whose whole body is an FMA -// loop. So it is its own row. +// Not a GEMM: `gemm_nt` contracts the last axis of both operands, this contracts the first. +// Expressing it as a GEMM would need a transposed copy of X (a 26 MB scratch and a transpose). // -// WHY THE INPUT IS E4M3 AND NOT bf16. The two taps are the MoE block's own quantiser outputs -- -// `had_quant_act_fp8`'s (q, scale) for gate_up, and `gated_had_quant_fp8`'s for down. Those are -// literally the bytes the expert GEMM contracts, so a Hessian built from them is a Hessian of the -// arithmetic that actually runs rather than of the bf16 that preceded it. It is also the only -// form the rotated path HAS: nothing stores the rotated activation as bf16. +// E4M3 input: the taps are the MoE block's own quantiser outputs (`had_quant_act_fp8` for gate_up, +// `gated_had_quant_fp8` for down), the bytes the expert GEMM actually contracts, and the only form +// the rotated path stores. A bf16 instantiation reads the plain activation of a bf16-served model; +// everything past the staging is shared. // -// AND A bf16 FORM BESIDE IT, for the same reason pointing the other way. A model served at bf16 -// contracts its experts against the plain bf16 activation, so that IS the operand there, and the -// bf16 instantiation reads it with no scale. Everything past the staging is shared. +// The gate_up tap is the unsorted activation. Every token is routed to exactly top_k experts, so +// the expert GEMM's input distribution gives H_sorted = top_k * H_token, and GPTQ is invariant to a +// positive scale on H (damping is a fraction of the trace, LDLQ uses ratios). Taking M token rows +// instead of M*top_k gathered ones saves a factor of top_k. // -// THE TOP-K WEIGHTING IS FREE AND THIS IS WHY THE gate_up TAP IS THE UNSORTED ACTIVATION. -// The expert GEMM reads token rows through a `sorted` index list, so its true input distribution -// is every token repeated top_k times. Every token is routed to EXACTLY top_k experts, so that -// distribution is the token distribution scaled by top_k -- H_sorted = top_k * H_token, exactly -- -// and GPTQ is invariant to a positive scale on H (the damping is a fraction of the trace and the -// LDLQ update uses ratios). So the tap takes the M token rows once and not the M*top_k gathered -// ones, at a top_k-fold saving, and loses nothing. -// -// ACCUMULATION IS f32 AND DELIBERATELY NOT f64. A block keeps its whole tile in registers across -// the M loop and touches global once, so the error over a 2048-row launch is a register tree, not -// a 2048-deep serial sum. Across launches the global f32 accumulator sees ~one add per launch. -// The consumer damps H by a percent of its trace before inverting it, which is four orders of -// magnitude above anything this rounds away; f64 would double 1.3 GB of state to buy nothing. +// Accumulation is f32, not f64: a block keeps its tile in registers across the M loop and adds to +// global once per launch. The consumer damps H by a percent of its trace, far above this rounding; +// f64 would double 1.3 GB of state. // // Returns a negative code rather than throwing, for the reason given in r4d_gemm_fp8a8.hip. @@ -43,19 +29,16 @@ namespace { -// A 64-wide C tile, 256 threads, 4x4 accumulators a thread: 16x16 threads x 16 = 4096 = 64*64. -// 64 is chosen against the SCALE GRID as much as against the register file -- a 64-column tile -// whose start is a multiple of 64 lies entirely inside one 128-wide scale group, so a row's scale -// is ONE load a tile rather than one a column. The launcher enforces that by refusing a group the -// tile does not divide. +// A 64-wide C tile, 256 threads, 4x4 accumulators per thread (16x16 threads x 16 = 64*64). A +// 64-aligned tile lies inside one scale group, so a row's scale is one load per tile; the launcher +// refuses a group the tile does not divide. constexpr int kTile = 64; constexpr int kThreads = 256; constexpr int kMB = 32; // M rows staged a pass; 2 * 32 * 64 * 4 = 16 KiB of LDS constexpr int kTT = 4; -/* BF16 reads a plain bf16 activation and no scale: a staging slot is then four elements in two - * dwords, and everything after the staging -- the tile, the accumulation order, the store -- is the - * fp8 form's. The fp8 instantiation carries none of the bf16 staging. */ +/* BF16 reads a plain bf16 activation with no scale: a staging slot is four elements in two dwords. + * Everything after the staging is shared with the fp8 form. */ template __global__ __launch_bounds__(kThreads) void gram_accum_kernel( const void* __restrict__ qv, const float* __restrict__ sc, float* __restrict__ h, @@ -78,8 +61,8 @@ __global__ __launch_bounds__(kThreads) void gram_accum_kernel( for (uint32_t m0 = 0; m0 < M; m0 += (uint32_t)kMB) { __syncthreads(); - // 32 rows x 16 dwords = 512 staging slots for 256 threads, twice, for each of the two - // tiles. A dword is four E4M3 codes and decodes in two v_cvt_pk_f32_fp8. + // 32 rows x 16 slots = 512 per tile, two per thread. An fp8 slot is a dword of four E4M3 + // codes, decoded by two v_cvt_pk_f32_fp8. for (uint32_t idx = threadIdx.x; idx < (uint32_t)(kMB * kTile / 4); idx += (uint32_t)kThreads) { const uint32_t mi = idx >> 4, cq = (idx & 15u) * 4u; @@ -103,9 +86,8 @@ __global__ __launch_bounds__(kThreads) void gram_accum_kernel( } } else { if (c1 < K) { - // The row is owned out to K rounded up to four bytes -- quant_act_fp8's - // own contract -- so a dword load at c1 < K is inside the caller's - // allocation even when the last group is ragged. + // The row is owned out to K rounded up to four bytes (quant_act_fp8's + // contract), so a dword load at c1 < K stays inside the allocation. const uint32_t w = *(const uint32_t*)((const uint8_t*)qv + qrow + c1); const float s = sc[(size_t)m * s_ld + g1]; const v2f lo = r4d_fp8::e4m3_pk(w), hi = r4d_fp8::e4m3_pk(w); @@ -139,8 +121,8 @@ __global__ __launch_bounds__(kThreads) void gram_accum_kernel( } } - // One block owns one C tile, so this read-modify-write races with nothing. It is an ACCUMULATE - // and not a store: the caller zeroes H once and then drives the whole corpus through it. + // One block owns one C tile, so the read-modify-write is race-free. The caller zeroes H once + // and accumulates the whole corpus into it. #pragma unroll for (int i = 0; i < kTT; ++i) { const uint32_t k1 = k1_0 + ty * kTT + (uint32_t)i; @@ -159,7 +141,7 @@ extern "C" int r4d_gram_accum_fp8_tile(void) { return kTile; } // q [M][K] E4M3, `q_ld` bytes a row (0 = K), owned out to a multiple of 4 // s [M][ceil(K/grp)] f32, `s_ld` elements a row (0 = ceil(K/grp)) -// h [K][K] f32, `h_ld` elements a row (0 = K) -- READ AND WRITTEN +// h [K][K] f32, `h_ld` elements a row (0 = K), read and written extern "C" int r4d_gram_accum_fp8(long q, long s, long h, int M, int K, int grp, int q_ld, int s_ld, int h_ld, long stream) { if (!q || !s || !h) return -1; @@ -179,7 +161,7 @@ extern "C" int r4d_gram_accum_fp8(long q, long s, long h, int M, int K, int grp, } // a [M][K] bf16, `a_ld` elements a row (0 = K) -// h [K][K] f32, `h_ld` elements a row (0 = K) -- READ AND WRITTEN +// h [K][K] f32, `h_ld` elements a row (0 = K), read and written extern "C" int r4d_gram_accum_bf16(long a, long h, int M, int K, int a_ld, int h_ld, long stream) { if (!a || !h) return -1; if (M <= 0 || K <= 0) return -2; @@ -203,9 +185,10 @@ extern "C" int r4d_rad_gram_accum(const RadArgs* a, RadStream s) { const RadTensor* sc = r4d_opt(a, GA_S); const RadTensor* h = r4d_opt(a, GA_H); if (!q || !sc || !h) return R4D_NO(RAD_E_INVAL); - /* ROWS ARE DIM 0 AND EVERYTHING AFTER IT IS THE ROW, the same reading r4d_rad_quant_act_fp8 - * takes: a rank-3 activation is one row a token and its K is the product of the rest. `sc` - * and `h` stay rank 2 because this op's meaning fixes them. */ + if (q->dtype != RAD_F8E4M3 || sc->dtype != RAD_F32 || h->dtype != RAD_F32) + return R4D_NO(RAD_E_DTYPE); + /* Rows are dim 0 and everything after is the row, as in r4d_rad_quant_act_fp8; `sc` and `h` + * are rank 2 by definition. */ if (q->rank < 2 || sc->rank != 2 || h->rank != 2) return R4D_NO(RAD_E_SHAPE); const long long M = q->shape[0]; if (M < 1 || r4d_numel(q) % M) return R4D_NO(RAD_E_SHAPE); @@ -225,8 +208,7 @@ extern "C" int r4d_rad_gram_accum_bf16(const RadArgs* a, RadStream s) { const RadTensor* x = r4d_opt(a, GA_Q); const RadTensor* h = r4d_opt(a, GA_H); if (!x || !h) return R4D_NO(RAD_E_INVAL); - /* No scale: the bf16 form reads the activation as it stands. One handed over anyway is a - * caller that believes the input is quantised, and it is refused rather than ignored. */ + /* A scale operand means the caller believes the input is quantised; refuse it. */ if (r4d_opt(a, GA_S)) return R4D_NO(RAD_E_INVAL); if (x->dtype != RAD_BF16 || h->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); if (x->rank < 2 || h->rank != 2) return R4D_NO(RAD_E_SHAPE); diff --git a/libr4d/r4d_had_quant_act_i8.hip b/libr4d/r4d_had_quant_act_i8.hip index 629761b3..1de75294 100644 --- a/libr4d/r4d_had_quant_act_i8.hip +++ b/libr4d/r4d_had_quant_act_i8.hip @@ -1,38 +1,28 @@ // r4d_had_quant_act_i8.hip - r4d_had_quant_act_i8: a block Hadamard along K, then per-row symmetric // int8 quantisation, written in the order r4d_gemm_w4a8_nt_m64's A fragment wants. // -// WHY THE ROTATION LIVES HERE. Plain per-token int8 activations are unusable on these models: the -// KL against the bf16 model is an order of magnitude worse than per-token e4m3. A block Hadamard -// first puts int8 several times BETTER than e4m3 instead. The mechanism is that a rotation fixes -// RANGE, not precision: int8 spends its whole grid covering a few outlier channels, and mixing each -// value with 127 others removes them. The same rotation does nothing for e4m3 -- marginally worse, -// in fact -- because four exponent bits already carry the outliers and Gaussianising does not add -// mantissa bits. +// Why the rotation: plain per-token int8 activations are unusable on these models (KL against bf16 +// an order of magnitude worse than per-token e4m3); a block Hadamard first makes int8 several times +// better than e4m3. A rotation fixes range, not precision: int8 spends its grid covering a few +// outlier channels, and mixing each value with 127 others removes them. It does not help e4m3 +// (marginally worse), whose four exponent bits already carry the outliers. It must happen before +// the absmax, since the benefit is a smaller row maximum, so it belongs in the quantiser. // -// It has to happen BEFORE the absmax, which is why it belongs in the quantiser rather than in front -// of it: the entire benefit is that the row maximum the int8 grid is scaled by gets smaller. +// The seven butterfly stages (~14 ops per element) ride on a launch the quantiser pays anyway. The +// remaining cost is one launch per rotated site per layer, which fusing into the producing RMSNorm +// or SwiGLU removes. // -// THE ROTATION IS FREE, THE LAUNCH IS NOT. A quantiser has to run either way, so seven butterfly -// stages ride along on a launch already being paid -- ~14 ops per element on a kernel that already -// touches every element twice. What costs is the number of these a decode step needs: one per -// rotated site per layer. That cost comes out by fusing the rotation into the RMSNorm or SwiGLU -// that produces the input, not by making the transform cheaper. +// Width: 128, 256 and 512 are built; 1024 is not, for sharding reasons. A rotation block cannot +// straddle a tensor-parallel boundary, so the width must divide the per-rank K, and a down_proj of +// 17408 at TP=2 is 8704 = 2^9 * 17. The weight error barely moves from 128 to 1024, so the width +// is picked on the activation's terms alone. // -// WIDTH. 128, 256 and 512 are all buildable; 1024 is NOT, and the reason is sharding rather than -// quality. A rotation block cannot straddle a tensor-parallel boundary, so the width has to divide -// the PER-RANK K, and a down_proj of 17408 at TP=2 is 8704 = 2^9 * 17. 512 divides it, 1024 does -// not. Width is nearly free to choose because the weight error barely moves across 128 through -// 1024, so it is picked on the activation's terms alone. +// The transform is in registers (r4d_fwht.h): one wave owns a `had`-wide block, and the only LDS +// traffic left is one staging write so the row absmax can see the whole row. // -// THE TRANSFORM IS IN REGISTERS, NOT LDS. See r4d_fwht.h for why staging the butterfly in LDS -// costs several times the whole quantiser. One wave owns a `had`-wide block in registers and the -// only shared traffic left is a single staging write, because the row absmax still has to see the -// whole row. -// -// NORMALISATION IS FOLDED INTO THE SCALE. The stages below compute the UNNORMALISED transform, whose -// values are sqrt(had) times the orthonormal ones. Rather than a pass to divide them, the row scale -// carries it: quantising with inv = 127/absmax_unnorm gives exactly the codes the normalised -// transform would, and S[row] = absmax_unnorm / (sqrt(had) * 127) is the scale that undoes both. +// Normalisation is folded into the scale. The stages compute the unnormalised transform (sqrt(had) +// times the orthonormal one); quantising with inv = 127/absmax_unnorm gives exactly the normalised +// codes, and S[row] = absmax_unnorm / (sqrt(had) * 127) undoes both. #include "r4d.h" #include "r4d_args.h" #include "r4d_common.h" @@ -41,12 +31,6 @@ #include #include -// 0 = choose the workgroup width from M at launch (see r4d_act_threads in r4d_common.h); a -// non-zero build-time value pins one width for every M. -#ifndef R4D_HQAI8_THREADS -#define R4D_HQAI8_THREADS 0 -#endif - template __global__ __launch_bounds__(THR) void r4d_had_quant_act_i8_kernel( const __hip_bfloat16* __restrict__ A, signed char* __restrict__ Q, float* __restrict__ S, @@ -96,10 +80,8 @@ __global__ __launch_bounds__(THR) void r4d_had_quant_act_i8_kernel( // The launch, as the plugin ABI's RadLaunchFn. See the note at the head of r4d_quant_act_i8.hip on // the argument list and the status return. // -// THE WIDTH SET IS A PROPERTY OF THIS FILE, not of the row that selects it: the rows bound the -// rotation with `had <= 512` and nothing else, and the kernel compiles exactly 128, 256 and 512. -// 1024 cannot tile a down_proj of 8704 per rank, and nothing narrower than 128 is instantiated, so -// a legal-looking 64 is refused here. +// The width set belongs to this file, not the row: the rows only bound `had <= 512`, and the kernel +// compiles exactly 128, 256 and 512, so a legal-looking 64 is refused here. enum { HQ_X = 0, HQ_Q, HQ_S }; extern "C" int r4d_rad_had_quant_act_i8(const RadArgs* args, RadStream stream) { @@ -116,11 +98,11 @@ extern "C" int r4d_rad_had_quant_act_i8(const RadArgs* args, RadStream stream) { const long long had = r4d_geti_or(args, "group", 0); if (had != 128 && had != 256 && had != 512) return R4D_NO(RAD_E_SHAPE); - // A rotation block cannot straddle a tensor-parallel shard boundary, so the PER-RANK K is what - // it has to divide -- which is why 512 is the widest that down_proj's 8704 admits. + // A rotation block cannot straddle a tensor-parallel shard, so it must divide the per-rank K + // (down_proj's 8704 admits at most 512). if (K % had) return R4D_NO(RAD_E_SHAPE); - const int thr = R4D_HQAI8_THREADS ? R4D_HQAI8_THREADS : r4d_act_threads((int)M, (int)K); + const int thr = r4d_act_threads((int)M, (int)K); const size_t shmem = (size_t)K * sizeof(float) + (thr / 32) * sizeof(float); if (shmem > 65536) return R4D_NO(RAD_E_SCRATCH); // K too large to stage in LDS const float rn = 1.f / sqrtf((float)had); @@ -128,7 +110,6 @@ extern "C" int r4d_rad_had_quant_act_i8(const RadArgs* args, RadStream stream) { dim3(T), shmem, (hipStream_t)stream, (const __hip_bfloat16*)r4d_p(x), \ (signed char*)r4d_wp(q), (float*)r4d_wp(sc), (int)K, rn) #define R4D_HQ_T(H) switch (thr) { \ - case 128: R4D_HQ_LAUNCH(H, 128); break; \ case 256: R4D_HQ_LAUNCH(H, 256); break; \ case 512: R4D_HQ_LAUNCH(H, 512); break; \ case 1024: R4D_HQ_LAUNCH(H, 1024); break; \ @@ -140,5 +121,5 @@ extern "C" int r4d_rad_had_quant_act_i8(const RadArgs* args, RadStream stream) { } #undef R4D_HQ_T #undef R4D_HQ_LAUNCH - return RAD_OK; + return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); } diff --git a/libr4d/r4d_hc_bf16.hip b/libr4d/r4d_hc_bf16.hip index 1a10f238..0614b06c 100644 --- a/libr4d/r4d_hc_bf16.hip +++ b/libr4d/r4d_hc_bf16.hip @@ -1,11 +1,11 @@ -// r4d_hc_bf16.hip -- the GATED RESIDUAL: hc_enter, hc_read and hc_write. +// r4d_hc_bf16.hip -- the gated residual (hyper-connections): hc_enter, hc_read and hc_write. // -// Qwen4-Exp carries a residual stream `hc` times the model width and has no pre-norm and no -// residual add; every block reads a data-dependent mix of the hc sub-streams and writes its output -// back into all of them with hc data-dependent gains. docs/OPS.md's three rows hold the schema and -// arch/common/rad_block_hc.h holds the composition. This file is what runs it. +// Qwen4-Exp carries a residual stream `hc` times the model width, with no pre-norm and no residual +// add: every block reads a data-dependent mix of the hc sub-streams and writes its output back into +// all of them with hc data-dependent gains. Schema: docs/OPS.md; composition: +// arch/common/rad_block_hc.h. // -// ============================== WHY hc_read IS TWO KERNELS AND NOT ONE ============================== +// ============================== hc_read is two kernels ============================== // // The read is // @@ -14,51 +14,43 @@ // x = mean_c( sigmoid(W_up @ d)[c] * N[c] ) [n] // inj = 2 * sigmoid(W_inj @ N / hc) [hc] // -// and `x` depends on ALL of `d`, so no single workgroup can produce a channel of `x` without every -// column of `d` first. A one-kernel form would need a grid-wide barrier; two kernels with the -// kernel boundary as the barrier is the same thing without cooperative launch. +// `x` depends on all of `d`, so no workgroup can produce a channel of `x` before every column of +// `d` exists. The kernel boundary serves as the grid-wide barrier, without cooperative launch. // -// WHAT DECIDES THE DECOMPOSITION IS THE WEIGHT TRAFFIC, NOT THE ARITHMETIC. At Qwen3.8-Flash-Next's -// shape (n 2560, hc 4, LR 320) the two mixing matrices are 6.55 MB each, and there are 96 -// connections -- 1.27 GB a step, which at ~600 GB/s is 2.1 ms and is the floor for ANY -// implementation. The arithmetic is 6.6M MACs a token, which is nothing. So the only thing that -// matters is that each weight byte is read ONCE per step, and that is what the grids below do: +// Weight traffic, not arithmetic, decides the decomposition. At Qwen3.8-Flash-Next's shape +// (n 2560, hc 4, LR 320) each mixing matrix is 6.55 MB and there are 96 connections: 1.27 GB per +// step, a 2.1 ms floor at ~600 GB/s, against a negligible 6.6M MACs per token. So each weight byte +// must be read once per step: // // kernel A grid (ceil(LR/64), T). A workgroup owns 64 columns of W_down and reads all of h -// once for the norm -- so h is read ceil(LR/64) times a row, 100 KB against the -// 1.3 MB of W_down the same workgroup reads, and W_down is read exactly once. -// kernel B grid (n/128, T). A workgroup owns 128 CHANNELS, which is hc*128 rows of W_up, so -// W_up is read exactly once -- and `u` is never materialised, because the workgroup -// holding all hc of a channel's rows can do the mean itself. +// for the norm, so W_down is read once and h ceil(LR/64) times per row (100 KB +// against 1.3 MB of W_down per workgroup). +// kernel B grid (n/128, T). A workgroup owns 128 channels (hc*128 rows of W_up), so W_up is +// read once, and `u` is never materialised because the workgroup holds all hc rows of +// a channel and does the mean itself. // -// The fp8 twin of `x` falls out of kernel B for free: 128 channels is exactly one 128-column scale -// group, so a workgroup owns whole groups and quantises its own with no second pass and no second -// launch. That is the whole reason the read emits it -- a separate `quant_act_fp8` at each of 96 -// connections is ~0.43 ms of pure launch overhead at this tree's ~4.5 us floor. +// 128 channels are exactly one fp8 scale group, so kernel B also quantises `x` to fp8 with no +// extra pass or launch (a separate quant_act_fp8 at 96 connections would cost ~0.43 ms of launch +// overhead). // -// THE TILED PATH KEEPS THAT PROPERTY, BUT ONLY WITH THE RIGHT TILE. Above ~8 rows the per-row -// kernels re-read both mixing matrices once a ROW, so the products run TILED -- and a tile over the -// FLATTENED channel index, 64 consecutive `j`, is 64 channels of ONE sub-stream. The four terms of -// a channel's mean then live in four different workgroups, so `u` has to be materialised into -// `ubuf` and a third kernel (`hc_mix`) has to read it back: an extra launch a connection and -// 1.28 MB of pure round trip with it. +// Tiled path: above ~8 rows the per-row kernels would re-read both matrices per row, so the +// products run tiled. A tile over the flattened channel index (64 consecutive `j`) covers one +// sub-stream, putting a channel's hc terms in different workgroups; `u` must then go through +// `ubuf` and a third kernel (`hc_mix`), costing a launch and a 1.28 MB round trip per connection. // -// `hc_up_mix_tiled_kernel` tiles over (sub-stream, channel) PAIRS instead. Same bytes of W_up, in -// hc runs of NT/hc rows rather than one run of NT, and all hc of a channel land in one workgroup -// again. What it gives up is the free fp8 twin -- a workgroup owns NT/hc = 16 channels where a -// scale group is 128 -- and an arrival counter buys that back: the last of the eight workgroups -// covering a group quantises it. Worth 1-2% of the step at multi-sequence decode, for identical -// output. At the 128-row prefill tile the same pairing is `hc_up_mix_wide_kernel`, which holds a -// channel's sub-streams in one lane's accumulators instead of in LDS. +// `hc_up_mix_tiled_kernel` instead tiles over (sub-stream, channel) pairs: the same W_up bytes in +// hc runs of NT/hc rows, with all hc terms of a channel in one workgroup. A workgroup then owns +// NT/hc = 16 channels of a 128-wide scale group, so an arrival counter lets the last of the eight +// workgroups covering a group quantise it (1-2% of the step at multi-sequence decode, same +// output). At the 128-row prefill tile the same pairing is `hc_up_mix_wide_kernel`, which keeps a +// channel's sub-streams in one lane's accumulators instead of LDS. // -// ============================== WHAT MUST MATCH THE REFERENCE ============================== +// ============================== matching the reference ============================== // -// libref/ref_hc.cpp is the oracle and three of its roundings are deliberate rather than incidental -// -- torch's grouped norm returns `.type_as(x)`, so the REFERENCE MODEL reads a bf16 N in both -// matrix products and in the final multiply. So this narrows N, narrows `d`, and narrows -// sigmoid(u) before the multiply, in the same places. The sums of squares are accumulated in f32 -// here and f64 there, which is the one difference, and it is inside any tolerance a bf16 operand -// carries. +// libref/ref_hc.cpp is the oracle. torch's grouped norm returns `.type_as(x)`, so the reference +// model reads a bf16 N in both matrix products and the final multiply. This kernel narrows N, `d` +// and sigmoid(u) in the same places. Sums of squares are f32 here and f64 there, within bf16 +// tolerance. #include #include @@ -84,19 +76,12 @@ constexpr int kDownTAMax = 64; // columns of W_down a workgroup owns, at most constexpr int kUpRows = 64; // rows of W_up a workgroup owns constexpr int kWantWG = 64; // workgroups worth launching, when the CU count cannot be read -/* WHAT THIS CALL RETURNS IS NOT THE CU COUNT. `hipDeviceProp_t::multiProcessorCount` reports WGPs - * on RDNA, and a WGP is two CUs -- the R9700 has 64 CUs in 32 WGPs, which rocminfo confirms as - * `Compute Unit: 64` -- so every grid sized from this number targets half the part. - * - * It is left reporting WGPs deliberately, because the number it feeds is a FLOOR on how many - * workgroups are worth launching, and doubling that floor here would be a guess. On this kernel a - * grid of 40, 80 and 160 all measure the same, so the block count is not what binds, and halving - * `ta` only doubles the redundant work: each workgroup re-reads all of `h` and all of the norm - * weight (60 KiB at this model's shape) before touching its own columns of W_down. At ta=4 that is - * 4.8 MB of re-read against 6.55 MB of weight; at ta=8, 2.4 MB. - * - * A kernel that IS short of blocks on this part should double the number at its own call site - * rather than re-titling it here. */ +/* Returns WGPs, not CUs: `hipDeviceProp_t::multiProcessorCount` reports WGPs on RDNA, two CUs + * each (the R9700 has 64 CUs in 32 WGPs). Left as is on purpose: it is a floor on workgroups worth + * launching, and here grids of 40, 80 and 160 perform the same. Halving `ta` only doubles redundant + * work, since each workgroup re-reads all of `h` and the norm weight (60 KiB here) before its own + * W_down columns (4.8 MB of re-read at ta=4, 2.4 MB at ta=8). A kernel short of blocks should + * double the number at its own call site. */ static inline int want_wg() { static const int v = [] { int dev = 0; @@ -110,21 +95,17 @@ static inline int want_wg() { constexpr int kUpTB = 128; // CHANNELS a workgroup owns -- and one fp8 scale group constexpr int kFp8Grp = 128; -#ifndef R4D_HC_DOT_U -#define R4D_HC_DOT_U 4 // 512-byte loads a wave keeps in flight over a long weight row -#endif -constexpr int kDotU = R4D_HC_DOT_U; +constexpr int kDotU = 4; // 512-byte loads a wave keeps in flight over a long weight row __device__ __forceinline__ float sigmoidf_(float v) { return 1.0f / (1.0f + __expf(-v)); } __device__ __forceinline__ float siluf_(float v) { return v * sigmoidf_(v); } __device__ __forceinline__ float nbf(float v) { return bf2f(f2bf(v)); } -/* BF16 IN WHOLE REGISTERS. gfx12's compiler holds a 16-bit value in a register HALF: eight f2bf - * results written through a union of shorts are eight half moves before the pack, and a short - * loaded on its own is a d16 load that leaves the register's other half live, so it waits on that - * register's last write. These keep every value 32 bits wide -- pairs packed with f2bf2, whose - * rounding is f2bf's, a pair word's halves read with a shift and a mask, a lone bf16 loaded - * zero-extended -- and give the same bits. */ +/* bf16 in whole registers. gfx12's compiler holds a 16-bit value in a register half: shorts written + * through a union cost a half move each before the pack, and a lone d16 load leaves the other half + * live, waiting on that register's last write. These helpers keep values 32 bits wide (pairs packed + * with f2bf2, same rounding as f2bf; halves read by shift and mask; lone bf16 loaded zero-extended) + * and give the same bits. */ __device__ __forceinline__ uint4 f2bf8(const float (&f)[8]) { return make_uint4(f2bf2(f[0], f[1]), f2bf2(f[2], f[3]), f2bf2(f[4], f[5]), f2bf2(f[6], f[7])); } @@ -136,18 +117,17 @@ __device__ __forceinline__ void bf8_f(r4d_u32x4 v, float (&f)[8]) { f[0] = bf16w_lo(v.x); f[1] = bf16w_hi(v.x); f[2] = bf16w_lo(v.y); f[3] = bf16w_hi(v.y); f[4] = bf16w_lo(v.z); f[5] = bf16w_hi(v.z); f[6] = bf16w_lo(v.w); f[7] = bf16w_hi(v.w); } -/* Read through a GLOBAL pointer: through a generic one the load is still flat_load_d16_b16. */ +/* Read through a global pointer; through a generic one the load is still flat_load_d16_b16. */ typedef __attribute__((address_space(1))) const unsigned short* hc_gu16; __device__ __forceinline__ uint32_t bfw(const unsigned short* p) { return *(hc_gu16)p; } __device__ __forceinline__ float bfw_f(uint32_t w) { return __uint_as_float(w << 16); } -/* ---- THE E4M3 MIXING MATRICES (r4d_hc_fp8.h) ------------------------------------------------ +/* ---- E4M3 mixing matrices (r4d_hc_fp8.h) ------------------------------------------------ * - * Every kernel below that reads mix_down or mix_up has an F8 form, selected by the stored dtype: - * a row is its codes and then its f32 group scales, `ld` bytes from the next. The per-row kernels - * multiply codes in f32 and apply a group's scale to that group's partial sum; the tiled ones - * decode into their bf16 staging tile, scale applied, and keep the bf16 WMMA. Nothing else about a - * kernel changes, and the bf16 form of each is compiled from the same text with F8 false. */ + * Every kernel reading mix_down or mix_up has an F8 form, selected by the stored dtype: a row is + * its codes then its f32 group scales, `ld` bytes apart. Per-row kernels multiply codes in f32 and + * scale each group's partial sum; tiled kernels decode into their bf16 staging tile with the scale + * applied and keep the bf16 WMMA. The bf16 form compiles from the same text with F8 false. */ /* Eight E4M3 codes, two dwords of them, to f32 in order: v_cvt_pk_f32_fp8, two a time. */ __device__ __forceinline__ void e4m3x8(uint32_t lo, uint32_t hi, float* f) { @@ -179,12 +159,10 @@ __device__ __forceinline__ uint4 e4m3x8_bf16(const unsigned char* __restrict__ c return f2bf8(f); } -/* A WAVE'S DOT OF THE NATURAL-ORDER LDS VECTOR WITH ONE E4M3 ROW OF mix_down. A lane takes - * SIXTEEN consecutive codes of every 512-element step -- one 16-byte load, so a wave's request is - * 512 bytes as the bf16 dots' are; at eight codes a lane it would be 256, twice the requests for - * the same bytes. Sixteen share one 128-group, whose scale multiplies the lane's - * partial sum for the step. kU steps are loaded before the first is summed. K is a multiple of - * 512. */ +/* A wave's dot of the natural-order LDS vector with one E4M3 row of mix_down. A lane takes sixteen + * consecutive codes of every 512-element step (one 16-byte load, so a wave requests 512 bytes like + * the bf16 dots). The sixteen share one 128-group, whose scale multiplies the lane's partial sum + * for the step. kU steps are loaded before the first is summed. K is a multiple of 512. */ constexpr long kHc8Step = kWave * 16; __device__ __forceinline__ float hc8_dot16(const unsigned short* __restrict__ sv, uint4 c) { @@ -228,10 +206,10 @@ __device__ __forceinline__ float hc8_dot_down(const unsigned short* __restrict__ return acc; } -/* ONE THREAD'S QUARTER OF AN E4M3 ROW OF mix_up against RG rows of `d` in LDS. The quarter is the - * row's scale group (r4d_hc8::up_group), so its partial sums are complete before the scale is - * applied and four threads' sums make the row. All of a quarter's sixteen-code loads are issued - * before the first is used: at lowrank 320 that is five of them, and kMaxQ bounds it at 512. */ +/* One thread's quarter of an E4M3 row of mix_up against RG rows of `d` in LDS. The quarter is the + * row's scale group (r4d_hc8::up_group), so its partial sums are complete before scaling, and four + * threads' sums make the row. All of a quarter's sixteen-code loads issue before the first is used + * (five at lowrank 320); kUpMaxQ bounds lowrank at 512. */ constexpr int kUpMaxQ = 8; template __device__ __forceinline__ void hc8_dot_up(const float* __restrict__ sd, long lr, @@ -268,16 +246,15 @@ __device__ __forceinline__ void hc8_dot_up(const float* __restrict__ sd, long lr } } -/* ON THE VALU, NOT THE LDS CROSSBAR -- r4d_common.h has the measurement. It matters here because - * the norm prologue reduces `hc + 1` accumulators back to back and `hc` is a runtime bound, so the - * five exchanges of each are one dependency chain of five times `hc + 1`. Bit-identical: the same - * lanes in the same order. */ +/* On the VALU, not the LDS crossbar (r4d_common.h). The norm prologue reduces `hc + 1` + * accumulators back to back with a runtime `hc`, so the exchanges form one long dependency chain. + * Bit-identical: same lanes, same order. */ __device__ __forceinline__ float wave_sum(float v) { return r4d_wave_sum(v); } /* ============================================================== hc_enter * - * h[c][i] = x[i], for every stream. One launch a step, and it is its own op because the embedding - * lookup's weight is [vocab, n] -- a wide output would be a different weight shape. */ + * h[c][i] = x[i] for every stream. One launch per step; its own op because the embedding lookup's + * weight is [vocab, n] and a wide output would need a different weight shape. */ __global__ __launch_bounds__(kThreads) void hc_enter_kernel(const unsigned short* __restrict__ x, unsigned short* __restrict__ h, long rows, long n, int hc, long xrow, long hrow) { @@ -291,20 +268,18 @@ void hc_enter_kernel(const unsigned short* __restrict__ x, unsigned short* __res } } - /* ============================================================== hc_write * - * h[c][i] += inj[c] * y[i]. In place, on the UNNORMED stream -- the read's normalisation is - * consumed by the block input and the gates and never enters the residual. */ + * h[c][i] += inj[c] * y[i], in place on the unnormed stream: the read's normalisation feeds the + * block input and gates only, never the residual. */ __global__ __launch_bounds__(kThreads) void hc_write_kernel(const unsigned short* __restrict__ y, const unsigned short* __restrict__ inj, unsigned short* __restrict__ h, long rows, long n, int hc, long yrow, long irow, long hrow) { const long r = blockIdx.y; if (r >= rows) return; - /* THROUGH LDS AND NOT A REGISTER ARRAY. `hc` is a runtime value, so `g[c]` in the inner loop - * is a dynamic index into private memory -- which the compiler spills to scratch, turning a - * four-element broadcast into a per-element memory round trip. */ + /* Gains go through LDS, not a register array: with a runtime `hc`, `g[c]` would be a dynamic + * private index, which the compiler spills to scratch. */ __shared__ float s_g[kHcMax]; if ((int)threadIdx.x < hc) s_g[threadIdx.x] = bf2f(inj[r * irow + threadIdx.x]); __syncthreads(); @@ -319,46 +294,30 @@ void hc_write_kernel(const unsigned short* __restrict__ y, const unsigned short* } } -/* A WAVE'S DOT PRODUCT OF THE LDS VECTOR WITH A CONTIGUOUS bf16 ROW, at 512 bytes a load and in - * the ORDER THE SCALAR FORM SUMMED IN. +/* A wave's dot product of the LDS vector with a contiguous bf16 row, using 512-byte loads but + * summing in the scalar form's order. * - * `for (j = lane; j < HN; j += kWave)` is one 64-BYTE load a wave instruction -- a quarter of what - * the memory system wants -- and it reaches 219 GB/s on a shape where the lm head gets 631 out of - * the same part. Eight CONTIGUOUS bf16 a lane is 512 bytes and reaches 554, but it changes which - * j's a lane owns, and therefore the last bit of every output the kernel writes. + * A strided `j = lane` loop issues 64-byte loads per wave instruction (219 GB/s here, against 631 + * for the lm head). Eight contiguous bf16 per lane (512 bytes) reaches 554 but changes which j a + * lane owns, and so the last bit of every output. So the wide load is staged through LDS and each + * lane reads back its strided subset, ascending (lane L sums j = L, L+32, ...). This is also + * faster than reordering j (8.9 us vs 9.0, scalar 29.9), whose lanes conflict on `sN`'s banks. + * `stage` is this wave's own 256-entry slot, so no barrier is needed: a wave's LDS operations + * complete in order. * - * So the wide load goes THROUGH LDS and each lane reads back exactly the strided subset it would - * have loaded itself, ascending: lane L still sums j = L, L+32, L+64, ... The transpose costs - * nothing and in fact wins -- 8.9 us, against 9.0 for simply reordering which j a lane owns and - * 29.9 for the scalar form -- because the reordered form's lanes fight over the same LDS banks - * for `sN` where these do not. - * `stage` is this wave's own 256-entry slot, so the round trip needs no barrier: a wave's LDS - * operations complete in order and no other wave reads it. - * - * The unaligned row falls back to the scalar loop rather than being refused -- the fast path needs - * the row 16-byte aligned, which is the base and `HN % 8` together. */ + * An unaligned row (base or `HN % 8`) falls back to the scalar loop. */ __device__ __forceinline__ float sv_at(const unsigned short* p, long i) { return bf2f(p[i]); } __device__ __forceinline__ float sv_at(const float* p, long i) { return p[i]; } -/* `kU` IS HOW MANY LOADS A WAVE HAS IN FLIGHT, and it is the whole performance of kernel A. +/* `kU` is how many loads a wave keeps in flight, which sets kernel A's speed. With one load per + * iteration the global latency is fully exposed: 40 workgroups of 8 waves keep only 320 x 512 B in + * flight, 258 GB/s, while kernel B reaches 504 GB/s on the same bytes because each wave owns eight + * rows. Block count (40 to 160) makes no difference; depth does. So kU loads are issued into + * registers first (back-to-back global_load_dwordx4), then walked through LDS one at a time. * - * The staged form above issues ONE 512-byte load and then immediately reads the staged bytes back - * out of LDS, so the global latency is exposed in full on every iteration -- a wave is never - * waiting on more than one load. Kernel A runs 40 workgroups of 8 waves, so that is 320 loads of - * 512 bytes in flight against a part that needs some hundreds of KiB to stay fed, which is - * 25.4 us for 6.55 MB, or 258 GB/s. Kernel B moves the SAME 6.55 MB in 13.0 us (504 GB/s) purely - * because its waves each own eight rows and so have eight loads outstanding. - * - * So the lever is not a wider load, a bigger grid or fewer workgroups -- every block count from 40 - * to 160 lands within 0.2 us of the others. It is depth: issue kU loads into registers FIRST, where - * they have no dependency on each other and the compiler emits kU back-to-back global_load_dwordx4, - * and only then walk them through LDS one at a time. - * - * BIT-IDENTICAL, and that is why the staging slot is not replicated kU times. Lane L still sums - * j = L, L+32, ... within a 256-element chunk and still takes the chunks in ascending order; only - * when the bytes ARRIVE moves. One slot reused kU times costs kU ordered LDS round trips, ~100 - * cycles each, which is what the one global latency already cost -- and replicating the slot would - * take kernel A's LDS from 25 KiB to 37 KiB and halve the workgroups a CU can hold. */ + * Bit-identical: the summation order is unchanged, only arrival time moves. The staging slot is + * reused kU times (kU ordered LDS round trips, ~100 cycles each) rather than replicated, which + * would raise kernel A's LDS from 25 to 37 KiB and halve its occupancy. */ template __device__ __forceinline__ float wave_dot_lds(const SV* __restrict__ sv, const unsigned short* __restrict__ wr, long HN, @@ -397,64 +356,29 @@ __device__ __forceinline__ float wave_dot_lds(const SV* __restrict__ sv, return acc; } -/* N IS HELD IN LDS TRANSPOSED WITHIN EACH 256-ELEMENT CHUNK, AND THAT IS WORTH A THIRD OF KERNEL A. +/* Swizzled form: N is held in LDS transposed within each 256-element chunk, and the weight is + * transposed by the load. * - * `wave_dot_lds` above reads the STAGED WEIGHT out of LDS strided -- lane L takes jj = L, L+32, - * ... -- because that is the summation order and it is not negotiable. It reads `sv`, the LDS copy - * of N, at the SAME strided addresses, and that one is free to move: N is written by this kernel, - * so the layout is ours to pick. + * wave_dot_lds reads N at strided addresses (lane L takes L, L+32, ...). A strided 16-bit LDS read + * puts 32 lanes on 16 banks, two cycles for half a cycle's bytes; with the weight's matching reads + * the inner loop is 228 instructions for 32 lane-FMAs, and the kernel is issue-bound (M=1 at + * 6.55 MB and M=4 at 26.2 MB both take 18.7 us). * - * A strided 16-bit LDS read is the worst access this part has. `ds_load_u16 v, v6 offset:64*t` - * gives lane L the address 2L + 64t: thirty-two lanes land in sixteen of the thirty-two four-byte - * banks, two lanes a bank, so the instruction takes two LDS cycles and returns 64 of the 128 bytes - * a cycle is worth. Eight of them a chunk, for N, and eight more for the weight. Disassembled at - * this model's shape the inner loop is 228 instructions for 32 lane-FMAs -- 64 ds_load_u16, 42 - * v_lshlrev_b32 (which is what bf2f is) and 60 VALU -- and at 84 blocks that is ~24k cycles a - * compute unit, which IS the 18.7 us the kernel traces. THE KERNEL IS ISSUE-BOUND, NOT BANDWIDTH- - * BOUND, and the evidence is that M=1 reading 6.55 MB and M=4 reading 26.2 MB both take 18.7 us. + * N layout: within a 256-element chunk, logical p is stored at physical (p % 32) * 8 + (p / 32), + * so lane L's eight elements are one conflict-free ds_load_b128. Requires n % 256 == 0 so a chunk + * never straddles a sub-stream; otherwise the plain layout and loop are used (the `swz` flag). + * Whoever writes N pays: a plain staged copy transposed in LDS would be an 8-way conflict, so + * staging and rescale are one pass in which a thread reads its eight `h` and `w` from global and + * writes one ds_store_b128. The sum of squares then reads `h` from global (20 KiB a block against + * 320 KiB of W_down). Its order is unchanged: thread tid accumulates i = tid, tid + 256, ... * - * So store N so that the eight elements ONE LANE WANTS ARE CONTIGUOUS. Inside a chunk of kPer = - * 256, logical element p goes to physical (p % 32) * 8 + (p / 32); lane L's eight then sit at - * physical L*8 .. L*8+7, which is one 16-byte `ds_load_b128` at a 16-byte-aligned address, no - * conflict, four cycles for the whole 512-byte chunk. Eight ds_load_u16 become one ds_load_b128. + * Weight: `global_load_tr_b128` (r4d_common.h) gives lane j of each 8-lane group element j from + * all eight lanes' addresses. With L = 8g + i naming `wr + j + 8g + 32i`, lane L receives elements + * L, L+32, ... L+224 in ascending order, all 16-byte aligned (`swz` requires `down` aligned). This + * removes the staging store and eight conflicting ds_load_u16 per chunk; no `stage` slot is used. * - * BIT-IDENTICAL, and that is the point: lane L still multiplies N[j + L + 32t] by W[j + L + 32t] - * for t ascending, still sums into its own scalar, and the chunks still ascend. ONLY THE ADDRESS - * THE VALUE IS FETCHED FROM MOVES. The chunk is 256 and never straddles a sub-stream because - * n % 256 == 0 is a condition of the path; when it does not hold the kernel keeps the plain layout - * and the plain loop, which is what the `swz` flag below selects. - * - * THE COST LANDS ON WHOEVER WRITES N, and it is why there is no raw copy of `h` into LDS. Writing - * the transpose out of a plain staged copy would be eight 2-byte LDS stores at stride 16, an - * EIGHT-way conflict -- worse than what it saves. So the staging and the rescale are ONE pass: - * a thread owns one (chunk, lane) group, reads its eight `h` and eight `w` straight from global - * where both are still coalesced across the wave, and writes the group with a single - * ds_store_b128. That is fewer instructions than a copy-then-rescale, and it costs one extra pass - * over `h` (20 KiB a block, against the 320 KiB of W_down the same block reads) because the sum of - * squares has no LDS copy to read and takes `h` from global instead. - * The reduction's order is untouched: thread tid still accumulates i = tid, tid + 256, ... */ + * Bit-identical: lane L multiplies the same elements in the same order; only addresses move. */ template -/* AND THE WEIGHT IS TRANSPOSED BY THE LOAD, WHICH RETIRES THE STAGING SLOT ALTOGETHER. - * - * The bank-conflict argument above rules out doing the weight's transpose IN LDS, and nothing - * more. `global_load_tr_b128` does it in the LOAD instead: the eight lanes of a group each name an - * address and lane j receives element j from all eight of them (r4d_common.h, and three attention - * kernels already read V that way). - * - * THE ADDRESS THAT MAKES IT THE RIGHT TRANSPOSE. Lane L must own the chunk's elements L, L+32, - * ... L+224 -- that is the summation order and it is not negotiable. Write L = 8g + i; if lane L - * names `wr + j + 8g + 32i`, then lane 8g+j receives { wr[j + 8g + j' + 32i] : i = 0..7 } for its - * own j' = L % 8, which is exactly elements L, L+32, ... in ascending order. Every address is - * 16-byte aligned because j is a multiple of kPer, 8g and 32i are multiples of 8, and `swz` - * already requires `down` itself to be. - * - * WHAT IT REMOVES: one 16-byte LDS store and EIGHT `ds_load_u16` a chunk, the eight being a - * two-way bank conflict (lane L reads byte 2L + 64t, so thirty-two lanes land in sixteen banks) -- - * about sixteen of the twenty LDS cycles a chunk that remain once N is one `ds_load_b128`. This - * path takes no `stage` slot at all. - * - * BIT-IDENTICAL: lane L multiplies the same N element by the same weight element in the same - * order into the same scalar. Only where the weight arrives from moves. */ __device__ __forceinline__ float wave_dot_swz(const unsigned short* __restrict__ sv, const unsigned short* __restrict__ wr, long HN, int lane) { @@ -489,37 +413,31 @@ __device__ __forceinline__ float wave_dot_swz(const unsigned short* __restrict__ /* ============================================================== mtp_enter * - * THE MULTI-TOKEN-PREDICTION HEAD'S ENTRY, and it is in this file because it is the same shape of - * problem as hc_read: a wide stream, a grouped norm over it, and a matvec whose weight is the only - * traffic that matters. + * The multi-token-prediction head's entry. It lives here because it has hc_read's shape: a wide + * stream, a grouped norm over it, and a matvec whose weight dominates traffic. * * ne[j] = e[j] * rsqrt(mean(e^2) + eps) * (w_e[j] + wadd) * fe[i] = fc_e[i] . ne * nh[k][j] = h[k*n+j] * rs[k] * (w_h[k*n+j] + wadd) rs[k] over sub-stream k * x[k*n+i] = fc_h[i] . nh[k] + fe[i] for each of the hc sub-streams * - * WHAT DECIDES THE DECOMPOSITION IS THAT fc_h[i] IS READ ONCE AND USED hc TIMES. The two square - * matrices are 13.1 MB at this model's shape and a draft round issues this once, so the arithmetic - * (hc + 1 dots of 2560 per output channel) is free and the weight bytes are the whole cost. A - * workgroup therefore owns kOutTB output CHANNELS, stages `nh` and `ne` in LDS, and walks each - * weight row ONCE with hc accumulators live -- the alternative, hc calls to wave_dot_lds over the - * same row, would read fc_h four times and quadruple the only traffic there is. + * fc_h[i] is read once and used hc times. The two square matrices are 13.1 MB here and the + * arithmetic is negligible, so a workgroup owns kMtpOutTB output channels, stages `nh` and `ne` in + * LDS, and walks each weight row once with hc accumulators live (hc separate dots would read fc_h + * hc times). * - * The norms are recomputed by every workgroup, which is 25 KB of `h` and `e` against the 327 KB of - * weights the same workgroup reads -- 7.6%, and the alternative is a second launch and a scratch - * buffer for five scalars. */ + * Every workgroup recomputes the norms: 25 KB of `h` and `e` against its 327 KB of weights, + * cheaper than a second launch and a scratch buffer for five scalars. */ constexpr int kMtpOutTB = 32; // output channels a workgroup owns: 80 blocks at n = 2560 -/* Above this many rows the tiled form below wins, and at one row it cannot -- the per-row kernel - * already reads the weight once there and is the floor. From two rows up the tiled form is never - * worse in step time and the kernel itself is up to 2.7x faster a call; at high concurrency the - * step is flat only because the device is not fully busy there. */ +/* From this many rows the tiled form is used: at one row the per-row kernel reads the weight once + * and is the floor; from two rows the tiled form is never worse per step and up to 2.7x faster per + * call. */ constexpr long kMtpTileMinRows = 2; -/* `nh` + `ne` in LDS, in elements. 64 KiB less the staging slots and the reduction planes. */ +/* `nh` + `ne` in LDS, in elements: 64 KiB less the staging slots and reduction planes. */ constexpr long kMtpLdsMaxN = 28672; -/* One pass over a weight row with hc accumulators live, staged through LDS exactly as - * wave_dot_lds does and for the same reason -- a 16-byte lane load reorders which j a lane owns, - * and that changes the last bit of the sum. Lane L still sums j = L, L+32, L+64, ... */ +/* One pass over a weight row with hc accumulators live, staged through LDS as in wave_dot_lds to + * keep the summation order (lane L sums j = L, L+32, ...). */ template __device__ __forceinline__ void wave_dot_hc(const unsigned short* __restrict__ sv, long svstride, int hc, const unsigned short* __restrict__ wr, long n, @@ -565,21 +483,16 @@ __device__ __forceinline__ void wave_dot_hc(const unsigned short* __restrict__ s } } -/* BOTH WEIGHT ROWS OF ONE OUTPUT CHANNEL IN ONE PASS, over `nh` and `ne` held TRANSPOSED within - * each 256-element chunk as wave_dot_swz reads N: a lane's eight elements of a chunk are one - * ds_load_b128 a stream, and each weight row arrives transposed by global_load_tr_b128. The fc_h - * row feeds the hc stream accumulators off one load and the fc_e row feeds `ae`, and all 2 kU loads - * of an iteration are issued before the first is read. +/* Both weight rows of one output channel in one pass, over `nh` and `ne` held transposed per + * 256-element chunk as in wave_dot_swz: a lane's eight elements are one ds_load_b128 per stream, + * and each weight row arrives transposed by global_load_tr_b128. The fc_h row feeds the hc stream + * accumulators, the fc_e row feeds `ae`; all 2*kU loads of an iteration issue before the first is + * read. * - * wave_dot_hc and wave_dot_lds, the plain-layout pair, stage each weight load through LDS and read - * it and every stream back with strided 16-bit LDS loads -- two-way bank conflicts, 41 LDS - * instructions a chunk for 40 lane-FMAs, and an accumulator array indexed by the runtime `hc`, - * which is private memory. Here a chunk is hc + 1 conflict-free LDS loads, and the accumulators - * are unrolled over kHcMax with the stream count as a guard, so they stay in registers. - * - * BIT-IDENTICAL to that pair: each accumulator still sums elements L, L + 32, ... L + 224 of each - * chunk, chunks ascending, each product the stream value times the weight. That the fc_e dot - * interleaves with the fc_h ones changes no accumulator's own sequence. */ + * The plain-layout pair (wave_dot_hc, wave_dot_lds) uses conflicting strided 16-bit LDS reads and + * an accumulator array indexed by runtime `hc` (private memory). Here a chunk is hc + 1 + * conflict-free loads and the accumulators are unrolled over kHcMax with a guard, so they stay in + * registers. Bit-identical to that pair: each accumulator's summation order is unchanged. */ template __device__ __forceinline__ void wave_dot_mtp_swz(const unsigned short* __restrict__ snh, const unsigned short* __restrict__ sne, @@ -652,16 +565,14 @@ void mtp_enter_kernel(const unsigned short* __restrict__ h, const unsigned short const int wave = tid / kWave; const int lane = tid % kWave; - /* ---- the sums of squares. One partial a sub-stream plus the embedding's, in one pass over - * both rows -- and the FLAT reading is the same partials added together, which is why `flat` - * costs a branch here and nothing anywhere else. */ + /* ---- sums of squares: one partial per sub-stream plus the embedding's, in one pass. The + * `flat` norm adds the same partials together. */ float part[kHcMax]; #pragma unroll for (int c = 0; c < kHcMax; ++c) part[c] = 0.0f; float pe = 0.0f; - /* kSsIter ITERATIONS' LOADS ARE ISSUED BEFORE THE FIRST IS SUMMED. One iteration at a time, - * each of a thread's ten iterations waits out a load latency before the next is asked for; - * this way two do. Same elements, same order into the same accumulators. */ + /* kSsIter iterations' loads issue before the first is summed, so a thread's ten iterations + * wait out two load latencies instead of ten. Same elements, same order. */ constexpr int kSsIter = 5; long i = tid; for (; i + (long)(kSsIter - 1) * kThreads < n; i += (long)kSsIter * kThreads) { @@ -719,21 +630,19 @@ void mtp_enter_kernel(const unsigned short* __restrict__ h, const unsigned short } __syncthreads(); - /* THE TRANSPOSED LAYOUT, WHEN THE SHAPE ALLOWS IT -- the same condition hc_read_a states: - * every 256-element chunk inside one stream, and every weight row 16-byte aligned for the - * transposing load. Otherwise the plain layout and the plain loop; both write the same values. */ + /* Transposed layout when the shape allows (as in hc_read_a): every 256-element chunk inside + * one stream and every weight row 16-byte aligned. Otherwise the plain layout; both write the + * same values. */ constexpr long kPer = kWave * 8; const bool swz = (n % kPer == 0) && (((uintptr_t)fch & 15u) == 0u) && (((uintptr_t)fce & 15u) == 0u); - /* ---- the normed vectors, staged bf16. Both are read hc + 1 times below and are what makes - * one pass over each weight row enough. */ + /* ---- the normed vectors, staged bf16, so one pass over each weight row suffices. */ { const float rse = s_rse; if (swz) { /* A thread owns one (chunk, lane) group: logical elements lane + 32t of its chunk, - * written as one 16-byte store at physical lane * 8. The reads stay coalesced across - * the wave; see hc_read_a's build for why the transpose is done here and not in LDS. */ + * written as one 16-byte store at physical lane * 8 (see wave_dot_swz). */ const int lane8 = tid & (kWave - 1); for (int c = -1; c < hc; ++c) { const unsigned short* src = c < 0 ? ep : hp + (long)c * n; @@ -766,7 +675,7 @@ void mtp_enter_kernel(const unsigned short* __restrict__ h, const unsigned short } __syncthreads(); - /* ---- the output channels this workgroup owns: one weight row read, hc + 1 dots off it. */ + /* ---- this workgroup's output channels: one weight row read, hc + 1 dots from it. */ const long i0 = (long)blockIdx.x * kMtpOutTB; for (int t = wave; t < kMtpOutTB; t += kWaves) { const long i = i0 + t; @@ -789,28 +698,22 @@ void mtp_enter_kernel(const unsigned short* __restrict__ h, const unsigned short } } -/* THE STATIC LDS kernel A declares beside N: the reduction planes and the staging slots. The - * dynamic allocation for N has to fit in what is left of the workgroup's 64 KiB, so the launcher's - * bound on hc * n is taken from this number, and the kernel asserts it matches its declarations. */ +/* Kernel A's static LDS beside N (reduction planes and staging slots). N's dynamic allocation must + * fit in the rest of 64 KiB, so the launcher bounds hc * n with this; the kernel asserts it. */ constexpr long kHcReadAStaticLds = (long)(kWaves * kHcMax + kHcMax) * (long)sizeof(float) + (long)kWaves * kWave * 8 * (long)sizeof(unsigned short); /* ============================================================== hc_read, kernel A * - * The grouped norm, then `d = silu(W_down @ N / hc)` for this workgroup's `ta` columns. Workgroup - * 0 also produces the hc inject gains and publishes the per-stream norm scales for kernel B, which - * cannot recompute them: kernel B reads only its own 128 channels of `h` and a stream's scale is a - * reduction over all n of them. + * The grouped norm, then `d = silu(W_down @ N / hc)` for this workgroup's `ta` columns. One + * workgroup also produces the hc inject gains and publishes the per-stream norm scales for kernel + * B, which reads only its own 128 channels of `h` and so cannot recompute them. * - * LDS holds N as bf16 -- HN * 2 bytes, 20 KiB at this model's shape -- which is what lets the - * columns share one pass over `h` and one grouped reduction. It is held TRANSPOSED inside each - * 256-element chunk; wave_dot_swz above is the whole argument for that, and it is the difference - * between eight conflicted 16-bit LDS reads a chunk and one ds_load_b128. */ -/* THE WAVES A SIMD: nine for the E4M3 dot, the budget it was tuned at. Left to choose, LLVM 24 - * builds it at 120 VGPRs for twelve waves, which costs 11% at four rows and 20% at seven with the - * weight read cold -- the shapes a speculative decode step runs. The bf16 form keeps the full - * range, which is what it is built at without the attribute; pinning it to sixteen changes its - * code. */ + * LDS holds N as bf16 (HN * 2 bytes, 20 KiB here), so the columns share one pass over `h` and one + * grouped reduction. It is transposed per 256-element chunk; see wave_dot_swz. */ +/* Waves per SIMD: nine for the E4M3 dot, as tuned. Unconstrained, LLVM 24 builds it at 120 VGPRs + * for twelve waves, 11-20% slower at the 4-7 rows of a speculative decode step. The bf16 form keeps + * the full range; pinning it would change its code. */ template __global__ __launch_bounds__(kThreads) __attribute__((amdgpu_waves_per_eu(F8 ? 9 : 1, F8 ? 9 : 16))) @@ -824,8 +727,7 @@ void hc_read_a_kernel(const unsigned short* __restrict__ h, const float* __restr extern __shared__ unsigned short sN[]; /* [hc * n], transposed per 256-element chunk */ __shared__ float s_part[kWaves][kHcMax]; __shared__ float s_scale[kHcMax]; - /* One 256-entry staging slot a wave, for the dot above. 4 KiB, and no barrier: a wave writes - * and reads only its own. */ + /* One 256-entry staging slot per wave (4 KiB); no barrier, a wave uses only its own. */ __shared__ unsigned short s_stage[kWaves][kWave * 8]; static_assert(sizeof(s_part) + sizeof(s_scale) + sizeof(s_stage) == kHcReadAStaticLds, "the launcher sizes N's allocation against this kernel's static LDS"); @@ -835,74 +737,31 @@ void hc_read_a_kernel(const unsigned short* __restrict__ h, const float* __restr const long r = blockIdx.y; if (r >= rows) return; const long HN = (long)hc * n; - /* THE INJECT GAINS GET A BLOCK OF THEIR OWN, AND THAT IS A LOAD-BALANCE REQUIREMENT, NOT - * TIDINESS. - * - * Putting them on block 0, which also owns `ta` columns of W_down, is what a naive layout - * does. With ta at kWaves the column loop gives every wave exactly one dot product over HN -- - * except on that block, where waves 0..hc-1 would do a SECOND one for the gains. A kernel - * takes as long as its slowest block, so one block at 2x sets the duration of all of them, and - * the kernel runs over three times the matvec's own cost at this shape. - * - * The grid is one wider instead and the last block owns no columns, so every wave in the - * kernel does one dot. The output does not move -- the gains and the published scales are the - * same arithmetic on the same bytes, and only which block does it changes. */ + /* The inject gains get a block of their own for load balance. With ta = kWaves every wave does + * one dot over HN; adding the gains to a column-owning block would give its waves a second + * one, and that slowest block would set the kernel's duration. So the grid is one wider and + * the last block owns no columns. */ const bool pub = (blockIdx.x == gridDim.x - 1); const int tid = threadIdx.x, lane = tid & (kWave - 1), wave = tid / kWave; const unsigned short* hp = h + r * hrow; const unsigned short* __restrict__ down = (const unsigned short*)downv; - /* THE TRANSPOSED LAYOUT IS A PROPERTY OF THE SHAPE, NOT A SWITCH. It needs the chunk to sit - * inside one sub-stream (n % 256) and every 16-byte group to be aligned in LDS and in `h`. A - * model that does not satisfy it keeps the plain layout and the plain loop; nothing else in - * the kernel changes, and both write the same N. */ - /* The E4M3 dot reads N in its natural order, eight consecutive elements a lane, so the - * transposed layout is a bf16 form's alone. */ + /* The transposed layout follows from the shape: the chunk must sit inside one sub-stream + * (n % 256) and every 16-byte group be aligned in LDS and in `h`; otherwise the plain layout, + * with the same N. The E4M3 dot reads N in natural order, so only the bf16 form transposes. */ const bool swz = !F8 && (n % kPer == 0) && (((uintptr_t)hp & 15u) == 0u) && (((uintptr_t)down & 15u) == 0u) && (!injw || ((uintptr_t)injw & 15u) == 0u); - /* ---- the sums of squares, one stream at a time, straight from `h`. */ - /* ONE STREAM AT A TIME, which keeps the accumulator a SCALAR. Summing all hc at once needs an - * accumulator indexed by `j / n`, and `hc` is a runtime value -- so that array lives in - * scratch memory and every element of the row pays a private-memory round trip. */ - /* THE PREFETCH DEPTH IS THE POINT OF THE LOOP, and it is worth more than its byte count - * suggests. This moves 20 KiB against the 320 KiB of W_down the same block reads -- and yet - * the norm is 6.7 us of the kernel's 18.7 at the decode grid. The loop is not moving bytes, it - * is WAITING: a runtime trip count of ten, a global load feeding an FMA, and nothing else - * resident on the compute unit to cover the latency. Issuing eight iterations' loads into - * registers first turns eight serial latencies into one. Bit-identical: the same element is - * computed from the same inputs in the same order, and only when the load is issued moves. + /* ---- sums of squares, one stream at a time, straight from `h`. One stream at a time keeps + * the accumulator a scalar; an array indexed by runtime `hc` would live in scratch. * - * THE PROLOGUE IS LATENCY-BOUND, NOT TRAFFIC-BOUND, and three separate traffic levers are - * worth nothing here: - * - * LOAD WIDTH. The N-build loop below reads `h` 32 consecutive bf16 at a time and `w` 32 - * consecutive f32 -- 64- and 128-byte requests, where wave_dot_lds measures 64 bytes at - * 219 GB/s against 554 for the same bytes taken eight contiguous to a lane. Putting both - * operands through the same per-wave LDS staging turns sixteen narrow loads into three - * global_load_b128, bit-identically, and changes the step time by nothing. THE WIDTH - * ARGUMENT IS A DRAM ARGUMENT AND THESE BYTES ARE NOT COLD: `w` is one 40 KiB array every - * block of the grid reads and `h` is 20 KiB read by the blocks of one row, so the norm phase - * moves 6.7 MB across the grid in 6.7 us -- about 1 TB/s, above what this part's DRAM can - * deliver, so it is served out of the 64 MB last level where a narrow request costs a small - * fraction of what it costs at the DRAM boundary. Load width is a lever ONLY where the bytes - * are cold, which is why it is worth 2.5x on the dot's streamed weight and nothing here. - * - * BYTE COUNT. The prologue reads `h` TWICE -- once for the sums of squares and again to - * build N -- on top of 40 KiB of f32 norm weight. The second read is removable: sN holds - * nothing until the scale pass writes it, so the first pass can park the RAW bytes there and - * the second read them back, bit-identically (the transposed store is a permutation inside - * one 256-element chunk and a wave owns a whole chunk, so it needs no barrier beyond the - * wave's own lockstep). That takes 80 KiB a block to 60 and is worth zero. - * - * DEEPER STAGING. Prefetching the four sub-streams together, 32 loads outstanding instead of - * 8, is also within noise. - * - * What is left is the LATENCY CHAIN and the two barriers: ten dependent iterations, a - * block-wide reduction over kWaves partials, and 5.25 waves a SIMD at the decode grid with - * nothing else resident to hide any of it. A gain here has to come from concurrency or from - * the chain, not from traffic. */ + * This prologue is latency-bound, not traffic-bound: 20 KiB against the block's 320 KiB of + * W_down, yet 6.7 of the kernel's 18.7 us at the decode grid, because ten dependent iterations + * wait on loads with nothing else resident. Issuing kPreSs iterations' loads first turns eight + * serial latencies into one, bit-identically. Wider loads (these bytes are served from the + * 64 MB last-level cache, not DRAM), reading `h` once instead of twice, and deeper prefetch + * were all measured as no gain. */ constexpr int kPreSs = 8; // n / kThreads is 10 a stream at this shape, and 12 spills for (int c = 0; c < hc; ++c) { const long cb = (long)c * n; @@ -924,26 +783,20 @@ void hc_read_a_kernel(const unsigned short* __restrict__ h, const float* __restr float ss = 0.0f; for (int k = 0; k < kWaves; ++k) ss += s_part[k][tid]; s_scale[tid] = __frsqrt_rn(ss / (float)n + eps); - /* One workgroup publishes; the rest recompute the identical value from the identical - * bytes, so which one wins is not a question. */ + /* One workgroup publishes; the others compute the identical value. */ if (pub && scaleout) scaleout[r * kHcMax + tid] = s_scale[tid]; } __syncthreads(); - /* ---- N into LDS, narrowed to bf16 exactly where the reference narrows it. */ - /* PER STREAM, AND NOT `j / n`. `j` and `n` are both long, so `j / n` is a 64-BIT INTEGER - * DIVISION per element -- a software sequence on this part -- to recover a value the loop - * structure already knows. The map is elementwise, so the scale is a loop-invariant scalar - * and every element is computed from the same inputs in the same way: bit-identical. */ + /* ---- N into LDS, narrowed to bf16 where the reference narrows it. Looped per stream rather + * than computing `j / n`, a 64-bit integer division per element (a software sequence here). */ for (int c = 0; c < hc; ++c) { const long cb = (long)c * n; const float sc = s_scale[c]; if (swz) { - /* A THREAD OWNS ONE (chunk, lane) GROUP, which is the transpose: its eight logical - * elements are `lane + 32t`, and they are one 16-byte store at physical `q`. A wave's - * 32 threads cover exactly one chunk, so `ch` is wave-uniform and the eight `h` and - * `w` reads are each 32 consecutive elements -- still coalesced, which the transposed - * store is not asking them to give up. */ + /* A thread owns one (chunk, lane) group: logical elements `lane + 32t`, one 16-byte + * store at physical `q`. A wave covers one chunk, so `ch` is wave-uniform and the + * `h` and `w` reads stay coalesced. */ for (long base = 0; base < n; base += (long)kThreads * 8) { const long q = base + (long)tid * 8; if (q >= n) break; @@ -977,7 +830,7 @@ void hc_read_a_kernel(const unsigned short* __restrict__ h, const float* __restr } __syncthreads(); - /* ---- this workgroup's columns of W_down. One wave a column, a lane striding by 32. */ + /* ---- this workgroup's columns of W_down, one wave per column. */ const float inv_hc = 1.0f / (float)hc; const long k0 = (long)blockIdx.x * ta; for (long k = k0 + wave; k < k0 + ta && k < lr; k += kWaves) { @@ -1007,89 +860,29 @@ void hc_read_a_kernel(const unsigned short* __restrict__ h, const float* __restr /* ============================================================== hc_read, kernel B1 * - * `u = sigmoid(W_up @ d)`, one wave a row of W_up. SEPARATE FROM THE MIX, and the reason is - * occupancy rather than tidiness: the mix owns 128 CHANNELS, which is hc*128 rows of W_up, so a - * 2560-wide model gives it twenty workgroups against sixty-four compute units and the matvec runs - * at a quarter of the machine. Split, this one is HN/64 = 160 workgroups on the same bytes. + * `u = sigmoid(W_up @ d)`, one wave per row of W_up. Separate from the mix for occupancy: the mix + * owns 128 channels (hc*128 rows of W_up), only twenty workgroups at width 2560 on 64 CUs, while + * this kernel runs HN/64 = 160 workgroups on the same bytes. `u` costs a 20 KiB-per-row round trip + * through scratch against 6.55 MiB of weight. * - * `u` costs a round trip through scratch -- 20 KiB a row written and read -- against 6.55 MiB of - * weight, which is the trade. + * RG rows share one block and one pass over the weight. With the row on blockIdx.y, a depth-3 MTP + * verify (four rows) streams W_up four times; the last-level cache absorbs most of it (1.4x, not + * 4x), but needlessly. `d` is 320 floats per row, so RG rows fit in LDS and a wave takes RG dots + * from each weight row it loads (~3% of a multi-row step, same output). RG=1 is the one-row case. * - * ---- RG: THE ROWS OF A STEP SHARE ONE BLOCK, NOT ONE BLOCK EACH ------------------------------- + * At the decode grid this moves 6.55 MB in 14.9 us (440 GB/s; the part reads 621 cold). Measured + * slower: four rows in flight per wave (+16%); kUpRows 16 or 128; staging the 64-element tail as + * one wide load (+4.6%; both narrow loads hit one 128-byte line); eight consecutive rows per wave + * instead of strided (+9.9%; strided rows make a block's eight waves read one contiguous burst); + * and register-staging the tail (+13.1%; the compiler hoists the wait in front of the chunk load). + * A block-cooperative stage of the span would take 40 KiB of LDS (1 block per CU instead of 7). * - * Putting the row on `blockIdx.y` reads W_up ONCE A ROW. At decode that is the floor and the - * file's header says so -- but a depth-3 MTP verify is FOUR rows, and four blocks each streaming - * the same 6.55 MB is 26.2 MB for 6.55 MB of weight. At M=4 that form runs 640 blocks at 1120 GB/s - * aggregate -- above what the part's DRAM can deliver, so three of the four reads are already - * being served out of the 64 MB last level. That is why the cost is 1.4x and not 4x, and also why - * it is worth removing rather than free: the cache is doing work that need not exist, and every - * byte of it evicts something else. - * - * RG rows share ONE pass over the weight. `d` is 320 floats a row -- 1.25 KiB -- so all of them - * fit in LDS beside the staging slots, and a wave that has the weight row in registers can take - * RG dot products off it instead of one. The weight traffic drops to 6.55 MB whatever M is, worth - * about 3% of a multi-row step for identical output, and RG=1 is the one-row case. - * - * ---- THIS KERNEL IS AT 440 GB/s, AND FIVE LEVERS ON THAT ARE SLOWER --------------------------- - * - * It moves 6.55 MB of W_up in 14.9 us at the decode grid -- 440 GB/s against a part that reads - * 621 cold. A wave owns eight rows of 640 bytes and takes them ONE at a time, so it has one - * 512-byte load outstanding, and 160 blocks of 8 waves on 64 compute units is ~10 KiB in flight a - * CU. That reads exactly like the depth argument wave_dot_lds makes, and it is not. Each of the - * following is SLOWER, with hc_read_a flat in the same traces as a control: - * - * DEPTH. Four weight rows in flight instead of one (the eight rows are independent, so four - * uint4 of register buys four times the bytes outstanding): 17.5 us, worse by 16%. - * - * GRID, IN BOTH DIRECTIONS. kUpRows 64 -> 16 is four times the blocks at the same depth a wave: - * 15.9 us here, and 112 -> 131 us at prefill. kUpRows 64 -> 128 is HALF the blocks -- 80 of - * them, which is where hc_read_a's faster 84 sits -- and is worse again. - * - * LOAD WIDTH AT THE TAIL. `lr` is 320 and a chunk is 256, so wave_dot_lds_rows takes 256 - * elements as one 512-byte staged load and the last 64 as TWO 64-byte ones. Eight lanes bringing - * a uint4 each is the same 128 bytes in ONE request and is 4.6% WORSE. The 219-against-554 - * figure elsewhere in this file does not reach this tail, because that is a REQUEST-RATE effect - * across a 20 KiB row, where the narrow form pays the per-request cost forty times over. A 64-element tail is TWO requests and both land in the SAME 128-byte line -- a - * 640-byte row is five lines, so `wr + 256` is line-aligned and the second load is an L1 hit. - * There is no transaction to save, and the wide form costs one: the scalar pair issues two loads - * and waits once, where the staged form issues one load and then waits on a dependent LDS round - * trip that eight lane-FMAs cannot hide. - * - * PER-WAVE SEQUENTIALITY. `for (t = wave; t < kUpRows; t += kWaves)` gives a wave rows 5120 - * bytes apart, where hc_read_a -- the kernel at 546 GB/s -- gives each of its waves ONE 20 KiB - * row to walk end to end. Giving each wave eight CONSECUTIVE rows instead, same block and same - * bytes, is 9.9% worse. SO THE LOCALITY THAT MATTERS IS ACROSS THE EIGHT WAVES OF A BLOCK AT ONE - * INSTANT, NOT ALONG ONE WAVE'S OWN SEQUENCE: strided, the block's eight waves work on eight - * ADJACENT rows at the same time and their loads arrive as one contiguous 5 KiB burst; - * consecutive, the same eight waves sit 5 KiB apart and the block asks the memory system for - * eight scattered pieces. The strided form in the code is the one the part wants. - * - * THE TAIL'S STALL COUNT. At lr = 320 the tail is TWO iterations of a rolled loop the compiler - * cannot unroll, because HN is a runtime value, and each is `global_load_u16`, - * `s_wait_loadcnt 0x0`, four VALU -- so a row costs THREE dependent global stalls. Issuing the - * tail into registers first (an unrolled `tv[8]` with `(i < HN)` masking, one waitcnt serving - * all of them) does turn three stalls into two, and is 13.1% worse: the compiler turns the - * masked unrolled load into EIGHT conditional basic blocks and sinks the single - * `s_wait_loadcnt 0x0` to just after the last of them, BEFORE the chunk's load is issued. The - * tail's latency stops being something the chunk's FMAs retire under and becomes a naked stall - * at the front, plus six branches a row that do nothing. FEWER STALLS ON A LATENCY-BOUND KERNEL - * IS NOT THE SAME AS LESS STALLING. - * - * NOTHING THAT CHANGES WHAT ONE WAVE ASKS FOR MOVES THIS KERNEL. A sixth lever would have to be - * about what the BLOCK asks for, and the arithmetic is at least expressible -- kUpRows * lr * 2 - * is 40960 bytes, exactly ten block-wide passes of 256 threads by 16 bytes, so a cooperative - * stage of the whole span is one clean loop. It is also 40 KiB of LDS against the 9 KiB this - * kernel holds, which is 1 block a CU instead of 7, at an occupancy cost that is not measured. - * - * BIT-IDENTICAL, and for the same reason wave_dot_lds is: lane L still sums j = L, L+32, ... - * within a 256-element chunk, still takes the chunks in ascending order, and still accumulates - * into a per-row scalar. Only the LOOP NEST changes -- rows move from the grid to the innermost - * position -- and `acc[]` is indexed by an unrolled constant so it stays in registers. A runtime - * `rows` bound there would put it in scratch, which is the trap hc_write's header records. */ + * Bit-identical to wave_dot_lds: only the loop nest changes (rows move innermost), and `acc[]` is + * indexed by an unrolled constant so it stays in registers; a runtime `rows` bound would put it in + * scratch. */ -/* RG rows of the LDS vector against ONE contiguous bf16 weight row, the weight read once. - * `sv_ld` is the row pitch of `sv`; `live` masks the tail group of a row count RG does not - * divide. */ +/* RG rows of the LDS vector against one contiguous bf16 weight row, read once. `sv_ld` is the row + * pitch of `sv`. */ template __device__ __forceinline__ void wave_dot_lds_rows(const float* __restrict__ sv, long sv_ld, const unsigned short* __restrict__ wr, long HN, @@ -1129,8 +922,7 @@ void hc_up_kernel(const void* __restrict__ upv, long uld, const unsigned short* if (r0 >= rows) return; const int tid = threadIdx.x, lane = tid & (kWave - 1), wave = tid / kWave; - /* A dead row of the tail group reads nothing and is zero-filled, so its dot is defined and - * its store is dropped below. */ + /* A dead row of the tail group is zero-filled, so its dot is defined; its store is dropped. */ for (long k = tid; k < (long)RG * lr; k += kThreads) { const long r = k / lr; sd[k] = (r0 + r < rows) ? bf2f(dbuf[(r0 + r) * lr + (k - r * lr)]) : 0.0f; @@ -1138,8 +930,8 @@ void hc_up_kernel(const void* __restrict__ upv, long uld, const unsigned short* __syncthreads(); const long j0 = (long)blockIdx.x * kUpRows; - /* THE E4M3 FORM TAKES A ROW FOUR THREADS AT A TIME, a quarter each -- the quarter is the row's - * scale group -- so the block's 256 threads cover its 64 rows in one pass. */ + /* The E4M3 form takes a row four threads at a time, a quarter (one scale group) each, so 256 + * threads cover the block's 64 rows in one pass. */ if constexpr (F8) { static_assert(kUpRows * 4 == kThreads, "four threads a row of W_up"); const int tr = tid >> 2, q4 = tid & 3; @@ -1159,19 +951,17 @@ void hc_up_kernel(const void* __restrict__ upv, long uld, const unsigned short* #pragma unroll for (int r = 0; r < RG; ++r) { const float a = wave_sum(acc[r]); - /* Narrowed where the reference narrows it: torch's sigmoid output is bf16 before the - * multiply, so an f32 `u` here would disagree in the last bit of every channel. */ + /* Narrowed as in the reference, where the sigmoid output is bf16 before the multiply. */ if (lane == 0 && r0 + r < rows) ubuf[(r0 + r) * hn + j] = f2bf(sigmoidf_(a)); } } } -/* THE ROTATED TWIN OF ONE 128-CHANNEL GROUP, for a consumer whose weight carries a 128-wide - * Hadamard (the w4a8h expert plane). A wave holds the group four consecutive values a lane -- the - * layout r4d_fwht_wave<128> transforms in registers -- loaded by the caller from the bf16 the read - * stored, and quantises the rotated values exactly as the rotated quant_act_fp8 kernel does: the - * same transform, absmax, scale, clamp and packing, so its consumer cannot tell which op wrote - * the codes and no separate launch over `x` is needed. */ +/* Rotated fp8 codes of one 128-channel group, for a consumer whose weight carries a 128-wide + * Hadamard (the w4a8h expert plane). A wave holds the group four consecutive values per lane (the + * r4d_fwht_wave<128> layout), loaded by the caller from the stored bf16, and quantises exactly as + * the rotated quant_act_fp8 kernel does (transform, absmax, scale, clamp, packing), so no separate + * launch over `x` is needed. */ __device__ __forceinline__ void hc_rot_group(float* v, int lane, unsigned char* qg, float* sg) { r4d_fwht_wave(v, lane); float m = 0.0f; @@ -1191,21 +981,17 @@ __device__ __forceinline__ void hc_rot_group(float* v, int lane, unsigned char* /* ============================================================== hc_read, kernels B and B2 as one * - * hc_up tiles the FLATTENED index, so a workgroup's 64 rows of W_up are 64 channels of ONE - * sub-stream, the hc terms of a channel's mean land in hc different workgroups, and `u` has to - * round-trip through `ubuf` into hc_mix. That second launch is a whole dependent dispatch a - * connection -- on this part a gap longer than either kernel's own work at one row. + * hc_up tiles the flattened index, so a channel's hc terms land in different workgroups and `u` + * round-trips through `ubuf` into hc_mix, a dependent launch that costs more than either kernel's + * work at one row. * - * This workgroup owns 64 / hc CHANNELS in all hc sub-streams instead: the same 64 rows of W_up and - * the same grid, taken as hc runs of 64 / hc rows, so every term of its channels' means is in its - * own LDS and `u` never leaves it. What it gives up is the whole 128-channel scale group, and an - * arrival counter buys that back exactly as hc_up_mix_tiled does: the last of the workgroups - * covering a group of a row group quantises it, from the bf16 `x` the others wrote. + * This workgroup instead owns 64 / hc channels in all hc sub-streams (the same 64 rows of W_up and + * grid, as hc runs of 64 / hc rows), so `u` stays in LDS. An arrival counter replaces the whole + * 128-channel scale group, as in hc_up_mix_tiled: the last workgroup covering a group of a row + * group quantises it from the bf16 `x` the others wrote. * - * BIT-IDENTICAL to the pair. Each row's dot is wave_dot_lds_rows over the same weight row, - * narrowed where hc_up narrows it; the mean runs over c ASCENDING in hc_mix's expression; and the - * codes are taken from the same bf16 values against the same amax, which a max reaches in any - * order. */ + * Bit-identical to the pair: the same per-row dots and narrowing as hc_up, the mean over c + * ascending as in hc_mix, and codes from the same bf16 values and amax. */ template __global__ __launch_bounds__(kThreads) void hc_up_mix_kernel(const void* __restrict__ upv, long uld, @@ -1234,7 +1020,7 @@ void hc_up_mix_kernel(const void* __restrict__ upv, long uld, __syncthreads(); /* Row t of this workgroup's slice of W_up is sub-stream t / ipb of channel i0 + t % ipb. The - * E4M3 form takes each row four threads at a time, as hc_up_kernel's does. */ + * E4M3 form takes each row four threads at a time, as in hc_up_kernel. */ if constexpr (F8) { static_assert(kUpRows * 4 == kThreads, "four threads a row of W_up"); const int t = tid >> 2, q4 = tid & 3; @@ -1291,8 +1077,8 @@ void hc_up_mix_kernel(const void* __restrict__ upv, long uld, __hip_atomic_store(&ctr[slot], 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); __threadfence(); - /* One wave a row: RG is at most the wave count, and a wave's 32 lanes take the group's 128 - * channels four apiece, which is also one packed dword of codes a lane. */ + /* One wave per row (RG <= wave count); a lane takes four of the group's 128 channels, one + * packed dword of codes. */ if (wave >= RG) return; const long r = r0 + wave; if (r >= rows) return; @@ -1318,16 +1104,12 @@ void hc_up_mix_kernel(const void* __restrict__ upv, long uld, } } -/* THE GROUP SIZE IS THE ROW COUNT, UP TO EIGHT. RG is a template parameter because `acc[RG]` has - * to be registers; a runtime bound makes it scratch, and one private-memory round trip an element - * would cost more than the weight re-read it is here to remove. Every group from 1 to 8 is - * instantiated, so a row count up to eight is ONE group and the weight is read once: a five- or - * six-row verify (depth 4 or 5) split as 4 + 1 or 4 + 2 would read W_up twice. The output is the - * same bytes at any group, because only the loop nest over rows changes. +/* Row group size: the row count, up to eight. RG is a template parameter so `acc[RG]` stays in + * registers. Every size from 1 to 8 is instantiated, so up to eight rows read the weight once + * (a five-row verify split 4 + 1 would read W_up twice). Output bytes do not depend on RG. * - * The LDS cap is the real bound: RG rows of `d` are RG*lr floats beside the 4 KiB of staging - * slots, so a model with a wide low rank gets a smaller group rather than a launch failure -- the - * largest that fits, one row at a time, since every size below eight is an instantiation. */ + * LDS bounds it: RG rows of `d` are RG*lr floats beside 4 KiB of staging, so a wide low rank gets + * the largest group that fits rather than a launch failure. */ static inline long hc_up_rg(long long rows, long long lr) { constexpr long kLdsCap = 60 * 1024; /* leave the 4 KiB of staging slots room */ long rg = rows < 8 ? (rows > 1 ? (long)rows : 1) : 8; @@ -1337,7 +1119,7 @@ static inline long hc_up_rg(long long rows, long long lr) { static inline int hc_up_launch(const RadTensor* up, long uld, bool f8, const unsigned short* dbuf, unsigned short* ubuf, long long rows, long long HN, long long lr, - const R4dSink& sk) { + RadStream stream) { int emit_rc = RAD_OK; const long rg = hc_up_rg(rows, lr); const dim3 grid((unsigned)((HN + kUpRows - 1) / kUpRows), @@ -1345,8 +1127,8 @@ static inline int hc_up_launch(const RadTensor* up, long uld, bool f8, const uns const unsigned lds = (unsigned)(rg * lr * sizeof(float)); const void* upp = up->data; #define HC_UP1_CASE(RG_, F8_) \ - emit_rc = R4D_EMIT(sk, (hc_up_kernel), grid, dim3(kThreads), lds, upp, uld, dbuf, \ - ubuf, (long)rows, (long)HN, (long)lr) + emit_rc = R4D_EMIT(stream, (hc_up_kernel), grid, dim3(kThreads), lds, upp, uld, \ + dbuf, ubuf, (long)rows, (long)HN, (long)lr) switch (rg) { case 8: if (f8) HC_UP1_CASE(8, true); else HC_UP1_CASE(8, false); break; case 7: if (f8) HC_UP1_CASE(7, true); else HC_UP1_CASE(7, false); break; @@ -1361,8 +1143,8 @@ static inline int hc_up_launch(const RadTensor* up, long uld, bool f8, const uns return emit_rc; } -/* hc_up_mix_kernel's launch: hc_up's grid and row group, which the counter slots are laid over -- - * (rows / rg) row groups of n / kUpTB scale groups each. */ +/* hc_up_mix_kernel's launch: hc_up's row group; counter slots are (rows / rg) row groups of + * n / kUpTB scale groups. */ static inline int hc_up_mix_launch(const RadTensor* up, long uld, bool f8, bool i8, const unsigned short* dbuf, const unsigned short* h, const float* w, const float* scale, @@ -1371,15 +1153,16 @@ static inline int hc_up_mix_launch(const RadTensor* up, long uld, bool f8, bool unsigned int* ctr, long long rows, long long n, int hc, long long lr, long long hrow, long long xrow, long long qrow, long long srow, long long rqrow, long long rsrow, float wadd, - const R4dSink& sk) { + RadStream stream) { int emit_rc = RAD_OK; const long rg = hc_up_rg(rows, lr); const dim3 grid((unsigned)(n / (kUpRows / hc)), (unsigned)((rows + rg - 1) / rg)); const unsigned lds = (unsigned)(rg * lr * sizeof(float)); const void* upp = up->data; #define HC_UPMIX_CASE3(RG_, F8_, I8_) \ - emit_rc = R4D_EMIT(sk, (hc_up_mix_kernel), grid, dim3(kThreads), lds, upp, uld,\ - dbuf, h, w, scale, x, q, qs, rq, rqs, ctr, (long)rows, (long)n, hc, \ + emit_rc = R4D_EMIT(stream, (hc_up_mix_kernel), grid, dim3(kThreads), lds, \ + upp, uld, dbuf, h, w, scale, x, q, qs, rq, rqs, ctr, (long)rows, (long)n, \ + hc, \ (long)lr, (long)hrow, (long)xrow, (long)qrow, (long)srow, (long)rqrow, \ (long)rsrow, wadd) #define HC_UPMIX_CASE(RG_, F8_) \ @@ -1401,11 +1184,11 @@ static inline int hc_up_mix_launch(const RadTensor* up, long uld, bool f8, bool /* ============================================================== hc_read, kernel B2 * - * `x = mean_c( u[c] * N[c] )` for this workgroup's 128 channels, and their fp8 codes -- 128 is one - * scale group, so the amax is this workgroup's alone and there is no second pass over the row. + * `x = mean_c( u[c] * N[c] )` for this workgroup's 128 channels, plus their fp8 codes: 128 is one + * scale group, so the amax needs no second pass. * - * N is rebuilt from `h` and the scales kernel A published rather than carried: 128 channels of it - * is 512 elements against the 20 KiB the whole row would cost to move. */ + * N is rebuilt from `h` and kernel A's published scales (512 elements here, against 20 KiB to + * carry the whole row). */ template __global__ __launch_bounds__(kThreads) void hc_mix_kernel(const unsigned short* __restrict__ h, const float* __restrict__ w, @@ -1443,9 +1226,7 @@ void hc_mix_kernel(const unsigned short* __restrict__ h, const float* __restrict if (!q) return; __syncthreads(); - /* IT QUANTISES WHAT WAS WRITTEN: `s_x` is narrowed to bf16 first, because that is what the - * reference reads back and a fused kernel using its f32 accumulator would disagree in the last - * bit of every code. */ + /* Quantise what was written: `s_x` is narrowed to bf16 first, as the reference reads it back. */ float m = 0.0f; for (int t = tid; t < kUpTB; t += kThreads) m = fmaxf(m, fabsf(nbf(s_x[t]))); m = r4d_wave_max(m); @@ -1456,7 +1237,7 @@ void hc_mix_kernel(const unsigned short* __restrict__ h, const float* __restrict const float sc = amax > 0.0f ? amax * (1.0f / q8_top()) : 1.0f; const float inv = 1.0f / sc; if (tid == 0) qs[r * srow + blockIdx.x] = sc; - /* Four codes a lane, packed into one dword, exactly as r4d_quant_act_fp8 does it. */ + /* Four codes per lane packed into one dword, as in r4d_quant_act_fp8. */ if (tid < kUpTB / 4) { const long c0 = i0 + (long)tid * 4; float v[4]; @@ -1464,8 +1245,7 @@ void hc_mix_kernel(const unsigned short* __restrict__ h, const float* __restrict const uint32_t pk = q8_pack4(v[0], v[1], v[2], v[3], inv); if (c0 < n) *(unsigned*)(q + r * qrow + c0) = (unsigned)pk; } - /* The rotated twin from the same narrowed values; the launch refuses a channel count that is - * not whole groups, so the group is always full. */ + /* The rotated codes from the same narrowed values; the launch requires whole groups. */ if (rq && wave == 0) { float v[4]; #pragma unroll @@ -1474,78 +1254,50 @@ void hc_mix_kernel(const unsigned short* __restrict__ h, const float* __restrict } } -/* ==================================================== hc_read, the PREFILL path +/* ==================================================== hc_read, the tiled path * - * The three kernels above PUT ROWS ON THE GRID: one workgroup a token, and each of them reads the - * whole of its slice of the mixing matrix. At decode that is exactly right -- there is one row, the - * weight is read once, and the header's 2.1 ms is the floor. At a prefill chunk it is a disaster: - * EVERY TOKEN re-reads both 6.55 MB matrices, so 2048 tokens times 96 connections times 13.1 MB is - * 2.5 TB of weight traffic for a step whose arithmetic is 6.6M MACs a token. On the full Flash-Next - * that is 56% of a prefill step, nearly twice the MoE. + * The kernels above put rows on the grid, so each token reads its whole slice of the mixing + * matrices. Right at decode; at a 2048-token prefill chunk it is 2.5 TB of weight traffic per step + * (56% of a Flash-Next prefill step). * - * Above a row count the two products run as TILED GEMMs instead. A workgroup owns 128 rows and 64 - * output columns; the weight tile lands in LDS once and is reused by all 128 rows, so the weight is - * read ceil(rows/128) times a step rather than `rows` times -- 16 passes at a 2048-token chunk - * instead of 2048. The arithmetic is the same two products; only the ORDER of the sum changes, from - * a lane-strided partial sum to WMMA's 16-wide fragments, which is the same class of reordering the - * per-row form already does against the reference's sequential f32 sum. + * Above a row threshold the two products run as tiled GEMMs: a workgroup owns 128 rows and 64 + * output columns and reuses each weight tile across its rows, so the weight is read + * ceil(rows/128) times. Only the summation order changes (WMMA fragments instead of lane-strided + * partials), the same kind of reordering the per-row form already has against the reference. * - * THE NORM MOVES OUT rather than being carried. The per-row kernel A folds the grouped rmsnorm, the - * inject gains and the W_down product into one pass because it already holds N in LDS. A tile - * cannot: N for 128 rows is 2.5 MB. So the scales and the gains get a kernel of their own (one pass - * over `h`, and injw is 80 KB that stays in L2), and the GEMM rebuilds N as it stages each A tile -- - * which costs nothing, because the tile has to be staged either way and `h` would be read anyway. + * The norm moves out: N for 128 rows is 2.5 MB, too big for LDS. The scales get their own kernel + * (one pass over `h`) and the GEMM rebuilds N while staging each A tile, which it must stage + * anyway. * - * THE COLUMN COUNT IS WHY THIS IS TWO GEMMS AND NOT ONE. `d` is [rows, 320] and `u` is [rows, - * 10240]; a workgroup that owned a whole 128-channel scale group of the mix would own hc*128 = 512 - * rows of W_up for only its 16 affordable rows of accumulator, and the weight would then be read - * rows/16 times. What keeps `u` out of memory instead is a workgroup owning sixteen channels of - * every sub-stream and an arrival counter for the scale group: hc_up_mix_tiled_kernel at the decode - * tiles, hc_up_mix_wide_kernel at the prefill one. + * Two GEMMs, not one: a workgroup owning a whole 128-channel scale group of the mix would own + * hc*128 = 512 rows of W_up but only 16 rows of accumulator, re-reading the weight rows/16 times. + * Instead a workgroup owns sixteen channels of every sub-stream with an arrival counter for the + * scale group (hc_up_mix_tiled_kernel at decode tiles, hc_up_mix_wide_kernel at prefill). */ constexpr int kTNT = 64; // output columns a workgroup owns: four n tiles -/* AND IT IS FITTED AT DECODE SHAPES, WHICH COSTS SOMETHING AT PREFILL. The tiled down product's - * grid is (ncol/kTNT, rows/rt, HN/kc), so `h` is re-read once per COLUMN tile and the weight once - * per ROW tile. At decode h is 20 KiB against 1.3 MiB of weight and six reads of it are free; at a - * 2048-row chunk h is 41.9 MB and six reads are 251 MB against 105 MB of weight. The trade - * inverts and nothing here notices. - * - * So the prefill tile does not use it: hc_down_wide_kernel takes kWideNT columns a workgroup. - * The K-split stays hc_down_kchunk's, counted at kTNT columns: at 2048 rows and 112 columns, splits - * of 1, 3, 4, 5 and 8 are all slower than the rule's 2 (844 / 797 / 774 / 765 / 766 us a call - * against 760), and keeping it keeps the bytes. No split at all loses because the grid is then 48 - * workgroups on 64 CUs. */ +/* kTNT is fitted to decode shapes. The tiled down product's grid is (ncol/kTNT, rows/rt, HN/kc), so + * `h` is re-read per column tile and the weight per row tile; at decode h is small, but at a + * 2048-row chunk six reads of `h` (251 MB) outweigh the weight (105 MB). So the prefill tile uses + * hc_down_wide_kernel with kWideNT columns per workgroup, keeping hc_down_kchunk's split counted at + * kTNT columns (at 2048 rows, splits of 1, 3, 4, 5 and 8 are all slower than its 2; no split + * leaves 48 workgroups on 64 CUs). */ constexpr int kTKT = 64; // K staged per pass -constexpr int kTAP = kTKT + 4; // LDS row pitch in shorts. 136 B: 8-byte aligned, and the 16 - // lanes of a fragment land on 16 distinct bank pairs (AP 68, - // the same pitch the kkt solve uses). -constexpr long kTileMinRows = 64; // at or above this the 128-row tile fills and the down product - // needs no K-split: the prefill form. -constexpr long kDecMinRows = 8; // ...and below THIS the per-row kernels still win: there is not - // enough re-read to pay for hc_scale_inj and the partials. - // Eight rows is the crossover -- the two forms are level there - // -- and above it the tiled form pulls away, reaching ~25% - // of the step by eight concurrent sequences. +constexpr int kTAP = kTKT + 4; // LDS row pitch in shorts (136 B): 8-byte aligned, and a + // fragment's 16 lanes hit 16 distinct bank pairs (as in the + // kkt solve). +constexpr long kTileMinRows = 64; // from here the 128-row tile fills and the down product needs + // no K-split: the prefill form. +constexpr long kDecMinRows = 8; // below this the per-row kernels win; the two forms are level + // at eight rows, and the tiled form gains ~25% of the step by + // eight concurrent sequences. /* ==================================================== the norm scales, alone * - * THE SCALES GET A GRID, NOT A WORKGROUP. The inject gains ride along as four more columns of the - * down product (see hc_down_tiled_kernel), so nothing here needs a shared LDS copy of N -- a form - * that computed the per-stream rsqrt AND the gains off one such copy would have to stage the whole - * 20 KiB row and walk it a second time for four dot products. - * - * With the gains gone the streams are independent, so the grid is (hc, rows) rather than - * (1, rows): one rsqrt per (row, stream), four times the workgroups, and no LDS staging in front - * of them. The fused form's 75 VGPRs and 4384 B of LDS are 9 and 32 here. - * - * BIT-IDENTICAL to the fused form: the same thread stride over the same values, the same - * wave_sum, and the same ascending sum over the eight wave partials. - * - * IT IS WORTH TENS OF MICROSECONDS A STEP AND NOT MORE. A kernel this short is mostly the ~20% - * launch ramp this part charges anything under ~13 us, so deleting its WORK can never buy much. - * Only deleting the LAUNCH would, and that needs the scales computed by something already running - * -- which the op's private scratch forbids, since the producer of `h` is hc_write, a different op - * with a different arena. */ + * The inject gains ride along as extra columns of the down product (hc_down_tiled_kernel), so + * streams are independent and the grid is (hc, rows): one rsqrt per (row, stream), no LDS copy of + * N. Bit-identical to the fused form: same thread stride, wave_sum and ascending sum over the wave + * partials. Removing the launch itself would need `h`'s producer (hc_write, another op with its + * own arena) to compute the scales. */ __global__ __launch_bounds__(kThreads) void hc_norm_scale_kernel(const unsigned short* __restrict__ h, float* __restrict__ scaleout, long rows, long n, long hrow, float eps) { @@ -1566,46 +1318,36 @@ void hc_norm_scale_kernel(const unsigned short* __restrict__ h, float* __restric } } -/* ==================================================== THE TILE SHAPE IS A FUNCTION OF THE ROWS +/* ==================================================== tile shape follows the row count * - * One tile shape cannot serve a 2048-token prefill chunk and a 32-row decode batch. RT is what - * varies: 128 rows a workgroup is right when there are thousands, and at 32 it stages 128 rows - * of A to use 32 of them AND leaves the down product's grid at ceil(320/64) = FIVE workgroups on - * a 64-CU part. Forcing the 128-row tile on at decode roughly doubles the step at one sequence - * and costs ~18% at eight -- which is what `kTileMinRows` protects against, and why simply - * lowering that bound is not the fix. + * RT varies with rows: 128 suits thousands of rows, but at 32 it would stage 128 rows to use 32 + * and leave the down product five workgroups on 64 CUs (the 128-row tile at decode roughly doubles + * the step at one sequence; kTileMinRows guards it). * - * WHICH WAVE OWNS WHICH TILE FOLLOWS FROM RT. With 8 m-tiles there is one a wave and each wave - * walks every n-tile, which is the 128-row form's mapping. With 2 m-tiles the same rule would idle - * six waves, so the waves spread over N instead: WM = min(MT, waves) waves across the m-tiles and - * WN = waves/WM across the n-tiles. RT 128 gives exactly the one-m-tile-a-wave mapping (WM 8, - * WN 1). + * Wave mapping follows RT: WM = min(MT, waves) waves across the m-tiles and WN = waves/WM across + * the n-tiles. RT 128 gives one m-tile per wave (WM 8, WN 1). * - * AND THE DOWN PRODUCT NEEDS THE K-SPLIT THAT THE UP PRODUCT DOES NOT. Its output is [rows, 320] - * -- five 64-column tiles, one workgroup each -- while the up product's is [rows, 10240] and - * already covers the part at 160. So the down product splits K over blockIdx.z, writes f32 - * partials, and a reduce pass sums them in ASCENDING z and applies the silu. The partial buffer - * is ksplit * rows * lr floats, 655 KB at the decode band, and the reduce reads it once. + * Only the down product splits K: its output is [rows, 320], five 64-column tiles, while the up + * product's [rows, 10240] already fills the part. Split blocks write f32 partials over blockIdx.z + * (ksplit * rows * lr floats, 655 KB at the decode band) and a reduce pass sums them in ascending z + * and applies the silu. */ constexpr int kTKSPLIT_WANT = 128; // workgroups the down product aims to cover the part with /* ==================================================== d = silu(W_down @ N / hc), tiled * - * C[RT rows, NT cols] over K = hc*n. The A tile is N, rebuilt from `h` as it is staged: the launch - * refuses `n % kTKT`, so a K slice never straddles a stream and the scale index is one divide a - * tile rather than one an element -- the same reason the per-row kernel walks streams outermost. + * C[RT rows, NT cols] over K = hc*n. The A tile is N, rebuilt from `h` while staged; the launch + * requires n % kTKT == 0, so a K slice never straddles a stream and the scale index is one divide + * per tile. * - * `part` non-null is the split-K form: this block owns K in [z*kc, min(HN, (z+1)*kc)) and writes - * its raw f32 accumulator; the silu and the /hc move to the reduce. With `part` null, z is 0, the - * block owns all of K and the epilogue applies them itself. + * `part` non-null is the split-K form: the block owns K in [z*kc, min(HN, (z+1)*kc)) and writes its + * raw f32 accumulator; silu and /hc move to the reduce. With `part` null, z is 0 and the epilogue + * applies them. * - * THE INJECT GAINS RIDE ALONG AS FOUR MORE COLUMNS. `inj[c] = 2 sigmoid(W_inj[c] . N / hc)` is a - * dot of the SAME A matrix this GEMM already has staged, over the same K, and W_inj is [hc, HN] -- - * four more rows of a weight whose other 320 rows are W_down. Computed on its own it costs a whole - * kernel -- a (1, rows) grid in which four of eight waves walk a 20 KiB row each, ~18 us a call at - * eight sequences for 3.2 MB. Folded here it is 4/324 of a kernel that is already at bandwidth, - * and the norm kernel is left with one pass over `h`. `ncol` is lr + hc when there are gains and - * lr when there are not; columns at or past lr read injw and take the sigmoid epilogue. */ + * The inject gains ride along as hc more columns: `inj[c] = 2 sigmoid(W_inj[c] . N / hc)` uses the + * same staged A, and W_inj [hc, HN] is just more weight rows (a separate kernel would cost ~18 us + * at eight sequences). `ncol` is lr + hc with gains, lr without; columns at or past lr read injw + * and take the sigmoid epilogue. */ template __global__ __launch_bounds__(kThreads) void hc_down_tiled_kernel(const unsigned short* __restrict__ h, const float* __restrict__ w, @@ -1704,9 +1446,8 @@ void hc_down_tiled_kernel(const unsigned short* __restrict__ h, const float* __r } } -/* The split-K reduce: ksplit partials summed in ASCENDING z -- a fixed function of the shape, so - * the result is reproducible -- then the epilogue the tiled form would have applied, which is the - * silu for a W_down column and the doubled sigmoid for an inject column. */ +/* The split-K reduce: partials summed in ascending z (reproducible), then the epilogue: silu for a + * W_down column, doubled sigmoid for an inject column. */ __global__ __launch_bounds__(kThreads) void hc_down_reduce_kernel(const float* __restrict__ part, unsigned short* __restrict__ dout, unsigned short* __restrict__ inj, long rows, long lr, long ncol, @@ -1714,11 +1455,8 @@ void hc_down_reduce_kernel(const float* __restrict__ part, unsigned short* __res const long i = (long)blockIdx.x * kThreads + threadIdx.x; const long tot = rows * ncol; if (i >= tot) return; - /* EIGHT LOADS BEFORE THE ADDS, which is the whole performance of this kernel and none of its - * arithmetic: written as one `s +=` an iteration each load sits behind the previous add, and - * a 23-way split is a 23-deep dependent chain of DRAM latency on a 41-workgroup grid. The - * batching does not touch the ORDER of the adds, so the answer is the same bytes. - * gemm_fp8a8's splitk_reduce_kernel says the same thing at more length. */ + /* Eight loads before the adds: with one `s +=` per iteration a deep split becomes a dependent + * chain of DRAM latency. The add order is unchanged (as in gemm_fp8a8's splitk_reduce_kernel). */ float s = 0.0f; int z = 0; for (; z + 8 <= ksplit; z += 8) { @@ -1734,42 +1472,30 @@ void hc_down_reduce_kernel(const float* __restrict__ part, unsigned short* __res else inj[r * irow + (col - lr)] = f2bf(2.0f * sigmoidf_(s * inv_hc)); } -/* THE PREFILL TILE: its rows, the down product's columns a workgroup and the up product's - * channels a workgroup. 112 columns is three tiles over 320 + 4, the fewest that hold a - * 128-row A tile and the B tile in LDS twice a CU; measured against 64 and 128 at 129 to 4096 - * rows, it is the fastest at every one. */ +/* The prefill tile: rows, down-product columns per workgroup and up-product channels per + * workgroup. 112 columns is three tiles over 320 + 4, the fewest that fit the 128-row A tile and + * the B tile in LDS twice per CU; faster than 64 and 128 at 129 to 4096 rows. */ constexpr int kWideRT = 128, kWideNT = 112, kWideCH = 16; -/* THE PREFILL TILE'S FORM, pinned for a test: 0 is the launcher's rule, 1 the decode tiles' - * kernels at RT 128 (hc_down_tiled, then hc_up_tiled into `ubuf` and hc_mix), 2 the wide kernels - * (which then refuse a shape they are not built for), 3 the PF2 form (hc_pf2_launch; refused - * likewise, and also at a band under kPf2MinRows, whose `u` is not sized for its weight - * planes). */ +/* The prefill form, pinnable for tests: 0 the launcher's rule, 1 the decode tiles' kernels at + * RT 128 (hc_down_tiled, then hc_up_tiled into `ubuf` and hc_mix), 2 the wide kernels (refusing + * shapes they are not built for), 3 the PF2 form (hc_pf2_launch; refused likewise, and below + * kPf2MinRows, where `u` is not sized for its weight planes). */ static int g_hc_prefill_form = 0; /* ==================================================== d = silu(W_down @ N / hc) at the PREFILL tile * - * hc_down_tiled_kernel at RT 128 pays three things at a 2048-row chunk that its decode tiles do not - * notice: + * hc_down_tiled_kernel at RT 128 has three costs at a 2048-row chunk: a sixth 64-column tile + * rebuilds the whole A tile and runs every WMMA for four inject columns; every column tile rebuilds + * the same N; and slice loads never overlap the WMMAs. * - * THE INJECT TILE. 320 + 4 columns in 64-column tiles is six tiles, and the sixth stages the - * whole A tile -- N rebuilt from h, the costliest part of a slice -- and runs every WMMA of the - * tile for four real columns. - * THE A TILE ONCE PER COLUMN TILE. Every column tile rebuilds the same N; the fewer the tiles, - * the fewer the rebuilds. - * NO PREFETCH. A slice's global loads are issued after the previous slice's WMMAs and waited on - * before the next, so a workgroup's loads and its matrix work never overlap. + * This kernel takes NT columns per workgroup, skips n-tiles past the last real column, and issues + * the next slice's global loads into registers before this slice's WMMAs. A thread stages one + * fixed 8-wide column of four A rows, so the norm weight is loaded once per slice. * - * So the prefill tile has its own kernel: NT columns a workgroup, the n-tiles past the last real - * column skipped, and the next slice's global loads issued into registers before this slice's - * WMMAs. A thread stages one fixed 8-wide column of four A rows, so the norm weight is loaded once - * a slice rather than once a row. - * - * THE ARITHMETIC IS hc_down_tiled_kernel's: the same N, the same decode of W_down, the same 16x16 - * tiles over the same K slices in the same order, and the launch keeps hc_down_kchunk's split -- - * so it is the same bytes, which r4d_selftest checks. hc_read at Qwen3.8-Flash-Next's shape, with - * hc_up_mix_wide_kernel, against the decode tiles' kernels at RT 128: 767 us a call against 1134 - * at 2048 rows, 396 against 560 at 1024, 106 against 128 at 129. */ + * Arithmetic and bytes match hc_down_tiled_kernel (same N, W_down decode, 16x16 tiles, K order and + * hc_down_kchunk split; r4d_selftest checks). With hc_up_mix_wide_kernel, hc_read at + * Qwen3.8-Flash-Next's shape takes 767 us against 1134 at 2048 rows. */ template __global__ __launch_bounds__(kThreads) void hc_down_wide_kernel(const unsigned short* __restrict__ h, const float* __restrict__ w, @@ -1785,11 +1511,10 @@ void hc_down_wide_kernel(const unsigned short* __restrict__ h, const float* __re constexpr int kRS = kThreads / kKV; /* rows between a thread's A rows */ constexpr int kAV = RT / kRS; constexpr int kBV = (NT * kKV + kThreads - 1) / kThreads; - /* THE WAVES TILE THE BLOCK TWO WAYS, four over the rows and two over the columns, each holding - * two m-tiles and up to four n-tiles. One m-tile a wave across all seven n-tiles read eight - * fragments out of LDS for seven WMMA; two by four read six for eight, and the block's LDS - * reads a k step fall from 64 fragments to 44. The column halves are four n-tiles and three, - * and a wave's half is `wave / kDWM`, so waves w and w + 4 -- one of each -- share a SIMD. */ + /* Waves tile the block 4 (rows) x 2 (columns), each holding two m-tiles and up to four + * n-tiles: six LDS fragment reads per eight WMMA instead of eight per seven, so the block's + * reads per k step fall from 64 fragments to 44. A wave's column half is `wave / kDWM`, so + * waves w and w + 4 (one of each half) share a SIMD. */ constexpr int kDWM = 4, kDTM = RT / 16 / kDWM, kDTN = (NT16 + 1) / 2; static_assert(kDWM * 2 == kWaves && kDTM * 16 * kDWM == RT && RT % kRS == 0, "the waves cover the tile, whole A rows a pass"); @@ -1927,9 +1652,9 @@ void hc_down_wide_kernel(const unsigned short* __restrict__ h, const float* __re } } -/* Eight elements of row j of W_up at k, as the bf16 a tiled kernel stages: the stored bf16 itself, - * or eight E4M3 codes decoded against their group's scale. A group is a multiple of sixteen codes, - * so eight from a multiple of eight never straddle two. */ +/* Eight elements of row j of W_up at k as staged bf16: the stored bf16, or eight E4M3 codes decoded + * with their group's scale. A group is a multiple of sixteen codes, so eight aligned codes never + * straddle two groups. */ template __device__ __forceinline__ uint4 hc_up_stage(const void* __restrict__ upv, long uld, long j, long k, long lr) { @@ -1943,8 +1668,8 @@ __device__ __forceinline__ uint4 hc_up_stage(const void* __restrict__ upv, long /* ==================================================== u = sigmoid(W_up @ d), tiled * - * C[RT rows, NT channels] over K = lowrank. Same tiling; the A tile is `d` straight out of scratch - * and the K loop is five passes rather than 160. No K-split: hn/NT is already 160 workgroups. */ + * C[RT rows, NT channels] over K = lowrank. Same tiling; the A tile is `d` straight from scratch + * and the K loop is five passes. No K-split: hn/NT is already 160 workgroups. */ template __global__ __launch_bounds__(kThreads) void hc_up_tiled_kernel(const void* __restrict__ upv, long uld, @@ -2020,27 +1745,18 @@ void hc_up_tiled_kernel(const void* __restrict__ upv, long uld, } } - -/* ==================================== hc_read, kernels B and B2 in ONE launch, tiled +/* ==================================== hc_read, kernels B and B2 in one launch, tiled * - * `x = mean_c( u[c] * N[c] )` with `u` NEVER MATERIALISED -- which is what this file's header says - * kernel B is for, and what a tile over the FLATTENED channel index cannot give. A tile of 64 - * consecutive `j` is 64 channels of ONE sub-stream, so the four terms of a channel's mean live in - * four different workgroups and `ubuf` has to carry them; a tile of (stream, channel) PAIRS puts - * all hc of a channel in the same workgroup and the mean is local. + * `x = mean_c( u[c] * N[c] )` without materialising `u`. The tile is over (stream, channel) pairs, + * so all hc terms of a channel's mean are in one workgroup (see the file header). * - * WHAT IT COSTS AND WHAT IT BUYS. The B tile stops being 64 contiguous rows of W_up and becomes hc - * groups of NT/hc -- same bytes, four runs of 10 KiB instead of one of 40 -- and the fp8 twin - * cannot fall out of one workgroup, because 128 contiguous channels is one scale group and a - * workgroup owns NT/hc = 16 of them. That is the arrival counter below: the last of the eight - * workgroups covering a group quantises it, reading back the 128 bf16 it and its siblings just - * wrote. The tail is 8 KiB on the same 20 workgroups `hc_mix` would use, NOT on one, which is why - * it costs less than the launch it saves. + * The B tile becomes hc runs of NT/hc rows of W_up (same bytes), and a workgroup owns only + * NT/hc = 16 channels of a 128-wide scale group, so an arrival counter lets the last of the eight + * covering workgroups quantise the group from the bf16 the others wrote. That tail runs on the + * same 20 workgroups hc_mix would use, so it costs less than the launch it saves. * - * BIT-IDENTICAL TO THE UNFUSED PAIR, and every rounding is placed to keep it that way: `u` is - * narrowed to bf16 before the multiply because hc_mix reads it back out of a bf16 `ubuf`, `N` is - * narrowed by `nbf` in the same place, both go through LDS as bf16 so the reducer sees exactly the - * bytes the unfused form loads, and the sum over c runs ASCENDING. */ + * Bit-identical to the unfused pair: `u` and `N` are narrowed to bf16 where hc_mix would read them + * back, both pass through LDS as bf16, and the sum over c ascends. */ template __global__ __launch_bounds__(kThreads) void hc_up_mix_tiled_kernel(const void* __restrict__ upv, long uld, @@ -2108,11 +1824,9 @@ void hc_up_mix_tiled_kernel(const void* __restrict__ upv, long uld, } } } - /* N, IN A COALESCED PASS OF ITS OWN. The (stream, channel) tile is what makes the mean local - * and it is also what would wreck this read: in the wmma epilogue consecutive lanes hold - * consecutive `t`, which is consecutive SUB-STREAMS, so `h[r * hrow + j]` walks n elements a - * lane and every load is its own transaction. Here consecutive threads take consecutive - * channels of one sub-stream, exactly as `hc_mix` did. */ + /* N in a separate coalesced pass: in the WMMA epilogue consecutive lanes hold consecutive + * sub-streams, so reading `h` there would stride n elements per lane. Here consecutive threads + * take consecutive channels of one sub-stream, as in hc_mix. */ for (int idx = tid; idx < RT * NT; idx += kThreads) { const int rl = idx / NT, rem = idx - rl * NT; const int c = rem / ipb, ii = rem - c * ipb; @@ -2123,7 +1837,7 @@ void hc_up_mix_tiled_kernel(const void* __restrict__ upv, long uld, f2bf(bf2f(h[r * hrow + j]) * scalein[r * kHcMax + c] * (w[j] + wadd)); } - /* u out of the accumulators, where it is. */ + /* u from the accumulators. */ const int e0 = 8 * (lane >> 4), nn = lane & 15; #pragma unroll for (int im = 0; im < AM; ++im) { @@ -2157,7 +1871,7 @@ void hc_up_mix_tiled_kernel(const void* __restrict__ upv, long uld, } if (!q || !ctr) return; - /* The group's last workgroup quantises it. `nb` is how many cover one 128-channel group. */ + /* The group's last workgroup quantises it; `nb` workgroups cover one 128-channel group. */ const int nb = kUpTB / ipb; __threadfence(); __syncthreads(); @@ -2172,8 +1886,8 @@ void hc_up_mix_tiled_kernel(const void* __restrict__ upv, long uld, __hip_atomic_store(&ctr[slot], 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); __threadfence(); - /* The rotated twin wants a whole wave a row, where the codes below take kThreads / RT threads - * a row -- so it walks the tile's rows a wave at a time, before those threads split off. */ + /* The rotated codes need a whole wave per row, while the codes below use kThreads / RT threads + * per row, so the rotation walks the tile's rows a wave at a time first. */ if (rq) { const long gb = (i0 / kUpTB) * kUpTB; for (int rl = wave; rl < RT; rl += kWaves) { @@ -2207,36 +1921,25 @@ void hc_up_mix_tiled_kernel(const void* __restrict__ upv, long uld, } } -/* ==================================== hc_read, kernels B and B2 in ONE launch at the PREFILL tile +/* ==================================== hc_read, kernels B and B2 in one launch at the prefill tile * - * AT THE 128-ROW TILE THE PAIRED FORM DOES NOT FIT. hc_up_mix_tiled_kernel keeps `u` out of memory - * at the decode tiles, but at RT 128 its two staging planes on top of the A tile are 58 KiB of LDS - * and one workgroup a CU, and the unfused pair -- hc_up_tiled into `ubuf`, hc_mix reading it back - * -- costs 42 MB written and 42 MB read again a call at a 2048-row chunk, the largest stream the op - * moves, and a third launch. + * At RT 128 hc_up_mix_tiled_kernel's two staging planes plus the A tile take 58 KiB of LDS (one + * workgroup per CU), and the unfused pair moves 42 MB through `ubuf` each way per call at a + * 2048-row chunk, plus a third launch. * - * NEITHER PLANE IS NEEDED when a LANE holds every sub-stream of a channel. A WMMA accumulator gives + * Neither plane is needed when a lane holds every sub-stream of a channel: a WMMA accumulator gives * lane `l` column `l & 15` of each 16-column n-tile, so with n-tile `c` holding sub-stream c of the - * workgroup's sixteen channels, the hc terms of a channel's mean are the same lane's `acc[c]` and - * the mean is register-local. N is staged once, coalesced, into the A tile's LDS after the K loop is - * done with it. The workgroup's LDS is the unfused up product's. + * workgroup's sixteen channels, a channel's hc terms are one lane's `acc[c]`. N is staged once, + * coalesced, into the A tile's LDS after the K loop. LDS use equals the unfused up product's. * - * BIT-IDENTICAL TO THE UNFUSED PAIR: `u` is narrowed to bf16 before the multiply as hc_mix reads it - * out of `ubuf`, N the same way, and the sum over c runs ascending in the same `a += u * N` form. A - * 16x16 output tile is computed the same way whichever workgroup computes it. + * Bit-identical to the unfused pair: `u` and N are narrowed to bf16 as hc_mix reads them, and the + * sum over c ascends in the same `a += u * N` form. fp8 codes come via the arrival counter, as in + * hc_up_mix_tiled_kernel. * - * THE FP8 TWIN is the arrival counter's, as in hc_up_mix_tiled_kernel: a workgroup owns 16 of a - * scale group's 128 channels, and the last of the eight covering a group quantises it for the - * tile's rows. - * - * RT IS THE ROW TILE, MW = RT / 128 m-tiles a wave: 128 here (one m-tile a wave), 256 in the PF2 - * form over the mix_up its prologue decoded (two, so each B fragment read out of LDS feeds two - * WMMAs). The m-tile loops are the only difference, and at MW 1 each runs once over the same - * expressions in the same order as a body without them. The accumulators are ONE FLAT ARRAY, - * acc[mi * HC + c], because at MW 1 that is acc[c] exactly: an [MW][HC] array is the same values - * but reaches the register allocator in another shape, and gfx1201's code for the 128-row form then - * moves its zeros in another order. The rows keep their place in a 16-row tile at either RT (a - * tile starts at a multiple of RT), so both are the same bytes. */ + * MW = RT / 128 m-tiles per wave: 128 here (one), 256 in the PF2 form over its decoded mix_up (two, + * so each B fragment read feeds two WMMAs). The accumulators are one flat array, acc[mi * HC + c], + * because an [MW][HC] array changes gfx1201's register allocation for the 128-row form. Rows keep + * their place in a 16-row tile at either RT, so both produce the same bytes. */ template __global__ __launch_bounds__(kThreads) void hc_up_mix_wide_kernel(const void* __restrict__ upv, long uld, @@ -2257,15 +1960,13 @@ void hc_up_mix_wide_kernel(const void* __restrict__ upv, long uld, const long i0 = (long)blockIdx.x * CH; if (r0 >= rows) return; - /* EVERY GLOBAL LOAD IS ISSUED A STEP BEFORE IT IS NEEDED. The mix's `h` -- 42 MB a call at a - * 2048-row chunk, the op's largest read, and needed only after the product -- is loaded into - * registers before the K loop, so its latency runs under the matrix work instead of after it; - * and the loop holds the next slice's A rows and weight codes in registers while this slice's - * WMMA runs, as hc_down_wide_kernel does. Only WHEN a load is issued moves: the same bytes reach - * the same LDS and the same arithmetic, so the output is the same bytes. + /* Every global load is issued a step early. The mix's `h` (42 MB per call at a 2048-row chunk, + * needed only after the product) is loaded into registers before the K loop so its latency + * hides under the matrix work, and the loop holds the next slice's A rows and weight codes in + * registers during this slice's WMMA, as in hc_down_wide_kernel. Output is unchanged. * * A thread's slots are fixed: A and B rows `tid / 8 + 32 i` at column `(tid % 8) * 8` of a - * slice, and for N the (row, sub-stream, eight channels) the idx `tid + 256 i` names. */ + * slice, and for N the (row, sub-stream, eight channels) that idx `tid + 256 i` names. */ constexpr int kKV = kTKT / 8; /* 16-byte vectors a staged row */ constexpr int kRS = kThreads / kKV; /* rows between a thread's rows */ constexpr int kAV = RT / kRS, kBV = NT / kRS; @@ -2342,9 +2043,8 @@ void hc_up_mix_wide_kernel(const void* __restrict__ upv, long uld, } __syncthreads(); if (k0 + kTKT < lr) fetch(k0 + kTKT); - /* A's fragments are read once a k step and taken to every n-tile, and B's to every m-tile. - * Each accumulator still sees its k steps in ascending order, which is all its bytes - * depend on. */ + /* A's fragments are read once per k step and used for every n-tile, B's for every m-tile. + * Each accumulator still sees its k steps in ascending order. */ #pragma unroll for (int ks = 0; ks < kTKT / 16; ++ks) { v8bf af[MW]; @@ -2395,15 +2095,11 @@ void hc_up_mix_wide_kernel(const void* __restrict__ upv, long uld, } } -/* THE FP8 CODES OF `x` AT THE PREFILL TILE, and the rotated twin: one wave a (row, 128-channel - * scale group), after hc_up_mix_wide_kernel. That kernel's workgroup owns sixteen of a group's - * channels, so quantising inside it means whichever of its eight workgroups arrives last, behind - * an arrival counter and a device-scope fence in every one of them, walking the group's 128 rows - * by itself, a row at a time -- 82 of that kernel's 356 us at a 2048-row chunk. This launch is a - * stream over `x` at memory speed. - * - * The same bytes: the amax is an fmaxf reduction, exact in any order, and every code is the same - * conversion of the same bf16 value by the same scale; the rotated twin is hc_rot_group itself. */ +/* fp8 codes of `x` at the prefill tile, plus the rotated codes: one wave per (row, 128-channel + * scale group), after hc_up_mix_wide_kernel. Quantising inside that kernel would leave the last of + * eight workgroups walking the group's 128 rows alone behind a counter and fences (82 of its + * 356 us at a 2048-row chunk); this launch streams over `x` at memory speed. Same bytes: the amax + * is exact in any order and each code converts the same bf16 by the same scale. */ template __global__ __launch_bounds__(kThreads) void hc_quant_rows_kernel(const unsigned short* __restrict__ x, unsigned char* __restrict__ q, @@ -2433,10 +2129,9 @@ void hc_quant_rows_kernel(const unsigned short* __restrict__ x, unsigned char* _ if (rq) hc_rot_group(t, lane, rq + r * rqrow + base, rqs + r * rsrow + g); } -/* The mix finisher's arrival counters, one block a STREAM and not a device -- the same rule - * gemm_fp8a8's split_ctr states, for the same reason: a self-resetting counter is sound only - * while two launches of its kernel cannot overlap, and one stream is what guarantees that. - * Failure to allocate is not an error; the caller runs the unfused pair instead. */ +/* The mix finisher's arrival counters, one block per stream (as gemm_fp8a8's split_ctr): a + * self-resetting counter is sound only while two launches of its kernel cannot overlap, which one + * stream guarantees. Allocation failure is not an error; the caller runs the unfused pair. */ constexpr unsigned kMaxMixCtr = 2048; unsigned int* hc_mix_ctr(RadStream s) { @@ -2488,8 +2183,8 @@ static inline void hc_up_mix_tiled_launch(int rt, bool f8, bool i8, const void* #undef HC_UM_CASE3 } -/* The codes of `x` and the rotated twin, after a mix that writes `x` alone: hc_quant_rows_kernel - * over every (row, scale group). Nothing to do without codes. */ +/* The codes of `x` and the rotated codes, after a mix that writes only `x`: hc_quant_rows_kernel + * over every (row, scale group). No-op without codes. */ static inline void hc_quant_rows_launch(bool i8, const unsigned short* x, unsigned char* q, float* qs, unsigned char* rq, float* rqs, long rows, long n, long xrow, long qrow, long srow, long rqrow, @@ -2523,72 +2218,57 @@ static inline void hc_up_mix_wide_launch(bool f8, bool i8, const void* up, long hc_quant_rows_launch(i8, x, q, qs, rq, rqs, rows, n, xrow, qrow, srow, rqrow, rsrow, s); } -/* ==================================================== hc_read, the SECOND PREFILL FORM (PF2) +/* ==================================================== hc_read, second prefill form (PF2) * - * THE LAUNCHER'S RULE AT A PREFILL CHUNK of kPf2MinRows rows or more whose shape it is built for -- - * hc 4, n a multiple of 256, at most kPf2MaxNT n-tiles of columns -- with either dtype of mixing - * matrix; pinned form 3 takes it at any 128-row tile of such a band for a test. Every other - * prefill call is the wide form's. The same five steps as the wide form and the same bytes out of - * every one of them -- what moves is which workgroup does which part of the work, and how often - * (711 -> 611 us a call at a 2048-row chunk on gfx1201, E4M3 matrices): + * Used for prefill chunks of at least kPf2MinRows rows whose shape fits (hc 4, n a multiple of + * 256, at most kPf2MaxNT column n-tiles), with either mixing-matrix dtype; pinned form 3 forces it + * at any 128-row tile of such a band. Other prefill calls use the wide form. Same steps and bytes + * as the wide form, with the work redistributed (711 -> 611 us per call at a 2048-row chunk on + * gfx1201, E4M3 matrices): * - * THE A OPERAND OF THE DOWN PRODUCT IS BUILT ONCE. hc_down_wide_kernel owns 112 columns, so the - * three column tiles of a row tile each rebuild N from `h` -- the norm weight, the scale and the - * rounding to bf16, three times for every element of a 42 MB stream. A PF2 workgroup owns 64 - * rows and EVERY column, so `h` is read and N is built exactly once a call. - * THE WEIGHT IS DECODED ONCE. Every row tile of the wide form decodes the E4M3 rows of both - * mixing matrices it stages -- sixteen decodes of each matrix a call at a 2048-row chunk. A PF2 - * call decodes each matrix once, in its prologue, into the `u` scratch, which no fused form - * uses. At bf16 the prologue copies mix_down and mix_up is read where it is stored. - * THE DOWN PRODUCT'S B OPERAND SKIPS LDS. With every column in one workgroup, each 16-column - * n-tile belongs to exactly one wave, so nothing is shared and nothing needs staging: the - * prologue writes the decoded matrix in WMMA FRAGMENT ORDER and a wave's fragment is one - * 512-byte load. Only N goes through LDS, double-buffered, one barrier a slice. - * THE UP PRODUCT'S TILE IS 256 ROWS: hc_up_mix_wide_kernel at RT 256 over a bf16 mix_up, two - * m-tiles a wave. Each B fragment read out of LDS feeds two WMMAs instead of one, and the weight - * is staged and read half as often. + * N is built once: a PF2 workgroup owns 64 rows and every column, where hc_down_wide_kernel's + * three column tiles each rebuild N from `h`. + * Weights are decoded once, in the prologue, into the `u` scratch (no fused form uses it), + * instead of by every row tile. At bf16 the prologue copies mix_down and mix_up is read in place. + * The down product's B skips LDS: each 16-column n-tile belongs to one wave, so the prologue + * writes the decoded matrix in WMMA fragment order and a fragment is one 512-byte load. Only N + * goes through LDS, double-buffered, one barrier per slice. + * The up product uses a 256-row tile (hc_up_mix_wide_kernel at RT 256, two m-tiles per wave), + * so each B fragment read feeds two WMMAs. * - * WHAT KEEPS IT THE SAME BYTES. Every output element is the same chain of 16x16x16 WMMAs over - * the same fragments in the same order: N is the same expression, the decoded weight is the bf16 - * the wide form stages into LDS, the fragment layout is r4d_gdn_wmma.h's, rows and columns keep - * their place inside a 16x16 tile, and the down product keeps the K-split of hc_down_kchunk at - * the 128-row tile, partial for partial, summed by the same reduce. The norm scales are - * hc_norm_scale_kernel's sums in hc_norm_scale_kernel's order (see the prologue). r4d_selftest - * compares all three forms byte for byte, at both dtypes. + * Same bytes: every output element is the same chain of 16x16x16 WMMAs over the same fragments in + * the same order (layout from r4d_gdn_wmma.h), the down product keeps hc_down_kchunk's K-split at + * the 128-row tile with the same reduce, and the norm scales match hc_norm_scale_kernel's order. + * r4d_selftest compares all three forms byte for byte at both dtypes. * - * THE PLANES' ROOM IS RESERVED, NOT HOPED FOR. r4d_rad_hc_read_scratch sizes `u` for both planes - * at every band that reaches kPf2MinRows (hc_u_rows), so the rule never meets a `u` too small. */ + * r4d_rad_hc_read_scratch sizes `u` for both planes at every band reaching kPf2MinRows + * (hc_u_rows). */ constexpr int kPf2RT = 64; // down product: rows a workgroup, four m-tiles constexpr int kPf2NW = 3; // down product: n-tiles a wave, at most constexpr int kPf2MaxNT = kWaves * kPf2NW; // ...so ceil((lr + hc) / 16) <= 24 constexpr int kPf2UpRT = 256; // up product: rows a workgroup, two m-tiles a wave constexpr long kPf2MinRows = 512; // the rule's floor, and where `u` holds the planes -/* THE PROLOGUE: the per-stream norm scales and the two weight planes, in ONE launch, because - * the down product needs all three and none of them needs another. +/* The prologue: per-stream norm scales and the two weight planes in one launch, since the down + * product needs all three and none depends on another. * - * Blocks [0, nnb) are the scales, one WAVE a (row, stream). hc_norm_scale_kernel gives a - * (row, stream) a workgroup: thread t sums the squares of elements t, t + 256, ... in ascending - * order, each wave folds its 32 sums with r4d_wave_sum, and thread 0 adds the eight wave totals - * in ascending order. Here lane L loads elements 8L .. 8L + 7 of each 256-element chunk -- so it - * holds threads 8L .. 8L + 7's running sums, each over the same elements in the same order -- - * and a wave-private slot of LDS turns them back into thread order, so that lane L of the k-th - * r4d_wave_sum holds thread 32k + L's sum, as wave k's lane L did. Same squares, same sums, same - * butterfly, same eight adds: the same scale. A wave's LDS operations complete in order and no - * other wave touches its slot, so the round trip needs no barrier (wave_dot_lds relies on the - * same rule). + * Blocks [0, nnb) compute the scales, one wave per (row, stream), matching hc_norm_scale_kernel + * (a workgroup per (row, stream): thread t sums elements t, t + 256, ... ascending, waves fold with + * r4d_wave_sum, thread 0 adds the eight wave totals). Here lane L loads elements 8L .. 8L + 7 of + * each 256-element chunk, holding threads 8L .. 8L + 7's running sums, and a wave-private LDS slot + * puts them back in thread order so lane L of the k-th r4d_wave_sum holds thread 32k + L's sum. + * Same sums, same scale. No barrier: a wave's LDS operations complete in order. * - * Blocks [nnb, ...) write the planes, a 16-byte vector an item: + * Blocks [nnb, ...) write the planes, a 16-byte vector per item: * - * `plane`, the down product's B in FRAGMENT ORDER: [ntt][HN/16][32 lanes][8 bf16]. Lane l of - * the fragment for n-tile nt and k-step g holds column nt*16 + (l & 15) at k = 16g + 4(l >> 4) - * + {0..3, 8..11} -- what frag() reads out of an LDS tile, in the order it reads it. Columns - * below lr are mix_down decoded (or copied, at bf16), the next hc the inject weights, and the - * pad up to the n-tile clamps to the last real column, as the wide form's staging does. + * `plane`, the down product's B in fragment order: [ntt][HN/16][32 lanes][8 bf16]. Lane l of the + * fragment for n-tile nt and k-step g holds column nt*16 + (l & 15) at k = 16g + 4(l >> 4) + * + {0..3, 8..11}, as frag() reads an LDS tile. Columns below lr are mix_down (decoded, or + * copied at bf16), the next hc the inject weights, and the pad clamps to the last real column, + * as the wide form's staging does. * `udec`, mix_up decoded to plain [HN][lr] bf16 (E4M3 only; a bf16 mix_up is read in place). * - * Every decoded element is f2bf(code * scale) of the same code and the same group scale the wide - * form's staging multiplies -- the same bf16. */ + * Every decoded element is f2bf(code * scale) as in the wide form's staging. */ __global__ __launch_bounds__(kThreads) void hc_pf2_prep_kernel(const unsigned short* __restrict__ h, float* __restrict__ scaleout, long rows, long n, int hc, long hrow, float eps, long nnb, @@ -2606,8 +2286,7 @@ void hc_pf2_prep_kernel(const unsigned short* __restrict__ h, float* __restrict_ const long r = p / hc; const int c = (int)(p - r * hc); const unsigned short* hp = h + r * hrow + (long)c * n; - /* Five chunks' loads in flight before the first is summed; the chunks are still summed - * in ascending order, so a thread's running sum is the same sequence of adds. */ + /* Five chunks' loads in flight before the first is summed; summation order is unchanged. */ constexpr int kU = 5; float acc[8]; #pragma unroll @@ -2680,18 +2359,16 @@ void hc_pf2_prep_kernel(const unsigned short* __restrict__ h, float* __restrict_ } /* d = silu(W_down @ N / hc) and the inject gains, PF2: a workgroup owns 64 rows, every column and - * one K chunk -- hc_down_kchunk's at the 128-row tile, so the partials are the wide form's. + * one K chunk (hc_down_kchunk's at the 128-row tile, so partials match the wide form's). * * Wave w owns n-tiles w, w + 8 and w + 16 (those below ntt) across all four m-tiles: twelve - * accumulators, a fragment of B taken to four WMMAs and a fragment of A to three. B comes straight - * from `plane`, a slice ahead: the loads of the next slice's fragment for a k-step are issued as - * soon as the WMMAs of this slice's have read it, so they have a whole slice to land. N is built - * from `h` into one of two LDS tiles while the other is read, one barrier a slice. + * accumulators, each B fragment feeding four WMMAs and each A fragment three. B comes straight + * from `plane` a slice ahead: the next slice's fragment for a k-step is loaded as soon as this + * slice's has been consumed. N is built from `h` into one of two LDS tiles while the other is + * read, one barrier per slice. * - * Each accumulator sees the K steps of its chunk in ascending order from zero, its fragments are - * the ones the wide form's would be, and its element sits at the same place in its 16x16 tile: - * the same partial, written to the same place, or the same epilogue applied when there is one - * chunk. */ + * Each accumulator sees its chunk's K steps in ascending order from zero with the wide form's + * fragments, so partials (or the one-chunk epilogue) match. */ __global__ __launch_bounds__(kThreads) void hc_down_pf2_kernel(const unsigned short* __restrict__ h, const float* __restrict__ w, const uint4* __restrict__ plane, const float* __restrict__ scalein, @@ -2707,8 +2384,7 @@ void hc_down_pf2_kernel(const unsigned short* __restrict__ h, const float* __res static_assert(RT % kRS == 0 && MT * 16 == RT, "whole A rows a pass"); __shared__ unsigned short sA[2 * RT * kTAP]; - /* `wave` through readfirstlane: the n-tile a wave skips is then a scalar branch around its - * WMMAs rather than an EXEC mask over them. */ + /* `wave` via readfirstlane, so skipping an n-tile is a scalar branch rather than an EXEC mask. */ const int tid = threadIdx.x, lane = tid & (kWave - 1); const int wave = __builtin_amdgcn_readfirstlane(tid / kWave); const long HN = (long)hc * n, KS = HN / 16; @@ -2770,9 +2446,9 @@ void hc_down_pf2_kernel(const unsigned short* __restrict__ h, const float* __res #pragma unroll for (int i = 0; i < NW; ++i) acc[m][i] = (v8f){0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; - /* THE LOOP BODY HAS NO BRANCH ON THE SLICE. The last slice prefetches itself again and stages - * into the tile nobody reads next, which costs one slice of redundant loads a call and keeps - * every load's wait a straight-line count. */ + /* No branch on the slice in the loop body: the last slice prefetches itself again into the + * unread tile, costing one redundant slice of loads per call but keeping every wait count + * straight-line. */ fetchA(ka); stageA(sA); __syncthreads(); @@ -2820,48 +2496,38 @@ void hc_down_pf2_kernel(const unsigned short* __restrict__ h, const float* __res } } - -/* K per down-product workgroup: enough z-blocks that lr/kTNT * z covers the part, rounded to a - * whole number of kTKT slices so a slice never straddles a sub-stream. Returns HN when one block - * already covers K, which is the prefill form and takes the un-split epilogue. */ +/* K per down-product workgroup: enough z-blocks that lr/kTNT * z covers the part, rounded to whole + * kTKT slices so a slice never straddles a sub-stream. Returns HN when one block covers K (the + * prefill form, un-split epilogue). */ /* ==================================================== mtp_enter, tiled * - * THE PER-ROW FORM READS BOTH SQUARE MATRICES ONCE A ROW, and a draft round at eight concurrent - * sequences has eight. Its grid is (n/kMtpOutTB, rows) and a workgroup owns 32 output channels of - * ONE row, so the 26.2 MB of fc_h and fc_e is read `rows` times -- 210 MB a call at eight rows, - * four times the cost of one. Same shape of problem as the gated residual's, and the same fix. + * The per-row form reads both square matrices (26.2 MB) once per row, 210 MB per call at eight + * concurrent sequences. As for the gated residual, the fix is a tiled GEMM. * - * AS A GEMM IT IS TWO PRODUCTS SHARING ONE ACCUMULATOR. Number the output rows (r, k) -- one per - * sub-stream of each token -- and + * It is two products sharing one accumulator. With output rows (r, k), one per sub-stream of each + * token, * * x[(r,k)][i] = nh[(r,k)] . fc_h[i] + ne[r] . fc_e[i] * - * is C[R, n] over K = n with R = rows*hc, where the second term's A operand is the same `ne[r]` - * for all hc of a token's rows. So one tile, two A tiles, two B tiles, one accumulator: the fc_e - * product is computed hc times instead of once, which costs WMMA slots that are idle anyway and - * buys the weight being read ONCE. + * is C[R, n] over K = n with R = rows*hc; the second term's A operand `ne[r]` repeats for a token's + * hc rows. The fc_e product is computed hc times, using otherwise idle WMMA slots, so each weight + * is read once. * - * THE NORM SCALES ARE RECOMPUTED PER BLOCK rather than published, because this op has no scratch - * hook and adding one to the ABI for five floats a row is the wrong trade: `h` and `e` are 25 KiB - * a row and stay in cache across the 40 blocks, against the 655 KiB of weight each block reads. - * The reduction order is per output row here and per thread-stride there, so the scales differ in - * their last bit from the per-row kernel's -- the same class of reassociation the tiled gated - * residual already carries, on a draft head whose output is a proposal. */ -/* THE COLUMN TILE FOLLOWS THE ROW TILE. The product has no split over K -- its two products share - * an accumulator, and splitting them would need a reduce launch and a scratch the op does not have - * -- so the grid is n / NT workgroups a row tile, and each of them sums the squares of every row - * of its tile before its first weight byte. A narrow tile buys workgroups for the weight stream - * and pays for them in that prologue, once each; the prologue grows with the row tile. Measured - * at this model's n = 2560, kbench, us a call: + * Norm scales are recomputed per block, since the op has no scratch hook: `h` and `e` (25 KiB per + * row) stay in cache against 655 KiB of weight per block. The reduction order differs from the + * per-row kernel's, so scales can differ in the last bit; acceptable for a draft head. */ +/* The column tile follows the row tile. There is no K-split (the two products share an + * accumulator, and a split would need a reduce launch and scratch), so the grid is n / NT + * workgroups per row tile, each summing squares for every row of its tile first. Narrow tiles add + * workgroups for the weight stream but repeat that prologue. At n = 2560, us per call: * * columns M=2 M=4 M=8 M=16 M=32 * 16 68 70 72 124 280 * 32 48 50 55 92 303 * 64 60 63 69 103 189 * - * so 32 up to the 64-row tile and 64 at the 128-row one. Which workgroup computes a 16x16 output - * tile changes nothing about how it is computed. */ + * so 32 up to the 64-row tile and 64 at the 128-row one. The choice does not change any output. */ constexpr int kMtpTNTNarrow = 32, kMtpTNTWide = 64; template @@ -2890,21 +2556,15 @@ void mtp_enter_tiled_kernel(const unsigned short* __restrict__ h, const unsigned const long j0 = (long)blockIdx.x * NT; if (r0 >= R || j0 >= n) return; - /* ---- the scales, one output row a wave. `flat` sums the whole wide row instead of one - * sub-stream, which is the same partials added together. + /* ---- the scales, one output row per wave. `flat` sums the whole wide row (the same partials + * added together). * - * THE SUMS OF SQUARES ARE LATENCY CHAINS, AND UNHIDDEN THEY ARE THE KERNEL'S TIME. A lane's - * share of a row is 80 loads at this shape, each feeding an add; written as one load an - * iteration, every link waits out a full load latency, for every row of the tile, in every - * workgroup, before the first weight byte is used -- ~170 us a call at two, four and sixteen - * rows alike, where the weight stream is ~50. So a wave keeps its loads in flight: kSsRows rows - * at a time, and kSsPre of each row's loads issued before the first is summed. + * The sums of squares are latency chains (80 dependent loads per lane per row) and unhidden + * they dominated (~170 us per call against ~50 for the weight stream). So a wave keeps loads in + * flight: kSsRows rows at a time, kSsPre of each row's loads issued before the first is summed. + * The embedding's scale is per token, since a token's hc output rows share `e`. * - * AND THE EMBEDDING'S SCALE IS A TOKEN'S, NOT A ROW'S: the hc output rows of one token share - * `e`, so its sum is taken once a token of the tile rather than hc times. - * - * Bit-identical: each row is still summed by one wave, a lane still takes j = lane, lane + 32, - * ... ascending into one accumulator, and the wave reduction is the same. */ + * Bit-identical: each row is summed by one wave, lane j = lane, lane + 32, ... ascending. */ constexpr int kSsPre = 8, kSsRows = 4; auto sumsq = [&](const unsigned short* const* p, int nr, long len, float* out) { float acc[kSsRows]; @@ -2949,8 +2609,8 @@ void mtp_enter_tiled_kernel(const unsigned short* __restrict__ h, const unsigned for (int k = 0; k < nr; ++k) s_rs[rb + k * kWaves] = __frsqrt_rn(ss[k] / (float)hlen + eps); } - /* The tile's tokens: those of its real rows, and `rows - 1` for the padding rows past R, - * which is the last real row's token -- so the tile's tokens are [t0, t1]. */ + /* The tile's tokens [t0, t1]: those of its real rows; padding rows past R use `rows - 1`, the + * last real row's token. */ const long t0 = r0 / hc; const long t1 = ((r0 + RT < R) ? (r0 + RT - 1) : (R - 1)) / hc; for (long tb = t0 + wave; tb <= t1; tb += kWaves * kSsRows) { @@ -2976,13 +2636,11 @@ void mtp_enter_tiled_kernel(const unsigned short* __restrict__ h, const unsigned #pragma unroll for (int in = 0; in < AN; ++in) acc[im][in] = (v8f){0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; - /* THE NEXT K SLICE IS LOADED INTO REGISTERS WHILE THIS ONE COMPUTES. Staged straight through, - * every one of the n / kTKT slices exposes a global latency in full -- nothing else in the - * block is runnable while its loads are out, and at decode the grid is a few workgroups a CU. - * So a thread's share of slice k + 1 -- the raw `h`, `e` and norm-weight values of its A items - * and the weight rows of its B items -- is issued right after slice k is written to LDS, and - * waited for at the next write. Only WHEN a byte is loaded moves: the values written to LDS - * and every product are the ones the straight form computes. */ + /* The next K slice is loaded into registers while this one computes; otherwise each of the + * n / kTKT slices exposes a full global latency, with few workgroups per CU at decode. A + * thread's share of slice k + 1 (raw `h`, `e` and norm-weight values for its A items, weight + * rows for its B items) is issued after slice k is written to LDS and awaited at the next + * write. Values are unchanged. */ constexpr int kAI = (RT * (kTKT / 8) + kThreads - 1) / kThreads; constexpr int kBI = (NT * (kTKT / 8) + kThreads - 1) / kThreads; struct APre { uint4 h, e; float4 wh0, wh1, we0, we1; }; @@ -3012,10 +2670,9 @@ void mtp_enter_tiled_kernel(const unsigned short* __restrict__ h, const unsigned return o.v; } }; - /* AN A ITEM'S ROWS ARE THE SAME EVERY K STEP: its token and sub-stream are a 64-bit division - * by `hc` and its remainder, worked out once here as element offsets. Left in the step, gfx12's - * compiler expands the division again every slice -- twenty times over at the 64-row tile and - * fifty at the 128-row one -- where LLVM 22 moved it out of the loop. The same addresses. */ + /* An A item's rows are the same every K step: its token and sub-stream (a 64-bit division by + * `hc`) are computed once here as element offsets. Inside the step, gfx12's compiler would + * redo the division every slice. */ uint32_t aoh[kAI], aoe[kAI], aow[kAI], ak8[kAI]; #pragma unroll for (int a = 0; a < kAI; ++a) { @@ -3109,8 +2766,8 @@ void mtp_enter_tiled_kernel(const unsigned short* __restrict__ h, const unsigned if (nt >= NT16) continue; const long j = j0 + nt * 16 + nn; if (j >= n) continue; - /* The eight rows are consecutive output rows: one division for the first, and the - * (token, sub-stream) pair stepped from there rather than divided out again a row. */ + /* The eight rows are consecutive output rows: one division for the first, then the + * (token, sub-stream) pair is stepped. */ const long Rq = r0 + mt * 16 + e0; long tq = Rq / hc, kq = Rq % hc; #pragma unroll @@ -3123,35 +2780,28 @@ void mtp_enter_tiled_kernel(const unsigned short* __restrict__ h, const unsigned } /* ==================================================== mtp_enter from 32 tokens up * - * THE TILED KERNEL ABOVE IS THE SHAPE FOR A FEW ROWS -- a draft round -- and past that it pays - * three costs in proportion to the rows. It computes the embedding term `ne[r] . fc_e[i]` once for each - * of a token's hc output rows, because the two products share its accumulator; every one of its - * 40 column blocks sums the squares of its 128 rows again before its first weight byte; and each - * of those blocks re-stages and re-normalises the same A rows. At 2048 tokens that is 6.2 ms a - * chunk, ~22 TF/s of useful work. + * The tiled kernel above suits a draft round's few rows; beyond that its costs grow with rows: it + * computes the embedding term `ne[r] . fc_e[i]` once per output row, and each of its 40 column + * blocks re-sums squares and re-stages the same A rows (6.2 ms per 2048-token chunk). * - * HERE THE TWO PRODUCTS ARE SEPARATE GEMMS. The scales are one pass, a wave a row - * (mtp_prefill_scale_kernel). The embedding term is a [rows, n] GEMM over the tokens, kept in f32 - * in scratch; the stream term is the [rows * hc, n] GEMM, and its epilogue adds the token's - * embedding term before the one rounding to bf16. Both are mtp_prefill_gemm_kernel: 128 x 128 - * tiles, eight waves each holding 64 x 32, the next K tile in registers while this one computes, - * the A tile normalised and the weight rows decoded on the way into LDS. + * Here the two products are separate GEMMs. Scales take one pass, a wave per row + * (mtp_prefill_scale_kernel). The embedding term is a [rows, n] GEMM kept in f32 scratch; the + * stream term is the [rows * hc, n] GEMM whose epilogue adds the token's embedding term before the + * single bf16 rounding. Both use mtp_prefill_gemm_kernel: 128 x 128 tiles, eight waves of 64 x 32, + * the next K tile in registers during compute, A normalised and weights decoded on the way to LDS. * - * THE BYTES DIFFER FROM THE TILED KERNEL'S. That one adds both products into one accumulator a K - * step at a time; this one sums each over all of K and adds the two once. Same terms, different - * rounding, on a head whose output is a draft the trunk verifies -- the tiled gated residual's - * scales already differ from its per-row form's in the same way. */ -/* THE FORM CHANGES AT 32 TOKENS. Below it the grid is n/128 = 20 blocks and the three launches - * cost ~100 us whatever the rows; the tiled kernel is under that there and over it above. - * rad-kbench on the Flash-Next container, us a call (tiled / this form): + * Bytes differ from the tiled kernel's (which accumulates both products together per K step); + * acceptable for a draft head the trunk verifies. */ +/* The form switches at 32 tokens: below, the grid is n/128 = 20 blocks and the three launches cost + * ~100 us regardless of rows. us per call (tiled / this form), Flash-Next: * * tokens 8 16 32 64 128 512 2048 * 52 / 98 88 / 105 182 / 117 267 / 158 433 / 213 1540 / 627 6180 / 2430 */ constexpr long kMtpPrefillRows = 32; -/* One wave a row: rows [0, R) are the output rows (t, k) over `h` -- sub-stream k of token t, or - * the whole wide row when `flat` -- and rows [R, R + rows) are the tokens over `e`. A lane sums - * j = lane, lane + 32, ... in order, eight loads ahead of the adds. */ +/* One wave per row: rows [0, R) are the output rows (t, k) over `h` (sub-stream k of token t, or + * the whole wide row when `flat`), rows [R, R + rows) the tokens over `e`. A lane sums j = lane, + * lane + 32, ... in order, eight loads ahead of the adds. */ __global__ __launch_bounds__(kThreads) void mtp_prefill_scale_kernel(const unsigned short* __restrict__ h, const unsigned short* __restrict__ e, @@ -3189,10 +2839,10 @@ void mtp_prefill_scale_kernel(const unsigned short* __restrict__ h, #define MP_TM 4 /* WMMA tiles a wave over M ... */ #define MP_TN 2 /* ... and over N: 64 x 32 a wave, 128 x 128 a block */ -/* C = normalise(A) @ fc^T for one of the two products. EPASS: A is `e`, one row a token, and the +/* C = normalise(A) @ fc^T for one of the two products. EPASS: A is `e`, one row per token, and the * f32 result goes to `eterm`. Otherwise A is `h` read as rows (t, k), and the result plus the - * token's `eterm` row is rounded once into `x`. The weight is bf16 rows, or at F8 E4M3 rows with - * their f32 128-column group scales in each row's tail (r4d_hc_fp8.h), `fld` bytes apart. */ + * token's `eterm` row is rounded once into `x`. Weights are bf16 rows or, with F8, E4M3 rows with + * f32 128-column group scales in each row's tail (r4d_hc_fp8.h), `fld` bytes apart. */ template __global__ __launch_bounds__(kThreads) void mtp_prefill_gemm_kernel(const unsigned short* __restrict__ src, long srow, @@ -3213,7 +2863,7 @@ void mtp_prefill_gemm_kernel(const unsigned short* __restrict__ src, long srow, const long m0 = (long)blockIdx.y * BM, n0 = (long)blockIdx.x * BN; /* A thread's staging slots: chunk c = tid + 256 i is tile row c / CPR, K offset (c % CPR) * 8. - * Per slot the row's source, its gain offset and its scale, fixed for the whole K loop. */ + * Each slot's row source, gain offset and scale are fixed for the whole K loop. */ const unsigned short* asrc[AL]; const float* again[AL]; float asc[AL]; @@ -3351,22 +3001,13 @@ static inline long long mtp_prefill_bytes(long long rows, long long n, long long return al(rows * hc * 4) + al(rows * 4) + al(rows * n * 4); } -/* ==================================================== HOW MANY WORKGROUPS THE DOWN PRODUCT GETS +/* ==================================================== down-product workgroup count * - * THE SPLIT HAS TO COUNT THE ROW TILES, NOT JUST THE COLUMN ONES. Taking `nb` as ceil(ncol/kTNT) - * alone -- five or six workgroups -- and choosing `ks` to bring that to kTKSPLIT_WANT is right at - * one row tile and wrong at any other; disabling the split outright at rt = 128, on the grounds - * that the prefill form does not need it, makes it worse still. - * - * WHAT THAT COSTS: rt is 128 at or above kTileMinRows = 64 rows, and a decode step has - * C * (1 + n_spec) rows -- so SIXTEEN concurrent sequences at depth 3 is exactly 64 rows and falls - * onto the prefill tile with no split. Six workgroups on a 64-CU part. That is a throughput CLIFF - * of about 25% at one particular concurrency, invisible from any smaller one, because the usual - * shape is eight slots and 32 rows. - * - * So `nrt` enters here and there is no rt = 128 special case: the split is a function of the WHOLE - * grid, it turns itself off exactly when the grid is already wide enough (about 2800 rows at this - * model's ncol), and no row count has a cliff in it. */ + * The split counts row tiles (`nrt`) as well as column tiles. Counting only ceil(ncol/kTNT) (five + * or six workgroups), or disabling the split at rt = 128, leaves a large decode step (e.g. sixteen + * sequences at depth 3) with six workgroups on 64 CUs, a ~25% throughput cliff. As a function of + * the whole grid, the split turns itself off once the grid is wide enough (about 2800 rows at this + * model's ncol). */ static inline long hc_down_kchunk(long long lr, long long HN, long long nrt) { const long long nb = ((lr + kTNT - 1) / kTNT) * (nrt > 0 ? nrt : 1); const long long chunks = (HN + kTKT - 1) / kTKT; @@ -3375,29 +3016,23 @@ static inline long hc_down_kchunk(long long lr, long long HN, long long nrt) { if (want > chunks) want = chunks; return (long)(((chunks + want - 1) / want) * kTKT); } -/* THE TILE A ROW COUNT PICKS. One place, because the planner and the call site have to agree. +/* The row tile for a row count, defined once so the planner and the call site agree. * - * STRICTLY GREATER, and the character matters. A 128-row tile at EXACTLY 64 rows stages 128 rows - * of A to use 64 -- the staging loop clamps the overshoot to `rows - 1`, so half the LDS traffic - * and half the WMMA slots go to duplicate rows -- and its 26112 B of LDS puts two workgroups on a - * WGP where the 64-row tile puts three. It buys nothing in return: the weight is re-read - * ceil(rows/rt) times and ceil(64/64) is ceil(64/128) is one. Above 64 rows it does halve that - * re-read and is the right tile. A `>=` here costs several milliseconds a step at exactly the row - * count where the two tiles are equivalent on traffic. */ + * Strictly greater than 64: at exactly 64 rows a 128-row tile re-reads the weight just as often + * (once) but wastes half its LDS traffic and WMMA slots on clamped duplicate rows, and its 26112 B + * of LDS fits two workgroups per WGP instead of three. Do not change to `>=`. */ static inline int hc_down_rt(long long rows) { return (rows > kTileMinRows) ? 128 : (rows > 32 ? 64 : 32); } -/* THE PARTIAL BUFFER FOR ANY ROW COUNT UP TO THE BAND'S M, in bytes. +/* The partial buffer for any row count up to the band's M, in bytes. * - * The planner does not know the step's rows and `ks * rows` is NOT monotone in rows: a smaller row - * count takes a coarser tile and therefore a DEEPER split, so an endpoint is not the worst case. - * This walks the band instead. Past the point where the row tiles alone cover the part the split + * `ks * rows` is not monotone in rows (fewer rows take a coarser tile and a deeper split), so the + * band is walked rather than its endpoints checked. Once row tiles alone cover the part the split * is off and the buffer grows linearly, so the walk stops there and takes M as the last candidate. * - * The rule is: derive the split from `lr` on BOTH sides, and size the buffer for the widest `ncol` - * a gain fold can produce. Breaking it overruns the partial buffer, which the kbench red zone - * catches. */ + * Invariant: derive the split from `lr` on both sides and size for the widest `ncol` a gain fold + * can produce, or the partial buffer overruns. */ static inline long long hc_part_bytes(long long M, long long lr, long long HN) { const long long ncol = lr + (long long)kHcMax; const long long hi = (M < 4096) ? M : 4096; @@ -3470,24 +3105,23 @@ static inline void hc_up_tiled_launch(int rt, bool f8, const void* up, long uld, #undef HC_UP_CASE } -/* THE PF2 FORM'S WEIGHT PLANES in the `u` scratch, in bytes: mix_down (and the inject weights) in - * fragment order over ntt n-tiles, then -- E4M3 only -- mix_up decoded to [HN][lr] bf16. */ +/* The PF2 form's weight planes in the `u` scratch, in bytes: mix_down (and the inject weights) in + * fragment order over ntt n-tiles, then (E4M3 only) mix_up decoded to [HN][lr] bf16. */ static inline long long pf2_plane_bytes(long long HN, long long lr, long long ntt, bool f8) { return ntt * 16 * HN * 2 + (f8 ? HN * lr * 2 : 0); } -/* `u`'S ROWS IN THE SCRATCH, [rows][HN] bf16: the band's M, and at a band that reaches the PF2 rule - * at least the rows its planes take at the widest fold (ncol = lr + hc) and either dtype -- - * ceil((lr + hc) / 16) * 16 + lr. The scratch hook and the launcher both size `u` from this, so the - * offsets behind it agree, and the rule never finds the planes without room. */ +/* Rows of `u` in the scratch, [rows][HN] bf16: the band's M and, at a band reaching the PF2 rule, + * at least the rows its planes need at the widest fold (ncol = lr + hc) and either dtype, + * ceil((lr + hc) / 16) * 16 + lr. The scratch hook and the launcher both size `u` from this. */ static inline long long hc_u_rows(long long M, long long lr, long long hc) { const long long pf2 = ((lr + hc + 15) / 16) * 16 + lr; return (M >= kPf2MinRows && pf2 > M) ? pf2 : M; } -/* THE PF2 FORM, start to finish: prologue, down product, reduce, up product and mix, codes. `wsp` - * is the plane space -- the `u` buffer, which no fused form uses -- and the caller has checked it - * holds pf2_plane_bytes() and that hc is 4. Returns a RAD code. */ +/* The PF2 form: prologue, down product, reduce, up product and mix, codes. `wsp` is the plane + * space (the `u` buffer); the caller has checked it holds pf2_plane_bytes() and that hc is 4. + * Returns a RAD code. */ static int hc_pf2_launch(bool f8, bool i8, const unsigned short* h, const float* w, const void* down, long dld, const void* up, long uld, const unsigned short* injw, unsigned short* dbuf, float* scale, @@ -3528,8 +3162,8 @@ static int hc_pf2_launch(bool f8, bool i8, const unsigned short* h, const float* if (hipGetLastError() != hipSuccess) return RAD_E_DEVICE; } - /* The up product and mix: the wide kernel at 256 rows over a bf16 mix_up, whose row pitch is - * lr -- the decoded plane, or the stored matrix at bf16. */ + /* The up product and mix: the wide kernel at 256 rows over a bf16 mix_up with row pitch lr + * (the decoded plane, or the stored matrix at bf16). */ hipLaunchKernelGGL((hc_up_mix_wide_kernel<4, false, kPf2UpRT>), dim3((unsigned)(n / kWideCH), (unsigned)((rows + kPf2UpRT - 1) / kPf2UpRT)), dim3(kThreads), 0, (hipStream_t)s, (const void*)ubf, lr, @@ -3548,10 +3182,9 @@ enum { HCE_X = 0, HCE_H }; enum { HCW_Y = 0, HCW_INJ, HCW_H }; enum { HCR_H = 0, HCR_W, HCR_DOWN, HCR_UP, HCR_INJW, HCR_X, HCR_INJ, HCR_Q, HCR_S, HCR_RQ, HCR_RS }; -/* The LDS kernel A holds N in, as bf16, beside its own static planes. gfx1201 gives a workgroup - * 64 KiB, so N may have 64 KiB less kHcReadAStaticLds -- 30576 elements. The row table claims - * `n <= 7552` and `hc <= 4`, which is 30208 of them, and the shim refuses the rest by name rather - * than launching a kernel whose shared allocation fails. */ +/* LDS for kernel A's bf16 N beside its static planes: gfx1201 gives a workgroup 64 KiB, so N gets + * 64 KiB less kHcReadAStaticLds (30576 elements). The row table claims `n <= 7552` and `hc <= 4` + * (30208); the shim refuses larger shapes instead of failing the launch. */ static const long kHcLdsMaxHN = (65536 - kHcReadAStaticLds) / (long)sizeof(unsigned short); static int hc_common(const RadArgs* a, const RadTensor* h, long long* rows, long long* n, @@ -3584,7 +3217,7 @@ extern "C" int r4d_rad_hc_enter(const RadArgs* a, RadStream s) { return (int)hipGetLastError(); } -static int rad_hc_write_body(const RadArgs* a, const R4dSink& sk) { +extern "C" int r4d_rad_hc_write(const RadArgs* a, RadStream stream) { const RadTensor* y = r4d_opt(a, HCW_Y); const RadTensor* inj = r4d_opt(a, HCW_INJ); const RadTensor* h = r4d_opt(a, HCW_H); @@ -3599,17 +3232,15 @@ static int rad_hc_write_body(const RadArgs* a, const R4dSink& sk) { if (yrow < 0 || irow < 0 || yrows < rows || irows < rows) return R4D_NO(RAD_E_STRIDE); const unsigned blocks = (unsigned)((n + kThreads - 1) / kThreads); - return R4D_EMIT(sk, hc_write_kernel, dim3(blocks, (unsigned)rows), dim3(kThreads), 0, + return R4D_EMIT(stream, hc_write_kernel, dim3(blocks, (unsigned)rows), dim3(kThreads), 0, (const unsigned short*)y->data, (const unsigned short*)inj->data, (unsigned short*)h->data, (long)rows, (long)n, (int)hc, (long)yrow, (long)irow, (long)hrow); } -R4D_ENTRY(r4d_rad_hc_write, rad_hc_write_body) - enum { MTE_H = 0, MTE_E, MTE_WH, MTE_WE, MTE_FCH, MTE_FCE, MTE_X }; -static int rad_mtp_enter_body(const RadArgs* a, const R4dSink& sk) { +extern "C" int r4d_rad_mtp_enter(const RadArgs* a, RadStream stream) { int emit_rc = RAD_OK; const RadTensor* h = r4d_opt(a, MTE_H); const RadTensor* e = r4d_opt(a, MTE_E); @@ -3621,8 +3252,8 @@ static int rad_mtp_enter_body(const RadArgs* a, const R4dSink& sk) { if (!h || !e || !wh || !we || !fch || !fce || !x) return R4D_NO(RAD_E_INVAL); R4D_DT(h, RAD_BF16); R4D_DT(e, RAD_BF16); R4D_DT(x, RAD_BF16); R4D_DT(wh, RAD_F32); R4D_DT(we, RAD_F32); - /* BOTH fc MATRICES bf16 OR BOTH E4M3 rows with f32 128-column group scales in each row's tail - * (r4d_hc_fp8.h's geometry at K = n), as the stored dtype says. */ + /* Both fc matrices bf16, or both E4M3 rows with f32 128-column group scales in each row's tail + * (r4d_hc_fp8.h at K = n), per the stored dtype. */ const bool f8 = fch->dtype == RAD_F8E4M3; if (f8) { R4D_DT(fce, RAD_F8E4M3); } else { R4D_DT(fch, RAD_BF16); R4D_DT(fce, RAD_BF16); } @@ -3630,9 +3261,8 @@ static int rad_mtp_enter_body(const RadArgs* a, const R4dSink& sk) { const int rc = hc_common(a, h, &rows, &n, &hc, &hrow); if (rc != RAD_OK) return rc; const long long HN = n * hc; - /* `nh` and `ne` both live in LDS for the whole of the second phase -- that is what makes one - * pass over a weight row enough -- so the wide stream plus one narrow row has to fit beside - * the per-wave staging slots. 64 KiB less the 4 KiB of `s_stage` and the reduction planes. */ + /* `nh` and `ne` stay in LDS for the second phase, so the wide stream plus one row must fit + * beside the staging slots and reduction planes in 64 KiB. */ if ((HN + n) > kMtpLdsMaxN) return R4D_NO(RAD_E_SHAPE); long long erows = 0, xrows = 0; @@ -3640,8 +3270,8 @@ static int rad_mtp_enter_body(const RadArgs* a, const R4dSink& sk) { const long long xrow = r4d_rows_pitch(x, HN, &xrows); if (erow < 0 || xrow < 0 || erows < rows || xrows < rows) return R4D_NO(RAD_E_STRIDE); if (r4d_numel(wh) < HN || r4d_numel(we) < n) return R4D_NO(RAD_E_SHAPE); - /* A stored row's pitch, in the stored dtype's elements. At E4M3 the DECLARED shape arrives - * ([n, n], the stored dtype), so the pitch is derived by the layout's rule -- see hc_read. */ + /* A stored row's pitch in the stored dtype's elements. At E4M3 the declared shape ([n, n]) + * arrives, so the pitch comes from the layout rule, as in hc_read. */ long long fld = n; if (f8) { if (!r4d_hc8::group_ok(n, r4d_hc8::kDownGroup)) return R4D_NO(RAD_E_SHAPE); @@ -3655,10 +3285,9 @@ static int rad_mtp_enter_body(const RadArgs* a, const R4dSink& sk) { if (!r4d_contig(wh) || !r4d_contig(we) || !r4d_contig(fch) || !r4d_contig(fce)) return R4D_NO(RAD_E_STRIDE); - /* `ngroup` == 1 is the FLAT reading -- one rsqrt over the whole wide row instead of one per - * sub-stream. The checkpoint fits both and only the acceptance rate can tell them apart, so - * the choice travels as a parameter rather than being compiled in. Default is the grouped - * form, which is what every gated residual in this architecture does. */ + /* `ngroup` == 1 is the flat norm: one rsqrt over the whole wide row instead of one per + * sub-stream. The checkpoint does not determine which, so it is a parameter; the default is + * grouped, as in every gated residual of this architecture. */ const long long ngroup = r4d_geti_or(a, "ngroup", hc); if (ngroup != 1 && ngroup != hc) return R4D_NO(RAD_E_SHAPE); const float eps = (float)r4d_getf(a, "eps", 1e-6); @@ -3667,35 +3296,30 @@ static int rad_mtp_enter_body(const RadArgs* a, const R4dSink& sk) { const unsigned blocks = (unsigned)((n + kMtpOutTB - 1) / kMtpOutTB); const size_t lds = (size_t)(HN + n) * sizeof(unsigned short); - /* THE ROW COUNT PICKS THE SHAPE, as it does for the gated residual. One row is the floor and - * the per-row kernel is at it; a draft round at eight sequences carries eight rows and pays - * eight times the weight. */ + /* The row count picks the form, as for the gated residual: the per-row kernel is the floor at + * one row but re-reads the weight per row. */ const long R = rows * hc; const bool tileable = (n % kTKT) == 0 && (n % 8) == 0 && (hrow % 8) == 0 && (((uintptr_t)h->data & 15u) == 0u) && (((uintptr_t)e->data & 15u) == 0u) && (((uintptr_t)fch->data & 15u) == 0u) && (((uintptr_t)fce->data & 15u) == 0u) && (((uintptr_t)wh->data & 15u) == 0u) && (((uintptr_t)we->data & 15u) == 0u) && (erow % 8) == 0; - /* E4M3 fc rows are read by the TILED kernel at every row count, one row included: at one row - * it is 46 us against the per-row bf16 kernel's 54, where a per-row E4M3 dot is 57 -- - * the per-row kernel's win is its transposed LDS layout, which the codes cannot use. So the - * per-row kernel stays bf16's alone, and a shape the tile cannot take is refused. */ + /* E4M3 fc rows always use the tiled kernel, even at one row (46 us, against 57 for a per-row + * E4M3 dot): the per-row kernel's advantage is its transposed LDS layout, which codes cannot + * use. A shape the tile cannot take is refused. */ if (f8 && !tileable) return R4D_NO(RAD_E_SHAPE); - /* THE PREFILL FORM from kMtpPrefillRows tokens, on its scratch: a shape the tile takes is one - * this form takes, so past the threshold there is no second path. */ + /* The prefill form from kMtpPrefillRows tokens, on its scratch; it accepts every shape the + * tile does. */ if (rows >= kMtpPrefillRows && tileable) { if (!a->scratch || a->scratch_bytes < mtp_prefill_bytes(rows, n, hc)) return R4D_NO(RAD_E_SCRATCH); - /* Three launches over a private scratch, which the descriptor form does not cover; it is - * submitted individually (ABI v10), as hc_read's tiled path is. */ - if (sk.desc) return RAD_E_UNSUPPORTED; auto al = [](long long b) { return (b + 255) & ~255LL; }; float* rs = (float*)a->scratch; float* re = (float*)((unsigned char*)a->scratch + al(R * 4)); float* et = (float*)((unsigned char*)a->scratch + al(R * 4) + al(rows * 4)); const unsigned sb = (unsigned)((R + rows + kWaves - 1) / kWaves); hipLaunchKernelGGL(mtp_prefill_scale_kernel, dim3(sb), dim3(kThreads), 0, - (hipStream_t)sk.stream, + (hipStream_t)stream, (const unsigned short*)h->data, (const unsigned short*)e->data, rs, re, (long)rows, (long)n, (int)hc, ngroup == 1 ? 1 : 0, eps, (long)hrow, (long)erow); @@ -3703,7 +3327,7 @@ static int rad_mtp_enter_body(const RadArgs* a, const R4dSink& sk) { const dim3 gh((unsigned)((n + 127) / 128), (unsigned)((R + 127) / 128)); #define MTP_PF(F8_, EP_, G_, SRC_, SROW_, GAIN_, RSC_, FC_) \ hipLaunchKernelGGL((mtp_prefill_gemm_kernel), G_, dim3(kThreads), 0, \ - (hipStream_t)sk.stream, (const unsigned short*)SRC_, (long)SROW_, \ + (hipStream_t)stream, (const unsigned short*)SRC_, (long)SROW_, \ (const float*)GAIN_, RSC_, (const void*)FC_, (long)fld, et, \ (unsigned short*)x->data, (long)rows, (long)n, (int)hc, wadd, \ (long)xrow) @@ -3722,7 +3346,7 @@ static int rad_mtp_enter_body(const RadArgs* a, const R4dSink& sk) { const int nt = rt >= 128 ? kMtpTNTWide : kMtpTNTNarrow; const dim3 gm((unsigned)((n + nt - 1) / nt), (unsigned)((R + rt - 1) / rt)); #define MTP_TILE_CASE(RT_, NT_, F8_) \ - emit_rc = R4D_EMIT(sk, (mtp_enter_tiled_kernel), gm, dim3(kThreads), 0, \ + emit_rc = R4D_EMIT(stream, (mtp_enter_tiled_kernel), gm, dim3(kThreads), 0, \ (const unsigned short*)h->data, \ (const unsigned short*)e->data, (const float*)wh->data, \ (const float*)we->data, (const void*)fch->data, \ @@ -3739,10 +3363,10 @@ static int rad_mtp_enter_body(const RadArgs* a, const R4dSink& sk) { } #undef MTP_TILE_CASE if (emit_rc != RAD_OK) return emit_rc; - return sk.desc ? RAD_OK : (int)hipGetLastError(); + return (int)hipGetLastError(); } - emit_rc = R4D_EMIT(sk, mtp_enter_kernel, dim3(blocks, (unsigned)rows), dim3(kThreads), lds, + emit_rc = R4D_EMIT(stream, mtp_enter_kernel, dim3(blocks, (unsigned)rows), dim3(kThreads), lds, (const unsigned short*)h->data, (const unsigned short*)e->data, (const float*)wh->data, (const float*)we->data, (const unsigned short*)fch->data, @@ -3750,12 +3374,11 @@ static int rad_mtp_enter_body(const RadArgs* a, const R4dSink& sk) { (long)rows, (long)n, (int)hc, ngroup == 1 ? 1 : 0, eps, wadd, (long)hrow, (long)erow, (long)xrow); if (emit_rc != RAD_OK) return emit_rc; - return sk.desc ? RAD_OK : (int)hipGetLastError(); + return (int)hipGetLastError(); } -R4D_ENTRY(r4d_rad_mtp_enter, rad_mtp_enter_body) -/* The prefill form's scratch, for a band that reaches it. `M` is the band's ceiling and the form - * is chosen per call, so a band reaching kMtpPrefillRows is sized at its ceiling. */ +/* The prefill form's scratch, for a band that reaches it. The form is chosen per call, so a band + * reaching kMtpPrefillRows is sized at its ceiling `M`. */ extern "C" int64_t r4d_rad_mtp_enter_scratch(const RadArgs* a) { const long long M = r4d_geti_or(a, "M", 0); const long long n = r4d_geti_or(a, "n", 0); @@ -3763,40 +3386,30 @@ extern "C" int64_t r4d_rad_mtp_enter_scratch(const RadArgs* a) { if (M <= 0 || n <= 0 || hc <= 0) return R4D_NO(RAD_E_SHAPE); return M >= kMtpPrefillRows ? mtp_prefill_bytes(M, n, hc) : 0; } -/* `d` between the two kernels, and the per-stream norm scales beside it. Sized from the BAND's `M` - * rather than from the operand, because the arena is sized once for the whole band and the launch - * below checks against the same number -- a scratch hook that answered for the step's actual rows - * would size the arena for whatever step happened to be asked first. */ +/* `d` between the two kernels, with the per-stream norm scales beside it. Sized from the band's `M`, + * not the operand: the arena is sized once per band and the launch checks the same number. */ extern "C" int64_t r4d_rad_hc_read_scratch(const RadArgs* a) { const long long M = r4d_geti_or(a, "M", 0); const long long lr = r4d_geti_or(a, "lowrank", 0); const long long n = r4d_geti_or(a, "n", 0); const long long hc = r4d_geti_or(a, "hc", 0); if (M <= 0 || lr <= 0 || n <= 0 || hc <= 0) return R4D_NO(RAD_E_SHAPE); - /* `d` [M, lowrank] bf16, the per-stream norm scales [M, kHcMax] f32, and `u` [M, hc*n] bf16 -- - * 20 KiB a row at this model's shape, which is what buys the up-matvec its own grid. A band - * that reaches the PF2 rule holds its weight planes in `u` as well, so `u` there has at least - * the rows they take (hc_u_rows). + /* `d` [M, lowrank] bf16, the per-stream norm scales [M, kHcMax] f32, and `u` [M, hc*n] bf16 + * (20 KiB per row here; it gives the up matvec its own grid). At a band reaching the PF2 rule + * `u` also holds the weight planes (hc_u_rows). * - * PLUS THE SPLIT-K PARTIALS. Every row count below a few thousand takes a split, so this is - * not a decode-only buffer and is not bounded by kTileMinRows -- hc_part_bytes - * walks the band because ks * rows is not monotone in rows. */ + * Plus the split-K partials: every row count below a few thousand splits, so this is not + * bounded by kTileMinRows; hc_part_bytes walks the band. */ const long long HN = hc * n; - /* THE SPLIT MUST BE COMPUTED FROM THE SAME NUMBER IN BOTH PLACES. The call site knows whether - * this connection has inject weights and the planner does not, so both derive `kc` from `lr` - * alone and the buffer is sized for the widest ncol a fold can produce. Deriving it from ncol - * here and from lr there gives two different split counts for the same shape, and the partial - * buffer then overruns. */ + /* The split must come from the same number here and at the call site. Only the call site knows + * whether there are inject weights, so both derive `kc` from `lr` and the buffer is sized for + * the widest ncol; mismatched derivations overrun the partial buffer. */ return M * ((long long)lr * 2 + (long long)kHcMax * 4) + hc_u_rows(M, lr, hc) * HN * 2 + hc_part_bytes(M, lr, HN); } -static int rad_hc_read_body(const RadArgs* a, const R4dSink& sk) { +extern "C" int r4d_rad_hc_read(const RadArgs* a, RadStream s) { int emit_rc = RAD_OK; - /* The tiled path below launches directly -- it declines to describe -- and takes the stream - * as `s`. */ - const RadStream s = sk.stream; - (void)s; const RadTensor* h = r4d_opt(a, HCR_H); const RadTensor* w = r4d_opt(a, HCR_W); const RadTensor* down = r4d_opt(a, HCR_DOWN); @@ -3810,23 +3423,22 @@ static int rad_hc_read_body(const RadArgs* a, const R4dSink& sk) { const RadTensor* rqs = r4d_opt(a, HCR_RS); if (!h || !w || !down || !up || !x) return R4D_NO(RAD_E_INVAL); R4D_DT(h, RAD_BF16); R4D_DT(w, RAD_F32); - /* THE MIXING MATRICES ARE BOTH bf16 OR BOTH E4M3 rows (r4d_hc_fp8.h), and which one is the - * stored dtype's to say: the layout hook that wrote them is the one this row resolved to. */ + /* The mixing matrices are both bf16 or both E4M3 rows (r4d_hc_fp8.h), per the stored dtype + * written by this row's layout hook. */ const bool f8 = down->dtype == RAD_F8E4M3; if (f8) { R4D_DT(up, RAD_F8E4M3); } else { R4D_DT(down, RAD_BF16); R4D_DT(up, RAD_BF16); } R4D_DT(x, RAD_BF16); - /* An inject WEIGHT with no `inj` output is a connection whose two halves disagree about - * whether there is a write; refused rather than silently dropped. */ + /* An inject weight without an `inj` output (or vice versa) is inconsistent and refused. */ if ((injw != nullptr) != (inj != nullptr)) return R4D_NO(RAD_E_INVAL); if (injw) { R4D_DT(injw, RAD_BF16); R4D_DT(inj, RAD_BF16); } if ((q != nullptr) != (qs != nullptr)) return R4D_NO(RAD_E_INVAL); - /* THE CODES' DTYPE IS THE FORMAT: E4M3 for an fp8 trunk, int8 for an int8 one (gemm_i8a8_*), - * the same scale grid either way (r4d_q8.h). The rotated twin below stays E4M3 -- it is the - * routed experts' operand, whatever the trunk is. */ + /* The codes' dtype is the format: E4M3 for an fp8 trunk, int8 for an int8 one (gemm_i8a8_*), + * on the same scale grid (r4d_q8.h). The rotated codes stay E4M3, as the routed experts' + * operand. */ if (q && q->dtype != RAD_F8E4M3 && q->dtype != RAD_I8) return R4D_NO(RAD_E_DTYPE); if (q) R4D_DT(qs, RAD_F32); const bool i8 = q && q->dtype == RAD_I8; - /* The rotated twin rides in the plain codes' finisher, so it is refused without them. */ + /* The rotated codes are produced by the plain codes' finisher, so they require them. */ if ((rq != nullptr) != (rqs != nullptr) || (rq && !q)) return R4D_NO(RAD_E_INVAL); if (rq) { R4D_DT(rq, RAD_F8E4M3); R4D_DT(rqs, RAD_F32); } @@ -3835,15 +3447,13 @@ static int rad_hc_read_body(const RadArgs* a, const R4dSink& sk) { if (rc != RAD_OK) return rc; const long long HN = n * hc; if (HN > kHcLdsMaxHN) return R4D_NO(RAD_E_SHAPE); - /* One workgroup owns 128 channels AND the 128-column scale group over them, so a channel count - * that is not a whole number of them would split a group across two workgroups -- two amaxes - * for one scale. */ + /* A workgroup owns 128 channels and their scale group, so n must be whole groups. */ if (n % kUpTB) return R4D_NO(RAD_E_SHAPE); const long long lr = r4d_geti_or(a, "lowrank", 0); if (lr <= 0) return R4D_NO(RAD_E_SHAPE); - /* A row's pitch in ELEMENTS of the stored dtype: HN or lr for bf16, the stored row's bytes for - * E4M3, whose dot needs K a multiple of its 256-element step and whose up rows split in four + /* Row pitch in elements of the stored dtype: HN or lr for bf16, the stored row's bytes for + * E4M3, whose dot needs K a multiple of its 256-element step and whose up rows split into four * sixteen-code quarters of at most kUpMaxQ loads. */ long long dld = HN, uld = lr; if (f8) { @@ -3851,10 +3461,9 @@ static int rad_hc_read_body(const RadArgs* a, const R4dSink& sk) { if (!r4d_hc8::group_ok(HN, gd) || !r4d_hc8::group_ok(lr, gu) || HN % kHc8Step || gu / 16 > kUpMaxQ) return R4D_NO(RAD_E_SHAPE); - /* THE DECLARED SHAPE ARRIVES, NOT THE STORED ONE -- a weight's RadTensor is built from - * `decl.shape` with the layout's stored dtype, as the fp8 lm_head's is (its launcher says - * so at length). So the row pitch is DERIVED here by the layout hook's own rule, and what - * guarantees the plane has it is the engine's layout-tag check, run before a byte moves. */ + /* A weight's RadTensor carries the declared shape with the stored dtype (as for the fp8 + * lm_head), so the row pitch is derived by the layout hook's rule; the engine's layout-tag + * check guarantees the plane matches. */ if (down->rank != 2 || down->shape[0] != lr || down->shape[1] != HN || up->rank != 2 || up->shape[0] != HN || up->shape[1] != lr) return R4D_NO(RAD_E_SHAPE); @@ -3898,15 +3507,12 @@ static int rad_hc_read_body(const RadArgs* a, const R4dSink& sk) { const float eps = (float)r4d_getf(a, "eps", 1e-6); const float wadd = (float)r4d_getf(a, "wadd", 0.0); - /* THE CHECK IS AGAINST WHAT THIS LAUNCH TOUCHES, NOT AGAINST THE SCRATCH HOOK. The hook walks - * the band's row counts to find the worst split -- right once at planning, and a large share - * of the issuing thread's time when repeated on every launch. `d`, the scales and `u` sit at - * offsets fixed by the band's M; the split-K partials behind them are checked where the - * split is known, in the tiled branch below. */ + /* Check what this launch touches, not the scratch hook's total: the hook walks the band, which + * is too slow per launch. `d`, the scales and `u` sit at offsets fixed by the band's M; the + * split-K partials are checked in the tiled branch, where the split is known. */ const long long Mband = r4d_geti_or(a, "M", 0); if (Mband <= 0) return R4D_NO(RAD_E_SHAPE); - /* `d`, the scales and `u` are all sized from the BAND, so a step wider than the band it was - * planned for does not run slowly -- it writes past three buffers. */ + /* `d`, the scales and `u` are sized from the band; a wider step would overrun them. */ if (rows > Mband) return R4D_NO(RAD_E_SHAPE); const long long ubytes = hc_u_rows(Mband, lr, hc) * HN * 2; const long long fixed = Mband * (lr * 2 + (long long)kHcMax * 4) + ubytes; @@ -3916,41 +3522,24 @@ static int rad_hc_read_body(const RadArgs* a, const R4dSink& sk) { unsigned short* ubuf = (unsigned short*)((unsigned char*)a->scratch + Mband * (lr * 2 + kHcMax * 4)); - /* THE COLUMN TILE IS CHOSEN FOR THE GRID AND NOT FOR THE CACHE. A workgroup owning 64 of the - * 320 columns is five workgroups at decode, on a part with sixty-four compute units -- which - * costs this op an order of magnitude over what its weight traffic says it should. Narrowing - * the tile until the grid covers the machine costs one extra pass over `h` per workgroup - * (20 KiB against the 1.3 MiB of weight the same workgroup reads at the widest tile), and at - * decode that is a megabyte and a half against six and a half of weight. - * - * IT ONLY EVER NARROWS: rows past kDecMinRows leave this path entirely for the tiled one - * below, so the widest tile is never the right answer here and `rows` in the condition is only - * ever a one-to-seven-row speculative window. */ + /* The column tile is chosen to fill the grid: 64 of 320 columns per workgroup would be five + * workgroups on 64 CUs. Narrowing costs one extra pass over `h` per workgroup (20 KiB against + * up to 1.3 MiB of weight). It only narrows; rows past kDecMinRows take the tiled path, so + * `rows` here is a one-to-seven-row speculative window. */ const bool can_tile = (n % kTKT) == 0 && (HN % 8) == 0 && (lr % 8) == 0 && (hrow % 8) == 0 && (((uintptr_t)h->data & 15u) == 0u) && (((uintptr_t)down->data & 15u) == 0u) && (((uintptr_t)up->data & 15u) == 0u); - /* THE ROW COUNT PICKS THE SHAPE OF THE OP, and it is not a tuning knob. The per-row kernels - * read both mixing matrices once A ROW: one row is the floor, four rows is a 4x re-read that - * an issue-bound kernel hides, and THIRTY-TWO -- eight sequences at depth 3 -- is 210 MB a - * connection that nothing hides. Left per-row, these two kernels alone account for roughly - * 45% of the whole cost of going from one sequence to eight. - * - * So above kDecMinRows the two products run TILED, and which tile is a function of the rows: - * 128 when there are enough to fill it (the prefill form), 32 or 64 below that - * with the down product split over K. Below kDecMinRows the per-row kernels still win -- - * there is not enough re-read to pay for the extra launch and the partials. */ + /* The row count picks the form. The per-row kernels read both mixing matrices once per row: + * four rows is hidden by an issue-bound kernel, but 32 (eight sequences at depth 3) is 210 MB + * per connection. So from kDecMinRows the products run tiled, 128 rows when there are enough + * (prefill), else 32 or 64 with a K-split down product. Below kDecMinRows the per-row kernels + * win. */ bool fused = false; const bool tiled = can_tile && rows >= kDecMinRows; - /* THE TILED PATH DECLINES TO DESCRIBE, and declining is a first-class answer: ABI v10 - * says a kernel that cannot describe a configuration is submitted individually, which is - * correct and merely slower. This path dispatches through three more launch helpers and takes - * a second per-stream counter, none of which the descriptor form covers. Declining keeps - * hc_read describable on the path decode takes without pretending about the one it does not. */ - if (tiled && sk.desc) return RAD_E_UNSUPPORTED; if (tiled) { const int rt = hc_down_rt(rows); - /* The inject gains are four more columns of the same GEMM when there are any. */ + /* The inject gains, if any, are hc more columns of the same GEMM. */ const bool fold = injw != nullptr && inj != nullptr; const long ncol = fold ? lr + hc : lr; const long nrt = (rows + rt - 1) / rt; @@ -3961,13 +3550,11 @@ static int rad_hc_read_body(const RadArgs* a, const R4dSink& sk) { return R4D_NO(RAD_E_SCRATCH); float* part = (ks > 1) ? (float*)((unsigned char*)a->scratch + fixed) : nullptr; - /* THE SECOND PREFILL FORM (hc_pf2_launch), at the 128-row tile and for the same bytes: - * the rule from kPf2MinRows rows wherever the shape is one it is built for -- hc 4, n a - * multiple of 256, at most kPf2MaxNT column n-tiles -- and the wide form's below that or - * at any other shape. Its weight planes live in `u`, which no fused form touches and which - * the scratch hook sizes for them at every band the rule reaches, so the room check below - * can only refuse the PIN, at a band under kPf2MinRows. The pin refuses a shape the form - * is not built for as well, so a test cannot pass on a form it did not ask for. */ + /* PF2 (hc_pf2_launch) at the 128-row tile, same bytes: used from kPf2MinRows rows when + * the shape fits (hc 4, n a multiple of 256, at most kPf2MaxNT column n-tiles), else the + * wide form. Its planes live in `u`, sized by the scratch hook at every band the rule + * reaches, so the room check can only refuse a pin below kPf2MinRows. A pin also refuses + * an unsupported shape, so a test cannot pass on a form it did not ask for. */ const long ntt = (ncol + 15) / 16; const bool pf2_shape = rt == kWideRT && hc == 4 && (n % kThreads) == 0 && ntt <= (long)kPf2MaxNT; @@ -3988,7 +3575,7 @@ static int rad_hc_read_body(const RadArgs* a, const R4dSink& sk) { return prc == RAD_OK ? RAD_OK : R4D_NO(prc); } - /* The per-stream norm scales, on a grid: one workgroup a (row, stream). */ + /* The per-s norm scales: one workgroup per (row, s). */ hipLaunchKernelGGL(hc_norm_scale_kernel, dim3((unsigned)hc, (unsigned)rows), dim3(kThreads), 0, (hipStream_t)s, (const unsigned short*)h->data, scale, @@ -4021,11 +3608,10 @@ static int rad_hc_read_body(const RadArgs* a, const R4dSink& sk) { if (hipGetLastError() != hipSuccess) return R4D_NO(RAD_E_DEVICE); } - /* THE UP PRODUCT AND THE MIX IN ONE LAUNCH, when the tile divides into (stream, channel) - * pairs and the finisher's counters fit. At the 32- and 64-row tiles that is - * hc_up_mix_tiled_kernel. The prefill tile takes hc_up_mix_wide_kernel instead, whose - * lanes hold a channel's sub-streams in registers: the pair form's two staging planes on - * top of a 128-row A tile would be 58 KiB of LDS and one workgroup a CU. */ + /* Up product and mix in one launch when the tile divides into (s, channel) pairs and + * the finisher's counters fit: hc_up_mix_tiled_kernel at 32- and 64-row tiles, + * hc_up_mix_wide_kernel at the prefill tile (registers instead of the 58 KiB of LDS staging + * planes). */ const int ipb = (hc > 0 && (kTNT % hc) == 0) ? kTNT / hc : 0; const long ntile = (long)(n / kUpTB) * ((rows + rt - 1) / rt); unsigned int* mctr = nullptr; @@ -4060,28 +3646,17 @@ static int rad_hc_read_body(const RadArgs* a, const R4dSink& sk) { if (hipGetLastError() != hipSuccess) return R4D_NO(RAD_E_DEVICE); } else { long long ta = kDownTAMax; - /* TWO PER WGP, WHICH IS ONE PER CU -- and this is the kernel want_wg()'s note anticipates. - * `multiProcessorCount` reports WGPs on RDNA and this part has 64 CUs in 32 of them, so a grid - * sized to want_wg() alone covers half the machine. At a depth-3 verify that is four rows at - * ta = 32, or 44 blocks, which a one-WGP target accepts and a one-CU target does not. Widening - * the target is worth ~1.3% of the step at that shape and is inside the noise at one row; - * below about 64 blocks the step falls off hard either way, which is the half-idle part - * showing up directly. + /* Target two workgroups per WGP, i.e. one per CU, since want_wg() returns WGPs (see its note). + * A one-WGP target would accept 44 blocks at a depth-3 verify (four rows, ta = 32); the one-CU + * target is worth ~1.3% of the step there. Below about 64 blocks the step degrades sharply. * - * THE LADDER HALVES ta, so it only ever lands on 44 / 84 / 164 blocks. Across every value of ta - * at ONE row -- where the median launch of a decode step lives, and where this rule already - * runs at its floor of 4 -- the floor IS the optimum, and it is a SHARP one: ta 4 (81 blocks) - * is 18.6 us, ta 5 (65 blocks) is +50% and ta 3 (108 blocks) is +76%, while ta 11, 12 and 24 - * (31, 28 and 15 blocks) all sit within 1.7 us of each other. Whatever ta 4 does right is NOT a - * smooth function of the block count -- 65 blocks is worse than both 81 and 31 -- so do not - * reason about this grid from CU occupancy or from a balance argument. Leave it at 4. - * - * BLOCK COUNT IS RULED OUT AS A DIRECTION HERE. With the prologue's traffic worth zero (above) - * and the dot already at 546 GB/s, this kernel has no lever left that is not a restructuring. */ + * The ladder halves ta, landing on 44 / 84 / 164 blocks. At one row ta's floor of 4 (81 blocks, + * 18.6 us) is a sharp optimum: ta 5 (65 blocks) is +50%, ta 3 (108) +76%, while ta 11-24 sit + * within 1.7 us of each other. Performance is not smooth in block count, so leave ta at 4. */ while (ta > 4 && ((lr + ta - 1) / ta) * rows < 2 * want_wg()) ta >>= 1; #define HC_READ_A(F8_) \ - R4D_EMIT(sk, hc_read_a_kernel, dim3((unsigned)((lr + ta - 1) / ta) + 1u, (unsigned)rows), \ + R4D_EMIT(s, hc_read_a_kernel, dim3((unsigned)((lr + ta - 1) / ta) + 1u, (unsigned)rows), \ dim3(kThreads), (unsigned)(HN * sizeof(unsigned short)), \ (const unsigned short*)h->data, (const float*)w->data, (const void*)down->data, \ (long)dld, injw ? (const unsigned short*)injw->data : nullptr, dbuf, \ @@ -4090,18 +3665,15 @@ static int rad_hc_read_body(const RadArgs* a, const R4dSink& sk) { emit_rc = f8 ? HC_READ_A(true) : HC_READ_A(false); #undef HC_READ_A if (emit_rc != RAD_OK) return R4D_NO(RAD_E_DEVICE); - if (!sk.desc && hipGetLastError() != hipSuccess) return R4D_NO(RAD_E_DEVICE); + if (hipGetLastError() != hipSuccess) return R4D_NO(RAD_E_DEVICE); - /* THE UP PRODUCT AND THE MIX IN ONE LAUNCH whenever a channel's hc rows divide a workgroup's - * 64 and the finisher's counters fit -- which at this model's hc of 4 is every row count this - * path takes. A counter makes the launch indescribable, as on the tiled path, so a describe - * that would need one declines. */ + /* Up product and mix in one launch whenever hc divides a workgroup's 64 rows and the + * finisher's counters fit (always, at this model's hc 4). */ const long long ipb = (hc > 0 && (kUpRows % hc) == 0) ? kUpRows / hc : 0; const long long slots = ((rows + hc_up_rg(rows, lr) - 1) / hc_up_rg(rows, lr)) * (n / kUpTB); unsigned int* mctr = nullptr; fused = ipb > 0 && (kUpTB % ipb) == 0 && (n % ipb) == 0 && slots <= (long long)kMaxMixCtr; if (fused && q) { - if (sk.desc) return RAD_E_UNSUPPORTED; mctr = hc_mix_ctr(s); fused = (mctr != nullptr); } @@ -4113,16 +3685,16 @@ static int rad_hc_read_body(const RadArgs* a, const R4dSink& sk) { q ? (float*)qs->data : nullptr, rq ? (unsigned char*)rq->data : nullptr, rq ? (float*)rqs->data : nullptr, mctr, rows, n, (int)hc, lr, - hrow, xrow, qrow, srow, rqrow, rsrow, wadd, sk); + hrow, xrow, qrow, srow, rqrow, rsrow, wadd, s); else - emit_rc = hc_up_launch(up, (long)uld, f8, dbuf, ubuf, rows, HN, lr, sk); + emit_rc = hc_up_launch(up, (long)uld, f8, dbuf, ubuf, rows, HN, lr, s); if (emit_rc != RAD_OK) return R4D_NO(RAD_E_DEVICE); - if (!sk.desc && hipGetLastError() != hipSuccess) return R4D_NO(RAD_E_DEVICE); + if (hipGetLastError() != hipSuccess) return R4D_NO(RAD_E_DEVICE); } if (!fused) { #define HC_MIX_EMIT(I8_) \ - R4D_EMIT(sk, hc_mix_kernel, \ + R4D_EMIT(s, hc_mix_kernel, \ dim3((unsigned)(n / kUpTB), (unsigned)rows), \ dim3(kThreads), 0, \ (const unsigned short*)h->data, (const float*)w->data, ubuf, scale, \ @@ -4137,8 +3709,7 @@ static int rad_hc_read_body(const RadArgs* a, const R4dSink& sk) { } if (emit_rc != RAD_OK) return emit_rc; - return sk.desc ? RAD_OK : (int)hipGetLastError(); + return (int)hipGetLastError(); } -R4D_ENTRY(r4d_rad_hc_read, rad_hc_read_body) extern "C" void r4d_hc_read_pin_prefill(int form) { g_hc_prefill_form = form; } diff --git a/libr4d/r4d_hc_fp8.h b/libr4d/r4d_hc_fp8.h index 2242724b..199200b5 100644 --- a/libr4d/r4d_hc_fp8.h +++ b/libr4d/r4d_hc_fp8.h @@ -1,25 +1,24 @@ -// r4d_hc_fp8.h -- the STORED ROW GEOMETRY of hc_read's two mixing matrices at E4M3, and nothing -// else. Pure C++: no HIP, no r4d.h, so the host layout hook (r4d_fp8_layout.cpp), the kernels -// (r4d_hc_bf16.hip) and the selftest derive a row from the same lines. +// r4d_hc_fp8.h -- stored row geometry of hc_read's two mixing matrices at E4M3. Pure C++ (no HIP, +// no r4d.h), so the host layout hook (r4d_fp8_layout.cpp), the kernels (r4d_hc_bf16.hip) and the +// selftest share one definition. // -// A stored row is [K E4M3 codes][K/G f32 scales][pad to 16 bytes], one row after another, for the -// reason r4d_rad_layout_fp8_logits gives: the scales ride in the row that uses them, so a row is -// self-contained and a kernel finds its scales at a fixed offset from its codes. +// A stored row is [K E4M3 codes][K/G f32 scales][pad to 16 bytes], rows back to back. As in +// r4d_rad_layout_fp8_logits, the scales ride in their row, so a kernel finds them at a fixed +// offset from its codes. // -// THE GROUP IS A PROPERTY OF THE KERNEL THAT READS THE ROW, not a tuning choice, and the two -// matrices get different ones for that reason: +// The group size is set by the kernel that reads the row, not by tuning: // // mix_down [lowrank rows, K = hc*n] G = 128. A wave walks the row in 256-element steps with -// eight codes a lane, so every lane's eight sit inside one group and a step needs two +// eight codes a lane, so each lane's eight sit in one group and a step needs two // scales a wave. // mix_up [hc*n rows, K = lowrank] G = K/4. Four threads share a row, each taking one -// contiguous quarter of it -- 80 codes at lowrank 320 -- so a thread's quarter IS its -// group and it multiplies by one scale after its whole partial sum. lowrank must be a -// multiple of 64 for the quarter to be sixteen-code loads. +// contiguous quarter (80 codes at lowrank 320), so a thread's quarter is its group and +// it applies one scale after its partial sum. lowrank must be a multiple of 64 so a +// quarter splits into sixteen-code loads. // -// Both are FINER than the 128 x 128 blocks the GEMMs use, which is deliberate: these rows are -// read against a normalised stream whose every element matters, and a per-row group costs one f32 -// per G codes -- 3.1% of mix_down's bytes and 5% of mix_up's. +// Both are finer than the GEMMs' 128 x 128 blocks on purpose: these rows meet a normalised stream +// where every element matters, and a per-row group costs one f32 per G codes (3.1% of mix_down's +// bytes, 5% of mix_up's). #pragma once #include @@ -27,17 +26,17 @@ namespace r4d_hc8 { constexpr int64_t kDownGroup = 128; -// constexpr and not merely inline, which is what makes them callable from device code too: the -// compiler treats a constexpr function as both host and device. +// constexpr rather than inline so device code can call them: a constexpr function is implicitly +// host and device. constexpr int64_t down_group(int64_t /*K*/) { return kDownGroup; } constexpr int64_t up_group(int64_t K) { return K / 4; } -// Whether a K can be stored with the given group at all. The kernels' loads are what decide it: -// sixteen codes at a time, a group a whole number of those. +// Whether K can be stored with group G: the kernels load sixteen codes at a time, and a group must +// be a whole number of those. constexpr bool group_ok(int64_t K, int64_t G) { return G > 0 && G % 16 == 0 && K % G == 0; } -// The BYTES one stored row occupies, and where its pad starts. The row starts 16-byte aligned so -// every code load is a uint4 or a uint2 at a 16- or 8-byte boundary. +// Bytes one stored row occupies, and where its pad starts. Rows start 16-byte aligned so every +// code load is a uint4 or uint2 at a 16- or 8-byte boundary. constexpr int64_t row_used(int64_t K, int64_t G) { return K + 4 * (K / G); } constexpr int64_t row_bytes(int64_t K, int64_t G) { return (row_used(K, G) + 15) & ~(int64_t)15; } diff --git a/libr4d/r4d_launch.h b/libr4d/r4d_launch.h index 3d3cd321..2878c7eb 100644 --- a/libr4d/r4d_launch.h +++ b/libr4d/r4d_launch.h @@ -1,15 +1,21 @@ -/* r4d_launch.h -- the one spelling of a kernel launch in the libr4d units tests/r4d_emu runs on the - * host: the windowed paged attention, pair_argmax, the sandwich-norm joins and expert_scale. +/* r4d_launch.h -- the kernel-launch spelling for the libr4d units tests/r4d_emu runs on the host: + * the windowed paged attention, pair_argmax, the sandwich-norm joins, expert_scale and the QSA + * block selection. * - * A template kernel's name carries commas, so it goes through R4D_KNAME the way HIP_KERNEL_NAME - * exists for hipLaunchKernelGGL. R4D_KLAUNCH is overridable so the same sources can be driven by a - * host-side SIMT emulator in a test -- the kernels are ordinary C++ once the HIP names are - * supplied. A build never defines it, and gets the triple-chevron launch, which the engine answers - * through hipLaunchKernel on its own queues (docs/PLUGIN.md §5). */ + * R4D_KNAME wraps a template kernel name containing commas, as HIP_KERNEL_NAME does for + * hipLaunchKernelGGL. A test may define R4D_KLAUNCH to drive the same sources through a host SIMT + * emulator; a build does not, and gets the triple-chevron launch, which the engine services via + * hipLaunchKernel on its own queues (docs/PLUGIN.md §5). + * + * R4D_DYN_LDS declares a kernel's dynamic LDS, sized by the launch: `extern __shared__` in a + * build. The emulator has no such storage class and defines its own. */ #ifndef R4D_LAUNCH_H #define R4D_LAUNCH_H #define R4D_KNAME(...) __VA_ARGS__ #ifndef R4D_KLAUNCH #define R4D_KLAUNCH(kernel, grid, block, stream, ...) kernel<<>>(__VA_ARGS__) #endif +#ifndef R4D_DYN_LDS +#define R4D_DYN_LDS(type, name) extern __shared__ type name[] +#endif #endif diff --git a/libr4d/r4d_layout.cpp b/libr4d/r4d_layout.cpp index 30e0cebc..a0321290 100644 --- a/libr4d/r4d_layout.cpp +++ b/libr4d/r4d_layout.cpp @@ -1,38 +1,36 @@ -/* r4d_layout.cpp -- what libr4d's integer and MXFP4 GEMMs store for a weight, and the relayouts +/* r4d_layout.cpp -- the stored form of libr4d's integer and MXFP4 GEMM weights, and the relayouts * that produce it from the weight's canonical planes (spec.md §4.3). Pure host C++: nothing here - * includes r4d.h or , so it compiles and can be exercised on a box with no - * ROCm, which is where a packing bug is cheapest to find. + * includes r4d.h or , so packing can be tested without ROCm. * - * A container holds each weight's encoding -- codes, scales and zero points, canonical and - * row-major -- and the kernel that reads it rearranges it at load. That is what lets this file - * change a fragment order without anyone converting a model again; the numbers were chosen by a - * quantiser (libquant), and nothing here chooses one. + * A container holds each weight's encoding (codes, scales and zero points, canonical and + * row-major), and the kernel that reads it rearranges it at load, so a fragment order can change + * without reconverting models. The numbers are chosen by a quantiser (libquant), never here. * - * THE FRAGMENT ORDER IS THE WHOLE POINT. gfx1201's wave32 WMMA fragment layout is + * Fragment order. gfx1201's wave32 WMMA fragment layout is * * idx = lane % 16 , k = 8*(e>>2) + 4*(lane>>4) + (e&3) * - * so a B fragment maps lane l onto output row l&15: in canonical order the sixteen lanes of a - * half-wave read sixteen rows K/2 bytes apart, which is a fully strided read on the operand that - * dominates traffic. Rearranged, a wave's weight load for four k steps is one 512-byte - * global_load_b128 with a constant stride and no address arithmetic in the loop. + * so a B fragment maps lane l onto output row l&15. In canonical order the sixteen lanes of a + * half-wave read sixteen rows K/2 bytes apart, a fully strided read on the operand that dominates + * traffic. Rearranged, a wave's weight load for four k steps is one 512-byte global_load_b128 with + * a constant stride and no address arithmetic in the loop. * - * Every element->slot map below is transcribed from the kernel that reads it; the comment at the - * top of each libr4d GEMM states it in closed form. + * Every element->slot map below is transcribed from the kernel that reads it; each libr4d GEMM's + * header states it in closed form. */ #include "r4d_plugin.h" #include "r4d_enc.h" #include +#include #include #include /* ------------------------------------------------------------------ half-precision * - * Written out rather than pulled from a header because this file must build without ROCm and - * without any float16 extension: __fp16 is not portable and _Float16 is not guaranteed on every - * host compiler the converter might be built with. */ + * Written out so the file builds without ROCm or a float16 extension: __fp16 is not portable and + * _Float16 is not available on every host compiler. */ static uint16_t f32_to_f16(float f) { uint32_t x; @@ -84,12 +82,10 @@ static float f16_to_f32(uint16_t h) { return f; } -/* THE SCALE DWORD. libr4d packs the group's two quantiser parameters into one 32-bit word: the f16 - * scale in the low half and the f16 of -(1024 + zero) in the high half, ready to be broadcast into - * a v_pk_add_f16. The kernel builds 1024 + code and adds that constant, which is what makes the - * subtraction of an INTEGER zero point exact. A symmetric 4-bit grid is expressed in the same - * encoding with zero == 8, which is why one packed weight can feed both the f16 and the int8 - * kernel byte for byte. */ +/* The scale dword: a group's f16 scale in the low half and the f16 of -(1024 + zero) in the high + * half, broadcast into a v_pk_add_f16. The kernel builds 1024 + code and adds that constant, which + * subtracts an integer zero point exactly. A symmetric 4-bit grid uses zero == 8, so one packed + * weight feeds both the f16 and the int8 kernel. */ static uint32_t scale_zero_dword(float scale, int zero) { const uint32_t lo = f32_to_f16(scale); const uint32_t hi = f32_to_f16(-(1024.0f + (float)zero)); @@ -120,20 +116,18 @@ static void fill(RadLayout* o, const char* tag, uint32_t dtype, long long r0, lo o->rank = 2; o->shape[0] = r0; o->shape[1] = r1; - /* Every one of these streams is read with 128-bit loads; 256 is a cacheline on the - * architectures in scope, and the .rad plane alignment. */ + /* Every stream is read with 128-bit loads; 256 bytes is a cacheline on the target + * architectures and the .rad plane alignment. */ o->align = 256; o->bytes = bytes; } -/* THE ASYMMETRIC 4-BIT GRID IS A DIFFERENT WEIGHT, and `dtype` is what says so. `w4a8_asym`'s - * kernels read the nibble UNSIGNED and subtract a per-group integer zero from the scale dword's - * high half; the symmetric grid stores a two's-complement nibble with the zero pinned at 8. The - * packing, the extents and the byte counts are identical, so a plane written for one and read by - * the other is accepted everywhere and decodes to the wrong numbers -- a symmetric plane read - * unsigned is eight levels off at every code. The test is the kernels' own (r4d_gemm_args.h's - * is_asym), so the encoding the layout hook accepts -- i4 with no zero, or u4 with one -- is the - * grid the launch selects, and the other is refused at declare. */ +/* The asymmetric 4-bit grid is a different weight, and `dtype` says which. `w4a8_asym` kernels + * read the nibble unsigned and subtract a per-group integer zero from the scale dword's high half; + * the symmetric grid stores a two's-complement nibble with the zero fixed at 8. Packing, extents + * and byte counts are identical, so a plane read as the other grid decodes eight levels off. This + * is the kernels' own test (r4d_gemm_args.h is_asym), so the layout hook accepts only the matching + * encoding (i4 without a zero, u4 with one) and refuses the other at declare. */ static bool w4_asym(const RadParam* p, int n_p) { const char* d = r4d_pgets(p, n_p, "dtype"); return d && std::strstr(d, "_asym") != nullptr; @@ -141,80 +135,66 @@ static bool w4_asym(const RadParam* p, int n_p) { /* ================================================================== moe w4 * - * THE GROUPED MoE GEMM'S 4-BIT EXPERT WEIGHT, and it is a different plane from the dense w4 above - * for one structural reason: the dense kernels read a WMMA fragment straight out of a coalesced - * global load, so their weight is stored PERMUTED into fragment order; the grouped kernel stages - * its weight through LDS -- it has to, because eight M tiles share one N tile of it -- so a - * permutation would buy nothing and would have to be undone on the way in. + * The grouped MoE GEMM's 4-bit expert weight. Unlike the dense w4 it is not permuted into fragment + * order: the grouped kernel stages its weight through LDS (eight M tiles share one N tile), so a + * permutation would only have to be undone. * - * WHAT THE FORMAT IS + * weight [N][K/2] bytes, row-major, two's complement codes -8..7: an ordinary symmetric int4 + * grid, as GPTQ writes. + * scale [N][K/group] bf16, one per row per 128 of K. w ~= code * scale. * - * weight [N][K/2] bytes, row-major, TWO'S COMPLEMENT codes -8..7 -- an ordinary symmetric - * int4 grid, the one GPTQ and every other 4-bit method is written against. - * scale [N][K/group] bf16, one per row per group of 128 along K. w ~= code * scale. + * Decode: V_PERM_B32 permutes the bytes of an eight-byte source, so one table holds eight entries + * and a two's complement nibble needs sixteen. Two perms index a positive and a negative table + * with the low three bits, and a third selects on bit 3 by adding 4 to a selector byte (which + * cannot carry): all sixteen levels for five more VALU per eight weights than a fifteen-level + * sign-magnitude grid. See r4d_moe.hip w4_e4m3. * - * THE DECODE IS TWO V_PERM_B32 AND A THIRD THAT CHOOSES BETWEEN THEM. A perm is a byte permute of - * an EIGHT-byte source, so one table holds eight entries and a two's complement nibble needs - * sixteen. Indexing both a positive and a negative table with the low three bits and selecting on - * bit 3 -- by ADDING 4 to a selector byte, which cannot carry -- gets all sixteen levels for five - * more VALU per eight weights than a fifteen-level sign-magnitude grid would cost. r4d_moe.hip's - * w4_e4m3 is the five lines. + * The integers -8..7 are exact in E4M3 (three mantissa bits reach 16), so expanding a code to an + * E4M3 byte is lossless and the weight runs on the existing f32_16x16x16_fp8_fp8 inner loop; only + * the staging differs. * - * THE INTEGERS -8..7 ARE ALL EXACT IN E4M3 (three mantissa bits reach 16), so expanding a code to an - * E4M3 byte is lossless and the product the WMMA computes is code * activation with no rounding - * the fp8 path did not already have. That is the whole reason this weight can ride the existing - * f32_16x16x16_fp8_fp8 inner loop untouched: only the STAGING changes. + * Nibble order: byte b of a packed dword holds element b in its low nibble and element b+4 in its + * high nibble, so the two masks yield elements 0..3 and 4..7 already in order, as in the dense + * w4a8 kernel. * - * THE NIBBLE ORDER IS THE ONE THE EXPANSION WANTS. Byte b of a packed dword holds element b in its - * low nibble and element b+4 in its high nibble, so the two masks above produce elements 0..3 and - * 4..7 already in order and nothing has to be interleaved afterwards. It is the same argument the - * dense w4a8 kernel's header makes for the same pair of masks. - * - * IT IS NOT SHARDABLE AND THE ARCHITECTURE SAYS SO. A packed row is K/2 bytes and a column shard - * would cut a byte in half; an expert under expert parallelism is whole on one rank, which is the - * only configuration that declares this format. rad_block_moe_fp8.h refuses a width-sharded - * declaration by name rather than leaving it to the loader to discover. + * Not shardable: a packed row is K/2 bytes and a column shard could cut a byte in half. Under + * expert parallelism an expert is whole on one rank, the only configuration that declares this + * format; rad_block_moe_fp8.h refuses a width-sharded declaration. */ -/* THE ROTATED FORM IS THE SAME BYTES WITH DIFFERENT NUMBERS IN THEM, and that is exactly why the - * encoding says so. `dtype=w4a8h` serves `i4*bf16[1x128]/fwht128`: every group of K was multiplied - * by a `group`-wide Hadamard before it was quantised. Nothing in the packing, the extents or the - * byte count would say so, and a weight quantised one way and served the other reads as noise -- - * so the layout hook accepts exactly the encoding the dtype names, and refuses the other at - * declare. +/* `dtype=w4a8h` serves `i4*bf16[1x128]/fwht128`: the same bytes, but every group of K was + * multiplied by a `group`-wide Hadamard before quantisation. Nothing in packing, extents or byte + * count shows this, and a weight served the other way reads as noise, so the layout hook accepts + * only the encoding the dtype names. * - * THE KERNEL DOES NOT BRANCH ON IT. = group * , and the residual factor is folded - * into the stored weight scale by the quantiser (docs/MOE-W4.md), so the GEMM multiplies codes by - * scales exactly as it does for the unrotated grid. What has to agree is the ACTIVATION: the - * routed experts' input must be quantised by the rotated quantiser at the same width, which is - * what had_quant_act_fp8 is for. That pairing is not checkable from here -- it is a property of the - * graph, and the arch block that declares one declares the other. */ -/* THE CODEBOOK FORM IS THE ROTATED FORM WITH OTHER NUMBERS FOR THE SAME CODES. `dtype=w4nla8h` - * serves `u4*bf16[1x128]/fwht128` whose codes index a sixteen-entry `table` plane -- libquant's - * `table=w4nl` -- and the kernel decodes that table and no other (r4d_args.h). An encoding cannot - * say what its table holds, so the codes view selects the table plane beside the codes and the - * relayout compares it with the kernel's, value for value, before it serves a byte: a container - * quantised against another table is refused at load rather than served as other numbers. */ + * The kernel does not branch on it: = group * , and the quantiser folds the + * residual factor into the stored scale (docs/MOE-W4.md). What must agree is the activation, which + * had_quant_act_fp8 quantises with the same rotation width. That pairing is a property of the + * graph and is not checked here; the arch block that declares one declares the other. */ +/* `dtype=w4nla8h` serves `u4*bf16[1x128]/fwht128` whose codes index a sixteen-entry `table` plane + * (libquant `table=w4nl`), and the kernel decodes only its own table (r4d_args.h). The codes view + * selects the table plane and the relayout compares it with the kernel's value for value, so a + * container quantised against another table is refused at load. */ static int moe_w4_nl(const RadParam* p, int n_p) { const char* d = r4d_pgets(p, n_p, "dtype"); return d && (std::strcmp(d, "w4nla8h") == 0 || std::strcmp(d, "w4nl64a8h") == 0 || std::strcmp(d, "w4nl32a8h") == 0 || std::strcmp(d, "w5nl64a8h") == 0); } -/* `w5nl64a8h` IS w4nl64a8h AT FIVE BITS: `u5*fp8_e4m3[1x64]*f32[*x*]/fwht128` whose codes index - * libquant's 32-entry `table=w5nl`. Its codes view relays each row into R4D_DT_MOEW5 -- the low - * four bits of every code as w4nla8h's nibble plane, then the high bit of every code, the sign, - * a dword a 32 elements (moew5_row says in which order) -- and compares the table with - * kW5nlTable as w4nla8h's is; its scale view is w4nl64a8h's. */ +/* `w5nl64a8h` is w4nl64a8h at five bits: `u5*fp8_e4m3[1x64]*f32[*x*]/fwht128`, codes indexing + * libquant's 32-entry `table=w5nl`. Its codes view relays each row into R4D_DT_MOEW5 (the low four + * bits of every code as w4nla8h's nibble plane, then each code's high bit, the sign, one dword per + * 32 elements in moew5_row's order) and checks the table against kW5nlTable. Its scale view is + * w4nl64a8h's. */ static bool moe_w5(const RadParam* p, int n_p) { const char* d = r4d_pgets(p, n_p, "dtype"); return d && std::strcmp(d, "w5nl64a8h") == 0; } -/* `w4nl64a8h` IS THE CODEBOOK FORM WITH ITS SCALES A 64 OF K, as E4M3 under the fixed - * kW4G64Scale -- `u4*fp8_e4m3[1x64]*f32[*x*]/fwht128` with the table, the f32 second level being - * that constant, stated once a weight. The codes are stored as w4nla8h's; the scale view selects - * the E4M3 plane and the second level, and its relayout compares the second with the kernel's - * constant, as the codes view does the table, and stores the E4M3 plane as it is. */ -/* And `w4nl32a8h` the same at one a (row, 32 of K). The value is the scale groups a 128 of K the - * dtype has beside its bf16 forms' one: 2, 4, or 0 for neither. */ +/* `w4nl64a8h` is the codebook form with one E4M3 scale per (row, 64 of K) under a fixed f32 + * second level, kW4G64Scale, stored once per weight (`u4*fp8_e4m3[1x64]*f32[*x*]/fwht128` with the + * table). Codes are stored as w4nla8h's. The scale view selects the E4M3 plane and the second + * level; its relayout checks the second level against the kernel's constant and stores the E4M3 + * plane unchanged. `w4nl32a8h` is the same with one scale per (row, 32 of K). + * + * Returns the scale groups per 128 of K (the bf16 forms have one): 2, 4, or 0 for neither. */ static int moe_w4_g64(const RadParam* p, int n_p) { const char* d = r4d_pgets(p, n_p, "dtype"); if (!d) return 0; @@ -229,10 +209,9 @@ static int moe_w4_rot(const RadParam* p, int n_p) { /* ================================================================== moe_gemm_q's two classes * * `moe_gemm_q` takes its experts as two tables by parity: operands 2 and 3 hold the even experts - * at [N, K], operands 6 and 7 the odd ones at [N_odd, K_odd] (r4d_rows.cpp's schema says why). A - * hook asked about 6 or 7 answers exactly as it would for 2 or 3 at the odd geometry, so every - * hook below is the plain one behind this view, and the two classes cannot come to disagree about - * a format they share. */ + * at [N, K], operands 6 and 7 the odd ones at [N_odd, K_odd] (see the schema in r4d_rows.cpp). A + * hook asked about 6 or 7 answers as for 2 or 3 at the odd geometry, so both classes share one + * format definition. */ namespace { struct MoeView { RadParam p[32]; @@ -258,8 +237,7 @@ int moe_view(const RadParam* p, int n_p, int operand, MoeView* v) { } /* `moe_gemm_q_mod4`'s four classes: operands 6/7, 8/9 and 10/11 are classes 1, 2 and 3 at - * N_1/K_1, N_2/K_2 and N_3/K_3, answered as 2/3 at that geometry -- the same view, one class - * further along. */ + * N_1/K_1, N_2/K_2 and N_3/K_3, answered as 2/3 at that geometry. */ int moe_view_mod4(const RadParam* p, int n_p, int operand, MoeView* v) { if (n_p < 0 || n_p > 32 || (n_p > 0 && !p)) return RAD_E_INVAL; v->n = n_p; @@ -283,10 +261,9 @@ int moe_view_mod4(const RadParam* p, int n_p, int operand, MoeView* v) { /* ================================================================== the hooks * - * The codes and scales arrive chosen, by a quantiser, and what is left here is the arrangement the - * kernel reads -- fragment order, the (scale, zero) dword, a tile-major scale plane, a nibble - * order -- which moves bits and chooses none. Each refuses, with RAD_E_DTYPE, an encoding its - * kernel does not read. */ + * Codes and scales arrive chosen by a quantiser; the hooks only arrange them as the kernel reads + * them (fragment order, the (scale, zero) dword, a tile-major scale plane, a nibble order). Each + * refuses an encoding its kernel does not read with RAD_E_DTYPE. */ namespace { using r4d_enc::selects; @@ -295,7 +272,7 @@ using r4d_enc::dims; /* A selected plane's dense bytes. */ const uint8_t* pdata(const RadTensor& t) { return (const uint8_t*)t.data; } -/* The f16 scale of a canonical plane, as f32 -- the value scale_zero_dword re-narrows exactly. */ +/* The f16 scale of a canonical plane as f32; scale_zero_dword narrows it back exactly. */ float f16_at(const RadTensor& t, long long i) { return f16_to_f32(((const uint16_t*)t.data)[i]); } /* An integer zero point from a u4 or u8 plane. */ @@ -327,9 +304,9 @@ void sz_write(const WGeom& g, const RadTensor* pl, int zfixed, uint32_t* sz) { } } -/* Every zero point a code of `bits` bits: what an asymmetric grid's zero is, and what the int8 - * prefill kernel reads back out of the scale dword (r4d_gemm_wpa8i8_tiled.hip takes five bits of it, - * where the f16 kernel takes the whole value -- a larger zero would make the two disagree). */ +/* Whether every zero point fits in `bits` bits. The int8 prefill kernel (r4d_gemm_wpa8i8_tiled.hip) + * reads five bits of the zero out of the scale dword where the f16 kernel reads the whole value, + * so a larger zero would make the two disagree. */ bool sz_zeros_fit(const WGeom& g, const RadTensor& zp, int bits) { const long long nz = g.N * (g.K / g.group); for (long long i = 0; i < nz; ++i) { @@ -354,9 +331,9 @@ void sz_read(const WGeom& g, const uint32_t* sz, const RadTensor* pl, bool asym) } } -/* A ROTATED asymmetric grid (ParoQuant): codes of `codes` dtype, an f16 scale and a u8 zero point a - * group, then a `givens` transform and its tables -- the same bytes as the unrotated grid, the - * rotation being the activation's. */ +/* A rotated asymmetric grid (ParoQuant): codes of dtype `codes`, an f16 scale and a zero point + * per group, optionally with a `givens` transform and its tables. The bytes are the unrotated + * grid's; the rotation is applied to the activation. */ static bool paro_asym_enc(const RadEncoding* e, uint32_t codes, long long group) { if (!e || !rad_enc_is(e, "affine") || e->n_planes < 3) return false; const bool giv = std::strncmp(e->transform, "givens", RAD_ENC_STR) == 0; @@ -428,10 +405,11 @@ extern "C" int r4d_rad_relayout_w4(const RadParam* p, int n_p, int operand, cons if (dst_bytes != L.bytes) return RAD_E_SHAPE; std::memset(dst, 0, (size_t)dst_bytes); if (operand == Q_BSCALE) { - /* a ROTATED (ParoQuant) grid's zero is a 4-bit code */ - if (w4_asym(p, n_p) && std::strncmp(enc->transform, "givens", RAD_ENC_STR) == 0 && + const bool asym = w4_asym(p, n_p); + /* A rotated (ParoQuant) grid's zero must fit a 4-bit code. */ + if (asym && std::strncmp(enc->transform, "givens", RAD_ENC_STR) == 0 && !sz_zeros_fit(g, pl[1], 4)) return RAD_E_FORMAT; - sz_write(g, pl, w4_asym(p, n_p) ? -1 : 8, (uint32_t*)dst); + sz_write(g, pl, asym ? -1 : 8, (uint32_t*)dst); return RAD_OK; } uint32_t* wq = (uint32_t*)dst; @@ -473,13 +451,13 @@ extern "C" int r4d_rad_unrelayout_w4(const RadParam* p, int n_p, int operand, return RAD_OK; } -/* ---- w5: ParoQuant's int5, asymmetric: u5 codes, an f16 scale and a u8 zero point (0..31) a 128 of K. - * The blob is w4's fragment order for the low four bits of every code (offset binary, no sign flip) - * followed by a plane of 32-bit words holding the fifth bits, one a (n-tile, 64 of K, lane): byte s - * is k step s of the block and bit e the fragment element e -- the element whose nibble is - * 2e (e < 4) or 2(e-4)+1 in dword s of that lane's 16 bytes (r4d_gemm_w5a16_nt_m64.hip). The scale - * operand is w4u's (scale, zero) dword plane. A ROTATED weight (a `givens` transform and its - * tables beside the first three planes) is the same bytes: the rotation is the activation's. */ +/* ---- w5: ParoQuant's asymmetric int5: u5 codes, an f16 scale and a u8 zero point (0..31) per + * 128 of K. The blob is w4's fragment order for the low four bits of every code (offset binary, no + * sign flip), then 32-bit words of fifth bits, one per (n-tile, 64 of K, lane): byte s is k step s + * of the block and bit e is fragment element e, whose nibble is 2e (e < 4) or 2(e-4)+1 in dword s + * of that lane's 16 bytes (r4d_gemm_w5a16_nt_m64.hip). The scale operand is w4u's (scale, zero) + * dword plane. A rotated weight (a `givens` transform and its tables beside the first three + * planes) has the same bytes; the rotation is the activation's. */ namespace { bool w5_enc(const RadEncoding* e, long long group) { return paro_asym_enc(e, RAD_U5, group); } @@ -571,10 +549,10 @@ extern "C" int r4d_rad_unrelayout_w5(const RadParam* p, int n_p, int operand, co return RAD_OK; } -/* ---- givens pairs: ParoQuant's rotation pairs (i32 [P*S, K]), stored as they are but CHECKED. - * The rotate kernels index a group's 128 LDS slots with them unchecked, so a stage that is not a - * pairing of its own group -- an index outside the group, or one column twice -- is refused here, - * at load, rather than read out of bounds. Operand 1 of the givens rows; the rest is as stored. */ +/* ---- givens pairs: ParoQuant's rotation pairs (i32 [P*S, K]), stored unchanged but checked. The + * rotate kernels index a group's 128 LDS slots with them unchecked, so a stage that is not a + * pairing within its own group (an index outside the group, or a column twice) is refused at load. + * Operand 1 of the givens rows; the other operands are stored as they are. */ namespace { constexpr int GV_PAIRS_OPERAND = 1; constexpr long long GV_GROUP = 128; @@ -636,14 +614,14 @@ extern "C" int r4d_rad_unrelayout_givens_pairs(const RadParam* p, int n_p, int o return RAD_OK; } -/* ---- givens_dense: ParoQuant's rotation as one dense matrix a (part, group). +/* ---- givens_dense: ParoQuant's rotation as one dense matrix per (part, group). * - * The dense kernel (r4d_givens_dense.hip) applies a part's Givens stages over each group of 128 columns as - * T (x / D), T being their composition. rad-convert composes T and stores it as the "givens" encoding's - * "t.dense" table, f16 [P * K/128, 128 * 128], row p * (K/128) + g element j * 128 + i the output j for the - * unit input e_i (abi/rad_encoding.h) -- which is the order the kernel stages a (part, group), 32 KiB, whole. - * So the layout is the table as stored: a relayout that moves bytes and derives none (abi/rad_abi.h). - * Operand 1 of givens_dense_quant; everything else stays as stored. */ + * The dense kernel (r4d_givens_dense.hip) applies a part's Givens stages over each group of 128 + * columns as T (x / D), T being their composition. rad-convert composes T and stores it as the + * "givens" encoding's "t.dense" table, f16 [P * K/128, 128 * 128]: in row p * (K/128) + g, element + * j * 128 + i is output j for unit input e_i (abi/rad_encoding.h). The kernel stages a (part, + * group), 32 KiB, whole in that order, so the layout is the table as stored. Operand 1 of + * givens_dense_quant; everything else stays as stored. */ namespace { constexpr int GD_OPERAND = 1; constexpr long long GD_GROUP = 128; @@ -676,14 +654,14 @@ extern "C" int r4d_rad_relayout_gdense(const RadParam* p, int n_p, int operand, RadLayout L; int rc = r4d_rad_layout_gdense(p, n_p, operand, enc, sel, pl, n, &L); if (rc != RAD_OK) return rc; - if (dst_bytes != L.bytes) return RAD_E_SHAPE; + if (dst_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE; std::memcpy(dst, pdata(pl[0]), (size_t)L.bytes); return RAD_OK; } -/* ---- w8: i8 codes, symmetric about zero, an f16 scale a group. The f16 kernel (a16) reads the - * code offset binary with zero 128 in the shared dword; the int8 kernel (a8) reads it signed with a - * bare f16 scale plane. */ +/* ---- w8: i8 codes, symmetric about zero, an f16 scale per group. The f16 kernel (a16) reads the + * code as offset binary with zero 128 in the shared dword; the int8 kernel (a8) reads it signed + * with a bare f16 scale plane. */ namespace { int w8_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel, const RadTensor* pl, int n, RadLayout* out, WGeom* gout, int a16) { @@ -766,7 +744,7 @@ extern "C" int r4d_rad_relayout_w8a8(const RadParam* p, int n_p, int operand, return w8_relayout(p, n_p, operand, enc, sel, pl, n, dst, dst_bytes, 0); } -/* ---- w2a8: u2 codes, asymmetric, an f16 scale and an integer zero a group, both streams +/* ---- w2a8: u2 codes, asymmetric, an f16 scale and an integer zero per group, both streams * tile-major. */ namespace { int w2_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel, @@ -855,17 +833,15 @@ extern "C" int r4d_rad_unrelayout_w2a8(const RadParam* p, int n_p, int operand, return RAD_OK; } -/* ---- MXFP4: fp4 e2m1 codes with an E8M0 exponent a 32. The codes go to fragment order, the - * exponents to [K/32][N], and b_ref is each row's largest exponent -- a reduction over the plane, - * which is a derivation any reader of the plane could make and so not a choice. */ +/* ---- MXFP4: fp4 e2m1 codes with an E8M0 exponent per 32. The codes go to fragment order, the + * exponents to [K/32][N], and b_ref is each row's largest exponent: a reduction any reader of the + * plane could compute, so not a choice. */ namespace { -/* A ROTATED MXFP4 WEIGHT (ParoQuant): the same two planes -- e2m1 codes, an E8M0 exponent a 32 -- - * stored in the basis the "givens" transform names, with the rotation's tables beside them. The - * GEMM reads the codes and exponents exactly as it reads an unrotated weight; the rotation is the - * activation's (givens_dense_quant), and the tables are separate weight operands of that op, so - * nothing here touches them. What is checked is that they are there and are the kind of - * rotation the quantiser applies: a transform this library does not read would hand the kernel - * codes that decode to other numbers. */ +/* A rotated MXFP4 weight (ParoQuant): the same two planes stored in the basis the "givens" + * transform names, with the rotation's tables beside them. The GEMM reads codes and exponents as + * for an unrotated weight; the rotation is applied to the activation (givens_dense_quant), whose + * tables are separate weight operands. This only checks that the tables are present and are the + * rotation the quantiser applies; any other transform would decode to other numbers. */ bool mx_paro_enc(const RadEncoding* e, long long K) { if (!e || !rad_enc_is(e, "affine") || std::strncmp(e->transform, "givens", RAD_ENC_STR) != 0) return false; if (e->n_planes < 5 || !rad_enc_valid(e)) return false; @@ -878,7 +854,7 @@ bool mx_paro_enc(const RadEncoding* e, long long K) { if (p < 0 || an < 0 || sc < 0) return false; if (e->plane[p].dtype != RAD_I32 || e->plane[an].dtype != RAD_F32 || e->plane[sc].dtype != RAD_F32) return false; - // the quantiser rotates whole groups of 128 columns, one scale per group + /* The quantiser rotates whole groups of 128 columns, one scale per group. */ return K % 128 == 0 && e->plane[p].extent[1] == K; } @@ -956,11 +932,10 @@ extern "C" int r4d_rad_relayout_mxfp4(const RadParam* p, int n_p, int operand, return RAD_OK; } -/* ---- the MoE experts. Their 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 exactly. `w4a8h` is the same - * plane with the weight rotated by the group's Hadamard, and only an encoding that says so is - * accepted for it. */ +/* ---- 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 + * plane with the weight Hadamard-rotated per group, accepted only from an encoding that says so. */ namespace { int moew4_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel, const RadTensor* pl, int n, RadLayout* out, WGeom* gout) { @@ -1024,12 +999,12 @@ bool moew5_table_is_kernels(const RadTensor& t) { return true; } -/* THE EXPANSION'S NIBBLE ORDER, two dwords a word. Canonical element 8g+i is nibble i of dword g; - * stored, byte b holds element b low and b+4 high -- nibbles n0 n4 n1 n5 n2 n6 n3 n7, a perfect - * shuffle of the dword's halves. Swapping the middle bytes and then each half's middle nibbles - * makes it; each step exchanges two fields, so the same steps in the other order undo it. Done - * a nibble at a time, with the read-modify-write that implies, the same permutation costs most of - * a Flash-Next load's CPU: every routed expert goes through it. */ +/* The expansion's nibble order, applied to a 64-bit word (two dwords). Canonical element 8g+i is + * nibble i of dword g; stored, byte b holds element b low and b+4 high (nibbles n0 n4 n1 n5 n2 n6 + * n3 n7, a perfect shuffle of the dword's halves). Swapping the middle bytes, then each half's + * middle nibbles, produces it; each step swaps two fields, so the steps in reverse order undo it. + * Every routed expert passes through here at load, so a nibble-at-a-time loop would dominate the + * load's CPU time. */ inline uint64_t moew4_bytes(uint64_t x) { return (x & 0xFF0000FFFF0000FFull) | ((x & 0x0000FF000000FF00ull) << 8) | ((x >> 8) & 0x0000FF000000FF00ull); @@ -1039,7 +1014,7 @@ inline uint64_t moew4_nibbles(uint64_t x) { ((x >> 4) & 0x00F000F000F000F0ull); } -/* `bytes` of codes, a multiple of four, from `s` to `d` -- forward or back. */ +/* Permutes `bytes` of codes (a multiple of four) from `s` to `d`, forward or back. */ void moew4_permute(const uint8_t* s, uint8_t* d, int64_t bytes, bool forward) { int64_t i = 0; for (; i + 8 <= bytes; i += 8) { @@ -1057,16 +1032,15 @@ void moew4_permute(const uint8_t* s, uint8_t* d, int64_t bytes, bool forward) { std::memcpy(d + i, &w, 4); } } -/* ONE w5nl64a8h ROW BETWEEN THE CONTAINER AND THE KERNEL. Stored, a row is K five-bit codes, - * LSB first (rad_plugin.h's packing), so every eight codes are five bytes. Served, it is the - * codes' low nibbles in the canonical 4-bit order -- two a byte, element 2i low -- put through - * moew4_permute as w4nla8h's are, then their high bits, one dword a 32 elements: K/2 + K/8 bytes, - * the same count. +/* One w5nl64a8h row between container and kernel. Stored, a row is K five-bit codes, LSB first + * (rad_plugin.h packing), so every eight codes are five bytes. Served, it is the codes' low nibbles + * in canonical 4-bit order (two per byte, element 2i low) put through moew4_permute as w4nla8h's + * are, then their high bits, one dword per 32 elements: K/2 + K/8 bytes, the same count. * - * THE SIGN DWORD IS TRANSPOSED for the kernel's merge: element 4m+b of a 32 -- byte b of the - * expansion's output dword m -- is bit 7-m of byte b, so `sg << m` lines dword m's four signs up - * on E4M3's sign bits at once (r4d_moe.hip, w5_expand). `nib` is a scratch row of K/2 bytes. */ -inline uint32_t moew5_sign_bit(int64_t j) { /* j: an element's place in its 32 */ + * The sign dword is transposed for the kernel's merge: element 4m+b of a 32 (byte b of the + * expansion's output dword m) is bit 7-m of byte b, so `sg << m` aligns dword m's four signs with + * E4M3's sign bits at once (r4d_moe.hip, w5_expand). `nib` is a scratch row of K/2 bytes. */ +inline uint32_t moew5_sign_bit(int64_t j) { /* j: the element's index within its 32 */ return 8u * (uint32_t)(j & 3) + 7u - (uint32_t)(j >> 2); } void moew5_row(const uint8_t* s, uint8_t* d, int64_t K, uint8_t* nib, bool forward) { @@ -1131,7 +1105,7 @@ int moew4_relayout_by(MoeViewFn view, const RadParam* p, int n_p, int operand, if (rc == RAD_OK) rc = moew4_enc_layout(v.p, v.n, v.operand, enc, sel, pl, n, &L, &g); if (rc != RAD_OK) return rc; if (dst_bytes != L.bytes) return RAD_E_SHAPE; - if (v.operand == Q_BSCALE) { /* w4nl64a8h's: the second level is ours */ + if (v.operand == Q_BSCALE) { /* g64 forms: the second level is fixed */ float s2 = 0.0f; std::memcpy(&s2, pdata(pl[1]), sizeof s2); if (s2 != kW4G64Scale) return RAD_E_DTYPE; @@ -1233,13 +1207,12 @@ extern "C" int r4d_rad_layout_moe_fp8_mod4(const RadParam* p, int n_p, int opera n, out); } -/* ---- conv2d_nhwc: PyTorch's [cout][cin][k][k] stored TAP-MAJOR, [cout][k][k][cin]. +/* ---- conv2d_nhwc: PyTorch's [cout][cin][k][k] stored tap-major, [cout][k][k][cin]. * * The implicit-GEMM convolution (r4d_gen.hip) contracts over K = (tap, channel) with the channel - * innermost, so that eight consecutive K are eight channels of one input pixel -- one 16-byte read - * of an NHWC row. The weight's K has to run the same way, and PyTorch's runs channel-major. A - * permutation of a bf16 plane, so the inverse is the same loop backwards. Operand 1 of - * conv2d_nhwc; the bias is read as it is. */ + * innermost, so eight consecutive K are eight channels of one input pixel, one 16-byte read of an + * NHWC row. The weight's K must run the same way; PyTorch's is channel-major. Operand 1 of + * conv2d_nhwc; the bias is read as stored. */ namespace { constexpr int CONV_W_OPERAND = 1; diff --git a/libr4d/r4d_model_bf16.hip b/libr4d/r4d_model_bf16.hip index 8cfff398..495596c1 100644 --- a/libr4d/r4d_model_bf16.hip +++ b/libr4d/r4d_model_bf16.hip @@ -1,45 +1,26 @@ -// The ten small bf16 ops the engine issues between the GEMMs, and the reason they are here at all. +// The small bf16 ops the engine issues between the GEMMs: embedding gathers, norms, elementwise +// ops, rope, KV stores. Every op in a step needs a device launch, because the engine's buffers +// live in VRAM and `rad_issue` refuses an op with no launch for its operands' domain. // -// The rest of this library is kernels worth writing: a WMMA GEMM, a paged attention, a chunked -// scan. These are not -- they are an embedding gather, a norm, an add, a sigmoid. They -// are here because a step is not a set of interesting kernels, it is a CHAIN, and a chain with one -// host link does not run: the engine's buffers live in VRAM, libref is domain HOST, and -// `rad_issue` refuses an op with no launch for the domain its operands are on. Twenty-one ops -// short of a device implementation is not "slower", it is a server that answers the first request -// with `no device kernel for this band` and exits. So: one kernel library, and this is where a -// kernel with no other home goes -- including the ops nobody would choose to write. -// -// THE ARITHMETIC IS libref's, DELIBERATELY. Ref is the oracle (spec §17) and these are the -// ops whose disagreements would be invisible -- an RMS norm that accumulates in bf16, a gather that -// reads a negative id as unsigned, a rotary that pairs the wrong halves. Each kernel below states -// which ref function it must equal. Where ref rounds, this rounds, in the same place: +// The arithmetic is libref's (the oracle, spec §17); each kernel names the ref function it must +// equal, rounding in the same places: // // * every reduction accumulates in f32 and only the store narrows to bf16; -// * `f32_to_bf16` is round-to-nearest-even (r4d_common.h), which is ref's rounder; -// * a NEGATIVE index -- token id, gather row, KV slot -- is the PADDING convention and writes a -// zero row or skips the store. It is not an error and it is not clamped to zero, which would -// silently duplicate token 0 across every padding position of a ragged batch. +// * `f32_to_bf16` is round-to-nearest-even (r4d_common.h), as in ref; +// * a negative index (token id, gather row, KV slot) is padding and writes a zero row or skips +// the store. It is not clamped to zero, which would duplicate token 0 across padding. // -// ONE DELIBERATE DIVERGENCE FROM REF, and it is about what a kernel can do rather than about the -// arithmetic. Ref reads its index arrays on the host and REFUSES the launch when one is out of -// range -- an id at or above n_vocab, a gather row past the source, a KV slot past the last block. -// A device kernel cannot: the indices are in VRAM, checking them means a copy and a synchronisation -// on the step path, and a per-row `return` cannot become a status. So the bound is an ARGUMENT and -// an out-of-range index takes the same path as a negative one -- a zero row, or no store. That is -// a defined answer to a caller bug; the alternative is a page fault that takes the server down. +// One divergence from ref: ref checks index arrays on the host and refuses out-of-range values. A +// kernel cannot without a copy and sync on the step path, so the bound is an argument and an +// out-of-range index is treated like a negative one (zero row or no store) instead of faulting. // -// AND ONE ON PRECISION: `expf`, `powf` and `sincosf` here are the ACCURATE forms, not the `__` -// hardware approximations. A rope angle is position * inv_freq and position reaches 262144, where -// __sincosf's argument reduction has nothing left; and every one of these ops is an oracle -// comparison away from libref, which uses the libm forms. None of them is on a hot path -// that would notice. +// `expf`, `powf` and `sincosf` are the accurate forms, not the `__` approximations: rope positions +// reach 262144, beyond __sincosf's argument reduction, and libref uses libm. None is on a hot path. // -// WHAT IS NOT HERE. No fusion. `rmsnorm` and `add` next to each other are the unfused sequence -// the architecture plugin asked for, and fusing them is a SELECTION the plugin makes by declaring -// `rmsnorm_add` (spec §2.3), not something a kernel library does behind its back. When the fused -// forms are wanted they are new entry points and new rows, not a rewrite of these. +// No fusion: fused forms such as `rmsnorm_add` are separate entry points the architecture plugin +// selects (spec §2.3). // -// Every entry point returns a negative code rather than throwing, matching r4d_gemm_fp8a8.hip. +// Entry points return a negative code rather than throwing, as in r4d_gemm_fp8a8.hip. #include "r4d.h" #include "r4d_args.h" @@ -57,30 +38,7 @@ constexpr uint32_t kWave = 32; constexpr uint32_t kThreads = 256; constexpr uint32_t kWaves = kThreads / kWave; -__device__ __forceinline__ float bf2f(uint16_t h) { - return __builtin_bit_cast(float, (uint32_t)h << 16); -} - -/* An orthonormal Walsh-Hadamard over N values a THREAD owns, in place and its own inverse. Only - * `kv_store_kernel`'s quality probe uses it, and only there does a sequential butterfly make sense: - * r4d_fwht.h's is the one to reuse anywhere speed matters, and it wants a WAVE per N-wide block - * with N/32 values a lane. N must be a power of two, which every scale group the probe accepts is. */ -template -__device__ __forceinline__ void hadamard(float* a) { - static_assert(N && (N & (N - 1u)) == 0u, "the Walsh-Hadamard width must be a power of two"); - for (uint32_t len = 1; len < N; len <<= 1) - for (uint32_t i = 0; i < N; i += len << 1) - for (uint32_t j = 0; j < len; ++j) { - const float u = a[i + j], w = a[i + j + len]; - a[i + j] = u + w; - a[i + j + len] = u - w; - } - const float s = rsqrtf((float)N); - for (uint32_t e = 0; e < N; ++e) a[e] *= s; -} - -// Sum across the block, broadcast to every thread. One LDS round trip after the wave reduction, -// which is what the norms need and nothing else here does. +// Sum across the block, broadcast to every thread: one LDS round trip after the wave reduction. template __device__ __forceinline__ float block_sum(float v, float* lds) { v = r4d_wave_sum(v); @@ -94,15 +52,13 @@ __device__ __forceinline__ float block_sum(float v, float* lds) { } // ---------------------------------------------------------------------------- embed_lookup -// ref_embed_lookup. One block a token; a negative id -- or one at or above n_vocab, see the -// divergence note at the top -- writes a zero row. +// ref_embed_lookup. One block per token; a negative id, or one at or above n_vocab, writes a zero +// row. // -// `vocab_off` is the first GLOBAL row this rank's table stands for, which makes the embedding -// vocab-parallel: ids stay global, a rank subtracts the offset, and a token belonging to another -// rank takes the same zero-row path the padding id takes. Summing the ranks then reconstructs x. -// At vocab_off = 0 this is the plain gather, to the bit. -// `mult` multiplies every gathered entry, the product rounded once (Gemma's sqrt(hidden)); 1 is the -// plain copy, to the bit. +// `vocab_off` is the first global row of this rank's table, making the embedding vocab-parallel: +// ids stay global, a rank subtracts the offset, and another rank's token takes the zero-row path. +// Summing the ranks reconstructs x. `mult` scales every entry with one rounding (Gemma's +// sqrt(hidden)); 1 is a plain copy. __global__ __launch_bounds__(kThreads) void embed_lookup_kernel( const int32_t* __restrict__ tok, const uint16_t* __restrict__ wte, uint16_t* __restrict__ x, uint32_t n_embd, int32_t n_vocab, int32_t vocab_off, uint32_t x_ld, float mult) { @@ -118,25 +74,22 @@ __global__ __launch_bounds__(kThreads) void embed_lookup_kernel( for (uint32_t i = threadIdx.x; i < n_embd; i += kThreads) dst[i] = src[i]; return; } - for (uint32_t i = threadIdx.x; i < n_embd; i += kThreads) dst[i] = f32_to_bf16(bf2f(src[i]) * mult); + for (uint32_t i = threadIdx.x; i < n_embd; i += kThreads) dst[i] = f32_to_bf16(bf16_to_f32(src[i]) * mult); } // ---------------------------------------------------------------------------- embed_lookup_q -// ref_embed_lookup_q. x[m] = bf16(wte[id] * scale), from a table stored as E4M3 codes with ONE -// scale (Q) or as plain bf16, where an absent scale is one. This is the n-gram table's gather -// (arch/common/rad_block_ple.h) wherever --ngram-placement lets a card read the table: in VRAM, or -// in pinned host memory the card reads in place over the link. +// ref_embed_lookup_q. x[m] = bf16(wte[id] * scale), from a table of E4M3 codes with one scale (Q) +// or plain bf16; an absent scale is one. This is the n-gram table's gather +// (arch/common/rad_block_ple.h) when --ngram-placement lets a card read the table, in VRAM or in +// pinned host memory over the link. // -// A THREAD A QUAD OF ENTRIES, NOT A BLOCK A ROW. A row of the n-gram table is 160 entries, so a -// block a row leaves most of its threads idle and the grid is as deep as the chunk's row count. -// Flattened, consecutive threads take consecutive quads, and a row's 40 threads read its 160 -// contiguous bytes. V = 1 is the same walk an entry at a time, for a width or a pitch the quad's -// 4- and 8-byte accesses would misalign. +// One thread per quad of entries: an n-gram row is only 160 entries, so a block per row would +// leave most threads idle. Consecutive threads take consecutive quads. V = 1 walks one entry at a +// time, for widths or pitches the quad's 4- and 8-byte accesses would misalign. // -// THE VALUE libavx's LOOKUP TABLE HOLDS, to the bit: a code decodes to f32 exactly -// (v_cvt_pk_f32_fp8, or the software form beside it in r4d_fp8_wmma.h), the product with the -// scale rounds once in f32, and f32_to_bf16 rounds to nearest even. An id outside [0, n_vocab) -// after the offset writes a zero row (the divergence note at the top of this file). +// Bit-identical to libavx's lookup table: a code decodes to f32 exactly (v_cvt_pk_f32_fp8 or the +// software form in r4d_fp8_wmma.h), the scale product rounds once in f32, and f32_to_bf16 rounds +// to nearest even. An id outside [0, n_vocab) after the offset writes a zero row. template __global__ __launch_bounds__(kThreads) void embed_lookup_q_kernel( const int32_t* __restrict__ tok, const void* __restrict__ wte, const void* __restrict__ sc, @@ -179,9 +132,9 @@ __global__ __launch_bounds__(kThreads) void embed_lookup_q_kernel( } // ---------------------------------------------------------------------------- gather_rows -// ref_gather_rows. Same shape as the embedding gather and the same negative-index rule, but the -// source row pitch is the caller's rather than n: a gather off a padded activation buffer is what -// the op exists for (one logits row per sequence out of a whole prefill chunk). +// ref_gather_rows. Like the embedding gather, with the same negative-index rule, but the source +// row pitch is the caller's: it gathers from padded activation buffers (one logits row per +// sequence out of a prefill chunk). __global__ __launch_bounds__(kThreads) void gather_rows_kernel( const uint16_t* __restrict__ x, const int32_t* __restrict__ idx, uint16_t* __restrict__ y, uint32_t n, int32_t src_rows, uint32_t x_ld, uint32_t y_ld) { @@ -196,20 +149,15 @@ __global__ __launch_bounds__(kThreads) void gather_rows_kernel( for (uint32_t i = threadIdx.x; i < n; i += kThreads) dst[i] = src[i]; } - // ---------------------------------------------------------------- byte row gather / scatter // -// ref_gather_rows and ref_scatter_rows at dtype u8. A SEPARATE PAIR FROM THE bf16 ONES, and not -// a widened version of them, because these move OPAQUE BYTES: the KV pool's tier traffic is the -// caller, a row is one layer's fragment of one block, and what is in it is whatever the attention -// kernel wrote. Reading that as bf16 would be a lie with teeth -- libref is the oracle for every -// op here, its bf16 path loads through float, and a bf16 NaN payload is not guaranteed to survive -// that round trip. At u8 every value is 0..255 and float carries it exactly, so oracle and kernel -// agree bit for bit on any payload at all. +// ref_gather_rows and ref_scatter_rows at dtype u8. Separate from the bf16 pair because these move +// opaque bytes: the KV pool's tier traffic, where a row is one layer's fragment of one block. +// libref's bf16 path loads through float, which need not preserve a NaN payload; at u8 every value +// is exact in float, so oracle and kernel agree on any payload. // -// 16 BYTES A THREAD WHERE THE ROW ALLOWS IT. A KV fragment is a tensor extent and is aligned; the -// registry constrains `n` to a multiple of 16 so this is the only path, and a row that did not -// satisfy it would not have resolved here. +// One uchar4 per thread step. The registry constrains `n` to a multiple of 16, so there is no +// ragged path. __global__ __launch_bounds__(kThreads) void gather_rows_u8_kernel( const uchar4* __restrict__ x, const int32_t* __restrict__ idx, uchar4* __restrict__ y, uint32_t n4, int32_t src_rows, uint32_t x_ld4, uint32_t y_ld4) { @@ -225,9 +173,8 @@ __global__ __launch_bounds__(kThreads) void gather_rows_u8_kernel( for (uint32_t i = threadIdx.x; i < n4; i += kThreads) dst[i] = src[i]; } -// The mirror. A negative index writes NOTHING -- the destination is a live pool and the rows this -// call was not asked about belong to somebody else, so the zero-fill the gather does for an absent -// row would be data loss here rather than padding. +// The mirror. A negative index writes nothing: the destination is a live pool, so the gather's +// zero-fill would be data loss here. __global__ __launch_bounds__(kThreads) void scatter_rows_u8_kernel( const uchar4* __restrict__ v, const int32_t* __restrict__ idx, uchar4* __restrict__ x, uint32_t n4, int32_t dst_rows, uint32_t v_ld4, uint32_t x_ld4) { @@ -242,19 +189,15 @@ __global__ __launch_bounds__(kThreads) void scatter_rows_u8_kernel( // ---------------------------------------------------------------------------- rmsnorm // ref_rmsnorm: y = x * rsqrt(mean(x^2) + eps) * (w + wadd). // -// THE GAIN IS ADDED IN f32 AFTER THE bf16 LOAD. `wadd` is GemmaRMSNorm's `1 +` (Qwen3.5, -// Qwen3-Next, Gemma store a zero-centred gamma); forming `1 + w` in bf16 first loses 0.3% per -// channel, which is why r4d_rmsnorm_had_quant_i8 takes the same argument and why it is not the -// caller's job to bake it into the weight. +// `wadd` is added to the gain in f32 after the load: it is GemmaRMSNorm's `1 +` (Qwen3.5, +// Qwen3-Next and Gemma store a zero-centred gamma), and forming `1 + w` in bf16 loses 0.3% per +// channel. r4d_rmsnorm_had_quant_i8 takes the same argument. // -// THE GAIN IS f32 OR bf16 AND THE CALLER SAYS WHICH. Every norm gain in this project's -// architecture plugins is declared RAD_F32 -- they are a few thousand elements against gigabytes of -// weights, and the norm is where a rounded gain shows -- while the activation either side is bf16. -// A kernel that assumed one width would read the other as two halves of the wrong number, so the -// width is a template parameter and the shim reads it off the operand. +// The gain is f32 or bf16 (WF32), read off the operand by the shim. Architecture plugins declare +// norm gains RAD_F32, since they are small and a rounded gain shows in the norm. // -// Two passes over the row. n is 256 (a QK-norm head) or 5120 (the hidden state), so the row is in -// L1 for the second pass and a one-pass Welford would buy nothing but a different rounding. +// Two passes over the row: n is 256 (a QK-norm head) or 5120 (the hidden state), so the row is in +// L1 for the second pass, and one-pass Welford would only change the rounding. template __global__ __launch_bounds__(THR) void rmsnorm_kernel( const uint16_t* __restrict__ x, const void* __restrict__ w, uint16_t* __restrict__ y, @@ -265,23 +208,19 @@ __global__ __launch_bounds__(THR) void rmsnorm_kernel( uint16_t* __restrict__ yr = y + (size_t)m * y_ld; float ss = 0.0f; - for (uint32_t i = threadIdx.x; i < n; i += THR) { const float v = bf2f(xr[i]); ss += v * v; } + for (uint32_t i = threadIdx.x; i < n; i += THR) { const float v = bf16_to_f32(xr[i]); ss += v * v; } ss = block_sum(ss, lds); const float s = rsqrtf(ss / (float)n + eps); for (uint32_t i = threadIdx.x; i < n; i += THR) { - const float g = !w ? 1.0f : WF32 ? ((const float*)w)[i] : bf2f(((const uint16_t*)w)[i]); - yr[i] = f32_to_bf16(bf2f(xr[i]) * s * (g + wadd) * mult); + const float g = !w ? 1.0f : WF32 ? ((const float*)w)[i] : bf16_to_f32(((const uint16_t*)w)[i]); + yr[i] = f32_to_bf16(bf16_to_f32(xr[i]) * s * (g + wadd) * mult); } } // ---------------------------------------------------------------------------- rmsnorm_p -// ref_rmsnorm_p: y = x * rsqrt(mean(x^2) + eps) -- the SAME normalisation as rmsnorm with NO gain. -// It is the weightless value normalisation Gemma's attention uses on V (llama.cpp's -// ggml_rms_norm(V, eps), no tensor); there is no checkpoint plane to feed a gain through, so an -// rmsnorm call would need a phantom all-zero weight. Two passes over the row, the sum of squares -// in f32; the second pass drops the gain multiply rmsnorm has. The mean accumulates in f32 in -// ascending index order, exactly as rmsnorm does, so the two agree bit-for-bit where rmsnorm's -// gain happens to be one. +// ref_rmsnorm_p: y = x * rsqrt(mean(x^2) + eps), rmsnorm with no gain. Gemma's attention applies +// it to V (llama.cpp's ggml_rms_norm(V, eps)), which has no checkpoint gain. Accumulates exactly as +// rmsnorm does, so the two agree bit for bit where rmsnorm's gain is one. __global__ __launch_bounds__(kThreads) void rmsnorm_p_kernel( const uint16_t* __restrict__ x, uint16_t* __restrict__ y, uint32_t n, float eps, uint32_t x_ld, uint32_t y_ld) { @@ -290,19 +229,17 @@ __global__ __launch_bounds__(kThreads) void rmsnorm_p_kernel( const uint16_t* __restrict__ xr = x + (size_t)m * x_ld; uint16_t* __restrict__ yr = y + (size_t)m * y_ld; float ss = 0.0f; - for (uint32_t i = threadIdx.x; i < n; i += kThreads) { const float v = bf2f(xr[i]); ss += v * v; } + for (uint32_t i = threadIdx.x; i < n; i += kThreads) { const float v = bf16_to_f32(xr[i]); ss += v * v; } ss = block_sum(ss, lds); const float s = rsqrtf(ss / (float)n + eps); for (uint32_t i = threadIdx.x; i < n; i += kThreads) - yr[i] = f32_to_bf16(bf2f(xr[i]) * s); + yr[i] = f32_to_bf16(bf16_to_f32(xr[i]) * s); } // ---------------------------------------------------------------------------- add / mul -// ref_add / ref_mul, including THE ONE BROADCAST RULE: an operand carrying exactly n elements -// against an output of rows*n broadcasts along rows, and nothing else broadcasts at all. That is -// what makes a bias add this op instead of a second one, and the narrowness is the point -- silent -// broadcasting of an arbitrary shape is how a shape bug becomes a plausible number. -// `b_step` 0 reads one element for the whole row -- with b_ld 0 too, a scalar for the whole op. +// ref_add / ref_mul with one broadcast rule: an operand of exactly n elements against an output of +// rows*n broadcasts along rows; nothing else broadcasts, so shape bugs are not hidden. +// `b_step` 0 reads one element per row; with b_ld 0 too, a scalar for the whole op. __global__ __launch_bounds__(kThreads) void binary_kernel( const uint16_t* __restrict__ a, const uint16_t* __restrict__ b, uint16_t* __restrict__ y, uint32_t n, uint32_t a_ld, uint32_t b_ld, uint32_t y_ld, int mul, uint32_t b_step) { @@ -311,19 +248,16 @@ __global__ __launch_bounds__(kThreads) void binary_kernel( const uint16_t* __restrict__ br = b + (size_t)m * b_ld; uint16_t* __restrict__ yr = y + (size_t)m * y_ld; for (uint32_t i = threadIdx.x; i < n; i += kThreads) { - const float u = bf2f(ar[i]), v = bf2f(br[i * b_step]); + const float u = bf16_to_f32(ar[i]), v = bf16_to_f32(br[i * b_step]); yr[i] = f32_to_bf16(mul ? u * v : u + v); } } // ---------------------------------------------------------------------------- sigmoid -// ref_sigmoid. Its own op and not a mode on a unary kernel for the same reason it is its own row: -// a gated attention output multiplies by sigmoid(gate) and the selector has to be able to name that. +// ref_sigmoid, its own op so the selector can name a gated attention's sigmoid(gate). // -// ROW-WISE WITH A PITCH, not flat over the extent, because the operand it is issued against is a -// COLUMN SLICE: the gate is the second half of each head of an interleaved [tokens, heads, -// 2*head_dim] projection, so its rows are `n` wide inside a stride of 2n and there is no contiguous -// extent to walk. A flat kernel would either refuse it or read the query. +// Row-wise with a pitch because the operand is a column slice: the gate is the second half of each +// head of an interleaved [tokens, heads, 2*head_dim] projection, `n` wide inside a stride of 2n. __global__ __launch_bounds__(kThreads) void sigmoid_kernel( const uint16_t* __restrict__ x, uint16_t* __restrict__ y, uint32_t n, uint32_t x_ld, uint32_t y_ld) { @@ -331,18 +265,16 @@ __global__ __launch_bounds__(kThreads) void sigmoid_kernel( const uint16_t* __restrict__ xr = x + (size_t)m * x_ld; uint16_t* __restrict__ yr = y + (size_t)m * y_ld; for (uint32_t i = threadIdx.x; i < n; i += kThreads) - yr[i] = f32_to_bf16(1.0f / (1.0f + expf(-bf2f(xr[i])))); + yr[i] = f32_to_bf16(1.0f / (1.0f + expf(-bf16_to_f32(xr[i])))); } // ---------------------------------------------------------------------------- logit_softcap -// ref_logit_softcap: y = cap * tanh(x / cap), the final-logit softcap. THE ROW-WISE-WITH-A-PITCH -// SHAPE IS COPIED FROM sigmoid on purpose: Gemma's arch issues it against the logits_gemm's output, -// and the pitch form costs nothing on a contiguous buffer -- it is x_ld == n. +// ref_logit_softcap: y = cap * tanh(x / cap), the final-logit softcap. Row-wise with a pitch like +// sigmoid; on a contiguous buffer x_ld == n. // -// A ROW IS SPREAD OVER gridDim.y BLOCKS, because a row is a vocabulary shard: 65536 wide at Gemma -// 4's tp 4, and the step's rows are a decode's few. One block a row walked 256 elements a thread of -// tanhf on a handful of CUs -- ~85 us at one row, --profile-ops on an R9700, for 256 KiB of f32. -// Elementwise, so the spread moves no bits. +// A row is spread over gridDim.y blocks: it is a vocabulary shard (65536 wide at Gemma 4's tp 4) +// and decode has few rows, so one block per row leaves most CUs idle (~85 us at one row on an +// R9700). Elementwise, so the split changes no bits. __global__ __launch_bounds__(kThreads) void logit_softcap_kernel( const uint16_t* __restrict__ x, uint16_t* __restrict__ y, uint32_t n, float cap, uint32_t x_ld, uint32_t y_ld) { @@ -350,12 +282,10 @@ __global__ __launch_bounds__(kThreads) void logit_softcap_kernel( const uint16_t* __restrict__ xr = x + (size_t)m * x_ld; uint16_t* __restrict__ yr = y + (size_t)m * y_ld; for (uint32_t i = blockIdx.y * kThreads + threadIdx.x; i < n; i += gridDim.y * kThreads) - yr[i] = f32_to_bf16(cap * tanhf(bf2f(xr[i]) / cap)); + yr[i] = f32_to_bf16(cap * tanhf(bf16_to_f32(xr[i]) / cap)); } -/* The f32 leg: the 1.3.0 sampling chain carries the logits in f32 from the gemm, so the softcap - * is issued against f32 rows. The same row-with-pitch shape as the bf16 leg, and the math is the - * op's definition verbatim -- no rounding pass, the buffer already holds the arithmetic dtype. */ +/* The f32 leg, for logits the gemm writes as f32. Same shape as the bf16 leg, with no rounding. */ __global__ __launch_bounds__(kThreads) void logit_softcap_kernel_f32( const float* __restrict__ x, float* __restrict__ y, uint32_t n, float cap, uint32_t x_ld, uint32_t y_ld) { @@ -366,42 +296,34 @@ __global__ __launch_bounds__(kThreads) void logit_softcap_kernel_f32( yr[i] = cap * tanhf(xr[i] / cap); } -/* The blocks a softcap row is spread over: eight elements a thread, at most 64 blocks a row. */ +/* Blocks per softcap row: eight elements a thread, at most 64 blocks. */ static uint32_t softcap_blocks_per_row(int n) { uint32_t b = (uint32_t)((n + kThreads * 8 - 1) / (kThreads * 8)); return b < 1 ? 1 : (b > 64 ? 64 : b); } // ---------------------------------------------------------------------------- scale -// ref_scale: y = x * s, s a [1] weight broadcast over every element. THE ROW-WISE-WITH-A-PITCH -// SHAPE IS COPIED FROM sigmoid on purpose: Gemma's arch issues it against the residual stream at -// the end of every layer (the per-layer scalar), and the pitch form costs nothing on a contiguous -// buffer -- it is x_ld == n. The scalar is read once per block (a single load, cached), not per -// element: a per-element reload of a [1] tensor is the same value every time and costs a load per -// element. `s` is f32 or bf16 (the layer_scalar weight is bf16 in the checkpoint); the branch is -// on its dtype, so the op is dtype-generic in the scalar and the bf16 kernel is the residual -// stream's, which is what a served Gemma 4 issues it against. +// ref_scale: y = x * s, s a [1] weight broadcast over every element (Gemma's per-layer scalar on +// the residual stream). Row-wise with a pitch like sigmoid. The scalar is loaded once per block; +// it is f32 or bf16 (the checkpoint's layer_scalar is bf16), selected by `s_dt`. __global__ __launch_bounds__(kThreads) void scale_kernel( const uint16_t* __restrict__ x, const void* __restrict__ s, uint32_t s_dt, uint16_t* __restrict__ y, uint32_t n, uint32_t x_ld, uint32_t y_ld) { const uint32_t m = blockIdx.x; - const float sv = (s_dt == RAD_F32) ? ((const float*)s)[0] : bf2f(((const uint16_t*)s)[0]); + const float sv = (s_dt == RAD_F32) ? ((const float*)s)[0] : bf16_to_f32(((const uint16_t*)s)[0]); const uint16_t* __restrict__ xr = x + (size_t)m * x_ld; uint16_t* __restrict__ yr = y + (size_t)m * y_ld; for (uint32_t i = threadIdx.x; i < n; i += kThreads) - yr[i] = f32_to_bf16(bf2f(xr[i]) * sv); + yr[i] = f32_to_bf16(bf16_to_f32(xr[i]) * sv); } // ---------------------------------------------------------------------------- silu_mul -// ref_silu_mul: y[.., i] = silu(gu[.., i]) * gu[.., n + i]. THE GATE IS THE FIRST HALF, which is -// the order rad-convert fuses gate_proj and up_proj into one weight in; the two conventions cannot -// drift because both are stated and neither is inferred. +// ref_silu_mul: y[.., i] = silu(gu[.., i]) * gu[.., n + i]. The gate is the first half, the order in +// which rad-convert fuses gate_proj and up_proj. // -// A ROW IS SPLIT OVER grid.y, kSiluPer elements a thread. One workgroup a row put a decode step's few -// rows on as many workgroups, each walking its row a strided element at a time behind an exp and a -// divide: latency-bound, and the shape of that walk was up to the compiler. Here a thread's -// elements are independent and their loads unconditional (a column past the row reads its last -// element and the store drops it), so they are all in flight at once. Same arithmetic an element. +// A row is split over grid.y, kSiluPer elements per thread, so decode's few rows use more than a +// few workgroups. A thread's loads are unconditional (a column past the row reads the last element +// and its store is dropped), so all are in flight at once. constexpr uint32_t kSiluPer = 4; __global__ __launch_bounds__(kThreads) void silu_mul_kernel( const uint16_t* __restrict__ gu, uint16_t* __restrict__ y, @@ -420,17 +342,15 @@ __global__ __launch_bounds__(kThreads) void silu_mul_kernel( #pragma unroll for (uint32_t u = 0; u < kSiluPer; ++u) { const uint32_t i = i0 + u * kThreads; - const float g = bf2f(gv[u]); - if (i < n) yr[i] = f32_to_bf16((g / (1.0f + expf(-g))) * bf2f(uv[u])); + const float g = bf16_to_f32(gv[u]); + if (i < n) yr[i] = f32_to_bf16((g / (1.0f + expf(-g))) * bf16_to_f32(uv[u])); } } // ---------------------------------------------------------------------------- gelu_mul -// ref_gelu_mul: y[.., i] = gelu_tanh(gu[.., i]) * gu[.., n + i]. THE GATE IS THE FIRST HALF, the -// same order-lock as silu_mul. The tanh-approx GELU (gemma's gelu_pytorch_tanh), NOT the erf one: -// gated feed-forwards are trained with the tanh form, and the constants are the standard fit the -// gemm_nt_bias "gelu_tanh" epilogue uses (the identical function, so a GELU-gated FFN and a -// tanh-gelu epilogue agree to the last bit). +// ref_gelu_mul: y[.., i] = gelu_tanh(gu[.., i]) * gu[.., n + i], gate first as in silu_mul. The tanh +// GELU (gemma's gelu_pytorch_tanh), not erf, with the same constants as the gemm_nt_bias +// "gelu_tanh" epilogue so the two agree bit for bit. __global__ __launch_bounds__(kThreads) void gelu_mul_kernel( const uint16_t* __restrict__ gu, uint16_t* __restrict__ y, uint32_t n, uint32_t gu_ld, uint32_t y_ld) { @@ -438,35 +358,30 @@ __global__ __launch_bounds__(kThreads) void gelu_mul_kernel( const uint16_t* __restrict__ gr = gu + (size_t)m * gu_ld; uint16_t* __restrict__ yr = y + (size_t)m * y_ld; for (uint32_t i = threadIdx.x; i < n; i += kThreads) { - const float g = bf2f(gr[i]); + const float g = bf16_to_f32(gr[i]); const float k0 = 0.7978845608028654f, k1 = 0.044715f; const float gelu = 0.5f * g * (1.0f + tanhf(k0 * (g + k1 * g * g * g))); - yr[i] = f32_to_bf16(gelu * bf2f(gr[n + i])); + yr[i] = f32_to_bf16(gelu * bf16_to_f32(gr[n + i])); } } // ---------------------------------------------------------------------------- rope -// ref_rope, in place over a fused [n_head + 2*n_head_kv] head row -- the V heads at the end are -// left alone, which is the whole reason the op takes the fused projection rather than two tensors. +// ref_rope, in place over a fused [n_head + 2*n_head_kv] head row; the trailing V heads are left +// alone, which is why the op takes the fused projection. // -// NeoX pairs element i with i + rot/2; GPT-J pairs 2i with 2i+1. Which one a checkpoint wants is a -// property of the checkpoint, and getting it wrong produces fluent text with a broken sense of -// position -- the hardest kind of wrong to notice. `mrope` is NOT a third case: RadBatch carries -// one position component per token, and mrope over equal components is bit-identical to neox -// (rad_block_attn_gated.h says so and says what would have to change first), so the shim maps it. +// NeoX pairs element i with i + rot/2; GPT-J pairs 2i with 2i+1. The checkpoint decides, and the +// wrong choice yields fluent text with broken positions. With one position component per token, +// mrope is bit-identical to neox (rad_block_attn_gated.h), so the shim maps it. // -// PARTIAL ROTARY. `rot` may be less than head_dim -- 64 of 256 on this target -- and the tail of -// the head is untouched. The base ladder's exponent divides by `den`, which `ladder` resolves: -// `rot` for `rotary` (the rotated prefix, a complete rotary of its own width) and `head_dim` for -// `head` (the proportional variant, a prefix of the full-width table). `den` = `rot` on the -// default path, so existing models are bit-for-bit unchanged. +// Partial rotary: `rot` may be less than head_dim (64 of 256 here) and the tail is untouched. The +// base ladder's exponent divides by `den`: `rot` for `rotary` (default), `head_dim` for `head` +// (the proportional variant). // -// One thread a PAIR. The pair's two loads and two stores are the whole body, so there is no -// reduction and no LDS; the grid is (M, heads). +// One thread per pair: two loads and two stores, no reduction, no LDS. // -// THE MULTI-COMPONENT MODES (ref_rope's rope_freqs): `mode` 2 mrope, 3 imrope, 4 axial, with up to -// three sections, read a position per component out of `plane`-strided rows -- component c of -// token m at pos[c * plane + m]. `plane` 0 is the one-component form, where every mode is neox. +// Multi-component modes (ref_rope's rope_freqs): `mode` 2 mrope, 3 imrope, 4 axial, up to three +// sections, with component c of token m at pos[c * plane + m]. `plane` 0 is the one-component +// form, where every mode is neox. __device__ __forceinline__ int rope_comp(int mode, uint32_t i, const int* sec, int n_sec, uint32_t* j) { *j = i; @@ -506,9 +421,9 @@ __global__ __launch_bounds__(kThreads) void rope_kernel( inv = 1.0f / powf(theta, (float)(2 * j) / (float)(2 * sec[c])); } inv = yarn.frequency(inv, (int)i); - /* THE PROPORTIONAL LADDER rotates the whole head with every frequency past nfreq zero - * (HF's _compute_proportional_rope_parameters), so pair i is (i, i + head_dim/2) and the - * pairs past nfreq turn by 0: cos 1, sin 0, the value back exactly. */ + /* The proportional ladder rotates the whole head with every frequency past nfreq zero + * (HF's _compute_proportional_rope_parameters): pair i is (i, i + head_dim/2), and pairs + * past nfreq turn by 0 (cos 1, sin 0), returning the value exactly. */ if (i >= nfreq) inv = 0.0f; const float ang = p * inv; float c, s; @@ -516,22 +431,20 @@ __global__ __launch_bounds__(kThreads) void rope_kernel( if (yarn.factor != 0.0f) { c *= yarn.magnitude; s *= yarn.magnitude; } const uint32_t i0 = gptj ? 2 * i : i; const uint32_t i1 = gptj ? 2 * i + 1 : i + half; - const float x0 = bf2f(hd[i0]), x1 = bf2f(hd[i1]); + const float x0 = bf16_to_f32(hd[i0]), x1 = bf16_to_f32(hd[i1]); hd[i0] = f32_to_bf16(x0 * c - x1 * s); hd[i1] = f32_to_bf16(x0 * s + x1 * c); } } // ---------------------------------------------------------------------------- kv_store -// ref_kv_store, and THE PAGED LAYOUT IS THE ONE EVERY KERNEL IN THIS PROJECT SHARES: +// ref_kv_store. The paged layout every kernel in this project shares: // // kv_cache[num_blocks, kv_heads, block_size, 2 * head_dim] // -// K first and V second inside a slot: element d of the key at [..., d] and of the value at -// [..., head_dim + d]. A flat slot index decomposes as block = slot / block_size and -// offset = slot % block_size, which is what `slot_mapping` carries. A NEGATIVE slot is a padding -// position and stores nothing. -template +// K then V inside a slot: key element d at [..., d], value element d at [..., head_dim + d]. A flat +// slot index (`slot_mapping`) splits into block = slot / block_size, offset = slot % block_size. A +// negative slot is padding and stores nothing. __global__ __launch_bounds__(kThreads) void kv_store_kernel( const uint16_t* __restrict__ k, const uint16_t* __restrict__ v, const int32_t* __restrict__ slot, uint16_t* __restrict__ kv, @@ -544,101 +457,6 @@ __global__ __launch_bounds__(kThreads) void kv_store_kernel( const size_t slot_base = ((size_t)blk * kv_heads * block_size + (size_t)off) * 2 * head_dim; const size_t head_step = (size_t)block_size * 2 * head_dim; - if constexpr (QG) { - /* ---- A QUALITY PROBE, NOT A FORMAT. `R4D_KV_QSIM=` round-trips every `g`-element - * group of k and of v through a quantiser with its own scale and stores the result as - * ordinary bf16. Nothing about the cache's layout, size or bandwidth changes -- the point - * is to answer "would this format still write correct code" BEFORE any of that is built, - * rather than building a real cache to find out. - * - * THREE KNOBS, and each one is a question: - * R4D_KV_QSIM= the scale group. int8 spends its 8 bits on the range the group - * occupies, so the components that carry the dot product land near - * bf16 and only the small ones are coarse. - * R4D_KV_QSIMF=1 snap to E4M3 instead of int8. E4M3 keeps 3 mantissa bits at EVERY - * magnitude -- ~6% relative everywhere -- so a scale cannot change its - * step, only keep a small head out of the subnormals below 2^-6. - * R4D_KV_QSIMW=1 ROTATE the group by an orthonormal Walsh-Hadamard first. A scale is - * set by the group's largest element, so one outlier channel costs - * every other element its resolution; the rotation spreads that - * outlier over all QG channels. It is why this engine's own WIRE codec - * is `wht6` and not `u6`. - * - * THE ROTATION IS FREE TO DEPLOY ON BOTH SIDES, which is what makes it worth measuring. - * The transform is orthonormal and its own inverse, so - * - * score[t] = q . k[t] = (R q) . (R k[t]) - * out = sum p[t] v[t] = R^T ( sum p[t] (R v[t]) ) - * - * -- a cache holding R k and R v needs the QUERY rotated once per (token, head) and the - * OUTPUT rotated back once per (token, head). Neither is per CACHED token, so the cost - * does not grow with context, which is the whole reason a KV cache is expensive. This - * probe rotates back itself instead, because it stores bf16: same values, one extra round. - * - * WHAT THE PROBE SAYS ABOUT EIGHT BITS. Top-1 agreement against a bf16 control is a - * Bernoulli trial a prompt, so at p ~ 0.93 its standard error is a couple of points at any - * prompt count worth running -- and every 8-bit arm sits inside that band at ~93-94% - * agreement. The mean absolute delta, which has thousands of samples rather than hundreds, - * separates them by only ~5% end to end: int8 with a per-head scale and a rotated K at - * 0.196, int8 with a scale per 32 at 0.199, unscaled fp8 e4m3 at 0.205. - * - * THE CASE FOR AN INTEGER KV CACHE IS THEREFORE WEAK: fp8 is already built, is DENSER - * (50.0% of bf16 against 50.8% for scaled int8), and measures the same. The rotation does - * not change that. The rotation MECHANISM is real all the same -- at int4 it is worth - * +5.0 points of agreement and takes |delta| from 0.308 to 0.255 -- there is simply little - * left for it to fix at eight bits. - * - * ONE THREAD OWNS A GROUP, and k and v are done in SEPARATE PASSES so the thread holds QG - * floats and not 2*QG -- at QG = 256 that is the difference between 1 KiB of scratch a - * lane and 2. This runs once per stored token and its speed is irrelevant; a plain - * sequential butterfly is used rather than r4d_fwht.h's, which wants a WAVE per block. */ - const uint32_t ng = kv_heads * head_dim / QG; - for (uint32_t g = threadIdx.x; g < ng; g += kThreads) { - const uint32_t j0 = g * QG, h = j0 / head_dim, d0 = j0 % head_dim; - uint16_t* __restrict__ c = kv + slot_base + (size_t)h * head_step; - const uint16_t* const src[2] = { k + (size_t)t * k_ld + j0, - v + (size_t)t * v_ld + j0 }; - uint16_t* const dst[2] = { c + d0, c + head_dim + d0 }; -#pragma unroll 1 - for (uint32_t which = 0; which < 2u; ++which) { - /* QW: 0 none, 1 both, 2 K only, 3 V only. The asymmetry is the point -- the - * outlier structure a rotation exists to break up is a KEY phenomenon (channels - * that are consistently large after RoPE), and a value row has no such structure, - * so rotating V may only be mixing its own quantisation noise across channels. */ - constexpr bool rot_k = (QW == 1u || QW == 2u); - constexpr bool rot_v = (QW == 1u || QW == 3u); - const bool rot = which == 0u ? rot_k : rot_v; - float b[QG]; - for (uint32_t e = 0; e < QG; ++e) b[e] = bf2f(src[which][e]); - if constexpr (rot_k || rot_v) { if (rot) hadamard(b); } - float amax = 0.0f; - for (uint32_t e = 0; e < QG; ++e) amax = fmaxf(amax, fabsf(b[e])); - /* QB is the integer width: 8 bits is +-127 and 4 is +-7. Four is where a rotation - * has the most to gain, because that is where one outlier really does cost every - * other element in the group its resolution. E4M3 ignores it. */ - const float lvl = (float)((1u << (QB - 1u)) - 1u); - const float sc = - amax > 0.0f ? amax * (QF ? (1.0f / 448.0f) : (1.0f / lvl)) : 1.0f; - for (uint32_t e = 0; e < QG; ++e) { - const float q = b[e] / sc; - if constexpr (QF) { - /* The clamp is the fp8 quantiser's own: the builtin answers an - * out-of-range input with a NaN rather than saturating, and amax/scale is - * 448 in exact arithmetic but can land an ulp above it. */ - int pk = 0; - pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(q, -448.0f), 448.0f), - 0.0f, pk, false); - b[e] = r4d_fp8::e4m3((uint32_t)pk & 0xFFu) * sc; - } else { - b[e] = fminf(fmaxf(rintf(q), -lvl), lvl) * sc; - } - } - if constexpr (rot_k || rot_v) { if (rot) hadamard(b); } - for (uint32_t e = 0; e < QG; ++e) dst[which][e] = f32_to_bf16(b[e]); - } - } - return; - } for (uint32_t j = threadIdx.x; j < kv_heads * head_dim; j += kThreads) { const uint32_t h = j / head_dim, d = j % head_dim; uint16_t* __restrict__ c = kv + slot_base + (size_t)h * head_step; @@ -647,20 +465,15 @@ __global__ __launch_bounds__(kThreads) void kv_store_kernel( } } -// The same scatter into an E4M3 cache. It is the write side of the fp8kv attention family and its -// `k_descale` / `v_descale` operands: without it a cache declared fp8 has no way to be filled. +// The same scatter into an E4M3 cache: the write side of the fp8kv attention family and its +// `k_descale` / `v_descale` operands. // -// THE SCALE IS A CALLER CONSTANT AND IT HAS TO BE. The reader's descale is indexed -// `[seq * kv_heads + kv_head]` (r4d.h), which is ONE number for a whole sequence -- so it cannot -// depend on the token being written, because tokens written at different steps share it. vLLM has -// the same contract and defaults both scales to 1.0. This takes them as arguments so a calibrated -// pair costs nothing later; at 1.0 the store is a plain E4M3 round of the bf16 the attention would -// otherwise have cached. +// The scale is a caller constant: the reader's descale is indexed `[seq * kv_heads + kv_head]` +// (r4d.h), one number per sequence, so it cannot depend on the token written. vLLM has the same +// contract and defaults both scales to 1.0, where the store is a plain E4M3 round of the bf16. // -// FOUR COLUMNS A THREAD, for the reason quant_act_fp8 takes four: it is exactly the two -// v_cvt_pk_fp8_f32 that fill one dword, and the store is then a single dword rather than four -// byte writes. head_dim is a multiple of 4 on every shape this serves and the entry point refuses -// anything else, so a head's 4-column group never straddles two heads and there is no ragged tail. +// Four columns per thread: two v_cvt_pk_fp8_f32 fill one dword, stored at once. The entry point +// requires head_dim % 4 == 0, so a group never straddles two heads. __global__ __launch_bounds__(kThreads) void kv_store_fp8_kernel( const uint16_t* __restrict__ k, const uint16_t* __restrict__ v, const int32_t* __restrict__ slot, uint8_t* __restrict__ kv, @@ -679,11 +492,11 @@ __global__ __launch_bounds__(kThreads) void kv_store_fp8_kernel( float kf[4], vf[4]; #pragma unroll for (int e = 0; e < 4; ++e) { - kf[e] = bf2f(k[(size_t)t * k_ld + j + (uint32_t)e]) * k_inv; - vf[e] = bf2f(v[(size_t)t * v_ld + j + (uint32_t)e]) * v_inv; + 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; } - // Clamped because v_cvt_pk_fp8_f32 answers an out-of-range input with NaN, not a - // saturate -- the same reason quant_act_fp8 clamps. + // Clamped because v_cvt_pk_fp8_f32 returns NaN for out-of-range input instead of + // saturating (as in quant_act_fp8). 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); @@ -702,20 +515,16 @@ __global__ __launch_bounds__(kThreads) void kv_store_fp8_kernel( // ================================================================================ entry points // -// Pitches are in ELEMENTS and 0 means "tight". Every pointer is bf16 except the index arrays, -// which are i32 -- the core's derived buffers are all i32 (core/sched/batch.cpp refuses anything -// else), so there is no 64-bit index form to serve. +// Pitches are in elements; 0 means tight. Pointers are bf16 except the index arrays, which are i32 +// (the core's derived buffers are all i32, core/sched/batch.cpp). -/* THE BODY TAKES A SINK; THE PUBLIC ENTRY IS A WRAPPER. `r4d.h`'s long-stream signature is - * libr4d's driver API and callers outside this tree use it, so it stays exactly as it was -- but - * the launch has to be describable, and writing the geometry twice is the one thing ABI v10's - * contract says not to do. One body, two ways in. */ +/* The plugin entry and r4d.h's long-stream entry share this body. */ static int embed_lookup_bf16_emit(long tok, long wte, long x, int M, int n_embd, int n_vocab, - int vocab_off, int x_ld, float mult, const R4dSink& sk) { + int vocab_off, int x_ld, float mult, RadStream stream) { if (!tok || !wte || !x) return -1; if (M <= 0 || n_embd <= 0 || n_vocab <= 0 || vocab_off < 0) return -2; if (!x_ld) x_ld = n_embd; - return R4D_EMIT(sk, embed_lookup_kernel, dim3((uint32_t)M), dim3(kThreads), 0, + return R4D_EMIT(stream, embed_lookup_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (const int32_t*)tok, (const uint16_t*)wte, (uint16_t*)x, (uint32_t)n_embd, (int32_t)n_vocab, (int32_t)vocab_off, (uint32_t)x_ld, mult) == RAD_OK ? 0 : -4; @@ -723,21 +532,21 @@ static int embed_lookup_bf16_emit(long tok, long wte, long x, int M, int n_embd, extern "C" int r4d_embed_lookup_bf16(long tok, long wte, long x, int M, int n_embd, int n_vocab, int vocab_off, int x_ld, long stream) { - R4dSink sk; sk.stream = (RadStream)(uintptr_t)stream; - return embed_lookup_bf16_emit(tok, wte, x, M, n_embd, n_vocab, vocab_off, x_ld, 1.0f, sk); + return embed_lookup_bf16_emit(tok, wte, x, M, n_embd, n_vocab, vocab_off, x_ld, 1.0f, + (RadStream)(uintptr_t)stream); } -/* The quad walk when the width, the pitch and both bases allow its 4- and 8-byte accesses (a bf16 - * table's quad is 8 bytes), an entry a thread otherwise. */ +/* The quad walk when width, pitch and both bases allow its 4- and 8-byte accesses (a bf16 quad is + * 8 bytes); otherwise one entry per thread. */ static int embed_lookup_q_emit(const int32_t* tok, const void* wte, bool q, const void* sc, bool sc_f32, uint16_t* x, long long M, int n_embd, int n_vocab, - int vocab_off, long long x_ld, const R4dSink& sk) { + int vocab_off, long long x_ld, RadStream stream) { const bool quad = n_embd % 4 == 0 && x_ld % 4 == 0 && r4d_aligned(x, 8) && r4d_aligned(wte, q ? 4 : 8); const uint64_t threads = (uint64_t)M * (uint64_t)(quad ? n_embd / 4 : n_embd); const dim3 grid((uint32_t)((threads + kThreads - 1) / kThreads)); #define R4D_ELQ(V, Q) \ - R4D_EMIT(sk, (embed_lookup_q_kernel), grid, dim3(kThreads), 0, tok, wte, sc, \ + R4D_EMIT(stream, (embed_lookup_q_kernel), grid, dim3(kThreads), 0, tok, wte, sc, \ (uint32_t)(sc_f32 ? 1u : 0u), x, (uint32_t)M, (uint32_t)n_embd, (int32_t)n_vocab, \ (int32_t)vocab_off, (uint32_t)x_ld) const int rc = quad ? (q ? R4D_ELQ(4, true) : R4D_ELQ(4, false)) @@ -749,17 +558,17 @@ static int embed_lookup_q_emit(const int32_t* tok, const void* wte, bool q, cons extern "C" int r4d_embed_lookup_bf16_scaled(long tok, long wte, long x, int M, int n_embd, int n_vocab, int vocab_off, int x_ld, float scale, long stream) { - R4dSink sk; sk.stream = (RadStream)(uintptr_t)stream; - return embed_lookup_bf16_emit(tok, wte, x, M, n_embd, n_vocab, vocab_off, x_ld, scale, sk); + return embed_lookup_bf16_emit(tok, wte, x, M, n_embd, n_vocab, vocab_off, x_ld, scale, + (RadStream)(uintptr_t)stream); } static int gather_rows_bf16_emit(long x, long idx, long y, int M, int n, int src_rows, - int x_ld, int y_ld, const R4dSink& sk) { + int x_ld, int y_ld, RadStream stream) { if (!x || !idx || !y) return -1; if (M <= 0 || n <= 0 || src_rows <= 0) return -2; if (!x_ld) x_ld = n; if (!y_ld) y_ld = n; - return R4D_EMIT(sk, gather_rows_kernel, dim3((uint32_t)M), dim3(kThreads), 0, + return R4D_EMIT(stream, gather_rows_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (const uint16_t*)x, (const int32_t*)idx, (uint16_t*)y, (uint32_t)n, (int32_t)src_rows, (uint32_t)x_ld, (uint32_t)y_ld) == RAD_OK ? 0 : -4; @@ -767,22 +576,19 @@ static int gather_rows_bf16_emit(long x, long idx, long y, int M, int n, int src extern "C" int r4d_gather_rows_bf16(long x, long idx, long y, int M, int n, int src_rows, int x_ld, int y_ld, long stream) { - R4dSink sk; sk.stream = (RadStream)(uintptr_t)stream; - return gather_rows_bf16_emit(x, idx, y, M, n, src_rows, x_ld, y_ld, sk); + return gather_rows_bf16_emit(x, idx, y, M, n, src_rows, x_ld, y_ld, + (RadStream)(uintptr_t)stream); } - -/* Byte rows. `n`, `x_ld` and `y_ld` are in BYTES at this boundary and are divided down to uchar4 - * inside, so a caller that thinks in a pool's byte strides never has to convert -- and the one - * place the /4 happens is the one place it can be wrong. */ +/* Byte rows. `n`, `x_ld` and `y_ld` are in bytes here and divided down to uchar4 inside. */ static int gather_rows_u8_emit(long x, long idx, long y, int M, int n, int src_rows, - int x_ld, int y_ld, const R4dSink& sk) { + int x_ld, int y_ld, RadStream stream) { if (!x || !idx || !y) return -1; if (M <= 0 || n <= 0 || src_rows <= 0) return -2; if (!x_ld) x_ld = n; if (!y_ld) y_ld = n; if ((n | x_ld | y_ld) & 3) return -2; /* the registry constrains n; pitches too */ - return R4D_EMIT(sk, gather_rows_u8_kernel, dim3((uint32_t)M), dim3(kThreads), 0, + return R4D_EMIT(stream, gather_rows_u8_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (const uchar4*)x, (const int32_t*)idx, (uchar4*)y, (uint32_t)(n / 4), (int32_t)src_rows, (uint32_t)(x_ld / 4), (uint32_t)(y_ld / 4)) == RAD_OK ? 0 : -4; @@ -790,18 +596,18 @@ static int gather_rows_u8_emit(long x, long idx, long y, int M, int n, int src_r extern "C" int r4d_gather_rows_u8(long x, long idx, long y, int M, int n, int src_rows, int x_ld, int y_ld, long stream) { - R4dSink sk; sk.stream = (RadStream)(uintptr_t)stream; - return gather_rows_u8_emit(x, idx, y, M, n, src_rows, x_ld, y_ld, sk); + return gather_rows_u8_emit(x, idx, y, M, n, src_rows, x_ld, y_ld, + (RadStream)(uintptr_t)stream); } static int scatter_rows_u8_emit(long v, long idx, long x, int M, int n, int dst_rows, - int v_ld, int x_ld, const R4dSink& sk) { + int v_ld, int x_ld, RadStream stream) { if (!v || !idx || !x) return -1; if (M <= 0 || n <= 0 || dst_rows <= 0) return -2; if (!v_ld) v_ld = n; if (!x_ld) x_ld = n; if ((n | v_ld | x_ld) & 3) return -2; - return R4D_EMIT(sk, scatter_rows_u8_kernel, dim3((uint32_t)M), dim3(kThreads), 0, + return R4D_EMIT(stream, scatter_rows_u8_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (const uchar4*)v, (const int32_t*)idx, (uchar4*)x, (uint32_t)(n / 4), (int32_t)dst_rows, (uint32_t)(v_ld / 4), (uint32_t)(x_ld / 4)) == RAD_OK ? 0 : -4; @@ -809,24 +615,22 @@ static int scatter_rows_u8_emit(long v, long idx, long x, int M, int n, int dst_ extern "C" int r4d_scatter_rows_u8(long v, long idx, long x, int M, int n, int dst_rows, int v_ld, int x_ld, long stream) { - R4dSink sk; sk.stream = (RadStream)(uintptr_t)stream; - return scatter_rows_u8_emit(v, idx, x, M, n, dst_rows, v_ld, x_ld, sk); + return scatter_rows_u8_emit(v, idx, x, M, n, dst_rows, v_ld, x_ld, + (RadStream)(uintptr_t)stream); } -// `w_f32` says whether the gain is f32 (every norm gain the architecture plugins declare) or bf16; -// a null `w` is a gain of one. `mult` scales the row before its one rounding (rmsnorm's `mult`). +// `w_f32` selects an f32 or bf16 gain; a null `w` is a gain of one. `mult` scales the row before +// its single rounding. extern "C" int r4d_rmsnorm_mult_bf16(long x, long w, long y, int M, int n, float eps, float wadd, float mult, int w_f32, int x_ld, int y_ld, long stream) { if (!x || !y) return -1; if (M <= 0 || n <= 0) return -2; if (!x_ld) x_ld = n; if (!y_ld) y_ld = n; - // ONE WORKGROUP A ROW, so the grid at a decode batch is a handful of workgroups on a 64-CU - // part and the row is latency bound. r4d_act_threads is the measured crossover table the int8 - // activation kernels already use; r4d_rmsnorm_quant_fp8 calls the SAME function, and it has to, - // because the width decides which columns a thread folds into the sum of squares. Two kernels - // that disagree about it disagree in the last bits of the norm, and the fused one is required - // to be byte-identical to this kernel followed by the quantiser. + // One workgroup per row, so decode rows are latency-bound. r4d_act_threads is the measured + // width table; r4d_rmsnorm_quant_fp8 must use the same one, because the width decides which + // columns a thread folds into the sum of squares and the fused kernel must be byte-identical + // to this one followed by the quantiser. const int thr = r4d_act_threads(M, n); #define R4D_RN_T(wf, T) \ hipLaunchKernelGGL((rmsnorm_kernel), dim3((uint32_t)M), dim3(T), 0, \ @@ -843,16 +647,14 @@ extern "C" int r4d_rmsnorm_mult_bf16(long x, long w, long y, int M, int n, float return hipGetLastError() == hipSuccess ? 0 : -4; } -/* The unscaled form, the entry point every caller before `mult` used: times one is exact. */ +/* The unscaled form (mult = 1 is exact). */ extern "C" int r4d_rmsnorm_bf16(long x, long w, long y, int M, int n, float eps, float wadd, int w_f32, int x_ld, int y_ld, long stream) { return r4d_rmsnorm_mult_bf16(x, w, y, M, n, eps, wadd, 1.0f, w_f32, x_ld, y_ld, stream); } -// The weightless norm: rmsnorm without the gain multiply. It is not templated on a thread count -// the way rmsnorm is, because rmsnorm's width is pinned to the fused rmsnorm_quant_fp8 by their -// shared byte-identical requirement, and rmsnorm_p has no fused quantiser counterpart to match -- -// kThreads is the same choice the other non-templated row kernels (binary, sigmoid, silu_mul) make. +// The weightless norm. Unlike rmsnorm it is not templated on width: rmsnorm's width is pinned to +// match the fused rmsnorm_quant_fp8, and rmsnorm_p has no fused counterpart, so it uses kThreads. extern "C" int r4d_rmsnorm_p_bf16(long x, long y, int M, int n, float eps, int x_ld, int y_ld, long stream) { if (!x || !y) return -1; @@ -865,9 +667,8 @@ extern "C" int r4d_rmsnorm_p_bf16(long x, long y, int M, int n, float eps, return hipGetLastError() == hipSuccess ? 0 : -4; } -// `op` is 0 for a sum and 1 for a product. `b_ld` of 0 with the same n is the broadcast form: the -// caller passes a b_ld of zero and every row reads the same n elements. -// b_ld -1 is a ONE-ELEMENT b, the scalar broadcast; 0 is one row broadcast down the rows. +// `op` is 0 for a sum, 1 for a product. `b_ld` 0 broadcasts one row of n down the rows; -1 is a +// one-element b, broadcast as a scalar. extern "C" int r4d_binary_bf16(long a, long b, long y, int M, int n, int op, int a_ld, int b_ld, int y_ld, long stream) { if (!a || !b || !y) return -1; @@ -894,16 +695,16 @@ extern "C" int r4d_sigmoid_bf16(long x, long y, int M, int n, int x_ld, int y_ld } // ---------------------------------------------------------------------------- fill -// y[m, i] = v for every element of an [M, n] extent with a row pitch -- the op a rank issues where -// it has nothing to compute and a downstream reader (an all-reduce, a residual) still expects a -// defined buffer. A memset cannot do this: the wire may have a pitch and bf16 is two bytes. +// y[m, i] = v over an [M, n] extent with a row pitch, for a rank with nothing to compute whose +// downstream reader (an all-reduce, a residual) still needs a defined buffer. A memset cannot +// handle the pitch or a two-byte value. __global__ __launch_bounds__(kThreads) void fill_kernel(uint16_t* __restrict__ y, uint32_t n, uint32_t y_ld, uint16_t v) { uint16_t* __restrict__ yr = y + (size_t)blockIdx.x * y_ld; for (uint32_t i = threadIdx.x; i < n; i += kThreads) yr[i] = v; } -// The host form of r4d_common.h's f32_to_bf16 (which is __device__): the same round-to-nearest-even. +// Host form of r4d_common.h's f32_to_bf16 (which is __device__), round-to-nearest-even. static inline uint16_t f32_to_bf16_host(float f) { uint32_t u; std::memcpy(&u, &f, sizeof u); @@ -975,9 +776,8 @@ extern "C" int r4d_silu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y return hipGetLastError() == hipSuccess ? 0 : -4; } -// GELU-gated product, the gemma FFN activation. Same shape and order-lock as silu_mul (the gate -// is the first half of the fused [M, 2n] row); the only difference is the nonlinearity, which is -// the tanh approximation, not the erf one, to match ref_gelu_mul's act_gelu_tanh. +// GELU-gated product, the gemma FFN activation. Same shape and gate order as silu_mul; tanh GELU to +// match ref_gelu_mul's act_gelu_tanh. extern "C" int r4d_gelu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y_ld, long stream) { if (!gu || !y) return -1; if (M <= 0 || n <= 0) return -2; @@ -998,11 +798,9 @@ extern "C" int r4d_rope_bf16(long qkv, long pos, int M, int head_dim, int n_rope row_pitch, 0, nullptr, 0, 0, stream); } -// THE ONE LAUNCH OF rope_kernel. `yarn` with factor 0 is the plain rotary: the kernel's YaRN -// blend returns the frequency it was given and the magnitude is not applied, so the C entry points -// below and the op without YaRN run the same arithmetic with the same arguments. `den` is the -// ladder's width (`rot` for `rotary`, `head_dim` for `head`) -- the multi-component form passes -// the caller's, and the plain entry passes `rot`, as it always has. +// The single launch of rope_kernel. `yarn` with factor 0 is the plain rotary (the YaRN blend +// returns the frequency unchanged and no magnitude is applied). `den` is the ladder width (`rot` +// for `rotary`, `head_dim` for `head`); the plain entry passes `rot`. static int rope_launch(long qkv, long pos, int M, int head_dim, int n_rope_heads, int rot, int den, int gptj, float theta, float rscale, int row_pitch, int mode, const int* sec, int n_sec, int plane, RadYarn yarn, long stream, @@ -1041,14 +839,8 @@ extern "C" int r4d_kv_store_bf16(long k, long v, long slot, long kv, int M, int if (M <= 0 || head_dim <= 0 || kv_heads <= 0 || block_size <= 0 || n_blocks <= 0) return -2; if (!k_ld) k_ld = kv_heads * head_dim; if (!v_ld) v_ld = kv_heads * head_dim; - /* NO QUANTISATION-SIMULATION BRANCH ON THE SERVING PATH. The probe above is compiled only when - * its template parameters are set; this launch pins them off. A simulation that stays in the - * store path is four branches and a macro tree between every token and its cache, for a - * question that is answered once. - * - * The real fp8 cache is a separate entry point (r4d_kv_store_fp8, below) selected by - * --kv-cache-dtype, not a mode of this one. */ - hipLaunchKernelGGL((kv_store_kernel<0u, 0u, 0u, 8u>), dim3((uint32_t)M), dim3(kThreads), 0, + /* The fp8 cache is a separate entry point (r4d_kv_store_fp8), selected by --kv-cache-dtype. */ + hipLaunchKernelGGL(kv_store_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream, (const uint16_t*)k, (const uint16_t*)v, (const int32_t*)slot, (uint16_t*)kv, (uint32_t)head_dim, (uint32_t)kv_heads, @@ -1056,22 +848,21 @@ extern "C" int r4d_kv_store_bf16(long k, long v, long slot, long kv, int M, int return hipGetLastError() == hipSuccess ? 0 : -4; } -// bf16 k and v in, E4M3 cache out. `k_scale` and `v_scale` are what the READER will multiply back -// by -- they are the descale, so this divides -- and 1.0 is the vLLM default and the value the -// attention kernels assume when their descale pointers are null. +// bf16 k and v in, E4M3 cache out. `k_scale` and `v_scale` are the reader's descales, so this +// divides by them; 1.0 is the vLLM default and what the attention kernels assume when their +// descale pointers are null. static int kv_store_fp8_emit(long k, long v, long slot, long kv, int M, int head_dim, int kv_heads, int block_size, int n_blocks, int k_ld, int v_ld, float k_scale, float v_scale, - const R4dSink& sk) { + RadStream stream) { if (!k || !v || !slot || !kv) return -1; if (M <= 0 || head_dim <= 0 || kv_heads <= 0 || block_size <= 0 || n_blocks <= 0) return -2; - // Four columns a thread is the packing, so a head must be a whole number of groups; otherwise - // one group would straddle two heads and write the next head's first bytes. + // Four columns per thread, so a head must be whole groups or a group would straddle two heads. if (head_dim % 4) return -3; if (!(k_scale > 0.0f) || !(v_scale > 0.0f)) return -5; if (!k_ld) k_ld = kv_heads * head_dim; if (!v_ld) v_ld = kv_heads * head_dim; - return R4D_EMIT(sk, kv_store_fp8_kernel, dim3((uint32_t)M), dim3(kThreads), 0, + return R4D_EMIT(stream, kv_store_fp8_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (const uint16_t*)k, (const uint16_t*)v, (const int32_t*)slot, (uint8_t*)kv, (uint32_t)head_dim, (uint32_t)kv_heads, (uint32_t)block_size, (uint32_t)n_blocks, (uint32_t)k_ld, (uint32_t)v_ld, @@ -1081,29 +872,21 @@ static int kv_store_fp8_emit(long k, long v, long slot, long kv, int M, int head extern "C" int r4d_kv_store_fp8(long k, long v, long slot, long kv, int M, int head_dim, int kv_heads, int block_size, int n_blocks, int k_ld, int v_ld, float k_scale, float v_scale, long stream) { - R4dSink sk; sk.stream = (RadStream)(uintptr_t)stream; return kv_store_fp8_emit(k, v, slot, kv, M, head_dim, kv_heads, block_size, n_blocks, - k_ld, v_ld, k_scale, v_scale, sk); + k_ld, v_ld, k_scale, v_scale, (RadStream)(uintptr_t)stream); } // ================================================================================ logits_gemm // -// THE OUTPUT IS f32 AND THAT IS THE WHOLE REASON THIS KERNEL EXISTS. `logits_gemm` is the same -// arithmetic as r4d_gemm_bf16_nt_m16 under another parameter spelling, so dispatching it there -// looks correct -- but that kernel writes `__hip_bfloat16* C`, and the engine declares its logits -// buffer f32, because a bf16 logit has eight bits of mantissa and a nucleus cut is a comparison of -// neighbouring probabilities. The projection would write bf16 pairs into an f32 plane: every -// logit wrong, the magnitudes roughly right, and fluent nonsense out of the sampler. rad-kbench -// catches it as rel_l2 1.2 against the oracle, but only where it has a device domain to run in. +// The output is f32, which is why this kernel exists: `logits_gemm` is r4d_gemm_bf16_nt_m16's +// arithmetic, but that kernel writes bf16 and the engine's logits buffer is f32 (eight mantissa +// bits are too few for nucleus cuts between neighbouring probabilities). // -// One workgroup a vocabulary column, 256 threads striding K. At n_vocab 248320 and K 5120 that is -// a 2.5 GiB weight read a step and the read is the cost; the arithmetic is a v_dot2 per pair. It -// is not a tuned kernel and does not pretend to be -- there is one variant, it is correct, and the -// tuning axis is open. +// One workgroup per vocabulary column, 256 threads striding K. At n_vocab 248320 and K 5120 the +// 2.5 GiB weight read per step is the cost. Untuned: one correct variant. // -// Rows come in chunks of kLgRows so the accumulators stay in registers whatever M is. M here is -// one row per SAMPLED position -- `gather_rows` has already reduced a prefill chunk to one row a -// sequence -- so a chunk is almost always the whole of it. +// Rows are processed in chunks of kLgRows so accumulators stay in registers. M is one row per +// sampled position (`gather_rows` runs first), so one chunk usually covers it. namespace { @@ -1132,7 +915,7 @@ __global__ __launch_bounds__(kThreads) void logits_gemm_kernel( const uint16_t* __restrict__ ar = a + (size_t)(r0 + i) * a_ld + k; float s = 0.0f; #pragma unroll - for (uint32_t p = 0; p < kLgVec; ++p) s += bf2f(ar[p]) * bf2f(wv[p]); + for (uint32_t p = 0; p < kLgVec; ++p) s += bf16_to_f32(ar[p]) * bf16_to_f32(wv[p]); acc[i] += s; } } @@ -1174,24 +957,17 @@ extern "C" int r4d_logits_gemm_bf16(long a, long w, long c, int M, int K, int N, // ============================================================== the plugin ABI entry points // -// Unpacking RadArgs and re-deriving the row pitches IS this kernel's own business, so it lives -// here rather than in a translation layer an out-of-tree author cannot write. See -// libr4d/r4d_args.h. +// Unpacking RadArgs and deriving row pitches belongs to the kernel library (libr4d/r4d_args.h). +// The kernels take raw pointers and one pitch, so anything unpitched must be tight (spec 2.1). +// Before each launch an op checks: // -// WHAT THESE CHECK, and why here and not deeper in. The kernels take raw pointers and one -// pitch, so anything they do not pitch has to be tight -- the "necessary condition only" -// boundary of spec 2.1. Every op below therefore establishes, before the launch: -// -// * the dtype. These kernels are bf16 and read through a uint16_t; an f32 operand would be -// read as two bf16 halves and the output would be plausible garbage. The rows constrain -// `dtype`, but a constraint is a NECESSARY condition on the geometry and not a promise -// about the tensors, so the operand's own dtype is what is tested. -// * the row pitch. r4d_rows_pitch() gives it in elements, or -1 when an inner axis is -// strided, and -1 is RAD_E_STRIDE rather than a silently wrong walk. -// * the row count. It comes from the OPERAND and never from the `M` parameter: M is RANGED, -// so the value in the args is the band's upper bound and a loop bounded by it walks off -// the arena (libref/ref_ops.h makes the same point at more length). -/* bf16 is the only activation width these kernels read. Stated once. */ +// * the dtype, from the operand itself: a row's `dtype` constraint is a necessary condition on +// the geometry, not a promise about the tensors, and an f32 operand read as bf16 is garbage. +// * the row pitch: r4d_rows_pitch() returns elements, or -1 (RAD_E_STRIDE) for a strided inner +// axis. +// * the row count, from the operand, never the `M` parameter: M is ranged, so the args hold the +// band's upper bound (libref/ref_ops.h). +/* bf16 is the only activation width these kernels read. */ static inline int dt_bf16(const RadTensor* t) { return (t && t->dtype == RAD_BF16) ? RAD_OK : RAD_E_DTYPE; } @@ -1199,8 +975,7 @@ static inline int dt_i32(const RadTensor* t) { return (t && (t->dtype == RAD_I32 || t->dtype == RAD_U32)) ? RAD_OK : RAD_E_DTYPE; } -/* Opaque bytes. The tier traffic moves KV fragments whose contents are whatever the attention - * kernel wrote, so u8 is the dtype that describes them without claiming to interpret them. */ +/* Opaque bytes: KV tier traffic, whose contents are whatever the attention kernel wrote. */ static inline int dt_u8(const RadTensor* t) { return (t && (t->dtype == RAD_U8 || t->dtype == RAD_I8)) ? RAD_OK : RAD_E_DTYPE; } @@ -1211,7 +986,7 @@ static inline int dt_u8(const RadTensor* t) { enum { EL_TOK = 0, EL_WTE, EL_X }; -static int rad_embed_lookup_body(const RadArgs* a, const R4dSink& sk) { +extern "C" int r4d_rad_embed_lookup(const RadArgs* a, RadStream stream) { const RadTensor* tok = r4d_opt(a, EL_TOK); const RadTensor* wte = r4d_opt(a, EL_WTE); const RadTensor* x = r4d_opt(a, EL_X); @@ -1235,18 +1010,16 @@ static int rad_embed_lookup_body(const RadArgs* a, const R4dSink& sk) { const float mult = (float)r4d_getf(a, "mult", 1.0); return embed_lookup_bf16_emit(r4d_addr(tok), r4d_addr(wte), r4d_addr(x), (int)M, (int)n_embd, (int)n_vocab, (int)voff, (int)x_ld, - mult, sk) == 0 ? RAD_OK : RAD_E_DEVICE; + mult, stream) == 0 ? RAD_OK : RAD_E_DEVICE; } -R4D_ENTRY(r4d_rad_embed_lookup, rad_embed_lookup_body) /* ------------------------------------------------------------------ embed_lookup_q */ -/* Operand 4, `ahead`, is not read. It carries the ids of the prompt after this step for a host - * reader that fetches table rows from a file before they are wanted; a card reads its table where - * it already is, so there is nothing to fetch. */ +/* Operand 4, `ahead`, is not read: it carries upcoming prompt ids for a host reader that + * prefetches table rows from a file, and a card reads its table in place. */ enum { ELQ_TOK = 0, ELQ_WTE, ELQ_SCALE, ELQ_X }; -static int rad_embed_lookup_q_body(const RadArgs* a, const R4dSink& sk) { +extern "C" int r4d_rad_embed_lookup_q(const RadArgs* a, RadStream stream) { const RadTensor* tok = r4d_opt(a, ELQ_TOK); const RadTensor* wte = r4d_opt(a, ELQ_WTE); const RadTensor* sc = r4d_opt(a, ELQ_SCALE); @@ -1274,16 +1047,15 @@ static int rad_embed_lookup_q_body(const RadArgs* a, const R4dSink& sk) { return embed_lookup_q_emit((const int32_t*)r4d_addr(tok), (const void*)r4d_addr(wte), q, sc ? (const void*)r4d_addr(sc) : nullptr, sc && sc->dtype == RAD_F32, (uint16_t*)r4d_addr(x), M, - (int)n_embd, (int)n_vocab, (int)voff, x_ld, sk) == 0 + (int)n_embd, (int)n_vocab, (int)voff, x_ld, stream) == 0 ? RAD_OK : RAD_E_DEVICE; } -R4D_ENTRY(r4d_rad_embed_lookup_q, rad_embed_lookup_q_body) /* ------------------------------------------------------------------ gather_rows */ enum { GR_X = 0, GR_IDX, GR_Y }; -static int rad_gather_rows_body(const RadArgs* a, const R4dSink& sk) { +extern "C" int r4d_rad_gather_rows(const RadArgs* a, RadStream stream) { const RadTensor* x = r4d_opt(a, GR_X); const RadTensor* idx = r4d_opt(a, GR_IDX); const RadTensor* y = r4d_opt(a, GR_Y); @@ -1303,15 +1075,12 @@ static int rad_gather_rows_body(const RadArgs* a, const R4dSink& sk) { return gather_rows_bf16_emit(r4d_addr(x), r4d_addr(idx), r4d_addr(y), (int)M, (int)n, (int)src, (int)x_ld, (int)y_ld, - sk) == 0 ? RAD_OK : RAD_E_DEVICE; + stream) == 0 ? RAD_OK : RAD_E_DEVICE; } -R4D_ENTRY(r4d_rad_gather_rows, rad_gather_rows_body) - /* ------------------------------------------------------------------ byte rows */ -/* The u8 forms. `n` here is a COUNT OF BYTES, because at dtype u8 an element is a byte -- so the - * pitches r4d_rows_pitch returns are byte pitches and go straight through. */ -static int rad_gather_rows_u8_body(const RadArgs* a, const R4dSink& sk) { +/* The u8 forms. `n` is a byte count, so r4d_rows_pitch's pitches are byte pitches. */ +extern "C" int r4d_rad_gather_rows_u8(const RadArgs* a, RadStream stream) { const RadTensor* x = r4d_opt(a, GR_X); const RadTensor* idx = r4d_opt(a, GR_IDX); const RadTensor* y = r4d_opt(a, GR_Y); @@ -1331,15 +1100,13 @@ static int rad_gather_rows_u8_body(const RadArgs* a, const R4dSink& sk) { return gather_rows_u8_emit(r4d_addr(x), r4d_addr(idx), r4d_addr(y), (int)M, (int)n, (int)src, (int)x_ld, (int)y_ld, - sk) == 0 ? RAD_OK : RAD_E_DEVICE; + stream) == 0 ? RAD_OK : RAD_E_DEVICE; } -R4D_ENTRY(r4d_rad_gather_rows_u8, rad_gather_rows_u8_body) -/* The operand order is (v, idx, x) and x is INOUT: the destination is the pool and the rows this - * call does not name stay as they were. */ +/* Operands (v, idx, x), x inout: rows the call does not name are left unchanged. */ enum { SR_V = 0, SR_IDX, SR_X }; -static int rad_scatter_rows_u8_body(const RadArgs* a, const R4dSink& sk) { +extern "C" int r4d_rad_scatter_rows_u8(const RadArgs* a, RadStream stream) { const RadTensor* v = r4d_opt(a, SR_V); const RadTensor* idx = r4d_opt(a, SR_IDX); const RadTensor* x = r4d_opt(a, SR_X); @@ -1359,14 +1126,12 @@ static int rad_scatter_rows_u8_body(const RadArgs* a, const R4dSink& sk) { return scatter_rows_u8_emit(r4d_addr(v), r4d_addr(idx), r4d_addr(x), (int)M, (int)n, (int)dst, (int)v_ld, (int)x_ld, - sk) == 0 ? RAD_OK : RAD_E_DEVICE; + stream) == 0 ? RAD_OK : RAD_E_DEVICE; } -R4D_ENTRY(r4d_rad_scatter_rows_u8, rad_scatter_rows_u8_body) -/* THE SAME COPY, for rows a caller declared bf16: the kernel moves bytes, so a bf16 row of n is - * 2n bytes and nothing else about it changes. An encoder's rows over a language model's - * embeddings are the case -- both sides are activations, declared bf16. */ -static int rad_scatter_rows_bf16_body(const RadArgs* a, const R4dSink& sk) { +/* The same copy for rows declared bf16 (e.g. an encoder's rows over a language model's + * embeddings): a bf16 row of n is 2n bytes. */ +extern "C" int r4d_rad_scatter_rows_bf16(const RadArgs* a, RadStream stream) { const RadTensor* v = r4d_opt(a, SR_V); const RadTensor* idx = r4d_opt(a, SR_IDX); const RadTensor* x = r4d_opt(a, SR_X); @@ -1386,20 +1151,15 @@ static int rad_scatter_rows_bf16_body(const RadArgs* a, const R4dSink& sk) { return scatter_rows_u8_emit(r4d_addr(v), r4d_addr(idx), r4d_addr(x), (int)M, (int)(2 * n), (int)dst, (int)(2 * v_ld), (int)(2 * x_ld), - sk) == 0 ? RAD_OK : RAD_E_DEVICE; + stream) == 0 ? RAD_OK : RAD_E_DEVICE; } -R4D_ENTRY(r4d_rad_scatter_rows_bf16, rad_scatter_rows_bf16_body) /* ------------------------------------------------------------------ cast (bf16 -> bf16) */ -/* A STRIDED ROW COPY, which is what `cast` degenerates to when the two ends are the same dtype, - * and the reason there is a device row for it at all: an architecture that conditions a drafter on - * the trunk's INTERMEDIATE hidden states has to move rows out of the residual stream before the - * next layer overwrites it, and the only other implementation is ref's -- on the host, which the - * reference gate refuses in a serve. - * - * libr4d's 2D copy takes byte pitches, so a column slice of a wider buffer is expressible and no - * kernel has to learn about the layout: this is exactly how five taps land side by side in one - * [T, 5 * n_embd] row. */ +/* A strided row copy, which is what `cast` reduces to when both ends are the same dtype. A + * drafter conditioned on the trunk's intermediate hidden states must copy rows out of the residual + * stream before the next layer overwrites them, and ref's host implementation is refused in a + * serve. libr4d's 2D copy takes byte pitches, so taps can land side by side as column slices of + * one [T, 5 * n_embd] row. */ enum { CS_X = 0, CS_Y }; extern "C" int r4d_rad_cast(const RadArgs* a, RadStream s) { @@ -1415,9 +1175,8 @@ extern "C" int r4d_rad_cast(const RadArgs* a, RadStream s) { const long long y_ld = r4d_rows_pitch(y, n, &M); const long long x_ld = r4d_rows_pitch(x, n, &Mx); if (y_ld < 0 || x_ld < 0) return R4D_NO(RAD_E_STRIDE); - /* The ROW COUNT is the destination's. A tap writes a column slice of a buffer sized for the - * step's ceiling while the source is the live rows, so the two extents differ by design; what - * must hold is that the source has the rows the destination asks for. */ + /* The row count is the destination's: a tap's destination is sized for the step's ceiling + * while the source holds the live rows, so the source need only have at least as many. */ if (M <= 0 || Mx < M) return R4D_NO(RAD_E_SHAPE); return r4d_p2p_copy2d(r4d_addr(y), r4d_addr(x), y_ld * 2, x_ld * 2, n * 2, M, @@ -1435,8 +1194,8 @@ extern "C" int r4d_rad_rmsnorm(const RadArgs* a, RadStream s) { if (!x || !y) return R4D_NO(RAD_E_INVAL); R4D_NEED(dt_bf16(x)); R4D_NEED(dt_bf16(y)); - /* An ABSENT gain is one: a norm with no scale (Gemma 4's value norm, its multimodal - * embedder's pre-projection norm). `wadd` belongs to a gain and is refused without one. */ + /* An absent gain is one (Gemma 4's value norm, its multimodal embedder's pre-projection norm). + * `wadd` without a gain is refused. */ if (!w) { const long long n = r4d_geti_or(a, "n", r4d_dim(y, (int)y->rank - 1)); if (n <= 0) return R4D_NO(RAD_E_SHAPE); @@ -1452,11 +1211,8 @@ extern "C" int r4d_rad_rmsnorm(const RadArgs* a, RadStream s) { (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; } if (!r4d_contig(w)) return R4D_NO(RAD_E_STRIDE); - /* THE GAIN IS THE ONE OPERAND THAT IS NOT bf16. Every architecture plugin here declares its - * norm gains RAD_F32 -- a few thousand elements against gigabytes of weights, and the norm is - * where a rounded gain shows -- so the width is read off the operand and handed to the kernel - * rather than assumed. Assuming it would read an f32 gain as two bf16 halves of the wrong - * number, which is the silent kind of wrong. */ + /* The gain may be f32 (as plugins declare norm gains) or bf16; its width is read off the + * operand rather than assumed. */ if (w->dtype != RAD_F32 && w->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); const int w_f32 = w->dtype == RAD_F32; @@ -1520,10 +1276,8 @@ static int binary(const RadArgs* a, int mul, RadStream s) { if (y_ld < 0 || a_ld < 0) return R4D_NO(RAD_E_STRIDE); if (M <= 0 || Ma < M) return R4D_NO(RAD_E_SHAPE); - /* THE ONE BROADCAST RULE: an operand carrying exactly n elements against an output of M rows - * broadcasts along rows, and nothing else broadcasts at all. A pitch of 0 is how the kernel is - * told. Anything in between -- more than n, fewer than M*n -- is a shape bug and is refused - * rather than made plausible. */ + /* The one broadcast rule: exactly n elements against M rows broadcasts along rows (pitch 0). + * Anything between n and M*n is a shape bug and is refused. */ long long b_ld = 0; if (r4d_numel(B) == n && M > 1) { if (!r4d_contig(B)) return R4D_NO(RAD_E_STRIDE); @@ -1544,7 +1298,7 @@ extern "C" int r4d_rad_add(const RadArgs* a, RadStream s) { return binary(a, 0, extern "C" int r4d_rad_mul(const RadArgs* a, RadStream s) { return binary(a, 1, s); } /* mul_weight: y = x * w, `w` a bf16 weight of one element (pitch -1, a scalar) or one row (pitch - * 0, broadcast down the rows) -- the binary kernel's two broadcast forms. */ + * 0, broadcast down the rows). */ extern "C" int r4d_rad_mul_weight(const RadArgs* a, RadStream s) { const RadTensor* X = r4d_opt(a, 0); const RadTensor* W = r4d_opt(a, 1); @@ -1578,10 +1332,8 @@ extern "C" int r4d_rad_sigmoid(const RadArgs* a, RadStream s) { R4D_NEED(dt_bf16(x)); R4D_NEED(dt_bf16(y)); - /* ROW-WISE, WITH A PITCH, because the input is usually a COLUMN SLICE. A gated attention block - * issues this against the second half of each head of an interleaved [tokens, heads, - * 2*head_dim] projection: `n` wide inside a stride of 2n, with no contiguous extent anywhere. - * Treating it as a flat elementwise op refused it outright. */ + /* Row-wise with a pitch: the input is usually a column slice (the gate half of an interleaved + * [tokens, heads, 2*head_dim] projection, `n` wide inside a stride of 2n). */ const long long n = r4d_geti_or(a, "n", r4d_dim(y, (int)y->rank - 1)); if (n <= 0) return R4D_NO(RAD_E_SHAPE); long long M = 0, My = 0; @@ -1617,21 +1369,17 @@ extern "C" int r4d_rad_logit_softcap(const RadArgs* a, RadStream s) { const RadTensor* x = r4d_opt(a, 0); const RadTensor* y = r4d_opt(a, 1); if (!x || !y) return R4D_NO(RAD_E_INVAL); - /* Two legs, one op: bf16 (the logits buffer as the gemm writes it on the bf16 chain) and f32 - * (the 1.3.0 sampling chain, where the gemm hands the sampler f32 rows). The dtype check - * moved from the entry to the call below because the legs differ, not the geometry. */ + /* Two legs: bf16 logits, or f32 logits as the gemm hands the sampler. */ const bool leg_bf16 = (x->dtype == RAD_BF16) && (y->dtype == RAD_BF16); const bool leg_f32 = (x->dtype == RAD_F32) && (y->dtype == RAD_F32); if (!leg_bf16 && !leg_f32) return R4D_NO(RAD_E_DTYPE); - /* `cap` is where the model lives: Gemma 4 issues it at 30.0. The default exists for the same - * reason every other one here does (a direct call with no declare in front), and the `> 0` - * test is load-bearing: a zero cap is a division by zero in every lane, not a bad answer. */ + /* Gemma 4 issues cap 30.0; the default serves direct calls. A zero cap would divide by zero + * in every lane. */ const float cap = (float)r4d_getf(a, "cap", 30.0); if (!(cap > 0.0f)) return R4D_NO(RAD_E_INVAL); - /* ROW-WISE WITH A PITCH, same as sigmoid: issued against a column slice there is no contiguous - * extent to walk, and the contiguous case costs nothing. */ + /* Row-wise with a pitch, as sigmoid. */ const long long n = r4d_geti_or(a, "n", r4d_dim(y, (int)y->rank - 1)); if (n <= 0) return R4D_NO(RAD_E_SHAPE); long long M = 0, My = 0; @@ -1658,16 +1406,12 @@ extern "C" int r4d_rad_scale(const RadArgs* a, RadStream s) { R4D_NEED(dt_bf16(x)); R4D_NEED(dt_bf16(y)); - /* `s` is a [1] weight, f32 or bf16 (the layer_scalar weight is bf16 in the checkpoint). A - * scalar with no element is a shape error, not a broadcast of zero -- a zero scalar would be - * a plausible number, which is the thing the oracle rules out. Read on the device (the kernel - * reads s[0] once per block) rather than a host copy: a device-to-host copy of one element is - * a synchronisation on the step path, and the per-block read is cached. */ + /* `s` is a [1] weight, f32 or bf16. An empty scalar is a shape error, not a zero. It is read + * on the device, once per block, to avoid a device-to-host sync on the step path. */ if (sc->dtype != RAD_F32 && sc->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); if (r4d_numel(sc) < 1) return R4D_NO(RAD_E_SHAPE); - /* ROW-WISE WITH A PITCH, same as sigmoid: issued against the residual stream at the end of a - * layer there is no contiguous extent to walk, and the contiguous case costs nothing. */ + /* Row-wise with a pitch, as sigmoid. */ const long long n = r4d_geti_or(a, "n", r4d_dim(y, (int)y->rank - 1)); if (n <= 0) return R4D_NO(RAD_E_SHAPE); long long M = 0, My = 0; @@ -1743,25 +1487,22 @@ extern "C" int r4d_rad_rope(const RadArgs* a, RadStream s) { if (head_dim <= 0 || n_head <= 0) return R4D_NO(RAD_E_SHAPE); if (rot <= 0 || rot > head_dim || (rot & 1)) return R4D_NO(RAD_E_SHAPE); - /* `ladder`: `rotary` (default) measures the base ladder in `rot`; `head` in `head_dim`, the - * proportional variant. head_dim is already validated above, so `den = head_dim` is safe. */ + /* `ladder`: `rotary` (default) measures the base ladder in `rot`; `head` in `head_dim` (the + * proportional variant). */ const char* lad = r4d_gets(a, "ladder"); long long den = rot; if (lad) { if (!std::strcmp(lad, "head")) den = head_dim; - else if (std::strcmp(lad, "rotary") && std::strcmp(lad, "head")) - return R4D_NO(RAD_E_UNSUPPORTED); + else if (std::strcmp(lad, "rotary")) return R4D_NO(RAD_E_UNSUPPORTED); } - /* `head` is HF's proportional RoPE: the rotation spans the WHOLE head (rotate_half over - * head_dim, so pair i is (i, i + head_dim/2)) and only the first rotary_dim/2 frequencies are - * non-zero. Rotating the first rotary_dim dims as a rotary of their own pairs (i, i + rot/2) - * instead -- Gemma 4's global layers, 128 of 512 -- turns the wrong channels, and long-range - * attention degrades with distance. */ + /* `head` is HF's proportional RoPE: the rotation spans the whole head (pair i is + * (i, i + head_dim/2)) and only the first rotary_dim/2 frequencies are non-zero. Pairing + * (i, i + rot/2) instead turns the wrong channels (Gemma 4's global layers, 128 of 512) and + * degrades long-range attention. */ - /* THE MODE, and with it how many components a position has. With [M] positions -- one - * component a token -- mrope and imrope ARE neox: every frequency reads the same position and - * the ladder is the same. With [C, M] positions and `sections`, each frequency reads the - * component its section names (docs/OPS.md, `rope`). */ + /* The mode sets how many components a position has. With [M] positions, mrope and imrope are + * neox. With [C, M] positions and `sections`, each frequency reads its section's component + * (docs/OPS.md, `rope`). */ const char* mode = r4d_gets(a, "mode"); int gptj = 0, mc = 0; if (mode) { @@ -1803,10 +1544,9 @@ extern "C" int r4d_rad_rope(const RadArgs* a, RadStream s) { const float rscale = (float)r4d_getf(a, "scale", 1.0); const RadYarn yarn = rad_yarn_args(a); if (!rad_yarn_valid(yarn)) return R4D_NO(RAD_E_INVAL); - /* YaRN over the axial vision rotary, or over a linear position divide, is no model's. */ + /* No model uses YaRN with the axial vision rotary or a linear position divide. */ if (yarn.factor != 0.0f && (mc == 4 || rscale != 1.0f)) return R4D_NO(RAD_E_UNSUPPORTED); - /* The Q heads and the K heads rotate; the V heads that follow them do not, which is the whole - * reason this op takes the fused projection rather than two tensors. */ + /* The Q and K heads rotate; the trailing V heads do not. */ long long rot_l = rot, nfreq = rot / 2; if (den == head_dim && rot < head_dim && !multi && !gptj && mc == 0) rot_l = head_dim; return rope_launch(r4d_addr(qkv), r4d_addr(pos), (int)Mp, (int)head_dim, @@ -1821,9 +1561,8 @@ extern "C" int r4d_rad_rope(const RadArgs* a, RadStream s) { enum { KS_K = 0, KS_V, KS_SLOT, KS_CACHE }; -/* The geometry both stores share. The ONLY difference between them is the cache's dtype and what - * the kernel does with a value on the way in, so everything up to the launch is one function -- - * two copies of a paged-layout check is how the two drift into disagreeing about the layout. */ +/* Geometry shared by both stores, which differ only in the cache dtype, so the paged-layout check + * exists once. */ struct KvStoreGeom { const RadTensor *k, *v, *sm, *kv; long long head_dim, block_size, kv_heads, n_blocks, k_ld, v_ld, T; @@ -1844,9 +1583,8 @@ static int kv_store_geom(const RadArgs* a, KvStoreGeom* g) { g->block_size = r4d_geti_or(a, "block_size", 0); g->kv_heads = r4d_geti_or(a, "n_head_kv", g->kv->rank == 4 ? g->kv->shape[1] : 0); if (g->head_dim <= 0 || g->block_size <= 0 || g->kv_heads <= 0) return R4D_NO(RAD_E_SHAPE); - /* The paged layout is [n_blocks, kv_heads, block_size, 2*head_dim] and every kernel in this - * project shares it. A cache that disagrees is refused rather than walked with the parameters' - * idea of the shape. */ + /* The shared paged layout is [n_blocks, kv_heads, block_size, 2*head_dim]; refuse a cache that + * disagrees. */ if (g->kv->rank != 4) return R4D_NO(RAD_E_SHAPE); if (g->kv->shape[1] != g->kv_heads || g->kv->shape[2] != g->block_size || g->kv->shape[3] != 2 * g->head_dim) return R4D_NO(RAD_E_SHAPE); @@ -1874,16 +1612,15 @@ extern "C" int r4d_rad_kv_store(const RadArgs* a, RadStream s) { (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; } -/* The E4M3 twin. `k_scale` and `v_scale` are the DESCALES the attention side multiplies back by -- - * one number per (sequence, head) there, so a constant here -- and 1.0 is both vLLM's default and - * what the fp8kv kernels assume when their descale operands are absent. */ -static int rad_kv_store_fp8_body(const RadArgs* a, const R4dSink& sk) { +/* The E4M3 store. `k_scale` and `v_scale` are the attention side's descales (one per sequence and + * head there, a constant here); 1.0 is vLLM's default and the fp8kv kernels' assumption when the + * descale operands are absent. */ +extern "C" int r4d_rad_kv_store_fp8(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) return R4D_NO(RAD_E_DTYPE); - /* Four columns a thread is the packing the kernel uses, so a head must be a whole number of - * groups; otherwise one group straddles two heads and writes the next head's first bytes. */ + /* Four columns per thread, so a head must be whole groups. */ if (g.head_dim % 4) return R4D_NO(RAD_E_SHAPE); const double ks = r4d_getf(a, "k_scale", 1.0); @@ -1893,24 +1630,14 @@ static int rad_kv_store_fp8_body(const RadArgs* a, const R4dSink& sk) { return kv_store_fp8_emit(r4d_addr(g.k), r4d_addr(g.v), r4d_addr(g.sm), r4d_addr(g.kv), (int)g.T, (int)g.head_dim, (int)g.kv_heads, (int)g.block_size, (int)g.n_blocks, (int)g.k_ld, (int)g.v_ld, - (float)ks, (float)vs, sk) == 0 ? RAD_OK : RAD_E_DEVICE; + (float)ks, (float)vs, stream) == 0 ? RAD_OK : RAD_E_DEVICE; } -R4D_ENTRY(r4d_rad_kv_store_fp8, rad_kv_store_fp8_body) /* ------------------------------------------------------------------ logits_gemm * - * ITS OWN KERNEL, AND THE OUTPUT DTYPE IS WHY. `logits_gemm` is `gemm_nt`'s arithmetic under the - * vocabulary edge's parameter spelling -- `n_vocab` and `n_embd` where gemm_nt says N and K -- so - * the skinny bf16 GEMM looks like the right target for it. That GEMM writes bf16. The engine - * declares its logits buffer f32, because a bf16 logit has eight bits of mantissa and a nucleus - * cut is a comparison of neighbouring probabilities, so that dispatch writes bf16 pairs into an - * f32 plane: every logit wrong, the magnitudes roughly right, fluent nonsense out of the sampler. - * - * M is one row per SAMPLED position, not per token: `gather_rows` runs first and reduces a prefill - * chunk to one row a sequence. At max_tok 8192 against a 248K vocabulary the ungathered logits - * buffer alone would be 8 GiB, which is what that op is for. - * - */ + * gemm_nt's arithmetic with `n_vocab`/`n_embd` for N/K, but writing f32 (see the kernel above). + * M is one row per sampled position: `gather_rows` runs first, since ungathered logits at + * max_tok 8192 and a 248K vocabulary would be 8 GiB. */ enum { LG_X = 0, LG_W, LG_Y }; @@ -1921,8 +1648,7 @@ extern "C" int r4d_rad_logits_gemm(const RadArgs* a, RadStream s) { if (!x || !w || !y) return R4D_NO(RAD_E_INVAL); R4D_NEED(dt_bf16(x)); R4D_NEED(dt_bf16(w)); - /* f32, and checked rather than assumed: the bf16 GEMM this op resembles writes bf16 into - * exactly this buffer. See the note above. */ + /* f32 output, checked. */ if (y->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); if (!r4d_contig(w)) return R4D_NO(RAD_E_STRIDE); diff --git a/libr4d/r4d_moe.hip b/libr4d/r4d_moe.hip index 384c9d1f..f23e0819 100644 --- a/libr4d/r4d_moe.hip +++ b/libr4d/r4d_moe.hip @@ -1,57 +1,42 @@ // R4D mixture of experts: the router, the scatter/gather pair, and the grouped block-scaled FP8 -// GEMM. One translation unit, because the four are one graph and three of them exist only to feed -// the fourth. +// GEMM, in one translation unit because the first three exist to feed the GEMM. // -// ---- WHAT THE GEMM IS SHAPED BY --------------------------------------------------------------- +// ---- GEMM shape --------------------------------------------------------------- // -// Qwen3.6-35B-A3B: 256 experts, 8 of them per token, 512 columns of intermediate each. So a decode -// step at eight requests routes 64 (token, slot) rows across up to 64 distinct experts, and reads -// ONE expert's gate_up [1024, 2048] plus its down [2048, 512] for each -- 3 MB an expert, 24 MB a -// layer, and that read IS the step. A grouped GEMM on this model is a bandwidth problem wearing a -// matmul's clothes, and everything below follows from that: +// Qwen3.6-35B-A3B: 256 experts, 8 per token, 512 intermediate columns each. A decode step at eight +// requests routes 64 (token, slot) rows across up to 64 experts and reads each one's gate_up +// [1024, 2048] and down [2048, 512] (3 MB an expert, 24 MB a layer). The grouped GEMM is +// bandwidth-bound, which shapes everything below: // -// * A BLOCK OWNS A CONTIGUOUS RANGE OF SORTED ROWS AND LOOPS OVER THE EXPERTS IN IT. No block -// map, no padded sort. The cost of a block that straddles two experts is that it stages two -// weight tiles instead of one, and the number of (block, expert) incidences -- which is what -// the weight traffic is proportional to -- is at most `n_expert + T/FM`. At prefill that is -// 384 against an optimum of 256, at decode it is within one of the number of distinct experts. +// * A block owns a contiguous range of sorted rows and loops over the experts in it; no padded +// sort. A block straddling two experts stages two weight tiles, so weight traffic scales with +// (block, expert) incidences, at most `n_expert + T/FM`. // -// AT PREFILL A BLOCK MAP IS BUILT ALL THE SAME. See the AL note beside moe_blockmap_kernel: -// at the shipped 2048 chunk the uniform grid is 414 incidences against 254, and a duplicate -// staging of a POOLED expert is another pass of its shard over PCIe rather than an L2 hit. One -// run a block removes every straddle. It is worth 3.6% of prefill end to end, bit-identical -- -// less than the incidence count suggests, because most duplicate stagings are served from -// cache, so a straddle never costs the full link price of its bytes. +// At prefill a block map gives one run per block anyway (see the AL note beside +// moe_blockmap_kernel): at a 2048 chunk the uniform grid has 414 incidences against 254, and a +// duplicate staging of a pooled expert is another pass over PCIe. Worth 3.6% of prefill, +// bit-identical. At decode the (tile, run) grid already gives one run per block. // -// At DECODE the map is not built: the (tile, run) grid already gives one run a block, and the -// incidence count is within one of the number of distinct experts. +// * FM is banded: decode runs are a row or two and get 16-row tiles, one run per block; prefill +// runs are tens of rows and get 32-row tiles, a wave skipping the 16-row M tiles its run does +// not reach. See r4d_moe_decode_band and the kernel's prefill-tile note. // -// * FM IS BANDED. A decode step's runs are a row or two, so it gets 16-row tiles spread one run a -// block; a prefill chunk's are tens of rows, so it gets 32-row tiles one run a block, and a wave -// skips the 16-row M tiles its run does not reach. See r4d_moe_decode_band for the crossover and -// the kernel's prefill-tile note for why 32. +// * Within a 16-row tile dead rows are masked, not skipped: free on a weight-bound kernel, and it +// keeps the K loop and its barriers wave-uniform. // -// * WITHIN A 16-ROW TILE, DEAD ROWS ARE MASKED, NOT SKIPPED. A run of one row still runs a -// 16-row WMMA tile. On a kernel whose wall is the weight stream that is free, and it keeps the -// K loop and its barriers wave-uniform, which a dynamic tile range would not. +// ---- the weight is a pointer table -------------------------------------------------------- // -// ---- WHY THE WEIGHT IS A POINTER TABLE -------------------------------------------------------- +// `Wtab[e]`, not `W + e * stride`: a layer's experts are separate movement units (spec §4.2) that +// may sit in VRAM, behind the link or on disk, so no stride describes them (RAD_OPK_WTAB, +// abi/rad_runtime.h). The stacked rank-3 [n_expert, N, K] form is accepted too, for callers with +// no engine (rad-kbench fixtures); a zero leading stride distinguishes the table. // -// `Wtab[e]` and not `W + e * stride`. A layer's experts are separate movement units (spec §4.1): -// after placement one is in VRAM, the next is streamed over the link and the third is still on -// disk, so there is no stride that describes them. RAD_OPK_WTAB is how the core says that; see -// abi/rad_runtime.h. The STACKED form -- an ordinary rank-3 [n_expert, N, K] tensor -- is accepted -// too, because a caller with no engine behind it (rad-kbench replaying a fixture) has nowhere to -// put a pointer array, and the two are told apart by the leading stride being zero. +// ---- determinism ------------------------------------------------------------------------------ // -// ---- DETERMINISM ------------------------------------------------------------------------------ -// -// The scatter is a STABLE counting sort and it is stable without atomics ordering anything: a -// slot's position is `expert_offset[e] + blocks_before[b][e] + rank_within_block`, all three of -// which are computed by reduction rather than by whoever got there first. An atomic cursor would -// have been four lines and would have made `sorted_tok` -- and therefore every row of the grouped -// GEMM's output -- depend on the scheduler. This engine's reproducibility claims are byte-level -// (spec §17) and a non-deterministic sort forfeits all of them. +// The scatter is a stable counting sort with no atomic ordering: a slot's position is +// `expert_offset[e] + blocks_before[b][e] + rank_within_block`, all computed by reduction. An +// atomic cursor would make `sorted_tok`, and every row of the GEMM output, depend on scheduling, +// breaking the byte-level reproducibility of spec §17. #include "r4d.h" #include "r4d_common.h" #include "r4d_fp8_wmma.h" @@ -72,17 +57,14 @@ namespace { constexpr uint32_t kWave = 32; -/* THE EXPERT-COUNT CEILING, and it is a real limit of these kernels rather than a policy. - * Three of them size something by it: the router keeps a lane's own logits in registers - * (kMaxOwn below), and both scatter forms keep a histogram of n_expert + 1 counters in LDS. - * 512 is what Qwen3.8-Flash-Next asks for -- 512 experts of 640 at top-10 -- and it costs - * 4 KiB of LDS in the scatter and, in the router, a second instantiation rather than sixteen - * registers on every model. */ +/* Expert-count ceiling, a hard limit of these kernels: the router keeps a lane's logits in + * registers (MAXOWN) and both scatter forms keep n_expert + 1 counters in LDS. 512 covers + * Qwen3.8-Flash-Next (512 experts of 640, top-10) for 4 KiB of scatter LDS and a second router + * instantiation. */ constexpr uint32_t kMaxExpert = 512; constexpr uint32_t kBlock = 128; // the fp8 scale block, along K and along N -/* A RUN-MAP ENTRY THAT OWNS NO EXPERT: the rows above `off[n_expert]` are dropped slots whose - * output must be zeroed and which no run covers. Declared here because the GEMM reads it and the - * map that writes it is built further down, beside the launcher it belongs to. */ +/* Run-map entry that owns no expert: rows above `off[n_expert]` are dropped slots whose output must + * be zeroed. Declared here because the GEMM reads it; the map is built further down. */ constexpr uint32_t kMapTail = 0xffffffffu; constexpr uint32_t kFK = 128; // K bytes staged per pass; one scale block exactly @@ -102,52 +84,34 @@ using r4d_fp8::lds_pitch; #define R4D_MOE_CHK() do { hipError_t e_ = hipGetLastError(); \ if (e_ != hipSuccess) return -100 - (int)e_; } while (0) -/* An entry of a weight-table operand. `tab` is the pointer array when `stride0` is 0, and the - * base of a stacked plane otherwise. Resolved on the device rather than the host because the - * table lives in device memory -- reading it host-side would be a synchronisation a step cannot - * afford, and the mover may have rewritten it since the last one. */ +/* An entry of a weight-table operand: `tab` is the pointer array when `stride0` is 0, else the base + * of a stacked plane. Resolved on the device: the table is in device memory, the mover may rewrite + * it, and a host read would need a sync. */ __device__ __forceinline__ const uint8_t* wtab_at(const void* const* tab, size_t stride0, uint32_t e) { if (stride0 == 0) return (const uint8_t*)tab[e]; return (const uint8_t*)tab + (size_t)e * stride0; } -/* ONE SORTABLE INTEGER FOR (value, expert id), WHICH IS WHAT TAKES THE BRANCHES OUT OF THE - * SELECTION -- and it is free only because the logits are BF16. +/* One sortable u32 for (value, expert id), which removes the branches from the selection; possible + * because the logits are bf16. * - * The selection wants "largest value, ties to the lower id". Written as a comparison that is what - * it says -- `v > bv || (v == bv && id < bid)` over two registers -- and gfx12 compiles it, plus - * the `continue` that skips an already-chosen entry, into exec-mask branches: 40 s_and_saveexec, - * 80 s_cbranch_execz and 306 s_wait_alu in a 2137-instruction kernel that runs on ONE workgroup. - * On four waves of one CU there is nothing to hide any of that behind. + * The selection wants the largest value, ties to the lower id. As a two-register comparison gfx12 + * compiles it into exec-mask branches, and the kernel runs on one workgroup with nothing to hide + * them. Instead the order-preserving map of the bf16 (flip the sign bit if positive, invert all + * bits if negative; monotone including -inf) goes in the top half and `~id` in the low half, so a + * lower id wins ties. Selection is then an unsigned max, the wave reduction carries one register, + * and an entry is removed by zeroing its key. * - * A bf16 has sixteen bits, so the ORDER-PRESERVING map of the value fits in the top half of a - * u32 and the id fits under it. The map is the standard one -- flip the sign bit for a positive - * float, invert every bit for a negative -- and it is monotone across the whole range including - * -inf. `~id` in the low half makes a LOWER id compare HIGHER at equal value, which is the tie - * rule exactly. The selection is then `v_max_u32`, the wave reduction carries one register - * instead of two (half the ds_bpermute), and an entry is removed by setting its key to zero. + * Same answer as the comparison form, with two special cases handled: + * - -0.0 compares equal to +0.0 but has a different pattern, so it is folded to +0.0. + * - NaN never wins a float comparison, but a positive NaN's pattern sorts above +inf, so NaN gets + * key 0 (never selected; an all-NaN row takes the `nothing left` exit). * - * IT IS THE SAME ANSWER, and the two places it would not be are handled rather than assumed: + * Inverting the map returns the original bf16, so the softmax input is unchanged. * - * - NEGATIVE ZERO. -0.0 == +0.0 in float, so the comparison form breaks that tie on the id; as - * bit patterns they differ and the key would not. Folded to +0.0 when the key is built. - * - NaN. A NaN loses every float comparison, so the comparison form can never select one; a - * positive NaN's bit pattern sorts ABOVE +inf and the key would select it first. Given key - * zero, which is the same "never selected" and leaves the all-NaN row hitting the same - * `nothing left` exit. - * - * `bv` is recovered by inverting the map, which returns the ORIGINAL bf16 pattern and therefore - * the identical f32 -- the softmax that reads it is untouched. - * - * WHAT IT BUYS is not instruction count but the DEPENDENCY CHAIN. Against the two-register - * comparison the object is 2014 instructions and 78 basic blocks with 30 ds_bpermute and 214 - * s_wait_alu, where that form is 2137, 96, 40 and 306. This kernel runs on ONE workgroup at - * decode, so a chain with exec-mask branches in it is what it costs. - * - * DO NOT CHASE rad-kbench's 6.354e-05 ON THE M=512 ROUTER CASE. The selection there is exact - * (expert_ids rel_l2 0.000e+00); what differs by about one bf16 ulp is the WEIGHT, and it is not - * this key form's doing. Every case from M=1 to M=256, decode included, is exact. */ + * Note: rad-kbench's 6.354e-05 on the M=512 router case is a one-ulp difference in the weight, not + * the selection (expert_ids are exact); every case from M=1 to M=256 is exact. */ __device__ __forceinline__ uint32_t topk_key(uint16_t raw, uint32_t e) { const bool nan = ((raw & 0x7F80u) == 0x7F80u) && (raw & 0x7Fu); uint16_t u = (raw == 0x8000u) ? (uint16_t)0u : raw; /* -0.0 folds to +0.0 */ @@ -159,11 +123,9 @@ __device__ __forceinline__ uint16_t topk_key_raw(uint32_t key) { return (k & 0x8000u) ? (uint16_t)(k & 0x7FFFu) : (uint16_t)~k; } -/* THE SELECTION'S WAVE MINIMUM, ON THE DPP AND PERMLANE EXCHANGE r4d_xor_lane provides rather than - * `__shfl_xor`, which gfx1201 lowers to `ds_bpermute_b32`: an LDS round trip a stage. A row runs - * this top_k times, five stages each, and nothing else is in flight on the wave to cover it, so - * those round trips would be most of the selection. The minimum of unsigned integers has one answer - * whatever order the lanes combine in. */ +/* The selection's wave minimum, on r4d_xor_lane's DPP/permlane exchange rather than `__shfl_xor` + * (an LDS round trip per stage on gfx1201, run top_k times per row with nothing to hide it). An + * unsigned minimum is order-independent. */ __device__ __forceinline__ uint32_t wave_min_u32(uint32_t b) { uint32_t o; o = r4d_xor_lane_u32<16>(b); b = b < o ? b : o; @@ -179,34 +141,22 @@ __device__ __forceinline__ uint32_t wave_min_u32(uint32_t b) { * Softmax over all n_expert logits, then the top_k of them by value, then -- if `norm` -- the kept * weights renormalised to sum to one. * - * ONE WAVE A ROW, and the selection is k passes of a wave reduction rather than a sort. At - * n_expert 256 and top_k 8 that is 8 passes over 8 values a lane, which is less work than any sort - * and, more to the point, is EXACTLY the reference's selection: the largest remaining value, ties - * broken on the lower expert id. A partial sort with a different tie rule is a different router on - * exactly the rows where two experts score the same, and those rows are not rare in a trained - * model's tail. - * - * The selection runs on the LOGITS, not on the probabilities: softmax is monotone, so the order is - * identical and the comparison is exact rather than through an exp. libref says the same. */ -/* MAXOWN is how many of the row's logits ONE LANE holds, so n_expert <= MAXOWN * kWave. It is a - * template parameter and not a constant because those are REGISTERS: a 512-expert model needs 16 - * of them a lane and a 256-expert one needs 8, and paying the larger everywhere would cost - * occupancy on every model in the tree to serve one. Each entry is one u32 key -- see topk_key -- - * so MAXOWN is bounded by registers and by nothing else. */ -/* ONE ROW, ONE WAVE, AND NOTHING OUTSIDE THE WAVE. Every reduction below is a butterfly over the - * row's own 32 lanes and every store is addressed by `m`, so WHICH wave of WHICH workgroup - * runs a row cannot change its answer. That is what lets `router_topk_scatter_kernel` walk the - * same rows from a different grid and still be byte-identical -- it is the same code, not a copy - * of it, which is the only form of that claim that cannot drift. */ -/* WHERE A ROW ALSO HANDS ITS SLOTS TO THE SORT, when it runs inside the fused kernel: each slot's - * expert relative to the slice, or -1 when it went to another rank, into `e`. The standalone - * selection passes a null `e` and the branch folds away. */ -/* THE PROTECTED EXPERTS OF A SLICE, SORTED LAST. A layer may keep a few of its experts at a higher - * precision than the rest -- the ones whose output dwarfs the others' -- and one grouped GEMM takes - * one weight format. So the sort places those experts' runs after every other expert's, in the - * order listed, and two GEMMs serve the two segments: the regular experts are [0, n - p) and the - * protected ones [n - p, n) of the offsets. Local indices, strictly ascending; p <= kMaxProtect. - * With none listed the place of an expert is the expert, which is every layer without them. */ + * One wave per row; the selection is k passes of a wave reduction, not a sort. That matches the + * reference exactly (largest remaining value, ties to the lower id); a sort with another tie rule + * would be a different router on tied rows, which are not rare. Selection runs on the logits: + * softmax is monotone, so the order is the same and the comparison exact (as in libref). */ +/* MAXOWN is how many of a row's logits one lane holds (n_expert <= MAXOWN * kWave). It is a + * template parameter because they are registers: 16 per lane at 512 experts, 8 at 256. */ +/* One row per wave, with nothing outside the wave: reductions are butterflies over the row's 32 + * lanes and stores are addressed by `m`, so the grid shape cannot change the answer. That lets + * `router_topk_scatter_kernel` run this same code from a different grid, byte-identically. */ +/* In the fused kernel a row also hands its slots to the sort through `e`: each slot's expert + * relative to the slice, or -1 for another rank's. The standalone selection passes a null `e`. */ +/* Protected experts of a slice, sorted last. A layer may keep a few experts (those whose output + * dwarfs the rest) at higher precision, and one grouped GEMM takes one weight format, so the sort + * places their runs after all others, in the listed order, and two GEMMs serve [0, n - p) and + * [n - p, n) of the offsets. Local indices, strictly ascending; p <= kMaxProtect. With none, an + * expert's place is itself. */ constexpr uint32_t kMaxProtect = 8; struct Protect { uint32_t n; @@ -237,30 +187,18 @@ __device__ __forceinline__ void router_topk_row( SlotSink snk) { const uint16_t* row = lg + (size_t)m * lg_ld; - /* Up to MAXOWN experts a lane: n_expert <= MAXOWN * kWave is a launch precondition, checked - * on the host, which is also what picks the instantiation. + /* Up to MAXOWN experts per lane; n_expert <= MAXOWN * kWave is checked on the host, which also + * picks the instantiation. * - * THE TRIP COUNT IS MAXOWN AND NOT `n_own`, AND THAT IS THE WHOLE COST OF THIS KERNEL. - * - * `for (e = lane; e < n_expert; e += kWave) v[n_own++] = ...` makes `n_own` a value the - * compiler derives from `lane`, so every later `v[i]` is a register index it must assume is - * DIVERGENT -- and a divergent VGPR index on gfx12 is not an addressing mode, it is a - * waterfall: `v_movrels_b32` inside an exec-masked loop that re-runs for each distinct index - * in the wave. The top-k loop reads `v[i]` top_k * MAXOWN times, so written that way the kernel - * disassembles to four such loops and takes tens of microseconds to rank 512 numbers -- tens of - * thousands of cycles, on one wave, for about a kilobyte of input. - * - * Unrolled to the compile-time bound every index is a constant, the array stays in registers - * and there are no waterfalls. Slots past `n_expert` hold -INFINITY and start out marked in - * `taken`, which is what keeps the result BIT-IDENTICAL: fmaxf against -inf is the identity, - * __expf(-inf - mx) is exactly zero and lands at the tail of the same ascending sum, and the - * selection loop skips a marked slot exactly as it skips a chosen one. At this model's 512 - * experts every lane owns all 16 anyway, so nothing is even masked. */ - /* ALL MAXOWN LOADS ARE ISSUED BEFORE ANY IS WAITED ON. Guarded as `if (ok) raw = row[e]`, each - * load sits in its own exec-masked branch with its use straight after it, so the compiler - * waits for every one before issuing the next: MAXOWN dependent round trips to L2, most of a - * row's time. So a slot past `n_expert` reads the row's first logit instead -- always in - * bounds -- and the select below discards it. */ + * The trip count is MAXOWN, not a lane-derived `n_own`: a lane-derived count makes every later + * `v[i]` a divergent register index, which gfx12 implements as a v_movrels waterfall loop, + * costing tens of microseconds to rank 512 numbers. Unrolled to the constant bound, the array + * stays in registers. Slots past `n_expert` hold -INFINITY with key 0, which keeps the result + * bit-identical: fmaxf ignores -inf, __expf(-inf - mx) is exactly zero, and the selection + * never picks key 0 while a real entry remains. */ + /* All MAXOWN loads issue before any is waited on. A guarded `if (ok) raw = row[e]` would put + * each load in its own exec-masked branch and serialise the round trips, so a slot past + * `n_expert` reads the row's first logit (always in bounds) and the select discards it. */ uint16_t raw[MAXOWN]; #pragma unroll for (uint32_t i = 0; i < MAXOWN; ++i) { @@ -292,27 +230,21 @@ __device__ __forceinline__ void router_topk_row( sum = r4d_wave_sum(sum); const float inv = sum > 0.0f ? 1.0f / sum : 0.0f; - /* ---- THE SELECTION LEAVES IN A REGISTER, NOT THROUGH DEVICE MEMORY AND BACK. + /* ---- the selection stays in registers. * - * The reference stores each selected probability as bf16 and, if `norm`, scales the STORED - * value -- so that round trip is part of the answer. Done literally it is top_k scalar stores, - * top_k dependent loads and top_k more stores on one lane of one wave, and on a decode step - * this kernel is one workgroup, so that chain would be its whole cost. Round r parks its - * winner on LANE r instead, which needs top_k <= kWave; both launchers refuse more. + * The reference stores each selected probability as bf16 and, with `norm`, rescales the stored + * value. Doing that literally would chain top_k stores and dependent loads on one lane. Instead + * round r parks its winner on lane r (top_k <= kWave; both launchers refuse more). * - * ROUND r TAKES THE LARGEST KEY BELOW ROUND r-1's, rather than zeroing the last winner and - * taking the largest one left. Keys are unique -- the low half is ~id -- so the two are the - * same sequence, but zeroing is a compare and a select on every entry, each waiting on the - * one condition register, top_k times over. "Below" is one subtraction instead: with P the - * last winner minus one, P - key is at most P for every key not above P and wraps past P for - * every key already taken, so the smallest P - key names the largest key not yet taken. An - * absent or NaN entry (key 0) gives P itself, so it is chosen only once nothing real is left, - * and that is the `nothing left` exit. + * Round r takes the largest key below round r-1's, which equals zeroing the last winner (keys + * are unique) but costs one subtraction: with P the last winner minus one, P - key is at most P + * for keys not above P and wraps past P for taken keys, so the smallest P - key names the + * largest untaken key. Key 0 (absent or NaN) yields P itself and is chosen only when nothing + * real is left, the `nothing left` exit. * - * THE PROBABILITIES ARE WORKED OUT AFTER THE LOOP, each on the lane its winner is parked on, - * from the same expression on the same inputs, so the same bits. `wsum` then adds them in - * round order, the order the reference adds them in, and the renormalisation reads the bf16 - * that was produced, not the f32 behind it, as the reference does. */ + * Probabilities are computed after the loop on each winner's lane with the same expression, so + * the same bits. `wsum` adds them in round order, as the reference does, and the + * renormalisation reads the produced bf16, not the f32 behind it. */ uint32_t P = 0xFFFFFFFFu; /* round 0 may take any key */ uint32_t mykey = 0u; uint32_t nsel = 0; @@ -360,38 +292,28 @@ __global__ __launch_bounds__(NW * kWave) void router_topk_kernel( /* ================================================================== moe_scatter * - * The small form: one workgroup does the whole sort. T <= kScatterSmall, which covers every decode - * and verify step (a verify step at eight sequences and depth 3 is 32 rows at top_k 10, T = 320), - * and it is one launch against the three the general form needs. The histogram is in LDS, the - * offsets are an exclusive prefix over the n_expert <= kMaxExpert counts, and each slot finds its - * own place from its rank inside its expert's run. + * The small form: one workgroup does the whole sort, for T <= kScatterSmall, which covers every + * decode and verify step (eight sequences at depth 3 and top_k 10 is T = 320), in one launch + * instead of three. Histogram in LDS, offsets an exclusive prefix over n_expert <= kMaxExpert + * counts, and each slot placed by its rank inside its expert's run. * - * ON ONE WORKGROUP THE COST IS THE CRITICAL PATH, NOT THE WORK, and it goes to barriers and to - * serial chains of LDS round trips. Phase by phase, a Hillis-Steele scan costs 0.72 us (sixteen - * barriers), prefixing a per-wave cursor table 0.45 us, and placing with one lane a wave walking - * its chunk of 40 slots -- each step an LDS read, a read-modify-write of its cursor and a store -- - * 2.24 us at T = 320. So: + * On one workgroup the critical path (barriers, serial LDS chains) is the cost, not the work: * - * - THE PREFIX is a DPP scan inside each wave and one exchange of the wave totals through LDS: - * a barrier a tile of 32 counts a wave, and n_expert <= 512 is at most two tiles at eight - * waves and one at sixteen or more. - * - THE PLACEMENT GROUPS FIRST AND ORDERS AFTER. The histogram's atomic hands each slot a ticket - * inside its expert's run; tickets come in arrival order, so the slots are first gathered - * into their runs in that order, and then each slot's place in the run is the number of the - * run's slots with a lower index. That count is as long as the run -- at most one slot a row, - * since a row picks an expert once -- where counting over every earlier slot is T/4 LDS - * reads long and slower than the walk. + * - The prefix is a DPP scan inside each wave plus one exchange of wave totals through LDS: one + * barrier per tile of 32 counts per wave (at most two tiles at eight waves for 512 experts). + * - Placement groups first and orders after. The histogram atomic hands each slot a ticket in its + * expert's run (arrival order); slots are gathered into runs in ticket order, then each slot's + * place is the number of the run's slots with a lower index. That count is as long as the run + * (a row picks an expert at most once), far shorter than counting all earlier slots. * - * STABLE AND BYTE-IDENTICAL: the place in the run is the position among the same expert's slots - * in ascending i, which is the order the reference produces, whatever order the tickets were - * handed out in; and an exclusive prefix of non-negative integers - * has one answer. Every barrier here orders LDS alone, so none of them waits on or invalidates - * anything in the vector memory path. */ + * Stable and byte-identical: a slot's place is its position among the same expert's slots in + * ascending i, as in the reference, whatever the ticket order. Every barrier orders LDS only, so + * none waits on or invalidates the vector memory path. */ constexpr uint32_t kScatterSmall = 1024; constexpr uint32_t kScatWaves = 8; /* the standalone sort: 256 threads */ -/* THE SMALL SORT'S LDS, NAMED ONCE so the standalone kernel and the fused one cannot declare it - * differently. About 16 KiB. NW is the workgroup's wave count, which sizes the scan's exchange. */ +/* The small sort's LDS (about 16 KiB), defined once for the standalone and fused kernels. NW is the + * workgroup's wave count, which sizes the scan's exchange. */ template struct ScatterLds { static constexpr uint32_t kTiles = (kMaxExpert + NW * kWave - 1) / (NW * kWave); @@ -403,9 +325,9 @@ struct ScatterLds { int32_t wt[kTiles][NW]; /* each wave's total, a slot per tile */ }; -/* INCLUSIVE PREFIX SUM OVER A WAVE32, on the DPP row shifts: four steps inside each row of - * sixteen, then the upper row adds the lower row's total. A lane shifted in from outside its row - * reads zero (bound_ctrl), which is what a prefix sum wants there. */ +/* Inclusive prefix sum over a wave32 with DPP row shifts: four steps within each 16-lane row, then + * the upper row adds the lower row's total. Lanes shifted in from outside the row read zero + * (bound_ctrl). */ __device__ __forceinline__ int32_t wave_incl_scan_i32(int32_t x, uint32_t lane) { x += __builtin_amdgcn_update_dpp(0, x, 0x111, 0xF, 0xF, true); /* row_shr:1 */ x += __builtin_amdgcn_update_dpp(0, x, 0x112, 0xF, 0xF, true); /* row_shr:2 */ @@ -416,9 +338,8 @@ __device__ __forceinline__ int32_t wave_incl_scan_i32(int32_t x, uint32_t lane) } /* The sort, from a filled slot list on: histogram, offsets and counts, placement. The caller has - * written `sl.e[0, T)` and zeroed `sl.cnt[0, n_expert)`, and a barrier has passed since. Extracted - * so the standalone sort and the fused kernel run THIS code and not a transcription of it. The - * workgroup is exactly NW waves. */ + * written `sl.e[0, T)` and zeroed `sl.cnt[0, n_expert)`, followed by a barrier. Shared by the + * standalone sort and the fused kernel. The workgroup is exactly NW waves. */ template __device__ __forceinline__ void scatter_small_place( int32_t* __restrict__ sorted, int32_t* __restrict__ off, int32_t* __restrict__ cnt, @@ -431,8 +352,8 @@ __device__ __forceinline__ void scatter_small_place( } lds_barrier(); - /* Every thread sums all NW wave totals, so `carry` -- and at the end the number of live - * slots -- is the same in every thread without another read. */ + /* Every thread sums all NW wave totals, so `carry` (finally the live slot count) is the same + * in every thread. */ int32_t carry = 0; for (uint32_t b = 0, t = 0; b < n_expert; b += NW * kWave, ++t) { const uint32_t e = b + tid; @@ -490,40 +411,26 @@ __global__ __launch_bounds__(kScatWaves * kWave) void scatter_small_kernel( /* ================================================================== router_topk + moe_scatter * - * ONE LAUNCH FOR THE PAIR, and the pair is worth fusing because NEITHER HALF IS WORK. At the - * decode shape each is a single 256-thread workgroup -- `router_topk` is a wave a row and four rows - * is one workgroup; the small sort is one workgroup by construction -- moving about a kilobyte, - * so each launch is its dispatch floor plus a critical path of barriers and round trips. With one - * of each per MoE layer per rank per step, a separate launch is a real share of the decode step. + * One launch for the pair: at decode each half is a single 256-thread workgroup moving about a + * kilobyte, so each launch is mostly dispatch floor and barriers, once per MoE layer per step. * - * THE SLOTS REACH THE SORT THROUGH LDS, NOT THROUGH `expert_ids`. Each row's lanes write their - * slot's expert (relative to the slice, or -1) into the sort's slot list as they finish, so the - * one barrier between the halves orders LDS only: the sort neither re-reads what the selection - * just stored nor waits for those stores to land. Nothing comes BEFORE the rows either -- the - * histogram is zeroed by each thread on its way in and counted after that barrier -- because a - * barrier at the top waits for the workgroup's last wave to be launched, about half a - * microsecond that otherwise passes under the first rows' selection. + * Slots reach the sort through LDS, not `expert_ids`: each row's lanes write their slot's expert + * (relative to the slice, or -1) into the sort's slot list, so the one barrier between the halves + * orders LDS only. There is no barrier before the rows (each thread zeroes the histogram on its + * way in), since a top barrier would wait for the workgroup's last wave to launch. * - * WHY IT IS BYTE-IDENTICAL: the selection is the same device function the standalone kernel - * calls, wave-local in every reduction and addressing every store by `m`, so running the rows - * from a different number of waves cannot move a bit; the placement is the same function the - * standalone sort calls, and it is stable without an atomic ordering anything, so it does not - * depend on which wave got there first. The one input on which the two paths differ is a row - * with fewer live experts than top_k -- NaN logits -- whose unselected slots the standalone sort - * reads from whatever `expert_ids` held and this one records as dropped. + * Byte-identical to the unfused pair: the selection and placement are the same device functions, + * wave-local and stable. The one difference is a row with fewer live experts than top_k (NaN + * logits): the standalone sort reads its unselected slots from whatever `expert_ids` held, this + * one records them as dropped. * - * A LOOP AND NOT AN EARLY RETURN over the rows -- every thread has to reach the barrier, and - * `router_topk_kernel`'s `if (m >= M) return;` is exactly what would make that fail on the tail - * workgroup. The row bound is the caller's: T = M * top_k must fit `kScatterSmall`, which the shim - * checks and the architecture asks about before it declares the op at all. + * The rows are a loop, not an early return, because every thread must reach the barrier. T = + * M * top_k must fit kScatterSmall, checked by the shim and by the architecture before declaring + * the op. */ -/* TWO EXPERT COUNTS AND THEY ARE NOT THE SAME NUMBER. The selection runs over the WHOLE router -- - * it is replicated, and every rank picks from every expert -- while the sort runs over THIS - * RANK'S SLICE and drops what went elsewhere. On this model at two ranks that is 512 against 254. - * Passing one count to both is the bug this signature exists to make impossible: the sort would - * accept ids outside the slice and index its histogram out of range, and the selection would rank - * half the experts. `n_expert` is the router's, `n_local` the slice's, exactly as the two - * unfused ops declare them. */ +/* Two different expert counts: the selection runs over the whole (replicated) router, `n_expert`, + * while the sort runs over this rank's slice, `n_local`, dropping the rest (512 against 254 at two + * ranks here). Passing one count to both would let the sort index its histogram out of range. */ template __global__ __launch_bounds__(NW * kWave) void router_topk_scatter_kernel( const uint16_t* __restrict__ lg, int32_t* __restrict__ ids, uint16_t* __restrict__ w, @@ -540,8 +447,8 @@ __global__ __launch_bounds__(NW * kWave) void router_topk_scatter_kernel( scatter_small_place(sorted, off, cnt, M * top_k, n_local, sl); } -/* The general form, in three passes, and the three exist to keep it stable without an atomic - * deciding anything. `bcnt` is [n_tile, n_expert] in scratch. */ +/* The general form, in three passes so it stays stable without an atomic deciding order. `bcnt` is + * [n_tile, n_expert] in scratch. */ constexpr uint32_t kScatterTile = 256; __global__ __launch_bounds__(kScatterTile) void scatter_hist_kernel( @@ -561,16 +468,13 @@ __global__ __launch_bounds__(kScatterTile) void scatter_hist_kernel( bcnt[(size_t)b * n_expert + e] = s_h[e]; } -/* ONE WORKGROUP, ONE THREAD AN EXPERT: the exclusive scan across tiles within each expert, in - * place -- so `bcnt[b][e]` becomes "how many of expert e are in tiles before b" -- each expert's - * total, and the exclusive scan of the totals across experts. +/* One workgroup, one thread per expert: the exclusive scan across tiles within each expert, in + * place (`bcnt[b][e]` becomes the count of expert e in tiles before b), each expert's total, and + * the exclusive scan of the totals across experts. * - * A thread's column of `bcnt` comes in kScanBatch loads at a time, all issued before any is used: - * at a 2048-token chunk and top 10 that is 80 tiles, and walked a load at a time -- load, add, - * store, then the next load -- it is 80 dependent round trips on the one workgroup a layer's sort - * waits for. The prefix across experts is the small sort's: a DPP scan in each wave and one - * exchange of the wave totals. Integers, and every sum has one answer whatever order it is formed - * in. */ + * A thread's column of `bcnt` is loaded kScanBatch at a time before use; one at a time it would be + * 80 dependent round trips at a 2048-token chunk and top 10. The prefix across experts is the small + * sort's (DPP scan per wave plus one exchange). Integer sums are order-independent. */ constexpr uint32_t kScanBatch = 16; __global__ __launch_bounds__(kMaxExpert) void scatter_scan_kernel( @@ -582,8 +486,8 @@ __global__ __launch_bounds__(kMaxExpert) void scatter_scan_kernel( int32_t run = 0; if (e < n_expert) { for (uint32_t b0 = 0; b0 < n_tile; b0 += kScanBatch) { - /* Every load in bounds -- a row past the last is the last row again, and discarded -- - * so none of them sits in a branch the next one has to wait behind. */ + /* Every load in bounds (past the end re-reads the last row, discarded), so no load sits + * in a branch. */ int32_t v[kScanBatch]; #pragma unroll for (uint32_t k = 0; k < kScanBatch; ++k) { @@ -613,11 +517,10 @@ __global__ __launch_bounds__(kMaxExpert) void scatter_scan_kernel( if (e == 0) off[n_expert] = tot; } -/* THE PLACEMENT, AND THE TAIL. Every routed slot of the tile goes to its expert's offset, plus the - * expert's count in the tiles before this one, plus its rank in this tile. The sorted rows past the - * live count are -1; they are never a placement target (every placed slot lands below - * `off[n_expert]`), so the placement's own threads write them, each its own index, and no thread - * can race another for a row. */ +/* Placement and tail. Each routed slot goes to its expert's offset plus the expert's count in + * earlier tiles plus its rank in this tile. Sorted rows past the live count are -1; no placement + * lands there (all placed slots are below `off[n_expert]`), so each thread writes its own index + * without races. */ __global__ __launch_bounds__(kScatterTile) void scatter_place_kernel( const int32_t* __restrict__ ids, const int32_t* __restrict__ bcnt, const int32_t* __restrict__ off, int32_t* __restrict__ sorted, @@ -625,9 +528,8 @@ __global__ __launch_bounds__(kScatterTile) void scatter_place_kernel( __shared__ int32_t s_id[kScatterTile]; const uint32_t tid = threadIdx.x, b = blockIdx.x; const uint32_t i = b * kScatterTile + tid; - /* THE PLACE IN THE SORT throughout -- the local expert index, with any protected experts moved - * last: s_id, the range test and the rank scan all work in the indices the offsets and the - * weight tables are built from. */ + /* Everything works in sort places (local index, protected experts last), the indices the + * offsets and weight tables use. */ const int32_t l = (i < T) ? ids[i] - base : -1; const int32_t e = (l >= 0 && l < (int32_t)n_expert) ? sort_place(l, n_expert, prot) : -1; s_id[tid] = e; @@ -635,8 +537,8 @@ __global__ __launch_bounds__(kScatterTile) void scatter_place_kernel( if (i >= live && i < T) sorted[i] = -1; __syncthreads(); if (i >= T || e < 0) return; - /* Rank within the tile: how many earlier slots of this tile chose the same expert. A serial - * scan of at most 256 LDS words a thread, which is the price of stability. */ + /* Rank within the tile: earlier slots of this tile with the same expert. A serial scan of at + * most 256 LDS words per thread, the price of stability. */ int32_t rank = 0; for (uint32_t j = 0; j < tid; ++j) rank += (s_id[j] == e); sorted[off[e] + bcnt[(size_t)b * n_expert + e] + rank] = (int32_t)i; @@ -644,24 +546,20 @@ __global__ __launch_bounds__(kScatterTile) void scatter_place_kernel( /* ================================================================== the 4-bit expert weight * - * SIXTEEN PACKED BYTES TO THE THIRTY-TWO E4M3 BYTES OF A Stage8, and nothing downstream of it - * changes: the padded LDS pitch, frag(), the WMMA and the store are the fp8 kernel's, untouched. - * r4d_layout.cpp's moe w4 section states the stored plane; this is the decode it was chosen for. + * Sixteen packed bytes expand to the thirty-two E4M3 bytes of a Stage8; everything downstream (LDS + * pitch, frag(), WMMA, store) is the fp8 kernel's. The stored plane is described in + * r4d_layout.cpp's moe w4 section. * - * Byte b of a packed dword holds element b in its low nibble and element b+4 in its high one, so - * the two masks below produce elements 0..3 and 4..7 already in order and nothing has to be - * interleaved afterwards. It is the same argument the dense w4a8 kernel's header makes for the - * same pair of masks. + * Byte b of a packed dword holds element b in its low nibble and b+4 in its high one, so the two + * masks yield elements 0..3 and 4..7 in order with no interleave (as in the dense w4a8 kernel). * - * Fifteen VALU per eight weights. At every shape this kernel runs it is DRAM-bound by better than - * an order of magnitude -- a prefill layer reads about 3 GiB of expert weight for 134 GFLOP, which - * is 25 FLOP a byte against a part that wants 400 -- so the dequant is free and the halved weight - * stream is the whole of the win. + * Fifteen VALU per eight weights. The kernel is DRAM-bound by over an order of magnitude (a + * prefill layer: ~3 GiB of expert weight for 134 GFLOP), so the dequant is free and halving the + * weight stream is the win. */ __device__ __forceinline__ uint32_t w4_e4m3(uint32_t nib, const uint32_t (&tab)[4]) { - /* SIXTEEN LEVELS OUT OF AN EIGHT-BYTE PERMUTE, which is the whole trick. V_PERM_B32 selects - * from a 64-bit source, so one table holds eight entries and no more -- and a nibble needs - * sixteen. Two tables and a selector that CHOOSES BETWEEN THEM gets there: + /* Sixteen levels from eight-byte permutes. V_PERM_B32 selects from a 64-bit source, so one + * table holds eight entries; two tables and a selector between them cover a nibble: * * m = nib & 7 the index within a half, the same for both * lo = perm(tab[1], tab[0], m) E4M3 of entries 0..7 (codes 0..7) @@ -669,15 +567,11 @@ __device__ __forceinline__ uint32_t w4_e4m3(uint32_t nib, const uint32_t (&tab)[ * sel = 0x03020100 + ((nib & 8) >> 1) byte i picks lo[i], or hi[i] four bytes further on * out = perm(hi, lo, sel) * - * The add cannot carry: every selector byte is 0..3 before it and 4..7 after. Fifteen VALU per - * eight weights, and the same fifteen whatever the table holds -- on a kernel that is - * DRAM-bound by better than an order of magnitude. + * The add cannot carry: each selector byte is 0..3 before it and 4..7 after. * - * THE TABLE IS AN ARGUMENT, one of two (r4d_args.h): the integers -8..7 of a two's complement - * nibble (w4a8, w4a8h) or the w4nl levels (w4nla8h). Every entry of both is EXACT IN E4M3, so a - * code expands losslessly and the WMMA's product is entry * activation with no rounding the fp8 - * path did not already have. That is what lets this weight ride the existing - * f32_16x16x16_fp8_fp8 inner loop untouched: only the STAGING changes. */ + * The table is an argument (r4d_args.h): the integers -8..7 of a two's-complement nibble (w4a8, + * w4a8h) or the w4nl levels (w4nla8h). Every entry is exact in E4M3, so codes expand losslessly + * and the f32_16x16x16_fp8_fp8 inner loop is reused unchanged; only staging differs. */ const uint32_t m = nib & 0x07070707u; const uint32_t lo = __builtin_amdgcn_perm(tab[1], tab[0], m); const uint32_t hi = __builtin_amdgcn_perm(tab[3], tab[2], m); @@ -699,11 +593,10 @@ __device__ __forceinline__ Stage8 w4_expand(uint4 p, const uint32_t (&tab)[4]) { return r; } -/* w5nl64a8h's 32 codes: the magnitudes as w4_expand expands any nibble -- `tab` is the sixteen - * magnitudes -- and then each byte's sign bit from `sg`. Output dword m holds elements 4m..4m+3, - * and the relayout stores element 4m+b's sign at bit 7-m of byte b of `sg` (r4d_layout.cpp), so a - * shift by m puts dword m's four signs at bit 7 of their bytes -- E4M3's sign -- and the mask keeps - * just those: two VALU per four weights, one where m is 0. */ +/* w5nl64a8h's 32 codes: magnitudes via w4_expand (`tab` holds the sixteen magnitudes), then each + * byte's sign from `sg`. Output dword m holds elements 4m..4m+3, and the relayout stores element + * 4m+b's sign at bit 7-m of byte b of `sg` (r4d_layout.cpp), so shifting by m puts dword m's signs + * at bit 7 of their bytes (E4M3's sign bit) and the mask keeps them. */ __device__ __forceinline__ Stage8 w5_expand(uint4 p, uint32_t sg, const uint32_t (&tab)[4]) { Stage8 r = w4_expand(p, tab); uint32_t o[8] = { r.v.x, r.v.y, r.v.z, r.v.w, r.w.x, r.w.y, r.w.z, r.w.w }; @@ -715,31 +608,23 @@ __device__ __forceinline__ Stage8 w5_expand(uint4 p, uint32_t sg, const uint32_t return r; } -/* The packed half of a Stage8's worth of K, or zeros for a row this block does not own. A dead - * lane's zeros expand to entry 0, which is E4M3 zero under -8..7 and 1.125 under w4nl; either way - * the column contributes nothing, because the staging gives a column this block does not own a - * weight scale of zero. */ +/* The packed half of a Stage8's worth of K, or zeros for a row this block does not own. Zeros + * expand to entry 0 (E4M3 zero under -8..7, 1.125 under w4nl); either way the column contributes + * nothing, since staging gives an unowned column a weight scale of zero. */ __device__ __forceinline__ uint4 w4_load(const uint8_t* __restrict__ src, bool live) { return live ? *(const uint4*)src : make_uint4(0, 0, 0, 0); } -/* ---- UW: THE WEIGHT STREAM FROM A UNIFORM GLOBAL ADDRESS ---------------------------------------- +/* ---- UW: the weight stream from a uniform global address ---------------------------------------- * - * The weight and its scales are reached through the table, so their base pointer is a value LOADED - * by the kernel: `e` comes out of LDS, the compiler cannot prove it uniform, and the table entry is - * fetched with a vector load into VGPRs and then used as a GENERIC pointer -- every weight load is - * a flat_load. On gfx12 that combination serialises the staging. A flat load may also reach LDS, so - * once one is in flight the waitcnt pass can only wait for a vector-load count of ZERO; and the - * base pointer's own load is never seen as retired across the exec-masked `live` branches. The - * disassembly of the decode form shows the result: `s_wait_loadcnt 0x0` in front of every weight - * load, so a pass's activation, first weight row and second weight row go to memory one after the - * other -- three round trips where one was written. + * The weight base pointer is loaded through the table with an index from LDS, so the compiler + * treats it as a divergent generic pointer and every weight load becomes a flat_load. On gfx12 a + * flat load may reach LDS, so the waitcnt pass waits for a load count of zero before every weight + * load, serialising a pass's activation and weight loads into three round trips. * - * Under UW the two table entries are made uniform (readfirstlane: `e` is block-uniform, every lane - * holds the same pointer) and the loads go through address_space(1), as the dense w4 kernels do: - * an SGPR base, global_load, and nothing for the waitcnt pass to wait on until the LDS store that - * consumes them. The same bytes reach the same registers: bit-identical. A table entry that points - * into host memory (a pooled expert) is still a global address; nothing here can be LDS. */ + * Under UW the table entries are made uniform with readfirstlane (`e` is block-uniform) and loaded + * through address_space(1), as in the dense w4 kernels: SGPR base, global_load, no premature wait. + * Bit-identical. A pooled expert's host-memory entry is still a global address. */ typedef unsigned r4d_moe_u4v __attribute__((ext_vector_type(4))); typedef __attribute__((address_space(1))) const r4d_moe_u4v* r4d_moe_gu4; typedef __attribute__((address_space(1))) const uint32_t* r4d_moe_gu32; @@ -785,12 +670,10 @@ __device__ __forceinline__ uint32_t u32_load_w(const uint32_t* p) { if constexpr (!UW) return *p; return *(r4d_moe_gu32)p; } -/* A 16-BIT SCALE LOADED ZERO-EXTENDED INTO A WHOLE REGISTER. Kept 16-bit, LLVM 24 loads it into a - * register HALF (global_load_d16_b16), which leaves the other half live in the same register: the - * load then depends on that register's last write, and the waitcnt pass answers with a full wait - * at the branch joins around the scale loads. The first pass's three loads -- this scale, the - * activation scale, the activation -- went out one round trip each, which cost the down - * projection's four-pass blocks 25-30%. Widened here, it is LLVM 22's global_load_u16. */ +/* A 16-bit scale loaded zero-extended into a whole register. As a 16-bit value LLVM 24 loads it into + * a register half (global_load_d16_b16), which depends on the register's last write and forces a + * full wait at the surrounding branch joins (25-30% on the down projection's four-pass blocks). + * Widened, it is a global_load_u16. */ template __device__ __forceinline__ uint32_t u16_load_w(const uint16_t* p) { if constexpr (!UW) return *p; @@ -802,13 +685,10 @@ __device__ __forceinline__ uint32_t u16_load_w(const uint16_t* p) { * y[i, :] = a[row(i), :] @ w[e]^T, in SORTED order, both operands E4M3 with a scale per 128 along * K (and, for the weight, per 128 along N). * - * `a_sorted` PICKS row(i), and it is an argument because the two grouped GEMMs of one routed block - * disagree about it. The gate_up projection reads the block INPUT, one row per token, so row(i) is - * `sorted[i] / top_k`. The down projection reads gate_up's OUTPUT, which is already one row per - * (token, slot) in this very order, so row(i) is i -- gathering that a second time reads another - * slot's activation, which is a model that still runs and answers wrongly. Only the resolution of - * `s_tok` below changes; everything downstream reads a row index and does not care where it came - * from. + * `a_sorted` picks row(i). gate_up reads the block input, one row per token, so row(i) is + * `sorted[i] / top_k`. down reads gate_up's output, already one row per (token, slot) in sorted + * order, so row(i) is i; gathering again would read another slot's activation. Only `s_tok`'s + * resolution differs. * * MT M tiles a block, 16 rows each; the banded knob. * NTL N tiles a block, 16 columns each. @@ -817,118 +697,49 @@ __device__ __forceinline__ uint32_t u16_load_w(const uint16_t* p) { * * SK skip, per wave, the M tiles that start at or past the end of the block's run. * - * ---- THE PREFILL TILE IS 32 ROWS BY 64 COLUMNS, AND A WAVE SKIPS WHAT ITS RUN DOES NOT REACH ---- + * ---- prefill tile: 32 rows x 64 columns, waves skipping rows their run does not reach ---- * - * (And by 128 columns over eight waves where the weight's parts allow it: see kPrefillCols.) + * (128 columns over eight waves where the weight's parts allow: see kPrefillCols.) * - * At a prefill chunk a block serves one run (AL, below), and a run is `T / n_expert` rows on - * average -- forty at Qwen3.8-Flash-Next's 2048 chunk, from none to a few hundred. A tile of 128 - * rows by 64 columns, eight waves of one 16-row M tile each, is therefore mostly rows past the end - * of the run, and every wave runs its WMMA over them anyway: dead rows are masked at the load and - * the store but not at the arithmetic. Reshaping that tile -- WGN 2, FN 128, or FM 64 at WGN 2 -- - * only moves the staging depth, and each is slower; none of them removes the dead work. + * At prefill a block serves one run (AL), averaging T / n_expert rows (forty at a 2048 chunk on + * Qwen3.8-Flash-Next). A 128-row tile is then mostly dead rows, masked at load and store but still + * computed; reshaping it only moves the staging depth. Two changes remove the dead work, both + * bit-identical: * - * Two things do, and both are bit-identical -- every live element is still one wave's - * accumulation over the same K in the same order: + * SK a wave skips fragment reads, WMMA and scale fold for M tiles starting at or past its + * run's end (wave-uniform; it still stages and meets every barrier). + * FM 32 the tile matches a typical run; a longer run spans blocks and re-stages from L2. * - * SK a wave skips the fragment reads, the WMMA and the scale fold of any M tile that starts - * at or past the end of its run. The test is wave-uniform, and the wave still stages and - * meets every barrier. On the 128-row tile alone it is -18% on both projections. - * FM 32 the tile is what a run fills. A longer run is two or more blocks, and the second - * staging of its weight is an L2 hit. + * Measured (us per call, gate_up / down, 40 rows per run): 128 x 64 with 8 waves 3346 / 2081; + * 32 x 64 with 4 waves and SK 1552 / 987. 16- and 64-row tiles at 128 columns, and 32 x 128 at + * small runs, are slower, so the tile keeps 64 columns (and the op's "N a multiple of 64"). * - * r4d_selftest --perfmoe, rank 0's tp2 shape over a skewed routing, us a call (gate_up / down): + * At prefill the link is not the bottleneck: per-layer GEMM time does not correlate with how many + * experts are pooled. The deployment uses a 2048 chunk; larger chunks do not help (the checkpoint + * interval clamps them, and a larger activation arena costs expert residency). * - * rows a run (mean) 20 40 64 (256 experts, top 8) - * 128 x 64, 8 waves 3138 / 1915 3346 / 2081 1920 / 1198 - * 32 x 64, 4 waves, SK 1067 / 667 1552 / 987 1115 / 717 + * ES one run per block instead of all of a tile's runs (below). * - * At 128 columns a 16-row tile is slower again (1908 / 1193 at forty) and a 64-row one slower - * still (1843 / 1206). A 128-column tile at 32 rows is within ~3% at forty rows and slower at - * twenty, so the tile keeps 64 columns -- and the op's "N a multiple of 64" with them. + * ---- ES: spreading a decode step's runs over blocks ----------------------------------- * - * AT PREFILL IT IS NOT THE LINK. Across a prefill, each layer's GEMM time is uncorrelated with the - * number of that layer's experts that are pooled rather than resident (61 to 78 of 512): the - * pooled experts' reads overlap the resident ones', and the kernel's own time is the cost. + * At decode T is about eleven rows, one 16-row tile, so a row-range grid collapses to (1, N/FN) + * (20 workgroups for a 1280-column gate_up) and walks the experts serially (~89 GB/s). Runs are + * independent (run j reads expert e(j) and writes rows [rs, re), partitioning the tile), so + * `blockIdx.x` carries (tile, run) and each block does one run. Weight traffic and accumulation + * order are unchanged, so output is bit-identical. A tile has at most FM runs (each owns a row), so + * FM blocks per tile suffice; extra blocks exit at the loop head. The split is unconditional inside + * the decode band (r4d_moe_decode_band). * - * THE DEPLOYMENT RUNS A 2048 CHUNK: a run fills more of its tile, and the whole expert plane is - * swept once for four times the tokens of a 512 chunk. End to end on prompts of 8k and 24k, with - * the 128-row tile: - * - * chunk asked for 512 1024 2048 4096 - * chunk actually run 512 1024 2048 2048 - * tok/s 1750 2200 2706 2620 - * - * 4096 IS NOT A 4096 CHUNK. `plan_chunk` clamps to the checkpoint interval BEFORE the token - * budget, and the interval is 2048, so asking for 4096 runs 2048 chunks and pays for 4096: the - * activation arena grows with the budget and is charged to the VRAM budget ahead of the - * expert/KV division, so the expert slab loses residency for a chunk it never got -- 9458 - * resident units at 512, 9219 at 2048, 8980 at 4096. That is the whole of the 4096 column, and - * it is why the number falls. AND A REAL 4096 CHUNK DOES NOT HELP EITHER: with - * --checkpoint-interval 4096 the engine runs 4096-token chunks, and prefill is 2610 tok/s against - * 2748. The arena takes another 239 resident experts and the extra amortisation does not pay for - * them. - * - * AND IT DOES NOT COST CO-RUNNING DECODERS. A longer chunk holds the device longer per step, so - * every decode step queued behind one waits longer -- but the prefill those steps are queued - * behind is a third shorter, and that is the larger term. Four 1500-token decoders with a ~24k - * prefill landing beside them: - * - * chunk decoders alone beside the prefill the prefill - * 512 19.12 s 31.86 s 1840 tok/s - * 2048 19.13 s 29.52 s 2434 tok/s - * - * Both halves improve. - * - * ES one RUN a block instead of all of a tile's runs -- see below. - * - * ---- ES: WHY A DECODE STEP NEEDS THE RUNS SPREAD OVER BLOCKS ----------------------------------- - * - * A block owning a contiguous row range and looping over the experts in it is a workable shape at - * prefill, where a tile holds a handful of runs and there are enough tiles to fill the device. At - * DECODE it is the whole problem: one token routes to `top_k` experts, so T is about eleven rows - * -- ONE 16-row tile -- and the grid collapses to (1, N/FN). That is 20 workgroups for a - * 1280-column gate_up on a 32-CU part, 80 waves against the ~1000 the device holds, and the - * eleven experts are then walked SERIALLY inside those 20 blocks -- around 89 GB/s on a kernel - * that is a bandwidth problem. - * - * The runs are independent: run `j` reads expert `e(j)`'s weight and writes rows [rs, re), and - * those row ranges partition the tile. So `blockIdx.x` carries (tile, run) instead of tile alone - * and each block does one run. The weight traffic is UNCHANGED -- every expert's N slice is still - * read exactly once -- and so is every accumulation order, so the output is bit-identical; only - * which workgroup does it moves. A tile has at most FM runs because a run owns at least one row, - * so FM blocks a tile always suffices and the ones past the run count exit at the loop head. - * - * The split is unconditional inside the decode band; r4d_moe_decode_band says where that band - * ends and why. - * - * ---- AT DECODE WHAT BINDS IT IS THE LINK, NOT THIS KERNEL --------------------------------------- - * - * This instantiation is the largest single item in a decode trace -- around a fifth of two-rank - * device time -- so it is worth saying precisely what it is waiting for, because it is not anything - * this file can change. - * - * A gate/up dispatch reads about 19.7 MB of expert weight. Its FASTEST dispatches run at 576 GB/s, - * which IS this part's cold-stream peak, so the best case is already perfect and there is no - * compute or bandwidth inefficiency left to find here. The MEAN is 270 GB/s, and the entire gap is - * dispatches that routed to an expert the slab could not hold, whose shard is then streamed over - * the link inside the kernel at ~26 GB/s: one pooled expert is 1.64 MB and about 63 us, which is - * why the median sits near the resident cost and the upper quantiles near one and two misses. - * - * SO THE LEVER IS THE MISS RATE AND NOTHING ELSE. Residency is 82% of 256 experts a layer and it - * is not raisable here: the KV pool lends the experts every block no live request holds, and what - * live requests hold is set by --max-num-seqs and --max-model-len, which are the deployment's - * capability rather than a tuning knob. If every routed expert were resident this - * kernel would run at its resident rate and its share of device time would roughly halve. That is - * the size of the prize for anything that raises capacity or sharpens the ranking, and it is why - * the kernel's own arithmetic is not the lever. + * At decode the link binds, not this kernel: a gate/up dispatch reads ~19.7 MB; the fastest run at + * the part's 576 GB/s cold-stream peak, and the mean (270 GB/s) gap is entirely experts not + * resident in the slab, streamed over the link at ~26 GB/s (~63 us per 1.64 MB expert). The lever + * is the miss rate, not this kernel's arithmetic. */ -/* ONE CLASS OF EXPERTS: the even-numbered or the odd-numbered ones, whose weight tables are - * separate operands because every entry of one table has one geometry. Expert e is entry e / 2 of - * class e % 2. The classes differ when a rank holds an uneven slice of each expert's width -- three - * 128-column blocks of one parity and two of the other -- and are the same geometry otherwise. - * `moe_gemm_q_mod4` has four, by the expert's number mod 4: expert e is entry e / 4 of class e % 4, - * which is what lets four ranks take the extra block of a five-block expert in turn. +/* One class of experts: even- or odd-numbered, with separate weight tables because every entry of + * one table has one geometry. Expert e is entry e / 2 of class e % 2. The classes differ when a rank + * holds an uneven slice of each expert's width (three 128-column blocks of one parity, two of the + * other). `moe_gemm_q_mod4` has four classes, by expert number mod 4 (entry e / 4 of class e % 4), + * so four ranks take a five-block expert's extra block in turn. * * `n` is the weight's rows and `k` its K; `w_ld` the packed byte pitch of a weight row and `s_ld` * the scale plane's row pitch in elements. */ @@ -938,48 +749,30 @@ struct MoeCls { uint32_t w_s0, s_s0; /* bytes an entry of a stacked plane; 0 marks a pointer table */ uint32_t n, k, w_ld, s_ld; }; -/* W4: the code table, r4d_args.h's kW4IntPerm, kW4nlPerm or kW5nlMagPerm -- one for every class, - * since every class is one format. - * - * FOUR CLASSES AND THE TABLE MUST FIT RAD_KPARAM_BLOB (256 bytes) BESIDE EVERYTHING ELSE, because - * a kernel's arguments are packed into one descriptor whether it is launched or described: four - * classes at 40 bytes, the five operand pointers and the map, eight words and this -- 160 + 48 + - * 32 + 16, exactly 256, with no padding since a class is 8-aligned. That is why a class carries - * 32-bit entry strides and no table of its own, and why `mode` packs three small values into one - * word. The sizes are asserted here and the whole list after the kernel. */ +/* W4: the code table (r4d_args.h's kW4IntPerm, kW4nlPerm or kW5nlMagPerm), shared by all classes. */ struct MoeTab { uint32_t v[4]; }; -static_assert(sizeof(MoeCls) == 40 && alignof(MoeCls) == 8, - "a class is two pointers and six words: the kernel's argument budget counts 40"); -static_assert(sizeof(MoeTab) == 16, "the code table is four words"); -/* W4 IS THE WEIGHT'S FORM: 0 block E4M3, 1 four-bit with one bf16 scale a (row, 128 of K), 2 the - * same codes with one E4M3 scale a (row, 64 of K) times the fixed kW4G64Scale (w4nl64a8h), 3 the - * same at one a (row, 32 of K) (w4nl32a8h), 4 five-bit codes -- 2's magnitudes and scales, and a - * sign bit a code from the plane after a row's nibbles (w5nl64a8h). At 2, 3 and 4 a staged - * 128-wide tile holds two or four scale groups, each summed in its own accumulator; a tile's E4M3 - * scales are one sixteen- or thirty-two-bit load. +/* W4 is the weight's form: 0 block E4M3; 1 four-bit with one bf16 scale per (row, 128 of K); 2 the + * same codes with one E4M3 scale per (row, 64 of K) times the fixed kW4G64Scale (w4nl64a8h); 3 the + * same per (row, 32 of K) (w4nl32a8h); 4 five-bit codes, form 2's magnitudes and scales plus a sign + * bit per code from the plane after a row's nibbles (w5nl64a8h). At 2-4 a staged 128-wide tile holds + * two or four scale groups, each in its own accumulator; a tile's E4M3 scales are one 16- or 32-bit + * load. * - * FK IS THE K STAGED A PASS: kFK, one 128-wide scale block, or -- at W4 2 to 4 only -- two of them. - * At FK 256 a pass stages two blocks' worth of weight, so a block has twice the bytes in flight - * behind each barrier pair and the K chain is half as many passes. Every scale group still has its - * own accumulator, started fresh at its first WMMA, and the fold runs the two 128-wide blocks one - * after the other in K order, each exactly the expression the 128 pass folds once a pass, under - * its own activation scale. Same products, same sums, same order: bit-identical to FK 128. + * FK is the K staged per pass: kFK (one 128-wide scale block) or, at W4 2-4 only, two blocks, which + * doubles the bytes in flight per barrier pair and halves the passes. Each scale group keeps its + * own accumulator and the fold runs the two blocks in K order, so FK 256 is bit-identical to 128. * - * UW reads the weight and its scales from a uniform global base -- see the UW note at w4_load. - * The decode form and the run-aligned prefill form always take it; the aligned form needs it for - * the first pass of weight it issues at the map read (see THE ALIGNED FORM'S FIRST PASS, below - * the map read), and was measured with it. The uniform prefill grid keeps the plain loads: its - * timing under UW was never measured, so its instructions stay as they were. + * UW: uniform global weight loads (see the UW note above). Used by the decode form and the + * run-aligned prefill form (whose first-pass prefetch at the map read needs it); the uniform + * prefill grid keeps plain loads, as it was never measured with UW. * - * RS finds an ES block's run in one round trip -- see the RS note at the run search. It covers - * up to kMaxExpert experts; a wider expert count takes the chunked search, which numbers the runs - * the same way. + * RS finds an ES block's run in one round trip (see the RS note at the run search), for up to + * kMaxExpert experts; wider counts use the chunked search, which numbers runs the same way. * - * THE WAVES A SIMD EACH FORM RUNS AT (R4D_WAVES), as every form was measured: the ES prefill grid - * at 9-11 (5 at FK 256, where the staged pass is the register budget), the aligned form at 9-12, - * the uniform grid at 8-9. Left to itself LLVM 24 spends about 30 more VGPRs on the aligned - * split-K form for one to three fewer waves, which cost its prefill tiles 16-52%. */ + * Waves per SIMD (R4D_WAVES), as tuned: ES prefill 9-11 (5 at FK 256, register-bound), aligned + * 9-12, uniform grid 8-9. Unconstrained, LLVM 24 spends ~30 more VGPRs on the aligned split-K form + * for one to three fewer waves (16-52% slower prefill tiles). */ constexpr uint32_t moe_waves(uint32_t ntl, int w4, bool es, bool al, uint32_t fk, bool rs) { return es ? (fk == 256u ? 5u : w4 == 0 ? (rs ? 10u : 11u) : w4 == 1 ? 11u : w4 == 3 ? 9u : 10u) : al ? (ntl == 16u ? (w4 == 1 ? 12u : 9u) : ntl == 8u ? (w4 <= 1 ? 10u : 9u) : 9u) @@ -997,20 +790,20 @@ void moe_gemm_q_kernel( uint16_t* __restrict__ Y, const uint32_t* __restrict__ map, uint32_t T, uint32_t N, uint32_t n_expert, uint32_t top_k, uint32_t a_ld, uint32_t as_ld, uint32_t y_ld, uint32_t mode, const MoeTab tab) { - /* `mode`: bit 0 `a_sorted`, bits 1-2 the class shift (1 for two classes, 2 for four), bits - * 8 up `parts`. */ + /* `mode`: bit 0 `a_sorted`, bits 1-2 the class shift (1 for two classes, 2 for four), bits 8+ + * `parts`. */ const uint32_t a_sorted = mode & 1u, cshift = (mode >> 1) & 3u, parts = mode >> 8; constexpr uint32_t FM = MT * 16, FN = NTL * 16; constexpr uint32_t NTHR = WGM * WGN * kWave; constexpr uint32_t WM = MT / WGM, WN = NTL / WGN; static_assert(MT % WGM == 0 && NTL % WGN == 0, "the wave grid must divide the tile"); - /* The block-fp8 weight has one scale a 128x128 tile; a w4 weight one a ROW, so its block may - * span two of the fp8 grid's scale rows (the aligned form's 256-column down tile). */ + /* The block-fp8 weight has one scale per 128x128 tile; a w4 weight one per row, so its block + * may span two fp8 scale rows (the aligned form's 256-column down tile). */ static_assert(W4 != 0 || kBlock % FN == 0, "a block's N rows must sit in one 128-row weight scale row"); - /* Scale groups a 128-wide block: one, or at W4 2, 3 and 4 the 64- or 32-column ones. */ + /* Scale groups per 128-wide block: one, or the 64- or 32-column groups at W4 2-4. */ constexpr uint32_t kSub = W4 == 3 ? 4u : (W4 == 2 || W4 == 4) ? 2u : 1u; - /* 128-wide blocks a staged pass (one, or two at FK 256), and so scale groups a pass. */ + /* 128-wide blocks per staged pass (one, or two at FK 256), and scale groups per pass. */ constexpr uint32_t kBpS = FK / kBlock; constexpr uint32_t kSubT = kSub * kBpS; static_assert(FK == kFK || (FK == 2 * kFK && kSub > 1), @@ -1022,20 +815,19 @@ void moe_gemm_q_kernel( __shared__ uint8_t s_a[FM * lds_pitch()]; __shared__ uint8_t s_b[FN * lds_pitch()]; __shared__ int32_t s_tok[FM]; - /* The staged K block's scales: one an activation row, and one a weight column (w4) or one for - * the whole block (fp8) -- each once a 128-wide block of the pass. See THE SCALES RIDE WITH THE - * TILE, at the K loop. */ + /* The staged K block's scales: one per activation row, and one per weight column (w4) or one + * per block (fp8), for each 128-wide block of the pass. See "the scales ride with the tile" at + * the K loop. */ __shared__ float s_as[kBpS * FM]; __shared__ float s_ws[kSubT * FN]; const uint32_t tid = threadIdx.x, lane = tid % kWave, wave = tid / kWave; const uint32_t wgm = wave / WGN, wgn = wave % WGN; - /* With ES the x axis is (tile, run) and the run index is the minor half, so a tile's blocks - * stay adjacent and land on neighbouring CUs -- they share the activation rows. */ + /* With ES the x axis is (tile, run) with run minor, so a tile's blocks, which share activation + * rows, land on neighbouring CUs. */ const uint32_t jrun = ES ? (blockIdx.x % FM) : 0u; - /* UNDER AL THE BLOCK IS NAMED BY THE MAP, not by arithmetic on blockIdx: entry i is - * (expert, first row) and the block serves that run and no other. The grid is the upper bound - * `n_expert + T/FM`, so the blocks past the real count exit here. */ + /* Under AL the map names the block: entry i is (expert, first row) and the block serves only + * that run. The grid is the upper bound `n_expert + T/FM`; blocks past the real count exit. */ const uint32_t n0 = blockIdx.y * FN; uint32_t r0, rN, e_al = 0; [[maybe_unused]] uint32_t al_end = 0; /* AL: the run's end, off[e_al + 1] */ @@ -1044,10 +836,8 @@ void moe_gemm_q_kernel( const uint32_t* ent = map + 1 + 2 * blockIdx.x; e_al = ent[0]; r0 = ent[1]; - /* A TAIL BLOCK OWNS NO RUN: it exists to zero the rows past the live count, which no - * expert owns, and it does that here and leaves -- before the first pass's weight below is - * issued for an expert it does not have. Block-uniform (the map entry is the block's), so - * the early loads below are on one path with no join behind them. */ + /* A tail block owns no run: it zeroes the rows past the live count and leaves before the + * early weight loads below. Block-uniform, so those loads stay on one path. */ if (e_al == kMapTail) { const uint32_t live = (uint32_t)off[n_expert]; const uint32_t rT = (r0 + FM < T) ? (r0 + FM) : T; @@ -1056,8 +846,8 @@ void moe_gemm_q_kernel( Y[(size_t)r * y_ld + n0 + c] = 0; return; } - /* The run's end, clamped to the output's rows: an operand may name fewer rows than its - * buffer, never more. */ + /* The run's end, clamped to the output's rows (an operand may name fewer rows than its + * buffer, never more). */ const uint32_t oe = (uint32_t)off[e_al + 1]; al_end = oe < T ? oe : T; rN = (r0 + FM < al_end) ? (r0 + FM) : al_end; @@ -1067,30 +857,20 @@ void moe_gemm_q_kernel( rN = (r0 + FM < T) ? (r0 + FM) : T; } - /* THE ALIGNED FORM'S FIRST PASS OF WEIGHT, IN FLIGHT AS SOON AS THE MAP HAS NAMED THE EXPERT - * (the `ew_` registers: the early weight). Under AL the map entry names the expert, and - * nothing the weight's address needs comes later -- not the tokens, not the run's rows, not - * the live count. Loaded in the run loop, the weight would wait behind the token loads, the - * barrier that publishes them, the live count, the run's end read again and the table entry: - * four round trips in front of the one that carries the bytes, on a block whose whole K is one - * or two passes at the down projection. + /* The aligned form's first pass of weight (`ew_`, the early weight), issued as soon as the map + * names the expert. Nothing the weight's address needs comes later, and in the run loop it + * would wait behind four round trips (tokens, barrier, live count, table entry) on a block + * whose whole K is one or two passes at the down projection. * - * So the block's loads go out in the order their waits want them. First everything the token - * barrier needs -- the block's sorted rows and the live count -- then the table entries - * (uniform: scalar) and the first pass's weight. The vector-load counter retires in order, so - * the wait for the tokens leaves the weight in flight; the token barrier orders LDS alone; and - * the run's end is the one the map read already loaded. The weight comes off UW's uniform global - * base, which a block whose expert the map names has as much as a decode block does -- a flat - * load would also count against the LDS counter the barrier waits on. The first issue() then - * takes these registers instead of loading. The same bytes reach the same registers and the - * same tokens the same LDS slots: bit-identical. + * Loads go out in the order their waits want: the block's sorted rows and the live count, then + * the (uniform, scalar) table entries and the first pass's weight. The vector-load counter + * retires in order, so waiting for the tokens leaves the weight in flight, and the token + * barrier orders LDS only. The weight uses UW's uniform global base (a flat load would also + * count against the LDS counter). The first issue() takes these registers. Bit-identical. * - * EVERY EARLY LOAD IS UNCONDITIONAL. A load under an exec mask -- `if (live) load` -- may not be - * issued at all, and the waitcnt pass, not knowing how many went out, then waits for every one - * of them where it needs the first. So a dead row (past the class's width) reads the expert's - * row 0 instead, a dead token slot reads a real one, and the zero is selected where the value - * is used -- the first issue() for the weight, the token's store for the slot. A tail block - * has already left: it has no expert to load for. */ + * Every early load is unconditional: a load under an exec mask makes the waitcnt pass wait for + * all of them. A dead row reads the expert's row 0 and a dead token slot a real one; the zero + * is selected where the value is used. */ constexpr uint32_t kEwTPR = FK / 32, kEwRPP = NTHR / kEwTPR; constexpr uint32_t kEwBP = (FN + kEwRPP - 1) / kEwRPP; [[maybe_unused]] uint4 ew_b4[AL && W4 ? kEwBP : 1]; @@ -1109,7 +889,7 @@ void moe_gemm_q_kernel( ew_f = sorted[i < T ? i : T - 1u]; } ew_live = (uint32_t)off[n_expert]; - /* Nothing below is scheduled in front of these two: the counter retires in order. */ + /* Keep these two loads first: the counter retires in order. */ __builtin_amdgcn_sched_barrier(0); const uint32_t cls = e_al & ((1u << cshift) - 1u); const MoeCls& C = cls == 0u ? c_even : cls == 1u ? c_odd : cls == 2u ? c_2 : c_3; @@ -1118,8 +898,8 @@ void moe_gemm_q_kernel( ew_wp = uw_ptr(wtab_at(C.w, C.w_s0, e_al >> cshift)); ew_wsp = uw_ptr((const uint16_t*)wtab_at(C.s, C.s_s0, e_al >> cshift)); const uint32_t sn = tid / kEwTPR, sk = (tid % kEwTPR) * 32u; - /* Where a staging pass covers the tile's rows exactly, every thread's every row exists: - * no guard, so no exec mask around a load (a thread's `sn` is below kEwRPP). */ + /* When a staging pass covers the tile's rows exactly every thread's rows exist, so there + * is no guard and no exec mask around a load. */ #pragma unroll for (uint32_t p = 0; p < kEwBP; ++p) { const uint32_t r = sn + p * kEwRPP; @@ -1135,9 +915,8 @@ void moe_gemm_q_kernel( } } - /* RS: this thread's NPT experts' offsets (and the next one's), which of them hold a run that - * meets the tile, and its wave's running count of those -- carried from the loads below to the - * run search further down. See the RS note there. */ + /* RS: this thread's NPT experts' offsets (plus the next), which of them hold a run meeting the + * tile, and the wave's running count of those, carried to the run search below. */ constexpr uint32_t NPT = RS ? kMaxExpert / NTHR : 1; static_assert(!RS || (ES && kMaxExpert % NTHR == 0 && FM <= NTHR), "RS is the decode grid's search: the offsets divide over the block's threads"); @@ -1147,9 +926,8 @@ void moe_gemm_q_kernel( uint32_t live; if constexpr (RS) { - /* EVERY LOAD THE SEARCH NEEDS, ISSUED AT ONCE: the block's sorted rows, its thread's share - * of the offsets and the live count. One round trip, then one barrier publishes the - * tokens and the waves' counts together. */ + /* Every load the search needs, issued at once (sorted rows, this thread's offsets, live + * count): one round trip, then one barrier publishes tokens and wave counts together. */ int32_t f = -1; if (tid < FM && r0 + tid < rN) f = sorted[r0 + tid]; #pragma unroll @@ -1170,12 +948,11 @@ void moe_gemm_q_kernel( } rs_inc = (uint32_t)wave_incl_scan_i32((int32_t)rs_cnt, lane); if (lane == kWave - 1) s_rc[wave] = rs_inc; - /* Both of RS's barriers order LDS alone -- the tokens, the counts, the selection. */ + /* Both RS barriers order LDS only. */ lds_barrier(); } else if constexpr (AL) { - /* The tokens and the live count were loaded with the weight, ahead of it; see THE ALIGNED - * FORM'S FIRST PASS. A row past the block's is a dropped slot, as the loop of the plain - * form writes it. */ + /* Tokens and live count were loaded ahead of the early weight (see above). A row past the + * block's is a dropped slot, as in the plain form. */ if (tid < FM) { const int32_t f = r0 + tid < rN ? ew_f : -1; s_tok[tid] = f < 0 ? -1 : (a_sorted ? (int32_t)(r0 + tid) : f / (int32_t)top_k); @@ -1198,10 +975,9 @@ void moe_gemm_q_kernel( live = (uint32_t)off[n_expert]; } - /* Rows past the live count are dropped slots: zeroed here, and then the run loop below has - * nothing left to do for them. No run owns them, so under ES exactly one of the tile's blocks - * must -- every block writing the same zeros would be a benign race and is still a race. Under - * AL the tail blocks zeroed them at the map read, and every other block's rows are its run's. */ + /* Rows past the live count are dropped slots, zeroed here. No run owns them, so under ES only + * one of the tile's blocks writes them (identical concurrent writes are still a race). Under AL + * the tail blocks zeroed them at the map read. */ if constexpr (!AL) { if (!ES || jrun == 0) for (uint32_t r = (r0 > live ? r0 : live); r < rN; ++r) @@ -1209,39 +985,27 @@ void moe_gemm_q_kernel( Y[(size_t)r * y_ld + n0 + c] = 0; } - /* THE EXPERT OF THE BLOCK'S FIRST RUN. The row-tile grid finds the expert of its first row by - * binary search over the offsets and walks the runs from there, which the loop below does. + /* The expert of the block's first run. The row-tile grid binary-searches the offsets for its + * first row's expert, and the loop below walks runs from there. * - * UNDER ES THAT WALK WOULD BE THE KERNEL. A decode step routes a few dozen slots over hundreds - * of experts, so between two runs sit a dozen experts with no rows, and the walk to run `jrun` - * steps over every one of them a dependent load at a time -- a block serving a tile's last run - * walks most of the tile's expert range before it does anything, and a block past the tile's - * last run walks all of it to find it has nothing to do. At hundreds of experts a rank and a - * down projection a few K blocks long, that walk is a large part of the kernel. - * - * So the block finds its tile's runs in one parallel pass: every thread tests one expert for - * "has rows, and they meet this tile", a ballot and a count of the waves before it place the - * hits in expert order -- which is row order -- and run `jrun` is entry `jrun`. Chunks of - * experts wholly before or after the tile are skipped on one broadcast load, and the pass - * stops once it has found the block's run. The same rows reach the same expert: bit-identical. + * Under ES that walk would dominate: at decode a few dozen slots spread over hundreds of + * experts, so reaching run `jrun` would step over many empty experts one dependent load at a + * time. Instead the block finds its tile's runs in one parallel pass: each thread tests one + * expert for rows meeting this tile, and a ballot plus wave counts place hits in expert (= row) + * order, so run `jrun` is entry `jrun`. Chunks wholly before or after the tile are skipped with + * one broadcast load, and the pass stops at the block's run. Bit-identical. */ uint32_t e = 0; [[maybe_unused]] uint32_t rs_first = 0, rs_end = 0; if constexpr (AL) { e = e_al; /* the map already named it */ } else if constexpr (RS) { - /* RS: THE SAME SEARCH, IN ONE ROUND TRIP AND TWO BARRIERS. The pass above walks the - * experts a chunk of NTHR at a time, each chunk a broadcast load to skip it or two - * dependent loads and two barriers to scan it, after the tokens' own load and barrier and - * the live count's load: a block pays four to six round trips to L2 before it knows its - * expert, and a block past the tile's last run pays them to learn it has nothing to do. - * - * Here every thread holds NPT consecutive experts' offsets from the one batch of loads - * above. The hits are numbered in expert order -- a thread's own in order, then a running - * count over the wave (DPP) and the waves before it -- which is the order the chunked pass - * numbers them in, so run `jrun` is the same expert. Its owner hands the expert and the - * run's bounds over LDS, so neither `off[e]` nor `off[e + 1]` is loaded again. The same - * rows reach the same expert: bit-identical. */ + /* RS: the same search in one round trip and two barriers, where the chunked pass costs four + * to six round trips to L2 before a block knows its expert. Each thread holds NPT + * consecutive experts' offsets from the batch above; hits are numbered in expert order (a + * thread's own, then a DPP running count over the wave and the waves before it), the same + * numbering as the chunked pass. The owner of run `jrun` hands the expert and the run's + * bounds over LDS, so `off[e]` and `off[e + 1]` are not reloaded. Bit-identical. */ uint32_t before = rs_inc - rs_cnt, nrun = 0; for (uint32_t w = 0; w < NTHR / kWave; ++w) { if (w < wave) before += s_rc[w]; @@ -1266,10 +1030,9 @@ void moe_gemm_q_kernel( rs_first = s_sel[1]; rs_end = s_sel[2]; } else if constexpr (ES) { - /* THE CHUNKED SEARCH SERVES THE DECODE FORM ABOVE kMaxExpert EXPERTS. RS holds a thread's - * share of the offsets in NPT registers sized for kMaxExpert, so a wider expert count is - * this loop's, which walks any count a chunk of NTHR at a time. r4d_selftest runs the - * decode form at 640 experts against the uniform prefill grid, byte for byte. */ + /* The chunked search serves the decode form above kMaxExpert experts (RS's registers are + * sized for kMaxExpert), walking NTHR experts at a time. r4d_selftest checks it at 640 + * experts against the uniform prefill grid. */ __shared__ int32_t s_run[FM]; __shared__ uint32_t s_wc[NTHR / kWave]; uint32_t nrun = 0; @@ -1307,12 +1070,11 @@ void moe_gemm_q_kernel( e = lo; } - /* THE OUTPUT IS `parts` STACKED PARTS OF N / parts COLUMNS, and so is every weight, each part - * of it `n / parts` rows. A weight part narrower than the output's fills the part's leading - * columns and the rest are ZERO: that is a rank's two-block slice of a gate/up pair written - * into the three-block layout the gated quantiser reads, and the zeros are what make the - * quantiser's output there zero rather than whatever the arena held. With one part and one - * geometry this is the whole weight at column n0. */ + /* The output is `parts` stacked parts of N / parts columns, as is every weight (n / parts rows + * per part). A weight part narrower than the output's fills the part's leading columns and the + * rest are zero: a rank's two-block slice of a gate/up pair in the three-block layout the gated + * quantiser reads, whose output there must be zero. With one part this is the whole weight at + * column n0. */ const uint32_t fy = N / parts; const uint32_t part = n0 / fy, j0 = n0 - part * fy; @@ -1323,8 +1085,7 @@ void moe_gemm_q_kernel( constexpr uint32_t kBP = (FN + kRPP - 1) / kRPP; const uint32_t sn = tid / kTPR, sk = (tid % kTPR) * kSeg; - /* Under ES the block's run was found above, so the loop starts at it: its first row in the - * tile, and the run count already at `jrun`. */ + /* Under ES the loop starts at the block's run: its first row in the tile, run count `jrun`. */ uint32_t rs = r0, run = 0; if constexpr (RS) { rs = rs_first; @@ -1335,33 +1096,26 @@ void moe_gemm_q_kernel( run = jrun; } while (rs < rN && rs < live) { - /* This run: rows [rs, re) all belong to expert `e`. The advance is at the TOP so `e` can - * never be walked past the last expert -- `off[e + 1]` is read only for e < n_expert, and - * off[n_expert] is the live row count, which is the bound the loop already respects. - * Under RS the search handed over the run's end, and its start meets it: nothing to walk. */ + /* This run: rows [rs, re) all belong to expert `e`. The advance is at the top so `e` never + * passes the last expert (`off[e + 1]` is read only for e < n_expert). Under RS the search + * supplied the run's end. */ if constexpr (!RS && !AL) { while (e < n_expert && (uint32_t)off[e + 1] <= rs) ++e; if (e >= n_expert) break; } - /* AL: the map's run is e_al's from r0 on, so there is nothing to walk, and its end is the - * one the map read loaded. */ + /* AL: the map's run is e_al's from r0, with its end already loaded. */ const uint32_t ehi = RS ? rs_end : AL ? al_end : (uint32_t)off[e + 1]; const uint32_t re = rN < live ? (rN < ehi ? rN : ehi) : (live < ehi ? live : ehi); if (re <= rs) break; - /* Not this block's run: walk past it. Block-uniform, so no barrier is skipped by some - * threads and not others. */ - /* Not this block's run: never true, since under ES the loop starts at the block's run. - * It stays for the fp8 weight (W4 0) alone, as the back edge it makes: the CFG - * structurizer keeps it, and LLVM 24's waitcnt pass then places the decode form's first-pass - * waits differently. With it the four-bit forms' first pass went out one load a round trip - * (FK 256 gate_up at one and two tokens 4-7% slower than 7.2); without it the fp8 form's - * K loop did (11-13% slower at one and two tokens). Each form is built the way it measured - * faster: r4d_selftest --perfmoe --cold and the MoE fixture's cold kbench. */ + /* Never true (under ES the loop starts at the block's run), but kept for the fp8 weight + * (W4 0) for the back edge it creates: with it LLVM 24's waitcnt placement serialises the + * four-bit forms' first pass, without it the fp8 form's K loop (11-13% slower at one and two + * tokens). Each form is built the way it measured faster. */ if (ES && W4 == 0 && run != jrun) { rs = re; ++run; continue; } - /* The expert's class, and where this block's columns sit in its weight. Block-uniform: a - * pad tile zeroes the run's rows and moves on without touching LDS or a barrier. `cshift` - * is 1 for two classes and 2 for four; c_2 and c_3 are never read at two. */ + /* The expert's class and where this block's columns sit in its weight. Block-uniform: a pad + * tile zeroes the run's rows and moves on without LDS or a barrier. `cshift` is 1 for two + * classes, 2 for four; c_2 and c_3 are unused at two. */ const uint32_t cls = e & ((1u << cshift) - 1u); const MoeCls& C = cls == 0u ? c_even : cls == 1u ? c_odd : cls == 2u ? c_2 : c_3; const uint32_t fc = C.n / parts; @@ -1381,8 +1135,8 @@ void moe_gemm_q_kernel( const uint32_t kb_n = wn0 / kBlock; /* the weight scale's N row for this block */ if constexpr (W4) (void)kb_n; /* w4 scales vary per ROW, not per N block */ - /* Both table entries are loaded before either is made uniform, so under UW the two - * readfirstlanes wait on one round trip and not on two. */ + /* Both table entries load before either is made uniform, so the two readfirstlanes wait on + * one round trip. */ const uint8_t* Wp0; const uint16_t* Wsp0; if constexpr (AL) { @@ -1395,106 +1149,71 @@ void moe_gemm_q_kernel( const uint8_t* Wp = uw_ptr(Wp0); const uint16_t* Wsp = uw_ptr(Wsp0); - /* SK: A WAVE WHOSE M TILES ARE ALL PAST THE RUN has nothing to accumulate. Under AL the - * run is the block's rows [rs, re) from its first row, so that is a wave-uniform test; - * such a wave still stages and meets every barrier, and only its fragment reads, its - * WMMA and its scale fold are skipped. */ + /* SK: a wave whose M tiles are all past the run has nothing to accumulate (wave-uniform + * test); it still stages and meets every barrier, skipping only fragment reads, WMMA and + * scale fold. */ const bool wlive = !SK || (r0 + wgm * WM * 16 < re); f8v raw[WM][WN], out[WM][WN]; - /* The other scale groups' accumulators at W4 2 and 3 (`raw` is the first's) -- the pass's, - * so both blocks' at FK 256; one unused element otherwise. Each starts fresh in its group's - * first WMMA, so none is zeroed. */ + /* The other scale groups' accumulators at W4 2-4 (`raw` is the first's), for every block of + * the pass; one unused element otherwise. Each starts fresh at its group's first WMMA, so + * none is zeroed. */ f8v rx[kSubT > 1 ? kSubT - 1 : 1][kSubT > 1 ? WM : 1][kSubT > 1 ? WN : 1]; #pragma unroll for (uint32_t i = 0; i < WM; ++i) #pragma unroll for (uint32_t j = 0; j < WN; ++j) { raw[i][j] = acc_zero(); out[i][j] = acc_zero(); } - /* THE K LOOP IS SOFTWARE PIPELINED, and without that it spends most of its time waiting. + /* The K loop is software pipelined. Staged straight through, each of K/kFK = 20 iterations + * exposes its global latency, with under two blocks per CU at decode to cover it (~245 GB/s + * against the part's 486 cold). So the tile is loaded into registers one iteration ahead: + * tile i+1's loads issue right after tile i reaches LDS and are collected at the next LDS + * store, a barrier and a WMMA block later, for sixteen VGPRs. Bit-identical. * - * Staged straight through -- issue the loads, wait for them, store to LDS, barrier, - * compute -- the global latency of every one of K/kFK = 20 iterations is exposed in full, - * because nothing else in the block is runnable while the loads are outstanding. A decode - * layer puts about 110 of these blocks on 64 CUs, which is under two a CU: there is no - * second resident block to cover the stall either. Staged that way the kernel runs at - * about 245 GB/s on gate_up's 9.0 MB, against the 486 this part reaches on a cold stream, - * and its K loop disassembles to 432 instructions for 8 WMMA -- so it is not issue-bound - * and not short of blocks. It is waiting. - * - * So the tile is loaded into REGISTERS one iteration ahead. The loads for tile i+1 are - * issued right after tile i's bytes have been handed to LDS, and the `s_waitcnt` that - * collects them does not land until the next iteration's LDS store -- one barrier and the - * whole WMMA block later. Sixteen VGPRs a thread buys that; nothing else changes. - * - * BIT-IDENTICAL: the same bytes reach the same LDS addresses in the same order and the - * accumulation is untouched. Only WHEN the load is issued moves. - * - * ONE TILE AHEAD IS THE WHOLE OF IT -- do not go deeper. A two-slot ring is WORSE both ways - * it can be written: indexing the ring with a running `slot` puts the register arrays in - * SCRATCH, and unrolling the K loop by the depth to make the index a constant instead takes - * VGPRs 96 -> 112 and doubles the body. Neither is the reason it cannot win, though. This - * kernel is not waiting on DRAM at all: at eight concurrent sequences it serves eight times - * the tokens and several times the distinct experts in the SAME time it takes at one, and - * its duration barely moves with the number of experts routed. At decode it is - * critical-path bound -- 400 waves on 256 SIMDs, each stalled about 88% of cycles on its - * own dependencies -- and the only axis - * that shortens the 20-step serial K chain is a split-K, which is not bit-identical and so - * is not a decision this file gets to make. */ - /* THE SCALES RIDE WITH THE TILE. The fold at the end of a K block needs the activation - * scale of eight rows a lane and the weight scale of a lane's columns; loaded there, from - * global memory, after the block's WMMA, they would be ten scattered loads a lane, issued - * behind the matrix work and waited on before the next block could start. They are - * one value a row and one a column, so the thread that stages a row or a column loads its - * scale with the tile, one K block ahead, and the fold reads them from LDS. The same - * values reach the same multiplies: bit-identical. */ + * Do not go deeper than one tile: a two-slot ring puts the arrays in scratch (running + * index) or costs 16 VGPRs and a doubled body (unrolled). At decode the kernel is + * critical-path bound on the 20-step K chain, which only a split-K would shorten, and that + * is not bit-identical. */ + /* The scales ride with the tile: the fold needs each row's activation scale and each + * column's weight scale, which loaded after the WMMA would be scattered dependent loads. So + * the thread staging a row or column loads its scale with the tile, one K block ahead, and + * the fold reads them from LDS. Bit-identical. */ Stage8 apre[kAP]; uint4 bpre4[kBP]; /* W4: packed nibbles, expanded at store time as before */ uint32_t spre[W4 == 4 ? kBP : 1]; /* W4 4: the same 32 elements' sign bits */ Stage8 bpre8[kBP]; /* otherwise: the fp8 bytes themselves */ - /* kUL: WHETHER EACH STAGED ROW IS LIVE. Under kUL a row's tile is loaded whether it is - * live or not -- a dead row reads a row that exists -- and the zero it stages is selected - * at the LDS store, from these. Loaded only when live, the zero is written into the - * load's destination first, and that write lands on registers the previous pass's load - * filled: on the path where a wave's lanes all skipped that load's store branch, the - * waitcnt pass cannot see the load collected, so it waits for every load in flight before - * the write. Each pass's loads then went out one pair a round trip -- three a K step at - * the aligned down projection's tile, 15% of its time -- where an unconditional load into - * the same registers needs no wait at all (loads of one kind retire in order). The - * one-run-a-block form (ES) keeps the guarded loads: unconditional, it measured 1.5% - * slower, and it does not have the waits. */ + /* kUL: whether each staged row is live. Under kUL every row's tile is loaded (a dead row + * reads a row that exists) and the zero is selected at the LDS store. A guarded load writes + * its zero into registers the previous pass's load filled, and the waitcnt pass then waits + * for every load in flight (15% of the aligned down projection's time); unconditional loads + * retire in order and need no wait. ES keeps the guarded loads (1.5% faster there). */ constexpr bool kUL = UW && AL; [[maybe_unused]] bool aok[kUL ? kAP : 1]; [[maybe_unused]] bool bok[kUL ? kBP : 1]; - /* thread tid < FM: its row's activation scale, one a 128-wide block of the pass */ + /* thread tid < FM: its row's activation scale, one per 128-wide block of the pass */ float pas[kBpS] = {}; - /* thread FM + c: column c's weight scale (w4), or the block's (fp8); at W4 3 its four -- - * again one a 128-wide block of the pass */ - /* At W4 3 the scale IS 32 bits, its four E4M3 groups packed: a 16-bit register would keep - * two of them. Otherwise a 16-bit scale: under AL held zero-extended in a whole register - * (see u16_load_w), the other forms measured 1% slower that way and keep it 16-bit. */ + /* thread FM + c: column c's weight scale (w4) or the block's (fp8), one per 128-wide block + * of the pass. At W4 3 it is 32 bits (four packed E4M3 groups). Otherwise 16-bit, held + * zero-extended in a whole register under AL (see u16_load_w); the other forms measured 1% + * slower that way. */ using PwsT = std::conditional_t; PwsT pws[kBpS] = {}; - /* UW: the thread's scale as loaded, and whether it is live -- the zero is selected where - * it is staged. Two registers, one a role, and NOT initialised: the two branches run in - * one wave, gfx12 retires two vector loads into one register in no promised order, and a - * role initialised to zero is provably zero in the other role's branch, where the - * compiler then writes that zero -- each a wait for the other branch's load. */ + /* UW: the thread's scale as loaded and whether it is live; the zero is selected where it is + * staged. One register per role, deliberately uninitialised: an initialised role is + * provably zero in the other role's branch, and the compiler's write of that zero would + * wait for the other branch's load (both branches run in one wave). */ float pau[UW ? kBpS : 1]; PwsT pwu[UW ? kBpS : 1]; bool pok = false; - /* `first` is the pass at cc 0 as a TYPE, not a test of cc: the early weight is read there - * and nowhere else, and a runtime `cc == 0` in the loop's issue(c0 + FK) is one the compiler - * cannot rule out (the sum is unsigned and may wrap), so it kept the ew_ registers live - * across every pass -- under LLVM 24, sixteen VGPRs the WMMA block then went without: at - * the pinned occupancy it read each fragment pair behind a full LDS wait. */ + /* `first` marks the cc 0 pass as a type, not a runtime test: the compiler cannot rule out + * `cc == 0` in issue(c0 + FK) (unsigned wrap) and would keep the ew_ registers live across + * every pass, starving the WMMA block of sixteen VGPRs. */ auto issue = [&](uint32_t cc, auto first) { const uint32_t kbk = cc / kBlock; if constexpr (UW) { - /* UNDER UW THE SCALE LOADS ARE UNCONDITIONAL -- from a row that exists when this - * one is dead -- and the zero is selected at the LDS store. Selected here, the zero - * is a VALU write into a register that another lane's scale load is still filling - * (the two branches run in one wave), and the waitcnt pass answers that write by - * waiting for the load, in front of every other load of the pass. */ + /* Under UW the scale loads are unconditional (from an existing row when this one is + * dead) and the zero is selected at the LDS store; selecting it here would write a + * register another lane's load is filling and force a wait before the pass's other + * loads. */ if (tid < FM) { const int32_t tok = s_tok[tid]; pok = tok >= 0 && (r0 + tid) >= rs && (r0 + tid) < re; @@ -1584,10 +1303,10 @@ void moe_gemm_q_kernel( const uint32_t r = sn + p * kRPP; if (r >= FN) continue; const bool ok = (j0 + r) < fc; - /* W4: half the bytes off the same row, expanded on the way in. `w_ld` is the - * PACKED byte pitch there, which is why it is not divided here. At W4 4 the row's - * sign plane follows its K/2 bytes of nibbles, a bit an element. Under kUL a dead - * row reads the tile's first row, and the store selects its zero (see bok). */ + /* W4: half the bytes of the row, expanded on the way in; `w_ld` is already the + * packed byte pitch. At W4 4 the row's sign plane (one bit per element) follows its + * K/2 bytes of nibbles. Under kUL a dead row reads the tile's first row and the + * store selects its zero (see bok). */ const uint8_t* wr = Wp + (size_t)(kUL && !ok ? wn0 : wn0 + r) * w_ld; if constexpr (kUL) bok[p] = ok; if constexpr (W4) { @@ -1600,32 +1319,27 @@ void moe_gemm_q_kernel( bpre8[p] = stage8_load_w(wr + cc + sk, kUL || ok); } }; - /* `s_tok` is settled by the barrier above the run loop and no run rewrites it, so priming - * ahead of the loop's own barrier reads nothing another thread is still writing. */ + /* `s_tok` is settled by the barrier above the run loop and never rewritten, so priming + * before the loop's own barrier is safe. */ issue(0u, std::true_type{}); - /* THE K LOOP'S BARRIERS ORDER LDS AND NOTHING ELSE -- no thread reads what another wrote - * to global memory inside it. __syncthreads() is a workgroup fence over every address - * space, and on gfx12 that is `s_wait_loadcnt 0` in front of the barrier: the pass's - * prefetch is waited for right after it is issued, before the WMMA it was meant to hide - * behind. Under UW the barriers are lds_barrier(), and the loads stay in flight until the - * next pass's LDS store collects them. + /* The K loop's barriers order LDS only; no thread reads another's global writes inside it. + * __syncthreads() fences every address space, which on gfx12 waits for the prefetch right + * after issuing it, so under UW the barriers are lds_barrier() and the loads stay in flight + * until the next pass's LDS store. * - * AND THAT COLLECTION IS ONE EXPLICIT WAIT, for everything, where the stores begin. Left - * to the waitcnt pass, the wait sits inside the exec-masked branches of the stores; a wave - * that skips one keeps the register "in flight" as far as the pass can tell, and it then - * guards the next pass's load into that register with `s_wait_loadcnt 0` -- after the - * load just ahead of it has been issued, so the pass's loads are serial again. Nothing is - * in flight at this point that the stores do not need. */ + * That collection is one explicit wait where the stores begin. Left to the waitcnt pass, + * the wait sits inside the stores' exec-masked branches, and a wave skipping one would + * guard the next pass's load with a full wait, serialising the loads again. */ auto kbar = [] { if constexpr (UW) lds_barrier(); else __syncthreads(); }; for (uint32_t c0 = 0; c0 < K; c0 += FK) { kbar(); /* the previous run's reads are done */ - /* The wait, as a release fence on the global address space: the only spelling of - * `s_wait_loadcnt 0` the waitcnt pass reads as one, so it then knows every register - * of the pass's prefetch has landed. No invalidate -- that is the acquire half. */ + /* The wait, as a global release fence: the only form of `s_wait_loadcnt 0` the waitcnt + * pass recognises, so it knows the prefetch has landed. No invalidate (that is the + * acquire half). */ if constexpr (UW) __builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "global"); #pragma unroll for (uint32_t p = 0; p < kAP; ++p) { @@ -1661,8 +1375,8 @@ void moe_gemm_q_kernel( for (uint32_t h = 0; h < kBpS; ++h) s_as[h * FM + tid] = pas_v(h); } else if (tid < FM + FN) { if constexpr (kSub > 1) { - /* The tile's scale groups in column order, the first in the low byte; at - * FK 256 the first block's groups, then the second's. */ + /* The tile's scale groups in column order, first in the low byte; at FK 256 + * the first block's groups, then the second's. */ #pragma unroll for (uint32_t h = 0; h < kBpS; ++h) #pragma unroll @@ -1678,8 +1392,8 @@ void moe_gemm_q_kernel( kbar(); if (!wlive) continue; - /* One K step of the tile into the accumulator `acc`; `fresh` starts it from zero - * rather than from what it holds -- exactly the same sum, and no reset to pay. */ + /* One K step of the tile into `acc`; `fresh` starts from zero instead of the held value + * (same sum, no reset). */ auto kstep = [&](uint32_t ks, f8v (&acc)[WM][WN], bool fresh = false) { i2v af[WM], bf[WN]; #pragma unroll @@ -1698,13 +1412,10 @@ void moe_gemm_q_kernel( acc[i][j] = mma(af[i], bf[j], fresh ? acc_zero() : acc[i][j]); } }; - /* AT W4 2 AND 3 EACH SCALE GROUP OF THE TILE HAS ITS OWN ACCUMULATOR, because each - * has its own scale: folding a group as it ends would make the next group's WMMA wait - * on its results, and at a decode step -- a serial chain of tiles -- that wait is most - * of what the finer groups would cost. They fold once, at the end of the tile, and - * each group's first step starts its accumulator, so the fold resets none. At FK 256 - * that is every group of both 128-wide blocks: group g of the pass is group g % kSub - * of block g / kSub, in K order. */ + /* At W4 2-4 each scale group of the tile has its own accumulator, so no group's WMMA + * waits on the previous group's fold; all fold once at the end of the tile, and each + * group's first step starts its accumulator. At FK 256 group g of the pass is group + * g % kSub of block g / kSub, in K order. */ if constexpr (kSubT > 1) { constexpr uint32_t kG = FK / kSubT; #pragma unroll @@ -1719,21 +1430,17 @@ void moe_gemm_q_kernel( for (uint32_t ks = 0; ks < FK; ks += r4d_fp8::kK) kstep(ks, raw); } { - /* THE GRIDS DIFFER IN WHAT THE WEIGHT SCALE VARIES OVER, and that is the only - * arithmetic difference between the instantiations. + /* The forms differ only in what the weight scale varies over: * - * fp8: one bf16 per 128x128 tile, so it is uniform over the whole block and folds - * into the activation scale before the accumulate -- one multiply. - * w4: one bf16 per (ROW, group of 128 K), which a 4-bit grid needs: a 128x128 - * block scale would spend all sixteen levels on the largest row in it. A - * fragment's lanes hold sixteen consecutive output COLUMNS, so the scale is - * a per-lane constant per N tile and comes out as a third factor. - * W4 2-4: groups of 64 or 32 K, two or four a tile, each group's sum under its - * own scale. + * fp8: one bf16 per 128x128 tile, uniform over the block, folded into the + * activation scale before the accumulate. + * w4: one bf16 per (row, 128 of K); a 128x128 block scale would spend all sixteen + * levels on its largest row. A fragment's lanes hold sixteen consecutive + * output columns, so the scale is a per-lane constant per N tile. + * W4 2-4: groups of 64 or 32 K, two or four per tile, each sum under its scale. * - * The fp8 form is written out separately rather than folded into a common - * expression because a * (b * c) and (a * b) * c differ in the last bit, and that - * kernel's output is byte-checked. */ + * The fp8 form is written out separately because a * (b * c) and (a * b) * c differ + * in the last bit, and its output is byte-checked. */ float as[kBpS][WM][8]; #pragma unroll for (uint32_t h = 0; h < kBpS; ++h) @@ -1760,9 +1467,9 @@ void moe_gemm_q_kernel( for (uint32_t q = 1; q < kSub; ++q) v += rx[q - 1][i][j][t] * wq[q][j]; out[i][j][t] += v * as[0][i][t]; if constexpr (kBpS > 1) { - /* FK 256: the pass's second 128-wide block, folded after the - * first in the very expression the next 128 pass would fold - * it with, so `out` sees the same sequence of updates. */ + /* FK 256: the second 128-wide block, folded after the first + * with the expression a separate 128 pass would use, so `out` + * sees the same updates. */ float v1 = rx[kSub - 1][i][j][t] * wq[kSub][j]; #pragma unroll for (uint32_t q = 1; q < kSub; ++q) @@ -1803,9 +1510,8 @@ void moe_gemm_q_kernel( } } - /* The store. For a fixed accumulator slot the wave's sixteen lanes hold sixteen - * consecutive output columns, so this is coalesced across the wave even though a lane's - * own eight values are eight rows apart. */ + /* The store: for a fixed accumulator slot sixteen lanes hold sixteen consecutive columns, + * so it is coalesced across the wave. */ #pragma unroll for (uint32_t i = 0; i < WM; ++i) #pragma unroll @@ -1821,63 +1527,44 @@ void moe_gemm_q_kernel( rs = re; ++run; - /* One run a block under ES and AL, and it is done. Under AL a second pass of this loop would - * leave at once (the map's run ends at al_end), but as a loop it lets the compiler hoist - * the first pass's selects of the early weight out of it, to the top: LLVM 24 does, and - * then waits for that weight before the pass's other loads are issued. */ + /* One run per block under ES and AL. Under AL a second iteration would exit at once, but + * without the break LLVM 24 hoists the early weight's selects to the top and waits for + * that weight before issuing the pass's other loads. */ if (ES || AL) break; } } -/* The whole argument list against the descriptor (see MoeTab): every instantiation takes the same - * parameters, so the decode form stands for all of them. */ -using MoeQArgs = R4dParams)>; -static_assert(MoeQArgs::bytes() <= RAD_KPARAM_BLOB, - "moe_gemm_q_kernel's arguments overflow RAD_KPARAM_BLOB"); -static_assert(MoeQArgs::count <= RAD_MAX_KPARAMS, - "moe_gemm_q_kernel has more arguments than RAD_MAX_KPARAMS"); /* ================================================================== moe_gemm_q, the down decode form * - * THE SORTED-OPERAND PROJECTION AT DECODE, ONE BLOCK A RUN TILE, G COLUMN TILES A BLOCK. + * The sorted-operand projection at decode: one block per run tile, G column tiles per block. * - * The (tile, run) grid above gives down -- K 128 or 256 a rank, N the model width -- one block for - * every 16-row tile's every run slot and every 64 columns: at sixteen sequences, 640 routed rows - * over some three hundred experts, that is 640 x 40 = 25 600 blocks for about 63 MB of weight. - * More than half of them find no run and leave after the search, and each of the others stages - * 4 or 8 KB of weight behind a search, a table load and a barrier pair -- one or two K passes, so - * nothing of its own to overlap. A run that crosses a tile boundary is staged by two blocks. + * The (tile, run) grid gives down (K 128 or 256 per rank, N the model width) a block per 16-row + * tile, run slot and 64 columns: 25 600 blocks at sixteen sequences for ~63 MB of weight, most + * finding no run, the rest staging 4-8 KB behind a search, a table load and a barrier pair. A run + * crossing a tile boundary is staged twice. * - * Here a block owns ONE 16-ROW TILE OF ONE RUN -- the tiles start at the run's first row, as the - * run-aligned prefill form's do -- and G 64-column tiles of its output: + * Here a block owns one 16-row tile of one run (tiles start at the run's first row, as in the + * run-aligned prefill form) and G 64-column tiles of output: * - * - THE GRID IS (run tile, column group). A run of n rows is ceil(n / 16) tiles, so there are at - * most min(T, n_expert) + T/16 of them; block j finds the j-th in expert order in one round - * trip (every offset, four a thread, one load wave, a DPP count and one exchange of the waves' - * totals), the way RS finds a tile's run. One more block at the end zeroes the rows past the - * live count, which no run owns. - * - A RUN IS NEVER SPLIT AT AN ARBITRARY ROW: a run of up to sixteen rows is one tile however it - * falls, so an expert's weight is staged once a column tile, not once for each 16-row band of - * the sorted rows it touches. A longer run is a block a tile, side by side, rather than one - * block walking all of them -- a popular expert does not become the kernel's tail. - * - THE PASSES OF ALL G COLUMN TILES ARE ONE PIPELINE: (column tile, K block), each pass's - * operands loaded one pass ahead as in the K loop above -- so the next tile's weight is in - * flight while this one's last block is computed. The chain the (tile, run) form pays once a - * block -- search, table, first load -- is paid once a G tiles here. + * - The grid is (run tile, column group). A run of n rows is ceil(n / 16) tiles, at most + * min(T, n_expert) + T/16 in all; block j finds the j-th in expert order in one round trip + * (four offsets per thread, a DPP count and one exchange), as RS does. One extra last block + * zeroes the rows past the live count. + * - A run of up to sixteen rows is always one tile, so an expert's weight is staged once per + * column tile; a longer run gets one block per tile, side by side. + * - All G column tiles' passes form one pipeline over (column tile, K block), each loaded one + * pass ahead, so the search/table/first-load chain is paid once per G tiles. * - * G is the launcher's (kMoeDownDecG2Rows, kMoeDownDecG4Rows): one at a step of a few sequences, - * where every run is needed to fill the part, and up to four at sixteen, where there are runs - * enough. At most kMoeDownDecMaxG, so the block's column tiles are bits of one word. The loads are - * UW's throughout -- uniform global bases and LDS-only barriers -- because a barrier that waits for - * the prefetch would make the pipeline a chain again. + * G comes from the launcher (kMoeDownDecG2Rows, kMoeDownDecG4Rows): one at a few sequences, up to + * four at sixteen; at most kMoeDownDecMaxG so the column tiles are bits of one word. Loads are UW + * throughout (uniform bases, LDS-only barriers), since a barrier waiting on the prefetch would + * serialise the pipeline. * - * BIT-IDENTICAL to the (tile, run) form: an output element is one wave's WMMA chain over the same K - * in the same order, folded by the same expression under the same scales; only which block, and - * which row of its 16-row tile, computes it moves -- the argument the AL form makes, and the - * selftest compares every form with this one byte for byte. + * Bit-identical to the (tile, run) form: each output element is the same WMMA chain and fold; the + * selftest compares them byte for byte. * - * ONLY THE SORTED OPERAND, where a run's activation rows are its own rows: [rs, re) of `Aq`, with - * no gather. Inside a run every row is a placed slot -- the scatter fills [0, off[n_expert]) and - * nothing else -- so `sorted` decides nothing here and is not read. */ + * Sorted operand only: a run's activation rows are [rs, re) of `Aq` with no gather. Every row in a + * run is a placed slot (the scatter fills exactly [0, off[n_expert])), so `sorted` is not read. */ template __global__ __launch_bounds__(4 * kWave) void moe_down_dec_kernel( const uint8_t* __restrict__ Aq, const float* __restrict__ As, @@ -1908,9 +1595,8 @@ __global__ __launch_bounds__(4 * kWave) void moe_down_dec_kernel( const uint32_t cend = cg0 + G * FN < N ? cg0 + G * FN : N; const uint32_t ng = (cend - cg0 + FN - 1) / FN; - /* THE LAST BLOCK OWNS NO RUN: the rows past the live count are dropped slots, or the protected - * experts' rows their own GEMM writes after this one, and here they are zero -- every column, - * as the (tile, run) form's first block of a tile leaves them. */ + /* The last block owns no run: it zeroes every column of the rows past the live count (dropped + * slots, or protected experts' rows their own GEMM writes afterwards). */ if (blockIdx.x == gridDim.x - 1) { const uint32_t live = (uint32_t)off[n_expert]; for (uint32_t r = live; r < T; ++r) @@ -1918,18 +1604,14 @@ __global__ __launch_bounds__(4 * kWave) void moe_down_dec_kernel( return; } - /* THE TILE: the j-th 16-row tile of a run, in expert order and then row order. Every thread - * holds NPT consecutive experts' offsets and the next one, from one wave of loads; the tiles - * are numbered a thread's own in order, then over the wave (DPP) and the waves before it. - * Both barriers order LDS. + /* The tile: the j-th 16-row run tile in expert, then row, order. Each thread holds NPT + * consecutive experts' offsets plus the next; tiles are numbered by thread, then over the wave + * (DPP) and the waves before it. Both barriers order LDS. * - * EVERY OFFSET IS CLAMPED TO T, so every run ends at the output's last row at the latest, as - * the (tile, run) form's runs do: an operand may name fewer rows than its buffer, never more. - * A run that would start past T is then empty and has no tile, so the tile count also stays - * inside the grid's bound. */ - /* The loads are unconditional -- a thread past the experts reads off[n_expert] again and a - * select drops it -- so the NPT + 1 of them issue in one round. Guarded, each sits in a branch - * of its own with its wait behind it: NPT + 1 round trips in front of the first barrier. */ + * Every offset is clamped to T, so no run extends past the output (an operand may name fewer + * rows than its buffer, never more) and the tile count stays within the grid. */ + /* Unconditional loads (a thread past the experts re-reads off[n_expert], dropped by a select), + * so all NPT + 1 issue in one round instead of one round trip each. */ uint32_t ov[NPT + 1]; #pragma unroll for (uint32_t k = 0; k <= NPT; ++k) { @@ -1971,8 +1653,8 @@ __global__ __launch_bounds__(4 * kWave) void moe_down_dec_kernel( } } lds_barrier(); - /* Block-uniform from here on, and said so: the class, the table entry and every pass bound - * below are then scalar. The block's rows are [rs, re), at most a tile. */ + /* Block-uniform from here (readfirstlane), so the class, table entry and pass bounds are + * scalar. The block's rows are [rs, re), at most a tile. */ const uint32_t e = (uint32_t)__builtin_amdgcn_readfirstlane((int)s_sel[0]); const uint32_t rs = (uint32_t)__builtin_amdgcn_readfirstlane((int)s_sel[1]); const uint32_t r1 = (uint32_t)__builtin_amdgcn_readfirstlane((int)s_sel[2]); @@ -1987,8 +1669,8 @@ __global__ __launch_bounds__(4 * kWave) void moe_down_dec_kernel( const uint8_t* Wp = uw_ptr(Wp0); const uint16_t* Wsp = uw_ptr(Wsp0); - /* A COLUMN TILE PAST THE CLASS'S WIDTH holds no weight: the run's rows there are zero, as the - * (tile, run) form writes them, and it takes no pass. The others are `npm`. */ + /* A column tile past the class's width holds no weight: its rows are zeroed and it takes no + * pass. The others are marked in `npm`. */ uint32_t npm = 0; for (uint32_t g = 0; g < ng; ++g) { const uint32_t n0 = cg0 + g * FN, part = n0 / fy, j0 = n0 - part * fy; @@ -2001,7 +1683,7 @@ __global__ __launch_bounds__(4 * kWave) void moe_down_dec_kernel( } if (!npm) return; - /* THE PASSES: (column tile, K block), K innermost. The last pass's successor is never + /* Passes over (column tile, K block), K innermost. The last pass's successor is never * issued. */ const uint32_t nK = K / FK; const uint32_t P = (uint32_t)__builtin_popcount(npm) * nK; @@ -2021,9 +1703,8 @@ __global__ __launch_bounds__(4 * kWave) void moe_down_dec_kernel( constexpr uint32_t kBP = (FN + kRPP - 1) / kRPP; const uint32_t sn = tid / kTPR, sk = (tid % kTPR) * kSeg; - /* The operands one pass ahead, as moe_gemm_q_kernel's UW path holds them: the scale loads - * unconditional, the zero selected at the LDS store, and the two scale roles' registers not - * initialised -- see the note there. */ + /* Operands one pass ahead, as in moe_gemm_q_kernel's UW path: unconditional scale loads, the + * zero selected at the LDS store, scale-role registers uninitialised (see the note there). */ Stage8 apre[kAP]; uint4 bpre4[kBP]; uint32_t spre[W4 == 4 ? kBP : 1]; @@ -2190,38 +1871,23 @@ __global__ __launch_bounds__(4 * kWave) void moe_down_dec_kernel( cur = nxt; } } -using MoeDnArgs = R4dParams)>; -static_assert(MoeDnArgs::bytes() <= RAD_KPARAM_BLOB, - "moe_down_dec_kernel's arguments overflow RAD_KPARAM_BLOB"); -static_assert(MoeDnArgs::count <= RAD_MAX_KPARAMS, - "moe_down_dec_kernel has more arguments than RAD_MAX_KPARAMS"); /* ================================================================== moe_gemm, bf16 * - * y[i, :] = a[row(i), :] @ w[e]^T in SORTED order, both operands bf16 and one f32 accumulator over - * the whole of K -- the expert GEMM of a model served from its own bf16 checkpoint. That is the - * reference deployment, and it is the forward pass a calibration run records its Hessians through, - * where the activations reaching each layer have to be the ones the unquantised weights produce. + * y[i, :] = a[row(i), :] @ w[e]^T in sorted order, bf16 operands and one f32 accumulator over all + * of K: the expert GEMM for a model served from its bf16 checkpoint (the reference deployment, and + * the forward pass a calibration run records Hessians through). * - * THE GROUPING IS moe_gemm_q_kernel's AND ONLY THE INNER LOOP DIFFERS. A block serves one run of - * the run map at prefill (AL) and one run of a 16-row tile at decode (ES), a wave skips the M tiles - * its run does not reach (SK), and `a_sorted` picks the activation row a sorted row reads -- every - * argument made for those beside the fp8 kernel holds here unchanged. So does the reason the forms - * are byte-identical to each other: every output element is one wave's accumulation over the whole - * of K, in one order, whichever block computes it. - * - * WHAT DIFFERS: - * - ONE TABLE, one geometry. The parity classes and `parts` exist because a 640-column expert - * does not halve into 128-column scale blocks; a bf16 plane has no block to respect, so a rank - * holds whole experts or every expert at one width and every entry has one shape. - * - THE PLANE IS THE CHECKPOINT'S ROW-MAJOR [N, K] AS IT STANDS -- no layout hook, no relayout. - * The bytes the kernel reads are the bytes in the safetensors file, which is what lets a - * container's expert go from disk into a staging buffer and straight to this kernel. - * - K IS STAGED kBK16 = 64 ELEMENTS A PASS, 128 bytes a row like the fp8 kernel's 128 codes, - * through r4d_gemm_bf16_nt_tiled.hip's LDS pitch of 72 elements: a fragment read's sixteen rows - * then land on distinct bank pairs. The next pass is loaded into registers while the current - * one is computed, the one-ahead prefetch the fp8 kernel's K-loop note argues for. - * - NOTHING TO FOLD: the WMMA accumulates into the output tile across every pass of K. + * Grouping is moe_gemm_q_kernel's (AL at prefill, ES at decode, SK, `a_sorted`), so the forms are + * byte-identical to each other for the same reason. Differences: + * - One table, one geometry: no parity classes or `parts`, since a bf16 plane has no scale + * blocks to respect. + * - The plane is the checkpoint's row-major [N, K] as stored, with no relayout, so an expert can + * go from disk through a staging buffer straight to this kernel. + * - K is staged kBK16 = 64 elements (128 bytes) per pass with r4d_gemm_bf16_nt_tiled.hip's LDS + * pitch of 72, so a fragment's sixteen rows hit distinct bank pairs; the next pass is + * prefetched into registers. + * - Nothing to fold: the WMMA accumulates across every pass of K. */ constexpr uint32_t kBK16 = 64; // bf16 K elements staged per pass constexpr uint32_t kP16 = kBK16 + 8; // the LDS row pitch, in elements @@ -2233,10 +1899,9 @@ __device__ __forceinline__ mb_v8f mb_mma(mb_v8bf a, mb_v8bf b, mb_v8f c) { return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12(a, b, c); } -/* A 16x16 bf16 operand fragment out of an LDS tile whose row 0 is `tile`, already advanced to the k - * step. Lane l reads row l % 16 at k = 4 * (l / 16) .. +3 and eight past that -- the wave32 bf16 - * WMMA operand layout, two runs of four (r4d_gdn_wmma.h probed it). Two 8-byte reads 16 bytes apart - * off one base, which the assembler folds into one ds_load_2addr_b64. */ +/* A 16x16 bf16 operand fragment from an LDS tile whose row 0 is `tile`, advanced to the k step. + * Lane l reads row l % 16 at k = 4 * (l / 16) .. +3 and eight past that (the wave32 bf16 WMMA + * operand layout, r4d_gdn_wmma.h): two 8-byte reads 16 bytes apart, one ds_load_2addr_b64. */ __device__ __forceinline__ mb_v8bf mb_frag(const uint16_t* __restrict__ tile, uint32_t lane) { const uint2* pw = (const uint2*)(tile + (lane & 15u) * kP16 + 4u * (lane >> 4)); union { uint2 w[2]; mb_v8bf f; } u; @@ -2257,7 +1922,7 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_bf16_kernel( constexpr uint32_t FM = MT * 16, FN = NTL * 16; constexpr uint32_t NTHR = WGM * WGN * kWave; constexpr uint32_t WM = MT / WGM, WN = NTL / WGN; - /* Sixteen-byte chunks: eight of them a staged row, and how many a thread carries per tile. */ + /* Sixteen-byte chunks: eight per staged row, and how many a thread carries per tile. */ constexpr uint32_t kCPR = kBK16 / 8; constexpr uint32_t kAC = (FM * kCPR + NTHR - 1) / NTHR; constexpr uint32_t kBC = (FN * kCPR + NTHR - 1) / NTHR; @@ -2269,7 +1934,7 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_bf16_kernel( const uint32_t tid = threadIdx.x, lane = tid % kWave, wave = tid / kWave; const uint32_t wgm = wave / WGN, wgn = wave % WGN; - /* The block's rows and its run, named exactly as moe_gemm_q_kernel names them -- see there. */ + /* The block's rows and run, as in moe_gemm_q_kernel. */ const uint32_t jrun = ES ? (blockIdx.x % FM) : 0u; uint32_t r0, rN, e_al = 0; bool tail = false; @@ -2355,10 +2020,9 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_bf16_kernel( rs = s0 > r0 ? s0 : r0; run = jrun; } else { - /* A CALL MAY SERVE A TRAILING SEGMENT of the sort -- a layer's protected experts, after - * the four-bit GEMM has served the rest -- and then its offsets begin at off[0] > 0 and the - * rows below are another call's output. The block map never names them and the run search - * above never finds one there; the plain row grid has to be told. */ + /* A call may serve a trailing segment of the sort (a layer's protected experts, after the + * four-bit GEMM served the rest); then off[0] > 0 and the rows below belong to another + * call. The block map and run search never reach them; the plain row grid must skip them. */ const uint32_t s0 = (uint32_t)off[0]; rs = s0 > r0 ? s0 : r0; } @@ -2378,12 +2042,10 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_bf16_kernel( #pragma unroll for (uint32_t j = 0; j < WN; ++j) acc[i][j] = (mb_v8f)(0.0f); - /* Chunk c of a tile is row c / kCPR, elements (c % kCPR) * 8 of it. A row outside the run, - * a dropped slot or a column past N stages zeros. EVERY LOAD IS ISSUED, a dead row's from a - * row that exists -- the activation's row 0, the tile's last weight row -- and the store - * selects its zero: a load under its own condition is an exec-masked branch, and the - * waitcnt pass then waits inside it, which serialises the pass's loads (moe_gemm_q_kernel's - * K-loop note). */ + /* Chunk c of a tile is row c / kCPR, elements (c % kCPR) * 8. A row outside the run, a + * dropped slot or a column past N stages zeros. Every load is issued (a dead row reads an + * existing row) and the store selects the zero, since a conditional load would serialise + * the pass's loads (moe_gemm_q_kernel's K-loop note). */ uint4 apre[kAC], bpre[kBC]; bool aok[kAC], bok[kBC]; auto issue = [&](uint32_t k0) { @@ -2407,12 +2069,9 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_bf16_kernel( }; issue(0); - /* THE K LOOP'S BARRIERS ORDER LDS AND NOTHING ELSE, so they are lds_barrier(): - * __syncthreads() is a fence over global memory too, `s_wait_loadcnt 0` in front of the - * barrier, and the next pass's prefetch would be waited for right after it is issued - * instead of behind this pass's WMMA. The prefetch is collected by one explicit wait where - * the stores begin -- a release fence on the global address space, the spelling the - * waitcnt pass reads as `s_wait_loadcnt 0` (moe_gemm_q_kernel's K-loop note). */ + /* The K loop's barriers order LDS only, so they are lds_barrier() (__syncthreads() would + * wait for the prefetch right after issuing it). The prefetch is collected by one global + * release fence where the stores begin (moe_gemm_q_kernel's K-loop note). */ for (uint32_t k0 = 0; k0 < K; k0 += kBK16) { lds_barrier(); /* the previous pass's fragments are read */ __builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "global"); @@ -2454,8 +2113,8 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_bf16_kernel( } } - /* Lane l holds column l % 16 of a tile and rows 8 * (l / 16) + t: the accumulator layout - * the fp8 kernel's acc_row / frag_c also describe. Rounded to nearest-even. */ + /* Lane l holds column l % 16 and rows 8 * (l / 16) + t (the layout of acc_row / frag_c). + * Rounded to nearest-even. */ #pragma unroll for (uint32_t i = 0; i < WM; ++i) #pragma unroll @@ -2477,14 +2136,12 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_bf16_kernel( /* ================================================================== moe_gather * - * y[t, :] = sum over a token's slots of expert_w[t, j] * y_expert[position of (t, j)], and the sum - * runs in ASCENDING SLOT ORDER because that is what makes it reproducible -- walking the - * expert-sorted rows instead would sum a token's contributions in expert-id order and the two - * differ in the last bits. + * y[t, :] = sum over a token's slots of expert_w[t, j] * y_expert[position of (t, j)], summed in + * ascending slot order for reproducibility (expert-sorted order would differ in the last bits). * - * The inverse permutation is built by a pass of its own rather than searched per token: `sorted` is - * a permutation of the live slots, so `inv[sorted[i]] = i` is one scattered store per row. A slot - * nothing claims keeps -1 and contributes nothing, which is how a dropped slot is expressed. */ + * The inverse permutation is built by its own pass: `sorted` permutes the live slots, so + * `inv[sorted[i]] = i` is one scattered store per row. An unclaimed (dropped) slot keeps -1 and + * contributes nothing. */ __global__ void gather_inv_kernel(int32_t* __restrict__ inv, uint32_t T) { const uint32_t i = blockIdx.x * blockDim.x + threadIdx.x; if (i < T) inv[i] = -1; @@ -2498,35 +2155,20 @@ __global__ void gather_scatter_kernel(const int32_t* __restrict__ sorted, if (f >= 0 && f < (int32_t)T) inv[f] = (int32_t)i; } -/* THE SLOT TABLE IS HOISTED, AND THAT IS THE WHOLE OF THIS KERNEL'S COST. +/* The slot table is hoisted: `inv[t * top_k + j]` and `ew[t * ew_ld + j]` do not depend on the + * column, and read inside the column loop each `inv` load would serialise the `ye` load behind it + * (110 dependent latencies per layer at decode). Read once into LDS, the `ye` loads pipeline. * - * `inv[t * top_k + j]` and `ew[t * ew_ld + j]` do not depend on the column. Read inside the column - * loop -- `inv` IN FRONT OF the `ye` load that uses it -- every one of the top_k loads is a - * dependent round trip: at a decode step's one token, 2560 columns and eleven slots, that is 110 - * serialised memory latencies, tens of microseconds a layer. Read once into LDS, the `ye` loads - * are independent and pipeline. - * - * The column range is also split over blocks, because one token is one block otherwise and a - * decode step has one token. Neither the hoist nor the split touches the sum: a column's slots are - * still summed in ASCENDING SLOT ORDER, which is what the note above says is load-bearing, and no - * column's sum is split across blocks. */ + * The column range is also split over blocks, since decode has one token. Neither change touches + * the sum: each column's slots are still summed in ascending order within one block. */ constexpr uint32_t kGatherSlots = 64; -/* THE INVERSE PERMUTATION IS BUILT IN THIS KERNEL WHEN IT IS SMALL ENOUGH TO BE FREE, and the two - * prepass kernels above are then not launched at all. +/* When small, the inverse permutation is built in this kernel and the two prepass kernels are not + * launched. A block owns one token, so it scans `sorted` for entries in [t*top_k, (t+1)*top_k), + * giving exactly the table `inv` would hold. Every block repeats the scan, so the launcher caps it + * (r4d_rad_moe_gather); at decode T = 40 and the scan is one pass, against two dependent dispatches + * (~2.1 us each) of single-block kernels. * - * A block owns one token, so it needs the inverse for `top_k` slots and not for all T of them: - * scanning `sorted` for the entries that land in [t*top_k, (t+1)*top_k) gives exactly the same - * table `inv` would have held, built from LDS instead of a device round trip. Every block repeats - * the scan, which is why the launcher caps it -- at a decode step T is M*top_k = 40 and the scan - * is one pass of a 256-thread block, against two dispatches and 2.9 us of kernel time for two - * single-block kernels that between them touch 40 integers. See r4d_rad_moe_gather for the bound. - * - * WHAT IT SAVES IS DISPATCHES RATHER THAN KERNEL TIME, and the arithmetic is unchanged -- `inv` - * holds exactly what the prepass would have put there. The two kernels it removes are together a - * fraction of a millisecond a rank a step of device time across 96 dispatches, and at the ~2.1 us - * this part charges for a dependent launch the dispatches are the larger half. - * - * `sorted == nullptr` is the prepass path, the one a prefill chunk takes. */ + * `sorted == nullptr` selects the prepass path, used at prefill. */ constexpr uint32_t kGatherSelfT = 512; template @@ -2542,16 +2184,15 @@ __global__ __launch_bounds__(NTHR) void gather_kernel( const uint32_t t = blockIdx.x; if (t >= M) return; const bool cached = top_k <= kGatherSlots; - /* The shared arm's scalar, read once a block exactly as scale_rows reads it once a row. */ + /* The shared arm's scalar, read once per block as scale_rows reads it once per row. */ float gate = 0.0f; if (sh) { const float v0 = bf16_to_f32(sg[(size_t)t * sg_ld]); gate = sig ? (1.0f / (1.0f + __expf(-v0))) : v0; } if (sorted) { - /* A slot no sorted row claims must read -1, which is why the fill and the scan are two - * phases with a barrier between them -- the same reason the prepass is two kernels. Here - * the barrier is __syncthreads() and costs nothing. */ + /* An unclaimed slot must read -1, so fill and scan are separated by a barrier (as the + * prepass is two kernels). */ for (uint32_t j = threadIdx.x; j < top_k; j += NTHR) s_i[j] = -1; __syncthreads(); const int32_t lo = (int32_t)(t * top_k), hi = lo + (int32_t)top_k; @@ -2579,26 +2220,23 @@ __global__ __launch_bounds__(NTHR) void gather_kernel( } const uint16_t g = f32_to_bf16(acc); if (!sh) { y[(size_t)t * y_ld + c] = g; continue; } - /* THE SHARED ARM, FOLDED. Both narrows are the unfused pair's: `scale_rows` reads this - * gather out of a bf16 buffer and narrows its own product before adding, so carrying - * either in f32 here would move the last bit of every channel. */ + /* The shared arm, folded with the unfused pair's two narrows: `scale_rows` reads the gather + * as bf16 and narrows its own product before adding. */ const uint16_t p = f32_to_bf16(bf16_to_f32(sh[(size_t)t * sh_ld + c]) * gate); y[(size_t)t * y_ld + c] = f32_to_bf16(bf16_to_f32(p) + bf16_to_f32(g)); } } -/* ---- THE PREFILL GATHER, A WAVE A TOKEN AND EIGHT COLUMNS A LANE --------------------------------- +/* ---- prefill gather: a wave per token, eight columns per lane --------------------------------- * - * At a prefill chunk this op is a read of `ye` -- one row a routed slot, 105 MB a layer at a 2048 - * chunk of Qwen3.8-Flash-Next on a rank of four -- and gather_kernel moves it TWO BYTES A LANE: a - * block is one token's 256 columns, each of its loads one slot's 64 bytes a wave, and a lane's slots - * are a loop whose loads wait on the slot table one after the other. That is about two thirds of - * the part's cold-stream rate on the op's bytes. + * At prefill this op reads `ye` (105 MB per layer at a 2048 chunk of Qwen3.8-Flash-Next on four + * ranks), and gather_kernel moves two bytes per lane with slot loads serialised on the slot table + * (about two thirds of cold-stream rate). * - * Here a wave owns one token and 256 columns, eight a lane. The token's slot table is read first - * (uniform: scalar loads), then every slot's sixteen bytes are issued before any is used, then - * summed. THE ARITHMETIC IS gather_kernel's: per column, ascending slot order, a dropped slot skipped, - * `acc += w * x` in f32, and the shared arm's two narrows exactly as there -- the same bits. + * Here a wave owns one token and 256 columns, eight per lane: the slot table is read first (scalar + * loads), then every slot's sixteen bytes are issued before any is used. Arithmetic is + * gather_kernel's (ascending slot order, dropped slots skipped, f32 `acc += w * x`, the shared + * arm's two narrows), so the bits match. */ constexpr uint32_t kGatherWideSlots = 16; /* top_k at most this: the slots live in registers */ constexpr uint32_t kGatherWideCols = 8; /* columns a lane, one sixteen-byte load */ @@ -2615,14 +2253,13 @@ __global__ __launch_bounds__(NW * kWave) void gather_wide_kernel( const uint32_t wave = (uint32_t)__builtin_amdgcn_readfirstlane((int)(threadIdx.x / kWave)); const uint32_t t = blockIdx.x * NW + wave; const uint32_t c = (blockIdx.y * kWave + lane) * kGatherWideCols; - /* No barrier anywhere below, so a wave past the last token simply leaves. */ + /* No barrier below, so a wave past the last token simply leaves. */ if (t >= M) return; - /* THE TOKEN'S SLOTS AND WEIGHTS IN ONE LOAD: lane j fetches slot j (a lane past top_k fetches - * slot 0 again, in bounds and never used) and every lane then reads them off the lanes, as - * constants into scalar registers. Loaded one a slot, each would be a scalar load waited on - * just before its own row's load is issued. Every lane of the wave takes part -- a lane past - * the last column leaves only after -- since a value is read off ANY lane. */ + /* The token's slots and weights in one load: lane j fetches slot j (lanes past top_k re-fetch + * slot 0, unused) and every lane reads them off the lanes into scalar registers. Every lane + * takes part (a lane past the last column leaves only afterwards), since values are read off + * any lane. */ const uint32_t jl = lane < top_k ? lane : 0u; const int32_t il = inv[(size_t)t * top_k + jl]; const int32_t wl = (int32_t)ew[(size_t)t * ew_ld + jl]; @@ -2634,10 +2271,9 @@ __global__ __launch_bounds__(NW * kWave) void gather_wide_kernel( sw[j] = bf16_to_f32((uint16_t)__builtin_amdgcn_readlane(wl, (int)j)); } if (c >= n) return; - /* NO break AND NO continue IN THESE LOOPS: with an early exit the compiler keeps the slot loop - * rolled, `yv[j]` is then indexed at run time, and the whole array goes to scratch. Written as - * uniform branches over a constant trip count, every index is a constant and every slot a - * register. A slot is live exactly where gather_kernel's loop reaches it and does not skip it. */ + /* No break or continue in these loops: an early exit keeps the slot loop rolled and `yv` goes + * to scratch. Uniform branches over a constant trip count keep every slot in a register. A slot + * is live exactly where gather_kernel's loop would use it. */ bool lv[kGatherWideSlots]; uint4 yv[kGatherWideSlots]; #pragma unroll @@ -2646,7 +2282,7 @@ __global__ __launch_bounds__(NW * kWave) void gather_wide_kernel( yv[j] = make_uint4(0, 0, 0, 0); if (lv[j]) yv[j] = *(const uint4*)(ye + (size_t)si[j] * ye_ld + c); } - /* The shared arm after the slots, so nothing it waits on stands in front of their loads. */ + /* The shared arm after the slots, so its loads do not delay theirs. */ float gate = 0.0f; uint4 shv = make_uint4(0, 0, 0, 0); if (sh) { @@ -2677,7 +2313,7 @@ __global__ __launch_bounds__(NW * kWave) void gather_wide_kernel( for (uint32_t q = 0; q < 4; ++q) { uint16_t lo = f32_to_bf16(acc[2 * q]), hi = f32_to_bf16(acc[2 * q + 1]); if (sh) { - /* THE SHARED ARM, FOLDED, with gather_kernel's two narrows. */ + /* The shared arm, folded with gather_kernel's two narrows. */ const uint16_t plo = f32_to_bf16(bf16_to_f32((uint16_t)(s[q] & 0xFFFFu)) * gate); const uint16_t phi = f32_to_bf16(bf16_to_f32((uint16_t)(s[q] >> 16)) * gate); lo = f32_to_bf16(bf16_to_f32(plo) + bf16_to_f32(lo)); @@ -2690,14 +2326,11 @@ __global__ __launch_bounds__(NW * kWave) void gather_wide_kernel( /* ================================================================== scale_rows * - * y[m, i] = x[m, i] * act(s[m]). One workgroup a row, grid-strided along the row, and the scalar - * read once into a register rather than once per element. It is the shared expert's gate and - * nothing else in this tree uses it; see docs/OPS.md for why `mul` cannot serve it. */ -/* `ad` PRESENT IS THE FUSED GATE-AND-ADD FORM, `y = bf16(x * act(s)) + ad`, and the NARROW in the - * middle is load-bearing: the pair this stands in for writes the product to a bf16 buffer and - * then adds that buffer, so the product is rounded before the sum sees it. Carrying the f32 - * product into the add would differ in the last bit of every channel, and the emitted text with - * it. */ + * y[m, i] = x[m, i] * act(s[m]). One workgroup per row, grid-strided along it, with the scalar read + * once. Used only for the shared expert's gate; docs/OPS.md explains why `mul` cannot serve it. */ +/* With `ad`, the fused gate-and-add form `y = bf16(x * act(s)) + ad`. The middle narrow matches the + * unfused pair, which stores the product as bf16 before adding; an f32 product would change the + * last bit of every channel. */ template __global__ __launch_bounds__(NTHR) void scale_rows_kernel( const uint16_t* __restrict__ x, const uint16_t* __restrict__ sc, @@ -2716,10 +2349,10 @@ __global__ __launch_bounds__(NTHR) void scale_rows_kernel( } /* namespace */ -/* THE GATHER'S FORM, pinned for a test: 0 is the launcher's rule, 1 gather_kernel (a column a - * thread), 2 gather_wide_kernel (a wave a token). The rule takes 2 past the self-scan bound wherever - * the shape allows it; see r4d_rad_moe_gather. A pinned form the shape cannot take is refused. Both - * are bit-identical, and r4d_selftest compares their bytes. */ +/* The gather's form, pinnable for tests: 0 the launcher's rule, 1 gather_kernel (a column per + * thread), 2 gather_wide_kernel (a wave per token). The rule takes 2 past the self-scan bound where + * the shape allows (r4d_rad_moe_gather); an impossible pin is refused. Both are bit-identical + * (r4d_selftest). */ static int g_moe_gather_pin = 0; extern "C" void r4d_moe_gather_pin_form(int form) { g_moe_gather_pin = form; } @@ -2735,9 +2368,8 @@ extern "C" int r4d_rad_router_topk(const RadArgs* a, RadStream s) { const long long norm = r4d_geti_or(a, "norm", 0); if (n_expert <= 0 || n_expert > (long long)kMaxExpert || top_k <= 0 || top_k > n_expert) return R4D_NO(RAD_E_SHAPE); - /* The key packs `~e` into sixteen bits, so an expert id has to fit there: kMaxExpert is 512 - * and the refusal above is what holds it. top_k is bounded by the wave, because round r parks - * its winner on lane r. */ + /* The key packs `~e` into sixteen bits, which the kMaxExpert check above guarantees. top_k is + * bounded by the wave, since round r parks its winner on lane r. */ if (top_k > (long long)kWave) return R4D_NO(RAD_E_SHAPE); if (lg->dtype != RAD_BF16 || w->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); if (ids->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE); @@ -2750,8 +2382,7 @@ extern "C" int r4d_rad_router_topk(const RadArgs* a, RadStream s) { constexpr uint32_t NW = 4; const dim3 grid((unsigned)((M + NW - 1) / NW)), blk(NW * kWave); - /* THE NARROWEST INSTANTIATION THAT COVERS n_expert, because the wider one costs eight - * registers a lane for nothing on a 256-expert model. */ + /* The narrowest instantiation covering n_expert; the wider costs eight registers per lane. */ if (n_expert <= (long long)(8 * kWave)) hipLaunchKernelGGL((router_topk_kernel), grid, blk, 0, (hipStream_t)s, (const uint16_t*)lg->data, (int32_t*)ids->data, (uint16_t*)w->data, @@ -2787,14 +2418,13 @@ static int protect_of(const RadArgs* a, long long n_local, Protect* p) { return RAD_OK; } -/* THE PAIR IN ONE LAUNCH. Operands are the two ops' own, concatenated with the selection's first: - * logits -> expert_ids, expert_w, sorted_tok, expert_offset, expert_count. Every check below is - * one of the two shims' checks; nothing new is asserted, because nothing new is computed. +/* The pair in one launch. Operands are the two ops' own, selection first: logits -> expert_ids, + * expert_w, sorted_tok, expert_offset, expert_count. The checks are the two shims' checks. * - * IT REFUSES rather than falls back when the sort would not fit one workgroup. A silent fallback - * would make the op's cost depend on a bound the caller cannot see, and the architecture already - * asks the same question before declaring it (`moe_fuse_rows`). */ -static int rad_router_topk_scatter_body(const RadArgs* a, const R4dSink& sk) { + * It refuses, rather than falls back, when the sort would not fit one workgroup, so the op's cost + * does not hinge on a hidden bound; the architecture checks the same before declaring it + * (`moe_fuse_rows`). */ +extern "C" int r4d_rad_router_topk_scatter(const RadArgs* a, RadStream stream) { int emit_rc = RAD_OK; const RadTensor* lg = r4d_opt(a, 0); const RadTensor* ids = r4d_opt(a, 1); @@ -2807,7 +2437,7 @@ static int rad_router_topk_scatter_body(const RadArgs* a, const R4dSink& sk) { return R4D_NO(RAD_E_INVAL); const long long n_expert = r4d_geti_or(a, "n_expert", 0); - /* Absent means "no expert parallelism", where the slice IS the router. */ + /* Absent means no expert parallelism: the slice is the whole router. */ const long long n_local = r4d_geti_or(a, "n_local", n_expert); const long long top_k = r4d_geti_or(a, "top_k", 0); const long long norm = r4d_geti_or(a, "norm", 0); @@ -2837,21 +2467,19 @@ static int rad_router_topk_scatter_body(const RadArgs* a, const R4dSink& sk) { if (r4d_numel(off) < n_local + 1 || r4d_numel(cnt) < n_local) return R4D_NO(RAD_E_SHAPE); #define R4D_RTS_L(OWN, NWV) \ - emit_rc = R4D_EMIT(sk, (router_topk_scatter_kernel), dim3(1), \ + emit_rc = R4D_EMIT(stream, (router_topk_scatter_kernel), dim3(1), \ dim3((NWV) * kWave), 0, \ (const uint16_t*)lg->data, (int32_t*)ids->data, \ (uint16_t*)w->data, (int32_t*)sorted->data, (int32_t*)off->data, \ (int32_t*)cnt->data, (uint32_t)M, (uint32_t)n_expert, \ (uint32_t)n_local, (uint32_t)top_k, \ (uint32_t)lg_ld, (int)norm, (int32_t)base, prot) - /* The same narrowest-instantiation rule the standalone selection uses, and for the same - * reason: MAXOWN is registers a lane. + /* The narrowest instantiation, as in the standalone selection. * - * ONE WAVE A ROW, as a power of two between the sort's own eight waves and the workgroup's - * thirty-two. A wave selects its rows one after another, so at eight waves a 32-row verify - * step runs four selections back to back: 8.6 us against 5.4 at thirty-two waves. Fewer rows do - * not pay for more waves -- a launch of thirty-two costs about 0.4 us more than one of eight at - * four rows. Above 32 rows the waves wrap. */ + * One wave per row, rounded to a power of two between 8 and 32 waves: a wave selects its rows + * serially, so a 32-row verify step at eight waves runs four selections back to back (8.6 us + * against 5.4 at 32 waves), while extra waves cost ~0.4 us at four rows. Above 32 rows the + * waves wrap. */ const int nw = M <= 8 ? 8 : M <= 16 ? 16 : 32; if (n_expert <= (long long)(8 * kWave)) { if (nw == 8) R4D_RTS_L(8, 8); @@ -2864,14 +2492,12 @@ static int rad_router_topk_scatter_body(const RadArgs* a, const R4dSink& sk) { } #undef R4D_RTS_L if (emit_rc != RAD_OK) return emit_rc; - if (!sk.desc) R4D_MOE_CHK(); + R4D_MOE_CHK(); return RAD_OK; } -R4D_ENTRY(r4d_rad_router_topk_scatter, rad_router_topk_scatter_body) -/* Scratch for the general scatter: the per-tile histogram plane. The small form needs none, and - * the hook answers for the shape it is asked about rather than for the worst case, because the - * band the op resolves in is what sizes the arena. */ +/* Scratch for the general scatter: the per-tile histogram plane (none for the small form). Sized + * for the shape asked about, since the resolved band sizes the arena. */ static int scatter_dims(const RadArgs* a, long long* T, long long* n_expert) { const RadTensor* ids = r4d_opt(a, 0); *n_expert = r4d_geti_or(a, "n_expert", 0); @@ -2909,9 +2535,8 @@ extern "C" int r4d_rad_moe_scatter(const RadArgs* a, RadStream s) { if (rc != RAD_OK) return rc; if (r4d_numel(sorted) < T) return R4D_NO(RAD_E_SHAPE); if (r4d_numel(off) < n_expert + 1 || r4d_numel(cnt) < n_expert) return R4D_NO(RAD_E_SHAPE); - /* THIS RANK'S FIRST EXPERT, subtracted from every routed id so that everything downstream -- - * the offsets, the counts, the weight table -- is indexed locally. 0 is the whole-model case, - * without expert parallelism. */ + /* This rank's first expert, subtracted from every routed id so offsets, counts and the weight + * table are indexed locally. 0 without expert parallelism. */ const long long base = r4d_geti_or(a, "expert_base", 0); if (base < 0) return R4D_NO(RAD_E_SHAPE); Protect prot; @@ -2950,9 +2575,9 @@ extern "C" int r4d_rad_moe_scatter(const RadArgs* a, RadStream s) { return RAD_OK; } -/* The weight-table operand, read off the tensor the core built. A zero leading stride is the - * marker for a pointer array (abi/rad_runtime.h, RAD_WTAB); anything else is a stacked plane and - * the stride is in ELEMENTS of the weight's dtype, which for E4M3 is bytes. */ +/* The weight-table operand from the core's tensor. A zero leading stride marks a pointer array + * (abi/rad_runtime.h, RAD_WTAB); otherwise it is a stacked plane with the stride in elements of the + * weight's dtype (bytes for E4M3). */ static int wtab_of(const RadTensor* t, uint32_t dtype, int bits, long long n_expert, long long rows, long long cols, const void* const** tab, size_t* stride0, long long* ld) { @@ -2962,120 +2587,72 @@ static int wtab_of(const RadTensor* t, uint32_t dtype, int bits, long long n_exp return R4D_NO(RAD_E_SHAPE); if (t->stride[2] != 1) return R4D_NO(RAD_E_STRIDE); *tab = (const void* const*)t->data; - /* THE ELEMENT WIDTH IS PASSED IN, not looked up. A plugin-private dtype -- which the 4-bit - * expert plane is -- is not in the core's table, so rad_dtype_bits() answers 0 for it and a - * stacked stride would collapse to the very zero that marks a POINTER ARRAY. The bits are - * multiplied before the divide so a four-bit plane keeps its half-byte. */ + /* The element width is passed in: for a plugin-private dtype such as the 4-bit plane, + * rad_dtype_bits() returns 0 and a stacked stride would collapse to the zero that marks a + * pointer array. Bits are multiplied before the divide so a 4-bit plane keeps its half-byte. */ *stride0 = (size_t)((t->stride[0] * (int64_t)bits) / 8); *ld = t->stride[1]; return RAD_OK; } -/* ---- AL: ONE RUN A BLOCK, SO A STREAMED EXPERT'S WEIGHT CROSSES THE LINK ONCE ----------------- +/* ---- AL: one run per block, so a streamed expert's weight crosses the link once ----------------- * - * The uniform row grid above puts a block on rows [i*FM, i*FM + FM) whatever expert those rows - * belong to, so a run that straddles a tile boundary is served by TWO blocks and its weight is - * staged twice. The kernel's tile note counts that as `n_expert + T/FM` incidences against an - * optimum of `n_expert`, and for a resident expert a duplicated tile is not worth a prefix-sum - * pass and an extra launch a layer. + * The uniform row grid serves a run straddling a tile boundary with two blocks, staging its weight + * twice. For a resident expert the second staging is an L2/MALL hit, but for a pooled one it is + * another pass over PCIe (~26 GB/s against VRAM's 576). At a 2048 chunk the grid has 414 + * incidences over 254 experts, so a third of the link traffic would be re-reads. * - * THAT IS TRUE OF A RESIDENT EXPERT AND FALSE OF A POOLED ONE. A second staging of a weight that - * is in VRAM is an L2 or MALL hit. A second staging of one that is not is another pass of its - * whole shard over PCIe, and the two differ by more than an order of magnitude: on this part the - * streamed read runs at about 26 GB/s against VRAM's 576. At the shipped 2048 chunk the - * grid is 160 tiles over 254 experts, so the incidence count is 414 against 254 -- a THIRD of the - * link traffic is a re-read of weight a neighbouring block already pulled. + * So a block map gives one run per block: entry i names (expert, first row) and the block serves + * rows [first, min(first + FM, off[e+1])); an expert is staged by two blocks only if its run is + * longer than FM. This costs no extra activation traffic (stage8_load skips rows outside the run), + * no extra arithmetic (the uniform grid already runs a full tile per covered run), and no + * determinism (each output row still comes from one block and one expert in the same K order). * - * So a block map is built here, and it is one run a block: - * entry i names (expert, first row), the block serves rows [first, min(first + FM, off[e+1])), and - * no expert is ever staged by two blocks unless its own run is longer than FM. + * The grid is an upper bound, `n_expert + T/FM` (each expert one block plus one per FM rows), since + * the true count needs the offsets on the host; the map's first slot holds the real count and + * extra blocks exit at the head. * - * WHAT IT DOES NOT COST: - * - * * NOT ACTIVATION TRAFFIC. An aligned block still stages FM rows, but `stage8_load` takes a - * live flag and issues no load at all for a row outside the run -- so the bytes read are the - * LIVE rows either way, and the block count does not enter it. - * * NOT ARITHMETIC. The uniform grid already runs the whole FM tile once per run it covers, with - * the rows of the other runs masked. At the shipped chunk that is 160 tiles x ~1.6 runs = 256 - * full-tile passes; aligned it is 254, one a run. The dead-row work is the same work. - * * NOT DETERMINISM. Every output row is still produced by one block, from one expert, with the - * same K order -- only which workgroup does it moves, exactly as the ES split above. The - * result is bit-identical. - * - * THE GRID IS AN UPPER BOUND AND THE COUNT IS ON THE DEVICE. `sum_e ceil(run_e / FM)` cannot be - * known on the host without reading the offsets back, which is a synchronisation a step does not - * have. It is bounded by `n_expert + T/FM` -- every expert contributes one block plus at most one - * more per FM rows -- so the launcher uses that, the map's first slot carries the real count, and - * blocks past it exit at the head. Those are a few hundred empty workgroups on a grid of tens of - * thousands. - * - * ROWS NO EXPERT OWNS still have to be zeroed: `off[n_expert]` is the live row count and anything - * above it is a dropped slot whose output row must not be whatever the arena left there. The map - * carries them as entries with expert `kMapTail`, and such a block zeroes and returns. */ + * Rows past `off[n_expert]` (dropped slots) must still be zeroed: the map carries them as entries + * with expert `kMapTail`, whose block zeroes and returns. */ - -/* THE PREFILL TILE'S ROWS -- see "THE PREFILL TILE IS 32 ROWS BY 64 COLUMNS" at the kernel. */ +/* The prefill tile's rows; see the prefill-tile note at the kernel. */ constexpr long long kPrefillRows = 32; -/* ...AND 128 COLUMNS OVER EIGHT WAVES where a column tile cannot straddle two stacked parts of the - * weight. A wave's share is what the 64-column tile's four waves each had -- one 16-row tile by two - * 16-column ones -- so the arithmetic of every element is unchanged; what the wider block buys is - * the rows' activation staged once for twice the columns, and half the blocks. r4d_selftest - * --perfmoe, rank 0's tp2 shape, 512 experts, top 10, us a call (gate_up / down), same bytes: - * - * tokens 512 1024 2048 4096 - * 32 x 64, 4 waves 822 / 491 898 / 620 1305 / 884 2255 / 1477 - * 32 x 128, 8 waves 780 / 468 868 / 582 1242 / 845 2133 / 1450 - * - * Four waves over 128 columns (two a wave across 64) are within ~3% of the 64-column tile at forty - * rows a run and slower at twenty: the width is only worth it with the waves to go with it. */ +/* ...and 128 columns over eight waves where a column tile cannot straddle two stacked weight parts. + * Each wave's share is unchanged (one 16-row by two 16-column tiles), so every element's arithmetic + * is the same; the wider block stages the activation once for twice the columns, with half the + * blocks (~5% faster per call at 512-4096 tokens). 128 columns over only four waves is no better. */ constexpr long long kPrefillCols = 128; -/* WHERE THE (tile, run) DECODE GRID ENDS AND THE RUN-ALIGNED PREFILL GRID BEGINS: at an average of - * one and a half routed rows an expert. At file scope because the scratch hook and the launcher - * must answer for the SAME band -- a hook that sized a map for a shape the launcher then ran the - * other form on would be arena charged to nothing, and the reverse would be a launcher finding - * scratch it was not given. +/* Where the (tile, run) decode grid ends and the run-aligned prefill grid begins: an average of 1.5 + * routed rows per expert. At file scope because the scratch hook and the launcher must agree on + * the band. * - * THE CROSSOVER IS A RUN LENGTH, NOT A TOKEN COUNT. The decode form gives every run its own block - * and a 16-row tile; the prefill form gives it a 32-row tile. Where runs are a row or two the - * narrower tile wins, and once they are several rows the wider one does. --perfmoe at 512 - * experts, gate_up + down in us: + * The crossover is a run length, not a token count: 16-row tiles win for runs of a row or two, + * 32-row tiles for several rows. Measured at 512 experts (gate_up + down, us): * * T (rows) 640 800 1000 1280 2560 5120 * decode form 804 900 1006 1113 1541 2224 * prefill form 826 900 981 1053 1247 1413 * - * So the band is T <= 1.5 * n_expert: 768 rows here. The decode envelope is - * `max_num_seqs * (1 + n_spec) * top_k` -- 320 rows at eight sequences, depth 3 and top 10 -- so - * a decode step stays on the decode form with room; a server with a few dozen concurrent - * sequences crosses onto the prefill form exactly where that form is the faster one. */ + * So the band is T <= 1.5 * n_expert (768 rows here). Decode is at most + * `max_num_seqs * (1 + n_spec) * top_k` (320 rows at eight sequences, depth 3, top 10). */ static inline bool r4d_moe_decode_band(long long T, long long n_expert) { return 2 * T <= 3 * n_expert; } -/* THE ROW LIMIT OF TWO 128-WIDE K BLOCKS A PASS, by weight format: the decode form of the - * TOKEN-operand projection (gate_up) stages two blocks a pass instead of one -- see FK at the - * kernel -- at most this many routed rows. Only a shape whose weight format already folds scale - * groups (W4 2 to 4) and whose every class's K is a multiple of 256 can take two; anything else - * keeps one block. The two are bit-identical. A constant, so a recorded pass and a live one take - * the same kernel. +/* Row limit, per weight format, for staging two 128-wide K blocks per pass (FK 256) in the decode + * form of the token-operand projection (gate_up). Only formats that already fold scale groups + * (W4 2-4) with every class's K a multiple of 256 qualify. Bit-identical either way; a constant, so + * recorded and live passes take the same kernel. * - * MEASURED, `r4d_selftest --perfmoe M` on gfx1201 at rank 0's tp2 width split (512 experts, top - * 10), gate_up in us, one block a pass / two: - * - * tokens (rows) 1 (10) 2 (20) 4 (40) 8 (80) 16 (160) 32 (320) - * w4nl64a8h (2) 17.9/15.6 25.6/22.4 36.4/37.3 65.6/67.8 164.6/170.2 328.7/310.8 - * w4nl32a8h (3) 19.5/17.0 26.2/24.0 40.0/40.5 71.6/77.7 177.9/177.5 337.0/321.0 - * w5nl64a8h (4) 20.3/17.6 30.0/25.5 122.3/43.1 212.9/78.6 373.2/219.8 672.3/380.5 - * - * The four-bit formats gain at one and two tokens and not in between, which is where a - * speculative decode step sits (one sequence at depth 3 is 40 rows); the five-bit format's one - * block a pass is two to three times slower from 40 rows on, and two blocks are the faster at - * every row count. */ + * Measured (gate_up, us, one block / two): the 4-bit formats gain at 10-20 rows but not at 40-160 + * (e.g. w4nl64a8h 17.9/15.6 at 10 rows, 36.4/37.3 at 40); the 5-bit format is 2-3x faster with two + * blocks from 40 rows on (122.3/43.1 at 40) and faster at every row count. In a whole decode step + * the 4-bit formats still take two blocks up to 80 rows (two sequences at depth 3): on Flash-Next + * (w4nl64a8h) a one-stream step at depth 3 is 1.1% shorter at TP4 and no slower at TP2. */ template -constexpr long long kMoeGuFk256Rows = W4 == 4 ? (1ll << 40) : (W4 == 2 || W4 == 3) ? 20 : 0; -/* THE STAGED K OF THE DECODE FORM, pinned for a test: 0 is kMoeGuFk256Rows's rule, 1 one 128-wide - * block a pass, 2 two wherever the shape allows it. r4d_selftest compares the two byte for byte, - * so the two-block path is held to the one-block bytes whatever the row limit is. */ +constexpr long long kMoeGuFk256Rows = W4 == 4 ? (1ll << 40) : (W4 == 2 || W4 == 3) ? 80 : 0; +/* The decode form's staged K, pinnable for tests: 0 kMoeGuFk256Rows's rule, 1 one 128-wide block + * per pass, 2 two wherever allowed. r4d_selftest compares both byte for byte. */ static int g_moe_fk_pin = 0; template static inline bool r4d_moe_gu_fk256(long long T, bool a_sorted) { @@ -3083,68 +2660,45 @@ static inline bool r4d_moe_gu_fk256(long long T, bool a_sorted) { if (g_moe_fk_pin == 2) return true; return T <= kMoeGuFk256Rows; } -/* THE SORTED-OPERAND PROJECTION'S DECODE KERNEL, and its column tiles a block. The decode form of - * down -- the sorted operand, one part, at most kMaxExpert experts -- is moe_down_dec_kernel: a - * block a 16-row tile of a run and G 64-column tiles a block, see its note. Any other shape takes - * the (tile, run) form. G follows the routed-row count: one below kMoeDownDecG2Rows, two below - * kMoeDownDecG4Rows, four from there, which keeps a few thousand working blocks from one sequence - * to sixteen. Bit-identical to the (tile, run) form at every G. Constants, so a recorded pass and - * a live one take the same kernel. +/* The sorted-operand projection's decode kernel and its column tiles per block. The decode form of + * down (sorted operand, one part, at most kMaxExpert experts) is moe_down_dec_kernel; any other + * shape takes the (tile, run) form. G follows the routed-row count: one below kMoeDownDecG2Rows, + * two below kMoeDownDecG4Rows, four above, keeping a few thousand working blocks from one sequence + * to sixteen. Bit-identical at every G; constants, so recorded and live passes agree. * - * MEASURED at TP4 on four R9700 (gfx1201), MTP depth 3, end to end: ms a decode step with this - * rule against the (tile, run) form at the same concurrency. - * - * concurrent sequences 4 8 16 - * ms a step -0.9% -3.1% -7.8% - * - * At TP2 on two R9700, Qwen3.8-Flash-Next, MTP depth 3, distinct prompts a sequence, the same - * measure (one window each; boot to boot the same arm moves about 0.5%): - * - * concurrent sequences 1 4 6 8 - * (tile, run) form 14.78 25.64 - 36.15 ms a step - * this rule 14.64 25.53 - 36.26 - * G = 1 always - - 31.58 36.37 - * G = 2 always - 25.59 31.17 36.15 - * G = 4 always - - 31.66 36.48 - * - * Nothing at TP2 moves by more than that noise, so the TP4 thresholds stand: a rank holding twice - * each expert's width already keeps its blocks busy at the (tile, run) form's grid. */ + * At TP4 (MTP depth 3) this saves 0.9%, 3.1% and 7.8% of a decode step at 4, 8 and 16 sequences. + * At TP2 differences are within noise (a rank holding twice each expert's width already keeps the + * (tile, run) grid busy), so the TP4 thresholds stand. */ constexpr long long kMoeDownDecG2Rows = 200; constexpr long long kMoeDownDecG4Rows = 480; /* G's bound: the kernel keeps its column tiles in one 32-bit mask. */ constexpr long long kMoeDownDecMaxG = 16; -/* THE SORTED OPERAND'S DECODE KERNEL, pinned for a test: 0 is the rule above, -1 the (tile, run) - * form, n > 0 moe_down_dec_kernel at n column tiles a block (capped at kMoeDownDecMaxG). A pin to - * the kernel on a shape it does not serve is refused. */ +/* The sorted operand's decode kernel, pinnable for tests: 0 the rule above, -1 the (tile, run) + * form, n > 0 moe_down_dec_kernel with n column tiles per block (capped at kMoeDownDecMaxG). A pin + * on an unsupported shape is refused. */ static int g_moe_down_dec_pin = 0; static inline long long r4d_moe_down_dec_g(long long T) { if (g_moe_down_dec_pin < 0) return 0; if (g_moe_down_dec_pin > 0) return g_moe_down_dec_pin; return T >= kMoeDownDecG4Rows ? 4 : T >= kMoeDownDecG2Rows ? 2 : 1; } -/* THE MAP'S UPPER BOUND, stated once because the scratch hook and the launcher must agree about - * it exactly: a hook that answers for a different shape than the launch uses is how a kernel ends - * up writing past the arena it was given. Every expert contributes one block, plus one more for - * each FM rows its run exceeds; the dropped-slot tail contributes at most T/FM and one more. */ +/* The map's upper bound, defined once so the scratch hook and the launcher agree exactly (or the + * kernel writes past its arena). Each expert contributes one block plus one per FM rows beyond the + * first; the dropped-slot tail at most T/FM plus one. */ static inline long long r4d_blockmap_cap(long long T, long long n_expert, long long FM) { return n_expert + (T + FM - 1) / FM + 1; } -/* One count slot, then two uint32 an entry. */ +/* One count slot, then two uint32 per entry. */ static inline long long r4d_blockmap_bytes(long long cap) { return (1 + 2 * cap) * (long long)sizeof(uint32_t); } - -/* ONE WORKGROUP, because the whole of it is a scan over at most kMaxExpert counters and a second - * launch to split that across the device would cost more than the scan does. The offsets are read - * once, in parallel, so the scan is not 512 dependent global loads. The launch is NT threads, a - * thread owning experts tid, tid + NT, ... +/* One workgroup: the job is a scan over at most kMaxExpert counters, cheaper than a second launch. + * NT threads, thread tid owning experts tid, tid + NT, ...; offsets are read once, in parallel. * - * THE PREFIX IS PARALLEL: a DPP scan in each wave and one exchange of the wave totals, 256 counts - * a tile -- three tiles at 512 experts, whose n_expert + 1 counts end one past the second. On one - * thread it is 513 dependent LDS round trips in front of a GEMM that waits for the map, and the map - * is built twice a routed layer. Integers: the offsets have one answer whatever order the sums are - * formed in. */ + * The prefix is parallel (a DPP scan per wave and one exchange of wave totals, 256 counts per tile; + * three tiles at 512 experts), not 513 dependent LDS round trips on one thread ahead of a GEMM that + * waits for the map. Integer sums are order-independent. */ __global__ __launch_bounds__(256) void moe_blockmap_kernel( const int32_t* __restrict__ off, uint32_t n_expert, uint32_t T, uint32_t FM, uint32_t cap, uint32_t* __restrict__ map) { @@ -3153,12 +2707,9 @@ __global__ __launch_bounds__(256) void moe_blockmap_kernel( __shared__ int32_t s_wt[kTiles][NW]; const uint32_t tid = threadIdx.x, lane = tid % kWave, wave = tid / kWave; - /* EVERY OFFSET THIS THREAD NEEDS IN ONE ROUND OF LOADS: both ends of each expert it owns - * (e = tid + i * NT), the index clamped so every load is unconditional, all issued before the - * first is waited on. A loop over e that stores each offset to LDS before the next load makes - * one dependent trip to memory per expert a thread owns -- three at 512 experts -- and the - * offsets are read cold, straight after the router wrote them. The counts and the map's rows - * then come from these registers, so the offsets never pass through LDS. */ + /* Every offset this thread needs in one round of loads: both ends of each expert it owns + * (e = tid + i * NT), index clamped so every load is unconditional, all issued before the first + * wait. Counts and map rows come from these registers; offsets never pass through LDS. */ int32_t lo[kTiles], hi[kTiles]; #pragma unroll for (uint32_t i = 0; i < kTiles; ++i) { @@ -3167,8 +2718,7 @@ __global__ __launch_bounds__(256) void moe_blockmap_kernel( hi[i] = off[e + 1 < n_expert ? e + 1 : n_expert]; } const uint32_t live = (uint32_t)off[n_expert]; - /* Blocks this expert needs. A zero-row run needs none, and asking for one would put an empty - * block in the map that the GEMM would then have to recognise. */ + /* Blocks this expert needs; a zero-row run needs none. */ #pragma unroll for (uint32_t i = 0; i < kTiles; ++i) { const uint32_t e = tid + i * NT; @@ -3178,8 +2728,8 @@ __global__ __launch_bounds__(256) void moe_blockmap_kernel( if (tid == 0) s_cnt[n_expert] = T > live ? (T - live + FM - 1) / FM : 0u; __syncthreads(); - /* Exclusive scan over the n_expert + 1 counts, a tile of NT at a time. Each tile has its own - * exchange slots, so no tile's writes meet the reads of the one before it. */ + /* Exclusive scan over the n_expert + 1 counts, NT at a time. Each tile has its own exchange + * slots, so a tile's writes never meet the previous tile's reads. */ uint32_t carry = 0; for (uint32_t b = 0, tl = 0; b <= n_expert; b += NT, ++tl) { const uint32_t e = b + tid; @@ -3222,25 +2772,22 @@ __global__ __launch_bounds__(256) void moe_blockmap_kernel( } } -/* WHICH FORM A LAUNCH TAKES: 0 is the rule; for a test, 1 pins the run-aligned prefill form, 2 the - * (tile, run) decode form and 3 the uniform prefill grid, whatever the band. r4d_selftest --perfmoe - * times each on one input and compares it with form 1: all three must match byte for byte. */ +/* Launch form: 0 the rule; for tests, 1 pins the run-aligned prefill form, 2 the (tile, run) + * decode form, 3 the uniform prefill grid, whatever the band. r4d_selftest --perfmoe requires all + * three to match byte for byte. */ static int g_moe_prefill_form = 0; -/* THE ALIGNED FORM'S COLUMN TILE, pinned for a test: 0 is the launcher's shape rule, 1 never the - * down projection's 256-column tile (the 128- or 64-column one), 2 the 256-column tile, refused - * where the shape cannot take it or the launch is not the aligned form. r4d_selftest compares the - * two byte for byte. */ +/* The aligned form's column tile, pinnable for tests: 0 the launcher's rule, 1 never the down + * projection's 256-column tile (use 128 or 64), 2 the 256-column tile (refused where the shape + * cannot take it or the launch is not aligned). r4d_selftest compares them byte for byte. */ static int g_moe_down_tile_pin = 0; -/* Both instantiations, from one body. The only things that differ are the weight table's dtype and - * its two pitches, so the fp8 launcher and the w4 one are the same forty lines with three values - * swapped -- and writing them twice is how a shape check drifts between two paths that must agree. +/* One body for the fp8 and w4 launchers, which differ only in the weight dtype and its two + * pitches, so their shape checks cannot drift apart. * - * `ncls` is the op's class count: 2 for `moe_gemm_q`, whose odd class is operands 6 and 7 at - * N_odd/K_odd, and 4 for `moe_gemm_q_mod4`, whose classes 1..3 are operands 6/7, 8/9 and 10/11 at - * N_1/K_1, N_2/K_2 and N_3/K_3, with `y` after them at 12. Everything else is one body. */ + * `ncls` is the class count: 2 for `moe_gemm_q` (odd class = operands 6 and 7 at N_odd/K_odd), 4 + * for `moe_gemm_q_mod4` (classes 1..3 = operands 6/7, 8/9, 10/11 at N_1/K_1 .. N_3/K_3, `y` at 12). */ template -static int moe_gemm_launch(const RadArgs* a, const R4dSink& sk, int ncls = 2) { +static int moe_gemm_launch(const RadArgs* a, RadStream stream, int ncls = 2) { int emit_rc = RAD_OK; if (ncls != 2 && ncls != 4) return R4D_NO(RAD_E_INVAL); const RadTensor* Aq = r4d_opt(a, 0); @@ -3260,8 +2807,8 @@ static int moe_gemm_launch(const RadArgs* a, const R4dSink& sk, int ncls = 2) { if (!Aq->data || !As->data || !sorted->data || !off->data || !Y->data) return R4D_NO(RAD_E_INVAL); - /* Each class's weight geometry, the others defaulting to class 0's; the output is as wide as - * the widest class and the activation as long as the longest K. */ + /* Each class's weight geometry (defaulting to class 0's); the output is as wide as the widest + * class and the activation as long as the longest K. */ static const char* const kNk[4][2] = { { "N", "K" }, { "N_1", "K_1" }, { "N_2", "K_2" }, { "N_3", "K_3" } }; long long Nc[4] = { 0, 0, 0, 0 }, Kc[4] = { 0, 0, 0, 0 }; @@ -3300,27 +2847,24 @@ static int moe_gemm_launch(const RadArgs* a, const R4dSink& sk, int ncls = 2) { if (as_ld < 0 || Ms < M) return R4D_NO(RAD_E_STRIDE); if (r4d_numel(sorted) < T || r4d_numel(off) < n_expert + 1) return R4D_NO(RAD_E_SHAPE); - /* WHICH ROWS THE ACTIVATION HAS. Checked, not inferred: an operand a row short is the caller - * having handed the down projection the gate_up projection's buffer, and refusing it by name - * here is the only place that reads as what it is. */ + /* The activation's row count is checked, not inferred: a short operand means the caller passed + * the gate_up projection's buffer to the down projection. */ const char* ord = r4d_gets(a, "a_order"); const bool a_sorted = ord && !std::strcmp(ord, "sorted"); if (ord && !a_sorted && std::strcmp(ord, "token")) return R4D_NO(RAD_E_UNSUPPORTED); if (M < (a_sorted ? T : (T + top_k - 1) / top_k)) return R4D_NO(RAD_E_SHAPE); - /* WHICH TABLE THE CODES INDEX, read off the dtype the layout hook accepted the weight under: - * w4nla8h's levels, w5nl64a8h's magnitudes, or two's complement for w4a8 and w4a8h. The schema - * admits no other. */ + /* The code table, from the dtype the layout hook accepted: w4nla8h's levels, w5nl64a8h's + * magnitudes, or two's complement for w4a8 and w4a8h. */ const char* wdt = r4d_gets(a, "dtype"); const uint32_t* tab = W4 == 4 ? kW5nlMagPerm : (W4 && wdt && (!std::strcmp(wdt, "w4nla8h") || !std::strcmp(wdt, "w4nl64a8h") || !std::strcmp(wdt, "w4nl32a8h"))) ? kW4nlPerm : kW4IntPerm; - /* One class's tables. THE WEIGHT PITCH THE KERNEL WANTS IS IN BYTES, and for a 4-bit plane - * that is half the element count, for the 5-bit one five eighths. `wtab_of` reports the - * declared element stride, so the scaling happens here, once, where the forms are side by - * side. */ + /* One class's tables. The kernel wants the weight pitch in bytes: half the element count for a + * 4-bit plane, five eighths for the 5-bit one. `wtab_of` reports the declared element stride, + * so the scaling happens here. */ auto cls_of = [&](const RadTensor* w, const RadTensor* ws, long long cnt, long long n, long long k, MoeCls* c) -> int { long long w_ld = 0, ws_ld = 0; @@ -3330,21 +2874,20 @@ static int moe_gemm_launch(const RadArgs* a, const R4dSink& sk, int ncls = 2) { W4 == 4 ? 5 : W4 ? 4 : 8, cnt, n, k, &c->w, &w_s0, &w_ld); if (rc != RAD_OK) return rc; if constexpr (W4 >= 2) { - /* One E4M3 byte per (row, group of 64 or 32 K), and the stored row is exactly those - * bytes. THE PITCH IS DERIVED, NOT READ: the scale view selects two planes, so the - * engine declares it at the weight's logical [n, k] and hands it over at that shape -- - * its row stride is k, the stored row k/64 or k/32 (r4d_layout.cpp). A tile's scales - * are one sixteen- or thirty-two-bit word, so the kernel's pitch is k/128 words. */ + /* One E4M3 byte per (row, group of 64 or 32 K). The pitch is derived, not read: the + * scale view arrives at the weight's logical [n, k] (row stride k) while the stored row + * is k/64 or k/32 bytes (r4d_layout.cpp). A tile's scales are one 16- or 32-bit word, + * so the kernel's pitch is k/128 words. */ rc = wtab_of(ws, RAD_F8E4M3, 8, cnt, n, k / (kBlock / (W4 == 3 ? 4 : 2)), &c->s, &s_s0, &ws_ld); if (rc != RAD_OK) return rc; - /* A 5-bit row is its nibbles then its sign bits, so its pitch is whole bytes of both; - * the kernel finds the signs K/2 bytes in. */ + /* A 5-bit row is its nibbles then its sign bits; the kernel finds the signs K/2 bytes + * in. */ if (W4 == 4 ? (w_ld % 8 || k % 32) : (w_ld % 2)) return R4D_NO(RAD_E_STRIDE); w_ld = W4 == 4 ? w_ld / 8 * 5 : w_ld / 2; ws_ld = k / kBlock; } else if constexpr (W4) { - /* The scale plane is one bf16 per (row, group of 128 K) -- not per 128x128 tile. */ + /* The scale plane is one bf16 per (row, 128 of K), not per 128x128 tile. */ rc = wtab_of(ws, RAD_BF16, 16, cnt, n, k / kBlock, &c->s, &s_s0, &ws_ld); if (rc != RAD_OK) return rc; if (w_ld % 2) return R4D_NO(RAD_E_STRIDE); @@ -3364,8 +2907,8 @@ static int moe_gemm_launch(const RadArgs* a, const R4dSink& sk, int ncls = 2) { c->s_ld = (uint32_t)ws_ld; return RAD_OK; }; - /* Class q holds the experts e with e % ncls == q, entry e / ncls: ceil((n - q) / ncls) of - * them. At two classes the last two are never read and stay zero. */ + /* Class q holds experts e with e % ncls == q at entry e / ncls, ceil((n - q) / ncls) of them. + * At two classes the last two stay zero and unread. */ MoeCls cl[4]{}; for (int q = 0; q < ncls; ++q) { const int rc = cls_of(Wc[q], Wsc[q], (n_expert + ncls - 1 - q) / ncls, Nc[q], Kc[q], @@ -3382,41 +2925,37 @@ static int moe_gemm_launch(const RadArgs* a, const R4dSink& sk, int ncls = 2) { MoeTab tabv{}; for (int i = 0; i < 4; ++i) tabv.v[i] = tab[i]; - /* THE BAND: a decode step takes the (tile, run) form -- one 16-row tile of runs spread over - * blocks, see the kernel's ES note -- and anything with runs of several rows takes the aligned - * 32-row form. r4d_moe_decode_band has the crossover. */ + /* The band: a decode step takes the (tile, run) form (the kernel's ES note) and runs of several + * rows take the aligned 32-row form; r4d_moe_decode_band has the crossover. */ const uint32_t ny = (uint32_t)(N / 64); const int form = g_moe_prefill_form; if ((form == 0 && r4d_moe_decode_band(T, n_expert)) || form == 2) { - /* THE DECODE GRID IS (tile, run) WIDE -- see the kernel's ES note. One tile of rows is all - * a decode step has, so without this the whole layer runs on N/64 workgroups. */ + /* The decode grid is (tile, run) wide (the kernel's ES note); decode has one tile of rows, + * which alone would give only N/64 workgroups. */ const unsigned tiles = (unsigned)((T + 15) / 16); - /* THE SORTED OPERAND'S OWN DECODE KERNEL, a block a run tile and G column tiles -- see - * moe_down_dec_kernel and kMoeDownDecG2Rows. Its grid is the run tiles' upper bound, a - * tile for every run and one more for every 16 rows, and one block for the dropped tail, - * by the column groups. */ + /* The sorted operand's decode kernel (moe_down_dec_kernel, kMoeDownDecG2Rows): the grid is + * the run tiles' upper bound (one per run plus one per 16 rows) plus one tail block, by + * column groups. */ const bool dn_dec = a_sorted && parts == 1 && n_expert <= (long long)kMaxExpert; const long long g2 = r4d_moe_down_dec_g(T); if (!dn_dec && g_moe_down_dec_pin > 0) return R4D_NO(RAD_E_UNSUPPORTED); if (dn_dec && g2 > 0) { const unsigned slots = (unsigned)(std::min(T, n_expert) + (T + 15) / 16); const unsigned groups = (unsigned)((N + 64 * g2 - 1) / (64 * g2)); - emit_rc = R4D_EMIT(sk, (moe_down_dec_kernel), + emit_rc = R4D_EMIT(stream, (moe_down_dec_kernel), dim3(slots + 1u, groups), dim3(4 * kWave), 0, (const uint8_t*)Aq->data, (const float*)As->data, ce, co, c2, c3, (const int32_t*)off->data, (uint16_t*)Y->data, (uint32_t)T, (uint32_t)N, (uint32_t)n_expert, (uint32_t)g2, (uint32_t)a_ld, (uint32_t)as_ld, (uint32_t)y_ld, mode, tabv); if (emit_rc != RAD_OK) return emit_rc; - if (!sk.desc) R4D_MOE_CHK(); + R4D_MOE_CHK(); return RAD_OK; } - /* WHICH INSTANTIATION: the weight from a uniform global base (UW) always; the run search - * in one round trip (RS) up to kMaxExpert experts and the chunked search above that; and - * two 128-wide K blocks a pass where kMoeGuFk256Rows admits the row count, every class's - * K is whole passes of 256 and the format folds scale groups. All of them are - * bit-identical; the function moves with the choice, which a recorded pass sees as a new - * node. */ + /* Instantiation: UW always; RS up to kMaxExpert experts, the chunked search above; two + * 128-wide K blocks per pass where kMoeGuFk256Rows admits the row count, every class's K is + * whole 256-wide passes and the format folds scale groups. All are bit-identical; a + * recorded pass sees a different choice as a new node. */ const bool rs = n_expert <= (long long)kMaxExpert; auto pick = [&](auto fk) { constexpr uint32_t F = decltype(fk)::value; @@ -3429,7 +2968,7 @@ static int moe_gemm_launch(const RadArgs* a, const R4dSink& sk, int ncls = 2) { for (int q = 0; q < ncls; ++q) fk2 = fk2 && Kc[q] % (2 * (long long)kBlock) == 0; if (fk2) kern = pick(std::integral_constant{}); } - emit_rc = R4D_EMIT(sk, kern, + emit_rc = R4D_EMIT(stream, kern, dim3(tiles * 16u, ny), dim3(4 * kWave), 0, (const uint8_t*)Aq->data, (const float*)As->data, ce, co, c2, c3, (const int32_t*)sorted->data, (const int32_t*)off->data, @@ -3437,14 +2976,11 @@ static int moe_gemm_launch(const RadArgs* a, const R4dSink& sk, int ncls = 2) { (uint32_t)T, (uint32_t)N, (uint32_t)n_expert, (uint32_t)top_k, (uint32_t)a_ld, (uint32_t)as_ld, (uint32_t)y_ld, mode, tabv); } else { - /* THE PREFILL FORM IS ALIGNED TO RUNS when the scratch for a map is there, and uniform - * when it is not. A caller that never asked the scratch hook -- a tool replaying a - * recording, a plugin issuing this op by hand -- gets the uniform grid and the same - * answer: a run that straddles a tile is staged by both, and nothing else differs. + /* The prefill form is run-aligned when map scratch is present, uniform otherwise (e.g. a + * caller that never asked the scratch hook); the answer is the same. * - * The map's builder scans the offsets in LDS tables of kMaxExpert + 1 entries, so a wider - * expert count takes the uniform grid whatever scratch it was handed -- the GEMM itself - * reads `off` from global memory and serves any count. */ + * The map builder's LDS tables hold kMaxExpert + 1 entries, so wider expert counts take the + * uniform grid regardless of scratch. */ const long long cap = r4d_blockmap_cap(T, n_expert, kPrefillRows); uint32_t* map = (form != 3 && n_expert <= (long long)kMaxExpert && a->scratch && a->scratch_bytes >= r4d_blockmap_bytes(cap)) @@ -3452,13 +2988,11 @@ static int moe_gemm_launch(const RadArgs* a, const R4dSink& sk, int ncls = 2) { /* The 128-column tile where no column tile straddles two parts of the weight. */ const bool wide_n = (N / parts) % kPrefillCols == 0; const unsigned nyw = (unsigned)(N / kPrefillCols); - /* THE DOWN PROJECTION'S 256-COLUMN TILE, a rule of shape: the sorted operand, one part, a - * w4 weight whose scale is a row's, and every class's width whole tiles of it take 256 - * columns over sixteen waves instead of 128 over eight. Each wave's share is the - * 128-column tile's: one 16-row M tile by two N tiles, the same K passes and the same fold, - * so every element is the same sum in the same order. What the wider block buys is its - * rows' activation and its run's prologue once for twice the columns. Any other shape keeps - * the 128- or 64-column tile. */ + /* The down projection's 256-column tile: the sorted operand, one part, a w4 weight with + * per-row scales and every class's width whole tiles take 256 columns over sixteen waves + * instead of 128 over eight. Each wave's share is unchanged, so every element is the same + * sum; the wider block stages the activation and run prologue once for twice the columns. + * Other shapes keep the 128- or 64-column tile. */ bool dn_wide = W4 != 0 && a_sorted && parts == 1 && N % (2 * kPrefillCols) == 0; for (int q = 0; q < ncls; ++q) dn_wide = dn_wide && Nc[q] % (2 * kPrefillCols) == 0; const int tpin = g_moe_down_tile_pin; @@ -3466,17 +3000,17 @@ static int moe_gemm_launch(const RadArgs* a, const R4dSink& sk, int ncls = 2) { if (tpin == 2 && (!map || !dn_wide)) return R4D_NO(RAD_E_UNSUPPORTED); if (tpin == 1) dn_wide = false; if (map) { - emit_rc = R4D_EMIT(sk, moe_blockmap_kernel, dim3(1), dim3(256), 0, + emit_rc = R4D_EMIT(stream, moe_blockmap_kernel, dim3(1), dim3(256), 0, (const int32_t*)off->data, (uint32_t)n_expert, (uint32_t)T, (uint32_t)kPrefillRows, (uint32_t)cap, map); if (emit_rc != RAD_OK) return emit_rc; - /* Every aligned instantiation reads the weight from a uniform base (UW) and issues its - * first pass at the map read -- see THE ALIGNED FORM'S FIRST PASS at the kernel. */ + /* Every aligned instantiation uses UW and issues its first pass at the map read (see + * the early-weight note at the kernel). */ if (dn_wide) { - /* Only a w4 weight takes it (dn_wide is false otherwise), and the block-fp8 - * instantiation would not compile: its scale is a 128x128 tile's. */ + /* Only a w4 weight takes it (dn_wide is false otherwise); the block-fp8 + * instantiation would not compile, its scale being per 128x128 tile. */ if constexpr (W4 != 0) - emit_rc = R4D_EMIT(sk, (moe_gemm_q_kernel), + emit_rc = R4D_EMIT(stream, (moe_gemm_q_kernel), dim3((unsigned)cap, (unsigned)(N / (2 * kPrefillCols))), dim3(16 * kWave), 0, (const uint8_t*)Aq->data, (const float*)As->data, ce, co, c2, c3, @@ -3485,7 +3019,7 @@ static int moe_gemm_launch(const RadArgs* a, const R4dSink& sk, int ncls = 2) { (uint32_t)T, (uint32_t)N, (uint32_t)n_expert, (uint32_t)top_k, (uint32_t)a_ld, (uint32_t)as_ld, (uint32_t)y_ld, mode, tabv); } else if (wide_n) { - emit_rc = R4D_EMIT(sk, (moe_gemm_q_kernel), + emit_rc = R4D_EMIT(stream, (moe_gemm_q_kernel), dim3((unsigned)cap, nyw), dim3(8 * kWave), 0, (const uint8_t*)Aq->data, (const float*)As->data, ce, co, c2, c3, (const int32_t*)sorted->data, (const int32_t*)off->data, @@ -3493,7 +3027,7 @@ static int moe_gemm_launch(const RadArgs* a, const R4dSink& sk, int ncls = 2) { (uint32_t)T, (uint32_t)N, (uint32_t)n_expert, (uint32_t)top_k, (uint32_t)a_ld, (uint32_t)as_ld, (uint32_t)y_ld, mode, tabv); } else { - emit_rc = R4D_EMIT(sk, (moe_gemm_q_kernel), + emit_rc = R4D_EMIT(stream, (moe_gemm_q_kernel), dim3((unsigned)cap, ny), dim3(4 * kWave), 0, (const uint8_t*)Aq->data, (const float*)As->data, ce, co, c2, c3, (const int32_t*)sorted->data, (const int32_t*)off->data, @@ -3502,7 +3036,7 @@ static int moe_gemm_launch(const RadArgs* a, const R4dSink& sk, int ncls = 2) { (uint32_t)a_ld, (uint32_t)as_ld, (uint32_t)y_ld, mode, tabv); } } else if (wide_n) { - emit_rc = R4D_EMIT(sk, (moe_gemm_q_kernel), + emit_rc = R4D_EMIT(stream, (moe_gemm_q_kernel), dim3((unsigned)((T + kPrefillRows - 1) / kPrefillRows), nyw), dim3(8 * kWave), 0, (const uint8_t*)Aq->data, (const float*)As->data, ce, co, c2, c3, @@ -3511,7 +3045,7 @@ static int moe_gemm_launch(const RadArgs* a, const R4dSink& sk, int ncls = 2) { (uint32_t)T, (uint32_t)N, (uint32_t)n_expert, (uint32_t)top_k, (uint32_t)a_ld, (uint32_t)as_ld, (uint32_t)y_ld, mode, tabv); } else { - emit_rc = R4D_EMIT(sk, (moe_gemm_q_kernel), + emit_rc = R4D_EMIT(stream, (moe_gemm_q_kernel), dim3((unsigned)((T + kPrefillRows - 1) / kPrefillRows), ny), dim3(4 * kWave), 0, (const uint8_t*)Aq->data, (const float*)As->data, ce, co, c2, c3, @@ -3522,21 +3056,16 @@ static int moe_gemm_launch(const RadArgs* a, const R4dSink& sk, int ncls = 2) { } } if (emit_rc != RAD_OK) return emit_rc; - if (!sk.desc) R4D_MOE_CHK(); + R4D_MOE_CHK(); return RAD_OK; } -/* Bytes for the run map, and zero everywhere it is not used. +/* Bytes for the run map, zero where it is not used. * - * T IS COMPUTED FROM THE PARAMETERS, not from an operand, because a scratch hook is called at - * DECLARE with the band's shape and the tensors need not be bound yet. `M * top_k` is the routed - * row count by definition -- the same quantity the launcher reads off Y's row pitch -- so the two - * agree at every shape that reaches the aligned form. - * - * IF THEY EVER DISAGREE THE FAILURE IS SAFE BY CONSTRUCTION, and that is deliberate rather than - * lucky: the launcher checks the scratch it was actually handed against the size the map needs and - * runs the uniform grid when it comes up short. A hook that underestimates costs the optimisation, - * not the arena. + * T comes from the parameters (`M * top_k`, the routed row count), not an operand, since the hook + * runs at declare before tensors are bound; the launcher derives the same count from Y. If they + * ever disagree it is safe: the launcher checks the scratch it was handed and falls back to the + * uniform grid when it is short. */ static int64_t moe_gemm_map_scratch(const RadArgs* a) { const long long n_expert = r4d_geti_or(a, "n_expert", 0); @@ -3559,44 +3088,39 @@ extern "C" void r4d_moe_gemm_pin_down_dec(int pin) { } extern "C" int r4d_rad_moe_gemm_q(const RadArgs* a, RadStream s) { - return moe_gemm_launch<0>(a, r4d_stream_sink(s)); + return moe_gemm_launch<0>(a, s); } -/* The four-bit forms -- w4nl64a8h's and w4nl32a8h's E4M3 scale a 64 or 32 of K, or the others' - * bf16 a 128 -- and the five-bit w5nl64a8h. */ -static int rad_moe_gemm_w4a8_body(const RadArgs* a, const R4dSink& sk) { +/* The four-bit forms (an E4M3 scale per 64 or 32 of K for w4nl64a8h / w4nl32a8h, else a bf16 + * scale per 128) and the five-bit w5nl64a8h. */ +extern "C" int r4d_rad_moe_gemm_w4a8(const RadArgs* a, RadStream stream) { const char* wdt = r4d_gets(a, "dtype"); - if (wdt && !std::strcmp(wdt, "w4nl64a8h")) return moe_gemm_launch<2>(a, sk); - if (wdt && !std::strcmp(wdt, "w4nl32a8h")) return moe_gemm_launch<3>(a, sk); - if (wdt && !std::strcmp(wdt, "w5nl64a8h")) return moe_gemm_launch<4>(a, sk); - return moe_gemm_launch<1>(a, sk); + if (wdt && !std::strcmp(wdt, "w4nl64a8h")) return moe_gemm_launch<2>(a, stream); + if (wdt && !std::strcmp(wdt, "w4nl32a8h")) return moe_gemm_launch<3>(a, stream); + if (wdt && !std::strcmp(wdt, "w5nl64a8h")) return moe_gemm_launch<4>(a, stream); + return moe_gemm_launch<1>(a, stream); } -R4D_ENTRY(r4d_rad_moe_gemm_w4a8, rad_moe_gemm_w4a8_body) -/* `moe_gemm_q_mod4`: the same launches over four classes, by the expert's number mod 4. The run - * map and its scratch are the two-class op's -- they depend on the offsets and nothing else. */ +/* `moe_gemm_q_mod4`: the same launches over four classes, by expert number mod 4. The run map and + * its scratch are the two-class op's, since they depend only on the offsets. */ extern "C" int r4d_rad_moe_gemm_q_mod4(const RadArgs* a, RadStream s) { - return moe_gemm_launch<0>(a, r4d_stream_sink(s), 4); + return moe_gemm_launch<0>(a, s, 4); } -static int rad_moe_gemm_w4a8_mod4_body(const RadArgs* a, const R4dSink& sk) { +extern "C" int r4d_rad_moe_gemm_w4a8_mod4(const RadArgs* a, RadStream stream) { const char* wdt = r4d_gets(a, "dtype"); - if (wdt && !std::strcmp(wdt, "w4nl64a8h")) return moe_gemm_launch<2>(a, sk, 4); - if (wdt && !std::strcmp(wdt, "w4nl32a8h")) return moe_gemm_launch<3>(a, sk, 4); - if (wdt && !std::strcmp(wdt, "w5nl64a8h")) return moe_gemm_launch<4>(a, sk, 4); - return moe_gemm_launch<1>(a, sk, 4); + if (wdt && !std::strcmp(wdt, "w4nl64a8h")) return moe_gemm_launch<2>(a, stream, 4); + if (wdt && !std::strcmp(wdt, "w4nl32a8h")) return moe_gemm_launch<3>(a, stream, 4); + if (wdt && !std::strcmp(wdt, "w5nl64a8h")) return moe_gemm_launch<4>(a, stream, 4); + return moe_gemm_launch<1>(a, stream, 4); } -R4D_ENTRY(r4d_rad_moe_gemm_w4a8_mod4, rad_moe_gemm_w4a8_mod4_body) -/* `moe_gemm` at bf16: operands a, w (one table), sorted_tok, expert_offset -> y. The band and the - * three forms are moe_gemm_launch's and are chosen by the same rule from the same arguments, so the - * scratch hook that sizes the run map is the same function too. +/* `moe_gemm` at bf16: operands a, w (one table), sorted_tok, expert_offset -> y. Band and forms + * follow moe_gemm_launch's rule, so the same scratch hook sizes the run map. * - * EVERY LOAD IS SIXTEEN BYTES, and that is what the alignment checks below are for: a row pitch - * that is not a multiple of eight elements, or a stacked plane whose experts do not start on a - * sixteen-byte boundary, would put a chunk across two lines. A pointer table's entries cannot be - * checked from here -- they live in device memory -- and every allocator that fills one hands out - * movement-unit-aligned addresses. */ -static int moe_gemm_bf16_body(const RadArgs* a, const R4dSink& sk) { + * Every load is sixteen bytes, hence the alignment checks: row pitches must be multiples of eight + * elements and stacked experts 16-byte aligned. Pointer-table entries live in device memory and + * cannot be checked here; their allocators hand out movement-unit-aligned addresses. */ +extern "C" int r4d_rad_moe_gemm_bf16(const RadArgs* a, RadStream stream) { int emit_rc = RAD_OK; const RadTensor* A = r4d_opt(a, 0); const RadTensor* W = r4d_opt(a, 1); @@ -3613,7 +3137,7 @@ static int moe_gemm_bf16_body(const RadArgs* a, const R4dSink& sk) { const long long n_expert = r4d_geti_or(a, "n_expert", 0); const long long top_k = r4d_geti_or(a, "top_k", 0); if (N <= 0 || K <= 0 || n_expert <= 0 || top_k <= 0) return R4D_NO(RAD_E_SHAPE); - /* A column tile is 64 wide and every tile is all weight; a K pass is 64 deep. */ + /* Column tiles are 64 wide and all weight; a K pass is 64 deep. */ if (N % 64 || K % (long long)kBK16) return R4D_NO(RAD_E_SHAPE); if (A->dtype != RAD_BF16 || Y->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); if (sorted->dtype != RAD_I32 || off->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE); @@ -3626,7 +3150,7 @@ static int moe_gemm_bf16_body(const RadArgs* a, const R4dSink& sk) { if (a_ld < 0 || M <= 0 || a_ld % 8 || ((uintptr_t)A->data % 16)) return R4D_NO(RAD_E_STRIDE); if (r4d_numel(sorted) < T || r4d_numel(off) < n_expert + 1) return R4D_NO(RAD_E_SHAPE); - /* WHICH ROWS THE ACTIVATION HAS, checked rather than inferred -- see moe_gemm_launch. */ + /* The activation's row count is checked, not inferred (see moe_gemm_launch). */ const char* ord = r4d_gets(a, "a_order"); const bool a_sorted = ord && !std::strcmp(ord, "sorted"); if (ord && !a_sorted && std::strcmp(ord, "token")) return R4D_NO(RAD_E_UNSUPPORTED); @@ -3643,7 +3167,7 @@ static int moe_gemm_bf16_body(const RadArgs* a, const R4dSink& sk) { const int form = g_moe_prefill_form; if ((form == 0 && r4d_moe_decode_band(T, n_expert)) || form == 2) { const unsigned tiles = (unsigned)((T + 15) / 16); - emit_rc = R4D_EMIT(sk, (moe_gemm_bf16_kernel<1, 4, 1, 4, true>), + emit_rc = R4D_EMIT(stream, (moe_gemm_bf16_kernel<1, 4, 1, 4, true>), dim3(tiles * 16u, ny), dim3(4 * kWave), 0, (const uint16_t*)A->data, tab, w_s0, (const int32_t*)sorted->data, (const int32_t*)off->data, @@ -3655,18 +3179,19 @@ static int moe_gemm_bf16_body(const RadArgs* a, const R4dSink& sk) { uint32_t* map = (form != 3 && n_expert <= (long long)kMaxExpert && a->scratch && a->scratch_bytes >= r4d_blockmap_bytes(cap)) ? (uint32_t*)a->scratch : nullptr; - /* The 128-column, eight-wave tile wherever the width allows it, as the fp8 forms do. */ + /* The 128-column, eight-wave tile wherever the width allows, as in the fp8 forms. */ const bool wide_n = N % kPrefillCols == 0; const unsigned nyw = (unsigned)(N / kPrefillCols); const unsigned gx = map ? (unsigned)cap : (unsigned)((T + kPrefillRows - 1) / kPrefillRows); if (map) { - emit_rc = R4D_EMIT(sk, moe_blockmap_kernel, dim3(1), dim3(256), 0, + emit_rc = R4D_EMIT(stream, moe_blockmap_kernel, dim3(1), dim3(256), 0, (const int32_t*)off->data, (uint32_t)n_expert, (uint32_t)T, (uint32_t)kPrefillRows, (uint32_t)cap, map); if (emit_rc != RAD_OK) return emit_rc; } #define R4D_MOE16(AL_, NTL_, WGN_, NYG_) \ - R4D_EMIT(sk, (moe_gemm_bf16_kernel), \ + R4D_EMIT(stream, \ + (moe_gemm_bf16_kernel), \ dim3(gx, NYG_), dim3(2 * WGN_ * kWave), 0, \ (const uint16_t*)A->data, tab, w_s0, \ (const int32_t*)sorted->data, (const int32_t*)off->data, \ @@ -3680,10 +3205,9 @@ static int moe_gemm_bf16_body(const RadArgs* a, const R4dSink& sk) { #undef R4D_MOE16 } if (emit_rc != RAD_OK) return emit_rc; - if (!sk.desc) R4D_MOE_CHK(); + R4D_MOE_CHK(); return RAD_OK; } -R4D_ENTRY(r4d_rad_moe_gemm_bf16, moe_gemm_bf16_body) extern "C" int64_t r4d_rad_moe_gemm_bf16_scratch(const RadArgs* a) { return moe_gemm_map_scratch(a); @@ -3711,7 +3235,7 @@ extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) { if (ye->dtype != RAD_BF16 || ew->dtype != RAD_BF16 || Y->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); if (sorted->dtype != RAD_I32 || !r4d_contig(sorted)) return R4D_NO(RAD_E_STRIDE); - /* The shared arm is a PAIR: the plane and its per-row gate, or neither. */ + /* The shared arm is a pair: the plane and its per-row gate, or neither. */ if ((sh != nullptr) != (sg != nullptr)) return R4D_NO(RAD_E_INVAL); if (sh && (sh->dtype != RAD_BF16 || sg->dtype != RAD_BF16)) return R4D_NO(RAD_E_DTYPE); @@ -3727,12 +3251,9 @@ extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) { const long long T = M * top_k; if (Te < T || r4d_numel(sorted) < T) return R4D_NO(RAD_E_SHAPE); - - /* SELF: small enough that the gather builds its own slot table and the two prepass kernels - * are not launched at all -- see gather_kernel. The bound is on T because every one of the - * M*gy blocks repeats the scan: at a decode step that is 4*10 blocks over 40 entries, and at - * the cap it is still under half a megabyte of L2 traffic, against two dispatches saved on - * every MoE layer of every step. A prefill chunk is far past it and takes the prepass. */ + /* SELF: small enough for the gather to build its own slot table, skipping the two prepass + * kernels (see gather_kernel). Bounded on T because each of the M*gy blocks repeats the scan; + * at the cap it is under half a megabyte of L2 traffic. Prefill takes the prepass. */ const bool self = T <= (long long)kGatherSelfT && top_k <= (long long)kGatherSlots; const int64_t need = self ? 0 : T * (long long)sizeof(int32_t); @@ -3741,9 +3262,8 @@ extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) { if (!a->scratch || a->scratch_bytes < need) return R4D_NO(RAD_E_SCRATCH); inv = (int32_t*)a->scratch; const unsigned blocks = (unsigned)((T + 255) / 256); - /* TWO PASSES AND NOT ONE: a slot no sorted row claims must read -1, and the clear cannot - * be fused into the scatter because a thread does not know which entries nobody will - * write. Both are T/256 workgroups of trivial work; the launch is the cost. */ + /* Two passes: an unclaimed slot must read -1, and the clear cannot be fused into the + * scatter because no thread knows which entries nobody will write. */ hipLaunchKernelGGL(gather_inv_kernel, dim3(blocks), dim3(256), 0, (hipStream_t)s, inv, (uint32_t)T); R4D_MOE_CHK(); @@ -3762,11 +3282,9 @@ extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) { else if (act && std::strcmp(act, "none")) return R4D_NO(RAD_E_UNSUPPORTED); } - /* THE PREFILL FORM, a wave a token and sixteen bytes a lane (gather_wide_kernel), past the - * self-scan bound wherever the slots fit its registers and every row it reads or writes starts - * on sixteen bytes. The same sums as gather_kernel's; see the kernel. Anything else -- a decode - * step, a top_k past kGatherWideSlots, a width or a pitch sixteen-byte pieces do not tile -- - * takes gather_kernel. */ + /* The prefill form (gather_wide_kernel, a wave per token, sixteen bytes per lane) past the + * self-scan bound, where top_k fits kGatherWideSlots and every row is 16-byte aligned. Same + * sums as gather_kernel, which serves everything else. */ auto al16 = [](const void* p, long long ld) { return ((uintptr_t)p % 16) == 0 && ld % (long long)kGatherWideCols == 0; }; @@ -3816,9 +3334,8 @@ extern "C" int r4d_rad_scale_rows(const RadArgs* a, RadStream s) { if (ad && ad->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); const long long n = r4d_geti_or(a, "n", 0); if (n <= 0) return R4D_NO(RAD_E_SHAPE); - /* Read as a NAME, not through r4d_act_code: that helper's vocabulary is silu/sigmoid and this - * op's is sigmoid/none, so "none" would come back as "not in the list" and be indistinguishable - * from a typo. An unknown name is refused rather than run as the other activation. */ + /* Read as a name, not via r4d_act_code (whose vocabulary is silu/sigmoid, not sigmoid/none), so + * "none" is distinguishable from a typo. An unknown name is refused. */ const char* act = r4d_gets(a, "act"); const int sig = (act && !std::strcmp(act, "sigmoid")) ? 1 : 0; if (act && std::strcmp(act, "sigmoid") && std::strcmp(act, "none")) return R4D_NO(RAD_E_INVAL); @@ -3836,8 +3353,7 @@ extern "C" int r4d_rad_scale_rows(const RadArgs* a, RadStream s) { a_ld = r4d_rows_pitch(ad, n, &Ma); if (a_ld < 0 || Ma < M) return R4D_NO(RAD_E_STRIDE); } - /* One scalar a row. The stream arrives either as [M] rank 1 or as [M, 1] rank 2, and the row - * stride is dim 0's in both -- a rank-1 tensor's stride[0] is its element stride. */ + /* One scalar per row, as [M] or [M, 1]; the row stride is dim 0's in both. */ const long long s_ld = r4d_stride(sc, 0) > 0 ? r4d_stride(sc, 0) : 1; hipLaunchKernelGGL((scale_rows_kernel<256>), dim3((unsigned)M), dim3(256), 0, (hipStream_t)s, @@ -3851,43 +3367,30 @@ extern "C" int r4d_rad_scale_rows(const RadArgs* a, RadStream s) { /* ================================================================== router GEMM + router_topk_scatter * - * THE ROUTER, ITS SELECTION AND ITS SORT IN ONE LAUNCH -- and, where the layer has a shared expert, - * that expert's one-column gate beside them. rad_block_moe_fp8.h asks for it wherever it declares - * router_topk_scatter and issues it up to kRgMaxM rows; this is the kernel and its shim. + * The router GEMM, its selection and its sort in one launch, plus, where the layer has a shared + * expert, that expert's one-column gate. rad_block_moe_fp8.h issues it up to kRgMaxM rows wherever + * it declares router_topk_scatter. * - * At a decode step the router is a [n_expert, n_embd] bf16 GEMM over a handful of rows, and what - * follows it -- `router_topk_scatter` -- is one workgroup with almost no work in it. They are two - * DEPENDENT dispatches on every routed layer, and the boundary between them is a command-processor - * gap plus a second launch, on the critical path. The selection needs every logit of a row, so it - * cannot run inside a column tile; it runs in whichever workgroup finishes LAST, which an arrival - * counter names. That is the device-wide pattern gemm_fp8a8's split-K finisher and hc_up_mix's - * quantiser already use, and its rule is theirs: self-resetting, and never shared by two launches - * that can run at once. Here it is the op instance's, taken at init -- see THE ARRIVAL COUNTER. + * At decode the router GEMM and router_topk_scatter are two dependent dispatches per routed layer + * with almost no work in the second. The selection needs a row's every logit, so it runs in the + * workgroup that finishes last, named by an arrival counter (the pattern of gemm_fp8a8's split-K + * finisher and hc_up_mix's quantiser: self-resetting, never shared by concurrent launches). Here + * the counter is the op instance's, taken at init (see the arrival-counter note). * - * The shared expert's gate is a gemm_nt at N = 1 over the SAME input, a launch of its own for one - * output column. It rides along as one more workgroup of this grid (`skg` > 0), so the launch the - * routed gate_up was overlapping disappears from the queue. + * The shared expert's gate (gemm_nt at N = 1 over the same input) rides along as one more + * workgroup (`skg` > 0), removing its separate launch. * - * BYTE-IDENTICAL TO THE LAUNCHES IT STANDS IN FOR, and the claim rests on two things: + * Byte-identical to the launches it replaces: + * - The GEMM is r4d_gemm_bf16_nt_m64_kernel's arithmetic: an output element is SK partial tiles, + * each one wave's WMMA chain over a contiguous K slice, summed in ascending split order from + * 0.f and narrowed by the language's conversion. Only SK matters, so the split counts come from + * the same law (cfg_for with the same N-tile count), and a wave may run several (tile, split) + * items, each into its own LDS slot. + * - The selection and sort are router_topk_scatter_kernel's body: wave-local and stable, so the + * last block's wave count changes no bit. * - * - THE GEMM IS r4d_gemm_bf16_nt_m64_kernel'S ARITHMETIC, ELEMENT BY ELEMENT. An output element of - * that kernel is SK partial tiles, each ONE wave's WMMA chain over one contiguous K slice in - * ascending K, summed in ascending split order from 0.f and narrowed by the language's own - * conversion. Which block owns the tile, how many tiles a block holds (WV, MB) and how many - * waves a block has do not enter it -- only SK does. So the split counts are asked of the law - * the unfused launches ask (cfg_for with the same N-tile count: a 512-wide router and a - * one-column gate get different ones), and a wave here may run several (tile, split) items - * one after another: each item is the same chain from zero into an LDS slot of its own, so the - * sum sees exactly the operands it saw before. - * - THE SELECTION AND THE SORT ARE router_topk_scatter_kernel'S BODY: the same two device - * functions over the same logits, wave-local per row and stable without an atomic ordering - * anything, so the number of waves the last block happens to have moves no bit. - * - * A TUNED POINT for the unfused router would break the first of those: this row is NOTUNE and - * always takes the law's split. No shipped configuration tunes these GEMMs. - * - * DECODE ONLY: at most kRgMaxM rows (four 16-row tiles), which is the skinny GEMM's decode band; - * past it the router is the tiled kernel and the architecture issues the pair. */ + * A tuned point for the unfused router would break the first, so this row is NOTUNE. Decode only: + * at most kRgMaxM rows (four 16-row tiles); beyond that the architecture issues the pair. */ constexpr long long kRgMaxM = 64; namespace { @@ -3916,8 +3419,8 @@ __device__ __forceinline__ unsigned rg_rowGo(unsigned rowstride, int row0, int l return (unsigned)r * rowstride + 4u * (unsigned)(lane >> 4); } -/* ONE (tile, split) ITEM: the 16 x 16 partial tile r4d_gemm_bf16_nt_m64_kernel's wave (n0, ks) - * accumulates at MT = 1 -- the same loads, the same WMMA chain in the same order from zero. */ +/* One (tile, split) item: the 16 x 16 partial tile r4d_gemm_bf16_nt_m64_kernel's wave (n0, ks) + * accumulates at MT = 1, with the same loads and WMMA chain from zero. */ __device__ __forceinline__ rg_v8f rg_item(const uint16_t* __restrict__ A, const uint16_t* __restrict__ W, int M, int K, int N, int n0, int m0, int ks, int SK, int lane) { @@ -3948,9 +3451,9 @@ __device__ __forceinline__ rg_v8f rg_item(const uint16_t* __restrict__ A, return acc; } -/* The launch geometry, one argument: `sk` the router's split and `tpb` its 16-column tiles a - * block, `nrb` the router's blocks along x, `skg` the gate's split (0: no gate; its block is - * x = nrb). Rows are tiled along y, one 16-row tile a block. */ +/* Launch geometry: `sk` the router's split, `tpb` its 16-column tiles per block, `nrb` the + * router's blocks along x, `skg` the gate's split (0: no gate; its block is x = nrb). Rows are + * tiled along y, one 16-row tile per block. */ struct RgGeom { uint32_t M, K, n_expert, n_local, top_k, lg_ld; int32_t norm, base; @@ -3965,8 +3468,8 @@ __global__ __launch_bounds__(NW * kWave) void router_gemm_topk_scatter_kernel( int32_t* __restrict__ ids, uint16_t* __restrict__ w, int32_t* __restrict__ sorted, int32_t* __restrict__ off, int32_t* __restrict__ cnt, unsigned int* __restrict__ ctr, RgGeom g, Protect prot) { - /* The partial tiles of the GEMM, then -- in the last block only, after two barriers -- the - * sort's LDS. The shim sizes it for the larger of the two. */ + /* The GEMM's partial tiles, then (last block only, after two barriers) the sort's LDS; the + * shim sizes it for the larger. */ extern __shared__ __align__(16) unsigned char rg_smem[]; float* const red = (float*)rg_smem; const uint32_t tid = threadIdx.x, wave = tid / kWave, lane = tid % kWave; @@ -3989,9 +3492,8 @@ __global__ __launch_bounds__(NW * kWave) void router_gemm_topk_scatter_kernel( for (int e = 0; e < 8; e++) slot[e * (int)kWave + (int)lane] = acc[e]; } __syncthreads(); - /* THE REDUCTION, r4d_gemm_bf16_nt_m64_kernel's: the splits in ascending order from 0.f, and - * the language's float-to-bf16 conversion -- not f32_to_bf16, which is the same only away - * from NaN. */ + /* The reduction, as in r4d_gemm_bf16_nt_m64_kernel: splits in ascending order from 0.f, and + * the language's float-to-bf16 conversion (not f32_to_bf16, which differs on NaN). */ for (uint32_t idx = tid; idx < nti * 256u; idx += NW * kWave) { const uint32_t j = idx >> 8, o = idx & 255u; float v = 0.f; @@ -4005,9 +3507,9 @@ __global__ __launch_bounds__(NW * kWave) void router_gemm_topk_scatter_kernel( } } - /* ---- THE LAST BLOCK RANKS. Every store above is made visible device-wide before the - * arrival is published, and the block that completes the count resets it for the next - * launch and acquires the other blocks' logits. */ + /* ---- the last block ranks. Every store is made visible device-wide before the arrival is + * published; the block completing the count resets it for the next launch and acquires the + * other blocks' logits. */ __threadfence(); __syncthreads(); __shared__ unsigned int s_arrived; @@ -4028,23 +3530,17 @@ __global__ __launch_bounds__(NW * kWave) void router_gemm_topk_scatter_kernel( scatter_small_place(sorted, off, cnt, g.M * g.top_k, g.n_local, sl); } -/* THE ARRIVAL COUNTER IS THE OP INSTANCE'S, taken at init and not on the launch path. +/* The arrival counter belongs to the op instance and is taken at init, not on the launch path. * - * It has to persist between launches, zeroed: the last block of every launch resets it, and a - * launch that found it non-zero would rank before the GEMM was done. A scratch hook cannot carry - * that -- the scratch is one arena region every other op's kernel writes between two of these - * launches. The other counters in this library (gemm_fp8a8's split_ctr, hc_bf16's mix counters) - * are allocated on first use from the launch path, which leaves them out of the VRAM budget and - * puts an allocation on the describe path that must not allocate. The init hook has neither - * problem: the engine calls it once per resolved instance during declare, on the rank's device, - * and reads the free VRAM for its budget after every init has run, so what init takes is - * counted. + * It must persist between launches, zeroed (the last block resets it; a non-zero start would rank + * before the GEMM finished), so scratch cannot hold it: other ops write the arena between + * launches. Allocating on first use (as gemm_fp8a8's split_ctr and hc_bf16's mix counters do) + * escapes the VRAM budget. Init runs once per resolved instance + * during declare, before the engine measures free VRAM, so its allocation is counted. * - * ONE COUNTER AN INSTANCE -- one declared op, one band, one domain, one rank. Each routed layer - * declares its own op, so two layers never share one, and the launches of one instance are - * ordered: every one of them writes the same declared sort outputs, which the engine does not - * reorder or overlap. The counters are 64-byte slots of one zeroed block a device, so a model's - * few hundred instances cost one allocation; the block is freed with its last instance. */ + * One counter per instance (op, band, domain, rank). Each routed layer declares its own op, and an + * instance's launches are ordered since they write the same declared outputs. Counters are 64-byte + * slots of one zeroed block per device, freed with its last instance. */ constexpr uint32_t kRgCtrStride = 16; /* uint32 words a slot: one 64-byte line each */ constexpr uint32_t kRgCtrSlots = 4096; /* instances a device; a model declares hundreds */ @@ -4074,8 +3570,8 @@ extern "C" int r4d_rad_router_gemm_topk_scatter_init(const RadParam*, int, int, const size_t bytes = (size_t)kRgCtrSlots * kRgCtrStride * sizeof(unsigned int); void* p = nullptr; if (hipMalloc(&p, bytes) != hipSuccess) return RAD_E_NOMEM; - /* Zero before any launch can read it: the memset is ordered on the null stream, and the - * engine's streams need not wait for that one, so it is waited for here. */ + /* 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. */ if (hipMemset(p, 0, bytes) != hipSuccess || hipDeviceSynchronize() != hipSuccess) { (void)hipFree(p); return RAD_E_DEVICE; @@ -4083,8 +3579,8 @@ extern "C" int r4d_rad_router_gemm_topk_scatter_init(const RadParam*, int, int, blk.base = (unsigned int*)p; blk.next = 0; } - /* A slot is never handed out twice while its block lives: one returned by fini is not known - * to be zero if its last launch did not finish, so it is not reused. */ + /* A slot is never reused while its block lives: one returned by fini may not be zero if its + * last launch did not finish. */ if (blk.next >= kRgCtrSlots) return RAD_E_FULL; RgInst* in = new RgInst; in->dev = dev; @@ -4112,10 +3608,9 @@ extern "C" void r4d_rad_router_gemm_topk_scatter_fini(void* inst) { } /* Operands: a, b (the router), gate_b? -> logits, expert_ids, expert_w, sorted_tok, - * expert_offset, expert_count, gate?. The two optional ones come together or not at all. Every - * check of the two shims it stands in for is made here too; nothing new is asserted beyond the - * row bound. */ -static int rad_router_gemm_topk_scatter_body(const RadArgs* a, const R4dSink& sk) { + * expert_offset, expert_count, gate?. The two optional ones come together or not at all. The + * replaced shims' checks are all made here, plus the row bound. */ +extern "C" int r4d_rad_router_gemm_topk_scatter(const RadArgs* a, RadStream stream) { int emit_rc = RAD_OK; const RadTensor* x = r4d_opt(a, 0); const RadTensor* wr = r4d_opt(a, 1); @@ -4149,8 +3644,8 @@ static int rad_router_gemm_topk_scatter_body(const RadArgs* a, const R4dSink& sk if (ids->dtype != RAD_I32 || sorted->dtype != RAD_I32 || off->dtype != RAD_I32 || cnt->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE); - /* The GEMM's operands, as gemm_ops reads them: A [M, K] contiguous, the output contiguous, - * A and the weights 16-byte aligned. */ + /* The GEMM's operands, as gemm_ops reads them: A [M, K] and the output contiguous, A and the + * weights 16-byte aligned. */ long long M = 0, K = 0; if (r4d_rows_of(x, &M, &K) != RAD_OK) return R4D_NO(RAD_E_SHAPE); if (!r4d_contig(x)) return R4D_NO(RAD_E_STRIDE); @@ -4170,8 +3665,8 @@ static int rad_router_gemm_topk_scatter_body(const RadArgs* a, const R4dSink& sk if (r4d_numel(sorted) < T) return R4D_NO(RAD_E_SHAPE); if (r4d_numel(off) < n_local + 1 || r4d_numel(cnt) < n_local) return R4D_NO(RAD_E_SHAPE); - /* THE SPLITS THE UNFUSED LAUNCHES TAKE: gemm_bf16_nt_m16/_m64 ask cfg_for with ceil(N/16) - * tiles, so the router asks with its own width and the gate with one tile. */ + /* The unfused launches' splits: gemm_bf16_nt_m16/_m64 ask cfg_for with ceil(N/16) tiles, so + * the router asks with its width and the gate with one tile. */ const long long ntiles = (n_expert + 15) / 16; Cfg cr{}, cg{}; int rc = cfg_for(a, K, M, 16, BR_FLAT, &cr, ntiles); @@ -4180,14 +3675,14 @@ static int rad_router_gemm_topk_scatter_body(const RadArgs* a, const R4dSink& sk rc = cfg_for(a, K, M, 16, BR_FLAT, &cg, 1); if (rc != RAD_OK) return rc; } - /* The instance's counter (see THE ARRIVAL COUNTER). A caller that ran no init has none, and - * the op is refused: a launch without it would have no last block to rank. */ + /* The instance's counter (see the arrival-counter note). Without init there is none and the + * op is refused. */ const RgInst* const inst = (const RgInst*)a->instance; if (!inst || !inst->ctr) return R4D_NO(RAD_E_STATE); unsigned int* const ctr = inst->ctr; - /* THE WAVE COUNT IS THE SELECTION'S, router_topk_scatter's rule: a wave a row up to 32. The - * GEMM then takes as many 16-column tiles a block as fills those waves at its split. */ + /* The wave count follows router_topk_scatter's rule (a wave per row, up to 32); the GEMM takes + * as many 16-column tiles per block as fill those waves at its split. */ const uint32_t nw = M <= 8 ? 8u : M <= 16 ? 16u : 32u; long long tpb = (long long)nw / cr.sk; if (tpb < 1) tpb = 1; @@ -4209,7 +3704,7 @@ static int rad_router_gemm_topk_scatter_body(const RadArgs* a, const R4dSink& sk const dim3 grid((unsigned)(nrb + (wg ? 1 : 0)), (unsigned)((M + 15) / 16)); #define R4D_RG_L(OWN, NWV) \ - emit_rc = R4D_EMIT(sk, (router_gemm_topk_scatter_kernel), grid, \ + emit_rc = R4D_EMIT(stream, (router_gemm_topk_scatter_kernel), grid, \ dim3((NWV) * kWave), lds, \ (const uint16_t*)x->data, (const uint16_t*)wr->data, \ wg ? (const uint16_t*)wg->data : (const uint16_t*)nullptr, \ @@ -4227,7 +3722,6 @@ static int rad_router_gemm_topk_scatter_body(const RadArgs* a, const R4dSink& sk } #undef R4D_RG_L if (emit_rc != RAD_OK) return emit_rc; - if (!sk.desc) R4D_MOE_CHK(); + R4D_MOE_CHK(); return RAD_OK; } -R4D_ENTRY(r4d_rad_router_gemm_topk_scatter, rad_router_gemm_topk_scatter_body) diff --git a/libr4d/r4d_mxfp4.h b/libr4d/r4d_mxfp4.h index 58655f5c..b0d15200 100644 --- a/libr4d/r4d_mxfp4.h +++ b/libr4d/r4d_mxfp4.h @@ -1,10 +1,9 @@ -// Shared device-side machinery for the OCP-MXFP4 GEMMs (r4d_gemm_mxfp4a8_nt_m64, _tiled, _decode): -// the folded-magnitude table and the eight-element unpack that reads it. One definition, because -// the three kernels must fold every weight element to the same e4m3 byte -- a model whose step -// crosses from one row's band into another's must not change what the weight is. +// Shared device code for the OCP-MXFP4 GEMMs (r4d_gemm_mxfp4a8_nt_m64, _tiled, _decode): the +// folded-magnitude table and the eight-element unpack that reads it. Shared so all three fold every +// weight element to the same e4m3 byte, and a step crossing M bands sees the same weight. // -// r4d_gemm_mxfp4a8_nt_m64.hip explains the fold: d = Wref[n] - E8M0[n][blk] is pushed into the -// e4m3 value through this table, and 2^(Wref[n]-127) is applied once in the epilogue. +// The fold is explained in r4d_gemm_mxfp4a8_nt_m64.hip: d = Wref[n] - E8M0[n][blk] is applied +// through this table, and 2^(Wref[n]-127) once in the epilogue. #pragma once #include @@ -12,14 +11,12 @@ #define R4D_MXFP4_GROUP 32 // K per E8M0 exponent, fixed by the OCP MX format // kMxfp4Mag[d] is the eight e2m1 magnitudes {0, .5, 1, 1.5, 2, 3, 4, 6} scaled by 2^-d, as packed -// e4m3 bytes, low word then high word, indexed by the 3-bit magnitude through v_perm_b32. -// Every entry is the round-to-nearest-EVEN e4m3 of that product, which is exact for d <= 8 and a -// rounding for d >= 9 -- three entries there (d=9 mag 1.5, d=10 mag 3, d=11 mag 6) are the same -// exact tie 1.5*2^-9 and take the even neighbour 2^-8, not the smaller one. They matter little -// (such an element is 2.9e-3 of its row's reference), but the table is generated, not hand-rounded, -// so it agrees with the hardware's own conversion. d >= 13 is zero: below the row's range. +// e4m3 bytes (low word, high word), indexed by the 3-bit magnitude through v_perm_b32. Entries are +// the round-to-nearest-even e4m3 of the product, matching the hardware conversion: exact for +// d <= 8; for d >= 9 the ties at 1.5*2^-9 (d=9 mag 1.5, d=10 mag 3, d=11 mag 6) round to 2^-8. +// d >= 13 is zero. // -// Static: each kernel's code object carries its own copy, and no two define the same symbol. +// Static: each kernel's code object carries its own copy. static __device__ __constant__ unsigned int kMxfp4Mag[16][2] = { {0x3c383000u, 0x4c484440u}, {0x34302800u, 0x44403c38u}, {0x2c282000u, 0x3c383430u}, {0x24201800u, 0x34302c28u}, @@ -31,21 +28,20 @@ static __device__ __constant__ unsigned int kMxfp4Mag[16][2] = { {0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u}, }; -// The exponent difference a block is folded at, clamped to the table: a block above its row's -// reference cannot occur (the reference is the row's maximum), and one 15 or more below is zero. +// The exponent difference a block is folded at, clamped to the table. d < 0 cannot occur (the +// reference is the row's maximum); d >= 15 is zero. static __device__ __forceinline__ int r4d_mxfp4_fold_d(int ref, int e8) { const int d = ref - e8; return d < 0 ? 0 : (d > 15 ? 15 : d); } // Eight e2m1 codes (four packed bytes, element 2j in the low nibble of byte j) -> eight e4m3 bytes -// in k order, word 0 holding elements 0..3 and word 1 elements 4..7, with the block's exponent -// difference `d` already folded in. Splitting the nibbles gives the even and odd elements; each is -// mapped through the table by a v_perm_b32 indexed with the 3-bit magnitude, the sign rides along -// as bit 3 shifted into the e4m3 sign position, and two more v_perm_b32 interleave the halves. +// in k order (word 0 = elements 0..3, word 1 = 4..7), with exponent difference `d` folded in. Even +// and odd nibbles are each mapped through the table by a v_perm_b32 on the 3-bit magnitude, bit 3 +// is shifted into the e4m3 sign, and two more v_perm_b32 interleave the halves. // -// `_t` takes the table row (t0, t1) the caller already holds -- a kernel that copies the table to -// LDS reads it there, off the global load counter its weight and activation loads wait on. +// `_t` takes a table row (t0, t1) the caller already holds, e.g. from an LDS copy, which keeps the +// lookup off the global load counter the weight and activation loads wait on. static __device__ __forceinline__ void r4d_mxfp4_unpack8_t(unsigned int wv, unsigned int t0, unsigned int t1, unsigned int* lo, unsigned int* hi) { @@ -61,10 +57,9 @@ static __device__ __forceinline__ void r4d_mxfp4_unpack8(unsigned int wv, int d, r4d_mxfp4_unpack8_t(wv, kMxfp4Mag[d][0], kMxfp4Mag[d][1], lo, hi); } -// THE ACTIVATION SCALE A ROW'S ACCUMULATOR IS CARRIED IN, for the per-(row, 128 of K) grid: the -// last non-zero entry of row `row` at or before block `kb`, or 1 when there is none. A block whose -// scale is zero has zero codes and adds nothing whichever scale the sum is carried in, so it keeps -// the previous one rather than dividing by zero. +// The activation scale a row's accumulator is carried in, for the per-(row, 128 of K) grid: the +// last non-zero entry of `row` at or before block `kb`, or 1 if none. A zero-scale block has zero +// codes and contributes nothing, so it keeps the previous scale instead of dividing by zero. static __device__ __forceinline__ float r4d_mxfp4_carried(const float* __restrict__ row, int kb) { for (int j = kb; j >= 0; --j) { const float s = row[j]; diff --git a/libr4d/r4d_ngram_ids.hip b/libr4d/r4d_ngram_ids.hip index 11bfe361..d951480a 100644 --- a/libr4d/r4d_ngram_ids.hip +++ b/libr4d/r4d_ngram_ids.hip @@ -1,36 +1,22 @@ // r4d_ngram_ids.hip -- the hashed row ids of Qwen4-Exp's Per-Layer Embedding. // -// ============================== WHAT IT COMPUTES ============================== -// // mixed(k) = t0*mult[0] ^ t1*mult[1] ^ ... ^ tk*mult[k] int64, wrapping // ids[h] = mixed(b+1) % vocab_sizes[h] + offsets[h] h in block b // -// with `heads` laid out as `ngram - 1` equal blocks, block b using the (b+2)-gram, and `t_s` the -// token `s` positions back OR the EOS id if the shift would cross one. libref/ref_ngram.cpp holds -// the derivation of that EOS rule -- it collapses a cummax over segment starts into "once a shift -// falls back, every deeper one does" -- and docs/OPS.md holds the operand contract. +// `heads` is laid out as `ngram - 1` equal blocks, block b using the (b+2)-gram, and `t_s` is the +// token `s` positions back, or the EOS id if the shift would cross one. libref/ref_ngram.cpp +// derives that EOS rule (a cummax over segment starts reduces to "once a shift falls back, every +// deeper one does"); docs/OPS.md holds the operand contract. // -// ============================== ONE THREAD A TOKEN, NOT A HEAD ============================== +// One thread a token, looping its heads. A token's heads share the shifted tokens, the EOS walk +// and the `ngram - 1` hash mixes and differ only in the modulus, so a thread per head would redo +// that work per head, and at decode (one token) would be partial waves either way. At prefill the +// grid is thousands of tokens; at decode the kernel is negligible beside the gather that follows. // -// The obvious grid is one thread per (token, head): 16x the parallelism and every thread doing one -// modulo. It is the wrong one. The sixteen heads of a token share the THREE shifted tokens and the -// `ngram - 1` hash mixes -- the whole EOS walk and every multiply -- and differ only in which -// constant they reduce against. A thread per head redoes that work sixteen times, and at decode the -// grid is one token: sixteen threads either way, and the per-head form is sixteen partial waves -// instead of one. -// -// So a thread owns a token and loops its heads. At prefill the grid is the token count, which is -// thousands; at decode it is 1 to 8 and the kernel is a rounding error beside the 5 KB gather that -// follows it. Neither end wants more threads. -// -// ============================== THE MODULO IS THE COST, AND IT IS FINE ============================== -// -// `mixed % vocab_sizes[h]` is a 64-bit division by a runtime value -- no reciprocal, no strength -// reduction, ~70 cycles on this part -- sixteen per token. At decode that is ~1100 cycles for the -// whole step's ids. Magic-number division would remove it and would mean the ARCHITECTURE computing -// a multiplier and a shift per head at declare and passing them as a second weight; it is not worth -// a second source of truth for sixteen divisions a token. If a model ever hashes at prefill width -// with a hundred heads, that is the change to make. +// `mixed % vocab_sizes[h]` is a 64-bit division by a runtime value (~70 cycles on this part), +// sixteen per token. Magic-number division would need the architecture to compute a multiplier +// and shift per head and pass them as a second weight; not worth it at this head count, but the +// change to make if a model hashes at prefill width with many more heads. #include "r4d.h" #include "r4d_args.h" #include "r4d_emit.h" @@ -39,10 +25,9 @@ namespace { -/* THE SAME TWO OPERATIONS libref SPELLS OUT, and for the same reason: a signed overflow is UB and - * torch's `remainder` FLOORS where C truncates. On a real checkpoint neither can fire -- the - * multipliers are bounded so a real token's product has its sign bit clear -- but the kernel and - * the oracle have to agree on inputs a harness draws, not only on the ones a model produces. */ +/* The same two operations libref spells out: signed overflow is UB, and torch's `remainder` floors + * where C truncates. On a real checkpoint neither fires (the multipliers keep a real token's + * product non-negative), but kernel and oracle must also agree on test inputs. */ __device__ __forceinline__ long long ng_wrap_mul(long long a, long long b) { return (long long)((unsigned long long)a * (unsigned long long)b); } @@ -53,18 +38,15 @@ __device__ __forceinline__ long long ng_floor_mod(long long a, long long b) { enum { kNgMaxShift = 8, kNgThreads = 256 }; -/* ONE WORKGROUP A (TOKEN TILE, SEQUENCE), AND THE WINDOW WRITE-BACK IS IN IT. +/* One workgroup per (token tile, sequence), with the window write-back in the same launch. * - * `s` is blockIdx.y, so the sequence scan is gone and so is the second launch. What makes the - * fold legal is WHICH THREADS READ THE WINDOW: only a token with `t - bos < ctx` reaches back - * past its own sequence's first row, and those are the first `ctx` tokens, which live in tile - * ZERO. So tile 0's block is the only reader of state[slot], its threads are ordered against each - * other by __syncthreads(), and thread 0 writes the new window after that barrier. No other block - * touches those bytes and no grid-wide barrier is needed. + * `s` is blockIdx.y. The fold is legal because only a token with `t - bos < ctx` reads past its + * sequence's first row into the window, and those are the first `ctx` tokens, all in tile 0. So + * tile 0's block is the only reader of state[slot]; its threads are ordered by __syncthreads(), and + * thread 0 writes the new window after it. No other block touches those bytes. * - * AT DECODE THIS OP IS NOTHING BUT LAUNCHES: its cost is flat from M=1 to M=512, which is the - * dispatches and none of the work. Folding the write-back into the same launch, rather than - * taking a second one for it, is therefore most of what the op costs. */ + * At decode this op's cost is the dispatch itself (flat from M=1 to M=512), so avoiding a second + * launch for the write-back is most of the saving. */ __global__ __launch_bounds__(kNgThreads) void ngram_ids_kernel( const int32_t* __restrict__ tok, int32_t* __restrict__ state, const int32_t* __restrict__ cu, const long long* __restrict__ mult, @@ -79,8 +61,8 @@ __global__ __launch_bounds__(kNgThreads) void ngram_ids_kernel( const uint32_t bos = (uint32_t)cu[s]; const uint32_t eot = (uint32_t)cu[s + 1]; const uint32_t ctx = ngram - 1u; - /* UNIFORM EXITS ONLY before the barrier below: an empty sequence and a negative slot are - * properties of the block, not of the thread, so every thread of the block leaves together. */ + /* Only block-uniform exits before the barrier below: an empty sequence and a negative slot are + * properties of the block, so all its threads leave together. */ if (eot <= bos) return; const int32_t slot = sidx ? sidx[s] : (int32_t)s; if (slot < 0) return; @@ -90,21 +72,20 @@ __global__ __launch_bounds__(kNgThreads) void ngram_ids_kernel( const long long o = nacc ? (long long)nacc[s] - 1 : 0; const uint32_t lt = blockIdx.x * kNgThreads + threadIdx.x; /* this thread's row, in-sequence */ - /* THE PROMPT THAT FOLLOWS continues the LAST sequence: its tokens sit in `tok` right after - * the step's, so a row past the sequence's end hashes exactly as that row will when the next - * step runs it -- same history, same EOS rule -- and lands in `ahead` instead of `ids`. The - * window below is the step's own and never sees them. */ + /* The following prompt continues the last sequence: its tokens sit in `tok` after the step's, + * so a row past the sequence's end hashes exactly as it will when the next step runs it, and + * lands in `ahead` instead of `ids`. The window below is the step's own and never sees them. */ const uint32_t reach = slen + ((ahead && s + 1u == gridDim.y) ? n_ahead : 0u); if (lt < reach) { const uint32_t t = bos + lt; - /* The `ctx` committed ids in front of this sequence's first row. A COLD slot's window is - * EOS and not what the slot last held -- and not zero, which is a real token id. */ + /* The `ctx` committed ids before this sequence's first row. A cold slot's window is EOS, + * not its stale contents and not zero (a real token id). */ long long prev[kNgMaxShift]; for (uint32_t i = 0; i < ctx; ++i) prev[i] = warm ? (long long)state[(long long)slot * W + o + i] : eos; - /* The shifted tokens. `p` indexes the history `prev ++ this sequence's rows`, so row `lt` - * sits at `ctx + lt` and every shift is in range without a bounds test. */ + /* `p` indexes the history `prev ++ this sequence's rows`, so row `lt` sits at `ctx + lt` + * and every shift is in range without a bounds test. */ const uint32_t p = ctx + lt; long long sh[kNgMaxShift]; sh[0] = (long long)tok[t]; @@ -116,7 +97,7 @@ __global__ __launch_bounds__(kNgThreads) void ngram_ids_kernel( } /* One mix per n-gram order, extended in place: the (b+2)-gram's mix is the (b+1)-gram's - * XOR'd with one more term, which is the reference's own inner loop. */ + * XOR one more term, as in the reference's inner loop. */ long long mixed = 0; int blk = -1; for (uint32_t k = 0; k < ngram; ++k) { @@ -133,20 +114,20 @@ __global__ __launch_bounds__(kNgThreads) void ngram_ids_kernel( } } - /* THE WINDOW THIS STEP LEAVES BEHIND, in libref/ref_ngram.cpp's two layouts. + /* The window this step leaves, in libref/ref_ngram.cpp's two layouts. * - * WITH `num_accepted` the step is a decode step whose drafts a verify may reject, so the - * window is shifted down by one and EVERY id of the step follows it: slot i holds position - * i + 1 of (window read ++ step). A next step that kept k of these ids reads at k - 1 and - * finds the `ctx` ids ending at the k-th. Slot i is read from o + i + 1, which is past every - * slot already written, so the ascending walk is safe in place. Slots past W are not written; - * the manager sizes the window ctx + n_spec, which covers a step of 1 + n_spec ids. + * With `num_accepted` this is a decode step whose drafts a verify may reject: the window shifts + * down by one and every id of the step follows it, so slot i holds position i + 1 of + * (window read ++ step). A next step that kept k of these ids reads at k - 1 and finds the + * `ctx` ids ending at the k-th. Slot i is read from o + i + 1, past every slot already written, + * so the ascending walk is safe in place. Slots past W are not written; the manager sizes the + * window ctx + n_spec, enough for a step of 1 + n_spec ids. * - * WITHOUT it every id commits and the last `ctx` land at offset zero. + * Without it every id commits and the last `ctx` land at offset zero. * - * ONE THREAD, not one per slot: a thread per (sequence, k) races within the sequence -- at - * ctx = 2 and slen = 1, thread 0 reads slot o+1 while thread 1 writes slot 1 -- and at decode - * the serial form is a loop of ctx - 1 + slen stores, so removing the class costs nothing. */ + * One thread, not one per slot: a thread per (sequence, k) races within the sequence (at + * ctx = 2 and slen = 1, thread 0 reads slot o+1 while thread 1 writes slot 1), and at decode + * the serial loop is only ctx - 1 + slen stores. */ __syncthreads(); if (blockIdx.x != 0 || threadIdx.x != 0) return; int32_t* const win = state + (long long)slot * W; @@ -170,7 +151,7 @@ __global__ __launch_bounds__(kNgThreads) void ngram_ids_kernel( enum { NG_TOK = 0, NG_STATE, NG_CU, NG_MULT, NG_VSZ, NG_OFF, NG_CIDX, NG_HINIT, NG_NACC, NG_IDS, NG_AHEAD }; -static int ngram_ids_body(const RadArgs* a, const R4dSink& sk) { +extern "C" int r4d_rad_ngram_ids(const RadArgs* a, RadStream stream) { const RadTensor* tok = r4d_opt(a, NG_TOK); const RadTensor* st = r4d_opt(a, NG_STATE); const RadTensor* cu = r4d_opt(a, NG_CU); @@ -202,8 +183,8 @@ static int ngram_ids_body(const RadArgs* a, const R4dSink& sk) { long long rows = 0; const long long ids_ld = r4d_rows_pitch(ids, heads, &rows); if (ids_ld < 0 || rows <= 0) return R4D_NO(RAD_E_STRIDE); - /* THE ROW COUNT COMES FROM THE OPERAND. `M` is RANGED, so the value in the args is the band's - * upper bound and a grid sized by it walks off the arena. */ + /* The row count comes from the operand: `M` is ranged, so the arg holds the band's upper bound + * and a grid sized by it would run off the arena. */ const long long T = rows; /* The prompt that follows: `ahead`'s rows, whose tokens `tok` holds after the step's. */ long long A = 0, ahead_ld = heads; @@ -221,12 +202,11 @@ static int ngram_ids_body(const RadArgs* a, const R4dSink& sk) { const long long W = st->rank >= 2 ? r4d_dim(st, (int)st->rank - 1) : ctx; if (W < ctx) return R4D_NO(RAD_E_SHAPE); - /* (token tiles, sequences). The tile count is taken from the batch's TOTAL token count, - * which is an upper bound on any one sequence's -- a short sequence in a mixed batch launches - * a few blocks that find their rows past its end, and the waste is bounded by the sequence - * count. Reading a per-sequence tile count would mean reading `cu` on the host. */ + /* (token tiles, sequences). Tiles are sized by the batch's total token count, an upper bound on + * any one sequence's; a short sequence's extra blocks find their rows past its end. A + * per-sequence count would mean reading `cu` on the host. */ const uint32_t tiles = (uint32_t)((T + A + kNgThreads - 1) / kNgThreads); - return R4D_EMIT(sk, ngram_ids_kernel, dim3(tiles, (uint32_t)N), dim3(kNgThreads), 0, + return R4D_EMIT(stream, ngram_ids_kernel, dim3(tiles, (uint32_t)N), dim3(kNgThreads), 0, (const int32_t*)r4d_addr(tok), (int32_t*)r4d_addr(st), (const int32_t*)r4d_addr(cu), (const long long*)r4d_addr(mult), (const long long*)r4d_addr(vsz), (const long long*)r4d_addr(off), @@ -238,6 +218,3 @@ static int ngram_ids_body(const RadArgs* a, const R4dSink& sk) { A > 0 ? (int32_t*)r4d_addr(ahd) : nullptr, (uint32_t)A, (uint32_t)ahead_ld); } - -/* ABI v10: the launch and its description, from the body above. */ -R4D_ENTRY(r4d_rad_ngram_ids, ngram_ids_body) diff --git a/libr4d/r4d_norm_join_bf16.hip b/libr4d/r4d_norm_join_bf16.hip index c74f80fc..b9fad8f7 100644 --- a/libr4d/r4d_norm_join_bf16.hip +++ b/libr4d/r4d_norm_join_bf16.hip @@ -1,46 +1,40 @@ -/* r4d_norm_join_bf16.hip -- Gemma 4's sandwich-norm joins, each one kernel instead of a chain of small ones. +/* r4d_norm_join_bf16.hip -- Gemma 4's sandwich-norm joins, each one kernel instead of a chain. * - * A decode step of the 26B-A4B launches ~250 rmsnorms and ~90 adds a step, each a few hundred - * bytes of work behind a full launch: --profile-ops measured 2.0 ms and 0.85 ms of a 16.6 ms step. - * Two places in every layer are pure chains of them: + * A 26B-A4B decode step launches ~250 rmsnorms and ~90 adds, each a few hundred bytes of work + * behind a full launch (about 2.0 and 0.85 ms of a 16.6 ms step). Two places per layer are pure + * chains of them: * * norm_add_norm the attention's join: t = norm(a) * w_a; x += t; y = norm(x) * w_y * (post_attention_layernorm, the residual add, pre_feedforward_layernorm) * join_add_scale the feed-forward's: d' = norm(d) * w_d; r' = norm(r) * w_r; * j = norm(d' + r') * w_j; x = (x + j) * s; and optionally y = norm(x) * w_n * (post_feedforward_layernorm_1 and _2, the arms' sum, post_feedforward_layernorm, - * the residual add, layer_scalar -- and the NEXT layer's input_layernorm, or the - * final norm after the last layer, which read the x this writes) + * the residual add, layer_scalar, and the next layer's input_layernorm or the + * final norm, which read the x this writes) * - * THE SAME FUNCTION AS THE CHAIN, ROUNDING FOR ROUNDING. Every value the chain stores as bf16 is - * rounded to bf16 here at the same point, and every element is computed with libr4d's own - * expression: a norm is bf16((v * rsqrtf(mean(v^2) + eps)) * g), an add bf16(u + v), a scale - * bf16(x * s). The one thing that can differ is the ORDER the sum of squares is added in -- libr4d - * picks its block width from a measured table -- which moves the f32 norm factor by an ulp at most - * and, rarely, a bf16 output by one ulp. The arch plugin asks for these first and falls back to - * the chain where nothing serves them (gemma4.cpp). + * Same function as the chain, rounding for rounding: every value the chain stores as bf16 is + * rounded here at the same point, with libr4d's own expressions (a norm is + * bf16((v * rsqrtf(mean(v^2) + eps)) * g), an add bf16(u + v), a scale bf16(x * s)). Only the + * order of the sum of squares can differ (libr4d picks its block width from a table), moving the + * f32 norm factor by at most an ulp and, rarely, a bf16 output by one. The arch plugin falls back + * to the chain where nothing serves these (gemma4.cpp). * - * AND THE ROUTED ARM'S TWO INPUTS (norm_add_norm_route). The 26B-A4B's router reads norm(x) * w_r * - * hidden^-0.5 and its experts norm(x) * w_e, quantised to E4M3 -- two more launches a layer - * (`rmsnorm`, `rmsnorm_quant_fp8`), each reading back the x norm_add_norm has just written and - * taking the sum of squares norm_add_norm has just taken. The route form writes both from the norm - * factor it holds: the router's row by libr4d's rmsnorm expression, ((x * s) * w) * mult, and the - * experts' codes as libr4d's rmsnorm_quant_fp8 writes them -- the bf16-rounded norm, a scale of - * amax * (1 / 448) a 128 columns (1 where the group is all zero), the value times its reciprocal - * clamped to +-448, one v_cvt_pk_fp8_f32. Element i is thread i % 256 at slot i / 256, so a group - * is four waves at one slot: a wave's max, then the four. + * norm_add_norm_route also writes the routed arm's two inputs: the router's norm(x) * w_r * + * hidden^-0.5 and the experts' norm(x) * w_e quantised to E4M3, which would otherwise be two more + * launches (`rmsnorm`, `rmsnorm_quant_fp8`) re-reading x and redoing its sum of squares. The router + * row uses libr4d's rmsnorm expression, ((x * s) * w) * mult; the codes match rmsnorm_quant_fp8: + * the bf16-rounded norm, a scale of amax * (1 / 448) per 128 columns (1 for an all-zero group), + * value times reciprocal clamped to +-448, one v_cvt_pk_fp8_f32. Element i is thread i % 256 at + * slot i / 256, so a group is four waves at one slot: a wave max, then the four. * - * One 256-thread block a row: a decode step is a handful of rows, so the row is latency-bound and - * a block's three reductions beat seven launches. Values a later stage reuses stay in registers - * (PER a thread, 12 to n = 3072 and kMaxPer = 24 to 6144; the row table says so). + * One 256-thread block per row: a decode step is a handful of rows, so the row is latency bound + * and three block reductions beat seven launches. Values a later stage reuses stay in registers + * (PER per thread: 12 up to n = 3072, kMaxPer = 24 up to 6144; the row table enforces it). * - * EVERY LOAD IS ISSUED FIRST. A barrier is a fence, so a load written after a reduction waits for - * it: the first version fetched the gains, the residual and the layer scalar phase by phase and - * paid a global round trip for each on top of the reductions -- 17.8 us for join_add_scale and 13.2 - * for norm_add_norm at decode under --profile-ops, against ~7 for a launch that does nothing. Now - * the row's every operand is in flight at once, the two arm norms share one barrier pair, and a - * thread holds the elements it touches and no more. Nothing about the arithmetic moved: the same - * expressions in the same order, a sum's extra terms past n were +0. + * Every load is issued first. A barrier is a fence, so a load written after a reduction waits for + * it and pays a global round trip per phase. All of the row's operands are in flight at once, the + * two arm norms share one barrier pair, and a thread holds only the elements it touches. Sums over + * the padding past n add +0. */ #include diff --git a/libr4d/r4d_pair_argmax_f32.hip b/libr4d/r4d_pair_argmax_f32.hip index 19c23ec4..8cee28a2 100644 --- a/libr4d/r4d_pair_argmax_f32.hip +++ b/libr4d/r4d_pair_argmax_f32.hip @@ -1,17 +1,16 @@ -/* r4d_pair_argmax_f32.hip -- pair_argmax: the global argmax of a row of gathered (id, value) pairs, written as - * ONE CONTIGUOUS COLUMN of token ids. +/* r4d_pair_argmax_f32.hip -- pair_argmax: the global argmax of a row of gathered (id, value) pairs, + * written as one contiguous column of token ids. * - * WHY THIS OP EXISTS. A vocab-sharded draft head finds each rank's best candidates with `row_topk` - * and moves them with `all_gather`. The gather moves whole 16-byte words a row, and one (int32 id, - * f32 value) pair is 8 bytes, so a rank contributes at least R = 2 (rad_block_mtp_hc.h states the - * same bound). `row_topk_merge` then returns R = 2 columns a row, and a BLOCK drafter's proposal - * is `steps` contiguous ids a sequence -- column 0 of an [S, 2] plane is not that, and nothing in - * libr4d copies a strided i32 column. This reduces the gathered row to its top-1 and writes it + * A vocab-sharded draft head finds each rank's best candidates with `row_topk` and moves them with + * `all_gather`, which moves whole 16-byte words per row; a pair is 8 bytes, so a rank contributes + * at least R = 2 (rad_block_mtp_hc.h states the same bound). `row_topk_merge` then returns two + * columns per row, but a block drafter's proposal is `steps` contiguous ids per sequence, and + * nothing in libr4d copies a strided i32 column. This reduces the row to its top-1 and writes it * where the proposal reads it. * - * It is row_topk_merge at R = 1 with a strided output, rule for rule: the largest value wins, a tie - * goes to the LOWER id, and a pair whose id is negative (a slot a shard could not fill) is skipped. - * A row with no valid pair writes id -1 and value -inf. One wave a row, eight rows a workgroup. + * Same rules as row_topk_merge at R = 1, with a strided output: the largest value wins, a tie goes + * to the lower id, and a negative id (a slot a shard could not fill) is skipped. A row with no + * valid pair writes id -1 and value -inf. One wave per row, eight rows per workgroup. */ #include @@ -94,9 +93,10 @@ extern "C" int r4d_rad_pair_argmax_f32(const RadArgs* a, RadStream stream) { if (t->rank < 1 || t->shape[0] < rows || (v && (v->rank < 1 || v->shape[0] < rows))) return RAD_E_SHAPE; r4d_pick::PickArgs A{}; A.pairs = (const float*)p->data; A.p_rs = p->stride[0]; - A.tok = (int*)t->data; A.t_rs = t->rank >= 2 ? t->stride[0] : 1; + /* A row's element is stride[0] apart at any rank: a rank-1 output may be a strided column. */ + A.tok = (int*)t->data; A.t_rs = t->stride[0]; A.val = v ? (float*)v->data : nullptr; - A.v_rs = v ? (v->rank >= 2 ? v->stride[0] : 1) : 0; + A.v_rs = v ? v->stride[0] : 0; A.rows = rows; A.n = (int)n; R4D_KLAUNCH(R4D_KNAME(r4d_pick::pick_kernel), dim3((unsigned)((rows + 7) / 8)), dim3(256), diff --git a/libr4d/r4d_ple_conv_bf16.hip b/libr4d/r4d_ple_conv_bf16.hip index a2e3774f..6ad534ea 100644 --- a/libr4d/r4d_ple_conv_bf16.hip +++ b/libr4d/r4d_ple_conv_bf16.hip @@ -2,60 +2,31 @@ // residual add that finishes the layer; and, as `causal_conv1d`, the same convolution with no // activation, no residual and no dilation, which is LFM2's short convolution. // -// ============================== WHAT IT COMPUTES ============================== -// // y[t][c] = resid[t][c] + silu( sum_j w[c][j] * x[t - (width-1-j)*dilation][c] ) // -// libref/ref_ple.cpp is the oracle and docs/OPS.md the contract. THE TAPS ARE `dilation` APART, so -// at this model's width 4 and dilation 3 they sit 9, 6, 3 and 0 timesteps back and the history a -// sequence carries is (width-1)*dilation = NINE, not three. Every off-by-one in a convolution cache -// is a model that generates fluently from a slightly wrong context, so the indexing here mirrors -// ref's line for line: state slot `i` holds the value at relative position `i - hist`, a read at -// `src < 0` becomes `cs[slot][c][off + src + hist]`, and `has_init` 0 means that window is ZEROS -// rather than whatever the slot last held. +// libref/ref_ple.cpp is the oracle and docs/OPS.md the contract. The taps are `dilation` apart, so +// at width 4 and dilation 3 they sit 9, 6, 3 and 0 timesteps back and a sequence carries a history +// of (width-1)*dilation = 9, not 3. An off-by-one in a convolution cache yields fluent output from +// a slightly wrong context, so the indexing mirrors ref's line for line: state slot `i` holds +// relative position `i - hist`, a read at `src < 0` becomes `cs[slot][c][off + src + hist]`, and +// `has_init` 0 means that window is zeros, not the slot's stale contents. // -// ============================== ONE THREAD A CHANNEL ============================== -// -// A depthwise convolution never mixes channels, so the only axis that has to stay together is time. -// A thread owns one channel and walks a tile of tokens; consecutive threads own consecutive -// channels, so a wave's load is one contiguous 512-byte slice of a token row on both sides, and the -// time axis -- the one with the dependence -- never crosses a thread. +// One thread per channel: a depthwise convolution never mixes channels, so only time must stay +// together. A thread walks a tile of tokens; consecutive threads own consecutive channels, so a +// wave loads one contiguous 512-byte slice of a token row. // // The grid is (channel blocks, token tiles, sequences). Token tiles are counted from the batch's -// TOTAL token count, which is an upper bound on any one sequence's: a short sequence in a mixed -// batch launches a few blocks that find `t0 >= slen` and return, and the waste is bounded by the -// sequence count. Reading a per-sequence tile count would mean reading `cu` on the host. +// total token count, an upper bound on any one sequence's; a short sequence's extra blocks find +// `t0 >= slen` and return. A per-sequence count would mean reading `cu` on the host. // -// ============================== FOUR TAP READS AND NOT A SHIFT REGISTER ============================== +// The taps are read from memory, not kept in a shift register: the window would need `hist + 1` +// registers indexed by a runtime value, which compiles to a select tree (see CU_STATIC in +// r4d_gdn_conv_w4_h128_bf16.hip), and a compile-time window would need a specialisation per +// (width, dilation). The re-reads hit a tile working set of (BT + hist) * 512 bytes (21 KB at +// BT 32, L0-resident), and the op is bound by the three arrays it must touch anyway. // -// The taps move by ONE timestep per output while they are spaced `dilation` apart, so a thread that -// kept its window in registers would need `hist + 1` of them and would index that array by a value -// the compiler cannot see -- and a register array under a runtime index is not a register read, it -// is a select tree. The GDN conv update's CU_STATIC note records exactly that -// (r4d_gdn_conv_w4_h128_bf16.hip: a third of the kernel becomes s_cselect/v_cndmask choosing which -// register to read). A compile-time window would mean templating on (width, dilation) and a -// specialisation per model. -// -// So the taps are read where they lie. They are re-reads of the same 512-byte slice a handful of -// iterations apart -- a tile's whole working set is (BT + hist) * 512 bytes, 21 KB at BT 32, which -// is L0-resident -- and this op is bandwidth-bound on the three arrays it must touch anyway. If a -// profile ever says otherwise, the templated window is the change to make, not a runtime ring. -// -// ============================== THE WINDOW WRITE-BACK IS IN THE SAME LAUNCH ============================== -// -// The obvious reading says it cannot be: the write-back overwrites the window other blocks read, -// and a kernel boundary is the only grid-wide barrier this tree has. What makes it legal here is -// WHICH BLOCK READS THE STATE. History is reached only where `t - hist + j*dilation < 0`, so only -// tokens below `hist` -- nine of them -- read it at all, and they are all inside the 32-token TILE -// ZERO. One block reads state[slot][c], one thread inside it owns the whole channel, and its own -// reads are ordered before its own writes by program order. No barrier and no second dispatch. -// -// That matters because at decode this op is nothing but dispatch: its cost is flat from M=1 to -// M=8, which is the launches and none of the work. A second dispatch for the write-back would -// roughly double it. -// -// It only holds while `hist < kPcBT`, which the constraint table already guarantees -- the -// static_assert below is where that dependency is written down. +// The window write-back is in the same launch; see the note at the end of the kernel. It relies +// on `hist < kPcBT`, asserted below. #include "r4d.h" #include "r4d_args.h" #include "r4d_common.h" @@ -71,21 +42,18 @@ enum { kPcMaxHist = 16, /* (width-1)*dilation, the write-back's register window; see cPleConv */ }; -/* THE WINDOW WRITE-BACK LIVES IN TILE ZERO and that is only sound while the deepest tap is inside - * the first tile. At hist >= BT a second block would read history too, and the fold would overwrite - * bytes another block is still reading -- a wrong prefix on the first tokens of a sequence, which - * nothing downstream reports. The constraint table caps width and dilation so that hist <= 16; this - * is the line that says the tile size is the OTHER half of that bound. */ +/* The write-back lives in tile 0, which is sound only while the deepest tap is inside the first + * tile. At hist >= BT a second block would read history and the write-back would overwrite bytes + * it is still reading, silently corrupting a sequence's first tokens. The constraint table caps + * hist <= 16; the tile size is the other half of that bound. */ static_assert(kPcMaxHist < kPcBT, "the conv history must fit inside tile 0 for the fused write-back"); -/* x * sigmoid(x), and expf rather than __expf. The result is rounded to bf16 two instructions - * later, so the fast intrinsic's couple of ULP would be invisible in the bytes -- but this op is - * bound by the three arrays it moves, not by its transcendental, and the oracle it is checked - * against uses std::exp. The GDN conv, which is instruction-bound, makes the opposite trade. */ +/* expf rather than __expf: the op is bound by memory, not the transcendental, and the oracle uses + * std::exp. The instruction-bound GDN conv makes the opposite trade. */ __device__ __forceinline__ float pc_silu(float z) { return z / (1.0f + expf(-z)); } -/* SILU is ple_conv's activation; causal_conv1d (LFM2's short convolution) is the same window - * with none, no residual and dilation one. */ +/* SILU is ple_conv's activation; causal_conv1d (LFM2's short convolution) is the same window with + * no activation, no residual and dilation one. */ template __global__ __launch_bounds__(kPcThreads) void ple_conv_kernel( const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, @@ -108,9 +76,8 @@ __global__ __launch_bounds__(kPcThreads) void ple_conv_kernel( const int32_t slot = sidx ? sidx[s] : (int32_t)s; if (slot < 0) return; - /* A cold slot's window is ZEROS and not what the slot last held: a fresh sequence landing on a - * recycled slot would otherwise convolve the previous sequence's tail into its first `hist` - * tokens -- fluent output with the wrong prefix. */ + /* A cold slot's window is zeros: a fresh sequence on a recycled slot would otherwise convolve + * the previous sequence's tail into its first `hist` tokens. */ const bool warm = cs && (!hini || hini[s] != 0); const long long off = nacc ? (long long)nacc[s] - 1 : 0; @@ -140,29 +107,22 @@ __global__ __launch_bounds__(kPcThreads) void ple_conv_kernel( yc[(size_t)t * yld] = f32_to_bf16(r + (SILU ? pc_silu(acc) : acc)); } - /* THE WINDOW THIS STEP LEAVES BEHIND, in the same launch and with no barrier at all. + /* The window this step leaves, in the same launch with no barrier. History is read only where + * `t - hist + j*dilation < 0`, i.e. by tokens below `hist` (9, against a 32-token tile), so + * tile 0 is the only block touching state[slot][c]. One thread owns the whole channel there, so + * its reads precede its writes in program order. At decode the op's cost is the dispatch itself + * (flat from M=1 to M=8), so a second launch would roughly double it. * - * WHICH BLOCK READ THE STATE decides that this is legal: history is read only where - * `t - hist + j*dilation < 0`, so only tokens below `hist` reach back -- and `hist` is 9 - * against a 32-token tile, so TILE ZERO is the only block that ever touches state[slot][c]. - * Within it one thread owns a whole channel, so its own reads are ordered before its own - * writes by program order and there is nothing to synchronise. + * The layout is libref/ref_ple.cpp's, chosen by `num_accepted`. Present, this is a decode step + * whose drafts a verify may reject: the history read shifts down by one and every input of the + * step follows it, slot i holding position i + 1 of (window read ++ step), so a next step that + * kept k tokens reads at k - 1. Absent, every token commits and the last `hist` inputs land at + * offset zero. The two agree at one token. Slots past `state_len` are not written; the manager + * sizes the window hist + n_spec, enough for a step of 1 + n_spec tokens. * - * Folding it in matters because at decode this op is nothing but launches: its cost is flat - * from M=1 to M=8, which is the dispatches and none of the work. - * - * THE LAYOUT IS libref/ref_ple.cpp's, and `num_accepted` picks it. Present, this is a decode - * step whose drafts a verify may reject: the history read is shifted down by one and every - * input of the step follows it, slot i holding position i + 1 of (window read ++ step), so a - * next step that kept k tokens reads at k - 1 and finds the history ending at the k-th. - * Absent, every token commits and the last `hist` inputs land at offset zero. The two agree - * at one token. Slots past `state_len` are not written; the manager sizes the window - * hist + n_spec, which covers a step of 1 + n_spec tokens. - * - * The values are copied as bf16 BITS -- the same tensor's bytes on both sides, and a round - * trip through f32 would be a second definition of the state's precision. The step's rows - * come out of `x`, which is read-only here, so reading rows another tile is also reading is - * not a hazard. Every history value is loaded before the first store, as in the tail form. */ + * Values are copied as bf16 bits, the same tensor's bytes on both sides. The step's rows come + * from the read-only `x`, so other tiles reading them is no hazard. Every history value is + * loaded before the first store. */ if (!dst || blockIdx.y != 0) return; uint16_t keep[kPcMaxHist]; if (nacc) { @@ -204,9 +164,9 @@ int conv_launch(const RadArgs* a, RadStream s, bool silu, const RadTensor* x, co if (cs && cs->data && cs->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); if (cu->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE); if (cidx && cidx->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE); - /* `has_init` IS THE CALLER'S WIDTH and reading it as bytes is how the GDN conv lost a long - * prompt's history: ctx_len 512 has a zero low byte. The engine hands over RadBatch::ctx_lens, - * which is int32 like every derived buffer, so anything else is refused rather than guessed. */ + /* `has_init` must be int32 (RadBatch::ctx_lens, like every derived buffer): read as bytes, a + * ctx_len of 512 has a zero low byte and the history would be dropped. Anything else is + * refused. */ if (hini && hini->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE); if (nacc && nacc->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE); @@ -224,8 +184,8 @@ int conv_launch(const RadArgs* a, RadStream s, bool silu, const RadTensor* x, co const long long rld = resid ? r4d_rows_pitch(resid, n, &tr) : 0; const long long wld = r4d_rows_pitch(w, wid, &wrows); if (xld < 0 || yld < 0 || wld < 0 || (resid && rld < 0)) return R4D_NO(RAD_E_STRIDE); - /* THE ROW COUNT COMES FROM THE OPERANDS AND EVERY ONE HAS TO AGREE. `M` is ranged, so the value - * in the args is the band's upper bound and a grid sized by it walks off the arena. */ + /* The row count comes from the operands, and they must agree: `M` is ranged, so the arg holds + * the band's upper bound and a grid sized by it would run off the arena. */ if (T <= 0 || ty != T || (resid && tr != T)) return R4D_NO(RAD_E_SHAPE); if (wrows < n) return R4D_NO(RAD_E_SHAPE); @@ -233,9 +193,9 @@ int conv_launch(const RadArgs* a, RadStream s, bool silu, const RadTensor* x, co if (N <= 0) return R4D_NO(RAD_E_SHAPE); if (!r4d_contig(cu)) return R4D_NO(RAD_E_STRIDE); - /* [n_slots, n, state_len]. A state too shallow for the deepest tap is refused here; the OFFSET - * a rollback reads at cannot be checked without reading `num_accepted` on the host, and the - * manager sizes the window as hist + n_spec for exactly that reason. */ + /* [n_slots, n, state_len]. A state too shallow for the deepest tap is refused here; the + * rollback offset cannot be checked without reading `num_accepted` on the host, which is why + * the manager sizes the window hist + n_spec. */ long long cs_slot = 0, cs_ch = 0, cs_tok = 0, state_len = 0; const bool have_cs = cs && cs->data && hist > 0; if (have_cs) { diff --git a/libr4d/r4d_ple_gate_bf16.hip b/libr4d/r4d_ple_gate_bf16.hip index a4f7ead2..77dd9f37 100644 --- a/libr4d/r4d_ple_gate_bf16.hip +++ b/libr4d/r4d_ple_gate_bf16.hip @@ -1,45 +1,29 @@ // r4d_ple_gate_bf16.hip -- Per-Layer Embedding's dot-product gate. // -// ============================== WHAT IT COMPUTES ============================== -// // K[c] = grouped_rmsnorm(k)[c] * (w_key + wadd) k is key_proj(embedding) -// Q[c] = grouped_rmsnorm(q)[c] * (w_query + wadd) q is the INCOMING hc stream +// Q[c] = grouped_rmsnorm(q)[c] * (w_query + wadd) q is the incoming hc stream // s[c] = sum_d K[c][d] * Q[c][d] / sqrt(n) -// s[c] = sign(s[c]) * sqrt(max(|s[c]|, gate_eps)) <- the SIGNED square root -// gv[c] = sigmoid(s[c]) * v v is value_proj(embedding), ONE row +// s[c] = sign(s[c]) * sqrt(max(|s[c]|, gate_eps)) <- the signed square root +// gv[c] = sigmoid(s[c]) * v v is value_proj(embedding), one row // gvn = grouped_rmsnorm(gv) * (w_conv + wadd) // -// libref/ref_ple.cpp is the oracle and docs/OPS.md the contract. THE SIGN COMES FROM THE ORIGINAL, -// not from the clamped magnitude: torch's sign(0) is 0, so a dot of exactly zero stays zero instead -// of becoming sqrt(gate_eps), and a quantised activation row produces exact zeros. +// libref/ref_ple.cpp is the oracle and docs/OPS.md the contract. The sign comes from the original +// value, not the clamped magnitude: torch's sign(0) is 0, so an exactly-zero dot (as a quantised +// activation row produces) stays zero instead of becoming sqrt(gate_eps). // -// ============================== ONE WORKGROUP A (ROW, STREAM) ============================== +// One workgroup per (row, stream): every reduction (two norms, the dot, the gate's rms) is over +// one stream's `n`, and a workgroup is the widest unit that reduces without a second launch. At +// decode that is four workgroups, which is fine: the op moves 107 KB a row and is latency bound +// well before occupancy matters. // -// Every reduction here is over ONE stream's `n` -- two for the norms, one for the dot, one for the -// gate's own rms -- and a workgroup is the widest thing that reduces without a second launch. So a -// workgroup owns one (row, stream) pair and each thread carries n/threads elements of it. +// Each thread keeps its n/threads elements of k and q in registers across the norm and the dot, +// and `gv` from its store to its rms, so nothing is read twice. `gv` is narrowed to bf16 before +// its rms, because the reference norms the bf16 tensor it wrote; keeping the f32 value would give +// a different number. // -// AT DECODE THAT IS FOUR WORKGROUPS, which is 1.6% of this part, and it is the right shape anyway: -// the op moves 107 KB a row and is latency-bound long before it is occupancy-bound. Splitting the -// reduction across workgroups would buy parallelism the launch floor eats. -// -// ============================== WHY k AND q LIVE IN REGISTERS ============================== -// -// The naive form reads k and q once for the norm and again for the dot. Each thread instead keeps -// its own n/threads elements across both passes -- 10 values at this model's shape, 20 halves, ten -// VGPRs -- and the second read disappears. The same trick carries `gv` from where it is written to -// where its rms is taken. -// -// AND THAT IS NOT A SHORTCUT PAST THE NARROWING. `gv` is narrowed to bf16 BEFORE the rms sees it, -// because the reference writes a bf16 tensor and norms what was written; keeping the narrowed value -// in a register is the same bits as storing and reading it back. Keeping the f32 accumulator would -// be a different number -- the epilogue-fold rule the GDN projection states at more length. -// -// ============================== AN INVARIANT WORTH KNOWING ============================== -// -// gv[c] is a SCALAR times one shared v row, and norm_conv's rms is per stream -- so the gate divides -// straight back out and `gvn` does not depend on it at all. Exact only in exact arithmetic (gv is -// narrowed first), so it is a thing to CHECK a fused kernel against, never a thing to fold. +// Invariant: gv[c] is a scalar times one shared v row and norm_conv's rms is per stream, so the +// gate cancels out of `gvn`. This holds only in exact arithmetic (gv is narrowed first), so it is a +// property to check a fused kernel against, never one to fold. #include "r4d.h" #include "r4d_args.h" #include "r4d_common.h" @@ -50,19 +34,16 @@ namespace { enum { kPgThreads = 256 }; -/* A value narrowed to bf16 and read back, which is what the reference's `.type_as(x)` does after - * every norm. One definition, used four times below. */ +/* A value narrowed to bf16 and read back, as the reference's `.type_as(x)` after every norm. */ __device__ __forceinline__ float pg_narrow(float v) { return bf16_to_f32(f32_to_bf16(v)); } -/* expf and NOT __expf. The fast intrinsic is a couple of ULP off, and this gate is compared against - * libref's std::exp to a tolerance meant for summation order -- one op in one layer of the model is - * not where to spend accuracy on an instruction. */ +/* expf, not __expf: this gate is compared against libref's std::exp with a tolerance meant for + * summation order. */ __device__ __forceinline__ float pg_sigmoid(float x) { return 1.0f / (1.0f + expf(-x)); } -/* A workgroup-wide sum through LDS, called four times. The trailing barrier is what lets the same - * array serve the next reduction without a second allocation. */ +/* A workgroup-wide sum through LDS. The trailing barrier lets the next call reuse the array. */ __device__ __forceinline__ float pg_reduce(float v, float* lds) { const uint32_t t = threadIdx.x; lds[t] = v; @@ -85,8 +66,7 @@ __global__ __launch_bounds__(kPgThreads) void ple_gate_kernel( uint32_t g_ld, uint32_t gn_ld, float eps, float wadd, float geps, uint32_t per_thread) { __shared__ float lds[kPgThreads]; - /* `gv` is carried from where it is written to where its rms is taken. 16 is the widest this - * kernel serves: n <= 16 * kPgThreads = 4096, which the row constrains. */ + /* At most 16 elements per thread: n <= 16 * kPgThreads = 4096, which the row constrains. */ float mine_k[16], mine_q[16], mine_gv[16]; const uint32_t row = blockIdx.x / hc; @@ -120,8 +100,8 @@ __global__ __launch_bounds__(kPgThreads) void ple_gate_kernel( } float s = pg_reduce(dot, lds) * rsqrtf((float)n); - /* THE SIGNED SQUARE ROOT, in the reference's order: clamp the MAGNITUDE, take the root, and - * take the SIGN FROM THE ORIGINAL. sign(0) is 0, so an exactly-zero dot stays zero. */ + /* The signed square root in the reference's order: clamp the magnitude, take the root, take the + * sign from the original. */ const float mag = sqrtf(fabsf(s) < geps ? geps : fabsf(s)); s = s > 0.0f ? mag : (s < 0.0f ? -mag : 0.0f); const float gate = pg_sigmoid(s); @@ -183,8 +163,8 @@ extern "C" int r4d_rad_ple_gate(const RadArgs* a, RadStream s) { const long long g_ld = r4d_rows_pitch(gv, hn, &tg); const long long gn_ld = r4d_rows_pitch(gvn, hn, &tn); if (k_ld < 0 || q_ld < 0 || v_ld < 0 || g_ld < 0 || gn_ld < 0) return R4D_NO(RAD_E_STRIDE); - /* THE ROW COUNT COMES FROM THE OPERANDS AND EVERY ONE HAS TO AGREE: `M` is ranged, so the - * value in the args is the band's upper bound, and a grid sized by it walks off the arena. */ + /* The row count comes from the operands, and they must agree: `M` is ranged, so the arg holds + * the band's upper bound and a grid sized by it would run off the arena. */ if (T <= 0 || tq != T || tv != T || tg != T || tn != T) return R4D_NO(RAD_E_SHAPE); if (r4d_numel(wk) < hn || r4d_numel(wq) < hn || r4d_numel(wc) < hn) return R4D_NO(RAD_E_SHAPE); diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 1b410c23..7031530f 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -1,10 +1,9 @@ /* r4d_plugin.h -- what libr4d's translation units share. * - * The row table (r4d_rows.cpp) and the weight layouts (r4d_layout.cpp) are PURE HOST C++ and - * include only this file and the ABI; the launch shims include r4d.h and therefore - * . That split is deliberate: it is what lets the constraint table -- the part - * a transcription error hides in -- be compiled and read on a machine with no ROCm, and it is why - * every shim is declared here rather than in the file that defines it. + * The row table (r4d_rows.cpp) and the weight layouts (r4d_layout.cpp) are pure host C++ and + * include only this file and the ABI; the launch shims include r4d.h and so . + * The split lets the constraint table compile and be checked without ROCm, and is why every shim + * is declared here rather than beside its definition. * * Nothing in this header may include r4d.h. */ @@ -16,68 +15,61 @@ /* ================================================================== the priority ladder * - * The selector ranks candidate rows by an integer priority (spec §2.1). Where two rows of one op - * can both match a geometry, the value is what decides which serves it; each group below states - * the reason its order is what it is. - * - * Values are spaced by ten so a row can be slipped between two of them without renumbering. + * The selector ranks candidate rows by an integer priority (spec §2.1); where two rows of one op + * can match a geometry, it decides which serves. Each group states the reason for its order. + * Values are spaced by ten so a row can be slipped between two without renumbering. */ enum { - /* A two-shot row's constraints are a SUPERSET of the one-shot's at the same world_size, so a - * two-shot that ranked below could never be reached: every query it serves the one-shot also - * matches. Its lower bound on `numel` is what keeps a small message on the one-shot, and the - * priority is what hands a large one to the two-shot. */ + /* A two-shot row's constraints are a superset of the one-shot's at the same world_size, so it + * must rank higher to be reachable. Its lower bound on `numel` keeps small messages on the + * one-shot. */ R4D_PRIO_AR_TWOSHOT = 70, R4D_PRIO_AR_ONESHOT = 60, - /* One op (`attn_paged`) banded on q_len, so the decode row's bound -- q_len<=10 at h256, - * q_len<=16 at h128 -- is a bucket boundary and not a partition: inside the low band BOTH rows - * match. The decode row therefore has to outrank the prefill one, which is the same choice a - * caller selecting an entry point by hand would make. */ + /* `attn_paged` is banded on q_len, and the decode row's bound (q_len<=10 at h256, q_len<=16 at + * h128) is a bucket boundary, not a partition: both rows match in the low band, so decode must + * outrank prefill. */ R4D_PRIO_ATTN_DECODE = 70, R4D_PRIO_ATTN_PREFILL = 60, /* The windowed kernels (r4d_attn_paged_window.hip) serve every q_len, so where their geometry - * meets another leg's -- h256 at gqa 2 -- they match in both of that leg's bands, and rank - * below both: timed by rad-kbench on two R9700s at the 31B's shapes (window 1024, fp8 cache), - * the h256/gqa2 decode kernel takes 0.26-0.71 of the windowed kernel's time at q_len 1..32 and - * its prefill kernel 0.43-0.67 at 33..512, a bf16 cache the same order. The windowed rows keep - * that geometry's non-causal band past q_len 32, and attn_paged_qrow, which no other kernel - * serves. */ + * meets another leg's (h256 at gqa 2) they match in both of that leg's bands and rank below + * both: on R9700 at the 31B's shapes (window 1024, fp8 cache) the h256/gqa2 decode kernel takes + * 0.26-0.71 of the windowed kernel's time at q_len 1..32 and its prefill kernel 0.43-0.67 at + * 33..512, bf16 cache similar. The windowed rows keep that geometry's non-causal band past + * q_len 32, and attn_paged_qrow, which no other kernel serves. */ R4D_PRIO_ATTN_WINDOW = 50, - /* At M<=16 with K%256==0 both bf16 skinny rows match and the m16 (dot2) kernel is taken. - * The m64 WMMA kernel is faster on every shape measured, so a caller that wants it at low M - * asks with M=64 to exclude m16. */ + /* At M<=16 with K%256==0 both bf16 skinny rows match and the m16 (dot2) kernel is taken. The + * m64 WMMA kernel is faster on every shape measured, so a caller wanting it at low M asks with + * M=64 to exclude m16. */ R4D_PRIO_GEMM_M16 = 60, R4D_PRIO_GEMM_SKINNY = 50, /* The MXFP4 decode row outranks the MXFP4 skinny row, whose band it shares up to N = 36864. */ R4D_PRIO_GEMM_MXDEC = 55, - /* The skinny m64 row has no upper bound on M, so the tiled bf16 row -- M > 64 only -- has to - * outrank it to be reached, and stays below m16 whose band it never enters. */ + /* The skinny m64 row has no upper bound on M, so the tiled bf16 row (M > 64 only) must outrank + * it, and stays below m16, whose band it never enters. */ R4D_PRIO_GEMM_BF16_TILED = 55, - /* The bands already separate the tiled and prefill GEMMs from the skinny kernels -- skinny is - * M<=64, these are unbounded -- so this pair only decides the M>64 band. `pf` is the newer - * kernel and its tuned picks fall back to the tiled one where it is absent, so it outranks. - * WHAT THIS CANNOT EXPRESS: the optimum crosses BETWEEN the two kernels at a shape-dependent - * M, and the tuning axis is variants WITHIN a kernel, so a per-shape crossover has no home - * here. */ + /* Bands already separate these from the skinny kernels (skinny is M<=64, these unbounded), so + * this pair only decides M>64. `pf` is the newer kernel and its tuned picks fall back to the + * tiled one, so it outranks. Not expressible here: the optimum crosses between the two kernels + * at a shape-dependent M, and tuning varies only within a kernel. */ R4D_PRIO_GEMM_PREFILL = 40, R4D_PRIO_GEMM_TILED = 30, - /* The block-scaled fp8 family. fp8a16 is a separate dtype and needs no ordering against these - * two; the narrow fp8a8 row's M <= 16 is a subset of the tiled row's unbounded M, so the - * narrow row must outrank or it could not be reached. These sit above the skinny int8 GEMMs' - * band only in the sense that no dtype string reaches both. */ + /* The block-scaled fp8 family. fp8a16 is a separate dtype and needs no ordering against these; + * the narrow fp8a8 row's M <= 16 is a subset of the tiled row's unbounded M, so it must + * outrank. No dtype string reaches both these and the skinny int8 GEMMs. */ R4D_PRIO_GEMM_FP8_M16 = 60, R4D_PRIO_GEMM_FP8_TILED = 40, - /* The lm_head at fp8, above the bf16 projection: both serve the same declared geometry, and - * the one that reads half the bytes wins. The container follows the resolved row (spec 4.2), - * so this choice is what decides the format the head is stored in. */ + /* The lm_head at fp8 (and int8), above the bf16 projection, which reads twice the bytes. + * The head's encoding, fixed at conversion, decides which rows are candidates (spec §4.3): + * these rows' layout hooks refuse a bf16 head, and the bf16 row has no hook for a scaled + * one. */ R4D_PRIO_LOGITS_FP8 = 60, - /* Everything with exactly one candidate row per (op, geometry). The value carries no ordering - * information; it exists so a user's override plugin has room underneath and above. */ + /* Exactly one candidate row per (op, geometry). The value carries no ordering; it leaves a + * user's override plugin room above and below. */ R4D_PRIO_ONLY = 50, }; @@ -97,17 +89,17 @@ int r4d_rad_attn_decode_h128_fp8 (const RadArgs*, RadStream); int r4d_rad_attn_decode_h128_bf16 (const RadArgs*, RadStream); int64_t r4d_rad_attn_decode_h256_scratch(const RadArgs*); int64_t r4d_rad_attn_decode_h128_scratch(const RadArgs*); - /* Gemma 4 dense sliding window (r4d_attn_paged_h256_gqa2.hip): head_dim 256, 2 queries per KV head, - * windowed. Both bands: the decode band (q_len*gqa <= 64, verify width 32 against the gqa6 leg's - * 10) and the windowed prefill band (the same r4d_attn_prefill_kernel the gqa6 leg uses, WIN on). */ - int r4d_rad_attn_prefill_h256_gqa2_fp8 (const RadArgs*, RadStream); - int r4d_rad_attn_prefill_h256_gqa2_bf16 (const RadArgs*, RadStream); - int r4d_rad_attn_decode_h256_gqa2_fp8 (const RadArgs*, RadStream); - int r4d_rad_attn_decode_h256_gqa2_bf16 (const RadArgs*, RadStream); - int64_t r4d_rad_attn_decode_h256_gqa2_scratch(const RadArgs*); +/* Gemma 4 dense sliding window (r4d_attn_paged_h256_gqa2.hip): head_dim 256, 2 queries per KV + * head. Both bands: decode (q_len*gqa <= 64, verify width 32 against the gqa6 leg's 10) and + * windowed prefill (the gqa6 leg's r4d_attn_prefill_kernel with WIN on). */ +int r4d_rad_attn_prefill_h256_gqa2_fp8 (const RadArgs*, RadStream); +int r4d_rad_attn_prefill_h256_gqa2_bf16 (const RadArgs*, RadStream); +int r4d_rad_attn_decode_h256_gqa2_fp8 (const RadArgs*, RadStream); +int r4d_rad_attn_decode_h256_gqa2_bf16 (const RadArgs*, RadStream); +int64_t r4d_rad_attn_decode_h256_gqa2_scratch(const RadArgs*); /* Paged attention at head_dim 256 and 512, 1/2/4/8 queries per KV head, any window, causal or not - * (r4d_attn_paged_window.hip): one entry point a geometry and cache dtype, serving every q_len and - * reading q at any row pitch, so the same entry points serve attn_paged and attn_paged_qrow. */ + * (r4d_attn_paged_window.hip): one entry point per geometry and cache dtype, every q_len and any q + * row pitch, so they serve both attn_paged and attn_paged_qrow. */ int r4d_rad_attn_window_h256_gqa1_bf16(const RadArgs*, RadStream); int r4d_rad_attn_window_h256_gqa1_fp8 (const RadArgs*, RadStream); int r4d_rad_attn_window_h256_gqa2_bf16(const RadArgs*, RadStream); @@ -138,6 +130,7 @@ int r4d_rad_join_add_scale_bf16 (const RadArgs*, RadStream); int r4d_rad_expert_scale_bf16 (const RadArgs*, RadStream); int r4d_rad_attn_vit (const RadArgs*, RadStream); int r4d_rad_attn_dense (const RadArgs*, RadStream); +int r4d_rad_seg_sinusoid (const RadArgs*, RadStream); /* The image generator's attention (r4d_attn_gen.hip): a paged prefix and the pass's own rows, the * causal-capable dense form at head_dim 128 (a text encoder's prompt), and one 1152-wide head * (an image decoder's mid block). */ @@ -162,9 +155,9 @@ int r4d_rad_s2d_avg_add (const RadArgs*, RadStream); int r4d_rad_to_rgba8 (const RadArgs*, RadStream); int r4d_rad_gelu_tanh (const RadArgs*, RadStream); int r4d_rad_scatter_add_rows (const RadArgs*, RadStream); -/* Eight queries per KV head (r4d_attn_paged_gqa8.hip): the routed 35B-A3B at head_dim 256 - * and MiniCPM5-2B at 128. A decode workgroup holds 64 rows of q_len*gqa, so the verify - * width is 8 here against the gqa6 leg's 10 -- which is the row's constraint value. */ +/* Eight queries per KV head (r4d_attn_paged_gqa8.hip): the routed 35B-A3B at head_dim 256 and + * MiniCPM5-2B at 128. A decode workgroup holds 64 rows of q_len*gqa, so the verify width (the + * row's constraint value) is 8, against the gqa6 leg's 10. */ int r4d_rad_attn_prefill_h256_gqa8_fp8 (const RadArgs*, RadStream); int r4d_rad_attn_prefill_h256_gqa8_bf16(const RadArgs*, RadStream); int r4d_rad_attn_decode_h256_gqa8_fp8 (const RadArgs*, RadStream); @@ -175,54 +168,45 @@ int r4d_rad_attn_prefill_h128_gqa8_bf16(const RadArgs*, RadStream); int r4d_rad_attn_decode_h128_gqa8_fp8 (const RadArgs*, RadStream); int r4d_rad_attn_decode_h128_gqa8_bf16 (const RadArgs*, RadStream); int64_t r4d_rad_attn_decode_h128_gqa8_scratch(const RadArgs*); -/* Four queries a KV head, head_dim 256 only -- Qwen3.5-0.8B. Same body, different - * instantiation (r4d_attn_paged_h256_gqa4.hip). */ +/* Four queries per KV head, head_dim 256 only (Qwen3.5-0.8B); same body, another instantiation + * (r4d_attn_paged_h256_gqa4.hip). */ int r4d_rad_attn_prefill_h256_gqa4_fp8 (const RadArgs*, RadStream); int r4d_rad_attn_prefill_h256_gqa4_bf16(const RadArgs*, RadStream); int r4d_rad_attn_decode_h256_gqa4_fp8 (const RadArgs*, RadStream); int r4d_rad_attn_decode_h256_gqa4_bf16 (const RadArgs*, RadStream); int64_t r4d_rad_attn_decode_h256_gqa4_scratch(const RadArgs*); -/* ...and its head_dim 64 prefill leg, LFM2's geometry, which serves every query length. */ +/* ...and its head_dim 64 prefill leg, LFM2's geometry, serving every query length. */ int r4d_rad_attn_prefill_h64_gqa4_fp8 (const RadArgs*, RadStream); int r4d_rad_attn_prefill_h64_gqa4_bf16(const RadArgs*, RadStream); -/* Twelve queries a KV head, head_dim 256 only -- Qwen3.8-Flash-Next's QSA layers. Same body, - * different instantiation; r4d_attn_paged_h256_gqa12.hip is four lines. */ +/* Two queries per KV head at head_dim 128 (Qwen3-1.7B, Qwen3-ASR's decoder): the gqa8 body at + * gqa 2 (r4d_attn_paged_h128_gqa2.hip). */ +int r4d_rad_attn_prefill_h128_gqa2_fp8 (const RadArgs*, RadStream); +int r4d_rad_attn_prefill_h128_gqa2_bf16(const RadArgs*, RadStream); +int r4d_rad_attn_decode_h128_gqa2_fp8 (const RadArgs*, RadStream); +int r4d_rad_attn_decode_h128_gqa2_bf16 (const RadArgs*, RadStream); +int64_t r4d_rad_attn_decode_h128_gqa2_scratch(const RadArgs*); +/* Twelve queries per KV head, head_dim 256 only: Qwen3.8-Flash-Next's QSA layers. Same body, + * another instantiation (r4d_attn_paged_h256_gqa12.hip). */ int r4d_rad_attn_prefill_h256_gqa12_fp8 (const RadArgs*, RadStream); int r4d_rad_attn_prefill_h256_gqa12_bf16(const RadArgs*, RadStream); int r4d_rad_attn_decode_h256_gqa12_fp8 (const RadArgs*, RadStream); -int r4d_rad_attn_decode_h256_gqa12_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, - int, int*); int r4d_rad_attn_decode_h256_gqa12_bf16 (const RadArgs*, RadStream); -int r4d_rad_attn_decode_h256_gqa12_bf16_describe(const RadArgs*, RadStream, RadLaunchDesc*, - int, int*); int r4d_rad_attn_decode_gq_h256_gqa12_fp8(const RadArgs*, RadStream); -int r4d_rad_attn_decode_gq_h256_gqa12_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, - int, int*); int r4d_rad_attn_decode_gq_h256_gqa12_bf16(const RadArgs*, RadStream); -int r4d_rad_attn_decode_gq_h256_gqa12_bf16_describe(const RadArgs*, RadStream, RadLaunchDesc*, - int, int*); int64_t r4d_rad_attn_decode_h256_gqa12_scratch(const RadArgs*); -/* Six queries a KV head, head_dim 256, paged block 4 -- the same QSA layers at four ranks, where - * the KV head is replicated across a rank pair. Same body again; the verify width is 64/6 = 10 - * against gqa12's 5, which is the decode rows' constraint value. */ +/* Six queries per KV head, head_dim 256, paged block 4: the same QSA layers at four ranks, with + * the KV head replicated across a rank pair. The verify width is 64/6 = 10 against gqa12's 5, + * the decode rows' constraint value. */ int r4d_rad_attn_prefill_h256_gqa6_fp8 (const RadArgs*, RadStream); int r4d_rad_attn_prefill_h256_gqa6_bf16(const RadArgs*, RadStream); int r4d_rad_attn_decode_h256_gqa6_fp8 (const RadArgs*, RadStream); -int r4d_rad_attn_decode_h256_gqa6_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, - int, int*); int r4d_rad_attn_decode_h256_gqa6_bf16 (const RadArgs*, RadStream); -int r4d_rad_attn_decode_h256_gqa6_bf16_describe(const RadArgs*, RadStream, RadLaunchDesc*, - int, int*); int64_t r4d_rad_attn_decode_h256_gqa6_scratch(const RadArgs*); -/* The same two merges with the output gate and the quantiser in them, at the four-rank ratio. The - * body instantiates these at every ratio (`R4D_ATTN_GQA` pastes them), so unlike `all_gather` this - * one needed a ROW and not a kernel — see attn_decode_gq_h256_gqa6_fp8kv. */ +/* The same two merges with the output gate and the quantiser, at the four-rank ratio. The body + * instantiates these at every ratio (`R4D_ATTN_GQA` pastes them), so this needed a row, not a + * kernel; see attn_decode_gq_h256_gqa6_fp8kv. */ int r4d_rad_attn_decode_gq_h256_gqa6_fp8(const RadArgs*, RadStream); -int r4d_rad_attn_decode_gq_h256_gqa6_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, - int, int*); int r4d_rad_attn_decode_gq_h256_gqa6_bf16(const RadArgs*, RadStream); -int r4d_rad_attn_decode_gq_h256_gqa6_bf16_describe(const RadArgs*, RadStream, RadLaunchDesc*, - int, int*); /* -- gated delta net (r4d_gdn_*.hip) -- */ int r4d_rad_gdn_chunk_scan (const RadArgs*, RadStream); @@ -230,8 +214,8 @@ int r4d_rad_gdn_conv_prep (const RadArgs*, RadStream); int r4d_rad_gdn_conv_update (const RadArgs*, RadStream); int r4d_rad_gdn_kkt_solve (const RadArgs*, RadStream); int r4d_rad_gdn_recurrent_update(const RadArgs*, RadStream); -/* gdn_conv_update folded into the recurrent update's prologue: the decode shape, q/k/v never - * written (r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip). */ +/* gdn_conv_update folded into the recurrent update's prologue for the decode shape; q/k/v are + * never written (r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip). */ int r4d_rad_gdn_conv_recurrent_update(const RadArgs*, RadStream); int r4d_rad_gdn_gated_rmsnorm (const RadArgs*, RadStream); int r4d_rad_dflash_conv (const RadArgs*, RadStream); @@ -240,19 +224,16 @@ int r4d_rad_dflash_select (const RadArgs*, RadStream); /* -- the gated residual (r4d_hc_bf16.hip) -- */ int r4d_rad_hc_enter (const RadArgs*, RadStream); int r4d_rad_mtp_enter (const RadArgs*, RadStream); -int r4d_rad_mtp_enter_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int64_t r4d_rad_mtp_enter_scratch(const RadArgs*); int r4d_rad_hc_read (const RadArgs*, RadStream); -int r4d_rad_hc_read_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int64_t r4d_rad_hc_read_scratch(const RadArgs*); int r4d_rad_hc_write (const RadArgs*, RadStream); -int r4d_rad_hc_write_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); /* -- all-reduce (r4d_ar_entry.hip) -- */ int r4d_rad_ar_init(const RadParam*, int, int rank, int world, void** out); void r4d_rad_ar_fini(void*); -/* The same three inits with every rank's exchange buffers in pinned host memory: the host twins - * of the collective rows (r4d_rows.cpp) take them, and every launch and the fini are shared. */ +/* The same three inits with every rank's exchange buffers in pinned host memory, for the host + * twins of the collective rows (r4d_rows.cpp); launches and fini are shared. */ int r4d_rad_ar_host_init(const RadParam*, int, int rank, int world, void** out); int r4d_rad_ar_ln_host_init(const RadParam*, int, int rank, int world, void** out); int r4d_rad_ar_hc_wide_host_init(const RadParam*, int, int rank, int world, void** out); @@ -295,7 +276,6 @@ int r4d_rad_gemm_w4a16asym_m64(const RadArgs*, RadStream); int r4d_rad_gemm_w4a8i8_tiled(const RadArgs*, RadStream); int r4d_rad_gemm_w5a8i8_tiled(const RadArgs*, RadStream); int r4d_rad_givens_dense_quant(const RadArgs*, RadStream); -int r4d_rad_givens_dense_quant_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_gemm_w8a16_m64 (const RadArgs*, RadStream); int r4d_rad_gemm_w4a8_m64 (const RadArgs*, RadStream); int r4d_rad_gemm_w4a8_tiled (const RadArgs*, RadStream); @@ -310,52 +290,42 @@ int r4d_rad_gemm_mxfp4a8_decode(const RadArgs*, RadStream); int64_t r4d_rad_gemm_mxfp4a8_decode_scratch(const RadArgs*); int r4d_rad_dequant_w4 (const RadArgs*, RadStream); int r4d_rad_rowtopk (const RadArgs*, RadStream); -int r4d_rad_rowtopk_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int64_t r4d_rad_rowtopk_scratch(const RadArgs*); int r4d_rad_rowtopk_merge (const RadArgs*, RadStream); int r4d_rad_logit_rerank (const RadArgs*, RadStream); -int r4d_rad_logit_rerank_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_logit_rerank_i8 (const RadArgs*, RadStream); -int r4d_rad_logit_rerank_i8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); /* -- the routed mixture of experts (r4d_moe.hip) -- * - * `moe_gemm_q`'s weight operands are TABLES (RAD_OPD_WTAB): the core resolves a run of declared - * weights to a device array of pointers, one per expert, because after placement a layer's - * experts are not in one place. See abi/rad_runtime.h. */ + * `moe_gemm_q`'s weight operands are tables (RAD_OPD_WTAB): the core resolves a run of declared + * weights to a device array of per-expert pointers, since after placement a layer's experts are + * not contiguous. See abi/rad_runtime.h. */ int r4d_rad_router_topk (const RadArgs*, RadStream); int r4d_rad_moe_scatter (const RadArgs*, RadStream); int r4d_rad_router_topk_scatter(const RadArgs*, RadStream); -int r4d_rad_router_topk_scatter_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); -/* The router GEMM, the selection and the sort in one launch, the shared gate optionally beside - * them. init takes the instance's arrival counter (r4d_moe.hip, THE ARRIVAL COUNTER) and fini - * gives it back; a launch with no instance is refused. */ +/* The router GEMM, selection and sort in one launch, optionally with the shared gate. init takes + * the instance's arrival counter (r4d_moe.hip, "the arrival counter") and fini returns it; a + * launch with no instance is refused. */ int r4d_rad_router_gemm_topk_scatter_init(const RadParam*, int, int rank, int world, void** out); void r4d_rad_router_gemm_topk_scatter_fini(void*); int r4d_rad_router_gemm_topk_scatter(const RadArgs*, RadStream); -int r4d_rad_router_gemm_topk_scatter_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, - int*); int64_t r4d_rad_moe_scatter_scratch(const RadArgs*); int r4d_rad_moe_gemm_q (const RadArgs*, RadStream); -/* Scratch for the run map the prefill form is aligned by. Zero in the decode band and zero for a - * shape whose parameters do not describe one, so a caller that never asks still gets a correct - * uniform grid. */ +/* Scratch for the run map that aligns the prefill form. Zero in the decode band and for a shape + * whose parameters do not describe one, so a caller that never asks still gets a correct uniform + * grid. */ int64_t r4d_rad_moe_gemm_q_scratch (const RadArgs*); int64_t r4d_rad_moe_gemm_w4a8_scratch(const RadArgs*); -/* The same grouped GEMM with the expert weight at FOUR BITS: same operands, same schema, same - * inner loop -- only the LDS staging and the scale grid differ. See r4d_layout.cpp's moe w4 - * section for the stored plane. */ +/* The same grouped GEMM with a 4-bit expert weight: same operands, schema and inner loop; only the + * LDS staging and scale grid differ. See r4d_layout.cpp's moe w4 section for the stored plane. */ int r4d_rad_moe_gemm_w4a8 (const RadArgs*, RadStream); -int r4d_rad_moe_gemm_w4a8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); /* `moe_gemm_q_mod4`: the same two kernels over four classes of experts, by the expert's number * mod 4. The scratch hooks are the two-class ones. */ int r4d_rad_moe_gemm_q_mod4 (const RadArgs*, RadStream); int r4d_rad_moe_gemm_w4a8_mod4 (const RadArgs*, RadStream); -int r4d_rad_moe_gemm_w4a8_mod4_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); -/* `moe_gemm` at bf16: one weight table of the checkpoint's own row-major planes, no scales. The - * same grouping and the same three forms; its scratch hook sizes the same run map. */ +/* `moe_gemm` at bf16: one weight table of the checkpoint's row-major planes, no scales. Same + * grouping and three forms; its scratch hook sizes the same run map. */ int r4d_rad_moe_gemm_bf16 (const RadArgs*, RadStream); -int r4d_rad_moe_gemm_bf16_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int64_t r4d_rad_moe_gemm_bf16_scratch(const RadArgs*); int r4d_rad_moe_gather (const RadArgs*, RadStream); int r4d_rad_scale_rows (const RadArgs*, RadStream); @@ -363,83 +333,59 @@ int64_t r4d_rad_moe_gather_scratch (const RadArgs*); /* -- quantisation, norms and the fusions (r4d_*quant*.hip, r4d_qk_norm_rope_gate.hip) -- */ int r4d_rad_quant_act_i8 (const RadArgs*, RadStream); -int r4d_rad_quant_act_i8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_qkv_norm_rope (const RadArgs*, RadStream); -int r4d_rad_qkv_norm_rope_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_gelu_mul_quant_i8 (const RadArgs*, RadStream); -int r4d_rad_gelu_mul_quant_i8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_ar_rmsnorm_quant_i8 (const RadArgs*, RadStream); int r4d_rad_rmsnorm_quant_i8 (const RadArgs*, RadStream); -int r4d_rad_rmsnorm_quant_i8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_had_quant_act_i8 (const RadArgs*, RadStream); int r4d_rad_rmsnorm_had_quant_i8 (const RadArgs*, RadStream); 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_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_qk_norm_rope_gate_kv_store(const RadArgs*, RadStream); -int r4d_rad_qk_norm_rope_gate_kv_store_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, - int*); int r4d_rad_rope_table (const RadArgs*, RadStream); -int r4d_rad_rope_table_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); /* -- block-scaled fp8, and the device sampler (r4d_gemm_fp8*.hip / r4d_fp8_layout.cpp) -- * - * These entry points RETURN a negative code rather than throwing, unlike the rest of libr4d's GEMM - * family, so their shims carry no R4D_TRY. */ + * These return a negative code instead of throwing, unlike the rest of libr4d's GEMMs, so their + * shims carry no R4D_TRY. */ int r4d_rad_gemm_fp8a16_m1 (const RadArgs*, RadStream); int r4d_rad_gemm_fp8a8_m16 (const RadArgs*, RadStream); -int r4d_rad_gemm_fp8a8_m16_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_gemm_fp8a8_gated_m16(const RadArgs*, RadStream); int64_t r4d_rad_gemm_fp8a8_m16_scratch(const RadArgs*); int r4d_rad_gemm_fp8a8_tiled(const RadArgs*, RadStream); int r4d_rad_gemm_i8a8_m16 (const RadArgs*, RadStream); -int r4d_rad_gemm_i8a8_m16_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int64_t r4d_rad_gemm_i8a8_m16_scratch(const RadArgs*); int r4d_rad_logits_gemm_i8(const RadArgs*, RadStream); int r4d_rad_gemm_i8a8_tiled(const RadArgs*, RadStream); int r4d_rad_quant_act_i8g(const RadArgs*, RadStream); -int r4d_rad_quant_act_i8g_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_had_quant_act_i8g(const RadArgs*, RadStream); -int r4d_rad_had_quant_act_i8g_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_quant_act_fp8 (const RadArgs*, RadStream); -int r4d_rad_quant_act_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_had_quant_act_fp8 (const RadArgs*, RadStream); -int r4d_rad_had_quant_act_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_givens_rotate (const RadArgs*, RadStream); -int r4d_rad_givens_rotate_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_rmsnorm_quant_fp8(const RadArgs*, RadStream); int r4d_rad_gated_quant_fp8 (const RadArgs*, RadStream); -int r4d_rad_gated_quant_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_gated_had_quant_fp8(const RadArgs*, RadStream); -int r4d_rad_gated_had_quant_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_gate_quant_fp8 (const RadArgs*, RadStream); -int r4d_rad_gate_quant_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_gram_accum (const RadArgs*, RadStream); /* The same accumulator over a plain bf16 activation, no scale operand. */ int r4d_rad_gram_accum_bf16 (const RadArgs*, RadStream); -int r4d_rad_qsa_block_key_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_qsa_block_key (const RadArgs*, RadStream); -int r4d_rad_qsa_score_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_qsa_score (const RadArgs*, RadStream); -int r4d_rad_qsa_select_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_qsa_select (const RadArgs*, RadStream); int64_t r4d_rad_qsa_select_scratch(const RadArgs*); -int r4d_rad_qsa_tail_store_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_qsa_tail_store (const RadArgs*, RadStream); -int r4d_rad_qsa_work_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_qsa_work (const RadArgs*, RadStream); int r4d_rad_sample_chain (const RadArgs*, RadStream); int r4d_rad_logits_gemm_fp8 (const RadArgs*, RadStream); /* -- what each weight-reading kernel stores, from a weight's canonical planes -- * - * RadLayoutFn / RadRelayoutFn / RadUnrelayoutFn (rad_abi.h, spec §4.3). r4d_fp8_layout.cpp holds the - * fp8 families -- block-fp8 codes in fragment order, the lm_head and the hyper-connection and MTP - * rows with their scales in each row's tail -- and r4d_layout.cpp the packed integer ones. Each - * refuses an encoding its kernel does not read. A family whose kernel reads the canonical plane as - * it is -- the row-major fp8 matvec, the fp8 experts -- has only the layout hook, to check what it - * is handed. */ + * RadLayoutFn / RadRelayoutFn / RadUnrelayoutFn (rad_abi.h, spec §4.3). r4d_fp8_layout.cpp holds + * the fp8 families (block-fp8 codes in fragment order; the lm_head, hyper-connection and MTP rows + * with scales in each row's tail), r4d_layout.cpp the packed integer ones. Each refuses an + * encoding its kernel does not read. A family whose kernel reads the canonical plane unchanged + * (the row-major fp8 matvec, the fp8 experts) has only the layout hook, to check its input. */ #define R4D_HOOKS(name) \ int r4d_rad_layout_##name(const RadParam*, int, int, const RadEncoding*, const int*, \ const RadTensor*, int, RadLayout*); \ @@ -505,31 +451,21 @@ int r4d_rad_unrelayout_givens_pairs(const RadParam*, int, int, const RadEncoding /* -- the small bf16 model ops (r4d_model_bf16.hip) -- * - * The embedding gather, the norm, the adds, the rotary and the KV scatter. Uninteresting kernels - * that the engine cannot run without: its buffers are in VRAM and an op with no DEVICE launch is a - * fatal issue, not a slow one. `logits_gemm` is declared with them. */ + * The embedding gather, norm, adds, rotary and KV scatter. Required because the buffers are in + * VRAM and an op with no device launch is a fatal issue. `logits_gemm` is declared with them. */ int r4d_rad_embed_lookup (const RadArgs*, RadStream); -int r4d_rad_embed_lookup_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); -/* The quantised gather (embed_lookup_q): the n-gram table's, where a card reads the table -- in - * VRAM, or in pinned host memory over the link. */ +/* The quantised gather (embed_lookup_q) for the n-gram table, read from VRAM or from pinned host + * memory over the link. */ int r4d_rad_embed_lookup_q (const RadArgs*, RadStream); -int r4d_rad_embed_lookup_q_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_ngram_ids (const RadArgs*, RadStream); -/* ABI v10: the same dispatch, described. Generated with the launch above by R4D_ENTRY, from one - * body, so the two cannot describe different work. */ -int r4d_rad_ngram_ids_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_ple_gate (const RadArgs*, RadStream); int r4d_rad_ple_conv (const RadArgs*, RadStream); int r4d_rad_causal_conv1d (const RadArgs*, RadStream); int r4d_rad_cast (const RadArgs*, RadStream); int r4d_rad_gather_rows (const RadArgs*, RadStream); int r4d_rad_gather_rows_u8 (const RadArgs*, RadStream); -int r4d_rad_gather_rows_u8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_scatter_rows_u8 (const RadArgs*, RadStream); -int r4d_rad_scatter_rows_u8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_scatter_rows_bf16(const RadArgs*, RadStream); -int r4d_rad_scatter_rows_bf16_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); -int r4d_rad_gather_rows_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_rmsnorm (const RadArgs*, RadStream); int r4d_rad_rmsnorm_p (const RadArgs*, RadStream); int r4d_rad_add (const RadArgs*, RadStream); @@ -546,6 +482,7 @@ int r4d_rad_clamp (const RadArgs*, RadStream); int r4d_rad_conv2d (const RadArgs*, RadStream); int r4d_rad_conv1d_dw (const RadArgs*, RadStream); int r4d_rad_rel_sinusoid (const RadArgs*, RadStream); +int r4d_rad_conv2d_unfold (const RadArgs*, RadStream); int r4d_rad_attn_local_rel (const RadArgs*, RadStream); int r4d_rad_sigmoid (const RadArgs*, RadStream); int r4d_rad_fill (const RadArgs*, RadStream); @@ -556,23 +493,18 @@ int r4d_rad_gelu_mul (const RadArgs*, RadStream); int r4d_rad_rope (const RadArgs*, RadStream); /* -- the vision tower's ops (r4d_vit_bf16.hip) -- */ int r4d_rad_layernorm (const RadArgs*, RadStream); -int r4d_rad_layernorm_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_grid_embed (const RadArgs*, RadStream); int r4d_rad_grid_embed_aa (const RadArgs*, RadStream); -int r4d_rad_grid_embed_aa_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); -int r4d_rad_grid_embed_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_gemm_nt_bias (const RadArgs*, RadStream); -int r4d_rad_gemm_nt_bias_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_kv_store (const RadArgs*, RadStream); int r4d_rad_kv_store_fp8 (const RadArgs*, RadStream); -int r4d_rad_kv_store_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_logits_gemm (const RadArgs*, RadStream); /* -- the decomposed sampler chain (r4d_sample_stages_f32.hip) -- * - * docs/OPS.md's eleven ops, as opposed to r4d_rad_sample_chain's fused form above. Both stay: the - * fused one is what a speculative verify wants, these are what an engine that composes the chain - * per request needs, and they carry the stages the fused one has no room for. */ + * docs/OPS.md's eleven ops, beside r4d_rad_sample_chain's fused form. The fused one suits a + * speculative verify; these let an engine compose the chain per request and carry the stages the + * fused one lacks. */ int r4d_rad_sample_penalties (const RadArgs*, RadStream); int r4d_rad_sample_dry (const RadArgs*, RadStream); int r4d_rad_sample_temp (const RadArgs*, RadStream); @@ -589,15 +521,14 @@ int r4d_rad_sample_merge_topk(const RadArgs*, RadStream); /* -- operand descriptions (r4d_shapes.cpp, pure host) -- * - * `RadKernelInfo::opd_shape`: how big is operand i of this op at this geometry, and what may be in - * it. One function per OP and not per row, because the description is a property of the operand - * list and not of the tiling: all six `attn_paged` rows take one function and read the cache's - * width off `kv_dtype`. Where two rows of one op genuinely differ, they take different functions - * -- or the one that cannot be described carries a NULL and is skipped by name, which is what - * `logits_gemm`'s fp8 row does. r4d_shapes.cpp's header lists every decline and its reason. + * `RadKernelInfo::opd_shape`: the size and allowed contents of operand i of this op at this + * geometry. One function per op, not per row, because the description belongs to the operand list, + * not the tiling: all six `attn_paged` rows share one and read the cache width off `kv_dtype`. + * Where rows genuinely differ they take different functions, or carry NULL and are skipped by name + * (`logits_gemm`'s fp8 row). r4d_shapes.cpp's header lists every decline and its reason. * - * Pure host code, called before anything is allocated, so it includes neither r4d.h nor - * -- the same split r4d_rows.cpp and r4d_layout.cpp keep. */ + * Pure host code called before allocation, so like r4d_rows.cpp and r4d_layout.cpp it includes + * neither r4d.h nor . */ int r4d_shape_embed_lookup (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_embed_lookup_q (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_gather_rows (const RadParam*, int, int operand, RadOpdDesc*); @@ -686,20 +617,17 @@ int r4d_shape_dflash_select (const RadParam*, int, int operand, RadOpdDesc*); /* -- declared fusions (r4d_fuse.cpp, pure host) -- * - * `RadKernelInfo::replaces`: the chain of conventional ops this kernel computes in one launch, so - * that a tool may run the chain out of this plugin's OWN unfused rows and compare the bytes. One - * function per FUSED ROW and not per op, unlike the shape hooks: two rows of one op could fold - * different things, and the chain is a claim about a kernel rather than about an operand list. + * `RadKernelInfo::replaces`: the chain of conventional ops this kernel computes in one launch, so a + * tool can run the chain on this plugin's own unfused rows and compare bytes. One function per + * fused row, not per op: two rows of one op could fold different things. * - * FIVE ROWS DECLARE ONE AND THE REST DELIBERATELY DO NOT. r4d_fuse.cpp's header lists every - * decline with the line of libr4d that decides it -- the int8 rotated family runs its Hadamard - * before the norm closes and keeps the product in f32, so `silu_mul` + `had_quant_act_i8` is a - * different function however it is spelled, and `ar_ln_had_quant_i8` reduces without the bf16 - * round its unfused pair stores. A chain that is merely close publishes no hook, because a false - * failure is worse than a skip. + * Only some rows declare one. r4d_fuse.cpp's header lists each decline with the libr4d line that + * decides it: the int8 rotated family runs its Hadamard before the norm closes and keeps the + * product in f32, so `silu_mul` + `had_quant_act_i8` is a different function, and + * `ar_ln_had_quant_i8` reduces without the bf16 round its unfused pair stores. A chain that is only + * close publishes no hook, because a false failure is worse than a skip. * - * Pure host code, called before anything is allocated, so it includes neither r4d.h nor - * -- the same split r4d_rows.cpp, r4d_layout.cpp and r4d_shapes.cpp keep. */ + * Pure host code, like r4d_rows.cpp, r4d_layout.cpp and r4d_shapes.cpp. */ int r4d_fuse_rmsnorm_quant_fp8 (const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_gated_quant_fp8 (const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_gate_quant_fp8 (const RadParam*, int, uint64_t, int, RadFuseStep*); diff --git a/libr4d/r4d_q8.h b/libr4d/r4d_q8.h index 9afb82b9..16cae9b4 100644 --- a/libr4d/r4d_q8.h +++ b/libr4d/r4d_q8.h @@ -1,15 +1,13 @@ // r4d_q8.h -- the 8-bit activation codes the trunk GEMMs read, written by every quantising producer: // E4M3 for the fp8a8 GEMMs, int8 for their int8 twins (gemm_i8a8_*). One scale per (row, 128 -// columns) either way; only the largest code and the conversion differ. +// columns); only the largest code and the conversion differ. // -// THE E4M3 FORM IS EXACTLY WHAT EACH PRODUCER WROTE INLINE BEFORE: the scale `amax * (1 / 448)`, -// the clamp to +-448 (v_cvt_pk_fp8_f32 answers an out-of-range input with NaN rather than -// saturating, and `amax * (1 / scale)` can land an ulp above 448), and two packed conversions. So a -// producer switched to this header writes the same bytes it did. +// E4M3: scale `amax * (1 / 448)`, clamp to +-448, two packed conversions. The clamp is required: +// v_cvt_pk_fp8_f32 returns NaN for out-of-range input instead of saturating, and +// `amax * (1 / scale)` can land an ulp above 448. // -// THE INT8 FORM IS quant_act_i8g's (r4d_quant_act_fp8.hip): the scale `amax * (1 / 127)` and the -// value over it rounded to nearest-even, -127..127 -- so a producer that writes int8 itself writes -// exactly what the standalone quantiser would have written from the bf16 plane. +// Int8: as quant_act_i8g (r4d_quant_act_fp8.hip), scale `amax * (1 / 127)` and round-to-nearest- +// even into -127..127, so a fused producer writes the same codes as the standalone quantiser. #pragma once #include #include diff --git a/libr4d/r4d_qk_norm_rope_gate.hip b/libr4d/r4d_qk_norm_rope_gate.hip index 8e370c47..51b7f7c2 100644 --- a/libr4d/r4d_qk_norm_rope_gate.hip +++ b/libr4d/r4d_qk_norm_rope_gate.hip @@ -1,23 +1,20 @@ // r4d_qk_norm_rope_gate.hip -- r4d_qk_norm_rope_gate: the whole gated-attention QKV preamble in one // pass: split [q|gate] per head, QK RMS norm over the head, partial NeoX RoPE, and the gate copy. // -// WHY. vLLM already has this fusion -- `fused_qk_rmsnorm_rope_gate` -- and gates it on -// `current_platform.is_cuda()`. The kernel behind it is plain Triton with nothing CUDA-specific in -// it, so the gate looks like conservatism, but it is not: on gfx1201 that kernel does not compile. -// Triton's AMD backend fails in `TritonAMDGPUCanonicalizePointers` on its pointer arithmetic. So -// ROCm runs the unfused branch -- a split, two GemmaRMSNorms, a RoPE and a gate chunk, which -// inductor lands as FOUR kernels per attention layer, 16 layers, 64 dispatches a decode step for -// ~6.3 us of work that is four passes over the same 14 KB. +// vLLM's equivalent fusion, `fused_qk_rmsnorm_rope_gate`, is gated on `is_cuda()`, and its Triton +// kernel does not compile on gfx1201 (Triton's AMD backend fails in +// `TritonAMDGPUCanonicalizePointers`). The unfused ROCm path is four kernels per attention layer +// (split, two GemmaRMSNorms, RoPE and gate chunk): 64 dispatches a decode step over 16 layers for +// ~6.3 us of work. // -// WHAT IT IS BIT-FOR-BIT. The reference path stores the normed value to memory as bf16 and then -// RoPEs what it reads back, so the norm output is ROUNDED TO bf16 BEFORE the rotation. Skipping -// that round trip is more accurate and would be wrong: it is a different function. The `.to( -// INPUT_DTYPE).to(tl.float32)` in vLLM's own kernel is there for the same reason. +// Bit-identity: the reference stores the normed value as bf16 and RoPEs what it reads back, so the +// norm output is rounded to bf16 before the rotation. Skipping the round trip would be more +// accurate and a different function; vLLM's kernel has `.to(INPUT_DTYPE).to(tl.float32)` for the +// same reason. // -// `wadd` IS ADDED TO EVERY GAIN. Qwen3NextRMSNorm is GemmaRMSNorm: `x_hat * (1 + w)` over a -// zero-centred gamma, formed in fp32. vLLM's fused kernel takes `weight.float() + 1.0` from the -// caller; this takes the bf16 weight and the offset, and adds it after the load, inside the fp32 -// arithmetic -- identical, and it does not need a per-layer fp32 copy of the gain. +// `wadd` is added to every gain: Qwen3NextRMSNorm is GemmaRMSNorm, `x_hat * (1 + w)` over a +// zero-centred gamma in fp32. This takes the stored gain and the offset and adds them in fp32 after +// the load, which matches vLLM's `weight.float() + 1.0` without a per-layer fp32 copy. // #include "r4d.h" #include "r4d_args.h" @@ -28,33 +25,24 @@ #include #include -// ONE BLOCK PER (TOKEN, HEAD) AND ONE ELEMENT PER LANE, WHICH IS NOT A LAYOUT CHOICE -- IT IS THE -// BIT-EQUALITY REQUIREMENT. +// One block per (token, head) and one element per lane, required for bit-equality. // -// The tempting layout gives each lane EIGHT CONSECUTIVE elements and reduces one wave per head: no -// LDS, no barrier, and the rotary partner one `__shfl_xor` away, because element i and i + rot/2 -// sit in lanes (rot/2)/VPL apart. It is elegant and it is a DIFFERENT FUNCTION. -// `r4d_rmsnorm_bf16` states the rule that kills it: "the width decides which columns a thread -// folds into the sum of squares. Two kernels that disagree about it disagree in the last bits of -// the norm." A ULP in the mean square is a ULP in the normed value, a ROTATED element is a -// difference of two products, and where those nearly cancel the ULP comes out as a few percent -- -// enough to move the engine's text within a few dozen steps, which forces the fusion off. +// Eight consecutive elements per lane with one wave per head (no LDS, rotary partner one shuffle +// away) computes a different function. r4d_rmsnorm_bf16's width decides which columns a thread +// folds into the sum of squares, and a last-bit difference in the norm becomes a few percent where +// a rotated element's two products nearly cancel, enough to change the engine's text within a few +// dozen steps. // -// The reference's fold is reproducible exactly, and it is simpler than it looks. `rmsnorm_bf16` -// runs `for (i = threadIdx.x; i < n; i += THR)`, and `r4d_act_threads` never returns fewer than 256 -// threads while every head_dim compiled here is at most 256 -- so the reference ALWAYS folds -// exactly one element per thread, whatever width it picks. The widths above the head dim contribute -// zeros, and adding 0.0f to an f32 accumulator is exact, so `block_sum` over 8 wave partials and -// over 32 of them are the same number. One element a lane, 256 threads, `block_sum` in ascending -// wave order: that is the whole of it. +// The reference's fold is easy to reproduce: `rmsnorm_bf16` runs +// `for (i = threadIdx.x; i < n; i += THR)`, `r4d_act_threads` never returns fewer than 256 threads, +// and every head_dim here is at most 256, so it always folds exactly one element per thread. Lanes +// past the head add exact zeros, so `block_sum` over 8 or 32 wave partials gives the same number. +// Hence one element a lane, 256 threads, `block_sum` in ascending wave order. // -// WHAT IT COSTS: the rotary partner is `rot/2` lanes away, which at rot 64 is a different WAVE, so -// no shuffle reaches it. The partner is RE-DERIVED rather than exchanged through LDS and a -// barrier -- the lane loads the partner's input element and norms it itself, which is one L1-hot -// read and the same `inv` the block already agreed on. No shared memory beyond block_sum's eight -// floats, and no barrier the reduction did not already need. -/* THE PAGED CACHE the KV form writes: kv_store's operands and parameters, in one argument so the - * launch stays inside the emitter's parameter budget. The descales are read by the E4M3 form only. */ +// Cost: at rot 64 the rotary partner is in another wave. The lane re-derives it instead of an LDS +// exchange: it loads the partner's input (an L1-hot read) and norms it with the block's `inv`. +/* The paged cache the KV form writes: kv_store's operands and parameters in one argument, to stay + * inside the emitter's parameter budget. Only the E4M3 form reads the descales. */ struct QkKvStore { const __hip_bfloat16* v; const int32_t* slot; @@ -66,17 +54,16 @@ struct QkKvStore { /* The cache forms KV selects. */ enum { QK_KV_NONE = 0, QK_KV_FP8 = 1, QK_KV_BF16 = 2 }; -/* KV folds kv_store in: a k head's block, holding its token's rotated k one element a lane, also - * writes that element and the head's v element into the cache at the token's slot -- as E4M3 with - * kv_store_fp8's arithmetic element for element, or as the bf16 kv_store_bf16 copies (see the store - * at the end). */ +/* 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 + * kv_store_fp8's arithmetic or as bf16 like kv_store_bf16 (see the store at the end). */ template __global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel( const __hip_bfloat16* __restrict__ QG, const __hip_bfloat16* __restrict__ K, __hip_bfloat16* __restrict__ QO, __hip_bfloat16* __restrict__ KO, __hip_bfloat16* __restrict__ GO, const void* __restrict__ WQ, const void* __restrict__ WK, - const void* __restrict__ CS, const void* __restrict__ POS, + const void* __restrict__ CS, const void* __restrict__ POS, long cs_rows, int nq, int nkv, int rot, float eps, float wadd, int qg_pitch, int k_pitch, int cs_f32, int pos_i64, int w_f32, QkKvStore kvs) { constexpr int THR = 256; @@ -89,36 +76,34 @@ __global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel( const int lh = isk ? h - nq : h; const __hip_bfloat16* in = isk ? (K + (size_t)tok * k_pitch + (size_t)lh * HD) : (QG + (size_t)tok * qg_pitch + (size_t)lh * 2 * HD); - // THE GAIN IS f32 IN THIS MODEL AND bf16 IN vLLM's, and both are the dtype the unfused rmsnorm - // beside it would have read -- so the width is a property of the operand, not of the kernel. + // The gain is f32 in this engine's plugins and bf16 in vLLM's; its width follows the operand. const void* w = isk ? WK : WQ; __hip_bfloat16* out = isk ? (KO + ((size_t)tok * nkv + lh) * HD) : (QO + ((size_t)tok * nq + lh) * HD); const float* csf = (const float*)CS; const __hip_bfloat16* csb = (const __hip_bfloat16*)CS; - // `gain` is spelled once so the two sites that need it -- this lane's element and, in the rotary - // range, its partner's -- cannot pick different widths. + // Spelled once so this lane's element and its rotary partner cannot use different widths. auto gain = [&](int i) -> float { return w_f32 ? ((const float*)w)[i] : __bfloat162float(((const __hip_bfloat16*)w)[i]); }; - // ROUNDED TO bf16 BEFORE THE ROTATION, which is the whole bit-identity argument at the top of - // this file: the reference stores the norm and RoPEs what it reads back. + // Rounded to bf16 before the rotation; see the bit-identity note at the top of this file. auto normed = [&](float v, float g, float inv) -> float { return __bfloat162float(__float2bfloat16(v * inv * (g + wadd))); }; - // EVERYTHING THE ROTATION READS IS LOADED HERE, ahead of the reduction, so it is in flight while - // the sum of squares goes round: this lane's element and gain, its partner's, and its cos and - // sin. None of it depends on the norm. The indices are clamped rather than the loads guarded -- - // a lane past the head reads its last element, a lane past the rotary range its own element and - // column 0 of the table (rot >= 2, so the table has one) -- and the values are used only where - // the guards below say. + // Everything the rotation reads is loaded before the reduction, so it is in flight during the + // sum of squares: this lane's element and gain, its partner's, and its cos and sin. Indices are + // clamped instead of guarding the loads (a lane past the head reads its last element; a lane past + // the rotary range reads its own element and table column 0, which exists since rot >= 2), and + // the values are used only where the guards below allow. const int tc = t < HD ? t : HD - 1; const bool rl = t < rot, first = t < half; const int pt = rl ? (first ? t + half : t - half) : tc; const int ci = rl ? (first ? t : t - half) : 0; - const size_t co = (size_t)p * rot; + // The table row is clamped: a padded row (negative) or a position past the table's height has no + // row rope_table wrote, and must not read outside the plane. + const size_t co = (size_t)(p < 0 ? 0 : (p < cs_rows ? p : cs_rows - 1)) * rot; const float vt = __bfloat162float(in[tc]), gt = gain(tc); const float vp = __bfloat162float(in[pt]), gp = gain(pt); const float c = cs_f32 ? csf[co + ci] : __bfloat162float(csb[co + ci]); @@ -127,9 +112,8 @@ __global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel( float ss = 0.0f; if (t < HD) ss = vt * vt; // rmsnorm_bf16's block_sum, transcribed: the wave butterfly, then the wave partials summed in - // ASCENDING index order. Both halves matter -- an accumulation over the same values in a - // different order breaks the bit-equality argument above. The barrier orders the partials in LDS - // and nothing else, so the loads above stay in flight across it. + // ascending order. Any other order breaks the bit-equality above. The barrier orders only the LDS + // partials, so the loads above stay in flight across it. ss = r4d_wave_sum(ss); if ((t & 31) == 0) lds[t >> 5] = ss; lds_barrier(); @@ -146,28 +130,23 @@ __global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel( res = first ? (res * c - xp * s) : (xp * s + res * c); } } - // EVERY LANE HAS READ ITS INPUT BEFORE ANY LANE WRITES IT BACK. `k` is rotated IN PLACE by the - // engine -- one buffer for the operand and the result -- and under the one-element-a-lane layout - // a lane's partner element is a MEMORY READ rather than a shuffle, so without this barrier the - // partner may already have been overwritten. A shuffle-based layout does not need the barrier, - // which is exactly why it is easy to leave out here: the failure is a 1% scatter of elements - // that reads like a rounding difference and is not one. r4d_selftest's byte-equality row catches - // it. + // Every lane must read its input before any lane writes back: the engine rotates `k` in place, + // and a lane's partner is a memory read, so without this barrier it may already be overwritten. + // The failure is a ~1% scatter of wrong elements that looks like rounding; r4d_selftest's + // byte-equality row catches it. __syncthreads(); if (t < HD) { out[t] = __float2bfloat16(res); - // `gate_out` is OPTIONAL in the schema, and a caller that already reads the gate straight out - // of the interleaved projection -- which the fp8 block does, through gate_quant_fp8 -- passes - // none rather than paying for a copy it will not read. + // `gate_out` is optional: a caller that reads the gate straight from the interleaved projection + // (the fp8 block, via gate_quant_fp8) passes none. if (!isk && GO) GO[((size_t)tok * nq + lh) * HD + t] = in[HD + t]; } - // THE CACHE WRITE kv_store WOULD MAKE NEXT, from the same bytes it would read: the rotated k as - // the bf16 just stored and the v row as the projection left it. The E4M3 form scales each by the - // inverse descale, clamps (v_cvt_pk_fp8_f32 answers out-of-range with NaN) and converts; the pair - // conversion there rounds each element on its own, so one element a lane is the same byte. The - // bf16 form stores the two values as they are, which is all kv_store_bf16 does. The layout is - // [n_blocks, kv_heads, block_size, 2*head_dim], k then v, in the cache's element; a negative or - // out-of-range slot stores nothing. + // The cache write kv_store would make next, from the same bytes: the rotated k as just stored + // and the v row as the projection left it. The E4M3 form scales by the inverse descale, clamps + // (v_cvt_pk_fp8_f32 returns NaN out of range) and converts each element on its own, so one + // element a lane gives the same byte. The bf16 form stores the values as kv_store_bf16 does. + // Layout [n_blocks, kv_heads, block_size, 2*head_dim], k then v; a negative or out-of-range slot + // stores nothing. if constexpr (KV != QK_KV_NONE) { if (isk && t < HD) { const int32_t sl = kvs.slot[tok]; @@ -198,31 +177,28 @@ __global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel( } } - // ============================================================ the cos/sin table // -// The fused kernel above reads a PRECOMPUTED table instead of theta, and this fills it. One launch -// a step serves every attention layer, against one rope launch a layer -- which is the whole point: -// at head_dim 256 the rotation is ~7 us of dispatch for ~1 us of work, sixteen times over. +// The fused kernel reads a precomputed table instead of theta, and this fills it: one launch per +// step for every attention layer, instead of a rope launch per layer (~7 us of dispatch for ~1 us +// of work at head_dim 256). // -// IT IS WRITTEN AT THE POSITION'S OWN ROW, so the table has a row per position the model can name -// and only the rows a step actually touches are filled. A decode step touches at most a few dozen -// of them, so this moves kilobytes and not the six megabytes a whole table would. Rows nothing +// Each position is written at its own row, so the table has a row per nameable position and only +// the rows a step touches are filled (kilobytes at decode, not the whole ~6 MB table). Rows nothing // addresses are never read. // -// THE ARITHMETIC IS r4d_model_bf16.hip's rope_kernel, LINE FOR LINE, and that is what makes the -// fusion bit-for-bit rather than merely close: `1.0f / powf(theta, 2i/den)`, where `den` is the -// ladder's width (`rot` for `rotary`, `head_dim` for `head`), the position divided by `rscale` -// in f32, `sincosf`, and the products consumed in f32 by the caller. Changing any of those here -// silently changes the model's output -- a different rope is a different model. +// The arithmetic is r4d_model_bf16.hip's rope_kernel line for line, which makes the fusion +// bit-identical: `1.0f / powf(theta, 2i/den)` with `den` the ladder's width (`rot` for `rotary`, +// `head_dim` for `head`), the position divided by `rscale` in f32, `sincosf`, and the products +// consumed in f32 by the caller. Changing any of it changes the model's output. __global__ __launch_bounds__(64) void r4d_qk_rope_table_kernel( const void* __restrict__ POS, void* __restrict__ CS, long rows, int rot, int den, float theta, float rscale, int cs_f32, int pos_i64, RadYarn yarn) { const int m = blockIdx.x; const long pp = pos_i64 ? ((const long*)POS)[m] : (long)((const int*)POS)[m]; // A padded row addresses no table row, and a position at or past the table's height writes - // nothing: its row would land in whatever buffer the arena placed after the plane. libref and - // libavx skip the same rows. + // nothing (it would land in whatever the arena placed after the plane). libref and libavx skip + // the same rows. if (pp < 0 || pp >= rows) return; const int half = rot >> 1; const float p = (float)pp / (rscale != 0.0f ? rscale : 1.0f); @@ -243,13 +219,13 @@ __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 for why the flattened argument list and the throws are gone. +// 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 }; /* The body of both forms; KVF is the kv_store fold and `kvs` its cache, already checked. */ template -static int qk_body(const RadArgs* args, const R4dSink& sk, const QkKvStore& kvs) { +static int qk_body(const RadArgs* args, RadStream stream, const QkKvStore& kvs) { const RadTensor* qg = r4d_opt(args, QK_QGATE); const RadTensor* k = r4d_opt(args, QK_K); const RadTensor* cs = r4d_opt(args, QK_COSSIN); @@ -259,12 +235,10 @@ static int qk_body(const RadArgs* args, const R4dSink& sk, const QkKvStore& kvs) const RadTensor* qo = r4d_opt(args, QK_QOUT); const RadTensor* ko = r4d_opt(args, QK_KOUT); const RadTensor* go = r4d_opt(args, QK_GOUT); - // THE K-ONLY FORM. `n_head` 0 means the caller has no [q|gate] projection to split -- its heads - // are already one plain `head_dim` run each -- so `q_gate`, `q_w` and `q_out` are absent and - // every head is served off `k`. The KERNEL NEEDS NOTHING for this: `isk` is `h >= nq`, so at - // nq 0 every block takes the k path and the three absent operands are never dereferenced - // (`r4d_p` and `r4d_wp` already return null for an absent tensor, so the launch needs no case - // of its own). + // The k-only form: `n_head` 0 means there is no [q|gate] projection to split (each head is a + // plain `head_dim` run), so `q_gate`, `q_w` and `q_out` are absent and every head is served off + // `k`. The kernel needs nothing for it: `isk` is `h >= nq`, so at nq 0 every block takes the k + // path and the absent operands (null via r4d_p / r4d_wp) are never dereferenced. if (!k || !cs || !po || !wk || !ko) return R4D_NO(RAD_E_INVAL); if (!r4d_contig(cs) || !r4d_contig(po) || !r4d_contig(wk)) return R4D_NO(RAD_E_STRIDE); if (!r4d_contig(ko)) return R4D_NO(RAD_E_STRIDE); @@ -282,32 +256,33 @@ static int qk_body(const RadArgs* args, const R4dSink& sk, const QkKvStore& kvs) const long long k_pitch = r4d_row_pitch(k); if (qg_pitch < 0 || k_pitch < 0) return R4D_NO(RAD_E_STRIDE); - // The row count is the OPERAND'S, and which operand carries it is what the form decides. + // The row count is the operand's; which operand carries it depends on the form. const long long M = qg ? qg->shape[0] : k->shape[0]; if (M < 1) return R4D_NO(RAD_E_SHAPE); if (hd != 64 && hd != 128 && hd != 256) return R4D_NO(RAD_E_SHAPE); // the compiled set if (rot < 2 || (rot & 1) || rot > hd) return R4D_NO(RAD_E_SHAPE); + const long long cs_rows = r4d_numel(cs) / rot; + if (cs_rows < 1 || r4d_numel(cs) % rot) return R4D_NO(RAD_E_SHAPE); const float eps = (float)r4d_getf(args, "eps", 1e-6); const float wadd = (float)r4d_getf(args, "wadd", 0.0); - // The two width flags are read off the OPERANDS rather than declared twice: a cos/sin table - // built in f32 and a positions vector in int64 are what the tensor SAYS they are. + // The width flags come from the operands: a cos/sin table in f32 and positions in int64 are what + // the tensors say they are. const int cs_f32 = (cs->dtype == RAD_F32) ? 1 : 0; const int pos_i64 = (po->dtype == RAD_I64) ? 1 : 0; - // THE NORM GAIN'S WIDTH IS THE OPERAND'S TOO, and it is f32 in every architecture plugin here - // where vLLM's is bf16. The two gains must agree, because one flag serves both. + // The norm gain's width is the operand's too (f32 in every architecture plugin here, bf16 in + // vLLM). One flag serves both gains, so they must agree. if (wq && wq->dtype != wk->dtype) return R4D_NO(RAD_E_DTYPE); if (wk->dtype != RAD_F32 && wk->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); const int w_f32 = (wk->dtype == RAD_F32) ? 1 : 0; const int nh = (int)(nq + nkv); - // One block a (token, head), 256 threads, one element a lane. The width is FIXED at 256 and not - // fitted to the head count: it is what makes the sum of squares agree with r4d_rmsnorm_bf16, and - // the kernel says at length why. -#define R4D_QKG_L(H) emit_rc = R4D_EMIT(sk, (r4d_qk_norm_rope_gate_kernel), \ + // One block per (token, head), 256 threads, one element per lane. The width is fixed at 256, not + // fitted to the head count, so the sum of squares matches r4d_rmsnorm_bf16 (see the kernel). +#define R4D_QKG_L(H) emit_rc = R4D_EMIT(stream, (r4d_qk_norm_rope_gate_kernel), \ dim3((int)M, nh), dim3(256), 0, (const __hip_bfloat16*)r4d_p(qg), \ (const __hip_bfloat16*)r4d_p(k), (__hip_bfloat16*)r4d_wp(qo), (__hip_bfloat16*)r4d_wp(ko), \ - (__hip_bfloat16*)r4d_wp(go), r4d_p(wq), r4d_p(wk), r4d_p(cs), r4d_p(po), \ + (__hip_bfloat16*)r4d_wp(go), r4d_p(wq), r4d_p(wk), r4d_p(cs), r4d_p(po), (long)cs_rows, \ (int)nq, (int)nkv, (int)rot, eps, wadd, (int)qg_pitch, (int)k_pitch, cs_f32, pos_i64, w_f32, \ kvs) int emit_rc = RAD_OK; @@ -320,17 +295,15 @@ static int qk_body(const RadArgs* args, const R4dSink& sk, const QkKvStore& kvs) return emit_rc; } -static int rad_qk_norm_rope_gate_body(const RadArgs* args, const R4dSink& sk) { - return qk_body(args, sk, QkKvStore{}); +extern "C" int r4d_rad_qk_norm_rope_gate(const RadArgs* args, RadStream stream) { + return qk_body(args, stream, QkKvStore{}); } -R4D_ENTRY(r4d_rad_qk_norm_rope_gate, rad_qk_norm_rope_gate_body) -/* THE PROLOGUE WITH THE KV STORE FOLDED IN: qk_norm_rope_gate's operands, then kv_store's `v`, - * `slot_mapping` and `kv_cache`, and kv_store's parameters. The cache is E4M3 or bf16, whichever - * `kv_dtype` names and the tensor is, checked the way kv_store checks it, and one slot a row of - * the prologue. The k kv_store would read is the prologue's own output, so it is not an operand of - * its own. */ -static int rad_qk_norm_rope_gate_kv_store_body(const RadArgs* args, const R4dSink& sk) { +/* The prologue with the KV store folded in: qk_norm_rope_gate's operands, then kv_store's `v`, + * `slot_mapping` and `kv_cache`, and its parameters. The cache is E4M3 or bf16 as `kv_dtype` + * names, checked as kv_store checks it, one slot per prologue row. The k kv_store would read is the + * prologue's own output, so it is not a separate operand. */ +extern "C" int r4d_rad_qk_norm_rope_gate_kv_store(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); @@ -369,20 +342,17 @@ static int rad_qk_norm_rope_gate_kv_store_body(const RadArgs* args, const R4dSin kvs.n_blocks = (int)kv->shape[0]; kvs.k_inv = 1.0f / (float)ks; kvs.v_inv = 1.0f / (float)vs; - return kv->dtype == RAD_BF16 ? qk_body(args, sk, kvs) - : qk_body(args, sk, kvs); + return kv->dtype == RAD_BF16 ? qk_body(args, stream, kvs) + : qk_body(args, stream, kvs); } -R4D_ENTRY(r4d_rad_qk_norm_rope_gate_kv_store, rad_qk_norm_rope_gate_kv_store_body) -// The cos/sin plane the fused prologue above reads. One launch a step against `rope`'s one a -// layer, and the reason the fusion is reachable at all: `qk_norm_rope_gate` takes a table and not -// a theta, and until this row existed nothing in the tree could build one. +// The cos/sin plane the fused prologue reads: one launch a step, against `rope`'s one per layer. +// `qk_norm_rope_gate` takes a table, not a theta, so this row is what makes it usable. // -// ONLY THE ROWS `positions` NAMES ARE WRITTEN, at each position's own row of a [rows, rot] plane -// whose height is the operand's. A decode step names a few dozen, so this moves kilobytes where a -// whole-table fill would move six megabytes; a row nothing addresses keeps whatever it held, which -// is correct because nothing reads it. -static int rad_rope_table_body(const RadArgs* args, const R4dSink& sk) { +// Only the rows `positions` names are written, each at its own row of a [rows, rot] plane whose +// height is the operand's. A row nothing addresses keeps its contents, which is correct because +// nothing reads it. +extern "C" int r4d_rad_rope_table(const RadArgs* args, RadStream stream) { const RadTensor* po = r4d_opt(args, 0); const RadTensor* cs = r4d_opt(args, 1); if (!po || !cs) return R4D_NO(RAD_E_INVAL); @@ -390,8 +360,8 @@ static int rad_rope_table_body(const RadArgs* args, const R4dSink& sk) { if (cs->dtype != RAD_F32 && cs->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); if (po->dtype != RAD_I32 && po->dtype != RAD_I64) return R4D_NO(RAD_E_DTYPE); - // The row count is the OPERAND'S: `M` is declared as a band ceiling and this is called with a - // step's rows, not the band's. + // The row count is the operand's: `M` is declared as a band ceiling, but the call carries a + // step's rows. const long long M = r4d_numel(po); const long long rot = r4d_geti_or(args, "rot", 0); if (M < 1 || rot < 2 || (rot & 1)) return R4D_NO(RAD_E_SHAPE); @@ -406,16 +376,16 @@ static int rad_rope_table_body(const RadArgs* args, const R4dSink& sk) { if (!std::strcmp(lad, "head")) { if (head_dim <= 0) return R4D_NO(RAD_E_SHAPE); den = head_dim; - } else if (std::strcmp(lad, "rotary") && std::strcmp(lad, "head")) + } else if (std::strcmp(lad, "rotary")) { return R4D_NO(RAD_E_UNSUPPORTED); + } } const float theta = (float)r4d_getf(args, "theta", 10000.0); const float rscale = (float)r4d_getf(args, "scale", 1.0); const RadYarn yarn = rad_yarn_args(args); if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && rscale != 1.0f)) return R4D_NO(RAD_E_INVAL); - return R4D_EMIT(sk, r4d_qk_rope_table_kernel, dim3((int)M), dim3(64), 0, + return R4D_EMIT(stream, r4d_qk_rope_table_kernel, dim3((int)M), dim3(64), 0, r4d_p(po), r4d_wp(cs), (long)(r4d_numel(cs) / rot), (int)rot, (int)den, theta, rscale, cs->dtype == RAD_F32 ? 1 : 0, po->dtype == RAD_I64 ? 1 : 0, yarn); } -R4D_ENTRY(r4d_rad_rope_table, rad_rope_table_body) diff --git a/libr4d/r4d_qkv_norm_rope.hip b/libr4d/r4d_qkv_norm_rope.hip index eb1072fa..8947fbdb 100644 --- a/libr4d/r4d_qkv_norm_rope.hip +++ b/libr4d/r4d_qkv_norm_rope.hip @@ -1,28 +1,26 @@ // r4d_qkv_norm_rope.hip - r4d_qkv_norm_rope: the per-head norms and the rotary of separate q, k and // v projections in one dispatch -- Gemma 4's attention prologue. // -// WHY. Between its projections and the cache store a Gemma 4 attention block runs five single-pass -// kernels over a few dozen heads: the weightless value norm (rmsnorm_p), the q and the k norms -// (rmsnorm, one row a head) and the two rotaries (rope). At a decode batch each is a handful of -// workgroups, so the block pays five dispatches for work the card does in a fraction of one. This is -// the five as one, one workgroup a (token, head). +// Between its projections and the cache store a Gemma 4 attention block runs five single-pass +// kernels over a few dozen heads: the weightless value norm (rmsnorm_p), the q and k norms +// (rmsnorm, one row per head) and two rotaries (rope). At decode each is a handful of workgroups, +// so this fuses the five into one dispatch, one workgroup per (token, head). // -// BYTE-IDENTICAL TO THE FIVE, for the reason r4d_rmsnorm_quant_i8.hip gives. What makes that hold: +// Byte-identical to the five (see r4d_rmsnorm_quant_i8.hip for why that matters), because: // -// * each norm's sum of squares is taken by THE PARTITION ITS STANDALONE KERNEL USES. rmsnorm runs -// one workgroup a row at r4d_act_threads(rows, head_dim) threads and rmsnorm_p at 256; thread t -// folds columns t, t+THR, ... in order, the waves are summed in order through LDS. Here a +// * each norm's sum of squares uses its standalone kernel's partition. rmsnorm runs one workgroup +// per row at r4d_act_threads(rows, head_dim) threads and rmsnorm_p at 256; thread t folds +// columns t, t+THR, ... in order and the waves are summed in order through LDS. Here a // workgroup is head_dim threads, and thread t < min(THR, head_dim) folds the same columns in the -// same order while the rest hold zero -- which is what the standalone kernel's surplus waves hold -// too, and adding +0.0 to a sum of squares changes no bit; +// same order while the rest hold zero, as the standalone kernel's surplus waves do; // * the norm output is rounded to bf16 as the standalone norm stores it, and the rotary reads that; -// * the rotary's per-pair arithmetic is rope_kernel's, written the same way (powf ladder, -// sincosf, `x0*c - x1*s`, `x0*s + x1*c`), under the library's -ffp-contract=off. +// * the rotary's per-pair arithmetic is rope_kernel's (powf ladder, sincosf, `x0*c - x1*s`, +// `x0*s + x1*c`), under the library's -ffp-contract=off. // -// `v_from_k` IS GEMMA'S GLOBAL CLASS: k == v, so v is the value norm of the RAW k, taken before the -// k norm rewrites it -- the order the unfused block issues them in. +// `v_from_k` is Gemma's global class: k == v, so v is the value norm of the raw k, taken before the +// k norm overwrites it, in the order the unfused block issues them. // -// Returns a negative code rather than throwing, for the reason given in r4d_gemm_fp8a8.hip. +// Returns a negative code instead of throwing, for the reason given in r4d_gemm_fp8a8.hip. #include "r4d.h" #include "r4d_args.h" #include "r4d_emit.h" @@ -37,8 +35,8 @@ constexpr uint32_t kWave = 32; __device__ __forceinline__ float bf2f(uint16_t h) { return __uint_as_float((uint32_t)h << 16); } -// THR threads' partition of one head's sum of squares, reproduced inside a head_dim-wide workgroup: -// thread t < P = min(THR, HD) folds t, t+P, ...; the waves are then summed in order. +// THR threads' partition of one head's sum of squares inside a head_dim-wide workgroup: thread +// t < P = min(THR, HD) folds t, t+P, ...; the waves are then summed in order. template __device__ __forceinline__ float head_ss(const uint16_t* __restrict__ x, uint32_t P, float* lds) { float ss = 0.0f; @@ -79,13 +77,13 @@ __global__ __launch_bounds__(HD) void qkv_norm_rope_kernel( uint16_t* __restrict__ q, uint16_t* __restrict__ k, uint16_t* __restrict__ v, const int32_t* __restrict__ pos, const void* __restrict__ qw, const void* __restrict__ kw, uint32_t nq, uint32_t nkv, uint32_t pq, uint32_t pk, uint32_t pv, - uint32_t q_ld, uint32_t k_ld, uint32_t v_ld, float eps, float wadd, float mult, + uint32_t q_ld, uint32_t k_ld, uint32_t v_ld, float eps, float wadd, uint32_t rot, uint32_t nfreq, int den, float theta, float rscale, uint32_t n_pos) { __shared__ float l1[HD / kWave], l2[HD / kWave]; __shared__ uint16_t nb[HD]; const uint32_t m = blockIdx.x, hh = blockIdx.y, t = threadIdx.x; const float div = rscale != 0.0f ? rscale : 1.0f; - // rope rotates the rows its positions cover; a row past them is normed and left unrotated + // rope rotates only the rows its positions cover; a row past them is normed and not rotated const float p0 = m < n_pos ? (float)pos[m] / div : 0.0f; if (hh >= nq + nkv) { // a value head, in place: rmsnorm_p @@ -109,7 +107,7 @@ __global__ __launch_bounds__(HD) void qkv_norm_rope_kernel( const float s = rsqrtf(head_ss(x, isq ? pq : pk, l1) / (float)HD + eps); for (uint32_t i = t; i < HD; i += HD) { const float g = WF32 ? ((const float*)w)[i] : bf2f(((const uint16_t*)w)[i]); - nb[i] = f32_to_bf16(bf2f(x[i]) * s * (g + wadd) * mult); + nb[i] = f32_to_bf16(bf2f(x[i]) * s * (g + wadd)); } __syncthreads(); // the normed head is complete before any pair reads across it if (m < n_pos) rotate(nb, x, p0, rot, nfreq, den, theta); @@ -121,7 +119,7 @@ __global__ __launch_bounds__(HD) void qkv_norm_rope_kernel( // ============================================================== the plugin ABI entry point enum { QN_Q = 0, QN_K, QN_V, QN_POS, QN_QW, QN_KW }; -static int rad_qkv_norm_rope_body(const RadArgs* a, const R4dSink& sk) { +extern "C" int r4d_rad_qkv_norm_rope(const RadArgs* a, RadStream stream) { int emit_rc = RAD_OK; const RadTensor* q = r4d_opt(a, QN_Q); const RadTensor* k = r4d_opt(a, QN_K); @@ -144,7 +142,7 @@ static int rad_qkv_norm_rope_body(const RadArgs* a, const R4dSink& sk) { const char* mode = r4d_gets(a, "mode"); if (mode && std::strcmp(mode, "neox")) return R4D_NO(RAD_E_UNSUPPORTED); if (r4d_getf(a, "yarn_factor", 0.0) != 0.0) return R4D_NO(RAD_E_UNSUPPORTED); - // rope's ladder, resolved exactly as r4d_rad_rope resolves it + // rope's ladder, resolved as r4d_rad_rope resolves it const char* lad = r4d_gets(a, "ladder"); long long den = rot; if (lad) { @@ -162,8 +160,8 @@ static int rad_qkv_norm_rope_body(const RadArgs* a, const R4dSink& sk) { const long long Mp = r4d_numel(ps); if (Mp <= 0 || M < Mp || Mk != M || Mv != M) return R4D_NO(RAD_E_SHAPE); - // the standalone kernels' widths, from the same function: rmsnorm one row a head at - // r4d_act_threads(rows, head_dim), rmsnorm_p at 256 + // The standalone kernels' widths, from the same function: rmsnorm (one row per head) at + // r4d_act_threads(rows, head_dim), rmsnorm_p at 256. const uint32_t pq = (uint32_t)std::min(r4d_act_threads((int)(M * nq), (int)hd), hd); const uint32_t pk = (uint32_t)std::min(r4d_act_threads((int)(M * nkv), (int)hd), hd); const uint32_t pv = (uint32_t)std::min(256, hd); @@ -171,13 +169,12 @@ static int rad_qkv_norm_rope_body(const RadArgs* a, const R4dSink& sk) { const float wadd = (float)r4d_getf(a, "wadd", 0.0); const float theta = (float)r4d_getf(a, "theta", 10000.0); const float rsc = (float)r4d_getf(a, "scale", 1.0); - const float mult = 1.0f; const dim3 grid((uint32_t)M, (uint32_t)(nq + nkv + (vk ? 0 : nkv))); -#define R4D_QNR_T(HD, WF, VK) emit_rc = R4D_EMIT(sk, (qkv_norm_rope_kernel), grid, dim3(HD), 0, \ +#define R4D_QNR_T(HD, WF, VK) emit_rc = R4D_EMIT(stream, (qkv_norm_rope_kernel), grid, dim3(HD), 0, \ (uint16_t*)r4d_wp(q), (uint16_t*)r4d_wp(k), (uint16_t*)r4d_wp(v), (const int32_t*)r4d_p(ps), \ r4d_p(qw), r4d_p(kw), (uint32_t)nq, (uint32_t)nkv, pq, pk, pv, (uint32_t)q_ld, (uint32_t)k_ld, \ - (uint32_t)v_ld, eps, wadd, mult, (uint32_t)rot_l, (uint32_t)nfreq, (int)den, theta, rsc, (uint32_t)Mp) + (uint32_t)v_ld, eps, wadd, (uint32_t)rot_l, (uint32_t)nfreq, (int)den, theta, rsc, (uint32_t)Mp) #define R4D_QNR(HD) \ do { if (qw->dtype == RAD_F32) { if (vk) R4D_QNR_T(HD, true, true); else R4D_QNR_T(HD, true, false); } \ else { if (vk) R4D_QNR_T(HD, false, true); else R4D_QNR_T(HD, false, false); } } while (0) @@ -187,4 +184,3 @@ static int rad_qkv_norm_rope_body(const RadArgs* a, const R4dSink& sk) { #undef R4D_QNR_T return emit_rc; } -R4D_ENTRY(r4d_rad_qkv_norm_rope, rad_qkv_norm_rope_body) diff --git a/libr4d/r4d_qsa_block_key_bf16.hip b/libr4d/r4d_qsa_block_key_bf16.hip index c2020181..b7e6743a 100644 --- a/libr4d/r4d_qsa_block_key_bf16.hip +++ b/libr4d/r4d_qsa_block_key_bf16.hip @@ -1,33 +1,30 @@ -// The QSA indexer's COMPRESSED KEY: one 128-dim vector per four tokens of key history. +// The QSA indexer's compressed key: one 128-dim vector per four tokens of key history. // -// Qwen3.8-Flash-Next's full-attention layers do not attend to everything. A small MQA indexer -// scores 4-token blocks of the key history and the attention reads only the best 512 of them, so -// attention cost is constant past 2051 tokens instead of linear. This kernel builds the thing -// those scores are taken against. docs/QSA.md is the whole decomposition. +// Qwen3.8-Flash-Next's full-attention layers use a small MQA indexer that scores 4-token blocks of +// the key history; attention reads only the best 512, so its cost is constant past 2051 tokens. +// This kernel builds the block keys those scores use (docs/QSA.md has the decomposition). // -// WHAT THE REFERENCE HIDES, AND IT IS THE REASON THIS IS A KERNEL AT ALL. `Qwen4ExpTextQSAIndexer` -// recomputes every block key inside its per-query loop, because it is written for clarity. A block -// key does not depend on the query and does not change once its four tokens exist -- so it is -// computed ONCE, when the fourth token arrives, and cached. That is the difference between the -// indexer costing 64 bytes a token a layer and costing a pass over the whole history every step. +// The reference (`Qwen4ExpTextQSAIndexer`) recomputes every block key per query. A block key does +// not depend on the query and is fixed once its four tokens exist, so it is computed once, when +// the fourth token arrives, and cached (64 bytes per token per layer instead of a pass over the +// history every step). // -// THE ARITHMETIC, in the order the reference does it and with the roundings that order implies: +// Arithmetic, in the reference's order and rounding: // -// pooled = mean over the block's `ratio` raw keys, ACCUMULATED IN f32 and rounded to bf16 +// pooled = mean over the block's `ratio` raw keys, accumulated in f32 and rounded to bf16 // normed = RMSNorm(pooled) over `n`, gain (wadd + w) -// out = rope(normed) at the position of the block's FIRST token +// out = rope(normed) at the position of the block's first token // -// THE MEAN IS ROUNDED TO bf16 BEFORE THE NORM and that is not an accident of transcription: the -// reference is `key_groups.float().mean(dim=1).to(raw_keys.dtype)` and the norm then reads a bf16 -// tensor. Accumulating in f32 and carrying f32 into the norm is a DIFFERENT number -- small, and -// systematic on every block of every layer. +// The mean is rounded to bf16 before the norm, as in the reference +// (`key_groups.float().mean(dim=1).to(raw_keys.dtype)`); carrying f32 would give systematically +// different values. // -// THE ROTATION IS r4d_qk_norm_rope_gate's, line for line: `1/powf(theta, 2i/rot)`, the position -// divided by `rscale` in f32, `sincosf`, neox pairing at a stride of `rot/2`. It computes sincos -// rather than reading that kernel's table because the table holds only the positions THIS STEP -// touches, and a block completing at decode has its first token three positions back. +// The rotation matches r4d_qk_norm_rope_gate: `1/powf(theta, 2i/rot)`, position divided by +// `rscale` in f32, `sincosf`, neox pairing at stride `rot/2`. sincos is computed rather than read +// from that kernel's table, which holds only this step's positions (a block completing at decode +// starts three positions back). // -// Returns a negative code rather than throwing, for the reason given in r4d_gemm_fp8a8.hip. +// Returns a RAD status rather than throwing, for the reason given in r4d_gemm_fp8a8.hip. #include "r4d.h" #include "r4d_args.h" @@ -46,8 +43,8 @@ namespace { constexpr int kMaxN = 256; // the index head dim; 128 on this model, bounded for the LDS -/* Which position component frequency `i` reads, for the multi-component rotaries: `mode` 2 is - * contiguous sections, 3 Qwen3-VL's interleaved ones (r4d_model_bf16.hip's rope says the same). */ +/* Position component read by frequency `i` for multi-component rotaries: mode 2 is contiguous + * sections, 3 Qwen3-VL's interleaved ones (as in r4d_model_bf16.hip's rope). */ __device__ __forceinline__ int qbk_comp(int mode, int i, int s0, int s1, int s2) { if (mode == 3) { if (i % 3 == 1 && i < 3 * s1) return 1; @@ -70,7 +67,7 @@ __global__ __launch_bounds__(kMaxN) void qsa_block_key_kernel( const int b = blockIdx.x; const int t = threadIdx.x; - /* The mean, in f32 over the block's rows, rounded to bf16 exactly once. */ + /* Mean in f32 over the block's rows, rounded to bf16 once. */ float acc = 0.0f; if (t < n) { const size_t base = (size_t)b * ratio; @@ -79,8 +76,7 @@ __global__ __launch_bounds__(kMaxN) void qsa_block_key_kernel( acc = __bfloat162float(__float2bfloat16(acc / (float)ratio)); } - /* RMSNorm over n. The sum is over the whole row, so it is a block reduction and not a wave - * one -- n is 128 here and a wave is 32. */ + /* RMSNorm over n: a block reduction, since n (128) spans several waves. */ float ss = t < n ? acc * acc : 0.0f; ss = r4d_wave_sum(ss); if ((t & 31) == 0) red[t >> 5] = ss; @@ -90,9 +86,8 @@ __global__ __launch_bounds__(kMaxN) void qsa_block_key_kernel( for (int i = 0; i < nw; ++i) sum += red[i]; const float inv = rsqrtf(sum / (float)n + eps); - /* f32 THROUGH THE NORM AND THE ROTATION, rounded once at the store. That is - * r4d_qk_norm_rope_gate's choice for the model's own K and this follows it rather than - * rounding again after the gain, so the two rotations in a layer are the same arithmetic. */ + /* f32 through the norm and rotation, rounded once at the store, matching + * r4d_qk_norm_rope_gate for the model's own K. */ if (t < n) sh[t] = acc * inv * (wadd + w[t]); __syncthreads(); @@ -103,14 +98,10 @@ __global__ __launch_bounds__(kMaxN) void qsa_block_key_kernel( const bool first = t < half; const int pt = first ? t + half : t - half; const int ci = first ? t : t - half; - /* THE BLOCK'S OWN POSITION, from the work list when there is one. `pos0 + b*ratio` is the - * tiling and serves a prefill chunk, where the completing blocks ARE a contiguous run of - * one sequence. It does not serve a decode step: the sequences in a batch are at - * different positions, so the blocks completing in one launch belong to different - * sequences and are not a run at all. An explicit list makes a launch a set of work items - * rather than a range, and then one launch a layer serves any mix. */ - /* With `mc`, the list holds a block's three components side by side, blocks `bstep` - * apart, and each frequency reads the one its section names. */ + /* The block's position: from the work list (bpos) when given, so one launch serves blocks + * of different sequences (decode); otherwise the pos0 + b*ratio tiling (a prefill chunk's + * contiguous run). With `mc` the list holds a block's three components side by side, + * blocks `bstep` apart, and each frequency reads its section's component. */ const int comp = mc ? qbk_comp(mode, ci, s0, s1, s2) : 0; const long long bp = bpos ? (long long)bpos[(size_t)b * bstep + comp] : (pos0 + (long long)b * ratio); @@ -122,12 +113,8 @@ __global__ __launch_bounds__(kMaxN) void qsa_block_key_kernel( const float xp = sh[pt]; res = first ? (res * c - xp * s) : (xp * s + res * c); } - /* THE DESTINATION IS A PAGE AND NOT A ROW when `page` is passed, because the block-key store - * is the paged KV group described in docs/QSA.md: block b of a sequence lives at whatever page - * the manager gave it, and consecutive blocks are not consecutive pages. Absent, the write is - * contiguous -- which is the shape a test drives and the shape a caller with its own scratch - * wants. A negative entry is a block with no page, and is skipped rather than written - * somewhere arbitrary. */ + /* With `page`, block b is written to its page of the paged block-key store (docs/QSA.md); + * a negative entry (no page) is skipped. Without it the write is contiguous. */ long long orow = b; if (page) { const int32_t p = page[b]; @@ -143,56 +130,40 @@ __global__ __launch_bounds__(kMaxN) void qsa_block_key_kernel( // w [n] f32 // out [M][n] bf16, `o_ld` elements a row (0 = n) // -// `pos0` is the position of the FIRST token of the FIRST block. Blocks tile the token stream, so -// block i's first token is at `pos0 + i * ratio` and no position operand is needed; a caller with -// a non-contiguous run issues it in runs. +// Without `bpos`, `pos0` is the position of the first block's first token and block i starts at +// `pos0 + i * ratio`. static int r4d_qsa_block_key_bf16_emit(long k, long w, long page, long bpos, long out, int M, int n, int ratio, int rot, float eps, float wadd, float theta, float rscale, long long pos0, int k_ld, int o_ld, int mode, int s0, int s1, int s2, int bstep, int mc, - const R4dSink& sk, RadYarn yarn = {}) { - int emit_rc = RAD_OK; - if (!k || !w || !out) return -1; - if (M <= 0 || n <= 0 || n > kMaxN || ratio <= 0) return -2; - if (rot < 0 || rot > n || (rot & 1)) return -3; - if (pos0 < 0 && !bpos) return -5; + RadStream stream, RadYarn yarn) { + if (!k || !w || !out || (pos0 < 0 && !bpos)) return R4D_NO(RAD_E_INVAL); + if (M <= 0 || n <= 0 || n > kMaxN || ratio <= 0) return R4D_NO(RAD_E_SHAPE); + if (rot < 0 || rot > n || (rot & 1)) return R4D_NO(RAD_E_SHAPE); if (!k_ld) k_ld = n; if (!o_ld) o_ld = n; - /* The launch is n threads rounded up to a wave, because the reduction is a block reduction - * over exactly n values and a partial wave would fold garbage into it. */ + /* n threads rounded up to whole waves for the block reduction (extra threads contribute 0). */ const int thr = ((n + 31) / 32) * 32; - emit_rc = R4D_EMIT(sk, qsa_block_key_kernel, dim3((unsigned)M), dim3((unsigned)thr), 0, (const uint16_t*)k, (const float*)w, - (const int32_t*)page, (const int32_t*)bpos, (uint16_t*)out, - n, ratio, rot, eps, wadd, theta, rscale, pos0, k_ld, o_ld, mode, s0, s1, - s2, bstep, mc, yarn); - return emit_rc == RAD_OK && (sk.desc || hipGetLastError() == hipSuccess) ? 0 : -4; -} - -extern "C" int r4d_qsa_block_key_bf16_emit(long k, long w, long page, long bpos, long out, int M, - int n, int ratio, int rot, float eps, float wadd, - float theta, float rscale, long long pos0, int k_ld, - int o_ld, long stream) { - R4dSink sk; sk.stream = (RadStream)(uintptr_t)stream; - return r4d_qsa_block_key_bf16_emit(k, w, page, bpos, out, M, n, ratio, rot, eps, wadd, theta, rscale, pos0, k_ld, o_ld, 0, 0, 0, 0, 1, 0, sk); + return R4D_EMIT(stream, qsa_block_key_kernel, dim3((unsigned)M), dim3((unsigned)thr), 0, + (const uint16_t*)k, (const float*)w, (const int32_t*)page, + (const int32_t*)bpos, (uint16_t*)out, n, ratio, rot, eps, wadd, theta, rscale, + pos0, k_ld, o_ld, mode, s0, s1, s2, bstep, mc, yarn); } // ============================================================== the plugin ABI entry point enum { QBK_K = 0, QBK_W = 1, QBK_PAGE = 2, QBK_POS = 3, QBK_OUT = 4 }; -static int r4d_rad_qsa_block_key_body(const RadArgs* a, const R4dSink& sk) { +extern "C" int r4d_rad_qsa_block_key(const RadArgs* a, RadStream stream) { const RadTensor* k = r4d_opt(a, QBK_K); const RadTensor* w = r4d_opt(a, QBK_W); - const RadTensor* pg = r4d_opt(a, QBK_PAGE); /* OPTIONAL: absent is a contiguous write */ - const RadTensor* bp = r4d_opt(a, QBK_POS); /* OPTIONAL: absent is the pos0 tiling */ + const RadTensor* pg = r4d_opt(a, QBK_PAGE); /* optional: absent is a contiguous write */ + const RadTensor* bp = r4d_opt(a, QBK_POS); /* optional: absent is the pos0 tiling */ const RadTensor* o = r4d_opt(a, QBK_OUT); if (!k || !w || !o) return R4D_NO(RAD_E_INVAL); - /* THE DESTINATION MAY BE A KV CACHE, WHICH IS RANK FOUR. The block-key store is a KV group - * whose geometry is a container and not an attention shape -- `kv_heads` 1, `block_size` the - * compress ratio, `head_dim` n/(2*ratio) -- so a page holds exactly `n` contiguous values and - * the manager allocates one per `ratio` tokens (docs/QSA.md). Read that way it IS [pages, n], - * and the check is on the PRODUCT rather than on the rank, because the rank is the engine's - * business and the width is this op's. */ + /* The destination may be a rank-4 KV cache: the block-key store is a KV group with kv_heads 1, + * block_size = ratio and head_dim n/(2*ratio), so a page holds exactly n values (docs/QSA.md). + * It is checked as [pages, n] by the product of the inner dims, not the rank. */ if (k->rank != 2) return R4D_NO(RAD_E_SHAPE); if (o->rank < 2) return R4D_NO(RAD_E_SHAPE); const long long n = r4d_geti_or(a, "n", 0); @@ -200,20 +171,18 @@ static int r4d_rad_qsa_block_key_body(const RadArgs* a, const R4dSink& sk) { const long long rot = r4d_geti_or(a, "rotary_dim", 0); const long long pos0 = r4d_geti_or(a, "pos0", -1); if (n <= 0 || ratio <= 0 || (pos0 < 0 && !bp)) return R4D_NO(RAD_E_INVAL); - /* `block_size` exists to size the block-key KV group and is the compress block by definition. - * A caller that set them apart has a group whose page holds a different number of tokens than - * a block does, which is the one way this whole design stops working. */ + /* block_size sizes the block-key KV group and must equal the compress ratio, so a page holds + * exactly one block. */ const long long bs = r4d_geti_or(a, "block_size", ratio); if (bs != ratio) return R4D_NO(RAD_E_SHAPE); - /* THE BLOCK COUNT IS THE KEY OPERAND'S, NOT THE OUTPUT'S, once a page list is in play: the - * store is as tall as the POOL and the launch is as tall as the blocks completing this step. - * Reading M off `out` would write the whole store on every call. */ + /* With a page list, M is the number of blocks completing this step, not the store's height + * (the whole pool). */ const long long M = pg ? r4d_numel(pg) : o->shape[0]; const long long ow = o->shape[0] > 0 ? r4d_numel(o) / o->shape[0] : 0; if (M < 1 || ow != n) return R4D_NO(RAD_E_SHAPE); if (pg && o->shape[0] < 1) return R4D_NO(RAD_E_SHAPE); - /* `pos` is one position a block, or a rank-2 [>= M, 1 or 3] column slice with a block's - * components side by side and the blocks a row pitch apart (qsa_work's output). */ + /* `pos` is one position per block, or a rank-2 [>= M, 1 or 3] column slice with a block's + * components side by side and blocks a row pitch apart (qsa_work's output). */ int bstep = 1; if (bp && bp->rank == 2) { if (bp->shape[0] < M || bp->stride[1] != 1 || bp->stride[0] < bp->shape[1]) @@ -222,9 +191,8 @@ static int r4d_rad_qsa_block_key_body(const RadArgs* a, const R4dSink& sk) { } else if (bp && r4d_numel(bp) < M) { return R4D_NO(RAD_E_SHAPE); } - /* THE MULTI-COMPONENT ROTARY: `mode` mrope or imrope with `sections`, and three columns of - * `pos` (qsa_work's output with its `rope` operand). A single column is the one-component - * form, which every mode reads as NeoX. */ + /* Multi-component rotary: mode mrope or imrope with `sections` and three columns of `pos` + * (qsa_work's output with its `rope` operand). A single column is read as NeoX in any mode. */ const char* mode_s = r4d_gets(a, "mode"); int mode = 0, sec[3] = { 0, 0, 0 }, n_sec = 0, mc = 0; if (mode_s && !std::strcmp(mode_s, "mrope")) mode = 2; @@ -239,9 +207,8 @@ static int r4d_rad_qsa_block_key_body(const RadArgs* a, const R4dSink& sk) { v = e; } if (mode && n_sec > 0 && bp && bp->rank == 2 && bp->shape[1] >= 3) mc = 1; - /* THE KEY OPERAND IS `ratio` TIMES TALLER, and it is checked rather than assumed: an operand - * narrowed to the block count instead of the token count would make every block pool three - * rows of the next one, which produces plausible numbers and a different model. */ + /* The key operand must be exactly M * ratio rows; a wrong height would silently pool rows + * from neighbouring blocks. */ if (k->shape[0] != M * ratio || k->shape[1] != n) return R4D_NO(RAD_E_SHAPE); if (r4d_numel(w) < n) return R4D_NO(RAD_E_SHAPE); const long long kp = r4d_row_pitch(k), op = r4d_row_pitch(o); @@ -250,13 +217,11 @@ static int r4d_rad_qsa_block_key_body(const RadArgs* a, const R4dSink& sk) { if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && (rot <= 0 || r4d_getf(a, "scale", 1.0) != 1.0))) return R4D_NO(RAD_E_INVAL); - const int e = r4d_qsa_block_key_bf16_emit( + return r4d_qsa_block_key_bf16_emit( r4d_addr(k), r4d_addr(w), r4d_addr(pg), r4d_addr(bp), r4d_addr(o), (int)M, (int)n, (int)ratio, (int)rot, (float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "wadd", 1.0), (float)r4d_getf(a, "theta", 10000.0), (float)r4d_getf(a, "scale", 1.0), - pos0, (int)kp, (int)op, mode, sec[0], sec[1], sec[2], bstep, mc, sk, yarn); - return e == 0 ? RAD_OK : RAD_E_SHAPE; + pos0, (int)kp, (int)op, mode, sec[0], sec[1], sec[2], bstep, mc, stream, yarn); } -R4D_ENTRY(r4d_rad_qsa_block_key, r4d_rad_qsa_block_key_body) diff --git a/libr4d/r4d_qsa_score_bf16.hip b/libr4d/r4d_qsa_score_bf16.hip index 96b47c84..3c4c5c29 100644 --- a/libr4d/r4d_qsa_score_bf16.hip +++ b/libr4d/r4d_qsa_score_bf16.hip @@ -1,27 +1,21 @@ -// The QSA indexer's BLOCK SCORE: how much one query wants each compressed block of key history. +// The QSA indexer's block score: how much one query wants each compressed block of key history. // // score[m][b] = ( sum over heads h of relu( q[m][h] . bk[bt[seq(m)][b]] ) ) / sqrt(n) // -// The top `budget/ratio` of these per query is the set the attention then reads, so this is the -// whole of what makes Qwen3.8-Flash-Next's attention constant-cost past 2051 tokens rather than -// linear. docs/QSA.md is the decomposition; r4d_qsa_block_key_bf16.hip builds `bk`. +// The top budget/ratio scores per query select the blocks attention reads (docs/QSA.md; +// r4d_qsa_block_key_bf16.hip builds `bk`). // -// THE RELU IS PER (BLOCK, HEAD) AND THE SUM IS OVER HEADS, in that order, and swapping them is a -// different model that still ranks blocks plausibly. The reference is `relu(scores).sum(dim=-1)` -// over a [n_blocks, heads] plane -- four independent votes, each of which can only ever argue FOR -// a block. Summing first would let one head's large negative cancel another's positive. +// The relu is per (block, head), then summed over heads, as in the reference +// (`relu(scores).sum(dim=-1)`); summing first would let one head's negative cancel another's +// positive and still rank plausibly. // -// `bt` IS A LIST OF PAGE IDS, NOT BLOCK INDICES, and that is the point of the whole design: the -// attention KV group is paged at `ratio` tokens, so a compress block and a page are the same -// thing, the block keys are stored per page, and the sequence's existing attention block table is -// already the list this scores. The top-k over the output is then a list of page ids, which is -// the block table the attention reads. Nothing is remapped anywhere. +// `bt` holds page ids, not block indices: the attention KV group is paged at `ratio` tokens, so a +// compress block is a page, block keys are stored per page, and the sequence's attention block +// table is the list scored. The top-k is then directly the block table attention reads. // -// AN ABSENT ENTRY SCORES -inf RATHER THAN ZERO. A block table is padded to its declared width and -// a real score can be zero (every head vetoed the block), so zero would let padding outrank a -// live block the model chose to ignore. +// An absent entry scores -inf, not zero: tables are padded, and a real score can be zero. // -// Returns a negative code rather than throwing, for the reason given in r4d_gemm_fp8a8.hip. +// Returns a RAD status rather than throwing, for the reason given in r4d_gemm_fp8a8.hip. #include "r4d.h" #include "r4d_args.h" @@ -42,44 +36,28 @@ constexpr int kThreads = 256; constexpr int kWaves = kThreads / kWave; constexpr int kMaxH = 8; // indexer query heads; 4 on this model constexpr int kMaxVPL = 8; // n / kWave, so n <= 256 -// One WAVE a block, and a workgroup covers a TILE OF QUERIES rather than one -- which is the -// whole of what makes this affordable at length. +// Scalar form: one wave per block, and a workgroup covers a tile of queries, so the key history +// (the only real traffic) is read once per tile instead of once per query row. // -// A block key is 256 bytes and every query in the step wants the same one. Scoring one query a -// workgroup reads the entire key history ONCE A QUERY ROW, and a speculative decode step is -// `1 + n_spec` rows -- at 200K of context that is dead linear in M, 88.3 us at M=1 and 298.6 at -// M=4. The keys are the only real traffic here, so holding a tile of queries in LDS and paying for -// them once is a straight divide by the tile. -// -// THE TILE IS FOUR BECAUSE A DECODE ROW-GROUP IS. Every sequence contributes exactly `1 + n_spec` -// query rows and `cu` is their cumulative count, so at the shipped depth of 3 a tile of 4 lands -// on a sequence boundary exactly. It is not required to: a tile that straddles two sequences is -// split at the boundary and the keys are read once per part, which is no worse than the one-query -// form does for every query anyway. The tile lives in registers -- see the scoring loop. +// kQT = 4 matches a decode row group (1 + n_spec rows at depth 3), so tiles usually align with +// sequences; a tile straddling two sequences is processed per part, reading the keys once per +// part. The tile lives in registers (see the scoring loop). constexpr int kBPW = 4; // blocks a WAVE; a workgroup owns kWaves * kBPW = 32 constexpr int kQT = 4; // query rows a workgroup, and the grid's third axis -/* THE BUTTERFLY IS `r4d_wave_sum` AND ITS FIVE STEPS ARE SPELLED OUT BELOW, not called as one, - * because the reduction is per HEAD and the five STEPS have to be hoisted out of the head loop: - * a whole reduction inside it is `HEADS * 5` dependent lane exchanges with nothing to hide behind, - * where five steps of `HEADS` independent ones is a quarter of the chain. Same lanes, same order, - * same bits -- r4d_common.h has the measurement and why it is not on the LDS crossbar. */ +/* The scoring loop spells out r4d_wave_sum's five butterfly steps so they can be hoisted out of + * the head loop (see there); same lanes, order and bits. */ - -// `m` IS A QUERY AND NOT A SEQUENCE, and `cu` is what tells the two apart. At decode they are the -// same thing up to the draft rows -- `1 + n_spec` queries a sequence -- but a prefill chunk is -// many queries over one history and every one of them selects its own set (docs/QSA.md, Stage B). -// The block table is the SEQUENCE's, so the scan of `cu` is how a query row finds its table row. +// `m` is a query row, not a sequence: a prefill chunk has many queries over one history, each +// selecting its own set (docs/QSA.md, "Per-query selection"). A query finds its sequence's block-table row by +// scanning `cu`. // -// A lane owns `n / 32` consecutive dims of both 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 four heads AND all -// `kQT` queries -- which is why the head loop and the query loop are both inside the block loop. +// A lane owns n / 32 consecutive dims of the query heads and the block key, so a head's dot is one +// wave reduction and each block key is read once for all heads and all kQT queries. // -// `nc` BOUNDS THE BLOCK LOOP AND IS NOT OPTIONAL. `nb` is the smaller of two DECLARED widths -- -// the score plane's and the block table's pitch -- and both are sized for max_ctx, so scoring to -// `nb` on a 200-token prompt would read 65536 padding entries a query. The sequence's complete -// block count is an upper bound for every query in the chunk and is within `T / ratio` of each -// one's own; `qsa_select` applies the exact per-query bound, which it can because it has `pos`. +// `nc` (complete blocks per sequence) bounds the block loop; nb is a declared width sized for +// max_ctx and would mostly score padding. nc is an upper bound for every query in the chunk; +// qsa_select applies the exact per-query bound from `pos`. template __global__ __launch_bounds__(kThreads) void qsa_score_kernel( const __hip_bfloat16* __restrict__ q, const __hip_bfloat16* __restrict__ bk, @@ -90,21 +68,17 @@ __global__ __launch_bounds__(kThreads) void qsa_score_kernel( __shared__ int sh_seq; const int lane = threadIdx.x & (kWave - 1), wave = threadIdx.x >> 5; const float inv = rsqrtf((float)n); - /* HOW WIDE A LANE MAY LOAD. A lane's dims are consecutive, so the widest vector that divides - * both `vpl` and the row pitch is legal and the narrow cases still work -- a KV cache row - * pitch is not required to be a multiple of anything. */ + /* Load width: the widest vector dividing both VPL and the row pitch (a KV cache row pitch + * need not be a multiple of anything). */ const int kvec = ((VPL & 3) == 0 && (bk_ld & 3) == 0) ? 4 : ((VPL & 1) == 0 && (bk_ld & 1) == 0) ? 2 : 1; const int m0 = (int)blockIdx.y * kQT; - /* The tile walks its queries a SEQUENCE at a time: everything below the query loop -- the - * block table row, the complete-block count, the grid's block bound -- belongs to the - * sequence and not to the query. At the shipped depth the loop runs once. */ + /* The tile walks its queries one sequence at a time (block table row, complete-block count + * and block bound are per sequence). Usually one iteration. */ for (int m = m0; m < m0 + kQT; ) { - /* The sequence of query `m`. Exactly one `i` can match, so the store is deterministic - * however the threads are scheduled -- which matters because this tree compares generated - * text across builds byte for byte. A query past the batch matches nothing and ends the - * tile. */ + /* The sequence of query `m`. Exactly one i matches, so the store is deterministic. A query + * past the batch matches nothing and ends the tile. */ if (threadIdx.x == 0) sh_seq = -1; __syncthreads(); for (int i = (int)threadIdx.x; i < nseq; i += kThreads) @@ -116,17 +90,13 @@ __global__ __launch_bounds__(kThreads) void qsa_score_kernel( const int nq = mend - m; const int nbs = nc[seq] < nb ? nc[seq] : nb; - /* The block axis is sized from the DECLARED width, so most workgroups on a short context - * have nothing to do; they skip here, before the query load. It is a SKIP and not a - * return because the count is the sequence's: a tile straddling two of them can be past - * the end of the first and inside the second. Every thread takes the same branch -- the - * bound is uniform -- so the barriers below stay matched. + /* The block axis is sized from the declared width, so most workgroups on a short context + * skip here, before the query load. A skip, not a return: a straddling tile may be past + * the first sequence's blocks but inside the second's. The bound is uniform, so barriers + * stay matched. * - * THE SKIP STILL WAITS AT A BARRIER. The next part begins with thread 0 resetting - * `sh_seq`, and a wave that has not yet read this part's value would read the reset and - * leave the tile early, its blocks of the next sequence never scored. The barrier at the - * bottom of the loop is what orders that on the scoring path; this is the same one for - * the path that skips it, taken only when there is a next part to reset for. */ + * The skip path still needs the barrier: the next part starts with thread 0 resetting + * sh_seq, and a wave that has not read this part's value would leave early. */ const int b0 = (int)blockIdx.x * (kWaves * kBPW); if (nbs <= 0 || b0 >= nbs) { m = mend; @@ -135,12 +105,9 @@ __global__ __launch_bounds__(kThreads) void qsa_score_kernel( } const int b1 = (b0 + kWaves * kBPW) < nbs ? (b0 + kWaves * kBPW) : nbs; - /* THE QUERY TILE IN REGISTERS, loaded once for every block this workgroup owns. A lane - * needs only its own VPL dims of each head of each query, and with the head count, the - * dims a lane owns and the tile all compile-time that is kQT * HEADS * VPL registers -- - * 64 at this model's shape. Held in LDS instead, every block re-reads all of them, 64 - * `ds_read_b32` a block a lane, and LDS issue is what this kernel queues on. A query - * past the tile's part reads the part's last row and is never scored. */ + /* The query tile in registers (kQT * HEADS * VPL, 64 at this model's shape), loaded once + * for all of this workgroup's blocks; in LDS every block would re-read it, and LDS issue + * is this kernel's bottleneck. A query past the part reads its last row, unscored. */ float qv[kQT][HEADS][VPL]; #pragma unroll for (int mi = 0; mi < kQT; ++mi) { @@ -153,13 +120,10 @@ __global__ __launch_bounds__(kThreads) void qsa_score_kernel( } } - /* ALL OF THIS WAVE'S BLOCKS ARE ASKED FOR BEFORE ANY IS SCORED. A block is two dependent - * reads -- its page id out of the block table, then its key out of that page -- and taken - * a block at a time a wave waits out both, kBPW times over: eight memory latencies in a - * row, with the key history streaming at a third of what the part can deliver at 200K of - * context. So every page id is read first, then every key, and only then does the scoring - * begin. A block past the end or without a page reads page 0's key, which is always there, - * and is skipped below. */ + /* Issue all of this wave's loads before scoring: each block is two dependent reads (page + * id, then key), so all page ids are read first, then all keys, instead of 2 * kBPW + * serial latencies. A block past the end or without a page reads page 0's key (always + * present) and is skipped below. */ int pg[kBPW]; float kvs[kBPW][VPL]; #pragma unroll @@ -170,12 +134,9 @@ __global__ __launch_bounds__(kThreads) void qsa_score_kernel( #pragma unroll for (int i = 0; i < kBPW; ++i) { float* kv = kvs[i]; - /* ONE LOAD A LANE, NOT `vpl` OF THEM, and the difference is the whole bus. A lane owns - * `vpl` CONSECUTIVE dims, so a scalar loop issues `vpl` two-byte loads each of which - * spans the wave's entire 256-byte page: four cache lines touched to use 64 bytes of - * them, four times over, which reads the key history at about 145 GB/s on a 621 GB/s - * part. The vector form is the same bytes in the same order into the same registers -- - * only the instruction changes, so the sum below is bit-identical. */ + /* One vector load per lane instead of VPL two-byte loads, each of which would touch + * the wave's whole 256-byte row (about 145 GB/s on a 621 GB/s part). Same bytes and + * registers, so the sum is bit-identical. */ const uint16_t* kp = (const uint16_t*)bk + (size_t)(pg[i] >= 0 ? pg[i] : 0) * bk_ld + lane * VPL; if (kvec == 4) { @@ -215,17 +176,10 @@ __global__ __launch_bounds__(kThreads) void qsa_score_kernel( #pragma unroll for (int mi = 0; mi < kQT; ++mi) { if (mi >= nq) break; - /* EVERY HEAD'S DOT FIRST, THEN ONE BUTTERFLY OVER ALL OF THEM. A wave reduction is - * five lane exchanges and each depends on the last, so a reduction per head inside - * the head loop is `HEADS * 5` exchanges in a single dependency chain with nothing - * to hide behind. Hoisting the five STEPS out leaves five dependent - * ones with `HEADS` independent shuffles inside each -- the same instructions in - * the same order on the same values, so the sum is bit-identical, and the chain - * is a quarter as long. - * - * `HEADS` is a template parameter because `dv[]` -- and `qv` above -- have to - * live in registers: indexed by a runtime bound they become scratch, and a spilled - * accumulator would cost more than the chain it is here to shorten. */ + /* Every head's dot first, then one butterfly over all of them: five dependent steps + * with HEADS independent shuffles each, instead of a HEADS * 5 chain. Same values in + * the same order, so bit-identical. HEADS is a template parameter so dv[] and qv + * stay in registers. */ float dv[HEADS]; #pragma unroll for (int h = 0; h < HEADS; ++h) { @@ -244,9 +198,7 @@ __global__ __launch_bounds__(kThreads) void qsa_score_kernel( for (int h = 0; h < HEADS; ++h) dv[h] = r4d_dpp_xor_add<0x162>(dv[h]); /* xor 2 */ #pragma unroll for (int h = 0; h < HEADS; ++h) dv[h] = r4d_dpp_xor_add<0x161>(dv[h]); /* xor 1 */ - /* Every lane holds the reduced values, so the relu and the head sum are the same - * on all of them and only lane 0 stores. A partial reduction would be a score - * that depends on which lane asked. */ + /* Every lane holds the full reduction; lane 0 stores. */ float s = 0.0f; #pragma unroll for (int h = 0; h < HEADS; ++h) s += fmaxf(dv[h], 0.0f); @@ -254,64 +206,39 @@ __global__ __launch_bounds__(kThreads) void qsa_score_kernel( } } m = mend; - /* The next part of a straddling tile resets `sh_seq`, so nobody may still be reading it. */ + /* The next part resets sh_seq, so all reads of it must be done. */ __syncthreads(); } } /* ================================================================== the matrix form * - * THE SAME SCORE AS A MATRIX PRODUCT, for a batch with many queries on one history -- a prefill - * chunk. Per head the scores of 16 queries against 16 blocks are one 16x16 tile of - * K_tile . Q_h^T, eight bf16 WMMA steps over the 128 dims, and the relu and the head sum then - * happen in the accumulator registers: a lane holds one query and eight consecutive blocks of - * every head's tile, so the four votes of a (query, block) pair are already side by side. + * The same score as a matrix product. Per head, 16 queries x 16 blocks is one 16x16 tile of + * K_tile . Q_h^T (eight bf16 WMMA steps over 128 dims); a lane then holds one query against eight + * consecutive blocks of every head's tile, so relu and head sum happen in registers. * - * WHY THE FORM ABOVE LOSES AT PREFILL. It is built for a decode step's four rows: a workgroup holds - * four queries in registers and every block costs a five-step lane reduction per head. A 2048-row - * chunk is 512 of those tiles, so the key history is read 512 times and the reductions outnumber - * the multiplies; at 80K of context that is 9.3 ms a call, thirteen calls a step. Here the key - * history is read once per 16 queries, there is no reduction at all, and the multiplies run on - * the matrix units. + * The scalar form reads the key history once per four query rows and does a lane reduction per + * head per block, so it is linear in M (a 2048-row chunk at 80K context: 9.3 ms per call). Here + * the history is read once per 16 queries with no reductions. It is used for every batch it fits, + * since it was faster at every measured shape except a single short-context query (by ~0.25 us), + * e.g. at 200K context: M=1 29.9 -> 12.7 us, M=32 437 -> 27.2 us, M=2048 27.7 -> 1.36 ms. * - * AND IT WINS AT DECODE TOO, which is why it is the form for every batch it is built for and not - * only for prefill. --perfqsa, one scattered history (us a call): + * One form for all batch sizes also keeps a score a function of its query: the two forms sum in + * different orders and differ in the last bit (rel_l2 ~4e-8), which could flip an exact tie. * - * ctx M=1 M=16 M=32 M=2048 - * 2000 5.28 -> 5.54 6.38 -> 5.50 8.03 -> 5.50 276 -> 17.4 - * 80000 25.0 -> 7.9 (M=4) 10849 -> 535 - * 200000 29.9 -> 12.7 220 -> 16.2 437 -> 27.2 27711 -> 1356 - * - * The scalar form's cost is linear in the rows -- a four-row tile per workgroup reads the history - * again for every four rows -- so eight sequences at depth 3 and 200K of context cost 5.7 ms a - * step in this op across its thirteen calls. The one row it still wins is a single query at a short - * context, by a quarter of a microsecond. - * - * ONE FORM FOR EVERY BATCH ALSO KEEPS A SCORE A FUNCTION OF ITS QUERY. The two forms multiply the - * same bf16 pairs exactly in f32 but sum them in different orders -- the WMMA's internal order over - * sixteen dims and then eight steps, against a lane's four-dim chain and a butterfly -- so they - * differ in the last bit (rel_l2 ~4e-8 between them), and a selection at an exact tie could differ - * with it. Choosing the form by batch size would make a query's selection depend on what else was - * in its step; within one form, which rows share a tile does not change a row's score. - * - * ONE WAVE OWNS 16 QUERY ROWS AND A RANGE OF `tpw` BLOCK TILES. The query rows are loaded once, - * into registers -- HEADS x 8 fragments, 128 VGPRs at four heads -- and the wave then streams its - * block tiles past them, one page-id read and eight fragment loads a tile. A workgroup is four - * waves on four consecutive block ranges of the same query rows, so the rows they share are - * fetched once into the WGP's cache. There is no LDS and no barrier. - * - * ROWS OF TWO SEQUENCES IN ONE TILE ARE SCORED A SEQUENCE AT A TIME, exactly as the scalar form - * does it: each part walks its own sequence's table, and only the rows of that part are stored. - * A tile of decode rows beside a prefill chunk is the only place that happens. */ + * One wave owns 16 query rows (in registers: HEADS x 8 fragments, 128 VGPRs at four heads) and a + * range of `tpw` block tiles, each one page-id read and eight fragment loads. A workgroup is four + * waves on consecutive block ranges of the same query rows, sharing them through the WGP cache. + * No LDS, no barrier. A tile with rows of two sequences is scored per sequence, as in the scalar + * form (decode rows next to a prefill chunk). */ constexpr int kMxWaves = 4; // waves a workgroup, each on its own block range constexpr int kMxQ = 16; // query rows a wave: the WMMA tile's N constexpr int kMxKS = 8; // 16-wide K steps: n = 128, the only width this form is built for -/* A wave's block range: enough of them that the grid holds about this many waves, which is a - * couple of rounds of the part's resident capacity (64 CUs x 4 SIMDs x ~6 waves at this form's - * register count) ... */ +/* Target grid size in waves for sizing a wave's block range: a couple of rounds of resident + * capacity (64 CUs x 4 SIMDs x ~6 waves at this form's register count) ... */ constexpr long long kMxWavesTarget = 4096; -/* ... and never fewer tiles than this, because a wave loads its sixteen query rows -- 16 KiB at - * four heads -- before its first tile, and at one tile a wave that load is most of what it reads. */ +/* ... and at least this many tiles per wave, since loading the 16 query rows (16 KiB at four + * heads) would otherwise dominate. */ constexpr long long kMxMinTiles = 4; template @@ -328,8 +255,8 @@ __global__ __launch_bounds__(kMxWaves * kWave) void qsa_score_mx_kernel( if (m0 >= M || wb0 >= nb) return; /* wave-uniform, and nothing below synchronises */ const float inv = rsqrtf((float)(kMxKS * 16)); - /* The B operand: query row `col` of the tile, every head, every K step. A row past the batch - * reads the last one and is never stored. */ + /* B operand: query row `col` of the tile, every head and K step. A row past the batch reads + * the last row and is never stored. */ v8bf qf[HEADS][kMxKS]; { const int qr = m0 + col < M ? m0 + col : M - 1; @@ -357,13 +284,12 @@ __global__ __launch_bounds__(kMxWaves * kWave) void qsa_score_mx_kernel( const int bend = wb0 + tpw * 16 < nbs ? wb0 + tpw * 16 : nbs; const int32_t* tab = bt + (size_t)seq * bt_ld; - /* THE NEXT TILE'S PAGE ID IS READ WHILE THIS TILE'S KEY IS OUT: the key's address - * depends on it, so read in its own iteration it is a second load latency every tile. */ + /* Read the next tile's page id while this tile's key loads, hiding one dependent latency + * per tile. */ int pg_next = wb0 + col < bend ? tab[wb0 + col] : -1; for (int b0 = wb0; b0 < bend; b0 += 16) { - /* The A operand: block `b0 + col`'s key, one page-id read and eight fragment loads. A - * block past the end or without a page reads page 0's key, which always exists, and - * is overwritten or skipped at the store. */ + /* A operand: block b0 + col's key. A block past the end or without a page reads page + * 0's key (always present) and is masked or skipped at the store. */ const int b = b0 + col; const int pg = pg_next; const unsigned short* kp = bk + (size_t)(pg >= 0 ? pg : 0) * bk_ld + 4 * half; @@ -408,15 +334,15 @@ __global__ __launch_bounds__(kMxWaves * kWave) void qsa_score_mx_kernel( } } -/* WHICH FORM A LAUNCH TAKES: 0 is the rule below, 1 pins the scalar form, 2 the matrix form. A - * test hook, like r4d_gemm_fp8a8_pin_mw -- r4d_selftest compares the two on one input. */ +/* Form override for tests (r4d_selftest compares the two): 0 = automatic, 1 = scalar, + * 2 = matrix. Like r4d_gemm_fp8a8_pin_mw. */ int g_qsa_form = 0; } // namespace extern "C" void r4d_qsa_score_pin_form(int form) { g_qsa_form = form; } -// q [M][heads*n] bf16, `q_ld` elements a row (0 = heads*n) -- M is QUERIES +// q [M][heads*n] bf16, `q_ld` elements a row (0 = heads*n); M is query rows // bk [pages][n] bf16, `bk_ld` elements a row (0 = n) // bt [nseq][nb] i32, `bt_ld` elements a row (0 = nb); negative = no block // cu [nseq+1] i32, cumulative query counts: which sequence a query row belongs to @@ -424,38 +350,33 @@ extern "C" void r4d_qsa_score_pin_form(int form) { g_qsa_form = form; } // out [M][nb] f32, `out_ld` elements a row (0 = nb) static int r4d_qsa_score_bf16_emit(long q, long bk, long bt, long cu, long nc, long out, int M, int n, int heads, int nb, int nseq, - int q_ld, int bk_ld, int bt_ld, int out_ld, const R4dSink& sk) { + int q_ld, int bk_ld, int bt_ld, int out_ld, RadStream stream) { int emit_rc = RAD_OK; - if (!q || !bk || !bt || !cu || !nc || !out) return -1; - if (M <= 0 || n <= 0 || heads <= 0 || nb <= 0 || nseq <= 0) return -2; - if (n % kWave || n / kWave > kMaxVPL) return -3; // a lane owns n/32 dims, at most 8 - if (heads > kMaxH) return -5; + if (!q || !bk || !bt || !cu || !nc || !out) return R4D_NO(RAD_E_INVAL); + if (M <= 0 || n <= 0 || heads <= 0 || nb <= 0 || nseq <= 0) return R4D_NO(RAD_E_SHAPE); + /* A lane owns n/32 dims, at most 8. */ + if (n % kWave || n / kWave > kMaxVPL || heads > kMaxH) return R4D_NO(RAD_E_SHAPE); if (!q_ld) q_ld = heads * n; if (!bk_ld) bk_ld = n; if (!bt_ld) bt_ld = nb; if (!out_ld) out_ld = nb; - /* The block axis is sized from the DECLARED width because the live count is device data; a - * workgroup past the live end exits on its first compare, which is what `nb` inside the kernel - * is bounded to. The QUERY axis is tiled the same way and for the same reason: a tile whose - * first row is past the batch ends on its `cu` scan. */ - /* THE MATRIX FORM WHENEVER IT IS BUILT FOR THE SHAPE: 128 dims and at most four heads, which - * is what fits the query rows in registers. The scalar form serves every other width and head - * count the op admits. */ + /* Grid axes are sized from declared widths (live counts are device data); surplus workgroups + * exit early. The matrix form is used whenever it fits (n = 128, at most four heads, so the + * query rows fit in registers); the scalar form serves the rest. */ const bool mx_fits = n == kMxKS * 16 && heads <= 4; - if (g_qsa_form == 2 && !mx_fits) return -3; + if (g_qsa_form == 2 && !mx_fits) return R4D_NO(RAD_E_SHAPE); const bool mx = g_qsa_form == 1 ? false : mx_fits; if (mx) { - /* THE BLOCK RANGE A WAVE OWNS is sized so the grid holds about kMxWavesTarget waves, and - * never less than kMxMinTiles tiles, below which loading the query rows costs more than - * the tiles they are used for. */ + /* Tiles per wave: about kMxWavesTarget waves in the grid, at least kMxMinTiles each. */ const long long qt = (M + kMxQ - 1) / kMxQ, tiles = (nb + 15) / 16; long long tpw = (tiles * qt + kMxWavesTarget - 1) / kMxWavesTarget; if (tpw < kMxMinTiles) tpw = kMxMinTiles; const unsigned gx = (unsigned)((tiles + tpw * kMxWaves - 1) / (tpw * kMxWaves)); const int vec = (out_ld % 4 == 0) && ((out & 15) == 0); #define RAD_QSA_MX(H) \ - emit_rc = R4D_EMIT(sk, (qsa_score_mx_kernel), dim3(gx, (unsigned)qt), dim3(kMxWaves * kWave), \ - 0, (const unsigned short*)q, (const unsigned short*)bk, \ + emit_rc = R4D_EMIT(stream, (qsa_score_mx_kernel), dim3(gx, (unsigned)qt), \ + dim3(kMxWaves * kWave), 0, (const unsigned short*)q, \ + (const unsigned short*)bk, \ (const int32_t*)bt, (const int32_t*)cu, (const int32_t*)nc, \ (float*)out, M, nb, nseq, (int)tpw, q_ld, bk_ld, bt_ld, out_ld, vec) switch (heads) { @@ -463,23 +384,18 @@ static int r4d_qsa_score_bf16_emit(long q, long bk, long bt, long cu, long nc, l case 2: RAD_QSA_MX(2); break; case 3: RAD_QSA_MX(3); break; case 4: RAD_QSA_MX(4); break; - default: return -5; + default: return R4D_NO(RAD_E_SHAPE); } #undef RAD_QSA_MX - return emit_rc == RAD_OK && (sk.desc || hipGetLastError() == hipSuccess) ? 0 : -4; + return emit_rc; } const unsigned nbg = (unsigned)((nb + kWaves * kBPW - 1) / (kWaves * kBPW)); const unsigned nmg = (unsigned)((M + kQT - 1) / kQT); - /* THE DIMS A LANE OWNS ARE A TEMPLATE PARAMETER, and that is not tidiness. `n / 32` is a - * runtime value, so as a function argument the dot is a ROLLED loop -- the whole kernel - * disassembles to ONE `v_fmac_f32` with a dependent `ds_load_b32` in front of it, four times a - * head, and the block key sits in a runtime-indexed array the compiler cannot keep in - * registers. Fixing the count at compile time unrolls both and turns the dot into register - * FMAs. Four - * instantiations cover every `n` and every head count the op's own checks admit - * (n % 32 == 0, n <= 256, heads <= 8). */ + /* Dims per lane (n / 32) are a template parameter: as a runtime value the dot is a rolled loop + * and the block key a runtime-indexed array in scratch. The instantiations cover every n and + * head count the checks admit (n % 32 == 0, n <= 256, heads <= 8). */ #define RAD_QSA_GO(V, H) \ - emit_rc = R4D_EMIT(sk, (qsa_score_kernel), dim3(nbg, nmg), dim3(kThreads), 0, \ + emit_rc = R4D_EMIT(stream, (qsa_score_kernel), dim3(nbg, nmg), dim3(kThreads), 0, \ (const __hip_bfloat16*)q, (const __hip_bfloat16*)bk, (const int32_t*)bt, \ (const int32_t*)cu, (const int32_t*)nc, \ (float*)out, n, heads, nb, nseq, q_ld, bk_ld, bt_ld, out_ld) @@ -493,7 +409,7 @@ static int r4d_qsa_score_bf16_emit(long q, long bk, long bt, long cu, long nc, l case 6: RAD_QSA_GO(V, 6); break; \ case 7: RAD_QSA_GO(V, 7); break; \ case 8: RAD_QSA_GO(V, 8); break; \ - default: return -5; \ + default: return R4D_NO(RAD_E_SHAPE); \ } switch (n / kWave) { case 1: RAD_QSA_HEADS(1); break; @@ -504,25 +420,18 @@ static int r4d_qsa_score_bf16_emit(long q, long bk, long bt, long cu, long nc, l case 6: RAD_QSA_HEADS(6); break; case 7: RAD_QSA_HEADS(7); break; case 8: RAD_QSA_HEADS(8); break; - default: return -3; + default: return R4D_NO(RAD_E_SHAPE); } #undef RAD_QSA_HEADS #undef RAD_QSA_GO - return emit_rc == RAD_OK && (sk.desc || hipGetLastError() == hipSuccess) ? 0 : -4; -} - -extern "C" int r4d_qsa_score_bf16_emit(long q, long bk, long bt, long cu, long nc, long out, - int M, int n, int heads, int nb, int nseq, - int q_ld, int bk_ld, int bt_ld, int out_ld, long stream) { - R4dSink sk; sk.stream = (RadStream)(uintptr_t)stream; - return r4d_qsa_score_bf16_emit(q, bk, bt, cu, nc, out, M, n, heads, nb, nseq, q_ld, bk_ld, bt_ld, out_ld, sk); + return emit_rc; } // ============================================================== the plugin ABI entry point enum { QS_Q = 0, QS_BK = 1, QS_BT = 2, QS_CU = 3, QS_NC = 4, QS_OUT = 5 }; -static int r4d_rad_qsa_score_body(const RadArgs* a, const R4dSink& sk) { +extern "C" int r4d_rad_qsa_score(const RadArgs* a, RadStream stream) { const RadTensor* q = r4d_opt(a, QS_Q); const RadTensor* bk = r4d_opt(a, QS_BK); const RadTensor* bt = r4d_opt(a, QS_BT); @@ -530,25 +439,20 @@ static int r4d_rad_qsa_score_body(const RadArgs* a, const R4dSink& sk) { const RadTensor* nc = r4d_opt(a, QS_NC); const RadTensor* o = r4d_opt(a, QS_OUT); if (!q || !bk || !bt || !cu || !nc || !o) return R4D_NO(RAD_E_INVAL); - /* `bk` MAY BE A KV CACHE AND IS THEN RANK FOUR -- see r4d_qsa_block_key_bf16.hip on why the - * block-key store's geometry is a container. A page holds `n` contiguous values either way. */ + /* bk may be a rank-4 KV cache (see r4d_qsa_block_key_bf16.hip); a page holds n contiguous + * values either way. */ if (bk->rank < 2 || bt->rank != 2 || o->rank != 2) return R4D_NO(RAD_E_SHAPE); const long long n = r4d_geti_or(a, "n", 0); const long long heads = r4d_geti_or(a, "heads", 0); if (n <= 0 || heads <= 0) return R4D_NO(RAD_E_INVAL); const long long M = o->shape[0]; - /* HOW MANY BLOCKS TO SCORE IS WHAT BOTH SIDES CAN NAME, and taking the smaller is safe rather - * than approximate: a query's real block count is bounded by max_ctx/ratio and both the table - * and the score plane are sized for that, so the minimum is never below the live count. It is - * the MINIMUM and not one of them because the two come from different places -- the score - * plane is the architecture's buffer and the table's pitch is the KV manager's, and requiring - * them equal would refuse a configuration where they merely round differently. `qsa_select` - * bounds the range it reads by `nc` regardless, so a score past the live count is never looked - * at. */ + /* nb = min(table width, score-plane width). Both are sized for max_ctx / ratio (by the KV + * manager and the architecture respectively, and may round differently), so the minimum is + * never below the live count. qsa_select bounds its reads by nc regardless. */ const long long nb = bt->shape[1] < o->shape[1] ? bt->shape[1] : o->shape[1]; if (M < 1 || nb < 1) return R4D_NO(RAD_E_SHAPE); - /* THE SEQUENCE COUNT COMES OFF `cu` AND NOT OFF THE TABLE'S HEIGHT, which is max_seqs -- the - * same rule qsa_work and qsa_tail_store follow. The table must be at least that tall. */ + /* The sequence count comes from cu, not the table height (max_seqs), as in qsa_work and + * qsa_tail_store. */ if (cu->rank != 1 || cu->shape[0] < 2) return R4D_NO(RAD_E_SHAPE); const long long nseq = cu->shape[0] - 1; if (bt->shape[0] < nseq || r4d_numel(nc) < nseq) return R4D_NO(RAD_E_SHAPE); @@ -557,11 +461,9 @@ static int r4d_rad_qsa_score_body(const RadArgs* a, const R4dSink& sk) { const long long qp = r4d_row_pitch(q), kp = r4d_row_pitch(bk); const long long tp = r4d_row_pitch(bt), op = r4d_row_pitch(o); if (qp < 0 || kp < 0 || tp < 0 || op < 0) return R4D_NO(RAD_E_STRIDE); - const int e = r4d_qsa_score_bf16_emit(r4d_addr(q), r4d_addr(bk), r4d_addr(bt), r4d_addr(cu), - r4d_addr(nc), r4d_addr(o), - (int)M, (int)n, (int)heads, (int)nb, (int)nseq, - (int)qp, (int)kp, (int)tp, (int)op, sk); - return e == 0 ? RAD_OK : RAD_E_SHAPE; + return r4d_qsa_score_bf16_emit(r4d_addr(q), r4d_addr(bk), r4d_addr(bt), r4d_addr(cu), + r4d_addr(nc), r4d_addr(o), + (int)M, (int)n, (int)heads, (int)nb, (int)nseq, + (int)qp, (int)kp, (int)tp, (int)op, stream); } -R4D_ENTRY(r4d_rad_qsa_score, r4d_rad_qsa_score_body) diff --git a/libr4d/r4d_qsa_select_bf16.hip b/libr4d/r4d_qsa_select_bf16.hip index e591a321..c0b5154d 100644 --- a/libr4d/r4d_qsa_select_bf16.hip +++ b/libr4d/r4d_qsa_select_bf16.hip @@ -1,35 +1,26 @@ -// The QSA indexer's SELECTION: the `topk` highest-scoring blocks of a query's key history, as a -// page-id table the paged attention can read directly. +// The QSA indexer's selection: the `topk` highest-scoring blocks of a query's key history, as a +// page-id table the paged attention reads directly, so attention reads at most `topk + 1` pages +// at any context length (docs/QSA.md). // -// This is the last step of the indexer and the one that makes the attention constant-cost: below -// it the scorer has produced one number per complete 4-token block of the sequence, and above it -// the attention reads at most `topk + 1` pages however long the context is. docs/QSA.md is the -// decomposition. +// The output is page ids: the KV group is paged at the compress ratio, so a selected block is a +// page and the table is the attention's block table as is. // -// THE OUTPUT IS A PAGE-ID TABLE AND NOT A LIST OF RANKS, which is the whole reason the KV group -// is paged at the compress ratio: a selected block IS a page, so what comes out of here is -// literally what the attention's block table wants. Nothing is remapped. +// The partial page is appended last and is not a candidate: the reference always attends the +// `(pos+1) % ratio` tokens after the last complete block (the query is among them). Every complete +// page is entirely in the query's past, so placing the partial page last lets the attention's +// own `kk <= q` bound do the remaining causal masking. The caller passes the effective query +// position `(nsel - 1) * ratio + pos % ratio`. // -// THE PARTIAL PAGE IS APPENDED LAST AND IS NOT A CANDIDATE. The reference attends the -// `(pos+1) % ratio` tokens after the last complete block UNCONDITIONALLY -- they are the newest -// tokens and the query is among them -- so they are not scored and cannot be dropped. Last is -// load-bearing and not cosmetic: every selected COMPLETE page is entirely in the query's past, so -// the only causal masking left is inside the final page, and putting it at the end of the table -// makes the attention's own `kk <= q` bound do exactly that with no change to the kernel. The -// effective query position the caller must then pass is `(nsel - 1) * ratio + pos % ratio`. +// Selection is a four-digit radix select, not a sort: attention is a softmax over a set, so table +// order within the set is irrelevant. The set is exact and deterministic: ties break to the lower +// block index by prefix count, never by atomic completion order. // -// SELECTION IS A FOUR-DIGIT RADIX SELECT, not a sort and not a threshold search. A sort of 65536 -// scores a query a layer a step is not affordable and is not needed -- attention is a softmax over -// a SET, so the order within the table does not matter. What does matter is that the set is -// EXACT and DETERMINISTIC: ties break to the lower block index through a prefix count, never -// through the order atomics happen to complete in, because this tree compares generated text -// across builds byte for byte. -// -// Returns a negative code rather than throwing, for the reason given in r4d_gemm_fp8a8.hip. +// Returns a RAD status rather than throwing, for the reason given in r4d_gemm_fp8a8.hip. #include "r4d.h" #include "r4d_args.h" #include "r4d_emit.h" +#include "r4d_launch.h" // R4D_DYN_LDS #include "r4d_common.h" // the DPP wave scans #include @@ -43,28 +34,23 @@ constexpr int kThreads = 256; constexpr int kWave = 32; constexpr int kWaves = kThreads / kWave; constexpr int kBins = 256; -/* ONE THREAD A BIN, which is what lets the threshold scan below be parallel at all. */ +/* One thread per bin for the parallel threshold scan. */ static_assert(kThreads == kBins, "the bin scan gives one bin to one thread"); -/* THE KEY CACHE, AND WHY IT IS GATED ON THE LAUNCH WIDTH RATHER THAN ALWAYS ON. +/* Key cache, gated on the launch width. * - * Five passes read every key -- four radix digits and the emit -- and on the same workgroup, so - * at decode this kernel is one workgroup on the whole device making the same 5277 dependent - * loads five times. Staging the keys in LDS once makes four of those five passes an LDS read, - * worth about 25% of the kernel at n = 5277, topk = 512. + * Five passes read every key (four radix digits and the emit). Staging the keys in LDS once makes + * four of them LDS reads, ~25% faster at decode (n = 5277, topk = 512). * - * IT IS A LOSS AT PREFILL AND THE REASON IS OCCUPANCY, NOT THE COPY. 32 KiB a workgroup is half - * the per-workgroup LDS budget, so a prefill chunk's 2048 workgroups stop fitting side by side: - * at M=2048 the cache costs about 7%, and M=128 is already the wrong - * side. The crossover sits between 96 and 128 workgroups on a 64-CU part -- about where a - * workgroup stops having a CU to itself -- so the gate is the launch width and 64 leaves margin. - * Decode is M = n_seq and prefill is M = the chunk; nothing real lands in between, and a MIXED - * step is wide and correctly takes the uncached path. */ + * At prefill it costs occupancy: 32 KiB is half the per-workgroup LDS budget, and at M=2048 the + * cache is ~7% slower. The crossover is 96-128 workgroups on a 64-CU GPU, so the gate is M <= 64. + * Decode M is n_seq and prefill M is the chunk size; mixed steps are wide and take the uncached + * path. */ constexpr int kLdsCap = 8192; /* keys, so 32 KiB of dynamic LDS */ constexpr int kCacheMaxM = 64; /* launch width above which the cache costs more than it saves */ -/* Clamped to what the device will actually grant a workgroup, minus the static shared above. A - * part with a smaller LDS gets a smaller cache and deeper queries simply take the global path. */ +/* Cache size clamped to the device's per-workgroup LDS minus the static shared memory; deeper + * queries take the global path. */ static inline int lds_cap_of() { static const int v = [] { int dev = 0; @@ -79,30 +65,21 @@ static inline int lds_cap_of() { return v; } -/* The gate is the launch width, for the occupancy reason in the note above. */ -static inline int cache_max_m() { return kCacheMaxM; } - -/* THE ORDER KEY. A score is a sum of relus over a positive constant, so it is >= 0 or -inf, and - * for non-negative floats the IEEE bit pattern is monotonic as an unsigned. `+1` keeps a live - * score of exactly zero -- every head vetoed the block -- above the 0 that means "no block here", - * which is the distinction the scorer's -inf padding exists to make. */ +/* Order key. Scores are >= 0 or -inf, and non-negative float bit patterns order as unsigned. + * `+1` keeps a live score of exactly zero above key 0, which means "no block". The clamp is a + * select, not fmaxf: fmaxf(-0.0f, 0.0f) may return -0.0f, whose sign bit would rank it above + * every positive score. */ __device__ __forceinline__ uint32_t keyof(float v, int page) { if (page < 0 || !(v > -1e30f)) return 0u; - return __float_as_uint(fmaxf(v, 0.0f)) + 1u; + return __float_as_uint(v > 0.0f ? v : 0.0f) + 1u; } -/* THE SCANS RUN IN REGISTERS, ON DPP, rather than as LDS round trips between barriers. +/* Scans run in registers on DPP (five steps per wave, r4d_common.h); only wave totals go through + * LDS, instead of step-doubling LDS rounds with barriers that wait on up to 32 waves. * - * In LDS the bin suffix scan is eight step-doubling rounds with two barriers each, and the - * per-wave count prefix a serial walk over up to 32 LDS words, both once per radix digit or once - * per 256 candidates, on workgroups of up to 1024 threads, where every barrier waits for - * thirty-two waves. The merge is one workgroup a query, so those barriers and walks would be most - * of what it does. A wave's 32 values scan in five DPP steps -- row_shr or row_shl within each row - * of sixteen, then one readlane across the two rows (r4d_common.h) -- and only the waves' totals - * need LDS at all. The sums are of integers, so either form gives the same answer. */ -/* suf[b] = the sum of hist[i] over i >= b, for all kBins bins: each wave's 32 bins by a suffix - * scan in registers, then the totals of the waves above it. Two barriers. The caller has a barrier - * between the histogram and this, and `wt` holds kBins / 32 words nothing else is using. */ + * suf[b] = sum of hist[i] over i >= b for all kBins bins: a per-wave suffix scan in registers, + * plus the totals of the waves above. Two barriers. The caller has a barrier between the + * histogram and this; `wt` is kBins / 32 free words. */ template __device__ __forceinline__ void bin_suffix(const uint32_t* hist, uint32_t* suf, uint32_t* wt) { static_assert(NT >= kBins && kBins % kWave == 0, "the bins are whole waves of the workgroup"); @@ -121,8 +98,8 @@ __device__ __forceinline__ void bin_suffix(const uint32_t* hist, uint32_t* suf, __syncthreads(); } -/* How many of the workgroup's NW wave counts come before this wave, and all of them together, from - * `wsum` after the barrier that published them: every wave scans the NW words in its own lanes. */ +/* Sum of the wave counts before this wave, and the total, from `wsum` (published before a + * barrier); each wave scans the NW words in its own lanes. */ template __device__ __forceinline__ void counts_before(const uint32_t* wsum, int lane, int wave, uint32_t* before, uint32_t* total) { @@ -134,14 +111,10 @@ __device__ __forceinline__ void counts_before(const uint32_t* wsum, int lane, in *total = (uint32_t)__builtin_amdgcn_readlane((int)inc, NW - 1); } - -/* `m` IS A QUERY AND NOT A SEQUENCE -- see the same note in r4d_qsa_score_bf16.hip. The block - * table and the complete-block count belong to the SEQUENCE, `cu` says which one, and the - * per-query bound is `(pos + 1) / ratio`: block `b` is entirely in this query's past exactly when - * `b * ratio + ratio - 1 <= pos`. At decode the two agree by construction -- a sequence's complete - * count IS its single query's -- so the per-query bound changes nothing there, to the bit. Any - * sparse-against-dense comparison below the exactness bound therefore tests the SELECTION and not - * the arithmetic it sits on. */ +/* `m` is a query row, not a sequence (see r4d_qsa_score_bf16.hip); `cu` maps it to its sequence's + * block table and complete-block count. The per-query bound is (pos + 1) / ratio: block b is + * entirely in the query's past when b * ratio + ratio - 1 <= pos. At decode this equals the + * sequence's complete count. */ __global__ __launch_bounds__(kThreads) void qsa_select_kernel( const float* __restrict__ score, const int32_t* __restrict__ bt, const int32_t* __restrict__ nc, const int32_t* __restrict__ pos, @@ -154,7 +127,7 @@ __global__ __launch_bounds__(kThreads) void qsa_select_kernel( __shared__ uint32_t wsum[kWaves]; __shared__ uint32_t sh_T, sh_need, sh_out; __shared__ int sh_seq; - extern __shared__ uint32_t sh_key[]; /* `cap` keys, or nothing when the gate said no */ + R4D_DYN_LDS(uint32_t, sh_key); /* `cap` keys, or nothing when the gate said no */ const int m = blockIdx.x; const int t = threadIdx.x; @@ -175,7 +148,7 @@ __global__ __launch_bounds__(kThreads) void qsa_select_kernel( const int32_t* tb = bt + (size_t)seq * t_ld; int32_t* ou = sel + (size_t)m * o_ld; - /* ---- the key cache. One global pass with nothing dependent in it, in place of four. */ + /* ---- the key cache: one global pass instead of four. */ const bool cached = n <= cap; if (cached) { for (int b0 = 0; b0 < n; b0 += kThreads) { @@ -185,8 +158,8 @@ __global__ __launch_bounds__(kThreads) void qsa_select_kernel( __syncthreads(); } - /* ---- the threshold. `T` is the exact key of the topk-th largest and `need` how many entries - * hold it, which together define the set without ever ordering it. */ + /* ---- the threshold: T is the exact key of the topk-th largest and `need` how many entries + * equal to T to take; together they define the set without ordering it. */ uint32_t T = 0, need = 0; if (n > topk) { uint32_t fixed = 0, want = (uint32_t)topk; @@ -200,21 +173,13 @@ __global__ __launch_bounds__(kThreads) void qsa_select_kernel( atomicAdd(&hist[(k >> shift) & 255u], 1u); } __syncthreads(); - /* ---- the digit, from a SUFFIX SCAN over the bins and not a walk down them. + /* ---- the digit: the largest bin whose suffix sum reaches `want`, found by a parallel + * suffix scan instead of a serial walk from bin 255 (real scores occupy a few adjacent + * exponents, so the walk mostly crosses empty bins). About a third faster at decode, + * and faster at prefill too. * - * The answer is the largest bin whose suffix sum still reaches `want`; a serial - * form walks from 255 until it does. Real scores are a sum of four relus over a - * positive constant, so they occupy a handful of adjacent exponents and that walk - * spends two hundred of its iterations on empty bins ABOVE them, one thread, four - * times a query. Eight parallel steps instead is worth about a third of the kernel at - * decode, and it wins at PREFILL too (M=2048: 158 us against 289), which the key cache - * above does not. - * - * Bit-identical to the walk by construction. `suf` is non-increasing in the index, so - * `suf[t] >= want && suf[t+1] < want` holds for exactly one bin and it is the one the - * walk stops at, with `run` its `suf[t+1]`. The fallback covers the case where the - * walk reaches the bottom without ever arriving: fewer live keys than `want`, which - * happens whenever enough of the table is padding. */ + * suf is non-increasing, so suf[t] >= want && suf[t+1] < want holds for exactly one + * bin. The t == 0 preset covers fewer live keys than `want` (enough padding). */ bin_suffix(hist, suf, wsum); if (t == 0) { sh_T = fixed; sh_need = want - suf[0]; } __syncthreads(); @@ -226,8 +191,15 @@ __global__ __launch_bounds__(kThreads) void qsa_select_kernel( } } __syncthreads(); - fixed = sh_T; + /* topk or fewer live keys: every one is taken, in block order, as libref takes them, + * and T = 0 says so. Only the first digit counts every live key (a later one counts + * one bin, which holds at least `want`, often exactly), and no later digit may run: + * it would narrow into bin 0, where a score of exactly zero lives, and turn those + * keys into a threshold to tie on. */ + const bool every = shift == 24 && suf[0] <= want; + fixed = every ? 0u : sh_T; want = sh_need; + if (every) break; } T = fixed; need = want; } @@ -235,10 +207,9 @@ __global__ __launch_bounds__(kThreads) void qsa_select_kernel( if (t == 0) sh_out = 0; __syncthreads(); - /* ---- the emit. Two predicates: strictly above the threshold (always in) and exactly at it - * (in while slots remain, LOWEST BLOCK INDEX FIRST). Both are placed by a workgroup prefix - * count over chunks, so a block's slot depends only on how many qualifying blocks precede it - * -- never on the order the hardware got there. */ + /* ---- the emit. Entries strictly above the threshold are always in; entries equal to it are + * in while slots remain, lowest block index first. Slots come from a workgroup prefix count, + * so a block's slot depends only on how many qualifying blocks precede it. */ uint32_t taken_eq = 0; for (int b0 = 0; b0 < n; b0 += kThreads) { const int b = b0 + t; @@ -247,8 +218,8 @@ __global__ __launch_bounds__(kThreads) void qsa_select_kernel( const bool hi = k != 0u && (n <= topk || k > T); const bool eq = k != 0u && n > topk && k == T; - /* Two scans in one pass: the high entries take their slots from the running output - * count, the tie entries from the count of ties already taken. */ + /* High entries take slots from the running output count, ties from the count of ties + * already taken. */ const unsigned long long mh = __ballot(hi), me = __ballot(eq); const uint32_t rh = (uint32_t)__popcll(mh & ((1ull << lane) - 1ull)); const uint32_t re = (uint32_t)__popcll(me & ((1ull << lane) - 1ull)); @@ -281,64 +252,50 @@ __global__ __launch_bounds__(kThreads) void qsa_select_kernel( __syncthreads(); } - /* ---- the partial page, appended last. `bt[n]` is the page the query itself lives in, and - * there is one exactly when the query does NOT sit on the last token of a block. + /* ---- the partial page, appended last. bt[n] is the page the query lives in, present exactly + * when the query is not on the last token of a block. * - * THE `(p + 1) % ratio` TEST IS WHAT KEEPS PREFILL CAUSAL, and at decode it is invisible. A - * decode query on a block boundary has `n == nc`, and `bt[nc]` is the page after the - * sequence's last, which the KV manager leaves -1 -- so a bare `part >= 0` test is right at - * decode and only there. Mid-CHUNK the same query has later tokens of the - * same chunk already stored in `bt[n]`, which is a LIVE page entirely in its future, and - * `seqused` would then cover all `ratio` of them. The condition is the query's position, not - * whether a page happens to be allocated. */ + * The `(p + 1) % ratio` test keeps prefill causal: mid-chunk, a query on a block boundary may + * find bt[n] already holding later tokens of the same chunk (a live page entirely in its + * future). At decode bt[nc] is -1 there, but the test must use the position, not whether a + * page is allocated. */ if (t == 0) { - uint32_t out = n <= topk ? sh_out : (uint32_t)topk; + /* Above topk blocks the table is full (ties fill it), unless topk or fewer are live: + * then T is 0, every live key was emitted, and the slots past them hold nothing. */ + uint32_t out = (n <= topk || T == 0u) ? sh_out : (uint32_t)topk; const int32_t part = (n < nb && (p + 1) % ratio != 0) ? tb[n] : -1; if (part >= 0) ou[out++] = part; for (uint32_t i = out; i < (uint32_t)(topk + 1); ++i) ou[i] = -1; nsel[m] = (int32_t)out; - /* THE ATTENTION'S CAUSAL BOUND, AND IT IS WHY THIS OP EXISTS IN THE SHAPE IT DOES. + /* The attention's causal bound. attn_paged takes the block table and seqused_k as + * ordinary operands, so QSA issues the same op with `sel` as the table and this as the + * length; no new attention kernel is needed. * - * `attn_paged` takes the block table and `seqused_k` as ORDINARY OPERANDS -- the - * architecture already reads them off the KV group batch and passes them -- so QSA needs - * no new attention kernel and no engine change: the same op is issued with `sel` in place - * of the sequence's table and this number in place of its length. - * - * The flat KV the attention then walks is `out` pages of `ratio`, and the query sits at - * flat index `(out - 1) * ratio + pos % ratio` because the partial page is LAST. One - * formula covers both cases: with a tail the query is inside that last page, and without - * one `pos % ratio` is `ratio - 1` and the expression collapses to `out * ratio`, which - * is every selected page fully visible -- correct, because a COMPLETE page is entirely in - * the query's past by construction. */ + * The attention walks `out` pages of `ratio`, with the query at flat index + * (out - 1) * ratio + pos % ratio (partial page last). Without a partial page + * pos % ratio = ratio - 1, so this is out * ratio: every complete page fully visible. */ const int32_t su = (int32_t)((out == 0) ? 0 : (out - 1) * (uint32_t)ratio + (uint32_t)(p % ratio) + 1u); if (seqused) seqused[m] = su; } } - -/* ===================================================== the WIDE-LAUNCH path, for a prefill chunk +/* ===================================================== the wide-launch path, for a prefill chunk * - * AT A PREFILL CHUNK THE KERNEL ABOVE READS EVERY KEY FROM GLOBAL MEMORY FIVE TIMES -- four radix - * digits and the emit, a score and a page id a block each time; the key cache is off for the - * occupancy reason at kCacheMaxM -- and its first digit is the key's top EIGHT bits, which for a - * score is its exponent. Real scores sit in a handful of adjacent exponents, so that pass puts - * nearly every key into a few LDS bins one atomic at a time and settles almost nothing. At 80K of - * context, 20K blocks a query, that form costs 1.43 ms a call and 5% of a prefill chunk, and it - * grows with the context. + * Without the key cache the kernel above reads every key from global memory five times, and its + * first 8-bit digit is the score's exponent: real scores share a few exponents, so that pass + * funnels nearly every key into a few LDS bins and settles little (1.43 ms per call at 80K + * context, growing with context). * - * So a wide launch takes the top TWELVE bits first -- the exponent and four bits of mantissa, 4096 - * bins -- which spreads the atomics and leaves one bin holding the threshold. A second pass copies - * that bin's keys into LDS, over the bins the first digit no longer needs, and the other three - * digits run on them there; the emit is the third and last pass over global memory -- or, when - * the bin is small enough to keep its blocks too (kMergeCand), part of the second, which is then - * the last. A bin larger than the LDS list runs those digits over global memory instead, as the - * kernel above does. + * The wide path takes the top twelve bits first (exponent plus four mantissa bits, 4096 bins), + * spreading the atomics and isolating one bin holding the threshold. A second pass copies that + * bin's keys into LDS (over first-digit bins no longer needed), the remaining digits run there, + * and a third pass emits; when the bin also fits with its block indices (kMergeCand), the second + * pass is the last. A bin too large for LDS runs those digits over global memory. * - * THE SAME TABLE, BIT FOR BIT. The threshold is a number, not a procedure -- the topk-th largest - * key, and how many entries equal to it to take -- so any digit split finds the same one; and the - * emit is the kernel above's, line for line, so the same entries land in the same slots. - * r4d_selftest compares the two launches' tables byte for byte. */ + * The table is bit-identical to the kernel above: the threshold (topk-th largest key and the tie + * count) does not depend on the digit split, and the emit is the same. r4d_selftest compares the + * two byte for byte. */ constexpr int kWideBits = 12; /* the first digit */ constexpr int kWideShift = 31 - kWideBits; /* a key's bit 31 is clear: see keyof */ constexpr int kWideBins = 1 << kWideBits; @@ -346,15 +303,11 @@ constexpr int kWideCand = kWideBins - kBins; /* keys the second pass may constexpr int kWidePer = kWideBins / kThreads; /* first-digit bins a thread scans */ static_assert(kWideBins % kThreads == 0 && kWideCand > 0, "the first digit's bins tile the block"); -/* THE SECOND PASS IS ALSO THE EMIT when the threshold's bin is small enough to hold with its block - * indices (at 150K of context and a 2048-query chunk, 1179 us a call against 1800): the pass over - * global memory compacts, in block order, every key ABOVE that bin (all of them are taken, and - * there are fewer than topk) and every key IN it with its block, so once the later digits have - * fixed the threshold the table is a merge of the two lists by block index and the third pass - * over global memory is not needed. Same entries in the same slots: the taken keys above the - * threshold in block order, the ties after them in block order. The three lists share the first - * digit's bins, so the LDS and the occupancy are the three-pass form's; a larger bin, or a wider - * topk, takes the three-pass form. */ +/* Merged form: when the threshold's bin fits with its block indices, the second pass compacts, + * in block order, every block above that bin (all taken; fewer than topk) and every key in it with + * its block. Once the threshold is fixed, the table is a merge of the two lists by block index, + * with no third pass (1179 vs 1800 us per call at 150K context, 2048-query chunk). Same slots as + * the three-pass form; the lists reuse the first digit's bins, so LDS use is unchanged. */ constexpr int kMergeAbove = 512; /* keys above the threshold's bin */ constexpr int kMergeCand = (kWideCand - kMergeAbove) / 2; /* keys, and blocks, in it */ static_assert(kMergeCand > 0, "room for the bin's keys and their blocks"); @@ -368,30 +321,26 @@ __device__ __forceinline__ uint32_t lower_bound_u32(const uint32_t* v, uint32_t return lo; } -/* THE FIRST PASS IS A SAMPLE when the history is long (at 150K of context a query has 37.5K keys: - * 0.67 ms a layer this way, 1.2 ms as two passes over them): kSampRuns runs of kSampRun - * consecutive keys spread over the history bound the threshold from below, one pass collects every - * key at or above that bound with its block in block order, and the exact select and the emit run - * on that list in LDS. EXACT BY CONSTRUCTION, not by estimate: when at least topk keys clear the - * bound, the threshold is at or above it, so every taken key -- ties included -- is in the list, in - * block order, and lands in the slot the full passes give it. When fewer clear it, or more than the - * list holds, the kernel takes the two-pass form below; the sample only decides which. +/* Sampled first pass for long histories (37.5K keys at 150K context: 0.67 ms vs 1.2 ms per + * layer). kSampRuns runs of kSampRun consecutive keys bound the threshold from below; one pass + * collects every key at or above the bound with its block, in block order, and the exact select + * and emit run on that list in LDS. Exact, not estimated: if at least topk keys clear the bound, + * every taken key (ties included) is in the list and lands in the same slot. If fewer clear it, or + * the list overflows, the kernel falls back to the two-pass form. * - * Runs rather than a stride, because a strided sample touches every cache line of the scores and - * saves nothing. The bound is the sample's (2 topk S / n + 8)-th largest, about twice the - * expected count, so the list is ~1000 of kSampCap and short of topk rarely. */ + * Runs, not a stride, since a strided sample touches every cache line. The bound is the sample's + * (2 topk S / n + 8)-th largest, about twice the expected count (~1000 entries of kSampCap). */ constexpr int kSampRun = 32; constexpr int kSampRuns = 64; constexpr int kSamp = kSampRun * kSampRuns; /* 2048 keys */ -/* Below it the two passes win: at a 2048-query chunk 174 against 196 us at 5000 blocks, and the - * sample 221 against 243 at 7500. */ +/* Below this the two-pass form wins (2048-query chunk: 174 vs 196 us at 5000 blocks; the sample + * wins 221 vs 243 at 7500). */ constexpr int kSampMinN = 3 * kSamp; constexpr int kSampCap = (kWideBins - kBins) / 2; /* list entries: a key and a block */ static_assert(kSamp + kBins <= kWideBins, "the sample and its histogram share the bins"); -/* The `want`-th largest of `cnt` keys in LDS, and how many entries equal to it to take: the - * single-workgroup kernel's four eight-bit digits over a list. Fewer than `want` live keys leave - * the threshold at 0, which every live key exceeds. */ +/* The `want`-th largest of `cnt` LDS keys and the tie count, by the single-workgroup kernel's + * four 8-bit digits. `want` or fewer live keys leave the threshold at 0. */ __device__ __forceinline__ void lds_kth(const uint32_t* keys, int cnt, uint32_t want, uint32_t* hist, uint32_t* suf, uint32_t* wsum, uint32_t* sh_T, uint32_t* sh_need, uint32_t* T, @@ -418,8 +367,11 @@ __device__ __forceinline__ void lds_kth(const uint32_t* keys, int cnt, uint32_t } } __syncthreads(); - fixed = *sh_T; + /* `want` or fewer live keys stop at T = 0, as in the single-workgroup kernel. */ + const bool every = shift == 24 && suf[0] <= want; + fixed = every ? 0u : *sh_T; want = *sh_need; + if (every) break; } *T = fixed; *need = want; @@ -432,8 +384,8 @@ __global__ __launch_bounds__(kThreads) void qsa_select_wide_kernel( int32_t* __restrict__ sel, int32_t* __restrict__ nsel, int32_t* __restrict__ seqused, int nb, int topk, int ratio, int nseq, int s_ld, int t_ld, int o_ld) { - /* The first digit's 4096 bins; after it, bins [0, kBins) are the later digits' histogram and - * the rest hold the collected keys. */ + /* The first digit's 4096 bins; afterwards [0, kBins) is the later digits' histogram and the + * rest holds the collected keys. */ __shared__ uint32_t wide[kWideBins]; __shared__ uint32_t suf[kBins]; __shared__ uint32_t wsum[kWaves], wsum2[kWaves]; @@ -441,8 +393,7 @@ __global__ __launch_bounds__(kThreads) void qsa_select_wide_kernel( __shared__ int sh_seq; uint32_t* const hist = wide; uint32_t* const cand = wide + kBins; - /* The merged form's lists, over the same words: the bin's keys, their blocks, and the blocks - * above the bin. */ + /* Merged-form lists over the same words: the bin's keys, their blocks, and the blocks above. */ uint32_t* const mkey = wide + kBins; uint32_t* const mblk = mkey + kMergeCand; uint32_t* const mabv = mblk + kMergeCand; @@ -478,17 +429,16 @@ __global__ __launch_bounds__(kThreads) void qsa_select_wide_kernel( samp[i] = keyof(sc[b], tb[b]); } __syncthreads(); - uint32_t m = (uint32_t)(((uint64_t)topk * 2u * kSamp + (uint64_t)n - 1u) / (uint64_t)n) + 8u; - if (m > (uint32_t)kSamp) m = (uint32_t)kSamp; + uint32_t ms = (uint32_t)(((uint64_t)topk * 2u * kSamp + (uint64_t)n - 1u) / (uint64_t)n) + 8u; + if (ms > (uint32_t)kSamp) ms = (uint32_t)kSamp; uint32_t lo, lo_need; - lds_kth(samp, kSamp, m, wide + kSamp, suf, wsum, &sh_T, &sh_need, &lo, &lo_need); + lds_kth(samp, kSamp, ms, wide + kSamp, suf, wsum, &sh_T, &sh_need, &lo, &lo_need); /* ---- one pass: every key at or above the bound, with its block, in block order. */ uint32_t* const lkey = wide + kBins; uint32_t* const lblk = lkey + kSampCap; - /* EIGHT CONSECUTIVE KEYS A THREAD, so a pass is a vector load stream with one workgroup - * prefix -- two barriers -- every 2048 keys rather than every 256. Block order holds: a - * thread's keys are consecutive and the threads are in order. */ + /* Eight consecutive keys per thread: vector loads and one workgroup prefix per 2048 keys + * instead of per 256. Block order holds (consecutive keys, threads in order). */ constexpr int kPer = 8; const bool vec = (((uintptr_t)sc | (uintptr_t)tb) & 15u) == 0u; uint32_t cnt = 0; @@ -527,7 +477,8 @@ __global__ __launch_bounds__(kThreads) void qsa_select_wide_kernel( } /* ---- the table from the list, when the list holds the answer. */ - if (cnt >= (uint32_t)topk && cnt <= (uint32_t)kSampCap) { + /* More than topk: exactly topk could be every live key, which takes no threshold. */ + if (cnt > (uint32_t)topk && cnt <= (uint32_t)kSampCap) { lds_kth(lkey, (int)cnt, (uint32_t)topk, hist, suf, wsum, &sh_T, &sh_need, &T, &need); uint32_t hbase = 0, ebase = 0; for (uint32_t i0 = 0; i0 < cnt; i0 += kThreads) { @@ -569,37 +520,41 @@ __global__ __launch_bounds__(kThreads) void qsa_select_wide_kernel( __syncthreads(); /* The bin holding the topk-th largest key: the largest bin whose suffix count reaches - * `topk`. A thread owns kWidePer consecutive bins; the counts above its range come from a - * suffix scan over the threads, and it walks its own bins down from there. None qualifies - * when fewer than topk keys are live, and then every live key is in: T stays 0 and `need` - * is what is left, as in the kernel above. */ + * topk. A thread owns kWidePer consecutive bins, gets the count above them by a suffix + * scan, and walks its own bins down. With topk or fewer keys live there is no search: + * T stays 0 and every live key is taken, in block order, as libref takes them. */ uint32_t loc[kWidePer], mine = 0; #pragma unroll for (int j = 0; j < kWidePer; ++j) { loc[j] = wide[t * kWidePer + j]; mine += loc[j]; } const uint32_t x = r4d_wave_suffix_u32(mine, lane); if (lane == 0) wsum[wave] = x; __syncthreads(); - uint32_t above = 0; - for (int w = wave + 1; w < kWaves; ++w) above += wsum[w]; + uint32_t above = 0, live = 0; + for (int w = 0; w < kWaves; ++w) { + live += wsum[w]; + if (w > wave) above += wsum[w]; + } uint32_t run = x - mine + above; - if (t == 0) { sh_bin = 0xFFFFFFFFu; sh_T = 0; sh_need = (uint32_t)topk - (run + mine); } + if (t == 0) { sh_bin = 0xFFFFFFFFu; sh_T = 0; sh_need = 0; } __syncthreads(); + if (live > (uint32_t)topk) { #pragma unroll - for (int j = kWidePer - 1; j >= 0; --j) { - if (run < (uint32_t)topk && run + loc[j] >= (uint32_t)topk) { - sh_bin = (uint32_t)(t * kWidePer + j); - sh_need = (uint32_t)topk - run; - sh_cnt = loc[j]; + for (int j = kWidePer - 1; j >= 0; --j) { + if (run < (uint32_t)topk && run + loc[j] >= (uint32_t)topk) { + sh_bin = (uint32_t)(t * kWidePer + j); + sh_need = (uint32_t)topk - run; + sh_cnt = loc[j]; + } + run += loc[j]; } - run += loc[j]; } __syncthreads(); const uint32_t B = sh_bin; if (B != 0xFFFFFFFFu) { uint32_t fixed = B << kWideShift, want = sh_need; - /* ---- the threshold's bin, into LDS when it fits: with its blocks and the keys above - * it, in block order, when those fit too (the merged form); else its keys alone. */ + /* ---- the threshold's bin into LDS when it fits: with its blocks and the blocks above, + * in block order, when those fit too (merged form); else its keys alone. */ merged = sh_cnt <= (uint32_t)kMergeCand && topk <= kMergeAbove; const bool inlds = sh_cnt <= (uint32_t)kWideCand; __syncthreads(); @@ -679,11 +634,10 @@ __global__ __launch_bounds__(kThreads) void qsa_select_wide_kernel( T = fixed; need = want; if (merged) { - /* ---- the emit, from the lists. A key of the bin above the threshold takes the - * slot after every taken key before its block: the bin's own before it, then the - * above-bin keys before its block, found by search. Its running count replaces - * its key, and an above-bin key finds its slot the same way from the other side. - * The ties fill from topk - need, in block order. */ + /* ---- emit from the lists. An in-bin key above the threshold takes the slot after + * every taken key before its block: in-bin ones by prefix count, above-bin ones by + * binary search. Its running count then replaces its key so above-bin keys can find + * their slots the same way. Ties fill from topk - need, in block order. */ const uint32_t nin = (uint32_t)ncand; uint32_t hbase = 0, ebase = 0; for (uint32_t i0 = 0; i0 < nin; i0 += kThreads) { @@ -728,7 +682,7 @@ __global__ __launch_bounds__(kThreads) void qsa_select_wide_kernel( if (t == 0) sh_out = 0; __syncthreads(); - /* ---- the emit, the kernel above's line for line. */ + /* ---- the emit, identical to the kernel above. */ uint32_t taken_eq = 0; for (int b0 = 0; b0 < ((merged || sampled) ? 0 : n); b0 += kThreads) { const int b = b0 + t; @@ -769,9 +723,9 @@ __global__ __launch_bounds__(kThreads) void qsa_select_wide_kernel( __syncthreads(); } - /* ---- the partial page, appended last: the kernel above's rule. */ + /* ---- the partial page, appended last, as above. */ if (t == 0) { - uint32_t out = n <= topk ? sh_out : (uint32_t)topk; + uint32_t out = (n <= topk || T == 0u) ? sh_out : (uint32_t)topk; const int32_t part = (n < nb && (p + 1) % ratio != 0) ? tb[n] : -1; if (part >= 0) ou[out++] = part; for (uint32_t i = out; i < (uint32_t)(topk + 1); ++i) ou[i] = -1; @@ -782,59 +736,43 @@ __global__ __launch_bounds__(kThreads) void qsa_select_wide_kernel( } } -/* THE SELECTION'S FORM, pinned for a test: 0 the launcher's rule, 1 the single-workgroup kernel, - * 2 the wide-launch kernel. The split path is its own rule and neither pin touches it. */ +/* Form override for tests: 0 = automatic, 1 = single-workgroup kernel, 2 = wide kernel. Does not + * affect the split path. */ static int g_qsa_select_form = 0; -/* ===================================================== the split path, for a DECODE-shaped launch +/* ===================================================== the split path, for a decode-shaped launch * - * ONE WORKGROUP A QUERY IS SIX PERCENT OF THE DEVICE, and at length that is the whole kernel. The - * grid above is `M` and nothing else, so a decode step runs `1 + n_spec` workgroups -- four at the - * shipped depth -- each walking the entire block list five times. At the deployment's geometry - * (topk 512, ratio 4) its cost barely moves from M=1 to M=8, around 255-285 us either way, which - * is the signature of a kernel that is one workgroup deep however wide the batch is. At 200K of - * context that is ~257 us a layer a step, and sixteen such layers make it 4.1 ms. + * One workgroup per query leaves most of the GPU idle at decode (1 + n_spec workgroups, each + * walking the whole block list five times; ~257 us per layer per step at 200K context). * - * A CHUNK'S LOCAL TOP-K CONTAINS EVERY GLOBAL TOP-K MEMBER OF THAT CHUNK, so the block list splits - * with nothing shared and the answer is still EXACT. Suppose a block is in the global top-k but not - * in its own chunk's: then k blocks of that chunk outrank it, and a block that outranks it in the - * chunk outranks it globally -- so k blocks outrank it globally and it was not in the global top-k. - * The order has to be the same TOTAL order on both sides for that to hold, and it is: key - * descending, then block index ascending, which is what the emit below builds by prefix count. + * A chunk's local top-k contains every global top-k member of that chunk, so the block list can + * be split exactly: if a block were in the global top-k but not its chunk's, k blocks of the chunk + * would outrank it, hence k blocks globally. This needs the same total order on both sides: key + * descending, then block index ascending, as the emit builds by prefix count. * - * So: `kParW` chunks a query find their own top-k in LDS, and one workgroup merges at most - * `kParW * topk` candidates -- 6656 at the deployment's shape against 50000 -- and emits. The - * merge's input is chunk-ordered and each chunk's list is block-ordered, so the concatenation is - * block-ordered and the tie rule needs no sort. + * So up to kParWMax chunks per query find their local top-k in LDS, and one workgroup per query + * merges the candidates and emits. Chunk lists are block-ordered and concatenated in chunk order, + * so the tie rule needs no sort. The merge is not split further: its input is already small, and + * splitting it would need a global prefix (two more kernels and dispatch gaps) for ~4% of the cost. * - * WHY NOT ALSO SPLIT THE MERGE: it reads a candidate list that is already small enough to stage, - * and a second split would need a global prefix over chunk counts to keep the tie rule exact -- - * two more kernels and two more dispatch gaps (2.8 us each on this part) for a pass that costs - * about 4% of what the unsplit kernel does. - * - * The path is DECODE-SHAPED and says so: above `kParM` query rows the grid is wide enough on its - * own and the single-workgroup kernel above is what runs. A prefill chunk is 512 queries. */ + * Above kParM query rows the grid is wide enough and the single-workgroup kernel runs. */ constexpr int kParM = 32; /* query rows the split path serves; a prefill chunk is wider */ constexpr int kParWMax = 16; /* chunks a query, and what the scratch is sized for */ constexpr int kParCap = 8192; /* keys a chunk may stage: 32 KiB, the same budget as above */ +/* Set in a chunk's count when the chunk had more than topk live keys: the merge then knows the + * whole list has more than topk, which the candidate count alone cannot tell at exactly topk. */ +constexpr int32_t kParOver = 1 << 30; -/* THE MERGE IS WIDER THAN EVERYTHING ELSE, because it is the one kernel here with no blocks to - * spare. It runs one workgroup a query -- four at the deployment's decode shape -- so it occupies - * four CUs of sixty-four and the only parallelism available to it is INSIDE a workgroup. At 256 - * threads that is eight waves over a CU's four SIMDs, two apiece, which is not enough to hide an - * LDS round trip let alone a global one; at 1024 it is eight apiece. VGPR is 24, so occupancy is - * not the limit -- the workgroup size is. - * - * The bin scan does not widen with it (256 bins, one a thread) and `par_scan`'s count prefix is - * one wave's scan at any width, so neither of those is what the width buys; the wave count is. */ +/* The merge runs one workgroup per query (four at the decode shape), so its only parallelism is + * within the workgroup: 1024 threads give eight waves per SIMD instead of two at 256, enough to + * hide LDS and global latency (24 VGPRs, so occupancy is not the limit). The bin scan stays at + * 256 threads. */ constexpr int kMergeThreads = 1024; -/* The local pass has forty-eight workgroups at this shape and a CU each, so it is not starved of - * waves the way the merge is and takes a narrower block. */ +/* The local pass has many more workgroups (48 at the decode shape), so a narrower block. */ constexpr int kLocalThreads = 512; -/* How many chunks a block list of `nb` is cut into, and the cut is the same on both sides of the - * pair -- the merge indexes the scratch at a fixed `kParWMax` stride whatever this returns, so the - * two kernels agree by construction rather than by both recomputing it the same way. */ +/* Chunks for a block list of nb (at most kParWMax). Both kernels index the scratch at the fixed + * kParWMax stride, so they agree regardless of this value. */ static inline int par_chunks(long long nb) { long long w = (nb + 4095) / 4096; if (w < 1) w = 1; @@ -842,19 +780,20 @@ static inline int par_chunks(long long nb) { return (int)w; } -/* THE THRESHOLD, over keys already staged in LDS. Digit for digit the same four-pass radix and the - * same suffix scan the single-workgroup kernel above runs, so a split selection and an unsplit one - * are the same bits -- which is the property the whole path rests on. */ -/* TEMPLATED ON THE WORKGROUP WIDTH, because the merge wants to be wider than the bin count. +/* The threshold over keys staged in LDS: the same four-digit radix and suffix scan as the + * single-workgroup kernel, so split and unsplit selections are bit-identical. * - * The bin scan is still one bin to one thread and always will be -- it is a 256-entry suffix scan - * -- so above 256 threads the surplus has to sit the scan out. The guards are around the WORK and - * never around a `__syncthreads()`: a barrier reached by some threads of a block and not others is - * undefined, and the whole point of widening is that some threads have nothing to do here. */ + * `every_at_want`: `want` or fewer live keys are all taken (T = 0), as the single-workgroup + * kernel takes topk or fewer. The local pass sets it. The merge does not: its candidates can be + * exactly the top-k of a longer list, whose ties still go last, and it never has fewer. + * + * Templated on the workgroup width (the merge is wider than the bin count). Above 256 threads the + * surplus skips the bin scan; guards wrap the work, never a __syncthreads(). */ template __device__ __forceinline__ void radix_thresh(const uint32_t* __restrict__ key, int n, - uint32_t want, uint32_t* hist, uint32_t* suf, - uint32_t* wt, uint32_t* sh_T, uint32_t* sh_need) { + uint32_t want, bool every_at_want, uint32_t* hist, + uint32_t* suf, uint32_t* wt, uint32_t* sh_T, + uint32_t* sh_need) { const int t = (int)threadIdx.x; uint32_t fixed = 0; for (int shift = 24; shift >= 0; shift -= 8) { @@ -878,23 +817,23 @@ __device__ __forceinline__ void radix_thresh(const uint32_t* __restrict__ key, i } } __syncthreads(); + /* Only the first digit counts every live key (see the single-workgroup kernel). */ + if (every_at_want && shift == 24 && suf[0] <= want) { + if (t == 0) { *sh_T = 0u; *sh_need = 0u; } + __syncthreads(); + break; + } fixed = *sh_T; want = *sh_need; } } -/* THE QUALIFYING SET, BY PREFIX COUNT, IN TWO LAYOUTS -- and the second one is not a nicety. +/* The qualifying set by prefix count, in two layouts. * - * The single-workgroup kernel puts the entries strictly above the threshold at the FRONT of the - * output table and the ties at the BACK, because a selected set has no order. The attention that - * reads the table disagrees: it accumulates a softmax over the pages in table order, and float - * addition is not associative, so a permuted table is different BITS. This tree compares generated - * text across builds byte for byte, so the split path has to reproduce that layout exactly. - * - * The chunk pass wants the other one: its output is the merge's input and the merge's tie rule - * reads it in block order, so there a tie has to land in its block's place. Hence both prefixes - * are computed and the caller picks. Every count is a workgroup prefix over chunks of `kThreads`, - * so a candidate's slot depends only on how many candidates precede it, never on scheduling. */ + * The merge must reproduce the single-workgroup kernel's table exactly (entries above the + * threshold first, ties last): the attention sums pages in table order and float addition is not + * associative. The local pass instead writes in block order, since the merge's tie rule reads it + * that way. Slots come from workgroup prefix counts, never from scheduling. */ struct ParEmit { uint32_t* wsum; /* [kWaves] scratch for the wave prefix */ uint32_t* sh_hi; /* running count of entries above the threshold */ @@ -908,8 +847,8 @@ struct ParTake { uint32_t slot_hi, slot_ord, rank_eq; }; -/* One ballot, one wave prefix, one workgroup prefix -- the shape the loop below repeats three - * times. `*run` is the running total and is advanced by thread 0. */ +/* One ballot, one wave prefix, one workgroup prefix. `*run` is the running total, advanced by + * thread 0. */ template __device__ __forceinline__ uint32_t par_scan(ParEmit& e, bool p, int lane, int wave, uint32_t* run, uint32_t base0, uint32_t* total) { @@ -927,24 +866,10 @@ __device__ __forceinline__ uint32_t par_scan(ParEmit& e, bool p, int lane, int w return base + rk; } -/* WHICH SLOTS THIS CALLER ACTUALLY READS, as template parameters, because neither caller reads - * both and without them each pays for the other's. - * - * `par_scan` is not cheap: a ballot, two `__syncthreads()` and a scan of the wave counts. The emit - * calls it once per predicate per iteration of a loop that runs `tot/kThreads` times, so a scan - * nobody reads is a third of the emit. - * - * And a third of them go unread: the MERGE uses `slot_hi` and `rank_eq` and never touches - * `slot_ord`, while the LOCAL pass uses `slot_ord` and never touches `slot_hi`. Computing both - * unconditionally is expensive -- the emit is over half of the merge's time, and the threshold - * scan most of the rest. - * - * The branches are on template parameters, so they are resolved at compile time and every thread - * of the block takes the same path -- which is what makes a `__syncthreads()` inside them legal. - * The running counter a skipped scan would have advanced is the one its caller does not read. - * - * Bit-identical: the scans are independent of each other except that `take` needs `rank_eq`, and - * that ordering is kept. */ +/* WantHi / WantOrd select which slots are computed: each par_scan costs a ballot and two + * barriers, the merge reads only slot_hi and rank_eq, and the local pass only slot_ord. The + * branches are compile-time, so every thread takes the same path and the barriers inside are + * legal. `take` depends on rank_eq, which is always computed first. */ template __device__ __forceinline__ ParTake par_take(ParEmit& e, uint32_t k, int lane, int wave) { ParTake r{}; @@ -973,7 +898,7 @@ __global__ __launch_bounds__(kLocalThreads) void qsa_local_kernel( __shared__ uint32_t hist[kBins], suf[kBins], wsum[LT / kWave]; __shared__ uint32_t sh_T, sh_need, sh_hi, sh_ord; __shared__ int sh_seq; - extern __shared__ uint32_t sh_key[]; + R4D_DYN_LDS(uint32_t, sh_key); const int m = (int)blockIdx.y, c = (int)blockIdx.x; const int t = (int)threadIdx.x, lane = t & (kWave - 1), wave = t >> 5; @@ -1001,14 +926,15 @@ __global__ __launch_bounds__(kLocalThreads) void qsa_local_kernel( ParEmit e{ wsum, &sh_hi, &sh_ord, 0u, 0u, 0u, cn <= topk }; if (!e.all) { - radix_thresh(sh_key, cn, (uint32_t)topk, hist, suf, wsum, &sh_T, &sh_need); + radix_thresh(sh_key, cn, (uint32_t)topk, true, hist, suf, wsum, &sh_T, &sh_need); e.T = sh_T; e.need = sh_need; } + /* A threshold means more than topk live keys here, so more than topk in the whole list. */ + const bool over = !e.all && e.T != 0u; if (t == 0) { sh_hi = 0; sh_ord = 0; } __syncthreads(); - /* IN BLOCK ORDER, because this list is the merge's input and the merge breaks ties by block - * index. The output table's own layout is the merge's business. */ + /* In block order: the merge breaks ties by block index. */ uint32_t* dk = ck + (size_t)(m * kParWMax + c) * topk; int32_t* di = ci + (size_t)(m * kParWMax + c) * topk; for (int i0 = 0; i0 < cn; i0 += LT) { @@ -1017,20 +943,15 @@ __global__ __launch_bounds__(kLocalThreads) void qsa_local_kernel( const ParTake r = par_take(e, k, lane, wave); if (r.take && r.slot_ord < (uint32_t)topk) { dk[r.slot_ord] = k; - /* THE PAGE, NOT THE BLOCK INDEX, and the difference is which kernel pays for the - * lookup. Leaving it to the merge means resolving `tb[ci[...]]` there -- two DEPENDENT - * global loads for every candidate it takes -- on four workgroups, one a query, with - * nothing to hide the second round trip behind. Resolving it here costs the same load - * on FORTY-EIGHT workgroups, where there is. Nothing downstream wants the index: the - * merge's tie rule breaks on a candidate's position in the concatenated list, which is - * block-ordered by construction, and the index is never compared. A taken candidate - * has `k != 0`, which `keyof` only returns for a live page, so no dead page arrives - * here. */ + /* Store the page, not the block index: resolving it here spreads the dependent load + * over many workgroups instead of the merge's few. The merge breaks ties by list + * position (block-ordered), never by index. A taken candidate has k != 0, so its + * page is live. */ di[r.slot_ord] = tb[lo + i]; } } if (t == 0) cc[(size_t)m * kParWMax + c] = - (int32_t)(sh_ord < (uint32_t)topk ? sh_ord : (uint32_t)topk); + (int32_t)(sh_ord < (uint32_t)topk ? sh_ord : (uint32_t)topk) | (over ? kParOver : 0); } /* ---- pass two: merge the chunk lists and emit the page-id table. */ @@ -1044,9 +965,9 @@ __global__ __launch_bounds__(kMergeThreads) void qsa_merge_kernel( constexpr int NT = kMergeThreads; __shared__ uint32_t hist[kBins], suf[kBins], wsum[NT / kWave]; - __shared__ uint32_t sh_T, sh_need, sh_hi, sh_ord, sh_tot; + __shared__ uint32_t sh_T, sh_need, sh_hi, sh_ord, sh_tot, sh_over; __shared__ int sh_seq, sh_off[kParWMax + 1]; - extern __shared__ uint32_t sh_key[]; + R4D_DYN_LDS(uint32_t, sh_key); const int m = (int)blockIdx.x; const int t = (int)threadIdx.x, lane = t & (kWave - 1), wave = t >> 5; @@ -1062,12 +983,19 @@ __global__ __launch_bounds__(kMergeThreads) void qsa_merge_kernel( int n = nc[seq] < nb ? nc[seq] : nb; if (own < n) n = own; - /* The chunk offsets, serially on one thread: `nchunk` is at most sixteen. */ + /* Chunk offsets, serially on one thread (nchunk <= 16). */ if (t == 0) { int s = 0; - for (int c = 0; c < nchunk; ++c) { sh_off[c] = s; s += cc[(size_t)m * kParWMax + c]; } + uint32_t over = 0; + for (int c = 0; c < nchunk; ++c) { + const int32_t v = cc[(size_t)m * kParWMax + c]; + over |= (v & kParOver) ? 1u : 0u; + sh_off[c] = s; + s += v & ~kParOver; + } sh_off[nchunk] = s; sh_tot = (uint32_t)s; + sh_over = over; } __syncthreads(); const int tot = (int)sh_tot; @@ -1079,9 +1007,13 @@ __global__ __launch_bounds__(kMergeThreads) void qsa_merge_kernel( } __syncthreads(); - ParEmit e{ wsum, &sh_hi, &sh_ord, 0u, 0u, 0u, tot <= topk }; + /* Everything, in block order, exactly when the single-workgroup kernel takes everything: at + * most topk blocks, or topk or fewer live. With no chunk over topk the candidates are every + * live key, so their count is the live count; a chunk over topk means more than topk live, + * and then exactly topk candidates are the top-k, whose ties go last. */ + ParEmit e{ wsum, &sh_hi, &sh_ord, 0u, 0u, 0u, n <= topk || (!sh_over && tot <= topk) }; if (!e.all) { - radix_thresh(sh_key, tot, (uint32_t)topk, hist, suf, wsum, &sh_T, &sh_need); + radix_thresh(sh_key, tot, (uint32_t)topk, false, hist, suf, wsum, &sh_T, &sh_need); e.T = sh_T; e.need = sh_need; } if (t == 0) { sh_hi = 0; sh_ord = 0; } @@ -1094,29 +1026,25 @@ __global__ __launch_bounds__(kMergeThreads) void qsa_merge_kernel( const uint32_t k = i < tot ? sh_key[i] : 0u; const ParTake r = par_take(e, k, lane, wave); if (r.take) { - /* The chunk a candidate came from, from the offsets; `nchunk` is at most sixteen. */ + /* The candidate's chunk, from the offsets. */ int c = nchunk - 1; while (c > 0 && sh_off[c] > i) --c; - /* Already a page: the local pass resolved it where there were blocks to hide - * the load behind. `tb` is still needed below, for the partial page. */ + /* Already a page (resolved by the local pass); tb is still needed for the partial + * page. */ const int32_t page = ci[(size_t)(m * kParWMax + c) * topk + (i - sh_off[c])]; - /* THE SINGLE-WORKGROUP KERNEL'S LAYOUT, slot for slot: above the threshold at the - * front, ties at the back. The attention sums the pages in table order. */ + /* The single-workgroup kernel's layout: above the threshold first, ties last. */ if (r.hi) { if (r.slot_hi < (uint32_t)topk) ou[r.slot_hi] = page; } else { ou[(uint32_t)topk - e.need + r.rank_eq] = page; } } } - /* The partial page, appended last -- the same contract the single-workgroup kernel documents - * at length: `bt[n]` is the page the query itself lives in, and there is one exactly when the - * query does not sit on the last token of a block. */ + /* The partial page, appended last, as in the single-workgroup kernel. */ if (t == 0) { - /* `n` AND NOT THE CANDIDATE COUNT, slot for slot with the single-workgroup kernel: past - * the top-k the table is full to `topk` because the ties fill it, and below it the live - * count is the answer. The merged candidate count can fall short of `topk` where the - * single-workgroup kernel's table is full, and the padding loop below would then write -1 - * over the ties. */ - uint32_t out = n <= topk ? sh_hi : (uint32_t)topk; + /* Use n, not the candidate count, as the single-workgroup kernel does: above topk the + * table is full (ties fill it), and the merged count can fall short, which would let the + * padding loop overwrite ties with -1. The exception is the same as there: topk or + * fewer live blocks, all of them emitted. */ + uint32_t out = e.all ? sh_hi : (uint32_t)topk; const int32_t part = (n < nb && (p + 1) % ratio != 0) ? tb[n] : -1; if (part >= 0) ou[out++] = part; for (uint32_t i = out; i < (uint32_t)(topk + 1); ++i) ou[i] = -1; @@ -1128,18 +1056,17 @@ __global__ __launch_bounds__(kMergeThreads) void qsa_merge_kernel( } } // namespace -/* WHAT THE SPLIT PATH NEEDS, sized from `topk` alone so the answer is the same at declare -- when - * the op has parameters and no tensors -- as it is at issue. Two candidate planes and a count per - * (query, chunk), at the FIXED `kParM x kParWMax` stride both kernels index: 2.1 MiB at the - * deployment's topk of 512, out of an arena that is shared with every other op's worst step. */ +/* Split-path scratch, sized from topk alone so declare (parameters only) and issue agree: two + * candidate planes and a count per (query, chunk) at the fixed kParM x kParWMax stride (2.1 MiB + * at topk 512). */ static inline int64_t par_scratch_bytes(long long topk) { if (topk <= 0) return 0; return (int64_t)kParM * kParWMax * topk * 8 + (int64_t)kParM * kParWMax * 4; } -// score [M][nb] f32, `s_ld` elements a row (0 = nb) -- M is QUERIES +// score [M][nb] f32, `s_ld` elements a row (0 = nb); M is query rows // bt [nseq][nb] i32, `t_ld` elements a row (0 = nb); page ids, -1 = absent -// nc [nseq] i32, complete blocks a SEQUENCE +// nc [nseq] i32, complete blocks per sequence // pos [M] i32, each query's absolute position // cu [nseq+1] i32, cumulative query counts: which sequence a query row belongs to // sel [M][topk+1] i32, `o_ld` elements a row (0 = topk+1); -1 padded @@ -1147,18 +1074,15 @@ static inline int64_t par_scratch_bytes(long long topk) { static int r4d_qsa_select_bf16_emit(long score, long bt, long nc, long pos, long cu, long sel, long nsel, long seqused, int M, int nb, int topk, int ratio, int nseq, int s_ld, int t_ld, int o_ld, - void* scratch, long long scratch_bytes, const R4dSink& sk) { - int emit_rc = RAD_OK; - if (!score || !bt || !nc || !cu || !sel || !nsel) return -1; - if (M <= 0 || nb <= 0 || topk <= 0 || ratio <= 0 || nseq <= 0) return -2; + void* scratch, long long scratch_bytes, RadStream stream) { + if (!score || !bt || !nc || !cu || !sel || !nsel || !seqused) return R4D_NO(RAD_E_INVAL); + if (M <= 0 || nb <= 0 || topk <= 0 || ratio <= 0 || nseq <= 0) return R4D_NO(RAD_E_SHAPE); if (!s_ld) s_ld = nb; if (!t_ld) t_ld = nb; if (!o_ld) o_ld = topk + 1; - /* THE SPLIT PATH WHEN THE LAUNCH IS DECODE-SHAPED AND EVERYTHING IT NEEDS IS THERE. Every - * clause is a capacity: a wider launch already fills the device, a chunk or a candidate list - * that will not stage is not a chunk, and a caller that gave no scratch gets the kernel that - * needs none. None of them changes the answer -- see the proof above the split. */ + /* The split path for decode-shaped launches when chunks and candidate lists fit LDS and + * scratch was given. The choice never changes the result. */ const int nchunk = par_chunks(nb); const int chunk = (int)((nb + nchunk - 1) / nchunk); const int lds = lds_cap_of(); @@ -1169,53 +1093,42 @@ static int r4d_qsa_select_bf16_emit(long score, long bt, long nc, long pos, long uint32_t* ck = (uint32_t*)scratch; int32_t* ci = (int32_t*)(ck + (size_t)kParM * kParWMax * topk); int32_t* cc = ci + (size_t)kParM * kParWMax * topk; - emit_rc = R4D_EMIT(sk, qsa_local_kernel, dim3((unsigned)nchunk, (unsigned)M), dim3(kLocalThreads), - (size_t)chunk * sizeof(uint32_t), (const float*)score, (const int32_t*)bt, - (const int32_t*)nc, (const int32_t*)pos, (const int32_t*)cu, - ck, ci, cc, nb, topk, ratio, nseq, s_ld, t_ld, chunk); - emit_rc = R4D_EMIT(sk, qsa_merge_kernel, dim3((unsigned)M), dim3(kMergeThreads), - (size_t)nchunk * topk * sizeof(uint32_t), (const uint32_t*)ck, (const int32_t*)ci, - (const int32_t*)cc, (const int32_t*)bt, (const int32_t*)nc, - (const int32_t*)pos, (const int32_t*)cu, - (int32_t*)sel, (int32_t*)nsel, (int32_t*)seqused, - nb, topk, ratio, nseq, t_ld, o_ld, nchunk); - return emit_rc == RAD_OK && (sk.desc || hipGetLastError() == hipSuccess) ? 0 : -4; + const int rc = R4D_EMIT(stream, qsa_local_kernel, dim3((unsigned)nchunk, (unsigned)M), + dim3(kLocalThreads), (size_t)chunk * sizeof(uint32_t), + (const float*)score, (const int32_t*)bt, (const int32_t*)nc, + (const int32_t*)pos, (const int32_t*)cu, ck, ci, cc, nb, topk, + ratio, nseq, s_ld, t_ld, chunk); + if (rc != RAD_OK) return rc; + return R4D_EMIT(stream, qsa_merge_kernel, dim3((unsigned)M), dim3(kMergeThreads), + (size_t)nchunk * topk * sizeof(uint32_t), (const uint32_t*)ck, + (const int32_t*)ci, (const int32_t*)cc, (const int32_t*)bt, + (const int32_t*)nc, (const int32_t*)pos, (const int32_t*)cu, + (int32_t*)sel, (int32_t*)nsel, (int32_t*)seqused, + nb, topk, ratio, nseq, t_ld, o_ld, nchunk); } - /* A WIDE LAUNCH -- a prefill chunk, where the key cache is off -- takes the three-pass form. */ - if (g_qsa_select_form == 2 || (g_qsa_select_form == 0 && M > cache_max_m())) { - emit_rc = R4D_EMIT(sk, qsa_select_wide_kernel, dim3((unsigned)M), dim3(kThreads), 0, - (const float*)score, (const int32_t*)bt, (const int32_t*)nc, - (const int32_t*)pos, (const int32_t*)cu, (int32_t*)sel, - (int32_t*)nsel, (int32_t*)seqused, nb, topk, ratio, nseq, s_ld, t_ld, - o_ld); - return emit_rc == RAD_OK && (sk.desc || hipGetLastError() == hipSuccess) ? 0 : -4; + /* A wide launch (prefill chunk, key cache off) takes the wide kernel. */ + if (g_qsa_select_form == 2 || (g_qsa_select_form == 0 && M > kCacheMaxM)) { + return R4D_EMIT(stream, qsa_select_wide_kernel, dim3((unsigned)M), dim3(kThreads), 0, + (const float*)score, (const int32_t*)bt, (const int32_t*)nc, + (const int32_t*)pos, (const int32_t*)cu, (int32_t*)sel, + (int32_t*)nsel, (int32_t*)seqused, nb, topk, ratio, nseq, s_ld, t_ld, + o_ld); } - /* Never wider than the table itself: a short context asks for less LDS, not for the cap. */ - int cap = (M <= cache_max_m()) ? lds_cap_of() : 0; + /* Never more than the table width. */ + int cap = (M <= kCacheMaxM) ? lds_cap_of() : 0; if (cap > nb) cap = nb; - emit_rc = R4D_EMIT(sk, qsa_select_kernel, dim3((unsigned)M), dim3(kThreads), - (size_t)cap * sizeof(uint32_t), (const float*)score, (const int32_t*)bt, - (const int32_t*)nc, (const int32_t*)pos, (const int32_t*)cu, - (int32_t*)sel, (int32_t*)nsel, - (int32_t*)seqused, nb, topk, ratio, nseq, s_ld, t_ld, o_ld, cap); - return emit_rc == RAD_OK && (sk.desc || hipGetLastError() == hipSuccess) ? 0 : -4; + return R4D_EMIT(stream, qsa_select_kernel, dim3((unsigned)M), dim3(kThreads), + (size_t)cap * sizeof(uint32_t), (const float*)score, (const int32_t*)bt, + (const int32_t*)nc, (const int32_t*)pos, (const int32_t*)cu, + (int32_t*)sel, (int32_t*)nsel, + (int32_t*)seqused, nb, topk, ratio, nseq, s_ld, t_ld, o_ld, cap); } -extern "C" int r4d_qsa_select_bf16_emit(long score, long bt, long nc, long pos, long cu, long sel, - long nsel, long seqused, int M, int nb, int topk, int ratio, - int nseq, int s_ld, int t_ld, int o_ld, - void* scratch, long long scratch_bytes, long stream) { - R4dSink sk; sk.stream = (RadStream)(uintptr_t)stream; - return r4d_qsa_select_bf16_emit(score, bt, nc, pos, cu, sel, nsel, seqused, M, nb, topk, ratio, nseq, s_ld, t_ld, o_ld, scratch, scratch_bytes, sk); -} - -/* The arena the split path asks for. Called at DECLARE, where the op has parameters and no - * tensors -- so it reads `topk` and nothing shape-derived, and the fixed stride above is what - * makes that legal. */ extern "C" void r4d_qsa_select_pin_form(int form) { g_qsa_select_form = form; } +/* Split-path scratch, called at declare (parameters only), so it depends on topk alone. */ extern "C" int64_t r4d_rad_qsa_select_scratch(const RadArgs* a) { return par_scratch_bytes(r4d_geti_or(a, "topk", 0)); } @@ -1225,7 +1138,7 @@ extern "C" int64_t r4d_rad_qsa_select_scratch(const RadArgs* a) { enum { QL_SCORE = 0, QL_BT = 1, QL_NC = 2, QL_POS = 3, QL_CU = 4, QL_SEL = 5, QL_NSEL = 6, QL_SEQ = 7 }; -static int r4d_rad_qsa_select_body(const RadArgs* a, const R4dSink& sk) { +extern "C" int r4d_rad_qsa_select(const RadArgs* a, RadStream stream) { const RadTensor* sc = r4d_opt(a, QL_SCORE); const RadTensor* bt = r4d_opt(a, QL_BT); const RadTensor* nc = r4d_opt(a, QL_NC); @@ -1239,35 +1152,25 @@ static int r4d_rad_qsa_select_body(const RadArgs* a, const R4dSink& sk) { const long long topk = r4d_geti_or(a, "topk", 0); const long long ratio = r4d_geti_or(a, "ratio", 0); if (topk <= 0 || ratio <= 0) return R4D_NO(RAD_E_INVAL); - /* THE SMALLER OF THE TWO WIDTHS, for the reason r4d_qsa_score_bf16.hip gives at the same - * check: the score plane is the architecture's buffer and the table's pitch is the KV - * manager's, and requiring them equal refuses a configuration where they merely round - * differently. - * A query's live block count is bounded by max_ctx/ratio and both are sized for that, so the - * minimum is never below it -- and `nc` bounds the range actually read regardless. */ + /* nb = min of the two widths, as in r4d_qsa_score_bf16.hip. */ const long long M = sc->shape[0]; const long long nb = bt->shape[1] < sc->shape[1] ? bt->shape[1] : sc->shape[1]; if (M < 1 || nb < 1) return R4D_NO(RAD_E_SHAPE); - /* THE SEQUENCE COUNT COMES OFF `cu`, not off the table's height, which is max_seqs. */ + /* The sequence count comes from cu, not the table height (max_seqs). */ if (cu->rank != 1 || cu->shape[0] < 2) return R4D_NO(RAD_E_SHAPE); const long long nseq = cu->shape[0] - 1; if (bt->shape[0] < nseq || r4d_numel(nc) < nseq) return R4D_NO(RAD_E_SHAPE); - /* THE OUTPUT IS topk + 1 WIDE AND THE EXTRA SLOT IS NOT SPARE: it is the partial page, which - * is appended unconditionally and is what the query itself lives in. A caller that sized it - * at `topk` would drop the newest tokens on every query whose position is not a multiple of - * the ratio -- which is three queries in four. */ + /* The output is topk + 1 wide: the extra slot is the partial page holding the query. */ if (se->shape[0] != M || se->shape[1] != topk + 1) return R4D_NO(RAD_E_SHAPE); if (r4d_numel(ns) < M) return R4D_NO(RAD_E_SHAPE); if (r4d_numel(po) < M || r4d_numel(su) < M) return R4D_NO(RAD_E_SHAPE); const long long sp = r4d_row_pitch(sc), tp = r4d_row_pitch(bt), op = r4d_row_pitch(se); if (sp < 0 || tp < 0 || op < 0) return R4D_NO(RAD_E_STRIDE); - /* Scratch is OPTIONAL here and the launcher says so: the split path takes it when it is - * there and big enough, and the single-workgroup kernel runs when it is not. */ - const int e = r4d_qsa_select_bf16_emit(r4d_addr(sc), r4d_addr(bt), r4d_addr(nc), r4d_addr(po), - r4d_addr(cu), r4d_addr(se), r4d_addr(ns), r4d_addr(su), - (int)M, (int)nb, (int)topk, (int)ratio, (int)nseq, - (int)sp, (int)tp, (int)op, a->scratch, a->scratch_bytes, sk); - return e == 0 ? RAD_OK : RAD_E_SHAPE; + /* Scratch is optional: without enough, the non-split kernels run. */ + return r4d_qsa_select_bf16_emit(r4d_addr(sc), r4d_addr(bt), r4d_addr(nc), r4d_addr(po), + r4d_addr(cu), r4d_addr(se), r4d_addr(ns), r4d_addr(su), + (int)M, (int)nb, (int)topk, (int)ratio, (int)nseq, + (int)sp, (int)tp, (int)op, a->scratch, a->scratch_bytes, + stream); } -R4D_ENTRY(r4d_rad_qsa_select, r4d_rad_qsa_select_body) diff --git a/libr4d/r4d_qsa_tail_store_bf16.hip b/libr4d/r4d_qsa_tail_store_bf16.hip index 2ac0c5bf..82588658 100644 --- a/libr4d/r4d_qsa_tail_store_bf16.hip +++ b/libr4d/r4d_qsa_tail_store_bf16.hip @@ -1,41 +1,23 @@ -// The QSA indexer's TAIL: the raw index keys of the tokens that have not yet completed a block. +// The QSA indexer's tail: raw index keys of tokens that have not yet completed a block (a block key +// needs all `ratio` raw keys, and at decode most of them come from earlier steps). // -// A block key is the mean of `ratio` consecutive raw keys, so a block cannot be built until its -// last token arrives -- and at decode three of the four are from earlier steps. This is where they -// wait. +// The tail is a per-layer linear KV state owned by the sequence (allocated zeroed, kept for the +// sequence's life, checkpointed with the linear state), not a plane indexed by the step-local batch +// row (arch/common/rad_qsa.h's Wire). `state` is one layer's cache, [slots, 1, ring, n]; `sidx` +// names the sequence's slot; position p lands at row p % ring. // -// IT IS A LINEAR KV STATE AND NOT A PLANE INDEXED BY THE BATCH ROW. A sequence owns one state per -// bound layer, the engine keeps it for that sequence's life, zeroes it when it hands one out and -// checkpoints it with the rest of the linear state; the batch row is step-local and names a -// different sequence from one step to the next. arch/common/rad_qsa.h's Wire is the argument, and -// it is the same one that makes this per LAYER: the keys are `index_qk_proj`'s output. +// The ring is ratio + n_spec, not ratio: the next step restarts at the first rejected position, so +// a step may still owe positions back to p0 - ratio + 1 while writing up to p0 + n_spec. With that +// ring length a row is only overwritten by a position past any step that could still need it. // -// `state` is the group's cache for ONE layer, `[slots, 1, ring, n]`, and `sidx` names this -// sequence's slot in it. A token at position `p` lands at row `p % ring`. +// A token's sequence comes from cu_seqlens (slot_mapping is a flat KV slot and does not identify +// the sequence); a linear scan suffices for a handful of sequences. // -// THE RING IS `ratio + n_spec`, NOT `ratio`, AND SPECULATION IS THE WHOLE OF IT. A verify step -// runs 1 + n_spec positions and the next step restarts at the first REJECTED one, so a position -// this step has already overwritten is owed to the next. At ratio 4 depth 3 the step covering -// positions 9..12 writes rows 1,2,3,0 -- and row 0 is the one position 8 is still owed, because -// the block holding 8..11 is rebuilt as soon as the step that follows starts at 10. The widest -// window a step can still owe is [p0 - ratio + 1, p0 + n_spec]; a ring that long means a row is -// only ever overwritten by a position past the end of any step that could ask for it. +// Only the last `ring` tokens of a sequence's chunk write: positions p and p + ring share a row, so +// writing all of a prefill chunk would race. The last `ring` positions hit distinct rows, giving +// what a token-by-token loop would leave; older tokens' blocks are built from the chunk itself. // -// WHICH SEQUENCE A TOKEN BELONGS TO IS `cu_seqlens`, and that is the whole reason this op takes a -// boundary list. The batch's other per-token index is `slot_mapping`, which is a FLAT KV slot and -// says nothing about the sequence; the boundary list does, and with at most a handful of sequences -// a linear scan of it is free beside the copy it guards. -// -// ONLY THE LAST `ring` TOKENS OF A SEQUENCE'S CHUNK WRITE, AND THAT IS NOT AN OPTIMISATION. A -// prefill chunk carries many tokens per sequence and positions `p` and `p + ring` land on the -// SAME row, so a launch that wrote every token would have two workgroups racing for one row and -// the winner would depend on the schedule. Restricting the write to the last `ring` tokens makes -// every row the target of at most one token -- their positions differ by less than `ring`, so -// their rows differ -- and the result is what a token-by-token loop would have left. The older -// tokens of the chunk are not lost: the blocks they complete are built from the chunk's own keys, -// which are still in the projection's output. -// -// Returns a negative code rather than throwing, for the reason given in r4d_gemm_fp8a8.hip. +// Returns a RAD status rather than throwing, for the reason given in r4d_gemm_fp8a8.hip. #include "r4d.h" #include "r4d_args.h" @@ -57,9 +39,7 @@ __global__ __launch_bounds__(kThreads) void qsa_tail_store_kernel( const int t = (int)blockIdx.x; if (t >= T) return; - /* The sequence this token belongs to. A linear scan of at most `seqs + 1` boundaries, done - * redundantly by every thread rather than once into LDS: it is a handful of compares against - * a broadcast load, and a barrier would cost more than it saves. */ + /* This token's sequence, by a linear scan in every thread (cheaper than LDS plus a barrier). */ int s = -1; for (int i = 0; i < seqs; ++i) if (t >= cu[i] && t < cu[i + 1]) { s = i; break; } @@ -68,8 +48,7 @@ __global__ __launch_bounds__(kThreads) void qsa_tail_store_kernel( /* Only the last `ring` tokens of this sequence's chunk -- see the header. */ if (t < cu[s + 1] - ring) return; - /* COLUMN 0 IS THE COMMITTED SLOT. -1 is the pad a sequence with no state carries, and every - * kernel that reads a state row already tests for it. */ + /* Column 0 is the committed slot; -1 marks a sequence with no state. */ const int si = sidx[(size_t)s * sidx_ld]; if (si < 0) return; @@ -85,35 +64,27 @@ __global__ __launch_bounds__(kThreads) void qsa_tail_store_kernel( // pos [T] i32, each token's position in its sequence // cu [seqs + 1] i32, cu_seqlens // sidx [seqs][sidx_ld] i32, the tail group's state row; column 0 is the committed slot -// state [slots][ring][n] bf16, this layer's tail cache -- READ NOWHERE HERE, written in -// place, and rows nothing targets keep what they held +// state [slots][ring][n] bf16, this layer's tail cache; written only, untargeted rows +// keep their contents static int r4d_qsa_tail_store_bf16_emit(long k, long pos, long cu, long sidx, long state, int T, int n, int ring, int seqs, int k_ld, int s_slot, int s_row, - int sidx_ld, const R4dSink& sk) { - int emit_rc = RAD_OK; - if (!k || !pos || !cu || !sidx || !state) return -1; - if (T <= 0 || n <= 0 || ring <= 0 || seqs <= 0) return -2; + int sidx_ld, RadStream stream) { + if (!k || !pos || !cu || !sidx || !state) return R4D_NO(RAD_E_INVAL); + if (T <= 0 || n <= 0 || ring <= 0 || seqs <= 0) return R4D_NO(RAD_E_SHAPE); if (!k_ld) k_ld = n; if (!s_row) s_row = n; if (!sidx_ld) sidx_ld = 1; - emit_rc = R4D_EMIT(sk, qsa_tail_store_kernel, dim3((unsigned)T), dim3(kThreads), 0, (const uint16_t*)k, (const int32_t*)pos, - (const int32_t*)cu, (const int32_t*)sidx, (uint16_t*)state, T, n, ring, - seqs, k_ld, s_slot, s_row, sidx_ld); - return emit_rc == RAD_OK && (sk.desc || hipGetLastError() == hipSuccess) ? 0 : -4; -} - -extern "C" int r4d_qsa_tail_store_bf16_emit(long k, long pos, long cu, long sidx, long state, int T, - int n, int ring, int seqs, int k_ld, int s_slot, int s_row, - int sidx_ld, long stream) { - R4dSink sk; sk.stream = (RadStream)(uintptr_t)stream; - return r4d_qsa_tail_store_bf16_emit(k, pos, cu, sidx, state, T, n, ring, seqs, k_ld, s_slot, s_row, sidx_ld, sk); + return R4D_EMIT(stream, qsa_tail_store_kernel, dim3((unsigned)T), dim3(kThreads), 0, + (const uint16_t*)k, (const int32_t*)pos, (const int32_t*)cu, + (const int32_t*)sidx, (uint16_t*)state, T, n, ring, seqs, k_ld, s_slot, s_row, + sidx_ld); } // ============================================================== the plugin ABI entry point enum { QT_K = 0, QT_POS = 1, QT_CU = 2, QT_STATE = 3, QT_SIDX = 4 }; -static int r4d_rad_qsa_tail_store_body(const RadArgs* a, const R4dSink& sk) { +extern "C" int r4d_rad_qsa_tail_store(const RadArgs* a, RadStream stream) { const RadTensor* k = r4d_opt(a, QT_K); const RadTensor* po = r4d_opt(a, QT_POS); const RadTensor* cu = r4d_opt(a, QT_CU); @@ -121,10 +92,8 @@ static int r4d_rad_qsa_tail_store_body(const RadArgs* a, const R4dSink& sk) { const RadTensor* sx = r4d_opt(a, QT_SIDX); if (!k || !po || !cu || !st || !sx) return R4D_NO(RAD_E_INVAL); if (k->rank != 2) return R4D_NO(RAD_E_SHAPE); - /* THE STATE ARRIVES AS THE GROUP DECLARED IT: [slots, heads, ring, n], heads 1. The engine - * composes that shape out of the declaration and the manager's slot count - * (core/engine_bringup.cpp), so a different rank here means a different group, not a layout - * this kernel could have coped with. */ + /* The state arrives as the group declared it: [slots, heads, ring, n], heads 1 + * (core/engine_bringup.cpp). */ if (st->rank != 4 || st->shape[1] != 1) return R4D_NO(RAD_E_SHAPE); if (st->stride[3] != 1) return R4D_NO(RAD_E_STRIDE); const long long n = r4d_geti_or(a, "n", 0); @@ -134,9 +103,8 @@ static int r4d_rad_qsa_tail_store_body(const RadArgs* a, const R4dSink& sk) { const long long T = k->shape[0]; if (T < 1 || k->shape[1] != n) return R4D_NO(RAD_E_SHAPE); if (st->shape[2] < ring || st->shape[3] != n) return R4D_NO(RAD_E_SHAPE); - /* `cu_seqlens` IS seqs + 1 LONG AND THAT IS WHERE THE SEQUENCE COUNT COMES FROM. Taking it - * from the state's slot count instead would read the DECLARED max_seqs, and a step with fewer - * sequences than that would scan boundaries the batch never wrote. */ + /* The sequence count comes from cu_seqlens, not the state's slot count (the declared + * max_seqs). */ const long long seqs = r4d_numel(cu) - 1; if (seqs < 1 || r4d_numel(po) < T) return R4D_NO(RAD_E_SHAPE); const long long sxp = sx->rank >= 2 ? r4d_row_pitch(sx) : 1; @@ -144,11 +112,9 @@ static int r4d_rad_qsa_tail_store_body(const RadArgs* a, const R4dSink& sk) { const long long kp = r4d_row_pitch(k); if (kp < 0) return R4D_NO(RAD_E_STRIDE); if (k->dtype != RAD_BF16 || st->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); - const int e = r4d_qsa_tail_store_bf16_emit(r4d_addr(k), r4d_addr(po), r4d_addr(cu), r4d_addr(sx), - r4d_addr(st), (int)T, (int)n, (int)ring, (int)seqs, - (int)kp, (int)st->stride[0], (int)st->stride[2], - (int)sxp, sk); - return e == 0 ? RAD_OK : RAD_E_SHAPE; + return r4d_qsa_tail_store_bf16_emit(r4d_addr(k), r4d_addr(po), r4d_addr(cu), r4d_addr(sx), + r4d_addr(st), (int)T, (int)n, (int)ring, (int)seqs, + (int)kp, (int)st->stride[0], (int)st->stride[2], + (int)sxp, stream); } -R4D_ENTRY(r4d_rad_qsa_tail_store, r4d_rad_qsa_tail_store_body) diff --git a/libr4d/r4d_qsa_work_bf16.hip b/libr4d/r4d_qsa_work_bf16.hip index 6c3b38b3..5a052ff2 100644 --- a/libr4d/r4d_qsa_work_bf16.hip +++ b/libr4d/r4d_qsa_work_bf16.hip @@ -1,36 +1,22 @@ -// The QSA indexer's WORK LIST: which blocks complete this step, where their raw keys are, and +// The QSA indexer's work list: which blocks complete this step, where their raw keys are, and // where their block key goes. // -// `qsa_block_key` takes a flat list of blocks and reads each one's `ratio` raw keys from -// consecutive rows of one plane. Nothing in a batch hands it that. The keys of a block completing -// at DECODE are three rows of the tail and one row of this step; the keys of a block completing -// inside a PREFILL chunk are four rows of the chunk; and a block straddling the start of a chunk -// is some of each. The blocks themselves belong to different sequences at different positions. +// qsa_block_key reads each block's `ratio` raw keys from consecutive rows of one plane, but a +// block completing at decode has its keys partly in the tail and partly in this step, and blocks +// belong to different sequences. This op finds the completed blocks, gathers each one's raw keys +// into consecutive rows of a staging plane, and writes its destination page and first-token +// position: exactly qsa_block_key's three operands (docs/QSA.md). The copy is small (1 KiB per +// completing block) and keeps qsa_block_key single-source. // -// So this op gathers. It walks the sequences, works out which blocks became complete, copies each -// one's `ratio` raw keys into consecutive rows of a staging plane, and writes the block's -// destination page and first-token position beside it. What comes out is exactly the three -// operands `qsa_block_key` wants, and that kernel does not learn that two sources existed. -// docs/QSA.md is the decomposition. +// The tail is a per-layer linear KV state ([slots, 1, ring, n]; `sidx` names the sequence's slot, +// not the step-local batch row); see r4d_qsa_tail_store_bf16.hip, including why ring is +// ratio + n_spec. Keys are read at row q % ring to match. // -// THE TAIL IS A LINEAR KV STATE. `state` is the tail group's cache for ONE layer, -// `[slots, 1, ring, n]`, and `sidx` names this sequence's slot -- not the batch row, which is -// step-local and would hand a long-lived request the keys of a shorter one that used to sit -// there. r4d_qsa_tail_store_bf16.hip's header is the whole argument, including why the ring is -// `ratio + n_spec` rather than `ratio`; this side only has to read `q % ring` to match. +// The launch is bounded on the host (ceil(T / ratio) + n_seq: one block per `ratio` tokens plus +// one straddling block per sequence). Work items past the real count get page = -1, which +// qsa_block_key skips. // -// THE COPY IS THE POINT AND IT IS CHEAP. A kilobyte a completing block: 512 KiB for a full -// 2048-token prefill chunk a layer, four kilobytes for a decode step. The alternative is a -// block-key kernel that takes two sources, a per-key source selector and a tail layout -- three -// more things to get wrong inside the kernel that does the arithmetic. -// -// THE LAUNCH IS BOUNDED ON THE HOST, NOT COUNTED ON THE DEVICE. How many blocks complete is -// device data, but `ceil(T / ratio) + n_seq` bounds it from numbers the caller already has -- one -// block a `ratio` tokens, plus at most one straddling block a sequence. Slots past the real count -// get `page = -1`, and `qsa_block_key` skips those, so the bound costs empty workgroups that exit -// on their first load and never a wrong answer. -// -// Returns a negative code rather than throwing, for the reason given in r4d_gemm_fp8a8.hip. +// Returns a RAD status rather than throwing, for the reason given in r4d_gemm_fp8a8.hip. #include "r4d.h" #include "r4d_args.h" @@ -42,10 +28,8 @@ namespace { constexpr int kThreads = 128; -/* The sequence loop's bound. It is NOT a constraint on the declared `seqs`, which is a deployment - * maximum -- rad-convert declares at 256 and a row that refused that would not resolve at convert - * and its weights would never be written. The real count comes off `cu_seqlens` at issue and the - * launcher checks it there; the loop only ever runs to that. */ +/* The sequence loop's bound, checked by the launcher against the real count from cu_seqlens. Not a + * row constraint on the declared seqs (rad-convert declares 256, which must still resolve). */ constexpr int kMaxSeq = 256; __global__ __launch_bounds__(kThreads) void qsa_work_kernel( @@ -59,28 +43,25 @@ __global__ __launch_bounds__(kThreads) void qsa_work_kernel( int bstep) { const int w = (int)blockIdx.x; - /* COMPLETE BLOCKS A SEQUENCE, written by the first `seqs` workgroups on their way past. The - * scorer and the selection both need it and it is one division of a number this kernel has - * already loaded; a launch a layer a step for that alone would be five microseconds of - * dispatch for four instructions. */ + /* Complete blocks per sequence (needed by the scorer and the selection), written by the first + * `seqs` workgroups instead of a separate launch. */ if (w < seqs && threadIdx.x == 0) { const int t1 = cu[w + 1]; nc[w] = t1 > cu[w] ? (pos[t1 - 1] + 1) / ratio : 0; } if (w >= max_work) return; - /* WHICH SEQUENCE OWNS WORK ITEM w. A running count over the sequences, recomputed by every - * workgroup: `seqs` is a handful and the alternative is a second launch to build a prefix. */ + /* The sequence owning work item w, by a running count recomputed in every workgroup (seqs is + * small; a prefix would need a second launch). */ int s = -1, j = 0; int run = 0; for (int i = 0; i < seqs && i < kMaxSeq; ++i) { const int t0 = cu[i], t1 = cu[i + 1]; if (t1 <= t0) continue; const int p0 = pos[t0], p1 = pos[t1 - 1]; - /* A block is complete when its LAST token exists: 4b + ratio - 1 in [p0, p1]. Both - * bounds are taken on non-negative numerators, because C division truncates toward zero: - * `(p1 - (ratio - 1)) / ratio` is 0 rather than -1 for p1 < ratio - 1, which would count - * block 0 complete from its first token and gather keys past the end of the sequence. */ + /* A block completes this step when its last token, b * ratio + ratio - 1, is in [p0, p1]. + * Both bounds use non-negative numerators: C division truncates toward zero, so + * (p1 - (ratio - 1)) / ratio would be 0, not -1, for p1 < ratio - 1. */ const int lo = p0 / ratio; /* ceil((p0-ratio+1)/ratio) */ const int hi = (p1 + 1) / ratio - 1; /* floor((p1-ratio+1)/ratio) */ const int cnt = hi >= lo ? hi - lo + 1 : 0; @@ -88,7 +69,7 @@ __global__ __launch_bounds__(kThreads) void qsa_work_kernel( run += cnt; } if (s < 0) { - /* Past the real count. `page = -1` is what makes the host's bound safe. */ + /* Past the real count: page = -1 makes the host's bound safe. */ if (threadIdx.x == 0) { page[w] = -1; for (int c = 0; c < (rope ? 3 : 1); ++c) bpos[(size_t)w * bstep + c] = 0; @@ -99,9 +80,8 @@ __global__ __launch_bounds__(kThreads) void qsa_work_kernel( const int b = j; /* the block index within the sequence */ const int t0 = cu[s]; const int p0 = pos[t0]; - /* Column 0 is the committed slot; -1 is the pad for a sequence with no state. A block whose - * earlier keys are in a state that does not exist cannot be built, and writing a page out of - * whatever the pointer arithmetic reached is the failure this guard exists to prevent. */ + /* Column 0 is the committed slot; -1 marks a sequence with no state, whose blocks cannot be + * built (page -1, no gather). */ const int si = sidx[(size_t)s * sidx_ld]; if (threadIdx.x == 0) { @@ -109,13 +89,11 @@ __global__ __launch_bounds__(kThreads) void qsa_work_kernel( if (!rope) { bpos[(size_t)w * bstep] = b * ratio; } else { - /* THE ROTARY POSITION OF THE BLOCK'S FIRST TOKEN, three components, a work item's - * three side by side and items `bstep` apart. A first token in this step reads its - * own components. One committed in an earlier step is TEXT -- a prefill chunk ends on a - * whole block, so only a decode row or a prompt's last chunk leaves a block open, and a - * prompt ends in text -- and text rotates at its index plus the shift this step's first - * row of the sequence carries, the same shift, because nothing but text lies between. - * */ + /* Rotary position of the block's first token, three components side by side, items + * bstep apart. A first token in this step reads its own components. One from an + * earlier step is text (only a decode row or a prompt's last chunk leaves a block open, + * and a prompt ends in text), so it rotates at its index plus the shift carried by + * this step's first row of the sequence. */ const int f = b * ratio; for (int c = 0; c < 3; ++c) bpos[(size_t)w * bstep + c] = @@ -124,7 +102,7 @@ __global__ __launch_bounds__(kThreads) void qsa_work_kernel( } if (si < 0) return; - /* The block's `ratio` raw keys, from whichever side of the chunk boundary each one is on. */ + /* The block's raw keys, each from this step or from the tail. */ for (int i = 0; i < ratio; ++i) { const int q = b * ratio + i; /* this key's position */ const uint16_t* src; @@ -142,7 +120,7 @@ __global__ __launch_bounds__(kThreads) void qsa_work_kernel( // cu [seqs + 1] i32 // state [slots][ring][n] bf16, the tail group's cache for this layer // sidx [seqs][sidx_ld] i32, the tail group's state row; column 0 is the slot -// bt [seqs][bt_ld] i32, the BLOCK-KEY group's block table +// bt [seqs][bt_ld] i32, the block-key group's block table // stage [max_work * ratio][n] bf16 // page [max_work] i32, -1 past the real count // bpos [max_work][bstep] i32, a work item's first-token position at [w * bstep] @@ -153,29 +131,21 @@ static int r4d_qsa_work_bf16_emit(long k, long pos, long cu, long state, long si long stage, long page, long bpos, long nc, int n, int ratio, int ring, int seqs, int max_work, int k_ld, int s_slot, int s_row, int sidx_ld, int bt_ld, int g_ld, long rope, - int rplane, int bstep, const R4dSink& sk) { - int emit_rc = RAD_OK; - if (!k || !pos || !cu || !state || !sidx || !bt || !stage || !page || !bpos || !nc) return -1; - if (n <= 0 || ratio <= 0 || ring < ratio || seqs <= 0 || max_work <= 0) return -2; - if (seqs > kMaxSeq) return -5; + int rplane, int bstep, RadStream stream) { + if (!k || !pos || !cu || !state || !sidx || !bt || !stage || !page || !bpos || !nc) + return R4D_NO(RAD_E_INVAL); + if (n <= 0 || ratio <= 0 || ring < ratio || seqs <= 0 || max_work <= 0 || seqs > kMaxSeq) + return R4D_NO(RAD_E_SHAPE); if (!k_ld) k_ld = n; if (!s_row) s_row = n; if (!g_ld) g_ld = n; if (!sidx_ld) sidx_ld = 1; - emit_rc = R4D_EMIT(sk, qsa_work_kernel, dim3((unsigned)max_work), dim3(kThreads), 0, (const uint16_t*)k, (const int32_t*)pos, - (const int32_t*)cu, (const uint16_t*)state, (const int32_t*)sidx, - (const int32_t*)bt, (uint16_t*)stage, (int32_t*)page, (int32_t*)bpos, - (int32_t*)nc, n, ratio, ring, seqs, max_work, k_ld, s_slot, s_row, - sidx_ld, bt_ld, g_ld, (const int32_t*)rope, rplane, bstep); - return emit_rc == RAD_OK && (sk.desc || hipGetLastError() == hipSuccess) ? 0 : -4; -} - -extern "C" int r4d_qsa_work_bf16_emit(long k, long pos, long cu, long state, long sidx, long bt, - long stage, long page, long bpos, long nc, int n, int ratio, - int ring, int seqs, int max_work, int k_ld, int s_slot, - int s_row, int sidx_ld, int bt_ld, int g_ld, long stream) { - R4dSink sk; sk.stream = (RadStream)(uintptr_t)stream; - return r4d_qsa_work_bf16_emit(k, pos, cu, state, sidx, bt, stage, page, bpos, nc, n, ratio, ring, seqs, max_work, k_ld, s_slot, s_row, sidx_ld, bt_ld, g_ld, 0, 0, 1, sk); + return R4D_EMIT(stream, qsa_work_kernel, dim3((unsigned)max_work), dim3(kThreads), 0, + (const uint16_t*)k, (const int32_t*)pos, (const int32_t*)cu, + (const uint16_t*)state, (const int32_t*)sidx, (const int32_t*)bt, + (uint16_t*)stage, (int32_t*)page, (int32_t*)bpos, (int32_t*)nc, n, ratio, + ring, seqs, max_work, k_ld, s_slot, s_row, sidx_ld, bt_ld, g_ld, + (const int32_t*)rope, rplane, bstep); } // ============================================================== the plugin ABI entry point @@ -183,14 +153,14 @@ extern "C" int r4d_qsa_work_bf16_emit(long k, long pos, long cu, long state, lon enum { QW_K = 0, QW_POS, QW_CU, QW_STATE, QW_SIDX, QW_BT, QW_ROPE, QW_STAGE, QW_PAGE, QW_BPOS, QW_NC }; -static int r4d_rad_qsa_work_body(const RadArgs* a, const R4dSink& sk) { +extern "C" int r4d_rad_qsa_work(const RadArgs* a, RadStream stream) { const RadTensor* k = r4d_opt(a, QW_K); const RadTensor* po = r4d_opt(a, QW_POS); const RadTensor* cu = r4d_opt(a, QW_CU); const RadTensor* tl = r4d_opt(a, QW_STATE); const RadTensor* sx = r4d_opt(a, QW_SIDX); const RadTensor* bt = r4d_opt(a, QW_BT); - const RadTensor* rp = r4d_opt(a, QW_ROPE); /* OPTIONAL: multi-component positions */ + const RadTensor* rp = r4d_opt(a, QW_ROPE); /* optional: multi-component positions */ const RadTensor* st = r4d_opt(a, QW_STAGE); const RadTensor* pg = r4d_opt(a, QW_PAGE); const RadTensor* bp = r4d_opt(a, QW_BPOS); @@ -202,9 +172,8 @@ static int r4d_rad_qsa_work_body(const RadArgs* a, const R4dSink& sk) { * r4d_qsa_tail_store_bf16.hip. */ if (tl->rank != 4 || tl->shape[1] != 1) return R4D_NO(RAD_E_SHAPE); if (tl->stride[3] != 1) return R4D_NO(RAD_E_STRIDE); - /* `bt` here is the BLOCK-KEY group's table, not the attention group's. They are different - * pages for the same sequence and the join between them is the block INDEX, which is the same - * number in both because both groups are paged at `ratio` (docs/QSA.md). */ + /* bt is the block-key group's table, not the attention group's; both are paged at `ratio`, + * so they share block indices (docs/QSA.md). */ const long long n = r4d_geti_or(a, "n", 0); const long long ratio = r4d_geti_or(a, "ratio", 0); const long long ring = r4d_geti_or(a, "ring", 0); @@ -217,17 +186,12 @@ static int r4d_rad_qsa_work_body(const RadArgs* a, const R4dSink& sk) { if (bt->shape[0] < seqs) return R4D_NO(RAD_E_SHAPE); const long long sxp = sx->rank >= 2 ? r4d_row_pitch(sx) : 1; if (sxp < 1 || r4d_dim(sx, 0) < seqs) return R4D_NO(RAD_E_SHAPE); - /* THE WORK COUNT COMES OFF `page` AND `stage` MUST BE `ratio` TIMES IT. Taking it off `stage` - * instead would let a caller pass a plane sized for more blocks than it has slots to name, - * and the overflow would be silent -- the kernel writes keys for a block whose page nobody - * reads. */ + /* The work count comes from `page`, and `stage` must hold ratio rows per item. */ const long long mw = r4d_numel(pg); if (mw < 1 || st->shape[0] < mw * ratio) return R4D_NO(RAD_E_SHAPE); - /* `bpos` is one position a work item, or a rank-2 [>= work, 1 or 3] column slice of a buffer - * declared [max_work, 3]: a work item's components side by side and the items a row pitch - * apart, so the buffer's rows are its work items and a smaller step is fewer of them. Three - * columns are required with `rope`. `rope` itself is [3, rplane] component-major, a plane at - * least as long as the step. */ + /* bpos is one position per work item, or a rank-2 [>= work, 1 or 3] column slice of a + * [max_work, 3] buffer (components side by side, items a row pitch apart); three columns are + * required with `rope`. rope is [3, rplane] component-major, rplane >= the step's tokens. */ long long bstep = 1; if (bp->rank == 2) { if (bp->shape[0] < mw || bp->stride[1] != 1 || bp->stride[0] < bp->shape[1] || @@ -241,20 +205,17 @@ static int r4d_rad_qsa_work_body(const RadArgs* a, const R4dSink& sk) { rp->dtype != RAD_I32)) return R4D_NO(RAD_E_SHAPE); if (r4d_numel(nc) < seqs) return R4D_NO(RAD_E_SHAPE); - /* The per-sequence output is written by the first `seqs` workgroups, so a launch narrower - * than the batch would leave some of it stale. */ + /* nc is written by the first `seqs` workgroups, so the launch must be at least that wide. */ if (mw < seqs) return R4D_NO(RAD_E_SHAPE); const long long kp = r4d_row_pitch(k); const long long bp2 = r4d_row_pitch(bt), sp = r4d_row_pitch(st); if (kp < 0 || bp2 < 0 || sp < 0) return R4D_NO(RAD_E_STRIDE); if (k->dtype != RAD_BF16 || tl->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); - const int e = r4d_qsa_work_bf16_emit(r4d_addr(k), r4d_addr(po), r4d_addr(cu), r4d_addr(tl), - r4d_addr(sx), r4d_addr(bt), r4d_addr(st), r4d_addr(pg), - r4d_addr(bp), r4d_addr(nc), (int)n, (int)ratio, (int)ring, - (int)seqs, (int)mw, (int)kp, (int)tl->stride[0], - (int)tl->stride[2], (int)sxp, (int)bp2, (int)sp, - r4d_addr(rp), rp ? (int)rp->shape[1] : 0, (int)bstep, sk); - return e == 0 ? RAD_OK : RAD_E_SHAPE; + return r4d_qsa_work_bf16_emit(r4d_addr(k), r4d_addr(po), r4d_addr(cu), r4d_addr(tl), + r4d_addr(sx), r4d_addr(bt), r4d_addr(st), r4d_addr(pg), + r4d_addr(bp), r4d_addr(nc), (int)n, (int)ratio, (int)ring, + (int)seqs, (int)mw, (int)kp, (int)tl->stride[0], + (int)tl->stride[2], (int)sxp, (int)bp2, (int)sp, + r4d_addr(rp), rp ? (int)rp->shape[1] : 0, (int)bstep, stream); } -R4D_ENTRY(r4d_rad_qsa_work, r4d_rad_qsa_work_body) diff --git a/libr4d/r4d_quant_act_fp8.hip b/libr4d/r4d_quant_act_fp8.hip index 1ef8aade..985320d9 100644 --- a/libr4d/r4d_quant_act_fp8.hip +++ b/libr4d/r4d_quant_act_fp8.hip @@ -1,34 +1,22 @@ -// Per-(row, 128-column) symmetric E4M3 quantisation of a bf16 activation -- the gate on the fp8a8 -// GEMMs. `quantization_config.activation_scheme` on the target checkpoint is "dynamic", which means -// the file ships no activation scale and one is computed every step; and a GEMM cannot compute its -// own without a reduction across every M block, so it does not try. +// Per-(row, 128-column) symmetric E4M3 quantisation of a bf16 activation, the input to the fp8a8 +// GEMMs. The checkpoint's activation_scheme is "dynamic" (no stored activation scale), and a GEMM +// cannot compute one without a reduction across every M block. // -// UNLIKE r4d_quant_act_i8, THE OUTPUT IS PLAIN ROW-MAJOR. That kernel writes the byte order -// gemm_w4a8_nt_m64's A fragment reads, because that GEMM loads A straight to registers. The fp8a8 -// GEMMs stage BOTH operands through the same `stage8` byte copy and read both through the same XOR -// swizzle, so the permutation would have to be undone. Row-major is also what makes the activation -// a legal B operand of the narrow instantiation, where it is the sixteen-wide side. +// Output is plain row-major, unlike r4d_quant_act_i8 (which writes gemm_w4a8_nt_m64's register +// fragment order): the fp8a8 GEMMs stage both operands through the same `stage8` copy and fragment +// read, and row-major lets the activation be the B operand of the narrow instantiation. // -// THE GROUP IS 128 AND IS NOT A BUILD FLAG. It is the weight scale's block width -- a property of -// the checkpoint on disk, not a choice this library's quantiser makes, unlike R4D_GEMM_W4A8_GROUP. -// A different group would make the GEMM's fold read the wrong scale for part of a block. +// The group is fixed at 128, the checkpoint's weight-scale block width (unlike +// R4D_GEMM_W4A8_GROUP); another group would make the GEMM's fold read the wrong scale. No LDS: the +// input is already row-major per token. // -// NO LDS. Every activation in this library is already row-major per token, the layout the codes -// are written in, so there is no transpose to do and staging through LDS would buy nothing. -// -// THE THREE THINGS THAT ARE NOT OBVIOUS: -// -// 448 is E4M3's largest finite value, and the scale is `amax / 448` -- a DEQUANT multiplier, the -// same sense as the checkpoint's `weight_scale_inv`, so the GEMM's fold multiplies both scales -// and never divides. -// -// A ZERO BLOCK gets a scale of 1 and quantises to zeros, because `amax / 448` would be zero and -// its reciprocal infinite. -// -// THE CLAMP IS NOT DEFENSIVE. `amax * (1/scale)` is 448 in exact arithmetic but can land an ulp -// above it in float, and v_cvt_pk_fp8_f32 answers an out-of-range input with NaN rather than -// saturating -- so without the clamp EVERY block containing its own maximum produces a NaN. One -// missing fminf is a whole-model failure. +// Not obvious: +// - The scale is `amax / 448` (E4M3's largest finite value), a dequant multiplier like the +// checkpoint's `weight_scale_inv`, so the GEMM's fold only multiplies. +// - A zero block gets scale 1 and quantises to zeros. +// - The clamp is required: `amax * (1/scale)` can land an ulp above 448, and v_cvt_pk_fp8_f32 +// returns NaN for out-of-range input instead of saturating, so every block's maximum would +// become NaN. // // Returns a negative code rather than throwing, for the reason given in r4d_gemm_fp8a8.hip. @@ -45,29 +33,16 @@ constexpr uint32_t kThreads = 256; constexpr uint32_t kWaves = kThreads / kWave; constexpr uint32_t kGroup = 128; -__device__ __forceinline__ float wave_max(float v) { - v = r4d_wave_max(v); - return v; -} - -// One block a row; a wave owns one 128-column group, a lane four consecutive columns of it. Four is -// what makes the store a single dword and the wave's store 128 contiguous bytes, and it is also -// exactly the two v_cvt_pk_fp8_f32 the packing needs. +// One block per row; a wave owns one 128-column group, a lane four consecutive columns (one dword +// store, 128 contiguous bytes per wave, two v_cvt_pk_fp8_f32). // -// ROT MAKES IT THE ROTATED QUANTISER AND NEEDS NO EXTRA MACHINERY, because that mapping -- one -// wave a 128-wide group, four consecutive values a lane -- is exactly the one r4d_fwht_wave<128> wants -// (VPL = 128/32 = 4). The transform runs in registers between the load and the absmax, with no -// LDS and no barrier, and the absmax then sees the ROTATED values -- which is the entire point, -// since the whole benefit of a rotation is that the maximum the grid is scaled by gets smaller. +// ROT applies r4d_fwht_wave<128> in registers between the load and the absmax; the mapping (four +// values per lane) is the one it expects, so no LDS or barrier is needed, and the absmax sees the +// rotated values. The sqrt(128) factor of the unnormalised transform is not removed here: +// = 128 , and r4d_layout.cpp folds that into the stored weight scale at convert. // -// NOTHING NORMALISES sqrt(128) HERE. The unnormalised transform gives sqrt(128) times the -// orthonormal values, the scale is amax/448 over exactly those, and = 128 -- so -// the whole residual factor is one number, and r4d_layout.cpp folds it into the STORED WEIGHT -// SCALE at convert, where it is an exponent shift and costs nothing. A pass here to divide by -// sqrt(128) would be a second touch of every element for a constant the other side carries free. -// I8 IS THE SAME QUANTISER AT INT8 CODES (quant_act_i8g, had_quant_act_i8g): the scale is amax/127 -// and a code is the value over it rounded to nearest-even, -127..127, one byte -- for the int8 trunk -// GEMMs, which read the same plain row-major bytes and per-(row, 128) scales the fp8 ones do. +// I8 is the same quantiser at int8 codes (quant_act_i8g, had_quant_act_i8g): scale amax/127, +// round-to-nearest-even into -127..127, same row-major layout and per-(row, 128) scales. template __global__ __launch_bounds__(kThreads) void quant_act_fp8_kernel( const uint16_t* __restrict__ x, uint8_t* __restrict__ q, float* __restrict__ s, @@ -86,13 +61,12 @@ __global__ __launch_bounds__(kThreads) void quant_act_fp8_kernel( const uint32_t c = c0 + (uint32_t)j; v[j] = c < K ? __uint_as_float((uint32_t)x[xrow + c] << 16) : 0.0f; } - // The whole wave has to be inside the row for this, which is why the rotated launcher - // refuses a K that is not a multiple of the group: a partial block would rotate real - // values against padding zeros, and the weight side has no matching block to undo it. + // The rotated launcher requires K % 128 == 0: a partial block would rotate real values + // with padding zeros, and the weight has no matching block. if constexpr (ROT) r4d_fwht_wave<(int)kGroup>(v, (int)lane); #pragma unroll for (int j = 0; j < 4; ++j) m = fmaxf(m, fabsf(v[j])); - m = wave_max(m); + m = r4d_wave_max(m); constexpr float kTop = I8 ? 127.0f : 448.0f; const float sc = m > 0.0f ? m * (1.0f / kTop) : 1.0f; if (lane == 0) s[(size_t)row * s_ld + kb] = sc; @@ -114,10 +88,8 @@ __global__ __launch_bounds__(kThreads) void quant_act_fp8_kernel( fminf(fmaxf(v[3] * inv, -448.0f), 448.0f), pk, true); } - // A ragged last group is written zero-padded rather than partially: the padding lanes hold - // zeros, which quantise to zeros, and the GEMM's own bounds guard is what stops them - // reaching an accumulator. A partial store would be a second code path for a case no dense - // tensor in the target has -- but the caller must own K rounded up to 4 bytes of `q`. + // A ragged last group is written zero-padded; the GEMM's bounds guard keeps the padding out + // of the accumulators. The caller must own K rounded up to 4 bytes of `q`. if (c0 < K) *(uint32_t*)(q + qrow + c0) = (uint32_t)pk; } } @@ -130,12 +102,9 @@ extern "C" int r4d_quant_act_fp8_group(void) { return (int)kGroup; } // q [M][K] E4M3, `q_ld` bytes a row (0 = K), rounded up to 4 // s [M][ceil(K/128)] f32, `s_ld` elements a row (0 = ceil(K/128)) // -// `rot` runs the 128-wide Hadamard first. It is a STRICTER call, not a flag on the same one: a -// ragged last group is legal unrotated (it is written zero-padded and the GEMM's bounds guard -// stops the padding) and is not legal rotated, because a block that mixes real values with -// padding has no matching weight block on the other side. +// `rot` runs the 128-wide Hadamard first and additionally requires K % 128 == 0 (see the kernel). static int quant_act_fp8_launch(long a, long q, long s, int M, int K, - int x_ld, int q_ld, int s_ld, const R4dSink& sk, bool rot, + int x_ld, int q_ld, int s_ld, RadStream stream, bool rot, bool i8 = false) { int emit_rc = RAD_OK; if (!a || !q || !s) return -1; @@ -147,103 +116,75 @@ static int quant_act_fp8_launch(long a, long q, long s, int M, int K, const int nkb = (K + (int)kGroup - 1) / (int)kGroup; if (!s_ld) s_ld = nkb; #define R4D_QA(ROT_, I8_) \ - R4D_EMIT(sk, (quant_act_fp8_kernel), dim3((uint32_t)M), dim3(kThreads), 0, \ + R4D_EMIT(stream, (quant_act_fp8_kernel), dim3((uint32_t)M), dim3(kThreads), 0, \ (const uint16_t*)a, (uint8_t*)q, (float*)s, (uint32_t)K, (uint32_t)nkb, \ (uint32_t)x_ld, (uint32_t)q_ld, (uint32_t)s_ld) - if (i8) - emit_rc = rot ? R4D_QA(true, true) : R4D_QA(false, true); - else if (rot) - emit_rc = R4D_EMIT(sk, quant_act_fp8_kernel, dim3((uint32_t)M), dim3(kThreads), 0, - (const uint16_t*)a, (uint8_t*)q, (float*)s, - (uint32_t)K, (uint32_t)nkb, (uint32_t)x_ld, (uint32_t)q_ld, - (uint32_t)s_ld); - else - emit_rc = R4D_EMIT(sk, quant_act_fp8_kernel, dim3((uint32_t)M), dim3(kThreads), 0, - (const uint16_t*)a, (uint8_t*)q, (float*)s, - (uint32_t)K, (uint32_t)nkb, (uint32_t)x_ld, (uint32_t)q_ld, - (uint32_t)s_ld); + if (i8) emit_rc = rot ? R4D_QA(true, true) : R4D_QA(false, true); + else emit_rc = rot ? R4D_QA(true, false) : R4D_QA(false, false); #undef R4D_QA if (emit_rc != RAD_OK) return -4; - return (!sk.desc && hipGetLastError() != hipSuccess) ? -4 : 0; + return (hipGetLastError() != hipSuccess) ? -4 : 0; } extern "C" int r4d_quant_act_fp8(long a, long q, long s, int M, int K, int x_ld, int q_ld, int s_ld, long stream) { return quant_act_fp8_launch(a, q, s, M, K, x_ld, q_ld, s_ld, - r4d_stream_sink((RadStream)(uintptr_t)stream), false); + (RadStream)(uintptr_t)stream, false); } extern "C" int r4d_had_quant_act_fp8(long a, long q, long s, int M, int K, int x_ld, int q_ld, int s_ld, long stream) { return quant_act_fp8_launch(a, q, s, M, K, x_ld, q_ld, s_ld, - r4d_stream_sink((RadStream)(uintptr_t)stream), true); + (RadStream)(uintptr_t)stream, true); } // ============================================================== the plugin ABI entry points // -// The shared operand reader is r4d_fp8_args.h. See libr4d/r4d_args.h for why there is no adapter -// directory between the core and these launches. +// The shared operand reader is r4d_fp8_args.h; see libr4d/r4d_args.h. /* ================================================================== the fp8 activation quantiser */ -static int rad_quant_act_fp8(const RadArgs* a, const R4dSink& sk, bool rot, bool i8 = false) { +static int rad_quant_act_fp8(const RadArgs* a, RadStream stream, bool rot, bool i8 = false) { const RadTensor* x = r4d_opt(a, QF_X); const RadTensor* q = r4d_opt(a, QF_Q); const RadTensor* sc = r4d_opt(a, QF_S); if (!x || !q || !sc) return R4D_NO(RAD_E_INVAL); - /* ROWS ARE DIM 0 AND EVERYTHING AFTER IT IS THE ROW, which is the same reading r4d_row_pitch - * already takes -- it folds every trailing extent into one pitch and returns stride[0]. So a - * rank-3 activation is accepted and is one row per token: a GDN block's out-projection input is - * declared [tokens, heads, width] because libr4d's scan kernels require that rank, and its K is - * heads*width. Flattening it here rather than making the caller declare a second buffer is the - * only way to quantise it at all, and reading it as one row per HEAD would put a scale on a - * grid the consuming GEMM does not read. - * - * `q` and `sc` stay rank 2 because this kernel WRITES them and they exist for the GEMM. */ + /* Rows are dim 0 and everything after is the row, as r4d_row_pitch reads it. A GDN block's + * out-projection input is [tokens, heads, width] (the scan kernels require that rank) and its + * K is heads*width; one row per head would put scales on a grid the GEMM does not read. + * `q` and `sc` are written for the GEMM and stay rank 2. */ if (x->rank < 2 || q->rank != 2 || sc->rank != 2) return R4D_NO(RAD_E_SHAPE); const long long M = x->shape[0], K = r4d_numel(x) / (x->shape[0] > 0 ? x->shape[0] : 1); const long long grp = r4d_quant_act_fp8_group(); const long long nkb = (K + grp - 1) / grp; - /* The group is a property of the checkpoint's scale grid, not a knob. A geometry that declares - * a different one is asking for a format the GEMM's fold does not read, and the answer is a - * refusal by name rather than a silent 128. */ + /* The group is fixed by the checkpoint's scale grid; a different declared group is refused. */ if (r4d_geti_or(a, "group", grp) != grp) return R4D_NO(RAD_E_SHAPE); if (q->shape[0] != M || q->shape[1] != K) return R4D_NO(RAD_E_SHAPE); if (sc->shape[0] != M || sc->shape[1] != nkb) return R4D_NO(RAD_E_SHAPE); const long long xp = r4d_row_pitch(x), qp = r4d_row_pitch(q), sp = r4d_row_pitch(sc); if (xp < 0 || qp < 0 || sp < 0) return R4D_NO(RAD_E_STRIDE); const int e = quant_act_fp8_launch(r4d_addr(x), r4d_addr(q), r4d_addr(sc), (int)M, (int)K, - (int)xp, (int)qp, (int)sp, sk, rot, i8); + (int)xp, (int)qp, (int)sp, stream, rot, i8); return e == 0 ? RAD_OK : RAD_E_SHAPE; } -static int rad_quant_act_fp8_body(const RadArgs* a, const R4dSink& sk) { - return rad_quant_act_fp8(a, sk, false); +extern "C" int r4d_rad_quant_act_fp8(const RadArgs* a, RadStream stream) { + return rad_quant_act_fp8(a, stream, false); } -R4D_ENTRY(r4d_rad_quant_act_fp8, rad_quant_act_fp8_body) -/* THE ROTATED FORM, and it is a DIFFERENT OP rather than a parameter on that one, for the reason - * quant_act_i8 and had_quant_act_i8 are two ops: the number it writes is not the same number, so - * a graph in which one was substituted for the other would be a different model that still ran. - * The op name is what says which, and it is checked against the weight's layout tag by the pair - * being declared together in arch/common/rad_block_moe_fp8.h -- nothing here can see the weight. - * - * It pairs with the `w4a8h` expert plane and with NOTHING ELSE: any consumer of this activation - * that was not rotated at convert reads it as noise. */ -static int rad_had_quant_act_fp8_body(const RadArgs* a, const R4dSink& sk) { - return rad_quant_act_fp8(a, sk, true); +/* The rotated form is a separate op, not a parameter: it writes different numbers, so a swapped + * graph would still run as a different model. The op name pairs with the weight's layout tag in + * arch/common/rad_block_moe_fp8.h. It pairs only with the `w4a8h` expert plane; any consumer not + * rotated at convert reads it as noise. */ +extern "C" int r4d_rad_had_quant_act_fp8(const RadArgs* a, RadStream stream) { + return rad_quant_act_fp8(a, stream, true); } -R4D_ENTRY(r4d_rad_had_quant_act_fp8, rad_had_quant_act_fp8_body) - -/* THE INT8 PAIR: the same rows at int8 codes, for the int8 trunk GEMMs (gemm_i8a8_*). Ops of their - * own for the reason the rotated form is one: they write other numbers into a buffer of the same - * shape, and the name is what says which. */ -static int rad_quant_act_i8g_body(const RadArgs* a, const R4dSink& sk) { - return rad_quant_act_fp8(a, sk, false, true); +/* The int8 pair, for the int8 trunk GEMMs (gemm_i8a8_*). Separate ops for the same reason as the + * rotated form: different numbers in a buffer of the same shape. */ +extern "C" int r4d_rad_quant_act_i8g(const RadArgs* a, RadStream stream) { + return rad_quant_act_fp8(a, stream, false, true); } -R4D_ENTRY(r4d_rad_quant_act_i8g, rad_quant_act_i8g_body) -static int rad_had_quant_act_i8g_body(const RadArgs* a, const R4dSink& sk) { - return rad_quant_act_fp8(a, sk, true, true); +extern "C" int r4d_rad_had_quant_act_i8g(const RadArgs* a, RadStream stream) { + return rad_quant_act_fp8(a, stream, true, true); } -R4D_ENTRY(r4d_rad_had_quant_act_i8g, rad_had_quant_act_i8g_body) diff --git a/libr4d/r4d_quant_act_i8.hip b/libr4d/r4d_quant_act_i8.hip index a87211d0..ac66d5da 100644 --- a/libr4d/r4d_quant_act_i8.hip +++ b/libr4d/r4d_quant_act_i8.hip @@ -1,16 +1,12 @@ // r4d_quant_act_i8.hip - r4d_quant_act_i8: per-row symmetric int8 quantisation of a bf16 activation, // written in the order r4d_gemm_w4a8_nt_m64's A fragment wants. // -// One row per workgroup: absmax over K, then a second pass writing the bytes. K is a few thousand -// and M is a speculative-decode batch, so the whole thing is well under a microsecond -- one launch -// in place of the several an unfused quantiser would cost. +// One row per workgroup: absmax over K, then a second pass writing the bytes. // -// THE BYTE ORDER. Fragment element e of lane l is A[row][16s + 8*(e>>2) + 4*(l>>4) + (e&3)], so a -// lane's eight bytes are two dwords eight bytes apart in a row-major activation. Writing each k -// step's sixteen bytes as [half 0's eight][half 1's eight] instead makes them contiguous and the -// GEMM reads a fragment with one global_load_b64. Rows are untouched, so every lane of a wave -// stays inside the same sixteen rows it would have read anyway -- laying A out as two separate -// PLANES is the version that loses, see the note in the GEMM. +// Byte order: fragment element e of lane l is A[row][16s + 8*(e>>2) + 4*(l>>4) + (e&3)], two dwords +// eight bytes apart in a row-major activation. Each k step's sixteen bytes are written as +// [half 0's eight][half 1's eight], so the GEMM reads a fragment with one global_load_b64. Rows are +// not permuted; splitting A into two planes is slower (see the note in the GEMM). #include "r4d.h" #include "r4d_args.h" #include "r4d_emit.h" @@ -18,13 +14,6 @@ #include #include -// 0 = choose the workgroup width from M at launch (see r4d_act_threads in r4d_common.h). This -// kernel is not on the W4A8 path -- the rotated sibling is faster -- but it has the same -// one-workgroup-per-row shape, so it gets the same knob rather than being the odd one out. -#ifndef R4D_QAI8_THREADS -#define R4D_QAI8_THREADS 0 -#endif - template __global__ __launch_bounds__(THR) void r4d_quant_act_i8_kernel( const __hip_bfloat16* __restrict__ A, signed char* __restrict__ Q, float* __restrict__ S, @@ -60,20 +49,15 @@ __global__ __launch_bounds__(THR) void r4d_quant_act_i8_kernel( } } - - // --------------------------------------------------------------------------------------------- -// Same quantisation, plus the per-row per-group SUM of the int8 codes that an asymmetric weight -// grid needs: sum_k a_k (nibble_k - z_g) = sum_k a_k nibble_k - z_g * sum_k a_k, and the second -// factor depends only on the activation, so it is computed once here rather than N times in the -// GEMM. Output layout is [K/group][Mpad] -- GROUP-MAJOR, Mpad = ceil(M/16)*16 -- because in the -// GEMM a lane's eight accumulator elements are eight CONTIGUOUS output rows at one group, and the -// padding is what lets the GEMM read them as two aligned v4f instead of eight scalars. The caller -// allocates it zeroed; nothing writes the pad rows and the GEMM discards their outputs anyway. +// Same quantisation, plus the per-row per-group sum of the int8 codes for an asymmetric weight +// grid: sum_k a_k (nibble_k - z_g) = sum_k a_k nibble_k - z_g * sum_k a_k, and the second term is +// computed once here instead of N times in the GEMM. Output is [K/group][Mpad], group-major with +// Mpad = ceil(M/16)*16, because a lane's eight accumulator elements are eight contiguous rows at +// one group, read as two aligned v4f. The caller zeroes it; pad rows are never written. // -// The fragment permutation is a shuffle INSIDE each 16-element step and a group is a whole number -// of steps, so it does not change which elements belong to which group and the sum can be taken on -// either side of it. +// The fragment permutation stays within a 16-element step and a group is whole steps, so group +// membership is unchanged. #define R4D_QAI8_MAXG 256 template @@ -117,16 +101,14 @@ __global__ __launch_bounds__(THR) void r4d_quant_act_i8_asum_kernel( Asum[(size_t)g * Mpad + row] = (float)gs[g]; } -// The two launches, as the plugin ABI's RadLaunchFn: `(const RadArgs*, RadStream) -> int`. A -// refused shape is a status code, not a throw; see libr4d/r4d_args.h for why the entry point takes -// the ABI's argument list directly and needs no adapter in front of it. +// The plugin ABI entry point (RadLaunchFn); a refused shape is a status code, not a throw. See +// libr4d/r4d_args.h. // -// THE THIRD OUTPUT SELECTS THE FORM. Whether the caller wants the per-group row sums that an -// asymmetric weight grid subtracts is a property of the CALL, not of the model, so this is one -// row with a branch rather than two rows a constraint cannot tell apart. +// The optional fourth operand (asum) selects the form: the row sums are a property of the call, +// so this is one row with a branch rather than two rows a constraint cannot tell apart. enum { QA_X = 0, QA_Q, QA_S, QA_ASUM }; -static int rad_quant_act_i8_body(const RadArgs* args, const R4dSink& sk) { +extern "C" int r4d_rad_quant_act_i8(const RadArgs* args, RadStream stream) { int emit_rc = RAD_OK; const RadTensor* x = r4d_opt(args, QA_X); const RadTensor* q = r4d_opt(args, QA_Q); @@ -141,11 +123,11 @@ static int rad_quant_act_i8_body(const RadArgs* args, const R4dSink& sk) { if (K % 16) return R4D_NO(RAD_E_SHAPE); // a k step is sixteen bytes of one row if (r4d_numel(q) != M * K) return R4D_NO(RAD_E_SHAPE); - const int thr = R4D_QAI8_THREADS ? R4D_QAI8_THREADS : r4d_act_threads((int)M, (int)K); + const int thr = r4d_act_threads((int)M, (int)K); // the workgroup width, from M if (!as) { -#define R4D_QAI8_LAUNCH(T) emit_rc = R4D_EMIT(sk, (r4d_quant_act_i8_kernel), dim3((int)M), \ - dim3(T), 0, (const __hip_bfloat16*)r4d_p(x), (signed char*)r4d_wp(q), \ +#define R4D_QAI8_LAUNCH(T) emit_rc = R4D_EMIT(stream, (r4d_quant_act_i8_kernel), \ + dim3((int)M), dim3(T), 0, (const __hip_bfloat16*)r4d_p(x), (signed char*)r4d_wp(q), \ (float*)r4d_wp(sc), (int)K) switch (thr) { case 128: R4D_QAI8_LAUNCH(128); break; @@ -162,12 +144,12 @@ static int rad_quant_act_i8_body(const RadArgs* args, const R4dSink& sk) { const long long group = r4d_geti_or(args, "group", R4D_W4_GROUP); if (group < 1 || K % group) return R4D_NO(RAD_E_SHAPE); if (K / group > R4D_QAI8_MAXG) return R4D_NO(RAD_E_SHAPE); // the LDS accumulator's bound - // asum is [K/group][Mpad] with Mpad = ceil(M/16)*16 -- GROUP-MAJOR, and padded, because the - // asymmetric GEMM reads it a whole n-tile at a time. Sizing it from M alone overruns. + // asum is [K/group][Mpad], Mpad = ceil(M/16)*16, because the asymmetric GEMM reads whole + // 16-row tiles. Sizing it from M alone overruns. const long long mpad = ((M + 15) / 16) * 16; if (r4d_numel(as) < (K / group) * mpad) return R4D_NO(RAD_E_SCRATCH); -#define R4D_QAI8A_LAUNCH(T) emit_rc = R4D_EMIT(sk, (r4d_quant_act_i8_asum_kernel), \ +#define R4D_QAI8A_LAUNCH(T) emit_rc = R4D_EMIT(stream, (r4d_quant_act_i8_asum_kernel), \ dim3((int)M), dim3(T), 0, (const __hip_bfloat16*)r4d_p(x), (signed char*)r4d_wp(q), \ (float*)r4d_wp(sc), (float*)r4d_wp(as), (int)K, (int)group, (int)mpad) switch (thr) { @@ -180,4 +162,3 @@ static int rad_quant_act_i8_body(const RadArgs* args, const R4dSink& sk) { #undef R4D_QAI8A_LAUNCH return emit_rc; } -R4D_ENTRY(r4d_rad_quant_act_i8, rad_quant_act_i8_body) diff --git a/libr4d/r4d_rmsnorm_had_quant_i8.hip b/libr4d/r4d_rmsnorm_had_quant_i8.hip index b65b3b74..9a5cd833 100644 --- a/libr4d/r4d_rmsnorm_had_quant_i8.hip +++ b/libr4d/r4d_rmsnorm_had_quant_i8.hip @@ -1,53 +1,42 @@ -// r4d_rmsnorm_had_quant_i8.hip - r4d_rmsnorm_had_quant_i8: the residual add, the RMS norm, the block -// Hadamard and the int8 activation quantiser, in one pass over the row. +// r4d_rmsnorm_had_quant_i8.hip - r4d_rmsnorm_had_quant_i8: the residual add, the RMS norm, the +// block Hadamard and the int8 activation quantiser, in one pass over the row. // -// WHY FUSE. W4A8 needs a rotated int8 activation in front of every quantised linear, and there are -// four such inputs per layer -- 256 per decode step at 64 layers. As separate kernels that is -// 0.4-1.0 ms of pure launch on a step the whole project is trying to get to ~19 ms, and it is launch -// count rather than bandwidth: the arithmetic is ~14 ops per element and the traffic is 50 MB. -// Production pays none of it today because vLLM already fuses its fp8 quantiser into the norm, so a -// standalone rotate-and-quantise would be a REGRESSION against the thing it is trying to beat. -// Fused, the rotation and the quantiser both ride on a pass that already has the row in registers. +// W4A8 needs a rotated int8 activation in front of every quantised linear: four per layer, 256 per +// decode step at 64 layers. As separate kernels that is 0.4-1.0 ms of launch overhead per step +// (the arithmetic is ~14 ops per element), and vLLM's fp8 path already fuses its quantiser into the +// norm. Fused, the rotation and quantiser ride on a pass that already has the row in registers. // -// WHAT IT WRITES. Two consumers, not one. The int8 output feeds r4d_gemm_w4a8_nt_m64 in the byte -// order its A fragment reads. The bf16 output is optional and exists because a GDN block's -// in_proj_a and in_proj_b are in modules_to_not_convert, stay bf16, and read the SAME post-norm -// tensor -- pass a null pointer on the layers that have no such consumer and the write is skipped. -// The bf16 written is the UNROTATED norm output, so those two projections keep their original -// weights; rotating them offline instead would round W_a into bf16 for no gain. +// Outputs: the int8 row in r4d_gemm_w4a8_nt_m64's A-fragment byte order, and optionally the bf16 +// unrotated norm output for a GDN block's in_proj_a / in_proj_b, which are in +// modules_to_not_convert and read the same post-norm tensor (null skips the write). They keep +// their original weights; rotating them offline would round W_a into bf16 for no gain. // -// `wadd` IS ADDED TO EVERY GAIN, AND IT IS NOT A CONVENIENCE. Qwen3.5/Qwen3-Next norms are -// GemmaRMSNorm, which is `x_hat * (1 + w)` with a ZERO-CENTRED gamma, and vLLM forms that gain as -// `weight.float() + 1.0` -- in fp32. Rounding `1 + w` to bf16 first throws away most of w: near 1 -// a bf16 ULP is 2^-7, so a gain that should be 1.0031 becomes 1.0000, a 0.3% per-channel error that -// is systematic rather than random and is far larger than anything the int8 quantiser does. Adding -// it here, after the bf16 load and inside the fp32 arithmetic, is bit-identical to what vLLM -// computes and costs one v_add_f32 per element. Pass 0.0f for a plain (Llama-style) RMS norm. +// `wadd` is added to every gain: Qwen3.5/Qwen3-Next norms are GemmaRMSNorm, `x_hat * (1 + w)` with +// a zero-centred gamma, which vLLM forms as `weight.float() + 1.0` in fp32. Rounding `1 + w` to +// bf16 first loses most of w (a bf16 ULP near 1 is 2^-7, so 1.0031 becomes 1.0000), a systematic +// 0.3% per-channel error far larger than the int8 quantiser's. Added here after the bf16 load, in +// fp32, it matches vLLM bit for bit. Pass 0.0f for a plain (Llama-style) RMS norm. // -// The residual is updated in place exactly as vLLM's fused_add_rms_norm does: residual += x first, -// then the norm is taken of the sum. Pass a null residual for the non-additive form. +// The residual is updated in place as vLLM's fused_add_rms_norm does: residual += x, then the norm +// of the sum. A null residual is the non-additive form. // -// THE TRANSFORM DOES NOT HAVE TO WAIT FOR THE NORM. A sum of squares closes only after the whole -// row is seen, which looks like it forces the rotation behind a barrier. But the FWHT is LINEAR -// and `inv_rms` is a per-row SCALAR, so FWHT(x * Wg * inv_rms) = inv_rms * FWHT(x * Wg): the -// transform can run before the norm is known. And since the int8 codes are -// round(value * 127 / absmax(value)), a positive scalar cancels out of them entirely -- so inv_rms -// touches nothing but S[row], exactly like the 1/sqrt(had) it already carries. The sum of squares -// and the row max then reduce in the SAME barrier. +// The transform does not wait for the norm: the FWHT is linear and `inv_rms` a per-row scalar, so +// FWHT(x * Wg * inv_rms) = inv_rms * FWHT(x * Wg). A positive scalar cancels out of the int8 codes +// (round(value * 127 / absmax(value))), so inv_rms only enters S[row], like 1/sqrt(had). The sum of +// squares and the row max reduce behind the same barrier. // -// THE ROW NEVER GOES THROUGH LDS TWICE. The reduction still splits the kernel in two, and staging -// the row in LDS across it costs an LDS write, read and rewrite per element -- enough to put this -// kernel at 3.5x the plain quantiser at M=4096, where the sibling `gated_had_quant_i8`, which has -// no such pass, is 1.4x. The wave instead KEEPS its blocks in registers across the reduction: ~34 -// floats per lane at the widest per-rank K, and LDS is touched once, for the permuted store. +// The row goes through LDS once: staging it across the reduction and rewriting it costs an LDS +// write, read and rewrite per element (3.5x the plain quantiser at M=4096, against 1.4x for +// gated_had_quant_i8). Each wave keeps its blocks in registers across the reduction (~34 floats per +// lane at the widest per-rank K); LDS holds only the permuted store's source. // -// Re-reading the residual from memory in pass 2 is NOT an alternative: it is stored as bf16, and -// normalising from a bf16-rounded sum produces thousands of +/-1 code errors and a 1e-3 scale -// error against 5e-7. Storing bf16 is correct -- it is what the next layer reads -- normalising -// from it is not. +// Re-reading the residual in a second pass is not an alternative: it is stored as bf16, and +// normalising from the bf16-rounded sum gives thousands of +/-1 code errors and a 1e-3 scale error +// (against 5e-7). Storing bf16 is correct, since the next layer reads it; normalising from it is +// not. // -// NORMALISATION. As in r4d_had_quant_act_i8, the butterfly computes the UNNORMALISED transform and -// the row scale carries the 1/sqrt(had), so no pass is spent scaling by a constant. +// As in r4d_had_quant_act_i8, the butterfly computes the unnormalised transform and the row scale +// carries the 1/sqrt(had). #include "r4d.h" #include "r4d_args.h" #include "r4d_common.h" @@ -56,14 +45,8 @@ #include #include -// 0 = choose the workgroup width from M at launch (see r4d_act_threads in r4d_common.h); a -// non-zero build-time value pins one width instead. -#ifndef R4D_RHQ_THREADS -#define R4D_RHQ_THREADS 0 -#endif - -// Register staging bound: blocks-per-wave * VPL floats per lane. ~K/256 at NW=8, so 72 covers -// every per-rank K up to 18432 and every compiled width. +// Register staging bound: blocks-per-wave * VPL floats per lane, ~K/256 at NW=8, so 72 covers +// every per-rank K up to 18432 at every compiled width. #define R4D_RHQ_MAXVALS 72 template @@ -82,8 +65,8 @@ __global__ __launch_bounds__(THR) void r4d_rmsnorm_had_quant_i8_kernel( const int lane = threadIdx.x & 31, wave = threadIdx.x >> 5; const int nblk = K / HAD; - // Kept only when a bf16 consumer wants the unrotated norm output, since that one DOES need - // inv_rms and so cannot be written before the reduction. + // Kept only for the bf16 consumer: the unrotated output needs inv_rms, so it cannot be written + // before the reduction. float u[WOUT ? MAXB : 1][VPL]; float ss = 0.f, m = 0.f; @@ -144,10 +127,9 @@ __global__ __launch_bounds__(THR) void r4d_rmsnorm_had_quant_i8_kernel( // The launch, as the plugin ABI's RadLaunchFn. See the note at the head of r4d_quant_act_i8.hip. // -// THE RESIDUAL AND THE BF16 ECHO ARE OPTIONAL OPERANDS, and each one changes what this computes: -// with a residual it is `add` then `rmsnorm` then the quantiser, without it just the last two. -// That is why the fusion declaration (RadFuseFn) has to be handed the present-operand mask -- the -// CHAIN LENGTH depends on an operand rather than on a parameter. +// The residual and the bf16 echo are optional operands that change the computed chain: with a +// residual it is `add`, `rmsnorm`, quantiser; without, the last two. So the fusion declaration +// (RadFuseFn) takes the present-operand mask, since the chain length depends on an operand. enum { RN_X = 0, RN_RESID, RN_W, RN_Q, RN_S, RN_OUTBF16 }; extern "C" int r4d_rad_rmsnorm_had_quant_i8(const RadArgs* args, RadStream stream) { @@ -171,16 +153,15 @@ extern "C" int r4d_rad_rmsnorm_had_quant_i8(const RadArgs* args, RadStream strea const long long had = r4d_geti_or(args, "group", 0); if (had != 128 && had != 256 && had != 512) return R4D_NO(RAD_E_SHAPE); - // A rotation block cannot straddle a tensor-parallel shard boundary, and this is the check that - // catches a width the split cannot carry: down_proj is 8704 per rank, so 1024 is unavailable. + // A rotation block cannot straddle a tensor-parallel shard: down_proj is 8704 per rank, so 1024 + // is unavailable. if (K % had) return R4D_NO(RAD_E_SHAPE); const float eps = (float)r4d_getf(args, "eps", 1e-6); - // GemmaRMSNorm stores a zero-centred gamma and uses `1 + w`; forming that in bf16 first costs - // 0.3% per channel, so it is added in fp32 after the load. 0 is a plain RMS norm. + // GemmaRMSNorm's `1 +`, added in fp32 after the load (see the file header); 0 = plain RMS. const float wadd = (float)r4d_getf(args, "wadd", 0.0); - const int thr = R4D_RHQ_THREADS ? R4D_RHQ_THREADS : r4d_act_threads((int)M, (int)K); + const int thr = r4d_act_threads((int)M, (int)K); if ((K / had + thr / 32 - 1) / (thr / 32) * (had / 32) > R4D_RHQ_MAXVALS) return R4D_NO(RAD_E_SHAPE); // K too large for the register staging here const size_t shmem = (size_t)K * sizeof(float) + 2 * (thr / 32) * sizeof(float); @@ -191,7 +172,6 @@ extern "C" int r4d_rad_rmsnorm_had_quant_i8(const RadArgs* args, RadStream strea (__hip_bfloat16*)r4d_wp(rs), (const __hip_bfloat16*)r4d_p(w), (__hip_bfloat16*)r4d_wp(ob), \ (signed char*)r4d_wp(q), (float*)r4d_wp(sc), (int)K, eps, wadd, rn) #define R4D_RHQ_T(H, W) switch (thr) { \ - case 128: R4D_RHQ_LAUNCH(H, 128, W); break; \ case 256: R4D_RHQ_LAUNCH(H, 256, W); break; \ case 512: R4D_RHQ_LAUNCH(H, 512, W); break; \ case 1024: R4D_RHQ_LAUNCH(H, 1024, W); break; \ @@ -204,5 +184,5 @@ extern "C" int r4d_rad_rmsnorm_had_quant_i8(const RadArgs* args, RadStream strea #undef R4D_RHQ_W #undef R4D_RHQ_T #undef R4D_RHQ_LAUNCH - return RAD_OK; + return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); } diff --git a/libr4d/r4d_rmsnorm_quant_i8.hip b/libr4d/r4d_rmsnorm_quant_i8.hip index 6ceb0ba7..8e9bfc48 100644 --- a/libr4d/r4d_rmsnorm_quant_i8.hip +++ b/libr4d/r4d_rmsnorm_quant_i8.hip @@ -2,34 +2,32 @@ // r4d_gemm_w4a8_nt_m64 reads, in one pass over the row -- optionally with the residual junction // in front of it: a post-norm on the branch output, the residual add and a scalar on the sum. // -// WHY. A w4a8 linear needs its activation as int8 codes in the GEMM's fragment order with one f32 -// scale per row (r4d_quant_act_i8), and the producer of that activation is a norm. Unfused, a -// model whose linears take that grid issues the norm and the quantiser as two dispatches, and a +// A w4a8 linear needs its activation as int8 codes in the GEMM's fragment order with one f32 scale +// per row (r4d_quant_act_i8), produced by a norm. Unfused that is two dispatches, and a // sandwich-norm model (Gemma 2/3/4) issues four or five at every residual junction: // // rmsnorm(branch; w_post) -> add(residual) -> [scale] -> rmsnorm(residual; w) -> quant_act_i8 // -// each one a single workgroup over one row at a decode batch, so the step pays the dispatch, not -// the bytes. This is that chain as one dispatch. +// each a single workgroup per row at decode, so the step pays for dispatches, not bytes. This is +// the chain as one dispatch. // -// BYTE-IDENTICAL TO THE CHAIN IT REPLACES, not merely close, because the engine's greedy output is -// compared byte for byte across builds. What makes that hold: +// Byte-identical to the chain, because the engine's greedy output is compared byte for byte across +// builds: // -// * every intermediate the chain stores in bf16 is rounded to bf16 here too, and the next stage -// reads the rounded value: the post-norm output, the residual sum, the scaled residual and the -// norm output the quantiser takes its absmax and codes over; -// * both sums of squares are taken by the same partition the standalone norm uses -- the width -// r4d_act_threads(M, n) picks, thread t folding columns t, t+THR, ... in ascending order, then -// r4d_wave_sum and the waves in order through LDS (r4d_model_bf16.hip's rmsnorm_kernel and -// block_sum, which this copies rather than shares only because that one lives in another unit); -// * the arithmetic of every element is written the way the standalone kernels write it -- -// `x * s * (g + wadd)`, `a + b`, `x * scalar`, `fmaxf(m, 1e-8f) / 127.f` -- and the library is -// built with -ffp-contract=off, so no stage picks up an fma the chain does not have. +// * every intermediate the chain stores in bf16 is rounded to bf16 here and the next stage reads +// the rounded value: the post-norm output, the residual sum, the scaled residual and the norm +// output the quantiser reduces over; +// * both sums of squares use the standalone norm's partition: the width r4d_act_threads(M, n) +// picks, thread t folding columns t, t+THR, ... in order, then r4d_wave_sum and the waves in +// order through LDS (copied from r4d_model_bf16.hip's rmsnorm_kernel and block_sum, which live +// in another unit); +// * each element's arithmetic matches the standalone kernels (`x * s * (g + wadd)`, +// `a + b`, `x * scalar`, `fmaxf(m, 1e-8f) / 127.f`), under -ffp-contract=off. // -// THE RESIDUAL IS READ AND WRITTEN, and nothing else reads it before this kernel is done: each -// thread rewrites only the columns it read, so the second pass reads its own writes back. +// The residual is read and written; each thread rewrites only the columns it read, so the second +// pass reads its own writes back. // -// Returns a negative code rather than throwing, for the reason given in r4d_gemm_fp8a8.hip. +// Returns a negative code instead of throwing, for the reason given in r4d_gemm_fp8a8.hip. #include "r4d.h" #include "r4d_args.h" #include "r4d_emit.h" @@ -44,8 +42,8 @@ constexpr uint32_t kWave = 32; __device__ __forceinline__ float bf2f(uint16_t h) { return __uint_as_float((uint32_t)h << 16); } // The standalone norm's reduction, verbatim (r4d_model_bf16.hip): the wave butterfly, then the -// waves summed IN ORDER by every thread out of LDS. `lds` must not be reused by a second -// reduction without a barrier between them -- the kernel below gives each its own array. +// waves summed in order by every thread from LDS. `lds` must not be reused by a second reduction +// without a barrier in between; the kernel below gives each its own array. template __device__ __forceinline__ float block_sum(float v, float* lds) { v = r4d_wave_sum(v); @@ -67,9 +65,9 @@ __device__ __forceinline__ float gain(const void* w, uint32_t i, bool f32) { // SCL: the sum is multiplied by the [1] scalar before it is stored and normalised. // `ybuf` holds the row's norm output for the fragment-order store, which reads across threads. // -// THE ROW BODY, from the junction on: `s1` is the post-norm's factor, already reduced over `xr` by -// the caller (the plain kernel below takes it off the row; the all-reduce form takes it off the -// reduced sum it has just stored). l2 and lm are this function's own reduction planes. +// The row body from the junction on: `s1` is the post-norm's factor, already reduced over `xr` by +// the caller (the plain kernel takes it off the row; the all-reduce form off the reduced sum it has +// just stored). l2 and lm are this function's own reduction planes. template __device__ __forceinline__ void junction_row( const uint16_t* __restrict__ xr, uint16_t* __restrict__ rr, const void* __restrict__ w, @@ -151,13 +149,13 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_i8_kernel( } // --------------------------------------------------------------------------------------------- -// THE SAME JUNCTION WITH THE TWO-RANK ALL-REDUCE THAT ALWAYS PRECEDES IT: the branch output is a -// rank's partial sum of a column-sharded linear (o_proj, down_proj), and the post-norm is of the -// WHOLE sum. ar_rmsnorm_quant_fp8's handshake, exact wire only: each block pushes the rows it owns -// into the peer's scratch slot as 16B words, publishes its flag, waits for the peer's, and reduces -// `f2bf(mine + peer)` back into `x` -- the bytes the standalone exact all-reduce stores, fp32 add -// commuting exactly so both ranks agree -- on the post-norm's own sum-of-squares pass. A block owns -// whole rows, one a block at a decode batch. +// The same junction with the two-rank all-reduce that precedes it: the branch output is a rank's +// partial sum of a column-sharded linear (o_proj, down_proj), and the post-norm is of the whole +// sum. ar_rmsnorm_quant_fp8's handshake, exact wire only: each block pushes its rows into the +// peer's scratch slot as 16B words, publishes its flag, waits for the peer's, and reduces +// `f2bf(mine + peer)` back into `x` (the standalone exact all-reduce's bytes; the fp32 add +// commutes, so both ranks agree) during the post-norm's sum-of-squares pass. A block owns whole +// rows, one per block at decode. #define R4D_ARQ8_SPIN_MAX 4000000000ULL __device__ __forceinline__ void arq8_store_rel(unsigned int* p, unsigned int v) { @@ -240,7 +238,7 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_kernel( // 7 scalar [1] optional multiplies the sum; needs the residual enum { RQ_X = 0, RQ_RES, RQ_W, RQ_Q, RQ_S, RQ_Y, RQ_WP, RQ_SC }; -static int rad_rmsnorm_quant_i8_body(const RadArgs* a, const R4dSink& sk) { +extern "C" int r4d_rad_rmsnorm_quant_i8(const RadArgs* a, RadStream stream) { int emit_rc = RAD_OK; const RadTensor* x = r4d_opt(a, RQ_X); const RadTensor* rs = r4d_opt(a, RQ_RES); @@ -271,14 +269,14 @@ static int rad_rmsnorm_quant_i8_body(const RadArgs* a, const R4dSink& sk) { const size_t lds = (size_t)n * sizeof(uint16_t); if (lds > 60 * 1024) return R4D_NO(RAD_E_SHAPE); - // THE SAME WIDTH AS rmsnorm_bf16 AND quant_act_i8 PICK, from the same function: it decides - // which columns a thread folds into each sum of squares, which is the byte-identity. + // The same width rmsnorm_bf16 and quant_act_i8 pick, from the same function: it decides which + // columns a thread folds into each sum of squares, hence the byte-identity. const int thr = r4d_act_threads((int)M, (int)n); const float eps = (float)r4d_getf(a, "eps", 1e-6); const float wadd = (float)r4d_getf(a, "wadd", 0.0); const uint32_t scf = sc ? (sc->dtype == RAD_F32) : 0u; -#define R4D_RQI8_T(WF, RS, PO, SC, T) emit_rc = R4D_EMIT(sk, \ +#define R4D_RQI8_T(WF, RS, PO, SC, T) emit_rc = R4D_EMIT(stream, \ (rmsnorm_quant_i8_kernel), dim3((uint32_t)M), dim3(T), lds, \ (const uint16_t*)r4d_p(x), (uint16_t*)r4d_wp(rs), r4d_p(w), r4d_p(wp), r4d_p(sc), scf, \ (signed char*)r4d_wp(q), (float*)r4d_wp(s), (uint16_t*)r4d_wp(y), (uint32_t)n, eps, wadd, \ @@ -301,7 +299,6 @@ static int rad_rmsnorm_quant_i8_body(const RadArgs* a, const R4dSink& sk) { #undef R4D_RQI8_T return emit_rc; } -R4D_ENTRY(r4d_rad_rmsnorm_quant_i8, rad_rmsnorm_quant_i8_body) // The fused all-reduce form's launch. The IPC arguments are r4d_ar_oneshot_2rank_exact's -- the // double-buffered scratch, the per-block flags and the device-resident sequence counters -- and the diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index c80af39e..f5b21fff 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -1,33 +1,25 @@ /* r4d_rows.cpp -- the libr4d row table, and the op schemas that go with it. * - * THIS IS THE TABLE -- the single declaration of what libr4d can serve. A KERNEL MISSING FROM THIS - * FILE IS INVISIBLE to every caller that asks rather than remembers, and a second table beside it - * drifts from it, so there is exactly one. + * This is the single declaration of what libr4d can serve: a kernel missing from this table is + * invisible to callers, and a second table would drift. * - * A row's constraints are the ENTRY POINT'S rules, restated here; each row says where its band - * came from, which is the question a reader of one of these rows actually has. Three things do not - * line up one-to-one with the kernel side's own spelling, and each is marked at the row that does - * it: + * A row's constraints restate its entry point's rules, and each row says where its band came from. + * Three things differ from the kernel side's spelling, each marked at the row: * - * 1. KEY NAMES. The kernel library's select() has its own parameter vocabulary; radiance's op - * schemas are docs/OPS.md's, because that is what an architecture plugin writes and what - * `libref` has to implement. Where the two differ the PREDICATE and its VALUE are the - * kernel's exactly and only the key is renamed, with the kernel-side key named in a comment. - * `K` -> `n` in the quantiser family, `had` -> `group` for the rotation width, and - * `q_dtype`/`kv_dtype` -> `dtype` for the dense vision kernel are the whole list. + * 1. Key names. Op schemas use docs/OPS.md's vocabulary (what architecture plugins write and + * libref implements). Where the kernel's select() differs, the predicate and value are the + * kernel's and only the key is renamed, with the kernel-side key in a comment: `K` -> `n` in + * the quantiser family, `had` -> `group` for the rotation width, and `q_dtype`/`kv_dtype` -> + * `dtype` for the dense vision kernel. * - * 2. ORDER IS `priority`, not position. Preference between two rows that both match is expressed - * by the R4D_PRIO_* constants, each of which names the kernel-side ordering it preserves - * (r4d_plugin.h). + * 2. Preference between matching rows is `priority`, not position: the R4D_PRIO_* constants, + * each naming the kernel-side ordering it preserves (r4d_plugin.h). * - * 3. ROWS WHOSE BAND COMES FROM THE ENTRY POINT ITSELF -- the tiled and prefill W4A8/W8A8 GEMMs, - * the asymmetric grids, `quant_act_i8_asum`, `gemm_w8a8_nt_m64`. Their constraints are read - * off the entry point's own rejection tests and its header prose rather than off a - * kernel-side registry row, and every one of them says so. + * 3. Some bands come from the entry point itself (the tiled and prefill W4A8/W8A8 GEMMs, the + * asymmetric grids, `quant_act_i8_asum`, `gemm_w8a8_nt_m64`): read off its rejection tests + * and header rather than a kernel-side registry row. * - * Every row is RAD_DOMAIN_DEVICE. libr4d is a gfx1201 kernel library; there is no host arm of any - * of this, and claiming one would tell the placement planner that a host execution site exists - * where it does not. + * Every row is RAD_DOMAIN_DEVICE: libr4d is a gfx1201 kernel library with no host execution site. */ #include "r4d_plugin.h" @@ -40,11 +32,10 @@ #define ROW(a) (a), (int)(sizeof(a) / sizeof((a)[0])) #define NELEM(a) ((int)(sizeof(a) / sizeof((a)[0]))) -/* Parameter kinds, spelled once. A real-valued parameter is RAD_P_F64 (docs/OPS.md, "The four - * rules"): eps, scale, theta, softplus_thr, l2_eps and wadd are all real, and round-tripping one - * through a "%.9g" string is exact for an IEEE single but unreadable in a graph dump. RAD_DERIVED - * is a value the KERNEL supplies rather than the caller -- `block_size` and `chunk` -- and a - * constraint on one is skipped during matching and read back off the winner (spec §7.2). */ +/* Parameter kinds. Real-valued parameters (eps, scale, theta, softplus_thr, l2_eps, wadd) are + * RAD_P_F64 (docs/OPS.md, "The four rules"). RAD_DERIVED is a value the kernel supplies, not the + * caller (`block_size`, `chunk`); a constraint on one is skipped during matching and read back off + * the winner (spec §7.2). */ #define P_INT(k) { (k), RAD_P_INT, RAD_REQUIRED } #define P_INTO(k) { (k), RAD_P_INT, RAD_OPTIONAL } #define P_INTD(k) { (k), RAD_P_INT, RAD_DERIVED } @@ -56,31 +47,28 @@ #define P_F64(k) { (k), RAD_P_F64, RAD_REQUIRED } #define P_F64O(k) { (k), RAD_P_F64, RAD_OPTIONAL } -/* Spelled the way the kernel side spells its own constraints, so a row can be compared against the - * entry point line for line. */ +/* Spelled as the kernel side spells its constraints, so a row compares line for line. */ #define C_EQ(k, v) { (k), RAD_C_EQ, (long long)(v), nullptr } #define C_LE(k, v) { (k), RAD_C_LE, (long long)(v), nullptr } #define C_GE(k, v) { (k), RAD_C_GE, (long long)(v), nullptr } #define C_DIV(k, v) { (k), RAD_C_DIV, (long long)(v), nullptr } #define C_IN(k, s) { (k), RAD_C_IN, 0, (s) } -/* EVERY KERNEL THAT TOUCHES A PEER'S MEMORY: the collectives push into the other ranks' scratch and - * raise their flags directly, so a machine whose cards cannot reach each other must not select - * them. The engine measures this at launch (rad_types.h, device.p2p). */ +/* Required by every kernel that touches a peer's memory: the collectives write the other ranks' + * scratch and flags directly. The engine measures this at launch (rad_types.h, device.p2p). */ #define C_P2P C_EQ(RAD_FACT_P2P, 1) /* libr4d's R4D_AR_TWOSHOT_WIDE_MAX_ELEMS, restated because this file must not include r4d.h. * r4d_ar_entry.hip static_asserts the two against each other. */ #define R4D_AR_TWOSHOT_WIDE_MAX_ELEMS 268435456 -/* The largest message, in elements, a 4- or 8-rank exact all-reduce keeps on the one-shot; above it - * the two-shot rows take it. 1 MiB of a 16-bit payload. The one-shot sends (ws-1)*N bytes a rank - * in one hop and the two-shot 2*(ws-1)/ws*N in two, so the one-shot wins while the second hop's - * latency outweighs the bytes it saves. The value is a separation, not a measured crossover: on - * Qwen3.8-Flash-Next (2560 wide, 5 KiB a row) the largest decode message is 640 KiB, at 32 - * sequences each verifying four tokens, and a 2048-token prefill chunk is 10 MiB, so any bound - * between the two sends decode one-shot and prefill two-shot. It is a multiple of 128 for the - * reason pAllReduce's `numel` gives. */ +/* The largest message, in elements (1 MiB of a 16-bit payload), a 4- or 8-rank exact all-reduce + * keeps on the one-shot; above it the two-shot rows take it. The one-shot sends (ws-1)*N bytes per + * rank in one hop, the two-shot 2*(ws-1)/ws*N in two, so the one-shot wins while the second hop's + * latency outweighs the bytes saved. The value separates decode from prefill rather than marking a + * measured crossover: on Qwen3.8-Flash-Next (5 KiB per row) the largest decode message is 640 KiB + * (32 sequences verifying four tokens) and a 2048-token prefill chunk is 10 MiB. A multiple of 128 + * (see pAllReduce's `numel`). */ #define R4D_AR_WIDE_ONESHOT_MAX_ELEMS 524288 #define R4D_XSTR(v) R4D_STR(v) #define R4D_STR(v) #v @@ -88,10 +76,9 @@ /* ==================================================================================== schemas * * The first plugin in hierarchy order to declare an op fixes its schema (spec §2.3), and this - * plugin sits ahead of `libref`. So where an op below carries operands or parameters that - * docs/OPS.md does not list, THAT IS A CHANGE TO THE VOCABULARY and it is called out at the - * schema, not buried: ref has to grow the same operand or the two plugins are refused against - * each other at load, which is the correct outcome and the reason the check exists. + * plugin sits ahead of `libref`. An operand or parameter that docs/OPS.md does not list is a + * vocabulary change and is called out at the schema: ref must grow the same one, or the two + * plugins are refused against each other at load. */ /* -------------------------------------------------------------------------------- attention */ @@ -99,33 +86,23 @@ static const RadParamSpec pAttnPaged[] = { P_INT("q_len"), P_INT("head_dim"), P_INT("gqa"), - /* SUPPLIED BY THE KERNEL, not the caller (spec §7.2): the block manager reads the paged block - * size OFF the resolved attention kernel, so a caller cannot state it in the query that - * resolves it. libr4d's rows answer 16. Declared RAD_REQUIRED it would make those rows - * unreachable by the only query anyone can ask. */ + /* Supplied by the kernel (spec §7.2): the block manager reads the paged block size off the + * resolved attention kernel, so the resolving query cannot state it. libr4d answers 16. */ P_INTD("block_size"), P_INT("causal"), P_INT("window"), P_STR("q_dtype"), P_STR("kv_dtype"), - /* The softmax scale is a model constant and libr4d takes it per launch. Absent, the shim uses - * 1/sqrt(head_dim), which is right for every model in scope and wrong for anything that - * scales its query differently -- so it is a parameter and not a hardcode. */ + /* The softmax scale, a model constant. Absent, the shim uses 1/sqrt(head_dim). */ P_F64O("scale"), - /* NOT IN docs/OPS.md, and needed at DECLARE: the split-KV scratch hook has to size the arena - * before there is a batch, and libr4d's split law reads the host-side context bound. Absent, - * the shim derives it from the block table's width, which is an upper bound and therefore - * safe. */ + /* Not in docs/OPS.md. Needed at declare: the split-KV scratch hook sizes the arena before + * there is a batch, and the split law reads the context bound. Absent, the shim uses the + * block table's width, a safe upper bound. */ P_INTO("max_ctx"), - /* The other two the scratch hook needs, and for the same reason: RadScratchFn is called at - * DECLARE, when the op has parameters and no tensors, and libr4d's split-KV partial buffer is - * num_seqs * q_len * q_heads * splits rows. q_heads and num_seqs are not derivable from - * anything else in this list -- gqa gives the ratio, not the count. - * - * `max_seqs` is the BOUND, not the step's sequence count, and that is correct rather than - * conservative: the scratch region is arena storage sized once for the worst step, so sizing - * it for max_seqs is what makes every later step fit. Absent, the shim falls back to the - * tensors, which exist at issue and not at declare. */ + /* Also for the scratch hook, which runs at declare with parameters but no tensors: the + * split-KV partial buffer is num_seqs * q_len * q_heads * splits rows, and gqa gives only the + * head ratio. `max_seqs` is the bound, since the scratch is sized once for the worst step. + * Absent, the shim falls back to the tensors, which exist only at issue. */ P_INTO("n_head"), P_INTO("max_seqs"), }; @@ -140,17 +117,16 @@ static const RadOperandSpec oAttnPaged[] = { { "out", RAD_OPD_OUT, 0 }, }; -/* attn_paged with gate_quant_fp8 folded into its merge: attn_paged's parameters and the two of - * gate_quant_fp8's that are not implied -- its `n` is `head_dim` and its rows are attn_paged's - * (token, head) pairs -- and attn_paged's operands, then the gate, the codes and the scales. `out` - * holds the gated bf16 product, which is where the in-place pair leaves it. */ +/* attn_paged with gate_quant_fp8 folded into its merge: attn_paged's parameters plus the two of + * gate_quant_fp8's that are not implied (its `n` is `head_dim`, its rows attn_paged's (token, + * head) pairs), then attn_paged's operands, the gate, the codes and the scales. `out` holds the + * gated bf16 product, as the in-place pair leaves it. */ static const RadParamSpec pAttnPagedGq[] = { P_INT("q_len"), P_INT("head_dim"), P_INT("gqa"), - /* REQUIRED here where attn_paged derives it: the cache's page size is read off the resolved - * attn_paged kernel, and the caller passes that value on rather than this op answering it a - * second time. */ + /* Required here, where attn_paged derives it: the caller passes on the page size read off + * the resolved attn_paged kernel. */ P_INT("block_size"), P_INT("causal"), P_INT("window"), @@ -159,9 +135,9 @@ static const RadParamSpec pAttnPagedGq[] = { P_F64O("scale"), P_INTO("max_ctx"), P_INTO("n_head"), - /* A capacity: the row launches by the block table's rows and checks its scratch against - * them, so a declare at a smaller step may bound it lower -- which the gated attention block - * does, because it sizes this op at the step (one launch a step on the sparse path). */ + /* A capacity: the row launches by the block table's rows and checks its scratch against them, + * so a declare may bound it lower. The gated attention block sizes this op per step (one + * launch per step on the sparse path). */ { "max_seqs", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_CAPACITY }, P_INT("group"), P_STR("act"), @@ -187,12 +163,15 @@ static const RadParamSpec pAttnDense[] = { P_INT("causal"), P_STR("dtype"), P_F64O("scale"), - /* libr4d's `max_seqlen` selects the query-block height and is a HOST-side bound on the - * cu_seqlens segments. Absent, the shim passes the total token count, which is a valid bound - * and picks the tall arm -- a speed choice, never a correctness one. */ + /* Selects the query-block height; a host-side bound on the cu_seqlens segments. Absent, the + * shim passes the total token count, a valid bound that picks the tall arm (speed only). */ P_INTO("max_seqlen"), /* attn_paged's window over a segment's own positions (docs/OPS.md); 0 is none. */ P_INTO("window"), + /* cu_seqlens read in units that many rows apart, and blocks of `block` rows from a segment's + * start that attend only within themselves (a chunked encoder's windows). */ + P_INTO("cu_div"), + P_INTO("block"), }; static const RadOperandSpec oAttnDense[] = { { "q", RAD_OPD_IN, 0 }, @@ -202,11 +181,9 @@ static const RadOperandSpec oAttnDense[] = { { "out", RAD_OPD_OUT, 0 }, }; -/* docs/OPS.md has `qk_norm_rope` (qkv in place, `theta`). libr4d's kernel is a DIFFERENT op: it - * splits a [q|gate] packed projection per head, writes q, k and the gate to three separate - * destinations, and takes a PRECOMPUTED cos/sin table rather than theta. One operand list cannot - * be both, so this is its own op name and `qk_norm_rope` stays available for a kernel that - * matches OPS.md. */ +/* Not docs/OPS.md's `qk_norm_rope` (qkv in place, `theta`): this kernel splits a packed [q|gate] + * projection per head, writes q, k and the gate to three destinations, and takes a precomputed + * cos/sin table. Hence its own op name. */ static const RadParamSpec pQkNormRopeGate[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "head_dim", RAD_P_INT, RAD_REQUIRED }, @@ -219,11 +196,9 @@ static const RadParamSpec pQkNormRopeGate[] = { { "cs_f32", RAD_P_INT, RAD_OPTIONAL }, /* cos_sin table is f32 rather than bf16 */ { "pos_i64", RAD_P_INT, RAD_OPTIONAL }, }; -/* THE q HALF IS OPTIONAL, WHICH IS THE K-ONLY FORM. `n_head` 0 passes no `q_gate`, no `q_w` and - * no `q_out`, and every head the op serves is then read from `k` at its own row pitch and written - * contiguously to `k_out`. That is not a special case bolted on: the k side IS the plain - * [tokens, heads, head_dim] reader, and the only thing the q side adds is the [q|gate] split. An - * input with no gate to split is a k. */ +/* The q half is optional (the k-only form): with `n_head` 0 there is no `q_gate`, `q_w` or + * `q_out`, and every head is read from `k` at its row pitch and written contiguously to `k_out`. + * The k side is the plain [tokens, heads, head_dim] reader; the q side only adds the split. */ static const RadOperandSpec oQkNormRopeGate[] = { { "q_gate", RAD_OPD_IN, 1 }, { "k", RAD_OPD_IN, 0 }, @@ -235,8 +210,8 @@ static const RadOperandSpec oQkNormRopeGate[] = { { "k_out", RAD_OPD_OUT, 0 }, { "gate_out", RAD_OPD_OUT, 1 }, }; -/* The prologue with kv_store folded in: its parameters and kv_store's, its operands and then - * kv_store's `v`, `slot_mapping` and `kv_cache` -- the `k` kv_store reads is `k_out`. */ +/* The prologue with kv_store folded in: its parameters and kv_store's, its operands, then + * kv_store's `v`, `slot_mapping` and `kv_cache`. kv_store's `k` is `k_out`. */ static const RadParamSpec pQkNormRopeGateKv[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "head_dim", RAD_P_INT, RAD_REQUIRED }, @@ -267,11 +242,9 @@ static const RadOperandSpec oQkNormRopeGateKv[] = { { "slot_mapping", RAD_OPD_IN, 0 }, { "kv_cache", RAD_OPD_INOUT, 0 }, }; -/* The table that operand reads, filled at each position's OWN row of a [max_ctx, rot] plane. It is - * the reason the fused prologue is reachable at all: nothing in the tree built such a table, and - * `theta` is not one of the fused op's parameters. `rot` and the two f64s are `rope`'s own, spelled - * the same way, because the two have to compute the same angles or the fusion is a different - * model. */ +/* 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. */ static const RadParamSpec pRopeTable[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "rot", RAD_P_INT, RAD_REQUIRED }, @@ -295,24 +268,19 @@ static const RadParamSpec pGdnConvPrep[] = { P_INT("M"), P_INT("head_k"), P_INT("head_v"), - /* The chunk length the gate cumsum is cut at is the same one gdn_chunk_scan tiles on, and that - * one belongs to the kernel. Declaring it here as anything but DERIVED gives the same number - * two sources, and a disagreement is a decay summed over the wrong span rather than a - * diagnostic. libr4d answers 64. */ + /* The gate cumsum's chunk is the one gdn_chunk_scan tiles on, which the kernel owns, so it + * is derived; a second source could sum a decay over the wrong span. libr4d answers 64. */ P_CHUNK("chunk"), P_INT("conv_width"), - /* The l2 norm's epsilon. libr4d has no argument for it -- it is 1e-6f in the kernel body, FLA's - * L2NORM_EPS -- so the shim accepts the key only at that value and refuses anything else by - * name rather than silently normalising at a different epsilon. */ + /* The l2 norm's epsilon, fixed at 1e-6f in the kernel (FLA's L2NORM_EPS). The shim accepts + * only that value. */ P_F64O("l2_eps"), P_F64O("softplus_thr"), }; -/* THE INPUTS COME FIRST AND THE OUTPUTS LAST. `a` and `b_gate` are the gate and beta projections, - * which the layer hands separately from x (x is the qkv slice); `cache_idx` is the conv-state slot - * each sequence owns and `has_init` says whether that slot holds a history. All four are optional - * in the SCHEMA -- libref reads a and b_gate out of the fused x row when they are absent -- - * and the first three are required by THIS shim, which dereferences them unconditionally and so - * returns RAD_E_INVAL naming them rather than reading a null. */ +/* Inputs first, outputs last. `a` and `b_gate` are the gate and beta projections, passed + * separately from x (the qkv slice); `cache_idx` is each sequence's conv-state slot and `has_init` + * whether it holds a history. All four are optional in the schema (libref reads a and b_gate out + * of the fused x row), but this shim requires the first three (RAD_E_INVAL naming them). */ static const RadOperandSpec oGdnConvPrep[] = { { "x", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, @@ -345,10 +313,9 @@ static const RadOperandSpec oGdnConvUpdate[] = { { "b", RAD_OPD_WEIGHT, 1 }, { "conv_state", RAD_OPD_INOUT, 0 }, { "state_idx", RAD_OPD_IN, 0 }, - /* REQUIRED. spec §10 makes speculative rollback part of this op's schema rather than an - * assumption: the conv window has already absorbed the rejected tokens and a rejection is a - * change of read offset. An op that lets the caller omit num_accepted is an op whose rollback - * contract is optional. A non-speculative decode passes all ones. */ + /* Required: speculative rollback is part of the schema (spec §10). The conv window has + * absorbed the rejected tokens, and a rejection changes the read offset. A non-speculative + * decode passes all ones. */ { "num_accepted", RAD_OPD_IN, 0 }, { "cu", RAD_OPD_IN, 0 }, { "q", RAD_OPD_OUT, 0 }, @@ -375,8 +342,7 @@ static const RadParamSpec pGdnChunkScan[] = { P_INT("head_v"), P_CHUNK("chunk"), P_F64O("scale"), - /* An fp16 SSM state costs less step time than an fp32 one and frees KV capacity, so which - * one a deployment runs is a declared choice. */ + /* An fp16 SSM state is faster than fp32 and frees KV capacity; a deployment declares which. */ P_INTO("state_fp16"), }; static const RadOperandSpec oGdnChunkScan[] = { @@ -390,39 +356,33 @@ static const RadOperandSpec oGdnChunkScan[] = { { "cu", RAD_OPD_IN, 0 }, { "o", RAD_OPD_OUT, 0 }, { "ht", RAD_OPD_OUT, 1 }, - /* The state slot each batch row owns. Optional: without it a row owns slot n, which is what - * a caller that hands slots out in batch order means. */ + /* The state slot each batch row owns. Optional: without it row n owns slot n. */ { "state_idx", RAD_OPD_IN, 1 }, }; -/* `norm_eps` and `norm_act` are libr4d's argument names; the vocabulary calls the folded gated - * norm's epsilon `eps` and its activation `act`, because that is what the unfused gdn_gated_rmsnorm - * calls them and one op composing another's arithmetic cannot rename its parameters. `act` is a - * NAME -- "silu" or "sigmoid" -- and not an integer: a graph dump reading `act=1` is precisely the - * "unclear what actually runs" complaint this engine exists to answer, and the shim maps the name - * to the integer libr4d's entry point wants. */ +/* libr4d's `norm_eps` and `norm_act` are `eps` and `act` here, as on the unfused + * gdn_gated_rmsnorm whose arithmetic the fold reproduces. `act` is a name ("silu" or "sigmoid") so + * graph dumps are readable; the shim maps it to the entry point's integer. */ static const RadParamSpec pGdnRecurrentUpdate[] = { P_INT("q_len"), P_INT("head_k"), P_INT("head_v"), - /* Stated rather than left to the value tensor's rank: 48 value heads against 16 key heads is - * the one geometry where guessing it from a flattened view gives a plausible wrong answer. */ + /* Stated rather than inferred from the value tensor: with 48 value heads against 16 key + * heads, a flattened view gives a plausible wrong count. */ P_INTO("n_head_v"), P_F64O("scale"), P_F64O("eps"), - /* The qk l2 norm's epsilon, 1e-6f in libr4d's kernel body and not an argument. The shim - * accepts the key at that value and refuses any other by name. */ + /* The qk l2 norm's epsilon, fixed at 1e-6f in the kernel; the shim accepts only that value. */ P_F64O("l2_eps"), P_F64O("softplus_thr"), P_STRO("act"), P_INTO("state_fp16"), - /* WHAT THE STATE CACHE MEANS, and the two forms produce the same `o` from a completely - * different `state`: "per_candidate" writes one full state per candidate token and needs - * 1 + n_spec distinct slots, "anchor" keeps one committed state a sequence and replays the - * accepted prefix onto it out of a scratch slot. Optional because the out-of-tree caller that - * shares this kernel has no RadArgs to declare it in and selects the arm by environment; a - * caller that DOES declare it is naming the shape its pool was sized for, and the entry point - * refuses the arm that disagrees rather than writing a state the pool cannot hold. */ + /* The state cache's meaning; both forms produce the same `o` from different `state`. + * "per_candidate" writes one full state per candidate token (1 + n_spec slots); "anchor" keeps + * one committed state per sequence and replays the accepted prefix onto it from a scratch slot. + * Optional because an out-of-tree caller sharing this kernel selects the form by environment. + * When declared it names the shape the pool was sized for, and the entry point refuses the + * other. */ P_STRO("state_form"), }; static const RadOperandSpec oGdnRecurrentUpdate[] = { @@ -435,34 +395,27 @@ static const RadOperandSpec oGdnRecurrentUpdate[] = { { "dt_bias", RAD_OPD_WEIGHT, 0 }, { "state", RAD_OPD_INOUT, 0 }, { "state_idx", RAD_OPD_IN, 0 }, - /* REQUIRED, for the same reason as on gdn_conv_update: the recurrent state has already - * absorbed the rejected tokens, so rollback is part of the schema and not an assumption - * (spec §10). A non-speculative decode passes all ones. */ + /* Required, as on gdn_conv_update: the state has absorbed the rejected tokens (spec §10). A + * non-speculative decode passes all ones. */ { "num_accepted", RAD_OPD_IN, 0 }, - /* cu IS AN OPERAND, in the same slot the sibling gdn_conv_update puts it. The decode kernel - * opens with `bos = cu[n], T = cu[n+1] - bos` and dereferences it before any null test, so a - * schema that omits it does not make it optional -- it hands the kernel a null and the launch - * faults. The two decode kernels run off one cu on one step, and the two schemas say so in one - * shape. */ + /* Required, in the same slot as on gdn_conv_update: the kernel reads `cu[n]` and `cu[n+1]` + * before any null test. Both decode kernels run off one cu per step. */ { "cu", RAD_OPD_IN, 0 }, { "z", RAD_OPD_IN, 1 }, { "norm_w", RAD_OPD_WEIGHT, 1 }, { "o", RAD_OPD_OUT, 0 }, - /* THE OUT PROJECTION'S QUANTISER, OPTIONAL AND FOLDED IN. `o` is read by exactly one thing, - * the fp8 out projection, and the standalone quant_act_fp8 between them costs a launch a layer - * for less work than the gap in front of it. The fold is only expressible because the group - * IS the row -- head_v is 128 and so is the fp8 block -- so the scale plane is one f32 per - * (token, value head) and the kernel's own workgroup already owns exactly that. Absent, the - * kernel writes bf16 only and the caller quantises separately; the prefill path does. */ + /* The out projection's quantiser, optional and folded in, saving a quant_act_fp8 launch per + * layer. Possible because head_v equals the fp8 block (128): the scale plane is one f32 per + * (token, value head), which one workgroup owns. Absent, the kernel writes bf16 only and the + * caller quantises separately (the prefill path). */ { "o_q", RAD_OPD_OUT, 1 }, { "o_scale", RAD_OPD_OUT, 1 }, }; -/* THE DECODE CONVOLUTION FOLDED INTO THE RECURRENT UPDATE. gdn_conv_update's only reader at - * decode is gdn_recurrent_update, so the pair's q, k and v are an intermediate: this op takes the - * convolution's inputs and the recurrent update's minus those three. The parameters are the - * union of the two ops' under their own names. `z` and `norm_w` are REQUIRED here: the fold is - * the decode shape, one workgroup per (sequence, value head), which is the shape the fused row +/* The decode convolution folded into the recurrent update. gdn_recurrent_update is the only + * reader of gdn_conv_update's q, k and v at decode, so this op takes the convolution's inputs and + * the recurrent update's minus those three; the parameters are the union of both. `z` and `norm_w` + * are required: the fold runs one workgroup per (sequence, value head), the shape the fused row * norm already forces. */ static const RadParamSpec pGdnConvRecurrentUpdate[] = { P_INT("q_len"), @@ -499,10 +452,9 @@ static const RadOperandSpec oGdnConvRecurrentUpdate[] = { { "o_scale", RAD_OPD_OUT, 1 }, }; -/* The GATED RESIDUAL. `hc_enter` and `hc_write` share a parameter list; `hc_read` adds the two - * switches the operand list is banded on -- `inject` 0 is the final mixer and `group` 0 is a read - * whose consumer wants bf16. Both DEFAULT ON, because every trunk connection wants both and the - * exceptions are two sites in a 48-layer model. */ +/* The gated residual. `hc_enter` and `hc_write` share a parameter list; `hc_read` adds the two + * switches its operand list depends on: `inject` 0 is the final mixer and `group` 0 a read whose + * consumer wants bf16. Both default on, as every trunk connection uses both. */ static const RadParamSpec pHcPlain[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_STR("dtype"), }; @@ -512,8 +464,8 @@ static const RadOperandSpec oHcEnter[] = { static const RadOperandSpec oHcWrite[] = { { "y", RAD_OPD_IN, 0 }, { "inj", RAD_OPD_IN, 0 }, { "h", RAD_OPD_INOUT, 0 }, }; -/* hc_write with the preceding all-reduce folded in: `y` is the message too, so it is INOUT -- - * the reduced sum lands in it exactly as the standalone collective leaves it. */ +/* hc_write with the preceding all-reduce folded in: `y` is also the message, so it is inout and + * holds the reduced sum as the standalone collective leaves it. */ static const RadParamSpec pArHcWrite[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_INT("world_size"), P_STR("dtype"), P_INTO("wire"), /* 0 = exact bf16, 6 = rotated 6-bit */ @@ -521,8 +473,8 @@ static const RadParamSpec pArHcWrite[] = { static const RadOperandSpec oArHcWrite[] = { { "y", RAD_OPD_INOUT, 0 }, { "inj", RAD_OPD_IN, 0 }, { "h", RAD_OPD_INOUT, 0 }, }; -/* moe_gather's parameters and operands, then ar_hc_write's: the gather's output IS the reduction's - * message, so it is one operand -- written by the gather half and reduced in place by the rest. */ +/* moe_gather's parameters and operands, then ar_hc_write's. The gather's output is the + * reduction's message, one operand written by the gather and reduced in place. */ static const RadParamSpec pArGatherHcWrite[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_INT("top_k"), P_INT("world_size"), P_STR("dtype"), P_STRO("act"), P_INTO("wire"), @@ -533,9 +485,9 @@ static const RadOperandSpec oArGatherHcWrite[] = { { "y", RAD_OPD_INOUT, 0 }, { "inj", RAD_OPD_IN, 0 }, { "h", RAD_OPD_INOUT, 0 }, }; -/* The MTP head's entry, for a model whose residual stream is `hc` wide. `ngroup` is the one thing - * the checkpoint cannot say -- hc rsqrts, one per sub-stream, or a single one over the whole wide - * row -- so it is a parameter and defaults to the grouped form every gated residual here uses. */ +/* The MTP head's entry, for a model whose residual stream is `hc` wide. `ngroup` (hc rsqrts, one + * per sub-stream, or one over the whole row) is not in the checkpoint, so it is a parameter; it + * defaults to the grouped form every gated residual here uses. */ static const RadParamSpec pMtpEnter[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_F64("eps"), P_STR("dtype"), P_F64O("wadd"), P_INTO("ngroup"), P_STRO("fc"), @@ -577,10 +529,8 @@ static const RadOperandSpec oGdnGatedRmsNorm[] = { { "o", RAD_OPD_OUT, 0 }, }; -/* Not in docs/OPS.md at all: the DFlash2 drafter's grouped dynamic depthwise convolution. It is a - * drafter op, so it has no unfused equivalent in the vocabulary and no ref implementation -- - * which means the drafter has no fallback for it. Stated here so that is a decision on the record - * (spec §17) and not a discovery. */ +/* Not in docs/OPS.md: the DFlash2 drafter's grouped dynamic depthwise convolution. It has no + * unfused equivalent and no ref implementation, so the drafter has no fallback (spec §17). */ static const RadParamSpec pDflashConv[] = { { "T", RAD_P_INT, RAD_REQUIRED }, { "hidden_size", RAD_P_INT, RAD_REQUIRED }, @@ -593,42 +543,36 @@ static const RadParamSpec pDflashConv[] = { static const RadOperandSpec oDflashConv[] = { { "x", RAD_OPD_IN, 0 }, { "delta", RAD_OPD_IN, 0 }, - /* A WEIGHT, not an input: `base_kernel` is a checkpoint parameter and the role is what puts - * it in the op's weight list -- which is what gives it a prefetch interval and a residency - * class. Declared as an input it would be a weight no op admits to using. */ + /* A weight: `base_kernel` is a checkpoint parameter, and the role gives it a prefetch + * interval and a residency class. */ { "base", RAD_OPD_WEIGHT, 0 }, { "out", RAD_OPD_OUT, 0 }, }; -/* The other half of the drafter that has no equivalent anywhere else in the vocabulary: DFlash2's - * candidate selector. A block-diffusion drafter computes every position of a block in one pass, so - * position l+1 cannot be conditioned on the token chosen at position l -- the selector is what puts - * that dependence back, as a low-rank bilinear score on the EDGE between consecutive positions plus - * a greedy walk over those scores. +/* DFlash2's candidate selector, also without an equivalent in the vocabulary. A block-diffusion + * drafter computes every position of a block in one pass, so position l+1 cannot condition on the + * token chosen at l; the selector restores that dependence with a low-rank bilinear score on the + * edge between consecutive positions and a greedy walk over the scores. * - * `M` is ranged and is the SEQUENCE count; `steps` is the draft depth and is not, because the block - * length is a property of the checkpoint (it was trained at one) and not of the step. Like - * dflash_conv this has no ref implementation, so the drafter has no host fallback -- on the record - * (spec §17), and the same decision for the same reason. */ + * `M` is ranged and counts sequences; `steps`, the draft depth, is fixed by the checkpoint's + * trained block length. No ref implementation, so no host fallback (spec §17). */ static const RadParamSpec pDflashSelect[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "steps", RAD_P_INT, RAD_REQUIRED }, { "top_k", RAD_P_INT, RAD_REQUIRED }, { "rank", RAD_P_INT, RAD_REQUIRED }, { "n_vocab", RAD_P_INT, RAD_REQUIRED }, - /* The stride between one sequence's anchor and the next INSIDE the `anchor` operand. It exists - * so the operand can be the step's own token_ids: a draft pass carries `block` ids a sequence, - * the anchor is the first of them, and the alternative is a second batch field holding a copy - * of every `block`-th entry. Absent means a packed [M] array. */ + /* The stride between consecutive sequences' anchors inside `anchor`, so the operand can be + * the step's token_ids (`block` ids per sequence, anchor first). Absent means a packed [M] + * array. */ { "anchor_stride", RAD_P_INT, RAD_OPTIONAL }, { "dtype", RAD_P_STR, RAD_REQUIRED }, }; static const RadOperandSpec oDflashSelect[] = { { "cand", RAD_OPD_IN, 0 }, { "unary", RAD_OPD_IN, 0 }, - /* OPTIONAL, and absent it is ones: the edge score drops from trilinear to a plain bigram - * ``, which is DSpark's Markov head. r4d_dflash_select_bf16.hip - * argues why that belongs in this walk and not in a head of its own. */ + /* Optional; absent means ones, and the edge score drops from trilinear to the bigram + * ``, DSpark's Markov head (see r4d_dflash_select_bf16.hip). */ { "hp", RAD_OPD_IN, 1 }, { "anchor", RAD_OPD_IN, 0 }, { "pred", RAD_OPD_WEIGHT, 0 }, @@ -639,59 +583,50 @@ static const RadOperandSpec oDflashSelect[] = { /* ------------------------------------------------------------------------------ collectives */ static const RadParamSpec pAllReduce[] = { { "world_size", RAD_P_INT, RAD_REQUIRED }, - /* The message, in elements. Every block declares it as a RANGE -- a step carries its row - * count times the width -- so the selector cuts it into bands at the bounds the rows below - * place on it and resolves each band at its upper bound: init() sizes the peer scratch for - * that bound once, and the launch reads the real count off the tensor. A row's RAD_C_DIV on - * `numel` is therefore checked at a band's upper bound, so every bound a row here places on - * it is a multiple of 128, the largest DIV among them; a bound that was not would leave a - * band no DIV row could serve. */ + /* The message, in elements. Blocks declare it as a range (rows times width), so the selector + * cuts bands at the rows' bounds and resolves each at its upper bound; init() sizes the peer + * scratch for that bound and the launch reads the real count off the tensor. RAD_C_DIV is thus + * checked at a band's upper bound, so every bound here is a multiple of 128 (the largest DIV); + * otherwise some band would have no DIV row to serve it. */ { "numel", RAD_P_INT, RAD_REQUIRED }, { "dtype", RAD_P_STR, RAD_REQUIRED }, { "exact", RAD_P_INT, RAD_REQUIRED }, - /* The byte floor under which a LOSSY row must serve the message exactly anyway. Absent means - * the shim's own measured default. It is a parameter and not a constant because it is a - * property of the LINK, not of the kernel: the crossover sits where the rotate/pack/unpack - * stops costing more than the bytes it removes, and that is a bandwidth the deployment knows - * and the library does not. An exact row ignores it -- there is nothing to fall back to. */ + /* The byte floor below which a lossy row serves the message exactly. Absent means the shim's + * default. A parameter because the crossover (where rotate/pack/unpack stops costing more than + * the bytes it saves) depends on the link's bandwidth, which the deployment knows. Exact rows + * ignore it. */ { "min_bytes", RAD_P_INT, RAD_OPTIONAL }, - /* A caller's request for a one-shot (1) or two-shot (2). docs/OPS.md's schema is the union of - * every plugin's parameters and libref accepts it, so it stays declared here; no row of this - * plugin reads it, because the message size picks the two-shot (the all-reduce constraints - * below). */ + /* A request for one-shot (1) or two-shot (2). Declared because docs/OPS.md's schema is the + * union of every plugin's and libref accepts it; no row here reads it, since the message size + * picks the two-shot. */ { "hops", RAD_P_INT, RAD_OPTIONAL }, - /* 1 when the caller issues this collective on its second lane, beside compute (rad_lane). It - * picks the rows whose launch is narrow -- see tArLane -- and changes nothing the kernel - * computes. */ + /* 1 when issued on the caller's second lane, beside compute (rad_lane). Picks the rows with a + * narrow launch (tArLane); the result is unchanged. */ { "overlap", RAD_P_INT, RAD_OPTIONAL }, }; -/* docs/OPS.md has `x` -> `x` (inout). Every kernel here is safe in place -- the thread that - * overwrites a word of the input is the one that read it (r4d_ar_entry.hip says so per kernel) -- - * and every block issues it that way. The output is an optional SECOND operand for a caller that - * wants the sum somewhere else: absent means in place. */ +/* docs/OPS.md has `x` -> `x` (inout). Every kernel here is safe in place: the thread that + * overwrites a word of the input is the one that read it (r4d_ar_entry.hip). `y` is an optional + * second destination; absent means in place. */ static const RadOperandSpec oAllReduce[] = { { "x", RAD_OPD_INOUT, 0 }, { "y", RAD_OPD_OUT, 1 }, }; -/* No `exact` and no `hops`. A gather moves its payload, so there is no lossy wire to be told - * apart from and no second topology at two ranks. `numel` is this rank's CONTRIBUTION -- the - * output carries world_size times it -- and, like the all-reduce's, it is the bound init sizes - * the peer scratch from once rather than the count a given step passes. */ +/* No `exact` and no `hops`: a gather has no lossy wire and no second topology at two ranks. + * `numel` is this rank's contribution (the output holds world_size times it) and, as for the + * all-reduce, the bound init sizes the peer scratch from. */ static const RadParamSpec pAllGather[] = { { "world_size", RAD_P_INT, RAD_REQUIRED }, { "numel", RAD_P_INT, RAD_REQUIRED }, { "dtype", RAD_P_STR, RAD_REQUIRED }, - /* ONE ROW of this rank's contribution, in elements. Absent or 0 means the whole message is - * one row and `y` is the plain concatenation: rank r's slice at r * numel. Present, and the - * placement is ROW-INTERLEAVED -- x is [rows][row] and y is [rows][world_size][row] -- which - * is what the vocab-parallel candidate merge needs, because it reads one row of gathered - * candidates per sampled position at a single row stride and the concatenated form puts rank - * 1's row a whole message away from rank 0's. */ + /* One row of this rank's contribution, in elements. Absent or 0: the message is one row and + * `y` the plain concatenation, rank r's slice at r * numel. Present: row-interleaved, x + * [rows][row] and y [rows][world_size][row], so the vocab-parallel candidate merge reads each + * position's gathered candidates at one row stride. */ { "row", RAD_P_INT, RAD_OPTIONAL }, }; -/* Both REQUIRED (the third field is `optional`, not an index): unlike the all-reduce there is no - * in-place form, because the output is world_size times the input and cannot alias it. */ +/* Both required (the third field is `optional`): the output is world_size times the input, so + * there is no in-place form. */ static const RadOperandSpec oAllGather[] = { { "x", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 }, @@ -710,11 +645,10 @@ static const RadOperandSpec oGemmNt[] = { { "y", RAD_OPD_OUT, 0 }, }; -/* `pb1` and `pb2` are ParoQuant's, and the mxfp4a8 rows and the 4- and 5-bit asymmetric rows (w5a16, - * w4a16_asym, w4a8i8_asym, w5a8i8) read them: the weight's rows - * [0, pb1), [pb1, pb2) and [pb2, N) each meet their own copy of the activation, side by side in a - * row of `a` (so `a` is [M, parts * K]). 0 leaves a bound out. Optional, and absent from every - * other grid: a fused projection whose pieces were not rotated apart has one activation. */ +/* `pb1` and `pb2` are ParoQuant's, read by the mxfp4a8 rows and the 4- and 5-bit asymmetric rows + * (w5a16, w4a16_asym, w4a8i8_asym, w5a8i8): weight rows [0, pb1), [pb1, pb2) and [pb2, N) each + * meet their own copy of the activation, side by side in a row of `a` ([M, parts * K]). 0 leaves a + * bound out. Absent on other grids, where a fused projection has one activation. */ static const RadParamSpec pGemmNtQ[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "N", RAD_P_INT, RAD_REQUIRED }, @@ -725,21 +659,17 @@ static const RadParamSpec pGemmNtQ[] = { { "pb2", RAD_P_INT, RAD_OPTIONAL }, }; /* docs/OPS.md's `gemm_nt_q` is `a`, `a_scale`, `b`w, `b_scale`w -> `y`. Two of libr4d's six - * quantised GEMMs need a seventh operand each and neither is expressible as a weight aux stream, - * because RadLayout can DECLARE aux streams beside a weight but RadArgs has no way to DELIVER - * them to a launch: + * quantised GEMMs need a seventh operand. RadLayout can declare aux streams beside a weight, but + * RadArgs cannot deliver them to a launch (an ABI gap), so both are operands: * - * `a_sum` the per-row per-group sum of the int8 activation codes, which the ASYMMETRIC 4-bit - * and the 2-bit grids subtract to remove the stored zero point. It is produced by - * `quant_act_i8`'s third output, so it is activation-side and could never have been a - * weight aux in the first place. + * `a_sum` per-row per-group sums of the int8 activation codes, which the asymmetric 4-bit and + * the 2-bit grids subtract to remove the stored zero point. Produced by + * `quant_act_i8`'s third output, so activation-side. * `b_ref` MXFP4's per-output-row reference exponent, against which the E8M0 block scale is - * folded so the inner loop has no rescale. This one IS a weight aux and is exactly the - * case RadLayout.aux_tag was written for -- it just cannot be passed. + * folded so the inner loop needs no rescale. A weight aux in principle. * - * Both are appended after `y` so OPS.md's list stays a positional prefix and ref is unaffected - * until it implements a grid that needs them. That RadArgs cannot deliver a declared aux stream is - * a genuine gap in the ABI, not a shortcut taken here. */ + * Both follow `y`, so OPS.md's list stays a positional prefix and ref is unaffected until it + * implements a grid that needs them. */ static const RadOperandSpec oGemmNtQ[] = { { "a", RAD_OPD_IN, 0 }, { "a_scale", RAD_OPD_IN, 1 }, /* absent for the f16-activation grids (w4a16, w8a16) */ @@ -751,25 +681,19 @@ static const RadOperandSpec oGemmNtQ[] = { }; /* docs/OPS.md's `dequant` is activation-shaped (`M`(range) `n` `group` `dtype`). libr4d's - * dequant_w4_bf16 unpacks a WEIGHT out of WMMA fragment order back to row-major bf16, for the - * prefill path where W4A8 wins nothing. Its own op, with libr4d's own N/K keys, because calling a - * weight [N,K] an activation [M,n] would put the fragment-order inverse under a name that a - * sensible ref implementation would answer with a plain elementwise dequantiser. + * dequant_w4_bf16 unpacks a weight from WMMA fragment order to row-major bf16, for the prefill + * path where W4A8 gains nothing. It is its own op with N/K keys, so a ref implementation of + * `dequant` is never mistaken for the fragment-order inverse. * - * NOT ONE OF THE SIXTEEN SHARED OPS, whatever docs/OPS.md's resolved table says: `libref` - * declares `dequant`, not `dequant_w4`, so nothing here is negotiated with anything and the union - * rule leaves this schema as libr4d's own. The table's row also drops `twos`, which is load- - * bearing -- the symmetric grid's two's-complement nibble and the asymmetric grid's unsigned - * nibble minus a per-group zero differ by bit 3, and the wrong one is silently wrong -- and marks - * the two weight operands as plain inputs, which would stop the core resolving their handles. The - * schema here is the one the kernel needs; that table's row is not applied. */ + * libref declares `dequant`, not `dequant_w4`, so this schema is libr4d's alone (docs/OPS.md, + * "Quantisation and rotation"). */ static const RadParamSpec pDequantW4[] = { { "N", RAD_P_INT, RAD_REQUIRED }, { "K", RAD_P_INT, RAD_REQUIRED }, { "group", RAD_P_INT, RAD_REQUIRED }, { "dtype", RAD_P_STR, RAD_REQUIRED }, /* 1 = the symmetric grid's two's-complement nibble, 0 = the asymmetric grid's unsigned nibble - * minus a per-group zero. libr4d: "they differ by bit 3 and the wrong one is silently wrong". */ + * minus a per-group zero. They differ by bit 3, and the wrong one decodes silently wrong. */ { "twos", RAD_P_INT, RAD_REQUIRED }, }; static const RadOperandSpec oDequantW4[] = { @@ -778,30 +702,23 @@ static const RadOperandSpec oDequantW4[] = { { "y", RAD_OPD_OUT, 0 }, }; -/* `vocab_off` and `pairs` are the VOCAB-PARALLEL form and both are absent on a single-rank graph, - * which is what keeps that graph byte-identical to the unsplit form. With them, `x` is one rank's - * SLICE of a wider plane, `idx` carries GLOBAL columns, and `pairs` is an [M, R, 2] plane of (int32 - * id, float value) -- the plane `core/sample/sampler.h` holds as `buf_pairs_` -- which an - * all_gather moves so the ranks can agree on a global top-R without ever gathering the plane. */ /* ---- the routed mixture of experts ------------------------------------------------------------ * - * `moe_gemm_q` is a SEPARATE OP from docs/OPS.md's `moe_gemm`, for the same reason `gemm_nt_q` is - * separate from `gemm_nt`: the operand list differs -- an activation scale stream and a weight - * scale plane per expert -- and an op whose operand COUNT depends on a dtype string is an op whose - * positional arguments mean different things to different kernels. libref declares the same two. + * `moe_gemm_q` is a separate op from docs/OPS.md's `moe_gemm`, as `gemm_nt_q` is from `gemm_nt`: + * it adds an activation scale stream and a per-expert weight scale plane, and an operand count must + * not depend on a dtype string. libref declares both. * - * Both weight operands are RAD_OPD_WTAB and both carry one entry per expert, which is what lets - * the declaration divide evenly between them (core/build/rad_builder.cpp states that rule). */ + * Weight operands are RAD_OPD_WTAB with one entry per expert, so the declaration divides evenly + * between them (core/build/rad_builder.cpp). */ static const RadParamSpec pScaleRows[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_STR("dtype"), }; static const RadOperandSpec oScaleRows[] = { { "x", RAD_OPD_IN, 0 }, { "s", RAD_OPD_IN, 0 }, - /* Present = the fused gate-and-add form, `y = bf16(x * act(s)) + add`. It exists because the - * two ops are adjacent everywhere this is used -- a gated shared expert scales its output and - * then adds the routed arm to it -- and on the MoE block that pair is two dispatches a layer - * on ONE rank, which the other rank waits out inside the block's all-reduce. */ + /* Present = the fused gate-and-add form, `y = bf16(x * act(s)) + add`: a gated shared expert + * scales its output, then adds the routed arm. On the MoE block that pair runs on one rank + * while the other waits in the block's all-reduce, so fusing saves a dispatch per layer. */ { "add", RAD_OPD_IN, 1 }, { "y", RAD_OPD_OUT, 0 }, }; @@ -815,26 +732,24 @@ static const RadOperandSpec oRouterTopk[] = { }; static const RadParamSpec pMoeScatter[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"), - /* THIS RANK'S FIRST EXPERT ID -- what makes expert parallelism a parameter and not a second - * op. Absent or 0 is the whole-model case. */ + /* This rank's first expert id, so expert parallelism is a parameter, not a second op. Absent + * or 0 is the whole-model case. */ P_INTO("expert_base"), - /* THE EXPERTS SORTED LAST: a comma list of local indices, ascending. A layer that keeps a few - * experts at a higher precision serves them with a second grouped GEMM, and that GEMM takes a - * contiguous run of the offsets -- so their rows go after every other expert's, and the - * offsets and counts are in sort order. Absent is none. */ + /* Experts sorted last: a comma list of local indices, ascending. A layer that keeps a few + * experts at higher precision serves them with a second grouped GEMM over a contiguous run of + * offsets, so their rows go after all others and offsets and counts are in sort order. Absent + * is none. */ P_STRO("protect"), }; -/* THE PAIR AS ONE OP. Its parameters are the union of the two -- nothing new is computed, so - * nothing new is declared -- and its operands are their operands with the shared `expert_ids` - * named once, as an OUTPUT, because the fused form produces it rather than being handed it. */ +/* router_topk and moe_scatter as one op: the union of their parameters, and their operands with + * the shared `expert_ids` named once, as an output. */ static const RadParamSpec pRouterTopkScatter[] = { P_INT("M"), - /* THE ROUTER'S COUNT, which is every expert in the model: the router is replicated and each - * rank picks from all of them. */ + /* The router's count, every expert in the model: the router is replicated and each rank + * picks from all of them. */ P_INT("n_expert"), - /* THIS RANK'S SLICE, which the SORT runs over. Absent means the slice is the router, which is - * every deployment without expert parallelism. Under it the two counts differ, and one number - * serving both would either rank half the experts or overrun the histogram. */ + /* This rank's slice, which the sort runs over. Absent means the whole router (no expert + * parallelism). Under expert parallelism the two counts differ. */ P_INTO("n_local"), P_INT("top_k"), P_INT("norm"), P_STR("dtype"), P_INTO("expert_base"), @@ -848,11 +763,10 @@ static const RadOperandSpec oRouterTopkScatter[] = { { "expert_offset", RAD_OPD_OUT, 0 }, { "expert_count", RAD_OPD_OUT, 0 }, }; -/* THE ROUTER'S GEMM IN FRONT OF THAT PAIR, and the shared expert's one-column gate beside it: - * `gemm_nt` [M, K] x [n_expert, K]^T, then `router_topk_scatter` over what it wrote, and -- with - * `gate_b` and `gate` present -- `gemm_nt` at N = 1 over the same input. The parameters are the - * union again; N is `n_expert` for the router and 1 for the gate, so neither is a parameter. - * The logits stay an OUTPUT: the routing report and the debug paths read them after the step. */ +/* The router's GEMM before that pair, with the shared expert's one-column gate beside it: + * `gemm_nt` [M, K] x [n_expert, K]^T, `router_topk_scatter` over its output, and, with `gate_b` and + * `gate` present, `gemm_nt` at N = 1 over the same input. N is implied (n_expert, 1). The logits + * stay an output: the routing report and debug paths read them after the step. */ static const RadParamSpec pRouterGemmTopkScatter[] = { P_INT("M"), P_INT("K"), P_INT("n_expert"), P_INTO("n_local"), P_INT("top_k"), P_INT("norm"), P_STR("dtype"), @@ -877,24 +791,13 @@ static const RadOperandSpec oMoeScatter[] = { { "expert_offset", RAD_OPD_OUT, 0 }, { "expert_count", RAD_OPD_OUT, 0 }, }; -/* `a_order` is "token" or "sorted" and says which rows the ACTIVATION has: one per token, to be - * gathered through sorted_tok, or one per (token, slot) already in the scatter's order. The two - * grouped GEMMs of one routed block disagree about it -- gate_up reads the block input, down reads - * gate_up's output -- and it is a parameter rather than a row count because an operand whose - * meaning changes with its extent gives no way to tell the two readings apart. */ -/* THE EXPERTS ARE TWO TABLES, BY PARITY: `w`/`w_scale` hold the even-numbered experts and - * `w_odd`/`w_odd_scale` the odd ones, expert e being entry e / 2 of its class. A table's entries - * share one geometry, and a rank that holds an uneven slice of every expert's width -- three - * 128-column blocks of one parity's experts and two of the other's, which is how a five-block - * expert splits across two ranks evenly on average -- has two geometries. `N`/`K` are the even - * class's, `N_odd`/`K_odd` the odd class's and default to them. +/* `a_order` ("token" or "sorted") says which rows the activation has: one per token, gathered + * through sorted_tok, or one per (token, slot) already in scatter order. A routed block's two + * grouped GEMMs differ (gate_up reads the block input, down reads gate_up's output), and the row + * count alone cannot tell the readings apart. * - * `parts` is how many stacked parts the weight rows and the output columns both hold -- two for a - * fused gate/up. The output is as wide as the wider class, and a narrower class fills the leading - * columns of each output part and writes zeros after them. */ -/* `moe_gemm`, the unquantised op, is the vocabulary's and libref fixes its schema; this is the same - * schema, which the registry requires of any plugin that serves the op. ONE weight table: every - * entry has one geometry, and nothing about an unscaled plane forces the parity split above. */ + * `moe_gemm`, the unquantised op, has the vocabulary's schema, which libref fixes. It has one + * weight table: an unscaled plane needs no parity split (see moe_gemm_q). */ static const RadParamSpec pMoeGemm[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("n_expert"), P_INT("top_k"), P_STR("a_order"), P_STR("dtype"), @@ -906,6 +809,15 @@ static const RadOperandSpec oMoeGemm[] = { { "expert_offset", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 }, }; +/* The experts are two tables by parity: `w`/`w_scale` hold the even experts, `w_odd`/`w_odd_scale` + * the odd ones, expert e at entry e / 2 of its class. A table's entries share one geometry, and a + * rank holding an uneven slice of every expert's width (a five-block expert split across two ranks + * as three 128-column blocks of one parity and two of the other) has two. `N`/`K` are the even + * class's; `N_odd`/`K_odd` default to them. + * + * `parts` is how many stacked parts the weight rows and output columns hold (two for a fused + * gate/up). The output is as wide as the wider class; a narrower class fills the leading columns + * of each output part and writes zeros after them. */ static const RadParamSpec pMoeGemmQ[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("n_expert"), P_INT("top_k"), P_INT("group"), P_STR("a_order"), P_STR("dtype"), P_INTO("N_odd"), P_INTO("K_odd"), P_INTO("parts"), @@ -921,14 +833,12 @@ static const RadOperandSpec oMoeGemmQ[] = { { "w_odd_scale", RAD_OPD_WTAB, 0 }, { "y", RAD_OPD_OUT, 0 }, }; -/* THE SAME GEMM OVER FOUR CLASSES, BY THE EXPERT'S NUMBER MOD 4: `w`/`w_scale` hold class 0 at - * [N, K] and `w_q`/`w_q_scale` class q at [N_q, K_q], expert e being entry e / 4 of class e % 4. - * Four ranks splitting a five-block expert cannot share the extra block evenly over two classes -- - * whichever two ranks take it carry three blocks of every even/odd pair against the others' two -- - * and over four they can: rank r takes two blocks of class r and one of each other, five of every - * four experts. A separate op and not a parameter on `moe_gemm_q`, because the declaration divides - * a table op's weights over its table operands by count alone (core/build/rad_builder.cpp): the - * operand list is the class count. `y` follows the last class. */ +/* The same GEMM over four classes by expert number mod 4: `w`/`w_scale` hold class 0 at [N, K], + * `w_q`/`w_q_scale` class q at [N_q, K_q], expert e at entry e / 4 of class e % 4. Four ranks + * cannot share a five-block expert's extra block evenly over two classes, but can over four: rank + * r takes two blocks of class r and one of each other. A separate op, because the declaration + * divides a table op's weights over its table operands by count alone + * (core/build/rad_builder.cpp). `y` follows the last class. */ static const RadParamSpec pMoeGemmQMod4[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("n_expert"), P_INT("top_k"), P_INT("group"), P_STR("a_order"), P_STR("dtype"), P_INTO("N_1"), P_INTO("K_1"), P_INTO("N_2"), P_INTO("K_2"), @@ -951,28 +861,27 @@ static const RadOperandSpec oMoeGemmQMod4[] = { }; static const RadParamSpec pMoeGather[] = { P_INT("M"), P_INT("n"), P_INT("top_k"), P_STR("dtype"), - /* The shared arm's gate, and it is present exactly when `shared` and `shared_gate` are. - * "sigmoid" or "none", applying to the SCALAR -- the same spelling and the same meaning - * `scale_rows` gives it, because this is that op folded in. */ + /* The shared arm's gate, present exactly when `shared` and `shared_gate` are: "sigmoid" or + * "none", applied to the scalar, as in `scale_rows` (the op folded in). */ P_STRO("act"), }; static const RadOperandSpec oMoeGather[] = { { "y_expert", RAD_OPD_IN, 0 }, { "expert_w", RAD_OPD_IN, 0 }, { "sorted_tok", RAD_OPD_IN, 0 }, - /* PRESENT = THE SHARED ARM FOLDED IN, `y = bf16(shared * act(gate)) + gathered`. It is the - * `scale_rows` this op's output would otherwise be handed to, and the two narrows are - * load-bearing: the unfused pair writes the gather to a bf16 buffer and the product to another - * one before adding, so BOTH are rounded before the sum sees them. - * - * WHY IT IS WORTH A PAIR OF OPERANDS: the shared arm runs on ONE RANK, so the scale_rows it - * feeds is a dispatch a layer that the other rank waits out inside the block's all-reduce -- - * and with it gone the routed arm's `moe` buffer is never written either. */ + /* Present = the shared arm folded in, `y = bf16(shared * act(gate)) + gathered`, replacing + * the following `scale_rows`. Both terms are rounded to bf16 before the sum, as in the unfused + * pair. The shared arm runs on one rank, so this removes a dispatch per layer the other rank + * would wait out in the all-reduce, and the routed arm's `moe` buffer is never written. */ { "shared", RAD_OPD_IN, 1 }, { "shared_gate", RAD_OPD_IN, 1 }, { "y", RAD_OPD_OUT, 0 }, }; +/* `vocab_off` and `pairs` are the vocab-parallel form, both absent on a single-rank graph (which + * keeps it byte-identical to the unsplit form). With them, `x` is one rank's slice, `idx` carries + * global columns, and `pairs` is an [M, R, 2] plane of (int32 id, float value) (`buf_pairs_` in + * core/sample/sampler.h), which an all_gather moves so the ranks agree on a global top-R. */ static const RadParamSpec pRowTopk[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "N", RAD_P_INT, RAD_REQUIRED }, @@ -986,9 +895,9 @@ static const RadOperandSpec oRowTopk[] = { { "val", RAD_OPD_OUT, 0 }, { "pairs", RAD_OPD_OUT, 1 }, }; -/* The other half of that form: the k largest of the all-gathered per-rank candidate sets, in the - * same (idx, val) shape the single-rank top-R produces, so `dflash_select` downstream cannot tell - * which path it was handed. `R` is the width OUT; the input holds world_size * R of them. */ +/* The other half of that form: the R largest of the all-gathered per-rank candidates, in the + * (idx, val) shape the single-rank top-R produces, so `dflash_select` sees the same input either + * way. `R` is the output width; the input holds world_size * R. */ static const RadParamSpec pRowTopkMerge[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "R", RAD_P_INT, RAD_REQUIRED }, @@ -1025,11 +934,10 @@ static const RadParamSpec pQuantAct[] = { { "group", RAD_P_INT, RAD_REQUIRED }, { "dtype", RAD_P_STR, RAD_REQUIRED }, }; -/* docs/OPS.md gives `x` -> `q`, `scale`. The third output selects libr4d's `_asum` form, which - * additionally emits the [K/group][Mpad] group-major row sums the ASYMMETRIC weight grids - * subtract. One row, not two: whether the caller wants the sums is a property of the call and not - * of the model, so it belongs in the entry point exactly where spec §2.1 puts strides and - * alignment. */ +/* docs/OPS.md gives `x` -> `q`, `scale`. The optional third output selects libr4d's `_asum` form, + * which also emits the [K/group][Mpad] group-major row sums the asymmetric weight grids subtract. + * Whether the sums are wanted is a property of the call, so it is an operand of one op (spec + * §2.1). */ static const RadOperandSpec oQuantAct[] = { { "x", RAD_OPD_IN, 0 }, { "q", RAD_OPD_OUT, 0 }, @@ -1037,15 +945,10 @@ static const RadOperandSpec oQuantAct[] = { { "asum", RAD_OPD_OUT, 1 }, }; -/* `quant_act_fp8` is a NEW OP and this plugin fixes its schema. Shaped exactly on docs/OPS.md's - * `quant_act_i8` -- same params, same first three operands -- because it is the same op at a - * different width, and an architecture plugin that switches activation format should change one op - * name and nothing else. There is no `asum`: that output exists for the asymmetric integer grids, - * and an fp8 grid is symmetric by construction. - * - * libref implements it (ref_quant.cpp), so the whole block-scaled fp8 family has an oracle: - * without a reference for this op the GEMM that consumes its output could only ever be checked - * against activations libref quantised differently (spec §17). */ +/* `quant_act_fp8`, a new op whose schema this plugin fixes. Shaped on docs/OPS.md's + * `quant_act_i8` (same params, same first three operands), so switching activation format changes + * only the op name. No `asum`: fp8 grids are symmetric. libref implements it (ref_quant.cpp), which + * gives the block-scaled fp8 family an oracle (spec §17). */ static const RadParamSpec pQuantActFp8[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "n", RAD_P_INT, RAD_REQUIRED }, @@ -1058,9 +961,9 @@ static const RadOperandSpec oQuantActFp8[] = { { "scale", RAD_OPD_OUT, 0 }, }; -/* `givens_rotate` is ParoQuant's activation side for the 16-bit GEMMs, and libref declared this schema - * first (the loader refuses two that differ). The tables are the "givens" encoding's, as WEIGHT - * operands; see libref/ref_quant.cpp for the contract and r4d_givens_rotate.hip for the kernel. */ +/* `givens_rotate` is ParoQuant's activation side for the 16-bit GEMMs. libref declared this + * schema first (the loader refuses two that differ). The tables are the "givens" encoding's, as + * weight operands; see libref/ref_quant.cpp for the contract and r4d_givens_rotate.hip. */ static const RadParamSpec pGivensRotate[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "n", RAD_P_INT, RAD_REQUIRED }, @@ -1077,10 +980,10 @@ static const RadOperandSpec oGivensRotate[] = { { "y", RAD_OPD_OUT, 0 }, }; -/* `givens_dense_quant` is ParoQuant's activation quantiser, the rotation done by a dense per-group matrix on the - * matrix cores (r4d_givens_dense.hip). The matrices are the weight -- the givens encoding's "t.dense" table, - * which rad-convert composes -- so its tables are `tdense` and the channel scale `rscale`. - * `out` is the quantiser: "i8" (scale amax / 127) or "fp8" (E4M3, amax / 448), as q's dtype says. */ +/* `givens_dense_quant` is ParoQuant's activation quantiser, the rotation done by a dense per-group + * matrix on the matrix cores (r4d_givens_dense.hip). The matrices are the weight `tdense` (the + * givens encoding's "t.dense" table, composed by rad-convert), the channel scale `rscale`. `out` + * is the quantiser: "i8" (scale amax / 127) or "fp8" (E4M3, amax / 448), matching q's dtype. */ static const RadParamSpec pGivensDense[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "n", RAD_P_INT, RAD_REQUIRED }, @@ -1097,19 +1000,12 @@ static const RadOperandSpec oGivensDense[] = { { "scale", RAD_OPD_OUT, 0 }, }; -/* `gram_accum` is a NEW OP and this plugin fixes its schema. It is the calibration half of GPTQ: - * `h += x^T x` over an E4M3 activation, accumulated across every launch of a corpus. +/* `gram_accum`, a new op whose schema this plugin fixes: GPTQ's calibration half, `h += x^T x` + * over an E4M3 activation, accumulated across every launch of a corpus. * - * `h` IS INOUT AND THAT IS THE WHOLE OP. A caller zeroes it once and then drives a corpus through - * the graph; each launch adds its own block. Declaring it OUT would say the op overwrites, which - * is the one reading that makes the result wrong without making it fail. - * - * The operand names are `a` and `a_scale` rather than `x` and `scale` because they are the same - * pair `gemm_nt_q` takes in that order, and this op exists to characterise exactly the operand - * that GEMM contracts. - * - * `a_scale` IS OPTIONAL because an unquantised GEMM contracts a plain activation: dtype "bf16" - * reads `a` as it stands and takes no scale, which is the tap of a model served at bf16. */ + * `h` is inout: a caller zeroes it once and each launch adds its block. The operands are named `a` + * and `a_scale` as in `gemm_nt_q`, whose activation this characterises. `a_scale` is optional: + * dtype "bf16" reads a plain activation with no scale (a model served at bf16). */ static const RadParamSpec pGramAccum[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "n", RAD_P_INT, RAD_REQUIRED }, @@ -1122,36 +1018,29 @@ static const RadOperandSpec oGramAccum[] = { { "h", RAD_OPD_INOUT, 0 }, }; -/* `qsa_block_key` is a NEW OP and this plugin fixes its schema. It builds the QSA indexer's - * compressed key: one vector per `ratio` tokens of key history, which is what the indexer's - * scores are taken against. +/* `qsa_block_key`, a new op whose schema this plugin fixes: the QSA indexer's compressed key, one + * vector per `ratio` tokens of key history, which the indexer scores against. * - * `M` IS BLOCKS AND `k` IS `ratio` TIMES TALLER. Every other op in this vocabulary has one output - * row per input row; this one has one per four, and a caller that sized `k` at the block count - * would have every block pool three rows of the next one -- plausible numbers, different model. - * - * `pos0` IS A PARAMETER AND NOT AN OPERAND because blocks TILE the token stream: block i's first - * token is at `pos0 + i * ratio`, always. A caller with a discontiguous run issues it in runs, - * which is cheaper than a position operand every launch would have to build. */ + * `M` counts blocks and `k` is `ratio` times taller; unlike other ops, there is one output row per + * `ratio` input rows. `pos0` is a parameter because blocks tile the token stream (block i starts at + * `pos0 + i * ratio`); the optional `pos` operand serves non-contiguous blocks. */ static const RadParamSpec pQsaBlockKey[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "n", RAD_P_INT, RAD_REQUIRED }, { "ratio", RAD_P_INT, RAD_REQUIRED }, { "rotary_dim", RAD_P_INT, RAD_REQUIRED }, { "pos0", RAD_P_INT, RAD_OPTIONAL }, /* the tiling; a `pos` operand overrides it */ - /* THE SAME NUMBER AS `ratio`, AND IT IS HERE TO SIZE A KV GROUP. `Builder::find_kv_consumer` - * binds a group to the first op declared after it that carries the literal key `block_size`, - * so an op that wants to decide a group's page size has to spell it that way -- and the - * block-key store's page IS the compress block. The shim refuses a disagreement rather than - * picking one. */ + /* Equal to `ratio`; it sizes a KV group. `Builder::find_kv_consumer` binds a group to the + * first op declared after it with the key `block_size`, and the block-key store's page is the + * compress block. The shim refuses a mismatch. */ { "block_size", RAD_P_INT, RAD_OPTIONAL }, P_F64("eps"), P_F64("theta"), P_F64O("scale"), P_F64O("wadd"), { "dtype", RAD_P_STR, RAD_REQUIRED }, - /* THE LAYER'S ROTARY, when it has several position components: `mode` mrope or imrope and - * its `sections`, read against a [3, M] component-major `pos` list. Absent is NeoX. */ + /* The layer's rotary when it has several position components: `mode` mrope or imrope and its + * `sections`, against a [3, M] component-major `pos` list. Absent is NeoX. */ { "mode", RAD_P_STR, RAD_OPTIONAL }, { "sections", RAD_P_STR, RAD_OPTIONAL }, { "yarn_factor", RAD_P_F64, RAD_OPTIONAL }, @@ -1162,63 +1051,31 @@ static const RadParamSpec pQsaBlockKey[] = { static const RadOperandSpec oQsaBlockKey[] = { { "k", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, - /* OPTIONAL, and its presence changes where the answer goes rather than what it is. The - * block-key store is the PAGED KV group of docs/QSA.md, so block b of a sequence lives at - * whatever page the manager gave it and consecutive blocks are not consecutive pages. Absent, - * the write is contiguous -- a caller with its own scratch, or a test. Present, `M` comes off - * THIS operand and not off `out`, because `out` is then as tall as the pool. */ + /* Optional; it changes where the result goes. The block-key store is the paged KV group of + * docs/QSA.md, so a sequence's blocks live on arbitrary pages. Absent, the write is contiguous + * (own scratch, tests). Present, `M` comes from this operand, since `out` is as tall as the + * pool. */ { "page", RAD_OPD_IN, 1 }, - /* OPTIONAL, and it is what turns a launch from a RANGE into a LIST. `pos0 + b*ratio` is the - * tiling and serves a prefill chunk, where the completing blocks are a contiguous run of one - * sequence. It does not serve a decode step: the sequences in a batch are at different - * positions, so the blocks completing in one launch belong to different sequences and are not - * a run. With this, one launch a layer a step serves any mix. */ + /* Optional; turns the launch from a range into a list. `pos0 + b*ratio` serves a prefill + * chunk, whose completing blocks are one sequence's contiguous run. At decode the completing + * blocks belong to different sequences, so one launch per layer per step needs this list. */ { "pos", RAD_OPD_IN, 1 }, { "out", RAD_OPD_OUT, 0 }, }; -/* `qsa_score` is a NEW OP and this plugin fixes its schema. It is the indexer's vote: how much - * one query wants each compressed block of key history. +/* `qsa_work`, a new op whose schema this plugin fixes: the gather that turns a batch into the + * flat block list `qsa_block_key` reads. * - * `bt` IS A LIST OF PAGE IDS AND NOT BLOCK INDICES. The attention KV group is paged at the - * compress ratio, so a block and a page are the same thing and the sequence's existing block - * table is already the list this scores -- and the top-k over the output is already the block - * table the attention reads. That identity is the design (docs/QSA.md); an op that took block - * indices would put a translation on both sides of it. */ -/* `qsa_select` is a NEW OP and this plugin fixes its schema. It turns the scorer's numbers into - * the page-id table the attention reads. - * - * `nc` IS THE COMPLETE-BLOCK COUNT AND IS A SEPARATE OPERAND from the table's width, because the - * two differ by exactly the thing the op has to treat specially: `bt[nc]`, when it is not -1, is - * the PARTIAL page -- the tokens after the last complete block, which the reference attends - * unconditionally and which the query itself lives in. It is appended after the selection and is - * never a candidate for it. - * - * `sel` IS `topk + 1` WIDE for that reason and the last slot is not spare. */ -/* `qsa_tail_store` is a NEW OP and this plugin fixes its schema. It parks the raw index keys of - * the tokens that have not completed a block yet, so the next step can finish one. - * - * `cu` IS HOW A TOKEN FINDS ITS SEQUENCE, and it is the only operand in the batch that says so -- - * `slot_mapping` is a flat KV slot and carries no sequence. It is also where the sequence COUNT - * comes from at run time, rather than from any declared height, which is max_seqs. - * - * WHICH SEQUENCE'S STATE IS `sidx`, AND THAT IS A DIFFERENT QUESTION. `cu` says which ROW of this - * step a token is in; the row is step-local, so the keys have to be kept somewhere the engine - * keeps per SEQUENCE. That is a linear KV group, and `state` is its cache for this layer. */ -/* `qsa_work` is a NEW OP and this plugin fixes its schema. It is the gather that turns a batch - * into the flat block list `qsa_block_key` reads. - * - * `M` IS TOKENS AND `work` IS BLOCKS, and they are different numbers: one block a `ratio` tokens - * plus at most one straddling block a sequence. `work` is a HOST bound on how many blocks can - * complete, not a count of how many did -- the count is device data, and slots past it get - * `page = -1`, which is the sentinel `qsa_block_key` already skips. */ + * `M` counts tokens and `work` blocks (one per `ratio` tokens plus at most one straddling block + * per sequence). `work` is a host bound on how many blocks can complete; the actual count is + * device data, and slots past it get `page = -1`, which `qsa_block_key` skips. */ static const RadParamSpec pQsaWork[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "n", RAD_P_INT, RAD_REQUIRED }, { "ratio", RAD_P_INT, RAD_REQUIRED }, { "ring", RAD_P_INT, RAD_REQUIRED }, { "seqs", RAD_P_INT, RAD_REQUIRED }, - /* A capacity: the launch is as wide as `page`, whatever this says (r4d_qsa_work_bf16.hip). */ + /* A capacity: the launch is as wide as `page` (r4d_qsa_work_bf16.hip). */ { "work", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_CAPACITY }, { "dtype", RAD_P_STR, RAD_REQUIRED }, }; @@ -1226,25 +1083,30 @@ static const RadOperandSpec oQsaWork[] = { { "k", RAD_OPD_IN, 0 }, { "pos", RAD_OPD_IN, 0 }, { "cu", RAD_OPD_IN, 0 }, - /* THE TAIL IS THE STATE GROUP'S CACHE FOR THIS LAYER and `sidx` names the sequence's slot - * in it. Indexing it by the batch row instead would not survive a step: the row is - * step-local, the sequence is not. */ + /* The tail is the state group's cache for this layer; `sidx` names the sequence's slot (the + * batch row is step-local, the sequence is not). */ { "state", RAD_OPD_IN, 0 }, { "sidx", RAD_OPD_IN, 0 }, { "bt", RAD_OPD_IN, 0 }, - /* OPTIONAL: the step's rotary components, [3, T] (RadBatch::rope_pos). Present, `bpos` holds - * each block's first-token components as [3, work] -- what an M-RoPE layer's block key - * rotates at -- instead of its index. */ + /* Optional: the step's rotary components, [3, T] (RadBatch::rope_pos). Present, `bpos` holds + * each block's first-token components as [3, work], which an M-RoPE layer's block key rotates + * at, instead of its index. */ { "rope", RAD_OPD_IN, 1 }, { "stage", RAD_OPD_OUT, 0 }, { "page", RAD_OPD_OUT, 0 }, { "bpos", RAD_OPD_OUT, 0 }, - /* COMPLETE BLOCKS A SEQUENCE, which the scorer and the selection both need and which this op - * has already computed on its way to the work list. A separate op for one division a sequence - * would be a launch a layer a step for nothing. */ + /* Complete blocks per sequence, needed by the scorer and the selection and computed here on + * the way, which saves a launch per layer per step. */ { "nc", RAD_OPD_OUT, 0 }, }; +/* `qsa_tail_store`, a new op whose schema this plugin fixes: it keeps the raw index keys of + * tokens that have not completed a block, so a later step can finish it. + * + * `cu` is the only batch operand that maps a token to its sequence (`slot_mapping` is a flat KV + * slot), and it supplies the run-time sequence count; the declared height is max_seqs. `cu` gives + * the step-local row, so the keys live in a per-sequence linear KV group: `state` is its cache for + * this layer and `sidx` the sequence's slot. */ static const RadParamSpec pQsaTailStore[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "n", RAD_P_INT, RAD_REQUIRED }, @@ -1261,6 +1123,13 @@ static const RadOperandSpec oQsaTailStore[] = { { "sidx", RAD_OPD_IN, 0 }, }; +/* `qsa_select`, a new op whose schema this plugin fixes: it turns the scores into the page-id + * table the attention reads. + * + * `nc`, the complete-block count, is separate from the table width: `bt[nc]`, when not -1, is the + * partial page (tokens after the last complete block, where the query itself lives), which the + * reference always attends. It is appended after the selection and never competes in it, so `sel` + * is `topk + 1` wide. */ static const RadParamSpec pQsaSelect[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "blocks", RAD_P_INT, RAD_REQUIRED }, @@ -1273,21 +1142,23 @@ static const RadOperandSpec oQsaSelect[] = { { "bt", RAD_OPD_IN, 0 }, { "nc", RAD_OPD_IN, 0 }, { "pos", RAD_OPD_IN, 0 }, - /* `M` IS QUERIES AND `bt`/`nc` ARE PER SEQUENCE, so something has to join them: at decode one - * query a sequence made the two the same list, and at prefill a chunk's queries share one - * history and each selects its own set out of it (docs/QSA.md, Stage B). `cu` is the only - * operand in the batch that says which sequence a token belongs to. */ + /* `M` counts queries while `bt`/`nc` are per sequence; `cu` joins them. At prefill a chunk's + * queries share one history and each selects its own set (docs/QSA.md, "Per-query selection"). */ { "cu", RAD_OPD_IN, 0 }, { "sel", RAD_OPD_OUT, 0 }, { "nsel", RAD_OPD_OUT, 0 }, - /* `seqused` IS WHY QSA NEEDS NO NEW ATTENTION KERNEL. `attn_paged` takes its block table and - * its per-sequence length as ORDINARY OPERANDS -- the architecture reads them off the KV group - * batch and passes them -- so the sparse attention is the same op issued with `sel` in place - * of the table and this in place of the length. Emitted here rather than by an op of its own - * because it is one store off a number this kernel already has. */ + /* With `seqused`, QSA needs no new attention kernel: `attn_paged` takes its block table and + * per-sequence length as ordinary operands, so the sparse attention is the same op issued with + * `sel` and this. Emitted here because it is one store of a value this kernel has. */ { "seqused", RAD_OPD_OUT, 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. + * + * `bt` holds page ids, not block indices. The attention KV group is paged at the compress ratio, + * so a block is a page, the sequence's block table is the list scored, and the top-k over the + * output is the block table the attention reads (docs/QSA.md). */ static const RadParamSpec pQsaScore[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "n", RAD_P_INT, RAD_REQUIRED }, @@ -1300,27 +1171,24 @@ static const RadOperandSpec oQsaScore[] = { { "q", RAD_OPD_IN, 0 }, { "bk", RAD_OPD_IN, 0 }, { "bt", RAD_OPD_IN, 0 }, - /* See oQsaSelect's note: `M` is QUERIES and the table is the SEQUENCE's. */ + /* As in oQsaSelect: `M` counts queries and the table is the sequence's. */ { "cu", RAD_OPD_IN, 0 }, - /* THE BLOCK LOOP'S BOUND, and it is required rather than derived. `blocks` is a DECLARED - * width sized for max_ctx, so a scorer that trusted it would read 65536 padding entries a - * query on a 200-token prompt. `nc` is the sequence's live count, which is an upper bound for - * every query in the chunk; `qsa_select` narrows it to each query's own. */ + /* The block loop's bound, required. `blocks` is a declared width sized for max_ctx (65536 + * padding entries per query on a short prompt); `nc` is the sequence's live count, an upper + * bound for every query in the chunk, which `qsa_select` narrows per query. */ { "nc", RAD_OPD_IN, 0 }, { "score", RAD_OPD_OUT, 0 }, }; -/* `rmsnorm_quant_fp8` and `gated_quant_fp8` are NEW OPS and this plugin fixes their schemas. Each - * is its producer's operand list with the quantiser's two outputs appended and the producer's own - * bf16 output demoted to OPTIONAL -- so an architecture that fuses changes an op name, keeps the - * operands it already passed in the order it already passed them, and adds `q` and `scale`. +/* `rmsnorm_quant_fp8` and `gated_quant_fp8`, new ops whose schemas this plugin fixes. Each is its + * producer's operand list with the quantiser's two outputs added and the producer's bf16 output + * made optional, so an architecture that fuses changes only the op name and adds `q` and `scale`. * - * THE RESIDUAL IS SECOND, which is where `rmsnorm_had_quant_i8` puts it, so the two ops differ by - * the rotation and nothing else. It is what turns `add` + `rmsnorm` into one launch: a block adds - * the PREVIOUS block's delta into the shared residual stream at the front of its own norm rather - * than at the end of the block before it. Unlike the int8 sibling this one rounds the sum to bf16 - * and stores it BEFORE normalising, which is what the pair it replaces does and is what keeps the - * output identical to the byte. */ + * The residual is second, as in `rmsnorm_had_quant_i8`, so the two differ only by the rotation. It + * folds `add` + `rmsnorm` into one launch: a block adds the previous block's delta into the + * residual stream at the front of its own norm. Unlike the int8 sibling, it rounds the sum to bf16 + * and stores it before normalising, as the replaced pair does, which keeps the output + * byte-identical. */ static const RadParamSpec pRmsNormQuantFp8[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "n", RAD_P_INT, RAD_REQUIRED }, @@ -1338,13 +1206,8 @@ static const RadOperandSpec oRmsNormQuantFp8[] = { { "out_bf16", RAD_OPD_OUT, 1 }, /* layers with a bf16 consumer of the post-norm tensor */ }; -/* The same op again with the all-reduce in front of it, which is `ar_ln_had_quant_i8`'s bargain - * without the rotation. Same operands in the same order, plus `world_size` -- and no `wire`, which - * is the one place this differs from the int8 sibling's schema: that kernel carries the rotated - * 6-bit payload as well and this one serves the exact wire only, so a caller above - * --tp-wire-min-kb emits `all_reduce` then `rmsnorm_quant_fp8` and gets the compressed message - * from the standalone kernel. A parameter for a wire there is no code for would be a lie the - * matcher could not catch. */ +/* The same op with the all-reduce in front, like `ar_ln_had_quant_i8` without the rotation: same + * operands, plus `world_size` and `wire` (0 exact, 6 the rotated 6-bit payload). */ static const RadParamSpec pArRmsNormQuantFp8[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "n", RAD_P_INT, RAD_REQUIRED }, @@ -1356,7 +1219,7 @@ static const RadParamSpec pArRmsNormQuantFp8[] = { { "wire", RAD_P_INT, RAD_OPTIONAL }, /* 0 = exact bf16, 6 = rotated 6-bit */ }; static const RadOperandSpec oArRmsNormQuantFp8[] = { - { "x", RAD_OPD_INOUT, 0 }, /* the message AND the input; the reduced sum lands here */ + { "x", RAD_OPD_INOUT, 0 }, /* the message and the input; receives the reduced sum */ { "residual", RAD_OPD_INOUT, 1 }, { "w", RAD_OPD_WEIGHT, 0 }, { "q", RAD_OPD_OUT, 0 }, @@ -1364,14 +1227,13 @@ static const RadOperandSpec oArRmsNormQuantFp8[] = { { "out_bf16", RAD_OPD_OUT, 1 }, }; -/* `rmsnorm_quant_i8` is the norm with r4d_gemm_w4a8_nt_m64's own activation producer on its pass: - * int8 codes in the GEMM's fragment order and ONE f32 scale per row -- quant_act_i8's grid, not - * quant_act_i8g's per-group one and not the rotated rmsnorm_had_quant_i8's. Its first six operands - * are rmsnorm_quant_fp8's, so the residual is the fused_add_rms_norm form; two optional weights - * after them make it a sandwich-norm model's whole residual junction: `w_post` normalises the - * branch output BEFORE the add and `scalar` multiplies the sum after it (Gemma's per-layer - * scalar). Every stage rounds to bf16 where the chain it replaces stores bf16, so the op is - * byte-identical to that chain. */ +/* `rmsnorm_quant_i8` is the norm with r4d_gemm_w4a8_nt_m64's activation producer on its pass: + * int8 codes in the GEMM's fragment order and one f32 scale per row (quant_act_i8's grid, not + * quant_act_i8g's per-group one nor the rotated rmsnorm_had_quant_i8's). Its first six operands are + * rmsnorm_quant_fp8's. Two optional weights make it a sandwich-norm model's whole residual + * junction: `w_post` normalises the branch output before the add, `scalar` multiplies the sum + * after it (Gemma's per-layer scalar). Every stage rounds to bf16 where the replaced chain stores + * bf16, so the op is byte-identical to it. */ static const RadParamSpec pRmsNormQuantI8[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "n", RAD_P_INT, RAD_REQUIRED }, @@ -1390,12 +1252,11 @@ static const RadOperandSpec oRmsNormQuantI8[] = { { "scalar", RAD_OPD_WEIGHT, 1 }, /* [1], multiplies the sum; needs the residual */ }; -/* `qkv_norm_rope` is `qk_norm_rope` over SEPARATE q, k and v projections rather than one fused row: - * the per-head q and k norms, the weightless value norm and the rotary of q and k, in one - * dispatch -- Gemma 4's attention prologue, whose projections are three GEMMs. `v_from_k` 1 is its - * global class (k == v): v is the value norm of the RAW k, written before the k norm rewrites it. - * The rotary parameters are `rope`'s (`ladder` included), the norm parameters `rmsnorm`'s, and the - * op is byte-identical to rmsnorm_p + rmsnorm + rmsnorm + rope + rope. */ +/* `qkv_norm_rope` is `qk_norm_rope` over separate q, k and v projections: the per-head q and k + * norms, the weightless value norm and the rotary of q and k in one dispatch (Gemma 4's attention + * prologue). `v_from_k` 1 is its global class (k == v): v is the value norm of the raw k, written + * before the k norm rewrites it. Rotary parameters are `rope`'s (`ladder` included), norm + * parameters `rmsnorm`'s; byte-identical to rmsnorm_p + rmsnorm + rmsnorm + rope + rope. */ static const RadParamSpec pQkvNormRope[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "head_dim", RAD_P_INT, RAD_REQUIRED }, @@ -1435,7 +1296,7 @@ static const RadOperandSpec oGeluMulQuantI8[] = { }; /* `ar_rmsnorm_quant_i8` is rmsnorm_quant_i8 with the two-rank exact all-reduce of `x` in front: - * same operands, `x` INOUT because the reduced sum lands back in it, plus `world_size`. */ + * same operands with `x` inout (it receives the reduced sum), plus `world_size`. */ static const RadParamSpec pArRmsNormQuantI8[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "n", RAD_P_INT, RAD_REQUIRED }, @@ -1468,18 +1329,10 @@ static const RadOperandSpec oGatedQuantFp8[] = { { "scale", RAD_OPD_OUT, 0 }, { "out_bf16", RAD_OPD_OUT, 1 }, }; -/* THE GATE IN A SEPARATE OPERAND, which is the shape a gated attention has: the gate is a column - * slice of the [q|gate] projection and `x` is the attention output, two buffers with different - * pitches. `M` is a (token, head) pair rather than a token -- see the kernel -- and that is what - * makes both sources a fixed stride apart and leaves the scale plane exactly where the out - * projection reads it. */ -/* THE gate_up GEMM WITH gated_quant_fp8'S PASS IN ITS EPILOGUE, and a schema of its own rather - * than a flag on `gemm_nt_q`, because it does not write a `y`: its outputs are the quantiser's - * and an architecture that resolved it into a `gemm_nt_q` operand list would hand the GEMM a - * buffer of the wrong width. `N` is the WEIGHT's rows -- 2 * the fused width, gate then up, the - * same plane the unfused GEMM reads -- so a caller that has both declared spells the geometry - * once. `act` is `gated_quant_fp8`'s and is REQUIRED here: the fold is compiled for silu only, - * and an op that took the parameter optionally would resolve for a sigmoid it cannot serve. */ +/* The gate_up GEMM with gated_quant_fp8's pass in its epilogue. Its own schema, not a flag on + * `gemm_nt_q`, because it writes the quantiser's outputs instead of a `y`. `N` is the weight's + * rows, 2 * the fused width (gate then up), the same plane the unfused GEMM reads. `act` is + * required: the fold is compiled for silu only. */ static const RadParamSpec pGemmNtQGated[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "N", RAD_P_INT, RAD_REQUIRED }, @@ -1498,6 +1351,10 @@ static const RadOperandSpec oGemmNtQGated[] = { { "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 + * (token, head) pair, so both sources are a fixed stride apart and the scale plane lands where the + * out projection reads it. */ static const RadParamSpec pGateQuantFp8[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "n", RAD_P_INT, RAD_REQUIRED }, @@ -1513,27 +1370,22 @@ static const RadOperandSpec oGateQuantFp8[] = { { "out_bf16", RAD_OPD_OUT, 1 }, }; -/* `sample_chain` is a NEW OP, and it is NOT docs/OPS.md's eight-op sampler chain - * (`sample_penalties`, `sample_temp`, `sample_topk`, `sample_topp`, `sample_minp`, `sample_mask`, - * `sample_pick`, `sample_argmax`). Those are eight launches over a 248K-entry row per position and - * nothing in this project implements any of them on a device. libr4d's is ONE kernel that walks the - * vocabulary several times inside one workgroup, which after the first pass is L2-resident. - * Splitting it into the eight would throw that away, and fusing back is not something the core - * does: "fusion is a selection, not a compiler pass" (spec §2.3), so the plugin declares the fused - * op and a caller asks for it first. +/* `sample_chain`, a new op, distinct from docs/OPS.md's eight-op sampler chain (`sample_penalties`, + * `sample_temp`, `sample_topk`, `sample_topp`, `sample_minp`, `sample_mask`, `sample_pick`, + * `sample_argmax`), which would be eight launches over a 248K-entry row per position. libr4d's is + * one kernel walking the vocabulary several times inside one workgroup, L2-resident after the first + * pass. The core does not fuse ("fusion is a selection, not a compiler pass", spec §2.3), so the + * plugin declares the fused op. * - * top_k, top_p, min_p and temperature are per-REQUEST and change between steps, so they are - * parameters read at LAUNCH and never constraints -- putting a resolution boundary on a sampling - * setting would rebuild the bucket table when a user moved a slider. The float ones are RAD_P_F64 - * per docs/OPS.md; constraints never match on a float. + * top_k, top_p, min_p and temperature change per request, so they are launch-time parameters, + * never constraints (a constraint would rebuild the bucket table on every setting change). The + * float ones are RAD_P_F64 per docs/OPS.md. * - * THE SPECULATIVE OPERANDS ARE WHY IT IS WORTH ONE OP RATHER THAN EIGHT: `query` is the drafted - * token per position and `u` two uniforms per position, and the three outputs are a draw, a draw - * with `query` excluded and renormalised, and `query`'s filtered probability -- everything a - * rejection-sampling verify needs from one pass, so the host never comes back (spec §10). + * `query` is the drafted token per position and `u` two uniforms per position. The three outputs + * are a draw, a draw with `query` excluded and renormalised, and `query`'s filtered probability: + * everything a rejection-sampling verify needs in one pass (spec §10). * - * libref does not implement this either, and here the gap is real work rather than fifteen - * lines. Its oracle is llama.cpp's host sampler, which spec §13 already requires rad-kbench to keep. */ + * libref does not implement it; its oracle is llama.cpp's host sampler (spec §13). */ static const RadParamSpec pSampleChain[] = { { "M", RAD_P_INT, RAD_REQUIRED }, /* positions in the verify block */ { "n_vocab", RAD_P_INT, RAD_REQUIRED }, @@ -1545,7 +1397,7 @@ static const RadParamSpec pSampleChain[] = { static const RadOperandSpec oSampleChain[] = { { "logits", RAD_OPD_IN, 0 }, { "query", RAD_OPD_IN, 1 }, /* the drafted token per position, or absent */ - { "u", RAD_OPD_IN, 0 }, /* TWO uniforms per position */ + { "u", RAD_OPD_IN, 0 }, /* two uniforms per position */ { "draw", RAD_OPD_OUT, 0 }, /* [M] x {u32 tok, u32 tok_excl, f32 p_query} */ }; @@ -1568,8 +1420,8 @@ static const RadParamSpec pRmsNormHadQuant[] = { P_INT("group"), P_STR("dtype"), /* GemmaRMSNorm (Qwen3.5, Qwen3-Next, Gemma) stores a zero-centred gamma and uses `1 + w`. - * Forming that in bf16 first costs 0.3% per channel, so libr4d adds it in fp32 after the - * load and takes the addend as an argument. 0 is a plain RMS norm. */ + * Forming that in bf16 costs 0.3% per channel, so libr4d adds it in fp32 after the load. 0 is + * a plain RMS norm. */ P_F64O("wadd"), }; static const RadOperandSpec oRmsNormHadQuant[] = { @@ -1581,10 +1433,8 @@ static const RadOperandSpec oRmsNormHadQuant[] = { { "out_bf16", RAD_OPD_OUT, 1 }, /* layers with a bf16 consumer of the post-norm tensor */ }; -/* `act` is the vocabulary's name for the gate and it is a NAME: "silu" is down_proj's input, - * "sigmoid" is a gated-attention o_proj's. `mode` is libr4d's integer spelling of the same choice - * and survives as OPTIONAL because it is libr4d's, not the vocabulary's; a caller written against - * either name works, and `act` wins where both are given. */ +/* `act` names the gate: "silu" for down_proj's input, "sigmoid" for a gated-attention o_proj's. + * `mode` is libr4d's optional integer spelling of the same choice; `act` wins if both are given. */ static const RadParamSpec pGatedHadQuant[] = { P_INT("M"), P_INT("n"), @@ -1600,9 +1450,8 @@ static const RadOperandSpec oGatedHadQuant[] = { { "scale", RAD_OPD_OUT, 0 }, }; -/* Not in docs/OPS.md. A fusion with no unfused equivalent in the vocabulary, exactly like - * `rmsnorm_had_quant_i8`: the GDN gated RMS norm is per HEAD while the rotation and the int8 scale - * are per TOKEN, so the reduction is segmented and nothing in the vocabulary composes to it. */ +/* Not in docs/OPS.md. Like `rmsnorm_had_quant_i8`, a fusion with no unfused equivalent: the GDN + * gated RMS norm is per head while the rotation and the int8 scale are per token. */ static const RadParamSpec pGdnGatedNormHadQuant[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "n", RAD_P_INT, RAD_REQUIRED }, @@ -1610,7 +1459,7 @@ static const RadParamSpec pGdnGatedNormHadQuant[] = { { "group", RAD_P_INT, RAD_REQUIRED }, P_F64("eps"), { "dtype", RAD_P_STR, RAD_REQUIRED }, - /* Z may be the INTERLEAVED qkvz projection rather than a compacted gate: element i of the + /* Z may be the interleaved qkvz projection rather than a compacted gate: element i of the * flattened row sits at (i / zblk) * zgrp + (i % zblk). 0 means a contiguous gate. */ { "zgrp", RAD_P_INT, RAD_OPTIONAL }, { "zblk", RAD_P_INT, RAD_OPTIONAL }, @@ -1623,10 +1472,9 @@ static const RadOperandSpec oGdnGatedNormHadQuant[] = { { "scale", RAD_OPD_OUT, 0 }, }; -/* Not in docs/OPS.md, and spec §2.3 names it as the example of a fused op a plugin asks for - * first. Every row-parallel linear's output is all-reduced and then immediately normalised -- 128 - * adjacent dispatches on a decode step -- and fused, the all-reduce's bf16 output never exists. - * The unfused emission a plugin falls back to is `all_reduce` then `rmsnorm_had_quant_i8`. */ +/* Not in docs/OPS.md; spec §2.3's example of a fused op a plugin asks for first. Every + * row-parallel linear's output is all-reduced and then normalised; fused, the all-reduce's bf16 + * output never exists. The unfused fallback is `all_reduce` then `rmsnorm_had_quant_i8`. */ static const RadParamSpec pArLnHadQuant[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "n", RAD_P_INT, RAD_REQUIRED }, @@ -1648,17 +1496,13 @@ static const RadOperandSpec oArLnHadQuant[] = { /* ---------------------------------------------- the small model ops and the sampler chain ----- * - * TRANSCRIBED FROM libref, EXACTLY. The first plugin in hierarchy order to declare an op - * fixes its schema and a later plugin that disagrees is refused at load with both plugins named - * (core/plugin/loader.cpp) -- and rightly, since arguments are positional and two schemas would - * make the same call mean different things depending on which plugin won. libr4d loads FIRST, so - * these are the fixed forms and ref's have to match: they agree with libref/ref_registry.cpp field - * for field, and a change to one belongs in both files at once. + * Transcribed from libref/ref_registry.cpp field for field. The first plugin in hierarchy order to + * declare an op fixes its schema, and a disagreeing later plugin is refused at load + * (core/plugin/loader.cpp), since arguments are positional. libr4d loads first, so a change here + * belongs in both files. * - * These ops have no interesting geometry -- there is nothing to specialise an add on -- so the - * constraint rows below say only what the kernels actually require: bf16 operands, and for - * kv_store a block size at all. That is a NECESSARY condition and not a sufficient one: the shims - * still check every stride, pitch and extent per call. */ + * The constraint rows for these ops state only what the kernels require (bf16 operands, and a + * block size for kv_store); the shims still check every stride, pitch and extent per call. */ static const RadParamSpec pRmsNorm[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "n", RAD_P_INT, RAD_REQUIRED }, @@ -1679,9 +1523,8 @@ static const RadParamSpec pMnDtype[] = { { "n", RAD_P_INT, RAD_REQUIRED }, { "dtype", RAD_P_STR, RAD_REQUIRED }, }; -/* `logit_softcap`'s, matched field for field to ref's `pMnCap` so the two plugins agree (spec - * §2.3). `cap` is required and must be > 0; a non-positive cap is a division by zero in every - * lane, so the op refuses it rather than answering with NaNs. */ +/* `logit_softcap`'s, matching ref's `pMnCap` (spec §2.3). `cap` must be > 0; the op refuses a + * non-positive cap (a division by zero in every lane). */ static const RadParamSpec pMnCap[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "n", RAD_P_INT, RAD_REQUIRED }, @@ -1712,7 +1555,7 @@ static const RadParamSpec pQkNormRope[] = { P_F64("eps"), P_F64O("scale"), P_STRO("mode"), P_INTO("rotary_dim"), P_F64O("wadd"), P_INTO("v_norm"), P_STRO("sections"), P_STRO("comps"), }; -/* `M` is the INPUT row count, a multiple of `k`. */ +/* `M` is the input row count, a multiple of `k`. */ static const RadParamSpec pPoolRows[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_F64O("mult"), P_STR("dtype"), }; @@ -1722,7 +1565,7 @@ static const RadOperandSpec oQkNormRope[] = { { "q_w", RAD_OPD_WEIGHT, 0 }, { "k_w", RAD_OPD_WEIGHT, 0 }, }; -/* `scalar` 1 says `w` is one element rather than one row -- for the shape description; the shim +/* `scalar` 1 says `w` is one element rather than one row, for the shape description; the shim * reads it off the operand. */ static const RadParamSpec pMulWeight[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_INTO("scalar"), @@ -1737,6 +1580,7 @@ static const RadOperandSpec oClamp[] = { static const RadParamSpec pConv2d[] = { P_INT("M"), P_INT("width"), P_INT("cin"), P_INT("cout"), P_INT("kh"), P_INT("kw"), P_INT("stride"), P_INT("pad"), P_INTO("cu_div"), P_INTO("valid_stride"), P_STR("dtype"), + P_INTO("t_last"), P_STRO("act"), }; static const RadOperandSpec oConv2d[] = { { "x", RAD_OPD_IN, 0 }, @@ -1744,6 +1588,17 @@ static const RadOperandSpec oConv2d[] = { { "cu_seqlens", RAD_OPD_IN, 0 }, { "valid", RAD_OPD_IN, 1 }, { "y", RAD_OPD_OUT, 0 }, + { "b", RAD_OPD_WEIGHT, 1 }, +}; +static const RadParamSpec pConv2dUnfold[] = { + P_INT("M"), P_INT("width"), P_INT("cin"), P_INT("kh"), P_INT("kw"), P_INT("stride"), + P_INT("pad"), P_INTO("cu_div"), P_INTO("valid_stride"), P_INTO("t_last"), P_STR("dtype"), +}; +static const RadOperandSpec oConv2dUnfold[] = { + { "x", RAD_OPD_IN, 0 }, + { "cu_seqlens", RAD_OPD_IN, 0 }, + { "valid", RAD_OPD_IN, 1 }, + { "y", RAD_OPD_OUT, 0 }, }; static const RadParamSpec pConv1dDw[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_INTO("cu_div"), P_STR("dtype"), @@ -1760,6 +1615,14 @@ static const RadParamSpec pRelSin[] = { static const RadOperandSpec oRelSin[] = { { "y", RAD_OPD_OUT, 0 }, }; +static const RadParamSpec pSegSin[] = { + P_INT("M"), P_INT("n"), P_INT("period"), P_F64O("max_timescale"), P_INTO("cu_div"), + P_STR("dtype"), +}; +static const RadOperandSpec oSegSin[] = { + { "cu_seqlens", RAD_OPD_IN, 0 }, + { "y", RAD_OPD_OUT, 0 }, +}; static const RadParamSpec pAttnLocalRel[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"), P_INT("left"), P_INT("right"), P_F64("softcap"), P_INTO("cu_div"), P_STR("dtype"), @@ -1798,8 +1661,7 @@ static const RadOperandSpec oScale[] = { { "s", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 }, }; -/* `cast`'s two dtype keys are STRINGS and not one `dtype`, because the whole point of the op is - * that the two ends differ. ref's spelling, matched field for field so the two plugins agree. */ +/* `cast` takes two dtype strings, `from` and `to`, as ref spells them. */ static const RadParamSpec pCast[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "n", RAD_P_INT, RAD_REQUIRED }, @@ -1875,11 +1737,10 @@ static const RadParamSpec pKvStore[] = { { "n_head_kv", RAD_P_INT, RAD_REQUIRED }, { "block_size", RAD_P_INT, RAD_REQUIRED }, { "kv_dtype", RAD_P_STR, RAD_REQUIRED }, - /* THE DESCALES THE READER WILL MULTIPLY BACK BY, so the store divides. Meaningless for a bf16 - * cache and optional for that reason; an fp8 one defaults them to 1.0, which is vLLM's default - * and what the attention kernels assume when their descale operands are absent. They are ONE - * number per (sequence, head) on the read side, so they cannot be derived from the tokens - * being written -- see r4d.h on r4d_kv_store_fp8. */ + /* The descales the reader multiplies back by, so the store divides. Unused for a bf16 cache; + * an fp8 one defaults them to 1.0, vLLM's default and what the attention kernels assume when + * their descale operands are absent. They are one number per (sequence, head), so they cannot + * be derived from the tokens written (r4d.h, r4d_kv_store_fp8). */ P_F64O("k_scale"), P_F64O("v_scale"), }; @@ -1893,11 +1754,11 @@ static const RadOperandSpec oKvStore[] = { static const RadParamSpec pEmbed[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "n_embd", RAD_P_INT, RAD_REQUIRED }, - { "n_vocab", RAD_P_INT, RAD_REQUIRED }, /* THIS RANK'S rows when vocab_offset is given */ + { "n_vocab", RAD_P_INT, RAD_REQUIRED }, /* this rank's rows when vocab_offset is given */ { "dtype", RAD_P_STR, RAD_REQUIRED }, - { "vocab_offset", RAD_P_INT, RAD_OPTIONAL }, /* first GLOBAL row; vocab-parallel embedding */ - /* The scale embed_lookup_q's layout quantises with. That op shares this parameter list and - * libref fixes it for both, so it is spelled here to match. */ + { "vocab_offset", RAD_P_INT, RAD_OPTIONAL }, /* first global row; vocab-parallel embedding */ + /* The scale embed_lookup_q's layout quantises with; embed_lookup_q shares this list, which + * libref fixes. */ { "wscale", RAD_P_F64, RAD_OPTIONAL }, }; /* embed_lookup's own: pEmbed and `mult`, the factor every gathered row is multiplied by (Gemma's @@ -1916,9 +1777,8 @@ static const RadOperandSpec oEmbed[] = { { "wte", RAD_OPD_WEIGHT, 0 }, { "x", RAD_OPD_OUT, 0 }, }; -/* The quantised gather's: libref's list (ref_registry.cpp), which the loader holds every plugin - * serving the op to -- a one-element `scale`, absent for a table stored plain, and `ahead`, the - * next prompt's ids for a host reader that fetches rows from a file. */ +/* The quantised gather's, libref's list (ref_registry.cpp): a one-element `scale`, absent for a + * plain table, and `ahead`, the next prompt's ids for a host reader fetching rows from a file. */ static const RadOperandSpec oEmbedQ[] = { { "tokens", RAD_OPD_IN, 0 }, { "wte", RAD_OPD_WEIGHT, 0 }, @@ -1926,9 +1786,6 @@ static const RadOperandSpec oEmbedQ[] = { { "x", RAD_OPD_OUT, 0 }, { "ahead", RAD_OPD_IN, 1 }, }; -/* PLE's hashed n-gram ids. `state` is a rolling window of committed ids -- RAD_KV_CONV's shape and - * ple_conv's contract -- except that a cold window is EOS and not zero, because zero is a real - * token id. */ static const RadParamSpec pPleGate[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "n", RAD_P_INT, RAD_REQUIRED }, @@ -1956,8 +1813,8 @@ static const RadParamSpec pPleConv[] = { { "dilation", RAD_P_INT, RAD_REQUIRED }, { "dtype", RAD_P_STR, RAD_REQUIRED }, }; -/* Four optionals, and they are the union of the two contracts gdn_conv_prep and gdn_conv_update - * split between them: `has_init` is prefill's question and `num_accepted` is decode's. */ +/* The optionals unite gdn_conv_prep's and gdn_conv_update's contracts: `has_init` serves + * prefill, `num_accepted` decode. */ static const RadOperandSpec oPleConv[] = { { "x", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, @@ -1987,6 +1844,9 @@ static const RadOperandSpec oCausalConv[] = { { "y", RAD_OPD_OUT, 0 }, }; +/* PLE's hashed n-gram ids. `state` is a rolling window of committed ids (RAD_KV_CONV's shape, + * ple_conv's contract), except that a cold window holds EOS, not zero, since zero is a real token + * id. */ static const RadParamSpec pNgramIds[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "heads", RAD_P_INT, RAD_REQUIRED }, @@ -2019,11 +1879,9 @@ static const RadOperandSpec oLogits[] = { { "logits", RAD_OPD_OUT, 0 }, }; -/* EVERY SAMPLER SCALAR IS PER ROW and arrives in `params`, an array of RadSampleParams - * (abi/rad_sample.h). A parameter is geometry -- the selector matches on it and freezes it - * at declare -- so `top_p` as a parameter would make two requests with different top_p two - * different resolutions of one op, and a deployment would have exactly one top_p. Only the two - * extents are parameters. */ +/* Every sampler scalar is per row and arrives in `params`, an array of RadSampleParams + * (abi/rad_sample.h). Parameters are geometry, frozen at declare, so only the two extents are + * parameters. */ static const RadParamSpec pMVocab[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "n_vocab", RAD_P_INT, RAD_REQUIRED }, @@ -2032,9 +1890,8 @@ static const RadParamSpec pMCand[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "n_cand", RAD_P_INT, RAD_REQUIRED }, }; -/* The history stages read GLOBAL token ids and write this rank's columns, so under a split - * vocabulary they take the rank's first row -- sample_topk's `vocab_off`, for the same crossing in - * the other direction. Absent is 0. */ +/* The history stages read global token ids and write this rank's columns, so under a split + * vocabulary they take the rank's first row, `vocab_off` (as sample_topk does). Absent is 0. */ static const RadParamSpec pPenal[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "n_vocab", RAD_P_INT, RAD_REQUIRED }, @@ -2045,7 +1902,7 @@ static const RadOperandSpec oPenalties[] = { { "params", RAD_OPD_IN, 0 }, { "history", RAD_OPD_IN, 0 }, }; -/* `breakers` is optional: a u8 plane the shape of `history`, nonzero where that position's token +/* `breakers` is optional: a u8 plane shaped like `history`, nonzero where that position's token * is a whole DRY sequence breaker and so never penalised. */ static const RadOperandSpec oDry[] = { { "logits", RAD_OPD_INOUT, 0 }, @@ -2062,10 +1919,9 @@ static const RadOperandSpec oMask[] = { { "params", RAD_OPD_IN, 0 }, { "bitmask", RAD_OPD_IN, 0 }, }; -/* `pairs` is the VOCAB-PARALLEL path and is optional: [M, 2 * n_cand] u32 holding this rank's - * candidates as (u32 GLOBAL id, f32 logit) -- what sample_merge_topk reads once the all-gather has - * put every rank's side by side. `vocab_off` is added by the kernel, so the gather never has to - * know the shard layout. Absent, and this is the single-rank top-k. */ +/* `pairs`, the optional vocab-parallel output: [M, 2 * n_cand] u32 of this rank's candidates as + * (u32 global id, f32 logit), which sample_merge_topk reads after the all-gather. The kernel adds + * `vocab_off`, so the gather needs no shard layout. Absent: the single-rank top-k. */ static const RadParamSpec pTopk[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "n_vocab", RAD_P_INT, RAD_REQUIRED }, @@ -2116,12 +1972,10 @@ static const RadOperandSpec oMergeTopk[] = { /* ------------------------------------------------------- pair_argmax, the joins, expert_scale * - * pair_argmax is libref's schema restated field for field. The other four ops are this library's - * own, and attn_paged_qrow, whose schema is attn_paged's above: libref has no row for any of them - * ON PURPOSE. A reference row would resolve them wherever this library is not loaded -- a CPU-only - * build, a --kernels list without it -- and the architecture's fallback to the chain each one - * replaces would never be taken. docs/OPS.md carries all six, which is what the ops_doc test holds - * them to. */ + * pair_argmax is libref's schema restated. The other four ops, and attn_paged_qrow (attn_paged's + * schema), are this library's own; libref deliberately has no row for them, so that where libr4d + * is not loaded (CPU-only, a --kernels list without it) the architecture falls back to the chain + * each replaces. docs/OPS.md lists all six (checked by the ops_doc test). */ static const RadParamSpec pPairArgmax[] = { P_INT("M"), P_INT("n"), @@ -2191,8 +2045,7 @@ static const RadOperandSpec oExpertScale[] = { #define SCHEMA(op, p, o, doc) { (op), ROW(p), ROW(o), (doc) } /* ---- image generation (r4d_gen.hip, r4d_attn_gen.hip) ------------------------------------- - * ref's spellings (libref/ref_registry.cpp), field for field: the first plugin to declare an op - * fixes its schema and the second is refused if it disagrees. */ + * ref's spellings (libref/ref_registry.cpp), field for field. */ static const RadParamSpec pGenMn[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; static const RadParamSpec pLnMod[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype") }; static const RadOperandSpec oLnMod[] = { @@ -2309,16 +2162,26 @@ static const RadOpSchema kSchemas[] = { SCHEMA("clamp", pMnDtype, oClamp, "y = min(max(x, lo), hi), lo and hi WEIGHTS of one element each: a clipped linear's range."), SCHEMA("conv2d", pConv2d, oConv2d, - "A 2-D convolution over (time, width), channels innermost, w [cout, cin, kh, kw]. Each " - "cu_seqlens segment (rows cu/cu_div) is convolved on its own with zero padding at its " - "edges; its output rows start at cu/(cu_div*stride). With `valid`, input row t reads " - "as zeros unless valid[t * valid_stride] != 0. f32 sum, one rounding."), + "A 2-D convolution over (time, width), channels innermost, w [cout, cin, kh, kw] " + "([cout, cin, kw, kh] with t_last). Each cu_seqlens segment (rows cu/cu_div) is " + "convolved on its own with zero padding at its edges; its output rows start at " + "cu/(cu_div*stride). With `valid`, input row t reads as zeros unless valid[t * " + "valid_stride] != 0. f32 sum plus the optional bias `b`, one rounding; then `act` " + "(none, gelu) rounded."), + SCHEMA("conv2d_unfold", pConv2dUnfold, oConv2dUnfold, + "conv2d's receptive fields as rows: row (to, wo) holds, per input channel and kernel " + "tap, what conv2d multiplies that tap's weight by (zero in the padding and on masked " + "rows), its columns in the weight's order -- (ci, i, j), or (ci, j, i) with t_last -- so " + "a GEMM against the weight as [cout, cin*kh*kw] is the convolution."), SCHEMA("conv1d_dw", pConv1dDw, oConv1dDw, "Causal depthwise convolution over time, w [C, 1, k], rows before the segment's start " "(cu/cu_div) reading as zeros. f32 sum, one rounding."), SCHEMA("rel_sinusoid", pRelSin, oRelSin, "The sinusoidal relative-position table: row d is sin(d * inv[i]) then cos(d * inv[i]), " "inv[i] = exp(i * -log(max_timescale) / max(n/2 - 1, 1)), in f32, rounded once."), + SCHEMA("seg_sinusoid", pSegSin, oSegSin, + "Row r of segment s (rows cu/cu_div) takes position p = (r - cu[s]/cu_div) mod period: " + "sin(p * inv[i]) then cos(p * inv[i]), inv as rel_sinusoid's, in f32, rounded once."), SCHEMA("attn_local_rel", pAttnLocalRel, oAttnLocalRel, "Local attention with a relative-position term and a softcap (Gemma 4's audio): query i " "of a segment sees keys j with 0 <= i - j <= left; qf = q * head_dim^-0.5/ln2 * " @@ -2456,13 +2319,11 @@ static const RadOpSchema kSchemas[] = { "paged causal attention, varlen. The ranged parameter is q_len, not M: one query row " "at decode, up to 64/gqa at a speculative verify, thousands in a prefill chunk, and " "libr4d has a different kernel for each band."), - /* attn_paged under a name of its own, for a q read at its own row pitch. The windowed kernels - * (r4d_attn_paged_window.hip) read q where a fused [q|k|v] projection left it; the other - * attn_paged kernels, this library's included, read q dense and refuse the slice - * (RAD_E_STRIDE), which stops the engine at the first step. Under attn_paged, whichever row - * resolved would decide whether the slice works; under this name the op resolves to a kernel - * that takes it or to nothing, and the architecture lifts q into a dense block for attn_paged - * where it is nothing. */ + /* attn_paged under its own name, for q read at its own row pitch. The windowed kernels + * (r4d_attn_paged_window.hip) read q in place in a fused [q|k|v] projection; the other + * attn_paged kernels read q dense and refuse a slice (RAD_E_STRIDE). Under this name the op + * resolves to a kernel that takes the slice or to nothing, and in the latter case the + * architecture lifts q into a dense block for attn_paged. */ SCHEMA("attn_paged_qrow", pAttnPaged, oAttnPaged, "attn_paged, parameter for parameter and value for value, with q read at its own row " "pitch: a column slice of a wider row -- the q part of a fused [q|k|v] projection -- read " @@ -2472,8 +2333,9 @@ static const RadOpSchema kSchemas[] = { "merged (token, head) row is gated, rounded, written to `out` and quantised to E4M3 " "with one scale per 128 columns into `q8` / `q8_scale`."), SCHEMA("attn_dense", pAttnDense, oAttnDense, - "dense attention over cu_seqlens segments, with attn_paged's window rule over a " - "segment's positions."), + "dense attention over cu_seqlens segments (rows cu/cu_div), with attn_paged's window " + "rule over a segment's positions and optional blocks of `block` rows that attend " + "within themselves."), SCHEMA("qk_norm_rope_gate", pQkNormRopeGate, oQkNormRopeGate, "split [q|gate] per head, QK RMS norm over the head, partial NeoX RoPE and the gate " "copy, in one pass. Not docs/OPS.md's qk_norm_rope: different operands, and a " @@ -2836,13 +2698,13 @@ static const RadOpSchema kSchemas[] = { /* ================================================================================ constraints * - * Each row restates its entry point's own admissibility rules, line for line where the keys agree; - * the three key renames are marked where they happen. + * Each row restates its entry point's admissibility rules, line for line where the keys agree; + * the key renames are marked. */ /* ---- attention ------------------------------------------------------------------------------ - * `causal` is a constraint, not a note: the paged kernels are causal by construction and the - * vision kernel is dense, and neither can serve the other's masking. */ + * `causal` is a constraint: the paged prefill kernels are causal and the vision kernel dense, and + * neither serves the other's masking. */ static const RadConstraint cAttnPrefillFp8[] = { C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 16), C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), @@ -2851,9 +2713,8 @@ static const RadConstraint cAttnPrefillBf16[] = { C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 16), C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), }; -/* q_len <= 10 is the q_len*gqa <= 64 of the prose, at the gqa 6 this kernel is compiled for. In - * radiance this doubles as the bucket boundary that splits `attn_paged` into a decode band and a - * prefill band (spec §2.2) -- the boundary is the constraint value and nobody chose a policy. */ +/* q_len <= 10 is q_len*gqa <= 64 at the gqa 6 this kernel is compiled for. It is also the bucket + * boundary splitting `attn_paged` into decode and prefill bands (spec §2.2). */ static const RadConstraint cAttnDecodeFp8[] = { C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 16), C_EQ("causal", 1), C_LE("q_len", 10), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), @@ -2862,9 +2723,8 @@ static const RadConstraint cAttnDecodeBf16[] = { C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 16), C_EQ("causal", 1), C_LE("q_len", 10), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), }; -/* The DFlash2 drafter: head_dim 128, 4 queries per kv head, and a sliding window -- which this - * kernel supports and the h256 pair above does not, so `window` is a constraint on both sides - * rather than an option one of them ignores. */ +/* The DFlash2 drafter: head_dim 128, 4 queries per kv head, and a sliding window, which this + * kernel supports and the h256 pair above does not. */ static const RadConstraint cAttnDecodeH128Fp8[] = { C_GE("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 4), C_EQ("block_size", 16), C_GE("causal", 0), C_LE("q_len", 16), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), @@ -2874,9 +2734,8 @@ static const RadConstraint cAttnDecodeH128Bf16[] = { C_GE("causal", 0), C_LE("q_len", 16), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), }; /* Gemma 4 dense sliding window: head_dim 256, 2 queries per kv head, windowed decode - * (r4d_attn_paged_h256_gqa2.hip). window is a launch argument -- 1024 in the model, 0 = full - * attention -- so it is constrained on both sides like the drafter leg, not fixed. q_len <= 32 is - * the q_len*gqa <= 64 of the prose at gqa 2, and the bucket boundary that keeps prefill out. */ + * (r4d_attn_paged_h256_gqa2.hip). `window` is a launch argument (1024 in the model, 0 = full + * attention). q_len <= 32 is q_len*gqa <= 64 at gqa 2, and the bucket boundary to prefill. */ static const RadConstraint cAttnDecodeH256Gqa2Fp8[] = { C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16), C_GE("causal", 0), C_LE("q_len", 32), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), @@ -2885,12 +2744,10 @@ static const RadConstraint cAttnDecodeH256Gqa2Bf16[] = { C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16), C_GE("causal", 0), C_LE("q_len", 32), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), }; -/* Gemma 4 dense sliding-window PREFILL (r4d_attn_paged_h256_gqa2.hip): the same geometry as the - * decode leg above, but no q_len bound -- it serves the prefill band (q_len > 32, the bucket the - * decode leg's C_LE leaves). window is a launch argument (1024 in the model) exactly as on the - * decode leg, so C_GE on both sides; the kernel's WIN bit masks the window and skips the below- - * window tiles. This was the band the decode-only leg left as a hole: a base-model prefill with no - * device kernel is fatal (spec §17 -- libref is an opt-in fallback the engine refuses by default). */ +/* Gemma 4 dense sliding-window prefill (r4d_attn_paged_h256_gqa2.hip): the decode leg's geometry + * without a q_len bound, serving q_len > 32. The kernel's WIN bit masks the window and skips tiles + * below it. Without this row the prefill band would have no device kernel, which is fatal (spec + * §17: libref is an opt-in fallback). */ static const RadConstraint cAttnPrefillH256Gqa2Fp8[] = { C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16), C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), @@ -2899,11 +2756,9 @@ static const RadConstraint cAttnPrefillH256Gqa2Bf16[] = { C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16), C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), }; -/* EIGHT QUERIES PER KV HEAD, at both head widths (r4d_attn_paged_gqa8.hip). q_len <= 8 is the - * `q_len * gqa <= 64` of the prose at gqa 8, and the difference from the gqa6 leg's 10 is the whole - * of what the ratio changes: a decode workgroup holds 64 rows and the verify width is how many of - * them a query position claims. As on the gqa6 leg, that bound doubles as the bucket boundary that - * splits `attn_paged` into a decode band and a prefill band (spec §2.2). */ +/* Eight queries per KV head, at both head widths (r4d_attn_paged_gqa8.hip). q_len <= 8 is + * `q_len * gqa <= 64` at gqa 8: a decode workgroup holds 64 rows, each query position claims gqa + * of them. As on the gqa6 leg, it is also the decode/prefill bucket boundary (spec §2.2). */ static const RadConstraint cAttnPrefillH256G8Fp8[] = { C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 8), C_EQ("block_size", 16), C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), @@ -2912,7 +2767,7 @@ static const RadConstraint cAttnPrefillH256G8Bf16[] = { C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 8), C_EQ("block_size", 16), C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), }; -/* The same two, at the other head width and for the same reason: one kernel, one runtime field. */ +/* The decode pair at gqa 8, head_dim 256. */ static const RadConstraint cAttnDecodeH256G8Fp8[] = { C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 8), C_EQ("block_size", 16), C_GE("causal", 0), C_LE("q_len", 8), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), @@ -2921,7 +2776,7 @@ static const RadConstraint cAttnDecodeH256G8Bf16[] = { C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 8), C_EQ("block_size", 16), C_GE("causal", 0), C_LE("q_len", 8), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), }; -/* FOUR QUERIES PER KV HEAD, head_dim 256 (r4d_attn_paged_h256_gqa4.hip) -- Qwen3.5-0.8B, 8 query +/* Four queries per KV head, head_dim 256 (r4d_attn_paged_h256_gqa4.hip): Qwen3.5-0.8B, 8 query * heads over 2. `q_len <= 16` is the same `q_len * gqa <= 64` bound, so every legal speculation * depth is a decode launch at this ratio. */ static const RadConstraint cAttnPrefillH256G4Fp8[] = { @@ -2940,8 +2795,8 @@ static const RadConstraint cAttnDecodeH256G4Bf16[] = { C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 4), C_EQ("block_size", 16), C_GE("causal", 0), C_LE("q_len", 16), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), }; -/* The prefill pair at head_dim 64 (LFM2: 32 query heads over 8). There is no decode row at this - * width -- the split-KV kernel's lanes hold 128 or 256 columns -- so the query-tiled kernel serves +/* The prefill pair at head_dim 64 (LFM2: 32 query heads over 8). No decode row exists at this + * width (the split-KV kernel's lanes hold 128 or 256 columns), so the query-tiled kernel serves * every q_len. */ static const RadConstraint cAttnPrefillH64G4Fp8[] = { C_EQ("window", 0), C_EQ("head_dim", 64), C_EQ("gqa", 4), C_EQ("block_size", 16), @@ -2951,17 +2806,15 @@ static const RadConstraint cAttnPrefillH64G4Bf16[] = { C_EQ("window", 0), C_EQ("head_dim", 64), C_EQ("gqa", 4), C_EQ("block_size", 16), C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), }; -/* THE WINDOWED KERNELS (r4d_attn_paged_window.hip): head_dim 256 and 512, 1/2/4/8 queries per KV - * head, ANY window, causal or not -- Gemma 4's sliding layers are h256/gqa2 with a 1024-token +/* The windowed kernels (r4d_attn_paged_window.hip): head_dim 256 and 512, 1/2/4/8 queries per KV + * head, any window, causal or not. Gemma 4's sliding layers are h256/gqa2 with a 1024-token * window, its full layers h512 at gqa 8 (TP1/TP2), 4 (TP4) or 2 (TP8). One kernel serves every - * q_len -- decode, verify and prefill, splitting the key range where there are too few tiles to - * fill the card -- so `q_len` carries no constraint and cuts no band. `causal` and `window` are - * runtime fields of the kernel; block_size is the kernel's (RAD_DERIVED): 16. + * q_len (splitting the key range when there are too few tiles to fill the card), so `q_len` cuts + * no band. `causal` and `window` are runtime fields; block_size is derived: 16. * - * h256 AT gqa 4 AND 8 TAKE A WINDOW ONLY (C_GE 1): their window-0 band is the gqa4 / gqa8 legs' - * above (Qwen3.5-0.8B, the routed 35B-A3B), which these rows leave to them. At h256/gqa2 the - * rows overlap the sliding leg's two bands and rank below it (R4D_PRIO_ATTN_WINDOW says why); - * every other geometry here is these rows' alone. */ + * h256 at gqa 4 and 8 take a window only (C_GE 1), leaving the window-0 band to the gqa4 / gqa8 + * legs above. At h256/gqa2 these rows overlap the sliding leg's bands and rank below it + * (R4D_PRIO_ATTN_WINDOW); every other geometry here is theirs alone. */ #define R4D_WIN_C(NAME, HD, G, KV, WMIN) \ static const RadConstraint NAME[] = { \ C_EQ("head_dim", HD), C_EQ("gqa", G), C_EQ("block_size", 16), C_GE("causal", 0), \ @@ -2976,12 +2829,10 @@ R4D_WIN_C(cWinH512G2Bf16, 512, 2, "bf16", 0) R4D_WIN_C(cWinH512G2Fp8, 512, 2, "f R4D_WIN_C(cWinH512G4Bf16, 512, 4, "bf16", 0) R4D_WIN_C(cWinH512G4Fp8, 512, 4, "fp8_e4m3", 0) R4D_WIN_C(cWinH512G8Bf16, 512, 8, "bf16", 0) R4D_WIN_C(cWinH512G8Fp8, 512, 8, "fp8_e4m3", 0) #undef R4D_WIN_C -/* TWELVE QUERIES PER KV HEAD, head_dim 256 (r4d_attn_paged_h256_gqa12.hip) -- Qwen3.8-Flash-Next's - * QSA layers, 24 query heads over 2. `q_len <= 5` is the same `q_len * gqa <= 64` bound the two - * ratios above state, and it is TIGHTER than the legal speculation depths: a verify of depth 7 is - * q_len 8, which 12 rows a position does not fit, so that band takes the PREFILL kernel -- which - * serves any q_len and is causal, which a verify is. Nothing is missing; the bucket boundary just - * falls in a different place at this ratio. */ +/* Twelve queries per KV head, head_dim 256 (r4d_attn_paged_h256_gqa12.hip): Qwen3.8-Flash-Next's + * QSA layers, 24 query heads over 2. `q_len <= 5` is the same `q_len * gqa <= 64` bound, tighter + * than the legal speculation depths: a depth-7 verify (q_len 8) takes the prefill kernel, which + * serves any q_len causally. */ static const RadConstraint cAttnPrefillH256G12Fp8[] = { C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 12), C_EQ("block_size", 4), C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), @@ -3008,21 +2859,15 @@ static const RadConstraint cAttnDecodeGqH256G12Bf16[] = { C_GE("causal", 0), C_LE("q_len", 5), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), C_EQ("group", 128), C_IN("act", "sigmoid"), }; -/* SIX QUERIES PER KV HEAD, head_dim 256, paged block 4 (r4d_attn_paged_h256_gqa6_bs4.hip) -- the - * SAME QSA layers as the gqa12 leg above, at four ranks. The model has two KV heads; a world of - * four replicates each across a rank pair, so a rank declares 6 queries over the 1 kv head it - * holds and `gqa` is 6 where the TP2 leg reads 12. What the ratio changes is the two bounds, as - * ever: `q_len <= 10` is the same `q_len * gqa <= 64` at 6 queries a position rather than 12, so - * this leg's bucket boundary sits where the plain h256/gqa6 leg's does, and a draft block of six or - * seven positions -- which gqa12 hands to the prefill kernel -- is a decode launch here. The page - * stays 4 because it is the model's indexer's block size, not a consequence of the parallelism. +/* Six queries per KV head, head_dim 256, paged block 4 (r4d_attn_paged_h256_gqa6_bs4.hip): the + * gqa12 leg's QSA layers at four ranks. The model's two KV heads are each replicated across a rank + * pair, so a rank declares 6 queries over its 1 kv head. `q_len <= 10` is `q_len * gqa <= 64` at + * 6, so a draft block of six or seven positions is a decode launch here. The page stays 4: it is + * the indexer's block size. * - * THE `attn_paged_gate_quant` ROWS ARE HERE TOO (see attn_decode_gq_h256_gqa6_fp8kv). Registering - * them costs nothing the plain legs don't already pay -- the body instantiates the `_gq` entry - * points at EVERY ratio, so this leg needs a row and not a kernel -- and NOT registering them is - * not neutral: the block declares the fused op beside its unfused pair either way, so an - * unregistered geometry is a device band with nothing behind it, reported as a hole a request can - * fall into. The unfused pair still runs whenever the fused row does not resolve, unchanged. */ + * The `attn_paged_gate_quant` rows are registered here too (see attn_decode_gq_h256_gqa6_fp8kv): + * the `_gq` entry points are instantiated at every ratio, and the block declares the fused op + * beside its unfused pair, so an unregistered geometry would be reported as a band hole. */ static const RadConstraint cAttnPrefillH256G6Bs4Fp8[] = { C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 4), C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), @@ -3039,8 +2884,8 @@ static const RadConstraint cAttnDecodeH256G6Bs4Bf16[] = { C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 4), C_GE("causal", 0), C_LE("q_len", 10), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), }; -/* The gate and the quantiser as the merge's epilogue, at the four-rank ratio: the gqa12 pair's - * constraints with the ratio and the verify width moved together (`q_len <= 10`, not `<= 5`). */ +/* The gate and quantiser as the merge's epilogue at the four-rank ratio: the gqa12 pair's + * constraints with ratio and verify width moved together (`q_len <= 10`, not `<= 5`). */ static const RadConstraint cAttnDecodeGqH256G6Bs4Fp8[] = { C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 4), C_GE("causal", 0), C_LE("q_len", 10), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), @@ -3059,20 +2904,15 @@ static const RadConstraint cAttnPrefillH128G8Bf16[] = { C_EQ("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 8), C_EQ("block_size", 16), C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), }; -/* NON-CAUSAL IS SERVED AND THE WINDOW IS NOT, and the two halves of that come from different - * places -- which is why one loosens here and the other must not. +/* Non-causal is served, the window is not. * - * `causal` IS A RUNTIME FIELD of R4DArgs that the shared decode kernel already reads: at cz == 0 - * it bounds the key by ctx - 1 instead of by the row's own position, which is exactly a - * block-diffusion drafter's own block attending to the whole context AND to itself - * (r4d_attn_decode_h256_gqa6.hip, klimit). Nothing is compiled out and nothing is added. The gqa4 - * leg states C_GE("causal", 0) over the same kernel and these two do as well, because DSpark - * issues a non-causal gqa8 decode -- 16 heads over 2 kv at head_dim 128, non-causal over 7 noise - * rows. + * `causal` is a runtime field of R4DArgs: at cz == 0 the shared decode kernel bounds the key by + * ctx - 1 instead of the row's own position, which is a block-diffusion drafter's block attending + * to the whole context and itself (r4d_attn_decode_h256_gqa6.hip, klimit). DSpark issues a + * non-causal gqa8 decode (16 heads over 2 kv at head_dim 128, over 7 noise rows). * - * `window` STAYS C_EQ 0, because that one IS a template parameter: this dispatch instantiates the - * kernel at WIN = 0 and a windowed geometry has no bound, no clamp and no second mask term in the - * code that would run. Loosening it would resolve a kernel that silently attends to everything. */ + * `window` stays C_EQ 0 because it is a template parameter: this dispatch instantiates WIN = 0, + * so a windowed geometry would silently attend to everything. */ static const RadConstraint cAttnDecodeH128G8Fp8[] = { C_EQ("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 8), C_EQ("block_size", 16), C_GE("causal", 0), C_LE("q_len", 8), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), @@ -3081,35 +2921,48 @@ static const RadConstraint cAttnDecodeH128G8Bf16[] = { C_EQ("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 8), C_EQ("block_size", 16), C_GE("causal", 0), C_LE("q_len", 8), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), }; -/* KEY RENAME. libr4d writes C_IN("q_dtype","bf16") and C_IN("kv_dtype","bf16"); docs/OPS.md's - * `attn_dense` has one `dtype` because nothing about a dense bf16 tower is mixed-precision. The - * predicate -- "bf16, and nothing else" -- is unchanged. */ -/* NO CONSTRAINT ON `window`. It is optional in the schema, a tower without one does not pass it, - * and a constraint whose key the geometry lacks does not hold -- so C_EQ("window", 0) here made - * this row unreachable for every Qwen vision tower. The kernel attends to the whole segment and - * refuses a non-zero window at launch instead (r4d_rad_attn_vit). */ +/* Two queries per KV head at head_dim 128 (Qwen3-1.7B, Qwen3-ASR's decoder): the gqa8 pair's + * constraints with the ratio and the decode verify width changed together. A decode workgroup + * holds 64 (query, head) rows, so q_len <= 32 at gqa 2. */ +static const RadConstraint cAttnPrefillH128G2Fp8[] = { + C_EQ("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 2), C_EQ("block_size", 16), + C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), +}; +static const RadConstraint cAttnPrefillH128G2Bf16[] = { + C_EQ("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 2), C_EQ("block_size", 16), + C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), +}; +static const RadConstraint cAttnDecodeH128G2Fp8[] = { + C_EQ("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 2), C_EQ("block_size", 16), + C_GE("causal", 0), C_LE("q_len", 32), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), +}; +static const RadConstraint cAttnDecodeH128G2Bf16[] = { + C_EQ("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 2), C_EQ("block_size", 16), + C_GE("causal", 0), C_LE("q_len", 32), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), +}; +/* Key rename: libr4d writes C_IN("q_dtype","bf16") and C_IN("kv_dtype","bf16"); docs/OPS.md's + * `attn_dense` has one `dtype`. The predicate is unchanged. + * + * No constraint on `window`: it is optional and vision towers omit it, and a constraint on an + * absent key does not hold. The kernel refuses a non-zero window at launch (r4d_rad_attn_vit). */ static const RadConstraint cAttnVit[] = { C_EQ("head_dim", 72), C_EQ("gqa", 1), C_EQ("causal", 0), C_IN("dtype", "bf16"), }; -/* `cast` at bf16 -> bf16, which is a strided ROW COPY and is why this row exists. An architecture - * that taps an intermediate residual stream -- DFlash2 conditions its drafter on the trunk's - * hidden states at five layers -- has to move rows out of a buffer the next layer overwrites, and - * the vocabulary already has the op for it. What this row adds is a DEVICE arm: without one `cast` - * resolves to ref alone, so a model using it runs the copy on the host and the reference gate - * refuses the serve. libr4d's 2D copy is exactly the kernel, pitches and all. - * - * The predicate is deliberately from == to == bf16. A widening or narrowing cast is a different - * kernel and this one would reinterpret the bytes rather than convert them. */ +/* `cast` at bf16 -> bf16: a strided row copy, the device arm for an architecture that taps an + * intermediate residual stream (DFlash2 conditions its drafter on the trunk's hidden states at five + * layers) and must copy rows out of a buffer the next layer overwrites. Without it `cast` resolves + * only to ref on the host. Only from == to == bf16: this kernel copies bytes, it does not + * convert. */ static const RadConstraint cCastBf16[] = { C_IN("from", "bf16"), C_IN("to", "bf16"), }; -/* `cast` widening bf16 -> f32: an exact conversion, the form a pooled embedding leaves the - * device in. */ /* The audio attention's window: a query's keys are held in LDS, 64 of them at most. */ static const RadConstraint cAttnLocalRel[] = { C_IN("dtype", "bf16"), C_LE("left", 63), C_EQ("right", 0), }; +/* `cast` widening bf16 -> f32: an exact conversion, the form a pooled embedding leaves the + * device in. */ static const RadConstraint cCastWiden[] = { C_IN("from", "bf16"), C_IN("to", "f32"), }; @@ -3146,9 +2999,9 @@ static const RadConstraint cGdnKktSolve[] = { static const RadConstraint cGdnRecurrentUpdate[] = { C_EQ("head_k", 128), C_EQ("head_v", 128), }; -/* q_len <= 8 IS THE REGISTER WINDOW: the fold preloads a sequence's tokens into registers and +/* q_len <= 8 is the register window: the fold preloads a sequence's tokens into registers and * indexes them at compile time, as the standalone update does. The entry point checks the conv - * cache's own depth against the same bound. */ + * cache's depth against the same bound. */ static const RadConstraint cGdnConvRecurrentUpdate[] = { C_EQ("head_k", 128), C_EQ("head_v", 128), C_EQ("conv_width", 4), C_GE("q_len", 1), C_LE("q_len", 8), @@ -3157,30 +3010,17 @@ static const RadConstraint cGdnGatedRmsNorm[] = { C_EQ("channels", 128), }; -/* ---- all-reduce ------------------------------------------------------------------------------ - * `exact` separates the two, and a caller has to say which it wants: a request that does not - * declare it will accept a lossy wire format gets no kernel rather than the quantised one. - * MESSAGE SIZE separates the one-shot from the two-shot at a width that has both. The two-shot - * rows start above R4D_AR_WIDE_ONESHOT_MAX_ELEMS, which makes that bound a band edge of `numel`: - * the band at or under it resolves only the one-shot, and in the band above both rows match and - * R4D_PRIO_AR_TWOSHOT > R4D_PRIO_AR_ONESHOT hands it the two-shot. The GE is one past the bound so - * the band under it ends ON the bound, a multiple of every DIV here (see pAllReduce's `numel`). The - * choice is the selector's and so it is what the band report names; no entry point substitutes - * one kernel for another. The ti8 wire needs no such key -- exact=0 already separates it, and it - * serves its own small messages exactly. */ /* ---- all-gather ------------------------------------------------------------------------------- - * The vocab-parallel sampler's candidate merge, and nothing else in the engine issues one. No - * `exact` key: a gather MOVES its payload and cannot be lossy, so there is no second row for it - * to be told apart from. dtype is the element SIZE here -- the pairs it carries are half u32 -- - * and BOTH SPELLINGS of each type are listed because the two callers disagree: the arch blocks - * declare `bf16`/`fp32` and core/sample/sampler.cpp declares `f32`. r4d_ar_dtype_code already - * accepts either, so a constraint that took only one would refuse the sampler by a synonym. */ + * Issued only by the vocab-parallel sampler's candidate merge. No `exact` key: a gather moves its + * payload and cannot be lossy. dtype gives the element size (the pairs are half u32), and both + * spellings of each type are listed because the arch blocks declare `bf16`/`fp32` and + * core/sample/sampler.cpp `f32` (r4d_ar_dtype_code accepts either). */ static const RadConstraint cArGather2[] = { C_EQ("world_size", 2), C_IN("dtype", "bf16 fp16 f16 fp32 f32"), C_P2P, }; -/* The same gather at a width whose handshake is the wide family's tree and not one peer flag. The - * dtype set is cArGather2's verbatim for the same reason -- the two callers' synonyms. */ +/* The same gather at a width whose handshake is the wide family's tree, not one peer flag; the + * dtype set is cArGather2's. */ static const RadConstraint cArGather4[] = { C_EQ("world_size", 4), C_IN("dtype", "bf16 fp16 f16 fp32 f32"), C_P2P, @@ -3190,6 +3030,14 @@ static const RadConstraint cArGather8[] = { C_P2P, }; +/* ---- all-reduce ------------------------------------------------------------------------------ + * `exact` separates the exact sum from the lossy wire; a request that does not declare it gets no + * kernel. Message size separates one-shot from two-shot at widths that have both: the two-shot rows + * start above R4D_AR_WIDE_ONESHOT_MAX_ELEMS, so the band at or under it resolves only the one-shot, + * and above it both match and R4D_PRIO_AR_TWOSHOT > R4D_PRIO_AR_ONESHOT picks the two-shot. The GE + * is one past the bound so the lower band ends on it, a multiple of every DIV here (see + * pAllReduce's `numel`). The selector makes the choice, so the band report names it. The ti8 wire + * needs no such key: exact=0 separates it, and it serves its own small messages exactly. */ static const RadConstraint cArExact[] = { C_EQ("world_size", 2), C_EQ("exact", 1), C_IN("dtype", "bf16 fp16 fp32"), C_P2P, @@ -3223,6 +3071,14 @@ static const RadConstraint cArTsExact4[] = { C_LE("numel", R4D_AR_TWOSHOT_WIDE_MAX_ELEMS), C_P2P, }; +/* The same at `overlap` 1 (tArTs4Lane), so a pipelined prefill on the exact wire does not get the + * wide launch above, which holds the card beside the other piece's work. */ +static const RadConstraint cArTsExact4Lane[] = { + C_EQ("world_size", 4), C_EQ("exact", 1), C_IN("dtype", "bf16 fp16 fp32"), + C_DIV("numel", 64), C_GE("numel", R4D_AR_WIDE_ONESHOT_MAX_ELEMS + 1), + C_LE("numel", R4D_AR_TWOSHOT_WIDE_MAX_ELEMS), + C_EQ("overlap", 1), C_P2P, +}; static const RadConstraint cArTsExact8[] = { C_EQ("world_size", 8), C_EQ("exact", 1), C_IN("dtype", "bf16 fp16 fp32"), C_DIV("numel", 64), C_GE("numel", R4D_AR_WIDE_ONESHOT_MAX_ELEMS + 1), @@ -3251,11 +3107,16 @@ static const RadConstraint cArTi8Ts4[] = { C_EQ("world_size", 4), C_EQ("exact", 0), C_IN("dtype", "bf16 fp16"), C_DIV("numel", 128), C_P2P, }; +/* The same at `overlap` 1 (tArTs4Lane). */ +static const RadConstraint cArTi8Ts4Lane[] = { + C_EQ("world_size", 4), C_EQ("exact", 0), C_IN("dtype", "bf16 fp16"), C_DIV("numel", 128), + C_EQ("overlap", 1), C_P2P, +}; /* ---- GEMM ------------------------------------------------------------------------------------ - * DFlash2's grouped dynamic depthwise convolution. block_size is not listed as a predicate: the - * body masks the position with block_size-1, so only powers of two are admissible, and that is a - * property of the value rather than a bound a constraint can express. The entry point rejects it. */ + * DFlash2's grouped dynamic depthwise convolution. block_size must be a power of two (the body + * masks the position with block_size-1), which no constraint can express; the entry point + * rejects others. */ static const RadConstraint cDflashConv[] = { C_EQ("taps", 2), C_EQ("group_size", 16), C_DIV("hidden_size", 128), C_IN("dtype", "bf16"), }; @@ -3281,38 +3142,28 @@ static const RadConstraint cExpertScale[] = { /* ---- the routed mixture of experts ---------------------------------------------------------- * - * The router's `n_expert` bound is a real limit rather than a tuning choice: the selection keeps a - * lane's share of a row's logits in registers, and the LDS histogram the scatter's small form - * keeps is one word an expert. Both are sized at r4d_moe.hip's kMaxExpert -- see the note on that - * constant below -- and a wider model wants a different distribution, which would be a different - * kernel rather than a larger constant. + * The router's `n_expert` bound is a hard limit: the selection keeps a lane's share of a row's + * logits in registers, and the scatter's small form keeps a one-word-per-expert LDS histogram, + * both sized at r4d_moe.hip's kMaxExpert (see cRouterTopK). A wider model needs a different kernel. * - * The GEMM's N%64 is the block's N tile and K%128 is the fp8 scale block. `group` has to BE that - * block: a checkpoint quantised at any other edge is not one these kernels read, and saying so as - * a predicate is what makes the selector decline it rather than the launch. */ + * The GEMM's N%64 is the block's N tile and K%128 the fp8 scale block; `group` must equal that + * block, so the selector, not the launch, declines any other quantisation. */ static const RadConstraint cScaleRows[] = { C_GE("M", 1), C_GE("n", 1), C_IN("dtype", "bf16"), }; -/* 512 IS r4d_moe.hip's kMaxExpert and it is a real limit of those kernels: the router keeps a - * lane's share of the row's logits in registers (16 a lane at 512, which is a separate - * instantiation) and both scatter forms keep an n_expert + 1 histogram in LDS. Qwen3.8-Flash-Next - * routes 10 of 512, which is the widest geometry the bound serves. */ -/* THE GATED RESIDUAL. `n <= 7552` and `hc <= 4` together bound hc*n at 30208, inside the 30576 - * elements of bf16 that kernel A can hold the normed row in once its own 4384 bytes of static - * planes are out of the 64 KiB (kHcLdsMaxHN) -- claiming a wider stream would be claiming a band - * the shared allocation cannot serve, and there is no fallback under these rows to catch it - * (libref is HOST domain, so it is the oracle and not a second implementation). 7552 is the - * widest multiple of 128 under that bound at hc = 4. `n` divisible by 128 is the workgroup's - * channel tile AND the fp8 scale group, which are deliberately the same number so that a workgroup - * owns whole groups. */ +/* The gated residual. `n <= 7552` and `hc <= 4` bound hc*n at 30208, inside the 30576 bf16 + * elements kernel A can hold the normed row in after its 4384 bytes of static planes in 64 KiB + * (kHcLdsMaxHN); no device fallback exists for a wider stream (libref is host domain). 7552 is the + * widest multiple of 128 under that bound at hc = 4. `n` divisible by 128 is both the workgroup's + * channel tile and the fp8 scale group, so a workgroup owns whole groups. */ static const RadConstraint cHcRead[] = { C_GE("M", 1), C_DIV("n", 128), C_LE("n", 7552), C_GE("hc", 2), C_LE("hc", 4), C_GE("lowrank", 1), C_LE("group", 128), C_LE("inject", 1), C_IN("dtype", "bf16"), C_IN("mix", "bf16"), }; -/* The mixing matrices as E4M3 rows (r4d_hc_fp8.h). `n` a multiple of 512 keeps hc*n a whole number - * of the down dot's 512-element steps at any hc; `lowrank` a multiple of 64 up to 512 makes the up - * row's quarter -- its scale group -- one to eight sixteen-code loads. */ +/* The mixing matrices as E4M3 rows (r4d_hc_fp8.h). `n` a multiple of 512 keeps hc*n a whole + * number of the down dot's 512-element steps at any hc; `lowrank` a multiple of 64 up to 512 makes + * the up row's quarter (its scale group) one to eight sixteen-code loads. */ static const RadConstraint cHcReadE4m3[] = { C_GE("M", 1), C_DIV("n", 512), C_LE("n", 7552), C_GE("hc", 2), C_LE("hc", 4), C_DIV("lowrank", 64), C_LE("lowrank", 512), C_LE("group", 128), C_LE("inject", 1), @@ -3321,8 +3172,8 @@ static const RadConstraint cHcReadE4m3[] = { static const RadConstraint cHcPlain[] = { C_GE("M", 1), C_GE("n", 1), C_GE("hc", 2), C_LE("hc", 8), C_IN("dtype", "bf16"), }; -/* `n` is bounded by LDS: nh is hc*n and ne is n more, both bf16, and both live for the whole of - * the second phase. 28672 elements is that budget at hc 4, which 2560 sits well inside. */ +/* `n` is bounded by LDS: nh (hc*n) and ne (n) are both bf16 and live through the second phase; + * 28672 elements is that budget at hc 4. */ static const RadConstraint cMtpEnter[] = { C_GE("M", 1), C_GE("n", 128), C_LE("n", 5734), C_GE("hc", 2), C_LE("hc", 4), C_IN("dtype", "bf16"), C_IN("fc", "bf16"), @@ -3333,14 +3184,13 @@ static const RadConstraint cMtpEnterE4m3[] = { C_GE("M", 1), C_DIV("n", 128), C_LE("n", 5734), C_GE("hc", 2), C_LE("hc", 4), C_IN("dtype", "bf16"), C_IN("fc", "e4m3"), }; +/* 512 is r4d_moe.hip's kMaxExpert, a hard limit: the router keeps a lane's share of the row's + * logits in registers (16 per lane at 512, a separate instantiation) and both scatter forms keep an + * n_expert + 1 histogram in LDS. Qwen3.8-Flash-Next routes 10 of 512. */ static const RadConstraint cRouterTopK[] = { C_GE("M", 1), C_GE("n_expert", 1), C_LE("n_expert", 512), C_GE("top_k", 1), C_LE("top_k", 32), C_IN("dtype", "bf16"), }; -static const RadConstraint cRouterTopkScatter[] = { - C_GE("M", 1), C_GE("n_expert", 1), C_LE("n_expert", 512), C_GE("top_k", 1), - C_LE("top_k", 32), C_IN("dtype", "bf16"), -}; /* The selection's bounds and the skinny GEMM's decode band: four 16-row tiles. */ static const RadConstraint cRouterGemmTopkScatter[] = { C_GE("M", 1), C_LE("M", 64), C_DIV("K", 16), C_GE("n_expert", 1), C_LE("n_expert", 512), @@ -3353,30 +3203,25 @@ static const RadConstraint cMoeGemmQ[] = { C_GE("M", 1), C_DIV("N", 64), C_DIV("K", 128), C_GE("n_expert", 1), C_LE("n_expert", 65536), C_GE("top_k", 1), C_EQ("group", 128), C_IN("dtype", "fp8a8"), }; -/* The same op at a FOUR-BIT expert weight. Identical band, identical operands -- only the stored - * weight plane and its scale grid differ, which is why the two rows share a schema and are told - * apart by the dtype string alone. +/* The same op at a four-bit expert weight: same band and operands, only the stored weight plane + * and scale grid differ, so the dtype string alone separates the rows. * - * `w4a8h` IS THE SAME ROW AND THE SAME LAUNCH. It says the stored weight was rotated by a 128-wide - * Hadamard along K before it was quantised, and the residual factor was folded into the stored - * scale -- so the kernel still just multiplies codes by scales and there is nothing here to - * branch on. What differs is the LAYOUT TAG the hooks return, which is what stops a container - * converted one way from being served the other, and the activation the graph must pair with it - * (`had_quant_act_fp8`, not `quant_act_fp8`). A second row would be the same entry point, the same - * band and the same operands under a second name. + * `w4a8h` is the same row and launch: the weight was rotated by a 128-wide Hadamard along K before + * quantisation, with the residual factor folded into the scale, so the kernel does not branch on + * it. What differs is the layout tag (so a container converted one way is not served the other) + * and the paired activation (`had_quant_act_fp8`, not `quant_act_fp8`). * - * `w4nla8h` IS THE ROTATED PLANE WITH ANOTHER CODE TABLE: the codes index libquant's w4nl levels - * instead of -8..7, and the launcher hands the kernel that table (r4d_args.h). Same bytes a code, - * same scale grid, same activation; the layout hook checks the container's table against the - * kernel's before it serves it. + * `w4nla8h` is the rotated plane with another code table: codes index libquant's w4nl levels + * instead of -8..7, and the launcher passes the table (r4d_args.h). The layout hook checks the + * container's table against the kernel's. * - * `w4nl64a8h` IS w4nla8h WITH A SCALE A 64 OF K: one E4M3 byte under the fixed kW4G64Scale, so the - * same bytes as a bf16 scale a 128; `w4nl32a8h` one a 32, twice those bytes. `group` stays 128 -- - * the staged K block and the rotation -- and the kernel sums each scale group of it apart. + * `w4nl64a8h` is w4nla8h with one E4M3 scale per 64 of K under the fixed kW4G64Scale (the same + * bytes as a bf16 scale per 128); `w4nl32a8h` one per 32, twice the bytes. `group` stays 128 (the + * staged K block and the rotation), and the kernel sums each scale group separately. * - * `w5nl64a8h` IS w4nl64a8h AT FIVE BITS: the codes index libquant's 32-level w5nl table, whose - * high bit is the sign, so the kernel expands the low four as a w4nl code over the sixteen - * magnitudes and sets the sign from a bit plane stored after each row's nibbles. */ + * `w5nl64a8h` is w4nl64a8h at five bits: codes index libquant's 32-level w5nl table, whose high bit + * is the sign; the kernel expands the low four as a w4nl magnitude and sets the sign from a bit + * plane stored after each row's nibbles. */ static const RadConstraint cMoeGemmW4[] = { C_GE("M", 1), C_DIV("N", 64), C_DIV("K", 128), C_GE("n_expert", 1), C_LE("n_expert", 65536), C_GE("top_k", 1), C_EQ("group", 128), @@ -3391,11 +3236,11 @@ static const RadConstraint cMoeGather[] = { C_GE("M", 1), C_GE("n", 1), C_GE("top_k", 1), C_IN("dtype", "bf16"), }; +/* R <= 32 is stage 2's PT (R4D_TOPK_PT2): a lane holds the whole answer, so no distribution of the + * candidates over lanes can lose one. The merge and the rerank share the limit. */ static const RadConstraint cRowTopK[] = { - C_DIV("N", 8), C_GE("M", 1), C_GE("R", 1), C_LE("R", 1024), C_IN("dtype", "bf16"), + C_DIV("N", 8), C_GE("M", 1), C_GE("R", 1), C_LE("R", 32), C_IN("dtype", "bf16"), }; -/* R <= 32 is stage 2's PT, and the merge carries the same one for the same reason: a lane holds - * the whole answer, so no distribution of the candidates over lanes can lose one. */ static const RadConstraint cRowTopKMerge[] = { C_GE("M", 1), C_GE("R", 1), C_LE("R", 32), C_GE("world_size", 1), C_IN("dtype", "bf16"), }; @@ -3406,9 +3251,8 @@ static const RadConstraint cLogitRerank[] = { static const RadConstraint cGemmNt[] = { C_LE("M", 16), C_DIV("K", 256), C_IN("dtype", "bf16"), }; -/* NO 64-ROW CAP: grid.y covers any row count this kernel is given, so the band is the grid's reach - * and not a launcher guard. A cap here would force a caller with a taller projection -- the gated - * delta net's a|b, for one -- to slice it. */ +/* No 64-row cap: grid.y covers any row count, so the band is the grid's reach. A cap would force a + * caller with a taller projection (the gated delta net's a|b) to slice it. */ static const RadConstraint cGemmNt64[] = { C_LE("M", 65536), C_DIV("K", 16), C_IN("dtype", "bf16"), }; @@ -3448,26 +3292,16 @@ static const RadConstraint cGemmNtMxfp4A8[] = { }; /* ---- block-scaled fp8 ------------------------------------------------------------------------- * - * THE `group` PREDICATE IS THIS TABLE'S OWN, and the only one on this family that has no - * kernel-side counterpart: the kernel takes no `group` argument on a GEMM -- its quantised GEMMs - * read the group off a build flag -- but docs/OPS.md's `gemm_nt_q` schema carries one and this - * family's block is a property of the checkpoint on disk rather than of the build. A caller - * declaring a different group is asking for a format these kernels do not read, and the right - * answer is no kernel rather than a silent 128. - * - * K's divisor differs between the two fp8a8 rows and is not cosmetic: the narrow instantiation - * stages a whole 256-byte cacheline a row, and a K that is only a multiple of 128 makes a split - * slice run one tile past its own end. The entry point refuses it. */ + * The `group` predicate has no kernel-side counterpart (the kernel's quantised GEMMs take the + * group from a build flag), but docs/OPS.md's `gemm_nt_q` schema carries one and this family's + * block belongs to the checkpoint. Any other group gets no kernel rather than a silent 128. */ static const RadConstraint cGemmNtFp8A16[] = { C_LE("M", 8), C_DIV("K", R4D_FP8_BLOCK), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "fp8a16"), }; -/* K DIV 128, NOT 256, AND THE DECLARED NUMBER IS THE ONE THAT DECIDES. The entry serves a K that - * is a multiple of 128 by staging a 128-byte tile instead of a 256-byte one (see narrow_fk), and - * relaxing that runtime guard alone achieves nothing: the resolver offers a call to a kernel by - * its DECLARED constraints, so a row claiming 256 never sees the shape at all. That is the - * band-coverage hazard read backwards -- a kernel that does not claim a band it can serve is as - * invisible as one that claims a band it cannot. */ +/* K DIV 128, not 256: the entry serves a K that is a multiple of 128 by staging a 128-byte tile + * instead of a 256-byte one (narrow_fk). The resolver offers shapes by declared constraints, so the + * row must claim the band it can serve. */ static const RadConstraint cGemmNtFp8A8M16[] = { C_LE("M", 64), C_DIV("K", 128), C_DIV("N", 16), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "fp8a8"), @@ -3485,41 +3319,25 @@ static const RadConstraint cGemmNtI8A8Tiled[] = { C_DIV("K", R4D_FP8_BLOCK), C_DIV("N", R4D_FP8_BLOCK), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "i8a8"), }; -/* libr4d's row says `K DIV 4`; the key rename to docs/OPS.md's `n` is the same one every quantiser - * row here makes. */ +/* libr4d's `K DIV 4`, renamed to docs/OPS.md's `n` as in every quantiser row here. */ static const RadConstraint cQuantActFp8[] = { C_DIV("n", 4), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"), }; -/* The rotated form wants n DIVISIBLE BY THE GROUP, not merely by 4. A rotation block cannot - * straddle the end of a row: the ragged tail the unrotated kernel writes zero-padded would mix - * real values with padding inside one butterfly, and there is no weight block on the other side - * that was rotated the same way. */ +/* The rotated form needs n divisible by the group, not just by 4: a rotation block cannot + * straddle the end of a row (a zero-padded ragged tail would mix real values and padding in one + * butterfly, matching no rotated weight block). */ static const RadConstraint cHadQuantActFp8[] = { C_DIV("n", R4D_FP8_BLOCK), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"), }; -/* ParoQuant's dense rotation: the same whole-group rule (a rotation group cannot straddle a row's end), - * and `out` one of the two quantisers its epilogue has. */ +/* ParoQuant's dense rotation: the same whole-group rule, and `out` one of the two quantisers its + * epilogue has. */ static const RadConstraint cGivensDense[] = { C_DIV("n", R4D_FP8_BLOCK), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"), C_IN("out", "i8 fp8"), }; -/* The dtype is the INPUT's, and the input is already quantised -- so it is `fp8a8` and not `bf16` - * the way every other row in this family reads it. A four-multiple `n` is the staging slot (one - * dword of four codes); the 64-wide C tile needs `n` to be nothing in particular, because a ragged - * tile masks. */ -/* The head dim is bounded by the LDS row the block reduction needs, and the rotary width by the - * neox pairing (`rot/2` apart, so it must be even and fit inside the head). 128 and 64 are what - * this checkpoint has; the bounds are the kernel's, not the model's. */ -/* A lane owns n/32 dims of both operands, so n is a wave multiple and at most eight of them. The - * head bound is the register file: the query stays resident across the whole block loop. */ -/* No dtype: every operand is f32 or i32 by the op's meaning and none of them is an activation. */ -/* The sequence bound is the loop that finds which sequence owns a work item: it is recomputed by - * every workgroup, so it is a handful of compares and not a table. */ -/* NO BOUND ON `seqs` HERE. The declared value is a deployment MAXIMUM -- rad-convert declares at - * 256 -- and a row that refused it would not resolve at convert, so the weights the op reads - * would never be written into the container and the model would refuse to load with a missing - * weight rather than with a band. The real count comes off `cu_seqlens` at issue, and the - * launcher is where it is checked. */ +/* No bound on `seqs`: the declared value is a deployment maximum (rad-convert declares 256), and a + * row refusing it would not resolve at convert, leaving the op's weights out of the container. The + * real count comes from `cu_seqlens` at issue and the launcher checks it. */ static const RadConstraint cQsaWork[] = { C_GE("n", 1), C_GE("ratio", 1), C_GE("seqs", 1), C_GE("work", 1), C_IN("dtype", "bf16"), }; @@ -3528,35 +3346,42 @@ static const RadConstraint cQsaTailStore[] = { C_GE("n", 1), C_GE("ratio", 1), C_GE("seqs", 1), C_IN("dtype", "bf16"), }; +/* No dtype: every operand is f32 or i32. */ static const RadConstraint cQsaSelect[] = { C_GE("blocks", 1), C_GE("topk", 1), C_GE("ratio", 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[] = { C_DIV("n", 32), C_GE("n", 32), C_LE("n", 256), C_GE("heads", 1), C_LE("heads", 8), C_GE("blocks", 1), C_IN("dtype", "bf16"), }; +/* The head dim is bounded by the LDS row the block reduction needs, and the rotary width by the + * neox pairing (`rot/2` apart, so even and inside the head). The bounds are the kernel's. */ static const RadConstraint cQsaBlockKey[] = { C_GE("n", 32), C_LE("n", 256), C_DIV("n", 32), C_GE("ratio", 1), C_GE("rotary_dim", 0), C_IN("dtype", "bf16"), }; +/* The dtype is the input's, already quantised: `fp8a8`, not `bf16` as elsewhere in this family. + * `n` a multiple of 4 is the staging slot (one dword of four codes); the 64-wide C tile masks a + * ragged tile. */ static const RadConstraint cGramAccum[] = { C_DIV("n", 4), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "fp8a8"), }; -/* The bf16 form has no scale grid, so `group` constrains nothing; the staging slot is four elements - * of a row, which is the only divisor left. */ +/* The bf16 form has no scale grid, so `group` constrains nothing; the staging slot is four + * elements of a row. */ static const RadConstraint cGramAccumBf16[] = { C_DIV("n", 4), C_IN("dtype", "bf16"), }; -/* The two fused forms carry the quantiser's own row and nothing else. That is the whole difference - * from the int8 fusions below, whose rotation makes the width a power-of-two divisor question. */ +/* The fused fp8 forms carry the quantiser's own constraints; the int8 fusions below also need the + * rotation's divisor. */ static const RadConstraint cRmsNormQuantFp8[] = { C_DIV("n", 4), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"), }; -/* `n DIV 8`, not 4: this one is the all-reduce's message as well as the norm's input and a block - * pushes its rows as 16B WORDS, so a row has to be a whole number of them. world_size is a hard - * constraint for the reason cArLnHadQuantI8 gives -- the handshake is one peer flag per block. */ +/* `n DIV 8`, not 4: `x` is also the all-reduce's message, pushed as 16-byte words. world_size 2: + * the handshake is one peer flag per block (as cArLnHadQuantI8). */ static const RadConstraint cArRmsNormQuantFp8[] = { C_DIV("n", 8), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"), C_EQ("world_size", 2), @@ -3569,11 +3394,10 @@ static const RadConstraint cArHcWrite[] = { C_EQ("world_size", 2), C_P2P, }; -/* The same bounds at four ranks, where the handshake is the wide family's (r4d_ar_wide.h). Exact - * wire only: the four-rank lossy wire is the ti8 two-shot and has no fused form, so a `wire` 6 - * request is a selection miss here and its caller keeps the unfused pair, where an init refusal - * would stop declare. The caller states `wire` 0 on the exact form, because a constraint on an - * absent key does not hold; the init and the entry still refuse any other wire. */ +/* The same at four ranks, with the wide family's handshake (r4d_ar_wide.h). Exact wire only: the + * four-rank lossy wire is the ti8 two-shot, which has no fused form, so `wire` 6 misses selection + * and the caller keeps the unfused pair. Callers must state `wire` 0, since a constraint on an + * absent key does not hold; init and the entry refuse other wires. */ static const RadConstraint cArHcWrite4[] = { C_GE("M", 1), C_DIV("n", 8), C_GE("hc", 2), C_LE("hc", 8), C_IN("dtype", "bf16"), C_EQ("world_size", 4), C_EQ("wire", 0), @@ -3585,7 +3409,7 @@ static const RadConstraint cArGatherHcWrite[] = { C_EQ("world_size", 2), C_GE("top_k", 1), C_LE("top_k", 64), C_P2P, }; -/* The same at four ranks, exact wire only and constrained so for cArHcWrite4's reason. */ +/* The same at four ranks, exact wire only (see cArHcWrite4). */ static const RadConstraint cArGatherHcWrite4[] = { C_GE("M", 1), C_DIV("n", 8), C_GE("hc", 2), C_LE("hc", 8), C_IN("dtype", "bf16"), C_EQ("world_size", 4), C_EQ("wire", 0), C_GE("top_k", 1), C_LE("top_k", 64), @@ -3594,23 +3418,18 @@ static const RadConstraint cArGatherHcWrite4[] = { static const RadConstraint cGatedQuantFp8[] = { C_DIV("n", 4), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"), }; -/* The rotated form wants n divisible by the GROUP and not merely by 4, for the reason - * cHadQuantActFp8 gives: a butterfly cannot straddle the end of a row. */ +/* n divisible by the group, as in cHadQuantActFp8. */ static const RadConstraint cGatedHadQuantFp8[] = { C_DIV("n", R4D_FP8_BLOCK), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"), }; -/* The narrow GEMM's row plus the fold's own two. `N DIV 256` is `nout DIV 128` restated on the - * weight's extent: a block emits exactly one 128-column scale group, so a fused width that is not - * a multiple of 128 would put a group across two blocks with nowhere to finish it. `act IN silu` - * because only that arm is compiled -- a sigmoid gate is a gated attention's and reaches - * `gate_quant_fp8`, whose operands are two buffers rather than one plane. +/* The narrow GEMM's row plus the fold's own constraints. `N DIV 256` is `nout DIV 128` on the + * weight's extent: a block emits exactly one 128-column scale group. `act IN silu` because only + * that arm is compiled (a sigmoid gate reaches `gate_quant_fp8`). * - * `N GE 2048` IS THE SPLIT-K RULE, NOT A TUNING. The fold has no partial plane and no second - * launch, so its entry point REFUSES any shape the narrow split rule would widen, and that rule - * splits whenever K >= 512 and the grid's wave count, N/16, is under its target of 128 -- which is - * every N under 2048. The one shape it serves below that, K = 256, is a 256-wide residual stream - * no model here has. Claiming the band anyway hands the op a kernel that fails at issue, where an - * unclaimed band is reported at declare. */ + * `N GE 2048` is the split-K rule: the fold has no partial plane, so its entry point refuses any + * shape the narrow split rule would split, which is K >= 512 with N/16 under 128 waves, i.e. every + * N under 2048 (the K = 256 exception is a residual width no model has). Claiming that band would + * fail at issue instead of being reported at declare. */ 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"), @@ -3618,9 +3437,8 @@ static const RadConstraint cGemmNtQGatedFp8[] = { static const RadConstraint cGateQuantFp8[] = { C_DIV("n", 4), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"), }; -/* libr4d's cSampleChain, unchanged. The kernel has no geometry -- the radix passes are over the 256 - * buckets of a float's bytes, not over the vocabulary -- so a row with no predicate at all would - * match a query that forgot to say what it wanted. */ +/* libr4d's cSampleChain. The kernel has no geometry constraint (the radix passes run over a + * float's 256 byte buckets), but a row with no predicate would match a query that named nothing. */ static const RadConstraint cSampleChain[] = { C_GE("n_vocab", 1), }; @@ -3629,9 +3447,8 @@ static const RadConstraint cQuantActI8[] = { C_DIV("n", 16), C_IN("dtype", "bf16"), }; /* `n DIV 16`: a k step of the fragment order is sixteen bytes of one row. The row is staged in LDS - * as bf16 for the cross-thread fragment store: `n <= 30720` is the 60 KiB the shims bound it to, - * stated here so a wider row is refused at selection, where the caller can keep the unfused chain, - * and not at its first launch. */ + * as bf16 for the cross-thread fragment store; `n <= 30720` is the shims' 60 KiB bound, stated + * here so a wider row is refused at selection and the caller can keep the unfused chain. */ static const RadConstraint cRmsNormQuantI8[] = { C_DIV("n", 16), C_LE("n", 30720), C_IN("dtype", "bf16"), }; @@ -3652,11 +3469,11 @@ static const RadConstraint cHadQuantActI8[] = { static const RadConstraint cRmsNormHadQuantI8[] = { C_DIV("n", 16), C_DIV("n", 128), C_LE("group", 512), C_IN("dtype", "bf16"), }; -/* world_size is a hard constraint, not a preference: the handshake is one peer flag per block. - * `n <= 16256` is the widest row whose fp32 staging fits LDS beside the reduction planes at the - * widest workgroup (r4d_ar_ln_blocks_min), rounded down to the 128 above. The compressed wire also - * stages every row a block owns, which bounds M by the flag capacity times the rows that fit; that - * product is not a predicate, so the shim refuses it by name. */ +/* world_size 2: the handshake is one peer flag per block. `n <= 16256` is the widest row whose + * fp32 staging fits LDS beside the reduction planes at the widest workgroup + * (r4d_ar_ln_blocks_min), rounded down to a multiple of 128. The compressed wire also stages every + * row a block owns, bounding M by the flag capacity times the rows that fit; the shim checks that + * product. */ static const RadConstraint cArLnHadQuantI8[] = { C_DIV("n", 16), C_DIV("n", 128), C_LE("n", 16256), C_LE("group", 512), C_IN("dtype", "bf16"), C_EQ("world_size", 2), @@ -3686,28 +3503,23 @@ static const RadConstraint cDequantW4Bf16[] = { C_DIV("N", 16), C_DIV("K", 64), C_IN("dtype", "w4"), }; -/* ---- THE INT4 / INT8 / ROTATED-QUANT FAMILY IS RETAINED ON PURPOSE --------------------------- +/* ---- the int4 / int8 / rotated-quant family, retained ------------------------------------------ * * No architecture in this tree resolves a dense w4a8, w8a8, w4a16 or `*_had_quant_i8` row, and - * `rad-quantize`'s w4_g128 output has no consumer in an engine run. They stay because a kernel - * family is far cheaper to carry than to rewrite. - * - * So the rows below are not dead, they are UNRESOLVED, and the difference is which plugin exists - * rather than whether the kernel works. `rad-kbench --bench` still covers them and r4d_selftest - * still checks the fusion claims, which is what keeps "retained" from decaying into "rotted". + * `rad-quantize`'s w4_g128 output has no engine consumer. The rows stay because carrying a kernel + * family is cheaper than rewriting it; `rad-kbench --bench` covers them and r4d_selftest checks + * the fusion claims. */ /* ---- rows whose band is read off the entry point --------------------------------------------- - * The constraints below come from the entry point's OWN rejection tests and its header prose - * rather than from a kernel-side row, which is the weaker source a row table exists to replace -- - * so each is marked. + * These constraints come from the entry point's own rejection tests and header rather than a + * kernel-side row, a weaker source, so each is marked. */ -/* r4d_gemm_w8a8_nt_m64. Prose: same fragment order as the 4-bit kernel at twice the radix, one - * f16 scale per (row, group of 128) in an f16-ONLY plane. Rejection tests mirror the w4a8 kernel's - * (N % 16, K % (SK*group)); MAX_M is 32768 and explicitly "not structural", but the kernel is a - * skinny one and the tiled sibling covers above 64, so the band bound is transcribed from the - * w4a8 row it is a copy of. */ +/* r4d_gemm_w8a8_nt_m64: the 4-bit kernel's fragment order at twice the radix, one f16 scale per + * (row, group of 128) in an f16-only plane. Rejection tests mirror the w4a8 kernel's (N % 16, + * K % (SK*group)). Its MAX_M of 32768 is not structural; as a skinny kernel with a tiled sibling + * above 64, it takes the w4a8 row's band. */ static const RadConstraint cGemmNtW8A8[] = { C_LE("M", 64), C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w8a8"), }; @@ -3727,55 +3539,44 @@ static const RadConstraint cGemmMxfp4A8Decode[] = { static const RadConstraint cGemmMxfp4A8Tiled[] = { C_GE("M", 1), C_DIV("K", 64), C_DIV("N", 16), C_IN("dtype", "mxfp4a8"), }; -/* r4d_gemm_w8a8_tiled. The same kernel at radix 8; the asym arm exists in the .hip but is NOT - * declared in r4d.h, so this plugin cannot reach it and `w8a8_asym` is deliberately absent from - * the dtype set. */ +/* r4d_gemm_w8a8_tiled: the same kernel at radix 8. Its asym arm is not declared in r4d.h, so + * `w8a8_asym` is absent from the dtype set. */ static const RadConstraint cGemmW8A8Tiled[] = { C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 256), C_IN("dtype", "w8a8"), }; -/* r4d_gemm_w4a8_prefill. Entry point: N % BN and K % group, where BN is the VARIANT's block width - * -- 256 at the default and at every variant listed below except the two 1024-thread arms. N % - * 256 is the necessary condition for the default; a variant whose BN does not divide N is refused - * by the shim, which is the per-call half of spec §2.1. */ +/* r4d_gemm_w4a8_prefill. Entry point: N % BN and K % group, BN being the variant's block width + * (256 except for the two 1024-thread arms). N % 256 is the default's condition; the shim refuses + * a variant whose BN does not divide N (the per-call half of spec §2.1). */ static const RadConstraint cGemmW4A8Prefill[] = { C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 256), C_IN("dtype", "w4a8"), }; /* =================================================================================== tunables * - * spec §15: constraint matching finds a kernel that is CORRECT for a geometry; the tile - * configuration is a property of the shape and the machine. What follows is the SPACE each of - * those kernels can be instantiated over, one axis at a time, plus the cross-axis legality test - * that a product of independent lists cannot express. Every axis carries the value an untuned - * install runs, so a fresh card is fast rather than broken. + * spec §15: constraint matching finds a kernel that is correct for a geometry; the tile + * configuration depends on the shape and the machine. Below is the space each kernel can be + * instantiated over, one axis at a time, plus cross-axis legality tests a product of independent + * lists cannot express. Each axis carries the value an untuned install runs. * - * AXES, NOT A LIST OF PRE-NAMED COMBINATIONS, and the difference is not cosmetic. A hand-written - * list of points has holes an axis list cannot have: a ladder that skips one value leaves every - * shape that wanted it running on a tile sized for something else, silently. Thirty names over - * five axes reach thirty of nine hundred points. - * - * Naming points also keeps the tuning LAW -- ladders, caps, pick_sk -- inside this plugin's launch - * adapter as C++, where an out-of-tree author cannot write the same thing. Declaring the space is - * what lets the core tune a library it was not compiled against. + * Axes rather than named points: a hand-written point list has holes (thirty names over five axes + * reach thirty of nine hundred points), and declaring the space lets the core tune a library it + * was not compiled against. */ /* ------------------------------------------------------------------- the skinny GEMM's axes * - * (WV, SK, MB, NPW, NT). Zero means "decide at issue" on the two axes that have a law -- SK is - * then the split count the shape's own ladder picks and MB covers every row tile in one block -- - * and those laws stay in r4d_gemm_args.h because they read M and the N tile count, which exist only - * at issue. A TUNED value overrides the law; it never merges with it. - * - * A point in this space is what a name like "wv1_sk8_mb3_npw4" abbreviates: wv=1 sk=8 mb=3 npw=4 - * nt=0. The space holds nine hundred of them. */ + * (WV, SK, MB, NPW, NT). Zero means "decide at issue" on the two axes with a law: SK is then the + * shape's own ladder and MB covers every row tile in one block. The laws live in r4d_gemm_args.h + * because they read M and the N tile count, known only at issue. A tuned value replaces the law. + * A point such as "wv1_sk8_mb3_npw4" is wv=1 sk=8 mb=3 npw=4 nt=0; the space has nine hundred. */ static const int64_t kGemmWv[] = { 1, 2, 4 }; static const int64_t kGemmSk[] = { 0, 1, 2, 4, 5, 8, 10, 16, 20, 32 }; static const int64_t kGemmMb[] = { 0, 1, 2, 3, 4 }; static const int64_t kGemmNpw[] = { 1, 2, 4 }; static const int64_t kGemmNt[] = { 0, 1 }; -/* THE TILE IS (BM, BN), named as one axis because each value is one compiled arm. 0 is the - * shape's own choice; see r4d_rad_gemm_bf16_tiled. */ +/* The tile (BM, BN) is one axis because each value is one compiled arm. 0 is the shape's own + * choice; see r4d_rad_gemm_bf16_tiled. */ static const int64_t kGemmBf16Tile[] = { 0, 1, 2 }; static const RadTunable tGemmBf16Tiled[] = { { "tile", kGemmBf16Tile, NELEM(kGemmBf16Tile), 0, @@ -3789,17 +3590,11 @@ static const RadTunable tGemmSkinny[] = { { "nt", kGemmNt, NELEM(kGemmNt), 1, "non-temporal weight loads" }, }; -/* wv*sk*32 IS THE BLOCK'S THREAD COUNT and 1024 is the hardware's ceiling; the per-MB/NPW bound - * is tighter still and r4d_gemm_args.h's block_bound() owns it, because it depends on the bound - * RULE which is a property of the row rather than of the geometry. This is the part that can be - * decided from the geometry alone, and it is here so the tuner skips ~40% of the space without - * launching anything. - * - * K MUST DIVIDE INTO SK SLICES OF THE KERNEL'S OWN UNIT -- 16 for the bf16 kernels, 128 wherever - * a quantised weight carries a scale per 128 K. `dtype` is a geometry parameter on every one of - * these rows, so the unit is derivable here and a candidate that this K cannot split is skipped - * rather than measured. cfg_for() refuses the same combination at issue; this is the cheap half - * of the same rule and neither is load-bearing alone. */ +/* Geometry-only legality, so the tuner skips ~40% of the space without launching. wv*sk*32 is the + * block's thread count, at most 1024 in hardware; the tighter per-MB/NPW bound depends on the row + * and lives in r4d_gemm_args.h's block_bound(). K must divide into SK slices of the kernel's unit: + * 16 for bf16, 128 where a quantised weight carries a scale per 128 K. cfg_for() refuses the same + * combinations at issue. */ static int r4d_tune_valid_gemm(const RadParam* p, int n_p, const RadParam* c, int n_c) { long long wv = 1, sk = 0; for (int i = 0; i < n_c; ++i) { @@ -3807,7 +3602,7 @@ static int r4d_tune_valid_gemm(const RadParam* p, int n_p, const RadParam* c, in if (!std::strcmp(c[i].key, "wv")) wv = c[i].ival; else if (!std::strcmp(c[i].key, "sk")) sk = c[i].ival; } - if (sk <= 0) return 1; /* the law decides, and it decides legally */ + if (sk <= 0) return 1; /* the law decides, legally */ if (wv * sk * 32 > 1024) return 0; long long K = 0; @@ -3823,31 +3618,24 @@ static int r4d_tune_valid_gemm(const RadParam* p, int n_p, const RadParam* c, in /* --------------------------------------------------------------- the tiled GEMM's tile ladder * - * ONE AXIS, AND IT IS NOT A CROSS PRODUCT, because libr4d's tiled kernel is not parameterised on - * (BM, BN): it is a switch over compiled template instantiations, and only some (BM, BN) pairs - * have an arm. Declaring bm x bn would name combinations that do not exist -- the opposite defect - * to the hole the skinny GEMM had, and just as wrong. - * - * The values are the arm ids, and r4d_cfg_tiled() maps each to the (BM, BN) the N constraint - * needs. Only arms that compute a CORRECT result are listed: libr4d's table is mostly cost - * ablations, which "compute wrong answers by construction" in its own words, and a tuner handed - * those would benchmark a kernel that does not do the GEMM and then pick it. */ + * One axis, not a cross product: the tiled kernel switches over compiled template instantiations, + * and only some (BM, BN) pairs have an arm. The values are arm ids, which r4d_cfg_tiled() maps to + * (BM, BN). Only arms that compute a correct result are listed. */ static const int64_t kTileArms[] = { 0, 6, 10, 12, 57, 59, 114, 124, 125, 126, 128, 129, 138, 139, 146 }; static const RadTunable tGemmTiled[] = { { "tile", kTileArms, NELEM(kTileArms), 0, "compiled tile arm; 0 is BM 128 x BN 256, libr4d's own default" }, }; -/* The prefill kernel's arms, on the same terms. Ablations (20-23, 25, 26) are excluded for the - * same reason. */ +/* The prefill kernel's arms, likewise. */ static const int64_t kPrefillArms[] = { 0, 2, 3, 5, 6, 8, 9, 10, 13, 14, 27, 28, 29, 30 }; static const RadTunable tGemmPrefill[] = { { "tile", kPrefillArms, NELEM(kPrefillArms), 0, "compiled tile arm; 0 is BM 128 x BN 256, libr4d's own default" }, }; -/* The MXFP4 tiled GEMM's one axis. Both values are compiled arms of one template; 0 is the M - * crossover (TN=4 from M >= 2048), which needs M and so cannot be a constant. */ +/* The MXFP4 tiled GEMM's one axis: compiled arms of one template. 0 is the M crossover (TN=4 from + * M >= 2048), which needs M. */ static const int64_t kMxTn[] = { 0, 2, 4 }; static const RadTunable tGemmMxfp4Tiled[] = { { "tn", kMxTn, NELEM(kMxTn), 0, @@ -3866,11 +3654,9 @@ static const RadTunable tGemmMxfp4Decode[] = { }; /* ------------------------------------------------------------------------ split-KV attention - * 0 is libr4d's measured split law (r4d_attn_paged_h256_gqa6.hip carries the table), which reads - * num_seqs and max_ctx -- values that exist only at issue -- so it cannot be a constant and stays - * the default. The fixed counts are for a tuner that has a concrete batch. RadScratchFn is handed - * the same choice, so the arena is sized for what this picks and not for the law's answer at some - * other shape. */ + * 0 is libr4d's split law (table in r4d_attn_paged_h256_gqa6.hip), which reads num_seqs and + * max_ctx at issue. The fixed counts are for a tuner with a concrete batch. RadScratchFn receives + * the same choice, so the arena is sized for what this picks. */ static const int64_t kSplits[] = { 0, 8, 16, 32, 64 }; static const RadTunable tAttnSplit[] = { { "splits", kSplits, NELEM(kSplits), 0, "split-KV segments per sequence. 0 = libr4d's split law" }, @@ -3878,24 +3664,18 @@ static const RadTunable tAttnSplit[] = { /* ------------------------------------------------------------------- all-reduce launch geometry * - * FOUR AXES, and the cross product is real here: nblocks, nthreads, drain and acq are independent - * properties of the handshake. `pub` is not an axis -- every arm uses 1 -- so it stays a constant - * in r4d_ar_entry.hip rather than becoming a knob with one value. + * Four independent axes of the handshake: nblocks, nthreads, drain and acq. (`pub` is 1 in every + * arm, a constant in r4d_ar_entry.hip.) nblocks 0 scales with the message and clamps; drain 3 is + * s_wait_storecnt, the correct wait for the fine-grained uncached IPC scratch. * - * nblocks 0 is "scale with the message and clamp"; drain 3 is s_wait_storecnt, which is the - * correct wait for the fine-grained uncached IPC scratch. + * rad-tune cannot reach these rows: the two-rank kernels need a real peer over IPC and rad-tune + * runs one process. A serving engine at --tp 2 can compare points via RADIANCE_TUNE, e.g. + * `RADIANCE_TUNE=all_reduce:drain=1`. The defaults are the fastest point at both decode and + * prefill message sizes. * - * RAD-TUNE CANNOT REACH THIS ROW: the 2-rank kernels need a real peer over IPC and rad-tune runs - * one process, so it reports "no candidate served it" and a deployment runs the defaults. The only - * harness that can compare them is a serving engine at --tp 2, and RADIANCE_TUNE is how it is told - * which point to use -- `RADIANCE_TUNE=all_reduce:drain=1`. - * - * THE DEFAULTS BELOW ARE THE FASTEST POINT AT BOTH ENDS OF THE RANGE. At a decode message the axes - * barely separate; at a prefill chunk they do, and the default still wins. - * - * On the fp8 fused row only drain and acq are meaningful: it forces `nthreads` to the norm's width - * for bit-exactness, and pinning `nblocks` would undo the cap r4d_ar_entry.hip's own comment - * argues for. None of these axes changes a byte of the result. */ + * On the fp8 fused row only drain and acq apply: it forces `nthreads` to the norm's width for + * bit-exactness, and pinning `nblocks` would undo r4d_ar_entry.hip's cap. No axis changes the + * result. */ static const int64_t kArNblocks[] = { 0, 8, 16, 24 }; static const int64_t kArNthreads[] = { 256, 512, 1024 }; static const int64_t kArDrain[] = { 1, 3 }; @@ -3906,13 +3686,22 @@ static const RadTunable tAr[] = { { "drain", kArDrain, NELEM(kArDrain), 3, "store-drain wait before the flag: 3 = s_wait_storecnt, 1 = vmcnt" }, { "acq", kArAcq, NELEM(kArAcq), 0, "acquire fence after the flag read" }, }; -/* THE SAME AXES WITH NARROW DEFAULTS, for a collective issued beside compute (`overlap` 1). The - * wide launch -- up to 24 blocks of 1024 threads, 768 waves pushing over the link and then - * spinning on peer flags -- is right when the all-reduce has the card to itself and wrong when a - * GEMM shares it: on Qwen-Image's two-rank pass the GEMMs that ran beside it took 1.45 to 2.1x - * their time alone, which ate the whole overlap. Eight blocks of 256 threads still keep the link - * busy, and the same picture went 13.8 -> 13.0 s at 2048^2, bit for bit the same; 8 x 512 and - * 24 x 256 were 13.4 and 13.5. */ +/* The four-rank two-shots beside compute: four blocks of 1024. A pipelined Flash-Next prefill at + * TP4 (qwen4exp_fp8) runs each all-reduce of a 2048-row piece beside the other piece's MoE passes, + * where the size-chosen 24 blocks hold a third of the card while they wait on the link. With every + * all-reduce pinned, 4 blocks beat 8 by about 1.6 % at 18K-64K tokens, and 8 beat 16 and 24. */ +static const int64_t kArNblocksLane4[] = { 0, 4, 8, 16, 24 }; +static const RadTunable tArTs4Lane[] = { + { "nblocks", kArNblocksLane4, NELEM(kArNblocksLane4), 4, "blocks in the grid. 0 = scale with the message and clamp" }, + { "nthreads", kArNthreads, NELEM(kArNthreads), 1024, "threads per block" }, + { "drain", kArDrain, NELEM(kArDrain), 3, "store-drain wait before the flag: 3 = s_wait_storecnt, 1 = vmcnt" }, + { "acq", kArAcq, NELEM(kArAcq), 0, "acquire fence after the flag read" }, +}; +/* The same axes with narrow defaults, for a collective issued beside compute (`overlap` 1). The + * wide launch (up to 24 blocks of 1024 threads spinning on peer flags) suits an all-reduce that has + * the card to itself; beside a GEMM it slows the GEMM by 1.45-2.1x. Eight blocks of 256 threads + * still keep the link busy and were fastest on Qwen-Image's two-rank pass (ahead of 8 x 512 and + * 24 x 256). */ static const RadTunable tArLane[] = { { "nblocks", kArNblocks, NELEM(kArNblocks), 8, "blocks in the grid. 0 = scale with the message and clamp" }, { "nthreads", kArNthreads, NELEM(kArNthreads), 256, "threads per block" }, @@ -3921,10 +3710,10 @@ static const RadTunable tArLane[] = { }; /* --------------------------------------------------------------------------------- row top-k - * NCH is a REQUEST -- libr4d rounds the chunk width up to a multiple of eight columns -- so the - * scratch hook asks r4d_rowtopk_bf16_chunks() rather than computing it. PT1 is the stage-1 partial - * depth in waves and the entry point compiles exactly 2, 4, 8 and 16. `rc`, how many candidates a - * chunk keeps, is bounded by pt1*32 and stays derived. */ + * NCH is a request (libr4d rounds the chunk width up to a multiple of eight columns), so the + * scratch hook asks r4d_rowtopk_bf16_chunks(). PT1 is the stage-1 partial depth in waves; the + * entry point compiles 2, 4, 8 and 16. `rc`, the candidates a chunk keeps, is bounded by pt1*32 + * and derived. */ static const int64_t kTopkNch[] = { 0, 1024, 2048, 4096 }; static const int64_t kTopkPt1[] = { 2, 4, 8, 16 }; static const RadTunable tTopk[] = { @@ -3933,10 +3722,9 @@ static const RadTunable tTopk[] = { }; /* ------------------------------------------------------------------------------- fp8 matvec - * Rows a wave. 0 is libr4d's own rule, so an untuned install is fast rather than broken. 8 is - * offered even though the rule never returns it -- `rows_dot` is templated and 8 divides 128, so - * it is a legal instantiation, and the rule's ceiling of 4 was not derived from the shapes of the - * models served here. */ + * Rows per wave. 0 is libr4d's own rule. 8 is offered though the rule never returns it: `rows_dot` + * is templated and 8 divides 128, and the rule's ceiling of 4 was not derived from the served + * models' shapes. */ static const int64_t kMvRb[] = { 0, 1, 2, 4, 8 }; static const RadTunable tMv[] = { { "rb", kMvRb, NELEM(kMvRb), 0, "rows of the weight one wave owns. 0 = libr4d's own rule" }, @@ -3946,40 +3734,33 @@ static const RadTunable tMv[] = { /* ------------------------------------------- the small model ops and the sampler chain ------- * - * A constraint is a NECESSARY condition on the GEOMETRY (spec §2.1), and these ops have almost - * none: there is nothing to specialise an elementwise add on and nothing a norm rejects. What the - * kernels do require is the activation width -- they read through a uint16_t, and an f32 operand - * would be read as two bf16 halves and produce plausible garbage -- so `dtype` is the row, and the - * shims check the operands' own dtypes per call because a parameter is not a promise about a - * tensor. + * A constraint is a necessary condition on the geometry (spec §2.1), and these ops have almost + * none. The kernels require the activation width (they read through a uint16_t), so `dtype` is + * the row; the shims also check operand dtypes per call. * - * kv_store carries `block_size >= 1` for the reason ref's does: the key stays RAD_REQUIRED there, - * so the predicate admits every value and refuses only a query that does not name one. The paged - * block size itself is derived from the resolved ATTENTION kernel (spec §7.2), which answers 16. + * kv_store's `block_size >= 1`, as in ref, admits every value and refuses only a query that names + * none. The paged block size is derived from the resolved attention kernel (spec §7.2): 16. * - * The sampler rows constrain only the extent, and only so that a row with no predicate at all - * cannot match a query that forgot to say what it wanted -- the same reasoning cSampleChain gives. - * n_cand is bounded because the top-k's bitonic sort runs in LDS over a power-of-two padding. */ + * The sampler rows constrain only the extent, so they cannot match a query that named nothing (as + * cSampleChain). n_cand is bounded because the top-k's bitonic sort runs in LDS over a + * power-of-two padding. */ static const RadConstraint cBf16Row[] = { C_IN("dtype", "bf16") }; static const RadConstraint cF32Row[] = { C_IN("dtype", "f32") }; /* bf16 rows over the byte copy, which moves four bytes a thread: an even width. */ static const RadConstraint cBf16Row2[] = { C_IN("dtype", "bf16"), C_DIV("n", 2) }; -/* Opaque byte rows, four at a time. The width constraint is the vectorised copy's - * alignment requirement stated where the selector can see it, so a row that cannot be - * served is refused at resolve rather than at launch. */ +/* Opaque byte rows, four at a time: the vectorised copy's alignment, stated so the selector + * refuses an unservable row at resolve rather than at launch. */ static const RadConstraint cU8Row4[] = { C_IN("dtype", "u8"), C_DIV("n", 4) }; -/* The n-gram hash. It reads no activation, so it constrains no dtype -- what it DOES constrain is - * the shift window, which lives in a register array: `ngram` past 8 is a kernel that would spill - * its whole history to scratch, and no model asks for one. */ +/* The n-gram hash reads no activation, so no dtype. The shift window lives in a register array; + * `ngram` past 8 would spill it to scratch. */ static const RadConstraint cNgramIds[] = { C_GE("ngram", 2), C_LE("ngram", 8), C_GE("heads", 1) }; -/* PLE's gate. `n` is the per-stream width every reduction runs over and it lives in a workgroup, so - * 4096 is the ceiling: 16 values a thread at 256 threads, which is what the register arrays hold. */ +/* PLE's gate. `n` is the per-stream width every reduction runs over within a workgroup; 4096 is + * 16 values per thread at 256 threads, what the register arrays hold. */ static const RadConstraint cPleGate[] = { C_IN("dtype", "bf16"), C_GE("n", 1), C_LE("n", 4096), C_GE("hc", 2) }; -/* PLE's convolution. The dtype is the activation's; `width` and `dilation` are capped so that - * (width-1)*dilation -- the register window the state write-back holds -- cannot exceed 16. The - * product is what the kernel actually bounds, and a constraint table cannot say "product"; these - * two caps are the tightest pair that admits every combination under it. */ +/* PLE's convolution. The kernel bounds (width-1)*dilation, the state write-back's register + * window, at 16; a constraint cannot express a product, so these are the tightest separate caps + * admitting every combination under it. */ static const RadConstraint cPleConv[] = { C_IN("dtype", "bf16"), C_GE("width", 1), C_LE("width", 5), C_GE("dilation", 1), C_LE("dilation", 4) }; @@ -4000,32 +3781,18 @@ static const RadConstraint cSampleCand[] = { C_GE("n_cand", 1), C_LE("n_cand", 4 static const RadConstraint cSampleLogprobs[] = { C_GE("n_vocab", 1), C_GE("k", 1), C_LE("k", 64) }; /* The activation width the column loop vectorises over; M is unbounded -- the kernel chunks rows. */ static const RadConstraint cLogitsGemm[] = { C_DIV("n_embd", 8), C_IN("dtype", "bf16") }; -/* The fp8 head. n_embd on the 128 block the scales are taken over, and NO CAP ON M -- the row - * re-layouts the weight, so it has to cover the whole range or none of it. A cap at 32 would leave - * the band above it to the bf16 projection, which reads the E4M3 codes as bf16 and returns empty - * completions as soon as enough sequences batch together. The kernel chunks above 32 instead, and - * core/build/rad_builder.cpp refuses the capped arrangement at declare time as well. */ -/* 128 IS THE SCALE BLOCK AND IT IS THE WHOLE CONSTRAINT. What makes that worth explaining is its - * interaction with the layout: r4d_rad_layout_fp8_logits stores a vocabulary row as `n_embd` codes - * followed by its own scales, and the kernel reads sixteen codes at a time through a uint4, so the - * row stride has to be a multiple of 16. With K = 128j the used width is 130j, and 130j % 16 == 0 - * reduces to j % 8 == 0 -- K % 1024 == 0 -- so a layout that REFUSED an unaligned stride could - * only honestly claim 1024 here. +/* The fp8 head: n_embd on the 128 scale block, and no cap on M. The row relayouts the weight, so + * it must cover the whole range; above a cap the bf16 projection would read the E4M3 codes as bf16. + * The kernel chunks above 32, and core/build/rad_builder.cpp refuses a capped arrangement. * - * A ROW'S CONSTRAINTS HAVE TO BE WHAT ITS LAYOUT CAN DO. Claiming 128 against such a layout claims - * a band the row cannot serve, and the failure is invisible at any n_embd that happens to be a - * multiple of 1024 (5120, 2048). At one that is not -- 2560 -- the row satisfies the constraint, - * wins selection on priority, and then has its layout REFUSED at declare time, with the fallback - * below it unreachable. That is the band-coverage hazard. - * - * SO THE LAYOUT IS THE SIDE THAT WIDENS, NOT THE CONSTRAINT. r4d_fp8_lm.h pads the stored row to - * 16 bytes -- under 0.3% at K = 2560 and exactly nothing at every K the 1024 rule already admitted - * -- so the hook serves every multiple of 128 and this row can say so. Which direction to move is - * decided by what the band is WORTH: at 2560 the alternative is the bf16 head at 1.27 GB a step. */ + * A row's constraints must match what its layout can serve. r4d_rad_layout_fp8_logits stores a + * vocabulary row as `n_embd` codes plus its scales, read sixteen codes at a time through a uint4. + * Unpadded, K = 128j gives a row of 130j bytes, 16-aligned only when K % 1024 == 0, so at n_embd + * 2560 the row would win selection and then fail at layout with no fallback. r4d_fp8_lm.h pads the + * stored row to 16 bytes instead (under 0.3% at K = 2560), so every multiple of 128 is served. */ static const RadConstraint cLogitsGemmFp8[] = { C_DIV("n_embd", 128), C_IN("dtype", "bf16") }; -/* No axes: one implementation with nothing to tune. The core appends no choices and the kernel - * reads no tuned key. */ +/* No tunable axes. */ #define NOTUNE nullptr, 0, nullptr /* ---- image generation ------------------------------------------------------------------- */ @@ -4058,13 +3825,11 @@ static const RadConstraint cAttnDenseH1152[] = { static const RadKernelInfo kKernels[] = { /* ---------------------------------- the small model ops (r4d_model_bf16.hip) ---------------- * - * The ops between the interesting kernels. They are in this library because a step is a CHAIN: the - * engine's buffers live in VRAM, libref is domain HOST, and `rad_issue` refuses an op with no - * launch for the domain the placement planner put it on. An add with no device row is not a slow - * add, it is a fatal "no device kernel for this band" on the first request. + * The ops between the larger kernels. They need device rows because the engine's buffers live in + * VRAM, libref is host domain, and `rad_issue` refuses an op with no launch for its placed domain: + * a missing device add is a fatal "no device kernel for this band". * - * R4D_PRIO_ONLY throughout: nothing else in this plugin implements them, and ref is the fallback - * only on a host domain. + * R4D_PRIO_ONLY throughout: nothing else in this plugin implements them. */ { "embed_lookup_bf16", "embed_lookup", "vocab", "embedding gather, one workgroup a token", @@ -4073,7 +3838,7 @@ static const RadKernelInfo kKernels[] = { RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cBf16Row), NOTUNE, nullptr, nullptr, r4d_rad_embed_lookup, nullptr, nullptr, nullptr, - r4d_shape_embed_lookup, nullptr, nullptr, r4d_rad_embed_lookup_describe }, + r4d_shape_embed_lookup }, { "embed_lookup_q_bf16", "embed_lookup_q", "vocab", "quantised embedding gather, four entries a thread", @@ -4082,7 +3847,7 @@ static const RadKernelInfo kKernels[] = { RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cBf16Row), NOTUNE, nullptr, nullptr, r4d_rad_embed_lookup_q, nullptr, r4d_rad_layout_embed_q, nullptr, - r4d_shape_embed_lookup_q, nullptr, nullptr, r4d_rad_embed_lookup_q_describe }, + r4d_shape_embed_lookup_q }, { "ple_gate_bf16", "ple_gate", "norm", "PLE's dot-product gate, one workgroup a (row, stream) pair", @@ -4090,8 +3855,7 @@ static const RadKernelInfo kKernels[] = { "bf16 activations, F32 norm gains", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cPleGate), NOTUNE, - nullptr, nullptr, r4d_rad_ple_gate, nullptr, nullptr, nullptr, - nullptr, nullptr }, + nullptr, nullptr, r4d_rad_ple_gate }, { "ple_conv_bf16", "ple_conv", "norm", "PLE's dilated depthwise conv, silu and residual add; one thread a channel", @@ -4099,8 +3863,7 @@ static const RadKernelInfo kKernels[] = { "bf16 activations, weights and conv state; i32 cu, slots, has_init and num_accepted", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cPleConv), NOTUNE, - nullptr, nullptr, r4d_rad_ple_conv, nullptr, nullptr, nullptr, - nullptr, nullptr }, + nullptr, nullptr, r4d_rad_ple_conv }, { "causal_conv1d_bf16", "causal_conv1d", "conv", "depthwise causal conv with no activation (ple_conv's kernel); one thread a channel", @@ -4108,8 +3871,7 @@ static const RadKernelInfo kKernels[] = { "bf16 activations, weights and conv state; i32 cu, slots, has_init and num_accepted", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cCausalConv), NOTUNE, - nullptr, nullptr, r4d_rad_causal_conv1d, nullptr, nullptr, nullptr, - nullptr, nullptr }, + nullptr, nullptr, r4d_rad_causal_conv1d }, { "ngram_ids_i32", "ngram_ids", "vocab", "PLE's hashed n-gram row ids, one thread a token", @@ -4117,8 +3879,7 @@ static const RadKernelInfo kKernels[] = { "i32 tokens and state, i64 multipliers and per-head vocab sizes and offsets", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cNgramIds), NOTUNE, - nullptr, nullptr, r4d_rad_ngram_ids, nullptr, nullptr, nullptr, - nullptr, nullptr, nullptr, r4d_rad_ngram_ids_describe }, + nullptr, nullptr, r4d_rad_ngram_ids }, { "gather_rows_bf16", "gather_rows", "elem", "y[i, :] = x[idx[i], :], one workgroup a row", @@ -4127,14 +3888,12 @@ static const RadKernelInfo kKernels[] = { RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cBf16Row), NOTUNE, nullptr, nullptr, r4d_rad_gather_rows, nullptr, nullptr, nullptr, - r4d_shape_gather_rows, nullptr, nullptr, r4d_rad_gather_rows_describe }, + r4d_shape_gather_rows }, -/* THE BYTE FORMS, and they are separate rows rather than a widened dtype constraint on the bf16 - * one. What moves through here is a KV fragment -- one layer's worth of one block -- and its - * contents are whatever the attention kernel wrote. Calling that bf16 would be a lie with teeth: - * libref is the oracle for every op in this tree and its bf16 path loads through float, which is - * not guaranteed to return a NaN payload unchanged. At u8 every value is 0..255, float carries it - * exactly, and oracle and kernel agree bit for bit on any payload at all. */ +/* The byte forms, separate rows rather than a widened bf16 dtype. They move KV fragments (one + * layer of one block) with arbitrary contents. libref's bf16 path loads through float, which need + * not preserve a NaN payload; at u8 float carries every value exactly, so oracle and kernel agree + * bit for bit. */ { "gather_rows_u8", "gather_rows", "elem", "y[i, :] = x[idx[i], :] over opaque bytes, one workgroup a row, 4 bytes a thread", "n a multiple of 4; source and destination row pitches are read off the operands", @@ -4142,7 +3901,7 @@ static const RadKernelInfo kKernels[] = { RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cU8Row4), NOTUNE, nullptr, nullptr, r4d_rad_gather_rows_u8, nullptr, nullptr, nullptr, - r4d_shape_gather_rows_u8, nullptr, nullptr, r4d_rad_gather_rows_u8_describe }, + r4d_shape_gather_rows_u8 }, { "scatter_rows_u8", "scatter_rows", "elem", "x[idx[i], :] = v[i, :] over opaque bytes, one workgroup a row, 4 bytes a thread", @@ -4151,7 +3910,7 @@ static const RadKernelInfo kKernels[] = { RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cU8Row4), NOTUNE, nullptr, nullptr, r4d_rad_scatter_rows_u8, nullptr, nullptr, nullptr, - r4d_shape_scatter_rows_u8, nullptr, nullptr, r4d_rad_scatter_rows_u8_describe }, + r4d_shape_scatter_rows_u8 }, { "scatter_rows_bf16", "scatter_rows", "elem", "x[idx[i], :] = v[i, :] for bf16 rows -- the u8 row's byte copy at twice the width", @@ -4160,7 +3919,7 @@ static const RadKernelInfo kKernels[] = { RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cBf16Row2), NOTUNE, nullptr, nullptr, r4d_rad_scatter_rows_bf16, nullptr, nullptr, nullptr, - r4d_shape_scatter_rows_bf16, nullptr, nullptr, r4d_rad_scatter_rows_bf16_describe }, + r4d_shape_scatter_rows_bf16 }, { "cast_bf16_bf16", "cast", "elem", "y = x, bf16 to bf16 -- a strided row copy through libr4d's 2D copy", @@ -4196,7 +3955,7 @@ static const RadKernelInfo kKernels[] = { "bf16 in and out, f64 sum, one rounding", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cBf16Row), NOTUNE, - nullptr, nullptr, r4d_rad_seg_mean, nullptr, nullptr, nullptr }, + nullptr, nullptr, r4d_rad_seg_mean }, { "qk_norm_rope_bf16", "qk_norm_rope", "attn", "per-head RMS norm of q and k (and optionally v, unit gain) with rotary on q and k, in place", @@ -4207,7 +3966,7 @@ static const RadKernelInfo kKernels[] = { "bf16 qkv and gains, i32 positions, f32 arithmetic, the norm rounded before the rotation", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cQkNormRope), NOTUNE, - nullptr, nullptr, r4d_rad_qk_norm_rope, nullptr, nullptr, nullptr }, + nullptr, nullptr, r4d_rad_qk_norm_rope }, { "relu_bf16", "relu", "elem", "max(x, 0)", @@ -4233,16 +3992,25 @@ static const RadKernelInfo kKernels[] = { "bf16 in and out", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cBf16Row), NOTUNE, - nullptr, nullptr, r4d_rad_clamp, nullptr, nullptr, nullptr }, + nullptr, nullptr, r4d_rad_clamp }, { "conv2d_bf16", "conv2d", "elem", - "segment-wise 2-D convolution over (time, width), channels innermost, optional row mask", + "segment-wise 2-D convolution over (time, width), channels innermost, optional row mask, bias " + "and gelu, either kernel layout", "any geometry; a workgroup an output time row, a thread an output element; sized for an audio " "subsampler (a few thousand frames, kernels of 3)", "bf16 x / w / y, i32 cu_seqlens and mask, f32 accumulate", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cBf16Row), NOTUNE, - nullptr, nullptr, r4d_rad_conv2d, nullptr, nullptr, nullptr }, + nullptr, nullptr, r4d_rad_conv2d }, + +{ "conv2d_unfold_bf16", "conv2d_unfold", "elem", + "a convolution's receptive fields as rows, for a GEMM against its weight", + "any geometry; a workgroup an output time row, a thread an unfolded element", + "bf16 x / y, i32 cu_seqlens and mask", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r4d_rad_conv2d_unfold, nullptr, nullptr, nullptr }, { "conv1d_dw_bf16", "conv1d_dw", "elem", "segment-wise causal depthwise convolution over time", @@ -4250,7 +4018,7 @@ static const RadKernelInfo kKernels[] = { "bf16 x / w / y, i32 cu_seqlens, f32 accumulate", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cBf16Row), NOTUNE, - nullptr, nullptr, r4d_rad_conv1d_dw, nullptr, nullptr, nullptr }, + nullptr, nullptr, r4d_rad_conv1d_dw }, { "rel_sinusoid_bf16", "rel_sinusoid", "elem", "the sinusoidal relative-position table", @@ -4258,7 +4026,16 @@ static const RadKernelInfo kKernels[] = { "bf16 out, f32 libm sin / cos / exp", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cBf16Row), NOTUNE, - nullptr, nullptr, r4d_rad_rel_sinusoid, nullptr, nullptr, nullptr }, + nullptr, nullptr, r4d_rad_rel_sinusoid }, + +{ "seg_sinusoid_bf16", "seg_sinusoid", "elem", + "sinusoidal absolute positions restarting every `period` rows of a segment (Whisper-style " + "chunk positions)", + "any rows and even width; a workgroup a row, its segment by a scan over cu_seqlens", + "bf16 out, i32 cu_seqlens, f32 libm sin / cos / exp", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r4d_rad_seg_sinusoid, nullptr, nullptr, nullptr }, { "attn_local_rel_bf16", "attn_local_rel", "attn", "local attention with a relative-position term and a softcap (Gemma 4's audio)", @@ -4267,7 +4044,7 @@ static const RadKernelInfo kKernels[] = { "bf16 q / k / v / relk / out, bf16 or f32 per-dim scale, f32 softmax", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cAttnLocalRel), NOTUNE, - nullptr, nullptr, r4d_rad_attn_local_rel, nullptr, nullptr, nullptr }, + nullptr, nullptr, r4d_rad_attn_local_rel }, { "pool_rows_bf16", "pool_rows", "elem", "mean of every k consecutive rows, then a multiplier: a vision pooler over windows its " @@ -4276,7 +4053,7 @@ static const RadKernelInfo kKernels[] = { "bf16 in and out, f32 sum, two roundings", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cBf16Row), NOTUNE, - nullptr, nullptr, r4d_rad_pool_rows, nullptr, nullptr, nullptr }, + nullptr, nullptr, r4d_rad_pool_rows }, { "rmsnorm_bf16", "rmsnorm", "norm", "root-mean-square norm with a gain, two passes over the row", @@ -4303,7 +4080,7 @@ static const RadKernelInfo kKernels[] = { RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cLayernorm), NOTUNE, nullptr, nullptr, r4d_rad_layernorm, nullptr, nullptr, nullptr, - r4d_shape_layernorm, nullptr, nullptr, r4d_rad_layernorm_describe }, + r4d_shape_layernorm }, { "grid_embed_bf16", "grid_embed", "elem", "a learned position grid resampled bilinearly to each row's grid and added in", @@ -4312,7 +4089,7 @@ static const RadKernelInfo kKernels[] = { RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGridEmbed), NOTUNE, nullptr, nullptr, r4d_rad_grid_embed, nullptr, nullptr, nullptr, - r4d_shape_grid_embed, nullptr, nullptr, r4d_rad_grid_embed_describe }, + r4d_shape_grid_embed }, { "grid_embed_aa_bf16", "grid_embed_aa", "elem", "a learned position grid resampled as torch's antialiased bilinear and added in (SigLIP2)", @@ -4321,7 +4098,7 @@ static const RadKernelInfo kKernels[] = { RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGridEmbed), NOTUNE, nullptr, nullptr, r4d_rad_grid_embed_aa, nullptr, nullptr, nullptr, - r4d_shape_grid_embed, nullptr, nullptr, r4d_rad_grid_embed_aa_describe }, + r4d_shape_grid_embed }, { "gemm_bf16_nt_bias_tiled", "gemm_nt_bias", "gemm", "biased GEMM C = res + act(A @ W^T + bias): eight waves over an LDS-staged 64-deep K tile, " @@ -4331,7 +4108,7 @@ static const RadKernelInfo kKernels[] = { RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGemmBias), NOTUNE, nullptr, nullptr, r4d_rad_gemm_nt_bias, nullptr, nullptr, nullptr, - r4d_shape_gemm_nt_bias, nullptr, nullptr, r4d_rad_gemm_nt_bias_describe }, + r4d_shape_gemm_nt_bias }, { "add_bf16", "add", "elem", "elementwise sum, with the one row-broadcast form", @@ -4444,8 +4221,8 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_kv_store, nullptr, nullptr, nullptr, r4d_shape_kv_store }, -/* The write side of the fp8kv attention family: without it a cache declared fp8_e4m3 has no way to - * be filled. Four columns a thread, so head_dim must be a multiple of 4. */ +/* The write side of the fp8kv attention family. Four columns per thread, so head_dim must be a + * multiple of 4. */ { "kv_store_fp8", "kv_store", "attn", "scatter k and v into a paged E4M3 cache, one workgroup a token", "cache exactly [n_blocks, kv_heads, block_size, 2*head_dim]; head_dim a multiple of 4; a " @@ -4454,7 +4231,7 @@ static const RadKernelInfo kKernels[] = { RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cKvStoreFp8), NOTUNE, nullptr, nullptr, r4d_rad_kv_store_fp8, nullptr, nullptr, nullptr, - r4d_shape_kv_store, nullptr, nullptr, r4d_rad_kv_store_fp8_describe }, + r4d_shape_kv_store }, { "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", @@ -4493,12 +4270,10 @@ static const RadKernelInfo kKernels[] = { /* ---------------------------- the decomposed sampler chain (r4d_sample_stages_f32.hip) ------ * - * NOT sample_chain above, and both stay. That one fuses temperature, softmax, top_k, top_p, min_p - * and the draw in vLLM's fixed order and answers the speculative verify's three outputs; these are - * the eleven ops the core composes per request, and they carry the stages the fused form has no - * room for -- the penalties, DRY, a grammar bitmask, locally-typical, XTC. "Fusion is a selection, - * not a compiler pass" (spec §2.3): shipping only the fused form would make the choice for the - * plugin. + * Distinct from sample_chain, which fuses temperature, softmax, top_k, top_p, min_p and the draw + * in vLLM's fixed order and produces the speculative verify's outputs. These are the ops the core + * composes per request, including stages the fused form lacks: penalties, DRY, a grammar bitmask, + * locally-typical, XTC (spec §2.3: fusion is a selection). */ { "sample_penalties_f32", "sample_penalties", "sample", "repetition, frequency and presence penalties in one pass over the row's history", @@ -4628,11 +4403,8 @@ static const RadKernelInfo kKernels[] = { "u32 (id, logit-bits) pairs in, i32 candidate ids and f32 candidate logits out", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cSampleCand), NOTUNE, - /* NO `opd_shape`: the gathered plane is (u32 id, f32 logit) pairs in one word-typed buffer, so - * no fill domain can put a sensible float in the value lane, and `world_size` is not a parameter - * of this op. r4d_shapes.cpp's header carries the argument; ref declines it for the same two - * reasons, and a tool skips the case by name rather than comparing two orderings of denormals. */ - nullptr, nullptr, r4d_rad_sample_merge_topk, nullptr, nullptr, nullptr }, + /* No `opd_shape`: see r4d_shapes.cpp (word-typed pairs, no `world_size`); ref declines it too. */ + nullptr, nullptr, r4d_rad_sample_merge_topk }, /* ---------------------------------------------------------------------------------- attention */ @@ -4832,10 +4604,9 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_attn_prefill_h64_gqa4_bf16, nullptr, nullptr, nullptr, r4d_shape_attn_paged }, -/* The windowed kernels (r4d_attn_paged_window.hip), under attn_paged and, the same launches with - * the same constraints, under attn_paged_qrow. The qrow rows carry no opd_shape: libref has no row - * for that op, so there is no oracle to run them against, and tests/r4d_emu's attention cases - * already take q as a pitched slice of a wider row. */ +/* The windowed kernels (r4d_attn_paged_window.hip), under attn_paged and, with the same launches + * and constraints, under attn_paged_qrow. The qrow rows have no opd_shape: libref has no row for + * that op, and tests/r4d_emu's attention cases already take q as a pitched slice. */ #define R4D_WIN_ROW(HD, G, KVN, KVS, C, KVDOC) \ { "attn_window_h" #HD "_gqa" #G "_" #KVN, "attn_paged", "attn", \ "paged attention, any window, causal or not; split-KV with a merge where tiles are few", \ @@ -4890,10 +4661,10 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cAttnDecodeH256G12Fp8), ROW(tAttnSplit), nullptr, nullptr, nullptr, r4d_rad_attn_decode_h256_gqa12_fp8, r4d_rad_attn_decode_h256_gqa12_scratch, nullptr, nullptr, - r4d_shape_attn_paged, nullptr, nullptr, r4d_rad_attn_decode_h256_gqa12_fp8_describe }, + r4d_shape_attn_paged }, -/* The same decode dispatch with gate_quant_fp8 as the merge's epilogue: two launches, where the - * attention followed by gate_quant_fp8 is three. */ +/* The same decode dispatch with gate_quant_fp8 as the merge's epilogue: two launches instead of + * three. */ { "attn_decode_gq_h256_gqa12_fp8kv", "attn_paged_gate_quant", "attn", "paged split-KV decode attention with the output gate and the fp8 quantiser in the merge", "attn_decode_h256_gqa12_fp8kv's geometry; gate_quant_fp8 over the merged (token, head) rows: " @@ -4903,8 +4674,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cAttnDecodeGqH256G12Fp8), ROW(tAttnSplit), nullptr, nullptr, nullptr, r4d_rad_attn_decode_gq_h256_gqa12_fp8, r4d_rad_attn_decode_h256_gqa12_scratch, nullptr, nullptr, - r4d_shape_attn_paged_gate_quant, nullptr, r4d_fuse_attn_paged_gate_quant, - r4d_rad_attn_decode_gq_h256_gqa12_fp8_describe }, + r4d_shape_attn_paged_gate_quant, nullptr, r4d_fuse_attn_paged_gate_quant }, { "attn_decode_h256_gqa12_bf16kv", "attn_paged", "attn", "paged attention, causal or not, split-KV (decode / speculative verify / draft block)", @@ -4914,7 +4684,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cAttnDecodeH256G12Bf16), ROW(tAttnSplit), nullptr, nullptr, nullptr, r4d_rad_attn_decode_h256_gqa12_bf16, r4d_rad_attn_decode_h256_gqa12_scratch, nullptr, nullptr, - r4d_shape_attn_paged, nullptr, nullptr, r4d_rad_attn_decode_h256_gqa12_bf16_describe }, + r4d_shape_attn_paged }, /* The bf16 cache's decode with gate_quant_fp8 in the merge, as the fp8 cache's row above. */ { "attn_decode_gq_h256_gqa12_bf16kv", "attn_paged_gate_quant", "attn", @@ -4926,13 +4696,11 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cAttnDecodeGqH256G12Bf16), ROW(tAttnSplit), nullptr, nullptr, nullptr, r4d_rad_attn_decode_gq_h256_gqa12_bf16, r4d_rad_attn_decode_h256_gqa12_scratch, nullptr, nullptr, - r4d_shape_attn_paged_gate_quant, nullptr, r4d_fuse_attn_paged_gate_quant, - r4d_rad_attn_decode_gq_h256_gqa12_bf16_describe }, + r4d_shape_attn_paged_gate_quant, nullptr, r4d_fuse_attn_paged_gate_quant }, -/* The TP4 leg of Flash-Next's sparse attention: the same kernels the gqa12 rows above resolve, at - * the ratio a four-rank world hands a rank (see cAttnPrefillH256G6Bs4Fp8). The two are not - * alternatives -- `gqa` is a per-rank parameter, so world 2 resolves gqa 12 and these four rows - * never win there, and world 4 resolves gqa 6 and the gqa12 rows never win. */ +/* The TP4 leg of Flash-Next's sparse attention: the gqa12 rows' kernels at the ratio a four-rank + * world hands a rank (see cAttnPrefillH256G6Bs4Fp8). `gqa` is per rank, so world 2 resolves only + * the gqa12 rows and world 4 only these. */ { "attn_prefill_h256_gqa6_bs4_fp8kv", "attn_paged", "attn", "paged causal attention, query-tiled (prefill / chunked prefill)", "head_dim 256, 6 queries per kv head, paged block 4, varlen", @@ -4959,7 +4727,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cAttnDecodeH256G6Bs4Fp8), ROW(tAttnSplit), nullptr, nullptr, nullptr, r4d_rad_attn_decode_h256_gqa6_fp8, r4d_rad_attn_decode_h256_gqa6_scratch, nullptr, nullptr, - r4d_shape_attn_paged, nullptr, nullptr, r4d_rad_attn_decode_h256_gqa6_fp8_describe }, + r4d_shape_attn_paged }, { "attn_decode_h256_gqa6_bs4_bf16kv", "attn_paged", "attn", "paged attention, causal or not, split-KV (decode / speculative verify / draft block)", @@ -4969,11 +4737,9 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cAttnDecodeH256G6Bs4Bf16), ROW(tAttnSplit), nullptr, nullptr, nullptr, r4d_rad_attn_decode_h256_gqa6_bf16, r4d_rad_attn_decode_h256_gqa6_scratch, nullptr, nullptr, - r4d_shape_attn_paged, nullptr, nullptr, r4d_rad_attn_decode_h256_gqa6_bf16_describe }, + r4d_shape_attn_paged }, -/* The TP4 leg's sparse decode WITH the gate and the quantiser in the merge, as the gqa12 pair - * above. Two launches where the unfused path is three, once a layer, at the shape TP4 serves every - * decode step of this model. */ +/* The TP4 leg's sparse decode with the gate and quantiser in the merge, as the gqa12 pair above. */ { "attn_decode_gq_h256_gqa6_bs4_fp8kv", "attn_paged_gate_quant", "attn", "paged split-KV decode attention with the output gate and the fp8 quantiser in the merge", "attn_decode_h256_gqa6_bs4_fp8kv's geometry; gate_quant_fp8 over the merged (token, head) rows: " @@ -4983,8 +4749,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cAttnDecodeGqH256G6Bs4Fp8), ROW(tAttnSplit), nullptr, nullptr, nullptr, r4d_rad_attn_decode_gq_h256_gqa6_fp8, r4d_rad_attn_decode_h256_gqa6_scratch, nullptr, nullptr, - r4d_shape_attn_paged_gate_quant, nullptr, r4d_fuse_attn_paged_gate_quant, - r4d_rad_attn_decode_gq_h256_gqa6_fp8_describe }, + r4d_shape_attn_paged_gate_quant, nullptr, r4d_fuse_attn_paged_gate_quant }, { "attn_decode_gq_h256_gqa6_bs4_bf16kv", "attn_paged_gate_quant", "attn", "paged split-KV decode attention with the output gate and the fp8 quantiser in the merge", @@ -4995,8 +4760,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cAttnDecodeGqH256G6Bs4Bf16), ROW(tAttnSplit), nullptr, nullptr, nullptr, r4d_rad_attn_decode_gq_h256_gqa6_bf16, r4d_rad_attn_decode_h256_gqa6_scratch, nullptr, nullptr, - r4d_shape_attn_paged_gate_quant, nullptr, r4d_fuse_attn_paged_gate_quant, - r4d_rad_attn_decode_gq_h256_gqa6_bf16_describe }, + r4d_shape_attn_paged_gate_quant, nullptr, r4d_fuse_attn_paged_gate_quant }, { "attn_prefill_h128_gqa8_fp8kv", "attn_paged", "attn", "paged causal attention, query-tiled (prefill / chunked prefill)", @@ -5036,6 +4800,44 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_shape_attn_paged }, +{ "attn_prefill_h128_gqa2_fp8kv", "attn_paged", "attn", + "paged causal attention, query-tiled (prefill / chunked prefill)", + "head_dim 128, 2 queries per kv head, paged block 16, varlen", + "bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL, + ROW(cAttnPrefillH128G2Fp8), NOTUNE, + nullptr, nullptr, r4d_rad_attn_prefill_h128_gqa2_fp8, nullptr, nullptr, nullptr, + r4d_shape_attn_paged }, + +{ "attn_prefill_h128_gqa2_bf16kv", "attn_paged", "attn", + "paged causal attention, query-tiled (prefill / chunked prefill)", + "head_dim 128, 2 queries per kv head, paged block 16, varlen", + "bf16 query, bf16 kv cache, bf16 out", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL, + ROW(cAttnPrefillH128G2Bf16), NOTUNE, + nullptr, nullptr, r4d_rad_attn_prefill_h128_gqa2_bf16, nullptr, nullptr, nullptr, + r4d_shape_attn_paged }, + +{ "attn_decode_h128_gqa2_fp8kv", "attn_paged", "attn", + "paged attention, causal or not, split-KV (decode / speculative verify)", + "head_dim 128, 2 queries per kv head, paged block 16, q_len*gqa <= 64, no window", + "bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out, f16 partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnDecodeH128G2Fp8), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_decode_h128_gqa2_fp8, r4d_rad_attn_decode_h128_gqa2_scratch, + nullptr, nullptr, + r4d_shape_attn_paged }, + +{ "attn_decode_h128_gqa2_bf16kv", "attn_paged", "attn", + "paged attention, causal or not, split-KV (decode / speculative verify)", + "head_dim 128, 2 queries per kv head, paged block 16, q_len*gqa <= 64, no window", + "bf16 query, bf16 kv cache, bf16 out, f16 partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnDecodeH128G2Bf16), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_decode_h128_gqa2_bf16, r4d_rad_attn_decode_h128_gqa2_scratch, + nullptr, nullptr, + r4d_shape_attn_paged }, + { "attn_vit_h72_bf16", "attn_dense", "attn", "dense non-causal vision-encoder attention, varlen over images / windows", "head_dim 72 native (no padding to 128), multi-head (no GQA), contiguous q/k/v/o, " @@ -5043,16 +4845,17 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16 query / key / value / out, f16 operands, fp32 accumulate", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cAttnVit), NOTUNE, - nullptr, nullptr, r4d_rad_attn_vit, nullptr, nullptr, nullptr }, + nullptr, nullptr, r4d_rad_attn_vit }, { "attn_dense_h64_bf16", "attn_dense", "attn", - "dense bidirectional encoder attention, varlen over cu_seqlens, optional two-sided window", + "dense bidirectional encoder attention, varlen over cu_seqlens, optional two-sided window or " + "blocks", "head_dim 64, multi-head (no GQA), q/k/v/o at their own token pitches (column slices of a " "fused projection allowed)", "bf16 query / key / value / out, f16 operands, fp32 accumulate", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cAttnDenseH64), NOTUNE, - nullptr, nullptr, r4d_rad_attn_dense, nullptr, nullptr, nullptr }, + nullptr, nullptr, r4d_rad_attn_dense }, { "attn_dense_h256_gqa2_bf16", "attn_dense", "attn", "dense bidirectional encoder attention, varlen over cu_seqlens, optional two-sided window", @@ -5060,7 +4863,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16 query / key / value / out, f16 operands, fp32 accumulate", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cAttnDenseH256G2), NOTUNE, - nullptr, nullptr, r4d_rad_attn_dense, nullptr, nullptr, nullptr }, + nullptr, nullptr, r4d_rad_attn_dense }, { "attn_dense_h512_gqa4_bf16", "attn_dense", "attn", "dense bidirectional encoder attention, varlen over cu_seqlens, optional two-sided window", @@ -5068,7 +4871,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16 query / key / value / out, f16 operands, fp32 accumulate", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cAttnDenseH512G4), NOTUNE, - nullptr, nullptr, r4d_rad_attn_dense, nullptr, nullptr, nullptr }, + nullptr, nullptr, r4d_rad_attn_dense }, /* -------------------------------------------------------------------------- gated delta net */ { "gdn_chunk_scan_k128_v128_c64_bf16", "gdn_chunk_scan", "gdn", @@ -5077,11 +4880,10 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16 q/k/v/A, fp32 gate/beta, bf16 out; the state cache is f32 or f16", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGdnChunkScan), NOTUNE, - nullptr, nullptr, r4d_rad_gdn_chunk_scan, nullptr, nullptr, nullptr }, + nullptr, nullptr, r4d_rad_gdn_chunk_scan }, -/* UNVALIDATED. The DPP row_xmask exchanges in this translation unit (r4d_common.h r4d_xor_lane, - * used by the conv) are compile-verified only: never measured and never through a correctness - * gate. Anything this row produces is unverified until it passes rad-kbench. */ +/* Unvalidated: the DPP row_xmask exchanges in this translation unit (r4d_common.h r4d_xor_lane, + * used by the conv) are compile-verified only, not measured or correctness-gated. */ { "gdn_conv_prep_w4_h128_bf16", "gdn_conv_prep", "gdn", "gdn prefill preamble: causal conv + qkv split + qk l2norm + gating + per-chunk cumsum " "[UNVALIDATED: DPP row_xmask rewrite never correctness-gated]", @@ -5089,9 +4891,9 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16 x / weights / conv state / q,k,v out, fp32 a,b and gate/beta out", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGdnConvPrep), NOTUNE, - nullptr, nullptr, r4d_rad_gdn_conv_prep, nullptr, nullptr, nullptr }, + nullptr, nullptr, r4d_rad_gdn_conv_prep }, -/* UNVALIDATED -- same translation unit and same exchanges as gdn_conv_prep above. */ +/* Unvalidated, as gdn_conv_prep above (same translation unit and exchanges). */ { "gdn_conv_update_w4_h128_bf16", "gdn_conv_update", "gdn", "gdn decode conv: rolling speculative window over the conv state cache, writes q/k/v " "[UNVALIDATED: DPP row_xmask rewrite never correctness-gated]", @@ -5099,7 +4901,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16 x / weights / conv state / q,k,v out", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGdnConvUpdate), NOTUNE, - nullptr, nullptr, r4d_rad_gdn_conv_update, nullptr, nullptr, nullptr }, + nullptr, nullptr, r4d_rad_gdn_conv_update }, { "gdn_kkt_solve_k128_c64_bf16", "gdn_kkt_solve", "gdn", "gdn chunk preamble: A = (I + strict_lower(diag(beta) K K^T e^dg))^-1, gram never in HBM", @@ -5107,11 +4909,10 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16 k and A out, fp32 beta / gate / gram / inverse", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGdnKktSolve), NOTUNE, - nullptr, nullptr, r4d_rad_gdn_kkt_solve, nullptr, nullptr, nullptr }, + nullptr, nullptr, r4d_rad_gdn_kkt_solve }, -/* UNVALIDATED. The DPP row_xmask exchanges here stand in for 408 ds_bpermute, several of them - * inside the token loop on the dependency chain, and have never been measured or - * correctness-gated. */ +/* Unvalidated: the DPP row_xmask exchanges here replace 408 ds_bpermute, several inside the token + * loop on the dependency chain, and are not measured or correctness-gated. */ { "gdn_recurrent_update_k128_v128_bf16_fp32state", "gdn_recurrent_update", "gdn", "gdn decode recurrent update: gating, qk l2norm, delta-rule state update, gated rms norm and " "output [UNVALIDATED: DPP row_xmask rewrite never correctness-gated]", @@ -5119,7 +4920,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16 q/k/v and out, fp32 a,b; the state cache is f32 or f16 and the operand says which", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGdnRecurrentUpdate), NOTUNE, - nullptr, nullptr, r4d_rad_gdn_recurrent_update, nullptr, nullptr, nullptr }, + nullptr, nullptr, r4d_rad_gdn_recurrent_update }, { "gdn_conv_recurrent_update_k128_v128_bf16", "gdn_conv_recurrent_update", "gdn", "gdn decode: the recurrent update with gdn_conv_update folded into its prologue -- each " @@ -5131,12 +4932,12 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGdnConvRecurrentUpdate), NOTUNE, nullptr, nullptr, r4d_rad_gdn_conv_recurrent_update, nullptr, nullptr, nullptr, nullptr, - nullptr, r4d_fuse_gdn_conv_recurrent_update, nullptr }, + nullptr, r4d_fuse_gdn_conv_recurrent_update }, /* ---------------------------------------------------------------- the gated residual -------- * r4d_hc_bf16.hip. Three rows; the read is two launches behind one entry point, because `x` - * depends on every column of the low-rank waist and the kernel boundary is the grid-wide barrier - * that says so. */ + * depends on every column of the low-rank waist and the kernel boundary is the grid-wide + * barrier. */ { "hc_enter_bf16", "hc_enter", "norm", "hc identical copies of x into the wide residual stream", "any M, any n, hc 2..8", @@ -5153,7 +4954,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cHcPlain), NOTUNE, nullptr, nullptr, r4d_rad_hc_write, nullptr, nullptr, nullptr, - r4d_shape_hc_write, nullptr, nullptr, r4d_rad_hc_write_describe }, + r4d_shape_hc_write }, { "mtp_enter_bf16", "mtp_enter", "norm", "MTP head entry: two norms, a per-sub-stream fc and one broadcast fc", @@ -5162,7 +4963,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMtpEnter), NOTUNE, nullptr, nullptr, r4d_rad_mtp_enter, r4d_rad_mtp_enter_scratch, nullptr, nullptr, - r4d_shape_mtp_enter, nullptr, nullptr, r4d_rad_mtp_enter_describe }, + r4d_shape_mtp_enter }, { "mtp_enter_e4m3", "mtp_enter", "norm", "the MTP head's entry with fc_hidden and fc_embedding stored as E4M3 rows: half the bytes of the " @@ -5173,7 +4974,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cMtpEnterE4m3), NOTUNE, nullptr, nullptr, r4d_rad_mtp_enter, r4d_rad_mtp_enter_scratch, r4d_rad_layout_mtp_e4m3, r4d_rad_relayout_mtp_e4m3, - r4d_shape_mtp_enter, r4d_rad_unrelayout_mtp_e4m3, nullptr, r4d_rad_mtp_enter_describe }, + r4d_shape_mtp_enter, r4d_rad_unrelayout_mtp_e4m3 }, { "hc_read_bf16", "hc_read", "norm", "grouped rmsnorm, the low-rank read gate, the stream mean, the per-branch write gains and the " @@ -5183,7 +4984,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cHcRead), NOTUNE, nullptr, nullptr, r4d_rad_hc_read, r4d_rad_hc_read_scratch, nullptr, nullptr, - r4d_shape_hc_read, nullptr, nullptr, r4d_rad_hc_read_describe }, + r4d_shape_hc_read }, { "hc_read_e4m3", "hc_read", "norm", "hc_read with the two mixing matrices stored as E4M3 rows -- half their bytes, the largest " @@ -5196,7 +4997,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cHcReadE4m3), NOTUNE, nullptr, nullptr, r4d_rad_hc_read, r4d_rad_hc_read_scratch, r4d_rad_layout_hc_e4m3, r4d_rad_relayout_hc_e4m3, - r4d_shape_hc_read, r4d_rad_unrelayout_hc_e4m3, nullptr, r4d_rad_hc_read_describe }, + r4d_shape_hc_read, r4d_rad_unrelayout_hc_e4m3 }, { "gdn_gated_rmsnorm_h128_bf16", "gdn_gated_rmsnorm", "gdn", "gated rms norm over a row: out = rms(x) . w . act(z), for the prefill path only", @@ -5208,7 +5009,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, r4d_shape_gdn_gated_rmsnorm }, /* ---------------------------------------------------------------------------- all-reduce ---- - * The two-shot rows outrank the one-shots, for the reason the constraint block above states. */ + * The two-shot rows outrank the one-shots (see the all-reduce constraints above). */ { "ar_twoshot_3rank_exact", "all_reduce", "ar", "all-reduce (sum), reduce-scatter + all-gather over P2P IPC scratch, per-block pipelined " "handshake", @@ -5235,6 +5036,21 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, r4d_rad_ar_init, r4d_rad_ar_fini, r4d_rad_ar_twoshot_4rank_exact, nullptr, nullptr, nullptr, r4d_shape_all_reduce }, +/* The row above at `overlap` 1: the same entry point and the same arithmetic, a narrow launch + * that leaves the CUs to the compute running beside it (tArTs4Lane). */ +{ "ar_twoshot_4rank_exact_lane", "all_reduce", "ar", + "all-reduce (sum), reduce-scatter + all-gather over P2P IPC scratch; narrow launch beside " + "compute", + "exactly 4 ranks, all peer-accessible, overlap 1; messages above " + R4D_XSTR(R4D_AR_WIDE_ONESHOT_MAX_ELEMS) " elements; message must shard evenly over the ranks; " + "in place; cudagraph-safe", + "bf16 / fp16 / fp32 payload, fp32 accumulate in ascending rank order, bit-identical across ranks " + "and to the wide row", + RAD_DOMAIN_DEVICE, R4D_PRIO_AR_TWOSHOT + 1, + ROW(cArTsExact4Lane), ROW(tArTs4Lane), nullptr, + r4d_rad_ar_init, r4d_rad_ar_fini, r4d_rad_ar_twoshot_4rank_exact, nullptr, nullptr, nullptr, + r4d_shape_all_reduce }, + { "ar_twoshot_8rank_exact", "all_reduce", "ar", "all-reduce (sum), reduce-scatter + all-gather over P2P IPC scratch, per-block pipelined " "handshake", @@ -5300,8 +5116,8 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, r4d_rad_ar_init, r4d_rad_ar_fini, r4d_rad_ar_oneshot_2rank_wht6, nullptr, nullptr, nullptr, r4d_shape_all_reduce }, -/* The two above at `overlap` 1: the same entry points and the same arithmetic, a launch that - * leaves the CUs to the compute running beside it (tArLane). */ +/* The two above at `overlap` 1: same entry points and arithmetic, with a launch that leaves the + * CUs to the compute running beside it (tArLane). */ { "ar_oneshot_2rank_exact_lane", "all_reduce", "ar", "all-reduce (sum), one-shot push over P2P IPC scratch, narrow launch beside compute", "exactly 2 ranks, peer-accessible, overlap 1; scratch sized by the full message; cudagraph-safe", @@ -5385,6 +5201,20 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, r4d_rad_ar_init, r4d_rad_ar_fini, r4d_rad_ar_twoshot_4rank_ti8, nullptr, nullptr, nullptr, r4d_shape_all_reduce }, +/* The row above at `overlap` 1: the same entry point and the same arithmetic, a launch that leaves + * the CUs to the compute running beside it (tArTs4Lane). */ +{ "ar_twoshot_4rank_ti8_lane", "all_reduce", "ar", + "all-reduce (sum), reduce-scatter + all-gather on the tiered-int8 wire -- lossy; narrow launch " + "beside compute", + "exactly 4 ranks, all peer-accessible, overlap 1; groups of 32 per shard (numel tiles 128); " + "cudagraph-safe", + "bf16 / fp16 payload, int8 + fp16 scale + u32 record per group on the wire, fp32 accumulate in " + "ascending rank order, bit-identical across ranks and to the wide row", + RAD_DOMAIN_DEVICE, R4D_PRIO_AR_ONESHOT + 1, + ROW(cArTi8Ts4Lane), ROW(tArTs4Lane), nullptr, + r4d_rad_ar_init, r4d_rad_ar_fini, r4d_rad_ar_twoshot_4rank_ti8, nullptr, nullptr, nullptr, + r4d_shape_all_reduce }, + /* ---------------------------------------------------------------------------------- GEMM ---- */ { "gemm_bf16_nt_m16", "gemm_nt", "gemm", "skinny GEMM C[M,N] = A[M,K] @ W[N,K]^T, split-K reduced in LDS", @@ -5496,12 +5326,10 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, /* ------------------------------------------------------------------------ block-scaled fp8 * - * THE FORMAT THE CHECKPOINT SHIPS IN. Every other quantised GEMM here reads a weight this project's - * own quantiser produced; these three read `.weight` as safetensors stores it -- F8_E4M3 - * [N][K] with `.weight_scale_inv` BF16 on a [ceil(N/128)][ceil(K/128)] grid. No repacking - * and no scale conversion, so a .rad built for them costs exactly what the checkpoint does. Without - * them the only way to serve Qwen3.8-27B-FP8 is to dequantise it to bf16 at conversion, at twice - * the weight bytes of a 27B model across two 32 GB cards. + * These read block-scaled FP8 checkpoints as shipped: `.weight` F8_E4M3 [N][K] with + * `.weight_scale_inv` BF16 on a [ceil(N/128)][ceil(K/128)] grid. No repacking or scale + * conversion, so a .rad costs what the checkpoint does, instead of a bf16 dequantisation at twice + * the weight bytes. */ { "gemm_fp8a16_nt_m1", "gemm_nt_q", "gemm", "block-scaled FP8 matvec against the checkpoint's own weight bytes: one wave a row, 512 " @@ -5515,7 +5343,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cGemmNtFp8A16), ROW(tMv), nullptr, nullptr, nullptr, r4d_rad_gemm_fp8a16_m1, nullptr, r4d_rad_layout_fp8_rowmajor, nullptr, - r4d_shape_gemm_nt_q, nullptr }, + r4d_shape_gemm_nt_q }, { "gemm_fp8a8_nt_m16", "gemm_nt_q", "gemm", "block-scaled FP8 W8A8 GEMM at the speculative-verify width: 16-wide token tiles, NT up to 4 of " @@ -5533,8 +5361,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cGemmNtFp8A8M16), NOTUNE, nullptr, nullptr, r4d_rad_gemm_fp8a8_m16, r4d_rad_gemm_fp8a8_m16_scratch, r4d_rad_layout_fp8_block, r4d_rad_relayout_fp8_block, - r4d_shape_gemm_nt_q, r4d_rad_unrelayout_fp8_block, nullptr, - r4d_rad_gemm_fp8a8_m16_describe }, + r4d_shape_gemm_nt_q, r4d_rad_unrelayout_fp8_block }, { "gemm_fp8a8_gated_nt_m16", "gemm_nt_q_gated", "gemm", "the narrow fp8 GEMM with the SwiGLU and the fp8 quantiser folded into its epilogue: the block's " @@ -5552,9 +5379,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_gemm_fp8a8_gated_m16, nullptr, r4d_rad_layout_fp8_block, r4d_rad_relayout_fp8_block, r4d_shape_gemm_nt_q_gated, r4d_rad_unrelayout_fp8_block, - /* The "byte-identical to gemm_nt_q followed by gated_quant_fp8" above, made executable: both - * steps are rows of this plugin, so the claim is checkable libr4d-against-libr4d rather than - * against a tolerance. r4d_fuse.cpp names the two parameters that are not copies. */ + /* The byte-identity claim above, as a chain of two rows of this plugin (r4d_fuse.cpp). */ r4d_fuse_gemm_nt_q_gated }, { "gemm_fp8a8_tiled", "gemm_nt_q", "gemm", @@ -5579,8 +5404,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cGemmNtI8A8M16), NOTUNE, nullptr, nullptr, r4d_rad_gemm_i8a8_m16, r4d_rad_gemm_i8a8_m16_scratch, r4d_rad_layout_i8_block, r4d_rad_relayout_i8_block, - nullptr, r4d_rad_unrelayout_i8_block, nullptr, - r4d_rad_gemm_i8a8_m16_describe }, + nullptr, r4d_rad_unrelayout_i8_block }, { "gemm_i8a8_tiled", "gemm_nt_q", "gemm", "gemm_fp8a8_tiled at INT8 codes: the same 128x128 prefill tile, the iu8 WMMA for the fp8 one and " @@ -5593,7 +5417,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, r4d_rad_layout_i8_block, r4d_rad_relayout_i8_block, nullptr, r4d_rad_unrelayout_i8_block }, -/* BAND READ OFF THE ENTRY POINT'S OWN REJECTION TESTS, not off a kernel-side row. */ +/* Band read off the entry point's own rejection tests, not a kernel-side row. */ { "gemm_w8a8_nt_m64", "gemm_nt_q", "gemm", "skinny GEMM with an 8-bit weight and an 8-bit activation: the promoted linears of the INT4 " "target (every down_proj, the attention o_proj) and lm_head", @@ -5652,7 +5476,7 @@ 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_tiled, r4d_rad_gemm_mxfp4a8_tiled_scratch, r4d_rad_layout_mxfp4, r4d_rad_relayout_mxfp4 }, -/* BAND READ OFF THE ENTRY POINT'S OWN REJECTION TESTS. */ +/* Band read off the entry point's own rejection tests. */ { "gemm_w4a8_prefill", "gemm_nt_q", "gemm", "the 4-bit GEMM for PREFILL row counts, where the matrix pipe rather than the weight stream is " "the constraint: the activation is stored half-major in LDS so one ds_load_b128 fetches two k " @@ -5664,7 +5488,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_gemm_w4a8_prefill, nullptr, r4d_rad_layout_w4, r4d_rad_relayout_w4, nullptr, r4d_rad_unrelayout_w4 }, -/* BAND READ OFF THE ENTRY POINT'S OWN REJECTION TESTS. */ +/* Band read off the entry point's own rejection tests. */ { "gemm_w4a8_tiled", "gemm_nt_q", "gemm", "the 4-bit GEMM tiled for large M, where the skinny kernel gives a block 64 rows and so re-reads " "the weight M/64 times. dtype w4a8_asym takes the asymmetric grid and needs a_sum", @@ -5676,7 +5500,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_gemm_w4a8_tiled, nullptr, r4d_rad_layout_w4, r4d_rad_relayout_w4, nullptr, r4d_rad_unrelayout_w4 }, -/* BAND READ OFF THE ENTRY POINT'S OWN REJECTION TESTS. */ +/* Band read off the entry point's own rejection tests. */ { "gemm_w8a8_tiled", "gemm_nt_q", "gemm", "the 8-bit GEMM tiled for large M; inherits the 4-bit kernel's unpack-at-staging path, whose LDS " "buffer already holds bytes", @@ -5695,12 +5519,6 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_dequant_w4, nullptr, nullptr, nullptr, r4d_shape_dequant_w4 }, -/* THE KERNEL-SIDE ROW AND THE ENTRY POINT DISAGREE ON R. The kernel's row says R <= 1024, in the - * predicate and in the prose; the entry point throws for R > R4D_TOPK_PT2, which is 32, and calls - * that "a real limit, not a tuning choice". The predicate below keeps the kernel-side value -- a - * constraint is a NECESSARY condition and this one is simply weak -- and the shim rejects R > 32 - * with RAD_E_SHAPE. Here the code is the only correct statement of the bound: both the row and its - * prose overstate it. */ { "scale_rows_bf16", "scale_rows", "elem", "one scalar a row, optionally through a sigmoid, broadcast across the row", "any M and n; the scalar stream is [M] or [M, 1]", @@ -5725,9 +5543,9 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "single-workgroup form; bf16 logits and weights, i32 everything else", "bf16 in, bf16 weights + i32 ids, sorted slots, offsets and counts out", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, - ROW(cRouterTopkScatter), NOTUNE, + ROW(cRouterTopK), NOTUNE, nullptr, nullptr, r4d_rad_router_topk_scatter, nullptr, nullptr, nullptr, - r4d_shape_router_topk_scatter, nullptr, nullptr, r4d_rad_router_topk_scatter_describe }, + r4d_shape_router_topk_scatter }, { "router_gemm_topk_scatter_bf16", "router_gemm_topk_scatter", "moe", "the router GEMM, its top-k and the stable counting sort in one launch -- the last workgroup " @@ -5740,8 +5558,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cRouterGemmTopkScatter), NOTUNE, r4d_rad_router_gemm_topk_scatter_init, r4d_rad_router_gemm_topk_scatter_fini, r4d_rad_router_gemm_topk_scatter, nullptr, nullptr, nullptr, - r4d_shape_router_gemm_topk_scatter, nullptr, nullptr, - r4d_rad_router_gemm_topk_scatter_describe }, + r4d_shape_router_gemm_topk_scatter }, { "moe_scatter_i32", "moe_scatter", "moe", "a stable counting sort of the routing slots by expert, with the offsets and the histogram", @@ -5763,24 +5580,14 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "tile, bf16 out", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMoeGemmQ), NOTUNE, - /* THE ROW-MAJOR fp8 LAYOUT, WHICH IS THE CHECKPOINT'S OWN BYTES, and it is shared verbatim with - * the fp8a16 matvec. `moe_gemm_q`'s operand positions put the weight at 2 and its scale plane at - * 3 -- the same places `gemm_nt_q` puts them -- so the hook needs no MoE-specific arm and the - * container stores an expert exactly as the safetensors file holds it. - * - * NOT the FRAGMENT order the dense fp8a8 GEMMs use. A fragment plane is a permutation for a - * kernel that reads a WMMA fragment straight from a coalesced global load; this kernel stages - * through LDS because its rows are GATHERED -- a sorted row's activation comes from whichever - * token routed there -- so there is nothing for the permutation to buy, and reading it would - * require the de-permuting staging path the dense kernel uses for its OTHER operand. - * - * A DECLARED-fp8 WEIGHT WITH NO LAYOUT HOOK IS REFUSED BY rad-convert, by name, with "fp8_e4m3 - * with block scales in a companion tensor, which this path cannot read". That is the right - * refusal when the hook is missing: the converter has no other way to know that the bytes on - * disk are already the bytes the kernel wants. */ + /* The row-major fp8 layout: the checkpoint's own bytes, shared with the fp8a16 matvec. + * `moe_gemm_q` puts the weight at operand 2 and its scale at 3, as `gemm_nt_q` does, so the hook + * needs no MoE arm. Not the dense fp8a8 GEMMs' fragment order: this kernel stages through LDS + * because its rows are gathered, so a permutation buys nothing. rad-convert refuses a declared + * fp8 weight with no layout hook, so the hook is what tells it the bytes are already right. */ nullptr, nullptr, r4d_rad_moe_gemm_q, r4d_rad_moe_gemm_q_scratch, r4d_rad_layout_moe_fp8, nullptr, - r4d_shape_moe_gemm_q, nullptr }, + r4d_shape_moe_gemm_q }, { "moe_gemm_w4a8", "moe_gemm_q", "moe", "the same grouped GEMM with the expert weight at FOUR BITS: row-major packed nibbles expanded to " @@ -5795,29 +5602,18 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "five-bit codes into libquant's w5nl levels, a sign bit plane after each row's nibbles", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMoeGemmW4), NOTUNE, - /* NO SHAPE FUNCTION, for the reason r4d_shapes.cpp's header gives for every non-fp8 gemm_nt_q - * grid: the weight is a plugin-private packed plane whose byte count r4d_layout.cpp owns, and a - * second statement of it here would drift the first time the packing changed. The kernel's - * decode is checked by r4d_selftest against the relayout that produced the bytes, which is the - * comparison that can actually fail -- a kbench case would be comparing two readings of random - * nibbles. + /* No shape function: the weight is a plugin-private packed plane whose byte count + * r4d_layout.cpp owns (see r4d_shapes.cpp). r4d_selftest checks the decode against the + * relayout that produced the bytes. * - * WHY 4 BITS AT ALL, and it is capacity and not quality. Qwen3.8-Flash-Next is 512 experts of - * 640 over 48 layers: 112.8 GiB of expert weight at E4M3, against two 32 GB cards. Expert - * parallelism halves the per-rank share and the placement plan still refuses 26 GiB of it -- - * and a ROUTED weight cannot be served from the file tier, because nothing schedules a read for - * an expert the router picks this step. At four bits the share fits VRAM plus a few GiB of - * pinned host, which is the difference between a model that serves and one that does not. + * Four bits for capacity: Qwen3.8-Flash-Next's 512 experts over 48 layers are 112.8 GiB at + * E4M3, too much for two 32 GB cards even with expert parallelism, and a routed weight cannot + * be served from the file tier. At four bits the share fits VRAM plus a few GiB of pinned host. * - * THERE IS AN INVERSE THOUGH, and with no shape function beside it that is not a contradiction: - * the two hooks answer different questions. The shape function describes the plane the KERNEL is - * handed, which here is a plugin-private packed one a caller cannot allocate meaningfully; the - * inverse produces the canonical codes plane, from which the oracle hands a dense REFERENCE the - * codes one per element in whatever form that reference reads. Without it this row -- the - * largest weight a routed model touches -- would be one an oracle has to decline by name. */ + * The unrelayout hook is still provided: it yields the canonical codes plane, so an oracle can + * hand a dense reference the codes even though callers cannot allocate the packed plane. */ nullptr, nullptr, r4d_rad_moe_gemm_w4a8, r4d_rad_moe_gemm_w4a8_scratch, - r4d_rad_layout_moe_w4, r4d_rad_relayout_moe_w4, nullptr, r4d_rad_unrelayout_moe_w4, nullptr, - r4d_rad_moe_gemm_w4a8_describe }, + r4d_rad_layout_moe_w4, r4d_rad_relayout_moe_w4, nullptr, r4d_rad_unrelayout_moe_w4 }, { "moe_gemm_fp8a8_mod4", "moe_gemm_q_mod4", "moe", "moe_gemm_fp8a8 over four classes of experts by number mod 4: the same kernel, each run reading " @@ -5828,7 +5624,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cMoeGemmQ), NOTUNE, nullptr, nullptr, r4d_rad_moe_gemm_q_mod4, r4d_rad_moe_gemm_q_scratch, r4d_rad_layout_moe_fp8_mod4, nullptr, - r4d_shape_moe_gemm_q_mod4, nullptr }, + r4d_shape_moe_gemm_q_mod4 }, { "moe_gemm_w4a8_mod4", "moe_gemm_q_mod4", "moe", "moe_gemm_w4a8 over four classes of experts by number mod 4: the same kernel, each run reading " @@ -5839,7 +5635,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cMoeGemmW4), NOTUNE, nullptr, nullptr, r4d_rad_moe_gemm_w4a8_mod4, r4d_rad_moe_gemm_w4a8_scratch, r4d_rad_layout_moe_w4_mod4, r4d_rad_relayout_moe_w4_mod4, nullptr, - r4d_rad_unrelayout_moe_w4_mod4, nullptr, r4d_rad_moe_gemm_w4a8_mod4_describe }, + r4d_rad_unrelayout_moe_w4_mod4 }, { "moe_gemm_bf16", "moe_gemm", "moe", "the grouped GEMM with unquantised experts: one run of expert-sorted rows a block, bf16 WMMA over " @@ -5850,12 +5646,10 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "f32 accumulate over the whole of K, bf16 out rounded to nearest-even", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMoeGemmBf16), NOTUNE, - /* NO LAYOUT HOOK AND NO SHAPE FUNCTION. The plane is the checkpoint's own bytes, so the core's - * identity layout is the right answer and a container stores an expert exactly as the - * safetensors file holds it -- which is what lets the file tier read one into a staging buffer - * and hand it to this kernel unchanged. libref describes the op for a tool that needs buffers. */ - nullptr, nullptr, r4d_rad_moe_gemm_bf16, r4d_rad_moe_gemm_bf16_scratch, nullptr, nullptr, - nullptr, nullptr, nullptr, r4d_rad_moe_gemm_bf16_describe }, + /* No layout hook and no shape function. The plane is the checkpoint's own bytes (identity + * layout), so the file tier can stage an expert and hand it to this kernel unchanged. libref + * describes the op for tools. */ + nullptr, nullptr, r4d_rad_moe_gemm_bf16, r4d_rad_moe_gemm_bf16_scratch }, { "moe_gather_bf16", "moe_gather", "moe", "the weighted scatter back to token order, summing a token's slots in ascending slot order", @@ -5868,13 +5662,12 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, { "rowtopk_bf16", "row_topk", "select", "exact per-row top-R of a bf16 matrix, descending, ties to the lower column", - "any M, N a multiple of 8, R <= 32 (the row says 1024 and the entry point says 32); " - "two launches, caller-sized partial buffer", + "any M, N a multiple of 8, R <= 32; two launches, caller-sized partial buffer", "bf16 in, f32 values + i32 columns out", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cRowTopK), ROW(tTopk), nullptr, nullptr, nullptr, r4d_rad_rowtopk, r4d_rad_rowtopk_scratch, nullptr, nullptr, - r4d_shape_row_topk , nullptr, nullptr, r4d_rad_rowtopk_describe }, + r4d_shape_row_topk }, { "logit_rerank", "logit_rerank", "select", "R candidates a row rescored exactly against the full-precision head", @@ -5885,13 +5678,9 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cLogitRerank), NOTUNE, nullptr, nullptr, r4d_rad_logit_rerank, nullptr, r4d_rad_layout_fp8_logits, r4d_rad_relayout_fp8_logits, - /* NO opd_shape, for logits_gemm_fp8's reason and in its words: the declared shape and - * the stored plane differ and only the container knows. A tool that allocated - * [n_vocab][n_embd] would hand this kernel a buffer it reads 1.6% past the end of on - * every row, because the row's own bf16 scales ride in its tail -- and the comparison - * that follows fails on the padding rather than on the arithmetic. So it is skipped by - * name like its neighbour until RadOpdDesc can say "declared this, stored that". */ - nullptr, r4d_rad_unrelayout_fp8_logits, nullptr, r4d_rad_logit_rerank_describe }, + /* No opd_shape, as for logits_gemm_fp8: the declared shape and the stored plane (scales in + * each row's tail) differ, so a buffer of the declared shape would be read past its end. */ + nullptr, r4d_rad_unrelayout_fp8_logits }, { "logit_rerank_i8", "logit_rerank", "select", "logit_rerank over an INT8 head: the same candidates rescored against logits_gemm_i8's rows", @@ -5902,7 +5691,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_logit_rerank_i8, nullptr, r4d_rad_layout_i8_logits, r4d_rad_relayout_i8_logits, /* No opd_shape, for logit_rerank's reason: the declared shape and the stored row differ. */ - nullptr, r4d_rad_unrelayout_i8_logits, nullptr, r4d_rad_logit_rerank_i8_describe }, + nullptr, r4d_rad_unrelayout_i8_logits }, { "rowtopk_merge", "row_topk_merge", "select", "the global top-R of world_size all-gathered per-rank candidate sets", @@ -5916,10 +5705,10 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, /* ------------------------------------------------- quantisation, norms and the fusions ------ */ -/* The gate on both fp8a8 GEMMs: `activation_scheme: "dynamic"` means the checkpoint ships no - * activation scale, so one is computed every step. This is the STANDALONE form, for the launches - * whose input is some GEMM's output and so cannot ride on a producer. Where a producer already - * holds the row, `rmsnorm_quant_fp8` or `gated_quant_fp8` below does the same work on its pass. */ +/* The input quantiser of both fp8a8 GEMMs: `activation_scheme: "dynamic"` means the checkpoint + * ships no activation scale, so one is computed every step. This standalone form serves inputs + * that are some GEMM's output; where a producer holds the row, `rmsnorm_quant_fp8` or + * `gated_quant_fp8` below quantises on its pass. */ { "quant_act_fp8", "quant_act_fp8", "quant", "per-(row, 128-column) symmetric E4M3 quantisation of a bf16 activation", "n a multiple of 4 -- a lane owns four columns, so the store is one dword and the wave's is 128 " @@ -5929,15 +5718,12 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cQuantActFp8), NOTUNE, nullptr, nullptr, r4d_rad_quant_act_fp8, nullptr, nullptr, nullptr, - r4d_shape_quant_act_fp8, nullptr, nullptr, r4d_rad_quant_act_fp8_describe }, + r4d_shape_quant_act_fp8 }, -/* The rotated twin. It exists for the FOUR-BIT expert weight and for nothing else: at E4M3 a - * rotation is slightly WORSE, because four exponent bits already carry the outliers a rotation - * removes. Four-bit weights are the opposite case -- sixteen levels spent covering one outlier - * channel is the whole error -- so this pays the activation's small price to buy the weight's - * large one. The trade only closes with GPTQ on top: rotation alone makes plain round-to-nearest - * int4 substantially worse, which is why this row exists ahead of the error-feedback packer and - * not the other way round. */ +/* The rotated twin, for the four-bit expert weight only. At E4M3 a rotation is slightly worse + * (four exponent bits already carry the outliers it removes); at four bits, sixteen levels spent + * covering one outlier channel is the whole error. The trade pays off only with GPTQ: rotation + * alone makes round-to-nearest int4 substantially worse. */ { "had_quant_act_fp8", "had_quant_act_fp8", "quant", "a 128-wide Hadamard along K, then per-(row, 128-column) symmetric E4M3 quantisation", "n a multiple of 128 -- a rotation block cannot straddle the end of a row -- and group 128, " @@ -5948,7 +5734,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cHadQuantActFp8), NOTUNE, nullptr, nullptr, r4d_rad_had_quant_act_fp8, nullptr, nullptr, nullptr, - r4d_shape_quant_act_fp8, nullptr, nullptr, r4d_rad_had_quant_act_fp8_describe }, + r4d_shape_quant_act_fp8 }, { "givens_dense_quant", "givens_dense_quant", "quant", "ParoQuant's rotation as a dense 128 x 128 f16 matrix a (part, group) on the matrix cores, then " @@ -5959,8 +5745,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "or amax/448) per (row, part, 128 columns); f16 matrices and f32 channel scales", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGivensDense), NOTUNE, - nullptr, nullptr, r4d_rad_givens_dense_quant, nullptr, r4d_rad_layout_gdense, r4d_rad_relayout_gdense, - nullptr, nullptr, nullptr, r4d_rad_givens_dense_quant_describe }, + nullptr, nullptr, r4d_rad_givens_dense_quant, nullptr, r4d_rad_layout_gdense, r4d_rad_relayout_gdense }, { "givens_rotate", "givens_rotate", "quant", "the channel scale and ParoQuant's Givens rotations, once for each rotated part, to f16", @@ -5970,8 +5755,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cHadQuantActFp8), NOTUNE, nullptr, nullptr, r4d_rad_givens_rotate, nullptr, r4d_rad_layout_givens_pairs, - r4d_rad_relayout_givens_pairs, nullptr, r4d_rad_unrelayout_givens_pairs, nullptr, - r4d_rad_givens_rotate_describe }, + r4d_rad_relayout_givens_pairs, nullptr, r4d_rad_unrelayout_givens_pairs }, { "quant_act_i8g", "quant_act_i8g", "quant", "per-(row, 128-column) symmetric int8 quantisation of a bf16 activation", @@ -5979,8 +5763,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16 in, int8 out in PLAIN ROW-MAJOR order with an f32 scale of amax/127 per (row, 128 columns)", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cQuantActFp8), NOTUNE, - nullptr, nullptr, r4d_rad_quant_act_i8g, nullptr, nullptr, nullptr, - nullptr, nullptr, nullptr, r4d_rad_quant_act_i8g_describe }, + nullptr, nullptr, r4d_rad_quant_act_i8g }, { "had_quant_act_i8g", "had_quant_act_i8g", "quant", "a 128-wide Hadamard along K, then per-(row, 128-column) symmetric int8 quantisation", @@ -5989,30 +5772,9 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "columns); the sqrt(128) of the unnormalised transform is left to the weight's stored scale", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cHadQuantActFp8), NOTUNE, - nullptr, nullptr, r4d_rad_had_quant_act_i8g, nullptr, nullptr, nullptr, - nullptr, nullptr, nullptr, r4d_rad_had_quant_act_i8g_describe }, + nullptr, nullptr, r4d_rad_had_quant_act_i8g }, -/* THE CALIBRATION HALF OF GPTQ, and the only op in this library that no forward pass issues. It - * runs under a calibration flag, beside the quantiser whose output it characterises, and the - * Hessians it accumulates are read at CONVERT time by the 4-bit expert packer -- so the producer - * and the consumer are in different processes and the channel between them is a file. That is - * unusual enough to say out loud: a row here that the serving graph never resolves is normally a - * defect -- a kernel built and never wired -- and this one is not. */ -/* THE FIRST PIECE OF QSA, and the only one of its four that is query-independent -- which is - * exactly why it is a kernel and not a loop inside the scorer. A block key is fixed once its four - * tokens exist, so it is built when the fourth arrives and read by every query after it. - * docs/QSA.md is the decomposition it belongs to. */ -/* The indexer's vote. One workgroup a query, one WAVE a 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 four heads -- which is why the head loop is inside the block - * loop. docs/QSA.md is what it belongs to. */ -/* A four-digit radix select, one workgroup a query. Not a sort: attention is a softmax over a SET - * so the order inside the table does not matter, and sorting 65536 scores a query a layer a step - * is not affordable. What does matter is that the set is exact and DETERMINISTIC, so ties break - * to the lower block index through a prefix count rather than through whichever atomic landed - * first -- this tree compares generated text across builds byte for byte. */ -/* One workgroup a token, and most of them exit on the second compare. */ -/* One workgroup a potential block. */ +/* QSA (docs/QSA.md). The work list: one workgroup per potential block. */ { "qsa_work_bf16", "qsa_work", "attn", "gather the blocks completing this step into the flat list qsa_block_key reads", "any declared sequence maximum -- the real count comes off cu_seqlens at issue and the launcher " @@ -6023,8 +5785,9 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cQsaWork), NOTUNE, nullptr, nullptr, r4d_rad_qsa_work, nullptr, nullptr, nullptr, - r4d_shape_qsa_work, nullptr, nullptr, r4d_rad_qsa_work_describe }, + r4d_shape_qsa_work }, +/* One workgroup per token; most exit on the second compare. */ { "qsa_tail_store_bf16", "qsa_tail_store", "attn", "park the raw index keys of the tokens that have not completed a block, one slot a position", "any token count, any width, any ratio; the sequence count comes off cu_seqlens at run time " @@ -6033,8 +5796,11 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cQsaTailStore), NOTUNE, nullptr, nullptr, r4d_rad_qsa_tail_store, nullptr, nullptr, nullptr, - r4d_shape_qsa_tail_store, nullptr, nullptr, r4d_rad_qsa_tail_store_describe }, + r4d_shape_qsa_tail_store }, +/* A four-digit radix select, one workgroup per query. Not a sort: attention is a softmax over a + * set, and sorting 65536 scores per query per layer per step is too costly. The set is exact and + * deterministic: ties break to the lower block index through a prefix count, never atomic order. */ { "qsa_select_i32", "qsa_select", "attn", "the topk highest-scoring blocks as a page-id table, with the partial page appended last", "any M, any block count, any topk; a decode-shaped launch splits the block list across the " @@ -6043,8 +5809,11 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cQsaSelect), NOTUNE, nullptr, nullptr, r4d_rad_qsa_select, r4d_rad_qsa_select_scratch, nullptr, nullptr, - r4d_shape_qsa_select, nullptr, nullptr, r4d_rad_qsa_select_describe }, + r4d_shape_qsa_select }, +/* 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). */ { "qsa_score_bf16", "qsa_score", "attn", "the QSA indexer's block score: relu per (block, head), summed over heads, over 1/sqrt(n)", "n a multiple of 32 up to 256, at most 8 heads, any block count and any M", @@ -6053,8 +5822,10 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cQsaScore), NOTUNE, nullptr, nullptr, r4d_rad_qsa_score, nullptr, nullptr, nullptr, - r4d_shape_qsa_score, nullptr, nullptr, r4d_rad_qsa_score_describe }, + r4d_shape_qsa_score }, +/* The only query-independent piece of QSA, hence a kernel of its own: a block key is fixed once + * its tokens exist, so it is built when the last arrives and read by every later query. */ { "qsa_block_key_bf16", "qsa_block_key", "attn", "the QSA indexer's compressed key: mean of `ratio` raw keys, RMS-normed, rotated at the " "block's first position", @@ -6065,8 +5836,12 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cQsaBlockKey), NOTUNE, nullptr, nullptr, r4d_rad_qsa_block_key, nullptr, nullptr, nullptr, - r4d_shape_qsa_block_key, nullptr, nullptr, r4d_rad_qsa_block_key_describe }, + r4d_shape_qsa_block_key }, +/* GPTQ's calibration half, the only op here no forward pass issues. It runs under a calibration + * flag beside the quantiser whose output it characterises, and the 4-bit expert packer reads the + * accumulated Hessians at convert time, from a file. So it is unresolved by the serving graph on + * purpose, not an unwired kernel. */ { "gram_accum", "gram_accum", "quant", "h += x^T x over an E4M3 activation, in f32 -- the Gram matrix a GPTQ packer needs", "n a multiple of 4 and group 128, because a 64-wide output tile must lie inside one scale " @@ -6087,11 +5862,9 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_gram_accum_bf16, nullptr, nullptr, nullptr, r4d_shape_gram_accum }, -/* THE TWO fp8 FUSIONS, the counterparts of the ones the int8 path carries. A producer that - * already holds the row -- an RMS norm, a gated product -- writes the E4M3 pair on the same pass, - * so the quantiser's launch and its second read of the row both disappear. The - * codes are the unfused pair's exactly, because both round to bf16 before quantising; the engine - * compares generated text across builds byte for byte and that is what makes it hold. */ +/* The two fp8 fusions, counterparts of the int8 path's. A producer that holds the row (an RMS + * norm, a gated product) writes the E4M3 pair on the same pass, saving the quantiser's launch and + * its second read. The codes equal the unfused pair's, since both round to bf16 first. */ { "rmsnorm_quant_fp8", "rmsnorm_quant_fp8", "quant", "RMS norm and the fp8 activation quantiser in one pass over the row, plus the bf16 norm output " "the unfused pair wrote", @@ -6104,10 +5877,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cRmsNormQuantFp8), NOTUNE, nullptr, nullptr, r4d_rad_rmsnorm_quant_fp8, nullptr, nullptr, nullptr, r4d_shape_rmsnorm_quant_fp8, nullptr, - /* `add` + `rmsnorm` + `quant_act_fp8`, and NOT `rmsnorm_add` + `quant_act_fp8`: this kernel - * takes the sum of squares over the BF16-ROUNDED residual and ref's `rmsnorm_add` takes it over - * the unrounded f32 sum, so only the first spelling is the function this computes. See - * r4d_fuse.cpp, which also states what the hook cannot see about the residual's presence. */ + /* `add` + `rmsnorm` + `quant_act_fp8`, not `rmsnorm_add` (r4d_fuse.cpp). */ r4d_fuse_rmsnorm_quant_fp8 }, { "gated_quant_fp8", "gated_quant_fp8", "quant", @@ -6121,17 +5891,11 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cGatedQuantFp8), NOTUNE, nullptr, nullptr, r4d_rad_gated_quant_fp8, nullptr, nullptr, nullptr, r4d_shape_gated_quant_fp8, nullptr, - /* `silu_mul` + `quant_act_fp8` on the silu arm only. The sigmoid arm has no chain and the - * reason is not the activation -- `sigmoid` and `mul` are both ops with rows here -- but that - * `gate_up` is one packed [M, 2n] plane and the operand wiring cannot name half of an operand. - * `silu_mul` is the only op that does that split itself. */ - r4d_fuse_gated_quant_fp8, r4d_rad_gated_quant_fp8_describe }, + /* `silu_mul` + `quant_act_fp8`, silu arm only (r4d_fuse.cpp). */ + r4d_fuse_gated_quant_fp8 }, -/* The rotated twin, for a down projection whose weight is stored at w4a8h. NO FUSION HOOK, and - * the absence is the honest answer rather than an oversight: `silu_mul` + `had_quant_act_fp8` is - * a pair a plugin could emit, but nothing in this tree emits it -- the rotated activation exists - * for the routed MoE arm and the MoE block declares this op directly. A hook that matched a chain - * no graph contains would be a claim nothing exercises. */ +/* The rotated twin, for a down projection whose weight is stored at w4a8h. No fusion hook: + * nothing emits `silu_mul` + `had_quant_act_fp8`; the MoE block declares this op directly. */ { "gated_had_quant_fp8", "gated_had_quant_fp8", "quant", "an elementwise gated product, a 128-wide Hadamard along n, and the fp8 activation quantiser, " "in one pass", @@ -6144,7 +5908,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGatedHadQuantFp8), NOTUNE, nullptr, nullptr, r4d_rad_gated_had_quant_fp8, nullptr, nullptr, nullptr, - r4d_shape_gated_quant_fp8, nullptr, nullptr, r4d_rad_gated_had_quant_fp8_describe }, + r4d_shape_gated_quant_fp8 }, { "gate_quant_fp8", "gate_quant_fp8", "quant", "an elementwise gated product and the fp8 activation quantiser in one pass, with the gate in " @@ -6158,18 +5922,13 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cGateQuantFp8), NOTUNE, nullptr, nullptr, r4d_rad_gate_quant_fp8, nullptr, nullptr, nullptr, r4d_shape_gate_quant_fp8, nullptr, - /* `sigmoid` + `mul` + `quant_act_fp8`. This row rounds the activation to bf16 before the - * multiply where its `gated_quant_fp8` sibling does not, precisely because the pair IT replaces - * is two kernels with a bf16 buffer between them -- so the sibling's expressible arm is silu and - * this one's is sigmoid. The silu arm is declined: libr4d has no `silu` row and ref's is - * `x * sigmoid(x)` against this kernel's `x / (1 + exp(-x))`. */ - r4d_fuse_gate_quant_fp8, r4d_rad_gate_quant_fp8_describe }, + /* `sigmoid` + `mul` + `quant_act_fp8`; the silu arm is declined (r4d_fuse.cpp). */ + r4d_fuse_gate_quant_fp8 }, /* ---------------------------------------------------------------------------------- sampling * - * spec §13 requires sampling on device, and this is the project's only device sampler: libref - * implements docs/OPS.md's eight HOST ops and nothing else implements this one, so there is no - * second implementation to compare it against. */ + * spec §13 requires sampling on device. This is the only implementation of sample_chain (libref + * implements docs/OPS.md's host stages), so there is nothing to compare it against. */ { "sample_chain_f32", "sample_chain", "sample", "temperature, softmax, top_k, top_p, min_p, renormalise and the draw in vLLM's order -- plus the " "exclusive draw and the accept probability a greedy-draft rejection-sampling verify needs -- in " @@ -6193,7 +5952,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cQuantActI8), NOTUNE, nullptr, nullptr, r4d_rad_quant_act_i8, nullptr, nullptr, nullptr, - r4d_shape_quant_act_i8 , nullptr, nullptr, r4d_rad_quant_act_i8_describe }, + r4d_shape_quant_act_i8 }, { "rmsnorm_quant_i8", "rmsnorm_quant_i8", "quant", "RMS norm and quant_act_i8's quantiser in one pass over the row; optionally the residual " @@ -6204,8 +5963,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "out; every stored intermediate rounded to bf16 as the unfused chain stores it", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cRmsNormQuantI8), NOTUNE, - nullptr, nullptr, r4d_rad_rmsnorm_quant_i8, nullptr, nullptr, nullptr, - nullptr, nullptr, nullptr, r4d_rad_rmsnorm_quant_i8_describe }, + nullptr, nullptr, r4d_rad_rmsnorm_quant_i8 }, { "qkv_norm_rope_bf16", "qkv_norm_rope", "attn", "per-head RMS norms of separate q and k projections, the weightless norm of v (or of the raw k), " @@ -6216,8 +5974,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "rope x2, each norm taken by its standalone kernel's partition", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cQkvNormRope), NOTUNE, - nullptr, nullptr, r4d_rad_qkv_norm_rope, nullptr, nullptr, nullptr, - nullptr, nullptr, nullptr, r4d_rad_qkv_norm_rope_describe }, + nullptr, nullptr, r4d_rad_qkv_norm_rope }, { "gelu_mul_quant_i8", "gelu_mul_quant_i8", "quant", "gelu(gate) * up, the tanh form, and quant_act_i8's quantiser in one pass over the row", @@ -6226,8 +5983,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16 out; the codes taken over the bf16-rounded product", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGeluMulQuantI8), NOTUNE, - nullptr, nullptr, r4d_rad_gelu_mul_quant_i8, nullptr, nullptr, nullptr, - nullptr, nullptr, nullptr, r4d_rad_gelu_mul_quant_i8_describe }, + nullptr, nullptr, r4d_rad_gelu_mul_quant_i8 }, { "ar_rmsnorm_quant_i8", "ar_rmsnorm_quant_i8", "quant", "the two-rank exact all-reduce and the junction after it -- post-norm of the reduced sum, residual " @@ -6237,8 +5993,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "rounded to bf16 as the standalone exact all-reduce stores it", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cArRmsNormQuantI8), ROW(tAr), nullptr, - r4d_rad_ar_ln_init, r4d_rad_ar_fini, r4d_rad_ar_rmsnorm_quant_i8, nullptr, nullptr, nullptr, - nullptr }, + r4d_rad_ar_ln_init, r4d_rad_ar_fini, r4d_rad_ar_rmsnorm_quant_i8 }, { "had_quant_act_i8", "had_quant_act_i8", "quant", "block Hadamard along K then per-row symmetric int8 quantisation; the rotation is what makes " @@ -6263,9 +6018,8 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_rmsnorm_had_quant_i8, nullptr, nullptr, nullptr, r4d_shape_rmsnorm_had_quant_i8 }, -/* UNVALIDATED. The DPP row_xmask form of the fused all-reduce (the r4d_xor_lane exchanges in - * r4d_ar_ln_had_quant_i8.hip) is compile-verified only: never measured and never - * correctness-gated. */ +/* Unvalidated: the DPP row_xmask form of the fused all-reduce (the r4d_xor_lane exchanges in + * r4d_ar_ln_had_quant_i8.hip) is compile-verified only, not measured or correctness-gated. */ { "ar_ln_had_quant_i8", "ar_ln_had_quant_i8", "quant", "the two-rank all-reduce and the residual add, RMS norm, block Hadamard and per-row int8 " "quantisation that always follow it, in one kernel; the all-reduce's bf16 output never exists " @@ -6294,11 +6048,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cArRmsNormQuantFp8), ROW(tAr), nullptr, r4d_rad_ar_ln_init, r4d_rad_ar_fini, r4d_rad_ar_rmsnorm_quant_fp8, nullptr, nullptr, nullptr, r4d_shape_ar_rmsnorm_quant_fp8, nullptr, - /* `all_reduce` + `rmsnorm_quant_fp8`, both wires -- the "byte-identical to the pair it replaces" - * above, made executable. It is the one chain here that needs no assumption about which optional - * operands were passed: its tail step carries the same two optionals in the same positions, so - * absence propagates through the wiring. `ar_ln_had_quant_i8` gets no hook for the opposite - * reason -- it reduces without the bf16 round its unfused pair stores. */ + /* `all_reduce` + `rmsnorm_quant_fp8`, both wires (r4d_fuse.cpp). */ r4d_fuse_ar_rmsnorm_quant_fp8 }, { "ar_hc_write", "ar_hc_write", "norm", @@ -6379,10 +6129,10 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cQkNormRopeGate), NOTUNE, nullptr, nullptr, r4d_rad_qk_norm_rope_gate, nullptr, nullptr, nullptr, - r4d_shape_qk_norm_rope_gate, nullptr, nullptr, r4d_rad_qk_norm_rope_gate_describe }, + r4d_shape_qk_norm_rope_gate }, -/* The prologue and the fp8 cache store as one launch: a k head's block holds its token's rotated - * k one element a lane already, so the store is two byte writes a lane on the same block. */ +/* The prologue and the fp8 cache store in one launch: a k head's block already holds its token's + * rotated k one element per lane, so the store is two byte writes per lane. */ { "qk_norm_rope_gate_kv_store_fp8", "qk_norm_rope_gate_kv_store", "attn", "qk_norm_rope_gate, and kv_store into an E4M3 paged cache from the same launch", "qk_norm_rope_gate's shapes; cache exactly [n_blocks, kv_heads, block_size, 2*head_dim] and " @@ -6391,8 +6141,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cQkNormRopeGateKv), NOTUNE, 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, - r4d_rad_qk_norm_rope_gate_kv_store_describe }, + r4d_shape_qk_norm_rope_gate_kv_store, nullptr, r4d_fuse_qk_norm_rope_gate_kv_store }, /* The same fold into a bf16 cache: the store is the two values the pair's kv_store_bf16 copies. */ { "qk_norm_rope_gate_kv_store_bf16", "qk_norm_rope_gate_kv_store", "attn", @@ -6403,8 +6152,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cQkNormRopeGateKvBf16), NOTUNE, 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, - r4d_rad_qk_norm_rope_gate_kv_store_describe }, + r4d_shape_qk_norm_rope_gate_kv_store, nullptr, r4d_fuse_qk_norm_rope_gate_kv_store }, { "rope_table_f32", "rope_table", "attn", "the cos/sin plane the fused prologue reads, at each position's own row", @@ -6414,7 +6162,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cRopeTable), NOTUNE, nullptr, nullptr, r4d_rad_rope_table, nullptr, nullptr, nullptr, - r4d_shape_rope_table, nullptr, nullptr, r4d_rad_rope_table_describe }, + r4d_shape_rope_table }, { "gated_had_quant_i8", "gated_had_quant_i8", "quant", "an elementwise gated product, block Hadamard and per-row int8 quantisation in one pass; mode 0 " @@ -6460,11 +6208,9 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_dflash_select, nullptr, nullptr, nullptr, r4d_shape_dflash_select }, -/* pair_argmax, the sandwich-norm joins and expert_scale. NO opd_shape on the joins and - * expert_scale: libref has no row for them (see their schemas), so there is no oracle to run them - * against; tests/r4d_emu runs these kernels' source on the host and holds them to the chain they - * replace, bit for bit. pair_argmax is described as libref describes it, so rad-kbench runs it - * against the oracle. */ +/* pair_argmax, the sandwich-norm joins and expert_scale. The joins and expert_scale have no + * opd_shape: libref has no row for them, and tests/r4d_emu holds their source to the replaced chain + * bit for bit on the host. pair_argmax is described as libref describes it. */ { "pair_argmax_f32", "pair_argmax", "select", "the top-1 of a row of (id, value) pairs, ties to the lower id, negative ids skipped", "any M and n; one wave a row; the outputs one element a row at their own pitch", @@ -6480,8 +6226,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16 activations, f32 gains", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cNormJoin), NOTUNE, - nullptr, nullptr, r4d_rad_norm_add_norm_bf16, nullptr, nullptr, nullptr, - nullptr }, + nullptr, nullptr, r4d_rad_norm_add_norm_bf16 }, { "norm_add_norm_route_bf16", "norm_add_norm_route", "norm", "norm_add_norm, and the routed arm's router input and fp8 expert input from the same norm", @@ -6489,8 +6234,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16 activations, f32 gains; E4M3 codes with an f32 scale a 128 columns", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cNormJoinRoute), NOTUNE, - nullptr, nullptr, r4d_rad_norm_add_norm_route_bf16, nullptr, nullptr, nullptr, - nullptr }, + nullptr, nullptr, r4d_rad_norm_add_norm_route_bf16 }, { "join_add_scale_bf16", "join_add_scale", "norm", "two arms' post-norms, sum, norm, residual add, layer scalar: one block a row", @@ -6498,8 +6242,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16 activations, f32 gains, bf16 scalar", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cNormJoin), NOTUNE, - nullptr, nullptr, r4d_rad_join_add_scale_bf16, nullptr, nullptr, nullptr, - nullptr }, + nullptr, nullptr, r4d_rad_join_add_scale_bf16 }, { "expert_scale_bf16", "expert_scale", "moe", "routing weight times its expert's scale, in place: one thread an element", @@ -6507,8 +6250,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "i32 ids, bf16 table and weights", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cExpertScale), NOTUNE, - nullptr, nullptr, r4d_rad_expert_scale_bf16, nullptr, nullptr, nullptr, - nullptr }, + nullptr, nullptr, r4d_rad_expert_scale_bf16 }, { "attn_prefix_self_h128_bf16", "attn_prefix_self", "attn", "attention over a paged prefix and the pass's own rows, causal over the own rows or not", "head_dim 128, 1/2/4/8 query heads a KV head, a flat grid over the sequences' query blocks; " @@ -6516,8 +6258,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16 q/k/v/out and cache, bf16 operands, fp32 accumulate; or i8 Q.K codes, i32 accumulate", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cAttnPrefixSelf), NOTUNE, - nullptr, nullptr, r4d_rad_attn_prefix_self, nullptr, nullptr, nullptr, - nullptr }, + nullptr, nullptr, r4d_rad_attn_prefix_self }, { "attn_dense_h128_bf16", "attn_dense", "attn", "dense varlen attention over cu_seqlens, causal or bidirectional", @@ -6525,8 +6266,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16 query / key / value / out, bf16 operands, fp32 accumulate", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cAttnDenseH128), NOTUNE, - nullptr, nullptr, r4d_rad_attn_dense_h128, nullptr, nullptr, nullptr, - nullptr }, + nullptr, nullptr, r4d_rad_attn_dense_h128 }, { "attn_dense_h768_bf16", "attn_dense", "attn", "one 768-wide head over every row of a segment: an image encoder's mid-block attention", @@ -6534,8 +6274,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16 query / key / value / out, bf16 operands, fp32 accumulate", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cAttnDenseH768), NOTUNE, - nullptr, nullptr, r4d_rad_attn_dense_wide, nullptr, nullptr, nullptr, - nullptr }, + nullptr, nullptr, r4d_rad_attn_dense_wide }, { "attn_dense_h1152_bf16", "attn_dense", "attn", "one 1152-wide head over every row of a segment: an image decoder's mid-block attention", @@ -6543,8 +6282,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16 query / key / value / out, bf16 operands, fp32 accumulate", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cAttnDenseH1152), NOTUNE, - nullptr, nullptr, r4d_rad_attn_dense_wide, nullptr, nullptr, nullptr, - nullptr }, + nullptr, nullptr, r4d_rad_attn_dense_wide }, { "ln_mod_quant_fp8_bf16", "ln_mod_quant_fp8", "norm", "gate_add, ln_mod and quant_act_fp8 in one pass: a workgroup a row", @@ -6552,16 +6290,14 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16 in, E4M3 codes with f32 scales out", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cLnModQ), NOTUNE, - nullptr, nullptr, r4d_rad_ln_mod_quant_fp8, nullptr, nullptr, nullptr, - nullptr }, + nullptr, nullptr, r4d_rad_ln_mod_quant_fp8 }, { "ln_mod_bf16", "ln_mod", "norm", "gainless layer norm times (1 + a sequence's scale row): a workgroup a row", "any M, row pitches honoured", "bf16", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGenRows8), NOTUNE, - nullptr, nullptr, r4d_rad_ln_mod, nullptr, nullptr, nullptr, - nullptr }, + nullptr, nullptr, r4d_rad_ln_mod }, { "gate_add_bf16", "gate_add", "elem", "x += tanh(gate row) * y, the reference's three roundings", @@ -6569,8 +6305,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGenRows8), NOTUNE, - nullptr, nullptr, r4d_rad_gate_add, nullptr, nullptr, nullptr, - nullptr }, + nullptr, nullptr, r4d_rad_gate_add }, { "timestep_embed_bf16", "timestep_embed", "elem", "sinusoidal timestep embedding, f32 angles", @@ -6578,8 +6313,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGenTimestep), NOTUNE, - nullptr, nullptr, r4d_rad_timestep_embed, nullptr, nullptr, nullptr, - nullptr }, + nullptr, nullptr, r4d_rad_timestep_embed }, { "gather_rows2_bf16", "gather_rows2", "elem", "rows from two sources by a signed index", @@ -6587,8 +6321,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGenRows8), NOTUNE, - nullptr, nullptr, r4d_rad_gather_rows2, nullptr, nullptr, nullptr, - nullptr }, + nullptr, nullptr, r4d_rad_gather_rows2 }, { "lane_gather_w32", "lane_gather", "elem", "each entry's rows out of its lane", @@ -6596,8 +6329,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGenLanes), NOTUNE, - nullptr, nullptr, r4d_rad_lane_gather, nullptr, nullptr, nullptr, - nullptr }, + nullptr, nullptr, r4d_rad_lane_gather }, { "lane_store_w32", "lane_store", "elem", "one source's rows into several lanes", @@ -6605,8 +6337,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGenLanes), NOTUNE, - nullptr, nullptr, r4d_rad_lane_store, nullptr, nullptr, nullptr, - nullptr }, + nullptr, nullptr, r4d_rad_lane_store }, { "randn_lanes_bf16", "randn_lanes", "elem", "a lane's rows from its seed's Philox normal stream", @@ -6614,8 +6345,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGenBf16), NOTUNE, - nullptr, nullptr, r4d_rad_randn_lanes, nullptr, nullptr, nullptr, - nullptr }, + nullptr, nullptr, r4d_rad_randn_lanes }, { "flow_euler_bf16", "flow_euler", "elem", "a flow-matching Euler step with guidance, preview and repaint", @@ -6623,8 +6353,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGenBf16), NOTUNE, - nullptr, nullptr, r4d_rad_flow_euler, nullptr, nullptr, nullptr, - nullptr }, + nullptr, nullptr, r4d_rad_flow_euler }, { "chan_affine_bf16", "chan_affine", "elem", "a per-channel affine from parameter lists", @@ -6632,8 +6361,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGenAffine), NOTUNE, - nullptr, nullptr, r4d_rad_chan_affine, nullptr, nullptr, nullptr, - nullptr }, + nullptr, nullptr, r4d_rad_chan_affine }, { "l2norm_chan_bf16", "l2norm_chan", "norm", "unit-L2 channel norm, scaled, optional silu: a wave a pixel", @@ -6641,8 +6369,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGenRows8), NOTUNE, - nullptr, nullptr, r4d_rad_l2norm_chan, nullptr, nullptr, nullptr, - nullptr }, + nullptr, nullptr, r4d_rad_l2norm_chan }, { "d2s_add_bf16", "d2s_add", "elem", "an upsampling shortcut added in", @@ -6650,8 +6377,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGenBf16), NOTUNE, - nullptr, nullptr, r4d_rad_d2s_add, nullptr, nullptr, nullptr, - nullptr }, + nullptr, nullptr, r4d_rad_d2s_add }, { "s2d_avg_add_bf16", "s2d_avg_add", "elem", "a downsampling shortcut added in", @@ -6659,8 +6385,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGenBf16), NOTUNE, - nullptr, nullptr, r4d_rad_s2d_avg_add, nullptr, nullptr, nullptr, - nullptr }, + nullptr, nullptr, r4d_rad_s2d_avg_add }, { "to_rgba8_bf16", "to_rgba8", "elem", "decoded pixels to bytes", @@ -6668,8 +6393,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGenBf16), NOTUNE, - nullptr, nullptr, r4d_rad_to_rgba8, nullptr, nullptr, nullptr, - nullptr }, + nullptr, nullptr, r4d_rad_to_rgba8 }, { "gelu_tanh_bf16", "gelu_tanh", "elem", "tanh gelu", @@ -6677,8 +6401,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGenRows8), NOTUNE, - nullptr, nullptr, r4d_rad_gelu_tanh, nullptr, nullptr, nullptr, - nullptr }, + nullptr, nullptr, r4d_rad_gelu_tanh }, { "scatter_add_rows_bf16", "scatter_add_rows", "elem", "x[idx[i]] += v[i]", @@ -6686,8 +6409,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGenRows8), NOTUNE, - nullptr, nullptr, r4d_rad_scatter_add_rows, nullptr, nullptr, nullptr, - nullptr }, + nullptr, nullptr, r4d_rad_scatter_add_rows }, { "conv2d_nhwc_bf16", "conv2d_nhwc", "conv", "an image convolution as an implicit GEMM over (tap, cin), the weight stored tap-major", @@ -6711,6 +6433,19 @@ static const RadPluginInfo kInfo = { "gfx1201", }; +/* r4d_record_dispatches' log, read by r4d_emit (r4d_emit.h). */ +const void** r4d_dispatch_log = nullptr; +int r4d_dispatch_cap = 0; +int r4d_dispatch_n = 0; + +extern "C" int r4d_record_dispatches(const void** fns, int cap) { + const int n = r4d_dispatch_n; + r4d_dispatch_log = fns; + r4d_dispatch_cap = fns ? cap : 0; + r4d_dispatch_n = 0; + return n; +} + extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; } extern "C" const RadPluginInfo* rad_plugin_info(void) { return &kInfo; } @@ -6723,17 +6458,14 @@ extern "C" const RadOpSchema* rad_kernel_schema_at(int i) { } /* ================================================================================ the host twins * - * A MACHINE WITHOUT PEER ACCESS RUNS THE SAME COLLECTIVES WITH THEIR MAILBOX IN HOST MEMORY. Every - * row that takes one of the three all-reduce inits has a twin: the same op, kernel, launch, fini, - * priority and tuning axes, `_host` appended to its name, its device.p2p == 1 turned into - * device.p2p == 0, and the init that puts every rank's exchange buffers in pinned host memory - * (r4d_ar_entry.hip, build). Exactly one of a pair matches any machine, so neither outranks the - * other, and a band report names which transport the step runs. + * Without peer access, the same collectives run with their mailbox in host memory. Every row using + * one of the three all-reduce inits gets a twin: same op, kernel, launch, fini, priority and tuning + * axes, `_host` appended to its name, device.p2p == 1 turned into device.p2p == 0, and the init + * that puts every rank's exchange buffers in pinned host memory (r4d_ar_entry.hip, build). Exactly + * one of a pair matches any machine. * - * DERIVED, NOT WRITTEN OUT, so a collective row added to the table above has its twin by being - * added and the two cannot drift: the transport is the only thing they differ in. A collective row - * that does not require device.p2p == 1 gets no twin, and r4d_selftest fails it for the missing - * constraint. */ + * Twins are derived, so they cannot drift from the table. A collective row that does not require + * device.p2p == 1 gets no twin, and r4d_selftest fails it. */ namespace { struct HostTwin { @@ -6808,23 +6540,20 @@ extern "C" const RadKernelInfo* rad_kernel_at(int i) { return &host_twins()[(size_t)(i - base)].info; } -/* WHICH ROWS TOUCH NOTHING BUT THEIR OPERANDS AND SCRATCH (rad_abi.h). Nothing on an R4D launch - * path allocates, and the exceptions are the kernels that keep something between launches on a - * stream -- arrival counters and split workspaces a file allocates once and keys on the stream, - * so that only the stream's own ordering keeps two launches from sharing them: +/* Which rows touch nothing but their operands and scratch (rad_abi.h). The exceptions keep state + * between launches keyed on the stream (arrival counters, split workspaces allocated once), so only + * the stream's ordering keeps two launches from sharing it: * * hc_* and mtp_enter r4d_hc_bf16.hip's mix counters, one block a stream * gemm_w4a8_tiled, the split tail's workspace and counters, one a (device, stream) * gemm_w8a8_tiled * 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_fp8a8_nt_m16's finisher counters are keyed on the stream and the output; * gemm_mxfp4a8_decode's split partial is the op's scratch and its arrival counters are keyed on the - * output alone, so no argument depends on the stream a pass is recorded or replayed on; and - * router_gemm_topk_scatter_bf16's arrival counter is its op instance's (taken at init, one a - * declared op and band). Two launches that could run at once never share any of them, so all three - * rows are concurrent. A row added with state of its own that the stream's order protects belongs - * in this list. */ + * 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 three + * rows are concurrent. A new row with stream-ordered state belongs in the list above. */ extern "C" int rad_kernel_concurrent(int i) { const RadKernelInfo* k = rad_kernel_at(i); if (!k) return 0; @@ -6837,33 +6566,46 @@ extern "C" int rad_kernel_concurrent(int i) { return 1; } -/* WHICH ROWS ARE COLLECTIVES (rad_abi.h): every row whose instance its init builds with the - * exchange buffers, peer flags and handshake of the all-reduce family -- the standalone all-reduces - * and gathers, and the norms and hc writes with one folded in -- and each one's `_host` twin, which - * exchanges through the pinned mailbox instead. Keyed on the init because that is what makes a row - * one: a kernel that reduces across ranks cannot run without the instance only these build. */ +/* Which rows are collectives (rad_abi.h): every row whose init builds the all-reduce family's + * exchange buffers, peer flags and handshake (standalone all-reduces and gathers, and norms and hc + * writes with one folded in), plus each `_host` twin. Keyed on the init, since a cross-rank kernel + * cannot run without the instance only these build. */ extern "C" int rad_kernel_collective(int i) { const RadKernelInfo* k = rad_kernel_at(i); if (!k || !k->init) return 0; const bool coll = host_init_for(k->init) != nullptr || k->init == r4d_rad_ar_host_init || k->init == r4d_rad_ar_ln_host_init || k->init == r4d_rad_ar_hc_wide_host_init; if (!coll) return 0; - /* The two-rank hc writes end the engine's link hold themselves, through `link_gate`, as soon as - * the peer's push has landed over P2P (RAD_LINK_ENDED); through the host mailbox they leave it - * to the engine. */ - return (k->launch == r4d_rad_ar_hc_write || k->launch == r4d_rad_ar_gather_hc_write) ? 2 : 1; + /* The rows that end the engine's link hold themselves, through `link_gate`, as soon as the + * peers' pushes have landed over P2P (RAD_LINK_ENDED); through the host mailbox they leave it + * to the engine (`in->host` keeps `early` 0, so the launch returns RAD_OK and the barrier + * release stands). + * + * Invariant: a launch joins this list only if its device kernel calls r4d_ar_link_landed on + * every path after its last handshake. A row answering 2 whose kernel does not decrement + * leaves the gate odd, and every yielding DMA list on that card waits forever. The one-shot + * family releases after its single handshake, the two-shot family after its second (its + * reduce is fused with the phase-2 push); the 3- and 8-rank entries pass no gate and answer + * 1. */ + static const RadLaunchFn kReleasing[] = { + r4d_rad_ar_hc_write, r4d_rad_ar_gather_hc_write, + r4d_rad_ar_oneshot_4rank_exact, r4d_rad_ar_twoshot_4rank_exact, + r4d_rad_ar_twoshot_4rank_ti8, r4d_rad_ar_gather_4rank, + r4d_rad_ar_hc_write_4rank, r4d_rad_ar_gather_hc_write_4rank, + }; + for (RadLaunchFn f : kReleasing) + if (k->launch == f) return 2; + return 1; } /* ------------------------------------------------------------------------ tuned config access * - * THE CHOSEN POINT ARRIVES AS ORDINARY PARAMETERS. The core resolved one instantiation of this - * kernel, picked a point in the space declared above -- from the tune cache, from RADIANCE_TUNE, - * or from each axis's own default -- and appended the choices to RadArgs::p. A launch reads `sk` - * with the same rad_args_geti() it reads `M` with. There is no variant index anywhere. + * The chosen point arrives as ordinary parameters: the core picks a point in the space above (from + * the tune cache, RADIANCE_TUNE, or each axis's default) and appends it to RadArgs::p, so a launch + * reads `sk` as it reads `M`. * - * These read the tables above for the fallback, so the default is defined ONCE. A cold caller - * (rad-kbench, a selftest) that supplies no tuned key gets exactly what an untuned install runs, - * which is what makes a checker's answer mean something about a deployment. */ + * The fallback comes from the tables above, so each default is defined once, and a caller that + * supplies no tuned key (rad-kbench, a selftest) runs what an untuned install runs. */ static int64_t tune_i(const RadArgs* a, const RadTunable* tab, int n, const char* key) { long long v = 0; if (rad_args_geti(a, key, &v)) return (int64_t)v; @@ -6881,10 +6623,8 @@ extern "C" void r4d_cfg_gemm(const RadArgs* a, R4dGemmCfg* out) { out->nt = TUNE(a, tGemmSkinny, "nt"); } -/* The tile axis names a COMPILED ARM, and (BM, BN) is a property of that arm rather than a second - * axis -- see the note at tGemmTiled. This is the map, and it is the only place it exists: the N - * constraint a call has to check is `N % BN`, and a wrong BN here would not fail, it would compute - * a wrong answer in silence. */ +/* Maps a compiled tile arm to its (BM, BN) (see tGemmTiled); the only copy of this map. A call + * checks `N % BN`, so a wrong BN here would silently compute a wrong answer. */ static void tile_bmbn(int arm, int prefill, R4dTileCfg* out) { struct Arm { int v, bm, bn; }; static const Arm tiled[] = { @@ -6904,9 +6644,8 @@ static void tile_bmbn(int arm, int prefill, R4dTileCfg* out) { const int n = prefill ? NELEM(pf) : NELEM(tiled); for (int i = 0; i < n; ++i) if (t[i].v == arm) { out->variant = arm; out->bm = t[i].bm; out->bn = t[i].bn; return; } - /* An arm the map does not know cannot be launched: fall to the default rather than guess a - * tile width the kernel was not compiled for. The loader already refuses a default outside - * its own value list, so arm 0 is always reachable. */ + /* An unknown arm falls back to the default rather than guessing a tile width. The loader + * refuses a default outside its value list, so arm 0 is always reachable. */ out->variant = 0; out->bm = 128; out->bn = 256; } diff --git a/libr4d/r4d_rowtopk_bf16.hip b/libr4d/r4d_rowtopk_bf16.hip index 5fbaea02..48641f71 100644 --- a/libr4d/r4d_rowtopk_bf16.hip +++ b/libr4d/r4d_rowtopk_bf16.hip @@ -1,86 +1,64 @@ // r4d_rowtopk_bf16.hip - r4d_rowtopk_bf16: exact per-row top-R of a wide bf16 matrix. // -// WHAT IT IS FOR. A quantised draft head produces coarse logits over a whole vocabulary shard and -// only the best few dozen of them are ever rescored exactly. Selecting those is not a GEMM -// problem, but doing it with a general top-k costs more than the GEMM saves: torch.topk over a -// 15520-wide candidate array measures 132 us at M=64 in three kernels (digit counts, within-K -// counts, gather), and over a full 124160-wide row it is several times that. +// Purpose: a quantised draft head produces coarse logits over a vocabulary shard, and only the +// best few dozen are rescored exactly. A general top-k costs more than that saves: torch.topk over +// a 15520-wide array takes 132 us at M=64 in three kernels, and several times that over a full +// 124160-wide row. // -// THE SHAPE IS TWO STAGES BECAUSE THE SCAN AND THE SELECTION WANT OPPOSITE THINGS. Reading the -// matrix wants thousands of waves in flight; the selection is a chain of dependent cross-lane -// steps, ~300 cycles a round, and running that chain thousands of times costs more than the read. -// Two simpler shapes are both far off that on a 15.9 MB matrix whose roofline is 25 us: +// Two stages, because scanning and selecting want opposite shapes. Reading the matrix wants +// thousands of waves in flight; selection is a chain of dependent cross-lane steps (~300 cycles a +// round), too costly to run thousands of times. On a 15.9 MB matrix with a 25 us roofline: // // 256-thread blocks, R=32 rounds, two barriers a round 75.6 us (chain, plus barriers) // one wave per chunk, R=32 rounds, no barrier 68.5 us (chain, or too few waves) // -// Neither is bandwidth-bound. So stage 1 runs MANY waves and a SHORT chain -- one wave per (row, -// chunk), keeping only the chunk's top-RC -- and stage 2 runs one wave per row over the nch*RC -// survivors with the full R-round chain, where there are only M chains in the whole launch. +// So stage 1 runs many waves with a short chain (one wave per (row, chunk), keeping the chunk's +// top-RC), and stage 2 runs one wave per row over the nch*RC survivors with the full R-round chain. // -// * A LANE KEEPS ITS OWN TOP-PT IN REGISTERS, SORTED. Insertion is guarded by a single compare -// against the tail, so the common element costs one instruction; only an element that actually -// places pays the branch-free shift. There is no LDS array of candidates. -// * A ROUND ONLY EVER REMOVES A LIST HEAD. The round winner is the head of exactly one lane's -// sorted list, so "remove it" is that lane shifting its own registers. A mask-and-rescan over -// a shared candidate array -- the obvious form -- re-reads every candidate each round; this -// reads none. -// * ONE WAVE PER BLOCK, so a round is five xor-butterfly steps and NO barrier. +// * A lane keeps its own top-PT in registers, sorted. Insertion is guarded by one compare +// against the tail, so most elements cost one instruction; only a placing element pays the +// branch-free shift. No LDS candidate array. +// * A round only removes a list head: the winner is the head of exactly one lane's list, so that +// lane shifts its own registers. Nothing is re-read per round. +// * One wave per block, so a round is five xor-butterfly steps and no barrier. // -// THE KEY IS ONE 64-BIT INTEGER, which is what makes a round a plain max. The high 32 bits are the -// float's order-preserving image (invert everything if negative, set the sign bit if not), the low -// 32 are ~index, so a larger key means a larger value and, on an exact tie, the LOWER column -- -// the tie rule a dense top-k over the row would give. The index in the low bits also makes every -// key distinct, which is what lets a round identify its winner by equality instead of carrying a -// position alongside the value. +// The key is one 64-bit integer, so a round is a plain max. The high 32 bits are the float's +// order-preserving image (invert all bits if negative, set the sign bit if not), the low 32 are +// ~index, so a larger key is a larger value and, on a tie, the lower column (a dense top-k's tie +// rule). The index also makes every key distinct, so a round identifies its winner by equality. // -// WHERE PT HAS TO BE BIG ENOUGH, AND WHERE IT BIT. A lane's top-PT filter loses a candidate when -// more than PT of the ones that matter land in that lane's slice, so PT is a statement about how -// the slice is chosen: +// PT bounds how many relevant candidates one lane's slice can hold: // -// * Stage 1 gives a lane every 32nd eight-column group, and PT must cover a whole VECTOR LOAD -- -// eight bf16 arrive at once, so PT=4 can lose a candidate to a single load. That is a real -// failure and not a conservative bound: PT=4 disagrees with torch.topk on smooth data while -// passing on tied data. PT=8 makes one load placeable in full, and beyond that a chunk would -// need nine of its own top-RC in one of 32 slices. -// * Stage 2's slice is NOT random. Stage 1 writes chunk-major, so at stride 32 with RC=32 lane -// 0 would receive the maximum of EVERY chunk -- exactly where the row's top-R concentrates -- -// and PT=8 then drops all but eight of them. That is the second way the filter can lose. Stage 2 -// therefore carries PT = 32 >= R: a lane can hold the entire answer, so no distribution of the -// candidates over lanes can lose one. It is exact by construction, not by argument. +// * Stage 1 gives a lane every 32nd eight-column group, and PT must cover a whole vector load: +// eight bf16 arrive at once, so PT=4 can lose a candidate to a single load (and does disagree +// with torch.topk on smooth data). PT=8 places one load in full; beyond that a chunk would need +// nine of its own top-RC in one of 32 slices. +// * Stage 2's slice is not random: stage 1 writes chunk-major, so at stride 32 with RC=32 lane 0 +// receives every chunk's maximum, exactly where the row's top-R concentrates. Stage 2 therefore +// uses PT = 32 >= R: one lane can hold the entire answer, so it is exact for any distribution. // -// RC IS THE ONE PLACE THE ANSWER CAN BE APPROXIMATE, and it is the caller's choice. A chunk hands -// on its own top-RC, so the row top-R survives unless MORE THAN RC of it falls in a single chunk. -// RC=R is exact for any data; smaller RC shortens stage 1's chain, which is what stage 1 costs, at -// a risk that falls off fast in the chunk count -- at R=32, RC=8 and 64 chunks it takes nine of -// the thirty-two in one sixty-fourth of the row. The caller that rescores its candidates exactly -// loses a candidate, not correctness, when that happens. +// RC is the only possible approximation, and the caller's choice. A chunk hands on its top-RC, so +// the row's top-R survives unless more than RC of it falls in one chunk. RC=R is exact for any +// data; a smaller RC shortens stage 1's chain at a risk that falls fast with the chunk count (at +// R=32, RC=8 and 64 chunks it takes nine of the 32 in one sixty-fourth of the row). A caller that +// rescores exactly then loses a candidate, not correctness. #include "r4d.h" #include "r4d_emit.h" -#include "r4d_emit.h" #include "r4d_gemm_args.h" #include "r4d_common.h" #include "r4d_fp8_wmma.h" #include "r4d_fp8_lm.h" #include #include -#include #define R4D_TOPK_WAVE 32 -#ifndef R4D_TOPK_PT1 -#define R4D_TOPK_PT1 8 // stage 1: >= the eight bf16 a lane loads in one step -#endif #define R4D_TOPK_PT2 32 // stage 2: >= R, so a lane can hold the whole answer typedef unsigned u4v_tk __attribute__((ext_vector_type(4))); typedef __attribute__((address_space(1))) const u4v_tk* r4d_tk_gv4; -#ifndef R4D_TOPK_WPB #define R4D_TOPK_WPB 8 // independent waves per block: one chunk each, no barrier between -#endif -#ifndef R4D_TOPK_UNROLL #define R4D_TOPK_UNROLL 4 // vector loads issued before any of them is consumed -#endif __device__ __forceinline__ unsigned long long tk_key(unsigned short bf, unsigned idx) { unsigned u = (unsigned)bf << 16; @@ -98,21 +76,19 @@ __device__ __forceinline__ int tk_idx(unsigned long long k) { return (int)(0xFFFFFFFFu - (unsigned)(k & 0xFFFFFFFFull)); } -// The larger of this lane's key and its partner's at lane ^ N, the partner read through DPP or -// permlanex16 rather than `__shfl_xor` -- see r4d_xor_lane. +// The larger of this lane's key and its partner's at lane ^ N, read through DPP or permlanex16 +// (see r4d_xor_lane). template __device__ __forceinline__ unsigned long long tk_xor_max(unsigned long long m) { const unsigned long long p = r4d_xor_lane_u64(m); return p > m ? p : m; } -// THE ONLY GUARD IN FRONT OF THE INSERT IS ITS OWN, ON THE KEY. A float guard -- one v_cmp_f32 -// against the list tail's value -- is a loss in stage 1, where making it a branch breaks the -// unrolled straight-line body that eight elements per vector load produce and costs about 18% at -// M=64 even on tied data. And it is wrong anywhere a NaN can arrive: the key orders a positive NaN -// above +inf and a negative one below -inf, while a float compare is false against everything, so -// a float guard drops what the key would keep and, once a NaN is the tail, drops every candidate -// after it. Every stage here and the merge rank on the key alone, so they agree on one order. +// The insert's only guard is its own key compare. A float guard against the tail's value costs +// ~18% at M=64 in stage 1 (a branch breaks the unrolled straight-line body), and it is wrong with +// NaN: the key orders a positive NaN above +inf and a negative one below -inf, while a float +// compare is false, so once a NaN is the tail every later candidate would be dropped. Every stage +// and the merge rank on the key alone, so they agree on one order. template __device__ __forceinline__ void tk_insert(unsigned long long* t, unsigned long long k) { if (k > t[PT - 1]) { @@ -126,8 +102,8 @@ __device__ __forceinline__ void tk_insert(unsigned long long* t, unsigned long l } } -// One reduction round over the wave. Every lane gets the winner; the one lane that owns it drops -// its head. No LDS and no barrier -- that is what one wave per block buys. +// One reduction round over the wave: every lane gets the winner and its owner drops its head. No +// LDS and no barrier. template __device__ __forceinline__ unsigned long long tk_round(unsigned long long* t) { unsigned long long m = t[0]; @@ -148,9 +124,8 @@ template __global__ __launch_bounds__(R4D_TOPK_WAVE * R4D_TOPK_WPB) void r4d_rowtopk_stage1_kernel( const unsigned short* __restrict__ Y, unsigned long long* __restrict__ P, int N, int RC, int NCH, int CH) { - // WPB independent waves in one block, each on its own chunk. They share nothing -- no LDS, no - // barrier -- and the only reason to group them is that a block of 32 threads spends the CU's - // workgroup slots, not its wave slots, and runs out of the former first. + // WPB independent waves per block, each on its own chunk, sharing nothing. Grouping them only + // matters because 32-thread blocks exhaust the CU's workgroup slots before its wave slots. const int m = blockIdx.y; const int c = blockIdx.x * R4D_TOPK_WPB + (int)(threadIdx.x >> 5); if (c >= NCH) return; @@ -164,10 +139,9 @@ __global__ __launch_bounds__(R4D_TOPK_WAVE * R4D_TOPK_WPB) void r4d_rowtopk_stag for (int q = 0; q < PT; q++) t[q] = 0ull; const unsigned short* row = Y + (size_t)m * N; - // Eight bf16 a lane a step: the wave then moves 512 contiguous bytes per issue, where a scalar - // ushort load would move 64 for the same instruction. UNROLL of them are issued before the - // first is consumed -- the insert chain is a register dependency and would otherwise let one - // memory latency stand between every load and the next. + // Eight bf16 per lane per load, so the wave moves 512 contiguous bytes per issue. UNROLL loads + // are issued before the first is consumed, since the insert chain would otherwise put a memory + // latency between consecutive loads. const int v0 = c0 >> 3, v1 = c1 >> 3; const int step = R4D_TOPK_WAVE * R4D_TOPK_UNROLL; int v = v0 + lane; @@ -206,17 +180,14 @@ __global__ __launch_bounds__(R4D_TOPK_WAVE * R4D_TOPK_WPB) void r4d_rowtopk_stag } } -// `off` is the first GLOBAL column this rank's plane stands for, and `OP` is the optional -// (id, value) pair plane an all-gather moves -- eight bytes an entry, an int32 id riding in the -// first float slot, which is the layout core/sample/sampler.h holds as buf_pairs_ and the -// same one the sampler's own vocab-parallel path gathers. Both are inert at off = 0 with OP null, -// and that is the single-rank launch unchanged to the bit. +// `off` is the first global column this rank's plane stands for, and `OP` the optional (id, value) +// pair plane an all-gather moves: eight bytes an entry, an int32 id in the first float slot, the +// layout core/sample/sampler.h holds as buf_pairs_. Both are inert at off = 0 with OP null, which +// is the single-rank launch bit for bit. // -// AN EMPTY SLOT IS NOT TOKEN `off`. A chunk that ran out of candidates leaves a zero key; OI has -// always written column 0 for it and keeps doing so, because adding the offset there would make a -// pad indistinguishable from this rank's first real token. The pair plane says -1 instead, which -// is the sentinel the merge drops -- and a sentinel rather than -INFINITY, because a masked logit -// legitimately takes that value. +// An empty slot is not token `off`. A chunk that ran out of candidates leaves a zero key; OI gets +// column 0 for it, without the offset, so a pad cannot look like this rank's first real token. The +// pair plane writes -1, the sentinel the merge drops (not -INFINITY, a valid masked logit). __global__ __launch_bounds__(R4D_TOPK_WAVE) void r4d_rowtopk_stage2_kernel( const unsigned long long* __restrict__ P, float* __restrict__ OV, int* __restrict__ OI, float* __restrict__ OP, int off, int R, int n) { @@ -227,18 +198,16 @@ __global__ __launch_bounds__(R4D_TOPK_WAVE) void r4d_rowtopk_stage2_kernel( #pragma unroll for (int q = 0; q < R4D_TOPK_PT2; q++) t[q] = 0ull; - // THE KEY DECIDES, NOT THE FLOAT, as in stage 1 -- see tk_insert. A chunk that handed on a NaN - // among its top-RC handed on one fewer real candidate, so dropping the NaN here can leave the row - // short of R, and the pad that fills the gap is what the merge reports as id -1. An empty slot's - // key is 0 and never places. + // The key decides, as in stage 1 (see tk_insert). A NaN a chunk handed on displaced a real + // candidate, so dropping it here can leave the row short of R; the pad filling the gap is what + // the merge reports as id -1. An empty slot's key is 0 and never places. const unsigned long long* p = P + (size_t)m * n; for (int i = lane; i < n; i += R4D_TOPK_WAVE) tk_insert(t, p[i]); for (int r = 0; r < R; r++) { const unsigned long long w = tk_round(t); if (lane == 0) { - // A chunk that ran out of candidates wrote a zero key, and a zero key must not read back as - // a real column: it is an empty slot and says so. + // A zero key is an empty slot, not a real column. const float v = w ? tk_val(w) : -INFINITY; OV[(size_t)m * R + r] = v; OI[(size_t)m * R + r] = w ? (int)tk_idx(w) + off : 0; @@ -252,43 +221,34 @@ __global__ __launch_bounds__(R4D_TOPK_WAVE) void r4d_rowtopk_stage2_kernel( } } -// Chunks are a multiple of eight columns so stage 1 stays on the vector load, and the last one is -// clamped to N rather than padded -- a padded tail would need a mask on every element. The caller -// sizes `partial` from this, so the rounding lives in one place. +// Chunks are a multiple of eight columns so stage 1 stays on the vector load; the last one is +// clamped to N rather than padded (a padded tail would need a mask per element). The caller sizes +// `partial` from r4d_rowtopk_bf16_chunks, so the rounding lives here only. +static int rowtopk_chunk_width(int N, int NCH) { + const int CH = ((N + NCH - 1) / NCH + 7) & ~7; + return CH < 8 ? 8 : CH; +} + int r4d_rowtopk_bf16_chunks(int N, int NCH) { - int CH = ((N + NCH - 1) / NCH + 7) & ~7; - if (CH < 8) CH = 8; + const int CH = rowtopk_chunk_width(N, NCH); return (N + CH - 1) / CH; } -void r4d_rowtopk_bf16(long y, long partial, long outv, long outi, - int M, int N, int R, int RC, int NCH, int PT1, long stream) { - r4d_rowtopk_bf16_sharded(y, partial, outv, outi, 0, M, N, R, RC, NCH, PT1, 0, stream); -} - -// The same top-R over a plane that is one rank's SLICE of a wider one: `off` is the first global -// column the slice stands for, and `outp` -- optional, 0 for none -- is the M*R (int32 id, float -// value) pair plane an all-gather moves so the ranks can agree on a global top-R without ever -// gathering the plane itself. It is a separate entry point, so the unsharded one keeps its -// signature. -/* The body takes a sink and RETURNS; the exported thrower keeps its signature. */ +// The top-R over one rank's slice of a wider plane: `off` is the slice's first global column, and +// `outp` (optional, 0 for none) is the M*R (int32 id, float value) pair plane an all-gather moves +// so ranks can agree on a global top-R without gathering the plane. static int rowtopk_bf16_sharded_emit(long y, long partial, long outv, long outi, long outp, int M, int N, int R, int RC, int NCH, int PT1, int off, - const R4dSink& sk) { + RadStream stream) { int emit_rc = RAD_OK; - if (M < 1 || N < 1) return -1; - if (N % 8) return -2; - // R <= PT2 is what makes stage 2 exact whatever the candidates look like; it is a real limit, - // not a tuning choice, so it is checked rather than clamped. - if (R < 1 || R > R4D_TOPK_PT2) - return -3; - if (RC < 1 || RC > PT1 * R4D_TOPK_WAVE) - return -4; - if (NCH < 1) return -5; - int CH = ((N + NCH - 1) / NCH + 7) & ~7; - if (CH < 8) CH = 8; + // R <= PT2 is what makes stage 2 exact for any candidates; a real limit, so checked, not + // clamped. + if (M < 1 || N < 1 || N % 8 || R < 1 || R > R4D_TOPK_PT2 || RC < 1 || + RC > PT1 * R4D_TOPK_WAVE || NCH < 1) + return R4D_NO(RAD_E_SHAPE); + const int CH = rowtopk_chunk_width(N, NCH); const int nch = (N + CH - 1) / CH; -#define R4D_TK_S1(PT) emit_rc = R4D_EMIT(sk, (r4d_rowtopk_stage1_kernel), \ +#define R4D_TK_S1(PT) emit_rc = R4D_EMIT(stream, (r4d_rowtopk_stage1_kernel), \ dim3((nch + R4D_TOPK_WPB - 1) / R4D_TOPK_WPB, M), \ dim3(R4D_TOPK_WAVE * R4D_TOPK_WPB), 0, \ (const unsigned short*)y, (unsigned long long*)partial, N, RC, nch, CH) @@ -297,38 +257,27 @@ static int rowtopk_bf16_sharded_emit(long y, long partial, long outv, long outi, case 4: R4D_TK_S1(4); break; case 8: R4D_TK_S1(8); break; case 16: R4D_TK_S1(16); break; - default: return -6; + default: return R4D_NO(RAD_E_INVAL); } #undef R4D_TK_S1 if (emit_rc != RAD_OK) return emit_rc; - return R4D_EMIT(sk, r4d_rowtopk_stage2_kernel, dim3(M), dim3(R4D_TOPK_WAVE), 0, + return R4D_EMIT(stream, r4d_rowtopk_stage2_kernel, dim3(M), dim3(R4D_TOPK_WAVE), 0, (const unsigned long long*)partial, (float*)outv, (int*)outi, (float*)outp, off, R, nch * RC); } -void r4d_rowtopk_bf16_sharded(long y, long partial, long outv, long outi, long outp, - int M, int N, int R, int RC, int NCH, int PT1, int off, - long stream) { - const int rc = rowtopk_bf16_sharded_emit(y, partial, outv, outi, outp, M, N, R, RC, NCH, PT1, - off, r4d_stream_sink((RadStream)(uintptr_t)stream)); - if (rc != RAD_OK) throw std::runtime_error("r4d rowtopk_bf16: refused or failed to launch"); -} - // ============================================================ the vocab-parallel merge // -// The other half of a sharded top-R. Each rank ran the two stages above over ITS OWN slice of the -// plane and wrote an [M, R, 2] pair plane -- an int32 global id beside a float value; an all-gather -// concatenated those into [M, W*R, 2] with rank r's at [r*R, (r+1)*R). This picks the R largest of -// the W*R and writes them in the same (idx, val) form stage 2 writes, so nothing downstream can -// tell which path produced them. +// The other half of a sharded top-R. Each rank ran the two stages over its own slice and wrote an +// [M, R, 2] pair plane (int32 global id, float value); an all-gather concatenated those into +// [M, W*R, 2] with rank r's at [r*R, (r+1)*R). This picks the R largest of the W*R and writes them +// in stage 2's (idx, val) form. // -// THE KEY IS THE SAME 64-BIT INTEGER, built from the float's bits rather than a bf16's, so a round -// is still a plain max and ties still break on the LOWER id -- which is what makes this equal to a -// top-R over the unsharded plane rather than merely close to it. A pad carries id -1 and is -// skipped: a sentinel, because -INFINITY is a value a masked logit legitimately takes. +// The key is the same 64-bit integer, built from the float's bits, so a round is a plain max and +// ties break on the lower id, which makes this equal to a top-R over the unsharded plane. A pad +// carries id -1 and is skipped (a sentinel, since -INFINITY is a legitimate masked logit). // -// One wave a row, W*R entries -- 32 at world 2 and R 16 -- so this is a launch with a rounding -// error attached, and its only real requirement is that it be exact. +// One wave per row over W*R entries (32 at world 2, R 16); its cost is its launch. __device__ __forceinline__ unsigned long long tk_key_f32(float v, unsigned id) { unsigned u = __float_as_uint(v); u = (u & 0x80000000u) ? ~u : (u | 0x80000000u); @@ -361,46 +310,29 @@ __global__ __launch_bounds__(R4D_TOPK_WAVE) void r4d_rowtopk_merge_kernel( } } -void r4d_rowtopk_merge(long gathered, long outv, long outi, int M, int R, int W, long stream) { - if (M < 1 || R < 1 || W < 1) throw std::runtime_error("r4d rowtopk_merge: M, R and W must be >= 1"); - // R <= PT2 is what makes this exact whatever the candidates look like -- a lane can hold the - // whole answer -- so it is checked rather than clamped, the same as stage 2's. - if (R > R4D_TOPK_PT2) throw std::runtime_error("r4d rowtopk_merge: R must be 1..32"); - hipLaunchKernelGGL(r4d_rowtopk_merge_kernel, dim3(M), dim3(R4D_TOPK_WAVE), 0, - (hipStream_t)stream, (const float*)gathered, (float*)outv, (int*)outi, - R, W * R); -} - // ============================================================== logit_rerank // -// THE EXACT SECOND HALF OF A COARSE TOP-R, which is what this file's header already says the top-R -// is for: "only the best few dozen of them are ever rescored exactly". The coarse head proposes R -// candidates a row and this scores those R -- and only those R -- against the FULL-PRECISION head, -// then re-sorts on the exact values. A draft round reads R rows of the weight instead of all of -// it: 40 KB a row against 318 MB. On Qwen3.8-Flash-Next the 2-bit head accepts 4 to 8 points -// below the exact one, and that gap is what this closes. +// The exact second half of a coarse top-R: the coarse head proposes R candidates per row, and this +// scores only those against the full-precision head, then re-sorts on the exact values. A draft +// round reads R weight rows instead of the whole head (40 KB a row against 318 MB). On +// Qwen3.8-Flash-Next the 2-bit head's acceptance is 4 to 8 points below the exact head's, and this +// closes that gap. // -// ONE BLOCK A ROW, THE WAVES SPREAD OVER THE CANDIDATES. A wave walks K with a lane stride and -// folds with the same five xor-butterfly steps the selection uses, so the reduction order is a fixed -// function of the shape and the score is reproducible. Then wave 0 runs the ORDINARY top-R chain -// over the R scores -- one lane a candidate, R <= PT2 -- so the tie rule is tk_key_f32's and is the -// same rule row_topk and row_topk_merge break on. A tie inside a shard and a tie between shards -// therefore resolve alike, which is the property that makes the merged answer exact. +// One block per row, waves spread over the candidates. A wave walks K with a lane stride and folds +// with the same five xor-butterfly steps, so the reduction order is a fixed function of the shape. +// Wave 0 then runs the ordinary top-R chain over the R scores (one lane a candidate, R <= PT2), +// so ties break by tk_key_f32's rule, as in row_topk and row_topk_merge; ties within and between +// shards resolve alike, which keeps the merged answer exact. // -// A CANDIDATE OUTSIDE THIS RANK'S ROWS IS A PAD. `voff` is the shard's first column and the ids -// are GLOBAL, because that is what row_topk reports; under vocab-parallel drafting every id a rank -// is handed came from its own plane, and the guard is for a caller that mixes them. +// A candidate outside this rank's rows is a pad. `voff` is the shard's first column and ids are +// global, as row_topk reports them; under vocab-parallel drafting a rank only gets its own ids, and +// the guard is for a caller that mixes them. // -// I8 READS THE INT8 HEAD logits_gemm_i8 stores (r4d.i8lm.r128): the same row -- K codes, then the -// row's own bf16 scale per 128 columns in its tail -- with each code an int8 value rather than an -// E4M3 one. The drafter's rescoring reads whichever head the trunk's logits GEMM reads, so a model -// with an int8 head needs this form or its lm_head has no device reader here. +// I8 reads the int8 head logits_gemm_i8 stores (r4d.i8lm.r128): the same row (K codes, then the +// row's bf16 scale per 128 columns in its tail) with int8 codes instead of E4M3. The drafter +// rescores against whichever head the trunk's logits GEMM reads, so an int8 head needs this form. #define R4D_RERANK_WPB 8 // waves a block: 256 threads, and R <= 32 so a wave takes <= 4 -__device__ __forceinline__ float tk_bf2f(unsigned short b) { - return __uint_as_float((unsigned)b << 16); -} - template __global__ __launch_bounds__(R4D_TOPK_WAVE * R4D_RERANK_WPB) void r4d_logit_rerank_kernel( const unsigned short* __restrict__ X, const int* __restrict__ IN, @@ -420,15 +352,15 @@ __global__ __launch_bounds__(R4D_TOPK_WAVE * R4D_RERANK_WPB) void r4d_logit_rera const bool own = gid >= 0 && loc >= 0 && loc < nv; float acc = 0.0f; if (own) { - /* THE STORED ROW, exactly as logits_gemm_fp8 reads it (r4d_fp8_lm.h): K E4M3 codes then - * K/128 bf16 block scales in the row's own tail. A lane owns a strided subset of the - * columns and applies each column's own block scale locally, so the fold below is a plain - * sum and the order is fixed by the lane count alone. */ + /* The stored row, as logits_gemm_fp8 reads it (r4d_fp8_lm.h): K E4M3 codes then K/128 bf16 + * block scales in the row's tail. A lane owns a strided subset of columns and applies each + * column's block scale locally, so the fold is a plain sum whose order depends only on the + * lane count. */ const unsigned char* const wr = W + (size_t)loc * w_ld; const unsigned short* const sr = (const unsigned short*)(wr + K); for (long k = lane; k < K; k += R4D_TOPK_WAVE) { const float c = I8 ? (float)(int8_t)wr[k] : r4d_fp8::e4m3((uint32_t)wr[k]); - acc = fmaf(c * r4d_fp8::bscale(sr[k / 128]), tk_bf2f(xr[k]), acc); + acc = fmaf(c * r4d_fp8::bscale(sr[k / 128]), bf16_to_f32(xr[k]), acc); } acc = r4d_wave_sum(acc); } @@ -460,53 +392,41 @@ __global__ __launch_bounds__(R4D_TOPK_WAVE * R4D_RERANK_WPB) void r4d_logit_rera } static int logit_rerank_emit(long x, long idx_in, long head, long outi, long outv, long outp, - int M, int R, long K, long voff, long nv, const R4dSink& sk, - bool i8 = false) { + int M, int R, long K, long voff, long nv, RadStream stream, + bool i8) { const long w_ld = r4d_fp8::lm_row_bytes(K); - if (M < 1 || R < 1 || K < 1 || nv < 1) return -1; - // R <= PT2 is what makes the re-sort exact whatever the scores look like -- one lane holds the - // whole answer -- so it is checked rather than clamped, the same as the merge's. - if (R > R4D_TOPK_PT2) return -2; + // R <= PT2 makes the re-sort exact for any scores (one lane holds the whole answer), so it is + // checked, not clamped. + if (M < 1 || R < 1 || K < 1 || nv < 1 || R > R4D_TOPK_PT2) return R4D_NO(RAD_E_SHAPE); #define R4D_RERANK_EMIT(I8) \ - R4D_EMIT(sk, r4d_logit_rerank_kernel, dim3(M), dim3(R4D_TOPK_WAVE * R4D_RERANK_WPB), 0, \ - (const unsigned short*)x, (const int*)idx_in, (const unsigned char*)head, (int*)outi, \ + R4D_EMIT(stream, r4d_logit_rerank_kernel, dim3(M), dim3(R4D_TOPK_WAVE * R4D_RERANK_WPB), \ + 0, (const unsigned short*)x, (const int*)idx_in, (const unsigned char*)head, \ + (int*)outi, \ (float*)outv, (float*)outp, R, K, voff, nv, w_ld) const int rc = i8 ? R4D_RERANK_EMIT(true) : R4D_RERANK_EMIT(false); #undef R4D_RERANK_EMIT return rc; } -void r4d_logit_rerank(long x, long idx_in, long head, long outi, long outv, long outp, - int M, int R, long K, long voff, long nv, long stream) { - if (logit_rerank_emit(x, idx_in, head, outi, outv, outp, M, R, K, voff, nv, - r4d_stream_sink((RadStream)(uintptr_t)stream)) != RAD_OK) - throw std::runtime_error("r4d logit_rerank: refused or failed to launch"); -} - // ============================================================== the plugin ABI entry points // -// The operand reader and the split law are r4d_gemm_args.h. See libr4d/r4d_args.h for why there is -// no adapter directory between the core and these launches. +// The operand reader and the split law are in r4d_gemm_args.h. See libr4d/r4d_args.h on why there +// is no adapter layer. /* ------------------------------------------------------------------ row top-k */ enum { T_X = 0, T_IDX, T_VAL, T_PAIRS }; -/* R > 32 is refused here, not by a constraint: libr4d's row says R <= 1024 in both its predicate - * and its prose, and the entry point throws above R4D_TOPK_PT2 == 32, calling that "a real limit, - * not a tuning choice". The constraint table transcribes what libr4d wrote and this is the - * per-call half that makes the pair sound. */ +/* Also the scratch sizer's reader, which runs at declare with no tensors and no constraint check, so + * it repeats the row's R <= 32. */ static int topk_params(const RadArgs* a, const RadTensor** x, const RadTensor** idx, const RadTensor** val, long long* M, long long* N, long long* R, int* RC, int* NCH, int* PT1) { *x = r4d_opt(a, T_X); *idx = r4d_opt(a, T_IDX); *val = r4d_opt(a, T_VAL); - /* THE SCRATCH SIZER RUNS AT DECLARE, WHERE THERE ARE NO TENSORS. It is the same entry point as - * the launch, so reading the geometry out of `x` alone would make sizing the partial plane - * ahead of a step fail with "invalid argument" -- which reads as a refusal by the kernel and - * is actually an absent operand. `M` and `N` are declared parameters of this op for exactly - * this reason (spec §2.1), so they are the fallback; when the tensor IS present it still wins, - * because a band ceiling is an upper bound and the tensor is the row count of the call. */ + /* The scratch sizer runs at declare, with no tensors, through this same function. `M` and `N` + * are declared parameters of this op for that reason (spec §2.1) and serve as the fallback; + * when the tensor is present it wins, since a band ceiling is only an upper bound. */ if (*x) { if ((*x)->rank != 2 || !r4d_contig(*x)) return R4D_NO(RAD_E_STRIDE); *M = (*x)->shape[0]; @@ -528,8 +448,8 @@ static int topk_params(const RadArgs* a, *RC = c->rc > 0 ? c->rc : (int)*R; if (*RC < (int)*R) return R4D_NO(RAD_E_INVAL); /* a chunk must keep at least R */ if (*RC > *PT1 * 32) return R4D_NO(RAD_E_SHAPE); - /* NCH is a REQUEST for a chunk COUNT. 0 means "one chunk per 2048 columns, at least one", - * which is the shape the MoE router this kernel serves actually runs. */ + /* NCH is a requested chunk count. 0 means one chunk per 2048 columns, at least one, the shape + * the MoE router this kernel serves runs. */ *NCH = c->nch > 0 ? c->nch : (int)((*N + 2047) / 2048); if (*NCH < 1) *NCH = 1; return RAD_OK; @@ -541,14 +461,12 @@ extern "C" int64_t r4d_rad_rowtopk_scratch(const RadArgs* a) { int RC, NCH, PT1; int rc = topk_params(a, &x, &idx, &val, &M, &N, &R, &RC, &NCH, &PT1); if (rc != RAD_OK) return rc; - /* The chunk width is rounded up to a multiple of eight columns inside libr4d, so the count is - * asked for rather than recomputed -- "the caller sizes `partial` from this, so the rounding - * lives in one place". */ + /* The chunk width is rounded inside libr4d, so the count is asked for, not recomputed. */ const int nch = r4d_rowtopk_bf16_chunks((int)N, NCH); return (int64_t)M * nch * RC * (int64_t)sizeof(unsigned long long); } -static int rad_rowtopk_body(const RadArgs* a, const R4dSink& sk) { +extern "C" int r4d_rad_rowtopk(const RadArgs* a, RadStream stream) { const RadTensor *x, *idx, *val; long long M, N, R; int RC, NCH, PT1; @@ -561,9 +479,9 @@ static int rad_rowtopk_body(const RadArgs* a, const R4dSink& sk) { const int64_t need = (int64_t)M * nch * RC * (int64_t)sizeof(unsigned long long); if (!a->scratch || a->scratch_bytes < need) return R4D_NO(RAD_E_SCRATCH); - /* The vocab-parallel form, and both halves of it are optional: `vocab_off` shifts the columns - * reported so a rank's slice reports global ids, and `pairs` is the [M, R, 2] plane an - * all_gather moves. Absent and zero is the single-rank launch, bit for bit. */ + /* The vocab-parallel form; both halves optional. `vocab_off` shifts the reported columns to + * global ids, and `pairs` is the [M, R, 2] plane an all_gather moves. Absent and zero is the + * single-rank launch, bit for bit. */ const RadTensor* pairs = r4d_opt(a, T_PAIRS); const long long off = r4d_geti_or(a, "vocab_off", 0); if (off < 0) return R4D_NO(RAD_E_SHAPE); @@ -572,19 +490,15 @@ static int rad_rowtopk_body(const RadArgs* a, const R4dSink& sk) { if (r4d_numel(pairs) < M * R * 2) return R4D_NO(RAD_E_SHAPE); } - if (rowtopk_bf16_sharded_emit(r4d_addr(x), (long)(uintptr_t)a->scratch, r4d_addr(val), - r4d_addr(idx), pairs ? r4d_addr(pairs) : 0, - (int)M, (int)N, (int)R, RC, NCH, PT1, (int)off, sk) != RAD_OK) - return R4D_NO(RAD_E_DEVICE); - return RAD_OK; + return rowtopk_bf16_sharded_emit(r4d_addr(x), (long)(uintptr_t)a->scratch, r4d_addr(val), + r4d_addr(idx), pairs ? r4d_addr(pairs) : 0, + (int)M, (int)N, (int)R, RC, NCH, PT1, (int)off, stream); } -R4D_ENTRY(r4d_rad_rowtopk, rad_rowtopk_body) /* ------------------------------------------------------------------ row_topk_merge * - * The R largest of the all-gathered per-rank candidate sets. No variants and no scratch: it is one - * wave a row over world_size * R pairs -- 32 of them at world 2 and R 16 -- so what it costs is its - * launch, and the only thing that matters about it is that it be exact. */ + * The R largest of the all-gathered per-rank candidate sets. No variants and no scratch: one wave + * per row over world_size * R pairs, so its cost is its launch; it only has to be exact. */ extern "C" int r4d_rad_rowtopk_merge(const RadArgs* a, RadStream s) { const RadTensor* g = r4d_opt(a, 0); const RadTensor* idx = r4d_opt(a, 1); @@ -593,12 +507,9 @@ extern "C" int r4d_rad_rowtopk_merge(const RadArgs* a, RadStream s) { if (g->dtype != RAD_F32 || !r4d_contig(g)) return R4D_NO(RAD_E_STRIDE); if (!r4d_contig(idx) || !r4d_contig(val)) return R4D_NO(RAD_E_STRIDE); - /* M COMES OFF THE OPERAND, not off the parameter. `M` is declared as a RANGE -- a band ceiling - * -- and what the parameter table carries is that ceiling, not the row count of this call; the - * gathered plane is row-narrowed to the rows the step actually has. Reading the parameter - * sized the checks below at the band and refused every real issue, which is the same trap - * `topk_params` above documents for the top-R's own scratch hook. The parameter is still the - * fallback, for a sizing query made before there are tensors. */ + /* M comes from the operand: the `M` parameter is a band ceiling, and the gathered plane is + * narrowed to the step's rows, so sizing the checks by the parameter would refuse real calls. + * The parameter is the fallback for a sizing query made before there are tensors. */ const long long M = (g->rank >= 1) ? g->shape[0] : r4d_geti_or(a, "M", 0); const long long R = r4d_geti_or(a, "R", 0); const long long W = r4d_geti_or(a, "world_size", 0); @@ -607,16 +518,15 @@ extern "C" int r4d_rad_rowtopk_merge(const RadArgs* a, RadStream s) { if (r4d_numel(g) < M * W * R * 2) return R4D_NO(RAD_E_SHAPE); if (r4d_numel(idx) < M * R || r4d_numel(val) < M * R) return R4D_NO(RAD_E_SHAPE); - R4D_TRY("rowtopk_merge", - r4d_rowtopk_merge(r4d_addr(g), r4d_addr(val), r4d_addr(idx), (int)M, (int)R, (int)W, - (long)(uintptr_t)s)); - return RAD_OK; + /* R <= PT2 makes the merge exact for any candidates (one lane can hold the whole answer). */ + return R4D_EMIT(s, r4d_rowtopk_merge_kernel, dim3((unsigned)M), + dim3(R4D_TOPK_WAVE), 0, (const float*)g->data, (float*)val->data, + (int*)idx->data, (int)R, (int)(W * R)); } -/* `M` and the candidate count come off the OPERANDS for the reason rowtopk_merge's do: `M` is a - * band ceiling and a step narrows it. `n_vocab` is THIS RANK'S rows of the head, which is what - * makes the ownership guard a shard test rather than a vocabulary one. */ -static int rad_logit_rerank(const RadArgs* a, const R4dSink& sk, bool i8) { +/* `M` and the candidate count come from the operands, as in rowtopk_merge: `M` is a band ceiling. + * `n_vocab` is this rank's rows of the head, so the ownership guard is a shard test. */ +static int rad_logit_rerank(const RadArgs* a, RadStream stream, bool i8) { const RadTensor* x = r4d_opt(a, 0); const RadTensor* w = r4d_opt(a, 1); const RadTensor* in = r4d_opt(a, 2); @@ -625,13 +535,11 @@ static int rad_logit_rerank(const RadArgs* a, const R4dSink& sk, bool i8) { const RadTensor* pr = r4d_opt(a, 5); if (!x || !in || !w || !idx || !val) return R4D_NO(RAD_E_INVAL); if (x->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); - /* THE DECLARED DTYPE IS WHAT ARRIVES, and for this weight it is the bf16 the trunk - * declared -- the E4M3 plane is the STORED form. logits_gemm_fp8 says the same thing - * about the stored WIDTH: it cannot be checked here and is derived by the same rule - * the layout hook used, and what guarantees the two agree is the engine's layout-tag - * check, which refuses a container laid out for any other row before a byte of it - * moves. So the head is accepted at either spelling and read as r4d.fp8lm.b128 -- or, for - * the int8 form, as r4d.i8lm.r128. */ + /* The declared dtype arrives, which for this weight is the trunk's bf16; the E4M3 (or int8) + * plane is the stored form. Its stored width cannot be checked here and follows the layout + * hook's rule; the engine's layout-tag check guarantees agreement by refusing a container laid + * out for another row. So the head is accepted at either spelling and read as r4d.fp8lm.b128, + * or r4d.i8lm.r128 for the int8 form. */ if (w->dtype != (i8 ? RAD_I8 : RAD_F8E4M3) && w->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); if (in->dtype != RAD_I32 || idx->dtype != RAD_I32 || val->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); @@ -652,18 +560,14 @@ static int rad_logit_rerank(const RadArgs* a, const R4dSink& sk, bool i8) { if (pr && r4d_numel(pr) < M * R * 2) return R4D_NO(RAD_E_SHAPE); if (K % 128) return R4D_NO(RAD_E_SHAPE); /* the scale block; lm_row_bytes assumes it */ - if (logit_rerank_emit(r4d_addr(x), r4d_addr(in), r4d_addr(w), r4d_addr(idx), r4d_addr(val), - pr ? r4d_addr(pr) : 0, (int)M, (int)R, (long)K, (long)voff, (long)NV, - sk, i8) != RAD_OK) - return R4D_NO(RAD_E_DEVICE); - return RAD_OK; + return logit_rerank_emit(r4d_addr(x), r4d_addr(in), r4d_addr(w), r4d_addr(idx), r4d_addr(val), + pr ? r4d_addr(pr) : 0, (int)M, (int)R, (long)K, (long)voff, (long)NV, + stream, i8); } -static int rad_logit_rerank_body(const RadArgs* a, const R4dSink& sk) { - return rad_logit_rerank(a, sk, false); +extern "C" int r4d_rad_logit_rerank(const RadArgs* a, RadStream stream) { + return rad_logit_rerank(a, stream, false); } -R4D_ENTRY(r4d_rad_logit_rerank, rad_logit_rerank_body) -static int rad_logit_rerank_i8_body(const RadArgs* a, const R4dSink& sk) { - return rad_logit_rerank(a, sk, true); +extern "C" int r4d_rad_logit_rerank_i8(const RadArgs* a, RadStream stream) { + return rad_logit_rerank(a, stream, true); } -R4D_ENTRY(r4d_rad_logit_rerank_i8, rad_logit_rerank_i8_body) diff --git a/libr4d/r4d_sample_chain_f32.hip b/libr4d/r4d_sample_chain_f32.hip index cc2a9a36..e96752ae 100644 --- a/libr4d/r4d_sample_chain_f32.hip +++ b/libr4d/r4d_sample_chain_f32.hip @@ -1,41 +1,31 @@ -// SAMPLING ON THE DEVICE: the whole vLLM chain for one position in one workgroup -- temperature, -// softmax, top_k, top_p, min_p, renormalise, draw -- plus the second draw and the accept -// probability a greedy-draft rejection-sampling verify needs. +// Sampling on the device: the vLLM chain for one position in one workgroup (temperature, softmax, +// top_k, top_p, min_p, renormalise, draw), plus the second draw and accept probability that a +// greedy-draft rejection-sampling verify needs. // -// WHY THE LIBRARY NEEDS IT. The head this feeds leaves a [vocab][M] plane in VRAM with the -// vocabulary ROW-SPLIT across ranks. A host sampler therefore needs every card's band brought back -// and then a softmax and a nucleus cut over 248K entries per position, on the dispatch thread, in -// the middle of the decode loop. Sampling where the logits already are costs one gather of the -// other ranks' bands and nothing else. +// The head leaves a [vocab][M] plane in VRAM, row-split across ranks. A host sampler would need +// every band copied back and a softmax and nucleus cut over 248K entries per position on the +// dispatch thread; on the device it costs one gather of the other ranks' bands. // -// WHY IT RETURNS THREE THINGS. Greedy speculation accepts a drafted token when it equals the -// target's argmax, and that rule is only correct at temperature 0. With the target sampling, the -// correct rule is rejection sampling -- and with a GREEDY draft the proposal is a point mass, so it -// is accepted with probability p(x) under the target's own FILTERED distribution. On rejection the -// emitted token must come from the residual, which for a point-mass proposal is the same -// distribution with the proposed token removed and the rest renormalised. One pass produces all -// three, and the host then walks the positions with its own uniforms without coming back. +// Three outputs: accepting a draft token when it equals the target's argmax is only correct at +// temperature 0. With a sampling target the rule is rejection sampling, and a greedy draft is a +// point mass, so it is accepted with probability p(x) under the target's filtered distribution. On +// rejection the token comes from the residual, which for a point mass is the same distribution +// with the proposal removed and renormalised. One pass produces all three; the host then walks the +// positions with its own uniforms. Acceptance is lower than greedy-against-greedy, which is the +// cost of emitting the target's true distribution. // -// Stated plainly, because it is a cost and not a bug: acceptance FALLS relative to -// greedy-against-greedy, because a proposal the target agrees with is still only accepted with -// probability p(x). That is the price of emitting the target's true distribution. +// The order is vLLM's; reordering changes which tokens survive. Temperature 0 is a real path, not +// special-cased by the caller, so it uses the argmax kernel's tie-break (lowest id wins) and a +// temperature-0 request matches a greedy run. // -// THE ORDER IS vLLM'S and it is not a detail: reordering changes which tokens survive. The -// temperature-0 path is kept as a real path rather than special-cased by the caller, so a -// deterministic request gets the SAME tie-break (lowest id wins) an argmax would; the two must -// agree or a temperature-0 request stops matching a greedy run. +// One block owns one position and walks the vocabulary several times; after the first pass the +// plane is L2-resident, which beats staging at this vocabulary size. The top_k and top_p cuts are +// four radix passes each over 256 buckets of a monotone key, giving the k-th largest probability +// and the nucleus threshold exactly without sorting. // -// ONE BLOCK OWNS ONE POSITION and walks the vocabulary several times. Every pass reads the same -// plane, so after the first it is L2-resident; at this vocabulary that beats any staging. The -// top_k and top_p cuts are four radix passes each over the 256 buckets of a monotone key -- the -// k-th largest probability and the nucleus threshold EXACTLY, without sorting the vocabulary. -// -// NO GEOMETRY OF ITS OWN. The kernel body takes the logits plane through explicit row and column -// strides, so nothing in it is specific to a model. The entry point takes flat scalar arguments -// and returns a negative code rather than throwing, for the reason given in r4d_gemm_fp8a8.hip. -// -// `f32` in the name is the LOGITS dtype, which is what discriminates this entry point: the head -// writes f32 and a bf16-logits variant would be a different instantiation beside this one. +// The kernel reads the logits through explicit row and column strides, so nothing is +// model-specific. The entry point takes flat scalars and returns a negative code instead of +// throwing, for the reason given in r4d_gemm_fp8a8.hip. `f32` in the name is the logits dtype. #include "r4d.h" #include "r4d_fp8_args.h" @@ -50,16 +40,14 @@ typedef R4DSpecDraw SpecDraw; constexpr uint32_t kThr = 256; -// A monotone map from float to uint32, so a radix pass on the bits orders the values. The same trick -// the indexer's top-k uses; written for the general case even though probabilities are non-negative, -// so it cannot surprise anyone who reuses it. +// A monotone map from float to uint32, so a radix pass over the bits orders the values. Written for +// the general case although probabilities are non-negative. __device__ __forceinline__ uint32_t mono(float v) { const uint32_t u = __float_as_uint(v); return (u & 0x80000000u) ? ~u : (u | 0x80000000u); } -// Everything the block shares, declared once. Shared memory inside a nested scope is a portability -// question nobody should have to ask while reading a sampler. +// Everything the block shares, declared once at kernel scope. struct Shared { float red[kThr]; // the general-purpose reduction buffer uint32_t red_i[kThr]; // ...and the ids that ride along with it @@ -100,11 +88,7 @@ __device__ __forceinline__ float reduce_sum(Shared& sh, float v) { // ---- the kernel --------------------------------------------------------------------------------- // -// One block owns one position and walks the vocabulary several times. Every pass reads the same -// plane, so after the first it is L2-resident; at this vocabulary that beats any staging. -// -// The order is vLLM's — temperature, softmax, top_k, top_p, min_p, renormalise, sample — and it is -// not a detail: reordering changes which tokens survive. +// See the file header for the chain order and the multi-pass structure. __global__ __launch_bounds__(kThr) void sample_kernel( const float* __restrict__ logits, uint32_t vocab, uint32_t row_stride, uint32_t col_stride, const uint32_t* __restrict__ query, const float* __restrict__ u, float temperature, @@ -123,11 +107,8 @@ __global__ __launch_bounds__(kThr) void sample_kernel( return best; }()); - // ---- temperature 0 is greedy, and stays a real path ------------------------------------------ - // - // Kept here rather than special-cased by the caller so that a request asking for determinism gets - // it from the same code, with the SAME tie-break the argmax kernel uses (lowest id wins) — the two - // must agree or a temperature-0 request stops matching a greedy run. + // ---- temperature 0 is greedy, and stays a real path, with the argmax kernel's tie-break + // (lowest id wins) so it matches a greedy run. if (!(temperature > 0.0f)) { float bv = -INFINITY; uint32_t bi = 0xFFFFFFFFu; @@ -149,8 +130,7 @@ __global__ __launch_bounds__(kThr) void sample_kernel( __syncthreads(); } if (tid == 0) { - // A row of NaNs beats nothing and leaves the reduction at its seed, which is not a token; - // token 0 is then as good an answer as any and is at least one. + // An all-NaN row leaves the reduction at its seed, which is not a token; emit token 0. const uint32_t g = sh.red_i[0] < vocab ? sh.red_i[0] : 0u; out[pos].tok = g; out[pos].tok_excl = g; @@ -168,8 +148,8 @@ __global__ __launch_bounds__(kThr) void sample_kernel( // ---- top_k, as an exact threshold on the monotone key ---------------------------------------- // - // Four radix passes narrowing one byte at a time, counting tokens. That is the k-th largest - // probability exactly, without sorting the vocabulary. + // Four radix passes narrowing one byte at a time, counting tokens: the k-th largest probability + // exactly, without sorting. uint32_t k_key = 0u; if (top_k > 0 && top_k < vocab) { if (tid == 0) sh.prefix = 0u; @@ -200,10 +180,10 @@ __global__ __launch_bounds__(kThr) void sample_kernel( // ---- top_p, the same passes accumulating MASS ------------------------------------------------ // - // Descend the buckets summing probability until the nucleus target is reached; the bucket that - // crosses it holds the threshold and the next pass narrows inside it. Ties AT the threshold are - // all kept, which can overshoot top_p by the mass of the tie — the alternative is inventing an - // order among equal probabilities. + // Descend the buckets summing probability until the nucleus target is reached; the crossing + // bucket holds the threshold and the next pass narrows inside it. Ties at the threshold are all + // kept, which can overshoot top_p by the tie's mass, rather than inventing an order among equal + // probabilities. uint32_t p_key = 0u; if (top_p < 1.0f) { if (tid == 0) sh.prefix = 0u; @@ -265,21 +245,17 @@ __global__ __launch_bounds__(kThr) void sample_kernel( // ---- inverse CDF, in two stages --------------------------------------------------------------- // - // CONTIGUOUS slices, not the strided ones every other loop here uses, and that is the whole - // correctness argument. An inverse CDF walks the distribution in some order, and any fixed order - // samples correctly — but only ASCENDING TOKEN ID makes the answer a property of the uniform - // rather than of the block size. Strided slices put token 256 second; a host reference, another - // implementation, or this kernel at a different kThr would all disagree about which token a given - // draw selects. Contiguous slices make the per-thread prefix the id prefix, so they agree. + // Contiguous slices, unlike the strided ones elsewhere here, for correctness: any fixed order + // samples correctly, but only ascending token id makes the result a function of the uniform + // alone and not of the block size, so a host reference or another kThr picks the same token. // - // Each thread sums its own range, thread 0 finds which range the draw lands in, that thread - // rescans it. Exact, and no sort. Every thread reaches both calls, so the barriers are uniform. + // Each thread sums its own range, thread 0 finds the range the draw lands in, and that thread + // rescans it. Exact, no sort. Every thread reaches both calls, so the barriers are uniform. // - // ONLY A RANGE WITH MASS CAN BE CHOSEN, and only a token with mass inside it. A range holding - // no kept token satisfies `acc + 0 >= want` whenever the draw is 0 or float drift has left the - // walk a hair short, and rescanning it finds nothing, which would emit 0xFFFFFFFF as a token. - // So empty ranges are passed over, the fall-through is the last range that has mass, and - // inside it the fall-through is the last token that has mass. `total > 0` guarantees one exists. + // Only a range with mass, and a token with mass inside it, can be chosen. An empty range + // satisfies `acc + 0 >= want` when the draw is 0 or float drift leaves the walk short, and + // rescanning it would emit 0xFFFFFFFF. So empty ranges are skipped, the fall-through is the last + // range with mass, and within it the last token with mass; `total > 0` guarantees one exists. const uint32_t chunk = (vocab + kThr - 1) / kThr; const uint32_t lo = tid * chunk; const uint32_t hi = lo + chunk < vocab ? lo + chunk : vocab; @@ -321,8 +297,8 @@ __global__ __launch_bounds__(kThr) void sample_kernel( acc += p; if (acc >= want) { sh.pick = v; break; } } - // Float drift can leave the walk a hair short at the very top of the range; the last token - // with mass in this range is the right answer there, not token 0. + // Float drift can leave the walk just short at the top of the range; the last token with + // mass is the answer there. if (sh.pick == 0xFFFFFFFFu) sh.pick = last; } __syncthreads(); @@ -344,18 +320,15 @@ __global__ __launch_bounds__(kThr) void sample_kernel( } // namespace // `logits` is the head's plane, addressed as `logits[pos*col_stride + v*row_stride]`, so either -// layout the head produces is read without a transpose. +// head layout is read without a transpose. // -// `query[i]` is the token the draft proposed for position i, or 0xFFFFFFFF where there is none (the -// last position of a verify block, which has no proposal to accept); the whole pointer may be 0. -// `u` holds TWO uniforms a position in [0,1), for `tok` and `tok_excl`; the accept draw stays on the -// host, which is where the seed lives. +// `query[i]` is the draft's proposal for position i, or 0xFFFFFFFF where there is none (the last +// position of a verify block); the pointer may be 0. `u` holds two uniforms per position in [0,1), +// for `tok` and `tok_excl`; the accept draw stays on the host, which owns the seed. // -// `n_vocab` is the FULL vocabulary. On a vocab-parallel rank the caller gathers the other bands -// first, because a nucleus over half a distribution is not a nucleus -- and that gather is the -// caller's, not this kernel's. +// `n_vocab` is the full vocabulary: a vocab-parallel caller gathers the other bands first. // -// Returns 0, or a negative code. +// Returns 0, -4 for a failed launch, or another negative code for arguments it refuses. extern "C" int r4d_sample_chain_f32(long logits, long query, long u, long out, int M, int n_vocab, int row_stride, int col_stride, float temperature, float top_p, int top_k, float min_p, @@ -374,8 +347,8 @@ extern "C" int r4d_sample_chain_f32(long logits, long query, long u, long out, // ============================================================== the plugin ABI entry points // -// The shared operand reader is r4d_fp8_args.h. See libr4d/r4d_args.h for why there is no adapter -// directory between the core and these launches. +// The shared operand reader is r4d_fp8_args.h. See libr4d/r4d_args.h on why there is no adapter +// layer. /* ================================================================== the device sampler */ extern "C" int r4d_rad_sample_chain(const RadArgs* a, RadStream s) { @@ -387,14 +360,13 @@ extern "C" int r4d_rad_sample_chain(const RadArgs* a, RadStream s) { if (lg->rank != 2) return R4D_NO(RAD_E_SHAPE); const long long M = lg->shape[0], V = lg->shape[1]; if (M < 1 || V < 1) return R4D_NO(RAD_E_SHAPE); - /* TWO uniforms a position -- one for the draw and one for the exclusive draw. Checked because a - * caller that supplies M of them reads past the end of its own buffer, on a kernel whose whole - * purpose is that the host does not have to look at the result. */ + /* Two uniforms per position, one for each draw; a caller supplying M would read past its own + * buffer. */ if (r4d_numel(u) < 2 * M) return R4D_NO(RAD_E_SHAPE); if (r4d_numel(dr) < M) return R4D_NO(RAD_E_SHAPE); if (qy && r4d_numel(qy) < M) return R4D_NO(RAD_E_SHAPE); - /* The strides ARE the interface here: the head writes either [M][V] or [V][M] and this kernel - * reads both without a transpose. So they are taken from the tensor rather than assumed. */ + /* The head writes [M][V] or [V][M], and the kernel reads both, so the strides come from the + * tensor. */ const long long rs = lg->stride[1], cs = lg->stride[0]; if (rs < 1 || cs < 1) return R4D_NO(RAD_E_STRIDE); @@ -408,5 +380,5 @@ extern "C" int r4d_rad_sample_chain(const RadArgs* a, RadStream s) { (int)M, (int)V, (int)rs, (int)cs, (float)temp, (float)topp, (int)topk, (float)minp, (long)(uintptr_t)s); - return e == 0 ? RAD_OK : RAD_E_SHAPE; + return e == 0 ? RAD_OK : R4D_NO(e == -4 ? RAD_E_DEVICE : RAD_E_SHAPE); } diff --git a/libr4d/r4d_sample_stages_f32.hip b/libr4d/r4d_sample_stages_f32.hip index eda985a5..c6543014 100644 --- a/libr4d/r4d_sample_stages_f32.hip +++ b/libr4d/r4d_sample_stages_f32.hip @@ -1,49 +1,36 @@ -// docs/OPS.md's DECOMPOSED sampler chain, on device. Not r4d_sample_chain_f32 -- that is one -// workgroup doing temperature, softmax, top_k, top_p, min_p and the draw in vLLM's fixed order, and -// it is the right kernel when the order is fixed. It is the wrong kernel for this engine: the -// chain the core issues is eleven ops it composes per request (core/sample/sampler.h), with -// penalties, DRY, a grammar bitmask, locally-typical and XTC stages the fused one does not have and -// with stages a request may skip. "Fusion is a selection, not a compiler pass" (spec §2.3) cuts -// both ways: a library that ships only the fused form forces the fusion. +// docs/OPS.md's decomposed sampler chain, on the device. r4d_sample_chain_f32 does temperature, +// softmax, top_k, top_p, min_p and the draw in one workgroup in vLLM's fixed order. This engine's +// chain is eleven ops composed per request (core/sample/sampler.h), with penalties, DRY, a grammar +// bitmask, locally-typical and XTC stages the fused kernel lacks, and stages a request may skip. +// Since fusion is a selection (spec §2.3), both exist: this unit runs a served request's sampler; +// r4d_sample_chain_f32 serves the speculative-verify path and its three outputs. // -// So both exist. This unit is what makes a served request's sampler run on the card at all; -// r4d_sample_chain_f32 stays for the speculative-verify path, which needs its three outputs. +// Every scalar is per row: `params` is an array of RadSampleParams, one row per sampled position, +// uploaded once a step. The struct is included from abi/rad_sample.h rather than restated, since it +// is a wire format between the core and this library. // -// ============================== EVERY SCALAR IS PER ROW ============================== +// What is exact, and why. libref is the oracle (spec §17), and two samplers that disagree on one +// candidate's survival emit different tokens, which compounds: // -// `params` is an array of RadSampleParams, one row per sampled position, uploaded once a step. It -// is abi/rad_sample.h's struct, INCLUDED rather than restated, because it is a WIRE FORMAT between -// the core and this library and a silent disagreement is a sampler reading `top_p` out of `min_p`. +// * The top-k is exact, without ref's O(k*n_vocab) repeated-maximum scan: eight radix passes over +// a monotone 32-bit key, four for the k-th largest logit and four over the token id to break a +// tie at that logit by the lower id (ref's rule), then a bitonic sort of the k survivors, since +// every later stage assumes descending order. // -// ============================== WHAT IS EXACT AND WHY ============================== +// * The sequential stages stay sequential: `top_p` accumulates a cumulative probability in f32 in +// candidate order and `sample_pick` walks an inverse CDF the same way. A parallel prefix sum +// rounds differently and would flip a candidate near the cut. Both run on one thread over at +// most a few thousand candidates. // -// libref is the oracle (spec §17) and a sampler is the one place where "close" is worthless: -// two implementations that disagree on one candidate's survival produce different TOKENS, and the -// difference compounds. So: +// * The draw is the specified one: splitmix64 over (seed * golden + pos), top 24 bits as a float +// in [0,1), fixed by rad_sample.h so a host reference, the device and a rerun agree. // -// * THE TOP-K IS EXACT, and it is not ref's O(k*n_vocab) repeated-maximum scan either. Eight -// radix passes over a monotone 32-bit key: four to find the k-th largest logit, four more over -// the token id to break a tie at that logit by the LOWER id -- which is ref's tie rule -- and -// then one bitonic sort of the k survivors, because every stage after this one assumes -// descending order. Exact, deterministic, and nine reads of the row instead of a thousand. +// * expf / logf / fabsf are the accurate forms, not __expf, because ref uses libm. // -// * THE SEQUENTIAL STAGES STAY SEQUENTIAL. `top_p` accumulates a cumulative probability in f32 -// in candidate order and `sample_pick` walks an inverse CDF the same way. A parallel prefix -// sum would be a different rounding, so a candidate near the cut would survive in one -// implementation and not the other. Both run on one thread over at most a couple of thousand -// candidates, which costs nothing next to the vocabulary passes around them. -// -// * THE DRAW IS THE SPECIFIED ONE. splitmix64 over (seed * golden + pos), top 24 bits as a float -// in [0,1) -- rad_sample.h fixes it so that a host reference, a device kernel and a rerun -// produce the same stream. Restated here, bit for bit. -// -// * expf / logf / fabsf ARE THE ACCURATE FORMS, not __expf. Ref takes libm and these are -// compared against it. -// -// A DROPPED CANDIDATE IS index -1, value -infinity, and the buffers never shrink. Kept candidates -// stay where they are, in descending order, so a later stage may stop at the first hole or skip it; -// these skip. `cand_val` carries LOGITS and each narrowing stage takes its own softmax over the -// live set, which is what keeps the stages composable in any order. +// A dropped candidate is index -1, value -infinity, and the buffers never shrink. Kept candidates +// stay in place in descending order, so a later stage may stop at the first hole or skip it (these +// skip). `cand_val` carries logits, and each narrowing stage takes its own softmax over the live +// set, so the stages compose in any order. #include "r4d.h" #include "r4d_args.h" @@ -51,10 +38,8 @@ #include -// THE PARAMS ROW IS THE ENGINE'S STRUCT, not a restatement of it. Two independent declarations of -// one wire format drift, and the drift is silent: a sampler reading `top_p` out of `min_p` -// produces text, not an error. A kernel library that can include the ABI header has no reason to -// keep a second declaration and a field-by-field static_assert to police it. +// The params row is the engine's struct, included rather than redeclared: two declarations of one +// wire format drift silently (a sampler reading `top_p` out of `min_p` still produces text). #include "rad_sample.h" namespace { @@ -63,34 +48,29 @@ constexpr uint32_t kWave = 32; constexpr uint32_t kThreads = 256; constexpr uint32_t kWaves = kThreads / kWave; -// THE VOCABULARY SCAN GETS ITS OWN WIDTH, and it is the only stage that needs one. Every kernel -// below `topk_kernel` reads a CANDIDATE set -- a thousand or two words -- where 256 threads is -// already more than the work; `topk_kernel` reads the whole row, 124160 floats a row on this -// model, and at 256 threads that is 117.6 us a step for 3.97 MB -- 34 GB/s on a -// part that streams 620. It is not bandwidth: one block a row is eight blocks on a 64-CU card, -// and 256 threads is two waves a SIMD, which cannot keep enough loads in flight to cover the -// latency of even one CU. 1024 threads is eight waves a SIMD on the same one block a row. +// The vocabulary scan gets its own width. Every kernel after `topk_kernel` reads a candidate set +// of a thousand or two words, where 256 threads is plenty; `topk_kernel` reads the whole row +// (124160 floats on this model). At 256 threads that took 117.6 us a step for 3.97 MB, 34 GB/s on +// a part that streams 620: one block per row is eight blocks on a 64-CU card, and two waves per +// SIMD cannot keep enough loads in flight. 1024 threads is eight waves per SIMD on the same grid. // -// IT DOES NOT CHANGE A BIT, and that is a property of this kernel rather than of the file. The -// scan reduces with max over a packed (key, ~id) word and the select counts histogram bins -- both -// commutative and associative, so the answer does not depend on how the row was cut up. The -// narrowing stages below are NOT like this: `sum_block` folds lds[0..kWaves) in wave order and a -// float sum is not associative, so widening THOSE would move the last bits of top_p and min_p. -// That is why this is a second constant and not a larger `kThreads`. -/* Four times kThreads, for the reason argmax_kernel's header gives: the grid is one workgroup a - * row whatever happens, so the only knob left is how many loads that workgroup has in flight. */ +// It changes no bit, a property of this kernel: the scan reduces with max over a packed (key, ~id) +// word and the select counts histogram bins, both associative. The narrowing stages are not: +// `sum_block` folds lds[0..kWaves) in wave order and a float sum is not associative, so widening +// them would move the last bits of top_p and min_p. Hence a second constant, not a larger +// kThreads. argmax_kernel uses the same width for the same reason. constexpr uint32_t kArgmaxThreads = 1024; constexpr uint32_t kTopkThreads = 1024; constexpr uint32_t kTopkWaves = kTopkThreads / kWave; -// The largest candidate width this unit sorts. The bitonic network runs in LDS over a -// power-of-two padding, so the bound is LDS: 4096 x 8 bytes = 32 KiB, half the 64 KiB a workgroup -// may have. The engine declares 1024 (core/sample/sampler.h sizes it from max_num_seqs), so this -// is four doublings of headroom; the shim refuses anything wider rather than truncating a set. +// The largest candidate width this unit sorts. The bitonic network runs in LDS over a power-of-two +// padding, so the bound is 4096 x 8 bytes = 32 KiB, half a workgroup's 64 KiB. The engine declares +// 1024 (core/sample/sampler.h sizes it from max_num_seqs); the shim refuses anything wider rather +// than truncating a set. constexpr uint32_t kMaxCand = 4096; // ---------------------------------------------------------------------------- the params row -// One declaration, the engine's. See the note at the include. +// The engine's declaration; see the note at the include. using SP = RadSampleParams; enum { @@ -113,16 +93,16 @@ __device__ __forceinline__ float uniform01(uint64_t seed, uint64_t pos) { return (float)(uint32_t)(z >> 40) * (1.0f / 16777216.0f); } -// A float's ORDER-PRESERVING 32-bit key. Flipping the sign bit of a positive and every bit of a -// negative makes unsigned comparison agree with float comparison, which is what lets a radix select -// work on logits at all. -infinity maps to 0, so a dropped candidate sorts last without a branch. +// A float's order-preserving 32-bit key: flip the sign bit of a positive and every bit of a +// negative, so unsigned comparison matches float comparison. -infinity maps to 0, so a dropped +// candidate sorts last without a branch. __device__ __forceinline__ uint32_t fkey(float f) { const uint32_t u = __builtin_bit_cast(uint32_t, f); return (u & 0x80000000u) ? ~u : (u | 0x80000000u); } -// The wave's largest (key, ~index), by an xor butterfly on r4d_xor_lane's exchange. A maximum of -// integers has one answer in any order. +// The wave's largest (key, ~index), by an xor butterfly on r4d_xor_lane's exchange. An integer max +// is order-independent. __device__ __forceinline__ unsigned long long wave_max_u64(unsigned long long b) { unsigned long long o; o = r4d_xor_lane_u64<16>(b); if (o > b) b = o; @@ -158,8 +138,8 @@ __device__ __forceinline__ float block_max(float v, float* lds) { } // ---------------------------------------------------------------------------- sample_temp -// ref_sample_temp. temp <= 0 leaves the row alone: greedy is `sample_argmax`, and a temperature of -// zero quietly meaning something else is how a sampler chain becomes unreadable. +// ref_sample_temp. temp <= 0 leaves the row alone: greedy is `sample_argmax`, and a temperature of +// zero silently meaning something else would make the chain unreadable. __global__ __launch_bounds__(kThreads) void temp_kernel( float* __restrict__ lg, const SP* __restrict__ sp, uint32_t n_vocab, uint32_t lg_ld) { const uint32_t m = blockIdx.x; @@ -172,10 +152,9 @@ __global__ __launch_bounds__(kThreads) void temp_kernel( } // ---------------------------------------------------------------------------- sample_mask -// ref_sample_mask. A SET BIT MEANS ALLOWED -- a grammar produces the admissible set, and the mask -// is that set rather than its complement. Word w bit b covers token 32w + b, least significant -// first. `mask_row` is -1 for an unconstrained sequence, which is why the plane is shared and -// shorter than M. +// ref_sample_mask. A set bit means allowed: the mask is the grammar's admissible set. Word w bit b +// covers token 32w + b, least significant first. `mask_row` is -1 for an unconstrained sequence, +// which is why the plane is shared and shorter than M. __global__ __launch_bounds__(kThreads) void mask_kernel( float* __restrict__ lg, const SP* __restrict__ sp, const uint32_t* __restrict__ bm, uint32_t n_vocab, uint32_t lg_ld, uint32_t words, int32_t mask_rows) { @@ -196,19 +175,17 @@ __global__ __launch_bounds__(kThreads) void mask_kernel( // frequency logit -= count * freq // presence logit -= pres (once per distinct token) // -// The repetition penalty being multiplicative and sign-dependent is the part everyone gets wrong: -// dividing a negative logit would make it larger. +// The repetition penalty is multiplicative and sign-dependent: dividing a negative logit would make +// it larger. // -// PARALLEL OVER THE HISTORY AND STILL RACE-FREE, which is worth stating because it looks like a -// scatter. Only the FIRST occurrence of a token updates it, so every distinct token has exactly -// one writing thread; two threads writing different tokens do not collide. That is the same -// property that makes ref's `first` test necessary, used for a second purpose. +// Parallel over the history and still race-free: only the first occurrence of a token updates it, +// so each distinct token has exactly one writing thread (the same `first` test ref needs anyway). // -// History ids are GLOBAL and the row is this rank's shard: a token's column is its id less +// History ids are global and the row is this rank's shard: a token's column is its id minus // `voff`, and a token outside the shard is another rank's to penalise. -// The window both history stages read, ref's hist_window: the row's own row of the plane, clamped, -// then the TAIL `last_n` long. last_n 0 turns the stage off for the row (false); negative keeps +// The window both history stages read, ref's hist_window: the row's own span of the plane, clamped, +// then its last `last_n` tokens. last_n 0 disables the stage for the row (false); negative keeps // the whole span. __device__ __forceinline__ bool hist_window(const SP& p, int32_t last_n, uint32_t hmax, int32_t* ho_out, int32_t* hl_out) { @@ -262,23 +239,22 @@ __global__ __launch_bounds__(kThreads) void penalties_kernel( } // ---------------------------------------------------------------------------- sample_dry -// ref_sample_dry, which is llama.cpp's DRY: every token that would EXTEND a suffix of the window -// that has occurred before is penalised ONCE, by multiplier * base^(L - allowed) for the LONGEST -// repeat L it would extend, repeats capped at the row's dry_rep_limit, and a position the optional -// `brk` plane marks -- a whole sequence breaker -- is never penalised. +// ref_sample_dry, which is llama.cpp's DRY: every token that would extend a suffix of the window +// that occurred before is penalised once, by multiplier * base^(L - allowed) for the longest repeat +// L it would extend, with repeats capped at the row's dry_rep_limit; a position the optional `brk` +// plane marks (a sequence breaker) is never penalised. // -// ONE BLOCK A ROW, TWO PHASES, AND NO ATOMICS. Phase one is parallel over the earlier positions j: -// each thread measures how long a suffix of the window also ends at j and leaves it in LDS, zero -// where the continuation after j is exempt or another rank's. Phase two picks, for every -// continuation token, ONE representative position -- its longest repeat, the earliest on a tie -- -// and only that thread writes the token's logit. A token therefore has exactly one writer and one -// subtraction, which is both llama.cpp's rule and what keeps the answer independent of thread -// order; summing a penalty per position, or an atomic sum, would give neither. +// One block per row, two phases, no atomics. Phase one is parallel over earlier positions j: each +// thread measures how long a suffix of the window also ends at j and stores it in LDS (zero where +// the continuation after j is exempt or another rank's). Phase two picks, for each continuation +// token, one representative position (its longest repeat, earliest on a tie), and only that thread +// writes the token's logit. One writer and one subtraction per token is llama.cpp's rule and makes +// the result independent of thread order; a per-position or atomic sum would give neither. // -// The cost is quadratic only in a history that really is repetitive: phase one's match loop exits -// on the first mismatch, and phase two scans only for positions whose repeat already qualifies. -// The penalty is formed by repeated multiplication stopping short of overflow, exactly as ref -// forms it, so the two agree to the bit. +// The cost is quadratic only for a genuinely repetitive history: phase one's match loop exits at +// the first mismatch, and phase two only scans for positions that already qualify. The penalty is +// formed by repeated multiplication stopping short of overflow, as ref forms it, so the two agree +// to the bit. __device__ __forceinline__ float dry_penalty(float multiplier, float base, int32_t e) { float pen = multiplier; if (base == 1.0f) return pen; @@ -297,7 +273,7 @@ __global__ __launch_bounds__(kThreads) void dry_kernel( extern __shared__ uint16_t len[]; const uint32_t m = blockIdx.x; const SP p = sp[m]; - // Every test below reads only the row, so the whole block leaves together. + // Every test below reads only the row's params, so the whole block leaves together. if (!(p.flags & SP_DRY) || !(p.dry_multiplier > 0.0f)) return; const int32_t allowed = p.dry_allowed_length > 0 ? p.dry_allowed_length : 2; @@ -339,24 +315,20 @@ __global__ __launch_bounds__(kThreads) void dry_kernel( } // ---------------------------------------------------------------------------- sample_argmax -// ref_sample_argmax. Greedy, TIES TO THE LOWER TOKEN ID -- the same rule the top-k selection uses, -// so a greedy step and a top-1 step cannot disagree. Packing (key, ~id) into one 64-bit word makes -// that tie rule fall out of a plain unsigned max reduction. +// ref_sample_argmax. Greedy, ties to the lower token id (the top-k selection's rule, so a greedy +// step and a top-1 step agree). Packing (key, ~id) into one 64-bit word makes that tie rule a plain +// unsigned max. // -// ONE WORKGROUP A ROW, AND IT STAYS THAT WAY -- so the row has to be read WIDE. A greedy step -// samples one row, so the grid is one workgroup and the other 31 CUs are idle no matter what. At -// Qwen3.8-Flash-Next's 248320-entry vocabulary that one workgroup reads 993 KB, and at 256 threads -// of scalar loads it took 170 us to do it -- 5.8 GB/s, which is not a bandwidth number, it is a -// not-enough-loads-in-flight number. Four times the threads and a float4 load each is 15.5 us at -// 64 GB/s, an eleven-fold cut for the same single workgroup and the same one dispatch. +// One workgroup per row, so the row is read wide. A greedy step samples one row, so the grid is one +// workgroup regardless. At a 248320-entry vocabulary (993 KB), 256 threads of scalar loads took +// 170 us (5.8 GB/s, too few loads in flight); 4x the threads with float4 loads take 15.5 us. // -// SPLITTING THE ROW ACROSS WORKGROUPS IS FASTER AND STILL NOT WORTH IT. A two-stage form over 128 -// partials measures 7.3 us, but it needs a scratch plane through the ABI and a second launch, and -// this tree's per-dispatch floor is ~4.5 us -- so the split lands at ~12 us against this 15.5 and -// costs an operand for the difference. +// Splitting the row across workgroups is faster (7.3 us over 128 partials) but needs an ABI scratch +// plane and a second launch, and the per-dispatch floor of ~4.5 us brings it to ~12 us, not worth +// an extra operand. // -// The vector path needs the ROW aligned, which is the base and the pitch together; `VEC` is chosen -// by the launcher and the scalar body is the fallback, not a legacy path. +// The vector path needs the row aligned (base and pitch together); the launcher chooses `VEC`, and +// the scalar body is the fallback. template __global__ __launch_bounds__(TH) void argmax_kernel( const float* __restrict__ lg, int32_t* __restrict__ tok, uint32_t n_vocab, uint32_t lg_ld) { @@ -381,7 +353,7 @@ __global__ __launch_bounds__(TH) void argmax_kernel( e = ((unsigned long long)fkey(v.w) << 32) | (unsigned long long)(~(i + 3u)); if (e > best) best = e; } - /* The <4 entries a vocabulary that is not a multiple of four leaves over. */ + /* The up to 3 entries left when the vocabulary is not a multiple of four. */ for (uint32_t i = (n4 << 2) + threadIdx.x; i < n_vocab; i += TH) { const unsigned long long e = ((unsigned long long)fkey(row[i]) << 32) | (unsigned long long)(~i); @@ -405,29 +377,27 @@ __global__ __launch_bounds__(TH) void argmax_kernel( // ---------------------------------------------------------------------------- sample_topk // -// THE RADIX SELECT. Four passes over the row, most significant byte first, narrowing a prefix of -// the monotone key until the k-th largest is pinned exactly. `remaining` is how many of the k are -// still unaccounted for once every strictly-larger prefix has been counted; at the end it is how -// many of the elements EQUAL to the threshold belong in the set. +// The radix select: four passes over the row, most significant byte first, narrowing a prefix of +// the monotone key until the k-th largest is pinned exactly. `remaining` is how many of the k are +// still owed once every strictly larger prefix is counted; at the end it is how many elements equal +// to the threshold belong in the set. // -// Then, ONLY WHEN THE TIE GROUP IS BIGGER THAN THE SET IS OWED, four more passes over the token -// id, restricted to that group, to find which of them -- -// the LOWEST ids, ref's rule. Ids are unique, so `idx <= I` takes exactly the right number and -// there is no second tie to break. -// DESC selects on the LOGIT KEY and walks the bins from 255 down; ASC selects on the TOKEN ID and -// walks them from 0 up. `gate` is the tie group the ASC pass is restricted to -- only elements -// whose key equals it take part -- and is ignored by the DESC pass, which sees the whole row. +// Only when the tie group is larger than what is owed, four more passes over the token id within +// that group find which of them: the lowest ids, ref's rule. Ids are unique, so `idx <= I` takes +// exactly the right number. // -// FOUR AT A TIME, AND THE DIGIT FROM A SCAN RATHER THAN A WALK. The row is one workgroup's to read, -// so how many bytes each load instruction carries is what the pass runs at; a float4 is four times -// what a float is for the same wait, and the guard is the shape's, as in the top-1 path below. -// And a digit chosen by ONE thread walking the 256 bins keeps 1023 waiting at the barrier, four -// times a select: the bins' running sums in the walk's direction (a suffix sum for DESC, a -// prefix sum for ASC) are a DPP scan a wave and one add across the eight waves, and the bin the walk -// stops at is the one whose running sum first reaches `remaining` -- exactly one, because the sums -// are monotone -- with `cum` the sum before it. A walk that never stops ends on the last bin with -// every bin counted, and so does this. Counts are integers, so it is the same digit and the same -// `cum`. `scan` holds 256 words and `wt` eight. +// DESC selects on the logit key and walks the bins from 255 down; ASC selects on the token id and +// walks from 0 up. `gate` is the tie group the ASC pass is restricted to (only elements whose key +// equals it count); the DESC pass ignores it and sees the whole row. +// +// Loads are float4 where the shape allows (as in the top-1 path below), since bytes per load +// instruction set the pass's speed. The digit comes from a scan rather than one thread walking 256 +// bins while 1023 wait: the bins' running sums in the walk's direction (suffix for DESC, prefix for +// ASC) are a DPP scan per wave plus one add across the eight waves, and the chosen bin is the one +// whose running sum first reaches `remaining` (exactly one, as the sums are monotone), with `cum` +// the sum before it. A walk that never stops ends on the last bin with every bin counted, and so +// does this. Counts are integers, so the digit and `cum` match the walk. `scan` holds 256 words and +// `wt` eight. template __device__ uint32_t radix_select(const float* __restrict__ row, uint32_t n, uint32_t gate, uint32_t rank, uint32_t* hist, uint32_t* scan, uint32_t* wt, @@ -507,9 +477,8 @@ __global__ __launch_bounds__(kTopkThreads) void topk_kernel( int32_t* __restrict__ oi = ci + (size_t)m * ci_ld; float* __restrict__ ov = cv + (size_t)m * cv_ld; - // A GREEDY ROW HAS NO CANDIDATES: its token is sample_argmax's, and in a mixed batch every - // stage after this one skips it. Holes, written without reading the row -- the vocabulary - // pass a greedy row would otherwise cost is the whole price of this kernel. The test reads + // A greedy row has no candidates: its token is sample_argmax's, and every later stage skips it. + // Holes are written without reading the row, avoiding this kernel's whole cost. The test reads // only the row's params, so the whole block leaves together. if (sp[m].flags & SP_GREEDY) { uint32_t* __restrict__ gp = pr ? pr + (size_t)m * pr_ld : nullptr; @@ -524,29 +493,24 @@ __global__ __launch_bounds__(kTopkThreads) void topk_kernel( return; } - // A row's own top_k, clamped to the buffer AND to the vocabulary. 0 or negative means the - // whole candidate width, which is what a request that set no top_k asks for. + // The row's own top_k, clamped to the buffer and to the vocabulary. 0 or negative means the + // whole candidate width (a request that set no top_k). uint32_t k = (uint32_t)(sp[m].top_k > 0 ? sp[m].top_k : (int32_t)n_cand); if (k > n_cand) k = n_cand; if (k > n_vocab) k = n_vocab; - // TOP-1 IS AN ARGMAX AND DOES NOT NEED THE SELECT. A greedy row over a split vocabulary - // arrives here at k = 1 and not at sample_argmax -- core/sample/sampler.cpp stages it that way - // so the merge can turn this rank's local index into a global one -- and the general path then - // spends EIGHT passes over the vocabulary and a bitonic sort of the whole candidate width to - // find a single element -- on the 27B at tp 2 that is 896 us a step, 2.7% of decode, for one - // maximum. The packed (key, ~id) word below is the one argmax_kernel reduces, so the two - // agree by construction, and its tie rule IS the select's tie rule -- see both comments above. + // Top-1 is an argmax and needs no select. A greedy row over a split vocabulary arrives here at + // k = 1, not at sample_argmax (core/sample/sampler.cpp stages it so the merge can map this + // rank's local index to a global one), and the general path would spend eight vocabulary passes + // and a full bitonic sort on one element (896 us a step on the 27B at tp 2). The packed + // (key, ~id) word is argmax_kernel's, so the two agree, and its tie rule is the select's. uint32_t got; if (k == 1) { unsigned long long best = 0; - // FOUR AT A TIME while the row and the pointer allow it. A thread that loads one float an - // iteration issues one 4-byte request and then waits on it; the scan is latency-bound (see - // kTopkThreads), so what it needs is more bytes in flight per instruction, and a float4 is - // four times as many for the same wait. The guard is the shape's, not the loop's: `row` - // moves by lg_ld between rows, so a row is 16-byte aligned only when the base and the - // stride both are, and n_vocab need not be a multiple of four. When either fails this - // falls back to the scalar form, which is what a vocabulary that is not 4-aligned gets. + // Four at a time where the row and pointer allow: the scan is latency bound (see + // kTopkThreads), so a float4 puts four times the bytes in flight per wait. A row is 16-byte + // aligned only when base and stride both are, and n_vocab need not be a multiple of four; + // otherwise the scalar form runs. const bool v4 = ((uintptr_t)row & 15u) == 0 && (n_vocab & 3u) == 0; if (v4) { const float4* __restrict__ r4 = (const float4*)row; @@ -580,18 +544,15 @@ __global__ __launch_bounds__(kTopkThreads) void topk_kernel( __syncthreads(); got = 1; } else { - // `n_eq` is how many of the k are still owed once every strictly-larger logit has been - // counted: exactly the number to take from the tie group at the threshold, and always at - // least one. `n_tie` is how big that group is. + // `n_eq` is how many of the k are still owed once every strictly larger logit is counted: + // the number to take from the threshold's tie group, always at least one. `n_tie` is that + // group's size. uint32_t n_eq = 0, dummy = 0, n_tie = 0; const uint32_t T = radix_select(row, n_vocab, 0, k, hist, scan, wt, &n_eq, &n_tie); - // THE TIE-BREAK PASS ONLY RUNS WHEN THERE IS A TIE TO BREAK. `n_tie` is how many elements - // carry the threshold key exactly and `n_eq` how many of them the set is owed; when they - // are equal the whole group is in and there is nothing for the ASC select to choose - // between, so the four passes it would cost are four passes over 124160 logits for an - // answer already known. Distinct logits are the ordinary case, and `i <= 0xffffffff` is - // then true for every member -- the same set, without the search. + // The tie-break pass runs only when there is a tie to break. When `n_tie == n_eq` the whole + // group is in, and the four ASC passes (over 124160 logits) would find nothing new. With + // distinct logits, the ordinary case, `i <= 0xffffffff` holds for every member. const uint32_t idx_cut = (n_tie == n_eq) ? 0xffffffffu : radix_select(row, n_vocab, T, n_eq, hist, scan, wt, @@ -599,9 +560,8 @@ __global__ __launch_bounds__(kTopkThreads) void topk_kernel( if (threadIdx.x == 0) fill = 0; __syncthreads(); - /* Four at a time, for the reason radix_select gives. The slots are claimed in whatever - * order the atomics land, and the sort below puts the set in (key, ~id) order, so the - * candidates come out the same whatever that order was. */ + /* Four at a time, as in radix_select. Slots are claimed in atomic order, and the sort below + * puts the set in (key, ~id) order, so the result does not depend on that order. */ auto collect = [&](float f, uint32_t i) { const uint32_t key = fkey(f); const bool take = key > T || (key == T && i <= idx_cut); @@ -625,18 +585,16 @@ __global__ __launch_bounds__(kTopkThreads) void topk_kernel( __syncthreads(); got = fill < kMaxCand ? fill : kMaxCand; - // SORTED OVER THE LIVE SET, NOT THE CANDIDATE WIDTH. The select puts exactly `got` - // elements in the low slots and the output loop reads none above them, so a request at - // top_k = 20 sorts 32 words rather than the 4096 the buffer is wide. + // Sorted over the live set, not the candidate width: the select fills exactly `got` low + // slots and the output reads none above them, so top_k = 20 sorts 32 words, not 4096. uint32_t sn = 1; while (sn < got) sn <<= 1; for (uint32_t i = got + threadIdx.x; i < sn; i += kTopkThreads) shared_cand[i] = 0; __syncthreads(); - // Bitonic sort, descending. The packed word is (key, ~id), so a plain descending sort puts - // the largest logit first and, among equal logits, the LOWER id first -- ref's tie rule, - // again for free. Padding words are 0 and sort to the tail, where they are written as - // holes. + // Bitonic sort, descending. The packed word is (key, ~id), so the largest logit comes + // first and, among equal logits, the lower id (ref's tie rule). Padding words are 0, sort + // to the tail, and are written as holes. for (uint32_t sz = 2; sz <= sn; sz <<= 1) { for (uint32_t st = sz >> 1; st > 0; st >>= 1) { for (uint32_t t = threadIdx.x; t < sn; t += kTopkThreads) { @@ -652,12 +610,10 @@ __global__ __launch_bounds__(kTopkThreads) void topk_kernel( } (void)pad; - // THE CANDIDATE INDEX IS LOCAL AND THE PAIR PLANE IS GLOBAL, deliberately. ci/cv index `row`, - // which is this rank's slice of the vocabulary, and every stage after top-k reads them that - // way. `pr` is the vocab-parallel path's payload instead: (u32 GLOBAL id, f32 logit) pairs, in - // the layout sample_merge_topk reads, with vocab_off already added -- so the all-gather in - // between moves bytes it does not have to understand, and the single-rank path is unchanged - // because it passes pr = null. + // The candidate index is local and the pair plane global. ci/cv index `row`, this rank's slice + // of the vocabulary, as every later stage reads them. `pr` is the vocab-parallel payload: + // (u32 global id, f32 logit) pairs in sample_merge_topk's layout with vocab_off added, so the + // all-gather moves opaque bytes; the single-rank path passes pr = null. uint32_t* __restrict__ op = pr ? pr + (size_t)m * pr_ld : nullptr; for (uint32_t r = threadIdx.x; r < n_cand; r += kTopkThreads) { const bool live = r < got && r < k; @@ -667,8 +623,8 @@ __global__ __launch_bounds__(kTopkThreads) void topk_kernel( oi[r] = live ? (int32_t)loc : -1; ov[r] = val; if (op) { - // 0xffffffff is the hole: the merge tests the id as a SIGNED int and drops it when - // negative, which is the same convention ci carries as -1. + // 0xffffffff is the hole: the merge reads the id as signed and drops a negative one, + // the convention ci carries as -1. op[2 * r] = live ? (uint32_t)((int32_t)loc + vocab_off) : 0xffffffffu; op[2 * r + 1] = __builtin_bit_cast(uint32_t, val); } @@ -676,20 +632,19 @@ __global__ __launch_bounds__(kTopkThreads) void topk_kernel( } // ---------------------------------------------------------------------------- sample_logprobs -// ref_sample_logprobs. For a row with RAD_SP_LOGPROBS: [max, sum of exp(l - max), k (id, logit) -// pairs], descending, ties to the lower id, ids global (+ vocab_off) and written as floats. A row -// without the flag is not written, and its block leaves before reading anything. +// ref_sample_logprobs. For a row with RAD_SP_LOGPROBS: [max, sum of exp(l - max), k (id, logit) +// pairs], descending, ties to the lower id, ids global (+ vocab_off) and written as floats. A row +// without the flag is not written, and its block exits before reading anything. // -// THE k LARGEST ARE topk_kernel's SELECT, at the op's fixed k rather than a row's top_k: the same -// radix_select passes, the tie-break pass only when the threshold's tie group is bigger than the -// set is owed, and the same packed (key, ~id) bitonic sort, so this set and a top-k candidate set -// over the same row agree to the bit and the tie rule is ref's by construction. The maximum is -// the first of them, so it costs nothing; the sum is one more pass, accurate expf, folded wave by -// wave in a fixed order -- the same row gives the same bits every step. +// The k largest come from topk_kernel's select at the op's fixed k rather than a row's top_k: the +// same radix_select passes, the tie-break pass only when needed, and the same packed (key, ~id) +// bitonic sort, so this set and a top-k candidate set over the same row agree to the bit. The max +// is the first of them; the sum is one more pass with accurate expf, folded wave by wave in a fixed +// order, so the same row gives the same bits every step. // -// k IS BOUNDED BY kMaxLogprobs, the LDS the sort runs in. The engine declares 21 (OpenAI's bound on -// top_logprobs, and one more so a row is whole 16-byte words); the shim refuses a wider op rather -// than truncating it. +// k is bounded by kMaxLogprobs, the LDS the sort runs in. The engine declares 21 (OpenAI's +// top_logprobs bound plus one, so a row is whole 16-byte words); the shim refuses a wider op +// rather than truncating. constexpr uint32_t kMaxLogprobs = 64; __global__ __launch_bounds__(kTopkThreads) void logprobs_kernel( @@ -787,7 +742,7 @@ __global__ __launch_bounds__(kTopkThreads) void logprobs_kernel( // ---------------------------------------------------------------------------- the narrowing stages // // All four read a fixed-width candidate set in place: index -1 and value -infinity mark a hole, and -// the live set keeps its descending order. n_cand is a thousand or two, so one block a row with a +// the live set keeps its descending order. n_cand is a thousand or two, so one block per row with a // couple of block reductions is the whole cost. enum { NR_TOPP = 0, NR_MINP, NR_TYPICAL, NR_XTC }; @@ -815,9 +770,9 @@ __global__ __launch_bounds__(kThreads) void narrow_kernel( __syncthreads(); if (which == NR_MINP) { - // Keep everything within a factor min_p of the most likely candidate. Comparing - // exp(v - max) against p is the same test as prob >= p * max_prob without forming the - // normaliser: one pass fewer and one rounding fewer. + // Keep everything within a factor min_p of the most likely candidate. Comparing + // exp(v - max) against p is the same test as prob >= p * max_prob without the normaliser: + // one pass and one rounding fewer. if (!(p.min_p > 0.0f)) return; for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) { if (oi[i] < 0) continue; @@ -838,16 +793,14 @@ __global__ __launch_bounds__(kThreads) void narrow_kernel( const float inv = sh_inv; if (which == NR_TOPP) { - // ONE THREAD FINDS THE CUT, and deliberately: it is the shortest prefix whose cumulative - // probability reaches top_p, accumulated in f32 in candidate order. A parallel prefix sum - // sums in a different order and a candidate at the boundary would survive here and not in - // ref. + // One thread finds the cut: the shortest prefix whose cumulative probability reaches + // top_p, accumulated in f32 in candidate order, as ref does; a parallel prefix sum would + // round differently at the boundary. // - // BUT ONLY THE CUT IS SERIAL, and the removal after it is not. The scan stops at the - // candidate that reaches top_p; every live candidate past it goes, which the whole block - // does. Walking the rest on the one thread costs a dependent global load per candidate -- - // ~50 us a row at 1024 candidates, on every step of a greedy request over a split - // vocabulary, whose top-1 row reaches any top_p on its first candidate. + // Only the cut is serial; the whole block removes the candidates past it. Walking them on + // one thread costs a dependent global load each (~50 us a row at 1024 candidates), on + // every step of a greedy request over a split vocabulary, whose top-1 row reaches any top_p + // at its first candidate. if (!(p.top_p < 1.0f) || !(p.top_p > 0.0f)) return; __shared__ uint32_t sh_cut; if (threadIdx.x == 0) { @@ -867,11 +820,10 @@ __global__ __launch_bounds__(kThreads) void narrow_kernel( } if (which == NR_TYPICAL) { - // Locally typical: keep the candidates whose surprisal is closest to the distribution's - // entropy until their mass reaches typical_p. NOT a prefix -- the candidate order is by - // probability and this order is by |surprisal - H| -- so it is a threshold on the distance, - // ties kept, which can overshoot p slightly. The alternative is an order that depends on - // the candidate index, which is worse. + // Locally typical: keep the candidates whose surprisal is closest to the entropy until + // their mass reaches typical_p. Not a prefix (candidates are ordered by probability, this + // by |surprisal - H|), so it is a threshold on the distance with ties kept, which can + // overshoot p slightly, rather than an order that depends on the candidate index. if (!(p.typical_p < 1.0f) || !(p.typical_p > 0.0f)) return; float H = 0.0f; for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) { @@ -882,16 +834,16 @@ __global__ __launch_bounds__(kThreads) void narrow_kernel( H = block_sum(H, red); if (threadIdx.x == 0) { sh_H = H; - /* A distance is non-negative, so its f32 bit pattern is a non-negative int and orders - * the same way -- which is what lets the minimum be an integer atomicMin. */ + /* A non-negative float's bit pattern orders like the float, so the minimum can be an + * integer atomicMin. */ sh_cut_bits = __float_as_int(INFINITY); sh_have_cut = 0; } __syncthreads(); - // The smallest distance threshold whose mass reaches p, over the distances that actually - // occur. Quadratic in n_cand and parallel over the outer index; the reduction is a - // minimum, so it is order-independent and reproduces. + // The smallest distance threshold whose mass reaches p, over the distances that occur. + // Quadratic in n_cand, parallel over the outer index; the reduction is a minimum, so it is + // order-independent. float local_cut = INFINITY; bool local_have = false; for (uint32_t c = threadIdx.x; c < n_cand; c += kThreads) { @@ -923,10 +875,9 @@ __global__ __launch_bounds__(kThreads) void narrow_kernel( return; } - // XTC -- "exclude top choices". With probability xtc_probability, DROP every candidate at or - // above xtc_threshold EXCEPT the least likely of them. The opposite of every other stage here - // and that is the point: it removes the obvious continuations and leaves the interesting one. - // The draw is per row from the row's own stream, so it reproduces. + // XTC ("exclude top choices"): with probability xtc_probability, drop every candidate at or + // above xtc_threshold except the least likely of them, removing the obvious continuations. The + // draw comes from the row's own stream, so it reproduces. if (!(p.xtc_probability > 0.0f) || !(p.xtc_threshold > 0.0f)) return; if (uniform01(p.seed ^ RAD_SAMPLE_KEY_XTC, p.pos) >= p.xtc_probability) return; @@ -940,8 +891,8 @@ __global__ __launch_bounds__(kThreads) void narrow_kernel( } } __syncthreads(); - // Nothing to do unless at least two clear the threshold: dropping the only one would leave the - // row without its own choice. + // Only when at least two clear the threshold: dropping the only one would leave the row + // without its own choice. if (sh_above < 2) return; for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) { if (oi[i] < 0 || (int)i == sh_last) continue; @@ -950,15 +901,14 @@ __global__ __launch_bounds__(kThreads) void narrow_kernel( } // ---------------------------------------------------------------------------- sample_pick -// ref_sample_pick: the inverse CDF over the candidate set, walked in candidate order with the sum -// accumulated in f32. ONE THREAD for the same reason top_p is one thread -- the walk's rounding is -// the contract. The fallback is the last candidate ABOVE -INFINITY: `u` is strictly below 1 and -// the probabilities sum to 1 in exact arithmetic but not in f32, and a draw that falls through the -// last comparison must still produce a token the distribution allows. A live candidate at -// -infinity is a grammar-masked logit top-k took to fill its width, and falling through to it emits -// a token the grammar ruled out. It adds nothing to `cum`, so the comparison never chooses one. +// ref_sample_pick: the inverse CDF over the candidate set, walked in candidate order with an f32 +// sum, on one thread like top_p because the walk's rounding is the contract. The fallback is the +// last candidate above -infinity: `u` is below 1 but the probabilities only sum to 1 in exact +// arithmetic, and a draw that falls through must still yield an allowed token. A live candidate at +// -infinity is a grammar-masked logit top-k took to fill its width; it adds nothing to `cum`, so +// the comparison never chooses one, and the fallback must not either. // -// A GREEDY ROW IS NOT TOUCHED: its token is the argmax's, written before the chain ran. +// A greedy row is not touched: its token is the argmax's, written before the chain ran. __global__ __launch_bounds__(kThreads) void pick_kernel( const int32_t* __restrict__ ci, const float* __restrict__ cv, const SP* __restrict__ sp, int32_t* __restrict__ tok, uint32_t n_cand, uint32_t ci_ld, uint32_t cv_ld) { @@ -999,13 +949,13 @@ __global__ __launch_bounds__(kThreads) void pick_kernel( } // ---------------------------------------------------------------------------- sample_merge_topk -// THE VOCAB-PARALLEL MERGE. Each rank runs top-k over its own lm_head shard and the candidate sets -// are all-gathered -- k * world_size pairs, kilobytes, against the tens of megabytes a full-logits -// gather would move. `gathered` is (u32 global id, f32 logit) pairs: each rank adds its own vocab -// offset before the gather, so this needs no shard layout. +// The vocab-parallel merge. Each rank runs top-k over its own lm_head shard and the candidate sets +// are all-gathered (k * world_size pairs, kilobytes, instead of tens of megabytes of logits). +// `gathered` holds (u32 global id, f32 logit) pairs; each rank added its vocab offset before the +// gather, so this needs no shard layout. // -// One block a row, and the same packed (key, ~id) word as the top-k, so the descending order and -// the lower-id tie rule are the same code path. n_in is world_size * n_cand, a few thousand. +// One block per row, with the top-k's packed (key, ~id) word, so descending order and the lower-id +// tie rule come from the same code. n_in is world_size * n_cand, a few thousand. __global__ __launch_bounds__(kTopkThreads) void merge_topk_kernel( const uint32_t* __restrict__ gt, const SP* __restrict__ sp, int32_t* __restrict__ ci, float* __restrict__ cv, @@ -1022,15 +972,13 @@ __global__ __launch_bounds__(kTopkThreads) void merge_topk_kernel( return; } - /* THE INPUT IS ALREADY world_size SORTED RUNS, and the sort starts where they leave off. Each - * rank's top-k wrote its n_cand pairs in descending (key, ~id) order with its holes at the - * tail, and a rank's vocab offset is one constant added to every id, so the run is in THIS - * kernel's key order too. When the runs are a power of two long and fill the padded width, - * that is exactly the state the bitonic network is in after its stages up to sz = n_cand -- - * provided the odd runs are loaded reversed, since those stages leave them ascending -- and - * only the log2(world_size) merge stages are left: 11 passes over two runs of 1024 where the - * whole network is 66. Any other shape starts from the first stage. The keys are distinct but - * for the holes, which are all zero, so the order that comes out is the only one there is. */ + /* The input is already world_size sorted runs: each rank wrote its n_cand pairs in descending + * (key, ~id) order with holes at the tail, and adding a rank's vocab offset preserves that + * order. When the runs are a power of two long and fill the padded width, that is the bitonic + * network's state after its stages up to sz = n_cand, provided the odd runs are loaded reversed + * (those stages leave them ascending), so only the log2(world_size) merge stages remain: 11 + * passes over two runs of 1024 instead of 66. Any other shape starts from the first stage. The + * keys are distinct except for the all-zero holes, so the output order is unique. */ const bool runs = (n_cand & (n_cand - 1)) == 0 && pad == n_in; const uint32_t first = runs ? 2 * n_cand : 2; for (uint32_t j = threadIdx.x; j < pad; j += kTopkThreads) { @@ -1058,14 +1006,10 @@ __global__ __launch_bounds__(kTopkThreads) void merge_topk_kernel( } } - // THE ROW'S OWN top_k, RE-APPLIED. Each rank ran its own top-k before the gather, so the - // merged set holds up to world_size * k candidates where the request asked for k -- and - // nothing downstream narrows again. Leaving them live is not a rounding error in the - // sampling support, it is a different distribution, and at k = 1 it is a different ANSWER: - // a greedy row is staged at top_k = 1 precisely so the chain returns the argmax, and with - // world_size candidates alive `sample_pick` draws among them against the request's seed - // instead. On two ranks that makes the same greedy prompt return either the true argmax or the - // OTHER rank's local best, depending on nothing but an unset seed, about a quarter of the time. + // The row's own top_k, re-applied. Each rank kept k before the gather, so the merged set holds + // up to world_size * k, and nothing downstream narrows again. Leaving them live changes the + // distribution, and at k = 1 the answer: a greedy row is staged at top_k = 1 so the chain + // returns the argmax, and with world_size candidates live `sample_pick` would draw among them. // 0 or negative means the whole candidate width, as everywhere else. const uint32_t keep = (uint32_t)(sp[m].top_k > 0 ? sp[m].top_k : (int32_t)n_cand); for (uint32_t r = threadIdx.x; r < n_cand; r += kTopkThreads) { @@ -1081,30 +1025,27 @@ __global__ __launch_bounds__(kTopkThreads) void merge_topk_kernel( // ================================================================================ entry points // -// Every pitch is in ELEMENTS and 0 means tight. `lg` is f32 -- the sampler runs in f32 whatever -// the model's activation dtype is, because a bf16 logit has 8 bits of mantissa and a nucleus cut is -// a comparison of neighbouring probabilities. +// Every pitch is in elements and 0 means tight. `lg` is f32 whatever the model's activation dtype: +// a bf16 logit has 8 mantissa bits, and a nucleus cut compares neighbouring probabilities. static uint32_t host_pow2(uint32_t v) { uint32_t p = 1; while (p < v) p <<= 1; return p; } -static int r4d_sample_max_cand(void) { return (int)kMaxCand; } - static int r4d_sample_temp_f32(long lg, long params, int M, int n_vocab, int lg_ld, long stream) { - if (!lg || !params) return -1; - if (M <= 0 || n_vocab <= 0) return -2; + if (!lg || !params) return R4D_NO(RAD_E_INVAL); + if (M <= 0 || n_vocab <= 0) return R4D_NO(RAD_E_SHAPE); if (!lg_ld) lg_ld = n_vocab; const uint32_t gy = ((uint32_t)n_vocab + kThreads - 1) / kThreads; hipLaunchKernelGGL(temp_kernel, dim3((uint32_t)M, gy > 256u ? 256u : gy), dim3(kThreads), 0, (hipStream_t)stream, (float*)lg, (const SP*)params, (uint32_t)n_vocab, (uint32_t)lg_ld); - return hipGetLastError() == hipSuccess ? 0 : -4; + return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); } static int r4d_sample_mask_f32(long lg, long params, long bitmask, int M, int n_vocab, int mask_rows, int lg_ld, long stream) { - if (!lg || !params || !bitmask) return -1; - if (M <= 0 || n_vocab <= 0 || mask_rows <= 0) return -2; + if (!lg || !params || !bitmask) return R4D_NO(RAD_E_INVAL); + if (M <= 0 || n_vocab <= 0 || mask_rows <= 0) return R4D_NO(RAD_E_SHAPE); if (!lg_ld) lg_ld = n_vocab; const uint32_t words = ((uint32_t)n_vocab + 31u) / 32u; const uint32_t gy = ((uint32_t)n_vocab + kThreads - 1) / kThreads; @@ -1112,44 +1053,44 @@ static int r4d_sample_mask_f32(long lg, long params, long bitmask, int M, int n_ (hipStream_t)stream, (float*)lg, (const SP*)params, (const uint32_t*)bitmask, (uint32_t)n_vocab, (uint32_t)lg_ld, words, (int32_t)mask_rows); - return hipGetLastError() == hipSuccess ? 0 : -4; + return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); } static int r4d_sample_penalties_f32(long lg, long params, long hist, int M, int n_vocab, int hmax, int lg_ld, int vocab_off, long stream) { - if (!lg || !params || !hist) return -1; - if (M <= 0 || n_vocab <= 0 || hmax <= 0) return -2; + if (!lg || !params || !hist) return R4D_NO(RAD_E_INVAL); + if (M <= 0 || n_vocab <= 0 || hmax <= 0) return R4D_NO(RAD_E_SHAPE); if (!lg_ld) lg_ld = n_vocab; hipLaunchKernelGGL(penalties_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream, (float*)lg, (const SP*)params, (const int32_t*)hist, (uint32_t)n_vocab, (uint32_t)lg_ld, (uint32_t)hmax, (int32_t)vocab_off); - return hipGetLastError() == hipSuccess ? 0 : -4; + return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); } -// The widest history row DRY takes: one u16 repeat length a position lives in LDS, and 16384 of -// them is 32 KiB, half of what a workgroup may have. The engine declares 2048. +// The widest history row DRY takes: one u16 repeat length per position in LDS, so 16384 of them is +// 32 KiB, half a workgroup's LDS. The engine declares 2048. constexpr uint32_t kDryMaxHist = 16384; static int r4d_sample_dry_f32(long lg, long params, long hist, long brk, int M, int n_vocab, int hmax, int lg_ld, int vocab_off, long stream) { - if (!lg || !params || !hist) return -1; - if (M <= 0 || n_vocab <= 0 || hmax <= 0) return -2; - if ((uint32_t)hmax > kDryMaxHist) return -3; + if (!lg || !params || !hist) return R4D_NO(RAD_E_INVAL); + if (M <= 0 || n_vocab <= 0 || hmax <= 0) return R4D_NO(RAD_E_SHAPE); + if ((uint32_t)hmax > kDryMaxHist) return R4D_NO(RAD_E_SHAPE); if (!lg_ld) lg_ld = n_vocab; hipLaunchKernelGGL(dry_kernel, dim3((uint32_t)M), dim3(kThreads), (size_t)hmax * sizeof(uint16_t), (hipStream_t)stream, (float*)lg, (const SP*)params, (const int32_t*)hist, (const uint8_t*)brk, (uint32_t)n_vocab, (uint32_t)lg_ld, (uint32_t)hmax, (int32_t)vocab_off); - return hipGetLastError() == hipSuccess ? 0 : -4; + return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); } static int r4d_sample_argmax_f32(long lg, long tok, int M, int n_vocab, int lg_ld, long stream) { - if (!lg || !tok) return -1; - if (M <= 0 || n_vocab <= 0) return -2; + if (!lg || !tok) return R4D_NO(RAD_E_INVAL); + if (M <= 0 || n_vocab <= 0) return R4D_NO(RAD_E_SHAPE); if (!lg_ld) lg_ld = n_vocab; - /* THE PITCH IS PART OF THE ALIGNMENT, not just the base: row m starts at `m * lg_ld` floats, so - * a pitch that is not a multiple of four misaligns every row after the first. */ + /* The pitch is part of the alignment: row m starts at `m * lg_ld` floats, so a pitch that is + * not a multiple of four misaligns every row after the first. */ const bool vec = ((uintptr_t)lg % (4 * sizeof(float)) == 0) && ((uint32_t)lg_ld % 4u == 0u); if (vec) hipLaunchKernelGGL((argmax_kernel), dim3((uint32_t)M), @@ -1159,30 +1100,30 @@ static int r4d_sample_argmax_f32(long lg, long tok, int M, int n_vocab, int lg_l hipLaunchKernelGGL((argmax_kernel), dim3((uint32_t)M), dim3(kArgmaxThreads), 0, (hipStream_t)stream, (const float*)lg, (int32_t*)tok, (uint32_t)n_vocab, (uint32_t)lg_ld); - return hipGetLastError() == hipSuccess ? 0 : -4; + return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); } static int r4d_sample_logprobs_f32(long lg, long params, long stats, int M, int n_vocab, int k, int lg_ld, int st_ld, int vocab_off, long stream) { - if (!lg || !params || !stats) return -1; - if (M <= 0 || n_vocab <= 0 || k <= 0) return -2; - if ((uint32_t)k > kMaxLogprobs) return -3; + if (!lg || !params || !stats) return R4D_NO(RAD_E_INVAL); + if (M <= 0 || n_vocab <= 0 || k <= 0) return R4D_NO(RAD_E_SHAPE); + if ((uint32_t)k > kMaxLogprobs) return R4D_NO(RAD_E_SHAPE); if (!lg_ld) lg_ld = n_vocab; if (!st_ld) st_ld = 2 + 2 * k; hipLaunchKernelGGL(logprobs_kernel, dim3((uint32_t)M), dim3(kTopkThreads), 0, (hipStream_t)stream, (const float*)lg, (const SP*)params, (float*)stats, (uint32_t)n_vocab, (uint32_t)k, (uint32_t)lg_ld, (uint32_t)st_ld, (int32_t)vocab_off); - return hipGetLastError() == hipSuccess ? 0 : -4; + return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); } static int r4d_sample_topk_f32(long lg, long params, long cand_idx, long cand_val, long pairs, int M, int n_vocab, int n_cand, int lg_ld, int ci_ld, int cv_ld, int pr_ld, int vocab_off, long stream) { - if (!lg || !params || !cand_idx || !cand_val) return -1; - if (M <= 0 || n_vocab <= 0 || n_cand <= 0) return -2; - if ((uint32_t)n_cand > kMaxCand) return -3; + if (!lg || !params || !cand_idx || !cand_val) return R4D_NO(RAD_E_INVAL); + if (M <= 0 || n_vocab <= 0 || n_cand <= 0) return R4D_NO(RAD_E_SHAPE); + if ((uint32_t)n_cand > kMaxCand) return R4D_NO(RAD_E_SHAPE); if (!lg_ld) lg_ld = n_vocab; if (!ci_ld) ci_ld = n_cand; if (!cv_ld) cv_ld = n_cand; @@ -1194,43 +1135,42 @@ static int r4d_sample_topk_f32(long lg, long params, long cand_idx, long cand_va (uint32_t*)pairs, (uint32_t)n_vocab, (uint32_t)n_cand, (uint32_t)lg_ld, (uint32_t)ci_ld, (uint32_t)cv_ld, (uint32_t)pr_ld, (int32_t)vocab_off, pad); - return hipGetLastError() == hipSuccess ? 0 : -4; + return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); } -// `which` is 0 top_p, 1 min_p, 2 typical, 3 xtc -- one entry point because the four differ by a -// branch after the same two reductions, and four rows in the table because the SELECTOR names ops, -// not entry points. +// `which` is 0 top_p, 1 min_p, 2 typical, 3 xtc: one entry point because the four differ by a +// branch after the same two reductions, four rows in the table because the selector names ops. static int r4d_sample_narrow_f32(long cand_idx, long cand_val, long params, int M, int n_cand, int which, int ci_ld, int cv_ld, long stream) { - if (!cand_idx || !cand_val || !params) return -1; - if (M <= 0 || n_cand <= 0) return -2; - if (which < 0 || which > 3) return -3; + if (!cand_idx || !cand_val || !params) return R4D_NO(RAD_E_INVAL); + if (M <= 0 || n_cand <= 0) return R4D_NO(RAD_E_SHAPE); + if (which < 0 || which > 3) return R4D_NO(RAD_E_SHAPE); if (!ci_ld) ci_ld = n_cand; if (!cv_ld) cv_ld = n_cand; hipLaunchKernelGGL(narrow_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream, (int32_t*)cand_idx, (float*)cand_val, (const SP*)params, (uint32_t)n_cand, (uint32_t)ci_ld, (uint32_t)cv_ld, which); - return hipGetLastError() == hipSuccess ? 0 : -4; + return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); } static int r4d_sample_pick_f32(long cand_idx, long cand_val, long params, long tok, int M, int n_cand, int ci_ld, int cv_ld, long stream) { - if (!cand_idx || !cand_val || !params || !tok) return -1; - if (M <= 0 || n_cand <= 0) return -2; + if (!cand_idx || !cand_val || !params || !tok) return R4D_NO(RAD_E_INVAL); + if (M <= 0 || n_cand <= 0) return R4D_NO(RAD_E_SHAPE); if (!ci_ld) ci_ld = n_cand; if (!cv_ld) cv_ld = n_cand; hipLaunchKernelGGL(pick_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream, (const int32_t*)cand_idx, (const float*)cand_val, (const SP*)params, (int32_t*)tok, (uint32_t)n_cand, (uint32_t)ci_ld, (uint32_t)cv_ld); - return hipGetLastError() == hipSuccess ? 0 : -4; + return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); } static int r4d_sample_merge_topk_f32(long gathered, long params, long cand_idx, long cand_val, int M, int n_in, int n_cand, int gt_ld, int ci_ld, int cv_ld, long stream) { - if (!gathered || !params || !cand_idx || !cand_val) return -1; - if (M <= 0 || n_in <= 0 || n_cand <= 0) return -2; - if ((uint32_t)n_in > kMaxCand) return -3; + if (!gathered || !params || !cand_idx || !cand_val) return R4D_NO(RAD_E_INVAL); + if (M <= 0 || n_in <= 0 || n_cand <= 0) return R4D_NO(RAD_E_SHAPE); + if ((uint32_t)n_in > kMaxCand) return R4D_NO(RAD_E_SHAPE); if (!gt_ld) gt_ld = 2 * n_in; if (!ci_ld) ci_ld = n_cand; if (!cv_ld) cv_ld = n_cand; @@ -1241,28 +1181,19 @@ static int r4d_sample_merge_topk_f32(long gathered, long params, long cand_idx, (int32_t*)cand_idx, (float*)cand_val, (uint32_t)n_in, (uint32_t)n_cand, (uint32_t)gt_ld, (uint32_t)ci_ld, (uint32_t)cv_ld, pad); - return hipGetLastError() == hipSuccess ? 0 : -4; + return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); } // ============================================================== the plugin ABI entry points // -// Unpacking RadArgs and re-deriving the pitches IS the kernel's own business -- which operand is -// the candidate index plane, whether a row pitch is tight -- so it lives beside the kernel rather -// than in a translation layer an out-of-tree author cannot write. The flattened entry points above -// are private to this unit. +// Unpacking RadArgs and deriving the pitches is the kernel's own business, so it lives beside the +// kernel rather than in a translation layer an out-of-tree author could not write. The flattened +// entry points above are private to this unit. See the file header for why the chain is eleven ops +// beside r4d_sample_chain_f32. // -// WHY THE CHAIN IS ELEVEN OPS AND NOT r4d_sample_chain_f32's ONE. The fused kernel does -// temperature, softmax, top_k, top_p, min_p and the draw in vLLM's fixed order; the core -// composes its chain per request out of stages a request may skip, and it has stages the fused -// kernel does not -- the penalties, DRY, a grammar bitmask, locally-typical, XTC. "Fusion is a -// selection, not a compiler pass" (spec 2.3) cuts both ways: a library that shipped only the -// fused form would be choosing the fusion on the plugin's behalf. Both rows exist; this is the -// one the served path resolves. -// -// EVERY SCALAR IS PER ROW. `top_p` as a parameter would make two requests with different top_p -// two different resolutions of one op, so a deployment would have exactly one top_p -// (rad_sample.h says this at length). The ops take `M` and `n_vocab` / `n_cand` as parameters -// and everything else as `params` data. +// Every scalar is per row: `top_p` as a parameter would make two requests with different top_p two +// resolutions of one op, so a deployment could have only one (see rad_sample.h). The ops take `M` +// and `n_vocab` / `n_cand` as parameters and everything else as `params` data. #define R4D_NEED(x) do { const int _s = (x); if (_s != RAD_OK) return R4D_NO(_s); } while (0) @@ -1273,9 +1204,9 @@ static inline int dt_i32(const RadTensor* t) { return (t && (t->dtype == RAD_I32 || t->dtype == RAD_U32)) ? RAD_OK : RAD_E_DTYPE; } -/* `params` is a BYTE BLOB viewed through a 32-bit dtype: the builder can only say "this many - * words a row", so the extent is checked in words and the dtype is required to be a 32-bit one -- - * rad_dtype_bytes is core's and a kernel plugin links only the ABI. */ +/* `params` is a byte blob viewed through a 32-bit dtype: the builder can only say "this many words + * a row", so the extent is checked in words and the dtype must be 32-bit (rad_dtype_bytes is + * core's, and a kernel plugin links only the ABI). */ static int params_ok(const RadTensor* t, long long M) { if (!t || !t->data) return R4D_NO(RAD_E_INVAL); if (t->dtype != RAD_U32 && t->dtype != RAD_I32 && t->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); @@ -1284,20 +1215,9 @@ static int params_ok(const RadTensor* t, long long M) { return RAD_OK; } -/* [rows, n] with a row pitch. The row count comes from the OPERAND: `M` is ranged, so the value in - * the args is the band's upper bound and a loop bounded by it walks off the arena. */ -static long long rows_pitch(const RadTensor* t, long long n, long long* rows) { - if (!t || t->rank < 1 || n <= 0) return -1; - const long long nel = r4d_numel(t); - if (nel % n) return -1; - *rows = nel / n; - if (t->rank == 1) return n; - if (t->shape[t->rank - 1] != n) return r4d_contig(t) ? n : -1; - if (t->stride[t->rank - 1] != 1) return -1; - return t->rank >= 2 ? t->stride[t->rank - 2] : n; -} - -#define R4D_LAUNCH(call) return ((call) == 0 ? RAD_OK : RAD_E_DEVICE) +/* Every [rows, n] operand is read with r4d_rows_pitch, which takes the row count from the operand: + * `M` is ranged, so the arg holds the band's upper bound and a loop bounded by it would run off the + * arena. */ /* ------------------------------------------------------------------ the vocabulary-wide stages */ @@ -1311,7 +1231,7 @@ static int logits_of(const RadArgs* a, const RadTensor** lg, long long* M, long R4D_NEED(dt_f32(*lg)); *n_vocab = r4d_geti_or(a, "n_vocab", r4d_dim(*lg, (int)(*lg)->rank - 1)); if (*n_vocab <= 0) return R4D_NO(RAD_E_SHAPE); - *ld = rows_pitch(*lg, *n_vocab, M); + *ld = r4d_rows_pitch(*lg, *n_vocab, M); if (*ld < 0) return R4D_NO(RAD_E_STRIDE); if (*M <= 0) return R4D_NO(RAD_E_SHAPE); return RAD_OK; @@ -1323,8 +1243,8 @@ extern "C" int r4d_rad_sample_temp(const RadArgs* a, RadStream s) { R4D_NEED(logits_of(a, &lg, &M, &nv, &ld)); const RadTensor* pr = r4d_opt(a, V_PARAMS); R4D_NEED(params_ok(pr, M)); - R4D_LAUNCH(r4d_sample_temp_f32(r4d_addr(lg), r4d_addr(pr), (int)M, (int)nv, (int)ld, - (long)(uintptr_t)s)); + return r4d_sample_temp_f32(r4d_addr(lg), r4d_addr(pr), (int)M, (int)nv, (int)ld, + (long)(uintptr_t)s); } extern "C" int r4d_rad_sample_mask(const RadArgs* a, RadStream s) { @@ -1337,19 +1257,19 @@ extern "C" int r4d_rad_sample_mask(const RadArgs* a, RadStream s) { if (!bm) return R4D_NO(RAD_E_INVAL); R4D_NEED(dt_i32(bm)); if (!r4d_contig(bm)) return R4D_NO(RAD_E_STRIDE); - /* The plane is [rows, ceil(n_vocab/32)] and is SHORTER than M: a constrained sequence and an - * unconstrained one share it, and `mask_row` is -1 for the second. */ + /* The plane is [rows, ceil(n_vocab/32)] and shorter than M: constrained and unconstrained + * sequences share it, and `mask_row` is -1 for the latter. */ const long long words = (nv + 31) / 32; const long long rows = r4d_numel(bm) / (words > 0 ? words : 1); if (rows <= 0) return R4D_NO(RAD_E_SHAPE); - R4D_LAUNCH(r4d_sample_mask_f32(r4d_addr(lg), r4d_addr(pr), r4d_addr(bm), (int)M, (int)nv, - (int)rows, (int)ld, (long)(uintptr_t)s)); + return r4d_sample_mask_f32(r4d_addr(lg), r4d_addr(pr), r4d_addr(bm), (int)M, (int)nv, + (int)rows, (int)ld, (long)(uintptr_t)s); } -/* `history` is [M, max_hist] int32 of GLOBAL token ids, row m's window addressed by row m's - * hist_off / hist_len within row m. `vocab_off` is this rank's first vocabulary row, 0 when the - * vocabulary is whole. DRY's optional fourth operand, `breakers`, is a u8 plane of the same shape: - * nonzero where that position's token is a whole sequence breaker. */ +/* `history` is [M, max_hist] int32 of global token ids, row m's window addressed by its hist_off / + * hist_len. `vocab_off` is this rank's first vocabulary row (0 for a whole vocabulary). DRY's + * optional fourth operand, `breakers`, is a u8 plane of the same shape, nonzero where the token is + * a sequence breaker. */ static int penal(const RadArgs* a, int dry, RadStream s) { const RadTensor* lg; long long M = 0, nv = 0, ld = 0; @@ -1372,12 +1292,12 @@ static int penal(const RadArgs* a, int dry, RadStream s) { if (r4d_numel(b) < M * hmax) return R4D_NO(RAD_E_SHAPE); } if (hmax > (long long)kDryMaxHist) return R4D_NO(RAD_E_SHAPE); - R4D_LAUNCH(r4d_sample_dry_f32(r4d_addr(lg), r4d_addr(pr), r4d_addr(h), - b ? r4d_addr(b) : 0, (int)M, (int)nv, (int)hmax, (int)ld, - (int)voff, (long)(uintptr_t)s)); + return r4d_sample_dry_f32(r4d_addr(lg), r4d_addr(pr), r4d_addr(h), + b ? r4d_addr(b) : 0, (int)M, (int)nv, (int)hmax, (int)ld, + (int)voff, (long)(uintptr_t)s); } - R4D_LAUNCH(r4d_sample_penalties_f32(r4d_addr(lg), r4d_addr(pr), r4d_addr(h), (int)M, (int)nv, - (int)hmax, (int)ld, (int)voff, (long)(uintptr_t)s)); + return r4d_sample_penalties_f32(r4d_addr(lg), r4d_addr(pr), r4d_addr(h), (int)M, (int)nv, + (int)hmax, (int)ld, (int)voff, (long)(uintptr_t)s); } extern "C" int r4d_rad_sample_penalties(const RadArgs* a, RadStream s) { @@ -1393,8 +1313,8 @@ extern "C" int r4d_rad_sample_argmax(const RadArgs* a, RadStream s) { if (!tok) return R4D_NO(RAD_E_INVAL); R4D_NEED(dt_i32(tok)); if (!r4d_contig(tok) || r4d_numel(tok) < M) return R4D_NO(RAD_E_SHAPE); - R4D_LAUNCH(r4d_sample_argmax_f32(r4d_addr(lg), r4d_addr(tok), (int)M, (int)nv, (int)ld, - (long)(uintptr_t)s)); + return r4d_sample_argmax_f32(r4d_addr(lg), r4d_addr(tok), (int)M, (int)nv, (int)ld, + (long)(uintptr_t)s); } /* stats [M, 2 + 2k] f32: max, sum of exp(l - max), then k (global id, logit) pairs. */ @@ -1410,13 +1330,13 @@ extern "C" int r4d_rad_sample_logprobs(const RadArgs* a, RadStream s) { const long long k = r4d_pgeti_or(a->p, a->n_p, "k", 0); if (k <= 0 || k > (long long)kMaxLogprobs) return R4D_NO(RAD_E_SHAPE); long long Ms = 0; - const long long st_ld = rows_pitch(st, 2 + 2 * k, &Ms); + const long long st_ld = r4d_rows_pitch(st, 2 + 2 * k, &Ms); if (st_ld < 0) return R4D_NO(RAD_E_STRIDE); if (Ms < M) return R4D_NO(RAD_E_SHAPE); const long long voff = r4d_pgeti_or(a->p, a->n_p, "vocab_off", 0); - R4D_LAUNCH(r4d_sample_logprobs_f32(r4d_addr(lg), r4d_addr(pr), r4d_addr(st), (int)M, (int)nv, - (int)k, (int)ld, (int)st_ld, (int)voff, - (long)(uintptr_t)s)); + return r4d_sample_logprobs_f32(r4d_addr(lg), r4d_addr(pr), r4d_addr(st), (int)M, (int)nv, + (int)k, (int)ld, (int)st_ld, (int)voff, + (long)(uintptr_t)s); } /* ------------------------------------------------------------------ top-k */ @@ -1435,35 +1355,33 @@ extern "C" int r4d_rad_sample_topk(const RadArgs* a, RadStream s) { R4D_NEED(dt_i32(ci)); R4D_NEED(dt_f32(cv)); - /* The candidate WIDTH is the buffer's and not the request's: it is the deployment bound the - * arena was sized for, and every later stage reads it. A row's own top_k may be narrower and - * leaves holes, which is the kernel's business. */ + /* The candidate width is the buffer's, not the request's: the deployment bound the arena was + * sized for, read by every later stage. A narrower top_k leaves holes. */ const long long n_cand = ci->rank >= 2 ? ci->shape[ci->rank - 1] : r4d_numel(ci) / M; - if (n_cand <= 0 || n_cand > r4d_sample_max_cand()) return R4D_NO(RAD_E_SHAPE); + if (n_cand <= 0 || n_cand > (int)kMaxCand) return R4D_NO(RAD_E_SHAPE); long long Mi = 0, Mv = 0; - const long long ci_ld = rows_pitch(ci, n_cand, &Mi); - const long long cv_ld = rows_pitch(cv, n_cand, &Mv); + const long long ci_ld = r4d_rows_pitch(ci, n_cand, &Mi); + const long long cv_ld = r4d_rows_pitch(cv, n_cand, &Mv); if (ci_ld < 0 || cv_ld < 0) return R4D_NO(RAD_E_STRIDE); if (Mi < M || Mv < M) return R4D_NO(RAD_E_SHAPE); - /* THE VOCAB-PARALLEL PAIR PLANE, optional. Present only when lm_head is row-sharded: the - * candidates this rank found, as (u32 global id, f32 logit) pairs, which is what the - * all-gather moves and what sample_merge_topk reads. `vocab_off` is this rank's first - * vocabulary row and the kernel adds it, so the gather never has to know the shard layout. */ + /* The optional vocab-parallel pair plane, present only when lm_head is row-sharded: this rank's + * candidates as (u32 global id, f32 logit) pairs, what the all-gather moves and + * sample_merge_topk reads. The kernel adds `vocab_off`, so the gather needs no shard layout. */ const RadTensor* pp = r4d_opt(a, TK_PAIRS); long long pr_ld = 0, Mp = 0; if (pp) { R4D_NEED(dt_i32(pp)); - pr_ld = rows_pitch(pp, 2 * n_cand, &Mp); + pr_ld = r4d_rows_pitch(pp, 2 * n_cand, &Mp); if (pr_ld < 0) return R4D_NO(RAD_E_STRIDE); if (Mp < M) return R4D_NO(RAD_E_SHAPE); } const long long voff = r4d_pgeti_or(a->p, a->n_p, "vocab_off", 0); - R4D_LAUNCH(r4d_sample_topk_f32(r4d_addr(lg), r4d_addr(pr), r4d_addr(ci), r4d_addr(cv), - pp ? r4d_addr(pp) : 0, - (int)M, (int)nv, (int)n_cand, (int)ld, (int)ci_ld, (int)cv_ld, - (int)pr_ld, (int)voff, (long)(uintptr_t)s)); + return r4d_sample_topk_f32(r4d_addr(lg), r4d_addr(pr), r4d_addr(ci), r4d_addr(cv), + pp ? r4d_addr(pp) : 0, + (int)M, (int)nv, (int)n_cand, (int)ld, (int)ci_ld, (int)cv_ld, + (int)pr_ld, (int)voff, (long)(uintptr_t)s); } /* ------------------------------------------------------------------ the narrowing stages */ @@ -1481,15 +1399,15 @@ static int narrow(const RadArgs* a, int which, RadStream s) { const long long n_cand = r4d_geti_or(a, "n_cand", r4d_dim(ci, (int)ci->rank - 1)); if (n_cand <= 0) return R4D_NO(RAD_E_SHAPE); long long M = 0, Mv = 0; - const long long ci_ld = rows_pitch(ci, n_cand, &M); - const long long cv_ld = rows_pitch(cv, n_cand, &Mv); + const long long ci_ld = r4d_rows_pitch(ci, n_cand, &M); + const long long cv_ld = r4d_rows_pitch(cv, n_cand, &Mv); if (ci_ld < 0 || cv_ld < 0) return R4D_NO(RAD_E_STRIDE); if (M <= 0 || Mv < M) return R4D_NO(RAD_E_SHAPE); R4D_NEED(params_ok(pr, M)); - R4D_LAUNCH(r4d_sample_narrow_f32(r4d_addr(ci), r4d_addr(cv), r4d_addr(pr), (int)M, - (int)n_cand, which, (int)ci_ld, (int)cv_ld, - (long)(uintptr_t)s)); + return r4d_sample_narrow_f32(r4d_addr(ci), r4d_addr(cv), r4d_addr(pr), (int)M, + (int)n_cand, which, (int)ci_ld, (int)cv_ld, + (long)(uintptr_t)s); } extern "C" int r4d_rad_sample_topp(const RadArgs* a, RadStream s) { return narrow(a, 0, s); } @@ -1515,15 +1433,15 @@ extern "C" int r4d_rad_sample_pick(const RadArgs* a, RadStream s) { const long long n_cand = r4d_geti_or(a, "n_cand", r4d_dim(ci, (int)ci->rank - 1)); if (n_cand <= 0) return R4D_NO(RAD_E_SHAPE); long long M = 0, Mv = 0; - const long long ci_ld = rows_pitch(ci, n_cand, &M); - const long long cv_ld = rows_pitch(cv, n_cand, &Mv); + const long long ci_ld = r4d_rows_pitch(ci, n_cand, &M); + const long long cv_ld = r4d_rows_pitch(cv, n_cand, &Mv); if (ci_ld < 0 || cv_ld < 0) return R4D_NO(RAD_E_STRIDE); if (M <= 0 || Mv < M || r4d_numel(tok) < M) return R4D_NO(RAD_E_SHAPE); R4D_NEED(params_ok(pr, M)); - R4D_LAUNCH(r4d_sample_pick_f32(r4d_addr(ci), r4d_addr(cv), r4d_addr(pr), r4d_addr(tok), - (int)M, (int)n_cand, (int)ci_ld, (int)cv_ld, - (long)(uintptr_t)s)); + return r4d_sample_pick_f32(r4d_addr(ci), r4d_addr(cv), r4d_addr(pr), r4d_addr(tok), + (int)M, (int)n_cand, (int)ci_ld, (int)cv_ld, + (long)(uintptr_t)s); } /* ------------------------------------------------------------------ merge_topk */ @@ -1535,15 +1453,10 @@ extern "C" int r4d_rad_sample_merge_topk(const RadArgs* a, RadStream s) { const RadTensor* pr = r4d_opt(a, MG_PARAMS); const RadTensor* ci = r4d_opt(a, MG_CI); const RadTensor* cv = r4d_opt(a, MG_CV); - /* `params` carries the row's top_k, and the merge is the one place that can re-apply it: - * each rank narrowed to k before the gather, so the merged set holds world_size * k - * candidates and no later stage narrows again. At k = 1 -- which is what - * a greedy row is staged at, precisely so the chain returns the argmax -- leaving two alive - * makes `sample_pick` draw between them against the request's seed. */ + /* `params` carries the row's top_k, which the merge re-applies (see merge_topk_kernel). */ if (!gt || !pr || !ci || !cv) return R4D_NO(RAD_E_INVAL); - /* Each gathered entry is a (u32 id, f32 logit) PAIR IN ONE BUFFER, so the two halves have - * different types and the buffer's dtype can only be one of them. It is a word type and the - * logit is read by BIT PATTERN. */ + /* Each gathered entry is a (u32 id, f32 logit) pair in one buffer, so the dtype is a word type + * and the logit is read by bit pattern. */ R4D_NEED(dt_i32(gt)); R4D_NEED(dt_i32(ci)); R4D_NEED(dt_f32(cv)); @@ -1552,16 +1465,16 @@ extern "C" int r4d_rad_sample_merge_topk(const RadArgs* a, RadStream s) { const long long n_cand = r4d_geti_or(a, "n_cand", r4d_dim(ci, (int)ci->rank - 1)); if (n_cand <= 0) return R4D_NO(RAD_E_SHAPE); long long M = 0, Mv = 0; - const long long ci_ld = rows_pitch(ci, n_cand, &M); - const long long cv_ld = rows_pitch(cv, n_cand, &Mv); + const long long ci_ld = r4d_rows_pitch(ci, n_cand, &M); + const long long cv_ld = r4d_rows_pitch(cv, n_cand, &Mv); if (ci_ld < 0 || cv_ld < 0) return R4D_NO(RAD_E_STRIDE); if (M <= 0 || Mv < M) return R4D_NO(RAD_E_SHAPE); const long long per_row = r4d_numel(gt) / M; const long long n_in = per_row / 2; - if (n_in <= 0 || n_in > r4d_sample_max_cand()) return R4D_NO(RAD_E_SHAPE); + if (n_in <= 0 || n_in > (int)kMaxCand) return R4D_NO(RAD_E_SHAPE); - R4D_LAUNCH(r4d_sample_merge_topk_f32(r4d_addr(gt), r4d_addr(pr), r4d_addr(ci), r4d_addr(cv), - (int)M, (int)n_in, (int)n_cand, (int)per_row, (int)ci_ld, - (int)cv_ld, (long)(uintptr_t)s)); + return r4d_sample_merge_topk_f32(r4d_addr(gt), r4d_addr(pr), r4d_addr(ci), r4d_addr(cv), + (int)M, (int)n_in, (int)n_cand, (int)per_row, (int)ci_ld, + (int)cv_ld, (long)(uintptr_t)s); } diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 00ae7bbd..7afab208 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -1,46 +1,35 @@ /* r4d_selftest -- dump the libr4d row table, cross-check it, and prove every row links and runs. * - * A transcription error in a constraint table is invisible until a model silently picks the wrong - * kernel, which is exactly the failure this project exists to make impossible. So the table is - * printed in full and then checked against itself: + * A transcription error in a constraint table stays invisible until a model silently picks the + * wrong kernel. So the table is printed in full and checked against itself: * - * - every row's `op` has a schema declared by this plugin, or nothing can ever select it; - * - every CONSTRAINT KEY is a declared parameter of that op. This is the check that earns its - * keep: libr4d's select() has its own parameter vocabulary and radiance's schemas are - * docs/OPS.md's, so a key that was renamed in one place and not the other produces a row that - * matches nothing and reports nothing; + * - every row's `op` has a schema declared by this plugin, or nothing can select it; + * - every constraint key is a declared parameter of that op. libr4d's select() and radiance's + * schemas (docs/OPS.md) use different vocabularies, and a key renamed in only one place + * yields a row that matches nothing; * - names are unique, launches exist, an init has a fini, a declared variant list is non-empty. * - * Then, on a device: every launch is called once with a minimal valid input, so a linkage error, a - * missing libr4d symbol or an argument-order mistake surfaces here rather than in a serve. Two of - * these are real numerical checks rather than smoke tests, because they are cheap and because they - * cover the two things most likely to be silently wrong: + * Then, on a device, every launch is called with a minimal valid input, so a linkage error, a + * missing libr4d symbol or an argument-order mistake surfaces here rather than in a serve. Some + * cases are real numerical checks, e.g.: * - * - the W4 weight arrangement, checked against libr4d's own dequant (`dequant_w4_bf16` undoes - * the fragment order), so the host relayout and the device kernel have to agree; - * - the two-rank all-reduce, run across two real cards through the plugin's init/fini - * rendezvous, with a known sum. That exercises the peer handshake, which cannot be tested any - * other way. + * - the W4 weight arrangement against libr4d's own dequant (`dequant_w4_bf16` undoes the + * fragment order), so the host relayout and the device kernel must agree; + * - the two-rank all-reduce across two real cards through the plugin's init/fini rendezvous, + * with a known sum: the only test of the peer handshake. * - * The plugin is dlopened rather than linked, because an undefined symbol in the .so is itself one - * of the failures worth catching. + * The plugin is dlopened rather than linked, so an undefined symbol in the .so is caught too. * - * ONE CHILD PROCESS PER ROW. A bad pointer handed to a kernel is a GPU page fault, and a GPU page - * fault is not an error code -- the ROCr runtime prints one line to stderr and aborts the process - * where it stands. In a single process that means the FIRST bad row ends the run and every row - * after it reports nothing, which is the opposite of what a catalogue check is for; worse, stdout - * is block-buffered down a pipe, so the abort interleaves the fault line into whatever was still - * in the buffer and the row it lands next to is not the row that faulted -- a fault that reads as - * `quant_act_i8`'s can belong to a row twenty earlier. + * One child process per row. A bad pointer handed to a kernel is a GPU page fault, which ROCr + * reports by printing a line and aborting the process. In one process the first bad row would end + * the run, and with stdout block-buffered down a pipe the fault line can land next to the wrong + * row. So the parent runs the static phase and then re-execs itself once per row with + * `--case `; a child killed by a signal is a FAIL naming the signal, and the run continues. + * posix_spawn rather than fork, because the parent already has the HIP runtime's threads up and + * only exec resets them. The row list is the plugin's own table, so a row without a smoke case + * reports `no smoke case`. * - * So the parent runs the static phase and then re-execs ITSELF once per row with `--case `, - * and reports the child's exit status: a signal is a FAIL naming the signal, and the run - * continues. posix_spawn rather than a bare fork, because the parent has the HIP runtime and its - * threads up by then and only exec resets them. The row list is the plugin's own row table, so a - * row nobody wrote a smoke case for reports `no smoke case` rather than being silently absent -- - * the coverage check falls out of the isolation for free. - * - * `--case ` is also the reproducer: it runs exactly one row, alone, in the foreground. + * `--case ` is also the reproducer: it runs one row, alone, in the foreground. */ #include "rad_abi.h" @@ -69,7 +58,7 @@ #include #include -/* posix_spawn's environment. Declared here rather than relying on unistd.h's _GNU_SOURCE guard. */ +/* posix_spawn's environment; declared here rather than relying on unistd.h's _GNU_SOURCE guard. */ extern char** environ; #ifdef RAD_HAVE_HIP @@ -82,13 +71,7 @@ static int g_skip = 0; /* The row this process was asked to run, or null for the parent. Set from --case. */ static const char* g_case = nullptr; -/* This binary and the plugin it was given, so a case that needs a process of its own can ask for - * one. A kernel that reads its configuration from the environment caches the answer, which makes - * two settings of it two processes whatever else is true. */ -static const char* g_exe = nullptr; -static const char* g_plugin = nullptr; -/* Whether any case block claimed g_case. A row the sweep never mentions is a coverage hole and - * says so, rather than exiting 0 having done nothing. */ +/* Whether any case block claimed g_case; a row no case mentions is reported as a coverage hole. */ static bool g_matched = false; static bool sel(const char* name) { @@ -98,8 +81,8 @@ static bool sel(const char* name) { return true; } -/* Exit codes the child speaks: 0 clean, 1 at least one FAIL, 2 nothing but skips. Anything else, - * or a signal, is the child dying where it stood and is a FAIL the parent attributes by name. */ +/* Child exit codes: 0 clean, 1 at least one FAIL, 2 only skips. Anything else, or a signal, is a + * crash, which the parent reports as a FAIL for that row. */ enum { CH_OK = 0, CH_FAIL = 1, CH_SKIP = 2 }; static void ok(const char* what, bool cond, const std::string& detail = std::string()) { @@ -123,27 +106,6 @@ static std::string fmt(const char* f, ...) { return b; } -/* Re-exec this binary on one case with the anchor state form selected, and hand back the exit - * status the way the row driver does. The state form is read from the environment once per process - * and cached, so the per-candidate smoke case and the anchor check cannot share one: the choice is - * made before either of them can ask for it. */ -static int spawn_anchor_child(const char* case_name) { - std::vector env; - for (char** e = environ; *e; ++e) - if (std::strncmp(*e, "RADIANCE_GDN_ANCHOR=", 20) != 0) env.push_back(*e); - char on[] = "RADIANCE_GDN_ANCHOR=1"; - env.push_back(on); - env.push_back(nullptr); - char* const argv[] = { const_cast(g_exe), const_cast(g_plugin), - const_cast("--case"), const_cast(case_name), nullptr }; - pid_t pid = 0; - if (posix_spawn(&pid, g_exe, nullptr, nullptr, argv, env.data()) != 0) return -1; - int st = 0; - if (waitpid(pid, &st, 0) < 0) return -1; - std::fflush(stdout); - if (WIFSIGNALED(st)) return 128 + WTERMSIG(st); - return WIFEXITED(st) ? WEXITSTATUS(st) : -1; -} /* ------------------------------------------------------------------ the plugin surface */ @@ -156,8 +118,8 @@ struct Plugin { const RadOpSchema* (*schema_at)(int) = nullptr; int (*kernel_count)(void) = nullptr; const RadKernelInfo* (*kernel_at)(int) = nullptr; - /* A TEST HOOK and not part of the plugin ABI -- libr4d's own, resolved out of the same .so. - * r4d.h says why the wave count cannot be compared any other way. */ + /* Test hooks, not part of the plugin ABI: libr4d's own, resolved from the same .so. r4d.h + * explains why the wave count cannot be compared any other way. */ void (*pin_mw)(int) = nullptr; void (*pin_nt)(int) = nullptr; void (*pin_qsa)(int) = nullptr; @@ -168,6 +130,7 @@ struct Plugin { void (*pin_ddec)(int) = nullptr; void (*pin_hc)(int) = nullptr; void (*pin_qsel)(int) = nullptr; + int (*record)(const void**, int) = nullptr; }; /* Defined after the tiny-tensor helpers it needs; called from the static checks above them. */ @@ -202,6 +165,7 @@ static bool load(Plugin* pl, const char* path) { okall &= sym(pl->h, "r4d_moe_gemm_pin_down_dec", &pl->pin_ddec); okall &= sym(pl->h, "r4d_hc_read_pin_prefill", &pl->pin_hc); okall &= sym(pl->h, "r4d_qsa_select_pin_form", &pl->pin_qsel); + okall &= sym(pl->h, "r4d_record_dispatches", &pl->record); return okall; } @@ -301,17 +265,14 @@ static void cross_check(const Plugin& pl) { const RadKernelInfo* r = pl.kernel_at(k); if (!r->launch) { ++no_launch; continue; } if (r->init && !r->fini) ++init_no_fini; - /* EVERY ROW IS DEVICE DOMAIN. This library is a device kernel library and a stray host - * row would be a step that silently leaves the card -- which is why the check exists. + /* Every row is device domain; a stray host row would silently move a step off the card. * Host kernels are libavx's. */ if (r->domain != RAD_DOMAIN_DEVICE) { ++bad_domain; keydetail += std::string(r->name) + " is not RAD_DOMAIN_DEVICE; "; } - /* EVERY AXIS CARRIES A DEFAULT AND THE DEFAULT IS ONE OF ITS OWN VALUES. The loader - * refuses a plugin that breaks this, by name, so a deployment can never run an axis with - * no legal fallback -- but the loader's refusal is a startup failure, and this is the - * check that tells the author which row and which key at the moment they add it. */ + /* Every axis's default is one of its own values. The loader also refuses a plugin that + * breaks this, but at startup; this names the row and key at authoring time. */ for (int v = 0; v < r->n_tunables; ++v) { const RadTunable& t = r->tunables[v]; if (!t.key || !t.key[0] || !t.values || t.n_values < 1) { @@ -344,9 +305,9 @@ static void cross_check(const Plugin& pl) { keydetail += std::string(r->name) + " has no schema for op '" + r->op + "'; "; continue; } - /* THE CHECK THAT EARNS ITS KEEP. A constraint on a key the op does not declare can never - * be satisfied, so the row is unreachable and nothing says so. A "device." key is not a - * parameter at all: it is matched against the machine (rad_types.h). */ + /* A constraint on a key the op does not declare can never be satisfied, so the row is + * silently unreachable. A "device." key is not a parameter: it is matched against the + * machine (rad_types.h). */ static const size_t kFact = std::strlen(RAD_DEVICE_FACT_PREFIX); for (int c = 0; c < r->n_constraints; ++c) { if (!std::strncmp(r->constraints[c].key, RAD_DEVICE_FACT_PREFIX, kFact)) continue; @@ -359,12 +320,10 @@ static void cross_check(const Plugin& pl) { "' which op '" + r->op + "' does not declare; "; } } - /* EVERY MULTI-CARD ROW STATES THE TRANSPORT IT NEEDS. A kernel in this library that runs - * only at two or more ranks either reads and writes the other cards' memory directly and - * requires device.p2p == 1, or is a host twin whose mailbox is pinned host memory and - * requires device.p2p == 0. Without the key, a machine whose cards cannot reach each other - * resolves a P2P kernel and the launch faults or hangs instead of being refused by name at - * selection; and a host twin without it would compete with its original where P2P works. */ + /* Every multi-card row states its transport: device.p2p == 1 for a kernel that accesses + * peer memory directly, device.p2p == 0 for a host twin with a pinned host mailbox. + * Without it, a machine without P2P would resolve a P2P kernel that faults or hangs, and + * a host twin would compete with its original where P2P works. */ bool multi = false, p2p = false; for (int c = 0; c < r->n_constraints; ++c) { const RadConstraint& rc = r->constraints[c]; @@ -423,24 +382,14 @@ static int64_t g_cold = 0; #ifdef RAD_HAVE_HIP -/* EVERY hipError_t IN THIS FILE IS CHECKED, and that is not pedantry about a `nodiscard`. A - * dropped device-to-host hipMemcpy is exactly how a correctness harness reports PASS on memory the - * device never wrote: a kernel that faults leaves its error sticky on the next HIP call, so the - * copy meant to bring the answer back fails and the comparison runs on whatever the host buffer - * already held. Fresh, that is zeros and the case fails loudly. REUSED -- one allocation and a - * loop over geometries, which is the normal shape in this file -- it still holds the PREVIOUS - * geometry's correct answer, and the case passes. +/* Every hipError_t in this file is checked. A kernel fault leaves a sticky error, so the + * device-to-host copy of the answer fails; unchecked, the comparison then runs on stale host + * memory, which in a loop over geometries holds the previous geometry's correct answer and passes. * - * Forwarding macros rather than a wrapper function, so every call site stays an ordinary call and - * __LINE__ comes for free. The failure goes through `g_fail`, which every one of main()'s four - * exit paths already returns, so nothing downstream needs to know about this. - * - * AND IT RETURNS int, NOT hipError_t. ROCm puts the `nodiscard` on the TYPE -- `typedef enum - * __HIP_NODISCARD hipError_t` -- not on the individual functions, so ANY expression of that type - * whose value is dropped warns, this wrapper's own return included; returning hipError_t here - * would move every one of those warnings onto the ten #define lines below instead of removing - * them. `hipSuccess` is 0 and an enum promotes, so the handful of sites that do test the result - * read unchanged. */ + * Forwarding macros keep call sites ordinary and supply __LINE__; failures count in `g_fail`, + * which main() returns. The wrapper returns int, not hipError_t: ROCm puts `nodiscard` on the type + * itself, so a hipError_t return would warn at every macro. hipSuccess is 0, so sites that test the + * result read unchanged. */ static int hip_ck(hipError_t e, const char* what, int line) { if (e != hipSuccess) { std::printf(" FAIL %s at r4d_selftest.cpp:%d: %s\n", what, line, hipGetErrorString(e)); @@ -474,19 +423,16 @@ static void* dalloc(size_t bytes) { return p; } -/* ---- THE TIMED WINDOW, WARM OR COLD (--cold MIB). +/* ---- the timed window, warm or cold (--cold MIB). * * Warm, a perf mode launches `iters` times back to back on one set of operands, so a weight that - * fits in L2 (8 MiB here) or the last-level cache (64 MiB) is read from cache after the first - * launch: --perfmoe's whole expert set times at ten thousand GB/s "of weight", sixteen times what - * the part's DRAM delivers. The engine streams its weights cold every step, and a change in how a - * kernel waits on memory can look free warm and cost microseconds there. + * fits in L2 (8 MiB) or the last-level cache (64 MiB) is read from cache after the first launch, + * unlike in the engine, which streams weights cold every step. * - * Cold, every launch is preceded by a read of g_cold bytes through the hierarchy and timed alone - * between two events, and the median launch is the figure. The read is device copies into one - * kColdChunk destination: copied in full, the span would leave that many dirty lines for the - * timed launch to write back, which inflates exactly the bandwidth-bound kernels this mode is for. - * The flush buffers are allocated outside dalloc because dfree_all runs between shapes. */ + * Cold, each launch follows a read of g_cold bytes through the hierarchy and is timed alone between + * two events; the median is reported. The read copies into one kColdChunk destination, since + * copying the full span would leave dirty lines for the timed launch to write back. The flush + * buffers live outside dalloc because dfree_all runs between shapes. */ constexpr int64_t kColdChunk = 4ll << 20; template @@ -548,10 +494,10 @@ static RadTensor T(void* d, uint32_t dt, std::vector shape) { return t; } -/* moe_gemm_q TAKES ITS EXPERTS AS TWO TABLES BY PARITY (operands 2/3 even, 6/7 odd). A stacked - * plane holding every expert in order is both at once: the even entries at twice its leading - * stride, and the odd ones the same from one plane in. `wbits`/`sbits` are the two planes' - * element widths, which a plugin-private dtype cannot be asked for. */ +/* moe_gemm_q takes its experts as two tables by parity (operands 2/3 even, 6/7 odd). A stacked + * plane of every expert is both: the even entries at twice its leading stride, the odd ones the + * same from one entry in. `wbits`/`sbits` are the planes' element widths, which a plugin-private + * dtype cannot report. */ static void moe_parity_tables(std::vector& ts, int64_t ne, int wbits, int sbits) { const RadTensor w = ts[2], s = ts[3]; RadTensor wo = w, so = s; @@ -568,16 +514,12 @@ static void moe_parity_tables(std::vector& ts, int64_t ne, int wbits, ts.insert(ts.end() - 1, so); } -/* An ABSENT optional operand is a null `data`, not a zero rank -- r4d_opt() keys on the pointer - * (rad_abi.h) and a shim reading a rank-0 tensor whose data still points at the last allocation - * takes the present branch on an operand the test meant to withhold. Clearing rank alone leaves - * quant_act_i8's plain form re-running the asum form. */ +/* An absent optional operand is a null `data`, not a zero rank: r4d_opt() keys on the pointer + * (rad_abi.h), so clearing only the rank would still take the present branch. */ static void absent(RadTensor& t) { t.data = nullptr; t.rank = 0; } -/* Cumulative sequence lengths, on the device. Every gdn kernel opens with `bos = cu[n]` and - * `T = cu[n+1] - bos`, so a cu of zeros -- which is what dalloc hands back -- means T == 0 for - * every sequence and the whole grid returns before it touches an operand. That is a launch that - * proves nothing, so the smoke tests fill it. */ +/* Fills an i32 device buffer, e.g. cumulative sequence lengths. A zeroed cu (as dalloc returns) + * means T == 0 for every sequence and the gdn kernels exit immediately, so smoke tests fill it. */ static void fill_i32(void* d, const std::vector& v) { st_memcpy(d, v.data(), v.size() * sizeof(int32_t), hipMemcpyHostToDevice); } @@ -596,17 +538,16 @@ static RadParam PS(const char* k, const char* v) { RadParam p; std::memset(&p, 0, sizeof(p)); p.key = k; p.kind = RAD_P_STR; p.sval = v; return p; } -/* A real-valued parameter. These are RAD_P_F64 in the schemas (docs/OPS.md), and the point of - * spelling them that way here is that this file feeds the launches DIRECTLY -- there is no declare - * in front of it to catch a kind mismatch, so a case that passed them as strings would silently - * take the shim's default instead of the value it names. */ +/* A real-valued parameter, RAD_P_F64 as in the schemas (docs/OPS.md). This file calls launches + * directly with no declare to catch a kind mismatch, so a string would silently fall back to the + * shim's default. */ static RadParam PF(const char* k, double v) { RadParam p; std::memset(&p, 0, sizeof(p)); p.key = k; p.kind = RAD_P_F64; p.dval = v; return p; } -/* Bytes per element for the dtypes this file allocates. Deliberately local: the core's - * rad_dtype_bytes is not linkable from here (see the note in r4d_plugin.h). */ +/* Bytes per element for the dtypes this file allocates. Local because the core's rad_dtype_bytes + * is not linkable from here (r4d_plugin.h). */ static size_t esz(uint32_t dt) { switch (dt) { case RAD_F32: case RAD_I32: case RAD_U32: return 4; @@ -629,11 +570,9 @@ static void* alloc_for(const RadTensor& t) { return dalloc((size_t)n * esz(t.dtype)); } -/* An i32 operand whose CONTENTS matter -- cu, state_idx, num_accepted. run_case allocates what is - * still null and dalloc zeroes it, and a zero is a wrong answer for all three: a zero cu means - * every sequence has no tokens and the grid exits before touching an operand, and a zero - * num_accepted makes the recurrent update read column `nacc - 1` == -1 of its state-index row. - * So these are built and filled here, before run_case sees them. */ +/* An i32 operand whose contents matter (cu, state_idx, num_accepted), built and filled before + * run_case, which would otherwise zero it. A zero cu means no tokens, and a zero num_accepted + * makes the recurrent update read column -1 of its state-index row. */ static RadTensor TI32(const std::vector& shape, const std::vector& v) { RadTensor t = T(nullptr, RAD_I32, shape); t.data = alloc_for(t); @@ -646,9 +585,8 @@ static std::vector rep_i32(int64_t n, int32_t v) { return std::vector((size_t)n, v); } -/* An f32 operand filled with one value. The attention descales are the case: dalloc zeroes, a zero - * descale scales every score to zero, and a uniform softmax over a zeroed cache is a launch that - * would pass with the dequantise multiply deleted. */ +/* An f32 operand filled with one value, e.g. attention descales: a zero descale would zero every + * score, and a uniform softmax would pass even with the dequantise multiply deleted. */ static RadTensor TF32(const std::vector& shape, float v) { RadTensor t = T(nullptr, RAD_F32, shape); t.data = alloc_for(t); @@ -668,18 +606,12 @@ static std::vector iota_i32(int64_t n) { /* ------------------------------------------------------------------ the tuning space * - * A row declares AXES and one point in their cross product is one instantiation of the kernel. - * This enumerates that product the way the core does at tune time -- all-defaults first, so a - * sweep's first line is what an untuned install runs, then every other legal point -- and asks - * the row's own tune_valid to prune the combinations no geometry can serve. - * - * THE SELFTEST ENUMERATES RATHER THAN LISTING, for the same reason rows declare their space rather - * than naming a table of points: a hand-kept list in a harness drifts from the plugin it is - * testing, and drifts silently, because a missing point looks exactly like a point that was never - * fast. */ -/* How many points an INTERACTIVE sweep walks. rad-tune walks the whole space; a --perfbf16 that - * printed four hundred lines at 400 iterations each would be a different tool. Raise it with - * R4D_PERF_POINTS when a specific axis needs the whole ladder. */ + * A row declares axes; one point in their cross product is one instantiation of the kernel. This + * enumerates the product as the core does at tune time (all-defaults first, so a sweep's first + * line is what an untuned install runs) and prunes points with the row's own tune_valid. + * Enumerating rather than listing points keeps the harness from drifting from the plugin. */ +/* How many points an interactive sweep walks (rad-tune walks the whole space). Raise it with + * R4D_PERF_POINTS when an axis needs the whole ladder. */ static const size_t kPerfCap = [] { const char* e = std::getenv("R4D_PERF_POINTS"); const long v = (e && *e) ? std::strtol(e, nullptr, 10) : 0; @@ -714,8 +646,7 @@ static std::vector tune_points(const RadKernelInfo* r, const std::vec r->tune_valid(geom.data(), (int)geom.size(), tp.choice.data(), (int)tp.choice.size()); if (legal) { - /* The all-defaults point goes FIRST wherever it lands in the odometer: a sweep is read - * top-down and the baseline has to be the first line or every delta is eyeballed. */ + /* The all-defaults point goes first, so a sweep's baseline is its first line. */ int is_deflt = 1; for (int i = 0; i < n; ++i) if (tp.choice[(size_t)i].ival != r->tunables[i].deflt) { is_deflt = 0; break; } @@ -731,9 +662,7 @@ static std::vector tune_points(const RadKernelInfo* r, const std::vec return out; } -/* Append a point's choices to a case's parameters. This is exactly what the core does at issue: - * the chosen values arrive as ordinary parameters and the launch reads `sk` with the same - * rad_args_geti() it reads `M` with. */ +/* Appends a point's choices to a case's parameters, as the core does at issue. */ static std::vector with_point(const std::vector& ps, const TunePoint& tp) { std::vector out = ps; out.insert(out.end(), tp.choice.begin(), tp.choice.end()); @@ -784,11 +713,9 @@ static void attn_case(const Plugin& pl, const char* name, int64_t head_dim, int6 const int64_t seqs = 2, kv_heads = 2, blocks = 8, bs = 16; const int64_t q_heads = kv_heads * gqa, total_q = seqs * q_len; const uint32_t kvdt = std::strcmp(kv_dtype, "bf16") == 0 ? RAD_BF16 : RAD_F8E4M3; - /* One disjoint run of blocks per sequence, and a context that fills them. Both operands are - * i32 and dalloc zeroes: a zeroed block table points every sequence at block 0, so the two - * race on one slot, and a zeroed seqused is no context at all -- the decode grid's `live` and - * the prefill grid's `qb * BLOCK_Q >= qlen` both exit on the first comparison, which is a - * launch that proves the kernel starts and nothing else. */ + /* One disjoint run of blocks per sequence, and a context that fills them. Zeroed (as dalloc + * returns), the block table would point every sequence at block 0, and seqused would mean no + * context, so both grids would exit at once. */ const int64_t max_blocks = blocks / seqs, ctx = max_blocks * bs; std::vector ts = { @@ -798,10 +725,8 @@ static void attn_case(const Plugin& pl, const char* name, int64_t head_dim, int6 TI32({ seqs }, rep_i32(seqs, (int32_t)ctx)), TF32({ seqs, kv_heads }, 1.0f), TF32({ seqs, kv_heads }, 1.0f), - /* cu_seqlens. THE OPERAND LIST IS oAttnPaged's AND IT HAS EIGHT SLOTS: leaving this one - * out shifts `out` into it, puts AP_OUT past n_t, and makes fill_paged refuse every row - * with RAD_E_INVAL -- which reads as kernels that do not work. Absent is the uniform - * batch, which is what this case is. */ + /* cu_seqlens. oAttnPaged has eight slots; omitting this one would shift `out` into it + * and every row would fail with RAD_E_INVAL. Absent means a uniform batch, as here. */ T(nullptr, RAD_I32, { seqs + 1 }), T(nullptr, RAD_BF16, { total_q, q_heads, head_dim }), }; @@ -841,10 +766,9 @@ static void gemm_case(const Plugin& pl, const char* name, const char* dtype, int /* ================================================================== the block-scaled fp8 family * - * The gemm_case helper above hands `b` and `b_scale` as flat U8 buffers, which the fp8 shim - * refuses: it checks the scale plane's own extents, because that is the operand a converter is most - * likely to hand over at the wrong grid and a wrong grid reads a plausible number. So the fp8 rows - * get their own builder, with the [N][K] and [ceil(N/128)][ceil(K/128)] shapes spelled out. */ + * The gemm_case helper hands `b` and `b_scale` as flat U8 buffers, which the fp8 shim refuses: it + * checks the scale plane's extents, since a scale at the wrong grid reads plausible numbers. So the + * fp8 rows get their own builder with [N][K] and [ceil(N/128)][ceil(K/128)] shapes. */ static void fp8_gemm_case(const Plugin& pl, const char* name, const char* dtype, int64_t M, int64_t N, int64_t K, int need_ascale, const TunePoint* tp = nullptr) { @@ -881,8 +805,8 @@ static uint16_t h_to_bf16(float f) { uint32_t u; std::memcpy(&u, &f, 4); return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); } -/* E4M3 -> f32, the software form. Exponent 0 is subnormal (no implicit leading one). This is the - * ORACLE for the device's v_cvt_f32_fp8, so it is written from the format and not from the kernel. */ +/* E4M3 -> f32 in software; exponent 0 is subnormal (no implicit leading one). The oracle for the + * device's v_cvt_f32_fp8, so it is written from the format, not from the kernel. */ static float h_e4m3(uint8_t b) { const float sign = (b & 0x80u) ? -1.0f : 1.0f; const uint32_t ex = (uint32_t)(b >> 3) & 0x0Fu, mn = (uint32_t)b & 0x07u; @@ -899,11 +823,9 @@ static uint16_t st_rand_bf16(uint32_t i) { } static uint8_t st_rand_e4m3(uint32_t i) { const uint32_t x = st_mix32(i + 0x9e3779b9u); - /* Bounded to [-1, 1] (the positive magnitudes below), mirroring st_rand_bf16. The full e4m3 - * range (up to 448) makes the attention scores reach ~448*head_dim/sqrt(head_dim), so the - * softmax dominates by e^score and a 1-ulp difference between the device's v_cvt_f32_fp8 and - * this software h_e4m3 flips the max into a large output error; bounded, the scores stay ~22 - * (the passing bf16 path) and the comparison is stable. */ + /* Bounded to [-1, 1] like st_rand_bf16. With the full e4m3 range (up to 448) the attention + * scores grow so large that a 1-ulp difference between v_cvt_f32_fp8 and h_e4m3 flips the + * softmax max into a large output error; bounded, the scores stay near 22. */ static const uint8_t mag[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* subnormal, 0 .. 7/64 */ 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, /* exp 4, 0.125 .. 0.234375 */ @@ -915,11 +837,10 @@ static uint8_t st_rand_e4m3(uint32_t i) { return (uint8_t)(m | (((x >> 8) & 1u) << 7)); } -/* The inline paged-attention oracle: a port of ref_attn_paged (libref/ref_attn.cpp) for the - * uniform batch, bf16 q, fp8-e4m3 or bf16 k/v, f32 descales. The selftest does not link libref, - * so the reference the kbench byte-equality uses is carried here; the mask, the two-pass softmax - * and the k/v dequant are the same, so a wrong kernel fails the comparison. One (row, head) at a - * time: `i` is the query's position within its sequence's query, and `pos = ctx - qlen + i`. */ +/* Inline paged-attention oracle: a port of ref_attn_paged (libref/ref_attn.cpp) for the uniform + * batch, bf16 q, fp8-e4m3 or bf16 k/v, f32 descales, with the same mask, two-pass softmax and k/v + * dequant (the selftest does not link libref). One (row, head) at a time: `i` is the query's index + * within its sequence's query, and `pos = ctx - qlen + i`. */ static void attn_oracle_one(const uint16_t* qh, const uint8_t* kv, int kv_is_fp8, int64_t head_dim, int64_t kv_heads, int64_t block_size, int64_t kh, const int* block_table, int64_t max_blocks, int ctx, @@ -973,10 +894,9 @@ static void attn_oracle_one(const uint16_t* qh, const uint8_t* kv, int kv_is_fp8 for (int64_t d = 0; d < head_dim; ++d) out[d] *= inv; } -/* The numeric attention check: fill q and the paged k/v with avalanche-random data, run the row, - * and compare the bf16 output against the inline oracle above. The launch smoke (attn_case) proves - * the kernel starts; this proves it computes. A negative control corrupts a share of the reference - * and requires the comparison to FAIL -- the proof the check has teeth. */ +/* Numeric attention check: fill q and the paged k/v with avalanche-random data, run the row, and + * compare the bf16 output against the oracle above. A negative control corrupts part of the + * reference and requires the comparison to fail. */ static void attn_numeric_case(const Plugin& pl, const char* name, int64_t head_dim, int64_t gqa, int64_t q_len, const char* kv_dtype, int window, int64_t ctx = 64) { if (!sel(name)) return; @@ -1053,8 +973,7 @@ static void attn_numeric_case(const Plugin& pl, const char* name, int64_t head_d ok(nm, nbad == 0, fmt("max_err=%.5g bad=%d/%d", max_err, nbad, (int)oref.size())); - /* Negative control: corrupt a share of the reference and require the comparison to FAIL -- the - * proof the check has teeth, since a broken (always-passing) comparison would flag nothing. */ + /* Negative control: corrupt part of the reference and require the comparison to fail. */ for (size_t idx = 0; idx < oref.size(); ++idx) if ((idx & 7) == 0) oref[idx] += 0.5f; float nmax = 0.0f; int nbadc = 0; @@ -1073,14 +992,12 @@ static void attn_numeric_case(const Plugin& pl, const char* name, int64_t head_d /* ================================================================== a weight's canonical planes * * A container holds a weight as the planes of its encoding, row-major (spec §4.1), and a kernel's - * own layout hooks arrange those into what it reads, at load. The cases below that need a weight - * build its planes here, get the bytes the kernel reads from the ROW'S OWN HOOKS (`stored`), and - * compute their reference from the PLANES -- so the reference is what the weight means, and the - * arrangement is checked by the one reader that matters, the kernel. A reference computed from the - * stored bytes would only repeat the arrangement back to itself. + * layout hooks arrange them at load. Cases build the planes here, get the kernel's bytes from the + * row's own hooks (`stored`), and compute the reference from the planes, so the arrangement is + * checked by the kernel rather than against itself. * - * The quantisation here is the plainest there is (absmax over each scale block) and is not under - * test: what is checked is that the kernel reads the numbers the planes hold. */ + * The quantisation (absmax per scale block) is not under test; what is checked is that the kernel + * reads the numbers the planes hold. */ struct Planes { RadEncoding enc{}; std::vector> data; /* one per plane of `enc` */ @@ -1111,9 +1028,9 @@ struct Planes { } }; -/* gemm_nt_q's `pb1`/`pb2` over N rows (ParoQuant): rows [0, e1), [e1, e2), [e2, N) meet copies 0, 1, - * 2 of the activation, side by side in a row; `parts` is how many copies there are. 0 leaves a - * bound out, as the kernels read it. */ +/* gemm_nt_q's `pb1`/`pb2` over N rows (ParoQuant): rows [0, e1), [e1, e2), [e2, N) meet + * activation copies 0, 1, 2, side by side in a row; `parts` counts the copies. 0 leaves a bound + * out, as the kernels read it. */ struct PartCut { int64_t e1, e2; int parts; @@ -1124,8 +1041,9 @@ struct PartCut { int part_of(int64_t n) const { return (int)(n >= e1) + (int)(n >= e2); } }; -/* An ASYMMETRIC grid's planes for a [N, K] weight: `bits`-bit codes (a bit stream along K), an f16 - * scale and a u8 zero point 0 .. 2^bits - 1 a 128 of K, drawn through st_mix32 of their coordinates. */ +/* An asymmetric grid's planes for a [N, K] weight: `bits`-bit codes (a bit stream along K), an f16 + * scale and a u8 zero point 0 .. 2^bits - 1 per 128 of K, drawn from st_mix32 of the + * coordinates. */ static Planes asym_planes(int bits, int64_t N, int64_t K) { Planes p; p.enc = rad_enc_affine(bits == 4 ? RAD_U4 : RAD_U5, RAD_F16, 1, 128); @@ -1159,9 +1077,9 @@ static void h_fwht(float* v, int64_t n) { } } -/* Block fp8 over [N, K]: E4M3 codes, and a bf16 scale a 128x128 block that is the block's absmax - * over 448 -- the format the checkpoints ship. Codes are taken against the ROUNDED scale, so code - * times stored scale is the weight the planes describe. */ +/* Block fp8 over [N, K], the checkpoint format: E4M3 codes and a bf16 scale per 128x128 block + * (absmax / 448). Codes are taken against the rounded scale, so code times stored scale is the + * weight the planes describe. */ static Planes fp8_block_planes(const std::vector& w, int64_t N, int64_t K) { Planes p; rad_enc_clear(&p.enc); @@ -1185,11 +1103,11 @@ static Planes fp8_block_planes(const std::vector& w, int64_t N, int64_t K return p; } -/* A symmetric 4-bit grid over [N, K]: i4 codes -8..7 and a scale of dtype `sdt` a row per `group` - * columns, absmax over 7. ROTATED, each group of a row is multiplied by the `group`-wide Hadamard - * first and the stored scale carries the 1/group the rotation leaves -- = group , - * so a kernel that multiplies codes by stored scales against a rotated activation computes the - * unrotated product. The encoding names the rotation, which is what a kernel's hook checks. */ +/* A symmetric 4-bit grid over [N, K]: i4 codes -8..7 and a scale of dtype `sdt` per row per + * `group` columns (absmax / 7). With `rot`, each group is multiplied by the `group`-wide Hadamard + * first and the stored scale carries the residual 1/group ( = group ), so codes + * times scales against a rotated activation give the unrotated product. The encoding names the + * rotation, which the kernel's hook checks. */ static Planes int4_planes(const std::vector& w, int64_t N, int64_t K, int64_t group, uint32_t sdt, bool rot) { Planes p; @@ -1224,9 +1142,9 @@ static Planes int4_planes(const std::vector& w, int64_t N, int64_t K, int return p; } -/* The same rotated grid with libquant's w4nl CODEBOOK: u4 codes indexing a sixteen-entry f32 - * `table` plane holding r4d_args.h's kW4nlTable, a scale of amax over the largest entry (22), the - * nearest entry chosen, and the residual 1/group folded into the stored scale as above. */ +/* The same rotated grid with libquant's w4nl codebook: u4 codes indexing a sixteen-entry f32 + * `table` plane (r4d_args.h's kW4nlTable), scale = amax / largest entry (22), nearest entry chosen, + * residual 1/group folded into the stored scale. */ static Planes nl_planes(const std::vector& w, int64_t N, int64_t K, int64_t group, uint32_t sdt) { Planes p; @@ -1263,12 +1181,11 @@ static Planes nl_planes(const std::vector& w, int64_t N, int64_t K, int64 return p; } -/* The same codebook at w4nl64a8h's scales (`gs` 64) or w4nl32a8h's (32): the weight rotated by 128 - * as above, and each `gs`-column part of a rotated group scaled on its own -- amax over the largest - * entry, residual 1/128 folded in, stored as an E4M3 code under r4d_args.h's fixed kW4G64Scale -- - * with the nearest entry chosen against the scale as stored. Planes: codes, scale (E4M3 - * [1 x gs]), scale.1 (f32, the constant), table. With `w5`, w5nl64a8h's: u5 codes into - * kW5nlTable, whose largest entry is 30. */ +/* The same codebook at w4nl64a8h's scales (`gs` 64) or w4nl32a8h's (32): the weight rotated by 128, + * each `gs`-column part of a rotated group scaled on its own (amax / largest entry, residual 1/128 + * folded in, stored as E4M3 under r4d_args.h's fixed kW4G64Scale), nearest entry chosen against + * the stored scale. Planes: codes, scale (E4M3 [1 x gs]), scale.1 (f32 constant), table. With + * `w5`, w5nl64a8h's: u5 codes into kW5nlTable, whose largest entry is 30. */ static Planes nl64_planes(const std::vector& w, int64_t N, int64_t K, int64_t gs = 64, bool w5 = false) { const float* tab = w5 ? kW5nlTable : kW4nlTable; @@ -1312,9 +1229,9 @@ static Planes nl64_planes(const std::vector& w, int64_t N, int64_t K, int return p; } -/* A symmetric 8-bit grid over [N, K]: i8 codes -127..127 and an f16 scale of amax / 127 a row per - * 128 columns -- what libquant writes for `codes=i8 group=128 scale=f16 clamp=sym`, and the - * encoding the w8a16 layout hook takes. */ +/* A symmetric 8-bit grid over [N, K]: i8 codes -127..127 and an f16 scale of amax / 127 per row per + * 128 columns, as libquant writes for `codes=i8 group=128 scale=f16 clamp=sym` and the w8a16 + * layout hook takes. */ static Planes int8_planes(const std::vector& w, int64_t N, int64_t K) { Planes p; p.enc = rad_enc_affine(RAD_I8, RAD_F16, 1, 128); @@ -1340,9 +1257,8 @@ static int code_at(const Planes& p, int64_t n, int64_t k) { return (int)rad_load_f32(p.data[0].data() + n * p.row_bytes(0), p.enc.plane[0].dtype, k); } -/* The rectangle [r0, r1) x [c0, c1) of a LOGICAL weight, as the planes covering it -- each plane - * cut on its own blocks, the way the loader takes a tensor-parallel rank's share. Byte-wide planes - * only, which is every plane the shards below are taken of. */ +/* The rectangle [r0, r1) x [c0, c1) of a logical weight as the planes covering it, each cut on its + * own blocks as the loader takes a tensor-parallel rank's share. Byte-wide planes only. */ static Planes share(const Planes& p, int64_t r0, int64_t r1, int64_t c0, int64_t c1) { Planes q; q.enc = p.enc; @@ -1365,9 +1281,9 @@ static Planes share(const Planes& p, int64_t r0, int64_t r1, int64_t c0, int64_t return q; } -/* WHAT ROW `r` READS for `operand`, from the planes named `roles`: RAD_OK with its own arrangement - * in `out` (relayout), or RAD_E_UNSUPPORTED with the one selected plane as it is -- a hook's - * "stored as it is", and what a row with no hook gets. Anything else is the hook's refusal. */ +/* What row `r` reads for `operand` from the planes named `roles`: RAD_OK with its arrangement in + * `out` (relayout), or RAD_E_UNSUPPORTED with the one selected plane unchanged (a hook's "stored as + * is", or a row with no hook). Anything else is the hook's refusal. */ static int stored(const RadKernelInfo* r, const std::vector& lp, int operand, const Planes& p, std::initializer_list roles, std::vector* out, RadLayout* lay = nullptr) { @@ -1398,8 +1314,8 @@ static int stored(const RadKernelInfo* r, const std::vector& lp, int o L.bytes); } -/* AND BACK: the row's inverse of `stored`, which must give exactly the planes it was handed. True - * when it does; `why` says what differed, or that the row has no inverse. */ +/* The row's inverse of `stored`, which must give back exactly the planes it was handed. `why` + * says what differed, or that the row has no inverse. */ static bool restores(const RadKernelInfo* r, const std::vector& lp, int operand, const Planes& p, std::initializer_list roles, const std::vector& bytes, std::string* why) { @@ -1430,56 +1346,16 @@ static bool restores(const RadKernelInfo* r, const std::vector& lp, in return true; } -/* kv_store, both widths, AGAINST AN EXACTLY-REPRESENTABLE SET so the check is equality and not a - * tolerance. E4M3 has three mantissa bits, so every value below -- the halves and integers up to 8 - * -- survives a round trip unchanged, and the bf16 path stores them unchanged too. That makes ONE - * expectation serve both rows: `h_e4m3` or `h_bf16` of what landed must equal what went in, - * exactly. A tolerance would pass the two failures this is actually for. - * - * WHAT IT IS FOR. The op scatters into kv_cache[n_blocks, kv_heads, block_size, 2*head_dim] with K - * at [.., d] and V at [.., head_dim + d], addressed by a slot that decomposes as - * (slot / block_size, slot % block_size). That is four indices deep and every one of them is a - * place to be off by a head, a block or a half-row -- and a k/v swap or a head transposition is - * invisible to any test whose values do not distinguish (token, head, dim). These do: the value is - * built from all three, and K and V are given disjoint sign. - * - * THE NEGATIVE AND OUT-OF-RANGE SLOTS ARE THE OTHER HALF OF THE CONTRACT. A pad row must store - * NOTHING -- the scheduler hands them for rows with no request -- so the cache is prefilled with a - * sentinel and those slots are checked to still hold it. `libref` and libr4d agree that zero - * is a REAL slot (r4d_gdn_conv_w4_h128_bf16.hip follows the same rule), so slot 0 is used - * deliberately here rather than avoided. */ - -/* ------------------------------------------------------- the vocab-parallel top-R, end to end - * - * THE PROPERTY IS AN EQUALITY, not a tolerance: a top-R taken over one plane must equal the merge - * of the two half-plane top-Rs, index for index and value for value. That one check covers all - * three pieces at once -- the `vocab_off` shift, the `pairs` plane row_topk writes, and the - * merge -- and it is the property the engine depends on, since a sharded draft head is only - * allowed to be silent if it proposes exactly what the replicated one did. - * - * THE VALUES ARE DELIBERATELY FULL OF TIES, because ties are where a merge stops agreeing. A - * dense top-R breaks them on the lower column, so a merge that broke them on rank order would - * disagree exactly when the same logit appears in both shards -- which, on a 23-value alphabet - * over 2048 columns, is every row. Distinct values would pass either way. - * - * The gathered plane is assembled here the way `all_gather` with `row = R*2` assembles it: rank - * r's R pairs at [r*R, (r+1)*R) of each row. If that interleave is ever spelled differently in - * the graph, this case is what says so. */ - /* ------------------------------------------------- static YaRN, in double * * cos and sin of one rotary pair at one position: the inverse frequency theta^(-2i/rot), blended - * toward inv/factor over the linear ramp [low, high] -- vLLM's YaRNScalingRotaryEmbedding, whose - * correction bounds tests/yarn_test.cpp holds yarn_from to -- and both scaled by the magnitude. - * Computed here, so the YaRN cases need nothing beside this binary. + * toward inv/factor over the linear ramp [low, high] (vLLM's YaRNScalingRotaryEmbedding; its + * correction bounds are held to yarn_from by tests/yarn_test.cpp), both scaled by the magnitude. * - * `tol` IS WHAT AN f32 EVALUATION OF THE SAME FORMULA MAY DIFFER BY. powf, the reciprocal, the - * blend and the product with the position each cost an ulp or so of the ANGLE, so the bound is 8 - * ulp of the angle plus the rounding of the result. Where the ramp sits it is a few 1e-5 even at - * position 524287, so a wrong factor, bound or blend order is far outside it; it is loose only in - * the fastest pairs at long positions, which YaRN leaves unscaled and which no f32 rotary places - * better than its own angle's ulp. A double reference cannot reproduce the device's powf rounding - * there, and a tolerance that pretended to would be a table of this card's answers. */ + * `tol` is how far an f32 evaluation of the same formula may differ: 8 ulp of the angle plus the + * rounding of the result. Where the ramp sits it is a few 1e-5 even at position 524287, so a wrong + * factor, bound or blend order falls far outside it; it is loose only in the fastest pairs at long + * positions, which YaRN leaves unscaled and where f32 cannot do better than the angle's ulp. */ struct YarnRef { double c, s, tol; }; static YarnRef yarn_ref(double pos, int i, int rot, double theta, double factor, double low, double high, double magnitude) { @@ -1498,27 +1374,19 @@ static double yarn_high(int64_t rot) { return rot == 64 ? 22 : rot == 128 ? 43 : /* ------------------------------------------------- the fused attention prologue, against its pair * - * THE QUESTION IS BIT EQUALITY AND NOTHING ELSE. `qk_norm_rope_gate` replaces rmsnorm(q) + - * rmsnorm(k) + rope(q) + rope(k) -- four launches a layer, sixteen layers -- and it is only worth - * having if the model that comes out is the SAME model. Its own header says it rounds the norm - * output to bf16 before rotating for exactly this reason ("skipping that round trip is more - * accurate and would be wrong: it is a different function"), and this is the check that the claim - * holds against the kernels it replaces rather than against an argument. + * Bit equality: `qk_norm_rope_gate` replaces rmsnorm(q) + rmsnorm(k) + rope(q) + rope(k), and + * rounds the norm output to bf16 before rotating so that it computes the same function. * - * THE TABLE IS PART OF THE CLAIM. The fused kernel takes cos/sin instead of theta, so a table - * built with different angles is a different rope -- fluent text with subtly wrong positions, - * which nothing downstream would flag. `rope_table` is therefore run here as the fused path's - * first stage rather than filled by this file, so what is compared is the pair the engine issues. + * The table is part of the claim: the fused kernel takes cos/sin, and a table with different + * angles is a different rope. So `rope_table` runs here as the fused path's first stage, and the + * comparison is of what the engine issues. * - * The q side reads a STRIDED view in the engine (the [q|gate] projection is interleaved per head) - * and the unfused norm cannot, so the reference is fed a contiguous copy of the same numbers. The - * arithmetic does not depend on the stride; the values are what is being compared. */ + * In the engine the q side is a strided view (the [q|gate] projection is interleaved per head); + * see the reference block below. */ static void qk_prologue_case(const Plugin& pl, uint32_t gain_dt, bool yarn = false, int64_t rot = 64) { if (!sel("qk_norm_rope_gate") && !sel("rope_table_f32")) return; - /* THE GAIN'S WIDTH IS RUN BOTH WAYS, because the two callers differ: every architecture plugin - * here declares an f32 norm gain and vLLM's declares bf16, and one flag inside the kernel picks - * between them. Checking only bf16 -- which is what the shape smoke test above passes -- would - * leave the width the ENGINE uses unexercised. */ + /* Both gain widths run: architecture plugins here declare f32 norm gains, vLLM's bf16, and one + * kernel flag picks between them. The smoke test only passes bf16. */ const bool gf32 = gain_dt == RAD_F32; const RadKernelInfo* rf = find(pl, "qk_norm_rope_gate"); const RadKernelInfo* rt = find(pl, "rope_table_f32"); @@ -1526,11 +1394,8 @@ static void qk_prologue_case(const Plugin& pl, uint32_t gain_dt, bool yarn = fal const RadKernelInfo* rr = find(pl, "rope_bf16"); if (!rf || !rt || !rn || !rr) { ok("qk_norm_rope_gate vs its pair", false, "row absent"); return; } - /* THE ENGINE'S HEAD COUNTS, and k rotated IN PLACE the way the block issues it -- the two ways - * this case could pass while the model still moved. A separate k_out is not what a caller with - * one k buffer does, and 4 query heads is not 12: the wave count the launcher picks is a - * function of nq + nkv, so a head count the model does not have exercises a launch it does not - * make. */ + /* The engine's head counts, and k rotated in place as the block issues it: the launcher's + * wave count depends on nq + nkv, so other head counts would exercise a different launch. */ const int64_t M = 512, nq = 12, nkv = 2, hd = 256, ctx = yarn ? 524288 : 4096; auto add_yarn = [&](std::vector& ps) { if (!yarn) return; @@ -1538,11 +1403,9 @@ static void qk_prologue_case(const Plugin& pl, uint32_t gain_dt, bool yarn = fal ps.push_back(PF("yarn_high", yarn_high(rot))); ps.push_back(PF("yarn_magnitude", kYarnMag)); }; const double theta = 1e7, eps = 1e-6, wadd = 1.0; - /* MANY ROWS, because the difference this case is hunting is one bf16 in tens of thousands: two - * summation orders for the same mean-square agree to a ULP in f32 and that ULP almost never - * crosses a bf16 boundary. A handful of rows settles nothing; 512 rows x 14 heads x 256 lanes - * is 1.8M elements a side. The positions still span the interesting range -- 0, small, and - * near the top. */ + /* Many rows: two summation orders of one mean square differ by an f32 ULP that rarely crosses + * a bf16 boundary, so a mismatch shows in about one element in tens of thousands. 512 rows x + * 14 heads x 256 lanes is 1.8M elements a side; positions span 0, small and near the top. */ std::vector pos((size_t)M); for (int64_t i = 0; i < M; ++i) pos[(size_t)i] = (int32_t)((i * 7 + i * i) % ctx); if (yarn) std::copy(std::begin(kYarnPos), std::end(kYarnPos), pos.begin()); @@ -1564,8 +1427,7 @@ static void qk_prologue_case(const Plugin& pl, uint32_t gain_dt, bool yarn = fal hgate[(size_t)((t * nq + h) * hd + d)] = g; } for (size_t i = 0; i < hk.size(); ++i) hk[i] = h_to_bf16(rnd(2000000 + (int64_t)i)); - /* The gain is built in bf16 either way and WIDENED for the f32 run, so the two runs put the - * same numbers through both widths -- a difference between them is the flag, not the data. */ + /* The gain is built in bf16 and widened for the f32 run, so both runs use the same values. */ std::vector hwq((size_t)hd), hwk((size_t)hd); std::vector fwq((size_t)hd), fwk((size_t)hd); for (int64_t d = 0; d < hd; ++d) { @@ -1585,15 +1447,13 @@ static void qk_prologue_case(const Plugin& pl, uint32_t gain_dt, bool yarn = fal void* d_cs = dalloc((size_t)ctx * rot * 4); void* d_qr = dalloc(qb); /* the reference q and k, normed then rotated in place */ void* d_kr = dalloc(kb); - void* d_qs = dalloc(qb); /* the contiguous q source the unfused norm reads */ void* d_qo = dalloc(qb); void* d_ko = dalloc(kb); void* d_go = dalloc(qb); - if (!d_qg || !d_k || !d_wq || !d_wk || !d_p || !d_cs || !d_qr || !d_kr || !d_qs || + if (!d_qg || !d_k || !d_wq || !d_wk || !d_p || !d_cs || !d_qr || !d_kr || !d_qo || !d_ko || !d_go) { ok("qk_norm_rope_gate vs its pair", false, "hipMalloc failed"); return; } st_memcpy(d_qg, hqg.data(), hqg.size() * 2, hipMemcpyHostToDevice); st_memcpy(d_k, hk.data(), kb, hipMemcpyHostToDevice); - st_memcpy(d_qs, hq_src.data(), qb, hipMemcpyHostToDevice); if (gf32) { st_memcpy(d_wq, fwq.data(), (size_t)hd * 4, hipMemcpyHostToDevice); st_memcpy(d_wk, fwk.data(), (size_t)hd * 4, hipMemcpyHostToDevice); @@ -1606,11 +1466,9 @@ static void qk_prologue_case(const Plugin& pl, uint32_t gain_dt, bool yarn = fal /* ---- the pair the fusion replaces ---- */ { - /* THE ENGINE FEEDS THIS NORM A STRIDED VIEW, not a contiguous copy: the q half of each - * head inside the interleaved [q|gate] projection, so its rows are 2*head_dim apart. If - * the norm answers differently on a strided row than on a dense one, the fused kernel can - * be exact against the dense form and the MODEL still move -- so the reference here is the - * operand the block actually issues. */ + /* The engine feeds this norm a strided view: the q half of each head inside the + * interleaved [q|gate] projection, rows 2*head_dim apart. The reference uses the same + * operand, in case the norm differs on strided and dense rows. */ RadTensor qsrc = T(d_qg, RAD_BF16, { M * nq, hd }); qsrc.stride[0] = 2 * hd; qsrc.stride[1] = 1; std::vector ts = { qsrc, @@ -1690,22 +1548,13 @@ static void qk_prologue_case(const Plugin& pl, uint32_t gain_dt, bool yarn = fal st_memcpy(wq_.data(), d_qr, qb, hipMemcpyDeviceToHost); st_memcpy(wk_.data(), d_kr, kb, hipMemcpyDeviceToHost); - /* BIT EQUALITY, and it holds only because the two FOLD THE SUM OF SQUARES THE SAME WAY. - * `r4d_rmsnorm_bf16` picks its thread width from `r4d_act_threads(M, n)` and states the rule - * itself: "the width decides which columns a thread folds into the sum of squares. Two - * kernels that disagree about it disagree in the last bits of the norm, and the fused one is - * required to be byte-identical to this kernel followed by the quantiser." The fused prologue - * reproduces that fold, so the comparison below is an equality and not a tolerance. + /* Bit equality holds because both fold the sum of squares the same way: `r4d_rmsnorm_bf16` + * takes its thread width from `r4d_act_threads(M, n)`, which decides the columns each thread + * folds, and the fused prologue reproduces that fold. * - * THE FAILURE MESSAGE STILL REPORTS A RELATIVE WORST CASE rather than a bf16 step count, - * because a ULP in the mean square is a ULP in the normed value -- and a ROTATED element is a - * difference of two products, so where they nearly cancel that ULP comes out as a few percent - * of a small number while a wrong angle or a wrong pairing is O(1). The two read very - * differently. - * - * 512 rows is not decoration: where the folds do differ they differ on a handful of elements - * in a million, so a few rows agree exactly and say nothing -- which is also why a model's - * transcript moves after a few dozen steps and not at the first one. */ + * The failure message reports a relative worst case: a rotated element is a difference of two + * products, so a ULP can be a few percent of a small number, while a wrong angle or pairing is + * O(1). */ auto cmp = [&](const char* what, const std::vector& got, const std::vector& want, int64_t width) { int64_t n_off = 0; @@ -1732,11 +1581,8 @@ static void qk_prologue_case(const Plugin& pl, uint32_t gain_dt, bool yarn = fal char rate[128]; std::snprintf(rate, sizeof rate, "%lld of %zu differ, worst %.2e of full scale", (long long)n_off, got.size(), worst); - /* BYTE EQUALITY, NOT A TOLERANCE. The kernel reproduces `rmsnorm_bf16`'s fold, so the - * only honest assertion is that not one of 1.8M elements differs -- a relative bound here - * would let the engine's transcript move while this row still said "ok". `worst` stays in - * the message because a failure that is a rounding and a failure that is a wrong angle - * read very differently. */ + /* Byte equality: no element may differ. `worst` in the message separates a rounding + * from a wrong angle. */ ok(("qk_norm_rope_gate " + tag + " is byte-identical to the unfused pair").c_str(), n_off == 0, std::string(rate) + (n_off == 0 ? "" : " -- " + where)); }; @@ -1746,16 +1592,14 @@ static void qk_prologue_case(const Plugin& pl, uint32_t gain_dt, bool yarn = fal } /* ------------------------------------ the prologue with the cache store folded on, against the pair * - * `qk_norm_rope_gate_kv_store` is `qk_norm_rope_gate` followed by `kv_store` into the E4M3 or the - * bf16 cache, and the claim is byte equality with that pair -- the q and rotated k it leaves, and - * every byte of the cache, including the ones it must not touch. The same inputs go down both paths - * on separate buffers (k is rotated in place, so each path needs its own), and the caches start - * from the same random bytes, so a store at a wrong place or a store that should not have happened - * shows up against the pair and not only against a clean slate. + * `qk_norm_rope_gate_kv_store` is `qk_norm_rope_gate` followed by `kv_store` into the E4M3 or bf16 + * cache, and must be byte-identical to that pair: q, the rotated k, and every byte of the cache. + * Both paths get the same inputs on separate buffers (k is rotated in place) and caches starting + * from the same random bytes, so a misplaced or spurious store shows. * - * THE INPUTS SPAN THE CLAMP: v up to +-2000 and k normed and rotated, so E4M3's +-448 saturation - * and its subnormals are both reached. A pad row (slot -1) and a slot past the cache's end must - * store nothing. The engine's geometry: 12 query heads and 2 kv heads of 256, rot 64. */ + * The inputs span the clamp (v up to +-2000, k normed and rotated), reaching E4M3's +-448 + * saturation and its subnormals. A pad row (slot -1) and a slot past the cache's end must store + * nothing. The engine's geometry: 12 query heads and 2 kv heads of 256, rot 64. */ static void qk_kv_fold_case(const Plugin& pl, bool bf16) { const char* row = bf16 ? "qk_norm_rope_gate_kv_store_bf16" : "qk_norm_rope_gate_kv_store_fp8"; if (!sel(row)) return; @@ -1873,7 +1717,7 @@ static void qk_kv_fold_case(const Plugin& pl, bool bf16) { for (size_t i = 0; i < a.size(); ++i) n += a[i] != b[i]; return n; }; - /* And the store did happen: the pair's cache is not the initial bytes. */ + /* And the store happened: the pair's cache differs from the initial bytes. */ const int64_t dq = ndiff(qa, qbv), dk = ndiff(ka, kbv), dc = ndiff(ca, cb), moved = ndiff(ca, hc); char msg[160]; std::snprintf(msg, sizeof msg, "q %lld, k %lld, cache %lld of %zu bytes differ; the pair wrote " @@ -1881,23 +1725,18 @@ static void qk_kv_fold_case(const Plugin& pl, bool bf16) { (long long)moved); ok(name, dq == 0 && dk == 0 && dc == 0 && moved > 0, msg); } -/* ------------------------------------------------ the K-ONLY form, against the pair IT replaces +/* ------------------------------------------------ the k-only form, against the pair it replaces * - * `n_head` 0 is what the QSA indexer asks for: its query heads are already one plain `head_dim` - * run each inside the `heads + 1` projection, so there is no [q|gate] split to do and no q - * operands to pass. The unfused pair it replaces is `heads` rmsnorms on a STRIDED view plus one - * rope -- five launches a layer, sixteen indexer calls a step -- and the only thing that makes - * the fusion worth having is that the model which comes out is the same model. + * `n_head` 0 is what the QSA indexer asks for: its query heads are already plain `head_dim` runs + * inside the `heads + 1` projection, so there is no [q|gate] split and no q operand. It replaces + * `heads` rmsnorms on a strided view plus one rope, and must be byte-identical to them. * - * THE STRIDE IS THE POINT AND IT IS WHY THIS IS A SECOND CASE. The pair above feeds the fused - * kernel a [tokens, heads, head_dim] k whose heads are contiguous; this one feeds it a head that - * is 128 columns inside a 640-column row, which is the only layout the indexer has. If the shim - * ever took the row pitch from the head count rather than from the operand, that case would still - * pass and this one would read another head's numbers. + * The stride is why this is a separate case: the head here is 128 columns inside a 640-column row, + * the indexer's layout. A shim taking the row pitch from the head count rather than the operand + * would pass the case above and fail this one. * - * THE GEOMETRY IS THE MODEL'S: 4 heads of 128 at rot 64, the fifth head of the projection being - * the raw key that this op must leave ALONE. It is checked explicitly -- an off-by-one in the - * head loop would otherwise be invisible, since nothing downstream of here reads it in this file. */ + * The model's geometry: 4 heads of 128 at rot 64. The projection's fifth head is the raw key, which + * this op must leave untouched; that is checked explicitly. */ static void qsa_qprep_case(const Plugin& pl) { if (!sel("qk_norm_rope_gate") && !sel("rope_table_f32")) return; const RadKernelInfo* rf = find(pl, "qk_norm_rope_gate"); @@ -1968,7 +1807,7 @@ static void qsa_qprep_case(const Plugin& pl) { { std::vector ts = { T(d_qk, RAD_BF16, { M, nw }), /* q_gate -- made absent below */ - T(d_qk, RAD_BF16, { M, nw }), /* k: the projection WHOLE, at its own pitch */ + T(d_qk, RAD_BF16, { M, nw }), /* k: the whole projection, at its pitch */ T(d_cs, RAD_F32, { ctx, rot }), T(d_p, RAD_I32, { M }), T(d_w, RAD_F32, { hd }), /* q_w -- absent */ T(d_w, RAD_F32, { hd }), @@ -2002,9 +1841,8 @@ static void qsa_qprep_case(const Plugin& pl) { ok("qk_norm_rope_gate k-only is byte-identical to heads norms plus a rope", n_off == 0, std::string(rate) + where); - /* THE HEAD IT MUST NOT TOUCH. `k_out` is `heads` wide, so the raw key at columns - * [heads*hd, nw) of the INPUT is not addressed by the output at all -- but the input is what - * a caller passes in place and an over-long head loop would norm it. */ + /* The head it must not touch: `k_out` is `heads` wide, so the raw key at input columns + * [heads*hd, nw) is never an output, but an over-long head loop would norm it in place. */ std::vector back((size_t)M * nw); st_memcpy(back.data(), d_qk, qkb, hipMemcpyDeviceToHost); ok("qk_norm_rope_gate k-only leaves the projection's untouched heads alone", @@ -2013,35 +1851,24 @@ static void qsa_qprep_case(const Plugin& pl) { /* -------------------------------------------- router_topk + moe_scatter, against the pair * - * The claim is byte equality on all five outputs, and it is structural rather than hopeful: the - * fused kernel calls the SAME two device functions the standalone kernels call. What this case - * exists to catch is the wiring around them -- and there is one specific way to get it wrong that - * would otherwise produce plausible numbers. + * Byte equality on all five outputs. The fused kernel calls the same two device functions as the + * standalone kernels, so this checks the wiring around them. * - * THE TWO EXPERT COUNTS ARE DIFFERENT NUMBERS. The selection runs over the WHOLE router, because - * the router is replicated and every rank picks from every expert; the sort runs over THIS RANK'S - * SLICE and drops what went elsewhere. Under expert parallelism the two are different numbers -- - * a 512-expert router against a rank slice of 254, say. So this case is run with - * `n_local < n_expert` and a non-zero `expert_base` -- a fused op - * handed one count for both would rank half the experts, or index its histogram past the end, and - * a case built at n_local == n_expert would not notice either. + * The two expert counts differ: the selection runs over the whole (replicated) router, the sort + * over this rank's slice. The case runs with `n_local < n_expert` and a non-zero `expert_base`, so + * a fused op using one count for both would fail. * - * ROWS ENOUGH TO CROSS EVERY WAVE ASSIGNMENT. The standalone selection gives a workgroup NW = 4 - * rows; the fused one launches a wave a row, eight, sixteen or thirty-two of them, and wraps - * above thirty-two. 5, 13 and 20 rows reach each width with a partial final pass, 45 wraps, and - * the answer must not depend on which wave got a row -- which is the property that makes the - * fusion legal in the first place. + * Rows cross every wave assignment: the standalone selection gives a workgroup NW = 4 rows, the + * fused one a wave per row with 8, 16 or 32 waves, wrapping above 32. 5, 13 and 20 rows reach each + * width with a partial final pass, and 45 wraps. */ static void topk_scatter_at(const RadKernelInfo* rf, const RadKernelInfo* rt, const RadKernelInfo* rs, int64_t M, const char* prot = nullptr); static void topk_scatter_case(const Plugin& pl) { - /* ROW names, not op names. `sel` compares against whatever the sweep is naming, and the - * sweep names ROWS -- every other case here guards on `rowtopk_bf16`, `gated_had_quant_i8`, - * `rmsnorm_bf16`. `qk_prologue_case` reads as an exception and is not one: its row is spelled - * `qk_norm_rope_gate`, the same as its op. Guarding on the op name where the row carries a - * suffix means the case never runs and reports nothing, which is indistinguishable from - * passing. */ + /* Row names, not op names: `sel` matches the row the sweep names. Guarding on an op name + * whose row carries a suffix would never run the case. (qk_prologue_case's row is spelled + * like its op.) */ if (!sel("router_topk_scatter_bf16") && !sel("router_topk_bf16") && !sel("moe_scatter_i32")) return; const RadKernelInfo* rf = find(pl, "router_topk_scatter_bf16"); @@ -2049,7 +1876,7 @@ static void topk_scatter_case(const Plugin& pl) { const RadKernelInfo* rs = find(pl, "moe_scatter_i32"); if (!rf || !rt || !rs) { ok("router_topk_scatter", false, "row absent"); return; } for (const int64_t M : { 5, 13, 20, 45 }) topk_scatter_at(rf, rt, rs, M); - /* ...and with protected experts sorted last: the first, a middle and the last of the slice. */ + /* And with protected experts sorted last: the first, a middle and the last of the slice. */ for (const int64_t M : { 13, 45 }) topk_scatter_at(rf, rt, rs, M, "0,17,101,253"); } @@ -2150,23 +1977,19 @@ static void topk_scatter_at(const RadKernelInfo* rf, const RadKernelInfo* rt, /* -------------------------------- router_gemm_topk_scatter, against the launches it stands in for * - * The claim is byte equality with THREE launches: the router's gemm_nt, the shared gate's gemm_nt - * at N = 1, and router_topk_scatter over the router's logits -- so all seven outputs are compared, - * the logits and the gate included. Those two are what the claim rests on: an element of the - * skinny bf16 GEMM is a function of its split-K count alone, and the fused op asks the unfused - * launch's own law for that count at each N (four at 512 x 2560, twenty for the one-column gate; - * eight and sixteen at 256 x 2048). + * Byte equality with three launches: the router's gemm_nt, the shared gate's gemm_nt at N = 1, + * and router_topk_scatter over the logits; all seven outputs are compared, logits and gate + * included. An element of the skinny bf16 GEMM depends only on its split-K count, and the fused op + * asks the unfused launch's law for that count at each N (four at 512 x 2560, twenty for the + * one-column gate; eight and sixteen at 256 x 2048). * - * ROWS AT EVERY WAVE COUNT AND EVERY ROW-TILE COUNT the fused op launches -- 8, 16 and 32 waves, - * one to four 16-row tiles, partial tiles included -- at the served geometry (512 experts, - * top_k 10, K 2560) and at a 256-expert one, which takes the other selection instantiation and - * other splits. An expert-parallel slice with a protect list, and the form without the gate. + * Rows cover every wave count (8, 16, 32) and row-tile count (one to four 16-row tiles, partial + * included) at the served geometry (512 experts, top_k 10, K 2560) and a 256-expert one (the other + * selection instantiation). Also an expert-parallel slice with a protect list, and no gate. * - * AND TWICE, BACK TO BACK, ON ONE OUTPUT. The last workgroup is named by a counter that resets - * itself; a counter left behind by one launch would make the next one rank before the GEMM was - * done, or never. The counter is the instance's, taken by the row's init as the engine takes it, - * and every launch here shares that one instance -- and with it one counter -- in an order that - * changes the grid between consecutive launches. A launch with no instance is refused. */ + * Each shape runs twice back to back on one output: the last workgroup is found by a + * self-resetting counter, owned by the instance the row's init creates, which all launches here + * share while the grid changes between them. A launch with no instance is refused. */ static void router_gemm_fused_case(const Plugin& pl) { if (!sel("router_gemm_topk_scatter_bf16")) return; const RadKernelInfo* rg = find(pl, "router_gemm_topk_scatter_bf16"); @@ -2224,8 +2047,7 @@ static void router_gemm_fused_case(const Plugin& pl) { } for (const RgCase& c : cfgs) { - /* A trained router's logits are a few units wide; these are about that, with a tie - * planted in every row so the selection's tie rule decides something. */ + /* Logits a few units wide, like a trained router's, with a tie planted in every row. */ std::vector hw((size_t)c.ne * c.K), hwg((size_t)c.K); for (auto& v : hw) v = h_to_bf16(uni(-0.06f, 0.06f)); for (auto& v : hwg) v = h_to_bf16(uni(-0.06f, 0.06f)); @@ -2371,18 +2193,14 @@ static void router_gemm_fused_case(const Plugin& pl) { rg->fini(inst); } -/* THE PROTECTED EXPERTS ARE SORTED LAST, against a host stable sort by place. A layer that keeps a - * few experts at a higher precision serves them with a second grouped GEMM over a trailing run of - * the offsets, so the sort has to put their rows after every other expert's, in the order listed, - * with the rest closed up -- and keep every run stable. Both forms of the standalone sort run: 450 - * slots is the one-workgroup form, 3000 the three-pass one, and the first, a middle and the last - * expert of a rank's slice are protected so the closing-up is tested at both ends. The fused - * decode kernel is held to the standalone pair in topk_scatter_case. +/* Protected experts are sorted last, checked against a host stable sort. Their rows must follow + * every other expert's, in the listed order, with the rest closed up and every run stable. Both + * standalone sort forms run (450 slots: one workgroup; 3000: three passes), with the first, a + * middle and the last expert of a slice protected. topk_scatter_case covers the fused kernel. * - * The general form also runs at a prefill chunk's sizes: 79 and 80 tiles of 256 slots, so a - * scan thread's column of tile counts takes several batches of loads with a short last one, on a - * rank's slice and with every one of 512 experts local (the mod4 split's case), where the scan's - * workgroup is every thread an expert. */ + * The general form also runs at prefill sizes: 79 and 80 tiles of 256 slots (several batches of + * loads per scan thread, a short last one), on a rank's slice and with all 512 experts local (the + * mod4 split's case), where every scan thread is an expert. */ static void scatter_protect_at(const RadKernelInfo* rs, int64_t M, int64_t nl, int64_t base); static void scatter_protect_case(const Plugin& pl) { @@ -2407,8 +2225,8 @@ static void scatter_protect_at(const RadKernelInfo* rs, int64_t M, int64_t nl, i const int64_t NS = M * k; const std::string at = " (" + std::to_string(NS) + " slots, slice " + std::to_string(nl) + ")"; - /* Each row's k distinct experts from the whole router, a quarter of them in this slice and - * the protected ones over-represented so their runs are long. */ + /* Each row's k distinct experts from the whole router, a quarter in this slice, the + * protected ones over-represented so their runs are long. */ std::vector ids((size_t)NS); uint64_t rs64 = 0x9E3779B97F4A7C15ull ^ (uint64_t)M; auto rnd = [&]() { rs64 ^= rs64 << 13; rs64 ^= rs64 >> 7; rs64 ^= rs64 << 17; return rs64; }; @@ -2473,18 +2291,17 @@ static void scatter_protect_at(const RadKernelInfo* rs, int64_t M, int64_t nl, i } } -/* moe_gather'S FORMS, against each other byte for byte. +/* moe_gather's forms, against each other byte for byte. * - * Past the self-scan cap the op builds the slot inverse in scratch and sums each token's slots. - * Its rule takes gather_wide_kernel there -- a wave a token and sixteen bytes a lane -- wherever - * the slots fit its registers and every row starts on sixteen bytes, and gather_kernel -- a column - * a thread -- everywhere else. r4d_moe_gather_pin_form pins each (1 the column a thread, 2 the wave - * a token), and every form must write the column-a-thread form's bytes: with and without the shared arm folded - * in, under both gates, with dropped slots, at a width that ends inside a column group, and at - * Qwen3.8-Flash-Next's 2048-token chunk on a rank of four -- where the case also prints what each - * form costs. A decode step (under the cap), a top_k past the wide form's registers and a width it - * cannot take in sixteen-byte pieces must refuse the wide pins, and the rule then writes the same - * bytes as the column a thread. `wide` is whether the shape takes the wide form. */ + * Past the self-scan cap the op builds the slot inverse in scratch and sums each token's slots, + * using gather_wide_kernel (a wave per token, sixteen bytes per lane) where the slots fit its + * registers and every row starts on sixteen bytes, and gather_kernel (a column per thread) + * elsewhere. r4d_moe_gather_pin_form pins each (1 column per thread, 2 wave per token), and every + * form must write the column-per-thread bytes: with and without the shared arm, under both gates, + * with dropped slots, at a width ending inside a column group, and at Qwen3.8-Flash-Next's + * 2048-token chunk on a rank of four (also timed). A decode step (under the cap), a top_k past the + * wide form's registers, and a width not tiled by sixteen-byte pieces must refuse the wide pin. + * `wide` says whether the shape takes the wide form. */ struct MoeGatherShape { int64_t M, n, k; const char* act; bool wide; }; static void moe_gather_at(const Plugin& pl, const RadKernelInfo* r, const MoeGatherShape& sh) { @@ -2496,8 +2313,8 @@ static void moe_gather_at(const Plugin& pl, const RadKernelInfo* r, const MoeGat uint64_t rs = 0x9E3779B97F4A7C15ull ^ ((uint64_t)M * 1315423911ull) ^ ((uint64_t)n * 2654435761ull) ^ (uint64_t)k; auto rnd = [&]() { rs ^= rs << 13; rs ^= rs >> 7; rs ^= rs << 17; return rs; }; - /* Each slot to one of 64 experts or, one in thirty-one, dropped; `sorted` is the stable sort by - * expert with the live slots first and -1 after them, as moe_scatter writes it. */ + /* Each slot to one of 64 experts, or dropped one in thirty-one; `sorted` is the stable sort by + * expert, live slots first and -1 after, as moe_scatter writes it. */ std::vector ex((size_t)NS), sorted((size_t)NS, -1); for (int64_t i = 0; i < NS; ++i) { const uint64_t v = rnd(); @@ -2640,6 +2457,17 @@ static void moe_gather_case(const Plugin& pl) { for (const MoeGatherShape& sh : kSh) moe_gather_at(pl, r, sh); } +/* ------------------------------------------------------- the vocab-parallel top-R, end to end + * + * A top-R over one plane must equal the merge of the two half-plane top-Rs, index for index and + * value for value. This covers the `vocab_off` shift, the `pairs` plane row_topk writes and the + * merge at once; a sharded draft head must propose exactly what the replicated one does. + * + * The values are full of ties (a 23-value alphabet over 2048 columns), because a dense top-R + * breaks ties on the lower column and a merge that broke them on rank order would disagree. + * + * The gathered plane is assembled as `all_gather` with `row = R*2` does: rank r's R pairs at + * [r*R, (r+1)*R) of each row. */ static void rowtopk_shard_case(const Plugin& pl) { if (!sel("rowtopk_merge") && !sel("rowtopk_bf16")) return; const RadKernelInfo* rt = find(pl, "rowtopk_bf16"); @@ -2678,12 +2506,8 @@ static void rowtopk_shard_case(const Plugin& pl) { st_memcpy(wv.data(), d_v0, (size_t)M * R * 4, hipMemcpyDeviceToHost); /* Each rank's own slice, reporting global columns, plus the pairs an all_gather would move. - * - * THE SLICE IS COPIED OUT RATHER THAN VIEWED. libr4d's top-R takes a CONTIGUOUS [M, N] plane - * and refuses a strided one, so a column slice of the wide plane is not an operand it accepts - * -- and it does not have to be: under a real shard each rank's draft head writes only its own - * rows, so the plane it hands this op is contiguous and `SH` wide by construction. Passing a - * view here would be testing a shape the engine never produces. */ + * The slice is copied out: the top-R refuses a strided plane, and under a real shard each + * rank's plane is contiguous and `SH` wide anyway. */ std::vector half((size_t)M * SH); std::vector gath((size_t)M * W * R * 2); for (int64_t r = 0; r < W; ++r) { @@ -2734,18 +2558,17 @@ static void rowtopk_shard_case(const Plugin& pl) { /* --------------------------- the attention with the output gate and quantiser in its merge, vs the pair * * `attn_decode_gq_h256_gqa12_` is `attn_decode_h256_gqa12_` followed by `gate_quant_fp8` - * over its output, for the E4M3 cache and the bf16 one, and the claim is byte equality with that - * pair: the gated bf16 product it leaves in `out`, every E4M3 code and every scale. The engine's - * sparse-path geometry -- 12 query heads over one kv head of 256, 4-token pages, one query row a - * sequence -- with the gate a column view of a [q|gate] plane exactly as the block hands it over. + * over its output, for E4M3 and bf16 caches, and must be byte-identical to that pair: the gated + * bf16 product in `out`, every code and every scale. The engine's sparse-path geometry: 12 query + * heads over one kv head of 256, 4-token pages, one query row per sequence, the gate a column view + * of a [q|gate] plane as the block passes it. * - * TWO BATCH SIZES, because the merge has two forms: three rows is 36 (row, head) jobs and takes - * the one-thread-a-column merge, 24 rows is 288 and takes the one-wave-a-row form. Each has one - * padded row (no context), which the pair gives zeros, a zero scale group and a scale of 1. The - * E4M3 cache is random bytes but for the NaN codes, the bf16 one random finite values, and the - * descales are not 1. */ -/* `i8` runs both at INT8 codes -- the codes operand an int8 out projection reads -- and the claim - * is the same: the fold's int8 merge leaves what gate_quant_fp8's int8 form leaves. */ + * Two batch sizes cover the merge's two forms: 3 rows (36 (row, head) jobs, one thread per column) + * and 24 rows (288, one wave per row). Each has one padded row (no context), which gets zeros, a + * zero scale group and a scale of 1. The E4M3 cache is random bytes except NaN codes, the bf16 one + * random finite values, and the descales are not 1. + * + * `i8` runs both at int8 codes (the operand an int8 out projection reads), with the same claim. */ static void attn_gq_fold_case(const Plugin& pl, int64_t S, bool bf16, bool i8 = false) { const std::string kvs = bf16 ? "bf16kv" : "fp8kv"; const std::string fold = "attn_decode_gq_h256_gqa12_" + kvs; @@ -2868,7 +2691,7 @@ static void attn_gq_fold_case(const Plugin& pl, int64_t S, bool bf16, bool i8 = for (size_t i = 0; i < a.size(); ++i) n += a[i] != b[i]; return n; }; - /* And the pair did write something: its codes are not all zero. */ + /* And the pair wrote something: its codes are not all zero. */ int64_t live = 0; for (uint8_t x : qa) live += x != 0; const int64_t n_o = ndiff(oa, obv), n_q = ndiff(qa, qbv), n_s = ndiff(sa, sbv); @@ -2879,6 +2702,18 @@ static void attn_gq_fold_case(const Plugin& pl, int64_t S, bool bf16, bool i8 = ok(name.c_str(), n_o == 0 && n_q == 0 && n_s == 0 && live > 0, msg); } +/* kv_store, both widths, against an exactly representable set so the check is equality: halves + * and integers up to 8 survive E4M3 (three mantissa bits) and bf16 unchanged, so `h_e4m3` or + * `h_bf16` of what landed must equal what went in. + * + * The op scatters into kv_cache[n_blocks, kv_heads, block_size, 2*head_dim], K at [.., d] and V at + * [.., head_dim + d], at (slot / block_size, slot % block_size). Each value is built from (token, + * head, dim) and K and V have disjoint sign, so a k/v swap, head transposition or off-by-a-block + * shows. + * + * A negative or out-of-range slot (a pad row) must store nothing: the cache is prefilled with a + * sentinel and those slots must still hold it. Slot 0 is a real slot (as in libref and + * r4d_gdn_conv_w4_h128_bf16.hip) and is used deliberately. */ static void kv_store_case(const Plugin& pl, const char* name, const char* kv_dtype) { if (!sel(name)) return; const RadKernelInfo* r = find(pl, name); @@ -2892,8 +2727,8 @@ static void kv_store_case(const Plugin& pl, const char* name, const char* kv_dty const std::vector slots = { 0, 17, 63, -1, (int32_t)(n_blocks * block_size), 33 }; const int64_t T_tok = (int64_t)slots.size(); - /* Exact in E4M3 and in bf16. Sign separates K from V, the magnitude carries the head and the - * column, so no two (token, head, dim) triples that this could confuse share a value. */ + /* Exact in E4M3 and bf16. Sign separates K from V, the magnitude encodes head and column, so + * no two confusable (token, head, dim) triples share a value. */ auto want = [&](int64_t t, int64_t h, int64_t d, bool is_v) { static const float mag[8] = { 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 8.0f }; const float m = mag[(size_t)((t * 3 + h * 5 + d) % 8)]; @@ -2917,8 +2752,8 @@ static void kv_store_case(const Plugin& pl, const char* name, const char* kv_dty st_memcpy(d_k, hk.data(), (size_t)T_tok * lane * 2, hipMemcpyHostToDevice); st_memcpy(d_v, hv.data(), (size_t)T_tok * lane * 2, hipMemcpyHostToDevice); st_memcpy(d_sm, slots.data(), (size_t)T_tok * 4, hipMemcpyHostToDevice); - /* 0x7f is NaN in E4M3 and a large number in bf16 -- either way it is a value the store cannot - * produce from the inputs above, so anything still holding it was not written. */ + /* 0x7f is NaN in E4M3 and large in bf16; the store cannot produce it from these inputs, so + * anything still holding it was not written. */ st_memset(d_c, 0x7f, cbytes); std::vector ts = { @@ -2962,11 +2797,8 @@ static void kv_store_case(const Plugin& pl, const char* name, const char* kv_dty } } } - /* Every element of a block no live slot names must still be the sentinel, and that is checked - * on the RAW STORAGE rather than through `at`. 0x7f is the NaN encoding in E4M3 and this - * file's `h_e4m3` does not implement it -- it reads exponent 15, mantissa 7 as 480.0 -- so a - * decoded comparison against NaN reports every untouched byte as written. The bytes are what - * the question is about anyway: "was this written", not "what does it mean". */ + /* Every element no live slot names must still be the sentinel, checked on raw storage: 0x7f + * is E4M3's NaN, which h_e4m3 decodes as 480.0, so a decoded comparison would misreport. */ for (int64_t i = 0; i < cache_elts; ++i) { const int64_t blk = i / (kv_heads * block_size * 2 * head_dim); const int64_t off = (i / (2 * head_dim)) % block_size; @@ -2991,91 +2823,30 @@ static void kv_store_case(const Plugin& pl, const char* name, const char* kv_dty pad_touched == 0, pad_touched ? "written: " + first : ""); } -/* THE FP8 GEMM, CHECKED AGAINST A HOST REFERENCE ON THE SAME BYTES. +/* The anchor state form, end to end. * - * A kernel that produces plausible numbers is not evidence (spec §17). This builds a weight's two - * block-fp8 planes, has the plugin's OWN layout hooks arrange them, dequantises the planes on the - * host -- the same E4M3 codes and the same bf16 block scales the kernel will read -- and compares. - * So it falsifies four things at once: the arrangement, the kernel's scale INDEXING (a `>> 7` off - * by one reads a neighbouring tile and still looks like weights), the fold's placement inside the - * K loop, and -- for fp8a8 -- the activation quantiser and the epilogue's transpose. - * - * It is deliberately NOT a tolerance on the quantisation error: both sides see the same quantised - * weight, so the only difference permitted is summation order. The bound is bf16's own resolution - * on the output, 2^-8 relative, loosened to 3e-2 because a K=512 reduction reordered across 32 - * lanes moves the last bf16 mantissa bit on values near a rounding boundary and this is a - * correctness gate, not a numerics measurement -- a transposed operand or a misread scale lands - * two orders of magnitude away from it, which is the thing being caught. - * - * WHAT IT ACTUALLY MEASURES, so a later loosening is visible: 1.739e-3 for the matvec at every one - * of the five rb variants, agreeing to six digits, and 1.1731e-2 for BOTH W8A8 rows. 2^-9 is - * 1.95e-3, so the matvec is sitting on bf16's own rounding floor and nothing else; the W8A8 rows - * are higher because their ACTIVATION is quantised to E4M3 as well, whose three mantissa bits are - * ~6% per element before the K=512 average. On real checkpoint weights (--real) the matvec measures - * 1.66e-3 at gate_proj, o_proj and q_proj alike. - * - * THE TWO W8A8 ROWS AGREEING TO SIX DIGITS IS THE RESULT WORTH READING. They put the weight on - * OPPOSITE operands, fold opposite scale shapes, and store through opposite epilogues -- one - * transposed and split over K, one coalesced and not -- and they land on the same number. Two - * independent paths agreeing with the host is a much stronger statement than either agreeing on - * its own, because the ways they could each be wrong do not overlap. */ -/* THE GROUPED DYNAMIC CONVOLUTION AGAINST A HOST MIRROR OF DFlash2's `_grouped_conv`. - * - * The smoke case above launches it against zeroed buffers, which cannot tell a convolution from a - * copy: every tap term is zero, the block-position mask is never exercised, and the group index is - * irrelevant when every delta is the same. This one puts the reference formula on the host -- - * - * out[t,h] = SUM over k of (base[k][h] + delta[t][k*NG + h/group]) * x[t-k][h] * (t%block >= k) - * - * -- and asks whether the kernel agrees. The three things it can get wrong and the smoke case - * cannot see are all in that line: which delta belongs to which channel (the group index), whether - * the tap shift is within the block or across it (the mask), and whether base is indexed by - * channel or by group. */ -/* THE ANCHOR STATE FORM, END TO END. - * - * `gdn_recurrent_update` serves two contracts for the same arithmetic. Under `per_candidate` every - * candidate token writes its own state slot and the next step reads the one the last accepted - * token wrote. Under `anchor` a sequence keeps ONE state, the step's tokens are recorded beside it - * as replay factors, and the next step folds the accepted prefix back in before it runs. The two - * produce the same output from a completely different cache, so nothing that compares the state - * can compare them -- and a fixture recording cannot reach the anchor at all, because drawing one - * state index per candidate IS the per-candidate contract. - * - * What that leaves unchecked is the whole anchor path: the replay loop, the factor block's layout, - * and the column algebra that has to survive a paged cache whose window slides. So this drives a - * multi-step schedule against a host walk of the delta rule with a rollback between steps, which - * is the per-candidate contract's answer by definition: + * `gdn_recurrent_update` serves two state contracts with the same arithmetic. Under + * `per_candidate` every candidate token writes its own state slot and the next step reads the one + * the last accepted token wrote. Under `anchor` a sequence keeps one state, the step's tokens are + * recorded beside it as replay factors, and the next step folds the accepted prefix back in. Both + * give the same output from different caches, so this drives a multi-step schedule against a host + * walk of the delta rule with rollback: * * the state a step starts from is the state after the previous step's first `num_accepted` - * tokens, whatever the cache did to hold on to it. + * tokens. * - * THE WINDOW MOVES ALL THREE WAYS. A paged caller re-derives the page index every step, so the six - * columns slide by -1, 0 or +1 and the kernel finds its anchor through a marker it left in the - * factor block. The schedule below takes +1, then 0, then -1. With a window that never moves, - * every read lands where it was written whatever the algebra says and the marker is untested. + * The window moves all three ways: a paged caller re-derives the page index every step, so the six + * columns slide by -1, 0 or +1 and the kernel finds its anchor through a marker in the factor + * block. The schedule takes +1, then 0, then -1. * - * AND IT ASSERTS ITS OWN SENSITIVITY. A second host chain rolls back to the FIRST token at every - * step -- what a kernel that ignored `num_accepted` would produce -- and the check requires that - * one to DISAGREE with the device. Without it, a schedule whose acceptances all happened to be one - * would pass with the replay loop deleted. - * - * It needs a process of its own. The state form is selected by an environment variable read once - * and cached, so the smoke case above and this one cannot share one; the child is spawned the same - * way and for the same reason the per-row children are. + * A second host chain always rolls back to the first token (what a kernel ignoring `num_accepted` + * would produce) and must disagree with the device, so the check is sensitive. */ static void gdn_recurrent_anchor(const Plugin& pl) { const char* row = "gdn_recurrent_update_k128_v128_bf16_fp32state"; const char* nm = "gdn_recurrent_update anchor replays the accepted prefix"; - if (sel(row)) { /* the per-candidate child hands the form to its own */ - if (!g_exe || !g_plugin) { ok(nm, false, "no re-exec path"); return; } - const int st = spawn_anchor_child(nm); - if (st == CH_FAIL) ++g_fail; /* the child printed the line and the detail */ - else if (st == CH_SKIP) ++g_skip; - else if (st != CH_OK) ok(nm, false, "child exit " + std::to_string(st)); - return; - } - if (!sel(nm)) return; + if (!sel(row) && !sel(nm)) return; const RadKernelInfo* r = find(pl, row); if (!r) { ok(nm, false, "row absent"); return; } @@ -3084,9 +2855,9 @@ static void gdn_recurrent_anchor(const Plugin& pl) { const int64_t PAGES = 7; /* the widest window the schedule below slides over */ const int64_t SLOTS = N * PAGES; const double scale = 0.088388, neps = 1e-6; - /* `win` is the window's first page and `nacc` is what the PREVIOUS step committed. The first - * step is the bootstrap: its factor block is the zeros a freshly handed out slot carries, the - * marker reads as absent, and replaying one zeroed token leaves the anchor alone. */ + /* `win` is the window's first page, `nacc` what the previous step committed. The first step + * bootstraps: its factor block is a fresh slot's zeros, the marker reads as absent, and + * replaying one zeroed token leaves the anchor alone. */ struct Step { int nacc, win; }; const Step sched[] = { {1, 0}, {2, 1}, {3, 1}, {1, 0} }; const int NS = (int)(sizeof(sched) / sizeof(sched[0])); @@ -3103,8 +2874,8 @@ static void gdn_recurrent_anchor(const Plugin& pl) { rs = rs * 1664525u + 1013904223u; return (float)((rs >> 9) & 0xFFFFu) * (1.0f / 32768.0f) - 1.0f; }; - /* A_log sits where the decay is a few percent a token: exp(A_log) * softplus(a + dt_bias) of - * order 0.05, so the state neither freezes nor forgets inside twelve tokens. */ + /* A_log gives a decay of a few percent per token (exp(A_log) * softplus(a + dt_bias) ~ 0.05), + * so the state neither freezes nor forgets within twelve tokens. */ for (int64_t h = 0; h < H; ++h) { halog[(size_t)h] = -2.0f + 0.25f * (float)h; hdtb[(size_t)h] = -1.0f + 0.5f * (float)h; } for (int64_t j = 0; j < V; ++j) hnw[(size_t)j] = 1.0f + 0.25f * rnd(); @@ -3152,9 +2923,8 @@ static void gdn_recurrent_anchor(const Plugin& pl) { a.p = ps.data(); a.n_p = (int)ps.size(); a.world_size = 1; - /* Two host chains over the same data: one that rolls back to the accepted token, and one that - * always rolls back to the first. `sn` keeps a state per candidate token so the next step's - * rollback has somewhere to go. */ + /* Two host chains over the same data: one rolls back to the accepted token, one always to + * the first. `sn` keeps a state per candidate token for the next step's rollback. */ const size_t selems = (size_t)(N * H * V * K); std::vector S(selems), Sw(selems); std::vector sn((size_t)NT * selems), snw((size_t)NT * selems); @@ -3249,10 +3019,8 @@ static void gdn_recurrent_anchor(const Plugin& pl) { } walk(S, sn, ref); walk(Sw, snw, refw); - /* A RELATIVE L2 AND NOT A PER-ELEMENT MAXIMUM. The gated norm leaves a fair number of - * outputs next to zero, and dividing by one of those turns a rounding difference into a - * large ratio -- which flatters the sensitivity check exactly as much as it slanders the - * agreement, so neither number would mean anything. */ + /* Relative L2, not a per-element maximum: the gated norm leaves many outputs near zero, + * where a per-element ratio would inflate rounding differences. */ double en = 0.0, ew = 0.0, rn = 0.0; for (size_t i = 0; i < hdev.size(); ++i) { const double d = h_bf16(hdev[i]); @@ -3294,24 +3062,21 @@ static int64_t i8_code_misses(const uint16_t* x, int64_t x_ld, const int8_t* q, return miss; } -/* THE DECODE CONVOLUTION FOLDED INTO THE RECURRENT UPDATE, AGAINST THE PAIR IT REPLACES. +/* The decode convolution folded into the recurrent update, against the pair it replaces. * - * gdn_conv_recurrent_update claims to leave every byte gdn_conv_update followed by - * gdn_recurrent_update leaves: the output, its fp8 codes and scales, the recurrent state and the - * conv state. So both run from identical copies and all five are compared exactly, over TWO steps - * -- the second is what catches an arrival counter that does not reset, because the key heads' - * conv state is then never rewritten. + * gdn_conv_recurrent_update must leave every byte gdn_conv_update + gdn_recurrent_update leave: + * output, fp8 codes and scales, recurrent state and conv state. Both run from identical copies + * and all five are compared over two steps; the second catches an arrival counter that does not + * reset (the key heads' conv state would then not be rewritten). * - * The geometry puts two value heads on each key head, which is what makes the last-arriver rewrite - * run at all; gives the sequences uneven windows and read offsets; slots sequence 1 at conv slot 0, - * the real slot a `<= 0` test would drop; and makes the last sequence padding, with every slot - * negative. The projection is one row with the gate behind the convolution's columns, as the - * block lays it out, so `x` and `z` are both column views with the row's pitch. + * Two value heads per key head (so the last-arriver rewrite runs), uneven windows and read + * offsets, sequence 1 at conv slot 0 (a real slot a `<= 0` test would drop), and a last sequence + * of padding with every slot negative. `x` and `z` are column views of one projection row, the + * gate after the convolution's columns, as the block lays it out. * - * AND IT ASSERTS ITS OWN SENSITIVITY: the key heads' conv state has to have moved, or a fold that - * never rewrote it would pass against a pair that also did not. The state contract is chosen once a - * process, so the anchor form runs in a child, as gdn_recurrent_anchor's does. */ -/* `i8` runs both at INT8 codes, and holds the pair's codes to quant_act_i8g over its `o` too. */ + * The key heads' conv state must have moved, so the check is sensitive. The anchor form runs in a + * child process, as in gdn_recurrent_anchor. `i8` runs both at int8 codes and also holds the pair's + * codes to quant_act_i8g over its `o`. */ static void gdn_conv_fold_run(const Plugin& pl, const char* nm, const char* form, bool i8 = false) { const RadKernelInfo* rf = find(pl, "gdn_conv_recurrent_update_k128_v128_bf16"); @@ -3453,8 +3218,8 @@ static void gdn_conv_fold_run(const Plugin& pl, const char* nm, const char* form break; } } - /* At int8 codes, the real sequences' tokens -- every sequence but the padded last one -- - * against quant_act_i8g over the `o` the pair left. A (token, head) row is one group. */ + /* At int8 codes, the real sequences' tokens (all but the padded last) against + * quant_act_i8g over the pair's `o`. A (token, head) row is one group. */ if (i8 && why.empty()) { const std::vector O = fetch(d_o[0], o_b), Q = fetch(d_oq[0], oq_b), S = fetch(d_os[0], os_b); @@ -3486,29 +3251,17 @@ static void gdn_conv_fold(const Plugin& pl) { gdn_conv_fold_run(pl, "gdn_conv_recurrent_update is byte-identical to the pair at int8 " "codes, which are quant_act_i8g's, per_candidate", "per_candidate", true); - if (!g_exe || !g_plugin) { ok(nma, false, "no re-exec path"); return; } - const int st = spawn_anchor_child(nma); - if (st == CH_FAIL) ++g_fail; - else if (st == CH_SKIP) ++g_skip; - else if (st != CH_OK) ok(nma, false, "child exit " + std::to_string(st)); - return; } - if (sel(nma)) gdn_conv_fold_run(pl, nma, "anchor"); + if (sel(row) || sel(nma)) gdn_conv_fold_run(pl, nma, "anchor"); } -/* THE GATED NORM'S GATE AS A COLUMN SLICE, WHICH ONE PITCH CANNOT DESCRIBE. +/* The gated norm's gate as a column slice, which one pitch cannot describe. * - * The fp8 delta net projects [q|k|v|z] in ONE GEMM (arch/common/rad_block_gdn_fp8.h), so the gate - * this kernel reads is the right-hand columns of a wider row: its (token, head) rows are `channels` - * apart INSIDE a token and the projection's whole width apart BETWEEN tokens. An implementation - * that multiplies the flat row index by a single stride therefore walks into the next token after - * `n_head_v` rows -- still in bounds, still finite, and wrong in a way that reads as a slightly - * different model rather than as a crash. - * - * The smoke case above cannot see it, because it only ever hands over a dense gate. So this one - * runs the same numbers TWICE -- dense, and as the tail of a row twice as wide -- and requires the - * two outputs to agree byte for byte. Every value is a multiple of an eighth so the equality is - * exact and not a tolerance. */ + * The fp8 delta net projects [q|k|v|z] in one GEMM (arch/common/rad_block_gdn_fp8.h), so the gate + * is the right-hand columns of a wider row: its (token, head) rows are `channels` apart within a + * token and the projection's width apart between tokens. A single stride walks into the next token + * after `n_head_v` rows, silently. This runs the same numbers dense and as the tail of a row twice + * as wide and requires identical bytes; values are multiples of an eighth, so equality is exact. */ static void gdn_gated_norm_sliced_gate(const Plugin& pl) { if (!sel("gdn_gated_rmsnorm_h128_bf16")) return; const char* nm = "gdn_gated_rmsnorm_h128_bf16 reads a column-sliced gate"; @@ -3586,6 +3339,13 @@ static void gdn_gated_norm_sliced_gate(const Plugin& pl) { ok(nm, bad == 0, d); } +/* The grouped dynamic convolution against a host mirror of DFlash2's `_grouped_conv`: + * + * out[t,h] = SUM over k of (base[k][h] + delta[t][k*NG + h/group]) * x[t-k][h] * (t%block >= k) + * + * The smoke case runs on zeroed buffers and cannot tell a convolution from a copy. This checks the + * group index (which delta belongs to which channel), the block-position mask, and whether base is + * indexed by channel or by group. */ static void dflash_conv_numeric(const Plugin& pl, int64_t nt, int64_t H, int64_t group, int64_t taps, int64_t bsz) { if (!sel("dflash_conv_t2_g16_bf16")) return; @@ -3599,8 +3359,7 @@ static void dflash_conv_numeric(const Plugin& pl, int64_t nt, int64_t H, int64_t const int64_t dpitch = 2 * taps * NG; std::vector hx((size_t)(nt * H)), hd((size_t)(nt * dpitch)), hb((size_t)(taps * H)), hy((size_t)(nt * H), 0); - /* Quarters and eighths, so every product and sum is exact in f32 and the comparison is an - * equality rather than a tolerance. */ + /* Quarters and eighths, so every product and sum is exact in f32. */ for (int64_t t = 0; t < nt; ++t) for (int64_t h = 0; h < H; ++h) hx[(size_t)(t * H + h)] = h_to_bf16((float)(((t * 5 + h * 3) % 17) - 8) * 0.25f); @@ -3667,16 +3426,9 @@ static void dflash_conv_numeric(const Plugin& pl, int64_t nt, int64_t H, int64_t ok(nm, bad == 0, d); } -/* THE SKINNY bf16 GEMM AGAINST A HOST REFERENCE, AT A GIVEN K. - * - * The smoke case above launches it; this one says whether the number is right, and it takes K as a - * parameter because K is the dimension this kernel decomposes along -- pick_sk splits it, rowGo - * strides rows by it, and the unrolled fragment loop walks it. A K no model has used is therefore - * exactly the shape that has never been checked, and "it launches" says - * nothing about it. - * - * The weight is plain row-major [N, K]: this row declares no layout hook, so there is nothing to - * arrange and the bytes the host builds are the bytes the kernel reads. */ +/* The skinny bf16 GEMM against a host reference at a given K. K is the dimension this kernel + * decomposes along (pick_sk splits it, rowGo strides rows by it, the unrolled fragment loop walks + * it), so it is a parameter. The weight is plain row-major [N, K]: the row has no layout hook. */ static void bf16_gemm_numeric(const Plugin& pl, const char* row, int64_t M, int64_t N, int64_t K) { if (!sel(row)) return; char nm[128]; @@ -3685,9 +3437,9 @@ static void bf16_gemm_numeric(const Plugin& pl, const char* row, int64_t M, int6 const RadKernelInfo* r = find(pl, row); if (!r) { ok(nm, false, "row absent"); return; } - /* Deterministic and in the range the drafter's own fc actually sees: activations to a couple - * of hundred, weights inside one. A pattern that is symmetric in k would hide a split-K bug by - * making every partial sum equal, so the sign alternates on a period coprime with 16. */ + /* Deterministic, in the drafter fc's range: activations to a couple of hundred, weights + * within one. The sign alternates on a period coprime with 16, since a pattern symmetric in k + * would make every split-K partial sum equal. */ std::vector ha((size_t)(M * K)), hw((size_t)(N * K)), hy((size_t)(M * N), 0); for (int64_t i = 0; i < M; ++i) for (int64_t k = 0; k < K; ++k) @@ -3720,11 +3472,9 @@ static void bf16_gemm_numeric(const Plugin& pl, const char* row, int64_t M, int6 } st_memcpy(hy.data(), ts[2].data, hy.size() * 2, hipMemcpyDeviceToHost); - /* The reference reads the SAME bf16 values the kernel does, so what is left to disagree about - * is the arithmetic and the addressing and nothing else. A wide N is checked on a STRIDED - * SAMPLE of its columns: the host cost is M*N*K and the production shape is 655 million - * products, while what a column can be wrong about -- which weight row it read -- is a - * property of the column index, so sampling the index space finds it. */ + /* The reference reads the same bf16 values, so only arithmetic and addressing can differ. A + * wide N is checked on a strided sample of columns (the host cost is M*N*K); which weight row a + * column reads depends only on its index, so sampling finds a misread. */ const int64_t nstep = N > 64 ? N / 64 : 1; double num = 0, den = 0, worst = 0; for (int64_t i = 0; i < M; ++i) @@ -3744,10 +3494,9 @@ static void bf16_gemm_numeric(const Plugin& pl, const char* row, int64_t M, int6 } -/* THE 8-BIT-WEIGHT SKINNY GEMM AGAINST WHAT THE PLANES MEAN. The row reads the w8a16 hooks' - * fragment-order codes and (scale, zero) dwords, got from its own hooks, and the reference is the - * planes dequantised on the host, so an arrangement the kernel misread shows as a column that - * disagrees. `adt` is the activation's dtype, which the row takes as f16 and refuses otherwise. */ +/* The 8-bit-weight skinny GEMM against the planes' meaning. The row reads fragment-order codes + * and (scale, zero) dwords from its own w8a16 hooks; the reference dequantises the planes on the + * host. `adt` is the activation dtype: the row takes f16 and refuses others. */ static void w8a16_numeric(const Plugin& pl, const char* row, int64_t M, int64_t N, int64_t K, uint32_t adt) { if (!sel(row)) return; @@ -3840,10 +3589,10 @@ static void w8a16_numeric(const Plugin& pl, const char* row, int64_t M, int64_t } -/* An OCP-MXFP4 weight's planes, drawn through st_mix32 of each coordinate and `seed`: codes over - * all sixteen e2m1 values, and an exponent per (row, 32 of K) within three binades of 127. With - * `deep`, about one block in eleven sits 6..12 binades lower still -- the folded table's subnormal - * tail. */ +/* An OCP-MXFP4 weight's planes, drawn from st_mix32 of each coordinate and `seed`: codes over all + * sixteen e2m1 values, and an exponent per (row, 32 of K) within three binades of 127. With + * `deep`, about one block in eleven sits 6..12 binades lower (the folded table's subnormal + * tail). */ static void mxfp4_fill(Planes& p, int ic, int is, int64_t N, int64_t K, uint32_t seed, bool deep) { const int64_t nblk = K / 32; for (int64_t n = 0; n < N; ++n) @@ -3867,30 +3616,26 @@ static float mxfp4_act(int64_t i, int64_t k, uint32_t seed) { return (float)((int)(h % 401) - 200) * 0.02f; } -/* THE MXFP4 GEMMS AGAINST WHAT THE PLANES MEAN. The weight is an OCP-MXFP4 plane pair -- e2m1 - * codes and an E8M0 exponent per 32 K -- stored through the row's own hooks, so the fragment - * order, the [K/32][N] exponents and the per-row reference all come from r4d_layout.cpp and the - * kernel is checked on what the loader would hand it. The reference decodes the planes on the host - * with no fold at all, so a misread arrangement shows as a column that disagrees. +/* The MXFP4 GEMMs against the planes' meaning. The weight is an OCP-MXFP4 plane pair (e2m1 codes, + * an E8M0 exponent per 32 K) stored through the row's own hooks, so fragment order, [K/32][N] + * exponents and the per-row reference all come from r4d_layout.cpp. The host reference decodes + * the planes with no fold. * - * Codes, exponents and activations are drawn through st_mix32 of their coordinates, so a misread - * pitch or lane map reads unrelated numbers rather than a shifted copy of the right ones. The - * exponents are spread so a row's blocks sit up to 12 binades under its reference: d <= 8 is exact - * in the folded e4m3 table and d = 9..12 rounds, which is the subnormal tail every MXFP4 row - * shares. M and N are chosen ragged against the tiled row's 256-row block and 64/128-column tile, - * so the clamped staging and the guarded epilogue both run. `tn` pins the tiled row's column - * width; 0 leaves it to the row's own M rule (and is ignored by the skinny row). + * Exponents are spread so a row's blocks sit up to 12 binades under its reference: d <= 8 is exact + * in the folded e4m3 table, d = 9..12 rounds (the subnormal tail). M and N are ragged against the + * tiled row's 256-row block and 64/128-column tile, so clamped staging and the guarded epilogue + * run. `tn` pins the tiled row's column width; 0 leaves it to the row's M rule (the skinny row + * ignores it). * - * `ablk` hands the activation scale as the block-scaled fp8 family's grid, one f32 per (row, 128 - * of K), instead of one per row -- what an architecture's fused quantisers write. The scales are - * spread over two decades and every eleventh block's is ZERO with zero codes behind it (an - * all-zero activation block), which is the case the kernels carry their previous scale through. */ + * `ablk` passes the activation scale on the block-scaled fp8 grid, one f32 per (row, 128 of K), as + * fused quantisers write it. Scales span two decades, and every eleventh block's is zero with zero + * codes (an all-zero activation block), where the kernels carry their previous scale through. */ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_t N, int64_t K, int tn, bool ablk = false, std::vector extra = {}, int64_t pb1 = 0, int64_t pb2 = 0) { if (!sel(row)) return; - /* PARTS (ParoQuant): the weight's rows [0, pb1), [pb1, pb2), [pb2, N) each meet their own copy - * of the activation, the copies side by side in a row. `K` is one copy's width. */ + /* Parts (ParoQuant): weight rows [0, pb1), [pb1, pb2), [pb2, N) each meet their own copy of + * the activation, side by side in a row. `K` is one copy's width. */ const PartCut cut(N, pb1, pb2); const int parts = cut.parts; char nm[160]; @@ -3969,8 +3714,8 @@ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_ a.t = ts.data(); a.n_t = (int)ts.size(); a.p = ps.data(); a.n_p = (int)ps.size(); a.world_size = 1; - /* A row with a scratch hook (the decode row's split partial) gets what it asks for, as the - * core would hand it; the decode row refuses a split with too little. */ + /* A row with a scratch hook (the decode row's split partial) gets what it asks for, as from + * the core; the decode row refuses a split with too little. */ if (r->scratch) { const int64_t sb = r->scratch(&a); if (sb > 0) { @@ -3986,8 +3731,8 @@ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_ } st_memcpy(hy.data(), d_y, hy.size() * 2, hipMemcpyDeviceToHost); - /* Every column for small N, a stride otherwise -- always including the last column, which is - * the clamped tail of the tiled row's weight staging. */ + /* Every column for small N, a stride otherwise, always including the last column (the clamped + * tail of the tiled row's weight staging). */ const int64_t nstep = N > 96 ? N / 96 : 1; double num = 0, den = 0, worst = 0; for (int64_t i = 0; i < M; ++i) @@ -4013,16 +3758,16 @@ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_ } -/* PAROQUANT'S ACTIVATION QUANTISER AGAINST A DOUBLE-PRECISION ROTATION. The tables are real - * pairings -- every stage of every group is a random permutation of the group's 128 columns read - * as 64 pairs -- with angles over (-pi, pi) and channel scales over (0.5, 2), drawn through - * st_mix32 of their coordinates. The reference divides, rotates in f64 and takes the absmax; the - * kernel's scale must match it to the rounding of its f32 sincos, and every dequantised element - * must sit within the E4M3 grid of the reference (half a step at the top of the range is 1/16 of - * the group's maximum, so 7% of it is a bound a wrong pair or a wrong angle cannot meet). */ -/* What givens_numeric runs: the sequential rotation to f16, or the dense rotation with either quantiser. */ +/* What givens_numeric runs: the sequential rotation to f16, or the dense rotation with either + * quantiser. */ enum class GvCase { Rotate, DenseFp8, DenseI8 }; +/* ParoQuant's activation quantiser against a double-precision rotation. The tables are real + * pairings (each stage of each group a random permutation of its 128 columns read as 64 pairs), + * angles over (-pi, pi), channel scales over (0.5, 2). The reference divides, rotates in f64 and + * takes the absmax. The kernel's scale must match to the rounding of its f32 sincos, and each + * dequantised element must lie within the reference's E4M3 grid (half a step at the top of the + * range is 1/16 of the group maximum, so the 7% bound rejects a wrong pair or angle). */ static void givens_numeric(const Plugin& pl, int64_t M, int64_t K, int parts, int stages, GvCase mode) { const bool rot_only = mode == GvCase::Rotate, i8 = mode == GvCase::DenseI8, dense = !rot_only; const char* row = dense ? "givens_dense_quant" : "givens_rotate"; @@ -4084,8 +3829,8 @@ static void givens_numeric(const Plugin& pl, int64_t M, int64_t K, int parts, in PI("stages", stages), PI("parts", parts) }; if (dense) { // The matrices as a container stores them (the "t.dense" table, abi/rad_encoding.h): one - // 128x128 f16 matrix a (part, group), row p * ng + g, element [j][i] the image of column i - // under the stages, composed in f64 as rad-convert does. Through the row's own layout hook. + // 128x128 f16 matrix per (part, group), row p * ng + g, element [j][i] the image of column + // i under the stages, composed in f64 as rad-convert does; through the row's layout hook. std::vector dm((size_t)(parts * ng * G * G)); std::vector v((size_t)G); for (int p = 0; p < parts; ++p) @@ -4185,17 +3930,17 @@ static void givens_numeric(const Plugin& pl, int64_t M, int64_t K, int parts, in st_ev_destroy(e0); st_ev_destroy(e1); std::printf(" %.1f us a launch (%s)\n", (double)ms * 50.0, d); } - // the dense form carries f16 matrices: its scale reads ~1e-3 off the f32 network's, its values stay within the - // quantiser's own step + // The dense form carries f16 matrices: its scale is ~1e-3 off the f32 network's, and its + // values stay within the quantiser's own step. ok(nm, rot_only ? worst_val < 1e-3 : (worst_scale < (dense ? 3e-3 : 1e-4) && worst_val < (i8 ? 0.01 : 0.07)), d); } -/* PARO'S 5-BIT SKINNY GEMM against what the planes mean: u5 codes (a bit stream along K), an f16 scale - * and a zero point 0..31 a 128 of K, an f16 activation, the weight stored through the row's hooks. - * `pb1`/`pb2` give a partitioned weight (the activation copies side by side). M past 64 runs the - * dispatcher's 64-row chunks. */ +/* ParoQuant's 5-bit skinny GEMM against the planes' meaning: u5 codes (a bit stream along K), an + * f16 scale and a zero point 0..31 per 128 of K, an f16 activation, the weight stored through the + * row's hooks. `pb1`/`pb2` give a partitioned weight. M past 64 runs the dispatcher's 64-row + * chunks. */ static void w5a16_numeric(const Plugin& pl, int64_t M, int64_t N, int64_t K, int64_t pb1 = 0, int64_t pb2 = 0) { const char* row = "gemm_w5a16_nt_m64"; @@ -4279,9 +4024,9 @@ static void w5a16_numeric(const Plugin& pl, int64_t M, int64_t N, int64_t K, int } -/* TIMING OF THE 5/4-BIT GEMM AT ONE PREFILL CHUNK, over the row's tuned axes. `--case w5a16_perf` - * only (it is a measurement, not a check). One weight buffer is replicated past the last-level cache - * and walked in turn, as perf_row does, so the GB/s printed is the weight stream's. */ +/* Timing of the 5/4-bit GEMM at one prefill chunk over the row's tuned axes; `--case w5a16_perf` + * only (a measurement, not a check). The weight is replicated past the last-level cache and walked + * in turn, as in perf_row, so the printed GB/s is the weight stream's. */ static void w5a16_perf(const Plugin& pl, int bits, int64_t M, int64_t N, int64_t K) { if (!g_case || std::strcmp(g_case, "w5a16_perf")) return; const char* row = bits == 5 ? "gemm_w5a16_nt_m64" : "gemm_w4a16_asym_nt_m64"; @@ -4364,8 +4109,9 @@ static void w5a16_perf(const Plugin& pl, int bits, int64_t M, int64_t N, int64_t } -/* THE 4/5-BIT ASYMMETRIC x INT8 PREFILL GEMM against what the planes mean: u4/u5 codes, an f16 scale and - * a u8 zero a 128 of K, an int8 activation with an f32 scale a (row, 128), parts side by side. */ +/* The 4/5-bit asymmetric x int8 prefill GEMM against the planes' meaning: u4/u5 codes, an f16 + * scale and a u8 zero per 128 of K, an int8 activation with an f32 scale per (row, 128), parts + * side by side. */ static void wpa8i8_numeric(const Plugin& pl, int bits, int64_t M, int64_t N, int64_t K, int64_t pb1 = 0, int64_t pb2 = 0) { const char* row = bits == 4 ? "gemm_w4a8i8_tiled" : "gemm_w5a8i8_tiled"; @@ -4475,15 +4221,13 @@ static void wpa8i8_numeric(const Plugin& pl, int bits, int64_t M, int64_t N, int } -/* TWO DECODE GEMMS THE ENGINE MAY OVERLAP (gemm_mxfp4a8_decode is a concurrent row: its split partial - * is the op's scratch and its arrival counters are keyed on the output). Each GEMM has its own - * weights, activations and output and a DISJOINT slice of one scratch allocation, with a split - * (ks > 1) so the partial and the counters are live. The reference is each launched alone, then the - * pair is launched on two non-blocking streams with nothing ordering them -- repeated, so the - * launches overlap in different phases -- and every output must be BYTE-identical to the serial one - * (the reducer sums the splits in a fixed order, so a lost or shared counter / partial shows as a - * different byte or a hang). A last serial launch after the loop checks that the counters were - * left at zero. */ +/* Two decode GEMMs the engine may overlap (gemm_mxfp4a8_decode is a concurrent row: its split + * partial is the op's scratch and its arrival counters are keyed on the output). Each GEMM has its + * own operands and a disjoint slice of one scratch allocation, with a split (ks > 1) so the partial + * and counters are live. Each runs alone for a reference, then pairs run on two unordered + * non-blocking streams, repeatedly, and every output must be byte-identical (the reducer sums + * splits in a fixed order, so a lost or shared counter or partial shows as a different byte or a + * hang). A final serial launch checks the counters were left at zero. */ struct MxdOverlapGemm { int64_t M, N, K; int ks; @@ -4578,7 +4322,7 @@ static void mxd_overlap_case(const Plugin& pl) { for (int i = 0; i < 3; ++i) { off[i] = tot; tot += (g[i].scratch + 255) & ~int64_t(255); } char* base = (char*)dalloc((size_t)tot); if (!base) { ok(nm, false, "hipMalloc failed"); return; } - /* The serial reference gets its own scratch, so the two runs share nothing but the kernel. */ + /* The serial reference gets its own scratch, sharing nothing with the overlapped runs. */ std::vector> want(3); for (int i = 0; i < 3; ++i) { void* sc = dalloc((size_t)g[i].scratch); @@ -4635,7 +4379,7 @@ static void mxd_overlap_case(const Plugin& pl) { (void)hipStreamDestroy(s1); (void)hipStreamDestroy(s2); ok(nm, !bad, bad ? why : std::to_string(iters) + " overlapped pairs identical"); - /* The counters must be zero again: a serial launch after the storm is still byte-identical. */ + /* The counters must be zero again: a serial launch afterwards is still byte-identical. */ bool again = true; for (int i = 0; i < 3 && again; ++i) { st_memset(g[i].y, 0, (size_t)(g[i].M * g[i].N) * 2); @@ -4650,19 +4394,18 @@ static void mxd_overlap_case(const Plugin& pl) { ok("gemm_mxfp4a8_decode: serial after the overlap storm is still identical (counters left at " "zero)", again); /* A split given less scratch than its partial is refused, not run unsplit: the hook sized it - * for the whole band, so a short one is a caller's error and must surface as one. */ + * for the whole band, so a short one is a caller error. */ const int rc = mxd_overlap_launch(r, g[0], base + off[0], nullptr, g[0].scratch / 2); (void)st_stream_sync(nullptr); ok("gemm_mxfp4a8_decode: a split with half its scratch is refused", rc != RAD_OK, "rc=" + std::to_string(rc)); } -/* THE INT8 TRUNK CHAIN: quant_act_i8g on a bf16 activation, then one of the i8a8 GEMMs on what it - * wrote, against the planes' meaning. The weight is i8 with a bf16 scale per row per 128 K (what - * libquant writes for `codes=i8 group=128 scale=bf16 clamp=sym`), stored through the row's own - * hooks. The reference multiplies the codes the QUANTISER wrote -- read back -- by their scales, - * so what is left to disagree about is the GEMM alone; the quantiser is checked separately against - * a host one, code for code. Ragged M reaches the guarded fold; N and K are what the rows take. */ +/* The int8 trunk chain: quant_act_i8g on a bf16 activation, then an i8a8 GEMM on its output, + * against the planes' meaning. The weight is i8 with a bf16 scale per row per 128 K (libquant's + * `codes=i8 group=128 scale=bf16 clamp=sym`), stored through the row's hooks. The reference uses + * the codes the quantiser wrote, read back, so only the GEMM is under test; the quantiser is + * checked separately, code for code. Ragged M reaches the guarded fold. */ static void i8a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_t N, int64_t K) { if (!sel(row) && !sel("quant_act_i8g")) return; char nm[160]; @@ -4795,12 +4538,11 @@ static void i8a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_t N } -/* THE TILED bf16 GEMM AGAINST THE SKINNY ONE, BYTE FOR BYTE, at every tile variant. The claim in - * its row is identity and not closeness: an op declared over M 1..max_tok is served by the skinny - * row at M <= 64 and by this one above, so any difference would make a decode step and a prefill - * chunk disagree about the same row. The shapes reach both forms of the sum -- one slice (N wide - * enough that the split rule answers 1) and several (N 512 answers 4; K 64 answers a slice a k - * step) -- and ragged M and N, so a clamped fragment row that were ever stored would show. */ +/* The tiled bf16 GEMM against the skinny one, byte for byte, at every tile variant. An op over + * M 1..max_tok is served by the skinny row at M <= 64 and the tiled one above, so they must agree + * exactly or a decode step and a prefill chunk would disagree about the same row. The shapes reach + * one split-K slice and several (N 512 gives 4; K 64 one per k step), with ragged M and N so a + * stored clamped fragment row would show. */ static void bf16_tiled_identity(const Plugin& pl, int64_t M, int64_t N, int64_t K) { if (!sel("gemm_bf16_nt_tiled")) return; char nm[128]; @@ -4828,7 +4570,7 @@ static void bf16_tiled_identity(const Plugin& pl, int64_t M, int64_t N, int64_t auto run = [&](const RadKernelInfo* r, int64_t tile, std::vector& out) { std::vector ps = { PI("M", M), PI("N", N), PI("K", K), PS("dtype", "bf16") }; if (tile >= 0) ps.push_back(PI("tile", tile)); - /* A stale output would compare equal to itself, so the buffer is poisoned before each. */ + /* Poisoned before each run, since a stale output would compare equal. */ if (hipMemset(ts[2].data, 0xA5, (size_t)(M * N) * 2) != hipSuccess) return -1; RadArgs a; std::memset(&a, 0, sizeof(a)); @@ -4863,19 +4605,14 @@ static void bf16_tiled_identity(const Plugin& pl, int64_t M, int64_t N, int64_t /* logit_softcap, against an f64 evaluation of the same formula. * - * THE CAP IS THE PARAMETER THE MODEL LIVES IN (Gemma 4's graph issues it at 30.0), so the case - * runs at two values: the model's, and a smaller one that moves every answer -- a kernel that - * hard-wires 30.0, or one that swaps `cap` with its inverse, passes one cap and fails the other. - * - * The inputs are 0, half, one, two and five TIMES THE CAP, signed: x/cap is then an exact small - * half-integer, the f64 oracle cap * tanh(x/cap) is five constants deep, and the only room for an - * error in the comparison is the kernel's own f32 arithmetic and its bf16 store. The tolerance is - * this file's f32-against-f64 one (1% relative, 1e-3 absolute). */ + * Two caps: the model's (Gemma 4 issues 30.0) and a smaller one, so a hard-wired 30.0 or a cap + * swapped with its inverse fails one of them. Inputs are 0, 0.5, 1, 2 and 5 times the cap, signed, + * so x/cap is exact and only the kernel's f32 arithmetic and bf16 store can differ. Tolerance: 1% + * relative, 1e-3 absolute. */ static void logit_softcap_case(const Plugin& pl) { const char* what = "logit_softcap vs an f64 evaluation of the same formula"; - /* Both device legs run the case: bf16 (the gemm's own dtype) and f32 (the 1.3.0 sampling - * chain, where the logits reach the softcap as f32 rows). The f32 leg answers in the - * arithmetic dtype itself, so its oracle compare reads f32, not a bf16 round trip. */ + /* Both dtypes: bf16 (the GEMM's) and f32 (the sampling chain's logits). The f32 leg is + * compared in f32, not through a bf16 round trip. */ for (const uint32_t dt : { (uint32_t)RAD_BF16, (uint32_t)RAD_F32 }) { const char* row = dt == RAD_BF16 ? "logit_softcap_bf16" : "logit_softcap_f32"; const size_t es = dt == RAD_BF16 ? 2 : 4; @@ -4941,15 +4678,10 @@ static void logit_softcap_case(const Plugin& pl) { /* rmsnorm_p, against an f64 evaluation of the weightless normalisation. * - * THE EPS IS THE PARAMETER THE MODEL LIVES IN (Gemma 4 issues it at 1e-6), so the case runs at - * two values: the model's, and a larger one (1e-2) that moves every answer -- a kernel that hard- - * wires 1e-6, or one that drops the +eps and answers a bare 1/rms, passes the small one and fails - * the large. - * - * The inputs are a fixed set of magnitudes, signed, so the f64 oracle x * rsqrt(mean(x^2) + eps) - * is exact and the only room for an error in the comparison is the kernel's own f32 accumulation - * and its bf16 store. The oracle is computed from the bf16 values the kernel actually reads. The - * tolerance is this file's f32-against-f64 one (1% relative, 1e-3 absolute). */ + * Two eps values: the model's (Gemma 4 issues 1e-6) and 1e-2, so a hard-wired 1e-6 or a dropped + * +eps fails the larger one. The inputs are a fixed set of signed magnitudes, and the f64 oracle + * x * rsqrt(mean(x^2) + eps) is computed from the bf16 values the kernel reads. Tolerance: 1% + * relative, 1e-3 absolute. */ static void rmsnorm_p_case(const Plugin& pl) { const char* what = "rmsnorm_p vs an f64 evaluation of the weightless normalisation"; const RadKernelInfo* r = find(pl, "rmsnorm_p_bf16"); @@ -5016,11 +4748,10 @@ static void rmsnorm_p_case(const Plugin& pl) { /* gelu_mul, against an f64 evaluation of the tanh-approximation GELU. * - * The inputs are a fixed set of magnitudes, signed, for both the gate and the up half, so the f64 - * oracle 0.5*g*(1 + tanh(0.7978845608028654*(g + 0.044715*g^3))) * u is exact and the only room for - * an error in the comparison is the kernel's own f32 tanhf and its bf16 store. The oracle is computed - * from the bf16 values the kernel reads; the gate is the first half of the [M, 2n] row. The - * tolerance is this file's f32-against-f64 one (1% relative, 1e-3 absolute). */ + * Fixed signed magnitudes for the gate and up halves; the f64 oracle + * 0.5*g*(1 + tanh(0.7978845608028654*(g + 0.044715*g^3))) * u uses the bf16 values the kernel + * reads, the gate being the first half of the [M, 2n] row. Tolerance: 1% relative, 1e-3 + * absolute. */ static void gelu_mul_case(const Plugin& pl) { const char* what = "gelu_mul vs an f64 evaluation of the tanh GELU"; const RadKernelInfo* r = find(pl, "gelu_mul_bf16"); @@ -5083,16 +4814,10 @@ static void gelu_mul_case(const Plugin& pl) { /* scale, against an f64 evaluation of the same multiply. * - * THE SCALAR IS THE [1] WEIGHT THE MODEL LIVES IN (Gemma 4's per-layer scalar, 0.03-0.99), so the - * case runs at three values: two positive of different magnitude (a kernel that hard-wires one of - * them, or one that squares the scalar, passes one and fails the other) and a negative (a kernel - * that drops the sign passes the positives and fails this). - * - * The inputs are a fixed set of magnitudes, signed, so the f64 oracle x * s is five constants deep - * and the only room for an error in the comparison is the kernel's own f32 arithmetic and its bf16 - * store. The tolerance is this file's f32-against-f64 one (1% relative, 1e-3 absolute). The scalar - * is stored as f32 (the kernel's branch reads it as such); a bf16 `s` takes the other branch and is - * not exercised here, which is fine -- the multiply is the same either way. */ + * Three scalars (Gemma 4's per-layer scalar is 0.03-0.99): two positive of different magnitude, + * catching a hard-wired or squared scalar, and a negative one, catching a dropped sign. Inputs are + * fixed signed magnitudes. Tolerance: 1% relative, 1e-3 absolute. The scalar is stored as f32; the + * bf16 `s` branch is not exercised (same multiply). */ static void scale_case(const Plugin& pl) { const char* what = "scale vs an f64 evaluation of the same multiply"; const RadKernelInfo* r = find(pl, "scale_bf16"); @@ -5151,10 +4876,9 @@ static void scale_case(const Plugin& pl) { } } -/* rope_bf16, against an f32 mirror of rope_kernel at each ladder width. `den` is the ladder's - * width -- `rot` for `rotary`/absent and `head_dim` for `head` -- so the same kernel body is - * checked under both. The V head is untouched in every case; the absences there would be invisible - * in magnitude (the rotation preserves length) and rel_l2 is what sees the angle itself. */ +/* rope_bf16 against an f32 mirror of rope_kernel at each ladder width. `den` is the ladder's + * width (`rot` for `rotary`/absent, `head_dim` for `head`). The V head must stay untouched. rel_l2 + * catches a wrong angle, which magnitude alone would not (rotation preserves length). */ static void rope_ladder_case(const Plugin& pl) { const char* what = "rope ladder vs an f32 mirror of rope_kernel at each width"; const RadKernelInfo* r = find(pl, "rope_bf16"); @@ -5233,14 +4957,13 @@ static void rope_ladder_case(const Plugin& pl) { /* ---- the two fp8 fusions, against the pair each one replaces -------------------------------- */ // -// THE INVARIANT IS NOT "CLOSE", IT IS BYTE-IDENTICAL, which is why this compares against the -// UNFUSED KERNELS rather than a host mirror. The engine's own acceptance test is that generated -// text does not move across builds; a fused quantiser whose codes differed by one in the last -// place on a few channels a layer would pass any tolerance-based check and change the text anyway. +// Byte-identical, so the comparison is against the unfused kernels, not a host mirror: generated +// text must not move across builds, and a last-place code difference on a few channels would pass +// any tolerance. // -// The trap it guards is a single line. The unfused pair writes a BF16 norm output and the -// quantiser reads those bytes back, so the amax and the codes are taken over bf16-ROUNDED values. -// A fused kernel that quantises the f32 it already has in a register is MORE accurate, and wrong. +// The unfused pair writes a bf16 norm output and the quantiser reads it back, so amax and codes are +// taken over bf16-rounded values. A fused kernel quantising its f32 register value is more +// accurate, and wrong. static int launch_row(const RadKernelInfo* r, std::vector ts, std::vector ps) { RadArgs a; @@ -5266,9 +4989,8 @@ static void fused_quant_fp8_numeric(const Plugin& pl) { ok("fp8 fusions vs the unfused pair", false, "rows absent"); return; } - /* M is a speculative decode step's token count and K is a per-rank hidden width that is a - * whole number of 128-column groups without being a power of two -- five groups, so a wave - * that got its group stride wrong lands somewhere visible. */ + /* M is a speculative decode step's token count; K is five 128-column groups, not a power of + * two, so a wrong group stride lands somewhere visible. */ const int64_t M = 8, K = 640, nkb = K / 128; std::vector hx((size_t)M * K), hgu((size_t)M * 2 * K); @@ -5276,15 +4998,15 @@ static void fused_quant_fp8_numeric(const Plugin& pl) { for (int64_t r = 0; r < M; ++r) for (int64_t c = 0; c < K; ++c) { /* Per-group magnitudes an order of magnitude apart, so one group's amax cannot stand - in for its neighbour's, and one channel per row far above the rest, which is what a - dropped clamp turns into a NaN. */ + in for its neighbour's, and one channel per row far above the rest (a dropped clamp + turns it into a NaN). */ const float m = std::ldexp(1.0f, (int)(c / 128) - 2); const float v = m * (0.037f * (float)((r * 29 + c * 13) % 71) - 1.3f); hx[(size_t)r * K + c] = h_to_bf16(c == (r * 37) % K ? v * 19.0f : v); hgu[(size_t)r * 2 * K + c] = h_to_bf16(v * 0.75f); hgu[(size_t)r * 2 * K + K + c] = h_to_bf16(m * (0.011f * (float)((r + c * 7) % 43) - 0.2f)); } - /* A zero-centred gain, which is what GemmaRMSNorm stores and what makes `wadd` matter. */ + /* A zero-centred gain, as GemmaRMSNorm stores, so `wadd` matters. */ for (int64_t c = 0; c < K; ++c) hw[(size_t)c] = 0.004f * (float)((c * 19) % 51) - 0.1f; void* d_x = dalloc((size_t)M * K * 2); @@ -5317,8 +5039,7 @@ static void fused_quant_fp8_numeric(const Plugin& pl) { for (size_t i = 0; i < y0.size(); ++i) ny += y0[i] != y1[i]; for (size_t i = 0; i < q0.size(); ++i) nq += q0[i] != q1[i]; for (size_t i = 0; i < s0.size(); ++i) ns += std::memcmp(&s0[i], &s1[i], 4) != 0; - /* A run that wrote nothing at all would compare equal against a zeroed buffer, so the - * codes are also required to be non-trivial. */ + /* The codes must also be non-trivial: a run that wrote nothing would compare equal. */ int nz = 0; for (size_t i = 0; i < q1.size(); ++i) nz += q1[i] != 0; ok(what, ny == 0 && nq == 0 && ns == 0 && nz > (int)q1.size() / 2, @@ -5364,11 +5085,9 @@ static void fused_quant_fp8_numeric(const Plugin& pl) { /* --- sigmoid + mul + quant_act_fp8, against gate_quant_fp8 --- * - * The gated attention's epilogue, and the case that says the two-buffer form agrees with the - * three passes it replaces. The gate is the FIRST half of `gu` and the thing it scales is the - * second, which is the packed layout; the strided form -- a column view of a [q|gate] - * projection -- differs from it only in the pitch the shim reads off the operand, and the - * arch is the only place that shape exists. */ + * The gated attention's epilogue. The gate is the first half of `gu` and the scaled value the + * second; the engine's strided form (a column view of a [q|gate] projection) differs only in + * the pitch the shim reads off the operand. */ rc = launch_row(sg, { T(d_gu, RAD_BF16, { M, K }), T(d_y[0], RAD_BF16, { M, K }) }, { PI("M", M), PI("n", K), PS("dtype", "bf16") }); if (rc == RAD_OK) @@ -5389,11 +5108,10 @@ static void fused_quant_fp8_numeric(const Plugin& pl) { "rc=" + std::to_string(rc)); else same("gate_quant_fp8 is byte-identical to sigmoid + mul + quant_act_fp8"); - /* --- the same two at INT8 codes, against the same products and quant_act_i8g --- + /* --- the same two at int8 codes, against the same products and quant_act_i8g --- * - * An int8 trunk linear reads int8 codes, and the producer in front of it writes them itself - * when its codes operand is I8: the bf16 product must not move, and the codes and scales must - * be what quant_act_i8g takes over that product. */ + * With an I8 codes operand the producer writes int8 codes for an int8 trunk linear: the bf16 + * product must not move, and codes and scales must equal quant_act_i8g's over it. */ if (const RadKernelInfo* qi = find(pl, "quant_act_i8g")) { rc = launch_row(smu, { T(d_gu, RAD_BF16, { M, 2 * K }), T(d_y[0], RAD_BF16, { M, K }) }, { PI("M", M), PI("n", K), PS("dtype", "bf16") }); @@ -5430,8 +5148,7 @@ static void fused_quant_fp8_numeric(const Plugin& pl) { "rc=" + std::to_string(rc)); else same("gate_quant_fp8 at int8 codes is byte-identical to sigmoid + mul + quant_act_i8g"); - /* The rotated form pairs with E4M3 experts only, and says so rather than writing codes - * no reader could use. */ + /* The rotated form pairs with E4M3 experts only and refuses int8 codes. */ if (const RadKernelInfo* gh = find(pl, "gated_had_quant_fp8")) { rc = launch_row(gh, { T(d_gu, RAD_BF16, { M, 2 * K }), T(d_q[1], RAD_I8, { M, K }), T(d_s[1], RAD_F32, { M, nkb }) }, @@ -5443,16 +5160,13 @@ static void fused_quant_fp8_numeric(const Plugin& pl) { /* --- add + rmsnorm + quant_act_fp8, against the same three fused --- * - * The residual is what a block folds into the norm in front of it, and it is the case where - * "bit-identical" is a real choice rather than a formality: the sum is f32 and the pair this - * replaces ROUNDS IT TO BF16 in `add`'s store before `rmsnorm` ever sees it. Keeping the f32 - * sum -- which is what the int8 sibling does, and is more accurate -- moves the text. */ + * The residual sum is f32, and the replaced pair rounds it to bf16 in `add`'s store before + * `rmsnorm` reads it. Keeping the f32 sum (as the int8 sibling does) would move the text. */ const RadKernelInfo* ad = find(pl, "add_bf16"); if (!ad) { ok("rmsnorm_quant_fp8 residual", false, "add_bf16 absent"); return; } void* d_r[2] = { dalloc((size_t)M * K * 2), dalloc((size_t)M * K * 2) }; if (!d_r[1]) { ok("fp8 fusion residual alloc", false, "hipMalloc failed"); return; } - /* A residual with its own structure, and BOTH copies start from it: the fused form updates it - * in place, so a shared buffer would have the second run reading the first run's output. */ + /* A structured residual, copied for each run: the fused form updates it in place. */ std::vector hr((size_t)M * K); for (int64_t r = 0; r < M; ++r) for (int64_t c = 0; c < K; ++c) @@ -5547,12 +5261,11 @@ static void gelu_mul_quant_i8_numeric(const Plugin& pl) { /* ---- qkv_norm_rope, against the five ops it replaces ------------------------------------------ * - * rmsnorm_p (v, or the raw k under v_from_k), rmsnorm over the q heads and over the k heads, then - * rope over q and over k -- kernel by kernel, against the one dispatch. Both of Gemma 4 31B's - * classes at one rank of two: sliding (head_dim 256, 16 q over 8 kv heads, full rotary, separate v) - * and global (512, 16 over 2, the proportional `head` ladder over 128, k == v), at batch heights - * that put the q/k norms at every width r4d_act_threads answers -- including 256 at head_dim 512, - * where a thread of the standalone norm folds two channels. */ + * rmsnorm_p (v, or the raw k under v_from_k), rmsnorm over the q heads and the k heads, then rope + * over q and k, kernel by kernel, against the one dispatch. Both of Gemma 4 31B's classes at one + * rank of two: sliding (head_dim 256, 16 q over 8 kv heads, full rotary, separate v) and global + * (512, 16 over 2, the proportional `head` ladder over 128, k == v), at batch heights reaching + * every width r4d_act_threads answers, including 256 at head_dim 512 (two channels per thread). */ static void qkv_norm_rope_numeric(const Plugin& pl) { const RadKernelInfo* np = find(pl, "rmsnorm_p_bf16"); const RadKernelInfo* nrm = find(pl, "rmsnorm_bf16"); @@ -5633,12 +5346,12 @@ static void qkv_norm_rope_numeric(const Plugin& pl) { /* ---- rmsnorm_quant_i8, against the chain it replaces ------------------------------------------ * - * Byte-identical, for the reason the fp8 fusions above give, in all three forms a sandwich-norm - * model issues: the plain norm + quantiser (a first block's entry), the junction without a scalar - * (attention -> feed-forward) and with one (feed-forward -> the next layer). The unfused chain is - * rmsnorm(x; w_post) -> add(residual) -> scale -> rmsnorm(residual; w) -> quant_act_i8, run here - * kernel by kernel. bf16 gains, which is what Gemma's checkpoint stores, and two batch heights so - * both of r4d_act_threads' widths a decode step meets are covered (1024 at M <= 32, 512 above). */ + * Byte-identical, as the fp8 fusions above, in the three forms a sandwich-norm model issues: the + * plain norm + quantiser (a first block's entry), the junction without a scalar (attention -> + * feed-forward) and with one (feed-forward -> next layer). The unfused chain, kernel by kernel, is + * rmsnorm(x; w_post) -> add(residual) -> scale -> rmsnorm(residual; w) -> quant_act_i8. bf16 gains + * (as Gemma's checkpoint stores), and two batch heights covering both r4d_act_threads widths a + * decode step meets (1024 at M <= 32, 512 above). */ static void rmsnorm_quant_i8_numeric(const Plugin& pl) { const RadKernelInfo* nrm = find(pl, "rmsnorm_bf16"); const RadKernelInfo* ad = find(pl, "add_bf16"); @@ -5647,7 +5360,7 @@ static void rmsnorm_quant_i8_numeric(const Plugin& pl) { const RadKernelInfo* rq = find(pl, "rmsnorm_quant_i8"); if (!nrm || !ad || !scl || !qz || !rq) { ok("rmsnorm_quant_i8 vs its chain", false, "rows absent"); return; } for (const int64_t M : { (int64_t)1, (int64_t)8, (int64_t)40 }) { - const int64_t K = 5376; /* Gemma 4 31B's hidden width: 336 sixteen-byte k steps, not a power of two */ + const int64_t K = 5376; /* Gemma 4 31B's hidden width: 336 sixteen-byte k steps */ std::vector hx((size_t)M * K), hr((size_t)M * K), hw((size_t)K), hp((size_t)K); for (int64_t r = 0; r < M; ++r) for (int64_t c = 0; c < K; ++c) { @@ -5744,17 +5457,15 @@ static void rmsnorm_quant_i8_numeric(const Plugin& pl) { } } -/* THE fp8 lm_head, end to end through its OWN hooks. +/* The fp8 lm_head, end to end through its own hooks. * - * The arrangement is the odd one in this library -- E4M3 codes with the row's own bf16 scales in - * the tail of the same row, rather than the separate [sn][sk] plane the linears read -- so the - * things that can go wrong are the interleave (a scale read from the wrong row), the f32 store - * (this is the op most prone to a bf16 write into an f32 plane), and the m_real mask on the - * instantiations that round M up. + * Unlike the linears' separate [sn][sk] plane, each stored row carries its own bf16 scales in its + * tail, so this checks the interleave (a scale read from the wrong row), the f32 store (a bf16 + * write into the f32 plane) and the m_real mask on instantiations that round M up. * - * The weight is block fp8's two planes, relaid by the row's own hooks into the row it reads; the - * oracle is those planes, code times its block's scale. The inverse must give the planes back. */ -/* `i8`: the int8 head, logits_gemm_i8 -- i8 codes with a bf16 scale a ROW per 128 columns. */ + * The weight is block fp8's two planes, relaid by the row's hooks; the oracle is code times its + * block's scale, and the inverse must return the planes. `i8` selects the int8 head + * (logits_gemm_i8): i8 codes with a bf16 scale per row per 128 columns. */ static void fp8_logits_numeric(const Plugin& pl, int64_t N, int64_t K, int64_t M, bool i8 = false) { const char* row = i8 ? "logits_gemm_i8" : "logits_gemm_fp8"; const RadKernelInfo* lg = find(pl, row); @@ -5839,13 +5550,12 @@ static void fp8_logits_numeric(const Plugin& pl, int64_t N, int64_t K, int64_t M if (!d_w || !d_x || !d_y) { ok(i8 ? "i8 logits alloc" : "fp8 logits alloc", false, std::string("hipMalloc failed") + tag); return; } st_memcpy(d_w, wq.data(), wq.size(), hipMemcpyHostToDevice); st_memcpy(d_x, xb.data(), (size_t)M * K * 2, hipMemcpyHostToDevice); - /* Poisoned, so a kernel that writes bf16 pairs into the f32 plane -- the failure mode this op - * is prone to -- cannot pass by leaving the high half of each word at zero. */ + /* Poisoned, so a kernel writing bf16 pairs into the f32 plane cannot pass on zeroed high + * halves. */ st_memset(d_y, 0x5a, (size_t)M * N * 4); - // THE DECLARED SHAPE, [N][K] and not [N][K + 2*nkb], because that is what the engine hands a - // kernel: core/runtime/ctx.cpp builds a weight's tensor from decl.shape with the layout - // hook's dtype. Passing the stored width here would test a call the engine never makes. + // The declared shape [N][K], not the stored [N][K + 2*nkb]: core/runtime/ctx.cpp builds a + // weight's tensor from decl.shape with the layout hook's dtype. const int rc = launch_row(lg, { T(d_x, RAD_BF16, { M, K }), T(d_w, i8 ? RAD_I8 : RAD_F8E4M3, { N, K }), T(d_y, RAD_F32, { M, N }) }, @@ -5865,9 +5575,9 @@ static void fp8_logits_numeric(const Plugin& pl, int64_t N, int64_t K, int64_t M ok(i8 ? "logits_gemm_i8 vs host ref over its planes" : "logits_gemm_fp8 vs host ref over its planes", e < 2e-3, "rel_l2 " + std::to_string(e) + tag); - /* THE DRAFTER'S RESCORING READS THE SAME STORED HEAD, so it is checked over the same bytes: - * R candidates a row -- one of them an id past the shard, which must come back a pad -- each - * scored against the planes, and the answer sorted by value. */ + /* The drafter's rescoring reads the same stored head, so it is checked over the same bytes: + * R candidates per row (one an id past the shard, which must come back a pad), each scored + * against the planes, sorted by value. */ const RadKernelInfo* rr = find(pl, i8 ? "logit_rerank_i8" : "logit_rerank"); if (!rr) return; const int64_t R = std::min(8, N); @@ -5910,6 +5620,18 @@ static void fp8_logits_numeric(const Plugin& pl, int64_t N, int64_t K, int64_t M ok(rn.c_str(), bad == 0, std::to_string(bad) + " wrong ids, values or orderings"); } +/* The fp8 GEMM against a host reference on the same bytes (spec §17). A weight's two block-fp8 + * planes are arranged by the plugin's own layout hooks, the planes are dequantised on the host, + * and the results compared. This catches a wrong arrangement, wrong scale indexing (an off-by-one + * `>> 7` reads a neighbouring tile), a misplaced fold in the K loop and, for fp8a8, a wrong + * activation quantiser or epilogue transpose. + * + * Both sides use the same quantised weight, so only summation order may differ. The bound is + * bf16's resolution (2^-8 relative) loosened to 3e-2, since a K=512 reduction reordered across 32 + * lanes moves the last bf16 bit near a rounding boundary; a transposed operand or misread scale + * lands two orders of magnitude away. The W8A8 rows also quantise the activation to E4M3 (about 6% + * per element before averaging), so their error is higher. The two W8A8 rows put the weight on + * opposite operands with opposite scale shapes and epilogues, so their failure modes differ. */ static void fp8_numeric(const Plugin& pl, int64_t N, int64_t K) { const RadKernelInfo* mv = find(pl, "gemm_fp8a16_nt_m1"); const RadKernelInfo* tl = find(pl, "gemm_fp8a8_tiled"); @@ -5921,19 +5643,12 @@ static void fp8_numeric(const Plugin& pl, int64_t N, int64_t K) { } const int64_t sn = N / 128, sk = K / 128; - /* A weight with real structure: an asymmetric, per-block-varying magnitude. A constant or a - * symmetric pattern cannot tell a transposed fragment from a correct one -- both give zero - * error -- and cannot tell one block scale from its neighbour either. + /* A weight with an asymmetric, per-block-varying magnitude; a constant or symmetric pattern + * cannot distinguish a transposed fragment or a neighbouring block's scale. * - * THE EXPONENT WRAPS, and it has to. An unwrapped `(r/128)*3 - (c/128)` reaches 405 by row - * 17408 at 128 rows a step, and ldexp(1.0f, 405) is INFINITY -- so the generator would produce - * a valid weight only below about 5400 rows and every fp8 numeric case in this file would be - * pinned to N = 256: raising it would fill the weight with inf rather than exercise a bigger - * shape. Every large projection in the model is 17408 rows. - * - * Wrapping the block index keeps what the variation is FOR -- neighbouring 128-row blocks still - * differ by 8x, which is what tells one block scale from the next -- and bounds the range at - * 2^12, comfortably inside float and inside E4M3's own reach after the per-block scale. */ + * The exponent wraps: unwrapped, `(r/128)*3 - (c/128)` reaches 405 by row 17408 and + * ldexp(1.0f, 405) is infinity. Wrapped, neighbouring 128-row blocks still differ by 8x and the + * range stays within 2^12. */ std::vector wf((size_t)N * K); for (int64_t r = 0; r < N; ++r) for (int64_t c = 0; c < K; ++c) @@ -5941,16 +5656,9 @@ static void fp8_numeric(const Plugin& pl, int64_t N, int64_t K) { std::ldexp(1.0f, (int)(((r / 128) % 5) * 3 - ((c / 128) % 4))) * (0.031f * (float)((r * 37 + c * 11) % 61) - 0.9f); - /* TWO ARRANGEMENTS OF ONE PAIR OF PLANES, and the two-arrangement part is not optional. The - * fp8a16 matvec reads the planes ROW-MAJOR, as they are; the two fp8a8 GEMMs read the same - * codes permuted into WMMA FRAGMENT ORDER, and each row's own layout hook says which it wants. - * - * Building ONE arrangement and testing all three kernels against it is how this test lies: the - * oracle and a fp8a8 kernel would then read the same bytes the same way, agree with each - * other, both disagree with the weight, and the case would report ok. - * - * ONE oracle is still right, because an arrangement does not change VALUES: the planes, - * dequantised on the host, are the reference for every kernel. */ + /* Two arrangements of one pair of planes: the fp8a16 matvec reads them row-major, the fp8a8 + * GEMMs read the codes in WMMA fragment order, each as its own layout hook says. One oracle + * serves all: the planes dequantised on the host. */ const Planes p = fp8_block_planes(wf, N, K); std::vector lp = { PI("N", N), PI("K", K), PI("group", 128) }; std::vector wq, wqf, wsb, wsf; @@ -6014,8 +5722,7 @@ static void fp8_numeric(const Plugin& pl, int64_t N, int64_t K) { }; /* --- the matvec, at every point of its declared space: `rb` changes which rows share an - * activation window, and a wrong RB reads the neighbouring row's scale. That is exactly - * the bug a smoke test misses. */ + * activation window, and a wrong RB reads the neighbouring row's scale. */ for (const TunePoint& tp : tune_points(mv, std::vector{ PI("M", 1), PI("N", N), PI("K", K), PI("group", 128), PS("dtype", "fp8a16") })) { @@ -6038,17 +5745,11 @@ static void fp8_numeric(const Plugin& pl, int64_t N, int64_t K) { ok(what.c_str(), e < 3e-2, "rel_l2 " + std::to_string(e)); } - /* --- THE MULTI-ROW MATVEC, which is what a speculative verify step runs: M = 1 + n_spec token - * rows against one weight read. - * - * THE ROWS ARE DELIBERATELY DISTINCT, and that is the whole value of this case. The failure - * it exists to catch is a token row reading another row's activation -- an `a_ld` off by - * anything, or a hoisted pointer -- and the W8A8 case below CANNOT see that, because every - * row there holds the same vector and a kernel that read row 0 five times would pass it. - * Each row is checked against its own host reference. - * - * M = 5 rather than a power of two: it is 1 + n_spec at n_spec 4, and rounding a token count - * up to a template instantiation is exactly the kind of thing that works at 4 and 8. */ + /* --- the multi-row matvec, as a speculative verify step runs it: M = 1 + n_spec token rows + * against one weight read. The rows are distinct, each with its own host reference, to + * catch a row reading another's activation (a wrong `a_ld`, a hoisted pointer). M = 5 + * (n_spec 4) is not a power of two, so a token count rounded up to an instantiation + * shows. */ { const int64_t M = 5; void* d_xm = dalloc((size_t)M * K * 2); @@ -6100,27 +5801,21 @@ static void fp8_numeric(const Plugin& pl, int64_t N, int64_t K) { } } - /* --- the NARROW W8A8 row, which is the riskiest kernel in the family and the only one where - * two hazards meet: the epilogue TRANSPOSES (the weight is on the A - * operand there, so D is [N][M] and C must be [M][N]), and split-K is on. At N=256, K=512 - * the split law gives ksplit=2, so the partial plane and the reduce are both exercised. - * M=8 is deliberately not a multiple of the 16-wide token tile: the ragged path is what a - * speculative batch actually runs. Every one of the 8 rows must match, because a wrong - * transposed stride writes one right row and seven wrong ones. */ + /* --- the narrow W8A8 row, where two hazards meet: the epilogue transposes (the weight is the + * A operand, so D is [N][M] and C must be [M][N]), and split-K is on (N=256, K=512 gives + * ksplit=2, exercising the partial plane and the reduce). Ragged M (not a multiple of the + * 16-wide token tile) is what a speculative batch runs. Every row must match, since a + * wrong transposed stride writes one right row. */ { - /* EVERY TOKEN-TILE COUNT AND BOTH SIDES OF `Full`. The narrow tile covers NT * 16 tokens - * with one weight read, and NT is chosen from M, so the M list has to cross every - * boundary: 1 and 8 are NT = 1 (and M = 1 is the only M where the Full predicate and the - * transposed epilogue see a single token), 24 and 32 are NT = 2, 40 and 48 are NT = 3, - * and 64 is NT = 4. + /* Every token-tile count and both sides of `Full`. The narrow tile covers NT * 16 tokens + * per weight read, NT chosen from M: 1 and 8 give NT = 1, 24 and 32 NT = 2, 40 and 48 + * NT = 3, 64 NT = 4. * - * The ODD ones are the point. `Full` drops the epilogue's column guard, and it means "all - * NT tiles are live", NOT "M is a multiple of 16" -- at M = 48 with NT = 4 the second is - * true and the first is false, and a kernel that conflated them writes columns 48..63 - * past the end of a split-K scratch sized for 48, over the arrival counter, and the - * finisher spins forever. 24 and 48 are here to keep that covered, and 40 is the one M in - * the band that is ragged under NT = 3 as well -- 48 is a whole number of tiles there and - * would not exercise it. */ + * `Full` drops the epilogue's column guard and means "all NT tiles are live", not "M is a + * multiple of 16": at M = 48 with NT = 4 the second holds and the first does not, and a + * kernel conflating them writes columns 48..63 past a split-K scratch sized for 48, over + * the arrival counter, and the finisher hangs. 24 and 48 cover that; 40 is ragged under + * NT = 3 as well. */ for (const int64_t M : { (int64_t)1, (int64_t)8, (int64_t)24, (int64_t)32, (int64_t)40, (int64_t)48, (int64_t)64 }) { void* d_xm = dalloc((size_t)M * K * 2); @@ -6131,9 +5826,8 @@ static void fp8_numeric(const Plugin& pl, int64_t N, int64_t K) { if (!nr) { ok("gemm_fp8a8_nt_m16 numeric", false, "row absent"); } else if (!d_xm || !d_q || !d_qs || !d_ym) { ok("fp8 narrow alloc", false, "hipMalloc failed"); } else { - /* DISTINCT ROWS, because identical ones cannot see the failure this case exists - * for: a token tile reading another tile's activation. With every row the same vector - * a kernel that read row 0 sixty-four times passes. Each row gets its own reference. */ + /* Distinct rows, each with its own reference, so a token tile reading another tile's + * activation shows. */ std::vector xm((size_t)M * K); for (int64_t m = 0; m < M; ++m) for (int64_t c = 0; c < K; ++c) @@ -6185,27 +5879,23 @@ static void fp8_numeric(const Plugin& pl, int64_t N, int64_t K) { " DISTINCT rows (transposed store + split-K)").c_str(), worst < 8e-2, "rel_l2 " + std::to_string(worst)); - /* THE WAVE COUNT MUST NOT MOVE A BYTE, and this is the only place that can be asked. - * MW is a launch heuristic chosen from (N, M) inside libr4d, so a rule change is - * invisible from out here and the environment pin that sweeps it is read once a - * process -- one run cannot hold two settings. A rel_l2 against a host reference will - * not answer it either: a wave count that moved the last bit of every element passes - * that at 1e-7 and changes the emitted text. + /* The wave count must not move a byte. MW is a launch heuristic chosen from (N, M) + * inside libr4d, pinned here through the test hook; a rel_l2 check would pass a + * last-bit change that moves the emitted text. * - * A DIFFERENT GRID IS ALLOWED TO DIFFER. `narrow_ksplit` decides from `gx * mw`, which - * is N/16 only when N divides MW*16; where it does not, the split repartitions K and - * the accumulation chain legitimately changes. So the sweep compares the wave counts - * whose grid the shape actually admits, which is the same test the rule applies to - * itself when it asks `n % 128` and `n % 256`. */ + * A different grid may differ: `narrow_ksplit` decides from `gx * mw`, which is N/16 + * only when N divides MW*16; otherwise the split repartitions K. So only the wave + * counts whose grid the shape admits are compared (the rule's own `n % 128` and + * `n % 256` test). */ if (pl.pin_mw) { const std::vector base = got; std::vector alt((size_t)M * N); std::string why; for (const int mw : { 1, 2, 4, 8, 16 }) { if (N % (mw * 16)) continue; - /* A K that is not a multiple of 256 runs the 128-wide staged set, which - * compiles only the wave counts the rule answers (4, 8, 16); a pin outside - * them is refused by contract -- see R4D_F8D_NT128 in r4d_gemm_fp8a8.hip. */ + /* A K not a multiple of 256 runs the 128-wide staged set, which compiles + * only the wave counts the rule answers (4, 8, 16); other pins are refused + * (R4D_F8D_NT128 in r4d_gemm_fp8a8.hip). */ if (K % 256 && mw != 4 && mw != 8 && mw != 16) continue; pl.pin_mw(mw); st_memset(d_ym, 0, (size_t)M * N * 2); @@ -6219,12 +5909,10 @@ static void fp8_numeric(const Plugin& pl, int64_t N, int64_t K) { why.empty(), why); } - /* AND THE TOKEN-TILE COUNT MUST NOT MOVE A BYTE EITHER, for the same reason and with - * one extra hazard the wave count does not have. NT decides which wave owns which - * token AND it feeds `Full`: at M = 48 the rule's NT = 3 makes Full true where NT = 4 - * makes it false, so the pin sweeps two different epilogue paths as well as two - * different tilings. The pin only goes UP -- NT*16 is the column extent the epilogue - * may write, so NT below ceil(M/16) drops rows rather than running a slower variant. */ + /* Nor may the token-tile count. NT also feeds `Full`: at M = 48, NT = 3 makes Full + * true and NT = 4 false, so the pin sweeps two epilogue paths. The pin only goes up: + * NT*16 is the column extent the epilogue may write, so NT below ceil(M/16) would + * drop rows. */ if (pl.pin_nt) { const std::vector base = got; std::vector alt((size_t)M * N); @@ -6243,31 +5931,21 @@ static void fp8_numeric(const Plugin& pl, int64_t N, int64_t K) { why.empty(), why); } - /* ---- ...AND WITH THE GATE AND THE QUANTISER FOLDED INTO ITS EPILOGUE ------------- + /* ---- ...and with the gate and the quantiser folded into its epilogue ------------- * - * THE QUESTION IS BYTE EQUALITY AND NOTHING ELSE, for the reason the wave-count sweep - * above gives from the other side: the engine substitutes the fold for the pair on a - * band, so a fold that moved the last bit of every code would be a SECOND numerical - * path wearing the first one's name, and a rel_l2 against a host reference would pass - * it at 1e-7 while the emitted text moved. The pair is this GEMM's bf16 output read - * back by `gated_quant_fp8`; the fold never writes that tensor at all. - * - * Run over the same M list, which crosses every token-tile count, and over N = 256, - * 5120 and 17408 -- the last is gate_up's own per-rank width, so the shape the engine - * issues is one of the shapes checked and not an extrapolation from smaller ones. */ + * Byte equality: the engine substitutes the fold for the pair (this GEMM's bf16 + * output read back by `gated_quant_fp8`), so any last-bit difference would be a second + * numerical path. Over the same M list and N = 256, 5120 and 17408 (gate_up's + * per-rank width). */ const RadKernelInfo* gq = find(pl, "gated_quant_fp8"); const RadKernelInfo* gg = find(pl, "gemm_fp8a8_gated_nt_m16"); - /* The fold stages K 256 wide and refuses any other K. The one K % 256 shape in - * the engine is the shared expert's down projection, which is never gated. */ + /* The fold stages K 256 wide and refuses other K; the engine's one K % 256 shape, + * the shared expert's down projection, is never gated. */ if (gq && gg && N % 256 == 0 && K % 256 == 0) { const int64_t nout = N / 2, gkb = nout / 128; - /* THE FOLD REFUSES A SHAPE WHOSE GRID THE SPLIT RULE WOULD WIDEN, and that is a - * contract and not an accident: it has no partial plane to reduce and no second - * launch to fold a reduce into. `narrow_ksplit` splits when `K >= 512` and - * `N/16 < 128`, so N = 256 here is a REFUSAL and the equality question does not - * arise. gate_up is 17408 rows and never comes near it; the k and v projections - * that do are not gated. Asserted rather than skipped, because a fold that served - * this shape by ignoring the split would be silently wrong. */ + /* The fold refuses a shape the split rule would split (it has no partial plane): + * `narrow_ksplit` splits when `K >= 512` and `N/16 < 128`, so N = 256 must be + * refused. Asserted, since serving it while ignoring the split would be wrong. */ const bool splits = K >= 512 && N < 2048; void* d_gq[2] = { dalloc((size_t)M * nout), dalloc((size_t)M * nout) }; void* d_gs[2] = { dalloc((size_t)M * gkb * 4), dalloc((size_t)M * gkb * 4) }; @@ -6275,8 +5953,7 @@ static void fp8_numeric(const Plugin& pl, int64_t N, int64_t K) { if (!d_gq[1] || !d_gs[1] || !d_gy[1]) { ok("gated fold alloc", false, "hipMalloc failed"); } else { - /* The GEMM is re-run because the wave-count sweep left the LAST pin's output - * in d_ym, and a pinned wave count is not what the engine issues. */ + /* Re-run the GEMM: d_ym holds the last pinned wave count's output. */ st_memset(d_ym, 0, (size_t)M * N * 2); run_case(nr, ts, ps); int rc = launch_row(gq, { T(d_ym, RAD_BF16, { M, N }), @@ -6322,8 +5999,7 @@ static void fp8_numeric(const Plugin& pl, int64_t N, int64_t K) { for (size_t i = 0; i < z0.size(); ++i) nz += std::memcmp(&z0[i], &z1[i], 4) != 0; for (size_t i = 0; i < b0.size(); ++i) nb += b0[i] != b1[i]; - /* Two zeroed buffers compare equal, so the codes are also required to be - * non-trivial -- the failure mode a fold that wrote nothing would have. */ + /* The codes must also be non-trivial: zeroed buffers compare equal. */ for (size_t i = 0; i < c1.size(); ++i) live += c1[i] != 0; ok((std::string("gemm_fp8a8_gated_nt_m16 is byte-identical to the GEMM + " "gated_quant_fp8, N ") + std::to_string((long long)N) + @@ -6339,11 +6015,11 @@ static void fp8_numeric(const Plugin& pl, int64_t N, int64_t K) { } } - /* --- A ROW SHARD, AS THE LOADER MAKES ONE: rank 1's share of each canonical plane -- rows - * [N/2, N) of the codes and the scale rows that cover them, cut on the scale plane's 128-row - * blocks -- relaid by the row's own hook as a weight of N/2 rows, which has to reproduce - * rows [N/2, N) of the full run. The share is cut BEFORE the arrangement, so a relayout - * that leaned on rows it was not handed shows here. */ + /* --- a row shard, as the loader makes one: rank 1's share of each canonical plane (rows + * [N/2, N) of the codes and the scale rows covering them, cut on 128-row blocks), relaid + * by the row's hook as an N/2-row weight, must reproduce rows [N/2, N) of the full run. + * The share is cut before the arrangement, so a relayout reading rows it was not handed + * shows. */ if (N % 32 == 0 && (N / 2) % 128 == 0) { const int64_t Nh = N / 2, snh = Nh / 128, M = 8; const Planes half = share(p, Nh, N, 0, K); @@ -6405,15 +6081,12 @@ static void fp8_numeric(const Plugin& pl, int64_t N, int64_t K) { } } - /* --- A COLUMN SHARD, which is where a fragment plane and a row-major one stop agreeing. + /* --- a column shard, where a fragment plane and a row-major one stop agreeing. * - * The fragment arrangement groups sixteen rows into one run, so a K-slice of the WHOLE - * arranged plane is a 2D copy of pitch K*16 and width (K/tp)*16 -- the shape a loader that cut - * arranged bytes would have to know. The loader cuts the CANONICAL planes instead, where a - * column share is a plain rectangle of the codes and of the scale plane, and the kernel's hook - * arranges each rank's share as a weight of K/2. Both shares are made that way here and run - * as independent weights; their sum is what the all-reduce forms, and it has to be the - * unsharded product. */ + * The loader cuts the canonical planes (a column share is a plain rectangle of codes and + * scales) and the hook arranges each share as a K/2 weight, rather than slicing the arranged + * plane (a pitch-K*16 copy). Both shares run as independent weights; their sum, as the + * all-reduce forms it, must equal the unsharded product. */ if (K % 256 == 0) { const int64_t Kh = K / 2, skh = Kh / 128, M = 8; void* d_xh = dalloc((size_t)M * Kh * 2); @@ -6487,12 +6160,12 @@ static void fp8_numeric(const Plugin& pl, int64_t N, int64_t K) { } } - /* --- the tiled W8A8 path: quantise the activation with the library's own quantiser, then GEMM. - * M is 128 so the tile is exactly full; every row holds the SAME activation, so a wrong - * epilogue index shows up as one row of the output being right and the rest not. */ + /* --- the tiled W8A8 path: quantise the activation with the library's own quantiser, then + * GEMM. Every row holds the same activation, so a wrong epilogue index shows as one row + * right and the rest wrong. */ { - /* THE PREFILL WIDTH. 128 is one FM tile and grid.x = 1; a prefill chunk is 2048 and - * sixteen of them, which is the only place a per-M-block staging bug can show. */ + /* A prefill chunk: 2048 rows is sixteen 128-row tiles, so a per-M-block staging bug + * shows. */ const int64_t M = 2048; void* d_xm = dalloc((size_t)M * K * 2); void* d_q = dalloc((size_t)M * K); @@ -6525,9 +6198,9 @@ static void fp8_numeric(const Plugin& pl, int64_t N, int64_t K) { run_case(tl, ts, ps); std::vector got((size_t)M * N); st_memcpy(got.data(), d_ym, (size_t)M * N * 2, hipMemcpyDeviceToHost); - /* Every row must match, not just row 0: a wrong epilogue stride writes one right row. The - * tolerance is looser than the matvec's because the ACTIVATION is quantised here too, and - * E4M3's three mantissa bits are 6% of a value on their own. */ + /* Every row must match (a wrong epilogue stride writes one right row). The tolerance is + * looser than the matvec's: the activation is quantised too, and E4M3's three mantissa + * bits are 6% of a value. */ double worst = 0; for (int64_t m = 0; m < M; ++m) { double num = 0, den = 0; @@ -6544,28 +6217,21 @@ static void fp8_numeric(const Plugin& pl, int64_t N, int64_t K) { } } -/* THE SAME CHECK ON A REAL CHECKPOINT WEIGHT. +/* The same check on a real checkpoint weight (spec §17 without the .rad container). * - * `fp8_numeric` above builds its own weight, so it proves the kernel agrees with this file's idea - * of the format. That is necessary and it is not sufficient: both sides could share a wrong idea. - * This runs the identical comparison against BYTES READ OUT OF THE SAFETENSORS FILE -- real - * magnitudes, real per-block scale variation, whatever subnormals and zero blocks the checkpoint - * actually contains -- so what it falsifies is the claim that radiance can serve THIS model. The - * file's two tensors ARE block fp8's canonical planes, and the matvec reads them as they are, so - * the kernel and the oracle both read them row-major. + * `fp8_numeric` builds its own weight, so kernel and test could share a wrong idea of the format. + * This runs the same comparison on bytes read from a safetensors file: real magnitudes, scale + * variation, subnormals and zero blocks. The file's two tensors are block fp8's canonical planes, + * and the matvec and the oracle both read them row-major. * - * The offsets are arguments rather than parsed here, because a safetensors header is JSON and this - * binary has no business carrying a JSON parser. The parameters are: the file, the weight's byte - * offset, the scale plane's byte offset, N and K. Reading the two offsets out of the file needs no - * parser either -- the header length is a u64 at byte 0 and the JSON follows it, so the data - * region begins at 8 + that, and each tensor's `data_offsets[0]` is relative to there: + * Arguments: the file, the weight's byte offset, the scale plane's byte offset, N and K. The + * header length is a u64 at byte 0 followed by the JSON header, so the data region starts at 8 + + * that and each tensor's `data_offsets[0]` is relative to it: * * N=$(od -An -tu8 -N8 w.safetensors | tr -d ' ') * dd if=w.safetensors bs=1 skip=8 count=$N status=none | tr ',' '\n' | grep -A2 gate_proj * - * then pass 8 + $N + data_offsets[0], once for the weight and once for its scale plane. - * - * It is spec §17's assertion with the .rad container taken out of the path. */ + * then pass 8 + $N + data_offsets[0] for the weight and for its scale plane. */ static void fp8_real(const Plugin& pl, const char* file, long long woff, long long soff, int64_t N, int64_t K) { const RadKernelInfo* mv = find(pl, "gemm_fp8a16_nt_m1"); @@ -6584,8 +6250,8 @@ static void fp8_real(const Plugin& pl, const char* file, long long woff, long lo std::fclose(f); if (!okread) { ok("fp8 real-weight check", false, "short read"); return; } - /* A checkpoint block scale is ~1e-4 and a weight byte spans E4M3's whole range, so a plane read - * at the wrong offset shows up here rather than as a tolerance failure fifty lines later. */ + /* A checkpoint block scale is ~1e-4 and a weight byte spans E4M3's whole range, so a plane + * read at the wrong offset shows here first. */ double smin = 1e30, smax = -1e30; for (size_t i = 0; i < ws.size(); ++i) { const double v = h_bf16(ws[i]); @@ -6640,41 +6306,31 @@ static void fp8_real(const Plugin& pl, const char* file, long long woff, long lo den += (double)ref[(size_t)r] * (double)ref[(size_t)r]; } const double e = den > 0 ? std::sqrt(num / den) : 1.0; - /* Printed whether it passes or not. `ok` shows its detail only on failure, and a correctness - * gate whose margin is invisible when it passes is a gate nobody can tell has loosened. */ + /* Printed even on a pass (`ok` shows detail only on failure), so the margin stays visible. */ std::printf(" N=%lld K=%lld rel_l2 %.6g (bound 3e-2; bf16 output rounding alone is " "~2e-3)\n", (long long)N, (long long)K, e); ok("gemm_fp8a16_nt_m1 vs host ref on REAL checkpoint bytes", e < 3e-2, "rel_l2 " + std::to_string(e)); } -/* ---- THE DECODE GEMM, TIMED -------------------------------------------------------------------- +/* ---- the decode GEMM, timed ------------------------------------------------------------------ * - * The cases above answer "is it right". This answers "at what fraction of the card", which is the - * only other question a decode GEMM has, and it lives here because the alternatives do not reach - * it: rad-tune searches a row's declared axes and the fp8a8 rows declare none, and a serve is a - * round trip that buries one shape under thirty other ops. This is a second per point. + * Timing per shape for rows rad-tune cannot reach (the fp8a8 rows declare no axes). * - * WHY THE WEIGHT IS ROTATED. Back-to-back launches on ONE weight buffer measure the last level of - * cache, not HBM, and this part has enough of it to hold a whole decode GEMM's weight. Decode - * reads every weight in the model exactly once and hits none of it, so the buffer is replicated - * until it is comfortably past any cache on the card and the launches walk the copies in turn. - * Without that the same kernel reads more than twice the bandwidth here that it reaches in a - * serve, and the faster number is the useless one. + * The weight is replicated past the last-level cache and the launches walk the copies in turn: + * back-to-back launches on one buffer would measure cache, while decode reads every weight once. * - * The reported bandwidth is the WEIGHT stream and nothing else: at M <= 16 the activation is 16*K - * bytes against N*K and the output 16*N, so the two together are under a percent of the traffic at - * any shape this band serves. That makes the number directly comparable to the 638 GB/s a plain - * stream of the same bytes reaches, which is the point of printing it. + * The reported bandwidth is the weight stream only: at M <= 16 the activation (16*K) and output + * (16*N) are under a percent of the traffic, so it compares directly with the part's plain-stream + * bandwidth (638 GB/s). */ static void perf_row(const Plugin& pl, const char* name, std::vector ts, std::vector ps, void* wbase, size_t wbytes, int copies, double bytes, int iters, int widx = 2, const char* point = nullptr) { const RadKernelInfo* r = find(pl, name); if (!r) { std::printf(" %-22s row absent\n", name); return; } - /* The label is the row unless a sweep named the tuned point, because a sweep that prints one - * row name fifteen times is a sweep nobody can read. `ps` already CARRIES that point -- the - * caller appended it -- so this is only how it is spelled, never how it is applied. */ + /* The label is the row, or the tuned point in a sweep. `ps` already carries that point; this + * only names it. */ char lbl[64]; std::snprintf(lbl, sizeof lbl, "%s", (point && *point && std::strcmp(point, "-")) ? point : name); name = lbl; @@ -6691,9 +6347,8 @@ static void perf_row(const Plugin& pl, const char* name, std::vector if (need > 0) { a.scratch = dalloc((size_t)need); a.scratch_bytes = need; } } - /* One warm launch, and it is also the check that the row SERVES this shape. A row that refuses - * is reported rather than timed: timing a kernel that returned -3 without launching is how a - * heuristic sweep gets a spectacular wrong answer. */ + /* One warm launch, which also checks the row serves this shape; a refusal is reported, not + * timed. */ const int rc = r->launch(&a, nullptr); if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) { std::printf(" %-22s rc=%d (shape not served)\n", name, rc); @@ -6710,16 +6365,10 @@ static void perf_row(const Plugin& pl, const char* name, std::vector /* ------------------------------------------------------------------ the small ops, timed * - * A decode step issues roughly twelve hundred kernels and only about four hundred of them are - * GEMMs. The other eight hundred each move a few tens of kilobytes, which is nothing, so what - * they actually cost is a question about LAUNCHES rather than about bandwidth -- and the per-op - * profiler cannot answer it, because enabling it restores a synchronisation per call and that - * sync is the same order as the thing being measured. - * - * So: back-to-back launches with no host synchronisation between them, over a buffer set that - * makes every one of them independent. The number that comes out is the floor a fusion would - * have to beat, and the gap between it and the profiler's per-call figure is what the step is - * paying to dispatch. */ + * Most of a decode step's kernels are small ops moving a few tens of kilobytes, so their cost is + * launch overhead. The per-op profiler cannot measure it, since it adds a synchronisation per call + * of the same order. So this times back-to-back launches with no host synchronisation over + * independent buffers: the floor a fusion would have to beat. */ static void smallop_perf(const Plugin& pl, int64_t M, int64_t K, int iters) { if (iters <= 0) iters = 2000; const int64_t nkb = K / 128; @@ -6811,17 +6460,14 @@ static void smallop_perf(const Plugin& pl, int64_t M, int64_t K, int iters) { /* ------------------------------------------------------------- the QSA indexer, timed at length * - * THE INDEXER IS THE ONLY PART OF A DECODE STEP THAT GROWS WITH CONTEXT. `qsa_score` and - * `qsa_select` both scale with the number of compressed blocks in the history and both run once a - * layer, so between them they account for the whole of the step-time-against-context curve; every - * other op in the step is flat to within noise. That makes the pair worth timing AT LENGTH rather - * than at a convenient context. + * The indexer is the only part of a decode step that grows with context: `qsa_score` and + * `qsa_select` scale with the compressed blocks of history and run once per layer, so they are + * timed at length. * - * `blocks` is the DECLARED width (max_ctx / ratio) and `ctx` the live one, because the launch - * geometry is sized from the declaration and the work from `nc` -- so a harness that passes the - * live count for both measures a kernel the deployment never runs. + * `blocks` is the declared width (max_ctx / ratio) and `ctx` the live one: the launch geometry + * comes from the declaration and the work from `nc`, as in the deployment. * - * M IS 1 + n_spec, not the sequence count: every draft row selects its own set. */ + * M is 1 + n_spec, not the sequence count: every draft row selects its own set. */ static void qsa_perf(const Plugin& pl, int64_t ctx, int64_t M, int iters) { if (iters <= 0) iters = 200; const int64_t ratio = 4, heads = 4, n = 128, topk = 512; @@ -6838,14 +6484,12 @@ static void qsa_perf(const Plugin& pl, int64_t ctx, int64_t M, int iters) { qh[(size_t)i] = h_to_bf16((float)(((i * 29 + 7) % 83) - 41) / 47.0f); for (int64_t i = 0; i < pages * n; ++i) bkh[(size_t)i] = h_to_bf16((float)(((i * 41 + 13) % 71) - 35) / 39.0f); - /* A SCATTERED TABLE, because a paged pool hands out whatever is free and the block key read - * is the only random access in the kernel -- a table in page order measures a different - * machine. */ + /* A scattered table, as a paged pool hands out pages; the block key read is the kernel's only + * random access. */ std::vector bth((size_t)nb, -1); for (int64_t b = 0; b < live; ++b) bth[(size_t)b] = (int32_t)((b * 7919 + 13) % pages); - /* ...AND THE SAME TABLE IN PAGE ORDER, because the difference between the two IS the price of - * the paged pool, and it is the only number that says whether a contiguous block-key store - * would be worth building. Nothing else in this kernel is a random access. */ + /* And the same table in page order: the difference is the cost of the paged pool, i.e. what a + * contiguous block-key store could save. */ std::vector bti((size_t)nb, -1); for (int64_t b = 0; b < live; ++b) bti[(size_t)b] = (int32_t)b; std::vector nch(1, (int32_t)live), cuh(2), posh((size_t)M); @@ -6876,8 +6520,7 @@ static void qsa_perf(const Plugin& pl, int64_t ctx, int64_t M, int iters) { st_memcpy(d_cu, cuh.data(), 8, hipMemcpyHostToDevice); st_memcpy(d_po, posh.data(), posh.size() * 4, hipMemcpyHostToDevice); - /* `row` finds the kernel, `label` names the LINE -- two forms of the same row is the point of - * this harness, and a lambda that used one string for both could not express it. */ + /* `row` finds the kernel and `name` labels the line, so one row can be timed in two forms. */ auto run = [&](const char* row, const char* name, std::vector ts, std::vector ps, double bytes) { const RadKernelInfo* r = find(pl, row); @@ -6896,15 +6539,9 @@ static void qsa_perf(const Plugin& pl, int64_t ctx, int64_t M, int iters) { std::printf(" %-18s rc=%d (shape not served)\n", name, rc); return; } - /* WARM THE CLOCKS, NOT JUST THE CACHES, and one launch does not do it. `rocm-smi` reports - * these cards in a LOW-POWER STATE whenever nothing is running, and 300 iterations of a - * 100 us kernel is ~30 ms -- comfortably inside the ramp back up. On an UNCHANGED kernel - * the same shape can take close to twice as long after an idle gap as it does after other - * work, and the whole of that swing is the governor. Half a second of launches first, so - * the timed window runs at the clock the deployment runs at. - * - * A harness that starts cold does not measure a slow kernel, it measures a sleeping card, - * and the failure is invisible: the number is plausible and it moves with the shape. */ + /* Warm the clocks, not just the caches: an idle card drops to a low-power state, and a + * ~30 ms timed window falls inside the ramp back up (up to ~2x slower after an idle gap). + * Half a second of launches first, so the timed window runs at deployment clocks. */ { hipEvent_t w0, w1; st_ev_create(&w0); st_ev_create(&w1); @@ -6922,18 +6559,14 @@ static void qsa_perf(const Plugin& pl, int64_t ctx, int64_t M, int iters) { std::printf(" %-30s %9.2f us %6.1f GB/s\n", name, us, bytes / (us * 1e3)); }; - /* THE SCORE PLANE IS NARROWED TO THE LIVE REACH, exactly as the architecture narrows it - * (arch/common/rad_qsa.h): the pitch stays the declared `nb` and the column count is what the - * host knows the context can have reached. Both kernels size their grid from it, so a harness - * that passed the declared width would measure a grid the deployment never launches. */ + /* The score plane is narrowed to the live reach as the architecture does (arch/common/ + * rad_qsa.h): pitch the declared `nb`, column count what the context can have reached. Both + * kernels size their grid from it. */ RadTensor sc_t = T(d_sc, RAD_F32, { M, nb }); sc_t.shape[1] = live + 1; - /* THE BYTES ARE `live * n * 2` AND NOT `M *` THAT. The kernel tiles `kQT` query rows through - * LDS, so the key history is read ONCE for the tile and not once a row. Counting it once a - * query row overstates the bandwidth by exactly the factor that tiling saved -- a gauge that - * flatters a kernel by the size of its own best optimisation is worse than none, because it - * hides the headroom that optimisation left. */ + /* `live * n * 2` bytes, not `M *` that: the kernel tiles `kQT` query rows through LDS and reads + * the key history once per tile. */ const double score_bytes = (double)live * n * 2.0; auto score_args = [&]() { return std::vector{ T(d_q, RAD_BF16, { M, heads * n }), @@ -6944,9 +6577,9 @@ static void qsa_perf(const Plugin& pl, int64_t ctx, int64_t M, int iters) { const std::vector score_params = { PI("M", M), PI("n", n), PI("heads", heads), PI("blocks", nb), PI("seqs", 1), PS("dtype", "bf16") }; - /* BOTH FORMS ON ONE INPUT, timed and compared. They multiply the same bf16 pairs and sum them - * in different orders, so the comparison is a tolerance on the live plane -- and the -inf of - * an absent block has to match exactly, which a tolerance on finite values would not see. */ + /* Both forms on one input, timed and compared. They sum the same products in different + * orders, so the live plane is compared within a tolerance, and an absent block's -inf must + * match exactly. */ if (pl.pin_qsa) { std::vector plane[2]; const char* label[2] = { "qsa_score_bf16 scalar form", "qsa_score_bf16 matrix form" }; @@ -6999,24 +6632,19 @@ static void qsa_perf(const Plugin& pl, int64_t ctx, int64_t M, int iters) { } -/* THE ROUTED-EXPERT GEMM AT A PREFILL CHUNK, both projections, every prefill form. +/* The routed-expert GEMM at a prefill chunk, both projections, every prefill form. * - * WHY IT NEEDS ITS OWN MODE. rad-kbench declares at world 1, where the width split does not exist - * and the geometry is the whole 1280-column expert, and its fixture does not serve the rotated w4 - * dtype -- so the shape the engine runs at tp2 is reachable only in the engine, where a profile - * restores a synchronisation per op and a run moves ~8% between servers. This is rank 0's shape at - * Qwen3.8-Flash-Next: gate_up with three 128-column blocks of an even expert and two of an odd one - * (parts 2), and the down projection with the matching K slices over the SORTED rows. + * rad-kbench declares at world 1 (no width split) and does not serve the rotated w4 dtype, so the + * engine's tp2 shape is timed here: rank 0's at Qwen3.8-Flash-Next, gate_up with three 128-column + * blocks of an even expert and two of an odd one (parts 2), and the down projection with the + * matching K slices over the sorted rows. * - * THE ROUTING IS SKEWED, because the kernel's cost is a function of the run lengths and a uniform - * routing gives every expert the mean. Expert popularity is lognormal (sigma 0.8) and each token - * takes its top_k by a Gumbel draw, so a run ranges from a handful of rows to several times the - * mean, as a real chunk's do. The weights are random codes: what is timed is the traffic and the - * arithmetic, and both are value-independent. + * The routing is skewed, since cost depends on run lengths: expert popularity is lognormal (sigma + * 0.8) and each token takes its top_k by a Gumbel draw. Weights are random codes; traffic and + * arithmetic do not depend on values. * - * EVERY FORM IS RUN ON THE SAME BYTES and compared with the first -- the run-aligned prefill form, - * the (tile, run) decode form and the uniform prefill grid, whatever the band would pick. All three - * keep each output element's accumulation order, so they must match byte for byte. */ + * Every form (run-aligned prefill, (tile, run) decode, uniform prefill grid) runs on the same bytes + * and must match the first byte for byte, since all keep each element's accumulation order. */ static void moe_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E = 512, int64_t top_k = 10, int pool_pct = 0) { if (iters <= 0) iters = 20; @@ -7063,9 +6691,9 @@ static void moe_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E = 512, struct Proj { const char* name; int64_t N0, K0, N1, K1, parts; bool srt; }; const Proj projs[2] = { { "gate_up", 768, 2560, 512, 2560, 2, false }, { "down", 2560, 384, 2560, 256, 1, true } }; - /* Form 4, where the plugin has the pin, is the decode form at two 128-wide K blocks a pass: - * the timing kMoeGuFk256Rows is set from. Only gate_up has it (K a multiple of 256 and a - * format that folds scale groups); elsewhere it runs as form 2. */ + /* Form 4, where pinnable, is the decode form at two 128-wide K blocks per pass (the timing + * kMoeGuFk256Rows is set from). Only gate_up has it (K a multiple of 256 and a format that + * folds scale groups); elsewhere it runs as form 2. */ const int nforms = pl.pin_moe ? (pl.pin_fk ? 4 : 3) : 1; for (const Proj& P : projs) { const int64_t N = std::max(P.N0, P.N1), K = std::max(P.K0, P.K1), kb = K / group; @@ -7086,16 +6714,14 @@ static void moe_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E = 512, st_memcpy(d_as, asc.data(), asc.size() * 4, hipMemcpyHostToDevice); void* d_w[2]; void* d_ws[2]; void* d_tab[2] = { nullptr, nullptr }; for (int c = 0; c < 2; ++c) { - /* Five bits an element: the five-bit pass reads the same plane at its own pitch, and - * the four-bit ones the front of each expert's share of it. */ + /* Five bits per element: the five-bit pass reads the plane at its own pitch, the + * four-bit passes the front of each expert's share. */ d_w[c] = dalloc((size_t)(nec[c] * Nc[c] * Kc[c] / 8 * 5)); fill((size_t)(nec[c] * Nc[c] * Kc[c] / 8 * 5), 0, 255); st_memcpy(d_w[c], hb.data(), hb.size(), hipMemcpyHostToDevice); - /* POOLED EXPERTS, as the engine has them: a pointer table, with `pool_pct` percent of - * the entries pointing into pinned host memory the GEMM reads over the link. The - * LEAST ROUTED ones, because residency keeps the hot experts on the card and pools the - * cold tail -- a random choice would pool hot experts whose long runs the engine never - * streams. */ + /* Pooled experts, as in the engine: a pointer table with `pool_pct` percent of entries + * in pinned host memory read over the link. The least routed ones are pooled, as + * residency keeps hot experts on the card. */ if (pool_pct > 0) { const size_t eb = (size_t)(Nc[c] * Kc[c] / 2); std::vector tab((size_t)nec[c]); @@ -7132,7 +6758,7 @@ static void moe_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E = 512, d_tab[c] = dalloc(tab.size() * sizeof(void*)); st_memcpy(d_tab[c], tab.data(), tab.size() * sizeof(void*), hipMemcpyHostToDevice); } - /* Room for the 32-wide grid's four E4M3 bytes a 128, twice the bf16 grid's two. */ + /* Room for the 32-wide grid's four E4M3 bytes per 128 (the bf16 grid's two bytes). */ std::vector wsc((size_t)(2 * nec[c] * Nc[c] * (Kc[c] / group)), h_to_bf16(0.02f)); d_ws[c] = dalloc(wsc.size() * 2); st_memcpy(d_ws[c], wsc.data(), wsc.size() * 2, hipMemcpyHostToDevice); @@ -7165,9 +6791,8 @@ static void moe_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E = 512, std::memset(&a, 0, sizeof(a)); a.t = ts.data(); a.n_t = (int)ts.size(); a.p = ps.data(); a.n_p = (int)ps.size(); - /* The run map the aligned prefill form reads, sized for it whatever the hook answers: - * inside the decode band the hook sizes none, because the rule runs no map there, and - * the pinned aligned form would then time the uniform grid it falls back to. */ + /* The aligned prefill form's run map, sized regardless of the hook: inside the decode band + * the hook sizes none, and the pinned aligned form would fall back to the uniform grid. */ { const int64_t need = std::max(r->scratch ? r->scratch(&a) : 0, (1 + 2 * (E + Tr / 32 + 2)) * 4); @@ -7177,11 +6802,10 @@ static void moe_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E = 512, const double flop = 2.0 * ((double)rows_c[0] * P.N0 * P.K0 + (double)rows_c[1] * P.N1 * P.K1); const double welems = (double)nec[0] * P.N0 * P.K0 + (double)nec[1] * P.N1 * P.K1; std::vector first((size_t)(Tr * N)), got((size_t)(Tr * N)); - /* EVERY SCALE GRID over the same bytes: w4a8h's bf16 a (row, 128 of K), then - * w4nl64a8h's two E4M3 a 128 and w4nl32a8h's four -- the same plane read as more groups, - * so the later passes time the extra accumulators and fold and nothing else -- and last - * w5nl64a8h (`sub` 5 here), w4nl64a8h's grid over five-bit rows: the sign plane's loads - * and the sign merge. Not over pooled experts, whose blocks are sized for four bits. */ + /* Every scale grid over the same bytes: w4a8h's bf16 per (row, 128 of K), w4nl64a8h's two + * E4M3 per 128 and w4nl32a8h's four (timing only the extra accumulators and fold), and + * w5nl64a8h (`sub` 5), which adds the sign plane's loads and merge. Not over pooled + * experts, whose blocks are sized for four bits. */ for (const int sub : { 1, 2, 4, 5 }) { const bool g64 = sub > 1, w5 = sub == 5; if (w5 && (d_tab[0] || d_tab[1])) continue; @@ -7226,8 +6850,8 @@ static void moe_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E = 512, std::string same = ""; if (f == 0) { first = got; - /* A hash of the first form's bytes, so two BUILDS can be compared as well as two - * forms of one: the inputs are a fixed function of the arguments. */ + /* A hash of the first form's bytes, to compare builds; the inputs are a fixed + * function of the arguments. */ uint64_t hsh = 1469598103934665603ull; for (uint16_t v : got) { hsh ^= v; hsh *= 1099511628211ull; } same = " fnv " + std::to_string(hsh); @@ -7251,13 +6875,11 @@ static void moe_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E = 512, * sizes `u` for its weight planes; below it the pin to PF2 is refused. */ static constexpr int64_t kHcPf2MinRows = 512; -/* THE GATED RESIDUAL'S READ AT INT8 CODES. The same inputs run twice, the codes plane once E4M3 - * and once I8: the bf16 block input and the rotated E4M3 twin must come out byte-identical -- the - * codes' format is the only thing the dtype changes -- and the int8 codes must be the bf16 input - * quantised per (row, 128) at amax / 127, code for code, which is what quant_act_i8g would have - * written from it. Row counts reach the per-row kernels, the decode tiles and the prefill tile; the - * null stream takes the unfused path and a real one the fused finishers, and `form` pins the - * launcher to one family of kernels where the plugin exports the pin (0 leaves it the rule). */ +/* The gated residual's read at int8 codes. The same inputs run with the codes plane as E4M3 and + * as I8: the bf16 block input and the rotated E4M3 twin must be byte-identical, and the int8 codes + * must equal quant_act_i8g's over the bf16 input (per (row, 128) at amax / 127). Row counts reach + * the per-row kernels, decode tiles and prefill tile; the null stream takes the unfused path, a + * real one the fused finishers. `form` pins one kernel family where exported (0: the rule). */ static void hc_read_i8(const Plugin& pl, int64_t M, bool real_stream, int form) { const RadKernelInfo* r = find(pl, "hc_read_e4m3"); if (!r) { skip("hc_read_e4m3 int8 codes", "row absent"); return; } @@ -7371,19 +6993,17 @@ static void hc_read_i8(const Plugin& pl, int64_t M, bool real_stream, int form) : "the int8 run changed" + bad); } -/* THE GATED RESIDUAL'S READ AT A PREFILL CHUNK: hc_read_e4m3 at Qwen3.8-Flash-Next's shape (n - * 2560, four streams, lowrank 320, the inject gains, the fp8 twin and its rotated twin). At prefill - * it is several launches, so this is also the harness to run under libr4d/isa/trace.sh for their - * split. Random codes and small positive scales: what is timed is the traffic and the arithmetic. +/* The gated residual's read at a prefill chunk: hc_read_e4m3 at Qwen3.8-Flash-Next's shape (n + * 2560, four streams, lowrank 320, inject gains, the fp8 twin and its rotated twin). Several + * launches at prefill, so also a harness for libr4d/isa/trace.sh. Random codes, small positive + * scales. * - * EVERY FORM OF THE PREFILL TILE is run -- the decode tiles' kernels at 128 rows, the wide kernels - * and, from kHcPf2MinRows rows, the PF2 kernels, through the r4d_hc_read_pin_prefill hook -- and - * their outputs compared BYTE FOR BYTE, which is what the wide and the PF2 kernels claim. `timed` - * times each form as well. + * Every form of the prefill tile runs through the r4d_hc_read_pin_prefill hook (the decode tiles' + * kernels at 128 rows, the wide kernels, and from kHcPf2MinRows the PF2 kernels), compared byte + * for byte. `timed` also times each form. * - * `f8` picks the row: hc_read_e4m3, or hc_read_bf16 over bf16 mixing matrices. Both enter the same - * launcher and both reach PF2, whose prologue then copies mix_down where it decodes it at E4M3 and - * whose up product reads the stored mix_up where it reads a decoded one -- a path of its own. */ + * `f8` picks hc_read_e4m3, or hc_read_bf16 over bf16 mixing matrices; at bf16, PF2's prologue + * copies mix_down instead of decoding it, and its up product reads the stored mix_up. */ static void hc_prefill(const Plugin& pl, int64_t M, int iters, bool timed, bool f8 = true) { if (iters <= 0) iters = 20; const char* const rn = f8 ? "hc_read_e4m3" : "hc_read_bf16"; @@ -7445,8 +7065,8 @@ static void hc_prefill(const Plugin& pl, int64_t M, int iters, bool timed, bool st_memcpy(d_up, up.data(), up.size(), hipMemcpyHostToDevice); st_memcpy(d_iw, injw.data(), injw.size() * 2, hipMemcpyHostToDevice); - /* The mixing matrices arrive at their DECLARED shape with the stored dtype, as the engine - * hands them; the launcher derives the stored row pitch itself. */ + /* The mixing matrices at their declared shape with the stored dtype, as the engine passes + * them; the launcher derives the stored row pitch. */ const uint32_t mdt = f8 ? (uint32_t)RAD_F8E4M3 : (uint32_t)RAD_BF16; std::vector ts = { T(d_h, RAD_BF16, { M, HN }), T(d_w, RAD_F32, { HN }), @@ -7469,8 +7089,8 @@ static void hc_prefill(const Plugin& pl, int64_t M, int iters, bool timed, bool const int64_t need = r->scratch(&a); if (need > 0) { a.scratch = dalloc((size_t)need); a.scratch_bytes = need; } } - /* A REAL STREAM, because the op keys per-stream state on it -- the fused forms' arrival - * counters -- and on the null stream it finds none and takes the unfused path. */ + /* A real stream: the fused forms key their arrival counters on it, and the null stream takes + * the unfused path. */ hipStream_t hs = nullptr; if (hipStreamCreate(&hs) != hipSuccess) { ok(fmt("%s prefill forms: stream", rn).c_str(), false); @@ -7512,7 +7132,7 @@ static void hc_prefill(const Plugin& pl, int64_t M, int iters, bool timed, bool if (outs[0].qs != outs[f].qs) bad += " qs"; if (outs[0].rq != outs[f].rq) bad += " rq"; if (outs[0].rs != outs[f].rs) bad += " rs"; - /* A zero output would pass a byte comparison between two forms that both wrote nothing. */ + /* Non-zero output required: two forms that wrote nothing would compare equal. */ size_t nz = 0; for (uint8_t v : outs[f].q) nz += v != 0; ok(fmt("%s prefill tile at M=%lld, %s: byte-identical to the decode tiles' kernels", rn, @@ -7548,43 +7168,19 @@ static void hc_prefill(const Plugin& pl, int64_t M, int iters, bool timed, bool (void)hipStreamDestroy(hs); } -/* THE INT2 DRAFT HEAD, at every variant it has. +/* The bf16 skinny GEMM at one shape, every variant, side by side, with the working set rotated + * past the last-level cache (rad-tune's absolute numbers vary too much between runs to choose a + * default from). * - * WHY IT NEEDS ITS OWN MODE. rad-tune walks the declared graph and never reaches this row -- on - * the DFlash2 container the requests it lists are `gemm_nt` and `all_reduce` -- so the one kernel - * in the drafter that is not at bandwidth is never swept. It streams 178.8 MB a decode step at - * well under the 638 GB/s the part sustains, and the file's own header sets the target: a 280 us - * memory roofline and a 200 us compute floor with the codes on v_wmma_i32_16x16x16_iu8. - * - * The numbers are safe to chase harder than the trunk's. This head only PROPOSES; greedy verify - * takes the trunk's argmax whatever the draft said, so a variant that changes the head's output - * bits changes the acceptance rate and not the text. Nothing else in the step has that property. - * - * The weight is one packed blob -- N*K/4 bytes of codes plus N*(K/128)*4 of scale/zero pairs -- - * and the activation is the int8 the quantiser writes with its per-group sums, so this builds the - * gemm_nt_q operand list rather than the fp8 one. Contents are shape-correct garbage: what is - * being timed is a stream of the right size in the right order. - */ - -/* The bf16 skinny GEMM at one shape, every variant. rad-tune reaches these rows, but its absolute - * numbers are not repeatable enough between back-to-back runs of the same command to base a - * default on -- the same reason `--perf` and `--perfw2` exist beside it. This rotates a working - * set past the last level, times each variant the same way, and prints them together. - * - * THE SHAPES THIS IS FOR are the three the model's declared graph reaches: N = 48 (the GDN a|b - * projection, forty-eight times a step and the only TRUNK caller), N = 1280 and N = 256 (the - * DFlash2 drafter's, ten and one). The distinction matters more than the sizes: a default that - * changes the drafter's bits changes which tokens it PROPOSES and not which the model emits, and - * one that changes the trunk's changes the model. */ + * The shapes the model's graph reaches: N = 48 (the GDN a|b projection, the only trunk caller), + * N = 1280 and N = 256 (the DFlash2 drafter's). A default that changes the drafter's bits changes + * only its proposals; one that changes the trunk's changes the model. */ static void bf16_perf(const Plugin& pl, int64_t N, int64_t K, int64_t M, int iters) { if (N % 16 || K % 16 || M < 1) { std::printf("--perfbf16: N and K must be 16-aligned and M >= 1\n"); return; } - /* R4D_PERFBF16_M64 forces the WMMA kernel onto the M <= 16 band the registry gives to the - * scalar one, which is the only way to ask whether that row still earns its place. */ - static const bool f64 = std::getenv("R4D_PERFBF16_M64") != nullptr; - const RadKernelInfo* r = find(pl, (M <= 16 && !f64) ? "gemm_bf16_nt_m16" : "gemm_bf16_nt_m64"); + const RadKernelInfo* r = find(pl, M <= 16 ? "gemm_bf16_nt_m16" : "gemm_bf16_nt_m64"); if (!r) { std::printf("--perfbf16: row absent\n"); return; } const size_t wbytes = (size_t)N * (size_t)K * 2; @@ -7613,15 +7209,12 @@ static void bf16_perf(const Plugin& pl, int64_t N, int64_t K, int64_t M, int ite "%d iters\n", r->name, (long long)N, (long long)K, (long long)M, (double)wbytes / (1 << 20), copies, iters); - /* EVERY LEGAL POINT OF THE DECLARED SPACE, capped. The skinny GEMM's five axes are ~900 points - * and tune_valid prunes that to a few hundred at any one K -- more than an interactive sweep - * wants but exactly what rad-tune walks. `kPerfCap` keeps this readable; the cap is a property - * of the HARNESS and not of the kernel, which is the whole reason the space is declared. */ + /* Every legal point of the declared space (~900, pruned to a few hundred at one K by + * tune_valid), capped at `kPerfCap` for readability. */ std::vector geom = { PI("M", M), PI("N", N), PI("K", K), PS("dtype", "bf16"), }; - /* Above the skinny band the tiled row is timed as well, at each of its tile variants: the two - * serve the same op, so the numbers belong side by side. */ + /* Above the skinny band the tiled row (same op) is timed too, at each tile variant. */ const RadKernelInfo* rt = M > 64 && N >= 128 && K % 64 == 0 ? find(pl, "gemm_bf16_nt_tiled") : nullptr; for (const RadKernelInfo* row : { r, rt }) { @@ -7638,6 +7231,14 @@ static void bf16_perf(const Plugin& pl, int64_t N, int64_t K, int64_t M, int ite } } } +/* The int2 draft head at every variant. rad-tune never reaches this row (on the DFlash2 + * container its requests are `gemm_nt` and `all_reduce`), and it runs well under the part's + * 638 GB/s. Tuning it is safe: the head only proposes, and greedy verify takes the trunk's argmax, + * so changed output bits change the acceptance rate, not the text. + * + * The weight is one packed blob (N*K/4 bytes of codes plus N*(K/128)*4 of scale/zero pairs) and + * the activation the quantiser's int8 with per-group sums: the gemm_nt_q operand list. Contents are + * shape-correct garbage; only the stream is timed. */ static void w2_perf(const Plugin& pl, int64_t N, int64_t K, int64_t M, int iters) { if (N % 16 || K % 128 || M < 1) { std::printf("--perfw2: N must be 16-aligned, K 128-aligned, M >= 1\n"); @@ -7649,8 +7250,7 @@ static void w2_perf(const Plugin& pl, int64_t N, int64_t K, int64_t M, int iters const int64_t nkb = K / 128; const size_t wbytes = (size_t)N * (size_t)K / 4; const size_t sbytes = (size_t)N * (size_t)nkb * 4; - /* Same rotation argument as fp8_perf: enough copies that the working set is past the last - * level, capped so a 160 MiB weight does not try to allocate the card. */ + /* Copies past the last-level cache, as in fp8_perf, capped for large weights. */ int copies = (int)(((size_t)768 << 20) / wbytes) + 1; if (copies > 16) copies = 16; @@ -7665,8 +7265,7 @@ static void w2_perf(const Plugin& pl, int64_t N, int64_t K, int64_t M, int iters (wbytes * (size_t)copies) >> 20); return; } - /* A zeroed scale/zero pair is two f16 zeroes, which makes every dequant zero and is exactly - * the shape of measurement that finds a denormal fast path instead of the kernel. */ + /* Non-zero scales: all-zero dequants could hit a denormal fast path and mismeasure. */ { std::vector sz((size_t)N * (size_t)nkb, 0x00003C00u); /* zp 0, scale 1.0 */ st_memcpy(d_s, sz.data(), sz.size() * 4, hipMemcpyHostToDevice); @@ -7711,9 +7310,8 @@ static void fp8_perf(const Plugin& pl, int64_t N, int64_t K, int64_t M, int iter } const int64_t sn = N / 128, sk = K / 128; const size_t wbytes = (size_t)N * K; - /* Enough copies that the rotation's whole working set is past the last level of cache on this - * part, with a ceiling so a 600 MiB weight does not try to allocate the card. A shape small - * enough to sit in cache would otherwise report a bandwidth decode can never see. */ + /* Enough copies to push the working set past the last-level cache, capped for large + * weights. */ int copies = (int)(((size_t)768 << 20) / wbytes) + 1; if (copies > 64) copies = 64; @@ -7728,8 +7326,7 @@ static void fp8_perf(const Plugin& pl, int64_t N, int64_t K, int64_t M, int iter (wbytes * (size_t)copies) >> 20); return; } - /* Zeroed scales would make every dequant a zero, which some day will be a denormal-flush fast - * path somewhere and a wrong measurement here. Fill with a checkpoint-shaped multiplier. */ + /* Non-zero, checkpoint-like scales, so no dequant is zero (a possible fast path). */ { std::vector s((size_t)sn * sk, h_to_bf16(3.0e-4f)); st_memcpy(d_s, s.data(), s.size() * 2, hipMemcpyHostToDevice); @@ -7774,12 +7371,9 @@ static void fp8_perf(const Plugin& pl, int64_t N, int64_t K, int64_t M, int iter perf_row(pl, "gemm_fp8a8_tiled", ts, ps, d_w, wbytes, copies, bytes, iters); } - /* THE LM HEAD, which is a decode GEMM too and the one nothing could time. Its weight is a - * plane of its own shape -- [N][K + 2*nkb] E4M3, each row's bf16 scales in its own tail, see - * r4d_fp8_layout.cpp -- so it cannot share the rotation buffer above, and its row is the - * SECOND operand rather than the third. At this model's 124160 x 5120 it is the largest - * single kernel of a decode step after the trunk's GEMMs, and without this block the only way - * to measure it is a rocprofv3 trace of a serving engine. */ + /* The lm head, a decode GEMM too. Its weight is [N][K + 2*nkb] E4M3 with each row's bf16 + * scales in its tail (r4d_fp8_layout.cpp), so it has its own buffer, and the weight is the + * second operand. */ if (M <= 64) { const int64_t lstride = r4d_fp8::lm_row_bytes(K); const size_t lwb = (size_t)N * (size_t)lstride; @@ -7801,9 +7395,8 @@ static void fp8_perf(const Plugin& pl, int64_t N, int64_t K, int64_t M, int iter for (int c = 0; c < lcopies; ++c) st_memcpy((uint8_t*)d_lw + (size_t)c * lwb, plane.data(), lwb, hipMemcpyHostToDevice); - /* The DECLARED shape, [N][K], because that is what reaches the shim -- the stored - * width is derived there from n_embd; the fp8 logits_gemm launcher in - * r4d_gemm_fp8a16_nt_m1.hip says why. */ + /* The declared shape, [N][K], as the shim receives it; it derives the stored width + * from n_embd (r4d_gemm_fp8a16_nt_m1.hip). */ std::vector ts = { T(d_x, RAD_BF16, { M, K }), T(d_lw, RAD_F8E4M3, { N, K }), @@ -7817,10 +7410,9 @@ static void fp8_perf(const Plugin& pl, int64_t N, int64_t K, int64_t M, int iter } } -/* THE 8-BIT TRUNK GEMMS, side by side: block E4M3 W8A8 (the fp8 trunk), the int8 W8A8 - * tiled kernel, and the fp8 kernels' int8 twins (gemm_i8a8_*), one shape, each with its useful - * TFLOP/s -- and at M <= 64 the two narrow rows too. The operands hold constants: timing does not - * depend on the values, and the bytes are only the shape each row's shim checks. */ +/* The 8-bit trunk GEMMs side by side at one shape, each with its useful TFLOP/s: block E4M3 W8A8 + * (the fp8 trunk), the int8 W8A8 tiled kernel, and the fp8 kernels' int8 twins (gemm_i8a8_*); at + * M <= 64 also the two narrow rows. Operands hold constants (timing does not depend on values). */ static void w8_perf(const Plugin& pl, int64_t N, int64_t K, int64_t M, int iters) { if (N % 256 || K % 128 || M < 1) { std::printf("--perfw8: N a multiple of 256, K of 128, M >= 1\n"); @@ -7905,7 +7497,7 @@ static void w8_perf(const Plugin& pl, int64_t N, int64_t K, int64_t M, int iters absent(i8[5]); absent(i8[6]); run("gemm_w8a8_tiled", "w8a8", i8); /* The int8 twin of the fp8 row: i8 activation with an f32 scale per (row, 128), i8 weight with - * a bf16 scale per row per 128. The fp8 row's own scale buffers are the right size for both. */ + * a bf16 scale per row per 128; the fp8 row's scale buffers fit both. */ std::vector rs((size_t)N * sk, h_to_bf16(3.0e-4f)); void* d_rs = dalloc(rs.size() * 2); if (!d_rs) { std::printf("--perfw8: hipMalloc failed\n"); return; } @@ -7923,10 +7515,9 @@ static void w8_perf(const Plugin& pl, int64_t N, int64_t K, int64_t M, int iters } } -/* THE W4 ARRANGEMENT, CHECKED AGAINST libr4d's OWN DEQUANT. The relayout writes the fragment - * order and the (scale, zero) dwords and dequant_w4_bf16 undoes both on the card, so a disagreement - * between the two is exactly the class of bug that would otherwise reach a model. The planes are - * an i4 grid with an f16 scale a group of 128, and what comes back must be code times scale. */ +/* The w4 arrangement against libr4d's own dequant: the relayout writes fragment order and (scale, + * zero) dwords and dequant_w4_bf16 undoes both on the card. The planes are an i4 grid with an f16 + * scale per 128, and the result must be code times scale. */ static void w4_roundtrip(const Plugin& pl) { const RadKernelInfo* wrow = find(pl, "gemm_w4a8_nt_m64"); const RadKernelInfo* drow = find(pl, "dequant_w4_bf16"); @@ -7986,8 +7577,7 @@ static void w4_roundtrip(const Plugin& pl) { std::vector got((size_t)(N * K)); st_memcpy(got.data(), dout, got.size() * 2, hipMemcpyDeviceToHost); - /* Code times scale exactly as the planes hold them, rounded to bf16 as the kernel's output - * is -- so the only freedom left is the rounding of one product. */ + /* Code times scale as the planes hold them, rounded to bf16 like the kernel's output. */ const int64_t ng = K / group; double worst = 0.0; int64_t bad = 0; @@ -8000,7 +7590,7 @@ static void w4_roundtrip(const Plugin& pl) { const float want = h_bf16(h_to_bf16( (float)code_at(p, n, k) * rad_load_f32(p.data[1].data(), RAD_F16, n * ng + k / group))); const double err = std::fabs((double)f - (double)want); - /* one bf16 step either way: the two sides may round the same product apart */ + /* one bf16 step either way: the two sides may round one product differently */ if (!(err <= 1e-6 + 1e-2 * std::fabs((double)want))) { ++bad; if (err > worst) worst = err; } } ok("w4 relayout round-trips through libr4d's own dequant_w4_bf16", bad == 0, @@ -8008,99 +7598,61 @@ static void w4_roundtrip(const Plugin& pl) { } -/* THE 4-BIT GROUPED MoE GEMM, AGAINST A HOST PRODUCT OVER THE SAME PLANES. - * - * This is the check the `moe_gemm_w4a8` registry row promises in place of a kbench case, and it is - * the one that can actually fail. The relayout reorders each dword's nibbles; the kernel expands - * them with three V_PERM_B32 on the way into LDS; the two have to agree about the nibble order, - * the row pitch (the launcher halves an ELEMENT stride into bytes -- get that wrong and every row - * is read from the wrong place) and the scale grid (one bf16 per ROW per group of 128, not per - * 128x128 tile). The reference reads the canonical planes -- code k of row n, times its group's - * scale -- so it shares nothing with either side's arrangement. - * - * BOTH BANDS. `T <= 128` runs a 16-row M tile and above it a 128-row one, and the two differ in - * the wave grid and in how many experts a block's row range straddles -- which is the part with - * the binary search and the run loop in it. A case in only one band tests half the kernel. */ -static float st_e4m3(uint8_t b) { - const uint32_t sign = (uint32_t)(b & 0x80u) << 24, ex = (b >> 3) & 0x0Fu, mn = b & 0x07u; - const uint32_t nrm = ((ex + 120u) << 23) | (mn << 20); - float f; - std::memcpy(&f, &nrm, 4); - const float v = ex ? f : (float)mn * (1.0f / 512.0f); - uint32_t u; - std::memcpy(&u, &v, 4); - u |= sign; - std::memcpy(&f, &u, 4); - return f; -} - -/* One geometry per class -- the even experts' and the odd ones' -- and the number of stacked parts - * along the weight rows and the output. One class shape is the plain grouped GEMM; two are a - * rank's uneven slice of every expert, where the narrower class's gate/up pair writes zeros past - * its part and its down projection reads a shorter K. */ -/* `sorted_a`: the down projection's operand, one row a routed slot in sorted order (a_order - * sorted), where the others read the token rows (a_order token). */ +/* One geometry per class (even and odd experts) and the number of stacked parts along the weight + * rows and the output. One class shape is the plain grouped GEMM; two are a rank's uneven slice of + * every expert, where the narrower class's gate/up pair writes zeros past its part and its down + * projection reads a shorter K. `sorted_a`: the down projection's operand, one row per routed slot + * in sorted order (a_order sorted); otherwise token rows (a_order token). */ struct MoeW4Shape { const char* name; int64_t N0, K0, N1, K1, parts, ne; bool sorted_a = false; }; -/* THE DECODE FORM'S STAGED K, BOTH WAYS, byte for byte: one 128-wide K block a pass and two. Every - * launch is DESCRIBED first: a pin that named the other's kernel would match it trivially, so two - * pins naming one function is a failure, not a pass. `fk2` is whether this shape can take two - * blocks a pass -- the token operand, a format that folds scale groups, every class's K a multiple - * of 256; a shape that cannot has one form only, which the form loop already held to the host - * decode. Both launches are PINNED, so the launcher's row limit cannot make the comparison one form - * against itself. - * - * A row with no describe hook -- moe_gemm_fp8a8_mod4 -- is compared on its bytes alone, and says - * so in its label: that the variant ran is then not shown, only that what ran agrees. */ +/* The last kernel one launch dispatches, as r4d_record_dispatches saw it; null if it dispatched + * none. */ +static const void* last_dispatch(const Plugin& pl, const RadKernelInfo* row, RadArgs& a, int* rc) { + const void* fns[8] = {}; + pl.record(fns, 8); + *rc = row->launch(&a, nullptr); + const int n = pl.record(nullptr, 0); + return n >= 1 && n <= 8 ? fns[n - 1] : nullptr; +} + +/* The decode form's staged K both ways, byte for byte: one 128-wide K block per pass and two. + * Two pins dispatching one function fail, so a form is never compared against itself. Both + * launches are pinned, for the same reason. `fk2` says whether the shape can take two blocks per + * pass (token operand, a format that folds scale groups, every class's K a multiple of 256); + * otherwise there is one form, already checked by the form loop. */ static void moe_dec_variants(const Plugin& pl, const RadKernelInfo* row, RadArgs& a, void* d_y, size_t elems, bool fk2, const std::string& what) { if (!fk2 || !pl.pin_fk || !pl.pin_moe) return; - const bool described = row->describe != nullptr; struct Var { int fk; const char* name; }; static const Var kVar[] = { { 1, "one K block a pass" }, { 2, "two K blocks a pass" } }; constexpr int kN = (int)(sizeof(kVar) / sizeof(kVar[0])); const void* fn[kN] = {}; std::vector base; for (int v = 0; v < kN; ++v) { - const std::string label = what + " decode form, " + kVar[v].name + - (described ? "" : " (launch not described)"); - auto pin = [&](bool on) { - pl.pin_moe(on ? 2 : 0); - pl.pin_fk(on ? kVar[v].fk : 0); - }; - if (described) { - static RadLaunchDesc d[4]; - int n = 0; - pin(true); - const int drc = row->describe(&a, nullptr, d, 4, &n); - pin(false); - if (drc != RAD_OK || n < 1) { - ok(label.c_str(), false, "describe rc=" + std::to_string(drc) + " n=" + - std::to_string(n)); - return; - } - fn[v] = d[n - 1].func; - int same = -1; - for (int u = 0; u < v; ++u) - if (fn[u] && fn[u] == fn[v]) same = u; - if (same >= 0) { - ok(label.c_str(), false, - std::string("named the same kernel as ") + kVar[same].name); - continue; - } - } + const std::string label = what + " decode form, " + kVar[v].name; { std::vector junk(elems, 0x7f7fu); st_memcpy(d_y, junk.data(), junk.size() * 2, hipMemcpyHostToDevice); } - pin(true); - const int rc = row->launch(&a, nullptr); + pl.pin_moe(2); + pl.pin_fk(kVar[v].fk); + int rc = RAD_OK; + fn[v] = last_dispatch(pl, row, a, &rc); st_stream_sync(nullptr); - pin(false); + pl.pin_moe(0); + pl.pin_fk(0); if (rc != RAD_OK) { ok(label.c_str(), false, "launch rc=" + std::to_string(rc)); return; } + int same = -1; + for (int u = 0; u < v; ++u) + if (fn[u] && fn[u] == fn[v]) same = u; + if (same >= 0) { + ok(label.c_str(), false, std::string("dispatched the same kernel as ") + + kVar[same].name); + continue; + } std::vector got(elems); st_memcpy(got.data(), d_y, got.size() * 2, hipMemcpyDeviceToHost); - if (v == 0) { base = got; continue; } /* the form loop held it to the host decode */ + if (v == 0) { base = got; continue; } /* checked against the host by the form loop */ int64_t diff = 0; for (size_t i = 0; i < got.size(); ++i) diff += got[i] != base[i]; ok(label.c_str(), diff == 0, std::to_string(diff) + " of " + std::to_string(elems) + @@ -8108,17 +7660,15 @@ static void moe_dec_variants(const Plugin& pl, const RadKernelInfo* row, RadArgs } } -/* THE RUN-ALIGNED FORM'S TWO COLUMN TILES ON THE DOWN PROJECTION, byte for byte. Where the - * sorted operand, one part and every class's width in whole 256-column tiles let the rule take the - * 256-column tile, the 128-column tile (r4d_moe_gemm_pin_down_tile 1) must write its bytes. Every - * launch is DESCRIBED first where the row can be: the rule and the 256 pin must name one GEMM and - * the 128 pin another, so the bytes below are never one kernel against itself. Where the shape - * cannot take the 256-column tile, the pin to it is refused. `base` is the aligned form's own bytes - * under the rule, already held to the host decode by the form loop. +/* The run-aligned form's two column tiles on the down projection, byte for byte. Where the sorted + * operand, one part and every class's width in whole 256-column tiles let the rule take the + * 256-column tile, the 128-column tile (r4d_moe_gemm_pin_down_tile 1) must write the same bytes. + * Each launch records its two dispatches (the run map, then the GEMM): the rule and the 256 pin + * must dispatch one GEMM and the 128 pin another. Where the 256-column tile does not fit, its pin is refused. `base` is the + * aligned form's bytes under the rule, already checked against the host. * - * PAST 512 EXPERTS THERE IS NO ALIGNED LAUNCH: the map's builder holds kMaxExpert + 1 offsets, so - * the launcher hands a wider expert count the uniform grid whatever scratch it is given. Such a - * shape is skipped, not failed. */ + * Past 512 experts there is no aligned launch (the map holds kMaxExpert + 1 offsets), so such a + * shape is skipped. */ static void moe_aligned_down_tile(const Plugin& pl, const RadKernelInfo* row, RadArgs& a, void* d_y, void* d_map, int64_t map_bytes, size_t elems, const std::vector& base, bool dn_wide, int64_t ne, @@ -8140,15 +7690,20 @@ static void moe_aligned_down_tile(const Plugin& pl, const RadKernelInfo* row, Ra a.scratch = sc0; a.scratch_bytes = sb0; }; - auto launch = [&](int pin, std::vector* got) { + /* One pinned launch into stale bytes; `gemm` gets its second dispatch, the GEMM. */ + auto launch = [&](int pin, std::vector* got, const void** gemm) { { std::vector junk(elems, 0x7f7fu); st_memcpy(d_y, junk.data(), junk.size() * 2, hipMemcpyHostToDevice); } + const void* fns[4] = {}; pl.pin_dtile(pin); + pl.record(fns, 4); const int rc = row->launch(&a, nullptr); + const int n = pl.record(nullptr, 0); st_stream_sync(nullptr); pl.pin_dtile(0); + if (gemm) *gemm = n == 2 ? fns[1] : nullptr; if (got) { got->assign(elems, 0); st_memcpy(got->data(), d_y, elems * 2, hipMemcpyDeviceToHost); @@ -8156,64 +7711,61 @@ static void moe_aligned_down_tile(const Plugin& pl, const RadKernelInfo* row, Ra return rc; }; if (!dn_wide) { - const int rc = launch(2, nullptr); + const int rc = launch(2, nullptr, nullptr); restore(); ok((head + ", the 256-column down tile is refused on this shape").c_str(), rc == RAD_E_UNSUPPORTED, "rc=" + std::to_string(rc)); return; } - if (row->describe) { - const void* fn[3] = {}; - for (int pin = 0; pin < 3; ++pin) { - static RadLaunchDesc d[4]; - int n = 0; - pl.pin_dtile(pin); - const int drc = row->describe(&a, nullptr, d, 4, &n); - pl.pin_dtile(0); - if (drc != RAD_OK || n != 2) { - restore(); - ok((head + ", column tiles described").c_str(), false, - "pin " + std::to_string(pin) + ": describe rc " + std::to_string(drc) + - ", launches " + std::to_string(n)); - return; - } - fn[pin] = d[1].func; - } - if (fn[0] != fn[2] || fn[1] == fn[2]) { + const void* fn[3] = {}; + std::vector got[3]; + for (int pin = 0; pin < 3; ++pin) { + const int rc = launch(pin, &got[pin], &fn[pin]); + if (rc != RAD_OK || !fn[pin]) { restore(); - ok((head + ", column tiles described").c_str(), false, - std::string("the rule ") + (fn[0] == fn[2] ? "names" : "does not name") + - " the 256-column GEMM; the 128 pin " + - (fn[1] == fn[2] ? "names it too" : "names another")); + ok((head + ", column tiles").c_str(), false, + "pin " + std::to_string(pin) + ": launch rc " + std::to_string(rc) + + (fn[pin] ? "" : ", not two dispatches")); return; } } + restore(); + if (fn[0] != fn[2] || fn[1] == fn[2]) { + ok((head + ", column tiles").c_str(), false, + std::string("the rule ") + (fn[0] == fn[2] ? "dispatches" : "does not dispatch") + + " the 256-column GEMM; the 128 pin " + + (fn[1] == fn[2] ? "dispatches it too" : "dispatches another")); + return; + } struct Var { int pin; const char* name; }; static const Var kVar[] = { { 1, "the 128-column down tile" }, { 2, "the 256-column down tile, pinned" } }; for (const Var& v : kVar) { - const std::string label = head + ", " + v.name + - (row->describe ? "" : " (launch not described)"); - std::vector got; - const int rc = launch(v.pin, &got); - if (rc != RAD_OK) { ok(label.c_str(), false, "launch rc=" + std::to_string(rc)); continue; } int64_t diff = 0; - for (size_t i = 0; i < elems; ++i) diff += got[i] != base[i]; - ok(label.c_str(), diff == 0, std::to_string(diff) + " of " + std::to_string(elems) + - " elements differ from the rule's 256-column tile"); + for (size_t i = 0; i < elems; ++i) diff += got[v.pin][i] != base[i]; + ok((head + ", " + v.name).c_str(), diff == 0, + std::to_string(diff) + " of " + std::to_string(elems) + + " elements differ from the rule's 256-column tile"); } - restore(); } -/* EVERY FORM THE LAUNCHER HAS, each against the host decode: the run-aligned prefill form (a run - * map in the scratch it is handed), the (tile, run) decode form, and the uniform prefill grid a - * caller with no scratch gets. The rule picks one by the routed-row count, so a case that only - * ran the rule would test whichever form its row count landed on. */ -/* `sub` 2 runs the codebook at E4M3 scales a 64 of K (w4nl64a8h), 4 at a 32 (w4nl32a8h): the - * codes' values are the table's and each part of a 128-wide group has its own scale, the fold the - * forms must agree on. `w5` with `sub` 2 runs the five-bit codebook (w5nl64a8h), whose stored row - * is its nibbles and then its signs. `four` also runs `moe_gemm_w4a8_mod4` over the same experts - * and holds it to the two-class op's bytes -- that row's own case. */ +/* The 4-bit grouped MoE GEMM against a host product over the same planes (the check the + * `moe_gemm_w4a8` row promises instead of a kbench case). The relayout reorders each dword's + * nibbles and the kernel expands them with V_PERM_B32 into LDS; they must agree on nibble order, + * row pitch (the launcher halves an element stride into bytes) and scale grid (one bf16 per row + * per 128, not per 128x128 tile). The reference reads the canonical planes, independent of either + * arrangement. + * + * Both bands: `T <= 128` runs a 16-row M tile, above it a 128-row one, differing in wave grid and + * in how many experts a block's row range straddles (the binary search and run loop). + * + * Every launcher form runs against the host: the run-aligned prefill form (a run map in its + * scratch), the (tile, run) decode form, and the uniform prefill grid of a caller with no scratch. + * + * `sub` 2 runs the codebook at E4M3 scales per 64 of K (w4nl64a8h), 4 per 32 (w4nl32a8h): each part + * of a 128-wide group has its own scale. `w5` with `sub` 2 runs the five-bit codebook (w5nl64a8h), + * whose stored row is its nibbles then its signs. `four` also runs `moe_gemm_w4a8_mod4` over the + * same experts and holds it to the two-class op's bytes. */ static void moe_w4_gemm(const Plugin& pl, int64_t Tr, const MoeW4Shape& sh, int sub = 0, bool w5 = false, bool four = false) { const bool g64 = sub > 1; @@ -8241,9 +7793,9 @@ static void moe_w4_gemm(const Plugin& pl, int64_t Tr, const MoeW4Shape& sh, int std::vector lp = { PI("N", sh.N0), PI("K", sh.K0), PI("N_odd", sh.N1), PI("K_odd", sh.K1), PI("group", group), PS("dtype", dt) }; - /* Each class's stored bytes from the hooks, asked through the class's own operands -- 2/3 and - * 6/7 -- so the view that answers for the odd table is under test as well. One float source an - * expert, its planes, and the arrangement beside them; the planes are kept for the reference. */ + /* Each class's stored bytes from the hooks via its own operands (2/3 and 6/7), so the odd + * table's view is tested too. Per expert: a float source, its planes (kept for the reference) + * and the arrangement. */ std::vector wq[2]; std::vector ws[2]; std::vector cp[2]; @@ -8283,25 +7835,22 @@ static void moe_w4_gemm(const Plugin& pl, int64_t Tr, const MoeW4Shape& sh, int } } - /* The activation is written as E4M3 BYTES and a per-(row, group) f32 scale, so the host and - * the device read the same numbers and the only difference left is summation order. The scale - * varies along the rows as well as the groups: one the same for every row would let a kernel - * that reads another row's scale pass. */ + /* The activation as E4M3 bytes and a per-(row, group) f32 scale, so host and device read the + * same numbers. The scale varies along rows and groups, so reading another row's scale + * shows. */ std::vector aq((size_t)(M * K)); std::vector as((size_t)(M * kb)); for (int64_t m = 0; m < M; ++m) { for (int64_t g = 0; g < kb; ++g) as[(size_t)(m * kb + g)] = 0.011f + 0.003f * (float)g + 0.0007f * (float)(m % 11); for (int64_t k = 0; k < K; ++k) { - /* 8..126: no subnormal, and no 0x7F -- which is E4M3's NaN, and which a comparison - * that lets NaN through never noticed. */ + /* 8..126: no subnormal and no 0x7F (E4M3's NaN). */ const uint32_t c = (uint32_t)((m * 13 + k * 5) % 119) + 8; aq[(size_t)(m * K + k)] = (uint8_t)(((m + k) & 1) ? (c | 0x80u) : c); } } - /* A routing that puts an uneven run on each expert and drops the tail, which is what the run - * loop and the dropped-slot zeroing have to survive. */ + /* Uneven runs per expert and a dropped tail, for the run loop and dropped-slot zeroing. */ std::vector off((size_t)(ne + 1), 0), sorted((size_t)Tr, -1); const int64_t live = Tr - 3; for (int64_t e = 0; e <= ne; ++e) off[(size_t)e] = (int32_t)((live * e) / ne); @@ -8329,9 +7878,8 @@ static void moe_w4_gemm(const Plugin& pl, int64_t Tr, const MoeW4Shape& sh, int st_memcpy(d_y, junk.data(), junk.size() * 2, hipMemcpyHostToDevice); } - /* THE STACKED WEIGHT-TABLE FORM (a leading stride that is not zero). A pointer array is what - * the engine hands the kernel; a test has nowhere to put one, and the kernel reads both - * precisely so that this case runs against the same bytes. */ + /* The stacked weight-table form (a non-zero leading stride); the engine passes a pointer + * array, and the kernel reads both. */ std::vector ts = { T(d_a, RAD_F8E4M3, { M, K }), T(d_as, RAD_F32, { M, kb }), @@ -8354,8 +7902,8 @@ static void moe_w4_gemm(const Plugin& pl, int64_t Tr, const MoeW4Shape& sh, int std::memset(&a, 0, sizeof(a)); a.t = ts.data(); a.n_t = (int)ts.size(); a.p = ps.data(); a.n_p = (int)ps.size(); - /* Room for the run map at the smallest prefill tile, whatever the hook answers: the hook sizes - * none inside the decode band, and the aligned form pinned there would then not run. */ + /* Room for the run map at the smallest prefill tile regardless of the hook, which sizes none + * inside the decode band. */ const int64_t map_bytes = (1 + 2 * (ne + Tr / 16 + 2)) * 4; void* d_map = dalloc((size_t)map_bytes); @@ -8374,14 +7922,14 @@ static void moe_w4_gemm(const Plugin& pl, int64_t Tr, const MoeW4Shape& sh, int const int64_t tok = sh.sorted_a ? i : f / top_k, wr = pp * fc + j; for (int64_t g = 0; g < kbc; ++g) { if (g64) { - /* `sub` scale groups a 128, each an E4M3 byte under the fixed constant. */ + /* `sub` scale groups per 128, each E4M3 under the fixed constant. */ const Planes& q = cp[c][(size_t)x]; const int64_t gw = group / sub; for (int64_t h = 0; h < sub; ++h) { double part = 0.0; for (int64_t k = g * group + h * gw; k < g * group + (h + 1) * gw; ++k) part += (double)tab[code_at(q, wr, k)] * - (double)st_e4m3(aq[(size_t)(tok * K + k)]); + (double)h_e4m3(aq[(size_t)(tok * K + k)]); const double sf = (double)h_e4m3(q.data[1][(size_t)(wr * q.row_bytes(1) + sub * g + h)]) * (double)kW4G64Scale; @@ -8392,7 +7940,7 @@ static void moe_w4_gemm(const Plugin& pl, int64_t Tr, const MoeW4Shape& sh, int double sub = 0.0; for (int64_t k = g * group; k < (g + 1) * group; ++k) sub += (double)code_at(cp[c][(size_t)x], wr, k) * - (double)st_e4m3(aq[(size_t)(tok * K + k)]); + (double)h_e4m3(aq[(size_t)(tok * K + k)]); const float sf = rad_load_f32(cp[c][(size_t)x].data[1].data(), RAD_BF16, wr * kbc + g); want += sub * (double)sf * (double)as[(size_t)(tok * kb + g)]; @@ -8407,8 +7955,7 @@ static void moe_w4_gemm(const Plugin& pl, int64_t Tr, const MoeW4Shape& sh, int for (int form = f_lo; form <= f_hi; ++form) { const std::string label = what + " " + kForm[form]; if (pl.pin_moe) pl.pin_moe(form); - /* Stale bytes again, so a form that leaves a pad tile unwritten cannot inherit the zeros - * the form before it wrote. */ + /* Stale bytes again, so a form cannot inherit the previous form's zeros. */ { std::vector junk((size_t)(Tr * N), 0x7f7fu); st_memcpy(d_y, junk.data(), junk.size() * 2, hipMemcpyHostToDevice); @@ -8431,10 +7978,8 @@ static void moe_w4_gemm(const Plugin& pl, int64_t Tr, const MoeW4Shape& sh, int const uint32_t u = (uint32_t)got[(size_t)(i * N + n)] << 16; float gf; std::memcpy(&gf, &u, 4); - /* bf16 carries eight mantissa bits, so a relative half-ulp is 1/512; the tolerance - * is that plus room for a 256-term f32 sum taken in a different order. Written so - * that a NaN on either side counts as a miss: `err > tol` is false for one, and a - * NaN is exactly what a kernel that read a stale row would produce. */ + /* A bf16 relative half-ulp (1/512) plus room for a reordered 256-term f32 sum. + * Written so a NaN on either side counts as a miss. */ const double err = std::fabs((double)gf - want); if (!(err <= 0.004 * std::fabs(want) + 1e-4)) { if (!bad++) @@ -8448,12 +7993,9 @@ static void moe_w4_gemm(const Plugin& pl, int64_t Tr, const MoeW4Shape& sh, int " elements off, worst " + std::to_string(worst) + first); two_cls[form] = got; } - /* THE DECODE FORM AGAINST THE UNIFORM PREFILL GRID, byte for byte. Every form keeps each - * output element's accumulation order, so the bytes agree exactly, not within the host - * decode's tolerance. The decode form finds its runs by the one-round-trip search up to 512 - * experts and by the chunked search above that; the uniform grid walks the offsets from a - * binary search, so this holds whichever search the expert count picks to a third way of - * finding the same runs. */ + /* The decode form against the uniform prefill grid, byte for byte (every form keeps each + * element's accumulation order). The decode form finds runs by a one-round-trip search up to + * 512 experts and a chunked search above; the grid uses a binary search, a third way. */ if (!two_cls[2].empty() && !two_cls[3].empty()) { int64_t diff = 0; for (size_t i = 0; i < two_cls[2].size(); ++i) diff += two_cls[2][i] != two_cls[3][i]; @@ -8461,23 +8003,21 @@ static void moe_w4_gemm(const Plugin& pl, int64_t Tr, const MoeW4Shape& sh, int diff == 0, std::to_string(diff) + " of " + std::to_string(Tr * N) + " elements differ"); } - /* The aligned form's two column tiles on the down projection, where the sorted operand's every - * class is whole 256-column tiles; elsewhere the 256-column pin is refused. */ + /* The aligned form's two column tiles on the down projection where every class is whole + * 256-column tiles; elsewhere the 256-column pin is refused. */ const bool dn_wide = sh.sorted_a && sh.parts == 1 && sh.N0 % 256 == 0 && sh.N1 % 256 == 0; moe_aligned_down_tile(pl, r, a, d_y, d_map, map_bytes, (size_t)(Tr * N), two_cls[1], dn_wide, ne, what); - /* The decode form's staged K both ways, where this shape can take two blocks a pass -- - * never on the sorted operand, which the rule keeps at one. */ + /* The decode form's staged K both ways, where the shape can take two blocks per pass (never on + * the sorted operand). */ const bool fk2 = !sh.sorted_a && g64 && sh.K0 % 256 == 0 && sh.K1 % 256 == 0; moe_dec_variants(pl, r, a, d_y, (size_t)(Tr * N), fk2, what); if (!four) return; - /* AND THE SAME EXPERTS AS FOUR CLASSES, by number mod 4 (`moe_gemm_q_mod4`). Each parity table - * read at twice its stride is two of them -- from its first entry, the experts 0, 4, 8, ... of - * its parity's numbers mod 4, and from its second the others -- so classes 0 and 2 are the even - * table's halves and 1 and 3 the odd one's, at the even and the odd geometry. The same experts - * at the same geometry, read in the same order: every form must give the two-class op's bytes, - * byte for byte. What this checks is the class and entry each run resolves to. */ + /* The same experts as four classes by number mod 4 (`moe_gemm_q_mod4`): each parity table read + * at twice its stride from its first and second entries gives two classes, so classes 0 and 2 + * are the even table's halves and 1 and 3 the odd one's. Every form must reproduce the + * two-class op's bytes, checking the class and entry each run resolves to. */ const RadKernelInfo* r4 = find(pl, "moe_gemm_w4a8_mod4"); const std::string what4 = what + ", four classes"; if (!r4) { @@ -8514,7 +8054,7 @@ static void moe_w4_gemm(const Plugin& pl, int64_t Tr, const MoeW4Shape& sh, int a4.p = ps4.data(); a4.n_p = (int)ps4.size(); for (int form = f_lo; form <= f_hi; ++form) { const std::string label = what4 + " " + kForm[form]; - if (two_cls[form].empty()) continue; /* the two-class launch failed, and said so */ + if (two_cls[form].empty()) continue; /* the two-class launch failed (reported) */ if (pl.pin_moe) pl.pin_moe(form); { std::vector junk((size_t)(Tr * N), 0x7f7fu); @@ -8538,25 +8078,22 @@ static void moe_w4_gemm(const Plugin& pl, int64_t Tr, const MoeW4Shape& sh, int moe_dec_variants(pl, r4, a4, d_y, (size_t)(Tr * N), fk2, what4); } -/* THE FOUR-CLASS GROUPED GEMM, EACH CLASS AT ITS OWN GEOMETRY, AGAINST A HOST DECODE. +/* The four-class grouped GEMM, each class at its own geometry, against a host decode. * - * moe_w4_gemm's four-class pass reads the two-class op's tables as four, so its classes come in - * geometry pairs -- 0 with 2, 1 with 3 -- and class 0 is always among the wide ones. A rank of four - * holds two blocks of its own class of every five-block expert and one of each other: ONE wide - * class, which is class 0 on rank 0 only. Here every class is built at its own [N_q, K_q], stored - * through the row's own hooks at its own operands (2/3, 6/7, 8/9, 10/11), and checked against the - * planes, so a wide class 1, 2 or 3 has to read its own width and pitch, and a narrow class 0 has - * to write the zeros past its part. `dt` names the format: fp8a8 runs `moe_gemm_fp8a8_mod4`, block - * E4M3 with a bf16 scale a 128x128 tile; the four-bit ones run `moe_gemm_w4a8_mod4`, as - * moe_w4_gemm reads them. Every form, as there. */ + * moe_w4_gemm's four-class pass pairs geometries (0 with 2, 1 with 3), with class 0 always wide. + * A rank of four holds one wide class (two blocks of each five-block expert, one of the others), + * which is class 0 only on rank 0. Here each class is built at its own [N_q, K_q], stored through + * the row's hooks at its own operands (2/3, 6/7, 8/9, 10/11) and checked against the planes, so a + * wide class 1, 2 or 3 must read its own width and pitch and a narrow class 0 must write zeros past + * its part. `dt`: fp8a8 runs `moe_gemm_fp8a8_mod4` (block E4M3, a bf16 scale per 128x128 tile); + * the four-bit formats run `moe_gemm_w4a8_mod4`. Every form, as in moe_w4_gemm. */ struct MoeQ4Shape { const char* name; int64_t N[4], K[4], parts, ne; }; -/* A rank of four's slices of a five-block expert: the gate/up pair (two parts) at two 128-column - * blocks a part for the wide class and one for the others, the down projection at 256 and 128 of - * K. The wide class is 1, 2 or 3 -- what the ranks other than 0 hold. Ten experts make classes 0 - * and 1 one expert longer than 2 and 3; three hundred spread a decode step's few runs over - * experts that are mostly empty. Every part is whole 128-row blocks of the fp8 scale grid or lies - * inside one, so no output tile's weight rows straddle two -- block fp8 reads one scale a tile. */ +/* A rank of four's slices of a five-block expert: gate/up (two parts) at two 128-column blocks per + * part for the wide class and one for the others, down at 256 and 128 of K. The wide class is 1, 2 + * or 3 (ranks other than 0). Ten experts make classes 0 and 1 one expert longer; three hundred + * spread a decode step's runs over mostly empty experts. Every part is whole 128-row blocks of the + * fp8 scale grid or inside one, since block fp8 reads one scale per tile. */ static const MoeQ4Shape kMoeQ4Shapes[] = { { "gate/up, class 1 wide", { 256, 512, 256, 256 }, { 256, 256, 256, 256 }, 2, 10 }, { "gate/up, class 2 wide", { 256, 256, 512, 256 }, { 256, 256, 256, 256 }, 2, 10 }, @@ -8567,7 +8104,7 @@ static const MoeQ4Shape kMoeQ4Shapes[] = { static void moe_q4_gemm(const Plugin& pl, int64_t Tr, const MoeQ4Shape& sh, const char* dt) { const bool fp8 = std::strcmp(dt, "fp8a8") == 0, w5 = std::strcmp(dt, "w5nl64a8h") == 0; - /* Scale groups a 128 of K at the E4M3-scaled forms (moe_w4_gemm's `sub`), 0 at the others. */ + /* Scale groups per 128 of K at the E4M3-scaled forms (moe_w4_gemm's `sub`), 0 otherwise. */ const int64_t sub = std::strcmp(dt, "w4nl32a8h") == 0 ? 4 : (w5 || std::strcmp(dt, "w4nl64a8h") == 0) ? 2 : 0; const bool g64 = sub > 1; @@ -8596,10 +8133,10 @@ static void moe_q4_gemm(const Plugin& pl, int64_t Tr, const MoeQ4Shape& sh, cons PI("group", group), PS("dtype", dt), }; - /* Each class's experts e = 4x + q, from moe_w4_gemm's float source; their planes, kept for - * the reference, and the bytes the hooks store for them, asked at the class's own operands. - * Block fp8 is stored as its planes are, in both views; the four-bit codes are re-laid, and so - * is the E4M3 scale view with its second level, while a bf16 scale plane is stored as it is. */ + /* Each class's experts e = 4x + q from moe_w4_gemm's float source: their planes (kept for the + * reference) and the hooks' stored bytes at the class's operands. Block fp8 is stored as its + * planes; four-bit codes and the E4M3 scale view are relaid; a bf16 scale plane is stored + * as is. */ std::vector wq[4], ws[4]; std::vector cp[4]; int64_t nec[4] = { 0, 0, 0, 0 }; @@ -8643,8 +8180,8 @@ static void moe_q4_gemm(const Plugin& pl, int64_t Tr, const MoeQ4Shape& sh, cons } } - /* moe_w4_gemm's activation and routing: E4M3 bytes with no subnormal and no NaN, an f32 scale - * a (row, group) that varies along both, an uneven run on each expert and a dropped tail. */ + /* moe_w4_gemm's activation and routing: E4M3 bytes without subnormals or NaN, an f32 scale per + * (row, group) varying along both, uneven runs and a dropped tail. */ std::vector aq((size_t)(M * K)); std::vector as((size_t)(M * kb)); for (int64_t m = 0; m < M; ++m) { @@ -8727,21 +8264,21 @@ static void moe_q4_gemm(const Plugin& pl, int64_t Tr, const MoeQ4Shape& sh, cons for (int64_t g = 0; g < kbq; ++g) { const double a_s = (double)as[(size_t)(tok * kb + g)]; if (fp8) { - /* E4M3 codes, and the bf16 scale of the 128x128 tile the element is in. */ + /* E4M3 codes and the bf16 scale of the element's 128x128 tile. */ double part = 0.0; for (int64_t k = g * group; k < (g + 1) * group; ++k) part += (double)h_e4m3(p.data[0][(size_t)(wr * Kq + k)]) * - (double)st_e4m3(aq[(size_t)(tok * K + k)]); + (double)h_e4m3(aq[(size_t)(tok * K + k)]); want += part * (double)rad_load_f32(p.data[1].data(), RAD_BF16, (wr / group) * kbq + g) * a_s; } else if (g64) { - /* `sub` scale groups a 128, each an E4M3 byte under the fixed constant. */ + /* `sub` scale groups per 128, each E4M3 under the fixed constant. */ const int64_t gw = group / sub; for (int64_t h = 0; h < sub; ++h) { double part = 0.0; for (int64_t k = g * group + h * gw; k < g * group + (h + 1) * gw; ++k) part += (double)tab[code_at(p, wr, k)] * - (double)st_e4m3(aq[(size_t)(tok * K + k)]); + (double)h_e4m3(aq[(size_t)(tok * K + k)]); const uint8_t sb = p.data[1][(size_t)(wr * p.row_bytes(1) + sub * g + h)]; want += part * (double)h_e4m3(sb) * (double)kW4G64Scale * a_s; @@ -8750,7 +8287,7 @@ static void moe_q4_gemm(const Plugin& pl, int64_t Tr, const MoeQ4Shape& sh, cons double part = 0.0; for (int64_t k = g * group; k < (g + 1) * group; ++k) part += (double)code_at(p, wr, k) * - (double)st_e4m3(aq[(size_t)(tok * K + k)]); + (double)h_e4m3(aq[(size_t)(tok * K + k)]); want += part * (double)rad_load_f32(p.data[1].data(), RAD_BF16, wr * kbq + g) * a_s; } @@ -8786,7 +8323,7 @@ static void moe_q4_gemm(const Plugin& pl, int64_t Tr, const MoeQ4Shape& sh, cons for (int64_t n = 0; n < N; ++n) { const double want = ref[(size_t)(i * N + n)]; const double err = std::fabs((double)h_bf16(got[(size_t)(i * N + n)]) - want); - /* moe_w4_gemm's tolerance, written so that a NaN on either side is a miss. */ + /* moe_w4_gemm's tolerance; a NaN on either side is a miss. */ if (!(err <= 0.004 * std::fabs(want) + 1e-4)) { if (!bad++) first = ", first at row " + std::to_string(i) + " col " + @@ -8809,11 +8346,10 @@ static void moe_q4_gemm(const Plugin& pl, int64_t Tr, const MoeQ4Shape& sh, cons moe_dec_variants(pl, r, a, d_y, (size_t)(Tr * N), fk2, what); } -/* A DECODE STEP'S ROUTING, the way router_topk_scatter leaves it: M tokens, `top_k` distinct experts - * each -- half of the picks from thirty-two popular experts, the rest anywhere -- and, with `hot`, - * every token's first slot on one expert, whose run is then M rows long and crosses 16-row tiles. - * Every 37th slot goes to another rank (dropped, so the live count is short of T). Then the - * scatter's stable counting sort: runs in expert order, a run's slots in slot order. */ +/* A decode step's routing as router_topk_scatter leaves it: M tokens with `top_k` distinct experts + * each (half from thirty-two popular experts) and, with `hot`, every token's first slot on one + * expert, whose M-row run crosses 16-row tiles. Every 37th slot goes to another rank (dropped). + * Then the scatter's stable counting sort: runs in expert order, slots in slot order. */ static void moe_route(int64_t M, int64_t top_k, int64_t ne, uint64_t seed, bool hot, std::vector& off, std::vector& sorted) { const int64_t T = M * top_k; @@ -8849,23 +8385,18 @@ static void moe_route(int64_t M, int64_t top_k, int64_t ne, uint64_t seed, bool if (ids[(size_t)i] >= 0) sorted[(size_t)(at[(size_t)ids[(size_t)i]]++)] = (int32_t)i; } -/* THE SORTED OPERAND -- the down projection -- AT DECODE, every form against a host decode, and - * moe_down_dec_kernel, which the rule gives the decode form here, against the (tile, run) form - * BYTE FOR BYTE. +/* The sorted operand (the down projection) at decode: every form against a host decode, and + * moe_down_dec_kernel (the rule's decode form here) against the (tile, run) form byte for byte. * - * moe_q4_gemm reads the activation in token order; down reads it in sorted order, one row a routed - * slot, so that is the operand here, with a routing shaped like a decode step's (moe_route): at - * T = 40 one sequence at depth 3, at T = 640 sixteen, a run longer than a tile, runs that cross - * tile boundaries, a dropped tail. Each class has its own [N_q, K_q]; one class narrower than the - * output puts a column tile past its width, which both forms must zero. The decode kernel runs at - * several column groups, three of them uneven over the output's 64-column tiles; and the (tile, - * run) form itself against the uniform prefill grid, byte for byte, on the sorted-operand path the - * token-order cases never take. Every pinned variant is DESCRIBED first where the row can be: one - * that named the reference's kernel would match it trivially. + * Down reads the activation in sorted order, one row per routed slot, with a decode-shaped routing + * (moe_route): T = 40 (one sequence at depth 3) and T = 640 (sixteen), a run longer than a tile, + * runs crossing tiles, a dropped tail. Each class has its own [N_q, K_q]; one narrower than the + * output must zero the column tile past its width. The decode kernel runs at several column groups, + * three uneven over the 64-column tiles, and the (tile, run) form is checked against the uniform + * prefill grid on this sorted-operand path. Each pinned variant must dispatch a kernel of its own. * - * AND AN OUTPUT THAT NAMES FEWER ROWS THAN ITS BUFFER, while the offsets still name the whole - * routing: both decode forms must write those rows as the full launch did and never a row past - * them. */ + * Also an output naming fewer rows than its buffer while the offsets name the whole routing: both + * decode forms must write those rows as the full launch did and nothing past them. */ struct MoeDnShape { const char* name; int64_t N[4], K[4], ne, top_k; }; static void moe_down_dec_case(const Plugin& pl, const MoeDnShape& sh, const char* dt, @@ -8902,8 +8433,8 @@ static void moe_down_dec_case(const Plugin& pl, const MoeDnShape& sh, const char PI("group", group), PS("dtype", dt), }; - /* The experts, as moe_q4_gemm builds them: e = 4x + q, each class at its own geometry, the - * bytes the row's own hooks store for them at the class's operands. */ + /* The experts as moe_q4_gemm builds them: e = 4x + q, each class at its own geometry, stored + * by the row's hooks at the class's operands. */ std::vector wq[4], ws[4]; std::vector cp[4]; int64_t nec[4] = { 0, 0, 0, 0 }; @@ -8975,8 +8506,8 @@ static void moe_down_dec_case(const Plugin& pl, const MoeDnShape& sh, const char longest = std::max(longest, n); } - /* One activation row a routed slot: E4M3 bytes with no subnormal and no NaN, an f32 scale - * a (row, group) that varies along both, so a row read under another's scale shows. */ + /* One activation row per routed slot: E4M3 bytes without subnormals or NaN, an f32 scale + * per (row, group) varying along both. */ std::vector aq((size_t)(Tr * K)); std::vector as((size_t)(Tr * kb)); for (int64_t m = 0; m < Tr; ++m) { @@ -9031,7 +8562,7 @@ static void moe_down_dec_case(const Plugin& pl, const MoeDnShape& sh, const char double part = 0.0; for (int64_t k = g * group; k < (g + 1) * group; ++k) part += (double)h_e4m3(p.data[0][(size_t)(n * Kq + k)]) * - (double)st_e4m3(aq[(size_t)(i * K + k)]); + (double)h_e4m3(aq[(size_t)(i * K + k)]); want += part * (double)rad_load_f32(p.data[1].data(), RAD_BF16, (n / group) * kbq + g) * a_s; } else if (g64) { @@ -9040,7 +8571,7 @@ static void moe_down_dec_case(const Plugin& pl, const MoeDnShape& sh, const char double part = 0.0; for (int64_t k = g * group + h * gw; k < g * group + (h + 1) * gw; ++k) part += (double)tab[code_at(p, n, k)] * - (double)st_e4m3(aq[(size_t)(i * K + k)]); + (double)h_e4m3(aq[(size_t)(i * K + k)]); const uint8_t sb = p.data[1][(size_t)(n * p.row_bytes(1) + sub * g + h)]; want += part * (double)h_e4m3(sb) * (double)kW4G64Scale * a_s; } @@ -9048,7 +8579,7 @@ static void moe_down_dec_case(const Plugin& pl, const MoeDnShape& sh, const char double part = 0.0; for (int64_t k = g * group; k < (g + 1) * group; ++k) part += (double)code_at(p, n, k) * - (double)st_e4m3(aq[(size_t)(i * K + k)]); + (double)h_e4m3(aq[(size_t)(i * K + k)]); want += part * (double)rad_load_f32(p.data[1].data(), RAD_BF16, n * kbq + g) * a_s; } @@ -9057,9 +8588,11 @@ static void moe_down_dec_case(const Plugin& pl, const MoeDnShape& sh, const char } } - /* One pinned launch into stale bytes, its output back. `pins` is (form, the sorted - * operand's decode kernel: -1 the (tile, run) form, 0 the rule, n its column tiles). */ - auto run = [&](const int (&pins)[2], std::vector* got) { + /* One pinned launch into stale bytes, returning its output and its last dispatch. `pins` + * is (form, the sorted operand's decode kernel: -1 the (tile, run) form, 0 the rule, n + * its column tiles). */ + auto run = [&](const int (&pins)[2], std::vector* got, + const void** fn = nullptr) { { std::vector junk((size_t)(Tr * N), 0x7f7fu); st_memcpy(d_y, junk.data(), junk.size() * 2, hipMemcpyHostToDevice); @@ -9068,35 +8601,25 @@ static void moe_down_dec_case(const Plugin& pl, const MoeDnShape& sh, const char a.scratch_bytes = pins[0] == 3 ? 0 : map_bytes; pl.pin_moe(pins[0]); pl.pin_ddec(pins[1]); - const int rc = r->launch(&a, nullptr); + int rc = RAD_OK; + const void* last = last_dispatch(pl, r, a, &rc); st_stream_sync(nullptr); pl.pin_moe(0); pl.pin_ddec(0); + if (fn) *fn = last; got->assign((size_t)(Tr * N), 0); st_memcpy(got->data(), d_y, got->size() * 2, hipMemcpyDeviceToHost); return rc; }; - auto described = [&](const int (&pins)[2]) -> const void* { - if (!r->describe) return nullptr; - static RadLaunchDesc d[4]; - int n = 0; - a.scratch = pins[0] == 3 ? nullptr : d_map; - a.scratch_bytes = pins[0] == 3 ? 0 : map_bytes; - pl.pin_moe(pins[0]); - pl.pin_ddec(pins[1]); - const int drc = r->describe(&a, nullptr, d, 4, &n); - pl.pin_moe(0); - pl.pin_ddec(0); - return drc == RAD_OK && n >= 1 ? d[n - 1].func : nullptr; - }; /* Every form with the decode kernel off, against the host. */ std::vector base, grid; + const void* fn0 = nullptr; /* the (tile, run) form's kernel */ for (int form = 1; form <= 3; ++form) { const std::string label = what + " " + kForm[form]; const int pins[2] = { form, -1 }; std::vector got; - const int rc = run(pins, &got); + const int rc = run(pins, &got, form == 2 ? &fn0 : nullptr); if (rc != RAD_OK) { ok(label.c_str(), false, "launch rc=" + std::to_string(rc)); continue; } double worst = 0.0; int64_t bad = 0; @@ -9122,8 +8645,7 @@ static void moe_down_dec_case(const Plugin& pl, const MoeDnShape& sh, const char if (base.empty()) continue; /* The (tile, run) form on the sorted operand against the uniform prefill grid, byte for - * byte: every form keeps each output element's accumulation order, and the grid finds the - * runs a third way. */ + * byte. */ if (!grid.empty()) { int64_t diff = 0; for (size_t i = 0; i < grid.size(); ++i) diff += grid[i] != base[i]; @@ -9132,9 +8654,8 @@ static void moe_down_dec_case(const Plugin& pl, const MoeDnShape& sh, const char " elements differ"); } - /* The sorted operand's own decode kernel under the rule and at several column groups -- - * sixteen is the cap, past the output's five tiles here -- each against the (tile, run) - * form's bytes. */ + /* The sorted operand's decode kernel under the rule and at several column groups (sixteen, + * the cap, exceeds the output's five tiles), each against the (tile, run) form's bytes. */ struct Var { int dn; const char* name; }; static const Var kVar[] = { { 0, "down kernel, the rule's column tiles" }, @@ -9145,34 +8666,29 @@ static void moe_down_dec_case(const Plugin& pl, const MoeDnShape& sh, const char { 8, "down kernel, eight column tiles a block" }, { 16, "down kernel, sixteen column tiles a block" }, }; - const int ref_pins[2] = { 2, -1 }; - const void* fn0 = described(ref_pins); for (const Var& v : kVar) { const std::string label = what + " decode form, " + v.name + " (" + std::to_string(nrun) + " runs, longest " + - std::to_string(longest) + ")" + - (r->describe ? "" : " (launch not described)"); + std::to_string(longest) + ")"; const int pins[2] = { 2, v.dn }; - if (r->describe) { - const void* fn = described(pins); - if (!fn || fn == fn0) { - ok(label.c_str(), false, fn ? "named the (tile, run) form's kernel" - : "describe failed"); - continue; - } - } std::vector got; - const int rc = run(pins, &got); + const void* fn = nullptr; + const int rc = run(pins, &got, &fn); if (rc != RAD_OK) { ok(label.c_str(), false, "launch rc=" + std::to_string(rc)); continue; } + if (!fn || fn == fn0) { + ok(label.c_str(), false, fn ? "dispatched the (tile, run) form's kernel" + : "dispatched nothing"); + continue; + } int64_t diff = 0; for (size_t i = 0; i < got.size(); ++i) diff += got[i] != base[i]; ok(label.c_str(), diff == 0, std::to_string(diff) + " of " + std::to_string(Tr * N) + " elements differ from the (tile, run) form"); } - /* THE OUTPUT SEVEN ROWS SHORT: Y declared at Tr - 7 rows over the same buffer, the - * offsets unchanged, so the routing names rows past the output's last. Each decode form - * must write the rows it has exactly as the full launch did and leave the rest stale. */ + /* The output seven rows short: Y declared at Tr - 7 rows over the same buffer with the + * offsets unchanged. Each decode form must write its rows as the full launch did and leave + * the rest stale. */ { const int64_t Tv = Tr - 7; ts[12] = T(d_y, RAD_BF16, { Tv, N }); @@ -9199,25 +8715,21 @@ static void moe_down_dec_case(const Plugin& pl, const MoeDnShape& sh, const char } } -/* QFN's down projection at rank 0 of four, narrowed: 512 experts at top 10, K 256 for class 0 and - * 128 for the others -- and 384 for class 3, so a run takes three K blocks -- and N five 64-column - * tiles, class 2 one short of it. The other formats at 64 experts, top 4. */ +/* Qwen3.8-Flash-Next's down projection at rank 0 of four, narrowed: 512 experts at top 10, K 256 + * for class 0, 128 for classes 1-2 and 384 for class 3 (three K blocks per run), N five 64-column + * tiles with class 2 one short. The other formats at 64 experts, top 4. */ static const MoeDnShape kMoeDnShapes[] = { { "512 experts, top 10", { 320, 320, 256, 320 }, { 256, 128, 128, 384 }, 512, 10 }, { "64 experts, top 4", { 320, 320, 256, 320 }, { 256, 128, 128, 384 }, 64, 4 }, }; -/* THE ARRANGED PLANE, AGAINST THE FORMAT IT STATES, AND BACK. +/* The arranged plane against the format it states, and back. * - * `moe_gemm_w4a8` is the one large weight of a routed model, and what a checker reads it through is - * the row's inverse: a reference handed the arranged nibbles reads the wrong element in most - * positions and reports a correct kernel as wrong. So the inverse has to give back exactly the - * planes the relayout was handed. - * - * AND THE ARRANGEMENT HAS TO BE THE ONE r4d_layout.cpp STATES, which is checked from the - * statement and not from either hook: byte b of a packed dword holds element b low and element - * b+4 high, two's complement. The scale plane is read as it is stored, so its hook must answer - * RAD_E_UNSUPPORTED -- "nothing to arrange", which a caller has to be able to tell from a refusal. */ + * A checker reads `moe_gemm_w4a8`'s weight through the row's inverse, so the inverse must return + * exactly the planes the relayout was given. The arrangement is checked against r4d_layout.cpp's + * statement, not either hook: byte b of a packed dword holds element b low and b+4 high, two's + * complement. The scale plane is stored as is, so its hook must answer RAD_E_UNSUPPORTED + * ("nothing to arrange"). */ static void moe_w4_unlayout(const Plugin& pl) { const char* what = "moe_gemm_w4a8's arranged plane, vs the stated format and its inverse"; const RadKernelInfo* r = find(pl, "moe_gemm_w4a8"); @@ -9258,10 +8770,10 @@ static void moe_w4_unlayout(const Plugin& pl) { std::to_string(bad_code) + " code(s) not where the format puts them" + (back ? std::string() : "; inverse: " + why)); - /* w5nl64a8h's row, against the same statement: the low four bits of every code where w4a8's - * nibble would be, in a row K/2 + K/8 bytes long, and the high bit -- the sign -- of element - * 4m+b of a 32 at bit 7-m of byte b of that 32's dword, from byte K/2 on. The table beside - * the codes is the kernel's, and its inverse restores both planes. */ + /* w5nl64a8h's row against the same statement: the low four bits of every code where w4a8's + * nibble would be, in a K/2 + K/8-byte row, and the high bit (the sign) of element 4m+b of a + * 32 at bit 7-m of byte b of that 32's dword, from byte K/2 on. The table is the kernel's, and + * the inverse restores both planes. */ const char* what5 = "moe_gemm_w4a8's five-bit arranged plane, vs the stated format and its " "inverse"; std::vector lp5 = { PI("N", N), PI("K", K), PI("group", group), @@ -9289,30 +8801,22 @@ static void moe_w4_unlayout(const Plugin& pl) { } std::string why5; const bool back5 = restores(r, lp5, 2, p5, { "codes", "table" }, w5, &why5); - /* Half the source is negative, so a fixture with no sign bits set proves nothing. */ + /* Half the source is negative, so sign bits are exercised. */ ok(what5, bad5 == 0 && back5 && neg > N * K / 4, std::to_string(bad5) + " code(s) not where the format puts them, " + std::to_string(neg) + " negative" + (back5 ? std::string() : "; inverse: " + why5)); } -/* ---- THE ROTATED EXPERT FORMAT, end to end and against the float it approximates. +/* ---- the rotated expert format, end to end, against the float it approximates. * - * WHAT THIS CATCHES AND moe_w4_gemm CANNOT. That case compares the kernel against a host product - * over the planes: it proves the arrangement, the two's complement and the scale grid, and it would - * pass just as happily if the WEIGHT had been rotated by one Hadamard and the ACTIVATION by a - * different one, because it never looks at what the numbers mean. The rotated pair is only a model - * if the quantiser's Hadamard (this file's h_fwht, libquant's fwht_inplace) and r4d_fwht.h's - * r4d_fwht_wave are the same transform -- and they are written independently, one iterative over a - * host array and one in registers across a wave with five shuffles, so nothing but a test says so. + * moe_w4_gemm checks against the planes, so it would pass if the weight and the activation were + * rotated by different Hadamards. The quantiser's transform (h_fwht here, libquant's + * fwht_inplace) and r4d_fwht.h's r4d_fwht_wave are written independently (a host loop versus + * five in-register shuffles across a wave), so the oracle here is the exact dot product of the + * source weight and activation in original coordinates, against which both formats are measured. + * A mismatched rotation gives rel_l2 around 5 instead of around 0.1. * - * The oracle is therefore the exact f32 dot product of the SOURCE weight and the SOURCE - * activation, in the original coordinates, and both formats are measured against it in one run. - * A rotation mismatch is not subtle when read that way -- rotating the activation and not the - * weight measures rel_l2 5.32 against 0.13 -- but it is invisible without this oracle. - * - * The two numbers it prints are also the instrument the format decision rests on, which is why - * the source has a few outlier channels in it: sixteen levels spent covering one outlier is - * exactly the error a rotation is supposed to remove, and a source with none would make the two - * formats look alike for a reason that is not true of a real expert. */ + * The printed numbers also compare the two formats, so the source has a few outlier channels: + * covering an outlier with sixteen levels is the error rotation removes. */ static void moe_w4_rot(const Plugin& pl) { const char* what = "moe_gemm_w4a8h/w4nla8h/w4nl64a8h/w5nl64a8h + had_quant_act_fp8 vs the f32 " "they approximate"; @@ -9327,8 +8831,8 @@ static void moe_w4_rot(const Plugin& pl) { const int64_t ne = 3, N = 64, K = 256, group = 128, top_k = 2, Tr = 24; const int64_t kb = K / group, M = Tr / top_k; - /* The source weight and activation, in float. Outliers every 37th and 23rd column -- six - * times the body, which is mild beside a real MoE input and enough to separate the grids. */ + /* The source weight and activation in float, with outliers every 37th and 23rd column at six + * times the body (milder than a real MoE input, enough to separate the grids). */ std::vector wsrc((size_t)(ne * N * K)); std::vector xbf ((size_t)(M * K)); std::vector xsrc((size_t)(M * K)); @@ -9343,8 +8847,8 @@ static void moe_w4_rot(const Plugin& pl) { for (int64_t k = 0; k < K; ++k) { float v = (float)(((m * 29 + k * 11) % 53) - 26) / 41.0f; if (k % 23 == 0) v *= 6.0f; - /* Rounded through bf16 HERE, so the oracle reads the same number the device does and - * the residual is the format's and not the input's. */ + /* Rounded through bf16 here, so the oracle reads the device's value and the residual + * is the format's. */ const uint16_t h = h_to_bf16(v); xbf [(size_t)(m * K + k)] = h; xsrc[(size_t)(m * K + k)] = h_bf16(h); @@ -9364,7 +8868,7 @@ static void moe_w4_rot(const Plugin& pl) { st_memcpy(d_s, sorted.data(), sorted.size() * 4, hipMemcpyHostToDevice); st_memcpy(d_o, off.data(), off.size() * 4, hipMemcpyHostToDevice); - /* The exact answer, in the ORIGINAL coordinates: no rotation, no grid, f64 accumulation. */ + /* The exact answer in the original coordinates: no rotation, no grid, f64 accumulation. */ std::vector want((size_t)(Tr * N), 0.0); for (int64_t i = 0; i < live; ++i) { const int64_t tok = sorted[(size_t)i] / top_k; @@ -9379,21 +8883,21 @@ static void moe_w4_rot(const Plugin& pl) { } } - /* Six formats: plain, rotated, rotated with the w4nl codebook -- whose codes view takes the - * table beside the codes and whose kernel decodes that table -- the codebook at E4M3 scales a - * 64 and a 32 of K, whose scale view takes the fixed second level beside the scales, and the - * five-bit codebook at a 64, whose codes carry their signs in a plane of their own. */ + /* Six formats: plain; rotated; rotated with the w4nl codebook (the codes view takes the table + * and the kernel decodes it); the codebook at E4M3 scales per 64 and per 32 of K (the scale + * view takes the fixed second level); and the five-bit codebook per 64, with its signs in a + * separate plane. */ double rel[6] = { -1.0, -1.0, -1.0, -1.0, -1.0, -1.0 }; for (int pass = 0; pass < 6; ++pass) { const bool rot = pass >= 1, nl = pass >= 2, g64 = pass >= 3, w5 = pass == 5; - const int64_t sub = pass == 4 ? 4 : g64 ? 2 : 1; /* scale groups a 128 */ + const int64_t sub = pass == 4 ? 4 : g64 ? 2 : 1; /* scale groups per 128 */ const char* dt = w5 ? "w5nl64a8h" : pass == 4 ? "w4nl32a8h" : g64 ? "w4nl64a8h" : nl ? "w4nla8h" : rot ? "w4a8h" : "w4a8"; std::vector lp = { PI("N", N), PI("K", K), PI("group", group), PS("dtype", dt) }; const int64_t wbytes = w5 ? N * K / 8 * 5 : N * K / 2; std::vector wq((size_t)(ne * wbytes), 0); - std::vector ws((size_t)(ne * N * kb * (sub > 2 ? 2 : 1)), 0); /* bytes a 128: 2, or 4 */ + std::vector ws((size_t)(ne * N * kb * (sub > 2 ? 2 : 1)), 0); /* 2 or 4 B/128 */ for (int64_t e = 0; e < ne; ++e) { const std::vector we(wsrc.begin() + e * N * K, wsrc.begin() + (e + 1) * N * K); const Planes pe = g64 ? nl64_planes(we, N, K, 128 / sub, w5) @@ -9409,10 +8913,9 @@ static void moe_w4_rot(const Plugin& pl) { ok(what, false, "relayout rc " + std::to_string(rw) + "/" + std::to_string(rs)); return; } - /* THE ENCODING IS THE WHOLE GUARD AGAINST A MIS-SERVED CONTAINER, so it is checked - * here and not merely produced: the arrangement, the extents and the byte count are - * identical between the two formats, and only the encoding's transform differs. The - * hook must take the one its dtype names and refuse the other at declare. */ + /* The encoding is the only guard against a mis-served container (arrangement, + * extents and byte count are identical across formats), so the hook must accept the + * encoding its dtype names and refuse the other. */ if (e == 0) { const Planes other = int4_planes(we, N, K, group, RAD_BF16, nl || !rot); std::vector scratch; @@ -9435,8 +8938,8 @@ static void moe_w4_rot(const Plugin& pl) { std::memcpy((uint8_t*)ws.data() + (size_t)e * sc.size(), sc.data(), sc.size()); } - /* The activation goes through the DEVICE quantiser -- the whole point is that its - * rotation is the one the weight's planes were quantised under. */ + /* The activation goes through the device quantiser, whose rotation must match the one + * the weight's planes were quantised under. */ void* d_q = dalloc((size_t)(M * K)); void* d_qs = dalloc((size_t)(M * kb) * 4); std::vector qt = { @@ -9497,23 +9000,18 @@ static void moe_w4_rot(const Plugin& pl) { rel[pass] = den > 0.0 ? std::sqrt(num / den) : -1.0; } - /* 0.6 is loose ON PURPOSE. The measured pair is 0.20 and 0.13, and a quantiser that improves - * on either must not have to come back here and move a number. The failure it is set to catch is - * much further away than that: feeding the ROTATED activation to the UNROTATED weight -- the - * exact mismatch a mis-served container would produce -- measures 5.32, because the rotated - * values are also sqrt(128) larger. */ + /* 0.6 is deliberately loose, well above the formats' error, so a better quantiser needs no + * change here. A mis-served container (rotated activation, unrotated weight) measures around 5, + * since the rotated values are also sqrt(128) larger. */ bool pass = true; for (double x : rel) pass = pass && x >= 0.0 && x < 0.6; - /* PRINTED WHETHER OR NOT IT PASSES, because the pass is about the plumbing and the numbers - * are about the format: a reader comparing two quantisers wants them either way, and `ok` shows - * its detail only on a failure. A kernel that decoded the w4nl codes as -8..7 would read - * every code as a different number and measure near 1. */ + /* Printed even on a pass, to compare the formats (`ok` shows detail only on failure). A kernel + * decoding w4nl codes as -8..7 would measure near 1. */ std::printf(" rel_l2 vs f32: w4a8 %.4f, w4a8h %.4f, w4nla8h %.4f, w4nl64a8h %.4f, " "w4nl32a8h %.4f, w5nl64a8h %.4f\n", rel[0], rel[1], rel[2], rel[3], rel[4], rel[5]); - /* The finer groups have to show: a fold that read one group's scale for another, or the bytes - * in another order, lands at or above the coarser form. And the fifth bit has to: a sign plane - * read for the wrong elements -- or not at all -- flips half the signs, which measures near 1, - * and one read for the right elements of the wrong row measures well above w4nl64a8h. */ + /* The finer groups must improve on the coarser form (a fold reading the wrong group's scale, + * or bytes in another order, would not), and the fifth bit must too: a sign plane misread or + * ignored flips half the signs (near 1), and the wrong row's lands well above w4nl64a8h. */ pass = pass && rel[3] < rel[2] && rel[4] < rel[3] && rel[5] < 0.75 * rel[3]; ok(what, pass, "rel_l2 w4a8 " + std::to_string(rel[0]) + ", w4a8h " + std::to_string(rel[1]) + ", w4nla8h " + std::to_string(rel[2]) + ", w4nl64a8h " + std::to_string(rel[3]) + @@ -9523,33 +9021,25 @@ static void moe_w4_rot(const Plugin& pl) { /* qsa_work, against a host walk of the same batch. * - * THE FIXTURE IS A MIXED STEP, because that is the case the op exists for and the one a - * single-sequence test cannot reach: a long prefill chunk that completes many blocks and STRADDLES - * the boundary (so its first block takes keys from the tail AND from the chunk), a short chunk - * that stops inside a block, a speculative decode row of four that completes one out of two - * tail keys and two of its own, and a fresh three-token prompt that stops before its first block - * ends. Four sequences, four shapes, one launch. + * A mixed step: a long prefill chunk that completes many blocks and straddles a boundary (its + * first block takes keys from the tail and the chunk), a short chunk stopping inside a block, a + * four-row speculative decode completing a block from two tail keys and two of its own, and a + * fresh three-token prompt ending before its first block. One launch. * - * THREE THINGS HERE ARE REGRESSION TESTS AND NOT COVERAGE. + * Pinned on purpose: * - * THE STATE SLOTS ARE PERMUTED AND WIDER THAN THE BATCH -- {5, 0, 8} out of nine. A kernel that - * indexed the tail by the BATCH ROW reads slots 0, 1, 2 and every tail key comes back wrong. - * That is not a synthetic worry: the scheduler builds a step from the running set in priority - * order and stable-sorts decode first, so the row a sequence - * occupies changes under it and a long-lived request inherits a retired one's keys. + * The state slots are permuted and wider than the batch ({5, 0, 8, 3} of nine). The scheduler + * reorders rows between steps, so a kernel indexing the tail by batch row reads another + * sequence's keys. * - * THE RING IS 7 AND THE RATIO IS 4, so `q % ring` and `q % ratio` name different rows for every - * tail key in the fixture. A kernel that used `% ratio` passes a ring==ratio fixture and fails - * this one. + * The ring is 7 and the ratio 4, so `q % ring` and `q % ratio` name different rows for every + * tail key. * - * THE THREE-TOKEN PROMPT ENDS BEFORE ITS FIRST BLOCK DOES. A block bound taken with C's - * truncating division counts block 0 complete from position 0 and gathers a key past the end - * of the sequence; here that is a work item where the padding must say -1. + * The three-token prompt: a block bound from truncating division would count block 0 complete + * and gather a key past the sequence's end, where the padding must say -1. * - * What is otherwise checked is every operand the block-key kernel will read: the page, the - * first-token position, the `ratio` staged rows a block -- each against the source it should have - * come from -- and that the slots past the real count say -1 rather than naming a page nobody - * meant. + * Also checked: every operand the block-key kernel reads (page, first-token position, the `ratio` + * staged rows per block) against its source, and -1 in the slots past the real count. */ static void qsa_work_case(const Plugin& pl) { const char* what = "qsa_work vs a host walk of a mixed prefill/decode batch"; @@ -9559,12 +9049,12 @@ static void qsa_work_case(const Plugin& pl) { const int64_t n = 32, ratio = 4, ring = 7, seqs = 4, btw = 64, slots = 9; const int32_t cuh[5] = { 0, 22, 25, 29, 32 }; const int64_t NT = cuh[4]; - /* NOT the batch rows, and wider than the batch -- see the header. */ + /* Not the batch rows, and wider than the batch (see the header). */ const int32_t sxh[4] = { 5, 0, 8, 3 }; - /* Sequence 0 starts at 11 -- NOT a block boundary -- so its first complete block (indices - * 8..11) needs 8, 9 and 10 from the tail and only 11 from the chunk. Sequence 1 starts ON a - * boundary and needs none. Sequence 2 is a four-row speculative decode whose block takes two - * of each. Sequence 3 is positions 0..2, one short of its first block. */ + /* Sequence 0 starts at 11, mid-block, so its first complete block (8..11) takes 8-10 from the + * tail and 11 from the chunk. Sequence 1 starts on a boundary. Sequence 2 is a four-row + * speculative decode whose block takes two of each. Sequence 3 is positions 0..2, one short of + * its first block. */ const int64_t start[4] = { 11, 60, 130, 0 }; std::vector kh((size_t)(NT * n)); @@ -9575,8 +9065,7 @@ static void qsa_work_case(const Plugin& pl) { for (int64_t d = 0; d < n; ++d) kh[(size_t)(t * n + d)] = h_to_bf16((float)((t * 31 + d * 17) % 89) / 23.0f); } - /* The tail pool, [slots][ring][n], and every slot holds something DIFFERENT: a kernel reading - * the wrong slot has to come back with the wrong bytes, not with bytes that happen to match. */ + /* The tail pool, [slots][ring][n], every slot holding different values. */ std::vector th((size_t)(slots * ring * n)); for (int64_t sl = 0; sl < slots; ++sl) for (int64_t row = 0; row < ring; ++row) @@ -9649,9 +9138,8 @@ static void qsa_work_case(const Plugin& pl) { std::vector gnc((size_t)seqs); st_memcpy(gnc.data(), d_nc, gnc.size() * 4, hipMemcpyDeviceToHost); - /* COMPLETE BLOCKS A SEQUENCE, which the scorer and the selection read. It is (last position - * + 1) / ratio and not the number of blocks that completed THIS step -- a distinction worth a - * check, because the two are the same on a sequence that starts at zero and nothing else. */ + /* Complete blocks per sequence, (last position + 1) / ratio, not the blocks completed this + * step (the two agree only for a sequence starting at zero). */ bool nc_ok = true; for (int64_t s = 0; s < seqs; ++s) { const int32_t w2 = (int32_t)((ph[(size_t)(cuh[s + 1] - 1)] + 1) / ratio); @@ -9678,11 +9166,10 @@ static void qsa_work_case(const Plugin& pl) { if (gs[(size_t)((w * ratio + i) * n + d)] != src[(size_t)d]) key_ok = false; } } - /* UNDER M-RoPE, with the step's rotary planes: `bpos` is [work, 3], a block's components - * side by side. A block's first token in this step reads its own three; one committed - * earlier is text, at its index plus the shift the sequence's first row carries -- and the - * shift differs per sequence here, as it does after a picture, so a kernel that took one - * sequence's shift for another's is wrong. The components differ from each other too. */ + /* Under M-RoPE, with the step's rotary planes: `bpos` is [work, 3]. A block whose first + * token is in this step reads that token's three components; one committed earlier is text, + * at its index plus the shift of the sequence's first row. Shifts differ per sequence (as + * after a picture), and the components differ from each other. */ const int32_t shift[4] = { 0, -9, 17, 5 }; std::vector rh((size_t)(3 * NT)); for (int64_t s = 0; s < seqs; ++s) @@ -9719,9 +9206,8 @@ static void qsa_work_case(const Plugin& pl) { if (g3[(size_t)(w * 3 + c)] != e) mc_ok = false; } } - /* And a pass WITHOUT the planes on the same buffer, as a text-only step hands it: the first - * column alone, [work, 1] at a row pitch of 3. Component 0 is written and the other two - * columns keep what they held. */ + /* And a pass without the planes, as a text-only step: [work, 1] at a row pitch of 3. + * Component 0 is written; the other two columns keep their values. */ st_memcpy(d_b3, sentinel.data(), sentinel.size() * 4, hipMemcpyHostToDevice); std::vector tt = ts; RadTensor col = T(d_b3, RAD_I32, { W_, 1 }); @@ -9739,8 +9225,7 @@ static void qsa_work_case(const Plugin& pl) { std::printf(" M-RoPE: [work, 3] positions %s (%ld from committed text); one column at " "pitch 3 %s\n", mc_ok ? "ok" : "NO", mc_text, col_ok ? "ok" : "NO"); - /* The straddling block is what makes this a real test rather than a copy of the chunk, and - * `ring_differs` is what makes it a test of the RING rather than of the modulus. */ + /* `from_tail` requires a straddling block, `ring_differs` that ring and ratio rows differ. */ const bool pass = page_ok && pos_ok && key_ok && pad_ok && nc_ok && from_tail > 0 && ring_differs > 0 && !want.empty() && mc_ok && mc_text > 0 && col_ok; std::printf(" %zu blocks (%ld keys from the tail, %ld at a row the old modulus would " @@ -9755,26 +9240,16 @@ static void qsa_work_case(const Plugin& pl) { /* qsa_tail_store, against a token-by-token loop. * - * THE WHOLE CASE IS THE RACE. Positions p and p + ring share a row, so a prefill chunk carrying - * many tokens a sequence has several tokens targeting one row -- and the kernel is allowed to - * write only the last of them. The fixture therefore gives one sequence a long chunk, another a - * short one, and a third a four-row speculative decode, and the oracle is the SERIAL loop: every - * token in order, last writer wins. A kernel that wrote them all would agree with this on the - * short and single cases and disagree on the long one, non-deterministically -- so the case also - * runs twice and requires the same bytes. + * Positions p and p + ring share a row, so a long prefill chunk has several tokens per row and + * the kernel may write only the last. The fixture has a long chunk, a short one and a four-row + * speculative decode; the oracle is the serial loop (last writer wins). Writing every token would + * race on the long chunk, so the case also runs twice and requires identical bytes. * - * TWO THINGS HERE ARE PINNED DELIBERATELY AND ARE NOT COVERAGE: + * Pinned on purpose: the state slots are permuted and wider than the batch ({5, 0, 8} of nine), + * since the row is step-local and the slot belongs to the sequence; and the ring is 7 with ratio + * 4, so `pos % ring` and `pos % ratio` disagree. * - * THE STATE SLOTS ARE PERMUTED AND WIDER THAN THE BATCH -- {5, 0, 8} out of nine -- so a kernel - * that indexed by the BATCH ROW writes slots 0, 1, 2 and the untouched-row count collapses. - * The row a sequence occupies is step-local; the slot is the sequence's for its life. - * - * THE RING IS 7 AND THE RATIO IS 4. `pos % ring` and `pos % ratio` disagree for most of this - * fixture, so a kernel that used `% ratio` fails on the rows, and `ring` rows of a sequence's - * state are in play rather than four. - * - * The other thing it pins is that rows nothing targets KEEP WHAT THEY HELD. That is what makes - * the tail a tail: at decode a handful of rows are written a step and the rest are the point. + * Rows nothing targets must keep their values. */ static void qsa_tail_store_case(const Plugin& pl) { const char* what = "qsa_tail_store vs the serial last-writer-wins loop"; @@ -9786,9 +9261,7 @@ static void qsa_tail_store_case(const Plugin& pl) { const int32_t cuh[4] = { 0, 19, 22, 26 }; const int64_t NT = cuh[3]; const int32_t sxh[3] = { 5, 0, 8 }; - /* Each sequence starts somewhere different, and NOT on a block boundary for two of them -- - * `pos % ring` is the row and a fixture that only ever started at 0 would never see a - * sequence whose first token lands mid-block. */ + /* Different starts, two of them mid-block, since `pos % ring` is the row. */ const int64_t start[3] = { 40, 7, 131 }; std::vector kh((size_t)(NT * n)); @@ -9800,13 +9273,12 @@ static void qsa_tail_store_case(const Plugin& pl) { kh[(size_t)(t * n + d)] = h_to_bf16((float)((t * 13 + d * 7) % 97) / 31.0f); } - /* The pool arrives holding something, and most of it must still hold it afterwards -- every - * row of every slot, including the six slots this batch does not name at all. */ + /* A pre-filled pool; untargeted rows, including the six unnamed slots, must keep it. */ std::vector pre((size_t)(slots * ring * n)); for (size_t i = 0; i < pre.size(); ++i) pre[i] = h_to_bf16(-3.5f - (float)(i % 5)); std::vector want = pre; for (int64_t s = 0; s < seqs; ++s) - for (int64_t t = cuh[s]; t < cuh[s + 1]; ++t) { /* IN ORDER: last writer wins */ + for (int64_t t = cuh[s]; t < cuh[s + 1]; ++t) { /* in order: last writer wins */ const int64_t row = ph[(size_t)t] % ring; for (int64_t d = 0; d < n; ++d) want[(size_t)((sxh[s] * ring + row) * n + d)] = kh[(size_t)(t * n + d)]; @@ -9853,9 +9325,8 @@ static void qsa_tail_store_case(const Plugin& pl) { if (got[0][i] == pre[i]) ++kept; if (want[i] == pre[i]) ++kept_want; } - /* THE SLOTS THIS BATCH DOES NOT NAME MUST BE UNTOUCHED, and they are the ones a batch-row - * index would have walked straight into. Counted separately, because the aggregate above - * would still look plausible if three wrong slots were written and three right ones were not. */ + /* Slots the batch does not name must be untouched; a batch-row index would write them. + * Counted separately from the aggregate above. */ bool other_ok = true; for (int64_t sl = 0; sl < slots; ++sl) { bool named = false; @@ -9879,22 +9350,14 @@ static void qsa_tail_store_case(const Plugin& pl) { /* sample_argmax, against a host scan. * - * WHAT MAKES THIS WORTH A CASE IS THE TIE RULE AND THE TWO LOAD BODIES, not finding a maximum. - * Greedy must break ties to the LOWEST token id -- that is what lets a greedy step and a top-1 - * step never disagree -- and the kernel gets it by packing (key, ~id) into one word, which is - * right only if the packing is monotone in the key and ANTI-monotone in the id. A row whose - * maximum occurs at four ids is the only input that can tell the two apart; a row of distinct - * values passes either way. + * Checks the tie rule and both load bodies. Greedy breaks ties to the lowest token id (so greedy + * and top-1 agree); the kernel packs (key, ~id) into one word, monotone in the key and + * anti-monotone in the id. Each row's maximum occurs at four ids. * - * The kernel also has two bodies: a float4 one when the row base AND the row pitch are 16-byte - * aligned, and a scalar one when they are not. Both run here. `n_vocab` is deliberately not a - * multiple of four, so the vector body also has a two-entry tail to pick up scalar-wise, and one - * of the tied ids is inside that tail. - * - * THE PITCH IS THE THING THE ALIGNMENT TEST GETS WRONG IF IT ONLY LOOKS AT THE BASE: row m starts - * at m * lg_ld floats, so with an odd pitch every row after the first is misaligned even though - * the allocation is not. Pass 0 gives a pitch that is a multiple of four and pass 1 one that is - * not, and both must produce the same answer. + * The float4 body runs when both row base and row pitch are 16-byte aligned, the scalar body + * otherwise. `n_vocab` is not a multiple of four, so the vector body has a two-entry scalar tail, + * which holds one of the tied ids. Pass 0's pitch is a multiple of four, pass 1's is not (every + * row after the first misaligned); both must give the same answer. */ static void sample_argmax_case(const Plugin& pl) { const char* what = "sample_argmax vs a host scan, with ties and both load bodies"; @@ -9910,7 +9373,7 @@ static void sample_argmax_case(const Plugin& pl) { rs = rs * 1664525u + 1013904223u; rows[(size_t)m][(size_t)i] = (float)((int32_t)((rs >> 8) % 20001u) - 10000) * 0.001f; } - /* Four ids hold the maximum exactly; the last of them is in the vector body's tail. */ + /* Four ids hold the maximum; the last is in the vector body's tail. */ const int64_t ties[4] = { 7, V / 3, V - 6, V - 1 }; for (int k = 0; k < 4; ++k) rows[(size_t)m][(size_t)ties[k]] = 11.0f + (float)m; want[(size_t)m] = (int32_t)ties[0]; @@ -9955,19 +9418,15 @@ static void sample_argmax_case(const Plugin& pl) { /* qsa_select, against a host sort of the same scores. * - * WHAT MAKES THIS WORTH A CASE IS THE TIES AND THE TAIL, not the selection. A top-k is easy to get - * right on distinct inputs and easy to get wrong on equal ones, and a block score is a sum of four - * relus over a shared grid -- equal scores are ordinary, not pathological. So the fixture gives - * the threshold value to more blocks than there are slots left, and the oracle is a full sort by - * (score descending, index ascending), which is exactly the rule the kernel's two prefix counts - * implement. + * Focused on ties and the tail. Block scores (sums of relus over a shared grid) tie often, so the + * fixture gives the threshold value to more blocks than there are slots left, and the oracle is a + * full sort by (score descending, index ascending), the rule the kernel's prefix counts implement. * - * Four things are checked and three of them are not the answer itself: - * the SET matches a host sort - * the partial page is LAST, because that is what lets the attention's own causal bound mask - * inside it and nowhere else - * a page id of -1 inside the scored range is never selected, however good its score - * two runs produce byte-identical tables -- a top-k placed by atomics would not + * Checked: + * the set matches a host sort; + * the partial page is last, so the attention's causal bound masks inside it only; + * a page id of -1 inside the scored range is never selected, whatever its score; + * two runs give byte-identical tables (atomic placement would not). */ static void qsa_select_case(const Plugin& pl) { const char* what = "qsa_select vs a host sort, with ties, a tail and a dead page"; @@ -9979,18 +9438,17 @@ static void qsa_select_case(const Plugin& pl) { std::vector sc((size_t)(M * nb), 0.0f); std::vector bt((size_t)(M * nb), -1), nc((size_t)M, 0); for (int64_t m = 0; m < M; ++m) { - /* Row 0 and 1 are shorter than topk -- the fast path, where everything live is selected. - * The rest run the radix. Rows alternate on whether a partial page exists. */ + /* Rows 0 and 1 have at most topk live blocks (the fast path, all selected); the rest run + * the radix. Rows alternate on whether a partial page exists. */ const int64_t live = (m == 0) ? 9 : (m == 1) ? topk : (100 + m * 137); nc[(size_t)m] = (int32_t)live; for (int64_t b = 0; b < nb; ++b) { const size_t i = (size_t)(m * nb + b); if (b < live) { - /* A COARSE GRID ON PURPOSE: 40 distinct values over hundreds of blocks puts many - * blocks on the threshold exactly, which is the case the tie rule is for. */ + /* A coarse grid: 40 values over hundreds of blocks puts many on the threshold. */ sc[i] = (float)((b * 17 + m * 7) % 40) * 0.25f; bt[i] = (int32_t)((b * 31 + m * 11) % pages); - /* A DEAD PAGE WITH A WINNING SCORE, inside the scored range. */ + /* A dead page with a winning score, inside the scored range. */ if (b == live / 3) { sc[i] = 1e6f; bt[i] = -1; } } else if (b == live) { bt[i] = (m % 2 == 0) ? (int32_t)((m * 97 + 5) % pages) : -1; /* the tail */ @@ -10029,9 +9487,8 @@ static void qsa_select_case(const Plugin& pl) { pos[(size_t)m] = (int32_t)(want_tail[(size_t)m] >= 0 ? live * ratio + (m % 3) : live * ratio - 1); } - /* ONE QUERY A SEQUENCE: the decode shape, where `seq(m) == m` and each row's `nc` is its own. - * That is what the oracle above assumes, and it is deliberate -- the point of this case is the - * radix and the tie rule, not the join. qsa_select_prefill_case is the join. */ + /* One query per sequence (decode shape, `seq(m) == m`), as the oracle assumes; + * qsa_select_prefill_case covers the join. */ std::vector cuh((size_t)(M + 1)); for (int64_t i = 0; i <= M; ++i) cuh[(size_t)i] = (int32_t)i; @@ -10092,11 +9549,9 @@ static void qsa_select_case(const Plugin& pl) { std::sort(ref.begin(), ref.end()); if (mine != ref) set_ok = false; } - /* THE CAUSAL BOUND THE ATTENTION WILL BE GIVEN. The flat KV is `nsel` pages of `ratio` with - * the partial page LAST, so the query sits at `(nsel-1)*ratio + pos%ratio` and the length is - * one past it. Checked here because it is the number that decides whether the sparse - * attention reads the query's own token and stops there -- and because it is an off-by-one - * away from reading tokens the query cannot see. */ + /* The causal bound for the attention: the flat KV is `nsel` pages of `ratio`, partial page + * last, so the query sits at `(nsel-1)*ratio + pos%ratio` and the length is one past it. Off + * by one, the attention would skip the query's own token or read beyond it. */ bool su_ok = true; for (int64_t m = 0; m < M; ++m) { const int32_t ns = gn[0][(size_t)m]; @@ -10115,19 +9570,15 @@ static void qsa_select_case(const Plugin& pl) { " su=" + (su_ok ? "1" : "0") + " det=" + (det ? "1" : "0")); } -/* qsa_select AT PREFILL: many queries over one history, each bounded by its own position. +/* qsa_select at prefill: many queries over one history, each bounded by its own position. * - * THIS IS THE CASE THE DECODE FIXTURE CANNOT REACH. There, one query a sequence makes the - * sequence's complete-block count and the query's own the same number, and `bt[nc]` is the page - * after the sequence's last -- which the KV manager leaves -1, so a partial page could never be - * wrongly appended. Mid-CHUNK both of those stop being true at once: the sequence's count runs to - * the end of the chunk while the query's runs to the query, and the page the query sits in is a - * live one with LATER TOKENS OF THE SAME CHUNK in it. A selection that appended it and set - * `seqused` past the query would attend to its own future, which is not a wrong ranking -- it is - * a model that cheats, and it would show up as an implausibly good prefill and nothing else. + * At decode the sequence's complete-block count equals the query's and `bt[nc]` is -1. Mid-chunk, + * the sequence's count runs to the chunk's end while the query's runs to the query, and the query's + * page holds later tokens of the same chunk; appending it with `seqused` past the query would let + * the query attend to its own future (an implausibly good prefill). * - * So the two things checked here are the per-query bound `n = min(nc[seq], (pos+1)/ratio)` and the - * rule that the partial page exists exactly when `(pos + 1) % ratio != 0`. + * Checked: the per-query bound `n = min(nc[seq], (pos+1)/ratio)`, and that the partial page exists + * exactly when `(pos + 1) % ratio != 0`. */ static void qsa_select_prefill_case(const Plugin& pl) { const char* what = "qsa_select at prefill: per-query bound and the partial-page rule"; @@ -10135,9 +9586,8 @@ static void qsa_select_prefill_case(const Plugin& pl) { if (!r) { ok(what, false, "row absent"); return; } const int64_t S = 2, nb = 96, topk = 5, pages = 512, ratio = 4; - /* Two chunks of different lengths over two histories, which is the ragged case the engine - * actually builds -- and it makes a query's row index and its position different numbers, so - * a kernel that confused them fails here rather than agreeing by accident. */ + /* Two chunks of different lengths over two histories, as the engine builds them, so a query's + * row index and position differ. */ const int64_t q0 = 9, q1 = 14, M = q0 + q1; const int64_t base[2] = { 137, 4 }; /* each sequence's first position in the chunk */ @@ -10146,19 +9596,19 @@ static void qsa_select_prefill_case(const Plugin& pl) { for (int64_t i = 0; i < q0; ++i) pos[(size_t)i] = (int32_t)(base[0] + i); for (int64_t i = 0; i < q1; ++i) pos[(size_t)(q0 + i)] = (int32_t)(base[1] + i); - /* `nc` is the SEQUENCE's count after the chunk: every block the chunk's last token completed. */ + /* `nc` is the sequence's count after the chunk: every block its last token completed. */ std::vector nc((size_t)S); nc[0] = (int32_t)((base[0] + q0) / ratio); nc[1] = (int32_t)((base[1] + q1) / ratio); - /* The table and the scores are per SEQUENCE and are the same for every query in it -- which is - * the whole point: the queries differ only in how much of the row they may see. */ + /* The table and scores are per sequence, the same for every query in it; queries differ only + * in how much of the row they may see. */ std::vector sc((size_t)(M * nb), 0.0f); std::vector bt((size_t)(S * nb), -1); for (int64_t s = 0; s < S; ++s) for (int64_t b = 0; b < nb; ++b) - /* Live up to and including the block the chunk's last token is IN, so `bt[n]` is a - * real page for every query that has a partial one. */ + /* Live up to the block containing the chunk's last token, so `bt[n]` is a real page + * for every query with a partial one. */ bt[(size_t)(s * nb + b)] = b <= (base[s] + (s == 0 ? q0 : q1) - 1) / ratio ? (int32_t)((b * 29 + s * 7) % pages) : -1; @@ -10244,8 +9694,8 @@ static void qsa_select_prefill_case(const Plugin& pl) { const int32_t want_su = want_n == 0 ? 0 : (int32_t)((want_n - 1) * ratio + (p % ratio) + 1); if (gs[(size_t)m] != want_su) su_ok = false; - /* THE PREDICATE THAT MATTERS: the flat KV the attention will walk is `nsel` pages of - * `ratio`, and `seqused` must not reach past the query's own token in the last one. */ + /* The flat KV is `nsel` pages of `ratio`; `seqused` must not reach past the query's own + * token in the last one. */ if (want_n > 0 && gs[(size_t)m] > (int32_t)((want_n - 1) * ratio + (p % ratio) + 1)) future_ok = false; } @@ -10260,12 +9710,11 @@ static void qsa_select_prefill_case(const Plugin& pl) { " varied=" + (varied ? "1" : "0")); } -/* qsa_select's WIDE-LAUNCH FORM against its single-workgroup form, byte for byte: the table, the - * count and seqused. Two sequences, a hundred and twenty queries, each bounded by its own position - * so some select from fewer blocks than topk; dead pages and -inf scores scattered through the - * history; and five score distributions -- continuous, coarse with heavy ties, two packed into a - * single first-digit bin, one small enough for the LDS list and one past it, which is the form's - * fallback, and fine ties, where the sampled form's list is short and ends in a tie. */ +/* qsa_select's wide-launch form against its single-workgroup form, byte for byte: table, count + * and seqused. Two sequences, 120 queries each bounded by its own position (some below topk), dead + * pages and -inf scores scattered through the history, and five score distributions: continuous; + * coarse with heavy ties; two packed into one first-digit bin, one fitting the LDS list and one + * past it (the fallback); and fine ties, where the sampled list is short and ends in a tie. */ static void qsa_select_wide_case(const Plugin& pl) { const RadKernelInfo* r = find(pl, "qsa_select_i32"); if (!r || !pl.pin_qsel) { ok("qsa_select wide form", false, "row or hook absent"); return; } @@ -10295,13 +9744,13 @@ static void qsa_select_wide_case(const Plugin& pl) { switch (dist) { case 0: v = (float)(u % 1000003) / 1000.0f; break; case 1: v = (float)(u % 23) * 0.25f; break; - /* 1.0 to 1.06 is one bin of the first digit, whose bins are 1/16 of an octave; - * a few thousand of those sit in it, then the whole history. */ + /* 1.0 to 1.06 is one first-digit bin (1/16 of an octave); a few thousand scores + * fall in it. */ case 2: v = (u % 8 == 0) ? 1.0f + (float)(u % 60000) * 1e-6f : (float)(u % 1000) / 2000.0f; break; case 3: v = 1.0f + (float)(u % 60000) * 1e-6f; break; - /* ~5000 distinct scores a few times each: the sampled form's list is short and - * the threshold is a tie, which is the case its emit has to place exactly. */ + /* ~5000 distinct scores, a few times each: the sampled list is short and the + * threshold is a tie. */ default: v = (float)(u % 4999) * 0.01f; break; } } @@ -10357,32 +9806,26 @@ static void qsa_select_wide_case(const Plugin& pl) { } } -/* qsa_select WITH THE BLOCK LIST SPLIT ACROSS THE DEVICE, against the same launch unsplit. +/* qsa_select with the block list split across the device, against the same launch unsplit. * - * WHY IT SPLITS. One workgroup a query is 6% of the device and the whole of the kernel at length, - * so the launcher cuts the list into chunks, takes each chunk's own top-k, and merges -- which is - * exact because a chunk's local top-k contains every global top-k member of that chunk (the proof - * is above the split in r4d_qsa_select_bf16.hip). "Exact" here means BIT-IDENTICAL, not equivalent: - * the selection decides which keys the attention reads, so a set that differed by one block on a - * tie would be a different model. + * One workgroup per query uses 6% of the device, so the launcher splits the block list into + * chunks, takes each chunk's top-k and merges. That is exact because a chunk's local top-k holds + * every global top-k member in it (proof above the split in r4d_qsa_select_bf16.hip), and the + * result must be bit-identical. * - * THE TWO FORMS ARE THE SAME LAUNCH WITH AND WITHOUT SCRATCH, which is what makes this a test of - * the split rather than of a second oracle: the launcher falls back to the single-workgroup kernel - * when the arena is absent, so withholding it selects that form. A fixture that never crossed the - * chunk threshold would pass while testing nothing, so `nb` is over four thousand -- and the - * scores are drawn from a SMALL SET so that ties are everywhere, because the tie rule (lowest - * block index first, by prefix count) is the part a split can get wrong without being obviously - * wrong. */ + * The two forms are the same launch with and without scratch: without the arena the launcher falls + * back to the single-workgroup kernel. `nb` is over four thousand so the chunk threshold is + * crossed, and the scores come from a small set so ties (lowest block index first, by prefix + * count) are everywhere. */ static void qsa_select_split_one(const Plugin& pl, const char* what, int64_t S, int64_t per) { const RadKernelInfo* r = find(pl, "qsa_select_i32"); if (!r) { ok(what, false, "row absent"); return; } const int64_t M = S * per, nb = 20001, topk = 512, ratio = 4, pages = 8192; std::vector sc((size_t)(M * nb)); - /* ONE TABLE A SEQUENCE AND A DIFFERENT LIVE COUNT ON EACH, because the chunk pass reads both - * off the SEQUENCE while its grid is indexed by the QUERY -- a fixture with one sequence would - * never catch a `seq` that came from the wrong side of that join. At decode a sequence - * contributes exactly `1 + n_spec` query rows, which is what `per` is. */ + /* One table per sequence with different live counts: the chunk pass reads both per sequence + * while its grid is indexed by query. `per` is a sequence's query rows (`1 + n_spec` at + * decode). */ std::vector bt((size_t)(S * nb)), nc((size_t)S), pos((size_t)M), cuh((size_t)(S + 1)); const int64_t n = 19000; @@ -10397,8 +9840,7 @@ static void qsa_select_split_one(const Plugin& pl, const char* what, int64_t S, pos[(size_t)(s * per + j)] = (int32_t)(ns * ratio + j - 2); } cuh[(size_t)S] = (int32_t)M; - /* Only 96 distinct scores over 19000 blocks, so the threshold bin is thousands deep and the - * answer is decided by the tie rule rather than by the radix. */ + /* Only 96 distinct scores over 19000 blocks, so the tie rule decides the answer. */ for (int64_t m = 0; m < M; ++m) for (int64_t b = 0; b < nb; ++b) sc[(size_t)(m * nb + b)] = (float)(((b * 31 + m * 17) % 96)) * 0.125f; @@ -10452,14 +9894,12 @@ static void qsa_select_split_one(const Plugin& pl, const char* what, int64_t S, st_memcpy(su[pass].data(), d_su, su[pass].size() * 4, hipMemcpyDeviceToHost); } - /* THE TWO RUNS HAVE TO HAVE TAKEN DIFFERENT FORMS. Without the scratch hook the launcher takes - * the fallback in both, and three identical runs would then prove nothing at all. */ + /* The runs must take different forms: without the scratch hook all would be the fallback. */ const bool split_ran = need > 0; const bool same = se[0] == se[2] && ns[0] == ns[2] && su[0] == su[2]; const bool det = se[0] == se[1] && ns[0] == ns[1] && su[0] == su[1]; - /* A SET COMPARISON BESIDE THE BYTE ONE, because the two fail for different reasons: a wrong - * SET is a wrong selection, and a right set in a different ORDER is a table the attention sums - * in another order -- different text, same model. Reporting them apart is what says which. */ + /* A set comparison beside the byte one: a wrong set is a wrong selection, while a right set in + * another order changes only the attention's summation order. */ bool set_ok = true; long slots = 0; long long first = -1; @@ -10487,18 +9927,179 @@ static void qsa_select_split_one(const Plugin& pl, const char* what, int64_t S, " same=" + (same ? "1" : "0") + " det=" + (det ? "1" : "0")); } +/* qsa_select over more than topk blocks with topk or fewer live, in every form, against libref's + * rule byte for byte: the table (sentinel-filled before each launch, so a slot the kernel leaves + * alone shows), the count and seqused. + * + * With topk or fewer live (dead pages, -inf scores), every live block is taken in block order and + * the count says how many. The radix's first digit is the only one that sees every live key; a + * later digit run on too few would narrow into bin 0, where a score of exactly zero lives, and + * tie on it. Each row below is one way in: + * 0 few live pages, continuous scores 1 few live, most of them scoring zero or less + * 2 live pages, most scores -inf 3 exactly topk live, a third tied at zero + * 4 all live keys in the first chunk, more than topk, ties at the threshold (the split merge + * sees exactly topk candidates and must still put the ties last) + * 5 nothing live 6 at most topk blocks (control) + * 7 everything live (control) + * -0.0 scores are planted in rows 1 and 4: libref ranks them as zero. */ +static void qsa_select_few_live_case(const Plugin& pl) { + const char* what = "qsa_select with topk or fewer live blocks, every form vs libref's rule"; + const RadKernelInfo* r = find(pl, "qsa_select_i32"); + if (!r || !pl.pin_qsel) { ok(what, false, "row or hook absent"); return; } + + const int64_t S = 8, M = S, nb = 9000, topk = 512, ratio = 4, pages = 1 << 20; + const int64_t nrow[S] = { 8000, 8000, 8000, 8000, 2000, 8000, 300, 8000 }; + std::vector sc((size_t)(M * nb), -INFINITY); + std::vector bt((size_t)(S * nb), -1), nc((size_t)S), pos((size_t)M), + cuh((size_t)(S + 1)); + uint64_t x = 0x9E3779B97F4A7C15ull; + auto rnd = [&]() { x ^= x << 13; x ^= x >> 7; x ^= x << 17; return x; }; + for (int64_t s = 0; s < S; ++s) { + const int64_t n = nrow[s]; + nc[(size_t)s] = (int32_t)n; + cuh[(size_t)s] = (int32_t)s; + pos[(size_t)s] = (int32_t)(n * ratio + (s % 3)); /* mid-block: a partial page */ + for (int64_t b = 0; b < n; ++b) { + float* v = &sc[(size_t)(s * nb + b)]; + int32_t* pg = &bt[(size_t)(s * nb + b)]; + const uint64_t u = rnd(); + const float cont = (float)(u % 1000003) / 1000.0f + 0.001f; + *pg = (int32_t)(u % pages); + switch (s) { + case 0: if (b % 80 != 3) *pg = -1; *v = cont; break; /* 100 live */ + /* 400 live, three in four scoring zero or less: more zeros than the slots the + * live keys leave, so a radix that kept narrowing past the first digit would + * find a "threshold" among them. */ + case 1: if (b % 20 != 7) *pg = -1; + *v = (b / 20) % 4 == 0 ? cont + : (b / 20) % 3 == 0 ? -2.5f : (b / 20) % 3 == 1 ? -0.0f : 0.0f; + break; + case 2: *v = (b % 40 == 1) ? cont : -INFINITY; break; /* 200 live */ + case 3: if (b % 15 != 2 || b >= 15 * 512) *pg = -1; /* 512 live */ + *v = (b % 45 == 2) ? 0.0f : cont; break; + case 4: *v = (b % 7 == 0) ? cont : (b % 2 ? 0.0f : -0.0f); break; + case 5: *pg = -1; *v = cont; break; + case 6: if (b % 9 == 4) *pg = -1; *v = (float)(u % 13) * 0.5f; break; + default: *v = cont; break; + } + } + bt[(size_t)(s * nb + n)] = (s % 2 == 0) ? (int32_t)(rnd() % pages) : -1; /* the tail */ + } + cuh[(size_t)S] = (int32_t)M; + + /* libref's rule (ref_qsa_select): every live block when topk or fewer are live, else the + * blocks above the topk-th largest value in block order, then its ties in block order. */ + std::vector want((size_t)(M * (topk + 1)), -1), want_n((size_t)M), want_su((size_t)M); + for (int64_t m = 0; m < M; ++m) { + const int64_t n = nrow[m]; + std::vector live; + std::vector val((size_t)n, 0.0f); + for (int64_t b = 0; b < n; ++b) { + const float v = sc[(size_t)(m * nb + b)]; + if (bt[(size_t)(m * nb + b)] < 0 || !(v > -1e30f)) continue; + val[(size_t)b] = v > 0.0f ? v : 0.0f; + live.push_back(b); + } + std::vector take; + if ((int64_t)live.size() <= topk) { + take = live; + } else { + std::vector ord; + for (int64_t b : live) ord.push_back(val[(size_t)b]); + std::nth_element(ord.begin(), ord.begin() + (topk - 1), ord.end(), + [](float l, float r) { return l > r; }); + const float thr = ord[(size_t)(topk - 1)]; + for (int64_t b : live) if (val[(size_t)b] > thr) take.push_back(b); + for (int64_t b : live) + if ((int64_t)take.size() < topk && val[(size_t)b] == thr) take.push_back(b); + } + int32_t* row = &want[(size_t)(m * (topk + 1))]; + int64_t out = 0; + for (int64_t b : take) row[out++] = bt[(size_t)(m * nb + b)]; + const int32_t part = (n < nb && (pos[(size_t)m] + 1) % ratio != 0) + ? bt[(size_t)(m * nb + n)] : -1; + if (part >= 0) row[out++] = part; + want_n[(size_t)m] = (int32_t)out; + want_su[(size_t)m] = out == 0 ? 0 + : (int32_t)((out - 1) * ratio + pos[(size_t)m] % ratio + 1); + } + + void* d_sc = dalloc(sc.size() * 4); + void* d_bt = dalloc(bt.size() * 4); + void* d_nc = dalloc(nc.size() * 4); + void* d_po = dalloc(pos.size() * 4); + void* d_cu = dalloc(cuh.size() * 4); + void* d_se = dalloc((size_t)(M * (topk + 1)) * 4); + void* d_ns = dalloc((size_t)M * 4); + void* d_su = dalloc((size_t)M * 4); + if (!d_sc || !d_bt || !d_nc || !d_po || !d_cu || !d_se || !d_ns || !d_su) { + ok(what, false, "alloc failed"); return; + } + st_memcpy(d_sc, sc.data(), sc.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_bt, bt.data(), bt.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_nc, nc.data(), nc.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_po, pos.data(), pos.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_cu, cuh.data(), cuh.size() * 4, hipMemcpyHostToDevice); + std::vector ts = { + T(d_sc, RAD_F32, { M, nb }), T(d_bt, RAD_I32, { S, nb }), T(d_nc, RAD_I32, { S }), + T(d_po, RAD_I32, { M }), T(d_cu, RAD_I32, { S + 1 }), + T(d_se, RAD_I32, { M, topk + 1 }), T(d_ns, RAD_I32, { M }), T(d_su, RAD_I32, { M }) }; + std::vector ps = { PI("M", M), PI("blocks", nb), PI("topk", topk), + PI("ratio", ratio), PI("seqs", S) }; + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.t = ts.data(); a.n_t = (int)ts.size(); + a.p = ps.data(); a.n_p = (int)ps.size(); + const int64_t need = r->scratch ? r->scratch(&a) : 0; + void* d_sk = need > 0 ? dalloc((size_t)need) : nullptr; + if (need <= 0 || !d_sk) { ok(what, false, "the split path's scratch is unavailable"); return; } + + static const char* const kForm[] = { "single workgroup", "wide", "split" }; + for (int f = 0; f < 3; ++f) { + a.scratch = f == 2 ? d_sk : nullptr; + a.scratch_bytes = f == 2 ? need : 0; + st_memset(d_se, 0x55, (size_t)(M * (topk + 1)) * 4); + st_memset(d_ns, 0x55, (size_t)M * 4); + st_memset(d_su, 0x55, (size_t)M * 4); + pl.pin_qsel(f == 2 ? 0 : f + 1); + const int rc = r->launch(&a, nullptr); + pl.pin_qsel(0); + if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) { + ok(fmt("%s: the %s form is served", what, kForm[f]).c_str(), false, fmt("rc=%d", rc)); + continue; + } + std::vector se((size_t)(M * (topk + 1))), ns((size_t)M), su((size_t)M); + st_memcpy(se.data(), d_se, se.size() * 4, hipMemcpyDeviceToHost); + st_memcpy(ns.data(), d_ns, ns.size() * 4, hipMemcpyDeviceToHost); + st_memcpy(su.data(), d_su, su.size() * 4, hipMemcpyDeviceToHost); + std::string bad; + for (int64_t m = 0; m < M; ++m) { + int64_t diff = 0, first = -1; + for (int64_t i = 0; i <= topk; ++i) + if (se[(size_t)(m * (topk + 1) + i)] != want[(size_t)(m * (topk + 1) + i)]) { + ++diff; + if (first < 0) first = i; + } + if (diff || ns[(size_t)m] != want_n[(size_t)m] || su[(size_t)m] != want_su[(size_t)m]) + bad += fmt(" row %lld: nsel %d (want %d), %lld slot(s) differ from %lld;", + (long long)m, ns[(size_t)m], want_n[(size_t)m], (long long)diff, + (long long)first); + } + ok(fmt("%s: the %s form", what, kForm[f]).c_str(), bad.empty(), + bad.empty() ? std::string("8 rows exact") : bad); + } +} + /* qsa_score, against an f64 evaluation of the same formula. * - * TWO CONTROLS, AND BOTH ARE ORDERING MISTAKES A READER MAKES rather than transcription slips. + * Two controls: * - * sum-then-relu instead of relu-then-sum. Arithmetically it is one line either way and both - * rank blocks plausibly; it is a different model. Measured here at a rel_l2 of order one. + * sum-then-relu instead of relu-then-sum: both rank blocks plausibly, but it is a different + * model (rel_l2 of order one). * - * a padded table entry scoring ZERO instead of -inf. A real score can be zero -- every head - * vetoed the block -- so this is the mistake that makes padding outrank a block the model - * deliberately ignored, and it is invisible in the scores themselves. The case checks the - * padding lanes directly rather than through an l2, because an l2 over a mostly-live row - * drowns them. + * a padded entry scoring zero instead of -inf: a real score can be zero, so padding would + * outrank blocks every head rejected. The padding lanes are checked directly, since an l2 over + * a mostly live row would hide them. */ static void qsa_score_case(const Plugin& pl) { const char* what = "qsa_score vs an f64 evaluation of the same formula"; @@ -10513,8 +10114,8 @@ static void qsa_score_case(const Plugin& pl) { qh[(size_t)i] = h_to_bf16((float)(((i * 29 + 7) % 83) - 41) / 47.0f); for (int64_t i = 0; i < pages * n; ++i) bkh[(size_t)i] = h_to_bf16((float)(((i * 41 + 13) % 71) - 35) / 39.0f); - /* A scattered table with real padding at the end of every row, which is what a sequence - * shorter than the declared width actually produces. */ + /* A scattered table with padding at the end of every row, as a sequence shorter than the + * declared width produces. */ for (int64_t m = 0; m < M; ++m) { const int64_t live = nb - 3 - m * 4; for (int64_t b = 0; b < nb; ++b) @@ -10533,7 +10134,7 @@ static void qsa_score_case(const Plugin& pl) { for (int64_t j = 0; j < n; ++j) d += (double)h_bf16(qh[(size_t)((m * heads + h) * n + j)]) * (double)h_bf16(bkh[(size_t)(p * n + j)]); - s += d > 0.0 ? d : 0.0; /* relu per (block, head), THEN the head sum */ + s += d > 0.0 ? d : 0.0; /* relu per (block, head), then the head sum */ raw += d; /* the control: sum first, clamp after */ } const double inv = 1.0 / std::sqrt((double)n); @@ -10541,10 +10142,8 @@ static void qsa_score_case(const Plugin& pl) { sumrelu[(size_t)(m * nb + b)] = (raw > 0.0 ? raw : 0.0) * inv; } - /* ONE QUERY A SEQUENCE, which is the decode shape and makes `seq(m) == m` -- so the oracle - * above, which treats `m` as the sequence, describes what the kernel computes. The - * prefill shape (many queries over one history) is qsa_select_prefill_case's job, because it - * is the SELECTION that has to bound each query separately. */ + /* One query per sequence (decode shape, `seq(m) == m`), as the oracle assumes. Many queries + * per history are covered by qsa_score_rows_case and qsa_select_prefill_case. */ std::vector cuh((size_t)(M + 1)), nch((size_t)M, (int32_t)nb); for (int64_t i = 0; i <= M; ++i) cuh[(size_t)i] = (int32_t)i; @@ -10583,8 +10182,7 @@ static void qsa_score_case(const Plugin& pl) { std::vector got((size_t)(M * nb)); st_memcpy(got.data(), d_o, got.size() * 4, hipMemcpyDeviceToHost); - /* The l2 is over the LIVE entries only; the padding is checked as a predicate, because an l2 - * that mixed -inf with real scores is not a number. */ + /* The l2 covers live entries only; the padding (-inf) is checked as a predicate. */ auto rel = [&](const std::vector& ref) { double num = 0.0, den = 0.0; for (size_t i = 0; i < ref.size(); ++i) { @@ -10607,14 +10205,12 @@ static void qsa_score_case(const Plugin& pl) { ", padding " + std::to_string(pad_ninf) + "/" + std::to_string(pad)); } -/* qsa_score over SEQUENCES OF MANY ROWS, against the same f64 formula. +/* qsa_score over sequences of many rows, against the same f64 formula. * - * The case above is one row a sequence, the decode shape. A prefill chunk is many rows over one - * history, and in a mixed step the chunk sits beside other sequences' decode rows, so a 16-row - * query tile can hold the end of one sequence and the start of the next. Rows {7, 20, 5}: the - * second sequence starts inside the first tile and ends inside the second, and each sequence has - * its own table row with its own padding and its own live count. The control is scoring every row - * against sequence 0's table -- what a tile that forgot to split at the boundary would do. */ + * In a mixed step a 16-row query tile can hold the end of one sequence and the start of the next. + * Rows {7, 20, 5}: the second sequence starts inside the first tile and ends inside the second, + * and each sequence has its own table row, padding and live count. The control scores every row + * against sequence 0's table, as a tile that ignored the boundary would. */ static void qsa_score_rows_case(const Plugin& pl) { const char* what = "qsa_score, three sequences of 7, 20 and 5 rows, vs f64"; const RadKernelInfo* r = find(pl, "qsa_score_bf16"); @@ -10634,7 +10230,7 @@ static void qsa_score_rows_case(const Plugin& pl) { std::vector bth((size_t)(S * nb)); for (int64_t sq = 0; sq < S; ++sq) { const int64_t live = nb - 2 - sq * 9; - nch[(size_t)sq] = (int32_t)(live - 1); /* one table entry past the live count */ + nch[(size_t)sq] = (int32_t)(live - 1); /* the table has one entry past nc */ for (int64_t b = 0; b < nb; ++b) bth[(size_t)(sq * nb + b)] = b < live && (b % 11) != 4 ? (int32_t)((b * 17 + sq * 7) % pages) : -1; @@ -10665,7 +10261,7 @@ static void qsa_score_rows_case(const Plugin& pl) { st_memcpy(d_bt, bth.data(), bth.size() * 4, hipMemcpyHostToDevice); st_memcpy(d_cu, cuh.data(), cuh.size() * 4, hipMemcpyHostToDevice); st_memcpy(d_nc, nch.data(), nch.size() * 4, hipMemcpyHostToDevice); - /* A sentinel in every entry, so a store past a sequence's live count is caught. */ + /* A sentinel in every entry catches a store past a sequence's live count. */ std::vector sentinel((size_t)(M * nb), 12345.0f); st_memcpy(d_o, sentinel.data(), sentinel.size() * 4, hipMemcpyHostToDevice); @@ -10712,16 +10308,13 @@ static void qsa_score_rows_case(const Plugin& pl) { /* qsa_block_key, against an f64 evaluation of the same formula. * - * THE ROUNDING POINT IS THE PART WORTH TESTING. The reference pools in f32 and rounds to bf16 - * BEFORE the norm reads it; carrying f32 straight through is the convenient order and a different - * number. So this builds BOTH oracles and reports how far apart they are, which is what says the - * decision is load-bearing rather than pedantry -- and then checks the kernel against the right - * one. + * The reference pools in f32 and rounds to bf16 before the norm; carrying f32 through gives a + * different number. Both oracles are built and their distance reported, and the kernel is checked + * against the rounding one. * - * The negative control is the POSITION. `pos0` off by the ratio rotates every block key by one - * block's worth of angle, which is the mistake a reader makes when they take the position of the - * block's LAST token instead of its first, and it is invisible in magnitude: the vectors stay the - * same length and point somewhere else. rel_l2 is what sees it. */ + * The negative control is the position: `pos0` off by the ratio (the block's last token instead of + * its first) rotates every key by one block's angle, invisible in magnitude but caught by + * rel_l2. */ static void qsa_block_key_case(const Plugin& pl) { const char* what = "qsa_block_key vs an f64 evaluation of the same formula"; const RadKernelInfo* r = find(pl, "qsa_block_key_bf16"); @@ -10735,12 +10328,12 @@ static void qsa_block_key_case(const Plugin& pl) { for (int64_t i = 0; i < M * ratio; ++i) for (int64_t d = 0; d < n; ++d) { float v = (float)(((i * 37 + d * 11) % 97) - 48) / 53.0f; - if (d % 31 == 0) v *= 5.0f; /* outlier channels, as a real key has */ + if (d % 31 == 0) v *= 5.0f; /* outlier channels, as in a real key */ kh[(size_t)(i * n + d)] = h_to_bf16(v); } for (int64_t d = 0; d < n; ++d) wh[(size_t)d] = 0.1f + (float)((d * 7) % 13) / 40.0f; - /* `round_mean` false is the convenient order the reference does NOT take. */ + /* `round_mean` false is the order the reference does not take. */ auto oracle = [&](bool round_mean, int64_t p0, std::vector* out) { out->assign((size_t)(M * n), 0.0); std::vector v((size_t)n); @@ -10786,9 +10379,8 @@ static void qsa_block_key_case(const Plugin& pl) { st_memcpy(d_k, kh.data(), kh.size() * 2, hipMemcpyHostToDevice); st_memcpy(d_w, wh.data(), wh.size() * 4, hipMemcpyHostToDevice); - /* `page` ABSENT, which is one entry with a null pointer and NOT a shorter list -- operands are - * positional, so a three-entry list would hand `out` to `page` and the shim would refuse. The - * scattered form is the pass below. */ + /* `page` absent: an entry with a null pointer, not a shorter list (operands are positional). + * The scattered form is the pass below. */ std::vector ts = { T(d_k, RAD_BF16, { M * ratio, n }), T(d_w, RAD_F32, { n }), @@ -10812,11 +10404,9 @@ static void qsa_block_key_case(const Plugin& pl) { std::vector got((size_t)(M * n)); st_memcpy(got.data(), d_o, got.size() * 2, hipMemcpyDeviceToHost); - /* THE SCATTERED FORM, which is the one the engine uses: a page list sends block b to page - * `pg[b]` of a store as tall as the POOL, and a -1 says the block has no page and must not be - * written anywhere. Same arithmetic, so the same oracle holds -- what is under test is that - * the destination moved and the block count came off the PAGE LIST and not off `out`, which - * is taller than the launch. */ + /* The scattered form the engine uses: a page list sends block b to page `pg[b]` of a store as + * tall as the pool, and -1 means no page (nothing written). Same oracle; under test are the + * destination and that the block count comes from the page list, not from the taller `out`. */ const int64_t store = M * 3 + 11; std::vector pg((size_t)M); for (int64_t b = 0; b < M; ++b) @@ -10851,17 +10441,14 @@ static void qsa_block_key_case(const Plugin& pl) { for (int64_t b = 0; b < M; ++b) if (pg[(size_t)b] == (int32_t)p) named = true; if (!named && got2[(size_t)(p * n)] == h_to_bf16(-7.0f)) ++untouched; } - /* Every page nothing named must still hold the fill, INCLUDING the one the -1 block would have - * landed on if the guard were missing. */ + /* Every unnamed page must still hold the fill, including where the -1 block would land if the + * guard were missing. */ const bool scatter_clean = scatter_ok && untouched == store - (M - 1); - /* THE WORK-LIST FORM. `pos` given, the same positions the tiling would have produced but - * handed over one at a time and in a SHUFFLED block order -- which is what a decode step - * looks like, where the blocks completing in one launch belong to different sequences. The - * answer for block b must be the answer the tiled form gave for whichever block holds those - * positions, so the fixture permutes the POSITIONS and checks against the permuted oracle. - * Reading the same keys at a different position is the exact mistake this catches, and the - * pos0 control above shows it is worth 5.8e-01 of error. */ + /* The work-list form: `pos` given per block in shuffled order, as at decode, where the blocks + * completing in one launch belong to different sequences. The positions are permuted and each + * block is checked against the oracle at its permuted position, catching keys read at the wrong + * position. */ std::vector bpos((size_t)M); std::vector perm((size_t)M); for (int64_t b = 0; b < M; ++b) perm[(size_t)b] = (b * 5 + 2) % M; @@ -10884,8 +10471,8 @@ static void qsa_block_key_case(const Plugin& pl) { std::vector got3((size_t)(M * n)); st_memcpy(got3.data(), d_o3, got3.size() * 2, hipMemcpyDeviceToHost); { - /* Block b read rows [b*ratio, (b+1)*ratio) as before -- only the ANGLE moved -- so the - * oracle is the one built at the permuted position for the same keys. */ + /* Block b reads rows [b*ratio, (b+1)*ratio) as before and only the angle moves, so the + * oracle is built at the permuted position for the same keys. */ std::vector wantp; oracle(true, pos0, &wantp); /* shape only; recomputed per block below */ for (int64_t b = 0; b < M && list_ok; ++b) { @@ -10900,11 +10487,10 @@ static void qsa_block_key_case(const Plugin& pl) { } } - /* UNDER M-RoPE: `mode` imrope with Qwen3.8's sections, and each block's three components - * side by side in a [M, 3] view of a buffer with a row pitch of 4 -- so a kernel that took - * the view as dense reads the wrong block's components. Frequency i reads H when i % 3 == 1 - * and i < 33, W when i % 3 == 2 and i < 30, and T otherwise; every component differs, so a - * frequency that read the wrong one is off by at least one position's angle. */ + /* Under M-RoPE: `mode` imrope with Qwen3.8's sections, each block's three components in an + * [M, 3] view of a buffer with row pitch 4 (a dense reading picks the wrong block). Frequency i + * reads H when i % 3 == 1 and i < 33, W when i % 3 == 2 and i < 30, T otherwise; the components + * all differ, so a wrong component shows. */ const int64_t pitch = 4; std::vector b4((size_t)(M * pitch), -1); for (int64_t b = 0; b < M; ++b) { @@ -10937,8 +10523,8 @@ static void qsa_block_key_case(const Plugin& pl) { st_memcpy(got4.data(), d_o4, got4.size() * 2, hipMemcpyDeviceToHost); double mr_num = 0.0, mr_den = 0.0, mr_t = 0.0; for (int64_t b = 0; b < M && mrope_ok; ++b) { - /* The one-component oracle at each component's position, and per frequency the one the - * interleave names. */ + /* The one-component oracle at each component's position; per frequency, the interleave + * picks one. */ std::vector oc[3]; for (int c = 0; c < 3; ++c) { std::vector full; @@ -10957,8 +10543,8 @@ static void qsa_block_key_case(const Plugin& pl) { } const double r_mr = mr_den > 0.0 ? std::sqrt(mr_num / mr_den) : -1.0; const double r_mr_t = mr_den > 0.0 ? std::sqrt(mr_t / mr_den) : -1.0; - /* The same buffer's FIRST COLUMN, as a text-only step hands it: the one-component form, - * which must be the tiled answer bit for bit, since column 0 holds exactly the tiling. */ + /* The same buffer's first column, as a text-only step passes it: must equal the tiled answer + * bit for bit, since column 0 holds the tiling. */ RadTensor b1v = T(d_b4, RAD_I32, { M, 1 }); b1v.stride[0] = pitch; ts4[3] = b1v; @@ -10986,19 +10572,11 @@ static void qsa_block_key_case(const Plugin& pl) { sep = den > 0.0 ? std::sqrt(sep / den) : -1.0; const double r_ok = rel(want), r_shift = rel(shifted), r_unr = rel(unrounded); - /* 0.01 is the bf16 STORE and nothing tighter is available: the output is bf16, so a correct - * kernel lands within the grid's own spacing of the exact answer -- 1.7e-03 measured, against - * 2^-9 = 2.0e-03 of grid. Two controls give that bar its meaning. - * - * The POSITION control is the loud one: off by one block it measures 5.8e-01, three hundred - * times worse, because a wrong rope angle leaves the vector's length alone and only moves - * where it points. - * - * The ROUNDING control is the quiet one and it is the reason this case exists. The kernel - * must be closer to the order that rounds the pooled mean to bf16 before the norm than to the - * order that does not -- 1.68e-03 against 2.27e-03, a 35% separation out of two numbers only - * 1.6e-03 apart. It is not much, and it is the whole discrimination available at a bf16 - * output; a kernel that took the convenient order fails here and nowhere else. */ + /* 0.01 reflects the bf16 output: a correct kernel lands within the grid spacing (2^-9) of the + * exact answer. The position control (off by one block) must be over 20x worse. The rounding + * control is subtle: the kernel must be closer to the oracle that rounds the pooled mean to + * bf16 before the norm than to the one that does not; the two differ by only ~35%, the only + * discrimination a bf16 output allows. */ const bool pass = r_ok >= 0.0 && r_ok < 0.01 && r_shift > 20.0 * r_ok && r_unr > 0.0 && r_ok < 0.9 * r_unr && scatter_clean && list_ok && mrope_ok; std::printf(" rel_l2 vs f64: %.3e (unrounded-mean order %.3e, the two orders %.3e " @@ -11060,20 +10638,15 @@ static void qsa_block_key_yarn_case(const Plugin& pl) { /* gram_accum, against an f64 host Gram of the same dequantised bytes. * - * THE THING THIS IS ACTUALLY FOR IS THE ACCUMULATE. A kernel that stored instead of adding would - * agree with any single-call oracle and be wrong on the second launch, which is the only way this - * op is ever used -- a corpus is many launches into one buffer. So `h` is SEEDED with a non-zero - * pattern and the kernel is launched TWICE, and the expectation is seed + 2*want. Either mistake - * -- storing, or dropping the seed -- fails; neither would fail a zero-seeded single call. + * The accumulate is what matters: a corpus is many launches into one buffer. So `h` is seeded with + * a non-zero pattern and the kernel launched twice; the expectation is seed + 2*want, which a + * kernel that stores, or drops the seed, fails. * - * The activation goes through the DEVICE quantiser rather than being synthesised, so the case also - * pins the two ops' scale convention to each other: gram_accum reads `scale` as a DEQUANT - * multiplier, and reading it the other way would be a factor of 448^2 on every entry. + * The activation goes through the device quantiser, pinning the two ops' scale convention: + * gram_accum reads `scale` as a dequant multiplier (the other reading is off by 448^2). * - * K = 260 is deliberate and is three awkward things at once: not a multiple of the 64-wide output - * tile (the last tile has four live columns of sixty-four), not a multiple of the 128-wide scale - * group (the last group has four), and a multiple of four (the staging dword). A square K would - * have exercised none of the masking. */ + * K = 260 is not a multiple of the 64-wide output tile (four live columns in the last) or of the + * 128-wide scale group (four in the last), but is a multiple of four (the staging dword). */ static void gram_accum_case(const Plugin& pl) { const char* what = "gram_accum vs an f64 host Gram of the same bytes, accumulated twice"; const RadKernelInfo* g = find(pl, "gram_accum"); @@ -11086,7 +10659,7 @@ static void gram_accum_case(const Plugin& pl) { for (int64_t m = 0; m < M; ++m) for (int64_t k = 0; k < K; ++k) { float v = (float)(((m * 29 + k * 11) % 53) - 26) / 41.0f; - if (k % 23 == 0) v *= 6.0f; /* outlier channels, so the scales differ by group */ + if (k % 23 == 0) v *= 6.0f; /* outliers, so the scales differ by group */ xbf[(size_t)(m * K + k)] = h_to_bf16(v); } @@ -11111,9 +10684,7 @@ static void gram_accum_case(const Plugin& pl) { st_stream_sync(nullptr); if (qrc != RAD_OK) { ok(what, false, "quantiser rc=" + std::to_string(qrc)); return; } - /* Read the codes back and build the oracle from THEM, not from the bf16 source: the kernel - * contracts the codes, and an oracle that quantised again on the host would be measuring the - * quantiser as well as the Gram. */ + /* The oracle uses the codes read back, not the bf16 source, so only the Gram is measured. */ std::vector qc((size_t)(M * K)); std::vector qsc((size_t)(M * kb)); st_memcpy(qc.data(), d_q, qc.size(), hipMemcpyDeviceToHost); @@ -11167,8 +10738,8 @@ static void gram_accum_case(const Plugin& pl) { if (r > worst) worst = r; } const double rel = den > 0.0 ? std::sqrt(num / den) : -1.0; - /* f32 accumulation over 200 rows in a register tree against f64: 1e-5 is three orders of - * margin on what that costs, and four below anything the consumer's damping would notice. */ + /* f32 accumulation over 200 rows against f64: 1e-5 leaves three orders of margin, well below + * what the consumer's damping would notice. */ const bool pass = rel >= 0.0 && rel < 1e-5; std::printf(" rel_l2 %.3e, worst entry %.3e\n", rel, worst); ok(what, pass, "rel_l2 " + std::to_string(rel) + ", worst " + std::to_string(worst)); @@ -11176,14 +10747,12 @@ static void gram_accum_case(const Plugin& pl) { /* gram_accum at bf16, against an f64 host Gram of the same bf16 values. * - * The fp8 case above holds the accumulate to a seeded buffer and two launches; this one does the - * same for the form with no scale operand, and adds the property the consumer leans on hardest: a - * Gram is SYMMETRIC, and GPTQ's Cholesky takes the matrix as symmetric without looking. Each entry - * and its mirror are the same products summed in the same row order by two different blocks, so - * the kernel's output has to be symmetric to the bit, not to a tolerance. + * The same seeded two-launch accumulate for the form with no scale operand, plus symmetry: GPTQ's + * Cholesky assumes it, and each entry and its mirror are the same products summed in the same row + * order by two blocks, so the output must be symmetric to the bit. * - * Two shapes: K = 260 for the masking (see the fp8 case) and an M that is not a whole number of - * staged row blocks, and the routed down projection's width at a pass of sorted rows. */ + * Shapes: K = 260 for the masking (see the fp8 case) with M not a whole number of staged row + * blocks, and the routed down projection's width over sorted rows. */ static void gram_accum_bf16_case(const Plugin& pl, int64_t M, int64_t K) { const std::string what = "gram_accum_bf16 vs an f64 host Gram (M=" + std::to_string(M) + ", K=" + std::to_string(K) + "), accumulated twice"; @@ -11235,7 +10804,7 @@ static void gram_accum_bf16_case(const Plugin& pl, int64_t M, int64_t K) { ok((what + ": symmetric to the bit").c_str(), asym == 0, std::to_string(asym) + " mirrored pairs differ"); - /* Seed, then two launches: seed + 2 * want, which neither a store nor a dropped seed passes. */ + /* Seed, then two launches: expect seed + 2 * want. */ std::vector seed((size_t)(K * K)); for (int64_t i = 0; i < K * K; ++i) seed[(size_t)i] = (float)((i % 17) - 8) * 0.25f; st_memcpy(d_h, seed.data(), seed.size() * 4, hipMemcpyHostToDevice); @@ -11259,31 +10828,26 @@ static void gram_accum_bf16_case(const Plugin& pl, int64_t M, int64_t K) { ok(what.c_str(), rel >= 0.0 && rel < 1e-5, "rel_l2 " + std::to_string(rel) + ", worst " + std::to_string(worst)); - /* A scale handed to the bf16 form is a caller that thinks the input is quantised: refused. */ + /* A scale handed to the bf16 form is refused. */ ts[1] = T(d_h, RAD_F32, { M, 1 }); rc = g->launch(&a, nullptr); ok((what + ": refuses a scale operand").c_str(), rc != RAD_OK, "rc=" + std::to_string(rc)); dfree_all(); } -/* THE bf16 GROUPED MoE GEMM, AGAINST A HOST PRODUCT, EVERY FORM AGAINST EVERY OTHER. +/* The bf16 grouped MoE GEMM against a host product, every form against every other. * - * The routing is SKEWED the way moe_perf's is -- lognormal popularity, a Gumbel top-k a token -- so - * runs go from empty to several times the mean, and the last few sorted rows are dropped slots - * (sorted -1, past the live count) whose output must be zeros and not the stale bytes the output - * is seeded with. Every form the launcher has -- the run-aligned prefill form, the (tile, run) - * decode form and the uniform prefill grid -- runs on the same bytes and must match the first - * byte for byte: each output element is one wave's accumulation over K in one order whichever - * block computes it, so a byte apart is a form reading a different row or expert. + * The routing is skewed as in moe_perf (lognormal popularity, Gumbel top-k), and the last sorted + * rows are dropped slots (-1, past the live count) whose output must be zeros, not the seeded + * stale bytes. Every launcher form runs on the same bytes and must match the first byte for byte: + * each element is one wave's accumulation over K in one order, whichever block computes it. * - * THE WEIGHTS ARE ALSO HANDED AS A POINTER TABLE, which is what the engine hands the kernel, with - * the experts laid out in a PERMUTED order behind it where the shape is small enough to keep two - * copies: an entry the kernel addressed by arithmetic instead of through the table would then read - * another expert's plane. + * The weights are also passed as a pointer table, as the engine does, with the experts in permuted + * order behind it where two copies fit, so an entry addressed by arithmetic rather than through + * the table reads another expert. * - * THE NEGATIVE CONTROL is the down projection with `a_order` swapped to "token": the activation - * still has a row per (token, slot), so the launch is legal and gathers the wrong rows, and the - * comparison has to fail. A harness that passes it has stopped looking at the numbers. */ + * Negative control: the down projection with `a_order` swapped to "token" is legal but gathers the + * wrong rows, and must fail the comparison. */ struct MoeBf16Shape { const char* name; int64_t N, K, ne, top_k; bool srt; }; static void moe_gemm_bf16_case(const Plugin& pl, int64_t Mtok, const MoeBf16Shape& sh, @@ -11302,8 +10866,8 @@ static void moe_gemm_bf16_case(const Plugin& pl, int64_t Mtok, const MoeBf16Shap auto rnd = [&]() { rs ^= rs << 13; rs ^= rs >> 7; rs ^= rs << 17; return rs; }; auto unif = [&]() { return ((double)(rnd() >> 11) + 0.5) * (1.0 / 9007199254740992.0); }; - /* The routing: every token's top_k distinct experts, then a stable sort by expert. The last - * three tokens' slots are left out of the sort as dropped slots. */ + /* Each token's top_k distinct experts, then a stable sort by expert; the last three tokens' + * slots are dropped. */ std::vector logp((size_t)E); for (int64_t e = 0; e < E; ++e) logp[(size_t)e] = 1.0 * std::sqrt(-2.0 * std::log(unif())) * std::cos(6.283185307 * unif()); @@ -11332,19 +10896,19 @@ static void moe_gemm_bf16_case(const Plugin& pl, int64_t Mtok, const MoeBf16Shap } const int64_t live = off[(size_t)E]; sorted.resize((size_t)Tr, -1); - /* A CALL SERVING A TRAILING SEGMENT -- a layer's protected experts, sorted last -- is handed the - * offsets from that segment's first expert on and that segment's weights, and every row below - * the segment is another call's output: it must keep the seeded bytes exactly. */ + /* A call serving a trailing segment (a layer's protected experts, sorted last) gets the + * offsets from the segment's first expert and its weights; rows below the segment belong to + * another call and must keep the seeded bytes. */ const int64_t e0 = seg ? E - seg : 0, En = seg ? seg : E; const int64_t s0 = off[(size_t)e0]; - /* The activation: one row a token, or one a (token, slot) for the down projection. */ + /* The activation: one row per token, or per (token, slot) for the down projection. */ const int64_t AR = sh.srt ? Tr : Mtok; std::vector ah((size_t)(AR * K)), wh((size_t)(E * N * K)); for (auto& v : ah) v = h_to_bf16((float)((double)(int64_t)(rnd() % 2001) - 1000.0) / 700.0f); for (auto& v : wh) v = h_to_bf16((float)((double)(int64_t)(rnd() % 2001) - 1000.0) / 9000.0f); - /* The reference, every output element, in f64 over the bf16 inputs exactly. */ + /* The reference for every output element, in f64 over the exact bf16 inputs. */ std::vector ref((size_t)(Tr * N), 0.0); for (int64_t i = 0; i < live; ++i) { const int32_t f = sorted[(size_t)i]; @@ -11361,8 +10925,8 @@ static void moe_gemm_bf16_case(const Plugin& pl, int64_t Mtok, const MoeBf16Shap } } - /* Two copies of the weights where they are small: the stacked plane in expert order, and a - * permuted one the pointer table reads. One copy otherwise, and the table points into it. */ + /* Where small, two weight copies: the stacked plane in expert order and a permuted one for the + * pointer table. Otherwise one copy, which the table points into. */ const size_t eb = (size_t)(N * K) * 2; const bool permute = E * (int64_t)eb <= ((int64_t)16 << 20); void* d_w = dalloc((size_t)E * eb); @@ -11453,14 +11017,13 @@ static void moe_gemm_bf16_case(const Plugin& pl, int64_t Mtok, const MoeBf16Shap } const double want = ref[(size_t)(i * N + n)]; const double gf = (double)h_bf16(got[(size_t)(i * N + n)]); - /* Half a bf16 ulp of the output, plus room for a K-term f32 sum taken in the - * WMMA's order; NaN counts as a miss. `rel_max` is the worst element as a - * fraction of that allowance, printed so a margin shows and not only a pass. */ + /* Half a bf16 ulp plus room for a K-term f32 sum in the WMMA's order; NaN is a + * miss. `rel_max`, the worst element as a fraction of that, is printed. */ const double err = std::fabs(gf - want); const double tol = 0.004 * std::fabs(want) + 2e-3; if (err / tol > rel_max) rel_max = err / tol; - /* ...and in bf16 ulps from the f64 product rounded once, on the - * sign-magnitude ordering of the bits. */ + /* And in bf16 ulps from the once-rounded f64 product, on the sign-magnitude + * ordering of the bits. */ { const uint16_t rb = h_to_bf16((float)want), gb = got[(size_t)(i * N + n)]; const int32_t ro = (rb & 0x8000) ? -(int32_t)(rb & 0x7fff) : (int32_t)rb; @@ -11505,14 +11068,13 @@ static void moe_gemm_bf16_case(const Plugin& pl, int64_t Mtok, const MoeBf16Shap dfree_all(); } -/* THE bf16 EXPERT GEMM AT A PREFILL CHUNK: Qwen3.8-Flash-Next's whole experts (gate_up 1280 x 2560 +/* The bf16 expert GEMM at a prefill chunk: Qwen3.8-Flash-Next's whole experts (gate_up 1280 x 2560 * over token rows, down 2560 x 640 over sorted rows) under a skewed routing, every form timed and * compared with the first byte for byte. * - * `distinct` planes back the `experts` table entries, entry e reading plane e % distinct. Equal to - * `experts` it is the real weight traffic; smaller, it is what fits beside a running server, and - * the time is then the kernel's arithmetic and staging over planes the last-level cache can hold -- - * a floor on the real figure rather than the figure, and the line printed says which it was. */ + * `distinct` planes back the table entries (entry e reads plane e % distinct). Equal to `experts` + * it is the real weight traffic; smaller, the planes may sit in the last-level cache and the time + * is a floor, as the printed line says. */ static void moe16_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E, int64_t top_k, int64_t distinct) { if (iters <= 0) iters = 20; @@ -11644,11 +11206,11 @@ struct ArThread { void* inst = nullptr; int rc_init = RAD_E_STATE, rc_launch = RAD_E_STATE; std::vector out; - /* The all-gather row width in ELEMENTS. 0 is the plain concatenation; anything else asks for - * the row-interleaved placement the vocab-parallel sampler needs. */ + /* The all-gather row width in elements: 0 is plain concatenation, otherwise the + * row-interleaved placement the vocab-parallel sampler needs. */ int64_t row_elems = 0; - /* Ranks in the collective. 2 is the pair; 3 exercises the wide family at the one width that - * is not a power of two. */ + /* Ranks in the collective: 2, or 3 for the wide family at a width that is not a power of + * two. */ int world = 2; }; @@ -11690,8 +11252,8 @@ static void ar_two_rank(const Plugin& pl, const std::vector& devs, const ch if (!row) { ok(name, false, "row absent"); return; } if (devs.size() < 2) { skip(name, "fewer than two gfx1201 cards"); return; } - /* 8192 fp32 elements: a whole number of 16-byte pushes and small enough that the handshake, - * not the link, is what is being exercised. */ + /* 8192 fp32 elements: whole 16-byte pushes, small enough to exercise the handshake rather + * than the link. */ const int64_t numel = 8192; ArThread a{ row, 0, devs[0], numel }, b{ row, 1, devs[1], numel }; std::thread ta(ar_worker, &a), tb(ar_worker, &b); @@ -11719,19 +11281,17 @@ static void ar_two_rank(const Plugin& pl, const std::vector& devs, const ch } /* ------------------------------------------------------------------ changing block counts */ -/* BACK-TO-BACK ALL-REDUCES ON ONE INSTANCE, AT DIFFERENT BLOCK COUNTS. The block count follows the - * message, so the ops sharing an instance run different grids, and consecutive launches must still - * take opposite scratch slots as a whole: a slot taken per block lets a block of one launch push - * into bytes a different block of the previous launch is still reducing (r4d_ar_seq.h). Nothing - * synchronises between the launches here, and each has its own values and its own output, so a - * slot two in-flight launches share reads as a wrong sum and a counter the kernels disagree on as - * a hang. The sizes give 11, 4 and 7 blocks under the default block rule. */ +/* Back-to-back all-reduces on one instance at different block counts. The block count follows the + * message, so ops sharing an instance run different grids, and consecutive launches must alternate + * scratch slots as a whole (per-block slots would let one launch push into bytes the previous one + * is still reducing; r4d_ar_seq.h). Nothing synchronises between launches and each has its own + * values and output, so a shared slot shows as a wrong sum and a counter mismatch as a hang. The + * sizes give 11, 4 and 7 blocks under the default block rule. */ static const int64_t kArSweepNumel[] = { 65536, 8192, 40000, 65536, 12000, 24576, 65536, 8192 }; constexpr int kArSweepN = (int)(sizeof(kArSweepNumel) / sizeof(kArSweepNumel[0])); -/* The sweep again and again with new values each round, so every slot is reused many times over. - * A reader that is served a slot's previous contents -- a cached line of host memory or of a - * peer's, a flag seen before the bytes behind it -- folds the value of an earlier launch, and every - * launch's value is distinct, so that is a wrong sum and not a lucky one. */ +/* Rounds of the sweep with new values each, so every slot is reused many times; a reader served a + * slot's previous contents (a stale cached line, a flag seen before its bytes) yields a wrong sum, + * since every launch's value is distinct. */ constexpr int kArSweepRounds = 32; struct ArSweep { @@ -11819,11 +11379,10 @@ static void ar_two_rank_sweep(const Plugin& pl, const std::vector& devs, co } /* ------------------------------------------------------------------ the two-rank all-gather */ -/* The payload is what the vocab-parallel sampler really gathers: (u32 global token id, f32 logit) - * pairs. THE IDS ARE THE POINT. A token id is a small integer, and its bit pattern read as f32 is - * a DENORMAL -- so an all-gather faked as an all-reduce over zero-padded planes returns the ids - * flushed to zero anywhere denormals are flushed, and the model then samples token 0 forever while - * every logit still looks right. This checks the bytes, on both ranks, for both halves. */ +/* 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 + * over zero-padded planes would flush ids to zero where denormals flush. This checks the bytes on + * both ranks, for both halves. */ static void gather_worker(ArThread* t) { if (st_set_device(t->dev) != hipSuccess) { t->rc_init = RAD_E_DEVICE; return; } std::vector ps = { @@ -11845,7 +11404,7 @@ static void gather_worker(ArThread* t) { std::memcpy(&h[(size_t)i + 1], &v, 4); } st_memcpy(in, h.data(), h.size() * 4, hipMemcpyHostToDevice); - st_memset(out, 0xAB, (size_t)t->numel * 4 * t->world); /* so an untouched slice is visibly untouched */ + st_memset(out, 0xAB, (size_t)t->numel * 4 * t->world); /* marks untouched slices */ RadTensor ts[2] = { T(in, RAD_F32, { t->numel }), T(out, RAD_F32, { t->numel * t->world }) }; RadArgs a; @@ -11883,8 +11442,7 @@ static void gather_two_rank(const Plugin& pl, const std::vector& devs, cons a.rc_launch == RAD_OK && b.rc_launch == RAD_OK, "rc " + std::to_string(a.rc_launch) + "/" + std::to_string(b.rc_launch)); - /* What each rank sent, rebuilt here rather than read back off the device: the check is that - * the OUTPUT holds it, so the expectation must not come from the same memory. */ + /* What each rank sent, rebuilt on the host rather than read from the device. */ auto sent = [numel](int rank, int64_t i) -> uint32_t { if ((i & 1) == 0) return (uint32_t)(rank * 124160 + (int)i + 1); uint32_t u; const float v = (float)(rank + 1) * 0.5f + (float)(i - 1); @@ -11908,11 +11466,9 @@ static void gather_two_rank(const Plugin& pl, const std::vector& devs, cons if (row->fini) { row->fini(a.inst); row->fini(b.inst); } - /* THE ROW-INTERLEAVED PLACEMENT, which is the one the sampler actually asks for: the input is - * [rows][row] and the output must be [rows][2][row], so rank 1's row m sits immediately after - * rank 0's rather than a whole message away. A concatenating gather passes the check above and - * fails this one, and the difference between them is a merge that reads one rank's candidates - * twice and the other rank's never. */ + /* The row-interleaved placement the sampler uses: input [rows][row], output [rows][2][row], + * rank 1's row m directly after rank 0's. A concatenating gather passes the check above and + * fails this one. */ const int64_t rowe = 2048; /* 4 rows of 1024 (id, logit) pairs */ ArThread c{ row, 0, devs[0], numel }, d{ row, 1, devs[1], numel }; c.row_elems = d.row_elems = rowe; @@ -11948,83 +11504,81 @@ static void gather_two_rank(const Plugin& pl, const std::vector& devs, cons ok("2-rank all-gather fini ran", true); } -/* ------------------------------------------------------------------ the three-rank wide family */ -/* THE ONE WIDTH THAT IS NOT A POWER OF TWO. The wide kernels are templated on the world size and - * shipped at 4 and 8; three cards instantiate the same template at 3, and these are the checks that - * the instantiation, the dispatch rows and the entry points agree: a rendezvous of three, a sum of - * 1 + 2 + 3 on every rank bit for bit, the slot parity surviving a block-count sweep, and the - * gather placing three slices in both of its layouts. Skipped, not failed, on fewer cards. */ -static void ar_three_rank(const Plugin& pl, const std::vector& devs, const char* name) { +/* ------------------------------------------------------------------ the wide (3/4/8-rank) family */ +/* The wide kernels are templated on the world size; these cases run them at 3 and 4 ranks (4 is + * the TP4 width). Checked: a rendezvous of `world`, a sum of 1 + 2 + .. + world on every rank bit + * for bit, slot parity surviving a block-count sweep, and the gather placing every slice in both + * layouts. Skipped on fewer cards than the width, with the width named in the skip. */ +static void ar_wide_rank(const Plugin& pl, const std::vector& devs, const char* name, + int world) { const RadKernelInfo* row = find(pl, name); if (!row) { ok(name, false, "row absent"); return; } - if (devs.size() < 3) { skip(name, "fewer than three gfx1201 cards"); return; } - const int64_t numel = 8192; - ArThread a{ row, 0, devs[0], numel }, b{ row, 1, devs[1], numel }, c{ row, 2, devs[2], numel }; - a.world = b.world = c.world = 3; - std::thread ta(ar_worker, &a), tb(ar_worker, &b), tc(ar_worker, &c); - ta.join(); - tb.join(); - tc.join(); - ok("3-rank all-reduce init (peer rendezvous)", - a.rc_init == RAD_OK && b.rc_init == RAD_OK && c.rc_init == RAD_OK, - "rc " + std::to_string(a.rc_init) + "/" + std::to_string(b.rc_init) + "/" + - std::to_string(c.rc_init)); - if (a.rc_init != RAD_OK || b.rc_init != RAD_OK || c.rc_init != RAD_OK) return; - ok("3-rank all-reduce launch", - a.rc_launch == RAD_OK && b.rc_launch == RAD_OK && c.rc_launch == RAD_OK, - "rc " + std::to_string(a.rc_launch) + "/" + std::to_string(b.rc_launch) + "/" + - std::to_string(c.rc_launch)); - int64_t bad = 0; - for (int64_t i = 0; i < numel; ++i) { - if (a.out[(size_t)i] != 6.0f) ++bad; - if (b.out[(size_t)i] != 6.0f) ++bad; - if (c.out[(size_t)i] != 6.0f) ++bad; + if ((int)devs.size() < world) { + skip(name, (std::string("needs ") + std::to_string(world) + " gfx1201 cards").c_str()); + return; } - ok("3-rank all-reduce sums 1 + 2 + 3 == 6 on every rank, bit for bit", bad == 0, + const int64_t numel = 8192; + const std::string w = std::to_string(world); + std::vector t; + std::vector th; + for (int r = 0; r < world; ++r) t.push_back(ArThread{ row, r, devs[(size_t)r], numel }); + for (int r = 0; r < world; ++r) { t[(size_t)r].world = world; th.emplace_back(ar_worker, &t[(size_t)r]); } + for (std::thread& x : th) x.join(); + bool up = true; + std::string rcs; + for (const ArThread& a : t) { up = up && a.rc_init == RAD_OK; rcs += std::to_string(a.rc_init) + "/"; } + ok((w + "-rank all-reduce init (peer rendezvous)").c_str(), up, rcs); + if (!up) return; + up = true; rcs.clear(); + for (const ArThread& a : t) { up = up && a.rc_launch == RAD_OK; rcs += std::to_string(a.rc_launch) + "/"; } + ok((w + "-rank all-reduce launch").c_str(), up, rcs); + /* Rank r contributes (r + 1), so the fold is the triangular number -- 6 at three, 10 at four. */ + const float want = (float)(world * (world + 1) / 2); + int64_t bad = 0; + for (const ArThread& a : t) + for (int64_t i = 0; i < numel; ++i) if (a.out[(size_t)i] != want) ++bad; + ok((w + "-rank all-reduce sums 1 + 2 + .. + " + w + " == " + std::to_string((int)want) + + " on every rank, bit for bit").c_str(), bad == 0, std::to_string(bad) + " elements wrong"); - if (row->fini) { row->fini(a.inst); row->fini(b.inst); row->fini(c.inst); } - ok("3-rank all-reduce fini ran", true); + if (row->fini) for (ArThread& a : t) row->fini(a.inst); + ok((w + "-rank all-reduce fini ran").c_str(), true); /* Block counts that change launch to launch on one instance: the wide family takes its slot * parity from the shared counters exactly as the pair does, and this is the check that it - * does so at a width whose flag array is [block][3]. */ - ArSweep x{ row, 0, devs[0] }, y{ row, 1, devs[1] }, z{ row, 2, devs[2] }; - x.world = y.world = z.world = 3; - std::thread tx(ar_sweep_worker, &x), ty(ar_sweep_worker, &y), tz(ar_sweep_worker, &z); - tx.join(); - ty.join(); - tz.join(); - const bool up = x.rc_init == RAD_OK && y.rc_init == RAD_OK && z.rc_init == RAD_OK && - x.rc_launch == RAD_OK && y.rc_launch == RAD_OK && z.rc_launch == RAD_OK; - ok("3-rank all-reduce, 32 rounds of eight launches at changing block counts on one instance", - up && x.bad == 0 && y.bad == 0 && z.bad == 0, - up ? std::to_string(x.bad + y.bad + z.bad) + " elements wrong" - : "rc " + std::to_string(x.rc_init) + "/" + std::to_string(y.rc_init) + "/" + - std::to_string(z.rc_init) + " init, " + std::to_string(x.rc_launch) + "/" + - std::to_string(y.rc_launch) + "/" + std::to_string(z.rc_launch) + " launch"); - if (row->fini) { - if (x.inst) row->fini(x.inst); - if (y.inst) row->fini(y.inst); - if (z.inst) row->fini(z.inst); + * does so at a width whose flag array is [block][world]. */ + std::vector s; + std::vector sh2; + for (int r = 0; r < world; ++r) s.push_back(ArSweep{ row, r, devs[(size_t)r] }); + for (int r = 0; r < world; ++r) { s[(size_t)r].world = world; sh2.emplace_back(ar_sweep_worker, &s[(size_t)r]); } + for (std::thread& x : sh2) x.join(); + up = true; rcs.clear(); + int64_t bad2 = 0; + for (const ArSweep& a : s) { + up = up && a.rc_init == RAD_OK && a.rc_launch == RAD_OK; + bad2 += a.bad; + rcs += std::to_string(a.rc_init) + "/" + std::to_string(a.rc_launch) + " "; } + ok((w + "-rank all-reduce, 32 rounds of eight launches at changing block counts on one " + "instance").c_str(), + up && bad2 == 0, + up ? std::to_string(bad2) + " elements wrong" : "init/launch rc " + rcs); + if (row->fini) for (ArSweep& a : s) if (a.inst) row->fini(a.inst); } -/* THE THREE-RANK ALL-REDUCE ROWS, at the sizes the two-shot is selected for and the ones that do - * not divide. +/* The three-rank all-reduce rows, at the sizes that select the two-shot and sizes that do not + * divide. * - * ar_three_rank's input is a constant per rank, which a shard landing at the wrong offset still - * sums correctly. This one gives every element its own value, so a word reduced by the wrong - * owner, gathered from the wrong slot or dropped at a short shard's end is a wrong number at a - * known index. The sizes walk the uneven split: words % 3 of 0, 1 and 2, from a 16-word message - * to past the old 20971520 ceiling, in place (how every block issues it) and once out of - * place, back to back on ONE instance so the slot parity and the changing block count are - * exercised the way a step's mixed messages exercise them. The oracle is the fold the kernel - * claims -- fp32 in ascending rank order, rounded once -- so it is bit for bit, and so it is also - * the one-shot's answer: the band edge between the two rows changes no bits. */ + * Every element has its own value, so a word reduced by the wrong owner, gathered from the wrong + * slot or dropped at a short shard's end shows at a known index. The sizes walk the uneven split + * (words % 3 of 0, 1 and 2) from 16 words to past 20971520, in place and once out of place, back + * to back on one instance (slot parity, changing block counts). The oracle is the kernel's fold: + * fp32 in ascending rank order, rounded once, bit for bit; it is also the one-shot's answer, so + * the band edge between the rows changes no bits. */ struct ArPattern { - const RadKernelInfo* row; - int rank, dev; - const char* dtype; /* "bf16" or "fp32" */ + const RadKernelInfo* row = nullptr; + int rank = 0, dev = 0; + int world = 3; + const char* dtype = nullptr; /* "bf16" or "fp32" */ std::vector sizes; int out_of_place = -1; /* index into sizes, or -1 */ void* inst = nullptr; @@ -12033,8 +11587,8 @@ struct ArPattern { }; static float ar_pattern_value(int rank, int64_t i) { - /* Integers up to 254 over 64: exact in bf16 (8 significant bits), and three of them need ten, - * so the bf16 sum is rounded and the rounding is checked too. */ + /* Integers up to 254 over 64: exact in bf16 (8 significant bits), while sums of three need + * ten, so the bf16 sum's rounding is checked too. */ return (float)((int)((i * 37 + (int64_t)rank * 101) % 509) - 254) / 64.0f; } @@ -12045,9 +11599,9 @@ static void ar_pattern_worker(ArPattern* t) { int64_t most = 0; for (int64_t n : t->sizes) most = n > most ? n : most; std::vector ps = { - PI("world_size", 3), PI("numel", most), PS("dtype", t->dtype), PI("exact", 1), + PI("world_size", t->world), PI("numel", most), PS("dtype", t->dtype), PI("exact", 1), }; - t->rc_init = t->row->init(ps.data(), (int)ps.size(), t->rank, 3, &t->inst); + t->rc_init = t->row->init(ps.data(), (int)ps.size(), t->rank, t->world, &t->inst); if (t->rc_init != RAD_OK) return; void* in = nullptr; void* out = nullptr; @@ -12072,7 +11626,7 @@ static void ar_pattern_worker(ArPattern* t) { a.p = ps.data(); a.n_p = (int)ps.size(); a.instance = t->inst; a.rank = t->rank; - a.world_size = 3; + a.world_size = t->world; const int rc = t->row->launch(&a, nullptr); st_stream_sync(nullptr); if (rc != RAD_OK && t->rc_launch == RAD_OK) t->rc_launch = rc; @@ -12088,38 +11642,60 @@ static void ar_pattern_worker(ArPattern* t) { st_free(out); } -static void ar_three_rank_pattern(const Plugin& pl, const std::vector& devs, const char* name) { +static void ar_wide_pattern(const Plugin& pl, const std::vector& devs, const char* name, + int world) { const RadKernelInfo* row = find(pl, name); if (!row) { ok(name, false, "row absent"); return; } - if (devs.size() < 3) { skip(name, "fewer than three gfx1201 cards"); return; } + if ((int)devs.size() < world) { + skip(name, (std::string("needs ") + std::to_string(world) + " gfx1201 cards").c_str()); + return; + } struct Run { const char* dtype; std::vector sizes; int oop; }; - const std::vector runs = { - /* bf16, the residual: words = numel / 8. 2048 x 2048 rows is words % 3 == 2, x 2049 is - * 0, x 2050 is 1; 128 is 16 words (1), 24008 is 3001 (1); 20971520 the old ceiling (1); - * 46137344, Gemma 4's feed-forward reduce at an 8192-token chunk, past it (1). */ - { "bf16", { 4194304, 128, 4196352, 24008, 4198400, 20971520, 46137344, 4194304 }, 2 }, - /* fp32: words = numel / 4. 8196 -> 2049 (0), 4100 -> 1025 (2), 1048580 -> 262145 (2). */ - { "fp32", { 8196, 4100, 1048580 }, 0 }, - }; + /* The three-rank list walks the UNEVEN split (words % 3 of 0, 1 and 2); the four-rank rows + * cannot be given one -- cArTsExact4/cArTi8Ts4 constrain numel so the words divide evenly + * (r4d_rows.cpp), and the two-shot's own entry refuses any other message -- so its list keeps + * the whole-word sizes and the band edges instead. */ + std::vector runs; + if (world == 3) { + runs = { + /* bf16, the residual: words = numel / 8. 2048 x 2048 rows is words % 3 == 2, x 2049 is + * 0, x 2050 is 1; 128 is 16 words (1), 24008 is 3001 (1); 20971520 the old ceiling + * (1); 46137344, Gemma 4's feed-forward reduce at an 8192-token chunk, past it (1). */ + { "bf16", { 4194304, 128, 4196352, 24008, 4198400, 20971520, 46137344, 4194304 }, 2 }, + /* fp32: words = numel / 4. 8196 -> 2049 (0), 4100 -> 1025 (2), 1048580 -> 262145 (2). */ + { "fp32", { 8196, 4100, 1048580 }, 0 }, + }; + } else { + runs = { + /* bf16: 524288 the one-shot band's top, 524352 the first message the two-shot's rows + * take (numel % 64 == 0 either way, so both divide); the shipped chunk sizes; and + * 4194304 again to close the run on a size already folded. */ + { "bf16", { 4194304, 128, 524288, 524352, 4196352, 20971520, 46137344, 4194304 }, 2 }, + /* fp32: words = numel / 4, whole groups of four either side of the same edge. */ + { "fp32", { 1048580 - 4, 524352 }, 0 }, + }; + } for (const Run& run : runs) { - ArPattern t[3]; - for (int r = 0; r < 3; ++r) { - t[r].row = row; t[r].rank = r; t[r].dev = devs[(size_t)r]; - t[r].dtype = run.dtype; t[r].sizes = run.sizes; t[r].out_of_place = run.oop; + std::vector t((size_t)world); + std::vector th; + for (int r = 0; r < world; ++r) { + t[(size_t)r].row = row; t[(size_t)r].rank = r; t[(size_t)r].dev = devs[(size_t)r]; + t[(size_t)r].world = world; + t[(size_t)r].dtype = run.dtype; t[(size_t)r].sizes = run.sizes; + t[(size_t)r].out_of_place = run.oop; + th.emplace_back(ar_pattern_worker, &t[(size_t)r]); } - std::thread a(ar_pattern_worker, &t[0]), b(ar_pattern_worker, &t[1]), c(ar_pattern_worker, &t[2]); - a.join(); b.join(); c.join(); + for (std::thread& x : th) x.join(); const std::string what = std::string(name) + " " + run.dtype; - const bool up = t[0].rc_init == RAD_OK && t[1].rc_init == RAD_OK && t[2].rc_init == RAD_OK; - ok((what + " init (peer rendezvous)").c_str(), up, - "rc " + std::to_string(t[0].rc_init) + "/" + std::to_string(t[1].rc_init) + "/" + - std::to_string(t[2].rc_init)); + bool up = true, ran = true; + std::string rcs; + for (const ArPattern& a : t) { + up = up && a.rc_init == RAD_OK; ran = ran && a.rc_launch == RAD_OK; + rcs += std::to_string(a.rc_init) + "/" + std::to_string(a.rc_launch) + " "; + } + ok((what + " init (peer rendezvous)").c_str(), up, "init/launch rc " + rcs); if (!up) return; - const bool ran = t[0].rc_launch == RAD_OK && t[1].rc_launch == RAD_OK && - t[2].rc_launch == RAD_OK; - ok((what + " launches").c_str(), ran, - "rc " + std::to_string(t[0].rc_launch) + "/" + std::to_string(t[1].rc_launch) + "/" + - std::to_string(t[2].rc_launch)); + ok((what + " launches").c_str(), ran, "init/launch rc " + rcs); if (ran) { const bool bf = !std::strcmp(run.dtype, "bf16"); for (size_t k = 0; k < run.sizes.size(); ++k) { @@ -12127,13 +11703,13 @@ static void ar_three_rank_pattern(const Plugin& pl, const std::vector& devs int64_t bad = 0, first = -1; for (int64_t i = 0; i < n; ++i) { float acc = 0.0f; - for (int r = 0; r < 3; ++r) { + for (int r = 0; r < world; ++r) { const float v = ar_pattern_value(r, i); acc += bf ? h_bf16(h_to_bf16(v)) : v; } const float want = bf ? h_bf16(h_to_bf16(acc)) : acc; - for (int r = 0; r < 3; ++r) - if (t[r].out.size() <= k || t[r].out[k][(size_t)i] != want) { + for (int r = 0; r < world; ++r) + if (t[(size_t)r].out.size() <= k || t[(size_t)r].out[k][(size_t)i] != want) { if (first < 0) first = i; ++bad; } @@ -12141,31 +11717,54 @@ static void ar_three_rank_pattern(const Plugin& pl, const std::vector& devs const int64_t words = n * (bf ? 2 : 4) / 16; const std::string label = what + " numel " + std::to_string(n) + " (" + std::to_string(words) + - " words, % 3 = " + std::to_string(words % 3) + + " words, % " + std::to_string(world) + " = " + + std::to_string(words % world) + ((int)k == run.oop ? ", out of place" : ", in place") + ") == fp32 ascending-rank fold on every rank, bit for bit"; ok(label.c_str(), bad == 0, std::to_string(bad) + " elements wrong, first at " + std::to_string(first)); } } - if (row->fini) for (int r = 0; r < 3; ++r) if (t[r].inst) row->fini(t[r].inst); + if (row->fini) for (ArPattern& a : t) if (a.inst) row->fini(a.inst); + } + /* The four-rank rows' even-shard rule, checked from the one place that can: a message whose + * 16-byte words do not divide by four must be REFUSED (r4d_ar_twoshot_Nrank_exact.hip shards + * it evenly and the entry throws on any residual), not launched with a truncated tail. The + * three-rank row has no such rule -- it splits unevenly by design. */ + if (world == 4 && std::strstr(name, "twoshot")) { + ArPattern t[4]; + for (int r = 0; r < 4; ++r) { + t[r].row = row; t[r].rank = r; t[r].dev = devs[(size_t)r]; t[r].world = 4; + t[r].dtype = "bf16"; t[r].sizes = { 524288, 40 }; /* 40 elems = 5 words: 5 % 4 != 0 */ + t[r].out_of_place = 1; + } + std::thread a(ar_pattern_worker, &t[0]), b(ar_pattern_worker, &t[1]), + c(ar_pattern_worker, &t[2]), d(ar_pattern_worker, &t[3]); + a.join(); b.join(); c.join(); d.join(); + int refused = 0; + for (const ArPattern& x : t) { + if (x.rc_init == RAD_OK && x.rc_launch == RAD_E_SHAPE) ++refused; + if (x.inst) row->fini(x.inst); + } + ok((std::string(name) + " refuses a 5-word message at 4 ranks (RAD_E_SHAPE, not a launch)").c_str(), + refused == 4, + std::to_string(refused) + " of 4 ranks refused, rc " + std::to_string(t[0].rc_launch)); } } -/* THE THREE-RANK TIERED-INT8 WIRE, held to what a lossy wire can be held to. +/* The three-rank tiered-int8 wire. * - * Exactly: every rank ends with the same bytes (the owner stores the decode of the words it - * published, so the wire is bit-identical across ranks by construction), and a message the wire - * declines -- under `min_bytes`, or not whole 32-element groups -- is the exact one-shot's fold, - * bit for bit. Statistically: the rest is within a quantisation error of the fp32 sum. The input is - * the per-element pattern plus a large outlier every 997 elements on rank 1 (the record's tier 2 - * keeps a dominant element exact), and the sizes walk groups % 3 of 0, 1 and 2 to the 20971520 - * ceiling, so a group reduced by the wrong owner or read from the wrong slot is an error of the - * order of the values themselves -- a relative RMS near 1, not the few tenths of a percent an int8 - * wire costs. */ + * Exact: every rank ends with the same bytes (the owner stores the decode of what it published), + * and a message the wire declines (under `min_bytes`, or not whole 32-element groups) equals the + * exact one-shot's fold bit for bit. Statistical: the rest is within quantisation error of the + * fp32 sum. The input is the per-element pattern plus an outlier every 997 elements on rank 1 + * (tier 2 keeps a dominant element exact); sizes walk groups % 3 of 0, 1 and 2 up to 20971520, so + * a wrong owner or slot gives a relative RMS near 1, versus a fraction of a percent for the + * wire. */ struct ArTi8 { - const RadKernelInfo* row; - int rank, dev; + const RadKernelInfo* row = nullptr; + int rank = 0, dev = 0; + int world = 3; std::vector sizes; void* inst = nullptr; int rc_init = RAD_E_STATE, rc_launch = RAD_OK; @@ -12182,10 +11781,10 @@ static void ar_ti8_worker(ArTi8* t) { int64_t most = 0; for (int64_t n : t->sizes) most = n > most ? n : most; std::vector ps = { - PI("world_size", 3), PI("numel", most), PS("dtype", "bf16"), PI("exact", 0), + PI("world_size", t->world), PI("numel", most), PS("dtype", "bf16"), PI("exact", 0), PI("min_bytes", 131072), }; - t->rc_init = t->row->init(ps.data(), (int)ps.size(), t->rank, 3, &t->inst); + t->rc_init = t->row->init(ps.data(), (int)ps.size(), t->rank, t->world, &t->inst); if (t->rc_init != RAD_OK) return; void* buf = nullptr; if (hipMalloc(&buf, (size_t)most * 2) != hipSuccess) { t->rc_launch = RAD_E_NOMEM; return; } @@ -12200,7 +11799,7 @@ static void ar_ti8_worker(ArTi8* t) { a.p = ps.data(); a.n_p = (int)ps.size(); a.instance = t->inst; a.rank = t->rank; - a.world_size = 3; + a.world_size = t->world; const int rc = t->row->launch(&a, nullptr); st_stream_sync(nullptr); if (rc != RAD_OK && t->rc_launch == RAD_OK) t->rc_launch = rc; @@ -12211,40 +11810,53 @@ static void ar_ti8_worker(ArTi8* t) { st_free(buf); } -static void ar_three_rank_ti8(const Plugin& pl, const std::vector& devs, const char* name) { +static void ar_wide_ti8(const Plugin& pl, const std::vector& devs, const char* name, + int world) { const RadKernelInfo* row = find(pl, name); if (!row) { ok(name, false, "row absent"); return; } - if (devs.size() < 3) { skip(name, "fewer than three gfx1201 cards"); return; } - /* 32768 is under the 128 KiB floor and 65544 is not whole groups: both exact. The rest are + if ((int)devs.size() < world) { + skip(name, (std::string("needs ") + std::to_string(world) + " gfx1201 cards").c_str()); + return; + } + /* 32768 is under the 128 KiB floor and 65544 is not whole groups (at four ranks, not whole + * SHARD groups -- the 4-rank wire tiles numel by 128): both exact. The rest are * lossy: 65536 sits ON the floor (2048 groups, % 3 = 2), then 2048 x 2048 / 2049 / 2050 rows * (groups % 3 = 2, 0, 1) and the ceiling (655360 groups, % 3 = 1), and 2048 rows again. */ const std::vector sizes = { 4194304, 32768, 65536, 4196352, 65544, 4198400, 20971520, 4194304 }; - ArTi8 t[3]; - for (int r = 0; r < 3; ++r) { t[r].row = row; t[r].rank = r; t[r].dev = devs[(size_t)r]; t[r].sizes = sizes; } - std::thread a(ar_ti8_worker, &t[0]), b(ar_ti8_worker, &t[1]), c(ar_ti8_worker, &t[2]); - a.join(); b.join(); c.join(); + /* The wire's tile: at three any whole group of 32 goes lossy (the 3-rank entry only asks + * numel % 32 == 0); at four the shard must be whole groups too, so the fallback rule is + * numel % (32 * 4) == 0 (r4d_rad_ar_twoshot_4rank_ti8). */ + const int64_t tile = world == 3 ? 32 : 32 * (int64_t)world; + std::vector t((size_t)world); + std::vector th; + for (int r = 0; r < world; ++r) { + t[(size_t)r].row = row; t[(size_t)r].rank = r; t[(size_t)r].dev = devs[(size_t)r]; + t[(size_t)r].world = world; t[(size_t)r].sizes = sizes; + th.emplace_back(ar_ti8_worker, &t[(size_t)r]); + } + for (std::thread& x : th) x.join(); const std::string nm(name); - const bool up = t[0].rc_init == RAD_OK && t[1].rc_init == RAD_OK && t[2].rc_init == RAD_OK; - ok((nm + " init (peer rendezvous)").c_str(), up, - "rc " + std::to_string(t[0].rc_init) + "/" + std::to_string(t[1].rc_init) + "/" + - std::to_string(t[2].rc_init)); + bool up = true, ran = true; + std::string rcs; + for (const ArTi8& a : t) { + up = up && a.rc_init == RAD_OK; ran = ran && a.rc_launch == RAD_OK; + rcs += std::to_string(a.rc_init) + "/" + std::to_string(a.rc_launch) + " "; + } + ok((nm + " init (peer rendezvous)").c_str(), up, "init/launch rc " + rcs); if (!up) return; - const bool ran = t[0].rc_launch == RAD_OK && t[1].rc_launch == RAD_OK && t[2].rc_launch == RAD_OK; - ok((nm + " launches").c_str(), ran, - "rc " + std::to_string(t[0].rc_launch) + "/" + std::to_string(t[1].rc_launch) + "/" + - std::to_string(t[2].rc_launch)); + ok((nm + " launches").c_str(), ran, "init/launch rc " + rcs); if (ran) { for (size_t k = 0; k < sizes.size(); ++k) { const int64_t n = sizes[k]; - const bool lossy = n * 2 >= 131072 && n % 32 == 0; + const bool lossy = n * 2 >= 131072 && n % tile == 0; int64_t diff_ranks = 0, inexact = 0; double se = 0.0, sx = 0.0, worst = 0.0; for (int64_t i = 0; i < n; ++i) { const uint16_t g0 = t[0].out[k][(size_t)i]; - if (t[1].out[k][(size_t)i] != g0 || t[2].out[k][(size_t)i] != g0) ++diff_ranks; + for (int r = 1; r < world; ++r) if (t[(size_t)r].out[k][(size_t)i] != g0) ++diff_ranks; float acc = 0.0f; - for (int r = 0; r < 3; ++r) acc += h_bf16(h_to_bf16(ar_ti8_value(r, i))); + for (int r = 0; r < world; ++r) acc += h_bf16(h_to_bf16(ar_ti8_value(r, i))); const double e = (double)h_bf16(g0) - (double)acc; if (!lossy && g0 != h_to_bf16(acc)) ++inexact; se += e * e; sx += (double)acc * acc; @@ -12253,8 +11865,9 @@ static void ar_three_rank_ti8(const Plugin& pl, const std::vector& devs, co } const double rrms = sx > 0 ? std::sqrt(se / sx) : 0.0; const std::string what = nm + " numel " + std::to_string(n) + " (" + - std::to_string(n / 32) + " groups, % 3 = " + - std::to_string((n / 32) % 3) + ")"; + std::to_string(n / 32) + " groups, % " + + std::to_string(world) + " = " + + std::to_string((n / 32) % world) + ")"; ok((what + ": every rank holds the same bytes").c_str(), diff_ranks == 0, std::to_string(diff_ranks) + " elements differ between ranks"); if (!lossy) { @@ -12270,15 +11883,20 @@ static void ar_three_rank_ti8(const Plugin& pl, const std::vector& devs, co } } } - if (row->fini) for (int r = 0; r < 3; ++r) if (t[r].inst) row->fini(t[r].inst); + if (row->fini) for (ArTi8& a : t) if (a.inst) row->fini(a.inst); } -static void gather_three_rank(const Plugin& pl, const std::vector& devs, const char* name) { +static void gather_wide_rank(const Plugin& pl, const std::vector& devs, const char* name, + int world) { const RadKernelInfo* row = find(pl, name); if (!row) { ok(name, false, "row absent"); return; } - if (devs.size() < 3) { skip(name, "fewer than three gfx1201 cards"); return; } + if ((int)devs.size() < world) { + skip(name, (std::string("needs ") + std::to_string(world) + " gfx1201 cards").c_str()); + return; + } const int64_t numel = 8192; /* the sampler's own message at 4 rows and 1024 candidates */ - const int W = 3; + const int W = world; + const std::string w = std::to_string(world); /* What each rank sent, rebuilt here rather than read back off the device (gather_two_rank). */ auto sent = [](int rank, int64_t i) -> uint32_t { if ((i & 1) == 0) return (uint32_t)(rank * 124160 + (int)i + 1); @@ -12287,63 +11905,70 @@ static void gather_three_rank(const Plugin& pl, const std::vector& devs, co return u; }; { - ArThread a{ row, 0, devs[0], numel }, b{ row, 1, devs[1], numel }, c{ row, 2, devs[2], numel }; - a.world = b.world = c.world = W; - std::thread ta(gather_worker, &a), tb(gather_worker, &b), tc(gather_worker, &c); - ta.join(); - tb.join(); - tc.join(); - ok("3-rank all-gather init (peer rendezvous)", - a.rc_init == RAD_OK && b.rc_init == RAD_OK && c.rc_init == RAD_OK, - "rc " + std::to_string(a.rc_init) + "/" + std::to_string(b.rc_init) + "/" + - std::to_string(c.rc_init)); - if (a.rc_init != RAD_OK || b.rc_init != RAD_OK || c.rc_init != RAD_OK) return; - ok("3-rank all-gather launch", - a.rc_launch == RAD_OK && b.rc_launch == RAD_OK && c.rc_launch == RAD_OK, - "rc " + std::to_string(a.rc_launch) + "/" + std::to_string(b.rc_launch) + "/" + - std::to_string(c.rc_launch)); + std::vector t((size_t)W); + std::vector th; + for (int r = 0; r < W; ++r) { + t[(size_t)r] = ArThread{ row, r, devs[(size_t)r], numel }; + t[(size_t)r].world = W; + th.emplace_back(gather_worker, &t[(size_t)r]); + } + for (std::thread& x : th) x.join(); + bool up = true; + std::string rcs; + for (const ArThread& a : t) { up = up && a.rc_init == RAD_OK; rcs += std::to_string(a.rc_init) + "/"; } + ok((w + "-rank all-gather init (peer rendezvous)").c_str(), up, "rc " + rcs); + if (!up) return; + bool ran = true; + rcs.clear(); + for (const ArThread& a : t) { ran = ran && a.rc_launch == RAD_OK; rcs += std::to_string(a.rc_launch) + "/"; } + ok((w + "-rank all-gather launch").c_str(), ran, "rc " + rcs); int64_t bad = 0, bad_id = 0; - for (const ArThread* t : { &a, &b, &c }) { + for (const ArThread& a : t) { for (int r = 0; r < W; ++r) { for (int64_t i = 0; i < numel; ++i) { uint32_t got; - std::memcpy(&got, &t->out[(size_t)(r * numel + i)], 4); + std::memcpy(&got, &a.out[(size_t)(r * numel + i)], 4); if (got == sent(r, i)) continue; ++bad; if ((i & 1) == 0) ++bad_id; } } } - ok("3-rank all-gather places every rank's bytes on every rank, bit for bit", bad == 0, - std::to_string(bad) + " words wrong, " + std::to_string(bad_id) + " of them token ids"); - if (row->fini) { row->fini(a.inst); row->fini(b.inst); row->fini(c.inst); } + ok((w + "-rank all-gather places every rank's bytes on every rank, bit for bit").c_str(), + bad == 0, std::to_string(bad) + " words wrong, " + std::to_string(bad_id) + + " of them token ids"); + if (row->fini) for (ArThread& a : t) row->fini(a.inst); } - /* The row-interleaved placement the sampler asks for: [rows][3][row]. */ + /* The row-interleaved placement the sampler asks for: [rows][world][row]. */ const int64_t rowe = 2048; /* 4 rows of 1024 (id, logit) pairs */ - ArThread c{ row, 0, devs[0], numel }, d{ row, 1, devs[1], numel }, e{ row, 2, devs[2], numel }; - c.world = d.world = e.world = W; - c.row_elems = d.row_elems = e.row_elems = rowe; - std::thread tc(gather_worker, &c), td(gather_worker, &d), te(gather_worker, &e); - tc.join(); - td.join(); - te.join(); - if (c.rc_init != RAD_OK || d.rc_init != RAD_OK || e.rc_init != RAD_OK || - c.rc_launch != RAD_OK || d.rc_launch != RAD_OK || e.rc_launch != RAD_OK) { - ok("3-rank all-gather, row-interleaved", false, - "rc " + std::to_string(c.rc_init) + "/" + std::to_string(d.rc_init) + "/" + - std::to_string(e.rc_init) + " init, " + std::to_string(c.rc_launch) + "/" + - std::to_string(d.rc_launch) + "/" + std::to_string(e.rc_launch) + " launch"); + std::vector t((size_t)W); + std::vector th; + for (int r = 0; r < W; ++r) { + t[(size_t)r] = ArThread{ row, r, devs[(size_t)r], numel }; + t[(size_t)r].world = W; + t[(size_t)r].row_elems = rowe; + th.emplace_back(gather_worker, &t[(size_t)r]); + } + for (std::thread& x : th) x.join(); + bool up = true, ran = true; + std::string rcs; + for (const ArThread& a : t) { + up = up && a.rc_init == RAD_OK; ran = ran && a.rc_launch == RAD_OK; + rcs += std::to_string(a.rc_init) + "/" + std::to_string(a.rc_launch) + " "; + } + if (!up || !ran) { + ok((w + "-rank all-gather, row-interleaved").c_str(), false, "init/launch rc " + rcs); return; } const int64_t nrows = numel / rowe; int64_t bad = 0, bad_id = 0; - for (const ArThread* t : { &c, &d, &e }) { + for (const ArThread& a : t) { for (int64_t m = 0; m < nrows; ++m) { for (int r = 0; r < W; ++r) { for (int64_t j = 0; j < rowe; ++j) { uint32_t got; - std::memcpy(&got, &t->out[(size_t)(m * W * rowe + r * rowe + j)], 4); + std::memcpy(&got, &a.out[(size_t)(m * W * rowe + r * rowe + j)], 4); if (got == sent(r, m * rowe + j)) continue; ++bad; if ((j & 1) == 0) ++bad_id; @@ -12351,31 +11976,329 @@ static void gather_three_rank(const Plugin& pl, const std::vector& devs, co } } } - ok("3-rank all-gather interleaves by row, so one row carries all three ranks", bad == 0, - std::to_string(bad) + " words wrong, " + std::to_string(bad_id) + " of them token ids"); - if (row->fini) { row->fini(c.inst); row->fini(d.inst); row->fini(e.inst); } - ok("3-rank all-gather fini ran", true); + ok((w + "-rank all-gather interleaves by row, so one row carries all " + w + " ranks").c_str(), + bad == 0, std::to_string(bad) + " words wrong, " + std::to_string(bad_id) + + " of them token ids"); + if (row->fini) for (ArThread& a : t) if (a.inst) row->fini(a.inst); + ok((w + "-rank all-gather fini ran").c_str(), true); +} + +/* ------------------------------------------------------------------ the fused write (ar_hc_write*) */ +/* The fused all-reduce + gated-residual-write rows, with the MoE gather optionally in front (the + * rows that end the link hold themselves, r4d_rows.cpp). The oracle is the unfused chain rebuilt + * on the host in the kernels' own arithmetic: moe_gather's gather word (r4d_ar_gather_word: fp32 + * ascending-slot accumulate, round-to-nearest-even narrows, the shared arm's product rounded + * before the add), then ar_vsum's fp32 ascending-rank fold rounded once to bf16, then hc_write's + * word (r4d_ar_hc_write_word, whose pack is round-half-away f2bf rather than the reduce's RTNE, + * hence its own helper below). The rows promise bytes identical to the chain they replace, so the + * check is byte-exact. Exception: the sigmoid gate is __expf on the card and std::exp here, which + * may differ by an f32 ulp and move one bf16 rounding (the tolerance silu_bf16's check names), so + * a sigmoid shape counts moved bytes and fails only beyond an ulp. + * + * Both gather arms are walked: a small M keeps the block slot table in LDS (the launcher widens + * its own grid), a prefill-sized M takes the inverse table in the scratch (the same launcher's + * by_inv rule), and each rank is given the scratch or not per shape -- the same M, n and scratch + * on every rank is what makes the two ranks decide the arm identically. */ +struct ArHc { + const RadKernelInfo* row = nullptr; + int rank = 0, dev = 0, world = 2; + int64_t M = 0, n = 0, hc = 2, top_k = 0; /* top_k 0: the plain fused write */ + const char* act = nullptr; /* gather's shared arm: null operand, "none", "sigmoid" */ + bool use_scratch = false; /* hand the inverse table's scratch to the gather */ + void* inst = nullptr; + int rc_init = RAD_E_STATE, rc_launch = RAD_OK; + std::vector y_in, inj, h0; /* what we hand the kernel */ + std::vector ye, ew, sh, sg; /* the gather's inputs */ + std::vector sorted; + std::vector y_out, h_out; /* what it leaves behind */ +}; + +static void ar_hc_worker(ArHc* t) { + if (st_set_device(t->dev) != hipSuccess) { t->rc_init = RAD_E_DEVICE; return; } + const bool gather = t->top_k > 0; + const int64_t Tn = t->M * t->top_k; /* Tn, not T: T() is this file's RadTensor helper below */ + std::vector ps = { PI("world_size", t->world), PI("M", t->M), PI("n", t->n), + PI("hc", t->hc), PS("dtype", "bf16"), PI("wire", 0) }; + if (gather) ps.push_back(PI("top_k", t->top_k)); + if (t->act) ps.push_back(PS("act", t->act)); + t->rc_init = t->row->init(ps.data(), (int)ps.size(), t->rank, t->world, &t->inst); + if (t->rc_init != RAD_OK) return; + + /* Allocated and freed here, not through dalloc: g_allocs is one host-side list and four + * rank threads would race on it (every other cross-rank worker does the same). */ + void* y = nullptr; void* inj = nullptr; void* h = nullptr; + void* ye = nullptr; void* ew = nullptr; void* so = nullptr; void* sh = nullptr; void* sg = nullptr; + void* scr = nullptr; + const size_t yb = (size_t)(t->M * t->n * 2), hb = (size_t)(t->M * t->hc * t->n * 2); + bool mem = hipMalloc(&y, yb) == hipSuccess && hipMalloc(&inj, (size_t)(t->M * t->hc * 2)) == + hipSuccess && hipMalloc(&h, hb) == hipSuccess; + if (gather) mem = mem && hipMalloc(&ye, (size_t)(Tn * t->n * 2)) == hipSuccess && + hipMalloc(&ew, (size_t)(Tn * 2)) == hipSuccess && + hipMalloc(&so, (size_t)(Tn * 4)) == hipSuccess && + (!t->act || (hipMalloc(&sh, yb) == hipSuccess && + hipMalloc(&sg, (size_t)(t->M * 2)) == hipSuccess)); + if (!mem) { t->rc_launch = RAD_E_NOMEM; } + else { + st_memcpy(y, t->y_in.data(), yb, hipMemcpyHostToDevice); + st_memcpy(inj, t->inj.data(), (size_t)(t->M * t->hc * 2), hipMemcpyHostToDevice); + st_memcpy(h, t->h0.data(), hb, hipMemcpyHostToDevice); + if (gather) { + st_memcpy(ye, t->ye.data(), (size_t)(Tn * t->n * 2), hipMemcpyHostToDevice); + st_memcpy(ew, t->ew.data(), (size_t)(Tn * 2), hipMemcpyHostToDevice); + st_memcpy(so, t->sorted.data(), (size_t)(Tn * 4), hipMemcpyHostToDevice); + if (t->act) { + st_memcpy(sh, t->sh.data(), yb, hipMemcpyHostToDevice); + st_memcpy(sg, t->sg.data(), (size_t)(t->M * 2), hipMemcpyHostToDevice); + } + } + std::vector ts; + if (gather) { + ts = { T(ye, RAD_BF16, { Tn, t->n }), T(ew, RAD_BF16, { t->M, t->top_k }), + T(so, RAD_I32, { Tn }), T(sh, RAD_BF16, { t->M, t->n }), + T(sg, RAD_BF16, { t->M, 1 }), T(y, RAD_BF16, { t->M, t->n }), + T(inj, RAD_BF16, { t->M, t->hc }), T(h, RAD_BF16, { t->M, t->hc * t->n }) }; + if (!t->act) { absent(ts[3]); absent(ts[4]); } + } else { + ts = { T(y, RAD_BF16, { t->M, t->n }), T(inj, RAD_BF16, { t->M, t->hc }), + T(h, RAD_BF16, { t->M, t->hc * t->n }) }; + } + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.t = ts.data(); a.n_t = (int)ts.size(); + a.p = ps.data(); a.n_p = (int)ps.size(); + a.instance = t->inst; + a.rank = t->rank; + a.world_size = t->world; + const int64_t need = gather && t->row->scratch ? t->row->scratch(&a) : 0; + if (gather && t->use_scratch) { + /* The inverse table's bytes exactly: has_inv is `scratch && scratch_bytes >= Tn * 4`, + * and the row's own hook is what says how big that is. */ + if (need <= 0 || hipMalloc(&scr, (size_t)need) != hipSuccess) { + t->rc_launch = RAD_E_NOMEM; + } else { + st_memset(scr, 0, (size_t)need); + a.scratch = scr; a.scratch_bytes = need; + } + } + if (t->rc_launch == RAD_OK) { + t->rc_launch = t->row->launch(&a, nullptr); + st_stream_sync(nullptr); + t->y_out.resize((size_t)(t->M * t->n)); + t->h_out.resize((size_t)(t->M * t->hc * t->n)); + st_memcpy(t->y_out.data(), y, yb, hipMemcpyDeviceToHost); + st_memcpy(t->h_out.data(), h, hb, hipMemcpyDeviceToHost); + } + } + for (void* p : { y, inj, h, ye, ew, so, sh, sg, scr }) if (p) st_free(p); +} + +/* hc_write's pack (r4d_gdn_wmma.h f2bf): round-half-AWAY, one add. The reduce's from_f and + * arg_bf16_rne are round-to-nearest-even; this file's h_to_bf16 is that one, so the write's + * oracle needs this. */ +static uint16_t h_bf16_away(float f) { + uint32_t u; std::memcpy(&u, &f, 4); + return (uint16_t)((u + 0x8000u) >> 16); +} + +static void ar_hc_write_case(const Plugin& pl, const std::vector& devs, const char* name, + int world, bool want_gather) { + const RadKernelInfo* row = find(pl, name); + if (!row) { ok(name, false, "row absent"); return; } + if ((int)devs.size() < world) { + skip(name, (std::string("needs ") + std::to_string(world) + " gfx1201 cards").c_str()); + return; + } + struct Shape { int64_t M, n, hc, top_k; const char* act; bool scratch; }; + std::vector shapes; + if (!want_gather) { + /* A decode step's rows and a chunk's, both under the one-shot bands. */ + shapes = { { 8, 1024, 4, 0, nullptr, false }, { 64, 2560, 2, 0, nullptr, false } }; + } else { + /* The first two stay under the launcher's by_inv line (its own widening keeps the LDS + * table at or below eight rows a block); the third is a prefill-sized message where only + * the inverse table fits. The shared arm: absent, then "none" (the gate multiplies as it + * is -- exact against the host), then "sigmoid" (the ulp-tolerant arm). */ + shapes = { { 8, 256, 2, 10, nullptr, false }, { 40, 512, 4, 6, "none", false }, + { 200, 2048, 2, 10, "sigmoid", true } }; + } + const std::string nm(name); + for (const Shape& sh : shapes) { + const int64_t M = sh.M, n = sh.n, hc = sh.hc, k = sh.top_k, T = M * k; + const bool gather = k > 0; + const bool sig = sh.act && !std::strcmp(sh.act, "sigmoid"); + const std::string at = " M=" + std::to_string(M) + " n=" + std::to_string(n) + + " hc=" + std::to_string(hc) + + (gather ? " top_k=" + std::to_string(k) + + (sh.act ? std::string(", shared ") + sh.act + : std::string(", no shared arm")) + : std::string()) + + (gather && sh.scratch ? ", inverse table" : ""); + + /* The routing is replicated across ranks -- every rank sorts the same slots -- while the + * routed rows, the weights and the streams are each rank's own. `sorted` is the stable + * sort by expert with the live slots first and -1 after, as moe_scatter writes it. */ + std::vector sorted((size_t)(gather ? T : 0), -1); + if (gather) { + std::vector ex((size_t)T); + uint64_t rs = 0x9E3779B97F4A7C15ull ^ ((uint64_t)M * 1315423911ull) ^ + ((uint64_t)n * 2654435761ull) ^ (uint64_t)k; + auto rnd = [&]() { rs ^= rs << 13; rs ^= rs >> 7; rs ^= rs << 17; return rs; }; + for (int64_t i = 0; i < T; ++i) { + const uint64_t v = rnd(); + ex[(size_t)i] = (v % 31 == 0) ? -1 : (int32_t)((v >> 8) % 64); + } + int64_t pos = 0; + for (int32_t e = 0; e < 64; ++e) + for (int64_t i = 0; i < T; ++i) + if (ex[(size_t)i] == e) sorted[(size_t)pos++] = (int32_t)i; + } + /* ye's rows are in sorted order, so the kernel resolves token tok, slot j to the sorted + * ROW holding slot f = tok*k+j -- the inverse of `sorted` (s_i[f - lo] = i in + * r4d_ar_oneshot_2rank_exact.hip's scan, inv[f] = i in r4d_ar_gather_inv_kernel). The + * oracle inverts the same way; reading sorted forward would gather the wrong row. */ + std::vector inv((size_t)(gather ? T : 0), -1); + for (int64_t i = 0; gather && i < T; ++i) { + const int32_t f = sorted[(size_t)i]; + if (f >= 0 && f < T) inv[(size_t)f] = (int32_t)i; + } + + std::vector t((size_t)world); + std::vector th; + for (int r = 0; r < world; ++r) { + ArHc& x = t[(size_t)r]; + x.row = row; x.rank = r; x.dev = devs[(size_t)r]; x.world = world; + x.M = M; x.n = n; x.hc = hc; x.top_k = k; x.act = sh.act; x.use_scratch = sh.scratch; + x.y_in.resize((size_t)(M * n)); + x.inj.resize((size_t)(M * hc)); + x.h0.resize((size_t)(M * hc * n)); + uint64_t rs = 0x9E3779B97F4A7C15ull ^ ((uint64_t)(r + 1) * 0x9E3779B97F4A7C15ull) ^ + ((uint64_t)M * 1315423911ull) ^ ((uint64_t)n * 2654435761ull); + auto rnd = [&]() { rs ^= rs << 13; rs ^= rs >> 7; rs ^= rs << 17; return rs; }; + for (int64_t i = 0; i < M * n; ++i) + x.y_in[(size_t)i] = gather ? (uint16_t)0x7f7fu /* overwritten or it is junk */ + : h_to_bf16(ar_pattern_value(r, i)); + for (int64_t i = 0; i < M * hc; ++i) + x.inj[(size_t)i] = h_to_bf16(ar_pattern_value(r + 1, i)); + for (int64_t i = 0; i < M * hc * n; ++i) + x.h0[(size_t)i] = h_to_bf16(((int64_t)(rnd() % 4001) - 2000) / 512.0f); + if (gather) { + x.sorted = sorted; + x.ye.resize((size_t)(T * n)); + x.ew.resize((size_t)T); + for (auto& v : x.ye) v = h_to_bf16(((int64_t)(rnd() % 4001) - 2000) / 512.0f); + for (auto& v : x.ew) v = h_to_bf16((float)(rnd() % 1000 + 1) / 1024.0f); + if (sh.act) { + x.sh.resize((size_t)(M * n)); + x.sg.resize((size_t)M); + for (auto& v : x.sh) v = h_to_bf16(((int64_t)(rnd() % 4001) - 2000) / 256.0f); + for (auto& v : x.sg) v = h_to_bf16(((int64_t)(rnd() % 801) - 400) / 100.0f); + } + } + th.emplace_back(ar_hc_worker, &x); + } + for (std::thread& x : th) x.join(); + + bool up = true, ran = true; + std::string rcs; + for (const ArHc& x : t) { + up = up && x.rc_init == RAD_OK; ran = ran && x.rc_launch == RAD_OK; + rcs += std::to_string(x.rc_init) + "/" + std::to_string(x.rc_launch) + " "; + } + ok((nm + at + " init (peer rendezvous)").c_str(), up, "init/launch rc " + rcs); + if (!up) return; + ok((nm + at + " launch").c_str(), ran, "init/launch rc " + rcs); + if (!ran) { if (row->fini) for (ArHc& x : t) if (x.inst) row->fini(x.inst); continue; } + + /* The gather half, per rank, exactly as r4d_ar_gather_word folds it. */ + std::vector> ymsg((size_t)world, std::vector((size_t)(M * n))); + for (int r = 0; r < world; ++r) { + const ArHc& x = t[(size_t)r]; + if (!gather) { ymsg[(size_t)r] = x.y_in; continue; } + for (int64_t tok = 0; tok < M; ++tok) + for (int64_t e = 0; e < n; ++e) { + float acc = 0.0f; + for (int64_t j = 0; j < k; ++j) { + const int32_t idx = inv[(size_t)(tok * k + j)]; + if (idx < 0) continue; + acc += h_bf16(x.ew[(size_t)(tok * k + j)]) * + h_bf16(x.ye[(size_t)(idx * n + e)]); + } + uint16_t out = h_to_bf16(acc); + if (sh.act) { + const float gate = sig ? 1.0f / (1.0f + std::exp(-h_bf16(x.sg[(size_t)tok]))) + : h_bf16(x.sg[(size_t)tok]); + const uint16_t pr = h_to_bf16(h_bf16(x.sh[(size_t)(tok * n + e)]) * gate); + out = h_to_bf16(h_bf16(pr) + h_bf16(out)); + } + ymsg[(size_t)r][(size_t)(tok * n + e)] = out; + } + } + /* The fold, ascending rank, rounded once -- ar_vsum. Then the write -- hc_write_word. */ + int64_t bad_y = 0, moved_y = 0, bad_h = 0, moved_h = 0, first = -1; + double worst = 0.0; + for (int64_t i = 0; i < M * n; ++i) { + float acc = 0.0f; + for (int r = 0; r < world; ++r) acc += h_bf16(ymsg[(size_t)r][(size_t)i]); + const uint16_t want_y = h_to_bf16(acc); + const int64_t tok = i / n, e = i % n; + for (int r = 0; r < world; ++r) { + ArHc& x = t[(size_t)r]; + const uint16_t got = x.y_out[(size_t)i]; + if (got != want_y) { + const double rel = std::fabs((double)h_bf16(got) - (double)acc) / + (std::fabs((double)acc) + 1.0); + if (sig && rel <= 0.02) { ++moved_y; if (rel > worst) worst = rel; } + else { ++bad_y; if (first < 0) first = i; } + } + for (int64_t c = 0; c < hc; ++c) { + const int64_t o = (tok * hc + c) * n + e; + const float wantf = h_bf16(x.h0[(size_t)o]) + + h_bf16(x.inj[(size_t)(tok * hc + c)]) * h_bf16(want_y); + const uint16_t want = h_bf16_away(wantf); + const uint16_t g = x.h_out[(size_t)o]; + if (g != want) { + const double rel = std::fabs((double)h_bf16(g) - (double)wantf) / + (std::fabs((double)wantf) + 1.0); + if (sig && rel <= 0.02) { ++moved_h; if (rel > worst) worst = rel; } + else { ++bad_h; if (first < 0) first = o; } + } + } + } + } + char d[160]; + std::snprintf(d, sizeof d, "%lld + %lld wrong (first at %lld); %lld + %lld moved by " + "__expf vs std::exp, worst rel %.5f", (long long)bad_y, (long long)bad_h, + (long long)first, (long long)moved_y, (long long)moved_h, worst); + ok((nm + at + ": every rank holds the folded y and the written h of the unfused chain, " + "byte for bit").c_str(), + bad_y == 0 && bad_h == 0, d); + if (gather && !sig) { + /* The y the fold leaves is the same bytes on every rank -- the ascending-rank fold is + * rank-order symmetric. A rank-local gather output that differs is fine; the folded + * one must not. */ + int64_t skew = 0; + for (int64_t i = 0; i < M * n; ++i) + for (int r = 1; r < world; ++r) + if (t[(size_t)r].y_out[(size_t)i] != t[0].y_out[(size_t)i]) ++skew; + ok((nm + at + ": the folded message is the same bytes on every rank").c_str(), + skew == 0, std::to_string(skew) + " elements differ between ranks"); + } + if (row->fini) for (ArHc& x : t) if (x.inst) row->fini(x.inst); + } } /* ------------------------------------------------------------------ the device sweep */ -/* NGRAM_IDS' `ahead_ids`: the prompt that follows the step, hashed in the same launch. Step one - * runs two sequences, [5, 6] and [11, 42], with three more tokens of the LAST one, [7, 8, 9], in - * `tok` behind them. Their ids must be the ids step two computes running [7, 8, 9] against the - * window step one left; that window must be the step's own; and the step's own ids must be the - * ones a launch without `ahead_ids` writes. The same property ref_test holds libref to. */ /* embed_lookup_q against a host gather of the same bytes, through the host side's own conversions. * - * THE BAR IS THE BIT, not a tolerance. libavx's gather decodes a code as - * rad_f32_to_bf16(rad_fp8e4m3_to_f32(code) * scale), and the device kernel has to produce exactly - * that for every code, or one model reads a different n-gram embedding depending on which tier - * --ngram-placement put its table on. So the oracle is those two functions, the table holds every - * code but the two NaN encodings (no quantiser writes them), and the comparison is of the bytes. + * Bit-exact: libavx's gather decodes a code as rad_f32_to_bf16(rad_fp8e4m3_to_f32(code) * scale), + * and the device kernel must match for every code, or the n-gram embedding would depend on the + * tier --ngram-placement chose. The table holds every code except the two NaN encodings. * - * Five launches: the quad walk and the entry walk (the model's width of 160, and 13); an E4M3 - * table with a scale and a plain bf16 one without, whose rows come back unchanged; the table in - * VRAM and in pinned host memory read over the link, the placement this kernel exists for. The ids - * include padding (-1) and one past the table, and both write a zero row. */ + * Five launches: the quad walk and the entry walk (widths 160, the model's, and 13); an E4M3 table + * with a scale and a plain bf16 one (rows unchanged); the table in VRAM and in pinned host memory + * read over the link. The ids include padding (-1) and one past the table, both writing a zero + * row. */ static void embed_lookup_q_case(const Plugin& pl) { if (!sel("embed_lookup_q_bf16")) return; const char* what = "embed_lookup_q vs a host gather, to the bit"; @@ -12434,7 +12357,7 @@ static void embed_lookup_q_case(const Plugin& pl) { void* d_tok = dalloc((size_t)M * 4); st_memcpy(d_tok, ids.data(), (size_t)M * 4, hipMemcpyHostToDevice); void* d_x = dalloc((size_t)(M * sh.ne * 2)); - st_memset(d_x, 0xFF, (size_t)(M * sh.ne * 2)); /* a zero row has to be written */ + st_memset(d_x, 0xFF, (size_t)(M * sh.ne * 2)); /* zero rows must be written */ std::vector ts = { T(d_tok, RAD_I32, { M }), T(d_tab, sh.e4m3 ? RAD_F8E4M3 : RAD_BF16, { NV, sh.ne }), @@ -12477,6 +12400,11 @@ static void embed_lookup_q_case(const Plugin& pl) { ok(what, bad.empty(), bad); } +/* ngram_ids' `ahead_ids`: the prompt following the step, hashed in the same launch. Step one runs + * [5, 6] and [11, 42], with three more tokens of the last sequence, [7, 8, 9], in `tok` behind + * them. Their ids must equal what step two computes for [7, 8, 9] against the window step one + * left; that window must be the step's own; and the step's ids must match a launch without + * `ahead_ids`. ref_test holds libref to the same property. */ static void ngram_ahead_case(const Plugin& pl) { if (!sel("ngram_ids_i32")) return; const RadKernelInfo* r = find(pl, "ngram_ids_i32"); @@ -12542,10 +12470,9 @@ static void device_phase(const Plugin& pl) { skip("device phase", "no HIP device"); return; } - /* A host can present more HIP devices than it has discrete cards: an integrated part shows up - * alongside them, reporting tens of GiB of "VRAM" that is really system RAM. Filtering on the - * arch string rather than taking device 0 is not defensive tidiness -- a rank landing on the - * integrated part runs slowly and wrongly and the failure looks like a kernel bug. */ + /* An integrated GPU can appear beside the discrete cards, reporting system RAM as "VRAM". + * Devices are filtered on the arch string, since a rank on the integrated part would fail in a + * way that looks like a kernel bug. */ std::vector devs; for (int d = 0; d < n; ++d) { hipDeviceProp_t p; @@ -12574,41 +12501,46 @@ static void device_phase(const Plugin& pl) { attn_case(pl, "attn_decode_h128_gqa4_bf16kv", 128, 4, 1, "bf16", 0); attn_case(pl, "attn_prefill_h64_gqa4_bf16kv", 64, 4, 32, "bf16", 1); attn_case(pl, "attn_prefill_h64_gqa4_bf16kv", 64, 4, 1, "bf16", 1); - /* Gemma 4 dense sliding window: decode only, so the window is threaded through -- 1024 is the - * model's window. It exercises the windowed split law and the WIN=1 template the way the - * drafter leg does; max_ctx here is smaller than the window, so the span clamps to the context. */ + /* Gemma 4 dense sliding window, decode, with the model's window of 1024: exercises the + * windowed split law and the WIN=1 template. max_ctx is below the window, so the span clamps to + * the context. */ attn_case(pl, "attn_decode_h256_gqa2_fp8kv", 256, 2, 1, "fp8_e4m3", 0, 1024); attn_case(pl, "attn_decode_h256_gqa2_bf16kv", 256, 2, 1, "bf16", 0, 1024); - /* Gemma 4 dense sliding window: the PREFILL leg, the band above q_len 32 that a trunk layer - * needs on the device (libref is an opt-in fallback the engine refuses by default, spec §17). - * The windowed query-tiled prefill kernel; window 1024 is the model's, threaded through to - * instantiate WIN=1 the way the decode leg does. max_ctx here (64) is smaller than the window, so the span clamps to the - * context and the launch is the full-attention form. */ + /* Gemma 4 dense sliding window, prefill (q_len above 32), on the windowed query-tiled kernel + * with WIN=1 (window 1024). max_ctx (64) is below the window, so the span clamps to the context + * and the launch is the full-attention form. */ attn_case(pl, "attn_prefill_h256_gqa2_fp8kv", 256, 2, 32, "fp8_e4m3", 1, 1024); attn_case(pl, "attn_prefill_h256_gqa2_bf16kv", 256, 2, 32, "bf16", 1, 1024); - /* Gemma 4 dense global: head_dim 512, full attention, on the windowed kernel -- one row for - * every q_len, so a prefill-shaped launch (q_len 32) and a decode one (1) of the same row; the - * numeric check of both follows. */ + /* Gemma 4 dense global: head_dim 512, full attention, on the windowed kernel (one row for every + * q_len): a prefill-shaped launch (q_len 32) and a decode one (1); numeric checks follow. */ attn_case(pl, "attn_window_h512_gqa8_fp8kv", 512, 8, 32, "fp8_e4m3", 1); attn_case(pl, "attn_window_h512_gqa8_bf16kv", 512, 8, 32, "bf16", 1); attn_case(pl, "attn_window_h512_gqa8_fp8kv", 512, 8, 1, "fp8_e4m3", 0); attn_case(pl, "attn_window_h512_gqa8_bf16kv", 512, 8, 1, "bf16", 0); - /* The numeric attention check: the same rows, but with random data and a comparison - * against the inline oracle, plus a negative control. */ + /* Numeric checks of the same rows: random data against the inline oracle, with a negative + * control. */ attn_numeric_case(pl, "attn_window_h512_gqa8_fp8kv", 512, 8, 32, "fp8_e4m3", 0); attn_numeric_case(pl, "attn_window_h512_gqa8_bf16kv", 512, 8, 32, "bf16", 0); attn_numeric_case(pl, "attn_window_h512_gqa8_fp8kv", 512, 8, 1, "fp8_e4m3", 0); attn_numeric_case(pl, "attn_window_h512_gqa8_bf16kv", 512, 8, 1, "bf16", 0); - /* The h256/gqa2 PREFILL numeric check. Unlike the decode leg (ctx 64 < window, so the window - * clamps to the context), ctx here is 2048 > window 1024, so the window actually bites: for - * query row 0, pos = 2048-64 = 1984 and the visible keys are [961..1984], so the kernel's - * wlo0 = 961 and tstart = 961/48 = 20 -- exercising both the window mask (keys below 961 are - * masked) and the below-window tile skip (tiles 0..19 are never walked). The oracle's - * visible() is the same bound, so the two agree. */ + /* The h256/gqa2 prefill numeric check with ctx 2048 > window 1024, so the window applies: for + * query row 0, pos = 2048-64 = 1984 and the visible keys are [961..1984], so wlo0 = 961 and + * tstart = 961/48 = 20. This exercises the window mask and the below-window tile skip (tiles + * 0..19 are never walked). */ attn_numeric_case(pl, "attn_prefill_h256_gqa2_fp8kv", 256, 2, 64, "fp8_e4m3", 1024, 2048); attn_numeric_case(pl, "attn_prefill_h256_gqa2_bf16kv", 256, 2, 64, "bf16", 1024, 2048); attn_numeric_case(pl, "attn_decode_h256_gqa2_fp8kv", 256, 2, 1, "fp8_e4m3", 1024); attn_numeric_case(pl, "attn_decode_h256_gqa2_bf16kv", 256, 2, 1, "bf16", 1024); + /* Two queries per KV head at 128: Qwen3-1.7B, Qwen3-ASR's decoder. */ + attn_case(pl, "attn_prefill_h128_gqa2_fp8kv", 128, 2, 32, "fp8_e4m3", 1); + attn_case(pl, "attn_prefill_h128_gqa2_bf16kv", 128, 2, 32, "bf16", 1); + attn_case(pl, "attn_decode_h128_gqa2_fp8kv", 128, 2, 1, "fp8_e4m3", 0); + attn_case(pl, "attn_decode_h128_gqa2_bf16kv", 128, 2, 1, "bf16", 0); + attn_numeric_case(pl, "attn_prefill_h128_gqa2_fp8kv", 128, 2, 64, "fp8_e4m3", 0, 256); + attn_numeric_case(pl, "attn_prefill_h128_gqa2_bf16kv", 128, 2, 64, "bf16", 0, 256); + attn_numeric_case(pl, "attn_decode_h128_gqa2_fp8kv", 128, 2, 1, "fp8_e4m3", 0, 256); + attn_numeric_case(pl, "attn_decode_h128_gqa2_bf16kv", 128, 2, 1, "bf16", 0, 256); + attn_numeric_case(pl, "attn_decode_h128_gqa2_bf16kv", 128, 2, 24, "bf16", 0, 256); attn_gq_fold_case(pl, 3, false); attn_gq_fold_case(pl, 24, false); attn_gq_fold_case(pl, 3, true); @@ -12637,8 +12569,8 @@ static void device_phase(const Plugin& pl) { } } /* The encoder attention rows: a fused [q|k|v] projection read through column slices, at each - * compiled (head_dim, gqa), with and without a window. Numerics are rad-kbench's (libref is - * the oracle); this is the launch at every geometry. */ + * compiled (head_dim, gqa), with and without a window. Launch only; numerics are rad-kbench's + * (libref is the oracle). */ { struct G { const char* name; int64_t hd, nh, nkv; }; for (const G& g : { G{ "attn_dense_h64_bf16", 64, 4, 4 }, @@ -12749,10 +12681,9 @@ static void device_phase(const Plugin& pl) { run_case(r, ts, ps); } } - /* --- the audio tower's ops, NUMERICALLY: each kernel against the formula libref implements, - * computed here on the host from the same bf16 inputs. rad-kbench's replay fixture predates - * these ops and a container-driven run needs the model, so this is where a wrong index in - * one of them shows up without either. Relative L2 against a bf16 rounding of the answer. */ + /* --- the audio tower's ops, numerically: each kernel against the formula libref implements, + * computed on the host from the same bf16 inputs (rad-kbench's replay fixture predates these + * ops). Relative L2 against a bf16 rounding of the answer. */ { uint64_t seed = 0x5eedull; auto rnd = [&]() { @@ -12817,12 +12748,11 @@ static void device_phase(const Plugin& pl) { const float v = h_bf16(h_to_bf16(x[i])); want[i] = v * (1.0f / (1.0f + std::exp(-v))); } - /* expf on the card and std::exp here may differ by an ulp of f32, which can move - * a bf16 rounding; anything beyond that is a wrong kernel. */ + /* expf and std::exp may differ by an f32 ulp, moving a bf16 rounding. */ check("silu_bf16 numerics", down(dy, x.size()), want, 1e-3); } else ok("silu_bf16", false, "row absent"); - /* PAST THE GRID'S Y LIMIT: the audio subsampler's rectifier runs over 96000 rows of - * 128, and a launch of one grid row a matrix row stops at 65535. */ + /* Past the grid's y limit: the audio subsampler's rectifier runs over 96000 rows of + * 128, beyond the 65535 a one-grid-row-per-matrix-row launch reaches. */ if (const RadKernelInfo* r = find(pl, "relu_bf16")) { const int64_t Mb = 70000, nb = 32; std::vector xb = randv((size_t)(Mb * nb), 2.0f); @@ -12897,7 +12827,7 @@ static void device_phase(const Plugin& pl) { if (!r) break; const int64_t kh = 3, kw = 3, st = 2, pad = 1; const int64_t Wo = (g.W + 2 * pad - kw) / st + 1; - const int64_t T0 = g.M / 2; /* rows a segment */ + const int64_t T0 = g.M / 2; /* rows per segment */ const int64_t To = (T0 + 2 * pad - kh) / st + 1, Mo = 2 * To; std::vector x = randv((size_t)(g.M * g.W * g.cin), 1.0f); std::vector w = randv((size_t)(g.cout * g.cin * kh * kw), 0.3f); @@ -12945,6 +12875,195 @@ static void device_phase(const Plugin& pl) { check(g.cin == 1 ? "conv2d_bf16 layer0 numerics" : "conv2d_bf16 layer1 numerics", down(dy, want.size()), want, 1e-2); } + /* Qwen3-ASR's: a [mel, time] kernel (time last) with a bias and gelu, over seconds + * staged 13 rows apart with the alignment rows masked; and the 7680 -> 1024 linear as + * a 1 x W convolution over the frequency axis. Small channel counts, same indexing. */ + struct Q { int64_t M, W, cin, cout, kh, kw, st, pad, tl; bool bias, gelu; }; + for (const Q& q : { Q{ 26, 16, 6, 10, 3, 3, 2, 1, 1, true, true }, + Q{ 13, 8, 6, 12, 1, 8, 1, 0, 0, false, false } }) { + if (!r) break; + const int64_t Wo = (q.W + 2 * q.pad - q.kw) / q.st + 1; + const int64_t To = (q.M + 2 * q.pad - q.kh) / q.st + 1; + std::vector x = randv((size_t)(q.M * q.W * q.cin), 1.0f); + std::vector w = randv((size_t)(q.cout * q.cin * q.kh * q.kw), 0.3f); + std::vector bias = randv((size_t)q.cout, 0.5f); + std::vector cu = { 0, (int32_t)q.M }; + std::vector valid((size_t)q.M, 1); + if (q.bias) for (int64_t t = 0; t < q.M; ++t) valid[(size_t)t] = t % 13 < 11; + void* dx = up(x); + void* dw = up(w); + void* db = up(bias); + void* dcu = dalloc(cu.size() * 4); + void* dv = dalloc(valid.size() * 4); + fill_i32(dcu, cu); + fill_i32(dv, valid); + void* dy = dalloc((size_t)(To * Wo * q.cout) * 2); + std::vector ts = { T(dx, RAD_BF16, { q.M, q.W * q.cin }), + T(dw, RAD_BF16, { q.cout, q.cin, q.kh, q.kw }), + T(dcu, RAD_I32, { 2 }), + q.bias ? T(dv, RAD_I32, { q.M }) : RadTensor{}, + T(dy, RAD_BF16, { To, Wo * q.cout }), + q.bias ? T(db, RAD_BF16, { q.cout }) : RadTensor{} }; + std::vector ps = { PI("M", q.M), PI("width", q.W), PI("cin", q.cin), + PI("cout", q.cout), PI("kh", q.kh), PI("kw", q.kw), + PI("stride", q.st), PI("pad", q.pad), + PS("dtype", "bf16"), PI("t_last", q.tl), + PS("act", q.gelu ? "gelu" : "none") }; + run_case(r, ts, ps); + std::vector want((size_t)(To * Wo * q.cout), 0.0f); + for (int64_t to = 0; to < To; ++to) + for (int64_t wo = 0; wo < Wo; ++wo) + for (int64_t co = 0; co < q.cout; ++co) { + float acc = 0.0f; + for (int64_t i = 0; i < q.kh; ++i) { + const int64_t ti = to * q.st - q.pad + i; + if (ti < 0 || ti >= q.M || (q.bias && !valid[(size_t)ti])) continue; + for (int64_t j = 0; j < q.kw; ++j) { + const int64_t wi = wo * q.st - q.pad + j; + if (wi < 0 || wi >= q.W) continue; + for (int64_t ci = 0; ci < q.cin; ++ci) { + const int64_t wix = q.tl + ? ((co * q.cin + ci) * q.kw + j) * q.kh + i + : ((co * q.cin + ci) * q.kh + i) * q.kw + j; + acc += x[(size_t)((ti * q.W + wi) * q.cin + ci)] * + w[(size_t)wix]; + } + } + } + if (q.bias) acc += bias[(size_t)co]; + if (q.gelu) { + const float v = h_bf16(h_to_bf16(acc)); + acc = 0.5f * v * (1.0f + std::erf(v * 0.70710678118654752f)); + } + want[(size_t)((to * Wo + wo) * q.cout + co)] = acc; + } + check(q.gelu ? "conv2d_bf16 time-last bias gelu numerics" + : "conv2d_bf16 1 x W projection numerics", + down(dy, want.size()), want, 1e-2); + } + } + if (sel("conv2d_unfold_bf16")) { + /* The receptive fields of a [mel, time] 3x3 stride-2 convolution over one segment with + * a masked row, columns in the time-last weight's order. A copy: exact. */ + const RadKernelInfo* r = find(pl, "conv2d_unfold_bf16"); + if (!r) ok("conv2d_unfold_bf16", false, "row absent"); + else { + const int64_t M = 10, W = 6, cin = 5, Wo = 3, To = 5, K = cin * 9; + std::vector x = randv((size_t)(M * W * cin), 1.0f); + std::vector cu = { 0, (int32_t)M }; + std::vector valid((size_t)M, 1); + valid[4] = 0; + void* dx = up(x); + void* dcu = dalloc(8); + void* dv = dalloc((size_t)M * 4); + fill_i32(dcu, cu); + fill_i32(dv, valid); + void* dy = dalloc((size_t)(To * Wo * K) * 2); + std::vector ts = { T(dx, RAD_BF16, { M, W * cin }), T(dcu, RAD_I32, { 2 }), + T(dv, RAD_I32, { M }), + T(dy, RAD_BF16, { To * Wo, K }) }; + std::vector ps = { PI("M", M), PI("width", W), PI("cin", cin), + PI("kh", 3), PI("kw", 3), PI("stride", 2), + PI("pad", 1), PI("t_last", 1), PS("dtype", "bf16") }; + run_case(r, ts, ps); + std::vector want((size_t)(To * Wo * K), 0.0f); + for (int64_t to = 0; to < To; ++to) + for (int64_t wo = 0; wo < Wo; ++wo) + for (int64_t ci = 0; ci < cin; ++ci) + for (int64_t j = 0; j < 3; ++j) + for (int64_t i = 0; i < 3; ++i) { + const int64_t ti = to * 2 - 1 + i, wi = wo * 2 - 1 + j; + float v = 0.0f; + if (ti >= 0 && ti < M && wi >= 0 && wi < W && valid[(size_t)ti]) + v = x[(size_t)((ti * W + wi) * cin + ci)]; + want[(size_t)((to * Wo + wo) * K + (ci * 3 + j) * 3 + i)] = v; + } + check("conv2d_unfold_bf16 numerics", down(dy, want.size()), want, 1e-6); + } + } + if (sel("seg_sinusoid_bf16")) { + const RadKernelInfo* r = find(pl, "seg_sinusoid_bf16"); + if (!r) ok("seg_sinusoid_bf16", false, "row absent"); + else { + /* Two clips of 30 and 17 rows in units of 8, positions mod 13. */ + const int64_t M = 47, n = 64; + std::vector cu = { 0, 240, 376 }; + void* dcu = dalloc(cu.size() * 4); + fill_i32(dcu, cu); + void* dy = dalloc((size_t)(M * n) * 2); + std::vector ts = { T(dcu, RAD_I32, { 3 }), T(dy, RAD_BF16, { M, n }) }; + std::vector ps = { PI("M", M), PI("n", n), PI("period", 13), + PI("cu_div", 8), PS("dtype", "bf16") }; + run_case(r, ts, ps); + std::vector want((size_t)(M * n)); + const float inc = (float)(std::log(10000.0) / (double)(n / 2 - 1)); + for (int64_t row = 0; row < M; ++row) { + const int64_t p = (row < 30 ? row : row - 30) % 13; + for (int64_t i = 0; i < n / 2; ++i) { + const float ang = (float)p * std::exp((float)i * -inc); + want[(size_t)(row * n + i)] = std::sin(ang); + want[(size_t)(row * n + n / 2 + i)] = std::cos(ang); + } + } + check("seg_sinusoid_bf16 numerics", down(dy, want.size()), want, 5e-3); + } + } + if (sel("attn_dense_h64_bf16")) { + /* Blocks: two clips of 30 and 17 rows (cu_seqlens in units of 8), each cut into + * blocks of 13 rows from its start, attending within the block; 2 heads of 64 in one + * fused [q|k|v] row. Against a host softmax over the same bf16 inputs. */ + const RadKernelInfo* r = find(pl, "attn_dense_h64_bf16"); + if (r) { + const int64_t M = 47, H = 2, D = 64, width = 3 * H * D, blk = 13; + std::vector qkv = randv((size_t)(M * width), 1.0f); + std::vector cu = { 0, 240, 376 }; + void* dq = up(qkv); + void* dcu = dalloc(cu.size() * 4); + fill_i32(dcu, cu); + void* dout = dalloc((size_t)(M * H * D) * 2); + auto col = [&](int64_t first) { + RadTensor t = T(dq, RAD_BF16, { M, H * D }); + t.data = (void*)((uint16_t*)dq + first); + t.stride[0] = width; + return t; + }; + std::vector ts = { col(0), col(H * D), col(2 * H * D), + T(dcu, RAD_I32, { 3 }), + T(dout, RAD_BF16, { M, H * D }) }; + std::vector ps = { PI("M", M), PI("head_dim", D), PI("gqa", 1), + PI("causal", 0), PS("dtype", "bf16"), + PF("scale", 0.125), PI("max_seqlen", M), + PI("cu_div", 8), PI("block", blk) }; + run_case(r, ts, ps); + std::vector want((size_t)(M * H * D), 0.0f); + for (int64_t i = 0; i < M; ++i) { + const int64_t s0 = i < 30 ? 0 : 30, s1 = i < 30 ? 30 : M; + const int64_t b0 = s0 + (i - s0) / blk * blk; + const int64_t b1 = std::min(s1, b0 + blk); + for (int64_t h = 0; h < H; ++h) { + std::vector sc((size_t)(b1 - b0)); + double mx = -1e30; + for (int64_t j = b0; j < b1; ++j) { + double d = 0; + for (int64_t e = 0; e < D; ++e) + d += qkv[(size_t)(i * width + h * D + e)] * + qkv[(size_t)(j * width + H * D + h * D + e)]; + sc[(size_t)(j - b0)] = d * 0.125; + mx = std::max(mx, sc[(size_t)(j - b0)]); + } + double sum = 0; + for (auto& v : sc) { v = std::exp(v - mx); sum += v; } + for (int64_t e = 0; e < D; ++e) { + double a = 0; + for (int64_t j = b0; j < b1; ++j) + a += sc[(size_t)(j - b0)] * + qkv[(size_t)(j * width + 2 * H * D + h * D + e)]; + want[(size_t)(i * H * D + h * D + e)] = (float)(a / sum); + } + } + } + check("attn_dense_h64_bf16 blocks numerics", down(dout, want.size()), want, 2e-2); + } } if (sel("conv1d_dw_bf16")) { const RadKernelInfo* r = find(pl, "conv1d_dw_bf16"); @@ -13065,13 +13184,9 @@ static void device_phase(const Plugin& pl) { /* --- cast: the strided row copy an intermediate-hidden-state tap writes with ------------- * - * The destination is deliberately a COLUMN SLICE of a wider buffer, because that is the only - * thing about this row that can be wrong. A contiguous copy is uninteresting; a copy that has - * to honour a destination row pitch different from the source's is what puts five taps of the - * trunk's residual stream side by side in one [T, 5 * n_embd] row, and getting the pitch wrong - * writes a correct-looking tensor into the wrong columns. So the check is exact -- byte for - * byte, this is a copy -- and it asserts the UNTOUCHED columns too, since a kernel that - * ignored the pitch would fill them. */ + * The destination is a column slice of a wider buffer, as when five taps of the trunk's + * residual stream go side by side in one [T, 5 * n_embd] row; a wrong pitch writes the wrong + * columns. Checked byte for byte, including that the untouched columns keep their fill. */ if (sel("cast_bf16_bf16")) { const RadKernelInfo* r = find(pl, "cast_bf16_bf16"); if (!r) ok("cast_bf16_bf16", false, "row absent"); @@ -13085,13 +13200,13 @@ static void device_phase(const Plugin& pl) { if (!d_src || !d_dst) { ok("cast alloc", false, "hipMalloc failed"); } else { st_memcpy(d_src, src.data(), (size_t)M * n * 2, hipMemcpyHostToDevice); - /* A fill the copy must not spread: every untouched column has to still hold it. */ + /* A fill every untouched column must keep. */ std::vector fill((size_t)(M * wide), h_to_bf16(-7.5f)); st_memcpy(d_dst, fill.data(), (size_t)M * wide * 2, hipMemcpyHostToDevice); RadTensor ty = T(d_dst, RAD_BF16, { M, n }); ty.data = (void*)((uint16_t*)d_dst + slot * n); /* the slice's first element */ - ty.stride[0] = wide; /* ...at the WIDE row pitch */ + ty.stride[0] = wide; /* at the wide row pitch */ std::vector ts = { T(d_src, RAD_BF16, { M, n }), ty }; std::vector ps = { PI("M", M), PI("n", n), PS("from", "bf16"), PS("to", "bf16"), @@ -13127,7 +13242,7 @@ static void device_phase(const Plugin& pl) { RadTensor ty = T(d, RAD_BF16, { M, n }); ty.stride[0] = wide; std::vector ts = { ty }; - /* Default value: zero. The whole point of the op is that this is exactly 0x0000. */ + /* The default value, zero, must be exactly 0x0000. */ std::vector p0 = { PI("M", M), PI("n", n), PS("dtype", "bf16") }; run_case(r, ts, p0); std::vector got((size_t)(M * wide)); @@ -13155,11 +13270,9 @@ static void device_phase(const Plugin& pl) { } } /* --- byte rows: the KV tier's transfer pair --- */ - /* PACK AND UNPACK A POOL, which is the only thing these two are ever asked to do. The layout - * here is the real one in miniature: a "layer" is `rows` blocks of `n` bytes, the blocks a - * session holds are scattered through it, and what must come back is those blocks and nothing - * else. Bytes rather than a float dtype because a KV fragment is whatever the attention kernel - * wrote -- an exact comparison is the only meaningful one, and at u8 it is available. */ + /* Pack and unpack a pool, the real layout in miniature: a "layer" is `rows` blocks of `n` + * bytes, a session's blocks are scattered through it, and exactly those blocks must come back. + * Bytes, since a KV fragment holds arbitrary data and must compare exactly. */ if (sel("gather_rows_u8") || sel("scatter_rows_u8")) { const RadKernelInfo* rg = find(pl, "gather_rows_u8"); const RadKernelInfo* rs = find(pl, "scatter_rows_u8"); @@ -13195,10 +13308,8 @@ static void device_phase(const Plugin& pl) { pool[(size_t)(sel_blocks[m] * n + i)]) { gathered = false; break; } ok("gather_rows_u8 packs scattered blocks byte for byte", gathered); - /* Now scatter them back into a DIFFERENT pool prefilled with a marker, and the - * blocks nobody named have to still hold it. That is the property the whole op - * exists for: the destination is shared, and a restore that touched a row it was - * not given would be destroying another session's context. */ + /* Scatter them into a different pool prefilled with a marker; unnamed blocks must + * keep it, since the destination is shared with other sessions. */ std::vector mark((size_t)(rows * n), 0x5C); st_memcpy(d_pool, mark.data(), (size_t)rows * n, hipMemcpyHostToDevice); std::vector ts2 = { T(d_pack, RAD_U8, { M, n }), @@ -13325,19 +13436,16 @@ static void device_phase(const Plugin& pl) { T(nullptr, RAD_F32, { H }), /* dt_bias */ T(nullptr, RAD_F32, { N, H, V, K }), /* state */ TI32({ N }, iota_i32(N)), /* state_idx */ - /* num_accepted indexes the state-index ROW as `nacc - 1`, so a zero here is - * a read one int before the buffer. One accepted token is the decode step - * this case models. */ + /* num_accepted indexes the state-index row as `nacc - 1`, so zero would read + * one int before the buffer; one accepted token is a plain decode step. */ TI32({ N }, rep_i32(N, 1)), /* num_accepted */ TI32({ N + 1 }, cu_even(N, Td)), /* cu */ T(nullptr, RAD_BF16, { Td, H, V }), /* z */ T(nullptr, RAD_F32, { V }), /* norm_w */ T(nullptr, RAD_BF16, { Td, H, V }), /* o */ - /* THE FOLDED QUANTISER, present so the case covers it: absent, the kernel - * writes bf16 only and the two extra outputs are never compared. head_v is - * the fp8 block width, so the scale plane is one f32 a (token, value head) - * and ref quantises the bf16 it just stored -- which is what makes the two - * agree to the byte rather than to a tolerance. */ + /* The folded quantiser, present so it is covered. head_v is the fp8 block + * width, so the scale plane is one f32 per (token, value head), and ref + * quantises the bf16 it stored, so the two agree byte for byte. */ T(nullptr, RAD_F8E4M3, { Td, H * V }), /* o_q */ T(nullptr, RAD_F32, { Td, H }), /* o_scale */ }; @@ -13385,24 +13493,19 @@ static void device_phase(const Plugin& pl) { }; run_case(r, ts, ps); } - /* The drafter's own shape (block 8, 5120 channels) and a wider block, because the tap - * mask is the block position and a block of 16 exercises a different mask. */ + /* The drafter's own shape (block 8, 5120 channels) and a block of 16, whose tap mask + * differs. */ dflash_conv_numeric(pl, 64, 256, 16, 2, 16); dflash_conv_numeric(pl, 32, 5120, 16, 2, 8); } - /* --- dflash select: NUMERIC, because the thing worth testing is the CHAINING. + /* --- dflash select, numerically: the chaining is what is tested. * - * The walk's whole reason to exist is that step l's score depends on the token step l-1 chose. - * A kernel that scored every step against the anchor instead would still emit K plausible ids - * per sequence, in range, in the right shape -- and the drafter would simply accept less. So - * the case is built to distinguish the two: it asserts the chained path AND asserts that an - * anchor-pinned walk over the same data would have produced a different one, which is what - * makes the first assertion mean something. + * Step l's score depends on the token step l-1 chose. A kernel scoring every step against the + * anchor would still emit plausible ids, and the drafter would just accept less. So the case + * asserts the chained path and that an anchor-pinned walk over the same data differs. * - * Every value is a power of two times a quarter, so the f32 accumulation is EXACT whatever - * order the wave reduces in and the expected path is a comparison of exact integers rather - * than a tolerance. */ + * Every value is a power of two times a quarter, so f32 accumulation is exact in any order. */ if (sel("dflash_select_bf16")) { const RadKernelInfo* r = find(pl, "dflash_select_bf16"); if (!r) ok("dflash_select_bf16", false, "row absent"); @@ -13412,11 +13515,9 @@ static void device_phase(const Plugin& pl) { auto sv = [](int64_t t) { return 0.25f * (float)(t % 4); }; auto cnd = [&](int64_t row, int64_t c) { return (int32_t)((row * 7 + c * 10) % V); }; auto unf = [&](int64_t row, int64_t c) { return 8.0f * (float)((row + c * 3) % 5); }; - /* STRIDED, because that is how the drafter passes it: the operand is the step's own - * token_ids, which carries `block` ids a sequence with the anchor first. The entries - * between the anchors are mask tokens, and reading one instead would be a plausible - * walk from the wrong predecessor -- so they are filled with a value that would give a - * different answer if the stride were ignored. */ + /* Strided, as the drafter passes it: the step's token_ids, `block` ids per sequence + * with the anchor first. The entries between anchors (mask tokens) hold a value that + * changes the answer if the stride is ignored. */ const int64_t astride = steps + 1; const int32_t anchor[2] = { 2, 2 }; std::vector h_anc((size_t)(M * astride), 7); @@ -13499,16 +13600,11 @@ static void device_phase(const Plugin& pl) { ok("dflash_select_bf16 case can tell a chained walk from an anchor-pinned one", distinguishes); - /* THE BIGRAM FORM, which is why `hp` is optional: DSpark's Markov head is this - * walk with no hidden projection. `hp` above is a plane of - * EXACT ones, so absent has to give bit-identical tokens -- a kernel that read a - * null pointer, or skipped the multiply in one branch and not the other, moves - * some token here and none of it would show up as anything but acceptance. */ + /* The bigram form (`hp` absent), DSpark's Markov head. `hp` above is exact ones, + * so absent must give bit-identical tokens. */ std::vector tb = ts; - /* `absent`, NOT a null `data` with the rank left on: run_case allocates for any - * tensor that has a rank and no pointer, so spelling it the other way hands the - * kernel a plane of UNINITIALISED memory and tests the present branch against - * garbage rather than withholding the operand. */ + /* `absent`, not just a null `data`: run_case allocates any tensor with a rank and + * no pointer, which would pass uninitialised memory instead of no operand. */ absent(tb[2]); st_memcpy(d_out, h_cand.data(), (size_t)M * steps * 4, hipMemcpyHostToDevice); run_case(r, tb, ps); @@ -13569,16 +13665,16 @@ static void device_phase(const Plugin& pl) { gemm_case(pl, "gemm_w2a8_nt", "w2a8", M, N, K, RAD_I8, 1, 1, 0, N*K/4, N*(K/128)*4); gemm_case(pl, "gemm_mxfp4a8_nt_m64", "mxfp4a8", M, N, K, RAD_F8E4M3, 1, 0, 1, N*K/2, (K/32)*N); gemm_case(pl, "gemm_mxfp4a8_tiled", "mxfp4a8", 256, 256, K, RAD_F8E4M3, 1, 0, 1, 256*K/2, (K/32)*256); - /* The skinny row is known-good, so it checks the check; the tiled row at both widths, ragged - * in M and N, then at the size where tn=0 crosses over to TN=4. */ + /* The skinny row first (validating the check), then the tiled row at both widths, ragged + * in M and N, and at the size where tn=0 crosses over to TN=4. */ mxfp4a8_numeric(pl, "gemm_mxfp4a8_nt_m64", 40, 272, 640, 0); mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 40, 272, 640, 2); mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 272, 640, 2); mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 400, 640, 4); mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 2100, 512, 2560, 0); - /* ...and against the fp8 family's (row, 128) activation grid, which is what an architecture - * feeds them. K = 640 is five blocks and 2560 twenty, so every split-K segment of the - * skinny row and every slab pair of the tiled one crosses block boundaries. */ + /* And with the fp8 family's (row, 128) activation grid, as architectures feed them. K = 640 + * is five blocks and 2560 twenty, so split-K segments and slab pairs cross block + * boundaries. */ mxfp4a8_numeric(pl, "gemm_mxfp4a8_nt_m64", 40, 272, 640, 0, true); mxfp4a8_numeric(pl, "gemm_mxfp4a8_nt_m64", 7, 512, 2560, 0, true); mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 272, 640, 2, true); @@ -13587,17 +13683,17 @@ static void device_phase(const Plugin& pl) { /* K not a multiple of 128: the TN=2 kernel takes the 64-wide slab. */ mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 272, 576, 2); mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 272, 576, 2, true); - /* The decode row over its whole band: the split rule's own choice, then every split and - * slab forced, at both activation grids; N past a 128-column block, K a multiple of 64 - * but not 128 (the slab falls back to 64), and DTM 1..4. */ + /* The decode row over its band: the split rule's choice, then every split and slab forced, + * at both activation grids; N past a 128-column block, K a multiple of 64 but not 128 (the + * slab falls back to 64), and DTM 1..4. */ mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 8, 272, 640, 0, false); mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 8, 272, 640, 0, true); mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 40, 400, 2560, 0, true); mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 64, 512, 2560, 0, true); mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 5, 1040, 576, 0, true); mxd_overlap_case(pl); - /* PARTS (ParoQuant): each part of the weight against its own copy of the activation, with - * bounds that do not fall on a tile of any kernel's, two parts and three, at every band. */ + /* 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); mxfp4a8_numeric(pl, "gemm_mxfp4a8_nt_m64", 40, 400, 640, 0, true, {}, 144, 288); mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 8, 400, 2560, 0, true, {}, 128); @@ -13607,9 +13703,9 @@ static void device_phase(const Plugin& pl) { mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 400, 640, 4, true, {}, 96, 304); mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 2100, 512, 2560, 0, true, {}, 256); mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 34816, 5120, 0, true, {}, 17408); - /* Above 64 rows, every branch of the measured table: 110+ column blocks, 48+, 8 or - * fewer (with a K that is not a multiple of 128, so the slab falls back to 64), a deep K - * on both sides of M=80, and the plain case; then every split and slab forced. */ + /* Above 64 rows, every branch of the split table: 110+ column blocks, 48+, 8 or fewer + * (with K not a multiple of 128, so the slab falls back to 64), a deep K on both sides of + * M=80, and the plain case; then every split and slab forced. */ mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 96, 14336, 640, 0, true); mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 128, 6144, 1152, 0, true); mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 100, 1024, 576, 0, true); @@ -13624,8 +13720,8 @@ static void device_phase(const Plugin& pl) { for (int bk : { 64, 128 }) mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 24, 400, 2560, 0, true, { PI("ks", ks), PI("bk", bk), PI("nt", ks == 2 ? 2 : 1) }); - /* ...and the one-fragment form (DTM = 1: the register prefetch and 16 B loads) at every - * split, slab and load hint, on both activation grids, N past a column block. */ + /* And the one-fragment form (DTM = 1: register prefetch, 16 B loads) at every split, slab + * and load hint, on both activation grids, N past a column block. */ for (int ks : { 1, 2, 4, 8, 16 }) for (int bk : { 64, 128 }) for (int nt : { 1, 2 }) { @@ -13638,10 +13734,9 @@ static void device_phase(const Plugin& pl) { gemm_case(pl, "gemm_w8a8_tiled", "w8a8", 256, 256, K, RAD_I8, 1, 0, 0, 256*K, 256*(K/128)*2); gemm_case(pl, "gemm_w4a8_prefill", "w4a8", 256, 256, K, RAD_I8, 1, 0, 0, 256*K/2, 256*(K/128)*4); - /* Block-scaled fp8. The matvec is smoked at every point of its space because `rb` is the - * only axis in the family and each value is a different instantiation of the K loop. The - * narrow W8A8 row needs K a multiple of 256 -- 512 is -- and the tiled one needs N a - * multiple of 128. */ + /* Block-scaled fp8. The matvec runs at every point of its space (each `rb` is a different + * instantiation of the K loop). The shapes give the narrow W8A8 row K a multiple of 256 + * and the tiled one N a multiple of 128. */ for (const TunePoint& tp : tune_points(find(pl, "gemm_fp8a16_nt_m1"), std::vector{ PI("M", 1), PI("N", N), PI("K", K), PI("group", 128), @@ -13674,19 +13769,16 @@ static void device_phase(const Plugin& pl) { const RadKernelInfo* r = find(pl, "sample_chain_f32"); if (!r) ok("sample_chain_f32", false, "row absent"); else { - /* The vocabulary is deliberately not a round number: the radix passes are over a - * float's bytes and a power-of-two width would hide an off-by-one in the stride. */ + /* Not a power-of-two vocabulary, which could hide an off-by-one in the stride. */ const int64_t M = 4, V = 1000; - /* TWO uniforms a position, and they must be IN [0,1): dalloc zeroes, and a uniform - * of exactly 0 walks the inverse CDF to the first kept token every time -- which is - * a valid draw, so the smoke test would pass with the walk broken. */ + /* Two uniforms per position in [0,1). Zeros (as dalloc returns) would always select + * the first kept token and pass with the walk broken. */ std::vector uh((size_t)(2 * M)); for (size_t i = 0; i < uh.size(); ++i) uh[i] = 0.11f + 0.17f * (float)i; RadTensor tu = T(nullptr, RAD_F32, { 2 * M }); tu.data = alloc_for(tu); if (tu.data) st_memcpy(tu.data, uh.data(), uh.size() * 4, hipMemcpyHostToDevice); - /* `draw` is three 32-bit words a position. The schema names one operand, not three, - * because the kernel writes a struct -- so it is sized here in words. */ + /* `draw` is three 32-bit words per position (a struct), sized in words. */ std::vector ts = { T(nullptr, RAD_F32, { M, V }), T(nullptr, RAD_U32, { M }), @@ -13698,15 +13790,14 @@ static void device_phase(const Plugin& pl) { PF("min_p", 0.0), PI("k", 40), }; run_case(r, ts, ps); - /* Temperature 0 is a REAL path, not a caller special case: it must give the argmax - * with the same lowest-id tie-break a greedy run uses, and a zeroed logits plane is - * exactly the all-ties input that catches a tie-break that disagrees. */ + /* Temperature 0 must give the argmax with greedy's lowest-id tie-break; a zeroed + * logits plane is the all-ties input that checks it. */ std::vector ps0 = { PI("M", M), PI("n_vocab", V), PF("temp", 0.0), PF("p", 1.0), PF("min_p", 0.0), PI("k", 0), }; run_case(r, ts, ps0); - /* ...and with no draft proposal, which is the last position of a verify block. */ + /* And with no draft proposal, as at the last position of a verify block. */ absent(ts[1]); run_case(r, ts, ps); } @@ -13845,18 +13936,13 @@ static void device_phase(const Plugin& pl) { rowtopk_shard_case(pl); } - /* dequant_w4_bf16's case IS the round-trip: the row's only caller here is the check that the - * host relayout and libr4d's own dequant agree, so naming the case for the row keeps the one - * case-name-is-a-row-name rule that makes the coverage check below work. */ + /* dequant_w4_bf16's case is the w4 round trip, named for the row so the coverage check sees + * it. */ if (sel("dequant_w4_bf16")) { if (!g_case) std::printf("\nweight layout, against libr4d's own inverse\n"); w4_roundtrip(pl); } - /* The 4-bit grouped MoE GEMM gets its OWN case name, which is the rule the coverage check - * below enforces -- a row with no case of its own is reported as a hole. Nesting it inside - * another row's block makes it invisible and says nothing about it: a child process is - * spawned per row and `sel` is false for every name but that child's own. */ if (sel("sample_argmax_f32")) { if (!g_case) std::printf("\nthe greedy sampler, against a host scan\n"); sample_argmax_case(pl); @@ -13880,12 +13966,13 @@ static void device_phase(const Plugin& pl) { qsa_select_split_one(pl, "qsa_select split across chunks vs the same launch unsplit", 1, 4); qsa_select_split_one(pl, "qsa_select split, two sequences of four draft rows", 2, 4); + qsa_select_few_live_case(pl); } if (sel("qsa_score_bf16")) { if (!g_case) std::printf("\nthe QSA block score, against the formula it implements\n"); - /* EVERY FORM THE ROW HAS: the launcher picks one by shape, and a form the rule does not - * pick for these shapes is the one another model's shape would get. */ + /* Every form of the row: the launcher picks by shape, and another model's shape may get + * a form the rule does not pick here. */ for (int f = pl.pin_qsa ? 1 : 0; f <= (pl.pin_qsa ? 2 : 0); ++f) { if (pl.pin_qsa) { pl.pin_qsa(f); @@ -13928,29 +14015,28 @@ static void device_phase(const Plugin& pl) { rope_ladder_case(pl); } + /* Each row needs a case under its own name: a child runs per row and `sel` matches only that + * name, so a case nested in another row's block would never run. */ if (sel("moe_gemm_w4a8")) { if (!g_case) std::printf("\nthe 4-bit grouped MoE GEMM, against a host decode\n"); - /* One geometry; a gate/up pair whose odd experts are half as wide; a down projection - * whose odd experts are half as long; and a decode-shaped routing -- a few runs over - * hundreds of experts, most of them empty -- which is what the decode grid's run search - * has to find its way through. */ + /* One geometry; a gate/up pair whose odd experts are half as wide; a down projection whose + * odd experts are half as long; and a decode-shaped routing (a few runs over hundreds of + * mostly empty experts) for the decode grid's run search. */ static const MoeW4Shape kShapes[] = { { "one class", 64, 256, 64, 256, 1, 5 }, { "gate/up 2:1", 256, 256, 128, 256, 2, 5 }, { "down 2:1", 64, 256, 64, 128, 1, 5 }, { "300 experts, gate/up 2:1", 256, 128, 128, 128, 2, 300 }, - /* Three passes of 256 along K: the decode form's two-block pass then also runs its - * one-ahead prefetch, which a single pass never reaches. */ + /* Three passes of 256 along K, so the two-block pass also runs its one-ahead + * prefetch. */ { "40 experts, gate/up 2:1, K 768", 256, 768, 128, 768, 2, 40 }, - /* Past 512 experts: the decode form's chunked run search, which the one-round-trip - * search hands every wider expert count to. Runs land on experts on both sides of - * 512, and K 256 lets the two-block pass run on that search as well. */ + /* Past 512 experts: the decode form's chunked run search. Runs land on both sides of + * 512, and K 256 lets the two-block pass run on that search too. */ { "640 experts, gate/up 2:1, K 256", 256, 256, 128, 256, 2, 640 }, - /* The down projection as a rank of four runs it: the sorted operand, one part, the - * classes at 256 and 128 of K -- and a width of whole 256-column tiles, which is what - * the aligned form's 256-column down tile takes. Then with the odd class half as wide, - * so that tile is padding for every odd expert's run; and at 512 experts, whose - * n_expert + 1 block counts the run map scans in three 256-count tiles. */ + /* The down projection as a rank of four runs it: sorted operand, one part, classes at + * 256 and 128 of K, width in whole 256-column tiles (the aligned form's down tile). + * Then with the odd class half as wide (that tile is padding for odd experts), and at + * 512 experts, whose n_expert + 1 counts the run map scans in three 256-count tiles. */ { "down, sorted rows, 512 x K 256:128", 512, 256, 512, 128, 1, 10, true }, { "down, sorted rows, 512:256 x K 256:128", 512, 256, 256, 128, 1, 10, true }, { "512 experts, down, sorted rows, 256 x K 128", 256, 128, 256, 128, 1, 512, true }, @@ -13970,8 +14056,8 @@ static void device_phase(const Plugin& pl) { if (sel("moe_gemm_w4a8_mod4")) { if (!g_case) std::printf("\nthe 4-bit grouped MoE GEMM over four classes, against its " "two-class form and a host decode\n"); - /* The same shapes, read as four classes: the even table's halves are classes 0 and 2 and - * the odd one's 1 and 3, so the two-class launch is the reference, byte for byte. */ + /* The same shapes read as four classes (the even table's halves are classes 0 and 2, the + * odd one's 1 and 3), against the two-class launch byte for byte. */ static const MoeW4Shape kShapes4[] = { { "one class", 64, 256, 64, 256, 1, 5 }, { "gate/up 2:1", 256, 256, 128, 256, 2, 10 }, @@ -13996,9 +14082,9 @@ static void device_phase(const Plugin& pl) { for (const int64_t t : { (int64_t)24, (int64_t)200, (int64_t)600 }) for (const char* dt : { "w4a8", "w4nl64a8h", "w4nl32a8h", "w5nl64a8h" }) moe_q4_gemm(pl, t, sh, dt); - /* The sorted operand at decode, and its own kernel against the (tile, run) form: one - * sequence at depth 3 (T 40), five, sixteen and nineteen -- each side of both of the - * rule's column-tile thresholds. */ + /* The sorted operand at decode, its own kernel against the (tile, run) form: one sequence + * at depth 3 (T 40), then five, sixteen and nineteen, either side of both of the rule's + * column-tile thresholds. */ moe_down_dec_case(pl, kMoeDnShapes[0], "w4nl64a8h", { 40, 200, 640, 760 }); for (const char* dt : { "w4a8", "w4nl64a8h", "w4nl32a8h", "w5nl64a8h" }) moe_down_dec_case(pl, kMoeDnShapes[1], dt, { 40, 96 }); @@ -14016,10 +14102,10 @@ static void device_phase(const Plugin& pl) { if (sel("hc_read_e4m3")) { if (!g_case) std::printf("\nthe gated residual's read at the prefill tile, every form " "against the decode tiles'\n"); - /* 700 and 1000 put PF2's K chunks across a stream boundary and its row tiles past the - * last row; 4096 is the one-chunk epilogue. */ + /* 700 and 1000 put PF2's K chunks across a stream boundary and row tiles past the last + * row; 4096 is the one-chunk epilogue. */ for (int64_t m : { 65, 300, 700, 1000, 2048, 4096 }) hc_prefill(pl, m, 0, false); - /* 1 to 7 rows are one up-product row group each, every instantiation below eight. */ + /* 1 to 7 rows each hit a different up-product instantiation below eight. */ for (int64_t m : { 1, 2, 3, 4, 5, 6, 7, 33, 65, 300, 2048 }) { hc_read_i8(pl, m, false, 0); hc_read_i8(pl, m, true, 0); @@ -14113,10 +14199,9 @@ static void device_phase(const Plugin& pl) { if (sel("moe_gemm_bf16")) { if (!g_case) std::printf("\nthe bf16 grouped MoE GEMM, against an f64 host product\n"); - /* Qwen3.8-Flash-Next's and Qwen3.6-35B-A3B's whole-expert widths at a few experts each -- - * what fits beside a running server -- and the expert counts that exercise the run map - * and the decode grid's run search at small widths. A width that does not take the - * 128-column tile runs the 64-column one. */ + /* Qwen3.8-Flash-Next's and Qwen3.6-35B-A3B's whole-expert widths at a few experts each, and + * expert counts exercising the run map and decode run search at small widths. A width + * without the 128-column tile runs the 64-column one. */ static const MoeBf16Shape kShapes[] = { { "Flash-Next gate_up 1280x2560", 1280, 2560, 4, 2, false }, { "Flash-Next down 2560x640", 2560, 640, 4, 2, true }, @@ -14143,45 +14228,34 @@ static void device_phase(const Plugin& pl) { } if (sel("dequant_w4_bf16")) { - /* TWO SHAPES, and the second is the one the model actually runs: N = 256 is the k and v - * projections, gate_up is 17408 rows. Both wave counts run here without asking for them, - * because narrow_mw is a function of M and the M list inside fp8_numeric crosses its - * threshold -- 1 and 8 take MW = 4, 24 through 64 take MW = 8. The second shape is only - * reachable because the generator above wraps its exponent. */ + /* N = 256 (the k and v projections) and 17408 (gate_up). narrow_mw depends on M, and + * fp8_numeric's M list crosses its threshold (1 and 8 take MW = 4, 24-64 take MW = 8). */ fp8_numeric(pl, 256, 512); fp8_numeric(pl, 17408, 512); fp8_numeric(pl, 5120, 5120); - /* THE ONE PRODUCTION REGIME THE OTHERS MISS: many K tiles with split-K OFF. (256,512) and - * (17408,512) are two staged tiles, and (5120,5120) splits. gate_up is 17408 rows by 5120, - * which is twenty tiles and gx*mw over the split threshold -- so the prefetch fires - * nineteen times and nothing else here makes it fire more than once. */ + /* Many K tiles with split-K off: gate_up, 17408 x 5120, is twenty tiles with gx*mw over the + * split threshold, so the prefetch fires nineteen times ((256,512) and (17408,512) have + * two tiles; (5120,5120) splits). */ fp8_numeric(pl, 17408, 5120); - /* The two remaining production K values: the GDN out-projection reads K = v_dim = 1536 - * per rank, and down_proj reads K = n_ff = 8704. Both are multiples of 256 and 64, and - * neither falls out of the shapes above. */ + /* The remaining production K values: the GDN out-projection (K = v_dim = 1536 per rank) + * and down_proj (K = n_ff = 8704). */ fp8_numeric(pl, 5120, 1536); fp8_numeric(pl, 5120, 8704); - /* A SHARED EXPERT SPLIT BY WHOLE SCALE BLOCKS gives each rank a width the even split never - * does: Qwen3.8-Flash-Next's 640 columns go 384 / 256, so the down projection runs at - * K = 384 -- a multiple of 128 and not of 256, which is the narrow tile's 128-wide leg -- - * and K = 256, and the gate/up projection at N = 768 and N = 512 over K = 2560. */ + /* A shared expert split by whole scale blocks: Qwen3.8-Flash-Next's 640 columns go 384 / + * 256, so the down projection runs at K = 384 (a multiple of 128, not 256: the narrow + * tile's 128-wide leg) and K = 256, and gate/up at N = 768 and 512 over K = 2560. */ fp8_numeric(pl, 2560, 384); fp8_numeric(pl, 2560, 256); fp8_numeric(pl, 768, 2560); fp8_numeric(pl, 512, 2560); - /* The lm_head. 5120 rows stands in for 124160 -- the kernel walks rows with a grid-stride - * loop, so the row count is not what varies -- and M spans the exact instantiations, the - * rounded-up ones, and the cap. */ + /* The lm_head. 5120 rows stand in for 124160 (rows are walked with a grid-stride loop); + * M spans the exact instantiations, the rounded-up ones and the cap. */ for (const int64_t M : { (int64_t)1, (int64_t)8, (int64_t)13, (int64_t)32, (int64_t)33, (int64_t)64 }) fp8_logits_numeric(pl, 5120, 5120, M); - /* AND K = 2560, WHICH IS THE PADDED ROW. 5120's stored width is 5200 and already a - * multiple of 16; 2560's is 2600 and is not, so r4d_fp8_lm.h rounds it to 2608 and every - * odd row moves by eight bytes. That padding is invisible to any shape that does not need - * it, so without this case the layout, the relayout, its inverse and both kernels' - * strides agree on a number none of them was ever asked to derive. M = 1 takes the - * matvec, M = 8 the WMMA tile: the pad has to be right in both, and they index the row - * differently. */ + /* And K = 2560, the padded row: its stored width 2600 is not a multiple of 16, so + * r4d_fp8_lm.h rounds it to 2608 (5120's 5200 needs no pad). M = 1 takes the matvec, M = 8 + * the WMMA tile, which index the row differently. */ for (const int64_t M : { (int64_t)1, (int64_t)8, (int64_t)33 }) fp8_logits_numeric(pl, 2560, 2560, M); } @@ -14193,8 +14267,8 @@ static void device_phase(const Plugin& pl) { fp8_logits_numeric(pl, 2560, 2560, M, true); } - /* The fused quantisers are checked against the kernels they replace rather than against a host - * mirror, so they live outside `fp8_numeric` and are gated on their own row. */ + /* The fused quantisers are checked against the kernels they replace, gated on their own + * rows. */ if (sel("rmsnorm_quant_fp8") || sel("gated_quant_fp8") || sel("gate_quant_fp8")) { if (!g_case) std::printf("\nthe fp8 fusions, against the pair each one replaces\n"); fused_quant_fp8_numeric(pl); @@ -14212,20 +14286,15 @@ static void device_phase(const Plugin& pl) { rmsnorm_quant_i8_numeric(pl); } - /* The MTP head's fc is K=10240; the DFlash2 drafter's is 25600, the largest K any shape in - * the tree asks these kernels for. - * - * BOTH ROWS, because one op's band splits across both of them: an fc declared over M 1..64 - * resolves to _m16 for the small issues and _m64 for the wide ones, and the two are separate - * kernels with separate split laws. Checking only the one named in the declaration tests a - * kernel that never runs and leaves the one that does unchecked. */ + /* The MTP head's fc is K=10240; the DFlash2 drafter's is 25600, the largest K any shape asks + * these kernels for. Both rows run: an fc declared over M 1..64 resolves to _m16 for small + * issues and _m64 for wide ones, separate kernels with separate split laws. */ if (sel("gemm_bf16_nt_m16") || sel("gemm_bf16_nt_m64")) { if (!g_case) std::printf("\nthe skinny bf16 GEMMs, against a host reference\n"); for (const char* row : { "gemm_bf16_nt_m16", "gemm_bf16_nt_m64" }) { bf16_gemm_numeric(pl, row, 5, 32, 10240); bf16_gemm_numeric(pl, row, 5, 32, 25600); - /* The drafter's fc, exactly: N and K together, because the weight offset a lane - * computes is row * K and only the pair is large. */ + /* The drafter's fc exactly: the weight offset row * K is large only for the pair. */ bf16_gemm_numeric(pl, row, 5, 5120, 10240); bf16_gemm_numeric(pl, row, 5, 5120, 25600); bf16_gemm_numeric(pl, row, 16, 5120, 25600); @@ -14237,59 +14306,78 @@ static void device_phase(const Plugin& pl) { bf16_tiled_identity(pl, 2048, 512, 2560); /* the MoE router: four slices */ bf16_tiled_identity(pl, 1000, 2560, 2560); /* the PLE value projection: one slice */ bf16_tiled_identity(pl, 333, 1040, 2560); /* ragged M and N, two slices */ - bf16_tiled_identity(pl, 77, 128, 64); /* a slice a k step, the band's floor */ + bf16_tiled_identity(pl, 77, 128, 64); /* one slice per k step, the band's floor */ bf16_gemm_numeric(pl, "gemm_bf16_nt_tiled", 300, 1040, 2560); } /* Every collective has a host twin (r4d_rows.cpp): the same kernel with its mailbox in pinned * host memory. A case is the pair's, so the twin is held to exactly the original's checks. */ + /* The 2-rank pair keeps its own harness: its flag layout and its block ceiling are not the + * wide family's, and TP2 is what the fleet runs today. Everything at three and four goes + * through the width-parameterized functions, which take the world from the base's own name and + * skip themselves, named for the width they need, when the box has fewer cards. */ for (const char* base : { "ar_oneshot_2rank_exact", "ar_gather_2rank", "ar_oneshot_3rank_exact", - "ar_twoshot_3rank_exact", "ar_twoshot_3rank_ti8", "ar_gather_3rank" }) { + "ar_twoshot_3rank_exact", "ar_twoshot_3rank_ti8", "ar_gather_3rank", + "ar_oneshot_4rank_exact", "ar_twoshot_4rank_exact", + "ar_twoshot_4rank_ti8", "ar_gather_4rank" }) { for (const std::string& n : { std::string(base), std::string(base) + "_host" }) { if (!sel(n.c_str())) continue; - const bool three = std::strstr(base, "3rank") != nullptr; - if (!g_case) std::printf(three ? "\ncross-rank, three\n" : "\ncross-rank\n"); + const int world = std::strstr(base, "4rank") ? 4 + : std::strstr(base, "3rank") ? 3 : 2; + if (!g_case) { + if (world == 2) std::printf("\ncross-rank\n"); + else std::printf("\ncross-rank, %d\n", world); + } std::printf(" %s\n", n.c_str()); - 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()); - } else if (!std::strcmp(base, "ar_gather_2rank")) { - gather_two_rank(pl, devs, n.c_str()); - /* The wide family at three. Its own rows, so the sweep names them (a row the sweep - * never mentions is reported as a coverage hole) and so `--case - * ar_oneshot_3rank_exact` reproduces one of them alone. */ - } else if (three && std::strstr(base, "gather")) { - gather_three_rank(pl, devs, n.c_str()); - } else if (three && std::strstr(base, "ti8")) { - ar_three_rank_ti8(pl, devs, n.c_str()); - } else if (three && std::strstr(base, "twoshot")) { - ar_three_rank_pattern(pl, devs, n.c_str()); + if (world == 2) { + 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()); + } else { + gather_two_rank(pl, devs, n.c_str()); + } + /* Its own rows, so the sweep names them (a row the sweep never mentions is reported as + * a coverage hole) and so `--case ar_oneshot_4rank_exact` reproduces one alone. */ + } else if (std::strstr(base, "gather")) { + gather_wide_rank(pl, devs, n.c_str(), world); + } else if (std::strstr(base, "ti8")) { + ar_wide_ti8(pl, devs, n.c_str(), world); + } else if (std::strstr(base, "twoshot")) { + ar_wide_pattern(pl, devs, n.c_str(), world); } else { - ar_three_rank(pl, devs, n.c_str()); + ar_wide_rank(pl, devs, n.c_str(), world); /* The one-shot through the same per-element oracle: both rows of the op agree * with it, so they agree with each other at every size either could be given. */ - ar_three_rank_pattern(pl, devs, n.c_str()); + ar_wide_pattern(pl, devs, n.c_str(), world); } } } - /* The 4- and 8-rank rows cannot be exercised on a two-card box. Reported as skipped rather + /* The fused write rows at both widths and both gathers. The `_host` twins take the same + * calls; they differ only in where the mailbox lives. */ + for (const char* base : { "ar_hc_write", "ar_gather_hc_write", + "ar_hc_write_4rank", "ar_gather_hc_write_4rank" }) { + for (const std::string& n : { std::string(base), std::string(base) + "_host" }) { + if (!sel(n.c_str())) continue; + if (!g_case) std::printf("\ncross-rank, fused with the gated residual write\n"); + std::printf(" %s\n", n.c_str()); + ar_hc_write_case(pl, devs, n.c_str(), std::strstr(base, "4rank") ? 4 : 2, + std::strstr(base, "gather") != nullptr); + } + } + /* The 8-rank rows cannot be exercised on a four-card box. Reported as skipped rather * than quietly passing: a row that has never been launched is not a row that works. */ auto skip_pair = [](const char* base, const char* why) { for (const std::string& n : { std::string(base), std::string(base) + "_host" }) if (sel(n.c_str())) skip(n.c_str(), why); }; - for (const char* n : { "ar_oneshot_4rank_exact", "ar_oneshot_8rank_exact", - "ar_twoshot_4rank_exact", "ar_twoshot_8rank_exact", - "ar_twoshot_4rank_ti8" }) - skip_pair(n, "needs 4 or 8 cards"); + /* Only the 8-rank rows now: the four-rank ones are dispatched above and skip themselves with + * the width they need. */ + for (const char* n : { "ar_oneshot_8rank_exact", "ar_twoshot_8rank_exact", "ar_gather_8rank" }) + skip_pair(n, "needs 8 cards"); skip_pair("ar_oneshot_2rank_wht6", "lossy wire: needs a tolerance harness, not a smoke test"); skip_pair("ar_ln_had_quant_i8", "two-rank fusion: needs the same harness as the wht6 wire"); - /* Same reason, and one more: the norm half of it is rmsnorm_quant_fp8's, called through the - * same device function, so what a single-rank harness could check here is already checked - * there. What it cannot check without a peer -- the handshake and the reduced sum -- is what - * the two-rank harness is for. The engine covers it end to end: a decode step issues this op - * at every one of the 128 sites, and the generated text is compared byte for byte against a - * build that issues the pair instead. */ + /* Also skipped: the norm half is rmsnorm_quant_fp8's device function, checked there, and the + * handshake and reduced sum need a peer rank. */ skip_pair("ar_rmsnorm_quant_fp8", "two-rank fusion: needs a peer rank"); skip_pair("ar_rmsnorm_quant_i8", "two-rank fusion: needs a peer rank"); @@ -14298,14 +14386,12 @@ static void device_phase(const Plugin& pl) { /* ------------------------------------------------------------------ the isolating driver * - * The row table is the case list. Every case above is named for a row, so a row the sweep never - * mentions comes back from its child as "no smoke case" and the coverage hole is visible without - * a second list to keep in step with the first. + * The row table is the case list. Every case is named for a row, so a row no case mentions comes + * back from its child as "no smoke case". */ -/* The number as well as the name: a GPU page fault does not always come out of ROCr as SIGABRT, - * and "signal" on its own tells the reader nothing about which. The fault line itself is on - * stderr, unbuffered, immediately above this. */ +/* The signal's number and name (a GPU page fault is not always SIGABRT). The fault line itself + * is on stderr, unbuffered, just above. */ static std::string signame(int sig) { const char* n = nullptr; switch (sig) { @@ -14321,10 +14407,8 @@ static std::string signame(int sig) { } static void run_isolated(const Plugin& pl, const char* exe, const char* plugin) { - /* The inventory belongs to the parent: the children print one line each and repeating it - * forty times buries them. A host can present more HIP devices than it has discrete cards -- - * an integrated part reporting tens of GiB of "VRAM" that is really system RAM -- so seeing - * the list once is worth the parent touching HIP at all. */ + /* The device inventory is printed once, by the parent (an integrated part can appear beside + * the discrete cards). */ int nd = 0; if (hipGetDeviceCount(&nd) == hipSuccess) { for (int d = 0; d < nd; ++d) { @@ -14343,8 +14427,7 @@ static void run_isolated(const Plugin& pl, const char* exe, const char* plugin) const_cast("--case"), const_cast(name.c_str()), nullptr }; pid_t pid = 0; - /* posix_spawn, not fork: this process already has the HIP runtime and its worker threads - * up, and only the exec resets them in the child. */ + /* posix_spawn, not fork: the HIP runtime's threads are up, and only exec resets them. */ if (posix_spawn(&pid, exe, nullptr, nullptr, argv, environ) != 0) { ok(name.c_str(), false, "posix_spawn failed"); continue; @@ -14359,8 +14442,8 @@ static void run_isolated(const Plugin& pl, const char* exe, const char* plugin) } if (!WIFEXITED(st)) { ok(name.c_str(), false, "child did not exit normally"); continue; } switch (WEXITSTATUS(st)) { - case CH_OK: break; /* the child already printed its ok line */ - case CH_FAIL: ++g_fail; break; /* and its FAIL line, with the detail */ + case CH_OK: break; /* the child printed its ok line */ + case CH_FAIL: ++g_fail; break; /* and its FAIL line, with detail */ case CH_SKIP: ++g_skip; break; default: ok(name.c_str(), false, @@ -14388,8 +14471,7 @@ static void usage(void) { " reference over the same bytes. An offset is 8 +

+ the tensor's own data_offsets[0].\n" " --perf N K M [iters]: time the fp8 decode GEMMs at one shape and print the\n" - " weight bandwidth each reaches. R4D_F8_MW and R4D_F8_SPLITTGT pin\n" - " the narrow tile's launch heuristics for a sweep.\n" + " weight bandwidth each reaches.\n" " --perfbf16 N K M [iters]: the bf16 skinny GEMM at every variant it has.\n" " --perfw8 N K M [iters]: the 8-bit trunk GEMMs -- block E4M3 W8A8 and the int8\n" " rows -- at one shape, each with its TFLOP/s.\n" @@ -14453,9 +14535,7 @@ int main(int argc, char** argv) { perf_m = std::strtoll(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != '-') perf_it = (int)std::strtol(argv[++i], nullptr, 0); } else if (!std::strcmp(argv[i], "--perfbf16")) { - /* The bf16 skinny GEMM, at every variant. Its own flag because rad-tune reaches these - * rows but its absolute numbers are not repeatable enough between back-to-back runs - * of the same command to base a default on. */ + /* The bf16 skinny GEMM at every variant (see bf16_perf). */ if (i + 3 >= argc) { usage(); return 2; } perf_bf = 1; perf_n = std::strtoll(argv[++i], nullptr, 0); @@ -14470,9 +14550,7 @@ int main(int argc, char** argv) { perf_m = std::strtoll(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != '-') perf_it = (int)std::strtol(argv[++i], nullptr, 0); } else if (!std::strcmp(argv[i], "--perfw2")) { - /* The int2 draft head, at every variant. Its own flag because rad-tune's declared - * graph never reaches a gemm_nt_q row and this is the only kernel in the drafter - * that is not already at bandwidth. */ + /* The int2 draft head at every variant (see w2_perf). */ if (i + 3 >= argc) { usage(); return 2; } perf_w2 = 1; perf_n = std::strtoll(argv[++i], nullptr, 0); @@ -14480,7 +14558,7 @@ int main(int argc, char** argv) { perf_m = std::strtoll(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != '-') perf_it = (int)std::strtol(argv[++i], nullptr, 0); } else if (!std::strcmp(argv[i], "--perfqsa")) { - /* The indexer at a REAL context length: it is the only decode op that grows with one. */ + /* The indexer at a real context length (the only decode op that grows with it). */ if (i + 1 >= argc) { usage(); return 2; } qsa_ctx = std::strtoll(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != 0x2d) qsa_m = std::strtoll(argv[++i], nullptr, 0); @@ -14510,8 +14588,7 @@ int main(int argc, char** argv) { hc_m = std::strtoll(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != 0x2d) hc_it = (int)std::strtol(argv[++i], nullptr, 0); } else if (!std::strcmp(argv[i], "--perfops")) { - /* The elementwise ops at a decode shape. Separate from --perf because the question is - * about launches, not about a GEMM's bandwidth. */ + /* The elementwise ops at a decode shape: launch cost, not GEMM bandwidth. */ if (i + 2 >= argc) { usage(); return 2; } sop_m = std::strtoll(argv[++i], nullptr, 0); sop_k = std::strtoll(argv[++i], nullptr, 0); @@ -14533,8 +14610,7 @@ int main(int argc, char** argv) { Plugin pl; - /* The timing mode runs alone for the same reason the real-checkpoint check does: it answers a - * different question from the catalogue, and it is the one a reviewer runs by itself. */ + /* Timing modes run alone, without the catalogue. */ if (hc_m) { if (!load(&pl, path)) return 1; #ifdef RAD_HAVE_HIP @@ -14600,8 +14676,7 @@ int main(int argc, char** argv) { return 0; } - /* The real-checkpoint check runs alone: it is the one case whose input is not synthetic, so it - * is also the one a reviewer will want to run by itself against a particular tensor. */ + /* The real-checkpoint check runs alone, against one given tensor. */ if (real_file) { if (!load(&pl, path)) return 1; #ifdef RAD_HAVE_HIP @@ -14614,15 +14689,10 @@ int main(int argc, char** argv) { return g_fail; } - /* THE CHILD. One row, no catalogue, no static checks -- and an exit code the parent reads, - * because a row that faults never gets to print anything at all. */ + /* The child: one row, no catalogue or static checks, and an exit code for the parent, since + * a faulting row may print nothing. */ if (g_case) { if (!load(&pl, path)) return CH_FAIL; - /* A case that needs its own process re-execs this one; see spawn_anchor_child. Both paths - * live only as long as this frame, which outlives the device phase. */ - char me[4096]; - const ssize_t mn = readlink("/proc/self/exe", me, sizeof(me) - 1); - if (mn > 0) { me[mn] = 0; g_exe = me; g_plugin = path; } device_phase(pl); if (!g_matched) skip(g_case, "no smoke case"); std::fflush(stdout); @@ -14637,8 +14707,7 @@ int main(int argc, char** argv) { dump(pl); cross_check(pl); - /* /proc/self/exe rather than argv[0]: the children are this binary, and argv[0] is whatever - * the caller's shell felt like passing. */ + /* /proc/self/exe rather than argv[0], which the caller may set to anything. */ char self[4096]; const ssize_t n = readlink("/proc/self/exe", self, sizeof(self) - 1); if (n <= 0) { diff --git a/libr4d/r4d_shapes.cpp b/libr4d/r4d_shapes.cpp index 6662aca0..3e6db2ab 100644 --- a/libr4d/r4d_shapes.cpp +++ b/libr4d/r4d_shapes.cpp @@ -1,86 +1,67 @@ -/* r4d_shapes.cpp -- how big is operand i of this op at this geometry, and what may be in it. +/* r4d_shapes.cpp -- the extent and content domain of each operand of an op at a geometry. * - * THE COMPONENT THAT KNOWS AN OPERAND'S EXTENT IS THE ONE THAT READS IT, which is what the - * `RadShapeFn` hook is for. A tool's other source is the hand-written table in `tools/`, and that - * table cannot reach the ops that exist only here -- every fp8 fusion, both all-reduce folds, both - * DFlash2 ops, `attn_dense` and all twelve sampler stages -- so without this hook those are - * SKIPPED AND COUNTED for want of a recipe. This file is libr4d's side of the hook. + * This is libr4d's side of the `RadShapeFn` hook: the component that reads an operand is the one + * that knows its extent. The hand-written table in `tools/` cannot reach ops that exist only here + * (every fp8 fusion, both all-reduce folds, both DFlash2 ops, `attn_dense`, the sampler stages), so + * without this hook a tool skips them. * - * THE AUTHORITY FOR EVERY EXTENT BELOW IS THE SHIM, not the prose and not the row table. Each - * `rad_*` entry point in the libr4d shims unpacks `RadArgs.t[i]` and hands libr4d the - * extents and pitches; where a shim reads `x->shape[1]` and passes it as `K`, that is what the - * operand is. A comment naming the shim is on every group, so a reader can check one against - * the other -- and when a shim's contract changes, that is the file whose neighbour has to move. + * The authority for every extent is the shim, not the prose or the row table. Each `rad_*` entry + * point unpacks `RadArgs.t[i]` into extents and pitches; if a shim passes `x->shape[1]` as `K`, + * that is what the operand is. Each group names its shim, and a change to a shim's contract must + * be mirrored here. * - * WHAT IS IN AN OPERAND MATTERS AS MUCH AS HOW BIG IT IS. A token id gathers a row of a codebook, - * a KV slot indexes n_blocks * block_size positions, a block-table entry indexes n_blocks, and a - * uniform is in [0, 1); draw any of them from the wrong range and the case tests the kernel's - * out-of-range handling while the report calls it correctness. `RAD_FILL_INDEX` with an explicit - * `idx_max` is how each of those is said here, and `RAD_OPD_F_IDX_UNIQUE` marks the one scatter - * (kv_store's slot mapping) whose duplicates would make the store a race and the comparison a - * measurement of the scheduler. + * Content matters as much as size. A token id gathers a row of a codebook, a KV slot indexes + * n_blocks * block_size positions, a block-table entry indexes n_blocks, a uniform is in [0, 1). + * Drawn from the wrong range, such an operand tests the kernel's out-of-range handling instead of + * its arithmetic. `RAD_FILL_INDEX` with an explicit `idx_max` states each range, and + * `RAD_OPD_F_IDX_UNIQUE` marks scatters whose duplicate indices would make the store a race. * - * WHAT THIS FILE DOES NOT DESCRIBE, AND WHY. A decline is a real answer: the caller skips the case - * and counts it, which is correct, where an invented extent produces a PASS that means nothing. - * The rows below carry a null `opd_shape` deliberately. + * ============================================================ rows with no description + * + * A decline is a real answer: the caller skips and counts the case, where an invented extent + * yields a meaningless pass. These rows carry a null `opd_shape`: * * gdn_conv_prep, gdn_conv_update, gdn_kkt_solve, gdn_chunk_scan, gdn_recurrent_update - * THE HEAD COUNTS ARE NOT IN THE GEOMETRY. `head_k` and `head_v` are head WIDTHS (128 each); - * the number of key heads and value heads is read off the operands by the kernels and named - * by no parameter of any of these ops, so `conv_dim = 2*Hk*hk + Hv*hv` -- the leading extent - * of nearly every operand -- is not derivable from `p`. tools/opshapes.h reaches them only - * because rad-kbench hands it the container's metadata through `ShapeCtx`, which this hook's - * signature does not carry. A GDN case run at an invented head ratio is a check of a model - * nobody is running. (`gdn_gated_rmsnorm` and `gdn_gated_norm_had_quant_i8` ARE described: - * their rows are (token, head) pairs and their widths are parameters.) + * The head counts are not in the geometry. `head_k` and `head_v` are head widths (128); the + * kernels read the number of key and value heads off the operands, so + * `conv_dim = 2*Hk*hk + Hv*hv`, the leading extent of nearly every operand, is not derivable + * from `p`. tools/opshapes.h reaches them only through the container metadata rad-kbench + * passes in `ShapeCtx`, which this hook does not receive. (`gdn_gated_rmsnorm` and + * `gdn_gated_norm_had_quant_i8` are described: their rows are (token, head) pairs and their + * widths are parameters.) * * attn_dense - * No head count either. Its parameters are M, head_dim, gqa, causal and dtype; the vision - * kernel reads the head count off `q->shape[1]` and gqa is constrained to 1, so nothing in - * the geometry says how many heads a token carries. Picking one would be picking a model. - * ref describes it -- it chooses `gqa` query heads against one KV head, which at this row's - * gqa == 1 is a single head -- and ref's is the description a correctness check uses anyway, - * so the gap this leaves is a benchmark of the vision kernel at a head count nobody runs. + * No head count either: the parameters are M, head_dim, gqa, causal and dtype, the vision + * kernel reads the head count off `q->shape[1]`, and gqa is constrained to 1. ref describes + * it with a single head (`gqa` query heads against one KV head), and correctness checks use + * ref's description anyway. * * sample_merge_topk - * The extents are known and a description would still be a lie. `gathered` is - * world_size * n_cand (u32 global id, f32 logit) pairs packed into one WORD-TYPED buffer, so - * the value lane is read by BIT PATTERN and no fill domain puts a sensible float there: an - * integer draw makes every logit a denormal, and a device that flushes denormals against a - * host that does not orders the candidates differently -- which is the failure r4d_selftest's - * two-rank all-gather row exists to catch. `world_size` is not in the parameter list either. - * ref declines it for the same two reasons, and the two files agreeing on a decline is the - * point: a description here would supply the bytes ref refused to. The full argument is at - * the gap this leaves in the sampler section below. + * `gathered` packs (u32 global id, f32 logit) pairs into one word-typed buffer, so no fill + * domain puts a sensible float in the value lane, and `world_size` is not a parameter. ref + * declines it too. Details at the sampler section below. * * gemm_nt_q at every grid but fp8 * The weight is a plugin-private fragment stream (R4D_DT_W4_FRAG and friends) whose byte - * count comes from `RadLayout::bytes`, and RadOpdDesc has only a dtype and a shape -- so a - * description here would be a SECOND source for a number r4d_layout.cpp already owns, and - * the two would drift silently the first time a packing changed. The scale planes are worse: - * R4D_DT_W4_SZ is a (f16 scale, f16 -(1024+zero)) dword whose meaning no public dtype - * carries. The fp8 family is different and IS described -- its weight is the checkpoint's - * own E4M3 [N][K] bytes against a bf16 [ceil(N/128)][ceil(K/128)] plane, and the fragment - * reordering is a permutation of the same count (r4d_fp8_frag.h: `frag_bytes(N,K) == N*K`). + * count comes from `RadLayout::bytes`; RadOpdDesc has only a dtype and a shape, so a + * description would be a second source for a number r4d_layout.cpp owns. R4D_DT_W4_SZ, a + * (f16 scale, f16 -(1024+zero)) dword, has no public dtype either. The fp8 family is + * described: its weight is the checkpoint's E4M3 [N][K] against a bf16 + * [ceil(N/128)][ceil(K/128)] plane, and fragment order is a permutation of the same count + * (r4d_fp8_frag.h: `frag_bytes(N,K) == N*K`). * * logits_gemm at fp8 - * THE DECLARED SHAPE AND THE STORED PLANE DIFFER, and only the container knows. The weight - * arrives declared [n_vocab][n_embd] E4M3 while the kernel strides it by - * r4d_fp8::lm_row_bytes(n_embd) -- - * the row's own bf16 scales ride in its tail (r4d_fp8_layout.cpp says why: lm_head is ROW - * sharded and a shard has to stay a plain byte range). A tool that allocated the declared - * shape would hand the kernel a buffer it reads 1.6% past the end of, on every row. The - * bf16 row of the same op is described; this one cannot be, until RadOpdDesc can say - * "declared this, stored that". + * The declared shape and the stored plane differ. The weight is declared [n_vocab][n_embd] + * E4M3 but the kernel strides it by r4d_fp8::lm_row_bytes(n_embd), since each row carries + * its bf16 scales in its tail (r4d_fp8_layout.cpp). A buffer of the declared shape would be + * read 1.6% past its end. Describable once RadOpdDesc can say "declared this, stored that". * - * NO TUNED AXIS IS READ HERE, and none needs to be. Every axis this plugin declares -- tile - * shapes, split counts, wave counts, all-reduce launch geometry -- says how a kernel WALKS its - * operands, not what it is HANDED. An axis that did change an extent would be read from `p` - * like any other parameter, because the core appends the chosen point to the same list. + * No tuned axis is read here: this plugin's axes (tile shapes, split counts, wave counts, + * all-reduce launch geometry) change how a kernel walks its operands, not their extents. An axis + * that did would be read from `p`, where the core appends the chosen point. * - * Pure host code: no r4d.h, no HIP. It is in the CMake `SOURCES` list beside r4d_rows.cpp and - * r4d_layout.cpp for the reason that split exists -- the tables a transcription error hides in - * should compile and be readable on a box with no ROCm. + * Pure host code (no r4d.h, no HIP), like r4d_rows.cpp and r4d_layout.cpp, so the tables compile + * and can be read without ROCm. */ #include @@ -93,34 +74,28 @@ namespace { /* ==================================================================== building a description * - * Each op below builds its whole operand list, in schema order, and then hands out the one the - * caller asked for. Building the list rather than switching on the index is what makes the COUNT - * checkable by eye against the schema in r4d_rows.cpp -- the tool cross-checks it against - * `RadOpSchema::n_operands` as well, and a hook that has drifted from its schema is caught there, - * but a list a reader can count is the half that stops the drift happening. + * Each op builds its whole operand list in schema order and hands out the one asked for, so the + * count can be checked by eye against the schema in r4d_rows.cpp (the tool also checks it against + * `RadOpSchema::n_operands`). */ -/* A plain operand of up to four extents. A trailing 0 means "this rank is not present": zero is - * never a legal extent -- `pick` refuses one below -- so it cannot be confused with a real one, - * and it lets a two-dimensional and a four-dimensional operand be written the same way. */ +/* A plain operand of up to four extents. A trailing 0 ends the shape; zero is never a legal + * extent (`pick` refuses one), so it cannot be mistaken for a real one. */ RadOpdDesc opd(uint32_t dt, int64_t d0, int64_t d1 = 0, int64_t d2 = 0, int64_t d3 = 0) { RadOpdDesc d{}; d.dtype = dt; d.fill = RAD_FILL_NORMAL; - /* Explicit, though the caller pre-initialises it: -1 is "draw", and a description that meant - * "every element is zero" and got it by leaving a field alone is one edit away from being a - * description that means nothing. */ + /* -1 is "draw"; set explicitly though the caller pre-initialises it. */ d.idx_const = -1; const int64_t e[4] = { d0, d1, d2, d3 }; for (int i = 0; i < 4 && e[i] != 0; ++i) d.shape[d.rank++] = e[i]; return d; } -/* An INDEX operand. `idx_max` is the EXCLUSIVE upper bound of the draw and 0 means "the leading - * extent of the previous operand", which is the ABI's default and is right for a gather whose - * source is the operand before it. `konst >= 0` makes every element that value instead of a draw. - * i32 throughout: every index libr4d reads is a signed 32-bit one, and the two u32 spellings the - * sampler accepts (`dt_i32` takes either) are the same bytes. */ +/* An index operand. `idx_max` is the exclusive upper bound of the draw; 0 means the previous + * operand's leading extent (the ABI default, right for a gather from the operand before it). + * `konst >= 0` fills every element with that value. Always i32: every index libr4d reads is signed + * 32-bit, and the sampler's u32 spellings (`dt_i32` accepts either) are the same bytes. */ RadOpdDesc opd_idx(int64_t d0, int64_t d1, int64_t idx_max, int64_t konst = -1, uint32_t flags = 0) { RadOpdDesc d = opd((uint32_t)RAD_I32, d0, d1); @@ -131,9 +106,8 @@ RadOpdDesc opd_idx(int64_t d0, int64_t d1, int64_t idx_max, int64_t konst = -1, return d; } -/* An OPTIONAL operand this description deliberately does not pass. One entry per schema operand - * is still emitted -- that count is what catches a hook that has drifted -- so absence needs a - * spelling, and a null RadTensor is what the ABI already means by it. */ +/* An optional operand this description does not pass. One entry per schema operand is still + * emitted, so absence needs a spelling; to the ABI it means a null RadTensor. */ RadOpdDesc opd_none() { RadOpdDesc d{}; d.idx_const = -1; @@ -141,19 +115,14 @@ RadOpdDesc opd_none() { return d; } -/* A domain the fill has to land in. `RAD_FILL_SIGMOID` is the ABI's only (0, 1) draw. */ +/* Restricts the fill to (0, 1); `RAD_FILL_SIGMOID` is the ABI's only such draw. */ RadOpdDesc in_unit(RadOpdDesc d) { d.fill = RAD_FILL_SIGMOID; return d; } -/* Hand out operand `operand` of a list, having checked the WHOLE list first. - * - * The whole list, because a geometry missing one parameter would otherwise describe its first few - * operands and decline the rest, and a caller that allocated the first few is a caller that has - * done work for a case it is about to skip. A non-positive extent means a parameter this - * description needed was absent or zero, which is RAD_E_UNSUPPORTED -- the geometry does not carry - * what the description needs -- and not RAD_E_SHAPE, which would read as a bug in the tool. - * - * An operand index outside the list IS a bug, in this file or in the schema it was written - * against, and says so with a different code. */ +/* Hands out operand `operand` of a list after checking the whole list, so a geometry missing a + * parameter declines every operand rather than describing a few and declining the rest. A + * non-positive extent means a needed parameter was absent or zero: RAD_E_UNSUPPORTED, not + * RAD_E_SHAPE, which would read as a tool bug. An index outside the list is a bug here or in the + * schema, reported as RAD_E_SHAPE. */ int pick(RadOpdDesc* out, int operand, const RadOpdDesc* list, int n) { if (!out || !list || n <= 0) return RAD_E_INVAL; for (int i = 0; i < n; ++i) { @@ -171,50 +140,32 @@ int pick(RadOpdDesc* out, int operand, const RadOpdDesc* list, int n) { /* ==================================================================== parameters * - * `p` is the RESOLVED geometry, which is to say the geometry with its RANGES COLLAPSED: `M` here - * is the band's bound, not the row count of any particular step (the same reading every shim in - * this plugin takes, and the trap r4d_gdn.cpp's dflash_select shim spells out). That is the right - * value for a description -- the buffers a tool allocates have to hold the band the kernel was - * selected for -- and it is why nothing below tries to be cleverer about it. + * `M` and other ranged parameters read as the band's bound, not any one step's row count (as in + * every shim here; see the dflash_select shim in r4d_dflash_select_bf16.hip). Buffers must hold the whole band + * the kernel was selected for. */ -/* NOT r4d_pgeti_or(), and the difference is load-bearing: that reader takes RAD_P_INT only, which - * is right for a LAUNCH -- by then the core has collapsed every range to the band's value -- and - * wrong here, because this hook can be called with a geometry whose ranges are still ranges. A - * RAD_P_RANGE reads as its HIGH bound: the buffers a tool allocates have to hold the whole band the - * kernel was selected for, and the low end of a band fits inside them. - * - * That reading is rad_param_getdim's, in the ABI, and is shared by both plugins: a shape hook - * cannot be written without it. - * - * A string spelling of an integer parameter is deliberately NOT accepted, where ref's reader takes - * one: this plugin's shims read integers with r4d_geti_or, which is RAD_P_INT only, so describing a - * geometry the launch would then refuse would turn a skip into a failure. rad_param_getdim takes - * the strict reading for exactly that reason; ref layers its leniency on top. */ +/* Not r4d_pgeti_or(): that reads RAD_P_INT only, which suits a launch (every range has collapsed), + * but this hook can see ranges still open. rad_param_getdim (ABI, shared by both plugins) reads a + * RAD_P_RANGE as its high bound. Unlike ref's reader it rejects a string spelling of an integer, + * because this plugin's shims read RAD_P_INT only and describing a geometry the launch refuses + * would turn a skip into a failure. */ int64_t pi(const RadParam* p, int n_p, const char* k, int64_t dflt = 0) { return (int64_t)rad_param_getdim(p, n_p, k, (long long)dflt); } -/* THE ABI's PARSER, and not an if-ladder of this file's own. rad_dtype_parse is static inline in - * rad_types.h, which rad_abi.h includes, which this plugin compiles against, so it is reachable - * from a plugin. - * - * Using it is what keeps the accepted spellings identical to libref's. A local subset -- one - * missing u8, i16, i64, u32, bool, w4, w2 or mxfp4, say -- refuses here what libref accepts, and - * rad-kbench reads that divergence as a libr4d hole rather than as a parser gap. rad_dtype_parse - * also carries the `all_reduce` synonyms (the arch blocks declare `bf16`/`fp32` and - * core/sample/sampler.cpp declares `f32`). */ +/* The ABI's parser (static inline in rad_types.h), so the accepted spellings match libref's; a + * local subset would refuse what libref accepts and show up as a libr4d gap. It also carries the + * `all_reduce` synonyms (arch blocks declare `bf16`/`fp32`, core/sample/sampler.cpp `f32`). */ uint32_t dt_of(const char* s) { return rad_dtype_parse(s); } uint32_t dt_par(const RadParam* p, int n_p, const char* key) { return dt_of(r4d_pgets(p, n_p, key)); } -/* THE ACTIVATION WIDTH, with the fallback that matters. A `dtype` this table does not know is - * usually a quantisation SCHEME rather than an element width -- "fp8a8", "w4a8" -- and bf16 is - * what every activation in this project is when nothing says otherwise. Falling back to an invalid - * dtype instead would size a zero-byte buffer and the case would be skipped for a reason that - * looks like an allocation failure. `cast` uses the raw reader above, because there a dtype it - * does not know is a pair this row genuinely cannot serve. */ +/* The activation element type. An unknown `dtype` is usually a quantisation scheme ("fp8a8", + * "w4a8") rather than an element width, and activations are bf16 unless stated, so that is the + * fallback; an invalid dtype would size a zero-byte buffer. `cast` uses dt_par instead, because + * there an unknown dtype is a pair the row cannot serve. */ uint32_t dt_act(const RadParam* p, int n_p, const char* key) { const uint32_t dt = dt_par(p, n_p, key); return dt == (uint32_t)RAD_DT_INVALID ? (uint32_t)RAD_BF16 : dt; @@ -222,41 +173,31 @@ uint32_t dt_act(const RadParam* p, int n_p, const char* key) { /* ==================================================================== the sampler's params row * - * `params` is an ARRAY OF RadSampleParams viewed through a 32-bit dtype -- one row per sampled - * position, uploaded once a step (abi/rad_sample.h). Its EXTENT is exact: 96 bytes a row, - * which is what r4d_sample.cpp's `params_ok` checks in words. Its CONTENT is a struct, and the - * ABI's fill domains describe a buffer -- normals, a sigmoid, a gate cumsum, a triangular mask, an - * index draw -- so there is no spelling for "fill this like a request". + * `params` is an array of RadSampleParams viewed through a 32-bit dtype, one row per sampled + * position (abi/rad_sample.h). The extent is exact: 96 bytes per row, as r4d_sample_stages_f32.hip's + * `params_ok` checks. The content is a struct, and no ABI fill domain describes "a plausible + * request". * - * DESCRIBED AS f32, WHICH IS A CHOICE ABOUT CONTENT AND NOT ABOUT SIZE, and it is the same choice - * ref_shapes.cpp makes for the same operand -- the two files have to agree here, because whichever - * of them a tool asks, BOTH implementations are then handed those bytes. The struct is eleven - * floats and nine int32s. Drawn as f32 normals every float field -- temp, top_p, min_p, - * typical_p, the penalties, the two XTC values -- lands in a plausible range, so a third to a half - * of the rows fall inside the interval that makes their stage do work and the rest are the - * identity: which is the mix a real batch has. + * It is described as f32, matching ref_shapes.cpp (both implementations receive the same bytes, + * so the two files must agree). The struct is eleven floats and nine int32s. As f32 normals the + * float fields (temp, top_p, min_p, typical_p, the penalties, the XTC values) land in plausible + * ranges, so some rows make their stage do work and the rest are the identity, as in a real batch. * - * WHAT IT CANNOT REACH, said plainly rather than left for someone to discover from a PASS. The - * INTEGER fields come out as the bit patterns of those same normals, so `hist_off`, `hist_len` and - * `mask_row` are enormous -- and every stage clamps them, which is why this is safe on a device - * and also why it is weak: + * Limits: the integer fields are bit patterns of normals, so `hist_off`, `hist_len` and `mask_row` + * are huge. Every stage clamps them, which keeps this safe but weak: * * sample_penalties ho is clamped to hmax, hl to hmax - ho, and `hl <= 0` returns * sample_dry the same clamp, then `hl <= allowed` returns * sample_mask `mask_row >= mask_rows` returns before a word of the plane is read * - * `flags` is a bit pattern too, so roughly half the rows carry RAD_SP_GREEDY, and every candidate - * stage -- top-k, the narrowing stages, the merge, the pick -- treats those as having no - * candidates. Both implementations do, so the comparison holds; it covers the other half. + * So a pass on those three checks the plumbing, not the arithmetic. `flags` is a bit pattern too, + * so about half the rows carry RAD_SP_GREEDY, which every candidate stage treats as having no + * candidates; the comparison covers the other half. A word-typed or all-zero draw would be worse: + * denormal or NaN floats with `1 / temp` infinite, or every stage the identity. * - * A pass on those three says the plumbing agrees, not that the arithmetic does. The alternative -- - * a word-typed draw, or the all-zero row -- is worse in both directions: it makes every float - * field a denormal or a NaN and `1 / temp` an infinity, or it makes every stage the identity. - * - * u32 IS NEVER USED for this or any other word-typed operand here, and that is not taste: - * tools/opshapes.cpp's `rad_widen` and `rad_narrow` have no RAD_U32 case, so a u32 operand is - * FILLED as zeroes and COMPARED as zeroes -- a vacuous pass, which is worse than a skip. i32 is - * the same four bytes and is read. */ + * Word-typed operands here are never u32: tools/opshapes.cpp's `rad_widen` and `rad_narrow` have + * no RAD_U32 case, so a u32 operand is filled and compared as zeroes, a vacuous pass. i32 is the + * same four bytes. */ RadOpdDesc opd_sample_params(int64_t M) { return opd((uint32_t)RAD_F32, M, (int64_t)(sizeof(RadSampleParams) / 4)); } @@ -264,13 +205,12 @@ RadOpdDesc opd_sample_params(int64_t M) { } /* namespace */ /* ========================================================================================== - * The small model ops (shims in r4d_model.cpp). + * The small model ops (shims in r4d_model_bf16.hip and its neighbours). * - * Every one of these takes `n` as the row width and reads its row COUNT off the operand, so the - * band's `M` is what a description has to size for. The gain of a norm is the one operand that is - * not bf16: every architecture plugin in this tree declares its norm gains RAD_F32 -- a few - * thousand elements against gigabytes of weights, and a norm is where a rounded gain shows -- and - * the shim reads the width off the operand rather than assuming it. + * Each takes `n` as the row width and reads its row count off the operand, so descriptions size + * for the band's `M`. A norm's gain is the one operand that is not bf16: every architecture plugin + * declares norm gains RAD_F32 (a few thousand elements, and a norm is where a rounded gain shows), + * and the shim reads the width off the operand. * ========================================================================================= */ extern "C" int r4d_shape_embed_lookup(const RadParam* p, int n_p, int operand, @@ -282,13 +222,10 @@ extern "C" int r4d_shape_embed_lookup(const RadParam* p, int n_p, int operand, const int64_t vo = pi(p, n_p, "vocab_offset", 0); const uint32_t D = dt_act(p, n_p, "dtype"); const RadOpdDesc l[] = { - /* A TOKEN ID INDEXES THE TABLE, and the table is the operand AFTER it, so the ABI's - * default -- the previous operand's leading extent -- is the wrong one here and n_vocab is - * said outright. A draw from anywhere else tests the row's negative-id path and calls it - * an embedding. - * - * Under a vocab shard the bound is vo + nv, because ids are GLOBAL: drawing only within - * the slice never exercises the zero-row path the following all_reduce depends on. */ + /* A token id indexes the table, which is the next operand, so the ABI default (the + * previous operand's extent) is wrong and the bound is stated. Under a vocab shard ids + * are global, so the bound is vo + nv; drawing only within the slice would never exercise + * the zero-row path the following all_reduce depends on. */ opd_idx(M, 0, vo + nv), opd(D, nv, ne), opd(D, M, ne), @@ -296,9 +233,9 @@ extern "C" int r4d_shape_embed_lookup(const RadParam* p, int n_p, int operand, R4D_PICK(l); } -/* The quantised gather: libref's description (ref_embed_lookup_q_shape), an E4M3 table and a - * one-element scale in the activation dtype. `ahead` is not passed: it is ids for a reader that - * fetches rows from a file, and the kernel does not read it. */ +/* The quantised gather, as libref describes it (ref_embed_lookup_q_shape): an E4M3 table and a + * one-element scale in the activation dtype. `ahead` is not passed: it holds ids for a reader that + * fetches rows from a file, and the kernel ignores it. */ extern "C" int r4d_shape_embed_lookup_q(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = pi(p, n_p, "M"); @@ -323,9 +260,8 @@ extern "C" int r4d_shape_gather_rows(const RadParam* p, int n_p, int operand, const int64_t n = pi(p, n_p, "n"); const uint32_t D = dt_act(p, n_p, "dtype"); const RadOpdDesc l[] = { - /* FOUR TIMES THE ROWS THE GATHER PRODUCES, so the gather is not the identity: a source - * exactly M rows tall makes idx[i] == i a plausible answer, and the identity is the one - * case that passes while the kernel is broken. */ + /* Four times the output rows, so the gather is not the identity (with an M-row source, + * idx[i] == i is plausible and passes a broken kernel). */ opd(D, 4 * M, n), opd_idx(M, 0, 4 * M), opd(D, M, n), @@ -333,9 +269,8 @@ extern "C" int r4d_shape_gather_rows(const RadParam* p, int n_p, int operand, R4D_PICK(l); } -/* The byte-row pair. `n` is a count of BYTES here, and the registry constrains it to a multiple - * of 4 so the vectorised copy is the only path -- a description that drew an odd `n` would be - * describing a case the kernel correctly refuses. */ +/* The byte-row pair. `n` counts bytes, constrained by the registry to a multiple of 4 so the + * vectorised copy is the only path. */ extern "C" int r4d_shape_gather_rows_u8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = pi(p, n_p, "M"); @@ -348,10 +283,9 @@ extern "C" int r4d_shape_gather_rows_u8(const RadParam* p, int n_p, int operand, R4D_PICK(l); } -/* And the mirror. The destination is four times the height for the same reason, plus one of its - * own: a scatter onto exactly M rows under M DISTINCT indices is a permutation, so a kernel that - * ignored `idx` would still touch every row and could still pass. Wider than the write, and the - * rows nobody names have to come back unchanged. */ +/* The mirror. The destination is four times taller: a scatter of M distinct indices onto M rows + * is a permutation, so a kernel ignoring `idx` would still touch every row. With a taller + * destination, unnamed rows must come back unchanged. */ extern "C" int r4d_shape_scatter_rows_u8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = pi(p, n_p, "M"); @@ -381,10 +315,8 @@ extern "C" int r4d_shape_cast(const RadParam* p, int n_p, int operand, const int64_t M = pi(p, n_p, "M"); const int64_t n = pi(p, n_p, "n"); - /* `from` and `to` are separate keys because the whole point of the op is that the two ends - * differ. Two rows serve it -- bf16 -> bf16 (a strided row copy) and bf16 -> f32 (the - * widening) -- and the shims refuse anything else on dtype, so a geometry that names another - * pair is declined here rather than described into a refusal. */ + /* Two rows serve the op, bf16 -> bf16 (a strided row copy) and bf16 -> f32, and the shims + * refuse any other pair, so another pair is declined here. */ const uint32_t f = dt_par(p, n_p, "from"), t = dt_par(p, n_p, "to"); if (f != (uint32_t)RAD_BF16 || (t != (uint32_t)RAD_BF16 && t != (uint32_t)RAD_F32)) return RAD_E_UNSUPPORTED; @@ -406,9 +338,8 @@ extern "C" int r4d_shape_rmsnorm(const RadParam* p, int n_p, int operand, R4D_PICK(l); } -/* ---- the vision tower's (r4d_vit_bf16.hip). Every optional operand is PASSED: the bias of the - * norm and the residual of the GEMM are the same code with a branch taken, so describing them - * covers both forms. */ +/* ---- the vision tower's (r4d_vit_bf16.hip). Every optional operand is passed: the norm's bias and + * the GEMM's residual are the same code with a branch taken, so this covers both forms. */ extern "C" int r4d_shape_layernorm(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"); const uint32_t D = dt_act(p, n_p, "dtype"); @@ -419,8 +350,8 @@ extern "C" int r4d_shape_layernorm(const RadParam* p, int n_p, int operand, RadO extern "C" int r4d_shape_grid_embed(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), side = pi(p, n_p, "side"); const uint32_t D = dt_act(p, n_p, "dtype"); - /* Coordinates drawn over the table's side: some rows sit past their grid's last row and take - * the clamped taps as well as the interior ones. */ + /* Coordinates drawn over the table's side, so some rows fall past their grid's last row and + * exercise the clamped taps as well as the interior ones. */ const RadOpdDesc l[] = { opd(D, M, n), opd(D, side * side, n), opd_idx(4, M, side) }; R4D_PICK(l); } @@ -432,9 +363,9 @@ extern "C" int r4d_shape_gemm_nt_bias(const RadParam* p, int n_p, int operand, R R4D_PICK(l); } -/* ---- the gated residual (r4d_hc_bf16.hip's three shims). `inject` and `group` DEFAULT ON, so a +/* ---- the gated residual (r4d_hc_bf16.hip's three shims). `inject` and `group` default on, so a * query naming neither describes what every trunk connection runs; 0 for either describes one of - * the two exceptions -- the final mixer, and a read whose consumer wants bf16. */ + * the two exceptions: the final mixer, and a read whose consumer wants bf16. */ extern "C" int r4d_shape_hc_enter(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), hc = pi(p, n_p, "hc"); const uint32_t D = dt_act(p, n_p, "dtype"); @@ -442,8 +373,8 @@ extern "C" int r4d_shape_hc_enter(const RadParam* p, int n_p, int operand, RadOp R4D_PICK(l); } -/* The MTP head's entry. Both gains are F32, as hc_read's is, and the two fc matrices are the - * activation dtype -- the checkpoint's `mtp.fc_hidden` / `mtp.fc_embedding`, square and bf16. */ +/* The MTP head's entry. Both gains are F32, as hc_read's is; the two fc matrices are the + * checkpoint's `mtp.fc_hidden` / `mtp.fc_embedding`, square, in the activation dtype. */ extern "C" int r4d_shape_mtp_enter(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), hc = pi(p, n_p, "hc"); const uint32_t D = dt_act(p, n_p, "dtype"); @@ -456,18 +387,15 @@ extern "C" int r4d_shape_mtp_enter(const RadParam* p, int n_p, int operand, RadO extern "C" int r4d_shape_hc_write(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), hc = pi(p, n_p, "hc"); const uint32_t D = dt_act(p, n_p, "dtype"); - /* `inj` is a gain in (0, 2) -- twice a sigmoid -- and a normal draw would make hc_write a - * different test: the point of the op is that the four gains are small and data-dependent. */ + /* `inj` is a gain in (0, 2), twice a sigmoid, so it is drawn in (0, 1) rather than as a + * normal: the op's gains are small and data-dependent. */ const RadOpdDesc l[] = { opd(D, M, n), in_unit(opd(D, M, hc)), opd(D, M, hc * n) }; R4D_PICK(l); } -/* hc_write's operands with the all-reduce in front: the same three, `y` now the message as well. */ +/* hc_write's operands with the all-reduce in front; `y` is also the message. */ extern "C" int r4d_shape_ar_hc_write(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { - const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), hc = pi(p, n_p, "hc"); - const uint32_t D = dt_act(p, n_p, "dtype"); - const RadOpdDesc l[] = { opd(D, M, n), in_unit(opd(D, M, hc)), opd(D, M, hc * n) }; - R4D_PICK(l); + return r4d_shape_hc_write(p, n_p, operand, out); } /* moe_gather's five and ar_hc_write's three, in that order; the gather's `y` and the reduction's are @@ -515,10 +443,8 @@ extern "C" int r4d_shape_hc_read(const RadParam* p, int n_p, int operand, RadOpd R4D_PICK(l); } -/* add and mul share an operand list. THE BROADCAST FORM IS NOT DESCRIBED: `b` carrying exactly n - * elements against an output of M rows broadcasts along rows, and that is a second geometry of the - * same op -- one description can only be one of them, and the elementwise form is the one every - * caller in this tree issues. */ +/* add and mul share an operand list. Only the elementwise form is described, the one every caller + * issues; the broadcast form (`b` of exactly n elements against M rows) is a second geometry. */ extern "C" int r4d_shape_binary(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { @@ -564,8 +490,8 @@ extern "C" int r4d_shape_silu_mul(const RadParam* p, int n_p, int operand, const int64_t M = pi(p, n_p, "M"); const int64_t n = pi(p, n_p, "n"); const uint32_t D = dt_act(p, n_p, "dtype"); - /* The gate is the FIRST half of a [M, 2n] row, which is the order rad-convert fuses gate_proj - * and up_proj in. */ + /* The gate is the first half of a [M, 2n] row, the order rad-convert fuses gate_proj and + * up_proj in. */ const RadOpdDesc l[] = { opd(D, M, 2 * n), opd(D, M, n) }; R4D_PICK(l); } @@ -577,14 +503,12 @@ extern "C" int r4d_shape_rope(const RadParam* p, int n_p, int operand, const int64_t hd = pi(p, n_p, "head_dim"); const int64_t nq = pi(p, n_p, "n_head"); const int64_t nkv = pi(p, n_p, "n_head_kv"); - /* The fused projection row: n_head queries, then n_head_kv each of k and v. The V heads are - * untouched, which is the whole reason this op takes the fused row rather than two tensors -- - * and why the row width is not just (n_head + n_head_kv) * head_dim. `n_head_kv` 0 is the - * legal "q only" form the gated attention block issues, so it is not required to be positive - * and the width is what has to be. */ + /* The fused projection row: n_head queries, then n_head_kv each of k and v (v untouched), so + * the width includes the V heads. `n_head_kv` 0 is the legal q-only form the gated attention + * block issues, so only the width must be positive. */ const int64_t row = (nq + 2 * nkv) * hd; - /* A multi-component mode with its sections takes a position per component, component-major: - * three for the interleaved form, one a section otherwise. */ + /* A multi-component mode with sections takes one position per component, component-major: + * three for the interleaved form, one per section otherwise. */ const char* mode = rad_param_gets(p, n_p, "mode", "neox"); const char* sec = rad_param_gets(p, n_p, "sections", nullptr); int64_t nc = 0; @@ -600,22 +524,19 @@ extern "C" int r4d_shape_rope(const RadParam* p, int n_p, int operand, if (multi && !std::strcmp(mode, "imrope")) nc = 3; const RadOpdDesc l[] = { opd((uint32_t)RAD_BF16, M, row), - /* A POSITION IS NOT A LOOKUP HERE: this kernel computes sincos from the value, so any - * non-negative integer is legal and none of them is out of range. M keeps the draw in the - * range a step actually presents. */ + /* Not a lookup: the kernel computes sincos from the value, so any non-negative integer is + * legal. M keeps the draw in the range a step presents. */ multi ? opd_idx(nc, M, M) : opd_idx(M, 0, M), }; R4D_PICK(l); } -/* kv_store, both rows. The cache dtype is the one difference between them and it is a PARAMETER, - * so one description serves both: `kv_dtype` is what the constraint table selects on. +/* kv_store, both rows: they differ only in the cache dtype, the `kv_dtype` parameter. * - * The paged layout is stated once for the whole project in libref/ref_ops.h and checked by - * this plugin's shim: kv_cache[n_blocks, kv_heads, block_size, 2 * head_dim], K at [.., d] and V - * at [.., head_dim + d]. The block COUNT is not a parameter of anything -- it is a property of the - * deployment's cache -- so it is this description's to choose, and any cache big enough for the - * slots to land in will do. */ + * The paged layout (libref/ref_ops.h, checked by the shim) is + * kv_cache[n_blocks, kv_heads, block_size, 2 * head_dim], K at [.., d] and V at [.., head_dim + d]. + * The block count belongs to the deployment's cache, not to any parameter, so any count large + * enough for the slots will do. */ extern "C" int r4d_shape_kv_store(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { @@ -625,27 +546,23 @@ extern "C" int r4d_shape_kv_store(const RadParam* p, int n_p, int operand, const int64_t bs = pi(p, n_p, "block_size"); const uint32_t KV = dt_act(p, n_p, "kv_dtype"); if (M <= 0 || bs <= 0) return RAD_E_UNSUPPORTED; - /* Two blocks of slack, so the slot mapping is not a dense prefix: a scatter that only ever - * writes block 0 agrees with anything at all about the block index. */ + /* Two blocks of slack, so the slot mapping is not a dense prefix and the block index is + * actually tested. */ const int64_t nb = (M + bs - 1) / bs + 2; const RadOpdDesc l[] = { - /* Spelled [tokens, kv_heads, head_dim]: the shim folds every trailing extent into one row - * pitch, so the flattened [M, kv_heads * head_dim] an architecture may declare is the same - * bytes and the same pitch -- and this is the spelling ref's description of the op uses, - * which is the one that has to match when the two are compared against each other. */ + /* [tokens, kv_heads, head_dim], as ref spells it. The shim folds trailing extents into + * one row pitch, so a flattened [M, kv_heads * head_dim] is the same bytes and pitch. */ opd((uint32_t)RAD_BF16, M, kvh, hd), opd((uint32_t)RAD_BF16, M, kvh, hd), - /* A SCATTER DESTINATION, so no slot may repeat -- two tokens on one slot make the store a - * race and the two implementations resolve it differently. It indexes POSITIONS, which is - * n_blocks * block_size and is no operand's leading extent. */ + /* A scatter destination, so no slot may repeat (two tokens on one slot race). It indexes + * positions, n_blocks * block_size, which is no operand's leading extent. */ opd_idx(M, 0, nb * bs, -1, RAD_OPD_F_IDX_UNIQUE), opd(KV, nb, kvh, bs, 2 * hd), }; R4D_PICK(l); } -/* logits_gemm at bf16. The fp8 row of the same op is deliberately not described; see the file - * header on why its declared shape and its stored plane differ. */ +/* 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) { @@ -655,22 +572,17 @@ extern "C" int r4d_shape_logits_gemm(const RadParam* p, int n_p, int operand, const RadOpdDesc l[] = { opd((uint32_t)RAD_BF16, M, ne), opd((uint32_t)RAD_BF16, nv, ne), - /* F32 LOGITS OUT, and checked by the shim rather than assumed: dispatching this op to the - * bf16 GEMM instead writes bf16 pairs into an f32 plane -- every logit wrong, the - * magnitudes roughly right, fluent nonsense out of the sampler. */ + /* F32 logits, checked by the shim: the bf16 GEMM would write bf16 pairs into the f32 + * plane, giving plausible magnitudes and wrong logits. */ opd((uint32_t)RAD_F32, M, nv), }; R4D_PICK(l); } /* ========================================================================================== - * The decomposed sampler chain (shims in r4d_sample.cpp). Eleven of the twelve; `sample_merge_topk` - * is declined and the argument is with the others in the file header. - * - * Read the `opd_sample_params` note above before trusting a PASS from any of these: the row's float - * fields are real and its INTEGER fields are the bit patterns of the same normals, so - * `sample_penalties`, `sample_dry` and `sample_mask` take their "nothing to do" branch and a pass - * on those three says the plumbing agrees rather than the arithmetic. + * The decomposed sampler chain (shims in r4d_sample_stages_f32.hip). `sample_merge_topk` is declined (below). + * See opd_sample_params on the limits: `sample_penalties`, `sample_dry` and `sample_mask` take + * their early-out branch, so a pass on those three checks the plumbing only. * ========================================================================================= */ /* logits + params, and one auxiliary plane that differs per stage. */ @@ -679,24 +591,22 @@ extern "C" int r4d_shape_sample_penalties(const RadParam* p, int n_p, int operan const int64_t M = pi(p, n_p, "M"); const int64_t nv = pi(p, n_p, "n_vocab"); - /* THE HISTORY WINDOW IS THIS DESCRIPTION'S CHOICE. `history` is [M, max_hist] and the shim - * takes max_hist from the buffer (numel / M); no parameter names it, because a deployment's - * history plane is sized by its longest live sequence. 64 is a plausible window, and the - * kernel clamps `hist_off` and `hist_len` to it before reading a word -- which is what makes - * the params row above safe and this stage's comparison weak. */ + /* `history` is [M, max_hist], and the shim takes max_hist from the buffer (numel / M); no + * parameter names it, since a deployment sizes it by its longest live sequence. 64 is a + * plausible window; the kernel clamps `hist_off` and `hist_len` to it. */ const int64_t hist = 64; const RadOpdDesc l[] = { opd((uint32_t)RAD_F32, M, nv), opd_sample_params(M), - /* Token ids, so they are drawn from the vocabulary and not from the plane's own extent. */ + /* Token ids, drawn from the vocabulary. */ opd_idx(M, hist, nv), }; R4D_PICK(l); } -/* sample_dry: the penalties' three operands and the optional breaker plane, which is not passed -- - * absent means no token is exempt, and the params row above reaches the row's early out before a - * word of either plane is read. The same reading as ref's description of this op. */ +/* sample_dry: the penalties' three operands, and the optional breaker plane, not passed (absent + * means no token is exempt; the params row takes the early out before either plane is read). As + * ref describes it. */ extern "C" int r4d_shape_sample_dry(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = pi(p, n_p, "M"); @@ -726,18 +636,15 @@ extern "C" int r4d_shape_sample_mask(const RadParam* p, int n_p, int operand, const int64_t M = pi(p, n_p, "M"); const int64_t nv = pi(p, n_p, "n_vocab"); if (nv <= 0) return RAD_E_UNSUPPORTED; - /* The plane is [rows, ceil(n_vocab/32)] and is SHORTER than M in a real batch -- a constrained - * sequence and an unconstrained one share it and `mask_row` is -1 for the second. One row per - * position is the fully-constrained case and the only one a description can pick. */ + /* The plane is [rows, ceil(n_vocab/32)], shorter than M in a real batch (unconstrained + * sequences have `mask_row` -1). One row per position is the fully constrained case. */ const int64_t words = (nv + 31) / 32; const RadOpdDesc l[] = { opd((uint32_t)RAD_F32, M, nv), opd_sample_params(M), - /* A SET BIT MEANS ALLOWED: word w bit b covers token 32w + b, and a cleared bit sets - * -infinity. i32 and not u32 for the reason opd_sample_params gives -- a u32 operand is - * filled and compared as zeroes -- and a normal draw narrowed to i32 is a sparse mask - * rather than a plane that forbids everything. The kernel does not reach it at this params - * row anyway: `mask_row` is enormous and the row returns first. */ + /* A set bit means allowed: word w bit b covers token 32w + b; a cleared bit sets + * -infinity. i32, not u32 (see opd_sample_params). Unreached with this params row, whose + * `mask_row` is out of range. */ opd((uint32_t)RAD_I32, M, words), }; R4D_PICK(l); @@ -748,21 +655,18 @@ extern "C" int r4d_shape_sample_topk(const RadParam* p, int n_p, int operand, const int64_t M = pi(p, n_p, "M"); const int64_t nv = pi(p, n_p, "n_vocab"); - /* THE CANDIDATE WIDTH IS THE BUFFER'S, not the request's: it is the deployment bound the arena - * was sized for and every later stage reads it. No parameter carries it on this op -- `n_cand` - * is the narrowing stages' key -- so 64 is chosen here, well inside the 4096 the LDS bitonic - * sort covers. */ + /* The candidate width is the buffer's, the deployment bound every later stage reads. No + * parameter carries it on this op (`n_cand` is the narrowing stages' key), so 64 is used, + * well inside the 4096 the LDS bitonic sort covers. */ const int64_t n_cand = 64; const RadOpdDesc l[] = { opd((uint32_t)RAD_F32, M, nv), opd_sample_params(M), opd((uint32_t)RAD_I32, M, n_cand), - opd((uint32_t)RAD_F32, M, n_cand), /* cand_val -- LOGITS, not probabilities */ - /* `pairs` is the VOCAB-PARALLEL path, and it is described rather than skipped because it is - * an OUTPUT: nothing has to fill it, comparing it is what checks the packing -- (u32 global - * id, f32 logit) with a hole marker for a slot the row could not fill -- and `vocab_off` is - * zero on a single-rank graph, which makes the ids the local ones and the check exactly as - * strict. Same reading as ref's description of this operand. */ + opd((uint32_t)RAD_F32, M, n_cand), /* cand_val: logits, not probabilities */ + /* `pairs`, the vocab-parallel output: (u32 global id, f32 logit) with a hole marker for an + * unfilled slot. As an output it needs no fill, and comparing it checks the packing; with + * `vocab_off` zero on one rank the ids are local. As ref describes it. */ opd((uint32_t)RAD_I32, M, 2 * n_cand), }; R4D_PICK(l); @@ -802,12 +706,10 @@ extern "C" int r4d_shape_sample_narrow(const RadParam* p, int n_p, int operand, const int64_t M = pi(p, n_p, "M"); const int64_t nc = pi(p, n_p, "n_cand"); const RadOpdDesc l[] = { - /* EVERY DRAWN ID IS >= 0, so every candidate arrives LIVE -- a stage that dropped nothing - * because the set was already empty is the vacuous case. The range is the candidate width - * and not the vocabulary: nothing DEREFERENCES an id here, these kernels only reorder and - * drop, and `n_vocab` is not a parameter of a narrowing stage anyway. Stated rather than - * left at the ABI's default, which for operand ZERO has no previous operand to take a - * leading extent from. */ + /* Every drawn id is >= 0, so every candidate arrives live (an empty set would be + * vacuous). The range is the candidate width: these kernels only reorder and drop ids, + * and `n_vocab` is not a parameter here. Stated explicitly because operand 0 has no + * previous operand for the ABI default. */ opd_idx(M, nc, nc), opd((uint32_t)RAD_F32, M, nc), opd_sample_params(M), @@ -829,25 +731,18 @@ extern "C" int r4d_shape_sample_pick(const RadParam* p, int n_p, int operand, R4D_PICK(l); } -/* `sample_merge_topk` IS DECLINED, and ref declines it too -- deliberately the same answer, because - * a description here would supply the very bytes ref refused to. +/* `sample_merge_topk` is declined, as in ref. `gathered` is world_size * n_cand (u32 global token + * id, f32 logit) pairs in one word-typed buffer (i32 or u32 in both plugins: one buffer, one + * dtype). The logit lane is read by bit pattern, and an integer draw makes every logit a denormal; + * a device that flushes denormals then orders candidates differently from a host that does not. + * r4d_selftest's two-rank all-gather row checks exactly that. `world_size` is not a parameter + * either, so the gathered width is unknown. * - * `gathered` is world_size * n_cand (u32 GLOBAL token id, f32 logit) pairs packed into ONE - * WORD-TYPED buffer: both plugins require i32 or u32 for it, because the two halves have different - * types and a buffer has one dtype. The value lane is therefore read by BIT PATTERN, and no fill - * domain in this ABI puts a sensible float there -- an integer draw makes every logit a DENORMAL, - * and a device that flushes denormals against a host reference that does not then order the - * candidates differently. That is not hypothetical: it is the failure r4d_selftest's two-rank - * all-gather row exists to catch ("a token id is a small integer, and its bit pattern read as f32 - * is a denormal"). And `world_size` is not in this op's parameter list, so the gathered width would - * have to be invented on top of that. Either reason is sufficient. - * - * `row_topk_merge` is the same shape of operand and is NOT declined, because its plane is f32: - * there the value lane is a real float and the ID is the bit pattern, which is the way round that - * works. */ + * `row_topk_merge` has the same shape and is described, because its plane is f32: the value is a + * real float and the id is the bit pattern. */ -/* The FUSED sampler, which is a different op from the eleven above and not their composition - * (r4d_fp8.cpp). Its three outputs are what a rejection-sampling verify needs from one pass. */ +/* The fused sampler (r4d_sample_chain_f32.hip): a separate op, not a composition of the stages above. Its + * three outputs are what a rejection-sampling verify needs from one pass. */ extern "C" int r4d_shape_sample_chain(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { @@ -855,37 +750,30 @@ extern "C" int r4d_shape_sample_chain(const RadParam* p, int n_p, int operand, const int64_t nv = pi(p, n_p, "n_vocab"); const RadOpdDesc l[] = { opd((uint32_t)RAD_F32, M, nv), - /* The drafted token per position. Passed rather than left absent: `p_query` -- the accept - * probability -- is the output this op exists for, and with `query` absent the kernel - * computes two of its three answers. A token id, so it is drawn from the vocabulary. */ + /* The drafted token per position, drawn from the vocabulary. Passed because without it + * the kernel skips `p_query`, the accept probability. */ opd_idx(M, 0, nv), - /* TWO UNIFORMS A POSITION, one for the draw and one for the exclusive draw, and they have - * to be IN [0, 1): the inverse-CDF walk falls through to its last live candidate for - * anything above the mass, so a normal draw would make every position take the fallback - * and the case would check the fallback. RAD_FILL_SIGMOID is the ABI's (0, 1) domain. */ + /* Two uniforms per position (draw and exclusive draw), in (0, 1): the inverse-CDF walk + * falls through to its last live candidate above the mass, so normals would only test + * that fallback. */ in_unit(opd((uint32_t)RAD_F32, 2 * M)), - /* [M] x R4DSpecDraw = {u32 tok, u32 tok_excl, f32 p_query}: THREE dwords a position. The - * shim only checks numel >= M, which is the count of STRUCTS and not of words, so a - * description that said [M] would leave the kernel writing two thirds of its output past - * the end of the buffer. i32 rather than u32, for the reason opd_sample_params gives: a u32 - * operand is compared as zeroes and every case would pass vacuously. */ + /* [M] x R4DSpecDraw = {u32 tok, u32 tok_excl, f32 p_query}: three dwords per position. + * The shim checks only numel >= M (structs, not words), so [M] would let the kernel write + * past the buffer. i32, not u32 (see opd_sample_params). */ opd((uint32_t)RAD_I32, M, 3), }; R4D_PICK(l); } /* ========================================================================================== - * Attention (shims in r4d_attn.cpp). + * Attention (shims in the r4d_attn_*.hip units). * ========================================================================================= */ -/* attn_paged, all six rows. `q_len` is the ranged parameter -- one query row at decode, thousands - * in a prefill chunk -- and the KV cache's dtype comes from `kv_dtype`, which is what separates the - * fp8kv rows from the bf16kv ones, so one description serves the family. +/* attn_paged, all six rows. `q_len` is the ranged parameter (one row at decode, thousands in a + * prefill chunk), and `kv_dtype` separates the fp8kv rows from the bf16kv ones. * - * ONE SEQUENCE WHOSE CONTEXT IS EXACTLY ITS QUERY: a causal attention over its own prefix, which is - * what a prefill chunk runs and what a decode step's last row is. The block count follows from - * that, and the alternative -- a context longer than the query -- would need a number no parameter - * carries. */ + * One sequence attending causally over its own prefix, as a prefill chunk does; the context + * defaults to the query length (see `ctx` below) and the block count follows from it. */ extern "C" int r4d_shape_attn_paged(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { @@ -893,18 +781,15 @@ extern "C" int r4d_shape_attn_paged(const RadParam* p, int n_p, int operand, const int64_t hd = pi(p, n_p, "head_dim"); const int64_t gqa = pi(p, n_p, "gqa"); const int64_t bs = pi(p, n_p, "block_size"); - /* n_head is OPTIONAL on this op -- it is there because the split-KV scratch hook needs it at - * declare -- and without it there is no head count. tools/opshapes.h falls back to `gqa`, - * which makes one kv head; that is a different model and this declines instead. */ + /* n_head is optional on this op (the split-KV scratch hook needs it at declare). Without it + * there is no head count, so this declines; tools/opshapes.h falls back to one kv head. */ const int64_t nh = pi(p, n_p, "n_head"); if (q_len <= 0 || hd <= 0 || gqa <= 0 || bs <= 0 || nh <= 0 || nh % gqa) return RAD_E_UNSUPPORTED; const int64_t kvh = nh / gqa; - /* THE CONTEXT DEPTH. Defaults to the query length -- one sequence attending its own prefix, - * which is the prefill chunk -- and `ctx` overrides it. No op declares `ctx`: the kernel - * reads its context off `seqused` and the block table, so only a DESCRIPTION of the operands - * needs to be told, and a harness sweeping depth is the only thing that ever sets it. Must be - * at least q_len or the causal mask reads a prefix that is not there. */ + /* The context depth: the query length unless `ctx` overrides it. No op declares `ctx` (the + * kernel reads the context off `seqused` and the block table); it lets a caller sweep depth. + * It must be at least q_len, or the causal mask reads a missing prefix. */ int64_t ctx = pi(p, n_p, "ctx", 0); if (ctx < q_len) ctx = q_len; const int64_t nblk = (ctx + bs - 1) / bs; @@ -913,27 +798,24 @@ extern "C" int r4d_shape_attn_paged(const RadParam* p, int n_p, int operand, const RadOpdDesc l[] = { opd(Q, q_len, nh, hd), opd(KV, nblk, kvh, bs, 2 * hd), - /* A block-table entry indexes n_blocks and is a READ-side index, so it may repeat. */ + /* A block-table entry indexes n_blocks; it is read-side, so it may repeat. */ opd_idx(1, nblk, nblk), - /* NOT A DRAW. A context shorter than the query makes a causal attention read a prefix that - * does not exist, and both implementations would agree about the garbage while neither - * computed what the model asks for. */ + /* Fixed at ctx, not drawn: a shorter context would make causal attention read a missing + * prefix. */ opd_idx(1, 0, 0, ctx), - /* The descales are absent and that means 1.0, which is what vLLM defaults them to and what - * the fp8kv kernels assume: they are ONE number per (sequence, head) on the read side and - * cannot be derived from the tokens being written. */ + /* Absent descales mean 1.0, vLLM's default and what the fp8kv kernels assume. They are + * one number per (sequence, head) and cannot be derived from the tokens. */ opd_none(), opd_none(), - /* cu_seqlens absent = one q_len for the whole batch, which is exact at one sequence. */ + /* Absent cu_seqlens: one q_len for the whole batch, exact for one sequence. */ opd_none(), opd(Q, q_len, nh, hd), }; R4D_PICK(l); } -/* attn_paged_gate_quant -- attn_paged's operands, then gate_quant_fp8's gate, codes and scales - * over its (token, head) rows: the gate described flat as gate_quant_fp8 describes it, one row a - * (token, head) pair of `head_dim` columns. */ +/* attn_paged_gate_quant -- attn_paged's operands, then gate_quant_fp8's gate, codes and scales, + * flat as gate_quant_fp8 describes them: one row per (token, head) pair, `head_dim` columns. */ extern "C" int r4d_shape_attn_paged_gate_quant(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { if (operand < 8) return r4d_shape_attn_paged(p, n_p, operand, out); @@ -954,11 +836,11 @@ extern "C" int r4d_shape_attn_paged_gate_quant(const RadParam* p, int n_p, int o R4D_PICK(l); } -/* qk_norm_rope_gate -- the gated-attention QKV preamble (shim in r4d_quant.cpp). +/* qk_norm_rope_gate -- the gated-attention QKV preamble (shim in r4d_qk_norm_rope_gate.hip). * - * NOT docs/OPS.md's `qk_norm_rope`: it splits a [q|gate] projection per head, writes q, k and the - * gate to three destinations, and takes a PRECOMPUTED cos/sin table rather than a theta. The table - * is why `rope_table` exists at all. */ + * Not docs/OPS.md's `qk_norm_rope`: it splits a [q|gate] projection per head, writes q, k and the + * gate to three destinations, and takes a precomputed cos/sin table (from `rope_table`) instead of + * a theta. */ extern "C" int r4d_shape_qk_norm_rope_gate(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { @@ -968,35 +850,28 @@ extern "C" int r4d_shape_qk_norm_rope_gate(const RadParam* p, int n_p, int opera const int64_t nkv = pi(p, n_p, "n_head_kv"); const int64_t rot = pi(p, n_p, "rot"); const uint32_t Q = dt_act(p, n_p, "q_dtype"); - /* The two widths the kernel reads off the operands rather than off a parameter: a cos/sin - * table built in f32 and a positions vector in int64 are what the tensors SAY they are. The - * optional `cs_f32` / `pos_i64` keys are the caller's declaration of the same thing, so they - * decide what to allocate here. The arch that issues this passes cs_f32 = 1. */ + /* The kernel reads the cos/sin and position widths off the operands; the optional `cs_f32` / + * `pos_i64` keys declare the same, so they decide what is allocated here. The issuing arch + * passes cs_f32 = 1. */ const uint32_t CS = pi(p, n_p, "cs_f32", 0) ? (uint32_t)RAD_F32 : (uint32_t)RAD_BF16; const RadOpdDesc l[] = { - /* THE PROJECTION WHOLE, q and gate interleaved per head -- the kernel splits it itself, - * which is what the fusion replaces. Declared flat: the shim folds every trailing extent - * into one row pitch, so [M, n_head * 2 * head_dim] and [M, n_head, 2 * head_dim] are the - * same bytes and the same pitch. */ - /* ABSENT IN THE K-ONLY FORM (`n_head` 0), where there is no gate to split and every head - * the op serves is read off `k`. A zero-width operand would be a different statement -- - * "a tensor of no columns" rather than "no tensor" -- and the shim checks for the second. */ + /* The whole projection, q and gate interleaved per head; the kernel splits it. Flat: the + * shim folds trailing extents into one row pitch. Absent in the k-only form (`n_head` 0); + * the shim checks for no tensor, not a zero-width one. */ nq ? opd(Q, M, nq * 2 * hd) : opd_none(), opd(Q, M, nkv * hd), - /* The [max_ctx, rot] plane, at one row per position of this band. A position indexes a ROW - * of it, so the table's row count is the draw's bound -- and unlike `rope`, this one is a - * LOOKUP: a position past the end reads another layer's angles or nothing at all. */ + /* The [max_ctx, rot] plane, one row per position of this band. Unlike `rope`, a position + * is a lookup into it, so the table's row count bounds the draw. */ opd(CS, M, rot), opd_idx(M, 0, M), - /* The QK norm gains, one per head channel. f32 in every architecture plugin here where - * vLLM's are bf16, and the shim requires the two to agree because one flag serves both. */ + /* The QK norm gains, one per head channel: f32 in every architecture plugin here (vLLM's + * are bf16). The shim requires both to agree, since one flag serves both. */ nq ? opd((uint32_t)RAD_F32, hd) : opd_none(), opd((uint32_t)RAD_F32, hd), nq ? opd(Q, M, nq * hd) : opd_none(), opd(Q, M, nkv * hd), - /* `gate_out` absent, which is what the fp8 gated attention block passes: `gate_quant_fp8` - * reads the gate at its column offset inside the projection, so a contiguous copy would be - * q_dim of bf16 a layer written for nothing. */ + /* `gate_out` absent, as the fp8 gated attention block passes it: `gate_quant_fp8` reads + * the gate in place inside the projection. */ opd_none(), }; R4D_PICK(l); @@ -1024,7 +899,7 @@ extern "C" int r4d_shape_qk_norm_rope_gate_kv_store(const RadParam* p, int n_p, R4D_PICK(l); } -/* rope_table -- the cos/sin plane the fused prologue reads (shim in r4d_quant.cpp). */ +/* 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) { @@ -1032,10 +907,9 @@ extern "C" int r4d_shape_rope_table(const RadParam* p, int n_p, int operand, const int64_t rot = pi(p, n_p, "rot"); const uint32_t D = dt_act(p, n_p, "dtype"); const RadOpdDesc l[] = { - /* ONLY THE ROWS `positions` NAMES ARE WRITTEN, at each position's OWN row of the plane, so - * the draw's bound is the plane's row count and a position outside it would scribble past - * the table. The real table is [max_ctx, rot]; M rows is the smallest one that holds every - * row this band can name. */ + /* Only the rows `positions` names are written, each at its own row, so the plane's row + * count bounds the draw. The real table is [max_ctx, rot]; M rows holds every row this + * band can name. */ opd_idx(M, 0, M), opd(D, M, rot), }; @@ -1043,16 +917,14 @@ extern "C" int r4d_shape_rope_table(const RadParam* p, int n_p, int operand, } /* ========================================================================================== - * Gated delta net -- the one row of the family whose widths are all parameters. The other five are - * declined; see the file header on the head counts. (`gdn_gated_norm_had_quant_i8` is describable - * for the same reason and is with the fusions below, where its siblings are.) + * Gated delta net -- the one row of the family whose widths are all parameters; the other five are + * declined (file header). `gdn_gated_norm_had_quant_i8` is with the fusions below. * ========================================================================================= */ extern "C" int r4d_shape_gdn_gated_rmsnorm(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { - /* ONE ROW IS ONE (token, head): `M` is already tokens x heads and `channels` is head_v, which - * is what makes this op describable where the rest of the family is not. */ + /* One row per (token, head): `M` is tokens x heads and `channels` is head_v. */ const int64_t M = pi(p, n_p, "M"); const int64_t ch = pi(p, n_p, "channels"); const RadOpdDesc l[] = { @@ -1065,25 +937,23 @@ extern "C" int r4d_shape_gdn_gated_rmsnorm(const RadParam* p, int n_p, int opera } /* ========================================================================================== - * Collectives (shims in r4d_ar.cpp). + * Collectives (shims in r4d_ar_entry.hip). * - * These need a real peer over IPC, so a single-process tool gets RAD_E_STATE from init long before - * it gets to the buffers. Described anyway: the description is not what decides that, and a - * two-process harness needs it the moment one exists. + * These need a real peer over IPC, so a single-process tool gets RAD_E_STATE from init. They are + * described for a two-process caller. * ========================================================================================= */ extern "C" int r4d_shape_all_reduce(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { - /* `numel` is the LARGEST message this instance will ever carry -- init sizes the peer scratch - * from it once and the launch reads the real count off the tensor -- so it is exactly the - * extent a buffer has to have. */ + /* `numel` is the largest message the instance carries (init sizes the peer scratch from it; + * the launch reads the real count off the tensor), so it is the buffer extent. */ const int64_t numel = pi(p, n_p, "numel"); const uint32_t D = dt_act(p, n_p, "dtype"); const RadOpdDesc l[] = { opd(D, numel), - /* The optional SECOND DESTINATION. Absent means in place, which every row of the op - * serves; described so a caller that passes one is checked against the same extent. */ + /* The optional second destination; absent means in place. Described so a caller that + * passes one is checked against the same extent. */ opd(D, numel), }; R4D_PICK(l); @@ -1095,16 +965,14 @@ extern "C" int r4d_shape_all_gather(const RadParam* p, int n_p, int operand, const int64_t numel = pi(p, n_p, "numel"); const int64_t world = pi(p, n_p, "world_size"); const uint32_t D = dt_act(p, n_p, "dtype"); - /* `row` absent means the whole message is one row and `y` is the plain concatenation, rank r's - * slice at r * numel. The row-INTERLEAVED form is the same extent at a different placement, so - * this description covers both. */ + /* `row` absent: the message is one row and `y` the plain concatenation, rank r's slice at + * r * numel. The row-interleaved form has the same extent, so this covers both. */ const RadOpdDesc l[] = { opd(D, numel), opd(D, world * numel) }; R4D_PICK(l); } -/* The two fused all-reduce + norm folds. Same operands in the same order as the standalone norms - * they replace, which is the property that makes them substitutable -- so these two descriptions - * are the standalone ones with `x` reread as the message. */ +/* The two fused all-reduce + norm folds. Their operands match the standalone norms they replace, + * in order, with `x` also the message. */ extern "C" int r4d_shape_ar_ln_had_quant_i8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { @@ -1114,14 +982,13 @@ extern "C" int r4d_shape_ar_ln_had_quant_i8(const RadParam* p, int n_p, int oper const RadOpdDesc l[] = { opd((uint32_t)RAD_BF16, M, n), opd((uint32_t)RAD_BF16, M, n), /* residual: the fused_add_rms_norm form */ - /* THE GAIN IS BF16 ON THE INT8 SIDE, unlike the fp8 twin below whose shim reads the width - * off the operand: r4d_ar_ln_had_quant_i8 takes `wgain` as __hip_bfloat16 and has no flag - * for anything else. An f32 gain here would be read as two bf16 halves of the wrong - * number, which is the silent kind of wrong. */ + /* The gain is bf16 on the int8 side: r4d_ar_ln_had_quant_i8 takes `wgain` as + * __hip_bfloat16 with no flag (the fp8 twin below reads the width off the operand). An f32 + * gain would silently be read as two wrong bf16 values. */ opd((uint32_t)RAD_BF16, n), opd((uint32_t)RAD_I8, M, n), - /* ONE SCALE PER ROW -- the rotation is what makes that viable, and it carries the - * 1/sqrt(had) normalisation as well. Not a per-group plane: this family has no group. */ + /* One scale per row, viable because of the rotation; it also carries the 1/sqrt(had) + * normalisation. This family has no scale group. */ opd((uint32_t)RAD_F32, M, 1), opd((uint32_t)RAD_BF16, M, n), /* out_bf16, for a bf16 consumer of the post-norm row */ }; @@ -1134,12 +1001,10 @@ extern "C" int r4d_shape_ar_rmsnorm_quant_fp8(const RadParam* p, int n_p, int op const int64_t M = pi(p, n_p, "M"); const int64_t n = pi(p, n_p, "n"); const int64_t g = pi(p, n_p, "group", R4D_FP8_BLOCK); - /* The block is a property of the checkpoint's scale grid and not a knob: a geometry that - * declares a different one is asking for a format the GEMM's fold does not read, and the shim - * refuses it by name rather than substituting 128. */ + /* The block is the checkpoint's scale grid, not a knob; the shim refuses any other. */ if (g != R4D_FP8_BLOCK) return RAD_E_UNSUPPORTED; const RadOpdDesc l[] = { - opd((uint32_t)RAD_BF16, M, n), /* INOUT: the message AND the input */ + opd((uint32_t)RAD_BF16, M, n), /* inout: the message and the input */ opd((uint32_t)RAD_BF16, M, n), opd((uint32_t)RAD_F32, n), /* f32 or bf16; the shim reads the operand's own */ opd((uint32_t)RAD_F8E4M3, M, n), @@ -1150,7 +1015,8 @@ extern "C" int r4d_shape_ar_rmsnorm_quant_fp8(const RadParam* p, int n_p, int op } /* ========================================================================================== - * GEMM, dequant and the row top-R (shims in r4d_gemm.cpp and r4d_fp8.cpp). + * GEMM, dequant and the row top-R (shims in the r4d_gemm_*.hip units, r4d_dequant_w4_bf16.hip and + * r4d_rowtopk_bf16.hip). * ========================================================================================= */ extern "C" int r4d_shape_gemm_nt(const RadParam* p, int n_p, int operand, @@ -1164,13 +1030,10 @@ extern "C" int r4d_shape_gemm_nt(const RadParam* p, int n_p, int operand, R4D_PICK(l); } -/* gemm_nt_q, THE BLOCK-SCALED FP8 FAMILY ONLY. The other five grids are declined; the file header - * says why, and it is the same argument tools/opshapes.h makes from the other side. - * - * The grid here is stated by the CHECKPOINT -- E4M3 [N][K] against a bf16 - * [ceil(N/128)][ceil(K/128)] plane, with `group` carrying the 128 -- so there is nothing left to - * guess. The fragment-ordered arrangement the narrow and tiled rows read is a permutation of the - * same bytes (frag_bytes(N, K) == N * K), so one description sizes every row of the family. */ +/* gemm_nt_q, the block-scaled fp8 family only; the other five grids are declined (file header). + * The checkpoint fixes the grid: E4M3 [N][K] against a bf16 [ceil(N/128)][ceil(K/128)] plane, + * `group` carrying the 128. The fragment order the narrow and tiled rows read is a permutation of + * the same bytes (frag_bytes(N, K) == N * K), so one description sizes every row. */ extern "C" int r4d_shape_gemm_nt_q(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { @@ -1184,25 +1047,22 @@ extern "C" int r4d_shape_gemm_nt_q(const RadParam* p, int n_p, int operand, if ((!a8 && !a16) || g != R4D_FP8_BLOCK || K <= 0 || N <= 0) return RAD_E_UNSUPPORTED; const int64_t kb = (K + g - 1) / g, nb = (N + g - 1) / g; const RadOpdDesc l[] = { - /* a, a_scale. The matvec reads the bf16 activation DIRECTLY -- there is no quantise launch - * in front of it -- and its shim refuses an activation scale outright, because running - * anyway would silently drop a scale the caller believes was applied. */ + /* a, a_scale. The matvec reads the bf16 activation directly, and its shim refuses an + * activation scale rather than silently ignoring it. */ a8 ? opd((uint32_t)RAD_F8E4M3, M, K) : opd((uint32_t)RAD_BF16, M, K), a8 ? opd((uint32_t)RAD_F32, M, kb) : opd_none(), opd((uint32_t)RAD_F8E4M3, N, K), /* the checkpoint's own bytes */ opd((uint32_t)RAD_BF16, nb, kb), /* weight_scale_inv, one per 128x128 tile */ opd((uint32_t)RAD_BF16, M, N), - /* `a_sum` belongs to the asymmetric integer grids and `b_ref` to mxfp4. An fp8 grid is - * symmetric by construction and has neither. */ + /* `a_sum` belongs to the asymmetric integer grids and `b_ref` to mxfp4; fp8 has neither. */ opd_none(), opd_none(), }; R4D_PICK(l); } -/* The same GEMM with the SwiGLU and the quantiser folded into its epilogue. `N` is the WEIGHT's - * rows -- twice the fused width, gate then up -- so the quantiser's outputs are N/2 wide, and that - * factor is the whole reason this op has a schema of its own rather than a flag on gemm_nt_q. */ +/* The same GEMM with the SwiGLU and the quantiser in its epilogue. `N` is the weight's rows, gate + * then up, so the quantiser's outputs are N/2 wide (hence a schema of its own). */ extern "C" int r4d_shape_gemm_nt_q_gated(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { @@ -1227,18 +1087,15 @@ extern "C" int r4d_shape_gemm_nt_q_gated(const RadParam* p, int n_p, int operand R4D_PICK(l); } -/* dequant_w4 -- the packed 4-bit weight back to row-major bf16 (shim in r4d_gemm.cpp). +/* dequant_w4 -- the packed 4-bit weight back to row-major bf16 (shim in r4d_dequant_w4_bf16.hip). * - * The one weight in this plugin whose packed stream a PUBLIC dtype sizes exactly: RAD_I4 is four - * bits an element, so [N, K] is the N*K/2 bytes r4d_rad_layout_w4 declares. The scale plane is one - * (f16 scale, f16 -(1024+zero)) dword per (row, group), stored tile-major as [N/16][K/group][16] -- - * which is N * (K/group) dwords however it is grouped, and the kernel reads it at + * The one packed weight a public dtype sizes exactly: RAD_I4 is four bits per element, so [N, K] + * is the N*K/2 bytes r4d_rad_layout_w4 declares. The scale plane is one (f16 scale, + * f16 -(1024+zero)) dword per (row, group), tile-major [N/16][K/group][16], read at * [(t * ng + k/group) * 16 + r]. * - * NEITHER STREAM'S CONTENT IS EXPRESSIBLE and that is worth knowing before reading a result: a - * packed nibble plane and a scale dword are bit layouts, not numbers, so the caller's fill leaves - * them zeroed or filled with small integers. The extents are exact, which is what a timing harness - * needs; a correctness comparison would be comparing two dequantisations of the same nonsense. */ + * Neither stream's content is expressible (bit layouts, not numbers), so the extents are exact for + * timing but a correctness comparison here means nothing. */ extern "C" int r4d_shape_dequant_w4(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { @@ -1248,7 +1105,8 @@ extern "C" int r4d_shape_dequant_w4(const RadParam* p, int n_p, int operand, if (N <= 0 || K <= 0 || g <= 0 || N % R4D_NTILE || K % g) return RAD_E_UNSUPPORTED; const RadOpdDesc l[] = { opd((uint32_t)RAD_I4, N, K), - opd((uint32_t)RAD_U32, N / R4D_NTILE, (K / g) * R4D_NTILE), + /* i32, not u32: a u32 operand is filled with zeroes (see opd_sample_params). */ + opd((uint32_t)RAD_I32, N / R4D_NTILE, (K / g) * R4D_NTILE), opd((uint32_t)RAD_BF16, N, K), }; R4D_PICK(l); @@ -1256,14 +1114,11 @@ extern "C" int r4d_shape_dequant_w4(const RadParam* p, int n_p, int operand, /* ---- the routed mixture of experts (shims in r4d_moe.hip) -------------------------------------- * - * `expert_offset` IS NOT A FREE DRAW and no fill domain in the ABI says so: it is moe_scatter's - * output, a non-decreasing prefix array ending at the live row count, and the expert that owns a - * sorted row is found by searching it. Drawn at random it is a malformed histogram, so two - * implementations that search it differently can pick different experts and disagree without - * either being wrong. The EXTENTS are exactly right, which is what a benchmark needs; a - * correctness comparison over an op that reads it proves less than it looks like. libref's - * description of the same operand says the same thing, which is the point -- the two plugins have - * to agree about what a case means before they can be compared. */ + * `expert_offset` is moe_scatter's output, a non-decreasing prefix array ending at the live row + * count, searched to find a sorted row's expert. No ABI fill domain produces that, so a random draw + * is a malformed histogram and two implementations may search it differently without either being + * wrong. The extents are right for a benchmark; a correctness comparison over an op that reads it + * proves little. libref describes the operand the same way. */ extern "C" int r4d_shape_scale_rows(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"); if (M <= 0 || n <= 0) return RAD_E_UNSUPPORTED; @@ -1272,9 +1127,8 @@ extern "C" int r4d_shape_scale_rows(const RadParam* p, int n_p, int operand, Rad R4D_PICK(l); } -/* The per-tensor scalar: one [1] weight broadcast over the whole [M, n] extent. `s` is the middle - * operand; its extent is 1, not M (that would be scale_rows) and not M*n (that would be a - * per-element mask). The scalar's dtype is the stream's, so a bf16 or f32 `s` both read. */ +/* The per-tensor scalar: one [1] weight `s` (the middle operand) broadcast over [M, n]. Its dtype + * is the stream's, bf16 or f32. */ extern "C" int r4d_shape_scale(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"); if (M <= 0 || n <= 0) return RAD_E_UNSUPPORTED; @@ -1297,18 +1151,17 @@ extern "C" int r4d_shape_router_topk(const RadParam* p, int n_p, int operand, Ra R4D_PICK(l); } -/* The two shape functions concatenated, with `expert_ids` named ONCE -- it is an output here, not - * an input, which is the only difference between this list and the pair's two. */ +/* router_topk's and moe_scatter's lists concatenated, with `expert_ids` named once (here an + * output). */ extern "C" int r4d_shape_router_topk_scatter(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = pi(p, n_p, "M"); const int64_t ne = pi(p, n_p, "n_expert"); const int64_t k = pi(p, n_p, "top_k"); if (ne <= 0 || ne > 256 || k <= 0 || k > ne) return RAD_E_UNSUPPORTED; - /* The sort's single-workgroup bound, stated here too so the workbench never draws a shape the - * shim will refuse. 1024 is `kScatterSmall`. */ + /* The sort's single-workgroup bound (`kScatterSmall`), which the shim enforces. */ if (M * k > 1024) return RAD_E_UNSUPPORTED; - /* The sort's three outputs are sized by THIS RANK'S SLICE, not by the router. */ + /* The sort's three outputs are sized by this rank's slice of experts, not by the router. */ const int64_t nl = pi(p, n_p, "n_local", ne); if (nl <= 0 || nl > ne) return RAD_E_UNSUPPORTED; const uint32_t D = dt_act(p, n_p, "dtype"); @@ -1322,16 +1175,16 @@ extern "C" int r4d_shape_router_topk_scatter(const RadParam* p, int n_p, int ope }; R4D_PICK(l); } -/* The router's gemm_nt in front of router_topk_scatter, and the shared gate's gemm_nt at N = 1 - * beside it: the three lists, with `logits` named once as the GEMM's output. */ +/* The router's gemm_nt before router_topk_scatter, plus the shared gate's gemm_nt at N = 1: the + * three lists, with `logits` named once as the GEMM's output. */ extern "C" int r4d_shape_router_gemm_topk_scatter(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = pi(p, n_p, "M"); const int64_t K = pi(p, n_p, "K"); const int64_t ne = pi(p, n_p, "n_expert"); const int64_t k = pi(p, n_p, "top_k"); - /* 512 experts: the selection keeps sixteen logits a lane (kMaxExpert in r4d_moe.hip), which - * is the shim's bound and the row's constraint. */ + /* At most 512 experts: the selection keeps sixteen logits per lane (kMaxExpert in + * r4d_moe.hip), the shim's bound and the row's constraint. */ if (ne <= 0 || ne > 512 || k <= 0 || k > ne || K <= 0) return RAD_E_UNSUPPORTED; if (M > 64 || M * k > 1024) return RAD_E_UNSUPPORTED; const int64_t nl = pi(p, n_p, "n_local", ne); @@ -1357,7 +1210,7 @@ extern "C" int r4d_shape_moe_scatter(const RadParam* p, int n_p, int operand, Ra const int64_t k = pi(p, n_p, "top_k"); if (ne <= 0 || ne > 256 || k <= 0) return RAD_E_UNSUPPORTED; const RadOpdDesc l[] = { - /* Expert ids index EXPERTS, which is no operand's dim 0, so the range is stated. */ + /* Expert ids index experts, no operand's dim 0, so the range is stated. */ opd_idx(M, k, ne, -1), opd((uint32_t)RAD_I32, M * k), opd((uint32_t)RAD_I32, ne + 1), @@ -1379,25 +1232,23 @@ extern "C" int r4d_shape_moe_gemm_q(const RadParam* p, int n_p, int operand, Rad const int64_t N = N0 > N1 ? N0 : N1, K = K0 > K1 ? K0 : K1; const int64_t ne0 = (ne + 1) / 2, ne1 = ne / 2; const uint32_t D = dt_act(p, n_p, "dtype"); - /* `a_order` decides the activation's row count: one per token, or one per (token, slot) - * already in the scatter's order. A description that took the wrong reading would build the - * operand at the other extent, and nothing about the case would look like a shape error. */ + /* `a_order` sets the activation's row count: one per token, or one per (token, slot) already + * in scatter order ("sorted"). */ const char* ord = rad_param_gets(p, n_p, "a_order", nullptr); const int64_t AR = (ord && !std::strcmp(ord, "sorted")) ? M * k : M; const RadOpdDesc l[] = { opd((uint32_t)RAD_F8E4M3, AR, K), /* a -- see `a_order` */ opd((uint32_t)RAD_F32, AR, (K + g - 1) / g), /* a_scale */ - /* THE WEIGHT OPERANDS ARE TABLES at issue and are described here as the STACKED plane they - * would be if they were one tensor. A fixture has nowhere to put a pointer array, and the - * kernel reads both forms (r4d_moe.hip, wtab_at) precisely so that a described case runs - * against the same bytes the engine would hand it. */ + /* The weight operands are tables when issued, described here as one stacked plane; a + * fixture cannot hold a pointer array, and the kernel reads both forms (r4d_moe.hip, + * wtab_at). */ opd((uint32_t)RAD_F8E4M3, ne0, N0, K0), /* w -- the even experts */ opd((uint32_t)RAD_BF16, ne0, (N0 + g - 1) / g, (K0 + g - 1) / g), /* w_scale */ opd_idx(M * k, 0, M * k, -1), /* sorted_tok */ opd_idx(ne + 1, 0, M * k + 1, -1), /* expert_offset -- see the note above */ opd((uint32_t)RAD_F8E4M3, ne1, N1, K1), /* w_odd -- the odd experts */ opd((uint32_t)RAD_BF16, ne1, (N1 + g - 1) / g, (K1 + g - 1) / g), /* w_odd_scale */ - opd(D, M * k, N), /* y -- in SORTED order */ + opd(D, M * k, N), /* y, in sorted order */ }; R4D_PICK(l); } @@ -1453,12 +1304,10 @@ extern "C" int r4d_shape_moe_gather(const RadParam* p, int n_p, int operand, Rad const RadOpdDesc l[] = { opd(D, M * k, n), opd(D, M, k), - /* DISTINCT, and it has to be: gather rebuilds the INVERSE permutation of sorted_tok, so a - * repeated entry makes two sorted rows claim one (token, slot) and the last writer wins -- - * by whichever workgroup lands last, which is a measurement of the scheduler. */ + /* Distinct: gather rebuilds the inverse permutation of sorted_tok, and a repeated entry + * would let two sorted rows race for one (token, slot). */ opd_idx(M * k, 0, M * k, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE), - /* shared and shared_gate -- optional, described anyway so a cold caller allocates them - * and exercises the folded form. */ + /* shared and shared_gate: optional, described so a caller exercises the folded form. */ opd(D, M, n), opd(D, M), opd(D, M, n), @@ -1466,11 +1315,8 @@ extern "C" int r4d_shape_moe_gather(const RadParam* p, int n_p, int operand, Rad R4D_PICK(l); } -/* row_topk -- exact per-row top-R of a wide bf16 matrix (shim in r4d_gemm.cpp). - * - * R is capped at 32 by the entry point (stage 2's PT, "a real limit, not a tuning choice") even - * though libr4d's own row says 1024; the constraint is transcribed as written and the shim refuses - * above 32, so a band naming a wider R is declined here rather than described into a refusal. */ +/* row_topk -- exact per-row top-R of a wide bf16 matrix (shim in r4d_rowtopk_bf16.hip). R is at + * most 32, stage 2's PT. */ extern "C" int r4d_shape_row_topk(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { @@ -1483,13 +1329,10 @@ extern "C" int r4d_shape_row_topk(const RadParam* p, int n_p, int operand, opd(D, M, N), opd((uint32_t)RAD_I32, M, R), opd((uint32_t)RAD_F32, M, R), - /* `pairs` is the VOCAB-PARALLEL form and both halves of it are optional -- absent, with - * `vocab_off` zero, is the single-rank launch bit for bit. It is described anyway, and for - * the reason ref's description of the same operand gives: it is an OUTPUT, so nothing has - * to fill it, and comparing it is what checks the packing convention -- an int32 id - * memcpy'd into the first float slot beside its value, with id -1 for a slot the row could - * not fill. f32 for exactly that reason: the ID is carried by BIT PATTERN, and a - * word-typed plane could not hold the value. */ + /* `pairs`, the vocab-parallel output (optional; absent with `vocab_off` zero is the + * single-rank launch). Described, as in ref, because comparing it checks the packing: an + * int32 id memcpy'd into the first float slot beside its value, id -1 for an unfilled + * slot. f32 because the id travels as a bit pattern while the value must be a float. */ opd((uint32_t)RAD_F32, M, R, 2), }; R4D_PICK(l); @@ -1503,15 +1346,12 @@ extern "C" int r4d_shape_row_topk_merge(const RadParam* p, int n_p, int operand, const int64_t W = pi(p, n_p, "world_size"); if (R > 32) return RAD_E_UNSUPPORTED; const RadOpdDesc l[] = { - /* [M, world_size * R, 2] f32 pairs with rank r's at [r*R, (r+1)*R), an int32 id in the - * first slot of each. THE PLANE IS f32 AND THAT IS WHY THIS ONE IS DESCRIBABLE where - * `sample_merge_topk`'s is not: a normal fill puts a REAL float in the value lane, which is - * the lane the merge orders on, and the id lane is that same float's bit pattern read as an - * int32. A negative float is then a negative id, which the kernel drops as a pad - * (`if (id < 0) continue`), and a positive one is a large but perfectly legal id that is - * only ever compared against the others and copied out. So about half the candidates are - * pads and the rest are ordered exactly -- ties are impossible between distinct normals -- - * which exercises the pad rule and the ordering in one case. */ + /* [M, world_size * R, 2] f32 pairs, rank r's at [r*R, (r+1)*R), an int32 id in the first + * slot of each. Describable, unlike `sample_merge_topk`, because the plane is f32: a normal + * fill puts a real float in the value lane the merge orders on, and the id lane reads the + * same bits as an int32. A negative id is a pad the kernel drops, a positive one a large + * legal id, so about half the candidates are pads and the rest are ordered without ties, + * exercising both rules. */ opd((uint32_t)RAD_F32, M, W * R, 2), opd((uint32_t)RAD_I32, M, R), opd((uint32_t)RAD_F32, M, R), @@ -1519,10 +1359,8 @@ extern "C" int r4d_shape_row_topk_merge(const RadParam* p, int n_p, int operand, R4D_PICK(l); } -/* pair_argmax (r4d_pair_argmax_f32.hip): row_topk_merge at R = 1 over `n` gathered pairs, so the - * same f32 plane and the same reading of it -- the value lane draws proper floats, the id lane - * their bit patterns, a negative one a pad and a positive one a legal id -- and one id and one - * value a row out. */ +/* pair_argmax (r4d_pair_argmax_f32.hip): row_topk_merge at R = 1 over `n` gathered pairs, with + * the same f32 plane and fill reading, and one id and one value out per row. */ extern "C" int r4d_shape_pair_argmax(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"); if (M <= 0 || n <= 0) return RAD_E_UNSUPPORTED; @@ -1535,14 +1373,12 @@ extern "C" int r4d_shape_pair_argmax(const RadParam* p, int n_p, int operand, Ra } /* ========================================================================================== - * Quantisation, the norms and the fusions (shims in r4d_quant.cpp and r4d_fp8.cpp). + * Quantisation, the norms and the fusions (shims beside their kernels). * - * TWO FAMILIES, AND THE SCALE IS WHAT SEPARATES THEM. The int8 side is ROTATED and carries ONE f32 - * scale per row -- the block Walsh-Hadamard is what makes a single scale per row viable at all -- - * and its `group` parameter is the ROTATION WIDTH, not a scale grid. - * The fp8 side has no rotation and carries an f32 scale per (row, 128 columns), because 128 - * is the block the CHECKPOINT's weight scales are taken over. A description that swapped the two - * would be off by a factor of n/128 on the scale plane and would still look plausible. + * Two families, separated by the scale. The int8 side carries one f32 scale per row; its `group` + * is the rotation width of the rotated forms (the block Walsh-Hadamard makes one scale viable) and + * the width of quant_act_i8's code sums, never a scale grid. The fp8 side is not rotated and + * carries an f32 scale per (row, 128 columns), the block the checkpoint's weight scales use. * ========================================================================================= */ extern "C" int r4d_shape_quant_act_i8(const RadParam* p, int n_p, int operand, @@ -1550,26 +1386,15 @@ extern "C" int r4d_shape_quant_act_i8(const RadParam* p, int n_p, int operand, const int64_t M = pi(p, n_p, "M"); const int64_t n = pi(p, n_p, "n"); + const int64_t g = pi(p, n_p, "group"); const uint32_t D = dt_act(p, n_p, "dtype"); const RadOpdDesc l[] = { opd(D, M, n), opd((uint32_t)RAD_I8, M, n), - /* ONE SCALE PER ROW, AND THIS IS WHERE THE TWO PLUGINS DISAGREE ABOUT `group`. - * r4d_quant_act_i8 takes no group argument at all: its kernel writes `S[row] = amax/127` - * and nothing else, whatever `group` says -- the key reaches this op only to size the - * `_asum` form's per-group sums. ref's `quant_act_i8` reads `group` as the number of - * elements sharing one scale and writes ceil(n/group) of them a row, so at the - * declaration the MTP block makes (n = n_embd, group = 128) the two produce different - * planes and only libr4d's is what the w2a8 GEMM consumes. This description says what THIS - * kernel writes; the disagreement is real and is reported rather than papered over by - * describing a plane libr4d never fills. */ opd((uint32_t)RAD_F32, M, 1), - /* THE THIRD OUTPUT SELECTS THE `_asum` FORM, whose [K/group][ceil(M/16)*16] group-major - * sums the ASYMMETRIC weight grids subtract. Absent here: it is the form the engine - * issues, and libref implements no asymmetric grid, so passing the buffer would - * compare a zeroed reference against a real one and report a gap in the ORACLE as a fault - * in the kernel. */ - opd_none(), + /* The `_asum` form's group-major sums: whole 16-row tiles, as the asymmetric GEMMs read + * them. */ + g > 0 && n % g == 0 ? opd((uint32_t)RAD_F32, n / g, (M + 15) / 16 * 16) : opd_none(), }; R4D_PICK(l); } @@ -1599,8 +1424,8 @@ extern "C" int r4d_shape_rmsnorm_had_quant_i8(const RadParam* p, int n_p, int op opd(D, M, n), /* residual, the fused_add_rms_norm form */ opd((uint32_t)RAD_BF16, n), /* bf16 gain; see r4d_shape_ar_ln_had_quant_i8 */ opd((uint32_t)RAD_I8, M, n), - opd((uint32_t)RAD_F32, M, 1), /* one scale per ROW */ - opd(D, M, n), /* out_bf16, UNROTATED, for a bf16 consumer */ + opd((uint32_t)RAD_F32, M, 1), /* one scale per row */ + opd(D, M, n), /* out_bf16, unrotated, for a bf16 consumer */ }; R4D_PICK(l); } @@ -1612,13 +1437,12 @@ extern "C" int r4d_shape_gated_had_quant_i8(const RadParam* p, int n_p, int oper const int64_t n = pi(p, n_p, "n"); const uint32_t D = dt_act(p, n_p, "dtype"); const RadOpdDesc l[] = { - /* THE PACKED gate_up FORM: `b` absent means the two halves are one [M, 2n] tensor and `b` - * is `a + n`, which is vLLM's layout and the one the MLP actually produces. The two-buffer - * form is the same op at a different pitch, and only one of the two can be described. */ + /* The packed gate_up form: `b` absent means one [M, 2n] tensor with `b` at `a + n`, vLLM's + * layout and what the MLP produces. The two-buffer form differs only in pitch. */ opd(D, M, 2 * n), opd_none(), opd((uint32_t)RAD_I8, M, n), - opd((uint32_t)RAD_F32, M, 1), /* one scale per ROW */ + opd((uint32_t)RAD_F32, M, 1), /* one scale per row */ }; R4D_PICK(l); } @@ -1630,26 +1454,24 @@ extern "C" int r4d_shape_gdn_gated_norm_had_quant_i8(const RadParam* p, int n_p, const int64_t n = pi(p, n_p, "n"); const int64_t hd = pi(p, n_p, "head_dim"); const uint32_t D = dt_act(p, n_p, "dtype"); - /* The RMS is per HEAD while the rotation and the int8 scale are per TOKEN, which is why this - * fusion has no unfused equivalent in the vocabulary -- and why the gain is head_dim floats - * and not n of them. The shim checks exactly that (`wgain is 128 floats, not K`). + /* The RMS is per head while the rotation and the int8 scale are per token (so no unfused + * equivalent exists), and the gain is head_dim floats, not n; the shim checks this. * - * `zgrp` / `zblk` describe an INTERLEAVED qkvz projection, where element i of the flattened - * row sits at (i / zblk) * zgrp + (i % zblk). Absent means a contiguous gate, which is the - * shape this describes; the interleaved one is a column view of a wider plane whose width no - * parameter of this op carries. */ + * `zgrp` / `zblk` describe an interleaved qkvz projection, element i of the flattened row at + * (i / zblk) * zgrp + (i % zblk). Only the contiguous gate is described; the interleaved one + * is a column view of a plane whose width no parameter carries. */ if (pi(p, n_p, "zgrp", 0) != 0) return RAD_E_UNSUPPORTED; const RadOpdDesc l[] = { opd(D, M, n), opd(D, M, n), opd((uint32_t)RAD_F32, hd), opd((uint32_t)RAD_I8, M, n), - opd((uint32_t)RAD_F32, M, 1), /* one scale per ROW */ + opd((uint32_t)RAD_F32, M, 1), /* one scale per row */ }; R4D_PICK(l); } -/* ---- the fp8 side. `group` is the SCALE GRID here and is 128 by the checkpoint. ---- */ +/* ---- the fp8 side. `group` is the scale grid here, 128 from the checkpoint. ---- */ extern "C" int r4d_shape_quant_act_fp8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { @@ -1657,7 +1479,7 @@ extern "C" int r4d_shape_quant_act_fp8(const RadParam* p, int n_p, int operand, const int64_t M = pi(p, n_p, "M"); const int64_t n = pi(p, n_p, "n"); const int64_t g = pi(p, n_p, "group", R4D_FP8_BLOCK); - const uint32_t D = dt_act(p, n_p, "dtype"); /* the INPUT's width; the output is E4M3 */ + const uint32_t D = dt_act(p, n_p, "dtype"); /* the input's width; the output is E4M3 */ if (g != R4D_FP8_BLOCK) return RAD_E_UNSUPPORTED; const RadOpdDesc l[] = { opd(D, M, n), @@ -1667,19 +1489,8 @@ extern "C" int r4d_shape_quant_act_fp8(const RadParam* p, int n_p, int operand, R4D_PICK(l); } -/* H += X^T X. `n` is K on BOTH axes of the accumulator, which is what makes this op's shape hook - * worth reading: a caller that passed a [M][n] `h` by analogy with every other op here would be - * refused by name rather than silently accumulating a row block. */ -/* The QSA compressed key. `M` is BLOCKS and the key operand is `ratio` times taller, which is the - * one thing a caller sizing buffers off this hook has to read rather than assume. */ -/* The QSA block score. `pages` is the block-key store's height and is NOT derivable from this - * op's parameters -- it is however many pages the KV pool has, which the runtime decides -- so the - * hook reports the widest thing a table entry can address and a caller sizing a store off it is - * getting a bound, not the plan. `bt` entries are PAGE IDS. */ -/* The QSA selection. `sel` is `topk + 1` wide and the extra slot is the PARTIAL PAGE, not spare: - * sized at `topk` it would drop the newest tokens on three queries in four. */ -/* The work list. `M` is the TOKEN count and `work` the block bound, and they are different - * numbers with different meanings -- one op, two extents, which is why both are parameters. */ +/* The QSA work list. `M` is the token count and `work` the block bound: two different extents, + * hence two parameters. */ extern "C" int r4d_shape_qsa_work(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = pi(p, n_p, "M"); @@ -1693,13 +1504,13 @@ extern "C" int r4d_shape_qsa_work(const RadParam* p, int n_p, int operand, RadOp const RadOpdDesc l[] = { opd(D, M, n), opd_idx(M, 1, M * r), /* positions */ - opd_idx(s + 1, 1, M + 1), /* cu_seqlens; a drawn one is not ascending -- see below */ - /* THE TAIL STATE, SHAPED AS THE GROUP BINDS IT: [slots, heads, ring, n] with heads 1. - * One slot a sequence is the narrowest case that still makes `sidx` mean something. */ + opd_idx(s + 1, 1, M + 1), /* cu_seqlens; a drawn one is not ascending, see below */ + /* The tail state as the group binds it: [slots, heads, ring, n], heads 1. One slot per + * sequence, the narrowest case in which `sidx` means something. */ opd(D, s, 1, g, n), opd_idx(s, 1, s), /* the state row; one column, values inside the pool */ opd_idx(s, W, W), /* the block-key block table */ - opd_none(), /* rope: the one-component form, which is every text model */ + opd_none(), /* rope: the one-component form (every text model) */ opd(D, W * r, n), opd((uint32_t)RAD_I32, W), opd((uint32_t)RAD_I32, W), @@ -1708,8 +1519,8 @@ extern "C" int r4d_shape_qsa_work(const RadParam* p, int n_p, int operand, RadOp R4D_PICK(l); } -/* The tail. `seqs` is a parameter AND `cu` is `seqs + 1` long; the shim takes the count from the - * operand at run time, and this hook only has to size a buffer. */ +/* The QSA tail store. `cu` is `seqs + 1` long; the shim takes the count from the operand at run + * time, so `seqs` here only sizes the buffer. */ extern "C" int r4d_shape_qsa_tail_store(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { @@ -1723,14 +1534,16 @@ extern "C" int r4d_shape_qsa_tail_store(const RadParam* p, int n_p, int operand, const RadOpdDesc l[] = { opd(D, M, n), opd_idx(M, 1, M * r), /* positions; bounded by what the tail can index */ - opd_idx(s + 1, 1, M + 1), /* cu_seqlens, ASCENDING -- a drawn one is not, and a - * synthesised case here tests the scan and not the copy */ + opd_idx(s + 1, 1, M + 1), /* cu_seqlens should ascend; a drawn one does not, so a + * synthesised case tests the scan, not the copy */ opd(D, s, 1, g, n), /* the tail state: [slots, heads, ring, n], heads 1 */ opd_idx(s, 1, s), /* the state row; one column, values inside the pool */ }; R4D_PICK(l); } +/* The QSA selection. `sel` is `topk + 1` wide: the extra slot is the partial page, without which + * the newest tokens would be dropped. */ extern "C" int r4d_shape_qsa_select(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = pi(p, n_p, "M"); @@ -1743,7 +1556,7 @@ extern "C" int r4d_shape_qsa_select(const RadParam* p, int n_p, int operand, Rad const RadOpdDesc l[] = { opd((uint32_t)RAD_F32, M, nb), opd_idx(s, nb, nb), /* page ids, and they index nothing wider */ - opd_idx(s, 1, nb + 1), /* complete blocks a SEQUENCE, so at most nb */ + opd_idx(s, 1, nb + 1), /* complete blocks per sequence, at most nb */ opd_idx(M, 1, nb * r), /* the query's own position */ opd_idx(s + 1, 1, M + 1, -1, RAD_OPD_F_IDX_CU), opd((uint32_t)RAD_I32, M, k + 1), @@ -1753,6 +1566,9 @@ extern "C" int r4d_shape_qsa_select(const RadParam* p, int n_p, int operand, Rad 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. */ extern "C" int r4d_shape_qsa_score(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = pi(p, n_p, "M"); @@ -1765,16 +1581,16 @@ extern "C" int r4d_shape_qsa_score(const RadParam* p, int n_p, int operand, RadO const RadOpdDesc l[] = { opd(D, M, h * n), opd(D, nb, n), /* the store, bounded by the blocks one query can address */ - /* The table holds PAGE IDS, so a synthesised one must index the store and nothing wider. - * Drawn from the operand before it by the ABI's default, which is exactly right here. */ + /* Page ids, which must index the store: the ABI default (the previous operand) fits. */ opd_idx(s, nb, 0), opd_idx(s + 1, 1, M + 1, -1, RAD_OPD_F_IDX_CU), - opd_idx(s, 1, nb + 1), /* complete blocks a sequence, so at most nb */ + opd_idx(s, 1, nb + 1), /* complete blocks per sequence, at most nb */ opd((uint32_t)RAD_F32, M, nb), }; R4D_PICK(l); } +/* The QSA compressed key. `M` counts blocks, and the key input is `ratio` times taller. */ extern "C" int r4d_shape_qsa_block_key(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = pi(p, n_p, "M"); @@ -1792,6 +1608,8 @@ extern "C" int r4d_shape_qsa_block_key(const RadParam* p, int n_p, int operand, R4D_PICK(l); } +/* H += X^T X. The accumulator is [n][n] (K on both axes), not [M][n] as elsewhere; a row-shaped + * `h` is refused. */ extern "C" int r4d_shape_gram_accum(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = pi(p, n_p, "M"); @@ -1827,13 +1645,12 @@ extern "C" int r4d_shape_rmsnorm_quant_fp8(const RadParam* p, int n_p, int opera if (g != R4D_FP8_BLOCK) return RAD_E_UNSUPPORTED; const RadOpdDesc l[] = { opd(D, M, n), - /* THE RESIDUAL IS SECOND, where `rmsnorm_had_quant_i8` puts it, so the two ops differ by - * the rotation and nothing else. Passed: it is what turns `add` + `rmsnorm` into one - * launch and it is what every caller in this tree issues. It may ALIAS out_bf16 in the - * engine; a tool allocating two buffers is the safe case of that. */ + /* The residual is second, as in `rmsnorm_had_quant_i8`, so the two ops differ only by + * the rotation. Passed, as every caller issues it. The engine may alias it with + * out_bf16; separate buffers are the safe case. */ opd(D, M, n), - /* f32 or bf16 -- the shim reads the operand's own width and hands the kernel a flag. - * Every architecture plugin here declares its norm gains f32. */ + /* f32 or bf16: the shim reads the operand's width and passes the kernel a flag. Every + * architecture plugin declares norm gains f32. */ opd((uint32_t)RAD_F32, n), opd((uint32_t)RAD_F8E4M3, M, n), opd((uint32_t)RAD_F32, M, (n + g - 1) / g), @@ -1851,7 +1668,7 @@ extern "C" int r4d_shape_gated_quant_fp8(const RadParam* p, int n_p, int operand const uint32_t D = dt_act(p, n_p, "dtype"); if (g != R4D_FP8_BLOCK) return RAD_E_UNSUPPORTED; const RadOpdDesc l[] = { - opd(D, M, 2 * n), /* gate then up in one buffer; splitting is a copy */ + opd(D, M, 2 * n), /* gate then up in one buffer */ opd((uint32_t)RAD_F8E4M3, M, n), opd((uint32_t)RAD_F32, M, (n + g - 1) / g), opd(D, M, n), @@ -1867,10 +1684,9 @@ extern "C" int r4d_shape_gate_quant_fp8(const RadParam* p, int n_p, int operand, const int64_t g = pi(p, n_p, "group", R4D_FP8_BLOCK); const uint32_t D = dt_act(p, n_p, "dtype"); if (g != R4D_FP8_BLOCK) return RAD_E_UNSUPPORTED; - /* THE ROW IS A (token, head) PAIR here, not a token: `M` is tokens * n_head and `n` is - * head_dim, which is what makes the gate a fixed stride inside the [q|gate] projection and - * leaves the scale plane byte-for-byte where the out projection reads it. The gate is a COLUMN - * SLICE in the engine; described flat, because a slice is a pitch and the extents are these. */ + /* A row is a (token, head) pair: `M` is tokens * n_head and `n` is head_dim, so the gate is a + * fixed stride inside the [q|gate] projection and the scale plane lands where the out + * projection reads it. In the engine the gate is a column slice; described flat. */ const RadOpdDesc l[] = { opd(D, M, n), opd(D, M, n), @@ -1882,8 +1698,7 @@ extern "C" int r4d_shape_gate_quant_fp8(const RadParam* p, int n_p, int operand, } /* ========================================================================================== - * DFlash2 (shims in r4d_gdn.cpp). Neither op has an unfused equivalent in the vocabulary and - * neither has a ref implementation, so a tool's only description of them is this one. + * DFlash2 (shims in r4d_dflash_conv_t2_g16_bf16.hip and r4d_dflash_select_bf16.hip). Neither op has an unfused equivalent or a ref implementation. * ========================================================================================= */ extern "C" int r4d_shape_dflash_conv(const RadParam* p, int n_p, int operand, @@ -1895,19 +1710,17 @@ extern "C" int r4d_shape_dflash_conv(const RadParam* p, int n_p, int operand, const int64_t NG = pi(p, n_p, "NG"); const int64_t grp = pi(p, n_p, "group_size"); const uint32_t D = dt_act(p, n_p, "dtype"); - /* The entry point's own conditions: NG is H/group and a thread owns eight channels. Checked - * here so a geometry that cannot be served declines rather than being described into -1. */ + /* The entry point's conditions: NG is H/group and a thread owns eight channels. */ if (H <= 0 || grp <= 0 || NG <= 0 || taps <= 0) return RAD_E_UNSUPPORTED; if (H % (grp * 8) || NG != H / grp) return RAD_E_UNSUPPORTED; const RadOpdDesc l[] = { opd(D, T, H), - /* delta IS A SLICE of the [T, 2, taps, NG] kernel projection and its row pitch is - * 2*taps*NG, not taps*NG -- passing the packed pitch silently reads the other side's - * coefficients and is not a shape error. Declared with the projection's own rank so the - * pitch falls out of the shape rather than being asserted. */ + /* delta is a slice of the [T, 2, taps, NG] kernel projection, row pitch 2*taps*NG; a + * packed pitch would silently read the other side's coefficients. Declared at the + * projection's rank so the shape carries the pitch. */ opd(D, T, 2, taps, NG), - opd(D, taps, H), /* base_kernel: a WEIGHT, contiguous [taps, H] */ - opd(D, T, H), /* out -- must not alias x, which two buffers are */ + opd(D, taps, H), /* base_kernel: a weight, contiguous [taps, H] */ + opd(D, T, H), /* out; must not alias x */ }; R4D_PICK(l); } @@ -1923,22 +1736,19 @@ extern "C" int r4d_shape_dflash_select(const RadParam* p, int n_p, int operand, const int64_t astr = pi(p, n_p, "anchor_stride", 1); const uint32_t D = dt_act(p, n_p, "dtype"); if (M <= 0 || astr < 1) return RAD_E_UNSUPPORTED; - /* The three input planes are read at row s*steps+l, so between them they must hold M*steps - * rows -- a short one is a walk that reads another sequence's candidates and proposes a - * perfectly plausible draft belonging to the wrong request. */ + /* The three input planes are read at row s*steps+l, so each holds M*steps rows; a short one + * would read another sequence's candidates. */ const int64_t rows = M * steps; const RadOpdDesc l[] = { - /* CANDIDATE TOKEN IDS, AND THEY ARE GATHER ROWS: the walk scores an edge by reading - * pred[id] and succ[id] out of two [n_vocab, rank] codebooks, so a candidate outside the - * vocabulary reads off the end of a 1.2 GiB weight. The codebooks are the operands four - * and five, not the one before this, so the ABI's default range is the wrong one and - * n_vocab is said outright. */ + /* Candidate token ids, used as gather rows: the walk reads pred[id] and succ[id] from two + * [n_vocab, rank] codebooks (operands 4 and 5), so the range is n_vocab, not the ABI + * default. */ opd_idx(rows, K, V), opd((uint32_t)RAD_F32, rows, K), opd(D, rows, R), - /* `anchor` is usually the step's own token_ids, which carries `block` ids a sequence with - * the anchor first -- hence the stride. It is gathered from the codebooks exactly as the - * candidates are, so it has the same range. The buffer has to hold (M-1)*stride + 1. */ + /* `anchor` is usually the step's token_ids, `block` ids per sequence with the anchor + * first, hence the stride. Gathered like the candidates, so the same range. The buffer + * holds (M-1)*stride + 1. */ opd_idx((M - 1) * astr + 1, 0, V), opd(D, V, R), opd(D, V, R), diff --git a/libr4d/r4d_vit_bf16.hip b/libr4d/r4d_vit_bf16.hip index 3b96d900..54ac40c1 100644 --- a/libr4d/r4d_vit_bf16.hip +++ b/libr4d/r4d_vit_bf16.hip @@ -1,20 +1,14 @@ -// r4d_vit_bf16.hip -- the three ops a vision tower needs that no language model here does: a layer -// norm with a bias, the learned-grid position embedding, and a biased GEMM with the linear layer's -// activation and residual folded into its store. +// r4d_vit_bf16.hip -- vision-tower ops: layer norm with bias, learned-grid position embedding, and +// a biased GEMM with the activation and residual folded into its store. // -// THE ARITHMETIC IS libref's (ref_elementwise.cpp, ref_gemm.cpp), and where libref rounds, this -// rounds in the same place: every accumulation is f32, every store is round-to-nearest-even bf16, -// and the GEMM's epilogue rounds after the biased product, again after the activation and again -// after the residual -- the three tensors the unfused chain would have written. A fused form that -// kept f32 across those seams would be a little more accurate and a different function. +// Arithmetic matches libref (ref_elementwise.cpp, ref_gemm.cpp), rounding where it rounds: f32 +// accumulation, RTNE bf16 stores, and the GEMM epilogue rounds after the biased product, after the +// activation and after the residual, as the unfused chain would. // -// WHY THE GEMM IS NOT gemm_bf16_nt_tiled. That kernel is byte-identical to the skinny one by -// construction (split-K slices summed in a fixed order) and serves K in whole 64-element tiles; a -// tower's MLP projects to 4304 and back, which is 16 elements past a tile, and its linear layers -// all carry a bias. So this is the same block shape -- eight waves over an LDS-staged 64-deep K -// tile, the next tile prefetched into registers -- with a K tail staged as zeros, no split, and the -// epilogue in the store. It serves tall activations: a tower runs one pass over thousands of -// patches, never a decode row. +// Not gemm_bf16_nt_tiled: that kernel needs K in whole 64-element tiles (a tower MLP's 4304 is 16 +// past one) and has no bias. This uses the same block shape (eight waves over an LDS-staged 64-deep +// K tile, next tile prefetched into registers) with a zero-staged K tail, no split-K, and the +// epilogue in the store. Meant for tall activations (thousands of patches). #include "r4d.h" #include "r4d_args.h" #include "r4d_emit.h" @@ -54,9 +48,9 @@ __device__ __forceinline__ float ldw(const void* p, uint32_t i) { } // ---------------------------------------------------------------------------- layernorm -// ref_layernorm: y = (x - mean) * rsqrt(var + eps) * w + b, biased variance, TWO PASSES over the -// row -- the mean first, then the squared deviations -- because the one-pass E[x^2] - E[x]^2 is -// catastrophically worse on a residual whose mean is large against its spread. One block a row. +// ref_layernorm: y = (x - mean) * rsqrt(var + eps) * w + b, biased variance, two passes (mean, then +// squared deviations); one-pass E[x^2] - E[x]^2 cancels badly when the mean is large relative to +// the spread. One block per row. template __global__ __launch_bounds__(kThr) void layernorm_kernel( const unsigned short* __restrict__ x, const void* __restrict__ w, const void* __restrict__ b, @@ -82,9 +76,9 @@ __global__ __launch_bounds__(kThr) void layernorm_kernel( } // ---------------------------------------------------------------------------- grid_embed -// ref_grid_embed: a side x side table of rows resampled bilinearly to row m's grid (corners on the -// table's corners, edge taps clamped), the four taps summed in f32 in libref's order, rounded, -// added to x and rounded again. `coord` is [4, planes] -- row, column, grid height, grid width. +// ref_grid_embed: a side x side table resampled bilinearly to row m's grid (corners aligned, edge +// taps clamped), four taps summed in f32 in libref's order, rounded, added to x and rounded again. +// `crd` is [4, planes]: row, column, grid height, grid width. template __global__ __launch_bounds__(kThr) void grid_embed_kernel( unsigned short* __restrict__ x, const void* __restrict__ tab, const int32_t* __restrict__ crd, @@ -122,9 +116,8 @@ __global__ __launch_bounds__(kThr) void grid_embed_kernel( // ---------------------------------------------------------------------------- grid_embed_aa // ref_grid_embed_aa: torch's antialiased half-pixel bilinear resample (SigLIP2's position table). -// Thread 0 lays out the row's two tap lists -- at most `side` each -- in LDS; every thread then -// takes channels, summing the taps in libref's order (a row of columns, then the rows), and the sum -// is rounded once before the add. +// Thread 0 builds the row's two tap lists (at most `side` each) in LDS; threads then take channels, +// summing taps in libref's order (columns within a row, then rows), rounded once before the add. __device__ __forceinline__ int aa_taps(int at, int size, int side, float* w, int* lo) { size = size < 1 ? 1 : size; at = at < 0 ? 0 : (at >= size ? size - 1 : at); @@ -174,9 +167,9 @@ __global__ __launch_bounds__(kThr) void grid_embed_aa_kernel( // ---------------------------------------------------------------------------- gemm_nt_bias #define VB_BK 64 -#define VB_PITCH (VB_BK + 8) // 144-byte LDS rows: gemm_bf16_nt_tiled's bank argument +#define VB_PITCH (VB_BK + 8) // 144-byte LDS rows, as in gemm_bf16_nt_tiled (bank spread) -// TM x TN WMMA tiles a wave, eight waves as 2 x 4: BM = 2*TM*16, BN = 4*TN*16. ACT: 0 none, +// TM x TN WMMA tiles per wave, eight waves as 2 x 4: BM = 2*TM*16, BN = 4*TN*16. ACT: 0 none, // 1 exact GELU, 2 tanh GELU. template __global__ __launch_bounds__(256) void vit_gemm_kernel( @@ -195,8 +188,8 @@ __global__ __launch_bounds__(256) void vit_gemm_kernel( const int wm = wave / 4, wn = wave % 4; const int m0 = blockIdx.y * BM, n0 = blockIdx.x * BN; - // Staging: chunk c = tid + 256 i is row c / CPR, elements (c % CPR) * 8 of it. Rows past M - // or N re-read the last valid row and compute a result nobody stores. + // Staging: chunk c = tid + 256 i is row c / CPR, elements (c % CPR) * 8. Rows past M or N + // re-read the last valid row; their results are not stored. unsigned aoff[AL], woff[WL]; int ae[AL], we[WL]; unsigned short* adst[AL]; @@ -226,8 +219,8 @@ __global__ __launch_bounds__(256) void vit_gemm_kernel( #pragma unroll for (int j = 0; j < TN; ++j) acc[i][j] = (v8f)(0.f); - // THE K TAIL IS STAGED AS ZEROS: K is a multiple of 8, so a 16-byte chunk is wholly inside K - // or wholly past it, and a zero chunk contributes exactly nothing to the dot products. + // The K tail is staged as zeros: K is a multiple of 8, so a 16-byte chunk is wholly inside or + // wholly past K. const r4d_u32x4 zero = (r4d_u32x4)(0u); r4d_u32x4 ra[AL], rw[WL]; // registers; uint4 would sit in scratch #pragma unroll @@ -266,8 +259,8 @@ __global__ __launch_bounds__(256) void vit_gemm_kernel( } } - // Lane l holds column (l & 15) of a tile and rows 8 (l >> 4) + e. The residual is read at the - // element it is added to, by the thread that stores it, so `R` may be `C` itself. + // Lane l holds column (l & 15) of a tile and rows 8 (l >> 4) + e. The residual is read by the + // thread that stores the same element, so R may alias C. #pragma unroll for (int i = 0; i < TM; ++i) #pragma unroll @@ -296,14 +289,14 @@ __global__ __launch_bounds__(256) void vit_gemm_kernel( /* ------------------------------------------------------------------ layernorm */ enum { LN_X = 0, LN_W, LN_B, LN_Y }; -static int rad_layernorm_body(const RadArgs* a, const R4dSink& sk) { +extern "C" int r4d_rad_layernorm(const RadArgs* a, RadStream stream) { const RadTensor* x = r4d_opt(a, LN_X); const RadTensor* w = r4d_opt(a, LN_W); const RadTensor* b = r4d_opt(a, LN_B); const RadTensor* y = r4d_opt(a, LN_Y); if (!x || !w || !y) return R4D_NO(RAD_E_INVAL); if (x->dtype != RAD_BF16 || y->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); - /* The gain and the bias share one width, read off the operand: f32 or bf16. */ + /* Gain and bias share one dtype, f32 or bf16. */ if (w->dtype != RAD_F32 && w->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); if (b && b->dtype != w->dtype) return R4D_NO(RAD_E_DTYPE); if (!r4d_contig(w) || (b && !r4d_contig(b))) return R4D_NO(RAD_E_STRIDE); @@ -317,20 +310,19 @@ static int rad_layernorm_body(const RadArgs* a, const R4dSink& sk) { if (M <= 0 || My < M) return R4D_NO(RAD_E_SHAPE); const float eps = (float)r4d_getf(a, "eps", 1e-5); if (w->dtype == RAD_F32) - return R4D_EMIT(sk, layernorm_kernel, dim3((uint32_t)M), dim3(kThr), 0, + return R4D_EMIT(stream, layernorm_kernel, dim3((uint32_t)M), dim3(kThr), 0, (const unsigned short*)r4d_p(x), r4d_p(w), r4d_p(b), (unsigned short*)r4d_wp(y), (uint32_t)n, eps, (uint32_t)x_ld, (uint32_t)y_ld); - return R4D_EMIT(sk, layernorm_kernel, dim3((uint32_t)M), dim3(kThr), 0, + return R4D_EMIT(stream, layernorm_kernel, dim3((uint32_t)M), dim3(kThr), 0, (const unsigned short*)r4d_p(x), r4d_p(w), r4d_p(b), (unsigned short*)r4d_wp(y), (uint32_t)n, eps, (uint32_t)x_ld, (uint32_t)y_ld); } -R4D_ENTRY(r4d_rad_layernorm, rad_layernorm_body) /* ------------------------------------------------------------------ grid_embed */ enum { GE_X = 0, GE_TAB, GE_CRD }; -static int rad_grid_embed_body(const RadArgs* a, const R4dSink& sk) { +extern "C" int r4d_rad_grid_embed(const RadArgs* a, RadStream stream) { const RadTensor* x = r4d_opt(a, GE_X); const RadTensor* tab = r4d_opt(a, GE_TAB); const RadTensor* crd = r4d_opt(a, GE_CRD); @@ -350,17 +342,16 @@ static int rad_grid_embed_body(const RadArgs* a, const R4dSink& sk) { if (M <= 0) return R4D_NO(RAD_E_SHAPE); const uint32_t plane = (uint32_t)crd->shape[1]; if (tab->dtype == RAD_F32) - return R4D_EMIT(sk, grid_embed_kernel, dim3((uint32_t)M), dim3(kThr), 0, + return R4D_EMIT(stream, grid_embed_kernel, dim3((uint32_t)M), dim3(kThr), 0, (unsigned short*)r4d_wp(x), r4d_p(tab), (const int32_t*)r4d_p(crd), (uint32_t)n, (int)side, (uint32_t)x_ld, plane); - return R4D_EMIT(sk, grid_embed_kernel, dim3((uint32_t)M), dim3(kThr), 0, + return R4D_EMIT(stream, grid_embed_kernel, dim3((uint32_t)M), dim3(kThr), 0, (unsigned short*)r4d_wp(x), r4d_p(tab), (const int32_t*)r4d_p(crd), (uint32_t)n, (int)side, (uint32_t)x_ld, plane); } -R4D_ENTRY(r4d_rad_grid_embed, rad_grid_embed_body) /* grid_embed_aa: grid_embed's operands and checks, the antialiased resample. */ -static int rad_grid_embed_aa_body(const RadArgs* a, const R4dSink& sk) { +extern "C" int r4d_rad_grid_embed_aa(const RadArgs* a, RadStream stream) { const RadTensor* x = r4d_opt(a, GE_X); const RadTensor* tab = r4d_opt(a, GE_TAB); const RadTensor* crd = r4d_opt(a, GE_CRD); @@ -381,19 +372,18 @@ static int rad_grid_embed_aa_body(const RadArgs* a, const R4dSink& sk) { const uint32_t plane = (uint32_t)crd->shape[1]; const size_t lds = (size_t)(2 * side) * sizeof(float); if (tab->dtype == RAD_F32) - return R4D_EMIT(sk, grid_embed_aa_kernel, dim3((uint32_t)M), dim3(kThr), lds, + return R4D_EMIT(stream, grid_embed_aa_kernel, dim3((uint32_t)M), dim3(kThr), lds, (unsigned short*)r4d_wp(x), r4d_p(tab), (const int32_t*)r4d_p(crd), (uint32_t)n, (int)side, (uint32_t)x_ld, plane); - return R4D_EMIT(sk, grid_embed_aa_kernel, dim3((uint32_t)M), dim3(kThr), lds, + return R4D_EMIT(stream, grid_embed_aa_kernel, dim3((uint32_t)M), dim3(kThr), lds, (unsigned short*)r4d_wp(x), r4d_p(tab), (const int32_t*)r4d_p(crd), (uint32_t)n, (int)side, (uint32_t)x_ld, plane); } -R4D_ENTRY(r4d_rad_grid_embed_aa, rad_grid_embed_aa_body) /* ------------------------------------------------------------------ gemm_nt_bias */ enum { GB_A = 0, GB_W, GB_BIAS, GB_RES, GB_Y }; -static int rad_gemm_nt_bias_body(const RadArgs* a, const R4dSink& sk) { +extern "C" int r4d_rad_gemm_nt_bias(const RadArgs* a, RadStream stream) { const RadTensor* A = r4d_opt(a, GB_A); const RadTensor* W = r4d_opt(a, GB_W); const RadTensor* B = r4d_opt(a, GB_BIAS); @@ -431,7 +421,7 @@ static int rad_gemm_nt_bias_body(const RadArgs* a, const R4dSink& sk) { } const bool res = R != nullptr, bf32 = B->dtype == RAD_F32; - /* The large tile once its grid reaches half the part, as gemm_bf16_nt_tiled chooses. */ + /* The large tile once its grid reaches 32 workgroups, as gemm_bf16_nt_tiled chooses. */ const long long g128 = ((N + 127) / 128) * ((M + 127) / 128); const bool big = g128 >= 32; const int bt = big ? 128 : 64; @@ -442,8 +432,9 @@ static int rad_gemm_nt_bias_body(const RadArgs* a, const R4dSink& sk) { auto Cp = (unsigned short*)r4d_wp(Y); const void* Bp = r4d_p(B); #define VB_L(TM, TN, AC, RS, BF) \ - return R4D_EMIT(sk, (vit_gemm_kernel), grid, block, 0, Ap, (unsigned)lda, \ - Wp, (unsigned)K, Bp, Rp, (unsigned)ldr, Cp, (unsigned)ldc, (int)M, (int)K, \ + return R4D_EMIT(stream, (vit_gemm_kernel), grid, block, 0, Ap, \ + (unsigned)lda, Wp, (unsigned)K, Bp, Rp, (unsigned)ldr, Cp, (unsigned)ldc, \ + (int)M, (int)K, \ (int)N) #define VB_ACT(TM, TN, RS, BF) \ do { \ @@ -460,4 +451,3 @@ static int rad_gemm_nt_bias_body(const RadArgs* a, const R4dSink& sk) { #undef VB_ACT #undef VB_L } -R4D_ENTRY(r4d_rad_gemm_nt_bias, rad_gemm_nt_bias_body) diff --git a/libref/CMakeLists.txt b/libref/CMakeLists.txt index d430659b..94f8c8ca 100644 --- a/libref/CMakeLists.txt +++ b/libref/CMakeLists.txt @@ -1,15 +1,10 @@ # libref -- every op in the conventional vocabulary, naively and generically (spec §17). # -# It links radiance::abi AND NOTHING ELSE. A kernel plugin does not link the core: abi/ is the -# whole contract, and a plugin that reached into core/ would stop being substitutable, which is the -# one property the plugin boundary exists to have. What it shares with the engine -- the dtype -# conversions, the parameter readers -- it takes from the ABI headers, which define them inline. -# -# The glob is CONFIGURE_DEPENDS, so a new translation unit in this directory is picked up by the -# next build with no edit here. -# A plugin like any other: built here inside radiance's tree, or on its own against an installed -# radiance (`cmake -S libref -B build -DCMAKE_PREFIX_PATH=`) -- the same -# rad_add_plugin either way (cmake/RadAddPlugin.cmake). +# Links radiance::abi and nothing else: abi/ is the whole plugin contract, so the plugin stays +# substitutable. Shared helpers (dtype conversions, parameter readers) come inline from the ABI +# headers. +# Built in radiance's tree, or standalone against an installed radiance +# (`cmake -S libref -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake. if(NOT COMMAND rad_add_plugin) cmake_minimum_required(VERSION 3.21) project(libref LANGUAGES CXX) @@ -21,16 +16,13 @@ file(GLOB REF_SRC CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) rad_add_plugin(libref kernels SOURCES ${REF_SRC}) -# -ffp-contract=off IS A CORRECTNESS FLAG HERE, not a tuning one. rad-kbench compares resolved -# kernels against this plugin to a tolerance, so `a*b + c` has to round twice: a reference that -# contracts into an FMA disagrees with itself between two compilers, and one that reassociates -# cannot be trusted to a tolerance at all (libref/ref_common.h). +# -ffp-contract=off is a correctness flag: rad-kbench compares kernels against this reference to a +# tolerance, so `a*b + c` must round twice and give the same result under any compiler +# (libref/ref_common.h). target_compile_options(libref PRIVATE -ffp-contract=off) -# OpenMP over the outer dimension only -- one thread owns whole output elements, and there is not -# one reduction() clause in the plugin, so two runs at different thread counts are bit-identical. -# Optional: without it the pragmas are ignored and the plugin is correct and slower, which is the -# right failure mode for a fallback. +# Optional OpenMP over the outer dimension only. One thread owns whole output elements and there is +# no reduction() clause, so results are bit-identical at any thread count. find_package(OpenMP QUIET) if(OpenMP_CXX_FOUND) target_link_libraries(libref PRIVATE OpenMP::OpenMP_CXX) diff --git a/libref/ref_attn.cpp b/libref/ref_attn.cpp index 648589e1..baa88781 100644 --- a/libref/ref_attn.cpp +++ b/libref/ref_attn.cpp @@ -1,25 +1,21 @@ /* ref_attn.cpp -- paged attention, dense attention, the KV write, and the two rotary forms. * - * These are the ops most likely to be subtly wrong in any implementation, so they are written for - * legibility over everything else: the mask is an explicit predicate per key, the softmax is two - * plain passes with the max subtracted, and nothing is fused. + * These ops are the easiest to get subtly wrong, so they favour legibility: the mask is an explicit + * predicate per key, the softmax is two plain passes with the max subtracted, and nothing is fused. * - * ============================== THE PAGED LAYOUT ============================== + * ============================== The paged layout ============================== * * kv_cache[num_blocks, kv_heads, block_size, 2 * head_dim] K then V inside a slot * - * This is the layout every kernel in the project has to match (libr4d's `R4DArgs::kv` names the - * same one), so it is stated in ref_ops.h and obeyed here. A flat slot index - * s decomposes as block = s / block_size, offset = s % block_size; `block_table[seq, i]` holds the - * block id of the sequence's i-th block and `slot_mapping[token]` holds the flat slot a token's KV - * goes to. + * The layout every kernel must match (ref_ops.h; libr4d's `R4DArgs::kv`). A flat slot index s is + * block = s / block_size, offset = s % block_size; `block_table[seq, i]` holds the block id of the + * sequence's i-th block and `slot_mapping[token]` the flat slot a token's KV goes to. * - * ============================== THE MASK ============================== + * ============================== The mask ============================== * - * `seqused[s]` is the sequence's TOTAL key count INCLUDING this step's query tokens, so query row - * i of a q_len-row step sits at absolute position seqused[s] - q_len + i. That is what makes one - * kernel serve a decode (q_len 1), a speculative verify (q_len <= 64) and a prefill chunk - * (q_len in the thousands) without the caller passing a second length. + * `seqused[s]` is the sequence's total key count including this step's query tokens, so query row + * i of a q_len-row step sits at absolute position seqused[s] - q_len + i. One kernel thus serves + * decode (q_len 1), speculative verify (q_len <= 64) and prefill chunks (q_len in the thousands). * * causal = 1 key j is visible when j <= pos * causal = 0 key j is visible when j < seqused[s] @@ -28,9 +24,8 @@ */ #include "ref_common.h" #include "rad_yarn.h" -/* `row_stride`: which axis carries a row of `cols` elements, at whatever rank the operand arrived - * in. Every q/k/v/out below goes through it rather than through `rank >= 3 ? stride[rank-3] : cols` - * -- the comment above kv_store shows where that shortcut is wrong. */ +/* `row_stride`: every q/k/v/out row stride below goes through it rather than a rank-based + * shortcut; see kv_store for where the shortcut is wrong. */ #include "ref_gemm.h" #include "ref_ops.h" @@ -40,9 +35,9 @@ using namespace ref; namespace { -/* The largest head this reference accumulates in one stack frame. The widest in circulation is an - * image VAE's single-head mid-block attention at 1152 (Qwen-Image 2.1), so 2048 is headroom; above - * it the op says RAD_E_UNSUPPORTED by name instead of overflowing a frame. */ +/* The largest head this reference accumulates in one stack frame. The widest in use is an image + * VAE's single-head mid-block attention at 1152 (Qwen-Image 2.1); above 2048 the op returns + * RAD_E_UNSUPPORTED instead of overflowing the frame. */ enum { REF_HD_MAX = 2048 }; struct KVView { @@ -67,6 +62,16 @@ static inline KVView kv_view(const RadTensor* c, int64_t head_dim, int64_t block return v; } +/* Cache element loaders with the dtype resolved once per launch: the same floats as ldt, and the + * per-element switch out of the inner loops. */ +template struct KvFix { + float operator()(const void* p, int64_t i) const { return Cvt
::ld(p, i); } +}; +struct KvDyn { + uint32_t dt; + float operator()(const void* p, int64_t i) const { return ld_dt(dt, p, i); } +}; + } /* namespace */ /* ------------------------------------------------------------------ attn_paged */ @@ -80,10 +85,8 @@ int ref_attn_paged(const RadArgs* a, RadStream) { const int64_t head_dim = p_int(a, "head_dim", q->rank >= 3 ? q->shape[q->rank - 1] : 0); const int64_t gqa = p_int(a, "gqa", 1); - /* `block_size` is RAD_DERIVED on this op (docs/OPS.md), so a caller who did not pin it and - * resolved to a kernel that declares no RAD_C_EQ for it -- ref's own row -- arrives here - * without the key. The cache tensor says what the block size is; ref reads it off the operand, - * which is this plugin's rule anyway, and cross-checks it below where the caller did name one. */ + /* `block_size` is RAD_DERIVED here (docs/OPS.md), so a call resolved to ref's row may arrive + * without it. Read it off the cache tensor, and cross-check below when the caller names one. */ const int64_t block_size = p_int(a, "block_size", kv->rank == 4 ? kv->shape[2] : 0); const int causal = (int)p_int(a, "causal", 1); const int64_t window = p_int(a, "window", 0); @@ -93,18 +96,16 @@ int ref_attn_paged(const RadArgs* a, RadStream) { const int64_t kv_heads = kv->rank == 4 ? kv->shape[1] : 0; if (kv_heads <= 0) return RAD_E_SHAPE; const int64_t q_heads = gqa * kv_heads; - /* gqa and the cache's head count decide the query head count, so a rank-3 query that disagrees - * is a caller bug that would otherwise stride through the wrong rows and return plausible - * numbers. */ + /* gqa and the cache's head count fix the query head count; a rank-3 query that disagrees would + * stride through the wrong rows. */ if (q->rank >= 3 && q->shape[q->rank - 2] != q_heads) return RAD_E_SHAPE; const int64_t n_seq = numel(su); const int64_t rows = numel(q) / (q_heads * head_dim); if (n_seq <= 0 || rows <= 0) return RAD_E_SHAPE; - /* RAGGED BATCHES. cu_seqlens is optional and absent means every sequence presents the same - * query length, the uniform case. Present, it - * is [n_seq + 1] with cu[0] == 0 and cu[n_seq] == rows, and sequence s owns query rows - * [cu[s], cu[s+1]). A serving scheduler mixes one sequence prefill chunk with other single - * decode rows in the same step, so the ragged case is the ordinary one. */ + /* Ragged batches. cu_seqlens is optional; absent, every sequence has the same query length. + * Present, it is [n_seq + 1] with cu[0] == 0 and cu[n_seq] == rows, and sequence s owns query + * rows [cu[s], cu[s+1]). Serving mixes a prefill chunk with decode rows in one step, so ragged + * is the ordinary case. */ if (!cus && rows % n_seq != 0) return RAD_E_SHAPE; if (cus && numel(cus) != n_seq + 1) return RAD_E_SHAPE; const int64_t q_len = cus ? 0 : rows / n_seq; @@ -127,96 +128,129 @@ int ref_attn_paged(const RadArgs* a, RadStream) { const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim)); const int64_t total = rows * q_heads; + const int64_t jcap = max_blocks * block_size; - #pragma omp parallel for schedule(static) - for (int64_t idx = 0; idx < total; ++idx) { - const int64_t h = idx % q_heads; - const int64_t tok = idx / q_heads; /* the dense query row */ - /* Which sequence owns it, and where inside that sequence's query it sits. Linear rather than a - * binary search: n_seq is a handful and this is the reference. */ - int64_t s = 0, qlen = q_len, i = 0; - if (cus) { - while (s + 1 < n_seq && ld_int(cus->dtype, cus->data, offlin(cus, s + 1)) <= tok) ++s; - const int64_t beg = ld_int(cus->dtype, cus->data, offlin(cus, s)); - qlen = ld_int(cus->dtype, cus->data, offlin(cus, s + 1)) - beg; - i = tok - beg; - } else { - s = tok / q_len; - i = tok - s * q_len; - } - if (qlen <= 0) continue; - const int64_t kh = h / gqa; + /* Every (query row, head) is one output row, computed as below in a fixed order: per visible + * key, dot = sum over d of q[d] * (k[d] * k_descale), score = dot * scale; then the max over the + * scores in key order; then sum and acc[d] accumulate exp(score - max) and + * exp(...) * (v[d] * v_descale) in key order. The query row is widened once, each score is kept + * for the second pass instead of recomputed, and four keys' dot chains run side by side; none + * of that changes a value. */ + REF_PAR_REGION(total * head_dim * 64) + { + float* const sc = ws_get((size_t)std::max(jcap, 1)); + REF_FOR_DYN + for (int64_t idx = 0; idx < total; ++idx) { + auto unit = [&](auto kl) { + const int64_t h = idx % q_heads; + const int64_t tok = idx / q_heads; /* the dense query row */ + /* The owning sequence and the row's index within its query. */ + int64_t s = 0, qlen = q_len, i = 0; + if (cus) { + s = seq_of(cus, n_seq, tok); + qlen = cu_at(cus, s + 1) - cu_at(cus, s); + i = tok - cu_at(cus, s); + } else { + s = tok / q_len; + i = tok - s * q_len; + } + if (qlen <= 0) return; + const int64_t kh = h / gqa; - const int64_t ctx = ld_int(su->dtype, su->data, offlin(su, s)); - const int64_t pos = ctx - qlen + i; - const int64_t qb = tok * q_rs + h * q_hs; - const int64_t ob = tok * o_rs + h * o_hs; + const int64_t ctx = ld_int(su->dtype, su->data, offlin(su, s)); + const int64_t pos = ctx - qlen + i; + const int64_t qb = tok * q_rs + h * q_hs; + const int64_t ob = tok * o_rs + h * o_hs; - const float kds = kdes ? ldt(kdes, s * kv_heads + kh) : 1.0f; - const float vds = vdes ? ldt(vdes, s * kv_heads + kh) : 1.0f; + const float kds = kdes ? ldt(kdes, s * kv_heads + kh) : 1.0f; + const float vds = vdes ? ldt(vdes, s * kv_heads + kh) : 1.0f; - /* Pass one: the maximum score, so the exponent below cannot overflow. */ - float mx = -INFINITY; - for (int64_t j = 0; j < ctx; ++j) { - if (causal ? (j > pos) : (j >= ctx)) continue; - if (window > 0) { - const int64_t d = pos - j; - if (causal ? (d >= window) : (d >= window || d <= -window)) continue; + /* Keys past the block table's width are never read. */ + const int64_t jend = std::min(ctx, jcap); + /* Key j's slot in the cache, or -1 when the mask hides it or its block is + * unmapped. */ + auto key_at = [&](int64_t j) -> int64_t { + if (causal && j > pos) return -1; + if (window > 0) { + const int64_t d = pos - j; + if (causal ? (d >= window) : (d >= window || d <= -window)) return -1; + } + const int64_t blk = + ld_int(bt->dtype, bt->data, s * bt_rs + (j / block_size) * bt_cs); + return blk < 0 ? -1 : blk * kvv.sb + kh * kvv.sh + (j % block_size) * kvv.so; + }; + + float qf[REF_HD_MAX]; + for (int64_t d = 0; d < head_dim; ++d) qf[d] = ldt(q, qb + d * q_ds); + + /* Pass one: every visible key's score, four keys at a time, and the maximum. */ + float mx = -INFINITY; + for (int64_t j0 = 0; j0 < jend; j0 += 4) { + int64_t kb[4]; + float dot[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; + const int nk = (int)std::min(4, jend - j0); + for (int u = 0; u < 4; ++u) kb[u] = u < nk ? key_at(j0 + u) : -1; + if (kb[0] >= 0 && kb[1] >= 0 && kb[2] >= 0 && kb[3] >= 0) { + for (int64_t d = 0; d < head_dim; ++d) { + const float qd = qf[d]; + dot[0] += qd * (kl(kv->data, kb[0] + d * kvv.sd) * kds); + dot[1] += qd * (kl(kv->data, kb[1] + d * kvv.sd) * kds); + dot[2] += qd * (kl(kv->data, kb[2] + d * kvv.sd) * kds); + dot[3] += qd * (kl(kv->data, kb[3] + d * kvv.sd) * kds); + } + } else { + for (int u = 0; u < nk; ++u) { + if (kb[u] < 0) continue; + for (int64_t d = 0; d < head_dim; ++d) + dot[u] += qf[d] * (kl(kv->data, kb[u] + d * kvv.sd) * kds); + } + } + for (int u = 0; u < nk; ++u) { + if (kb[u] < 0) continue; + const float sj = dot[u] * scale; + sc[j0 + u] = sj; + if (sj > mx) mx = sj; + } + } + + /* No visible key (an empty sliding window) gives a zero row, not NaN, matching + * every kernel in the project. */ + if (mx == -INFINITY) { + for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, 0.0f); + return; + } + + /* Pass two: exponentiate and accumulate in ascending key order. */ + float acc[REF_HD_MAX]; + for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f; + float sum = 0.0f; + for (int64_t j = 0; j < jend; ++j) { + const int64_t kb = key_at(j); + if (kb < 0) continue; + const float w = ref_exp(sc[j] - mx); + sum += w; + const int64_t vb = kb + head_dim * kvv.sd; + for (int64_t d = 0; d < head_dim; ++d) + acc[d] += w * (kl(kv->data, vb + d * kvv.sd) * vds); + } + const float inv = sum > 0.0f ? 1.0f / sum : 0.0f; + for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, acc[d] * inv); + }; + switch (kv->dtype) { + case RAD_F32: unit(KvFix{}); break; + case RAD_BF16: unit(KvFix{}); break; + case RAD_F8E4M3: unit(KvFix{}); break; + default: unit(KvDyn{ kv->dtype }); break; } - if (j / block_size >= max_blocks) break; /* bounds first: the table is only this wide */ - const int64_t blk = ld_int(bt->dtype, bt->data, s * bt_rs + (j / block_size) * bt_cs); - if (blk < 0) continue; - const int64_t kb = blk * kvv.sb + kh * kvv.sh + (j % block_size) * kvv.so; - float dot = 0.0f; - for (int64_t d = 0; d < head_dim; ++d) - dot += ldt(q, qb + d * q_ds) * (ldt(kv, kb + d * kvv.sd) * kds); - dot *= scale; - if (dot > mx) mx = dot; } - - float acc[REF_HD_MAX]; - for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f; - - /* No visible key at all -- an empty sliding window on the first token of a sequence -- is a - * zero row, not a NaN. A softmax over nothing has no defined answer and zero is the one - * every kernel in this project produces. */ - if (mx == -INFINITY) { - for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, 0.0f); - continue; - } - - /* Pass two: the scores again, exponentiated and accumulated in ascending key order. The - * dot product is recomputed rather than kept, because keeping it would need a buffer the - * size of the context and the reference has time it does not have memory. */ - float sum = 0.0f; - for (int64_t j = 0; j < ctx; ++j) { - if (causal ? (j > pos) : (j >= ctx)) continue; - if (window > 0) { - const int64_t d = pos - j; - if (causal ? (d >= window) : (d >= window || d <= -window)) continue; - } - if (j / block_size >= max_blocks) break; /* bounds first: the table is only this wide */ - const int64_t blk = ld_int(bt->dtype, bt->data, s * bt_rs + (j / block_size) * bt_cs); - if (blk < 0) continue; - const int64_t kb = blk * kvv.sb + kh * kvv.sh + (j % block_size) * kvv.so; - float dot = 0.0f; - for (int64_t d = 0; d < head_dim; ++d) - dot += ldt(q, qb + d * q_ds) * (ldt(kv, kb + d * kvv.sd) * kds); - const float w = ref_exp(dot * scale - mx); - sum += w; - for (int64_t d = 0; d < head_dim; ++d) - acc[d] += w * (ldt(kv, kb + (head_dim + d) * kvv.sd) * vds); - } - const float inv = sum > 0.0f ? 1.0f / sum : 0.0f; - for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, acc[d] * inv); } return RAD_OK; } /* ------------------------------------------------------------------ attn_dense */ -/* The vision tower's: nothing paged, nothing quantised, `cu_seqlens` bounding one image (or one - * attention window) per entry so a whole batch is ONE launch rather than a per-segment loop and a - * concatenate. Causal is a parameter because a dense decoder-only prefill wants the same kernel. */ +/* For the vision tower: unpaged, unquantised, `cu_seqlens` bounding one image (or attention window) + * per entry so a whole batch is one launch. Causal is a parameter so a dense decoder-only prefill + * can use the same kernel. */ int ref_attn_dense(const RadArgs* a, RadStream) { if (!have(a, 5)) return RAD_E_INVAL; const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *cu = &a->t[3], *o = &a->t[4]; @@ -224,14 +258,19 @@ int ref_attn_dense(const RadArgs* a, RadStream) { const int64_t head_dim = p_int(a, "head_dim", q->rank >= 3 ? q->shape[q->rank - 1] : 0); const int64_t gqa = p_int(a, "gqa", 1); const int causal = (int)p_int(a, "causal", 0); - /* `window` is attn_paged's rule over a segment's own positions: causal, key j is visible to - * query i when i - j < window; non-causal, when |i - j| < window. 0 is no window. */ + /* `window` follows attn_paged's rule over a segment's own positions: causal, key j is visible + * to query i when i - j < window; non-causal, when |i - j| < window. 0 is no window. `block` + * cuts a segment into blocks of that many rows from its start, each attending only within + * itself (a chunked encoder's windows). `cu_div` reads cu_seqlens in units of that many rows: + * a segment is rows [cu[s] / cu_div, cu[s+1] / cu_div). */ const int64_t window = p_int(a, "window", 0); - if (head_dim <= 0 || gqa <= 0 || window < 0) return RAD_E_SHAPE; + const int64_t block = p_int(a, "block", 0); + const int64_t cdiv = p_int(a, "cu_div", 1); + if (head_dim <= 0 || gqa <= 0 || window < 0 || block < 0 || cdiv <= 0) return RAD_E_SHAPE; if (head_dim > REF_HD_MAX) return RAD_E_UNSUPPORTED; - /* [tokens, heads, head_dim], or [tokens, heads * head_dim] -- a column slice of a fused - * projection, whose row pitch is the projection's. */ + /* [tokens, heads, head_dim], or [tokens, heads * head_dim] as a column slice of a fused + * projection with the projection's row pitch. */ const int64_t q_heads = q->rank >= 3 ? q->shape[q->rank - 2] : (q->rank == 2 ? q->shape[1] / head_dim : 1); const int64_t kv_heads = q_heads / gqa; @@ -239,6 +278,7 @@ int ref_attn_dense(const RadArgs* a, RadStream) { const int64_t n_seq = numel(cu) - 1; if (n_seq <= 0) return RAD_E_SHAPE; const int64_t total_q = numel(q) / (q_heads * head_dim); + if (total_q <= 0 || cu_at(cu, n_seq) <= cu_at(cu, 0)) return RAD_E_SHAPE; /* zero rows */ if (numel(o) < total_q * q_heads * head_dim) return RAD_E_SHAPE; if (numel(k) < total_q * kv_heads * head_dim) return RAD_E_SHAPE; if (numel(v) < total_q * kv_heads * head_dim) return RAD_E_SHAPE; @@ -258,11 +298,11 @@ int ref_attn_dense(const RadArgs* a, RadStream) { const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim)); - #pragma omp parallel for schedule(static) + REF_PAR_FOR(total_q * q_heads * head_dim * 64) for (int64_t sh = 0; sh < n_seq * q_heads; ++sh) { const int64_t s = sh / q_heads, h = sh % q_heads, kh = h / gqa; - const int64_t b0 = ld_int(cu->dtype, cu->data, offlin(cu, s)); - const int64_t b1 = ld_int(cu->dtype, cu->data, offlin(cu, s + 1)); + const int64_t b0 = cu_at(cu, s) / cdiv; + const int64_t b1 = cu_at(cu, s + 1) / cdiv; for (int64_t i = b0; i < b1; ++i) { const int64_t qb = i * q_rs + h * q_hs, ob = i * o_rs + h * o_hs; int64_t jbeg = b0, jend = causal ? (i + 1) : b1; @@ -270,6 +310,11 @@ int ref_attn_dense(const RadArgs* a, RadStream) { jbeg = std::max(b0, i - window + 1); if (!causal) jend = std::min(b1, i + window); } + if (block > 0) { + const int64_t blk = b0 + (i - b0) / block * block; + jbeg = std::max(jbeg, blk); + jend = std::min(jend, blk + block); + } float mx = -INFINITY; for (int64_t j = jbeg; j < jend; ++j) { const int64_t kb = j * k_rs + kh * k_hs; @@ -303,23 +348,18 @@ int ref_attn_dense(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------------ kv_store */ -/* Writes this step's keys and values into the paged cache at `slot_mapping`. The cache operand is - * INOUT and not OUT: this op touches only the mapped slots and every other slot in the pool must - * survive it, which is a liveness fact the buffer planner has to know (docs/OPS.md draws it as an - * output; that is the one role this plugin states differently, and deliberately). +/* Writes this step's keys and values into the paged cache at `slot_mapping`. The cache is INOUT, + * not OUT: only mapped slots are touched and every other slot must survive, which the buffer + * planner needs to know (docs/OPS.md draws it as an output; this plugin deliberately differs). * - * A NEGATIVE slot is skipped. That is how a padded batch row says "this token has no cache slot", - * and it has to be a documented value rather than an accident: libr4d treats slot <= 0 as null - * because vLLM reserves block 0, but a generic reference must not steal a valid slot, so ref skips - * only the strictly negative. + * A negative slot is skipped: it marks a padded row with no cache slot. libr4d treats slot <= 0 as + * null because vLLM reserves block 0, but a generic reference must not steal a valid slot. * - * `k` AND `v` ARRIVE RANK 2 FROM THE ENGINE AND THEIR ROWS ARE NOT DENSE. An architecture that - * de-interleaves the projection hands [tokens, kv_heads, head_dim]; one that does not hands a - * COLUMN SLICE of the fused QKV plane -- [tokens, kv_heads * head_dim] whose row stride is the - * whole projection's width, 2560 against 256 on a 16-head model with 2 kv heads. Deriving the row - * stride from the shape instead of from the tensor puts token 0 in the right slot and every token - * after it inside the previous token's QUERY rows, which is a cache that looks written and holds - * the wrong keys from the second token on. `row_stride` asks the operand instead. */ + * `k` and `v` rows are not dense. A de-interleaved projection gives [tokens, kv_heads, head_dim]; + * otherwise they are a column slice of the fused QKV plane, [tokens, kv_heads * head_dim] with the + * projection's row stride (2560 vs 256 for 16 heads and 2 kv heads). Deriving the stride from the + * shape would write every token after the first from the wrong rows, so `row_stride` reads the + * operand. */ int ref_kv_store(const RadArgs* a, RadStream) { if (!have(a, 4)) return RAD_E_INVAL; const RadTensor *k = &a->t[0], *v = &a->t[1], *sm = &a->t[2], *kv = &a->t[3]; @@ -342,8 +382,8 @@ int ref_kv_store(const RadArgs* a, RadStream) { 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 KVView kvv = kv_view(kv, head_dim, block_size, kv_heads); - /* AN FP8 CACHE STORES k / k_scale: the scales are the descales the reader multiplies back by, - * 1.0 unless the call names them. A wider cache stores the value itself. */ + /* An fp8 cache stores k / k_scale, where the scales are the reader's descales (default 1.0). + * A wider cache stores the value itself. */ const bool fp8 = kv->dtype == RAD_F8E4M3 || kv->dtype == RAD_F8E5M2; 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; @@ -353,7 +393,7 @@ int ref_kv_store(const RadArgs* a, RadStream) { if (slot >= 0 && n_blocks > 0 && slot / block_size >= n_blocks) return RAD_E_SHAPE; } - #pragma omp parallel for schedule(static) + REF_PAR_FOR(M * kv_heads * head_dim * 2) for (int64_t t = 0; t < M; ++t) { const int64_t slot = ld_int(sm->dtype, sm->data, offlin(sm, t)); if (slot < 0) continue; @@ -372,21 +412,20 @@ int ref_kv_store(const RadArgs* a, RadStream) { /* ------------------------------------------------------------------ rope */ namespace { -/* NeoX pairs element i with i + rotary_dim/2; GPT-J (the "interleaved" style) pairs 2i with 2i+1. - * Which one a checkpoint wants is a property of the checkpoint, so it is a parameter and not a - * guess -- and getting it wrong produces fluent text with a broken sense of position, which is the - * hardest kind of wrong to notice (spec §12 makes the same point about token boundaries). +/* NeoX pairs element i with i + rotary_dim/2; GPT-J ("interleaved") pairs 2i with 2i+1. The + * checkpoint decides, so it is a parameter: the wrong one yields fluent text with broken position + * sense, which is hard to notice. * - * THE MULTI-COMPONENT MODES pair like NeoX and differ in which position component drives each + * The multi-component modes pair like NeoX and differ in which position component drives each * frequency (i indexes the rot/2 frequencies): * mrope contiguous sections: frequencies [0, s0) take component 0, the next s1 component 1... * (Qwen2-VL), all on one ladder theta^(-2i/rot). * imrope interleaved (Qwen3-VL): component 1 where i % 3 == 1 and i < 3*s1, component 2 where * i % 3 == 2 and i < 3*s2, component 0 everywhere else; one ladder. - * axial contiguous sections, EACH ON ITS OWN LADDER theta^(-2j/(2*s_c)) for its j-th - * frequency -- a 2-D rotary embedding over (row, column), the vision tower's. - * With one position component a token -- a rank-1 `positions` -- every component is that one and - * mrope and imrope ARE neox. */ + * axial contiguous sections, each on its own ladder theta^(-2j/(2*s_c)) for its j-th + * frequency: the vision tower's 2-D rotary embedding over (row, column). + * With one position component per token (rank-1 `positions`) every component is the same, and + * mrope and imrope reduce to neox. */ enum { ROPE_NEOX = 0, ROPE_GPTJ = 1, ROPE_MROPE = 2, ROPE_IMROPE = 3, ROPE_AXIAL = 4 }; struct RopeFreq { @@ -394,10 +433,10 @@ struct RopeFreq { float inv[REF_HD_MAX / 2]; }; -/* Which component and inverse frequency each of the rot/2 frequencies uses. */ -/* `den` is the width the BASE ladder is measured in: `rot` for a `rotary` ladder (a partial rotary - * is a complete rotation of its own width) and `head_dim` for `head`, the proportional variant. The - * loop count and the NeoX/GPT-J pairing still come from `rot`; `axial` overrides `inv` below. */ +/* The component and inverse frequency of each of the rot/2 frequencies. `den` is the width the base + * ladder is measured in: `rot` for a `rotary` ladder (a partial rotary is a full rotation of its + * own width), `head_dim` for the proportional `head` variant. The loop count and pairing still come + * from `rot`; `axial` overrides `inv`. */ static int rope_freqs(int mode, int64_t rot, int64_t den, float theta, const int64_t* sec, int n_sec, RopeFreq* f) { const int64_t half = rot / 2; @@ -407,12 +446,12 @@ static int rope_freqs(int mode, int64_t rot, int64_t den, float theta, const int if ((mode == ROPE_MROPE || mode == ROPE_AXIAL) && n_sec > 0 && total != half) return RAD_E_SHAPE; for (int64_t i = 0; i < half; ++i) { int c = 0; - float inv = 1.0f / std::pow(theta, (float)(2 * i) / (float)den); + float inv = 1.0f / ref_pow(theta, (float)(2 * i) / (float)den); if (n_sec > 0 && (mode == ROPE_MROPE || mode == ROPE_AXIAL)) { while (c + 1 < n_sec && i >= start[c + 1]) ++c; if (mode == ROPE_AXIAL) { const int64_t j = i - start[c]; - inv = 1.0f / std::pow(theta, (float)(2 * j) / (float)(2 * sec[c])); + inv = 1.0f / ref_pow(theta, (float)(2 * j) / (float)(2 * sec[c])); } } else if (n_sec >= 3 && mode == ROPE_IMROPE) { if (i % 3 == 1 && i < 3 * sec[1]) c = 1; @@ -429,7 +468,7 @@ static void rope_head(const RadTensor* t, int64_t base, int64_t ds, int64_t rot, const int64_t half = rot / 2; for (int64_t i = 0; i < half; ++i) { const float ang = pos[f.comp[i]] * f.inv[i]; - const float c = std::cos(ang) * magnitude, s = std::sin(ang) * magnitude; + const float c = ref_cos(ang) * magnitude, s = ref_sin(ang) * magnitude; const int64_t i0 = (mode == ROPE_GPTJ) ? 2 * i : i; const int64_t i1 = (mode == ROPE_GPTJ) ? 2 * i + 1 : i + half; const float x0 = ldt(t, base + i0 * ds), x1 = ldt(t, base + i1 * ds); @@ -453,9 +492,9 @@ static int rope_sections(const RadArgs* a, int64_t* sec) { return n; } -/* `ladder` names the width the base frequency ladder is measured in -- see rope_freqs. Absent and - * `rotary` divide by `rot` (every existing model); `head` divides by `head_dim`, which it needs. An - * unknown value is a schema error, not a silent default: a mistyped ladder is a silent wrong angle. */ +/* `ladder` names the width the base frequency ladder is measured in (see rope_freqs): absent or + * `rotary` divides by `rot`, `head` by `head_dim`. An unknown value is refused, since a mistyped + * ladder would silently give wrong angles. */ static int rope_ladder(const RadArgs* a, int64_t rot, int64_t head_dim, int64_t* den) { const char* lad = p_str(a, "ladder", nullptr); if (!lad) { *den = rot; return RAD_OK; } @@ -490,7 +529,7 @@ int ref_rope(const RadArgs* a, RadStream) { int64_t sec[8] = {}; const int n_sec = rope_sections(a, sec); if (n_sec < 0) return RAD_E_SHAPE; - /* POSITIONS: [M] is one component a token; [C, M] is C components, component-major. */ + /* Positions: [M] is one component per token; [C, M] is C components, component-major. */ const bool multi = pos->rank >= 2; const int64_t n_comp = multi ? pos->shape[0] : 1; const int64_t M = multi ? pos->shape[1] : numel(pos); @@ -499,9 +538,9 @@ int ref_rope(const RadArgs* a, RadStream) { const int64_t need = mode == ROPE_IMROPE ? 3 : n_sec; if (n_comp < need || n_comp > 8) return RAD_E_SHAPE; } - /* THE PROPORTIONAL LADDER (`head`) is HF's: the rotation spans the whole head -- pair i is - * (i, i + head_dim/2) -- and every frequency past rotary_dim/2 is zero, so those pairs turn by - * nothing. A rotary of rotary_dim's own width, pairing (i, i + rot/2), turns other channels. */ + /* The proportional ladder (`head`) is HF's: the rotation spans the whole head, pair i being + * (i, i + head_dim/2), and frequencies past rotary_dim/2 are zero so those pairs do not turn. + * A rotary of rotary_dim's own width, pairing (i, i + rot/2), would turn other channels. */ const int64_t nfreq = rot / 2; if (den == head_dim && rot < head_dim && !multi && mode == ROPE_NEOX) rot = head_dim; RopeFreq f; @@ -514,14 +553,13 @@ int ref_rope(const RadArgs* a, RadStream) { } for (int64_t i = nfreq; i < rot / 2; ++i) f.inv[i] = 0.0f; - const int64_t stride_row = (n_head + 2 * n_head_kv) * head_dim; if (M <= 0 || numel(qkv) < M * stride_row) return RAD_E_SHAPE; - const int64_t rs = qkv->rank >= 2 ? qkv->stride[qkv->rank - 2] : stride_row; + const int64_t rs = row_stride(qkv, stride_row); const int64_t ds = laststride(qkv); const int64_t pcs = multi ? pos->stride[0] : 0, pms = multi ? pos->stride[1] : 0; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(M * stride_row) for (int64_t m = 0; m < M; ++m) { float p[8]; const float div = rscale != 0.0f ? rscale : 1.0f; @@ -533,8 +571,7 @@ int ref_rope(const RadArgs* a, RadStream) { for (int c = 0; c < 8; ++c) p[c] = one; } const int64_t row = m * rs; - /* Q heads then K heads. The V heads that follow are left alone, which is the whole reason - * this op takes the fused qkv rather than two tensors. */ + /* Q heads then K heads; the V heads after them are left alone. */ for (int64_t h = 0; h < n_head + n_head_kv; ++h) rope_head(qkv, row + h * head_dim * ds, ds, rot, mode, f, p, yarn.magnitude); } @@ -542,16 +579,13 @@ int ref_rope(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------------ qk_norm_rope */ -/* The QK-norm preamble and the rotation in one op: an RMS norm over each 128-wide (or whatever - * head_dim is) q and k head against its own gain vector, then RoPE. `v_norm` 1 also RMS-norms - * each v head with a UNIT gain and no rotation -- Gemma 4's value norm, which has no weight. The - * v heads are otherwise left alone. +/* QK-norm and rotation in one op: an RMS norm over each head_dim-wide q and k head against its own + * gain vector, then RoPE. `v_norm` 1 also RMS-norms each v head with unit gain and no rotation + * (Gemma 4's weightless value norm); otherwise v heads are untouched. * - * THE NORM OUTPUT IS ROUNDED TO THE TENSOR'S DTYPE BEFORE THE ROTATION. That is not an accident of - * writing it back in place -- it is what the unfused pair does, because the norm stores a tensor - * and the rotation reads it, and libr4d's r4d_qk_norm_rope_gate matches the unfused reference for - * exactly this reason. A fused kernel that kept f32 across the seam would be half a ULP better and - * would fail a comparison against this. */ + * The norm output is rounded to the tensor's dtype before the rotation, as the unfused pair does; + * libr4d's r4d_qk_norm_rope_gate matches this. A fused kernel keeping f32 across the seam would be + * half a ULP better and fail the comparison. */ int ref_qk_norm_rope(const RadArgs* a, RadStream) { if (!have(a, 4)) return RAD_E_INVAL; const RadTensor *qkv = &a->t[0], *pos = &a->t[1], *qw = &a->t[2], *kw = &a->t[3]; @@ -564,9 +598,9 @@ int ref_qk_norm_rope(const RadArgs* a, RadStream) { const float rscale = p_f32(a, "scale", 1.0f); const float wadd = p_f32(a, "wadd", 0.0f); const int v_norm = (int)p_int(a, "v_norm", 0); - /* `gptj_blocks` is `blocks` with each section's pairs ADJACENT -- (start + 2j, start + 2j + 1), - * the complex-number form a 3-axis image rotary takes (Qwen-Image's). `imrope` is `rope`'s - * interleaved M-RoPE over NeoX pairs, after the norm (Qwen3-VL's text attention). */ + /* `gptj_blocks` is `blocks` with each section's pairs adjacent, (start + 2j, start + 2j + 1): + * the complex-number form of Qwen-Image's 3-axis rotary. `imrope` is `rope`'s interleaved + * M-RoPE over NeoX pairs, after the norm (Qwen3-VL text attention). */ static const char* kModes[] = { "neox", "gptj", "blocks", "gptj_blocks", "imrope" }; const int mode = p_enum(a, "mode", kModes, 5, 0); if (mode < 0) return RAD_E_UNSUPPORTED; @@ -577,10 +611,10 @@ int ref_qk_norm_rope(const RadArgs* a, RadStream) { if (head_dim <= 0 || n_head <= 0 || rot <= 0 || rot > head_dim || (rot & 1)) return RAD_E_SHAPE; if (numel(qw) < head_dim || numel(kw) < head_dim) return RAD_E_SHAPE; - /* BLOCKS: section c is `sec[c]` rotary pairs over its own run of 2 * sec[c] channels, paired + /* Blocks: section c is `sec[c]` rotary pairs over its own run of 2 * sec[c] channels, paired * (start + j, start + sec[c] + j) and turned by position component comps[c] at - * theta^(-j / sec[c]) -- each section a complete neox rotary of its own width. The sections - * fill the rotated prefix exactly. Positions are [C, M], component-major. */ + * theta^(-j / sec[c]), i.e. a complete neox rotary of its own width. The sections fill the + * rotated prefix exactly. Positions are [C, M], component-major. */ int64_t sec[8] = {}, comp[8] = {}; int n_sec = 0; if (im) { @@ -616,15 +650,28 @@ int ref_qk_norm_rope(const RadArgs* a, RadStream) { const int64_t stride_row = (n_head + 2 * n_head_kv) * head_dim; if (M <= 0 || numel(qkv) < M * stride_row) return RAD_E_SHAPE; - const int64_t rs = qkv->rank >= 2 ? qkv->stride[qkv->rank - 2] : stride_row; + const int64_t rs = row_stride(qkv, stride_row); const int64_t ds = laststride(qkv); RopeFreq f; - /* No `ladder` on this row yet: the fused norm+rope measures by `rot`, as it always has. */ + /* No `ladder` parameter here: the fused norm+rope measures by `rot`. */ if (im) RAD_REF_TRY(rope_freqs(ROPE_IMROPE, rot, rot, theta, sec, multi ? n_sec : 0, &f)); else RAD_REF_TRY(rope_freqs(blocks ? 0 : mode, rot, rot, theta, nullptr, 0, &f)); + /* RMS-norms one head in place, against gain `w` (+ wadd), or unit gain without one. */ + auto norm_head = [&](int64_t base, const RadTensor* w) { + float ss = 0.0f; + for (int64_t d = 0; d < head_dim; ++d) { + const float x = ldt(qkv, base + d * ds); + ss += x * x; + } + const float sc = 1.0f / std::sqrt(ss / (float)head_dim + eps); + for (int64_t d = 0; d < head_dim; ++d) { + const float x = ldt(qkv, base + d * ds) * sc; + stt(qkv, base + d * ds, w ? x * (ldt(w, d * laststride(w)) + wadd) : x); + } + }; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(M * stride_row) for (int64_t m = 0; m < M; ++m) { float p[8]; const float div = rscale != 0.0f ? rscale : 1.0f; @@ -637,16 +684,8 @@ int ref_qk_norm_rope(const RadArgs* a, RadStream) { } const int64_t row = m * rs; for (int64_t h = 0; h < n_head + n_head_kv; ++h) { - const RadTensor* w = h < n_head ? qw : kw; - const int64_t base = row + h * head_dim * ds, ws = laststride(w); - float ss = 0.0f; - for (int64_t d = 0; d < head_dim; ++d) { - float x = ldt(qkv, base + d * ds); - ss += x * x; - } - const float sc = 1.0f / std::sqrt(ss / (float)head_dim + eps); - for (int64_t d = 0; d < head_dim; ++d) - stt(qkv, base + d * ds, ldt(qkv, base + d * ds) * sc * (ldt(w, d * ws) + wadd)); + const int64_t base = row + h * head_dim * ds; + norm_head(base, h < n_head ? qw : kw); if (!blocks) { rope_head(qkv, base, ds, rot, im ? ROPE_IMROPE : mode, f, p); continue; @@ -654,9 +693,9 @@ int ref_qk_norm_rope(const RadArgs* a, RadStream) { int64_t start = 0; for (int c = 0; c < n_sec; ++c) { for (int64_t j = 0; j < sec[c]; ++j) { - const float inv = 1.0f / std::pow(theta, (float)j / (float)sec[c]); + const float inv = 1.0f / ref_pow(theta, (float)j / (float)sec[c]); const float ang = p[comp[c]] * inv; - const float cs = std::cos(ang), sn = std::sin(ang); + const float cs = ref_cos(ang), sn = ref_sin(ang); const int64_t i0 = adjacent ? start + 2 * j : start + j; const int64_t i1 = adjacent ? start + 2 * j + 1 : start + sec[c] + j; const float x0 = ldt(qkv, base + i0 * ds), x1 = ldt(qkv, base + i1 * ds); @@ -666,29 +705,12 @@ int ref_qk_norm_rope(const RadArgs* a, RadStream) { start += 2 * sec[c]; } } - for (int64_t h = 0; v_norm && h < n_head_kv; ++h) { - const int64_t base = row + (n_head + n_head_kv + h) * head_dim * ds; - float ss = 0.0f; - for (int64_t d = 0; d < head_dim; ++d) { - float x = ldt(qkv, base + d * ds); - ss += x * x; - } - const float sc = 1.0f / std::sqrt(ss / (float)head_dim + eps); - for (int64_t d = 0; d < head_dim; ++d) - stt(qkv, base + d * ds, ldt(qkv, base + d * ds) * sc); - } + for (int64_t h = 0; v_norm && h < n_head_kv; ++h) + norm_head(row + (n_head + n_head_kv + h) * head_dim * ds, nullptr); } return RAD_OK; } -/* A value as a tensor of `dt` holds it: rounded through the dtype's own store and load. */ -static inline float round_dt(uint32_t dt, float v) { - uint64_t buf = 0; - st_dt(dt, &buf, 0, v); - return ld_dt(dt, &buf, 0); -} -static inline int64_t rows_n(const RadTensor* t, int64_t n) { return n > 0 ? numel(t) / n : 0; } - /* ------------------------------------------------------------------ attn_local_rel */ /* Local attention with a relative-position term: Gemma 4's audio (USM conformer) attention. * @@ -702,11 +724,10 @@ static inline int64_t rows_n(const RadTensor* t, int64_t n) { return n > 0 ? num * then a softmax over those keys and the weighted sum of v, all in f32 and rounded once. `relk` * is [left + 1, n_head * head_dim]: row d is the projected relative position for distance d. * - * The reference computes this in 12-query blocks over 24-key context windows and shifts the - * relative term into place (Transformer-XL's rel_shift); every key outside 0 <= i - j <= left - * carries a -1e9 logit there and a zero weight after the softmax, so the sliding form below is - * the same function. softplus(pds) is rounded to the weight's dtype before use, as the reference - * evaluates it on the bf16 parameter. */ + * The upstream model computes this in 12-query blocks over 24-key windows with Transformer-XL's + * rel_shift; keys outside 0 <= i - j <= left get a -1e9 logit and zero weight there, so this + * sliding form is the same function. softplus(pds) is rounded to the weight's dtype before use, + * as upstream evaluates it on the bf16 parameter. */ int ref_attn_local_rel(const RadArgs* a, RadStream) { if (!have(a, 7)) return RAD_E_INVAL; const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *rk = &a->t[3]; @@ -722,7 +743,8 @@ int ref_attn_local_rel(const RadArgs* a, RadStream) { if (numel(pds) < D || numel(rk) < (L + 1) * W) return RAD_E_SHAPE; const int64_t S = numel(cu) - 1; if (S <= 0) return RAD_E_SHAPE; - const int64_t Mq = rows_n(q, W), Mk = rows_n(k, W), Mv = rows_n(v, W), Mo = rows_n(o, W); + const int64_t Mq = rows_of(q, W), Mk = rows_of(k, W), Mv = rows_of(v, W), Mo = rows_of(o, W); + if (Mq <= 0 || Mo <= 0 || cu_at(cu, S) <= cu_at(cu, 0)) return RAD_E_SHAPE; /* zero rows */ const float qs = (float)(1.0 / std::sqrt((double)D) / std::log(2.0)); const float ks = (float)(std::log(1.0 + std::exp(1.0)) / std::log(2.0)); @@ -731,13 +753,13 @@ int ref_attn_local_rel(const RadArgs* a, RadStream) { spd[d] = round_dt(pds->dtype, act_softplus(ldt(pds, d * laststride(pds)), 20.0f)); for (int64_t s = 0; s < S; ++s) { - const int64_t c0 = ld_int(cu->dtype, cu->data, offlin(cu, s)); - const int64_t c1 = ld_int(cu->dtype, cu->data, offlin(cu, s + 1)); + const int64_t c0 = cu_at(cu, s); + const int64_t c1 = cu_at(cu, s + 1); if (c0 % cdiv || c1 % cdiv || c1 < c0) return RAD_E_SHAPE; const int64_t t0 = c0 / cdiv, t1 = c1 / cdiv; if (t1 > Mq || t1 > Mk || t1 > Mv || t1 > Mo) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + REF_PAR_FOR((t1 - t0) * H * D * (L + R + 1)) for (int64_t ih = 0; ih < (t1 - t0) * H; ++ih) { const int64_t i = t0 + ih / H, h = ih % H; float qf[REF_HD_MAX], lg[REF_HD_MAX], acc[REF_HD_MAX]; @@ -753,13 +775,13 @@ int ref_attn_local_rel(const RadArgs* a, RadStream) { ac += qf[d] * (ldt(k, kb + d * laststride(k)) * ks); bd += qf[d] * ldt(rk, rb + d * laststride(rk)); } - const float x = cap * std::tanh((ac + bd) / cap); + const float x = cap * ref_tanh((ac + bd) / cap); lg[j - j0] = x; mx = x > mx ? x : mx; } float sum = 0.0f; for (int64_t j = j0; j <= i; ++j) { - lg[j - j0] = std::exp(lg[j - j0] - mx); + lg[j - j0] = ref_exp(lg[j - j0] - mx); sum += lg[j - j0]; } for (int64_t d = 0; d < D; ++d) acc[d] = 0.0f; @@ -776,14 +798,11 @@ int ref_attn_local_rel(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------------ rope_table */ -/* The cos/sin plane a fused prologue reads instead of theta, written at each position's OWN row of - * a [max_ctx, rot] table: `rot` values a row, cos for the first rot/2 and sin for the second. +/* The cos/sin plane a fused prologue reads instead of theta, written at each position's own row of + * a [max_ctx, rot] table: cos in the first rot/2 values of a row, sin in the second. * - * THE ANGLES ARE `rope`'s, TO THE LAST OPERATION, and that is the whole contract: a fused rotation - * that read a table built any other way would be a different model, and the difference would be a - * fraction of a ULP per element -- fluent text, subtly wrong positions, exactly the failure class - * this file's rope_head comment is about. Only the rows `positions` names are written; a negative - * position is a padded row and writes nothing. */ + * The angles must match `rope`'s to the last operation; any other construction gives subtly wrong + * positions. Only rows named by `positions` are written; a negative position writes nothing. */ int ref_rope_table(const RadArgs* a, RadStream) { if (!have(a, 2)) return RAD_E_INVAL; const RadTensor *pos = &a->t[0], *cs = &a->t[1]; @@ -801,16 +820,16 @@ int ref_rope_table(const RadArgs* a, RadStream) { const RadYarn yarn = rad_yarn_args(a); if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && rscale != 1.0f)) return RAD_E_INVAL; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(M * rot) for (int64_t m = 0; m < M; ++m) { const int64_t pp = ld_int(pos->dtype, pos->data, offlin(pos, m)); if (pp < 0 || pp >= rows) continue; const float p = (float)pp / (rscale != 0.0f ? rscale : 1.0f); for (int64_t i = 0; i < half; ++i) { - const float inv = yarn.frequency(1.0f / std::pow(theta, (float)(2 * i) / (float)den), (int)i); + const float inv = yarn.frequency(1.0f / ref_pow(theta, (float)(2 * i) / (float)den), (int)i); const float ang = p * inv; - stt(cs, offlin(cs, pp * rot + i), std::cos(ang) * yarn.magnitude); - stt(cs, offlin(cs, pp * rot + half + i), std::sin(ang) * yarn.magnitude); + stt(cs, offlin(cs, pp * rot + i), ref_cos(ang) * yarn.magnitude); + stt(cs, offlin(cs, pp * rot + half + i), ref_sin(ang) * yarn.magnitude); } } return RAD_OK; @@ -819,16 +838,16 @@ int ref_rope_table(const RadArgs* a, RadStream) { /* ------------------------------------------------------------------ qsa_block_key */ /* The QSA indexer's compressed key (docs/OPS.md, docs/QSA.md): for each of M blocks, * - * pooled = mean of the block's `ratio` rows of k, accumulated in f32 and ROUNDED TO k's dtype + * pooled = mean of the block's `ratio` rows of k, accumulated in f32 and rounded to k's dtype * normed = pooled * rsqrt(mean(pooled^2) + eps) * (wadd + w) * out = NeoX rotary of normed's first `rotary_dim` lanes at the block's position, the rest * passed through, rounded once at the store * - * The rounding after the mean is the reference model's (`.float().mean(dim=1).to(dtype)`) and is - * part of the answer. The block's position is `pos[b]` (a [>= M, 1 or 3] list carries a block's - * components side by side, read under `mode` mrope/imrope and `sections`), or `pos0 + b*ratio` - * without one. `page[b]`, when given, is the output row, and a negative entry writes nothing. The - * rotary is `rope`'s ladder with YaRN's blend and magnitude when the coefficients are given. */ + * The rounding after the mean is the upstream model's (`.float().mean(dim=1).to(dtype)`). The + * block's position is `pos[b]` (a [>= M, 1 or 3] list holds a block's components side by side, + * read under `mode` mrope/imrope and `sections`), or `pos0 + b*ratio` without one. `page[b]`, when + * given, is the output row; a negative entry writes nothing. The rotary is `rope`'s ladder, with + * YaRN's blend and magnitude when its coefficients are given. */ int ref_qsa_block_key(const RadArgs* a, RadStream) { const RadTensor* k = t_in(a, 0); const RadTensor* w = t_in(a, 1); @@ -857,8 +876,8 @@ int ref_qsa_block_key(const RadArgs* a, RadStream) { int64_t sec[8] = {}; const int n_sec = rope_sections(a, sec); if (n_sec < 0 || n_sec > 3) return RAD_E_SHAPE; - /* Several components only with a mode, its sections and three columns of `pos`; otherwise - * every frequency reads the block's one position, which every mode reads as NeoX. */ + /* Multiple components need a mode, its sections and three columns of `pos`; otherwise every + * frequency reads the block's single position, which reduces every mode to NeoX. */ const bool mc = mode != ROPE_NEOX && n_sec > 0 && pos2 && pos->shape[1] >= 3; const RadYarn yarn = rad_yarn_args(a); if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && (rot <= 0 || rscale != 1.0f))) @@ -867,7 +886,7 @@ int ref_qsa_block_key(const RadArgs* a, RadStream) { RAD_REF_TRY(rope_freqs(mc ? mode : ROPE_NEOX, rot, rot, theta, sec, mc ? n_sec : 0, &f)); for (int64_t i = 0; i < rot / 2; ++i) f.inv[i] = yarn.frequency(f.inv[i], (int)i); - #pragma omp parallel for schedule(static) + REF_PAR_FOR(M * n * ratio) for (int64_t b = 0; b < M; ++b) { const int64_t orow = page ? ld_int(page->dtype, page->data, offlin(page, b)) : b; if (orow < 0) continue; @@ -876,9 +895,7 @@ int ref_qsa_block_key(const RadArgs* a, RadStream) { for (int64_t t = 0; t < n; ++t) { float acc = 0.0f; for (int64_t j = 0; j < ratio; ++j) acc += ldt(k, offlin(k, (b * ratio + j) * n + t)); - uint64_t tmp = 0; - st_dt(k->dtype, &tmp, 0, acc / (float)ratio); - x[t] = ld_dt(k->dtype, &tmp, 0); + x[t] = round_dt(k->dtype, acc / (float)ratio); ss += (double)x[t] * x[t]; } const float inv = 1.0f / std::sqrt((float)(ss / (double)n) + eps); @@ -893,7 +910,7 @@ int ref_qsa_block_key(const RadArgs* a, RadStream) { const int64_t half = rot / 2; for (int64_t i = 0; i < half; ++i) { const float ang = p[f.comp[i]] * f.inv[i]; - const float c = std::cos(ang) * yarn.magnitude, s = std::sin(ang) * yarn.magnitude; + const float c = ref_cos(ang) * yarn.magnitude, s = ref_sin(ang) * yarn.magnitude; const float x0 = y[i], x1 = y[half + i]; y[i] = x0 * c - x1 * s; y[half + i] = x0 * s + x1 * c; diff --git a/libref/ref_collective.cpp b/libref/ref_collective.cpp index fcac6a8e..f6a63025 100644 --- a/libref/ref_collective.cpp +++ b/libref/ref_collective.cpp @@ -1,33 +1,26 @@ /* ref_collective.cpp -- all_reduce and all_gather on the host backend. * - * At world_size 1 both are the degenerate case: all_reduce is inout and already holds the answer, - * all_gather is a copy. Above 1 they are real, and they work because of how this engine is shaped: - * ONE PROCESS, ONE THREAD PER RANK, ONE ADDRESS SPACE (spec §1). There is no IPC to set up and no - * serialisation to do -- a peer's buffer is a pointer -- so the whole collective is a rendezvous, a - * read of every rank's pointer, and a second rendezvous before anyone overwrites theirs. + * At world_size 1 all_reduce is a no-op (inout) and all_gather a copy. Above 1 they rely on the + * engine's shape: one process, one thread per rank, one address space (spec §1). A peer's buffer is + * a pointer, so a collective is a rendezvous, a read of every rank's pointer, and a second + * rendezvous before anyone overwrites theirs. * - * That makes the host backend a FAKE MULTI-DEVICE BACKEND, which is the point: tensor-parallel code - * paths -- the sharded declare, the collective placement, the distributed top-k -- can be exercised - * on a machine with no accelerator at all. What it does not test is a device all-reduce's numerics, - * and it does not pretend to. + * This makes the host backend a fake multi-device backend, so tensor-parallel paths (sharded + * declare, collective placement, distributed top-k) can run without an accelerator. It does not + * test a device all-reduce's numerics. * - * REDUCTION ORDER IS ASCENDING RANK, in f32, on every rank. That is libr4d's rule ("fp32 - * accumulate in ascending rank order, bit-identical across ranks") and it is a correctness - * requirement rather than a convention: tensor-parallel ranks hold replicated state that must stay - * bit-identical, and two ranks that summed in different orders would drift apart over a - * generation. The `-ffp-contract=off` this plugin builds with is part of the same rule - * (docs/OPS.md). + * Reduction order is ascending rank, in f32, on every rank (libr4d's rule). Tensor-parallel ranks + * hold replicated state that must stay bit-identical; different summation orders would drift apart + * over a generation. -ffp-contract=off is part of the same rule (docs/OPS.md). * - * `exact` is honoured in one direction only. exact=1 gets the exact sum. exact=0 -- a caller that - * has declared it will accept a lossy quantised wire -- also gets the exact sum, because there is - * no wire here to quantise. Serving a lossy request with an exact answer is safe; the constraint - * exists so a caller who wanted exactness cannot be handed a lossy result by accident, not the - * reverse. `hops` is accepted and ignored: one-shot and two-shot are the same walk over an array - * when the peers are pointers. + * exact=0 (caller accepts a lossy quantised wire) also gets the exact sum, since there is no wire; + * the constraint only forbids handing a lossy result to a caller that asked for exact. `hops` is + * ignored: one-shot and two-shot are the same walk when peers are pointers. */ #include "ref_common.h" #include "ref_ops.h" +#include #include #include #include @@ -39,15 +32,15 @@ namespace { enum { REF_MAX_RANKS = 8 }; -/* One group per process. There is exactly one world size in a radiance process and the rank - * threads run the same declared graph in lockstep against one batch, so the sequence of collective - * calls is identical on every rank and a single sense-reversing barrier is enough to pair them up. - * A per-op group would need a key the ABI does not carry -- init() is called once per rank per - * resolved instance and cannot tell two ops apart from two ranks of one op. */ +/* One group per process. A process has one world size and the rank threads run the same graph in + * lockstep, so every rank issues the same sequence of collectives and one generation-counting + * barrier pairs them. A per-op group would need a key the ABI does not carry: init() cannot tell + * two ops apart from two ranks of one op. */ struct Group { std::mutex m; std::condition_variable cv; int world = 0; + int members = 0; /* initialised instances not yet finalised (see join) */ int arrived = 0; unsigned gen = 0; const void* slot[REF_MAX_RANKS] = {}; @@ -57,11 +50,14 @@ struct Group { static Group& group() { static Group g; return g; } -/* Returns false on timeout. A collective IS a synchronisation, so the no-blocking rule cannot - * apply to it -- but an unbounded wait would turn a mismatched call sequence into a wedged test - * run with no output, and this engine exits non-zero rather than serving from a wedged queue - * (spec §17). Thirty seconds is far longer than any correct step and far shorter than a CI - * timeout. */ +/* How long a rank waits for its peers. A collective must block, but an unbounded wait would turn a + * mismatched call sequence into a silent hang; the engine exits non-zero instead (spec §17). 30 s is + * far longer than any correct step and shorter than a CI timeout. ref_collective_timeout_ms sets it + * for a test. */ +static std::atomic g_timeout_ms{ 30000 }; + +/* Returns false on timeout. A rank that gives up withdraws its arrival, so the group's count is + * again that of the ranks still waiting and the next collective pairs from a clean start. */ static bool barrier(Group& g) { std::unique_lock lk(g.m); const unsigned mygen = g.gen; @@ -71,23 +67,48 @@ static bool barrier(Group& g) { g.cv.notify_all(); return true; } - return g.cv.wait_for(lk, std::chrono::seconds(30), [&] { return g.gen != mygen; }); + const bool met = g.cv.wait_for(lk, std::chrono::milliseconds(g_timeout_ms.load()), + [&] { return g.gen != mygen; }); + if (!met) --g.arrived; + return met; } -static int join(int rank, int world) { +/* The world size is fixed while it is in use: while an initialised instance is alive or a rank is + * mid-collective. Otherwise the next join may state another one, so a process can run one group + * after another (a re-initialised engine, a test). `member` counts an init, which fini releases. */ +static int join(int rank, int world, bool member) { if (world <= 0 || world > REF_MAX_RANKS) return RAD_E_UNSUPPORTED; if (rank < 0 || rank >= world) return RAD_E_INVAL; Group& g = group(); std::lock_guard lk(g.m); - if (g.world == 0) g.world = world; + if (g.world == 0 || (g.members == 0 && g.arrived == 0)) g.world = world; else if (g.world != world) return RAD_E_INVAL; + if (member) ++g.members; return RAD_OK; } -/* Staging, so a rank does not overwrite its own buffer while a peer is still reading it. The - * scratch the arena hands us is used when it is big enough -- that is what the scratch hook exists - * for -- and the per-thread workspace covers a caller that passed none (a test, or a tool calling - * the kernel directly). */ +/* Publishes this rank's input and waits until every rank has published a matching one. Peers read + * each other's input as `nel` contiguous elements, since only the pointer is published. */ +static int publish(int rank, int world, const RadTensor* x, int64_t nel) { + if (!rad_tensor_is_contiguous(x)) return RAD_E_STRIDE; + RAD_REF_TRY(join(rank, world, false)); + Group& g = group(); + { + std::lock_guard lk(g.m); + g.slot[rank] = x->data; + g.nel [rank] = nel; + g.dt [rank] = x->dtype; + } + if (!barrier(g)) return RAD_E_DEVICE; + for (int r = 0; r < world; ++r) { + if (!g.slot[r] || g.nel[r] != nel) return RAD_E_SHAPE; + if (g.dt[r] != x->dtype) return RAD_E_DTYPE; + } + return RAD_OK; +} + +/* Staging, so a rank does not overwrite its buffer while a peer still reads it. Uses the arena's + * scratch when large enough, else the per-thread workspace (for direct callers that pass none). */ static float* staging(const RadArgs* a, int64_t nel) { if (a->scratch && a->scratch_bytes >= nel * (int64_t)sizeof(float)) return (float*)a->scratch; @@ -98,18 +119,30 @@ static float* staging(const RadArgs* a, int64_t nel) { int ref_collective_init(const RadParam* p, int n_p, int rank, int world_size, void** out) { - /* The world size in the geometry wins: declare states it, and RadBuildCtx already divided the - * model by it (spec §9). */ + /* The geometry's world size wins: declare states it and RadBuildCtx divided the model by it + * (spec §9). */ int ws = world_size; for (int i = 0; i < n_p; ++i) if (p[i].key && std::strcmp(p[i].key, "world_size") == 0 && p[i].kind == RAD_P_INT) ws = (int)p[i].ival; if (out) *out = nullptr; if (ws <= 1) return RAD_OK; - return join(rank, ws); + RAD_REF_TRY(join(rank, ws, true)); + if (out) *out = &group(); + return RAD_OK; } -void ref_collective_fini(void*) {} +/* Pairs with an init that joined (its instance is the group); one that did not has none. */ +void ref_collective_fini(void* inst) { + if (!inst) return; + Group& g = group(); + std::lock_guard lk(g.m); + if (g.members > 0) --g.members; +} + +/* Test hook, exported beside the ABI entry points: how long a rank waits for its peers before + * the collective returns RAD_E_DEVICE. A non-positive value restores the default. */ +extern "C" void ref_collective_timeout_ms(int ms) { g_timeout_ms.store(ms > 0 ? ms : 30000); } int64_t ref_all_reduce_scratch(const RadArgs* a) { const int64_t ws = p_int(a, "world_size", a->world_size > 0 ? a->world_size : 1); @@ -119,10 +152,9 @@ int64_t ref_all_reduce_scratch(const RadArgs* a) { } /* ------------------------------------------------------------------ all_reduce */ -/* `y` is optional and absent means IN PLACE, which is the form docs/OPS.md draws and the only one - * the one-shot kernels need. libr4d's two-shot rows are not safe in place -- a rank gathers into - * the output while its own input is still being read for the scatter -- so the destination has to - * be expressible, and here it costs one branch on the store. */ +/* `y` is optional; absent means in place (docs/OPS.md's form, all the one-shot kernels need). + * libr4d's two-shot rows are not safe in place, since a rank gathers into the output while its + * input is still read for the scatter, so a separate destination must be expressible. */ int ref_all_reduce(const RadArgs* a, RadStream) { if (!have(a, 1)) return RAD_E_INVAL; const RadTensor* x = &a->t[0]; @@ -135,26 +167,12 @@ int ref_all_reduce(const RadArgs* a, RadStream) { const int world = (int)p_int(a, "world_size", a->world_size > 0 ? a->world_size : 1); if (world <= 1) { - /* inout: the answer is already there. With a separate destination it still has to be - * COPIED there, because a caller that passed one reads it and not x. */ + /* x already holds the answer; copy it to a separate destination if one was given. */ if (y) for (int64_t i = 0; i < nel; ++i) stt(y, offlin(y, i), ldt(x, offlin(x, i))); return RAD_OK; } - const int rank = a->rank; - RAD_REF_TRY(join(rank, world)); - + RAD_REF_TRY(publish(a->rank, world, x, nel)); Group& g = group(); - { - std::lock_guard lk(g.m); - g.slot[rank] = x->data; - g.nel [rank] = nel; - g.dt [rank] = x->dtype; - } - if (!barrier(g)) return RAD_E_DEVICE; - - for (int r = 0; r < world; ++r) - if (!g.slot[r] || g.nel[r] != nel || g.dt[r] != x->dtype) return RAD_E_SHAPE; - float* acc = staging(a, nel); for (int64_t i = 0; i < nel; ++i) { float s = 0.0f; @@ -162,9 +180,8 @@ int ref_all_reduce(const RadArgs* a, RadStream) { acc[i] = s; } - /* Everyone has finished READING before anyone WRITES. Without this the rank that finishes - * first would overwrite an input a slower peer has not consumed yet, and the bug would show up - * as a rank-dependent answer under load and never in a small test. */ + /* Every rank finishes reading before any writes; otherwise a fast rank overwrites input a + * slower peer has not consumed, giving rank-dependent answers under load. */ if (!barrier(g)) return RAD_E_DEVICE; for (int64_t i = 0; i < nel; ++i) stt(dst, offlin(dst, i), acc[i]); return RAD_OK; @@ -173,14 +190,10 @@ int ref_all_reduce(const RadArgs* a, RadStream) { /* ------------------------------------------------------------------ all_gather */ /* y is [world_size * numel] with rank r's contribution at offset r * numel. * - * A GATHER MOVES BYTES, NOT NUMBERS, and here the difference is not academic. The vocab-parallel - * candidate merge gathers (id, score) pairs as an opaque u32 payload -- the ids are i32 and the - * scores are f32 bit patterns, in one buffer. Carried through float, an id of -1 (0xFFFFFFFF, the - * empty-candidate marker) becomes 4294967296.0f, which is one past the largest u32, and storing - * that back is undefined; it lands as zero. A float-carrying reference therefore disagrees with a - * correct kernel on exactly the padding of every gathered candidate list, and rounds every id - * above 2^24 as well. Copying the stored representation is also simply what the operation IS: no - * arithmetic happens here. */ + * A gather moves bytes, not numbers. The vocab-parallel candidate merge gathers (id, score) pairs + * as an opaque u32 payload of i32 ids and f32 bit patterns. Through float, the -1 empty-candidate + * id (0xFFFFFFFF) becomes 4294967296.0f, which stores back as zero (undefined), and ids above 2^24 + * round. */ int ref_all_gather(const RadArgs* a, RadStream) { if (!have(a, 2)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *y = &a->t[1]; @@ -188,9 +201,8 @@ int ref_all_gather(const RadArgs* a, RadStream) { const int64_t nel = band_rows(numel(x), p_int(a, "numel", 0)); const int world = (int)p_int(a, "world_size", a->world_size > 0 ? a->world_size : 1); if (nel <= 0 || numel(y) < nel * world) return RAD_E_SHAPE; - /* One element has to have an address of its own for a byte copy to mean anything, which rules - * out the sub-byte codes -- and a gather of packed weights is not a thing any caller asks - * for, so refusing says more than a silent unpack would. */ + /* A byte copy needs whole-byte elements; sub-byte codes are refused (no caller gathers packed + * weights). */ const int64_t esz = rad_dtype_bytes(x->dtype, 1); if (esz <= 0 || y->dtype != x->dtype) return RAD_E_DTYPE; @@ -201,25 +213,11 @@ int ref_all_gather(const RadArgs* a, RadStream) { return RAD_OK; } - const int rank = a->rank; - RAD_REF_TRY(join(rank, world)); + RAD_REF_TRY(publish(a->rank, world, x, nel)); Group& g = group(); - { - std::lock_guard lk(g.m); - g.slot[rank] = x->data; - g.nel [rank] = nel; - g.dt [rank] = x->dtype; - } - if (!barrier(g)) return RAD_E_DEVICE; - - for (int r = 0; r < world; ++r) { - if (!g.slot[r] || g.nel[r] != nel) return RAD_E_SHAPE; - if (g.dt[r] != x->dtype) return RAD_E_DTYPE; - } - /* WHERE A RANK'S ELEMENTS LAND. `row` absent (or the whole message) is the plain - * concatenation; present, the placement is row-interleaved -- x is [rows][row] and y is - * [rows][world][row] -- which is the form the vocab-parallel candidate merge reads, because it - * takes one row of gathered candidates per sampled position at a single row stride. */ + /* Placement. `row` absent (or the whole message) is plain concatenation; present, it is + * row-interleaved, x [rows][row] into y [rows][world][row], the form the vocab-parallel + * candidate merge reads (one row of candidates per sampled position at one stride). */ const int64_t row = p_int(a, "row", 0); if (row < 0 || (row > 0 && nel % row)) return RAD_E_SHAPE; for (int r = 0; r < world; ++r) @@ -231,9 +229,8 @@ int ref_all_gather(const RadArgs* a, RadStream) { (const char*)g.slot[r] + i * esz, (size_t)esz); } - /* y is a different buffer from x, so no second barrier is needed for correctness -- but the - * ranks must not race ahead into the NEXT collective while a peer still reads this one's - * input, and the pairing of barriers is what keeps the call sequences aligned. */ + /* y is separate from x, but ranks must not start the next collective while a peer still reads + * this one's input; the barrier also keeps call sequences paired. */ if (!barrier(g)) return RAD_E_DEVICE; return RAD_OK; } diff --git a/libref/ref_common.h b/libref/ref_common.h index 4d80ea97..6dc82a7d 100644 --- a/libref/ref_common.h +++ b/libref/ref_common.h @@ -1,43 +1,45 @@ -/* ref_common.h -- libref's numeric bedrock: dtype conversion, strided element access, and - * the parameter readers every op shares. +/* ref_common.h -- libref's numeric core: dtype conversion, strided element access, and the + * parameter readers every op shares. * - * ============================ THE NUMERICS ARE THE REFERENCE DEFINITION ============================ + * The numerics are the reference definition. rad-kbench compares each resolved kernel against + * this plugin to a tolerance, so these rules are part of the contract: * - * rad-kbench compares a resolved kernel against this plugin to a tolerance, so what this plugin - * computes is not "one correct answer" -- it is THE answer, and every rule below is part of the - * contract rather than an implementation detail: + * * Every accumulation is f32. Not double: device kernels accumulate in f32, and an oracle more + * accurate than what it certifies makes a tolerance ambiguous. Not the operand dtype either: a + * bf16 accumulator would be worse than every kernel it judges. The exceptions sum in double + * and are part of their op's definition (docs/OPS.md): + * - seg_mean's segment sums, which OPS.md states; + * - gram_accum's Gram matrix, a calibration statistic read once at convert time; + * - logit_rerank's dot products, an exact rescoring of a coarse head's candidates; + * - sample_logprobs' normaliser, the sum of exp over the whole vocabulary; + * - givens_dense_quant's dense rotation and ple_gate's key-query dot; + * - the sums of squares of hc_read's, mtp_enter's, ple_gate's and qsa_block_key's norms. An + * f32 sum of n squares differs by at most about n * 2^-24 relative, which at these widths + * (n <= 10240) stays below one bf16 rounding of the normed value. + * * IEEE round-to-nearest-even everywhere, including the f32 -> bf16 / f16 / fp8 rounders. The + * target has no bf16 convert instruction, so software RTNE is the right reference. + * * No fused multiply-add and no reassociation: `a*b + c` rounds twice. A contracting reference + * disagrees with itself across compilers. libref/CMakeLists.txt passes -ffp-contract=off. + * * Summation order is fixed and independent of thread count. OpenMP parallelism is only over + * whole output elements (a row, a column block, a head), with no `reduction()` clause anywhere, + * so runs at different thread counts are bit-identical. * - * * EVERY accumulation is f32. Not double, because a device kernel accumulates in f32 and an - * oracle that is more accurate than the thing it certifies turns a tolerance into a guess - * about which of the two is drifting. Not the operand dtype either: a bf16 accumulator would - * make the reference worse than every kernel it judges. - * * IEEE round-to-nearest-even everywhere, including the hand-written f32 -> bf16 / f16 / fp8 - * rounders below. There is no bf16 convert instruction anywhere on this project's target, so - * a software RTNE is the right reference and not a workaround. - * * NO FUSED MULTIPLY-ADD AND NO REASSOCIATION. `a*b + c` must round twice. A reference that - * contracts is a reference that disagrees with itself between two compilers, and one that - * reassociates cannot be trusted to a tolerance at all. The pragma below asks the compiler for - * this and libref/CMakeLists.txt passes -ffp-contract=off, because the pragma is advisory - * in C++ and the flag is not. - * * SUMMATION ORDER IS FIXED AND INDEPENDENT OF THREAD COUNT. OpenMP parallelism in this plugin - * is only ever over whole output elements -- one thread owns a row, a column block, a head -- - * and there is not one `reduction()` clause in the plugin. Two runs at different thread counts - * are bit-identical, which is what makes a diff against a device kernel mean something. + * This plugin is deliberately simple: scalar loops with a per-element dtype switch outside the few + * hot paths (the GEMM tiles, ref_gemm.h, and the delta-net scans, ref_gdn.cpp, which run + * independent output chains side by side without changing any chain). Its jobs are to run an + * unsupported model at reduced speed instead of not at all, and to be what every fast kernel is + * checked against (spec §17). * - * The cost of all of this is stated plainly: this plugin is slow. It is a nest of scalar loops - * with a per-element dtype switch outside the few paths that matter, and it is meant to be. Its - * jobs are to make an unsupported model run at reduced speed instead of not at all, and to be the - * thing every fast kernel is checked against (spec §17). + * An operand of a dtype these conversions cannot read or store is refused at launch + * (ref_registry.cpp), never read as zeros. */ #ifndef RAD_REF_COMMON_H #define RAD_REF_COMMON_H -/* THE CONTRACTION RULE IS A BUILD FLAG, NOT A PRAGMA. `#pragma STDC FP_CONTRACT` is C, and g++ - * ignores it with a warning on every translation unit that includes this header; clang's - * equivalent is spelled differently and is scoped. libref/CMakeLists.txt therefore passes - * -ffp-contract=off on the target, which every compiler this project builds with honours, and the - * top-level build already sets it for device code (docs/OPS.md). If you compile these sources by - * hand, pass it. */ +/* The no-contraction rule is a build flag, not a pragma: `#pragma STDC FP_CONTRACT` is C and g++ + * ignores it with a warning, and clang's equivalent is spelled differently and scoped. The target + * gets -ffp-contract=off from libref/CMakeLists.txt (the top-level build sets it for device code, + * docs/OPS.md). Pass it when compiling these sources by hand. */ #include "rad_abi.h" #include "rad_plugin.h" @@ -52,13 +54,9 @@ namespace ref { /* ================================================================== narrowing conversions * - * ONE DEFINITION, IN rad_plugin.h, and these are the names ref's kernels call it by. - * - * These conversions ARE the reference definition, which is why they belong in the header every - * plugin gets rather than in this file. This plugin's contract is f32 accumulation, IEEE - * round-to-nearest-ties-to-even, no FMA and no reassociation, and a plugin whose bf16 narrowing - * truncates instead of rounding to even cannot reproduce it and therefore cannot be checked - * against it. A convention every implementer has to rediscover is a convention that drifts. */ + * Local names for rad_plugin.h's conversions. They are part of the reference definition, so they + * live in the header every plugin gets: a plugin whose bf16 narrowing truncates instead of rounding + * to even cannot be checked against this one. */ static inline float bf16_to_f32(uint16_t h) { return rad_bf16_to_f32(h); } static inline uint16_t f32_to_bf16(float f) { return rad_f32_to_bf16(f); } static inline float f16_to_f32(uint16_t h) { return rad_f16_to_f32(h); } @@ -68,8 +66,17 @@ static inline uint8_t f32_to_fp8e4m3(float f) { return rad_f32_to_fp8e4m3(f); static inline float fp8e5m2_to_f32(uint8_t b) { return rad_fp8e5m2_to_f32(b); } static inline uint8_t f32_to_fp8e5m2(float f) { return rad_f32_to_fp8e5m2(f); } -/* OCP MXFP4 element (e2m1): sign in bit 3, exponent in 2:1, mantissa in bit 0. Eight magnitudes, - * and no infinity or NaN -- the format has no room for either. */ +/* E4M3 decoded through a table of all 256 codes, filled by fp8e4m3_to_f32 itself: the same + * floats without the decode's branches, which otherwise dominate an fp8 GEMM or KV-cache read. */ +struct Fp8Table { + float v[256]; + Fp8Table() { for (int b = 0; b < 256; ++b) v[b] = fp8e4m3_to_f32((uint8_t)b); } +}; +inline const Fp8Table kFp8Table; +static inline float fp8e4m3_lut(uint8_t b) { return kFp8Table.v[b]; } + +/* OCP MXFP4 element (e2m1): sign in bit 3, exponent in 2:1, mantissa in bit 0. Eight magnitudes; + * no infinity or NaN. */ static inline float mxfp4_elem_to_f32(uint8_t nib) { static const float kMag[8] = { 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f }; float v = kMag[nib & 0x7u]; @@ -83,19 +90,21 @@ static inline float e8m0_to_f32(uint8_t e) { } /* ================================================================== packed weight codes - * The packing conventions are libr4d's, because a .rad file is specific to a kernel set (spec - * §4.2) and ref has to read the same bytes the fast kernel does: + * The canonical planes a container stores (abi/rad_encoding.h): sub-byte codes are a bit stream + * along the row, lowest bits first, and integer codes are two's complement (abi/rad_types.h). + * libref rearranges no plane (its relayouts only join whole planes, ref_planes.h), so it reads + * these bytes as stored; the op oracle compares a device kernel that relayouts a weight at load + * after RadUnrelayoutFn restores this form. * - * RAD_I4 two nibbles per byte, element 2i in the LOW nibble; symmetric two's-complement code, - * value = (n ^ 8) - 8, so 0..15 maps to -8..7. This is what radiance_w4.pack writes and - * what r4d_dequant_w4_bf16's `twos=1` path reads. - * RAD_I2 four codes per byte, element 4i in the LOW two bits; value = (c ^ 2) - 2, the same - * construction one radix down, so 0..3 maps to -2..1. - * RAD_FP4E2M1 two e2m1 nibbles per byte, element 2i low, with one e8m0 scale per 32 elements - * carried in a separate stream (the `b_scale` operand). + * RAD_I4 two nibbles per byte, element 2i in the low nibble; two's-complement code, + * value = (n ^ 8) - 8, so 0..15 maps to -8..7. + * RAD_I2 four codes per byte, element 4i in the low two bits; value = (c ^ 2) - 2, so 0..3 maps + * to -2..1. + * RAD_FP4E2M1 two e2m1 nibbles per byte, element 2i low, with one e8m0 scale per 32 elements in a + * separate stream (the `b_scale` operand). * - * All three return the RAW CODE's value. The group scale is applied by the caller, because only - * the caller knows where the scale stream is. */ + * All three return the raw code's value; the caller applies the group scale, since only it knows + * where the scale stream is. */ static inline float w4_code(const void* p, int64_t i) { uint8_t b = ((const uint8_t*)p)[i >> 1]; uint8_t n = (i & 1) ? (uint8_t)(b >> 4) : (uint8_t)(b & 0xf); @@ -112,29 +121,66 @@ static inline float mxfp4_code(const void* p, int64_t i) { } /* ================================================================== element access - * One switch per element, which is the price of being generic. The GEMM family lifts it out with - * the templated loaders below; nothing else runs often enough to care. */ + * One switch per element, the price of being generic. The GEMM family hoists it with the templated + * loaders below; nothing else runs often enough to matter. */ static inline float ld_dt(uint32_t dt, const void* p, int64_t i) { switch (dt) { case RAD_F32: return ((const float*)p)[i]; case RAD_F16: return f16_to_f32(((const uint16_t*)p)[i]); case RAD_BF16: return bf16_to_f32(((const uint16_t*)p)[i]); - case RAD_F8E4M3: return fp8e4m3_to_f32(((const uint8_t*)p)[i]); + case RAD_F8E4M3: return fp8e4m3_lut(((const uint8_t*)p)[i]); case RAD_F8E5M2: return fp8e5m2_to_f32(((const uint8_t*)p)[i]); case RAD_I8: return (float)((const int8_t*)p)[i]; case RAD_U8: return (float)((const uint8_t*)p)[i]; case RAD_BOOL: return ((const uint8_t*)p)[i] ? 1.0f : 0.0f; case RAD_I16: return (float)((const int16_t*)p)[i]; + case RAD_U16: return (float)((const uint16_t*)p)[i]; case RAD_I32: return (float)((const int32_t*)p)[i]; case RAD_U32: return (float)((const uint32_t*)p)[i]; case RAD_I64: return (float)((const int64_t*)p)[i]; case RAD_I4: return w4_code(p, i); case RAD_I2: return w2_code(p, i); case RAD_FP4E2M1: return mxfp4_code(p, i); + case RAD_E8M0: return e8m0_to_f32(((const uint8_t*)p)[i]); + /* Unreachable through a launch: the registry refuses an operand of any other dtype + * (ref_registry.cpp, ref_check_dtypes). */ default: return 0.0f; } } +/* A packed code's bits `c` (already masked to `bits`) into element `i` of a bit stream, lowest + * bits first. The two atomics touch only this element's bits, so rows written by different threads + * may share a byte. */ +static inline void st_packed(void* p, int64_t i, int bits, unsigned c) { + const int per = 8 / bits; + uint8_t* b = (uint8_t*)p + i / per; + const int sh = (int)(i % per) * bits; + const uint8_t mask = (uint8_t)(((1u << bits) - 1u) << sh); + __atomic_fetch_and(b, (uint8_t)~mask, __ATOMIC_RELAXED); + __atomic_fetch_or(b, (uint8_t)((c << sh) & mask), __ATOMIC_RELAXED); +} + +/* The e2m1 code nearest `v` (ties to the even code), saturating at 6; NaN is +0. */ +static inline unsigned e2m1_code(float v) { + static const float kMag[8] = { 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f }; + if (v != v) return 0u; + const unsigned sign = std::signbit(v) ? 8u : 0u; + const float a = std::fabs(v); + unsigned best = 0; + for (unsigned c = 1; c < 8; ++c) { + const float d = std::fabs(kMag[c] - a), db = std::fabs(kMag[best] - a); + if (d < db || (d == db && (c & 1u) == 0u)) best = c; + } + return sign | best; +} + +/* `v` rounded to nearest even and clamped to [lo, hi]; NaN is 0. */ +static inline float sat_round(float v, float lo, float hi) { + if (v != v) return 0.0f; + const float r = std::nearbyintf(v); + return r < lo ? lo : (r > hi ? hi : r); +} + static inline void st_dt(uint32_t dt, void* p, int64_t i, float v) { switch (dt) { case RAD_F32: ((float*)p)[i] = v; break; @@ -142,25 +188,42 @@ static inline void st_dt(uint32_t dt, void* p, int64_t i, float v) { case RAD_BF16: ((uint16_t*)p)[i] = f32_to_bf16(v); break; case RAD_F8E4M3: ((uint8_t*)p)[i] = f32_to_fp8e4m3(v); break; case RAD_F8E5M2: ((uint8_t*)p)[i] = f32_to_fp8e5m2(v); break; - /* Integer stores round-to-nearest and saturate. A reference that wrapped would turn one - * overflowing activation into a plausible small number, which is the failure this plugin - * exists to catch rather than to commit. */ - case RAD_I8: { float r = std::nearbyintf(v); r = r < -128.f ? -128.f : (r > 127.f ? 127.f : r); - ((int8_t*)p)[i] = (int8_t)r; break; } - case RAD_U8: { float r = std::nearbyintf(v); r = r < 0.f ? 0.f : (r > 255.f ? 255.f : r); - ((uint8_t*)p)[i] = (uint8_t)r; break; } + /* Integer stores round to nearest even, saturate to the type's range and store NaN as 0. + * Wrapping would turn an overflowing activation into a plausible small number, the kind + * of failure this plugin must catch. */ + case RAD_I8: ((int8_t*)p)[i] = (int8_t)sat_round(v, -128.0f, 127.0f); break; + case RAD_U8: ((uint8_t*)p)[i] = (uint8_t)sat_round(v, 0.0f, 255.0f); break; case RAD_BOOL: ((uint8_t*)p)[i] = v != 0.0f ? 1u : 0u; break; - case RAD_I16: { float r = std::nearbyintf(v); r = r < -32768.f ? -32768.f : (r > 32767.f ? 32767.f : r); - ((int16_t*)p)[i] = (int16_t)r; break; } - case RAD_I32: ((int32_t*)p)[i] = (int32_t)std::nearbyintf(v); break; - case RAD_U32: ((uint32_t*)p)[i] = (uint32_t)std::nearbyintf(v); break; - case RAD_I64: ((int64_t*)p)[i] = (int64_t)std::nearbyintf(v); break; - default: break; + case RAD_I16: ((int16_t*)p)[i] = (int16_t)sat_round(v, -32768.0f, 32767.0f); break; + case RAD_U16: ((uint16_t*)p)[i] = (uint16_t)sat_round(v, 0.0f, 65535.0f); break; + /* Bounds that are powers of two, exact in f32: at and past 2^31 (2^32, 2^63) the store + * saturates to the largest value, which f32 cannot hold. */ + case RAD_I32: { + const float r = sat_round(v, -0x1p31f, 0x1p31f); + ((int32_t*)p)[i] = r >= 0x1p31f ? INT32_MAX : (int32_t)r; + break; + } + case RAD_U32: { + const float r = sat_round(v, 0.0f, 0x1p32f); + ((uint32_t*)p)[i] = r >= 0x1p32f ? UINT32_MAX : (uint32_t)r; + break; + } + case RAD_I64: { + const float r = sat_round(v, -0x1p63f, 0x1p63f); + ((int64_t*)p)[i] = r >= 0x1p63f ? INT64_MAX : (int64_t)r; + break; + } + /* Packed codes: the nearest code, saturated, so a code read by ld_dt stores back as + * itself (a gather or scatter of packed rows moves them exactly). */ + case RAD_I4: st_packed(p, i, 4, (unsigned)(int)sat_round(v, -8.0f, 7.0f) & 0xFu); break; + case RAD_I2: st_packed(p, i, 2, (unsigned)(int)sat_round(v, -2.0f, 1.0f) & 0x3u); break; + case RAD_FP4E2M1: st_packed(p, i, 4, e2m1_code(v)); break; + default: break; /* refused at launch, as in ld_dt */ } } -/* Integer reads that must NOT go through f32: a token id, a slot index or a block id above 2^24 - * would come back rounded. Index tensors are read with this and never with ld_dt. */ +/* Integer reads that must not go through f32, where an id above 2^24 (token, slot, block) would + * be rounded. Index tensors are read with this, never with ld_dt. */ static inline int64_t ld_int(uint32_t dt, const void* p, int64_t i) { switch (dt) { case RAD_I32: return (int64_t)((const int32_t*)p)[i]; @@ -188,13 +251,13 @@ static inline void st_int(uint32_t dt, void* p, int64_t i, int64_t v) { } /* ================================================================== templated loaders - * The GEMM family reads one element per FLOP, so the switch above would be most of its cost. These - * let a caller hoist the decision to the top of the op and pay it once. */ + * The GEMM family reads one element per FLOP, so the switch above would dominate its cost. These + * let a caller resolve the dtype once at the top of the op. */ template struct Cvt; template <> struct Cvt { static inline float ld(const void* p, int64_t i) { return ((const float*)p)[i]; } }; template <> struct Cvt { static inline float ld(const void* p, int64_t i) { return f16_to_f32(((const uint16_t*)p)[i]); } }; template <> struct Cvt { static inline float ld(const void* p, int64_t i) { return bf16_to_f32(((const uint16_t*)p)[i]); } }; -template <> struct Cvt { static inline float ld(const void* p, int64_t i) { return fp8e4m3_to_f32(((const uint8_t*)p)[i]); } }; +template <> struct Cvt { static inline float ld(const void* p, int64_t i) { return fp8e4m3_lut(((const uint8_t*)p)[i]); } }; template <> struct Cvt { static inline float ld(const void* p, int64_t i) { return (float)((const int8_t*)p)[i]; } }; template <> struct Cvt { static inline float ld(const void* p, int64_t i) { return (float)((const int32_t*)p)[i]; } }; template <> struct Cvt { static inline float ld(const void* p, int64_t i) { return w4_code(p, i); } }; @@ -203,23 +266,19 @@ template <> struct Cvt { static inline float ld(const void* p, int /* ------------------------------------------------------------------ the ranged key * - * A RANGED PARAMETER NAMES THE BAND AND THE OPERAND NAMES THE CALL, and every kernel below that - * wants a row count asks the operand. + * A ranged parameter names the band; the operand names the call. Every kernel that wants a row + * count reads it from the operand. * - * `M`, `numel` and `q_len` are declared RAD_RANGE by the architectures, and the core freezes the - * band's UPPER BOUND into the geometry a kernel reads -- max_tok, max_seqs, the whole residual - * stream. It is what the selector matched on and what a kernel sizes a persistent buffer from; - * it is not this issue's extent. A decode step presents a few rows of a max_tok buffer, so a - * reference that reads the parameter as the length either REFUSES the call outright or, where the - * buffers are large enough to survive it, walks rows nobody wrote and reports a mismatch against - * a kernel that is right. + * `M`, `numel` and `q_len` are declared RAD_RANGE, and the core freezes the band's upper bound + * (max_tok, max_seqs, the whole residual stream) into the geometry. That is what the selector + * matched and what persistent buffers are sized from, not this issue's extent: a decode step + * presents a few rows of a max_tok buffer. Reading the parameter as the length would refuse the + * call or walk unwritten rows and report a false mismatch. The engine binds every operand with its + * real shape at issue, and libr4d reads the operand too (its all-reduce uses `numel` only to size + * peer scratch at init). * - * libr4d reads the operand for the same reason -- the all-reduce shim takes r4d_numel(x) and uses - * its `numel` parameter only to size the peer scratch at init -- and the engine binds every - * operand with its real shape at issue, which is what makes the operand the honest source. - * - * The parameter is kept as a CEILING where one is stated: a call above the band was resolved - * against constraints it does not satisfy, and that is a caller bug worth refusing. */ + * The parameter stays a ceiling where one is stated: a call above the band was resolved against + * constraints it does not satisfy, a caller bug worth refusing. */ static inline int64_t band_rows(int64_t from_operand, int64_t band) { if (from_operand <= 0) return 0; return (band > 0 && from_operand > band) ? 0 : from_operand; @@ -233,12 +292,9 @@ static inline int64_t numel(const RadTensor* t) { return n; } -static inline bool contig(const RadTensor* t) { return rad_tensor_is_contiguous(t) != 0; } - -/* Element offset of the `lin`-th element in row-major logical order. Contiguous is the norm and - * costs nothing; a strided view -- a slice of a wider projection, which the GDN block hands its - * conv in every real model -- costs a decomposition, and is supported rather than refused because - * "no geometry constraints" has to mean strides too. */ +/* Element offset of the `lin`-th element in row-major logical order. Contiguous costs nothing; a + * strided view (a slice of a wider projection, as the GDN block passes its conv) costs a + * decomposition. Strides are supported because the reference has no geometry constraints. */ static inline int64_t offlin(const RadTensor* t, int64_t lin) { if (t->rank == 0) return lin; int64_t acc = 1; @@ -258,12 +314,12 @@ static inline int64_t offlin(const RadTensor* t, int64_t lin) { return off; } -/* The element offset of logical row `r` when a tensor is read as [rows, cols]: rows is everything - * but the last dimension and cols is the last. This is the shape almost every op here wants. */ +/* Element offset of logical row `r` when a tensor is read as [rows, cols], cols being the last + * dimension and rows everything before it. Most ops here use this view. */ static inline int64_t rowoff(const RadTensor* t, int64_t r, int64_t cols) { if (t->rank >= 2 && t->shape[t->rank - 1] == cols) { /* Walk the leading dimensions with their own strides, so a [T,H,V] tensor read as - * [T*H, V] lands correctly even when H's stride is not V. */ + * [T*H, V] is correct even when H's stride is not V. */ int64_t off = 0; for (int i = (int)t->rank - 2; i >= 0; --i) { int64_t s = t->shape[i]; @@ -283,18 +339,40 @@ static inline int64_t laststride(const RadTensor* t) { static inline float ldt(const RadTensor* t, int64_t off) { return ld_dt(t->dtype, t->data, off); } static inline void stt(const RadTensor* t, int64_t off, float v) { st_dt(t->dtype, t->data, off, v); } +/* `v` rounded through a store and load of dtype `dt`, as an unfused pair rounds the tensor between + * them. Whole-byte dtypes only. */ +static inline float round_dt(uint32_t dt, float v) { + uint64_t buf = 0; + st_dt(dt, &buf, 0, v); + return ld_dt(dt, &buf, 0); +} + +/* Rows of a tensor read as [rows, n]: `n` is a parameter, the row count comes from the operand + * (ref_ops.h). */ +static inline int64_t rows_of(const RadTensor* t, int64_t n) { return n > 0 ? numel(t) / n : 0; } + +/* Entry `i` of a cu_seqlens operand. */ +static inline int64_t cu_at(const RadTensor* cu, int64_t i) { + return ld_int(cu->dtype, cu->data, offlin(cu, i)); +} + +/* The sequence that owns dense row `r`; a linear scan, since there are few. */ +static inline int64_t seq_of(const RadTensor* cu, int64_t n_seq, int64_t r) { + int64_t s = 0; + while (s + 1 < n_seq && cu_at(cu, s + 1) <= r) ++s; + return s; +} + /* ================================================================== parameters * - * p_find FORWARDS to the ABI's own lookup, and the property that makes that safe is that - * rad_args_geti/gets and the rest are `static inline` in the headers: this .so carries its own - * copy and has no undefined symbol from rad_abi.h. That matters because a kernel plugin links only - * the ABI (spec 18) -- a plugin referencing a symbol defined inside the engine would fail to - * dlopen unless the host exported its whole static core dynamically, which is a build coupling - * this side of the boundary must not have. + * p_find forwards to the ABI's lookup. That is safe because the rad_args_* helpers are `static + * inline` in the headers, so this .so has no undefined symbol from rad_abi.h. A kernel plugin links + * only the ABI (spec 18); referencing an engine symbol would break dlopen unless the host exported + * its static core. * - * The getters below stay ref's own, because they are deliberately LAXER than the ABI's: they - * accept a RANGE and a string spelling of an int, since a tool or a test may call a kernel - * directly with no declare in front of it to enforce the type. */ + * The getters are ref's own and deliberately laxer than the ABI's: they accept a RANGE and a string + * spelling of an int, since a tool or test may call a kernel directly with no declare to enforce + * the type. */ static inline const RadParam* p_find(const RadArgs* a, const char* k) { return a ? rad_param_find(a->p, a->n_p, k) : nullptr; } @@ -303,7 +381,7 @@ static inline long long p_int(const RadArgs* a, const char* k, long long dflt) { const RadParam* p = p_find(a, k); if (!p) return dflt; if (p->kind == RAD_P_INT) return p->ival; - if (p->kind == RAD_P_RANGE) return p->ihi; /* see p_range_note below */ + if (p->kind == RAD_P_RANGE) return p->ihi; /* the band's ceiling; see band_rows */ if (p->kind == RAD_P_STR && p->sval) return std::strtoll(p->sval, nullptr, 10); return dflt; } @@ -315,10 +393,9 @@ static inline const char* p_str(const RadArgs* a, const char* k, const char* dfl return dflt; } -/* A real-valued parameter. These are RAD_P_F64 in the schema (docs/OPS.md), and the core refuses - * any other spelling for a float key at declare -- so `dval` is what arrives. The other kinds are - * still read here because a tool or a test may call a kernel directly, with no declare in front of - * it to enforce the type, and failing such a caller over a spelling would tell it nothing useful. */ +/* A real-valued parameter. The schema types these RAD_P_F64 (docs/OPS.md) and declare refuses any + * other spelling, so `dval` is what normally arrives. Other kinds are still accepted for direct + * callers (tools, tests) with no declare in front. */ static inline float p_f32(const RadArgs* a, const char* k, float dflt) { const RadParam* p = p_find(a, k); if (!p) return dflt; @@ -329,8 +406,8 @@ static inline float p_f32(const RadArgs* a, const char* k, float dflt) { return dflt; } -/* An enumerated parameter that a caller may spell either way: act="silu" or act=0. Names win; - * the integer form is libr4d's ordering. */ +/* An enumerated parameter spelled either way, act="silu" or act=0. Names win; the integer form + * follows libr4d's ordering. An unknown name is -1, for the caller to refuse. */ static inline int p_enum(const RadArgs* a, const char* k, const char* const* names, int n, int dflt) { const RadParam* p = p_find(a, k); @@ -338,35 +415,50 @@ static inline int p_enum(const RadArgs* a, const char* k, const char* const* nam if (p->kind == RAD_P_STR && p->sval) { for (int i = 0; i < n; ++i) if (names[i] && std::strcmp(names[i], p->sval) == 0) return i; - return dflt; + return -1; } if (p->kind == RAD_P_INT) return (int)p->ival; return dflt; } /* ================================================================== operand checks */ -/* Errors are values (docs/IMPLEMENTATION.md). Nothing in this plugin throws, and nothing that did - * not do the work returns RAD_OK. */ +/* Errors are values (docs/IMPLEMENTATION.md): nothing here throws, and nothing returns RAD_OK + * without doing the work. */ #define RAD_REF_TRY(expr) do { int _s = (expr); if (_s < 0) return _s; } while (0) static inline const RadTensor* t_in(const RadArgs* a, int i) { return rad_arg_in(a, i); } static inline bool have(const RadArgs* a, int n) { return rad_args_have(a, n) != 0; } +/* ================================================================== parallel loops + * OpenMP over whole outputs, with an if() clause: a loop with fewer than REF_PAR_MIN units of + * work (a unit is about one multiply-add or element access) runs on the calling thread, so a + * small op does not wake a thread team. Which thread computes an output never changes its value. + * + * REF_PAR_FOR(work) a parallel for, static schedule (REF_PAR_FOR_DYN: dynamic) + * REF_PAR_REGION(work) a parallel region, for a loop that wants per-thread setup (ws_get) + * REF_FOR / REF_FOR_DYN the for inside such a region, static or dynamic schedule */ +#define REF_PRAGMA(x) _Pragma(#x) +#define REF_PAR_MIN ((int64_t)1 << 16) +#define REF_PAR_FOR(work) \ + REF_PRAGMA(omp parallel for schedule(static) if((int64_t)(work) >= REF_PAR_MIN)) +#define REF_PAR_FOR_DYN(work) \ + REF_PRAGMA(omp parallel for schedule(dynamic) if((int64_t)(work) >= REF_PAR_MIN)) +#define REF_PAR_REGION(work) REF_PRAGMA(omp parallel if((int64_t)(work) >= REF_PAR_MIN)) +#define REF_FOR REF_PRAGMA(omp for schedule(static)) +#define REF_FOR_DYN REF_PRAGMA(omp for schedule(dynamic)) + /* ================================================================== per-thread workspace - * The gated-delta-net ops carry state that is too big for a stack frame -- a [128,128] fp32 - * recurrent state alone is 64 KB, and the chunked scan wants three more matrices beside it. The - * fast kernel keeps all of that in WMMA accumulators; the reference cannot, so it needs somewhere - * to put it. + * The gated-delta-net ops carry state too big for a stack frame: a [128,128] fp32 recurrent state + * is 64 KB, and the chunked scan needs three more matrices. The fast kernel keeps that in WMMA + * accumulators; the reference needs memory. * - * A per-thread vector that GROWS ONCE and is then reused. This is the one place in the plugin that - * allocates, and it is worth naming why it is allowed to: the engine's no-allocation rule is about - * the arena and the step path (docs/IMPLEMENTATION.md), and this allocates on the first launch of - * a shape and never again -- there is no per-step malloc. The honest alternative is a scratch hook, - * and it does not work here: scratch is sized at declare from the geometry, and the amount this - * needs depends on the OpenMP thread count, which declare does not know. + * A per-thread vector that grows once and is then reused, so it allocates only on a shape's first + * launch. A scratch hook cannot replace it: scratch is sized at declare, but this depends on the + * OpenMP thread count, which declare does not know. (This plugin is not the step path the engine's + * no-allocation rule covers, docs/IMPLEMENTATION.md; other ops allocate small per-row vectors.) * - * ONE CALL PER LAUNCH. A second call may reallocate and invalidate the first pointer, so every op - * below asks for its whole workspace at once and carves it up itself. */ + * One call per launch: a second call may reallocate and invalidate the first pointer, so each op + * requests its whole workspace at once and carves it up. */ inline float* ws_get(size_t n_floats) { static thread_local std::vector v; if (v.size() < n_floats) v.resize(n_floats); @@ -374,15 +466,12 @@ inline float* ws_get(size_t n_floats) { } /* ================================================================== exact top-k - * One step of an exact selection over a row, descending by value and, ON A TIE, by the LOWER - * index. That tie rule is libr4d's (r4d_rowtopk_bf16: "descending, ties to the lower column") and - * it has to be stated rather than left to a sort's stability, because a router that breaks ties - * differently from the kernel it is checked against routes a token to a different expert and the - * diff is a whole layer wide. + * One step of an exact selection over a row: descending by value, ties to the lower index. That is + * libr4d's rule (r4d_rowtopk_bf16) and it must be explicit, not left to sort stability: a router + * that breaks ties differently sends a token to a different expert and the whole layer diverges. * - * `pv`/`pi` carry the previously selected (value, index); seed them with +infinity and -1. The - * cost is O(N) per selected element, i.e. O(N*R) for the whole row -- the straightforward - * definition, and the one that needs no scratch buffer to be exact. */ + * `pv`/`pi` carry the previous pick (value, index); seed them with +infinity and -1. O(N) per + * selected element, O(N*R) per row, with no scratch buffer. */ static inline bool topk_next(const RadTensor* x, int64_t base, int64_t st, int64_t N, float* pv, int64_t* pi) { float best_v = 0.0f; @@ -400,61 +489,99 @@ static inline bool topk_next(const RadTensor* x, int64_t base, int64_t st, int64 } /* ================================================================== small maths - * Written out rather than taken from 's fast paths, because the reference's exp is the one - * every softmax and every gate is checked against. std::expf is correctly rounded to well under a - * ULP on glibc, which is the accuracy an oracle wants; a device kernel's __expf is not, and the - * gap is what rad-kbench's tolerance is for. */ -static inline float ref_exp(float x) { return std::exp(x); } -/* Used by locally-typical sampling, which is a threshold on |surprisal - entropy| and therefore - * needs both. Same reasoning as ref_exp: the oracle takes the correctly-rounded libm. */ -static inline float ref_log(float x) { return std::log(x); } -static inline float ref_abs(float x) { return std::fabs(x); } -static inline float act_sigmoid(float x) { return 1.0f / (1.0f + std::exp(-x)); } + * Every transcendental is evaluated in double and rounded once to float. glibc's float routines + * are not the same function from one release to the next (2.41 made log1pf, tanhf, erff and + * others correctly rounded), so a float call answers differently on two hosts and an oracle held + * to its recordings exactly would fail on the one that did not record them. The double routines + * have been stable for many releases and are accurate to well under a ULP of double, so the + * rounded float is the same everywhere but for a double-rounding tie. A device kernel's __expf is + * further off; rad-kbench's tolerance covers that gap. */ +static inline float ref_exp(float x) { return (float)std::exp((double)x); } +static inline float ref_log(float x) { return (float)std::log((double)x); } +static inline float ref_log1p(float x) { return (float)std::log1p((double)x); } +static inline float ref_erf(float x) { return (float)std::erf((double)x); } +static inline float ref_tanh(float x) { return (float)std::tanh((double)x); } +static inline float ref_sin(float x) { return (float)std::sin((double)x); } +static inline float ref_cos(float x) { return (float)std::cos((double)x); } +static inline float ref_pow(float b, float e) { return (float)std::pow((double)b, (double)e); } +static inline float ref_abs(float x) { return std::fabs(x); } +static inline float act_sigmoid(float x) { return 1.0f / (1.0f + ref_exp(-x)); } static inline float act_silu(float x) { return x * act_sigmoid(x); } -/* The exact erf-based GELU, not tanh. A model trained with the tanh approximation should ask for - * it by name rather than have the reference guess; until an op says so, "gelu" is the real one. */ +/* The exact erf-based GELU. "gelu" means this; the tanh approximation must be requested by name. */ static inline float act_gelu(float x) { - return 0.5f * x * (1.0f + std::erf(x * 0.70710678118654752f)); + return 0.5f * x * (1.0f + ref_erf(x * 0.70710678118654752f)); } -/* The tanh approximation (PyTorch's gelu_tanh / gemma's gelu_pytorch_tanh) -- the form gated - * feed-forwards are trained with. The constants are the standard fit and are the same two the - * gemm_nt_bias "gelu_tanh" epilogue uses (ref_gemm.cpp), which is a GEMM-local copy of this same - * formula; both compute the identical function, so a GELU-gated FFN and a tanh-gelu epilogue agree - * to the last bit. Kept here rather than `#include`d into ref_gemm.cpp so the elementwise header - * stays self-contained. */ +/* The tanh approximation (PyTorch's gelu_tanh, Gemma's gelu_pytorch_tanh), which gated + * feed-forwards are trained with. */ static inline float act_gelu_tanh(float x) { const float k0 = 0.7978845608028654f, k1 = 0.044715f; - return 0.5f * x * (1.0f + std::tanh(k0 * (x + k1 * x * x * x))); + return 0.5f * x * (1.0f + ref_tanh(k0 * (x + k1 * x * x * x))); } -/* softplus in the two-sided form, with the large-x cutoff FLA and libr4d both use: above the - * threshold log1p(e^x) IS x to every bit f32 holds, and evaluating it costs an overflow. */ +/* softplus in the two-sided form, with FLA's and libr4d's large-x cutoff: above the threshold + * log1p(e^x) equals x in f32, and evaluating it would overflow. */ static inline float act_softplus(float x, float thr) { if (x > thr) return x; - return x > 0.0f ? x + std::log1p(std::exp(-x)) : std::log1p(std::exp(x)); + return x > 0.0f ? x + ref_log1p(ref_exp(-x)) : ref_log1p(ref_exp(x)); } /* ================================================================== the Hadamard rotation - * The widest rotation this reference performs in one stack frame. libr4d caps `had` at 512 -- a - * power of two dividing the per-rank K, and 8704 admits no more -- so 4096 is four doublings of - * headroom. A wider request returns RAD_E_UNSUPPORTED by name rather than silently rotating a - * narrower block, because a half-applied rotation is numerically plausible and completely wrong. */ + * The widest rotation this reference performs in one stack frame. libr4d caps `had` at 512 (a + * power of two dividing the per-rank K; 8704 admits no more), so 4096 leaves headroom. A wider + * request returns RAD_E_UNSUPPORTED rather than rotating a narrower block, since a half-applied + * rotation looks plausible and is wrong. */ enum { REF_HAD_MAX = 4096 }; /* The unnormalised in-place transform over `g` values, g a power of two. */ static inline void fwht(float* v, int64_t g) { for (int64_t h = 1; h < g; h <<= 1) - for (int64_t i = 0; i < g; ++i) - if ((i & h) == 0) { - const float a = v[i], b = v[i + h]; - v[i] = a + b; - v[i + h] = a - b; + for (int64_t i = 0; i < g; i += 2 * h) + for (int64_t j = i; j < i + h; ++j) { + const float a = v[j], b = v[j + h]; + v[j] = a + b; + v[j + h] = a - b; } } static inline bool pow2(int64_t v) { return v > 0 && (v & (v - 1)) == 0; } +/* ================================================================== the 8-bit group + * One group of the block-scaled 8-bit quantisers (constants explained at ref_quant.cpp's + * quant_act_fp8): `v(i)` for i < n is the group's values and `top` the largest code, 448 for E4M3 + * and 127 for int8. The codes clamp(v(i) / scale, +-top) go to q[qb + i * qs] in q's dtype (int8 + * rounded to nearest even), and the scale amax / top (1 for an all-zero group) is returned. */ +template +static inline float q8_group(const V& v, int64_t n, float top, const RadTensor* q, int64_t qb, + int64_t qs) { + float amax = 0.0f; + for (int64_t i = 0; i < n; ++i) { const float m = std::fabs(v(i)); if (m > amax) amax = m; } + const float sc = amax > 0.0f ? amax * (1.0f / top) : 1.0f; + const float inv = 1.0f / sc; + for (int64_t i = 0; i < n; ++i) { + float c = v(i) * inv; + if (c > top) c = top; + if (c < -top) c = -top; + st_dt(q->dtype, q->data, qb + i * qs, c); + } + return sc; +} + +/* ================================================================== the int8 step order + * quant_act_i8 stores a row's codes in the order libr4d's int8 WMMA reads an A fragment: within + * each sixteen-byte step the middle two dwords are exchanged, so column c sits at byte + * i8_step_pos(c) (bits 2 and 3 of c swapped). The map is its own inverse. gemm_nt_q reads its + * activation in this order at the dtypes i8_steps_dtype names. */ +static inline int64_t i8_step_pos(int64_t c) { + return (c & ~(int64_t)12) | ((c & 4) << 1) | ((c & 8) >> 1); +} +static inline bool i8_steps_dtype(const char* dt) { + static const char* const kDtypes[] = { "w4a8", "w4a8_asym", "w8a8", "w2a8" }; + for (const char* d : kDtypes) + if (dt && std::strcmp(dt, d) == 0) return true; + return false; +} + } /* namespace ref */ #endif /* RAD_REF_COMMON_H */ diff --git a/libref/ref_elementwise.cpp b/libref/ref_elementwise.cpp index 37bb1f0c..c88b5240 100644 --- a/libref/ref_elementwise.cpp +++ b/libref/ref_elementwise.cpp @@ -1,9 +1,8 @@ /* ref_elementwise.cpp -- the norms and the elementwise ops. * - * Nothing here is interesting except where the fused forms round, and those places are the whole - * reason the ops exist: `rmsnorm_add` is one pass in every real implementation, so the reference - * has to say exactly which of its two intermediates is rounded and which is not, or a fused kernel - * checked against it fails on a tolerance nobody can explain. + * The subtle part is where fused forms round: `rmsnorm_add` is one pass in every real + * implementation, so the reference must state which intermediates are rounded, or a correct fused + * kernel fails its tolerance. */ #include "ref_common.h" #include "ref_ops.h" @@ -13,37 +12,20 @@ using namespace ref; -/* Rows of a tensor read as [rows, n]. `n` is a declared parameter and the row count is whatever - * the operand actually carries, which is the rule this plugin follows everywhere (ref_ops.h). */ -static inline int64_t rows_of(const RadTensor* t, int64_t n) { - return n > 0 ? numel(t) / n : 0; -} - /* ------------------------------------------------------------------ rmsnorm */ /* y = x * rsqrt(mean(x^2) + eps) * (w + w_add) * - * The mean is over the LAST n elements of a row and is accumulated in f32 in ascending index - * order. `w_add` is GemmaRMSNorm's `1 +`: Qwen3.5, Qwen3-Next and Gemma store a zero-centred gain - * and use 1 + w, and forming that in the weight's dtype first loses 0.3% per channel (libr4d's - * r4d_rmsnorm_had_quant_i8 says the same). It defaults to 0, so a plain RMS norm is the plain - * call. */ -int ref_rmsnorm(const RadArgs* a, RadStream) { - if (!a || a->n_t < 3 || !a->t[0].data || !a->t[2].data) return RAD_E_INVAL; - const RadTensor *x = &a->t[0], *y = &a->t[2]; - /* An absent gain is one, and `wadd` belongs to a gain, so it is refused without one. */ - const RadTensor* w = a->t[1].data ? &a->t[1] : nullptr; - const int64_t n = p_int(a, "n", w && w->rank ? w->shape[w->rank - 1] : 0); - const float eps = p_f32(a, "eps", 1e-6f); - const float wadd = p_f32(a, "wadd", 0.0f); - /* `mult` scales the normed row before its one rounding: a residual branch weighted by a - * constant (Gemma 4's audio feed-forward, a half) without a second pass over the row. */ - const float mult = p_f32(a, "mult", 1.0f); + * The mean is over the last n elements of a row, accumulated in f32 in ascending index order. + * `w_add` is GemmaRMSNorm's `1 +`: Qwen3.5, Qwen3-Next and Gemma store a zero-centred gain and use + * 1 + w, and forming that in the weight's dtype first loses 0.3% per channel. Default 0. An absent + * gain `w` is 1. */ +static int rms_rows(const RadTensor* x, const RadTensor* w, const RadTensor* y, int64_t n, + float eps, float wadd, float mult) { if (n <= 0) return RAD_E_SHAPE; - if (!w && wadd != 0.0f) return RAD_E_INVAL; const int64_t rows = rows_of(x, n); if (rows <= 0 || numel(y) < rows * n || (w && numel(w) < n)) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { const int64_t xb = rowoff(x, r, n), yb = rowoff(y, r, n); const int64_t xs = laststride(x), ys = laststride(y), ws = w ? laststride(w) : 0; @@ -57,46 +39,35 @@ int ref_rmsnorm(const RadArgs* a, RadStream) { return RAD_OK; } +int ref_rmsnorm(const RadArgs* a, RadStream) { + if (!a || a->n_t < 3 || !a->t[0].data || !a->t[2].data) return RAD_E_INVAL; + const RadTensor* w = a->t[1].data ? &a->t[1] : nullptr; + const float wadd = p_f32(a, "wadd", 0.0f); + /* `wadd` without a gain is refused. */ + if (!w && wadd != 0.0f) return RAD_E_INVAL; + /* `mult` scales the normed row before its single rounding, for a residual branch weighted by + * a constant (Gemma 4's audio feed-forward uses 0.5). */ + return rms_rows(&a->t[0], w, &a->t[2], p_int(a, "n", w && w->rank ? w->shape[w->rank - 1] : 0), + p_f32(a, "eps", 1e-6f), wadd, p_f32(a, "mult", 1.0f)); +} + /* ------------------------------------------------------------------ rmsnorm_p */ -/* y = x * rsqrt(mean(x^2) + eps) -- the SAME normalisation as rmsnorm with NO gain at all. It is - * its own op rather than a zeroed gain on rmsnorm because the gain is a real, weightless thing: - * Gemma's attention normalises the VALUE with a bare RMS (llama.cpp's ggml_rms_norm(V, eps), no - * tensor) while normalising the KEY with the k_norm gain, and there is no checkpoint plane to feed - * a `wadd`/`w` through for the value -- so an rmsnorm call would need a phantom all-zero weight to - * express it, which is a name map to a tensor that does not exist. The mean is accumulated in f32 - * in ascending index order, exactly as rmsnorm does, so the two agree bit-for-bit where rmsnorm's - * gain happens to be one. */ +/* y = x * rsqrt(mean(x^2) + eps): rmsnorm with no gain. A separate op because Gemma normalises the + * value with a bare RMS (llama.cpp's ggml_rms_norm(V, eps)) and the checkpoint has no plane for a + * gain; rmsnorm would need a phantom weight. */ int ref_rmsnorm_p(const RadArgs* a, RadStream) { if (!have(a, 2)) return RAD_E_INVAL; - const RadTensor *x = &a->t[0], *y = &a->t[1]; - const int64_t n = p_int(a, "n", 0); - const float eps = p_f32(a, "eps", 1e-6f); - if (n <= 0) return RAD_E_SHAPE; - const int64_t rows = rows_of(x, n); - if (rows <= 0 || numel(y) < rows * n) return RAD_E_SHAPE; - - #pragma omp parallel for schedule(static) - for (int64_t r = 0; r < rows; ++r) { - const int64_t xb = rowoff(x, r, n), yb = rowoff(y, r, n); - const int64_t xs = laststride(x), ys = laststride(y); - float ss = 0.0f; - for (int64_t i = 0; i < n; ++i) { float v = ldt(x, xb + i * xs); ss += v * v; } - const float s = 1.0f / std::sqrt(ss / (float)n + eps); - for (int64_t i = 0; i < n; ++i) - stt(y, yb + i * ys, ldt(x, xb + i * xs) * s); - } - return RAD_OK; + return rms_rows(&a->t[0], nullptr, &a->t[1], p_int(a, "n", 0), p_f32(a, "eps", 1e-6f), 0.0f, + 1.0f); } /* ------------------------------------------------------------------ rmsnorm_add */ /* residual_out = x + residual; y = rmsnorm(residual_out) * (w + w_add) * - * THE ROUNDING IS THE CONTRACT. The sum is formed in f32 and the variance is taken from the - * UNROUNDED sum, but the multiply that produces y reads the sum back from residual_out AFTER it - * has been narrowed to that operand's dtype. That is what vLLM's fused_add_rms_norm does and what - * every fused kernel in this project will do, because the residual has to be stored anyway and - * re-reading it is free. A reference that kept f32 all the way through would be half a ULP better - * and would disagree with every kernel it certifies. + * The rounding is the contract: the variance comes from the unrounded f32 sum, but y reads the sum + * back from residual_out after it is narrowed to that dtype. vLLM's fused_add_rms_norm and every + * fused kernel here do the same, since the residual is stored anyway. Keeping f32 throughout would + * be half a ULP better and disagree with every kernel. */ int ref_rmsnorm_add(const RadArgs* a, RadStream) { if (!have(a, 5)) return RAD_E_INVAL; @@ -109,7 +80,7 @@ int ref_rmsnorm_add(const RadArgs* a, RadStream) { if (rows <= 0 || numel(y) < rows * n || numel(ro) < rows * n || numel(res) < rows * n || numel(w) < n) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { const int64_t xb = rowoff(x, r, n), rb = rowoff(res, r, n); const int64_t yb = rowoff(y, r, n), ob = rowoff(ro, r, n); @@ -129,9 +100,8 @@ int ref_rmsnorm_add(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------------ layernorm */ -/* y = (x - mean) * rsqrt(var + eps) * w + b, with the BIASED variance (divide by n, not n-1), - * which is what every transformer implementation means by layer norm. `b` is optional: a ViT that - * dropped its bias passes a null operand rather than a zero tensor. */ +/* y = (x - mean) * rsqrt(var + eps) * w + b, with the biased variance (divide by n, not n-1), as + * transformers use. `b` is optional: a bias-free ViT passes a null operand. */ int ref_layernorm(const RadArgs* a, RadStream) { if (a->n_t < 4 || !a->t[0].data || !a->t[1].data || !a->t[3].data) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *w = &a->t[1], *y = &a->t[3]; @@ -143,7 +113,7 @@ int ref_layernorm(const RadArgs* a, RadStream) { if (rows <= 0 || numel(y) < rows * n || numel(w) < n) return RAD_E_SHAPE; if (b && numel(b) < n) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { const int64_t xb = rowoff(x, r, n), yb = rowoff(y, r, n); const int64_t xs = laststride(x), ys = laststride(y), ws = laststride(w); @@ -163,19 +133,14 @@ int ref_layernorm(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------------ grid_embed */ -/* A learned side x side table of position rows, resampled to a grid of its own size per row of x - * and added in: the vision tower's position embedding, which is trained at one grid and applied to - * images of any shape. +/* A learned side x side table of position rows, resampled per row of x to that row's grid size and + * added in: the vision tower's position embedding, trained at one grid and applied to any image + * shape. * - * THE SAMPLING IS BILINEAR WITH THE CORNERS ALIGNED: grid row r of a grid of height g sits at table - * coordinate r * (side - 1) / max(g - 1, 1), in f32, and its two taps are the floor and the floor - * plus one, clamped to the table, weighted by distance. The four products are summed in f32 in the - * order (top-left, top-right, bottom-left, bottom-right) and rounded to x's dtype -- the position - * embedding as a tensor of its own -- and only then added to x, which is rounded again. */ -static float round_to(uint32_t dt, float v) { - return dt == RAD_BF16 ? rad_bf16_to_f32(rad_f32_to_bf16(v)) : v; -} - + * Bilinear with corners aligned: grid row r of height g sits at table coordinate + * r * (side - 1) / max(g - 1, 1) in f32, with taps at floor and floor + 1, clamped and weighted by + * distance. The four products are summed in f32 in the order (top-left, top-right, bottom-left, + * bottom-right), rounded to x's dtype as a tensor of its own, then added to x and rounded again. */ int ref_grid_embed(const RadArgs* a, RadStream) { if (!have(a, 3)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *tab = &a->t[1], *crd = &a->t[2]; @@ -188,7 +153,7 @@ int ref_grid_embed(const RadArgs* a, RadStream) { const int64_t cs = crd->stride[0], ms = crd->stride[1]; const int64_t ts = laststride(tab); - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * n * 4) for (int64_t r = 0; r < rows; ++r) { const int64_t gr = ld_int(crd->dtype, crd->data, 0 * cs + r * ms); const int64_t gc = ld_int(crd->dtype, crd->data, 1 * cs + r * ms); @@ -215,7 +180,7 @@ int ref_grid_embed(const RadArgs* a, RadStream) { for (int kj = 0; kj < 2; ++kj) acc += ldt(tab, rowoff(tab, th[ki] * side + tw[kj], n) + i * ts) * (wh[ki] * ww[kj]); - const float pe = round_to(x->dtype, acc); + const float pe = round_dt(x->dtype, acc); stt(x, xb + i * xs, ldt(x, xb + i * xs) + pe); } } @@ -223,10 +188,9 @@ int ref_grid_embed(const RadArgs* a, RadStream) { } /* grid_embed_aa: the table resampled as torch's F.interpolate(mode="bilinear", align_corners=False, - * antialias=True) does it -- SigLIP2's position embedding. Per axis a triangle filter on half-pixel - * centres, widened by the scale when shrinking, its taps inside the table normalised to sum to one. - * Separable, f32 throughout, rounded once before the add. A coordinate outside its grid is clamped - * into it, so every input is defined. */ + * antialias=True), SigLIP2's position embedding. Per axis, a triangle filter on half-pixel centres, + * widened by the scale when shrinking, with in-table taps normalised to sum to one. Separable, f32 + * throughout, rounded once before the add. Out-of-grid coordinates are clamped. */ static void aa_taps(int64_t at, int64_t size, int64_t side, float* w, int64_t* lo, int64_t* cnt) { if (size < 1) size = 1; at = at < 0 ? 0 : (at >= size ? size - 1 : at); @@ -259,7 +223,7 @@ int ref_grid_embed_aa(const RadArgs* a, RadStream) { const int64_t cs = crd->stride[0], ms = crd->stride[1]; const int64_t ts = laststride(tab); - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * n * 16) for (int64_t r = 0; r < rows; ++r) { int64_t g[4]; for (int c = 0; c < 4; ++c) g[c] = ld_int(crd->dtype, crd->data, c * cs + r * ms); @@ -277,7 +241,7 @@ int ref_grid_embed_aa(const RadArgs* a, RadStream) { ww[(size_t)c]; acc += row * wh[(size_t)y]; } - const float pe = round_to(x->dtype, acc); + const float pe = round_dt(x->dtype, acc); stt(x, xb + i * xs, ldt(x, xb + i * xs) + pe); } } @@ -285,10 +249,9 @@ int ref_grid_embed_aa(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------------ add / mul */ -/* Elementwise over the output's extent. `b` may carry one row instead of all of them, so a bias - * add is this op rather than a second one: an operand with exactly `n` elements against an output - * of rows*n broadcasts along rows, and nothing else broadcasts at all. Silent broadcasting of an - * arbitrary shape is how a shape bug becomes a plausible number. */ +/* Elementwise over the output's extent. `b` may be a single row of exactly `n` elements, which + * broadcasts along rows (a bias add); nothing else broadcasts, so a shape bug cannot pass as a + * plausible number. */ static int elementwise2(const RadArgs* a, bool mul) { if (!have(a, 3)) return RAD_E_INVAL; const RadTensor *A = &a->t[0], *B = &a->t[1], *Y = &a->t[2]; @@ -299,7 +262,7 @@ static int elementwise2(const RadArgs* a, bool mul) { const bool bcast = numel(B) == n && rows > 1; if (!bcast && numel(B) < rows * n) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { const int64_t ab = rowoff(A, r, n), yb = rowoff(Y, r, n); const int64_t bb = bcast ? 0 : rowoff(B, r, n); @@ -316,11 +279,10 @@ int ref_add(const RadArgs* a, RadStream) { return elementwise2(a, false); } int ref_mul(const RadArgs* a, RadStream) { return elementwise2(a, true); } /* ------------------------------------------------------------------ mul_weight */ -/* y = x * w, `w` a WEIGHT of one element or of one row: a learned gain on an activation -- a - * per-layer scalar on the residual stream (Gemma 4's layer_scalar), or a per-channel one (a - * vision tower's layer scale). Its own op and not a form of `mul` because an op's operand is a - * weight or an activation by its schema, and `mul`'s `b` is an activation. The product is f32, - * rounded once to y's dtype. */ +/* y = x * w, `w` a weight of one element or one row: a learned gain such as a per-layer residual + * scalar (Gemma 4's layer_scalar) or a per-channel layer scale (vision towers). Separate from `mul` + * because the schema fixes whether an operand is a weight or an activation, and `mul`'s `b` is an + * activation. The f32 product is rounded once to y's dtype. */ int ref_mul_weight(const RadArgs* a, RadStream) { if (!have(a, 3)) return RAD_E_INVAL; const RadTensor *X = &a->t[0], *W = &a->t[1], *Y = &a->t[2]; @@ -332,7 +294,7 @@ int ref_mul_weight(const RadArgs* a, RadStream) { if (!scalar && numel(W) != n) return RAD_E_SHAPE; const int64_t ws = scalar ? 0 : laststride(W); - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { const int64_t xb = rowoff(X, r, n), yb = rowoff(Y, r, n); const int64_t xs = laststride(X), ys = laststride(Y); @@ -343,26 +305,19 @@ int ref_mul_weight(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------------ scale_rows */ -/* y[m, i] = x[m, i] * act(s[m]) -- one scalar per ROW, broadcast across the row. +/* y[m, i] = x[m, i] * act(s[m]): one scalar per row, broadcast across it (a per-token gate). + * Separate from `mul`, which broadcasts one row down the rows; one op with both rules would be + * ambiguous when rows == n. * - * IT IS NOT `mul`, AND THE DIFFERENCE IS WHICH AXIS BROADCASTS. `mul` lets `b` carry one ROW and - * broadcasts it down the rows, which is a bias's shape; this carries one COLUMN and broadcasts it - * across them, which is a per-token gate's. Giving `mul` both rules would make them ambiguous - * exactly when rows == n, and a silent choice between two broadcasts is how a shape bug becomes a - * plausible number -- which is the rule the comment above elementwise2 already states. + * The activation applies to the scalar, not the product: Qwen3.5-MoE's shared expert is scaled by + * `sigmoid(shared_expert_gate(x))`. * - * The activation is applied to the SCALAR and not to the product, which is what a gate means: - * Qwen3.5-MoE's shared expert is scaled by `sigmoid(shared_expert_gate(x))`. */ -/* `add` PRESENT IS THE FUSED GATE-AND-ADD FORM: y = narrow(x * act(s)) + add, and the NARROW is - * the whole of why this is expressible as one op rather than an approximation of two. The pair it - * stands in for writes the product into a bf16 buffer and then adds that buffer to `add`, so the - * product is rounded BEFORE the sum sees it; an f32 product carried into the add would differ in - * the last bit of every channel. Written here as the two stores it replaces, through `y` itself, - * because the oracle's job is to be obviously the same rather than to be quick. - * - * `add` is read before `y` is written so the two may alias without the sum reading its own output. */ + * With `add` present it is the fused gate-and-add, y = narrow(x * act(s)) + add. The unfused pair + * stores the product to a bf16 buffer before adding, so the product is rounded first; this writes + * the same two stores through `y`. `add` is read before `y` is written so the two may alias. */ int ref_scale_rows(const RadArgs* a, RadStream) { - if (!have(a, 4)) return RAD_E_INVAL; + /* `add` (operand 2) is optional; the other three are required. */ + if (a->n_t < 4 || !t_in(a, 0) || !t_in(a, 1) || !t_in(a, 3)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *sc = &a->t[1], *y = &a->t[3]; const RadTensor *ad = t_in(a, 2); const int64_t n = p_int(a, "n", numel(y)); @@ -375,7 +330,7 @@ int ref_scale_rows(const RadArgs* a, RadStream) { if (act && std::strcmp(act, "sigmoid") && std::strcmp(act, "none")) return RAD_E_INVAL; const int64_t ss = laststride(sc); - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { const float v0 = ldt(sc, r * ss); const float v = sig ? act_sigmoid(v0) : v0; @@ -393,8 +348,8 @@ int ref_scale_rows(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------------ silu_mul */ -/* y[.., i] = silu(gate_up[.., i]) * gate_up[.., n + i]. The gate is the FIRST half, which is the - * order rad-convert fuses gate and up into one weight in, so the two conventions cannot drift. */ +/* y[.., i] = silu(gate_up[.., i]) * gate_up[.., n + i]. The gate is the first half, the order in + * which rad-convert fuses gate and up. */ int ref_silu_mul(const RadArgs* a, RadStream) { if (!have(a, 2)) return RAD_E_INVAL; const RadTensor *gu = &a->t[0], *y = &a->t[1]; @@ -403,7 +358,7 @@ int ref_silu_mul(const RadArgs* a, RadStream) { const int64_t rows = rows_of(y, n); if (rows <= 0 || numel(gu) < rows * 2 * n) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { const int64_t gb = rowoff(gu, r, 2 * n), yb = rowoff(y, r, n); const int64_t gs = laststride(gu), ys = laststride(y); @@ -414,18 +369,11 @@ int ref_silu_mul(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------------ act_mul */ -/* y = act(a) * b, the gated product with its two halves in two operands. `silu_mul` reads one - * fused gate_up row; this reads the gate and the multiplier from wherever they are, which covers - * a fused gate_up as two column slices of it AND a gate whose multiplier is some other tensor -- - * Gemma's per-layer-input block multiplies gelu(gate(x)) by a per-layer embedding. +/* y = act(a) * b, the gated product with its halves in two operands: two column slices of a fused + * gate_up, or a gate whose multiplier is another tensor (Gemma's per-layer-input block multiplies + * gelu(gate(x)) by a per-layer embedding). * - * THE ACTIVATION IS ROUNDED TO y's DTYPE BEFORE THE PRODUCT, which is what the unfused pair does: - * `act(gate)` is a tensor, and the product reads it back. */ -static float gelu_tanh_f(float x) { - const float k0 = 0.7978845608028654f, k1 = 0.044715f; - return 0.5f * x * (1.0f + std::tanh(k0 * (x + k1 * x * x * x))); -} - + * The activation is rounded to y's dtype before the product, as the unfused pair stores it. */ int ref_act_mul(const RadArgs* a, RadStream) { if (!have(a, 3)) return RAD_E_INVAL; const RadTensor *A = &a->t[0], *B = &a->t[1], *Y = &a->t[2]; @@ -437,38 +385,37 @@ int ref_act_mul(const RadArgs* a, RadStream) { const int act = p_enum(a, "act", kActs, 4, -1); if (act < 0) return RAD_E_INVAL; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { const int64_t ab = rowoff(A, r, n), bb = rowoff(B, r, n), yb = rowoff(Y, r, n); const int64_t as = laststride(A), bs = laststride(B), ys = laststride(Y); for (int64_t i = 0; i < n; ++i) { const float g = ldt(A, ab + i * as); const float v = act == 0 ? act_silu(g) : act == 1 ? act_gelu(g) - : act == 2 ? gelu_tanh_f(g) : act_sigmoid(g); - stt(Y, yb + i * ys, round_to(Y->dtype, v) * ldt(B, bb + i * bs)); + : act == 2 ? act_gelu_tanh(g) : act_sigmoid(g); + stt(Y, yb + i * ys, round_dt(Y->dtype, v) * ldt(B, bb + i * bs)); } } return RAD_OK; } /* ------------------------------------------------------------------ seg_mean */ -/* y[s, :] = the mean of x's rows [cu[s], cu[s+1]): one row a segment, which is a sentence - * embedding's mean pooling over a ragged batch. The sum is taken in DOUBLE and divided once, so the - * pooled row does not depend on how many rows a segment has beyond the one rounding to y's dtype. - * An empty segment writes zeros. */ +/* y[s, :] = mean of x's rows [cu[s], cu[s+1]): sentence-embedding mean pooling over a ragged + * batch. Summed in double and divided once, so only the final rounding to y's dtype depends on the + * segment length. An empty segment writes zeros. */ int ref_seg_mean(const RadArgs* a, RadStream) { if (!have(a, 3)) return RAD_E_INVAL; const RadTensor *X = &a->t[0], *cu = &a->t[1], *Y = &a->t[2]; const int64_t n = p_int(a, "n", 0); const int64_t S = numel(cu) - 1; if (n <= 0 || S <= 0 || numel(Y) < S * n) return RAD_E_SHAPE; - const int64_t total = ld_int(cu->dtype, cu->data, offlin(cu, S)); - if (total < 0 || numel(X) < total * n) return RAD_E_SHAPE; + const int64_t total = cu_at(cu, S); + if (total <= 0 || numel(X) < total * n) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + REF_PAR_FOR((total + S) * n) for (int64_t s = 0; s < S; ++s) { - const int64_t b0 = ld_int(cu->dtype, cu->data, offlin(cu, s)); - const int64_t b1 = ld_int(cu->dtype, cu->data, offlin(cu, s + 1)); + const int64_t b0 = cu_at(cu, s); + const int64_t b1 = cu_at(cu, s + 1); const int64_t yb = rowoff(Y, s, n), ys = laststride(Y), xs = laststride(X); for (int64_t i = 0; i < n; ++i) { double acc = 0.0; @@ -481,8 +428,8 @@ int ref_seg_mean(const RadArgs* a, RadStream) { /* ------------------------------------------------------------------ pool_rows */ /* Row r of y is the mean of x's rows [r*k, r*k + k), summed in f32 and rounded to y's dtype, then - * multiplied by `mult` and rounded again -- the unfused pair, which stores the mean. A vision - * pooler whose processor lays each k-patch window out consecutively pools with this. */ + * multiplied by `mult` and rounded again, as the unfused pair stores the mean. For vision poolers + * whose processor lays each k-patch window out consecutively. */ int ref_pool_rows(const RadArgs* a, RadStream) { if (!have(a, 2)) return RAD_E_INVAL; const RadTensor *X = &a->t[0], *Y = &a->t[1]; @@ -495,7 +442,7 @@ int ref_pool_rows(const RadArgs* a, RadStream) { if (numel(Y) < rows * n) return RAD_E_SHAPE; const float inv = 1.0f / (float)k; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows_in * n) for (int64_t r = 0; r < rows; ++r) { const int64_t yb = rowoff(Y, r, n), ys = laststride(Y), xs = laststride(X); for (int64_t i = 0; i < n; ++i) { @@ -518,7 +465,7 @@ int ref_relu(const RadArgs* a, RadStream) { const int64_t rows = rows_of(Y, n); if (rows <= 0 || numel(X) < rows * n) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { const int64_t xb = rowoff(X, r, n), yb = rowoff(Y, r, n); const int64_t xs = laststride(X), ys = laststride(Y); @@ -531,8 +478,8 @@ int ref_relu(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------------ clamp */ -/* y = min(max(x, lo), hi), the bounds WEIGHTS of one element each: a clipped linear's input or - * output range (Gemma 4's audio tower), which the checkpoint states per projection. */ +/* y = min(max(x, lo), hi), the bounds being one-element weights: a clipped linear's input or output + * range, stated per projection in the checkpoint (Gemma 4's audio tower). */ int ref_clamp(const RadArgs* a, RadStream) { if (!have(a, 4)) return RAD_E_INVAL; const RadTensor *X = &a->t[0], *L = &a->t[1], *H = &a->t[2], *Y = &a->t[3]; @@ -542,7 +489,7 @@ int ref_clamp(const RadArgs* a, RadStream) { if (rows <= 0 || numel(X) < rows * n) return RAD_E_SHAPE; const float lo = ldt(L, 0), hi = ldt(H, 0); - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { const int64_t xb = rowoff(X, r, n), yb = rowoff(Y, r, n); const int64_t xs = laststride(X), ys = laststride(Y); @@ -560,34 +507,49 @@ int ref_clamp(const RadArgs* a, RadStream) { /* A 2-D convolution over (time, width) with channels innermost, segment by segment. * * x is [M, W * cin]: row t is time t, element (t, w, c) at column w * cin + c. Each cu_seqlens - * segment [cu[s] / cu_div, cu[s+1] / cu_div) is convolved ON ITS OWN, zero-padded by `pad` at its - * edges on both axes -- two clips in one pass must not see each other -- and its output rows start - * at cu[s] / (cu_div * stride). `w` is PyTorch's [cout, cin, kh, kw]. With the optional `valid` - * operand, input row t (pass-global) is read as zeros unless valid[t * valid_stride] != 0: the - * frame mask Gemma 4's subsampler multiplies in before each convolution. f32 accumulation, one - * rounding. */ + * segment [cu[s] / cu_div, cu[s+1] / cu_div) is convolved separately, zero-padded by `pad` on both + * axes, so clips in one pass do not see each other; its output rows start at + * cu[s] / (cu_div * stride). `w` is PyTorch's [cout, cin, kh, kw], kh over time; with `t_last` it + * is [cout, cin, kw, kh], time last (a model that convolves a [mel, time] spectrogram, whose + * kernel's first spatial axis is the one this op calls width). With the optional `valid` operand, + * input row t (pass-global) reads as zeros unless valid[t * valid_stride] != 0: Gemma 4's + * subsampler frame mask, or the chunk boundary that keeps each second of Qwen3-ASR's audio apart. + * The optional `b` adds a bias per output channel before the one rounding; `act` (`none`, `gelu`) + * is then applied to the rounded value and rounded again, as gemm_nt_bias's epilogue does. f32 + * accumulation. */ int ref_conv2d(const RadArgs* a, RadStream) { if (!a || a->n_t < 5 || !a->t[0].data || !a->t[1].data || !a->t[2].data || !a->t[4].data) return RAD_E_INVAL; const RadTensor *X = &a->t[0], *Wt = &a->t[1], *cu = &a->t[2], *Y = &a->t[4]; const RadTensor* V = a->t[3].data ? &a->t[3] : nullptr; + const RadTensor* B = a->n_t > 5 && a->t[5].data ? &a->t[5] : nullptr; const int64_t W = p_int(a, "width", 0), cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0); const int64_t kh = p_int(a, "kh", 0), kw = p_int(a, "kw", 0); const int64_t st = p_int(a, "stride", 1), pad = p_int(a, "pad", 0); const int64_t cdiv = p_int(a, "cu_div", 1), vst = p_int(a, "valid_stride", 1); + const bool tlast = p_int(a, "t_last", 0) != 0; + const char* act = p_str(a, "act", "none"); + const bool gelu = !std::strcmp(act, "gelu"); + if (!gelu && std::strcmp(act, "none")) return RAD_E_UNSUPPORTED; if (W <= 0 || cin <= 0 || cout <= 0 || kh <= 0 || kw <= 0 || st <= 0 || pad < 0 || cdiv <= 0 || vst <= 0) return RAD_E_SHAPE; const int64_t Wo = (W + 2 * pad - kw) / st + 1; if (Wo <= 0 || numel(Wt) < cout * cin * kh * kw) return RAD_E_SHAPE; + if (B && numel(B) < cout) return RAD_E_SHAPE; const int64_t S = numel(cu) - 1; if (S <= 0) return RAD_E_SHAPE; const int64_t rin = W * cin, rout = Wo * cout; const int64_t Min = rows_of(X, rin), Mout = rows_of(Y, rout); + if (Min <= 0 || Mout <= 0 || cu_at(cu, S) <= cu_at(cu, 0)) return RAD_E_SHAPE; /* zero rows */ + /* Kernel tap (i over time, j over width) of channel pair (co, ci). */ + auto widx = [&](int64_t co, int64_t ci, int64_t i, int64_t j) { + return tlast ? ((co * cin + ci) * kw + j) * kh + i : ((co * cin + ci) * kh + i) * kw + j; + }; for (int64_t s = 0; s < S; ++s) { - const int64_t c0 = ld_int(cu->dtype, cu->data, offlin(cu, s)); - const int64_t c1 = ld_int(cu->dtype, cu->data, offlin(cu, s + 1)); + const int64_t c0 = cu_at(cu, s); + const int64_t c1 = cu_at(cu, s + 1); if (c0 % cdiv || c1 % cdiv || (c0 / cdiv) % st || c1 < c0) return RAD_E_SHAPE; const int64_t t0 = c0 / cdiv, T = c1 / cdiv - t0; if (T <= 0) continue; @@ -596,7 +558,7 @@ int ref_conv2d(const RadArgs* a, RadStream) { if (t0 + T > Min || o0 + To > Mout) return RAD_E_SHAPE; if (V && numel(V) < (t0 + T - 1) * vst + 1) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(To * rout * cin * kh * kw) for (int64_t to = 0; to < To; ++to) { const int64_t yb = rowoff(Y, o0 + to, rout), ys = laststride(Y), xs = laststride(X); for (int64_t wo = 0; wo < Wo; ++wo) @@ -612,17 +574,82 @@ int ref_conv2d(const RadArgs* a, RadStream) { const int64_t wi = wo * st - pad + j; if (wi < 0 || wi >= W) continue; for (int64_t ci = 0; ci < cin; ++ci) - acc += ldt(X, xb + (wi * cin + ci) * xs) * - ldt(Wt, ((co * cin + ci) * kh + i) * kw + j); + acc += ldt(X, xb + (wi * cin + ci) * xs) * ldt(Wt, widx(co, ci, i, j)); } } - stt(Y, yb + (wo * cout + co) * ys, acc); + if (B) acc += ldt(B, offlin(B, co)); + const int64_t yo = yb + (wo * cout + co) * ys; + stt(Y, yo, acc); + if (gelu) stt(Y, yo, act_gelu(ldt(Y, yo))); } } } return RAD_OK; } +/* ------------------------------------------------------------------ conv2d_unfold */ +/* conv2d's receptive fields as rows, so a GEMM against the weight is the convolution: row + * (o0 + to) * Wo + wo of y holds, for every input channel and kernel tap, the value conv2d would + * multiply that tap's weight by -- zero where the tap falls in the padding or on a row `valid` + * masks. Its columns are in the weight's order, (ci, i, j) for PyTorch's [cout, cin, kh, kw] and + * (ci, j, i) with t_last, so y times the weight viewed as [cout, cin * kh * kw] is conv2d's output + * with no relayout of either: row (to, wo) of the product is column block wo of conv2d's row to. + * Segments, cu_div and valid as conv2d's; rows no segment covers are left alone. */ +int ref_conv2d_unfold(const RadArgs* a, RadStream) { + if (!a || a->n_t < 4 || !a->t[0].data || !a->t[1].data || !a->t[3].data) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *cu = &a->t[1], *Y = &a->t[3]; + const RadTensor* V = a->t[2].data ? &a->t[2] : nullptr; + const int64_t W = p_int(a, "width", 0), cin = p_int(a, "cin", 0); + const int64_t kh = p_int(a, "kh", 0), kw = p_int(a, "kw", 0); + const int64_t st = p_int(a, "stride", 1), pad = p_int(a, "pad", 0); + const int64_t cdiv = p_int(a, "cu_div", 1), vst = p_int(a, "valid_stride", 1); + const bool tlast = p_int(a, "t_last", 0) != 0; + if (W <= 0 || cin <= 0 || kh <= 0 || kw <= 0 || st <= 0 || pad < 0 || cdiv <= 0 || vst <= 0) + return RAD_E_SHAPE; + const int64_t Wo = (W + 2 * pad - kw) / st + 1, K = cin * kh * kw; + const int64_t S = numel(cu) - 1; + if (Wo <= 0 || S <= 0) return RAD_E_SHAPE; + const int64_t rin = W * cin, Min = rows_of(X, rin), Mout = rows_of(Y, K); + if (Min <= 0 || Mout <= 0 || cu_at(cu, S) <= cu_at(cu, 0)) return RAD_E_SHAPE; /* zero rows */ + + for (int64_t s = 0; s < S; ++s) { + const int64_t c0 = cu_at(cu, s); + const int64_t c1 = cu_at(cu, s + 1); + if (c0 % cdiv || c1 % cdiv || (c0 / cdiv) % st || c1 < c0) return RAD_E_SHAPE; + const int64_t t0 = c0 / cdiv, T = c1 / cdiv - t0; + if (T <= 0) continue; + const int64_t To = (T + 2 * pad - kh) / st + 1, o0 = t0 / st; + if (To <= 0) continue; + if (t0 + T > Min || (o0 + To) * Wo > Mout) return RAD_E_SHAPE; + if (V && numel(V) < (t0 + T - 1) * vst + 1) return RAD_E_SHAPE; + + REF_PAR_FOR(To * Wo * K) + for (int64_t to = 0; to < To; ++to) { + const int64_t ys = laststride(Y), xs = laststride(X); + for (int64_t wo = 0; wo < Wo; ++wo) { + const int64_t yb = rowoff(Y, (o0 + to) * Wo + wo, K); + for (int64_t i = 0; i < kh; ++i) { + const int64_t ti = to * st - pad + i; + const int64_t tg = t0 + ti; + const bool row_ok = ti >= 0 && ti < T && + !(V && ld_int(V->dtype, V->data, offlin(V, tg * vst)) == 0); + for (int64_t j = 0; j < kw; ++j) { + const int64_t wi = wo * st - pad + j; + const bool ok = row_ok && wi >= 0 && wi < W; + for (int64_t ci = 0; ci < cin; ++ci) { + const int64_t k = tlast ? (ci * kw + j) * kh + i : (ci * kh + i) * kw + j; + const float v = ok ? ldt(X, rowoff(X, tg, rin) + (wi * cin + ci) * xs) + : 0.0f; + stt(Y, yb + k * ys, v); + } + } + } + } + } + } + return RAD_OK; +} + /* ------------------------------------------------------------------ conv1d_dw */ /* A causal depthwise convolution over time: y[t, c] = sum_j w[c, j] * x[t - (k-1) + j, c], the * rows before the segment's start (cu[s] / cu_div) read as zeros. `w` is PyTorch's depthwise @@ -635,15 +662,16 @@ int ref_conv1d_dw(const RadArgs* a, RadStream) { const int64_t S = numel(cu) - 1; if (S <= 0) return RAD_E_SHAPE; const int64_t Mx = rows_of(X, C), My = rows_of(Y, C); + if (Mx <= 0 || My <= 0 || cu_at(cu, S) <= cu_at(cu, 0)) return RAD_E_SHAPE; /* zero rows */ for (int64_t s = 0; s < S; ++s) { - const int64_t c0 = ld_int(cu->dtype, cu->data, offlin(cu, s)); - const int64_t c1 = ld_int(cu->dtype, cu->data, offlin(cu, s + 1)); + const int64_t c0 = cu_at(cu, s); + const int64_t c1 = cu_at(cu, s + 1); if (c0 % cdiv || c1 % cdiv || c1 < c0) return RAD_E_SHAPE; const int64_t t0 = c0 / cdiv, t1 = c1 / cdiv; if (t1 > Mx || t1 > My) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + REF_PAR_FOR((t1 - t0) * C * K) for (int64_t t = t0; t < t1; ++t) { const int64_t yb = rowoff(Y, t, C), ys = laststride(Y), xs = laststride(X); for (int64_t c = 0; c < C; ++c) { @@ -661,9 +689,9 @@ int ref_conv1d_dw(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------------ rel_sinusoid */ -/* The sinusoidal relative-position table, row d for distance d: sin(d * inv[i]) in the first - * half, cos(d * inv[i]) in the second, inv[i] = exp(i * -log(max_timescale) / max(n/2 - 1, 1)). - * Computed in f32 step by step the way the reference's torch expressions are, then rounded. */ +/* The sinusoidal relative-position table, row d for distance d: sin(d * inv[i]) in the first half, + * cos(d * inv[i]) in the second, inv[i] = exp(i * -log(max_timescale) / max(n/2 - 1, 1)). Computed + * in f32 step by step as the upstream torch expressions are, then rounded. */ int ref_rel_sinusoid(const RadArgs* a, RadStream) { if (!have(a, 1)) return RAD_E_INVAL; const RadTensor* Y = &a->t[0]; @@ -675,27 +703,24 @@ int ref_rel_sinusoid(const RadArgs* a, RadStream) { const double mt = (double)p_f32(a, "max_timescale", 10000.0f); const float inc = (float)(std::log(mt / 1.0) / (double)(h - 1 > 1 ? h - 1 : 1)); - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * n) for (int64_t d = 0; d < rows; ++d) { const int64_t yb = rowoff(Y, d, n), ys = laststride(Y); for (int64_t i = 0; i < h; ++i) { - const float inv = std::exp((float)i * -inc); + const float inv = ref_exp((float)i * -inc); const float ang = (float)d * inv; - stt(Y, yb + i * ys, std::sin(ang)); - stt(Y, yb + (h + i) * ys, std::cos(ang)); + stt(Y, yb + i * ys, ref_sin(ang)); + stt(Y, yb + (h + i) * ys, ref_cos(ang)); } } return RAD_OK; } /* ------------------------------------------------------------------ gelu_mul */ -/* y[.., i] = gelu_tanh(gate_up[.., i]) * gate_up[.., n + i] -- the tanh GELU, and the gate is the - * FIRST half, for the same order-locking reason as silu_mul. This is Gemma's gated FFN - * (down(gelu_tanh(gate(x)) * up(x)), activation gelu_pytorch_tanh in the checkpoint). It is not - * `gemm_nt`'s "gelu_tanh" EPLOGUE, which applies the activation to a whole GEMM's output and has no - * gate to multiply; gating needs the product of two halves of one fused plane, which is silu_mul's - * shape. The exact-erf form is the unary `gelu` op; a GELU-gated feed-forward in this family is - * trained with the tanh approximation, so this op is the tanh one on purpose and says so. */ +/* y[.., i] = gelu_tanh(gate_up[.., i]) * gate_up[.., n + i], gate first as in silu_mul. Gemma's + * gated FFN, down(gelu_tanh(gate(x)) * up(x)) (gelu_pytorch_tanh in the checkpoint). Unlike + * gemm_nt's "gelu_tanh" epilogue it multiplies two halves of one fused plane. Deliberately the tanh + * form, which GELU-gated FFNs are trained with; the exact-erf form is the unary `gelu` op. */ int ref_gelu_mul(const RadArgs* a, RadStream) { if (!have(a, 2)) return RAD_E_INVAL; const RadTensor *gu = &a->t[0], *y = &a->t[1]; @@ -704,7 +729,7 @@ int ref_gelu_mul(const RadArgs* a, RadStream) { const int64_t rows = rows_of(y, n); if (rows <= 0 || numel(gu) < rows * 2 * n) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { const int64_t gb = rowoff(gu, r, 2 * n), yb = rowoff(y, r, n); const int64_t gs = laststride(gu), ys = laststride(y); @@ -714,6 +739,43 @@ int ref_gelu_mul(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------------ seg_sinusoid */ +/* A Whisper-style absolute position table restarting every `period` rows of a segment: row r of + * segment s (rows [cu[s] / cu_div, cu[s+1] / cu_div)) takes position p = (r - cu[s] / cu_div) mod + * period, and is sin(p * inv[i]) then cos(p * inv[i]) over n/2 timescales, inv[i] as + * rel_sinusoid's, each step in f32 and rounded once. Qwen3-ASR's encoder adds it to every chunk's + * rows, which restart at position 0 with each second of audio. A row no segment covers is left + * untouched. */ +int ref_seg_sinusoid(const RadArgs* a, RadStream) { + if (!have(a, 2)) return RAD_E_INVAL; + const RadTensor *cu = &a->t[0], *Y = &a->t[1]; + const int64_t n = p_int(a, "n", 0), period = p_int(a, "period", 0), cdiv = p_int(a, "cu_div", 1); + if (n <= 0 || n % 2 || period <= 0 || cdiv <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_of(Y, n), S = numel(cu) - 1; + if (rows <= 0 || S <= 0 || cu_at(cu, S) <= cu_at(cu, 0)) return RAD_E_SHAPE; /* zero rows */ + const int64_t h = n / 2; + const double mt = (double)p_f32(a, "max_timescale", 10000.0f); + const float inc = (float)(std::log(mt / 1.0) / (double)(h - 1 > 1 ? h - 1 : 1)); + + for (int64_t s = 0; s < S; ++s) { + const int64_t c0 = cu_at(cu, s); + const int64_t c1 = cu_at(cu, s + 1); + if (c0 % cdiv || c1 % cdiv || c1 < c0 || c1 / cdiv > rows) return RAD_E_SHAPE; + REF_PAR_FOR((c1 / cdiv - c0 / cdiv) * n * 4) + for (int64_t r = c0 / cdiv; r < c1 / cdiv; ++r) { + const int64_t p = (r - c0 / cdiv) % period; + const int64_t yb = rowoff(Y, r, n), ys = laststride(Y); + for (int64_t i = 0; i < h; ++i) { + const float inv = ref_exp((float)i * -inc); + const float ang = (float)p * inv; + stt(Y, yb + i * ys, ref_sin(ang)); + stt(Y, yb + (h + i) * ys, ref_cos(ang)); + } + } + } + return RAD_OK; +} + /* ------------------------------------------------------------------ gelu / silu */ static int unary(const RadArgs* a, int which) { if (!have(a, 2)) return RAD_E_INVAL; @@ -721,7 +783,7 @@ static int unary(const RadArgs* a, int which) { const int64_t nel = numel(y); if (nel <= 0 || numel(x) < nel) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(nel * 4) for (int64_t i = 0; i < nel; ++i) { float v = ldt(x, offlin(x, i)); stt(y, offlin(y, i), which == 0 ? act_gelu(v) : which == 1 ? act_silu(v) : act_sigmoid(v)); @@ -733,13 +795,12 @@ int ref_gelu(const RadArgs* a, RadStream) { return unary(a, 0); } int ref_silu(const RadArgs* a, RadStream) { return unary(a, 1); } /* ------------------------------------------------------------------ sigmoid */ -/* Its own op rather than a `which` on gelu/silu, because a gated shared expert issues it against - * the router's output and the selector has to be able to name it (docs/OPS.md, "New ops"). Without - * it that expert runs ungated, which is a different model and not a slower one. */ +/* Its own op so the selector can name it: a gated shared expert issues it on the router's output + * (docs/OPS.md, "Elementwise and norms"). */ int ref_sigmoid(const RadArgs* a, RadStream) { return unary(a, 2); } /* ------------------------------------------------------------------ fill */ -/* y = value over [M, n], at y's own row pitch. The value is rounded once, by the store. */ +/* y = value over [M, n] at y's row pitch, rounded once by the store. */ int ref_fill(const RadArgs* a, RadStream) { if (!have(a, 1)) return RAD_E_INVAL; const RadTensor* y = &a->t[0]; @@ -749,7 +810,7 @@ int ref_fill(const RadArgs* a, RadStream) { if (rows <= 0) return RAD_E_SHAPE; const float v = p_f32(a, "value", 0.0f); - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { const int64_t yb = rowoff(y, r, n), ys = laststride(y); for (int64_t i = 0; i < n; ++i) stt(y, yb + i * ys, v); @@ -758,10 +819,8 @@ int ref_fill(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------------ logit_softcap */ -/* y = cap * tanh(x / cap), Gemma's final-logit softcap: the logits_gemm's output is a nearly - * unbounded row and the sampler wants it bounded, so this is issued against the LOGITS, not the - * hidden stream. Its own op for the same reason sigmoid is -- the selector has to be able to name - * it -- and `cap` is a parameter of the call, which the which-switch above cannot carry. */ +/* y = cap * tanh(x / cap), Gemma's final-logit softcap, issued on the logits. Its own op so the + * selector can name it and so `cap` can be a call parameter. */ int ref_logit_softcap(const RadArgs* a, RadStream) { if (!have(a, 2)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *y = &a->t[1]; @@ -770,51 +829,38 @@ int ref_logit_softcap(const RadArgs* a, RadStream) { const float cap = p_f32(a, "cap", 30.0f); if (!(cap > 0.0f)) return RAD_E_INVAL; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(nel * 4) for (int64_t i = 0; i < nel; ++i) { const float v = ldt(x, offlin(x, i)); - stt(y, offlin(y, i), cap * std::tanh(v / cap)); + stt(y, offlin(y, i), cap * ref_tanh(v / cap)); } return RAD_OK; } /* ------------------------------------------------------------------ scale */ -/* y = x * s, where s is a [1] weight broadcast over every element of x. - * - * Gemma 4's per-layer scalar: the residual stream is scaled by a learned [1] value at the end of - * every layer (llama.cpp `out_scale`, `cur = cur * out_scale`). It is NOT `mul`, which broadcasts - * a single ROW down the rows (a bias's shape) -- this broadcasts a single SCALAR over the whole - * [M, n] tensor. `scale_rows` is the per-ROW version (one scalar a row); this is the per-TENSOR - * version (one scalar for all rows). Giving `mul` both rules would make them ambiguous exactly - * when rows == 1, so a silent choice between two broadcasts is how a shape bug becomes a - * plausible number -- the same reason `scale_rows` is its own op. - * - * `s` is a weight (a [1] tensor in the checkpoint), not a parameter: it varies per layer, so it - * is a declared weight the name map points at, not a call constant. Read once, outside the loop: - * a per-element reload of a [1] tensor is the same value every time and costs a load per element. */ +/* y = x * s, s a [1] weight broadcast over all of x: Gemma 4's per-layer residual scalar (llama.cpp + * `out_scale`). `mul` broadcasts a row and `scale_rows` one scalar per row; this is one scalar per + * tensor, kept separate so the broadcasts are never ambiguous. `s` is a per-layer checkpoint weight, + * not a call constant. */ int ref_scale(const RadArgs* a, RadStream) { if (!have(a, 3)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *s = &a->t[1], *y = &a->t[2]; const int64_t nel = numel(y); if (nel <= 0 || numel(x) < nel || numel(s) < 1) return RAD_E_SHAPE; const float sv = ldt(s, 0); - #pragma omp parallel for schedule(static) + REF_PAR_FOR(nel) for (int64_t i = 0; i < nel; ++i) stt(y, offlin(y, i), ldt(x, offlin(x, i)) * sv); return RAD_OK; } /* ------------------------------------------------------------------ gather_rows */ -/* y[i, :] = x[idx[i], :]. The op that turns "correct" into "affordable": without it a plugin runs - * the lm_head GEMM over every token of a prefill chunk when the sampler wants one row per - * sequence -- n_tok/n_seq times the work, and at max_tok 8192 against a 248K vocab the logits - * buffer alone is 8 GiB (docs/OPS.md). +/* y[i, :] = x[idx[i], :]. Lets the lm_head GEMM run on one row per sequence instead of every + * prefill token: at max_tok 8192 and a 248K vocab the full logits buffer would be 8 GiB + * (docs/OPS.md). * - * `M` is a RANGE parameter, so the number of rows actually gathered is the extent of `y` and not - * the declared worst case; `idx` is read for exactly that many entries. A negative index writes a - * zero row, matching embed_lookup's padding rule -- it is what a step with fewer sampled rows - * than the buffer's extent leaves behind, and zeros are the only answer that cannot be mistaken - * for a real logit row. An index at or past x's row count is RAD_E_INVAL: that is a caller bug, - * and reading it would be reading another sequence's hidden state. */ + * `M` is a range parameter, so the row count is y's extent and `idx` is read for that many entries. + * A negative index writes a zero row (embed_lookup's padding rule; unsampled rows of a step). An + * index at or past x's row count is a caller bug and returns RAD_E_INVAL. */ int ref_gather_rows(const RadArgs* a, RadStream) { if (!have(a, 3)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *idx = &a->t[1], *y = &a->t[2]; @@ -830,7 +876,7 @@ int ref_gather_rows(const RadArgs* a, RadStream) { if (r >= src_rows) return RAD_E_INVAL; } - #pragma omp parallel for schedule(static) + REF_PAR_FOR(M * n) for (int64_t m = 0; m < M; ++m) { const int64_t r = ld_int(idx->dtype, idx->data, offlin(idx, m)); const int64_t yb = rowoff(y, m, n), ys = laststride(y); @@ -843,18 +889,14 @@ int ref_gather_rows(const RadArgs* a, RadStream) { /* ------------------------------------------------------------------ scatter_rows */ -/* The mirror of gather_rows, and it exists for the same reason that one does: without it the only - * way to write M rows to M arbitrary destinations is M transfers, and at a few hundred bytes a row - * that is dispatch cost with the data as a rounding error. +/* The mirror of gather_rows: writes M rows to M arbitrary destinations in one launch instead of M + * small transfers. * - * `x` IS INOUT AND THE WRITE IS PARTIAL. Rows no index names keep whatever they held -- which is - * the whole point when the destination is a pool other sequences are also using. An op that - * returned a fresh `x` would have to copy everything it was not asked to change. + * `x` is INOUT and the write is partial: unnamed rows keep their contents, since the destination + * is often a pool shared with other sequences. * - * DUPLICATE INDICES ARE NOT LEGAL, and the schema says so with RAD_OPD_F_IDX_UNIQUE rather than - * leaving it to prose. Two rows landing on one destination has no defined winner on a parallel - * machine, so an op that permitted it would be one whose reference implementation and whose real - * kernel are allowed to disagree -- which is exactly what the oracle exists to rule out. */ + * Duplicate indices are illegal (RAD_OPD_F_IDX_UNIQUE): two rows landing on one destination have no + * defined winner in parallel, so reference and kernel could legitimately disagree. */ int ref_scatter_rows(const RadArgs* a, RadStream) { if (!have(a, 3)) return RAD_E_INVAL; const RadTensor *v = &a->t[0], *idx = &a->t[1], *x = &a->t[2]; @@ -864,15 +906,14 @@ int ref_scatter_rows(const RadArgs* a, RadStream) { const int64_t dst_rows = rows_of(x, n); if (M <= 0 || dst_rows <= 0 || numel(idx) < M) return RAD_E_SHAPE; - /* Validated before the loop, because an OpenMP body cannot return. A negative index is a - * skip, mirroring the zero row gather_rows writes for one: both mean "this slot has no - * counterpart", and on this side the honest response is to leave the destination alone. */ + /* Validated before the loop, since an OpenMP body cannot return. A negative index is skipped, + * mirroring gather_rows' zero row: both mean the slot has no counterpart. */ for (int64_t m = 0; m < M; ++m) { const int64_t r = ld_int(idx->dtype, idx->data, offlin(idx, m)); if (r >= dst_rows) return RAD_E_INVAL; } - #pragma omp parallel for schedule(static) + REF_PAR_FOR(M * n) for (int64_t m = 0; m < M; ++m) { const int64_t r = ld_int(idx->dtype, idx->data, offlin(idx, m)); if (r < 0) continue; @@ -883,24 +924,20 @@ int ref_scatter_rows(const RadArgs* a, RadStream) { return RAD_OK; } /* ------------------------------------------------------------------ cast */ -/* `from` and `to` are in the schema because the SELECTOR needs them -- a kernel that converts bf16 - * to int8 is a different kernel from one that converts f32 to f16, and the constraint has to be - * expressible. Ref does not read them: the tensors carry their own dtypes and those are what the - * bytes actually are. A disagreement between the parameter and the tensor is a caller bug that - * ref cannot diagnose better than the caller can. */ +/* `from` and `to` exist for the selector (each dtype pair is a different kernel). Ref ignores them + * and uses the tensors' own dtypes, which describe the bytes. */ int ref_cast(const RadArgs* a, RadStream) { if (!have(a, 2)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *y = &a->t[1]; const int64_t nel = numel(y); if (nel <= 0 || numel(x) < nel) return RAD_E_SHAPE; - /* Integer targets and sources go through the integer path, so a token id or a block index - * survives a cast that f32 would round. */ + /* Integer-to-integer casts bypass f32, so ids and indices above 2^24 survive. */ const bool int_pair = (x->dtype == RAD_I32 || x->dtype == RAD_I64 || x->dtype == RAD_U32 || x->dtype == RAD_I16) && (y->dtype == RAD_I32 || y->dtype == RAD_I64 || y->dtype == RAD_U32 || y->dtype == RAD_I16); - #pragma omp parallel for schedule(static) + REF_PAR_FOR(nel) for (int64_t i = 0; i < nel; ++i) { if (int_pair) st_int(y->dtype, y->data, offlin(y, i), ld_int(x->dtype, x->data, offlin(x, i))); else stt(y, offlin(y, i), ldt(x, offlin(x, i))); @@ -909,9 +946,8 @@ int ref_cast(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------------ softmax */ -/* Max-subtracted, f32, over the last n elements of a row. The max subtraction is not an - * optimisation: without it a 60-nat logit range overflows, and every kernel this is an oracle for - * does it, so the reference must too or the two differ by more than rounding. */ +/* Max-subtracted, f32, over the last n elements of a row. Every kernel subtracts the max (a 60-nat + * logit range would otherwise overflow), so the reference must too. */ int ref_softmax(const RadArgs* a, RadStream) { if (!have(a, 2)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *y = &a->t[1]; @@ -920,7 +956,7 @@ int ref_softmax(const RadArgs* a, RadStream) { const int64_t rows = rows_of(y, n); if (rows <= 0 || numel(x) < rows * n) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * n * 4) for (int64_t r = 0; r < rows; ++r) { const int64_t xb = rowoff(x, r, n), yb = rowoff(y, r, n); const int64_t xs = laststride(x), ys = laststride(y); diff --git a/libref/ref_gdn.cpp b/libref/ref_gdn.cpp index c8beb753..db4e6fc1 100644 --- a/libref/ref_gdn.cpp +++ b/libref/ref_gdn.cpp @@ -1,12 +1,11 @@ /* ref_gdn.cpp -- the gated delta net: the conv preamble, the chunk preamble, the chunked scan, the * recurrent update and the gated norm. * - * The algorithm is libr4d's, stated in its own comments and reproduced here without any of the - * fusion. Where libr4d says the state lives in WMMA accumulators across a whole chunk, this keeps - * it in a per-thread workspace and writes every intermediate out; where libr4d recomputes the gram - * once per k head for three v heads, this recomputes it per v head. Both are the same arithmetic. + * libr4d's algorithm without the fusion: the state lives in a per-thread workspace instead of WMMA + * accumulators, every intermediate is written out, and the gram is recomputed per v head instead + * of once per k head. The arithmetic is the same. * - * ============================== THE ALGORITHM ============================== + * ============================== The algorithm ============================== * * Per token, per v head, with q and k l2-normalised and the state S shaped [head_v, head_k]: * @@ -14,25 +13,21 @@ * S *= e^g * u = beta . (v - S k) S += u k^T o = S q * - * That is the recurrent form, which is what DECODE runs. Prefill runs the chunked form, which is - * the same recurrence blocked over `chunk` tokens with the intra-chunk dependencies solved in one - * triangular inverse (`gdn_kkt_solve`) instead of sequentially: + * Decode runs this recurrent form. Prefill runs the chunked form: the same recurrence blocked over + * `chunk` tokens, with intra-chunk dependencies solved by one triangular inverse (`gdn_kkt_solve`): * - * ge[j] = e^{g_j} gs[j] = e^{g_last - g_j} (g is the INTRA-CHUNK CUMSUM of the gate) + * ge[j] = e^{g_j} gs[j] = e^{g_last - g_j} (g is the intra-chunk cumsum of the gate) * U = K S^T W = beta . (V - ge . U) V' = A W * P = Q K^T sA = scale . e^{g_i - g_j} . tril(P) * O = scale . ge . (Q S^T) + sA V' * S = e^{g_last} S + V'^T (gs . K) * - * EVERY DECAY FACTOR FORMED HERE IS <= 1, and that is a correctness requirement rather than a - * style. Intra-chunk gate spans on real prefill inputs reach several hundred nats, so - * any factorisation that puts half the exponent on its own -- e^{g_i - c} and e^{c - g_j} about - * some per-chunk reference c -- sends one half past fp32's e^88 while the other underflows to - * zero, whatever c is chosen. The pairs e^{g_i - g_j} (j <= i) and e^{g_last - g_j} never leave - * (0, 1]. A reference that took the convenient factorisation would produce infinities on inputs - * the fast kernel handles, which is the wrong way round for an oracle. + * Invariant: every decay factor formed is <= 1. Intra-chunk gate spans on real prefill inputs reach + * several hundred nats, so splitting the exponent about any reference c (e^{g_i - c}, e^{c - g_j}) + * overflows fp32's e^88 on one side and underflows on the other. The pairs e^{g_i - g_j} (j <= i) + * and e^{g_last - g_j} stay in (0, 1]. * - * ============================== THE LAYOUTS ============================== + * ============================== The layouts ============================== * * q, k [T, head_k_count, head_k] v, o [T, head_v_count, head_v] * g, beta [T, head_v_count] A [T, head_v_count, chunk] @@ -42,25 +37,24 @@ * state [n_slots, head_v_count, head_v, head_k] * * with conv_dim = 2 * head_k_count * head_k + head_v_count * head_v, and `x` the fused projection - * row [q | k | v | a | b] -- conv_dim convolved channels followed by one `a` and one `b` per v - * head. gdn_conv_prep takes `a` and `b_gate` as OPTIONAL operands: present, they are the layer's - * separate gate and beta projections; absent, they are the last 2 * head_v_count columns of `x`. - * gdn_recurrent_update always names them separately, and a caller with a fused row passes strided - * views of it. + * row [q | k | v | a | b]: conv_dim convolved channels, then one `a` and one `b` per v head. + * gdn_conv_prep's `a` and `b_gate` operands are optional: present, they are separate gate and beta + * projections; absent, they are the last 2 * head_v_count columns of `x`. gdn_recurrent_update + * always takes them separately (strided views of a fused row are fine). * - * The speculative rollback contract for the two state caches is in ref_ops.h and is obeyed here. + * The speculative rollback contract for the two state caches is in ref_ops.h. */ #include "ref_common.h" #include "ref_ops.h" +#include + using namespace ref; namespace { -/* The deepest convolution history this reference holds in a stack frame. libr4d's width is 4 and - * no linear-attention model in circulation exceeds it by much; a wider request returns - * RAD_E_UNSUPPORTED by name rather than convolving a truncated window, which would be numerically - * plausible and completely wrong. */ +/* The deepest convolution history held in a stack frame. libr4d's width is 4; a wider request + * returns RAD_E_UNSUPPORTED rather than convolving a truncated window. */ enum { REF_CONV_HIST_MAX = 16 }; struct V3 { const RadTensor* t; int64_t s0, s1, s2; }; @@ -75,10 +69,9 @@ static inline V3 v3(const RadTensor* t, int64_t d1, int64_t d2) { } return v; } -/* The same [tokens, d1, d2] reading for an operand that may be a COLUMN VIEW of a wider row: the - * fp8 delta net's output gate is the tail of a fused [q|k|v|z] projection, so its token stride is - * its own rather than d1*d2. A rank-3 spelling already carries all three strides; a rank-2 one - * carries the token stride in stride[0] and v3() would have guessed d1*d2 for it. */ +/* v3() for an operand that may be a column view of a wider row (the fp8 delta net's output gate is + * the tail of a fused [q|k|v|z] projection). A rank-2 view carries its token stride in stride[0], + * where v3() would assume d1*d2. */ static inline V3 v3_rows(const RadTensor* t, int64_t d1, int64_t d2) { if (t->rank != 2) return v3(t, d1, d2); return V3{ t, t->stride[0], d2 * t->stride[1], t->stride[1] }; @@ -93,11 +86,9 @@ static inline int64_t at3(const V3& v, int64_t i, int64_t j, int64_t k) { } static inline int64_t at2(const V2& v, int64_t i, int64_t j) { return i * v.s0 + j * v.s1; } -/* [N, heads, head_v, head_k] -- the shape both the chunked scan's h0/ht and the paged recurrent - * state have. The slot and head strides are read off the tensor and NOT derived from the shape: - * a paged state cache is padded so its page matches the attention page, and a kernel that derived - * the stride would read every slot but the first at the wrong offset, which looks exactly like a - * correct kernel producing noise (libr4d makes the same point about vLLM's mamba page). */ +/* [N, heads, head_v, head_k], the shape of the chunked scan's h0/ht and the paged recurrent state. + * Strides are read off the tensor, not derived: a paged state cache is padded to match the + * attention page, so a derived stride would misread every slot after the first. */ struct V4 { const RadTensor* t; int64_t s0, s1, s2, s3; }; static inline V4 v4(const RadTensor* t, int64_t d1, int64_t d2, int64_t d3) { V4 v{ t, d1 * d2 * d3, d2 * d3, d3, 1 }; @@ -113,33 +104,61 @@ static inline int64_t at4(const V4& v, int64_t i, int64_t j, int64_t k, int64_t return i * v.s0 + j * v.s1 + k * v.s2 + l * v.s3; } -static inline int64_t cu_at(const RadTensor* cu, int64_t i) { - return ld_int(cu->dtype, cu->data, offlin(cu, i)); -} - -/* The conv state is [n_slots, conv_dim, state_len]; a rank the caller flattened is read as the - * tight layout that shape implies. */ +/* The conv state is [n_slots, conv_dim, state_len]; a flattened one is read as the tight layout. */ static inline V3 conv_state_view(const RadTensor* cs, int64_t conv_dim, int64_t width, int64_t* state_len) { *state_len = cs->rank >= 3 ? cs->shape[cs->rank - 1] : (width > 1 ? width - 1 : 1); return v3(cs, conv_dim, *state_len); } +/* What gdn_conv_prep and gdn_conv_update share: the fused row `x`, the conv weight and bias, and + * the q, k and v outputs the channels split into. */ +struct ConvIO { + const RadTensor *x, *w, *bias, *q, *k, *v; + int64_t xrow, xcol, Hg, H, K, V, width; +}; + +/* Channel `c` of the depthwise causal convolution with silu over one sequence's `slen` tokens + * from row `bos`, `hist` holding its width - 1 entries of history. Channels are grouped in whole + * heads, so a group never straddles the q/k/v boundaries at any tensor-parallel width. */ +static void conv_channel(const ConvIO& io, int64_t c, int64_t bos, int64_t slen, const float* hist) { + const int64_t Hg = io.Hg, K = io.K, V = io.V, width = io.width; + const RadTensor* out; + V3 ov; + int64_t oh, od; + if (c < Hg * K) { + out = io.q; ov = v3(out, Hg, K); oh = c / K; od = c % K; + } else if (c < 2 * Hg * K) { + out = io.k; ov = v3(out, Hg, K); oh = (c - Hg * K) / K; od = (c - Hg * K) % K; + } else { + out = io.v; ov = v3(out, io.H, V); oh = (c - 2 * Hg * K) / V; od = (c - 2 * Hg * K) % V; + } + const V2 wv = v2(io.w, width); + const float bs = io.bias ? ldt(io.bias, c * laststride(io.bias)) : 0.0f; + for (int64_t t = 0; t < slen; ++t) { + float acc = bs; + for (int64_t j = 0; j < width; ++j) { + const int64_t src = t - (width - 1) + j; + const float val = src >= 0 ? ldt(io.x, (bos + src) * io.xrow + c * io.xcol) + : hist[src + width - 1]; + acc += val * ldt(io.w, at2(wv, c, j)); + } + stt(out, at3(ov, bos + t, oh, od), act_silu(acc)); + } +} + } /* namespace */ /* ------------------------------------------------------------------ gdn_conv_prep */ /* Everything between the qkv projection and the chunked scan: the width-`conv_width` depthwise - * causal convolution with silu and its state cache, the q/k/v split, the l2 norm over each q and k + * causal convolution with silu and its state cache, the q/k/v split, the l2 norm of each q and k * head, the gate with its per-chunk cumsum, and beta. * - * THE CONV OUTPUT IS ROUNDED BEFORE THE NORM. A fused kernel rounds to bf16 there because the pair - * of kernels it replaces does -- the conv writes a bf16 tensor and the prep reads it back -- and - * matching that is what lets the fused form stand in for the unfused pair on real weights. The - * reference does the same by writing the conv result into its output tensor and reading it back - * for the norm. + * The conv output is rounded before the norm, as the unfused pair does (the conv writes bf16, the + * prep reads it back); the reference writes it to its output tensor and reads it back. * - * The l2 norm is rsqrt(sum(x^2) + l2_eps) with NO division by the head width -- it is a norm, not - * an RMS -- and l2_eps is 1e-6, which is FLA's and libr4d's L2NORM_EPS. */ + * The l2 norm is rsqrt(sum(x^2) + l2_eps) with no division by head width (a norm, not an RMS); + * l2_eps defaults to 1e-6, FLA's and libr4d's L2NORM_EPS. */ int ref_gdn_conv_prep(const RadArgs* a, RadStream) { if (a->n_t < 16) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *w = &a->t[1], *cs = &a->t[5], *cu = &a->t[6]; @@ -148,27 +167,20 @@ int ref_gdn_conv_prep(const RadArgs* a, RadStream) { const RadTensor* bias = t_in(a, 2); const RadTensor* A_log = t_in(a, 3); const RadTensor* dt_bias = t_in(a, 4); - /* The gate and beta projections, when the layer hands them separately from the qkv slice. - * Absent, they are the last 2*H columns of the fused `x` row, which is what a caller holding - * a single fused projection passes. */ + /* Separate gate and beta projections; absent, they are the last 2*H columns of `x`. */ const RadTensor* ta = t_in(a, 7); const RadTensor* tb = t_in(a, 8); const RadTensor* sidx = t_in(a, 9); const RadTensor* hini = t_in(a, 10); if (!x->data || !w->data || !cu->data || !q->data || !k->data || !v->data || !g->data || !beta->data) return RAD_E_INVAL; - /* One of the two, not one of each: a caller that names the gate has to name beta as well, or - * the second read silently falls back into a fused row that may not be there. */ + /* Both or neither, or one read would fall back into a fused row that may not exist. */ if ((ta != nullptr) != (tb != nullptr)) return RAD_E_INVAL; const int64_t K = p_int(a, "head_k", 0), V = p_int(a, "head_v", 0); - /* `chunk` is RAD_DERIVED on this op, and NOTHING HERE CARRIES IT: the gate cumsum is cut at - * the chunk boundary and no operand's shape records where that is. Ref declares no RAD_C_EQ - * for it, so a caller who both omitted it and resolved to ref arrives with the key unset and - * gets RAD_E_SHAPE by name. The alternative -- treating the sequence as one chunk -- is a - * decay summed over the wrong span, which is numerically plausible and completely wrong. A - * caller pins `chunk` here (which is what the architecture plugins do) or resolves to a kernel - * that declares one. */ + /* `chunk` is RAD_DERIVED and no operand's shape records it, yet the gate cumsum is cut at the + * chunk boundary. A call that omits it gets RAD_E_SHAPE rather than a cumsum over the wrong + * span; the architecture plugins pin it. */ const int64_t chunk = p_int(a, "chunk", 0), width = p_int(a, "conv_width", 0); const float l2eps = p_f32(a, "l2_eps", 1e-6f); const float spthr = p_f32(a, "softplus_thr", 20.0f); @@ -178,7 +190,7 @@ int ref_gdn_conv_prep(const RadArgs* a, RadStream) { const int64_t N = numel(cu) - 1; if (N <= 0) return RAD_E_SHAPE; const int64_t T = cu_at(cu, N); - if (T <= 0) return RAD_OK; /* an empty step is not an error */ + if (T <= 0) return RAD_E_SHAPE; /* zero rows (docs/OPS.md, Conventions) */ const int64_t Hg = numel(q) / (T * K); const int64_t H = numel(v) / (T * V); if (Hg <= 0 || H <= 0 || H % Hg != 0) return RAD_E_SHAPE; @@ -188,11 +200,9 @@ int ref_gdn_conv_prep(const RadArgs* a, RadStream) { const int64_t xrow = x->rank >= 2 ? x->stride[x->rank - 2] : (conv_dim + (ta ? 0 : 2 * H)); const int64_t xcol = laststride(x); - /* THE BOUND IS THE VIEW'S AND NOT THE BUFFER'S. `x` may be a column slice of a wider row -- - * the fp8 block hands the convolution the left-hand `conv_dim` of a fused [q|k|v|z] - * projection -- and a slice's numel counts only the elements it names, so the flat product - * refuses a call that is perfectly in range. Rank 2 or more spells the extent in the shape; - * only a flattened operand has to be bounded by numel. */ + /* Bound by the view, not the buffer: `x` may be a column slice of a wider row (the fp8 block + * passes the left `conv_dim` of a fused [q|k|v|z] projection), whose numel undercounts the + * span. Rank >= 2 is checked by shape; only a flattened operand is bounded by numel. */ const int64_t xneed = conv_dim + (ta ? 0 : 2 * H); if (x->rank >= 2) { if (x->shape[x->rank - 1] < xneed || x->shape[x->rank - 2] < T) return RAD_E_SHAPE; @@ -205,52 +215,30 @@ int ref_gdn_conv_prep(const RadArgs* a, RadStream) { const V3 cvs = conv_state_view(cs, conv_dim, width, &state_len); if (cs->data && state_len < width - 1) return RAD_E_SHAPE; - const V3 qv = v3(q, Hg, K), kv = v3(k, Hg, K), vv = v3(v, H, V); - const V2 wv = v2(w, width); + const V3 qv = v3(q, Hg, K), kv = v3(k, Hg, K); const V2 gv = v2(g, H), bv = v2(beta, H); const V2 av = ta ? v2(ta, H) : V2{ nullptr, 0, 0 }; const V2 bgv = tb ? v2(tb, H) : V2{ nullptr, 0, 0 }; + const ConvIO io{ x, w, bias, q, k, v, xrow, xcol, Hg, H, K, V, width }; /* ---- phase 1: the convolution, straight into q / k / v ---------------------------------- */ - #pragma omp parallel for schedule(static) + REF_PAR_FOR(T * conv_dim * width) for (int64_t nc = 0; nc < N * conv_dim; ++nc) { const int64_t n = nc / conv_dim, c = nc % conv_dim; const int64_t bos = cu_at(cu, n), slen = cu_at(cu, n + 1) - bos; if (slen <= 0) continue; const int64_t slot = sidx ? ld_int(sidx->dtype, sidx->data, offlin(sidx, n)) : n; - /* A zero `has_init` means the slot holds no history: the window in front of the sequence's - * first token is ZEROS, not whatever the slot last held. Without it a fresh sequence - * landing on a recycled slot convolves the previous sequence's tail into its first - * conv_width-1 tokens, which is fluent output with the wrong prefix. */ + /* A zero `has_init` means the slot holds no history: the window before the first token is + * zeros, not a recycled slot's previous contents. */ const bool warm = !hini || ld_int(hini->dtype, hini->data, offlin(hini, n)) != 0; - - /* Which of the three outputs this channel belongs to. Channel groups are counted in HEADS, - * so a group never straddles the q/k/v boundaries at any tensor-parallel width. */ - const RadTensor* out; - V3 ov; - int64_t oh, od; - if (c < Hg * K) { out = q; ov = qv; oh = c / K; od = c % K; } - else if (c < 2 * Hg * K) { out = k; ov = kv; oh = (c - Hg * K) / K; od = (c - Hg * K) % K; } - else { out = v; ov = vv; oh = (c - 2 * Hg * K) / V; - od = (c - 2 * Hg * K) % V; } - - const float bs = bias ? ldt(bias, c * laststride(bias)) : 0.0f; - for (int64_t t = 0; t < slen; ++t) { - float acc = bs; - for (int64_t j = 0; j < width; ++j) { - const int64_t src = t - (width - 1) + j; - float val = 0.0f; - if (src >= 0) val = ldt(x, (bos + src) * xrow + c * xcol); - else if (warm && cs->data && slot >= 0) - val = ldt(cs, at3(cvs, slot, c, src + width - 1)); - acc += val * ldt(w, at2(wv, c, j)); - } - stt(out, at3(ov, bos + t, oh, od), act_silu(acc)); - } + float hist[REF_CONV_HIST_MAX]; + for (int64_t i = 0; i < width - 1; ++i) + hist[i] = warm && cs->data && slot >= 0 ? ldt(cs, at3(cvs, slot, c, i)) : 0.0f; + conv_channel(io, c, bos, slen, hist); } - /* ---- phase 2: the l2 norm over each q and k head, reading the ROUNDED conv output -------- */ - #pragma omp parallel for schedule(static) + /* ---- phase 2: the l2 norm over each q and k head, reading the rounded conv output -------- */ + REF_PAR_FOR(T * Hg * K * 2) for (int64_t th = 0; th < T * Hg * 2; ++th) { const int64_t which = th / (T * Hg); const int64_t rest = th % (T * Hg); @@ -265,9 +253,9 @@ int ref_gdn_conv_prep(const RadArgs* a, RadStream) { } /* ---- phase 3: the gate, its per-chunk cumsum, and beta ----------------------------------- */ - /* The cumsum is per CHUNK and per sequence, because that is what the scan consumes: g[j] is - * the decay from the start of j's chunk up to and including j. */ - #pragma omp parallel for schedule(static) + /* The cumsum restarts per chunk and per sequence, as the scan consumes it: g[j] is the decay + * from the start of j's chunk through j. */ + REF_PAR_FOR(T * H * 4) for (int64_t nh = 0; nh < N * H; ++nh) { const int64_t n = nh / H, h = nh % H; const int64_t bos = cu_at(cu, n), slen = cu_at(cu, n + 1) - bos; @@ -287,11 +275,11 @@ int ref_gdn_conv_prep(const RadArgs* a, RadStream) { } /* ---- phase 4: rewrite the conv state from the sequence's last width-1 tokens -------------- */ - /* After phase 1, so the history it overwrites has already been read. A sequence shorter than - * width-1 keeps what the old state held in front of its tokens, which is what makes chunked - * prefill work: the second chunk of a sequence continues from the first. */ + /* After phase 1, which has read the history this overwrites. A sequence shorter than width-1 + * keeps the old state in front of its tokens, so a later prefill chunk continues from the + * earlier one. */ if (cs->data && width > 1) { - #pragma omp parallel for schedule(static) + REF_PAR_FOR(N * conv_dim * width) for (int64_t nc = 0; nc < N * conv_dim; ++nc) { const int64_t n = nc / conv_dim, c = nc % conv_dim; const int64_t bos = cu_at(cu, n), slen = cu_at(cu, n + 1) - bos; @@ -312,14 +300,11 @@ int ref_gdn_conv_prep(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------------ gdn_conv_update */ -/* The same convolution for a decode step, against the rolling window. See ref_ops.h for the - * contract; the two things that matter are that the READ starts at num_accepted-1 and that the - * rewrite shifts the buffer down by one so the next step can do the same. A rejection is a change - * of read offset, not a recompute (spec §10), and that is the whole reason this is a separate - * entry point rather than a flag on the prefill one. +/* The same convolution for a decode step, against the rolling window (contract in ref_ops.h): the + * read starts at num_accepted-1, and the rewrite shifts the buffer down by one. A rejection changes + * the read offset instead of recomputing (spec §10). * - * No l2 norm here: on the decode path the recurrent update does it, which is where libr4d puts it - * too. */ + * No l2 norm: on the decode path the recurrent update does it, as in libr4d. */ int ref_gdn_conv_update(const RadArgs* a, RadStream) { if (a->n_t < 10) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *w = &a->t[1], *cs = &a->t[3], *cu = &a->t[6]; @@ -338,7 +323,7 @@ int ref_gdn_conv_update(const RadArgs* a, RadStream) { const int64_t N = numel(cu) - 1; if (N <= 0) return RAD_E_SHAPE; const int64_t T = cu_at(cu, N); - if (T <= 0) return RAD_OK; + if (T <= 0) return RAD_E_SHAPE; const int64_t Hg = numel(q) / (T * K); const int64_t H = numel(v) / (T * V); if (Hg <= 0 || H <= 0 || H % Hg != 0) return RAD_E_SHAPE; @@ -350,9 +335,8 @@ int ref_gdn_conv_update(const RadArgs* a, RadStream) { int64_t state_len = 0; const V3 cvs = conv_state_view(cs, conv_dim, width, &state_len); - /* The window this step needs: the largest read offset plus the history, and the largest write - * slot. Both are checked here rather than clamped, because a cache that is too shallow is a - * caller bug whose symptom would otherwise be a silently truncated history. */ + /* Check (not clamp) the read window and the last write slot against the state depth; a too + * shallow cache is a caller bug that would otherwise silently truncate history. */ for (int64_t n = 0; n < N; ++n) { const int64_t slen = cu_at(cu, n + 1) - cu_at(cu, n); const int64_t off = nacc ? ld_int(nacc->dtype, nacc->data, offlin(nacc, n)) - 1 : 0; @@ -361,10 +345,9 @@ int ref_gdn_conv_update(const RadArgs* a, RadStream) { if (width > 1 && (width - 2) + slen > state_len) return RAD_E_SHAPE; } - const V3 qv = v3(q, Hg, K), kv = v3(k, Hg, K), vv = v3(v, H, V); - const V2 wv = v2(w, width); + const ConvIO io{ x, w, bias, q, k, v, xrow, xcol, Hg, H, K, V, width }; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(T * conv_dim * width) for (int64_t nc = 0; nc < N * conv_dim; ++nc) { const int64_t n = nc / conv_dim, c = nc % conv_dim; const int64_t bos = cu_at(cu, n), slen = cu_at(cu, n + 1) - bos; @@ -374,31 +357,11 @@ int ref_gdn_conv_update(const RadArgs* a, RadStream) { const int64_t off = nacc ? ld_int(nacc->dtype, nacc->data, offlin(nacc, n)) - 1 : 0; float hist[REF_CONV_HIST_MAX]; - const int64_t st = width - 1; - for (int64_t i = 0; i < st; ++i) hist[i] = ldt(cs, at3(cvs, slot, c, off + i)); + for (int64_t i = 0; i < width - 1; ++i) hist[i] = ldt(cs, at3(cvs, slot, c, off + i)); + conv_channel(io, c, bos, slen, hist); - const RadTensor* out; - V3 ov; - int64_t oh, od; - if (c < Hg * K) { out = q; ov = qv; oh = c / K; od = c % K; } - else if (c < 2 * Hg * K) { out = k; ov = kv; oh = (c - Hg * K) / K; od = (c - Hg * K) % K; } - else { out = v; ov = vv; oh = (c - 2 * Hg * K) / V; - od = (c - 2 * Hg * K) % V; } - - const float bs = bias ? ldt(bias, c * laststride(bias)) : 0.0f; - for (int64_t t = 0; t < slen; ++t) { - float acc = bs; - for (int64_t j = 0; j < width; ++j) { - const int64_t src = t - (width - 1) + j; - const float val = src >= 0 ? ldt(x, (bos + src) * xrow + c * xcol) - : hist[src + width - 1]; - acc += val * ldt(w, at2(wv, c, j)); - } - stt(out, at3(ov, bos + t, oh, od), act_silu(acc)); - } - - /* Shift down by one: the tail of the old history, then this step's tokens. Reading before - * writing is what makes the in-place update safe, and the history is already in registers. */ + /* Shift down by one: the tail of the old history, then this step's tokens. Safe in place + * because the history was read into `hist` first. */ if (width > 1) { for (int64_t i = 0; i + 1 < width - 1; ++i) stt(cs, at3(cvs, slot, c, i), hist[i + 1]); @@ -413,29 +376,25 @@ int ref_gdn_conv_update(const RadArgs* a, RadStream) { /* ------------------------------------------------------------------ gdn_kkt_solve */ /* A = (I + strict_lower(diag(beta) . K K^T . e^{g_i - g_j}))^{-1}, per chunk, per v head. * - * The decay is applied PER ELEMENT as e^{g_i - g_j} rather than split about a per-chunk reference. - * Only i > j is kept and g decreases along the chunk, so the difference is always <= 0 and the - * direct form cannot overflow at any span -- which the split form can, on its own, at spans this - * model actually reaches (libr4d's r4d_gdn_kkt_solve says the same at length). + * The decay is applied per element as e^{g_i - g_j}, not split about a per-chunk reference: only + * i > j is kept and g decreases along the chunk, so the exponent is <= 0 and cannot overflow (see + * the file header and libr4d's r4d_gdn_kkt_solve). * - * The inverse is a forward substitution rather than libr4d's blocked 16 -> 32 -> 64 WMMA merge. - * The two agree exactly: I + M is unit lower triangular, so its inverse is unique and the - * substitution computes it in fp32, which is what libr4d's diagonal blocks do too. */ + * The inverse is a forward substitution instead of libr4d's blocked 16 -> 32 -> 64 WMMA merge. I + M + * is unit lower triangular, so its inverse is unique; both compute it in fp32. */ int ref_gdn_kkt_solve(const RadArgs* a, RadStream) { if (!have(a, 5)) return RAD_E_INVAL; const RadTensor *k = &a->t[0], *beta = &a->t[1], *g = &a->t[2], *cu = &a->t[3], *A = &a->t[4]; const int64_t K = p_int(a, "head_k", 0); - /* `chunk` is RAD_DERIVED, so a caller who did not pin it and resolved to ref (which declares - * no RAD_C_EQ for it) arrives without the key. Here the operand says: A is [T, heads, chunk] - * and the caller sized it, which is this plugin's rule for every other extent too. */ + /* `chunk` is RAD_DERIVED and may be absent; here A's shape [T, heads, chunk] carries it. */ const int64_t chunk = p_int(a, "chunk", A->rank >= 3 ? A->shape[A->rank - 1] : 0); if (K <= 0 || chunk <= 0) return RAD_E_SHAPE; const int64_t N = numel(cu) - 1; if (N <= 0) return RAD_E_SHAPE; const int64_t T = cu_at(cu, N); - if (T <= 0) return RAD_OK; + if (T <= 0) return RAD_E_SHAPE; const int64_t H = numel(beta) / T; const int64_t Hg = numel(k) / (T * K); if (H <= 0 || Hg <= 0 || H % Hg != 0) return RAD_E_SHAPE; @@ -445,33 +404,49 @@ int ref_gdn_kkt_solve(const RadArgs* a, RadStream) { const V3 kv = v3(k, Hg, K), Av = v3(A, H, chunk); const V2 gv = v2(g, H), bv = v2(beta, H); - #pragma omp parallel for schedule(static) + /* The chunk's keys are widened and transposed first, so the dot products and the + * substitution run across j in vector lanes; each element's chain keeps its order. */ + REF_PAR_FOR(T * H * chunk * K) for (int64_t nh = 0; nh < N * H; ++nh) { const int64_t n = nh / H, h = nh % H, hk = h / grp; const int64_t bos = cu_at(cu, n), slen = cu_at(cu, n + 1) - bos; - float* wsp = ws_get((size_t)(chunk * chunk + chunk)); - float* Am = wsp; /* [chunk, chunk] the inverse, in fp32 */ - float* row = wsp + chunk * chunk; + float* wsp = ws_get((size_t)(chunk * chunk + 3 * chunk + 2 * chunk * K)); + float* Am = wsp; /* [chunk, chunk] the inverse, in fp32 */ + float* row = Am + chunk * chunk; /* [chunk] */ + float* s = row + chunk; /* [chunk] */ + float* gc = s + chunk; /* [chunk] */ + float* kc = gc + chunk; /* [chunk, K] */ + float* kT = kc + chunk * K; /* [K, chunk] */ for (int64_t c0 = 0; c0 < slen; c0 += chunk) { const int64_t L = (c0 + chunk < slen) ? chunk : slen - c0; + for (int64_t j = 0; j < L; ++j) { + const int64_t tj = bos + c0 + j; + gc[j] = ldt(g, at2(gv, tj, h)); + for (int64_t d = 0; d < K; ++d) { + kc[j * K + d] = ldt(k, at3(kv, tj, hk, d)); + kT[d * chunk + j] = kc[j * K + d]; + } + } for (int64_t i = 0; i < L; ++i) { const int64_t ti = bos + c0 + i; const float bi = ldt(beta, at2(bv, ti, h)); - const float gi = ldt(g, at2(gv, ti, h)); - for (int64_t j = 0; j < i; ++j) { - const int64_t tj = bos + c0 + j; - float dot = 0.0f; - for (int64_t d = 0; d < K; ++d) - dot += ldt(k, at3(kv, ti, hk, d)) * ldt(k, at3(kv, tj, hk, d)); - row[j] = bi * dot * ref_exp(gi - ldt(g, at2(gv, tj, h))); + const float gi = gc[i]; + for (int64_t j = 0; j < i; ++j) row[j] = 0.0f; + for (int64_t d = 0; d < K; ++d) { + const float kd = kc[i * K + d]; + const float* kr = kT + d * chunk; + for (int64_t j = 0; j < i; ++j) row[j] += kd * kr[j]; } + for (int64_t j = 0; j < i; ++j) row[j] = bi * row[j] * ref_exp(gi - gc[j]); /* (I + M) A = I, row by row: A[i][j] = delta - sum_{j<=lt[4], *beta = &a->t[5], *cu = &a->t[7]; const RadTensor *o = &a->t[8], *ht = &a->t[9]; const RadTensor* h0 = t_in(a, 6); - /* THE STATE SLOT, when the caller keeps its recurrent states in a pool the batch does not - * index positionally. Absent, a row owns slot n, which is correct only where slots are handed - * out in batch order. */ + /* The state slot, for a state pool not indexed in batch order. Absent, row n owns slot n. */ const RadTensor* sidx = t_in(a, 10); if (!q->data || !k->data || !v->data || !A->data || !g->data || !beta->data || !cu->data || !o->data) return RAD_E_INVAL; const int64_t K = p_int(a, "head_k", 0), V = p_int(a, "head_v", 0); - /* RAD_DERIVED, and A is [T, heads, chunk] -- see gdn_kkt_solve, which writes the same tensor. */ + /* RAD_DERIVED; A is [T, heads, chunk], as gdn_kkt_solve writes it. */ const int64_t chunk = p_int(a, "chunk", A->rank >= 3 ? A->shape[A->rank - 1] : 0); const float scale = p_f32(a, "scale", 1.0f); if (K <= 0 || V <= 0 || chunk <= 0) return RAD_E_SHAPE; @@ -504,7 +477,7 @@ int ref_gdn_chunk_scan(const RadArgs* a, RadStream) { const int64_t N = numel(cu) - 1; if (N <= 0) return RAD_E_SHAPE; const int64_t T = cu_at(cu, N); - if (T <= 0) return RAD_OK; + if (T <= 0) return RAD_E_SHAPE; const int64_t H = numel(beta) / T; const int64_t Hg = numel(q) / (T * K); if (H <= 0 || Hg <= 0 || H % Hg != 0) return RAD_E_SHAPE; @@ -523,103 +496,173 @@ int ref_gdn_chunk_scan(const RadArgs* a, RadStream) { const V4 h0v = h0 ? v4(h0, H, V, K) : V4{ nullptr, 0, 0, 0, 0 }; const V4 htv = ht->data ? v4(ht, H, V, K) : V4{ nullptr, 0, 0, 0, 0 }; - #pragma omp parallel for schedule(static) + /* The state is held transposed, St[d][e], and the chunk's operands widened to f32 first, so + * every chain below runs across the V value columns in vector lanes. Each output element is + * still the same chain in the same order: the u, Vp, o and S sums over d or j ascending, and + * the products parenthesised as the formulas above write them. */ + REF_PAR_FOR(T * H * (K + chunk) * V) for (int64_t nh = 0; nh < N * H; ++nh) { const int64_t n = nh / H, h = nh % H, hk = h / grp; const int64_t bos = cu_at(cu, n), slen = cu_at(cu, n + 1) - bos; - /* COLUMN 0 IS THE STATE. A row may be wider -- a decode kernel serving speculation asks - * for scratch beside it -- and the scan writes the state and nothing else. */ + /* Column 0 of a state_idx row is the state slot. Rows may be wider (speculative decode + * keeps extra slots beside it); the scan writes only column 0's. */ const int64_t sw = sidx && sidx->rank >= 1 ? sidx->stride[0] : 1; const int64_t sn = sidx ? ld_int(sidx->dtype, sidx->data, n * sw) : n; if (sn < 0) continue; /* a padded row owns no state */ - /* One workspace request, carved up by hand -- a second ws_get() may reallocate and - * invalidate the first pointer (ref_common.h). */ - const size_t need = (size_t)(V * K + chunk * V + chunk * V + chunk); + /* One workspace request, carved up by hand (see ws_get in ref_common.h). */ + const size_t need = (size_t)(K * V + 3 * chunk * V + 3 * chunk * K + chunk * chunk + + 3 * chunk + 2 * V); float* wsp = ws_get(need); - float* S = wsp; /* [V, K] the recurrent state */ - float* Wm = S + V * K; /* [chunk, V] */ - float* Vp = Wm + chunk * V; /* [chunk, V] */ - float* row = Vp + chunk * V; /* [chunk] one row of sA */ + float* St = wsp; /* [K, V] the recurrent state, transposed */ + float* Wm = St + K * V; /* [chunk, V] */ + float* Vp = Wm + chunk * V; /* [chunk, V] */ + float* vc = Vp + chunk * V; /* [chunk, V] v, widened */ + float* kc = vc + chunk * V; /* [chunk, K] k, widened */ + float* qc = kc + chunk * K; /* [chunk, K] q, widened */ + float* kT = qc + chunk * K; /* [K, chunk] k, transposed */ + float* Ac = kT + chunk * K; /* [chunk, chunk] A, widened */ + float* gc = Ac + chunk * chunk; /* [chunk] g */ + float* bc = gc + chunk; /* [chunk] beta */ + float* row = bc + chunk; /* [chunk] one row of sA */ + float* acc = row + chunk; /* [V] */ + float* inr = acc + V; /* [V] */ for (int64_t e = 0; e < V; ++e) for (int64_t d = 0; d < K; ++d) - S[e * K + d] = h0 ? ldt(h0, at4(h0v, sn, h, e, d)) : 0.0f; + St[d * V + e] = h0 ? ldt(h0, at4(h0v, sn, h, e, d)) : 0.0f; for (int64_t c0 = 0; c0 < slen; c0 += chunk) { const int64_t L = (c0 + chunk < slen) ? chunk : slen - c0; - const float glast = ldt(g, at2(gv, bos + c0 + L - 1, h)); + for (int64_t j = 0; j < L; ++j) { + const int64_t tj = bos + c0 + j; + gc[j] = ldt(g, at2(gv, tj, h)); + bc[j] = ldt(beta, at2(bv, tj, h)); + for (int64_t d = 0; d < K; ++d) { + kc[j * K + d] = ldt(k, at3(kv, tj, hk, d)); + qc[j * K + d] = ldt(q, at3(qv, tj, hk, d)); + kT[d * chunk + j] = kc[j * K + d]; + } + for (int64_t e = 0; e < V; ++e) vc[j * V + e] = ldt(v, at3(vv, tj, h, e)); + for (int64_t i = 0; i <= j; ++i) Ac[j * chunk + i] = ldt(A, at3(Av, tj, h, i)); + } + const float glast = gc[L - 1]; /* W = beta . (V - e^{g_j} . (K S^T)) */ for (int64_t j = 0; j < L; ++j) { - const int64_t tj = bos + c0 + j; - const float ge = ref_exp(ldt(g, at2(gv, tj, h))); - const float bt = ldt(beta, at2(bv, tj, h)); - for (int64_t e = 0; e < V; ++e) { - float u = 0.0f; - for (int64_t d = 0; d < K; ++d) - u += ldt(k, at3(kv, tj, hk, d)) * S[e * K + d]; - Wm[j * V + e] = bt * (ldt(v, at3(vv, tj, h, e)) - ge * u); + const float ge = ref_exp(gc[j]); + for (int64_t e = 0; e < V; ++e) acc[e] = 0.0f; + for (int64_t d = 0; d < K; ++d) { + const float kd = kc[j * K + d]; + const float* sr = St + d * V; + for (int64_t e = 0; e < V; ++e) acc[e] += kd * sr[e]; } + for (int64_t e = 0; e < V; ++e) + Wm[j * V + e] = bc[j] * (vc[j * V + e] - ge * acc[e]); } /* V' = A W, with A unit lower triangular so only j <= i contributes. */ for (int64_t i = 0; i < L; ++i) { - const int64_t ti = bos + c0 + i; - for (int64_t e = 0; e < V; ++e) { - float s = 0.0f; - for (int64_t j = 0; j <= i; ++j) - s += ldt(A, at3(Av, ti, h, j)) * Wm[j * V + e]; - Vp[i * V + e] = s; + float* vp = Vp + i * V; + for (int64_t e = 0; e < V; ++e) vp[e] = 0.0f; + for (int64_t j = 0; j <= i; ++j) { + const float aij = Ac[i * chunk + j]; + const float* wr = Wm + j * V; + for (int64_t e = 0; e < V; ++e) vp[e] += aij * wr[e]; } } /* O = scale . e^{g_i} . (Q S^T) + sA V' */ for (int64_t i = 0; i < L; ++i) { const int64_t ti = bos + c0 + i; - const float gi = ldt(g, at2(gv, ti, h)); + const float gi = gc[i]; const float ge = ref_exp(gi); + for (int64_t j = 0; j <= i; ++j) row[j] = 0.0f; + for (int64_t d = 0; d < K; ++d) { + const float qd = qc[i * K + d]; + const float* kr = kT + d * chunk; + for (int64_t j = 0; j <= i; ++j) row[j] += qd * kr[j]; + } + for (int64_t j = 0; j <= i; ++j) row[j] = scale * ref_exp(gi - gc[j]) * row[j]; + for (int64_t e = 0; e < V; ++e) inr[e] = 0.0f; + for (int64_t d = 0; d < K; ++d) { + const float qd = qc[i * K + d]; + const float* sr = St + d * V; + for (int64_t e = 0; e < V; ++e) inr[e] += qd * sr[e]; + } + const float sg = scale * ge; + for (int64_t e = 0; e < V; ++e) acc[e] = sg * inr[e]; for (int64_t j = 0; j <= i; ++j) { - const int64_t tj = bos + c0 + j; - float p = 0.0f; - for (int64_t d = 0; d < K; ++d) - p += ldt(q, at3(qv, ti, hk, d)) * ldt(k, at3(kv, tj, hk, d)); - row[j] = scale * ref_exp(gi - ldt(g, at2(gv, tj, h))) * p; - } - for (int64_t e = 0; e < V; ++e) { - float inter = 0.0f; - for (int64_t d = 0; d < K; ++d) - inter += ldt(q, at3(qv, ti, hk, d)) * S[e * K + d]; - float s = scale * ge * inter; - for (int64_t j = 0; j <= i; ++j) s += row[j] * Vp[j * V + e]; - stt(o, at3(ov, ti, h, e), s); + const float rj = row[j]; + const float* vp = Vp + j * V; + for (int64_t e = 0; e < V; ++e) acc[e] += rj * vp[e]; } + for (int64_t e = 0; e < V; ++e) stt(o, at3(ov, ti, h, e), acc[e]); } /* S = e^{g_last} S + V'^T (e^{g_last - g_j} . K) */ - for (int64_t e = 0; e < V; ++e) - for (int64_t d = 0; d < K; ++d) { - float s = ref_exp(glast) * S[e * K + d]; - for (int64_t j = 0; j < L; ++j) { - const int64_t tj = bos + c0 + j; - const float gs = ref_exp(glast - ldt(g, at2(gv, tj, h))); - s += Vp[j * V + e] * (gs * ldt(k, at3(kv, tj, hk, d))); - } - S[e * K + d] = s; + const float el = ref_exp(glast); + for (int64_t j = 0; j < L; ++j) { + const float gs = ref_exp(glast - gc[j]); + for (int64_t d = 0; d < K; ++d) kc[j * K + d] = gs * kc[j * K + d]; + } + for (int64_t d = 0; d < K; ++d) { + float* sr = St + d * V; + for (int64_t e = 0; e < V; ++e) sr[e] = el * sr[e]; + for (int64_t j = 0; j < L; ++j) { + const float gk = kc[j * K + d]; + const float* vp = Vp + j * V; + for (int64_t e = 0; e < V; ++e) sr[e] += vp[e] * gk; } + } } if (ht->data) for (int64_t e = 0; e < V; ++e) for (int64_t d = 0; d < K; ++d) - stt(ht, at4(htv, sn, h, e, d), S[e * K + d]); + stt(ht, at4(htv, sn, h, e, d), St[d * V + e]); } return RAD_OK; } +/* ------------------------------------------------------------------ the anchor state form + * + * docs/OPS.md `state_form`: under `anchor` a sequence keeps one committed state, and each step + * records its tokens' rank-1 update factors beside it; the next step replays the first + * `num_accepted` of them onto the state before running its own tokens. The cache layout is + * libr4d's (r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip), so either library can continue + * a cache the other wrote and an oracle can compare them: + * + * state_idx six columns: 0..2 the anchor, 3..5 the factor block. A paged caller's window can + * shift by -1, 0 or +1 pages a step; the anchor is published at column 2 and each + * factor copy is stamped with its column (1, 2, 3), so the next step finds the shift + * m - 1 from the stamp m at column 4 and reads the anchor at column 3 - m. A zeroed + * block reads as no shift. A non-paged caller names one slot in columns 0..2 and + * another in 3..5. + * factors per token, from the head's [V, K] block of the factor slot: the normalised k once per + * 32-row group of V, then v, then (g, beta) once per group, each group's rows + * replaying from their own copy; room for `tmax` tokens, the stamp just past them. + * + * libr4d's kernel is K = V = 128, where the block holds kTmax = 16 tokens and the stamp sits at + * 16 * fstr. Square heads from 64 up hold 16 too, so the layout is libr4d's wherever both serve + * it. A smaller head's block holds fewer tokens' factors (a 16 x 16 head: 7), so `tmax` is as many + * as fit before the stamp; a step, or an accepted prefix, longer than that is refused. */ +struct AnchorLayout { + static constexpr int64_t kTmax = 16; + int64_t groups, fstr, vb, gb, tmax, mark; + AnchorLayout(int64_t K, int64_t V) + : groups((V + 31) / 32), fstr(groups * K + V + 2 * groups), vb(groups * K), + gb(groups * K + V), tmax(std::min(kTmax, (V * K - 1) / fstr)), + mark(tmax * fstr) {} + /* The anchor's column, from the stamp at the factor block's `mark`. */ + int anchor_col(const RadTensor* st, int64_t fb) const { + const int m = (int)(ldt(st, fb + mark) + 0.5f) - 1; + return 3 - ((m >= 0 && m <= 2) ? m : 1); + } +}; + /* ------------------------------------------------------------------ gdn_recurrent_update */ -/* What decode runs where prefill runs the chunked scan, against the PAGED state cache: the initial - * state comes from the slot the last accepted token wrote and every candidate token writes its own - * slot, because which of them survives verification is not known until after this layer has run - * (ref_ops.h). The gated RMS norm is folded into the epilogue, which is where libr4d puts it too -- - * its workgroup owns the whole row. */ +/* Decode's counterpart of the chunked scan, against the paged state cache: the initial state comes + * from the slot the last accepted token wrote, and every candidate token writes its own slot since + * survivors are unknown until verification (ref_ops.h). The gated RMS norm is folded into the + * epilogue, as in libr4d, whose workgroup owns the whole row. */ int ref_gdn_recurrent_update(const RadArgs* a, RadStream) { if (a->n_t < 14) return RAD_E_INVAL; const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *av = &a->t[3], *bvt = &a->t[4]; @@ -631,26 +674,19 @@ int ref_gdn_recurrent_update(const RadArgs* a, RadStream) { const RadTensor* cu = t_in(a, 10); const RadTensor* z = t_in(a, 11); const RadTensor* nw = t_in(a, 12); - /* The out projection's quantiser, folded in. Optional and all-or-nothing; see the - * operand list in r4d_rows.cpp for why the group is the row. */ + /* The out projection's quantiser, folded in. Optional, all-or-nothing; see the operand list in + * r4d_rows.cpp for why the group is the row. */ const RadTensor* oq = (a->n_t > 14 && a->t[14].data) ? &a->t[14] : nullptr; const RadTensor* osc = (a->n_t > 15 && a->t[15].data) ? &a->t[15] : nullptr; if (!q->data || !k->data || !v->data || !av->data || !bvt->data || !state->data || !o->data || !cu) return RAD_E_INVAL; - /* `cu` BOUNDS THE SEQUENCES, exactly as it does on the sibling gdn_conv_update, which runs off - * the same tensor on the same step. Carrying the sequence count in the state index instead - * works only for a rectangular batch, and leaves a fast kernel -- which reads `cu[n]` before - * any null test -- with a null pointer. Ref reads the token spans from cu and falls back to - * the rectangular reading only for a caller whose cu is degenerate. */ - /* THE OTHER STATE CONTRACT IS DECLINED, NOT APPROXIMATED. Under "anchor" the cache holds one - * committed state a sequence plus a block of replay factors, and the accepted prefix is - * replayed onto it next step -- two slots whatever the draft depth. The `o` it produces is the - * same, so a comparison against this reference AGREES on every output and disagrees on the - * whole state, which reads as a broken kernel and is not one. A named refusal is the honest - * answer: RAD_E_UNSUPPORTED says "not this contract", where a number would say "wrong". */ + /* `cu` bounds the sequences, as on gdn_conv_update, which reads the same tensor on the same + * step. A sequence count carried in the state index only works for rectangular batches, and the + * fast kernels read `cu[n]` before any null test. */ const char* sf = p_str(a, "state_form", "per_candidate"); - if (sf && std::strcmp(sf, "per_candidate") != 0) return RAD_E_UNSUPPORTED; + const bool anchor = sf && std::strcmp(sf, "anchor") == 0; + if (!anchor && sf && std::strcmp(sf, "per_candidate") != 0) return RAD_E_UNSUPPORTED; const int64_t K = p_int(a, "head_k", 0), V = p_int(a, "head_v", 0); const float scale = p_f32(a, "scale", 1.0f); @@ -659,11 +695,11 @@ int ref_gdn_recurrent_update(const RadArgs* a, RadStream) { const float spthr = p_f32(a, "softplus_thr", 20.0f); static const char* kActs[] = { "silu", "sigmoid" }; const int nact = p_enum(a, "act", kActs, 2, 0); + if (nact != 0 && nact != 1) return RAD_E_INVAL; if (K <= 0 || V <= 0) return RAD_E_SHAPE; - /* The head count and the token count come off the operands: v is [T, head_v_count, head_v], - * so a rank-3 value tensor names both. `n_head_v` overrides it for a caller that hands a - * flattened view. */ + /* Head and token counts come from v, [T, head_v_count, head_v]; `n_head_v` overrides the head + * count for a flattened view. */ int64_t Hv = p_int(a, "n_head_v", 0); if (Hv <= 0) Hv = v->rank >= 3 ? v->shape[v->rank - 2] : 0; if (Hv <= 0) return RAD_E_SHAPE; @@ -673,9 +709,7 @@ int ref_gdn_recurrent_update(const RadArgs* a, RadStream) { if (Hg <= 0 || Hv % Hg != 0) return RAD_E_SHAPE; const int64_t grp = Hv / Hg; - /* N comes from cu and nothing else: cu is [N+1] and its length minus one IS the sequence - * count. Deriving N from state_idx and trusting cu to be at least as long is an off-by-one - * waiting to happen, because a state index may be wider than one column per sequence. */ + /* N comes only from cu ([N+1]); state_idx may have several columns per sequence. */ const int64_t n_seq = numel(cu) - 1; if (n_seq <= 0) return RAD_E_SHAPE; if (cu_at(cu, n_seq) != Tk) return RAD_E_SHAPE; @@ -688,39 +722,109 @@ int ref_gdn_recurrent_update(const RadArgs* a, RadStream) { const V3 zv = z ? v3_rows(z, Hv, V) : vv; const V2 a2 = v2(av, Hv), b2 = v2(bvt, Hv); const V2 si = sidx ? v2(sidx, sw) : V2{ nullptr, 0, 0 }; + const V4 stv = v4(state, Hv, V, K); - #pragma omp parallel for schedule(static) + /* The anchor form keeps its replay factors inside a head's [V, K] block of a state slot, at + * libr4d's offsets (AnchorLayout), so the block must be dense and hold every token's factors. */ + const AnchorLayout al(K, V); + if (anchor) { + if (!sidx || sw < 6) return RAD_E_SHAPE; + if (stv.s3 != 1 || stv.s2 != K) return RAD_E_STRIDE; + if (al.tmax < 1) return RAD_E_SHAPE; + for (int64_t n = 0; n < n_seq; ++n) { + const int64_t na = nacc ? ld_int(nacc->dtype, nacc->data, offlin(nacc, n)) : 1; + if (cu_at(cu, n + 1) - cu_at(cu, n) > al.tmax || na > al.tmax) return RAD_E_SHAPE; + } + } + + /* The state is held transposed, St[d][e], so the two state passes run across the V value + * columns in vector lanes; every chain over d keeps its order. */ + REF_PAR_FOR(Tk * Hv * K * V) for (int64_t nh = 0; nh < n_seq * Hv; ++nh) { const int64_t n = nh / Hv, h = nh % Hv, hk = h / grp; const int64_t bos = cu_at(cu, n), q_len = cu_at(cu, n + 1) - bos; - if (q_len <= 0) continue; + /* Under `anchor` a sequence with no rows this step still folds its accepted prefix in. */ + if (q_len <= 0 && !anchor) continue; const int64_t na = nacc ? ld_int(nacc->dtype, nacc->data, offlin(nacc, n)) : 1; const int64_t rd = na > 0 ? na - 1 : 0; - const int64_t slot_in = sidx ? ld_int(sidx->dtype, sidx->data, at2(si, n, rd < sw ? rd : sw - 1)) - : n; - if (slot_in < 0) continue; + int64_t col[6] = { 0, 0, 0, 0, 0, 0 }; + int64_t slot_in = 0; + if (anchor) { + for (int c = 0; c < 6; ++c) col[c] = ld_int(sidx->dtype, sidx->data, at2(si, n, c)); + bool pad = false; + for (int c = 0; c < 6; ++c) pad = pad || col[c] < 0; + if (pad) continue; + slot_in = col[al.anchor_col(state, at4(stv, col[4], h, 0, 0))]; + } else { + slot_in = sidx ? ld_int(sidx->dtype, sidx->data, at2(si, n, rd < sw ? rd : sw - 1)) : n; + if (slot_in < 0) continue; + } + /* The factor blocks: column 4's is read, and 3, 4 and 5 are written (each a page the + * window can shift onto). */ + const int64_t fb = anchor ? at4(stv, col[4], h, 0, 0) : 0; + const int64_t fbs[3] = { anchor ? at4(stv, col[3], h, 0, 0) : 0, fb, + anchor ? at4(stv, col[5], h, 0, 0) : 0 }; + const bool dup_f = anchor && (col[3] != col[4] || col[5] != col[4]); - const size_t need = (size_t)(V * K + 2 * K + 2 * V); + const size_t need = (size_t)(V * K + 2 * K + 3 * V); float* wsp = ws_get(need); - float* S = wsp; - float* qn = S + V * K; + float* St = wsp; /* [K, V] */ + float* qn = St + V * K; float* kn = qn + K; float* uu = kn + K; float* orow = uu + V; - - const int64_t sstride = state->rank >= 4 ? state->stride[0] : (int64_t)Hv * V * K; - const int64_t hstride = state->rank >= 4 ? state->stride[1] : (int64_t)V * K; - const int64_t vstride = state->rank >= 4 ? state->stride[2] : K; - const int64_t dstride = state->rank >= 4 ? state->stride[3] : 1; + float* sk2 = orow + V; for (int64_t e = 0; e < V; ++e) - for (int64_t d = 0; d < K; ++d) - S[e * K + d] = ldt(state, slot_in * sstride + h * hstride + e * vstride + - d * dstride); + for (int64_t d = 0; d < K; ++d) St[d * V + e] = ldt(state, at4(stv, slot_in, h, e, d)); const float alog = A_log ? ldt(A_log, h * laststride(A_log)) : 0.0f; const float dtb = dt_bias ? ldt(dt_bias, h * laststride(dt_bias)) : 0.0f; + /* The delta rule's state update for one token over the state rows [e0, e1): decay by + * exp(g), then S += beta (v - S k) k^T, `vrow(e)` reading v. A row's update reads only + * that row, k, g and beta. Shared by the token loop and the replay, so a replayed token + * updates the state exactly as the step that ran it did. */ + auto update = [&](float g, float bt, auto vrow, int64_t e0, int64_t e1) { + const float dec = ref_exp(g); + for (int64_t e = e0; e < e1; ++e) sk2[e] = 0.0f; + for (int64_t d = 0; d < K; ++d) { + float* sr = St + d * V; + const float kd = kn[d]; + for (int64_t e = e0; e < e1; ++e) { + sr[e] *= dec; + sk2[e] += sr[e] * kd; + } + } + for (int64_t e = e0; e < e1; ++e) uu[e] = bt * (vrow(e) - sk2[e]); + for (int64_t d = 0; d < K; ++d) { + float* sr = St + d * V; + const float kd = kn[d]; + for (int64_t e = e0; e < e1; ++e) sr[e] += uu[e] * kd; + } + }; + + if (anchor) { + /* Replay the previous step's accepted tokens from their factors, publish the advanced + * anchor at column 2, and stamp each factor copy with the column it sits in. */ + for (int64_t t = 0; t < na; ++t) { + const int64_t f = fb + t * al.fstr; + /* Each 32-row group of V replays from its own copy of k and its own (g, beta), + * as libr4d's kernel reads them. Every writer stores equal copies, so on a block + * a step wrote this is the same as reading one copy for all rows. */ + for (int64_t gi = 0; gi < al.groups; ++gi) { + for (int64_t d = 0; d < K; ++d) kn[d] = ldt(state, f + gi * K + d); + update(ldt(state, f + al.gb + 2 * gi), ldt(state, f + al.gb + 2 * gi + 1), + [&](int64_t e) { return ldt(state, f + al.vb + e); }, + 32 * gi, std::min(V, 32 * gi + 32)); + } + } + for (int64_t e = 0; e < V; ++e) + for (int64_t d = 0; d < K; ++d) + stt(state, at4(stv, col[2], h, e, d), St[d * V + e]); + for (int c = 0; c < 3; ++c) stt(state, fbs[c] + al.mark, (float)(c + 1)); + } + for (int64_t t = 0; t < q_len; ++t) { const int64_t tok = bos + t; const float gv = -ref_exp(alog) * @@ -740,23 +844,28 @@ int ref_gdn_recurrent_update(const RadArgs* a, RadStream) { kn[d] = ldt(k, at3(kv, tok, hk, d)) * ks; } - const float dec = ref_exp(gv); - for (int64_t e = 0; e < V; ++e) { - float sk2 = 0.0f; - for (int64_t d = 0; d < K; ++d) { - S[e * K + d] *= dec; - sk2 += S[e * K + d] * kn[d]; - } - uu[e] = bt * (ldt(v, at3(vv, tok, h, e)) - sk2); + update(gv, bt, [&](int64_t e) { return ldt(v, at3(vv, tok, h, e)); }, 0, V); + for (int64_t e = 0; e < V; ++e) orow[e] = 0.0f; + for (int64_t d = 0; d < K; ++d) { + const float* sr = St + d * V; + const float qd = qn[d]; + for (int64_t e = 0; e < V; ++e) orow[e] += sr[e] * qd; } - for (int64_t e = 0; e < V; ++e) { - float ss = 0.0f; - for (int64_t d = 0; d < K; ++d) { - S[e * K + d] += uu[e] * kn[d]; - ss += S[e * K + d] * qn[d]; + + /* This token's factors, for the next step to replay: the normalised k once per + * 32-row group, v, then the decay exponent and beta once per group. */ + if (anchor) + for (int c = 0; c < 3; ++c) { + if (c != 1 && !dup_f) continue; + const int64_t f = fbs[c] + t * al.fstr; + for (int64_t gi = 0; gi < al.groups; ++gi) { + for (int64_t d = 0; d < K; ++d) stt(state, f + gi * K + d, kn[d]); + stt(state, f + al.gb + 2 * gi, gv); + stt(state, f + al.gb + 2 * gi + 1, bt); + } + for (int64_t e = 0; e < V; ++e) + stt(state, f + al.vb + e, ldt(v, at3(vv, tok, h, e))); } - orow[e] = ss; - } /* The gated RMS norm, over the head's V channels. */ float sq2 = 0.0f; @@ -772,47 +881,32 @@ int ref_gdn_recurrent_update(const RadArgs* a, RadStream) { stt(o, at3(ov, tok, h, e), r); } - /* QUANTISE WHAT WAS WRITTEN, not what produced it: the standalone quant_act_fp8 this - * replaces read `o` back out of memory, so it saw the rounded store and not the f32. - * One group per (token, head), because head_v is the fp8 block width. */ + /* Quantise the stored `o`, not the f32 value, as the standalone quant_act_fp8 read it + * back from memory. One group per (token, head), since head_v is the fp8 block width. */ if (oq && osc) { - float amax = 0.0f; - for (int64_t e = 0; e < V; ++e) { - const float m = std::fabs(ldt(o, at3(ov, tok, h, e))); - if (m > amax) amax = m; - } - const float qsc = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f; - const float inv = 1.0f / qsc; const int64_t qb = rowoff(oq, tok, Hv * V), qs = laststride(oq); - for (int64_t e = 0; e < V; ++e) { - float u = ldt(o, at3(ov, tok, h, e)) * inv; - if (u > 448.0f) u = 448.0f; - if (u < -448.0f) u = -448.0f; - st_dt(oq->dtype, oq->data, qb + (h * V + e) * qs, u); - } + const float qsc = q8_group([&](int64_t e) { return ldt(o, at3(ov, tok, h, e)); }, + V, 448.0f, oq, qb + h * V * qs, qs); stt(osc, rowoff(osc, tok, Hv) + h * laststride(osc), qsc); } + if (anchor) continue; const int64_t so = sidx ? ld_int(sidx->dtype, sidx->data, at2(si, n, t < sw ? t : sw - 1)) : n; if (so >= 0) for (int64_t e = 0; e < V; ++e) - for (int64_t d = 0; d < K; ++d) - stt(state, so * sstride + h * hstride + e * vstride + d * dstride, - S[e * K + d]); + for (int64_t d = 0; d < K; ++d) stt(state, at4(stv, so, h, e, d), St[d * V + e]); } } return RAD_OK; } /* ------------------------------------------------------------------ gdn_gated_rmsnorm */ -/* out = x * rsqrt(mean_channels(x^2) + eps) * w * act(z), one row per (token, head). The prefill - * path's form of the epilogue the recurrent update folds in. */ -/* The gate has a third spelling the shared rowoff() cannot see. [tokens, heads, ch] it walks, and - * a flat [rows, ch] projection is its product; but a COLUMN SLICE of a wider projection row -- the - * fp8 delta net fuses [q|k|v|z] into one GEMM -- has heads*ch as its last axis, so rowoff reads it - * as a dense row and lands in the next token. Spelled out here rather than generalised there, - * because it is a property of THIS operand and not of every one. */ +/* out = x * rsqrt(mean_channels(x^2) + eps) * w * act(z), one row per (token, head): the prefill + * form of the epilogue the recurrent update folds in. */ +/* Row offset of the gate. rowoff() handles [tokens, heads, ch] and flat [rows, ch], but not a + * column slice of a wider row (the fp8 delta net fuses [q|k|v|z] into one GEMM), whose last axis is + * heads*ch; rowoff would read it as a dense row. */ static inline int64_t gate_rowoff(const RadTensor* t, int64_t r, int64_t ch) { if (t->rank == 2 && ch > 0 && t->shape[1] != ch && t->shape[1] % ch == 0) { const int64_t heads = t->shape[1] / ch; @@ -828,12 +922,13 @@ int ref_gdn_gated_rmsnorm(const RadArgs* a, RadStream) { const float eps = p_f32(a, "eps", 1e-6f); static const char* kActs[] = { "silu", "sigmoid" }; const int act = p_enum(a, "act", kActs, 2, 0); + if (act != 0 && act != 1) return RAD_E_INVAL; if (ch <= 0) return RAD_E_SHAPE; const int64_t rows = numel(x) / ch; if (rows <= 0 || numel(o) < rows * ch || numel(z) < rows * ch || numel(w) < ch) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * ch) for (int64_t r = 0; r < rows; ++r) { const int64_t xb = rowoff(x, r, ch), zb = gate_rowoff(z, r, ch), ob = rowoff(o, r, ch); const int64_t xs = laststride(x), zs = laststride(z), os = laststride(o); @@ -851,9 +946,9 @@ int ref_gdn_gated_rmsnorm(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------------ gdn_conv_recurrent_update */ -/* gdn_conv_update into a staging q, k and v, then gdn_recurrent_update over them: the fused op is - * DEFINED as the pair, so the reference is the pair and nothing is restated. The head geometry the - * staging needs comes off `o` ([T, Hv, head_v]) and `x` (2 Hg head_k + Hv head_v columns). */ +/* gdn_conv_update into staging q, k and v, then gdn_recurrent_update over them; the fused op is + * defined as the pair. Head geometry comes from `o` ([T, Hv, head_v]) and `x` + * (2 Hg head_k + Hv head_v columns). */ int ref_gdn_conv_recurrent_update(const RadArgs* a, RadStream st) { if (a->n_t < 16) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *o = &a->t[15]; @@ -865,8 +960,10 @@ int ref_gdn_conv_recurrent_update(const RadArgs* a, RadStream st) { if (conv_dim <= Hv * V || (conv_dim - Hv * V) % (2 * K)) return RAD_E_SHAPE; const int64_t Hg = (conv_dim - Hv * V) / (2 * K); - std::vector qb((size_t)(T * Hg * K)), kb((size_t)(T * Hg * K)), vb((size_t)(T * Hv * V)); - auto stage = [&](uint16_t* d, int64_t h, int64_t w) { + /* The staging takes x's dtype, so q, k and v round as the unfused pair's stores do. */ + const auto bytes = [&](int64_t n) { return (size_t)rad_dtype_bytes(x->dtype, n); }; + std::vector qb(bytes(T * Hg * K)), kb(bytes(T * Hg * K)), vb(bytes(T * Hv * V)); + auto stage = [&](uint8_t* d, int64_t h, int64_t w) { RadTensor t{}; t.data = d; t.dtype = x->dtype; t.rank = 3; t.shape[0] = T; t.shape[1] = h; t.shape[2] = w; @@ -891,15 +988,12 @@ int ref_gdn_conv_recurrent_update(const RadArgs* a, RadStream st) { int rc = ref_gdn_conv_update(&ca, st); if (rc != RAD_OK) return rc; - std::vector rp; - for (int i = 0; i < a->n_p; ++i) - if (std::strcmp(a->p[i].key, "conv_width")) rp.push_back(a->p[i]); /* q, k, v, a, b, A_log, dt_bias, state, state_idx, num_accepted, cu, z, norm_w, o, o_q, - * o_scale */ + * o_scale. The parameters pass as they are: the recurrence reads its own by name. */ RadTensor rt[16] = { tq, tk, tv, a->t[5], a->t[6], a->t[7], a->t[8], a->t[9], a->t[10], a->t[11], a->t[12], a->t[13], a->t[14], a->t[15], a->n_t > 16 ? a->t[16] : RadTensor{}, a->n_t > 17 ? a->t[17] : RadTensor{} }; RadArgs ra = *a; - ra.t = rt; ra.n_t = 16; ra.p = rp.data(); ra.n_p = (int)rp.size(); + ra.t = rt; ra.n_t = 16; return ref_gdn_recurrent_update(&ra, st); } diff --git a/libref/ref_gemm.cpp b/libref/ref_gemm.cpp index bf642575..2b1b141b 100644 --- a/libref/ref_gemm.cpp +++ b/libref/ref_gemm.cpp @@ -2,87 +2,84 @@ * * nt: C[M,N] = A[M,K] @ B[N,K]^T * - * B is stored TRANSPOSED because that is the layout every weight in a transformer already has, so - * both operands are k-contiguous and the inner loop is a dot product over k. + * B is stored transposed, the layout transformer weights already have, so both operands are + * k-contiguous and the inner loop is a dot product over k. * - * This is the one family where the per-element dtype switch would BE the cost -- one element is - * read per FLOP -- so the inner loop is templated on the operand dtypes and selected once per - * launch through a function pointer. Everything else in this plugin pays the switch. The cost of - * not doing it is not marginal: a single prefill chunk is on the order of 10^11 element loads even - * for a small model, and a switch on each of them turns minutes of work into hours - * (docs/IMPLEMENTATION.md). + * This is the one family where the per-element dtype switch would dominate (one element read per + * FLOP; a prefill chunk is ~10^11 loads even for a small model), so the inner loop is templated on + * the operand dtypes and selected once per launch through a function pointer + * (docs/IMPLEMENTATION.md). Everything else pays the switch. * - * Parallelism is over N, not M. A decode step is M=1 and a verify step is M<=64, so an M-major - * split would leave all but one core idle on exactly the shape the engine spends its life in; N is - * thousands in every GEMM a transformer issues. Each thread owns whole output elements, so the - * summation order does not depend on the thread count. + * Parallelism is over N, not M: decode is M=1 and verify M<=64, while N is thousands in every + * transformer GEMM. Each thread owns whole output elements, so summation order is independent of + * thread count. */ #include #include "ref_common.h" #include "ref_gemm.h" #include "ref_ops.h" +#include "ref_planes.h" using namespace ref; namespace { -/* `Mat`, `as_mat`, `row_stride`, `Scales` and `make_scales` live in ref_gemm.h, because the - * mixture-of-experts GEMM reads its operands and scale streams exactly the same way. */ - -/* ------------------------------------------------------------------ the unquantised core */ -template -static void gemm_plain(const Mat& A, const Mat& B, const RadTensor* Y, const RadTensor* bias, - int64_t M, int64_t N, int64_t K, float alpha) { +/* ------------------------------------------------------------------ the tiled driver */ +/* Y[m, n] = quant_dot(m, n) (+ bias[n]) over every output, in quant_tile's tiles (ref_gemm.h). + * Each tile is owned by one thread and every output's chain is fixed, so the result depends on + * neither the tiling nor the thread count. */ +template +static void gemm_tiles(const Mat& A, const Mat& B, const Scales& SA, const Scales& SB, + const RadTensor* Y, const RadTensor* bias, int64_t M, int64_t N, + int64_t K) { const int64_t ys_r = row_stride(Y, N); const int64_t ys_c = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1; - #pragma omp parallel for schedule(static) - for (int64_t n = 0; n < N; ++n) { - const void* bp = B.t->data; - const int64_t b0 = n * B.rs; - for (int64_t m = 0; m < M; ++m) { - const int64_t a0 = m * A.rs; - float acc = 0.0f; - for (int64_t k = 0; k < K; ++k) - acc += Cvt::ld(A.t->data, a0 + k * A.cs) * Cvt::ld(bp, b0 + k * B.cs); - if (bias) acc += ldt(bias, n * laststride(bias)); - stt(Y, m * ys_r + n * ys_c, acc * alpha); + const int64_t bs = bias ? laststride(bias) : 0; + const TileGrid tg = tile_grid(M, N); + std::vector rows((size_t)M); + for (int64_t m = 0; m < M; ++m) rows[(size_t)m] = m; + REF_PAR_REGION(M * N * K) + { + float* const ws = ws_get(tile_ws_floats(tg.rg)); + REF_FOR + for (int64_t it = 0; it < tg.items(); ++it) { + const int64_t n0 = (it / tg.rgc) * REF_NB, r0 = (it % tg.rgc) * tg.rg; + const int64_t nb = (n0 + REF_NB < N) ? REF_NB : N - n0; + const int64_t R = (r0 + tg.rg < M) ? tg.rg : M - r0; + const float* acc = quant_tile(A, B, SA, SB, rows.data() + r0, R, n0, nb, K, + ws); + for (int64_t r = 0; r < R; ++r) + for (int64_t j = 0; j < nb; ++j) { + float v = acc[r * REF_NB + j]; + if (bias) v += ldt(bias, (n0 + j) * bs); + stt(Y, (r0 + r) * ys_r + (n0 + j) * ys_c, v); + } } } } -/* The same loop with the switch left in. Anything the table below does not name lands here and is - * correct, just slow -- which is the deal this whole plugin makes. */ -static void gemm_plain_generic(const Mat& A, const Mat& B, const RadTensor* Y, - const RadTensor* bias, int64_t M, int64_t N, int64_t K, - float alpha) { - const int64_t ys_r = row_stride(Y, N); - const int64_t ys_c = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1; - const uint32_t da = A.t->dtype, db = B.t->dtype; - #pragma omp parallel for schedule(static) - for (int64_t n = 0; n < N; ++n) { - const int64_t b0 = n * B.rs; - for (int64_t m = 0; m < M; ++m) { - const int64_t a0 = m * A.rs; - float acc = 0.0f; - for (int64_t k = 0; k < K; ++k) - acc += ld_dt(da, A.t->data, a0 + k * A.cs) * ld_dt(db, B.t->data, b0 + k * B.cs); - if (bias) acc += ldt(bias, n * laststride(bias)); - stt(Y, m * ys_r + n * ys_c, acc * alpha); - } - } +/* ------------------------------------------------------------------ the unquantised core */ +/* The tiled driver with no scale streams: each output is acc += a * b over ascending k from + * zero, then the bias. */ +template +static void gemm_plain(const Mat& A, const Mat& B, const RadTensor* Y, const RadTensor* bias, + int64_t M, int64_t N, int64_t K) { + const Scales none = make_scales(nullptr, 0, K, false); + gemm_tiles(A, B, none, none, Y, bias, M, N, K); } typedef void (*PlainFn)(const Mat&, const Mat&, const RadTensor*, const RadTensor*, - int64_t, int64_t, int64_t, float); + int64_t, int64_t, int64_t); -#define REF_PLAIN_ROW(DA) \ - case DA: \ - switch (db) { \ - case RAD_F32: return &gemm_plain; \ - case RAD_F16: return &gemm_plain; \ - case RAD_BF16: return &gemm_plain; \ - case RAD_I8: return &gemm_plain; \ - default: return nullptr; \ +/* The dtype pairs with a compile-time loader; any other pair takes gemm_plain. */ +#define REF_PLAIN_ROW(DA) \ + case DA: \ + switch (db) { \ + case RAD_F32: return &gemm_plain, Fix>; \ + case RAD_F16: return &gemm_plain, Fix>; \ + case RAD_BF16: return &gemm_plain, Fix>; \ + case RAD_I8: return &gemm_plain, Fix>; \ + default: return &gemm_plain; \ } static PlainFn pick_plain(uint32_t da, uint32_t db) { @@ -91,87 +88,49 @@ static PlainFn pick_plain(uint32_t da, uint32_t db) { REF_PLAIN_ROW(RAD_F16) REF_PLAIN_ROW(RAD_BF16) REF_PLAIN_ROW(RAD_I8) - default: return nullptr; + default: return &gemm_plain; } } #undef REF_PLAIN_ROW /* ------------------------------------------------------------------ the quantised core - * `quant_dot` in ref_gemm.h is the DEFINITION of one quantised product -- how the group sub-sum is - * formed from the raw codes and in what order the two scales fold onto it. This template is that - * function unrolled over a whole plane with the loads dispatched at COMPILE time, which is the only - * difference: `Cvt
::ld` and `ld_dt(DT, ...)` return the same float for every dtype. - * - * SO THE TWO CAN DRIFT, and the thing that holds them together is a test rather than a comment: - * ref_test runs gemm_nt_q_gated -- which goes through `quant_dot` -- against gemm_nt_q followed by - * gated_quant_fp8, which comes through here, and requires the two byte-identical. */ -template + * `quant_dot` (ref_gemm.h) over a whole plane, with the loaders chosen at compile time where the + * pair is listed below. */ +template static void gemm_quant(const Mat& A, const Mat& B, const Scales& SA, const Scales& SB, const RadTensor* Y, const RadTensor* bias, - int64_t M, int64_t N, int64_t K, float alpha) { - const int64_t ys_r = row_stride(Y, N); - const int64_t ys_c = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1; + int64_t M, int64_t N, int64_t K) { const int64_t g = SB.group > 0 ? SB.group : K; - const int64_t ngrp = (K + g - 1) / g; - const bool coarse_a = !SA.p || SA.group >= g; - - #pragma omp parallel for schedule(static) - for (int64_t n = 0; n < N; ++n) { - const int64_t b0 = n * B.rs; - for (int64_t m = 0; m < M; ++m) { - const int64_t a0 = m * A.rs; - float acc = 0.0f; - for (int64_t gi = 0; gi < ngrp; ++gi) { - const int64_t k0 = gi * g, k1 = (k0 + g < K) ? k0 + g : K; - const float sb = SB.p ? SB.grp(n, gi) : 1.0f; - float sub = 0.0f; - if (coarse_a) { - for (int64_t k = k0; k < k1; ++k) - sub += Cvt::ld(A.t->data, a0 + k * A.cs) * - Cvt::ld(B.t->data, b0 + k * B.cs); - acc += sub * (SA.p ? SA.at(m, k0) : 1.0f) * sb; - } else { - for (int64_t k = k0; k < k1; ++k) - sub += Cvt::ld(A.t->data, a0 + k * A.cs) * SA.at(m, k) * - Cvt::ld(B.t->data, b0 + k * B.cs); - acc += sub * sb; - } - } - if (bias) acc += ldt(bias, n * laststride(bias)); - stt(Y, m * ys_r + n * ys_c, acc * alpha); - } + if (!SA.p || SA.group >= g) { + gemm_tiles(A, B, SA, SB, Y, bias, M, N, K); + return; } -} - -static void gemm_quant_generic(const Mat& A, const Mat& B, const Scales& SA, const Scales& SB, - const RadTensor* Y, const RadTensor* bias, - int64_t M, int64_t N, int64_t K, float alpha) { + /* An activation grid finer than the weight's, which quant_tile does not serve. */ const int64_t ys_r = row_stride(Y, N); const int64_t ys_c = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1; - - #pragma omp parallel for schedule(static) + REF_PAR_FOR(N * M * K) for (int64_t n = 0; n < N; ++n) for (int64_t m = 0; m < M; ++m) { - float acc = quant_dot(A, B, SA, SB, m, n, K); + float acc = quant_dot(A, B, SA, SB, m, n, K); if (bias) acc += ldt(bias, n * laststride(bias)); - stt(Y, m * ys_r + n * ys_c, acc * alpha); + stt(Y, m * ys_r + n * ys_c, acc); } } typedef void (*QuantFn)(const Mat&, const Mat&, const Scales&, const Scales&, const RadTensor*, - const RadTensor*, int64_t, int64_t, int64_t, float); + const RadTensor*, int64_t, int64_t, int64_t); -#define REF_QUANT_ROW(DA) \ - case DA: \ - switch (db) { \ - case RAD_I4: return &gemm_quant; \ - case RAD_I2: return &gemm_quant; \ - case RAD_FP4E2M1: return &gemm_quant; \ - case RAD_I8: return &gemm_quant; \ - case RAD_F8E4M3:return &gemm_quant; \ - case RAD_BF16: return &gemm_quant; \ - case RAD_F32: return &gemm_quant; \ - default: return nullptr; \ +#define REF_QUANT_ROW(DA) \ + case DA: \ + switch (db) { \ + case RAD_I4: return &gemm_quant, Fix>; \ + case RAD_I2: return &gemm_quant, Fix>; \ + case RAD_FP4E2M1: return &gemm_quant, Fix>; \ + case RAD_I8: return &gemm_quant, Fix>; \ + case RAD_F8E4M3: return &gemm_quant, Fix>; \ + case RAD_BF16: return &gemm_quant, Fix>; \ + case RAD_F32: return &gemm_quant, Fix>; \ + default: return &gemm_quant; \ } static QuantFn pick_quant(uint32_t da, uint32_t db) { @@ -180,36 +139,101 @@ static QuantFn pick_quant(uint32_t da, uint32_t db) { REF_QUANT_ROW(RAD_F8E4M3) REF_QUANT_ROW(RAD_BF16) REF_QUANT_ROW(RAD_F32) - default: return nullptr; + default: return &gemm_quant; } } #undef REF_QUANT_ROW -/* gemm_nt_bias's EPILOGUE, applied to what the GEMM stored: an activation, then a residual. Each - * step reads the stored value and stores its result, so every one of them is rounded to the - * output's dtype -- which is the unfused chain exactly: a linear layer's output, an activation of - * it, a residual sum, three tensors. `act` 0 none, 1 exact (erf) GELU, 2 tanh GELU. */ -static float gelu_erf(float x) { return 0.5f * x * (1.0f + std::erf(x * 0.70710678118654752f)); } -static float gelu_tanh(float x) { - const float k0 = 0.7978845608028654f, k1 = 0.044715f; - return 0.5f * x * (1.0f + std::tanh(k0 * (x + k1 * x * x * x))); -} - +/* gemm_nt_bias's epilogue, applied to what the GEMM stored: an activation, then a residual. Each + * step reads and stores, so each rounds to the output dtype, exactly as the unfused chain of three + * tensors would. `act`: 0 none, 1 exact (erf) GELU, 2 tanh GELU. */ static void gemm_epilogue(const RadTensor* Y, const RadTensor* res, int act, int64_t M, int64_t N) { const int64_t ys_r = row_stride(Y, N), ys_c = laststride(Y); const int64_t rs_r = res ? row_stride(res, N) : 0, rs_c = res ? laststride(res) : 0; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(M * N) for (int64_t m = 0; m < M; ++m) for (int64_t n = 0; n < N; ++n) { const int64_t o = m * ys_r + n * ys_c; - if (act == 1) stt(Y, o, gelu_erf(ldt(Y, o))); - else if (act == 2) stt(Y, o, gelu_tanh(ldt(Y, o))); + if (act == 1) stt(Y, o, act_gelu(ldt(Y, o))); + else if (act == 2) stt(Y, o, act_gelu_tanh(ldt(Y, o))); if (res) stt(Y, o, ldt(res, m * rs_r + n * rs_c) + ldt(Y, o)); } } -/* Shared entry for gemm_nt / gemm_nt_bias / logits_gemm. `nk_from` names which parameters carry N - * and K, because logits_gemm spells them n_vocab and n_embd. */ +/* ------------------------------------------------------------------ a joined head */ +/* Y = A B^T for a B of codes and one scale (ref_planes.h: ScaledRows), decoded a block of rows at + * a time into f32 and multiplied by the plain core. Each decoded element is the f32 the core's + * affine decoder gives, so the result is bit-identical to the same product over that decoder's + * f32 head, which is what a tool hands this plugin as the logical form. */ +static int gemm_scaled_rows(const Mat& ma, const RadTensor* Bt, const RadTensor* Y, + const RadTensor* bias, int64_t M, int64_t N, int64_t K) { + ScaledRows sr; + const int st = scaled_rows(Bt, N, K, &sr); + if (st != RAD_OK) return st; + /* Rows per block: about 16 MiB of f32, at least one tile. */ + int64_t ch = ((int64_t)1 << 22) / K; + ch = std::max(REF_NB, ch / REF_NB * REF_NB); + std::vector dec((size_t)(std::min(ch, N) * K)); + const int64_t ys_r = row_stride(Y, N), ys_c = laststride(Y); + const PlainFn plain = pick_plain(ma.t->dtype, RAD_F32); + for (int64_t n0 = 0; n0 < N; n0 += ch) { + const int64_t nb = std::min(ch, N - n0); + REF_PAR_FOR(nb * K) + for (int64_t r = 0; r < nb; ++r) + for (int64_t k = 0; k < K; ++k) dec[(size_t)(r * K + k)] = sr.at(n0 + r, k); + RadTensor Bb{}; + Bb.data = dec.data(); + Bb.dtype = RAD_F32; + Bb.rank = 2; Bb.shape[0] = nb; Bb.shape[1] = K; Bb.stride[0] = K; Bb.stride[1] = 1; + RadTensor Yb = *Y; + Yb.data = (uint8_t*)Y->data + rad_dtype_bytes(Y->dtype, n0 * ys_c); + Yb.rank = 2; Yb.shape[0] = M; Yb.shape[1] = nb; Yb.stride[0] = ys_r; Yb.stride[1] = ys_c; + RadTensor bb{}; + if (bias) { + bb = *bias; + bb.data = (uint8_t*)bias->data + rad_dtype_bytes(bias->dtype, n0 * laststride(bias)); + } + plain(ma, as_mat(&Bb, K), &Yb, bias ? &bb : nullptr, M, nb, K); + } + return RAD_OK; +} + +/* Shared entry for gemm_nt / gemm_nt_bias / logits_gemm. `nkey`/`kkey` name the parameters that + * carry N and K, since logits_gemm spells them n_vocab and n_embd. */ +/* Whether two operands' memory overlaps: from the first element to one past the last element + * their strides reach. A residual may be the output itself (an in-place residual add). */ +static bool spans_overlap(const RadTensor* a, const RadTensor* b) { + auto span = [](const RadTensor* t, const char** lo, const char** hi) { + int64_t last = 0; + for (uint32_t i = 0; i < t->rank; ++i) last += (t->shape[i] - 1) * t->stride[i]; + const int64_t eb = (rad_dtype_bits(t->dtype) + 7) / 8; + *lo = static_cast(t->data); + *hi = *lo + (last + 1) * eb; + }; + const char *alo, *ahi, *blo, *bhi; + span(a, &alo, &ahi); + span(b, &blo, &bhi); + return alo < bhi && blo < ahi; +} + +/* The residual as f32 [M, N], read before the product overwrites it when it is the output's own + * memory. Widening is exact for every float dtype, so the epilogue's sum is unchanged. */ +static RadTensor snapshot_res(const RadTensor* res, int64_t M, int64_t N, std::vector* buf) { + const int64_t rs_r = row_stride(res, N), rs_c = laststride(res); + buf->resize((size_t)(M * N)); + for (int64_t m = 0; m < M; ++m) + for (int64_t n = 0; n < N; ++n) (*buf)[(size_t)(m * N + n)] = ldt(res, m * rs_r + n * rs_c); + RadTensor t{}; + t.dtype = RAD_F32; + t.rank = 2; + t.shape[0] = M; + t.shape[1] = N; + t.stride[0] = N; + t.stride[1] = 1; + t.data = buf->data(); + return t; +} + static int gemm_nt_impl(const RadArgs* a, bool bias_operand, const char* nkey, const char* kkey) { /* gemm_nt_bias is a, b, bias, res?, y; the other two are a, b, y. */ const int nt = bias_operand ? 5 : 3; @@ -219,25 +243,139 @@ static int gemm_nt_impl(const RadArgs* a, bool bias_operand, const char* nkey, c const RadTensor* res = bias_operand ? t_in(a, 3) : nullptr; static const char* kActs[] = { "none", "gelu", "gelu_tanh" }; const int act = bias_operand ? p_enum(a, "act", kActs, 3, 0) : 0; + if (act < 0 || act > 2) return RAD_E_INVAL; const int64_t K = p_int(a, kkey, B->rank >= 2 ? B->shape[B->rank - 1] : 0); const int64_t N = p_int(a, nkey, B->rank >= 2 ? B->shape[B->rank - 2] : 0); if (K <= 0 || N <= 0) return RAD_E_SHAPE; const int64_t M = numel(Y) / N; if (M <= 0) return RAD_E_SHAPE; - if (numel(A) < M * K || numel(B) < N * K) return RAD_E_SHAPE; + /* A head of codes and scale, joined (ref_planes.h); its extents are its planes'. */ + const bool joined = is_joined(B); + if (numel(A) < M * K || (!joined && numel(B) < N * K)) return RAD_E_SHAPE; if (bias && numel(bias) < N) return RAD_E_SHAPE; if (res && numel(res) < M * N) return RAD_E_SHAPE; + std::vector res_buf; + RadTensor res_copy{}; + if (res && spans_overlap(res, Y)) { + res_copy = snapshot_res(res, M, N, &res_buf); + res = &res_copy; + } - const Mat ma = as_mat(A, M, K), mb = as_mat(B, N, K); - PlainFn fn = pick_plain(A->dtype, B->dtype); - if (fn) fn(ma, mb, Y, bias, M, N, K, 1.0f); - else gemm_plain_generic(ma, mb, Y, bias, M, N, K, 1.0f); + const Mat ma = as_mat(A, K); + if (joined) { + const int st = gemm_scaled_rows(ma, B, Y, bias, M, N, K); + if (st != RAD_OK) return st; + if (act || res) gemm_epilogue(Y, res, act, M, N); + return RAD_OK; + } + const Mat mb = as_mat(B, K); + pick_plain(A->dtype, B->dtype)(ma, mb, Y, bias, M, N, K); if (act || res) gemm_epilogue(Y, res, act, M, N); return RAD_OK; } +/* ------------------------------------------------------------------ the zero-point grids */ +/* gemm_nt_q over an asymmetric grid (ref_planes.h, ZpGrid): weight element (n, k) is + * (code - zero) * scale with one f16 scale and one integer zero per (row, `group` of K), read from + * `b_scale`'s joined planes. Each group's sub-sum is formed on the integer grid and scaled once, as + * quant_dot does for the symmetric grids: + * + * ZP_I8_ROW sub = sum(a * code) - zero * a_sum[g][m] exact integers below 2^24 + * acc += (sub * a_scale[m]) * scale + * ZP_I8_GROUP sub = sum(a * (code - zero)) exact + * acc += (sub * a_scale[m][g]) * scale + * ZP_F16 sub = sum over ascending k of a * (code - zero), each product exact in f32 + * acc += sub * scale + * + * `a` is already in column order (the caller undoes the step order). `a_sum` is quant_act_i8's, + * group-major [K/group][Mpad], Mpad = ceil(M/16)*16; the grid's zero is removed through it, as + * libr4d's kernels do, so it is required. Parts (`pb1`, `pb2`, the ParoQuant grids only): weight + * rows [0, e1), [e1, e2), [e2, N) meet copies 0, 1, 2 of the activation, side by side in `a` and in + * `a_scale`. */ +static int gemm_zp(const ZpGrid& zg, const RadTensor* A, const RadTensor* as_, + const RadTensor* B, const RadTensor* bs_, const RadTensor* asum, + const RadTensor* Y, int64_t M, int64_t N, int64_t K, int64_t group, + int64_t pb1, int64_t pb2) { + if (!is_joined(bs_)) return RAD_E_DTYPE; + const JPlane sc = jplane(bs_, "scale"), zp = jplane(bs_, "zero"); + if (!sc || !zp || !float_scale_dt(sc.dt) || !zero_dt(zp.dt)) return RAD_E_DTYPE; + if (B->dtype != zg.codes) return RAD_E_DTYPE; + if (group <= 0 || K % group) return RAD_E_SHAPE; + const int64_t G = K / group; + if (sc.rows != N || sc.cols != G || zp.rows != N || zp.cols != G) return RAD_E_SHAPE; + if (!rad_tensor_is_contiguous(B)) return RAD_E_STRIDE; + const int64_t brow = rad_enc_row_bytes(B->dtype, K); + const int cbits = rad_dtype_bits(B->dtype); + + /* The parts' row bounds and the activation's width. */ + const bool parted = pb1 > 0 || pb2 > 0; + if (parted && zg.act == ZP_I8_ROW) return RAD_E_UNSUPPORTED; + const int64_t e1 = pb1 > 0 ? std::min(pb1, N) : N; + const int64_t e2 = pb2 > 0 ? std::max(e1, std::min(pb2, N)) : N; + const int64_t parts = e2 < N ? 3 : (e1 < N ? 2 : 1); + if (parted && ((e1 % 16) || (e2 % 16))) return RAD_E_SHAPE; + const int64_t acols = parts * K; + if (numel(A) < M * acols) return RAD_E_SHAPE; + if (A->rank >= 2 && A->shape[A->rank - 1] != acols) return RAD_E_SHAPE; + const int64_t ars = row_stride(A, acols), acs = laststride(A); + + const bool i8 = zg.act != ZP_F16; + if (i8 && A->dtype != RAD_I8) return RAD_E_DTYPE; + if (!i8 && !float_scale_dt(A->dtype)) return RAD_E_DTYPE; + const int64_t mpad = (M + 15) / 16 * 16; + if (zg.act == ZP_I8_ROW) { + if (!as_ || numel(as_) < M) return RAD_E_INVAL; + if (!asum || numel(asum) < G * mpad) return RAD_E_INVAL; + } + if (zg.act == ZP_I8_GROUP && (!as_ || numel(as_) < M * parts * G)) return RAD_E_INVAL; + const int64_t sa_rs = as_ ? row_stride(as_, zg.act == ZP_I8_GROUP ? parts * G : 1) : 0; + const int64_t sa_cs = as_ ? laststride(as_) : 0; + const int64_t ys_r = row_stride(Y, N), ys_c = laststride(Y); + const int64_t asum_s = asum ? laststride(asum) : 0; + + REF_PAR_FOR(N * M * K) + for (int64_t n = 0; n < N; ++n) { + const int64_t part = n < e1 ? 0 : (n < e2 ? 1 : 2); + const uint8_t* crow = (const uint8_t*)B->data + n * brow; + std::vector q((size_t)K); + for (int64_t k = 0; k < K; ++k) q[(size_t)k] = (int32_t)rad_load_bits(crow, cbits, k); + for (int64_t m = 0; m < M; ++m) { + const int64_t ab = m * ars + part * K * acs; + float acc = 0.0f; + for (int64_t g = 0; g < G; ++g) { + const float sb = sc.at(n, g); + const int32_t z = (int32_t)zp.at(n, g); + const int64_t k0 = g * group; + float sub; + if (zg.act == ZP_F16) { + sub = 0.0f; + for (int64_t k = k0; k < k0 + group; ++k) + sub += ldt(A, ab + k * acs) * (float)(q[(size_t)k] - z); + acc += sub * sb; + continue; + } + int64_t is = 0; + const int8_t* ar = (const int8_t*)A->data; + if (zg.act == ZP_I8_ROW) { + for (int64_t k = k0; k < k0 + group; ++k) + is += (int64_t)ar[ab + k * acs] * q[(size_t)k]; + sub = (float)is - (float)z * ldt(asum, (g * mpad + m) * asum_s); + acc += sub * ldt(as_, m * sa_rs) * sb; + } else { + for (int64_t k = k0; k < k0 + group; ++k) + is += (int64_t)ar[ab + k * acs] * (q[(size_t)k] - z); + sub = (float)is; + acc += sub * ldt(as_, m * sa_rs + (part * G + g) * sa_cs) * sb; + } + } + stt(Y, m * ys_r + n * ys_c, acc); + } + } + return RAD_OK; +} + static int gemm_ntq_impl(const RadArgs* a, bool bias_operand) { const int nt = bias_operand ? 6 : 5; if (a->n_t < nt || !a->t[0].data || !a->t[2].data || !a->t[nt - 1].data) return RAD_E_INVAL; @@ -245,6 +383,18 @@ static int gemm_ntq_impl(const RadArgs* a, bool bias_operand) { const RadTensor* as_ = t_in(a, 1); const RadTensor* bs_ = t_in(a, 3); const RadTensor* bias = bias_operand ? t_in(a, 4) : nullptr; + /* The zero-point grids read `b_scale` joined and the w2a8 / w4a8_asym ones `a_sum` too + * (gemm_zp); they have no bias form. Elsewhere `a_sum` would remove a zero point the grid + * does not have, so a call passing it is refused rather than answered as if it were absent. + * `b_ref` is the per-row reference exponent an mxfp4 kernel folds its scales at; it is derived + * from `b_scale` and does not change the product, so it is accepted beside an e2m1 weight + * only. */ + const ZpGrid* zg = zp_grid(p_str(a, "dtype", nullptr)); + if (zg && bias_operand) return RAD_E_UNSUPPORTED; + if (!bias_operand) { + if (t_in(a, 5) && (!zg || zg->act != ZP_I8_ROW)) return RAD_E_UNSUPPORTED; + if (t_in(a, 6) && B->dtype != RAD_FP4E2M1) return RAD_E_UNSUPPORTED; + } const int64_t K = p_int(a, "K", B->rank >= 2 ? B->shape[B->rank - 1] : 0); const int64_t N = p_int(a, "N", B->rank >= 2 ? B->shape[B->rank - 2] : 0); @@ -254,12 +404,33 @@ static int gemm_ntq_impl(const RadArgs* a, bool bias_operand) { if (numel(A) < M * K || numel(B) < N * K) return RAD_E_SHAPE; if (bias && numel(bias) < N) return RAD_E_SHAPE; - /* PARTS (`pb1`, `pb2`): the weight's rows are [0, pb1), [pb1, pb2) and [pb2, N), each against - * its own copy of the activation -- a fused projection whose pieces were rotated separately - * (ParoQuant). The copies sit side by side in a row of `a`, so `a` is [M, parts * K] and its - * scale [M, parts * K / 128]; a part is the plain product over its rows, which is how it is - * computed. 0 leaves a bound out: no `pb1` is one part, no `pb2` ends the second at N. */ + /* quant_act_i8's codes arrive in the step order (ref_common.h); read them back into column + * order. */ + std::vector a_cols; + RadTensor Ac; + if (A->dtype == RAD_I8 && i8_steps_dtype(p_str(a, "dtype", nullptr))) { + if (K % 16) return RAD_E_SHAPE; + if (laststride(A) != 1) return RAD_E_STRIDE; + a_cols.resize((size_t)(M * K)); + for (int64_t m = 0; m < M; ++m) { + const int8_t* row = (const int8_t*)A->data + rowoff(A, m, K); + for (int64_t c = 0; c < K; ++c) a_cols[(size_t)(m * K + c)] = row[i8_step_pos(c)]; + } + Ac = *A; + Ac.data = a_cols.data(); + Ac.rank = 2; Ac.shape[0] = M; Ac.shape[1] = K; Ac.stride[0] = K; Ac.stride[1] = 1; + A = &Ac; + } + + /* Parts (`pb1`, `pb2`): weight rows [0, pb1), [pb1, pb2) and [pb2, N) each multiply their own + * copy of the activation, for a fused projection whose pieces were rotated separately + * (ParoQuant). The copies sit side by side, so `a` is [M, parts * K] and its scale + * [M, parts * K / 128]; each part is computed as a plain product over its rows. 0 omits a + * bound: no `pb1` is one part, no `pb2` ends the second at N. */ const int64_t pb1 = p_int(a, "pb1", 0), pb2 = p_int(a, "pb2", 0); + if (zg) + return gemm_zp(*zg, A, as_, B, bs_, t_in(a, 5), Y, M, N, K, p_int(a, "group", 0), pb1, + pb2); if (pb1 > 0 || pb2 > 0) { if (bias_operand || B->dtype != RAD_FP4E2M1 || A->rank < 2) return RAD_E_UNSUPPORTED; const int64_t e1 = pb1 > 0 ? std::min(pb1, N) : N; @@ -292,10 +463,8 @@ static int gemm_ntq_impl(const RadArgs* a, bool bias_operand) { Yp.data = (uint8_t*)Y->data + rad_dtype_bytes(Y->dtype, n0); Yp.rank = 2; Yp.shape[0] = M; Yp.shape[1] = n1 - n0; Yp.stride[0] = ys; Yp.stride[1] = 1; Scales SAp = make_scales(&Sp, M, K, false), SBp = make_scales(&Bsp, n1 - n0, K, true); - const Mat map_ = as_mat(&Ap, M, K), mbp = as_mat(&Bp, n1 - n0, K); - QuantFn fn = pick_quant(Ap.dtype, Bp.dtype); - if (fn) fn(map_, mbp, SAp, SBp, &Yp, nullptr, M, n1 - n0, K, 1.0f); - else gemm_quant_generic(map_, mbp, SAp, SBp, &Yp, nullptr, M, n1 - n0, K, 1.0f); + const Mat map_ = as_mat(&Ap, K), mbp = as_mat(&Bp, K); + pick_quant(Ap.dtype, Bp.dtype)(map_, mbp, SAp, SBp, &Yp, nullptr, M, n1 - n0, K); } return RAD_OK; } @@ -303,16 +472,13 @@ static int gemm_ntq_impl(const RadArgs* a, bool bias_operand) { const bool mx = B->dtype == RAD_FP4E2M1; Scales SA = make_scales(as_, M, K, false); Scales SB = make_scales(bs_, N, K, mx); - /* `group` is in the schema and is what the SELECTOR matches on; the loop uses the group the - * scale stream actually implies. They agree in every well-formed call, and where they do not - * the stream is the one that describes the bytes. */ + /* `group` is what the selector matches on; the loop uses the group the scale stream implies, + * which describes the bytes. A disagreement is refused. */ const int64_t gp = p_int(a, "group", 0); if (gp > 0 && SB.p && SB.group != gp) return RAD_E_SHAPE; - const Mat ma = as_mat(A, M, K), mb = as_mat(B, N, K); - QuantFn fn = pick_quant(A->dtype, B->dtype); - if (fn) fn(ma, mb, SA, SB, Y, bias, M, N, K, 1.0f); - else gemm_quant_generic(ma, mb, SA, SB, Y, bias, M, N, K, 1.0f); + const Mat ma = as_mat(A, K), mb = as_mat(B, K); + pick_quant(A->dtype, B->dtype)(ma, mb, SA, SB, Y, bias, M, N, K); return RAD_OK; } @@ -332,113 +498,77 @@ int ref_gemm_nt_q_bias(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------------ logits_gemm */ -/* The same arithmetic as gemm_nt, and a separate op anyway: lm_head is its own access class - * (RAD_ACCESS_VOCAB) and the sampler wants to fuse against it, so the two have to be selectable - * apart even when one kernel serves both (docs/OPS.md). N and K are spelled n_vocab and n_embd. */ +/* gemm_nt's arithmetic as a separate op: lm_head is its own access class (RAD_ACCESS_VOCAB) and + * the sampler fuses against it, so the two must be selectable apart (docs/OPS.md). N and K are + * spelled n_vocab and n_embd. */ int ref_logits_gemm(const RadArgs* a, RadStream) { return gemm_nt_impl(a, false, "n_vocab", "n_embd"); } /* ------------------------------------------------------------------ embed_lookup */ -/* A gather, not a GEMM, which is half of why it is its own op. A NEGATIVE token id writes a zero - * row -- that is the padding convention a batch with a short sequence needs. +/* A gather, not a GEMM. A negative token id writes a zero row (padding for short sequences). * - * `vocab_offset` (optional, default 0) makes the table THIS RANK'S SLICE of a vocab-parallel - * embedding: it covers global ids [vocab_offset, vocab_offset + n_vocab), ids stay global, and one - * outside the slice writes a zero row so that summing the ranks reconstructs x. See the schema. + * `vocab_offset` (optional, default 0) makes the table this rank's slice of a vocab-parallel + * embedding, covering global ids [vocab_offset, vocab_offset + n_vocab). Ids stay global; one + * outside the slice writes a zero row, so summing the ranks reconstructs x. * - * WITHOUT AN OFFSET AN ID AT OR ABOVE n_vocab STILL FAILS THE LAUNCH, because there it is a caller - * bug rather than another rank's token and a plausible embedding is the worst answer. With one, - * that check is not available to this kernel -- it cannot know the global vocabulary -- so it is - * the caller's, and the sampler and the tokeniser are both already bounded by it. */ -int ref_embed_lookup(const RadArgs* a, RadStream) { - if (!have(a, 3)) return RAD_E_INVAL; - const RadTensor *tok = &a->t[0], *wte = &a->t[1], *x = &a->t[2]; + * When this rank holds the whole vocabulary, an id >= n_vocab fails the launch: it is a caller bug, + * and a plausible embedding is the worst answer. Under a split the kernel cannot know the global + * vocabulary, so the check is the caller's (the sampler and tokeniser are bounded by it). + * + * Every row read is multiplied by `factor`: embed_lookup's `mult`, embed_lookup_q's table scale. */ +static int embed_gather(const RadArgs* a, const RadTensor* tok, const RadTensor* wte, + const RadTensor* x, float factor) { const int64_t n_embd = p_int(a, "n_embd", wte->rank >= 2 ? wte->shape[wte->rank - 1] : 0); const int64_t n_vocab = p_int(a, "n_vocab", wte->rank >= 2 ? wte->shape[wte->rank - 2] : 0); const int64_t voff = p_int(a, "vocab_offset", 0); - const float mult = p_f32(a, "mult", 1.0f); if (n_embd <= 0 || n_vocab <= 0 || voff < 0) return RAD_E_SHAPE; const int64_t M = numel(x) / n_embd; if (M <= 0 || numel(tok) < M || numel(wte) < n_vocab * n_embd) return RAD_E_SHAPE; - /* Validated before the loop, because an OpenMP body cannot return. - * - * THE GUARD IS ABOUT HOLDING THE WHOLE VOCABULARY, NOT ABOUT THE OFFSET BEING ZERO. An id at - * or above n_vocab is a caller's mistake only where this rank holds every row; under a - * vocab-parallel split it is another rank's token, and the loop below writes it as a zero row - * exactly as it writes the padding id, which is what makes summing the ranks reconstruct x. - * Rank 0 of such a split has offset 0 -- so a guard keyed on the offset alone would refuse - * the engine's own operands on every step whose token belongs to the other half, where the - * device kernel correctly takes the zero-row path at any offset. */ + /* Validated before the loop, since an OpenMP body cannot return. The guard keys on holding the + * whole vocabulary, not on a zero offset: rank 0 of a vocab-parallel split has offset 0, and + * its out-of-slice ids are other ranks' tokens that must become zero rows. */ if (voff == 0 && a->world_size <= 1) { - for (int64_t m = 0; m < M; ++m) { - int64_t id = ld_int(tok->dtype, tok->data, offlin(tok, m)); - if (id >= n_vocab) return RAD_E_INVAL; - } - } - - const int64_t ws = wte->rank >= 2 ? wte->stride[wte->rank - 2] : n_embd; - const int64_t wc = wte->rank >= 2 ? wte->stride[wte->rank - 1] : 1; - #pragma omp parallel for schedule(static) - for (int64_t m = 0; m < M; ++m) { - const int64_t id = ld_int(tok->dtype, tok->data, offlin(tok, m)) - voff; - const int64_t xb = rowoff(x, m, n_embd), xs = laststride(x); - const bool have_row = id >= 0 && id < n_vocab; - for (int64_t i = 0; i < n_embd; ++i) - stt(x, xb + i * xs, have_row ? ldt(wte, id * ws + i * wc) * mult : 0.0f); - } - return RAD_OK; -} - -/* A gather from a QUANTISED table: one scale for the whole thing. - * - * WHY IT IS A SEPARATE OP AND NOT A `dtype` ON embed_lookup. The operand list differs -- there is a - * scale -- and operands are positional, so an op whose count depends on a string means different - * things to different kernels. That is the same argument `moe_gemm_q` and `gemm_nt_q` make against - * their unquantised twins, and adding the scale to embed_lookup as an OPTIONAL operand would have - * moved `x` from slot 2 to slot 3 for every caller in the tree. - * - * ONE SCALE FOR THE WHOLE TABLE, and that is the checkpoint's choice rather than a simplification. - * A hundreds-of-millions-of-rows n-gram embedding ships as E4M3 with a single bf16 `weight_scale`, - * and the reason that works is structural: E4M3 carries its own exponent, so a row spans very - * little dynamic range in units of the scale and the reconstruction is insensitive to the scale - * over octaves. A per-row scale buys a couple of percent there, which is why the format has none. - * (INT8 in the same byte WOULD gain substantially, because it spends all eight bits on resolution; - * that is a different format and not this one.) - */ -int ref_embed_lookup_q(const RadArgs* a, RadStream) { - /* `scale` (operand 2) is optional; the other three must be there. */ - if (a->n_t < 4 || !rad_arg_in(a, 0) || !rad_arg_in(a, 1) || !rad_arg_in(a, 3)) return RAD_E_INVAL; - const RadTensor *tok = &a->t[0], *wte = &a->t[1], *sc = &a->t[2], *x = &a->t[3]; - const int64_t n_embd = p_int(a, "n_embd", wte->rank >= 2 ? wte->shape[wte->rank - 1] : 0); - const int64_t n_vocab = p_int(a, "n_vocab", wte->rank >= 2 ? wte->shape[wte->rank - 2] : 0); - const int64_t voff = p_int(a, "vocab_offset", 0); - if (n_embd <= 0 || n_vocab <= 0 || voff < 0) return RAD_E_SHAPE; - const int64_t M = numel(x) / n_embd; - if (M <= 0 || numel(tok) < M || numel(wte) < n_vocab * n_embd) return RAD_E_SHAPE; - /* AN ABSENT SCALE IS ONE: a table stored as it ships -- a plain bf16 n-gram embedding read in - * place from a container -- takes the same op and the same host path as the quantised one, - * which is what keeps a table too large for any device pool on the mapped tier either way. */ - const float scale = sc->data && numel(sc) >= 1 ? ldt(sc, 0) : 1.0f; - - /* Validated before the loop, because an OpenMP body cannot return. Same rule as the dense - * gather above: a negative id is padding and writes a zero row, an id past the table is a - * launch error rather than a read of whatever follows it. */ - if (voff == 0) { for (int64_t m = 0; m < M; ++m) if (ld_int(tok->dtype, tok->data, offlin(tok, m)) >= n_vocab) return RAD_E_INVAL; } const int64_t ws = wte->rank >= 2 ? wte->stride[wte->rank - 2] : n_embd; const int64_t wc = wte->rank >= 2 ? wte->stride[wte->rank - 1] : 1; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(M * n_embd) for (int64_t m = 0; m < M; ++m) { const int64_t id = ld_int(tok->dtype, tok->data, offlin(tok, m)) - voff; const int64_t xb = rowoff(x, m, n_embd), xs = laststride(x); const bool have_row = id >= 0 && id < n_vocab; for (int64_t i = 0; i < n_embd; ++i) - stt(x, xb + i * xs, have_row ? ldt(wte, id * ws + i * wc) * scale : 0.0f); + stt(x, xb + i * xs, have_row ? ldt(wte, id * ws + i * wc) * factor : 0.0f); } return RAD_OK; } + +int ref_embed_lookup(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + return embed_gather(a, &a->t[0], &a->t[1], &a->t[2], p_f32(a, "mult", 1.0f)); +} + +/* A gather from a quantised table with one scale for the whole table. + * + * A separate op rather than a dtype on embed_lookup because operands are positional and this one + * adds a scale; an optional operand would have moved `x` from slot 2 to slot 3 for every caller + * (the same reason moe_gemm_q and gemm_nt_q are separate ops). + * + * One scale is the checkpoint's format: the n-gram embedding (hundreds of millions of rows) ships + * as E4M3 with a single bf16 `weight_scale`. E4M3 carries its own exponent, so reconstruction is + * insensitive to the scale over octaves and a per-row scale gains only a few percent. (INT8 would + * gain substantially, but that is a different format.) + */ +int ref_embed_lookup_q(const RadArgs* a, RadStream) { + /* `scale` (operand 2) is optional; the other three are required. */ + if (a->n_t < 4 || !rad_arg_in(a, 0) || !rad_arg_in(a, 1) || !rad_arg_in(a, 3)) return RAD_E_INVAL; + const RadTensor* sc = &a->t[2]; + /* An absent scale is 1, so a plain bf16 n-gram embedding read in place from a container takes + * the same op and host path, keeping a table too large for any device pool on the mapped tier. */ + const float scale = sc->data && numel(sc) >= 1 ? ldt(sc, 0) : 1.0f; + return embed_gather(a, &a->t[0], &a->t[1], &a->t[3], scale); +} diff --git a/libref/ref_gemm.h b/libref/ref_gemm.h index 910649e0..3a990ba8 100644 --- a/libref/ref_gemm.h +++ b/libref/ref_gemm.h @@ -1,14 +1,10 @@ /* ref_gemm.h -- how libref reads a matrix operand and its scale stream. * - * Shared by the dense GEMM and the mixture-of-experts GEMM, which need the same three answers: - * where row `r` of an operand begins, what the scale of a (row, k) pair is, and what a block- - * scaled grid looks like against the operand it scales. A grouped GEMM is a GEMM per row against - * a different weight, so it needs exactly the machinery the dense one has and nothing else; a - * second copy of `make_scales` in ref_moe.cpp would be a second place for the rblk rule to be - * wrong, and the rblk rule is what makes this reference usable as an oracle for a block-scaled - * fp8 checkpoint. + * Shared by the dense and mixture-of-experts GEMMs, which need the same answers: where row `r` of + * an operand begins, the scale of a (row, k) pair, and how a block-scaled grid maps onto its + * operand. Keeping one copy keeps one rblk rule, which block-scaled fp8 checkpoints depend on. * - * Everything here is a pure reading of a RadTensor. No op, no dispatch, no allocation. + * Pure reads of a RadTensor: no op, no dispatch, no allocation. */ #ifndef REF_GEMM_H #define REF_GEMM_H @@ -17,24 +13,16 @@ namespace ref { -/* A tensor read as [rows, cols], which is what every GEMM here wants and is NOT the same as - * "dim 0 and dim 1". +/* Row stride of a tensor read as [rows, cols], which is not the same as dim 0 by dim 1. * - * `stride[rank - 2]` is the row stride only when the LAST dimension is already `cols`. An - * activation that arrives rank 3 -- [tokens, heads, width], which is how the gated delta net's - * out-projection input is declared, because the scan kernels require that rank -- is read as - * [tokens, heads * width], and its row stride is the product of the trailing dimensions, not the - * head stride. Taking the head stride instead lands row 0 correctly and starts every row after it - * `width` elements in -- which reads as a correct implementation right up to the second row. + * `stride[rank - 2]` is the row stride only when the last dimension is already `cols`. A rank-3 + * activation [tokens, heads, width] (the gated delta net's out-projection input, rank 3 because the + * scan kernels need it) is read as [tokens, heads * width], whose row stride spans the trailing + * dimensions. Using the head stride gets row 0 right and every later row wrong. * - * THE OUTPUT SIDE IS THE WORSE HALF and has the same rule. A gated attention layer's q|gate - * projection is declared [tokens, heads, 2 * head_dim] -- rank 3, because the de-interleaving that - * follows needs the head axis -- and writing it at the HEAD stride does not merely write the wrong - * bytes, it leaves most of the buffer NEVER WRITTEN, so rows after the first carry a tail of exact - * zeros. - * - * This is libref, so it is the ORACLE: every tool that certifies a kernel against this arithmetic - * inherits whatever it gets wrong, which is why the rule is stated here once. */ + * Outputs follow the same rule. A gated attention q|gate projection is [tokens, heads, + * 2 * head_dim]; writing it at the head stride leaves most of the buffer unwritten, so later rows + * end in exact zeros. */ static inline int64_t row_stride(const RadTensor* t, int64_t cols) { if (!t || t->rank < 2) return cols; /* Fold trailing dimensions until they span `cols`; the next one out carries the row. */ @@ -47,18 +35,16 @@ static inline int64_t row_stride(const RadTensor* t, int64_t cols) { return t->stride[t->rank - 2]; /* the shapes disagree; fall back to the row axis */ } -/* The element offset of row `r` of a [rows, cols] operand, and the stride along cols. Weights - * arrive contiguous from the mapper; activations may be a slice of a wider arena buffer, so both - * are read through their strides. */ +/* Row and column strides of a [rows, cols] operand. Weights arrive contiguous; activations may be + * a slice of a wider arena buffer, so both are read through their strides. */ struct Mat { const RadTensor* t; int64_t rs; /* elements between rows */ int64_t cs; /* elements between columns */ }; -static inline Mat as_mat(const RadTensor* t, int64_t rows, int64_t cols) { +static inline Mat as_mat(const RadTensor* t, int64_t cols) { Mat m{ t, cols, 1 }; - (void)rows; if (t->rank < 2) return m; m.cs = t->stride[t->rank - 1]; m.rs = row_stride(t, cols); @@ -66,48 +52,39 @@ static inline Mat as_mat(const RadTensor* t, int64_t rows, int64_t cols) { } /* ------------------------------------------------------------------ scale streams - * A quantised operand's scales are a separate SoA stream (spec §4.1), shaped [rows, groups] with - * the group index fastest, or [rows] for one scale per row. The group SIZE is derived from the - * stream's own extent rather than trusted from the parameter: a `group` that disagrees with the - * scale tensor is the kind of mismatch that produces plausible wrong numbers, and deriving it - * makes the disagreement structurally impossible. + * A quantised operand's scales are a separate SoA stream (spec §4.1), [rows, groups] with the + * group index fastest, or [rows] for one scale per row. The group size is derived from the + * stream's extent rather than the `group` parameter, so the two cannot disagree. * - * A BLOCK-SCALED grid is the same stream with fewer rows than the operand. DeepSeek-style fp8 -- - * which is what Qwen3.8-27B-FP8 and every other `weight_block_size: [128, 128]` checkpoint ships -- - * stores one scale per 128x128 TILE, so `weight_scale_inv` is [ceil(N/128)][ceil(K/128)] against an - * [N][K] weight. `rblk` is how many operand rows share a scale row; it is 1 for every per-row grid, - * which is every other format in this project, so the division below costs those nothing. - * - * Without it this reference reads a 17408-row weight's 136-row scale plane as if it had 17408 rows - * and lands on `groups = 0`, which is not a diagnosable failure -- it is a plausible wrong number, - * and it makes ref useless as the oracle for exactly the format the production models are in. */ + * A block-scaled grid is the same stream with fewer rows than the operand. DeepSeek-style fp8 + * (Qwen3.8-27B-FP8 and any `weight_block_size: [128, 128]` checkpoint) stores one scale per + * 128x128 tile, so `weight_scale_inv` is [ceil(N/128)][ceil(K/128)] against an [N][K] weight. + * `rblk` is how many operand rows share a scale row; 1 for every per-row grid. Without it a + * 17408-row weight's 136-row scale plane would be read per row and give plausible wrong numbers. */ struct Scales { const void* p; uint32_t dt; int64_t rs; /* elements between scale rows */ int64_t cs; /* elements between groups */ int64_t group; /* K elements per scale */ - int64_t rblk; /* OPERAND rows per scale row; 1 unless the grid is block-scaled */ + int64_t rblk; /* operand rows per scale row; 1 unless the grid is block-scaled */ bool e8m0; /* the scale stream is OCP e8m0 exponent bytes, not floats */ - inline float at(int64_t row, int64_t k) const { - int64_t g = group > 0 ? k / group : 0; - int64_t i = (rblk > 1 ? row / rblk : row) * rs + g * cs; - return e8m0 ? e8m0_to_f32(((const uint8_t*)p)[i]) : ld_dt(dt, p, i); - } + /* The scale of group `g` of `row`. */ inline float grp(int64_t row, int64_t g) const { int64_t i = (rblk > 1 ? row / rblk : row) * rs + g * cs; return e8m0 ? e8m0_to_f32(((const uint8_t*)p)[i]) : ld_dt(dt, p, i); } + /* The scale of element `k` of `row`. */ + inline float at(int64_t row, int64_t k) const { return grp(row, group > 0 ? k / group : 0); } }; -/* THE BLOCK A GRID OF `blocks` PIECES IMPLIES OVER `ext` ELEMENTS, and it is not ext / blocks. - * A grid's last block may be partial -- ceil(300 / 128) is 3 scales over 128, 128 and 44 -- so - * the quotient (100 there) assigns elements 100..127 to the second scale. The block is the POWER - * OF TWO whose ceiling division gives `blocks`, which is unique whenever there is more than one - * block, and every scale grid in this project is one (32, 64, 128). Where no power of two fits, - * the smallest block that yields `blocks` pieces is taken. Either way ceil(ext / block) is at - * most `blocks`, so an index derived from it never leaves the grid. */ +/* The block size a grid of `blocks` pieces implies over `ext` elements; not ext / blocks, since + * the last block may be partial (300 over 128 is 3 scales covering 128, 128 and 44, but 300 / 3 = + * 100 would misassign 100..127). It is the power of two whose ceiling division gives `blocks`, + * unique for more than one block; every scale grid here is one (32, 64, 128). Otherwise the + * smallest block giving `blocks` pieces. Either way ceil(ext / block) <= `blocks`, so derived + * indices stay in the grid. */ static inline int64_t grid_block(int64_t ext, int64_t blocks) { if (ext <= 0) return 1; if (blocks <= 1) return ext; @@ -125,15 +102,13 @@ static inline Scales make_scales(const RadTensor* s, int64_t rows, int64_t K, bo } q.p = s->data; q.dt = s->dtype; - /* A rank-2 stream states its own grid, and that statement is preferred: it is the only source - * that can distinguish "one scale per row over `groups` groups" from "one scale per row BLOCK". - * FEWER scale rows than operand rows is a block grid, whatever the remainder: [ceil(N/128)] - * rows against N = 129 is two blocks, the second of one row. As many or more is one scale row - * per operand row, read through the stream's own row stride. + /* A rank-2 stream states its own grid, the only way to tell per-row groups from per-row-block + * scales. Fewer scale rows than operand rows is a block grid whatever the remainder + * ([ceil(N/128)] rows against N = 129 is two blocks, the second one row); otherwise one scale + * row per operand row, through the stream's row stride. * - * A rank-1 or flattened stream has no grid to state. With a scale for every row it is per row - * over nel / rows groups; with fewer it is one scale per BLOCK of rows. Reading it per row - * there walks off the end of the plane at the first row past its length. */ + * A rank-1 or flattened stream states no grid. With a scale per row it is nel / rows groups per + * row; with fewer it is one scale per block of rows (reading it per row would run off the end). */ int64_t groups = 0; if (s->rank >= 2) { const int64_t srows = s->shape[s->rank - 2]; @@ -154,40 +129,44 @@ static inline Scales make_scales(const RadTensor* s, int64_t rows, int64_t K, bo q.cs = 1; } q.group = grid_block(K, groups); - /* mxfp4's block scale is an e8m0 exponent byte. When the stream arrives as u8 beside an mxfp4 - * weight there is nothing else it could be; a float stream beside the same weight is read as - * a float, so a quantiser that chose to store the scale plainly still works. */ + /* mxfp4's block scale is an e8m0 exponent byte: a u8 stream beside an mxfp4 weight is read as + * e8m0, while a float stream is read as floats, so plainly stored scales still work. */ q.e8m0 = mxfp4_weight && (s->dtype == RAD_U8); return q; } /* ------------------------------------------------------------------ one quantised product * - * ONE (m, n) dot of a quantised GEMM, and the ONE DEFINITION of how the scales fold into it. + * One (m, n) dot of a quantised GEMM, and the single definition of how scales fold into it. * - * The group sub-sum is accumulated from the RAW CODES and scaled once at the end of the group, - * which is what an int8 or fp8 WMMA kernel does: it accumulates in the fragment's type and applies - * the block scales when the tile closes. Folding the scales into every product instead is the same - * value in exact arithmetic and a different one in the last bits, and rad-kbench would blame the - * kernel for the reference's choice. + * Each group's sub-sum is accumulated from the raw codes and scaled once at the group's end, as an + * int8 or fp8 WMMA kernel does when a tile closes. Scaling every product is equal in exact + * arithmetic but differs in the last bits. * - * `sub * sa * sb` IS AN ORDER AND NOT AN EXPRESSION. Float multiplication is commutative and not - * associative, so (sub*sa)*sb and (sub*sb)*sa differ by an ulp on some operands -- which is enough - * to move one fp8 code, and a fused op being byte-identical to the pair it replaces is the whole - * claim such a fold rests on. Every caller goes through here so that there is one order. + * `sub * sa * sb` is an order: (sub*sa)*sb and (sub*sb)*sa can differ by an ulp, enough to move an + * fp8 code, and fused ops must be byte-identical to the pair they replace. Every caller uses this + * function so there is one order. * - * The loads go through `ld_dt` rather than `Cvt
` so that one function serves every dtype pair. - * The two return the same float for every dtype, so a caller that dispatches on the type at - * compile time for speed still computes these bits. + * LA and LB load A's and B's elements: `Dyn` switches on the dtype per element and serves every + * pair; `Fix
` resolves it at compile time for the GEMM's hot pairs. Both return the same + * floats, so the result does not depend on which was used. */ +struct Dyn { + static inline float ld(const RadTensor* t, int64_t i) { return ld_dt(t->dtype, t->data, i); } +}; +template struct Fix { + static inline float ld(const RadTensor* t, int64_t i) { return Cvt
::ld(t->data, i); } +}; + + +template static inline float quant_dot(const Mat& A, const Mat& B, const Scales& SA, const Scales& SB, int64_t m, int64_t n, int64_t K) { const int64_t g = SB.group > 0 ? SB.group : K; const int64_t ngrp = (K + g - 1) / g; - /* No format in this project gives the activation a finer group than the weight; where one - * appears the scale cannot be hoisted out of the group and the sub-sum is formed per element. */ + /* No format here gives the activation a finer group than the weight; if one does, its scale + * cannot be hoisted and is applied per element. */ const bool coarse_a = !SA.p || SA.group >= g; - const uint32_t da = A.t->dtype, db = B.t->dtype; const int64_t a0 = m * A.rs, b0 = n * B.rs; float acc = 0.0f; for (int64_t gi = 0; gi < ngrp; ++gi) { @@ -196,28 +175,147 @@ static inline float quant_dot(const Mat& A, const Mat& B, const Scales& SA, cons float sub = 0.0f; if (coarse_a) { for (int64_t k = k0; k < k1; ++k) - sub += ld_dt(da, A.t->data, a0 + k * A.cs) * ld_dt(db, B.t->data, b0 + k * B.cs); + sub += LA::ld(A.t, a0 + k * A.cs) * LB::ld(B.t, b0 + k * B.cs); acc += sub * (SA.p ? SA.at(m, k0) : 1.0f) * sb; } else { for (int64_t k = k0; k < k1; ++k) - sub += ld_dt(da, A.t->data, a0 + k * A.cs) * SA.at(m, k) * - ld_dt(db, B.t->data, b0 + k * B.cs); + sub += LA::ld(A.t, a0 + k * A.cs) * SA.at(m, k) * LB::ld(B.t, b0 + k * B.cs); acc += sub * sb; } } return acc; } +/* ------------------------------------------------------------------ the blocked product + * + * quant_dot over a tile of outputs: A rows `arow[0..R)` against B rows [n0, n0 + nb). Every + * output is the chain quant_dot forms, per group a sub-sum from zero over ascending k and then + * `acc + (sub * sa) * sb`, so the result is bit-identical to calling it per element. What changes + * is that REF_NB outputs advance together: the chains are independent, so they run in vector lanes + * and their add latencies overlap, and B's codes are widened into an f32 panel once per K chunk + * and reused by every row of the tile (exact conversions, so the panel holds the same floats the + * loaders return). + * + * Only the coarse activation grid (no finer scale on A than on B) is tiled; quant_dot keeps the + * other, which no format uses. */ +static constexpr int64_t REF_NB = 16, REF_KC = 256, REF_MB = 2; + +typedef float RefV4 __attribute__((vector_size(16))); + +/* Floats a tile of R rows needs: the panel, two A rows, and the sub-sums and accumulators of R + * rows rounded up to whole row pairs. One ws_get() carves all of it. */ +static inline size_t tile_ws_floats(int64_t R) { + const int64_t rp = (R + REF_MB - 1) / REF_MB * REF_MB; + return (size_t)(REF_KC * REF_NB + REF_MB * REF_KC + 2 * rp * REF_NB); +} + +/* sub[2][REF_NB] += abuf[i][k] * panel[k][*] over k < kl, one chain per output. */ +static inline void tile_kernel(const float* abuf, const float* panel, float* sub, int64_t kl) { + static_assert(REF_NB == 16 && REF_MB == 2, "the kernel holds two rows of four vectors"); + auto ld = [](const float* f) { RefV4 v; std::memcpy(&v, f, sizeof v); return v; }; + auto st = [](float* f, RefV4 v) { std::memcpy(f, &v, sizeof v); }; + RefV4 c00 = ld(sub), c01 = ld(sub + 4), c02 = ld(sub + 8), c03 = ld(sub + 12); + RefV4 c10 = ld(sub + 16), c11 = ld(sub + 20), c12 = ld(sub + 24), c13 = ld(sub + 28); + for (int64_t k = 0; k < kl; ++k) { + const float a0 = abuf[k], a1 = abuf[REF_KC + k]; + const float* p = panel + k * REF_NB; + const RefV4 p0 = ld(p), p1 = ld(p + 4), p2 = ld(p + 8), p3 = ld(p + 12); + c00 += a0 * p0; c01 += a0 * p1; c02 += a0 * p2; c03 += a0 * p3; + c10 += a1 * p0; c11 += a1 * p1; c12 += a1 * p2; c13 += a1 * p3; + } + st(sub, c00); st(sub + 4, c01); st(sub + 8, c02); st(sub + 12, c03); + st(sub + 16, c10); st(sub + 20, c11); st(sub + 24, c12); st(sub + 28, c13); +} + +/* The tile's results land in `ws`'s accumulator block, [R][REF_NB] row-major, which this returns; + * columns at and past `nb` are padding. Requires the coarse activation grid (see above). */ +template +static float* quant_tile(const Mat& A, const Mat& B, const Scales& SA, const Scales& SB, + const int64_t* arow, int64_t R, int64_t n0, int64_t nb, int64_t K, + float* ws) { + const int64_t rp = (R + REF_MB - 1) / REF_MB * REF_MB; + float* const panel = ws; + float* const abuf = panel + REF_KC * REF_NB; + float* const sub = abuf + REF_MB * REF_KC; + float* const acc = sub + rp * REF_NB; + const int64_t g = SB.group > 0 ? SB.group : K; + const int64_t ngrp = (K + g - 1) / g; + /* No scale on either side: quant_dot's acc is 0 + (sub * 1) * 1, which is sub exactly (a + * sub-sum started at +0 is never -0). */ + const bool unscaled = !SA.p && !SB.p && ngrp == 1; + for (int64_t i = 0; i < rp * REF_NB; ++i) acc[i] = 0.0f; + float sb[REF_NB]; + for (int64_t gi = 0; gi < ngrp; ++gi) { + const int64_t k0 = gi * g, k1 = (k0 + g < K) ? k0 + g : K; + for (int64_t j = 0; j < REF_NB; ++j) sb[j] = (j < nb && SB.p) ? SB.grp(n0 + j, gi) : 1.0f; + for (int64_t i = 0; i < rp * REF_NB; ++i) sub[i] = 0.0f; + for (int64_t kc0 = k0; kc0 < k1; kc0 += REF_KC) { + const int64_t kl = (kc0 + REF_KC < k1) ? REF_KC : k1 - kc0; + for (int64_t j = 0; j < REF_NB; ++j) { + if (j < nb) { + const int64_t b0 = (n0 + j) * B.rs + kc0 * B.cs; + for (int64_t k = 0; k < kl; ++k) + panel[k * REF_NB + j] = LB::ld(B.t, b0 + k * B.cs); + } else { + for (int64_t k = 0; k < kl; ++k) panel[k * REF_NB + j] = 0.0f; + } + } + for (int64_t r0 = 0; r0 < R; r0 += REF_MB) { + for (int64_t i = 0; i < REF_MB; ++i) { + float* const ar = abuf + i * REF_KC; + if (r0 + i < R) { + const int64_t a0 = arow[r0 + i] * A.rs + kc0 * A.cs; + for (int64_t k = 0; k < kl; ++k) ar[k] = LA::ld(A.t, a0 + k * A.cs); + } else { + for (int64_t k = 0; k < kl; ++k) ar[k] = 0.0f; + } + } + tile_kernel(abuf, panel, sub + r0 * REF_NB, kl); + } + } + if (unscaled) { + for (int64_t i = 0; i < rp * REF_NB; ++i) acc[i] = sub[i]; + continue; + } + for (int64_t r = 0; r < R; ++r) { + const float sa = SA.p ? SA.at(arow[r], k0) : 1.0f; + for (int64_t j = 0; j < REF_NB; ++j) + acc[r * REF_NB + j] += sub[r * REF_NB + j] * sa * sb[j]; + } + } + return acc; +} + +/* How a grid of R rows by N outputs is cut into tiles for one parallel loop: `nblk` column blocks + * of REF_NB, each split into `rgc` row groups of `rg` rows. Rows are split only when there are too + * few column blocks to occupy the threads (a narrow projection at a prefill M); a row group then + * pays its own panel widening, which is cheap against rg rows of products. */ +struct TileGrid { + int64_t nblk, rg, rgc; + int64_t items() const { return nblk * rgc; } +}; +static inline TileGrid tile_grid(int64_t R, int64_t N) { + TileGrid t; + t.nblk = (N + REF_NB - 1) / REF_NB; + int64_t rg = R; + if (t.nblk < 128 && R > 8 * REF_MB) { + rg = (R * t.nblk + 127) / 128; + if (rg < 8 * REF_MB) rg = 8 * REF_MB; + rg = (rg + REF_MB - 1) / REF_MB * REF_MB; + } + t.rg = rg > 0 ? rg : 1; + t.rgc = R > 0 ? (R + t.rg - 1) / t.rg : 0; + return t; +} + /* ------------------------------------------------------------------ weight tables * - * A RAD_OPD_WTAB operand: `data` is a device (here, host) array of `shape[0]` pointers, one per - * expert, and `stride[0]` is 0 to say so -- see RAD_WTAB in abi/rad_runtime.h. The STACKED form, - * a plain rank-3 [n_expert, N, K] tensor with an ordinary leading stride, is accepted too and is - * what a caller outside the engine hands over: rad-kbench draws one dense plane and the fixture - * has nowhere to put a pointer array. Both are one expert per call to this, so nothing downstream - * has to know which arrived. + * A RAD_OPD_WTAB operand: `data` is an array of `shape[0]` pointers, one per expert, marked by + * `stride[0]` == 0 (RAD_WTAB in abi/rad_runtime.h). The stacked form, a plain rank-3 + * [n_expert, N, K] tensor, is also accepted; callers outside the engine such as rad-kbench pass + * that, having nowhere to put a pointer array. * - * Returns entry `e` as a rank-(rank-1) tensor over the same dtype, or a null-data tensor when the + * Returns entry `e` as a rank-(rank-1) tensor of the same dtype, or a null-data tensor when the * operand cannot be read that way. */ static inline RadTensor expert_entry(const RadTensor* w, int64_t e) { RadTensor t{}; @@ -232,8 +330,8 @@ static inline RadTensor expert_entry(const RadTensor* w, int64_t e) { void* const* tab = (void* const*)w->data; t.data = tab[e]; } else { - /* An element offset in a packed dtype can be mid-byte; the stacked form is only ever - * whole planes, so the arithmetic is done in bytes off the leading stride. */ + /* A packed-dtype element offset can be mid-byte; stacked planes are whole bytes, so + * compute in bits off the leading stride and refuse a fractional byte. */ const int64_t bits = rad_dtype_bits(w->dtype); const int64_t nbits = (int64_t)bits * w->stride[0] * e; if (bits <= 0 || (nbits & 7)) return t; /* data stays null: unreadable */ diff --git a/libref/ref_gen.cpp b/libref/ref_gen.cpp index 5bb0ba50..b2e7bccb 100644 --- a/libref/ref_gen.cpp +++ b/libref/ref_gen.cpp @@ -1,13 +1,11 @@ /* ref_gen.cpp -- the image generator's ops (docs/OPS.md, "Image generation"). * - * WHERE A ROUNDING IS WRITTEN OUT, IT IS THE REFERENCE MODEL'S. A diffusion transformer and its - * decoder are run in bf16 by the reference implementation, so every tensor it materialises is - * rounded there: `LN(x) * (1 + scale)` is three bf16 tensors, not one f32 expression, and the - * oracle rounds where the reference does so a kernel that fuses the chain can be held to it. + * Every explicit rounding follows the upstream model, which runs the diffusion transformer and its + * decoder in bf16 and so rounds every tensor it materialises: `LN(x) * (1 + scale)` is three bf16 + * tensors, not one f32 expression. Rounding at the same points lets a fused kernel be held to it. * - * Geometry a step decides -- an image's height and width -- arrives in the OPERANDS, never in the - * parameters: a 2-D image operand is [height, width * channels], dense, and the op reads both off - * its shape. A parameter is fixed at declare and an image's size is a request's. + * Per-request geometry (an image's height and width) comes from the operands, never the + * parameters, which are fixed at declare: a 2-D image operand is [height, width * channels], dense. */ #include "ref_common.h" #include "ref_gemm.h" @@ -23,41 +21,12 @@ using namespace ref; namespace { /* An entry's flags (docs/OPS.md, flow_euler): RadGenBatch's RAD_GEN_F_* values, restated because a - * kernel library compiles against rad_abi.h and not the run phase's header. */ + * kernel library compiles against rad_abi.h, not the run phase's header. */ enum { kFirst = 1, kInpaint = 2, kPreview = 4 }; -inline float rnd(uint32_t dt, float v) { - uint16_t h; - switch (dt) { - case RAD_BF16: h = f32_to_bf16(v); return bf16_to_f32(h); - case RAD_F16: h = f32_to_f16(v); return f16_to_f32(h); - default: return v; - } -} -inline float rbf(float v) { return bf16_to_f32(f32_to_bf16(v)); } +inline float rbf(float v) { return round_dt(RAD_BF16, v); } -inline int64_t cu_at(const RadTensor* cu, int64_t i) { - return ld_int(cu->dtype, cu->data, offlin(cu, i)); -} - -/* The sequence that owns dense row `r`: linear, because there are a handful. */ -inline int64_t seq_of(const RadTensor* cu, int64_t n_seq, int64_t r) { - int64_t s = 0; - while (s + 1 < n_seq && cu_at(cu, s + 1) <= r) ++s; - return s; -} - -inline int64_t rows_n(const RadTensor* t, int64_t n) { - if (!t || n <= 0) return 0; - if (t->rank >= 2 && t->shape[t->rank - 1] == n) { - int64_t r = 1; - for (uint32_t i = 0; i + 1 < t->rank; ++i) r *= t->shape[i]; - return r; - } - return numel(t) / n; -} - -/* A space-separated list of floats, each rounded to bf16 as the reference's bf16 tensor of it is. */ +/* A space-separated list of floats, each rounded to bf16 as the upstream bf16 tensor holds it. */ int parse_list(const char* s, std::vector* out) { out->clear(); while (s && *s) { @@ -73,19 +42,19 @@ int parse_list(const char* s, std::vector* out) { } /* namespace */ /* ------------------------------------------------------------------ ln_mod */ -/* y = bf16( bf16(LN(x)) * bf16(1 + s[seq]) ): a layer norm with no gain and no bias, then the - * modulation row of the row's sequence. `s` is [n_seq, >= n] at its own row pitch -- a column - * slice of the modulation projection. */ +/* y = bf16( bf16(LN(x)) * bf16(1 + s[seq]) ): a layer norm with no gain or bias, then the row's + * sequence's modulation row. `s` is [n_seq, >= n] at its own row pitch (a column slice of the + * modulation projection). */ int ref_ln_mod(const RadArgs* a, RadStream) { if (!have(a, 4)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *s = &a->t[1], *cu = &a->t[2], *y = &a->t[3]; const int64_t n = p_int(a, "n", 0); const float eps = p_f32(a, "eps", 1e-6f); if (n <= 0) return RAD_E_SHAPE; - const int64_t rows = rows_n(y, n), n_seq = numel(cu) - 1; - if (rows <= 0 || n_seq <= 0 || rows_n(x, n) < rows) return RAD_E_SHAPE; + const int64_t rows = rows_of(y, n), n_seq = numel(cu) - 1; + if (rows <= 0 || n_seq <= 0 || rows_of(x, n) < rows) return RAD_E_SHAPE; const int64_t s_rs = row_stride(s, n), s_cs = laststride(s); - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { const int64_t e = seq_of(cu, n_seq, r); const int64_t xb = rowoff(x, r, n), xs = laststride(x); @@ -100,8 +69,8 @@ int ref_ln_mod(const RadArgs* a, RadStream) { } const float rs = 1.0f / std::sqrt(var / (float)n + eps); for (int64_t i = 0; i < n; ++i) { - const float ln = rnd(y->dtype, (ldt(x, xb + i * xs) - mean) * rs); - const float sc = rnd(y->dtype, 1.0f + ldt(s, e * s_rs + i * s_cs)); + const float ln = round_dt(y->dtype, (ldt(x, xb + i * xs) - mean) * rs); + const float sc = round_dt(y->dtype, 1.0f + ldt(s, e * s_rs + i * s_cs)); stt(y, yb + i * ys, ln * sc); } } @@ -115,17 +84,17 @@ int ref_gate_add(const RadArgs* a, RadStream) { const RadTensor *y = &a->t[0], *g = &a->t[1], *cu = &a->t[2], *x = &a->t[3]; const int64_t n = p_int(a, "n", 0); if (n <= 0) return RAD_E_SHAPE; - const int64_t rows = rows_n(y, n), n_seq = numel(cu) - 1; - if (rows <= 0 || n_seq <= 0 || rows_n(x, n) < rows) return RAD_E_SHAPE; + const int64_t rows = rows_of(y, n), n_seq = numel(cu) - 1; + if (rows <= 0 || n_seq <= 0 || rows_of(x, n) < rows) return RAD_E_SHAPE; const int64_t g_rs = row_stride(g, n), g_cs = laststride(g); - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { const int64_t e = seq_of(cu, n_seq, r); const int64_t yb = rowoff(y, r, n), ys = laststride(y); const int64_t xb = rowoff(x, r, n), xs = laststride(x); for (int64_t i = 0; i < n; ++i) { - const float t = rnd(x->dtype, std::tanh(ldt(g, e * g_rs + i * g_cs))); - const float p = rnd(x->dtype, t * ldt(y, yb + i * ys)); + const float t = round_dt(x->dtype, ref_tanh(ldt(g, e * g_rs + i * g_cs))); + const float p = round_dt(x->dtype, t * ldt(y, yb + i * ys)); stt(x, xb + i * xs, ldt(x, xb + i * xs) + p); } } @@ -144,12 +113,12 @@ int ref_ln_mod_quant_fp8(const RadArgs* a, RadStream) { const bool gated = p_int(a, "gated", 0) != 0; const float eps = p_f32(a, "eps", 1e-6f); if (n <= 0 || grp <= 0 || n % grp || (gated && (!y || !g))) return RAD_E_SHAPE; - const int64_t rows = rows_n(q, n), n_seq = numel(cu) - 1, ngrp = n / grp; - if (rows <= 0 || n_seq <= 0 || rows_n(x, n) < rows || numel(sc) < rows * ngrp) + const int64_t rows = rows_of(q, n), n_seq = numel(cu) - 1, ngrp = n / grp; + if (rows <= 0 || n_seq <= 0 || rows_of(x, n) < rows || numel(sc) < rows * ngrp) return RAD_E_SHAPE; const int64_t s_rs = row_stride(s, n), s_cs = laststride(s); const int64_t g_rs = gated ? row_stride(g, n) : 0, g_cs = gated ? laststride(g) : 0; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { const int64_t e = seq_of(cu, n_seq, r); const int64_t xb = rowoff(x, r, n), xs = laststride(x); @@ -157,9 +126,9 @@ int ref_ln_mod_quant_fp8(const RadArgs* a, RadStream) { for (int64_t i = 0; i < n; ++i) { float xv = ldt(x, xb + i * xs); if (gated) { - const float t = rnd(x->dtype, std::tanh(ldt(g, e * g_rs + i * g_cs))); + const float t = round_dt(x->dtype, ref_tanh(ldt(g, e * g_rs + i * g_cs))); const float d = ldt(y, rowoff(y, r, n) + i * laststride(y)); - xv = rnd(x->dtype, xv + rnd(x->dtype, t * d)); + xv = round_dt(x->dtype, xv + round_dt(x->dtype, t * d)); stt(x, xb + i * xs, xv); } v[(size_t)i] = xv; @@ -171,24 +140,16 @@ int ref_ln_mod_quant_fp8(const RadArgs* a, RadStream) { for (int64_t i = 0; i < n; ++i) { const float d = v[(size_t)i] - mean; var += d * d; } const float rs = 1.0f / std::sqrt(var / (float)n + eps); for (int64_t i = 0; i < n; ++i) { - const float ln = rnd(RAD_BF16, (v[(size_t)i] - mean) * rs); - const float sm = rnd(RAD_BF16, 1.0f + ldt(s, e * s_rs + i * s_cs)); - o[(size_t)i] = rnd(RAD_BF16, ln * sm); + const float ln = round_dt(RAD_BF16, (v[(size_t)i] - mean) * rs); + const float sm = round_dt(RAD_BF16, 1.0f + ldt(s, e * s_rs + i * s_cs)); + o[(size_t)i] = round_dt(RAD_BF16, ln * sm); if (z) stt(z, rowoff(z, r, n) + i * laststride(z), o[(size_t)i]); } const int64_t qb = rowoff(q, r, n), qs = laststride(q); for (int64_t gi = 0; gi < ngrp; ++gi) { - float amax = 0.0f; - for (int64_t i = gi * grp; i < (gi + 1) * grp; ++i) - amax = std::max(amax, std::fabs(o[(size_t)i])); - const float scl = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f; - const float inv = 1.0f / scl; - for (int64_t i = gi * grp; i < (gi + 1) * grp; ++i) { - float w = o[(size_t)i] * inv; - if (w > 448.0f) w = 448.0f; - if (w < -448.0f) w = -448.0f; - st_dt(q->dtype, q->data, qb + i * qs, w); - } + const float* og = o.data() + gi * grp; + const float scl = q8_group([&](int64_t i) { return og[i]; }, grp, 448.0f, q, + qb + gi * grp * qs, qs); stt(sc, rowoff(sc, r, ngrp) + gi * laststride(sc), scl); } } @@ -208,7 +169,7 @@ int ref_timestep_embed(const RadArgs* a, RadStream) { const double mp = p_f32(a, "max_period", 10000.0f); const int round = (int)p_int(a, "round", 0); if (n <= 0 || (n & 1)) return RAD_E_SHAPE; - const int64_t rows = rows_n(y, n); + const int64_t rows = rows_of(y, n); if (rows <= 0 || numel(t) < rows) return RAD_E_SHAPE; const int64_t h = n / 2; const float coef = (float)(-std::log(mp)); @@ -217,10 +178,10 @@ int ref_timestep_embed(const RadArgs* a, RadStream) { const float tt = round ? scale * rbf(rbf(tv * scale) / scale) : scale * tv; const int64_t yb = rowoff(y, m, n), ys = laststride(y); for (int64_t i = 0; i < h; ++i) { - const float f = std::exp(coef * (float)i / (float)h); + const float f = ref_exp(coef * (float)i / (float)h); const float arg = tt * f; - stt(y, yb + i * ys, std::cos(arg)); - stt(y, yb + (h + i) * ys, std::sin(arg)); + stt(y, yb + i * ys, ref_cos(arg)); + stt(y, yb + (h + i) * ys, ref_sin(arg)); } } return RAD_OK; @@ -233,10 +194,10 @@ int ref_gather_rows2(const RadArgs* a, RadStream) { const RadTensor *A = &a->t[0], *B = &a->t[1], *idx = &a->t[2], *y = &a->t[3]; const int64_t n = p_int(a, "n", 0); if (n <= 0) return RAD_E_SHAPE; - const int64_t rows = rows_n(y, n); + const int64_t rows = rows_of(y, n); if (rows <= 0 || numel(idx) < rows) return RAD_E_SHAPE; - const int64_t ra = rows_n(A, n), rbn = rows_n(B, n); - #pragma omp parallel for schedule(static) + const int64_t ra = rows_of(A, n), rbn = rows_of(B, n); + REF_PAR_FOR(rows * n) for (int64_t i = 0; i < rows; ++i) { const int64_t r = ld_int(idx->dtype, idx->data, offlin(idx, i)); const RadTensor* src = r >= 0 ? A : B; @@ -259,8 +220,8 @@ int ref_lane_gather(const RadArgs* a, RadStream) { const RadTensor *src = &a->t[0], *lane = &a->t[1], *cu = &a->t[2], *y = &a->t[3]; const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0); if (n <= 0 || stride <= 0) return RAD_E_SHAPE; - const int64_t n_seq = numel(cu) - 1, src_rows = rows_n(src, n); - if (n_seq <= 0 || numel(lane) < n_seq) return RAD_E_SHAPE; + const int64_t n_seq = numel(cu) - 1, src_rows = rows_of(src, n); + if (n_seq <= 0 || numel(lane) < n_seq || cu_at(cu, n_seq) <= cu_at(cu, 0)) return RAD_E_SHAPE; for (int64_t e = 0; e < n_seq; ++e) { const int64_t L = ld_int(lane->dtype, lane->data, offlin(lane, e)); const int64_t b0 = cu_at(cu, e), b1 = cu_at(cu, e + 1); @@ -280,7 +241,7 @@ int ref_lane_store(const RadArgs* a, RadStream) { const RadTensor *src = &a->t[0], *lane = &a->t[1], *dst = &a->t[2]; const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0); if (n <= 0 || stride <= 0) return RAD_E_SHAPE; - const int64_t rows = rows_n(src, n), dst_rows = rows_n(dst, n), nl = numel(lane); + const int64_t rows = rows_of(src, n), dst_rows = rows_of(dst, n), nl = numel(lane); if (rows <= 0 || rows > stride) return RAD_E_SHAPE; for (int64_t l = 0; l < nl; ++l) { const int64_t L = ld_int(lane->dtype, lane->data, offlin(lane, l)); @@ -304,9 +265,10 @@ int ref_randn_lanes(const RadArgs* a, RadStream) { const RadTensor *dst = &a->t[4]; const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0); if (n <= 0 || stride <= 0) return RAD_E_SHAPE; - const int64_t n_seq = numel(cu) - 1, dst_rows = rows_n(dst, n); + const int64_t n_seq = numel(cu) - 1, dst_rows = rows_of(dst, n); if (n_seq <= 0 || numel(fl) < n_seq || numel(lane) < n_seq || numel(seed) < 2 * n_seq) return RAD_E_SHAPE; + if (cu_at(cu, n_seq) <= cu_at(cu, 0)) return RAD_E_SHAPE; for (int64_t e = 0; e < n_seq; ++e) { if (!(ld_int(fl->dtype, fl->data, offlin(fl, e)) & kFirst)) continue; const int64_t L = ld_int(lane->dtype, lane->data, offlin(lane, e)); @@ -314,7 +276,7 @@ int ref_randn_lanes(const RadArgs* a, RadStream) { if (L < 0 || len > stride || (L + 1) * stride > dst_rows) return RAD_E_SHAPE; const uint64_t sd = (uint64_t)(uint32_t)ld_int(seed->dtype, seed->data, offlin(seed, 2 * e)) | ((uint64_t)(uint32_t)ld_int(seed->dtype, seed->data, offlin(seed, 2 * e + 1)) << 32); - #pragma omp parallel for schedule(static) + REF_PAR_FOR(len * n * 8) for (int64_t k = 0; k < len; ++k) { const int64_t db = rowoff(dst, L * stride + k, n), ds = laststride(dst); for (int64_t c = 0; c < n; ++c) @@ -345,8 +307,8 @@ int ref_flow_euler(const RadArgs* a, RadStream) { const RadTensor *pv = t_in(a, 12); const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0); if (n <= 0 || stride <= 0) return RAD_E_SHAPE; - const int64_t n_seq = numel(cu) - 1, st_rows = rows_n(st, n); - if (n_seq <= 0) return RAD_E_SHAPE; + const int64_t n_seq = numel(cu) - 1, st_rows = rows_of(st, n); + if (n_seq <= 0 || cu_at(cu, n_seq) <= cu_at(cu, 0)) return RAD_E_SHAPE; const uint32_t dt = st->dtype; for (int64_t e = 0; e < n_seq; ++e) { const int64_t pr = ld_int(pair->dtype, pair->data, offlin(pair, e)); @@ -361,10 +323,10 @@ int ref_flow_euler(const RadArgs* a, RadStream) { const int64_t f = ld_int(fl->dtype, fl->data, offlin(fl, e)); const uint64_t sd = (uint64_t)(uint32_t)ld_int(seed->dtype, seed->data, offlin(seed, 2 * e)) | ((uint64_t)(uint32_t)ld_int(seed->dtype, seed->data, offlin(seed, 2 * e + 1)) << 32); - const float dts = rnd(dt, sn - s); + const float dts = round_dt(dt, sn - s); if ((f & kInpaint) && (!inp || !mask)) return RAD_E_INVAL; if ((f & kPreview) && !pv) return RAD_E_INVAL; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(len * n * 8) for (int64_t k = 0; k < len; ++k) { const int64_t vb = rowoff(v, b0 + k, n), vs = laststride(v); const int64_t nb = pr >= 0 ? rowoff(v, p0 + k, n) : 0; @@ -373,20 +335,20 @@ int ref_flow_euler(const RadArgs* a, RadStream) { float vv = ldt(v, vb + c * vs); if (pr >= 0) { const float vn = ldt(v, nb + c * vs); - vv = rnd(dt, vn + rnd(dt, w * rnd(dt, vv - vn))); + vv = round_dt(dt, vn + round_dt(dt, w * round_dt(dt, vv - vn))); } const float x = ldt(st, sb + c * ss); if (f & kPreview) { const int64_t pb = rowoff(pv, L * stride + k, n); stt(pv, pb + c * laststride(pv), x - s * vv); } - float xn = rnd(dt, x + rnd(dt, dts * vv)); + float xn = round_dt(dt, x + round_dt(dt, dts * vv)); if (f & kInpaint) { const float m = ldt(mask, offlin(mask, L * stride + k)); const float src = ldt(inp, rowoff(inp, L * stride + k, n) + c * laststride(inp)); const float nz = rad_philox_normal(sd, (uint64_t)(k * n + c)); const float kept = (1.0f - sn) * src + sn * nz; - xn = rnd(dt, m * xn + (1.0f - m) * kept); + xn = round_dt(dt, m * xn + (1.0f - m) * kept); } stt(st, sb + c * ss, xn); } @@ -396,9 +358,9 @@ int ref_flow_euler(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------------ chan_affine */ -/* A per-channel affine from two lists the PARAMETERS carry (a latent's mean and deviation are - * configuration, not weights), each value rounded to bf16 as the reference's bf16 tensor of it: - * mode `fma` is bf16(bf16(x * mul) + add), `inv` is bf16(bf16(x - add) / mul). */ +/* A per-channel affine from two parameter lists (a latent's mean and deviation are configuration, + * not weights), each value rounded to bf16 as upstream holds it: mode `fma` is + * bf16(bf16(x * mul) + add), `inv` is bf16(bf16(x - add) / mul). */ int ref_chan_affine(const RadArgs* a, RadStream) { if (!have(a, 2)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *y = &a->t[1]; @@ -410,16 +372,16 @@ int ref_chan_affine(const RadArgs* a, RadStream) { const char* mode = p_str(a, "mode", "fma"); const bool inv = mode && !std::strcmp(mode, "inv"); if (!inv && mode && std::strcmp(mode, "fma")) return RAD_E_INVAL; - const int64_t rows = rows_n(y, n); - if (rows <= 0 || rows_n(x, n) < rows) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + const int64_t rows = rows_of(y, n); + if (rows <= 0 || rows_of(x, n) < rows) return RAD_E_SHAPE; + REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { const int64_t xb = rowoff(x, r, n), xs = laststride(x); const int64_t yb = rowoff(y, r, n), ys = laststride(y); for (int64_t c = 0; c < n; ++c) { const float v = ldt(x, xb + c * xs); - stt(y, yb + c * ys, inv ? rnd(y->dtype, v - add[c]) / mul[c] - : rnd(y->dtype, v * mul[c]) + add[c]); + stt(y, yb + c * ys, inv ? round_dt(y->dtype, v - add[c]) / mul[c] + : round_dt(y->dtype, v * mul[c]) + add[c]); } } return RAD_OK; @@ -432,8 +394,8 @@ int ref_chan_affine(const RadArgs* a, RadStream) { * up 2 the input is first upsampled 2x nearest-neighbour (`nearest-exact` at an exact * factor of two is the same): the conv reads x[y / 2, x / 2] * pad same k / 2 zeros on every side - * pad down no zeros above and left, one below and right -- ZeroPad2d((0, 1, 0, 1)) then the - * conv, a stride-2 downsample's + * pad down no zeros above and left, one below and right: ZeroPad2d((0, 1, 0, 1)) then the conv, + * as a stride-2 downsample does * * f32 accumulation over (kh, kw, cin), the bias added, one rounding. */ int ref_conv2d_nhwc(const RadArgs* a, RadStream) { @@ -447,13 +409,14 @@ int ref_conv2d_nhwc(const RadArgs* a, RadStream) { if (x->rank != 2 || y->rank != 2 || x->shape[1] % cin || y->shape[1] % cout) return RAD_E_SHAPE; const int64_t Hin = x->shape[0], Win = x->shape[1] / cin; const int64_t Ho = y->shape[0], Wo = y->shape[1] / cout; + if (Hin <= 0 || Win <= 0 || Ho <= 0 || Wo <= 0) return RAD_E_SHAPE; const int64_t Hv = Hin * up, Wv = Win * up; const int64_t pt = down ? 0 : k / 2, pb = down ? 1 : k / 2; if ((Hv + pt + pb - k) / stride + 1 != Ho || (Wv + pt + pb - k) / stride + 1 != Wo) return RAD_E_SHAPE; if (numel(w) < cout * cin * k * k || numel(b) < cout) return RAD_E_SHAPE; const int64_t xr = x->stride[0], yr = y->stride[0]; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(Ho * Wo * cout * cin * k * k) for (int64_t oy = 0; oy < Ho; ++oy) for (int64_t ox = 0; ox < Wo; ++ox) for (int64_t co = 0; co < cout; ++co) { @@ -475,7 +438,7 @@ int ref_conv2d_nhwc(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------------ l2norm_chan */ -/* An image norm over the channels of each pixel, the reference's three bf16 tensors: +/* An image norm over each pixel's channels, as upstream's three bf16 tensors: * n1 = bf16(x / max(||x||, 1e-12)), n2 = bf16(n1 * sqrt(n)), y = bf16(n2 * gamma), then `act` * (none, or silu: bf16(y * sigmoid(y))). */ int ref_l2norm_chan(const RadArgs* a, RadStream) { @@ -486,11 +449,11 @@ int ref_l2norm_chan(const RadArgs* a, RadStream) { const char* act = p_str(a, "act", "none"); const bool silu = act && !std::strcmp(act, "silu"); if (!silu && act && std::strcmp(act, "none")) return RAD_E_INVAL; - const int64_t rows = rows_n(y, n); - if (rows <= 0 || rows_n(x, n) < rows) return RAD_E_SHAPE; + const int64_t rows = rows_of(y, n); + if (rows <= 0 || rows_of(x, n) < rows) return RAD_E_SHAPE; const float sq = (float)std::sqrt((double)n); const uint32_t dt = y->dtype; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { const int64_t xb = rowoff(x, r, n), xs = laststride(x); const int64_t yb = rowoff(y, r, n), ys = laststride(y); @@ -498,10 +461,10 @@ int ref_l2norm_chan(const RadArgs* a, RadStream) { for (int64_t c = 0; c < n; ++c) { const float v = ldt(x, xb + c * xs); ss += v * v; } const float nrm = std::max(std::sqrt(ss), 1e-12f); for (int64_t c = 0; c < n; ++c) { - const float n1 = rnd(dt, ldt(x, xb + c * xs) / nrm); - const float n2 = rnd(dt, n1 * sq); - float v = rnd(dt, n2 * ldt(g, c)); - if (silu) v = v / (1.0f + std::exp(-v)); + const float n1 = round_dt(dt, ldt(x, xb + c * xs) / nrm); + const float n2 = round_dt(dt, n1 * sq); + float v = round_dt(dt, n2 * ldt(g, c)); + if (silu) v = v / (1.0f + ref_exp(-v)); stt(y, yb + c * ys, v); } } @@ -512,7 +475,7 @@ int ref_l2norm_chan(const RadArgs* a, RadStream) { /* d2s_add, the decoder's upsampling shortcut (Wan's DupUp3D on one frame): x [H, W * cin] repeated * `rep = cout * F / cin` times per channel and dealt into a 2x larger y [2H, 2W * cout], added: * y[2r+i, 2c+j, o] += x[r, c, (o * F + off + 2i + j) / rep], F = 4 * ft, off = 4 when ft is 2 - * (the second of the two frames a temporal factor makes is the one a first chunk keeps). */ + * (a first chunk keeps the second of the two frames a temporal factor makes). */ int ref_d2s_add(const RadArgs* a, RadStream) { if (!have(a, 2)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *y = &a->t[1]; @@ -520,12 +483,13 @@ int ref_d2s_add(const RadArgs* a, RadStream) { if (cin <= 0 || cout <= 0 || (ft != 1 && ft != 2)) return RAD_E_SHAPE; if (x->rank != 2 || y->rank != 2 || x->shape[1] % cin || y->shape[1] % cout) return RAD_E_SHAPE; const int64_t H = x->shape[0], W = x->shape[1] / cin; + if (H <= 0 || W <= 0) return RAD_E_SHAPE; if (y->shape[0] != 2 * H || y->shape[1] / cout != 2 * W) return RAD_E_SHAPE; const int64_t F = 4 * ft, off = ft == 2 ? 4 : 0; if ((cout * F) % cin) return RAD_E_SHAPE; const int64_t rep = cout * F / cin; const int64_t xr = x->stride[0], yr = y->stride[0]; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(4 * H * W * cout) for (int64_t oy = 0; oy < 2 * H; ++oy) for (int64_t ox = 0; ox < 2 * W; ++ox) for (int64_t o = 0; o < cout; ++o) { @@ -539,8 +503,8 @@ int ref_d2s_add(const RadArgs* a, RadStream) { /* s2d_avg_add, the encoder's downsampling shortcut (Wan's AvgDown3D on one frame): each 2x2 block * of x [2H, 2W * cin] dealt into channels and averaged in groups of gs = cin * F / cout into - * y [H, W * cout], added. A channel of the dealt row is (c, t, i, j) at c * F + 4t + 2i + j; with - * ft 2 the frame t == 0 is the zero frame the reference pads in front, which the mean still counts. */ + * y [H, W * cout], added. A dealt channel (c, t, i, j) sits at c * F + 4t + 2i + j; with ft 2, + * frame t == 0 is upstream's zero padding frame, which the mean still counts. */ int ref_s2d_avg_add(const RadArgs* a, RadStream) { if (!have(a, 2)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *y = &a->t[1]; @@ -548,12 +512,13 @@ int ref_s2d_avg_add(const RadArgs* a, RadStream) { if (cin <= 0 || cout <= 0 || (ft != 1 && ft != 2)) return RAD_E_SHAPE; if (x->rank != 2 || y->rank != 2 || x->shape[1] % cin || y->shape[1] % cout) return RAD_E_SHAPE; const int64_t H = y->shape[0], W = y->shape[1] / cout; + if (H <= 0 || W <= 0) return RAD_E_SHAPE; if (x->shape[0] != 2 * H || x->shape[1] / cin != 2 * W) return RAD_E_SHAPE; const int64_t F = 4 * ft; if ((cin * F) % cout) return RAD_E_SHAPE; const int64_t gs = cin * F / cout; const int64_t xr = x->stride[0], yr = y->stride[0]; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(H * W * cout * gs) for (int64_t oy = 0; oy < H; ++oy) for (int64_t ox = 0; ox < W; ++ox) for (int64_t o = 0; o < cout; ++o) { @@ -565,7 +530,7 @@ int ref_s2d_avg_add(const RadArgs* a, RadStream) { acc += ldt(x, (2 * oy + i) * xr + (2 * ox + j) * cin + c); } const int64_t yo = oy * yr + ox * cout + o; - stt(y, yo, ldt(y, yo) + rnd(y->dtype, acc / (float)gs)); + stt(y, yo, ldt(y, yo) + round_dt(y->dtype, acc / (float)gs)); } return RAD_OK; } @@ -578,9 +543,9 @@ int ref_to_rgba8(const RadArgs* a, RadStream) { const RadTensor *x = &a->t[0], *y = &a->t[1]; const int64_t n = p_int(a, "n", 0); if (n <= 0) return RAD_E_SHAPE; - const int64_t rows = rows_n(y, n); - if (rows <= 0 || rows_n(x, n) < rows || y->dtype != RAD_U8) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + const int64_t rows = rows_of(y, n); + if (rows <= 0 || rows_of(x, n) < rows || y->dtype != RAD_U8) return RAD_E_SHAPE; + REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { const int64_t xb = rowoff(x, r, n), xs = laststride(x); const int64_t yb = rowoff(y, r, n), ys = laststride(y); @@ -601,17 +566,13 @@ int ref_gelu_tanh(const RadArgs* a, RadStream) { const RadTensor *x = &a->t[0], *y = &a->t[1]; const int64_t n = p_int(a, "n", 0); if (n <= 0) return RAD_E_SHAPE; - const int64_t rows = rows_n(y, n); - if (rows <= 0 || rows_n(x, n) < rows) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + const int64_t rows = rows_of(y, n); + if (rows <= 0 || rows_of(x, n) < rows) return RAD_E_SHAPE; + REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { const int64_t xb = rowoff(x, r, n), xs = laststride(x); const int64_t yb = rowoff(y, r, n), ys = laststride(y); - for (int64_t c = 0; c < n; ++c) { - const float v = ldt(x, xb + c * xs); - const float t = std::tanh(0.7978845608028654f * (v + 0.044715f * v * v * v)); - stt(y, yb + c * ys, 0.5f * v * (1.0f + t)); - } + for (int64_t c = 0; c < n; ++c) stt(y, yb + c * ys, act_gelu_tanh(ldt(x, xb + c * xs))); } return RAD_OK; } @@ -622,7 +583,7 @@ int ref_scatter_add_rows(const RadArgs* a, RadStream) { const RadTensor *v = &a->t[0], *idx = &a->t[1], *x = &a->t[2]; const int64_t n = p_int(a, "n", 0); if (n <= 0) return RAD_E_SHAPE; - const int64_t M = rows_n(v, n), dst_rows = rows_n(x, n); + const int64_t M = rows_of(v, n), dst_rows = rows_of(x, n); if (M <= 0 || numel(idx) < M) return RAD_E_SHAPE; for (int64_t m = 0; m < M; ++m) if (ld_int(idx->dtype, idx->data, offlin(idx, m)) >= dst_rows) return RAD_E_INVAL; @@ -637,13 +598,12 @@ int ref_scatter_add_rows(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------------ attn_prefix_self */ -/* Attention over two key sources: the sequence's PREFIX, `seqused[s]` positions in the paged cache, - * and the step's OWN rows, `k` and `v` beside `q` and not in the cache. Self row i of a sequence - * sees every prefix key and, with `causal`, its own rows j <= i -- otherwise all of them. +/* Attention over two key sources: the sequence's prefix (`seqused[s]` positions in the paged cache) + * and the step's own rows (`k` and `v` beside `q`, not cached). Self row i sees every prefix key + * and its own rows j <= i with `causal`, all of them otherwise. * - * It is the attention of a sequence whose rows are recomputed each step against a prefix that is - * not: an image's latent rows against the conditioning, or one segment of the conditioning against - * the segments before it. */ + * For rows recomputed each step against a fixed prefix: an image's latent rows against the + * conditioning, or one conditioning segment against the segments before it. */ /* quant_act_i8g's rule for one row of `n`: the scale (amax/127, 1 for an all-zero row) and the * codes rint(clamp(x * (1/scale), +-127)), in f32 as the device computes them. `code` may be `x`: * each code is written after its value is read. */ @@ -662,7 +622,7 @@ int ref_attn_prefix_self(const RadArgs* a, RadStream) { const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *kv = &a->t[3]; const RadTensor *bt = &a->t[4], *su = &a->t[5], *cu = &a->t[6], *o = &a->t[11]; const RadTensor *kdes = t_in(a, 7), *vdes = t_in(a, 8); - /* THE INT8 Q.K FORM: the own keys' codes and scales given, everything else quantised here. */ + /* The int8 Q.K form: own keys' codes and scales are given; everything else is quantised here. */ const RadTensor *k8 = t_in(a, 9), *ks = t_in(a, 10); const char* qk = p_str(a, "qk", "bf16"); const bool i8 = std::strcmp(qk, "i8") == 0; @@ -671,24 +631,31 @@ int ref_attn_prefix_self(const RadArgs* a, RadStream) { const int64_t head_dim = p_int(a, "head_dim", 0), gqa = p_int(a, "gqa", 1); const int causal = (int)p_int(a, "causal", 0); const int64_t block_size = kv->rank == 4 ? kv->shape[2] : p_int(a, "block_size", 0); + /* The widest head held in the stack rows below. */ + constexpr int64_t kHdMax = 1024; if (head_dim <= 0 || gqa <= 0 || block_size <= 0) return RAD_E_SHAPE; - if (head_dim > 1024) return RAD_E_UNSUPPORTED; + if (head_dim > kHdMax) return RAD_E_UNSUPPORTED; const int64_t kv_heads = kv->rank == 4 ? kv->shape[1] : 0; if (kv_heads <= 0) return RAD_E_SHAPE; const int64_t q_heads = kv_heads * gqa, n_seq = numel(cu) - 1; if (n_seq <= 0 || numel(su) < n_seq) return RAD_E_SHAPE; - /* The rows are cu's own span, which need not start at 0: one segment of a longer sequence is - * passed as the two offsets that bound it. */ + /* The rows are cu's span, which need not start at 0: a segment of a longer sequence is passed + * as its two bounding offsets. */ const int64_t r_first = cu_at(cu, 0), rows = cu_at(cu, n_seq) - r_first; + if (rows <= 0) return RAD_E_SHAPE; const int64_t max_blocks = bt->rank >= 2 ? bt->shape[1] : numel(bt) / n_seq; const int64_t bt_rs = bt->rank >= 2 ? bt->stride[0] : max_blocks; + const int64_t bt_cs = bt->rank >= 2 ? bt->stride[1] : 1; + /* Every prefix key must have a block-table entry. */ + for (int64_t s = 0; s < n_seq; ++s) + if (ld_int(su->dtype, su->data, offlin(su, s)) > max_blocks * block_size) return RAD_E_SHAPE; const int64_t q_rs = row_stride(q, q_heads * head_dim), k_rs = row_stride(k, kv_heads * head_dim); const int64_t v_rs = row_stride(v, kv_heads * head_dim), o_rs = row_stride(o, q_heads * head_dim); const int64_t k8_rs = i8 ? row_stride(k8, kv_heads * head_dim) : 0; const int64_t ks_rs = i8 ? row_stride(ks, kv_heads) : 0; const int64_t sb = kv->stride[0], sh = kv->stride[1], so = kv->stride[2]; const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim)); - #pragma omp parallel for schedule(dynamic) + REF_PAR_FOR_DYN(rows * q_heads * head_dim * 64) for (int64_t idx = 0; idx < rows * q_heads; ++idx) { const int64_t h = idx % q_heads, r = r_first + idx / q_heads, kh = h / gqa; const int64_t s = seq_of(cu, n_seq, r), b0 = cu_at(cu, s), b1 = cu_at(cu, s + 1); @@ -698,12 +665,12 @@ int ref_attn_prefix_self(const RadArgs* a, RadStream) { const int64_t qb = r * q_rs + h * head_dim; const int64_t nself = causal ? i + 1 : b1 - b0; auto pkey = [&](int64_t j, int64_t d, bool val) -> float { - const int64_t blk = ld_int(bt->dtype, bt->data, s * bt_rs + j / block_size); + const int64_t blk = ld_int(bt->dtype, bt->data, s * bt_rs + (j / block_size) * bt_cs); if (blk < 0) return 0.0f; return ldt(kv, blk * sb + kh * sh + (j % block_size) * so + (val ? head_dim : 0) + d) * (val ? vds : kds); }; - float xq[1024], cq[1024], ck[1024]; + float xq[kHdMax], cq[kHdMax], ck[kHdMax]; float sq = 1.0f; if (i8) { for (int64_t d = 0; d < head_dim; ++d) xq[d] = ldt(q, qb + d); @@ -738,7 +705,7 @@ int ref_attn_prefix_self(const RadArgs* a, RadStream) { const int64_t nk = P + nself; float mx = -INFINITY; for (int64_t j = 0; j < nk; ++j) mx = std::max(mx, dot(j)); - float acc[1024]; + float acc[kHdMax]; for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f; float sum = 0.0f; for (int64_t j = 0; j < nk; ++j) { diff --git a/libref/ref_hc.cpp b/libref/ref_hc.cpp index 6c7a05cb..287b96fe 100644 --- a/libref/ref_hc.cpp +++ b/libref/ref_hc.cpp @@ -1,14 +1,12 @@ -/* ref_hc.cpp -- the GATED RESIDUAL, which is Qwen4-Exp's replacement for a pre-norm and a - * residual add. +/* ref_hc.cpp -- the gated residual, Qwen4-Exp's replacement for a pre-norm and a residual add. * - * ============================== WHAT IT IS ============================== + * ============================== What it is ============================== * * The residual stream is `hc` times as wide as the model: hidden_size 2560 at hc_count 4 is a - * 10240-wide stream carried through every layer, entered as four identical copies of the - * embedding and collapsed once at the end. Every block reads a 2560 mix of the four and writes - * its output back into all four, and BOTH the read's mix and the write's per-stream gain are - * data-dependent -- which is what "gated" means here and what makes this a pair of ops rather - * than a norm. + * 10240-wide stream through every layer, entered as four identical copies of the embedding and + * collapsed once at the end. Each block reads a 2560 mix of the four and writes its output back + * into all four; both the read's mix and the write's per-stream gain are data-dependent ("gated"), + * so this is a pair of ops rather than a norm. * * hc_read N = grouped_rmsnorm(h) one rsqrt per 2560 stream, one gain of * 10240 over all four, `1 + w` @@ -17,67 +15,40 @@ * inj[s] = 2 * sigmoid(W_inj[s] . N / hc) four scalars in (0, 2) * hc_write h[s] += inj[s] * y for each stream s * - * THE WRITE READS THE UNNORMED `h`, NOT `N`. The reference is `hyper_input + injection` where - * `hyper_input` is the argument the read received, so the normalisation is consumed entirely by - * the block input and the gate and never enters the stream. Writing back into `N` instead would - * re-normalise the residual on every one of the 96 connections, which diverges within a few - * layers and is the one mistake this pair can make that still produces fluent text. + * The write reads the unnormed `h`, not `N`: upstream computes `hyper_input + injection` with + * `hyper_input` the read's argument, so the normalisation feeds only the block input and the gates. + * Writing into `N` would re-normalise the residual at each of the 96 connections and diverge within + * a few layers while still producing fluent text. * - * THE MIX IS A MEAN, NOT A SUM. `.mean(dim=-2)` over the hc dimension -- so the divide by hc - * happens here AND, separately, inside both gate arguments (`/ self.hc_count` before the silu and - * before the inject sigmoid). Three divisions by 4, all of them in the reference, none of them - * derivable from the others. + * The mix is a mean (`.mean(dim=-2)` over hc), and both gate arguments are separately divided by + * hc (`/ self.hc_count` before the silu and before the inject sigmoid): three independent + * divisions, all upstream's. * - * ============================== WHY THE QUANTISER IS IN THE READ ============================== + * ============================== Why the quantiser is in the read ============================== * - * `q` and `s` are OPTIONAL outputs. Present, the read also emits the fp8 block-scaled form of `x` - * that the following projection's GEMM wants, which is what keeps a gated-residual model at the - * same launch count as a pre-norm one: every launch costs a fixed floor whatever it computes, and a - * model with 96 connections cannot afford a separate quantise op at each. Absent, `x` is bf16 and the - * caller quantises it itself -- which is what the final mixer does, because its consumer is the - * lm_head and that is bf16. + * `q` and `s` are optional outputs. Present, the read also emits the fp8 block-scaled `x` the next + * projection's GEMM wants, keeping the launch count equal to a pre-norm model's (each launch has a + * fixed cost, and there are 96 connections). Absent, `x` is bf16 and the caller quantises it: the + * final mixer feeds the bf16 lm_head. * - * IT QUANTISES WHAT WAS WRITTEN. `x` is narrowed to its own dtype first and the codes are taken - * from the narrowed value, not from the f32 accumulator, because that is what a fused kernel - * necessarily does and the two have to agree bit for bit -- the same epilogue-fold rule the GDN - * out-projection's quantiser follows (libref/ref_gdn.cpp). + * Codes are taken from `x` narrowed to its dtype, not from the f32 accumulator, as a fused kernel + * must (the GDN out-projection quantiser follows the same rule, libref/ref_gdn.cpp). * - * `rq` and `rs` are the same argument one consumer further: had_quant_act_fp8 of the stored `x`, - * for an expert plane stored with a 128-wide Hadamard, whose block would otherwise run that - * quantiser as a launch of its own. + * `rq` and `rs` extend this one consumer further: had_quant_act_fp8 of the stored `x`, for expert + * planes stored with a 128-wide Hadamard. */ #include "ref_common.h" #include "ref_ops.h" +#include "ref_planes.h" #include using namespace ref; -namespace { - -/* A value narrowed to a tensor's own dtype and read back. The reference's arithmetic is f32 - * throughout, but the REFERENCE MODEL's is not: torch's grouped norm returns `.type_as(x)`, so the - * two matrix products and the final multiply all read a bf16 `N`. Rounding once here is what makes - * a fused kernel able to match this to a tolerance that means something. */ -inline float narrow(uint32_t dtype, float v) { - uint32_t buf[2] = {0, 0}; - st_dt(dtype, buf, 0, v); - return ld_dt(dtype, buf, 0); -} - -inline float sigmoidf(float v) { return 1.0f / (1.0f + std::exp(-v)); } -inline float siluf(float v) { return v * sigmoidf(v); } - -} /* namespace */ - /* ------------------------------------------------------------------ hc_enter */ -/* THE WIDE STREAM'S FIRST VALUE: hc identical copies of the embedding. - * - * It is one launch for the whole step and it exists rather than being folded into the embedding - * lookup because the lookup's weight is [vocab, n] and its output width is n -- a wide output - * would be a different op with a different weight shape. The four streams are identical here and - * diverge at the first connection, because each block writes into all four with a DIFFERENT - * per-branch gain. */ +/* The wide stream's initial value: hc identical copies of the embedding. Separate from the + * embedding lookup, whose output width is n. The streams diverge at the first connection, since + * each block writes into them with different per-stream gains. */ int ref_hc_enter(const RadArgs* a, RadStream) { if (!have(a, 2)) return RAD_E_INVAL; const RadTensor* x = &a->t[0]; @@ -87,7 +58,7 @@ int ref_hc_enter(const RadArgs* a, RadStream) { if (n <= 0 || hc <= 1) return RAD_E_SHAPE; const int64_t rows = numel(x) / n; if (rows <= 0 || numel(h) < rows * hc * n) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * hc * n) for (int64_t r = 0; r < rows; ++r) { const int64_t xb = rowoff(x, r, n), hb = rowoff(h, r, hc * n); const int64_t xs = laststride(x), hs = laststride(h); @@ -101,8 +72,8 @@ int ref_hc_enter(const RadArgs* a, RadStream) { /* ------------------------------------------------------------------ hc_read */ int ref_hc_read(const RadArgs* a, RadStream) { - /* NOT `have(a, 6)`: operand 4 is the OPTIONAL inject weight, and a prefix test would refuse - * the final mixer -- the one connection that has none. The required ones are 0..3 and 5. */ + /* Not `have(a, 6)`: operand 4, the inject weight, is optional (the final mixer has none). + * Operands 0..3 and 5 are required. */ if (a->n_t < 6) return RAD_E_INVAL; if (!rad_arg_in(a, 0) || !rad_arg_in(a, 1) || !rad_arg_in(a, 2) || !rad_arg_in(a, 3) || !rad_arg_in(a, 5)) return RAD_E_INVAL; @@ -112,10 +83,10 @@ int ref_hc_read(const RadArgs* a, RadStream) { const RadTensor* up = &a->t[3]; const RadTensor* injw = t_in(a, 4); /* absent on the final mixer */ const RadTensor* x = &a->t[5]; - const RadTensor* inj = rad_arg_in(a, 6); /* an OUT, but the optional test is the same */ + const RadTensor* inj = rad_arg_in(a, 6); /* an OUT; same optional test */ const RadTensor* q = rad_arg_in(a, 7); const RadTensor* s = rad_arg_in(a, 8); - const RadTensor* rq = rad_arg_in(a, 9); /* the ROTATED fp8 form, for a w4a8h consumer */ + const RadTensor* rq = rad_arg_in(a, 9); /* the rotated fp8 form, for a w4a8h consumer */ const RadTensor* rs = rad_arg_in(a, 10); const int64_t n = p_int(a, "n", 0); @@ -127,11 +98,19 @@ int ref_hc_read(const RadArgs* a, RadStream) { const int64_t hn = hc * n; const int64_t rows = numel(h) / hn; - if (rows <= 0 || numel(x) < rows * n || numel(w) < hn || - numel(down) < lr * hn || numel(up) < hn * lr) return RAD_E_SHAPE; + if (rows <= 0 || numel(x) < rows * n || numel(w) < hn) return RAD_E_SHAPE; + /* The mixing matrices are plain, or codes and a scale plane joined (ref_planes.h; `mix` + * e4m3), read element by element as the core's decoder gives them. A plain matrix's dtype is + * what the gate it feeds is rounded to; a joined one's gates are rounded to h's. */ + ScaledRows jd, ju; + const bool jdown = is_joined(down), jup = is_joined(up); + if (jdown) RAD_REF_TRY(scaled_rows(down, lr, hn, &jd)); + else if (numel(down) < lr * hn) return RAD_E_SHAPE; + if (jup) RAD_REF_TRY(scaled_rows(up, hn, lr, &ju)); + else if (numel(up) < hn * lr) return RAD_E_SHAPE; + const uint32_t ddt = jdown ? h->dtype : down->dtype, udt = jup ? h->dtype : up->dtype; if (injw && numel(injw) < hc * hn) return RAD_E_SHAPE; - /* `inj` is what the paired hc_write consumes, so an inject WEIGHT with no inject OUTPUT is a - * caller that computed four scalars and threw them away -- refused rather than ignored. */ + /* An inject weight without an inject output would compute scalars nobody reads; refused. */ if (injw && (!inj || !inj->data || numel(inj) < rows * hc)) return RAD_E_SHAPE; int64_t g = 0; @@ -142,10 +121,9 @@ int ref_hc_read(const RadArgs* a, RadStream) { ngrp = (n + g - 1) / g; if (numel(q) < rows * n || !s || !s->data || numel(s) < rows * ngrp) return RAD_E_SHAPE; } - /* The rotated form rotates each scale group whole, so the group must tile the row exactly and - * be a power of two: a block that straddled the end of the row would mix real values with - * padding, and no weight block was rotated that way. It is had_quant_act_fp8 of the stored `x` - * -- the operand's consumer cannot tell which op wrote it. */ + /* The rotated form rotates each scale group whole, so the group must be a power of two that + * tiles the row; no weight block was rotated across padding. The result equals + * had_quant_act_fp8 of the stored `x`. */ int64_t rg = 0; if (rq) { rg = p_int(a, "group", 0); @@ -154,12 +132,14 @@ int ref_hc_read(const RadArgs* a, RadStream) { if (rg > REF_HAD_MAX) return RAD_E_UNSUPPORTED; } - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * hn * (2 * lr + hc)) for (int64_t r = 0; r < rows; ++r) { const int64_t hb = rowoff(h, r, hn), xb = rowoff(x, r, n); const int64_t hs = laststride(h), xs = laststride(x), ws = laststride(w); - /* ---- the grouped norm. One rsqrt per stream over its own n, then the full-width gain. */ + /* ---- grouped norm: one rsqrt per stream over its n, then the full-width gain. N is + * rounded to h's dtype: upstream's norm returns `.type_as(x)`, so every product reads it + * rounded. */ std::vector N((size_t)hn); for (int64_t c = 0; c < hc; ++c) { double ss = 0.0; @@ -170,69 +150,60 @@ int ref_hc_read(const RadArgs* a, RadStream) { const float sc = 1.0f / std::sqrt((float)(ss / (double)n) + eps); for (int64_t i = 0; i < n; ++i) { const int64_t j = c * n + i; - N[(size_t)j] = narrow(h->dtype, - ldt(h, hb + j * hs) * sc * (ldt(w, j * ws) + wadd)); + N[(size_t)j] = round_dt(h->dtype, + ldt(h, hb + j * hs) * sc * (ldt(w, j * ws) + wadd)); } } - /* ---- the read gate: 10240 -> lowrank -> 10240, silu between and sigmoid after. */ + /* ---- read gate: hc*n -> lowrank -> hc*n, silu between and sigmoid after. */ std::vector d((size_t)lr); for (int64_t j = 0; j < lr; ++j) { float acc = 0.0f; - const int64_t db = rowoff(down, j, hn); + const int64_t db = jdown ? 0 : rowoff(down, j, hn); const int64_t ds = laststride(down); - for (int64_t i = 0; i < hn; ++i) acc += N[(size_t)i] * ldt(down, db + i * ds); - d[(size_t)j] = narrow(down->dtype, siluf(acc / (float)hc)); + for (int64_t i = 0; i < hn; ++i) + acc += N[(size_t)i] * (jdown ? jd.at(j, i) : ldt(down, db + i * ds)); + d[(size_t)j] = round_dt(ddt, act_silu(acc / (float)hc)); } - /* ---- the mix, and the mean over the streams. */ + /* ---- the gated mix, averaged over the streams. */ for (int64_t i = 0; i < n; ++i) { float acc = 0.0f; for (int64_t c = 0; c < hc; ++c) { const int64_t row = c * n + i; - const int64_t ub = rowoff(up, row, lr); + const int64_t ub = jup ? 0 : rowoff(up, row, lr); const int64_t us = laststride(up); float gv = 0.0f; - for (int64_t j = 0; j < lr; ++j) gv += d[(size_t)j] * ldt(up, ub + j * us); - acc += narrow(up->dtype, sigmoidf(gv)) * N[(size_t)row]; + for (int64_t j = 0; j < lr; ++j) + gv += d[(size_t)j] * (jup ? ju.at(row, j) : ldt(up, ub + j * us)); + acc += round_dt(udt, act_sigmoid(gv)) * N[(size_t)row]; } stt(x, xb + i * xs, acc / (float)hc); } - /* ---- the per-branch write gates. */ + /* ---- per-stream write gates. */ if (injw && inj) { const int64_t ib = rowoff(inj, r, hc), is = laststride(inj); for (int64_t c = 0; c < hc; ++c) { float acc = 0.0f; const int64_t jb = rowoff(injw, c, hn), js = laststride(injw); for (int64_t i = 0; i < hn; ++i) acc += N[(size_t)i] * ldt(injw, jb + i * js); - stt(inj, ib + c * is, 2.0f * sigmoidf(acc / (float)hc)); + stt(inj, ib + c * is, 2.0f * act_sigmoid(acc / (float)hc)); } } - /* ---- the optional fp8 form of x, read back from what was stored. */ + /* ---- optional fp8 form of x, from the stored values. */ if (q && q->data) { const int64_t qb = rowoff(q, r, n), qs = laststride(q); for (int64_t gi = 0; gi < ngrp; ++gi) { const int64_t k0 = gi * g, k1 = (k0 + g < n) ? k0 + g : n; - float amax = 0.0f; - for (int64_t i = k0; i < k1; ++i) { - const float m = std::fabs(ldt(x, xb + i * xs)); - if (m > amax) amax = m; - } - const float sc = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f; - const float invs = 1.0f / sc; - for (int64_t i = k0; i < k1; ++i) { - float v = ldt(x, xb + i * xs) * invs; - if (v > 448.0f) v = 448.0f; - if (v < -448.0f) v = -448.0f; - st_dt(q->dtype, q->data, qb + i * qs, v); - } + const float sc = q8_group([&](int64_t i) { return ldt(x, xb + (k0 + i) * xs); }, + k1 - k0, 448.0f, q, qb + k0 * qs, qs); stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc); } } - /* ---- the optional ROTATED fp8 form of x, from the same stored values. */ + /* ---- optional rotated fp8 form of x, from the same stored values. */ if (rq) { float buf[REF_HAD_MAX]; const int64_t qb = rowoff(rq, r, n), qs = laststride(rq), rgrp = n / rg; @@ -240,19 +211,8 @@ int ref_hc_read(const RadArgs* a, RadStream) { const int64_t k0 = gi * rg; for (int64_t i = 0; i < rg; ++i) buf[i] = ldt(x, xb + (k0 + i) * xs); fwht(buf, rg); - float amax = 0.0f; - for (int64_t i = 0; i < rg; ++i) { - const float m = std::fabs(buf[i]); - if (m > amax) amax = m; - } - const float sc = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f; - const float invs = 1.0f / sc; - for (int64_t i = 0; i < rg; ++i) { - float v = buf[i] * invs; - if (v > 448.0f) v = 448.0f; - if (v < -448.0f) v = -448.0f; - st_dt(rq->dtype, rq->data, qb + (k0 + i) * qs, v); - } + const float sc = q8_group([&](int64_t i) { return buf[i]; }, rg, 448.0f, rq, + qb + k0 * qs, qs); stt(rs, rowoff(rs, r, rgrp) + gi * laststride(rs), sc); } } @@ -261,8 +221,8 @@ int ref_hc_read(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------------ hc_write */ -/* `h[s] += inj[s] * y` for each of the hc streams. In place: `h` is the only output and it is the - * stream the paired read was handed, unchanged by it. */ +/* h[s] += inj[s] * y for each of the hc streams, in place on the stream the paired read was given + * (which the read left unchanged). */ int ref_hc_write(const RadArgs* a, RadStream) { if (!have(a, 3)) return RAD_E_INVAL; const RadTensor* y = &a->t[0]; @@ -277,7 +237,7 @@ int ref_hc_write(const RadArgs* a, RadStream) { const int64_t rows = numel(y) / n; if (rows <= 0 || numel(h) < rows * hn || numel(inj) < rows * hc) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * hn) for (int64_t r = 0; r < rows; ++r) { const int64_t yb = rowoff(y, r, n), hb = rowoff(h, r, hn), ib = rowoff(inj, r, hc); const int64_t ys = laststride(y), hs = laststride(h), is = laststride(inj); @@ -294,20 +254,19 @@ int ref_hc_write(const RadArgs* a, RadStream) { /* ================================================================== mtp_enter * - * THE MULTI-TOKEN-PREDICTION HEAD'S ENTRY, for a model whose residual stream is `hc` wide. + * The multi-token-prediction head's entry for a model whose residual stream is `hc` wide. * * A pre-norm MTP head (Qwen3.5, Qwen3-Next, DeepSeek-V3) joins the trunk's hidden state and the - * next token's embedding with ONE `fc` over their concatenation, and arch/common/rad_block_mtp_fp8.h - * runs that as two rmsnorms into the two halves of one buffer and a single gemm_nt. Qwen4-Exp's - * head cannot: its hidden state is the WIDE stream and the checkpoint carries TWO square matrices, + * next token's embedding with one `fc` over their concatenation (arch/common/rad_block_mtp_fp8.h: + * two rmsnorms into one buffer, one gemm_nt). Qwen4-Exp's hidden state is the wide stream and the + * checkpoint carries two square matrices, * * mtp.fc_hidden.weight [n, n] mtp.pre_fc_norm_hidden.weight [hc * n] * mtp.fc_embedding.weight [n, n] mtp.pre_fc_norm_embedding.weight [n] * - * so the hidden half is `fc_h` applied to EACH of the hc sub-streams -- the reference's own - * `.unflatten(-1, (hc_count, hidden_size))` idiom, which is how every other 10240-wide tensor in - * this architecture is handled -- and the embedding half is one 2560-wide product added into all - * hc of them, which is the same broadcast the trunk enters the stream with (`hidden_states.repeat`). + * so the hidden half is `fc_h` applied to each of the hc sub-streams (upstream's + * `.unflatten(-1, (hc_count, hidden_size))` idiom) and the embedding half is one n-wide product + * added into all of them, the broadcast the trunk enters the stream with (`hidden_states.repeat`). * * rs_e = rsqrt(mean(e^2) + eps) * ne[j] = e[j] * rs_e * (w_e[j] + wadd) @@ -316,19 +275,15 @@ int ref_hc_write(const RadArgs* a, RadStream) { * nh[k][j] = h[k*n+j] * rs[k] * (w_h[k*n+j] + wadd) * x[k*n+i] = sum_j fc_h[i][j] * nh[k][j] + fe[i] * - * IT IS ONE OP AND NOT SIX because every intermediate above is a DIFFERENT VIEW of the same bytes - * and this ABI has no reinterpreting view: `nh` is [M*hc, n] to the GEMM and [M, hc*n] to the norm, - * and core/runtime/issue.cpp narrows dim 0 or the last dimension with every stride left alone -- - * which is the right rule and makes a row-pitch change inexpressible. Spelling the entry as one op - * is what lets the wide buffers stay wide. It is also six launches off a draft round, and a draft - * round is the latency this head exists to hide. + * One op rather than six because the intermediates are different views of the same bytes and the + * ABI has no reinterpreting view: `nh` is [M*hc, n] to the GEMM and [M, hc*n] to the norm, while + * core/runtime/issue.cpp only narrows dim 0 or the last dimension with strides unchanged, so a + * row-pitch change is inexpressible. It also saves launches in the latency-critical draft round. * - * `ngroup` IS THE ONE THING THE CHECKPOINT DOES NOT SAY. A [hc * n] gain fits both a grouped norm - * (hc rsqrts, one per sub-stream -- what Qwen4ExpTextGatedResidual does at every one of its 97 - * connections) and a flat one (a single rsqrt over the whole wide row). Both are self-consistent - * and no per-op oracle can tell them apart, exactly as rad_block_mtp_fp8.h's concat order cannot - * be told apart -- and it has the same cheap empirical answer, the draft acceptance rate. `ngroup` - * carries the choice so it is asked once, at declare, instead of being compiled in. + * `ngroup` is the one thing the checkpoint does not say: a [hc * n] gain fits both a grouped norm + * (hc rsqrts, one per sub-stream, as Qwen4ExpTextGatedResidual does) and a flat one (one rsqrt over + * the wide row). No per-op oracle can tell them apart; the draft acceptance rate can. `ngroup` + * makes it a declare-time choice. */ int ref_mtp_enter(const RadArgs* a, RadStream) { if (!have(a, 7)) return RAD_E_INVAL; @@ -352,15 +307,21 @@ int ref_mtp_enter(const RadArgs* a, RadStream) { const int64_t rows = numel(h) / hn; if (rows <= 0 || numel(e) < rows * n || numel(x) < rows * hn) return RAD_E_SHAPE; if (numel(w_h) < hn || numel(w_e) < n) return RAD_E_SHAPE; - if (numel(fc_h) < n * n || numel(fc_e) < n * n) return RAD_E_SHAPE; + /* The fc matrices are plain, or codes and a scale plane joined (`fc` e4m3), as hc_read's. */ + ScaledRows jh, je; + const bool jfh = is_joined(fc_h), jfe = is_joined(fc_e); + if (jfh) RAD_REF_TRY(scaled_rows(fc_h, n, n, &jh)); + else if (numel(fc_h) < n * n) return RAD_E_SHAPE; + if (jfe) RAD_REF_TRY(scaled_rows(fc_e, n, n, &je)); + else if (numel(fc_e) < n * n) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * hn * n) for (int64_t r = 0; r < rows; ++r) { const int64_t hb = rowoff(h, r, hn), eb = rowoff(e, r, n), xb = rowoff(x, r, hn); const int64_t hs = laststride(h), es = laststride(e), xs = laststride(x); const int64_t whs = laststride(w_h), wes = laststride(w_e); - /* ---- the embedding half: one norm and one 2560-wide product, shared by every stream. */ + /* ---- embedding half: one norm and one n-wide product, shared by every stream. */ double ss = 0.0; for (int64_t i = 0; i < n; ++i) { const float v = ldt(e, eb + i * es); @@ -369,19 +330,21 @@ int ref_mtp_enter(const RadArgs* a, RadStream) { const float rse = 1.0f / std::sqrt((float)(ss / (double)n) + eps); std::vector ne((size_t)n); for (int64_t i = 0; i < n; ++i) - ne[(size_t)i] = narrow(e->dtype, ldt(e, eb + i * es) * rse * (ldt(w_e, i * wes) + wadd)); + ne[(size_t)i] = round_dt(e->dtype, + ldt(e, eb + i * es) * rse * (ldt(w_e, i * wes) + wadd)); std::vector fe((size_t)n); for (int64_t i = 0; i < n; ++i) { float acc = 0.0f; - const int64_t fb = rowoff(fc_e, i, n); + const int64_t fb = jfe ? 0 : rowoff(fc_e, i, n); const int64_t fs = laststride(fc_e); - for (int64_t j = 0; j < n; ++j) acc += ne[(size_t)j] * ldt(fc_e, fb + j * fs); + for (int64_t j = 0; j < n; ++j) + acc += ne[(size_t)j] * (jfe ? je.at(i, j) : ldt(fc_e, fb + j * fs)); fe[(size_t)i] = acc; } - /* ---- the hidden half: the grouped norm, then the SAME square matrix over each stream. - * The flat reading is one rsqrt over the whole wide row; `ngroup` says which. */ + /* ---- hidden half: the norm (grouped, or flat per `ngroup`), then the same square matrix + * over each stream. */ float flat = 0.0f; if (ngroup == 1) { double sw = 0.0; @@ -405,14 +368,15 @@ int ref_mtp_enter(const RadArgs* a, RadStream) { } for (int64_t i = 0; i < n; ++i) { const int64_t j = c * n + i; - nh[(size_t)i] = narrow(h->dtype, - ldt(h, hb + j * hs) * sc * (ldt(w_h, j * whs) + wadd)); + nh[(size_t)i] = round_dt(h->dtype, + ldt(h, hb + j * hs) * sc * (ldt(w_h, j * whs) + wadd)); } for (int64_t i = 0; i < n; ++i) { float acc = 0.0f; - const int64_t fb = rowoff(fc_h, i, n); + const int64_t fb = jfh ? 0 : rowoff(fc_h, i, n); const int64_t fs = laststride(fc_h); - for (int64_t j = 0; j < n; ++j) acc += nh[(size_t)j] * ldt(fc_h, fb + j * fs); + for (int64_t j = 0; j < n; ++j) + acc += nh[(size_t)j] * (jfh ? jh.at(i, j) : ldt(fc_h, fb + j * fs)); stt(x, xb + (c * n + i) * xs, acc + fe[(size_t)i]); } } diff --git a/libref/ref_moe.cpp b/libref/ref_moe.cpp index 18af48d2..0192d22c 100644 --- a/libref/ref_moe.cpp +++ b/libref/ref_moe.cpp @@ -1,24 +1,22 @@ /* ref_moe.cpp -- routing, the scatter/gather pair, the grouped GEMM, and the exact row top-k. * - * ============================== WHAT sorted_tok CARRIES ============================== + * ============================== What sorted_tok carries ============================== * - * docs/OPS.md names the operand and does not say what is in it, and the choice decides whether - * `moe_gather` can work at all. It holds the FLATTENED (token, slot) index -- token * top_k + slot - * -- grouped by expert, not the bare token id. With the bare id, gather would have no way to find - * which of a token's top_k routing weights applies to a row, and would have to search. This is - * also vLLM's `sorted_token_ids` convention, so a kernel lifted from there needs no translation. + * The flattened (token, slot) index, token * top_k + slot, grouped by expert; not the bare token + * id, with which moe_gather could not find which of a token's routing weights applies to a row. + * This is vLLM's `sorted_token_ids` convention. * - * A slot whose expert id is outside [0, n_expert) is DROPPED: it is not counted, and the tail of - * sorted_tok from expert_offset[n_expert] to M*top_k is filled with -1. A padded batch row has to - * be expressible, and a negative id is how it is said. + * A slot whose expert id is outside [0, n_expert) is dropped: not counted, and the tail of + * sorted_tok from expert_offset[n_expert] to M*top_k is filled with -1. A negative id marks a + * padded batch row. * - * The histogram this produces is what rad_route_report hands the heat engine; it is read back - * asynchronously and consumed on the NEXT step, and nothing here blocks the compute stream - * (spec §5.5). + * The resulting histogram is what rad_route_report hands the heat engine; it is read back + * asynchronously and consumed on the next step, without blocking the compute stream (spec §5.5). */ #include "ref_common.h" #include "ref_gemm.h" #include "ref_ops.h" +#include "ref_planes.h" #include #include @@ -27,10 +25,9 @@ using namespace ref; /* ------------------------------------------------------------------ router_topk */ -/* softmax over ALL n_expert logits, then the top_k by probability, then -- if `norm` -- renormalise - * the kept weights to sum to one. Softmax first and select second is the order Mixtral, Qwen3 and - * every model in this engine's scope use; selecting first and normalising the raw logits would be - * a different router, so the order is part of the op rather than an implementation choice. */ +/* Softmax over all n_expert logits, then the top_k by probability, then (with `norm`) renormalise + * the kept weights to sum to one. Softmax-then-select is the order Mixtral, Qwen3 and every model in + * scope use; selecting first would be a different router. */ int ref_router_topk(const RadArgs* a, RadStream) { if (!have(a, 3)) return RAD_E_INVAL; const RadTensor *lg = &a->t[0], *ids = &a->t[1], *w = &a->t[2]; @@ -41,7 +38,7 @@ int ref_router_topk(const RadArgs* a, RadStream) { const int64_t M = numel(lg) / n_expert; if (M <= 0 || numel(ids) < M * top_k || numel(w) < M * top_k) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(M * n_expert * (top_k + 2)) for (int64_t m = 0; m < M; ++m) { const int64_t lb = rowoff(lg, m, n_expert), ls = laststride(lg); float mx = -INFINITY; @@ -53,8 +50,8 @@ int ref_router_topk(const RadArgs* a, RadStream) { for (int64_t e = 0; e < n_expert; ++e) sum += ref_exp(ldt(lg, lb + e * ls) - mx); const float inv = sum > 0.0f ? 1.0f / sum : 0.0f; - /* The selection runs on the LOGITS, not the probabilities: softmax is monotone, so the - * order is identical and the comparison is exact rather than through an exp. */ + /* Select on the logits: softmax is monotone, so the order is the same and the comparison + * avoids an exp. */ float pv = INFINITY; int64_t pi = -1, kept = 0; float wsum = 0.0f; @@ -78,9 +75,9 @@ int ref_router_topk(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------------ moe_scatter */ -/* `protect`: local experts the sort places LAST, in the order listed, the rest closed up -- the - * layout a layer that serves a few experts with a second grouped GEMM needs (libr4d's sort_place). - * Returns false on a list that is not strictly ascending inside [0, n). */ +/* `protect`: local experts the sort places last, in the order listed, the rest closed up; the + * layout a layer serving a few experts with a second grouped GEMM needs (libr4d's sort_place). + * Returns false unless the list is strictly ascending within [0, n). */ static bool sort_places(const char* s, int64_t n, std::vector* place) { std::vector prot; for (const char* c = s ? s : ""; *c;) { @@ -100,17 +97,15 @@ static bool sort_places(const char* s, int64_t n, std::vector* place) { return true; } -/* A stable counting sort of the (token, slot) pairs by expert id. Serial on purpose: it is O(M) on - * a batch's worth of small integers, and a parallel version would need a per-thread histogram and - * a prefix pass to stay stable, which is more code than the work it saves. */ +/* A stable counting sort of the (token, slot) pairs by expert id. Serial: a parallel stable version + * would need per-thread histograms and a prefix pass, more code than the work it saves. */ int ref_moe_scatter(const RadArgs* a, RadStream) { if (!have(a, 4)) return RAD_E_INVAL; const RadTensor *ids = &a->t[0], *sorted = &a->t[1], *off = &a->t[2], *cnt = &a->t[3]; const int64_t n_expert = p_int(a, "n_expert", 0); const int64_t top_k = p_int(a, "top_k", 1); - /* THIS RANK'S FIRST EXPERT. Subtracted from every routed id, so the range test below is the - * one that was always here and the sort is over local indices -- which is what the weight - * table, the offsets and the GEMM downstream are indexed by. */ + /* This rank's first expert, subtracted from every routed id so the sort runs over local + * indices, as the weight table, offsets and downstream GEMM expect. */ const int64_t base = p_int(a, "expert_base", 0); if (n_expert <= 0 || top_k <= 0 || base < 0) return RAD_E_SHAPE; const int64_t M = numel(ids) / top_k; @@ -139,40 +134,247 @@ int ref_moe_scatter(const RadArgs* a, RadStream) { } st_int(off->dtype, off->data, offlin(off, n_expert), run); - /* A second cursor pass rather than mutating the offsets: the offsets are an output the caller - * reads, and rewinding them afterwards is one more place to be wrong. */ + /* Each slot goes to its expert's cursor, in ascending slot order. The cursors are a copy, so + * the offsets (an output) are never mutated. */ for (int64_t i = run; i < T; ++i) st_int(sorted->dtype, sorted->data, offlin(sorted, i), -1); - for (int64_t e = 0, w = 0; e < n_expert; ++e) { - w = ld_int(off->dtype, off->data, offlin(off, e)); - for (int64_t i = 0; i < T; ++i) { - if (at(i) != e) continue; - st_int(sorted->dtype, sorted->data, offlin(sorted, w), i); - ++w; - } + std::vector cur((size_t)n_expert); + for (int64_t e = 0; e < n_expert; ++e) + cur[(size_t)e] = ld_int(off->dtype, off->data, offlin(off, e)); + for (int64_t i = 0; i < T; ++i) { + const int64_t e = at(i); + if (e >= 0) st_int(sorted->dtype, sorted->data, offlin(sorted, cur[(size_t)e]++), i); } return RAD_OK; } /* ------------------------------------------------------------------ moe_gemm, moe_gemm_q */ -/* y[i, :] = a[row(i), :] @ w[e]^T, where e is the expert whose offset range contains i and - * `a_order` picks row(i) -- `sorted_tok[i] / top_k` when the activation has one row per TOKEN, - * and i itself when it already has one per (token, slot). The output is in SORTED order -- one - * row per (token, slot) pair, laid out the way moe_scatter grouped them -- because that is the - * layout that makes the expert loop contiguous, which is the entire point of the scatter. - * moe_gather puts it back. +/* y[i, :] = a[row(i), :] @ w[e]^T, e the expert whose offset range contains i. `a_order` picks + * row(i): `sorted_tok[i] / top_k` for one activation row per token, i itself for one per + * (token, slot). The output is in sorted order (one row per (token, slot), grouped as moe_scatter + * left them) so the expert loop is contiguous; moe_gather restores token order. * - * THE WEIGHT OPERAND IS A TABLE (RAD_OPD_WTAB), not a plane, and ref_gemm.h's expert_entry() is - * where that is read. A layer's experts are separate movement units, so after placement one is in - * VRAM and the next is streamed over the link; `base + e*stride` describes only the case where - * nothing was offloaded. The stacked form is still accepted, because a caller with no engine - * behind it -- rad-kbench replaying a fixture -- has nowhere to put a pointer array. + * The weight operand is a table (RAD_OPD_WTAB), read through ref_gemm.h's expert_entry(): experts + * are separate movement units, so one may be in VRAM while the next is streamed. The stacked form + * is also accepted for callers without an engine (rad-kbench fixtures). * - * The quantised arm is the same walk with ref_gemm.h's Scales over both operands, and the sub-sum - * is accumulated from the RAW CODES and scaled once per group exactly as `gemm_nt_q` does: the - * two references must agree in the last bits or rad-kbench blames a kernel for a choice made - * here. Only the WEIGHT scale grid is block-shaped -- one scale per 128x128 tile of an expert -- - * while the activation's is per row per group of K, which is `rblk = 1`, which is what - * make_scales derives on its own from the two extents. */ + * The quantised arm uses ref_gemm.h's Scales and quant_dot, accumulating raw codes and scaling once + * per group exactly as gemm_nt_q does. Only the weight scale grid is block-shaped (one scale per + * 128x128 tile); the activation's is per row per K group (rblk = 1), which make_scales derives from + * the extents. */ +/* quant_tile with the loaders resolved at compile time for the grouped GEMM's dtype pairs (the + * same floats as Dyn, which serves the rest). */ +typedef float* (*TileFn)(const Mat&, const Mat&, const Scales&, const Scales&, const int64_t*, + int64_t, int64_t, int64_t, int64_t, float*); + +#define REF_TILE_ROW(DA) \ + case DA: \ + switch (db) { \ + case RAD_F8E4M3: return &quant_tile, Fix>; \ + case RAD_I4: return &quant_tile, Fix>; \ + case RAD_I8: return &quant_tile, Fix>; \ + case RAD_BF16: return &quant_tile, Fix>; \ + case RAD_F32: return &quant_tile, Fix>; \ + default: return &quant_tile; \ + } + +static TileFn pick_tile(uint32_t da, uint32_t db) { + switch (da) { + REF_TILE_ROW(RAD_F8E4M3) + REF_TILE_ROW(RAD_BF16) + REF_TILE_ROW(RAD_F32) + REF_TILE_ROW(RAD_I8) + default: return &quant_tile; + } +} +#undef REF_TILE_ROW + +/* ------------------------------------------------------------------ the codebook experts + * + * Qwen3.8-Flash-Next's experts (docs/MOE-W4.md) are u4 or u5 codes indexing a table of 16 or 32 + * f32 levels, with a scale per (row, group of K): bf16 per 128 (`w4nla8h`), or E4M3 per 64 or 32 + * times one fixed f32 (`w4nl64a8h`, `w4nl32a8h`, `w5nl64a8h`). Element (n, k) of an expert is + * table[code(n, k)] * scale(n, k / group), times `scale.1` where there is one. The codes view takes + * the planes `codes,table` and the two-level forms' scale view `scale,scale.1`; such a weight is + * stored in the joined form of abi/rad_planes.h, which these rows' layout hooks ask for. A view of + * one plane (w4nla8h's bf16 scale, every view of the other dtypes) is stored as it is. + * + * The arithmetic is quant_dot's: per weight group, the sub-sum of table values times activation + * codes, then `(sub * sa) * sb` with sb the scale times its level in f32. The logical form the + * oracle and rad-kbench pass (enc_selection_logical: table entries for codes, scale products for + * scales) goes through the same chain, so the two readings agree bit for bit wherever the logical + * operands hold the values exactly, as E4M3 and bf16 do for the shipped tables and scales. libr4d + * folds each 64- or 32-wide group's sum under its scale first and the activation's scale per 128 + * after (`(sub0 * sb0 + sub1 * sb1) * sa`), which differs in the last bits. */ + +/* What a codebook `dtype` stores: the code width, the scale's group along K and dtype, and whether + * the scale view carries the level above it. `bits` is 0 for any other dtype. */ +struct CbForm { int bits; int64_t group; uint32_t sdt; bool level; }; +static CbForm cb_form(const RadParam* p, int n_p) { + const RadParam* d = rad_param_find(p, n_p, "dtype"); + const char* s = d && d->kind == RAD_P_STR ? d->sval : nullptr; + if (s && !std::strcmp(s, "w4nla8h")) return CbForm{ 4, 128, RAD_BF16, false }; + if (s && !std::strcmp(s, "w4nl64a8h")) return CbForm{ 4, 64, RAD_F8E4M3, true }; + if (s && !std::strcmp(s, "w4nl32a8h")) return CbForm{ 4, 32, RAD_F8E4M3, true }; + if (s && !std::strcmp(s, "w5nl64a8h")) return CbForm{ 5, 64, RAD_F8E4M3, true }; + return CbForm{ 0, 0, 0, false }; +} + +/* Whether a selection of several planes for `operand` is what `dtype` names: the codes operands of + * both grouped GEMMs are 2, 6, 8 and 10 and their scales 3, 7, 9 and 11. RAD_E_DTYPE otherwise, + * which refuses the weight at declare by name. */ +static int cb_check(const RadParam* p, int n_p, int operand, const RadEncoding* enc, + const int* sel, int n_planes) { + const CbForm f = cb_form(p, n_p); + const bool codes = operand == 2 || operand == 6 || operand == 8 || operand == 10; + const bool scale = operand == 3 || operand == 7 || operand == 9 || operand == 11; + if (!f.bits || (!codes && !scale) || !enc || !sel || n_planes != 2 || + std::strcmp(enc->transform, "fwht128") != 0) + return RAD_E_DTYPE; + for (int i = 0; i < 2; ++i) + if (sel[i] < 0 || sel[i] >= enc->n_planes) return RAD_E_SHAPE; + const RadEncPlane& a = enc->plane[sel[0]]; + const RadEncPlane& b = enc->plane[sel[1]]; + if (codes) + return !std::strcmp(a.role, "codes") && a.kind == RAD_PLANE_TILED && + a.dtype == (f.bits == 5 ? (uint32_t)RAD_U5 : (uint32_t)RAD_U4) && + a.block[0] == 1 && a.block[1] == 1 && !std::strcmp(b.role, "table") && + b.kind == RAD_PLANE_TABLE && b.dtype == RAD_F32 && b.extent[0] == 1 && + b.extent[1] == ((int64_t)1 << f.bits) + ? RAD_OK : RAD_E_DTYPE; + return f.level && !std::strcmp(a.role, "scale") && a.kind == RAD_PLANE_TILED && + a.dtype == f.sdt && a.block[0] == 1 && a.block[1] == f.group && + !std::strcmp(b.role, "scale.1") && b.kind == RAD_PLANE_TILED && b.dtype == RAD_F32 && + b.block[0] == 0 && b.block[1] == 0 + ? RAD_OK : RAD_E_DTYPE; +} + +extern "C" int ref_moe_cb_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, + const int* sel, const RadTensor* planes, int n_planes, + RadLayout* out) { + if (n_planes <= 1) return RAD_E_UNSUPPORTED; + const int rc = cb_check(p, n_p, operand, enc, sel, n_planes); + return rc < 0 ? rc : rad_planes_layout(enc, sel, planes, n_planes, out); +} + +extern "C" int ref_moe_cb_relayout(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, const RadTensor* planes, + int n_planes, void* dst, int64_t dst_bytes) { + if (n_planes <= 1) return RAD_E_UNSUPPORTED; + const int rc = cb_check(p, n_p, operand, enc, sel, n_planes); + return rc < 0 ? rc : rad_planes_relayout(enc, sel, planes, n_planes, dst, dst_bytes); +} + +extern "C" int ref_moe_cb_unrelayout(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, const void* src, + int64_t src_bytes, const RadTensor* planes, int n_planes) { + if (n_planes <= 1) return RAD_E_UNSUPPORTED; + const int rc = cb_check(p, n_p, operand, enc, sel, n_planes); + return rc < 0 ? rc : rad_planes_unrelayout(enc, sel, src, src_bytes, planes, n_planes); +} + +/* The joined form's header when weight entry `t` holds one. An entry smaller than a header is a + * plain plane, and is not read past its end. */ +static const RadPlanesHeader* cb_joined(const RadTensor& t) { + int64_t n = 1; + for (uint32_t i = 0; i < t.rank; ++i) n *= t.shape[i]; + if (!t.data || rad_dtype_bytes(t.dtype, n) < (int64_t)sizeof(RadPlanesHeader)) return nullptr; + return rad_planes_header(t.data); +} + +/* A codebook expert's codes, which LdCb reads as table values. The RadTensor comes first, so a Mat + * over `t` reaches the rest: element i is (i / cols, i % cols) of a plane whose rows start + * `row_bytes` apart, the layout rad_planes.h keeps. */ +struct CbTensor { + RadTensor t; /* `data`: the codes plane, from the tile's first weight row */ + float tab[32]; + int64_t cols = 0, row_bytes = 0; + int bits = 0; +}; +struct LdCb { + static inline float ld(const RadTensor* t, int64_t i) { + const CbTensor* c = reinterpret_cast(t); + const int64_t r = i / c->cols, k = i - r * c->cols; + return c->tab[rad_load_bits((const uint8_t*)c->t.data + r * c->row_bytes, c->bits, k)]; + } +}; + +/* An expert's codes when its entry is the joined form: 1 with `out` filled, 0 for a plain plane + * (any dtype but u4 and u5), RAD_E_DTYPE for a form these kernels do not read and RAD_E_SHAPE for + * codes not covering [n, k]. A u4 or u5 entry is always joined: only its table says what a code + * means. */ +static int cb_codes(const RadTensor& w, int64_t n, int64_t k, CbTensor* out) { + if (w.dtype != RAD_U4 && w.dtype != RAD_U5) return 0; + const RadPlanesHeader* h = rad_planes_header(w.data); + const RadPlanesEntry *ec = nullptr, *et = nullptr; + const void* codes = h ? rad_planes_find(w.data, "codes", &ec) : nullptr; + const void* tab = h ? rad_planes_find(w.data, "table", &et) : nullptr; + if (!codes || !tab || h->n_planes != 2) return RAD_E_DTYPE; + const int bits = ec->dtype == RAD_U4 ? 4 : ec->dtype == RAD_U5 ? 5 : 0; + if (!bits || ec->kind != RAD_PLANE_TILED || ec->block[0] != 1 || ec->block[1] != 1 || + et->kind != RAD_PLANE_TABLE || et->dtype != RAD_F32 || + et->rows * et->cols != ((int64_t)1 << bits)) + return RAD_E_DTYPE; + if (ec->rows < n || ec->cols < k) return RAD_E_SHAPE; + out->t = w; + out->t.data = const_cast(codes); + std::memcpy(out->tab, tab, sizeof(float) << bits); + out->cols = ec->cols; + out->row_bytes = ec->row_bytes; + out->bits = bits; + return 1; +} + +/* An expert's scales beside joined codes: the scale times the level above it. */ +struct CbScale { + Scales s; + float mul = 1.0f; + inline float at(int64_t row, int64_t g) const { return (s.p ? s.grp(row, g) : 1.0f) * mul; } +}; + +/* From the joined `scale,scale.1` form when the entry holds one, else the plane as make_scales + * reads it (w4nla8h's bf16 scale, or none). RAD_E_DTYPE for a joined form of other planes. */ +static int cb_scale(const RadTensor* ws, int64_t n, int64_t k, CbScale* out) { + out->mul = 1.0f; + const RadPlanesHeader* h = ws ? cb_joined(*ws) : nullptr; + if (!h) { + out->s = make_scales(ws, n, k, false); + return RAD_OK; + } + const RadPlanesEntry *es = nullptr, *e1 = nullptr; + const void* sp = rad_planes_find(ws->data, "scale", &es); + const void* lp = rad_planes_find(ws->data, "scale.1", &e1); + if (!sp || !lp || h->n_planes != 2) return RAD_E_DTYPE; + const uint32_t dt = es->dtype; + if (es->kind != RAD_PLANE_TILED || es->block[0] < 1 || es->block[1] < 1 || + (dt != RAD_F8E4M3 && dt != RAD_BF16 && dt != RAD_F16 && dt != RAD_F32) || + e1->kind != RAD_PLANE_TILED || e1->dtype != RAD_F32 || e1->block[0] != 0 || + e1->block[1] != 0 || e1->rows != 1 || e1->cols != 1) + return RAD_E_DTYPE; + if ((n + es->block[0] - 1) / es->block[0] > es->rows || + (k + es->block[1] - 1) / es->block[1] > es->cols) + return RAD_E_SHAPE; + Scales s{}; + s.p = sp; + s.dt = dt; + s.rs = es->cols; + s.cs = 1; + s.group = es->block[1]; + s.rblk = es->block[0]; + s.e8m0 = false; + out->s = s; + std::memcpy(&out->mul, lp, sizeof out->mul); + return 1; +} + +static TileFn pick_cb_tile(uint32_t da) { + switch (da) { + case RAD_F8E4M3: return &quant_tile, LdCb>; + case RAD_BF16: return &quant_tile, LdCb>; + case RAD_F32: return &quant_tile, LdCb>; + default: return &quant_tile; + } +} + static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) { const int n_opd = quant ? (ncls == 4 ? 13 : 9) : 5; if (!have(a, n_opd)) return RAD_E_INVAL; @@ -183,9 +385,8 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) { const RadTensor* sorted = &a->t[quant ? 4 : 2]; const RadTensor* off = &a->t[quant ? 5 : 3]; const RadTensor* Y = &a->t[quant ? (ncls == 4 ? 12 : 8) : 4]; - /* THE QUANTISED ARM'S EXPERTS ARE TWO TABLES BY PARITY -- see ref_registry.cpp -- or, for - * `moe_gemm_q_mod4`, four by the expert's number mod 4; the plain arm's are one, which is the - * same walk with every expert in the first class. */ + /* The quantised arm's experts are two tables by parity (see ref_registry.cpp), or four by + * expert number mod 4 for `moe_gemm_q_mod4`; the plain arm has one, every expert in class 0. */ const RadTensor* W1 = quant ? &a->t[6] : W; const RadTensor* ws1_ = quant ? t_in(a, 7) : nullptr; const bool two = quant; @@ -195,10 +396,9 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) { const RadTensor* wsq[4] = { ws_, ws1_, quant && nc == 4 ? t_in(a, 9) : nullptr, quant && nc == 4 ? t_in(a, 11) : nullptr }; - /* "sorted" means `a` already has one row per (token, slot) in the scatter's order, which is - * what the DOWN projection of a routed block reads -- its input is the first projection's - * output. "token" (the default, and the gate_up projection's case) means one row per token, - * gathered through sorted_tok. See ref_registry.cpp for why this is said and not derived. */ + /* "sorted": `a` has one row per (token, slot) in scatter order (the down projection, reading + * the first projection's output). "token" (default, gate_up): one row per token, gathered + * through sorted_tok. See ref_registry.cpp for why this is stated, not derived. */ const char* ord = p_str(a, "a_order", "token"); const bool sorted_a = ord && std::strcmp(ord, "sorted") == 0; if (ord && !sorted_a && std::strcmp(ord, "token") != 0) return RAD_E_UNSUPPORTED; @@ -218,8 +418,8 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) { const int64_t n_expert = p_int(a, "n_expert", W->rank >= 3 ? W->shape[0] : 0); const int64_t top_k = p_int(a, "top_k", 1); if (parts <= 0 || n_expert <= 0 || top_k <= 0) return RAD_E_SHAPE; - /* The output is the widest class's width, the activation the longest class's K. Class q - * holds ceil((n - q) / nc) experts. */ + /* The output is the widest class's N and the activation the longest class's K. Class q holds + * ceil((n - q) / nc) experts. */ int64_t N = 0, K = 0; for (int q = 0; q < nc; ++q) { if (Nq[q] <= 0 || Kq[q] <= 0 || Nq[q] % parts) return RAD_E_SHAPE; @@ -231,16 +431,14 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) { const int64_t T = numel(Y) / N; if (T <= 0 || numel(sorted) < T || numel(off) < n_expert + 1) return RAD_E_SHAPE; - /* `y` HAS ONE ROW PER (token, slot) AND `a` HAS WHATEVER `a_order` SAYS. The token count is - * recovered from T and top_k; the activation's row count is T under "sorted" and M under - * "token", and it is checked against THAT rather than against either extent on its own -- a - * sorted-order operand with only M rows is a caller that handed the down projection the - * gate_up projection's buffer. */ + /* `y` has one row per (token, slot); `a` has T rows under "sorted" and M = T / top_k under + * "token", checked against the matching count (M rows under "sorted" means the down projection + * was handed gate_up's input buffer). */ const int64_t M = T / top_k; const int64_t AR = sorted_a ? T : M; if (M <= 0 || numel(A) < AR * K) return RAD_E_SHAPE; - const Mat ma = as_mat(A, AR, K); + const Mat ma = as_mat(A, K); const Scales SA = make_scales(as_, AR, K, false); const int64_t gp = p_int(a, "group", 0); if (quant && gp > 0 && SA.p && SA.group != gp) return RAD_E_SHAPE; @@ -248,14 +446,16 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) { const int64_t y_rs = row_stride(Y, N); const int64_t y_cs = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1; - /* Per-expert readings, built once outside the row loop: a table lookup and a Scales are cheap, - * and doing them per row would be T of them against n_expert. A null `data` means the operand - * could not be read as a table at all, which is refused before the loop because an OpenMP body - * cannot return. Expert e is entry e / nc of class e % nc. */ + /* Per-expert views, built once outside the row loop (and validated there, since an OpenMP body + * cannot return). Expert e is entry e / nc of class e % nc. */ std::vector we((size_t)n_expert), wse((size_t)n_expert); std::vector mw((size_t)n_expert); std::vector SW((size_t)n_expert); std::vector en((size_t)n_expert), ek((size_t)n_expert); + /* Codebook experts (joined codes): every expert of the call, or none. */ + std::vector cbt; + std::vector cbs; + bool codebook = false; for (int64_t e = 0; e < n_expert; ++e) { const int q = (int)(e % nc); const RadTensor* tw = Wq[q]; @@ -268,48 +468,161 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) { if (!we[(size_t)e].data) return RAD_E_STRIDE; if (we[(size_t)e].rank < 2 || we[(size_t)e].shape[0] < n || we[(size_t)e].shape[1] < k) return RAD_E_SHAPE; - mw[(size_t)e] = as_mat(&we[(size_t)e], n, k); if (quant && ts) { wse[(size_t)e] = expert_entry(ts, ix); if (!wse[(size_t)e].data) return RAD_E_STRIDE; - SW[(size_t)e] = make_scales(&wse[(size_t)e], n, k, false); - } else { - SW[(size_t)e] = make_scales(nullptr, n, k, false); } + if (quant) { + CbTensor ct; + const int jc = cb_codes(we[(size_t)e], n, k, &ct); + if (jc < 0) return jc; + if (e == 0 && jc > 0) { + codebook = true; + cbt.resize((size_t)n_expert); + cbs.resize((size_t)n_expert); + } + if (codebook != (jc > 0)) return RAD_E_DTYPE; + if (codebook) { + cbt[(size_t)e] = ct; + const int js = cb_scale(ts ? &wse[(size_t)e] : nullptr, n, k, &cbs[(size_t)e]); + if (js < 0) return js; + continue; + } + /* A joined scale is read only beside joined codes. */ + if (ts && cb_joined(wse[(size_t)e])) return RAD_E_DTYPE; + } + mw[(size_t)e] = as_mat(&we[(size_t)e], k); + SW[(size_t)e] = make_scales(quant && ts ? &wse[(size_t)e] : nullptr, n, k, false); } const int64_t fy = N / parts; - #pragma omp parallel for schedule(static) + + /* Each row's expert (the binary search over the offsets) and activation row, or -1 for a row + * that is all zeros: a dropped slot, or a token past `a`. Zeros are written, never stale + * arena bytes, and so are each part's columns past a narrower class's width. */ + std::vector ex((size_t)T, -1), tk((size_t)T, 0); + REF_PAR_FOR(T * N) for (int64_t i = 0; i < T; ++i) { const int64_t flat = ld_int(sorted->dtype, sorted->data, offlin(sorted, i)); - if (flat < 0) { /* a dropped slot: a zero row, never stale arena bytes */ - for (int64_t n = 0; n < N; ++n) stt(Y, i * y_rs + n * y_cs, 0.0f); - continue; + int64_t e = -1; + if (flat >= 0) { + int64_t lo = 0, hi = n_expert; + while (lo + 1 < hi) { + const int64_t mid = (lo + hi) / 2; + if (ld_int(off->dtype, off->data, offlin(off, mid)) <= i) lo = mid; else hi = mid; + } + const int64_t tok = sorted_a ? i : flat / top_k; + if (tok < AR) { e = lo; tk[(size_t)i] = tok; } } - /* Which expert owns row i: a binary search over the offsets, so a 256-expert model does - * not pay a linear scan per row. */ - int64_t lo = 0, hi = n_expert; - while (lo + 1 < hi) { - const int64_t mid = (lo + hi) / 2; - if (ld_int(off->dtype, off->data, offlin(off, mid)) <= i) lo = mid; else hi = mid; - } - const int64_t e = lo; - const int64_t tok = sorted_a ? i : flat / top_k; - if (tok >= AR) { for (int64_t n = 0; n < N; ++n) stt(Y, i * y_rs + n * y_cs, 0.0f); continue; } + ex[(size_t)i] = e; + const int64_t fc = e >= 0 ? en[(size_t)e] / parts : 0; + for (int64_t n = 0; n < N; ++n) + if (n - (n / fy) * fy >= fc) stt(Y, i * y_rs + n * y_cs, 0.0f); + } - const Mat& B = mw[(size_t)e]; - const Scales& SB = SW[(size_t)e]; + /* The live rows grouped by expert, ascending within one, and the tiles over them: one per + * (expert, part, column block, row group). Output column pp * fy + j is weight row + * pp * fc + j of the expert's [N_e, K_e] plane. */ + std::vector start((size_t)n_expert + 1, 0), order((size_t)T), arow((size_t)T); + for (int64_t i = 0; i < T; ++i) + if (ex[(size_t)i] >= 0) ++start[(size_t)ex[(size_t)i] + 1]; + for (int64_t e = 0; e < n_expert; ++e) start[(size_t)e + 1] += start[(size_t)e]; + { + std::vector cur(start.begin(), start.end() - 1); + for (int64_t i = 0; i < T; ++i) { + const int64_t e = ex[(size_t)i]; + if (e < 0) continue; + const int64_t at = cur[(size_t)e]++; + order[(size_t)at] = i; + arow[(size_t)at] = tk[(size_t)i]; + } + } + struct Item { int64_t e, pp, j0, r0, R; }; + std::vector items; + int64_t rg_max = 1; + for (int64_t e = 0; e < n_expert; ++e) { + const int64_t cnt = start[(size_t)e + 1] - start[(size_t)e]; + if (cnt <= 0) continue; const int64_t fc = en[(size_t)e] / parts; - /* One product, and it is `quant_dot`'s: the same grouping and the same order the dense - * quantised GEMM folds its two scales in. A second copy of that arithmetic here would be a - * second place for it to be right by accident -- the expert GEMM and gemm_nt_q are the - * same function over different weights, and a reference that spelled them differently - * would put an ulp between them that no tolerance is meant to absorb. Output column n is - * weight row (n / fy) * fc + n % fy, and zero past a narrower class's part. */ - for (int64_t n = 0; n < N; ++n) { - const int64_t pp = n / fy, j = n - pp * fy; - stt(Y, i * y_rs + n * y_cs, - j < fc ? quant_dot(ma, B, SA, SB, tok, pp * fc + j, ek[(size_t)e]) : 0.0f); + const TileGrid tg = tile_grid(cnt, fc * parts); + if (tg.rg > rg_max) rg_max = tg.rg; + for (int64_t pp = 0; pp < parts; ++pp) + for (int64_t j0 = 0; j0 < fc; j0 += REF_NB) + for (int64_t r0 = 0; r0 < cnt; r0 += tg.rg) + items.push_back({ e, pp, j0, r0, (r0 + tg.rg < cnt) ? tg.rg : cnt - r0 }); + } + std::vector tile((size_t)n_expert); + for (int64_t e = 0; e < n_expert; ++e) + tile[(size_t)e] = codebook ? pick_cb_tile(A->dtype) + : pick_tile(A->dtype, we[(size_t)e].dtype); + + REF_PAR_REGION(T * N * K) + { + /* A codebook tile's scales are its REF_NB weight rows' groups, at most K of them. */ + const size_t wsf = tile_ws_floats(rg_max); + float* const ws = ws_get(wsf + (codebook ? (size_t)(REF_NB * K) : 0)); + REF_FOR_DYN + for (int64_t it = 0; it < (int64_t)items.size(); ++it) { + const Item& w = items[(size_t)it]; + const int64_t e = w.e, fc = en[(size_t)e] / parts, ke = ek[(size_t)e]; + const int64_t nb = (w.j0 + REF_NB < fc) ? REF_NB : fc - w.j0; + const int64_t base = start[(size_t)e] + w.r0; + if (codebook) { + /* The tile's weight rows as their own [nb, ke] operand: codes from its first row, + * and its scales, each times its level, as an f32 [nb, ngrp] stream. */ + const int64_t wr0 = w.pp * fc + w.j0; + CbTensor lt = cbt[(size_t)e]; + lt.t.data = (uint8_t*)lt.t.data + wr0 * lt.row_bytes; + const Mat B{ <.t, lt.cols, 1 }; + const CbScale& cs = cbs[(size_t)e]; + const int64_t g = cs.s.p && cs.s.group > 0 ? cs.s.group : ke; + const int64_t ngrp = (ke + g - 1) / g; + float* const sb = ws + wsf; + for (int64_t j = 0; j < nb; ++j) + for (int64_t gi = 0; gi < ngrp; ++gi) sb[j * ngrp + gi] = cs.at(wr0 + j, gi); + Scales SB{}; + SB.p = cs.s.p || cs.mul != 1.0f ? sb : nullptr; + SB.dt = RAD_F32; + SB.rs = ngrp; + SB.cs = 1; + SB.group = g; + SB.rblk = 1; + if (SA.p && SA.group < g) { + for (int64_t r = 0; r < w.R; ++r) + for (int64_t j = 0; j < nb; ++j) + stt(Y, order[(size_t)(base + r)] * y_rs + (w.pp * fy + w.j0 + j) * y_cs, + quant_dot(ma, B, SA, SB, arow[(size_t)(base + r)], j, + ke)); + continue; + } + const float* acc = tile[(size_t)e](ma, B, SA, SB, arow.data() + base, w.R, 0, nb, + ke, ws); + for (int64_t r = 0; r < w.R; ++r) { + const int64_t i = order[(size_t)(base + r)]; + for (int64_t j = 0; j < nb; ++j) + stt(Y, i * y_rs + (w.pp * fy + w.j0 + j) * y_cs, acc[r * REF_NB + j]); + } + continue; + } + const Mat& B = mw[(size_t)e]; + const Scales& SB = SW[(size_t)e]; + const int64_t g = SB.group > 0 ? SB.group : ke; + if (SA.p && SA.group < g) { + /* An activation grid finer than the weight's: quant_dot per element. */ + for (int64_t r = 0; r < w.R; ++r) + for (int64_t j = 0; j < nb; ++j) + stt(Y, order[(size_t)(base + r)] * y_rs + (w.pp * fy + w.j0 + j) * y_cs, + quant_dot(ma, B, SA, SB, arow[(size_t)(base + r)], + w.pp * fc + w.j0 + j, ke)); + continue; + } + const float* acc = tile[(size_t)e](ma, B, SA, SB, arow.data() + base, w.R, + w.pp * fc + w.j0, nb, ke, ws); + for (int64_t r = 0; r < w.R; ++r) { + const int64_t i = order[(size_t)(base + r)]; + for (int64_t j = 0; j < nb; ++j) + stt(Y, i * y_rs + (w.pp * fy + w.j0 + j) * y_cs, acc[r * REF_NB + j]); + } } } return RAD_OK; @@ -322,16 +635,14 @@ int ref_moe_gemm_q_mod4(const RadArgs* a, RadStream) { return moe_gemm_impl(a, t /* ------------------------------------------------------------------ moe_gather */ /* y[t] = sum over the token's slots of expert_w[t, j] * y_expert[position of (t, j)]. * - * THE SUMMATION ORDER IS ASCENDING SLOT j, which is what makes this reproducible: an - * implementation that walked the expert-sorted rows instead would sum a token's contributions in - * expert-id order, and the two differ in the last bits. + * Summation is in ascending slot j; walking the expert-sorted rows would sum in expert-id order and + * differ in the last bits. * - * The inverse permutation is rebuilt in blocks rather than allocated: one pass over sorted_tok per - * block of tokens, into a fixed stack array. That costs (M / block) passes, which at the sizes an - * MoE layer runs is nothing, and it keeps the op free of both scratch and allocation. */ + * The inverse permutation is rebuilt per block of tokens into a fixed stack array, one pass over + * sorted_tok per block, so the op needs no scratch or allocation. */ int ref_moe_gather(const RadArgs* a, RadStream) { - /* Operands are POSITIONAL, so an absent shared pair is two NULL SLOTS rather than a shorter - * array: `have` demands all six and would refuse every unfolded call. */ + /* Operands are positional: an absent shared pair is two null slots, which `have` would + * refuse. */ if (a->n_t < 6) return RAD_E_INVAL; const RadTensor *ye = &a->t[0], *ew = &a->t[1], *sorted = &a->t[2], *Y = &a->t[5]; if (!ye->data || !ew->data || !sorted->data || !Y->data) return RAD_E_INVAL; @@ -357,7 +668,7 @@ int ref_moe_gather(const RadArgs* a, RadStream) { const int64_t y_rs = Y->rank >= 2 ? Y->stride[Y->rank - 2] : n; const int64_t y_cs = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(T * n) for (int64_t b = 0; b < nblk; ++b) { int32_t inv[INV_MAX]; const int64_t t0 = b * tb, t1 = (t0 + tb < M) ? t0 + tb : M; @@ -383,9 +694,8 @@ int ref_moe_gather(const RadArgs* a, RadStream) { ldt(ye, (int64_t)i * ye_rs + c * ye_cs); } const int64_t yo = t * y_rs + c * y_cs; - /* THE NARROWS ARE THE UNFUSED PAIR'S, and the store is what performs them: the - * gather wrote a bf16 buffer and scale_rows narrowed its own product before the - * add, so both operands of the sum are rounded and the sum is rounded again. */ + /* The stores round as the unfused pair does: the gather's result and scale_rows' + * product are each rounded, then their sum. */ stt(Y, yo, acc); if (!sh) continue; const float g = ldt(Y, yo); @@ -397,16 +707,28 @@ int ref_moe_gather(const RadArgs* a, RadStream) { return RAD_OK; } +/* One step of a selection sort over `n` candidates: the unused one with the largest value, ties to + * the lower id, skipping pads (id < 0). Returns its index, or -1 when none is left. */ +template +static int64_t next_best(int64_t n, const Id& id, const Val& val, + const std::vector& used) { + int64_t best = -1; + for (int64_t c = 0; c < n; ++c) { + if (used[(size_t)c] || id(c) < 0) continue; + if (best < 0 || val(c) > val(best) || (val(c) == val(best) && id(c) < id(best))) best = c; + } + return best; +} + /* ------------------------------------------------------------------ row_topk */ -/* Exact per-row top-R, descending, ties to the lower column. The same selection the router uses, - * exposed as its own op because a drafter's candidate set and a speculative tree both want it - * without a softmax in front. */ +/* Exact per-row top-R, descending, ties to the lower column: the router's selection without the + * softmax, for drafter candidate sets and speculative trees. */ int ref_row_topk(const RadArgs* a, RadStream) { if (!have(a, 3)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *idx = &a->t[1], *val = &a->t[2]; - /* The vocab-parallel form. `off` shifts every column reported, so a rank's slice reports - * global ids; `pairs` is the [M, R, 2] plane an all_gather moves, an int32 id in the first - * float slot beside its value. Both absent is the ordinary single-rank top-R. */ + /* Vocab-parallel form: `vocab_off` shifts reported columns to global ids; `pairs` is the + * [M, R, 2] plane an all_gather moves (int32 id bits in the first float slot, then the value). + * Both absent is the single-rank top-R. */ const RadTensor* pairs = t_in(a, 3); const int64_t off = p_int(a, "vocab_off", 0); const int64_t N = p_int(a, "N", x->rank >= 2 ? x->shape[x->rank - 1] : 0); @@ -416,7 +738,7 @@ int ref_row_topk(const RadArgs* a, RadStream) { if (M <= 0 || numel(idx) < M * R || numel(val) < M * R) return RAD_E_SHAPE; if (pairs && (pairs->dtype != RAD_F32 || numel(pairs) < M * R * 2)) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(M * N * R) for (int64_t m = 0; m < M; ++m) { const int64_t xb = rowoff(x, m, N), xs = laststride(x); float pv = INFINITY; @@ -438,68 +760,57 @@ int ref_row_topk(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------------ row_topk_merge */ -/* The other half of the vocab-parallel top-R: the R largest of world_size all-gathered per-rank - * candidate sets, in the same descending (idx, val) form the single-rank path produces, so - * everything downstream is handed the answer it would have had from an unsharded plane. +/* The other half of the vocab-parallel top-R: the R largest of world_size gathered per-rank + * candidate sets, in the single-rank path's descending (idx, val) form. * - * TIES BREAK ON THE LOWER ID, which is what makes that equality true rather than approximate: a - * dense top-R over the whole vocabulary breaks ties on the lower column, so a merge that broke - * them on rank order would disagree with it exactly when two shards hold the same logit. + * Ties break on the lower id, matching a dense top-R over the whole vocabulary; rank order would + * disagree when two shards hold the same logit. * - * A slot the producing rank could not fill carries id -1 and is DROPPED -- a sentinel rather than - * a -INFINITY value, because -inf is a value a masked logit legitimately takes. */ + * An unfilled slot carries id -1 and is dropped; -inf cannot be the sentinel, since masked logits + * legitimately take it. */ int ref_row_topk_merge(const RadArgs* a, RadStream) { if (!have(a, 3)) return RAD_E_INVAL; const RadTensor *g = &a->t[0], *idx = &a->t[1], *val = &a->t[2]; const int64_t R = p_int(a, "R", 1); const int64_t W = p_int(a, "world_size", 1); if (R <= 0 || W <= 0) return RAD_E_SHAPE; - /* The rows are the OPERAND'S, not the parameter's: `M` is declared as a band ceiling and the - * gathered plane is narrowed to the rows this step actually has. */ + /* Rows come from the operand; `M` is a band ceiling (see band_rows). */ const int64_t M = numel(g) / (W * R * 2); if (M <= 0) return RAD_E_SHAPE; if (g->dtype != RAD_F32 || numel(g) < M * W * R * 2) return RAD_E_SHAPE; if (numel(idx) < M * R || numel(val) < M * R) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(M * W * R * R) for (int64_t m = 0; m < M; ++m) { const float* const row = (const float*)g->data + m * W * R * 2; - /* A selection sort over W*R entries: 32 of them at world 2 and R 16, so the quadratic - * form is cheaper than anything with an allocation in it, and it is the reference. */ + auto id = [&](int64_t c) { + int32_t v; + std::memcpy(&v, row + c * 2, sizeof v); + return v; + }; + auto value = [&](int64_t c) { return row[c * 2 + 1]; }; + /* Selection sort over W*R entries (32 at world 2, R 16). */ std::vector used((size_t)(W * R), 0); for (int64_t r = 0; r < R; ++r) { - int64_t best = -1; - float bv = 0.0f; - int32_t bid = 0; - for (int64_t c = 0; c < W * R; ++c) { - if (used[(size_t)c]) continue; - int32_t id; - std::memcpy(&id, row + c * 2, sizeof id); - if (id < 0) continue; /* a pad, not a candidate */ - const float v = row[c * 2 + 1]; - if (best < 0 || v > bv || (v == bv && id < bid)) { best = c; bv = v; bid = id; } - } + const int64_t best = next_best(W * R, id, value, used); if (best >= 0) used[(size_t)best] = 1; st_int(idx->dtype, idx->data, rowoff(idx, m, R) + r * laststride(idx), - best >= 0 ? (int64_t)bid : -1); - stt(val, rowoff(val, m, R) + r * laststride(val), best >= 0 ? bv : -INFINITY); + best >= 0 ? (int64_t)id(best) : -1); + stt(val, rowoff(val, m, R) + r * laststride(val), best >= 0 ? value(best) : -INFINITY); } } return RAD_OK; } /* ------------------------------------------------------------------ pair_argmax */ -/* row_topk_merge at R = 1, for a caller that wants the winner's id as a PROPOSAL rather than as - * a candidate list: one element a row, at the output's own pitch, so a block drafter's per-position - * picks land contiguous in the token buffer it verifies. `pairs` is the same gathered plane -- - * `n` (int32 id, f32 value) pairs a row, a negative id a pad -- and the rule is the same: the - * largest value, ties to the LOWER id, so the pick equals an argmax over the unsharded row. +/* The top-1 of a gathered pair plane as a proposal: one id per row at the output's pitch, so a block + * drafter's per-position picks land contiguous in the token buffer it verifies. `pairs` holds `n` + * (int32 id, f32 value) pairs per row, a negative id being a pad; largest value wins, ties to the + * lower id, matching an argmax over the unsharded row. * - * Its own op rather than row_topk_merge with R = 1 because the shapes differ where it matters: - * row_topk_merge's `gathered` is world_size * R pairs a row, and a rank that sends R = 1 sends 8 - * bytes, which a row-interleaved all_gather moving whole 16-byte words cannot carry. So a rank - * sends R >= 2 and this takes the top-1 of all of them, whatever `n` that makes. A row with no - * valid pair writes -1 and -inf, as the merge does for a slot it cannot fill. `val` is optional. */ + * Not row_topk_merge with R = 1: a rank sending R = 1 sends 8 bytes, which a row-interleaved + * all_gather of 16-byte words cannot carry, so ranks send R >= 2 and this takes the top-1 of all + * `n`. A row with no valid pair writes -1 and -inf. `val` is optional. */ int ref_pair_argmax(const RadArgs* a, RadStream) { if (!have(a, 2)) return RAD_E_INVAL; const RadTensor *p = &a->t[0], *idx = &a->t[1]; @@ -507,12 +818,12 @@ int ref_pair_argmax(const RadArgs* a, RadStream) { const int64_t n = p_int(a, "n", 0); if (n <= 0) return RAD_E_SHAPE; if (p->dtype != RAD_F32) return RAD_E_DTYPE; /* the id is carried by bit pattern */ - /* The rows are the operand's, as on row_topk_merge: `M` is a band ceiling. */ + /* Rows come from the operand; `M` is a band ceiling. */ const int64_t M = numel(p) / (n * 2); if (M <= 0 || numel(idx) < M || (val && numel(val) < M)) return RAD_E_SHAPE; const float* const pf = (const float*)p->data; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(M * n) for (int64_t m = 0; m < M; ++m) { int32_t bid = -1; float bv = -INFINITY; @@ -530,27 +841,18 @@ int ref_pair_argmax(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------------ logit_rerank */ -/* EXACTLY RESCORE R CANDIDATES A ROW AGAINST THE FULL-PRECISION HEAD. +/* Rescore R candidates per row exactly against the full-precision head. * - * A speculative step can afford a COARSE draft head -- the target verifies every proposal, so a - * worse draft costs acceptance and never a token -- but it cannot afford to be wrong about which - * candidate the coarse head liked best. A heavily quantised head disagrees with the exact one - * about the top-1 on a noticeable fraction of rows, and rescoring its top few candidates against - * the exact weight recovers nearly all of that disagreement. + * A speculative draft head may be coarse (the target verifies every proposal, so a worse draft + * costs only acceptance), but a heavily quantised head often disagrees with the exact one on the + * top-1. Rescoring its top few candidates against the exact weight recovers most of that, reading + * R rows of the head instead of all of it. * - * So this is the second half of a coarse top-R: the coarse head proposes R, the exact weight - * scores those R and only those R, and the answer is re-sorted on the exact values. R rows of the - * head against the whole of it is the entire point -- a few hundred KB against a few hundred MB. + * `vocab_off` is the shard's first column; ids are global, as row_topk reports and row_topk_merge + * consumes them. A candidate outside this rank's rows becomes a pad. * - * `vocab_off` IS THE SHARD'S FIRST COLUMN, and the ids are GLOBAL, because that is the form - * `row_topk` reports and `row_topk_merge` consumes. A candidate outside this rank's rows is not - * this rank's to score and becomes a pad: under vocab-parallel drafting `row_topk` picked from - * this rank's plane, so every id it reports is local and the guard is for a caller that mixes - * them. - * - * ORDER, AND WHY IT IS THE SAME ORDER row_topk USES: descending by value, ties to the LOWER id. - * The merge downstream breaks ties that way and the two have to agree, or a tie between shards - * resolves differently from a tie inside one. A pad sorts last and keeps id -1. */ + * Output order matches row_topk: descending value, ties to the lower id, so the downstream merge + * resolves ties consistently. Pads sort last with id -1. */ int ref_logit_rerank(const RadArgs* a, RadStream) { if (!have(a, 5)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *w = &a->t[1], *in = &a->t[2]; @@ -561,35 +863,44 @@ int ref_logit_rerank(const RadArgs* a, RadStream) { const int64_t NV = p_int(a, "n_vocab", 0); const int64_t voff = p_int(a, "vocab_off", 0); if (R <= 0 || K <= 0 || NV <= 0) return RAD_E_SHAPE; - /* The rows are the OPERAND'S: `M` is a band ceiling and a step narrows it. */ + /* Rows come from the operand; `M` is a band ceiling. */ const int64_t M = numel(x) / K; if (M <= 0 || numel(in) < M * R) return RAD_E_SHAPE; if (numel(idx) < M * R || numel(val) < M * R) return RAD_E_SHAPE; - if (numel(w) < NV * K) return RAD_E_SHAPE; + /* A head of codes and scale (ref_planes.h) is read element by element as the core's decoder + * gives it, so its scores are those of the decoded f32 head. */ + ScaledRows sr; + const bool joined = is_joined(w); + if (joined) RAD_REF_TRY(scaled_rows(w, NV, K, &sr)); + else if (numel(w) < NV * K) return RAD_E_SHAPE; + /* The pair plane is f32 words, ids carried by bit pattern, as row_topk writes it. */ + if (pairs && (pairs->dtype != RAD_F32 || numel(pairs) < M * R * 2)) return RAD_E_SHAPE; + const int64_t ws = laststride(w); - #pragma omp parallel for schedule(static) + REF_PAR_FOR(M * R * K) for (int64_t m = 0; m < M; ++m) { std::vector id((size_t)R); std::vector sc((size_t)R); for (int64_t r = 0; r < R; ++r) { const int64_t g = ld_int(in->dtype, in->data, rowoff(in, m, R) + r * laststride(in)); const int64_t local = g - voff; - if (g < 0 || local < 0 || local >= NV) { id[(size_t)r] = -1; sc[(size_t)r] = -INFINITY; continue; } - double acc = 0.0; /* the reference sums wide and in order */ + if (g < 0 || local < 0 || local >= NV) { + id[(size_t)r] = -1; + sc[(size_t)r] = -INFINITY; + continue; + } + double acc = 0.0; /* summed in double, in k order */ + const int64_t wb = joined ? 0 : rowoff(w, local, K); for (int64_t k = 0; k < K; ++k) - acc += (double)ldt(x, rowoff(x, m, K) + k * laststride(x)) - * (double)ldt(w, local * K + k); + acc += (double)ldt(x, rowoff(x, m, K) + k * laststride(x)) * + (double)(joined ? sr.at(local, k) : ldt(w, wb + k * ws)); id[(size_t)r] = (int32_t)g; sc[(size_t)r] = (float)acc; } std::vector used((size_t)R, 0); for (int64_t o = 0; o < R; ++o) { - int64_t best = -1; - for (int64_t c = 0; c < R; ++c) { - if (used[(size_t)c] || id[(size_t)c] < 0) continue; - if (best < 0 || sc[(size_t)c] > sc[(size_t)best] || - (sc[(size_t)c] == sc[(size_t)best] && id[(size_t)c] < id[(size_t)best])) best = c; - } + const int64_t best = next_best(R, [&](int64_t c) { return id[(size_t)c]; }, + [&](int64_t c) { return sc[(size_t)c]; }, used); const int32_t oid = best >= 0 ? id[(size_t)best] : -1; const float ov = best >= 0 ? sc[(size_t)best] : -INFINITY; if (best >= 0) used[(size_t)best] = 1; diff --git a/libref/ref_ngram.cpp b/libref/ref_ngram.cpp index c073bbe5..cdbbac1d 100644 --- a/libref/ref_ngram.cpp +++ b/libref/ref_ngram.cpp @@ -1,73 +1,56 @@ /* ref_ngram.cpp -- the n-gram row ids of Qwen4-Exp's Per-Layer Embedding (PLE). * - * ============================== WHAT IT IS ============================== + * ============================== What it is ============================== * - * PLE gives ONE layer of the model a second embedding table, addressed not by the token but by a - * HASH of the last `ngram` tokens. Qwen3.8-Flash-Next's is 320,001,536 rows of 160 bf16 -- 102 GB, - * 51 of the model's 125 billion parameters, four fifths of the checkpoint -- read sixteen rows a - * token. This op computes those sixteen row ids. The gather itself is `gather_rows` over - * [M * heads] indices; there is no second op for it and there should not be. + * PLE gives one layer a second embedding table addressed by a hash of the last `ngram` tokens + * rather than the token. Qwen3.8-Flash-Next's has 320,001,536 rows of 160 bf16 (102 GB, 51 of the + * model's 125 billion parameters), read sixteen rows per token. This op computes those row ids; the + * gather itself is `gather_rows` over [M * heads] indices. * * mixed[2gram] = t0*m0 ^ t1*m1 heads 0..7 * mixed[3gram] = t0*m0 ^ t1*m1 ^ t2*m2 heads 8..15 * ids[h] = mixed[ngram(h)] % vocab[h] + offset[h] * - * `m`, `vocab` and `offset` are all IN THE CHECKPOINT (`layer_multipliers`, - * `ngram_heads_vocab_sizes`, `ngram_heads_offsets`). The reference builds them from a splitmix64 - * seed and a prime search at construction time; a served model reads them, and re-deriving them - * here would be a second source for sixteen numbers the container already carries. + * `m`, `vocab` and `offset` come from the checkpoint (`layer_multipliers`, + * `ngram_heads_vocab_sizes`, `ngram_heads_offsets`). Upstream derives them from a splitmix64 seed + * and a prime search; re-deriving them here would be a second source for numbers the container + * already carries. * - * ============================== TWO THINGS THAT LOOK LIKE TRAPS AND ARE NOT ================== + * ============================== Two non-traps ============================== * - * THE HASH IS NON-NEGATIVE BY CONSTRUCTION, so `%` is unambiguous. The reference uses - * `torch.remainder`, which FLOORS -- `remainder(-5, 3) == 1` where C gives -2 -- and the obvious - * worry is that an int64 multiply wraps into the sign bit and the two disagree. It cannot: - * `_build_layer_multipliers` bounds every multiplier by `(2^63-1) // vocab_size`, so each product - * of a real token id has its sign bit clear, and an XOR of values with a clear sign bit has a - * clear sign bit. `mixed` is always in [0, 2^63). The bound is not decoration -- it is what makes - * the hash well defined -- so this op REFUSES a multiplier or a token that would break it rather - * than producing a different answer from the reference in silence. + * The hash is non-negative, so `%` is unambiguous even though upstream's `torch.remainder` floors + * (remainder(-5, 3) == 1, C gives -2). `_build_layer_multipliers` bounds each multiplier by + * `(2^63-1) // vocab_size`, so a real token's product and any XOR of such products have the sign + * bit clear: `mixed` is in [0, 2^63). * - * THE EOS RULE COLLAPSES TO TWO COMPARISONS. The reference shifts the token history right with - * `_shift_right_ignore_eos`, built out of a cummax over `where(ids == eos, positions, -1)`, a - * segment start, and `valid = (position_in_segment >= shift) & (p - shift >= 0)`. Expanded, - * `position_in_segment >= s` is exactly "no eos in [p-s, p-1]" -- and wherever the rule would - * substitute eos because `tok[p-s]` is ITSELF an eos, the substituted value is the value already - * there. So the whole construction is: + * The EOS rule collapses to two comparisons. Upstream's `_shift_right_ignore_eos` (a cummax over + * `where(ids == eos, positions, -1)`, a segment start, and + * `valid = (position_in_segment >= shift) & (p - shift >= 0)`) reduces to "no eos in [p-s, p-1]"; + * where it would substitute eos because `tok[p-s]` is itself eos, the value is unchanged. So: * * t0 = tok[p] * t1 = p >= 1 ? tok[p-1] : eos * t2 = (p >= 2 && t1 != eos) ? tok[p-2] : eos * - * and generally `t[s] = tok[p-s]` unless some earlier shift already fell back to eos, at which - * point every deeper shift is eos too. A serving engine needs no cummax and no segment - * bookkeeping: it needs the `ngram-1` COMMITTED ids in front of the step, and nothing deeper. + * and in general `t[s] = tok[p-s]` until a shift falls back to eos, after which all deeper shifts + * are eos. A serving engine needs only the `ngram-1` committed ids before the step. * - * ============================== WHERE THOSE IDS COME FROM ==================================== + * ============================== Where those ids come from ============================== * - * They arrive in an INOUT STATE -- a rolling window of `ngram - 1 + n_spec` ids per slot, read at - * `num_accepted - 1`. That is `ple_conv`'s contract, operand for operand, including what the - * window holds afterwards (ref_ple.cpp): with `num_accepted` present the step is a decode step - * whose drafts a verify may reject, and the window is rewritten the way gdn_conv_update rewrites - * its own -- the old ids shifted down by one, then every id of the step -- so a next step that - * kept k of them reads at k - 1 and finds the `ngram - 1` ids ending at the k-th. Absent, every - * id commits and the last `ngram - 1` of them land at offset zero. + * An INOUT state: a rolling window of `ngram - 1 + n_spec` ids per slot, read at + * `num_accepted - 1`, with exactly `ple_conv`'s contract (ref_ple.cpp). With `num_accepted` + * present (a decode step whose drafts may be rejected) the window is rewritten as gdn_conv_update + * does: old ids shifted down by one, then every id of the step, so a next step that kept k reads + * at k - 1. Absent, every id commits and the last `ngram - 1` land at offset zero. * - * THEY ARE A STATE AND NOT A PLAIN INPUT, even though nothing can invalidate them -- the - * predecessors of the step's first row are always committed, so no rejection reaches them. A plain - * input costs MORE than a state here, on two counts. It has to be filled by something, and nothing - * in the engine derives "the ids before this step": `DeriveInput` carries positions and cu_seqlens - * and no token ids at all, so a plain input means a new core derivation and a widened DeriveFn - * signature to serve one op. And the contract is already paid for by the layer -- the dilated - * convolution downstream carries a 9-timestep window with exactly this contract, so PLE passes - * `num_accepted`, `cache_idx` and `has_init` whether or not this op reads them. + * It is a state rather than a plain input although no rejection can reach the step's predecessors: + * nothing in the engine derives "the ids before this step" (`DeriveInput` carries positions and + * cu_seqlens, no token ids), and the layer's dilated convolution already passes `num_accepted`, + * `cache_idx` and `has_init` under the same contract. RAD_KV_CONV ("per-sequence, a rolling window + * of width-1 + num_spec entries") fits, and `conv_state_index` derives the read cursor. * - * RAD_KV_CONV is already "per-sequence, a rolling window of width-1 + num_spec entries", which is - * this, and `conv_state_index` already derives the read cursor for it. - * - * THE COLD VALUE IS EOS AND NOT ZERO, which is the one place this differs from a conv window. - * Zero is a real token id, so a slot the manager has not written yet must be filled from `eos` - * explicitly -- `has_init` 0 means exactly that. + * The cold value is eos, not zero (zero is a real token id): `has_init` 0 fills the window with + * `eos`. */ #include "ref_common.h" #include "ref_ops.h" @@ -76,18 +59,10 @@ using namespace ref; namespace { -/* THE TWO OPERATIONS TORCH WOULD DO, SPELLED SO THEY CANNOT BE UNDEFINED. - * - * A signed overflow is UB in C++ and wrapping in torch, so the multiply goes through uint64 and - * comes back -- two's complement, which is what an int64 tensor does on every machine this runs - * on. And `torch.remainder` FLOORS where C truncates, so the modulo is written out rather than - * left to `%`. - * - * On a real checkpoint NEITHER of these can fire: `_build_layer_multipliers` bounds every - * multiplier by `(2^63-1) // vocab_size`, so a real token's product has its sign bit clear, an XOR - * of such values has its sign bit clear, and truncating and flooring agree on a non-negative - * dividend. They are here so that a DRAWN case -- a harness index that no vocabulary bounds -- - * gets torch's answer rather than a refusal or a platform's. */ +/* Torch's int64 multiply and remainder without undefined behaviour: signed overflow is UB in C++ + * but wraps in torch, so the multiply goes through uint64; `torch.remainder` floors where C + * truncates. On a real checkpoint neither case arises (see the file header); these give torch's + * answer for drawn test inputs that no vocabulary bounds. */ inline int64_t wrap_mul(int64_t a, int64_t b) { return (int64_t)((uint64_t)a * (uint64_t)b); } @@ -109,20 +84,19 @@ inline int64_t floor_mod(int64_t a, int64_t b) { /* b > 0 */ * vocab_sizes [heads] i64 w * offsets [heads] i64 w * cache_idx [n_seq] i32 ? the state slot per sequence - * has_init [n_seq] i32 ? 0 = the window is EOS, not what the slot last held - * num_accepted [n_seq] i32 ? one-based; shifts the READ offset, and its presence + * has_init [n_seq] i32 ? 0 = the window is eos, not what the slot last held + * num_accepted [n_seq] i32 ? one-based; shifts the read offset, and its presence * makes the write-back the decode layout. Absent reads * at offset zero and leaves the prefill layout. * ids [M][heads] i32 out * ahead_ids [A][heads] i32 ? out: `tok` then holds A more tokens after the step's, - * continuing the LAST sequence, and these are their ids + * continuing the last sequence, and these are their ids * as the step that runs them will compute them. The * window is the step's own. */ int ref_ngram_ids(const RadArgs* a, RadStream) { - /* TEN POSITIONS AND AN ELEVENTH, four of them optional, so the count is checked and the - * optionals are tested one by one -- `have()` would refuse the op for an operand allowed to be - * absent. */ + /* Eleven positions, four optional, so the optionals are tested one by one; `have()` would + * refuse an absent optional operand. */ if (a->n_t < 10) return RAD_E_INVAL; const RadTensor* tok = t_in(a, 0); const RadTensor* st = t_in(a, 1); @@ -139,15 +113,15 @@ int ref_ngram_ids(const RadArgs* a, RadStream) { const int64_t heads = p_int(a, "heads", 0); if (heads <= 0) return RAD_E_SHAPE; - /* The token vector is the call and the prompt that follows it; `M` is the band. See band_rows - * in ref_common.h. */ + /* The token vector holds the call's tokens plus the `ahead` tokens; `M` is the band (see + * band_rows in ref_common.h). */ const int64_t A = ahead ? numel(ahead) / heads : 0; const int64_t M = band_rows(numel(tok) - A, p_int(a, "M", 0)); const int64_t ngram = p_int(a, "ngram", 0); const int64_t eos = p_int(a, "eos", -1); - if (M <= 0 || heads <= 0 || ngram < 2 || eos < 0) return RAD_E_SHAPE; - /* heads are laid out as `ngram - 1` blocks of `heads_per_ngram`, block b using the (b+2)-gram, - * so the head count has to divide that way or the block a head belongs to is a guess. */ + if (M <= 0 || ngram < 2 || eos < 0) return RAD_E_SHAPE; + /* Heads are `ngram - 1` blocks of `heads_per_ngram`, block b using the (b+2)-gram, so the + * head count must divide evenly. */ if (heads % (ngram - 1)) return RAD_E_SHAPE; const int64_t per = heads / (ngram - 1); const int64_t ctx = ngram - 1; @@ -155,47 +129,45 @@ int ref_ngram_ids(const RadArgs* a, RadStream) { if (numel(mult) < ngram || numel(vsz) < heads || numel(off_) < heads) return RAD_E_SHAPE; if (numel(ids) < M * heads) return RAD_E_SHAPE; + for (int64_t h = 0; h < heads; ++h) + if (ld_int(vsz->dtype, vsz->data, h) <= 0 || ld_int(off_->dtype, off_->data, h) < 0) + return RAD_E_SHAPE; const int64_t n_seq = numel(cu) - 1; if (n_seq <= 0) return RAD_E_SHAPE; const int64_t W = st->rank >= 2 ? st->shape[st->rank - 1] : ctx; if (W < ctx) return RAD_E_SHAPE; - /* Every sequence is checked before any state is written: the read window, and the window a - * decode step leaves behind, which is `ctx - 1` ids of history plus every id of the step. */ + /* Check every sequence before writing any state: its rows, the read window, and the window a + * decode step leaves (`ctx - 1` ids of history plus every id of the step). */ for (int64_t s = 0; s < n_seq; ++s) { const int64_t o = nacc ? ld_int(nacc->dtype, nacc->data, offlin(nacc, s)) - 1 : 0; if (o < 0) return RAD_E_INVAL; if (o + ctx > W) return RAD_E_SHAPE; - const int64_t T = ld_int(cu->dtype, cu->data, offlin(cu, s + 1)) - - ld_int(cu->dtype, cu->data, offlin(cu, s)); - if (nacc && T > 0 && ctx - 1 + T > W) return RAD_E_SHAPE; + const int64_t bos = cu_at(cu, s), eot = cu_at(cu, s + 1); + if (bos < 0 || eot < bos || eot > M) return RAD_E_SHAPE; + if (nacc && eot > bos && ctx - 1 + (eot - bos) > W) return RAD_E_SHAPE; } const int64_t ids_ld = rowoff(ids, 1, heads); const int64_t ahd_ld = ahead ? rowoff(ahead, 1, heads) : 0; for (int64_t s = 0; s < n_seq; ++s) { - const int64_t bos = ld_int(cu->dtype, cu->data, offlin(cu, s)); - const int64_t eot = ld_int(cu->dtype, cu->data, offlin(cu, s + 1)); - if (bos < 0 || eot < bos || eot > M) return RAD_E_SHAPE; - const int64_t T = eot - bos; + const int64_t bos = cu_at(cu, s); + const int64_t T = cu_at(cu, s + 1) - bos; if (T <= 0) continue; const int64_t slot = sidx ? ld_int(sidx->dtype, sidx->data, offlin(sidx, s)) : s; if (slot < 0) continue; const bool warm = !hini || ld_int(hini->dtype, hini->data, offlin(hini, s)) != 0; const int64_t o = nacc ? ld_int(nacc->dtype, nacc->data, offlin(nacc, s)) - 1 : 0; - /* The `ctx` committed ids in front of this step. A COLD slot's window is EOS and not what - * the slot last held -- and not zero either, which is a real token. Without that a fresh - * sequence landing on a recycled slot hashes the previous sequence's tail into its first - * two rows, which is a wrong lookup in a 320-million-row table and nothing says so. */ + /* The `ctx` committed ids before this step. A cold slot's window is eos, not a recycled + * slot's previous contents (and not zero, a real token). */ int64_t prev[8]; for (int64_t i = 0; i < ctx; ++i) prev[i] = warm ? ld_int(st->dtype, st->data, rowoff(st, slot, W) + o + i) : eos; - /* The history this sequence reads: its `ctx` predecessors, then its own rows. Indexed by - * `p` in [0, ctx + T), so row `t` is history position `ctx + t` and every shift is in - * range without a bounds test in the inner loop. */ + /* The sequence's history: `ctx` predecessors, then its own rows. Row `t` is history + * position `ctx + t`, so every shift is in range without a bounds test. */ auto hist = [&](int64_t p) -> int64_t { return p < ctx ? prev[p] : ld_int(tok->dtype, tok->data, offlin(tok, bos + p - ctx)); }; @@ -205,9 +177,8 @@ int ref_ngram_ids(const RadArgs* a, RadStream) { for (int64_t t = 0; t < reach; ++t) { const int64_t p = ctx + t; - /* The shifted tokens, with the EOS rule in its collapsed form: once a shift falls back - * to eos every deeper one does too, because `position_in_segment >= s` is monotone in - * s and an eos at `p - s` makes the substituted value the value already there. */ + /* The shifted tokens under the collapsed eos rule (file header): once a shift falls + * back to eos, every deeper one does too. */ int64_t sh[8]; sh[0] = hist(p); bool cut = false; @@ -217,8 +188,7 @@ int ref_ngram_ids(const RadArgs* a, RadStream) { } /* One mix per n-gram order, extended in place: the (b+2)-gram's mix is the - * (b+1)-gram's XOR'd with one more term, which is exactly the reference's inner loop - * and saves recomputing the shared prefix. */ + * (b+1)-gram's XOR one more term, as in upstream's inner loop. */ int64_t mixed = 0; int64_t blk = -1; for (int64_t k = 0; k < ngram; ++k) { @@ -230,7 +200,6 @@ int ref_ngram_ids(const RadArgs* a, RadStream) { const int64_t h = blk * per + j; const int64_t v = ld_int(vsz->dtype, vsz->data, h); const int64_t ofh = ld_int(off_->dtype, off_->data, h); - if (v <= 0 || ofh < 0) return RAD_E_SHAPE; if (t < T) st_int(ids->dtype, ids->data, (bos + t) * ids_ld + h, floor_mod(mixed, v) + ofh); @@ -241,12 +210,9 @@ int ref_ngram_ids(const RadArgs* a, RadStream) { } } - /* The window this step leaves behind, written after every read of it is done. Same rule - * as ple_conv's, said again because the two states sit in the same layer and a reader - * will compare them: a decode step (`num_accepted` present) shifts the old ids down by - * one and appends every id it ran, so the next step's `num_accepted - 1` lands on the - * ids ending at the last one it kept; a step that commits everything leaves its last - * `ctx` ids at offset zero. */ + /* Write the window back after all reads, by ple_conv's rule: a decode step (`num_accepted` + * present) shifts the old ids down by one and appends every id it ran; a step that + * commits everything leaves its last `ctx` ids at offset zero. */ const int64_t base = rowoff(st, slot, W); if (nacc) { for (int64_t i = 0; i + 1 < ctx; ++i) diff --git a/libref/ref_ops.h b/libref/ref_ops.h index cb613ce2..1ad0248a 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -1,58 +1,51 @@ /* ref_ops.h -- the entry points ref_registry.cpp puts in the kernel table, and the layout * conventions they share. * - * ============================== SHAPES ARE READ OFF THE OPERANDS ============================== + * ============================== Shapes are read off the operands ============================== * - * Every extent this plugin loops over comes from a RadTensor's shape, never from the op's - * parameters. That is a deliberate rule and not laziness: + * Every extent this plugin loops over comes from a RadTensor's shape, never from the parameters: * - * * A RANGED parameter is collapsed to a BAND when the instance is resolved (spec §2.2), and - * `rad_issue` carries the actual value as an integer rather than by rewriting the param list. - * A loop bounded by `M` would therefore run to the band's upper bound -- 8192 rows of a - * single-row decode -- and read off the end of the arena. Ref takes M from the tensor. - * * Everything else the parameters name is either derivable from a shape (head_dim, N, K, n) - * or is genuinely not a shape at all (causal, window, block_size, eps, group, top_k). Ref - * uses the parameter for the second kind and cross-checks it against the shape for the - * first, refusing with RAD_E_SHAPE where a disagreement would mean an out-of-bounds read. + * * A ranged parameter is collapsed to a band when the instance is resolved (spec §2.2), and + * `rad_issue` carries the actual value separately. A loop bounded by `M` would run to the + * band's upper bound (8192 rows for a one-row decode) and read past the arena. Ref takes M + * from the tensor. + * * Other parameters are either derivable from a shape (head_dim, N, K, n) or not shapes at all + * (causal, window, block_size, eps, group, top_k). Ref uses the latter directly and + * cross-checks the former against the shape, refusing with RAD_E_SHAPE where a disagreement + * would read out of bounds. * - * ============================== THE PAGED KV LAYOUT ============================== + * ============================== The paged KV layout ============================== * - * This is libr4d's and every kernel in the project has to match it, so it is written here once: + * libr4d's layout, which every kernel must match: * * kv_cache[num_blocks, kv_heads, block_size, 2 * head_dim] * - * K first and V second inside a slot: element d of the key is at [..., d] and element d of the - * value at [..., head_dim + d]. A flat slot index s decomposes as block = s / block_size and - * offset = s % block_size, which is what `slot_mapping` carries and what `block_table` indexes - * into. Nothing else in the file is allowed to invent a different one. + * K then V within a slot: key element d at [..., d], value element d at [..., head_dim + d]. A + * flat slot index s is block = s / block_size, offset = s % block_size; `slot_mapping` carries such + * indices and `block_table` maps to blocks. * - * ============================== THE SPECULATIVE ROLLBACK CONTRACT ============================== + * ============================== The speculative rollback contract ============================== * - * The linear-attention pair (gdn_conv_update, gdn_recurrent_update) must support rejection - * without recompute (spec §10), and the contract is part of the schema rather than an assumption: + * The linear-attention pair (gdn_conv_update, gdn_recurrent_update) supports rejection without + * recompute (spec §10); the contract is part of the schema: * * conv state [n_slots, conv_dim, state_len], state_len >= conv_width - 2 + q_len. - * A step READS its window at offset num_accepted[s] - 1 -- the slot the last - * accepted token left -- and REWRITES the buffer shifted down by one: slots - * 0 .. conv_width-3 take the tail of the old history, and this step's token t - * lands at slot t + conv_width - 2. The invariant that makes it work is that the - * last accepted token of a step always sits at the slot its own index implies, so - * the next step's read offset is the only thing that changes. + * A step reads its window at offset num_accepted[s] - 1 (the slot the last + * accepted token left) and rewrites the buffer shifted down by one: slots + * 0 .. conv_width-3 take the tail of the old history, and this step's token t lands + * at slot t + conv_width - 2. Invariant: a step's last accepted token always sits at + * the slot its index implies, so only the next step's read offset changes. * linear state [n_slots, n_head_v, head_v, head_k], addressed through state_idx[s, 0..q_len). - * The initial state is read from state_idx[s, num_accepted[s] - 1] and EVERY - * candidate token t writes its own state to state_idx[s, t], because which of them - * survives verification is not known until after this layer has run. + * The initial state is read from state_idx[s, num_accepted[s] - 1], and every + * candidate token t writes its own state to state_idx[s, t], since which survives + * verification is unknown until after this layer. * - * num_accepted counts the accepted tokens of the PREVIOUS step and is 1-based: 1 means "none of - * the drafts survived, only the token that was already committed". It is a REQUIRED operand on - * both ops -- an op that lets the caller omit it is an op whose rollback contract is optional -- - * and a non-speculative decode passes all ones. Ref still reads a null as 1 rather than faulting, - * because a tool calling the launch directly has no declare in front of it to enforce the schema. + * num_accepted counts the previous step's accepted tokens, 1-based: 1 means no draft survived, only + * the committed token. It is a required operand on both ops; a non-speculative decode passes all + * ones. Ref still reads a null as 1, for direct callers with no declare to enforce the schema. * - * BOTH OPS ALSO TAKE `cu`, and it is required. The two decode kernels run off the one cumulative- - * lengths tensor on the one step; the number of sequences is cu's length minus one and nothing - * else in either argument list carries it. The fast kernels read `cu[n]` before any null test, so - * a schema that omitted it would not make it optional -- it would make the launch fault. + * Both ops also require `cu`: the number of sequences is cu's length minus one and nothing else + * carries it. The fast kernels read `cu[n]` before any null test, so omitting it would fault. */ #ifndef RAD_REF_OPS_H #define RAD_REF_OPS_H @@ -83,8 +76,10 @@ int ref_pool_rows (const RadArgs*, RadStream); int ref_relu (const RadArgs*, RadStream); int ref_clamp (const RadArgs*, RadStream); int ref_conv2d (const RadArgs*, RadStream); +int ref_conv2d_unfold (const RadArgs*, RadStream); int ref_conv1d_dw (const RadArgs*, RadStream); int ref_rel_sinusoid (const RadArgs*, RadStream); +int ref_seg_sinusoid (const RadArgs*, RadStream); int ref_attn_local_rel (const RadArgs*, RadStream); int ref_gelu (const RadArgs*, RadStream); int ref_silu (const RadArgs*, RadStream); @@ -103,6 +98,7 @@ int ref_softmax (const RadArgs*, RadStream); /* ---- quantisation and rotation */ int ref_quant_act_i8 (const RadArgs*, RadStream); +int ref_quant_act_i8g (const RadArgs*, RadStream); int ref_had_quant_act_i8 (const RadArgs*, RadStream); int ref_quant_act_fp8 (const RadArgs*, RadStream); int ref_had_quant_act_fp8 (const RadArgs*, RadStream); @@ -153,6 +149,12 @@ int ref_gelu_tanh(const RadArgs*, RadStream); int ref_scatter_add_rows(const RadArgs*, RadStream); int ref_attn_prefix_self(const RadArgs*, RadStream); int ref_qsa_block_key (const RadArgs*, RadStream); +/* the QSA indexer and DFlash2's convolution (ref_qsa.cpp) */ +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); +int ref_dflash_conv (const RadArgs*, RadStream); /* ---- mixture of experts */ int ref_router_topk (const RadArgs*, RadStream); @@ -160,6 +162,14 @@ int ref_moe_scatter (const RadArgs*, RadStream); int ref_moe_gemm (const RadArgs*, RadStream); int ref_moe_gemm_q (const RadArgs*, RadStream); int ref_moe_gemm_q_mod4 (const RadArgs*, RadStream); +/* The layout hooks of moe_gemm_q and moe_gemm_q_mod4: a codebook expert's views of several planes + * in the joined form of abi/rad_planes.h, checked against `dtype` (ref_moe.cpp). */ +int ref_moe_cb_layout (const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, RadLayout*); +int ref_moe_cb_relayout (const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, void*, int64_t); +int ref_moe_cb_unrelayout (const RadParam*, int, int, const RadEncoding*, const int*, + const void*, int64_t, const RadTensor*, int); int ref_scale_rows (const RadArgs*, RadStream); int ref_moe_gather (const RadArgs*, RadStream); int ref_row_topk (const RadArgs*, RadStream); @@ -198,24 +208,17 @@ int ref_sample_pick (const RadArgs*, RadStream); int ref_sample_argmax (const RadArgs*, RadStream); int ref_sample_logprobs (const RadArgs*, RadStream); -/* ============================== OPERAND DESCRIPTION ============================== +/* ============================== Operand description ============================== * - * `RadKernelInfo::opd_shape` (rad_abi.h): how big is operand i of this op at this geometry, and - * what may legally be in it. libref/ref_shapes.cpp implements one for every entry point above, - * and the NAMING IS PART OF THE MECHANISM rather than a convention: the hook does not receive the - * op name, so a single shared function would have to recover it from a parameter and no op in this - * vocabulary carries its own name as one. Instead ref_registry.cpp's ROW() macro pastes the shape - * hook out of the launch it was already given -- `fn ## _shape` -- so every row gets its - * description without a row being edited, and an op added later that forgets to describe itself - * does not link. + * `RadKernelInfo::opd_shape` (rad_abi.h): the size of operand i at this geometry and what it may + * legally hold. libref/ref_shapes.cpp implements one per entry point above. The naming is + * load-bearing: the hook does not receive the op name, so ref_registry.cpp's ROW() macro pastes + * `fn ## _shape` from the launch function, and an op added without a description fails to link. * - * The signature is spelled once here because it is the same for every entry point above, and the - * parameter names are what document it: `p`/`n_p` is the resolved parameter list exactly as - * `launch` would receive it, `operand` is the positional index into the op's schema, and the - * answer lands in `out`. RAD_OK, or RAD_E_UNSUPPORTED when the geometry - * does not carry what the description needs -- which a caller SKIPS AND COUNTS rather than - * guessing, because a tool that invents an extent tests the kernel's bounds handling and calls the - * result correctness. */ + * `p`/`n_p` is the resolved parameter list as `launch` receives it, `operand` the positional index + * into the op's schema, and the result goes to `out`. Returns RAD_OK, or RAD_E_UNSUPPORTED when the + * geometry lacks what the description needs; callers skip and count those rather than guess, since + * an invented extent tests bounds handling, not correctness. */ #define REF_SHAPE_FN(fn) \ int fn##_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) @@ -240,8 +243,10 @@ REF_SHAPE_FN(ref_pool_rows); REF_SHAPE_FN(ref_relu); REF_SHAPE_FN(ref_clamp); REF_SHAPE_FN(ref_conv2d); +REF_SHAPE_FN(ref_conv2d_unfold); REF_SHAPE_FN(ref_conv1d_dw); REF_SHAPE_FN(ref_rel_sinusoid); +REF_SHAPE_FN(ref_seg_sinusoid); REF_SHAPE_FN(ref_attn_local_rel); REF_SHAPE_FN(ref_gelu); REF_SHAPE_FN(ref_silu); @@ -259,6 +264,7 @@ REF_SHAPE_FN(ref_cast); REF_SHAPE_FN(ref_softmax); REF_SHAPE_FN(ref_quant_act_i8); +REF_SHAPE_FN(ref_quant_act_i8g); REF_SHAPE_FN(ref_had_quant_act_i8); REF_SHAPE_FN(ref_quant_act_fp8); REF_SHAPE_FN(ref_had_quant_act_fp8); @@ -306,6 +312,11 @@ REF_SHAPE_FN(ref_gelu_tanh); REF_SHAPE_FN(ref_scatter_add_rows); REF_SHAPE_FN(ref_attn_prefix_self); REF_SHAPE_FN(ref_qsa_block_key); +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_dflash_conv); REF_SHAPE_FN(ref_router_topk); REF_SHAPE_FN(ref_moe_scatter); diff --git a/libref/ref_planes.h b/libref/ref_planes.h new file mode 100644 index 00000000..4a1f6e13 --- /dev/null +++ b/libref/ref_planes.h @@ -0,0 +1,235 @@ +/* ref_planes.h -- libref's reading of a weight operand joined over several planes + * (abi/rad_planes.h), and the layout hooks that ask for that form. + * + * A weight declared over several planes of one stored tensor reaches a kernel as one operand: an + * fp8 or int8 lm head's codes and scale, Flash-Next's E4M3 mixing rows with their f32 group + * scales, a zero-point grid's scale and zero. On the host it is stored joined: a header naming each + * plane, then the planes as the container holds them. A launch recognises the form by its header + * and reads the planes by role, so the bytes are the canonical ones and nothing is decoded at + * load. + * + * The hooks join only a selection of several planes; one plane is stored as it is (rad_planes.h + * declines it), so a row with these hooks still reads the plain forms a tool describes (the + * logical f32 head rad-kbench and the op oracle hand over). They refuse with RAD_E_DTYPE a joined + * selection the op does not compute, which keeps the row from being selected for it. + * + * libavx/avx_planes.h states the same rules for libavx; the two must accept the same encodings, + * since a selector may resolve either library for a band. + */ +#ifndef REF_PLANES_H +#define REF_PLANES_H + +#include "ref_common.h" +#include "rad_planes.h" + +namespace ref { + +/* ================================================================== reading at launch */ + +/* One plane of a joined operand, as its entry describes it. */ +struct JPlane { + const uint8_t* p = nullptr; + uint32_t dt = 0; + int64_t rows = 0, cols = 0, row_bytes = 0; + int64_t br = 0, bc = 0; /* logical rows x columns one element covers; 0 is all */ + + explicit operator bool() const { return p != nullptr; } + float at(int64_t i, int64_t j) const { return rad_load_f32(p + i * row_bytes, dt, j); } + /* The element of a TILED plane covering logical (r, c). */ + float cover(int64_t r, int64_t c) const { + return at(br > 0 ? r / br : 0, bc > 0 ? c / bc : 0); + } +}; + +static inline bool is_joined(const RadTensor* t) { + return t && t->data && rad_planes_header(t->data) != nullptr; +} + +/* The plane of `t`'s joined form with this role; false when there is none. */ +static inline JPlane jplane(const RadTensor* t, const char* role) { + JPlane v; + const RadPlanesEntry* e = nullptr; + const void* d = t && t->data ? rad_planes_find(t->data, role, &e) : nullptr; + if (!d) return v; + v.p = (const uint8_t*)d; + v.dt = e->dtype; + v.rows = e->rows; + v.cols = e->cols; + v.row_bytes = e->row_bytes; + v.br = e->block[0]; + v.bc = e->block[1]; + return v; +} + +static inline int64_t cdiv_or_1(int64_t n, int64_t b) { return b > 0 ? (n + b - 1) / b : 1; } + +static inline bool float_scale_dt(uint32_t dt) { + return dt == RAD_BF16 || dt == RAD_F16 || dt == RAD_F32; +} + +/* Codes with one scale over [rows, cols], read element by element as the core's affine decoder + * gives it: the code times the scale covering it, one f32 rounding. An E4M3 lm head with a bf16 + * scale per 128x128 block, an int8 one per (row, 128 of K), E4M3 rows with an f32 scale per group + * of their own. */ +struct ScaledRows { + JPlane codes, scale; + float at(int64_t r, int64_t c) const { return codes.at(r, c) * scale.cover(r, c); } +}; + +/* RAD_OK and the view, RAD_E_DTYPE for a joined form other than codes and a scale, RAD_E_SHAPE + * for planes that do not cover [rows, cols]. */ +static inline int scaled_rows(const RadTensor* t, int64_t rows, int64_t cols, ScaledRows* v) { + const RadPlanesHeader* h = t && t->data ? rad_planes_header(t->data) : nullptr; + if (!h) return RAD_E_INVAL; + v->codes = jplane(t, "codes"); + v->scale = jplane(t, "scale"); + if (h->n_planes != 2 || !v->codes || !v->scale) return RAD_E_DTYPE; + if ((v->codes.dt != RAD_F8E4M3 && v->codes.dt != RAD_I8) || !float_scale_dt(v->scale.dt) || + v->codes.br != 1 || v->codes.bc != 1) + return RAD_E_DTYPE; + if (v->codes.rows != rows || v->codes.cols != cols || + v->scale.rows != cdiv_or_1(rows, v->scale.br) || + v->scale.cols != cdiv_or_1(cols, v->scale.bc)) + return RAD_E_SHAPE; + return RAD_OK; +} + +/* ================================================================== the zero-point grids + * + * gemm_nt_q's asymmetric grids (docs/OPS.md): unsigned codes read as (code - zero) * scale, an f16 + * scale and an integer zero per (row, `group` of K), joined in `b_scale` from the weight's "scale" + * and "zero" planes; `b` is the codes plane. The activation side is one of three: + * + * ZP_I8_ROW quant_act_i8's codes in the step order, an f32 scale a row and the code sums + * `a_sum` the zero is removed with (w2a8, w4a8_asym) + * ZP_I8_GROUP row-major int8 codes with an f32 scale per (row, 128 of K), as givens_dense_quant + * writes them (w4a8i8_asym, w5a8i8) + * ZP_F16 a 16-bit activation, givens_rotate's (w4a16_asym, w5a16) */ +enum ZpAct { ZP_I8_ROW = 0, ZP_I8_GROUP = 1, ZP_F16 = 2 }; + +struct ZpGrid { + const char* name; + uint32_t codes; + ZpAct act; +}; + +static inline const ZpGrid* zp_grid(const char* dtype) { + static const ZpGrid kGrids[] = { + { "w2a8", RAD_U2, ZP_I8_ROW }, { "w4a8_asym", RAD_U4, ZP_I8_ROW }, + { "w4a16_asym", RAD_U4, ZP_F16 }, { "w5a16", RAD_U5, ZP_F16 }, + { "w4a8i8_asym", RAD_U4, ZP_I8_GROUP }, { "w5a8i8", RAD_U5, ZP_I8_GROUP }, + }; + if (!dtype) return nullptr; + for (const ZpGrid& g : kGrids) + if (std::strcmp(g.name, dtype) == 0) return &g; + return nullptr; +} + +/* An unsigned integer zero point a code is compared against: the same width as the codes or + * wider, never signed. */ +static inline bool zero_dt(uint32_t dt) { + return dt == RAD_U8 || dt == RAD_U2 || dt == RAD_U4 || dt == RAD_U5; +} + +/* ================================================================== the layout hooks */ + +/* The encoding's planes `sel` names, in order: one role per name. */ +static inline bool sel_roles(const RadEncoding* enc, const int* sel, int n, const char* r0, + const char* r1) { + if (!enc || !sel || n != 2) return false; + for (int i = 0; i < 2; ++i) + if (sel[i] < 0 || sel[i] >= enc->n_planes) return false; + return std::strncmp(enc->plane[sel[0]].role, r0, RAD_ENC_STR) == 0 && + std::strncmp(enc->plane[sel[1]].role, r1, RAD_ENC_STR) == 0; +} + +/* Whether `enc` and its selection are codes and one scale, untransformed: what ScaledRows reads. */ +static inline bool enc_scaled_rows(const RadEncoding* enc, const int* sel, int n) { + if (!rad_enc_is(enc, "affine") || enc->transform[0] || enc->n_planes != 2) return false; + if (!sel_roles(enc, sel, n, "codes", "scale")) return false; + const RadEncPlane& c = enc->plane[sel[0]]; + const RadEncPlane& s = enc->plane[sel[1]]; + return c.kind == RAD_PLANE_TILED && c.block[0] == 1 && c.block[1] == 1 && + (c.dtype == RAD_F8E4M3 || c.dtype == RAD_I8) && s.kind == RAD_PLANE_TILED && + float_scale_dt(s.dtype); +} + +/* The joined form for a weight operand that takes codes and one scale (`rows_opd` and `rows_opd2` + * are the operands that may be one, -1 for none). Every other operand, and a single plane, is + * stored as it is. */ +static inline int layout_scaled(int operand, int rows_opd, int rows_opd2, const RadEncoding* enc, + const int* sel, const RadTensor* planes, int n, RadLayout* out) { + if (n < 2 || (operand != rows_opd && operand != rows_opd2)) return RAD_E_UNSUPPORTED; + if (!enc_scaled_rows(enc, sel, n)) return RAD_E_DTYPE; + return rad_planes_layout(enc, sel, planes, n, out); +} + +/* logits_gemm and logit_rerank: the head is operand 1 of both. */ +static inline int ref_layout_head(const RadParam*, int, int operand, const RadEncoding* enc, + const int* sel, const RadTensor* planes, int n, RadLayout* out) { + return layout_scaled(operand, 1, -1, enc, sel, planes, n, out); +} + +/* hc_read: mix_down and mix_up (operands 2 and 3). */ +static inline int ref_layout_hc(const RadParam*, int, int operand, const RadEncoding* enc, + const int* sel, const RadTensor* planes, int n, RadLayout* out) { + return layout_scaled(operand, 2, 3, enc, sel, planes, n, out); +} + +/* mtp_enter: fc_h and fc_e (operands 4 and 5). */ +static inline int ref_layout_mtp(const RadParam*, int, int operand, const RadEncoding* enc, + const int* sel, const RadTensor* planes, int n, RadLayout* out) { + return layout_scaled(operand, 4, 5, enc, sel, planes, n, out); +} + +/* gemm_nt_q: `b_scale` (operand 3) as the scale and zero of the zero-point grid `dtype` names, + * one each per (row, `group` of K), over codes of that grid's width. The codes (operand 2) are one + * plane and stored as they are. A "givens" transform is the activation's (givens_rotate, + * givens_dense_quant), so the planes are read the same way under it. */ +static inline int ref_layout_gemm_q(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* planes, int n, RadLayout* out) { + if (n < 2 || operand != 3) return RAD_E_UNSUPPORTED; + const ZpGrid* zg = zp_grid(rad_param_gets(p, n_p, "dtype", nullptr)); + const long long group = rad_param_geti(p, n_p, "group", 0); + if (!zg || group <= 0 || !rad_enc_is(enc, "affine")) return RAD_E_DTYPE; + if (enc->transform[0] && std::strncmp(enc->transform, "givens", RAD_ENC_STR) != 0) + return RAD_E_DTYPE; + if (!sel_roles(enc, sel, n, "scale", "zero") || enc->n_planes < 3) return RAD_E_DTYPE; + const RadEncPlane& c = enc->plane[0]; + const RadEncPlane& s = enc->plane[sel[0]]; + const RadEncPlane& z = enc->plane[sel[1]]; + if (std::strncmp(c.role, "codes", RAD_ENC_STR) != 0 || c.dtype != zg->codes || + c.block[0] != 1 || c.block[1] != 1) + return RAD_E_DTYPE; + if (s.kind != RAD_PLANE_TILED || s.dtype != RAD_F16 || s.block[0] != 1 || s.block[1] != group || + z.kind != RAD_PLANE_TILED || !zero_dt(z.dtype) || z.block[0] != 1 || z.block[1] != group) + return RAD_E_DTYPE; + return rad_planes_layout(enc, sel, planes, n, out); +} + +/* RadRelayoutFn and RadUnrelayoutFn for any of the layout hooks above: the hook decides whether + * the planes are joined, and the copies are rad_planes.h's. */ +template +static int ref_relayout_planes(const RadParam* p, int n_p, int operand, const RadEncoding* enc, + const int* sel, const RadTensor* planes, int n, void* dst, + int64_t dst_bytes) { + RadLayout lay{}; + const int st = L(p, n_p, operand, enc, sel, planes, n, &lay); + if (st != RAD_OK) return st; + return rad_planes_relayout(enc, sel, planes, n, dst, dst_bytes); +} + +template +static int ref_unrelayout_planes(const RadParam* p, int n_p, int operand, const RadEncoding* enc, + const int* sel, const void* src, int64_t src_bytes, + const RadTensor* planes, int n) { + RadLayout lay{}; + const int st = L(p, n_p, operand, enc, sel, planes, n, &lay); + if (st != RAD_OK) return st; + return rad_planes_unrelayout(enc, sel, src, src_bytes, planes, n); +} + +} /* namespace ref */ + +#endif /* REF_PLANES_H */ diff --git a/libref/ref_ple.cpp b/libref/ref_ple.cpp index f564adaf..01a1ffea 100644 --- a/libref/ref_ple.cpp +++ b/libref/ref_ple.cpp @@ -1,42 +1,37 @@ /* ref_ple.cpp -- the gate of Qwen4-Exp's Per-Layer Embedding: everything between the n-gram * lookup's two projections and the dilated convolution. * - * ============================== WHAT IT IS ============================== + * ============================== What it is ============================== * - * PLE mixes a hashed n-gram embedding into the residual stream, and the mixing coefficient is a - * DOT PRODUCT between the embedding and the stream -- one scalar per hyper-connection stream, per - * token. Written out, with `n` the model width and `hc` the number of streams: + * PLE mixes a hashed n-gram embedding into the residual stream with a mixing coefficient that is a + * dot product between the embedding and the stream: one scalar per hyper-connection stream per + * token. With `n` the model width and `hc` the number of streams: * * K[c] = grouped_rmsnorm(k)[c] * (w_key[c] + wadd) k is key_proj(embedding) - * Q[c] = grouped_rmsnorm(q)[c] * (w_query[c] + wadd) q is the INCOMING hc stream + * Q[c] = grouped_rmsnorm(q)[c] * (w_query[c] + wadd) q is the incoming hc stream * s[c] = sum_d K[c][d] * Q[c][d] / sqrt(n) * s[c] = sign(s[c]) * sqrt(max(|s[c]|, gate_eps)) <- the signed square root - * gv[c] = sigmoid(s[c]) * v v is value_proj(embedding), ONE row + * gv[c] = sigmoid(s[c]) * v v is value_proj(embedding), one row * gvn = grouped_rmsnorm(gv) * (w_conv + wadd) * - * and the caller finishes with `out = gv + silu(dilated_conv(gvn))`. BOTH gv AND gvn leave this op - * because the convolution reads the NORMED copy and the residual add reads the UN-normed one -- - * two different tensors, and recomputing either outside would be a second definition of the norm. + * and the caller finishes with `out = gv + silu(dilated_conv(gvn))`. Both gv and gvn are outputs: + * the convolution reads the normed copy and the residual add the un-normed one. * - * ============================== THE SIGNED SQUARE ROOT ============================== + * ============================== The signed square root ============================== * - * `gate.abs().clamp_min(1e-6).sqrt() * gate.sign()` is not a monotone rescaling of the dot product - * and it is not decoration: it compresses a score whose magnitude spans orders of magnitude into - * something sigmoid can resolve, and it KEEPS THE SIGN, so a stream whose embedding opposes the - * residual gets a gate below a half rather than a gate of zero. + * `gate.abs().clamp_min(1e-6).sqrt() * gate.sign()` compresses a score spanning orders of magnitude + * into a range sigmoid can resolve and keeps the sign, so a stream whose embedding opposes the + * residual gets a gate below a half. * - * THE CLAMP IS ON THE MAGNITUDE AND THE SIGN IS TAKEN FROM THE ORIGINAL, which matters at exactly - * one value: torch's `sign(0)` is 0, so a dot product of exactly zero comes out as zero and not as - * sqrt(gate_eps). Clamping first and then re-signing the clamped value would give 1e-3 there. - * Zero is not a measure-zero curiosity in a quantised model -- an fp8 activation row can produce - * it -- so the order is written out rather than left to the arithmetic. + * The clamp applies to the magnitude and the sign comes from the original value. torch's `sign(0)` + * is 0, so an exactly-zero dot stays zero rather than becoming sqrt(gate_eps) = 1e-3; an fp8 + * activation row can produce exact zero. * - * ============================== ONE OP AND NOT SIX ============================== + * ============================== One op, not six ============================== * * Three grouped norms, a reduction, a scalar nonlinearity and a broadcast multiply would be six - * launches over tensors that are all [M, hc*n] -- 10240 wide at this model's shape. Every launch - * costs a fixed floor and every one of those ops is memory-bound, so the fused form is the only one - * worth writing. `hc_read` is the same argument at the same width. + * memory-bound launches over [M, hc*n] tensors (10240 wide at this model's shape). `hc_read` is + * fused for the same reason. */ #include "ref_common.h" #include "ref_ops.h" @@ -47,18 +42,8 @@ using namespace ref; namespace { -/* A value narrowed to a tensor's own dtype and read back -- the same helper ref_hc.cpp carries and - * for the same reason. The reference model's arithmetic is NOT f32 throughout: torch's grouped norm - * returns `.type_as(x)`, so everything downstream of a norm reads a bf16 value. Rounding once, here, - * is what lets a fused kernel match this to a tolerance that means something. */ -inline float narrow(uint32_t dtype, float v) { - uint32_t buf[2] = {0, 0}; - st_dt(dtype, buf, 0, v); - return ld_dt(dtype, buf, 0); -} - -/* One group's reciprocal RMS: the rsqrt is per `n`-wide stream while the gain below it spans all - * hc*n. That asymmetry is the whole of what `group_size` means on Qwen4ExpTextRMSNorm. */ +/* One group's reciprocal RMS: the rsqrt is per `n`-wide stream while the gain spans all hc*n + * (what `group_size` means on Qwen4ExpTextRMSNorm). */ inline float group_rsqrt(const RadTensor* x, int64_t base, int64_t stride, int64_t n, float eps) { double acc = 0; for (int64_t d = 0; d < n; ++d) { @@ -72,13 +57,13 @@ inline float group_rsqrt(const RadTensor* x, int64_t base, int64_t stride, int64 /* PLE's gate. * - * k [M][hc*n] key_proj(embedding), UN-normed - * q [M][hc*n] the incoming hyper-connection stream, UN-normed - * v [M][n] value_proj(embedding) -- ONE row, gated differently per stream + * k [M][hc*n] key_proj(embedding), un-normed + * q [M][hc*n] the incoming hyper-connection stream, un-normed + * v [M][n] value_proj(embedding): one row, gated differently per stream * w_key [hc*n] w * w_query [hc*n] w * w_conv [hc*n] w - * gv [M][hc*n] out, UN-normed: what the residual add reads + * gv [M][hc*n] out, un-normed: what the residual add reads * gvn [M][hc*n] out, normed: what the convolution reads */ int ref_ple_gate(const RadArgs* a, RadStream) { @@ -95,13 +80,11 @@ int ref_ple_gate(const RadArgs* a, RadStream) { const int64_t n = p_int(a, "n", 0); const int64_t hc = p_int(a, "hc", 0); - /* `v` is [M, n] and it is the call; `M` is the band. See band_rows in ref_common.h. */ + /* Rows come from `v` [M, n]; `M` is the band (see band_rows in ref_common.h). */ const int64_t M = n > 0 ? band_rows(numel(v) / n, p_int(a, "M", 0)) : 0; const float eps = p_f32(a, "eps", 1e-6f); const float wadd = p_f32(a, "wadd", 0.0f); - /* The floor the gate's magnitude is clamped to before the square root. Named rather than - * written into the expression: it is a model constant, and a constant a reader cannot see is - * one a kernel can disagree with in silence. */ + /* The floor the gate's magnitude is clamped to before the square root; a model constant. */ const float geps = p_f32(a, "gate_eps", 1e-6f); if (M <= 0 || n <= 0 || hc <= 0) return RAD_E_SHAPE; const int64_t hn = hc * n; @@ -113,49 +96,46 @@ int ref_ple_gate(const RadArgs* a, RadStream) { const int64_t wks = laststride(wk), wqs = laststride(wq), wcs = laststride(wc); const int64_t gls = laststride(gv), gnls = laststride(gvn); - #pragma omp parallel for schedule(static) + REF_PAR_FOR(M * hn * 4) for (int64_t m = 0; m < M; ++m) { const int64_t kb = rowoff(k, m, hn), qb = rowoff(q, m, hn), vb = rowoff(v, m, n); const int64_t gb = rowoff(gv, m, hn), nb = rowoff(gvn, m, hn); for (int64_t c = 0; c < hc; ++c) { - /* The two normed streams, and the dot between them. Neither is materialised: every - * element is used exactly once here, and at 2560 wide per stream a buffer would be the - * only allocation in the op. */ + /* The two normed streams and their dot, not materialised since each element is used + * once. Each norm is rounded to its input's dtype: upstream's grouped norm returns + * `.type_as(x)`. */ const float rk = group_rsqrt(k, kb + c * n * kls, kls, n, eps); const float rq = group_rsqrt(q, qb + c * n * qls, qls, n, eps); double dot = 0; for (int64_t d = 0; d < n; ++d) { const int64_t j = c * n + d; - const float kk = narrow(k->dtype, ldt(k, kb + j * kls) * rk * - (ldt(wk, j * wks) + wadd)); - const float qq = narrow(q->dtype, ldt(q, qb + j * qls) * rq * - (ldt(wq, j * wqs) + wadd)); + const float kk = round_dt(k->dtype, ldt(k, kb + j * kls) * rk * + (ldt(wk, j * wks) + wadd)); + const float qq = round_dt(q->dtype, ldt(q, qb + j * qls) * rq * + (ldt(wq, j * wqs) + wadd)); dot += (double)kk * (double)qq; } float s = (float)(dot / std::sqrt((double)n)); - /* THE SIGNED SQUARE ROOT, in the reference's own order: the magnitude is clamped, the - * root is taken, and the SIGN COMES FROM THE ORIGINAL. torch's sign(0) is 0, so a dot - * of exactly zero stays zero instead of becoming sqrt(gate_eps). */ + /* Signed square root in upstream's order: clamp the magnitude, take the root, sign + * from the original (sign(0) = 0). */ const float mag = std::sqrt(std::fabs(s) < geps ? geps : std::fabs(s)); s = s > 0.0f ? mag : (s < 0.0f ? -mag : 0.0f); const float g = act_sigmoid(s); for (int64_t d = 0; d < n; ++d) - stt(gv, gb + (c * n + d) * gls, narrow(gv->dtype, g * ldt(v, vb + d * vls))); + stt(gv, gb + (c * n + d) * gls, round_dt(gv->dtype, g * ldt(v, vb + d * vls))); } - /* And the third norm, over what was just written -- READ BACK, not carried in registers, - * because `gv` has been narrowed to its own dtype and the convolution's input is a norm of - * THOSE bytes. A fused kernel that normed the f32 it still held would disagree in the last - * bits -- the same epilogue-fold rule the GDN out-projection follows. */ + /* The third norm reads `gv` back after it was narrowed, since the convolution's input is a + * norm of the stored bytes (the GDN out-projection's epilogue-fold rule). */ for (int64_t c = 0; c < hc; ++c) { const float r = group_rsqrt(gv, gb + c * n * gls, gls, n, eps); for (int64_t d = 0; d < n; ++d) { const int64_t j = c * n + d; stt(gvn, nb + j * gnls, - narrow(gvn->dtype, ldt(gv, gb + j * gls) * r * (ldt(wc, j * wcs) + wadd))); + round_dt(gvn->dtype, ldt(gv, gb + j * gls) * r * (ldt(wc, j * wcs) + wadd))); } } } @@ -163,65 +143,55 @@ int ref_ple_gate(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------------ ple_conv */ -/* PLE's depthwise convolution: width 4 at DILATION 3, silu AFTER it, and the residual add folded - * in. That is the last piece of the layer -- `out = gv + silu(conv(gvn))`. +/* PLE's depthwise convolution: width 4 at dilation 3, silu after it, and the residual add folded + * in; the layer's last piece, `out = gv + silu(conv(gvn))`. * - * ============================== THE DILATION IS THE WHOLE DIFFERENCE ============================== + * ============================== Dilation ============================== * * A dilated causal convolution reads `width` taps spaced `dilation` apart: * * y[t] = silu( sum_j w[c][j] * x[t - (width-1-j)*dilation] ) * - * so at Qwen4-Exp's width 4 and dilation 3 the taps are 9, 6, 3 and 0 timesteps back, and the - * history a sequence has to carry is (width-1)*dilation = NINE, not three. Every off-by-one in a - * convolution cache is a model that generates fluently from a slightly wrong context, so the - * indexing is written once here and mirrors gdn_conv_prep's exactly: state slot `i` holds the - * value at relative position `i - state_len`, and a read at `src < 0` becomes `cs[slot][c][src + - * state_len]`. + * so at Qwen4-Exp's width 4 and dilation 3 the taps are 9, 6, 3 and 0 timesteps back and the + * carried history is (width-1)*dilation = 9, not 3. The indexing mirrors gdn_conv_prep's: state + * slot `i` holds relative position `i - state_len`, and a read at `src < 0` becomes + * `cs[slot][c][src + state_len]`. * - * The reference reaches the same place by a different route -- it pads by `state_len`, slices the - * last `state_len + seq_len`, and convolves with no padding -- and that pad-and-slice is a no-op - * on a warm cache. What it exists for is the COLD one, where the window in front of the first - * token must be zeros. + * Upstream pads by `state_len`, slices the last `state_len + seq_len` and convolves unpadded; on a + * warm cache that is a no-op, and on a cold one the window before the first token is zeros. * - * ============================== ONE OP WHERE THE GDN HAS TWO ============================== + * ============================== One op where the GDN has two ============================== * - * gdn_conv_prep and gdn_conv_update are separate because the work AROUND their convolutions - * differs -- one splits a fused projection and takes an l2 norm, the other does not. PLE's - * convolution is the same arithmetic at prefill and at decode, so it is one op, and it takes the - * union of the two contracts: `has_init` says whether the slot holds a history (prefill's - * question) and `num_accepted` shifts the read offset within a deeper window (decode's). + * gdn_conv_prep and gdn_conv_update differ in the work around the convolution. PLE's convolution is + * the same at prefill and decode, so one op takes both contracts: `has_init` says whether the slot + * holds history, and `num_accepted` shifts the read offset within a deeper window. * - * `num_accepted` ABSENT MEANS EVERY TOKEN COMMITS, which is what a prefill chunk is: the read is at - * offset zero and nothing this step ran can be rejected. gdn_conv_update makes it required and - * argues that an optional rollback contract is not a contract; the difference here is that this op - * serves prefill too, where there is no previous step to have rejected anything. The state must - * still be sized (width-1)*dilation + n_spec by the manager, and a window too shallow for the - * offset asked for is refused by shape rather than clamped. + * `num_accepted` absent means every token commits (a prefill chunk): the read is at offset zero. + * Unlike gdn_conv_update it is optional because this op also serves prefill. The state must still + * be sized (width-1)*dilation + n_spec, and a window too shallow for the requested offset is + * refused, not clamped. * - * ============================== WHAT THE WINDOW HOLDS AFTER A STEP ============================== + * ============================== The window after a step ============================== * - * The next step reads at ITS `num_accepted - 1`, and what that offset must find is the `hist` - * values ending at the last token this step COMMITTED. Which token that is depends on the kind of - * step, so the presence of `num_accepted` picks the layout: + * The next step reads at its `num_accepted - 1` and must find the `hist` values ending at the last + * token this step committed. The presence of `num_accepted` picks the layout: * - * PRESENT -- a decode step of `slen` tokens, any of which past the first a verify may reject. + * present -- a decode step of `slen` tokens, any past the first rejectable by verify. * The window is rewritten the way gdn_conv_update rewrites its own: slot i holds position * i + 1 of (the window this step read ++ this step's inputs), so the old history shifted down * by one and then token t at slot hist - 1 + t. A next step that kept k of these tokens reads * at k - 1 and finds the history ending at token k - 1. It needs hist - 1 + slen slots, which * is the manager's hist + n_spec for a step of 1 + n_spec tokens. * - * ABSENT -- every token commits, so the next step reads at offset zero (its `num_accepted` is - * 1) and the window is the last `hist` values of the step, there. + * absent -- every token commits, so the next step reads at offset zero (`num_accepted` 1) and + * the window is the step's last `hist` values. * - * The two agree when the step has one token. Writing the tail at offset zero after a verify of - * several would hand a step that accepted only the first of them a history ending at a rejected - * draft, and one that accepted two a slot nothing wrote. + * The two agree for a one-token step. After a multi-token verify, the absent layout would give a + * step that accepted only the first token a history ending at a rejected draft. */ -/* THE DEPTHWISE CAUSAL CONVOLUTION AND ITS ROLLING WINDOW, shared by `ple_conv` (dilated, silu, - * an optional residual) and `causal_conv1d` (LFM2's short convolution: undilated, no activation, - * no residual). One body, so the two ops cannot disagree about the window's layout. */ +/* The depthwise causal convolution and its rolling window, shared by `ple_conv` (dilated, silu, + * optional residual) and `causal_conv1d` (LFM2's short convolution: undilated, no activation, no + * residual), so the two agree on the window layout. */ struct ConvArgs { const RadTensor *x, *w, *cs, *cu, *resid, *sidx, *hini, *nacc, *y; bool silu; @@ -234,13 +204,12 @@ static int depthwise_causal_conv(const RadArgs* a, const ConvArgs& o) { const int64_t n = p_int(a, "n", 0); const int64_t wid = p_int(a, "width", 0); - /* `x` is [M, n] and it is the call; `M` is the band. See band_rows in ref_common.h. */ + /* Rows come from `x` [M, n]; `M` is the band (see band_rows in ref_common.h). */ const int64_t M = n > 0 ? band_rows(numel(x) / n, p_int(a, "M", 0)) : 0; const int64_t dil = p_int(a, "dilation", 1); if (M <= 0 || n <= 0 || wid <= 0 || dil <= 0) return RAD_E_SHAPE; const int64_t hist_len = (wid - 1) * dil; - /* The read window lives in a stack frame. Nine at this model's shape; the bound is stated so a - * caller with a wider one is refused rather than overrunning it. */ + /* The read window lives in a stack frame (9 at this model's shape); wider is refused. */ enum { kHistMax = 64 }; if (hist_len > kHistMax) return RAD_E_UNSUPPORTED; @@ -252,15 +221,13 @@ static int depthwise_causal_conv(const RadArgs* a, const ConvArgs& o) { const int64_t state_len = cs->rank >= 3 ? cs->shape[cs->rank - 1] : hist_len; if (cs->data && state_len < hist_len) return RAD_E_SHAPE; - /* Checked for every sequence BEFORE any of them is written: a state too shallow for the offset - * asked for, or for the window a decode step leaves behind, is a caller bug whose symptom - * would otherwise be a silently truncated history. */ + /* Check every sequence before writing any: a state too shallow for the requested offset or for + * a decode step's resulting window is a caller bug that would silently truncate history. */ for (int64_t s = 0; s < N; ++s) { const int64_t off = nacc ? ld_int(nacc->dtype, nacc->data, offlin(nacc, s)) - 1 : 0; if (off < 0) return RAD_E_INVAL; if (off + hist_len > state_len) return RAD_E_SHAPE; - const int64_t slen = ld_int(cu->dtype, cu->data, offlin(cu, s + 1)) - - ld_int(cu->dtype, cu->data, offlin(cu, s)); + const int64_t slen = cu_at(cu, s + 1) - cu_at(cu, s); if (nacc && cs->data && hist_len > 0 && slen > 0 && hist_len - 1 + slen > state_len) return RAD_E_SHAPE; } @@ -270,27 +237,31 @@ static int depthwise_causal_conv(const RadArgs* a, const ConvArgs& o) { const int64_t rrow = resid ? rowoff(resid, 1, n) : 0; const int64_t rcol = resid ? laststride(resid) : 0; const int64_t wrow = rowoff(w, 1, wid), wcol = laststride(w); - /* [n_slots, n, state_len], tight, the layout gdn's conv state already uses. */ - const int64_t cs_slot = n * state_len, cs_ch = state_len; + /* [n_slots, n, state_len], as gdn's conv state; a flattened one is read as the tight layout. */ + const bool cs3 = cs->rank >= 3; + const int64_t cs_slot = cs3 ? cs->stride[cs->rank - 3] : n * state_len; + const int64_t cs_ch = cs3 ? cs->stride[cs->rank - 2] : state_len; + const int64_t cs_t = cs3 ? cs->stride[cs->rank - 1] : 1; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(M * n * wid) for (int64_t sc = 0; sc < N * n; ++sc) { const int64_t s = sc / n, c = sc % n; - const int64_t bos = ld_int(cu->dtype, cu->data, offlin(cu, s)); - const int64_t slen = ld_int(cu->dtype, cu->data, offlin(cu, s + 1)) - bos; + const int64_t bos = cu_at(cu, s); + const int64_t slen = cu_at(cu, s + 1) - bos; if (slen <= 0) continue; const int64_t slot = sidx ? ld_int(sidx->dtype, sidx->data, offlin(sidx, s)) : s; if (slot < 0) continue; - /* A zero `has_init` means the slot holds no history: the window in front of the first - * token is ZEROS and not whatever the slot last held. Without it a fresh sequence landing - * on a recycled slot convolves the previous sequence's tail into its first nine tokens -- - * fluent output with the wrong prefix. */ + /* A zero `has_init` means the slot holds no history: the window before the first token + * is zeros, not a recycled slot's previous contents. */ const bool warm = !hini || ld_int(hini->dtype, hini->data, offlin(hini, s)) != 0; const int64_t off = nacc ? ld_int(nacc->dtype, nacc->data, offlin(nacc, s)) - 1 : 0; + const int64_t base = slot * cs_slot + c * cs_ch; + /* Read whole before anything is written back, since a step longer than the window + * overwrites history it still reads. */ float hist[kHistMax]; for (int64_t i = 0; i < hist_len; ++i) - hist[i] = (warm && cs->data) ? ldt(cs, slot * cs_slot + c * cs_ch + off + i) : 0.0f; + hist[i] = (warm && cs->data) ? ldt(cs, base + (off + i) * cs_t) : 0.0f; for (int64_t t = 0; t < slen; ++t) { float acc = 0.0f; @@ -303,50 +274,27 @@ static int depthwise_causal_conv(const RadArgs* a, const ConvArgs& o) { const float r = resid ? ldt(resid, (bos + t) * rrow + c * rcol) : 0.0f; stt(y, (bos + t) * yrow + c * ycol, r + (o.silu ? act_silu(acc) : acc)); } - } - /* The window this step leaves behind, written after every read is done -- a sequence longer - * than the window overwrites history it was still reading otherwise. The layout is the one - * the header describes: shifted by one with every input of the step behind it when - * `num_accepted` is present, the last `hist` values at offset zero when it is not. */ - if (cs->data && hist_len > 0) { - #pragma omp parallel for schedule(static) - for (int64_t sc = 0; sc < N * n; ++sc) { - const int64_t s = sc / n, c = sc % n; - const int64_t bos = ld_int(cu->dtype, cu->data, offlin(cu, s)); - const int64_t slen = ld_int(cu->dtype, cu->data, offlin(cu, s + 1)) - bos; - if (slen <= 0) continue; - const int64_t slot = sidx ? ld_int(sidx->dtype, sidx->data, offlin(sidx, s)) : s; - if (slot < 0) continue; - const bool warm = !hini || ld_int(hini->dtype, hini->data, offlin(hini, s)) != 0; - const int64_t off = nacc ? ld_int(nacc->dtype, nacc->data, offlin(nacc, s)) - 1 : 0; - const int64_t base = slot * cs_slot + c * cs_ch; - - float win[kHistMax]; - for (int64_t i = 0; i < hist_len; ++i) - win[i] = warm ? ldt(cs, base + off + i) : 0.0f; - - if (nacc) { - for (int64_t i = 0; i + 1 < hist_len; ++i) stt(cs, base + i, win[i + 1]); - for (int64_t t = 0; t < slen; ++t) - stt(cs, base + hist_len - 1 + t, ldt(x, (bos + t) * xrow + c * xcol)); - } else { - float keep[kHistMax]; - for (int64_t i = 0; i < hist_len; ++i) { - const int64_t src = slen - hist_len + i; - keep[i] = src >= 0 ? ldt(x, (bos + src) * xrow + c * xcol) - : win[src + hist_len]; - } - for (int64_t i = 0; i < hist_len; ++i) stt(cs, base + i, keep[i]); + /* The window after the step, in the layout described above ple_conv. */ + if (!cs->data || hist_len == 0) continue; + if (nacc) { + for (int64_t i = 0; i + 1 < hist_len; ++i) stt(cs, base + i * cs_t, hist[i + 1]); + for (int64_t t = 0; t < slen; ++t) + stt(cs, base + (hist_len - 1 + t) * cs_t, ldt(x, (bos + t) * xrow + c * xcol)); + } else { + float keep[kHistMax]; + for (int64_t i = 0; i < hist_len; ++i) { + const int64_t src = slen - hist_len + i; + keep[i] = src >= 0 ? ldt(x, (bos + src) * xrow + c * xcol) : hist[src + hist_len]; } + for (int64_t i = 0; i < hist_len; ++i) stt(cs, base + i * cs_t, keep[i]); } } return RAD_OK; } int ref_ple_conv(const RadArgs* a, RadStream) { - /* NINE positions, four of them optional, so the count is checked and the optionals are tested - * one by one -- `have()` would refuse the op for an absent operand that is allowed to be. */ + /* Nine positions, four optional; `have()` would refuse an absent optional operand. */ if (a->n_t < 9) return RAD_E_INVAL; return depthwise_causal_conv(a, { t_in(a, 0), t_in(a, 1), t_in(a, 2), t_in(a, 3), t_in(a, 4), t_in(a, 5), t_in(a, 6), t_in(a, 7), t_in(a, 8), true }); diff --git a/libref/ref_qsa.cpp b/libref/ref_qsa.cpp new file mode 100644 index 00000000..afc1c42d --- /dev/null +++ b/libref/ref_qsa.cpp @@ -0,0 +1,356 @@ +/* ref_qsa.cpp -- the QSA indexer's score, selection, tail store and work list, and DFlash2's + * grouped convolution (docs/OPS.md, "Sparse attention (QSA)" and "Draft heads"). + * + * None of these is a fusion: an architecture that issues them has no chain to fall back to, so + * without a row here the host backend could not run the model and a device kernel would have no + * oracle. Each follows its libr4d kernel's contract (r4d_qsa_*_bf16.hip, + * r4d_dflash_conv_body.h), including which elements it leaves unwritten and the order of every + * output, with f32 sums in ascending order and no FMA (ref_common.h). + * + * `cu` holds absolute row indices: sequence s owns rows [cu[s], cu[s+1]) of every per-token + * operand, and cu[0] need not be 0. + */ +#include "ref_common.h" +#include "ref_gemm.h" /* row_stride */ +#include "ref_ops.h" + +#include +#include + +using namespace ref; + +namespace { + +/* The sequence whose cu span holds row `m`, or `none`. */ +int64_t seq_holding(const RadTensor* cu, int64_t n_seq, int64_t m, int64_t none) { + for (int64_t s = 0; s < n_seq; ++s) + if (m >= cu_at(cu, s) && m < cu_at(cu, s + 1)) return s; + return none; +} + +/* Offset of entry `i` of a rank-1 operand, or of column 0 of row `i` of a rank-2 one (a state + * index row's committed slot). */ +int64_t col0(const RadTensor* t, int64_t i) { + return t->rank >= 2 ? i * t->stride[0] : offlin(t, i); +} + +int64_t ldi(const RadTensor* t, int64_t off) { return ld_int(t->dtype, t->data, off); } + +/* Whether the trailing dimensions after the first are dense, so a row of a paged store is + * `numel / shape[0]` contiguous values from `row * stride[0]`. */ +bool rows_dense(const RadTensor* t) { + int64_t acc = 1; + for (int i = (int)t->rank - 1; i >= 1; --i) { + if (t->shape[i] != 1 && t->stride[i] != acc) return false; + acc *= t->shape[i]; + } + return true; +} + +} /* namespace */ + +/* ------------------------------------------------------------------ qsa_score */ +/* score[m][b] = (sum over heads h of relu(q[m][h] . bk[bt[seq(m)][b]])) / sqrt(n), for b below + * min(nc[seq], the table's width, the score plane's width); a negative page id scores -inf. Each + * dot is an f32 sum over the n lanes in order, the relus are summed over the heads in order. + * Columns past the bound, and rows no sequence of `cu` holds, are not written. */ +int ref_qsa_score(const RadArgs* a, RadStream) { + if (!have(a, 6)) return RAD_E_INVAL; + const RadTensor *q = &a->t[0], *bk = &a->t[1], *bt = &a->t[2], *cu = &a->t[3]; + const RadTensor *nc = &a->t[4], *o = &a->t[5]; + const int64_t n = p_int(a, "n", 0), heads = p_int(a, "heads", 0); + if (n <= 0 || heads <= 0) return RAD_E_SHAPE; + if (bt->rank != 2 || o->rank != 2 || bk->rank < 2) return RAD_E_SHAPE; + const int64_t M = o->shape[0], nb = std::min(bt->shape[1], o->shape[1]); + const int64_t n_seq = numel(cu) - 1, pages = bk->shape[0]; + if (M <= 0 || nb <= 0 || n_seq <= 0 || pages <= 0) return RAD_E_SHAPE; + if (bt->shape[0] < n_seq || numel(nc) < n_seq || rows_of(q, heads * n) < M) return RAD_E_SHAPE; + if (numel(bk) / pages != n) return RAD_E_SHAPE; + if (!rows_dense(bk)) return RAD_E_STRIDE; + const int64_t bt_rs = bt->stride[0], bt_cs = bt->stride[1]; + /* Every page id the loop will read must name a page of `bk`. */ + for (int64_t s = 0; s < n_seq; ++s) { + const int64_t nbs = std::min(ldi(nc, offlin(nc, s)), nb); + for (int64_t b = 0; b < nbs; ++b) + if (ldi(bt, s * bt_rs + b * bt_cs) >= pages) return RAD_E_INVAL; + } + const int64_t q_rs = row_stride(q, heads * n), q_cs = laststride(q); + const int64_t pg_rs = bk->stride[0], o_rs = o->stride[0], o_cs = o->stride[1]; + const float rn = std::sqrt((float)n); + REF_PAR_FOR(M * nb * heads * n) + for (int64_t m = 0; m < M; ++m) { + const int64_t s = seq_holding(cu, n_seq, m, -1); + if (s < 0) continue; + const int64_t nbs = std::min(ldi(nc, offlin(nc, s)), nb); + for (int64_t b = 0; b < nbs; ++b) { + const int64_t pg = ldi(bt, s * bt_rs + b * bt_cs); + if (pg < 0) { stt(o, m * o_rs + b * o_cs, -INFINITY); continue; } + float sum = 0.0f; + for (int64_t h = 0; h < heads; ++h) { + float d = 0.0f; + for (int64_t i = 0; i < n; ++i) + d += ldt(q, m * q_rs + (h * n + i) * q_cs) * ldt(bk, pg * pg_rs + i); + sum += std::fmax(d, 0.0f); + } + stt(o, m * o_rs + b * o_cs, sum / rn); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ qsa_select */ +/* The page-id table the sparse attention reads (docs/OPS.md): over the query's complete blocks + * n = min(nc[seq], (pos + 1) / ratio, width), the live ones (page id >= 0, score > -1e30) ranked + * by max(score, 0). At most `topk` are taken: all of them when that many or fewer are live, else + * every block above the topk-th largest value in block order, then the blocks equal to it in block + * order until topk are taken. The partial page bt[n] follows when (pos + 1) % ratio != 0 and + * n < width, and -1 pads the row to topk + 1. nsel counts the entries, seqused is + * (nsel - 1) * ratio + pos % ratio + 1 (0 for an empty table). A row no sequence holds reads + * sequence 0, as libr4d's does. */ +int ref_qsa_select(const RadArgs* a, RadStream) { + if (!have(a, 8)) return RAD_E_INVAL; + const RadTensor *sc = &a->t[0], *bt = &a->t[1], *nc = &a->t[2], *po = &a->t[3]; + const RadTensor *cu = &a->t[4], *se = &a->t[5], *ns = &a->t[6], *su = &a->t[7]; + const int64_t topk = p_int(a, "topk", 0), ratio = p_int(a, "ratio", 0); + if (topk <= 0 || ratio <= 0) return RAD_E_SHAPE; + if (sc->rank != 2 || bt->rank != 2 || se->rank != 2) return RAD_E_SHAPE; + const int64_t M = sc->shape[0], nb = std::min(bt->shape[1], sc->shape[1]); + const int64_t n_seq = numel(cu) - 1; + if (M <= 0 || nb <= 0 || n_seq <= 0) return RAD_E_SHAPE; + if (bt->shape[0] < n_seq || numel(nc) < n_seq) return RAD_E_SHAPE; + if (se->shape[0] < M || se->shape[1] < topk + 1) return RAD_E_SHAPE; + if (numel(ns) < M || numel(po) < M || numel(su) < M) return RAD_E_SHAPE; + for (int64_t s = 0; s < n_seq; ++s) + if (ldi(nc, offlin(nc, s)) < 0) return RAD_E_INVAL; + for (int64_t m = 0; m < M; ++m) + if (ldi(po, offlin(po, m)) < 0) return RAD_E_INVAL; + const int64_t s_rs = sc->stride[0], s_cs = sc->stride[1]; + const int64_t bt_rs = bt->stride[0], bt_cs = bt->stride[1]; + const int64_t o_rs = se->stride[0], o_cs = se->stride[1]; + REF_PAR_FOR(M * nb * 4) + for (int64_t m = 0; m < M; ++m) { + const int64_t s = seq_holding(cu, n_seq, m, 0); + const int64_t p = ldi(po, offlin(po, m)); + const int64_t n = std::min(std::min(ldi(nc, offlin(nc, s)), nb), (p + 1) / ratio); + std::vector val((size_t)n); + std::vector live; + for (int64_t b = 0; b < n; ++b) { + const float v = ldt(sc, m * s_rs + b * s_cs); + if (ldi(bt, s * bt_rs + b * bt_cs) < 0 || !(v > -1e30f)) continue; + val[(size_t)b] = v > 0.0f ? v : 0.0f; + live.push_back(b); + } + std::vector take; + if ((int64_t)live.size() <= topk) { + take = live; + } else { + std::vector ord; + for (int64_t b : live) ord.push_back(val[(size_t)b]); + std::nth_element(ord.begin(), ord.begin() + (topk - 1), ord.end(), std::greater()); + const float thr = ord[(size_t)(topk - 1)]; + for (int64_t b : live) + if (val[(size_t)b] > thr) take.push_back(b); + for (int64_t b : live) + if ((int64_t)take.size() < topk && val[(size_t)b] == thr) take.push_back(b); + } + int64_t out = 0; + for (int64_t b : take) st_int(se->dtype, se->data, m * o_rs + (out++) * o_cs, + ldi(bt, s * bt_rs + b * bt_cs)); + if (n < nb && (p + 1) % ratio != 0) { + const int64_t part = ldi(bt, s * bt_rs + n * bt_cs); + if (part >= 0) st_int(se->dtype, se->data, m * o_rs + (out++) * o_cs, part); + } + for (int64_t i = out; i <= topk; ++i) st_int(se->dtype, se->data, m * o_rs + i * o_cs, -1); + st_int(ns->dtype, ns->data, offlin(ns, m), out); + st_int(su->dtype, su->data, offlin(su, m), out == 0 ? 0 : (out - 1) * ratio + p % ratio + 1); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ qsa_tail_store */ +/* state[sidx[s][0]][0][pos[t] % ring] = k[t] for the last `ring` rows of each sequence, rows in + * ascending order (a row whose slot is -1, or that no sequence holds, writes nothing). Every other + * row of `state` keeps its contents. */ +int ref_qsa_tail_store(const RadArgs* a, RadStream) { + if (!have(a, 5)) return RAD_E_INVAL; + const RadTensor *k = &a->t[0], *po = &a->t[1], *cu = &a->t[2], *st = &a->t[3]; + const RadTensor *sx = &a->t[4]; + const int64_t n = p_int(a, "n", 0), ratio = p_int(a, "ratio", 0), ring = p_int(a, "ring", 0); + if (n <= 0 || ratio <= 0 || ring < ratio) return RAD_E_INVAL; + if (k->rank != 2 || st->rank != 4 || st->shape[1] != 1) return RAD_E_SHAPE; + const int64_t T = k->shape[0], slots = st->shape[0], n_seq = numel(cu) - 1; + if (T <= 0 || k->shape[1] != n || st->shape[2] < ring || st->shape[3] != n) return RAD_E_SHAPE; + if (n_seq <= 0 || numel(po) < T) return RAD_E_SHAPE; + if ((sx->rank >= 2 ? sx->shape[0] : numel(sx)) < n_seq) return RAD_E_SHAPE; + /* The rows that write, validated before any write. */ + std::vector> w; /* (row, slot) */ + for (int64_t t = 0; t < T; ++t) { + const int64_t s = seq_holding(cu, n_seq, t, -1); + if (s < 0 || t < cu_at(cu, s + 1) - ring) continue; + const int64_t si = ldi(sx, col0(sx, s)); + if (si < 0) continue; + if (si >= slots || ldi(po, offlin(po, t)) < 0) return RAD_E_INVAL; + w.push_back({ t, si }); + } + for (const auto& [t, si] : w) { + const int64_t row = ldi(po, offlin(po, t)) % ring; + const int64_t db = si * st->stride[0] + row * st->stride[2]; + for (int64_t d = 0; d < n; ++d) + stt(st, db + d * st->stride[3], ldt(k, t * k->stride[0] + d * k->stride[1])); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ qsa_work */ +/* The blocks that complete in this batch, in sequence order and ascending within one: sequence s + * with positions p0 .. p1 completes blocks p0 / ratio .. (p1 + 1) / ratio - 1. Work item w gets its + * block's page bt[s][b] (-1 when the sequence has no tail slot), its first-token position b * ratio + * in bpos (or, with `rope`, three components: a first token in the batch reads its own, an earlier + * one its position plus the shift rope[0][cu[s]] - p0), and, when the slot exists, the block's + * `ratio` raw keys in stage rows w * ratio + i: key q from the batch row cu[s] + q - p0 when q >= p0, + * else from tail row q % ring. Items past the count get page -1 and position 0 and leave `stage` + * alone. nc[s] = (last position + 1) / ratio, 0 for an empty sequence. */ +int ref_qsa_work(const RadArgs* a, RadStream) { + if (a->n_t < 11) return RAD_E_INVAL; + const RadTensor *k = t_in(a, 0), *po = t_in(a, 1), *cu = t_in(a, 2), *tl = t_in(a, 3); + const RadTensor *sx = t_in(a, 4), *bt = t_in(a, 5), *rp = t_in(a, 6), *stg = t_in(a, 7); + const RadTensor *pg = t_in(a, 8), *bp = t_in(a, 9), *nc = t_in(a, 10); + if (!k || !po || !cu || !tl || !sx || !bt || !stg || !pg || !bp || !nc) return RAD_E_INVAL; + const int64_t n = p_int(a, "n", 0), ratio = p_int(a, "ratio", 0), ring = p_int(a, "ring", 0); + if (n <= 0 || ratio <= 0 || ring < ratio) return RAD_E_INVAL; + if (k->rank != 2 || bt->rank != 2 || stg->rank != 2) return RAD_E_SHAPE; + if (tl->rank != 4 || tl->shape[1] != 1 || tl->shape[2] < ring || tl->shape[3] != n) + return RAD_E_SHAPE; + const int64_t T = k->shape[0], n_seq = numel(cu) - 1, slots = tl->shape[0]; + if (T <= 0 || n_seq <= 0 || numel(po) < T || k->shape[1] != n || stg->shape[1] != n) + return RAD_E_SHAPE; + if (bt->shape[0] < n_seq || (sx->rank >= 2 ? sx->shape[0] : numel(sx)) < n_seq) + return RAD_E_SHAPE; + const int64_t mw = numel(pg); + if (mw < n_seq || stg->shape[0] < mw * ratio || numel(nc) < n_seq) return RAD_E_SHAPE; + int64_t bstep = 1; + if (bp->rank == 2) { + if (bp->shape[0] < mw || bp->stride[1] != 1 || bp->stride[0] < bp->shape[1] || + (rp && bp->shape[1] < 3)) + return RAD_E_SHAPE; + bstep = bp->stride[0]; + } else if (rp || numel(bp) < mw) { + return RAD_E_SHAPE; + } + if (rp && (rp->rank != 2 || rp->shape[0] < 3 || rp->shape[1] < T)) return RAD_E_SHAPE; + for (int64_t t = 0; t < T; ++t) + if (ldi(po, offlin(po, t)) < 0) return RAD_E_INVAL; + + /* The work list, validated before any write. */ + struct Item { int64_t s, b; }; + std::vector items; + for (int64_t s = 0; s < n_seq; ++s) { + const int64_t t0 = cu_at(cu, s), t1 = cu_at(cu, s + 1); + if (t1 <= t0) continue; + if (t0 < 0 || t1 > T) return RAD_E_SHAPE; + const int64_t p0 = ldi(po, offlin(po, t0)), p1 = ldi(po, offlin(po, t1 - 1)); + for (int64_t b = p0 / ratio; b <= (p1 + 1) / ratio - 1; ++b) { + if ((int64_t)items.size() >= mw) break; + if (b >= bt->shape[1]) return RAD_E_SHAPE; + const int64_t si = ldi(sx, col0(sx, s)); + if (si >= slots) return RAD_E_INVAL; + for (int64_t i = 0; si >= 0 && i < ratio; ++i) { + const int64_t q = b * ratio + i; + if (q >= p0 && t0 + (q - p0) >= T) return RAD_E_SHAPE; + } + items.push_back({ s, b }); + } + } + + for (int64_t s = 0; s < n_seq; ++s) { + const int64_t t0 = cu_at(cu, s), t1 = cu_at(cu, s + 1); + st_int(nc->dtype, nc->data, offlin(nc, s), + t1 > t0 ? (ldi(po, offlin(po, t1 - 1)) + 1) / ratio : 0); + } + const int ncomp = rp ? 3 : 1; + auto bpos_at = [&](int64_t w, int c) { return bp->rank == 2 ? w * bstep + c : offlin(bp, w); }; + for (int64_t w = 0; w < mw; ++w) { + if (w >= (int64_t)items.size()) { + st_int(pg->dtype, pg->data, offlin(pg, w), -1); + for (int c = 0; c < ncomp; ++c) st_int(bp->dtype, bp->data, bpos_at(w, c), 0); + continue; + } + const int64_t s = items[(size_t)w].s, b = items[(size_t)w].b; + const int64_t t0 = cu_at(cu, s), p0 = ldi(po, offlin(po, t0)); + const int64_t si = ldi(sx, col0(sx, s)); + st_int(pg->dtype, pg->data, offlin(pg, w), + si < 0 ? -1 : ldi(bt, s * bt->stride[0] + b * bt->stride[1])); + const int64_t f = b * ratio; + if (!rp) { + st_int(bp->dtype, bp->data, bpos_at(w, 0), f); + } else { + const int64_t rs = rp->stride[0], rc = rp->stride[1]; + for (int c = 0; c < 3; ++c) + st_int(bp->dtype, bp->data, bpos_at(w, c), + f >= p0 ? ldi(rp, c * rs + (t0 + f - p0) * rc) + : f + (ldi(rp, t0 * rc) - p0)); + } + if (si < 0) continue; + for (int64_t i = 0; i < ratio; ++i) { + const int64_t q = f + i; + const RadTensor* src = q >= p0 ? k : tl; + const int64_t sb = q >= p0 ? (t0 + q - p0) * k->stride[0] + : si * tl->stride[0] + (q % ring) * tl->stride[2]; + const int64_t sc = q >= p0 ? k->stride[1] : tl->stride[3]; + const int64_t db = (w * ratio + i) * stg->stride[0]; + for (int64_t d = 0; d < n; ++d) + stt(stg, db + d * stg->stride[1], ldt(src, sb + d * sc)); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ dflash_conv */ +/* DFlash2's grouped dynamic depthwise convolution over the [T, H] rows of x, blocks of + * `block_size` rows starting at row 0: + * + * out[t][h] = sum over taps j with j == 0 or t % block_size >= j of + * (base[j][h] + delta[t][j][h / group_size]) * x[t - j][h] + * + * in tap order, each term `(base + delta) * x` rounded as written, rounded once to out's dtype. + * `delta` is [T, taps, NG], or [T, >= taps * NG] read at its own row pitch (a slice of the + * [T, 2, taps, NG] coefficient projection). `out` must not alias `x`: tap j reads row t - j. */ +int ref_dflash_conv(const RadArgs* a, RadStream) { + if (!have(a, 4)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *dl = &a->t[1], *bs = &a->t[2], *o = &a->t[3]; + const int64_t taps = p_int(a, "taps", 0), group = p_int(a, "group_size", 0); + const int64_t NG = p_int(a, "NG", 0), bsz = p_int(a, "block_size", 0); + if (taps <= 0 || group <= 0 || NG <= 0 || bsz <= 0) return RAD_E_INVAL; + if (x->data == o->data) return RAD_E_INVAL; + if (x->rank != 2 || o->rank != 2) return RAD_E_SHAPE; + const int64_t T = x->shape[0], H = x->shape[1]; + if (T <= 0 || o->shape[0] != T || o->shape[1] != H || H != NG * group) return RAD_E_SHAPE; + if (numel(bs) < taps * H) return RAD_E_SHAPE; + int64_t d_rs = 0, d_ts = 0, d_gs = 0; + if (dl->rank == 3) { + if (dl->shape[0] < T || dl->shape[1] < taps || dl->shape[2] < NG) return RAD_E_SHAPE; + d_rs = dl->stride[0]; d_ts = dl->stride[1]; d_gs = dl->stride[2]; + } else if (dl->rank == 2) { + if (dl->shape[0] < T || dl->shape[1] < taps * NG) return RAD_E_SHAPE; + d_rs = dl->stride[0]; d_gs = dl->stride[1]; d_ts = NG * d_gs; + } else { + return RAD_E_SHAPE; + } + const int64_t x_rs = x->stride[0], x_cs = x->stride[1]; + const int64_t o_rs = o->stride[0], o_cs = o->stride[1]; + REF_PAR_FOR(T * H * taps) + for (int64_t t = 0; t < T; ++t) + for (int64_t h = 0; h < H; ++h) { + const int64_t g = h / group; + float acc = 0.0f; + for (int64_t j = 0; j < taps; ++j) { + if (j > 0 && t % bsz < j) continue; + const float c = ldt(bs, rowoff(bs, j, H) + h * laststride(bs)) + + ldt(dl, t * d_rs + j * d_ts + g * d_gs); + const float term = c * ldt(x, (t - j) * x_rs + h * x_cs); + acc = j == 0 ? term : acc + term; + } + stt(o, t * o_rs + h * o_cs, acc); + } + return RAD_OK; +} diff --git a/libref/ref_quant.cpp b/libref/ref_quant.cpp index 221eda82..6bd43b2d 100644 --- a/libref/ref_quant.cpp +++ b/libref/ref_quant.cpp @@ -1,59 +1,78 @@ /* ref_quant.cpp -- activation quantisation, the Walsh-Hadamard rotation, and the fused forms. * - * Activations in this engine are ROTATED INT8, not fp8: several times better error at the same - * width, and the rotation is what makes a single scale per row viable at all (docs/OPS.md). + * ============================== What `group` means ============================== * - * ============================== WHAT `group` MEANS ============================== + * docs/OPS.md gives these ops one parameter `group` with different meanings; ref fixes them to + * match the fast kernels: * - * docs/OPS.md gives all five ops one parameter called `group` and it does not mean the same thing - * in all five. Ref fixes the reading, because a fallback that guessed differently from the fast - * kernel would produce plausible wrong numbers: + * quant_act_i8 one scale per row; `group` is the width of the code sums `asum` holds. + * quant_act_i8g contiguous elements sharing one f32 scale, so `scale` is [M, ceil(n/group)]. + * dequant the same, inverted: the scale stream's extent gives the group count and + * `group` each group's width. + * had_* the Walsh-Hadamard rotation width (libr4d's `had`); the int8 scale is per row + * and carries the 1/sqrt(group) normalisation, as r4d_had_quant_act_i8 does. A + * rotation block may not cross a tensor-parallel shard, so the width must divide + * the per-rank n. * - * quant_act_i8 `group` is the number of contiguous elements sharing one f32 scale, so `scale` - * is [M, ceil(n/group)]. group <= 0 or group >= n is one scale per ROW, which is - * what every int8 GEMM in libr4d consumes. - * dequant the same reading, inverted: the scale stream's extent says how many groups - * there are and `group` says how wide each is. - * had_* `group` is the WALSH-HADAMARD ROTATION WIDTH (libr4d calls it `had`) and the - * int8 scale is per ROW, carrying the 1/sqrt(group) normalisation. That is the - * reading docs/OPS.md's own prose forces -- "the rotation (a per-group - * Walsh-Hadamard) is what makes a single scale per row viable" -- and it is what - * r4d_had_quant_act_i8 does. A rotation block may not cross a tensor-parallel - * shard boundary, so the width has to divide the PER-RANK n. - * - * ============================== THE ROTATION ============================== + * ============================== The rotation ============================== * * Unnormalised butterflies at ascending strides 1, 2, 4, ... group/2, pairing i with i+h where - * (i & h) == 0 -- the same order and the same pairing as r4d_fwht.h, so the two agree bit for bit - * on the same input. The 1/sqrt(group) is folded into the scale rather than applied to the values, - * again because that is what the fast kernel does: dividing every element by a constant cannot - * change which int8 code it rounds to, and folding it costs nothing. + * (i & h) == 0: the order and pairing of r4d_fwht.h, so the two agree bit for bit. The 1/sqrt(group) + * is folded into the scale, as the fast kernel does; scaling every element by a constant cannot + * change its int8 code here. */ #include "ref_common.h" -#include "ref_gemm.h" /* Mat and Scales: gemm_nt_q_gated reads a quantised operand the same way */ +#include "ref_gemm.h" /* Mat and Scales, for gemm_nt_q_gated */ #include "ref_ops.h" using namespace ref; -/* Symmetric int8 everywhere below: q = round(x * 127 / amax), scale = amax / 127, with the store - * rounding to nearest and saturating (ref_common.h). An all-zero row gets scale 0 and codes 0, - * which dequantises back to zero -- the alternative, a tiny epsilon scale, turns a zero row into - * denormal noise in the GEMM that reads it. */ - /* ------------------------------------------------------------------ quant_act_i8 */ +/* The activation of the w4a8, w8a8 and w2a8 GEMMs, with libr4d's arithmetic: one scale per row, + * max(amax, 1e-8) / 127, and codes x * (1 / scale) rounded to nearest even, stored in the step + * order (i8_step_pos). `asum`, when passed, receives each row's code sums per `group` columns, + * group-major [n/group][Mpad] with Mpad = ceil(M/16)*16 (the asymmetric GEMMs read whole 16-row + * tiles); rows M..Mpad-1 are not written. */ int ref_quant_act_i8(const RadArgs* a, RadStream) { if (!have(a, 3)) return RAD_E_INVAL; - /* THE ASUM FORM IS A DIFFERENT CONTRACT, AND THIS DECLINES IT BY NAME. `asum` present selects - * libr4d's asymmetric form, of which the extra output is only the visible half: that kernel - * writes ONE SCALE PER ROW over the whole of `n` -- `group` is the asum grouping width there, - * not the scale granularity -- and it stores `q` in fragment order rather than row-major. Run - * beside it, the symmetric quantiser below compares neither plane against what it means. - * - * The name matters more than the declining. Without it the per-group scale plane this code - * writes is simply wider than the per-row one the caller allocated, the size check refuses, - * and a sweep reports the ENGINE'S operands as the fault -- the production 2-bit draft head's - * quantiser among them. */ - if (a->n_t > 3 && a->t[3].data) return RAD_E_UNSUPPORTED; + const RadTensor *x = &a->t[0], *q = &a->t[1], *s = &a->t[2]; + const RadTensor* as = t_in(a, 3); + const int64_t n = p_int(a, "n", 0); + if (n <= 0 || n % 16) return RAD_E_SHAPE; /* whole steps */ + if (q->dtype != RAD_I8) return RAD_E_DTYPE; + if (laststride(q) != 1) return RAD_E_STRIDE; + const int64_t rows = numel(x) / n; + if (rows <= 0 || numel(q) < rows * n || numel(s) < rows) return RAD_E_SHAPE; + const int64_t g = as ? p_int(a, "group", 0) : 0; + const int64_t mpad = (rows + 15) / 16 * 16; + if (as && (g <= 0 || n % g || numel(as) < n / g * mpad)) return RAD_E_SHAPE; + + REF_PAR_FOR(rows * n) + for (int64_t r = 0; r < rows; ++r) { + const int64_t xb = rowoff(x, r, n), xs = laststride(x); + int8_t* qr = (int8_t*)q->data + rowoff(q, r, n); + float amax = 0.0f; + for (int64_t i = 0; i < n; ++i) amax = std::max(amax, std::fabs(ldt(x, xb + i * xs))); + const float scale = std::max(amax, 1e-8f) / 127.0f; + const float inv = 1.0f / scale; + for (int64_t i = 0; i < n; ++i) + st_dt(RAD_I8, qr, i8_step_pos(i), ldt(x, xb + i * xs) * inv); + stt(s, rowoff(s, r, 1), scale); + for (int64_t gi = 0; as && gi < n / g; ++gi) { + int64_t sum = 0; + for (int64_t i = gi * g; i < (gi + 1) * g; ++i) sum += qr[i8_step_pos(i)]; + stt(as, gi * mpad + r, (float)sum); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ quant_act_i8g */ +/* quant_act_fp8 at int8 codes, libr4d's arithmetic: per `group` contiguous elements a scale + * amax / 127 (1 for an all-zero group) and codes rounded to nearest even, row-major. What the + * i8a8 GEMMs read. */ +int ref_quant_act_i8g(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *q = &a->t[1], *s = &a->t[2]; const int64_t n = p_int(a, "n", 0); if (n <= 0) return RAD_E_SHAPE; @@ -65,27 +84,48 @@ int ref_quant_act_i8(const RadArgs* a, RadStream) { const int64_t ngrp = (n + g - 1) / g; if (numel(s) < rows * ngrp) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { const int64_t xb = rowoff(x, r, n), qb = rowoff(q, r, n); const int64_t xs = laststride(x), qs = laststride(q); for (int64_t gi = 0; gi < ngrp; ++gi) { const int64_t k0 = gi * g, k1 = (k0 + g < n) ? k0 + g : n; - float amax = 0.0f; - for (int64_t i = k0; i < k1; ++i) { - float m = std::fabs(ldt(x, xb + i * xs)); - if (m > amax) amax = m; - } - const float inv = amax > 0.0f ? 127.0f / amax : 0.0f; - for (int64_t i = k0; i < k1; ++i) - st_dt(q->dtype, q->data, qb + i * qs, ldt(x, xb + i * xs) * inv); - stt(s, rowoff(s, r, ngrp) + gi * laststride(s), amax / 127.0f); + const float sc = q8_group([&](int64_t i) { return ldt(x, xb + (k0 + i) * xs); }, + k1 - k0, 127.0f, q, qb + k0 * qs, qs); + stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc); } } return RAD_OK; } +/* The rotated forms below are symmetric int8 with one scale per row: q = round(x * 127 / amax), + * scale = amax / 127, the store rounding to nearest and saturating (ref_common.h). An all-zero row + * gets scale 0 and codes 0. */ + /* ------------------------------------------------------------------ had_quant_act_i8 */ +/* The rotated int8 row of the had_*_i8 ops: `v(i)` for i < n rotated in blocks of `g`, its codes + * stored at q[qb + i * qs] against one scale for the whole row (the amax is over the whole rotated + * row). The rotation is computed twice, for the amax and then for the codes, rather than held. + * Returns the row's scale, amax / 127 / sqrt(g). */ +template +static float had_i8_row(const V& v, int64_t n, int64_t g, const RadTensor* q, int64_t qb, + int64_t qs) { + float buf[REF_HAD_MAX]; + float amax = 0.0f; + for (int64_t b = 0; b < n; b += g) { + for (int64_t i = 0; i < g; ++i) buf[i] = v(b + i); + fwht(buf, g); + for (int64_t i = 0; i < g; ++i) { float m = std::fabs(buf[i]); if (m > amax) amax = m; } + } + const float inv = amax > 0.0f ? 127.0f / amax : 0.0f; + for (int64_t b = 0; b < n; b += g) { + for (int64_t i = 0; i < g; ++i) buf[i] = v(b + i); + fwht(buf, g); + for (int64_t i = 0; i < g; ++i) st_dt(q->dtype, q->data, qb + (b + i) * qs, buf[i] * inv); + } + return amax / 127.0f * (1.0f / std::sqrt((float)g)); +} + int ref_had_quant_act_i8(const RadArgs* a, RadStream) { if (!have(a, 3)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *q = &a->t[1], *s = &a->t[2]; @@ -95,47 +135,27 @@ int ref_had_quant_act_i8(const RadArgs* a, RadStream) { if (g > REF_HAD_MAX) return RAD_E_UNSUPPORTED; const int64_t rows = numel(x) / n; if (rows <= 0 || numel(q) < rows * n || numel(s) < rows) return RAD_E_SHAPE; - const float norm = 1.0f / std::sqrt((float)g); - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * n * 8) for (int64_t r = 0; r < rows; ++r) { - float buf[REF_HAD_MAX]; - const int64_t xb = rowoff(x, r, n), qb = rowoff(q, r, n); - const int64_t xs = laststride(x), qs = laststride(q); - /* amax is over the WHOLE rotated row, because the scale is per row. */ - float amax = 0.0f; - for (int64_t b = 0; b < n; b += g) { - for (int64_t i = 0; i < g; ++i) buf[i] = ldt(x, xb + (b + i) * xs); - fwht(buf, g); - for (int64_t i = 0; i < g; ++i) { float m = std::fabs(buf[i]); if (m > amax) amax = m; } - } - const float inv = amax > 0.0f ? 127.0f / amax : 0.0f; - for (int64_t b = 0; b < n; b += g) { - for (int64_t i = 0; i < g; ++i) buf[i] = ldt(x, xb + (b + i) * xs); - fwht(buf, g); - for (int64_t i = 0; i < g; ++i) - st_dt(q->dtype, q->data, qb + (b + i) * qs, buf[i] * inv); - } - stt(s, r * laststride(s), amax / 127.0f * norm); + const int64_t xb = rowoff(x, r, n), xs = laststride(x); + stt(s, r * laststride(s), had_i8_row([&](int64_t i) { return ldt(x, xb + i * xs); }, n, g, + q, rowoff(q, r, n), laststride(q))); } return RAD_OK; } /* ------------------------------------------------------------------ rmsnorm_had_quant_i8 */ -/* The fused form of rmsnorm + hadamard + quant_act_i8, which is what a w4a8 layer wants where a - * bf16 layer wants a plain rmsnorm (spec §2.3). A plugin asks for this first and emits the three - * unfused ops when it does not resolve; ref resolves it, so the fallback path is one launch. +/* Fused rmsnorm + hadamard + quant_act_i8, what a w4a8 layer uses in place of a plain rmsnorm + * (spec §2.3). A plugin asks for this first and falls back to the three unfused ops. * - * `residual` PRESENT IS THE fused_add_rms_norm FORM: the add happens first, the sum is written - * back into `residual` (that is what makes it INOUT and what the next layer's shortcut reads), and - * the norm is taken over the sum. The variance comes from the f32 sum and the rotation reads the - * sum back AFTER it has been narrowed to the residual tensor's own dtype, which is what the pair - * of kernels this replaces does -- matching it is what makes the fused form substitutable for - * that pair. + * With `residual` it is the fused_add_rms_norm form: the sum is written back to `residual` (INOUT; + * the next layer's shortcut reads it) and the norm is over the sum. The variance comes from the f32 + * sum, but the rotation reads the sum back after narrowing to the residual's dtype, as the unfused + * pair does. * - * `out_bf16` is the post-norm, PRE-ROTATION tensor for a layer that also has a bf16 consumer of - * it. Pre-rotation because the rotation is an artefact of the int8 path; a bf16 consumer wants the - * normalised activation, not a Walsh-Hadamard of it. */ + * `out_bf16` is the post-norm, pre-rotation tensor for a bf16 consumer; the rotation belongs only + * to the int8 path. */ int ref_rmsnorm_had_quant_i8(const RadArgs* a, RadStream) { if (a->n_t < 5) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *w = &a->t[2], *q = &a->t[3], *s = &a->t[4]; @@ -152,28 +172,25 @@ int ref_rmsnorm_had_quant_i8(const RadArgs* a, RadStream) { if (rows <= 0 || numel(q) < rows * n || numel(s) < rows || numel(w) < n) return RAD_E_SHAPE; if (res && numel(res) < rows * n) return RAD_E_SHAPE; if (ob && numel(ob) < rows * n) return RAD_E_SHAPE; - const float norm = 1.0f / std::sqrt((float)g); - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * n * 8) for (int64_t r = 0; r < rows; ++r) { - float buf[REF_HAD_MAX]; - const int64_t xb = rowoff(x, r, n), qb = rowoff(q, r, n); - const int64_t xs = laststride(x), qs = laststride(q), ws = laststride(w); + const int64_t xb = rowoff(x, r, n), xs = laststride(x), ws = laststride(w); - /* The residual add, written back before anything reads it, so what follows reads the - * narrowed sum rather than the f32 one. */ + /* The variance is taken from the f32 sum as it is written back; everything after reads + * the narrowed sum. */ const int64_t rb = res ? rowoff(res, r, n) : 0; const int64_t rst = res ? laststride(res) : 1; - if (res) - for (int64_t i = 0; i < n; ++i) - stt(res, rb + i * rst, ldt(x, xb + i * xs) + ldt(res, rb + i * rst)); - auto src = [&](int64_t i) { return res ? ldt(res, rb + i * rst) : ldt(x, xb + i * xs); }; float ss = 0.0f; - for (int64_t i = 0; i < n; ++i) { const float v = src(i); ss += v * v; } + for (int64_t i = 0; i < n; ++i) { + const float v = res ? ldt(x, xb + i * xs) + ldt(res, rb + i * rst) : src(i); + if (res) stt(res, rb + i * rst, v); + ss += v * v; + } const float sc = 1.0f / std::sqrt(ss / (float)n + eps); if (ob) { @@ -182,37 +199,20 @@ int ref_rmsnorm_had_quant_i8(const RadArgs* a, RadStream) { stt(ob, obb + i * obs, src(i) * sc * (ldt(w, i * ws) + wadd)); } - float amax = 0.0f; - for (int64_t b = 0; b < n; b += g) { - for (int64_t i = 0; i < g; ++i) - buf[i] = src(b + i) * sc * (ldt(w, (b + i) * ws) + wadd); - fwht(buf, g); - for (int64_t i = 0; i < g; ++i) { float m = std::fabs(buf[i]); if (m > amax) amax = m; } - } - const float inv = amax > 0.0f ? 127.0f / amax : 0.0f; - for (int64_t b = 0; b < n; b += g) { - for (int64_t i = 0; i < g; ++i) - buf[i] = src(b + i) * sc * (ldt(w, (b + i) * ws) + wadd); - fwht(buf, g); - for (int64_t i = 0; i < g; ++i) - st_dt(q->dtype, q->data, qb + (b + i) * qs, buf[i] * inv); - } - stt(s, r * laststride(s), amax / 127.0f * norm); + auto normed = [&](int64_t i) { return src(i) * sc * (ldt(w, i * ws) + wadd); }; + stt(s, r * laststride(s), had_i8_row(normed, n, g, q, rowoff(q, r, n), laststride(q))); } return RAD_OK; } /* ------------------------------------------------------------------ gated_had_quant_i8 */ -/* An elementwise gated product, then the rotation and the quantiser. Two of the four rotated sites - * in a w4a8 model have this shape and differ by one multiply, so `act` picks between them: - * silu(a)*b is down_proj's input, sigmoid(a)*b is o_proj's on a gated-attention layer - * (Qwen3_5Attention computes attn_output * sigmoid(gate)). It defaults to silu, which is the form - * docs/OPS.md's `silu_mul` names. `mode` is libr4d's integer spelling of the same choice and is - * accepted where `act` is absent, so a caller written against either name works. +/* An elementwise gated product, then the rotation and the quantiser. Two of a w4a8 model's four + * rotated sites have this shape: silu(a)*b is down_proj's input, sigmoid(a)*b is o_proj's on a + * gated-attention layer (Qwen3_5Attention's attn_output * sigmoid(gate)). `act` picks, default silu + * (docs/OPS.md's `silu_mul`); libr4d's integer `mode` is accepted where `act` is absent. * - * `b` ABSENT IS THE PACKED FORM: `a` is [M, 2n], the gate is its first half and the up its second. - * That is vLLM's layout and the one a fused gate_up projection produces, so both readings have to - * exist; two operands with the second optional is the only shape that expresses both. */ + * With `b` absent, `a` is the packed [M, 2n] form (gate first half, up second), vLLM's layout and + * what a fused gate_up projection produces. */ int ref_gated_had_quant_i8(const RadArgs* a, RadStream) { if (a->n_t < 4) return RAD_E_INVAL; const RadTensor *ga = &a->t[0], *q = &a->t[2], *s = &a->t[3]; @@ -229,13 +229,10 @@ int ref_gated_had_quant_i8(const RadArgs* a, RadStream) { if (rows <= 0 || numel(s) < rows) return RAD_E_SHAPE; if (numel(ga) < rows * (up ? n : 2 * n)) return RAD_E_SHAPE; if (up && numel(up) < rows * n) return RAD_E_SHAPE; - const float norm = 1.0f / std::sqrt((float)g); - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * n * 8) for (int64_t r = 0; r < rows; ++r) { - float buf[REF_HAD_MAX]; - const int64_t gb = rowoff(ga, r, up ? n : 2 * n), qb = rowoff(q, r, n); - const int64_t gs = laststride(ga), qs = laststride(q); + const int64_t gb = rowoff(ga, r, up ? n : 2 * n), gs = laststride(ga); const int64_t ub = up ? rowoff(up, r, n) : 0; const int64_t us = up ? laststride(up) : 0; auto gated = [&](int64_t i) { @@ -243,29 +240,14 @@ int ref_gated_had_quant_i8(const RadArgs* a, RadStream) { const float x = up ? ldt(up, ub + i * us) : ldt(ga, gb + (n + i) * gs); return (act == 1 ? act_sigmoid(gate) : act_silu(gate)) * x; }; - float amax = 0.0f; - for (int64_t b = 0; b < n; b += g) { - for (int64_t i = 0; i < g; ++i) buf[i] = gated(b + i); - fwht(buf, g); - for (int64_t i = 0; i < g; ++i) { float m = std::fabs(buf[i]); if (m > amax) amax = m; } - } - const float inv = amax > 0.0f ? 127.0f / amax : 0.0f; - for (int64_t b = 0; b < n; b += g) { - for (int64_t i = 0; i < g; ++i) buf[i] = gated(b + i); - fwht(buf, g); - for (int64_t i = 0; i < g; ++i) - st_dt(q->dtype, q->data, qb + (b + i) * qs, buf[i] * inv); - } - stt(s, r * laststride(s), amax / 127.0f * norm); + stt(s, r * laststride(s), had_i8_row(gated, n, g, q, rowoff(q, r, n), laststride(q))); } return RAD_OK; } /* ------------------------------------------------------------------ dequant */ -/* q * scale, with the scale stream's own extent deciding how many groups there are. The inverse of - * quant_act_i8 and NOT of the rotated forms: undoing a rotation is a second Hadamard, and an op - * that silently did one would make `dequant(had_quant(x)) == x` look true when the two have - * different meanings. A caller that wants the rotation undone asks for it. */ +/* q * scale, the scale stream's extent giving the group count. The inverse of quant_act_i8g only, + * not of the rotated forms: undoing a rotation is a separate Hadamard the caller must request. */ int ref_dequant(const RadArgs* a, RadStream) { if (!have(a, 3)) return RAD_E_INVAL; const RadTensor *q = &a->t[0], *s = &a->t[1], *y = &a->t[2]; @@ -278,7 +260,7 @@ int ref_dequant(const RadArgs* a, RadStream) { if (g <= 0) g = (n + ngrp - 1) / ngrp; if (numel(s) < rows * ngrp) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { const int64_t qb = rowoff(q, r, n), yb = rowoff(y, r, n), sb = rowoff(s, r, ngrp); const int64_t qs = laststride(q), ys = laststride(y), ss = laststride(s); @@ -293,27 +275,19 @@ int ref_dequant(const RadArgs* a, RadStream) { /* ------------------------------------------------------------------ quant_act_fp8 * - * The oracle for the block-scaled FP8 family. Without a reference for `quant_act_fp8` the one - * activation format the production checkpoints ship in is the one format rad-kbench cannot - * measure (spec §17). + * The oracle for the block-scaled FP8 family, the activation format the production checkpoints + * use (spec §17). The arithmetic is r4d_quant_act_fp8.hip's, agreeing on three choices: * - * The arithmetic is r4d_quant_act_fp8.hip's, restated rather than approximated, because the two - * have to agree on three choices that are all defensible and none of which are derivable: + * 448 E4M3's largest finite value; the scale is `amax / 448`, a dequant multiplier like + * the checkpoint's `weight_scale_inv`, so the GEMM multiplies the two scales. + * scale 1 for an all-zero group (amax / 448 would have an infinite reciprocal): the GEMM + * multiplies the two block scales, and a zero would erase the weight's. + * the clamp `amax * (1/scale)` is 448 exactly but can round an ulp above once the reciprocal is + * rounded, which would encode as NaN. * - * 448 E4M3's largest finite value, and the scale is `amax / 448` -- a DEQUANT multiplier, - * the same sense as the checkpoint's `weight_scale_inv`, so the GEMM's fold - * multiplies the two scales together and nothing has to be inverted. - * scale 1 for an all-zero group, where `amax / 448` is zero and its reciprocal infinite. NOT - * the zero scale ref_quant_act_i8 uses: that kernel's consumers read a per-row int8 - * scale and a zero row is a zero row, while here the GEMM multiplies the two block - * scales and a zero would erase the weight's. - * the clamp is not defensive. `amax * (1/scale)` is 448 in exact arithmetic and can land an ulp - * above it once the reciprocal is rounded, which encodes as a NaN rather than as the - * largest finite. - * - * `M` and `n` are the ROW COUNT and the ROW WIDTH, and rows are dim 0 -- so a rank-3 activation - * ([tokens, heads, width], which is what a GDN block hands its out-projection) is one row per - * token, not one per head. That is the reading the consuming GEMM forces: `n` is its K. + * `M` and `n` are the row count and width with rows along dim 0, so a rank-3 activation + * ([tokens, heads, width], a GDN block's out-projection input) is one row per token: `n` is the + * consuming GEMM's K. */ int ref_quant_act_fp8(const RadArgs* a, RadStream) { if (!have(a, 3)) return RAD_E_INVAL; @@ -328,25 +302,14 @@ int ref_quant_act_fp8(const RadArgs* a, RadStream) { const int64_t ngrp = (n + g - 1) / g; if (numel(s) < rows * ngrp) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { const int64_t xb = rowoff(x, r, n), qb = rowoff(q, r, n); const int64_t xs = laststride(x), qs = laststride(q); for (int64_t gi = 0; gi < ngrp; ++gi) { const int64_t k0 = gi * g, k1 = (k0 + g < n) ? k0 + g : n; - float amax = 0.0f; - for (int64_t i = k0; i < k1; ++i) { - const float m = std::fabs(ldt(x, xb + i * xs)); - if (m > amax) amax = m; - } - const float sc = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f; - const float inv = 1.0f / sc; - for (int64_t i = k0; i < k1; ++i) { - float v = ldt(x, xb + i * xs) * inv; - if (v > 448.0f) v = 448.0f; - if (v < -448.0f) v = -448.0f; - st_dt(q->dtype, q->data, qb + i * qs, v); - } + const float sc = q8_group([&](int64_t i) { return ldt(x, xb + (k0 + i) * xs); }, + k1 - k0, 448.0f, q, qb + k0 * qs, qs); stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc); } } @@ -354,27 +317,23 @@ int ref_quant_act_fp8(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------- had_quant_act_fp8 */ -/* The same quantiser with a `group`-wide Hadamard in front of the absmax, which is the only place - * a rotation can go: the whole benefit is that the maximum the grid is scaled by gets smaller. +/* The same quantiser with a `group`-wide Hadamard before the absmax, which lowers the maximum the + * grid is scaled by. * - * THE sqrt(g) IS NOT UNDONE HERE, and that is a DELIBERATE difference from ref_had_quant_act_i8 - * above, which folds 1/sqrt(g) into its own scale. H is symmetric, so - * = g , and the residual g has to be divided out exactly once between the two - * sides. The int8 op splits it; this one gives the WHOLE factor to the weight, where dividing a - * bf16 scale by a power of two is an exponent shift and therefore exact. Splitting it would make - * the stored weight scale bf16(amax/7/sqrt(g)) instead of bf16(amax/7)/g -- and the codes were - * chosen against amax/7, so that rounding lands as a ~0.2% multiplicative error on every group, - * which is a fifth of the int4 grid's own error bought for nothing. + * Unlike ref_had_quant_act_i8, the sqrt(g) is not undone here. H is symmetric, so + * = g , and g must be divided out once between the two sides. This op gives the + * whole factor to the weight, where dividing a bf16 scale by a power of two is exact. Splitting it + * would store bf16(amax/7/sqrt(g)) instead of bf16(amax/7)/g against codes chosen for amax/7, a + * ~0.2% error per group (a fifth of the int4 grid's own error). * - * So this op's output is NOT interchangeable with quant_act_fp8's, and its consumer is not free - * either: only a weight plane stored as w4a8h carries the matching rotation and the matching /g. */ + * The output is not interchangeable with quant_act_fp8's: only a weight plane stored as w4a8h + * carries the matching rotation and /g. */ int ref_had_quant_act_fp8(const RadArgs* a, RadStream) { if (!have(a, 3)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *q = &a->t[1], *s = &a->t[2]; const int64_t n = p_int(a, "n", 0); const int64_t g = p_int(a, "group", 0); - /* n % g != 0 is refused rather than rounded: a rotation block that straddled the end of the - * row would mix real values with padding, and no weight block was rotated that way. */ + /* n % g != 0 is refused: no weight block was rotated across the row's end. */ if (n <= 0 || !pow2(g) || n % g != 0) return RAD_E_SHAPE; if (g > REF_HAD_MAX) return RAD_E_UNSUPPORTED; const int64_t rows = numel(x) / n; @@ -382,7 +341,7 @@ int ref_had_quant_act_fp8(const RadArgs* a, RadStream) { if (rows <= 0 || numel(q) < rows * n) return RAD_E_SHAPE; if (numel(s) < rows * ngrp) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * n * 8) for (int64_t r = 0; r < rows; ++r) { float buf[REF_HAD_MAX]; const int64_t xb = rowoff(x, r, n), qb = rowoff(q, r, n); @@ -391,19 +350,8 @@ int ref_had_quant_act_fp8(const RadArgs* a, RadStream) { const int64_t k0 = gi * g; for (int64_t i = 0; i < g; ++i) buf[i] = ldt(x, xb + (k0 + i) * xs); fwht(buf, g); - float amax = 0.0f; - for (int64_t i = 0; i < g; ++i) { - const float m = std::fabs(buf[i]); - if (m > amax) amax = m; - } - const float sc = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f; - const float inv = 1.0f / sc; - for (int64_t i = 0; i < g; ++i) { - float v = buf[i] * inv; - if (v > 448.0f) v = 448.0f; - if (v < -448.0f) v = -448.0f; - st_dt(q->dtype, q->data, qb + (k0 + i) * qs, v); - } + const float sc = q8_group([&](int64_t i) { return buf[i]; }, g, 448.0f, q, + qb + k0 * qs, qs); stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc); } } @@ -411,20 +359,19 @@ int ref_had_quant_act_fp8(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------- givens_rotate */ -/* ParoQuant's activation side: every row scaled by its channel factors and rotated by `stages` rounds of - * disjoint Givens pairs, written in y's dtype. A weight stored as v = w . D . G_1 ... G_S - * (abi/rad_encoding.h, "givens") meets the activation x . D^-1 . G_1 ... G_S, because - * = and each G is orthogonal. For a weight whose GEMM reads a 16-bit - * activation (w5a16); the quantising form is givens_dense_quant, over the composed matrices. +/* ParoQuant's activation side: each row divided by its channel factors and rotated by `stages` + * rounds of disjoint Givens pairs, written in y's dtype. A weight stored as v = w . D . G_1 ... G_S + * (abi/rad_encoding.h, "givens") meets x . D^-1 . G_1 ... G_S, since each G is orthogonal and so + * = . For GEMMs reading a 16-bit activation (w5a16); the quantising + * form is givens_dense_quant. * - * PARTS. A fused projection (gate|up, q|k|v) was rotated per piece, so a row has `parts` rotated - * copies, written side by side: y is [rows, parts * n], part p at columns [p*n, (p+1)*n). The tables - * stack the parts: pairs and angle `stages` rows each, scale one row, per part. A part's pairs address - * columns of the row and stay inside one group of `group` (the checkpoint's are within groups of 128). + * Parts: a fused projection (gate|up, q|k|v) was rotated per piece, so y is [rows, parts * n] with + * part p at columns [p*n, (p+1)*n). The tables stack per part: `stages` rows of pairs and angles, + * one row of scales. A part's pairs stay within one `group` (128 in the checkpoints). * - * The arithmetic is the device kernel's, restated: the divide by the channel scale, then for each - * stage a' = a cos t + b sin t, b' = b cos t - a sin t in f32. Not bit-identical to the device on the - * angle: cos and sin of an f32 differ by an ulp between libm and the GPU's. */ + * The device kernel's arithmetic: divide by the channel scale, then per stage + * a' = a cos t + b sin t, b' = b cos t - a sin t in f32. Not bit-identical: libm's and the GPU's + * cos and sin differ by an ulp. */ int ref_givens_rotate(const RadArgs* a, RadStream) { if (!have(a, 5)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *pr = &a->t[1], *an = &a->t[2], *sc = &a->t[3], *q = &a->t[4]; @@ -442,7 +389,7 @@ int ref_givens_rotate(const RadArgs* a, RadStream) { if (c < 0 || c >= n) return RAD_E_INVAL; } - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * P * n * S) for (int64_t r = 0; r < rows; ++r) { std::vector buf((size_t)n); const int64_t xb = rowoff(x, r, n), qb = rowoff(q, r, P * n); @@ -454,7 +401,7 @@ int ref_givens_rotate(const RadArgs* a, RadStream) { for (int64_t j = 0; j < n / 2; ++j) { const int64_t ia = ld_int(pr->dtype, pr->data, t0 + 2 * j); const int64_t ib = ld_int(pr->dtype, pr->data, t0 + 2 * j + 1); - const float th = ldt(an, a0 + j), c = std::cos(th), sn = std::sin(th); + const float th = ldt(an, a0 + j), c = ref_cos(th), sn = ref_sin(th); const float va = buf[(size_t)ia], vb = buf[(size_t)ib]; buf[(size_t)ia] = va * c + vb * sn; buf[(size_t)ib] = vb * c - va * sn; @@ -466,9 +413,9 @@ int ref_givens_rotate(const RadArgs* a, RadStream) { return RAD_OK; } -/* ParoQuant's activation quantiser: the rotation applied as the dense matrix, y[j] = sum_i T[j][i] * x[i] / D[i] over - * each (part, 128-column group), then the quantiser `q`'s dtype names. T is the weight, f16, one [128, 128] - * matrix a (part, group) -- what rad-convert composes from the givens tables and stores as "t.dense". */ +/* ParoQuant's activation quantiser: the rotation as a dense matrix, y[j] = sum_i T[j][i] * x[i] / D[i] + * per (part, 128-column group), then the quantiser named by `q`'s dtype. T is an f16 weight, one + * [128, 128] matrix per (part, group), composed by rad-convert from the givens tables ("t.dense"). */ int ref_givens_dense_quant(const RadArgs* a, RadStream) { if (!have(a, 5)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *tm = &a->t[1], *sc = &a->t[2], *q = &a->t[3], *s = &a->t[4]; @@ -481,7 +428,7 @@ int ref_givens_dense_quant(const RadArgs* a, RadStream) { if (rows <= 0 || numel(tm) < P * n * g || numel(sc) < P * n || numel(q) < rows * P * n || numel(s) < rows * P * ngrp) return RAD_E_SHAPE; const float qmax = i8 ? 127.0f : 448.0f; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * P * n * g) for (int64_t r = 0; r < rows; ++r) { const int64_t xb = rowoff(x, r, n), qb = rowoff(q, r, P * n); const int64_t xs = laststride(x), qs = laststride(q); @@ -516,22 +463,17 @@ int ref_givens_dense_quant(const RadArgs* a, RadStream) { /* ---------------------------------------------------------------- the Gram accumulator * - * h[k1][k2] += sum over rows of x[m][k1] * x[m][k2], where x is the DEQUANTISED E4M3 input, or - * a bf16 input as it stands when no scale is passed -- the second moment GPTQ's error feedback - * needs, over exactly the operand the expert GEMM contracts. libr4d's kernel is the device half; - * this is the oracle for it. + * h[k1][k2] += sum over rows of x[m][k1] * x[m][k2], x being the dequantised E4M3 input (or a bf16 + * input as is when no scale is passed): the second moment GPTQ needs, over exactly the operand the + * expert GEMM contracts. Oracle for libr4d's device kernel. * - * THE ACCUMULATOR IS READ AS WELL AS WRITTEN, which is the one thing a reader coming from every - * other op in this file has to hold: `h` is INOUT, the caller zeroes it once, and each call adds - * its own block. An oracle that stored instead of added would agree with the kernel on a single - * call and disagree on a corpus. + * `h` is INOUT and accumulates: the caller zeroes it once and each call adds its block. * - * Rows are dequantised once into a scratch plane rather than inside the k2 loop: the triple loop - * is O(n^2 * rows) and a per-element dtype dispatch inside it is the difference between an oracle - * that finishes and one that does not. The accumulation is f64 here and f32 on the device on - * purpose -- an oracle should be tighter than the thing it checks, not bit-identical to it. */ + * Rows are dequantised once into a scratch plane, keeping the dtype dispatch out of the + * O(n^2 * rows) loop. Accumulation is deliberately f64 here (f32 on the device): this oracle is + * meant to be tighter than the kernel, not bit-identical. */ int ref_gram_accum(const RadArgs* a, RadStream) { - /* `a_scale` is optional: absent, `a` is read as it stands, which is the bf16 form. */ + /* `a_scale` is optional; absent, `a` is read as is (the bf16 form). */ if (a->n_t < 3) return RAD_E_INVAL; const RadTensor *x = t_in(a, 0), *s = t_in(a, 1), *h = t_in(a, 2); if (!x || !h) return RAD_E_INVAL; @@ -544,7 +486,7 @@ int ref_gram_accum(const RadArgs* a, RadStream) { if (h->rank != 2 || h->shape[0] != n || h->shape[1] != n) return RAD_E_SHAPE; std::vector xs((size_t)rows * (size_t)n); - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { const int64_t xb = rowoff(x, r, n), xst = laststride(x); const int64_t sb = s ? rowoff(s, r, ngrp) : 0, sst = s ? laststride(s) : 0; @@ -554,7 +496,7 @@ int ref_gram_accum(const RadArgs* a, RadStream) { } const int64_t hst = laststride(h); - #pragma omp parallel for schedule(static) + REF_PAR_FOR(n * n * rows) for (int64_t k1 = 0; k1 < n; ++k1) { const int64_t hb = rowoff(h, k1, n); for (int64_t k2 = 0; k2 < n; ++k2) { @@ -571,42 +513,29 @@ int ref_gram_accum(const RadArgs* a, RadStream) { /* ======================================================================== the fp8 fusions * - * THREE OPS THAT EXIST SO THAT A HOST RUN IS POSSIBLE AT ALL. libr4d fuses the fp8 activation - * quantiser into whichever kernel already has the row in registers, and declares the fused form as - * its own op. Without a host kernel for those names, a host-backend run -- the only thing that - * can answer "is the GRAPH right", because the per-op oracle reads the same graph both sides -- - * cannot start on an fp8 model ("site 'host' is unavailable for this band"). + * libr4d fuses the fp8 activation quantiser into whichever kernel already has the row in + * registers and declares the fused form as its own op. These host kernels for those names let a + * host-backend run start on an fp8 model; that run is the only check of the graph itself, since the + * per-op oracle reads the same graph on both sides. * - * These are the unfused arithmetic written out in one pass, which is what a reference is for. They - * are NOT required to be bit-identical to libr4d's kernels the way those kernels are required to be - * bit-identical to the pair they replace: the oracle compares within a tolerance, and a reference - * that chased the device's rounding would stop being a statement of what the op MEANS. - * - * WHAT THEY DO FOLLOW is the bf16 round-trip, because that is meaning and not rounding. The unfused - * pair writes a bf16 intermediate and the quantiser reads those bytes back, so the codes are taken - * over a bf16-narrowed value; a reference that quantised the f32 would be a different function, and - * `out_bf16` -- which the caller may ask for precisely so the fused and unfused forms leave the same - * buffers behind -- would not hold the value the codes were taken over. + * Each is the unfused arithmetic in one pass. They need not be bit-identical to libr4d's kernels; + * the oracle compares within a tolerance. They do follow the bf16 round-trip, which changes the + * function: the unfused pair writes a bf16 intermediate and quantises those bytes, so codes are + * taken over the narrowed value and `out_bf16` holds exactly the value the codes came from. */ -/* One group-scaled fp8 row, from values already in `v`. The scale layout is quant_act_fp8's and - * the reason for each constant is written there. */ +/* One group-scaled fp8 row from the values in `v`; constants and scale layout as quant_act_fp8. + * An int8 `q` (an int8 linear's input, ActFP8::q8_fed) takes quant_act_i8g's codes instead, scale + * amax / 127, as libr4d's fused quantisers write them. */ static inline void fp8_row(const float* v, int64_t n, int64_t g, const RadTensor* q, const RadTensor* s, int64_t r) { const int64_t ngrp = (n + g - 1) / g; const int64_t qb = rowoff(q, r, n), qs = laststride(q); + const float top = q->dtype == RAD_I8 ? 127.0f : 448.0f; for (int64_t gi = 0; gi < ngrp; ++gi) { const int64_t k0 = gi * g, k1 = (k0 + g < n) ? k0 + g : n; - float amax = 0.0f; - for (int64_t i = k0; i < k1; ++i) { const float m = std::fabs(v[i]); if (m > amax) amax = m; } - const float sc = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f; - const float inv = 1.0f / sc; - for (int64_t i = k0; i < k1; ++i) { - float c = v[i] * inv; - if (c > 448.0f) c = 448.0f; - if (c < -448.0f) c = -448.0f; - st_dt(q->dtype, q->data, qb + i * qs, c); - } + const float sc = q8_group([&](int64_t i) { return v[k0 + i]; }, k1 - k0, top, q, + qb + k0 * qs, qs); stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc); } } @@ -614,11 +543,10 @@ static inline void fp8_row(const float* v, int64_t n, int64_t g, const RadTensor /* ------------------------------------------------------------- rmsnorm_quant_fp8 */ /* `x`, `residual`:inout?, `w`w -> `q`, `scale`, `out_bf16`? * - * residual present is the fused_add_rms_norm form, and the add is STORED BEFORE THE VARIANCE READS - * IT -- the sum the norm is taken over is the bf16-narrowed one, not the f32 one. libr4d's kernel - * makes the same choice and says at length why: the pair it replaces writes a bf16 residual and - * reads those bytes back, and half a ULP per channel is the difference between the same text and - * very nearly the same text. `wadd` is added to every gain in f32 for the reason ref_rmsnorm gives. + * With `residual` it is the fused_add_rms_norm form, and the sum is stored before the variance + * reads it, so the norm is over the bf16-narrowed sum (as libr4d's kernel and the unfused pair do). + * Unlike ref_rmsnorm_add, the variance also uses the narrowed sum. `wadd` is added to each gain in + * f32, as in ref_rmsnorm. */ int ref_rmsnorm_quant_fp8(const RadArgs* a, RadStream) { if (a->n_t < 5) return RAD_E_INVAL; @@ -639,7 +567,7 @@ int ref_rmsnorm_quant_fp8(const RadArgs* a, RadStream) { if (res && numel(res) < rows * n) return RAD_E_SHAPE; if (ob && numel(ob) < rows * n) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { std::vector v((size_t)n); const int64_t xb = rowoff(x, r, n), xs = laststride(x), ws = laststride(w); @@ -654,8 +582,7 @@ int ref_rmsnorm_quant_fp8(const RadArgs* a, RadStream) { for (int64_t i = 0; i < n; ++i) { const float t = src(i); ss += t * t; } const float rs = 1.0f / std::sqrt(ss / (float)n + eps); - /* NARROWED TO BF16 AND THEN QUANTISED, and written out where asked. The codes belong to - * the value `out_bf16` holds; taking them over the f32 would make the two disagree. */ + /* Narrow to bf16, write `out_bf16` if asked, then quantise those values. */ const int64_t obb = ob ? rowoff(ob, r, n) : 0; const int64_t obs = ob ? laststride(ob) : 1; for (int64_t i = 0; i < n; ++i) { @@ -671,9 +598,8 @@ int ref_rmsnorm_quant_fp8(const RadArgs* a, RadStream) { /* ------------------------------------------------------------- gated_quant_fp8 */ /* `gate_up` -> `q`, `scale`, `out_bf16`? * - * The packed form only: `gate_up` is [M, 2n], gate first. `act` picks silu(gate)*up (down_proj's - * input) from sigmoid(gate)*up (a gated attention o_proj's), the same two ref_gated_had_quant_i8 - * takes and under the same two names. */ + * Packed form only: `gate_up` is [M, 2n], gate first. `act` picks silu(gate)*up (down_proj's input) + * or sigmoid(gate)*up (a gated-attention o_proj's), as in ref_gated_had_quant_i8. */ int ref_gated_quant_fp8(const RadArgs* a, RadStream) { if (!have(a, 3)) return RAD_E_INVAL; const RadTensor *gu = &a->t[0], *q = &a->t[1], *s = &a->t[2]; @@ -690,7 +616,7 @@ int ref_gated_quant_fp8(const RadArgs* a, RadStream) { if (rows <= 0 || numel(q) < rows * n || numel(s) < rows * ngrp) return RAD_E_SHAPE; if (ob && numel(ob) < rows * n) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { std::vector v((size_t)n); const int64_t gb = rowoff(gu, r, 2 * n), gs = laststride(gu); @@ -699,7 +625,7 @@ int ref_gated_quant_fp8(const RadArgs* a, RadStream) { for (int64_t i = 0; i < n; ++i) { const float gt = ldt(gu, gb + i * gs); const float up = ldt(gu, gb + (n + i) * gs); - const float sg = 1.0f / (1.0f + std::exp(-gt)); + const float sg = act_sigmoid(gt); const uint16_t h = f32_to_bf16((act == 0 ? gt * sg : sg) * up); if (ob) stt(ob, obb + i * obs, bf16_to_f32(h)); v[(size_t)i] = bf16_to_f32(h); @@ -712,32 +638,21 @@ int ref_gated_quant_fp8(const RadArgs* a, RadStream) { /* ------------------------------------------------------------- gemm_nt_q_gated */ /* `a`, `a_scale`, `b`w, `b_scale`w -> `q`, `scale`, `out_bf16`? * - * gemm_nt_q over a [N, K] gate_up plane -- N is the WEIGHT's rows, twice the fused width, gate half - * first -- with gated_quant_fp8's pass in the epilogue, so the [M, N] bf16 tensor between them is - * never written. `act` is REQUIRED here and optional on the quantiser, for the reason docs/OPS.md - * gives: an implementation is free to compile one gate, and an optional parameter would let it - * resolve for another. + * gemm_nt_q over an [N, K] gate_up plane (N the weight's rows, twice the fused width, gate half + * first) with gated_quant_fp8 in the epilogue, so the [M, N] bf16 intermediate is never written. + * `act` is required here, unlike on the quantiser (docs/OPS.md): an implementation may compile one + * gate, and an optional parameter would let it resolve for the other. * - * BYTE-IDENTICAL TO THE PAIR IT REPLACES, which is a requirement and not a hope -- the libr4d row - * that serves this op makes the same claim, and a fold that is a slightly different function from - * gemm_nt_q followed by gated_quant_fp8 is a different model. Two things earn it here: the product - * comes from `quant_dot`, which is also what gemm_nt_q's plane comes from and is the one place the - * grouping and the scale order are written down; and both halves are narrowed to bf16 BEFORE the - * gate, because the unfused form writes a bf16 [M, N] tensor and gated_quant_fp8 reads those bytes - * back. Taking either half off the f32 accumulator is a different function. ref_test holds both. + * Byte-identical to gemm_nt_q followed by gated_quant_fp8 (ref_test checks it): the product comes + * from `quant_dot` as gemm_nt_q's does, and both halves are narrowed to bf16 before the gate, as the + * unfused pair writes and re-reads a bf16 [M, N] tensor. * - * A NOTE FOR ANYONE COMPARING THIS AGAINST A DEVICE KERNEL ON THE ENGINE'S OWN OPERANDS. It will - * disagree, completely, and the kernel is not wrong: libr4d stores an fp8a8 weight in WMMA FRAGMENT - * ORDER (r4d.fp8.w.frag64), the same bytes in a different arrangement, and libref reads [N, K] - * row-major. Two readings of one permuted plane are uncorrelated tensors, which shows up as a - * relative error around 1.35 on every operand from element zero. The per-op oracle inverts the - * layout through the row's own RadUnrelayoutFn, back to the encoding's canonical planes, before it - * compares, and says so when a row publishes no inverse; a comparison that skips that step is - * measuring the permutation. + * Comparing against a device kernel on the engine's own operands needs the layout inverted first: + * libr4d stores fp8a8 weights in WMMA fragment order (r4d.fp8.w.frag64) while libref reads [N, K] + * row-major, and the two readings are uncorrelated (relative error around 1.35). The per-op oracle + * applies the row's RadUnrelayoutFn before comparing and says so when a row has none. * - * The product is formed a row at a time rather than all at once. A reference may be slow and may - * not be surprising about memory: [M, N] at a prefill M is hundreds of megabytes for a value the - * op exists to avoid materialising. */ + * The product is formed one row at a time; [M, N] at a prefill M would be hundreds of MB. */ int ref_gemm_nt_q_gated(const RadArgs* a, RadStream) { if (a->n_t < 6) return RAD_E_INVAL; const RadTensor *A = &a->t[0], *B = &a->t[2], *q = &a->t[4], *s = &a->t[5]; @@ -764,19 +679,19 @@ int ref_gemm_nt_q_gated(const RadArgs* a, RadStream) { const bool mx = B->dtype == RAD_FP4E2M1; const Scales SA = make_scales(as_, M, K, false); const Scales SB = make_scales(bs_, N, K, mx); - const Mat ma = as_mat(A, M, K), mb = as_mat(B, N, K); + const Mat ma = as_mat(A, K), mb = as_mat(B, K); - #pragma omp parallel for schedule(static) + REF_PAR_FOR(M * N * K) for (int64_t m = 0; m < M; ++m) { std::vector row((size_t)N), v((size_t)n); for (int64_t j = 0; j < N; ++j) row[(size_t)j] = quant_dot(ma, mb, SA, SB, m, j, K); const int64_t obb = ob ? rowoff(ob, m, n) : 0; const int64_t obs = ob ? laststride(ob) : 1; - /* Both halves narrowed to bf16 before the gate; the header says why. */ + /* Both halves narrowed to bf16 before the gate (see above). */ for (int64_t i = 0; i < n; ++i) { - const float gt = bf16_to_f32(f32_to_bf16(row[(size_t)i])); - const float up = bf16_to_f32(f32_to_bf16(row[(size_t)(n + i)])); - const float sg = 1.0f / (1.0f + std::exp(-gt)); + const float gt = round_dt(RAD_BF16, row[(size_t)i]); + const float up = round_dt(RAD_BF16, row[(size_t)(n + i)]); + const float sg = act_sigmoid(gt); const uint16_t h = f32_to_bf16((act == 0 ? gt * sg : sg) * up); if (ob) stt(ob, obb + i * obs, bf16_to_f32(h)); v[(size_t)i] = bf16_to_f32(h); @@ -790,19 +705,19 @@ int ref_gemm_nt_q_gated(const RadArgs* a, RadStream) { /* `cand`, `unary`, `hp`?, `anchor`, `pred`w, `succ`w -> `tokens` * * DFlash2's greedy walk over the candidate lattice. A block-diffusion drafter proposes every - * position of a block in ONE backbone pass, so it cannot condition position l+1 on what it chose at - * l; this puts that dependence back. + * position of a block in one backbone pass, so it cannot condition position l+1 on its choice at + * l; this restores that dependence. * * score[l, c] = unary[l, c] + sum_r pred[pid(l)][r] * hp[l][r] * succ[cand[l, c]][r] * pid(0) = anchor[s * anchor_stride] the token the target just committed * pid(l) = cand[l - 1, chosen(l - 1)] the walk's own previous pick * - * `hp` ABSENT IS A PLANE OF ONES, which drops the trilinear form to a plain low-rank bigram and is - * DSpark's Markov head rather than a degenerate case. + * `hp` absent is a plane of ones, reducing the trilinear form to a low-rank bigram (DSpark's Markov + * head). * - * THE WALK IS SERIAL IN l, which is why it is an op and not a GEMM and an argmax: scoring the full - * [steps, K, K] edge tensor computes K times the edges that are ever read, because the predecessor - * is not known until the previous step has been decided. The parallelism here is over sequences. */ + * The walk is serial in l, so it is an op rather than a GEMM plus argmax: scoring the full + * [steps, K, K] edge tensor computes K times the edges ever read, since each predecessor is known + * only after the previous step. Parallel over sequences. */ int ref_dflash_select(const RadArgs* a, RadStream) { if (a->n_t < 7) return RAD_E_INVAL; const RadTensor *cand = &a->t[0], *un = &a->t[1], *anc = &a->t[3]; @@ -813,7 +728,7 @@ int ref_dflash_select(const RadArgs* a, RadStream) { const int64_t steps = p_int(a, "steps", 0); const int64_t K = p_int(a, "top_k", 0); - /* `cand` is [M * steps, K] and it is the call; `M` is the band. See ref_common.h. */ + /* Rows come from `cand` [M * steps, K]; `M` is the band (see band_rows in ref_common.h). */ const int64_t M = steps > 0 && K > 0 ? band_rows(numel(cand) / (steps * K), p_int(a, "M", 0)) : 0; const int64_t R = p_int(a, "rank", pred->rank >= 2 ? pred->shape[pred->rank - 1] : 0); @@ -829,7 +744,7 @@ int ref_dflash_select(const RadArgs* a, RadStream) { const int64_t ps = laststride(pred), sxs = laststride(succ); const int64_t hs = hp ? laststride(hp) : 1; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(M * steps * K * R) for (int64_t m = 0; m < M; ++m) { std::vector ax((size_t)R); int64_t pid = ld_int(anc->dtype, anc->data, offlin(anc, m * astr)); @@ -837,10 +752,8 @@ int ref_dflash_select(const RadArgs* a, RadStream) { const int64_t r = m * steps + l; const int64_t cb = rowoff(cand, r, K), ub = rowoff(un, r, K); const int64_t hb = hp ? rowoff(hp, r, R) : 0; - /* The half of the form that does not depend on the candidate, computed once and read - * K times -- which is the shape the kernel is built around too. A predecessor outside - * the vocabulary contributes nothing rather than reading past the codebook: at step 0 - * it is whatever the target committed, and a padding row's is not a token. */ + /* The candidate-independent half of the form, computed once and read K times. A + * predecessor outside the vocabulary (a padding row's anchor) contributes nothing. */ const bool ok = pid >= 0 && pid < nv; for (int64_t i = 0; i < R; ++i) ax[(size_t)i] = (ok ? ldt(pred, rowoff(pred, pid, R) + i * ps) : 0.0f) * diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index 5bbaac8c..8ea7f18f 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -1,40 +1,31 @@ -/* ref_registry.cpp -- what libref contains, in the two forms the core reads it in. +/* ref_registry.cpp -- libref's op schemas and kernel rows. * - * THE SCHEMAS COME FIRST, and they are the authoritative copy of the conventional op vocabulary. - * docs/OPS.md is their prose form (spec §17): op names are free strings and the core never learns - * one, but ref cannot implement an op it has never heard of, so an architecture plugin that stays - * inside this table is guaranteed to run somewhere and one that invents an op has no fallback and - * no oracle for it. Adding a row here plus a host implementation beside it is the whole procedure - * for adding an op; no core file changes. + * The schemas are the authoritative copy of the conventional op vocabulary; docs/OPS.md is their + * prose form (spec §17). The core never learns op names, but ref can only implement ops it knows, + * so an architecture plugin using only these ops is guaranteed a fallback and an oracle. Adding an + * op means a row here plus a host implementation; no core file changes. * - * The first plugin in hierarchy order to declare an op FIXES its schema, and ref sits last, so in - * practice a faster plugin's schema wins and ref's has to agree with it. Since arguments are - * positional, two disagreeing schemas would make the same call mean different things depending on - * which plugin won selection -- silent numerical garbage rather than a diagnosable failure (spec - * §2.3). Every operand order below is therefore the one docs/OPS.md prints, in the order it prints - * it, and the deviations are marked in the doc string of the row that deviates. + * The first plugin in hierarchy order to declare an op fixes its schema, and ref sits last, so a + * faster plugin's schema wins and ref's must agree. Arguments are positional, so disagreeing + * schemas would silently give the same call different meanings (spec §2.3). Operand orders follow + * docs/OPS.md; deviations are marked in the deviating row's doc string. * - * THE KERNEL ROWS ARE DELIBERATELY UNCONSTRAINED. libr4d's rows state their geometry twice -- prose - * and predicates -- because they are specialised and reject what they were not compiled for. These - * are the opposite: every extent is read off the operands at launch, so there is nothing to - * predicate on, and REF MUST MATCH ANYTHING because that is what "runs somewhere" means. The one - * exception is structural rather than performance-related: kv_store has to be TOLD the paged block - * size to walk the cache, so it carries `block_size >= 1`, which admits every value and refuses - * only a query that does not name it (an absent key fails a constraint -- rad_util.cpp's - * constraint_holds). attn_paged carries the same row, but there - * `block_size` is RAD_DERIVED and a constraint on a derived key is skipped during matching, so it - * decides nothing; ref reads the block size off the cache tensor instead. + * The kernel rows are deliberately unconstrained: every extent is read off the operands, and ref + * must match anything. The exception is kv_store, which must be told the paged block size and so + * carries `block_size >= 1`; that admits every value and refuses only a query that omits the key + * (an absent key fails a constraint, rad_util.cpp's constraint_holds). attn_paged carries the same + * constraint, but there `block_size` is RAD_DERIVED, so it is skipped during matching and ref reads + * the block size off the cache tensor. * - * A CONSEQUENCE WORTH NAMING: spec §7.2 has the block manager read the KV block size off the - * resolved attention kernel's constraints. libr4d answers `block_size == 16`; ref answers "any", - * which is not a number. A core that resolves attention to ref alone therefore has to pick, and - * 16 is the value the rest of the project is built around. + * spec §7.2 has the block manager read the KV block size from the resolved attention kernel's + * constraints. libr4d answers `block_size == 16`; ref answers "any", so a core resolving attention + * to ref alone must pick, and 16 is the value the project is built around. * - * Everything is domain HOST at priority 0. libref is portable host code, so host is the only - * domain it declares; a device-side reference would be a second row, not a change to this one. + * Everything is domain HOST at priority 0; a device-side reference would be a separate row. */ #include "ref_common.h" #include "ref_ops.h" +#include "ref_planes.h" /* ================================================================== parameter specs */ #define P_INT(k) { k, RAD_P_INT, RAD_REQUIRED } @@ -42,19 +33,20 @@ #define P_STR(k) { k, RAD_P_STR, RAD_REQUIRED } #define P_STRO(k) { k, RAD_P_STR, RAD_OPTIONAL } -/* Supplied by the KERNEL and not by the caller (rad_abi.h, spec §7.2). Constraints on it are - * skipped during matching and the winning row's RAD_C_EQ value is written into the resolved - * geometry afterwards. Declaring one RAD_REQUIRED makes it unselectable, because the caller cannot - * know the value until a kernel is resolved and no kernel resolves until the value is known. */ +/* Supplied by the kernel, not the caller (rad_abi.h, spec §7.2): constraints on it are skipped + * during matching and the winner's RAD_C_EQ value is written into the resolved geometry. RAD_REQUIRED + * would make it unselectable, since the caller cannot know it before resolution. */ #define P_INTD(k) { k, RAD_P_INT, RAD_DERIVED } /* The linear-state tile length. The scheduler cuts its steps on a multiple of it (rad_abi.h, * RAD_PROLE_SEQ_CHUNK); nothing else in the core reads a parameter by meaning. */ #define P_CHUNK(k) { k, RAD_P_INT, RAD_DERIVED, RAD_PROLE_SEQ_CHUNK } +/* A count the kernel is handed as a bound and never writes past its operands for (rad_abi.h, + * RAD_PROLE_CAPACITY). */ +#define P_CAP(k) { k, RAD_P_INT, RAD_REQUIRED, RAD_PROLE_CAPACITY } -/* Real-valued parameters are RAD_P_F64 (docs/OPS.md, "The four rules"). The core refuses the - * string spelling for these keys, so a "%.9g" round trip -- exact for an IEEE single, and - * unreadable in a graph dump -- cannot creep back in, and two plugins cannot drift apart over it. - * Constraints never match on a float, by design: a tolerance is not a predicate. */ +/* Real-valued parameters are RAD_P_F64 (docs/OPS.md, "The four rules"); the core refuses a string + * spelling for these keys, so plugins cannot drift apart over formatting. Constraints never match + * on a float. */ #define P_F64(k) { k, RAD_P_F64, RAD_REQUIRED } #define P_F64O(k) { k, RAD_P_F64, RAD_OPTIONAL } @@ -65,16 +57,16 @@ #define INOUT(n) { n, RAD_OPD_INOUT, 0 } #define INOUT_O(n) { n, RAD_OPD_INOUT, 1 } #define WGT(n) { n, RAD_OPD_WEIGHT, 0 } -/* A weight TABLE: the issue names a RUN of declared weights and the kernel is handed a - * device array of pointers, one per expert. See RAD_WTAB in abi/rad_runtime.h. */ +/* A weight table: the issue names a run of declared weights and the kernel gets a device array of + * pointers, one per expert (RAD_WTAB in abi/rad_runtime.h). */ #define WTAB(n) { n, RAD_OPD_WTAB, 0 } #define WGT_O(n) { n, RAD_OPD_WEIGHT, 1 } #define ARR(a) (a), (int)(sizeof(a) / sizeof((a)[0])) /* ---- elementwise and norms ---------------------------------------------------------------- */ -/* `mult` scales the normed row before its one rounding (default 1). */ -/* rmsnorm_add has no `mult`: it is the fused pair, and nothing fuses a scaled branch. */ +/* `mult` scales the normed row before its one rounding (default 1). rmsnorm_add has none: nothing + * fuses a scaled branch into the add. */ static const RadParamSpec pRmsnormAdd[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype"), P_F64O("wadd") }; static const RadParamSpec pRmsnorm[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype"), @@ -83,11 +75,9 @@ static const RadParamSpec pRmsnorm[] = { P_INT("M"), P_INT("n"), P_F64("eps"), * its multimodal embedder's pre-projection norm). */ static const RadOperandSpec oRmsnorm[] = { OPD("x"), WGT_O("w"), OUT("y") }; -/* The GATED RESIDUAL pair. `inject` and `group` are the two switches the operand list is banded - * on: `inject` 0 is the final mixer (no per-branch gate weight, no gate output) and `group` 0 is a - * read whose consumer wants bf16 rather than block-scaled fp8. Both are OPTIONAL parameters that - * DEFAULT ON, because every connection in a trunk layer wants both and the exceptions are two - * sites in the whole model. */ +/* The gated residual pair. The operand list is banded on `inject` and `group`: `inject` 0 is the + * final mixer (no per-stream gate weight or output), `group` 0 a read whose consumer wants bf16 + * instead of block-scaled fp8. Both default on; only two sites in the model turn them off. */ static const RadParamSpec pHcRead[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_INT("lowrank"), P_F64("eps"), P_STR("dtype"), P_F64O("wadd"), P_INTO("inject"), P_INTO("group"), P_INTO("rotate"), @@ -97,11 +87,9 @@ static const RadOperandSpec oHcRead[] = { OPD("h"), WGT("w"), WGT("mix_down"), W OUT_O("scale"), OUT_O("rq"), OUT_O("rscale") }; /* ---- PLE / n-gram --------------------------------------------------------------------- * - * `state` is a ROLLING WINDOW of committed ids -- RAD_KV_CONV's shape, ple_conv's contract, read - * at `num_accepted - 1` and left in the layout that contract names. Its cold value is EOS and not - * zero, because zero is a real token; see ref_ngram.cpp on why this is a state and not an input. - * `eos` is a parameter rather than an operand because the shift rule is a property of the model, - * not of the batch, and a constraint can be written against it. */ + * `state` is a rolling window of committed ids with RAD_KV_CONV's shape and ple_conv's contract, + * read at `num_accepted - 1`. Its cold value is eos, not zero (a real token); see ref_ngram.cpp. `eos` + * is a parameter, not an operand: the shift rule is a model property and can be constrained on. */ static const RadParamSpec pNgramIds[] = { P_INT("M"), P_INT("heads"), P_INT("ngram"), P_INT("eos") }; static const RadOperandSpec oNgramIds[] = { OPD("tok"), INOUT("state"), OPD("cu"), WGT("mult"), @@ -109,16 +97,15 @@ static const RadOperandSpec oNgramIds[] = { OPD("tok"), INOUT("state"), OPD("cu" OPD_O("cache_idx"), OPD_O("has_init"), OPD_O("num_accepted"), OUT("ids"), OUT_O("ahead_ids") }; -/* PLE's gate. `k` and `q` arrive UN-normed -- the op owns all three norms, because the third one - * is taken over bytes the op itself wrote and splitting it would make two definitions of it. */ +/* PLE's gate. `k` and `q` arrive un-normed; the op owns all three norms, since the third is over + * bytes the op itself wrote. */ static const RadParamSpec pPleGate[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_F64("eps"), P_STR("dtype"), P_F64O("wadd"), P_F64O("gate_eps") }; static const RadOperandSpec oPleGate[] = { OPD("k"), OPD("q"), OPD("v"), WGT("w_key"), WGT("w_query"), WGT("w_conv"), OUT("gv"), OUT("gvn") }; -/* The dilated convolution that finishes the layer. ONE op where the GDN has two, because the work - * around it is the same at prefill and at decode -- so it takes the union of the two contracts: - * `has_init` is prefill's question and `num_accepted` is decode's. */ +/* The dilated convolution that finishes the layer: one op for prefill and decode, taking both + * contracts (`has_init` for prefill, `num_accepted` for decode; see ref_ple.cpp). */ static const RadParamSpec pPleConv[] = { P_INT("M"), P_INT("n"), P_INT("width"), P_INT("dilation"), P_STR("dtype") }; static const RadOperandSpec oPleConv[] = { OPD("x"), WGT("w"), INOUT("conv_state"), OPD("cu"), @@ -133,9 +120,8 @@ static const RadOperandSpec oCausalConv[] = { OPD("x"), WGT("w"), INOUT("conv_st static const RadParamSpec pHcWrite[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_STR("dtype") }; static const RadOperandSpec oHcEnter[] = { OPD("x"), OUT("h") }; static const RadOperandSpec oHcWrite[] = { OPD("y"), OPD("inj"), INOUT("h") }; -/* The MTP head's entry, for a wide residual stream. `ngroup` is hc for a grouped norm over - * the hc sub-streams and 1 for a flat one over the whole row -- see ref_hc.cpp on why the - * checkpoint cannot say which and the acceptance rate can. */ +/* The MTP head's entry for a wide residual stream. `ngroup` is hc for a grouped norm over the + * sub-streams, 1 for a flat one over the whole row (see ref_hc.cpp). */ static const RadParamSpec pMtpEnter[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_F64("eps"), P_STR("dtype"), P_F64O("wadd"), P_INTO("ngroup"), P_STRO("fc") }; @@ -152,11 +138,10 @@ static const RadParamSpec pGridEmbed[] = { P_INT("M"), P_INT("n"), P_INT("side") static const RadOperandSpec oGridEmbed[] = { INOUT("x"), WGT("table"), OPD("coord") }; static const RadParamSpec pMnD[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; -/* `scalar` 1 says `w` is one element rather than one row: a kernel reads that off the operand, and - * the parameter is what lets a shape description say which of the two geometries it is. */ +/* `scalar` 1 says `w` is one element rather than one row; kernels read that off the operand, but a + * shape description needs the parameter. */ static const RadParamSpec pMulWeight[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_INTO("scalar") }; -/* `cap` required and not optional: a softcap without a cap is a different op, and the one model in - * scope whose graph issues it (Gemma 4) has a value for it. */ +/* `cap` is required: the one model that issues this op (Gemma 4) has a value for it. */ static const RadParamSpec pMnCap[] = { P_INT("M"), P_INT("n"), P_F64("cap"), P_STR("dtype") }; static const RadOperandSpec oBinary[] = { OPD("a"), OPD("b"), OUT("y") }; static const RadOperandSpec oGateUp[] = { OPD("gate_up"), OUT("y") }; @@ -165,32 +150,44 @@ static const RadParamSpec pActMul[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_ /* `M` is the step's token count and bands the op; the segment count is cu_seqlens' length. */ static const RadParamSpec pSegMean[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; static const RadOperandSpec oSegMean[] = { OPD("x"), OPD("cu_seqlens"), OUT("y") }; -/* `M` is the INPUT row count, a multiple of `k`; y has M / k rows. */ +/* `M` is the input row count, a multiple of `k`; y has M / k rows. */ static const RadParamSpec pPoolRows[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_F64O("mult"), P_STR("dtype") }; static const RadOperandSpec oUnary[] = { OPD("x"), OUT("y") }; /* The audio (USM conformer) tower's operators. */ static const RadOperandSpec oClamp[] = { OPD("x"), WGT("lo"), WGT("hi"), OUT("y") }; -/* `M` is the INPUT time rows. */ +/* `M` is the input time rows. */ static const RadParamSpec pConv2d[] = { P_INT("M"), P_INT("width"), P_INT("cin"), P_INT("cout"), P_INT("kh"), P_INT("kw"), P_INT("stride"), P_INT("pad"), P_INTO("cu_div"), P_INTO("valid_stride"), - P_STR("dtype") }; + P_STR("dtype"), P_INTO("t_last"), P_STRO("act") }; static const RadOperandSpec oConv2d[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OPD_O("valid"), - OUT("y") }; + OUT("y"), WGT_O("b") }; +/* `M` counts input time rows; y is [output rows * Wo, cin * kh * kw]. */ +static const RadParamSpec pConv2dUnfold[] = { P_INT("M"), P_INT("width"), P_INT("cin"), + P_INT("kh"), P_INT("kw"), P_INT("stride"), + P_INT("pad"), P_INTO("cu_div"), + P_INTO("valid_stride"), P_INTO("t_last"), + P_STR("dtype") }; +static const RadOperandSpec oConv2dUnfold[] = { OPD("x"), OPD("cu_seqlens"), OPD_O("valid"), + OUT("y") }; static const RadParamSpec pConv1dDw[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_INTO("cu_div"), P_STR("dtype") }; static const RadOperandSpec oConv1dDw[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OUT("y") }; -/* `M` is the table's rows: one a distance. */ +/* `M` is the table's rows, one per distance. */ static const RadParamSpec pRelSin[] = { P_INT("M"), P_INT("n"), P_F64O("max_timescale"), P_STR("dtype") }; static const RadOperandSpec oRelSin[] = { OUT("y") }; +/* `M` is the output rows; `period` the rows a position cycle takes. */ +static const RadParamSpec pSegSin[] = { P_INT("M"), P_INT("n"), P_INT("period"), + P_F64O("max_timescale"), P_INTO("cu_div"), P_STR("dtype") }; +static const RadOperandSpec oSegSin[] = { OPD("cu_seqlens"), OUT("y") }; static const RadParamSpec pAttnLocalRel[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"), P_INT("left"), P_INT("right"), P_F64("softcap"), P_INTO("cu_div"), P_STR("dtype") }; static const RadOperandSpec oAttnLocalRel[] = { OPD("q"), OPD("k"), OPD("v"), OPD("relk"), WGT("pds"), OPD("cu_seqlens"), OUT("out") }; -/* `fill` has no input: `value` is the whole of what it writes. */ +/* `fill` has no input; it writes `value`. */ static const RadParamSpec pFill[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_F64O("value") }; static const RadOperandSpec oFill[] = { OUT("y") }; static const RadOperandSpec oScale[] = { OPD("x"), WGT("s"), OUT("y") }; @@ -201,18 +198,15 @@ static const RadParamSpec pCast[] = { P_INT("M"), P_INT("n"), P_STR("from"), P_S /* ---- quantisation and rotation ------------------------------------------------------------ */ static const RadParamSpec pQuant[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype") }; -/* `asum` is libr4d's third output: the group-major per-row code sums an ASYMMETRIC weight grid - * subtracts to remove the stored zero point. Optional, because whether the caller wants them is a - * property of the call and not of the model. Ref does not produce them -- it has no asymmetric - * grid to feed -- and leaves the buffer alone rather than filling it with something plausible. */ +/* `asum`, quant_act_i8's optional third output: group-major per-row code sums an asymmetric + * weight grid subtracts to remove the stored zero point. */ static const RadOperandSpec oQuant[] = { OPD("x"), OUT("q"), OUT("scale"), OUT_O("asum") }; static const RadOperandSpec oHadQuant[] = { OPD("x"), OUT("q"), OUT("scale") }; -/* No `asum`: that output exists for the asymmetric integer grids and an fp8 grid is symmetric by - * construction (libr4d/r4d_rows.cpp says the same). */ +/* No `asum`: it exists for asymmetric integer grids and fp8 is symmetric (as libr4d/r4d_rows.cpp + * notes). */ static const RadOperandSpec oQuantFp8[] = { OPD("x"), OUT("q"), OUT("scale") }; -/* ParoQuant's rotation: a rotation per part, to f16 for the 16-bit GEMMs. The three - * tables are the "givens" encoding's (abi/rad_encoding.h) and are WEIGHT operands, so they are - * resolved, moved and placed with the weight they belong to. */ +/* ParoQuant's rotation, one per part, to f16 for the 16-bit GEMMs. The tables are the "givens" + * encoding's (abi/rad_encoding.h) and are weight operands, so they are placed with their weight. */ static const RadParamSpec pGivensRotate[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype"), P_INT("stages"), P_INT("parts") }; static const RadParamSpec pGivensDense[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype"), @@ -223,9 +217,8 @@ static const RadOperandSpec oGivensRotate[] = { OPD("x"), WGT("pairs"), WGT("ang OUT("y") }; /* ---- the fp8 fusions ---------------------------------------------------------------------- - * A fused op's operands are the unfused pair's minus the tensor between them, and `out_bf16` - * puts even that back: the codes are taken over its value, so a caller that wants to compare - * the fused form against the pair has to be able to ask for it. */ + * A fused op's operands are the unfused pair's minus the intermediate; optional `out_bf16` restores + * it (the codes are taken over its value) so the fused form can be compared against the pair. */ static const RadParamSpec pRmsQuantFp8[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"), P_STR("dtype"), P_F64O("wadd") }; static const RadOperandSpec oRmsQuantFp8[] = { OPD("x"), INOUT_O("residual"), WGT("w"), @@ -234,9 +227,8 @@ static const RadParamSpec pGatedQuantFp8[] = { P_INT("M"), P_INT("n"), P_INT("gr P_STR("dtype"), P_STRO("act") }; static const RadOperandSpec oGatedQuantFp8[] = { OPD("gate_up"), OUT("q"), OUT("scale"), OUT_O("out_bf16") }; -/* `act` is REQUIRED here and optional on the quantiser, for the reason docs/OPS.md gives: an - * implementation is free to compile one gate, and an optional parameter would let it resolve - * for another. `N` is the WEIGHT's rows -- twice the fused width -- so the output is [M, N/2]. */ +/* `act` is required here, unlike on the quantiser (docs/OPS.md; see ref_gemm_nt_q_gated). `N` is + * the weight's rows, twice the fused width, so the output is [M, N/2]. */ static const RadParamSpec pGemmQGated[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"), P_STR("dtype"), P_STR("act") }; static const RadOperandSpec oGemmQGated[] = { OPD("a"), OPD("a_scale"), WGT("b"), @@ -254,19 +246,15 @@ static const RadParamSpec pRmsHadQuant[] = { P_INT("M"), P_INT("n"), P_F64("eps" static const RadOperandSpec oRmsHadQuant[] = { OPD("x"), INOUT_O("residual"), WGT("w"), OUT("q"), OUT("scale"), OUT_O("out_bf16") }; -/* Two callers spell this differently: the gate and the up as two operands with a `mode`, or one - * fused `gate_up` with an `act`. Two operands with the second OPTIONAL expresses both -- a caller - * with a fused [M, 2n] buffer passes it as `a` and omits `b` -- and `mode` stays as an optional - * integer spelling of `act`, since it is a kernel plugin's name for it and not the vocabulary's. */ +/* Callers pass gate and up as two operands, or one fused [M, 2n] `gate_up` as `a` with `b` + * omitted. `mode` is libr4d's optional integer spelling of `act`. */ static const RadParamSpec pGatedQuant[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype"), P_STRO("act"), P_INTO("mode") }; static const RadOperandSpec oGatedQuant[] = { OPD("a"), OPD_O("b"), OUT("q"), OUT("scale") }; -/* `h` is INOUT and that is the op: the caller zeroes it once and drives a whole calibration - * corpus through the graph, so every launch adds its own block. `a`/`a_scale` rather than - * `x`/`scale` because they are gemm_nt_q's first two operands in gemm_nt_q's order -- this op - * exists to characterise exactly the operand that GEMM contracts. */ -/* `a_scale` is optional: dtype "bf16" is a plain activation and carries none. */ +/* `h` is INOUT: the caller zeroes it once and each launch over the calibration corpus adds its + * block. `a`/`a_scale` are gemm_nt_q's first two operands, the activation this op characterises; + * `a_scale` is absent for a plain bf16 activation. */ static const RadOperandSpec oGram[] = { OPD("a"), OPD_O("a_scale"), INOUT("h") }; static const RadParamSpec pDequant[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype") }; @@ -275,9 +263,8 @@ static const RadOperandSpec oDequant[] = { OPD("q"), OPD("scale"), OUT("y") }; /* ---- gemm --------------------------------------------------------------------------------- */ static const RadParamSpec pGemm[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_STR("dtype") }; static const RadOperandSpec oGemm[] = { OPD("a"), WGT("b"), OUT("y") }; -/* The bias form carries a linear layer's usual epilogue: an activation of the biased product and a - * residual added after it -- each step rounded to the output's dtype, as three separate tensors - * would be. Both optional; absent they are the plain biased GEMM. */ +/* The bias form carries an optional epilogue: an activation of the biased product, then a residual + * add, each rounded to the output dtype as separate tensors would be. */ static const RadParamSpec pGemmBias[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_STR("dtype"), P_STRO("act") }; static const RadOperandSpec oGemmBias[] = { OPD("a"), WGT("b"), WGT("bias"), OPD_O("res"), @@ -285,14 +272,14 @@ static const RadOperandSpec oGemmBias[] = { OPD("a"), WGT("b"), WGT("bias"), OPD static const RadParamSpec pGemmQ[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"), P_STR("dtype"), P_INTO("pb1"), P_INTO("pb2") }; -/* The bias form has no parts: a fused projection rotated apart is the plain product's. */ +/* The bias form has no parts (`pb1`/`pb2`); only the plain product supports them. */ static const RadParamSpec pGemmQBias[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"), P_STR("dtype") }; -/* `a_sum` and `b_ref` are libr4d's, appended AFTER `y` so docs/OPS.md's list stays a positional - * prefix: the asymmetric 4-bit and 2-bit grids subtract the activation's per-group code sums, and - * mxfp4 folds a per-output-row reference exponent. Neither is expressible as a weight aux stream, - * because RadLayout can declare one and RadArgs has no way to deliver it. Ref implements no grid - * that needs either, so it ignores both -- which is what an optional operand means. */ +/* `a_sum` and `b_ref` are libr4d's, appended after `y` so docs/OPS.md's list stays a positional + * prefix: asymmetric 4- and 2-bit grids subtract the activation's per-group code sums, and mxfp4 + * folds a per-output-row reference exponent. Neither fits a weight aux stream (RadLayout can + * declare one but RadArgs cannot deliver it). Ref reads no zero point, so it refuses `a_sum`; + * `b_ref` is derived from `b_scale`, so ref accepts it beside an e2m1 weight and ignores it. */ static const RadOperandSpec oGemmQ[] = { OPD("a"), OPD_O("a_scale"), WGT("b"), WGT("b_scale"), OUT("y"), OPD_O("a_sum"), WGT_O("b_ref") }; static const RadOperandSpec oGemmQBias[] = { OPD("a"), OPD("a_scale"), WGT("b"), WGT("b_scale"), @@ -302,35 +289,29 @@ static const RadOperandSpec oGemmQBias[] = { OPD("a"), OPD("a_scale"), WGT("b"), static const RadParamSpec pAttnPaged[] = { P_INT("q_len"), P_INT("head_dim"), P_INT("gqa"), P_INTD("block_size"), P_INT("causal"), P_INT("window"), P_STR("q_dtype"), P_STR("kv_dtype"), P_F64O("scale"), P_INTO("max_ctx"), - /* Three the SCRATCH HOOK needs at declare, when an op has parameters and no tensors: libr4d's - * split-KV partial buffer is num_seqs * q_len * q_heads * splits rows, and gqa gives the head - * ratio rather than the count. Ref sizes no scratch and ignores all three; they are in its - * schema because the two plugins must agree on this op's parameter list. */ + /* For libr4d's scratch hook, which sizes its split-KV partial buffer at declare + * (num_seqs * q_len * q_heads * splits rows; gqa is only the head ratio). Ref ignores them; + * they are here because both plugins must agree on the parameter list. */ P_INTO("n_head"), P_INTO("max_seqs") }; static const RadOperandSpec oAttnPaged[] = { OPD("q"), OPD("kv_cache"), OPD("block_table"), OPD("seqused"), OPD_O("k_descale"), OPD_O("v_descale"), OPD_O("cu_seqlens"), OUT("out") }; -/* kv_store's, and attn_paged's only in the sense that it is skipped there: `block_size` is - * RAD_DERIVED on attn_paged now, and a constraint on a derived key the caller did not supply does - * not take part in matching (core/plugin/select.cpp). Ref therefore answers "any" to spec §7.2's - * question of what the paged block size is, which is not a number -- a core that resolves - * attention to ref alone has to pick, and 16 is what the rest of the project is built around. On - * kv_store, where the key stays RAD_REQUIRED, the constraint still does its job: it admits every - * value and refuses only a query that does not name one. */ +/* Effective on kv_store, where `block_size` is RAD_REQUIRED: admits every value and refuses only a + * query that omits it. On attn_paged the key is RAD_DERIVED and the constraint is skipped + * (core/plugin/select.cpp). See the file header for the spec §7.2 consequence. */ static const RadConstraint cPagedBlock[] = { RAD_CGE("block_size", 1) }; static const RadParamSpec pAttnDense[] = { P_INT("M"), P_INT("head_dim"), P_INT("gqa"), P_INT("causal"), P_STR("dtype"), P_F64O("scale"), - P_INTO("max_seqlen"), P_INTO("window") }; + P_INTO("max_seqlen"), P_INTO("window"), + P_INTO("cu_div"), P_INTO("block") }; static const RadOperandSpec oAttnDense[] = { OPD("q"), OPD("k"), OPD("v"), OPD("cu_seqlens"), OUT("out") }; /* `k_scale` and `v_scale` are the descales an fp8 cache is read back with, so a store divides by - * them; they are meaningless for a bf16 cache and optional for that reason. THE SCHEMA IS SHARED - * ACROSS PLUGINS -- the loader refuses a plugin whose spelling of an op differs from the one that - * fixed it first -- so they are here even though this reference store only serves bf16. */ + * them; optional because a bf16 cache has none. */ static const RadParamSpec pKvStore[] = { 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") }; @@ -345,9 +326,9 @@ static const RadParamSpec pRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_he P_STRO("ladder") }; static const RadOperandSpec oRope[] = { INOUT("qkv"), OPD("positions") }; -/* The cos/sin plane a fused prologue reads instead of theta: written at each position's OWN row - * of a [max_ctx, rot] table. `rot`, `theta` and `scale` are `rope`'s, spelled the same way, - * because the two have to compute the same angles. */ +/* The cos/sin plane a fused prologue reads instead of theta, at each position's own row of a + * [max_ctx, rot] table. `rot`, `theta` and `scale` are spelled as on `rope`, which must compute the + * same angles. */ static const RadParamSpec pRopeTable[] = { P_INT("M"), P_INT("rot"), P_F64("theta"), P_F64("scale"), P_STR("dtype"), P_F64O("yarn_factor"), P_F64O("yarn_low"), @@ -356,7 +337,7 @@ static const RadParamSpec pRopeTable[] = { P_INT("M"), P_INT("rot"), P_F64("thet static const RadOperandSpec oRopeTable[] = { OPD("positions"), OUT("cos_sin") }; /* QSA's compressed key, libr4d's schema exactly (libr4d/r4d_rows.cpp): `block_size` is `ratio` - * spelled for the KV group the block-key store is, `page` and `pos` are optional. */ + * spelled for the block-key store's KV group; `page` and `pos` are optional. */ static const RadParamSpec pQsaBlockKey[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), P_INT("rotary_dim"), P_INTO("pos0"), P_INTO("block_size"), P_F64("eps"), P_F64("theta"), @@ -367,6 +348,34 @@ static const RadParamSpec pQsaBlockKey[] = { P_INT("M"), P_INT("n"), P_INT("rati static const RadOperandSpec oQsaBlockKey[] = { OPD("k"), WGT("w"), OPD_O("page"), OPD_O("pos"), OUT("out") }; +/* The rest of the QSA indexer, libr4d's schemas exactly (libr4d/r4d_rows.cpp). `M` counts query + * rows (score, select) or tokens (tail store, work list); `cu` maps a row to its sequence, whose + * count is cu's length less one (`seqs` is the declared height). */ +static const RadParamSpec pQsaScore[] = { P_INT("M"), P_INT("n"), P_INT("heads"), P_INT("blocks"), + P_INT("seqs"), P_STR("dtype") }; +static const RadOperandSpec oQsaScore[] = { OPD("q"), OPD("bk"), OPD("bt"), OPD("cu"), OPD("nc"), + OUT("score") }; +static const RadParamSpec pQsaSelect[] = { P_INT("M"), P_INT("blocks"), P_INT("topk"), + P_INT("ratio"), P_INT("seqs") }; +static const RadOperandSpec oQsaSelect[] = { OPD("score"), OPD("bt"), OPD("nc"), OPD("pos"), + OPD("cu"), OUT("sel"), OUT("nsel"), OUT("seqused") }; +static const RadParamSpec pQsaTailStore[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), P_INT("ring"), + P_INT("seqs"), P_STR("dtype") }; +static const RadOperandSpec oQsaTailStore[] = { OPD("k"), OPD("pos"), OPD("cu"), INOUT("state"), + OPD("sidx") }; +/* `work` bounds the blocks that can complete; slots past the real count get page -1. */ +static const RadParamSpec pQsaWork[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), P_INT("ring"), + P_INT("seqs"), P_CAP("work"), P_STR("dtype") }; +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") }; + +/* DFlash2's grouped convolution, libr4d's schema exactly. */ +static const RadParamSpec pDflashConv[] = { P_INT("T"), P_INT("hidden_size"), P_INT("taps"), + P_INT("group_size"), P_INT("NG"), P_INT("block_size"), + P_STR("dtype") }; +static const RadOperandSpec oDflashConv[] = { OPD("x"), OPD("delta"), WGT("base"), OUT("out") }; + /* `mode` "blocks" rotates each of `sections` (pair counts) as its own neox block of channels, * reading the position component `comps` names for it; positions are then [C, M]. */ static const RadParamSpec pQkNormRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"), @@ -386,42 +395,37 @@ static const RadParamSpec pRouter[] = { P_INT("M"), P_INT("n_expert"), P_INT("to P_INT("norm"), P_STR("dtype") }; static const RadOperandSpec oRouter[] = { OPD("logits"), OUT("expert_ids"), OUT("expert_w") }; -/* `expert_base` is THIS RANK'S FIRST EXPERT ID, and it is what makes expert parallelism a - * parameter rather than a second op. Absent (or 0) is the whole-model case every non-sharded - * deployment has always issued. See the schema note. */ +/* `expert_base` is this rank's first expert id, making expert parallelism a parameter rather than + * a second op; absent (0) is the unsharded case. */ static const RadParamSpec pScatter[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"), P_INTO("expert_base"), P_STRO("protect") }; static const RadOperandSpec oScatter[] = { OPD("expert_ids"), OUT("sorted_tok"), OUT("expert_offset"), OUT("expert_count") }; -/* `a_order` SAYS WHICH ROWS THE ACTIVATION HAS, and it is a parameter because the two grouped - * GEMMs of one routed block disagree about it. The gate_up projection reads the block's INPUT, - * which is one row per TOKEN, and a sorted row i must gather `a[sorted_tok[i] / top_k]`. The down - * projection reads the FIRST projection's output, which is already one row per (token, slot) in - * the scatter's order -- row i is row i, and gathering it again reads another slot's activation. +/* `a_order` says which rows the activation has; a routed block's two grouped GEMMs differ. gate_up + * reads the block input, one row per token, so sorted row i gathers `a[sorted_tok[i] / top_k]`. + * down reads gate_up's output, already one row per (token, slot) in scatter order, so row i is row + * i. * - * It has to be said rather than derived. The row count would give it away -- M against M*top_k -- - * but an operand whose meaning changes with its extent is exactly the shape a checker cannot see: - * if both implementations gather they agree with each other, and a harness that sizes the operand - * the way the gather wants never exercises the other reading. */ + * It is stated rather than derived from the row count (M vs M*top_k): an operand whose meaning + * changes with its extent is invisible to a checker, since a harness sizing it for one reading + * never exercises the other. */ static const RadParamSpec pMoeGemm[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("n_expert"), P_INT("top_k"), P_STR("a_order"), P_STR("dtype") }; static const RadOperandSpec oMoeGemm[] = { OPD("a"), WTAB("w"), OPD("sorted_tok"), OPD("expert_offset"), OUT("y") }; -/* The quantised arm, and it is a SEPARATE OP for the same reason `gemm_nt_q` is separate from - * `gemm_nt`: the operand list differs -- an activation scale stream and a weight scale plane per - * expert -- and an op whose operand count depends on a dtype string is an op whose positional - * arguments mean different things to different kernels. `group` is the block edge, 128 for every - * DeepSeek-style fp8 checkpoint. Both weight operands are tables and both carry one entry per - * expert, which is what lets the declaration split evenly across them. */ -/* THE EXPERTS ARE TWO TABLES BY PARITY -- `w`/`w_scale` the even ones at [N, K], `w_odd`/ - * `w_odd_scale` the odd ones at [N_odd, K_odd], expert e at entry e / 2 -- because a table's - * entries share one geometry and a rank holding an uneven slice of each expert's width has two. - * `parts` stacked parts run along both the weight rows and the output columns; the output is the - * wider class's width, and a narrower class fills each part's leading columns and zeros the rest. - * libr4d's schema states the same. */ +/* The quantised arm is a separate op, like gemm_nt_q, because it adds operands (an activation + * scale stream and a per-expert weight scale plane) and positional operands cannot vary with a + * dtype string. `group` is the block edge, 128 for DeepSeek-style fp8 checkpoints. Both weight + * operands are tables with one entry per expert. + * + * Experts are two tables by parity: `w`/`w_scale` the even ones at [N, K], `w_odd`/`w_odd_scale` + * the odd ones at [N_odd, K_odd], expert e at entry e / 2. A table's entries share one geometry, + * and a rank holding an uneven slice of each expert's width has two. `parts` stacked parts run + * along both weight rows and output columns; the output is the wider class's width, and a narrower + * class fills each part's leading columns and zeros the rest (as in libr4d's schema). */ static const RadParamSpec pMoeGemmQ[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("n_expert"), P_INT("top_k"), P_INT("group"), P_STR("a_order"), P_STR("dtype"), P_INTO("N_odd"), P_INTO("K_odd"), @@ -429,9 +433,9 @@ static const RadParamSpec pMoeGemmQ[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_ static const RadOperandSpec oMoeGemmQ[] = { OPD("a"), OPD_O("a_scale"), WTAB("w"), WTAB("w_scale"), OPD("sorted_tok"), OPD("expert_offset"), WTAB("w_odd"), WTAB("w_odd_scale"), OUT("y") }; -/* THE SAME OP OVER FOUR CLASSES, by the expert's number mod 4: `w`/`w_scale` class 0 at [N, K], - * `w_q`/`w_q_scale` class q at [N_q, K_q], expert e at entry e / 4 of class e % 4 -- how four - * ranks take turns with the extra block of a five-block expert. libr4d's schema states the same. */ +/* The same op over four classes by expert number mod 4: `w`/`w_scale` class 0 at [N, K], + * `w_q`/`w_q_scale` class q at [N_q, K_q], expert e at entry e / 4 of class e % 4; how four ranks + * share the extra block of a five-block expert (as in libr4d's schema). */ static const RadParamSpec pMoeGemmQMod4[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("n_expert"), P_INT("top_k"), P_INT("group"), P_STR("a_order"), P_STR("dtype"), P_INTO("N_1"), P_INTO("K_1"), @@ -443,19 +447,16 @@ static const RadOperandSpec oMoeGemmQMod4[] = { OPD("a"), OPD_O("a_scale"), WTAB WTAB("w_1_scale"), WTAB("w_2"), WTAB("w_2_scale"), WTAB("w_3"), WTAB("w_3_scale"), OUT("y") }; -/* `shared` and `shared_gate` PRESENT = the shared arm folded in, `y = bf16(shared * act(gate)) + - * bf16(gathered)`, which is scale_rows' fused gate-and-add taken one op further back. `act` is - * that op's spelling, sigmoid or none, and applies to the SCALAR. */ +/* With `shared` and `shared_gate`, the shared expert is folded in: y = bf16(shared * act(gate)) + + * bf16(gathered), scale_rows' fused gate-and-add. `act` (sigmoid or none) applies to the scalar. */ static const RadParamSpec pMoeGather[] = { P_INT("M"), P_INT("n"), P_INT("top_k"), P_STR("dtype"), P_STRO("act") }; static const RadOperandSpec oMoeGather[] = { OPD("y_expert"), OPD("expert_w"), OPD("sorted_tok"), OPD_O("shared"), OPD_O("shared_gate"), OUT("y") }; /* `vocab_off` and `pairs` are the vocab-parallel form: `x` is one rank's slice, `idx` carries - * GLOBAL columns, and `pairs` is the [M, R, 2] (int32 id, float value) plane an all_gather moves. - * Both absent is the single-rank top-R unchanged. AN OP SCHEMA IS A CONTRACT ACROSS PLUGINS -- if - * this and libr4d's disagree the loader refuses ref and the arch plugin's model stops loading with - * a message that points nowhere near the cause. */ + * global columns, and `pairs` is the [M, R, 2] (int32 id, float value) plane an all_gather moves. + * Must match libr4d's schema, or the loader refuses ref and the model fails to load. */ static const RadParamSpec pRowTopk[] = { P_INT("M"), P_INT("N"), P_INT("R"), P_INTO("vocab_off"), P_STR("dtype") }; static const RadOperandSpec oRowTopk[] = { OPD("x"), OUT("idx"), OUT("val"), OUT_O("pairs") }; @@ -473,21 +474,17 @@ static const RadOperandSpec oLogitRerank[] = { OPD("x"), WGT("head"), OPD("idx_i /* ---- gated delta net ---------------------------------------------------------------------- * - * `cu` IS AN OPERAND OF EVERY GDN OP, DECODE INCLUDED, and `num_accepted` is REQUIRED on both - * decode ops. The first is not a preference: the fast decode kernels open with - * `bos = cu[n]; T = cu[n+1] - bos` before any null test, so a schema that omits `cu` does not make - * it optional, it makes the launch fault. The second is - * spec §10: the recurrent state and the conv window have already absorbed the rejected tokens, so - * a rejection is a change of read offset, and an op that lets the caller omit `num_accepted` is an - * op whose rollback contract is optional. A non-speculative decode passes all ones. */ + * `cu` is an operand of every GDN op, decode included: the fast decode kernels read + * `bos = cu[n]; T = cu[n+1] - bos` before any null test. `num_accepted` is required on both decode + * ops (spec §10): the state has absorbed the rejected tokens, so a rejection is a change of read + * offset. A non-speculative decode passes all ones. */ static const RadParamSpec pConvPrep[] = { P_INT("M"), P_INT("head_k"), P_INT("head_v"), P_CHUNK("chunk"), P_INT("conv_width"), P_F64O("l2_eps"), P_F64O("softplus_thr") }; -/* THE INPUTS COME FIRST AND THE OUTPUTS LAST, which is what docs/OPS.md's resolved table draws. - * `a` and `b_gate` are the gate and beta projections a layer may hand over separately from `x`; - * absent, they are the last 2*head_v_count columns of the fused `x` row. `cache_idx` is the conv - * state slot per sequence -- a paged conv cache cannot be indexed by the batch's sequence number - * -- and `has_init` says whether that slot holds a history at all. */ +/* Inputs first, outputs last, as docs/OPS.md's resolved table draws. `a` and `b_gate` are separate + * gate and beta projections; absent, they are the last 2*head_v_count columns of `x`. `cache_idx` + * is the conv state slot per sequence (a paged cache is not indexed by batch position), and + * `has_init` says whether that slot holds history. */ static const RadOperandSpec oConvPrep[] = { OPD("x"), WGT("w"), WGT_O("b"), WGT("A_log"), WGT("dt_bias"), INOUT("conv_state"), OPD("cu"), OPD_O("a"), OPD_O("b_gate"), OPD_O("cache_idx"), OPD_O("has_init"), @@ -522,9 +519,8 @@ static const RadOperandSpec oRecurrent[] = { WGT_O("norm_w"), OUT("o"), OUT_O("o_q"), OUT_O("o_scale") }; -/* gdn_conv_update folded into gdn_recurrent_update: the convolution's inputs, then the recurrence's - * minus q, k and v, which are the pair's intermediate. The parameters are the union of the two - * ops' under their own names. */ +/* gdn_conv_update folded into gdn_recurrent_update: the convolution's inputs, then the + * recurrence's minus the intermediate q, k and v. Parameters are the union of both ops'. */ static const RadParamSpec pConvRecurrent[] = { P_INT("q_len"), P_INT("head_k"), P_INT("head_v"), P_INT("conv_width"), P_INTO("n_head_v"), P_F64O("scale"), P_F64O("eps"), P_F64O("l2_eps"), @@ -545,10 +541,7 @@ static const RadOperandSpec oGatedNorm[] = { OPD("x"), OPD("z"), WGT("w"), OUT(" static const RadParamSpec pAllReduce[] = { P_INT("world_size"), P_INT("numel"), P_STR("dtype"), P_INT("exact"), P_INTO("min_bytes"), P_INTO("hops"), P_INTO("overlap") }; -/* `y` is an optional SECOND operand: absent means in place, which is what docs/OPS.md draws and - * what every one-shot kernel does. libr4d's two-shot rows are not safe in place -- a rank gathers - * into the output while its own input is still being read for the scatter -- so they need the - * separate destination, and a schema without it cannot express their call at all. */ +/* `y` is optional; absent means in place. libr4d's two-shot rows need it (see ref_all_reduce). */ static const RadOperandSpec oAllReduce[] = { INOUT("x"), OUT_O("y") }; static const RadParamSpec pAllGather[] = { P_INT("world_size"), P_INT("numel"), P_STR("dtype"), @@ -556,32 +549,29 @@ static const RadParamSpec pAllGather[] = { P_INT("world_size"), P_INT("numel"), static const RadOperandSpec oAllGather[] = { OPD("x"), OUT("y") }; /* ---- vocabulary edges --------------------------------------------------------------------- */ -/* `vocab_offset` MAKES THE EMBEDDING VOCAB-PARALLEL, which is the symmetry lm_head has had all - * along. Absent (or 0 with an unsharded table) it is exactly the gather it always was. +/* `vocab_offset` makes the embedding vocab-parallel, like lm_head. Absent (or 0 with an unsharded + * table) it is the plain gather. * - * Present, `n_vocab` is THIS RANK'S row count -- the same meaning it already carries for - * logits_gemm -- and the table covers GLOBAL ids [vocab_offset, vocab_offset + n_vocab). Token ids - * stay GLOBAL, so a rank subtracts the offset and writes a ZERO ROW for an id outside its slice, - * exactly as it does for the negative padding id. Every token lands on exactly one rank, so - * summing the ranks' outputs reconstructs x -- which is why the caller follows this with an - * all_reduce and why the reduction is exact rather than approximate. + * Present, `n_vocab` is this rank's row count (as for logits_gemm) and the table covers global ids + * [vocab_offset, vocab_offset + n_vocab). Ids stay global; an id outside the slice writes a zero + * row, as the negative padding id does. Each token lands on exactly one rank, so the following + * all_reduce reconstructs x exactly. * - * The cost of NOT having it: the table is replicated on every card. 248320 x 5120 in bf16 is - * 2.43 GiB, and it is bf16 even in the fp8 checkpoint. That is KV cache. */ + * Without it the table is replicated per card: 248320 x 5120 bf16 is 2.43 GiB (bf16 even in the + * fp8 checkpoint), memory taken from the KV cache. */ static const RadParamSpec pEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_vocab"), P_STR("dtype"), P_INTO("vocab_offset"), - /* embed_lookup_q's: the scale its LAYOUT quantises with. - * A parameter because a global scale needs the whole table - * and the transform sees one block. */ + /* embed_lookup_q's: the scale its layout quantises with; + * a parameter because a global scale needs the whole + * table and the transform sees one block. */ P_F64O("wscale") }; -/* embed_lookup's own list: pEmbed and `mult`, the factor every gathered row is multiplied by -- - * Gemma's sqrt(hidden). embed_lookup_q has its table scale and does not take it. */ +/* embed_lookup's list: pEmbed plus `mult`, the factor every gathered row is multiplied by (Gemma's + * sqrt(hidden)). embed_lookup_q has its table scale instead. */ static const RadParamSpec pEmbedM[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_vocab"), P_STR("dtype"), P_INTO("vocab_offset"), P_F64O("wscale"), P_F64O("mult") }; static const RadOperandSpec oEmbed[] = { OPD("tokens"), WGT("wte"), OUT("x") }; -/* The quantised table: one scale for all of it. A SEPARATE OP and not a dtype on the above -- - * the operand list differs and operands are positional, the same argument gemm_nt_q makes. */ +/* The quantised table, one scale for all of it; a separate op since it adds an operand. */ static const RadOperandSpec oEmbedQ[] = { OPD("tokens"), WGT("wte"), WGT_O("scale"), OUT("x"), OPD_O("ahead") }; @@ -591,54 +581,49 @@ static const RadOperandSpec oLogits[] = { OPD("x"), WGT("lm_head"), OUT("logits" /* ---- sampling ------------------------------------------------------------------------------- * - * EVERY SCALAR IS PER ROW AND ARRIVES AS AN OPERAND, not as a parameter. A parameter is geometry: - * the selector matches on it and freezes it at declare (spec §2.2), so `top_p` as a parameter - * would make two requests with different top_p two different resolutions of one op, and a - * deployment would have exactly one top_p. `params` is [M] rows of RadSampleParams - * (abi/rad_sample.h), uploaded once a step. + * Every sampling scalar is per row and arrives as an operand. Parameters are geometry, matched and + * frozen at declare (spec §2.2), so `top_p` as a parameter would allow one value per deployment. + * `params` is [M] rows of RadSampleParams (abi/rad_sample.h), uploaded once per step. * - * This is the schema core/sample/sampler.h issues against, and it is the correction of the one - * docs/OPS.md prints -- `rep`/`freq`/`pres`/`k`/`p` as parameters, and `seed`/`offset` as two more - * operands of sample_pick. A plugin declaring against that form cannot start: the parameters it - * names are per-request values, so declare refuses them as missing geometry. */ + * This is the schema core/sample/sampler.h issues against. It supersedes the one docs/OPS.md + * prints (`rep`/`freq`/`pres`/`k`/`p` as parameters, `seed`/`offset` as extra sample_pick + * operands); a plugin declaring that form cannot start, since declare refuses per-request values + * as missing geometry. */ static const RadParamSpec pMVocab[] = { P_INT("M"), P_INT("n_vocab") }; static const RadParamSpec pMCand[] = { P_INT("M"), P_INT("n_cand") }; -/* The history stages read GLOBAL token ids and write this rank's columns, so under a split - * vocabulary they take the rank's first row as `vocab_off`, the parameter sample_topk carries for - * the same crossing in the other direction. Absent is 0: the whole vocabulary. */ +/* The history stages read global token ids and write this rank's columns, so under a split + * vocabulary they take the rank's first row as `vocab_off` (as sample_topk does). Default 0. */ static const RadParamSpec pPenal[] = { P_INT("M"), P_INT("n_vocab"), P_INTO("vocab_off") }; /* `history` is [M, max_hist] int32 of global token ids; row m's window is addressed by row m's * hist_off / hist_len within row m. */ static const RadOperandSpec oPenalties[] = { INOUT("logits"), OPD("params"), OPD("history") }; /* `breakers` is optional: [M, max_hist] u8 beside `history`, nonzero where that position's token - * is a whole DRY sequence breaker and therefore never penalised. Absent, no token is exempt. */ + * is a whole DRY sequence breaker and never penalised. Absent, no token is exempt. */ static const RadOperandSpec oDry[] = { INOUT("logits"), OPD("params"), OPD("history"), OPD_O("breakers") }; static const RadOperandSpec oTemp[] = { INOUT("logits"), OPD("params") }; /* `bitmask` is [rows, ceil(n_vocab/32)] uint32, addressed by the row's mask_row -- which is -1 for * an unconstrained sequence, so the plane is shared and shorter than M. */ static const RadOperandSpec oMask[] = { INOUT("logits"), OPD("params"), OPD("bitmask") }; -/* `pairs` is the VOCAB-PARALLEL path and is optional: [M, 2 * n_cand] u32 holding this rank's - * candidates as (u32 GLOBAL id, f32 logit), which is exactly what sample_merge_topk reads once - * the all-gather has put every rank's side by side. `vocab_off` is added by the kernel, so the - * gather in between never has to know the shard layout. Absent, and the op is the single-rank - * top-k it has always been. */ +/* `pairs` is the optional vocab-parallel output: [M, 2 * n_cand] u32 of this rank's candidates as + * (u32 global id, f32 logit), which sample_merge_topk reads after the all-gather. The kernel adds + * `vocab_off`, so the gather needs no shard layout. */ static const RadParamSpec pTopk[] = { P_INT("M"), P_INT("n_vocab"), P_INTO("vocab_off") }; static const RadOperandSpec oTopk[] = { OPD("logits"), OPD("params"), OUT("cand_idx"), OUT("cand_val"), OUT_O("pairs") }; static const RadOperandSpec oArgmax[] = { OPD("logits"), OPD("params"), OUT("token") }; -/* `stats` is [M, 2 + 2k]: max, sum of exp(l - max), then k (id, logit) pairs. `k` is geometry -- - * the sampler declares the one width every request's top_logprobs fits in -- and `vocab_off` is - * sample_topk's, for global ids under a split vocabulary. */ +/* `stats` is [M, 2 + 2k]: max, sum of exp(l - max), then k (id, logit) pairs. `k` is geometry + * (the sampler declares one width every request's top_logprobs fits); `vocab_off` is as on + * sample_topk. */ static const RadParamSpec pLogprobs[] = { P_INT("M"), P_INT("n_vocab"), P_INT("k"), P_INTO("vocab_off") }; static const RadOperandSpec oLogprobs[] = { OPD("logits"), OPD("params"), OUT("stats") }; static const RadOperandSpec oNarrow[] = { INOUT("cand_idx"), INOUT("cand_val"), OPD("params") }; static const RadOperandSpec oPick[] = { OPD("cand_idx"), OPD("cand_val"), OPD("params"), OUT("token") }; -/* `gathered` is [M, world_size * n_cand] (u32 id, f32 logit) pairs with GLOBAL token ids -- each - * rank adds its own vocab offset before the gather, so the merge needs no shard layout. */ +/* `gathered` is [M, world_size * n_cand] (u32 id, f32 logit) pairs with global token ids, each rank + * having added its vocab offset before the gather. */ static const RadOperandSpec oMerge[] = { OPD("gathered"), OPD("params"), OUT("cand_idx"), OUT("cand_val") }; @@ -703,7 +688,7 @@ static const RadOpSchema kSchemas[] = { "h[s] = x for each of the hc streams -- the wide residual stream's first value. Shares `hc_write`'s parameter list." }, { "hc_read", ARR(pHcRead), ARR(oHcRead), "The read half of a gated residual. N = grouped_rmsnorm(h) -- one rsqrt per `n`-wide stream, " - "one gain of hc*n over all of them, `1 + wadd*w`; g = sigmoid(mix_up @ silu(mix_down @ N / hc)); " + "one gain of hc*n over all of them, `w + wadd`; g = sigmoid(mix_up @ silu(mix_down @ N / hc)); " "x = mean over the hc streams of g * N. With `inject_w`, inj[s] = 2*sigmoid(inject_w[s] . N / hc) " "-- the per-branch gains hc_write consumes. With `q`, x is also emitted block-scaled fp8, " "quantised from the NARROWED x and not from the accumulator. With `rotate` (and `group`), `rq` " @@ -754,15 +739,25 @@ static const RadOpSchema kSchemas[] = { "y = min(max(x, lo), hi), `lo` and `hi` WEIGHTS of one element each: a clipped linear's range." }, { "conv2d", ARR(pConv2d), ARR(oConv2d), "A 2-D convolution over (time, width), channels innermost: x[t, w*cin + c] -> y[t, w*cout + c], " - "w [cout, cin, kh, kw]. Each cu_seqlens segment (rows cu/cu_div) is convolved on its own with " - "zero padding `pad` at its edges; its output rows start at cu/(cu_div*stride). With `valid`, " - "input row t reads as zeros unless valid[t * valid_stride] != 0. f32 sum, one rounding." }, + "w [cout, cin, kh, kw] ([cout, cin, kw, kh] with t_last). Each cu_seqlens segment (rows " + "cu/cu_div) is convolved on its own with zero padding `pad` at its edges; its output rows start " + "at cu/(cu_div*stride). With `valid`, input row t reads as zeros unless valid[t * valid_stride] " + "!= 0. f32 sum plus the optional bias `b`, one rounding; then `act` (none, gelu) rounded." }, +{ "conv2d_unfold", ARR(pConv2dUnfold), ARR(oConv2dUnfold), + "conv2d's receptive fields as rows: row (to, wo) holds, per input channel and kernel tap, what " + "conv2d multiplies that tap's weight by (zero in the padding and on masked rows), its columns " + "in the weight's order -- (ci, i, j), or (ci, j, i) with t_last -- so a GEMM against the weight " + "as [cout, cin*kh*kw] is the convolution. Segments, cu_div and valid as conv2d's." }, { "conv1d_dw", ARR(pConv1dDw), ARR(oConv1dDw), "Causal depthwise convolution over time: y[t, c] = sum_j w[c, 0, j] * x[t - (k-1) + j, c], rows " "before the segment's start (cu/cu_div) read as zeros. f32 sum, one rounding." }, { "rel_sinusoid", ARR(pRelSin), ARR(oRelSin), "Row d: sin(d * inv[i]) then cos(d * inv[i]) over n/2 timescales, inv[i] = exp(i * " "-log(max_timescale) / max(n/2 - 1, 1)), each step in f32, rounded once." }, +{ "seg_sinusoid", ARR(pSegSin), ARR(oSegSin), + "Row r of segment s (rows cu/cu_div) takes position p = (r - cu[s]/cu_div) mod period: sin(p * " + "inv[i]) then cos(p * inv[i]) over n/2 timescales, inv as rel_sinusoid's, each step in f32, " + "rounded once. Rows no segment covers are left alone." }, { "attn_local_rel", ARR(pAttnLocalRel), ARR(oAttnLocalRel), "Local attention with a relative-position term (Gemma 4's audio): query i of a segment sees " "keys j with 0 <= i - j <= left (`right` 0). qf = q * head_dim^-0.5/ln2 * softplus(pds); logit " @@ -841,26 +836,23 @@ static const RadOpSchema kSchemas[] = { { "softmax", ARR(pMnD), ARR(oUnary), "Row-wise, f32, with the maximum subtracted." }, { "quant_act_i8", ARR(pQuant), ARR(oQuant), - "Symmetric int8 per group of `group` contiguous elements: q = round(x * 127 / amax), " - "scale = amax / 127, scale shaped [M, ceil(n/group)]. group <= 0 or >= n is one scale per row. " - "`asum` present selects libr4d's asymmetric arm and REF DECLINES THAT FORM: it writes one scale " - "per ROW over the whole of n -- there `group` is the asum grouping width and not the scale " - "granularity -- and stores q in fragment order, so neither of its planes means what this one's " - "does." }, -/* NOT one of docs/OPS.md's original ops: it comes from a kernel plugin, and ref adopts the schema - * libr4d/r4d_rows.cpp fixed rather than inventing a second one. Ref implements it so the FP8 path - * has an ORACLE -- without one, the activation format the production checkpoints ship in is the - * one format rad-kbench cannot measure. */ + "Symmetric int8 with ONE SCALE PER ROW, max(amax, 1e-8) / 127, and codes x / scale rounded to " + "nearest even, stored in the STEP ORDER the int8 WMMA reads (the middle two dwords of every " + "16-byte step exchanged; n a multiple of 16). The activation of the w4a8, w8a8 and w2a8 GEMMs. " + "`asum`, if passed, gets each row's code sums per `group` columns, group-major " + "[n/group][ceil(M/16)*16]; rows past M are not written." }, +{ "quant_act_i8g", ARR(pQuant), ARR(oQuantFp8), + "quant_act_fp8 at int8 codes: per `group` contiguous elements a scale amax / 127 (1 for an " + "all-zero group) and codes rounded to nearest even, row-major, scale [M, ceil(n/group)]. The " + "activation of the i8a8 GEMMs." }, +/* Not one of docs/OPS.md's original ops: ref adopts the schema libr4d/r4d_rows.cpp fixed, and + * implements it so the production fp8 activation format has an oracle. */ { "quant_act_fp8", ARR(pQuant), ARR(oQuantFp8), "Symmetric E4M3 per group of `group` contiguous elements: scale = amax / 448 (a DEQUANT " "multiplier, the same sense as a checkpoint's weight_scale_inv), q = clamp(x / scale, +-448), " "scale shaped [M, ceil(n/group)] in f32. An all-zero group gets scale 1, not scale 0: the GEMM " "multiplies this scale by the weight's block scale, and a zero here would erase that one. Rows " "are dim 0, so a rank-3 activation is one row per token and not one per head." }, -/* The rotated fp8 twin, and its scale convention is NOT had_quant_act_i8's: the group is both the - * rotation width and the scale granularity, and the residual factor of `group` is NOT normalised - * here at all -- the weight plane it pairs with (dtype w4a8h) carries the whole of it, where the - * division is an exponent shift on a bf16 and therefore exact. See libref/ref_quant.cpp. */ { "rmsnorm_quant_fp8", ARR(pRmsQuantFp8), ARR(oRmsQuantFp8), "RMS norm with an optional residual add, then the E4M3 quantiser, in one pass. The residual " "add is STORED BEFORE THE VARIANCE READS IT, so the sum the norm is taken over is the bf16 " @@ -892,15 +884,17 @@ static const RadOpSchema kSchemas[] = { "ParoQuant's rotation without a quantiser: y = x / rscale rotated by `stages` rounds of Givens " "pairs, `parts` copies side by side ([M, parts * n]) in y's own dtype. For a weight whose GEMM " "reads a 16-bit activation. `group` is the width a pair stays inside." }, +/* The rotated fp8 twin. Unlike had_quant_act_i8, the group is both rotation width and scale + * granularity, and the factor of `group` is left entirely to the paired w4a8h weight plane, where + * the division is an exact exponent shift on a bf16 (libref/ref_quant.cpp). */ { "had_quant_act_fp8", ARR(pQuant), ARR(oQuantFp8), "A Walsh-Hadamard rotation of width `group` along n, then symmetric E4M3 per group: scale = " "amax(rotated) / 448, shaped [M, n/group] in f32. n must be a multiple of `group` -- a rotation " "block cannot straddle the end of a row. NOT interchangeable with quant_act_fp8 in either " "direction: the consumer must be a weight that was rotated the same way." }, -/* The calibration op. It is the only entry in this vocabulary that no forward pass issues: it - * runs under a calibration flag and its output is read at CONVERT time, in another process, - * through a file. `dtype` is the INPUT's -- fp8a8 where the tap is a quantiser's output, and - * bf16, with no `a_scale`, where the consuming GEMM contracts a plain activation. */ +/* The calibration op, the only one no forward pass issues: it runs under a calibration flag and + * its output is read at convert time, in another process, through a file. `dtype` is the input's: + * fp8a8 where the tap is a quantiser's output, bf16 without `a_scale` for a plain activation. */ { "gram_accum", ARR(pQuant), ARR(oGram), "h[k1][k2] += sum over rows m of dequant(a)[m][k1] * dequant(a)[m][k2], in f32. The second " "moment of a layer's real input over a calibration corpus -- the Hessian a GPTQ packer needs. " @@ -922,7 +916,7 @@ static const RadOpSchema kSchemas[] = { "(down_proj's input) or \"sigmoid\" (a gated-attention o_proj's), and `mode` is libr4d's integer " "spelling of the same choice -- 0 silu, 1 sigmoid. `act` wins where both are given." }, { "dequant", ARR(pDequant), ARR(oDequant), - "y = q * scale, the inverse of quant_act_i8. It does NOT undo a rotation." }, + "y = q * scale, the inverse of quant_act_i8g. It does NOT undo a rotation." }, { "gemm_nt", ARR(pGemm), ARR(oGemm), "y[M,N] = a[M,K] @ b[N,K]^T, f32 accumulate." }, { "gemm_nt_bias", ARR(pGemmBias), ARR(oGemmBias), @@ -942,8 +936,10 @@ static const RadOpSchema kSchemas[] = { "including this step's query rows. k_descale / v_descale are optional and apply to an fp8 " "cache. `scale` is not in docs/OPS.md and defaults to 1/sqrt(head_dim)." }, { "attn_dense", ARR(pAttnDense), ARR(oAttnDense), - "Dense varlen attention over cu_seqlens segments. Nothing paged. `window` is attn_paged's rule " - "over a segment's positions: causal, i - j < window; non-causal, |i - j| < window; 0 none." }, + "Dense varlen attention over cu_seqlens segments (rows cu/cu_div). Nothing paged. `window` is " + "attn_paged's rule over a segment's positions: causal, i - j < window; non-causal, |i - j| < " + "window; 0 none. `block` cuts a segment into blocks of that many rows from its start, each " + "attending within itself; 0 none." }, { "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." }, @@ -957,6 +953,25 @@ static const RadOpSchema kSchemas[] = { "the block's position -- `pos[b]` (with `mode` mrope/imrope and `sections`, a [>= M, 3] list's " "three components) or `pos0 + b*ratio` -- with YaRN's blend and magnitude when given. `page[b]`, " "when given, is the output row; a negative entry writes nothing." }, +{ "qsa_score", ARR(pQsaScore), ARR(oQsaScore), + "score[m][b] = (sum over heads of relu(q[m][h] . bk[bt[seq(m)][b]])) / sqrt(n) for the sequence's " + "first min(nc, width) blocks; the relu is per (block, head) and the sum over heads, and a negative " + "page id scores -inf. Columns past the bound are not written." }, +{ "qsa_select", ARR(pQsaSelect), ARR(oQsaSelect), + "The topk highest-scoring complete blocks a query has passed, as page ids: ties to the lower block " + "index, the blocks above the threshold first and the tied ones after, then the partial page when " + "(pos + 1) % ratio != 0, then -1 to topk + 1. nsel counts the entries and seqused is the " + "attention's length over them." }, +{ "qsa_tail_store", ARR(pQsaTailStore), ARR(oQsaTailStore), + "state[sidx[s][0]][pos[t] % ring] = k[t] for the last `ring` tokens of each sequence; the other " + "rows of the tail keep what they held." }, +{ "qsa_work", ARR(pQsaWork), ARR(oQsaWork), + "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." }, +{ "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]." }, { "rope", ARR(pRope), ARR(oRope), "Rotary embedding in place over the q and k heads of a fused [q|k|v] row; the v heads are left " "alone. `mode` is \"neox\" or \"gptj\", or a multi-component form: \"mrope\" (contiguous " @@ -1215,34 +1230,126 @@ static const RadOpSchema kSchemas[] = { }; /* ================================================================== the kernel table */ -/* One row per op. `shape` says the same thing on every row on purpose: there is no geometry - * this refuses, and saying so in the row is what a --debug-graph dump prints next to the - * warning that an op fell through to ref. */ +/* One row per op. `shape` is the same on every row, since ref refuses no geometry; --debug-graph + * prints it beside the warning that an op fell through to ref. */ #define SHAPE_ANY "any: every extent is read off the operands, strides included" -/* THE OPERAND DESCRIPTION IS PASTED OUT OF THE LAUNCH and is not a twelfth macro argument. - * `RadKernelInfo::opd_shape` is the last member, after `transform`, and it answers "how big is - * operand i of this op at this geometry, and what may legally be in it" for a tool that wants to - * call the op cold (rad_abi.h). It cannot be one shared function, because the hook is not handed - * the op name and no op in this vocabulary carries its own name as a parameter -- so every row - * needs its own. Naming each one after its entry point (`ref_rmsnorm` -> `ref_rmsnorm_shape`) means - * `fn ## _shape` produces it here, so no row below carries it as an argument of its own. It also - * means an op added later cannot forget: the macro demands the symbol, so a - * row without a shape hook fails to link rather than silently making its op undescribable. The - * implementations, and every judgement call in them, are in libref/ref_shapes.cpp. */ -/* No tunables, on every row, deliberately. libref is the ORACLE and the last resort: there is one - * implementation of each op and nothing to choose between, so there is no axis to declare and - * nothing for rad-tune to measure. A reference with tile variants would be a reference whose - * answer depends on which one ran. The three nulls are tunables, n_tunables and tune_valid. */ +/* The operand-description hook (`RadKernelInfo::opd_shape`, rad_abi.h) is pasted from the launch + * name as `fn ## _shape` (see ref_ops.h), so a row without one fails to link. The implementations + * are in libref/ref_shapes.cpp. + * + * Every launch first passes ref_check_dtypes (below), so an operand libref cannot read or store + * is refused rather than read as zeros. + * + * No tunables on any row: the oracle has one implementation per op, so its answer never depends on + * a variant. The three nulls are tunables, n_tunables and tune_valid. */ +static bool ref_readable(uint32_t dt) { + switch (dt) { + case RAD_F32: case RAD_F16: case RAD_BF16: case RAD_F8E4M3: case RAD_F8E5M2: + case RAD_I8: case RAD_U8: case RAD_BOOL: case RAD_I16: case RAD_U16: case RAD_I32: + case RAD_U32: case RAD_I64: case RAD_I4: case RAD_I2: case RAD_FP4E2M1: case RAD_E8M0: + return true; + default: + return false; + } +} +static bool ref_storable(uint32_t dt) { + switch (dt) { + case RAD_F32: case RAD_F16: case RAD_BF16: case RAD_F8E4M3: case RAD_F8E5M2: + case RAD_I8: case RAD_U8: case RAD_BOOL: case RAD_I16: case RAD_U16: case RAD_I32: + case RAD_U32: case RAD_I64: case RAD_I4: case RAD_I2: case RAD_FP4E2M1: + return true; + default: + return false; + } +} + +/* A weight operand stored in the joined form of abi/rad_planes.h, or a table whose first entry is: + * its dtype is the first plane's, and the kernel reads each plane by the dtype its entry names. */ +static bool ref_joined_weight(const RadTensor& t, int role) { + if (role != RAD_OPD_WEIGHT && role != RAD_OPD_WTAB) return false; + const void* p = t.data; + if (role == RAD_OPD_WTAB && t.rank >= 1 && t.stride[0] == 0) + p = t.shape[0] > 0 ? ((void* const*)t.data)[0] : nullptr; + return rad_planes_header(p) != nullptr; +} + +/* RAD_E_DTYPE for a present operand whose dtype ref_common.h's ld_dt cannot read (an input) or + * st_dt cannot store (an output): those return zero and drop the store, which would make a call + * on an unsupported format return RAD_OK with a wrong answer. A joined weight is left to its + * kernel, which refuses the planes it does not compute. */ +static int ref_check_dtypes(const char* op, const RadArgs* a) { + if (!a) return RAD_E_INVAL; + const RadOpSchema* sc = nullptr; + for (const RadOpSchema& s : kSchemas) + if (std::strcmp(s.op, op) == 0) { sc = &s; break; } + if (!sc) return RAD_E_NOKERNEL; + const int n = a->n_t < sc->n_operands ? a->n_t : sc->n_operands; + for (int i = 0; i < n; ++i) { + const RadTensor& t = a->t[i]; + if (!t.data) continue; + const int role = sc->operands[i].role; + if (role != RAD_OPD_OUT && !ref_readable(t.dtype) && !ref_joined_weight(t, role)) + return RAD_E_DTYPE; + if ((role == RAD_OPD_OUT || role == RAD_OPD_INOUT) && !ref_storable(t.dtype)) + return RAD_E_DTYPE; + } + return RAD_OK; +} + #define ROW(nm, opname, fam, what, dts, cons, ncons, init, fini, fn, scr) \ { nm, opname, fam, what, SHAPE_ANY, dts, RAD_DOMAIN_HOST, 0, \ - cons, ncons, nullptr, 0, nullptr, init, fini, fn, scr, nullptr, nullptr, fn##_shape } + cons, ncons, nullptr, 0, nullptr, init, fini, \ + [](const RadArgs* a, RadStream s) -> int { \ + const int rc = ref_check_dtypes(opname, a); \ + return rc < 0 ? rc : fn(a, s); \ + }, \ + scr, nullptr, nullptr, fn##_shape } #define SIMPLE(nm, opname, fam, what, dts, fn) \ ROW(nm, opname, fam, what, dts, nullptr, 0, nullptr, nullptr, fn, nullptr) +/* A grouped GEMM row with the codebook experts' layout hooks (ref_moe.cpp). */ +#define ROW_CB(nm, opname, fam, what, dts, fn) \ + { nm, opname, fam, what, SHAPE_ANY, dts, RAD_DOMAIN_HOST, 0, \ + nullptr, 0, nullptr, 0, nullptr, nullptr, nullptr, \ + [](const RadArgs* a, RadStream s) -> int { \ + const int rc = ref_check_dtypes(opname, a); \ + return rc < 0 ? rc : fn(a, s); \ + }, \ + nullptr, ref_moe_cb_layout, ref_moe_cb_relayout, fn##_shape, ref_moe_cb_unrelayout } + +/* gemm_nt_q's zero-point grids read their codes as `b`: u2, u4 or u5, which ld_dt does not read + * and every other op refuses. The grid's own path reads them (ref_gemm.cpp: gemm_zp), so they pass + * the check there and only there. */ +static int ref_check_gemm_q(const char* op, const RadArgs* a) { + const ref::ZpGrid* zg = + a ? ref::zp_grid(rad_param_gets(a->p, a->n_p, "dtype", nullptr)) : nullptr; + if (!zg || a->n_t < 3 || !a->t[2].data || a->t[2].dtype != zg->codes) + return ref_check_dtypes(op, a); + RadArgs b = *a; + RadTensor t[16]; + if (a->n_t > 16) return RAD_E_INVAL; + for (int i = 0; i < a->n_t; ++i) t[i] = a->t[i]; + t[2].data = nullptr; + b.t = t; + return ref_check_dtypes(op, &b); +} + +/* A row whose weight operands may be joined over several planes (ref_planes.h): its layout hooks, + * and the dtype check its launch passes first. */ +#define ROWL(nm, opname, fam, what, dts, check, fn, lay) \ + { nm, opname, fam, what, SHAPE_ANY, dts, RAD_DOMAIN_HOST, 0, \ + nullptr, 0, nullptr, 0, nullptr, nullptr, nullptr, \ + [](const RadArgs* a, RadStream s) -> int { \ + const int rc = check(opname, a); \ + return rc < 0 ? rc : fn(a, s); \ + }, \ + nullptr, lay, ref::ref_relayout_planes, fn##_shape, ref::ref_unrelayout_planes } + #define DT_FLOAT "bf16 f16 f32 fp8_e4m3 fp8_e5m2 i8 i32, chosen per operand from its own dtype" #define DT_ANY "any dtype rad_types.h names, per operand" +#define DT_FLOAT_CB DT_FLOAT "; or u4 / u5 codes into an f32 table, joined (w4nl* / w5nl*)" static const RadKernelInfo kKernels[] = { SIMPLE("ref_rmsnorm", "rmsnorm", "norm", "root-mean-square norm with a gain", DT_FLOAT, @@ -1253,11 +1360,14 @@ SIMPLE("ref_rmsnorm_add", "rmsnorm_add", "norm", "residual add then RMS norm", D ref_rmsnorm_add), SIMPLE("ref_hc_enter", "hc_enter", "norm", "gated residual entry: hc copies of x", DT_FLOAT, ref_hc_enter), -SIMPLE("ref_hc_read", "hc_read", "norm", "gated residual read: grouped norm, low-rank gate, stream mix", - DT_FLOAT, ref_hc_read), -SIMPLE("ref_mtp_enter", "mtp_enter", "norm", - "MTP head entry: two norms, a per-sub-stream fc and a broadcast fc", DT_FLOAT, - ref_mtp_enter), +ROWL("ref_hc_read", "hc_read", "norm", + "gated residual read: grouped norm, low-rank gate, stream mix", + DT_FLOAT ", or mixing matrices of E4M3 / int8 codes with a scale plane, joined", + ref_check_dtypes, ref_hc_read, ref::ref_layout_hc), +ROWL("ref_mtp_enter", "mtp_enter", "norm", + "MTP head entry: two norms, a per-sub-stream fc and a broadcast fc", + DT_FLOAT ", or fc matrices of E4M3 / int8 codes with a scale plane, joined", + ref_check_dtypes, ref_mtp_enter, ref::ref_layout_mtp), SIMPLE("ref_hc_write", "hc_write", "norm", "gated residual write: h[s] += inj[s] * y", DT_FLOAT, ref_hc_write), SIMPLE("ref_layernorm", "layernorm", "norm", "layer norm with gain and bias", DT_FLOAT, @@ -1282,10 +1392,16 @@ SIMPLE("ref_relu", "relu", "elem", "max(x, 0)", DT_FLOAT, ref_relu), SIMPLE("ref_clamp", "clamp", "elem", "x clamped to two weight scalars", DT_FLOAT, ref_clamp), SIMPLE("ref_conv2d", "conv2d", "elem", "segment-wise 2-D convolution, channels innermost", DT_FLOAT, ref_conv2d), +SIMPLE("ref_conv2d_unfold", "conv2d_unfold", "elem", + "a convolution's receptive fields as rows, for a GEMM against its weight", DT_FLOAT, + ref_conv2d_unfold), SIMPLE("ref_conv1d_dw", "conv1d_dw", "elem", "segment-wise causal depthwise convolution", DT_FLOAT, ref_conv1d_dw), SIMPLE("ref_rel_sinusoid", "rel_sinusoid", "elem", "sinusoidal relative-position table", DT_FLOAT, ref_rel_sinusoid), +SIMPLE("ref_seg_sinusoid", "seg_sinusoid", "elem", + "sinusoidal absolute positions, restarting every `period` rows of a segment", DT_FLOAT, + ref_seg_sinusoid), SIMPLE("ref_attn_local_rel", "attn_local_rel", "attn", "local attention with a relative-position term and a softcap", DT_FLOAT, ref_attn_local_rel), @@ -1313,15 +1429,15 @@ SIMPLE("ref_scatter_rows", "scatter_rows", "elem", "x[idx[i],:] = v[i,:]", DT_AN SIMPLE("ref_cast", "cast", "elem", "dtype conversion", DT_ANY, ref_cast), SIMPLE("ref_softmax", "softmax", "elem", "row-wise softmax", DT_FLOAT, ref_softmax), -SIMPLE("ref_quant_act_i8", "quant_act_i8", "quant", "symmetric int8 activation quantiser", +SIMPLE("ref_quant_act_i8", "quant_act_i8", "quant", + "symmetric int8 activation quantiser, one scale a row, codes in the WMMA step order", "float in, i8 out, f32 scale", ref_quant_act_i8), +SIMPLE("ref_quant_act_i8g", "quant_act_i8g", "quant", + "symmetric int8 activation quantiser, one scale per group, row-major", + "float in, i8 out, f32 scale", ref_quant_act_i8g), SIMPLE("ref_quant_act_fp8", "quant_act_fp8", "quant", "symmetric block-scaled E4M3 quantiser", "float in, fp8_e4m3 out, f32 scale", ref_quant_act_fp8), -/* THE FUSED FORMS, AND THEY EXIST SO A HOST RUN IS POSSIBLE AT ALL. libr4d fuses the fp8 - * activation quantiser into whichever kernel already has the row in registers and declares the - * fused op as its own; without host kernels for those names, a host-backend run -- the only - * thing that can answer "is the GRAPH right", because the per-op oracle reads the same graph on - * both sides -- cannot start on an fp8 model. */ +/* The fused fp8 forms, so a host-backend run can start on an fp8 model (see ref_quant.cpp). */ SIMPLE("ref_rmsnorm_quant_fp8", "rmsnorm_quant_fp8", "quant", "RMS norm, optional residual add, and the E4M3 quantiser in one pass", "bf16 in, fp8_e4m3 out, f32 scale", ref_rmsnorm_quant_fp8), @@ -1365,8 +1481,10 @@ SIMPLE("ref_dequant", "dequant", "quant", "group-scaled dequantisation", DT_ANY, SIMPLE("ref_gemm_nt", "gemm_nt", "gemm", "C = A B^T, f32 accumulate", DT_FLOAT, ref_gemm_nt), SIMPLE("ref_gemm_nt_bias", "gemm_nt_bias", "gemm", "C = A B^T + bias", DT_FLOAT, ref_gemm_nt_bias), -SIMPLE("ref_gemm_nt_q", "gemm_nt_q", "gemm", "C = A B^T with group-scaled quantised operands", - "i8 / fp8 / float A; w4, w2, mxfp4, i8 or float B; f32 accumulate", ref_gemm_nt_q), +ROWL("ref_gemm_nt_q", "gemm_nt_q", "gemm", "C = A B^T with group-scaled quantised operands", + "i8 / fp8 / float A; w4, w2, mxfp4, i8 or float B; u2 / u4 / u5 codes with an f16 scale " + "and integer zero per group, joined; f32 accumulate", + ref_check_gemm_q, ref_gemm_nt_q, ref::ref_layout_gemm_q), SIMPLE("ref_gemm_nt_q_bias", "gemm_nt_q_bias", "gemm", "quantised C = A B^T + bias", "i8 / fp8 / float A; w4, w2, mxfp4, i8 or float B; f32 accumulate", ref_gemm_nt_q_bias), @@ -1392,21 +1510,37 @@ SIMPLE("ref_moe_scatter", "moe_scatter", "moe", "stable counting sort of routing "i32 indices", ref_moe_scatter), SIMPLE("ref_moe_gemm", "moe_gemm", "moe", "grouped GEMM over the expert-sorted rows", DT_FLOAT, ref_moe_gemm), -SIMPLE("ref_moe_gemm_q", "moe_gemm_q", "moe", - "grouped GEMM over the expert-sorted rows, quantised operands", DT_FLOAT, ref_moe_gemm_q), -SIMPLE("ref_moe_gemm_q_mod4", "moe_gemm_q_mod4", "moe", +ROW_CB("ref_moe_gemm_q", "moe_gemm_q", "moe", + "grouped GEMM over the expert-sorted rows, quantised operands", DT_FLOAT_CB, + ref_moe_gemm_q), +ROW_CB("ref_moe_gemm_q_mod4", "moe_gemm_q_mod4", "moe", "grouped GEMM over the expert-sorted rows, quantised operands, four classes by number mod 4", - DT_FLOAT, ref_moe_gemm_q_mod4), + DT_FLOAT_CB, ref_moe_gemm_q_mod4), SIMPLE("ref_moe_gather", "moe_gather", "moe", "weighted scatter back to token order", DT_FLOAT, ref_moe_gather), SIMPLE("ref_rope_table", "rope_table", "attn", "cos/sin at each position's own row", DT_FLOAT, ref_rope_table), SIMPLE("ref_qsa_block_key", "qsa_block_key", "attn", "QSA compressed key: pooled, normed and rotated at the block's position", DT_FLOAT, ref_qsa_block_key), +SIMPLE("ref_qsa_score", "qsa_score", "attn", + "QSA block scores: per-head relu dots summed over the heads", DT_FLOAT, ref_qsa_score), +SIMPLE("ref_qsa_select", "qsa_select", "attn", + "QSA selection: the top-k blocks as a page-id table, partial page last", + "f32 scores, i32 tables", ref_qsa_select), +SIMPLE("ref_qsa_tail_store", "qsa_tail_store", "attn", + "QSA tail: the raw keys of open blocks into a per-sequence ring", DT_FLOAT, + 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_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), SIMPLE("ref_row_topk_merge", "row_topk_merge", "moe", "the global top-R of the gathered per-rank candidate sets", DT_FLOAT, ref_row_topk_merge), SIMPLE("ref_pair_argmax", "pair_argmax", "moe", "the global top-1 of a row of gathered (id, value) pairs, one id a row", DT_FLOAT, ref_pair_argmax), -SIMPLE("ref_logit_rerank", "logit_rerank", "moe", "R candidates a row rescored exactly against the full-precision head", DT_FLOAT, ref_logit_rerank), +ROWL("ref_logit_rerank", "logit_rerank", "moe", + "R candidates a row rescored exactly against the full-precision head", + DT_FLOAT ", or a head of E4M3 / int8 codes with a scale plane, joined", + ref_check_dtypes, ref_logit_rerank, ref::ref_layout_head), SIMPLE("ref_gdn_conv_prep", "gdn_conv_prep", "gdn", "gdn prefill preamble: conv, split, l2 norm, gate cumsum, beta", DT_FLOAT, @@ -1418,7 +1552,8 @@ SIMPLE("ref_gdn_kkt_solve", "gdn_kkt_solve", "gdn", "gdn chunk preamble: the tri SIMPLE("ref_gdn_chunk_scan", "gdn_chunk_scan", "gdn", "gdn chunked scan", DT_FLOAT, ref_gdn_chunk_scan), SIMPLE("ref_gdn_recurrent_update", "gdn_recurrent_update", "gdn", - "gdn decode recurrence against the paged state cache", DT_FLOAT, ref_gdn_recurrent_update), + "gdn decode recurrence against the paged state cache, per-candidate or anchor state", + DT_FLOAT, ref_gdn_recurrent_update), SIMPLE("ref_gdn_conv_recurrent_update", "gdn_conv_recurrent_update", "gdn", "gdn_conv_update then gdn_recurrent_update, composed from those two references", DT_FLOAT, ref_gdn_conv_recurrent_update), @@ -1434,8 +1569,9 @@ SIMPLE("ref_embed_lookup", "embed_lookup", "vocab", "embedding gather", DT_FLOAT ref_embed_lookup), SIMPLE("ref_embed_lookup_q", "embed_lookup_q", "vocab", "embedding gather, one scale for the table", DT_ANY, ref_embed_lookup_q), -SIMPLE("ref_logits_gemm", "logits_gemm", "vocab", "the lm_head projection", DT_FLOAT, - ref_logits_gemm), +ROWL("ref_logits_gemm", "logits_gemm", "vocab", "the lm_head projection", + DT_FLOAT ", or a head of E4M3 / int8 codes with a scale plane, joined", + ref_check_dtypes, ref_logits_gemm, ref::ref_layout_head), SIMPLE("ref_sample_penalties", "sample_penalties", "sample", "repetition, frequency and presence penalties", DT_FLOAT, ref_sample_penalties), @@ -1511,8 +1647,8 @@ static const RadPluginInfo kInfo = { extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; } extern "C" const RadPluginInfo* rad_plugin_info(void) { return &kInfo; } -/* The oracle and the last resort, said through the ABI as any library would say it - * (RadPluginReferenceFn): the engine knows no library by name. */ +/* Declares this plugin the reference through the ABI (RadPluginReferenceFn); the engine knows no + * library by name. */ extern "C" int rad_plugin_reference(void) { return 1; } extern "C" int rad_kernel_schema_count(void) { @@ -1529,8 +1665,8 @@ extern "C" const RadKernelInfo* rad_kernel_at(int i) { if (i < 0 || i >= rad_kernel_count()) return nullptr; return &kKernels[i]; } -/* The rows that join the other ranks (ref_collective.cpp), said through the ABI - * (RadKernelCollectiveFn) so the gather counts as one as well as the all-reduce. */ +/* The rows that join the other ranks (ref_collective.cpp), via RadKernelCollectiveFn; covers the + * all-gather as well as the all-reduce. */ extern "C" int rad_kernel_collective(int i) { const RadKernelInfo* k = rad_kernel_at(i); return k && k->init == ref_collective_init; diff --git a/libref/ref_sample.cpp b/libref/ref_sample.cpp index e7f425f9..dc0091bd 100644 --- a/libref/ref_sample.cpp +++ b/libref/ref_sample.cpp @@ -1,45 +1,31 @@ /* ref_sample.cpp -- the sampler ops. * - * Every sampler in this engine is a KERNEL and not a host lift: at a 151K vocab and batch 256 the - * logits are ~77 MiB a step, and moving that across the link to run a host chain costs both the - * bandwidth and a synchronisation, on the step path, at exactly the concurrency the engine exists - * to serve (spec §13). llama.cpp's chain is kept as a host reference in core/sample/, and THIS is - * the second implementation of the same arithmetic -- the two are deliberately independent, so - * that comparing them says something. + * Sampling runs as kernels, not on the host: at a 151K vocab and batch 256 the logits are ~77 MiB + * per step, and copying them for a host chain would cost bandwidth and a synchronisation on the step + * path (spec §13). core/sample/ keeps llama.cpp's chain as a host reference; this is an independent + * second implementation of the same arithmetic, so comparing the two is meaningful. * - * ============================== EVERY SCALAR IS PER ROW ============================== + * ============================== Every scalar is per row ============================== * - * `rep`, `freq`, `pres`, `k` and `p` cannot be op PARAMETERS. A parameter is geometry: the selector - * matches constraints against it and freezes it at declare (spec §2.2), so two requests in one - * batch with different top_p would be two different resolutions of one op. A deployment would have - * exactly one top_p, which is not a sampler. + * Sampling scalars (`rep`, `freq`, `pres`, `k`, `p`, `seed`, `pos`) arrive as data, in a `params` + * operand of RadSampleParams rows, one per sampled position, uploaded once per step + * (abi/rad_sample.h). As parameters they would be frozen at declare (see ref_registry.cpp). * - * So they arrive as DATA, in a `params` operand of RadSampleParams rows -- one per sampled - * position, uploaded once a step (abi/rad_sample.h). That is the schema core/sample/sampler.h - * issues against, and the one every op below reads its scalars from. + * ============================== The candidate set ============================== * - * `seed` and `pos` are fields of the row for the same reason, rather than two more operands of - * `sample_pick`. + * `sample_topk` produces a fixed-width candidate set and the narrowing stages work in place. A + * dropped candidate is index -1, value -infinity; kept candidates stay in place in descending + * order, so a later stage can stop at the first -1 or skip holes (`sample_pick` skips). * - * ============================== THE CANDIDATE SET ============================== + * `cand_val` carries logits, not probabilities: each narrowing stage takes its own softmax over the + * set, as llama.cpp does, so stages compose in any order. * - * `sample_topk` produces a fixed-width candidate set and the narrowing stages work IN PLACE. The - * tensors do not shrink, so a dropped candidate has to be expressible, and the convention is: - * index -1, value -infinity. Kept candidates stay where they are, in descending order, so a later - * stage can stop at the first -1 or skip the holes -- both work, and `sample_pick` skips. + * A row's top_k may be narrower than the buffer (a declare-time bound): top_k 40 in a 1024-wide + * buffer gives 40 candidates and 984 holes. * - * `cand_val` carries LOGITS, not probabilities. Each narrowing stage takes its own softmax over - * the candidate set, which is what llama.cpp does and what keeps the stages composable in any - * order. - * - * A ROW'S OWN top_k MAY BE NARROWER THAN THE BUFFER. The candidate width is a deployment bound - * chosen at declare; a request asking for top_k 40 out of a 1024-wide buffer gets 40 candidates - * and 984 holes, which every later stage already knows how to skip. - * - * A GREEDY ROW (RAD_SP_GREEDY) HAS NO CANDIDATES. Its token is sample_argmax's, and in a batch - * that mixes greedy and sampled rows every stage runs over every row -- so top-k and the merge - * write it an empty set, the narrowing stages leave it alone, and the pick does not touch its - * token. A pick that ignored the flag would replace the argmax with a draw. + * A greedy row (RAD_SP_GREEDY) has no candidates; its token is sample_argmax's. In a mixed batch + * every stage runs over every row, so top-k and the merge write it an empty set, narrowing leaves it + * alone, and the pick must not overwrite its token with a draw. */ #include "ref_common.h" #include "ref_ops.h" @@ -54,22 +40,17 @@ using namespace ref; namespace { -/* The params operand, checked once. A sampler op with no rows to act on is not an error -- it is - * a step in which nothing asked for that stage. */ +/* The params operand, checked once. */ struct Rows { const RadSampleParams* p; int64_t n; }; -static inline int rows_of(const RadTensor* t, int64_t M, Rows* out) { +static inline int param_rows(const RadTensor* t, int64_t M, Rows* out) { if (!t || !t->data) return RAD_E_INVAL; - /* The row array is a BYTE BLOB viewed through some 32-bit dtype -- the sampler declares it - * [rows, sizeof(RadSampleParams)/4] u32, which is the only way the builder can express "this - * many bytes a row". So the extent is checked in words, and the dtype is required to be a - * 32-bit one rather than run through rad_dtype_bytes -- not because that is out of reach (it - * is static inline in rad_types.h, and this file could call it), but because "any width, as - * long as the arithmetic works out" is the wrong contract here: the blob is addressed as - * 32-bit words and a 16-bit view of it would pass a byte count and then misread every row. */ + /* The row array is a byte blob declared as [rows, sizeof(RadSampleParams)/4] u32, the only way + * the builder can express a per-row byte size. The dtype must be 32-bit: a 16-bit view could + * pass a byte-count check and then misread every row. */ if (t->dtype != RAD_U32 && t->dtype != RAD_I32 && t->dtype != RAD_F32) return RAD_E_DTYPE; if (numel(t) * 4 < M * (int64_t)sizeof(RadSampleParams)) return RAD_E_SHAPE; out->p = (const RadSampleParams*)t->data; @@ -80,11 +61,10 @@ static inline int rows_of(const RadTensor* t, int64_t M, Rows* out) { } /* namespace */ /* ------------------------------------------------------------------ the history window */ -/* The window both history stages read, as the row states it: `hist_off` and `hist_len` address the - * row's OWN row of the history plane, clamped to it, and `last_n` then keeps the TAIL of that span - * -- the last n tokens, not the first, because a window applied at the wrong end penalises what - * the request has already forgotten. last_n 0 turns the stage off for the row (false), a negative - * one keeps the whole span: llama.cpp's meaning for repeat_last_n and dry_penalty_last_n. */ +/* The window both history stages read: `hist_off` and `hist_len` address the row's own row of the + * history plane, clamped to it, and `last_n` keeps the tail of that span (the most recent tokens). + * last_n 0 disables the stage for the row (returns false); negative keeps the whole span, as + * llama.cpp's repeat_last_n and dry_penalty_last_n. */ static inline bool hist_window(const RadSampleParams& sp, int32_t last_n, int64_t hmax, int64_t* ho_out, int64_t* hl_out) { if (last_n == 0) return false; @@ -104,16 +84,15 @@ static inline bool hist_window(const RadSampleParams& sp, int32_t last_n, int64_ /* ------------------------------------------------------------------ sample_penalties */ /* llama.cpp's ordering, in one pass over the row's history: * - * repetition logit = logit > 0 ? logit / rep : logit * rep (once per DISTINCT token) + * repetition logit = logit > 0 ? logit / rep : logit * rep (once per distinct token) * frequency logit -= count * freq * presence logit -= pres (once per distinct token) * - * The repetition penalty being multiplicative and sign-dependent is the part everyone gets wrong: - * dividing a negative logit would make it LARGER, so it is multiplied instead. + * The repetition penalty is sign-dependent: dividing a negative logit would raise it, so it is + * multiplied instead. * - * The history holds GLOBAL token ids and the logits row is this rank's shard of the vocabulary, - * so a token's column is its id less `vocab_off`, and a token outside the shard is another rank's - * to penalise. */ + * History ids are global and the logits row is this rank's vocabulary shard, so a token's column is + * its id less `vocab_off`; tokens outside the shard are other ranks'. */ int ref_sample_penalties(const RadArgs* a, RadStream) { if (!have(a, 3)) return RAD_E_INVAL; const RadTensor *lg = &a->t[0], *pr = &a->t[1], *hist = &a->t[2]; @@ -122,12 +101,12 @@ int ref_sample_penalties(const RadArgs* a, RadStream) { const int64_t M = numel(lg) / n_vocab; if (M <= 0) return RAD_E_SHAPE; Rows R; - RAD_REF_TRY(rows_of(pr, M, &R)); + RAD_REF_TRY(param_rows(pr, M, &R)); const int64_t hmax = numel(hist) / M; if (hmax <= 0) return RAD_E_SHAPE; const int64_t voff = p_int(a, "vocab_off", 0); - #pragma omp parallel for schedule(static) + REF_PAR_FOR(M * (n_vocab + hmax)) for (int64_t m = 0; m < M; ++m) { const RadSampleParams& sp = R.p[m]; if (!(sp.flags & RAD_SP_PENALTY)) continue; @@ -144,8 +123,8 @@ int ref_sample_penalties(const RadArgs* a, RadStream) { const int64_t tok = ld_int(hist->dtype, hist->data, hb + i * hs); const int64_t col = tok - voff; if (tok < 0 || col < 0 || col >= n_vocab) continue; - /* First occurrence only: the penalties are per distinct token, and the count is what - * carries the multiplicity. O(hist^2) and the history is tens of tokens. */ + /* First occurrence only: penalties are per distinct token, the count carries the + * multiplicity. O(hist^2) over a short history. */ bool first = true; int64_t count = 0; for (int64_t j = 0; j < hl; ++j) { @@ -166,26 +145,22 @@ int ref_sample_penalties(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------------ sample_dry */ -/* DRY -- "don't repeat yourself". A penalty on the token that would EXTEND a suffix of the history - * that has occurred before, which is what stops a model looping on a phrase rather than on a - * token. llama.cpp's rule (llama_sampler_dry_apply): +/* DRY ("don't repeat yourself"): a penalty on a token that would extend a suffix of the history + * that occurred before, to stop phrase-level loops. llama.cpp's rule (llama_sampler_dry_apply): * * for every earlier position j, n_j is how long a suffix of the window also ends at j, capped * at the breaker limit; the token after j would extend that repeat. Each such token is - * penalised ONCE, by multiplier * base^(L - allowed_length), where L is the LONGEST n_j among - * the positions it follows. + * penalised once, by multiplier * base^(L - allowed_length), L the longest n_j among the + * positions it follows. * - * Only lengths at or above `allowed_length` count, so ordinary repetition of short n-grams is - * untouched, and a token that is itself a whole sequence breaker is never penalised -- it is what - * ends the repetition. Both breaker facts come from the host, which is the side with the - * vocabulary: the row's `dry_rep_limit` (0 for none) and the optional `breakers` plane, one byte - * per history position, nonzero where that position's token is a single-token breaker. + * Only lengths >= `allowed_length` count, and a token that is itself a whole sequence breaker is + * never penalised. Breaker facts come from the host, which has the vocabulary: the row's + * `dry_rep_limit` (0 for none) and the optional `breakers` plane, one byte per history position, + * nonzero for a single-token breaker. * - * The penalty is multiplier * base^e by repeated multiplication, stopping short of overflow, so - * every implementation of this op computes the same float; llama.cpp clamps the exponent to the - * same end. History ids are GLOBAL and a column is an id less `vocab_off`, as for the penalties. - * - * Written the obvious quadratic way over the window: this is the oracle, not the fast path. */ + * The penalty is computed by repeated multiplication, stopping short of overflow, so every + * implementation computes the same float (llama.cpp clamps the exponent likewise). Columns are + * global ids less `vocab_off`. Quadratic over the window. */ static inline float dry_penalty(float multiplier, float base, int64_t e) { float pen = multiplier; if (base == 1.0f) return pen; @@ -206,14 +181,14 @@ int ref_sample_dry(const RadArgs* a, RadStream) { const int64_t M = numel(lg) / n_vocab; if (M <= 0) return RAD_E_SHAPE; Rows R; - RAD_REF_TRY(rows_of(pr, M, &R)); + RAD_REF_TRY(param_rows(pr, M, &R)); const int64_t hmax = numel(hist) / M; if (hmax <= 0) return RAD_E_SHAPE; - /* The breaker plane is the history's twin, position for position. */ + /* The breaker plane matches the history position for position. */ if (brk && numel(brk) < M * hmax) return RAD_E_SHAPE; const int64_t voff = p_int(a, "vocab_off", 0); - #pragma omp parallel for schedule(static) + REF_PAR_FOR(M * (n_vocab + hmax * hmax)) for (int64_t m = 0; m < M; ++m) { const RadSampleParams& sp = R.p[m]; if (!(sp.flags & RAD_SP_DRY) || !(sp.dry_multiplier > 0.0f)) continue; @@ -261,8 +236,7 @@ int ref_sample_dry(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------------ sample_temp */ -/* temp <= 0 leaves the row untouched: greedy decoding is `sample_argmax`, and a temperature of - * zero silently meaning something else is how a sampler chain becomes unreadable. */ +/* temp <= 0 leaves the row untouched; greedy decoding is `sample_argmax`. */ int ref_sample_temp(const RadArgs* a, RadStream) { if (!have(a, 2)) return RAD_E_INVAL; const RadTensor *lg = &a->t[0], *pr = &a->t[1]; @@ -271,9 +245,9 @@ int ref_sample_temp(const RadArgs* a, RadStream) { const int64_t M = numel(lg) / n_vocab; if (M <= 0) return RAD_E_SHAPE; Rows R; - RAD_REF_TRY(rows_of(pr, M, &R)); + RAD_REF_TRY(param_rows(pr, M, &R)); - #pragma omp parallel for schedule(static) + REF_PAR_FOR(M * n_vocab) for (int64_t m = 0; m < M; ++m) { const float t = R.p[m].temp; if (!(t > 0.0f) || t == 1.0f) continue; @@ -293,25 +267,22 @@ int ref_sample_topk(const RadArgs* a, RadStream) { const int64_t M = numel(lg) / n_vocab; if (M <= 0) return RAD_E_SHAPE; Rows R; - RAD_REF_TRY(rows_of(pr, M, &R)); - /* The candidate WIDTH is the buffer's, not the request's: it is the deployment bound the - * arena was sized for, and every later stage reads it. */ + RAD_REF_TRY(param_rows(pr, M, &R)); + /* The candidate width is the buffer's (the declare-time bound), not the request's. */ const int64_t n_cand = ci->rank >= 2 ? ci->shape[ci->rank - 1] : numel(ci) / M; if (n_cand <= 0 || numel(cv) < M * n_cand) return RAD_E_SHAPE; - /* THE VOCAB-PARALLEL PAIR PLANE, optional. cand_idx stays LOCAL -- it indexes this rank's - * logits row and every stage after top-k reads it that way -- and `pairs` carries the same - * candidates with `vocab_off` added, as (u32 GLOBAL id, f32 logit), which is what the - * all-gather moves and what sample_merge_topk reads. Absent, and this is the single-rank - * top-k unchanged. */ + /* Optional vocab-parallel pair plane. cand_idx stays local (it indexes this rank's logits + * row); `pairs` carries the same candidates as (u32 global id, f32 logit) with `vocab_off` + * added, for the all-gather and sample_merge_topk. */ const RadTensor* pp = a->n_t > 4 && a->t[4].data ? &a->t[4] : nullptr; const int64_t voff = p_int(a, "vocab_off", 0); if (pp && numel(pp) < M * 2 * n_cand) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(M * n_vocab * 4) for (int64_t m = 0; m < M; ++m) { - /* A row's own top_k, clamped to the buffer. 0 or negative means "the whole candidate - * width", which is what a request that set no top_k asks for. A greedy row takes none. */ + /* The row's top_k, clamped to the buffer; <= 0 means the whole width. A greedy row takes + * none. */ int64_t k = R.p[m].top_k; if (k <= 0 || k > n_cand) k = n_cand; if (R.p[m].flags & RAD_SP_GREEDY) k = 0; @@ -327,8 +298,7 @@ int ref_sample_topk(const RadArgs* a, RadStream) { st_int(ci->dtype, ci->data, ib + r * is, ok ? pi : -1); stt(cv, vb + r * vs, ok ? pv : -INFINITY); if (!pp) continue; - /* 0xffffffff is the hole, which the merge tests as a negative signed id -- the same - * convention cand_idx carries as -1. */ + /* 0xffffffff is the hole (a negative signed id to the merge, -1 in cand_idx). */ uint32_t bits; const float val = ok ? pv : -INFINITY; std::memcpy(&bits, &val, 4); @@ -353,9 +323,9 @@ static int narrow(const RadArgs* a, Narrow which) { const int64_t M = numel(ci) / n_cand; if (M <= 0 || numel(cv) < M * n_cand) return RAD_E_SHAPE; Rows R; - RAD_REF_TRY(rows_of(pr, M, &R)); + RAD_REF_TRY(param_rows(pr, M, &R)); - #pragma omp parallel for schedule(static) + REF_PAR_FOR(M * n_cand * 4) for (int64_t m = 0; m < M; ++m) { const RadSampleParams& sp = R.p[m]; if (sp.flags & RAD_SP_GREEDY) continue; @@ -378,9 +348,8 @@ static int narrow(const RadArgs* a, Narrow which) { if (which == NR_MINP) { const float p = sp.min_p; if (!(p > 0.0f)) continue; - /* Keep everything within a factor p of the most likely candidate. Comparing - * exp(v - max) against p is the same test as prob >= p * max_prob without forming the - * normaliser, which is one fewer pass and one fewer rounding. */ + /* Keep everything within a factor p of the most likely candidate: exp(v - max) >= p + * is prob >= p * max_prob without forming the normaliser. */ for (int64_t i = 0; i < n_cand; ++i) { if (!live(i)) continue; const float v = ldt(cv, vb + i * vs); @@ -390,7 +359,7 @@ static int narrow(const RadArgs* a, Narrow which) { continue; } - /* The remaining three all need the normalised probabilities. */ + /* The other three stages need normalised probabilities. */ float sum = 0.0f; for (int64_t i = 0; i < n_cand; ++i) if (live(i)) sum += ref_exp(ldt(cv, vb + i * vs) - mx); @@ -399,19 +368,15 @@ static int narrow(const RadArgs* a, Narrow which) { if (which == NR_TOPP) { const float p = sp.top_p; if (!(p < 1.0f) || !(p > 0.0f)) continue; - /* The candidates arrive in DESCENDING order from sample_topk and this op does not - * re-sort them. Keep the shortest prefix whose cumulative probability reaches p, and - * always keep at least one -- a p small enough to select nothing still has to produce - * a token. */ + /* Candidates arrive in descending order from sample_topk and are not re-sorted. Keep + * the shortest prefix whose cumulative probability reaches p, at least one. */ float cum = 0.0f; bool done = false; - int64_t kept = 0; for (int64_t i = 0; i < n_cand; ++i) { if (!live(i)) continue; if (done) { drop(i); continue; } cum += ref_exp(ldt(cv, vb + i * vs) - mx) * inv; - ++kept; - if (cum >= p && kept >= 1) done = true; + if (cum >= p) done = true; } continue; } @@ -420,51 +385,42 @@ static int narrow(const RadArgs* a, Narrow which) { const float p = sp.typical_p; if (!(p < 1.0f) || !(p > 0.0f)) continue; /* Locally typical sampling: keep the candidates whose surprisal -log(prob) is closest - * to the distribution's entropy, until their mass reaches p. The candidate order is - * by probability and this order is by |surprisal - H|, so the two disagree and the - * selection is a threshold on the distance rather than a prefix. - * - * Two passes and no sort: find the distance at which the mass reaches p, then keep - * everything at or below it. Ties are kept, which can overshoot p slightly -- the - * alternative is an order that depends on the candidate index. */ + * to the entropy until their mass reaches p. That order differs from the candidate + * order, so this is a threshold on |surprisal - H| rather than a prefix: find the + * smallest distance whose mass reaches p, keep everything at or below it. Ties are + * kept (may overshoot p) so the result does not depend on candidate index. */ + /* q[i] is a live candidate's probability (0 for a dropped one), d[i] its distance. */ + std::vector q((size_t)n_cand, 0.0f), d((size_t)n_cand, 0.0f); float H = 0.0f; for (int64_t i = 0; i < n_cand; ++i) { if (!live(i)) continue; - const float q = ref_exp(ldt(cv, vb + i * vs) - mx) * inv; - if (q > 0.0f) H -= q * ref_log(q); + q[(size_t)i] = ref_exp(ldt(cv, vb + i * vs) - mx) * inv; + if (q[(size_t)i] > 0.0f) H -= q[(size_t)i] * ref_log(q[(size_t)i]); } - /* The smallest distance threshold whose mass reaches p, found by scanning the - * distances that actually occur. n_cand is a thousand at most. */ + for (int64_t i = 0; i < n_cand; ++i) + if (q[(size_t)i] > 0.0f) d[(size_t)i] = ref_abs(-ref_log(q[(size_t)i]) - H); + /* Scan the distances that occur (n_cand is at most about a thousand). */ float cut = 0.0f; bool have_cut = false; for (int64_t c = 0; c < n_cand; ++c) { - if (!live(c)) continue; - const float qc = ref_exp(ldt(cv, vb + c * vs) - mx) * inv; - if (!(qc > 0.0f)) continue; - const float dc = ref_abs(-ref_log(qc) - H); + if (!(q[(size_t)c] > 0.0f)) continue; float mass = 0.0f; - for (int64_t i = 0; i < n_cand; ++i) { - if (!live(i)) continue; - const float q = ref_exp(ldt(cv, vb + i * vs) - mx) * inv; - if (!(q > 0.0f)) continue; - if (ref_abs(-ref_log(q) - H) <= dc) mass += q; + for (int64_t i = 0; i < n_cand; ++i) + if (q[(size_t)i] > 0.0f && d[(size_t)i] <= d[(size_t)c]) mass += q[(size_t)i]; + if (mass >= p && (!have_cut || d[(size_t)c] < cut)) { + cut = d[(size_t)c]; + have_cut = true; } - if (mass >= p && (!have_cut || dc < cut)) { cut = dc; have_cut = true; } } if (!have_cut) continue; - for (int64_t i = 0; i < n_cand; ++i) { - if (!live(i)) continue; - const float q = ref_exp(ldt(cv, vb + i * vs) - mx) * inv; - if (!(q > 0.0f) || ref_abs(-ref_log(q) - H) > cut) drop(i); - } + for (int64_t i = 0; i < n_cand; ++i) + if (live(i) && (!(q[(size_t)i] > 0.0f) || d[(size_t)i] > cut)) drop(i); continue; } - /* XTC -- "exclude top choices". With probability `xtc_probability`, DROP every candidate - * above `xtc_threshold` except the least likely of them, which is the opposite of every - * other stage here and is the point: it removes the obvious continuations and leaves the - * interesting one. The draw is per row and comes from the row's own stream, so it - * reproduces. */ + /* XTC ("exclude top choices"): with probability `xtc_probability`, drop every candidate + * above `xtc_threshold` except the least likely of them, removing the obvious + * continuations. The draw comes from the row's own stream, so it reproduces. */ { if (!(sp.xtc_probability > 0.0f) || !(sp.xtc_threshold > 0.0f)) continue; if (rad_sample_uniform01(sp.seed ^ RAD_SAMPLE_KEY_XTC, sp.pos) >= sp.xtc_probability) @@ -477,8 +433,7 @@ static int narrow(const RadArgs* a, Narrow which) { ++n_above; } } - /* Nothing to do unless at least two candidates clear the threshold: dropping the only - * one would leave the row without its own choice. */ + /* Needs at least two candidates above the threshold. */ if (n_above < 2) continue; for (int64_t i = 0; i < n_cand; ++i) { if (!live(i) || i == last_above) continue; @@ -497,15 +452,12 @@ int ref_sample_typical(const RadArgs* a, RadStream) { return narrow(a, NR_TYPICA int ref_sample_xtc(const RadArgs* a, RadStream) { return narrow(a, NR_XTC); } /* ------------------------------------------------------------------ sample_mask */ -/* Where a GBNF grammar lands. The state machine stays on host and what crosses is a token bitmask - * per sequence -- 19 KiB at a 151K vocab, cheap enough to upload every step (spec §13). +/* GBNF grammar masking. The state machine stays on the host; a token bitmask per sequence (19 KiB + * at a 151K vocab) is uploaded every step (spec §13). * - * A SET BIT MEANS ALLOWED. That polarity has to be stated: a grammar produces a set of admissible - * tokens, and the mask is that set rather than its complement. Word w bit b covers token - * 32*w + b, least significant bit first. + * A set bit means allowed. Word w bit b covers token 32*w + b, least significant bit first. * - * The row says WHICH mask row it uses, because a constrained sequence and an unconstrained one - * share the plane and `mask_row` is -1 for the second. */ + * Each row names its mask row; unconstrained rows share the plane with `mask_row` -1. */ int ref_sample_mask(const RadArgs* a, RadStream) { if (!have(a, 3)) return RAD_E_INVAL; const RadTensor *lg = &a->t[0], *pr = &a->t[1], *bm = &a->t[2]; @@ -514,12 +466,12 @@ int ref_sample_mask(const RadArgs* a, RadStream) { const int64_t M = numel(lg) / n_vocab; if (M <= 0) return RAD_E_SHAPE; Rows R; - RAD_REF_TRY(rows_of(pr, M, &R)); + RAD_REF_TRY(param_rows(pr, M, &R)); const int64_t words = (n_vocab + 31) / 32; const int64_t mask_rows = numel(bm) / (words > 0 ? words : 1); if (mask_rows <= 0) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(M * n_vocab) for (int64_t m = 0; m < M; ++m) { const RadSampleParams& sp = R.p[m]; if (!(sp.flags & RAD_SP_MASK)) continue; @@ -544,9 +496,9 @@ int ref_sample_pick(const RadArgs* a, RadStream) { const int64_t M = numel(ci) / n_cand; if (M <= 0 || numel(cv) < M * n_cand || numel(tok) < M) return RAD_E_SHAPE; Rows R; - RAD_REF_TRY(rows_of(pr, M, &R)); + RAD_REF_TRY(param_rows(pr, M, &R)); - #pragma omp parallel for schedule(static) + REF_PAR_FOR(M * n_cand * 4) for (int64_t m = 0; m < M; ++m) { /* A greedy row's token is the argmax's, already written. */ if (R.p[m].flags & RAD_SP_GREEDY) continue; @@ -569,14 +521,10 @@ int ref_sample_pick(const RadArgs* a, RadStream) { const float inv = sum > 0.0f ? 1.0f / sum : 0.0f; const float u = rad_sample_uniform01(R.p[m].seed ^ RAD_SAMPLE_KEY_PICK, R.p[m].pos); - /* The inverse CDF, walked in candidate order, accumulating in f32. The fallback is the - * last candidate whose logit is ABOVE -infinity: `u` is strictly below 1 and the - * probabilities sum to 1 in exact arithmetic, but they do not in f32, and a draw that - * falls through the last comparison must still produce a token -- one the distribution - * allows. top-k fills its width from a masked row, so the grammar's forbidden tokens sit - * at the tail of the set at -infinity, and falling through to one of them emits a token - * the grammar ruled out. Such a candidate adds nothing to `cum`, so the comparison never - * chooses one either. */ + /* Inverse CDF in candidate order, accumulating in f32. The f32 probabilities may sum to + * less than u < 1, so a draw that falls through takes the last candidate above + * -infinity. Grammar-masked tokens sit at the set's tail at -infinity; they add nothing to + * `cum` and must never be the fallback. */ float cum = 0.0f; int64_t chosen = -1, last = -1; for (int64_t i = 0; i < n_cand; ++i) { @@ -593,8 +541,7 @@ int ref_sample_pick(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------------ sample_argmax */ -/* Greedy, ties to the LOWER token id -- the same tie rule the top-k selection uses, so a greedy - * step and a top-1 step cannot disagree. */ +/* Greedy, ties to the lower token id, as in top-k selection, so greedy and top-1 agree. */ int ref_sample_argmax(const RadArgs* a, RadStream) { if (!have(a, 3)) return RAD_E_INVAL; const RadTensor *lg = &a->t[0], *tok = &a->t[2]; @@ -603,7 +550,7 @@ int ref_sample_argmax(const RadArgs* a, RadStream) { const int64_t M = numel(lg) / n_vocab; if (M <= 0 || numel(tok) < M) return RAD_E_SHAPE; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(M * n_vocab) for (int64_t m = 0; m < M; ++m) { const int64_t lb = rowoff(lg, m, n_vocab), ls = laststride(lg); float best = -INFINITY; @@ -618,13 +565,12 @@ int ref_sample_argmax(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------------ sample_logprobs */ -/* THE RAW DISTRIBUTION'S SUMMARY, for a row that asks for logprobs (RAD_SP_LOGPROBS): the row's - * maximum, the sum of exp(l - max) over it, and its k largest as (id, logit) pairs, descending, - * ties to the lower id, ids as floats (exact below 2^24). Read off the logits before any sampling - * stage has touched them, which is the distribution OpenAI's and llama-server's logprobs report. - * A row without the flag is not written. Under a split vocabulary the ids are global - * (+ `vocab_off`) and the host merges the ranks' summaries; a slot past the row's width is id -1, - * logit -infinity. The sum is taken in double here: this is the oracle. */ +/* A summary of the raw distribution for rows with RAD_SP_LOGPROBS: the max, the sum of + * exp(l - max), and the k largest as (id, logit) pairs, descending, ties to the lower id, ids as + * floats (exact below 2^24). Read before any sampling stage, as OpenAI's and llama-server's + * logprobs report. Rows without the flag are not written. Under a split vocabulary ids are global + * (+ `vocab_off`) and the host merges ranks; an unfilled slot is id -1, logit -infinity. The sum is + * in double. */ int ref_sample_logprobs(const RadArgs* a, RadStream) { if (!have(a, 3)) return RAD_E_INVAL; const RadTensor *lg = &a->t[0], *pr = &a->t[1], *st = &a->t[2]; @@ -636,9 +582,9 @@ int ref_sample_logprobs(const RadArgs* a, RadStream) { const int64_t w = 2 + 2 * k; if (M <= 0 || numel(st) < M * w) return RAD_E_SHAPE; Rows R; - RAD_REF_TRY(rows_of(pr, M, &R)); + RAD_REF_TRY(param_rows(pr, M, &R)); - #pragma omp parallel for schedule(static) + REF_PAR_FOR(M * n_vocab * (k + 2)) for (int64_t m = 0; m < M; ++m) { if (!(R.p[m].flags & RAD_SP_LOGPROBS)) continue; const int64_t lb = rowoff(lg, m, n_vocab), ls = laststride(lg); @@ -670,15 +616,13 @@ int ref_sample_logprobs(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------------ sample_merge_topk */ -/* THE VOCAB-PARALLEL MERGE. lm_head is vocab-sharded, so each rank runs top-k over ITS OWN shard - * and the candidate sets are all-gathered -- k * world_size pairs, 2 KiB at k=64 and world_size=4, - * against the ~77 MiB a full-logits gather would move (spec §9, §13). +/* The vocab-parallel merge. lm_head is vocab-sharded, so each rank runs top-k over its shard and + * the candidate sets are all-gathered: k * world_size pairs, 2 KiB at k=64 and world_size=4, versus + * ~77 MiB for a full-logits gather (spec §9, §13). * - * `gathered` is [M, world_size * n_cand] pairs of (token id, logit) as raw u32 words: the token id - * is already GLOBAL, because each rank adds its own vocab offset before the gather -- a merge that - * had to know the offsets would need the shard layout, which is the caller's business and not a - * kernel's. The output is the same descending candidate set the single-rank path produces, so - * every stage after it is identical. */ + * `gathered` is [M, world_size * n_cand] (token id, logit) pairs as raw u32 words, ids already + * global. The output is the single-rank path's descending candidate set, so later stages are + * unchanged. */ int ref_sample_merge_topk(const RadArgs* a, RadStream) { if (!have(a, 4)) return RAD_E_INVAL; const RadTensor *gt = &a->t[0], *pr = &a->t[1], *ci = &a->t[2], *cv = &a->t[3]; @@ -687,11 +631,9 @@ int ref_sample_merge_topk(const RadArgs* a, RadStream) { const int64_t M = numel(ci) / n_cand; if (M <= 0 || numel(cv) < M * n_cand) return RAD_E_SHAPE; Rows R; - RAD_REF_TRY(rows_of(pr, M, &R)); - /* Each gathered entry is a (u32 id, f32 logit) PAIR IN ONE BUFFER, so the two halves have - * different types and the buffer's dtype can only be one of them. It is u32, and the logit is - * read by BIT PATTERN: `ldt` on a u32 buffer would convert 0x40800000 to 1.08e9 rather than - * to 4.0. A word-typed buffer is the only way the builder can express a packed pair. */ + RAD_REF_TRY(param_rows(pr, M, &R)); + /* Each entry packs a u32 id and an f32 logit in a u32 buffer, so the logit is read by bit + * pattern (`ldt` would convert 0x40800000 to 1.08e9, not 4.0). */ if (gt->dtype != RAD_U32 && gt->dtype != RAD_I32) return RAD_E_DTYPE; const int64_t per_row = numel(gt) / M; const int64_t n_in = per_row / 2; @@ -703,22 +645,18 @@ int ref_sample_merge_topk(const RadArgs* a, RadStream) { return f; }; - #pragma omp parallel for schedule(static) + REF_PAR_FOR(M * n_in * 4) for (int64_t m = 0; m < M; ++m) { const int64_t gb = rowoff(gt, m, per_row), gs = laststride(gt); const int64_t ib = rowoff(ci, m, n_cand), is = laststride(ci); const int64_t vb = rowoff(cv, m, n_cand), vs = laststride(cv); - /* Selection sort over the gathered pairs, n_cand times. n_in is world_size * n_cand and - * n_cand is a thousand at most, so this is the same O(n*k) the single-rank top-k already - * pays and it needs no scratch. Ties to the lower token id, which is the tie rule every - * other selection here uses. */ - /* THE ROW'S OWN top_k, RE-APPLIED. Every rank ran top-k over its own shard before the - * gather, so the merged set holds up to world_size * k candidates where the request asked - * for k, and no stage after this one narrows again. That is a different sampling support, - * and at k = 1 it is a different ANSWER: a greedy row is staged at top_k = 1 exactly so - * this chain returns the argmax, and with world_size candidates alive sample_pick draws - * among them against the request's seed. 0 or negative means the whole width. */ + /* Selection sort over the gathered pairs, n_cand times, ties to the lower id: O(n*k) as + * in single-rank top-k, no scratch. + * + * The row's own top_k is re-applied: the gather holds up to world_size * k candidates and + * nothing later narrows them, which at top_k 1 would let sample_pick draw among several + * instead of returning the argmax. <= 0 means the whole width. */ const int32_t tk = R.p[m].top_k; const int64_t keep = (R.p[m].flags & RAD_SP_GREEDY) ? 0 : (tk > 0 && (int64_t)tk < n_cand) ? (int64_t)tk : n_cand; @@ -734,7 +672,8 @@ int ref_sample_merge_topk(const RadArgs* a, RadStream) { float best = -INFINITY; int64_t best_id = -1; for (int64_t j = 0; j < n_in; ++j) { - const int64_t id = (int64_t)(uint32_t)ld_int(gt->dtype, gt->data, gb + 2 * j * gs); + /* As int32, so the 0xffffffff hole reads as -1 and is skipped. */ + const int64_t id = (int32_t)ld_int(gt->dtype, gt->data, gb + 2 * j * gs); const float v = bits_to_f32(ld_int(gt->dtype, gt->data, gb + (2 * j + 1) * gs)); if (id < 0) continue; const bool after = v < taken_v || (v == taken_v && id > taken_i); diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index fb9532dd..a18ae8dd 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -2,90 +2,68 @@ * it. libref's implementation of `RadKernelInfo::opd_shape` (rad_abi.h), for every op this * plugin registers. * - * ============================== WHY THIS LIVES HERE ============================== + * ============================== Why this lives here ============================== * - * A tool that wants to CALL an op cold -- which a correctness check and a benchmark both do -- has - * to size its buffers somehow, and an op's schema names its operands and their roles but not their - * extents. The alternative to this hook is a hand-written table inside `tools/` (opshapes.h), and - * its own header says why that is the wrong home: it can only describe the ops whoever wrote the - * table had heard of, it cannot be extended by anyone who does not patch the engine, and it is the - * one place a tool knows something about an op. The component that knows an operand's extent is the - * one that reads it. This file is ref answering for the whole conventional vocabulary, so an op - * that stays inside docs/OPS.md is describable even when the kernel under test is not. + * A tool that calls an op cold (a correctness check, a benchmark) must size its buffers, and a + * schema names operands and roles but not extents. A hand-written table in `tools/` (opshapes.h) + * could only describe ops its author knew and could not be extended without patching the engine. + * The component that reads an operand knows its extent; this file answers for the whole + * conventional vocabulary, so any op in docs/OPS.md is describable even when the kernel under test + * is not. * - * ============================== ONE FUNCTION PER ROW, NAMED AFTER THE LAUNCH ============== + * ============================== One function per row, named after the launch ============== * - * `RadShapeFn` does not carry the op name -- it gets the resolved parameter list and an operand - * index and nothing else -- so a single shared function would have to recover the op from a - * parameter, and no op in this vocabulary carries its own name as one. The alternative is a small - * per-op function in every registry row, and that is what this file supplies: for every entry point - * `ref_X` there is a `ref_X_shape` beside it, so ref_registry.cpp's ROW() macro pastes the second - * from the first (`fn ## _shape`) and no row names it explicitly. The 1:1 naming is load-bearing: - * adding an op to the registry is one row plus one host implementation plus one shape function - * whose name the macro already demands, so a new op that forgets to describe itself does not link. + * `RadShapeFn` gets only the resolved parameters and an operand index, not the op name. So every + * entry point `ref_X` has a `ref_X_shape`, which ref_registry.cpp's ROW() macro pastes as + * `fn ## _shape`; a new op without a description fails to link. * - * ============================== THE COUNT IS CHECKED, NOT ASSUMED ============================== + * ============================== The count is checked ============================== * - * A description must emit exactly as many operands as the schema declares, and that check is what - * catches a description that has drifted from the schema it describes -- an op that grows an - * optional operand and a description that does not follow leave the op silently skipped by a tool - * whose whole job is to say what was checked. Padding with a guess would hide the drift behind a - * number that looks like a result. + * A description must emit exactly as many operands as the schema declares; that catches a + * description that drifted from its schema (which would otherwise leave the op silently skipped). + * The hook is called per operand, so each function fills a local array with the whole list and + * hands out the requested entry, and `Opd::finish` compares the length with + * `RadOpSchema::n_operands` from this plugin's schema table. A mismatch returns RAD_E_SHAPE, a bug + * here or in the schema; RAD_E_UNSUPPORTED means the geometry lacks what the op needs, which a + * caller skips and counts. * - * The hook is called one operand at a time, so the property has to be rebuilt: every function below - * fills a small local array with the WHOLE operand list and then hands out the one that was asked - * for, and `Opd::finish` compares the length against `RadOpSchema::n_operands` read out of this - * plugin's own schema table. A mismatch returns RAD_E_SHAPE and not RAD_E_UNSUPPORTED, - * deliberately: RAD_E_UNSUPPORTED is "this geometry does not carry what the op needs" and is a - * correct answer a caller skips and counts, while a count mismatch is a BUG in this file or in the - * schema and deserves a distinguishable status. + * ============================== What is in an operand ============================== * - * ============================== WHAT IS IN AN OPERAND ============================== - * - * The fill domain matters as much as the extent (rad_abi.h's own comment says the same at length): + * The fill domain matters as much as the extent (see rad_abi.h): * * * A gated-delta-net `g` is an intra-chunk cumulative sum of log-decays: non-increasing and - * never positive. The scan forms e^{g_i - g_j} with j <= i, which is <= 1 ONLY because g is - * monotone; handed normals the oracle overflows to 2e38 while the kernel does something else, - * and the comparison then measures the test rather than the kernel. - * * `beta` is a sigmoid output and lives in (0, 1). `A` is a chunk's triangular inverse and is - * zero above the diagonal within a chunk -- a dense random A puts two implementations on - * opposite sides of a convention (whether the strictly-upper part is read at all) that they - * never disagree about on a real one. - * * An index operand's RANGE is part of its meaning. A KV slot indexes n_blocks * block_size - * positions and a block-table entry indexes n_blocks, and neither is any operand's dim 0; - * drawing either from the wrong range tests the kernel's out-of-range handling and calls the - * result correctness. - * * A SCATTER destination has to be unique. Two tokens drawn onto one slot make the store a race - * and two implementations resolve it differently -- ref runs the token loop under OpenMP and a - * device kernel runs a workgroup a token -- so the comparison would measure the scheduler. A - * read-side index (a gather row, a block-table entry) may repeat and does. - * * `seqused` is a CONSTANT and not a draw. A random context length shorter than the query makes - * a causal attention read a prefix that does not exist, which both implementations would then - * agree about while neither computed what the model asks for. - * * An OPTIONAL operand a description deliberately does not pass still needs an entry -- the - * count check above is what catches drift -- so absence has a spelling, and a null - * RadTensor.data is what the ABI already means by it. + * never positive. The scan's e^{g_i - g_j}, j <= i, is <= 1 only because g is monotone; normal + * draws overflow the oracle to 2e38. + * * `beta` is a sigmoid output in (0, 1). `A` is a chunk's triangular inverse, zero above the + * diagonal within a chunk; a dense random A exposes a convention (whether the upper part is + * read) that never matters on real data. + * * An index operand's range is part of its meaning: a KV slot indexes n_blocks * block_size + * positions and a block-table entry n_blocks, neither being any operand's dim 0. Drawing from + * the wrong range tests out-of-range handling instead. + * * A scatter destination must be unique: two tokens on one slot are a race that ref (OpenMP over + * tokens) and a device kernel resolve differently. Read-side indices (gather rows, block-table + * entries) may repeat. + * * `seqused` is a constant, not a draw: a context shorter than the query makes causal attention + * read a nonexistent prefix. + * * A sampler's `params` rows are requests: a stage gated by a flag, a history window or a mask + * row does work only where those integer fields are what a request sets. Its token history + * must repeat itself, or DRY never finds a repeat to penalise. + * * An optional operand deliberately not passed still needs an entry for the count check; a null + * RadTensor.data marks absence, as in the ABI. * - * ============================== WHAT THIS FILE MAY NOT ASSUME ============================== + * ============================== What this file may use ============================== * - * A kernel plugin links rad_abi and NOTHING ELSE (libref/CMakeLists.txt), so anything of core's - * that is not in a header is unreachable: RAD_DEBUG is core's, and ref_common.h makes that trade. + * A kernel plugin links only rad_abi (libref/CMakeLists.txt), so core symbols outside headers + * (e.g. RAD_DEBUG) are unreachable. Header-only ABI helpers are available: `rad_dtype_parse` and + * `rad_dtype_bytes` (rad_types.h) and `rad_param_*` (rad_plugin.h). Use the ABI's version first; + * `gi` below is the one local variant, and says why. * - * WHAT IS REACHABLE IS MORE THAN THE LINK RULE SUGGESTS. `rad_dtype_parse` and `rad_dtype_bytes` - * are `static inline` in rad_types.h and `rad_param_*` in rad_plugin.h -- header-only, which is - * the whole point of a header-only ABI -- so they compile into the plugin like any other inline. - * The rule is: reach for the ABI's version first, and write a local one only where the ABI - * genuinely has no answer. `gi` below is the one such place, and it says why. - * - * `rad_kernel_schema_count` / `rad_kernel_schema_at` ARE this plugin's own exports, defined in - * ref_registry.cpp beside the table they read, so the count check costs no coupling at all. + * `rad_kernel_schema_count` / `rad_kernel_schema_at` are this plugin's own exports + * (ref_registry.cpp), so the count check adds no coupling. */ #include "ref_ops.h" -/* rad_param_find / rad_param_getdim / rad_param_gets / rad_dtype_parse. Included by name rather - * than leaned on through ref_ops.h, because what this file needs from the ABI is exactly this - * header. */ +/* rad_param_find / rad_param_getdim / rad_param_gets / rad_dtype_parse. */ #include "rad_plugin.h" #include "rad_sample.h" @@ -97,16 +75,13 @@ namespace { /* ================================================================== parameters - * NOT ref_common.h's p_int(): those take a RadArgs, and this hook is handed a bare RadParam list - * with no tensors and no scratch -- it is called before anything is allocated. Same readings - * though, including the RAD_P_RANGE one: a caller that has not collapsed a range yet is describing - * the band's upper bound, which is the extent the arena has to be sized for. */ -/* rad_param_getdim IS the int-or-range reading above. What stays local is the ONE deliberate - * leniency on top of it: a STRING spelling of an integer is accepted, because this is the oracle - * and a geometry it can describe is a case that gets checked rather than skipped. libr4d's shape - * hooks refuse the same spelling on purpose -- its launches read integers as RAD_P_INT only, so - * describing a geometry its launch would then refuse turns a skip into a failure. The two - * libraries disagreeing here is intended; both saying so where they differ is the point. */ + * Not ref_common.h's p_int(), which takes a RadArgs; this hook gets a bare RadParam list before + * anything is allocated. rad_param_getdim gives the same int-or-range reading (an uncollapsed range + * describes the band's upper bound, the extent the arena is sized for). + * + * The one local leniency: a string spelling of an integer is accepted, so the oracle checks rather + * than skips such a geometry. libr4d's shape hooks deliberately refuse it, since its launches read + * RAD_P_INT only; the difference is intended. */ static int64_t gi(const RadParam* p, int n_p, const char* k, int64_t dflt) { const RadParam* q = rad_param_find(p, n_p, k); if (q && q->kind == RAD_P_STR && q->sval) return (int64_t)std::strtoll(q->sval, nullptr, 10); @@ -118,20 +93,12 @@ static const char* gs(const RadParam* p, int n_p, const char* k) { } /* ================================================================== dtype names - * THE ABI's PARSER, deliberately, rather than a table of spellings here. `rad_dtype_parse` is - * `static inline` in rad_types.h, which rad_abi.h includes, which is the one header this plugin - * compiles against -- so it is reachable and it is the single definition. A local copy would mean - * a dtype added to the ABI reads as RAD_DT_INVALID here and correctly everywhere else. */ + * The ABI's parser, so a dtype added to the ABI is understood here too. */ static uint32_t dt_parse(const char* n) { return rad_dtype_parse(n); } -/* THE ACTIVATION DTYPE, and the fallback matters. Several ops carry no `dtype` parameter at all -- - * `rope` names a `mode` and a `theta` and nothing about the width, because the tensor it rotates in - * place is whatever the caller declared -- and falling back to f32 there manufactures an f32 - * activation, which a shim that reads a bf16 rotation then refuses ON DTYPE: a check that reports - * FAIL on a kernel the engine runs correctly. `q_dtype` and `kv_dtype` are attention's spellings of - * the same thing, and bf16 is what every activation in this project is when nothing says otherwise. - * A dtype string the table does not know -- "w4a8", "fp8a8", the QUANTISATION SCHEME rather than an - * element width -- lands on bf16 for the same reason. */ +/* The activation dtype: `dtype`, else attention's `q_dtype` / `kv_dtype`, else bf16. Some ops + * (e.g. `rope`) carry no dtype parameter, and an f32 fallback would make a bf16-only kernel fail on + * dtype. A quantisation-scheme string ("w4a8", "fp8a8") also lands on bf16. */ static uint32_t act_dt(const RadParam* p, int n_p) { const char* s = gs(p, n_p, "dtype"); if (!s) s = gs(p, n_p, "q_dtype"); @@ -141,10 +108,8 @@ static uint32_t act_dt(const RadParam* p, int n_p) { } /* ================================================================== the operand list - * Every function below builds the WHOLE list and then hands out the entry that was asked for. That - * is what lets the count be checked against the schema (see the header), and it costs a couple of - * hundred bytes of stack per call on a hook that is called once per operand before anything is - * allocated. */ + * Each function builds the whole list and hands out the requested entry, so the count can be + * checked against the schema (see the header). */ enum { REF_MAX_OPD = 24 }; /* the widest schema here is gdn_conv_prep's sixteen */ struct Opd { @@ -158,9 +123,7 @@ struct Opd { RadOpdDesc& d = v[n++]; std::memset(&d, 0, sizeof d); d.fill = (uint32_t)RAD_FILL_NORMAL; - /* -1 is the ABI's "draw", and it is written on EVERY descriptor rather than left to the - * caller's zeroing: a caller that memsets the struct and does not pre-set this field would - * read a 0 as "the constant zero", which is a different operand. */ + /* -1 is the ABI's "draw"; set explicitly because a zeroed field means "the constant 0". */ d.idx_const = -1; return &d; } @@ -177,8 +140,8 @@ struct Opd { /* An ordinary float operand: standard normals. */ void t(uint32_t dt, std::initializer_list s) { shape(push(), dt, s); } - /* A float operand whose DOMAIN is narrower than a normal draw -- a sigmoid gate, a monotone - * log-decay cumsum, a chunk-triangular factor. `chunk` is the width the reset happens at. */ + /* A float operand whose domain is narrower than a normal draw (a sigmoid gate, a monotone + * log-decay cumsum, a chunk-triangular factor). `chunk` is the reset width. */ void t_fill(uint32_t dt, std::initializer_list s, uint32_t fill, int64_t chunk) { RadOpdDesc* d = push(); shape(d, dt, s); @@ -186,22 +149,10 @@ struct Opd { d->fill_chunk = chunk; } - /* An index operand. `max` is the EXCLUSIVE upper bound of the draw and 0 means "the leading - * extent of the previous operand", which is the common case and saves every gather from - * restating it. `konst` >= 0 makes every element that value instead. */ - void t_idx(std::initializer_list s, int64_t max, int64_t konst, uint32_t flags) { - RadOpdDesc* d = push(); - shape(d, (uint32_t)RAD_I32, s); - d->fill = (uint32_t)RAD_FILL_INDEX; - d->idx_max = max; - d->idx_const = konst; - d->flags = flags; - } - - /* AN INDEX OPERAND THAT IS NOT i32. `t_idx` hardcodes the index dtype, which is right for a - * gather row or a block-table entry and wrong for a WEIGHT whose values happen to be sizes or - * offsets: those are i64 in every container and every plugin refuses anything else by name, so - * describing one as i32 makes the op refuse its own description. */ + /* An index operand of dtype `dt`. `max` is the exclusive upper bound of the draw; 0 means the + * previous operand's leading extent. `konst` >= 0 makes every element that value. A dtype + * other than i32 is for weights whose values are sizes or offsets (those are i64 in every + * container and plugins refuse any other dtype) and for a byte plane of marks. */ void t_idx_dt(uint32_t dt, std::initializer_list s, int64_t max, int64_t konst, uint32_t flags) { RadOpdDesc* d = push(); @@ -211,8 +162,11 @@ struct Opd { d->idx_const = konst; d->flags = flags; } + void t_idx(std::initializer_list s, int64_t max, int64_t konst, uint32_t flags) { + t_idx_dt((uint32_t)RAD_I32, s, max, konst, flags); + } - /* An OPTIONAL operand this description deliberately does not pass. */ + /* An optional operand this description deliberately does not pass. */ void skip() { RadOpdDesc* d = push(); d->flags = (uint32_t)RAD_OPD_F_ABSENT; @@ -221,9 +175,7 @@ struct Opd { int finish(const char* op, int operand, RadOpdDesc* out) const; }; -/* How many operands the schema declares for this op, out of this plugin's own table. -1 if the op - * is not ours, which cannot happen for a row that named one of these functions but is answered - * rather than assumed. */ +/* The operand count this plugin's schema declares for `op`, or -1 if the op is not ours. */ static int schema_operands(const char* op) { const int n = rad_kernel_schema_count(); for (int i = 0; i < n; ++i) { @@ -236,14 +188,11 @@ static int schema_operands(const char* op) { int Opd::finish(const char* op, int operand, RadOpdDesc* out) const { if (over) return RAD_E_SHAPE; const int want = schema_operands(op); - /* THE DESCRIPTION AND THE SCHEMA DISAGREE. That is a bug in one of them, and answering the - * operands that do line up would hide it behind a number that looks like a result. */ + /* Description and schema disagree: a bug in one of them. */ if (want != n) return RAD_E_SHAPE; if (operand < 0 || operand >= n || !out) return RAD_E_SHAPE; - /* A ZERO OR NEGATIVE EXTENT means the geometry did not carry a parameter this description - * needed -- an `n` that was never set, a head count that is not in the schema. That is a - * DECLINE and not a bug: the caller skips and counts it, which is the honest outcome, because a - * tool that invents an extent tests the kernel's bounds handling and calls it correctness. */ + /* A non-positive extent means the geometry lacks a parameter this description needs: a + * decline (the caller skips and counts), not a bug. */ for (int i = 0; i < n; ++i) { if (v[i].flags & RAD_OPD_F_ABSENT) continue; if (v[i].rank == 0) return RAD_E_UNSUPPORTED; @@ -256,64 +205,50 @@ int Opd::finish(const char* op, int operand, RadOpdDesc* out) const { /* ================================================================== shared readings */ -/* The scale-stream granularity `quant_act_i8`, `quant_act_fp8` and `dequant` share, taken from the - * launch's own clamping (ref_quant.cpp) rather than restated: group <= 0 or wider than the row is - * ONE SCALE PER ROW, which is what every int8 GEMM in libr4d consumes, and anything else is - * ceil(n / group) groups. Note this is NOT the reading the `had_*` forms use -- there `group` is - * the Walsh-Hadamard rotation WIDTH and the scale is per row whatever it says. */ +/* The scale-stream group count shared by `quant_act_i8g`, `quant_act_fp8` and `dequant`, matching + * their launches (ref_quant.cpp): group <= 0 or wider than the row is one scale per row, otherwise + * ceil(n / group). Not the `had_*` reading, where `group` is the rotation width and the scale is + * per row. */ static int64_t scale_groups(int64_t n, int64_t group) { int64_t g = group; if (g <= 0 || g > n) g = n; return g > 0 ? (n + g - 1) / g : 0; } -/* THE GATED-DELTA-NET HEAD COUNTS, which are not parameters of any gdn op: the kernels read them - * off the operands, so no op names them and the resolved geometry does not carry them. A - * description that invented a head ratio would be describing a model nobody is running, so the - * whole family DECLINES unless the caller has put them in the parameter list under these names -- - * they come from the container's `linear_num_key_heads` / `linear_num_value_heads`, which is where - * the architecture plugin reads them from too. Absent, the caller skips and counts. */ +/* The gated-delta-net head counts. No gdn op has them as parameters (kernels read them off the + * operands), so the family declines unless the caller passes `n_head_k` / `n_head_v`, taken from + * the container's `linear_num_key_heads` / `linear_num_value_heads`. */ static bool gdn_heads(const RadParam* p, int n_p, int64_t* Hk, int64_t* Hv) { *Hk = gi(p, n_p, "n_head_k", 0); *Hv = gi(p, n_p, "n_head_v", 0); return *Hk > 0 && *Hv > 0; } -/* Sequences in the described batch. Not a parameter of anything either -- one sequence is what a - * cold call describes and what every recipe in opshapes.h assumed -- but a caller that wants a - * ragged batch can say so and the gdn and attention descriptions will follow. */ +/* Sequences in the described batch: 1 by default; a caller may pass `n_seq` for a ragged batch, + * which the gdn and attention descriptions follow. */ static int64_t n_seq_of(const RadParam* p, int n_p) { const int64_t s = gi(p, n_p, "n_seq", 1); return s > 0 ? s : 1; } -/* THE SAMPLER'S PER-ROW PARAMETER PLANE, one RadSampleParams per sampled position - * (abi/rad_sample.h). It is a BYTE BLOB viewed through a 32-bit dtype -- the builder can - * only say "this many words a row" -- and both this plugin and libr4d accept u32, i32 or f32 for - * it. +/* The sampler's per-row parameter plane, one RadSampleParams per sampled position + * (abi/rad_sample.h): a byte blob viewed through a 32-bit dtype; this plugin and libr4d accept u32, + * i32 or f32. * - * IT IS DESCRIBED AS f32, AND THAT IS A DELIBERATE CHOICE ABOUT CONTENT rather than about size. - * The struct is eleven floats and nine int32s, and the ABI's fill domains describe a BUFFER and - * not a struct, so there is no spelling for "fill this like a request". Drawn as f32 normals every - * float field -- temp, top_p, min_p, typical_p, the three penalties, the two XTC values -- lands in - * a plausible range, and a third to a half of the rows land inside the interval that makes their - * stage do work (temp > 0, 0 < top_p < 1, and so on), so `sample_temp`, `sample_topp`, - * `sample_minp`, `sample_typical` and `sample_xtc` are really exercised on some rows and identity - * on others, which is the mix a real batch has. + * Drawn with RAD_FILL_SAMPLE_PARAMS: each row is a request's settings, its flags agreeing with its + * fields, its history window inside the history plane and its `mask_row` a row of the bitmask + * plane, which the description passes as the fill's `fill_chunk` and `idx_max`. Row 0 switches + * every stage on, so a one-row case does work in each; every other row switches each stage on or + * leaves it at its identity at random, and a minority is greedy (rad_abi.h has the law). The + * history repeats itself (RAD_OPD_F_IDX_HISTORY), so the frequency penalty counts tokens more than + * once and DRY finds repeated suffixes to penalise. * - * WHAT IT CANNOT REACH, said plainly rather than left for someone to discover: the INTEGER fields - * come out as the bit patterns of those same normals, so `hist_off`, `hist_len` and `mask_row` are - * enormous, every op clamps them, and `sample_penalties`, `sample_dry` and `sample_mask` therefore - * take their "nothing to do for this row" branch. A pass on those three says the plumbing agrees, - * not that the arithmetic does. `flags` is a bit pattern as well, so roughly half the rows carry - * RAD_SP_GREEDY and every candidate stage treats them as having no candidates -- consistently in - * both implementations, so the comparison covers the other half. The alternative -- a word-typed - * draw -- is worse in both directions: it makes every float field a denormal or a NaN, and - * `1 / temp` an infinity. + * Described as f32: a tool that does not know the law draws normals, under which the float fields + * land in plausible ranges and the narrowing stages still work on some rows. A word-typed normal + * draw would make them denormals or NaN and `1 / temp` infinite. * - * u32 would also be invisible to the tools for a second reason: opshapes.cpp's rad_widen has no - * RAD_U32 case, so a u32 operand is compared as zeroes and every case passes vacuously. Every - * word-typed operand this file describes is therefore i32. */ + * Word-typed operands here are i32, never u32: opshapes.cpp's rad_widen has no RAD_U32 case, so a + * u32 operand would compare as zeroes and pass vacuously. */ static int64_t sample_params_words() { return (int64_t)(sizeof(RadSampleParams) / 4); /* 96 bytes, 24 words */ } @@ -353,11 +288,8 @@ int ref_rmsnorm_add_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* o return o.finish("rmsnorm_add", operand, out); } -/* The gated residual. `inject` and `group` DEFAULT ON, so a query that names neither describes the - * shape every trunk connection actually runs; passing either as 0 describes one of the two - * exceptions (the final mixer, and a read whose consumer is bf16). That is the same rule the - * schema's two optional parameters carry, said once more here because a cold caller reads this - * and not the schema. */ +/* The gated residual. `inject` and `group` default on (every trunk connection); 0 describes the + * final mixer or a bf16-consumer read (see the schema in ref_registry.cpp). */ int ref_hc_read_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); @@ -368,8 +300,7 @@ int ref_hc_read_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) const int64_t rotate = gi(p, n_p, "rotate", 0); Opd o; o.t(D, { M, hn }); /* h */ - /* The gain is F32 in the container, not the activation dtype: it is 10240 numbers read once a - * connection and the norm's arithmetic is f32 anyway, so narrowing it buys nothing. */ + /* The gain is f32 in the container, not the activation dtype. */ o.t((uint32_t)RAD_F32, { hn }); /* w */ o.t(D, { lr, hn }); /* mix_down */ o.t(D, { hn, lr }); /* mix_up */ @@ -421,8 +352,7 @@ int ref_mtp_enter_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out Opd o; o.t(D, { M, hc * n }); /* h, the wide stream */ o.t(D, { M, n }); /* e, the next token's embedding */ - /* Both gains are F32 in the container for the reason hc_read's is: read once a pass, - * multiplied in f32, and narrowing them buys nothing. */ + /* Both gains are f32 in the container, as hc_read's. */ o.t((uint32_t)RAD_F32, { hc * n }); /* w_h */ o.t((uint32_t)RAD_F32, { n }); /* w_e */ o.t(D, { n, n }); /* fc_h */ @@ -438,8 +368,8 @@ int ref_grid_embed_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou Opd o; o.t(D, { M, n }); /* x, INOUT */ o.t(D, { side * side, n }); /* table */ - /* row, column, height, width: drawn over the table's side, so some rows sit past their grid's - * last row and exercise the clamped taps as well as the interior. */ + /* row, column, height, width, drawn over the table's side so some rows exercise the clamped + * taps. */ o.t_idx({ 4, M }, side, -1, 0); return o.finish("grid_embed", operand, out); } @@ -462,17 +392,14 @@ int ref_layernorm_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out Opd o; o.t(D, { M, n }); /* x */ o.t(D, { n }); /* w */ - /* `b` is optional and is PASSED: a bias-free layer norm is the same code with one branch not - * taken, so describing the bias covers both and omitting it covers one. */ + /* `b` is optional but passed: the biased form covers strictly more code. */ o.t(D, { n }); /* b */ o.t(D, { M, n }); /* y */ return o.finish("layernorm", operand, out); } -/* add / mul share a schema and a description. An operand carrying exactly n elements against a - * taller output would broadcast along rows, and that is a second case rather than this one: `b` is - * described at full extent, because the broadcast form cannot be told from a shape bug once the - * buffers exist. */ +/* add / mul share a schema and a description. `b` is described at full extent; the row-broadcast + * form is not described, since its buffers cannot be told from a shape bug. */ static int binary_shape(const RadParam* p, int n_p, int operand, const char* op, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); @@ -520,8 +447,7 @@ int ref_seg_mean_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) int ref_pool_rows_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t n = gi(p, n_p, "n", 0), k = gi(p, n_p, "k", 0); - /* A band's bound need not be whole windows; the rows a pass issues always are, so the - * description takes the whole windows under it. */ + /* A band's bound need not be whole windows, but issued rows always are; round down. */ int64_t M = gi(p, n_p, "M", 0); if (k > 0) M -= M % k; if (M <= 0 || n <= 0 || k <= 0) return RAD_E_UNSUPPORTED; @@ -551,11 +477,10 @@ int ref_clamp_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { return o.finish("clamp", operand, out); } -/* THE AUDIO TOWER'S SEGMENTED OPS ARE DESCRIBED AS ONE SEGMENT. `cu_seqlens` counts in units +/* The audio tower's segmented ops are described as one segment. `cu_seqlens` counts in units * `cu_div` times finer than the operand's rows (a subsampled layer reads the pass's frame - * boundaries), so the description's rows are M / cu_div and a band that does not divide -- or, - * for a strided convolution, does not divide into whole output rows -- is declined rather than - * described into a refusal. */ + * boundaries), so the rows are M / cu_div; a band that does not divide (into whole output rows, for + * a strided convolution) is declined. */ int ref_conv2d_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), W = gi(p, n_p, "width", 0); @@ -569,13 +494,33 @@ int ref_conv2d_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t To = (T + 2 * pad - kh) / st + 1, Wo = (W + 2 * pad - kw) / st + 1; Opd o; o.t(D, { T, W * cin }); /* x */ - o.t(D, { cout, cin, kh, kw }); /* w */ + if (gi(p, n_p, "t_last", 0)) o.t(D, { cout, cin, kw, kh }); /* w, time last */ + else o.t(D, { cout, cin, kh, kw }); /* w */ o.t_idx({ 2 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */ o.t_idx({ T * vst }, 2, -1, 0); /* valid: 0 or 1 a row */ o.t(D, { To, Wo * cout }); /* y */ + o.t(D, { cout }); /* b */ return o.finish("conv2d", operand, out); } +int ref_conv2d_unfold_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), W = gi(p, n_p, "width", 0), cin = gi(p, n_p, "cin", 0); + const int64_t kh = gi(p, n_p, "kh", 0), kw = gi(p, n_p, "kw", 0); + const int64_t st = gi(p, n_p, "stride", 1), pad = gi(p, n_p, "pad", 0); + const int64_t cdiv = gi(p, n_p, "cu_div", 1), vst = gi(p, n_p, "valid_stride", 1); + if (M <= 0 || W <= 0 || st <= 0 || cdiv <= 0 || vst <= 0 || M % (cdiv * st)) + return RAD_E_UNSUPPORTED; + const int64_t T = M / cdiv; + const int64_t To = (T + 2 * pad - kh) / st + 1, Wo = (W + 2 * pad - kw) / st + 1; + Opd o; + o.t(D, { T, W * cin }); /* x */ + o.t_idx({ 2 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */ + o.t_idx({ T * vst }, 2, -1, 0); /* valid */ + o.t(D, { To * Wo, cin * kh * kw }); /* y */ + return o.finish("conv2d_unfold", operand, out); +} + int ref_conv1d_dw_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), C = gi(p, n_p, "n", 0), K = gi(p, n_p, "k", 0); @@ -597,6 +542,16 @@ int ref_rel_sinusoid_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* return o.finish("rel_sinusoid", operand, out); } +int ref_seg_sinusoid_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + if (gi(p, n_p, "cu_div", 1) != 1) return RAD_E_UNSUPPORTED; + Opd o; + o.t_idx({ 2 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */ + o.t(D, { M, n }); /* y */ + return o.finish("seg_sinusoid", operand, out); +} + int ref_attn_local_rel_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), hd = gi(p, n_p, "head_dim", 0); @@ -681,9 +636,8 @@ int ref_gather_rows_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* o const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); Opd o; - /* The source is FOUR TIMES the gathered height on purpose, so the gather is not the identity -- - * the identity is the one case that passes while broken. `idx` then draws from the previous - * operand's leading extent, which is exactly the 4M rows that are legal to read. */ + /* The source is 4x the gathered height so the gather is not the identity (which would pass + * while broken); `idx` draws over those 4M rows. */ o.t(D, { 4 * M, n }); /* x */ o.t_idx({ M }, 0, -1, 0); /* idx */ o.t(D, { M, n }); /* y */ @@ -691,10 +645,8 @@ int ref_gather_rows_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* o } -/* scatter_rows. The destination is four times the scattered height for the same reason gather's - * source is -- a scatter onto exactly M rows with M unique indices is a permutation, and a broken - * kernel that ignored `idx` entirely would still touch every row and could still pass. Wider than - * the write, and the rows nobody named have to come back unchanged. */ +/* scatter_rows. The destination is 4x the scattered height: onto exactly M rows a scatter is a + * permutation, which a kernel ignoring `idx` could pass. Unnamed rows must come back unchanged. */ int ref_scatter_rows_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); @@ -704,19 +656,8 @@ int ref_scatter_rows_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* o.t(D, { 4 * M, n }); /* x, inout */ return o.finish("scatter_rows", operand, out); } -/* PLE's n-gram ids. THE THREE WEIGHTS ARE I64 AND ARE NOT DRAWN LIKE INDICES: `mult` is a - * multiplier in the 10^13 range, `vocab_sizes` a prime near 2*10^7 and `offsets` its prefix sum, - * and a harness that drew them from an index distribution would produce a modulo by a small - * number -- which passes while saying nothing, because every id would land in the first rows of a - * 320-million-row table. They are described here with their real extents and left to the ordinary - * weight draw; the op's own arithmetic is exact for whatever arrives (see ref_ngram.cpp on the - * wrapping multiply and the flooring modulo). - * - * `tok` and `state` are index operands bounded by nothing, because a token id is bounded by the - * VOCABULARY and this op never sees it. Drawing them over the whole i32 range is the honest - * description and is also the case that exercises the wrap. */ -/* PLE's gate. `v` is the ONE narrow operand -- n wide against everything else's hc*n -- and that - * asymmetry is the op: a single value row gated differently into each of the hc streams. */ +/* PLE's gate. `v` is the one narrow operand (n wide against hc*n): a single value row gated + * differently into each of the hc streams. */ int ref_ple_gate_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), hc = gi(p, n_p, "hc", 0); @@ -725,8 +666,7 @@ int ref_ple_gate_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) o.t(D, { M, hn }); /* k */ o.t(D, { M, hn }); /* q */ o.t(D, { M, n }); /* v */ - /* The three gains are F32 in the container for the reason hc_read's are: they are read once a - * token, the norm's arithmetic is f32 anyway, and narrowing them buys nothing. */ + /* The three gains are f32 in the container, as hc_read's. */ o.t((uint32_t)RAD_F32, { hn }); /* w_key */ o.t((uint32_t)RAD_F32, { hn }); /* w_query */ o.t((uint32_t)RAD_F32, { hn }); /* w_conv */ @@ -735,16 +675,12 @@ int ref_ple_gate_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) return o.finish("ple_gate", operand, out); } -/* PLE's dilated convolution, described as the DECODE step it is on every token: `num_accepted` - * present, so the window the step leaves behind is the shifted one (ref_ple.cpp) and the state is - * (width-1)*dilation - 1 + M deep -- exactly what a step of M tokens needs, the way the manager's - * (width-1)*dilation + n_spec is exactly what a step of 1 + n_spec needs. A state at the read - * window's own depth would be refused for any M above one. +/* PLE's dilated convolution, described as a decode step: `num_accepted` present, so the state + * must be (width-1)*dilation - 1 + M deep for the shifted window (ref_ple.cpp), as the manager's + * (width-1)*dilation + n_spec is for a 1 + n_spec step. * - * WARM, and read at the DEEPEST offset that depth allows (`num_accepted` = M): a cold window or a - * read at offset zero would leave the offset arithmetic and the shifted history unexercised, and - * those are what two implementations of this op can disagree about. One sequence, because a shape - * query carries no sequence count. */ + * Warm and read at the deepest offset (`num_accepted` = M), so the offset arithmetic and shifted + * history are exercised. One sequence. */ int ref_ple_conv_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); @@ -758,8 +694,7 @@ int ref_ple_conv_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu */ o.t(D, { M, n }); /* resid -- gv */ o.t_idx({ S }, S, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* cache_idx */ - /* WARM, SAID rather than left absent: ref reads a null `has_init` as warm too, but a plugin - * need not, and a description should not lean on a default. */ + /* Warm, stated explicitly rather than relying on a null `has_init` default. */ o.t_idx({ S }, 0, 1, 0); /* has_init */ o.t_idx({ S }, 0, M, 0); /* num_accepted: read at M - 1 */ o.t(D, { M, n }); /* y */ @@ -784,51 +719,46 @@ int ref_causal_conv1d_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* return o.finish("causal_conv1d", operand, out); } +/* PLE's n-gram ids. The three i64 weights are not index-like: `mult` is ~10^13, `vocab_sizes` a + * prime near 2*10^7 and `offsets` its prefix sum. Index-range draws would give a modulo by a small + * number, landing every id in the first rows of the table. + * + * `tok` and `state` are unbounded index operands (a token id is bounded by the vocabulary, which + * this op never sees); drawing over the whole i32 range also exercises the wrapping multiply. */ int ref_ngram_ids_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0); const int64_t heads = gi(p, n_p, "heads", 0); const int64_t ngram = gi(p, n_p, "ngram", 0); const int64_t eos = gi(p, n_p, "eos", 0); const int64_t ctx = ngram > 0 ? ngram - 1 : 0; - /* One sequence, because `cu` is the only thing that says otherwise and a shape query carries - * no sequence count. The op reads `numel(cu) - 1`, so this describes the single-sequence - * launch every harness makes and every multi-sequence launch is the same code path. - * - * A DECODE STEP, for ple_conv's reason (see its description above): `num_accepted` present, - * a warm window read at the deepest offset, and a state `ctx - 1 + M` deep, which is what the - * shifted window a step of M ids leaves behind needs. */ + /* One sequence, a decode step as for ple_conv: `num_accepted` present, a warm window read at + * the deepest offset, and a state `ctx - 1 + M` deep for the shifted window. */ const int64_t S = 1, depth = ctx - 1 + M; Opd o; o.t_idx({ M }, 0, -1, 0); /* tok */ o.t_idx({ S, depth }, 0, -1, 0); /* state, INOUT */ o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu */ o.t((uint32_t)RAD_I64, { ngram }); /* mult */ - /* NOT A NORMAL DRAW, or the op refuses its own description: `ids[h] = floor_mod(mixed, v) + - * off[h]` and the launch checks `v <= 0 || off[h] < 0`, which a standard normal cast to i64 - * fails on most heads. The refusal looks exactly like a geometry the plugin does not serve, - * so rad-kbench would skip ngram_ids on every plugin without saying why. + /* Not normal draws: the launch refuses `v <= 0 || off[h] < 0`, which a normal cast to i64 + * fails on most heads, and the refusal would look like an unserved geometry. * - * The vocabulary is a CONSTANT because a draw cannot promise positive and the modulus has to - * be; `eos` is a token the head's vocabulary must contain, so eos + 1 is a bound derived from - * this op's own parameters rather than a number invented here. The offsets ARE drawn, because - * they only have to be non-negative -- and they are what gives the `heads_per_ngram` heads of - * one n-gram block different answers, since `mixed` is shared across them. `idx_max` 0 is the - * leading extent of the previous operand, which is `heads`. */ + * The vocabulary size is a constant eos + 1 (positive, and the vocabulary must contain eos). + * The offsets are drawn non-negative over [0, heads); they give the heads of one n-gram block, + * which share `mixed`, different answers. */ o.t_idx_dt((uint32_t)RAD_I64, { heads }, 0, eos + 1, 0); /* vocab_sizes */ o.t_idx_dt((uint32_t)RAD_I64, { heads }, 0, -1, 0); /* offsets */ o.t_idx({ S }, S, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* cache_idx */ o.t_idx({ S }, 0, 1, 0); /* has_init: warm */ o.t_idx({ S }, 0, M, 0); /* num_accepted: at M - 1 */ o.t((uint32_t)RAD_I32, { M, heads }); /* ids */ + o.skip(); /* ahead_ids */ return o.finish("ngram_ids", operand, out); } int ref_cast_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); - /* `from` and `to` are the only ops in this vocabulary whose operand dtypes come from the - * parameters rather than from a shared activation dtype, and an unparseable spelling falls back - * to f32 rather than to the activation default -- a cast with no `from` is a cast of nothing in - * particular, and f32 is the widest thing it could have meant. */ + /* Operand dtypes come from `from` and `to`; an unparseable spelling falls back to f32, the + * widest it could mean. */ uint32_t from = dt_parse(gs(p, n_p, "from")); uint32_t to = dt_parse(gs(p, n_p, "to")); if (from == (uint32_t)RAD_DT_INVALID) from = (uint32_t)RAD_F32; @@ -841,7 +771,22 @@ int ref_cast_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { /* ================================================================== quantisation and rotation */ +/* `asum` is described whenever `group` divides n, so a case checks the row sums as well. */ int ref_quant_act_i8_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), g = gi(p, n_p, "group", 0); + Opd o; + o.t(D, { M, n }); /* x */ + o.t((uint32_t)RAD_I8, { M, n }); /* q, in the step order */ + o.t((uint32_t)RAD_F32, { M, 1 }); /* scale */ + if (g > 0 && n % g == 0) + o.t((uint32_t)RAD_F32, { n / g, (M + 15) / 16 * 16 }); /* asum, group-major */ + else + o.skip(); + return o.finish("quant_act_i8", operand, out); +} + +int ref_quant_act_i8g_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); const int64_t ng = scale_groups(n, gi(p, n_p, "group", 0)); @@ -849,12 +794,7 @@ int ref_quant_act_i8_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* o.t(D, { M, n }); /* x */ o.t((uint32_t)RAD_I8, { M, n }); /* q */ o.t((uint32_t)RAD_F32, { M, ng }); /* scale */ - /* `asum` selects libr4d's _asum form and REF DOES NOT WRITE IT: ref implements no asymmetric - * grid, so it has no per-group code sums to produce and leaves the buffer alone. Passing it - * anyway would compare a zeroed reference against a real one and report a failure that is a gap - * in the ORACLE rather than a fault in the kernel. */ - o.skip(); /* asum */ - return o.finish("quant_act_i8", operand, out); + return o.finish("quant_act_i8g", operand, out); } int ref_quant_act_fp8_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { @@ -862,19 +802,14 @@ int ref_quant_act_fp8_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); const int64_t ng = scale_groups(n, gi(p, n_p, "group", 0)); Opd o; - /* `dtype` names the INPUT here, which is bf16; the output width is what the op name says. */ + /* `dtype` names the input; the output dtype is in the op name. */ o.t(D, { M, n }); /* x */ o.t((uint32_t)RAD_F8E4M3, { M, n }); /* q */ - o.t((uint32_t)RAD_F32, { M, ng }); /* scale, a DEQUANT multiplier (amax / 448) */ + o.t((uint32_t)RAD_F32, { M, ng }); /* scale, a dequant multiplier (amax / 448) */ return o.finish("quant_act_fp8", operand, out); } -/* IDENTICAL EXTENTS TO quant_act_fp8'S, and that is the point worth stating: `group` is BOTH the - * rotation width and the scale granularity here, unlike the int8 rotated forms below, where it is - * the rotation width alone and the scale is per row. So the description is the unrotated one -- - * the rotation changes the numbers, not the shapes. */ -/* `n` is K on BOTH axes of the accumulator, which is the one thing a caller coming from every - * other op in this file gets wrong: it is not [M, n]. */ +/* `n` is K on both axes of the accumulator: h is [n, n], not [M, n]. */ int ref_gram_accum_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); const char* dt = gs(p, n_p, "dtype"); @@ -885,16 +820,15 @@ int ref_gram_accum_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou } else { const int64_t ng = scale_groups(n, gi(p, n_p, "group", 0)); o.t((uint32_t)RAD_F8E4M3, { M, n }); /* a */ - o.t((uint32_t)RAD_F32, { M, ng }); /* a_scale, a DEQUANT multiplier (amax / 448) */ + o.t((uint32_t)RAD_F32, { M, ng }); /* a_scale, a dequant multiplier (amax / 448) */ } - o.t((uint32_t)RAD_F32, { n, n }); /* h, READ and added to */ + o.t((uint32_t)RAD_F32, { n, n }); /* h, read and added to */ return o.finish("gram_accum", operand, out); } -/* DECLINED, on purpose: `pairs` must be a pairing of each group's columns (every column once a - * stage, the partner inside the group), and a described operand can only be drawn, not constructed - * -- an index draw has repeats, and a Givens stage over a repeated column is not a rotation. A case - * built from one would compare two implementations of nothing. r4d_selftest builds real pairings. */ +/* Declined: `pairs` must pair each group's columns (every column once per stage, partner in the + * group), and a drawn index operand has repeats, so it would not be a rotation. r4d_selftest builds + * real pairings. */ int ref_givens_dense_quant_shape(const RadParam*, int, int, RadOpdDesc*) { return RAD_E_UNSUPPORTED; /* a composed rotation cannot be drawn: it is a weight, built from real pairings */ } @@ -903,6 +837,8 @@ int ref_givens_rotate_shape(const RadParam*, int, int, RadOpdDesc*) { return RAD_E_UNSUPPORTED; /* a pairing cannot be drawn: a described operand can only be drawn, and an index draw has repeats */ } +/* The same extents as quant_act_fp8: `group` is both rotation width and scale granularity here, + * unlike the int8 rotated forms, so the rotation changes the values, not the shapes. */ int ref_had_quant_act_fp8_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); @@ -910,17 +846,14 @@ int ref_had_quant_act_fp8_shape(const RadParam* p, int n_p, int operand, RadOpdD Opd o; o.t(D, { M, n }); /* x */ o.t((uint32_t)RAD_F8E4M3, { M, n }); /* q */ - o.t((uint32_t)RAD_F32, { M, ng }); /* scale, a DEQUANT multiplier (amax / 448) */ + o.t((uint32_t)RAD_F32, { M, ng }); /* scale, a dequant multiplier (amax / 448) */ return o.finish("had_quant_act_fp8", operand, out); } -/* The rotated forms share a scale convention that is NOT quant_act_i8's, and it is the one place - * this file corrects the table it replaces. `group` here is the WALSH-HADAMARD ROTATION WIDTH - * (libr4d calls it `had`) and the int8 scale is per ROW, carrying the 1/sqrt(group) normalisation - * -- libref/ref_quant.cpp says so at length and the launch refuses anything shorter than one - * scale a row. Describing the scale as [M, n/group] instead is not fatal (it is merely larger than - * the op writes) but it leaves the tail of every scale buffer untouched by both implementations, - * which is a comparison of two zero fills dressed up as agreement. */ +/* The int8 rotated forms: `group` is the Walsh-Hadamard rotation width (libr4d's `had`) and the + * scale is one per row, carrying the 1/sqrt(group) normalisation (ref_quant.cpp). Describing it as + * [M, n/group] would leave the tail of every scale buffer unwritten by both sides, comparing two + * zero fills. */ int ref_had_quant_act_i8_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); @@ -937,16 +870,13 @@ int ref_rmsnorm_had_quant_i8_shape(const RadParam* p, int n_p, int operand, RadO const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); Opd o; o.t(D, { M, n }); /* x */ - /* `residual` PRESENT is the fused_add_rms_norm form, and it is the form worth describing: the - * add happens first, the sum is written back through the INOUT operand, and the norm reads the - * NARROWED sum. That rounding is the contract the fused kernel has to match, and it is only - * exercised when the residual is passed. */ + /* `residual` passed, so the fused_add_rms_norm rounding (the norm reads the narrowed sum + * written back through the INOUT operand) is exercised. */ o.t(D, { M, n }); /* residual, INOUT */ o.t(D, { n }); /* w */ o.t((uint32_t)RAD_I8, { M, n }); /* q */ o.t((uint32_t)RAD_F32, { M, 1 }); /* scale -- one per row */ - /* `out_bf16` is the post-norm, PRE-ROTATION tensor for a layer that also has a bf16 consumer. - * Both plugins write it when it is present, so it is described rather than skipped. */ + /* `out_bf16` (post-norm, pre-rotation) is written by both plugins when present, so described. */ o.t(D, { M, n }); /* out_bf16 */ return o.finish("rmsnorm_had_quant_i8", operand, out); } @@ -955,9 +885,7 @@ int ref_gated_had_quant_i8_shape(const RadParam* p, int n_p, int operand, RadOpd const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); Opd o; - /* THE PACKED FORM: `b` absent means `a` is [M, 2n], the gate is its first half and the up its - * second, which is vLLM's layout and the one a fused gate_up projection actually produces. Both - * readings exist and only one can be described; this is the one the MLP issues. */ + /* The packed form the MLP issues: `b` absent, `a` [M, 2n] with the gate first. */ o.t(D, { M, 2 * n }); /* a */ o.skip(); /* b */ o.t((uint32_t)RAD_I8, { M, n }); /* q */ @@ -995,49 +923,74 @@ int ref_gemm_nt_bias_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* o.t(D, { M, K }); /* a */ o.t(D, { N, K }); /* b */ o.t(D, { N }); /* bias */ - /* `res` is optional and PASSED, the layernorm bias's reason: with it the description covers - * the residual epilogue, and a caller's plain form is the same code with a branch untaken. */ + /* `res` is optional but passed, to cover the residual epilogue. */ o.t(D, { M, N }); /* res */ o.t(D, { M, N }); /* y */ return o.finish("gemm_nt_bias", operand, out); } -/* BLOCK-SCALED FP8 ONLY, and the restriction is the honest one rather than laziness. +/* Block-scaled fp8, the symmetric int4 and int8 weights against quant_act_i8's activation, the + * int8 trunk (`i8a8`) and OCP-MXFP4 (`mxfp4a8`). The zero-point grids (`w2a8`, `w4a8_asym`, + * `w4a16_asym`, `w5a16`, `w4a8i8_asym`, `w5a8i8`) read their scale and zero joined in one operand + * (ref_planes.h), which a description cannot state; they and any other format are declined rather + * than guessed. * - * `gemm_nt_q` is one op over six weight formats and the SCALE GRID is what differs between them -- - * per row, per row-group, per output-row-block, an e8m0 exponent byte, with or without a zero point - * or a reference exponent. Every one of those is a property of the kernel that reads it and not of - * the schema, so a description that guessed would be sizing five kernels' scale streams wrong and - * calling whatever came back correctness. - * - * The fp8 family is different: its grid is stated by the CHECKPOINT -- E4M3 [N][K] against a bf16 - * [ceil(N/128)][ceil(K/128)] plane, with `group` carrying the 128 -- so there is nothing left to - * guess. It is also the family the production model runs on. `a_sum` and `b_ref` belong to the - * asymmetric-integer and mxfp4 grids and are absent; ref implements neither. */ + * The fp8 grid is stated by the checkpoint: E4M3 [N][K] against a bf16 [ceil(N/128)][ceil(K/128)] + * plane, `group` carrying the 128. w4a8 and w8a8 are the affine encoding's two planes, codes and + * an f16 scale per (row, `group` of K), against int8 codes in the step order with one f32 scale a + * row. `a_sum` (asymmetric grids) is absent, and so is `b_ref` except at mxfp4a8. Activation + * scales are drawn in (0, 1): a quantiser's are never negative, and an MXFP4 kernel treats a + * block whose scale is not positive as empty (docs/OPS.md). */ static int gemm_q_shape(const RadParam* p, int n_p, int operand, bool bias, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0), N = gi(p, n_p, "N", 0), K = gi(p, n_p, "K", 0); const int64_t group = gi(p, n_p, "group", 0); const char* q = gs(p, n_p, "dtype"); - const bool a8 = q && std::strcmp(q, "fp8a8") == 0; - const bool a16 = q && std::strcmp(q, "fp8a16") == 0; - if ((!a8 && !a16) || N <= 0 || K <= 0 || group <= 0) return RAD_E_UNSUPPORTED; - /* The bias form takes `a_scale` as a REQUIRED operand, so the fp8a16 reading -- a bf16 - * activation and no activation scale at all -- cannot be expressed there. Declining is the - * right answer rather than passing a scale stream the op does not mean. */ - if (bias && !a8) return RAD_E_UNSUPPORTED; + auto is = [&](const char* s) { return q && std::strcmp(q, s) == 0; }; + const bool a8 = is("fp8a8"), a16 = is("fp8a16"), w4 = is("w4a8"), w8 = is("w8a8"); + const bool i8 = is("i8a8"), mx = is("mxfp4a8"); + if ((!a8 && !a16 && !w4 && !w8 && !i8 && !mx) || N <= 0 || K <= 0 || group <= 0) + return RAD_E_UNSUPPORTED; + /* Neither has a bias form in any architecture. */ + if (bias && (i8 || mx)) return RAD_E_UNSUPPORTED; + /* The bias form requires `a_scale`, so the fp8a16 reading (bf16 activation, no scale) cannot + * be expressed there. */ + if (bias && a16) return RAD_E_UNSUPPORTED; const int64_t kb = (K + group - 1) / group; const int64_t nb = (N + group - 1) / group; Opd o; - if (a8) { - o.t((uint32_t)RAD_F8E4M3, { M, K }); /* a */ - o.t((uint32_t)RAD_F32, { M, kb }); /* a_scale */ + if (i8 || mx) { + /* i8a8: quant_act_i8g's row-major codes and f32 scale per (row, `group` of K) against int8 + * codes with a bf16 scale per (row, `group` of K). mxfp4a8: quant_act_fp8's pair at 128 + * against e2m1 codes with an E8M0 exponent per (row, `group` = 32 of K); `b_ref` is the same + * exponent plane, which an mxfp4 kernel reduces to a per-row reference at load. */ + const int64_t akb = mx ? (K + 127) / 128 : kb; + o.t((uint32_t)(mx ? RAD_F8E4M3 : RAD_I8), { M, K }); /* a */ + o.t_fill((uint32_t)RAD_F32, { M, akb }, (uint32_t)RAD_FILL_SIGMOID, 0); /* a_scale */ + o.t((uint32_t)(mx ? RAD_FP4E2M1 : RAD_I8), { N, K }); /* b */ + o.t((uint32_t)(mx ? RAD_E8M0 : RAD_BF16), { N, kb }); /* b_scale */ + o.t((uint32_t)RAD_BF16, { M, N }); /* y */ + o.skip(); /* a_sum */ + if (mx) o.t((uint32_t)RAD_E8M0, { N, kb }); /* b_ref */ + else o.skip(); + return o.finish("gemm_nt_q", operand, out); + } + if (w4 || w8) { + o.t((uint32_t)RAD_I8, { M, K }); /* a, in the step order */ + o.t_fill((uint32_t)RAD_F32, { M, 1 }, (uint32_t)RAD_FILL_SIGMOID, 0); /* a_scale */ + o.t((uint32_t)(w4 ? RAD_I4 : RAD_I8), { N, K }); /* b */ + o.t((uint32_t)RAD_F16, { N, kb }); /* b_scale */ } else { - o.t((uint32_t)RAD_BF16, { M, K }); /* a */ - o.skip(); /* a_scale */ + if (a8) { + o.t((uint32_t)RAD_F8E4M3, { M, K }); /* a */ + o.t_fill((uint32_t)RAD_F32, { M, kb }, (uint32_t)RAD_FILL_SIGMOID, 0); /* a_scale */ + } else { + o.t((uint32_t)RAD_BF16, { M, K }); /* a */ + o.skip(); /* a_scale */ + } + o.t((uint32_t)RAD_F8E4M3, { N, K }); /* b -- the checkpoint's own bytes */ + o.t((uint32_t)RAD_BF16, { nb, kb }); /* b_scale -- weight_scale_inv, per 128x128 */ } - o.t((uint32_t)RAD_F8E4M3, { N, K }); /* b -- the checkpoint's own bytes */ - o.t((uint32_t)RAD_BF16, { nb, kb }); /* b_scale -- weight_scale_inv, per 128x128 */ if (bias) { o.t((uint32_t)RAD_BF16, { N }); /* bias */ o.t((uint32_t)RAD_BF16, { M, N }); /* y */ @@ -1058,17 +1011,16 @@ int ref_gemm_nt_q_bias_shape(const RadParam* p, int n_p, int operand, RadOpdDesc /* ================================================================== attention * - * The paged pair share one layout and it is stated once for the whole project in ref_ops.h: + * The paged layout (ref_ops.h): * * kv_cache[num_blocks, kv_heads, block_size, 2 * head_dim] K first, V second in a slot * - * The extents they need beyond the parameters are a block COUNT and a context length, and both are - * this description's to choose rather than the model's: any cache big enough for the case will do, - * so long as the indices land inside it. */ + * The block count and context length are this description's choice; any cache large enough for + * the indices will do. */ int ref_attn_paged_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { - /* `q_len` is the ranged parameter and it is a QUERY LENGTH, not a token count -- one query row - * at decode and thousands in a prefill chunk are different kernels (docs/OPS.md). */ + /* `q_len` is the ranged parameter, a query length (one row at decode, thousands in a prefill + * chunk; different kernels, docs/OPS.md). */ const int64_t M = gi(p, n_p, "q_len", 0); const int64_t hd = gi(p, n_p, "head_dim", 0); const int64_t bs = gi(p, n_p, "block_size", 16); @@ -1077,27 +1029,18 @@ int ref_attn_paged_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou if (M <= 0 || hd <= 0 || bs <= 0 || gqa <= 0 || nh <= 0 || nh % gqa) return RAD_E_UNSUPPORTED; const int64_t kvh = nh / gqa; - /* THE CONTEXT DEPTH, AND IT IS NOT THE QUERY LENGTH. - * - * The default is one sequence whose context is exactly its own query -- a causal attention - * over its own prefix, which is the case a prefill chunk runs. On its own that default checks - * a decode of ten query rows against ten tokens of KV and never describes the paged path at - * any real depth: no block table long enough to rebase, no split over KV, no sliding window - * with anything to slide past. - * `ctx` is an ordinary parameter the harness sets when it sweeps depth, exactly as it hands - * over the GDN head counts, and no op declares it because the KERNEL reads its context off - * `seqused` -- which is right for the kernel and leaves only the description short. - * - * It must be at least the query length: a context shorter than the query makes causal - * attention read a prefix that does not exist. */ + /* Context depth, not the query length. By default one sequence whose context is exactly its + * query (a prefill chunk's case), which never exercises deep paging, KV splits or sliding + * windows. A harness sweeping depth passes `ctx` (no op declares it; kernels read the context + * from `seqused`). It is at least the query length, or causal attention would read a + * nonexistent prefix. */ const int64_t S = 1; int64_t ctx = gi(p, n_p, "ctx", 0); if (ctx < M) ctx = M; const int64_t max_blocks = (ctx + bs - 1) / bs; - /* `q_dtype` and `kv_dtype` are separate in this schema and are read separately: an fp8 cache - * beside a bf16 query is the shape the engine actually issues, and folding them into one dtype - * describes a call nobody makes. */ + /* `q_dtype` and `kv_dtype` are read separately: the engine issues fp8 caches beside bf16 + * queries. */ const uint32_t Q = act_dt(p, n_p); const uint32_t kv = dt_parse(gs(p, n_p, "kv_dtype")); const uint32_t KV = kv == (uint32_t)RAD_DT_INVALID ? Q : kv; @@ -1105,16 +1048,13 @@ int ref_attn_paged_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou Opd o; o.t(Q, { S * M, nh, hd }); /* q */ o.t(KV, { max_blocks, kvh, bs, 2 * hd }); /* kv_cache */ - o.t_idx({ S, max_blocks }, max_blocks, -1, 0); /* block_table -- indexes BLOCKS, may repeat */ - /* NOT a draw: a context shorter than the query makes causal attention read a prefix that does - * not exist, and both implementations would agree about the garbage. */ + o.t_idx({ S, max_blocks }, max_blocks, -1, 0); /* block_table -- indexes blocks, may repeat */ + /* A constant, not a draw (see the file header). */ o.t_idx({ S }, 0, ctx, 0); /* seqused */ o.skip(); /* k_descale -- no per-(seq,head) descales */ o.skip(); /* v_descale */ - /* `cu_seqlens` absent is the RECTANGULAR reading: every sequence presents the same query - * length, which at one sequence is the only thing it could mean. Present it would have to agree - * with the query's own row count, and the value a tool fills it with is the tool's `M` rather - * than this description's -- so describing it would couple the two. */ + /* `cu_seqlens` absent: the rectangular reading, the only one at one sequence. Present, it + * would have to agree with a tool's `M` rather than this description's. */ o.skip(); /* cu_seqlens */ o.t(Q, { S * M, nh, hd }); /* out */ return o.finish("attn_paged", operand, out); @@ -1125,11 +1065,10 @@ int ref_attn_dense_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou const int64_t hd = gi(p, n_p, "head_dim", 0); const int64_t gqa = gi(p, n_p, "gqa", 1); if (M <= 0 || hd <= 0 || gqa <= 0) return RAD_E_UNSUPPORTED; - /* THE HEAD COUNT IS NOT IN THIS SCHEMA -- `gqa` is the RATIO and the count is read off `q` at - * launch -- so it is chosen here, and `gqa` query heads against one KV head is the smallest - * geometry that exercises the grouping at all. That is a choice about the case and not about - * the model: this op's operands are all created by the caller, so any head count produces a - * well-formed dense attention. */ + /* A segment read in units finer than the rows has no [0, ..., T] description. */ + if (gi(p, n_p, "cu_div", 1) != 1) return RAD_E_UNSUPPORTED; + /* The head count is not in the schema (`gqa` is a ratio; the count is read off `q`), so this + * picks `gqa` query heads over one KV head, the smallest geometry exercising the grouping. */ const int64_t nh = gqa, kvh = 1; const uint32_t D = act_dt(p, n_p); const int64_t S = n_seq_of(p, n_p); @@ -1138,7 +1077,7 @@ int ref_attn_dense_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou o.t(D, { M, nh, hd }); /* q */ o.t(D, { M, kvh, hd }); /* k */ o.t(D, { M, kvh, hd }); /* v */ - /* [0, ..., T]: the batch's shape and not a draw. */ + /* [0, ..., T], the batch's shape, not a draw. */ o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */ o.t(D, { M, nh, hd }); /* out */ return o.finish("attn_dense", operand, out); @@ -1150,12 +1089,10 @@ int ref_kv_store_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) 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) return RAD_E_UNSUPPORTED; - /* Two blocks of slack so the slot mapping is not a dense prefix: a scatter that only ever - * writes block 0 agrees with anything about the block index. */ + /* Two blocks of slack so the slot mapping is not a dense prefix and the block index matters. */ const int64_t nb = (M + bs - 1) / bs + 2; - /* ONLY THE CACHE TAKES `kv_dtype`. k and v are the step's bf16 activations whatever the cache - * stores -- an E4M3 cache is written from bf16 keys -- and act_dt, which falls back on - * kv_dtype for an op with no `dtype`, would describe an fp8 k no engine passes. */ + /* Only the cache takes `kv_dtype`: k and v are bf16 activations whatever the cache stores + * (act_dt would fall back on kv_dtype and describe an fp8 k). */ const uint32_t D = (uint32_t)RAD_BF16; const uint32_t kv = dt_parse(gs(p, n_p, "kv_dtype")); const uint32_t KV = kv == (uint32_t)RAD_DT_INVALID ? D : kv; @@ -1163,9 +1100,7 @@ int ref_kv_store_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) Opd o; o.t(D, { M, kvh, hd }); /* k */ o.t(D, { M, kvh, hd }); /* v */ - /* A SCATTER DESTINATION: distinct, because two tokens on one slot make the store a race and - * ref (an OpenMP token loop) and a device kernel (a workgroup a token) resolve it differently. - * The range is the whole cache in SLOTS, which is no operand's dim 0. */ + /* A scatter destination: distinct (see the file header), over the whole cache in slots. */ o.t_idx({ M }, nb * bs, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* slot_mapping */ o.t(KV, { nb, kvh, bs, 2 * hd }); /* kv_cache, INOUT */ return o.finish("kv_store", operand, out); @@ -1179,12 +1114,10 @@ int ref_rope_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { if (M <= 0 || hd <= 0 || nh <= 0) return RAD_E_UNSUPPORTED; const uint32_t D = act_dt(p, n_p); /* no `dtype` on this op: bf16, see act_dt */ Opd o; - /* The fused row: n_head queries and n_head_kv each of k and v, all head_dim wide. The v heads - * are left alone, which is the whole reason this op takes the fused row rather than two - * tensors. */ + /* The fused row: n_head q heads, then n_head_kv each of k and v, head_dim wide. */ o.t(D, { M, (nh + 2 * nkv) * hd }); /* qkv, INOUT */ - /* A multi-component mode with its sections takes a position per component, component-major; - * the count is the sections' (three for the interleaved form, which always reads three). */ + /* A multi-component mode with sections takes one position per component, component-major: + * the section count, or three for imrope. */ const char* mode = gs(p, n_p, "mode"); if (!mode) mode = "neox"; const char* sec = gs(p, n_p, "sections"); @@ -1211,14 +1144,11 @@ int ref_qk_norm_rope_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* if (M <= 0 || hd <= 0 || nh <= 0) return RAD_E_UNSUPPORTED; const uint32_t D = act_dt(p, n_p); Opd o; - /* THIS IS NOT libr4d's `qk_norm_rope_gate`, which opshapes.h declines and is right to: that op - * reads an INTERLEAVED strided view -- attn_q is [n_embd, 2 * head_dim * n_head] with query and - * gate alternating per head, so it is not a contiguous split and no description built out of - * the parameters could know it. The vocabulary's `qk_norm_rope` takes the same contiguous fused - * [q|k|v] row `rope` does, so it is describable and is described. */ + /* The contiguous fused [q|k|v] row, as for `rope`. (libr4d's `qk_norm_rope_gate` reads an + * interleaved q/gate view that parameters cannot describe; opshapes.h declines it.) */ o.t(D, { M, (nh + 2 * nkv) * hd }); /* qkv, INOUT */ - /* `blocks` takes a position per component, [C, M] component-major, C being one past the - * largest component `comps` names (the section count when it names none). */ + /* `blocks` takes positions [C, M], component-major, C one past the largest `comps` entry (the + * section count without `comps`). */ const char* mode = gs(p, n_p, "mode"); if (mode && !std::strcmp(mode, "blocks")) { int64_t nc = 0; @@ -1256,12 +1186,9 @@ int ref_rope_table_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou if (M <= 0 || rot < 2 || (rot & 1)) return RAD_E_UNSUPPORTED; const uint32_t D = act_dt(p, n_p); Opd o; - /* THE TABLE HEIGHT IS THIS DESCRIPTION'S CHOICE and the position range has to be stated for it. - * Each position writes its OWN row of a [max_ctx, rot] plane, `max_ctx` is not an operand of - * this op, and a row no position names is left untouched -- so a table of M rows with positions - * drawn from [0, M) is the case where every row is reachable. Left at the default the draw - * would come from the previous operand's leading extent, and `positions` IS the first operand: - * the caller would fall back to the container's vocabulary size and write nothing at all. */ + /* Each position writes its own row of a [max_ctx, rot] plane and max_ctx is not a parameter, + * so the table is M rows with positions drawn from [0, M). The bound must be explicit: + * `positions` is the first operand, so the default (previous operand's extent) does not apply. */ o.t_idx({ M }, M, -1, 0); /* positions */ o.t(D, { M, rot }); /* cos_sin -- cos in the first half, sin in the second */ return o.finish("rope_table", operand, out); @@ -1276,14 +1203,109 @@ int ref_qsa_block_key_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* Opd o; o.t(D, { M * r, n }); /* k -- `ratio` rows a block */ o.t((uint32_t)RAD_F32, { n }); /* w -- the norm gain */ - /* page: absent, so the write is contiguous. A drawn page list may repeat an entry, and two - * blocks onto one row is a race whose winner the comparison would then measure. */ + /* page: absent, so the write is contiguous; a drawn page list could repeat and race. */ o.skip(); o.t_idx({ M }, M * r, -1, 0); /* pos -- each block's first-token position */ o.t(D, { M, n }); /* out */ return o.finish("qsa_block_key", operand, out); } +/* The indexer's other four ops. The fill laws have no per-sequence position run, so the + * descriptions pick batches whose answers are defined and race-free on every implementation: + * `cu` splits the M rows evenly over S sequences; the tail store gives every row a sequence and a + * distinct slot of its own (two rows of one sequence could share a ring row); the work list puts + * every row of a sequence at position ratio - 1, so each sequence completes block 0 from one key + * of the batch and ratio - 1 of the tail. */ +static int64_t qsa_seqs(const RadParam* p, int n_p, int64_t M) { + const int64_t s = gi(p, n_p, "seqs", 1); + return std::max(1, std::min(s, M)); +} + +int ref_qsa_score_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const int64_t heads = gi(p, n_p, "heads", 0), blocks = gi(p, n_p, "blocks", 0); + if (M <= 0 || n <= 0 || heads <= 0 || blocks <= 0) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + const int64_t S = qsa_seqs(p, n_p, M), pages = S * blocks; + Opd o; + o.t(D, { M, heads * n }); /* q */ + o.t(D, { pages, n }); /* bk -- one block key a page */ + o.t_idx({ S, blocks }, pages, -1, 0); /* bt -- page ids */ + o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu */ + o.t_idx({ S }, blocks + 1, -1, 0); /* nc -- 0 .. blocks */ + o.t((uint32_t)RAD_F32, { M, blocks }); /* score */ + return o.finish("qsa_score", operand, out); +} + +int ref_qsa_select_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 topk = gi(p, n_p, "topk", 0), ratio = gi(p, n_p, "ratio", 0); + if (M <= 0 || blocks <= 0 || topk <= 0 || ratio <= 0) return RAD_E_UNSUPPORTED; + const int64_t S = qsa_seqs(p, n_p, M); + Opd o; + o.t((uint32_t)RAD_F32, { M, blocks }); /* score */ + o.t_idx({ S, blocks }, S * blocks, -1, 0); /* bt -- page ids */ + o.t_idx({ S }, blocks + 1, -1, 0); /* nc -- 0 .. blocks */ + o.t_idx({ M }, (blocks + 1) * ratio, -1, 0); /* pos */ + o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu */ + o.t((uint32_t)RAD_I32, { M, topk + 1 }); /* sel */ + o.t((uint32_t)RAD_I32, { M }); /* nsel */ + o.t((uint32_t)RAD_I32, { M }); /* seqused */ + return o.finish("qsa_select", operand, out); +} + +int ref_qsa_tail_store_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const int64_t ratio = gi(p, n_p, "ratio", 0), ring = gi(p, n_p, "ring", ratio); + if (M <= 0 || n <= 0 || ratio <= 0 || ring < ratio) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { M, n }); /* k */ + o.t_idx({ M }, 1 << 16, -1, 0); /* pos */ + o.t_idx({ M + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu -- a row a sequence */ + o.t(D, { M, 1, ring, n }); /* state */ + o.t_idx({ M, 1 }, M, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* sidx -- a slot each */ + return o.finish("qsa_tail_store", operand, out); +} + +int ref_qsa_work_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const int64_t ratio = gi(p, n_p, "ratio", 0), ring = gi(p, n_p, "ring", ratio); + const int64_t work = gi(p, n_p, "work", 0); + if (M <= 0 || n <= 0 || ratio <= 0 || ring < ratio || work <= 0) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + const int64_t S = std::min(qsa_seqs(p, n_p, M), work); + Opd o; + o.t(D, { M, n }); /* k */ + o.t_idx({ M }, 0, ratio - 1, 0); /* pos -- see above */ + o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu */ + o.t(D, { S, 1, ring, n }); /* state -- the tail */ + o.t_idx({ S, 1 }, S, -1, 0); /* sidx */ + o.t_idx({ S, 2 }, 1 << 16, -1, 0); /* bt -- block-key pages */ + o.skip(); /* rope */ + o.t(D, { work * ratio, n }); /* stage */ + o.t((uint32_t)RAD_I32, { work }); /* page */ + o.t((uint32_t)RAD_I32, { work }); /* bpos */ + o.t((uint32_t)RAD_I32, { S }); /* nc */ + return o.finish("qsa_work", 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. */ +int ref_dflash_conv_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t T = gi(p, n_p, "T", 0), H = gi(p, n_p, "hidden_size", 0); + const int64_t taps = gi(p, n_p, "taps", 0), NG = gi(p, n_p, "NG", 0); + if (T <= 0 || H <= 0 || taps <= 0 || NG <= 0) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { T, H }); /* x */ + o.t(D, { T, 2 * taps * NG }); /* delta */ + o.t(D, { taps, H }); /* base */ + o.t(D, { T, H }); /* out */ + return o.finish("dflash_conv", operand, out); +} + /* ================================================================== mixture of experts */ int ref_scale_rows_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { @@ -1293,9 +1315,8 @@ int ref_scale_rows_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou Opd o; o.t(D, { M, n }); /* x */ o.t(D, { M }); /* s -- one scalar a row */ - o.t(D, { M, n }); /* add -- optional, described anyway: a tool - * calling this cold gets a buffer for it and - * exercises the fused form */ + o.t(D, { M, n }); /* add -- optional, described to exercise the + * fused form */ o.t(D, { M, n }); /* y */ return o.finish("scale_rows", operand, out); } @@ -1319,9 +1340,8 @@ int ref_moe_scatter_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* o const int64_t k = gi(p, n_p, "top_k", 0); if (M <= 0 || ne <= 0 || k <= 0) return RAD_E_UNSUPPORTED; Opd o; - /* Expert ids index EXPERTS, which is no operand's dim 0, so the range is stated. A slot whose - * expert is outside [0, n_expert) is dropped by the op and a draw inside it exercises the sort - * rather than the dropping; the dropping is the caller's to construct if it wants it. */ + /* Expert ids draw over [0, n_expert), exercising the sort rather than the dropping of + * out-of-range slots. */ o.t_idx({ M, k }, ne, -1, 0); /* expert_ids */ o.t((uint32_t)RAD_I32, { M * k }); /* sorted_tok -- token*top_k + slot, by expert */ o.t((uint32_t)RAD_I32, { ne + 1 }); /* expert_offset */ @@ -1329,9 +1349,8 @@ int ref_moe_scatter_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* o return o.finish("moe_scatter", operand, out); } -/* `a_order` decides the activation's row count: one per token, or one per (token, slot) already - * in the scatter's order. A described case that got this wrong would build the operand at the - * extent the WRONG reading wants, and the fault it names would go unseen. */ +/* `a_order` decides the activation's row count: one per token, or one per (token, slot) in + * scatter order. */ static inline bool sorted_a_order(const RadParam* p, int n_p) { const char* s = gs(p, n_p, "a_order"); return s && std::strcmp(s, "sorted") == 0; @@ -1348,36 +1367,26 @@ int ref_moe_gemm_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) const int64_t AR = sorted_a_order(p, n_p) ? M * k : M; o.t(D, { AR, K }); /* a -- see `a_order` */ o.t(D, { ne, N, K }); /* w */ - o.t_idx({ M * k }, M * k, -1, 0); /* sorted_tok */ - /* `expert_offset` IS NOT A FREE DRAW and the ABI has no fill domain that says so: it is - * moe_scatter's output, a non-decreasing prefix array ending at the live row count, and the - * expert that owns a sorted row is found by searching it. Drawn at random it is a malformed - * histogram, so two implementations that search it differently -- a binary search here, a - * linear scan there -- can pick different experts and disagree without either being wrong. - * The extents below are still exactly right, which is what a benchmark needs; a correctness - * comparison over this operand proves less than it appears to, and that is worth knowing - * before reading a result. */ - o.t_idx({ ne + 1 }, M * k + 1, -1, 0); /* expert_offset */ - o.t(D, { M * k, N }); /* y -- in SORTED order */ + /* A valid routing, as moe_scatter produces it: `sorted_tok` a permutation of [0, M*top_k) and + * `expert_offset` a non-decreasing prefix array from 0 to M*top_k. A random offset array is a + * malformed histogram that implementations searching it differently (binary against linear) + * may read differently without either being wrong. */ + o.t_idx({ M * k }, M * k, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* sorted_tok */ + o.t_idx({ ne + 1 }, M * k + 1, -1, (uint32_t)RAD_OPD_F_IDX_PREFIX); /* expert_offset */ + o.t(D, { M * k, N }); /* y -- in sorted order */ return o.finish("moe_gemm", operand, out); } -/* THE WEIGHT SCALE GRID IS THE ONE `dtype` NAMES, and the grouped GEMM serves more than one. The - * block-fp8 experts (fp8a8) carry the checkpoint's: a scale a 128x128 tile, `group` holding the - * 128. The four-bit ones (docs/MOE-W4.md) carry one a ROW per group of K -- all of `group` at - * w4a8, w4a8h and w4nla8h, half of it at w4nl64a8h and w5nl64a8h, a quarter at w4nl32a8h. Those - * strings are the served formats' own names (arch/common/rad_block_moe_fp8.h, kServed), so this - * states a format and guesses at no kernel's stream. Any other dtype, or none, names no grid this - * file knows: the answer is { 0, 0 } and the description declines (RAD_E_UNSUPPORTED), because a - * scale plane sized on a guessed grid is a tensor of the wrong extent handed to the oracle. +/* The weight scale grid `dtype` names, as weight rows and K elements per scale. Block-fp8 experts + * (fp8a8) carry the checkpoint's one scale per 128x128 tile (`group` = 128). The 4-bit formats + * (docs/MOE-W4.md) carry one per row per K group: all of `group` for w4a8, w4a8h and w4nla8h, half + * for w4nl64a8h and w5nl64a8h, a quarter for w4nl32a8h. These are the served format names + * (arch/common/rad_block_moe_fp8.h, kServed). Any other dtype returns { 0, 0 } and the description + * declines rather than guess a grid. * - * It matters past the extents. A weight its kernel stores re-laid goes back through that - * kernel's inverse into the tensor THIS describes before the oracle hands it over - * (core/runtime/oracle.cpp), and the E4M3 scale views are re-laid -- their two levels are one - * operand -- so tiles here leave every such expert's scales with nothing to be inverted into. - * The arithmetic reads whichever grid it is handed (ref_gemm.h derives the group from the - * extents) and is unchanged. Weight rows and K elements a scale covers, or 0 when `group` is too - * small to divide or the dtype names no grid. */ + * The grid matters beyond extents: re-laid weights are inverted into the tensor described here + * before the oracle reads them (core/runtime/oracle.cpp), so the wrong grid leaves the scales + * nothing to invert into. The arithmetic (ref_gemm.h) derives the group from the extents. */ struct MoeScaleGrid { int64_t rows, k; }; static MoeScaleGrid moe_scale_grid(const RadParam* p, int n_p, int64_t g) { const char* d = gs(p, n_p, "dtype"); @@ -1389,12 +1398,10 @@ static MoeScaleGrid moe_scale_grid(const RadParam* p, int n_p, int64_t g) { return { 0, 0 }; } -/* The quantised arm. Same planes, plus the two scale streams: the activation's is per row per - * group of K (rblk 1) and the weight's is one plane per expert on the grid above -- for block fp8 - * [ceil(N/g), ceil(K/g)], the DeepSeek block grid the checkpoint ships. `w` is described as the - * STACKED [ne, N, K] plane even though the engine issues a pointer table against it, because a - * fixture has nowhere to put a pointer array -- ref_gemm.h's expert_entry() reads both forms and - * rad-kbench therefore checks the arithmetic against the same bytes the engine would. */ +/* The quantised arm: the same planes plus two scale streams, the activation's per row per K group + * and the weight's one plane per expert on the grid above ([ceil(N/g), ceil(K/g)] for block fp8). + * `w` is described stacked [ne, N, K], since a fixture cannot hold a pointer table; expert_entry() + * reads both forms. */ int ref_moe_gemm_q_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0); const int64_t N0 = gi(p, n_p, "N", 0), K0 = gi(p, n_p, "K", 0); @@ -1404,8 +1411,8 @@ int ref_moe_gemm_q_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou int64_t g = gi(p, n_p, "group", 0); if (M <= 0 || N0 <= 0 || K0 <= 0 || N1 <= 0 || K1 <= 0 || ne <= 0 || k <= 0) return RAD_E_UNSUPPORTED; - /* The output is the wider class's width and the activation the longer class's K; the two - * tables are the even and the odd experts. */ + /* Output width and activation K are the larger class's; the tables hold even and odd + * experts. */ const int64_t N = N0 > N1 ? N0 : N1, K = K0 > K1 ? K0 : K1; const int64_t ne0 = (ne + 1) / 2, ne1 = ne / 2; if (g <= 0) g = K; @@ -1418,16 +1425,16 @@ int ref_moe_gemm_q_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou o.t((uint32_t)RAD_F32, { AR, (K + g - 1) / g }); /* a_scale */ o.t((uint32_t)RAD_F8E4M3, { ne0, N0, K0 }); /* w -- the even experts */ o.t(D, { ne0, (N0 + sg.rows - 1) / sg.rows, (K0 + sg.k - 1) / sg.k }); /* w_scale */ - o.t_idx({ M * k }, M * k, -1, 0); /* sorted_tok */ - o.t_idx({ ne + 1 }, M * k + 1, -1, 0); /* expert_offset -- see moe_gemm's note */ + o.t_idx({ M * k }, M * k, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* sorted_tok */ + o.t_idx({ ne + 1 }, M * k + 1, -1, (uint32_t)RAD_OPD_F_IDX_PREFIX); /* expert_offset */ o.t((uint32_t)RAD_F8E4M3, { ne1, N1, K1 }); /* w_odd -- the odd experts */ o.t(D, { ne1, (N1 + sg.rows - 1) / sg.rows, (K1 + sg.k - 1) / sg.k }); /* w_odd_scale */ - o.t(D, { M * k, N }); /* y -- in SORTED order */ + o.t(D, { M * k, N }); /* y -- in sorted order */ return o.finish("moe_gemm_q", operand, out); } -/* The four-class form: class q at [N_q, K_q], defaulting to class 0's, holds the experts e with - * e % 4 == q -- ceil((n - q) / 4) of them -- and `y` follows the last class. */ +/* The four-class form: class q at [N_q, K_q] (default class 0's) holds experts e % 4 == q, + * ceil((n - q) / 4) of them; `y` follows the last class. */ int ref_moe_gemm_q_mod4_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0); const int64_t N0 = gi(p, n_p, "N", 0), K0 = gi(p, n_p, "K", 0); @@ -1457,12 +1464,12 @@ int ref_moe_gemm_q_mod4_shape(const RadParam* p, int n_p, int operand, RadOpdDes o.t((uint32_t)RAD_F8E4M3, { AR, K }); /* a -- E4M3 codes, see `a_order` */ o.t((uint32_t)RAD_F32, { AR, (K + g - 1) / g }); /* a_scale */ cls(0); /* w, w_scale -- class 0 */ - o.t_idx({ M * k }, M * k, -1, 0); /* sorted_tok */ - o.t_idx({ ne + 1 }, M * k + 1, -1, 0); /* expert_offset */ + o.t_idx({ M * k }, M * k, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* sorted_tok */ + o.t_idx({ ne + 1 }, M * k + 1, -1, (uint32_t)RAD_OPD_F_IDX_PREFIX); /* expert_offset */ cls(1); cls(2); cls(3); - o.t(D, { M * k, N }); /* y -- in SORTED order */ + o.t(D, { M * k, N }); /* y -- in sorted order */ return o.finish("moe_gemm_q_mod4", operand, out); } @@ -1474,10 +1481,9 @@ int ref_moe_gather_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou Opd o; o.t(D, { M * k, n }); /* y_expert -- one row per (token, slot) */ o.t(D, { M, k }); /* expert_w */ - /* DISTINCT, and this one is a read-side index that still has to be: gather rebuilds the INVERSE - * permutation of sorted_tok, so a repeated entry makes two sorted rows claim one (token, slot) - * and the last writer wins -- serially here, by whichever workgroup lands last on a device. A - * full permutation of [0, M*top_k) is what moe_scatter produces and is what is described. */ + /* Distinct although read-side: gather rebuilds the inverse permutation, so a repeat would let + * two rows claim one (token, slot) with an implementation-defined winner. A full permutation of + * [0, M*top_k), as moe_scatter produces. */ o.t_idx({ M * k }, M * k, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* sorted_tok */ o.t(D, { M, n }); /* shared -- optional, described anyway */ o.t(D, { M }); /* shared_gate */ @@ -1493,11 +1499,8 @@ int ref_row_topk_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) o.t(D, { M, N }); /* x */ o.t((uint32_t)RAD_I32, { M, R }); /* idx */ o.t((uint32_t)RAD_F32, { M, R }); /* val */ - /* `pairs` is the vocab-parallel plane an all_gather moves and it is described rather than - * skipped, because it is an OUTPUT: nothing has to fill it, and comparing it is what checks the - * packing convention -- an int32 id memcpy'd into the first float slot beside its value, with - * id -1 for a slot the row could not fill. Both plugins require f32 here for exactly that - * reason: the id is carried by BIT PATTERN and a word-typed plane could not hold the value. */ + /* `pairs`, an output, is described to check the packing: an int32 id's bits in the first float + * slot beside its value, id -1 for an unfilled slot. It must be f32 to hold the value. */ o.t((uint32_t)RAD_F32, { M, R, 2 }); /* pairs */ return o.finish("row_topk", operand, out); } @@ -1507,21 +1510,16 @@ int ref_row_topk_merge_shape(const RadParam* p, int n_p, int operand, RadOpdDesc const int64_t W = gi(p, n_p, "world_size", 1); if (M <= 0 || R <= 0 || W <= 0) return RAD_E_UNSUPPORTED; Opd o; - /* THE ONE PACKED PAIR PLANE THIS FILE CAN FILL, and it is worth saying why it works here and - * not on `sample_merge_topk`. The plane is f32, so a normal draw puts a PROPER FLOAT in every - * value lane -- which is the lane the merge orders on -- while the id lane is that same float's - * bit pattern read as an int32: negative floats become negative ids and are dropped as pads, - * positive ones become large but perfectly legal ids that the op only ever compares against - * each other and copies out. Ties are then impossible and the answer is exact. */ + /* A fillable packed pair plane (unlike sample_merge_topk's): as f32 normals the value lanes are + * proper floats, and the id lanes are float bit patterns read as int32, negative ones dropped as + * pads and positive ones legal ids that are only compared and copied. No ties occur. */ o.t((uint32_t)RAD_F32, { M, W * R, 2 }); /* gathered */ o.t((uint32_t)RAD_I32, { M, R }); /* idx */ o.t((uint32_t)RAD_F32, { M, R }); /* val */ return o.finish("row_topk_merge", operand, out); } -/* The same plane at R = 1 a row, and fillable for the same reason the merge's is: the value lane - * draws proper floats and the id lane their bit patterns, so pads are dropped, ids compared and - * copied, and ties do not occur. */ +/* The same pair plane, fillable for the same reason as row_topk_merge's. */ int ref_pair_argmax_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); if (M <= 0 || n <= 0) return RAD_E_UNSUPPORTED; @@ -1534,21 +1532,16 @@ int ref_pair_argmax_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* o -/* logit_rerank DESCRIBES ITSELF, AND THE READER THAT NEEDS IT INVERTS FIRST. +/* The head is described in f32: an E4M3 code times its bf16 block scale needs more mantissa than + * bf16 has, and a reference reading rounded weights reorders candidates whose exact scores are + * close. At a full vocabulary that puts a case over rad-kbench's default --max-bytes, so it is + * checked only where the budget is raised; r4d_selftest checks the kernels over their stored head + * either way. Candidate ids are distinct, as row_topk's are: a repeated id is one entry of the + * kernel's top-R chain but two of a plain sort. * - * The head operand is the lm_head, which libr4d STORES as its own E4M3 row plane (r4d_fp8_lm.h) - * while the declaration says bf16. A SYNTHETIC case built from this description would hand libref - * a bf16 weight and libr4d the identical bytes read as fp8 codes, so the two would compute from - * different numbers -- a disagreement far outside any tolerance with no defect behind it. That is - * why a recording made through the fp8 row is skipped by name, exactly as logits_gemm's is. - * - * Declining the description does not buy that skip and costs the OTHER reader everything. The op - * oracle puts a relaid weight back through the device row's own RadUnrelayoutFn to its canonical - * planes and decodes them -- for this plane that DEQUANTISES -- so the dense weight it hands the - * reference is exactly what the kernel's arithmetic saw, and all it then needs is a logical form - * to write it into. Without one, the draft-head rerank goes unchecked on the engine's own - * operands, reported as "nothing could describe the logical form of 'output.weight'". - * ref_logits_gemm_shape describes the same weight, for the same reason. */ + * The op oracle needs the description too: it un-relays the device weight through + * RadUnrelayoutFn and dequantises it into this logical form, giving the reference exactly what the + * kernel saw. ref_logits_gemm_shape describes the same weight. */ int ref_logit_rerank_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0), R = gi(p, n_p, "R", 0); const int64_t nv = gi(p, n_p, "n_vocab", 0), ne = gi(p, n_p, "n_embd", 0); @@ -1557,39 +1550,20 @@ int ref_logit_rerank_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* const uint32_t D = act_dt(p, n_p); Opd o; o.t(D, { M, ne }); /* x */ - o.t(D, { nv, ne }); /* head */ - /* The candidate ids are GLOBAL, so the draw spans the whole vocabulary this rank can name and - * the ones below its own slice are the pads the op reports as -1. */ - o.t_idx({ M, R }, vo + nv, -1, 0); /* idx_in */ + o.t((uint32_t)RAD_F32, { nv, ne }); /* head */ + /* Candidate ids are global, drawn over [0, vo + nv); those below this rank's slice become pads + * (-1). */ + o.t_idx({ M, R }, vo + nv, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* idx_in */ o.t_idx({ M, R }, vo + nv, -1, 0); /* idx */ o.t((uint32_t)RAD_F32, { M, R }); /* val */ - /* f32 and [M, R, 2] for the same reason row_topk's is: the id rides in the first lane as a - * bit pattern beside its value, so a word-typed plane could not hold the value. */ + /* f32 [M, R, 2], as row_topk's. */ o.t((uint32_t)RAD_F32, { M, R, 2 }); /* pairs */ return o.finish("logit_rerank", operand, out); } -/* ================================================================== gated delta net - * - * The layouts are libref/ref_gdn.cpp's, stated there once: - * - * q, k [T, Hk, head_k] v, o [T, Hv, head_v] - * g, beta [T, Hv] fp32 A [T, Hv, chunk] - * h0, ht [N, Hv, head_v, head_k] fp32 cu [N+1] - * conv w [conv_dim, conv_width] conv_state [n_slots, conv_dim, state_len] - * - * with conv_dim = 2 * Hk * head_k + Hv * head_v. - * - * THE HEAD COUNTS ARE NOT PARAMETERS of any of these ops -- the kernels read them off the operands - * -- so the whole family declines unless the caller has supplied them (see gdn_heads above). A GDN - * case run at an invented head ratio is a case of a model nobody is running. */ - -/* Everything the five gdn descriptions share, resolved once. Returns false to decline. */ /* ================================================================== the fp8 fusions * - * libr4d fuses the fp8 activation quantiser into whichever kernel already had the row in - * registers. The shapes are the unfused pair's, which is the whole point of the fusion: the same - * operands, minus the bf16 tensor between them -- and `out_bf16` puts even that back, because the - * codes are taken over its value and a caller may need to compare them. + * The unfused pair's operands minus the bf16 intermediate, which `out_bf16` restores (the codes are + * taken over its value). */ int ref_rmsnorm_quant_fp8_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); @@ -1617,8 +1591,7 @@ int ref_gated_quant_fp8_shape(const RadParam* p, int n_p, int operand, RadOpdDes return o.finish("gated_quant_fp8", operand, out); } -/* `N` IS THE WEIGHT'S ROWS AND IT IS TWICE THE FUSED WIDTH, which is the one thing a caller coming - * from gemm_nt_q gets wrong here: the quantised output is [M, N/2], not [M, N]. */ +/* `N` is the weight's rows, twice the fused width: the quantised output is [M, N/2]. */ int ref_gemm_nt_q_gated_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0), N = gi(p, n_p, "N", 0), K = gi(p, n_p, "K", 0); const int64_t group = gi(p, n_p, "group", 0); @@ -1640,10 +1613,8 @@ int ref_gemm_nt_q_gated_shape(const RadParam* p, int n_p, int operand, RadOpdDes return o.finish("gemm_nt_q_gated", operand, out); } -/* DFlash2's candidate walk. `cand` holds TOKEN IDS drawn from the vocabulary and `anchor` one per - * sequence, so both are bounded by n_vocab rather than by a row count -- a draw outside it would - * make the codebook gather read past the plane, which is the one thing a description can prevent - * here. The rows of `cand`/`unary`/`hp` are (sequence, step) pairs, M * steps of them. */ +/* DFlash2's candidate walk. `cand` and `anchor` hold token ids, bounded by n_vocab so the codebook + * gather stays in the plane. `cand`/`unary`/`hp` have one row per (sequence, step), M * steps. */ int ref_dflash_select_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0); const int64_t steps = gi(p, n_p, "steps", 0); @@ -1664,7 +1635,20 @@ int ref_dflash_select_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* return o.finish("dflash_select", operand, out); } +/* ================================================================== gated delta net + * + * The layouts are libref/ref_gdn.cpp's: + * + * q, k [T, Hk, head_k] v, o [T, Hv, head_v] + * g, beta [T, Hv] fp32 A [T, Hv, chunk] + * h0, ht [N, Hv, head_v, head_k] fp32 cu [N+1] + * conv w [conv_dim, conv_width] conv_state [n_slots, conv_dim, state_len] + * + * with conv_dim = 2 * Hk * head_k + Hv * head_v. The family declines unless the caller supplies + * the head counts (see gdn_heads). */ + namespace { +/* What the gdn descriptions share, resolved once; gdn_geom returns false to decline. */ struct GdnGeom { int64_t Hk, Hv, hk, hv, chunk, width, conv_dim, S, M; uint32_t D; @@ -1684,15 +1668,47 @@ static bool gdn_geom(const RadParam* p, int n_p, const char* mkey, GdnGeom* g) { return true; } +/* The recurrence's state, state_idx and num_accepted, by `state_form` (docs/OPS.md). + * + * per_candidate: a slot per candidate token, a [S, M] table of distinct slots, and every token + * accepted. + * + * anchor: the kernels read six columns a sequence (the anchor's three, then the factor block's + * three), so the table is at least six wide, every entry a distinct slot. The state is drawn + * whole, so the factor block holds random factors and a random stamp; every implementation reads + * a block the same way (each 32-row group of V from its own copy of k, g and beta, the anchor + * column from the rounded stamp), so that is a defined input. One accepted token is replayed: with + * random k the replay scales the state by about |k|^2, which one token keeps finite. A step + * longer than the factor block holds is refused by the op, so it is not described. */ +bool gdn_state(const RadParam* p, int n_p, const GdnGeom& g, Opd& o) { + const char* form = gs(p, n_p, "state_form"); + if (form && std::strcmp(form, "anchor") == 0) { + const int64_t groups = (g.hv + 31) / 32, fstr = groups * g.hk + g.hv + 2 * groups; + const int64_t tmax = std::min(16, (g.hv * g.hk - 1) / fstr); + if (tmax < 1 || g.M > tmax) return false; + const int64_t cols = std::max(g.M, 6), slots = g.S * cols; + o.t((uint32_t)RAD_F32, { slots, g.Hv, g.hv, g.hk }); /* state, INOUT */ + o.t_idx({ g.S, cols }, slots, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* state_idx */ + o.t_idx({ g.S }, 0, 1, 0); /* num_accepted */ + return true; + } + if (form && std::strcmp(form, "per_candidate") != 0) return false; + const int64_t T = g.S * g.M; + /* One state slot per candidate token (ref_ops.h's rollback contract). */ + o.t((uint32_t)RAD_F32, { T, g.Hv, g.hv, g.hk }); /* state, INOUT */ + o.t_idx({ g.S, g.M }, T, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* state_idx */ + o.t_idx({ g.S }, 0, 1, 0); /* num_accepted: none rejected */ + return true; +} + } /* namespace */ int ref_gdn_conv_prep_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { GdnGeom g; if (!gdn_geom(p, n_p, "M", &g)) return RAD_E_UNSUPPORTED; Opd o; - /* T tokens over S sequences, one conv-state slot each. `state_len` is the manager's - * conv_width - 1 + n_spec; with no speculation that is conv_width - 1, and the kernel reads its - * window at the slot the last committed token left. */ + /* T tokens over S sequences, one conv-state slot each, `state_len` conv_width - 1 (the + * manager's conv_width - 1 + n_spec with no speculation). */ o.t(g.D, { g.M, g.conv_dim }); /* x -- the fused projection row */ o.t(g.D, { g.conv_dim, g.width }); /* w */ o.skip(); /* b -- this checkpoint has no conv bias */ @@ -1700,21 +1716,17 @@ int ref_gdn_conv_prep_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* o.t((uint32_t)RAD_F32, { g.Hv }); /* dt_bias */ o.t(g.D, { g.S, g.conv_dim, g.width - 1 }); /* conv_state, INOUT */ o.t_idx({ g.S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu */ - /* `a` and `b_gate` PRESENT: the layer's separate gate and beta projections. Absent they would - * be the last 2*Hv columns of the fused `x` row, which would make `x` wider and hide the - * separate-projection path that every current caller takes. */ + /* `a` and `b_gate` passed: the separate-projection path every current caller takes. */ o.t(g.D, { g.M, g.Hv }); /* a */ o.t(g.D, { g.M, g.Hv }); /* b_gate */ o.t_idx({ g.S }, g.S, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* cache_idx, one a sequence */ - /* A COLD PREFILL, SAID rather than left absent: ref reads a null `has_init` as WARM and libr4d - * as COLD, so the default is the one thing the two do not share. */ + /* A cold prefill, stated explicitly: ref reads a null `has_init` as warm, libr4d as cold. */ o.t_idx({ g.S }, 0, 0, 0); /* has_init */ o.t(g.D, { g.M, g.Hk, g.hk }); /* q */ o.t_fill(g.D, { g.M, g.Hk, g.hk }, (uint32_t)RAD_FILL_UNIT_ROW, 0); /* k */ o.t(g.D, { g.M, g.Hv, g.hv }); /* v */ - /* g and beta are OUTPUTS here and their domains are stated anyway: they are the same tensors - * gdn_kkt_solve and gdn_chunk_scan take as INPUTS, and the domain is the op's contract for what - * it produces rather than a property of who is filling the buffer. */ + /* g and beta are outputs, but their domains are stated: they are the inputs of gdn_kkt_solve + * and gdn_chunk_scan. */ o.t_fill((uint32_t)RAD_F32, { g.M, g.Hv }, (uint32_t)RAD_FILL_GATE_CUMSUM, g.chunk); /* g */ o.t_fill((uint32_t)RAD_F32, { g.M, g.Hv }, (uint32_t)RAD_FILL_SIGMOID, 0); /* beta */ return o.finish("gdn_conv_prep", operand, out); @@ -1723,9 +1735,8 @@ int ref_gdn_conv_prep_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* int ref_gdn_conv_update_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { GdnGeom g; if (!gdn_geom(p, n_p, "q_len", &g)) return RAD_E_UNSUPPORTED; - /* The decode pair. `M` is q_len here, one row per candidate token, and the window is - * conv_width - 2 + q_len deep so a rejection is a change of READ OFFSET rather than a recompute - * (ref_ops.h's rollback contract). */ + /* Decode: `M` is q_len, one row per candidate token, and the window is conv_width - 2 + q_len + * deep (ref_ops.h's rollback contract). */ const int64_t sl = g.width - 2 + g.M; Opd o; o.t(g.D, { g.S * g.M, g.conv_dim }); /* x */ @@ -1733,9 +1744,8 @@ int ref_gdn_conv_update_shape(const RadParam* p, int n_p, int operand, RadOpdDes o.skip(); /* b */ o.t(g.D, { g.S, g.conv_dim, sl }); /* conv_state, INOUT */ o.t_idx({ g.S, g.M }, g.S, -1, 0); /* state_idx */ - /* num_accepted is 1-BASED and all ones is the non-speculative decode: "none of the drafts - * survived, only the token that was already committed". A draw here would move the read offset - * to a slot this step's window does not cover. */ + /* num_accepted is 1-based; all ones is the non-speculative decode. A draw could move the read + * offset outside the window. */ o.t_idx({ g.S }, 0, 1, 0); /* num_accepted */ o.t_idx({ g.S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu */ o.t(g.D, { g.S * g.M, g.Hk, g.hk }); /* q */ @@ -1750,8 +1760,7 @@ int ref_gdn_kkt_solve_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* Opd o; o.t_fill(g.D, { g.M, g.Hk, g.hk }, (uint32_t)RAD_FILL_UNIT_ROW, 0); /* k */ o.t_fill((uint32_t)RAD_F32, { g.M, g.Hv }, (uint32_t)RAD_FILL_SIGMOID, 0); /* beta */ - /* NON-INCREASING AND NEVER POSITIVE, reset at every chunk boundary. The solve forms - * e^{g_i - g_j} with j <= i and that is <= 1 only because g is monotone. */ + /* Non-increasing, never positive, reset at each chunk boundary (see the file header). */ o.t_fill((uint32_t)RAD_F32, { g.M, g.Hv }, (uint32_t)RAD_FILL_GATE_CUMSUM, g.chunk); /* g */ o.t_idx({ g.S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu */ o.t_fill(g.D, { g.M, g.Hv, g.chunk }, (uint32_t)RAD_FILL_TRI_LOWER, g.chunk); /* A */ @@ -1765,10 +1774,7 @@ int ref_gdn_chunk_scan_shape(const RadParam* p, int n_p, int operand, RadOpdDesc o.t(g.D, { g.M, g.Hk, g.hk }); /* q */ o.t_fill(g.D, { g.M, g.Hk, g.hk }, (uint32_t)RAD_FILL_UNIT_ROW, 0); /* k */ o.t(g.D, { g.M, g.Hv, g.hv }); /* v */ - /* ZERO ABOVE THE DIAGONAL WITHIN A CHUNK. A is the chunk's triangular inverse and the scan - * multiplies by it; a dense random A puts two implementations on opposite sides of a convention - * -- whether the strictly-upper part is read at all -- that they never disagree about on a real - * one, because the same library's kkt_solve produced it. */ + /* Zero above the diagonal within a chunk, as kkt_solve produces (see the file header). */ o.t_fill(g.D, { g.M, g.Hv, g.chunk }, (uint32_t)RAD_FILL_TRI_LOWER, g.chunk); /* A */ o.t_fill((uint32_t)RAD_F32, { g.M, g.Hv }, (uint32_t)RAD_FILL_GATE_CUMSUM, g.chunk); /* g */ o.t_fill((uint32_t)RAD_F32, { g.M, g.Hv }, (uint32_t)RAD_FILL_SIGMOID, 0); /* beta */ @@ -1788,28 +1794,19 @@ int ref_gdn_recurrent_update_shape(const RadParam* p, int n_p, int operand, RadO o.t(g.D, { T, g.Hk, g.hk }); /* q */ o.t(g.D, { T, g.Hk, g.hk }); /* k */ o.t(g.D, { T, g.Hv, g.hv }); /* v */ - /* `a` and `b` are the RAW gate and beta projections here, not the cumsum and the sigmoid: this - * op applies softplus and sigmoid itself (o = -exp(A_log) . softplus(a + dt_bias)), so normals - * are the right domain and the monotone-cumsum rule belongs to the prefill path's `g`. */ + /* `a` and `b` are the raw gate and beta projections (the op applies softplus and sigmoid + * itself), so normals are the right domain. */ o.t(g.D, { T, g.Hv }); /* a */ o.t(g.D, { T, g.Hv }); /* b */ o.t((uint32_t)RAD_F32, { g.Hv }); /* A_log */ o.t((uint32_t)RAD_F32, { g.Hv }); /* dt_bias */ - /* One state slot per CANDIDATE TOKEN: the initial state is read from state_idx[s, - * num_accepted-1] and every candidate writes its own slot, because which of them survives - * verification is not known until after this layer has run. */ - o.t((uint32_t)RAD_F32, { T, g.Hv, g.hv, g.hk }); /* state, INOUT */ - o.t_idx({ g.S, g.M }, T, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* state_idx */ - o.t_idx({ g.S }, 0, 1, 0); /* num_accepted -- none rejected */ + if (!gdn_state(p, n_p, g, o)) return RAD_E_UNSUPPORTED; /* state, state_idx, num_accepted */ o.t_idx({ g.S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu */ o.t(g.D, { T, g.Hv, g.hv }); /* z -- the output gate */ o.t((uint32_t)RAD_F32, { g.hv }); /* norm_w */ o.t(g.D, { T, g.Hv, g.hv }); /* o */ - /* The out-projection's fp8 quantiser, folded into the epilogue. It is ALL-OR-NOTHING and it is - * skipped: with it present the op quantises the bf16 `o` it just wrote, which is a second - * contract on top of the recurrence, and describing it here would mean every gdn decode case - * also carried an fp8 comparison it did not ask for. The unfused pair (this op then - * quant_act_fp8) covers the same arithmetic and is separately describable. */ + /* The folded fp8 out-projection quantiser (all-or-nothing) is skipped; the unfused pair (this + * op, then quant_act_fp8) covers the same arithmetic. */ o.skip(); /* o_q */ o.skip(); /* o_scale */ return o.finish("gdn_recurrent_update", operand, out); @@ -1819,8 +1816,8 @@ int ref_gdn_conv_recurrent_update_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { GdnGeom g; if (!gdn_geom(p, n_p, "q_len", &g)) return RAD_E_UNSUPPORTED; - /* The decode pair's two descriptions spliced: gdn_conv_update's inputs, then - * gdn_recurrent_update's minus q, k and v. `conv_idx` is one slot a sequence. */ + /* gdn_conv_update's inputs, then gdn_recurrent_update's minus q, k and v. `conv_idx` is one + * slot per sequence. */ const int64_t T = g.S * g.M, sl = g.width - 2 + g.M; Opd o; o.t(g.D, { T, g.conv_dim }); /* x */ @@ -1832,9 +1829,7 @@ int ref_gdn_conv_recurrent_update_shape(const RadParam* p, int n_p, int operand, o.t(g.D, { T, g.Hv }); /* b */ o.t((uint32_t)RAD_F32, { g.Hv }); /* A_log */ o.t((uint32_t)RAD_F32, { g.Hv }); /* dt_bias */ - o.t((uint32_t)RAD_F32, { T, g.Hv, g.hv, g.hk }); /* state, INOUT */ - o.t_idx({ g.S, g.M }, T, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* state_idx */ - o.t_idx({ g.S }, 0, 1, 0); /* num_accepted -- none rejected */ + if (!gdn_state(p, n_p, g, o)) return RAD_E_UNSUPPORTED; /* state, state_idx, num_accepted */ o.t_idx({ g.S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu */ o.t(g.D, { T, g.Hv, g.hv }); /* z */ o.t((uint32_t)RAD_F32, { g.hv }); /* norm_w */ @@ -1845,8 +1840,8 @@ int ref_gdn_conv_recurrent_update_shape(const RadParam* p, int n_p, int operand, } int ref_gdn_gated_rmsnorm_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { - /* One row per (token, head): `M` is already tokens x heads and `channels` is head_v. No head - * count is needed, which is why this is the one member of the family that never declines. */ + /* One row per (token, head): `M` is tokens x heads and `channels` is head_v, so no head count + * is needed. */ const int64_t M = gi(p, n_p, "M", 0); const int64_t ch = gi(p, n_p, "channels", 0); if (M <= 0 || ch <= 0) return RAD_E_UNSUPPORTED; @@ -1867,10 +1862,8 @@ int ref_all_reduce_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou const uint32_t D = act_dt(p, n_p); Opd o; o.t(D, { numel }); /* x, INOUT */ - /* `y` is the optional SECOND DESTINATION. Absent means in place, which is the form docs/OPS.md - * draws and the only one a one-shot kernel needs -- but libr4d's two-shot rows are NOT safe in - * place (a rank gathers into the output while its own input is still being read for the - * scatter) and cannot be described at all without it, so it is passed. */ + /* `y`, the optional separate destination, is passed: libr4d's two-shot rows are not safe in + * place and need it (see ref_all_reduce). */ o.t(D, { numel }); /* y */ return o.finish("all_reduce", operand, out); } @@ -1896,26 +1889,18 @@ int ref_embed_lookup_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* if (M <= 0 || ne <= 0 || nv <= 0 || vo < 0) return RAD_E_UNSUPPORTED; const uint32_t D = act_dt(p, n_p); Opd o; - /* THE RANGE IS STATED even though the table follows: `tokens` is operand ZERO, so there is no - * previous operand to take a leading extent from and a caller falling back to something else - * would draw ids the launch refuses (an id at or above n_vocab fails the launch by name). - * - * `vocab_offset + nv` rather than `nv`: ids are GLOBAL, so under a shard the bench must draw - * across the slice boundary or it never exercises the zero-row arm that makes the following - * all_reduce correct. At offset 0 the bound is `nv`. */ + /* The range is explicit since `tokens` is operand 0. Ids are global, so the bound is + * `vocab_offset + nv`: under a shard the draw crosses the slice boundary and exercises the + * zero-row path. */ o.t_idx({ M }, vo + nv, -1, 0); /* tokens */ o.t(D, { nv, ne }); /* wte */ o.t(D, { M, ne }); /* x */ return o.finish("embed_lookup", operand, out); } -/* The quantised gather. The TABLE is E4M3 and the OUTPUT is the activation dtype, which is the - * whole reason `dtype` on this op names a combination ("w8a16") rather than one width -- and it is - * why the two operands are described with different dtypes here instead of one shared D. - * - * `scale` is a single element, and a harness drawing it from a normal is exactly right: the op's - * arithmetic is a multiply and nothing about it cares what the value is. What the value IS lives in - * the checkpoint (Qwen3.8-Flash-Next-FP8's is 1.9932e-4) and is not this hook's business. */ +/* The quantised gather: the table is E4M3 and the output the activation dtype (`dtype` names the + * combination, e.g. "w8a16"). `scale` is one element; a normal draw is fine, since the op only + * multiplies by it. */ int ref_embed_lookup_q_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0); const int64_t ne = gi(p, n_p, "n_embd", 0); @@ -1941,34 +1926,27 @@ int ref_logits_gemm_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* o Opd o; o.t(D, { M, ne }); /* x */ o.t(D, { nv, ne }); /* lm_head */ - /* f32 logits, always: the sampler chain reads them and every stage in it is f32. */ + /* f32 logits, as every sampler stage reads them. */ o.t((uint32_t)RAD_F32, { M, nv }); /* logits */ return o.finish("logits_gemm", operand, out); } /* ================================================================== sampling * - * Every scalar a request sets is PER ROW and arrives in the `params` operand rather than as a - * parameter -- see sample_params_words() above for what that plane is, how it is filled, and the - * three stages a filled-from-normals row cannot reach. The rest of the sampler's operands are - * plain: + * Per-row scalars arrive in the `params` operand (see sample_params_words() for its draw). The + * other operands: * * logits f32 [M, n_vocab] cand_idx i32 [M, n_cand] token i32 [M] * history i32 [M, max_hist] cand_val f32 [M, n_cand] bitmask i32 [M, ceil(nv/32)] + * breakers u8 [M, max_hist] * - * and the dtypes are not a choice: libr4d's shim requires exactly these - * (libr4d/r4d_sample_stages_f32.hip checks each one by name) and ref's requires the same of the - * two it can tell apart. Every word-typed operand here is i32 and never u32, because - * opshapes.cpp's rad_widen has no RAD_U32 case -- a u32 operand is compared as zeroes, and a - * vacuous pass is worse than a skip. */ + * libr4d's shim requires exactly these dtypes (libr4d/r4d_sample_stages_f32.hip). Word-typed + * operands are i32, never u32 (see sample_params_words()). */ -/* The history window. Not a parameter of anything -- it is the packed history plane's own extent, - * which the deployment sizes -- so it is chosen here. Sixty-four tokens is a plausible penalty - * window and any width walks the same loops. */ +/* The history window width: the deployment sizes the history plane, so this picks a plausible 64. */ enum { REF_SAMPLE_HIST = 64 }; -/* The candidate width for `sample_topk`, whose parameters carry `n_vocab` and not `n_cand`: the - * buffer's extent IS the deployment bound and the op reads it off the operand. Narrower than the - * vocabulary and wide enough that the narrowing stages downstream have something to narrow. */ +/* The candidate width for `sample_topk`, which reads it off the operand (its parameters carry only + * `n_vocab`): narrower than the vocabulary, wide enough for the narrowing stages. */ enum { REF_SAMPLE_CAND = 64 }; static int sample_vocab(const RadParam* p, int n_p, int64_t* M, int64_t* nv) { @@ -1977,21 +1955,31 @@ static int sample_vocab(const RadParam* p, int n_p, int64_t* M, int64_t* nv) { return (*M > 0 && *nv > 0) ? RAD_OK : RAD_E_UNSUPPORTED; } -/* sample_penalties and sample_dry share their first three operands and their description: - * logits, params, history. DRY's fourth, the optional breaker plane, is not passed: absent means - * no token is exempt, and the params rows drawn here reach the row's early out before a word of - * either plane is read. */ +/* The `params` plane, drawn as requests (see sample_params_words()). The law places each row's + * history window inside a plane `hist` wide and its `mask_row` among `mask_rows` bitmask rows; 0 + * for an op without that plane. */ +static void sample_params(Opd& o, int64_t M, int64_t hist, int64_t mask_rows) { + RadOpdDesc* d = o.push(); + Opd::shape(d, (uint32_t)RAD_F32, { M, sample_params_words() }); + d->fill = (uint32_t)RAD_FILL_SAMPLE_PARAMS; + d->fill_chunk = hist; + d->idx_max = mask_rows; +} + +/* sample_penalties and sample_dry share logits, params and history. The history is real token ids + * in [0, n_vocab) that repeat as text does (RAD_OPD_F_IDX_HISTORY). DRY's optional breaker plane is + * passed with about half its positions marked, so the exemption runs as well as the penalty. */ static int penalty_shape(const RadParam* p, int n_p, int operand, const char* op, bool breakers, RadOpdDesc* out) { int64_t M = 0, nv = 0; if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED; Opd o; o.t((uint32_t)RAD_F32, { M, nv }); /* logits, INOUT */ - o.t((uint32_t)RAD_F32, { M, sample_params_words() }); /* params */ - /* Real token ids: the penalties look each one up in the row's logits and skip anything outside - * [0, n_vocab), so a draw from the wrong range is a draw that does nothing. */ - o.t_idx({ M, (int64_t)REF_SAMPLE_HIST }, nv, -1, 0); /* history */ - if (breakers) o.skip(); /* breakers, optional */ + sample_params(o, M, REF_SAMPLE_HIST, 0); /* params */ + o.t_idx({ M, (int64_t)REF_SAMPLE_HIST }, nv, -1, + (uint32_t)RAD_OPD_F_IDX_HISTORY); /* history */ + if (breakers) /* breakers, optional */ + o.t_idx_dt((uint32_t)RAD_U8, { M, (int64_t)REF_SAMPLE_HIST }, 2, -1, 0); return o.finish(op, operand, out); } @@ -2007,7 +1995,7 @@ int ref_sample_temp_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* o if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED; Opd o; o.t((uint32_t)RAD_F32, { M, nv }); /* logits, INOUT */ - o.t((uint32_t)RAD_F32, { M, sample_params_words() }); /* params */ + sample_params(o, M, 0, 0); /* params */ return o.finish("sample_temp", operand, out); } @@ -2016,10 +2004,9 @@ int ref_sample_mask_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* o if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED; Opd o; o.t((uint32_t)RAD_F32, { M, nv }); /* logits, INOUT */ - o.t((uint32_t)RAD_F32, { M, sample_params_words() }); /* params */ - /* A SET BIT MEANS ALLOWED, word w bit b covering token 32w + b. The plane is shorter than M in - * a real step -- a constrained sequence and an unconstrained one share it and `mask_row` is -1 - * for the second -- and one row per sequence is the widest it is ever built. */ + sample_params(o, M, 0, M); /* params */ + /* A set bit means allowed, word w bit b covering token 32w + b. One row per sequence is the + * widest the plane gets (unconstrained rows share it with `mask_row` -1). */ o.t((uint32_t)RAD_I32, { M, (nv + 31) / 32 }); /* bitmask */ return o.finish("sample_mask", operand, out); } @@ -2029,7 +2016,7 @@ int ref_sample_argmax_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED; Opd o; o.t((uint32_t)RAD_F32, { M, nv }); /* logits */ - o.t((uint32_t)RAD_F32, { M, sample_params_words() }); /* params -- unread by argmax */ + sample_params(o, M, 0, 0); /* params -- unread by argmax */ o.t((uint32_t)RAD_I32, { M }); /* token */ return o.finish("sample_argmax", operand, out); } @@ -2041,7 +2028,7 @@ int ref_sample_logprobs_shape(const RadParam* p, int n_p, int operand, RadOpdDes if (k <= 0) return RAD_E_UNSUPPORTED; Opd o; o.t((uint32_t)RAD_F32, { M, nv }); /* logits */ - o.t((uint32_t)RAD_F32, { M, sample_params_words() }); /* params */ + sample_params(o, M, 0, 0); /* params */ o.t((uint32_t)RAD_F32, { M, 2 + 2 * k }); /* stats */ return o.finish("sample_logprobs", operand, out); } @@ -2052,40 +2039,32 @@ int ref_sample_topk_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* o const int64_t nc = nv < (int64_t)REF_SAMPLE_CAND ? nv : (int64_t)REF_SAMPLE_CAND; Opd o; o.t((uint32_t)RAD_F32, { M, nv }); /* logits */ - o.t((uint32_t)RAD_F32, { M, sample_params_words() }); /* params */ + sample_params(o, M, 0, 0); /* params */ o.t((uint32_t)RAD_I32, { M, nc }); /* cand_idx */ - o.t((uint32_t)RAD_F32, { M, nc }); /* cand_val -- LOGITS, not probs */ - /* The vocab-parallel pair plane, and it is described because it is an OUTPUT: nothing fills it, - * comparing it checks the packing -- (u32 global id, f32 logit) with 0xffffffff for a hole -- - * and `vocab_off` is zero on a single-rank graph, which makes the ids the local ones and the - * comparison exactly as strict. */ + o.t((uint32_t)RAD_F32, { M, nc }); /* cand_val -- logits, not probs */ + /* The vocab-parallel pair plane, an output, described to check the packing: (u32 global id, + * f32 logit), 0xffffffff for a hole; `vocab_off` is 0 here. */ o.t((uint32_t)RAD_I32, { M, 2 * nc }); /* pairs */ return o.finish("sample_topk", operand, out); } -/* The four narrowing stages share a schema -- cand_idx, cand_val, params, all in place -- and - * therefore one description. +/* The four narrowing stages share a schema (cand_idx, cand_val, params, in place) and one + * description. * - * THE CANDIDATE SET IS DRAWN, NOT SORTED, and that is worth naming. The stages take the set as - * sample_topk leaves it: descending, with index -1 / -infinity for a hole. The ABI has no - * "descending" fill domain, so what these get is a random (id, value) plane. min-p, locally-typical - * and XTC are per-candidate predicates and do not care. Top-p is a PREFIX rule -- keep the shortest - * run whose cumulative probability reaches p, walking the set in candidate order -- and walking a - * random order is still the same definition applied to the same bytes, so two implementations that - * both walk it agree. One that sorted internally would not, and that would be a real disagreement - * with the schema rather than an artefact of this description. */ + * The candidate set is drawn, not sorted: the ABI has no descending fill domain. min-p, typical and + * XTC are per-candidate predicates. Top-p is a prefix rule in candidate order, which applies equally + * to a random order; an implementation that sorted internally would genuinely disagree with the + * schema. */ static int narrow_shape(const RadParam* p, int n_p, int operand, const char* op, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0); const int64_t nc = gi(p, n_p, "n_cand", 0); if (M <= 0 || nc <= 0) return RAD_E_UNSUPPORTED; Opd o; - /* Every drawn index is >= 0, so every candidate arrives LIVE: a stage that dropped nothing - * because the set was already empty is the vacuous case. The range is the candidate width - * rather than the vocabulary, because the ids are only ever copied and compared here and a - * wider draw would say nothing more. */ + /* Drawn indices are >= 0, so every candidate is live. The range is the candidate width; ids + * are only copied and compared here. */ o.t_idx({ M, nc }, nc, -1, 0); /* cand_idx, INOUT */ o.t((uint32_t)RAD_F32, { M, nc }); /* cand_val, INOUT */ - o.t((uint32_t)RAD_F32, { M, sample_params_words() }); /* params */ + sample_params(o, M, 0, 0); /* params */ return o.finish(op, operand, out); } @@ -2109,41 +2088,26 @@ int ref_sample_pick_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* o Opd o; o.t_idx({ M, nc }, nc, -1, 0); /* cand_idx */ o.t((uint32_t)RAD_F32, { M, nc }); /* cand_val */ - o.t((uint32_t)RAD_F32, { M, sample_params_words() }); /* params -- seed and pos */ + sample_params(o, M, 0, 0); /* params -- seed and pos */ o.t((uint32_t)RAD_I32, { M }); /* token */ return o.finish("sample_pick", operand, out); } -/* sample_merge_topk is DECLINED, and it is the one op in this vocabulary whose extents are known - * and whose description would still be a lie. +/* sample_merge_topk is declined although its extents are known. `gathered` packs (u32 global id, + * f32 logit) pairs in a word-typed buffer, so logits are read by bit pattern and no fill domain + * yields sensible floats: an integer draw makes every logit a denormal, which a flushing device + * and a non-flushing host order differently (the failure r4d_selftest's two-rank all-gather + * checks). Also, `world_size` is not a parameter, so the gathered width would be invented. * - * `gathered` is [M, world_size * n_cand] pairs of (u32 global token id, f32 logit) packed into one - * WORD-TYPED buffer -- both plugins require i32 or u32 for it, because the two halves have - * different types and the buffer's dtype can only be one of them. The value lane is therefore read - * by BIT PATTERN, and there is no fill domain in this ABI that puts a sensible float there: an - * integer draw over the buffer makes every logit a DENORMAL, and a device that flushes denormals - * and a host reference that does not then order the candidates differently. That is not a - * hypothetical -- it is the failure r4d_selftest's two-rank all-gather exists to catch ("a token id - * is a small integer, and its bit pattern read as f32 is a denormal ... the model then samples - * token 0 forever while every logit still looks right"). A comparison built on it would be - * measuring the float mode. - * - * `world_size` is not in this op's parameter list either, so the gathered width would have to be - * invented on top of that. Two reasons, either sufficient. - * - * row_topk_merge is the same shape of operand and is NOT declined, because its plane is f32: there - * the value lane is a real float and the id lane is the bit pattern, which is the way round that - * works. See ref_row_topk_merge_shape. */ + * row_topk_merge is not declined: its plane is f32, so the value lane is a real float. */ int ref_sample_merge_topk_shape(const RadParam*, int, int, RadOpdDesc*) { return RAD_E_UNSUPPORTED; } /* ================================================================== image generation (ref_gen.cpp) * - * The row-wise ones are described; the rest DECLINE. A lane op's indices are lanes of a state the - * case would have to size to match them, a flow step's entries pair across the batch, and an image - * op reads its height and width off its operands -- each a case a cold draw would make up, and a - * description that makes up a case tests the bounds handling and calls it correctness. */ + * Lane ops are described over REF_LANES lanes and image ops at a chosen picture shape (below); + * gather_rows2 declines. */ int ref_ln_mod_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); const uint32_t D = act_dt(p, n_p); @@ -2190,11 +2154,9 @@ int ref_gather_rows2_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* (void)p; (void)n_p; (void)operand; (void)out; return RAD_E_UNSUPPORTED; /* a signed index: half its draw would have to be negative */ } -/* ---- the image generator's per-lane ops. A LANE is one image's slot of a state buffer, `stride` - * rows apart; an entry of the step reads or writes its own lane. Four lanes is the smallest count - * that leaves lanes no entry touches, so a write into the wrong lane shows as a difference in - * one that should have kept its fill. The entries are as many as the rows need at `stride` a - * piece (one, unless M is longer than a lane), split by cu_seqlens. */ +/* ---- the per-lane ops. A lane is one image's slot of a state buffer, `stride` rows apart; each + * entry reads or writes its own lane. Four lanes leaves some untouched, so a write into the wrong + * lane shows up. Entries are as many as M needs at `stride` rows each, split by cu_seqlens. */ enum { REF_LANES = 4 }; static int64_t lane_entries(const RadParam* p, int n_p, int64_t M, int64_t stride) { const int64_t s = n_seq_of(p, n_p), need = (M + stride - 1) / stride; @@ -2233,7 +2195,7 @@ int ref_randn_lanes_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* o const int64_t S = lane_entries(p, n_p, M, st); if (M > S * st) return RAD_E_UNSUPPORTED; Opd o; - /* Flags drawn over all three bits, so some entries are first steps and some are left. */ + /* Flags drawn over all three bits, so only some entries are first steps. */ o.t_idx({ S }, 8, -1, 0); /* flags */ o.t_idx({ 2 * S }, (int64_t)1 << 30, -1, 0); /* seed: two words an entry */ /* Distinct: two first steps in one lane would be a race between their seeds. */ @@ -2246,9 +2208,8 @@ int ref_randn_lanes_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* o int ref_flow_euler_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), st = gi(p, n_p, "stride", 0); if (M <= 0 || n <= 0 || st <= 0) return RAD_E_UNSUPPORTED; - /* TWO ENTRIES OF EQUAL LENGTH where M allows, so a pair drawn from {0, 1} is always legal: - * an entry guided against the other, or against itself. -1 and -2 are not drawable, so the - * unguided and the parked entry are left to the engine's own tests. */ + /* Two equal-length entries where M allows, so a pair drawn from {0, 1} is always legal. -1 + * (unguided) and -2 (parked) are not drawable and are left to the engine's tests. */ const int64_t S = (M % 2 == 0 && M / 2 <= st) ? 2 : 1; if (M > S * st) return RAD_E_UNSUPPORTED; const uint32_t F = (uint32_t)RAD_F32, B = (uint32_t)RAD_BF16; @@ -2269,10 +2230,9 @@ int ref_flow_euler_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou return o.finish("flow_euler", operand, out); } -/* ---- an image decoder's convolutions and shortcuts. Both sizes are read off the operands, and - * M counts the OUTPUT's pixels, so the picture's shape is this description's to choose: eight - * columns where M allows -- a row then has both edges and an interior -- and the input whatever - * makes that output. A shape no input produces is declined rather than bent. */ +/* ---- an image decoder's convolutions and shortcuts. Sizes are read off the operands and M counts + * output pixels, so this picks eight columns where M allows (a row with both edges and an interior) + * and the input that produces that output; otherwise it declines. */ static int64_t cols_for(int64_t M, int64_t mult) { for (int64_t w = 8; w >= 1; w /= 2) if (w % mult == 0 && M % w == 0 && (M / w) % mult == 0) return w; @@ -2329,9 +2289,9 @@ int ref_s2d_avg_add_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* o return o.finish("s2d_avg_add", operand, out); } -/* ---- attention over a paged prefix and the step's own rows. The prefix is `ctx` deep when the - * harness sweeps depth and 37 otherwise: two whole blocks and a part of a third, so both the - * block-table walk and the partial block's bound run. */ +/* ---- attention over a paged prefix and the step's own rows. The prefix is `ctx` deep, else 37 + * (two whole blocks and part of a third at block size 16), exercising the block walk and the + * partial block. */ int ref_attn_prefix_self_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "q_len", 0); const int64_t hd = gi(p, n_p, "head_dim", 0); diff --git a/scripts/README.md b/scripts/README.md index 3f5acb6d..ecf58b56 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -1,54 +1,54 @@ # scripts/ -Shell harnesses that drive a **running** engine: bring a model up, measure it, and assert on what -comes back over the wire. They are versioned with the engine because a measurement is only -reproducible if the thing that took it is, and because what each one encodes is an argument — why -a window is sampled the way it is, which counter is the honest one — that is expensive to -reconstruct from the number alone. +Harnesses that drive a running engine: bring a model up, measure it, and assert on what comes back +over the wire. They are versioned with the engine so measurements stay reproducible, and each +header records its method (why a window is sampled the way it is, which counter to trust), which is +hard to reconstruct from the number alone. -The scripts that start a server or a conversion expect the build at -`$HOME/workspace/radiance/build` and the containers under `$HOME/models/rad/`; every default is -an environment override (`M=` for the container, `P=` for the port, and so on — each script's -header lists its own). The ones that only attach to a live server need nothing but `curl` and -`jq`. Scripts resolve each other by `$(dirname "$0")`. +Scripts that start a server or a conversion run the build at `$BUILD`, by default `build/` in the +checkout the script is in, and default to containers under `$HOME/models/rad/` and checkpoints under +`$HOME/models//`. A script that starts a server first stops any `radiance` already +running (`oracle.sh` only the one on its own port) and logs to `$HOME/